stitchkit 0.101.0 → 0.101.1

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.
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  ApiError2,
10
10
  createHttpClient2
11
- } from "../index-qjeggp8w.js";
11
+ } from "../index-h43cepag.js";
12
12
  import"../index-m38ej7e5.js";
13
13
  import {
14
14
  DEFAULT_CONTRACT_STREAM_FRAME_BYTES2,
@@ -24,7 +24,7 @@ import {
24
24
  createUrlBuilder2,
25
25
  createUrlBuilders2,
26
26
  createScopedUrlBuilders2
27
- } from "../index-aaj97r4y.js";
27
+ } from "../index-65jwqhcf.js";
28
28
  import"../index-w0eqdhyd.js";
29
29
  import {
30
30
  LiveStatePhaseSchema2,
@@ -95,6 +95,93 @@ import {
95
95
  zodIssues2,
96
96
  formatZodError2
97
97
  } from "../index-1eeqpadm.js";
98
+
99
+ // src/browser/chunked-upload.ts
100
+ function isRetryableUploadFailure(error) {
101
+ if (ApiError2.is(error)) {
102
+ if (error.status === 0)
103
+ return error.code === "UNKNOWN_ERROR" || error.code === "REQUEST_TIMEOUT";
104
+ return error.status === 429 || error.status >= 500;
105
+ }
106
+ return error instanceof TypeError;
107
+ }
108
+ async function uploadInChunks(config) {
109
+ const { file, chunkBytes, signal } = config;
110
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) {
111
+ throw new TypeError("uploadInChunks: chunkBytes must be a positive integer");
112
+ }
113
+ if (file.size === 0)
114
+ throw new TypeError("uploadInChunks: the file is empty");
115
+ const totalBytes = file.size;
116
+ const chunkCount = Math.ceil(totalBytes / chunkBytes);
117
+ const uploadId = config.uploadId ?? crypto.randomUUID();
118
+ const retries = config.retries ?? 3;
119
+ const retryDelayMs = config.retryDelayMs ?? 1000;
120
+ const report = (sentBytes, index, attempt) => {
121
+ if (!config.onProgress)
122
+ return;
123
+ try {
124
+ config.onProgress({ sentBytes, totalBytes, index, chunkCount, attempt });
125
+ } catch {}
126
+ };
127
+ throwIfAborted(signal);
128
+ const opened = await repeating(() => config.init({ uploadId, totalBytes, chunkBytes, chunkCount }, { signal }), { retries, retryDelayMs, signal });
129
+ if (opened) {
130
+ report(totalBytes, chunkCount, 1);
131
+ return opened.finished;
132
+ }
133
+ report(0, 0, 1);
134
+ for (let index = 0;index < chunkCount; index += 1) {
135
+ throwIfAborted(signal);
136
+ const start = index * chunkBytes;
137
+ const bytes = file.slice(start, Math.min(totalBytes, start + chunkBytes));
138
+ await repeating((attempt) => config.chunk({ uploadId, index, bytes }, {
139
+ ...signal && { signal },
140
+ onUploadProgress: (progress) => report(start + fileShare(progress, bytes.size), index, attempt)
141
+ }), { retries, retryDelayMs, signal });
142
+ report(start + bytes.size, index + 1, 1);
143
+ }
144
+ throwIfAborted(signal);
145
+ return config.finalize({ uploadId }, { signal });
146
+ }
147
+ function fileShare(progress, partBytes) {
148
+ if (progress.totalBytes === 0)
149
+ return 0;
150
+ return Math.floor(partBytes * progress.sentBytes / progress.totalBytes);
151
+ }
152
+ async function repeating(call, {
153
+ retries,
154
+ retryDelayMs,
155
+ signal
156
+ }) {
157
+ for (let attempt = 1;; attempt += 1) {
158
+ try {
159
+ return await call(attempt);
160
+ } catch (error) {
161
+ if (signal?.aborted || attempt > retries || !isRetryableUploadFailure(error))
162
+ throw error;
163
+ await pause(retryDelayMs * 2 ** (attempt - 1), signal);
164
+ }
165
+ }
166
+ }
167
+ function throwIfAborted(signal) {
168
+ if (signal?.aborted) {
169
+ throw new ApiError2("REQUEST_ABORTED", 0, undefined, "Request was aborted");
170
+ }
171
+ }
172
+ function pause(ms, signal) {
173
+ return new Promise((resolve, reject) => {
174
+ const abort = () => {
175
+ clearTimeout(timer);
176
+ reject(new ApiError2("REQUEST_ABORTED", 0, undefined, "Request was aborted"));
177
+ };
178
+ const timer = setTimeout(() => {
179
+ signal?.removeEventListener("abort", abort);
180
+ resolve();
181
+ }, ms);
182
+ signal?.addEventListener("abort", abort, { once: true });
183
+ });
184
+ }
98
185
  // src/browser/socket-io-trace.ts
99
186
  var realtimeRequestTraces = new WeakMap;
100
187
  function observeRealtimeRequestPhase(trace, phase) {
@@ -954,6 +1041,7 @@ export {
954
1041
  rateLimited2 as rateLimited,
955
1042
  resumableIterator,
956
1043
  unauthorized2 as unauthorized,
1044
+ uploadInChunks,
957
1045
  withToolView2 as withToolView,
958
1046
  zodIssues2 as zodIssues
959
1047
  };
@@ -2,7 +2,7 @@ import"../index-hby4qhax.js";
2
2
  import {
3
3
  ApiError2,
4
4
  isAbortLikeError
5
- } from "../index-qjeggp8w.js";
5
+ } from "../index-h43cepag.js";
6
6
  import {
7
7
  isRecord
8
8
  } from "../index-9jfdm5tg.js";
@@ -1,12 +1,12 @@
1
1
  import"../index-hby4qhax.js";
2
2
  import {
3
3
  ApiError2
4
- } from "../index-qjeggp8w.js";
4
+ } from "../index-h43cepag.js";
5
5
  import"../index-m38ej7e5.js";
6
6
  import"../index-r5c4fedv.js";
7
7
  import {
8
8
  createClient2
9
- } from "../index-aaj97r4y.js";
9
+ } from "../index-65jwqhcf.js";
10
10
  import {
11
11
  AppError2
12
12
  } from "../index-n53mswt3.js";
@@ -1,5 +1,5 @@
1
1
  import"../index-hby4qhax.js";
2
- import"../index-qjeggp8w.js";
2
+ import"../index-h43cepag.js";
3
3
  import {
4
4
  joinRoutePath
5
5
  } from "../index-m38ej7e5.js";
@@ -7,7 +7,7 @@ import"../index-r5c4fedv.js";
7
7
  import {
8
8
  createClient2,
9
9
  createClients2
10
- } from "../index-aaj97r4y.js";
10
+ } from "../index-65jwqhcf.js";
11
11
  import"../index-n53mswt3.js";
12
12
  import"../index-q0th8q0z.js";
13
13
  import {
@@ -1,7 +1,7 @@
1
1
  import"../index-hby4qhax.js";
2
2
  import {
3
3
  ApiError2
4
- } from "../index-qjeggp8w.js";
4
+ } from "../index-h43cepag.js";
5
5
  import"../index-m38ej7e5.js";
6
6
  import {
7
7
  defineContract2
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The server half of a chunked upload (`uploadInChunks` is the client half):
3
+ * parts land on disk under the upload's owner, each with a receipt, and come
4
+ * back in order once every part is in.
5
+ *
6
+ * - An upload is keyed by `owner` (whoever the application says sends it —
7
+ * a user, a user and a device) and the client-minted `uploadId`; the same id
8
+ * from another owner is another upload.
9
+ * - `open` is idempotent: the same declaration again is `'reopened'`, a
10
+ * different one is `UPLOAD_CONFLICT`.
11
+ * - A part's receipt is its size and sha256. The same bytes again are
12
+ * `'repeated'`; other bytes at the same index are `UPLOAD_CONFLICT`. The
13
+ * first writer wins across processes: a part's data file is named by its hash
14
+ * and its receipt is published by an exclusive link, so a loser can neither
15
+ * replace the receipt nor the bytes it names.
16
+ * - Every part but the last is exactly `chunkBytes` long.
17
+ * - `sweep` removes an upload nothing has touched for `staleAfterMs`.
18
+ *
19
+ * Refusals are `AppError`s with a 4xx status, so a handler that does not catch
20
+ * them answers the client with a typed envelope the driver does not repeat.
21
+ */
22
+ import type { ZodType } from 'zod';
23
+ export type ChunkSpoolErrorCode = 'UPLOAD_INVALID' | 'UPLOAD_TOO_LARGE' | 'UPLOAD_NOT_FOUND' | 'UPLOAD_CONFLICT' | 'UPLOAD_CHUNK_OUT_OF_RANGE' | 'UPLOAD_CHUNK_SIZE' | 'UPLOAD_INCOMPLETE';
24
+ export interface ChunkSpoolConfig<TMeta> {
25
+ /** Where uploads in progress live; one directory per upload. */
26
+ readonly directory: string;
27
+ /** Bytes per part, the same number the client driver uses. */
28
+ readonly chunkBytes: number;
29
+ readonly maxFileBytes: number;
30
+ /** What `open` stores beside the upload — file name, type, the app's fields. */
31
+ readonly meta: ZodType<TMeta>;
32
+ /** Default 24 hours. */
33
+ readonly staleAfterMs?: number;
34
+ }
35
+ export interface ChunkSpoolKey {
36
+ readonly owner: string;
37
+ readonly uploadId: string;
38
+ }
39
+ export interface ChunkSpoolOpen<TMeta> extends ChunkSpoolKey {
40
+ readonly totalBytes: number;
41
+ readonly chunkCount: number;
42
+ readonly meta: TMeta;
43
+ }
44
+ export interface ChunkSpoolPart extends ChunkSpoolKey {
45
+ readonly index: number;
46
+ readonly bytes: Blob;
47
+ }
48
+ export interface ChunkSpoolAssembly<TMeta> {
49
+ readonly meta: TMeta;
50
+ readonly totalBytes: number;
51
+ /** The parts on disk, in order; valid until `discard`. */
52
+ readonly chunkPaths: readonly string[];
53
+ /** The whole file, part after part. */
54
+ stream(): ReadableStream<Uint8Array>;
55
+ }
56
+ export interface ChunkSpool<TMeta> {
57
+ open(upload: ChunkSpoolOpen<TMeta>): Promise<'opened' | 'reopened'>;
58
+ put(part: ChunkSpoolPart): Promise<'stored' | 'repeated'>;
59
+ /** Every part, checked against its receipt; `UPLOAD_INCOMPLETE` names the first missing. */
60
+ assemble(key: ChunkSpoolKey): Promise<ChunkSpoolAssembly<TMeta>>;
61
+ discard(key: ChunkSpoolKey): Promise<void>;
62
+ /** Remove uploads untouched for `staleAfterMs`; resolves with how many. */
63
+ sweep(): Promise<number>;
64
+ }
65
+ export declare function createChunkSpool<TMeta>(config: ChunkSpoolConfig<TMeta>): ChunkSpool<TMeta>;
66
+ //# sourceMappingURL=chunk-spool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chunk-spool.d.ts","sourceRoot":"","sources":["../../src/files/chunk-spool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAgBH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAInC,MAAM,MAAM,mBAAmB,GAC3B,gBAAgB,GAChB,kBAAkB,GAClB,kBAAkB,GAClB,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,mBAAmB,CAAC;AAoBxB,MAAM,WAAW,gBAAgB,CAAC,KAAK;IACrC,gEAAgE;IAChE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,8DAA8D;IAC9D,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,gFAAgF;IAChF,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,wBAAwB;IACxB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,cAAc,CAAC,KAAK,CAAE,SAAQ,aAAa;IAC1D,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,cAAe,SAAQ,aAAa;IACnD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB,CAAC,KAAK;IACvC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,0DAA0D;IAC1D,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,uCAAuC;IACvC,MAAM,IAAI,cAAc,CAAC,UAAU,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,UAAU,CAAC,KAAK;IAC/B,IAAI,CAAC,MAAM,EAAE,cAAc,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,QAAQ,GAAG,UAAU,CAAC,CAAC;IACpE,GAAG,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,QAAQ,GAAG,UAAU,CAAC,CAAC;IAC1D,4FAA4F;IAC5F,QAAQ,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;IACjE,OAAO,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,2EAA2E;IAC3E,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1B;AAkED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,gBAAgB,CAAC,KAAK,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,CA4J1F"}
@@ -2,10 +2,12 @@ import {
2
2
  RequestCancellationError,
3
3
  createRequestCancellation,
4
4
  responseTraceId,
5
+ uploadProgressRoute,
6
+ withUploadProgress,
5
7
  ApiError2,
6
8
  refuseLocally,
7
9
  parseApiErrorBody
8
- } from "./index-qjeggp8w.js";
10
+ } from "./index-h43cepag.js";
9
11
  import {
10
12
  parseTrailingWildcard
11
13
  } from "./index-m38ej7e5.js";
@@ -541,7 +543,8 @@ function createFetchExecutor(endpoint, prefix, config, contractConfig) {
541
543
  try {
542
544
  return await cancellation.run(async (signal) => {
543
545
  const body = endpoint.multipart ? buildMultipartForm(endpoint.multipart, plan.remainingArgs) : hasBody ? JSON.stringify(plan.remainingArgs) : undefined;
544
- const res = await executeFetch(url, {
546
+ const deliver = options?.onUploadProgress ? withUploadProgress(executeFetch, options.onUploadProgress, uploadProgressRoute(config.fetch !== undefined)) : executeFetch;
547
+ const res = await deliver(url, {
545
548
  method: endpoint.method,
546
549
  headers,
547
550
  credentials: config.credentials,
@@ -660,7 +663,7 @@ function createEndpointMethod(endpoint, execute, contractConfig) {
660
663
  return Object.assign(method, {
661
664
  withOptions: (...args) => {
662
665
  refuseExtraWithOptionsArguments(endpoint, args.length, 2);
663
- return settle(execute, readClientRequestArgs(args[0]), readClientRequestOptions(args[1]));
666
+ return settle(execute, readClientRequestArgs(args[0]), readClientRequestOptions(endpoint, args[1]));
664
667
  }
665
668
  });
666
669
  }
@@ -668,7 +671,7 @@ function createEndpointMethod(endpoint, execute, contractConfig) {
668
671
  return Object.assign(method, {
669
672
  withOptions: (...args) => {
670
673
  refuseExtraWithOptionsArguments(endpoint, args.length, 1);
671
- return settle(execute, {}, readClientRequestOptions(args[0]));
674
+ return settle(execute, {}, readClientRequestOptions(endpoint, args[0]));
672
675
  }
673
676
  });
674
677
  }
@@ -694,16 +697,30 @@ function readClientRequestArgs(requestArgs) {
694
697
  }
695
698
  return requestArgs ?? {};
696
699
  }
697
- function readClientRequestOptions(value) {
700
+ function readClientRequestOptions(endpoint, value) {
698
701
  if (!isRecord(value))
699
702
  throw new TypeError("Client request options must be an object");
700
- const signal = value.signal;
701
- if (signal === undefined)
702
- return {};
703
- if (!isAbortSignal(signal)) {
703
+ const { signal, onUploadProgress } = value;
704
+ if (signal !== undefined && !isAbortSignal(signal)) {
704
705
  throw new TypeError("Client request signal must be an AbortSignal");
705
706
  }
706
- return { signal };
707
+ if (onUploadProgress === undefined)
708
+ return signal === undefined ? {} : { signal };
709
+ if (typeof onUploadProgress !== "function") {
710
+ throw new TypeError("Client request onUploadProgress must be a function");
711
+ }
712
+ if (!endpointSendsBody(endpoint)) {
713
+ throw new TypeError(`${endpoint.method} ${endpoint.path}: onUploadProgress needs a request body — ` + "a GET, HEAD or DELETE sends none, and a streaming endpoint keeps its response live, " + "which the XMLHttpRequest route would buffer.");
714
+ }
715
+ return {
716
+ ...signal !== undefined && { signal },
717
+ onUploadProgress: (progress) => {
718
+ onUploadProgress(progress);
719
+ }
720
+ };
721
+ }
722
+ function endpointSendsBody(endpoint) {
723
+ return endpoint.method !== "GET" && endpoint.method !== "HEAD" && endpoint.method !== "DELETE" && !(("stream" in endpoint) && endpoint.stream);
707
724
  }
708
725
  function isAbortSignal(value) {
709
726
  return typeof value === "object" && value !== null && "aborted" in value && typeof value.aborted === "boolean" && "addEventListener" in value && typeof value.addEventListener === "function" && "removeEventListener" in value && typeof value.removeEventListener === "function";
@@ -144,6 +144,122 @@ function responseTraceId(response) {
144
144
  return response?.headers.get(REQUEST_ID_HEADER) ?? undefined;
145
145
  }
146
146
 
147
+ // src/browser/upload-progress.ts
148
+ var PIECE_BYTES = 64 * 1024;
149
+ function uploadProgressRoute(injectedTransport) {
150
+ return !injectedTransport && typeof globalThis.XMLHttpRequest === "function" ? "xhr" : "stream";
151
+ }
152
+ function withUploadProgress(transport, listener, route) {
153
+ let attempts = 0;
154
+ return async (input, init) => {
155
+ attempts += 1;
156
+ const attempt = attempts;
157
+ const request = new Request(input, init);
158
+ const headers = new Headers(request.headers);
159
+ const bytes = new Uint8Array(await request.arrayBuffer());
160
+ let reported = -1;
161
+ const report = (sentBytes) => {
162
+ if (sentBytes <= reported)
163
+ return;
164
+ reported = sentBytes;
165
+ try {
166
+ listener({ sentBytes, totalBytes: bytes.byteLength, attempt });
167
+ } catch {}
168
+ };
169
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
170
+ const credentials = init?.credentials ?? (input instanceof Request ? input.credentials : undefined);
171
+ report(0);
172
+ if (route === "xhr") {
173
+ return sendThroughXhr(request, headers, bytes, { signal, credentials, report });
174
+ }
175
+ headers.set("content-length", String(bytes.byteLength));
176
+ const counted = bytes.byteLength > 0 ? { body: countedBody(bytes, report), duplex: "half" } : {};
177
+ const outgoing = {
178
+ ...init,
179
+ method: request.method,
180
+ headers,
181
+ body: undefined,
182
+ ...counted,
183
+ ...signal && { signal },
184
+ ...credentials && { credentials }
185
+ };
186
+ return transport(request.url, outgoing);
187
+ };
188
+ }
189
+ function countedBody(bytes, report) {
190
+ let offset = 0;
191
+ return new ReadableStream({
192
+ pull(controller) {
193
+ if (offset >= bytes.byteLength) {
194
+ controller.close();
195
+ return;
196
+ }
197
+ const end = Math.min(offset + PIECE_BYTES, bytes.byteLength);
198
+ controller.enqueue(bytes.slice(offset, end));
199
+ offset = end;
200
+ report(offset);
201
+ }
202
+ }, { highWaterMark: 0 });
203
+ }
204
+ var BROWSER_OWNED_HEADERS = new Set(["content-length", "host", "connection"]);
205
+ function sendThroughXhr(request, headers, bytes, { signal, credentials, report }) {
206
+ return new Promise((resolve, reject) => {
207
+ if (credentials === "omit") {
208
+ reject(new TypeError("onUploadProgress sends through XMLHttpRequest, which cannot omit same-origin cookies — use credentials 'same-origin' or 'include'"));
209
+ return;
210
+ }
211
+ if (signal?.aborted) {
212
+ reject(abortReason(signal));
213
+ return;
214
+ }
215
+ const xhr = new XMLHttpRequest;
216
+ xhr.open(request.method, request.url, true);
217
+ headers.forEach((value, name) => {
218
+ if (!BROWSER_OWNED_HEADERS.has(name))
219
+ xhr.setRequestHeader(name, value);
220
+ });
221
+ xhr.withCredentials = credentials === "include";
222
+ xhr.responseType = "arraybuffer";
223
+ const abort = () => xhr.abort();
224
+ signal?.addEventListener("abort", abort, { once: true });
225
+ const settle = () => signal?.removeEventListener("abort", abort);
226
+ xhr.upload.onprogress = (event) => report(Math.min(event.loaded, bytes.byteLength));
227
+ xhr.upload.onload = () => report(bytes.byteLength);
228
+ xhr.onload = () => {
229
+ settle();
230
+ if (xhr.status < 200 || xhr.status > 599) {
231
+ reject(new TypeError("Network request failed"));
232
+ return;
233
+ }
234
+ report(bytes.byteLength);
235
+ resolve(responseOf(xhr));
236
+ };
237
+ xhr.onerror = () => {
238
+ settle();
239
+ reject(new TypeError("Network request failed"));
240
+ };
241
+ xhr.onabort = () => {
242
+ settle();
243
+ reject(signal ? abortReason(signal) : new DOMException("Aborted", "AbortError"));
244
+ };
245
+ xhr.send(bytes.byteLength > 0 ? bytes : null);
246
+ });
247
+ }
248
+ function abortReason(signal) {
249
+ return signal.reason ?? new DOMException("Aborted", "AbortError");
250
+ }
251
+ var NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
252
+ function responseOf(xhr) {
253
+ const headers = new Headers;
254
+ for (const line of xhr.getAllResponseHeaders().trim().split(/[\r\n]+/)) {
255
+ const colon = line.indexOf(":");
256
+ if (colon > 0)
257
+ headers.append(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
258
+ }
259
+ const body = xhr.response;
260
+ return new Response(NULL_BODY_STATUSES.has(xhr.status) || !(body instanceof ArrayBuffer) ? null : body, { status: xhr.status, statusText: xhr.statusText, headers });
261
+ }
262
+
147
263
  // src/browser/http.ts
148
264
  var API_ERROR_BRAND = Symbol.for("stitchkit.ApiError");
149
265
  function messageForCode(code, message) {
@@ -225,6 +341,15 @@ function requestFailure(error, emit) {
225
341
  const msg = error instanceof Error ? error.message : undefined;
226
342
  return new ApiError2("UNKNOWN_ERROR", status, msg ? { message: msg } : undefined, msg, undefined, responseTraceId(response), { cause: error });
227
343
  }
344
+ function errorBodyOf(data) {
345
+ if (typeof data !== "string")
346
+ return data ?? null;
347
+ try {
348
+ return JSON.parse(data);
349
+ } catch {
350
+ return null;
351
+ }
352
+ }
228
353
  function createHttpClient2(config) {
229
354
  assertTransportChoice(config);
230
355
  let ssrCookies = null;
@@ -280,23 +405,26 @@ function createHttpClient2(config) {
280
405
  emit({ type: "unauthorized" });
281
406
  }
282
407
  }
283
- if (!response.ok) {
284
- const body = await response.clone().json().catch(() => null);
285
- if (body) {
286
- const parsed = parseError(body);
287
- if (parsed) {
288
- throw new ApiError2(parsed.code, response.status, parsed.details, parsed.message, parsed.hint, responseTraceId(response));
289
- }
290
- }
291
- }
408
+ }
409
+ ],
410
+ beforeError: [
411
+ ({ error }) => {
412
+ if (!isHTTPError(error))
413
+ return error;
414
+ const body = errorBodyOf(error.data);
415
+ const parsed = body === null ? null : parseError(body);
416
+ if (!parsed)
417
+ return error;
418
+ return new ApiError2(parsed.code, error.response.status, parsed.details, parsed.message, parsed.hint, responseTraceId(error.response));
292
419
  }
293
420
  ]
294
421
  }
295
422
  });
296
423
  async function request(method, url, data, options = {}) {
297
424
  const cancellation = createRequestCancellation(options.signal, options.timeout ?? config.timeout ?? 30000);
425
+ const transport = config.fetch ?? globalThis.fetch.bind(globalThis);
298
426
  const kyOptions = {
299
- fetch: createRetryAwareFetch(config.fetch ?? globalThis.fetch.bind(globalThis), config.unix),
427
+ fetch: createRetryAwareFetch(options.onUploadProgress ? withUploadProgress(transport, options.onUploadProgress, uploadProgressRoute(config.fetch !== undefined || config.unix !== undefined)) : transport, config.unix),
300
428
  timeout: false,
301
429
  signal: cancellation.signal
302
430
  };
@@ -339,4 +467,4 @@ function createHttpClient2(config) {
339
467
  };
340
468
  }
341
469
 
342
- export { RequestCancellationError, createRequestCancellation, responseTraceId, ApiError2, refuseLocally, isAbortLikeError, parseApiErrorBody, createHttpClient2 };
470
+ export { RequestCancellationError, createRequestCancellation, responseTraceId, uploadProgressRoute, withUploadProgress, ApiError2, refuseLocally, isAbortLikeError, parseApiErrorBody, createHttpClient2 };
package/llms/files.txt CHANGED
@@ -29,5 +29,8 @@ available from `stitchkit/contract`.
29
29
  | `writeFileAtomic` / `writeFileAtomicSync` / `WriteFileAtomicOptions` | function / _type_ | replace a file atomically: a random staging name created exclusively (never through a planted link), the mode set on the descriptor before the file is visible (default `0o600`, not masked by the umask), `fsync`, rename; a failure leaves the target and no staging file. The asynchronous form keeps the event loop running |
30
30
  | `withExclusiveLock` / `ExclusiveLockOptions` / `ExclusiveLock` / `ExclusiveLockOwner` | function / _type_ | run work under an exclusive lock between processes — a file recording its owner (pid, host, machine identity, time and nullable kernel process identity); waits up to `timeoutMs` (default 10 s) and stops on `signal`; a dead owner on this machine is taken over, a live, slow or foreign one never is; an ownerless lock only after `ownerlessGraceMs` |
31
31
  | `ExclusiveLockError` | class | `LOCK_TIMEOUT` naming the resource and its holder, or `LOCK_ABORTED` with the signal's reason |
32
+ | `createChunkSpool` | function | the server half of a chunked upload: parts on disk under `owner` + client-minted `uploadId`, each with a size+sha256 receipt; idempotent `open` and `put`, the first writer of a part wins across processes, `assemble` in order once every part is in, `sweep` of untouched uploads — [guide](../guide/client.md#chunked-uploads) |
33
+ | `ChunkSpool` / `ChunkSpoolConfig` / `ChunkSpoolKey` / `ChunkSpoolOpen` / `ChunkSpoolPart` / `ChunkSpoolAssembly` | _type_ | the spool, its directory, part size, file limit, meta schema and age; an upload's key; its declaration; one part; the assembled parts with a concatenating `stream()` |
34
+ | `ChunkSpoolErrorCode` | _type_ | the `AppError` codes a spool refuses with, each with its 4xx status: `UPLOAD_INVALID`, `UPLOAD_TOO_LARGE`, `UPLOAD_NOT_FOUND`, `UPLOAD_CONFLICT`, `UPLOAD_CHUNK_OUT_OF_RANGE`, `UPLOAD_CHUNK_SIZE`, `UPLOAD_INCOMPLETE` |
32
35
 
33
36
  ---