@sanity-labs/client-fake-for-test 0.28.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.cjs 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 {
@@ -513,6 +823,98 @@ function createDocumentHistory() {
513
823
  function historyIds(list) {
514
824
  return list.split(",").map((id) => decodeURIComponent(id));
515
825
  }
826
+ const ORGANIZATION_STORES_PATH = "/internal/organization-stores";
827
+ function serveOrganizationStore(args) {
828
+ const { stores, organizationIds, session, request, query } = args;
829
+ refuseSession(request, session);
830
+ const organizationId = organizationIdOf(request, query);
831
+ if (!organizationIds.includes(organizationId))
832
+ throw boom(request, 404, "Not Found", `Organization ${organizationId} not found`);
833
+ const existing = stores.get(organizationId);
834
+ if (existing !== void 0) return { ...existing };
835
+ const store = {
836
+ id: organizationStoreId(organizationId),
837
+ organizationId,
838
+ status: "provisioning"
839
+ };
840
+ return stores.set(organizationId, store), { ...store };
841
+ }
842
+ function completeProvisioning(stores, organizationId) {
843
+ const store = stores.get(organizationId);
844
+ if (store?.status !== "provisioning")
845
+ throw fakeError(
846
+ `completeOrganizationStoreProvisioning(): organization "${organizationId}" has ` + (store === void 0 ? "no store. Populus creates one on the first GET /internal/organization-stores." : "an active store already.")
847
+ );
848
+ store.status = "active";
849
+ }
850
+ function refuseSession(request, session) {
851
+ const refused = "refused" in session ? session.refused : session.tokenType !== "service" && "A service session is required for this endpoint";
852
+ if (refused) throw boom(request, 401, "Unauthorized", refused);
853
+ }
854
+ function organizationIdOf(request, query) {
855
+ const nested = [...query.keys()].find((key) => key.includes("["));
856
+ if (nested !== void 0)
857
+ throw fakeError(
858
+ `request(): ${request.path} got query key "${nested}"; Express parses bracketed keys into nested values, which the fake does not model. Pass flat query parameters.`
859
+ );
860
+ const unknown = [...new Set(query.keys())].filter((key) => key !== "tag").find((key) => key !== "organizationId"), values = query.getAll("organizationId"), failure = values.length === 0 && {
861
+ key: "organizationId",
862
+ message: '"organizationId" is required'
863
+ } || values.length > 1 && {
864
+ key: "organizationId",
865
+ message: '"organizationId" must be a string'
866
+ } || values[0] === "" && {
867
+ key: "organizationId",
868
+ message: '"organizationId" is not allowed to be empty'
869
+ } || unknown !== void 0 && {
870
+ key: unknown,
871
+ message: `"${unknown}" is not allowed`
872
+ };
873
+ if (failure)
874
+ throw new PlatformHttpError({
875
+ ...request,
876
+ statusCode: 400,
877
+ statusMessage: "Bad Request",
878
+ body: {
879
+ statusCode: 400,
880
+ error: "Bad Request",
881
+ message: "Validation failed",
882
+ validation: {
883
+ query: {
884
+ source: "query",
885
+ keys: [escapeHtml(failure.key)],
886
+ message: failure.message
887
+ }
888
+ }
889
+ }
890
+ });
891
+ return values[0];
892
+ }
893
+ const DISALLOWED_SEGMENTS = ["ad", "api", "xxx"];
894
+ function organizationStoreId(organizationId) {
895
+ for (let attempt = 0; ; attempt++) {
896
+ const id = `os${node_crypto.createHash("sha256").update(`${organizationId}:${attempt}`).digest("hex").slice(0, 10)}`;
897
+ if (!DISALLOWED_SEGMENTS.some((segment) => id.includes(segment))) return id;
898
+ }
899
+ }
900
+ function escapeHtml(text) {
901
+ const entities = {
902
+ '"': "&quot;",
903
+ "&": "&amp;",
904
+ "'": "&#39;",
905
+ "<": "&lt;",
906
+ ">": "&gt;"
907
+ };
908
+ return text.replace(/["&'<>]/g, (char) => entities[char]);
909
+ }
910
+ function boom(request, statusCode, statusMessage, message) {
911
+ return new PlatformHttpError({
912
+ ...request,
913
+ statusCode,
914
+ statusMessage,
915
+ body: { statusCode, error: statusMessage, message }
916
+ });
917
+ }
516
918
  const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, ACCESS_ROBOT_PATH = /^\/robots(?:\/([^/]+))?$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, ACCESS_API_SINCE = "2025-07-11", PROJECT_API_PATHS = [
517
919
  /^\/users\/me$/,
518
920
  /^\/projects\/[^/]+$/,
@@ -520,7 +922,8 @@ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^
520
922
  PROJECT_ROLES_PATH,
521
923
  PROJECT_FEATURES_PATH,
522
924
  MY_ATTRIBUTES_PATH,
523
- ACCESS_PATH
925
+ ACCESS_PATH,
926
+ new RegExp(`^${ORGANIZATION_STORES_PATH}$`)
524
927
  ];
525
928
  function servedByProjectApi(path) {
526
929
  if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
@@ -536,8 +939,19 @@ function usersPage(data) {
536
939
  return { ...page(data), totalCount: data.length };
537
940
  }
538
941
  const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
539
- async function servePlatformRequest(ctx, uri, request) {
540
- const { path } = request, queryStart = uri.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : uri.slice(queryStart + 1)), myAttributes = path.match(MY_ATTRIBUTES_PATH);
942
+ async function servePlatformRequest(ctx, request) {
943
+ const { path } = request, queryStart = request.url.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : request.url.slice(queryStart + 1));
944
+ if (path === ORGANIZATION_STORES_PATH)
945
+ return {
946
+ value: serveOrganizationStore({
947
+ stores: ctx.organizationStores,
948
+ organizationIds: ctx.organizationId === void 0 ? [] : [ctx.organizationId],
949
+ session: ctx.populusSession(),
950
+ request,
951
+ query
952
+ })
953
+ };
954
+ const myAttributes = path.match(MY_ATTRIBUTES_PATH);
541
955
  if (myAttributes !== null) {
542
956
  const organizationId = decodeURIComponent(myAttributes[1]);
543
957
  return serveMyAttributes({ ctx, request, organizationId, query });
@@ -1007,6 +1421,7 @@ function serveProject(args) {
1007
1421
  function makeRequestImpl(ctx) {
1008
1422
  const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
1009
1423
  return async (opts) => {
1424
+ if ((opts.method ?? "GET").toUpperCase() !== "GET") return servePost(ctx, opts);
1010
1425
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
1011
1426
  if (path === "/users/me") {
1012
1427
  const user = useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
@@ -1028,13 +1443,25 @@ function makeRequestImpl(ctx) {
1028
1443
  identities: listIdentities(),
1029
1444
  organizationId
1030
1445
  });
1031
- const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
1446
+ const served = path === void 0 ? void 0 : await servePlatformRequest(platform, requestFor(opts));
1032
1447
  if (served !== void 0) return served.value;
1033
1448
  throw fakeError(
1034
1449
  `request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | robots[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
1035
1450
  );
1036
1451
  };
1037
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
+ }
1038
1465
  class GuardDeniedError extends client.ClientError {
1039
1466
  type = "guardDeniedError";
1040
1467
  denials;
@@ -1945,9 +2372,11 @@ function jwtError(token, keys) {
1945
2372
  function identityOf(claims) {
1946
2373
  const unmodelledClaims = UNMODELLED_CLAIMS.filter((key) => key in claims);
1947
2374
  if (unmodelledClaims.length > 0)
1948
- throw fakeError(
1949
- `internal token: the fake does not model the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s); it reads "i", "g" and "x".`
1950
- );
2375
+ return {
2376
+ identity: { user: { id: "" }, grants: [] },
2377
+ expiresAt: void 0,
2378
+ unmodelled: `internal token: the Content Lake reads the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s), which the fake does not model; it reads "i", "g" and "x".`
2379
+ };
1951
2380
  const { i: id, g: grantList = [], x: rawExpiry } = claims;
1952
2381
  let expiresAt;
1953
2382
  if (rawExpiry != null) {
@@ -1984,6 +2413,32 @@ function checkInternalToken(token, keys) {
1984
2413
  const parsed = jwtError(token, keys);
1985
2414
  return "error" in parsed ? { refused: `invalid JWT token ${quoted(token)}: ${parsed.error}` } : identityOf(parsed.claims);
1986
2415
  }
2416
+ function populusSession(token, keys) {
2417
+ const [headerSegment, claimsSegment, signatureSegment] = token.split(".");
2418
+ if (signatureSegment.trim() === "") {
2419
+ const decoded = [headerSegment, claimsSegment].map(decodeSegment);
2420
+ if (decoded.some((bytes) => typeof bytes == "string"))
2421
+ throw fakeError(
2422
+ "internal token: a segment is not base64url; jsonwebtoken's answer to it is not modelled."
2423
+ );
2424
+ return decoded.forEach(
2425
+ (bytes, index) => jsonObject(bytes, index === 0 ? "header" : "claims segment")
2426
+ ), { refused: "jwt signature is required" };
2427
+ }
2428
+ const parsed = jwtError(token, keys);
2429
+ if ("error" in parsed) {
2430
+ if (parsed.error === "crypto/rsa: verification error") return { refused: "invalid signature" };
2431
+ throw fakeError(
2432
+ `internal token: populus refuses it with jsonwebtoken's 401 (gradient's reason: ${parsed.error}), whose message the fake does not model.`
2433
+ );
2434
+ }
2435
+ const { tokenType, x } = parsed.claims;
2436
+ if (x != null && typeof x != "number")
2437
+ throw fakeError(
2438
+ `internal token: "x" must be a number of epoch seconds; got ${JSON.stringify(x)}.`
2439
+ );
2440
+ return x && x < Math.ceil(Date.now() / 1e3) ? { refused: "Session expired" } : { tokenType };
2441
+ }
1987
2442
  function goTime(epochSeconds) {
1988
2443
  const date = new Date(epochSeconds * 1e3);
1989
2444
  if (Number.isNaN(date.getTime()) || date.getUTCFullYear() < 1e3)
@@ -2272,11 +2727,40 @@ function seedEntry(registry, resource, documents) {
2272
2727
  const entry = ensureEntry(registry, resource);
2273
2728
  entry.store.seed(documents), entry.exists = !0;
2274
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
+ }
2739
+ function seedOrganizationStores(options) {
2740
+ const seeded = Object.entries(options.organizationStores ?? {}), unserved = seeded.find(([, status]) => status !== "provisioning" && status !== "active");
2741
+ if (unserved !== void 0)
2742
+ throw fakeError(
2743
+ `createTestClient(): \`organizationStores\` seeds "${unserved[0]}" as ${JSON.stringify(unserved[1])}; populus serves only "provisioning" and "active" stores.`
2744
+ );
2745
+ const stray = seeded.find(([organizationId]) => organizationId !== options.organizationId);
2746
+ if (stray !== void 0)
2747
+ throw fakeError(
2748
+ `createTestClient(): \`organizationStores\` has a store for "${stray[0]}", which is not the configured \`organizationId\`; populus creates stores only for organizations it has.`
2749
+ );
2750
+ return new Map(
2751
+ seeded.map(([organizationId, status]) => [
2752
+ organizationId,
2753
+ { id: organizationStoreId(organizationId), organizationId, status }
2754
+ ])
2755
+ );
2756
+ }
2275
2757
  function createTestClient(options = {}) {
2276
2758
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
2277
2759
  registry: /* @__PURE__ */ new Map(),
2278
2760
  organizationId: options.organizationId,
2279
2761
  projectFeatures: options.projectFeatures ?? {},
2762
+ organizationStores: seedOrganizationStores(options),
2763
+ functions: seedFunctions(options.functions ?? []),
2280
2764
  log: [],
2281
2765
  stubs: /* @__PURE__ */ new Map(),
2282
2766
  calls: [],
@@ -2408,7 +2892,7 @@ function makeHandle(handleArgs) {
2408
2892
  if (access === void 0)
2409
2893
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
2410
2894
  return access;
2411
- }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2895
+ }, projectHosted = useProjectHostname && resource === void 0, refuseSession2 = (request) => {
2412
2896
  if (token === void 0 || internal() !== void 0) return;
2413
2897
  if (backend.revoked.has(token)) throw sessionNotFound(request);
2414
2898
  const tokenProjectId = backend.identities.get(token)?.projectId;
@@ -2417,27 +2901,27 @@ function makeHandle(handleArgs) {
2417
2901
  }, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
2418
2902
  const check = internal();
2419
2903
  if (check === void 0) return;
2420
- const refusal = internalTokenRefusal(request, check);
2421
- if (refusal !== void 0) throw refusal;
2904
+ const refusal2 = internalTokenRefusal(request, check);
2905
+ if (refusal2 !== void 0) throw refusal2;
2422
2906
  }, withSession = (request) => async (opts) => {
2423
2907
  const sent = rawRequest(opts);
2424
- if (internal() !== void 0 && servedByProjectApi(sent.path))
2908
+ if (internal() !== void 0 && servedByProjectApi(sent.path) && sent.path !== ORGANIZATION_STORES_PATH)
2425
2909
  throw fakeError(
2426
2910
  `request(): "${sent.path}" with an internal token. The project API (populus) verifies internal tokens with its own key and answers differently from the Content Lake; the fake does not model that. Use a registered identity's token there.`
2427
2911
  );
2428
- if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2912
+ if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2429
2913
  throw projectApiDown(sent);
2430
2914
  return request(opts);
2431
2915
  }, admitToLake = (request) => {
2432
- if (refuseSession(request), missingKey !== void 0) {
2916
+ if (refuseSession2(request), missingKey !== void 0) {
2433
2917
  const parts = datasetParts(target.id);
2434
2918
  throw datasetNotFound(request, parts.projectId, parts.dataset);
2435
2919
  }
2436
2920
  refuseInternalToken(request);
2437
2921
  const access = activeAccess();
2438
2922
  if (access === void 0) return;
2439
- const refusal = refusedToken(request, access.grants);
2440
- if (refusal !== void 0) throw refusal;
2923
+ const refusal2 = refusedToken(request, access.grants);
2924
+ if (refusal2 !== void 0) throw refusal2;
2441
2925
  }, baseUrls = apiBaseUrls({
2442
2926
  apiHost,
2443
2927
  apiVersion,
@@ -2486,7 +2970,18 @@ function makeHandle(handleArgs) {
2486
2970
  ["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
2487
2971
  ]
2488
2972
  });
2489
- }, rawRequest = (opts) => platformRequest({ method: "GET", uri: opts.uri ?? opts.url ?? "", tag: opts.tag }), members = () => [
2973
+ }, rawRequest = (opts) => {
2974
+ if (opts.query !== void 0 && "tag" in opts.query)
2975
+ throw fakeError("request(): pass the request tag as `tag`, not in `query`.");
2976
+ return platformRequest({
2977
+ method: opts.method?.toUpperCase() === "POST" ? "POST" : "GET",
2978
+ uri: opts.uri ?? opts.url ?? "",
2979
+ tag: opts.tag,
2980
+ query: Object.entries(opts.query ?? {}).flatMap(
2981
+ ([key, value]) => (Array.isArray(value) ? value : [value]).map((one) => [key, one])
2982
+ )
2983
+ });
2984
+ }, members = () => [
2490
2985
  ...backend.identities.values(),
2491
2986
  ...token === void 0 && accessControl !== void 0 ? [
2492
2987
  {
@@ -2688,7 +3183,7 @@ function makeHandle(handleArgs) {
2688
3183
  tag,
2689
3184
  canUseCdn: !1
2690
3185
  });
2691
- if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
3186
+ if (refuseSession2(request), capabilities.actions !== "served") throw capabilities.actions(request);
2692
3187
  return write(async () => {
2693
3188
  for (const action of Array.isArray(actions) ? actions : [actions]) {
2694
3189
  const refused = capabilities.refusedActions[action.actionType];
@@ -2916,6 +3411,7 @@ function makeHandle(handleArgs) {
2916
3411
  makeRequestImpl({
2917
3412
  getAccess: requireActiveAccess,
2918
3413
  requestFor: rawRequest,
3414
+ projectId,
2919
3415
  useProjectHostname: projectHosted,
2920
3416
  organizationId: backend.organizationId,
2921
3417
  listIdentities: members,
@@ -2924,6 +3420,9 @@ function makeHandle(handleArgs) {
2924
3420
  apiVersion,
2925
3421
  organizationId: backend.organizationId,
2926
3422
  projectFeatures: backend.projectFeatures,
3423
+ organizationStores: backend.organizationStores,
3424
+ // A registered identity's session is a user or robot session, never a service one.
3425
+ populusSession: () => token === void 0 || internal() === void 0 ? { tokenType: void 0 } : populusSession(token, backend.internalTokenKeys),
2927
3426
  own: (asked) => registryKey(asked) === registryKey(target) ? {
2928
3427
  grants: requireActiveAccess().grants,
2929
3428
  documents: () => store.all(),
@@ -2941,6 +3440,18 @@ function makeHandle(handleArgs) {
2941
3440
  // A dataset stands for its project, and every project exists in
2942
3441
  // the fake, so a dataset handle still counts as before.
2943
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
2944
3455
  }
2945
3456
  })
2946
3457
  )
@@ -3012,6 +3523,10 @@ function makeHandle(handleArgs) {
3012
3523
  simulateOutage: (component) => {
3013
3524
  backend.outages.add(component);
3014
3525
  },
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),
3015
3530
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
3016
3531
  transactions: () => [...backend.log],
3017
3532
  clearLog: () => {