stitchkit 0.123.1 → 0.123.3

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 (36) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/browser/client-bound.d.ts +19 -0
  3. package/dist/browser/client-bound.d.ts.map +1 -0
  4. package/dist/browser/client-url.d.ts +2 -0
  5. package/dist/browser/client-url.d.ts.map +1 -1
  6. package/dist/browser/client.d.ts +20 -10
  7. package/dist/browser/client.d.ts.map +1 -1
  8. package/dist/contract/client-types.d.ts +13 -8
  9. package/dist/contract/client-types.d.ts.map +1 -1
  10. package/dist/entrypoints/http.js +1 -1
  11. package/dist/entrypoints/index.js +1 -1
  12. package/dist/entrypoints/remote.js +1 -1
  13. package/dist/entrypoints/server.js +3 -3
  14. package/dist/entrypoints/telegram/voice.d.ts +2 -0
  15. package/dist/entrypoints/telegram/voice.d.ts.map +1 -0
  16. package/dist/entrypoints/telegram/voice.js +18 -0
  17. package/dist/entrypoints/telegram.d.ts +1 -0
  18. package/dist/entrypoints/telegram.d.ts.map +1 -1
  19. package/dist/entrypoints/telegram.js +43 -0
  20. package/dist/entrypoints/testing.js +1 -1
  21. package/dist/entrypoints/tracking/performance.js +3 -3
  22. package/dist/index-0jdempdr.js +69 -0
  23. package/dist/{index-mdyhr36s.js → index-zbzagr9k.js} +127 -61
  24. package/dist/telegram/voice-waveform-pcm.d.ts +21 -0
  25. package/dist/telegram/voice-waveform-pcm.d.ts.map +1 -0
  26. package/dist/telegram/voice-waveform.d.ts +67 -0
  27. package/dist/telegram/voice-waveform.d.ts.map +1 -0
  28. package/llms/stitchkit.2.txt +36 -174
  29. package/llms/stitchkit.3.txt +186 -0
  30. package/llms/stitchkit.txt +6 -3
  31. package/llms/telegram-voice.txt +29 -0
  32. package/llms/telegram.2.txt +71 -0
  33. package/llms/telegram.txt +51 -59
  34. package/llms-full.txt +101 -2
  35. package/llms.txt +4 -3
  36. package/package.json +5 -1
@@ -37,56 +37,6 @@ function endpointHasArguments(endpoint) {
37
37
  return Boolean(endpoint.params || endpoint.input || endpoint.multipart);
38
38
  }
39
39
 
40
- // src/browser/client-multipart.ts
41
- function isFileDescriptor(value) {
42
- return typeof value === "object" && value !== null && !(value instanceof Blob) && "uri" in value && typeof value.uri === "string" && "name" in value && typeof value.name === "string" && "type" in value && typeof value.type === "string";
43
- }
44
- function isMultipartFile(value) {
45
- return value instanceof Blob || isFileDescriptor(value);
46
- }
47
- function appendMultipartFile(form, field, file) {
48
- const sink = form;
49
- sink.append(field, file);
50
- }
51
- function appendFormFields(formData, values, skipKeys) {
52
- for (const [key, value] of Object.entries(values)) {
53
- if (skipKeys.has(key) || value === undefined || value === null)
54
- continue;
55
- formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
56
- }
57
- }
58
- function buildMultipartForm(descriptor, values) {
59
- const formData = new FormData;
60
- const fileFields = new Set(Object.keys(descriptor.files));
61
- for (const [field, policy] of Object.entries(descriptor.files)) {
62
- const value = values[field];
63
- if (value === undefined) {
64
- if (policy.required !== false) {
65
- throw refuseLocally(field, `Missing multipart file field: ${field}`);
66
- }
67
- continue;
68
- }
69
- if (policy.multiple === true) {
70
- if (!Array.isArray(value) || value.length === 0) {
71
- throw refuseLocally(field, `Multipart file field "${field}" must be a non-empty array`);
72
- }
73
- for (const file of value) {
74
- if (!isMultipartFile(file)) {
75
- throw refuseLocally(field, `Invalid multipart file field: ${field}`);
76
- }
77
- appendMultipartFile(formData, field, file);
78
- }
79
- continue;
80
- }
81
- if (!isMultipartFile(value)) {
82
- throw refuseLocally(field, `Invalid multipart file field: ${field}`);
83
- }
84
- appendMultipartFile(formData, field, value);
85
- }
86
- appendFormFields(formData, values, fileFields);
87
- return formData;
88
- }
89
-
90
40
  // src/browser/client-url.ts
91
41
  function isParamArray(value) {
92
42
  return Array.isArray(value) && value.every((item) => typeof item === "string" || typeof item === "number");
@@ -184,7 +134,7 @@ function compileSegmentTest(pattern, markers) {
184
134
  const expression = new RegExp(`^${source}$`);
185
135
  return (actual) => expression.test(actual);
186
136
  }
187
- function extractParamNames(path) {
137
+ function routeParamNames(path) {
188
138
  const matches = path.match(/:(\w+)/g);
189
139
  const names = matches ? matches.map((match) => match.slice(1)) : [];
190
140
  const wildcard = parseTrailingWildcard(path);
@@ -213,7 +163,7 @@ function fillPathParams(path, args) {
213
163
  }
214
164
  function stripConsumedArgs(args, path, scopeKeys) {
215
165
  const consumed = new Set(scopeKeys);
216
- for (const name of extractParamNames(path))
166
+ for (const name of routeParamNames(path))
217
167
  consumed.add(name);
218
168
  const remaining = {};
219
169
  for (const [key, value] of Object.entries(args)) {
@@ -258,6 +208,118 @@ function joinClientBaseUrl(baseUrl, relativeUrl) {
258
208
  return `${base}${path}`;
259
209
  }
260
210
 
211
+ // src/browser/client-bound.ts
212
+ var WRAPPERS = new Set([
213
+ "optional",
214
+ "nullable",
215
+ "default",
216
+ "prefault",
217
+ "nonoptional",
218
+ "readonly",
219
+ "catch"
220
+ ]);
221
+ function collectDeclaredFields(schema, into) {
222
+ if (!isRecord(schema))
223
+ return false;
224
+ const def = isRecord(schema.def) ? schema.def : {};
225
+ if (isRecord(schema.shape)) {
226
+ for (const key of Object.keys(schema.shape))
227
+ into.add(key);
228
+ return def.catchall === undefined;
229
+ }
230
+ if (def.type === "union" && Array.isArray(def.options)) {
231
+ let closed = true;
232
+ for (const option of def.options)
233
+ closed = collectDeclaredFields(option, into) && closed;
234
+ return closed;
235
+ }
236
+ if (def.type === "intersection") {
237
+ const left = collectDeclaredFields(def.left, into);
238
+ return collectDeclaredFields(def.right, into) && left;
239
+ }
240
+ if (def.type === "pipe")
241
+ return collectDeclaredFields(def.in, into);
242
+ if (typeof def.type === "string" && WRAPPERS.has(def.type))
243
+ return collectDeclaredFields(def.innerType, into);
244
+ return false;
245
+ }
246
+ function boundEndpointArguments(endpoint, contractPrefix, config, surface = "request") {
247
+ const scopeKeys = config?.stripPrefixKeys ?? [];
248
+ const declared = new Set(scopeKeys);
249
+ const staticPrefix = typeof config?.pathPrefix === "string" ? config.pathPrefix : "";
250
+ for (const name of routeParamNames(`${staticPrefix}/${contractPrefix}${endpoint.path}`))
251
+ declared.add(name);
252
+ let closed = true;
253
+ if (endpoint.params)
254
+ closed = collectDeclaredFields(endpoint.params, declared) && closed;
255
+ if (surface === "request" || inputIsQuery(endpoint.method)) {
256
+ if (endpoint.input)
257
+ closed = collectDeclaredFields(endpoint.input, declared) && closed;
258
+ }
259
+ if (surface === "request")
260
+ for (const name of Object.keys(endpoint.multipart?.files ?? {}))
261
+ declared.add(name);
262
+ const bound = config?.bound ?? {};
263
+ const values = {};
264
+ for (const [key, value] of Object.entries(bound)) {
265
+ if (value !== undefined && declared.has(key))
266
+ values[key] = value;
267
+ }
268
+ const takesArguments = endpointHasArguments(endpoint) || scopeKeys.length > 0;
269
+ const complete = !takesArguments || Object.keys(values).length > 0 && closed && [...declared].every((key) => Object.hasOwn(values, key));
270
+ return { values, complete };
271
+ }
272
+
273
+ // src/browser/client-multipart.ts
274
+ function isFileDescriptor(value) {
275
+ return typeof value === "object" && value !== null && !(value instanceof Blob) && "uri" in value && typeof value.uri === "string" && "name" in value && typeof value.name === "string" && "type" in value && typeof value.type === "string";
276
+ }
277
+ function isMultipartFile(value) {
278
+ return value instanceof Blob || isFileDescriptor(value);
279
+ }
280
+ function appendMultipartFile(form, field, file) {
281
+ const sink = form;
282
+ sink.append(field, file);
283
+ }
284
+ function appendFormFields(formData, values, skipKeys) {
285
+ for (const [key, value] of Object.entries(values)) {
286
+ if (skipKeys.has(key) || value === undefined || value === null)
287
+ continue;
288
+ formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
289
+ }
290
+ }
291
+ function buildMultipartForm(descriptor, values) {
292
+ const formData = new FormData;
293
+ const fileFields = new Set(Object.keys(descriptor.files));
294
+ for (const [field, policy] of Object.entries(descriptor.files)) {
295
+ const value = values[field];
296
+ if (value === undefined) {
297
+ if (policy.required !== false) {
298
+ throw refuseLocally(field, `Missing multipart file field: ${field}`);
299
+ }
300
+ continue;
301
+ }
302
+ if (policy.multiple === true) {
303
+ if (!Array.isArray(value) || value.length === 0) {
304
+ throw refuseLocally(field, `Multipart file field "${field}" must be a non-empty array`);
305
+ }
306
+ for (const file of value) {
307
+ if (!isMultipartFile(file)) {
308
+ throw refuseLocally(field, `Invalid multipart file field: ${field}`);
309
+ }
310
+ appendMultipartFile(formData, field, file);
311
+ }
312
+ continue;
313
+ }
314
+ if (!isMultipartFile(value)) {
315
+ throw refuseLocally(field, `Invalid multipart file field: ${field}`);
316
+ }
317
+ appendMultipartFile(formData, field, value);
318
+ }
319
+ appendFormFields(formData, values, fileFields);
320
+ return formData;
321
+ }
322
+
261
323
  // src/browser/stream.ts
262
324
  function ndjsonLine(rawLine) {
263
325
  return (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).trim();
@@ -701,7 +763,7 @@ function createClient2(contract, configOrClient, contractConfig) {
701
763
  for (const [key, endpoint] of typedEntries(contract.endpoints)) {
702
764
  if (endpoint.expose && !endpoint.expose.includes("HTTP"))
703
765
  continue;
704
- setClientMethod(client, key, createEndpointMethod(endpoint, namedOperation(makeExecutor(endpoint), `${contract.meta.prefix}.${String(key)}`), contractConfig));
766
+ setClientMethod(client, key, createEndpointMethod(endpoint, namedOperation(makeExecutor(endpoint), `${contract.meta.prefix}.${String(key)}`), boundEndpointArguments(endpoint, contract.meta.prefix, contractConfig)));
705
767
  }
706
768
  return client;
707
769
  }
@@ -742,22 +804,25 @@ function isHttpAdapter(value) {
742
804
  function setClientMethod(target, key, method) {
743
805
  target[key] = method;
744
806
  }
745
- function createEndpointMethod(endpoint, execute, contractConfig) {
746
- const hasScopedArguments = (contractConfig?.stripPrefixKeys?.length ?? 0) > 0;
747
- if (endpointHasArguments(endpoint) || hasScopedArguments) {
748
- const method = (requestArgs) => settle(execute, readClientRequestArgs(requestArgs), undefined);
807
+ function createEndpointMethod(endpoint, execute, bound) {
808
+ if (!bound.complete) {
809
+ const readArgs = (requestArgs) => ({
810
+ ...readClientRequestArgs(requestArgs),
811
+ ...bound.values
812
+ });
813
+ const method = (requestArgs) => settle(execute, readArgs(requestArgs), undefined);
749
814
  return Object.assign(method, {
750
815
  withOptions: (...args) => {
751
816
  refuseExtraWithOptionsArguments(endpoint, args.length, 2);
752
- return settle(execute, readClientRequestArgs(args[0]), readClientRequestOptions(endpoint, args[1]));
817
+ return settle(execute, readArgs(args[0]), readClientRequestOptions(endpoint, args[1]));
753
818
  }
754
819
  });
755
820
  }
756
- const method = () => settle(execute, {}, undefined);
821
+ const method = () => settle(execute, { ...bound.values }, undefined);
757
822
  return Object.assign(method, {
758
823
  withOptions: (...args) => {
759
824
  refuseExtraWithOptionsArguments(endpoint, args.length, 1);
760
- return settle(execute, {}, readClientRequestOptions(endpoint, args[0]));
825
+ return settle(execute, { ...bound.values }, readClientRequestOptions(endpoint, args[0]));
761
826
  }
762
827
  });
763
828
  }
@@ -813,8 +878,9 @@ function createUrlBuilder2(contract, source, contractConfig) {
813
878
  for (const [key, endpoint] of typedEntries(contract.endpoints)) {
814
879
  if (endpoint.expose && !endpoint.expose.includes("HTTP"))
815
880
  continue;
881
+ const bound = boundEndpointArguments(endpoint, contract.meta.prefix, contractConfig, "url");
816
882
  setClientMethod(builder, key, (args) => {
817
- const plan = planClientRequest(endpoint, contract.meta.prefix, args ?? {}, contractConfig);
883
+ const plan = planClientRequest(endpoint, contract.meta.prefix, { ...args, ...bound.values }, contractConfig);
818
884
  if (endpoint.method !== "GET" && endpoint.method !== "DELETE" && Object.keys(plan.remainingArgs).length > 0) {
819
885
  const fields = Object.keys(plan.remainingArgs).join(", ");
820
886
  throw new Error(`URL builder for ${endpoint.method} ${endpoint.path} received non-URL fields: ${fields}`);
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The waveform of a recording from its decoded PCM: mono, 16-bit, little-endian
3
+ * (`ffmpeg -i <audio> -ac 1 -ar 8000 -f s16le <file>`).
4
+ *
5
+ * The file is read in chunks, so an hour of audio never sits in memory; the
6
+ * waveform needs the loudness of each part, not the bandwidth, and 8 kHz keeps
7
+ * six hours under 350 MB of PCM. The recording being sent is never this file:
8
+ * the PCM is a side copy, and what is uploaded stays byte for byte what it was.
9
+ */
10
+ export interface ReadTelegramVoiceWaveformOptions {
11
+ /** Stops the read between chunks with the signal's reason. */
12
+ readonly signal?: AbortSignal;
13
+ }
14
+ /**
15
+ * The packed waveform `sendVoice` takes, from a PCM file. A file with no
16
+ * sample is refused (`empty-pcm`), and so is one that ends inside a sample or
17
+ * shrinks while it is read (`truncated-pcm`): a waveform is never made up.
18
+ * The refusal names the reason, not the path.
19
+ */
20
+ export declare function readTelegramVoiceWaveform(pcmPath: string, options?: ReadTelegramVoiceWaveformOptions): Promise<string>;
21
+ //# sourceMappingURL=voice-waveform-pcm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice-waveform-pcm.d.ts","sourceRoot":"","sources":["../../src/telegram/voice-waveform-pcm.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAYH,MAAM,WAAW,gCAAgC;IAC/C,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,gCAAqC,GAC7C,OAAO,CAAC,MAAM,CAAC,CAoCjB"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The waveform of a Telegram voice message: the bars a client draws under the
3
+ * play button.
4
+ *
5
+ * Telegram stores it as a run of 5-bit levels packed little-endian — a voice
6
+ * note sent by a Telegram client carries 100 of them, 63 bytes. The public Bot
7
+ * API has no field for it, and Telegram then draws its own; a local Bot API
8
+ * server can accept one in `sendVoice`, and such a server says so in `getMe`
9
+ * (`supports_voice_waveform`, `voice_waveform_version`).
10
+ *
11
+ * The levels follow Telegram Desktop: each of the 100 parts of the recording
12
+ * keeps its loudest sample, and the scale is 1.8 times the mean of those
13
+ * peaks, never below a floor — a loud recording does not flatten its quiet
14
+ * parts to nothing, and a quiet one is not stretched into a loud-looking one.
15
+ * Silence stays at zero.
16
+ *
17
+ * Nothing here touches a file or the network, so the server that packs a
18
+ * waveform and the page that draws it read one format.
19
+ */
20
+ /** Parts of the recording a waveform describes. */
21
+ export declare const TELEGRAM_VOICE_WAVEFORM_SAMPLES = 100;
22
+ /** The highest level of a bar: levels are 5 bits, `0`–`31`. */
23
+ export declare const TELEGRAM_VOICE_WAVEFORM_MAX_LEVEL = 31;
24
+ /** The version of the `sendVoice` waveform field a Bot API server declares in `getMe`. */
25
+ export declare const TELEGRAM_VOICE_WAVEFORM_VERSION = 1;
26
+ /**
27
+ * Why a waveform was not made or not read.
28
+ *
29
+ * - `peak-count` — `packTelegramVoiceWaveform` takes exactly 100 peaks.
30
+ * - `peak-value` — a peak is not an integer from `0` to `32768`.
31
+ * - `malformed` — the waveform text is not base64.
32
+ * - `empty-pcm` — the PCM has no sample: there is nothing to draw.
33
+ * - `truncated-pcm` — the PCM ends inside a sample, or ended before its size.
34
+ */
35
+ export type TelegramVoiceWaveformRefusal = 'peak-count' | 'peak-value' | 'malformed' | 'empty-pcm' | 'truncated-pcm';
36
+ export declare class TelegramVoiceWaveformError extends Error {
37
+ readonly reason: TelegramVoiceWaveformRefusal;
38
+ constructor(reason: TelegramVoiceWaveformRefusal);
39
+ }
40
+ /**
41
+ * The waveform `sendVoice` takes, from the loudest absolute sample of each of
42
+ * the 100 equal parts of a recording (16-bit PCM: `0`–`32768`): base64 of 63
43
+ * bytes. `readTelegramVoiceWaveform` from `stitchkit/telegram` finds the
44
+ * peaks in a PCM file and calls this.
45
+ */
46
+ export declare function packTelegramVoiceWaveform(peaks: ArrayLike<number>): string;
47
+ /**
48
+ * The levels of a waveform, each `0`–`31`, for drawing it: one per 5 bits, so
49
+ * the 63 bytes `packTelegramVoiceWaveform` makes give 100, and a waveform
50
+ * Telegram drew itself gives however many it holds. Text that is not base64
51
+ * is refused, never read as silence.
52
+ */
53
+ export declare function unpackTelegramVoiceWaveform(waveform: string): number[];
54
+ /** What a Bot API server said in `getMe` about the `sendVoice` waveform field. */
55
+ export interface TelegramVoiceWaveformSupport {
56
+ /** The server takes the waveform this module packs: it declares version 1. */
57
+ readonly supported: boolean;
58
+ /** The version it declares; `null` when it declares none (the public Bot API). */
59
+ readonly version: number | null;
60
+ }
61
+ /**
62
+ * Whether the server behind a `getMe` answer takes the waveform: the `result`
63
+ * of `getMe` as it came, any shape. A server that declares nothing, or another
64
+ * version, does not — and a voice sent there gets whatever Telegram draws.
65
+ */
66
+ export declare function readTelegramVoiceWaveformSupport(me: unknown): TelegramVoiceWaveformSupport;
67
+ //# sourceMappingURL=voice-waveform.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice-waveform.d.ts","sourceRoot":"","sources":["../../src/telegram/voice-waveform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,mDAAmD;AACnD,eAAO,MAAM,+BAA+B,MAAM,CAAC;AACnD,+DAA+D;AAC/D,eAAO,MAAM,iCAAiC,KAAK,CAAC;AACpD,0FAA0F;AAC1F,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAWjD;;;;;;;;GAQG;AACH,MAAM,MAAM,4BAA4B,GACpC,YAAY,GACZ,YAAY,GACZ,WAAW,GACX,WAAW,GACX,eAAe,CAAC;AAEpB,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,QAAQ,CAAC,MAAM,EAAE,4BAA4B,CAAC;IAE9C,YAAY,MAAM,EAAE,4BAA4B,EAI/C;CACF;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,GAAG,MAAM,CA0B1E;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAetE;AAED,kFAAkF;AAClF,MAAM,WAAW,4BAA4B;IAC3C,8EAA8E;IAC9E,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,kFAAkF;IAClF,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACjC;AAED;;;;GAIG;AACH,wBAAgB,gCAAgC,CAAC,EAAE,EAAE,OAAO,GAAG,4BAA4B,CAS1F"}
@@ -1,11 +1,13 @@
1
- # stitchkit — stitchkit docs slice, part 2 of 2
1
+ # stitchkit — stitchkit docs slice, part 2 of 3
2
2
 
3
3
  > Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
4
4
  > `llms.txt` in this package.
5
+ > Continues in `llms/stitchkit.3.txt`.
5
6
 
6
7
  Parts of this slice:
7
8
  - `llms/stitchkit.txt`: Guide: Getting started (docs/guide/getting-started.md) · Guide: Typed client (docs/guide/client.md)
8
- - `llms/stitchkit.2.txt`: Guide: Typed client (docs/guide/client.md) · API reference: `stitchkit` (docs/api/reference.md)
9
+ - `llms/stitchkit.2.txt`: Guide: Typed client (docs/guide/client.md)
10
+ - `llms/stitchkit.3.txt`: API reference: `stitchkit` (docs/api/reference.md)
9
11
 
10
12
  Also read:
11
13
  - see `llms/contract.txt` for the Contracts guide
@@ -366,6 +368,8 @@ interface ContractClientConfig {
366
368
  * they are not also sent there (the endpoint's own path `:params` are
367
369
  * stripped automatically; list any *extra* keys here). */
368
370
  stripPrefixKeys?: string[]
371
+ /** Arguments given once for every call — see "Bound arguments" below. */
372
+ bound?: Record<string, unknown>
369
373
  }
370
374
  ```
371
375
 
@@ -386,6 +390,36 @@ List it in `stripPrefixKeys` so it lands in the URL **and is removed from the
386
390
  query/body** — otherwise it would be sent twice. Endpoint path `:params` are
387
391
  stripped for you; only extra prefix keys need listing.
388
392
 
393
+ ### Bound arguments
394
+
395
+ A client that always calls with the same value — a site that knows its `slug` for the whole page
396
+ load, a tenant-scoped service — states the value once in `bound`. The key leaves the arguments of
397
+ every method, in the type and at the call, and a method whose every argument is bound is called
398
+ with none:
399
+
400
+ ```ts
401
+ // site contract: GET /:slug/session, GET /:slug/courses/:courseSlug, POST /:slug/orders { item }
402
+ const site = createClient(siteContract, http, { bound: { slug } })
403
+
404
+ site.session() // GET /api/site/acme/session
405
+ site.course({ courseSlug }) // GET /api/site/acme/courses/intro
406
+ site.order({ item: 'book' }) // POST /api/site/acme/orders body: { item }
407
+ site.session.withOptions({ signal })
408
+ site.course({ slug, courseSlug }) // type error: `slug` is not an argument any more
409
+ ```
410
+
411
+ - The value travels where the caller's argument would: a path parameter, a key `pathPrefix`
412
+ consumes, a query parameter of a `GET` / `DELETE`, a body or multipart field.
413
+ - An endpoint receives a bound key only if it declares it — as a path parameter, a prefix key, or a
414
+ field of its `params` / `input` object schema. A bound `lang` reaches the operations whose input
415
+ has `lang` and is not added to the others.
416
+ - A bound value wins over the same key passed by an untyped caller.
417
+ - `createClients`, `createScopedClients` (per scope), `createUrlBuilder`, `createUrlBuilders` and
418
+ `createScopedUrlBuilders` take the same option. A URL builder binds what a URL carries: path and
419
+ prefix keys, and the input of a `GET` / `DELETE`.
420
+ - Write the object in place (`{ bound: { slug } }`): the keys are read from its type, so a value
421
+ typed `Record<string, string>` names no key and binds nothing in the types.
422
+
389
423
  ## React data layer
390
424
 
391
425
  stitchkit does not ship a hook engine. Pair the typed client with
@@ -695,175 +729,3 @@ may be retried once; do not replay a multi-step callback or treat any `403` as e
695
729
  This is per-instance coordination. Route all writes through it; shared tabs/processes
696
730
  need storage-level locking. Replace the local session counter and refresh queue when
697
731
  adopting these primitives instead of retaining two independent lifetimes.
698
-
699
- ==============================================================================
700
- # API reference: `stitchkit` (docs/api/reference.md)
701
- ==============================================================================
702
-
703
- ## `stitchkit`
704
-
705
- The browser-and-server entrypoint. Re-exports everything from
706
- [`stitchkit/contract`](#stitchkitcontract), plus the client and browser realtime.
707
-
708
- ### Client
709
-
710
- | Export | Kind | Summary |
711
- |--------|------|---------|
712
- | `createClient` | function | build a typed client from a contract — [guide](../guide/client.md#createclient) |
713
- | `createClients` | function | build one exact typed client per contract from a registry; accepts the same scoped config and transports as `createClient` |
714
- | `createScopedClients` | function | build one registry routed by contract scope; arrays compose contracts into one namespace |
715
- | `createScopedUrlBuilders` | function | build one URL registry routed by contract scope; arrays compose contracts into one namespace |
716
- | `ScopeClientConfigs` | _type_ | per-scope routing configuration consumed by scoped clients and URL builders |
717
- | `ScopedClientRegistry` | _type_ | exact composed registry returned by `createScopedClients` |
718
- | `ScopedUrlBuilderRegistry` | _type_ | exact composed registry returned by `createScopedUrlBuilders` |
719
- | `ClientRegistryValue` | _type_ | one contract or a contract array composing one client namespace |
720
- | `ClientContract` | _type_ | HTTP-client-compatible contract value used by scoped registries |
721
- | `RegistryScope` | _type_ | contract-scope union inferred from a scoped client registry value |
722
- | `createUrlBuilder` | function | build synchronous browser-native URLs for all HTTP endpoints; body methods accept URL-bound args only — [guide](../guide/client.md#contract-url-builders) |
723
- | `createUrlBuilders` | function | build one exact URL builder per contract in a registry |
724
- | `readContractIdentity` | function | read the server's contract fingerprint in one call and return it beside the client's own — [guide](../guide/client.md#which-contract-does-the-server-speak) |
725
- | `ContractIdentity` | _type_ | `{ client, server }` fingerprints; `server` is `undefined` when the server answers no identity |
726
- | `UrlBuilderConfig` | _type_ | explicit `{ baseUrl }` source for a URL builder |
727
- | `ClientConfig` | _type_ | config for `createClient`'s bare-fetch mode (2nd arg, no `HttpClient`) |
728
- | `ClientFetch` | _type_ | injectable Fetch-compatible transport used by framework and application-owned adapters |
729
- | `ClientRequestOptions` | _type_ | per-call `{ signal?, onUploadProgress? }` passed through an endpoint callable's `.withOptions(...)`; caller abort is distinct from timeout — [guide](../guide/client.md#per-call-cancellation) |
730
- | `UploadProgress` | _type_ | `{ sentBytes, totalBytes, attempt }` heard by `onUploadProgress`: bytes of the encoded body handed to the network, first `0`, last `totalBytes`, counted again on each transport retry — [guide](../guide/client.md#upload-progress) |
731
- | `uploadInChunks` | function | send a file larger than one request as `init` → parts → `finalize` through three calls the app owns; client-minted id, repeats of a part on a failure that may pass, `finalize` never repeated, cancel checked between parts, progress in file bytes — [guide](../guide/client.md#chunked-uploads) |
732
- | `ChunkedUploadConfig` / `ChunkedUploadStart` / `ChunkedUploadPart` / `ChunkedUploadProgress` | _type_ | the driver's file, part size, retries and three calls; what `init` declares; one part; progress `{ sentBytes, totalBytes, index, chunkCount, attempt }` |
733
- | `ChunkSource` | _type_ | what the driver reads a file through — `size` and `slice(start, end)`; a `Blob` is one, so is a platform file that is not (an Expo `File`), and a part's `bytes` is what its `slice` returns |
734
- | `ContractClientConfig` | _type_ | per-tenant / resource-scoped client config — dynamic `pathPrefix` + `stripPrefixKeys` ([guide](../guide/client.md#contractclientconfig--per-tenant--resource-scoped-clients)) |
735
- | `contractEndpointMatchers` | function | compile exact pathname matchers for selected HTTP contract operations and expected-401 policy |
736
- | `PathPrefixArgs` | _type_ | required string-valued keys exposed to a typed dynamic `pathPrefix` callback |
737
- | `createHttpClient` | function | the Ky-based HTTP transport; on Next.js SSR its first attempt stays request-memoizable while every retry is a distinct transport attempt — [guide](../guide/client.md#createhttpclient) |
738
- | `ApiError` | class | a non-2xx or client failure, with `code` / `status` / `details` / `hint`, optional readonly `traceId` from `x-request-id`, and standard `cause` preserving an injected transport failure |
739
- | `zodIssues` | function | a `ZodError` → structured `{ path, code, message }[]` — the exact projection a `VALIDATION_ERROR` carries in `ApiError.details.issues`, so a caller renders one shape. Also on `stitchkit/server`; same name, one definition |
740
- | `ZodIssueSummary` | _type_ | one structured validation issue (`{ path, code, message }`) — the element type of `details.issues`. Also on `stitchkit/server` |
741
- | `formatZodError` | function | a `ZodError` → a readable, field-summarised string. Also on `stitchkit/server` |
742
- | `HttpClient` | _type_ | the transport interface `createClient` builds on |
743
- | `ConfiguredHttpClient` | _type_ | a framework-created `HttpClient` carrying its readonly `baseUrl` for URL builders |
744
- | `HttpClientConfig` | _type_ | config for `createHttpClient`; retry `limit` counts retries after the initial attempt (default 2 = at most 3 GET attempts), with `statusCodes: []` by default; `fetch` installs an explicit transport and is mutually exclusive with the legacy Bun-only `unix` option — [details](../guide/client.md#createhttpclient) |
745
- | `UnauthorizedMatcher` | _type_ | exact `(pathname) => boolean` policy accepted by `suppressUnauthorizedFor` |
746
- | `RequestOptions` | _type_ | per-call options — params, timeout, response type, `onUploadProgress` |
747
- | `HeaderProvider` | _type_ | static or per-request headers |
748
- | `ApiEvent` | _type_ | a client event — `unauthorized` / `network_error` / `logout` |
749
- | `ApiEventListener` | _type_ | an `ApiEvent` handler |
750
-
751
- ### Realtime (client) & streaming
752
-
753
- | Export | Kind | Summary |
754
- |--------|------|---------|
755
- | `createSocketIOClient` | function | low-level typed Socket.IO transport primitive — [guide](../guide/realtime.md#low-level-transport) |
756
- | `defineRealtimeContract` | function | Zod-first shared Socket.IO event contract — [guide](../guide/realtime.md#zod-first-event-contract) |
757
- | `createRealtimeClient` | function | inferred, runtime-validated Socket.IO client — [guide](../guide/realtime.md#client--createrealtimeclient) |
758
- | `bindRealtimeClient` | function | bind contract validation and typed acknowledgements to an existing Stitchkit client transport without owning its lifecycle |
759
- | `createLiveStateController` | function | keep typed application state current across one source-owned snapshot/event generation with finite pre-snapshot buffering, generation fencing and explicit resync — [guide](../guide/realtime.md#snapshot--event-state-synchronization) |
760
- | `LiveStateController` | _type_ | renderer-neutral `start` / `resync` / `getSnapshot` / `subscribe` / `close` handle |
761
- | `LiveStateControllerConfig` | _type_ | typed source, reducer, explicit event/byte bounds, event sizing and isolated error hooks |
762
- | `LiveStateControllerSnapshot` / `LiveStateControllerStatus` | _types_ | current value plus phase, generation, buffer and application/duplicate/gap/refusal counters |
763
- | `LiveStateControllerStatusSchema` | schema | strict runtime validation for controller status metadata |
764
- | `LiveStatePhaseSchema` / `LiveStatePhase` | schema / _type_ | `idle`, `opening`, `live`, `resync-required`, `unavailable` or `closed` |
765
- | `LiveStateStopReasonSchema` / `LiveStateStopReason` | schema / _type_ | explicit gap, overflow, source loss, controller failure and bounded `controller-capacity` reasons |
766
- | `LiveStateEventDecision` | _type_ | provider-owned reducer result: applied state, duplicate or gap |
767
- | `LiveStateSource` / `LiveStateSourceOpenInput` / `LiveStateSourceOpenResult` | _types_ | host binding for one continuous snapshot/event boundary; transport retry and cursor semantics remain host-owned |
768
- | `LiveStateControllerError` / `LiveStateSubscriberError` | _types_ | isolated observer failure payloads that do not change source or subscriber truth |
769
- | `createRetainedTopics` | function | retained last-value store for sticky events — [guide](../guide/realtime.md#sticky-events) |
770
- | `parseSSE` | function | parse SSE from a `Response`, a web stream or an async byte iterable into an async generator — [guide](../guide/client.md#sse) |
771
- | `parseNDJSON` | function | parse bounded fatal-UTF-8 NDJSON from a `Response`, a `ReadableStream<Uint8Array>` or an `AsyncIterable<Uint8Array>` (a child's stdout); blank keep-alives are skipped, `finalLine: 'require-newline'` makes the delimiter mandatory and `signal` cancels the source — [guide](../guide/client.md#any-byte-source) |
772
- | `createNDJSONDecoder` / `NDJSONDecoder` | function / _type_ | the same bounded NDJSON reading driven by `push(chunk)` / `end()`, for a socket `data` callback |
773
- | `readBoundedBody` / `BoundedBodyOptions` | function / _type_ | the whole body of a `ReadableStream<Uint8Array>` or async byte iterable as bytes, never reading past `maxBytes` plus one chunk; `limitError(observedBytes)` and `abortError(reason)` choose the two errors, the source is cancelled on both, a `null` body is empty — [guide](../guide/client.md#reading-a-body-up-to-a-byte-limit) |
774
- | `StreamByteSource` | _type_ | `Response \| ReadableStream<Uint8Array> \| AsyncIterable<Uint8Array>`, what the NDJSON and SSE readers accept |
775
- | `StreamLineLimitError` / `StreamTruncatedLineError` | class | a line past `maxLineBytes` (`limitBytes`, `lineBytes`; a `RangeError`) and a source ended inside a line under `require-newline` (`lineBytes`; a `SyntaxError`) |
776
- | `resumableIterator` | function | re-open a long-lived stream from the last delivered cursor, with jittered backoff, a caller-owned terminal item and prompt abort — [guide](../guide/client.md#resumable-streams) |
777
- | `createBackoff` | function | exponential backoff with subtractive jitter as a value: `next()` / `reset()` |
778
- | `contractFingerprint` | function | synchronous digest of the operations HTTP carries, whole and per `prefix.key` — [guide](../guide/client.md#which-contract-does-the-server-speak) |
779
- | `ContractFingerprintSchema` / `ContractFingerprint` | schema / _type_ | `{ fingerprint, operations }` — one digest for the set and one per operation |
780
- | `contractIdentityContract` | contract | the operation a server answers its fingerprint with; mount it with `withContractIdentity` |
781
- | `ContractStreamFrameSchema` / `ContractStreamFrame` | schema / _type_ | default on-the-wire `data` / safe `error` / `end` envelope of a contract-first stream |
782
- | `ContractStreamFraming` / `ContractStreamCompletion` | _types_ | opt-in item-vs-envelope framing and terminal-vs-stream-end completion policies |
783
- | `StreamFinalLinePolicy` | _type_ | permissive or newline-required final NDJSON line policy |
784
- | `DEFAULT_CONTRACT_STREAM_FRAME_BYTES` | const | default maximum encoded contract-stream frame: 256 KiB |
785
- | `SocketIOClient` | _type_ | low-level client handle; `emit` reports disconnected drops and `emitWithAck` exposes the native Promise primitive used by validated `request()` |
786
- | `SocketIOClientPeerLoaders` | _type_ | inject `socket.io-client` so a bundler can put it in a self-contained artifact |
787
- | `SocketIOClientConfig` | _type_ | config for `createSocketIOClient` (incl. `retain`, `onConnectError`, `onDroppedEmit`) |
788
- | `SocketEventMap` | _type_ | the shape of an event map |
789
- | `RealtimeClient` | _type_ | validated client inferred from a realtime contract |
790
- | `RealtimeClientOptions` | _type_ | transport options plus rejected-event and metadata-only acknowledged-request phase hooks for `createRealtimeClient` |
791
- | `BoundRealtimeClient` | _type_ | validated non-owning `on`/`emit`/`request` client with no `connect`/`disconnect` |
792
- | `RealtimeClientTransport` | _type_ | minimal existing transport capability accepted by `bindRealtimeClient` |
793
- | `BindRealtimeClientOptions` | _type_ | rejection/logger options for a bound existing transport |
794
- | `RealtimeAcknowledgedEvent` | _type_ | event-name union restricted to definitions with an `ack` schema |
795
- | `RealtimeAcknowledgement` | _type_ | validated acknowledgement output inferred from an event definition |
796
- | `RealtimeRequestArguments` | _type_ | request arguments inferred from an acknowledged event tuple |
797
- | `RealtimeRequestOptions` | _type_ | finite positive native acknowledgement `timeoutMs` plus an optional invocation-scoped `onPhase` observer |
798
- | `RealtimeRequestPhaseSchema` / `RealtimeRequestPhase` | schema / _type_ | closed `engine-handoff` / `engine-ack-received` / `settled` / `timeout` / `disconnected` lifecycle |
799
- | `RealtimeRequestPhaseEventSchema` / `RealtimeRequestPhaseEvent` | schema / _type_ | strict metadata-only `{ requestId, event, phase, elapsedMs }` observation |
800
- | `RealtimeRequestPhaseHook` | _type_ | isolated sync/async observer accepted globally by `RealtimeClientOptions.onRequestPhase` or per invocation by `RealtimeRequestOptions.onPhase` |
801
- | `RealtimeRequestTimeoutError` | class | stable `REALTIME_REQUEST_TIMEOUT` rejection |
802
- | `RealtimeRequestDisconnectedError` | class | stable `REALTIME_REQUEST_DISCONNECTED` rejection, including an immediate disconnected call |
803
- | `RealtimeRequestInvalidAcknowledgementError` | class | invalid ack was reported through `onRejected` and the request rejected |
804
- | `RealtimeRequestRejectedError` | class | the peer refused the frame against its own contract and said so — `reason`, `issues` — instead of leaving the sender to time out ([ADR 0106](../decisions/0106-a-refused-frame-answers-its-sender.md)) |
805
- | `REALTIME_REJECTION_KEY` | const | the reserved acknowledgement key a refusal travels under |
806
- | `RealtimeRejectionEnvelope` | _type_ | the wire shape of a refusal |
807
- | `RealtimeRejectionReport` | _type_ | what the sender is told: event, reason, message, issues |
808
- | `RealtimeRejectionIssue` | _type_ | one refused field, already flattened (`path: '0.v'`) |
809
- | `asRealtimeRejection` | function | recognise a refusal in an acknowledgement value, validating it |
810
- | `RealtimeContract` | _type_ | shared server-to-client and client-to-server event registries |
811
- | `RealtimeEventRegistry` | _type_ | string-keyed registry of event definitions |
812
- | `RealtimeEventDefinition` | _type_ | one tuple-shaped event and optional acknowledgement schema |
813
- | `RealtimeEventArguments` | _type_ | tuple inferred from an event definition |
814
- | `RealtimeEmitArguments` | _type_ | emit arguments including an inferred acknowledgement callback |
815
- | `RealtimeEventHandler` | _type_ | handler inferred from an event definition |
816
- | `InferRealtimeEventMap` | _type_ | inferred Socket.IO-compatible event map |
817
- | `RealtimeRejectDirection` / `RealtimeRejectPhase` / `RealtimeRejectReason` / `RealtimeRejectFault` | _types_ | canonical inferred rejection direction, validation phase, reason and fault classification |
818
- | `RealtimeRejectedEvent` | _type_ | structured rejected event with event, direction, phase, reason and fault |
819
- | `RealtimeRejectedEventHook` | _type_ | sync/async observer for structured realtime rejections |
820
- | `ValidatedRealtimeSocket` | _type_ | runtime-validating `on`/`emit` surface inferred from registries; `emit` returns "accepted by the transport" (`false` only for a client-side disconnected drop) |
821
- | `RetainedTopics` | _type_ | the `createRetainedTopics` handle |
822
- | `ParseSSEOptions` | _type_ | options for `parseSSE` |
823
- | `ParseNDJSONOptions` | _type_ | options for `parseNDJSON` |
824
- | `BackoffPolicySchema` / `BackoffPolicy` | schema / _type_ | `minDelayMs`, `maxDelayMs` and a `0`–`1` jitter fraction; a ceiling below the floor is refused |
825
- | `Backoff` | _type_ | the backoff handle returned by `createBackoff` |
826
- | `ResumableIteratorConfig` | _type_ | caller-owned `open` / `advance` / `isTerminal`, retry policy, abort signal and `onAttempt` observer |
827
- | `ResumableAttempt` | _type_ | attempt number, the delay about to be waited and the error that caused it |
828
-
829
- ### Trace (client)
830
-
831
- Browser-safe W3C trace helpers — the same functions as on
832
- [`stitchkit/observability`](#stitchkitobservability), re-exported so a client
833
- can emit / propagate a `traceparent` (see `HttpClientConfig.trace`).
834
-
835
- | Export | Kind | Summary |
836
- |--------|------|---------|
837
- | `createTraceContext` | function | a fresh root trace |
838
- | `formatTraceparent` | function | render a `traceparent` header value |
839
- | `parseTraceparent` | function | parse a `traceparent` header |
840
- | `childSpan` | function | a child span of a parent trace |
841
- | `TraceContext` | _type_ | `{ traceId, spanId, parentSpanId?, tracestate?, baggage? }` |
842
-
843
- ---
844
-
845
- ### Session lifetime and credential coordination
846
-
847
- `createSessionScope` (`stitchkit`) returns the generic `SessionScope`: `replace(context)`
848
- creates a new login lifetime (including same-account relogin), `capture()` returns
849
- its `SessionOperation<T>`, `clear()` invalidates it, `stop()` permanently closes
850
- the host, and `owns(operation)` answers whether an operation is this scope's current
851
- one — `current()` alone cannot tell an operation of another scope. Operations expose `id`, `generation`, `context`, `signal`, `current()` and
852
- `assertCurrent()`. `run(callback)` checks both success and failure across an await;
853
- `deliver(callback)` admits a synchronous final send/state change or returns false.
854
- `bindFetch(fetch, headers?)` guards every attempt and scopes its abort signal. Wrap
855
- the complete client call in `run` too: headers are not the response body boundary.
856
- Expired work throws `SessionExpiredError`, not a refresh instruction; when the work
857
- itself failed, that failure is its `cause`.
858
-
859
- `createSessionCredentials` accepts `SessionCredentialsConfig`:
860
- `scope`, `refresh(credentials, signal)`, `storage.write(session, credentials)`,
861
- `storage.clear()`, `maxPendingWrites` (128), `refreshTimeoutMs` (30000, at most one
862
- hour) and `storageTimeoutMs` (30000, at most one hour): a storage call past it
863
- rejects and frees the queue, so `logout()` still clears; when the late call settles,
864
- storage is written again from memory, or cleared when nobody is logged in. `SessionCredentials` provides `login`, `logout`, `read(operation)` and
865
- `refresh(operation)`. Concurrent refresh calls in one generation share the same
866
- promise. Logout invalidates memory before its returned persistence promise settles.
867
- Storage errors and queue-capacity refusals reject; callers must handle them. All
868
- writes must pass through the same instance. There is no cross-process/tab lock,
869
- provider error classifier or automatic retry of arbitrary application callbacks.