@lumeweb/sia-testing 0.0.0-stage → 0.0.2

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 (90) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +202 -2
  3. package/dist/esm/client.d.ts +8 -0
  4. package/dist/esm/client.js +6 -0
  5. package/dist/esm/http.d.ts +3 -0
  6. package/dist/esm/http.js +3 -0
  7. package/dist/esm/mock.d.ts +8 -0
  8. package/dist/esm/mock.js +7 -0
  9. package/dist/esm/model/index.js +509 -0
  10. package/dist/esm/model/state.js +188 -0
  11. package/dist/esm/msw.d.ts +2 -0
  12. package/dist/esm/msw.js +3 -0
  13. package/dist/esm/node.d.ts +4 -0
  14. package/dist/esm/node.js +4 -0
  15. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js +169 -0
  16. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js +12 -0
  17. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js +199 -0
  18. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js +220 -0
  19. package/dist/esm/sdk/abort.js +23 -0
  20. package/dist/esm/sdk/control.js +129 -0
  21. package/dist/esm/sdk/index.js +454 -0
  22. package/dist/esm/sdk/link.js +55 -0
  23. package/dist/esm/sdk/object.js +24 -0
  24. package/dist/esm/sdk/payload-store.d.ts +9 -0
  25. package/dist/esm/sdk/payload-store.js +67 -0
  26. package/dist/esm/sdk/state.js +74 -0
  27. package/dist/esm/testing/application-client.d.ts +8 -0
  28. package/dist/esm/testing/application-client.js +295 -0
  29. package/dist/esm/testing/application-metadata.js +17 -0
  30. package/dist/esm/testing/application-transport.js +363 -0
  31. package/dist/esm/testing/auth-client.d.ts +20 -0
  32. package/dist/esm/testing/auth-client.js +63 -0
  33. package/dist/esm/testing/authentication.js +48 -0
  34. package/dist/esm/testing/byte-view.js +28 -0
  35. package/dist/esm/testing/chunked-files.d.ts +12 -0
  36. package/dist/esm/testing/chunked-files.js +50 -0
  37. package/dist/esm/testing/client.d.ts +8 -0
  38. package/dist/esm/testing/client.js +105 -0
  39. package/dist/esm/testing/controls.d.ts +44 -0
  40. package/dist/esm/testing/controls.js +255 -0
  41. package/dist/esm/testing/diagnostics.js +55 -0
  42. package/dist/esm/testing/files.d.ts +9 -0
  43. package/dist/esm/testing/files.js +86 -0
  44. package/dist/esm/testing/http-body.js +33 -0
  45. package/dist/esm/testing/http.d.ts +14 -0
  46. package/dist/esm/testing/http.js +181 -0
  47. package/dist/esm/testing/live/agent.d.ts +1 -0
  48. package/dist/esm/testing/live/agent.js +211 -0
  49. package/dist/esm/testing/live/approval.js +42 -0
  50. package/dist/esm/testing/live/cleanup.js +74 -0
  51. package/dist/esm/testing/live/journal.js +180 -0
  52. package/dist/esm/testing/live/lease.js +56 -0
  53. package/dist/esm/testing/live/private-files.js +50 -0
  54. package/dist/esm/testing/live/process.js +208 -0
  55. package/dist/esm/testing/live/profile.js +214 -0
  56. package/dist/esm/testing/live/recovery.js +164 -0
  57. package/dist/esm/testing/live/resource-limits.js +9 -0
  58. package/dist/esm/testing/live/run.js +390 -0
  59. package/dist/esm/testing/live/session.js +93 -0
  60. package/dist/esm/testing/live/types.d.ts +8 -0
  61. package/dist/esm/testing/mock.d.ts +8 -0
  62. package/dist/esm/testing/mock.js +1364 -0
  63. package/dist/esm/testing/msw.d.ts +21 -0
  64. package/dist/esm/testing/msw.js +61 -0
  65. package/dist/esm/testing/mutations.d.ts +59 -0
  66. package/dist/esm/testing/mutations.js +58 -0
  67. package/dist/esm/testing/node-payload-store.js +353 -0
  68. package/dist/esm/testing/node.d.ts +40 -0
  69. package/dist/esm/testing/node.js +148 -0
  70. package/dist/esm/testing/owner-client.d.ts +9 -0
  71. package/dist/esm/testing/owner-client.js +101 -0
  72. package/dist/esm/testing/owner-shares.js +80 -0
  73. package/dist/esm/testing/packed.d.ts +46 -0
  74. package/dist/esm/testing/packed.js +326 -0
  75. package/dist/esm/testing/reader-lifetime.js +40 -0
  76. package/dist/esm/testing/reply-loss.js +14 -0
  77. package/dist/esm/testing/runtime.d.ts +7 -0
  78. package/dist/esm/testing/runtime.js +13 -0
  79. package/dist/esm/testing/sdk-upload.d.ts +45 -0
  80. package/dist/esm/testing/sdk-upload.js +198 -0
  81. package/dist/esm/testing/streaming-source.js +72 -0
  82. package/dist/esm/testing/transport.d.ts +22 -0
  83. package/dist/esm/testing/transport.js +238 -0
  84. package/dist/esm/testing/types.d.ts +276 -0
  85. package/dist/esm/vitest.d.ts +23 -0
  86. package/dist/esm/vitest.js +34 -0
  87. package/docs/live-auth.md +154 -0
  88. package/docs/live-runs.md +188 -0
  89. package/docs/mock-contracts.md +647 -0
  90. package/package.json +91 -3
@@ -0,0 +1,326 @@
1
+ import { boundedByteView } from "./byte-view.js";
2
+ import { ownReaderLifetime } from "./reader-lifetime.js";
3
+ import { collectPayload } from "./streaming-source.js";
4
+ import { snapshotApplicationMetadata } from "./application-metadata.js";
5
+
6
+ //#region src/testing/packed.ts
7
+ /** Bounded direct packed simulation; handles carry session authority, never native crypto state. */
8
+ /** Carries only original objects acknowledged before a later finalization failure. */
9
+ var PackedFinalizeError = class extends Error {
10
+ objects;
11
+ constructor(cause, objects) {
12
+ super("Packed finalization partially completed", { cause });
13
+ this.name = "PackedFinalizeError";
14
+ this.objects = Object.freeze([...objects]);
15
+ }
16
+ };
17
+ const fail = (code, message) => Object.assign(new Error(message), { code });
18
+ function createPackedSdk(options, backend) {
19
+ const abort = new AbortController();
20
+ const signal = AbortSignal.any([abort.signal, backend.signal]);
21
+ const key = Object.freeze(Object.create(null));
22
+ const objects = /* @__PURE__ */ new WeakMap();
23
+ const uploads = /* @__PURE__ */ new Set();
24
+ const pending = /* @__PURE__ */ new Set();
25
+ const errors = [];
26
+ let closing;
27
+ function authorize() {
28
+ signal.throwIfAborted();
29
+ backend.authorize();
30
+ }
31
+ function owned(object) {
32
+ authorize();
33
+ const record = objects.get(object);
34
+ if (!record) throw fail("foreign-handle", "Unknown packed object");
35
+ return record;
36
+ }
37
+ function track(work) {
38
+ const result = Promise.resolve().then(() => backend.track(work));
39
+ pending.add(result);
40
+ result.then(() => pending.delete(result), () => pending.delete(result));
41
+ return result;
42
+ }
43
+ async function effect(operation, callSignal, work, id) {
44
+ authorize();
45
+ const receipt = await backend.before(operation, callSignal, id);
46
+ try {
47
+ callSignal.throwIfAborted();
48
+ authorize();
49
+ const result = await work(receipt);
50
+ receipt.committed = true;
51
+ if (operation === "pin") backend.afterCommit(receipt);
52
+ receipt.status = "completed";
53
+ return result;
54
+ } catch (error) {
55
+ receipt.status = callSignal.aborted ? "cancelled" : "failed";
56
+ throw error;
57
+ }
58
+ }
59
+ const sdk = {
60
+ appKey() {
61
+ authorize();
62
+ return key;
63
+ },
64
+ close() {
65
+ if (closing) return closing;
66
+ abort.abort();
67
+ closing = (async () => {
68
+ try {
69
+ await Promise.allSettled([...uploads].map((upload) => upload.dispose()));
70
+ await Promise.allSettled([...pending]);
71
+ if (errors.length) throw new AggregateError(errors, "Packed source cleanup failed");
72
+ } catch (error) {
73
+ backend.cleanupError(error);
74
+ throw error;
75
+ } finally {
76
+ unregister();
77
+ }
78
+ })();
79
+ return closing;
80
+ },
81
+ pinObject(object) {
82
+ return track(async () => {
83
+ const record = owned(object);
84
+ await effect("pin", signal, () => backend.pin(record.id, signal), record.id);
85
+ });
86
+ },
87
+ updateObjectMetadata(object) {
88
+ let bytes;
89
+ try {
90
+ bytes = new Uint8Array(owned(object).metadata);
91
+ } catch (error) {
92
+ return Promise.resolve().then(() => {
93
+ throw error;
94
+ });
95
+ }
96
+ return track(async () => {
97
+ const record = owned(object);
98
+ await effect("metadata", signal, () => backend.metadata(record.id, bytes), record.id);
99
+ });
100
+ },
101
+ uploadPacked(configuration = {}) {
102
+ authorize();
103
+ if (Object.keys(configuration).some((k) => ![
104
+ "dataShards",
105
+ "maxBufferedSlabs",
106
+ "parityShards"
107
+ ].includes(k)) || [
108
+ configuration.dataShards,
109
+ configuration.parityShards,
110
+ configuration.maxBufferedSlabs
111
+ ].some((n) => n !== void 0 && (!Number.isSafeInteger(n) || n < 1))) throw fail("invalid-input", "Unsupported packed configuration");
112
+ const reservation = backend.reserve();
113
+ const cancelled = new AbortController();
114
+ const uploadSignal = AbortSignal.any([signal, cancelled.signal]);
115
+ const inputs = [];
116
+ const failures = [];
117
+ let bytes = 0;
118
+ let busy = false;
119
+ let ended = false;
120
+ let current;
121
+ let disposal;
122
+ function available() {
123
+ authorize();
124
+ uploadSignal.throwIfAborted();
125
+ if (busy) throw fail("busy", "Packed operation is in progress");
126
+ if (ended) throw fail("closed", "Packed upload is finished");
127
+ }
128
+ function run(work) {
129
+ try {
130
+ available();
131
+ } catch (error) {
132
+ return Promise.resolve().then(() => {
133
+ throw error;
134
+ });
135
+ }
136
+ busy = true;
137
+ const result = track(work);
138
+ current = result;
139
+ result.then(() => {
140
+ busy = false;
141
+ }, () => {
142
+ busy = false;
143
+ });
144
+ return result;
145
+ }
146
+ async function discardInputs() {
147
+ const settled = await Promise.allSettled(inputs.map((input) => reservation.discard?.(input) ?? Promise.resolve()));
148
+ inputs.length = 0;
149
+ for (const result of settled) if (result.status === "rejected") {
150
+ failures.push(result.reason);
151
+ errors.push(result.reason);
152
+ }
153
+ }
154
+ const upload = {
155
+ add(stream) {
156
+ return run(async () => {
157
+ if (inputs.length >= options.maxObjects) throw fail("limit", "Packed object allowance exceeded");
158
+ const cleanup = (failure) => {
159
+ failures.push(failure);
160
+ errors.push(failure);
161
+ };
162
+ const input = await backend.collect(uploadSignal, async (checkpoint) => {
163
+ if (reservation.admit) return collectPayload(() => stream, await reservation.admit(options.maxBytes - bytes), uploadSignal, checkpoint, cleanup);
164
+ return collect(stream, options.maxBytes - bytes, uploadSignal, cleanup, checkpoint);
165
+ });
166
+ try {
167
+ return await effect("packed-add", uploadSignal, () => {
168
+ inputs.push(input);
169
+ bytes += input.length;
170
+ return options.platform === "node" ? BigInt(input.length) : input.length;
171
+ });
172
+ } catch (error) {
173
+ try {
174
+ await reservation.discard?.(input);
175
+ } catch (cleanup) {
176
+ failures.push(cleanup);
177
+ errors.push(cleanup);
178
+ throw new AggregateError([error, cleanup], "Packed add and discard failed", { cause: cleanup });
179
+ }
180
+ throw error;
181
+ }
182
+ });
183
+ },
184
+ cancel() {
185
+ cancelled.abort();
186
+ },
187
+ dispose() {
188
+ if (disposal) return disposal;
189
+ cancelled.abort();
190
+ disposal = (async () => {
191
+ await Promise.allSettled(current ? [current] : []);
192
+ await discardInputs();
193
+ ended = true;
194
+ try {
195
+ reservation.release();
196
+ } catch (error) {
197
+ failures.push(error);
198
+ errors.push(error);
199
+ }
200
+ uploads.delete(upload);
201
+ if (failures.length) throw new AggregateError(failures, "Packed source cleanup failed");
202
+ })();
203
+ return disposal;
204
+ },
205
+ finalize() {
206
+ return run(async () => {
207
+ ended = true;
208
+ const result = [];
209
+ const completionErrors = [];
210
+ try {
211
+ if (!inputs.length) await effect("packed-finalize", uploadSignal, () => void 0);
212
+ for (const input of inputs) await effect("packed-finalize", uploadSignal, async (receipt) => {
213
+ const id = await reservation.stage(input, uploadSignal, (id) => {
214
+ receipt.committed = true;
215
+ receipt.objectId = id;
216
+ });
217
+ const record = {
218
+ id,
219
+ metadata: /* @__PURE__ */ new Uint8Array()
220
+ };
221
+ const object = Object.freeze(Object.assign(Object.create(null), {
222
+ id: () => id,
223
+ seal(selected) {
224
+ if (this !== object) throw fail("foreign-handle", "Unknown packed object");
225
+ owned(object);
226
+ if (selected !== key) throw fail("foreign-handle", "Unknown packed app key");
227
+ },
228
+ updateMetadata(metadata) {
229
+ if (this !== object) throw fail("foreign-handle", "Unknown packed object");
230
+ owned(object);
231
+ record.metadata = snapshotApplicationMetadata(metadata);
232
+ }
233
+ }));
234
+ objects.set(object, record);
235
+ result.push(object);
236
+ });
237
+ } catch (error) {
238
+ completionErrors.push(error);
239
+ } finally {
240
+ const beforeCleanup = failures.length;
241
+ await discardInputs();
242
+ try {
243
+ reservation.release();
244
+ } catch (error) {
245
+ failures.push(error);
246
+ errors.push(error);
247
+ }
248
+ completionErrors.push(...failures.slice(beforeCleanup));
249
+ uploads.delete(upload);
250
+ }
251
+ if (completionErrors.length) {
252
+ const cause = completionErrors.length === 1 ? completionErrors[0] : new AggregateError(completionErrors, "Packed finalization and cleanup failed");
253
+ if (result.length) throw new PackedFinalizeError(cause, result);
254
+ throw cause;
255
+ }
256
+ return result;
257
+ });
258
+ }
259
+ };
260
+ uploads.add(upload);
261
+ return upload;
262
+ }
263
+ };
264
+ const unregister = backend.register(() => sdk.close());
265
+ return sdk;
266
+ }
267
+ /** Abort must join reader cancellation so a source cleanup failure is not lost. */
268
+ async function collect(stream, limit, signal, cleanupError, checkpoint) {
269
+ signal.throwIfAborted();
270
+ const reader = stream.getReader();
271
+ const lifetime = ownReaderLifetime(reader, signal);
272
+ const errors = [];
273
+ let bytes;
274
+ let length = 0;
275
+ let complete = false;
276
+ try {
277
+ bytes = /* @__PURE__ */ new Uint8Array();
278
+ const initial = checkpoint(0);
279
+ if (initial) await initial;
280
+ for (;;) {
281
+ signal.throwIfAborted();
282
+ let next;
283
+ try {
284
+ next = await reader.read();
285
+ } catch (error) {
286
+ lifetime.readFailed(error);
287
+ throw error;
288
+ }
289
+ signal.throwIfAborted();
290
+ if (next.done) break;
291
+ let chunk;
292
+ try {
293
+ chunk = boundedByteView(next.value, limit - length);
294
+ } catch {
295
+ throw fail("limit", "Packed byte allowance exceeded or invalid chunk");
296
+ }
297
+ const needed = length + chunk.length;
298
+ if (needed > bytes.length) {
299
+ const capacity = Math.min(limit, Math.max(needed, 1024, bytes.length * 2));
300
+ const grown = new Uint8Array(capacity);
301
+ grown.set(bytes.subarray(0, length));
302
+ bytes = grown;
303
+ }
304
+ bytes.set(chunk, length);
305
+ length = needed;
306
+ const pending = checkpoint(length);
307
+ if (pending) await pending;
308
+ }
309
+ complete = true;
310
+ } catch (error) {
311
+ errors.push(error);
312
+ }
313
+ const cancellation = await lifetime.finish(complete, errors[0]);
314
+ if (cancellation.failed) {
315
+ if (!errors.includes(cancellation.error)) errors.push(cancellation.error);
316
+ }
317
+ if (errors.length) {
318
+ const failure = errors.length === 1 ? errors[0] : new AggregateError(errors, "Packed read and source cancellation failed");
319
+ if (cancellation.failed) cleanupError(failure);
320
+ throw failure;
321
+ }
322
+ return length === bytes.length ? bytes : bytes.slice(0, length);
323
+ }
324
+
325
+ //#endregion
326
+ export { PackedFinalizeError, createPackedSdk };
@@ -0,0 +1,40 @@
1
+ //#region src/testing/reader-lifetime.ts
2
+ /** Buffered collectors join producer cancellation without treating repeated reader errors as cleanup failures. */
3
+ function ownReaderLifetime(reader, signal) {
4
+ const closed = reader.closed.then(() => ({ failed: false }), (error) => ({
5
+ error,
6
+ failed: true
7
+ }));
8
+ let readFailure;
9
+ let cancellation;
10
+ const cancel = (reason = signal.reason) => {
11
+ cancellation ??= reader.cancel(reason);
12
+ cancellation.catch(() => void 0);
13
+ };
14
+ const abort = () => cancel();
15
+ signal.addEventListener("abort", abort, { once: true });
16
+ return {
17
+ async finish(complete, reason) {
18
+ signal.removeEventListener("abort", abort);
19
+ if (!complete) cancel(reason);
20
+ try {
21
+ await cancellation;
22
+ return { failed: false };
23
+ } catch (error) {
24
+ const state = await closed;
25
+ return readFailure !== void 0 && Object.is(readFailure.error, error) || state.failed && Object.is(state.error, error) ? { failed: false } : {
26
+ error,
27
+ failed: true
28
+ };
29
+ } finally {
30
+ reader.releaseLock();
31
+ }
32
+ },
33
+ readFailed(error) {
34
+ readFailure = { error };
35
+ }
36
+ };
37
+ }
38
+
39
+ //#endregion
40
+ export { ownReaderLifetime };
@@ -0,0 +1,14 @@
1
+ //#region src/testing/reply-loss.ts
2
+ /** A private identity marker lets adapters drop delivery without serializing a new error code. */
3
+ const losses = /* @__PURE__ */ new WeakSet();
4
+ function isLostReply(error) {
5
+ return error instanceof Error && losses.has(error);
6
+ }
7
+ function lostReply() {
8
+ const error = Object.assign(/* @__PURE__ */ new Error("Mock mutation acknowledgement unavailable"), { code: "unavailable" });
9
+ losses.add(error);
10
+ return error;
11
+ }
12
+
13
+ //#endregion
14
+ export { isLostReply, lostReply };
@@ -0,0 +1,7 @@
1
+ //#region src/testing/runtime.d.ts
2
+ interface MockCredential {
3
+ readonly keyHex: string;
4
+ readonly kind: "app-key" | "registration" | "sharing-key";
5
+ }
6
+ //#endregion
7
+ export { MockCredential };
@@ -0,0 +1,13 @@
1
+ //#region src/testing/runtime.ts
2
+ const runtimes = /* @__PURE__ */ new WeakMap();
3
+ function mockRuntime(mock) {
4
+ const runtime = runtimes.get(mock);
5
+ if (!runtime) throw new Error("Unknown mock environment");
6
+ return runtime;
7
+ }
8
+ function registerRuntime(mock, runtime) {
9
+ runtimes.set(mock, runtime);
10
+ }
11
+
12
+ //#endregion
13
+ export { mockRuntime, registerRuntime };
@@ -0,0 +1,45 @@
1
+ import { ActorRef, BrowserAccess } from "./types.js";
2
+
3
+ //#region src/testing/sdk-upload.d.ts
4
+ interface UploadSdk {
5
+ appKey(): {
6
+ free(): void;
7
+ publicKey(): string;
8
+ };
9
+ close(): Promise<void>;
10
+ pinObject(object: MockPinnedObject): Promise<void>;
11
+ upload(object: MockPinnedObject, source: ReadableStream<Uint8Array>, options?: MockUploadOptions): Promise<MockPinnedObject>;
12
+ }
13
+ interface UploadSdkOptions {
14
+ readonly access: BrowserAccess;
15
+ readonly as: ActorRef;
16
+ /** Maximum bytes collected from one source before staging it. */
17
+ readonly maxBytes: number;
18
+ }
19
+ /** Mirrors SDK shard reports without requiring the optional native package in mock consumers. */
20
+ interface MockShardProgress {
21
+ elapsedMs: number;
22
+ hostKey: string;
23
+ shardIndex: number;
24
+ shardSize: number;
25
+ slabIndex: number;
26
+ }
27
+ interface MockUploadOptions {
28
+ dataShards?: number;
29
+ onShardUploaded?: (progress: MockShardProgress) => void;
30
+ parityShards?: number;
31
+ }
32
+ /** A test handle; `free` invalidates this reference but cannot undo a staged upload. */
33
+ declare class MockPinnedObject {
34
+ private alive;
35
+ private readonly identifier;
36
+ private value;
37
+ constructor(id?: string);
38
+ free(): void;
39
+ id(): string;
40
+ metadata(): Uint8Array;
41
+ updateMetadata(bytes: Uint8Array): void;
42
+ private check;
43
+ }
44
+ //#endregion
45
+ export { MockPinnedObject, UploadSdk, UploadSdkOptions };
@@ -0,0 +1,198 @@
1
+ import { boundedByteView } from "./byte-view.js";
2
+ import { ownReaderLifetime } from "./reader-lifetime.js";
3
+ import { bytesFixture } from "./files.js";
4
+
5
+ //#region src/testing/sdk-upload.ts
6
+ /** Direct SDK 0.2 upload calls use an owned application port without native encryption or host traffic. */
7
+ const fail = (code, message) => Object.assign(new Error(message), { code });
8
+ /** A test handle; `free` invalidates this reference but cannot undo a staged upload. */
9
+ var MockPinnedObject = class {
10
+ alive = true;
11
+ identifier;
12
+ value = /* @__PURE__ */ new Uint8Array();
13
+ constructor(id = crypto.randomUUID().replaceAll("-", "").padEnd(64, "0")) {
14
+ this.identifier = id;
15
+ }
16
+ free() {
17
+ this.alive = false;
18
+ }
19
+ id() {
20
+ this.check();
21
+ return this.identifier;
22
+ }
23
+ metadata() {
24
+ this.check();
25
+ return this.value.slice();
26
+ }
27
+ updateMetadata(bytes) {
28
+ this.check();
29
+ this.value = new Uint8Array(boundedByteView(bytes, 1024));
30
+ }
31
+ check() {
32
+ if (!this.alive) throw fail("closed", "Object handle has been freed");
33
+ }
34
+ };
35
+ const uploadedHandles = /* @__PURE__ */ new WeakSet();
36
+ /** Reuses the run's writer so SDK-shaped calls share its upload and pin fault controls. */
37
+ function createUploadSdk(writer, maxBytes, publicKey, register, reportCleanup) {
38
+ const abort = new AbortController();
39
+ const originals = /* @__PURE__ */ new WeakMap();
40
+ const pending = /* @__PURE__ */ new Set();
41
+ const cleanupFailures = [];
42
+ let closing;
43
+ function open() {
44
+ if (abort.signal.aborted) throw fail("closed", "Upload SDK has closed");
45
+ }
46
+ function track(work) {
47
+ const call = Promise.resolve().then(work);
48
+ pending.add(call);
49
+ call.then(() => pending.delete(call), () => pending.delete(call));
50
+ return call;
51
+ }
52
+ const sdk = {
53
+ appKey() {
54
+ open();
55
+ let freed = false;
56
+ return {
57
+ free() {
58
+ freed = true;
59
+ },
60
+ publicKey() {
61
+ if (freed) throw fail("closed", "App key has been freed");
62
+ return publicKey;
63
+ }
64
+ };
65
+ },
66
+ close() {
67
+ if (closing) return closing;
68
+ abort.abort();
69
+ closing = (async () => {
70
+ try {
71
+ await Promise.allSettled([...pending]);
72
+ const results = await Promise.allSettled([writer.close()]);
73
+ const failures = [...cleanupFailures, ...results.flatMap((result) => result.status === "rejected" ? [result.reason] : [])];
74
+ if (failures.length) {
75
+ const failure = new AggregateError(failures, "Upload SDK cleanup failed");
76
+ reportCleanup(failure);
77
+ throw failure;
78
+ }
79
+ } finally {
80
+ unregister();
81
+ }
82
+ })();
83
+ return closing;
84
+ },
85
+ pinObject(object) {
86
+ return track(async () => {
87
+ open();
88
+ if (!(object instanceof MockPinnedObject) || !originals.has(object)) throw fail("foreign-handle", "Unknown uploaded object");
89
+ object.id();
90
+ await writer.pin(originals.get(object), {
91
+ metadata: object.metadata(),
92
+ signal: abort.signal
93
+ });
94
+ });
95
+ },
96
+ upload(draft, source, options) {
97
+ return track(async () => {
98
+ open();
99
+ if (!(draft instanceof MockPinnedObject) || uploadedHandles.has(draft)) throw fail("invalid-input", "Upload requires a new object handle");
100
+ if (options && Object.keys(options).some((key) => ![
101
+ "dataShards",
102
+ "onShardUploaded",
103
+ "parityShards"
104
+ ].includes(key))) throw fail("unsupported", "Upload options are not simulated");
105
+ const dataShards = options?.dataShards ?? 10;
106
+ const parityShards = options?.parityShards ?? 20;
107
+ if (!Number.isSafeInteger(dataShards) || dataShards < 1 || !Number.isSafeInteger(parityShards) || parityShards < 0 || dataShards + parityShards > 255) throw fail("invalid-input", "Invalid shard counts");
108
+ const metadata = draft.metadata();
109
+ draft.free();
110
+ const bytes = await collectSource(source, maxBytes, abort.signal, (error) => {
111
+ cleanupFailures.push(error);
112
+ });
113
+ const file = await bytesFixture({
114
+ bytes,
115
+ name: "sdk-upload"
116
+ });
117
+ const original = await writer.upload({
118
+ file,
119
+ metadata,
120
+ signal: abort.signal
121
+ });
122
+ const shardSize = 4194304;
123
+ const slabs = Math.ceil(bytes.length / (dataShards * shardSize));
124
+ for (let slabIndex = 0; slabIndex < slabs; slabIndex++) for (let shardIndex = 0; shardIndex < dataShards + parityShards; shardIndex++) try {
125
+ options?.onShardUploaded?.({
126
+ elapsedMs: 0,
127
+ hostKey: `ed25519:${shardIndex.toString(16).padStart(64, "0")}`,
128
+ shardIndex,
129
+ shardSize,
130
+ slabIndex
131
+ });
132
+ } catch {}
133
+ const object = new MockPinnedObject(original.id);
134
+ object.updateMetadata(metadata);
135
+ originals.set(object, original);
136
+ uploadedHandles.add(object);
137
+ return object;
138
+ });
139
+ }
140
+ };
141
+ const unregister = register(() => sdk.close());
142
+ return sdk;
143
+ }
144
+ /** Joins source cancellation before the SDK can finish closing its run-owned writer. */
145
+ async function collectSource(source, limit, signal, cleanupFailure) {
146
+ signal.throwIfAborted();
147
+ const reader = source.getReader();
148
+ const lifetime = ownReaderLifetime(reader, signal);
149
+ let bytes = /* @__PURE__ */ new Uint8Array();
150
+ let length = 0;
151
+ let complete = false;
152
+ let error;
153
+ try {
154
+ for (;;) {
155
+ signal.throwIfAborted();
156
+ let part;
157
+ try {
158
+ part = await reader.read();
159
+ } catch (failure) {
160
+ lifetime.readFailed(failure);
161
+ throw failure;
162
+ }
163
+ signal.throwIfAborted();
164
+ if (part.done) break;
165
+ let chunk;
166
+ try {
167
+ chunk = boundedByteView(part.value, limit - length);
168
+ } catch {
169
+ throw fail("limit", "Upload exceeds its byte allowance or has an invalid chunk");
170
+ }
171
+ const needed = length + chunk.length;
172
+ if (needed > bytes.length) {
173
+ const next = new Uint8Array(Math.min(limit, Math.max(needed, 1024, bytes.length * 2)));
174
+ next.set(bytes.subarray(0, length));
175
+ bytes = next;
176
+ }
177
+ bytes.set(chunk, length);
178
+ length = needed;
179
+ }
180
+ complete = true;
181
+ } catch (failure) {
182
+ error = failure;
183
+ }
184
+ const cleanup = await lifetime.finish(complete, error);
185
+ if (cleanup.failed) {
186
+ const failure = new AggregateError(error === void 0 ? [cleanup.error] : [error, cleanup.error], "Upload source cleanup failed");
187
+ cleanupFailure(failure);
188
+ throw failure;
189
+ }
190
+ if (error !== void 0) {
191
+ if (error instanceof Error) throw error;
192
+ throw new Error("Upload source failed", { cause: error });
193
+ }
194
+ return bytes.slice(0, length);
195
+ }
196
+
197
+ //#endregion
198
+ export { MockPinnedObject, createUploadSdk };