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