@cloudbitmaps/core 0.1.0-rc.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.
Files changed (76) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +22 -0
  4. package/dist/azure/index.cjs +368 -0
  5. package/dist/azure/index.cjs.map +1 -0
  6. package/dist/azure/index.d.cts +48 -0
  7. package/dist/azure/index.d.ts +48 -0
  8. package/dist/azure/index.js +304 -0
  9. package/dist/azure/index.js.map +1 -0
  10. package/dist/cassandra/index.cjs +265 -0
  11. package/dist/cassandra/index.cjs.map +1 -0
  12. package/dist/cassandra/index.d.cts +52 -0
  13. package/dist/cassandra/index.d.ts +52 -0
  14. package/dist/cassandra/index.js +204 -0
  15. package/dist/cassandra/index.js.map +1 -0
  16. package/dist/chunk-2YDULGXS.js +203 -0
  17. package/dist/chunk-2YDULGXS.js.map +1 -0
  18. package/dist/chunk-7LMLYSVJ.js +43 -0
  19. package/dist/chunk-7LMLYSVJ.js.map +1 -0
  20. package/dist/chunk-AS6ODRLT.js +6 -0
  21. package/dist/chunk-AS6ODRLT.js.map +1 -0
  22. package/dist/chunk-NUIDEEFZ.js +91 -0
  23. package/dist/chunk-NUIDEEFZ.js.map +1 -0
  24. package/dist/chunk-SNJVZ227.js +35 -0
  25. package/dist/chunk-SNJVZ227.js.map +1 -0
  26. package/dist/dynamodb/index.cjs +731 -0
  27. package/dist/dynamodb/index.cjs.map +1 -0
  28. package/dist/dynamodb/index.d.cts +106 -0
  29. package/dist/dynamodb/index.d.ts +106 -0
  30. package/dist/dynamodb/index.js +460 -0
  31. package/dist/dynamodb/index.js.map +1 -0
  32. package/dist/gcs/index.cjs +343 -0
  33. package/dist/gcs/index.cjs.map +1 -0
  34. package/dist/gcs/index.d.cts +46 -0
  35. package/dist/gcs/index.d.ts +46 -0
  36. package/dist/gcs/index.js +279 -0
  37. package/dist/gcs/index.js.map +1 -0
  38. package/dist/index.cjs +4031 -0
  39. package/dist/index.cjs.map +1 -0
  40. package/dist/index.d.cts +1945 -0
  41. package/dist/index.d.ts +1945 -0
  42. package/dist/index.js +3642 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/mongodb/index.cjs +260 -0
  45. package/dist/mongodb/index.cjs.map +1 -0
  46. package/dist/mongodb/index.d.cts +45 -0
  47. package/dist/mongodb/index.d.ts +45 -0
  48. package/dist/mongodb/index.js +199 -0
  49. package/dist/mongodb/index.js.map +1 -0
  50. package/dist/mysql/index.cjs +281 -0
  51. package/dist/mysql/index.cjs.map +1 -0
  52. package/dist/mysql/index.d.cts +56 -0
  53. package/dist/mysql/index.d.ts +56 -0
  54. package/dist/mysql/index.js +211 -0
  55. package/dist/mysql/index.js.map +1 -0
  56. package/dist/ports-D3BrJ6ax.d.cts +357 -0
  57. package/dist/ports-D3BrJ6ax.d.ts +357 -0
  58. package/dist/postgres/index.cjs +273 -0
  59. package/dist/postgres/index.cjs.map +1 -0
  60. package/dist/postgres/index.d.cts +54 -0
  61. package/dist/postgres/index.d.ts +54 -0
  62. package/dist/postgres/index.js +203 -0
  63. package/dist/postgres/index.js.map +1 -0
  64. package/dist/redis/index.cjs +257 -0
  65. package/dist/redis/index.cjs.map +1 -0
  66. package/dist/redis/index.d.cts +42 -0
  67. package/dist/redis/index.d.ts +42 -0
  68. package/dist/redis/index.js +197 -0
  69. package/dist/redis/index.js.map +1 -0
  70. package/dist/s3/index.cjs +891 -0
  71. package/dist/s3/index.cjs.map +1 -0
  72. package/dist/s3/index.d.cts +112 -0
  73. package/dist/s3/index.d.ts +112 -0
  74. package/dist/s3/index.js +555 -0
  75. package/dist/s3/index.js.map +1 -0
  76. package/package.json +172 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ CloudRoaring
2
+ Copyright 2026 Sharvil Kadam
3
+
4
+ This product includes software developed as an open-source project.
5
+ Licensed under the Apache License, Version 2.0 (the "License"); see the LICENSE
6
+ file. You may obtain a copy of the License at:
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ CloudRoaring builds on the Roaring Bitmap data structure and is designed to use
11
+ the CRoaring engine (via the `roaring` Node.js binding) for in-memory bit math.
12
+ Those projects are independent works under their own licenses.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @cloudbitmaps/core
2
+
3
+ The **codec-agnostic cloud engine** behind the [CloudBitmaps](https://github.com/cloudbitmaps/cloudbitmaps) family:
4
+ tiered storage (HOT RAM → WARM key/value deltas → COLD immutable `.crbm` objects), serverless chunk-skipping
5
+ intersection, the segment registry, crash-safe 2-phase-commit compaction, encryption-at-rest + crypto-shred, and
6
+ **every storage driver** (S3 · GCS · Azure Blob · DynamoDB · PostgreSQL · Redis · MongoDB · Cassandra/ScyllaDB ·
7
+ MySQL/MariaDB, each on its own subpath with the backend SDK as an optional peer dependency).
8
+
9
+ ## You probably want a flavor, not this package
10
+
11
+ This package holds no bitmap codec — that lives in a *flavor* package which depends on this one and supplies it
12
+ through the `CodecInterface` seam. Install the flavor; `@cloudbitmaps/core` arrives **transitively**:
13
+
14
+ ```bash
15
+ npm i @cloudbitmaps/roaring # the roaring flavor (flagship)
16
+ ```
17
+
18
+ Depend on `@cloudbitmaps/core` directly only to **author a flavor or a driver**. It has **zero runtime
19
+ dependencies** of its own.
20
+
21
+ Full docs, guides, and the design corpus live in the
22
+ [repository](https://github.com/cloudbitmaps/cloudbitmaps). Licensed Apache-2.0.
@@ -0,0 +1,368 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+
5
+ // src/drivers/azure/cold.ts
6
+
7
+ // src/core/errors.ts
8
+ var ERROR_BRAND = /* @__PURE__ */ Symbol.for("cloud-roaring.error");
9
+ var TRANSIENT_BRAND = /* @__PURE__ */ Symbol.for("cloud-roaring.error.transient");
10
+ var CloudRoaringError = class extends Error {
11
+ /** Cross-bundle brand — see the predicates ({@link isCloudRoaringError}, …). Non-enumerable-ish (symbol key ⇒ not in JSON). */
12
+ [ERROR_BRAND] = true;
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = new.target.name;
16
+ }
17
+ };
18
+ var ValidationError = class extends CloudRoaringError {
19
+ };
20
+ var WriteConflictError = class extends CloudRoaringError {
21
+ };
22
+ var NotFoundError = class extends CloudRoaringError {
23
+ };
24
+ var TransientError = class extends CloudRoaringError {
25
+ /** A second brand so the whole transient subtree (incl. {@link TimeoutError}) is classifiable cross-bundle. */
26
+ [TRANSIENT_BRAND] = true;
27
+ constructor(message, options) {
28
+ super(message);
29
+ if (options && "cause" in options) this.cause = options.cause;
30
+ }
31
+ };
32
+ function hasBrand(err, brand) {
33
+ return typeof err === "object" && err !== null && err[brand] === true;
34
+ }
35
+ function isCloudRoaringError(err) {
36
+ return hasBrand(err, ERROR_BRAND);
37
+ }
38
+ function isWriteConflictError(err) {
39
+ return isCloudRoaringError(err) && err.name === "WriteConflictError";
40
+ }
41
+ function isNotFoundError(err) {
42
+ return isCloudRoaringError(err) && err.name === "NotFoundError";
43
+ }
44
+ function isValidationError(err) {
45
+ return isCloudRoaringError(err) && err.name === "ValidationError";
46
+ }
47
+
48
+ // src/core/validate.ts
49
+ var NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
50
+ function validatePart(value, field) {
51
+ if (typeof value !== "string" || !NAME.test(value) || value.includes("..")) {
52
+ throw new ValidationError(
53
+ `${field} must match ${String(NAME)} and contain no "..": got ${JSON.stringify(value)}`
54
+ );
55
+ }
56
+ }
57
+ function validateSegmentRef(ref) {
58
+ validatePart(ref.segment, "segment");
59
+ if (ref.namespace !== void 0) validatePart(ref.namespace, "namespace");
60
+ }
61
+
62
+ // src/drivers/_shared/keys.ts
63
+ var DEFAULT_NAMESPACE = "_default";
64
+ function namespacePart(namespace) {
65
+ return namespace ?? DEFAULT_NAMESPACE;
66
+ }
67
+
68
+ // src/drivers/azure/keys.ts
69
+ var SUFFIX = ".crbm";
70
+ function prefixPart(prefix) {
71
+ if (prefix === void 0) return "";
72
+ const trimmed = prefix.replace(/^\/+|\/+$/g, "");
73
+ return trimmed === "" ? "" : `${trimmed}/`;
74
+ }
75
+ function normalizeAzurePrefix(prefix) {
76
+ if (prefix === void 0) return void 0;
77
+ for (const ch of prefix) {
78
+ if (ch.charCodeAt(0) < 32) {
79
+ throw new ValidationError("prefix must not contain control characters");
80
+ }
81
+ }
82
+ for (const segment of prefix.split("/")) {
83
+ if (segment === "." || segment === "..") {
84
+ throw new ValidationError(
85
+ `prefix must not contain "." or ".." path segments: ${JSON.stringify(prefix)}`
86
+ );
87
+ }
88
+ }
89
+ return prefix;
90
+ }
91
+ function segmentObjectPrefix(prefix, ref) {
92
+ validateSegmentRef(ref);
93
+ return `${prefixPart(prefix)}${namespacePart(ref.namespace)}/segments/${ref.segment}.`;
94
+ }
95
+ function coldObjectName(prefix, key) {
96
+ if (!Number.isInteger(key.generation) || key.generation < 0) {
97
+ throw new ValidationError(`generation must be a non-negative integer; got ${key.generation}`);
98
+ }
99
+ return `${segmentObjectPrefix(prefix, key)}${key.generation}${SUFFIX}`;
100
+ }
101
+ function parseGenerationFromName(segmentPrefix, objectName) {
102
+ if (!objectName.startsWith(segmentPrefix) || !objectName.endsWith(SUFFIX)) return null;
103
+ const middle = objectName.slice(segmentPrefix.length, objectName.length - SUFFIX.length);
104
+ if (!/^(0|[1-9]\d*)$/.test(middle)) return null;
105
+ const generation = Number(middle);
106
+ return Number.isSafeInteger(generation) ? generation : null;
107
+ }
108
+
109
+ // src/drivers/azure/azure-errors.ts
110
+ function httpStatus(err) {
111
+ const code = err?.statusCode;
112
+ return typeof code === "number" ? code : void 0;
113
+ }
114
+ function azureCode(err) {
115
+ const e = err;
116
+ if (typeof e?.code === "string") return e.code;
117
+ if (typeof e?.details?.errorCode === "string") return e.details.errorCode;
118
+ return void 0;
119
+ }
120
+ function networkCode(err) {
121
+ const code = err?.code;
122
+ return typeof code === "string" ? code : void 0;
123
+ }
124
+ function isConditionalConflict(err) {
125
+ const status = httpStatus(err);
126
+ if (status === 409 || status === 412) return true;
127
+ const code = azureCode(err);
128
+ return code === "BlobAlreadyExists" || code === "ConditionNotMet";
129
+ }
130
+ function isNotFound(err) {
131
+ return httpStatus(err) === 404 || azureCode(err) === "BlobNotFound";
132
+ }
133
+ function isInvalidRange(err) {
134
+ return httpStatus(err) === 416 || azureCode(err) === "InvalidRange";
135
+ }
136
+ function isTransient(err) {
137
+ if (isConditionalConflict(err) || isNotFound(err) || isInvalidRange(err)) return false;
138
+ const status = httpStatus(err);
139
+ if (status === 429 || status !== void 0 && status >= 500 && status < 600) return true;
140
+ const code = azureCode(err);
141
+ if (code === "ServerBusy" || code === "OperationTimedOut" || code === "InternalError")
142
+ return true;
143
+ const net = networkCode(err);
144
+ return net === "ECONNRESET" || net === "ECONNABORTED" || net === "ETIMEDOUT" || net === "ESOCKETTIMEDOUT" || net === "ECONNREFUSED" || net === "EHOSTUNREACH" || net === "ENETUNREACH" || net === "EPIPE" || net === "EAI_AGAIN" || net === "ENOTFOUND";
145
+ }
146
+
147
+ // src/drivers/azure/cold.ts
148
+ var AZURE_BLOCK_BYTES = 8 * 1024 * 1024;
149
+ var AZURE_MAX_BLOCKS = 5e4;
150
+ var OCTET_STREAM = { blobContentType: "application/octet-stream" };
151
+ var IF_ABSENT = { conditions: { ifNoneMatch: "*" }, blobHTTPHeaders: OCTET_STREAM };
152
+ var AzureBlobColdDriver = class {
153
+ container;
154
+ prefix;
155
+ maxObjectBytes;
156
+ blockBytes;
157
+ constructor(options) {
158
+ this.container = options.containerClient;
159
+ this.prefix = normalizeAzurePrefix(options.prefix);
160
+ const requestedBlock = options.blockBytes ?? AZURE_BLOCK_BYTES;
161
+ if (!Number.isSafeInteger(requestedBlock) || requestedBlock < 1) {
162
+ throw new ValidationError(
163
+ `blockBytes must be a positive safe integer; got ${requestedBlock}`
164
+ );
165
+ }
166
+ if (options.maxObjectBytes !== void 0 && (!Number.isSafeInteger(options.maxObjectBytes) || options.maxObjectBytes < 1)) {
167
+ throw new ValidationError(
168
+ `maxObjectBytes must be a positive safe integer; got ${options.maxObjectBytes}`
169
+ );
170
+ }
171
+ this.maxObjectBytes = options.maxObjectBytes ?? requestedBlock * AZURE_MAX_BLOCKS;
172
+ this.blockBytes = Math.max(requestedBlock, Math.ceil(this.maxObjectBytes / AZURE_MAX_BLOCKS));
173
+ }
174
+ capabilities() {
175
+ return { rangeRead: true, maxObjectBytes: this.maxObjectBytes, conditionalPut: true };
176
+ }
177
+ blob(name) {
178
+ return this.container.getBlockBlobClient(name);
179
+ }
180
+ async putImmutable(key, write) {
181
+ const objectName = coldObjectName(this.prefix, key);
182
+ const sink = new AzureBlockBlobSink(
183
+ this.blob(objectName),
184
+ this.blockBytes,
185
+ this.maxObjectBytes
186
+ );
187
+ try {
188
+ await write(sink);
189
+ return await sink.finish();
190
+ } catch (err) {
191
+ if (isConditionalConflict(err)) {
192
+ throw new WriteConflictError(
193
+ `generation already exists (write-once): ${key.segment}.${key.generation}`
194
+ );
195
+ }
196
+ if (isValidationError(err) || isWriteConflictError(err) || isNotFoundError(err)) throw err;
197
+ throw this.mapError(err);
198
+ }
199
+ }
200
+ async getRange(key, offset, length) {
201
+ if (!Number.isInteger(offset) || !Number.isInteger(length) || offset < 0 || length < 0) {
202
+ throw new ValidationError(`invalid range offset=${offset} length=${length}`);
203
+ }
204
+ if (length === 0) return new Uint8Array(0);
205
+ const objectName = coldObjectName(this.prefix, key);
206
+ try {
207
+ const res = await this.blob(objectName).download(offset, length);
208
+ const bytes = await collect(res.readableStreamBody);
209
+ if (bytes.length !== length) {
210
+ throw new ValidationError(
211
+ `range [${offset}, ${offset + length}) out of bounds (got ${bytes.length}B)`
212
+ );
213
+ }
214
+ return bytes;
215
+ } catch (err) {
216
+ throw this.mapReadError(err, key);
217
+ }
218
+ }
219
+ async getTail(key, maxBytes) {
220
+ const objectName = coldObjectName(this.prefix, key);
221
+ try {
222
+ const props = await this.blob(objectName).getProperties();
223
+ const size = props.contentLength ?? 0;
224
+ if (!Number.isSafeInteger(size) || size < 0) {
225
+ throw new ValidationError(`Azure returned an invalid blob size: ${String(size)}`);
226
+ }
227
+ if (maxBytes <= 0 || size === 0) return { bytes: new Uint8Array(0), size };
228
+ const take = Math.min(maxBytes, size);
229
+ const res = await this.blob(objectName).download(size - take, take);
230
+ return { bytes: await collect(res.readableStreamBody), size };
231
+ } catch (err) {
232
+ throw this.mapReadError(err, key);
233
+ }
234
+ }
235
+ async delete(key) {
236
+ try {
237
+ await this.blob(coldObjectName(this.prefix, key)).deleteIfExists();
238
+ } catch (err) {
239
+ throw this.mapError(err);
240
+ }
241
+ }
242
+ async *list(ref) {
243
+ const prefix = segmentObjectPrefix(this.prefix, ref);
244
+ try {
245
+ for await (const item of this.container.listBlobsFlat({ prefix })) {
246
+ const generation = parseGenerationFromName(prefix, item.name);
247
+ if (generation !== null) {
248
+ yield { namespace: ref.namespace, segment: ref.segment, generation };
249
+ }
250
+ }
251
+ } catch (err) {
252
+ throw this.mapError(err);
253
+ }
254
+ }
255
+ /** Map Azure read errors to the driver vocabulary; pass everything else through {@link mapError}. */
256
+ mapReadError(err, key) {
257
+ if (isValidationError(err)) return err;
258
+ if (isNotFound(err))
259
+ return new NotFoundError(`no such generation: ${key.segment}.${key.generation}`);
260
+ if (isInvalidRange(err)) {
261
+ return new ValidationError(`range out of bounds for ${key.segment}.${key.generation}`);
262
+ }
263
+ return this.mapError(err);
264
+ }
265
+ /**
266
+ * Reclassify a transient Azure fault (throttle/5xx/dropped connection) as a retryable {@link TransientError}
267
+ * so the retry decorator can ride it out; everything else propagates unchanged. The final fallback at every
268
+ * client-call site, so callers + the decorator only ever see typed errors.
269
+ */
270
+ mapError(err) {
271
+ if (isTransient(err)) {
272
+ return new TransientError(
273
+ `transient Azure fault: ${err?.code ?? "unknown"}`,
274
+ { cause: err }
275
+ );
276
+ }
277
+ return err;
278
+ }
279
+ };
280
+ function concatBytes(parts, total) {
281
+ const out = new Uint8Array(total);
282
+ let offset = 0;
283
+ for (const p of parts) {
284
+ out.set(p, offset);
285
+ offset += p.length;
286
+ }
287
+ return out;
288
+ }
289
+ var AzureBlockBlobSink = class {
290
+ constructor(blob, blockBytes, maxObjectBytes) {
291
+ this.blob = blob;
292
+ this.blockBytes = blockBytes;
293
+ this.maxObjectBytes = maxObjectBytes;
294
+ }
295
+ blob;
296
+ blockBytes;
297
+ maxObjectBytes;
298
+ hash = crypto.createHash("sha256");
299
+ pending = [];
300
+ pendingLen = 0;
301
+ total = 0;
302
+ blockIds = [];
303
+ /**
304
+ * A random per-sink nonce folded into every block id. Azure pools **uncommitted** blocks per *blob name*,
305
+ * keyed by id — so two writers racing the same generation key on the staged path MUST use disjoint id spaces,
306
+ * else one would overwrite the other's staged blocks and a commit could reference an interleaved mix of both
307
+ * writers' bytes (a corrupt blob whose committed content wouldn't match the returned SHA-256). A per-instance
308
+ * nonce makes each writer's ids unique, so the winner commits only its own blocks and the loser cleanly 409s.
309
+ * 6 random bytes → 12 fixed hex chars, keeping every id equal-length (Azure's within-blob id requirement).
310
+ */
311
+ uploadNonce = crypto.randomBytes(6).toString("hex");
312
+ /** Fixed-width (constant length within a blob) AND per-sink-unique block id: `<nonce>-<zero-padded index>`. */
313
+ blockId(n) {
314
+ return Buffer.from(`${this.uploadNonce}-${String(n).padStart(6, "0")}`).toString("base64");
315
+ }
316
+ async write(bytes) {
317
+ if (bytes.length === 0) return;
318
+ this.total += bytes.length;
319
+ if (this.total > this.maxObjectBytes) {
320
+ throw new ValidationError(`object exceeds maxObjectBytes ${this.maxObjectBytes}`);
321
+ }
322
+ this.hash.update(bytes);
323
+ this.pending.push(new Uint8Array(bytes));
324
+ this.pendingLen += bytes.length;
325
+ if (this.pendingLen >= this.blockBytes) await this.flushBlock();
326
+ }
327
+ /** Stage the buffered bytes (≥ one block) as a single block, freeing them. */
328
+ async flushBlock() {
329
+ if (this.blockIds.length >= AZURE_MAX_BLOCKS) {
330
+ throw new ValidationError(`upload exceeded the Azure ${AZURE_MAX_BLOCKS}-block limit`);
331
+ }
332
+ const body = concatBytes(this.pending, this.pendingLen);
333
+ this.pending.length = 0;
334
+ this.pendingLen = 0;
335
+ const id = this.blockId(this.blockIds.length);
336
+ await this.blob.stageBlock(id, body, body.length);
337
+ this.blockIds.push(id);
338
+ }
339
+ /** Commit the blob: a single conditional `upload` if it fit in one block, else commit the staged block list. */
340
+ async finish() {
341
+ const sha256 = this.hash.digest("hex");
342
+ if (this.blockIds.length === 0) {
343
+ const body = concatBytes(this.pending, this.pendingLen);
344
+ await this.blob.upload(body, body.length, IF_ABSENT);
345
+ return { size: this.total, sha256 };
346
+ }
347
+ if (this.pendingLen > 0) await this.flushBlock();
348
+ await this.blob.commitBlockList(this.blockIds, IF_ABSENT);
349
+ return { size: this.total, sha256 };
350
+ }
351
+ };
352
+ async function collect(body) {
353
+ if (body === void 0) {
354
+ throw new NotFoundError("Azure download returned no body");
355
+ }
356
+ const chunks = [];
357
+ let total = 0;
358
+ for await (const chunk of body) {
359
+ const u8 = typeof chunk === "string" ? new TextEncoder().encode(chunk) : new Uint8Array(chunk);
360
+ chunks.push(u8);
361
+ total += u8.length;
362
+ }
363
+ return concatBytes(chunks, total);
364
+ }
365
+
366
+ exports.AzureBlobColdDriver = AzureBlobColdDriver;
367
+ //# sourceMappingURL=index.cjs.map
368
+ //# sourceMappingURL=index.cjs.map