@niscorp/moss 0.6.0 → 0.8.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 (59) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/DESIGN.md +77 -40
  3. package/DOCS.md +673 -78
  4. package/README.md +2 -2
  5. package/dist/chunk-3DCTQKPQ.cjs +943 -0
  6. package/dist/chunk-3DCTQKPQ.cjs.map +1 -0
  7. package/dist/{chunk-WKBH3UMB.js → chunk-3T422CCN.js} +9 -3
  8. package/dist/chunk-3T422CCN.js.map +1 -0
  9. package/dist/chunk-6XC2MD7S.js +906 -0
  10. package/dist/chunk-6XC2MD7S.js.map +1 -0
  11. package/dist/{chunk-D3YZIAYV.cjs → chunk-I4UOWER3.cjs} +11 -5
  12. package/dist/chunk-I4UOWER3.cjs.map +1 -0
  13. package/dist/{chunk-VBWNHF4H.cjs → chunk-PVZMCEBX.cjs} +4 -3
  14. package/dist/chunk-PVZMCEBX.cjs.map +1 -0
  15. package/dist/{chunk-NSK7QSSG.js → chunk-QAHDSRPK.js} +4 -3
  16. package/dist/chunk-QAHDSRPK.js.map +1 -0
  17. package/dist/{chunk-R66WUKGC.cjs → chunk-TMDKNZYL.cjs} +2169 -1319
  18. package/dist/chunk-TMDKNZYL.cjs.map +1 -0
  19. package/dist/{chunk-V5YMJL7Z.js → chunk-YZILOVCR.js} +2147 -1295
  20. package/dist/chunk-YZILOVCR.js.map +1 -0
  21. package/dist/document-BYAY-Qle.d.ts +381 -0
  22. package/dist/document-DAE71J27.d.cts +381 -0
  23. package/dist/{index-B411sK9M.d.cts → index-CSEo7Tys.d.cts} +5 -0
  24. package/dist/{index-B411sK9M.d.ts → index-CSEo7Tys.d.ts} +5 -0
  25. package/dist/index.cjs +17 -17
  26. package/dist/index.d.cts +8 -10
  27. package/dist/index.d.ts +8 -10
  28. package/dist/index.js +3 -3
  29. package/dist/integrations.cjs +3 -3
  30. package/dist/integrations.d.cts +1 -1
  31. package/dist/integrations.d.ts +1 -1
  32. package/dist/integrations.js +1 -1
  33. package/dist/node.cjs +8 -8
  34. package/dist/node.d.cts +3 -4
  35. package/dist/node.d.ts +3 -4
  36. package/dist/node.js +4 -4
  37. package/dist/tide.d.cts +1 -1
  38. package/dist/tide.d.ts +1 -1
  39. package/dist/unverified.cjs +3 -3
  40. package/dist/unverified.js +2 -2
  41. package/dist/vite.cjs +9 -9
  42. package/dist/vite.d.cts +6 -1
  43. package/dist/vite.d.ts +6 -1
  44. package/dist/vite.js +4 -4
  45. package/package.json +13 -13
  46. package/dist/app-CUnDcXQu.d.ts +0 -143
  47. package/dist/app-CdANzi2q.d.cts +0 -143
  48. package/dist/chunk-D3YZIAYV.cjs.map +0 -1
  49. package/dist/chunk-NSK7QSSG.js.map +0 -1
  50. package/dist/chunk-PWUO4RET.js +0 -374
  51. package/dist/chunk-PWUO4RET.js.map +0 -1
  52. package/dist/chunk-R2YPQHQH.cjs +0 -383
  53. package/dist/chunk-R2YPQHQH.cjs.map +0 -1
  54. package/dist/chunk-R66WUKGC.cjs.map +0 -1
  55. package/dist/chunk-V5YMJL7Z.js.map +0 -1
  56. package/dist/chunk-VBWNHF4H.cjs.map +0 -1
  57. package/dist/chunk-WKBH3UMB.js.map +0 -1
  58. package/dist/document-D7nroBww.d.cts +0 -169
  59. package/dist/document-DeTPGBil.d.ts +0 -169
@@ -1,27 +1,26 @@
1
1
  'use strict';
2
2
 
3
- var chunkR2YPQHQH_cjs = require('./chunk-R2YPQHQH.cjs');
4
- var chunkVBWNHF4H_cjs = require('./chunk-VBWNHF4H.cjs');
3
+ var chunk3DCTQKPQ_cjs = require('./chunk-3DCTQKPQ.cjs');
4
+ var chunkPVZMCEBX_cjs = require('./chunk-PVZMCEBX.cjs');
5
5
  var chunk3RIWTXGI_cjs = require('./chunk-3RIWTXGI.cjs');
6
6
  var zod = require('zod');
7
7
  var crypto$1 = require('crypto');
8
- var charter = require('@niscorp/charter');
9
- var nova = require('@niscorp/nova');
10
- var reflect = require('@niscorp/nova/reflect');
11
- var strata = require('@niscorp/strata');
12
8
  var vex = require('@niscorp/vex');
13
- var i18n = require('@niscorp/nova/i18n');
14
- var prism = require('@niscorp/prism');
15
9
  var postgres = require('@niscorp/strata/postgres');
16
- var migrations = require('@niscorp/nova/migrations');
17
- var migrations$1 = require('@niscorp/prism/migrations');
10
+ var strata = require('@niscorp/strata');
11
+ var migrations$1 = require('@niscorp/nova/migrations');
12
+ var prism = require('@niscorp/prism');
13
+ var migrations$2 = require('@niscorp/prism/migrations');
14
+ var migrations = require('@niscorp/vex/migrations');
15
+ var charter = require('@niscorp/charter');
18
16
  var hono = require('hono');
19
17
  var hono$1 = require('@niscorp/vex/hono');
20
18
  var async_hooks = require('async_hooks');
21
19
  var document = require('@niscorp/nova/document');
20
+ var nova = require('@niscorp/nova');
21
+ var i18n = require('@niscorp/nova/i18n');
22
+ var reflect = require('@niscorp/nova/reflect');
22
23
 
23
- // src/manifest/app.ts
24
- var defineApp = (app) => app;
25
24
  var tokenFromCookie = (header, name = chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY) => {
26
25
  if (header === void 0 || header === null) return null;
27
26
  const wanted = encodeURIComponent(name);
@@ -37,10 +36,10 @@ var tokenFromCookie = (header, name = chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY) => {
37
36
  }
38
37
  return null;
39
38
  };
40
- var ownOriginOf = (origin, host, listed = []) => {
39
+ var ownOriginOf = (origin, host, listed2 = []) => {
41
40
  if (origin === void 0 || origin === null || !URL.canParse(origin)) return void 0;
42
41
  const asked = new URL(origin);
43
- const own = asked.host === host?.toLowerCase() || listed.some((entry2) => URL.canParse(entry2) && new URL(entry2).origin === asked.origin);
42
+ const own = asked.host === host?.toLowerCase() || listed2.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
44
43
  return own ? asked : void 0;
45
44
  };
46
45
  var cookiesAt = (where, key, token, lastsMs) => {
@@ -169,8 +168,8 @@ var createHeldRecords = (max) => {
169
168
  const held = /* @__PURE__ */ new Map();
170
169
  const tagged = /* @__PURE__ */ new Map();
171
170
  let evicted = 0;
172
- const untag = (principal, record2) => {
173
- const tag = record2.tag;
171
+ const untag = (principal, record) => {
172
+ const tag = record.tag;
174
173
  if (tag === void 0) return;
175
174
  const group = tagged.get(tag);
176
175
  if (group === void 0) return;
@@ -178,9 +177,9 @@ var createHeldRecords = (max) => {
178
177
  if (group.size === 0) tagged.delete(tag);
179
178
  };
180
179
  const forget = (principal) => {
181
- const entry2 = held.get(principal);
182
- if (entry2 === void 0) return false;
183
- untag(principal, entry2.record);
180
+ const entry = held.get(principal);
181
+ if (entry === void 0) return false;
182
+ untag(principal, entry.record);
184
183
  held.delete(principal);
185
184
  return true;
186
185
  };
@@ -190,22 +189,22 @@ var createHeldRecords = (max) => {
190
189
  forget(oldest.value);
191
190
  evicted += 1;
192
191
  };
193
- const remember = (principal, record2, at) => {
192
+ const remember = (principal, record, at) => {
194
193
  forget(principal);
195
194
  while (held.size >= max) evictOldest();
196
- held.set(principal, { record: record2, since: at, lastSeen: at });
197
- if (record2.tag !== void 0) {
198
- const group = tagged.get(record2.tag) ?? /* @__PURE__ */ new Set();
195
+ held.set(principal, { record, since: at, lastSeen: at });
196
+ if (record.tag !== void 0) {
197
+ const group = tagged.get(record.tag) ?? /* @__PURE__ */ new Set();
199
198
  group.add(principal);
200
- tagged.set(record2.tag, group);
199
+ tagged.set(record.tag, group);
201
200
  }
202
201
  };
203
202
  return {
204
203
  of: (principal) => held.get(principal),
205
- touch: (principal, entry2, at) => {
204
+ touch: (principal, entry, at) => {
206
205
  held.delete(principal);
207
- entry2.lastSeen = at;
208
- held.set(principal, entry2);
206
+ entry.lastSeen = at;
207
+ held.set(principal, entry);
209
208
  },
210
209
  forget,
211
210
  remember,
@@ -219,14 +218,14 @@ var createHeldRecords = (max) => {
219
218
  return principals;
220
219
  },
221
220
  forgetIdle: (at, idleMs) => {
222
- for (const [principal, entry2] of [...held]) {
223
- if (at - entry2.lastSeen >= idleMs) {
221
+ for (const [principal, entry] of [...held]) {
222
+ if (at - entry.lastSeen >= idleMs) {
224
223
  forget(principal);
225
224
  evicted += 1;
226
225
  }
227
226
  }
228
227
  },
229
- list: () => [...held].map(([principal, entry2]) => ({ principal, since: entry2.since, lastSeen: entry2.lastSeen })),
228
+ list: () => [...held].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),
230
229
  size: () => held.size,
231
230
  evicted: () => evicted
232
231
  };
@@ -258,11 +257,11 @@ var createIdentityCache = (ctx) => {
258
257
  if (inFlight !== void 0) return inFlight.work;
259
258
  const forgotten = /* @__PURE__ */ new Set();
260
259
  const isStillOut = () => pending.get(principal)?.work === work;
261
- const work = ctx.resolve(principal).then((record2) => {
260
+ const work = ctx.resolve(principal).then((record) => {
262
261
  resolved += 1;
263
- const wearsForgottenTag = record2.tag !== void 0 && forgotten.has(record2.tag);
264
- if (isStillOut() && !wearsForgottenTag) held.remember(principal, record2, now());
265
- return record2;
262
+ const wearsForgottenTag = record.tag !== void 0 && forgotten.has(record.tag);
263
+ if (isStillOut() && !wearsForgottenTag) held.remember(principal, record, now());
264
+ return record;
266
265
  }).finally(() => {
267
266
  if (isStillOut()) pending.delete(principal);
268
267
  });
@@ -295,6 +294,7 @@ var createIdentityCache = (ctx) => {
295
294
  };
296
295
  };
297
296
  var memoKey = (roles, installed) => `${[...roles].sort().join("\0")}\0\0${installed === void 0 ? "*" : [...installed].sort().join("\0")}`;
297
+ var NOBODY_USER_ID = "anonymous";
298
298
  var assignedRoles = (assignments, principal) => principal === null ? ["public"] : assignments?.[principal] ?? ["public"];
299
299
  var IdentityRecordSchema = zod.z.looseObject({
300
300
  roles: zod.z.array(zod.z.string()),
@@ -305,25 +305,25 @@ var IdentityRecordSchema = zod.z.looseObject({
305
305
  var recordRefusal = (issues) => new Error(
306
306
  `moss: \`identity.resolve\` did not answer an identity record (${issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")}). A record is { roles: string[], scope: {\u2026}, installed?: string[], tag?: string }.`
307
307
  );
308
- var resolveThrough = (seam2, readAs) => async (principal) => {
309
- const role = seam2.as;
308
+ var resolveThrough = (seam, readAs) => async (principal) => {
309
+ const role = seam.as;
310
310
  const read2 = async (fingerprint, scope) => {
311
311
  if (role === void 0) throw new Error("moss: identity.read needs identity.as \u2014 name the charter role the reader executes as");
312
312
  return readAs(role, fingerprint, scope);
313
313
  };
314
- const answered = IdentityRecordSchema.safeParse(await seam2.resolve(principal, read2));
314
+ const answered = IdentityRecordSchema.safeParse(await seam.resolve(principal, read2));
315
315
  if (!answered.success) throw recordRefusal(answered.error.issues);
316
316
  return answered.data;
317
317
  };
318
318
  var createIdentity = (config) => {
319
- const seam2 = config.seam;
320
- const cache = seam2 === void 0 ? void 0 : createIdentityCache({ resolve: resolveThrough(seam2, config.readAs), max: config.max, idleMs: config.idleMs, revalidateMs: config.revalidateMs });
319
+ const seam = config.seam;
320
+ const cache = seam === void 0 ? void 0 : createIdentityCache({ resolve: resolveThrough(seam, config.readAs), max: config.max, idleMs: config.idleMs, revalidateMs: config.revalidateMs });
321
321
  const keys = /* @__PURE__ */ new WeakMap();
322
- const keyOf2 = (record2) => {
323
- const hit = keys.get(record2);
322
+ const keyOf2 = (record) => {
323
+ const hit = keys.get(record);
324
324
  if (hit !== void 0) return hit;
325
- const key = memoKey(record2.roles, record2.installed);
326
- keys.set(record2, key);
325
+ const key = memoKey(record.roles, record.installed);
326
+ keys.set(record, key);
327
327
  return key;
328
328
  };
329
329
  const fromAssignments = (principal) => {
@@ -332,13 +332,13 @@ var createIdentity = (config) => {
332
332
  };
333
333
  const resolve2 = async (principal) => {
334
334
  if (cache !== void 0 && principal !== null) {
335
- const record2 = await cache.get(principal);
336
- return { roles: record2.roles, scope: record2.scope, installed: record2.installed, memoKey: keyOf2(record2), record: record2 };
335
+ const record = await cache.get(principal);
336
+ return { roles: record.roles, scope: record.scope, installed: record.installed, memoKey: keyOf2(record), record };
337
337
  }
338
338
  return fromAssignments(principal);
339
339
  };
340
340
  const composeScope = (principal, resolved) => ({
341
- userId: principal ?? "anonymous",
341
+ userId: principal ?? NOBODY_USER_ID,
342
342
  ...resolved.scope,
343
343
  ...config.scope?.(principal, resolved.record) ?? {}
344
344
  });
@@ -353,1323 +353,2060 @@ var createIdentity = (config) => {
353
353
  stop: () => cache?.stop()
354
354
  };
355
355
  };
356
- var entriesOf = (app) => app.entries ?? [];
357
- var shellComponents = (manifest, shell2) => {
358
- const names = /* @__PURE__ */ new Set([nova.CANVAS_SLOT_NAME, nova.ACTION_SLOT_NAME]);
359
- for (const source of [manifest.actions, manifest.layouts ?? {}, shell2.canvases, shell2.layout ?? {}, shell2.layoutStore ?? {}, shell2.fragments ?? {}]) {
360
- for (const name of reflect.componentsOf(source)) names.add(name);
356
+
357
+ // src/data/tables.ts
358
+ var GENERATION_DDL = [
359
+ /* sql */
360
+ `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
361
+ /* sql */
362
+ `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
363
+ ];
364
+ var MOSS_SEQUENCE = {
365
+ id: "nisc.moss",
366
+ migrations: [
367
+ {
368
+ description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
369
+ steps: [
370
+ { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
371
+ id text PRIMARY KEY,
372
+ url text NOT NULL,
373
+ -- THE HASH, NEVER THE KEY. The integration key is minted at registration
374
+ -- (see assert.ts for the credential rule), returned once in that response,
375
+ -- and this is all that remains of it here. Presenting the key is the only
376
+ -- way to produce this value again, so a stolen database does not hold a
377
+ -- credential \u2014 and a lost key is re-registered, not recovered.
378
+ key_hash text,
379
+ status text NOT NULL DEFAULT 'pending',
380
+ -- The store card's words, straight from the bundle's meta. Columns
381
+ -- rather than jsonb so an app's vex read can select them like anything
382
+ -- else on this table.
383
+ title text NOT NULL DEFAULT '',
384
+ tagline text NOT NULL DEFAULT '',
385
+ description text NOT NULL DEFAULT '',
386
+ -- The listing page's long form, re-imported whole like everything else
387
+ -- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
388
+ -- intake (copyPress), never the paths the bundle declared \u2014 the listing
389
+ -- composes from host ground alone.
390
+ story jsonb NOT NULL DEFAULT '[]'::jsonb,
391
+ highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
392
+ press jsonb NOT NULL DEFAULT '[]'::jsonb,
393
+ -- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
394
+ -- printed by the approval card and the store tile from this one place.
395
+ adds text NOT NULL DEFAULT '',
396
+ -- The one integration action the store may open: its settings screen.
397
+ settings_action text NOT NULL DEFAULT '',
398
+ requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
399
+ requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
400
+ approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
401
+ -- What it tells and hears (bundle offers/needs), beside the grants
402
+ -- because they are the same kind of thing: the integration's declared
403
+ -- statement, written at import, replaced on re-registration. moss
404
+ -- never reads them; the host's bus does.
405
+ offers jsonb NOT NULL DEFAULT '[]'::jsonb,
406
+ needs jsonb NOT NULL DEFAULT '[]'::jsonb,
407
+ -- The verbs the integration gates on ({id, title}), for the host's role
408
+ -- editor to grant. Beside offers/needs because it is the same kind of
409
+ -- thing: a declaration written at import, replaced on re-registration,
410
+ -- that moss never reads \u2014 the host does.
411
+ capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
412
+ -- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
413
+ -- beside capabilities because it is the same kind of thing: a declaration
414
+ -- written at import, replaced on re-registration, that moss never reads.
415
+ -- The host renders a settings form from it and stores the values itself.
416
+ configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
417
+ -- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
418
+ -- and a section model the host's editor renders. Beside configuration
419
+ -- because it is the same kind of thing: a declaration written at import,
420
+ -- replaced on re-registration, that moss never reads \u2014 the host does.
421
+ documents jsonb NOT NULL DEFAULT '[]'::jsonb,
422
+ -- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
423
+ -- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
424
+ -- the host's assistant is the consumer.
425
+ assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
426
+ -- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
427
+ -- (reachOf). Beside the grants because it is one: a grant of reach, held
428
+ -- by the same row, revoked by the same delete.
429
+ reach jsonb NOT NULL DEFAULT '[]'::jsonb,
430
+ -- Pages this integration serves and the host frames. Kept apart from reach
431
+ -- because they are spent differently: reach is a screen's call carrying a
432
+ -- session, a frame is a document GET carrying a grant.
433
+ frames jsonb NOT NULL DEFAULT '[]'::jsonb,
434
+ last_import_at timestamptz,
435
+ last_error text
436
+ )
437
+ ` },
438
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
439
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
440
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
441
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
442
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
443
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
444
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
445
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
446
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
447
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
448
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
449
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
450
+ { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
451
+ integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
452
+ action_id text NOT NULL,
453
+ definition jsonb NOT NULL,
454
+ -- The bindings, beside the artifact and never inside it: which host
455
+ -- action this one rides (a panel), or which menu hub lists it. Empty
456
+ -- means neither \u2014 reachable only through whatever else names it.
457
+ -- preview is the rider's display endpoint (own-prefix, validated at
458
+ -- intake): the host calls it with the offered ids to paint the strip.
459
+ attach_to text NOT NULL DEFAULT '',
460
+ preview text NOT NULL DEFAULT '',
461
+ place_in text NOT NULL DEFAULT '',
462
+ PRIMARY KEY (integration_id, action_id)
463
+ )
464
+ ` },
465
+ ...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
466
+ ]
467
+ },
468
+ {
469
+ description: "Stored integration actions carry the grammar stamp their definition is written in",
470
+ steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
471
+ },
472
+ {
473
+ description: "No two integrations hold the hash of one key",
474
+ steps: [{ kind: "sql", sql: `CREATE UNIQUE INDEX integrations_key_hash_unique ON integrations (key_hash) WHERE key_hash IS NOT NULL` }]
475
+ },
476
+ {
477
+ description: "An integration keeps what its bundle says in the host app\u2019s own vocabulary as one value, and the columns of one product\u2019s vocabulary go",
478
+ steps: [
479
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN extension jsonb` },
480
+ {
481
+ kind: "sql",
482
+ sql: `ALTER TABLE integrations
483
+ DROP COLUMN IF EXISTS title,
484
+ DROP COLUMN IF EXISTS tagline,
485
+ DROP COLUMN IF EXISTS description,
486
+ DROP COLUMN IF EXISTS story,
487
+ DROP COLUMN IF EXISTS highlights,
488
+ DROP COLUMN IF EXISTS press,
489
+ DROP COLUMN IF EXISTS adds,
490
+ DROP COLUMN IF EXISTS settings_action,
491
+ DROP COLUMN IF EXISTS offers,
492
+ DROP COLUMN IF EXISTS needs,
493
+ DROP COLUMN IF EXISTS capabilities,
494
+ DROP COLUMN IF EXISTS configuration,
495
+ DROP COLUMN IF EXISTS documents,
496
+ DROP COLUMN IF EXISTS assistants,
497
+ DROP COLUMN IF EXISTS frames`
498
+ },
499
+ {
500
+ kind: "sql",
501
+ sql: `ALTER TABLE integration_actions
502
+ DROP COLUMN IF EXISTS attach_to,
503
+ DROP COLUMN IF EXISTS preview,
504
+ DROP COLUMN IF EXISTS place_in`
505
+ }
506
+ ]
507
+ },
508
+ {
509
+ description: "The artifactory\u2019s two tables: a row for each save, and a row for each version of an artifact a save holds",
510
+ steps: [
511
+ {
512
+ kind: "sql",
513
+ sql: `CREATE TABLE artifact_saves (
514
+ id uuid PRIMARY KEY,
515
+ created_by text NOT NULL,
516
+ -- Whose the save is: the userId of whoever made it, written by vex.
517
+ principal text NOT NULL,
518
+ created_at timestamptz NOT NULL DEFAULT now()
519
+ )`
520
+ },
521
+ {
522
+ kind: "sql",
523
+ sql: `CREATE TABLE artifacts (
524
+ save uuid NOT NULL REFERENCES artifact_saves(id),
525
+ kind text NOT NULL,
526
+ id text NOT NULL,
527
+ -- Whose the version is, as its save's.
528
+ principal text NOT NULL,
529
+ -- null, as SQL or as JSON: this version says none is in force.
530
+ body jsonb,
531
+ grammar jsonb NOT NULL DEFAULT '{}'::jsonb,
532
+ -- The save whose version of this artifact this one is a copy of.
533
+ copied_from uuid,
534
+ created_at timestamptz NOT NULL DEFAULT now(),
535
+ PRIMARY KEY (save, kind, id)
536
+ )`
537
+ },
538
+ // What is in force for an artifact is its latest row, and that is asked at every shell.
539
+ { kind: "sql", sql: `CREATE INDEX artifacts_latest ON artifacts (principal, kind, id, created_at)` }
540
+ ]
541
+ },
542
+ {
543
+ description: "When a version of an artifact was last loaded into a shell, for the sweep over what is unused",
544
+ steps: [{ kind: "sql", sql: `ALTER TABLE artifacts ADD COLUMN last_used_at timestamptz` }]
545
+ }
546
+ ]
547
+ };
548
+ var ARTIFACT_TABLES = ["artifacts", "artifact_saves"];
549
+ var tableSequencesOf = (owners) => {
550
+ const cacheSequence = (owners.cache ?? vex.createPostgresCache({ pool: owners.pool })).sequence;
551
+ return [
552
+ MOSS_SEQUENCE,
553
+ ...owners.storesSessions ? [SESSIONS_SEQUENCE] : [],
554
+ ...cacheSequence === void 0 ? [] : [cacheSequence],
555
+ ...(owners.featureTables ?? []).flatMap((kept) => kept.sequences),
556
+ ...owners.tables ?? []
557
+ ];
558
+ };
559
+ var misfitOf = (entry, schema) => {
560
+ if (!("mutation" in entry)) {
561
+ try {
562
+ vex.resolve(vex.pruneOptional(entry.dsl, "all"), schema);
563
+ return void 0;
564
+ } catch (error) {
565
+ return error instanceof Error ? error.message : String(error);
566
+ }
361
567
  }
362
- const contracts = shell2.components ?? {};
363
- for (const name of Object.keys(contracts)) names.add(name);
364
- return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
568
+ return vex.mutationMisfits(entry.mutation, schema)[0];
365
569
  };
366
- var wearableOf = (app) => {
367
- const declared = app.wearable;
368
- const source = declared ?? Object.values(app.assignments ?? {});
369
- const seen = /* @__PURE__ */ new Map();
370
- for (const roles of source) {
371
- const key = [...roles].sort().join("\0");
372
- if (!seen.has(key)) seen.set(key, roles);
570
+ var misfitsOf = (entries, schema) => {
571
+ const misfits = /* @__PURE__ */ new Map();
572
+ for (const entry of entries) {
573
+ const why = misfitOf(entry, schema);
574
+ if (why !== void 0) misfits.set(entry.fingerprint, why);
373
575
  }
374
- return [...seen.values()];
576
+ return misfits;
375
577
  };
376
- var narrowedBy = (filter, ids, installed) => {
377
- const answered = new Set(filter(ids, installed));
378
- return ids.filter((id) => answered.has(id));
578
+ var canonical = (value) => {
579
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
580
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
581
+ const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
582
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
379
583
  };
380
- var catalogFor = (app, roles, installed, installedOnly) => {
381
- const granted = [...charter.resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
382
- const ids = [...installedOnly(granted, installed === void 0 ? void 0 : new Set(installed))];
383
- return { ids, hash: versionToken(ids) };
584
+ var isSeededAs = async (cache, entry) => {
585
+ const held = await cache.get(entry.fingerprint);
586
+ if (held === void 0 || held.protected !== true) return false;
587
+ if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
588
+ return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
384
589
  };
385
- var variantLayouts = (variants, held) => {
386
- const layouts = /* @__PURE__ */ new Map();
387
- for (const id of held) {
388
- const variant = variants[id];
389
- if (variant !== void 0) layouts.set(variant.action, variant.layout);
590
+ var changesBetween = (before, after) => {
591
+ const removed = [];
592
+ const retyped = [];
593
+ for (const was of before.entities) {
594
+ const now = after.entities.find((entity) => entity.table === was.table);
595
+ if (now === void 0) {
596
+ removed.push(was.table);
597
+ continue;
598
+ }
599
+ for (const field of was.fields) {
600
+ const kept = now.fields.find((f) => f.name === field.name);
601
+ if (kept === void 0) removed.push(`${was.table}.${field.name}`);
602
+ else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
603
+ }
390
604
  }
391
- return layouts;
392
- };
393
- var resolveVariantsForRoles = (app, roles) => {
394
- const variants = app.layouts ?? {};
395
- return variantLayouts(variants, charter.resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
605
+ return { removed, retyped };
396
606
  };
397
- var withVariants = (actions, ids, layouts) => ids.flatMap((id) => {
398
- const definition = actions[id];
399
- if (definition === void 0) return [];
400
- const layout2 = layouts.get(id);
401
- return [[id, layout2 === void 0 ? definition : { ...definition, layout: layout2 }]];
402
- });
403
- var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(withVariants(actions, ids, variants)));
404
- var createRoleMemo = (config) => {
405
- const catalogs = /* @__PURE__ */ new Map();
406
- const variants = /* @__PURE__ */ new Map();
407
- const definitions = /* @__PURE__ */ new Map();
408
- const kept = (memo, key, resolve2) => {
409
- const hit = memo.get(key);
410
- if (hit !== void 0) return hit;
411
- const resolved = resolve2();
412
- memo.set(key, resolved);
413
- return resolved;
414
- };
415
- const roleMemo = {
416
- catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
417
- variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
418
- definitionsFor: (roles, installed) => kept(definitions, memoKey(roles, installed), () => definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles))),
419
- drop: () => {
420
- catalogs.clear();
421
- variants.clear();
422
- definitions.clear();
423
- }
607
+ var oneAtATime = (query) => {
608
+ let last = Promise.resolve();
609
+ return (text, values) => {
610
+ const next = last.then(() => query(text, values));
611
+ last = next.catch(() => void 0);
612
+ return next;
424
613
  };
425
- return roleMemo;
426
- };
427
- var versionToken = (ids) => {
428
- const s = ids.join("\n");
429
- let h = 2166136261;
430
- for (let i = 0; i < s.length; i += 1) {
431
- h ^= s.charCodeAt(i);
432
- h = Math.imul(h, 16777619) >>> 0;
433
- }
434
- return h.toString(16).padStart(8, "0");
435
- };
436
-
437
- // src/manifest/verify.ts
438
- var candidateOf = (shipped, inForce, grants) => ({
439
- charter: shipped.charter,
440
- actions: inForce.actions,
441
- layouts: shipped.layouts ?? {},
442
- wearable: wearableOf(shipped),
443
- grants,
444
- entries: inForce.entries,
445
- profiles: vex.scopeProfiles(shipped.behaviors ?? {})
446
- });
447
- var unreadActions = (actions) => Object.entries(actions).flatMap(([id, definition]) => {
448
- if (strata.exceedsDepth(definition)) return [{ id, why: strata.depthRefusal() }];
449
- const parsed = nova.ActionDefinitionSchema.safeParse(definition);
450
- if (parsed.success) return [];
451
- const first = parsed.error.issues[0];
452
- return [{ id, why: first === void 0 ? "no reason given" : `${first.path.join(".") || "(root)"}: ${first.message}` }];
453
- });
454
- var reachErrors = (entries, profiles) => {
455
- const unknown = entries.flatMap((entry2) => entry2.reach !== void 0 && !profiles.has(entry2.reach) ? [`${entry2.fingerprint} declares reach "${entry2.reach}"`] : []);
456
- return unknown.length === 0 ? [] : [...unknown, `known profiles: ${[...profiles].join(", ") || "(none)"}`];
457
- };
458
- var endlessChains = (actions) => reflect.chainCycles(actions).map((cycle) => ({ path: cycle.path, through: cycle.steps.map((step) => step.action) }));
459
- var verifyManifest = (candidate) => {
460
- const unread = unreadActions(candidate.actions);
461
- const refused = new Set(unread.map((action) => action.id));
462
- const read2 = refused.size === 0 ? candidate : { ...candidate, actions: Object.fromEntries(Object.entries(candidate.actions).filter(([id]) => !refused.has(id))) };
463
- const charter$1 = charter.verifyCharter(
464
- read2.charter,
465
- { actions: Object.keys(read2.actions), data: read2.grants, layouts: Object.keys(read2.layouts) },
466
- read2.wearable,
467
- auditClosure(read2.actions, read2.layouts)
468
- );
469
- const found = (check, details) => details.map((detail) => ({ check, detail }));
470
- return {
471
- errors: [
472
- ...found("actions", unread.map((action) => `"${action.id}" is not an action nova reads: ${action.why}`)),
473
- ...found("charter", charter$1.errors.map((error) => `${error.rule}: ${error.detail}`)),
474
- ...found("reach", reachErrors(read2.entries, read2.profiles)),
475
- ...found("variants", verifyVariants(read2))
476
- ],
477
- said: endlessChains(read2.actions).map((chain) => `a chain of steps that never ends: ${chain.path} \u2014 nova stops it at its budget when it runs (RUNAWAY_CHAIN)`),
478
- charter: charter$1
479
- };
480
- };
481
- var verifyApp = (app, grants) => verifyManifest(candidateOf(app, { actions: app.actions, entries: entriesOf(app) }, grants));
482
- var HEADLINES = {
483
- boot: {
484
- actions: "Actions are not ones nova reads \u2014 refusing to serve:",
485
- charter: "Charter is incoherent \u2014 refusing to serve:",
486
- reach: "Entries declare a reach no table offers \u2014 refusing to serve:",
487
- variants: "Layout variants are incoherent \u2014 refusing to serve:"
488
- },
489
- refresh: {
490
- actions: "Refresh refused \u2014 actions nova does not read:",
491
- charter: "Refresh refused \u2014 charter incoherent over the new artifacts:",
492
- reach: "Refresh refused \u2014 entries declare a reach no table offers:",
493
- variants: "Refresh refused \u2014 layout variants incoherent:"
494
- }
495
614
  };
496
- var refusalOf = (report, moment) => {
497
- const first = report.errors[0];
498
- if (first === void 0) return void 0;
499
- const findings = report.errors.filter((error) => error.check === first.check).map((error) => ` ${error.detail}`);
500
- return [HEADLINES[moment][first.check], ...findings].join("\n");
501
- };
502
- var verifyVariants = (app) => {
503
- const variants = app.layouts ?? {};
504
- const ids = Object.keys(variants);
505
- if (ids.length === 0) return [];
506
- const errors = [];
507
- for (const [id, variant] of Object.entries(variants)) {
508
- if (app.actions[variant.action] === void 0) {
509
- errors.push(`layout variant "${id}" reshapes unknown action "${variant.action}"`);
510
- }
511
- }
512
- const wearers = /* @__PURE__ */ new Map();
513
- for (const role of Object.keys(app.charter)) wearers.set(`role "${role}"`, [role]);
514
- for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(", ")}]`, roles);
515
- wearers.set("the anonymous principal", ["public"]);
516
- for (const [who, roles] of wearers) {
517
- let granted;
518
- try {
519
- granted = charter.resolvePrincipal(app.charter, ids, roles, "layouts");
520
- } catch {
521
- continue;
522
- }
523
- const byAction = /* @__PURE__ */ new Map();
524
- for (const id of granted) {
525
- const variant = variants[id];
526
- if (variant !== void 0) byAction.set(variant.action, [...byAction.get(variant.action) ?? [], id]);
527
- }
528
- for (const [action, held] of byAction) {
529
- if (held.length > 1) {
530
- errors.push(`${who} holds ${held.length} variants of "${action}" (${held.sort().join(", ")}) \u2014 one variant per action per principal`);
531
- }
532
- }
615
+ var migrateTables = async (runtime, app, options = {}) => {
616
+ const entries = chunk3DCTQKPQ_cjs.entriesOf(app);
617
+ const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
618
+ const before = await vex.createPostgresAdapter({ pool: runtime.pool }).introspect();
619
+ const misfitsBefore = misfitsOf(entries, before);
620
+ const excused = /* @__PURE__ */ new Set();
621
+ for (const entry of entries) {
622
+ if (misfitsBefore.has(entry.fingerprint) && await isSeededAs(cache, entry).catch(() => false)) excused.add(entry.fingerprint);
533
623
  }
534
- return errors;
535
- };
536
- var auditClosure = (definitions, variants = {}) => {
537
- return (grantedIds, layoutIds = []) => {
538
- const granted = withVariants(definitions, grantedIds, variantLayouts(variants, layoutIds)).map(([, definition]) => definition);
539
- const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));
540
- const channels = [
541
- ...new Set(
542
- granted.flatMap((definition) => {
543
- const found = nova.collectChannels(definition);
544
- return [...found.emits, ...found.listens];
545
- })
546
- )
547
- ];
548
- const issues = [];
549
- for (const definition of granted) {
550
- const audit = nova.auditAction(definition, { catalog, channels });
551
- if (audit.ok) continue;
552
- for (const issue of audit.issues) {
553
- if (issue.includes("which is not in the catalog") && !issue.includes("{{")) issues.push(`${definition.id}: ${issue}`);
624
+ let found = { removed: [], retyped: [], alreadyBroken: [] };
625
+ const owners = { pool: runtime.pool, cache: runtime.cache, storesSessions: runtime.session === "sessions", featureTables: featureTablesOf(app), tables: runtime.tables };
626
+ const report = await postgres.migrate(runtime.pool, tableSequencesOf(owners), {
627
+ ...options.dryRun === true ? { dryRun: true } : {},
628
+ guard: async (tx) => {
629
+ const after = await vex.createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
630
+ const refused = [];
631
+ const alreadyBroken = [];
632
+ for (const [fingerprint, why] of misfitsOf(entries, after)) {
633
+ if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
634
+ else refused.push(`${fingerprint}: ${why}`);
554
635
  }
636
+ found = { ...changesBetween(before, after), alreadyBroken };
637
+ return refused;
555
638
  }
556
- return issues;
557
- };
639
+ });
640
+ return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
558
641
  };
559
- var isDeferred = (value) => typeof value === "string" && i18n.isBinding(value) || reflect.isRecord(value) && Object.keys(value).some((key) => key.startsWith("$"));
560
- var layoutMisfits = (layout2, components) => {
561
- const found = /* @__PURE__ */ new Set();
562
- reflect.walkNodes(layout2, (record2) => {
563
- const name = record2["component"];
564
- if (typeof name !== "string") return;
565
- const spec = components.get(name);
566
- if (spec === void 0) {
567
- found.add(`layout uses "${name}", which this app has no component for`);
568
- return;
569
- }
570
- const schema = spec.propsSchema;
571
- const props = record2["props"];
572
- if (!(schema instanceof zod.z.ZodObject) || !reflect.isRecord(props)) return;
573
- const shape = schema.shape;
574
- for (const [key, value] of Object.entries(props)) {
575
- const prop = shape[key];
576
- if (prop === void 0) {
577
- found.add(`"${name}" has no prop "${key}"`);
578
- continue;
579
- }
580
- if (isDeferred(value)) continue;
581
- const check = zod.z.safeParse(prop, value);
582
- if (!check.success) found.add(`"${name}" prop "${key}" \u2014 ${check.error.issues[0]?.message ?? "invalid"}`);
642
+ var featureTablesOf = (app) => {
643
+ const features = /* @__PURE__ */ new Set();
644
+ return (app.features ?? []).map((feature) => {
645
+ if (features.has(feature.name)) {
646
+ throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
583
647
  }
648
+ features.add(feature.name);
649
+ const names = feature.tables?.names ?? [];
650
+ return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
584
651
  });
585
- return [...found];
586
652
  };
587
653
 
588
- // src/manifest/generation.ts
589
- var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
590
- var MAX_INTERVAL_MS = 2 ** 31 - 1;
591
- var MOVE_ATTEMPTS = 5;
592
- var createGeneration = (pointer, ctx) => {
593
- const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
594
- let seen = -1;
595
- let checking = false;
596
- const poll = async () => {
597
- if (checking) return;
598
- checking = true;
599
- try {
600
- const n = await readPointer();
601
- if (n === void 0 || n === seen) return;
602
- if (seen !== -1 && !await follow(n)) return;
603
- seen = n;
604
- } finally {
605
- checking = false;
606
- }
607
- };
608
- const readPointer = async () => {
609
- try {
610
- return await pointer.read();
611
- } catch (err) {
612
- console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
613
- return void 0;
614
- }
615
- };
616
- let unfollowed;
617
- const follow = async (n) => {
654
+ // src/data/aging.ts
655
+ var UNUSED_VERSIONS = (
656
+ /* sql */
657
+ `DELETE FROM artifacts a
658
+ WHERE a.principal <> '*'
659
+ AND (SELECT max(coalesce(b.last_used_at, b.created_at)) FROM artifacts b WHERE b.principal = a.principal AND b.kind = a.kind AND b.id = a.id) < now() - ($1::bigint * interval '1 millisecond')
660
+ RETURNING a.save`
661
+ );
662
+ var EMPTY_SAVES = (
663
+ /* sql */
664
+ `DELETE FROM artifact_saves s WHERE NOT EXISTS (SELECT 1 FROM artifacts a WHERE a.save = s.id) RETURNING s.id`
665
+ );
666
+ var sweepUnused = async (pool, unusedMs) => {
667
+ const versions = (await pool.query(UNUSED_VERSIONS, [unusedMs])).rows.length;
668
+ const saves = (await pool.query(EMPTY_SAVES)).rows.length;
669
+ return { versions, saves };
670
+ };
671
+ var AGING_EVERY_MS = 36e5;
672
+ var startAging = (pool, unusedMs, everyMs = AGING_EVERY_MS) => {
673
+ const sweep2 = async () => {
618
674
  try {
619
- await ctx.onMoved();
620
- } catch (err) {
621
- const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
622
- if (unfollowed?.said !== what) {
623
- console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
624
- }
625
- unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
626
- return false;
627
- }
628
- if (unfollowed !== void 0) {
629
- console.log(
630
- `[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
631
- );
632
- unfollowed = void 0;
633
- }
634
- return true;
675
+ const swept = await sweepUnused(pool, unusedMs);
676
+ if (swept.versions > 0) console.log(`[moss] aging: ${swept.versions} version(s) of what was generated and unused for ${unusedMs} ms deleted, and ${swept.saves} save(s) left empty`);
677
+ } catch (error) {
678
+ console.error("[moss] aging: the sweep failed, and is tried again at the next:", error);
679
+ }
680
+ };
681
+ void sweep2();
682
+ const timer = setInterval(() => void sweep2(), everyMs);
683
+ return () => clearInterval(timer);
684
+ };
685
+ var isWrittenForRequest = (entry) => entry.kind === "unsatisfiable" || entry.requestHash !== void 0;
686
+ var createEntryCache = (table) => {
687
+ let held;
688
+ const fromTable = (entry) => entry !== void 0 && isWrittenForRequest(entry) ? entry : void 0;
689
+ const tableEntries = async () => {
690
+ const rows = table.entries !== void 0 ? await table.entries() : await Promise.all((await table.keys()).map(async (key) => ({ key, entry: await table.get(key) })));
691
+ return rows.flatMap(({ key, entry }) => {
692
+ const kept = fromTable(entry);
693
+ return kept === void 0 ? [] : [{ key, entry: kept }];
694
+ });
635
695
  };
636
- const move = async () => {
637
- for (let attempt = 0; attempt < MOVE_ATTEMPTS; attempt += 1) {
638
- const n = await pointer.read();
639
- if (await pointer.move(n)) {
640
- if (seen === n || seen === -1) seen = n + 1;
641
- return;
642
- }
643
- }
644
- throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
696
+ const entries = async () => {
697
+ const first = await held?.entries() ?? [];
698
+ const answered = new Set(first.map((row) => row.key));
699
+ return [...first, ...(await tableEntries()).filter((row) => !answered.has(row.key))];
645
700
  };
646
- void poll();
647
- const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
648
- timer?.unref?.();
649
701
  return {
650
- bump: () => {
651
- void move().catch((err) => console.error("[moss:generation] could not move the pointer", err));
702
+ askFirst: (holder) => {
703
+ held = holder;
652
704
  },
653
- current: () => seen,
654
- stop: () => {
655
- if (timer !== void 0) clearInterval(timer);
705
+ cache: {
706
+ get: async (key, scope) => await held?.get(key, scope) ?? fromTable(await table.get(key)),
707
+ // Vex stamps an entry it replays by writing it back: one that was not written for a request is not the table's to keep.
708
+ set: async (key, entry) => {
709
+ if (isWrittenForRequest(entry)) await table.set(key, entry);
710
+ },
711
+ delete: (key) => table.delete(key),
712
+ clear: () => table.clear(),
713
+ keys: async () => (await entries()).map((row) => row.key),
714
+ entries
656
715
  }
657
716
  };
658
717
  };
659
- var seam = zod.z.custom((value) => typeof value === "function", "expected a function");
660
- var depthChecked = (schema) => zod.z.unknown().refine((value) => !strata.exceedsDepth(value), { message: strata.depthRefusal(), abort: true }).pipe(schema);
661
- var strings = zod.z.array(zod.z.string()).readonly();
662
- var record = zod.z.record(zod.z.string(), zod.z.unknown());
663
- var layout = depthChecked(nova.LayoutNodeSchema);
664
- var LayoutVariantSchema = zod.z.object({ action: zod.z.string(), layout }).strict();
665
- var CanvasSeedSchema = zod.z.union([zod.z.string(), zod.z.object({ action: zod.z.string(), input: record.optional(), with: strings.optional() }).strict()]);
666
- var CanvasSchema = zod.z.object({
667
- id: zod.z.string(),
668
- mode: zod.z.enum(["stack", "list"]).optional(),
669
- actionLayout: zod.z.union([zod.z.string(), layout]).optional(),
670
- initial: zod.z.union([CanvasSeedSchema, zod.z.array(CanvasSeedSchema)]).optional()
671
- }).strict();
672
- var ComponentContractSchema = zod.z.looseObject({ meta: zod.z.looseObject({ description: zod.z.string().optional() }).optional() });
673
- var shell = {
674
- canvases: zod.z.array(CanvasSchema),
675
- layout: layout.optional(),
676
- layoutStore: zod.z.record(zod.z.string(), layout).optional(),
677
- fragments: zod.z.record(zod.z.string(), depthChecked(nova.ActionFragmentSchema)).optional(),
678
- seeds: seam.optional(),
679
- components: zod.z.record(zod.z.string(), ComponentContractSchema).optional(),
680
- inputs: seam.optional()
681
- };
682
- var ShellManifestSchema = zod.z.object(shell).strict();
683
- var PageManifestSchema = zod.z.object({ ...shell, path: zod.z.string(), params: zod.z.string().optional() }).strict();
684
- var entry = { fingerprint: zod.z.string(), intent: zod.z.string().optional(), reach: zod.z.string().optional() };
685
- var ReadEntrySchema = zod.z.object({
686
- ...entry,
687
- shape: zod.z.unknown().optional(),
688
- dsl: depthChecked(vex.QuerySchema),
689
- mapping: depthChecked(prism.ConfigSchema).optional(),
690
- refresh: zod.z.enum(vex.REFRESH_MODES).optional()
691
- }).strict();
692
- var WriteEntrySchema = zod.z.object({ ...entry, mutation: depthChecked(vex.MutationDefinitionSchema) }).strict();
693
- var FeatureSchema = zod.z.looseObject({
694
- name: zod.z.string(),
695
- tables: zod.z.object({ names: strings, sequences: zod.z.array(strata.SequenceSchema).readonly().optional() }).strict().optional(),
696
- start: seam
697
- });
698
- var ReactionSchema = zod.z.object({ table: zod.z.string(), op: zod.z.enum(["insert", "update", "delete"]).optional(), run: seam }).strict();
699
- var fields = {
700
- charter: record,
701
- assignments: zod.z.record(zod.z.string(), strings).optional(),
702
- wearable: zod.z.array(strings).readonly().optional(),
703
- actions: zod.z.record(zod.z.string(), depthChecked(nova.ActionDefinitionSchema)),
704
- layouts: zod.z.record(zod.z.string(), LayoutVariantSchema).optional(),
705
- behaviors: zod.z.record(zod.z.string(), record).optional(),
706
- scope: seam.optional(),
707
- identity: zod.z.object({ as: zod.z.string().optional(), resolve: seam }).strict().optional(),
708
- phrases: seam.optional(),
709
- phraseKeys: zod.z.object({ props: strings.optional(), suffixes: strings.optional(), text: zod.z.boolean().optional() }).strict().optional(),
710
- features: zod.z.array(FeatureSchema).readonly().optional(),
711
- entries: zod.z.array(zod.z.union([ReadEntrySchema, WriteEntrySchema])).readonly().optional(),
712
- resources: zod.z.record(zod.z.string(), zod.z.union([strings, zod.z.looseObject({ entities: strings })])).optional(),
713
- shell: ShellManifestSchema.optional(),
714
- pages: zod.z.record(zod.z.string(), PageManifestSchema).optional(),
715
- grammars: zod.z.array(strata.SequenceSchema).readonly().optional(),
716
- functions: seam.optional(),
717
- onSession: seam.optional(),
718
- runs: seam.optional(),
719
- reactions: zod.z.array(ReactionSchema).readonly().optional()
720
- };
721
- var ManifestSchema = zod.z.object(fields).strict();
722
- var placesOf = (issue, under) => {
723
- const path = [...under, ...issue.path];
724
- if (issue.code !== "invalid_union") return [{ path, message: issue.message }];
725
- const branches = issue.errors.map((branch) => branch.flatMap((inner) => placesOf(inner, path))).filter((branch) => branch.length > 0);
726
- const reach = (places) => Math.max(...places.map((place) => place.path.length));
727
- const closer = (best, branch) => reach(branch) > reach(best) || reach(branch) === reach(best) && branch.length < best.length ? branch : best;
728
- const [first, ...others] = branches;
729
- return first === void 0 ? [{ path, message: issue.message }] : others.reduce(closer, first);
730
- };
731
- var manifestMisfits = (app) => {
732
- const parsed = ManifestSchema.safeParse(app);
733
- if (parsed.success) return [];
734
- return parsed.error.issues.flatMap((issue) => placesOf(issue, [])).map((place) => `${place.path.map(String).join(".") || "(the manifest)"}: ${place.message}`);
735
- };
736
- var isData = (value) => {
737
- if (Array.isArray(value)) return true;
738
- const made = Object.getPrototypeOf(value);
739
- return made === Object.prototype || made === null;
740
- };
741
- var freezeDeep = (data) => {
742
- const seen = /* @__PURE__ */ new Set();
743
- const pending = [data];
744
- while (pending.length > 0) {
745
- const value = pending.pop();
746
- if (typeof value !== "object" || value === null || !isData(value) || seen.has(value)) continue;
747
- seen.add(value);
748
- Object.freeze(value);
749
- for (const inner of Object.values(value)) pending.push(inner);
750
- }
751
- };
752
- var receiveManifest = (app) => {
753
- const misfits = manifestMisfits(app);
754
- if (misfits.length > 0) throw new Error(["The manifest does not parse \u2014 refusing to serve:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
755
- freezeDeep(app);
718
+ var createDataLayer = async (deps) => {
719
+ const adapter = vex.createPostgresAdapter({ pool: deps.pool });
720
+ const table = deps.cache ?? vex.createPostgresCache({ pool: deps.pool });
721
+ await table.init?.();
722
+ const { cache, askFirst } = createEntryCache(table);
723
+ const engine = vex.createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
724
+ const schema = await engine.introspect();
725
+ return { engine, adapter, schema, grants: vex.scopeGrants(schema.entities.map((e) => e.name)), askFirst };
756
726
  };
757
-
758
- // src/manifest/running.ts
759
- var mergedActions = (own, sets) => Object.freeze([...sets.values()].reduce((all, set) => ({ ...all, ...set }), { ...own }));
760
- var tell = (listener) => {
761
- try {
762
- listener();
763
- } catch (error) {
764
- console.error("[moss:manifest] a listener to a manifest change threw:", error);
727
+ var grammarsOf = (app) => [
728
+ migrations$1.NOVA_SEQUENCE,
729
+ migrations$2.PRISM_SEQUENCE,
730
+ migrations.VEX_SEQUENCE,
731
+ ...app.grammars ?? []
732
+ ];
733
+ var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: prism.evaluate });
734
+ var vexRecordToSpan = (rec) => ({
735
+ name: "vex.execute",
736
+ startUnixNano: rec.startUnixNano,
737
+ endUnixNano: rec.endUnixNano,
738
+ status: rec.status,
739
+ attributes: {
740
+ op: rec.kind,
741
+ hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
742
+ ...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
743
+ ...rec.reach !== void 0 ? { reach: rec.reach } : {},
744
+ ...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
745
+ ...rec.rows !== void 0 ? { rows: rec.rows } : {}
765
746
  }
766
- };
767
- var createSetOwners = () => {
768
- const owners = /* @__PURE__ */ new Map();
769
- const ownerRefusalOf = (source) => {
770
- const owner = owners.get(source);
771
- return owner === void 0 ? void 0 : `the set of actions "${source}" is ${owner}'s, and only its owner replaces it. An app hands a set over under a name of its own.`;
772
- };
773
- return {
774
- ownerRefusalOf,
775
- claim: (source, owner, handedOver) => {
776
- const held = owners.get(source);
777
- if (held !== void 0) throw new Error(`moss: the set of actions "${source}" is ${held}'s, and ${owner} claims it too. A set of actions has one writer.`);
778
- if (handedOver) throw new Error(`moss: the set of actions "${source}" was handed over by the app, and ${owner} claims it. A set of actions has one writer.`);
779
- owners.set(source, owner);
780
- },
781
- assertAppOwned: (source) => {
782
- const refusal = ownerRefusalOf(source);
783
- if (refusal !== void 0) throw new Error(`moss: ${refusal}`);
784
- return source;
785
- }
747
+ });
748
+ var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
749
+ var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
750
+ var createOwnEntries = (deps) => async (own) => {
751
+ const cache = vex.createMemoryCache();
752
+ await vex.seedCache(cache, own.entries);
753
+ const schema = await deps.adapter.introspect({ entities: [...own.tables] });
754
+ const engine = vex.createQueryEngine({
755
+ adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
756
+ cache
757
+ });
758
+ await engine.introspect();
759
+ const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, own.rules?.[table] ?? { public: true }])) };
760
+ const reachable = new Set((await vex.handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed2) => listed2.fingerprint));
761
+ const outside = own.entries.map((entry) => entry.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
762
+ if (outside.length > 0) {
763
+ throw new Error(
764
+ `moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
765
+ );
766
+ }
767
+ return async (fingerprint, context, scope = {}) => {
768
+ const outcome = await vex.handleQuery(
769
+ {
770
+ engine,
771
+ locked: true,
772
+ scopePolicy: policy,
773
+ mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(vex.tablesChangedBy(event.writes, schema)) },
774
+ ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
775
+ },
776
+ { fingerprint, context },
777
+ scope
778
+ );
779
+ if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
780
+ return resultOf(outcome.body);
786
781
  };
787
782
  };
788
- var verifiedAtBoot = (candidate) => {
789
- const report = verifyManifest(candidate);
790
- for (const line of report.said) console.error(`[moss] ${line}`);
791
- const refused = refusalOf(report, "boot");
792
- if (refused !== void 0) throw new Error(refused);
793
- return report;
783
+ var TABLE = "moss_generation";
784
+ var THE_ROW = { eq: [`${TABLE}.id`, 1] };
785
+ var readPointerEntry = {
786
+ fingerprint: "moss/generation",
787
+ intent: "Where the generation pointer is",
788
+ dsl: { from: [TABLE], fields: [`${TABLE}.n`], filter: THE_ROW, limit: 1 }
794
789
  };
795
- var createComponentNames = (read2) => {
796
- let components = /* @__PURE__ */ new WeakMap();
797
- return {
798
- of: (shell2) => {
799
- const kept = components.get(shell2);
800
- if (kept !== void 0) return kept;
801
- const names = read2(shell2);
802
- components.set(shell2, names);
803
- return names;
804
- },
805
- drop: () => {
806
- components = /* @__PURE__ */ new WeakMap();
807
- }
808
- };
790
+ var movePointerEntry = {
791
+ fingerprint: "moss/generation-move",
792
+ intent: "Move the generation pointer to the next number, if it is still where it was read",
793
+ mutation: {
794
+ op: "update",
795
+ table: TABLE,
796
+ set: { n: { $context: "next" } },
797
+ where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
798
+ }
809
799
  };
810
- var createRunningManifest = (config) => {
811
- const { shipped } = config;
812
- const entries = entriesOf(shipped);
813
- const candidate = (actions) => candidateOf(shipped, { actions, entries }, config.grants);
814
- const own = shipped.actions;
815
- const loaders = /* @__PURE__ */ new Map();
816
- const owners = createSetOwners();
817
- let sets = /* @__PURE__ */ new Map();
818
- let inForce = mergedActions(own, sets);
819
- let report = verifiedAtBoot(candidate(inForce));
820
- const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
821
- const roleMemo = createRoleMemo({
822
- manifest: () => ({ charter: shipped.charter, actions: inForce, layouts: shipped.layouts }),
823
- installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
824
- });
825
- const components = createComponentNames((shell2) => shellComponents({ actions: inForce, layouts: shipped.layouts }, shell2));
826
- const byFingerprint = new Map(entries.map((entry2) => [entry2.fingerprint, entry2]));
827
- const listeners = /* @__PURE__ */ new Set();
828
- let pointer;
829
- const applySets = (arrived, announce) => {
830
- const next = new Map([...sets, ...arrived]);
831
- const actions = mergedActions(own, next);
832
- const verified = verifyManifest(candidate(actions));
833
- const refusal = refusalOf(verified, "refresh");
834
- if (refusal !== void 0) throw new Error(refusal);
835
- for (const set of arrived.values()) freezeDeep(set);
836
- sets = next;
837
- inForce = actions;
838
- report = verified;
839
- roleMemo.drop();
840
- components.drop();
841
- for (const listener of [...listeners]) tell(listener);
842
- if (announce) pointer?.bump();
843
- };
844
- const reload = async () => {
845
- const read2 = [];
846
- for (const [source, load] of loaders) read2.push([source, await load()]);
847
- applySets(new Map(read2), false);
848
- };
800
+ var POINTER = { owner: "the generation pointer", entries: [readPointerEntry, movePointerEntry], tables: [TABLE] };
801
+ var RowSchema = zod.z.object({ n: zod.z.coerce.number() });
802
+ var RowsSchema = zod.z.array(zod.z.unknown());
803
+ var createPointer = (replay) => ({
804
+ read: async () => {
805
+ const rows = RowsSchema.parse(await (await replay())(readPointerEntry.fingerprint, {}));
806
+ return RowSchema.parse(rows[0] ?? { n: 0 }).n;
807
+ },
808
+ // A write that changed one row answers that row; one that changed none
809
+ // answers no row, which does not parse: the counter moved since it was read.
810
+ move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
811
+ });
812
+ var resolvePolicyForRoles = (app, grants, roles) => {
813
+ const behaviors = app.behaviors ?? {};
814
+ return vex.mergeScopePolicies(
815
+ roles.map(
816
+ (role) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, [role], "data"), behaviors, charter.resolveScoping(app.charter, role))
817
+ )
818
+ );
819
+ };
820
+ var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
821
+ var createPolicies = (config) => {
822
+ const { grants } = config;
823
+ const governed = { charter: config.charter, behaviors: config.behaviors };
824
+ const policies = /* @__PURE__ */ new Map();
825
+ const reachPolicies = /* @__PURE__ */ new Map();
849
826
  return {
850
- actions: () => inForce,
851
- entries: () => entries,
852
- verify: (actions) => verifyManifest(candidate(actions)),
853
- report: () => report,
854
- replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
855
- claim: (source, owner) => {
856
- owners.claim(source, owner, sets.has(source));
857
- return {
858
- replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
859
- setLoader: (load) => {
860
- loaders.set(source, load);
861
- if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
862
- }
863
- };
827
+ of: (who) => {
828
+ const hit = policies.get(who.memoKey);
829
+ if (hit !== void 0) return hit;
830
+ const compiled = resolvePolicyForRoles(governed, grants, who.roles);
831
+ policies.set(who.memoKey, compiled);
832
+ return compiled;
864
833
  },
865
- refresh: () => applySets(/* @__PURE__ */ new Map(), true),
866
- watch: () => {
867
- const where = config.pointer;
868
- if (pointer !== void 0 || where === void 0) return;
869
- pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
834
+ atReach: (who, reach) => {
835
+ const key = `${who.memoKey}\0${reach}`;
836
+ const hit = reachPolicies.get(key);
837
+ if (hit !== void 0) return hit;
838
+ const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
839
+ reachPolicies.set(key, compiled);
840
+ return compiled;
870
841
  },
871
- onChange: (listener) => {
842
+ drop: () => {
843
+ policies.clear();
844
+ reachPolicies.clear();
845
+ }
846
+ };
847
+ };
848
+ var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) => {
849
+ const roles = [role];
850
+ const policy = deps.policyFor(roles);
851
+ const outcome = await vex.handleQuery(
852
+ {
853
+ engine: deps.engine,
854
+ locked: true,
855
+ scopePolicy: policy,
856
+ policyForReach: (reach) => deps.policyAtReach(roles, reach),
857
+ mutations: { client: deps.db, policy },
858
+ ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
859
+ },
860
+ { fingerprint, context },
861
+ scope
862
+ );
863
+ if (outcome.status !== 200) {
864
+ console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
865
+ return void 0;
866
+ }
867
+ const body = outcome.body;
868
+ return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
869
+ };
870
+ var CREDENTIALS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization"]);
871
+ var writeRequestOf = (header) => ({
872
+ header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
873
+ });
874
+ var SAID_NOTHING = { header: () => void 0 };
875
+ var createWriteNotifier = () => {
876
+ const requests = new async_hooks.AsyncLocalStorage();
877
+ const listeners = /* @__PURE__ */ new Set();
878
+ return {
879
+ subscribe: (listener) => {
872
880
  listeners.add(listener);
873
881
  return () => {
874
882
  listeners.delete(listener);
875
883
  };
876
884
  },
877
- addCatalogFilter: (filter) => {
878
- catalogFilters.push(filter);
879
- roleMemo.drop();
880
- },
881
- catalogFor: roleMemo.catalogFor,
882
- artifactsFor: (shell2, roles, installed) => ({
883
- actions: roleMemo.definitionsFor(roles, installed),
884
- canvases: shell2.canvases,
885
- ...shell2.layout !== void 0 ? { frame: shell2.layout } : {},
886
- ...shell2.layoutStore !== void 0 ? { layoutStore: shell2.layoutStore } : {},
887
- ...shell2.fragments !== void 0 ? { fragments: shell2.fragments } : {},
888
- entries: byFingerprint,
889
- components: components.of(shell2)
890
- }),
891
- generation: () => pointer?.current() ?? -1,
892
- stop: () => pointer?.stop()
885
+ within: (request, run) => requests.run(request, run),
886
+ report: (event) => {
887
+ const request = requests.getStore() ?? SAID_NOTHING;
888
+ for (const listener of [...listeners]) {
889
+ try {
890
+ listener(event, request);
891
+ } catch (error) {
892
+ console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
893
+ }
894
+ }
895
+ }
896
+ };
897
+ };
898
+ var createWireFollower = (callSignal) => {
899
+ const controller = new AbortController();
900
+ const end = () => {
901
+ controller.abort();
902
+ };
903
+ if (callSignal.aborted) end();
904
+ else callSignal.addEventListener("abort", end, { once: true });
905
+ const handlers = /* @__PURE__ */ new Set();
906
+ let missed;
907
+ const live = {
908
+ signal: controller.signal,
909
+ onChange: (response) => {
910
+ if (handlers.size === 0) {
911
+ missed = { body: response.result };
912
+ return;
913
+ }
914
+ for (const handler of [...handlers]) handler(response.result);
915
+ }
916
+ };
917
+ const onChange = (handler) => {
918
+ if (controller.signal.aborted) return () => {
919
+ };
920
+ handlers.add(handler);
921
+ if (missed !== void 0) {
922
+ const { body } = missed;
923
+ missed = void 0;
924
+ handler(body);
925
+ }
926
+ return () => {
927
+ handlers.delete(handler);
928
+ if (handlers.size === 0) end();
929
+ };
893
930
  };
931
+ const handedOver = () => {
932
+ setTimeout(() => {
933
+ if (handlers.size === 0) end();
934
+ }, 0);
935
+ };
936
+ return { live, onChange, handedOver, end };
894
937
  };
895
938
 
896
- // src/data/tables.ts
897
- var GENERATION_DDL = [
898
- /* sql */
899
- `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
900
- /* sql */
901
- `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
902
- ];
903
- var MOSS_SEQUENCE = {
904
- id: "nisc.moss",
905
- migrations: [
906
- {
907
- description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
908
- steps: [
909
- { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
910
- id text PRIMARY KEY,
911
- url text NOT NULL,
912
- -- THE HASH, NEVER THE KEY. The integration key is minted at registration
913
- -- (see assert.ts for the credential rule), returned once in that response,
914
- -- and this is all that remains of it here. Presenting the key is the only
915
- -- way to produce this value again, so a stolen database does not hold a
916
- -- credential \u2014 and a lost key is re-registered, not recovered.
917
- key_hash text,
918
- status text NOT NULL DEFAULT 'pending',
919
- -- The store card's words, straight from the bundle's meta. Columns
920
- -- rather than jsonb so an app's vex read can select them like anything
921
- -- else on this table.
922
- title text NOT NULL DEFAULT '',
923
- tagline text NOT NULL DEFAULT '',
924
- description text NOT NULL DEFAULT '',
925
- -- The listing page's long form, re-imported whole like everything else
926
- -- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
927
- -- intake (copyPress), never the paths the bundle declared \u2014 the listing
928
- -- composes from host ground alone.
929
- story jsonb NOT NULL DEFAULT '[]'::jsonb,
930
- highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
931
- press jsonb NOT NULL DEFAULT '[]'::jsonb,
932
- -- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
933
- -- printed by the approval card and the store tile from this one place.
934
- adds text NOT NULL DEFAULT '',
935
- -- The one integration action the store may open: its settings screen.
936
- settings_action text NOT NULL DEFAULT '',
937
- requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
938
- requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
939
- approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
940
- -- What it tells and hears (bundle offers/needs), beside the grants
941
- -- because they are the same kind of thing: the integration's declared
942
- -- statement, written at import, replaced on re-registration. moss
943
- -- never reads them; the host's bus does.
944
- offers jsonb NOT NULL DEFAULT '[]'::jsonb,
945
- needs jsonb NOT NULL DEFAULT '[]'::jsonb,
946
- -- The verbs the integration gates on ({id, title}), for the host's role
947
- -- editor to grant. Beside offers/needs because it is the same kind of
948
- -- thing: a declaration written at import, replaced on re-registration,
949
- -- that moss never reads \u2014 the host does.
950
- capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
951
- -- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
952
- -- beside capabilities because it is the same kind of thing: a declaration
953
- -- written at import, replaced on re-registration, that moss never reads.
954
- -- The host renders a settings form from it and stores the values itself.
955
- configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
956
- -- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
957
- -- and a section model the host's editor renders. Beside configuration
958
- -- because it is the same kind of thing: a declaration written at import,
959
- -- replaced on re-registration, that moss never reads \u2014 the host does.
960
- documents jsonb NOT NULL DEFAULT '[]'::jsonb,
961
- -- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
962
- -- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
963
- -- the host's assistant is the consumer.
964
- assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
965
- -- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
966
- -- (reachOf). Beside the grants because it is one: a grant of reach, held
967
- -- by the same row, revoked by the same delete.
968
- reach jsonb NOT NULL DEFAULT '[]'::jsonb,
969
- -- Pages this integration serves and the host frames. Kept apart from reach
970
- -- because they are spent differently: reach is a screen's call carrying a
971
- -- session, a frame is a document GET carrying a grant.
972
- frames jsonb NOT NULL DEFAULT '[]'::jsonb,
973
- last_import_at timestamptz,
974
- last_error text
975
- )
976
- ` },
977
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
978
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
979
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
980
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
981
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
982
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
983
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
984
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
985
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
986
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
987
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
988
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
989
- { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
990
- integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
991
- action_id text NOT NULL,
992
- definition jsonb NOT NULL,
993
- -- The bindings, beside the artifact and never inside it: which host
994
- -- action this one rides (a panel), or which menu hub lists it. Empty
995
- -- means neither \u2014 reachable only through whatever else names it.
996
- -- preview is the rider's display endpoint (own-prefix, validated at
997
- -- intake): the host calls it with the offered ids to paint the strip.
998
- attach_to text NOT NULL DEFAULT '',
999
- preview text NOT NULL DEFAULT '',
1000
- place_in text NOT NULL DEFAULT '',
1001
- PRIMARY KEY (integration_id, action_id)
1002
- )
1003
- ` },
1004
- ...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
1005
- ]
1006
- },
1007
- {
1008
- description: "Stored integration actions carry the grammar stamp their definition is written in",
1009
- steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
1010
- },
1011
- {
1012
- description: "No two integrations hold the hash of one key",
1013
- steps: [{ kind: "sql", sql: `CREATE UNIQUE INDEX integrations_key_hash_unique ON integrations (key_hash) WHERE key_hash IS NOT NULL` }]
939
+ // src/data/routes.ts
940
+ var createVexRoutes = (deps) => {
941
+ const routes = new hono.Hono();
942
+ routes.use(
943
+ "/api/*",
944
+ (c, next) => deps.writes.within(
945
+ writeRequestOf((name) => c.req.header(name)),
946
+ () => next()
947
+ )
948
+ );
949
+ const mount = (path, entities) => {
950
+ routes.route(
951
+ path,
952
+ hono$1.vex({
953
+ engine: deps.engine,
954
+ ...entities !== void 0 ? { entities: [...entities] } : {},
955
+ locked: true,
956
+ getScope: deps.scope,
957
+ getPolicy: deps.policy,
958
+ getPolicyForReach: deps.policyAtReach,
959
+ ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
960
+ mutations: { client: deps.db, onWrite: deps.writes.report }
961
+ })
962
+ );
963
+ };
964
+ mount("/api/vex");
965
+ for (const [name, resource] of Object.entries(deps.resources ?? {})) {
966
+ mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
967
+ }
968
+ return routes;
969
+ };
970
+ var createIntentAnswers = (deps) => {
971
+ const engines = /* @__PURE__ */ new WeakMap();
972
+ const engineFor = (writers) => {
973
+ const kept = engines.get(writers);
974
+ if (kept !== void 0) return kept;
975
+ const { adapter, schema } = deps;
976
+ const created = (async () => {
977
+ const engine = vex.createQueryEngine({
978
+ adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
979
+ cache: deps.cache,
980
+ generateDsl: writers.generateDsl,
981
+ mapToShape: writers.mapToShape,
982
+ ...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
983
+ ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
984
+ });
985
+ await engine.introspect();
986
+ return engine;
987
+ })();
988
+ engines.set(writers, created);
989
+ return created;
990
+ };
991
+ return async (writers, asked, caller) => (await engineFor(writers)).execute(
992
+ "fingerprint" in asked ? { fingerprint: asked.fingerprint, context: asked.context ?? {} } : { intent: asked.intent, shape: asked.shape, context: asked.context ?? {} },
993
+ { scope: caller.scope, scopePolicy: caller.policy }
994
+ );
995
+ };
996
+
997
+ // src/data/data.ts
998
+ var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
999
+ var prepareEngine = async (config) => {
1000
+ await postgres.migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
1001
+ const grammars = await createGrammarUpgrader({ grammars: config.grammars });
1002
+ const layer = await createDataLayer(config);
1003
+ return {
1004
+ grammars,
1005
+ engine: layer.engine,
1006
+ grants: layer.grants,
1007
+ adapter: layer.adapter,
1008
+ askFirst: layer.askFirst,
1009
+ upgradeStore: async (store) => {
1010
+ await postgres.upgradeStore(config.pool, store, grammars);
1011
+ }
1012
+ };
1013
+ };
1014
+ var lazyIntentAnswers = (prepared, config) => {
1015
+ const { engine } = prepared;
1016
+ let answers;
1017
+ const answering = () => {
1018
+ if (answers !== void 0) return answers;
1019
+ const schema = engine.getSchema();
1020
+ if (schema === void 0) throw new Error("moss: an intent was asked before the engine had read the database.");
1021
+ answers = createIntentAnswers({
1022
+ adapter: prepared.adapter,
1023
+ schema,
1024
+ cache: engine.cache,
1025
+ ...config.behaviors !== void 0 ? { behaviors: config.behaviors } : {},
1026
+ ...config.vexConfig !== void 0 ? { vexConfig: config.vexConfig } : {}
1027
+ });
1028
+ return answers;
1029
+ };
1030
+ return answering;
1031
+ };
1032
+ var tablesByFeature = (config) => (feature) => {
1033
+ const kept = (config.featureTables ?? []).find((tables) => tables.feature === feature);
1034
+ if (kept === void 0) throw new Error(`moss: the data module was asked for the tables of a feature it was never told of ("${feature}").`);
1035
+ return kept.names;
1036
+ };
1037
+ var createUpgradeStore = (prepared, tablesOf) => async (feature, store) => {
1038
+ const own = tablesOf(feature);
1039
+ if (store.schema !== void 0) {
1040
+ throw new Error(
1041
+ `moss: the feature "${feature}" asked for the documents of a store in the schema "${store.schema}" to be upgraded. To a feature a store is named by its table alone: one of its own.`
1042
+ );
1043
+ }
1044
+ if (!own.includes(store.table)) {
1045
+ throw new Error(`moss: the feature "${feature}" asked for the documents stored in "${store.table}" to be upgraded, and that table is not its own (its own: ${own.join(", ") || "none"}).`);
1046
+ }
1047
+ await prepared.upgradeStore(store);
1048
+ };
1049
+ var createDataWith = (prepared, config) => {
1050
+ const { grammars, engine, grants } = prepared;
1051
+ const governed = { charter: config.charter, behaviors: { ...config.behaviors, ...config.rowRules } };
1052
+ const policies = createPolicies({ ...governed, grants });
1053
+ const emit = chunkPVZMCEBX_cjs.emitterOf(config.telemetry);
1054
+ const onExecute = emit === void 0 ? void 0 : (record) => emit(vexRecordToSpan(record));
1055
+ const writes = createWriteNotifier();
1056
+ const answering = lazyIntentAnswers(prepared, config);
1057
+ const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
1058
+ const tablesOf = tablesByFeature(config);
1059
+ let pointerEntries;
1060
+ const pointerReplay = () => {
1061
+ pointerEntries ??= ownEntries(POINTER, void 0);
1062
+ return pointerEntries;
1063
+ };
1064
+ return {
1065
+ grants,
1066
+ grammars,
1067
+ entriesHeldBy: prepared.askFirst,
1068
+ fingerprints: async () => await engine.cache.keys?.() ?? [],
1069
+ policyOf: policies.of,
1070
+ // Compiled afresh and not taken from the kept ones: the caller owns its
1071
+ // copy, and nothing it does to it reaches a policy a request is served under.
1072
+ policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
1073
+ fingerprintsFor: async (who) => (await vex.handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry) => entry.fingerprint).sort(),
1074
+ vexEntry: (fingerprint) => engine.cache.get(fingerprint),
1075
+ compileQuery: (dsl) => {
1076
+ engine.compile(dsl);
1014
1077
  },
1015
- {
1016
- description: "An integration keeps what its bundle says in the host app\u2019s own vocabulary as one value, and the columns of one product\u2019s vocabulary go",
1017
- steps: [
1018
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN extension jsonb` },
1019
- {
1020
- kind: "sql",
1021
- sql: `ALTER TABLE integrations
1022
- DROP COLUMN IF EXISTS title,
1023
- DROP COLUMN IF EXISTS tagline,
1024
- DROP COLUMN IF EXISTS description,
1025
- DROP COLUMN IF EXISTS story,
1026
- DROP COLUMN IF EXISTS highlights,
1027
- DROP COLUMN IF EXISTS press,
1028
- DROP COLUMN IF EXISTS adds,
1029
- DROP COLUMN IF EXISTS settings_action,
1030
- DROP COLUMN IF EXISTS offers,
1031
- DROP COLUMN IF EXISTS needs,
1032
- DROP COLUMN IF EXISTS capabilities,
1033
- DROP COLUMN IF EXISTS configuration,
1034
- DROP COLUMN IF EXISTS documents,
1035
- DROP COLUMN IF EXISTS assistants,
1036
- DROP COLUMN IF EXISTS frames`
1037
- },
1038
- {
1039
- kind: "sql",
1040
- sql: `ALTER TABLE integration_actions
1041
- DROP COLUMN IF EXISTS attach_to,
1042
- DROP COLUMN IF EXISTS preview,
1043
- DROP COLUMN IF EXISTS place_in`
1044
- }
1045
- ]
1078
+ executeAs: createExecuteAs({
1079
+ engine,
1080
+ db: config.db,
1081
+ policyFor: (roles) => policies.of(callerOfRoles(roles)),
1082
+ policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
1083
+ ...onExecute !== void 0 ? { onExecute } : {}
1084
+ }),
1085
+ answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
1086
+ ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
1087
+ artifactEntries: (entries, rules) => ownEntries({ owner: "the artifactory", entries, tables: ARTIFACT_TABLES, rules }, onExecute),
1088
+ routes: (routing) => createVexRoutes({
1089
+ engine,
1090
+ db: config.db,
1091
+ resources: routing.resources,
1092
+ scope: routing.scope,
1093
+ policy: (c) => policies.of(routing.caller(c)),
1094
+ policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
1095
+ ...onExecute !== void 0 ? { onExecute } : {},
1096
+ writes
1097
+ }),
1098
+ upgradeStore: createUpgradeStore(prepared, tablesOf),
1099
+ onWrite: writes.subscribe,
1100
+ pointer: createPointer(pointerReplay),
1101
+ dropOnChange: (changed) => {
1102
+ changed(policies.drop);
1046
1103
  }
1047
- ]
1104
+ };
1048
1105
  };
1049
- var tableSequencesOf = (owners) => {
1050
- const cacheSequence = (owners.cache ?? vex.createPostgresCache({ pool: owners.pool })).sequence;
1051
- return [
1052
- MOSS_SEQUENCE,
1053
- ...owners.storesSessions ? [SESSIONS_SEQUENCE] : [],
1054
- ...cacheSequence === void 0 ? [] : [cacheSequence],
1055
- ...(owners.featureTables ?? []).flatMap((kept) => kept.sequences),
1056
- ...owners.tables ?? []
1057
- ];
1106
+ var createData = async (config) => createDataWith(await prepareEngine(config), config);
1107
+ var DEFAULT_ROOT = '<div id="root"></div>';
1108
+ var embedSnapshot = (snapshot, principal, path) => {
1109
+ const { frame, trees, seed, live } = snapshot;
1110
+ const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
1111
+ const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1112
+ return `<script type="application/json" id="${chunk3RIWTXGI_cjs.SNAPSHOT_ELEMENT_ID}">${text}</script>`;
1058
1113
  };
1059
- var misfitOf = (entry2, schema) => {
1060
- if (!("mutation" in entry2)) {
1061
- try {
1062
- vex.resolve(vex.pruneOptional(entry2.dsl, "all"), schema);
1063
- return void 0;
1064
- } catch (error) {
1065
- return error instanceof Error ? error.message : String(error);
1066
- }
1067
- }
1068
- return vex.mutationMisfits(entry2.mutation, schema)[0];
1114
+ var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
1115
+ var rootHolding = (root) => {
1116
+ const closing = root.lastIndexOf("</");
1117
+ if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
1118
+ return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
1069
1119
  };
1070
- var misfitsOf = (entries, schema) => {
1071
- const misfits = /* @__PURE__ */ new Map();
1072
- for (const entry2 of entries) {
1073
- const why = misfitOf(entry2, schema);
1074
- if (why !== void 0) misfits.set(entry2.fingerprint, why);
1120
+ var escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1121
+ var renderDocument = async (config) => {
1122
+ const { server, template, request, draw } = config;
1123
+ const tokenKey = config.tokenKey ?? chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY;
1124
+ const root = config.root ?? DEFAULT_ROOT;
1125
+ const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
1126
+ if (!template.includes(root)) return undrawn;
1127
+ const holding = rootHolding(root);
1128
+ if (holding === void 0) {
1129
+ console.error(`[moss/document] the root ${root} has no place for a screen \u2014 a root is an empty element, like ${DEFAULT_ROOT}. "${request.path}" is served undrawn.`);
1130
+ return undrawn;
1131
+ }
1132
+ try {
1133
+ const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
1134
+ const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
1135
+ const principal = token === null ? null : await server.principalOf(token);
1136
+ const route = server.page(request.path);
1137
+ const host = route?.host ?? server.shells;
1138
+ if (host === void 0) return undrawn;
1139
+ const snapshot = await host.snapshot(principal === null ? null : token, principal, {
1140
+ ...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
1141
+ ...route !== void 0 ? { inputs: route.inputs } : {}
1142
+ });
1143
+ const screen = await draw(snapshot);
1144
+ const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
1145
+ const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
1146
+ const head = document.headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
1147
+ for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
1148
+ const html = document.placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
1149
+ return {
1150
+ html,
1151
+ ...head !== void 0 ? { head } : {},
1152
+ headers: documentHeaders(principal),
1153
+ drawn: true,
1154
+ principal,
1155
+ ...route !== void 0 ? { page: route.name } : {},
1156
+ live: snapshot.live,
1157
+ why: snapshot.why,
1158
+ drawnWith: snapshot.drawnWith,
1159
+ settled: snapshot.settled
1160
+ };
1161
+ } catch (error) {
1162
+ console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
1163
+ return undrawn;
1075
1164
  }
1076
- return misfits;
1077
- };
1078
- var canonical = (value) => {
1079
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1080
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1081
- const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
1082
- return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
1083
- };
1084
- var isSeededAs = async (cache, entry2) => {
1085
- const held = await cache.get(entry2.fingerprint);
1086
- if (held === void 0 || held.protected !== true) return false;
1087
- if ("mutation" in entry2) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry2.mutation);
1088
- return held.kind === "ok" && canonical(held.dsl) === canonical(entry2.dsl);
1089
1165
  };
1090
- var changesBetween = (before, after) => {
1091
- const removed = [];
1092
- const retyped = [];
1093
- for (const was of before.entities) {
1094
- const now = after.entities.find((entity) => entity.table === was.table);
1095
- if (now === void 0) {
1096
- removed.push(was.table);
1097
- continue;
1098
- }
1099
- for (const field of was.fields) {
1100
- const kept = now.fields.find((f) => f.name === field.name);
1101
- if (kept === void 0) removed.push(`${was.table}.${field.name}`);
1102
- else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
1166
+
1167
+ // src/documents/pages.ts
1168
+ var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
1169
+ var compile = (name, page) => {
1170
+ if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
1171
+ const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
1172
+ for (const segment of segments) {
1173
+ if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
1174
+ throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
1103
1175
  }
1104
1176
  }
1105
- return { removed, retyped };
1106
- };
1107
- var oneAtATime = (query) => {
1108
- let last = Promise.resolve();
1109
- return (text, values) => {
1110
- const next = last.then(() => query(text, values));
1111
- last = next.catch(() => void 0);
1112
- return next;
1113
- };
1177
+ const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
1178
+ const twice = named.find((param, index) => named.indexOf(param) !== index);
1179
+ if (twice !== void 0) {
1180
+ throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
1181
+ }
1182
+ if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
1183
+ throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
1184
+ }
1185
+ return { name, segments };
1114
1186
  };
1115
- var migrateTables = async (runtime, app, options = {}) => {
1116
- const entries = entriesOf(app);
1117
- const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
1118
- const before = await vex.createPostgresAdapter({ pool: runtime.pool }).introspect();
1119
- const misfitsBefore = misfitsOf(entries, before);
1120
- const excused = /* @__PURE__ */ new Set();
1121
- for (const entry2 of entries) {
1122
- if (misfitsBefore.has(entry2.fingerprint) && await isSeededAs(cache, entry2).catch(() => false)) excused.add(entry2.fingerprint);
1187
+ var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
1188
+ const other = b.segments[index];
1189
+ return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
1190
+ });
1191
+ var createPageRouter = (pages) => {
1192
+ const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));
1193
+ for (const [index, page] of compiled.entries()) {
1194
+ const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));
1195
+ if (other !== void 0) {
1196
+ throw new Error(`moss: pages "${page.name}" and "${other.name}" can both answer one path \u2014 give them paths that differ in a literal segment.`);
1197
+ }
1123
1198
  }
1124
- let found = { removed: [], retyped: [], alreadyBroken: [] };
1125
- const owners = { pool: runtime.pool, cache: runtime.cache, storesSessions: runtime.session === "sessions", featureTables: featureTablesOf(app), tables: runtime.tables };
1126
- const report = await postgres.migrate(runtime.pool, tableSequencesOf(owners), {
1127
- ...options.dryRun === true ? { dryRun: true } : {},
1128
- guard: async (tx) => {
1129
- const after = await vex.createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
1130
- const refused = [];
1131
- const alreadyBroken = [];
1132
- for (const [fingerprint, why] of misfitsOf(entries, after)) {
1133
- if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
1134
- else refused.push(`${fingerprint}: ${why}`);
1199
+ return {
1200
+ match: (path) => {
1201
+ const parts = segmentsOf(path);
1202
+ for (const page of compiled) {
1203
+ if (page.segments.length !== parts.length) continue;
1204
+ const params = {};
1205
+ let matches = true;
1206
+ for (const [index, segment] of page.segments.entries()) {
1207
+ const part = parts[index];
1208
+ if (part === void 0) {
1209
+ matches = false;
1210
+ break;
1211
+ }
1212
+ if ("param" in segment) {
1213
+ try {
1214
+ params[segment.param] = decodeURIComponent(part);
1215
+ } catch {
1216
+ matches = false;
1217
+ break;
1218
+ }
1219
+ } else if (segment.literal !== part) {
1220
+ matches = false;
1221
+ break;
1222
+ }
1223
+ }
1224
+ if (matches) return { name: page.name, params };
1135
1225
  }
1136
- found = { ...changesBetween(before, after), alreadyBroken };
1137
- return refused;
1226
+ return void 0;
1138
1227
  }
1228
+ };
1229
+ };
1230
+ var exportDocuments = async (config) => {
1231
+ const { paths, ...rest } = config;
1232
+ const out = [];
1233
+ for (const path of paths) {
1234
+ const page = await renderDocument({ ...rest, request: { path, cookie: null } });
1235
+ out.push({
1236
+ path,
1237
+ html: page.html,
1238
+ ...page.page !== void 0 ? { page: page.page } : {},
1239
+ ...page.head !== void 0 ? { head: page.head } : {},
1240
+ drawn: page.drawn,
1241
+ // A page that could not be drawn is not taken to be finished.
1242
+ live: page.live ?? true,
1243
+ why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
1244
+ drawnWith: page.drawnWith ?? [],
1245
+ settled: page.settled ?? false
1246
+ });
1247
+ }
1248
+ return out;
1249
+ };
1250
+ var isKept = (layout) => layout !== void 0 && layout !== null && typeof layout !== "string";
1251
+ var shellWithStoredLayouts = (shell) => {
1252
+ const layouts = {};
1253
+ const frame = shell.layout;
1254
+ if (isKept(frame)) layouts[chunk3DCTQKPQ_cjs.FRAME_LAYOUT_REF] = frame;
1255
+ const canvases = shell.canvases.map((canvas) => {
1256
+ const layout = canvas.actionLayout;
1257
+ if (!isKept(layout)) return canvas;
1258
+ const ref = chunk3DCTQKPQ_cjs.canvasLayoutRef(canvas.id);
1259
+ layouts[ref] = layout;
1260
+ return { ...canvas, actionLayout: ref };
1139
1261
  });
1140
- return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
1262
+ return { canvases, ...isKept(frame) ? { frame: chunk3DCTQKPQ_cjs.FRAME_LAYOUT_REF } : typeof frame === "string" ? { frame } : {}, layouts };
1263
+ };
1264
+ var slottedIn = /* @__PURE__ */ new WeakMap();
1265
+ var canvasesSlottedIn = (layout) => {
1266
+ const kept = slottedIn.get(layout);
1267
+ if (kept !== void 0) return kept;
1268
+ const ids = /* @__PURE__ */ new Set();
1269
+ reflect.walkNodes(layout, (node) => {
1270
+ const id = node["component"] === nova.CANVAS_SLOT_NAME && reflect.isRecord(node["props"]) ? node["props"]["canvasId"] : void 0;
1271
+ if (typeof id === "string" && id !== "" && !i18n.isBinding(id)) ids.add(id);
1272
+ });
1273
+ const found = [...ids];
1274
+ slottedIn.set(layout, found);
1275
+ return found;
1276
+ };
1277
+ var slottedCanvases = (declared, layouts) => {
1278
+ const ids = /* @__PURE__ */ new Set();
1279
+ for (const layout of layouts) {
1280
+ if (layout === null || typeof layout !== "object") continue;
1281
+ for (const id of canvasesSlottedIn(layout)) ids.add(id);
1282
+ }
1283
+ for (const canvas of declared) ids.delete(canvas.id);
1284
+ return [...ids];
1141
1285
  };
1142
- var featureTablesOf = (app) => {
1143
- const features = /* @__PURE__ */ new Set();
1144
- return (app.features ?? []).map((feature) => {
1145
- if (features.has(feature.name)) {
1146
- throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
1286
+ var shellComponents = (manifest, shell) => {
1287
+ const names = /* @__PURE__ */ new Set([nova.CANVAS_SLOT_NAME, nova.ACTION_SLOT_NAME]);
1288
+ for (const source of [manifest.actions, manifest.layouts ?? {}, shell.canvases, shell.layout ?? {}, shell.layoutStore ?? {}, shell.fragments ?? {}]) {
1289
+ for (const name of reflect.componentsOf(source)) names.add(name);
1290
+ }
1291
+ const contracts = shell.components ?? {};
1292
+ for (const name of Object.keys(contracts)) names.add(name);
1293
+ return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
1294
+ };
1295
+ var createComponentNames = (read2) => {
1296
+ let components = /* @__PURE__ */ new WeakMap();
1297
+ return {
1298
+ of: (shell) => {
1299
+ const kept = components.get(shell);
1300
+ if (kept !== void 0) return kept;
1301
+ const names = read2(shell);
1302
+ components.set(shell, names);
1303
+ return names;
1304
+ },
1305
+ drop: () => {
1306
+ components = /* @__PURE__ */ new WeakMap();
1147
1307
  }
1148
- features.add(feature.name);
1149
- const names = feature.tables?.names ?? [];
1150
- return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
1151
- });
1308
+ };
1152
1309
  };
1153
- var createDataLayer = async (deps) => {
1154
- const adapter = vex.createPostgresAdapter({ pool: deps.pool });
1155
- const cache = deps.cache ?? vex.createPostgresCache({ pool: deps.pool });
1156
- await cache.init?.();
1157
- const engine = vex.createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
1158
- const schema = await engine.introspect();
1159
- return { engine, adapter, schema, grants: vex.scopeGrants(schema.entities.map((e) => e.name)) };
1310
+ var SavedLayoutSchema = zod.z.strictObject({ ref: zod.z.string(), layout: nova.LayoutNodeSchema, use: zod.z.boolean().optional() });
1311
+ var upgradedLayoutBody = (upgrader, body, stamp) => reflect.isRecord(body) && body["layout"] !== void 0 ? { ...body, layout: upgrader.upgrade(body["layout"], { kind: "nisc.nova/layout", stamp }).document } : body;
1312
+ var actionAtRef = (actions, layouts) => (ref) => {
1313
+ const id = chunk3DCTQKPQ_cjs.actionOfLayoutRef(ref);
1314
+ const action = id !== void 0 && Object.hasOwn(actions, id) ? actions[id] : void 0;
1315
+ const layout = Object.hasOwn(layouts, ref) ? layouts[ref] : void 0;
1316
+ return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
1160
1317
  };
1161
- var grammarsOf = (app) => [
1162
- migrations.NOVA_SEQUENCE,
1163
- migrations$1.PRISM_SEQUENCE,
1164
- ...app.grammars ?? []
1165
- ];
1166
- var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: prism.evaluate });
1167
- var vexRecordToSpan = (rec) => ({
1168
- name: "vex.execute",
1169
- startUnixNano: rec.startUnixNano,
1170
- endUnixNano: rec.endUnixNano,
1171
- status: rec.status,
1172
- attributes: {
1173
- op: rec.kind,
1174
- hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
1175
- ...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
1176
- ...rec.reach !== void 0 ? { reach: rec.reach } : {},
1177
- ...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
1178
- ...rec.rows !== void 0 ? { rows: rec.rows } : {}
1318
+ var nothingKeptUnder = (ref) => `nothing is kept under "${ref}". A saved layout takes the place of the layout of an action its holder has, under "action/<the action\u2019s id>", or of one the app\u2019s own shell declares: its own under "frame", a canvas\u2019s under "canvas/<the canvas\u2019s id>".`;
1319
+ var targetAt = (ref, heldTo) => {
1320
+ if (heldTo.ownShell?.refs.has(ref) === true) return { kit: heldTo.ownShell.kit };
1321
+ const action = heldTo.actionAt(ref);
1322
+ return action === void 0 ? void 0 : { kit: heldTo.kit, action };
1323
+ };
1324
+ var refOf = (body) => {
1325
+ const ref = reflect.isRecord(body) ? body["ref"] : void 0;
1326
+ return typeof ref === "string" ? ref : void 0;
1327
+ };
1328
+ var readLayout = (body, heldTo) => {
1329
+ if (strata.exceedsDepth(body)) return { refusal: strata.depthRefusal() };
1330
+ const parsed = SavedLayoutSchema.safeParse(body);
1331
+ if (!parsed.success) {
1332
+ const first = parsed.error.issues[0];
1333
+ return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1179
1334
  }
1180
- });
1181
- var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
1182
- var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
1183
- var createOwnEntries = (deps) => async (own) => {
1184
- const cache = vex.createMemoryCache();
1185
- await vex.seedCache(cache, own.entries);
1186
- const schema = await deps.adapter.introspect({ entities: [...own.tables] });
1187
- const engine = vex.createQueryEngine({
1188
- adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
1189
- cache
1190
- });
1191
- await engine.introspect();
1192
- const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, { public: true }])) };
1193
- const reachable = new Set((await vex.handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed) => listed.fingerprint));
1194
- const outside = own.entries.map((entry2) => entry2.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
1195
- if (outside.length > 0) {
1196
- throw new Error(
1197
- `moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
1198
- );
1335
+ const { ref, layout } = parsed.data;
1336
+ const target = targetAt(ref, heldTo);
1337
+ if (target === void 0) return { refusal: nothingKeptUnder(ref) };
1338
+ const misfits = chunk3DCTQKPQ_cjs.layoutMisfits(layout, target.kit);
1339
+ if (misfits.length > 0) return { refusal: misfits.join("; ") };
1340
+ const named = chunk3DCTQKPQ_cjs.layoutNameRefusal(layout);
1341
+ if (named !== void 0) return { refusal: `it ${named}` };
1342
+ const { action } = target;
1343
+ if (action === void 0) return { layout: parsed.data };
1344
+ const found = new Set(nova.auditAction(action).issues);
1345
+ const added = nova.auditAction({ ...action, layout }).issues.filter((issue) => !found.has(issue));
1346
+ if (added.length > 0) return { refusal: added.join("; ") };
1347
+ return { layout: parsed.data };
1348
+ };
1349
+ var loaded = (version, { whose, heldTo, say }) => {
1350
+ const ref = refOf(version.body);
1351
+ if (ref === void 0 || targetAt(ref, heldTo) === void 0) return void 0;
1352
+ const read2 = version.unread !== void 0 ? { refusal: version.unread } : readLayout(version.body, heldTo);
1353
+ if ("layout" in read2) return read2.layout;
1354
+ (say ?? console.error)(`[moss] the layout "${version.id}" ${whose} is left out: ${read2.refusal}`);
1355
+ return void 0;
1356
+ };
1357
+ var isInUse = (version) => version.kind === "layout" && reflect.isRecord(version.body) && version.body["use"] === true;
1358
+ var isLater = (one, other) => one.createdAt === other.createdAt ? one.save > other.save : one.createdAt > other.createdAt;
1359
+ var layoutsInUse = (inForce2, drawnFor) => {
1360
+ const marked = /* @__PURE__ */ new Map();
1361
+ for (const version of inForce2.filter(isInUse)) {
1362
+ const ref = refOf(version.body);
1363
+ if (ref === void 0) continue;
1364
+ const held = marked.get(ref);
1365
+ if (held === void 0 || isLater(version, held)) marked.set(ref, version);
1199
1366
  }
1200
- return async (fingerprint, context) => {
1201
- const outcome = await vex.handleQuery(
1202
- {
1203
- engine,
1204
- locked: true,
1205
- scopePolicy: policy,
1206
- mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(vex.tablesChangedBy(event.writes, schema)) },
1207
- ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
1208
- },
1209
- { fingerprint, context },
1210
- {}
1211
- );
1212
- if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
1213
- return resultOf(outcome.body);
1367
+ const layouts = {};
1368
+ for (const version of marked.values()) {
1369
+ const read2 = loaded(version, drawnFor);
1370
+ if (read2 !== void 0) layouts[read2.ref] = read2.layout;
1371
+ }
1372
+ return layouts;
1373
+ };
1374
+ var generatedId = () => `${chunk3DCTQKPQ_cjs.GENERATED_ID_PREFIX}${crypto$1.randomUUID()}`;
1375
+ var VEX_ROUTE = /^\/api\/(?:[A-Za-z0-9_-]+\/)?vex$/;
1376
+ var endpointRefusals = async (endpoints, heldTo) => {
1377
+ const refusals = [];
1378
+ for (const [name, endpoint] of Object.entries(endpoints ?? {})) {
1379
+ if ("fn" in endpoint) {
1380
+ if (endpoint.fn.includes("{{")) refusals.push(`endpoint "${name}" names a function that is worked out when it is called, and what is generated names one written out`);
1381
+ else if (!heldTo.mayCall(endpoint.fn)) refusals.push(`endpoint "${name}" calls the function "${endpoint.fn}", which its owner\u2019s roles do not grant`);
1382
+ continue;
1383
+ }
1384
+ if (endpoint.method !== "POST" || !VEX_ROUTE.test(endpoint.url)) {
1385
+ refusals.push(`endpoint "${name}" calls "${endpoint.method} ${endpoint.url}", and what is generated calls only the app\u2019s vex route, with POST`);
1386
+ continue;
1387
+ }
1388
+ const fingerprint = reflect.isRecord(endpoint.request) ? endpoint.request["fingerprint"] : void 0;
1389
+ if (typeof fingerprint !== "string") {
1390
+ refusals.push(`endpoint "${name}" names no fingerprint`);
1391
+ continue;
1392
+ }
1393
+ const entry = heldTo.entryOf(fingerprint);
1394
+ if (entry === void 0) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is no entry the app ships or was handed, nor a read its owner saved`);
1395
+ else if ("mutation" in entry) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is a write, and what is generated only reads`);
1396
+ else if (!(await heldTo.replayable()).has(fingerprint)) refusals.push(`endpoint "${name}" replays "${fingerprint}", which its owner may not replay`);
1397
+ }
1398
+ return refusals;
1399
+ };
1400
+ var parsedUnder = (schema, body, id, more = {}) => {
1401
+ if (strata.exceedsDepth(body)) return { refusal: strata.depthRefusal() };
1402
+ if (reflect.isRecord(body) && body["id"] !== void 0 && body["id"] !== id) {
1403
+ return { refusal: `it names the id "${String(body["id"])}", and is kept under "${id}": leave the id out of the body.` };
1404
+ }
1405
+ const parsed = schema.safeParse(reflect.isRecord(body) ? { ...more, ...body, id } : body);
1406
+ if (parsed.success) return { body: parsed.data };
1407
+ const first = parsed.error.issues[0];
1408
+ return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1409
+ };
1410
+ var layoutRefusals = (layout, kit) => {
1411
+ const named = chunk3DCTQKPQ_cjs.layoutNameRefusal(layout);
1412
+ return [...layout === void 0 || typeof layout === "string" ? [] : chunk3DCTQKPQ_cjs.layoutMisfits(layout, kit), ...named === void 0 ? [] : [`it ${named}`]];
1413
+ };
1414
+ var passedOrRefused = (body, refusals) => refusals.length > 0 ? { refusal: refusals.join("; ") } : { body };
1415
+ var readAction = async (body, id, heldTo) => {
1416
+ const parsed = parsedUnder(nova.ActionDefinitionSchema, body, id);
1417
+ if ("refusal" in parsed) return parsed;
1418
+ const action = parsed.body;
1419
+ return passedOrRefused(action, [
1420
+ ...layoutRefusals(action.layout, heldTo.kit),
1421
+ ...await endpointRefusals(action.endpoints, heldTo),
1422
+ ...nova.auditAction(action, { catalog: heldTo.catalog() }).issues
1423
+ ]);
1424
+ };
1425
+ var readFragment = async (body, id, heldTo) => {
1426
+ const parsed = parsedUnder(nova.ActionFragmentSchema, body, id, { kind: "fragment" });
1427
+ if ("refusal" in parsed) return parsed;
1428
+ const fragment = parsed.body;
1429
+ return passedOrRefused(fragment, [...layoutRefusals(fragment.layout, heldTo.kit), ...await endpointRefusals(fragment.endpoints, heldTo)]);
1430
+ };
1431
+ var generatedIn = (inForce2, kind) => inForce2.filter((version) => version.kind === kind && version.body !== null);
1432
+ var catalogOfGenerated = (inForce2) => generatedIn(inForce2, "action").map((version) => ({ id: version.id, input: reflect.isRecord(version.body) && reflect.isRecord(version.body["input"]) ? version.body["input"] : {} }));
1433
+ var generatedInForce = async (inForce2, heldTo, whose) => {
1434
+ const passed = async (kind, read2) => {
1435
+ const kept = {};
1436
+ for (const version of generatedIn(inForce2, kind)) {
1437
+ const answered = version.unread !== void 0 ? { refusal: version.unread } : await read2(version.body, version.id, heldTo);
1438
+ if ("body" in answered) kept[version.id] = answered.body;
1439
+ else if (whose !== void 0) console.error(`[moss] the ${kind} "${version.id}" ${whose} is left out: ${answered.refusal}`);
1440
+ }
1441
+ return kept;
1442
+ };
1443
+ return { actions: await passed("action", readAction), fragments: await passed("fragment", readFragment) };
1444
+ };
1445
+ var compileEntries = async (entries) => {
1446
+ const compiled = vex.createMemoryCache();
1447
+ await vex.seedCache(compiled, entries);
1448
+ return new Map((await compiled.entries?.() ?? []).map(({ key, entry }) => [key, entry]));
1449
+ };
1450
+ var mergedEntries = (own, sets) => {
1451
+ const byFingerprint = /* @__PURE__ */ new Map();
1452
+ for (const entry of [...own, ...[...sets.values()].flat()]) byFingerprint.set(entry.fingerprint, entry);
1453
+ return Object.freeze([...byFingerprint.values()]);
1454
+ };
1455
+ var createEntriesInForce = (own) => {
1456
+ let sets = /* @__PURE__ */ new Map();
1457
+ let list = mergedEntries(own, sets);
1458
+ let byFingerprint = new Map(list.map((entry) => [entry.fingerprint, entry]));
1459
+ let ownCompiled;
1460
+ let setsCompiled = /* @__PURE__ */ new Map();
1461
+ let compiled;
1462
+ return {
1463
+ list: () => list,
1464
+ byFingerprint: () => byFingerprint,
1465
+ holdsSet: (source) => sets.has(source),
1466
+ withSet: (source, handed) => mergedEntries(own, new Map([...sets, [source, handed]])),
1467
+ takeSet: (source, handed, taken) => {
1468
+ sets = new Map([...sets, [source, handed]]);
1469
+ list = mergedEntries(own, sets);
1470
+ byFingerprint = new Map(list.map((entry) => [entry.fingerprint, entry]));
1471
+ setsCompiled = new Map([...setsCompiled, [source, taken]]);
1472
+ compiled = void 0;
1473
+ },
1474
+ compiled: () => {
1475
+ compiled ??= (async () => {
1476
+ ownCompiled ??= compileEntries(own);
1477
+ return new Map([...await ownCompiled, ...[...setsCompiled.values()].flatMap((set) => [...set])]);
1478
+ })();
1479
+ return compiled;
1480
+ }
1214
1481
  };
1215
1482
  };
1216
- var TABLE = "moss_generation";
1217
- var THE_ROW = { eq: [`${TABLE}.id`, 1] };
1218
- var readPointerEntry = {
1219
- fingerprint: "moss/generation",
1220
- intent: "Where the generation pointer is",
1221
- dsl: { from: [TABLE], fields: [`${TABLE}.n`], filter: THE_ROW, limit: 1 }
1483
+
1484
+ // src/artifactory/reads.ts
1485
+ var SavedReadSchema = migrations.VEX_SCHEMAS["nisc.vex/entry"];
1486
+ var sentenceOf = (error) => error instanceof Error ? error.message : String(error);
1487
+ var seedOf = (fingerprint, read2) => ({ fingerprint, ...read2 });
1488
+ var compiledRead = async (fingerprint, read2) => {
1489
+ const compiled = (await compileEntries([seedOf(fingerprint, read2)])).get(fingerprint);
1490
+ if (compiled === void 0) return void 0;
1491
+ const { protected: _shipped, ...entry } = compiled;
1492
+ return entry;
1493
+ };
1494
+ var shippedRefusal = (fingerprint) => `"${fingerprint}" is the fingerprint of an entry the app ships or was handed, and a read somebody generated never answers in its place`;
1495
+ var readSaved = async (body, fingerprint, heldTo) => {
1496
+ if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1497
+ if (strata.exceedsDepth(body)) return { refusal: strata.depthRefusal() };
1498
+ const parsed = SavedReadSchema.safeParse(body);
1499
+ if (!parsed.success) {
1500
+ const first = parsed.error.issues[0];
1501
+ return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1502
+ }
1503
+ try {
1504
+ heldTo.sources.compile(parsed.data.dsl);
1505
+ await compiledRead(fingerprint, parsed.data);
1506
+ } catch (error) {
1507
+ return { refusal: sentenceOf(error) };
1508
+ }
1509
+ return { body: parsed.data };
1510
+ };
1511
+ var readWritten = async (fingerprint, heldTo) => {
1512
+ if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1513
+ const entry = await heldTo.sources.written(fingerprint);
1514
+ if (entry === void 0 || entry.requestHash === void 0) return { refusal: `vex holds no query it wrote under "${fingerprint}"` };
1515
+ if (entry.kind !== "ok") return { refusal: `vex found no query to answer under "${fingerprint}"` };
1516
+ if (entry.shape !== void 0 && entry.mapping === void 0) {
1517
+ return { refusal: `vex kept no prism config for the mapping of "${fingerprint}": it was written before vex kept one. Ask for it again.` };
1518
+ }
1519
+ return readSaved(
1520
+ {
1521
+ dsl: entry.dsl,
1522
+ ...entry.mapping !== void 0 ? { mapping: entry.mapping } : {},
1523
+ ...entry.shape !== void 0 ? { shape: entry.shape } : {},
1524
+ ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1525
+ ...entry.reach !== void 0 ? { reach: entry.reach } : {},
1526
+ ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {}
1527
+ },
1528
+ fingerprint,
1529
+ heldTo
1530
+ );
1222
1531
  };
1223
- var movePointerEntry = {
1224
- fingerprint: "moss/generation-move",
1225
- intent: "Move the generation pointer to the next number, if it is still where it was read",
1226
- mutation: {
1227
- op: "update",
1228
- table: TABLE,
1229
- set: { n: { $context: "next" } },
1230
- where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
1532
+ var answeredRead = async (fingerprint, body) => {
1533
+ if (strata.exceedsDepth(body)) return void 0;
1534
+ const parsed = SavedReadSchema.safeParse(body);
1535
+ return parsed.success ? compiledRead(fingerprint, parsed.data) : void 0;
1536
+ };
1537
+ var readsInForce = async (inForce2, heldTo, whose) => {
1538
+ const reads = /* @__PURE__ */ new Map();
1539
+ for (const version of inForce2) {
1540
+ if (version.kind !== "read" || version.body === null) continue;
1541
+ const read2 = version.unread !== void 0 ? { refusal: version.unread } : await readSaved(version.body, version.id, heldTo);
1542
+ if ("body" in read2) reads.set(version.id, read2.body);
1543
+ else if (whose !== void 0) console.error(`[moss] the read "${version.id}" ${whose} is left out: ${read2.refusal}`);
1231
1544
  }
1545
+ return reads;
1232
1546
  };
1233
- var POINTER = { owner: "the generation pointer", entries: [readPointerEntry, movePointerEntry], tables: [TABLE] };
1234
- var RowSchema = zod.z.object({ n: zod.z.coerce.number() });
1235
- var RowsSchema = zod.z.array(zod.z.unknown());
1236
- var createPointer = (replay) => ({
1237
- read: async () => {
1238
- const rows = RowsSchema.parse(await (await replay())(readPointerEntry.fingerprint, {}));
1239
- return RowSchema.parse(rows[0] ?? { n: 0 }).n;
1240
- },
1241
- // A write that changed one row answers that row; one that changed none
1242
- // answers no row, which does not parse: the counter moved since it was read.
1243
- move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
1547
+
1548
+ // src/artifactory/session.ts
1549
+ var SaveIdSchema = zod.z.uuid();
1550
+ var ToSaveSchema = zod.z.array(zod.z.strictObject({ kind: zod.z.string(), id: zod.z.string().optional(), body: zod.z.unknown() })).min(1);
1551
+ var NEW_ID = {
1552
+ layout: crypto$1.randomUUID,
1553
+ action: generatedId,
1554
+ fragment: generatedId,
1555
+ read: () => {
1556
+ throw new Error("moss: a read is saved under the fingerprint vex gave it: name it as the id.");
1557
+ }
1558
+ };
1559
+ var listed = (version, kind) => ({
1560
+ kind,
1561
+ id: version.id,
1562
+ save: version.save,
1563
+ createdAt: version.createdAt,
1564
+ copiedFrom: version.copiedFrom,
1565
+ body: version.body
1244
1566
  });
1245
- var resolvePolicyForRoles = (app, grants, roles) => {
1246
- const behaviors = app.behaviors ?? {};
1247
- return vex.mergeScopePolicies(
1248
- roles.map(
1249
- (role) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, [role], "data"), behaviors, charter.resolveScoping(app.charter, role))
1250
- )
1251
- );
1567
+ var withoutMark = ({ use: _mark, ...layout }) => layout;
1568
+ var checked = async (kind, id, body, heldTo) => {
1569
+ if (kind === "layout") {
1570
+ const read3 = readLayout(body, heldTo.layouts);
1571
+ if ("refusal" in read3) throw new Error(`moss: the layout for "${refOf(body) ?? "(no ref)"}" is refused: ${read3.refusal}`);
1572
+ return read3.layout;
1573
+ }
1574
+ if (kind === "read") {
1575
+ const read3 = heldTo.reads === void 0 ? { refusal: "no read is saved here" } : body === void 0 ? await readWritten(id, heldTo.reads) : await readSaved(body, id, heldTo.reads);
1576
+ if ("refusal" in read3) throw new Error(`moss: the read "${id}" is refused: ${read3.refusal}`);
1577
+ return read3.body;
1578
+ }
1579
+ const read2 = await (kind === "action" ? readAction : readFragment)(body, id, heldTo.generated);
1580
+ if ("refusal" in read2) throw new Error(`moss: the ${kind} is refused: ${read2.refusal}`);
1581
+ return read2.body;
1582
+ };
1583
+ var markedRefs = (versions) => {
1584
+ const marked = versions.flatMap((version) => {
1585
+ const ref = refOf(version.body);
1586
+ return version.kind === "layout" && reflect.isRecord(version.body) && version.body["use"] === true && ref !== void 0 ? [ref] : [];
1587
+ });
1588
+ const twice = marked.find((ref, at) => marked.indexOf(ref) !== at);
1589
+ if (twice !== void 0) throw new Error(`moss: two layouts of one save are marked in use for "${twice}". One is in use at a time.`);
1590
+ return marked;
1591
+ };
1592
+ var unmarked = (versions, inForce2) => {
1593
+ const layouts = versions.filter((version) => version.kind === "layout");
1594
+ const marked = markedRefs(layouts);
1595
+ const saved = new Set(layouts.map((version) => version.id));
1596
+ const takenOut = inForce2.flatMap((held) => isInUse(held) && saved.has(held.id) ? [refOf(held.body)] : []);
1597
+ const decided = /* @__PURE__ */ new Set([...marked, ...takenOut]);
1598
+ return inForce2.flatMap((held) => {
1599
+ const ref = refOf(held.body);
1600
+ if (!isInUse(held) || held.unread !== void 0 || !reflect.isRecord(held.body) || ref === void 0 || !decided.has(ref) || saved.has(held.id)) return [];
1601
+ return [{ kind: "layout", id: held.id, body: withoutMark(held.body), copiedFrom: held.save }];
1602
+ });
1252
1603
  };
1253
- var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
1254
- var createPolicies = (config) => {
1255
- const { grants } = config;
1256
- const governed = { charter: config.charter, behaviors: config.behaviors };
1257
- const policies = /* @__PURE__ */ new Map();
1258
- const reachPolicies = /* @__PURE__ */ new Map();
1604
+ var idsOf = (versions) => versions.map(({ kind, id }) => ({ kind, id }));
1605
+ var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1606
+ const requireHolder = () => {
1607
+ if (holder === void 0) throw new Error(nobody);
1608
+ return holder;
1609
+ };
1610
+ const ofKind = (kind) => {
1611
+ const known = kinds.find((one) => one === kind);
1612
+ if (known === void 0) throw new Error(`moss: "${String(kind)}" is not a kind that is saved. The kinds: ${kinds.join(", ")}.`);
1613
+ return known;
1614
+ };
1615
+ const askedOf = (artifacts) => {
1616
+ const asked = ToSaveSchema.safeParse(artifacts);
1617
+ if (!asked.success) throw new Error("moss: a save holds one or several artifacts, each `{ kind, id?, body }` and nothing else.");
1618
+ return asked.data.map((artifact) => ({ ...artifact, kind: ofKind(artifact.kind) }));
1619
+ };
1620
+ const checkedEach = async (asked, inForce2, held) => {
1621
+ const versions = [];
1622
+ for (const { kind, id: named2, body } of asked) {
1623
+ if (defaults !== void 0 && named2 === void 0 && kind !== "layout" && kind !== "read") throw new Error(`moss: a published ${kind} is given its id by whoever publishes it: name it.`);
1624
+ const id = named2 ?? NEW_ID[kind]();
1625
+ if (kind === "read" && body !== void 0) throw new Error(`moss: the read "${id}" is refused: it is what vex wrote for the request. Leave the body out.`);
1626
+ versions.push({ kind, id, body: await checked(kind, id, body, held), copiedFrom: null });
1627
+ }
1628
+ const named = (kind) => kind !== "read" && (defaults === void 0 || kind === "layout");
1629
+ const notTheirs = asked.find(({ kind, id }) => id !== void 0 && named(kind) && !inForce2.some((version) => version.kind === kind && version.id === id));
1630
+ if (notTheirs !== void 0) {
1631
+ throw new Error(`moss: there is no ${notTheirs.kind} "${notTheirs.id}" ${whose}. Leave the id out, and moss gives a new ${notTheirs.kind} its id.`);
1632
+ }
1633
+ const twice = versions.find((version, at) => versions.findIndex((other) => other.kind === version.kind && other.id === version.id) !== at);
1634
+ if (twice !== void 0) throw new Error(`moss: the ${twice.kind} "${twice.id}" is in one save twice.`);
1635
+ return versions;
1636
+ };
1637
+ const write = async (saved, versions, inForce2) => {
1638
+ const save2 = crypto$1.randomUUID();
1639
+ await saved.write({ id: save2, versions: [...versions, ...unmarked(versions, inForce2)] });
1640
+ written();
1641
+ return save2;
1642
+ };
1643
+ return { requireHolder, ofKind, askedOf, checkedEach, write };
1644
+ };
1645
+ var savedArtifacts = (deps) => {
1646
+ const { holder, whose, kinds, defaults } = deps;
1647
+ const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
1259
1648
  return {
1260
- of: (who) => {
1261
- const hit = policies.get(who.memoKey);
1262
- if (hit !== void 0) return hit;
1263
- const compiled = resolvePolicyForRoles(governed, grants, who.roles);
1264
- policies.set(who.memoKey, compiled);
1265
- return compiled;
1649
+ save: async (artifacts) => {
1650
+ const holderOf = requireHolder();
1651
+ const asked = askedOf(artifacts);
1652
+ const { saved, heldTo } = await holderOf();
1653
+ const inForce2 = await saved.inForce();
1654
+ const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1655
+ await defaults?.verify(versions, inForce2);
1656
+ return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1266
1657
  },
1267
- atReach: (who, reach) => {
1268
- const key = `${who.memoKey}\0${reach}`;
1269
- const hit = reachPolicies.get(key);
1270
- if (hit !== void 0) return hit;
1271
- const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
1272
- reachPolicies.set(key, compiled);
1273
- return compiled;
1658
+ list: async (kind) => {
1659
+ const only = kind === void 0 ? void 0 : ofKind(kind);
1660
+ if (holder === void 0) return [];
1661
+ const inForce2 = await (await holder()).saved.inForce();
1662
+ return inForce2.flatMap((version) => {
1663
+ const known = kinds.find((one) => one === version.kind);
1664
+ return version.body !== null && known !== void 0 && (only === void 0 || known === only) ? [listed(version, known)] : [];
1665
+ });
1666
+ },
1667
+ history: async (kind, id) => {
1668
+ const known = ofKind(kind);
1669
+ if (holder === void 0) return [];
1670
+ return (await (await holder()).saved.history(known, id)).map((version) => listed(version, known));
1671
+ },
1672
+ restore: async (kind, id, save2) => {
1673
+ const holderOf = requireHolder();
1674
+ const known = ofKind(kind);
1675
+ const { saved, heldTo } = await holderOf();
1676
+ const version = SaveIdSchema.safeParse(save2).success ? (await saved.history(known, id, save2))[0] : void 0;
1677
+ if (version === void 0) throw new Error(`moss: no ${known} "${id}" ${whose} was saved in "${save2}".`);
1678
+ if (version.unread !== void 0) throw new Error(`moss: the ${known} "${id}" saved in "${save2}" cannot be read: ${version.unread}`);
1679
+ const inForce2 = await saved.inForce();
1680
+ const body = version.body === null ? null : await checked(known, id, version.body, await heldTo(inForce2));
1681
+ const restored = { kind: known, id, body, copiedFrom: version.save };
1682
+ await defaults?.verify([restored], inForce2);
1683
+ return { save: await write(saved, [restored], inForce2) };
1684
+ },
1685
+ reset: async (kind, id) => {
1686
+ const holderOf = requireHolder();
1687
+ const known = ofKind(kind);
1688
+ const { saved } = await holderOf();
1689
+ const inForce2 = await saved.inForce();
1690
+ if (!inForce2.some((version) => version.kind === known && version.id === id && version.body !== null)) throw new Error(`moss: no ${known} "${id}" ${whose} is in force.`);
1691
+ return { save: await write(saved, [{ kind: known, id, body: null, copiedFrom: null }], inForce2) };
1692
+ }
1693
+ };
1694
+ };
1695
+
1696
+ // src/artifactory/draft.ts
1697
+ var LATER_THAN_ANY_SAVE = "9999-12-31T23:59:59.999Z";
1698
+ var laidOver = (inForce2, drafted = []) => drafted.length === 0 ? inForce2 : [
1699
+ ...inForce2.filter((version) => !drafted.some((one) => one.kind === version.kind && one.id === version.id)),
1700
+ ...drafted.map((one) => ({ ...one, save: "draft", copiedFrom: null, createdAt: LATER_THAN_ANY_SAVE }))
1701
+ ];
1702
+ var draftSaving = (deps) => {
1703
+ const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a draft is somebody\u2019s to save.");
1704
+ return {
1705
+ // The draft with these added to it. Each is checked beside what is in force for its holder with the draft laid over.
1706
+ add: async (artifacts, drafted) => {
1707
+ const holderOf = requireHolder();
1708
+ const asked = askedOf(artifacts);
1709
+ const { saved, heldTo } = await holderOf();
1710
+ const inForce2 = laidOver(await saved.inForce(), drafted);
1711
+ const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1712
+ const added = versions.map(({ kind, id, body }) => ({ kind, id, body }));
1713
+ const marked = new Set(markedRefs(added));
1714
+ const kept = drafted.flatMap((one) => {
1715
+ if (added.some((other) => other.kind === one.kind && other.id === one.id)) return [];
1716
+ const ref = refOf(one.body);
1717
+ const loses = one.kind === "layout" && reflect.isRecord(one.body) && one.body["use"] === true && ref !== void 0 && marked.has(ref);
1718
+ return [loses && reflect.isRecord(one.body) ? { ...one, body: withoutMark(one.body) } : one];
1719
+ });
1720
+ return { drafted: [...kept, ...added], added: idsOf(versions) };
1721
+ },
1722
+ save: async (drafted) => {
1723
+ const holderOf = requireHolder();
1724
+ if (drafted.length === 0) throw new Error("moss: the draft holds nothing to save.");
1725
+ const { saved, heldTo } = await holderOf();
1726
+ const inForce2 = await saved.inForce();
1727
+ const held = await heldTo(laidOver(inForce2, drafted));
1728
+ const versions = [];
1729
+ for (const one of drafted) {
1730
+ const kind = ofKind(one.kind);
1731
+ versions.push({ kind, id: one.id, body: await checked(kind, one.id, one.body, held), copiedFrom: null });
1732
+ }
1733
+ return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1734
+ }
1735
+ };
1736
+ };
1737
+
1738
+ // src/artifactory/generation.ts
1739
+ var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
1740
+ var MAX_INTERVAL_MS = 2 ** 31 - 1;
1741
+ var MOVE_ATTEMPTS = 5;
1742
+ var createGeneration = (pointer, ctx) => {
1743
+ const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
1744
+ let seen = -1;
1745
+ let checking = false;
1746
+ const poll = async () => {
1747
+ if (checking) return;
1748
+ checking = true;
1749
+ try {
1750
+ const n = await readPointer();
1751
+ if (n === void 0 || n === seen) return;
1752
+ if (seen !== -1 && !await follow(n)) return;
1753
+ seen = n;
1754
+ } finally {
1755
+ checking = false;
1756
+ }
1757
+ };
1758
+ const readPointer = async () => {
1759
+ try {
1760
+ return await pointer.read();
1761
+ } catch (err) {
1762
+ console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
1763
+ return void 0;
1764
+ }
1765
+ };
1766
+ let unfollowed;
1767
+ const follow = async (n) => {
1768
+ try {
1769
+ await ctx.onMoved();
1770
+ } catch (err) {
1771
+ const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
1772
+ if (unfollowed?.said !== what) {
1773
+ console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
1774
+ }
1775
+ unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
1776
+ return false;
1777
+ }
1778
+ if (unfollowed !== void 0) {
1779
+ console.log(
1780
+ `[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
1781
+ );
1782
+ unfollowed = void 0;
1783
+ }
1784
+ return true;
1785
+ };
1786
+ const move = async () => {
1787
+ for (let attempt = 0; attempt < MOVE_ATTEMPTS; attempt += 1) {
1788
+ const n = await pointer.read();
1789
+ if (await pointer.move(n)) {
1790
+ if (seen === n || seen === -1) seen = n + 1;
1791
+ return;
1792
+ }
1793
+ }
1794
+ throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
1795
+ };
1796
+ void poll();
1797
+ const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
1798
+ timer?.unref?.();
1799
+ return {
1800
+ bump: () => {
1801
+ void move().catch((err) => console.error("[moss:generation] could not move the pointer", err));
1802
+ },
1803
+ current: () => seen,
1804
+ stop: () => {
1805
+ if (timer !== void 0) clearInterval(timer);
1806
+ }
1807
+ };
1808
+ };
1809
+
1810
+ // src/artifactory/published.ts
1811
+ var NO_DEFAULTS = { actions: {}, fragments: {}, reads: /* @__PURE__ */ new Map() };
1812
+ var drawableIn = (fragments, kit, say) => Object.fromEntries(
1813
+ Object.entries(fragments).filter(([id, fragment]) => {
1814
+ const misfits = chunk3DCTQKPQ_cjs.layoutMisfits(fragment.layout, kit);
1815
+ if (misfits.length > 0) say(`[moss] the fragment "${id}" published for everybody is left out of a shell that cannot draw it: ${misfits.join("; ")}`);
1816
+ return misfits.length === 0;
1817
+ })
1818
+ );
1819
+ var createPublishedMemo = () => {
1820
+ let read2;
1821
+ let said = /* @__PURE__ */ new Set();
1822
+ return {
1823
+ held: () => read2,
1824
+ keep: (promise) => {
1825
+ read2 = promise;
1274
1826
  },
1275
1827
  drop: () => {
1276
- policies.clear();
1277
- reachPolicies.clear();
1828
+ read2 = void 0;
1829
+ said = /* @__PURE__ */ new Set();
1830
+ },
1831
+ sayOnce: (line) => {
1832
+ if (said.has(line)) return;
1833
+ said.add(line);
1834
+ console.error(line);
1278
1835
  }
1279
1836
  };
1280
1837
  };
1281
- var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) => {
1282
- const roles = [role];
1283
- const policy = deps.policyFor(roles);
1284
- const outcome = await vex.handleQuery(
1285
- {
1286
- engine: deps.engine,
1287
- locked: true,
1288
- scopePolicy: policy,
1289
- policyForReach: (reach) => deps.policyAtReach(roles, reach),
1290
- mutations: { client: deps.db, policy },
1291
- ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
1838
+ var hasDefaults = (defaults) => Object.keys(defaults.actions).length > 0 || Object.keys(defaults.fragments).length > 0 || defaults.reads.size > 0;
1839
+ var checkedDefaults = async (versions, heldTo, whose) => {
1840
+ const reads = heldTo.reads === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, heldTo.reads, whose);
1841
+ const checks = {
1842
+ kit: heldTo.kit,
1843
+ entryOf: (fingerprint) => {
1844
+ const read2 = reads.get(fingerprint);
1845
+ return heldTo.entryOf(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
1292
1846
  },
1293
- { fingerprint, context },
1294
- scope
1295
- );
1296
- if (outcome.status !== 200) {
1297
- console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
1298
- return void 0;
1847
+ replayable: async () => /* @__PURE__ */ new Set([...heldTo.fingerprints(), ...reads.keys()]),
1848
+ mayCall: () => true,
1849
+ catalog: () => [...Object.values(heldTo.built).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1850
+ };
1851
+ const passed = await generatedInForce(versions, checks, whose);
1852
+ return { passed, reads, verified: chunk3DCTQKPQ_cjs.verifyManifest(heldTo.candidate({ ...heldTo.built, ...passed.actions }, passed.fragments)) };
1853
+ };
1854
+ var narrowedBy = (filter, ids, installed) => {
1855
+ const answered = new Set(filter(ids, installed));
1856
+ return ids.filter((id) => answered.has(id));
1857
+ };
1858
+ var catalogFor = (app, roles, installed, installedOnly) => {
1859
+ const granted = [...charter.resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
1860
+ const ids = [...installedOnly(granted, installed === void 0 ? void 0 : new Set(installed))];
1861
+ return { ids, hash: versionToken(ids) };
1862
+ };
1863
+ var resolveVariantsForRoles = (app, roles) => {
1864
+ const variants = app.layouts ?? {};
1865
+ return chunk3DCTQKPQ_cjs.variantLayouts(variants, charter.resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
1866
+ };
1867
+ var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(chunk3DCTQKPQ_cjs.withVariants(actions, ids, variants)));
1868
+ var actionsWithStoredLayouts = (definitions) => {
1869
+ const actions = {};
1870
+ const layouts = {};
1871
+ for (const [id, definition] of Object.entries(definitions)) {
1872
+ const layout = definition.layout;
1873
+ if (layout === void 0 || typeof layout === "string") {
1874
+ actions[id] = definition;
1875
+ continue;
1876
+ }
1877
+ const ref = chunk3DCTQKPQ_cjs.actionLayoutRef(id);
1878
+ layouts[ref] = layout;
1879
+ actions[id] = { ...definition, layout: { ref } };
1880
+ }
1881
+ return { actions: Object.freeze(actions), layouts: Object.freeze(layouts) };
1882
+ };
1883
+ var createRoleMemo = (config) => {
1884
+ const catalogs = /* @__PURE__ */ new Map();
1885
+ const variants = /* @__PURE__ */ new Map();
1886
+ const stored = /* @__PURE__ */ new Map();
1887
+ const kept = (memo, key, resolve2) => {
1888
+ const hit = memo.get(key);
1889
+ if (hit !== void 0) return hit;
1890
+ const resolved = resolve2();
1891
+ memo.set(key, resolved);
1892
+ return resolved;
1893
+ };
1894
+ const roleMemo = {
1895
+ catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
1896
+ variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
1897
+ storedLayoutsFor: (roles, installed) => kept(
1898
+ stored,
1899
+ memoKey(roles, installed),
1900
+ () => actionsWithStoredLayouts(definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles)))
1901
+ ),
1902
+ drop: () => {
1903
+ catalogs.clear();
1904
+ variants.clear();
1905
+ stored.clear();
1906
+ }
1907
+ };
1908
+ return roleMemo;
1909
+ };
1910
+ var versionToken = (ids) => {
1911
+ const s = ids.join("\n");
1912
+ let h = 2166136261;
1913
+ for (let i = 0; i < s.length; i += 1) {
1914
+ h ^= s.charCodeAt(i);
1915
+ h = Math.imul(h, 16777619) >>> 0;
1299
1916
  }
1300
- const body = outcome.body;
1301
- return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
1917
+ return h.toString(16).padStart(8, "0");
1302
1918
  };
1303
- var CREDENTIALS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization"]);
1304
- var writeRequestOf = (header) => ({
1305
- header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
1306
- });
1307
- var SAID_NOTHING = { header: () => void 0 };
1308
- var createWriteNotifier = () => {
1309
- const requests = new async_hooks.AsyncLocalStorage();
1310
- const listeners = /* @__PURE__ */ new Set();
1919
+
1920
+ // src/artifactory/sets.ts
1921
+ var createSetOwners = () => {
1922
+ const owners = /* @__PURE__ */ new Map();
1923
+ const ownerRefusalOf = (source) => {
1924
+ const owner = owners.get(source);
1925
+ return owner === void 0 ? void 0 : `the set "${source}" is ${owner}'s, and only its owner replaces it. An app hands a set over under a name of its own.`;
1926
+ };
1311
1927
  return {
1312
- subscribe: (listener) => {
1313
- listeners.add(listener);
1314
- return () => {
1315
- listeners.delete(listener);
1316
- };
1928
+ ownerRefusalOf,
1929
+ claim: (source, owner, handedOver) => {
1930
+ const held = owners.get(source);
1931
+ if (held !== void 0) throw new Error(`moss: the set "${source}" is ${held}'s, and ${owner} claims it too. A set has one writer.`);
1932
+ if (handedOver) throw new Error(`moss: the set "${source}" was handed over by the app, and ${owner} claims it. A set has one writer.`);
1933
+ owners.set(source, owner);
1317
1934
  },
1318
- within: (request, run) => requests.run(request, run),
1319
- report: (event) => {
1320
- const request = requests.getStore() ?? SAID_NOTHING;
1321
- for (const listener of [...listeners]) {
1322
- try {
1323
- listener(event, request);
1324
- } catch (error) {
1325
- console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
1326
- }
1327
- }
1935
+ assertAppOwned: (source) => {
1936
+ const refusal = ownerRefusalOf(source);
1937
+ if (refusal !== void 0) throw new Error(`moss: ${refusal}`);
1938
+ return source;
1328
1939
  }
1329
1940
  };
1330
1941
  };
1331
- var createWireFollower = (callSignal) => {
1332
- const controller = new AbortController();
1333
- const end = () => {
1334
- controller.abort();
1335
- };
1336
- if (callSignal.aborted) end();
1337
- else callSignal.addEventListener("abort", end, { once: true });
1338
- const handlers = /* @__PURE__ */ new Set();
1339
- let missed;
1340
- const live = {
1341
- signal: controller.signal,
1342
- onChange: (response) => {
1343
- if (handlers.size === 0) {
1344
- missed = { body: response.result };
1345
- return;
1346
- }
1347
- for (const handler of [...handlers]) handler(response.result);
1942
+
1943
+ // src/artifactory/usage.ts
1944
+ var TOUCH_EVERY_MS = 36e5;
1945
+ var createUsage = (everyMs, now = Date.now) => {
1946
+ const stamped2 = /* @__PURE__ */ new Map();
1947
+ return {
1948
+ touch: (principal, versions, rows) => {
1949
+ const at = now();
1950
+ for (const [key, when] of stamped2) if (when <= at - everyMs) stamped2.delete(key);
1951
+ const due = versions.filter((version) => version.body !== null && !stamped2.has(`${principal}\0${version.kind}\0${version.id}`));
1952
+ if (due.length === 0) return;
1953
+ for (const version of due) stamped2.set(`${principal}\0${version.kind}\0${version.id}`, at);
1954
+ rows.touch(
1955
+ due.map((version) => ({ kind: version.kind, id: version.id })),
1956
+ new Date(at).toISOString()
1957
+ ).catch((error) => console.error(`[moss] the artifacts of ${principal} could not be stamped as used:`, error));
1348
1958
  }
1349
1959
  };
1350
- const onChange = (handler) => {
1351
- if (controller.signal.aborted) return () => {
1960
+ };
1961
+
1962
+ // src/artifactory/running.ts
1963
+ var mergedActions = (own, sets, over = {}) => Object.freeze([...sets.values(), over].reduce((all, set) => ({ ...all, ...set }), { ...own }));
1964
+ var tell = (listener, ...told) => {
1965
+ try {
1966
+ listener(...told);
1967
+ } catch (error) {
1968
+ console.error("[moss:manifest] a listener to a manifest change threw:", error);
1969
+ }
1970
+ };
1971
+ var createRunningManifest = (config) => {
1972
+ const { shipped } = config;
1973
+ const entries = createEntriesInForce(chunk3DCTQKPQ_cjs.entriesOf(shipped));
1974
+ let defaults = NO_DEFAULTS;
1975
+ const usage = createUsage(config.touchEveryMs ?? TOUCH_EVERY_MS);
1976
+ let functionIds;
1977
+ const candidate = (actions, held = entries.list(), fragments = defaults.fragments) => chunk3DCTQKPQ_cjs.withFragments({ ...chunk3DCTQKPQ_cjs.candidateOf(shipped, { actions, entries: held }, config.grants), ...functionIds === void 0 ? {} : { functionIds } }, fragments);
1978
+ const own = shipped.actions;
1979
+ const loaders = /* @__PURE__ */ new Map();
1980
+ const owners = createSetOwners();
1981
+ let sets = /* @__PURE__ */ new Map();
1982
+ let inForce2 = mergedActions(own, sets);
1983
+ let report = chunk3DCTQKPQ_cjs.verifiedAtBoot(candidate(inForce2));
1984
+ const components = createComponentNames((shell) => shellComponents({ actions: inForce2, layouts: shipped.layouts }, shell));
1985
+ const componentsOf2 = (shells) => {
1986
+ const kit = /* @__PURE__ */ new Map();
1987
+ for (const shell of shells) {
1988
+ for (const [name, contract] of Object.entries(components.of(shell))) kit.set(name, { propsSchema: contract.meta?.propsSchema ?? kit.get(name)?.propsSchema });
1989
+ }
1990
+ return kit;
1991
+ };
1992
+ let ofTheApp;
1993
+ const dropMemos = () => {
1994
+ roleMemo.drop();
1995
+ components.drop();
1996
+ ofTheApp = void 0;
1997
+ };
1998
+ const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
1999
+ const roleMemo = createRoleMemo({
2000
+ manifest: () => ({ charter: shipped.charter, actions: inForce2, layouts: shipped.layouts }),
2001
+ installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
2002
+ });
2003
+ const kitOf2 = (shell) => shell === void 0 ? ofTheApp ??= componentsOf2(config.shells) : componentsOf2([shell]);
2004
+ const ownShell = shipped.shell;
2005
+ const ownShellRefs = new Set(ownShell === void 0 ? [] : Object.keys(shellWithStoredLayouts(ownShell).layouts));
2006
+ const heldTo = ({ actions, layouts }, shell) => {
2007
+ const kit = kitOf2(shell);
2008
+ return {
2009
+ kit,
2010
+ // A layout saved for the frame or a canvas is the app's own shell's, whichever shell it is saved from.
2011
+ ...ownShell !== void 0 && (shell === void 0 || shell === ownShell) ? { ownShell: { refs: ownShellRefs, kit: shell === ownShell ? kit : kitOf2(ownShell) } } : {},
2012
+ actionAt: actionAtRef(actions, layouts)
1352
2013
  };
1353
- handlers.add(handler);
1354
- if (missed !== void 0) {
1355
- const { body } = missed;
1356
- missed = void 0;
1357
- handler(body);
2014
+ };
2015
+ const { reads: readSources } = config;
2016
+ const functionsWritten = (written) => {
2017
+ if (functionIds !== void 0) return;
2018
+ const ids = chunk3DCTQKPQ_cjs.functionsIn(written).map((definition) => definition.id);
2019
+ const charter = chunk3DCTQKPQ_cjs.charterOverFunctions(shipped.charter, { actions: Object.keys(inForce2), data: config.grants, layouts: Object.keys(shipped.layouts ?? {}) }, ids);
2020
+ if (charter.errors.length > 0) throw new Error(`Charter is incoherent over the app\u2019s functions \u2014 refusing to serve:
2021
+ ${charter.errors.join("\n ")}`);
2022
+ functionIds = new Set(ids);
2023
+ const built = mergedActions(own, sets);
2024
+ const verified = chunk3DCTQKPQ_cjs.verifyManifest(candidate(built, entries.list(), {}));
2025
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "boot");
2026
+ if (refusal !== void 0) {
2027
+ functionIds = void 0;
2028
+ throw new Error(refusal);
1358
2029
  }
1359
- return () => {
1360
- handlers.delete(handler);
1361
- if (handlers.size === 0) end();
2030
+ report = verified;
2031
+ defaults = NO_DEFAULTS;
2032
+ inForce2 = built;
2033
+ dropMemos();
2034
+ memo.drop();
2035
+ for (const warning2 of charter.warnings) console.warn(`[moss] charter: ${warning2}`);
2036
+ const warning = chunk3DCTQKPQ_cjs.functionsWarning(written);
2037
+ if (warning !== void 0) console.warn(warning);
2038
+ };
2039
+ const grantedFunctionsOf = (roles) => (names) => charter.resolvePrincipal(shipped.charter, names, roles, "functions");
2040
+ const readsHeldTo = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
2041
+ const heldWithGenerated = async (held, versions, who, shell, whose) => {
2042
+ let replayable;
2043
+ let catalog;
2044
+ const reads = new Map([...defaults.reads, ...readsHeldTo === void 0 ? [] : await readsInForce(versions, readsHeldTo, whose)]);
2045
+ const checks = {
2046
+ kit: kitOf2(shell),
2047
+ entryOf: (fingerprint) => {
2048
+ const read2 = reads.get(fingerprint);
2049
+ return entries.byFingerprint().get(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
2050
+ },
2051
+ replayable: () => replayable ??= (async () => /* @__PURE__ */ new Set([...await who.replayable?.() ?? [], ...reads.keys()]))(),
2052
+ mayCall: (name) => who.roles !== void 0 && charter.resolvePrincipal(shipped.charter, [name], who.roles, "functions").has(name),
2053
+ catalog: () => catalog ??= [...Object.values(held.actions).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1362
2054
  };
2055
+ const passed = await generatedInForce(versions, checks, whose);
2056
+ const stored = actionsWithStoredLayouts(passed.actions);
2057
+ const all = Object.keys(passed.actions).length === 0 ? held : { actions: { ...held.actions, ...stored.actions }, layouts: { ...held.layouts, ...stored.layouts } };
2058
+ return { all, fragments: passed.fragments, heldTo: { layouts: heldTo(all, shell), generated: checks, ...readsHeldTo !== void 0 ? { reads: readsHeldTo } : {} } };
1363
2059
  };
1364
- const handedOver = () => {
1365
- setTimeout(() => {
1366
- if (handlers.size === 0) end();
1367
- }, 0);
2060
+ const listeners = /* @__PURE__ */ new Set();
2061
+ const listenersFor = /* @__PURE__ */ new Set();
2062
+ const kinds = readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"];
2063
+ const sessionDeps = (principal, callerOf, shell) => ({
2064
+ whose: "of yours",
2065
+ kinds,
2066
+ holder: principal === null ? void 0 : async () => {
2067
+ await publishedNow();
2068
+ const caller = await callerOf();
2069
+ const held = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
2070
+ return { saved: caller.saved, heldTo: async (inForce3) => (await heldWithGenerated(held, inForce3, caller, shell)).heldTo };
2071
+ },
2072
+ written: () => {
2073
+ if (principal !== null) for (const listener of [...listenersFor]) tell(listener, principal);
2074
+ }
2075
+ });
2076
+ let pointer;
2077
+ const memo = createPublishedMemo();
2078
+ const defaultsHeldTo = () => ({
2079
+ kit: kitOf2(),
2080
+ entryOf: (fingerprint) => entries.byFingerprint().get(fingerprint),
2081
+ fingerprints: () => entries.byFingerprint().keys(),
2082
+ reads: readsHeldTo,
2083
+ built: mergedActions(own, sets),
2084
+ candidate: (actions, fragments) => candidate(actions, entries.list(), fragments)
2085
+ });
2086
+ const applyPublished = async (versions) => {
2087
+ const over = sets;
2088
+ const { passed, reads, verified } = await checkedDefaults(versions, defaultsHeldTo(), "published for everybody");
2089
+ if (sets !== over) return applyPublished(versions);
2090
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "boot");
2091
+ if (refusal !== void 0) memo.sayOnce(`[moss] what is published for everybody is left out, and the build\u2019s copies stand: ${refusal}`);
2092
+ const next = refusal === void 0 ? { actions: passed.actions, fragments: passed.fragments, reads } : { ...NO_DEFAULTS, reads };
2093
+ if (!hasDefaults(next) && !hasDefaults(defaults)) return;
2094
+ defaults = next;
2095
+ if (refusal === void 0) report = verified;
2096
+ inForce2 = mergedActions(own, sets, defaults.actions);
2097
+ dropMemos();
2098
+ };
2099
+ const publishedNow = () => {
2100
+ const held = memo.held();
2101
+ if (held !== void 0) return held;
2102
+ const read2 = (async () => {
2103
+ const versions = await config.published?.() ?? [];
2104
+ await applyPublished(versions);
2105
+ return versions;
2106
+ })();
2107
+ memo.keep(read2);
2108
+ read2.catch(memo.drop);
2109
+ return read2;
1368
2110
  };
1369
- return { live, onChange, handedOver, end };
1370
- };
1371
-
1372
- // src/data/routes.ts
1373
- var createVexRoutes = (deps) => {
1374
- const routes = new hono.Hono();
1375
- routes.use(
1376
- "/api/*",
1377
- (c, next) => deps.writes.within(
1378
- writeRequestOf((name) => c.req.header(name)),
1379
- () => next()
1380
- )
1381
- );
1382
- const mount = (path, entities) => {
1383
- routes.route(
1384
- path,
1385
- hono$1.vex({
1386
- engine: deps.engine,
1387
- ...entities !== void 0 ? { entities: [...entities] } : {},
1388
- locked: true,
1389
- getScope: deps.scope,
1390
- getPolicy: deps.policy,
1391
- getPolicyForReach: deps.policyAtReach,
1392
- ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
1393
- mutations: { client: deps.db, onWrite: deps.writes.report }
1394
- })
1395
- );
2111
+ const applySets = (arrived, announce) => {
2112
+ const next = new Map([...sets, ...arrived]);
2113
+ const actions = mergedActions(own, next, defaults.actions);
2114
+ const verified = chunk3DCTQKPQ_cjs.verifyManifest(candidate(actions));
2115
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "refresh");
2116
+ if (refusal !== void 0) throw new Error(refusal);
2117
+ for (const set of arrived.values()) chunk3DCTQKPQ_cjs.freezeDeep(set);
2118
+ sets = next;
2119
+ inForce2 = actions;
2120
+ report = verified;
2121
+ dropMemos();
2122
+ for (const listener of [...listeners]) tell(listener);
2123
+ if (announce) pointer?.bump();
1396
2124
  };
1397
- mount("/api/vex");
1398
- for (const [name, resource] of Object.entries(deps.resources ?? {})) {
1399
- mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
1400
- }
1401
- return routes;
1402
- };
1403
- var createIntentAnswers = (deps) => {
1404
- const engines = /* @__PURE__ */ new WeakMap();
1405
- const engineFor = (writers) => {
1406
- const kept = engines.get(writers);
1407
- if (kept !== void 0) return kept;
1408
- const { adapter, schema } = deps;
1409
- const created = (async () => {
1410
- const engine = vex.createQueryEngine({
1411
- adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
1412
- cache: deps.cache,
1413
- generateDsl: writers.generateDsl,
1414
- mapToShape: writers.mapToShape,
1415
- ...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
1416
- ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
1417
- });
1418
- await engine.introspect();
1419
- return engine;
1420
- })();
1421
- engines.set(writers, created);
1422
- return created;
2125
+ const reload = async () => {
2126
+ const read2 = [];
2127
+ for (const [source, load] of loaders) read2.push([source, await load()]);
2128
+ memo.drop();
2129
+ applySets(new Map(read2), false);
1423
2130
  };
1424
- return async (writers, asked, caller) => (await engineFor(writers)).execute({ intent: asked.intent, shape: asked.shape, context: asked.context ?? {} }, { scope: caller.scope, scopePolicy: caller.policy });
1425
- };
1426
-
1427
- // src/data/data.ts
1428
- var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
1429
- var prepareEngine = async (config) => {
1430
- await postgres.migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
1431
- const grammars = await createGrammarUpgrader({ grammars: config.grammars });
1432
- const layer = await createDataLayer(config);
1433
- return {
1434
- grammars,
1435
- engine: layer.engine,
1436
- grants: layer.grants,
1437
- adapter: layer.adapter,
1438
- upgradeStore: async (store) => {
1439
- await postgres.upgradeStore(config.pool, store, grammars);
1440
- }
2131
+ const takeEntries = async (source, handed) => {
2132
+ owners.assertAppOwned(source);
2133
+ const misfits = chunk3DCTQKPQ_cjs.entryMisfits(handed);
2134
+ if (misfits.length > 0) throw new Error(["Refresh refused \u2014 entries that do not parse:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
2135
+ const compiled = await compileEntries(handed);
2136
+ const verified = chunk3DCTQKPQ_cjs.verifyManifest(candidate(inForce2, entries.withSet(source, handed)));
2137
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "refresh");
2138
+ if (refusal !== void 0) throw new Error(refusal);
2139
+ chunk3DCTQKPQ_cjs.freezeDeep(handed);
2140
+ entries.takeSet(source, handed, compiled);
2141
+ report = verified;
2142
+ for (const listener of [...listeners]) tell(listener);
2143
+ pointer?.bump();
1441
2144
  };
1442
- };
1443
- var lazyIntentAnswers = (prepared, config) => {
1444
- const { engine } = prepared;
1445
- let answers;
1446
- const answering = () => {
1447
- if (answers !== void 0) return answers;
1448
- const schema = engine.getSchema();
1449
- if (schema === void 0) throw new Error("moss: an intent was asked before the engine had read the database.");
1450
- answers = createIntentAnswers({
1451
- adapter: prepared.adapter,
1452
- schema,
1453
- cache: engine.cache,
1454
- ...config.behaviors !== void 0 ? { behaviors: config.behaviors } : {},
1455
- ...config.vexConfig !== void 0 ? { vexConfig: config.vexConfig } : {}
1456
- });
1457
- return answers;
2145
+ let entriesTaken = Promise.resolve();
2146
+ return {
2147
+ actions: () => inForce2,
2148
+ entries: entries.list,
2149
+ verify: (actions) => chunk3DCTQKPQ_cjs.verifyManifest(candidate(actions)),
2150
+ report: () => report,
2151
+ replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
2152
+ // In turn: a set is compiled before it is taken, and of two handed over
2153
+ // the later has to be the one in force.
2154
+ replaceEntries: (source, handed) => {
2155
+ const taken = entriesTaken.then(() => takeEntries(source, handed));
2156
+ entriesTaken = taken.catch(() => void 0);
2157
+ return taken;
2158
+ },
2159
+ cacheEntry: async (fingerprint, scope) => {
2160
+ const shippedEntry = (await entries.compiled()).get(fingerprint);
2161
+ if (shippedEntry !== void 0 || readSources === void 0 || scope === void 0) return shippedEntry;
2162
+ const userId = scope["userId"];
2163
+ if (typeof userId === "string" && userId !== NOBODY_USER_ID) {
2164
+ const newest = (await readSources.savedOf(scope).history("read", fingerprint))[0];
2165
+ if (newest !== void 0 && newest.body !== null && newest.unread === void 0) return answeredRead(fingerprint, newest.body);
2166
+ }
2167
+ await publishedNow();
2168
+ const everybodys = defaults.reads.get(fingerprint);
2169
+ return everybodys === void 0 ? void 0 : compiledRead(fingerprint, everybodys);
2170
+ },
2171
+ cacheEntries: async () => [...await entries.compiled()].map(([key, entry]) => ({ key, entry })),
2172
+ claim: (source, owner) => {
2173
+ owners.claim(source, owner, sets.has(source) || entries.holdsSet(source));
2174
+ return {
2175
+ replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
2176
+ setLoader: (load) => {
2177
+ loaders.set(source, load);
2178
+ if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
2179
+ }
2180
+ };
2181
+ },
2182
+ refresh: () => applySets(/* @__PURE__ */ new Map(), true),
2183
+ functionsWritten,
2184
+ watch: () => {
2185
+ const where = config.pointer;
2186
+ if (pointer !== void 0 || where === void 0) return;
2187
+ pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
2188
+ },
2189
+ onChange: (listener) => {
2190
+ listeners.add(listener);
2191
+ return () => {
2192
+ listeners.delete(listener);
2193
+ };
2194
+ },
2195
+ addCatalogFilter: (filter) => {
2196
+ catalogFilters.push(filter);
2197
+ roleMemo.drop();
2198
+ },
2199
+ catalogFor: roleMemo.catalogFor,
2200
+ artifactsFor: async (shell, { principal, roles, installed, saved, replayable, drafted }) => {
2201
+ const own2 = saved === void 0 || principal === null ? [] : await saved.inForce();
2202
+ if (saved !== void 0 && principal !== null) usage.touch(principal, own2, saved);
2203
+ const versions = own2.length === 0 && drafted === void 0 ? [] : laidOver(own2, drafted);
2204
+ const everybodysVersions = await publishedNow();
2205
+ const whose = `of ${principal ?? "nobody"}`;
2206
+ const theirOwn = await heldWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
2207
+ const drawable = theirOwn.heldTo.layouts;
2208
+ const theirs2 = layoutsInUse(versions, { whose, heldTo: drawable });
2209
+ const variants = roleMemo.variantsFor(roles);
2210
+ const underVariants = { ...drawable, actionAt: (ref) => variants.has(chunk3DCTQKPQ_cjs.actionOfLayoutRef(ref) ?? "") ? void 0 : drawable.actionAt(ref) };
2211
+ const everybodys = layoutsInUse(everybodysVersions, { whose: "published for everybody", heldTo: underVariants, say: memo.sayOnce });
2212
+ const laidOverShell = { ...drawableIn(defaults.fragments, kitOf2(shell), memo.sayOnce), ...theirOwn.fragments };
2213
+ const fragments = Object.keys(laidOverShell).length === 0 ? shell.fragments : { ...shell.fragments, ...laidOverShell };
2214
+ const { layouts: ofShell, ...named } = shellWithStoredLayouts(shell);
2215
+ const layoutStore = { ...shell.layoutStore, ...ofShell, ...theirOwn.all.layouts, ...everybodys, ...theirs2 };
2216
+ return {
2217
+ actions: theirOwn.all.actions,
2218
+ ...named,
2219
+ slottedCanvases: slottedCanvases(shell.canvases, [...Object.values(layoutStore), ...Object.values(fragments ?? {}).map((fragment) => fragment.layout)]),
2220
+ grantedFunctions: grantedFunctionsOf(roles),
2221
+ layoutStore,
2222
+ ...fragments !== void 0 ? { fragments } : {},
2223
+ entries: entries.byFingerprint(),
2224
+ components: components.of(shell)
2225
+ };
2226
+ },
2227
+ sessionArtifacts: (principal, callerOf) => savedArtifacts(sessionDeps(principal, callerOf)),
2228
+ draftSavingFor: (shell, principal, callerOf) => draftSaving(sessionDeps(principal, callerOf, shell)),
2229
+ // Held to every action in force with the layout it is built with: who holds
2230
+ // which is asked when a shell is built for them.
2231
+ publishedArtifacts: (saved, publisher) => savedArtifacts({
2232
+ whose: "published for everybody",
2233
+ kinds,
2234
+ holder: async () => {
2235
+ const who = await publisher();
2236
+ return { saved, heldTo: async (inForce3) => (await heldWithGenerated(actionsWithStoredLayouts(mergedActions(own, sets)), inForce3, who)).heldTo };
2237
+ },
2238
+ defaults: {
2239
+ verify: async (versions, inForce3) => {
2240
+ const kept = inForce3.filter((held) => !versions.some((version) => version.kind === held.kind && version.id === held.id));
2241
+ const asked = versions.map((version) => ({ ...version, save: "", createdAt: "" }));
2242
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf((await checkedDefaults([...kept, ...asked], defaultsHeldTo(), void 0)).verified, "publish");
2243
+ if (refusal !== void 0) throw new Error(refusal);
2244
+ }
2245
+ },
2246
+ written: () => {
2247
+ memo.drop();
2248
+ for (const listener of [...listeners]) tell(listener);
2249
+ pointer?.bump();
2250
+ }
2251
+ }),
2252
+ readPublished: async () => {
2253
+ memo.drop();
2254
+ await publishedNow();
2255
+ },
2256
+ onChangeFor: (listener) => {
2257
+ listenersFor.add(listener);
2258
+ return () => {
2259
+ listenersFor.delete(listener);
2260
+ };
2261
+ },
2262
+ generation: () => pointer?.current() ?? -1,
2263
+ stop: () => pointer?.stop()
1458
2264
  };
1459
- return answering;
1460
2265
  };
1461
- var tablesByFeature = (config) => (feature) => {
1462
- const kept = (config.featureTables ?? []).find((tables) => tables.feature === feature);
1463
- if (kept === void 0) throw new Error(`moss: the data module was asked for the tables of a feature it was never told of ("${feature}").`);
1464
- return kept.names;
2266
+ var theirs = { match: "principal", to: "userId" };
2267
+ var stamped = { set: "principal", to: "userId" };
2268
+ var MADE_BY = "artifactSavedBy";
2269
+ var madeBy = { set: "created_by", to: MADE_BY };
2270
+ var SAVE_ROW_RULES = {
2271
+ artifacts: { read: [theirs], write: [theirs, stamped] },
2272
+ artifact_saves: { read: [theirs], write: [theirs, stamped, madeBy] }
1465
2273
  };
1466
- var createUpgradeStore = (prepared, tablesOf) => async (feature, store) => {
1467
- const own = tablesOf(feature);
1468
- if (store.schema !== void 0) {
2274
+ var EVERYBODY = "*";
2275
+ var callerScope = (scope) => {
2276
+ if (scope["userId"] === EVERYBODY) {
1469
2277
  throw new Error(
1470
- `moss: the feature "${feature}" asked for the documents of a store in the schema "${store.schema}" to be upgraded. To a feature a store is named by its table alone: one of its own.`
2278
+ `moss: a caller\u2019s \`userId\` is "${EVERYBODY}", and that is whose the rows published for everybody are. No caller is it: the app\u2019s sign-in or its \`scope\` answers another.`
1471
2279
  );
1472
2280
  }
1473
- if (!own.includes(store.table)) {
1474
- throw new Error(`moss: the feature "${feature}" asked for the documents stored in "${store.table}" to be upgraded, and that table is not its own (its own: ${own.join(", ") || "none"}).`);
2281
+ if (Object.hasOwn(scope, MADE_BY)) {
2282
+ throw new Error(`moss: a caller\u2019s scope carries \`${MADE_BY}\`. Who made a save is written from that value, and it is moss\u2019s to say: the app\u2019s \`scope\` names its own otherwise.`);
1475
2283
  }
1476
- await prepared.upgradeStore(store);
1477
- };
1478
- var createDataWith = (prepared, config) => {
1479
- const { grammars, engine, grants } = prepared;
1480
- const governed = { charter: config.charter, behaviors: config.behaviors };
1481
- const policies = createPolicies({ ...governed, grants });
1482
- const emit = chunkVBWNHF4H_cjs.emitterOf(config.telemetry);
1483
- const onExecute = emit === void 0 ? void 0 : (record2) => emit(vexRecordToSpan(record2));
1484
- const writes = createWriteNotifier();
1485
- const answering = lazyIntentAnswers(prepared, config);
1486
- const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
1487
- const tablesOf = tablesByFeature(config);
1488
- let pointerEntries;
1489
- const pointerReplay = () => {
1490
- pointerEntries ??= ownEntries(POINTER, void 0);
1491
- return pointerEntries;
1492
- };
1493
- return {
1494
- grants,
1495
- grammars,
1496
- seed: (entries) => vex.seedCache(engine.cache, entries),
1497
- fingerprints: async () => await engine.cache.keys?.() ?? [],
1498
- policyOf: policies.of,
1499
- // Compiled afresh and not taken from the kept ones: the caller owns its
1500
- // copy, and nothing it does to it reaches a policy a request is served under.
1501
- policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
1502
- fingerprintsFor: async (who) => (await vex.handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry2) => entry2.fingerprint).sort(),
1503
- executeAs: createExecuteAs({
1504
- engine,
1505
- db: config.db,
1506
- policyFor: (roles) => policies.of(callerOfRoles(roles)),
1507
- policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
1508
- ...onExecute !== void 0 ? { onExecute } : {}
1509
- }),
1510
- answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
1511
- ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
1512
- routes: (routing) => createVexRoutes({
1513
- engine,
1514
- db: config.db,
1515
- resources: routing.resources,
1516
- scope: routing.scope,
1517
- policy: (c) => policies.of(routing.caller(c)),
1518
- policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
1519
- ...onExecute !== void 0 ? { onExecute } : {},
1520
- writes
1521
- }),
1522
- upgradeStore: createUpgradeStore(prepared, tablesOf),
1523
- onWrite: writes.subscribe,
1524
- pointer: createPointer(pointerReplay),
1525
- dropOnChange: (changed) => {
1526
- changed(policies.drop);
1527
- }
1528
- };
1529
- };
1530
- var createData = async (config) => createDataWith(await prepareEngine(config), config);
1531
- var DEFAULT_ROOT = '<div id="root"></div>';
1532
- var embedSnapshot = (snapshot, principal, path) => {
1533
- const { frame, trees, seed, live } = snapshot;
1534
- const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
1535
- const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1536
- return `<script type="application/json" id="${chunk3RIWTXGI_cjs.SNAPSHOT_ELEMENT_ID}">${text}</script>`;
1537
- };
1538
- var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
1539
- var rootHolding = (root) => {
1540
- const closing = root.lastIndexOf("</");
1541
- if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
1542
- return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
2284
+ return scope;
2285
+ };
2286
+ var PAGE = 500;
2287
+ var VERSION_COLUMNS = ["save", "kind", "id", "body", "grammar", "copied_from", "created_at"];
2288
+ var laterThanHeld = {
2289
+ and: [
2290
+ { eq: ["artifacts.kind", "held.kind"] },
2291
+ { eq: ["artifacts.id", "held.id"] },
2292
+ { or: [{ gt: ["artifacts.created_at", "held.created_at"] }, { and: [{ eq: ["artifacts.created_at", "held.created_at"] }, { gt: ["artifacts.save", "held.save"] }] }] }
2293
+ ]
1543
2294
  };
1544
- var escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1545
- var renderDocument = async (config) => {
1546
- const { server, template, request, draw } = config;
1547
- const tokenKey = config.tokenKey ?? chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY;
1548
- const root = config.root ?? DEFAULT_ROOT;
1549
- const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
1550
- if (!template.includes(root)) return undrawn;
1551
- const holding = rootHolding(root);
1552
- if (holding === void 0) {
1553
- console.error(`[moss/document] the root ${root} has no place for a screen \u2014 a root is an empty element, like ${DEFAULT_ROOT}. "${request.path}" is served undrawn.`);
1554
- return undrawn;
2295
+ var afterHeld = {
2296
+ or: [{ gt: ["held.kind", { $context: "after_kind" }] }, { and: [{ eq: ["held.kind", { $context: "after_kind" }] }, { gt: ["held.id", { $context: "after_id" }] }] }]
2297
+ };
2298
+ var inForce = {
2299
+ fingerprint: "artifactory/in-force",
2300
+ intent: "The latest version of each of the caller\u2019s artifacts, a page at a time",
2301
+ dsl: {
2302
+ from: [{ as: "held", query: { from: ["artifacts"], fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`) } }],
2303
+ fields: VERSION_COLUMNS.map((column) => `held.${column}`),
2304
+ filter: { and: [{ not: { exists: { from: ["artifacts"], filter: laterThanHeld } } }, afterHeld] },
2305
+ sort: [
2306
+ { field: "held.kind", dir: "asc" },
2307
+ { field: "held.id", dir: "asc" }
2308
+ ],
2309
+ limit: PAGE
1555
2310
  }
1556
- try {
1557
- const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
1558
- const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
1559
- const principal = token === null ? null : await server.principalOf(token);
1560
- const route = server.page(request.path);
1561
- const host = route?.host ?? server.shells;
1562
- if (host === void 0) return undrawn;
1563
- const snapshot = await host.snapshot(principal === null ? null : token, principal, {
1564
- ...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
1565
- ...route !== void 0 ? { inputs: route.inputs } : {}
1566
- });
1567
- const screen = await draw(snapshot);
1568
- const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
1569
- const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
1570
- const head = document.headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
1571
- for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
1572
- const html = document.placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
1573
- return {
1574
- html,
1575
- ...head !== void 0 ? { head } : {},
1576
- headers: documentHeaders(principal),
1577
- drawn: true,
1578
- principal,
1579
- ...route !== void 0 ? { page: route.name } : {},
1580
- live: snapshot.live,
1581
- why: snapshot.why,
1582
- drawnWith: snapshot.drawnWith,
1583
- settled: snapshot.settled
1584
- };
1585
- } catch (error) {
1586
- console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
1587
- return undrawn;
2311
+ };
2312
+ var history = {
2313
+ fingerprint: "artifactory/history",
2314
+ intent: "The versions of one of the caller\u2019s artifacts, the newest first",
2315
+ dsl: {
2316
+ from: ["artifacts"],
2317
+ fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`),
2318
+ filter: {
2319
+ and: [
2320
+ { eq: ["artifacts.kind", { $context: "kind" }] },
2321
+ { eq: ["artifacts.id", { $context: "id" }] },
2322
+ { optional: { key: "save", then: { eq: ["artifacts.save", { $context: "save" }] } } }
2323
+ ]
2324
+ },
2325
+ sort: [
2326
+ { field: "artifacts.created_at", dir: "desc" },
2327
+ { field: "artifacts.save", dir: "desc" }
2328
+ ],
2329
+ limit: PAGE
1588
2330
  }
1589
2331
  };
1590
-
1591
- // src/documents/pages.ts
1592
- var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
1593
- var compile = (name, page) => {
1594
- if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
1595
- const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
1596
- for (const segment of segments) {
1597
- if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
1598
- throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
2332
+ var save = {
2333
+ fingerprint: "artifactory/save",
2334
+ intent: "Keep a save of the caller\u2019s and the versions it holds",
2335
+ mutation: [
2336
+ { op: "insert", table: "artifact_saves", values: { id: { $context: "save" } } },
2337
+ {
2338
+ op: "insertEach",
2339
+ table: "artifacts",
2340
+ items: { $context: "versions" },
2341
+ values: { save: { $context: "save" }, kind: { $item: "kind" }, id: { $item: "id" }, body: { $item: "body" }, grammar: { $item: "grammar" }, copied_from: { $item: "copied_from" } }
1599
2342
  }
1600
- }
1601
- const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
1602
- const twice = named.find((param, index) => named.indexOf(param) !== index);
1603
- if (twice !== void 0) {
1604
- throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
1605
- }
1606
- if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
1607
- throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
1608
- }
1609
- return { name, segments };
2343
+ ]
1610
2344
  };
1611
- var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
1612
- const other = b.segments[index];
1613
- return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
1614
- });
1615
- var createPageRouter = (pages) => {
1616
- const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));
1617
- for (const [index, page] of compiled.entries()) {
1618
- const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));
1619
- if (other !== void 0) {
1620
- throw new Error(`moss: pages "${page.name}" and "${other.name}" can both answer one path \u2014 give them paths that differ in a literal segment.`);
2345
+ var touch = {
2346
+ fingerprint: "artifactory/touch",
2347
+ intent: "Mark one of the caller\u2019s artifacts as used now",
2348
+ mutation: [
2349
+ {
2350
+ op: "update",
2351
+ table: "artifacts",
2352
+ set: { last_used_at: { $context: "at" } },
2353
+ where: { and: [{ eq: ["artifacts.kind", { $context: "kind" }] }, { eq: ["artifacts.id", { $context: "id" }] }] }
1621
2354
  }
2355
+ ]
2356
+ };
2357
+ var SAVE_ENTRIES = [inForce, history, save, touch];
2358
+ var RowSchema2 = zod.z.object({
2359
+ save: zod.z.string(),
2360
+ kind: zod.z.string(),
2361
+ id: zod.z.string(),
2362
+ body: zod.z.unknown(),
2363
+ grammar: zod.z.record(zod.z.string(), zod.z.coerce.number()).catch({}),
2364
+ copied_from: zod.z.string().nullish(),
2365
+ // Drivers hand back a Date, an ISO string or a number for the same column.
2366
+ created_at: zod.z.union([zod.z.date(), zod.z.string(), zod.z.number()]).transform((at) => new Date(at).toISOString())
2367
+ });
2368
+ var upgradedAs = (grammarKind) => (upgrader, body, stamp) => upgrader.upgrade(body, { kind: grammarKind, stamp }).document;
2369
+ var upgradedBody = {
2370
+ layout: upgradedLayoutBody,
2371
+ action: upgradedAs("nisc.nova/action"),
2372
+ fragment: upgradedAs("nisc.nova/fragment"),
2373
+ read: upgradedAs("nisc.vex/entry")
2374
+ };
2375
+ var versionOf = (row, upgrader) => {
2376
+ const version = { save: row.save, kind: row.kind, id: row.id, copiedFrom: row.copied_from ?? null, createdAt: row.created_at };
2377
+ const upgrade = upgradedBody[row.kind];
2378
+ if (row.body === null || row.body === void 0 || upgrade === void 0) return { ...version, body: row.body ?? null };
2379
+ try {
2380
+ return { ...version, body: upgrade(upgrader, row.body, row.grammar) };
2381
+ } catch (error) {
2382
+ if (!(error instanceof strata.StrataError)) throw error;
2383
+ return { ...version, body: row.body, unread: error.message.split("\n")[0] ?? error.code };
1622
2384
  }
1623
- return {
1624
- match: (path) => {
1625
- const parts = segmentsOf(path);
1626
- for (const page of compiled) {
1627
- if (page.segments.length !== parts.length) continue;
1628
- const params = {};
1629
- let matches = true;
1630
- for (const [index, segment] of page.segments.entries()) {
1631
- const part = parts[index];
1632
- if (part === void 0) {
1633
- matches = false;
1634
- break;
1635
- }
1636
- if ("param" in segment) {
1637
- try {
1638
- params[segment.param] = decodeURIComponent(part);
1639
- } catch {
1640
- matches = false;
1641
- break;
1642
- }
1643
- } else if (segment.literal !== part) {
1644
- matches = false;
1645
- break;
1646
- }
1647
- }
1648
- if (matches) return { name: page.name, params };
2385
+ };
2386
+ var savedRowsOver = (replay, upgrader) => {
2387
+ const versionsIn = (answered) => zod.z.array(RowSchema2).parse(answered).map((row) => versionOf(row, upgrader));
2388
+ const rows = (scope) => {
2389
+ const everyVersionInForce = async (after) => {
2390
+ const page = versionsIn(await replay(inForce.fingerprint, { after_kind: after?.kind ?? "", after_id: after?.id ?? "" }, scope));
2391
+ const last = page.at(-1);
2392
+ return page.length < PAGE || last === void 0 ? page : [...page, ...await everyVersionInForce(last)];
2393
+ };
2394
+ return {
2395
+ inForce: () => everyVersionInForce(),
2396
+ history: async (kind, id, saved) => versionsIn(await replay(history.fingerprint, { kind, id, ...saved === void 0 ? {} : { save: saved } }, scope)),
2397
+ write: async (saved) => {
2398
+ const versions = saved.versions.map((version) => ({ kind: version.kind, id: version.id, body: version.body, grammar: upgrader.stamp, copied_from: version.copiedFrom }));
2399
+ await replay(save.fingerprint, { save: saved.id, versions }, scope);
2400
+ },
2401
+ touch: async (artifacts, at) => {
2402
+ for (const { kind, id } of artifacts) await replay(touch.fingerprint, { kind, id, at }, scope);
1649
2403
  }
1650
- return void 0;
1651
- }
2404
+ };
2405
+ };
2406
+ return {
2407
+ of: (scope) => rows({ ...callerScope(scope), [MADE_BY]: scope["userId"] }),
2408
+ published: (by) => rows({ userId: EVERYBODY, ...by === void 0 ? {} : { [MADE_BY]: by } })
1652
2409
  };
1653
- };
1654
- var exportDocuments = async (config) => {
1655
- const { paths, ...rest } = config;
1656
- const out = [];
1657
- for (const path of paths) {
1658
- const page = await renderDocument({ ...rest, request: { path, cookie: null } });
1659
- out.push({
1660
- path,
1661
- html: page.html,
1662
- ...page.page !== void 0 ? { page: page.page } : {},
1663
- ...page.head !== void 0 ? { head: page.head } : {},
1664
- drawn: page.drawn,
1665
- // A page that could not be drawn is not taken to be finished.
1666
- live: page.live ?? true,
1667
- why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
1668
- drawnWith: page.drawnWith ?? [],
1669
- settled: page.settled ?? false
1670
- });
1671
- }
1672
- return out;
1673
2410
  };
1674
2411
 
1675
2412
  // src/socket/revalidation.ts
@@ -1892,7 +2629,7 @@ var refusalOf2 = (error) => {
1892
2629
  };
1893
2630
  var spanOf = (emit) => {
1894
2631
  if (emit === void 0) return void 0;
1895
- const clock = chunkVBWNHF4H_cjs.spanClock();
2632
+ const clock = chunkPVZMCEBX_cjs.spanClock();
1896
2633
  return (name, status, hasPrincipal) => emit({ name, startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status, attributes: { hasPrincipal } });
1897
2634
  };
1898
2635
  var openingOf = (config, { seed, path }) => {
@@ -1952,7 +2689,7 @@ var open = async (held, url, connection, send, span, found) => {
1952
2689
  connection.onMessage(messageHandler(attached, connection, send));
1953
2690
  };
1954
2691
  var createSocket = (config) => {
1955
- const emit = chunkVBWNHF4H_cjs.emitterOf(config.telemetry);
2692
+ const emit = chunkPVZMCEBX_cjs.emitterOf(config.telemetry);
1956
2693
  const revalidation = createRevalidation(config);
1957
2694
  const anonymousShells = createAnonymousShellLimit(config.anonymousShellMax ?? DEFAULT_ANONYMOUS_SHELL_MAX);
1958
2695
  const held = { config, foreignPageWarning: { warned: false }, revalidation, anonymousShells };
@@ -2000,13 +2737,13 @@ var seamsFor = (feature, owned, { app, runtime, server, operator, registered, id
2000
2737
  grantedActionIds: (roles, installed) => running.catalogFor(roles, installed).ids,
2001
2738
  actions: running.actions,
2002
2739
  replaceActions: owned.replace,
2003
- refusalOf: (actions) => refusalOf(running.verify(actions), "refresh"),
2740
+ refusalOf: (actions) => chunk3DCTQKPQ_cjs.refusalOf(running.verify(actions), "refresh"),
2004
2741
  setActionsLoader: owned.setLoader,
2005
2742
  addCatalogFilter: running.addCatalogFilter,
2006
2743
  charter: app.charter,
2007
2744
  components: app.shell?.components ?? {},
2008
- layoutMisfits: (layout2) => layoutMisfits(layout2, kitOf(app)),
2009
- endlessChains,
2745
+ layoutMisfits: (layout) => chunk3DCTQKPQ_cjs.layoutMisfits(layout, kitOf(app)),
2746
+ endlessChains: chunk3DCTQKPQ_cjs.endlessChains,
2010
2747
  ownEntries: (entries) => data.ownEntries(feature.name, entries),
2011
2748
  grammars: data.grammars,
2012
2749
  upgradeStore: (store) => data.upgradeStore(feature.name, store),
@@ -2031,7 +2768,7 @@ var shellNeedOf = (definition, entries) => {
2031
2768
  const why = [];
2032
2769
  const drawnWith = [];
2033
2770
  if (facts.gestures) why.push("a person can act on it");
2034
- if (facts.opaqueLayout) why.push("its layout is kept in the store, so what can be pressed on it is not readable");
2771
+ if (facts.opaqueLayout) why.push("its layout is the name of a stored layout, so what can be pressed on it is not readable");
2035
2772
  for (const channel of facts.listens) why.push(`it waits on the channel "${channel}"`);
2036
2773
  for (const use of facts.endpoints) {
2037
2774
  if (!use.onOpen && !use.later) continue;
@@ -2040,12 +2777,12 @@ var shellNeedOf = (definition, entries) => {
2040
2777
  continue;
2041
2778
  }
2042
2779
  const fingerprint = fingerprintOf(use.request);
2043
- const entry2 = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
2044
- if (entry2 !== void 0 && !("mutation" in entry2) && entry2.refresh === "reactive") {
2045
- why.push(`its read "${use.name}" keeps answering (${entry2.fingerprint} is reactive)`);
2780
+ const entry = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
2781
+ if (entry !== void 0 && !("mutation" in entry) && entry.refresh === "reactive") {
2782
+ why.push(`its read "${use.name}" keeps answering (${entry.fingerprint} is reactive)`);
2046
2783
  continue;
2047
2784
  }
2048
- if (fingerprint !== void 0 && entry2 === void 0) {
2785
+ if (fingerprint !== void 0 && entry === void 0) {
2049
2786
  why.push(`its read "${use.name}" replays "${fingerprint}", which the manifest does not carry \u2014 whether it keeps answering is not readable`);
2050
2787
  continue;
2051
2788
  }
@@ -2073,9 +2810,9 @@ var read = (live) => {
2073
2810
  console.error("[moss/shells] the shell frame failed to render for a snapshot \u2014 serving an empty arrangement:", error);
2074
2811
  }
2075
2812
  const trees = {};
2076
- for (const canvasId of chunkR2YPQHQH_cjs.canvasesOf(live)) {
2813
+ for (const canvasId of chunk3DCTQKPQ_cjs.canvasesOf(live)) {
2077
2814
  try {
2078
- trees[canvasId] = chunkR2YPQHQH_cjs.treeOf(live, canvasId);
2815
+ trees[canvasId] = chunk3DCTQKPQ_cjs.treeOf(live, canvasId);
2079
2816
  } catch (error) {
2080
2817
  console.error(`[moss/shells] canvas "${canvasId}" failed to render for a snapshot \u2014 leaving it out:`, error);
2081
2818
  }
@@ -2092,7 +2829,7 @@ var needOf = (live, principal, kept) => {
2092
2829
  for (const instance of canvas.stack) {
2093
2830
  const definition = live.shell.getRuntime(instance.id)?.definition;
2094
2831
  if (definition === void 0) continue;
2095
- const need = shellNeedOf(definition, entries);
2832
+ const need = shellNeedOf(chunk3DCTQKPQ_cjs.withLayoutInPlace(definition, live.shell.layoutStore), entries);
2096
2833
  for (const reason of need.why) why.push(`${definition.id}: ${reason}`);
2097
2834
  for (const read2 of need.drawnWith) drawnWith.push(read2);
2098
2835
  }
@@ -2115,7 +2852,7 @@ var sweep = (host, idleMs) => {
2115
2852
  }
2116
2853
  if (live.connections.size > 0 || live.idleSince === null) continue;
2117
2854
  if (now - live.idleSince < idleMs) continue;
2118
- chunkR2YPQHQH_cjs.endShell(host, live);
2855
+ chunk3DCTQKPQ_cjs.endShell(host, live);
2119
2856
  live.shell.dispose();
2120
2857
  durable.delete(principal);
2121
2858
  }
@@ -2137,32 +2874,66 @@ var rosterOf = (durable) => {
2137
2874
  var sameDocument = (one, other) => one === other || JSON.stringify(one) === JSON.stringify(other);
2138
2875
  var takeLayouts = (live, made) => {
2139
2876
  const taken = live.layouts;
2140
- const answered = chunkR2YPQHQH_cjs.layoutsOf(made);
2141
- for (const [ref, layout2] of Object.entries(answered.layoutStore)) {
2142
- if (!sameDocument(taken.layoutStore[ref], layout2)) live.shell.setLayout(ref, layout2);
2877
+ const answered = chunk3DCTQKPQ_cjs.layoutsOf(made);
2878
+ for (const [ref, layout] of Object.entries(answered.layoutStore)) {
2879
+ if (!sameDocument(taken.layoutStore[ref], layout)) live.shell.setLayout(ref, layout);
2880
+ }
2881
+ for (const ref of Object.keys(taken.layoutStore)) {
2882
+ if (!Object.hasOwn(answered.layoutStore, ref)) live.shell.layoutStore.delete(ref);
2143
2883
  }
2144
2884
  for (const [id, fragment] of Object.entries(answered.fragments)) {
2145
- if (!sameDocument(taken.fragments[id], fragment)) live.shell.registerFragment({ ...fragment, id });
2885
+ if (!sameDocument(taken.fragments[id], fragment)) live.shell.registerAction({ ...fragment, id });
2886
+ }
2887
+ for (const id of Object.keys(taken.fragments)) {
2888
+ if (!Object.hasOwn(answered.fragments, id)) live.shell.removeAction(id);
2146
2889
  }
2147
- if (answered.frame !== void 0 && !sameDocument(taken.frame, answered.frame)) live.shell.setCanvasLayout(answered.frame);
2148
2890
  live.layouts = answered;
2149
2891
  };
2892
+ var takeCanvases = (live, made) => {
2893
+ const slotted = new Set(made.slottedCanvases);
2894
+ for (const id of live.slottedCanvases) if (!slotted.has(id)) live.shell.removeCanvas(id);
2895
+ live.slottedCanvases = slotted;
2896
+ };
2897
+ var takeComposition = (live, made) => {
2898
+ for (const [name, contract] of Object.entries(made.components)) {
2899
+ if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
2900
+ }
2901
+ for (const id of live.actionIds) if (!Object.hasOwn(made.actions, id)) live.shell.removeAction(id);
2902
+ for (const definition of Object.values(made.actions)) live.shell.registerAction(definition);
2903
+ live.actionIds = new Set(Object.keys(made.actions));
2904
+ live.entries = made.entries;
2905
+ takeLayouts(live, made);
2906
+ takeCanvases(live, made);
2907
+ chunk3DCTQKPQ_cjs.holdGranted(live.functions, made.grantedFunctions);
2908
+ };
2909
+ var adoptDraft = async (host, live, next) => {
2910
+ for (; ; ) {
2911
+ const cell = host.living.get(live);
2912
+ if (cell === void 0 || cell.live !== live) throw new Error(chunk3DCTQKPQ_cjs.SHELL_GONE);
2913
+ const changes = host.changes;
2914
+ const made = await host.config.composition(cell.principal, chunk3DCTQKPQ_cjs.draftedIn(next));
2915
+ if (live.ended || cell.live !== live) throw new Error(chunk3DCTQKPQ_cjs.SHELL_GONE);
2916
+ if (changes < cell.changes) continue;
2917
+ cell.changes = changes;
2918
+ live.draft = next;
2919
+ takeComposition(live, made);
2920
+ return;
2921
+ }
2922
+ };
2150
2923
  var adopt = (host, cell) => {
2151
2924
  const adopting = async () => {
2152
- if (cell.live.ended) return;
2925
+ const asked = cell.live;
2926
+ if (asked.ended) return;
2927
+ const drafted = asked.draft;
2153
2928
  const changes = host.changes;
2154
- const made = await host.config.composition(cell.principal);
2155
- const live = cell.live;
2156
- if (live.ended || changes <= cell.changes) return;
2157
- cell.changes = changes;
2158
- for (const [name, contract] of Object.entries(made.components)) {
2159
- if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
2929
+ const made = await host.config.composition(cell.principal, chunk3DCTQKPQ_cjs.draftedIn(drafted));
2930
+ if (asked.ended || changes <= cell.changes) return;
2931
+ if (asked.draft !== drafted) {
2932
+ adopt(host, cell);
2933
+ return;
2160
2934
  }
2161
- for (const id of live.actionIds) if (!Object.hasOwn(made.actions, id)) live.shell.removeAction(id);
2162
- for (const definition of Object.values(made.actions)) live.shell.registerAction(definition);
2163
- live.actionIds = new Set(Object.keys(made.actions));
2164
- live.entries = made.entries;
2165
- takeLayouts(live, made);
2935
+ cell.changes = changes;
2936
+ takeComposition(asked, made);
2166
2937
  };
2167
2938
  adopting().catch((error) => {
2168
2939
  console.error(`[moss/shells] the shell of ${cell.principal ?? "nobody"} could not adopt what changed, and keeps what it held:`, error);
@@ -2172,6 +2943,10 @@ var adoptAll = (host) => {
2172
2943
  host.changes += 1;
2173
2944
  for (const cell of [...host.living.values()]) adopt(host, cell);
2174
2945
  };
2946
+ var adoptFor = (host, principal) => {
2947
+ host.changes += 1;
2948
+ for (const cell of shellsOf(host, principal)) adopt(host, cell);
2949
+ };
2175
2950
  var build = (host, asked, wanted = () => true) => {
2176
2951
  const changes = host.changes;
2177
2952
  const limit = host.config.limits?.endpointTimeoutMs ?? DEFAULT_BUILD_TIMEOUT_MS;
@@ -2182,7 +2957,7 @@ var build = (host, asked, wanted = () => true) => {
2182
2957
  reject(new Error(`moss: the shell of ${asked.principal ?? "nobody"} was not built within ${limit}ms.`));
2183
2958
  }, limit);
2184
2959
  timer.unref?.();
2185
- chunkR2YPQHQH_cjs.buildShell(host, { ...asked, wanted: () => inTime && wanted() }).then((live) => resolve2(live === void 0 ? void 0 : { live, changes }), reject).finally(() => clearTimeout(timer));
2960
+ chunk3DCTQKPQ_cjs.buildShell(host, { ...asked, wanted: () => inTime && wanted() }).then((live) => resolve2(live === void 0 ? void 0 : { live, changes }), reject).finally(() => clearTimeout(timer));
2186
2961
  });
2187
2962
  };
2188
2963
  var builtOrThrow = (built) => {
@@ -2222,18 +2997,18 @@ var replaceShell = async (host, cell) => {
2222
2997
  if (built === void 0) return;
2223
2998
  const old = cell.live;
2224
2999
  if (!stands()) {
2225
- chunkR2YPQHQH_cjs.endShell(host, built.live);
3000
+ chunk3DCTQKPQ_cjs.endShell(host, built.live);
2226
3001
  built.live.shell.dispose();
2227
3002
  return;
2228
3003
  }
2229
3004
  const carried = [...old.connections].map((connection) => ({ connection, wants: old.deltaReady.has(connection) }));
2230
- chunkR2YPQHQH_cjs.endShell(host, old);
3005
+ chunk3DCTQKPQ_cjs.endShell(host, old);
2231
3006
  old.connections.clear();
2232
3007
  old.shell.dispose();
2233
3008
  cell.live = built.live;
2234
3009
  cell.changes = built.changes;
2235
3010
  registerLiving(host, cell);
2236
- for (const { connection, wants } of carried) chunkR2YPQHQH_cjs.attach(built.live, connection, host.delta && wants);
3011
+ for (const { connection, wants } of carried) chunk3DCTQKPQ_cjs.attach(built.live, connection, host.delta && wants);
2237
3012
  };
2238
3013
  var resetCell = (host, cell) => {
2239
3014
  const turn = (cell.resetting ?? Promise.resolve()).then(() => replaceShell(host, cell));
@@ -2271,7 +3046,7 @@ var snapshotOf = (host) => async (token, principal, options) => {
2271
3046
  const settled = await settle(live, waitMs);
2272
3047
  return { ...read(live), seed, settled, ...needOf(live, principal, kept) };
2273
3048
  } finally {
2274
- chunkR2YPQHQH_cjs.endShell(host, live);
3049
+ chunk3DCTQKPQ_cjs.endShell(host, live);
2275
3050
  live.shell.dispose();
2276
3051
  }
2277
3052
  };
@@ -2290,45 +3065,59 @@ var deliverTo = (host) => (principal, channel, payload) => {
2290
3065
  var createShellHost = (config) => {
2291
3066
  const host = {
2292
3067
  config,
2293
- emit: chunkVBWNHF4H_cjs.emitterOf(config.telemetry),
3068
+ emit: chunkPVZMCEBX_cjs.emitterOf(config.telemetry),
2294
3069
  kept: config.kept ?? true,
2295
3070
  delta: config.limits?.delta ?? false,
2296
3071
  durable: /* @__PURE__ */ new Map(),
2297
3072
  building: /* @__PURE__ */ new Map(),
2298
3073
  living: /* @__PURE__ */ new Map(),
2299
- changes: 0
3074
+ changes: 0,
3075
+ adoptDraft: (live, next) => adoptDraft(host, live, next)
2300
3076
  };
2301
3077
  const reset = (cell) => resetCell(host, cell);
2302
3078
  const handedOut = {
2303
3079
  session: async (token, principal, options) => {
2304
3080
  if (principal === null || !host.kept) {
2305
- return chunkR2YPQHQH_cjs.sessionOn(host, await open2(host, { token, principal, ...options !== void 0 ? { opening: options } : {} }, false), true, reset);
3081
+ return chunk3DCTQKPQ_cjs.sessionOn(host, await open2(host, { token, principal, ...options !== void 0 ? { opening: options } : {} }, false), true, reset);
2306
3082
  }
2307
- return chunkR2YPQHQH_cjs.sessionOn(host, await keptCell(host, token, principal), false, reset);
3083
+ return chunk3DCTQKPQ_cjs.sessionOn(host, await keptCell(host, token, principal), false, reset);
2308
3084
  },
2309
3085
  snapshot: snapshotOf(host),
2310
3086
  deliver: deliverTo(host),
2311
3087
  list: () => rosterOf(host.durable),
2312
3088
  reset: (principal) => {
2313
- const theirs = shellsOf(host, principal);
2314
- for (const cell of theirs) reset(cell);
2315
- return theirs.length > 0;
3089
+ const theirs2 = shellsOf(host, principal);
3090
+ for (const cell of theirs2) reset(cell);
3091
+ return theirs2.length > 0;
2316
3092
  }
2317
3093
  };
2318
- return { host: handedOut, adopt: () => adoptAll(host), stop: startSweep(host) };
3094
+ return { host: handedOut, adopt: () => adoptAll(host), adoptFor: (principal) => adoptFor(host, principal), stop: startSweep(host) };
2319
3095
  };
2320
3096
 
2321
3097
  // src/server/hosts.ts
2322
- var hostConfig = (deps, shell2, kept) => {
3098
+ var hostConfig = (deps, shell, kept) => {
2323
3099
  const { app, runtime, identity, running, data } = deps;
3100
+ const callerOf = async (principal) => {
3101
+ const resolved = await identity.resolve(principal);
3102
+ return {
3103
+ resolved,
3104
+ roles: resolved.roles,
3105
+ installed: resolved.installed,
3106
+ saved: deps.savedAs(identity.composeScope(principal, resolved)),
3107
+ replayable: () => data.fingerprintsFor(resolved)
3108
+ };
3109
+ };
2324
3110
  return {
2325
- composition: async (principal) => {
2326
- const resolved = await identity.resolve(principal);
2327
- return { roles: resolved.roles, scope: resolved.scope, ...running.artifactsFor(shell2, resolved.roles, resolved.installed) };
3111
+ composition: async (principal, drafted) => {
3112
+ const { resolved, saved, ...held } = await callerOf(principal);
3113
+ const who = { principal, ...held, ...principal === null ? {} : { saved, ...drafted === void 0 ? {} : { drafted } } };
3114
+ return { roles: resolved.roles, scope: resolved.scope, ...await running.artifactsFor(shell, who) };
2328
3115
  },
3116
+ artifacts: (principal) => running.sessionArtifacts(principal, () => callerOf(principal)),
3117
+ draftSaving: (principal) => running.draftSavingFor(shell, principal, () => callerOf(principal)),
2329
3118
  hooks: {
2330
- ...shell2.inputs !== void 0 ? { inputs: shell2.inputs } : {},
2331
- ...shell2.seeds !== void 0 ? { seeds: shell2.seeds } : {},
3119
+ ...shell.inputs !== void 0 ? { inputs: shell.inputs } : {},
3120
+ ...shell.seeds !== void 0 ? { seeds: shell.seeds } : {},
2332
3121
  ...app.phrases !== void 0 ? { phrases: app.phrases } : {},
2333
3122
  ...app.functions !== void 0 ? { functions: app.functions } : {},
2334
3123
  ...app.onSession !== void 0 ? { onSession: app.onSession } : {},
@@ -2340,7 +3129,7 @@ var hostConfig = (deps, shell2, kept) => {
2340
3129
  wrapWire: deps.wrapWire,
2341
3130
  answerIntent: async (principal, writers, asked) => {
2342
3131
  const resolved = await identity.resolve(principal);
2343
- return data.answerIntent(writers, asked, resolved, identity.composeScope(principal, resolved));
3132
+ return data.answerIntent(writers, asked, resolved, callerScope(identity.composeScope(principal, resolved)));
2344
3133
  },
2345
3134
  ...deps.revokeSessions !== void 0 ? { revokeSessions: deps.revokeSessions } : {},
2346
3135
  ...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
@@ -2351,12 +3140,24 @@ var hostConfig = (deps, shell2, kept) => {
2351
3140
  }
2352
3141
  };
2353
3142
  };
3143
+ var checkedOnce = (functions, written) => {
3144
+ let checked2 = false;
3145
+ return (session) => {
3146
+ const given = functions(session);
3147
+ if (!checked2) {
3148
+ written(given);
3149
+ checked2 = true;
3150
+ }
3151
+ return given;
3152
+ };
3153
+ };
2354
3154
  var buildShellHosts = (deps) => {
2355
3155
  const { app } = deps;
3156
+ const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: checkedOnce(app.functions, deps.running.functionsWritten) } };
2356
3157
  const pageManifests = app.pages ?? {};
2357
3158
  const pageRouter = createPageRouter(pageManifests);
2358
- const shells = app.shell !== void 0 ? createShellHost(hostConfig(deps, app.shell, true)) : void 0;
2359
- const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(deps, manifest, false))]));
3159
+ const shells = app.shell !== void 0 ? createShellHost(hostConfig(wired, app.shell, true)) : void 0;
3160
+ const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(wired, manifest, false))]));
2360
3161
  const owned = [...shells !== void 0 ? [shells] : [], ...pageHosts.values()];
2361
3162
  const every = owned.map((made) => made.host);
2362
3163
  return {
@@ -2370,9 +3171,17 @@ var buildShellHosts = (deps) => {
2370
3171
  return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
2371
3172
  },
2372
3173
  pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
3174
+ buildForNobody: async () => {
3175
+ if (app.functions === void 0) deps.running.functionsWritten([]);
3176
+ else await every[0]?.snapshot(null, null, { waitMs: 0 });
3177
+ await deps.running.readPublished();
3178
+ },
2373
3179
  adopt: () => {
2374
3180
  for (const made of owned) made.adopt();
2375
3181
  },
3182
+ adoptFor: (principal) => {
3183
+ for (const made of owned) made.adoptFor(principal);
3184
+ },
2376
3185
  // `map`, not `some`: each host is asked, whatever the one before answered.
2377
3186
  reset: (principal) => every.map((host) => host.reset(principal)).includes(true),
2378
3187
  deliver: (principal, channel, payload) => every.map((host) => host.deliver(principal, channel, payload)).includes(true),
@@ -2420,7 +3229,7 @@ var mountRoutes = (server, { app, session, credentials, identity, running, data
2420
3229
  "/",
2421
3230
  data.routes({
2422
3231
  resources: app.resources,
2423
- scope: (c) => identity.composeScope(c.get("principal"), c.get("resolved")),
3232
+ scope: (c) => callerScope(identity.composeScope(c.get("principal"), c.get("resolved"))),
2424
3233
  caller: (c) => c.get("resolved")
2425
3234
  })
2426
3235
  );
@@ -2477,7 +3286,7 @@ var operatorPrefix = (runtime) => {
2477
3286
  guardOperator(operator, { key: runtime.operatorKey ?? "", gate: runtime.operatorGate });
2478
3287
  return operator;
2479
3288
  };
2480
- var buildSignals = ({ fabric, identity, reset, deliver }) => {
3289
+ var buildSignals = ({ fabric, identity, reset, adopt: adopt2, deliver }) => {
2481
3290
  const origin = crypto$1.randomBytes(8).toString("hex");
2482
3291
  const applyInvalidateIdentity = (principal) => {
2483
3292
  const held = identity.invalidate(principal);
@@ -2491,7 +3300,8 @@ var buildSignals = ({ fabric, identity, reset, deliver }) => {
2491
3300
  const publish = wireFabric(fabric, origin, {
2492
3301
  invalidateIdentity: applyInvalidateIdentity,
2493
3302
  invalidateTag: applyInvalidateTag,
2494
- nudge: applyNudge
3303
+ nudge: applyNudge,
3304
+ adopt: adopt2
2495
3305
  });
2496
3306
  return {
2497
3307
  invalidateIdentity: (principal) => {
@@ -2508,6 +3318,10 @@ var buildSignals = ({ fabric, identity, reset, deliver }) => {
2508
3318
  applyNudge(principal, channel);
2509
3319
  publish({ kind: "nudge", principal, channel });
2510
3320
  },
3321
+ adopt: (principal) => {
3322
+ adopt2(principal);
3323
+ publish({ kind: "adopt", principal });
3324
+ },
2511
3325
  // The payload stays in this process. Across processes only the channel is
2512
3326
  // said, and a shell there reads again under its own policy.
2513
3327
  deliver: (principal, channel, payload) => {
@@ -2522,7 +3336,7 @@ var wireFabric = (fabric, origin, apply) => {
2522
3336
  };
2523
3337
  let refusalSaid = false;
2524
3338
  fabric.subscribe((handed) => {
2525
- const parsed = chunkVBWNHF4H_cjs.FabricMessageSchema.safeParse(handed);
3339
+ const parsed = chunkPVZMCEBX_cjs.FabricMessageSchema.safeParse(handed);
2526
3340
  if (!parsed.success) {
2527
3341
  if (refusalSaid) return;
2528
3342
  refusalSaid = true;
@@ -2543,6 +3357,9 @@ var wireFabric = (fabric, origin, apply) => {
2543
3357
  case "nudge":
2544
3358
  apply.nudge(message.principal, message.channel);
2545
3359
  break;
3360
+ case "adopt":
3361
+ apply.adopt(message.principal);
3362
+ break;
2546
3363
  }
2547
3364
  } catch (err) {
2548
3365
  console.error("[moss:fabric] a remote signal failed to apply", err);
@@ -2559,13 +3376,22 @@ var wireFabric = (fabric, origin, apply) => {
2559
3376
 
2560
3377
  // src/server/server.ts
2561
3378
  var createServerWith = async (app, runtime, dataOf) => {
2562
- receiveManifest(app);
3379
+ chunk3DCTQKPQ_cjs.receiveManifest(app);
2563
3380
  const session = sessionVerifierOf(runtime);
2564
3381
  const revokeSessions = sessionRevokerOf(runtime);
2565
3382
  const data = await dataOf(app, runtime);
2566
3383
  return assembleServer({ app, runtime, session, revokeSessions, data });
2567
3384
  };
2568
3385
  var createServer = (app, runtime) => createServerWith(app, runtime, buildData);
3386
+ var rowRulesBeside = (behaviors) => {
3387
+ const declared = Object.keys(SAVE_ROW_RULES).filter((table) => Object.hasOwn(behaviors ?? {}, table));
3388
+ if (declared.length > 0) {
3389
+ throw new Error(
3390
+ `moss: the app\u2019s \`behaviors\` say what a caller reads and writes of ${declared.map((table) => `"${table}"`).join(" and ")}. Those rows are whoever saved them: moss keeps every read and write of them to the caller\u2019s own, and an app does not say otherwise.`
3391
+ );
3392
+ }
3393
+ return SAVE_ROW_RULES;
3394
+ };
2569
3395
  var buildData = (app, runtime) => createData({
2570
3396
  pool: runtime.pool,
2571
3397
  db: runtime.db,
@@ -2578,6 +3404,7 @@ var buildData = (app, runtime) => createData({
2578
3404
  grammars: app.grammars,
2579
3405
  charter: app.charter,
2580
3406
  behaviors: app.behaviors,
3407
+ rowRules: rowRulesBeside(app.behaviors),
2581
3408
  telemetry: runtime.telemetry
2582
3409
  });
2583
3410
  var assembleServer = async (deps) => {
@@ -2590,25 +3417,36 @@ var assembleServer = async (deps) => {
2590
3417
  }
2591
3418
  };
2592
3419
  var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) => {
2593
- const running = await buildRunningManifest(app, runtime, data);
3420
+ const saved = savedRowsOver(await data.artifactEntries(SAVE_ENTRIES, SAVE_ROW_RULES), data.grammars);
3421
+ const running = await buildRunningManifest(app, runtime, data, saved);
2594
3422
  stops.push(running.stop);
3423
+ if (runtime.artifactsUnusedMs !== void 0) {
3424
+ if (!Number.isSafeInteger(runtime.artifactsUnusedMs) || runtime.artifactsUnusedMs < 2 * TOUCH_EVERY_MS) {
3425
+ throw new Error(
3426
+ `moss: \`runtime.artifactsUnusedMs\` is how long what a person generated may go unused before it is deleted: a whole number of milliseconds, at least ${2 * TOUCH_EVERY_MS} (two hours), or left out, and nothing is deleted.`
3427
+ );
3428
+ }
3429
+ stops.push(startAging(runtime.pool, runtime.artifactsUnusedMs));
3430
+ }
2595
3431
  const identity = buildIdentity(app, runtime, data);
2596
3432
  stops.push(identity.stop);
2597
3433
  const server = new hono.Hono();
2598
3434
  const registered = emptyRegister();
2599
3435
  mountRoutes(server, { app, session, credentials: registered.credentials, identity, running, data });
2600
- const hosts = buildShellHosts({ app, runtime, identity, running, data, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
3436
+ const hosts = buildShellHosts({ app, runtime, identity, running, data, savedAs: saved.of, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
2601
3437
  stops.push(hosts.stop);
2602
- const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, deliver: hosts.deliver });
3438
+ const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, adopt: hosts.adoptFor, deliver: hosts.deliver });
2603
3439
  running.onChange(() => {
2604
3440
  identity.invalidateAll();
2605
3441
  hosts.adopt();
2606
3442
  });
3443
+ running.onChangeFor(signals.adopt);
2607
3444
  const operator = operatorPrefix(runtime);
2608
3445
  await startFeatures(app.features ?? [], { app, runtime, server, operator, registered, identity, running, data });
2609
3446
  server.route("/operator", operator);
2610
3447
  subscribeReactions({ app, onWrite: data.onWrite, deliver: signals.deliver });
2611
3448
  running.watch();
3449
+ await running.readPublished();
2612
3450
  const socket = buildSocket({ runtime, session, identity, running, hosts });
2613
3451
  stops.push(socket.stop);
2614
3452
  return Object.assign(server, {
@@ -2616,10 +3454,21 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
2616
3454
  principalOf: async (token) => session(token),
2617
3455
  page: hosts.pageAt,
2618
3456
  pages: hosts.pages,
3457
+ checkFunctions: hosts.buildForNobody,
2619
3458
  ...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
2620
3459
  refresh: running.refresh,
2621
3460
  replaceActions: running.replace,
3461
+ replaceEntries: running.replaceEntries,
2622
3462
  actions: running.actions,
3463
+ defaults: (publisher) => {
3464
+ if (typeof publisher !== "string" || publisher === "") {
3465
+ throw new Error("moss: `defaults` is handed who publishes. What is published is everybody\u2019s, and who published it is kept with it.");
3466
+ }
3467
+ return running.publishedArtifacts(saved.published(publisher), async () => {
3468
+ const resolved = await identity.resolve(publisher);
3469
+ return { roles: resolved.roles, replayable: () => data.fingerprintsFor(resolved) };
3470
+ });
3471
+ },
2623
3472
  catalogOf: async (principal) => {
2624
3473
  const resolved = await identity.resolve(principal);
2625
3474
  return running.catalogFor(resolved.roles, resolved.installed);
@@ -2640,15 +3489,18 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
2640
3489
  ...identity.roster !== void 0 ? { identities: identity.roster } : {}
2641
3490
  });
2642
3491
  };
2643
- var buildRunningManifest = async (app, runtime, data) => {
3492
+ var buildRunningManifest = async (app, runtime, data, saved) => {
2644
3493
  const running = createRunningManifest({
2645
3494
  shipped: app,
2646
3495
  grants: data.grants,
2647
3496
  // Polled on the clock a socket's credential is re-verified on.
2648
- pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} }
3497
+ pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} },
3498
+ shells: [...app.shell !== void 0 ? [app.shell] : [], ...Object.values(app.pages ?? {})],
3499
+ ...saved !== void 0 ? { published: saved.published().inForce, reads: { written: data.vexEntry, compile: data.compileQuery, savedOf: saved.of } } : {}
2649
3500
  });
2650
3501
  data.dropOnChange(running.onChange);
2651
- await data.seed(running.entries());
3502
+ data.entriesHeldBy({ get: running.cacheEntry, entries: running.cacheEntries });
3503
+ await running.cacheEntries();
2652
3504
  return running;
2653
3505
  };
2654
3506
  var buildIdentity = (app, runtime, data) => createIdentity({
@@ -2703,7 +3555,6 @@ var subscribeReactions = ({ app, onWrite, deliver }) => {
2703
3555
 
2704
3556
  exports.MOSS_SEQUENCE = MOSS_SEQUENCE;
2705
3557
  exports.createServer = createServer;
2706
- exports.defineApp = defineApp;
2707
3558
  exports.exportDocuments = exportDocuments;
2708
3559
  exports.migrateTables = migrateTables;
2709
3560
  exports.mintDevToken = mintDevToken;
@@ -2711,6 +3562,5 @@ exports.mintSession = mintSession;
2711
3562
  exports.renderDocument = renderDocument;
2712
3563
  exports.revokeAllFor = revokeAllFor;
2713
3564
  exports.sessionCookies = sessionCookies;
2714
- exports.verifyApp = verifyApp;
2715
- //# sourceMappingURL=chunk-R66WUKGC.cjs.map
2716
- //# sourceMappingURL=chunk-R66WUKGC.cjs.map
3565
+ //# sourceMappingURL=chunk-TMDKNZYL.cjs.map
3566
+ //# sourceMappingURL=chunk-TMDKNZYL.cjs.map