@botiverse/porthole 0.7.0 → 0.9.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.
Files changed (166) hide show
  1. package/README.md +9 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/annotate/types.d.ts +40 -4
  4. package/dist/annotate/types.js +6 -1
  5. package/dist/annotate/validate.d.ts +10 -0
  6. package/dist/annotate/validate.js +24 -1
  7. package/dist/bridge/bounded-text.d.ts +34 -0
  8. package/dist/bridge/bounded-text.js +188 -0
  9. package/dist/bridge/bridge.d.ts +25 -5
  10. package/dist/bridge/bridge.js +311 -73
  11. package/dist/bridge/json-data.d.ts +28 -0
  12. package/dist/bridge/json-data.js +86 -0
  13. package/dist/bridge/navigation.d.ts +5 -0
  14. package/dist/bridge/navigation.js +7 -0
  15. package/dist/bridge/refusal.js +1 -0
  16. package/dist/bridge/types.d.ts +32 -1
  17. package/dist/check/page-source.js +1 -1
  18. package/dist/check/page.js +2 -0
  19. package/dist/compile/compile.d.ts +6 -0
  20. package/dist/compile/compile.js +3 -1
  21. package/dist/compile/policy.d.ts +38 -2
  22. package/dist/compile/policy.js +122 -7
  23. package/dist/config/capabilities.d.ts +23 -4
  24. package/dist/config/capabilities.js +12 -2
  25. package/dist/config/schema.d.ts +11 -0
  26. package/dist/config/validate.d.ts +8 -2
  27. package/dist/config/validate.js +28 -6
  28. package/dist/config/warnings.d.ts +20 -0
  29. package/dist/config/warnings.js +25 -0
  30. package/dist/conformance/behavior.js +46 -1
  31. package/dist/conformance/cookies.d.ts +15 -0
  32. package/dist/conformance/cookies.js +80 -0
  33. package/dist/conformance/harness/page.d.ts +1 -0
  34. package/dist/conformance/harness/page.js +9 -2
  35. package/dist/conformance/harness-source.js +1 -1
  36. package/dist/conformance/host-kit.js +5 -1
  37. package/dist/conformance/index.d.ts +10 -0
  38. package/dist/conformance/limits.js +38 -1
  39. package/dist/conformance/runtime.js +10 -0
  40. package/dist/conformance/served.d.ts +2 -0
  41. package/dist/conformance/served.js +737 -4
  42. package/dist/files/paths.js +4 -0
  43. package/dist/guide/gates.d.ts +7 -1
  44. package/dist/guide/gates.js +12 -0
  45. package/dist/guide/guide.js +2 -2
  46. package/dist/guide/runtime.js +11 -3
  47. package/dist/host/create-host.js +81 -39
  48. package/dist/host/pages-of-set.d.ts +43 -0
  49. package/dist/host/pages-of-set.js +196 -0
  50. package/dist/host/types.d.ts +8 -1
  51. package/dist/index.d.ts +5 -4
  52. package/dist/index.js +3 -2
  53. package/dist/mcp/adapter.js +11 -15
  54. package/dist/node/index.d.ts +36 -4
  55. package/dist/node/index.js +402 -101
  56. package/dist/platform/types.d.ts +9 -0
  57. package/dist/platform/web.js +8 -0
  58. package/dist/presets/presets.d.ts +16 -8
  59. package/dist/presets/presets.js +39 -8
  60. package/dist/protocol/live-data.d.ts +6 -2
  61. package/dist/protocol/live-data.js +20 -1
  62. package/dist/protocol/mcp-apps.d.ts +13 -2
  63. package/dist/protocol/mcp-apps.js +10 -2
  64. package/dist/protocol/message-text.d.ts +8 -0
  65. package/dist/protocol/message-text.js +29 -0
  66. package/dist/protocol/runtime-calls.js +3 -0
  67. package/dist/protocol/shell-adapter.js +16 -22
  68. package/dist/react/context-notice.d.ts +32 -0
  69. package/dist/react/context-notice.js +28 -0
  70. package/dist/react/dialog.js +62 -18
  71. package/dist/react/frame.d.ts +18 -3
  72. package/dist/react/frame.js +79 -2
  73. package/dist/react/index.d.ts +2 -1
  74. package/dist/react/index.js +2 -1
  75. package/dist/runtime/contract.d.ts +9 -1
  76. package/dist/runtime/contract.js +31 -2
  77. package/dist/runtime/db.d.ts +41 -6
  78. package/dist/runtime/db.js +120 -16
  79. package/dist/runtime/declaration.d.ts +15 -1
  80. package/dist/runtime/declaration.js +184 -87
  81. package/dist/runtime/requests.js +27 -11
  82. package/dist/runtime/types.generated.js +1 -1
  83. package/dist/server/files.d.ts +5 -0
  84. package/dist/server/files.js +22 -7
  85. package/dist/server/host.d.ts +18 -1
  86. package/dist/server/host.js +132 -2
  87. package/dist/server/index.d.ts +1 -1
  88. package/dist/server/index.js +1 -1
  89. package/dist/server/peer.d.ts +4 -0
  90. package/dist/server/peer.js +19 -0
  91. package/dist/server/proxy.d.ts +6 -0
  92. package/dist/server/proxy.js +12 -3
  93. package/dist/server/server.js +113 -26
  94. package/dist/server/types.d.ts +6 -3
  95. package/dist/shell/annotate.d.ts +7 -2
  96. package/dist/shell/annotate.js +233 -15
  97. package/dist/shell/document.d.ts +8 -0
  98. package/dist/shell/document.js +3 -0
  99. package/dist/shell/runtime.js +361 -14
  100. package/docs/ADOPTING.md +119 -14
  101. package/docs/ARCHITECTURE.md +15 -4
  102. package/docs/DECISIONS.md +1610 -9
  103. package/docs/DESIGN.md +114 -30
  104. package/docs/THREAT_MODEL.md +652 -0
  105. package/package.json +14 -3
  106. package/src/annotate/types.ts +37 -5
  107. package/src/annotate/validate.ts +30 -1
  108. package/src/bridge/bounded-text.ts +240 -0
  109. package/src/bridge/bridge.ts +373 -84
  110. package/src/bridge/json-data.ts +95 -0
  111. package/src/bridge/navigation.ts +10 -0
  112. package/src/bridge/refusal.ts +1 -0
  113. package/src/bridge/types.ts +30 -1
  114. package/src/check/page.ts +2 -0
  115. package/src/compile/compile.ts +9 -1
  116. package/src/compile/policy.ts +130 -7
  117. package/src/config/capabilities.ts +22 -3
  118. package/src/config/schema.ts +11 -0
  119. package/src/config/validate.ts +43 -5
  120. package/src/config/warnings.ts +42 -0
  121. package/src/conformance/behavior.ts +54 -1
  122. package/src/conformance/cookies.ts +93 -0
  123. package/src/conformance/harness/page.ts +11 -2
  124. package/src/conformance/host-kit.ts +10 -1
  125. package/src/conformance/index.ts +10 -0
  126. package/src/conformance/limits.ts +39 -1
  127. package/src/conformance/runtime.ts +21 -0
  128. package/src/conformance/served.ts +888 -4
  129. package/src/files/paths.ts +4 -0
  130. package/src/guide/gates.ts +13 -1
  131. package/src/guide/guide.ts +3 -3
  132. package/src/guide/runtime.ts +12 -3
  133. package/src/host/create-host.ts +88 -38
  134. package/src/host/pages-of-set.ts +226 -0
  135. package/src/host/types.ts +15 -1
  136. package/src/index.ts +5 -0
  137. package/src/mcp/adapter.ts +16 -20
  138. package/src/node/index.ts +507 -116
  139. package/src/platform/types.ts +6 -0
  140. package/src/platform/web.ts +10 -0
  141. package/src/presets/presets.ts +60 -17
  142. package/src/protocol/live-data.ts +31 -3
  143. package/src/protocol/mcp-apps.ts +11 -2
  144. package/src/protocol/message-text.ts +36 -0
  145. package/src/protocol/runtime-calls.ts +3 -0
  146. package/src/protocol/shell-adapter.ts +27 -23
  147. package/src/react/context-notice.tsx +95 -0
  148. package/src/react/dialog.tsx +77 -17
  149. package/src/react/frame.tsx +107 -2
  150. package/src/react/index.ts +8 -1
  151. package/src/runtime/contract.ts +36 -2
  152. package/src/runtime/db.ts +140 -20
  153. package/src/runtime/declaration.ts +227 -89
  154. package/src/runtime/requests.ts +27 -11
  155. package/src/runtime/types.generated.ts +1 -1
  156. package/src/server/files.ts +29 -11
  157. package/src/server/host.ts +158 -3
  158. package/src/server/index.ts +1 -0
  159. package/src/server/peer.ts +21 -0
  160. package/src/server/proxy.ts +13 -3
  161. package/src/server/server.ts +139 -36
  162. package/src/server/types.ts +6 -3
  163. package/src/shell/annotate.ts +233 -15
  164. package/src/shell/document.ts +8 -0
  165. package/src/shell/runtime.ts +361 -14
  166. package/types/runtime/v1/context.d.ts +13 -2
@@ -4,6 +4,7 @@ import { isRefused, reasonOf, Refused } from "../bridge/refusal.js";
4
4
  import { writeClipboard } from "../host/clipboard.js";
5
5
  import { createHost } from "../host/create-host.js";
6
6
  import { ConfirmDialog } from "./dialog.js";
7
+ import { ContextNotice } from "./context-notice.js";
7
8
  import { createLiveFrames } from "./live.js";
8
9
  import { CopyToast } from "./toast.js";
9
10
  /**
@@ -12,6 +13,9 @@ import { CopyToast } from "./toast.js";
12
13
  * display mounts it when it nears the screen, streams its content, flips its theme, and remembers
13
14
  * its height. All the isolation is the core's (`createHost`); this is mounting and lifecycle.
14
15
  */
16
+ /** Why a model context update didn't go: it was never drawn (the review of P100). */
17
+ const REPLACED_UNSEEN = "a later update of this display replaced it before the person saw it";
18
+ const HIDDEN_UNSEEN = "the person hid this display's notice before the update was drawn";
15
19
  /** How far off screen a frame starts (and keeps) running. */
16
20
  const NEAR_SCREEN = "800px 0px";
17
21
  /** The height a display holds before it has reported its own. */
@@ -84,6 +88,67 @@ export function PortholeProvider(props) {
84
88
  return copied;
85
89
  }, []);
86
90
  const closeNotice = useCallback(() => setNotice(null), []);
91
+ // The default show (P100): each display's latest model context update, in the notice, outside
92
+ // every frame; the host's own `show` replaces it.
93
+ const [contexts, setContexts] = useState([]);
94
+ // Each show waiting for its own update to be on the page (after the review: React may draw two
95
+ // updates of a display in one render, the latest only). The number orders a display's shows.
96
+ const unseen = useRef([]);
97
+ const latest = useRef(new Map());
98
+ const sequence = useRef(0);
99
+ useLayoutEffect(() => {
100
+ unseen.current = unseen.current.filter((each) => {
101
+ const drawn = contexts.find((one) => one.displayId === each.entry.displayId);
102
+ if (drawn === each.entry) {
103
+ each.resolve();
104
+ return false;
105
+ }
106
+ // A later update of the display replaced it before it was drawn: never seen, never sent.
107
+ if ((latest.current.get(each.entry.displayId) ?? 0) > each.seq) {
108
+ each.reject(new Error(REPLACED_UNSEEN));
109
+ return false;
110
+ }
111
+ return true;
112
+ });
113
+ }, [contexts]);
114
+ const ownShow = useRef(props.show);
115
+ useLayoutEffect(() => {
116
+ ownShow.current = props.show;
117
+ });
118
+ const show = useCallback((request) => {
119
+ if (ownShow.current !== undefined) {
120
+ return ownShow.current(request);
121
+ }
122
+ if (request.capability !== "setModelContext") {
123
+ // The notice words model context only: anything else it would show unworded, so it isn't
124
+ // shown, and doesn't go (fail closed).
125
+ throw new Error(`Porthole's notice shows model context only, not ${request.capability}`);
126
+ }
127
+ const entry = {
128
+ displayId: request.display.id,
129
+ title: request.display.title,
130
+ update: request.args,
131
+ };
132
+ sequence.current += 1;
133
+ const seq = sequence.current;
134
+ latest.current.set(entry.displayId, seq);
135
+ // The call goes once this very update is on the page, so the handler never has it first.
136
+ return new Promise((resolve, reject) => {
137
+ unseen.current.push({ entry, seq, resolve, reject });
138
+ setContexts((each) => [...each.filter((one) => one.displayId !== entry.displayId), entry]);
139
+ });
140
+ }, []);
141
+ const hideContext = useCallback((displayId) => {
142
+ // Hidden by the person: an update of the display not drawn yet never will be.
143
+ unseen.current = unseen.current.filter((each) => {
144
+ if (each.entry.displayId !== displayId) {
145
+ return true;
146
+ }
147
+ each.reject(new Error(HIDDEN_UNSEEN));
148
+ return false;
149
+ });
150
+ setContexts((each) => each.filter((one) => one.displayId !== displayId));
151
+ }, []);
87
152
  // Compared by value, and read when used: an inline hostInfo or locator doesn't start every
88
153
  // frame again on each render.
89
154
  const hostInfo = useByValue(props.hostInfo);
@@ -131,6 +196,7 @@ export function PortholeProvider(props) {
131
196
  heights,
132
197
  confirm,
133
198
  copyText,
199
+ show,
134
200
  ...(consents ? { consent } : {}),
135
201
  ...(refusesAll === undefined ? {} : { refusesAll }),
136
202
  ...(caches ? { cached } : {}),
@@ -147,6 +213,7 @@ export function PortholeProvider(props) {
147
213
  heights,
148
214
  confirm,
149
215
  copyText,
216
+ show,
150
217
  consents,
151
218
  consent,
152
219
  refusesAll,
@@ -187,7 +254,7 @@ export function PortholeProvider(props) {
187
254
  }
188
255
  current?.resolve(accepted ? "accepted" : "declined");
189
256
  setQueue((waiting) => waiting.slice(1));
190
- } })) : null, props.notify !== undefined ? null : (_jsx(CopyToast, { notice: notice, ...(props.toastClassName === undefined ? {} : { className: props.toastClassName }), onClose: closeNotice, onCopy: (failed) => {
257
+ } })) : null, props.show !== undefined ? null : (_jsx(ContextNotice, { updates: contexts, onHide: hideContext, ...(props.contextClassName === undefined ? {} : { className: props.contextClassName }) })), props.notify !== undefined ? null : (_jsx(CopyToast, { notice: notice, ...(props.toastClassName === undefined ? {} : { className: props.toastClassName }), onClose: closeNotice, onCopy: (failed) => {
191
258
  // A click on the host's own page: the write has the gesture it needs now.
192
259
  void writeClipboard(failed.text, globalThis.document).then((copied) => setNotice({ ...failed, copied }));
193
260
  } }))] }));
@@ -305,7 +372,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
305
372
  // value) re-themes the running display, never makes it again (#9, P074). What a display is
306
373
  // made with comes from the provider's stable parts below.
307
374
  const latestPage = useEffectEvent(() => page);
308
- const { handlers: pageHandlers, copyText: pageCopyText, confirm: pageConfirm, consent: pageConsent, cached: pageCached, hostInfo, locate, nonce, } = page;
375
+ const { handlers: pageHandlers, copyText: pageCopyText, confirm: pageConfirm, consent: pageConsent, show: pageShow, cached: pageCached, hostInfo, locate, nonce, } = page;
309
376
  const notify = useEffectEvent((event, detail) => {
310
377
  switch (event) {
311
378
  case "initialized":
@@ -422,6 +489,15 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
422
489
  },
423
490
  }
424
491
  : {}),
492
+ // Shown as the latest props name the display (P100).
493
+ ...(pageShow === undefined
494
+ ? {}
495
+ : {
496
+ show: (request) => pageShow({
497
+ ...request,
498
+ display: { ...request.display, id: latest().displayId, title: latest().title },
499
+ }),
500
+ }),
425
501
  ...(caches
426
502
  ? {
427
503
  cached: (args, context) => (latest().cached ?? pageCached)?.(args, named(context)),
@@ -489,6 +565,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
489
565
  pageCopyText,
490
566
  pageConfirm,
491
567
  pageConsent,
568
+ pageShow,
492
569
  pageCached,
493
570
  refusesAll,
494
571
  hostInfo,
@@ -2,7 +2,7 @@
2
2
  * `@botiverse/porthole/react`: the thin React binding (TSX: a host's bundler compiles it, or the
3
3
  * package's `dist`). Peer: `react` (19.2+, for `useEffectEvent`).
4
4
  *
5
- * <PortholeProvider> // per page: live-frame cap, heights, the dialog, the copy toast
5
+ * <PortholeProvider> // per page: live-frame cap, heights, the dialog, the copy toast, the context notice
6
6
  * <PortholeFrame config={widgetConfig} displayId={id} title={title} scheme={scheme}
7
7
  * content={code} partial={streaming} handlers={{ sendPrompt, openLink }}
8
8
  * theme={tokensFor} onError={report} />
@@ -10,6 +10,7 @@
10
10
  */
11
11
  export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, type PlaceholderProps, type PortholeFrameProps, type ConfirmActions, type PortholeProviderProps, } from "./frame.tsx";
12
12
  export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
13
+ export { ContextNotice, contextSize, contextText, type ContextNoticeProps, type ContextUpdate, } from "./context-notice.tsx";
13
14
  export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, type PortholeFallbackProps, type PortholeViewProps, } from "./view.tsx";
14
15
  export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, type CopyNotice, type CopyToastProps, } from "./toast.tsx";
15
16
  export { admitFrame, createLiveFrames, type FrameState, type LiveFrames } from "./live.ts";
@@ -2,7 +2,7 @@
2
2
  * `@botiverse/porthole/react`: the thin React binding (TSX: a host's bundler compiles it, or the
3
3
  * package's `dist`). Peer: `react` (19.2+, for `useEffectEvent`).
4
4
  *
5
- * <PortholeProvider> // per page: live-frame cap, heights, the dialog, the copy toast
5
+ * <PortholeProvider> // per page: live-frame cap, heights, the dialog, the copy toast, the context notice
6
6
  * <PortholeFrame config={widgetConfig} displayId={id} title={title} scheme={scheme}
7
7
  * content={code} partial={streaming} handlers={{ sendPrompt, openLink }}
8
8
  * theme={tokensFor} onError={report} />
@@ -10,6 +10,7 @@
10
10
  */
11
11
  export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, } from "./frame.js";
12
12
  export { ARM_DELAY_MS, ConfirmDialog } from "./dialog.js";
13
+ export { ContextNotice, contextSize, contextText, } from "./context-notice.js";
13
14
  export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, } from "./view.js";
14
15
  export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, } from "./toast.js";
15
16
  export { admitFrame, createLiveFrames } from "./live.js";
@@ -163,9 +163,17 @@ export declare function familyOf(serves: CapabilityName): {
163
163
  * (`artifact`, `assets`, `db`), else its one method.
164
164
  */
165
165
  export declare function methodOf(serves: CapabilityName, args: unknown): string | null;
166
+ /**
167
+ * The runtime methods a validated call runs, each as often as it runs it: its own, and for a db
168
+ * batch each of its writes' (`set`, `update`, `delete`), for a db watch the read it repeats (`get`
169
+ * for a document, `query` for a collection). Each one's level and gates apply to the call (P091
170
+ * item 4 for levels, P094 for gates): a batch is its writes, a watch its read.
171
+ */
172
+ export declare function methodsOfCall(serves: CapabilityName, args: unknown): readonly string[];
166
173
  /**
167
174
  * Whether a config's asset uploads are its admins' alone (`assets.upload` at admin or above,
168
- * P089): only then may scripts and styles an admin uploaded run from the library.
175
+ * P089): only then may scripts and styles an admin uploaded run from the library. Never where
176
+ * the config serves no assets (P103: a config that dropped them runs nothing of its library).
169
177
  */
170
178
  export declare function assetCodeRuns(config: PortholeConfig): boolean;
171
179
  /**
@@ -140,11 +140,38 @@ export function methodOf(serves, args) {
140
140
  const op = args !== null && typeof args === "object" ? args.op : undefined;
141
141
  return typeof op === "string" && family.methods.includes(op) ? op : null;
142
142
  }
143
+ /**
144
+ * The runtime methods a validated call runs, each as often as it runs it: its own, and for a db
145
+ * batch each of its writes' (`set`, `update`, `delete`), for a db watch the read it repeats (`get`
146
+ * for a document, `query` for a collection). Each one's level and gates apply to the call (P091
147
+ * item 4 for levels, P094 for gates): a batch is its writes, a watch its read.
148
+ */
149
+ export function methodsOfCall(serves, args) {
150
+ const own = methodOf(serves, args);
151
+ if (own === null) {
152
+ return [];
153
+ }
154
+ if (serves !== "db") {
155
+ return [own];
156
+ }
157
+ const request = args;
158
+ if (request.op === "batch") {
159
+ return [own, ...(request.writes ?? []).map((write) => write.op)];
160
+ }
161
+ if (request.op === "watch") {
162
+ return [own, (request.path ?? "").split("/").length % 2 === 0 ? "get" : "query"];
163
+ }
164
+ return [own];
165
+ }
143
166
  /**
144
167
  * Whether a config's asset uploads are its admins' alone (`assets.upload` at admin or above,
145
- * P089): only then may scripts and styles an admin uploaded run from the library.
168
+ * P089): only then may scripts and styles an admin uploaded run from the library. Never where
169
+ * the config serves no assets (P103: a config that dropped them runs nothing of its library).
146
170
  */
147
171
  export function assetCodeRuns(config) {
172
+ if (config.capabilities.assets === undefined) {
173
+ return false;
174
+ }
148
175
  const level = methodLevel(config, "assets", "upload");
149
176
  return level !== null && atLeast(level, "admin");
150
177
  }
@@ -179,7 +206,9 @@ export function methodLevel(config, family, name, declared) {
179
206
  }
180
207
  const host = config.capabilities[spec.serves]?.levels?.[name];
181
208
  const base = host === undefined ? spec.level : higher(host, spec.floor);
182
- const page = declared?.levels?.[name];
209
+ // The page's own names only (P093): a declaration a host passes unchecked may be a plain object.
210
+ const levels = declared?.levels;
211
+ const page = levels !== undefined && Object.hasOwn(levels, name) ? levels[name] : undefined;
183
212
  return page === undefined ? base : higher(base, page);
184
213
  }
185
214
  /**
@@ -50,8 +50,12 @@ export type DbData = {
50
50
  };
51
51
  /** Whether `value` is plain JSON within `nodes` nodes (a document's, a `where` operand's). */
52
52
  export declare function isPlainJson(value: unknown, nodes?: number): boolean;
53
- /** The bytes `value` takes as JSON. */
54
- export declare const jsonBytes: (value: unknown) => number;
53
+ /**
54
+ * The bytes checked plain JSON takes (`plainJson` first: no cycles, bounded nodes and depth), or
55
+ * `max + 1` once it surely takes more: written out only within its limit (P095: a string of
56
+ * control characters is six times its length as JSON, and could pass a string's longest).
57
+ */
58
+ export declare const jsonBytes: (value: unknown, max: number) => number;
55
59
  export type DbWhereOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "array-contains";
56
60
  export type DbWhere = readonly [field: string, op: DbWhereOp, value: DbValue];
57
61
  export type DbWrite = {
@@ -127,12 +131,43 @@ export declare function parseDbRequest(args: unknown): Parsed<DbRequest>;
127
131
  * the least level that may read and write it. They only raise the contract's (read: view, write:
128
132
  * interact); the host evaluates them again on its side (`dbAccess`).
129
133
  */
130
- export type DbRules = Readonly<Record<string, {
134
+ export type DbRules = Readonly<Record<string, DbRule>>;
135
+ /** One collection's rule: the least level that may read it, and write it (absent: the contract's). */
136
+ export interface DbRule {
131
137
  readonly read?: ViewerLevel;
132
138
  readonly write?: ViewerLevel;
133
- }>>;
134
- /** A rules object's problem, or null. */
135
- export declare function dbRulesProblem(value: unknown): string | null;
139
+ }
140
+ /**
141
+ * The most collections a page's rules name (P086). At publish, `DB_MAX_RULES`; where a
142
+ * declaration is shown (a mount, `intersectDeclarations`), an intersection of two: twice that, and
143
+ * `*` (P093, after its review).
144
+ */
145
+ export declare const DB_MAX_RULES = 100;
146
+ export declare const DB_MAX_SHOWN_RULES: number;
147
+ /** Where a declaration is checked: at publish, or where it is shown (a mount, an intersection). */
148
+ export type DeclarationStage = "publish" | "shown";
149
+ /** A collection's name, ASCII case folded: a store that folds case keeps `Votes` where `votes` is. */
150
+ export declare const foldCollection: (name: string) => string;
151
+ /** The level a rule asks to read or write (absent: the contract's, read view and write interact). */
152
+ export declare function dbRuleLevel(rule: DbRule | undefined, write: boolean): ViewerLevel;
153
+ /** The stricter of two rules, read and write each (absent: the contract's level). */
154
+ export declare function stricterDbRule(x: DbRule | undefined, y: DbRule | undefined): DbRule;
155
+ /**
156
+ * The rule a top-level collection is under (P086, P093): the rule object the rules give its exact
157
+ * name, else `*`'s, whole; never field by field (a collection's `{}` is the contract's levels,
158
+ * whatever `*` says). Then made stricter by every rule that names it in another ASCII case (a
159
+ * store that folds case keeps `Votes` where `votes` is): never looser than the exact name's
160
+ * lookup, and the same where nothing names it in another case. Own names only: a collection
161
+ * named `constructor` or `__proto__` is no rule unless the rules name it (P091). `dbAccess` and
162
+ * `intersectDeclarations` both read rules through this.
163
+ */
164
+ export declare function dbRuleOf(rules: DbRules | undefined, collection: string): DbRule | undefined;
165
+ /**
166
+ * A rules object's problem, or null. At publish (the default) at most `DB_MAX_RULES` names, none
167
+ * two that differ only in case (P093); where shown, an intersection's `DB_MAX_SHOWN_RULES`, and
168
+ * names in more than one case as a page from before P093 may have them.
169
+ */
170
+ export declare function dbRulesProblem(value: unknown, stage?: DeclarationStage): string | null;
136
171
  /**
137
172
  * Whether `viewer` may make `request` under `rules` (P088), and the call with `me` resolved:
138
173
  * someone else's per-user data is refused at every level, and so is any path under `data` that
@@ -106,8 +106,46 @@ export function isPlainJson(value, nodes = DB_LIMITS.maxNodes) {
106
106
  return plainJson(value, { nodes, seen: new WeakSet() }, 0);
107
107
  }
108
108
  const encoder = new TextEncoder();
109
- /** The bytes `value` takes as JSON. */
110
- export const jsonBytes = (value) => encoder.encode(JSON.stringify(value)).length;
109
+ /**
110
+ * The fewest bytes checked plain JSON takes written out: each string's and key's characters (a
111
+ * character is a byte or more in UTF-8, an escape more), a byte a scalar. Stops past `max`.
112
+ */
113
+ function leastJsonBytes(value, max) {
114
+ if (typeof value === "string") {
115
+ return value.length + 2;
116
+ }
117
+ if (value === null || typeof value !== "object") {
118
+ return 1;
119
+ }
120
+ // The brackets, and a separator before each value but the first.
121
+ let total = 2;
122
+ let first = true;
123
+ if (Array.isArray(value)) {
124
+ for (const each of value) {
125
+ total += (first ? 0 : 1) + leastJsonBytes(each, max - total);
126
+ first = false;
127
+ if (total > max) {
128
+ return total;
129
+ }
130
+ }
131
+ return total;
132
+ }
133
+ for (const [field, each] of Object.entries(value)) {
134
+ // `"field":` and the value.
135
+ total += (first ? 0 : 1) + field.length + 3 + leastJsonBytes(each, max - total);
136
+ first = false;
137
+ if (total > max) {
138
+ return total;
139
+ }
140
+ }
141
+ return total;
142
+ }
143
+ /**
144
+ * The bytes checked plain JSON takes (`plainJson` first: no cycles, bounded nodes and depth), or
145
+ * `max + 1` once it surely takes more: written out only within its limit (P095: a string of
146
+ * control characters is six times its length as JSON, and could pass a string's longest).
147
+ */
148
+ export const jsonBytes = (value, max) => leastJsonBytes(value, max) > max ? max + 1 : encoder.encode(JSON.stringify(value)).length;
111
149
  /** A document's data: a plain object, within the limits; "too_large" past them. */
112
150
  function dbData(value, budget = {
113
151
  nodes: DB_LIMITS.maxNodes,
@@ -119,7 +157,9 @@ function dbData(value, budget = {
119
157
  if (!plainJson(value, budget, 0)) {
120
158
  return null;
121
159
  }
122
- return jsonBytes(value) > DB_LIMITS.maxDocBytes ? "too_large" : value;
160
+ return jsonBytes(value, DB_LIMITS.maxDocBytes) > DB_LIMITS.maxDocBytes
161
+ ? "too_large"
162
+ : value;
123
163
  }
124
164
  const version = (value) => value === undefined
125
165
  ? undefined
@@ -170,7 +210,7 @@ function parseWhere(value) {
170
210
  field.length > 256 ||
171
211
  !WHERE_OPS.includes(op) ||
172
212
  !isPlainJson(operand, DB_LIMITS.maxOperandNodes) ||
173
- jsonBytes(operand) > DB_LIMITS.maxOperandBytes ||
213
+ jsonBytes(operand, DB_LIMITS.maxOperandBytes) > DB_LIMITS.maxOperandBytes ||
174
214
  (op === "in" && (!Array.isArray(operand) || operand.length > DB_LIMITS.maxIn))) {
175
215
  return null;
176
216
  }
@@ -256,7 +296,7 @@ export function parseDbRequest(args) {
256
296
  paths.add(write.path);
257
297
  parsed.push(write);
258
298
  }
259
- if (jsonBytes(parsed) > DB_LIMITS.maxBatchBytes) {
299
+ if (jsonBytes(parsed, DB_LIMITS.maxBatchBytes) > DB_LIMITS.maxBatchBytes) {
260
300
  return "too_large";
261
301
  }
262
302
  return { op: "batch", writes: parsed };
@@ -265,19 +305,89 @@ export function parseDbRequest(args) {
265
305
  return null;
266
306
  }
267
307
  }
268
- /** A rules object's problem, or null. */
269
- export function dbRulesProblem(value) {
308
+ /**
309
+ * The most collections a page's rules name (P086). At publish, `DB_MAX_RULES`; where a
310
+ * declaration is shown (a mount, `intersectDeclarations`), an intersection of two: twice that, and
311
+ * `*` (P093, after its review).
312
+ */
313
+ export const DB_MAX_RULES = 100;
314
+ export const DB_MAX_SHOWN_RULES = 2 * DB_MAX_RULES + 1;
315
+ /** A collection's name, ASCII case folded: a store that folds case keeps `Votes` where `votes` is. */
316
+ export const foldCollection = (name) => name.replace(/[A-Z]+/gu, (run) => run.toLowerCase());
317
+ /** The level a rule asks to read or write (absent: the contract's, read view and write interact). */
318
+ export function dbRuleLevel(rule, write) {
319
+ const base = write ? "interact" : "view";
320
+ const asked = write ? rule?.write : rule?.read;
321
+ return asked === undefined ? base : higher(base, asked);
322
+ }
323
+ /** The stricter of two rules, read and write each (absent: the contract's level). */
324
+ export function stricterDbRule(x, y) {
325
+ const out = Object.create(null);
326
+ for (const field of ["read", "write"]) {
327
+ const p = x?.[field];
328
+ const q = y?.[field];
329
+ const level = p === undefined ? q : q === undefined ? p : higher(p, q);
330
+ if (level !== undefined) {
331
+ out[field] = level;
332
+ }
333
+ }
334
+ return out;
335
+ }
336
+ /**
337
+ * The rule a top-level collection is under (P086, P093): the rule object the rules give its exact
338
+ * name, else `*`'s, whole; never field by field (a collection's `{}` is the contract's levels,
339
+ * whatever `*` says). Then made stricter by every rule that names it in another ASCII case (a
340
+ * store that folds case keeps `Votes` where `votes` is): never looser than the exact name's
341
+ * lookup, and the same where nothing names it in another case. Own names only: a collection
342
+ * named `constructor` or `__proto__` is no rule unless the rules name it (P091). `dbAccess` and
343
+ * `intersectDeclarations` both read rules through this.
344
+ */
345
+ export function dbRuleOf(rules, collection) {
346
+ if (rules === undefined) {
347
+ return undefined;
348
+ }
349
+ const own = (key) => (Object.hasOwn(rules, key) ? rules[key] : undefined);
350
+ // After the re-review: `*` counts whenever the exact name is absent, variants or not.
351
+ let rule = own(collection) ?? own("*");
352
+ if (collection === "*") {
353
+ return rule;
354
+ }
355
+ const folded = foldCollection(collection);
356
+ for (const name of Object.keys(rules)) {
357
+ const each = rules[name];
358
+ if (name !== "*" &&
359
+ name !== collection &&
360
+ typeof each === "object" &&
361
+ foldCollection(name) === folded) {
362
+ rule = stricterDbRule(rule, each);
363
+ }
364
+ }
365
+ return rule;
366
+ }
367
+ /**
368
+ * A rules object's problem, or null. At publish (the default) at most `DB_MAX_RULES` names, none
369
+ * two that differ only in case (P093); where shown, an intersection's `DB_MAX_SHOWN_RULES`, and
370
+ * names in more than one case as a page from before P093 may have them.
371
+ */
372
+ export function dbRulesProblem(value, stage = "publish") {
270
373
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
271
374
  return "must be an object of { read?, write } levels by collection";
272
375
  }
273
376
  const entries = Object.entries(value);
274
- if (entries.length > 100) {
275
- return "may name at most 100 collections";
377
+ const most = stage === "publish" ? DB_MAX_RULES : DB_MAX_SHOWN_RULES;
378
+ if (entries.length > most) {
379
+ return `may name at most ${most} collections`;
276
380
  }
381
+ const folded = new Map();
277
382
  for (const [collection, rule] of entries) {
278
383
  if (collection !== "*" && !SEGMENT.test(collection)) {
279
384
  return `${JSON.stringify(collection)} is not a collection name (or "*")`;
280
385
  }
386
+ const other = folded.get(foldCollection(collection));
387
+ if (stage === "publish" && other !== undefined) {
388
+ return `${JSON.stringify(other)} and ${JSON.stringify(collection)} differ only in case: name a collection once (a rule holds for its name in any case)`;
389
+ }
390
+ folded.set(foldCollection(collection), collection);
281
391
  if (rule === null || typeof rule !== "object" || Array.isArray(rule)) {
282
392
  return `${collection}: must be { read?, write? }`;
283
393
  }
@@ -328,13 +438,7 @@ function ownPath(path, viewer) {
328
438
  }
329
439
  /** The least level a rule asks for `path`. */
330
440
  function ruleLevel(rules, path, write) {
331
- const base = write ? "interact" : "view";
332
- const top = path.split("/")[0] ?? "";
333
- // Own rules only: a collection named `constructor` or `__proto__` is no rule (after the review).
334
- const own = (key) => rules !== undefined && Object.hasOwn(rules, key) ? rules[key] : undefined;
335
- const rule = own(top) ?? own("*");
336
- const asked = write ? rule?.write : rule?.read;
337
- return asked === undefined ? base : higher(base, asked);
441
+ return dbRuleLevel(dbRuleOf(rules, path.split("/")[0] ?? ""), write);
338
442
  }
339
443
  /**
340
444
  * Whether `viewer` may make `request` under `rules` (P088), and the call with `me` resolved:
@@ -81,6 +81,20 @@ export declare function declaredMatch(list: readonly string[] | undefined, name:
81
81
  * it (`declareCapabilities` at its publish) and mounts a version with this, so an old version
82
82
  * never keeps what the artifact has since revoked, nor gains what it declared later. Each
83
83
  * capability only where both declare it, at the stricter levels, the narrower `data` names and
84
- * the stricter `db` rules; the version's own pinned runtime.
84
+ * the stricter `db` rules (each side read as `dbAccess` reads it, P093); the version's own pinned
85
+ * runtime. Whatever the result allows, each side allows alone; a mount takes it (two pages at
86
+ * the publish limits make one within a mount's). Objects without a prototype.
87
+ *
88
+ * Answers its problems (P093, after its review) where either side isn't a declaration's shape
89
+ * (or the two make one past a mount's limits): show the version as an error, never with `null`
90
+ * (that is 0.6's surface) or with either side alone.
85
91
  */
92
+ export declare function tryIntersectDeclarations(version: PageDeclaration, current: PageDeclaration): {
93
+ readonly ok: true;
94
+ readonly declaration: PageDeclaration;
95
+ } | {
96
+ readonly ok: false;
97
+ readonly problems: readonly DeclarationProblem[];
98
+ };
99
+ /** `tryIntersectDeclarations`, a `TypeError` naming the problems where it answers some. */
86
100
  export declare function intersectDeclarations(version: PageDeclaration, current: PageDeclaration): PageDeclaration;