This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 744d33b4bf feat(bindings/nodejs): generate DeleteOptions from core 
(#9363)
744d33b4bf is described below

commit 744d33b4bfa1085c740c32cbdcf90e144826b8cc
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 15:45:46 2026 +0530

    feat(bindings/nodejs): generate DeleteOptions from core (#9363)
    
    * feat(bindings/nodejs): generate DeleteOptions from core
    
    Render the napi DeleteOptions object, its JSDoc, and its conversion to
    core from the core DeleteOptions, reusing the options generator and
    template. The three JS members keep their names, types, and order:
    version and ifMatch pass their strings through, and an omitted
    recursive is false. if_none_match, if_version_match,
    if_version_not_match, and if_not_changed stay unexposed.
    
    Qualify the core DeleteOptions sentence that deleting a missing file is
    a successful no-op. OpenDAL validates options and capabilities before
    it dispatches a delete, so on memory and fs, deleting a missing path
    with version fails with Unsupported naming version.
    
    Part of #9322.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * docs(bindings/nodejs): describe Unsupported errors by message in every 
options struct
    
    Apply the #9362 rewrite of `crate::ErrorKind::Unsupported` to the struct
    and field docs of every generated Node.js options struct, not only the
    ListOptions struct doc. StatOptions and DeleteOptions docs change;
    ListOptions output is unchanged.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    ---------
    
    Signed-off-by: Chitral Verma <[email protected]>
---
 bindings/nodejs/generated.d.ts                     |  64 ++++-
 bindings/nodejs/src/options.rs                     |  27 +-
 bindings/nodejs/src/options/delete.rs              |  85 ++++++
 bindings/nodejs/src/options/stat.rs                |  10 +-
 .../nodejs/tests/delete-options-surface.test.mjs   | 124 +++++++++
 core/core/src/types/options.rs                     |   4 +-
 dev/src/generate/nodejs.rs                         | 289 ++++++++++++++++-----
 7 files changed, 499 insertions(+), 104 deletions(-)

diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts
index ecc19ad4e1..7943c4baca 100644
--- a/bindings/nodejs/generated.d.ts
+++ b/bindings/nodejs/generated.d.ts
@@ -1203,13 +1203,59 @@ export declare class Writer {
   abort(): Promise<void>
 }
 
+/**
+ * Options for delete operations.
+ *
+ * Each condition checks the file currently stored at the delete path, and
+ * every condition must hold for the delete to proceed:
+ *
+ * - A false condition fails the delete with
+ * `crate::ErrorKind::ConditionNotMatch`.
+ * - A condition the service does not advertise through its capability fails
+ * the delete with an error whose message includes `Unsupported`; OpenDAL never
+ * silently drops a condition. A service that cannot preserve a
+ * combination of conditions also returns `Unsupported`.
+ * - A service-side conflict unrelated to these conditions surfaces as
+ * `crate::ErrorKind::Conflict`.
+ *
+ * With valid, supported options, deleting a missing file remains a
+ * successful no-op once every condition holds.
+ *
+ * See the conditional operation specification
+ * for the complete cross-operation contract.
+ */
 export interface DeleteOptions {
+  /**
+   * Delete the given version of the file instead of the current one.
+   *
+   * This selects which stored version the delete removes; it is not a
+   * condition on the file.
+   *
+   * Check `Capability.deleteWithVersion` before using this
+   * option.
+   */
   version?: string
-  /** Whether to delete recursively. */
+  /**
+   * Whether to delete the target recursively.
+   *
+   * The default, `false`, deletes a single object. With `true`, a trailing
+   * slash (for example, `"a/"`) scopes deletion to a directory and its
+   * descendants across services. Prefix matching for paths without a
+   * trailing slash is service-specific. On prefix-based services such as
+   * `memory`, `"a"` also matches entries under `"ab/"`.
+   */
   recursive?: boolean
-  /** * Sets if-match condition for this operation.
-   * If file exists and its etag does not match, an error of kind
-   * `ConditionNotMatch` will be returned.
+  /**
+   * Delete only when the file at the delete path has this exact ETag.
+   *
+   * The condition succeeds when the file exists and its ETag equals this
+   * value. A file with a different ETag, or a missing file, fails the
+   * delete with `crate::ErrorKind::ConditionNotMatch`. Only concrete
+   * ETag values are portable; a wildcard such as `"*"` has no portable
+   * meaning here.
+   *
+   * The operation returns an error whose message includes `Unsupported` when 
the
+   * service does not advertise `Capability.deleteWithIfMatch`.
    */
   ifMatch?: string
 }
@@ -1415,7 +1461,7 @@ export interface ReadOptions {
  * file that fails a condition returns
  * `crate::ErrorKind::ConditionNotMatch`, and a condition the service does
  * not advertise through its capability returns
- * `crate::ErrorKind::Unsupported`; OpenDAL never silently drops a
+ * an error whose message includes `Unsupported`; OpenDAL never silently drops 
a
  * condition.
  *
  * See the conditional operation specification
@@ -1442,7 +1488,7 @@ export interface StatOptions {
    * `crate::ErrorKind::NotFound`. Only concrete ETag values are
    * portable; a wildcard such as `"*"` has no portable meaning here.
    *
-   * The operation returns `crate::ErrorKind::Unsupported` when the
+   * The operation returns an error whose message includes `Unsupported` when 
the
    * service does not advertise `Capability.statWithIfMatch`.
    */
   ifMatch?: string
@@ -1455,7 +1501,7 @@ export interface StatOptions {
    * returns `crate::ErrorKind::NotFound`. Only concrete ETag values
    * are portable; a wildcard such as `"*"` has no portable meaning here.
    *
-   * The operation returns `crate::ErrorKind::Unsupported` when the
+   * The operation returns an error whose message includes `Unsupported` when 
the
    * service does not advertise
    * `Capability.statWithIfNoneMatch`.
    */
@@ -1468,7 +1514,7 @@ export interface StatOptions {
    * `crate::ErrorKind::ConditionNotMatch`; a missing file returns
    * `crate::ErrorKind::NotFound`.
    *
-   * The operation returns `crate::ErrorKind::Unsupported` when the
+   * The operation returns an error whose message includes `Unsupported` when 
the
    * service does not advertise
    * `Capability.statWithIfModifiedSince`.
    *
@@ -1485,7 +1531,7 @@ export interface StatOptions {
    * `crate::ErrorKind::ConditionNotMatch`; a missing file returns
    * `crate::ErrorKind::NotFound`.
    *
-   * The operation returns `crate::ErrorKind::Unsupported` when the
+   * The operation returns an error whose message includes `Unsupported` when 
the
    * service does not advertise
    * `Capability.statWithIfUnmodifiedSince`.
    *
diff --git a/bindings/nodejs/src/options.rs b/bindings/nodejs/src/options.rs
index 18152528e4..35fea5a62c 100644
--- a/bindings/nodejs/src/options.rs
+++ b/bindings/nodejs/src/options.rs
@@ -23,8 +23,10 @@ use std::collections::HashMap;
 
 use crate::validate::parse_count;
 
+mod delete;
 mod list;
 mod stat;
+pub use delete::DeleteOptions;
 pub use list::ListOptions;
 pub use stat::StatOptions;
 
@@ -435,31 +437,6 @@ impl TryFrom<WriteOptions> for 
opendal::options::WriteOptions {
     }
 }
 
-#[napi(object)]
-#[derive(Default)]
-pub struct DeleteOptions {
-    pub version: Option<String>,
-    /// Whether to delete recursively.
-    pub recursive: Option<bool>,
-    /**
-     * Sets if-match condition for this operation.
-     * If file exists and its etag does not match, an error of kind
-     * `ConditionNotMatch` will be returned.
-     */
-    pub if_match: Option<String>,
-}
-
-impl From<DeleteOptions> for opendal::options::DeleteOptions {
-    fn from(value: DeleteOptions) -> Self {
-        Self {
-            version: value.version,
-            recursive: value.recursive.unwrap_or_default(),
-            if_match: value.if_match,
-            ..Default::default()
-        }
-    }
-}
-
 #[cfg(test)]
 mod tests {
     use super::ListOptions;
diff --git a/bindings/nodejs/src/options/delete.rs 
b/bindings/nodejs/src/options/delete.rs
new file mode 100644
index 0000000000..dbf743ca55
--- /dev/null
+++ b/bindings/nodejs/src/options/delete.rs
@@ -0,0 +1,85 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by 
opendal/dev/src/generate/nodejs.rs.
+
+/// Options for delete operations.
+///
+/// Each condition checks the file currently stored at the delete path, and
+/// every condition must hold for the delete to proceed:
+///
+/// - A false condition fails the delete with
+/// `crate::ErrorKind::ConditionNotMatch`.
+/// - A condition the service does not advertise through its capability fails
+/// the delete with an error whose message includes `Unsupported`; OpenDAL 
never
+/// silently drops a condition. A service that cannot preserve a
+/// combination of conditions also returns `Unsupported`.
+/// - A service-side conflict unrelated to these conditions surfaces as
+/// `crate::ErrorKind::Conflict`.
+///
+/// With valid, supported options, deleting a missing file remains a
+/// successful no-op once every condition holds.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[napi(object)]
+#[derive(Debug, Default)]
+pub struct DeleteOptions {
+    /// Delete the given version of the file instead of the current one.
+    ///
+    /// This selects which stored version the delete removes; it is not a
+    /// condition on the file.
+    ///
+    /// Check `Capability.deleteWithVersion` before using this
+    /// option.
+    pub version: Option<String>,
+
+    /// Whether to delete the target recursively.
+    ///
+    /// The default, `false`, deletes a single object. With `true`, a trailing
+    /// slash (for example, `"a/"`) scopes deletion to a directory and its
+    /// descendants across services. Prefix matching for paths without a
+    /// trailing slash is service-specific. On prefix-based services such as
+    /// `memory`, `"a"` also matches entries under `"ab/"`.
+    pub recursive: Option<bool>,
+
+    /// Delete only when the file at the delete path has this exact ETag.
+    ///
+    /// The condition succeeds when the file exists and its ETag equals this
+    /// value. A file with a different ETag, or a missing file, fails the
+    /// delete with `crate::ErrorKind::ConditionNotMatch`. Only concrete
+    /// ETag values are portable; a wildcard such as `"*"` has no portable
+    /// meaning here.
+    ///
+    /// The operation returns an error whose message includes `Unsupported` 
when the
+    /// service does not advertise `Capability.deleteWithIfMatch`.
+    pub if_match: Option<String>,
+}
+
+impl From<DeleteOptions> for opendal::options::DeleteOptions {
+    fn from(value: DeleteOptions) -> Self {
+        Self {
+            version: value.version,
+            recursive: value.recursive.unwrap_or_default(),
+            if_match: value.if_match,
+            if_none_match: Default::default(),
+            if_version_match: Default::default(),
+            if_version_not_match: Default::default(),
+            if_not_changed: Default::default(),
+        }
+    }
+}
diff --git a/bindings/nodejs/src/options/stat.rs 
b/bindings/nodejs/src/options/stat.rs
index 83c5c0a62b..55a8724250 100644
--- a/bindings/nodejs/src/options/stat.rs
+++ b/bindings/nodejs/src/options/stat.rs
@@ -25,7 +25,7 @@
 /// file that fails a condition returns
 /// `crate::ErrorKind::ConditionNotMatch`, and a condition the service does
 /// not advertise through its capability returns
-/// `crate::ErrorKind::Unsupported`; OpenDAL never silently drops a
+/// an error whose message includes `Unsupported`; OpenDAL never silently 
drops a
 /// condition.
 ///
 /// See the conditional operation specification
@@ -51,7 +51,7 @@ pub struct StatOptions {
     /// `crate::ErrorKind::NotFound`. Only concrete ETag values are
     /// portable; a wildcard such as `"*"` has no portable meaning here.
     ///
-    /// The operation returns `crate::ErrorKind::Unsupported` when the
+    /// The operation returns an error whose message includes `Unsupported` 
when the
     /// service does not advertise `Capability.statWithIfMatch`.
     pub if_match: Option<String>,
 
@@ -63,7 +63,7 @@ pub struct StatOptions {
     /// returns `crate::ErrorKind::NotFound`. Only concrete ETag values
     /// are portable; a wildcard such as `"*"` has no portable meaning here.
     ///
-    /// The operation returns `crate::ErrorKind::Unsupported` when the
+    /// The operation returns an error whose message includes `Unsupported` 
when the
     /// service does not advertise
     /// `Capability.statWithIfNoneMatch`.
     pub if_none_match: Option<String>,
@@ -75,7 +75,7 @@ pub struct StatOptions {
     /// `crate::ErrorKind::ConditionNotMatch`; a missing file returns
     /// `crate::ErrorKind::NotFound`.
     ///
-    /// The operation returns `crate::ErrorKind::Unsupported` when the
+    /// The operation returns an error whose message includes `Unsupported` 
when the
     /// service does not advertise
     /// `Capability.statWithIfModifiedSince`.
     ///
@@ -91,7 +91,7 @@ pub struct StatOptions {
     /// `crate::ErrorKind::ConditionNotMatch`; a missing file returns
     /// `crate::ErrorKind::NotFound`.
     ///
-    /// The operation returns `crate::ErrorKind::Unsupported` when the
+    /// The operation returns an error whose message includes `Unsupported` 
when the
     /// service does not advertise
     /// `Capability.statWithIfUnmodifiedSince`.
     ///
diff --git a/bindings/nodejs/tests/delete-options-surface.test.mjs 
b/bindings/nodejs/tests/delete-options-surface.test.mjs
new file mode 100644
index 0000000000..67b4aa2a2d
--- /dev/null
+++ b/bindings/nodejs/tests/delete-options-surface.test.mjs
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+
+import { assert, describe, expect, test } from 'vitest'
+
+import { Operator } from '../index.mjs'
+
+// `DeleteOptions` and the delete methods as `generated.d.ts` declared them
+// before `DeleteOptions` was generated from core. Callers pass these options
+// as object literals or implement the interface structurally, so each member
+// must stay with its type and stay optional, and a new member must be added
+// here on purpose.
+//
+// Each member comes with a value of its type, the core option it sets, and
+// the capability that core checks for that option. A service without the
+// capability must reject the delete naming the core option.
+const FROZEN_MEMBERS = [
+  ['version?: string', 'v1', 'version', 'deleteWithVersion'],
+  ['recursive?: boolean', true, 'recursive', 'deleteWithRecursive'],
+  ['ifMatch?: string', '"etag"', 'if_match', 'deleteWithIfMatch'],
+]
+
+const FROZEN_SIGNATURES = [
+  'delete(path: string, options?: DeleteOptions | undefined | null): 
Promise<void>',
+  'deleteSync(path: string, options?: DeleteOptions | undefined | null): void',
+]
+
+const DELETES = [
+  ['delete', (op, path, options) => op.delete(path, options)],
+  ['deleteSync', async (op, path, options) => op.deleteSync(path, options)],
+]
+
+function declared(kind, name) {
+  const dts = readFileSync(path.resolve(__dirname, '../generated.d.ts'), 
'utf8')
+  const body = dts.match(new RegExp(`^export ${kind} ${name} 
\\{\\n([\\s\\S]*?)^\\}`, 'm'))
+  assert.ok(body, `generated.d.ts declares ${kind} ${name}`)
+  return body[1]
+    .split('\n')
+    .filter((line) => /^ {2}\w/.test(line))
+    .map((line) => line.trim())
+}
+
+describe('DeleteOptions keeps its historical surface', () => {
+  const op = new Operator('memory')
+
+  test('declares exactly the frozen members', () => {
+    assert.sameMembers(
+      declared('interface', 'DeleteOptions'),
+      FROZEN_MEMBERS.map(([member]) => member),
+    )
+  })
+
+  for (const signature of FROZEN_SIGNATURES) {
+    test(signature, () => {
+      assert.include(declared('declare class', 'Operator'), signature)
+    })
+  }
+
+  for (const [member, value, coreOption, capability] of FROZEN_MEMBERS) {
+    const [, field] = member.match(/^(\w+)\?: /)
+    const options = { [field]: value }
+
+    for (const [method, del] of DELETES) {
+      test(`${method} with ${member}`, async () => {
+        const file = `delete-options-surface/${method}-${field}`
+        const missing = `delete-options-surface/${method}-${field}-missing`
+        op.writeSync(file, 'content')
+
+        if (op.capability()[capability]) {
+          // The delete accepts a value of the declared type, and a missing
+          // path is a successful no-op.
+          await del(op, file, options)
+          assert.isFalse(op.existsSync(file))
+          await del(op, missing, options)
+        } else {
+          // The option reaches core as `coreOption`, which this service does
+          // not support, so the delete fails even for a missing path.
+          const unsupported = new RegExp(
+            `^Unsupported \\(permanent\\) at delete\\b.* with the arguments 
${coreOption}\\.`,
+          )
+          await expect(del(op, file, 
options)).rejects.toThrowError(unsupported)
+          await expect(del(op, missing, 
options)).rejects.toThrowError(unsupported)
+          assert.isTrue(op.existsSync(file))
+        }
+      })
+    }
+  }
+
+  for (const [method, del] of DELETES) {
+    test(`${method} deletes descendants only with recursive`, async () => {
+      const dir = `delete-options-surface/${method}-dir/`
+      op.writeSync(`${dir}child`, 'content')
+
+      // Without `recursive`, the delete targets only the directory itself;
+      // memory refuses to delete a directory that still has children.
+      for (const options of [undefined, {}, { recursive: false }]) {
+        await del(op, dir, options).catch(() => {})
+        assert.isTrue(op.existsSync(`${dir}child`), JSON.stringify(options))
+      }
+
+      await del(op, dir, { recursive: true })
+      assert.isFalse(op.existsSync(`${dir}child`))
+    })
+  }
+})
diff --git a/core/core/src/types/options.rs b/core/core/src/types/options.rs
index 846be9f343..b6d194bb8f 100644
--- a/core/core/src/types/options.rs
+++ b/core/core/src/types/options.rs
@@ -37,8 +37,8 @@ use std::collections::HashMap;
 /// - A service-side conflict unrelated to these conditions surfaces as
 ///   [`crate::ErrorKind::Conflict`].
 ///
-/// Once every condition holds, deleting a missing file remains a successful
-/// no-op.
+/// With valid, supported options, deleting a missing file remains a
+/// successful no-op once every condition holds.
 ///
 /// See the [conditional operation 
specification][crate::docs::specs::conditional_operations]
 /// for the complete cross-operation contract.
diff --git a/dev/src/generate/nodejs.rs b/dev/src/generate/nodejs.rs
index ca0fc02d29..c0f585e77a 100644
--- a/dev/src/generate/nodejs.rs
+++ b/dev/src/generate/nodejs.rs
@@ -214,6 +214,16 @@ const STAT_OPTIONS: JsOptions = JsOptions {
     ],
 };
 
+const DELETE_OPTIONS: JsOptions = JsOptions {
+    name: "DeleteOptions",
+    module: "delete",
+    fields: &[
+        ("version", OptionKind::OptionString),
+        ("recursive", OptionKind::Bool),
+        ("if_match", OptionKind::OptionString),
+    ],
+};
+
 /// Render model for one field of a napi options object.
 #[derive(Serialize)]
 struct OptionsField {
@@ -244,7 +254,7 @@ fn generate_options(workspace_dir: &Path) -> Result<()> {
 
     let dir = workspace_dir.join("bindings/nodejs/src/options");
     fs::create_dir_all(&dir)?;
-    for options in [&LIST_OPTIONS, &STAT_OPTIONS] {
+    for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS] {
         let rendered = render_options(&parsed, options, &capabilities)?;
         fs::write(
             dir.join(format!("{}.rs", options.module)),
@@ -307,21 +317,11 @@ fn render_options(
         });
     }
 
-    let mut doc = js_doc(&core.doc, options, capabilities);
-    if struct_name == LIST_OPTIONS.name {
-        for line in &mut doc {
-            *line = line.replace(
-                "`crate::ErrorKind::Unsupported`",
-                "an error whose message includes `Unsupported`",
-            );
-        }
-    }
-
     let mut env = Environment::new();
     env.add_template("options_rs", include_str!("nodejs/options_rs.j2"))?;
     Ok(env.get_template("options_rs")?.render(context! {
         name => struct_name,
-        doc => doc,
+        doc => js_doc(&core.doc, options, capabilities),
         fields => Serde(&fields),
         conversions => Serde(&conversions),
         fallible => fallible,
@@ -391,6 +391,9 @@ fn js_type(struct_name: &str, field: &OptionField) -> 
Result<JsType> {
 /// `[conditional operation 
specification][crate::docs::specs::conditional_operations]`
 /// keeps only its text. Code spans that name a JS property then use its JS
 /// name (see [`js_code_span`]); other code spans stay as written.
+///
+/// JS errors carry no `ErrorKind`, so `crate::ErrorKind::Unsupported` reads
+/// "an error whose message includes `Unsupported`".
 fn js_doc(lines: &[String], options: &JsOptions, capabilities: 
&[CapabilityField]) -> Vec<String> {
     lines
         .iter()
@@ -398,6 +401,10 @@ fn js_doc(lines: &[String], options: &JsOptions, 
capabilities: &[CapabilityField
             rewrite_code_spans(&strip_crate_reference_links(line), |code| {
                 js_code_span(code, options, capabilities)
             })
+            .replace(
+                "`crate::ErrorKind::Unsupported`",
+                "an error whose message includes `Unsupported`",
+            )
         })
         .collect()
 }
@@ -559,7 +566,7 @@ mod tests {
 
     #[test]
     fn test_options_new_core_field_is_not_exposed() {
-        for options in [&LIST_OPTIONS, &STAT_OPTIONS] {
+        for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS] {
             let core = core_options(options.name);
             let mut mutated = core.clone();
             mutated.fields.insert(
@@ -600,9 +607,18 @@ mod tests {
         let err = render(missing, &STAT_OPTIONS).unwrap_err().to_string();
         assert!(err.contains("StatOptions has no field `if_match`"), "{err}");
 
+        let mut missing = core_options("DeleteOptions");
+        missing.fields.retain(|field| field.name != "recursive");
+        let err = render(missing, &DELETE_OPTIONS).unwrap_err().to_string();
+        assert!(
+            err.contains("DeleteOptions has no field `recursive`"),
+            "{err}"
+        );
+
         // A kind change must fail, whether or not JS supports the new kind:
         // `limit` must not change its JS type, `startAfter` must not turn
-        // into a boolean, and `ifModifiedSince` must keep being parsed.
+        // into a boolean, `ifModifiedSince` must keep being parsed, and the
+        // delete `recursive` must stay a boolean.
         for (options, name, kind, expected) in [
             (
                 &LIST_OPTIONS,
@@ -628,6 +644,12 @@ mod tests {
                 OptionKind::OptionTimestamp,
                 "StatOptions::version is OptionTimestamp",
             ),
+            (
+                &DELETE_OPTIONS,
+                "recursive",
+                OptionKind::OptionString,
+                "DeleteOptions::recursive is OptionString",
+            ),
         ] {
             let mut changed = core_options(options.name);
             let field = changed.fields.iter_mut().find(|f| f.name == 
name).unwrap();
@@ -656,31 +678,70 @@ mod tests {
     }
 
     #[test]
-    fn test_stat_options_keep_existing_js_fields() {
-        let rendered = render(core_options("StatOptions"), 
&STAT_OPTIONS).unwrap();
-        let fields: Vec<&str> = napi_struct(&rendered)
-            .lines()
-            .filter_map(|line| line.strip_prefix("    pub "))
-            .collect();
-        // The members and order of `StatOptions` in `generated.d.ts` on main.
-        assert_eq!(
-            fields,
-            [
-                "version: Option<String>,",
-                "if_match: Option<String>,",
-                "if_none_match: Option<String>,",
-                "if_modified_since: Option<String>,",
-                "if_unmodified_since: Option<String>,",
-                "override_content_type: Option<String>,",
-                "override_cache_control: Option<String>,",
-                "override_content_disposition: Option<String>,",
-            ]
+    fn test_options_keep_existing_js_fields() {
+        // The members and order of each struct in `generated.d.ts` on main,
+        // and the core fields that JS does not expose.
+        for (options, expected, unexposed) in [
+            (
+                &STAT_OPTIONS,
+                &[
+                    "version: Option<String>,",
+                    "if_match: Option<String>,",
+                    "if_none_match: Option<String>,",
+                    "if_modified_since: Option<String>,",
+                    "if_unmodified_since: Option<String>,",
+                    "override_content_type: Option<String>,",
+                    "override_cache_control: Option<String>,",
+                    "override_content_disposition: Option<String>,",
+                ][..],
+                &["if_version_match", "if_version_not_match", "checksum"][..],
+            ),
+            (
+                &DELETE_OPTIONS,
+                &[
+                    "version: Option<String>,",
+                    "recursive: Option<bool>,",
+                    "if_match: Option<String>,",
+                ][..],
+                &[
+                    "if_none_match",
+                    "if_version_match",
+                    "if_version_not_match",
+                    "if_not_changed",
+                ][..],
+            ),
+        ] {
+            let name = options.name;
+            let rendered = render(core_options(name), options).unwrap();
+            let fields: Vec<&str> = napi_struct(&rendered)
+                .lines()
+                .filter_map(|line| line.strip_prefix("    pub "))
+                .collect();
+            assert_eq!(fields, expected, "{name}");
+            for unexposed in unexposed {
+                assert!(
+                    rendered.contains(&format!("            {unexposed}: 
Default::default(),\n")),
+                    "{name}::{unexposed}"
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn test_delete_options_conversion() {
+        let rendered = render(core_options("DeleteOptions"), 
&DELETE_OPTIONS).unwrap();
+        assert!(
+            rendered.contains("impl From<DeleteOptions> for 
opendal::options::DeleteOptions {")
         );
-        for unexposed in ["if_version_match", "if_version_not_match", 
"checksum"] {
-            assert!(
-                rendered.contains(&format!("            {unexposed}: 
Default::default(),\n")),
-                "{unexposed}"
-            );
+        assert!(!rendered.contains("TryFrom"));
+        // The conversion on main: strings pass through, and an omitted
+        // `recursive` deletes a single object.
+        for line in [
+            "            version: value.version,\n",
+            "            recursive: value.recursive.unwrap_or_default(),\n",
+            "            if_match: value.if_match,\n",
+        ] {
+            assert!(rendered.contains(line), "{line}");
         }
     }
 
@@ -775,17 +836,104 @@ mod tests {
         );
     }
 
+    #[test]
+    fn test_js_doc_describes_unsupported_errors_by_message() {
+        let lines = [
+            "Fails with [`crate::ErrorKind::Unsupported`] when unsupported.",
+            "The operation returns [`crate::ErrorKind::Unsupported`] when the",
+            "A missing file returns [`crate::ErrorKind::NotFound`], a failed 
condition",
+            "[`crate::ErrorKind::ConditionNotMatch`], and some calls also 
return `Unsupported`.",
+        ]
+        .map(String::from);
+        // The rewrite applies to every options struct, not only `ListOptions`,
+        // and leaves other error kinds as written.
+        for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS] {
+            assert_eq!(
+                js_doc(&lines, options, &core_capabilities()),
+                [
+                    "Fails with an error whose message includes `Unsupported` 
when unsupported.",
+                    "The operation returns an error whose message includes 
`Unsupported` when the",
+                    "A missing file returns `crate::ErrorKind::NotFound`, a 
failed condition",
+                    "`crate::ErrorKind::ConditionNotMatch`, and some calls 
also return `Unsupported`.",
+                ],
+                "{}",
+                options.name
+            );
+        }
+    }
+
+    #[test]
+    fn test_options_docs_describe_unsupported_errors_by_message() {
+        // Core's struct and field docs, as rendered for JS, for each struct.
+        for (options, expected) in [
+            (
+                &LIST_OPTIONS,
+                &[concat!(
+                    "/// The operation fails with an error whose message 
includes `Unsupported` when an option\n",
+                    "/// requires a capability that the operator lacks.\n",
+                    "#[napi(object)]",
+                )][..],
+            ),
+            (
+                &STAT_OPTIONS,
+                &[
+                    concat!(
+                        "/// not advertise through its capability returns\n",
+                        "/// an error whose message includes `Unsupported`; 
OpenDAL never silently drops a\n",
+                    ),
+                    concat!(
+                        "    /// The operation returns an error whose message 
includes `Unsupported` when the\n",
+                        "    /// service does not advertise 
`Capability.statWithIfMatch`.\n",
+                        "    pub if_match: Option<String>,",
+                    ),
+                    concat!(
+                        "    /// The operation returns an error whose message 
includes `Unsupported` when the\n",
+                        "    /// service does not advertise\n",
+                        "    /// `Capability.statWithIfUnmodifiedSince`.\n",
+                    ),
+                ][..],
+            ),
+            (
+                &DELETE_OPTIONS,
+                &[
+                    concat!(
+                        "/// - A condition the service does not advertise 
through its capability fails\n",
+                        "/// the delete with an error whose message includes 
`Unsupported`; OpenDAL never\n",
+                    ),
+                    concat!(
+                        "    /// The operation returns an error whose message 
includes `Unsupported` when the\n",
+                        "    /// service does not advertise 
`Capability.deleteWithIfMatch`.\n",
+                        "    pub if_match: Option<String>,",
+                    ),
+                ][..],
+            ),
+        ] {
+            let name = options.name;
+            let rendered = render(core_options(name), options).unwrap();
+            for expected in expected {
+                assert!(rendered.contains(expected), "{name}: {expected}");
+            }
+            assert!(
+                !rendered.contains("ErrorKind::Unsupported"),
+                "{name}: {rendered}"
+            );
+        }
+
+        // Other error kinds stay as core writes them.
+        let stat = render(core_options("StatOptions"), &STAT_OPTIONS).unwrap();
+        assert!(stat.contains(
+            "/// `crate::ErrorKind::ConditionNotMatch`, and a condition the 
service does\n"
+        ));
+        let delete = render(core_options("DeleteOptions"), 
&DELETE_OPTIONS).unwrap();
+        assert!(delete.contains("/// `crate::ErrorKind::Conflict`.\n"));
+    }
+
     #[test]
     fn test_list_options_docs_use_js_names() {
         let rendered = render(core_options("ListOptions"), 
&LIST_OPTIONS).unwrap();
         // Core writes `start_after` as a plain code span in the struct doc and
         // the capability as a rustdoc link in the field doc.
         assert!(rendered.contains("/// - Pagination: `limit`, 
`startAfter`.\n"));
-        assert!(rendered.contains(concat!(
-            "/// The operation fails with an error whose message includes 
`Unsupported` when an option\n",
-            "/// requires a capability that the operator lacks.\n",
-            "#[napi(object)]",
-        )));
         assert!(rendered.contains(
             "    /// Setting this requires `Capability.listWithStartAfter`.\n  
  pub start_after: Option<String>,"
         ));
@@ -799,29 +947,44 @@ mod tests {
     }
 
     #[test]
-    fn test_stat_options_docs_use_js_names() {
-        let rendered = render(core_options("StatOptions"), 
&STAT_OPTIONS).unwrap();
-        // Core links each condition to the capability that it requires.
-        for (name, capability) in [
-            ("version", "`Capability.statWithVersion`"),
-            ("if_match", "`Capability.statWithIfMatch`"),
-            ("if_none_match", "`Capability.statWithIfNoneMatch`"),
-            ("if_modified_since", "`Capability.statWithIfModifiedSince`"),
+    fn test_options_docs_use_js_capability_names() {
+        // Core links each version or condition option to the capability that
+        // it requires.
+        for (options, expected) in [
             (
-                "if_unmodified_since",
-                "`Capability.statWithIfUnmodifiedSince`",
+                &STAT_OPTIONS,
+                &[
+                    ("version", "`Capability.statWithVersion`"),
+                    ("if_match", "`Capability.statWithIfMatch`"),
+                    ("if_none_match", "`Capability.statWithIfNoneMatch`"),
+                    ("if_modified_since", 
"`Capability.statWithIfModifiedSince`"),
+                    (
+                        "if_unmodified_since",
+                        "`Capability.statWithIfUnmodifiedSince`",
+                    ),
+                ][..],
+            ),
+            (
+                &DELETE_OPTIONS,
+                &[
+                    ("version", "`Capability.deleteWithVersion`"),
+                    ("if_match", "`Capability.deleteWithIfMatch`"),
+                ][..],
             ),
         ] {
-            let doc = field_doc(&rendered, name).join(" ");
-            assert!(doc.contains(capability), "{name}: {doc}");
-        }
-        // No Rust capability paths or rustdoc link syntax reach JS.
-        for line in rendered
-            .lines()
-            .filter(|l| l.trim_start().starts_with("///"))
-        {
-            assert!(!line.contains("Capability::"), "{line}");
-            assert!(!line.contains('['), "{line}");
+            let rendered = render(core_options(options.name), 
options).unwrap();
+            for (name, capability) in expected {
+                let doc = field_doc(&rendered, name).join(" ");
+                assert!(doc.contains(capability), "{name}: {doc}");
+            }
+            // No Rust capability paths or rustdoc link syntax reach JS.
+            for line in rendered
+                .lines()
+                .filter(|l| l.trim_start().starts_with("///"))
+            {
+                assert!(!line.contains("Capability::"), "{line}");
+                assert!(!line.contains('['), "{line}");
+            }
         }
     }
 }

Reply via email to