@niscorp/moss 0.9.3 → 0.10.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 (108) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/DESIGN.md +58 -55
  3. package/DOCS.md +259 -168
  4. package/README.md +5 -5
  5. package/dist/{chunk-PVZMCEBX.cjs → chunk-3CKBKTXA.cjs} +2 -2
  6. package/dist/chunk-3CKBKTXA.cjs.map +1 -0
  7. package/dist/{chunk-TAAKHW3U.js → chunk-3PL4AH4I.js} +4 -4
  8. package/dist/{chunk-TAAKHW3U.js.map → chunk-3PL4AH4I.js.map} +1 -1
  9. package/dist/{chunk-QAHDSRPK.js → chunk-4URQHVYG.js} +2 -2
  10. package/dist/chunk-4URQHVYG.js.map +1 -0
  11. package/dist/{chunk-U43CBKKE.cjs → chunk-6ACVHHFK.cjs} +32 -30
  12. package/dist/chunk-6ACVHHFK.cjs.map +1 -0
  13. package/dist/{chunk-IUJ2TRNB.cjs → chunk-7MOEKAVC.cjs} +6 -6
  14. package/dist/{chunk-IUJ2TRNB.cjs.map → chunk-7MOEKAVC.cjs.map} +1 -1
  15. package/dist/{chunk-NCQBGK3E.cjs → chunk-BFA76AKR.cjs} +4 -4
  16. package/dist/chunk-BFA76AKR.cjs.map +1 -0
  17. package/dist/{chunk-T5BRTFKP.js → chunk-DSVRFAGX.js} +3 -3
  18. package/dist/{chunk-T5BRTFKP.js.map → chunk-DSVRFAGX.js.map} +1 -1
  19. package/dist/{chunk-IW3A2YIC.js → chunk-EYWD733E.js} +3 -3
  20. package/dist/{chunk-IW3A2YIC.js.map → chunk-EYWD733E.js.map} +1 -1
  21. package/dist/{chunk-IY5BOFLK.cjs → chunk-G4P3XEVM.cjs} +19 -19
  22. package/dist/chunk-G4P3XEVM.cjs.map +1 -0
  23. package/dist/{chunk-6QPTMKRE.cjs → chunk-HUP7CZ7X.cjs} +6 -6
  24. package/dist/{chunk-6QPTMKRE.cjs.map → chunk-HUP7CZ7X.cjs.map} +1 -1
  25. package/dist/{chunk-VKQPOZDJ.cjs → chunk-LTS4AM6T.cjs} +4 -4
  26. package/dist/chunk-LTS4AM6T.cjs.map +1 -0
  27. package/dist/{chunk-UTFOMFCH.js → chunk-MEHCZECW.js} +5 -5
  28. package/dist/chunk-MEHCZECW.js.map +1 -0
  29. package/dist/{chunk-6MZPY4X6.js → chunk-MYPK5YZR.js} +249 -199
  30. package/dist/chunk-MYPK5YZR.js.map +1 -0
  31. package/dist/{chunk-TKXYPO2Y.js → chunk-NUX5MH4I.js} +4 -4
  32. package/dist/chunk-NUX5MH4I.js.map +1 -0
  33. package/dist/{chunk-EXMOO7ZR.cjs → chunk-UVY5ZPWW.cjs} +326 -276
  34. package/dist/chunk-UVY5ZPWW.cjs.map +1 -0
  35. package/dist/{chunk-MVG333UF.js → chunk-VYYDLGQ2.js} +27 -25
  36. package/dist/chunk-VYYDLGQ2.js.map +1 -0
  37. package/dist/{chunk-NRZ3Z2FF.js → chunk-WKZWSWOJ.js} +4 -4
  38. package/dist/chunk-WKZWSWOJ.js.map +1 -0
  39. package/dist/{chunk-YGZS5B2U.cjs → chunk-XH6TSWG4.cjs} +7 -7
  40. package/dist/{chunk-YGZS5B2U.cjs.map → chunk-XH6TSWG4.cjs.map} +1 -1
  41. package/dist/client.cjs +5 -5
  42. package/dist/client.js +2 -2
  43. package/dist/{document-CuF4JqzJ.d.cts → document-DvhT_HaJ.d.cts} +1 -1
  44. package/dist/{document-BzXQvEc1.d.ts → document-iKaRinZE.d.ts} +1 -1
  45. package/dist/{index-CSEo7Tys.d.cts → index-DWj3_0Zg.d.cts} +3 -0
  46. package/dist/{index-CSEo7Tys.d.ts → index-DWj3_0Zg.d.ts} +3 -0
  47. package/dist/index.cjs +16 -16
  48. package/dist/index.d.cts +4 -4
  49. package/dist/index.d.ts +4 -4
  50. package/dist/index.js +4 -4
  51. package/dist/integrations.cjs +27 -18
  52. package/dist/integrations.cjs.map +1 -1
  53. package/dist/integrations.d.cts +1 -1
  54. package/dist/integrations.d.ts +1 -1
  55. package/dist/integrations.js +25 -16
  56. package/dist/integrations.js.map +1 -1
  57. package/dist/node.cjs +9 -9
  58. package/dist/node.d.cts +2 -2
  59. package/dist/node.d.ts +2 -2
  60. package/dist/node.js +5 -5
  61. package/dist/protocol.cjs +5 -5
  62. package/dist/protocol.js +1 -1
  63. package/dist/terminal/dom/index.cjs +3 -3
  64. package/dist/terminal/dom/index.js +1 -1
  65. package/dist/terminal/dom/server.cjs +2 -2
  66. package/dist/terminal/dom/server.js +1 -1
  67. package/dist/terminal/index.cjs +3 -3
  68. package/dist/terminal/index.js +2 -2
  69. package/dist/terminal/ink/index.js.map +1 -1
  70. package/dist/terminal/react/index.cjs +9 -9
  71. package/dist/terminal/react/index.cjs.map +1 -1
  72. package/dist/terminal/react/index.js +4 -4
  73. package/dist/terminal/react/index.js.map +1 -1
  74. package/dist/terminal/react/server.cjs +4 -4
  75. package/dist/terminal/react/server.js +2 -2
  76. package/dist/terminal/tty/index.cjs +12 -12
  77. package/dist/terminal/tty/index.cjs.map +1 -1
  78. package/dist/terminal/tty/index.js +6 -6
  79. package/dist/terminal/tty/index.js.map +1 -1
  80. package/dist/terminal/vue/index.cjs +9 -9
  81. package/dist/terminal/vue/index.cjs.map +1 -1
  82. package/dist/terminal/vue/index.js +4 -4
  83. package/dist/terminal/vue/index.js.map +1 -1
  84. package/dist/terminal/vue/server.cjs +4 -4
  85. package/dist/terminal/vue/server.js +2 -2
  86. package/dist/tide.d.cts +1 -1
  87. package/dist/tide.d.ts +1 -1
  88. package/dist/unverified.cjs +4 -4
  89. package/dist/unverified.js +3 -3
  90. package/dist/vite.cjs +36 -10
  91. package/dist/vite.cjs.map +1 -1
  92. package/dist/vite.d.cts +2 -2
  93. package/dist/vite.d.ts +2 -2
  94. package/dist/vite.js +31 -5
  95. package/dist/vite.js.map +1 -1
  96. package/package.json +13 -13
  97. package/dist/chunk-6MZPY4X6.js.map +0 -1
  98. package/dist/chunk-EXMOO7ZR.cjs.map +0 -1
  99. package/dist/chunk-IY5BOFLK.cjs.map +0 -1
  100. package/dist/chunk-MVG333UF.js.map +0 -1
  101. package/dist/chunk-NCQBGK3E.cjs.map +0 -1
  102. package/dist/chunk-NRZ3Z2FF.js.map +0 -1
  103. package/dist/chunk-PVZMCEBX.cjs.map +0 -1
  104. package/dist/chunk-QAHDSRPK.js.map +0 -1
  105. package/dist/chunk-TKXYPO2Y.js.map +0 -1
  106. package/dist/chunk-U43CBKKE.cjs.map +0 -1
  107. package/dist/chunk-UTFOMFCH.js.map +0 -1
  108. package/dist/chunk-VKQPOZDJ.cjs.map +0 -1
@@ -1,6 +1,6 @@
1
- import { entriesOf, receiveManifest, verifiedAtBoot, verifyManifest, withFragments, candidateOf, FRAME_LAYOUT_REF, canvasLayoutRef, functionsIn, charterOverFunctions, refusalOf, functionsWarning, layoutMisfits, freezeDeep, entryMisfits, sessionOn, endlessChains, actionLayoutRef, endShell, GENERATED_ID_PREFIX, layoutNameRefusal, actionOfLayoutRef, withLayoutInPlace, canvasesOf, treeOf, buildShell, SHELL_GONE, draftedIn, attach, holdGranted, layoutsOf, withVariants, variantLayouts } from './chunk-MVG333UF.js';
2
- import { emitterOf, FabricMessageSchema, spanClock } from './chunk-QAHDSRPK.js';
3
- import { DEFAULT_TOKEN_KEY, sessionNameOf, SNAPSHOT_ELEMENT_ID, CLOSE_SHELL_FAILED, CLOSE_PROTOCOL_MISMATCH, CLOSE_INVALID_TOKEN, CLOSE_AT_CAPACITY, PROTOCOL_MIN, PROTOCOL, offeredSealed, offeredToken, ClientMessageSchema } from './chunk-TKXYPO2Y.js';
1
+ import { entriesOf, receiveManifest, verifiedAtBoot, verifyManifest, withFragments, candidateOf, FRAME_LAYOUT_REF, canvasLayoutRef, functionsIn, charterOverFunctions, refusalOf, functionsWarning, layoutMisfits, freezeDeep, entryMisfits, sessionOn, endlessChains, actionLayoutRef, endShell, GENERATED_ID_PREFIX, layoutNameRefusal, actionOfLayoutRef, withLayoutInPlace, canvasesOf, treeOf, buildShell, SHELL_GONE, draftedIn, attach, keepGranted, layoutsOf, withVariants, variantLayouts } from './chunk-VYYDLGQ2.js';
2
+ import { emitterOf, FabricMessageSchema, spanClock } from './chunk-4URQHVYG.js';
3
+ import { DEFAULT_TOKEN_KEY, sessionNameOf, SNAPSHOT_ELEMENT_ID, CLOSE_SHELL_FAILED, CLOSE_PROTOCOL_MISMATCH, CLOSE_INVALID_TOKEN, CLOSE_AT_CAPACITY, PROTOCOL_MIN, PROTOCOL, offeredSealed, offeredToken, ClientMessageSchema } from './chunk-NUX5MH4I.js';
4
4
  import { z } from 'zod';
5
5
  import { randomBytes, createHash, timingSafeEqual, randomUUID } from 'crypto';
6
6
  import { createPostgresCache, createPostgresAdapter, resolve, pruneOptional, mutationMisfits, createMemoryCache, seedCache, handleDiscovery, handleQuery, mergeScopePolicies, createScopePolicy, createQueryEngine, scopeGrants, tablesChangedBy } from '@niscorp/vex';
@@ -37,7 +37,9 @@ var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
37
37
  var ownOriginOf = (origin, host, listed2 = []) => {
38
38
  if (origin === void 0 || origin === null || !URL.canParse(origin)) return void 0;
39
39
  const asked = new URL(origin);
40
- const own = asked.host === host?.toLowerCase() || listed2.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
40
+ const named = host?.toLowerCase();
41
+ const schemePort = asked.protocol === "https:" ? "443" : asked.protocol === "http:" ? "80" : void 0;
42
+ const own = asked.host === named || schemePort !== void 0 && asked.port === "" && `${asked.host}:${schemePort}` === named || listed2.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
41
43
  return own ? asked : void 0;
42
44
  };
43
45
  var cookiesAt = (where, key, token, lastsMs) => {
@@ -162,8 +164,8 @@ var devSession = (token) => {
162
164
  var DEFAULT_IDENTITY_MAX = 1e4;
163
165
  var DEFAULT_IDENTITY_IDLE_MS = 30 * 60 * 1e3;
164
166
  var SWEEP_EVERY_MS = 60 * 1e3;
165
- var createHeldRecords = (max) => {
166
- const held = /* @__PURE__ */ new Map();
167
+ var createResidentRecords = (max) => {
168
+ const resident = /* @__PURE__ */ new Map();
167
169
  const tagged = /* @__PURE__ */ new Map();
168
170
  let evicted = 0;
169
171
  const untag = (principal, record) => {
@@ -175,22 +177,22 @@ var createHeldRecords = (max) => {
175
177
  if (group.size === 0) tagged.delete(tag);
176
178
  };
177
179
  const forget = (principal) => {
178
- const entry = held.get(principal);
180
+ const entry = resident.get(principal);
179
181
  if (entry === void 0) return false;
180
182
  untag(principal, entry.record);
181
- held.delete(principal);
183
+ resident.delete(principal);
182
184
  return true;
183
185
  };
184
186
  const evictOldest = () => {
185
- const oldest = held.keys().next();
187
+ const oldest = resident.keys().next();
186
188
  if (oldest.done === true) return;
187
189
  forget(oldest.value);
188
190
  evicted += 1;
189
191
  };
190
192
  const remember = (principal, record, at) => {
191
193
  forget(principal);
192
- while (held.size >= max) evictOldest();
193
- held.set(principal, { record, since: at, lastSeen: at });
194
+ while (resident.size >= max) evictOldest();
195
+ resident.set(principal, { record, since: at, lastSeen: at });
194
196
  if (record.tag !== void 0) {
195
197
  const group = tagged.get(record.tag) ?? /* @__PURE__ */ new Set();
196
198
  group.add(principal);
@@ -198,16 +200,16 @@ var createHeldRecords = (max) => {
198
200
  }
199
201
  };
200
202
  return {
201
- of: (principal) => held.get(principal),
203
+ of: (principal) => resident.get(principal),
202
204
  touch: (principal, entry, at) => {
203
- held.delete(principal);
205
+ resident.delete(principal);
204
206
  entry.lastSeen = at;
205
- held.set(principal, entry);
207
+ resident.set(principal, entry);
206
208
  },
207
209
  forget,
208
210
  remember,
209
211
  forgetAll: () => {
210
- held.clear();
212
+ resident.clear();
211
213
  tagged.clear();
212
214
  },
213
215
  forgetTag: (tag) => {
@@ -216,15 +218,15 @@ var createHeldRecords = (max) => {
216
218
  return principals;
217
219
  },
218
220
  forgetIdle: (at, idleMs) => {
219
- for (const [principal, entry] of [...held]) {
221
+ for (const [principal, entry] of [...resident]) {
220
222
  if (at - entry.lastSeen >= idleMs) {
221
223
  forget(principal);
222
224
  evicted += 1;
223
225
  }
224
226
  }
225
227
  },
226
- list: () => [...held].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),
227
- size: () => held.size,
228
+ list: () => [...resident].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),
229
+ size: () => resident.size,
228
230
  evicted: () => evicted
229
231
  };
230
232
  };
@@ -236,17 +238,17 @@ var createIdentityCache = (ctx) => {
236
238
  const idleMs = ctx.idleMs ?? DEFAULT_IDENTITY_IDLE_MS;
237
239
  const revalidateMs = ctx.revalidateMs ?? 0;
238
240
  const now = ctx.now ?? Date.now;
239
- const held = createHeldRecords(max);
241
+ const records = createResidentRecords(max);
240
242
  const pending = /* @__PURE__ */ new Map();
241
243
  let resolved = 0;
242
244
  let expired = 0;
243
245
  const get = async (principal) => {
244
246
  const at = now();
245
- const hit = held.of(principal);
247
+ const hit = records.of(principal);
246
248
  if (hit !== void 0) {
247
249
  const stale = revalidateMs > 0 && at - hit.since >= revalidateMs;
248
250
  if (!stale) {
249
- held.touch(principal, hit, at);
251
+ records.touch(principal, hit, at);
250
252
  return hit.record;
251
253
  }
252
254
  expired += 1;
@@ -258,7 +260,7 @@ var createIdentityCache = (ctx) => {
258
260
  const work = ctx.resolve(principal).then((record) => {
259
261
  resolved += 1;
260
262
  const wearsForgottenTag = record.tag !== void 0 && forgotten.has(record.tag);
261
- if (isStillOut() && !wearsForgottenTag) held.remember(principal, record, now());
263
+ if (isStillOut() && !wearsForgottenTag) records.remember(principal, record, now());
262
264
  return record;
263
265
  }).finally(() => {
264
266
  if (isStillOut()) pending.delete(principal);
@@ -266,26 +268,26 @@ var createIdentityCache = (ctx) => {
266
268
  pending.set(principal, { work, forgotten });
267
269
  return work;
268
270
  };
269
- const sweep2 = idleMs > 0 ? setInterval(() => held.forgetIdle(now(), idleMs), Math.min(SWEEP_EVERY_MS, idleMs)) : void 0;
271
+ const sweep2 = idleMs > 0 ? setInterval(() => records.forgetIdle(now(), idleMs), Math.min(SWEEP_EVERY_MS, idleMs)) : void 0;
270
272
  sweep2?.unref?.();
271
273
  return {
272
274
  get,
273
275
  invalidate: (principal) => {
274
276
  pending.delete(principal);
275
- return held.forget(principal);
277
+ return records.forget(principal);
276
278
  },
277
279
  invalidateAll: () => {
278
- held.forgetAll();
280
+ records.forgetAll();
279
281
  pending.clear();
280
282
  },
281
283
  invalidateTag: (tag) => {
282
- const principals = held.forgetTag(tag);
284
+ const principals = records.forgetTag(tag);
283
285
  for (const principal of principals) pending.delete(principal);
284
286
  for (const flight of pending.values()) flight.forgotten.add(tag);
285
287
  return principals;
286
288
  },
287
- list: held.list,
288
- meter: () => ({ size: held.size(), max, resolved, evicted: held.evicted(), expired }),
289
+ list: records.list,
290
+ meter: () => ({ size: records.size(), max, resolved, evicted: records.evicted(), expired }),
289
291
  stop: () => {
290
292
  if (sweep2 !== void 0) clearInterval(sweep2);
291
293
  }
@@ -293,7 +295,7 @@ var createIdentityCache = (ctx) => {
293
295
  };
294
296
  var memoKey = (roles, installed) => `${[...roles].sort().join("\0")}\0\0${installed === void 0 ? "*" : [...installed].sort().join("\0")}`;
295
297
  var NOBODY_USER_ID = "anonymous";
296
- var assignedRoles = (assignments, principal) => principal === null ? ["public"] : assignments?.[principal] ?? ["public"];
298
+ var assignedRoles = (assignments, principal) => principal === null || assignments === void 0 || !Object.hasOwn(assignments, principal) ? ["public"] : assignments[principal] ?? ["public"];
297
299
  var IdentityRecordSchema = z.looseObject({
298
300
  roles: z.array(z.string()),
299
301
  scope: z.record(z.string(), z.unknown()),
@@ -580,10 +582,10 @@ var canonical = (value) => {
580
582
  return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
581
583
  };
582
584
  var isSeededAs = async (cache, entry) => {
583
- const held = await cache.get(entry.fingerprint);
584
- if (held === void 0 || held.protected !== true) return false;
585
- if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
586
- return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
585
+ const cached = await cache.get(entry.fingerprint);
586
+ if (cached === void 0 || cached.protected !== true) return false;
587
+ if ("mutation" in entry) return cached.kind === "mutation" && canonical(cached.mutation) === canonical(entry.mutation);
588
+ return cached.kind === "ok" && canonical(cached.dsl) === canonical(entry.dsl);
587
589
  };
588
590
  var changesBetween = (before, after) => {
589
591
  const removed = [];
@@ -680,8 +682,10 @@ var sweepUnused = async (pool, unusedMs) => {
680
682
  return { versions, saves };
681
683
  };
682
684
  var AGING_EVERY_MS = 36e5;
683
- var startAging = (pool, unusedMs, everyMs = AGING_EVERY_MS) => {
685
+ var startAging = (pool, unusedMs, { everyMs = AGING_EVERY_MS, sinceStart = false } = {}) => {
686
+ const startedAt = Date.now();
684
687
  const sweep2 = async () => {
688
+ if (sinceStart && Date.now() - startedAt < unusedMs) return;
685
689
  try {
686
690
  const swept = await sweepUnused(pool, unusedMs);
687
691
  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`);
@@ -691,11 +695,12 @@ var startAging = (pool, unusedMs, everyMs = AGING_EVERY_MS) => {
691
695
  };
692
696
  void sweep2();
693
697
  const timer = setInterval(() => void sweep2(), everyMs);
698
+ timer.unref?.();
694
699
  return () => clearInterval(timer);
695
700
  };
696
701
  var isWrittenForRequest = (entry) => entry.kind === "unsatisfiable" || entry.requestHash !== void 0;
697
702
  var createEntryCache = (table) => {
698
- let held;
703
+ let askedFirst;
699
704
  const fromTable = (entry) => entry !== void 0 && isWrittenForRequest(entry) ? entry : void 0;
700
705
  const tableEntries = async () => {
701
706
  const rows = table.entries !== void 0 ? await table.entries() : await Promise.all((await table.keys()).map(async (key) => ({ key, entry: await table.get(key) })));
@@ -705,16 +710,16 @@ var createEntryCache = (table) => {
705
710
  });
706
711
  };
707
712
  const entries = async () => {
708
- const first = await held?.entries() ?? [];
713
+ const first = await askedFirst?.entries() ?? [];
709
714
  const answered = new Set(first.map((row) => row.key));
710
715
  return [...first, ...(await tableEntries()).filter((row) => !answered.has(row.key))];
711
716
  };
712
717
  return {
713
- askFirst: (holder) => {
714
- held = holder;
718
+ askFirst: (first) => {
719
+ askedFirst = first;
715
720
  },
716
721
  cache: {
717
- get: async (key, scope) => await held?.get(key, scope) ?? fromTable(await table.get(key)),
722
+ get: async (key, scope) => await askedFirst?.get(key, scope) ?? fromTable(await table.get(key)),
718
723
  // 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.
719
724
  set: async (key, entry) => {
720
725
  if (isWrittenForRequest(entry)) await table.set(key, entry);
@@ -870,7 +875,7 @@ var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) =
870
875
  locked: true,
871
876
  scopePolicy: policy,
872
877
  policyForReach: (reach) => deps.policyAtReach(roles, reach),
873
- mutations: { client: deps.db, policy },
878
+ mutations: { client: deps.db, policy, ...deps.checkMovedRows === false ? { checkMovedRows: false } : {} },
874
879
  ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
875
880
  },
876
881
  { fingerprint, context },
@@ -973,7 +978,12 @@ var createVexRoutes = (deps) => {
973
978
  getPolicy: deps.policy,
974
979
  getPolicyForReach: deps.policyAtReach,
975
980
  ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
976
- mutations: { client: deps.db, onWrite: deps.writes.report }
981
+ mutations: {
982
+ client: deps.db,
983
+ onWrite: deps.writes.report,
984
+ ...deps.answerReadableRows === true ? { answerReadableRows: true } : {},
985
+ ...deps.checkMovedRows === false ? { checkMovedRows: false } : {}
986
+ }
977
987
  })
978
988
  );
979
989
  };
@@ -1007,7 +1017,7 @@ var createIntentAnswers = (deps) => {
1007
1017
  };
1008
1018
  return async (writers, asked, caller) => (await engineFor(writers)).execute(
1009
1019
  "fingerprint" in asked ? { fingerprint: asked.fingerprint, context: asked.context ?? {} } : { intent: asked.intent, shape: asked.shape, context: asked.context ?? {} },
1010
- { scope: caller.scope, scopePolicy: caller.policy }
1020
+ { scope: caller.scope, scopePolicy: caller.policy, ...caller.policyAtReach !== void 0 ? { policyForReach: caller.policyAtReach } : {} }
1011
1021
  );
1012
1022
  };
1013
1023
 
@@ -1105,7 +1115,7 @@ var createDataWith = (prepared, config) => {
1105
1115
  return {
1106
1116
  grants,
1107
1117
  grammars,
1108
- entriesHeldBy: prepared.askFirst,
1118
+ askEntriesFirst: prepared.askFirst,
1109
1119
  fingerprints: async () => await engine.cache.keys?.() ?? [],
1110
1120
  policyOf: policies.of,
1111
1121
  // Compiled afresh and not taken from the kept ones: the caller owns its
@@ -1121,9 +1131,10 @@ var createDataWith = (prepared, config) => {
1121
1131
  db: config.db,
1122
1132
  policyFor: (roles) => policies.of(callerOfRoles(roles)),
1123
1133
  policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
1124
- ...onExecute !== void 0 ? { onExecute } : {}
1134
+ ...onExecute !== void 0 ? { onExecute } : {},
1135
+ ...config.checkMovedRows === false ? { checkMovedRows: false } : {}
1125
1136
  }),
1126
- answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
1137
+ answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), policyAtReach: (reach) => policies.atReach(who, reach), scope }),
1127
1138
  ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
1128
1139
  artifactEntries: (entries, rules) => ownEntries({ owner: "the artifactory", entries, tables: ARTIFACT_TABLES, rules }, onExecute),
1129
1140
  routes: (routing) => createVexRoutes({
@@ -1134,7 +1145,9 @@ var createDataWith = (prepared, config) => {
1134
1145
  policy: (c) => policies.of(routing.caller(c)),
1135
1146
  policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
1136
1147
  ...onExecute !== void 0 ? { onExecute } : {},
1137
- writes
1148
+ writes,
1149
+ ...config.answerReadableRows === true ? { answerReadableRows: true } : {},
1150
+ ...config.checkMovedRows === false ? { checkMovedRows: false } : {}
1138
1151
  }),
1139
1152
  upgradeStore: createUpgradeStore(prepared, tablesOf),
1140
1153
  onWrite: writes.subscribe,
@@ -1153,7 +1166,7 @@ var embedSnapshot = (snapshot, principal, path) => {
1153
1166
  return `<script type="application/json" id="${SNAPSHOT_ELEMENT_ID}">${text}</script>`;
1154
1167
  };
1155
1168
  var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
1156
- var rootHolding = (root) => {
1169
+ var screenInRoot = (root) => {
1157
1170
  const closing = root.lastIndexOf("</");
1158
1171
  if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
1159
1172
  return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
@@ -1165,8 +1178,8 @@ var renderDocument = async (config) => {
1165
1178
  const root = config.root ?? DEFAULT_ROOT;
1166
1179
  const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
1167
1180
  if (!template.includes(root)) return undrawn;
1168
- const holding = rootHolding(root);
1169
- if (holding === void 0) {
1181
+ const inRoot = screenInRoot(root);
1182
+ if (inRoot === void 0) {
1170
1183
  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.`);
1171
1184
  return undrawn;
1172
1185
  }
@@ -1183,7 +1196,7 @@ var renderDocument = async (config) => {
1183
1196
  });
1184
1197
  const screen = await draw(snapshot);
1185
1198
  const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
1186
- const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
1199
+ const placed = template.replace(root, () => `${inRoot(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
1187
1200
  const head = headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
1188
1201
  for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
1189
1202
  const html = placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
@@ -1357,16 +1370,16 @@ var actionAtRef = (actions, layouts) => (ref) => {
1357
1370
  return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
1358
1371
  };
1359
1372
  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>".`;
1360
- var targetAt = (ref, heldTo) => {
1361
- if (heldTo.ownShell?.refs.has(ref) === true) return { kit: heldTo.ownShell.kit };
1362
- const action = heldTo.actionAt(ref);
1363
- return action === void 0 ? void 0 : { kit: heldTo.kit, action };
1373
+ var targetAt = (ref, checks) => {
1374
+ if (checks.ownShell?.refs.has(ref) === true) return { kit: checks.ownShell.kit };
1375
+ const action = checks.actionAt(ref);
1376
+ return action === void 0 ? void 0 : { kit: checks.kit, action };
1364
1377
  };
1365
1378
  var refOf = (body) => {
1366
1379
  const ref = isRecord(body) ? body["ref"] : void 0;
1367
1380
  return typeof ref === "string" ? ref : void 0;
1368
1381
  };
1369
- var readLayout = (body, heldTo) => {
1382
+ var readLayout = (body, checks) => {
1370
1383
  if (exceedsDepth(body)) return { refusal: depthRefusal() };
1371
1384
  const parsed = SavedLayoutSchema.safeParse(body);
1372
1385
  if (!parsed.success) {
@@ -1374,7 +1387,7 @@ var readLayout = (body, heldTo) => {
1374
1387
  return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1375
1388
  }
1376
1389
  const { ref, layout } = parsed.data;
1377
- const target = targetAt(ref, heldTo);
1390
+ const target = targetAt(ref, checks);
1378
1391
  if (target === void 0) return { refusal: nothingKeptUnder(ref) };
1379
1392
  const misfits = layoutMisfits(layout, target.kit);
1380
1393
  if (misfits.length > 0) return { refusal: misfits.join("; ") };
@@ -1387,10 +1400,10 @@ var readLayout = (body, heldTo) => {
1387
1400
  if (added.length > 0) return { refusal: added.join("; ") };
1388
1401
  return { layout: parsed.data };
1389
1402
  };
1390
- var loaded = (version, { whose, heldTo, say }) => {
1403
+ var loaded = (version, { whose, checks, say }) => {
1391
1404
  const ref = refOf(version.body);
1392
- if (ref === void 0 || targetAt(ref, heldTo) === void 0) return void 0;
1393
- const read2 = version.unread !== void 0 ? { refusal: version.unread } : readLayout(version.body, heldTo);
1405
+ if (ref === void 0 || targetAt(ref, checks) === void 0) return void 0;
1406
+ const read2 = version.unread !== void 0 ? { refusal: version.unread } : readLayout(version.body, checks);
1394
1407
  if ("layout" in read2) return read2.layout;
1395
1408
  (say ?? console.error)(`[moss] the layout "${version.id}" ${whose} is left out: ${read2.refusal}`);
1396
1409
  return void 0;
@@ -1402,8 +1415,8 @@ var layoutsInUse = (inForce2, drawnFor) => {
1402
1415
  for (const version of inForce2.filter(isInUse)) {
1403
1416
  const ref = refOf(version.body);
1404
1417
  if (ref === void 0) continue;
1405
- const held = marked.get(ref);
1406
- if (held === void 0 || isLater(version, held)) marked.set(ref, version);
1418
+ const latest = marked.get(ref);
1419
+ if (latest === void 0 || isLater(version, latest)) marked.set(ref, version);
1407
1420
  }
1408
1421
  const layouts = {};
1409
1422
  for (const version of marked.values()) {
@@ -1414,12 +1427,12 @@ var layoutsInUse = (inForce2, drawnFor) => {
1414
1427
  };
1415
1428
  var generatedId = () => `${GENERATED_ID_PREFIX}${randomUUID()}`;
1416
1429
  var VEX_ROUTE = /^\/api\/(?:[A-Za-z0-9_-]+\/)?vex$/;
1417
- var endpointRefusals = async (endpoints, heldTo) => {
1430
+ var endpointRefusals = async (endpoints, checks) => {
1418
1431
  const refusals = [];
1419
1432
  for (const [name, endpoint] of Object.entries(endpoints ?? {})) {
1420
1433
  if ("fn" in endpoint) {
1421
1434
  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`);
1422
- else if (!heldTo.mayCall(endpoint.fn)) refusals.push(`endpoint "${name}" calls the function "${endpoint.fn}", which its owner\u2019s roles do not grant`);
1435
+ else if (!checks.mayCall(endpoint.fn)) refusals.push(`endpoint "${name}" calls the function "${endpoint.fn}", which its owner\u2019s roles do not grant`);
1423
1436
  continue;
1424
1437
  }
1425
1438
  if (endpoint.method !== "POST" || !VEX_ROUTE.test(endpoint.url)) {
@@ -1431,10 +1444,10 @@ var endpointRefusals = async (endpoints, heldTo) => {
1431
1444
  refusals.push(`endpoint "${name}" names no fingerprint`);
1432
1445
  continue;
1433
1446
  }
1434
- const entry = heldTo.entryOf(fingerprint);
1447
+ const entry = checks.entryOf(fingerprint);
1435
1448
  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`);
1436
1449
  else if ("mutation" in entry) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is a write, and what is generated only reads`);
1437
- else if (!(await heldTo.replayable()).has(fingerprint)) refusals.push(`endpoint "${name}" replays "${fingerprint}", which its owner may not replay`);
1450
+ else if (!(await checks.replayable()).has(fingerprint)) refusals.push(`endpoint "${name}" replays "${fingerprint}", which its owner may not replay`);
1438
1451
  }
1439
1452
  return refusals;
1440
1453
  };
@@ -1453,29 +1466,29 @@ var layoutRefusals = (layout, kit) => {
1453
1466
  return [...layout === void 0 || typeof layout === "string" ? [] : layoutMisfits(layout, kit), ...named === void 0 ? [] : [`it ${named}`]];
1454
1467
  };
1455
1468
  var passedOrRefused = (body, refusals) => refusals.length > 0 ? { refusal: refusals.join("; ") } : { body };
1456
- var readAction = async (body, id, heldTo) => {
1469
+ var readAction = async (body, id, checks) => {
1457
1470
  const parsed = parsedUnder(ActionDefinitionSchema, body, id);
1458
1471
  if ("refusal" in parsed) return parsed;
1459
1472
  const action = parsed.body;
1460
1473
  return passedOrRefused(action, [
1461
- ...layoutRefusals(action.layout, heldTo.kit),
1462
- ...await endpointRefusals(action.endpoints, heldTo),
1463
- ...auditAction(action, { catalog: heldTo.catalog() }).issues
1474
+ ...layoutRefusals(action.layout, checks.kit),
1475
+ ...await endpointRefusals(action.endpoints, checks),
1476
+ ...auditAction(action, { catalog: checks.catalog() }).issues
1464
1477
  ]);
1465
1478
  };
1466
- var readFragment = async (body, id, heldTo) => {
1479
+ var readFragment = async (body, id, checks) => {
1467
1480
  const parsed = parsedUnder(ActionFragmentSchema, body, id, { kind: "fragment" });
1468
1481
  if ("refusal" in parsed) return parsed;
1469
1482
  const fragment = parsed.body;
1470
- return passedOrRefused(fragment, [...layoutRefusals(fragment.layout, heldTo.kit), ...await endpointRefusals(fragment.endpoints, heldTo)]);
1483
+ return passedOrRefused(fragment, [...layoutRefusals(fragment.layout, checks.kit), ...await endpointRefusals(fragment.endpoints, checks)]);
1471
1484
  };
1472
1485
  var generatedIn = (inForce2, kind) => inForce2.filter((version) => version.kind === kind && version.body !== null);
1473
1486
  var catalogOfGenerated = (inForce2) => generatedIn(inForce2, "action").map((version) => ({ id: version.id, input: isRecord(version.body) && isRecord(version.body["input"]) ? version.body["input"] : {} }));
1474
- var generatedInForce = async (inForce2, heldTo, whose) => {
1487
+ var generatedInForce = async (inForce2, checks, whose) => {
1475
1488
  const passed = async (kind, read2) => {
1476
1489
  const kept = {};
1477
1490
  for (const version of generatedIn(inForce2, kind)) {
1478
- const answered = version.unread !== void 0 ? { refusal: version.unread } : await read2(version.body, version.id, heldTo);
1491
+ const answered = version.unread !== void 0 ? { refusal: version.unread } : await read2(version.body, version.id, checks);
1479
1492
  if ("body" in answered) kept[version.id] = answered.body;
1480
1493
  else if (whose !== void 0) console.error(`[moss] the ${kind} "${version.id}" ${whose} is left out: ${answered.refusal}`);
1481
1494
  }
@@ -1517,7 +1530,7 @@ var createEntriesInForce = (own, compileRead) => {
1517
1530
  return {
1518
1531
  list: () => list,
1519
1532
  byFingerprint: () => byFingerprint,
1520
- holdsSet: (source) => sets.has(source),
1533
+ hasSet: (source) => sets.has(source),
1521
1534
  withSet: (source, handed) => mergedEntries(own, new Map([...sets, [source, handed]])),
1522
1535
  takeSet: (source, handed, taken) => {
1523
1536
  refuseUnrunnable(handed, compileRead, "Refresh refused \u2014 seeded reads that do not run:");
@@ -1548,8 +1561,8 @@ var compiledRead = async (fingerprint, read2) => {
1548
1561
  return entry;
1549
1562
  };
1550
1563
  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`;
1551
- var readSaved = async (body, fingerprint, heldTo) => {
1552
- if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1564
+ var readSaved = async (body, fingerprint, checks) => {
1565
+ if (checks.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1553
1566
  if (exceedsDepth(body)) return { refusal: depthRefusal() };
1554
1567
  const parsed = SavedReadSchema.safeParse(body);
1555
1568
  if (!parsed.success) {
@@ -1557,16 +1570,16 @@ var readSaved = async (body, fingerprint, heldTo) => {
1557
1570
  return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1558
1571
  }
1559
1572
  try {
1560
- heldTo.sources.compile(parsed.data.dsl);
1573
+ checks.sources.compile(parsed.data.dsl);
1561
1574
  await compiledRead(fingerprint, parsed.data);
1562
1575
  } catch (error) {
1563
1576
  return { refusal: sentenceOf(error) };
1564
1577
  }
1565
1578
  return { body: parsed.data };
1566
1579
  };
1567
- var readWritten = async (fingerprint, heldTo) => {
1568
- if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1569
- const entry = await heldTo.sources.written(fingerprint);
1580
+ var readWritten = async (fingerprint, checks) => {
1581
+ if (checks.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1582
+ const entry = await checks.sources.written(fingerprint);
1570
1583
  if (entry === void 0 || entry.requestHash === void 0) return { refusal: `vex holds no query it wrote under "${fingerprint}"` };
1571
1584
  if (entry.kind !== "ok") return { refusal: `vex found no query to answer under "${fingerprint}"` };
1572
1585
  if (entry.shape !== void 0 && entry.mapping === void 0) {
@@ -1582,7 +1595,7 @@ var readWritten = async (fingerprint, heldTo) => {
1582
1595
  ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {}
1583
1596
  },
1584
1597
  fingerprint,
1585
- heldTo
1598
+ checks
1586
1599
  );
1587
1600
  };
1588
1601
  var answeredRead = async (fingerprint, body) => {
@@ -1590,11 +1603,11 @@ var answeredRead = async (fingerprint, body) => {
1590
1603
  const parsed = SavedReadSchema.safeParse(body);
1591
1604
  return parsed.success ? compiledRead(fingerprint, parsed.data) : void 0;
1592
1605
  };
1593
- var readsInForce = async (inForce2, heldTo, whose) => {
1606
+ var readsInForce = async (inForce2, checks, whose) => {
1594
1607
  const reads = /* @__PURE__ */ new Map();
1595
1608
  for (const version of inForce2) {
1596
1609
  if (version.kind !== "read" || version.body === null) continue;
1597
- const read2 = version.unread !== void 0 ? { refusal: version.unread } : await readSaved(version.body, version.id, heldTo);
1610
+ const read2 = version.unread !== void 0 ? { refusal: version.unread } : await readSaved(version.body, version.id, checks);
1598
1611
  if ("body" in read2) reads.set(version.id, read2.body);
1599
1612
  else if (whose !== void 0) console.error(`[moss] the read "${version.id}" ${whose} is left out: ${read2.refusal}`);
1600
1613
  }
@@ -1621,18 +1634,18 @@ var listed = (version, kind) => ({
1621
1634
  body: version.body
1622
1635
  });
1623
1636
  var withoutMark = ({ use: _mark, ...layout }) => layout;
1624
- var checked = async (kind, id, body, heldTo) => {
1637
+ var checked = async (kind, id, body, checks) => {
1625
1638
  if (kind === "layout") {
1626
- const read3 = readLayout(body, heldTo.layouts);
1639
+ const read3 = readLayout(body, checks.layouts);
1627
1640
  if ("refusal" in read3) throw new Error(`moss: the layout for "${refOf(body) ?? "(no ref)"}" is refused: ${read3.refusal}`);
1628
1641
  return read3.layout;
1629
1642
  }
1630
1643
  if (kind === "read") {
1631
- 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);
1644
+ const read3 = checks.reads === void 0 ? { refusal: "no read is saved here" } : body === void 0 ? await readWritten(id, checks.reads) : await readSaved(body, id, checks.reads);
1632
1645
  if ("refusal" in read3) throw new Error(`moss: the read "${id}" is refused: ${read3.refusal}`);
1633
1646
  return read3.body;
1634
1647
  }
1635
- const read2 = await (kind === "action" ? readAction : readFragment)(body, id, heldTo.generated);
1648
+ const read2 = await (kind === "action" ? readAction : readFragment)(body, id, checks.generated);
1636
1649
  if ("refusal" in read2) throw new Error(`moss: the ${kind} is refused: ${read2.refusal}`);
1637
1650
  return read2.body;
1638
1651
  };
@@ -1649,19 +1662,19 @@ var unmarked = (versions, inForce2) => {
1649
1662
  const layouts = versions.filter((version) => version.kind === "layout");
1650
1663
  const marked = markedRefs(layouts);
1651
1664
  const saved = new Set(layouts.map((version) => version.id));
1652
- const takenOut = inForce2.flatMap((held) => isInUse(held) && saved.has(held.id) ? [refOf(held.body)] : []);
1665
+ const takenOut = inForce2.flatMap((version) => isInUse(version) && saved.has(version.id) ? [refOf(version.body)] : []);
1653
1666
  const decided = /* @__PURE__ */ new Set([...marked, ...takenOut]);
1654
- return inForce2.flatMap((held) => {
1655
- const ref = refOf(held.body);
1656
- if (!isInUse(held) || held.unread !== void 0 || !isRecord(held.body) || ref === void 0 || !decided.has(ref) || saved.has(held.id)) return [];
1657
- return [{ kind: "layout", id: held.id, body: withoutMark(held.body), copiedFrom: held.save }];
1667
+ return inForce2.flatMap((version) => {
1668
+ const ref = refOf(version.body);
1669
+ if (!isInUse(version) || version.unread !== void 0 || !isRecord(version.body) || ref === void 0 || !decided.has(ref) || saved.has(version.id)) return [];
1670
+ return [{ kind: "layout", id: version.id, body: withoutMark(version.body), copiedFrom: version.save }];
1658
1671
  });
1659
1672
  };
1660
1673
  var idsOf = (versions) => versions.map(({ kind, id }) => ({ kind, id }));
1661
- var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1662
- const requireHolder = () => {
1663
- if (holder === void 0) throw new Error(nobody);
1664
- return holder;
1674
+ var savingFor = ({ owner, whose, kinds, written, defaults }, nobody) => {
1675
+ const requireOwner = () => {
1676
+ if (owner === void 0) throw new Error(nobody);
1677
+ return owner;
1665
1678
  };
1666
1679
  const ofKind = (kind) => {
1667
1680
  const known = kinds.find((one) => one === kind);
@@ -1673,13 +1686,13 @@ var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1673
1686
  if (!asked.success) throw new Error("moss: a save holds one or several artifacts, each `{ kind, id?, body }` and nothing else.");
1674
1687
  return asked.data.map((artifact) => ({ ...artifact, kind: ofKind(artifact.kind) }));
1675
1688
  };
1676
- const checkedEach = async (asked, inForce2, held) => {
1689
+ const checkedEach = async (asked, inForce2, checks) => {
1677
1690
  const versions = [];
1678
1691
  for (const { kind, id: named2, body } of asked) {
1679
1692
  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.`);
1680
1693
  const id = named2 ?? NEW_ID[kind]();
1681
1694
  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.`);
1682
- versions.push({ kind, id, body: await checked(kind, id, body, held), copiedFrom: null });
1695
+ versions.push({ kind, id, body: await checked(kind, id, body, checks), copiedFrom: null });
1683
1696
  }
1684
1697
  const named = (kind) => kind !== "read" && (defaults === void 0 || kind === "layout");
1685
1698
  const notTheirs = asked.find(({ kind, id }) => id !== void 0 && named(kind) && !inForce2.some((version) => version.kind === kind && version.id === id));
@@ -1696,25 +1709,25 @@ var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1696
1709
  written();
1697
1710
  return save2;
1698
1711
  };
1699
- return { requireHolder, ofKind, askedOf, checkedEach, write };
1712
+ return { requireOwner, ofKind, askedOf, checkedEach, write };
1700
1713
  };
1701
1714
  var savedArtifacts = (deps) => {
1702
- const { holder, whose, kinds, defaults } = deps;
1703
- const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
1715
+ const { owner, whose, kinds, defaults } = deps;
1716
+ const { requireOwner, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
1704
1717
  return {
1705
1718
  save: async (artifacts) => {
1706
- const holderOf = requireHolder();
1719
+ const ownerOf = requireOwner();
1707
1720
  const asked = askedOf(artifacts);
1708
- const { saved, heldTo } = await holderOf();
1721
+ const { saved, checks } = await ownerOf();
1709
1722
  const inForce2 = await saved.inForce();
1710
- const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1723
+ const versions = await checkedEach(asked, inForce2, await checks(inForce2));
1711
1724
  await defaults?.verify(versions, inForce2);
1712
1725
  return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1713
1726
  },
1714
1727
  list: async (kind) => {
1715
1728
  const only = kind === void 0 ? void 0 : ofKind(kind);
1716
- if (holder === void 0) return [];
1717
- const inForce2 = await (await holder()).saved.inForce();
1729
+ if (owner === void 0) return [];
1730
+ const inForce2 = await (await owner()).saved.inForce();
1718
1731
  return inForce2.flatMap((version) => {
1719
1732
  const known = kinds.find((one) => one === version.kind);
1720
1733
  return version.body !== null && known !== void 0 && (only === void 0 || known === only) ? [listed(version, known)] : [];
@@ -1722,26 +1735,26 @@ var savedArtifacts = (deps) => {
1722
1735
  },
1723
1736
  history: async (kind, id) => {
1724
1737
  const known = ofKind(kind);
1725
- if (holder === void 0) return [];
1726
- return (await (await holder()).saved.history(known, id)).map((version) => listed(version, known));
1738
+ if (owner === void 0) return [];
1739
+ return (await (await owner()).saved.history(known, id)).map((version) => listed(version, known));
1727
1740
  },
1728
1741
  restore: async (kind, id, save2) => {
1729
- const holderOf = requireHolder();
1742
+ const ownerOf = requireOwner();
1730
1743
  const known = ofKind(kind);
1731
- const { saved, heldTo } = await holderOf();
1744
+ const { saved, checks } = await ownerOf();
1732
1745
  const version = SaveIdSchema.safeParse(save2).success ? (await saved.history(known, id, save2))[0] : void 0;
1733
1746
  if (version === void 0) throw new Error(`moss: no ${known} "${id}" ${whose} was saved in "${save2}".`);
1734
1747
  if (version.unread !== void 0) throw new Error(`moss: the ${known} "${id}" saved in "${save2}" cannot be read: ${version.unread}`);
1735
1748
  const inForce2 = await saved.inForce();
1736
- const body = version.body === null ? null : await checked(known, id, version.body, await heldTo(inForce2));
1749
+ const body = version.body === null ? null : await checked(known, id, version.body, await checks(inForce2));
1737
1750
  const restored = { kind: known, id, body, copiedFrom: version.save };
1738
1751
  await defaults?.verify([restored], inForce2);
1739
1752
  return { save: await write(saved, [restored], inForce2) };
1740
1753
  },
1741
1754
  reset: async (kind, id) => {
1742
- const holderOf = requireHolder();
1755
+ const ownerOf = requireOwner();
1743
1756
  const known = ofKind(kind);
1744
- const { saved } = await holderOf();
1757
+ const { saved } = await ownerOf();
1745
1758
  const inForce2 = await saved.inForce();
1746
1759
  if (!inForce2.some((version) => version.kind === known && version.id === id && version.body !== null)) throw new Error(`moss: no ${known} "${id}" ${whose} is in force.`);
1747
1760
  return { save: await write(saved, [{ kind: known, id, body: null, copiedFrom: null }], inForce2) };
@@ -1756,15 +1769,15 @@ var laidOver = (inForce2, drafted = []) => drafted.length === 0 ? inForce2 : [
1756
1769
  ...drafted.map((one) => ({ ...one, save: "draft", copiedFrom: null, createdAt: LATER_THAN_ANY_SAVE }))
1757
1770
  ];
1758
1771
  var draftSaving = (deps) => {
1759
- const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a draft is somebody\u2019s to save.");
1772
+ const { requireOwner, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a draft is somebody\u2019s to save.");
1760
1773
  return {
1761
- // The draft with these added to it. Each is checked beside what is in force for its holder with the draft laid over.
1774
+ // The draft with these added to it. Each is checked beside what is in force for its owner with the draft laid over.
1762
1775
  add: async (artifacts, drafted) => {
1763
- const holderOf = requireHolder();
1776
+ const ownerOf = requireOwner();
1764
1777
  const asked = askedOf(artifacts);
1765
- const { saved, heldTo } = await holderOf();
1778
+ const { saved, checks } = await ownerOf();
1766
1779
  const inForce2 = laidOver(await saved.inForce(), drafted);
1767
- const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1780
+ const versions = await checkedEach(asked, inForce2, await checks(inForce2));
1768
1781
  const added = versions.map(({ kind, id, body }) => ({ kind, id, body }));
1769
1782
  const marked = new Set(markedRefs(added));
1770
1783
  const kept = drafted.flatMap((one) => {
@@ -1776,15 +1789,15 @@ var draftSaving = (deps) => {
1776
1789
  return { drafted: [...kept, ...added], added: idsOf(versions) };
1777
1790
  },
1778
1791
  save: async (drafted) => {
1779
- const holderOf = requireHolder();
1792
+ const ownerOf = requireOwner();
1780
1793
  if (drafted.length === 0) throw new Error("moss: the draft holds nothing to save.");
1781
- const { saved, heldTo } = await holderOf();
1794
+ const { saved, checks } = await ownerOf();
1782
1795
  const inForce2 = await saved.inForce();
1783
- const held = await heldTo(laidOver(inForce2, drafted));
1796
+ const laidOverChecks = await checks(laidOver(inForce2, drafted));
1784
1797
  const versions = [];
1785
1798
  for (const one of drafted) {
1786
1799
  const kind = ofKind(one.kind);
1787
- versions.push({ kind, id: one.id, body: await checked(kind, one.id, one.body, held), copiedFrom: null });
1800
+ versions.push({ kind, id: one.id, body: await checked(kind, one.id, one.body, laidOverChecks), copiedFrom: null });
1788
1801
  }
1789
1802
  return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1790
1803
  }
@@ -1876,7 +1889,7 @@ var createPublishedMemo = () => {
1876
1889
  let read2;
1877
1890
  let said = /* @__PURE__ */ new Set();
1878
1891
  return {
1879
- held: () => read2,
1892
+ current: () => read2,
1880
1893
  keep: (promise) => {
1881
1894
  read2 = promise;
1882
1895
  },
@@ -1892,20 +1905,20 @@ var createPublishedMemo = () => {
1892
1905
  };
1893
1906
  };
1894
1907
  var hasDefaults = (defaults) => Object.keys(defaults.actions).length > 0 || Object.keys(defaults.fragments).length > 0 || defaults.reads.size > 0;
1895
- var checkedDefaults = async (versions, heldTo, whose) => {
1896
- const reads = heldTo.reads === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, heldTo.reads, whose);
1908
+ var checkedDefaults = async (versions, defaults, whose) => {
1909
+ const reads = defaults.reads === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, defaults.reads, whose);
1897
1910
  const checks = {
1898
- kit: heldTo.kit,
1911
+ kit: defaults.kit,
1899
1912
  entryOf: (fingerprint) => {
1900
1913
  const read2 = reads.get(fingerprint);
1901
- return heldTo.entryOf(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
1914
+ return defaults.entryOf(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
1902
1915
  },
1903
- replayable: async () => /* @__PURE__ */ new Set([...heldTo.fingerprints(), ...reads.keys()]),
1916
+ replayable: async () => /* @__PURE__ */ new Set([...defaults.fingerprints(), ...reads.keys()]),
1904
1917
  mayCall: () => true,
1905
- catalog: () => [...Object.values(heldTo.built).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1918
+ catalog: () => [...Object.values(defaults.built).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1906
1919
  };
1907
1920
  const passed = await generatedInForce(versions, checks, whose);
1908
- return { passed, reads, verified: verifyManifest(heldTo.candidate({ ...heldTo.built, ...passed.actions }, passed.fragments)) };
1921
+ return { passed, reads, verified: verifyManifest(defaults.candidate({ ...defaults.built, ...passed.actions }, passed.fragments)) };
1909
1922
  };
1910
1923
  var narrowedBy = (filter, ids, installed) => {
1911
1924
  const answered = new Set(filter(ids, installed));
@@ -1983,8 +1996,8 @@ var createSetOwners = () => {
1983
1996
  return {
1984
1997
  ownerRefusalOf,
1985
1998
  claim: (source, owner, handedOver) => {
1986
- const held = owners.get(source);
1987
- if (held !== void 0) throw new Error(`moss: the set "${source}" is ${held}'s, and ${owner} claims it too. A set has one writer.`);
1999
+ const claimed = owners.get(source);
2000
+ if (claimed !== void 0) throw new Error(`moss: the set "${source}" is ${claimed}'s, and ${owner} claims it too. A set has one writer.`);
1988
2001
  if (handedOver) throw new Error(`moss: the set "${source}" was handed over by the app, and ${owner} claims it. A set has one writer.`);
1989
2002
  owners.set(source, owner);
1990
2003
  },
@@ -2030,7 +2043,7 @@ var createRunningManifest = (config) => {
2030
2043
  let defaults = NO_DEFAULTS;
2031
2044
  const usage = createUsage(config.touchEveryMs ?? TOUCH_EVERY_MS);
2032
2045
  let functionIds;
2033
- const candidate = (actions, held = entries.list(), fragments = defaults.fragments) => withFragments({ ...candidateOf(shipped, { actions, entries: held }, config.grants), ...functionIds === void 0 ? {} : { functionIds } }, fragments);
2046
+ const candidate = (actions, listed2 = entries.list(), fragments = defaults.fragments) => withFragments({ ...candidateOf(shipped, { actions, entries: listed2 }, config.grants), ...functionIds === void 0 ? {} : { functionIds } }, fragments);
2034
2047
  const own = shipped.actions;
2035
2048
  const loaders = /* @__PURE__ */ new Map();
2036
2049
  const owners = createSetOwners();
@@ -2059,7 +2072,7 @@ var createRunningManifest = (config) => {
2059
2072
  const kitOf2 = (shell) => shell === void 0 ? ofTheApp ??= componentsOf2(config.shells) : componentsOf2([shell]);
2060
2073
  const ownShell = shipped.shell;
2061
2074
  const ownShellRefs = new Set(ownShell === void 0 ? [] : Object.keys(shellWithStoredLayouts(ownShell).layouts));
2062
- const heldTo = ({ actions, layouts }, shell) => {
2075
+ const layoutChecksOf = ({ actions, layouts }, shell) => {
2063
2076
  const kit = kitOf2(shell);
2064
2077
  return {
2065
2078
  kit,
@@ -2093,11 +2106,11 @@ var createRunningManifest = (config) => {
2093
2106
  if (warning !== void 0) console.warn(warning);
2094
2107
  };
2095
2108
  const grantedFunctionsOf = (roles) => (names) => resolvePrincipal(shipped.charter, names, roles, "functions");
2096
- const readsHeldTo = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
2097
- const heldWithGenerated = async (held, versions, who, shell, whose) => {
2109
+ const readChecks = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
2110
+ const checksWithGenerated = async (granted, versions, who, shell, whose) => {
2098
2111
  let replayable;
2099
2112
  let catalog;
2100
- const reads = new Map([...defaults.reads, ...readsHeldTo === void 0 ? [] : await readsInForce(versions, readsHeldTo, whose)]);
2113
+ const reads = new Map([...defaults.reads, ...readChecks === void 0 ? [] : await readsInForce(versions, readChecks, whose)]);
2101
2114
  const checks = {
2102
2115
  kit: kitOf2(shell),
2103
2116
  entryOf: (fingerprint) => {
@@ -2106,12 +2119,12 @@ var createRunningManifest = (config) => {
2106
2119
  },
2107
2120
  replayable: () => replayable ??= (async () => /* @__PURE__ */ new Set([...await who.replayable?.() ?? [], ...reads.keys()]))(),
2108
2121
  mayCall: (name) => who.roles !== void 0 && resolvePrincipal(shipped.charter, [name], who.roles, "functions").has(name),
2109
- catalog: () => catalog ??= [...Object.values(held.actions).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
2122
+ catalog: () => catalog ??= [...Object.values(granted.actions).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
2110
2123
  };
2111
2124
  const passed = await generatedInForce(versions, checks, whose);
2112
2125
  const stored = actionsWithStoredLayouts(passed.actions);
2113
- const all = Object.keys(passed.actions).length === 0 ? held : { actions: { ...held.actions, ...stored.actions }, layouts: { ...held.layouts, ...stored.layouts } };
2114
- return { all, fragments: passed.fragments, heldTo: { layouts: heldTo(all, shell), generated: checks, ...readsHeldTo !== void 0 ? { reads: readsHeldTo } : {} } };
2126
+ const all = Object.keys(passed.actions).length === 0 ? granted : { actions: { ...granted.actions, ...stored.actions }, layouts: { ...granted.layouts, ...stored.layouts } };
2127
+ return { all, fragments: passed.fragments, checks: { layouts: layoutChecksOf(all, shell), generated: checks, ...readChecks !== void 0 ? { reads: readChecks } : {} } };
2115
2128
  };
2116
2129
  const listeners = /* @__PURE__ */ new Set();
2117
2130
  const listenersFor = /* @__PURE__ */ new Set();
@@ -2119,11 +2132,11 @@ var createRunningManifest = (config) => {
2119
2132
  const sessionDeps = (principal, callerOf, shell) => ({
2120
2133
  whose: "of yours",
2121
2134
  kinds,
2122
- holder: principal === null ? void 0 : async () => {
2135
+ owner: principal === null ? void 0 : async () => {
2123
2136
  await publishedNow();
2124
2137
  const caller = await callerOf();
2125
- const held = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
2126
- return { saved: caller.saved, heldTo: async (inForce3) => (await heldWithGenerated(held, inForce3, caller, shell)).heldTo };
2138
+ const granted = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
2139
+ return { saved: caller.saved, checks: async (inForce3) => (await checksWithGenerated(granted, inForce3, caller, shell)).checks };
2127
2140
  },
2128
2141
  written: () => {
2129
2142
  if (principal !== null) for (const listener of [...listenersFor]) tell(listener, principal);
@@ -2131,17 +2144,17 @@ var createRunningManifest = (config) => {
2131
2144
  });
2132
2145
  let pointer;
2133
2146
  const memo = createPublishedMemo();
2134
- const defaultsHeldTo = () => ({
2147
+ const defaultsChecks = () => ({
2135
2148
  kit: kitOf2(),
2136
2149
  entryOf: (fingerprint) => entries.byFingerprint().get(fingerprint),
2137
2150
  fingerprints: () => entries.byFingerprint().keys(),
2138
- reads: readsHeldTo,
2151
+ reads: readChecks,
2139
2152
  built: mergedActions(own, sets),
2140
2153
  candidate: (actions, fragments) => candidate(actions, entries.list(), fragments)
2141
2154
  });
2142
2155
  const applyPublished = async (versions) => {
2143
2156
  const over = sets;
2144
- const { passed, reads, verified } = await checkedDefaults(versions, defaultsHeldTo(), "published for everybody");
2157
+ const { passed, reads, verified } = await checkedDefaults(versions, defaultsChecks(), "published for everybody");
2145
2158
  if (sets !== over) return applyPublished(versions);
2146
2159
  const refusal = refusalOf(verified, "boot");
2147
2160
  if (refusal !== void 0) memo.sayOnce(`[moss] what is published for everybody is left out, and the build\u2019s copies stand: ${refusal}`);
@@ -2153,8 +2166,8 @@ var createRunningManifest = (config) => {
2153
2166
  dropMemos();
2154
2167
  };
2155
2168
  const publishedNow = () => {
2156
- const held = memo.held();
2157
- if (held !== void 0) return held;
2169
+ const current = memo.current();
2170
+ if (current !== void 0) return current;
2158
2171
  const read2 = (async () => {
2159
2172
  const versions = await config.published?.() ?? [];
2160
2173
  await applyPublished(versions);
@@ -2226,7 +2239,7 @@ var createRunningManifest = (config) => {
2226
2239
  },
2227
2240
  cacheEntries: async () => [...await entries.compiled()].map(([key, entry]) => ({ key, entry })),
2228
2241
  claim: (source, owner) => {
2229
- owners.claim(source, owner, sets.has(source) || entries.holdsSet(source));
2242
+ owners.claim(source, owner, sets.has(source) || entries.hasSet(source));
2230
2243
  return {
2231
2244
  replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
2232
2245
  setLoader: (load) => {
@@ -2259,12 +2272,12 @@ var createRunningManifest = (config) => {
2259
2272
  const versions = own2.length === 0 && drafted === void 0 ? [] : laidOver(own2, drafted);
2260
2273
  const everybodysVersions = await publishedNow();
2261
2274
  const whose = `of ${principal ?? "nobody"}`;
2262
- const theirOwn = await heldWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
2263
- const drawable = theirOwn.heldTo.layouts;
2264
- const theirs2 = layoutsInUse(versions, { whose, heldTo: drawable });
2275
+ const theirOwn = await checksWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
2276
+ const drawable = theirOwn.checks.layouts;
2277
+ const theirs2 = layoutsInUse(versions, { whose, checks: drawable });
2265
2278
  const variants = roleMemo.variantsFor(roles);
2266
2279
  const underVariants = { ...drawable, actionAt: (ref) => variants.has(actionOfLayoutRef(ref) ?? "") ? void 0 : drawable.actionAt(ref) };
2267
- const everybodys = layoutsInUse(everybodysVersions, { whose: "published for everybody", heldTo: underVariants, say: memo.sayOnce });
2280
+ const everybodys = layoutsInUse(everybodysVersions, { whose: "published for everybody", checks: underVariants, say: memo.sayOnce });
2268
2281
  const laidOverShell = { ...drawableIn(defaults.fragments, kitOf2(shell), memo.sayOnce), ...theirOwn.fragments };
2269
2282
  const fragments = Object.keys(laidOverShell).length === 0 ? shell.fragments : { ...shell.fragments, ...laidOverShell };
2270
2283
  const { layouts: ofShell, ...named } = shellWithStoredLayouts(shell);
@@ -2282,20 +2295,20 @@ var createRunningManifest = (config) => {
2282
2295
  },
2283
2296
  sessionArtifacts: (principal, callerOf) => savedArtifacts(sessionDeps(principal, callerOf)),
2284
2297
  draftSavingFor: (shell, principal, callerOf) => draftSaving(sessionDeps(principal, callerOf, shell)),
2285
- // Held to every action in force with the layout it is built with: who holds
2298
+ // Checked against every action in force with the layout it is built with: who has
2286
2299
  // which is asked when a shell is built for them.
2287
2300
  publishedArtifacts: (saved, publisher) => savedArtifacts({
2288
2301
  whose: "published for everybody",
2289
2302
  kinds,
2290
- holder: async () => {
2303
+ owner: async () => {
2291
2304
  const who = await publisher();
2292
- return { saved, heldTo: async (inForce3) => (await heldWithGenerated(actionsWithStoredLayouts(mergedActions(own, sets)), inForce3, who)).heldTo };
2305
+ return { saved, checks: async (inForce3) => (await checksWithGenerated(actionsWithStoredLayouts(mergedActions(own, sets)), inForce3, who)).checks };
2293
2306
  },
2294
2307
  defaults: {
2295
2308
  verify: async (versions, inForce3) => {
2296
- const kept = inForce3.filter((held) => !versions.some((version) => version.kind === held.kind && version.id === held.id));
2309
+ const kept = inForce3.filter((current) => !versions.some((version) => version.kind === current.kind && version.id === current.id));
2297
2310
  const asked = versions.map((version) => ({ ...version, save: "", createdAt: "" }));
2298
- const refusal = refusalOf((await checkedDefaults([...kept, ...asked], defaultsHeldTo(), void 0)).verified, "publish");
2311
+ const refusal = refusalOf((await checkedDefaults([...kept, ...asked], defaultsChecks(), void 0)).verified, "publish");
2299
2312
  if (refusal !== void 0) throw new Error(refusal);
2300
2313
  }
2301
2314
  },
@@ -2341,14 +2354,14 @@ var callerScope = (scope) => {
2341
2354
  };
2342
2355
  var PAGE = 500;
2343
2356
  var VERSION_COLUMNS = ["save", "kind", "id", "body", "grammar", "copied_from", "created_at"];
2344
- var laterThanHeld = {
2357
+ var laterVersion = {
2345
2358
  and: [
2346
2359
  { eq: ["artifacts.kind", "held.kind"] },
2347
2360
  { eq: ["artifacts.id", "held.id"] },
2348
2361
  { or: [{ gt: ["artifacts.created_at", "held.created_at"] }, { and: [{ eq: ["artifacts.created_at", "held.created_at"] }, { gt: ["artifacts.save", "held.save"] }] }] }
2349
2362
  ]
2350
2363
  };
2351
- var afterHeld = {
2364
+ var afterCursor = {
2352
2365
  or: [{ gt: ["held.kind", { $context: "after_kind" }] }, { and: [{ eq: ["held.kind", { $context: "after_kind" }] }, { gt: ["held.id", { $context: "after_id" }] }] }]
2353
2366
  };
2354
2367
  var inForce = {
@@ -2357,7 +2370,7 @@ var inForce = {
2357
2370
  dsl: {
2358
2371
  from: [{ as: "held", query: { from: ["artifacts"], fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`) } }],
2359
2372
  fields: VERSION_COLUMNS.map((column) => `held.${column}`),
2360
- filter: { and: [{ not: { exists: { from: ["artifacts"], filter: laterThanHeld } } }, afterHeld] },
2373
+ filter: { and: [{ not: { exists: { from: ["artifacts"], filter: laterVersion } } }, afterCursor] },
2361
2374
  sort: [
2362
2375
  { field: "held.kind", dir: "asc" },
2363
2376
  { field: "held.id", dir: "asc" }
@@ -2470,6 +2483,7 @@ var DEFAULT_REVALIDATE_MS = 60 * 1e3;
2470
2483
  var MAX_INTERVAL_MS2 = 2 ** 31 - 1;
2471
2484
  var createRevalidation = (config) => {
2472
2485
  const live = /* @__PURE__ */ new Map();
2486
+ const revalidateMs = config.revalidateMs ?? DEFAULT_REVALIDATE_MS;
2473
2487
  const expire = (connection) => {
2474
2488
  live.delete(connection);
2475
2489
  const told = () => connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
@@ -2482,30 +2496,59 @@ var createRevalidation = (config) => {
2482
2496
  }
2483
2497
  }
2484
2498
  };
2499
+ const asking = /* @__PURE__ */ new Set();
2500
+ const question = async (token, presenting) => {
2501
+ for (const { connection } of presenting) asking.add(connection);
2502
+ try {
2503
+ const resolved = await config.session(token);
2504
+ for (const { connection, principal } of presenting) if (resolved !== principal && live.has(connection)) expire(connection);
2505
+ } finally {
2506
+ for (const { connection } of presenting) asking.delete(connection);
2507
+ }
2508
+ };
2485
2509
  const revalidate = async () => {
2510
+ const byToken = /* @__PURE__ */ new Map();
2486
2511
  let asked = 0;
2487
- const unanswered = [];
2488
- for (const [connection, credential] of [...live]) {
2489
- if (credential === null) continue;
2512
+ for (const [connection, credential] of live) {
2513
+ if (credential === null || asking.has(connection)) continue;
2490
2514
  asked += 1;
2491
- let resolved;
2492
- try {
2493
- resolved = await config.session(credential.token);
2494
- } catch (error) {
2495
- unanswered.push(error);
2496
- continue;
2497
- }
2498
- if (resolved === credential.principal) continue;
2499
- if (!live.has(connection)) continue;
2500
- expire(connection);
2515
+ byToken.set(credential.token, [...byToken.get(credential.token) ?? [], { connection, principal: credential.principal }]);
2516
+ }
2517
+ let due;
2518
+ const passDue = new Promise((resolve2) => {
2519
+ due = setTimeout(() => resolve2(false), revalidateMs);
2520
+ due.unref?.();
2521
+ });
2522
+ const unanswered = [];
2523
+ try {
2524
+ await Promise.all(
2525
+ [...byToken].map(async ([token, presenting]) => {
2526
+ const answer = question(token, presenting);
2527
+ try {
2528
+ if (!await Promise.race([answer.then(() => true), passDue])) {
2529
+ answer.catch(
2530
+ (error) => console.error("[moss/socket] the session verifier could not be asked about a token after its pass went on. Its connections stay open and are asked again:", error)
2531
+ );
2532
+ }
2533
+ } catch (error) {
2534
+ unanswered.push(...presenting.map(() => error));
2535
+ }
2536
+ })
2537
+ );
2538
+ } finally {
2539
+ clearTimeout(due);
2501
2540
  }
2502
2541
  if (unanswered.length > 0) {
2503
2542
  console.error(`[moss/socket] the session verifier could not be asked about ${unanswered.length} of ${asked} connection(s). They stay open and are asked again:`, unanswered[0]);
2504
2543
  }
2505
2544
  };
2506
2545
  let passing = false;
2546
+ let dueWhilePassing = false;
2507
2547
  const pass = async () => {
2508
- if (passing) return;
2548
+ if (passing) {
2549
+ dueWhilePassing = true;
2550
+ return;
2551
+ }
2509
2552
  passing = true;
2510
2553
  try {
2511
2554
  await revalidate();
@@ -2513,16 +2556,19 @@ var createRevalidation = (config) => {
2513
2556
  console.error("[moss/socket] a revalidation pass failed, and the next one starts over:", error);
2514
2557
  } finally {
2515
2558
  passing = false;
2559
+ if (dueWhilePassing && sweeper !== void 0) {
2560
+ dueWhilePassing = false;
2561
+ void pass();
2562
+ }
2516
2563
  }
2517
2564
  };
2518
- const revalidateMs = config.revalidateMs ?? DEFAULT_REVALIDATE_MS;
2519
2565
  let sweeper;
2520
2566
  if (revalidateMs > 0 && revalidateMs <= MAX_INTERVAL_MS2) {
2521
2567
  sweeper = setInterval(() => void pass(), revalidateMs);
2522
2568
  sweeper.unref?.();
2523
2569
  }
2524
2570
  return {
2525
- hold: (connection, credential) => {
2571
+ track: (connection, credential) => {
2526
2572
  live.set(connection, credential);
2527
2573
  },
2528
2574
  release: (connection) => {
@@ -2564,7 +2610,7 @@ var authenticateUpgrade = async (url, upgrade, config, foreignPageWarning) => {
2564
2610
  const key = parameters.key ?? DEFAULT_TOKEN_KEY;
2565
2611
  const page = upgrade === void 0 ? void 0 : ownOriginOf(upgrade.origin, upgrade.host, config.origins);
2566
2612
  const secure = page?.protocol === "https:";
2567
- const held = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
2613
+ const fromCookie = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
2568
2614
  const sealing = page !== void 0 && parameters.sealed === "1";
2569
2615
  if (page === void 0 && parameters.sealed === "1" && typeof upgrade?.origin === "string" && !foreignPageWarning.warned) {
2570
2616
  foreignPageWarning.warned = true;
@@ -2577,12 +2623,12 @@ var authenticateUpgrade = async (url, upgrade, config, foreignPageWarning) => {
2577
2623
  const sealLost = sealing && sealedOffer !== null && hadSeal === null;
2578
2624
  const seal = !sealing || sealLost ? null : hadSeal ?? (upgrade?.answer === void 0 ? null : newSeal());
2579
2625
  const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));
2580
- const carried = offered ?? (parameters.leave === "1" ? null : held?.token ?? null);
2626
+ const carried = offered ?? (parameters.leave === "1" ? null : fromCookie?.token ?? null);
2581
2627
  const principal = carried === null ? null : await config.session(carried);
2582
2628
  if (offered !== null && principal === null) return "invalid_token";
2583
2629
  const token = principal === null ? null : carried;
2584
2630
  const cookies = [
2585
- ...page === void 0 || offered === null && (held?.token ?? null) === token ? [] : token === null ? held?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await config.sessionLastsMs?.(token) ?? null }),
2631
+ ...page === void 0 || offered === null && (fromCookie?.token ?? null) === token ? [] : token === null ? fromCookie?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await config.sessionLastsMs?.(token) ?? null }),
2586
2632
  ...seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, "http://nisc.local").pathname })] : []
2587
2633
  ];
2588
2634
  return { token, principal, cookies, seal, sealLost };
@@ -2712,8 +2758,8 @@ var served = async (config, connection, send, close, opening, who) => {
2712
2758
  close.whenClosed(() => session.detach(connection));
2713
2759
  return session;
2714
2760
  };
2715
- var open = async (held, url, connection, send, span, found) => {
2716
- const { config, foreignPageWarning, revalidation, anonymousShells } = held;
2761
+ var open = async (state, url, connection, send, span, found) => {
2762
+ const { config, foreignPageWarning, revalidation, anonymousShells } = state;
2717
2763
  const params = parametersOf(url);
2718
2764
  const mismatch = protocolRefusal(params);
2719
2765
  if (mismatch !== void 0) {
@@ -2742,7 +2788,7 @@ var open = async (held, url, connection, send, span, found) => {
2742
2788
  connection.close(CLOSE_AT_CAPACITY, "at capacity");
2743
2789
  return;
2744
2790
  }
2745
- revalidation.hold(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
2791
+ revalidation.track(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
2746
2792
  const close = closeOf(connection);
2747
2793
  close.whenClosed(() => revalidation.release(connection));
2748
2794
  close.whenClosed(() => anonymousShells.release(connection));
@@ -2755,13 +2801,13 @@ var createSocket = (config) => {
2755
2801
  const emit = emitterOf(config.telemetry);
2756
2802
  const revalidation = createRevalidation(config);
2757
2803
  const anonymousShells = createAnonymousShellLimit(config.anonymousShellMax ?? DEFAULT_ANONYMOUS_SHELL_MAX);
2758
- const held = { config, foreignPageWarning: { warned: false }, revalidation, anonymousShells };
2804
+ const state = { config, foreignPageWarning: { warned: false }, revalidation, anonymousShells };
2759
2805
  const accept = async (url, connection) => {
2760
2806
  const send = (message) => connection.send(JSON.stringify(message));
2761
2807
  const span = spanOf(emit);
2762
2808
  const found = { principal: false };
2763
2809
  try {
2764
- await open(held, url, connection, send, span, found);
2810
+ await open(state, url, connection, send, span, found);
2765
2811
  } catch (error) {
2766
2812
  console.error("[moss/socket] refused a session:", error);
2767
2813
  span?.("socket.upgrade", "error", found.principal);
@@ -2967,7 +3013,7 @@ var takeComposition = (live, made) => {
2967
3013
  live.entries = made.entries;
2968
3014
  takeLayouts(live, made);
2969
3015
  takeCanvases(live, made);
2970
- holdGranted(live.functions, made.grantedFunctions);
3016
+ keepGranted(live.functions, made.grantedFunctions);
2971
3017
  };
2972
3018
  var adoptDraft = async (host, live, next) => {
2973
3019
  for (; ; ) {
@@ -3177,8 +3223,8 @@ var hostConfig = (deps, shell, kept) => {
3177
3223
  };
3178
3224
  return {
3179
3225
  composition: async (principal, drafted) => {
3180
- const { resolved, saved, ...held } = await callerOf(principal);
3181
- const who = { principal, ...held, ...principal === null ? {} : { saved, ...drafted === void 0 ? {} : { drafted } } };
3226
+ const { resolved, saved, ...caller } = await callerOf(principal);
3227
+ const who = { principal, ...caller, ...principal === null ? {} : { saved, ...drafted === void 0 ? {} : { drafted } } };
3182
3228
  return { roles: resolved.roles, scope: resolved.scope, ...await running.artifactsFor(shell, who) };
3183
3229
  },
3184
3230
  artifacts: (principal) => running.sessionArtifacts(principal, () => callerOf(principal)),
@@ -3262,11 +3308,13 @@ var buildShellHosts = (deps) => {
3262
3308
  var createInternalWire = (server) => (token) => async (url, init) => {
3263
3309
  const isVex = url.split("?")[0]?.endsWith("/vex") === true;
3264
3310
  const follower = isVex && init?.signal !== void 0 ? createWireFollower(init.signal) : void 0;
3311
+ const headers = new Headers(init?.headers);
3312
+ if (token !== null) headers.set("authorization", `Bearer ${token}`);
3265
3313
  const res = await server.request(
3266
3314
  url,
3267
3315
  {
3268
3316
  method: init?.method ?? "GET",
3269
- headers: { ...init?.headers ?? {}, ...token !== null ? { Authorization: `Bearer ${token}` } : {} },
3317
+ headers,
3270
3318
  ...init?.body !== void 0 ? { body: init.body } : {}
3271
3319
  },
3272
3320
  follower === void 0 ? void 0 : { [VEX_LIVE_ENV]: follower.live }
@@ -3306,7 +3354,7 @@ var mountRoutes = (server, { app, session, credentials, identity, running, data
3306
3354
  var INVALID_TOKEN = { refused: { status: 401, error: "invalid_token", message: "The session token did not resolve to a principal." } };
3307
3355
  var authenticateRequest = async (deps, header, request) => {
3308
3356
  if (header === void 0) return { principal: null, resolved: await deps.resolve(null) };
3309
- const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header;
3357
+ const token = header.replace(/^bearer +/i, "");
3310
3358
  const credential = deps.credentials.find(({ prefix }) => token.startsWith(prefix));
3311
3359
  if (credential !== void 0) {
3312
3360
  const answer = await credential.principalOf(token, request);
@@ -3358,9 +3406,9 @@ var operatorPrefix = (runtime) => {
3358
3406
  var buildSignals = ({ fabric, identity, reset, adopt: adopt2, adoptAll: adoptAll2, deliver }) => {
3359
3407
  const origin = randomBytes(8).toString("hex");
3360
3408
  const applyInvalidateIdentity = (principal) => {
3361
- const held = identity.invalidate(principal);
3409
+ const forgotten = identity.invalidate(principal);
3362
3410
  reset(principal);
3363
- return held;
3411
+ return forgotten;
3364
3412
  };
3365
3413
  const applyInvalidateTag = (tag) => {
3366
3414
  const forgotten = identity.invalidateTag(tag).length;
@@ -3378,9 +3426,9 @@ var buildSignals = ({ fabric, identity, reset, adopt: adopt2, adoptAll: adoptAll
3378
3426
  });
3379
3427
  return {
3380
3428
  invalidateIdentity: (principal) => {
3381
- const held = applyInvalidateIdentity(principal);
3429
+ const forgotten = applyInvalidateIdentity(principal);
3382
3430
  publish({ kind: "invalidate-identity", principal });
3383
- return held;
3431
+ return forgotten;
3384
3432
  },
3385
3433
  invalidateTag: (tag) => {
3386
3434
  const forgotten = applyInvalidateTag(tag);
@@ -3479,7 +3527,9 @@ var buildData = (app, runtime) => createData({
3479
3527
  charter: app.charter,
3480
3528
  behaviors: app.behaviors,
3481
3529
  rowRules: rowRulesBeside(app.behaviors),
3482
- telemetry: runtime.telemetry
3530
+ telemetry: runtime.telemetry,
3531
+ answerReadableRows: runtime.answerReadableRows,
3532
+ checkMovedRows: runtime.checkMovedRows
3483
3533
  });
3484
3534
  var assembleServer = async (deps) => {
3485
3535
  const stops = [];
@@ -3500,7 +3550,7 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3500
3550
  `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.`
3501
3551
  );
3502
3552
  }
3503
- stops.push(startAging(runtime.pool, runtime.artifactsUnusedMs));
3553
+ stops.push(startAging(runtime.pool, runtime.artifactsUnusedMs, { sinceStart: runtime.artifactsUnusedSinceStart === true }));
3504
3554
  }
3505
3555
  const identity = buildIdentity(app, runtime, data);
3506
3556
  stops.push(identity.stop);
@@ -3576,7 +3626,7 @@ var buildRunningManifest = async (app, runtime, data, saved) => {
3576
3626
  ...app.upgradedColumns !== void 0 ? { compileSeeded: data.compileQuery } : {}
3577
3627
  });
3578
3628
  data.dropOnChange(running.onChange);
3579
- data.entriesHeldBy({ get: running.cacheEntry, entries: running.cacheEntries });
3629
+ data.askEntriesFirst({ get: running.cacheEntry, entries: running.cacheEntries });
3580
3630
  await running.cacheEntries();
3581
3631
  return running;
3582
3632
  };
@@ -3631,5 +3681,5 @@ var subscribeReactions = ({ app, onWrite, deliver }) => {
3631
3681
  };
3632
3682
 
3633
3683
  export { MOSS_SEQUENCE, createServer, exportDocuments, migrateTables, mintDevToken, mintSession, renderDocument, revokeAllFor, sessionCookies, tableStatus };
3634
- //# sourceMappingURL=chunk-6MZPY4X6.js.map
3635
- //# sourceMappingURL=chunk-6MZPY4X6.js.map
3684
+ //# sourceMappingURL=chunk-MYPK5YZR.js.map
3685
+ //# sourceMappingURL=chunk-MYPK5YZR.js.map