@niscorp/moss 0.7.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 (51) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/DOCS.md +95 -58
  3. package/dist/{chunk-F45SFR7W.cjs → chunk-3DCTQKPQ.cjs} +56 -16
  4. package/dist/chunk-3DCTQKPQ.cjs.map +1 -0
  5. package/dist/{chunk-X2Q546EB.js → chunk-3T422CCN.js} +9 -3
  6. package/dist/chunk-3T422CCN.js.map +1 -0
  7. package/dist/{chunk-MYGVHWS5.js → chunk-6XC2MD7S.js} +51 -15
  8. package/dist/chunk-6XC2MD7S.js.map +1 -0
  9. package/dist/{chunk-Z2VA6AOE.cjs → chunk-I4UOWER3.cjs} +11 -5
  10. package/dist/chunk-I4UOWER3.cjs.map +1 -0
  11. package/dist/{chunk-C2DNDIQX.cjs → chunk-PVZMCEBX.cjs} +2 -2
  12. package/dist/chunk-PVZMCEBX.cjs.map +1 -0
  13. package/dist/{chunk-IMZZB4JE.js → chunk-QAHDSRPK.js} +2 -2
  14. package/dist/chunk-QAHDSRPK.js.map +1 -0
  15. package/dist/{chunk-DSTHFSTO.cjs → chunk-TMDKNZYL.cjs} +349 -159
  16. package/dist/chunk-TMDKNZYL.cjs.map +1 -0
  17. package/dist/{chunk-MTC46PGQ.js → chunk-YZILOVCR.js} +301 -111
  18. package/dist/chunk-YZILOVCR.js.map +1 -0
  19. package/dist/{document-AbQUbQaP.d.ts → document-BYAY-Qle.d.ts} +9 -9
  20. package/dist/{document-wHHxIXJz.d.cts → document-DAE71J27.d.cts} +9 -9
  21. package/dist/{index-Dml1klpZ.d.cts → index-CSEo7Tys.d.cts} +1 -0
  22. package/dist/{index-Dml1klpZ.d.ts → index-CSEo7Tys.d.ts} +1 -0
  23. package/dist/index.cjs +14 -14
  24. package/dist/index.d.cts +5 -5
  25. package/dist/index.d.ts +5 -5
  26. package/dist/index.js +3 -3
  27. package/dist/integrations.cjs +3 -3
  28. package/dist/integrations.d.cts +1 -1
  29. package/dist/integrations.d.ts +1 -1
  30. package/dist/integrations.js +1 -1
  31. package/dist/node.cjs +8 -8
  32. package/dist/node.d.cts +2 -2
  33. package/dist/node.d.ts +2 -2
  34. package/dist/node.js +4 -4
  35. package/dist/tide.d.cts +1 -1
  36. package/dist/tide.d.ts +1 -1
  37. package/dist/unverified.cjs +3 -3
  38. package/dist/unverified.js +2 -2
  39. package/dist/vite.cjs +9 -9
  40. package/dist/vite.d.cts +2 -2
  41. package/dist/vite.d.ts +2 -2
  42. package/dist/vite.js +4 -4
  43. package/package.json +8 -8
  44. package/dist/chunk-C2DNDIQX.cjs.map +0 -1
  45. package/dist/chunk-DSTHFSTO.cjs.map +0 -1
  46. package/dist/chunk-F45SFR7W.cjs.map +0 -1
  47. package/dist/chunk-IMZZB4JE.js.map +0 -1
  48. package/dist/chunk-MTC46PGQ.js.map +0 -1
  49. package/dist/chunk-MYGVHWS5.js.map +0 -1
  50. package/dist/chunk-X2Q546EB.js.map +0 -1
  51. package/dist/chunk-Z2VA6AOE.cjs.map +0 -1
@@ -1,5 +1,5 @@
1
- import { entriesOf, receiveManifest, verifyManifest, functionsWarning, refusalOf, candidateOf, FRAME_LAYOUT_REF, canvasLayoutRef, freezeDeep, entryMisfits, sessionOn, endlessChains, layoutMisfits, actionLayoutRef, actionOfLayoutRef, endShell, GENERATED_ID_PREFIX, layoutNameRefusal, withLayoutInPlace, canvasesOf, treeOf, buildShell, SHELL_GONE, draftedIn, attach, holdGranted, layoutsOf, withVariants, variantLayouts } from './chunk-MYGVHWS5.js';
2
- import { emitterOf, FabricMessageSchema, spanClock } from './chunk-IMZZB4JE.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, holdGranted, layoutsOf, withVariants, variantLayouts } from './chunk-6XC2MD7S.js';
2
+ import { emitterOf, FabricMessageSchema, spanClock } from './chunk-QAHDSRPK.js';
3
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-4ZGAFZGS.js';
4
4
  import { z } from 'zod';
5
5
  import { randomBytes, createHash, timingSafeEqual, randomUUID } from 'crypto';
@@ -10,7 +10,7 @@ import { NOVA_SEQUENCE } from '@niscorp/nova/migrations';
10
10
  import { evaluate } from '@niscorp/prism';
11
11
  import { PRISM_SEQUENCE } from '@niscorp/prism/migrations';
12
12
  import { VEX_SCHEMAS, VEX_SEQUENCE } from '@niscorp/vex/migrations';
13
- import { resolvePrincipal, verifyCharter, resolveScoping } from '@niscorp/charter';
13
+ import { resolvePrincipal, resolveScoping } from '@niscorp/charter';
14
14
  import { Hono } from 'hono';
15
15
  import { VEX_LIVE_ENV, vex } from '@niscorp/vex/hono';
16
16
  import { AsyncLocalStorage } from 'async_hooks';
@@ -536,6 +536,10 @@ var MOSS_SEQUENCE = {
536
536
  // What is in force for an artifact is its latest row, and that is asked at every shell.
537
537
  { kind: "sql", sql: `CREATE INDEX artifacts_latest ON artifacts (principal, kind, id, created_at)` }
538
538
  ]
539
+ },
540
+ {
541
+ description: "When a version of an artifact was last loaded into a shell, for the sweep over what is unused",
542
+ steps: [{ kind: "sql", sql: `ALTER TABLE artifacts ADD COLUMN last_used_at timestamptz` }]
539
543
  }
540
544
  ]
541
545
  };
@@ -644,6 +648,38 @@ var featureTablesOf = (app) => {
644
648
  return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
645
649
  });
646
650
  };
651
+
652
+ // src/data/aging.ts
653
+ var UNUSED_VERSIONS = (
654
+ /* sql */
655
+ `DELETE FROM artifacts a
656
+ WHERE a.principal <> '*'
657
+ 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')
658
+ RETURNING a.save`
659
+ );
660
+ var EMPTY_SAVES = (
661
+ /* sql */
662
+ `DELETE FROM artifact_saves s WHERE NOT EXISTS (SELECT 1 FROM artifacts a WHERE a.save = s.id) RETURNING s.id`
663
+ );
664
+ var sweepUnused = async (pool, unusedMs) => {
665
+ const versions = (await pool.query(UNUSED_VERSIONS, [unusedMs])).rows.length;
666
+ const saves = (await pool.query(EMPTY_SAVES)).rows.length;
667
+ return { versions, saves };
668
+ };
669
+ var AGING_EVERY_MS = 36e5;
670
+ var startAging = (pool, unusedMs, everyMs = AGING_EVERY_MS) => {
671
+ const sweep2 = async () => {
672
+ try {
673
+ const swept = await sweepUnused(pool, unusedMs);
674
+ 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`);
675
+ } catch (error) {
676
+ console.error("[moss] aging: the sweep failed, and is tried again at the next:", error);
677
+ }
678
+ };
679
+ void sweep2();
680
+ const timer = setInterval(() => void sweep2(), everyMs);
681
+ return () => clearInterval(timer);
682
+ };
647
683
  var isWrittenForRequest = (entry) => entry.kind === "unsatisfiable" || entry.requestHash !== void 0;
648
684
  var createEntryCache = (table) => {
649
685
  let held;
@@ -950,7 +986,10 @@ var createIntentAnswers = (deps) => {
950
986
  engines.set(writers, created);
951
987
  return created;
952
988
  };
953
- return async (writers, asked, caller) => (await engineFor(writers)).execute({ intent: asked.intent, shape: asked.shape, context: asked.context ?? {} }, { scope: caller.scope, scopePolicy: caller.policy });
989
+ return async (writers, asked, caller) => (await engineFor(writers)).execute(
990
+ "fingerprint" in asked ? { fingerprint: asked.fingerprint, context: asked.context ?? {} } : { intent: asked.intent, shape: asked.shape, context: asked.context ?? {} },
991
+ { scope: caller.scope, scopePolicy: caller.policy }
992
+ );
954
993
  };
955
994
 
956
995
  // src/data/data.ts
@@ -1251,8 +1290,29 @@ var shellComponents = (manifest, shell) => {
1251
1290
  for (const name of Object.keys(contracts)) names.add(name);
1252
1291
  return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
1253
1292
  };
1293
+ var createComponentNames = (read2) => {
1294
+ let components = /* @__PURE__ */ new WeakMap();
1295
+ return {
1296
+ of: (shell) => {
1297
+ const kept = components.get(shell);
1298
+ if (kept !== void 0) return kept;
1299
+ const names = read2(shell);
1300
+ components.set(shell, names);
1301
+ return names;
1302
+ },
1303
+ drop: () => {
1304
+ components = /* @__PURE__ */ new WeakMap();
1305
+ }
1306
+ };
1307
+ };
1254
1308
  var SavedLayoutSchema = z.strictObject({ ref: z.string(), layout: LayoutNodeSchema, use: z.boolean().optional() });
1255
1309
  var upgradedLayoutBody = (upgrader, body, stamp) => isRecord(body) && body["layout"] !== void 0 ? { ...body, layout: upgrader.upgrade(body["layout"], { kind: "nisc.nova/layout", stamp }).document } : body;
1310
+ var actionAtRef = (actions, layouts) => (ref) => {
1311
+ const id = actionOfLayoutRef(ref);
1312
+ const action = id !== void 0 && Object.hasOwn(actions, id) ? actions[id] : void 0;
1313
+ const layout = Object.hasOwn(layouts, ref) ? layouts[ref] : void 0;
1314
+ return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
1315
+ };
1256
1316
  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>".`;
1257
1317
  var targetAt = (ref, heldTo) => {
1258
1318
  if (heldTo.ownShell?.refs.has(ref) === true) return { kit: heldTo.ownShell.kit };
@@ -1338,7 +1398,7 @@ var endpointRefusals = async (endpoints, heldTo) => {
1338
1398
  var parsedUnder = (schema, body, id, more = {}) => {
1339
1399
  if (exceedsDepth(body)) return { refusal: depthRefusal() };
1340
1400
  if (isRecord(body) && body["id"] !== void 0 && body["id"] !== id) {
1341
- return { refusal: `it names the id "${String(body["id"])}". Moss gives what is generated its id: leave it out.` };
1401
+ return { refusal: `it names the id "${String(body["id"])}", and is kept under "${id}": leave the id out of the body.` };
1342
1402
  }
1343
1403
  const parsed = schema.safeParse(isRecord(body) ? { ...more, ...body, id } : body);
1344
1404
  if (parsed.success) return { body: parsed.data };
@@ -1540,7 +1600,7 @@ var unmarked = (versions, inForce2) => {
1540
1600
  });
1541
1601
  };
1542
1602
  var idsOf = (versions) => versions.map(({ kind, id }) => ({ kind, id }));
1543
- var savingFor = ({ holder, whose, kinds, written }, nobody) => {
1603
+ var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1544
1604
  const requireHolder = () => {
1545
1605
  if (holder === void 0) throw new Error(nobody);
1546
1606
  return holder;
@@ -1557,12 +1617,14 @@ var savingFor = ({ holder, whose, kinds, written }, nobody) => {
1557
1617
  };
1558
1618
  const checkedEach = async (asked, inForce2, held) => {
1559
1619
  const versions = [];
1560
- for (const { kind, id: named, body } of asked) {
1561
- const id = named ?? NEW_ID[kind]();
1620
+ for (const { kind, id: named2, body } of asked) {
1621
+ 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.`);
1622
+ const id = named2 ?? NEW_ID[kind]();
1562
1623
  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.`);
1563
1624
  versions.push({ kind, id, body: await checked(kind, id, body, held), copiedFrom: null });
1564
1625
  }
1565
- const notTheirs = asked.find(({ kind, id }) => id !== void 0 && kind !== "read" && !inForce2.some((version) => version.kind === kind && version.id === id));
1626
+ const named = (kind) => kind !== "read" && (defaults === void 0 || kind === "layout");
1627
+ const notTheirs = asked.find(({ kind, id }) => id !== void 0 && named(kind) && !inForce2.some((version) => version.kind === kind && version.id === id));
1566
1628
  if (notTheirs !== void 0) {
1567
1629
  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.`);
1568
1630
  }
@@ -1579,7 +1641,7 @@ var savingFor = ({ holder, whose, kinds, written }, nobody) => {
1579
1641
  return { requireHolder, ofKind, askedOf, checkedEach, write };
1580
1642
  };
1581
1643
  var savedArtifacts = (deps) => {
1582
- const { holder, whose, kinds } = deps;
1644
+ const { holder, whose, kinds, defaults } = deps;
1583
1645
  const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
1584
1646
  return {
1585
1647
  save: async (artifacts) => {
@@ -1588,6 +1650,7 @@ var savedArtifacts = (deps) => {
1588
1650
  const { saved, heldTo } = await holderOf();
1589
1651
  const inForce2 = await saved.inForce();
1590
1652
  const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1653
+ await defaults?.verify(versions, inForce2);
1591
1654
  return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1592
1655
  },
1593
1656
  list: async (kind) => {
@@ -1613,7 +1676,9 @@ var savedArtifacts = (deps) => {
1613
1676
  if (version.unread !== void 0) throw new Error(`moss: the ${known} "${id}" saved in "${save2}" cannot be read: ${version.unread}`);
1614
1677
  const inForce2 = await saved.inForce();
1615
1678
  const body = version.body === null ? null : await checked(known, id, version.body, await heldTo(inForce2));
1616
- return { save: await write(saved, [{ kind: known, id, body, copiedFrom: version.save }], inForce2) };
1679
+ const restored = { kind: known, id, body, copiedFrom: version.save };
1680
+ await defaults?.verify([restored], inForce2);
1681
+ return { save: await write(saved, [restored], inForce2) };
1617
1682
  },
1618
1683
  reset: async (kind, id) => {
1619
1684
  const holderOf = requireHolder();
@@ -1635,22 +1700,22 @@ var laidOver = (inForce2, drafted = []) => drafted.length === 0 ? inForce2 : [
1635
1700
  var draftSaving = (deps) => {
1636
1701
  const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a draft is somebody\u2019s to save.");
1637
1702
  return {
1638
- // The draft with these put into it. Each is checked beside what is in force for its holder with the draft laid over.
1639
- put: async (artifacts, drafted) => {
1703
+ // The draft with these added to it. Each is checked beside what is in force for its holder with the draft laid over.
1704
+ add: async (artifacts, drafted) => {
1640
1705
  const holderOf = requireHolder();
1641
1706
  const asked = askedOf(artifacts);
1642
1707
  const { saved, heldTo } = await holderOf();
1643
1708
  const inForce2 = laidOver(await saved.inForce(), drafted);
1644
1709
  const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1645
- const put = versions.map(({ kind, id, body }) => ({ kind, id, body }));
1646
- const marked = new Set(markedRefs(put));
1710
+ const added = versions.map(({ kind, id, body }) => ({ kind, id, body }));
1711
+ const marked = new Set(markedRefs(added));
1647
1712
  const kept = drafted.flatMap((one) => {
1648
- if (put.some((other) => other.kind === one.kind && other.id === one.id)) return [];
1713
+ if (added.some((other) => other.kind === one.kind && other.id === one.id)) return [];
1649
1714
  const ref = refOf(one.body);
1650
1715
  const loses = one.kind === "layout" && isRecord(one.body) && one.body["use"] === true && ref !== void 0 && marked.has(ref);
1651
1716
  return [loses && isRecord(one.body) ? { ...one, body: withoutMark(one.body) } : one];
1652
1717
  });
1653
- return { drafted: [...kept, ...put], put: idsOf(versions) };
1718
+ return { drafted: [...kept, ...added], added: idsOf(versions) };
1654
1719
  },
1655
1720
  save: async (drafted) => {
1656
1721
  const holderOf = requireHolder();
@@ -1739,6 +1804,51 @@ var createGeneration = (pointer, ctx) => {
1739
1804
  }
1740
1805
  };
1741
1806
  };
1807
+
1808
+ // src/artifactory/published.ts
1809
+ var NO_DEFAULTS = { actions: {}, fragments: {}, reads: /* @__PURE__ */ new Map() };
1810
+ var drawableIn = (fragments, kit, say) => Object.fromEntries(
1811
+ Object.entries(fragments).filter(([id, fragment]) => {
1812
+ const misfits = layoutMisfits(fragment.layout, kit);
1813
+ if (misfits.length > 0) say(`[moss] the fragment "${id}" published for everybody is left out of a shell that cannot draw it: ${misfits.join("; ")}`);
1814
+ return misfits.length === 0;
1815
+ })
1816
+ );
1817
+ var createPublishedMemo = () => {
1818
+ let read2;
1819
+ let said = /* @__PURE__ */ new Set();
1820
+ return {
1821
+ held: () => read2,
1822
+ keep: (promise) => {
1823
+ read2 = promise;
1824
+ },
1825
+ drop: () => {
1826
+ read2 = void 0;
1827
+ said = /* @__PURE__ */ new Set();
1828
+ },
1829
+ sayOnce: (line) => {
1830
+ if (said.has(line)) return;
1831
+ said.add(line);
1832
+ console.error(line);
1833
+ }
1834
+ };
1835
+ };
1836
+ var hasDefaults = (defaults) => Object.keys(defaults.actions).length > 0 || Object.keys(defaults.fragments).length > 0 || defaults.reads.size > 0;
1837
+ var checkedDefaults = async (versions, heldTo, whose) => {
1838
+ const reads = heldTo.reads === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, heldTo.reads, whose);
1839
+ const checks = {
1840
+ kit: heldTo.kit,
1841
+ entryOf: (fingerprint) => {
1842
+ const read2 = reads.get(fingerprint);
1843
+ return heldTo.entryOf(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
1844
+ },
1845
+ replayable: async () => /* @__PURE__ */ new Set([...heldTo.fingerprints(), ...reads.keys()]),
1846
+ mayCall: () => true,
1847
+ catalog: () => [...Object.values(heldTo.built).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1848
+ };
1849
+ const passed = await generatedInForce(versions, checks, whose);
1850
+ return { passed, reads, verified: verifyManifest(heldTo.candidate({ ...heldTo.built, ...passed.actions }, passed.fragments)) };
1851
+ };
1742
1852
  var narrowedBy = (filter, ids, installed) => {
1743
1853
  const answered = new Set(filter(ids, installed));
1744
1854
  return ids.filter((id) => answered.has(id));
@@ -1805,15 +1915,7 @@ var versionToken = (ids) => {
1805
1915
  return h.toString(16).padStart(8, "0");
1806
1916
  };
1807
1917
 
1808
- // src/artifactory/running.ts
1809
- var mergedActions = (own, sets) => Object.freeze([...sets.values()].reduce((all, set) => ({ ...all, ...set }), { ...own }));
1810
- var tell = (listener, ...told) => {
1811
- try {
1812
- listener(...told);
1813
- } catch (error) {
1814
- console.error("[moss:manifest] a listener to a manifest change threw:", error);
1815
- }
1816
- };
1918
+ // src/artifactory/sets.ts
1817
1919
  var createSetOwners = () => {
1818
1920
  const owners = /* @__PURE__ */ new Map();
1819
1921
  const ownerRefusalOf = (source) => {
@@ -1835,32 +1937,42 @@ var createSetOwners = () => {
1835
1937
  }
1836
1938
  };
1837
1939
  };
1838
- var verifiedAtBoot = (candidate) => {
1839
- const report = verifyManifest(candidate);
1840
- for (const line of report.said) console.error(`[moss] ${line}`);
1841
- const refused = refusalOf(report, "boot");
1842
- if (refused !== void 0) throw new Error(refused);
1843
- return report;
1844
- };
1845
- var createComponentNames = (read2) => {
1846
- let components = /* @__PURE__ */ new WeakMap();
1940
+
1941
+ // src/artifactory/usage.ts
1942
+ var TOUCH_EVERY_MS = 36e5;
1943
+ var createUsage = (everyMs, now = Date.now) => {
1944
+ const stamped2 = /* @__PURE__ */ new Map();
1847
1945
  return {
1848
- of: (shell) => {
1849
- const kept = components.get(shell);
1850
- if (kept !== void 0) return kept;
1851
- const names = read2(shell);
1852
- components.set(shell, names);
1853
- return names;
1854
- },
1855
- drop: () => {
1856
- components = /* @__PURE__ */ new WeakMap();
1946
+ touch: (principal, versions, rows) => {
1947
+ const at = now();
1948
+ for (const [key, when] of stamped2) if (when <= at - everyMs) stamped2.delete(key);
1949
+ const due = versions.filter((version) => version.body !== null && !stamped2.has(`${principal}\0${version.kind}\0${version.id}`));
1950
+ if (due.length === 0) return;
1951
+ for (const version of due) stamped2.set(`${principal}\0${version.kind}\0${version.id}`, at);
1952
+ rows.touch(
1953
+ due.map((version) => ({ kind: version.kind, id: version.id })),
1954
+ new Date(at).toISOString()
1955
+ ).catch((error) => console.error(`[moss] the artifacts of ${principal} could not be stamped as used:`, error));
1857
1956
  }
1858
1957
  };
1859
1958
  };
1959
+
1960
+ // src/artifactory/running.ts
1961
+ var mergedActions = (own, sets, over = {}) => Object.freeze([...sets.values(), over].reduce((all, set) => ({ ...all, ...set }), { ...own }));
1962
+ var tell = (listener, ...told) => {
1963
+ try {
1964
+ listener(...told);
1965
+ } catch (error) {
1966
+ console.error("[moss:manifest] a listener to a manifest change threw:", error);
1967
+ }
1968
+ };
1860
1969
  var createRunningManifest = (config) => {
1861
1970
  const { shipped } = config;
1862
1971
  const entries = createEntriesInForce(entriesOf(shipped));
1863
- const candidate = (actions, held = entries.list()) => candidateOf(shipped, { actions, entries: held }, config.grants);
1972
+ let defaults = NO_DEFAULTS;
1973
+ const usage = createUsage(config.touchEveryMs ?? TOUCH_EVERY_MS);
1974
+ let functionIds;
1975
+ const candidate = (actions, held = entries.list(), fragments = defaults.fragments) => withFragments({ ...candidateOf(shipped, { actions, entries: held }, config.grants), ...functionIds === void 0 ? {} : { functionIds } }, fragments);
1864
1976
  const own = shipped.actions;
1865
1977
  const loaders = /* @__PURE__ */ new Map();
1866
1978
  const owners = createSetOwners();
@@ -1876,6 +1988,11 @@ var createRunningManifest = (config) => {
1876
1988
  return kit;
1877
1989
  };
1878
1990
  let ofTheApp;
1991
+ const dropMemos = () => {
1992
+ roleMemo.drop();
1993
+ components.drop();
1994
+ ofTheApp = void 0;
1995
+ };
1879
1996
  const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
1880
1997
  const roleMemo = createRoleMemo({
1881
1998
  manifest: () => ({ charter: shipped.charter, actions: inForce2, layouts: shipped.layouts }),
@@ -1890,33 +2007,39 @@ var createRunningManifest = (config) => {
1890
2007
  kit,
1891
2008
  // A layout saved for the frame or a canvas is the app's own shell's, whichever shell it is saved from.
1892
2009
  ...ownShell !== void 0 && (shell === void 0 || shell === ownShell) ? { ownShell: { refs: ownShellRefs, kit: shell === ownShell ? kit : kitOf2(ownShell) } } : {},
1893
- actionAt: (ref) => {
1894
- const id = actionOfLayoutRef(ref);
1895
- const action = id !== void 0 && Object.hasOwn(actions, id) ? actions[id] : void 0;
1896
- const layout = Object.hasOwn(layouts, ref) ? layouts[ref] : void 0;
1897
- return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
1898
- }
2010
+ actionAt: actionAtRef(actions, layouts)
1899
2011
  };
1900
2012
  };
1901
2013
  const { reads: readSources } = config;
1902
- let functionsChecked = false;
1903
- const sayFunctionGrants = (names) => {
1904
- functionsChecked = true;
1905
- const universes = { actions: Object.keys(inForce2), data: config.grants, layouts: Object.keys(shipped.layouts ?? {}) };
1906
- const before = verifyCharter(shipped.charter, universes);
1907
- const known = new Set([...before.errors, ...before.warnings].map((issue) => issue.detail));
1908
- const after = verifyCharter(shipped.charter, { ...universes, functions: names });
1909
- for (const issue of [...after.errors, ...after.warnings]) if (!known.has(issue.detail)) console.warn(`[moss] charter: ${issue.detail}`);
1910
- };
1911
- const grantedFunctionsOf = (roles) => (names) => {
1912
- if (!functionsChecked) sayFunctionGrants(names);
1913
- return resolvePrincipal(shipped.charter, names, roles, "functions");
1914
- };
2014
+ const functionsWritten = (written) => {
2015
+ if (functionIds !== void 0) return;
2016
+ const ids = functionsIn(written).map((definition) => definition.id);
2017
+ const charter = charterOverFunctions(shipped.charter, { actions: Object.keys(inForce2), data: config.grants, layouts: Object.keys(shipped.layouts ?? {}) }, ids);
2018
+ if (charter.errors.length > 0) throw new Error(`Charter is incoherent over the app\u2019s functions \u2014 refusing to serve:
2019
+ ${charter.errors.join("\n ")}`);
2020
+ functionIds = new Set(ids);
2021
+ const built = mergedActions(own, sets);
2022
+ const verified = verifyManifest(candidate(built, entries.list(), {}));
2023
+ const refusal = refusalOf(verified, "boot");
2024
+ if (refusal !== void 0) {
2025
+ functionIds = void 0;
2026
+ throw new Error(refusal);
2027
+ }
2028
+ report = verified;
2029
+ defaults = NO_DEFAULTS;
2030
+ inForce2 = built;
2031
+ dropMemos();
2032
+ memo.drop();
2033
+ for (const warning2 of charter.warnings) console.warn(`[moss] charter: ${warning2}`);
2034
+ const warning = functionsWarning(written);
2035
+ if (warning !== void 0) console.warn(warning);
2036
+ };
2037
+ const grantedFunctionsOf = (roles) => (names) => resolvePrincipal(shipped.charter, names, roles, "functions");
1915
2038
  const readsHeldTo = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
1916
2039
  const heldWithGenerated = async (held, versions, who, shell, whose) => {
1917
2040
  let replayable;
1918
2041
  let catalog;
1919
- const reads = readsHeldTo === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, readsHeldTo, whose);
2042
+ const reads = new Map([...defaults.reads, ...readsHeldTo === void 0 ? [] : await readsInForce(versions, readsHeldTo, whose)]);
1920
2043
  const checks = {
1921
2044
  kit: kitOf2(shell),
1922
2045
  entryOf: (fingerprint) => {
@@ -1934,10 +2057,12 @@ var createRunningManifest = (config) => {
1934
2057
  };
1935
2058
  const listeners = /* @__PURE__ */ new Set();
1936
2059
  const listenersFor = /* @__PURE__ */ new Set();
2060
+ const kinds = readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"];
1937
2061
  const sessionDeps = (principal, callerOf, shell) => ({
1938
2062
  whose: "of yours",
1939
- kinds: readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"],
2063
+ kinds,
1940
2064
  holder: principal === null ? void 0 : async () => {
2065
+ await publishedNow();
1941
2066
  const caller = await callerOf();
1942
2067
  const held = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
1943
2068
  return { saved: caller.saved, heldTo: async (inForce3) => (await heldWithGenerated(held, inForce3, caller, shell)).heldTo };
@@ -1947,27 +2072,43 @@ var createRunningManifest = (config) => {
1947
2072
  }
1948
2073
  });
1949
2074
  let pointer;
1950
- let published;
1951
- let saidOfPublished = /* @__PURE__ */ new Set();
1952
- const dropPublished = () => {
1953
- published = void 0;
1954
- saidOfPublished = /* @__PURE__ */ new Set();
2075
+ const memo = createPublishedMemo();
2076
+ const defaultsHeldTo = () => ({
2077
+ kit: kitOf2(),
2078
+ entryOf: (fingerprint) => entries.byFingerprint().get(fingerprint),
2079
+ fingerprints: () => entries.byFingerprint().keys(),
2080
+ reads: readsHeldTo,
2081
+ built: mergedActions(own, sets),
2082
+ candidate: (actions, fragments) => candidate(actions, entries.list(), fragments)
2083
+ });
2084
+ const applyPublished = async (versions) => {
2085
+ const over = sets;
2086
+ const { passed, reads, verified } = await checkedDefaults(versions, defaultsHeldTo(), "published for everybody");
2087
+ if (sets !== over) return applyPublished(versions);
2088
+ const refusal = refusalOf(verified, "boot");
2089
+ if (refusal !== void 0) memo.sayOnce(`[moss] what is published for everybody is left out, and the build\u2019s copies stand: ${refusal}`);
2090
+ const next = refusal === void 0 ? { actions: passed.actions, fragments: passed.fragments, reads } : { ...NO_DEFAULTS, reads };
2091
+ if (!hasDefaults(next) && !hasDefaults(defaults)) return;
2092
+ defaults = next;
2093
+ if (refusal === void 0) report = verified;
2094
+ inForce2 = mergedActions(own, sets, defaults.actions);
2095
+ dropMemos();
1955
2096
  };
1956
2097
  const publishedNow = () => {
1957
- if (published !== void 0) return published;
1958
- const read2 = (async () => await config.published?.() ?? [])();
1959
- published = read2;
1960
- read2.catch(dropPublished);
2098
+ const held = memo.held();
2099
+ if (held !== void 0) return held;
2100
+ const read2 = (async () => {
2101
+ const versions = await config.published?.() ?? [];
2102
+ await applyPublished(versions);
2103
+ return versions;
2104
+ })();
2105
+ memo.keep(read2);
2106
+ read2.catch(memo.drop);
1961
2107
  return read2;
1962
2108
  };
1963
- const sayOnce = (line) => {
1964
- if (saidOfPublished.has(line)) return;
1965
- saidOfPublished.add(line);
1966
- console.error(line);
1967
- };
1968
2109
  const applySets = (arrived, announce) => {
1969
2110
  const next = new Map([...sets, ...arrived]);
1970
- const actions = mergedActions(own, next);
2111
+ const actions = mergedActions(own, next, defaults.actions);
1971
2112
  const verified = verifyManifest(candidate(actions));
1972
2113
  const refusal = refusalOf(verified, "refresh");
1973
2114
  if (refusal !== void 0) throw new Error(refusal);
@@ -1975,16 +2116,14 @@ var createRunningManifest = (config) => {
1975
2116
  sets = next;
1976
2117
  inForce2 = actions;
1977
2118
  report = verified;
1978
- roleMemo.drop();
1979
- components.drop();
1980
- ofTheApp = void 0;
2119
+ dropMemos();
1981
2120
  for (const listener of [...listeners]) tell(listener);
1982
2121
  if (announce) pointer?.bump();
1983
2122
  };
1984
2123
  const reload = async () => {
1985
2124
  const read2 = [];
1986
2125
  for (const [source, load] of loaders) read2.push([source, await load()]);
1987
- dropPublished();
2126
+ memo.drop();
1988
2127
  applySets(new Map(read2), false);
1989
2128
  };
1990
2129
  const takeEntries = async (source, handed) => {
@@ -2017,11 +2156,15 @@ var createRunningManifest = (config) => {
2017
2156
  },
2018
2157
  cacheEntry: async (fingerprint, scope) => {
2019
2158
  const shippedEntry = (await entries.compiled()).get(fingerprint);
2020
- const userId = scope?.["userId"];
2021
- if (shippedEntry !== void 0 || readSources === void 0 || scope === void 0 || typeof userId !== "string" || userId === NOBODY_USER_ID) return shippedEntry;
2022
- const newest = (await readSources.savedOf(scope).history("read", fingerprint))[0];
2023
- if (newest === void 0 || newest.body === null || newest.unread !== void 0) return void 0;
2024
- return answeredRead(fingerprint, newest.body);
2159
+ if (shippedEntry !== void 0 || readSources === void 0 || scope === void 0) return shippedEntry;
2160
+ const userId = scope["userId"];
2161
+ if (typeof userId === "string" && userId !== NOBODY_USER_ID) {
2162
+ const newest = (await readSources.savedOf(scope).history("read", fingerprint))[0];
2163
+ if (newest !== void 0 && newest.body !== null && newest.unread === void 0) return answeredRead(fingerprint, newest.body);
2164
+ }
2165
+ await publishedNow();
2166
+ const everybodys = defaults.reads.get(fingerprint);
2167
+ return everybodys === void 0 ? void 0 : compiledRead(fingerprint, everybodys);
2025
2168
  },
2026
2169
  cacheEntries: async () => [...await entries.compiled()].map(([key, entry]) => ({ key, entry })),
2027
2170
  claim: (source, owner) => {
@@ -2035,6 +2178,7 @@ var createRunningManifest = (config) => {
2035
2178
  };
2036
2179
  },
2037
2180
  refresh: () => applySets(/* @__PURE__ */ new Map(), true),
2181
+ functionsWritten,
2038
2182
  watch: () => {
2039
2183
  const where = config.pointer;
2040
2184
  if (pointer !== void 0 || where === void 0) return;
@@ -2052,15 +2196,19 @@ var createRunningManifest = (config) => {
2052
2196
  },
2053
2197
  catalogFor: roleMemo.catalogFor,
2054
2198
  artifactsFor: async (shell, { principal, roles, installed, saved, replayable, drafted }) => {
2055
- const versions = saved === void 0 || principal === null ? [] : laidOver(await saved.inForce(), drafted);
2199
+ const own2 = saved === void 0 || principal === null ? [] : await saved.inForce();
2200
+ if (saved !== void 0 && principal !== null) usage.touch(principal, own2, saved);
2201
+ const versions = own2.length === 0 && drafted === void 0 ? [] : laidOver(own2, drafted);
2202
+ const everybodysVersions = await publishedNow();
2056
2203
  const whose = `of ${principal ?? "nobody"}`;
2057
2204
  const theirOwn = await heldWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
2058
2205
  const drawable = theirOwn.heldTo.layouts;
2059
2206
  const theirs2 = layoutsInUse(versions, { whose, heldTo: drawable });
2060
2207
  const variants = roleMemo.variantsFor(roles);
2061
2208
  const underVariants = { ...drawable, actionAt: (ref) => variants.has(actionOfLayoutRef(ref) ?? "") ? void 0 : drawable.actionAt(ref) };
2062
- const everybodys = layoutsInUse(await publishedNow(), { whose: "published for everybody", heldTo: underVariants, say: sayOnce });
2063
- const fragments = Object.keys(theirOwn.fragments).length === 0 ? shell.fragments : { ...shell.fragments, ...theirOwn.fragments };
2209
+ const everybodys = layoutsInUse(everybodysVersions, { whose: "published for everybody", heldTo: underVariants, say: memo.sayOnce });
2210
+ const laidOverShell = { ...drawableIn(defaults.fragments, kitOf2(shell), memo.sayOnce), ...theirOwn.fragments };
2211
+ const fragments = Object.keys(laidOverShell).length === 0 ? shell.fragments : { ...shell.fragments, ...laidOverShell };
2064
2212
  const { layouts: ofShell, ...named } = shellWithStoredLayouts(shell);
2065
2213
  const layoutStore = { ...shell.layoutStore, ...ofShell, ...theirOwn.all.layouts, ...everybodys, ...theirs2 };
2066
2214
  return {
@@ -2078,18 +2226,29 @@ var createRunningManifest = (config) => {
2078
2226
  draftSavingFor: (shell, principal, callerOf) => draftSaving(sessionDeps(principal, callerOf, shell)),
2079
2227
  // Held to every action in force with the layout it is built with: who holds
2080
2228
  // which is asked when a shell is built for them.
2081
- publishedArtifacts: (saved) => savedArtifacts({
2229
+ publishedArtifacts: (saved, publisher) => savedArtifacts({
2082
2230
  whose: "published for everybody",
2083
- kinds: ["layout"],
2084
- holder: async () => ({ saved, heldTo: async () => (await heldWithGenerated(actionsWithStoredLayouts(inForce2), [], {})).heldTo }),
2231
+ kinds,
2232
+ holder: async () => {
2233
+ const who = await publisher();
2234
+ return { saved, heldTo: async (inForce3) => (await heldWithGenerated(actionsWithStoredLayouts(mergedActions(own, sets)), inForce3, who)).heldTo };
2235
+ },
2236
+ defaults: {
2237
+ verify: async (versions, inForce3) => {
2238
+ const kept = inForce3.filter((held) => !versions.some((version) => version.kind === held.kind && version.id === held.id));
2239
+ const asked = versions.map((version) => ({ ...version, save: "", createdAt: "" }));
2240
+ const refusal = refusalOf((await checkedDefaults([...kept, ...asked], defaultsHeldTo(), void 0)).verified, "publish");
2241
+ if (refusal !== void 0) throw new Error(refusal);
2242
+ }
2243
+ },
2085
2244
  written: () => {
2086
- dropPublished();
2245
+ memo.drop();
2087
2246
  for (const listener of [...listeners]) tell(listener);
2088
2247
  pointer?.bump();
2089
2248
  }
2090
2249
  }),
2091
2250
  readPublished: async () => {
2092
- dropPublished();
2251
+ memo.drop();
2093
2252
  await publishedNow();
2094
2253
  },
2095
2254
  onChangeFor: (listener) => {
@@ -2181,7 +2340,19 @@ var save = {
2181
2340
  }
2182
2341
  ]
2183
2342
  };
2184
- var SAVE_ENTRIES = [inForce, history, save];
2343
+ var touch = {
2344
+ fingerprint: "artifactory/touch",
2345
+ intent: "Mark one of the caller\u2019s artifacts as used now",
2346
+ mutation: [
2347
+ {
2348
+ op: "update",
2349
+ table: "artifacts",
2350
+ set: { last_used_at: { $context: "at" } },
2351
+ where: { and: [{ eq: ["artifacts.kind", { $context: "kind" }] }, { eq: ["artifacts.id", { $context: "id" }] }] }
2352
+ }
2353
+ ]
2354
+ };
2355
+ var SAVE_ENTRIES = [inForce, history, save, touch];
2185
2356
  var RowSchema2 = z.object({
2186
2357
  save: z.string(),
2187
2358
  kind: z.string(),
@@ -2224,6 +2395,9 @@ var savedRowsOver = (replay, upgrader) => {
2224
2395
  write: async (saved) => {
2225
2396
  const versions = saved.versions.map((version) => ({ kind: version.kind, id: version.id, body: version.body, grammar: upgrader.stamp, copied_from: version.copiedFrom }));
2226
2397
  await replay(save.fingerprint, { save: saved.id, versions }, scope);
2398
+ },
2399
+ touch: async (artifacts, at) => {
2400
+ for (const { kind, id } of artifacts) await replay(touch.fingerprint, { kind, id, at }, scope);
2227
2401
  }
2228
2402
  };
2229
2403
  };
@@ -2964,21 +3138,20 @@ var hostConfig = (deps, shell, kept) => {
2964
3138
  }
2965
3139
  };
2966
3140
  };
2967
- var sayingWhatToFix = (functions) => {
2968
- let said = false;
3141
+ var checkedOnce = (functions, written) => {
3142
+ let checked2 = false;
2969
3143
  return (session) => {
2970
- const written = functions(session);
2971
- if (!said) {
2972
- said = true;
2973
- const warning = functionsWarning(written);
2974
- if (warning !== void 0) console.warn(warning);
3144
+ const given = functions(session);
3145
+ if (!checked2) {
3146
+ written(given);
3147
+ checked2 = true;
2975
3148
  }
2976
- return written;
3149
+ return given;
2977
3150
  };
2978
3151
  };
2979
3152
  var buildShellHosts = (deps) => {
2980
3153
  const { app } = deps;
2981
- const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: sayingWhatToFix(app.functions) } };
3154
+ const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: checkedOnce(app.functions, deps.running.functionsWritten) } };
2982
3155
  const pageManifests = app.pages ?? {};
2983
3156
  const pageRouter = createPageRouter(pageManifests);
2984
3157
  const shells = app.shell !== void 0 ? createShellHost(hostConfig(wired, app.shell, true)) : void 0;
@@ -2996,6 +3169,11 @@ var buildShellHosts = (deps) => {
2996
3169
  return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
2997
3170
  },
2998
3171
  pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
3172
+ buildForNobody: async () => {
3173
+ if (app.functions === void 0) deps.running.functionsWritten([]);
3174
+ else await every[0]?.snapshot(null, null, { waitMs: 0 });
3175
+ await deps.running.readPublished();
3176
+ },
2999
3177
  adopt: () => {
3000
3178
  for (const made of owned) made.adopt();
3001
3179
  },
@@ -3240,6 +3418,14 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3240
3418
  const saved = savedRowsOver(await data.artifactEntries(SAVE_ENTRIES, SAVE_ROW_RULES), data.grammars);
3241
3419
  const running = await buildRunningManifest(app, runtime, data, saved);
3242
3420
  stops.push(running.stop);
3421
+ if (runtime.artifactsUnusedMs !== void 0) {
3422
+ if (!Number.isSafeInteger(runtime.artifactsUnusedMs) || runtime.artifactsUnusedMs < 2 * TOUCH_EVERY_MS) {
3423
+ throw new Error(
3424
+ `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.`
3425
+ );
3426
+ }
3427
+ stops.push(startAging(runtime.pool, runtime.artifactsUnusedMs));
3428
+ }
3243
3429
  const identity = buildIdentity(app, runtime, data);
3244
3430
  stops.push(identity.stop);
3245
3431
  const server = new Hono();
@@ -3266,6 +3452,7 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3266
3452
  principalOf: async (token) => session(token),
3267
3453
  page: hosts.pageAt,
3268
3454
  pages: hosts.pages,
3455
+ checkFunctions: hosts.buildForNobody,
3269
3456
  ...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
3270
3457
  refresh: running.refresh,
3271
3458
  replaceActions: running.replace,
@@ -3275,7 +3462,10 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3275
3462
  if (typeof publisher !== "string" || publisher === "") {
3276
3463
  throw new Error("moss: `defaults` is handed who publishes. What is published is everybody\u2019s, and who published it is kept with it.");
3277
3464
  }
3278
- return running.publishedArtifacts(saved.published(publisher));
3465
+ return running.publishedArtifacts(saved.published(publisher), async () => {
3466
+ const resolved = await identity.resolve(publisher);
3467
+ return { roles: resolved.roles, replayable: () => data.fingerprintsFor(resolved) };
3468
+ });
3279
3469
  },
3280
3470
  catalogOf: async (principal) => {
3281
3471
  const resolved = await identity.resolve(principal);
@@ -3362,5 +3552,5 @@ var subscribeReactions = ({ app, onWrite, deliver }) => {
3362
3552
  };
3363
3553
 
3364
3554
  export { MOSS_SEQUENCE, createServer, exportDocuments, migrateTables, mintDevToken, mintSession, renderDocument, revokeAllFor, sessionCookies };
3365
- //# sourceMappingURL=chunk-MTC46PGQ.js.map
3366
- //# sourceMappingURL=chunk-MTC46PGQ.js.map
3555
+ //# sourceMappingURL=chunk-YZILOVCR.js.map
3556
+ //# sourceMappingURL=chunk-YZILOVCR.js.map