@ac-kit/storage-opendal 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,51 @@
1
+ # @ac-kit/storage-opendal
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0b4fe43: New package: Apache OpenDAL's Node.js binding (a peer dependency,
8
+ `>=0.49.13 <0.50.0`) with its errors classified and Web Streams over an
9
+ `Operator`.
10
+
11
+ - `parseOpendalError(error)` reads an OpenDAL error's `kind` (`NotFound`,
12
+ `PermissionDenied`, `ConditionNotMatch`, `RateLimited`, …), `status`
13
+ (`permanent`, `temporary`, `persistent`) and `operation`, or answers `null`
14
+ for any other error; `isOpendalErrorWithKind(error, kind)` tests one kind;
15
+ `isKnownOpendalErrorKind` tells the known kinds from one a later release
16
+ adds.
17
+ - `opendalReadableStream(operator, path, { range, chunkSize, version, signal })`
18
+ reads an object as a byte stream (BYOB readers read in place). A ranged read
19
+ `stat`s the object and pins every request to its version or ETag where the
20
+ service supports it, so a replaced object fails the read rather than mixing
21
+ bytes; a range past the end reads nothing; a short read errors.
22
+ - `opendalWritableStream(operator, path, { write, signal })` writes an object,
23
+ committed only when the stream closes (an empty object when closed without
24
+ bytes), with OpenDAL's write options passed as given. Errors from both
25
+ streams are OpenDAL's own.
26
+
27
+ ### Patch Changes
28
+
29
+ - Updated dependencies [0b4fe43]
30
+ - Updated dependencies [0b4fe43]
31
+ - Updated dependencies [0b4fe43]
32
+ - Updated dependencies [0b4fe43]
33
+ - Updated dependencies [0b4fe43]
34
+ - Updated dependencies [0b4fe43]
35
+ - Updated dependencies [0b4fe43]
36
+ - Updated dependencies [0b4fe43]
37
+ - Updated dependencies [0b4fe43]
38
+ - Updated dependencies [0b4fe43]
39
+ - Updated dependencies [0b4fe43]
40
+ - Updated dependencies [0b4fe43]
41
+ - Updated dependencies [0b4fe43]
42
+ - Updated dependencies [0b4fe43]
43
+ - Updated dependencies [0b4fe43]
44
+ - Updated dependencies [0b4fe43]
45
+ - Updated dependencies [0b4fe43]
46
+ - Updated dependencies [0b4fe43]
47
+ - Updated dependencies [0b4fe43]
48
+ - Updated dependencies [0b4fe43]
49
+ - Updated dependencies [0b4fe43]
50
+ - @ac-kit/core@0.13.0
51
+ - @ac-kit/node@0.12.0
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024-2026 Anthony Champagne and contributors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # @ac-kit/storage-opendal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use [Apache OpenDAL](https://opendal.apache.org/)'s Node.js binding with its
4
+ errors told apart and its objects read and written as Web Streams.
5
+
6
+ OpenDAL reaches S3, Google Cloud Storage, Azure Blob Storage, WebDAV, a local
7
+ directory and some fifty other services through one `Operator`. Its Node.js
8
+ binding throws the same plain `Error` for every failure, with N-API's
9
+ `GenericFailure` as its `code`: whether an object is missing, access is denied
10
+ or the service throttled you is only in the message text. Its readers and
11
+ writers take Node `Buffer`s one call at a time, and a ranged read is one
12
+ request that loads the whole range into memory. This package reads the error
13
+ for you, and puts Web Streams over the operator, with ranged reads that cannot
14
+ mix two versions of an object.
15
+
16
+ Node only (`H`): OpenDAL's binding is native. Install `opendal` beside it, a
17
+ peer dependency (`>=0.49.13 <0.50.0`, the releases whose error text this
18
+ package was checked against). API reference:
19
+ <https://anthochamp.pages.grenadine.io/node-essentials/api/storage-opendal/>.
20
+
21
+ ## Errors
22
+
23
+ ```ts
24
+ import { isOpendalErrorWithKind, parseOpendalError } from "@ac-kit/storage-opendal";
25
+ import { Operator } from "opendal";
26
+
27
+ const operator = new Operator("s3", { bucket: "media", region: "eu-west-3" });
28
+
29
+ const metadata = await operator.stat("videos/talk.mp4").catch((error: unknown) => {
30
+ if (isOpendalErrorWithKind(error, "NotFound")) return null;
31
+ throw error;
32
+ });
33
+
34
+ try {
35
+ await operator.write("videos/talk.mp4", bytes, { ifNotExists: true });
36
+ } catch (error) {
37
+ parseOpendalError(error);
38
+ // { kind: "ConditionNotMatch", status: "permanent", operation: "write" }
39
+ }
40
+ ```
41
+
42
+ `kind` is OpenDAL's `ErrorKind` (`NotFound`, `PermissionDenied`,
43
+ `AlreadyExists`, `ConditionNotMatch`, `RateLimited`, `IsADirectory`, …) and
44
+ `status` says whether to retry: `temporary` yes, `permanent` no, `persistent`
45
+ when a retry layer already gave up. Anything that is not an OpenDAL error gives
46
+ `null`. Only the error's header is read; the context and message after it are
47
+ free text.
48
+
49
+ ## Reading
50
+
51
+ ```ts
52
+ import { opendalReadableStream } from "@ac-kit/storage-opendal";
53
+
54
+ const whole = opendalReadableStream(operator, "videos/talk.mp4");
55
+ const firstMegabyte = opendalReadableStream(operator, "videos/talk.mp4", {
56
+ range: { offset: 0n, length: 1_048_576n },
57
+ signal: request.signal,
58
+ });
59
+ return new Response(firstMegabyte);
60
+ ```
61
+
62
+ The stream is a byte stream: a BYOB reader has OpenDAL read straight into its
63
+ buffer. Without a range, one OpenDAL `Reader` reads the object from its start.
64
+ With one, the object is `stat`ed, then read in requests of `chunkSize` (256 KiB
65
+ by default), each pinned to the version or ETag the `stat` returned where the
66
+ service supports it, so an object replaced mid-read fails the read with
67
+ `ConditionNotMatch` instead of mixing two objects. A range past the end reads
68
+ nothing, as `Blob.slice` would. Errors are OpenDAL's own: a missing object
69
+ fails the first read with `NotFound`.
70
+
71
+ ## Writing
72
+
73
+ ```ts
74
+ import { opendalWritableStream } from "@ac-kit/storage-opendal";
75
+
76
+ await upload.body.pipeTo(
77
+ opendalWritableStream(operator, "videos/talk.mp4", {
78
+ write: { contentType: "video/mp4", ifNotExists: true },
79
+ }),
80
+ );
81
+ ```
82
+
83
+ Nothing is committed until the stream closes; closing it without bytes writes
84
+ an empty object. An aborted stream, an aborted `signal` or a failed write never
85
+ commits. `write` takes OpenDAL's own write options as they are (`chunk` sets
86
+ the part size of a multipart upload). An S3 multipart upload left by an abort
87
+ is not cancelled, since the binding cannot: let a lifecycle rule remove it.
88
+
89
+ Keys are passed as given. Check keys that come from outside with
90
+ `@ac-kit/storage-key` first.
@@ -0,0 +1,4 @@
1
+ export * from "./opendal-error.js";
2
+ export * from "./opendal-readable-stream.js";
3
+ export * from "./opendal-writable-stream.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,8BAA8B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./opendal-error.js";
2
+ export * from "./opendal-readable-stream.js";
3
+ export * from "./opendal-writable-stream.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,8BAA8B,CAAC"}
@@ -0,0 +1,93 @@
1
+ /**
2
+ * What went wrong, as OpenDAL's `ErrorKind` names it.
3
+ *
4
+ * - `"Unexpected"` — anything else, a service or network failure included.
5
+ * - `"Unsupported"` — the service or this operator cannot do it.
6
+ * - `"ConfigInvalid"` — the operator's configuration is wrong.
7
+ * - `"NotFound"` — no such object or directory.
8
+ * - `"PermissionDenied"` — the credentials do not allow it.
9
+ * - `"IsADirectory"` / `"NotADirectory"` — the path names the other kind.
10
+ * - `"AlreadyExists"` — the target exists.
11
+ * - `"RateLimited"` — the service throttled the request.
12
+ * - `"IsSameFile"` — a copy or rename onto itself.
13
+ * - `"ConditionNotMatch"` — a condition (`ifMatch`, `ifNoneMatch`, `ifNotExists`,
14
+ * a version) did not hold.
15
+ * - `"RangeNotSatisfied"` — a byte range outside the object.
16
+ */
17
+ export type OpendalErrorKind = "Unexpected" | "Unsupported" | "ConfigInvalid" | "NotFound" | "PermissionDenied" | "IsADirectory" | "NotADirectory" | "AlreadyExists" | "RateLimited" | "IsSameFile" | "ConditionNotMatch" | "RangeNotSatisfied";
18
+ /**
19
+ * Whether trying again may help, as OpenDAL's `ErrorStatus` says.
20
+ *
21
+ * - `"permanent"` — no: the same request fails the same way.
22
+ * - `"temporary"` — yes, such as a timeout or a throttled request.
23
+ * - `"persistent"` — it was temporary, but a retry layer already retried it and
24
+ * gave up.
25
+ */
26
+ export type OpendalErrorStatus = "permanent" | "temporary" | "persistent";
27
+ /** What {@link parseOpendalError} reads from an OpenDAL error. */
28
+ export type OpendalErrorInfo = {
29
+ /**
30
+ * One of {@link OpendalErrorKind}, or a kind a later OpenDAL release added, as
31
+ * it spells it.
32
+ */
33
+ readonly kind: OpendalErrorKind | (string & {});
34
+ readonly status: OpendalErrorStatus;
35
+ /**
36
+ * The operation that failed, as OpenDAL names it (`stat`, `read`,
37
+ * `Reader::read`, `Writer::close`, `list`), or `""` when building an
38
+ * operator.
39
+ */
40
+ readonly operation: string;
41
+ };
42
+ /**
43
+ * Reads the kind, status and operation of an error thrown by OpenDAL's Node.js
44
+ * binding, or `null` when `error` is not one.
45
+ *
46
+ * The binding (`opendal` 0.49) throws a plain `Error` whose `code` is N-API's
47
+ * `"GenericFailure"` for every failure; the kind and status are only in its
48
+ * message, `NotFound (permanent) at stat, context: { service: s3, path: a } =>
49
+ * …`. This reads them from there, the one place they are. Only the header is
50
+ * read: the context and message that follow are free text holding paths and
51
+ * service replies, which may contain anything.
52
+ *
53
+ * Complexity: O(1) beyond the engine's match of the header.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * try {
58
+ * await operator.stat("missing");
59
+ * } catch (error) {
60
+ * parseOpendalError(error); // { kind: "NotFound", status: "permanent", operation: "stat" }
61
+ * }
62
+ * ```;
63
+ *
64
+ * @param error Anything caught.
65
+ * @returns What the error says, or `null` for anything but an OpenDAL error.
66
+ * @see {@link isOpendalErrorWithKind} to test one kind.
67
+ */
68
+ export declare function parseOpendalError(error: unknown): OpendalErrorInfo | null;
69
+ /**
70
+ * Whether `error` is an OpenDAL error of `kind`: `"NotFound"` for a missing
71
+ * object, `"ConditionNotMatch"` for a failed `ifNotExists` write, and so on.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const metadata = await operator.stat(path).catch((error: unknown) => {
76
+ * if (isOpendalErrorWithKind(error, "NotFound")) return null;
77
+ * throw error;
78
+ * });
79
+ * ```;
80
+ *
81
+ * @param error Anything caught.
82
+ * @param kind The kind to test for.
83
+ * @see {@link parseOpendalError} for the status and operation as well.
84
+ */
85
+ export declare function isOpendalErrorWithKind(error: unknown, kind: OpendalErrorKind): boolean;
86
+ /**
87
+ * Whether `kind` is one of the kinds this package knows, rather than one a
88
+ * later OpenDAL release added.
89
+ *
90
+ * @param kind A kind read by {@link parseOpendalError}.
91
+ */
92
+ export declare function isKnownOpendalErrorKind(kind: string): kind is OpendalErrorKind;
93
+ //# sourceMappingURL=opendal-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opendal-error.d.ts","sourceRoot":"","sources":["../src/opendal-error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,gBAAgB,GACzB,YAAY,GACZ,aAAa,GACb,eAAe,GACf,UAAU,GACV,kBAAkB,GAClB,cAAc,GACd,eAAe,GACf,eAAe,GACf,aAAa,GACb,YAAY,GACZ,mBAAmB,GACnB,mBAAmB,CAAC;AAEvB;;;;;;;GAOG;AACH,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,WAAW,GAAG,YAAY,CAAC;AAE1E,kEAAkE;AAClE,MAAM,MAAM,gBAAgB,GAAG;IAC9B;;;OAGG;IACH,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;IAChD,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;IACpC;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC3B,CAAC;AAqBF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,gBAAgB,GAAG,IAAI,CAiBzE;AAaD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,sBAAsB,CACrC,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,gBAAgB,GACpB,OAAO,CAET;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACtC,IAAI,EAAE,MAAM,GACV,IAAI,IAAI,gBAAgB,CAE1B"}
@@ -0,0 +1,97 @@
1
+ const KINDS_ = new Set([
2
+ "Unexpected",
3
+ "Unsupported",
4
+ "ConfigInvalid",
5
+ "NotFound",
6
+ "PermissionDenied",
7
+ "IsADirectory",
8
+ "NotADirectory",
9
+ "AlreadyExists",
10
+ "RateLimited",
11
+ "IsSameFile",
12
+ "ConditionNotMatch",
13
+ "RangeNotSatisfied",
14
+ ]);
15
+ // `<kind> (<status>) at <operation>`, then the context, the message or the end.
16
+ const HEADER_ = /^([A-Z][A-Za-z]*) \((permanent|temporary|persistent)\) at ([A-Za-z_:]*)(?:, context: \{| => |$)/;
17
+ /**
18
+ * Reads the kind, status and operation of an error thrown by OpenDAL's Node.js
19
+ * binding, or `null` when `error` is not one.
20
+ *
21
+ * The binding (`opendal` 0.49) throws a plain `Error` whose `code` is N-API's
22
+ * `"GenericFailure"` for every failure; the kind and status are only in its
23
+ * message, `NotFound (permanent) at stat, context: { service: s3, path: a } =>
24
+ * …`. This reads them from there, the one place they are. Only the header is
25
+ * read: the context and message that follow are free text holding paths and
26
+ * service replies, which may contain anything.
27
+ *
28
+ * Complexity: O(1) beyond the engine's match of the header.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * try {
33
+ * await operator.stat("missing");
34
+ * } catch (error) {
35
+ * parseOpendalError(error); // { kind: "NotFound", status: "permanent", operation: "stat" }
36
+ * }
37
+ * ```;
38
+ *
39
+ * @param error Anything caught.
40
+ * @returns What the error says, or `null` for anything but an OpenDAL error.
41
+ * @see {@link isOpendalErrorWithKind} to test one kind.
42
+ */
43
+ export function parseOpendalError(error) {
44
+ if (!(error instanceof Error) ||
45
+ !("code" in error) ||
46
+ error.code !== "GenericFailure") {
47
+ return null;
48
+ }
49
+ const header = HEADER_.exec(error.message);
50
+ if (header === null) {
51
+ return null;
52
+ }
53
+ return {
54
+ kind: header[1],
55
+ status: status_(header[2]),
56
+ operation: header[3],
57
+ };
58
+ }
59
+ function status_(text) {
60
+ switch (text) {
61
+ case "temporary":
62
+ return "temporary";
63
+ case "persistent":
64
+ return "persistent";
65
+ default:
66
+ return "permanent";
67
+ }
68
+ }
69
+ /**
70
+ * Whether `error` is an OpenDAL error of `kind`: `"NotFound"` for a missing
71
+ * object, `"ConditionNotMatch"` for a failed `ifNotExists` write, and so on.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const metadata = await operator.stat(path).catch((error: unknown) => {
76
+ * if (isOpendalErrorWithKind(error, "NotFound")) return null;
77
+ * throw error;
78
+ * });
79
+ * ```;
80
+ *
81
+ * @param error Anything caught.
82
+ * @param kind The kind to test for.
83
+ * @see {@link parseOpendalError} for the status and operation as well.
84
+ */
85
+ export function isOpendalErrorWithKind(error, kind) {
86
+ return parseOpendalError(error)?.kind === kind;
87
+ }
88
+ /**
89
+ * Whether `kind` is one of the kinds this package knows, rather than one a
90
+ * later OpenDAL release added.
91
+ *
92
+ * @param kind A kind read by {@link parseOpendalError}.
93
+ */
94
+ export function isKnownOpendalErrorKind(kind) {
95
+ return KINDS_.has(kind);
96
+ }
97
+ //# sourceMappingURL=opendal-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opendal-error.js","sourceRoot":"","sources":["../src/opendal-error.ts"],"names":[],"mappings":"AAwDA,MAAM,MAAM,GAAwB,IAAI,GAAG,CAAmB;IAC7D,YAAY;IACZ,aAAa;IACb,eAAe;IACf,UAAU;IACV,kBAAkB;IAClB,cAAc;IACd,eAAe;IACf,eAAe;IACf,aAAa;IACb,YAAY;IACZ,mBAAmB;IACnB,mBAAmB;CACnB,CAAC,CAAC;AAEH,gFAAgF;AAChF,MAAM,OAAO,GACZ,iGAAiG,CAAC;AAEnG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC/C,IACC,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QACzB,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC;QAClB,KAAK,CAAC,IAAI,KAAK,gBAAgB,EAC9B,CAAC;QACF,OAAO,IAAI,CAAC;IACb,CAAC;IACD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3C,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACb,CAAC;IACD,OAAO;QACN,IAAI,EAAE,MAAM,CAAC,CAAC,CAAE;QAChB,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC;QAC3B,SAAS,EAAE,MAAM,CAAC,CAAC,CAAE;KACrB,CAAC;AACH,CAAC;AAED,SAAS,OAAO,CAAC,IAAY;IAC5B,QAAQ,IAAI,EAAE,CAAC;QACd,KAAK,WAAW;YACf,OAAO,WAAW,CAAC;QACpB,KAAK,YAAY;YAChB,OAAO,YAAY,CAAC;QACrB;YACC,OAAO,WAAW,CAAC;IACrB,CAAC;AACF,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,sBAAsB,CACrC,KAAc,EACd,IAAsB;IAEtB,OAAO,iBAAiB,CAAC,KAAK,CAAC,EAAE,IAAI,KAAK,IAAI,CAAC;AAChD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CACtC,IAAY;IAEZ,OAAO,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC"}
@@ -0,0 +1,65 @@
1
+ import type { Operator } from "opendal";
2
+ /** Bytes from `offset`, `length` of them or up to the end. */
3
+ export type OpendalByteRange = {
4
+ /** The first byte, from 0. */
5
+ readonly offset: bigint;
6
+ /** How many bytes; the rest of the object when absent. */
7
+ readonly length?: bigint | null;
8
+ };
9
+ export type OpendalReadableStreamOptions = {
10
+ /**
11
+ * Read these bytes only. The part of the range past the end of the object is
12
+ * not read, as `Blob.slice` would not, so a range starting at or past the end
13
+ * gives an empty stream.
14
+ */
15
+ readonly range?: OpendalByteRange | null;
16
+ /**
17
+ * Bytes asked of OpenDAL per read, a positive safe integer. Default 256 KiB.
18
+ * A BYOB reader's view, when smaller, bounds a read instead.
19
+ */
20
+ readonly chunkSize?: number | null;
21
+ /** Read this version of the object, where the service keeps versions. */
22
+ readonly version?: string | null;
23
+ /** Aborting errors the stream with the signal's reason. */
24
+ readonly signal?: AbortSignal | null;
25
+ };
26
+ /**
27
+ * Reads an object through an OpenDAL operator as a `ReadableStream` of bytes.
28
+ *
29
+ * It is a byte stream (`type: "bytes"`): a BYOB reader (`getReader({ mode:
30
+ * "byob" })`) has OpenDAL read straight into its own buffer, and a default
31
+ * reader receives a new array of up to `chunkSize` bytes a read. Nothing is
32
+ * read before the first read, and one OpenDAL read at most runs at a time.
33
+ *
34
+ * Without `range`, one OpenDAL `Reader` reads the object from its start. With
35
+ * `range`, the object is `stat`ed first (it must be a file of known size), then
36
+ * read by ranged requests of `chunkSize`, each pinned to the version or ETag
37
+ * the `stat` returned where the service supports it, so that an object replaced
38
+ * while it is read fails the read (`ConditionNotMatch`) rather than mixing two
39
+ * objects' bytes. A ranged request returning fewer bytes than asked errors the
40
+ * stream too.
41
+ *
42
+ * Errors are OpenDAL's own, so {@link parseOpendalError} classifies them: a
43
+ * missing object errors the first read with `NotFound`. Aborting `signal` or
44
+ * cancelling the stream stops it at once; a native read already running
45
+ * finishes in the background and its bytes are dropped.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const operator = new Operator("s3", { bucket: "media", region: "eu-west-3" });
50
+ * const response = new Response(
51
+ * opendalReadableStream(operator, "videos/talk.mp4", {
52
+ * range: { offset: 0n, length: 1_048_576n },
53
+ * }),
54
+ * );
55
+ * ```;
56
+ *
57
+ * @param operator The operator to read through.
58
+ * @param path The object's path, relative to the operator's root.
59
+ * @param options The range, chunk size, version and signal.
60
+ * @returns The stream; it opens nothing until read.
61
+ * @throws {RangeError} When `chunkSize` is not a positive safe integer, or the
62
+ * range has a negative bound.
63
+ */
64
+ export declare function opendalReadableStream(operator: Operator, path: string, options?: OpendalReadableStreamOptions): ReadableStream<Uint8Array<ArrayBuffer>>;
65
+ //# sourceMappingURL=opendal-readable-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opendal-readable-stream.d.ts","sourceRoot":"","sources":["../src/opendal-readable-stream.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAuB,MAAM,SAAS,CAAC;AAE7D,8DAA8D;AAC9D,MAAM,MAAM,gBAAgB,GAAG;IAC9B,8BAA8B;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACzC;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,yEAAyE;IACzE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,2DAA2D;IAC3D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;CACrC,CAAC;AA2BF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,4BAA4B,GACpC,cAAc,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CA0IzC"}
@@ -0,0 +1,174 @@
1
+ import { addAbortListener } from "node:events";
2
+ import { BYTES_PER_KIB } from "@ac-kit/core";
3
+ import { bufferView } from "@ac-kit/node";
4
+ const DEFAULT_CHUNK_SIZE_ = 256 * BYTES_PER_KIB;
5
+ /**
6
+ * Pins the ranged reads of a stream to the object `stat` found: its version
7
+ * where the service reads by version, otherwise its ETag where it reads under
8
+ * `If-Match`, otherwise nothing (a service such as `fs` that offers neither).
9
+ */
10
+ function pinOf_(operator, version, etag) {
11
+ const capability = operator.capability();
12
+ if (version !== null && capability.readWithVersion) {
13
+ return { version };
14
+ }
15
+ if (etag !== null && capability.readWithIfMatch) {
16
+ return { ifMatch: etag };
17
+ }
18
+ return {};
19
+ }
20
+ /**
21
+ * Reads an object through an OpenDAL operator as a `ReadableStream` of bytes.
22
+ *
23
+ * It is a byte stream (`type: "bytes"`): a BYOB reader (`getReader({ mode:
24
+ * "byob" })`) has OpenDAL read straight into its own buffer, and a default
25
+ * reader receives a new array of up to `chunkSize` bytes a read. Nothing is
26
+ * read before the first read, and one OpenDAL read at most runs at a time.
27
+ *
28
+ * Without `range`, one OpenDAL `Reader` reads the object from its start. With
29
+ * `range`, the object is `stat`ed first (it must be a file of known size), then
30
+ * read by ranged requests of `chunkSize`, each pinned to the version or ETag
31
+ * the `stat` returned where the service supports it, so that an object replaced
32
+ * while it is read fails the read (`ConditionNotMatch`) rather than mixing two
33
+ * objects' bytes. A ranged request returning fewer bytes than asked errors the
34
+ * stream too.
35
+ *
36
+ * Errors are OpenDAL's own, so {@link parseOpendalError} classifies them: a
37
+ * missing object errors the first read with `NotFound`. Aborting `signal` or
38
+ * cancelling the stream stops it at once; a native read already running
39
+ * finishes in the background and its bytes are dropped.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const operator = new Operator("s3", { bucket: "media", region: "eu-west-3" });
44
+ * const response = new Response(
45
+ * opendalReadableStream(operator, "videos/talk.mp4", {
46
+ * range: { offset: 0n, length: 1_048_576n },
47
+ * }),
48
+ * );
49
+ * ```;
50
+ *
51
+ * @param operator The operator to read through.
52
+ * @param path The object's path, relative to the operator's root.
53
+ * @param options The range, chunk size, version and signal.
54
+ * @returns The stream; it opens nothing until read.
55
+ * @throws {RangeError} When `chunkSize` is not a positive safe integer, or the
56
+ * range has a negative bound.
57
+ */
58
+ export function opendalReadableStream(operator, path, options) {
59
+ const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE_;
60
+ if (!Number.isSafeInteger(chunkSize) || chunkSize < 1) {
61
+ throw new RangeError(`chunkSize must be a positive safe integer: ${chunkSize}`);
62
+ }
63
+ const range = options?.range ?? null;
64
+ if (range !== null &&
65
+ (range.offset < 0n ||
66
+ (range.length !== undefined &&
67
+ range.length !== null &&
68
+ range.length < 0n))) {
69
+ throw new RangeError("A byte range cannot have a negative bound");
70
+ }
71
+ const requestedVersion = options?.version ?? null;
72
+ const signal = options?.signal ?? null;
73
+ let stopped = false;
74
+ let abortListener;
75
+ let reader = null;
76
+ // Ranged reads only: the next offset, the bytes left and the pin.
77
+ let offset = range?.offset ?? 0n;
78
+ let remaining = null;
79
+ let pin = {};
80
+ const stop = () => {
81
+ stopped = true;
82
+ reader = null;
83
+ abortListener?.[Symbol.dispose]();
84
+ };
85
+ const openRange = async (selected) => {
86
+ const metadata = await operator.stat(path, requestedVersion === null ? undefined : { version: requestedVersion });
87
+ const size = metadata.contentLength;
88
+ if (!metadata.isFile() || size === null) {
89
+ throw new TypeError("A byte range can only be read from a file of known size");
90
+ }
91
+ const available = size > selected.offset ? size - selected.offset : 0n;
92
+ remaining =
93
+ selected.length !== undefined &&
94
+ selected.length !== null &&
95
+ selected.length < available
96
+ ? selected.length
97
+ : available;
98
+ pin =
99
+ requestedVersion === null
100
+ ? pinOf_(operator, metadata.version, metadata.etag)
101
+ : { version: requestedVersion };
102
+ };
103
+ const readInto = async (view) => {
104
+ if (range === null) {
105
+ reader ??= await operator.reader(path, requestedVersion === null ? undefined : { version: requestedVersion });
106
+ return Number(await reader.read(bufferView(view)));
107
+ }
108
+ if (remaining === null) {
109
+ await openRange(range);
110
+ }
111
+ const left = remaining;
112
+ if (left === 0n) {
113
+ return 0;
114
+ }
115
+ const wanted = BigInt(view.byteLength) < left ? BigInt(view.byteLength) : left;
116
+ const bytes = await operator.read(path, { ...pin, offset, size: wanted });
117
+ if (BigInt(bytes.byteLength) !== wanted) {
118
+ throw new Error(`Short ranged read: ${bytes.byteLength} of ${wanted} bytes at offset ${offset}`);
119
+ }
120
+ view.set(bytes);
121
+ offset += wanted;
122
+ remaining = left - wanted;
123
+ return bytes.byteLength;
124
+ };
125
+ return new ReadableStream({
126
+ type: "bytes",
127
+ autoAllocateChunkSize: chunkSize,
128
+ start(controller) {
129
+ if (signal === null) {
130
+ return;
131
+ }
132
+ if (signal.aborted) {
133
+ stop();
134
+ controller.error(signal.reason);
135
+ return;
136
+ }
137
+ abortListener = addAbortListener(signal, () => {
138
+ stop();
139
+ controller.error(signal.reason);
140
+ });
141
+ },
142
+ async pull(controller) {
143
+ // Set on every pull, since `autoAllocateChunkSize` is.
144
+ const request = controller.byobRequest;
145
+ const target = request.view;
146
+ const view = new Uint8Array(target.buffer, target.byteOffset, Math.min(target.byteLength, chunkSize));
147
+ let count;
148
+ try {
149
+ count = await readInto(view);
150
+ }
151
+ catch (error) {
152
+ if (stopped) {
153
+ return;
154
+ }
155
+ stop();
156
+ throw error;
157
+ }
158
+ if (stopped) {
159
+ return;
160
+ }
161
+ if (count === 0) {
162
+ stop();
163
+ controller.close();
164
+ request.respond(0);
165
+ return;
166
+ }
167
+ request.respond(count);
168
+ },
169
+ cancel() {
170
+ stop();
171
+ },
172
+ });
173
+ }
174
+ //# sourceMappingURL=opendal-readable-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opendal-readable-stream.js","sourceRoot":"","sources":["../src/opendal-readable-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,UAA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;gBACP,MAAM,KAAK,CAAC;YACb,CAAC;YACD,IAAI,OAAO,EAAE,CAAC;gBACb,OAAO;YACR,CAAC;YACD,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;gBACjB,IAAI,EAAE,CAAC;gBACP,UAAU,CAAC,KAAK,EAAE,CAAC;gBACnB,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBACnB,OAAO;YACR,CAAC;YACD,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;QACD,MAAM;YACL,IAAI,EAAE,CAAC;QACR,CAAC;KACD,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { Operator, WriteOptions } from "opendal";
2
+ export type OpendalWritableStreamOptions = {
3
+ /**
4
+ * OpenDAL's own write options, passed as given: content type, user metadata,
5
+ * `ifNotExists`, `append`, `chunk` (the part size of a multipart upload),
6
+ * `concurrent`.
7
+ */
8
+ readonly write?: WriteOptions | null;
9
+ /** Aborting errors the stream with the signal's reason; nothing is committed. */
10
+ readonly signal?: AbortSignal | null;
11
+ };
12
+ /**
13
+ * Writes an object through an OpenDAL operator from a `WritableStream` of
14
+ * bytes.
15
+ *
16
+ * The object is committed when the stream closes, and only then: the first
17
+ * non-empty chunk opens an OpenDAL `Writer`, each chunk is written as it comes
18
+ * (without a copy on this side; do not change a chunk before its write settles,
19
+ * as with any sink), and closing closes the writer. A stream closed without
20
+ * bytes writes an empty object. A write that fails, an aborted stream or an
21
+ * aborted `signal` never closes the writer, so nothing is committed; an upload
22
+ * a service started (an S3 multipart upload) is left for the bucket's lifecycle
23
+ * rules, since the binding has no way to abort it.
24
+ *
25
+ * Errors are OpenDAL's own, so {@link parseOpendalError} classifies them: an
26
+ * `ifNotExists` write onto an existing object fails with `ConditionNotMatch`.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const response = await fetch(sourceUrl);
31
+ * await response.body?.pipeTo(
32
+ * opendalWritableStream(operator, "videos/talk.mp4", {
33
+ * write: { contentType: "video/mp4", ifNotExists: true },
34
+ * }),
35
+ * );
36
+ * ```;
37
+ *
38
+ * @param operator The operator to write through.
39
+ * @param path The object's path, relative to the operator's root.
40
+ * @param options OpenDAL's write options and a signal.
41
+ * @returns The stream; it opens nothing until written to or closed.
42
+ */
43
+ export declare function opendalWritableStream(operator: Operator, path: string, options?: OpendalWritableStreamOptions): WritableStream<Uint8Array>;
44
+ //# sourceMappingURL=opendal-writable-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opendal-writable-stream.d.ts","sourceRoot":"","sources":["../src/opendal-writable-stream.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAU,MAAM,SAAS,CAAC;AAE9D,MAAM,MAAM,4BAA4B,GAAG;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;IACrC,iFAAiF;IACjF,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;CACrC,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,4BAA4B,GACpC,cAAc,CAAC,UAAU,CAAC,CAqD5B"}
@@ -0,0 +1,90 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { addAbortListener } from "node:events";
3
+ import { bufferView } from "@ac-kit/node";
4
+ const EMPTY_ = Buffer.alloc(0);
5
+ /**
6
+ * Writes an object through an OpenDAL operator from a `WritableStream` of
7
+ * bytes.
8
+ *
9
+ * The object is committed when the stream closes, and only then: the first
10
+ * non-empty chunk opens an OpenDAL `Writer`, each chunk is written as it comes
11
+ * (without a copy on this side; do not change a chunk before its write settles,
12
+ * as with any sink), and closing closes the writer. A stream closed without
13
+ * bytes writes an empty object. A write that fails, an aborted stream or an
14
+ * aborted `signal` never closes the writer, so nothing is committed; an upload
15
+ * a service started (an S3 multipart upload) is left for the bucket's lifecycle
16
+ * rules, since the binding has no way to abort it.
17
+ *
18
+ * Errors are OpenDAL's own, so {@link parseOpendalError} classifies them: an
19
+ * `ifNotExists` write onto an existing object fails with `ConditionNotMatch`.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * const response = await fetch(sourceUrl);
24
+ * await response.body?.pipeTo(
25
+ * opendalWritableStream(operator, "videos/talk.mp4", {
26
+ * write: { contentType: "video/mp4", ifNotExists: true },
27
+ * }),
28
+ * );
29
+ * ```;
30
+ *
31
+ * @param operator The operator to write through.
32
+ * @param path The object's path, relative to the operator's root.
33
+ * @param options OpenDAL's write options and a signal.
34
+ * @returns The stream; it opens nothing until written to or closed.
35
+ */
36
+ export function opendalWritableStream(operator, path, options) {
37
+ const writeOptions = options?.write ?? undefined;
38
+ const signal = options?.signal ?? null;
39
+ let writer = null;
40
+ let abortListener;
41
+ const release = () => {
42
+ writer = null;
43
+ abortListener?.[Symbol.dispose]();
44
+ };
45
+ return new WritableStream({
46
+ start(controller) {
47
+ if (signal === null) {
48
+ return;
49
+ }
50
+ if (signal.aborted) {
51
+ controller.error(signal.reason);
52
+ return;
53
+ }
54
+ abortListener = addAbortListener(signal, () => {
55
+ release();
56
+ controller.error(signal.reason);
57
+ });
58
+ },
59
+ async write(chunk) {
60
+ signal?.throwIfAborted();
61
+ if (chunk.byteLength === 0) {
62
+ return;
63
+ }
64
+ try {
65
+ writer ??= await operator.writer(path, writeOptions);
66
+ signal?.throwIfAborted();
67
+ await writer.write(bufferView(chunk));
68
+ }
69
+ catch (error) {
70
+ release();
71
+ throw error;
72
+ }
73
+ },
74
+ async close() {
75
+ signal?.throwIfAborted();
76
+ const opened = writer;
77
+ release();
78
+ if (opened === null) {
79
+ await operator.write(path, EMPTY_, writeOptions);
80
+ }
81
+ else {
82
+ await opened.close();
83
+ }
84
+ },
85
+ abort() {
86
+ release();
87
+ },
88
+ });
89
+ }
90
+ //# sourceMappingURL=opendal-writable-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opendal-writable-stream.js","sourceRoot":"","sources":["../src/opendal-writable-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAc1C,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,UAAU,qBAAqB,CACpC,QAAkB,EAClB,IAAY,EACZ,OAAsC;IAEtC,MAAM,YAAY,GAAG,OAAO,EAAE,KAAK,IAAI,SAAS,CAAC;IACjD,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,IAAI,IAAI,CAAC;IACvC,IAAI,MAAM,GAAkB,IAAI,CAAC;IACjC,IAAI,aAAqC,CAAC;IAE1C,MAAM,OAAO,GAAG,GAAS,EAAE;QAC1B,MAAM,GAAG,IAAI,CAAC;QACd,aAAa,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;IACnC,CAAC,CAAC;IAEF,OAAO,IAAI,cAAc,CAAa;QACrC,KAAK,CAAC,UAAU;YACf,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;gBACrB,OAAO;YACR,CAAC;YACD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;gBACpB,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBAChC,OAAO;YACR,CAAC;YACD,aAAa,GAAG,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE;gBAC7C,OAAO,EAAE,CAAC;gBACV,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,CAAC,CAAC,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,KAAK;YAChB,MAAM,EAAE,cAAc,EAAE,CAAC;YACzB,IAAI,KAAK,CAAC,UAAU,KAAK,CAAC,EAAE,CAAC;gBAC5B,OAAO;YACR,CAAC;YACD,IAAI,CAAC;gBACJ,MAAM,KAAK,MAAM,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;gBACrD,MAAM,EAAE,cAAc,EAAE,CAAC;gBACzB,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YACvC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,OAAO,EAAE,CAAC;gBACV,MAAM,KAAK,CAAC;YACb,CAAC;QACF,CAAC;QACD,KAAK,CAAC,KAAK;YACV,MAAM,EAAE,cAAc,EAAE,CAAC;YACzB,MAAM,MAAM,GAAG,MAAM,CAAC;YACtB,OAAO,EAAE,CAAC;YACV,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;gBACrB,MAAM,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC;YAClD,CAAC;iBAAM,CAAC;gBACP,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;YACtB,CAAC;QACF,CAAC;QACD,KAAK;YACJ,OAAO,EAAE,CAAC;QACX,CAAC;KACD,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@ac-kit/storage-opendal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Apache OpenDAL for Node.js: its errors classified by kind and status, and objects read and written as Web Streams with byte ranges pinned to one version.",
5
+ "keywords": [
6
+ "azure-blob",
7
+ "gcs",
8
+ "object-storage",
9
+ "opendal",
10
+ "s3",
11
+ "storage",
12
+ "web-streams"
13
+ ],
14
+ "homepage": "https://anthochamp.pages.grenadine.io/node-essentials/api/storage-opendal/",
15
+ "bugs": {
16
+ "url": "https://git.grenadine.io/anthochamp/node-essentials/issues"
17
+ },
18
+ "license": "BSD-3-Clause",
19
+ "author": "Anthony Champagne <dev@anthonychampagne.fr>",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://git.grenadine.io/anthochamp/node-essentials.git",
23
+ "directory": "packages/storage-opendal"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "type": "module",
29
+ "sideEffects": false,
30
+ "main": "./dist/index.js",
31
+ "exports": {
32
+ ".": "./dist/index.js"
33
+ },
34
+ "publishConfig": {
35
+ "main": "./dist/index.js",
36
+ "exports": {
37
+ ".": "./dist/index.js"
38
+ },
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "compile": "tsc -p ./tsconfig.build.json -outDir dist",
43
+ "compile:check": "tsc -noEmit -p ./tsconfig.json",
44
+ "clean": "rimraf dist",
45
+ "build": "yarn clean && yarn compile",
46
+ "test": "yarn run -T vitest run",
47
+ "prepack": "yarn build"
48
+ },
49
+ "dependencies": {
50
+ "@ac-kit/core": "^0.13.0",
51
+ "@ac-kit/node": "^0.12.0"
52
+ },
53
+ "devDependencies": {
54
+ "@ac-kit/math-random": "0.4.1",
55
+ "@ac-kit/tsconfig": "0.1.0",
56
+ "@ac-kit/typedoc-config": "0.1.0",
57
+ "@ac-kit/vitest-config": "0.2.0",
58
+ "@types/node": "26.6.11",
59
+ "@typescript/native": "typescript@7.0.2",
60
+ "opendal": "0.49.13",
61
+ "rimraf": "6.1.4",
62
+ "typedoc": "0.28.20",
63
+ "typescript": "@typescript/typescript6@6.0.2"
64
+ },
65
+ "peerDependencies": {
66
+ "opendal": ">=0.49.13 <0.50.0"
67
+ },
68
+ "engines": {
69
+ "node": ">=24"
70
+ }
6
71
  }