@superbee/view-host 0.0.0-stage → 0.1.1-pre.1

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.
@@ -0,0 +1,892 @@
1
+ /**
2
+ * An operation-mapped View bridge host: the parent-page half of the View protocol
3
+ * (`docs/VIEW-PROTOCOL.md`, bridge `v0` and the v1 `read-versioned` and `action.propose`), for a
4
+ * page that runs a View in a sandboxed frame. It parses what the View's frame posts, maps each data
5
+ * request onto one named operation that the page's `execute` callback runs on the person's behalf,
6
+ * and answers in the protocol's vocabulary. It has no data semantics of its own:
7
+ *
8
+ * | request | operation |
9
+ * | --- | --- |
10
+ * | `query` | `documents.query.v1` |
11
+ * | `read`, `read-versioned`, `render-document` | `documents.read.v1` |
12
+ * | `relationships` | `documents.relationships.v1` |
13
+ * | `edges` | `documents.edges.v1` |
14
+ * | `graph` | `bundles.graph.v1` |
15
+ * | `action.propose` (v1) | the page's `proposeAction` (`documents.update.v1` behind its confirmation) |
16
+ *
17
+ * A request whose operation the caller does not offer is not declared in `hello` and is refused
18
+ * with `FORBIDDEN`. A `query` asks for up to 500 rows; the host reads `documents.query.v1` a page of
19
+ * at most 100 at a time (`./query-pages.ts`, the rule the local View bridge shares), so one `query`
20
+ * is several `execute` calls, and answers an exact `count` and `more`. Rows carry raw frontmatter:
21
+ * `query.kind-projection` is not declared.
22
+ *
23
+ * The bundle is fixed when the host is made: every operation input carries that `bundleId` and a
24
+ * View cannot name another. Nothing here builds an address: `hello.bundle` is `{ root: null, name }`,
25
+ * and `open-page` asks the page's own resolver.
26
+ *
27
+ * A host that stops answering must remove the frame. The protocol's reference client never times a
28
+ * request out, so a frame whose requests go unanswered waits forever: when `admitted()` turns false
29
+ * the host calls `invalidate()` and answers nothing more, and when `stop()` runs waiting requests are
30
+ * dropped. In both cases the page removes the View's frame (`invalidate` is where it does so).
31
+ */
32
+ import { ACTION_BRIDGE_PROTOCOL, parseActionBridgeMessage, actionReply } from "./action-bridge.js";
33
+ import { assertSafeConceptId } from "@superbee/core/storage";
34
+ import { isAnyRegistryId } from "@superbee/core/page";
35
+ import { compareCodeUnits } from "@superbee/core/code-unit-order";
36
+ // Nothing on this path loads a schema library: the host maps messages onto operations with plain
37
+ // checks, and the operation's own input schema, where `execute` runs it, is the validator.
38
+ import { ReadAdapterError } from "./read-adapter-error.js";
39
+ import { readQueryPages, VIEW_QUERY_MAX_ROWS } from "./query-pages.js";
40
+ export { ReadAdapterError } from "./read-adapter-error.js";
41
+ /** The row orders `documents.query.v1` answers: canonical id (the default) or newest first. */
42
+ export const QUERY_ORDERS = ["id", "newest"];
43
+ /** `bundles.graph.v1`'s ceilings, which equal the protocol's `graph` ceilings. */
44
+ export const GRAPH_MAX_DOCUMENTS = 1000;
45
+ export const GRAPH_MAX_RELATIONSHIPS = 10000;
46
+ export const BRIDGE_PROTOCOL = "v0";
47
+ export { ACTION_BRIDGE_PROTOCOL };
48
+ /** The operations a View's requests map onto, by the names the caller's `execute` runs them under. */
49
+ export const VIEW_BRIDGE_OPERATIONS = [
50
+ "documents.read.v1",
51
+ "documents.query.v1",
52
+ "documents.relationships.v1",
53
+ "documents.edges.v1",
54
+ "bundles.graph.v1",
55
+ "documents.update.v1",
56
+ ];
57
+ const MAX_MESSAGE_BYTES = 65536;
58
+ /** An oversize message is answered TOO_LARGE only when its `id` reads cheaply from the top level. */
59
+ const MAX_OVERSIZE_ECHO_ID_BYTES = 255;
60
+ const MAX_REQUEST_ID_BYTES = 128;
61
+ const MAX_ACTION_REQUEST_ID_BYTES = 64;
62
+ const MAX_HOST_CAPABILITY_BYTES = 128;
63
+ const HOST_CAPABILITY_NAME = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
64
+ const MAX_DOC_ID_BYTES = 1024;
65
+ /** A `query`'s row ceiling, read from `documents.query.v1` a page at a time. */
66
+ const MAX_QUERY_ROWS = VIEW_QUERY_MAX_ROWS;
67
+ /** The operations' bounds on a query's text facets and a document id, in UTF-8 bytes. */
68
+ const MAX_QUERY_TEXT_BYTES = 256;
69
+ const MAX_QUERY_PREFIX_BYTES = 512;
70
+ /** The most values one `field` filter may list. */
71
+ const MAX_FIELD_VALUES = 32;
72
+ const MAX_CANONICAL_ID_BYTES = 512;
73
+ /** `documents.edges.v1`'s own row ceiling; the operation refuses above it. */
74
+ const MAX_EDGE_ROWS = 1000;
75
+ const MAX_DOCUMENT_BODY_BYTES = 1024 * 1024;
76
+ const MAX_REPLY_BYTES = 2 * 1024 * 1024;
77
+ const HOST_INVOKE_TIMEOUT_MS = 15000;
78
+ /** At most four operations execute at once; further requests wait FIFO rather than being dropped,
79
+ * since the protocol's reference client never retries. */
80
+ const MAX_IN_FLIGHT = 4;
81
+ const MAX_PENDING = 64;
82
+ const SEEN_WINDOW = 10000;
83
+ /** The ceilings this host enforces where the caller offers the request; `bridgeLimits` zeroes the
84
+ * ones it does not offer, which is how the protocol expresses "not offered". */
85
+ export const BRIDGE_LIMITS = Object.freeze({
86
+ query: MAX_QUERY_ROWS,
87
+ edges: MAX_EDGE_ROWS,
88
+ graphDocuments: GRAPH_MAX_DOCUMENTS,
89
+ graphRelationships: GRAPH_MAX_RELATIONSHIPS,
90
+ replyBytes: MAX_REPLY_BYTES,
91
+ });
92
+ const encoder = new TextEncoder();
93
+ const byteLength = (value) => encoder.encode(value).length;
94
+ class BridgeFailure extends Error {
95
+ code;
96
+ constructor(code, message) {
97
+ super(message);
98
+ this.code = code;
99
+ }
100
+ }
101
+ function isPlainRecord(value) {
102
+ if (typeof value !== "object" || value === null || Array.isArray(value))
103
+ return false;
104
+ const prototype = Object.getPrototypeOf(value);
105
+ return prototype === Object.prototype || prototype === null;
106
+ }
107
+ function exactKeys(value, expected) {
108
+ const actual = Object.keys(value).sort();
109
+ const wanted = [...expected].sort();
110
+ return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
111
+ }
112
+ function boundedString(value, maxBytes) {
113
+ return typeof value === "string" && value.length > 0 && byteLength(value) <= maxBytes ? value : null;
114
+ }
115
+ function normalizeQueryParams(raw) {
116
+ if (!isPlainRecord(raw))
117
+ return null;
118
+ // `cursor` (the protocol's `query.cursor`, not offered here) is an unknown key like any other: USAGE.
119
+ const allowed = new Set(["type", "prefix", "field", "open", "limit", "order"]);
120
+ if (Object.keys(raw).some((key) => !allowed.has(key)))
121
+ return null;
122
+ const out = {};
123
+ if (raw.type !== undefined) {
124
+ const value = boundedString(raw.type, 256)?.trim();
125
+ if (!value)
126
+ return null;
127
+ out.type = value;
128
+ }
129
+ if (raw.prefix !== undefined) {
130
+ const value = boundedString(raw.prefix, 1024)?.trim();
131
+ if (!value)
132
+ return null;
133
+ out.prefix = value;
134
+ }
135
+ if (raw.field !== undefined) {
136
+ const value = boundedString(raw.field, 1024)?.trim();
137
+ if (!value)
138
+ return null;
139
+ out.field = value;
140
+ }
141
+ if (raw.open !== undefined) {
142
+ if (raw.open !== true && raw.open !== false)
143
+ return null;
144
+ if (raw.open)
145
+ out.open = true;
146
+ }
147
+ if (raw.limit !== undefined) {
148
+ if (!Number.isSafeInteger(raw.limit) || raw.limit < 0)
149
+ return null;
150
+ out.limit = raw.limit;
151
+ }
152
+ if (raw.order !== undefined) {
153
+ if (!QUERY_ORDERS.includes(raw.order))
154
+ return null;
155
+ out.order = raw.order;
156
+ }
157
+ return out;
158
+ }
159
+ /** The envelope only: an object of `from`, `to` and `text`. Their values (canonical ids or prefixes,
160
+ * 1 to 32, at most 1,024 bytes, nonblank text) are checked by the operation, whose `invalid_input`
161
+ * answers `USAGE`. */
162
+ function edgeParams(raw) {
163
+ return isPlainRecord(raw) && Object.keys(raw).every((key) => key === "from" || key === "to" || key === "text")
164
+ ? raw
165
+ : null;
166
+ }
167
+ /** The protocol's request grammar, extended by the reserved `host` request. A type this host does not
168
+ * serve is refused with FORBIDDEN and never dropped, so a View can tell refusal from silence. */
169
+ function parseBridgeRequest(value) {
170
+ const bridge = value.bridge;
171
+ const type = value.type;
172
+ // A v1 id is bounded at 64 bytes, as the protocol's other hosts bound it before forwarding.
173
+ const idBytes = bridge === ACTION_BRIDGE_PROTOCOL ? MAX_ACTION_REQUEST_ID_BYTES : MAX_REQUEST_ID_BYTES;
174
+ const id = boundedString(value.id, idBytes) ?? undefined;
175
+ // A refusal echoes whichever correlation key the message carried, so an action proposal
176
+ // (keyed by `requestId`) is refused in a reply its client can match, never dropped.
177
+ const echo = id ?? boundedString(value.requestId, idBytes) ?? undefined;
178
+ const usage = (message) => ({ kind: "refused", bridge, id: echo, code: "USAGE", message });
179
+ if (bridge === ACTION_BRIDGE_PROTOCOL) {
180
+ if (type !== "read-versioned")
181
+ return { kind: "refused", bridge, id: echo, code: "FORBIDDEN", message: "this host serves no bridge actions" };
182
+ if (!exactKeys(value, ["bridge", "type", "id", "docId"]) || !id)
183
+ return usage("invalid read-versioned request");
184
+ const docId = boundedString(value.docId, MAX_DOC_ID_BYTES);
185
+ return docId ? { kind: "read-versioned", bridge, id, docId } : usage("invalid read-versioned request");
186
+ }
187
+ if (type === "hello" || type === "subscribe" || type === "query" || type === "edges" || type === "graph") {
188
+ if (!id)
189
+ return usage(`invalid ${type} request`);
190
+ if (type === "hello" || type === "subscribe")
191
+ return exactKeys(value, ["bridge", "type", "id"]) ? { kind: type, bridge, id } : usage(`invalid ${type} request`);
192
+ if (type === "query") {
193
+ const params = exactKeys(value, ["bridge", "type", "id", "params"]) ? normalizeQueryParams(value.params) : null;
194
+ return params ? { kind: "query", bridge, id, params } : usage("invalid query request");
195
+ }
196
+ if (type === "edges") {
197
+ const params = exactKeys(value, ["bridge", "type", "id", "params"]) ? edgeParams(value.params) : null;
198
+ return params ? { kind: "edges", bridge, id, params } : usage("invalid edges request");
199
+ }
200
+ const expected = value.includeBodies === undefined ? ["bridge", "type", "id"] : ["bridge", "type", "id", "includeBodies"];
201
+ if (!exactKeys(value, expected) || (value.includeBodies !== undefined && typeof value.includeBodies !== "boolean"))
202
+ return usage("invalid graph request");
203
+ return { kind: "graph", bridge, id, includeBodies: value.includeBodies === true };
204
+ }
205
+ if (type === "read" || type === "render-document") {
206
+ if (!id)
207
+ return usage(`invalid ${type} request`);
208
+ const docId = exactKeys(value, ["bridge", "type", "id", "docId"])
209
+ ? boundedString(value.docId, MAX_DOC_ID_BYTES)
210
+ : null;
211
+ return docId ? { kind: type, bridge, id, docId } : usage(`invalid ${type} request`);
212
+ }
213
+ if (type === "relationships") {
214
+ // The cursor is whatever this host answered for the previous page, sent back unchanged; the
215
+ // operation's own input check is its validator.
216
+ const expected = value.cursor === undefined ? ["bridge", "type", "id", "docId"] : ["bridge", "type", "id", "docId", "cursor"];
217
+ const docId = id && exactKeys(value, expected) ? boundedString(value.docId, MAX_DOC_ID_BYTES) : null;
218
+ if (!docId || (value.cursor !== undefined && !isPlainRecord(value.cursor)))
219
+ return usage("invalid relationships request");
220
+ return {
221
+ kind: "relationships",
222
+ bridge,
223
+ id: id,
224
+ docId,
225
+ ...(value.cursor === undefined ? {} : { cursor: value.cursor }),
226
+ };
227
+ }
228
+ if (type === "open-page") {
229
+ const expected = value.id === undefined ? ["bridge", "type", "pageId"] : ["bridge", "type", "id", "pageId"];
230
+ const wellFormed = exactKeys(value, expected) && (value.id === undefined || !!id) && isAnyRegistryId(value.pageId);
231
+ return { kind: "open-page", bridge, id: echo, pageId: wellFormed ? value.pageId : null };
232
+ }
233
+ if (type === "host") {
234
+ if (!id)
235
+ return usage("invalid host request");
236
+ const expected = value.input === undefined
237
+ ? ["bridge", "type", "id", "capability"]
238
+ : ["bridge", "type", "id", "capability", "input"];
239
+ // The envelope grammar (a registry-shaped name, an object input) is checked before the
240
+ // capability lookup, so a malformed request is USAGE and only an undeclared name is FORBIDDEN.
241
+ const capability = exactKeys(value, expected) ? boundedString(value.capability, MAX_HOST_CAPABILITY_BYTES) : null;
242
+ if (!capability || !HOST_CAPABILITY_NAME.test(capability))
243
+ return usage("invalid host request");
244
+ if (value.input !== undefined && !isPlainRecord(value.input))
245
+ return usage("host input must be an object");
246
+ return { kind: "host", bridge, id, capability, input: value.input };
247
+ }
248
+ return { kind: "refused", bridge, id: echo, code: "FORBIDDEN", message: `this host does not serve ${type}` };
249
+ }
250
+ /** The registry capabilities this host declares for `operations` and the page's services, sorted as
251
+ * the protocol requires. `documents.query.v1` answers the OR of field values, the terminal filter,
252
+ * a total count and newest-first order, so `query.field-or`, `query.open`, `query.count` and
253
+ * `query.newest` are declared with it. Rows carry raw frontmatter, so `query.kind-projection` is
254
+ * not. Whether `query` is offered at all is `limits.query`, not a capability. */
255
+ export function bridgeCapabilities(operations, services = {}) {
256
+ const capabilities = [];
257
+ if (operations.has("documents.edges.v1"))
258
+ capabilities.push("edges");
259
+ if (operations.has("bundles.graph.v1"))
260
+ capabilities.push("graph");
261
+ if (operations.has("documents.query.v1"))
262
+ capabilities.push("query.count", "query.field-or", "query.newest", "query.open");
263
+ if (operations.has("documents.relationships.v1"))
264
+ capabilities.push("relationships");
265
+ if (operations.has("documents.read.v1") && services.renderDocument)
266
+ capabilities.push("render-document");
267
+ if (operations.has("documents.read.v1") && services.recordOpen)
268
+ capabilities.push("record.open");
269
+ // `frame.resize` needs no bundle operation: it reports a height, it reads nothing.
270
+ if (services.frameResize)
271
+ capabilities.push("frame.resize");
272
+ // `open-page` is the registry's "navigates the shell": declared where the page resolves sibling
273
+ // Views and opens them; it reads nothing either.
274
+ if (services.openPage)
275
+ capabilities.push("open-page");
276
+ return capabilities.sort(compareCodeUnits);
277
+ }
278
+ /** The `frame.resize` input: one finite, non-negative CSS pixel height and nothing else. */
279
+ function frameResizeInput(input) {
280
+ if (!isPlainRecord(input) || !exactKeys(input, ["height"]))
281
+ return null;
282
+ const height = input.height;
283
+ // No upper bound here: the registry names only finite and non-negative, and the sizer clamps.
284
+ return typeof height === "number" && Number.isFinite(height) && height >= 0 ? height : null;
285
+ }
286
+ /** The declared ceilings: `0` for a request the caller does not offer. */
287
+ export function bridgeLimits(operations) {
288
+ const query = operations.has("documents.query.v1"), edges = operations.has("documents.edges.v1"), graph = operations.has("bundles.graph.v1");
289
+ return {
290
+ query: query ? BRIDGE_LIMITS.query : 0,
291
+ edges: edges ? BRIDGE_LIMITS.edges : 0,
292
+ graphDocuments: graph ? BRIDGE_LIMITS.graphDocuments : 0,
293
+ graphRelationships: graph ? BRIDGE_LIMITS.graphRelationships : 0,
294
+ replyBytes: BRIDGE_LIMITS.replyBytes,
295
+ };
296
+ }
297
+ const operationFor = {
298
+ query: "documents.query.v1",
299
+ read: "documents.read.v1",
300
+ "read-versioned": "documents.read.v1",
301
+ "render-document": "documents.read.v1",
302
+ relationships: "documents.relationships.v1",
303
+ edges: "documents.edges.v1",
304
+ graph: "bundles.graph.v1",
305
+ };
306
+ /** One canonical document id, as the operations accept one, or null. */
307
+ function canonicalId(value) {
308
+ if (typeof value !== "string" || !value || byteLength(value) > MAX_CANONICAL_ID_BYTES)
309
+ return null;
310
+ try {
311
+ assertSafeConceptId(value);
312
+ return value;
313
+ }
314
+ catch {
315
+ return null;
316
+ }
317
+ }
318
+ /** Refused reads a retry alone never changes: grant denials and the older wire signals a caller
319
+ * may still forward. */
320
+ const DENIED_CODES = new Set([
321
+ "bundle_not_found",
322
+ "insufficient_scope",
323
+ "access_denied",
324
+ "denied",
325
+ ]);
326
+ /** A `query` as `documents.query.v1`'s selection (`type`, `prefix`, `fieldsAnyOf`, `open`, `order`)
327
+ * and the rows asked for. The protocol's `field` grammar: split at the first `=`, ignore a filter
328
+ * with no `=` or an empty key, drop empty values, and match nothing on an empty value list (`null`:
329
+ * no operation runs). Several values are an OR; `progress_status` is the logical Kind field, which
330
+ * the operation resolves. */
331
+ function queryInput(params) {
332
+ if (params.limit !== undefined && params.limit > MAX_QUERY_ROWS)
333
+ throw new BridgeFailure("USAGE", `this host answers at most ${MAX_QUERY_ROWS} rows`);
334
+ const selection = {};
335
+ const invalid = () => new BridgeFailure("USAGE", "invalid query parameters");
336
+ if (params.type) {
337
+ if (byteLength(params.type) > MAX_QUERY_TEXT_BYTES)
338
+ throw invalid();
339
+ selection.type = params.type;
340
+ }
341
+ if (params.prefix) {
342
+ const bare = params.prefix.endsWith("/") ? params.prefix.slice(0, -1) : params.prefix;
343
+ if (byteLength(params.prefix) > MAX_QUERY_PREFIX_BYTES || canonicalId(bare) === null)
344
+ throw invalid();
345
+ selection.prefix = params.prefix;
346
+ }
347
+ if (params.open)
348
+ selection.open = true;
349
+ // `id` is the operation's default order, so only `newest` is sent.
350
+ if (params.order === "newest")
351
+ selection.order = "newest";
352
+ if (params.field !== undefined) {
353
+ const separator = params.field.indexOf("=");
354
+ const key = separator < 0 ? "" : params.field.slice(0, separator).trim();
355
+ if (key) {
356
+ const values = params.field
357
+ .slice(separator + 1)
358
+ .split(",")
359
+ .map((value) => value.trim())
360
+ .filter((value) => value.length > 0);
361
+ if (values.length === 0)
362
+ return null;
363
+ if (values.length > MAX_FIELD_VALUES ||
364
+ byteLength(key) > MAX_QUERY_TEXT_BYTES ||
365
+ values.some((value) => byteLength(value) > MAX_QUERY_TEXT_BYTES))
366
+ throw invalid();
367
+ selection.fieldsAnyOf = { [key]: values };
368
+ }
369
+ }
370
+ return { selection, limit: params.limit ? params.limit : MAX_QUERY_ROWS };
371
+ }
372
+ function readInput(docId) {
373
+ const documentId = canonicalId(docId);
374
+ if (documentId === null)
375
+ throw new BridgeFailure("USAGE", "docId must be one canonical document id");
376
+ return { documentId };
377
+ }
378
+ function boundedBody(body) {
379
+ if (byteLength(body) > MAX_DOCUMENT_BODY_BYTES)
380
+ throw new BridgeFailure("TOO_LARGE", "the document body exceeded the 1 MiB View limit");
381
+ return body;
382
+ }
383
+ function readDocument(raw) {
384
+ const data = raw;
385
+ boundedBody(data.document.body);
386
+ return data;
387
+ }
388
+ /** `bundles.graph.v1` lists links by source and target, not by text, so `graph.relationships` is
389
+ * sorted here by `(from, to, text)`, by code unit rather than locale so every browser answers the
390
+ * same order. (`edges` arrives in the operation's own order, by code point.) */
391
+ function orderedEdges(edges) {
392
+ return edges
393
+ .map(({ from, to, text }) => ({ from, to, text }))
394
+ .sort((a, b) => compareCodeUnits(a.from, b.from) || compareCodeUnits(a.to, b.to) || compareCodeUnits(a.text, b.text));
395
+ }
396
+ function operationFailure(error) {
397
+ switch (error.code) {
398
+ case "document_not_found":
399
+ return new BridgeFailure("NOT_FOUND", error.message);
400
+ case "insufficient_scope":
401
+ case "bundle_not_found":
402
+ case "access_denied":
403
+ return new BridgeFailure("REVOKED", "the View lost access while the request was running");
404
+ case "invalid_input":
405
+ case "validation_failed":
406
+ return new BridgeFailure("USAGE", error.message);
407
+ case "result_too_large":
408
+ return new BridgeFailure("TOO_LARGE", error.message);
409
+ default:
410
+ return new BridgeFailure("RUNTIME", "the View request failed");
411
+ }
412
+ }
413
+ function thrownFailure(error) {
414
+ if (error instanceof BridgeFailure)
415
+ return error;
416
+ const code = error?.code;
417
+ if (typeof code === "string" && DENIED_CODES.has(code))
418
+ return new BridgeFailure("REVOKED", "the View lost access while the request was running");
419
+ if (code === "invalid_input")
420
+ return new BridgeFailure("USAGE", "invalid request");
421
+ // The host's result ceiling throws a plain `invalid_response`; the adapter's shape check throws
422
+ // its own error class with the same message, and only the ceiling is a size failure.
423
+ if (!(error instanceof ReadAdapterError) && error instanceof Error && error.message === "invalid_response")
424
+ return new BridgeFailure("TOO_LARGE", "the reply exceeded the host's result limit");
425
+ return new BridgeFailure("RUNTIME", "the View request failed");
426
+ }
427
+ /** The operation's data, or its refusal as the View's bridge error. */
428
+ function operationData(raw) {
429
+ const envelope = raw;
430
+ if (!isPlainRecord(envelope) || typeof envelope.ok !== "boolean")
431
+ throw new BridgeFailure("RUNTIME", "the View request failed");
432
+ if (!envelope.ok)
433
+ throw operationFailure(envelope.error);
434
+ return envelope.data;
435
+ }
436
+ /** `documents.query.v1`'s pages as the protocol's reply: the rows, an exact `count`, `more` when the
437
+ * cap cut matching rows, and each document the operation left out (frontmatter that does not parse
438
+ * or is too large to carry), named as the protocol's other hosts name it. */
439
+ function queryReply(answer) {
440
+ const rows = answer.rows.map(({ id, version, frontmatter }) => ({ id, version, frontmatter }));
441
+ return {
442
+ rows,
443
+ count: answer.count,
444
+ ...(answer.count > rows.length ? { more: true } : {}),
445
+ ...(answer.skipped.length > 0 ? { skipped: answer.skipped } : {}),
446
+ };
447
+ }
448
+ function translate(request, raw, render) {
449
+ const data = operationData(raw);
450
+ switch (request.kind) {
451
+ case "read": {
452
+ const { document } = readDocument(data);
453
+ return { id: document.id, frontmatter: document.frontmatter, body: document.body };
454
+ }
455
+ case "read-versioned": {
456
+ const { document, version } = readDocument(data);
457
+ return { doc: { id: document.id, frontmatter: document.frontmatter, body: document.body }, version };
458
+ }
459
+ case "render-document": {
460
+ const { document, version } = readDocument(data);
461
+ const rendered = render({ id: document.id, body: document.body });
462
+ return { document: { id: document.id, version }, html: rendered.html, bounded: rendered.bounded };
463
+ }
464
+ case "relationships": {
465
+ // The operation's page as the protocol's: the neighbor, its label and title, and the
466
+ // operation's own continuation as the opaque `cursor` the View sends back unchanged.
467
+ const page = data;
468
+ return {
469
+ documentId: request.docId,
470
+ rows: page.links.map(({ direction, documentId, label, title }) => ({ direction, documentId, label, title })),
471
+ ...(page.next === undefined ? {} : { cursor: page.next }),
472
+ };
473
+ }
474
+ case "edges": {
475
+ // The operation's rows and order, as they are; above its cap it refuses (`result_too_large`).
476
+ const edges = data.edges.map(({ from, to, text }) => ({ from, to, text }));
477
+ return { edges, count: edges.length };
478
+ }
479
+ case "graph": {
480
+ const graph = data;
481
+ if (graph.documents.length > GRAPH_MAX_DOCUMENTS)
482
+ throw new BridgeFailure("TOO_LARGE", `the graph exceeded ${GRAPH_MAX_DOCUMENTS} documents`);
483
+ if (graph.relationships.length > GRAPH_MAX_RELATIONSHIPS)
484
+ throw new BridgeFailure("TOO_LARGE", `the graph exceeded ${GRAPH_MAX_RELATIONSHIPS} relationships`);
485
+ // A graph row must not carry a body that a plain read would refuse: one oversize body refuses
486
+ // the whole request, with no partial rows.
487
+ const documents = graph.documents.map(({ id, version, frontmatter, body }) => ({
488
+ id,
489
+ version,
490
+ frontmatter,
491
+ ...(body === undefined ? {} : { body: boundedBody(body) }),
492
+ }));
493
+ const relationships = orderedEdges(graph.relationships);
494
+ return {
495
+ okfVersion: graph.okfVersion ?? "0.1",
496
+ documents,
497
+ relationships,
498
+ counts: { documents: documents.length, relationships: relationships.length },
499
+ };
500
+ }
501
+ }
502
+ }
503
+ /** Thrown out of a request the host no longer answers (stopped, withdrawn, or not admitted). */
504
+ const WITHDRAWN = Symbol("withdrawn");
505
+ const uiFailure = {
506
+ not_found: "NOT_FOUND",
507
+ denied: "REVOKED",
508
+ invalid_input: "USAGE",
509
+ unsupported: "FORBIDDEN",
510
+ busy: "RUNTIME",
511
+ unavailable: "RUNTIME",
512
+ cancelled: "RUNTIME",
513
+ };
514
+ /** The host for one View frame. `frame` is the frame's window (the only source whose messages are
515
+ * admitted, and only from the opaque origin `"null"` a `sandbox="allow-scripts"` frame has);
516
+ * `bundle` is fixed for the host's life; `execute` runs an operation on the person's behalf. The
517
+ * page forwards every `message` event to `receive`, calls `refresh` when its data may have
518
+ * changed, and `stop` when it removes the frame. */
519
+ export function createViewBridgeHost(frame, bundle, execute, options) {
520
+ if (!Array.isArray(options.operations) ||
521
+ options.operations.some((operation) => !VIEW_BRIDGE_OPERATIONS.includes(operation)) ||
522
+ new Set(options.operations).size !== options.operations.length)
523
+ throw new Error("Invalid View bridge operation subset");
524
+ if (typeof bundle?.id !== "string" || !bundle.id || typeof bundle.name !== "string")
525
+ throw new Error("Invalid View bridge bundle");
526
+ const operations = new Set(options.operations);
527
+ const bundleId = bundle.id;
528
+ const admitted = () => options.admitted?.() !== false;
529
+ const invalidate = () => options.invalidate?.();
530
+ let stopped = false, ready = false, subscribed = false;
531
+ const seen = new Set();
532
+ const active = new Map();
533
+ const queue = [];
534
+ /** Requests the frame sent are remembered in a sliding window, so a repeated id is refused as
535
+ * `USAGE` while the first is pending or recently answered. */
536
+ const remember = (id) => {
537
+ if (seen.size >= SEEN_WINDOW)
538
+ seen.delete(seen.values().next().value);
539
+ seen.add(id);
540
+ };
541
+ const post = (data) => {
542
+ if (!stopped)
543
+ frame.postMessage(data, "*");
544
+ };
545
+ const fail = (bridge, id, code, message) => post({ bridge, id, type: "error", error: { code, message } });
546
+ const reply = (bridge, id, type, result) => {
547
+ const message = { bridge, id, type: `${type}:result`, result };
548
+ if (byteLength(JSON.stringify(message)) > MAX_REPLY_BYTES)
549
+ fail(bridge, id, "TOO_LARGE", "the bridge reply exceeded the 2 MiB safety limit");
550
+ else
551
+ post(message);
552
+ };
553
+ const actionAvailable = () => operations.has("documents.read.v1") && operations.has("documents.update.v1") && !!options.proposeAction;
554
+ let activeAction = false;
555
+ const recordOpen = () => operations.has("documents.read.v1") && !!options.openRecord && options.recordAvailable?.() !== false;
556
+ const renderDocument = !!options.renderDocument;
557
+ const openPage = !!options.openPage;
558
+ async function invokeHost(request, documentId) {
559
+ const controller = new AbortController();
560
+ active.set(request.id, controller);
561
+ let timedOut = false;
562
+ const timer = setTimeout(() => {
563
+ timedOut = true;
564
+ controller.abort();
565
+ fail(request.bridge, request.id, "RUNTIME", "the record reader did not answer in time");
566
+ }, HOST_INVOKE_TIMEOUT_MS);
567
+ try {
568
+ const result = await options.openRecord(documentId, controller.signal);
569
+ if (stopped || controller.signal.aborted || active.get(request.id) !== controller)
570
+ return;
571
+ if (!admitted()) {
572
+ invalidate();
573
+ return;
574
+ }
575
+ if (result.ok)
576
+ reply(request.bridge, request.id, "host", { capability: request.capability, output: { opened: true } });
577
+ else
578
+ fail(request.bridge, request.id, uiFailure[result.code] ?? "RUNTIME", `record.open answered ${result.code}`);
579
+ }
580
+ catch {
581
+ if (!timedOut)
582
+ fail(request.bridge, request.id, "RUNTIME", "the record reader failed");
583
+ }
584
+ finally {
585
+ clearTimeout(timer);
586
+ active.delete(request.id);
587
+ }
588
+ }
589
+ const allows = (request) => operations.has(operationFor[request.kind]) &&
590
+ (request.kind !== "render-document" || renderDocument) &&
591
+ !(request.kind === "graph" && request.includeBodies && !operations.has("documents.read.v1"));
592
+ async function invokeOperation(request) {
593
+ const operation = operationFor[request.kind];
594
+ const controller = new AbortController();
595
+ active.set(request.id, controller);
596
+ /** Runs the operation once. Each call is checked as the request is: a stopped host, a withdrawn
597
+ * request or a View no longer admitted ends the request with no reply. */
598
+ const run = async (input) => {
599
+ const raw = await execute(operation, Object.freeze({ ...input, bundleId }), controller.signal);
600
+ if (stopped || controller.signal.aborted || active.get(request.id) !== controller)
601
+ throw WITHDRAWN;
602
+ if (!admitted()) {
603
+ invalidate();
604
+ throw WITHDRAWN;
605
+ }
606
+ return raw;
607
+ };
608
+ try {
609
+ if (request.kind === "query") {
610
+ const query = queryInput(request.params);
611
+ if (query === null) {
612
+ // A field filter with an empty value list matches nothing; no operation runs.
613
+ reply(request.bridge, request.id, request.kind, { rows: [], count: 0 });
614
+ return;
615
+ }
616
+ // Each page is its own call; a page that fails fails the whole query, with no partial rows.
617
+ const answer = await readQueryPages(async (input) => operationData(await run(input)), query.selection, query.limit);
618
+ reply(request.bridge, request.id, request.kind, queryReply(answer));
619
+ return;
620
+ }
621
+ const input = request.kind === "edges"
622
+ ? request.params
623
+ : request.kind === "graph"
624
+ ? request.includeBodies
625
+ ? { includeBodies: true }
626
+ : {}
627
+ : request.kind === "relationships"
628
+ ? { ...readInput(request.docId), ...(request.cursor ? { cursor: request.cursor } : {}) }
629
+ : readInput(request.docId);
630
+ const raw = await run({
631
+ ...input,
632
+ ...(request.kind === "read-versioned" && actionAvailable() ? { includeViewActionContext: true } : {}),
633
+ });
634
+ reply(request.bridge, request.id, request.kind, translate(request, raw, options.renderDocument));
635
+ }
636
+ catch (error) {
637
+ if (error === WITHDRAWN || stopped || controller.signal.aborted)
638
+ return;
639
+ const failure = thrownFailure(error);
640
+ fail(request.bridge, request.id, failure.code, failure.message);
641
+ }
642
+ finally {
643
+ active.delete(request.id);
644
+ }
645
+ }
646
+ function pump() {
647
+ while (!stopped && active.size < MAX_IN_FLIGHT && queue.length > 0) {
648
+ const entry = queue.shift();
649
+ void entry.run().finally(() => {
650
+ entry.settle();
651
+ pump();
652
+ });
653
+ }
654
+ }
655
+ /** Executes `run` in one of the in-flight slots, FIFO behind the requests already waiting. The
656
+ * returned promise settles when the request is answered or the host stops. */
657
+ function enqueue(bridge, id, run) {
658
+ if (queue.length >= MAX_PENDING) {
659
+ fail(bridge, id, "RUNTIME", "too many pending requests");
660
+ return Promise.resolve();
661
+ }
662
+ return new Promise((settle) => {
663
+ queue.push({
664
+ settle,
665
+ async run() {
666
+ // The binding may have changed while the request waited; `admitted` is checked again at
667
+ // the start of execution, as it is checked before and after every operation.
668
+ if (stopped)
669
+ return;
670
+ if (!admitted()) {
671
+ invalidate();
672
+ return;
673
+ }
674
+ await run();
675
+ },
676
+ });
677
+ pump();
678
+ });
679
+ }
680
+ return {
681
+ /** An empty `change` after `subscribe`: the refresh signal a host without deltas may send. */
682
+ refresh() {
683
+ if (stopped || !subscribed)
684
+ return;
685
+ if (!admitted()) {
686
+ invalidate();
687
+ return;
688
+ }
689
+ post({ bridge: BRIDGE_PROTOCOL, type: "change", event: { changes: [], removed: [] } });
690
+ },
691
+ /** The frame is gone, or about to be: nothing waiting is answered and nothing more is read. */
692
+ stop() {
693
+ stopped = true;
694
+ for (const controller of active.values())
695
+ controller.abort();
696
+ active.clear();
697
+ seen.clear();
698
+ // Waiting requests get no reply, and their callers are released.
699
+ for (const entry of queue.splice(0))
700
+ entry.settle();
701
+ },
702
+ async receive(event) {
703
+ if (stopped || event.source !== frame || event.origin !== "null")
704
+ return;
705
+ const data = event.data;
706
+ if (!isPlainRecord(data) ||
707
+ (data.bridge !== BRIDGE_PROTOCOL && data.bridge !== ACTION_BRIDGE_PROTOCOL) ||
708
+ typeof data.type !== "string")
709
+ return;
710
+ let serialized;
711
+ try {
712
+ serialized = JSON.stringify(data);
713
+ }
714
+ catch {
715
+ return;
716
+ }
717
+ if (data.bridge === ACTION_BRIDGE_PROTOCOL && data.type === "action.propose" && actionAvailable()) {
718
+ const parsed = parseActionBridgeMessage(data);
719
+ const id = boundedString(data.requestId, MAX_ACTION_REQUEST_ID_BYTES);
720
+ if (!id)
721
+ return;
722
+ if (!parsed?.ok || parsed.message.type !== "action.propose") {
723
+ post(actionReply(id, { status: "rejected", message: "Invalid View action proposal." }));
724
+ return;
725
+ }
726
+ if (!admitted()) {
727
+ invalidate();
728
+ return;
729
+ }
730
+ if (seen.has(id) || activeAction) {
731
+ post(actionReply(id, {
732
+ status: "rejected",
733
+ message: "A proposal is already active or this request was already used.",
734
+ }));
735
+ return;
736
+ }
737
+ remember(id);
738
+ activeAction = true;
739
+ const controller = new AbortController();
740
+ active.set(id, controller);
741
+ try {
742
+ const result = await options.proposeAction(parsed.message.action, controller.signal);
743
+ if (!stopped && admitted())
744
+ post(actionReply(id, result));
745
+ else if (!stopped)
746
+ invalidate();
747
+ }
748
+ catch {
749
+ if (!stopped)
750
+ post(actionReply(id, {
751
+ status: "failed",
752
+ writeState: "unknown",
753
+ message: "The outcome is unknown. Read the document before another proposal.",
754
+ }));
755
+ }
756
+ finally {
757
+ activeAction = false;
758
+ active.delete(id);
759
+ }
760
+ return;
761
+ }
762
+ if (byteLength(serialized) > MAX_MESSAGE_BYTES) {
763
+ // The one message with no reply is an oversize one whose id cannot be read cheaply: a
764
+ // top-level string id under 256 bytes is echoed in a TOO_LARGE reply, anything else is
765
+ // uncorrelatable and ignored. Nothing else the frame sends goes unanswered.
766
+ const echo = boundedString(data.id, MAX_OVERSIZE_ECHO_ID_BYTES) ??
767
+ boundedString(data.requestId, MAX_OVERSIZE_ECHO_ID_BYTES);
768
+ if (echo)
769
+ fail(data.bridge, echo, "TOO_LARGE", "the bridge request exceeded the 64 KiB message limit");
770
+ return;
771
+ }
772
+ if (!ready) {
773
+ ready = true;
774
+ options.onReady?.();
775
+ }
776
+ const request = parseBridgeRequest(data);
777
+ if (request.kind === "refused") {
778
+ fail(request.bridge, request.id, request.code, request.message);
779
+ return;
780
+ }
781
+ if (request.kind === "open-page") {
782
+ // The protocol's vocabulary for a host that navigates: a well-formed registry id the page
783
+ // does not open (another bundle's View among them) is NOT_FOUND; a malformed envelope (a
784
+ // document id, wrong keys, a non-string pageId) is USAGE as for every other request type; a
785
+ // page without a resolver does not serve open-page at all, FORBIDDEN. Each echoes the id
786
+ // when one was sent; a fire-and-forget request has no id to repeat, one with an id is
787
+ // deduplicated.
788
+ if (!openPage) {
789
+ fail(request.bridge, request.id, "FORBIDDEN", "this host does not serve open-page");
790
+ return;
791
+ }
792
+ if (request.pageId === null) {
793
+ fail(request.bridge, request.id, "USAGE", "invalid open-page request");
794
+ return;
795
+ }
796
+ if (request.id !== undefined) {
797
+ if (seen.has(request.id)) {
798
+ fail(request.bridge, request.id, "USAGE", "duplicate request id");
799
+ return;
800
+ }
801
+ remember(request.id);
802
+ }
803
+ if (!admitted()) {
804
+ invalidate();
805
+ return;
806
+ }
807
+ if (options.openPage(request.pageId) !== true)
808
+ fail(request.bridge, request.id, "NOT_FOUND", "this host does not open that View");
809
+ return;
810
+ }
811
+ if (seen.has(request.id)) {
812
+ fail(request.bridge, request.id, "USAGE", "duplicate request id");
813
+ return;
814
+ }
815
+ remember(request.id);
816
+ if (!admitted()) {
817
+ invalidate();
818
+ return;
819
+ }
820
+ // hello, subscribe and every refusal answer at once; only work that reaches the transport or
821
+ // the host reader takes one of the in-flight slots.
822
+ if (request.kind === "hello") {
823
+ reply(request.bridge, request.id, "hello", {
824
+ // No address: the View is named by its bundle and registry id, never a path.
825
+ bundle: { root: null, name: bundle.name },
826
+ mode: "hosted",
827
+ protocol: BRIDGE_PROTOCOL,
828
+ grant: actionAvailable() ? "propose" : "read",
829
+ ...(actionAvailable()
830
+ ? { actionProtocol: "v1", actions: ["document.set-field", "document.set-body", "document.update"] }
831
+ : {}),
832
+ host: {
833
+ kind: "hosted",
834
+ capabilities: bridgeCapabilities(operations, {
835
+ renderDocument,
836
+ recordOpen: recordOpen(),
837
+ frameResize: !!options.frame,
838
+ openPage,
839
+ }),
840
+ limits: bridgeLimits(operations),
841
+ // Additive descriptor fields: a View that ignores them draws as it does elsewhere.
842
+ ...(options.frame
843
+ ? {
844
+ frame: { title: "host", height: "content", maxHeight: options.frame.maxHeight },
845
+ ...(options.frame.theme ? { theme: options.frame.theme } : {}),
846
+ }
847
+ : {}),
848
+ },
849
+ });
850
+ return;
851
+ }
852
+ if (request.kind === "subscribe") {
853
+ subscribed = true;
854
+ reply(request.bridge, request.id, "subscribe", { ok: true });
855
+ return;
856
+ }
857
+ if (request.kind === "host") {
858
+ if (request.capability === "frame.resize" && options.frame) {
859
+ // Answered at once, like hello: a height report touches no bundle data.
860
+ const height = frameResizeInput(request.input);
861
+ if (height === null)
862
+ fail(request.bridge, request.id, "USAGE", "frame.resize takes one height in CSS pixels");
863
+ else
864
+ reply(request.bridge, request.id, "host", {
865
+ capability: request.capability,
866
+ output: { height: options.frame.resize(height) },
867
+ });
868
+ return;
869
+ }
870
+ if (request.capability !== "record.open" || !recordOpen()) {
871
+ fail(request.bridge, request.id, "FORBIDDEN", `this host does not offer ${request.capability}`);
872
+ return;
873
+ }
874
+ const documentId = isPlainRecord(request.input) && exactKeys(request.input, ["documentId"])
875
+ ? canonicalId(request.input.documentId)
876
+ : null;
877
+ if (documentId === null) {
878
+ fail(request.bridge, request.id, "USAGE", "record.open takes one canonical documentId");
879
+ return;
880
+ }
881
+ await enqueue(request.bridge, request.id, () => invokeHost(request, documentId));
882
+ return;
883
+ }
884
+ if (!allows(request)) {
885
+ fail(request.bridge, request.id, "FORBIDDEN", `this host does not offer ${request.kind}`);
886
+ return;
887
+ }
888
+ await enqueue(request.bridge, request.id, () => invokeOperation(request));
889
+ },
890
+ };
891
+ }
892
+ //# sourceMappingURL=view-bridge-host.js.map