@sanity-labs/client-fake-for-test 0.30.0 → 0.32.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/README.md +204 -129
- package/dist/index.cjs +443 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +56 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.js +443 -33
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { parse, evaluate } from "groq-js";
|
|
2
1
|
import { ClientError, ServerError } from "@sanity/client";
|
|
2
|
+
import { parse, evaluate, GroqSyntaxError } from "groq-js";
|
|
3
3
|
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
@@ -260,7 +260,22 @@ const RESOURCE_CAPABILITIES = {
|
|
|
260
260
|
refusedActions: {},
|
|
261
261
|
access: { type: "dashboard", id: (id) => id }
|
|
262
262
|
}
|
|
263
|
+
}, ORGANIZATION_STORE_CAPABILITIES = {
|
|
264
|
+
label: (id) => `organization store "${id}"`,
|
|
265
|
+
dataBase: (id) => `/organization-stores/${id}`,
|
|
266
|
+
matchBase: () => {
|
|
267
|
+
},
|
|
268
|
+
lookupAtBase: !1,
|
|
269
|
+
identity: "global",
|
|
270
|
+
acl: notMounted,
|
|
271
|
+
history: notMounted,
|
|
272
|
+
actions: notMounted,
|
|
273
|
+
refusedActions: {},
|
|
274
|
+
access: { type: "organization", id: (id) => id }
|
|
263
275
|
};
|
|
276
|
+
function storeCapabilitiesOf(type) {
|
|
277
|
+
return type === "organization-store" ? ORGANIZATION_STORE_CAPABILITIES : capabilitiesOf(type);
|
|
278
|
+
}
|
|
264
279
|
function capabilitiesOf(type) {
|
|
265
280
|
const row = Object.hasOwn(RESOURCE_CAPABILITIES, type) ? RESOURCE_CAPABILITIES[type] : void 0;
|
|
266
281
|
if (row === void 0)
|
|
@@ -558,7 +573,7 @@ function bodyIssue(body) {
|
|
|
558
573
|
const [path, value] = failed;
|
|
559
574
|
return issueAt(path, `Invalid input: expected object, received ${typeName(value)}`);
|
|
560
575
|
}
|
|
561
|
-
function parseQuery(request) {
|
|
576
|
+
function parseQuery$1(request) {
|
|
562
577
|
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
578
|
if (repeated !== void 0)
|
|
564
579
|
throw fakeError(
|
|
@@ -639,7 +654,7 @@ function admitScope(ctx, args) {
|
|
|
639
654
|
return { type, id };
|
|
640
655
|
}
|
|
641
656
|
function validate(request, parts) {
|
|
642
|
-
const query = parseQuery(request);
|
|
657
|
+
const query = parseQuery$1(request);
|
|
643
658
|
if (Array.isArray(query)) throw invalidInput(request, query);
|
|
644
659
|
const issue = [
|
|
645
660
|
tooShort({ key: "functionId", min: 3, value: parts.segment }),
|
|
@@ -1061,6 +1076,21 @@ async function readHistory(args) {
|
|
|
1061
1076
|
}
|
|
1062
1077
|
};
|
|
1063
1078
|
}
|
|
1079
|
+
function permissionRecords(args) {
|
|
1080
|
+
const { ctx, resource } = args, entries = Object.entries(ctx.actorAccess() ?? {}), own = accessKey(resource.type, resource.id);
|
|
1081
|
+
return (resource.type === "organization" && resource.id === ctx.organizationId ? entries : entries.filter(([key]) => key === own)).flatMap(([key, entry]) => {
|
|
1082
|
+
const separator = key.indexOf(":"), resourceType = key.slice(0, separator), resourceId = key.slice(separator + 1);
|
|
1083
|
+
return (entry.permissions ?? []).map((permission) => {
|
|
1084
|
+
const dot = permission.lastIndexOf(".");
|
|
1085
|
+
return {
|
|
1086
|
+
type: permission.slice(0, dot),
|
|
1087
|
+
resourceType,
|
|
1088
|
+
resourceId,
|
|
1089
|
+
action: permission.slice(dot + 1)
|
|
1090
|
+
};
|
|
1091
|
+
});
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1064
1094
|
function serveGated(args) {
|
|
1065
1095
|
const { capability, permission, held, request, serve } = args;
|
|
1066
1096
|
return serveCapability(capability, request, () => {
|
|
@@ -1140,19 +1170,7 @@ function serveAccess(args) {
|
|
|
1140
1170
|
value: usersPage(usersOn({ resource, registry, identities: ctx.identities() }))
|
|
1141
1171
|
}));
|
|
1142
1172
|
case "/user-permissions/me":
|
|
1143
|
-
return {
|
|
1144
|
-
value: page(
|
|
1145
|
-
permissions.map((permission) => {
|
|
1146
|
-
const dot = permission.lastIndexOf(".");
|
|
1147
|
-
return {
|
|
1148
|
-
type: permission.slice(0, dot),
|
|
1149
|
-
resourceType: resource.type,
|
|
1150
|
-
resourceId: id,
|
|
1151
|
-
action: permission.slice(dot + 1)
|
|
1152
|
-
};
|
|
1153
|
-
})
|
|
1154
|
-
)
|
|
1155
|
-
};
|
|
1173
|
+
return { value: page(permissionRecords({ ctx, resource })) };
|
|
1156
1174
|
default:
|
|
1157
1175
|
return;
|
|
1158
1176
|
}
|
|
@@ -2275,6 +2293,25 @@ function encodeGroqQuery(query, params = {}) {
|
|
|
2275
2293
|
value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
|
|
2276
2294
|
return `?${search}`;
|
|
2277
2295
|
}
|
|
2296
|
+
function handledRequest(options) {
|
|
2297
|
+
const full = new URL(options.url ?? ""), [, version, ...path] = full.pathname.split("/");
|
|
2298
|
+
if (version === void 0 || !version.startsWith("v"))
|
|
2299
|
+
throw fakeError(`requestHandler(): "${options.url}" has no /v<apiVersion> segment.`);
|
|
2300
|
+
const entries = options.query instanceof URLSearchParams ? [...options.query] : Object.entries(options.query ?? {}), search = new URLSearchParams(full.search);
|
|
2301
|
+
let tag;
|
|
2302
|
+
for (const [key, value] of entries)
|
|
2303
|
+
key === "tag" && typeof value == "string" ? tag = value : value !== void 0 && search.append(key, String(value));
|
|
2304
|
+
const query = search.toString(), bearer = new Headers(options.headers).get("authorization") ?? void 0;
|
|
2305
|
+
return {
|
|
2306
|
+
apiHost: `${full.protocol}//${full.host}`,
|
|
2307
|
+
apiVersion: version.slice(1),
|
|
2308
|
+
url: `/${path.join("/")}${query === "" ? "" : `?${query}`}`,
|
|
2309
|
+
method: options.method?.toUpperCase() === "POST" ? "POST" : "GET",
|
|
2310
|
+
token: bearer?.replace(/^Bearer /, ""),
|
|
2311
|
+
body: options.body,
|
|
2312
|
+
tag
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2278
2315
|
const SIGNING_METHODS = /* @__PURE__ */ new Set([
|
|
2279
2316
|
...["HS", "RS", "PS", "ES"].flatMap((family) => ["256", "384", "512"].map((n) => family + n)),
|
|
2280
2317
|
"EdDSA",
|
|
@@ -2466,6 +2503,107 @@ function internalTokenRefusal(request, check) {
|
|
|
2466
2503
|
}
|
|
2467
2504
|
});
|
|
2468
2505
|
}
|
|
2506
|
+
const IDENT = /[A-Za-z_][A-Za-z0-9_]*/y, SIMPLE_ESCAPES = /* @__PURE__ */ new Set(['"', "'", "\\", "/", "b", "f", "n", "r", "t"]), UNICODE_ESCAPE = /u([0-9A-Fa-f]{4})/y;
|
|
2507
|
+
function refuseUnsentParams(args) {
|
|
2508
|
+
const { request, query, params = {}, syntaxErrorAt } = args, { references, invalidStringAt } = scanQuery(query), errorAt = Math.min(syntaxErrorAt ?? 1 / 0, invalidStringAt ?? 1 / 0), unsent = references.find(
|
|
2509
|
+
(reference) => reference.index < errorAt && !isSent(params, reference.name)
|
|
2510
|
+
);
|
|
2511
|
+
if (unsent === void 0) return;
|
|
2512
|
+
const start = codePoints(query.slice(0, unsent.index));
|
|
2513
|
+
throw new PlatformHttpError({
|
|
2514
|
+
...request,
|
|
2515
|
+
statusCode: 400,
|
|
2516
|
+
statusMessage: "Bad Request",
|
|
2517
|
+
body: {
|
|
2518
|
+
error: {
|
|
2519
|
+
description: `param $${unsent.name} referenced, but not provided`,
|
|
2520
|
+
end: start + unsent.name.length,
|
|
2521
|
+
query,
|
|
2522
|
+
...start !== 0 ? { start } : {},
|
|
2523
|
+
type: "queryParseError"
|
|
2524
|
+
}
|
|
2525
|
+
}
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
function isSent(params, name) {
|
|
2529
|
+
return Object.hasOwn(params, name) && params[name] !== void 0;
|
|
2530
|
+
}
|
|
2531
|
+
function scanQuery(query) {
|
|
2532
|
+
const references = [];
|
|
2533
|
+
let declaration, atStatementStart = !0, index = 0;
|
|
2534
|
+
for (; index < query.length; ) {
|
|
2535
|
+
const char = query[index];
|
|
2536
|
+
if (char === '"' || char === "'") {
|
|
2537
|
+
const end = stringEnd(query, index);
|
|
2538
|
+
if (end === void 0) return { references, invalidStringAt: index };
|
|
2539
|
+
index = end, atStatementStart = !1;
|
|
2540
|
+
continue;
|
|
2541
|
+
}
|
|
2542
|
+
if (query.startsWith("//", index)) {
|
|
2543
|
+
const newline = query.indexOf(`
|
|
2544
|
+
`, index);
|
|
2545
|
+
index = newline === -1 ? query.length : newline + 1;
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
if (/\s/.test(char)) {
|
|
2549
|
+
index++;
|
|
2550
|
+
continue;
|
|
2551
|
+
}
|
|
2552
|
+
if (atStatementStart && isKeyword(query, index, "fn")) {
|
|
2553
|
+
declaration = { params: /* @__PURE__ */ new Set(), header: !0 }, atStatementStart = !1, index += 2;
|
|
2554
|
+
continue;
|
|
2555
|
+
}
|
|
2556
|
+
if (atStatementStart = !1, declaration?.header && char === ")" && (declaration.header = !1), declaration !== void 0 && char === ";") {
|
|
2557
|
+
declaration = void 0, atStatementStart = !0, index++;
|
|
2558
|
+
continue;
|
|
2559
|
+
}
|
|
2560
|
+
if (char === "$") {
|
|
2561
|
+
IDENT.lastIndex = index + 1;
|
|
2562
|
+
const name = IDENT.exec(query)?.[0];
|
|
2563
|
+
if (name !== void 0) {
|
|
2564
|
+
declaration?.header ? declaration.params.add(name) : declaration?.params.has(name) || references.push({ name, index }), index += 1 + name.length;
|
|
2565
|
+
continue;
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
index++;
|
|
2569
|
+
}
|
|
2570
|
+
return { references, invalidStringAt: void 0 };
|
|
2571
|
+
}
|
|
2572
|
+
function isKeyword(query, index, word) {
|
|
2573
|
+
return query.startsWith(word, index) && !/[A-Za-z0-9_]/.test(query[index + word.length] ?? "");
|
|
2574
|
+
}
|
|
2575
|
+
function stringEnd(query, index) {
|
|
2576
|
+
const quote = query[index];
|
|
2577
|
+
let at = index + 1;
|
|
2578
|
+
for (; at < query.length && query[at] !== quote; ) {
|
|
2579
|
+
if (query[at] !== "\\") {
|
|
2580
|
+
at++;
|
|
2581
|
+
continue;
|
|
2582
|
+
}
|
|
2583
|
+
const escaped = escapeLength(query, at + 1);
|
|
2584
|
+
if (escaped === void 0) return;
|
|
2585
|
+
at += 1 + escaped;
|
|
2586
|
+
}
|
|
2587
|
+
return at + 1;
|
|
2588
|
+
}
|
|
2589
|
+
function escapeLength(query, index) {
|
|
2590
|
+
const char = query[index];
|
|
2591
|
+
if (char === void 0) return 0;
|
|
2592
|
+
if (SIMPLE_ESCAPES.has(char)) return 1;
|
|
2593
|
+
const unit = unicodeEscape(query, index);
|
|
2594
|
+
if (unit === void 0 || unit >= 56320 && unit <= 57343) return;
|
|
2595
|
+
if (unit < 55296 || unit > 56319) return 5;
|
|
2596
|
+
const low = query[index + 5] === "\\" ? unicodeEscape(query, index + 6) : void 0;
|
|
2597
|
+
return low !== void 0 && low >= 56320 && low <= 57343 ? 11 : void 0;
|
|
2598
|
+
}
|
|
2599
|
+
function unicodeEscape(query, index) {
|
|
2600
|
+
UNICODE_ESCAPE.lastIndex = index;
|
|
2601
|
+
const hex = UNICODE_ESCAPE.exec(query)?.[1];
|
|
2602
|
+
return hex === void 0 ? void 0 : Number.parseInt(hex, 16);
|
|
2603
|
+
}
|
|
2604
|
+
function codePoints(text) {
|
|
2605
|
+
return [...text].length;
|
|
2606
|
+
}
|
|
2469
2607
|
const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
|
|
2470
2608
|
"fetch",
|
|
2471
2609
|
"getDocument",
|
|
@@ -2628,6 +2766,112 @@ function wrapWithGuards(client, config) {
|
|
|
2628
2766
|
}
|
|
2629
2767
|
});
|
|
2630
2768
|
}
|
|
2769
|
+
const READ_ROUTE = /^\/workflows\/organizations\/([^/]+)\/(query|doc|listen)(?=\/|$)(.*)$/, STORE_ROUTE = /^\/organization-stores\/([^/]+)\/(query|mutate|doc|listen|export|references|actions|history)(?=\/|$)(.*)$/, SERVICE_ROUTE = /^\/workflows(?=\/|$)/;
|
|
2770
|
+
function matchWorkflowsStoreRoute(args) {
|
|
2771
|
+
const { path, apiVersion } = args, read = path.match(READ_ROUTE);
|
|
2772
|
+
if (read !== null) {
|
|
2773
|
+
if (apiVersion !== "X") return "unrouted";
|
|
2774
|
+
const [, organizationId, action, rest] = read;
|
|
2775
|
+
return { route: "read", organizationId: decodeURIComponent(organizationId), action, rest };
|
|
2776
|
+
}
|
|
2777
|
+
const store = path.match(STORE_ROUTE);
|
|
2778
|
+
if (store !== null) {
|
|
2779
|
+
if (apiVersion === "1") return "unrouted";
|
|
2780
|
+
const [, storeId, action, rest] = store;
|
|
2781
|
+
return { route: "store", storeId: decodeURIComponent(storeId), action, rest };
|
|
2782
|
+
}
|
|
2783
|
+
if (SERVICE_ROUTE.test(path)) return apiVersion === "X" ? "service" : "unrouted";
|
|
2784
|
+
}
|
|
2785
|
+
function noRouteMatched(request) {
|
|
2786
|
+
return new PlatformHttpError({
|
|
2787
|
+
...request,
|
|
2788
|
+
statusCode: 404,
|
|
2789
|
+
statusMessage: "Not Found",
|
|
2790
|
+
body: { message: "no Route matched with those values" }
|
|
2791
|
+
});
|
|
2792
|
+
}
|
|
2793
|
+
function storeNotFound(request, identifier) {
|
|
2794
|
+
return new PlatformHttpError({
|
|
2795
|
+
...request,
|
|
2796
|
+
statusCode: 404,
|
|
2797
|
+
statusMessage: "Not Found",
|
|
2798
|
+
body: {
|
|
2799
|
+
statusCode: 404,
|
|
2800
|
+
error: "Dataset not found",
|
|
2801
|
+
message: `Dataset for id "${identifier}" not found`
|
|
2802
|
+
}
|
|
2803
|
+
});
|
|
2804
|
+
}
|
|
2805
|
+
function unauthorizedOrganization(request) {
|
|
2806
|
+
return new PlatformHttpError({
|
|
2807
|
+
...request,
|
|
2808
|
+
statusCode: 403,
|
|
2809
|
+
statusMessage: "Forbidden",
|
|
2810
|
+
body: {
|
|
2811
|
+
error: { type: "permissionDeniedError", description: "Unauthorized organization access" }
|
|
2812
|
+
}
|
|
2813
|
+
});
|
|
2814
|
+
}
|
|
2815
|
+
function failingMutation(args) {
|
|
2816
|
+
const held = new Set(args.revisions.keys()), written = /* @__PURE__ */ new Set();
|
|
2817
|
+
for (const mutation of args.mutations) {
|
|
2818
|
+
const refusal2 = refusalOf({ ...args, held, written, mutation });
|
|
2819
|
+
if (refusal2 !== void 0) return refusal2;
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
function refusalOf(args) {
|
|
2823
|
+
const { request, revisions, held, written, mutation } = args, created = mutation.create ?? mutation.createOrReplace ?? mutation.createIfNotExists;
|
|
2824
|
+
if (created !== void 0) {
|
|
2825
|
+
const id2 = String(created._id);
|
|
2826
|
+
if (mutation.create !== void 0 && held.has(id2))
|
|
2827
|
+
return mutationError(request, 409, {
|
|
2828
|
+
type: "documentAlreadyExistsError",
|
|
2829
|
+
description: `Document by ID ${goQuoted(id2)} already exists`,
|
|
2830
|
+
id: id2
|
|
2831
|
+
});
|
|
2832
|
+
held.add(id2), written.add(id2);
|
|
2833
|
+
return;
|
|
2834
|
+
}
|
|
2835
|
+
if (mutation.delete !== void 0) {
|
|
2836
|
+
held.delete(String(mutation.delete.id));
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
if (mutation.patch === void 0) return;
|
|
2840
|
+
const id = String(mutation.patch.id);
|
|
2841
|
+
if (!held.has(id))
|
|
2842
|
+
return mutationError(request, 404, {
|
|
2843
|
+
type: "documentNotFoundError",
|
|
2844
|
+
description: `The document with the ID ${goQuoted(id)} was not found`,
|
|
2845
|
+
id
|
|
2846
|
+
});
|
|
2847
|
+
const expected = mutation.patch.ifRevisionID;
|
|
2848
|
+
if (typeof expected == "string" && expected !== "") {
|
|
2849
|
+
if (written.has(id))
|
|
2850
|
+
throw fakeError(
|
|
2851
|
+
`request(): a mutate body patches "${id}" with ifRevisionID after writing it; the revision gradient gives a document mid-transaction is not modelled.`
|
|
2852
|
+
);
|
|
2853
|
+
const current = revisions.get(id) ?? "";
|
|
2854
|
+
if (expected !== current)
|
|
2855
|
+
return mutationError(request, 409, {
|
|
2856
|
+
type: "documentRevisionIDDoesNotMatchError",
|
|
2857
|
+
description: `Document ${goQuoted(id)} has unexpected revision ID (${goQuoted(current)}), expected ${goQuoted(expected)}`,
|
|
2858
|
+
expectedRevisionID: expected,
|
|
2859
|
+
currentRevisionID: current
|
|
2860
|
+
});
|
|
2861
|
+
}
|
|
2862
|
+
written.add(id);
|
|
2863
|
+
}
|
|
2864
|
+
function mutationError(request, statusCode, error) {
|
|
2865
|
+
return new PlatformHttpError({
|
|
2866
|
+
...request,
|
|
2867
|
+
statusCode,
|
|
2868
|
+
statusMessage: statusCode === 404 ? "Not Found" : "Conflict",
|
|
2869
|
+
body: { error }
|
|
2870
|
+
});
|
|
2871
|
+
}
|
|
2872
|
+
function goQuoted(text) {
|
|
2873
|
+
return JSON.stringify(text);
|
|
2874
|
+
}
|
|
2631
2875
|
const OPTIONS_ARG_POSITION = {
|
|
2632
2876
|
fetch: 2,
|
|
2633
2877
|
getDocument: 1,
|
|
@@ -2708,6 +2952,87 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
|
|
|
2708
2952
|
);
|
|
2709
2953
|
return validateResource(resource), resource;
|
|
2710
2954
|
};
|
|
2955
|
+
async function serveStoreAction(args) {
|
|
2956
|
+
const { client, history, action, rest, sent, opts } = args, search = new URL(sent.url).searchParams, tag = opts.tag !== void 0 ? { tag: opts.tag } : {};
|
|
2957
|
+
try {
|
|
2958
|
+
if (action === "doc") {
|
|
2959
|
+
if (sent.method !== "GET") throw notAllowed(sent);
|
|
2960
|
+
const ids = rest.slice(1).split(",").map(decodeURIComponent);
|
|
2961
|
+
if (rest === "" || ids.some((id) => id === ""))
|
|
2962
|
+
throw fakeError(`request(): "${sent.path}" names no document id; GET <store>/doc/<ids>.`);
|
|
2963
|
+
const found = await client.getDocuments(ids, tag), readable = new Set(found.flatMap((doc) => doc === null ? [] : [doc._id])), stored = new Set(
|
|
2964
|
+
client.store().all().map((doc) => doc._id)
|
|
2965
|
+
);
|
|
2966
|
+
return {
|
|
2967
|
+
documents: found.filter((doc) => doc !== null),
|
|
2968
|
+
omitted: ids.filter((id) => !readable.has(id)).map((id) => ({ id, reason: stored.has(id) ? "permission" : "existence" }))
|
|
2969
|
+
};
|
|
2970
|
+
}
|
|
2971
|
+
if (action === "query") {
|
|
2972
|
+
const { query, params } = storeQuery(sent, search, opts.body);
|
|
2973
|
+
return await client.fetch(query, params, {
|
|
2974
|
+
filterResponse: !1,
|
|
2975
|
+
returnQuery: search.get("returnQuery") !== "false",
|
|
2976
|
+
...tag
|
|
2977
|
+
});
|
|
2978
|
+
}
|
|
2979
|
+
if (sent.method !== "POST") throw notAllowed(sent);
|
|
2980
|
+
const body = opts.body;
|
|
2981
|
+
if (!Array.isArray(body?.mutations))
|
|
2982
|
+
throw fakeError(`request(): POST "${sent.path}" needs a body \`{ mutations: [...] }\`.`);
|
|
2983
|
+
const refusal2 = failingMutation({
|
|
2984
|
+
request: sent,
|
|
2985
|
+
revisions: new Map(
|
|
2986
|
+
client.store().all().map((doc) => [doc._id, doc._rev])
|
|
2987
|
+
),
|
|
2988
|
+
mutations: body.mutations
|
|
2989
|
+
});
|
|
2990
|
+
if (refusal2 !== void 0) throw refusal2;
|
|
2991
|
+
const committed = await client.mutate(body.mutations, {
|
|
2992
|
+
returnDocuments: !1,
|
|
2993
|
+
returnFirst: !1,
|
|
2994
|
+
...tag
|
|
2995
|
+
}), images = /* @__PURE__ */ new Map();
|
|
2996
|
+
if (search.get("returnDocuments") === "true") {
|
|
2997
|
+
const ids = committed.results.map((result) => result.id), record = history.transactions(ids, () => !0).find((txn) => txn.id === committed.transactionId);
|
|
2998
|
+
for (const mutation of record?.mutations ?? []) {
|
|
2999
|
+
const document = "create" in mutation ? mutation.create : "createOrReplace" in mutation ? mutation.createOrReplace : void 0;
|
|
3000
|
+
document !== void 0 && images.set(document._id, document);
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
return {
|
|
3004
|
+
transactionId: committed.transactionId,
|
|
3005
|
+
results: committed.results.map((result) => {
|
|
3006
|
+
const document = images.get(result.id) ?? (search.get("returnDocuments") === "true" ? client.store().get(result.id) : void 0);
|
|
3007
|
+
return document !== void 0 ? { ...result, document } : result;
|
|
3008
|
+
})
|
|
3009
|
+
};
|
|
3010
|
+
} catch (error) {
|
|
3011
|
+
throw (error instanceof ClientError || error instanceof ServerError) && Object.assign(error.response, { method: sent.method, url: sent.url }), error;
|
|
3012
|
+
}
|
|
3013
|
+
}
|
|
3014
|
+
function storeQuery(sent, search, body) {
|
|
3015
|
+
if (sent.method === "POST") {
|
|
3016
|
+
const posted = body;
|
|
3017
|
+
if (typeof posted?.query != "string")
|
|
3018
|
+
throw fakeError(`request(): POST "${sent.path}" needs a body \`{ query, params? }\`.`);
|
|
3019
|
+
return { query: posted.query, params: posted.params ?? {} };
|
|
3020
|
+
}
|
|
3021
|
+
const query = search.get("query");
|
|
3022
|
+
if (query === null) throw fakeError(`request(): GET "${sent.path}" needs a \`query\` parameter.`);
|
|
3023
|
+
const params = Object.fromEntries(
|
|
3024
|
+
[...search].filter(([name]) => name.startsWith("$")).map(([name, value]) => [name.slice(1), JSON.parse(value)])
|
|
3025
|
+
);
|
|
3026
|
+
return { query, params };
|
|
3027
|
+
}
|
|
3028
|
+
function notAllowed(sent) {
|
|
3029
|
+
return fakeError(`request(): ${sent.method} "${sent.path}" is not a method this route takes.`);
|
|
3030
|
+
}
|
|
3031
|
+
function clientResources(registry) {
|
|
3032
|
+
return [...registry.values()].filter(
|
|
3033
|
+
(entry) => entry.resource.type !== "organization-store"
|
|
3034
|
+
);
|
|
3035
|
+
}
|
|
2711
3036
|
function ensureEntry(registry, resource) {
|
|
2712
3037
|
const key = registryKey(resource);
|
|
2713
3038
|
let entry = registry.get(key);
|
|
@@ -2808,6 +3133,19 @@ function createTestClient(options = {}) {
|
|
|
2808
3133
|
configuredPerspective: options.perspective
|
|
2809
3134
|
});
|
|
2810
3135
|
}
|
|
3136
|
+
function parseQuery(request, query, params) {
|
|
3137
|
+
try {
|
|
3138
|
+
const tree = parse(query, params ? { params } : void 0);
|
|
3139
|
+
return refuseUnsentParams({ request, query, params }), tree;
|
|
3140
|
+
} catch (error) {
|
|
3141
|
+
throw refuseUnsentParams({
|
|
3142
|
+
request,
|
|
3143
|
+
query,
|
|
3144
|
+
params,
|
|
3145
|
+
...error instanceof GroqSyntaxError ? { syntaxErrorAt: error.position } : {}
|
|
3146
|
+
}), error;
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
2811
3149
|
function dedupeIds(results) {
|
|
2812
3150
|
const seen = /* @__PURE__ */ new Set(), out = [];
|
|
2813
3151
|
for (const r of results)
|
|
@@ -2872,7 +3210,7 @@ function makeHandle(handleArgs) {
|
|
|
2872
3210
|
apiVersion,
|
|
2873
3211
|
useCdn,
|
|
2874
3212
|
configuredPerspective
|
|
2875
|
-
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
3213
|
+
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = handleArgs.internalStore?.resource ?? resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
2876
3214
|
if (token === void 0) return accessControl;
|
|
2877
3215
|
const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
|
|
2878
3216
|
if (verified !== void 0 && "refused" in verified)
|
|
@@ -2881,7 +3219,7 @@ function makeHandle(handleArgs) {
|
|
|
2881
3219
|
throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
|
|
2882
3220
|
return {
|
|
2883
3221
|
// Per-project records apply only where the resource lives in a project.
|
|
2884
|
-
currentUser:
|
|
3222
|
+
currentUser: storeCapabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
|
|
2885
3223
|
...identity.globalUser !== void 0 ? { globalUser: identity.globalUser } : {},
|
|
2886
3224
|
...identity.robot ? { robot: !0 } : {},
|
|
2887
3225
|
grants: identity.grants,
|
|
@@ -2911,7 +3249,52 @@ function makeHandle(handleArgs) {
|
|
|
2911
3249
|
);
|
|
2912
3250
|
if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
|
|
2913
3251
|
throw projectApiDown(sent);
|
|
2914
|
-
|
|
3252
|
+
const routed = activeAccess()?.aclPath === (opts.uri ?? opts.url) ? void 0 : matchWorkflowsStoreRoute({ path: sent.path, apiVersion });
|
|
3253
|
+
return routed !== void 0 ? serveWorkflowsStore(routed, sent, opts) : request(opts);
|
|
3254
|
+
}, serveWorkflowsStore = (routed, sent, opts) => {
|
|
3255
|
+
if (routed === "unrouted") throw noRouteMatched(sent);
|
|
3256
|
+
if (routed === "service")
|
|
3257
|
+
throw fakeError(
|
|
3258
|
+
`request(): ${sent.method} "${sent.path}" goes to the Workflows service, which the fake does not serve. Mount a Workflows service double for it.`
|
|
3259
|
+
);
|
|
3260
|
+
const store2 = routed.route === "read" ? activeStoreOf(routed.organizationId) : [...backend.organizationStores.values()].find(
|
|
3261
|
+
(one) => one.id === routed.storeId && one.status === "active"
|
|
3262
|
+
);
|
|
3263
|
+
if (store2 === void 0)
|
|
3264
|
+
throw storeNotFound(
|
|
3265
|
+
sent,
|
|
3266
|
+
routed.route === "read" ? `org:${routed.organizationId}` : routed.storeId
|
|
3267
|
+
);
|
|
3268
|
+
const servedActions = routed.route === "read" ? ["query", "doc"] : ["query", "doc", "mutate"];
|
|
3269
|
+
if (!servedActions.includes(routed.action))
|
|
3270
|
+
throw fakeError(
|
|
3271
|
+
`request(): "${sent.path}" is ${routed.action} on the organization store; the fake serves ${servedActions.join(", ")} there.`
|
|
3272
|
+
);
|
|
3273
|
+
const scope = token === void 0 ? void 0 : backend.identities.get(token)?.organizationScope;
|
|
3274
|
+
if (scope !== void 0 && scope !== store2.organizationId) throw unauthorizedOrganization(sent);
|
|
3275
|
+
const onStore = makeHandle({
|
|
3276
|
+
...handleArgs,
|
|
3277
|
+
resource: void 0,
|
|
3278
|
+
// Both routes are on the global API host, whatever host the caller's other requests go to.
|
|
3279
|
+
useProjectHostname: !1,
|
|
3280
|
+
perspective: "raw",
|
|
3281
|
+
configuredPerspective: void 0,
|
|
3282
|
+
internalStore: {
|
|
3283
|
+
resource: { type: "organization-store", id: store2.id },
|
|
3284
|
+
store: { id: store2.id, organizationId: store2.organizationId }
|
|
3285
|
+
}
|
|
3286
|
+
});
|
|
3287
|
+
return serveStoreAction({
|
|
3288
|
+
client: onStore,
|
|
3289
|
+
history: ensureEntry(registry, { type: "organization-store", id: store2.id }).history,
|
|
3290
|
+
action: routed.action,
|
|
3291
|
+
rest: routed.rest,
|
|
3292
|
+
sent,
|
|
3293
|
+
opts
|
|
3294
|
+
});
|
|
3295
|
+
}, activeStoreOf = (organizationId) => {
|
|
3296
|
+
const store2 = backend.organizationStores.get(organizationId);
|
|
3297
|
+
return store2?.status === "active" ? store2 : void 0;
|
|
2915
3298
|
}, admitToLake = (request) => {
|
|
2916
3299
|
if (refuseSession2(request), missingKey !== void 0) {
|
|
2917
3300
|
const parts = datasetParts(target.id);
|
|
@@ -2991,7 +3374,7 @@ function makeHandle(handleArgs) {
|
|
|
2991
3374
|
...accessControl.access !== void 0 ? { access: accessControl.access } : {}
|
|
2992
3375
|
}
|
|
2993
3376
|
] : []
|
|
2994
|
-
], capabilities =
|
|
3377
|
+
], capabilities = storeCapabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
|
|
2995
3378
|
if (target.type !== "dataset") return;
|
|
2996
3379
|
const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
|
|
2997
3380
|
return backend.missingDatasets.has(key) ? key : void 0;
|
|
@@ -3030,6 +3413,7 @@ function makeHandle(handleArgs) {
|
|
|
3030
3413
|
projectId,
|
|
3031
3414
|
dataset,
|
|
3032
3415
|
...resource !== void 0 ? { resource } : {},
|
|
3416
|
+
...handleArgs.internalStore !== void 0 ? { organizationStore: { ...handleArgs.internalStore.store } } : {},
|
|
3033
3417
|
mutations,
|
|
3034
3418
|
...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
|
|
3035
3419
|
});
|
|
@@ -3204,16 +3588,15 @@ function makeHandle(handleArgs) {
|
|
|
3204
3588
|
return applyPerspective(accessible, override ?? perspective);
|
|
3205
3589
|
}, client = {
|
|
3206
3590
|
fetch: async (query, params, opts) => {
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
)
|
|
3216
|
-
const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
|
|
3591
|
+
const request = queryRequest({
|
|
3592
|
+
query,
|
|
3593
|
+
params,
|
|
3594
|
+
tag: opts?.tag,
|
|
3595
|
+
perspective: opts?.perspective,
|
|
3596
|
+
returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
|
|
3597
|
+
});
|
|
3598
|
+
admitToLake(request);
|
|
3599
|
+
const start = Date.now(), tree = parseQuery(request, query, params), result = await (await evaluate(tree, {
|
|
3217
3600
|
dataset: await visibleDocs(opts?.perspective),
|
|
3218
3601
|
...params !== void 0 ? { params } : {}
|
|
3219
3602
|
})).get();
|
|
@@ -3439,7 +3822,7 @@ function makeHandle(handleArgs) {
|
|
|
3439
3822
|
identities: members,
|
|
3440
3823
|
// A dataset stands for its project, and every project exists in
|
|
3441
3824
|
// the fake, so a dataset handle still counts as before.
|
|
3442
|
-
resources: () =>
|
|
3825
|
+
resources: () => clientResources(registry).filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
|
|
3443
3826
|
},
|
|
3444
3827
|
functions: {
|
|
3445
3828
|
apiVersion,
|
|
@@ -3504,7 +3887,7 @@ function makeHandle(handleArgs) {
|
|
|
3504
3887
|
backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);
|
|
3505
3888
|
},
|
|
3506
3889
|
datasets: () => [...registry.values()].filter((entry) => entry.resource.type === "dataset").map((entry) => datasetParts(entry.resource.id)),
|
|
3507
|
-
resources: () =>
|
|
3890
|
+
resources: () => clientResources(registry).map((entry) => ({ ...entry.resource })),
|
|
3508
3891
|
stub: (name, handler) => {
|
|
3509
3892
|
backend.stubs.set(name, handler);
|
|
3510
3893
|
},
|
|
@@ -3524,6 +3907,32 @@ function makeHandle(handleArgs) {
|
|
|
3524
3907
|
backend.outages.add(component);
|
|
3525
3908
|
},
|
|
3526
3909
|
completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
|
|
3910
|
+
organizationStore: (organizationId) => {
|
|
3911
|
+
const organizationStore = backend.organizationStores.get(organizationId);
|
|
3912
|
+
if (organizationStore === void 0)
|
|
3913
|
+
throw fakeError(
|
|
3914
|
+
`organizationStore(): organization "${organizationId}" has no store. Seed createTestClient({ organizationStores }), or look it up with GET /internal/organization-stores first.`
|
|
3915
|
+
);
|
|
3916
|
+
return ensureEntry(registry, { type: "organization-store", id: organizationStore.id }).store;
|
|
3917
|
+
},
|
|
3918
|
+
requestHandler: () => (options) => {
|
|
3919
|
+
const sent = handledRequest(options), sibling = client.withConfig({
|
|
3920
|
+
...sent.token !== void 0 ? { token: sent.token } : {},
|
|
3921
|
+
apiHost: sent.apiHost,
|
|
3922
|
+
apiVersion: sent.apiVersion,
|
|
3923
|
+
useProjectHostname: !1
|
|
3924
|
+
});
|
|
3925
|
+
if (sibling.request === void 0)
|
|
3926
|
+
throw fakeError(
|
|
3927
|
+
"requestHandler(): the request carries no token the fake knows, so it has no `request()` to answer it."
|
|
3928
|
+
);
|
|
3929
|
+
return sibling.request({
|
|
3930
|
+
url: sent.url,
|
|
3931
|
+
method: sent.method,
|
|
3932
|
+
...sent.body !== void 0 ? { body: sent.body } : {},
|
|
3933
|
+
...sent.tag !== void 0 ? { tag: sent.tag } : {}
|
|
3934
|
+
});
|
|
3935
|
+
},
|
|
3527
3936
|
addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
|
|
3528
3937
|
removeFunction: (id) => unregisterFunction(backend.functions, id),
|
|
3529
3938
|
functionInvocations: () => structuredClone(backend.functions.invocations),
|
|
@@ -3554,7 +3963,7 @@ function makeHandle(handleArgs) {
|
|
|
3554
3963
|
"error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
|
|
3555
3964
|
};
|
|
3556
3965
|
},
|
|
3557
|
-
recorded: RECORDED_METHODS
|
|
3966
|
+
recorded: handleArgs.internalStore === void 0 ? RECORDED_METHODS : /* @__PURE__ */ new Set()
|
|
3558
3967
|
});
|
|
3559
3968
|
}
|
|
3560
3969
|
export {
|
|
@@ -3578,6 +3987,7 @@ export {
|
|
|
3578
3987
|
isReleaseDocId,
|
|
3579
3988
|
isSystemId,
|
|
3580
3989
|
isVersionId,
|
|
3990
|
+
organizationStoreId,
|
|
3581
3991
|
publishedIdOf,
|
|
3582
3992
|
releaseNameOf,
|
|
3583
3993
|
wrapWithGuards
|