@foir/sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +805 -4
  2. package/README.md +46 -15
  3. package/dist/auth/auth.d.ts +104 -1
  4. package/dist/auth/index.d.ts +12 -6
  5. package/dist/auth/operations.d.ts +85 -64
  6. package/dist/auth/ops.d.ts +99 -0
  7. package/dist/auth.js +775 -106
  8. package/dist/chunk-IGNLWT3H.js +35 -0
  9. package/dist/chunk-OHYVKTGB.js +45 -0
  10. package/dist/chunk-TAL5H6VA.js +39 -0
  11. package/dist/client.js +25 -31
  12. package/dist/codegen/block-registry.d.ts +13 -19
  13. package/dist/codegen/block-registry.js +3 -31
  14. package/dist/codegen/block-scaffold.d.ts +12 -21
  15. package/dist/codegen/block-scaffold.js +3 -41
  16. package/dist/codegen/index.d.ts +9 -4
  17. package/dist/codegen/index.js +7 -11
  18. package/dist/codegen/item-registry.d.ts +28 -0
  19. package/dist/codegen/item-registry.js +7 -0
  20. package/dist/codegen/item-scaffold.d.ts +29 -0
  21. package/dist/codegen/item-scaffold.js +7 -0
  22. package/dist/codegen/preset.d.ts +14 -7
  23. package/dist/codegen/shared.d.ts +20 -9
  24. package/dist/content/content-renderer.d.ts +90 -24
  25. package/dist/content/index.d.ts +13 -7
  26. package/dist/content/richtext.d.ts +66 -18
  27. package/dist/content.js +227 -80
  28. package/dist/data/builtins.d.ts +302 -92
  29. package/dist/data/client.d.ts +97 -25
  30. package/dist/data/document.d.ts +251 -0
  31. package/dist/data/index.d.ts +38 -19
  32. package/dist/data/manifest.d.ts +266 -3
  33. package/dist/data/schema.d.ts +78 -8
  34. package/dist/data/selection.d.ts +231 -37
  35. package/dist/data/subjects.d.ts +221 -0
  36. package/dist/data/subscription-document.d.ts +75 -0
  37. package/dist/data/subscriptions.d.ts +181 -0
  38. package/dist/data/transport.d.ts +255 -37
  39. package/dist/data/ws-transport.d.ts +197 -0
  40. package/dist/data.js +1419 -45
  41. package/dist/graphql/cdn-route.d.ts +12 -28
  42. package/dist/media/index.d.ts +6 -2
  43. package/dist/media/media.d.ts +2 -2
  44. package/dist/media/screen-capture.d.ts +81 -0
  45. package/dist/media.js +97 -0
  46. package/dist/next.js +663 -182
  47. package/dist/push.js +700 -90
  48. package/dist/react/FoirFeedback.d.ts +62 -0
  49. package/dist/react/feedback-notes.d.ts +101 -0
  50. package/dist/react/index.d.ts +7 -1
  51. package/dist/react.js +1272 -194
  52. package/dist/realtime.js +1 -1
  53. package/dist/server/events-client.d.ts +279 -0
  54. package/dist/server/index.d.ts +4 -0
  55. package/dist/server.js +298 -0
  56. package/dist/transport/foir-http.d.ts +23 -6
  57. package/dist/transport/persisted-query.d.ts +68 -0
  58. package/dist/transport/retry.d.ts +1 -1
  59. package/package.json +13 -1
  60. package/dist/chunk-ADO5FJNM.js +0 -30
package/dist/next.js CHANGED
@@ -80,27 +80,6 @@ var FoirRequestError = class extends Error {
80
80
  return typeof seconds === "number" && seconds > 0 ? seconds * 1e3 : void 0;
81
81
  }
82
82
  };
83
- function readFoirRateLimit(headers) {
84
- const raw = {
85
- limit: headers.get("X-RateLimit-Limit"),
86
- remaining: headers.get("X-RateLimit-Remaining"),
87
- resetAt: headers.get("X-RateLimit-Reset")
88
- };
89
- if (raw.limit === null || raw.remaining === null || raw.resetAt === null) {
90
- return void 0;
91
- }
92
- const limit = Number(raw.limit);
93
- const remaining = Number(raw.remaining);
94
- const resetAt = Number(raw.resetAt);
95
- if (!Number.isFinite(limit) || !Number.isFinite(remaining) || !Number.isFinite(resetAt)) {
96
- return void 0;
97
- }
98
- return { limit, remaining, resetAt };
99
- }
100
- function readFoirRetryAfterMs(headers) {
101
- const seconds = Number(headers.get("Retry-After"));
102
- return Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : void 0;
103
- }
104
83
  function buildFoirHeaders(input) {
105
84
  const headers = {
106
85
  "Content-Type": "application/json",
@@ -119,6 +98,13 @@ function buildFoirHeaders(input) {
119
98
  }
120
99
  return headers;
121
100
  }
101
+ function foirApiEndpoint(apiUrl, path) {
102
+ const base = apiUrl.trim().replace(/\/+$/, "").replace(/\/graphql$/i, "");
103
+ if (!base) {
104
+ throw new FoirRequestError("[foir] apiUrl is empty \u2014 pass the Foir API origin");
105
+ }
106
+ return base + path;
107
+ }
122
108
  function readFoirEnvelope(json) {
123
109
  if (json.errors?.length) {
124
110
  const msg = json.errors.map((e) => e.message).join("; ");
@@ -136,18 +122,14 @@ function readFoirEnvelope(json) {
136
122
  return json.data;
137
123
  }
138
124
 
139
- // src/graphql/cdn-route.ts
140
- var CDN_PATH = "/cdn/graphql";
141
- function isCdnEligible(env, documentText, bearerToken) {
142
- if (bearerToken) return false;
143
- if (isFoirPreview(env)) return false;
144
- const apiKey = resolveFoirApiKey(env);
145
- if (!apiKey?.startsWith("pk_")) return false;
146
- return !/\bmutation\b/.test(documentText);
125
+ // src/transport/persisted-query.ts
126
+ var FOIR_CDN_GRAPHQL_PATH = "/cdn/graphql";
127
+ function persistedQueryExtension(hash) {
128
+ return { persistedQuery: { version: 1, sha256Hash: hash } };
147
129
  }
148
130
  function buildCdnUrl(endpoint, apiKey, hash, variables) {
149
131
  const url = new URL(endpoint);
150
- url.pathname = url.pathname.replace(/\/graphql\/?$/, "") + CDN_PATH;
132
+ url.pathname = url.pathname.replace(/\/graphql\/?$/, "") + FOIR_CDN_GRAPHQL_PATH;
151
133
  url.searchParams.set("key", apiKey);
152
134
  url.searchParams.set("extensions", JSON.stringify(persistedQueryExtension(hash)));
153
135
  if (variables && Object.keys(variables).length > 0) {
@@ -155,189 +137,688 @@ function buildCdnUrl(endpoint, apiKey, hash, variables) {
155
137
  }
156
138
  return url.toString();
157
139
  }
158
- function persistedQueryExtension(hash) {
159
- return { persistedQuery: { version: 1, sha256Hash: hash } };
160
- }
161
140
  async function documentHash(documentText) {
162
- const digest = await crypto.subtle.digest(
163
- "SHA-256",
164
- new TextEncoder().encode(documentText)
165
- );
141
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(documentText));
166
142
  return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
167
143
  }
168
144
  var PERSISTED_QUERY_NOT_FOUND = "PERSISTED_QUERY_NOT_FOUND";
169
145
  var NOT_SHAREABLE = "NOT_SHAREABLE";
146
+ async function hasFoirErrorCode(res, ...codes) {
147
+ try {
148
+ const body = await res.clone().json();
149
+ return body.errors?.some((e) => e.extensions?.code !== void 0 && codes.includes(e.extensions.code)) ?? false;
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
170
154
 
171
- // src/graphql/foir-request.ts
172
- async function foirRequest(env, document, variables, options) {
173
- const endpoint = env.PLATFORM_API_URL;
174
- const apiKey = resolveFoirApiKey(env);
175
- if (!endpoint || !apiKey) {
155
+ // src/data/document.ts
156
+ function buildPathTrie(paths) {
157
+ const root = { self: false, children: /* @__PURE__ */ new Map() };
158
+ for (const path of paths) {
159
+ let node = root;
160
+ for (const segment of path.split(".")) {
161
+ if (!segment) continue;
162
+ let next = node.children.get(segment);
163
+ if (!next) {
164
+ next = { self: false, children: /* @__PURE__ */ new Map() };
165
+ node.children.set(segment, next);
166
+ }
167
+ node = next;
168
+ }
169
+ node.self = true;
170
+ }
171
+ return root;
172
+ }
173
+ function childFor(node, field) {
174
+ return node.children.get(field.key) ?? (field.alias ? node.children.get(field.alias) : void 0);
175
+ }
176
+ function segmentFor(node, field) {
177
+ return node.children.has(field.key) ? field.key : field.alias ?? field.key;
178
+ }
179
+ var PROTECTED_ROOT_FIELD = "_id";
180
+ var MAX_QUERY_COMPLEXITY = 1e4;
181
+ var MAX_EMITTED_FIELDS = 4 * MAX_QUERY_COMPLEXITY;
182
+ var newBudget = () => ({ fields: 0, emitted: 0, stopped: false });
183
+ function charge(ctx, n = 1) {
184
+ ctx.budget.fields += n;
185
+ ctx.budget.emitted += n;
186
+ }
187
+ function mayExpand(ctx, depth) {
188
+ if (depth <= 1) return false;
189
+ if (ctx.budget.emitted > MAX_EMITTED_FIELDS) {
190
+ ctx.budget.stopped = true;
191
+ return false;
192
+ }
193
+ return true;
194
+ }
195
+ function printFields(fields, ctx, omit, pick, isRoot, path, depth) {
196
+ const parts = [];
197
+ for (const field of fields) {
198
+ if (field.relation) {
199
+ const named = pick ? childFor(pick, field) : void 0;
200
+ if (named) {
201
+ const segment = segmentFor(pick, field);
202
+ throw new FoirRequestError(
203
+ `[foir] pick "${path}${segment}": "${segment}" is a relation, and relations are not part of the default document \u2014 no pick can select one. ` + (path ? (
204
+ // Nested: there is no `include` form that reaches here at all.
205
+ // `include` addresses the ROOT model's own relations, and (nested)
206
+ // a related model's — never one reached through a composite or a
207
+ // union member. Saying "use include" would send the caller to a
208
+ // call that refuses them a second time.
209
+ `A relation at this position cannot be reached by \`include\` either \u2014 that addresses the model's own relations, not one inside a composite or a union member. Read it through the field that owns it, or drop "${path}${segment}" from the pick`
210
+ ) : `Use include: { ${segment}: true } instead`)
211
+ );
212
+ }
213
+ continue;
214
+ }
215
+ const protectedField = isRoot && field.key === PROTECTED_ROOT_FIELD;
216
+ const omitChild = omit ? childFor(omit, field) : void 0;
217
+ if (omitChild?.self && !protectedField) continue;
218
+ let pickChild;
219
+ if (pick) {
220
+ pickChild = childFor(pick, field);
221
+ if (!pickChild && !protectedField) continue;
222
+ if (pickChild?.self) pickChild = void 0;
223
+ }
224
+ const head = field.alias ? `${field.alias}: ${field.key}` : field.key;
225
+ const childPath = `${path}${pick && childFor(pick, field) ? segmentFor(pick, field) : field.key}.`;
226
+ if (field.truncated) {
227
+ if (field.union && mayExpand(ctx, depth)) {
228
+ const body = printUnion(field.union, ctx, omitChild, pickChild, childPath, depth - 1);
229
+ if (body) {
230
+ charge(ctx);
231
+ parts.push(`${head} ${body}`);
232
+ continue;
233
+ }
234
+ }
235
+ charge(ctx, 2);
236
+ parts.push(`${head} { __typename }`);
237
+ continue;
238
+ }
239
+ if (field.model) {
240
+ const body = printModelTree(field.model, ctx, depth);
241
+ if (body) {
242
+ charge(ctx);
243
+ parts.push(`${head} { ${body} }`);
244
+ }
245
+ continue;
246
+ }
247
+ if (field.union) {
248
+ const body = printUnion(field.union, ctx, omitChild, pickChild, childPath, depth);
249
+ if (body) {
250
+ charge(ctx);
251
+ parts.push(`${head} ${body}`);
252
+ }
253
+ continue;
254
+ }
255
+ if (field.fields?.length) {
256
+ const body = printFields(field.fields, ctx, omitChild, pickChild, false, childPath, depth);
257
+ if (body) {
258
+ charge(ctx);
259
+ parts.push(`${head} { ${body} }`);
260
+ }
261
+ continue;
262
+ }
263
+ charge(ctx);
264
+ parts.push(head);
265
+ }
266
+ return parts.join(" ");
267
+ }
268
+ function printModelTree(modelKey, ctx, depth) {
269
+ const model = ctx.source.models[modelKey];
270
+ if (!model?.selection) {
271
+ throw new FoirRequestError(
272
+ `[foir] the result shape references the model "${modelKey}", which publishes no selection \u2014 re-run \`foir types\``
273
+ );
274
+ }
275
+ const narrowing = ctx.record?.modelKey === modelKey ? ctx.record : void 0;
276
+ const body = printFields(
277
+ model.selection.fields,
278
+ ctx,
279
+ narrowing?.omit,
280
+ narrowing?.pick,
281
+ true,
282
+ "",
283
+ depth
284
+ );
285
+ const includes = narrowing?.include ? printIncludes(ctx.source, model, modelKey, narrowing.include, ctx, depth) : "";
286
+ if (!body) {
287
+ return includes;
288
+ }
289
+ return includes ? `${body} ${includes}` : body;
290
+ }
291
+ var NO_FIELDS = { self: false, children: /* @__PURE__ */ new Map() };
292
+ function addressesMembers(node, union) {
293
+ for (const member of union.members) {
294
+ if (node.children.has(member.typeName)) return true;
295
+ }
296
+ return false;
297
+ }
298
+ function printUnion(unionName, ctx, omit, pick, path, depth) {
299
+ const union = ctx.unions[unionName];
300
+ if (!union) {
176
301
  throw new FoirRequestError(
177
- "[foir] PLATFORM_API_URL or PLATFORM_API_KEY is not set \u2014 add them to .env"
302
+ `[foir] the selection tree names the union "${unionName}", which is not in selectionUnions \u2014 re-run \`foir types\`, or pass selectionUnions alongside selections`
178
303
  );
179
304
  }
305
+ const perVariantPick = pick !== void 0 && addressesMembers(pick, union);
306
+ const perVariantOmit = omit !== void 0 && addressesMembers(omit, union);
307
+ charge(ctx);
308
+ const parts = ["__typename"];
309
+ const chargeBefore = ctx.budget.fields;
310
+ let widestMember = 0;
311
+ for (const member of union.members) {
312
+ let memberPick = pick;
313
+ if (perVariantPick) {
314
+ const named = pick.children.get(member.typeName);
315
+ memberPick = named === void 0 ? NO_FIELDS : named.self ? void 0 : named;
316
+ }
317
+ let memberOmit = omit;
318
+ if (perVariantOmit) {
319
+ const named = omit.children.get(member.typeName);
320
+ if (named?.self) continue;
321
+ memberOmit = named;
322
+ }
323
+ const memberPath = perVariantPick ? `${path}${member.typeName}.` : path;
324
+ const memberStart = ctx.budget.fields;
325
+ const body = printFields(member.fields, ctx, memberOmit, memberPick, false, memberPath, depth);
326
+ const memberCost = ctx.budget.fields - memberStart;
327
+ ctx.budget.fields = memberStart;
328
+ if (memberCost > widestMember) widestMember = memberCost;
329
+ if (body) parts.push(`... on ${member.typeName} { ${body} }`);
330
+ }
331
+ ctx.budget.fields = chargeBefore + widestMember;
332
+ return `{ ${parts.join(" ")} }`;
333
+ }
334
+ function printIncludes(source, model, modelKey, include, ctx, depth) {
335
+ const parts = [];
336
+ for (const [key, value] of Object.entries(include)) {
337
+ if (value === void 0 || value === false) continue;
338
+ const relation = model.relations?.find((r) => r.key === key);
339
+ if (!relation) {
340
+ throw new FoirRequestError(
341
+ `[foir] include "${key}": ${modelKey} has no such relation \u2014 re-run \`foir types\` if the model has changed`
342
+ );
343
+ }
344
+ const nested = value && typeof value === "object" && "include" in value ? value["include"] : void 0;
345
+ const body = relation.targets?.length ? printPolymorphicRelation(source, relation, ctx, nested, depth) : printRelationTarget(source, relation.target ?? "", ctx, nested, relation.key, depth);
346
+ charge(ctx, relation.connection ? 1 + CONNECTION_WRAPPER_FIELDS : 1);
347
+ parts.push(`${key} ${relation.connection ? wrapRelationConnection(body) : `{ ${body} }`}`);
348
+ }
349
+ return parts.join(" ");
350
+ }
351
+ var CONNECTION_WRAPPER_FIELDS = 9;
352
+ function wrapRelationConnection(body) {
353
+ return `{ edges { cursor node { ${body} } } pageInfo { hasNextPage hasPreviousPage startCursor endCursor } totalCount }`;
354
+ }
355
+ function printRelationTarget(source, targetKey, ctx, nested, relationKey, depth) {
356
+ const target = source.models[targetKey];
357
+ if (!target?.selection) {
358
+ throw new FoirRequestError(
359
+ `[foir] include "${relationKey}": no selection published for its target model "${targetKey}" \u2014 re-run \`foir types\``
360
+ );
361
+ }
362
+ const bare = { source, unions: ctx.unions, budget: ctx.budget };
363
+ const body = printFields(target.selection.fields, bare, void 0, void 0, true, "", depth);
364
+ const includes = nested ? printIncludes(source, target, targetKey, nested, bare, depth) : "";
365
+ return includes ? `${body} ${includes}` : body;
366
+ }
367
+ function printPolymorphicRelation(source, relation, ctx, nested, depth) {
368
+ charge(ctx);
369
+ const parts = ["__typename"];
370
+ const chargeBefore = ctx.budget.fields;
371
+ let widestTarget = 0;
372
+ for (const targetKey of relation.targets ?? []) {
373
+ const target = source.models[targetKey];
374
+ if (!target?.selection) {
375
+ throw new FoirRequestError(
376
+ `[foir] include "${relation.key}": no selection published for its target model "${targetKey}" \u2014 re-run \`foir types\``
377
+ );
378
+ }
379
+ const targetStart = ctx.budget.fields;
380
+ const body = printRelationTarget(source, targetKey, ctx, nested, relation.key, depth);
381
+ const targetCost = ctx.budget.fields - targetStart;
382
+ ctx.budget.fields = targetStart;
383
+ if (targetCost > widestTarget) widestTarget = targetCost;
384
+ if (body) parts.push(`... on ${target.typeName} { ${body} }`);
385
+ }
386
+ ctx.budget.fields = chargeBefore + widestTarget;
387
+ return parts.join(" ");
388
+ }
389
+ var GRAPHQL_TYPE_REF = /^\[?\[?[_A-Za-z][_0-9A-Za-z]*!?\]?!?\]?!?$/;
390
+ function buildArguments(args, op, opLabel) {
391
+ const declared = op.args;
392
+ const definitions = [];
393
+ const call = [];
394
+ const variables = {};
395
+ for (const name of Object.keys(args).sort()) {
396
+ const value = args[name];
397
+ if (value === void 0) continue;
398
+ if (!declared?.includes(name)) {
399
+ throw new FoirRequestError(
400
+ `[foir] ${opLabel} does not take an argument "${name}" \u2014 it takes ${declared?.length ? declared.join(", ") : "no arguments"}`
401
+ );
402
+ }
403
+ const type = op.argTypes?.[name];
404
+ if (!type) {
405
+ throw new FoirRequestError(
406
+ `[foir] ${opLabel}: the manifest publishes no type for the argument "${name}", so it cannot be sent as a variable \u2014 and inferring one from the value would guess wrong on every enum. Re-run \`foir types\` against a server that publishes argTypes, or use foir.raw() with your own variable definitions`
407
+ );
408
+ }
409
+ if (!GRAPHQL_TYPE_REF.test(type)) {
410
+ throw new FoirRequestError(
411
+ `[foir] ${opLabel}: the manifest gives the argument "${name}" the type "${type}", which is not a GraphQL type reference`
412
+ );
413
+ }
414
+ definitions.push(`$${name}: ${type}`);
415
+ call.push(`${name}: $${name}`);
416
+ variables[name] = toVariableValue(value, `${opLabel} argument "${name}"`);
417
+ }
418
+ return {
419
+ definitions: definitions.length ? `(${definitions.join(", ")})` : "",
420
+ call: call.length ? `(${call.join(", ")})` : "",
421
+ variables
422
+ };
423
+ }
424
+ function toVariableValue(value, label) {
425
+ if (value === null) return null;
426
+ const kind = typeof value;
427
+ if (kind === "string" || kind === "boolean") return value;
428
+ if (kind === "number") {
429
+ if (!Number.isFinite(value)) {
430
+ throw new FoirRequestError(
431
+ `[foir] ${label} is ${String(value)}, which has no JSON form and cannot be sent`
432
+ );
433
+ }
434
+ return value;
435
+ }
436
+ if (kind === "bigint") {
437
+ const asNumber = Number(value);
438
+ if (!Number.isSafeInteger(asNumber)) {
439
+ throw new FoirRequestError(
440
+ `[foir] ${label} is the bigint ${String(value)}, which is outside the range JSON can carry exactly`
441
+ );
442
+ }
443
+ return asNumber;
444
+ }
445
+ if (value instanceof Date) {
446
+ if (Number.isNaN(value.getTime())) {
447
+ throw new FoirRequestError(`[foir] ${label} is an invalid Date`);
448
+ }
449
+ return value.toISOString();
450
+ }
451
+ if (Array.isArray(value)) {
452
+ return value.filter((item) => item !== void 0).map((item, index) => toVariableValue(item, `${label}[${index}]`));
453
+ }
454
+ if (kind === "object") {
455
+ const out = {};
456
+ for (const [key, child] of Object.entries(value)) {
457
+ if (child === void 0) continue;
458
+ out[key] = toVariableValue(child, `${label}.${key}`);
459
+ }
460
+ return out;
461
+ }
462
+ throw new FoirRequestError(
463
+ `[foir] ${label} is a ${kind}, which has no JSON form and cannot be sent`
464
+ );
465
+ }
466
+ function payloadRecordPaths(payload) {
467
+ if (payload.kind === "record") {
468
+ return payload.model ? [{ path: [], modelKey: payload.model }] : [];
469
+ }
470
+ const found = [];
471
+ const visit = (fields, prefix) => {
472
+ for (const field of fields ?? []) {
473
+ const at = [...prefix, field.alias ?? field.key];
474
+ if (field.model) found.push({ path: at, modelKey: field.model });
475
+ visit(field.fields, at);
476
+ }
477
+ };
478
+ visit(payload.fields, []);
479
+ return found;
480
+ }
481
+ function printPayload(payload, ctx, root, opLabel, depth) {
482
+ switch (payload.kind) {
483
+ case "leaf":
484
+ return void 0;
485
+ case "record": {
486
+ if (!payload.model) {
487
+ throw new FoirRequestError(
488
+ `[foir] ${opLabel}: the result shape says it is a record but names no model \u2014 re-run \`foir types\``
489
+ );
490
+ }
491
+ return printModelTree(payload.model, ctx, depth);
492
+ }
493
+ case "union": {
494
+ if (!payload.union) {
495
+ throw new FoirRequestError(
496
+ `[foir] ${opLabel}: the result shape says it is a union but names none \u2014 re-run \`foir types\``
497
+ );
498
+ }
499
+ return printUnion(payload.union, ctx, root.omit, root.pick, "", depth).slice(2, -2);
500
+ }
501
+ case "object": {
502
+ if (!payload.fields?.length) {
503
+ throw new FoirRequestError(
504
+ `[foir] ${opLabel}: the result shape is an object with no fields \u2014 re-run \`foir types\``
505
+ );
506
+ }
507
+ return printFields(payload.fields, ctx, root.omit, root.pick, false, "", depth);
508
+ }
509
+ default:
510
+ throw new FoirRequestError(
511
+ `[foir] ${opLabel}: the result shape has the kind "${String(payload.kind)}", which this client does not know how to print \u2014 upgrade @foir/sdk`
512
+ );
513
+ }
514
+ }
515
+ var DEFAULT_DEPTH = 1;
516
+ function planFoirNamespaceCall(source, call) {
517
+ const namespace = source.namespaces?.[call.namespace];
518
+ if (!namespace) {
519
+ throw new FoirRequestError(
520
+ `[foir] no namespace "${call.namespace}" in this credential's surface \u2014 re-run \`foir types\``
521
+ );
522
+ }
523
+ const opDef = namespace.ops?.[call.op];
524
+ if (!opDef) {
525
+ throw new FoirRequestError(
526
+ `[foir] the namespace "${call.namespace}" has no op "${call.op}" for this credential \u2014 re-run \`foir types\``
527
+ );
528
+ }
529
+ return planCall(
530
+ source,
531
+ opDef,
532
+ `${call.namespace}.${call.op}`,
533
+ operationName(call.namespace, call.op),
534
+ call
535
+ );
536
+ }
537
+ function planCall(source, opDef, opLabel, name, call) {
538
+ const payload = opDef.payload;
539
+ if (!payload) {
540
+ throw new FoirRequestError(
541
+ `[foir] ${opLabel}: the manifest publishes no result shape for this op, so there is nothing to print \u2014 and synthesising one client-side is exactly the guess this client refuses to make. Re-run \`foir types\` against a server that publishes op payloads`
542
+ );
543
+ }
544
+ if (payload.error) {
545
+ throw new FoirRequestError(
546
+ `[foir] ${opLabel}: the server could not resolve a result shape for this op: ${payload.error}`
547
+ );
548
+ }
549
+ if (call.omit && call.pick) {
550
+ throw new FoirRequestError(
551
+ `[foir] ${opLabel}: "omit" and "pick" are mutually exclusive \u2014 pass one or the other`
552
+ );
553
+ }
554
+ if (call.omit?.includes(PROTECTED_ROOT_FIELD)) {
555
+ throw new FoirRequestError(
556
+ `[foir] omit "${PROTECTED_ROOT_FIELD}": "${PROTECTED_ROOT_FIELD}" is required for correctness and cannot be removed`
557
+ );
558
+ }
559
+ const depth = call.depth ?? DEFAULT_DEPTH;
560
+ if (!Number.isInteger(depth) || depth < DEFAULT_DEPTH) {
561
+ throw new FoirRequestError(
562
+ `[foir] ${opLabel}: depth must be a whole number of union levels, ${DEFAULT_DEPTH} or more \u2014 got ${String(call.depth)}. ${DEFAULT_DEPTH} is the complete-by-default document; each level above it expands one further union`
563
+ );
564
+ }
565
+ const omit = call.omit?.length ? buildPathTrie(call.omit) : void 0;
566
+ const pick = call.pick?.length ? buildPathTrie(call.pick) : void 0;
567
+ const include = call.include && Object.keys(call.include).length ? call.include : void 0;
568
+ const narrowed = Boolean(omit || pick || include);
569
+ const recordPaths = payloadRecordPaths(payload);
570
+ const records = new Set(recordPaths.map((entry) => entry.modelKey));
571
+ if (records.size > 1 && narrowed) {
572
+ throw new FoirRequestError(
573
+ `[foir] ${opLabel}: the result carries records of more than one model (${[...records].sort().join(", ")}), so "include"/"pick"/"omit" do not say which one they mean \u2014 call it without them and narrow with foir.raw()`
574
+ );
575
+ }
576
+ const recordModel = records.size === 1 ? [...records][0] : void 0;
577
+ if (include && !recordModel) {
578
+ throw new FoirRequestError(
579
+ `[foir] ${opLabel}: "include" names relations of a record, and this op returns none`
580
+ );
581
+ }
582
+ const ctx = {
583
+ source,
584
+ unions: source.selectionUnions ?? {},
585
+ record: recordModel ? { modelKey: recordModel, omit, pick, include } : void 0,
586
+ budget: newBudget()
587
+ };
588
+ const root = recordModel ? {} : { omit, pick };
589
+ const selection = printPayload(payload, ctx, root, opLabel, depth);
590
+ if (selection === "") {
591
+ throw new FoirRequestError(
592
+ `[foir] ${opLabel}: the selection is empty after applying pick/omit \u2014 a GraphQL selection set cannot be empty`
593
+ );
594
+ }
595
+ charge(ctx);
596
+ if (depth > DEFAULT_DEPTH && (ctx.budget.stopped || ctx.budget.fields > MAX_QUERY_COMPLEXITY)) {
597
+ const reason = ctx.budget.stopped ? `expands to more than ${MAX_EMITTED_FIELDS} fields to print, which is past what this client will build in one call` : `makes this document select ${ctx.budget.fields} fields, over the server's limit of ${MAX_QUERY_COMPLEXITY}`;
598
+ throw new FoirRequestError(
599
+ `[foir] ${opLabel}: depth ${depth} ${reason}. Each level re-expands every stopping point inside the expansion, so spend the level on less: narrow with "pick"/"omit" \u2014 including per-member, pick: { <field>: { on: { <MemberType>: [...] } } } \u2014 or ask for depth ${depth - 1}`
600
+ );
601
+ }
602
+ const args = buildArguments(call.args, opDef, opLabel);
603
+ const keyword = opDef.mutation ? "mutation" : "query";
604
+ const body = selection === void 0 ? "" : ` { ${selection} }`;
605
+ return {
606
+ document: `${keyword} ${name}${args.definitions} { ${opDef.field}${args.call}${body} }`,
607
+ variables: args.variables,
608
+ mutation: opDef.mutation === true,
609
+ rootField: opDef.field,
610
+ fields: ctx.budget.fields,
611
+ records: recordPaths
612
+ };
613
+ }
614
+ function operationName(scope, op) {
615
+ const parts = `${scope} ${op}`.split(/[^0-9A-Za-z]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1));
616
+ const name = parts.join("");
617
+ return /^[_A-Za-z]/.test(name) ? name : `Foir${name}`;
618
+ }
619
+
620
+ // src/data/transport.ts
621
+ function foirDataEndpoint(apiUrl, path) {
622
+ return foirApiEndpoint(apiUrl, path);
623
+ }
624
+ async function resolveBearerToken(config) {
625
+ const source = config.bearerToken;
626
+ if (typeof source === "function") return await source() ?? void 0;
627
+ return source ?? void 0;
628
+ }
629
+ function foirRoute(input) {
630
+ if (!input.apiKey.startsWith("pk_")) return { lane: "origin", reason: "key" };
631
+ if (input.bearerToken) return { lane: "origin", reason: "bearer" };
632
+ if (input.mutation) return { lane: "origin", reason: "operation" };
633
+ if (input.channel === "draft") return { lane: "origin", reason: "channel" };
634
+ return { lane: "shared" };
635
+ }
636
+ async function executeFoirDocument(config, plan) {
637
+ const data = await runFoirDocument(config, plan.document, plan.mutation, plan.variables);
638
+ if (!(plan.rootField in data)) {
639
+ throw new FoirRequestError(
640
+ `[foir] the response has no "${plan.rootField}" field` + (Object.keys(data).length ? ` (got ${Object.keys(data).join(", ")})` : "")
641
+ );
642
+ }
643
+ return data[plan.rootField];
644
+ }
645
+ async function runFoirDocument(config, document, mutation, variables) {
646
+ const doFetch = config.fetch ?? globalThis.fetch;
647
+ const endpoint = foirDataEndpoint(config.apiUrl, "/graphql");
648
+ const bearerToken = await resolveBearerToken(config);
180
649
  const headers = buildFoirHeaders({
181
- apiKey,
182
- draftChannel: isFoirPreview(env),
183
- bearerToken: options?.bearerToken
650
+ apiKey: config.apiKey,
651
+ draftChannel: config.channel === "draft",
652
+ bearerToken,
653
+ extra: config.headers
654
+ });
655
+ const hash = await documentHash(document);
656
+ const route = foirRoute({
657
+ apiKey: config.apiKey,
658
+ bearerToken,
659
+ mutation,
660
+ channel: config.channel
184
661
  });
185
- const documentText = print2(document);
662
+ const post = (body) => doFetch(endpoint, {
663
+ method: "POST",
664
+ headers,
665
+ body: JSON.stringify(body),
666
+ ...config.requestInit
667
+ });
668
+ const extensions = persistedQueryExtension(hash);
186
669
  let res;
187
670
  try {
188
- if (isCdnEligible(env, documentText, options?.bearerToken)) {
189
- const hash = await documentHash(documentText);
190
- let shared = await fetch(buildCdnUrl(endpoint, apiKey, hash, variables), {
671
+ if (route.lane === "shared") {
672
+ res = await doFetch(buildCdnUrl(endpoint, config.apiKey, hash, variables), {
191
673
  method: "GET",
192
- headers
674
+ headers,
675
+ ...config.requestInit
193
676
  });
194
- if (await isPersistedQueryMiss(shared)) {
195
- shared = await fetch(buildCdnUrl(endpoint, apiKey, hash, variables), {
196
- method: "POST",
197
- headers,
198
- body: JSON.stringify({
199
- query: documentText,
200
- variables,
201
- extensions: persistedQueryExtension(hash)
202
- })
203
- });
204
- }
205
- if (await isSharedRefusal(shared)) {
206
- res = await fetch(endpoint, {
207
- method: "POST",
208
- headers,
209
- body: JSON.stringify({ query: documentText, variables })
210
- });
211
- } else {
212
- res = shared;
677
+ if (await hasFoirErrorCode(res, PERSISTED_QUERY_NOT_FOUND, NOT_SHAREABLE)) {
678
+ res = await post({ query: document, variables, extensions });
213
679
  }
214
680
  } else {
215
- res = await fetch(endpoint, {
216
- method: "POST",
217
- headers,
218
- body: JSON.stringify({ query: documentText, variables })
219
- });
681
+ res = await post({ variables, extensions });
682
+ if (await hasFoirErrorCode(res, PERSISTED_QUERY_NOT_FOUND)) {
683
+ res = await post({ query: document, variables, extensions });
684
+ }
220
685
  }
221
686
  } catch (err) {
222
687
  throw new FoirRequestError("[foir] network error", { cause: err });
223
688
  }
224
- options?.onRateLimit?.(readFoirRateLimit(res.headers));
225
689
  if (!res.ok) {
226
- const errors = await readErrorEnvelope(res);
227
- const first = errors?.[0]?.message;
228
- throw new FoirRequestError(
229
- first ? `[foir] HTTP ${res.status} ${res.statusText}: ${first}` : `[foir] HTTP ${res.status} ${res.statusText}`,
230
- { status: res.status, graphQLErrors: errors }
231
- );
690
+ const errors = await readErrorBody(res);
691
+ const detail = errors ? `: ${errors.map((e) => e.message).join("; ")}` : "";
692
+ throw new FoirRequestError(`[foir] HTTP ${res.status} ${res.statusText}${detail}`, {
693
+ status: res.status,
694
+ graphQLErrors: errors
695
+ });
232
696
  }
233
697
  const json = await res.json();
234
698
  return readFoirEnvelope(json);
235
699
  }
236
- async function readErrorEnvelope(res) {
237
- let errors;
700
+ async function readErrorBody(res) {
238
701
  try {
239
- const body = await res.json();
240
- errors = body.errors;
702
+ const json = await res.json();
703
+ return json?.errors?.length ? json.errors : void 0;
241
704
  } catch {
242
- errors = void 0;
243
- }
244
- const headerRetryMs = readFoirRetryAfterMs(res.headers);
245
- if (headerRetryMs === void 0) return errors;
246
- const seconds = Math.round(headerRetryMs / 1e3);
247
- if (!errors?.length) {
248
- return [
249
- {
250
- message: res.statusText || `HTTP ${res.status}`,
251
- extensions: { code: "RATE_LIMITED", retryAfter: seconds }
252
- }
253
- ];
254
- }
255
- if (errors[0].extensions?.retryAfter === void 0) {
256
- errors[0] = {
257
- ...errors[0],
258
- extensions: { ...errors[0].extensions, retryAfter: seconds }
259
- };
705
+ return void 0;
260
706
  }
261
- return errors;
262
707
  }
263
- async function isSharedRefusal(res) {
264
- if (res.ok) return false;
708
+
709
+ // src/data/manifest.ts
710
+ async function fetchFoirManifest(config) {
711
+ const url = foirDataEndpoint(config.apiUrl, "/v1/manifest");
712
+ const doFetch = config.fetch ?? globalThis.fetch;
713
+ let res;
265
714
  try {
266
- const body = await res.clone().json();
267
- return body.errors?.some((e) => e.extensions?.code === NOT_SHAREABLE) ?? false;
268
- } catch {
269
- return false;
715
+ res = await doFetch(url, {
716
+ method: "GET",
717
+ headers: buildFoirHeaders({
718
+ apiKey: config.apiKey,
719
+ draftChannel: config.channel === "draft",
720
+ bearerToken: await resolveBearerToken(config),
721
+ extra: config.headers
722
+ }),
723
+ ...config.requestInit
724
+ });
725
+ } catch (err) {
726
+ throw new FoirRequestError("[foir] network error", { cause: err });
270
727
  }
271
- }
272
- async function isPersistedQueryMiss(res) {
273
- try {
274
- const body = await res.clone().json();
275
- return body.errors?.some(
276
- (e) => e.extensions?.code === PERSISTED_QUERY_NOT_FOUND
277
- ) ?? false;
278
- } catch {
279
- return false;
728
+ if (!res.ok) {
729
+ throw new FoirRequestError(
730
+ `[foir] GET /v1/manifest failed: HTTP ${res.status} ${res.statusText}`,
731
+ { status: res.status }
732
+ );
280
733
  }
734
+ return await res.json();
281
735
  }
282
736
 
283
- // src/auth/operations.ts
284
- import { parse } from "graphql";
285
- var AUTH_RESULT_FIELDS = "token refreshToken customerId email";
286
- var CustomerLoginDocument = parse(
287
- `mutation CustomerLogin($email: String!, $password: String!) {
288
- customerLogin(email: $email, password: $password) { ${AUTH_RESULT_FIELDS} }
289
- }`
290
- );
291
- var CustomerRegisterDocument = parse(
292
- `mutation CustomerRegister($email: String!, $password: String!) {
293
- customerRegister(email: $email, password: $password) { ${AUTH_RESULT_FIELDS} }
294
- }`
295
- );
296
- var CustomerRefreshTokenDocument = parse(
297
- `mutation CustomerRefreshToken($refreshToken: String!) {
298
- customerRefreshToken(refreshToken: $refreshToken) { ${AUTH_RESULT_FIELDS} }
299
- }`
300
- );
301
- var CustomerRequestOTPDocument = parse(
302
- `mutation CustomerRequestOTP($email: String!) {
303
- customerRequestOTP(email: $email)
304
- }`
305
- );
306
- var CustomerLoginOTPDocument = parse(
307
- `mutation CustomerLoginOTP($email: String!, $otp: String!) {
308
- customerLoginOTP(email: $email, otp: $otp) { ${AUTH_RESULT_FIELDS} }
309
- }`
310
- );
311
- var CustomerLoginWithProviderDocument = parse(
312
- `mutation CustomerLoginWithProvider($input: ProviderLoginInput!) {
313
- customerLoginWithProvider(input: $input) { redirectUrl token }
314
- }`
315
- );
316
- var CustomerProviderCallbackDocument = parse(
317
- `mutation CustomerProviderCallback($input: ProviderCallbackInput!) {
318
- customerProviderCallback(input: $input) { ${AUTH_RESULT_FIELDS} }
319
- }`
320
- );
321
- var CustomerProviderVerifyOTPDocument = parse(
322
- `mutation CustomerProviderVerifyOTP($input: ProviderOTPVerifyInput!) {
323
- customerProviderVerifyOTP(input: $input) { ${AUTH_RESULT_FIELDS} }
324
- }`
325
- );
326
- var AuthProvidersDocument = parse(
327
- `query AuthProviders {
328
- authProviders { key name type isDefault }
329
- }`
330
- );
331
- var CustomerJoinWaitlistDocument = parse(
332
- `mutation CustomerJoinWaitlist($email: String!) {
333
- customerJoinWaitlist(email: $email) { id email status }
334
- }`
335
- );
336
- var CustomerSignupContextDocument = parse(
337
- `query CustomerSignupContext {
338
- customerSignupContext { signupMode }
339
- }`
340
- );
737
+ // src/auth/ops.ts
738
+ var AUTH_OPS = {
739
+ // Pre-credential reads a login screen renders itself from.
740
+ authConfig: "authConfig",
741
+ authProviders: "authProviders",
742
+ defaultAuthProvider: "defaultAuthProvider",
743
+ customerSignupContext: "customerSignupContext",
744
+ // Post-credential self reads.
745
+ currentUser: "currentUser",
746
+ myProviderToken: "myProviderToken",
747
+ // Methods.
748
+ customerLogin: "customerLogin",
749
+ customerRegister: "customerRegister",
750
+ customerRequestOTP: "customerRequestOTP",
751
+ customerLoginOTP: "customerLoginOTP",
752
+ // Session lifecycle.
753
+ customerRefreshToken: "customerRefreshToken",
754
+ customerLogout: "customerLogout",
755
+ customerJoinWaitlist: "customerJoinWaitlist",
756
+ // Password management and account lifecycle — the block that had no path.
757
+ customerRequestPasswordReset: "customerRequestPasswordReset",
758
+ customerResetPassword: "customerResetPassword",
759
+ customerUpdatePassword: "customerUpdatePassword",
760
+ customerVerifyEmail: "customerVerifyEmail",
761
+ deleteMyAccount: "deleteMyAccount",
762
+ // External identity providers.
763
+ customerLoginWithProvider: "customerLoginWithProvider",
764
+ customerProviderCallback: "customerProviderCallback",
765
+ customerProviderVerifyOTP: "customerProviderVerifyOTP"
766
+ };
767
+ function authClientConfig(env, options) {
768
+ const apiKey = resolveFoirApiKey(env);
769
+ if (!apiKey) {
770
+ throw new FoirRequestError(
771
+ "[foir] no api key configured: set PLATFORM_API_KEY (or PLATFORM_PREVIEW_API_KEY under FOIR_PREVIEW=true)"
772
+ );
773
+ }
774
+ const apiUrl = env.PLATFORM_API_URL;
775
+ if (!apiUrl) {
776
+ throw new FoirRequestError("[foir] no api url configured: set PLATFORM_API_URL");
777
+ }
778
+ return {
779
+ apiUrl,
780
+ apiKey,
781
+ channel: isFoirPreview(env) ? "draft" : "published",
782
+ bearerToken: options?.bearerToken,
783
+ headers: options?.headers,
784
+ fetch: options?.fetch
785
+ };
786
+ }
787
+ var MANIFEST_CACHE_LIMIT = 8;
788
+ var manifestCache = /* @__PURE__ */ new Map();
789
+ function authManifest(config) {
790
+ const key = `${config.apiUrl}\0${config.apiKey}\0${config.channel ?? "published"}`;
791
+ const held = manifestCache.get(key);
792
+ if (held) return held;
793
+ const pending = fetchFoirManifest(config).catch((err) => {
794
+ manifestCache.delete(key);
795
+ throw err;
796
+ });
797
+ manifestCache.set(key, pending);
798
+ while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
799
+ const oldest = manifestCache.keys().next();
800
+ if (oldest.done) break;
801
+ manifestCache.delete(oldest.value);
802
+ }
803
+ return pending;
804
+ }
805
+ async function authOp(env, op, args, options) {
806
+ const config = authClientConfig(env, options);
807
+ const manifest = await authManifest(config);
808
+ const plan = planFoirNamespaceCall(manifest, {
809
+ namespace: "auth",
810
+ op,
811
+ args: args ? stripUndefined(args) : {}
812
+ });
813
+ return executeFoirDocument(config, plan);
814
+ }
815
+ function stripUndefined(args) {
816
+ const out = {};
817
+ for (const [key, value] of Object.entries(args)) {
818
+ if (value !== void 0) out[key] = value;
819
+ }
820
+ return out;
821
+ }
341
822
 
342
823
  // src/auth/auth.ts
343
824
  var TOKEN_KEY = "foir:token";
@@ -345,16 +826,16 @@ var REFRESH_KEY = "foir:refreshToken";
345
826
  var CUSTOMER_ID_KEY = "foir:customerId";
346
827
  var EMAIL_KEY = "foir:email";
347
828
  async function customerLogin(env, vars) {
348
- return (await foirRequest(env, CustomerLoginDocument, vars)).customerLogin;
829
+ return authOp(env, AUTH_OPS.customerLogin, vars);
349
830
  }
350
831
  async function customerRegister(env, vars) {
351
- return (await foirRequest(env, CustomerRegisterDocument, vars)).customerRegister;
832
+ return authOp(env, AUTH_OPS.customerRegister, vars);
352
833
  }
353
834
  async function customerLoginOTP(env, vars) {
354
- return (await foirRequest(env, CustomerLoginOTPDocument, vars)).customerLoginOTP;
835
+ return authOp(env, AUTH_OPS.customerLoginOTP, vars);
355
836
  }
356
837
  async function customerProviderCallback(env, input) {
357
- return (await foirRequest(env, CustomerProviderCallbackDocument, { input })).customerProviderCallback;
838
+ return authOp(env, AUTH_OPS.customerProviderCallback, { input });
358
839
  }
359
840
  async function saveSession(adapter, result) {
360
841
  await adapter.set(TOKEN_KEY, result.token);