@sanity-labs/client-fake-for-test 0.30.0 → 0.31.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 +65 -0
- package/dist/index.cjs +309 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +309 -20
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -250,6 +250,50 @@ The first lookup for an organization without a store creates one `provisioning`,
|
|
|
250
250
|
|
|
251
251
|
Populus answers only `provisioning` and `active` stores, so the lookup never answers another status, and seeding another status throws. `request()` takes a `query` object as `@sanity/client` does, appended to the URL after the request tag; every route reads its parameters from that URL. A `tag` in `query`, and bracketed query keys such as `organizationId[]` (which Express parses into nested values), throw a fake error.
|
|
252
252
|
|
|
253
|
+
#### Workflows store
|
|
254
|
+
|
|
255
|
+
Workflows keeps its definitions and instances in the organization's store (see [Organization stores](#organization-stores)). Kong serves that store on two routes, and `request()` answers both on a handle with an acting identity, so code that reads and writes a Workflows store runs against the fake as against the platform:
|
|
256
|
+
|
|
257
|
+
| Route | Actions | Used by |
|
|
258
|
+
| --- | --- | --- |
|
|
259
|
+
| `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`) | `query` (GET, or POST `{ query, params }`), `doc/<ids>` | the read route, for Studio, the SDK and engines |
|
|
260
|
+
| `/v<X or date>/organization-stores/<storeId>/<action>` (kong `config/staging-internal/kong.jsonnet:326-345`, internal Kong) | `query`, `doc/<ids>`, `mutate` (POST `{ mutations }`) | the Workflows service, which reads and commits there |
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
const client = createTestClient({
|
|
264
|
+
useProjectHostname: false,
|
|
265
|
+
apiVersion: "X",
|
|
266
|
+
organizationId: "oAbc",
|
|
267
|
+
organizationStores: { oAbc: "active" },
|
|
268
|
+
identities: { "t-editor": { user: { id: "gEditor" }, grants } },
|
|
269
|
+
token: "t-editor",
|
|
270
|
+
});
|
|
271
|
+
client.organizationStore("oAbc").seed([{ _id: "wf.def", _type: "sanity.workflow.definition" }]);
|
|
272
|
+
|
|
273
|
+
await client.request({ url: "/workflows/organizations/oAbc/query?query=count(*)" });
|
|
274
|
+
// { query: "count(*)", result: 1, ms: … }
|
|
275
|
+
await client.request({ url: "/workflows/organizations/oAbc/doc/wf.def,wf.none" });
|
|
276
|
+
// { documents: [{ _id: "wf.def", … }], omitted: [{ id: "wf.none", reason: "existence" }] }
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
The store is the organization's store from `organizationStores` or the lookup, and `client.organizationStore(organizationId)` hands out its documents to seed or inspect. Reads and writes act as the handle's token, with its grants, mutation guards, mutation log and history, as on any resource:
|
|
280
|
+
|
|
281
|
+
- A query sees only the documents the token may read. `doc` omits a missing id with reason `existence` and one the token may not read with reason `permission` (gradient `pkg/server/httpapi/get_documents.go:25-33,140-162`).
|
|
282
|
+
- `mutate` applies its mutations atomically and answers `{ transactionId, results: [{ id, operation, document? }] }`, `document` only with `returnDocuments=true` (gradient `pkg/server/httpapi/mutate_test.go:66-98`). A write the grants do not allow is refused with `WriteAccessDeniedError`.
|
|
283
|
+
- A query that references a parameter it does not send answers the Content Lake's 400 (see [Unsent query parameters](#unsent-query-parameters)), and a revoked token its 401.
|
|
284
|
+
- A request carries no perspective, so reads are raw whatever the calling handle's `perspective` is. A write is logged in `client.transactions()` with `organizationStore: { id, organizationId }`; `projectId` and `dataset` there are the calling handle's. `client.calls()` records the `request()` call only.
|
|
285
|
+
|
|
286
|
+
Kong's answers, as staging gives them:
|
|
287
|
+
|
|
288
|
+
| Request | Answer |
|
|
289
|
+
| --- | --- |
|
|
290
|
+
| An organization without a store, or with one still `provisioning` | 404 `{ statusCode: 404, error: "Dataset not found", message: 'Dataset for id "org:<organizationId>" not found' }` (kong `kong/sanity-utils/sanity_namespace_routing_key.lua:47-56`; populus makes a store routable before it sets it `active`) |
|
|
291
|
+
| A store id that is not an `active` store | the same 404, naming the store id |
|
|
292
|
+
| The read route on API version `1` or a date, or the store route on `1` | 404 `{ message: "no Route matched with those values" }` |
|
|
293
|
+
| Any other `/vX/workflows…` path, such as `…/mutate` on the read route | Kong sends it to the Workflows service, which the fake does not serve: a fake error |
|
|
294
|
+
|
|
295
|
+
The fake does not tell the two Kongs apart, so it serves the store route on any host; on the platform only internal Kong does. `listen`, and the store route's `export`, `references`, `actions` and `history`, throw a fake error.
|
|
296
|
+
|
|
253
297
|
#### Functions
|
|
254
298
|
|
|
255
299
|
`createTestClient({ functions })` deploys functions as the Functions API (sanity-io/functions) holds them, and `request()` invokes them as `POST /v<apiVersion>/functions/<idOrName>/invoke` does:
|
|
@@ -312,6 +356,26 @@ client.functionInvocations();
|
|
|
312
356
|
|
|
313
357
|
A function is in scope when the scope owns it, or when an organization scope invokes a project's function and that organization is the client's `organizationId` (every project of the family belongs to it); a project scope never reaches an organization's function. Invocations are asynchronous only: a synchronous one that passes every check throws a fake error, as does an `x-sanity-lineage` header (the recursion limit is not modelled). The payload size is measured on `{ data, invokedBySanityUserId, lineage }`, slightly smaller than the Lambda payload the service measures. The service's quota check is not modelled.
|
|
314
358
|
|
|
359
|
+
#### Unsent query parameters
|
|
360
|
+
|
|
361
|
+
A query that references a parameter the request does not send is refused before it runs, as the Content Lake refuses it (gradient parses with go-groq, `parser/internal/parserv2/parser.go:105-121`; staging, 2026-11-30). `fetch` throws a `PlatformHttpError`:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
await client.fetch("*[_id == $x][0]"); // no $x sent
|
|
365
|
+
// statusCode: 400
|
|
366
|
+
// response.body: {
|
|
367
|
+
// error: {
|
|
368
|
+
// description: "param $x referenced, but not provided",
|
|
369
|
+
// end: 10,
|
|
370
|
+
// query: "*[_id == $x][0]",
|
|
371
|
+
// start: 9,
|
|
372
|
+
// type: "queryParseError",
|
|
373
|
+
// },
|
|
374
|
+
// }
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
It names the first unsent parameter in the query's text, even one in a branch the query never evaluates (`select(false => $x, 1)`). `start` and `end` are code-point offsets of the `$name`, and `start` is left out when it is 0. A parameter sent as `null` is sent; one whose value is `undefined` is not, as `@sanity/client` leaves it out of the request. A `$` in a string or a comment, and a custom function's own parameters, are not query parameters. A syntax error earlier in the query is answered first, as groq-js raises it, and so is a string with an escape the Content Lake refuses (`\q`, `\x41`, `\u{…}`, a lone surrogate), though groq-js accepts some of those; a token's 401 and a missing dataset's 404 come before the refusal.
|
|
378
|
+
|
|
315
379
|
#### Missing datasets
|
|
316
380
|
|
|
317
381
|
`createTestClient({ missingDatasets: ["p1:staged"] })` names datasets the platform does not have, as `"<projectId>:<dataset>"` keys. Every Content Lake request on one (queries, documents, mutations, actions, the History API) throws the `PlatformHttpError` the Content Lake answers for a missing dataset, on every handle of the family:
|
|
@@ -505,6 +569,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
505
569
|
| `client.addFunction(fn)` / `client.removeFunction(id)` | Deploy or remove a function the Functions API invoke route serves (see [Functions](#functions)) |
|
|
506
570
|
| `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
|
|
507
571
|
| `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
|
|
572
|
+
| `client.organizationStore(organizationId)` | The documents of the organization's store, the Workflows store, to seed or inspect (see [Workflows store](#workflows-store)). Throws unless the organization has a store |
|
|
508
573
|
| `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
|
|
509
574
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
510
575
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
3
|
-
var
|
|
3
|
+
var client = require("@sanity/client"), groqJs = require("groq-js"), node_crypto = require("node:crypto");
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
6
6
|
return new Error(`${ERR_PREFIX} ${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 }),
|
|
@@ -2466,6 +2481,107 @@ function internalTokenRefusal(request, check) {
|
|
|
2466
2481
|
}
|
|
2467
2482
|
});
|
|
2468
2483
|
}
|
|
2484
|
+
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;
|
|
2485
|
+
function refuseUnsentParams(args) {
|
|
2486
|
+
const { request, query, params = {}, syntaxErrorAt } = args, { references, invalidStringAt } = scanQuery(query), errorAt = Math.min(syntaxErrorAt ?? 1 / 0, invalidStringAt ?? 1 / 0), unsent = references.find(
|
|
2487
|
+
(reference) => reference.index < errorAt && !isSent(params, reference.name)
|
|
2488
|
+
);
|
|
2489
|
+
if (unsent === void 0) return;
|
|
2490
|
+
const start = codePoints(query.slice(0, unsent.index));
|
|
2491
|
+
throw new PlatformHttpError({
|
|
2492
|
+
...request,
|
|
2493
|
+
statusCode: 400,
|
|
2494
|
+
statusMessage: "Bad Request",
|
|
2495
|
+
body: {
|
|
2496
|
+
error: {
|
|
2497
|
+
description: `param $${unsent.name} referenced, but not provided`,
|
|
2498
|
+
end: start + unsent.name.length,
|
|
2499
|
+
query,
|
|
2500
|
+
...start !== 0 ? { start } : {},
|
|
2501
|
+
type: "queryParseError"
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
function isSent(params, name) {
|
|
2507
|
+
return Object.hasOwn(params, name) && params[name] !== void 0;
|
|
2508
|
+
}
|
|
2509
|
+
function scanQuery(query) {
|
|
2510
|
+
const references = [];
|
|
2511
|
+
let declaration, atStatementStart = !0, index = 0;
|
|
2512
|
+
for (; index < query.length; ) {
|
|
2513
|
+
const char = query[index];
|
|
2514
|
+
if (char === '"' || char === "'") {
|
|
2515
|
+
const end = stringEnd(query, index);
|
|
2516
|
+
if (end === void 0) return { references, invalidStringAt: index };
|
|
2517
|
+
index = end, atStatementStart = !1;
|
|
2518
|
+
continue;
|
|
2519
|
+
}
|
|
2520
|
+
if (query.startsWith("//", index)) {
|
|
2521
|
+
const newline = query.indexOf(`
|
|
2522
|
+
`, index);
|
|
2523
|
+
index = newline === -1 ? query.length : newline + 1;
|
|
2524
|
+
continue;
|
|
2525
|
+
}
|
|
2526
|
+
if (/\s/.test(char)) {
|
|
2527
|
+
index++;
|
|
2528
|
+
continue;
|
|
2529
|
+
}
|
|
2530
|
+
if (atStatementStart && isKeyword(query, index, "fn")) {
|
|
2531
|
+
declaration = { params: /* @__PURE__ */ new Set(), header: !0 }, atStatementStart = !1, index += 2;
|
|
2532
|
+
continue;
|
|
2533
|
+
}
|
|
2534
|
+
if (atStatementStart = !1, declaration?.header && char === ")" && (declaration.header = !1), declaration !== void 0 && char === ";") {
|
|
2535
|
+
declaration = void 0, atStatementStart = !0, index++;
|
|
2536
|
+
continue;
|
|
2537
|
+
}
|
|
2538
|
+
if (char === "$") {
|
|
2539
|
+
IDENT.lastIndex = index + 1;
|
|
2540
|
+
const name = IDENT.exec(query)?.[0];
|
|
2541
|
+
if (name !== void 0) {
|
|
2542
|
+
declaration?.header ? declaration.params.add(name) : declaration?.params.has(name) || references.push({ name, index }), index += 1 + name.length;
|
|
2543
|
+
continue;
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
index++;
|
|
2547
|
+
}
|
|
2548
|
+
return { references, invalidStringAt: void 0 };
|
|
2549
|
+
}
|
|
2550
|
+
function isKeyword(query, index, word) {
|
|
2551
|
+
return query.startsWith(word, index) && !/[A-Za-z0-9_]/.test(query[index + word.length] ?? "");
|
|
2552
|
+
}
|
|
2553
|
+
function stringEnd(query, index) {
|
|
2554
|
+
const quote = query[index];
|
|
2555
|
+
let at = index + 1;
|
|
2556
|
+
for (; at < query.length && query[at] !== quote; ) {
|
|
2557
|
+
if (query[at] !== "\\") {
|
|
2558
|
+
at++;
|
|
2559
|
+
continue;
|
|
2560
|
+
}
|
|
2561
|
+
const escaped = escapeLength(query, at + 1);
|
|
2562
|
+
if (escaped === void 0) return;
|
|
2563
|
+
at += 1 + escaped;
|
|
2564
|
+
}
|
|
2565
|
+
return at + 1;
|
|
2566
|
+
}
|
|
2567
|
+
function escapeLength(query, index) {
|
|
2568
|
+
const char = query[index];
|
|
2569
|
+
if (char === void 0) return 0;
|
|
2570
|
+
if (SIMPLE_ESCAPES.has(char)) return 1;
|
|
2571
|
+
const unit = unicodeEscape(query, index);
|
|
2572
|
+
if (unit === void 0 || unit >= 56320 && unit <= 57343) return;
|
|
2573
|
+
if (unit < 55296 || unit > 56319) return 5;
|
|
2574
|
+
const low = query[index + 5] === "\\" ? unicodeEscape(query, index + 6) : void 0;
|
|
2575
|
+
return low !== void 0 && low >= 56320 && low <= 57343 ? 11 : void 0;
|
|
2576
|
+
}
|
|
2577
|
+
function unicodeEscape(query, index) {
|
|
2578
|
+
UNICODE_ESCAPE.lastIndex = index;
|
|
2579
|
+
const hex = UNICODE_ESCAPE.exec(query)?.[1];
|
|
2580
|
+
return hex === void 0 ? void 0 : Number.parseInt(hex, 16);
|
|
2581
|
+
}
|
|
2582
|
+
function codePoints(text) {
|
|
2583
|
+
return [...text].length;
|
|
2584
|
+
}
|
|
2469
2585
|
const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
|
|
2470
2586
|
"fetch",
|
|
2471
2587
|
"getDocument",
|
|
@@ -2628,6 +2744,42 @@ function wrapWithGuards(client2, config) {
|
|
|
2628
2744
|
}
|
|
2629
2745
|
});
|
|
2630
2746
|
}
|
|
2747
|
+
const READ_ROUTE = /^\/workflows\/organizations\/([^/]+)\/(query|doc|listen)(?=\/|$)(.*)$/, STORE_ROUTE = /^\/organization-stores\/([^/]+)\/(query|mutate|doc|listen|export|references|actions|history)(?=\/|$)(.*)$/, SERVICE_ROUTE = /^\/workflows(?=\/|$)/;
|
|
2748
|
+
function matchWorkflowsStoreRoute(args) {
|
|
2749
|
+
const { path, apiVersion } = args, read = path.match(READ_ROUTE);
|
|
2750
|
+
if (read !== null) {
|
|
2751
|
+
if (apiVersion !== "X") return "unrouted";
|
|
2752
|
+
const [, organizationId, action, rest] = read;
|
|
2753
|
+
return { route: "read", organizationId: decodeURIComponent(organizationId), action, rest };
|
|
2754
|
+
}
|
|
2755
|
+
const store = path.match(STORE_ROUTE);
|
|
2756
|
+
if (store !== null) {
|
|
2757
|
+
if (apiVersion === "1") return "unrouted";
|
|
2758
|
+
const [, storeId, action, rest] = store;
|
|
2759
|
+
return { route: "store", storeId: decodeURIComponent(storeId), action, rest };
|
|
2760
|
+
}
|
|
2761
|
+
if (SERVICE_ROUTE.test(path)) return apiVersion === "X" ? "service" : "unrouted";
|
|
2762
|
+
}
|
|
2763
|
+
function noRouteMatched(request) {
|
|
2764
|
+
return new PlatformHttpError({
|
|
2765
|
+
...request,
|
|
2766
|
+
statusCode: 404,
|
|
2767
|
+
statusMessage: "Not Found",
|
|
2768
|
+
body: { message: "no Route matched with those values" }
|
|
2769
|
+
});
|
|
2770
|
+
}
|
|
2771
|
+
function storeNotFound(request, identifier) {
|
|
2772
|
+
return new PlatformHttpError({
|
|
2773
|
+
...request,
|
|
2774
|
+
statusCode: 404,
|
|
2775
|
+
statusMessage: "Not Found",
|
|
2776
|
+
body: {
|
|
2777
|
+
statusCode: 404,
|
|
2778
|
+
error: "Dataset not found",
|
|
2779
|
+
message: `Dataset for id "${identifier}" not found`
|
|
2780
|
+
}
|
|
2781
|
+
});
|
|
2782
|
+
}
|
|
2631
2783
|
const OPTIONS_ARG_POSITION = {
|
|
2632
2784
|
fetch: 2,
|
|
2633
2785
|
getDocument: 1,
|
|
@@ -2708,6 +2860,79 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
|
|
|
2708
2860
|
);
|
|
2709
2861
|
return validateResource(resource), resource;
|
|
2710
2862
|
};
|
|
2863
|
+
async function serveStoreAction(args) {
|
|
2864
|
+
const { client: client$1, history, action, rest, sent, opts } = args, search = new URL(sent.url).searchParams, tag = opts.tag !== void 0 ? { tag: opts.tag } : {};
|
|
2865
|
+
try {
|
|
2866
|
+
if (action === "doc") {
|
|
2867
|
+
if (sent.method !== "GET") throw notAllowed(sent);
|
|
2868
|
+
const ids = rest.slice(1).split(",").map(decodeURIComponent);
|
|
2869
|
+
if (rest === "" || ids.some((id) => id === ""))
|
|
2870
|
+
throw fakeError(`request(): "${sent.path}" names no document id; GET <store>/doc/<ids>.`);
|
|
2871
|
+
const found = await client$1.getDocuments(ids, tag), readable = new Set(found.flatMap((doc) => doc === null ? [] : [doc._id])), stored = new Set(
|
|
2872
|
+
client$1.store().all().map((doc) => doc._id)
|
|
2873
|
+
);
|
|
2874
|
+
return {
|
|
2875
|
+
documents: found.filter((doc) => doc !== null),
|
|
2876
|
+
omitted: ids.filter((id) => !readable.has(id)).map((id) => ({ id, reason: stored.has(id) ? "permission" : "existence" }))
|
|
2877
|
+
};
|
|
2878
|
+
}
|
|
2879
|
+
if (action === "query") {
|
|
2880
|
+
const { query, params } = storeQuery(sent, search, opts.body);
|
|
2881
|
+
return await client$1.fetch(query, params, {
|
|
2882
|
+
filterResponse: !1,
|
|
2883
|
+
returnQuery: search.get("returnQuery") !== "false",
|
|
2884
|
+
...tag
|
|
2885
|
+
});
|
|
2886
|
+
}
|
|
2887
|
+
if (sent.method !== "POST") throw notAllowed(sent);
|
|
2888
|
+
const body = opts.body;
|
|
2889
|
+
if (!Array.isArray(body?.mutations))
|
|
2890
|
+
throw fakeError(`request(): POST "${sent.path}" needs a body \`{ mutations: [...] }\`.`);
|
|
2891
|
+
const committed = await client$1.mutate(body.mutations, {
|
|
2892
|
+
returnDocuments: !1,
|
|
2893
|
+
returnFirst: !1,
|
|
2894
|
+
...tag
|
|
2895
|
+
}), images = /* @__PURE__ */ new Map();
|
|
2896
|
+
if (search.get("returnDocuments") === "true") {
|
|
2897
|
+
const ids = committed.results.map((result) => result.id), record = history.transactions(ids, () => !0).find((txn) => txn.id === committed.transactionId);
|
|
2898
|
+
for (const mutation of record?.mutations ?? []) {
|
|
2899
|
+
const document = "create" in mutation ? mutation.create : "createOrReplace" in mutation ? mutation.createOrReplace : void 0;
|
|
2900
|
+
document !== void 0 && images.set(document._id, document);
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
return {
|
|
2904
|
+
transactionId: committed.transactionId,
|
|
2905
|
+
results: committed.results.map((result) => {
|
|
2906
|
+
const document = images.get(result.id) ?? (search.get("returnDocuments") === "true" ? client$1.store().get(result.id) : void 0);
|
|
2907
|
+
return document !== void 0 ? { ...result, document } : result;
|
|
2908
|
+
})
|
|
2909
|
+
};
|
|
2910
|
+
} catch (error) {
|
|
2911
|
+
throw (error instanceof client.ClientError || error instanceof client.ServerError) && Object.assign(error.response, { method: sent.method, url: sent.url }), error;
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
function storeQuery(sent, search, body) {
|
|
2915
|
+
if (sent.method === "POST") {
|
|
2916
|
+
const posted = body;
|
|
2917
|
+
if (typeof posted?.query != "string")
|
|
2918
|
+
throw fakeError(`request(): POST "${sent.path}" needs a body \`{ query, params? }\`.`);
|
|
2919
|
+
return { query: posted.query, params: posted.params ?? {} };
|
|
2920
|
+
}
|
|
2921
|
+
const query = search.get("query");
|
|
2922
|
+
if (query === null) throw fakeError(`request(): GET "${sent.path}" needs a \`query\` parameter.`);
|
|
2923
|
+
const params = Object.fromEntries(
|
|
2924
|
+
[...search].filter(([name]) => name.startsWith("$")).map(([name, value]) => [name.slice(1), JSON.parse(value)])
|
|
2925
|
+
);
|
|
2926
|
+
return { query, params };
|
|
2927
|
+
}
|
|
2928
|
+
function notAllowed(sent) {
|
|
2929
|
+
return fakeError(`request(): ${sent.method} "${sent.path}" is not a method this route takes.`);
|
|
2930
|
+
}
|
|
2931
|
+
function clientResources(registry) {
|
|
2932
|
+
return [...registry.values()].filter(
|
|
2933
|
+
(entry) => entry.resource.type !== "organization-store"
|
|
2934
|
+
);
|
|
2935
|
+
}
|
|
2711
2936
|
function ensureEntry(registry, resource) {
|
|
2712
2937
|
const key = registryKey(resource);
|
|
2713
2938
|
let entry = registry.get(key);
|
|
@@ -2808,6 +3033,19 @@ function createTestClient(options = {}) {
|
|
|
2808
3033
|
configuredPerspective: options.perspective
|
|
2809
3034
|
});
|
|
2810
3035
|
}
|
|
3036
|
+
function parseQuery(request, query, params) {
|
|
3037
|
+
try {
|
|
3038
|
+
const tree = groqJs.parse(query, params ? { params } : void 0);
|
|
3039
|
+
return refuseUnsentParams({ request, query, params }), tree;
|
|
3040
|
+
} catch (error) {
|
|
3041
|
+
throw refuseUnsentParams({
|
|
3042
|
+
request,
|
|
3043
|
+
query,
|
|
3044
|
+
params,
|
|
3045
|
+
...error instanceof groqJs.GroqSyntaxError ? { syntaxErrorAt: error.position } : {}
|
|
3046
|
+
}), error;
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
2811
3049
|
function dedupeIds(results) {
|
|
2812
3050
|
const seen = /* @__PURE__ */ new Set(), out = [];
|
|
2813
3051
|
for (const r of results)
|
|
@@ -2872,7 +3110,7 @@ function makeHandle(handleArgs) {
|
|
|
2872
3110
|
apiVersion,
|
|
2873
3111
|
useCdn,
|
|
2874
3112
|
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 = () => {
|
|
3113
|
+
} = 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
3114
|
if (token === void 0) return accessControl;
|
|
2877
3115
|
const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
|
|
2878
3116
|
if (verified !== void 0 && "refused" in verified)
|
|
@@ -2881,7 +3119,7 @@ function makeHandle(handleArgs) {
|
|
|
2881
3119
|
throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
|
|
2882
3120
|
return {
|
|
2883
3121
|
// Per-project records apply only where the resource lives in a project.
|
|
2884
|
-
currentUser:
|
|
3122
|
+
currentUser: storeCapabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
|
|
2885
3123
|
...identity.globalUser !== void 0 ? { globalUser: identity.globalUser } : {},
|
|
2886
3124
|
...identity.robot ? { robot: !0 } : {},
|
|
2887
3125
|
grants: identity.grants,
|
|
@@ -2911,7 +3149,50 @@ function makeHandle(handleArgs) {
|
|
|
2911
3149
|
);
|
|
2912
3150
|
if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
|
|
2913
3151
|
throw projectApiDown(sent);
|
|
2914
|
-
|
|
3152
|
+
const routed = activeAccess()?.aclPath === (opts.uri ?? opts.url) ? void 0 : matchWorkflowsStoreRoute({ path: sent.path, apiVersion });
|
|
3153
|
+
return routed !== void 0 ? serveWorkflowsStore(routed, sent, opts) : request(opts);
|
|
3154
|
+
}, serveWorkflowsStore = (routed, sent, opts) => {
|
|
3155
|
+
if (routed === "unrouted") throw noRouteMatched(sent);
|
|
3156
|
+
if (routed === "service")
|
|
3157
|
+
throw fakeError(
|
|
3158
|
+
`request(): ${sent.method} "${sent.path}" goes to the Workflows service, which the fake does not serve. Mount a Workflows service double for it.`
|
|
3159
|
+
);
|
|
3160
|
+
const store2 = routed.route === "read" ? activeStoreOf(routed.organizationId) : [...backend.organizationStores.values()].find(
|
|
3161
|
+
(one) => one.id === routed.storeId && one.status === "active"
|
|
3162
|
+
);
|
|
3163
|
+
if (store2 === void 0)
|
|
3164
|
+
throw storeNotFound(
|
|
3165
|
+
sent,
|
|
3166
|
+
routed.route === "read" ? `org:${routed.organizationId}` : routed.storeId
|
|
3167
|
+
);
|
|
3168
|
+
const servedActions = routed.route === "read" ? ["query", "doc"] : ["query", "doc", "mutate"];
|
|
3169
|
+
if (!servedActions.includes(routed.action))
|
|
3170
|
+
throw fakeError(
|
|
3171
|
+
`request(): "${sent.path}" is ${routed.action} on the organization store; the fake serves ${servedActions.join(", ")} there.`
|
|
3172
|
+
);
|
|
3173
|
+
const onStore = makeHandle({
|
|
3174
|
+
...handleArgs,
|
|
3175
|
+
resource: void 0,
|
|
3176
|
+
// Both routes are on the global API host, whatever host the caller's other requests go to.
|
|
3177
|
+
useProjectHostname: !1,
|
|
3178
|
+
perspective: "raw",
|
|
3179
|
+
configuredPerspective: void 0,
|
|
3180
|
+
internalStore: {
|
|
3181
|
+
resource: { type: "organization-store", id: store2.id },
|
|
3182
|
+
store: { id: store2.id, organizationId: store2.organizationId }
|
|
3183
|
+
}
|
|
3184
|
+
});
|
|
3185
|
+
return serveStoreAction({
|
|
3186
|
+
client: onStore,
|
|
3187
|
+
history: ensureEntry(registry, { type: "organization-store", id: store2.id }).history,
|
|
3188
|
+
action: routed.action,
|
|
3189
|
+
rest: routed.rest,
|
|
3190
|
+
sent,
|
|
3191
|
+
opts
|
|
3192
|
+
});
|
|
3193
|
+
}, activeStoreOf = (organizationId) => {
|
|
3194
|
+
const store2 = backend.organizationStores.get(organizationId);
|
|
3195
|
+
return store2?.status === "active" ? store2 : void 0;
|
|
2915
3196
|
}, admitToLake = (request) => {
|
|
2916
3197
|
if (refuseSession2(request), missingKey !== void 0) {
|
|
2917
3198
|
const parts = datasetParts(target.id);
|
|
@@ -2991,7 +3272,7 @@ function makeHandle(handleArgs) {
|
|
|
2991
3272
|
...accessControl.access !== void 0 ? { access: accessControl.access } : {}
|
|
2992
3273
|
}
|
|
2993
3274
|
] : []
|
|
2994
|
-
], capabilities =
|
|
3275
|
+
], capabilities = storeCapabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
|
|
2995
3276
|
if (target.type !== "dataset") return;
|
|
2996
3277
|
const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
|
|
2997
3278
|
return backend.missingDatasets.has(key) ? key : void 0;
|
|
@@ -3030,6 +3311,7 @@ function makeHandle(handleArgs) {
|
|
|
3030
3311
|
projectId,
|
|
3031
3312
|
dataset,
|
|
3032
3313
|
...resource !== void 0 ? { resource } : {},
|
|
3314
|
+
...handleArgs.internalStore !== void 0 ? { organizationStore: { ...handleArgs.internalStore.store } } : {},
|
|
3033
3315
|
mutations,
|
|
3034
3316
|
...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
|
|
3035
3317
|
});
|
|
@@ -3204,16 +3486,15 @@ function makeHandle(handleArgs) {
|
|
|
3204
3486
|
return applyPerspective(accessible, override ?? perspective);
|
|
3205
3487
|
}, client2 = {
|
|
3206
3488
|
fetch: async (query, params, opts) => {
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
)
|
|
3216
|
-
const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
|
|
3489
|
+
const request = queryRequest({
|
|
3490
|
+
query,
|
|
3491
|
+
params,
|
|
3492
|
+
tag: opts?.tag,
|
|
3493
|
+
perspective: opts?.perspective,
|
|
3494
|
+
returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
|
|
3495
|
+
});
|
|
3496
|
+
admitToLake(request);
|
|
3497
|
+
const start = Date.now(), tree = parseQuery(request, query, params), result = await (await groqJs.evaluate(tree, {
|
|
3217
3498
|
dataset: await visibleDocs(opts?.perspective),
|
|
3218
3499
|
...params !== void 0 ? { params } : {}
|
|
3219
3500
|
})).get();
|
|
@@ -3439,7 +3720,7 @@ function makeHandle(handleArgs) {
|
|
|
3439
3720
|
identities: members,
|
|
3440
3721
|
// A dataset stands for its project, and every project exists in
|
|
3441
3722
|
// the fake, so a dataset handle still counts as before.
|
|
3442
|
-
resources: () =>
|
|
3723
|
+
resources: () => clientResources(registry).filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
|
|
3443
3724
|
},
|
|
3444
3725
|
functions: {
|
|
3445
3726
|
apiVersion,
|
|
@@ -3504,7 +3785,7 @@ function makeHandle(handleArgs) {
|
|
|
3504
3785
|
backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);
|
|
3505
3786
|
},
|
|
3506
3787
|
datasets: () => [...registry.values()].filter((entry) => entry.resource.type === "dataset").map((entry) => datasetParts(entry.resource.id)),
|
|
3507
|
-
resources: () =>
|
|
3788
|
+
resources: () => clientResources(registry).map((entry) => ({ ...entry.resource })),
|
|
3508
3789
|
stub: (name, handler) => {
|
|
3509
3790
|
backend.stubs.set(name, handler);
|
|
3510
3791
|
},
|
|
@@ -3524,6 +3805,14 @@ function makeHandle(handleArgs) {
|
|
|
3524
3805
|
backend.outages.add(component);
|
|
3525
3806
|
},
|
|
3526
3807
|
completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
|
|
3808
|
+
organizationStore: (organizationId) => {
|
|
3809
|
+
const organizationStore = backend.organizationStores.get(organizationId);
|
|
3810
|
+
if (organizationStore === void 0)
|
|
3811
|
+
throw fakeError(
|
|
3812
|
+
`organizationStore(): organization "${organizationId}" has no store. Seed createTestClient({ organizationStores }), or look it up with GET /internal/organization-stores first.`
|
|
3813
|
+
);
|
|
3814
|
+
return ensureEntry(registry, { type: "organization-store", id: organizationStore.id }).store;
|
|
3815
|
+
},
|
|
3527
3816
|
addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
|
|
3528
3817
|
removeFunction: (id) => unregisterFunction(backend.functions, id),
|
|
3529
3818
|
functionInvocations: () => structuredClone(backend.functions.invocations),
|
|
@@ -3554,7 +3843,7 @@ function makeHandle(handleArgs) {
|
|
|
3554
3843
|
"error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
|
|
3555
3844
|
};
|
|
3556
3845
|
},
|
|
3557
|
-
recorded: RECORDED_METHODS
|
|
3846
|
+
recorded: handleArgs.internalStore === void 0 ? RECORDED_METHODS : /* @__PURE__ */ new Set()
|
|
3558
3847
|
});
|
|
3559
3848
|
}
|
|
3560
3849
|
exports.ERR_PREFIX = ERR_PREFIX;
|