@sanity-labs/client-fake-for-test 0.29.0 → 0.30.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.
package/dist/index.d.cts CHANGED
@@ -152,6 +152,13 @@ export declare interface CreateTestClientOptions {
152
152
  * without an entry has none and answers `[]`.
153
153
  */
154
154
  projectFeatures?: Record<string, string[]>;
155
+ /**
156
+ * The functions deployed with the Functions API, which
157
+ * `request({ method: "POST", uri: "/functions/<idOrName>/invoke" })`
158
+ * invokes. Shared by the whole `withConfig` family; add and remove more
159
+ * with {@link TestClient.addFunction} and {@link TestClient.removeFunction}.
160
+ */
161
+ functions?: TestClientFunction[];
155
162
  /**
156
163
  * Opt-in access-control simulation. When set, the client exposes
157
164
  * `request({ url })` that serves `/users/me` (host-aware), the
@@ -953,6 +960,12 @@ export declare type ReleaseType = "asap" | "scheduled" | "undecided";
953
960
  declare interface RequestOptions {
954
961
  url?: string;
955
962
  uri?: string;
963
+ /** `GET` (the default) or `POST`; the fake serves `POST` on the Functions API's invoke route only. */
964
+ method?: "GET" | "POST";
965
+ /** The request body, sent as JSON. */
966
+ body?: unknown;
967
+ /** Request headers; names are case-insensitive. */
968
+ headers?: Record<string, string>;
956
969
  /** Query parameters, appended to the URL after the request tag; an array repeats its key. */
957
970
  query?: Record<string, string | string[]>;
958
971
  signal?: AbortSignal;
@@ -1313,6 +1326,19 @@ export declare interface TestClient {
1313
1326
  * store whose provisioning never completes stays `provisioning`.
1314
1327
  */
1315
1328
  completeOrganizationStoreProvisioning: (organizationId: string) => void;
1329
+ /**
1330
+ * Deploy a function, or replace the one with its id, for every handle of
1331
+ * the family. Throws for an id shorter than 10 characters, an unknown
1332
+ * type, or a name another function holds in the same Blueprint stack.
1333
+ */
1334
+ addFunction: (fn: TestClientFunction) => void;
1335
+ /** Remove the function with this id from the family. Throws when no function has it. */
1336
+ removeFunction: (id: string) => void;
1337
+ /**
1338
+ * Every invocation the Functions API accepted on any handle of the
1339
+ * family, in order. Refused invocations are not recorded.
1340
+ */
1341
+ functionInvocations: () => TestFunctionInvocation[];
1316
1342
  /**
1317
1343
  * Every mutation committed through this client's registry, flattened
1318
1344
  * and in order — `create` / `createOrReplace` / `createIfNotExists` /
@@ -1375,6 +1401,31 @@ export declare interface TestClientAccessControl {
1375
1401
  robot?: true;
1376
1402
  }
1377
1403
 
1404
+ /** A deployed function: what the invoke route looks up by id, or by name within its stack. */
1405
+ export declare interface TestClientFunction {
1406
+ /** The function id, at least 10 characters. */
1407
+ id: string;
1408
+ /** The function's name in its Blueprint stack; unique within the stack. */
1409
+ name: string;
1410
+ type: TestClientFunctionType;
1411
+ /** The Blueprint stack the function was deployed in. */
1412
+ blueprintStackId: string;
1413
+ /** The type of the resource that owns the function. */
1414
+ resourceType: "project" | "organization";
1415
+ /** The id of the project or organization that owns the function. */
1416
+ resourceId: string;
1417
+ }
1418
+
1419
+ /** The function types the Functions API deploys (`src/constants.js`, `SANITY_FUNCTION_*`). */
1420
+ export declare type TestClientFunctionType =
1421
+ | "sanity.function.pubsub"
1422
+ | "sanity.function.document"
1423
+ | "sanity.function.queue"
1424
+ | "sanity.function.durable"
1425
+ | "sanity.function.schedule"
1426
+ | "sanity.function.media-library-asset"
1427
+ | "sanity.function.sync-tag-invalidate";
1428
+
1378
1429
  /**
1379
1430
  * One entry in the token→identity registry (`createTestClient({ identities })`).
1380
1431
  * A handle bound to the entry's token behaves exactly like one configured
@@ -1444,6 +1495,27 @@ export declare interface TestClientResource {
1444
1495
  id: string;
1445
1496
  }
1446
1497
 
1498
+ /** One invocation the Functions API accepted, as the function receives it. */
1499
+ export declare interface TestFunctionInvocation {
1500
+ functionId: string;
1501
+ name: string;
1502
+ blueprintStackId: string;
1503
+ /** The request's `X-Sanity-Scope-Type`. */
1504
+ scopeType: "project" | "organization";
1505
+ /** The request's `X-Sanity-Scope-Id`. */
1506
+ scopeId: string;
1507
+ /** Whether the invocation was synchronous; always `false`, as the fake serves asynchronous invocations only. */
1508
+ sync: boolean;
1509
+ /** The request body's `event`: the function receives `event.data`. */
1510
+ event: {
1511
+ data: Record<string, unknown>;
1512
+ };
1513
+ /** The caller's account-global user id. */
1514
+ invokedBy: {
1515
+ userId: string;
1516
+ };
1517
+ }
1518
+
1447
1519
  /**
1448
1520
  * In-memory document store backing a TestClient. Closure-scoped — created
1449
1521
  * fresh per test, no global state.
package/dist/index.d.ts CHANGED
@@ -152,6 +152,13 @@ export declare interface CreateTestClientOptions {
152
152
  * without an entry has none and answers `[]`.
153
153
  */
154
154
  projectFeatures?: Record<string, string[]>;
155
+ /**
156
+ * The functions deployed with the Functions API, which
157
+ * `request({ method: "POST", uri: "/functions/<idOrName>/invoke" })`
158
+ * invokes. Shared by the whole `withConfig` family; add and remove more
159
+ * with {@link TestClient.addFunction} and {@link TestClient.removeFunction}.
160
+ */
161
+ functions?: TestClientFunction[];
155
162
  /**
156
163
  * Opt-in access-control simulation. When set, the client exposes
157
164
  * `request({ url })` that serves `/users/me` (host-aware), the
@@ -953,6 +960,12 @@ export declare type ReleaseType = "asap" | "scheduled" | "undecided";
953
960
  declare interface RequestOptions {
954
961
  url?: string;
955
962
  uri?: string;
963
+ /** `GET` (the default) or `POST`; the fake serves `POST` on the Functions API's invoke route only. */
964
+ method?: "GET" | "POST";
965
+ /** The request body, sent as JSON. */
966
+ body?: unknown;
967
+ /** Request headers; names are case-insensitive. */
968
+ headers?: Record<string, string>;
956
969
  /** Query parameters, appended to the URL after the request tag; an array repeats its key. */
957
970
  query?: Record<string, string | string[]>;
958
971
  signal?: AbortSignal;
@@ -1313,6 +1326,19 @@ export declare interface TestClient {
1313
1326
  * store whose provisioning never completes stays `provisioning`.
1314
1327
  */
1315
1328
  completeOrganizationStoreProvisioning: (organizationId: string) => void;
1329
+ /**
1330
+ * Deploy a function, or replace the one with its id, for every handle of
1331
+ * the family. Throws for an id shorter than 10 characters, an unknown
1332
+ * type, or a name another function holds in the same Blueprint stack.
1333
+ */
1334
+ addFunction: (fn: TestClientFunction) => void;
1335
+ /** Remove the function with this id from the family. Throws when no function has it. */
1336
+ removeFunction: (id: string) => void;
1337
+ /**
1338
+ * Every invocation the Functions API accepted on any handle of the
1339
+ * family, in order. Refused invocations are not recorded.
1340
+ */
1341
+ functionInvocations: () => TestFunctionInvocation[];
1316
1342
  /**
1317
1343
  * Every mutation committed through this client's registry, flattened
1318
1344
  * and in order — `create` / `createOrReplace` / `createIfNotExists` /
@@ -1375,6 +1401,31 @@ export declare interface TestClientAccessControl {
1375
1401
  robot?: true;
1376
1402
  }
1377
1403
 
1404
+ /** A deployed function: what the invoke route looks up by id, or by name within its stack. */
1405
+ export declare interface TestClientFunction {
1406
+ /** The function id, at least 10 characters. */
1407
+ id: string;
1408
+ /** The function's name in its Blueprint stack; unique within the stack. */
1409
+ name: string;
1410
+ type: TestClientFunctionType;
1411
+ /** The Blueprint stack the function was deployed in. */
1412
+ blueprintStackId: string;
1413
+ /** The type of the resource that owns the function. */
1414
+ resourceType: "project" | "organization";
1415
+ /** The id of the project or organization that owns the function. */
1416
+ resourceId: string;
1417
+ }
1418
+
1419
+ /** The function types the Functions API deploys (`src/constants.js`, `SANITY_FUNCTION_*`). */
1420
+ export declare type TestClientFunctionType =
1421
+ | "sanity.function.pubsub"
1422
+ | "sanity.function.document"
1423
+ | "sanity.function.queue"
1424
+ | "sanity.function.durable"
1425
+ | "sanity.function.schedule"
1426
+ | "sanity.function.media-library-asset"
1427
+ | "sanity.function.sync-tag-invalidate";
1428
+
1378
1429
  /**
1379
1430
  * One entry in the token→identity registry (`createTestClient({ identities })`).
1380
1431
  * A handle bound to the entry's token behaves exactly like one configured
@@ -1444,6 +1495,27 @@ export declare interface TestClientResource {
1444
1495
  id: string;
1445
1496
  }
1446
1497
 
1498
+ /** One invocation the Functions API accepted, as the function receives it. */
1499
+ export declare interface TestFunctionInvocation {
1500
+ functionId: string;
1501
+ name: string;
1502
+ blueprintStackId: string;
1503
+ /** The request's `X-Sanity-Scope-Type`. */
1504
+ scopeType: "project" | "organization";
1505
+ /** The request's `X-Sanity-Scope-Id`. */
1506
+ scopeId: string;
1507
+ /** Whether the invocation was synchronous; always `false`, as the fake serves asynchronous invocations only. */
1508
+ sync: boolean;
1509
+ /** The request body's `event`: the function receives `event.data`. */
1510
+ event: {
1511
+ data: Record<string, unknown>;
1512
+ };
1513
+ /** The caller's account-global user id. */
1514
+ invokedBy: {
1515
+ userId: string;
1516
+ };
1517
+ }
1518
+
1447
1519
  /**
1448
1520
  * In-memory document store backing a TestClient. Closure-scoped — created
1449
1521
  * fresh per test, no global state.
package/dist/index.js CHANGED
@@ -452,6 +452,316 @@ function badRequest(request, description) {
452
452
  body: { error: { description, type: "httpBadRequest" } }
453
453
  });
454
454
  }
455
+ const FUNCTION_INVOKE_PATH = /^\/functions\/([^/]+)\/invoke\/?$/, FUNCTION_TYPES = /* @__PURE__ */ new Set([
456
+ "sanity.function.pubsub",
457
+ "sanity.function.document",
458
+ "sanity.function.queue",
459
+ "sanity.function.durable",
460
+ "sanity.function.schedule",
461
+ "sanity.function.media-library-asset",
462
+ "sanity.function.sync-tag-invalidate"
463
+ ]), FUNCTION_ID_MIN_LENGTH = 10, INVOKE_PERMISSIONS = {
464
+ project: [
465
+ "sanity.project.functions.invoke",
466
+ "sanity.project.blueprints.deploy",
467
+ "sanity.project.deployStudio"
468
+ ],
469
+ organization: [
470
+ "sanity.organization.functions.invoke",
471
+ "sanity.blueprints.deploy",
472
+ "sanity.organization.tokens.create"
473
+ ]
474
+ }, MB_6 = 6291456, LAMBDA_ASYNC_LIMIT = 256 * 1024, CL_EVENTING_HINT = "Invoke the function by issuing a relevant Content Lake mutation operation instead.", STATUS_MESSAGES = {
475
+ 400: "Bad Request",
476
+ 401: "Unauthorized",
477
+ 403: "Forbidden",
478
+ 404: "Not Found",
479
+ 413: "Payload Too Large"
480
+ };
481
+ function registerFunction(registry, args) {
482
+ const { fn, site } = args;
483
+ if (typeof fn.id != "string" || fn.id.length < FUNCTION_ID_MIN_LENGTH)
484
+ throw fakeError(
485
+ `${site}: function id ${JSON.stringify(fn.id)} is shorter than ${FUNCTION_ID_MIN_LENGTH} characters; the Functions API's ids are at least that long.`
486
+ );
487
+ if (!FUNCTION_TYPES.has(fn.type))
488
+ throw fakeError(
489
+ `${site}: function "${fn.id}" has type ${JSON.stringify(fn.type)}; expected one of ${[...FUNCTION_TYPES].join(", ")}.`
490
+ );
491
+ if (fn.resourceType !== "project" && fn.resourceType !== "organization")
492
+ throw fakeError(
493
+ `${site}: function "${fn.id}" has resourceType ${JSON.stringify(fn.resourceType)}; expected "project" or "organization".`
494
+ );
495
+ const clash = [...registry.functions.values()].find(
496
+ (other) => other.id !== fn.id && other.blueprintStackId === fn.blueprintStackId && other.name === fn.name
497
+ );
498
+ if (clash !== void 0)
499
+ throw fakeError(
500
+ `${site}: functions "${clash.id}" and "${fn.id}" are both named "${fn.name}" in Blueprint stack ${fn.blueprintStackId}; a name is unique within its stack.`
501
+ );
502
+ registry.functions.set(fn.id, { ...fn });
503
+ }
504
+ function unregisterFunction(registry, id) {
505
+ if (!registry.functions.delete(id))
506
+ throw fakeError(
507
+ `removeFunction(): no function has id "${id}". Deployed ids: ${[...registry.functions.keys()].map((known) => `"${known}"`).join(", ") || "none"}.`
508
+ );
509
+ }
510
+ function refusal(request, args) {
511
+ const { statusCode } = args;
512
+ return new PlatformHttpError({
513
+ ...request,
514
+ statusCode,
515
+ statusMessage: STATUS_MESSAGES[statusCode],
516
+ body: { error: args.error, message: args.message, details: { errors: args.errors ?? [] } }
517
+ });
518
+ }
519
+ function invalidInput(request, issues) {
520
+ return new PlatformHttpError({
521
+ ...request,
522
+ statusCode: 400,
523
+ statusMessage: "Bad Request",
524
+ body: {
525
+ details: { errors: [{ message: issues.map((issue) => issue.pretty).join(`
526
+ `) }] },
527
+ error: "INVALID_INPUT",
528
+ message: `Validation error: ${issues.map((issue) => issue.summary).join("; ")}`
529
+ }
530
+ });
531
+ }
532
+ function prettyPath(path) {
533
+ return path.map((key, index) => /^[A-Za-z_$][\w$]*$/.test(key) ? index === 0 ? key : `.${key}` : `[${JSON.stringify(key)}]`).join("");
534
+ }
535
+ function issueAt(path, message) {
536
+ return path.length === 0 ? { summary: message, pretty: `\u2716 ${message}` } : {
537
+ summary: `${message} at "${path.join(".")}"`,
538
+ pretty: `\u2716 ${message}
539
+ \u2192 at ${prettyPath(path)}`
540
+ };
541
+ }
542
+ function tooShort(args) {
543
+ const { key, min, value } = args;
544
+ if (!(value.length >= min))
545
+ return issueAt([key], `Too small: expected string to have >=${min} characters`);
546
+ }
547
+ function typeName(value) {
548
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
549
+ }
550
+ function isRecord(value) {
551
+ return typeName(value) === "object";
552
+ }
553
+ function bodyIssue(body) {
554
+ const parts = [[[], body]];
555
+ isRecord(body) && (parts.push([["event"], body.event]), isRecord(body.event) && parts.push([["event", "data"], body.event.data]));
556
+ const failed = parts.find(([, value2]) => !isRecord(value2));
557
+ if (failed === void 0) return;
558
+ const [path, value] = failed;
559
+ return issueAt(path, `Invalid input: expected object, received ${typeName(value)}`);
560
+ }
561
+ function parseQuery(request) {
562
+ const queryStart = request.url.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : request.url.slice(queryStart + 1)), repeated = ["blueprintStackId", "sync"].find((key) => query.getAll(key).length > 1);
563
+ if (repeated !== void 0)
564
+ throw fakeError(
565
+ `request(): ${request.path} got "${repeated}" more than once; Hono reads a repeated query key as an array, whose validation answer the fake does not model. Pass it once.`
566
+ );
567
+ const blueprintStackId = query.get("blueprintStackId") ?? void 0, sync = query.get("sync") ?? "false", issues = [
568
+ blueprintStackId === void 0 ? void 0 : tooShort({ key: "blueprintStackId", min: 10, value: blueprintStackId }),
569
+ sync === "true" || sync === "false" ? void 0 : {
570
+ summary: 'Invalid input: expected "true" at "sync" or Invalid input: expected "false" at "sync"',
571
+ pretty: `\u2716 Invalid input
572
+ \u2192 at sync`
573
+ }
574
+ ].filter((issue) => issue !== void 0);
575
+ return issues.length > 0 ? issues : { blueprintStackId, sync: sync === "true" };
576
+ }
577
+ function decodeSegment$1(segment) {
578
+ try {
579
+ return decodeURIComponent(segment);
580
+ } catch {
581
+ return segment;
582
+ }
583
+ }
584
+ function lowercaseHeaders(headers) {
585
+ return new Map(Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]));
586
+ }
587
+ function cannotInvoke(fn, sync) {
588
+ switch (fn.type) {
589
+ case "sanity.function.document":
590
+ case "sanity.function.media-library-asset":
591
+ case "sanity.function.sync-tag-invalidate":
592
+ return `Content Lake evented functions like ${fn.type} cannot be directly invoked. ${CL_EVENTING_HINT}`;
593
+ case "sanity.function.schedule":
594
+ return `${fn.type} functions cannot be directly invoked.`;
595
+ case "sanity.function.queue":
596
+ case "sanity.function.durable":
597
+ return sync ? `${fn.type} functions cannot be synchronously invoked.` : void 0;
598
+ case "sanity.function.pubsub":
599
+ return;
600
+ }
601
+ }
602
+ function inScope(organizationId, args) {
603
+ const { fn, scope } = args;
604
+ return fn.resourceType === scope.type && fn.resourceId === scope.id ? !0 : scope.type === "organization" && fn.resourceType === "project" && organizationId !== void 0 && organizationId === scope.id;
605
+ }
606
+ function admitScope(ctx, args) {
607
+ const { request, headers } = args, type = headers.get("x-sanity-scope-type"), id = headers.get("x-sanity-scope-id");
608
+ if (!type || !id)
609
+ throw refusal(request, {
610
+ statusCode: 400,
611
+ error: "MISSING_SCOPE",
612
+ message: "X-Sanity-Scope-Type and X-Sanity-Scope-Id headers are required"
613
+ });
614
+ if (type !== "project" && type !== "organization")
615
+ throw refusal(request, {
616
+ statusCode: 400,
617
+ error: "INVALID_SCOPE_TYPE",
618
+ message: "Only organization and project scopes are currently supported"
619
+ });
620
+ if (ctx.projectApiDown())
621
+ throw new PlatformServerError({
622
+ ...request,
623
+ statusCode: 500,
624
+ statusMessage: "Internal Server Error",
625
+ body: {
626
+ error: "ACCESS_ERROR",
627
+ message: "Failed to validate project access",
628
+ details: { errors: [] }
629
+ }
630
+ });
631
+ const required = INVOKE_PERMISSIONS[type], held = ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? [];
632
+ if (!required.some((permission) => held.includes(permission)))
633
+ throw refusal(request, {
634
+ statusCode: 403,
635
+ error: "FORBIDDEN",
636
+ message: `You do not have invoke access to ${type} ${id}`,
637
+ errors: { required: [...required] }
638
+ });
639
+ return { type, id };
640
+ }
641
+ function validate(request, parts) {
642
+ const query = parseQuery(request);
643
+ if (Array.isArray(query)) throw invalidInput(request, query);
644
+ const issue = [
645
+ tooShort({ key: "functionId", min: 3, value: parts.segment }),
646
+ tooShort({
647
+ key: "x-sanity-scope-id",
648
+ min: 8,
649
+ value: parts.headers.get("x-sanity-scope-id")
650
+ }),
651
+ bodyIssue(parts.body)
652
+ ].find((found) => found !== void 0);
653
+ if (issue !== void 0) throw invalidInput(request, [issue]);
654
+ const { event } = parts.body;
655
+ return { ...query, data: event.data };
656
+ }
657
+ function findFunction(registry, args) {
658
+ const { request, segment, blueprintStackId } = args;
659
+ if (blueprintStackId === void 0) {
660
+ if (segment.length < FUNCTION_ID_MIN_LENGTH)
661
+ throw refusal(request, {
662
+ statusCode: 400,
663
+ error: "BAD_REQUEST",
664
+ message: "Invalid functionId"
665
+ });
666
+ return registry.functions.get(segment);
667
+ }
668
+ const byName = [...registry.functions.values()].find(
669
+ (fn) => fn.blueprintStackId === blueprintStackId && fn.name === segment
670
+ );
671
+ if (byName === void 0)
672
+ throw refusal(request, {
673
+ statusCode: 404,
674
+ error: "FUNCTION_NOT_FOUND",
675
+ message: `Function "${segment}" was not found in Blueprint Stack ${blueprintStackId}`
676
+ });
677
+ return byName;
678
+ }
679
+ function refuseOversized(request, args) {
680
+ const size = Buffer.byteLength(
681
+ JSON.stringify({ data: args.data, invokedBySanityUserId: args.userId, lineage: "" }),
682
+ "utf8"
683
+ );
684
+ if (!args.sync && size >= LAMBDA_ASYNC_LIMIT)
685
+ throw refusal(request, {
686
+ statusCode: 413,
687
+ error: "CONTENT_TOO_LARGE",
688
+ message: `Invoke payload must be smaller than ${LAMBDA_ASYNC_LIMIT} bytes for asynchronous invocations; current size=${size} bytes. Reduce payload size or set sync=true (not recommended due to blocking network request).`
689
+ });
690
+ if (args.sync && size > MB_6)
691
+ throw refusal(request, {
692
+ statusCode: 413,
693
+ error: "CONTENT_TOO_LARGE",
694
+ message: `Invoke payload must be smaller than ${MB_6} bytes for synchronous invocations; current size=${size} bytes.`
695
+ });
696
+ }
697
+ function serveFunctionInvoke(ctx, invoke) {
698
+ const { request, ...parts } = invoke, pathVersion = `v${ctx.apiVersion}`;
699
+ if (!/^v\d{4}-\d{2}-\d{2}$/.test(pathVersion) && pathVersion !== "vX")
700
+ throw refusal(request, {
701
+ statusCode: 400,
702
+ error: "BAD_REQUEST",
703
+ message: "Invalid API version in path",
704
+ errors: { version: pathVersion }
705
+ });
706
+ if (ctx.internalToken())
707
+ throw refusal(request, {
708
+ statusCode: 401,
709
+ error: "INVALID_TOKEN",
710
+ message: "Missing required claim: guid"
711
+ });
712
+ const headers = lowercaseHeaders(parts.headers), scope = admitScope(ctx, { request, headers });
713
+ if (parts.body === void 0)
714
+ throw fakeError(
715
+ `request(): POST ${request.path} without a body. The Functions API answers it with a 500 once its pre-flight checks pass, which the fake does not model. Send \`body: { event: { data: {} } }\`.`
716
+ );
717
+ if (typeof parts.body != "object" || parts.body === null)
718
+ throw fakeError(
719
+ `request(): POST ${request.path} with a ${typeof parts.body} body; @sanity/client sends it without a JSON content type, which the fake does not model. Send an object.`
720
+ );
721
+ if (Buffer.byteLength(JSON.stringify(parts.body), "utf8") > MB_6)
722
+ throw refusal(request, {
723
+ statusCode: 413,
724
+ error: "CONTENT_TOO_LARGE",
725
+ message: `Request must be smaller than ${MB_6} bytes for the Invoke Function operation`
726
+ });
727
+ const segment = decodeSegment$1(request.path.match(FUNCTION_INVOKE_PATH)[1]), { blueprintStackId, sync, data } = validate(request, {
728
+ segment,
729
+ headers,
730
+ body: parts.body
731
+ }), fn = findFunction(ctx.registry, { request, segment, blueprintStackId });
732
+ if (fn === void 0 || !inScope(ctx.organizationId, { fn, scope }))
733
+ throw refusal(request, {
734
+ statusCode: 404,
735
+ error: "FUNCTION_NOT_FOUND",
736
+ message: "function not found"
737
+ });
738
+ const notInvokable = cannotInvoke(fn, sync);
739
+ if (notInvokable !== void 0)
740
+ throw refusal(request, {
741
+ statusCode: 400,
742
+ error: "INVOKE_NOT_SUPPORTED",
743
+ message: notInvokable
744
+ });
745
+ if (headers.has("x-sanity-lineage"))
746
+ throw fakeError(
747
+ `request(): POST ${request.path} with an x-sanity-lineage header; the Functions API's recursion limit is not modelled. Omit the header.`
748
+ );
749
+ const userId = ctx.actorUser().id;
750
+ if (refuseOversized(request, { data, userId, sync }), sync)
751
+ throw fakeError(
752
+ `request(): POST ${request.path}?sync=true passed every check the Functions API makes, but synchronous invocation (the function's return value) is not modelled. Invoke asynchronously: omit \`sync\` or pass \`sync: "false"\`.`
753
+ );
754
+ ctx.registry.invocations.push({
755
+ functionId: fn.id,
756
+ name: fn.name,
757
+ blueprintStackId: fn.blueprintStackId,
758
+ scopeType: scope.type,
759
+ scopeId: scope.id,
760
+ sync,
761
+ event: { data: structuredClone(data) },
762
+ invokedBy: { userId }
763
+ });
764
+ }
455
765
  function createDocumentHistory() {
456
766
  const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
457
767
  return {
@@ -1111,6 +1421,7 @@ function serveProject(args) {
1111
1421
  function makeRequestImpl(ctx) {
1112
1422
  const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
1113
1423
  return async (opts) => {
1424
+ if ((opts.method ?? "GET").toUpperCase() !== "GET") return servePost(ctx, opts);
1114
1425
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
1115
1426
  if (path === "/users/me") {
1116
1427
  const user = useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
@@ -1139,6 +1450,18 @@ function makeRequestImpl(ctx) {
1139
1450
  );
1140
1451
  };
1141
1452
  }
1453
+ function servePost(ctx, opts) {
1454
+ const request = ctx.requestFor(opts);
1455
+ if (request.method === "POST" && FUNCTION_INVOKE_PATH.test(request.path))
1456
+ return serveFunctionInvoke(ctx.functions, {
1457
+ request,
1458
+ body: opts.body,
1459
+ headers: opts.headers
1460
+ });
1461
+ throw fakeError(
1462
+ `request(): no handler for ${opts.method} "${opts.uri ?? opts.url}". The fake serves POST on "/functions/<idOrName>/invoke" (the Functions API) only. For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
1463
+ );
1464
+ }
1142
1465
  class GuardDeniedError extends ClientError {
1143
1466
  type = "guardDeniedError";
1144
1467
  denials;
@@ -2404,6 +2727,15 @@ function seedEntry(registry, resource, documents) {
2404
2727
  const entry = ensureEntry(registry, resource);
2405
2728
  entry.store.seed(documents), entry.exists = !0;
2406
2729
  }
2730
+ function seedFunctions(functions) {
2731
+ const registry = { functions: /* @__PURE__ */ new Map(), invocations: [] };
2732
+ for (const fn of functions) {
2733
+ if (registry.functions.has(fn.id))
2734
+ throw fakeError(`createTestClient(): \`functions\` lists id "${fn.id}" twice.`);
2735
+ registerFunction(registry, { fn, site: "createTestClient()" });
2736
+ }
2737
+ return registry;
2738
+ }
2407
2739
  function seedOrganizationStores(options) {
2408
2740
  const seeded = Object.entries(options.organizationStores ?? {}), unserved = seeded.find(([, status]) => status !== "provisioning" && status !== "active");
2409
2741
  if (unserved !== void 0)
@@ -2428,6 +2760,7 @@ function createTestClient(options = {}) {
2428
2760
  organizationId: options.organizationId,
2429
2761
  projectFeatures: options.projectFeatures ?? {},
2430
2762
  organizationStores: seedOrganizationStores(options),
2763
+ functions: seedFunctions(options.functions ?? []),
2431
2764
  log: [],
2432
2765
  stubs: /* @__PURE__ */ new Map(),
2433
2766
  calls: [],
@@ -2568,8 +2901,8 @@ function makeHandle(handleArgs) {
2568
2901
  }, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
2569
2902
  const check = internal();
2570
2903
  if (check === void 0) return;
2571
- const refusal = internalTokenRefusal(request, check);
2572
- if (refusal !== void 0) throw refusal;
2904
+ const refusal2 = internalTokenRefusal(request, check);
2905
+ if (refusal2 !== void 0) throw refusal2;
2573
2906
  }, withSession = (request) => async (opts) => {
2574
2907
  const sent = rawRequest(opts);
2575
2908
  if (internal() !== void 0 && servedByProjectApi(sent.path) && sent.path !== ORGANIZATION_STORES_PATH)
@@ -2587,8 +2920,8 @@ function makeHandle(handleArgs) {
2587
2920
  refuseInternalToken(request);
2588
2921
  const access = activeAccess();
2589
2922
  if (access === void 0) return;
2590
- const refusal = refusedToken(request, access.grants);
2591
- if (refusal !== void 0) throw refusal;
2923
+ const refusal2 = refusedToken(request, access.grants);
2924
+ if (refusal2 !== void 0) throw refusal2;
2592
2925
  }, baseUrls = apiBaseUrls({
2593
2926
  apiHost,
2594
2927
  apiVersion,
@@ -2641,7 +2974,7 @@ function makeHandle(handleArgs) {
2641
2974
  if (opts.query !== void 0 && "tag" in opts.query)
2642
2975
  throw fakeError("request(): pass the request tag as `tag`, not in `query`.");
2643
2976
  return platformRequest({
2644
- method: "GET",
2977
+ method: opts.method?.toUpperCase() === "POST" ? "POST" : "GET",
2645
2978
  uri: opts.uri ?? opts.url ?? "",
2646
2979
  tag: opts.tag,
2647
2980
  query: Object.entries(opts.query ?? {}).flatMap(
@@ -3078,6 +3411,7 @@ function makeHandle(handleArgs) {
3078
3411
  makeRequestImpl({
3079
3412
  getAccess: requireActiveAccess,
3080
3413
  requestFor: rawRequest,
3414
+ projectId,
3081
3415
  useProjectHostname: projectHosted,
3082
3416
  organizationId: backend.organizationId,
3083
3417
  listIdentities: members,
@@ -3106,6 +3440,18 @@ function makeHandle(handleArgs) {
3106
3440
  // A dataset stands for its project, and every project exists in
3107
3441
  // the fake, so a dataset handle still counts as before.
3108
3442
  resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
3443
+ },
3444
+ functions: {
3445
+ apiVersion,
3446
+ organizationId: backend.organizationId,
3447
+ registry: backend.functions,
3448
+ internalToken: () => internal() !== void 0,
3449
+ projectApiDown: () => backend.outages.has("project-api"),
3450
+ actorUser: () => {
3451
+ const access = requireActiveAccess();
3452
+ return access.globalUser ?? access.currentUser;
3453
+ },
3454
+ actorAccess: () => requireActiveAccess().access
3109
3455
  }
3110
3456
  })
3111
3457
  )
@@ -3178,6 +3524,9 @@ function makeHandle(handleArgs) {
3178
3524
  backend.outages.add(component);
3179
3525
  },
3180
3526
  completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
3527
+ addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
3528
+ removeFunction: (id) => unregisterFunction(backend.functions, id),
3529
+ functionInvocations: () => structuredClone(backend.functions.invocations),
3181
3530
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
3182
3531
  transactions: () => [...backend.log],
3183
3532
  clearLog: () => {