@niscorp/moss 0.9.0 → 0.9.2

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 (70) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/DESIGN.md +1 -1
  3. package/DOCS.md +95 -25
  4. package/dist/{chunk-WTWRLOPK.js → chunk-5ZB7FZ2J.js} +3 -3
  5. package/dist/{chunk-WTWRLOPK.js.map → chunk-5ZB7FZ2J.js.map} +1 -1
  6. package/dist/{chunk-E6YAYR7G.cjs → chunk-6ZWMC2OV.cjs} +6 -6
  7. package/dist/{chunk-E6YAYR7G.cjs.map → chunk-6ZWMC2OV.cjs.map} +1 -1
  8. package/dist/{chunk-UUOATPZ7.js → chunk-FUJRIO4N.js} +20 -4
  9. package/dist/chunk-FUJRIO4N.js.map +1 -0
  10. package/dist/{chunk-TGKDS2T7.cjs → chunk-IY5BOFLK.cjs} +222 -37
  11. package/dist/chunk-IY5BOFLK.cjs.map +1 -0
  12. package/dist/{chunk-LKTS4PCD.cjs → chunk-KMZT6NVL.cjs} +23 -7
  13. package/dist/chunk-KMZT6NVL.cjs.map +1 -0
  14. package/dist/{chunk-L2GHVTJW.cjs → chunk-KVXP6OTW.cjs} +88 -81
  15. package/dist/chunk-KVXP6OTW.cjs.map +1 -0
  16. package/dist/{chunk-3RIWTXGI.cjs → chunk-NCQBGK3E.cjs} +6 -2
  17. package/dist/chunk-NCQBGK3E.cjs.map +1 -0
  18. package/dist/{chunk-4ZGAFZGS.js → chunk-TKXYPO2Y.js} +6 -2
  19. package/dist/chunk-TKXYPO2Y.js.map +1 -0
  20. package/dist/{chunk-TLNRFAQ6.js → chunk-UTFOMFCH.js} +207 -22
  21. package/dist/chunk-UTFOMFCH.js.map +1 -0
  22. package/dist/{chunk-Y7PRASR3.js → chunk-WMIJU6ZZ.js} +12 -5
  23. package/dist/chunk-WMIJU6ZZ.js.map +1 -0
  24. package/dist/client/node.d.cts +2 -2
  25. package/dist/client/node.d.ts +2 -2
  26. package/dist/client.cjs +5 -5
  27. package/dist/client.d.cts +7 -4
  28. package/dist/client.d.ts +7 -4
  29. package/dist/client.js +2 -2
  30. package/dist/{env-CY8EGWnD.d.cts → env-3qvvochI.d.cts} +3 -1
  31. package/dist/{env-DEPqqHEb.d.ts → env-DBPDpfU8.d.ts} +3 -1
  32. package/dist/index.cjs +15 -15
  33. package/dist/index.js +3 -3
  34. package/dist/{messages-CSwCJgH3.d.cts → messages-OSnNJL80.d.cts} +2 -0
  35. package/dist/{messages-CSwCJgH3.d.ts → messages-OSnNJL80.d.ts} +2 -0
  36. package/dist/node.cjs +8 -8
  37. package/dist/node.js +4 -4
  38. package/dist/protocol.cjs +5 -5
  39. package/dist/protocol.d.cts +1 -1
  40. package/dist/protocol.d.ts +1 -1
  41. package/dist/protocol.js +1 -1
  42. package/dist/terminal/dom/index.d.cts +2 -2
  43. package/dist/terminal/dom/index.d.ts +2 -2
  44. package/dist/terminal/index.cjs +3 -3
  45. package/dist/terminal/index.d.cts +2 -2
  46. package/dist/terminal/index.d.ts +2 -2
  47. package/dist/terminal/index.js +2 -2
  48. package/dist/terminal/react/index.d.cts +2 -2
  49. package/dist/terminal/react/index.d.ts +2 -2
  50. package/dist/terminal/react/server.d.cts +2 -2
  51. package/dist/terminal/react/server.d.ts +2 -2
  52. package/dist/terminal/tty/index.d.cts +2 -2
  53. package/dist/terminal/tty/index.d.ts +2 -2
  54. package/dist/terminal/vue/index.d.cts +2 -2
  55. package/dist/terminal/vue/index.d.ts +2 -2
  56. package/dist/terminal/vue/server.d.cts +2 -2
  57. package/dist/terminal/vue/server.d.ts +2 -2
  58. package/dist/unverified.cjs +3 -3
  59. package/dist/unverified.js +2 -2
  60. package/dist/vite.cjs +9 -9
  61. package/dist/vite.js +4 -4
  62. package/package.json +13 -13
  63. package/dist/chunk-3RIWTXGI.cjs.map +0 -1
  64. package/dist/chunk-4ZGAFZGS.js.map +0 -1
  65. package/dist/chunk-L2GHVTJW.cjs.map +0 -1
  66. package/dist/chunk-LKTS4PCD.cjs.map +0 -1
  67. package/dist/chunk-TGKDS2T7.cjs.map +0 -1
  68. package/dist/chunk-TLNRFAQ6.js.map +0 -1
  69. package/dist/chunk-UUOATPZ7.js.map +0 -1
  70. package/dist/chunk-Y7PRASR3.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/manifest/app.ts","../src/manifest/verify.ts","../src/manifest/schema.ts","../src/shells/draft.ts","../src/shells/host-state.ts","../src/shells/stream.ts","../src/shells/sessions.ts","../src/shells/build.ts"],"names":["shell","scopeProfiles","exceedsDepth","depthRefusal","ActionDefinitionSchema","isRecord","layout","entry","resolvePrincipal","charter","normalizeRole","chainCycles","verifyCharter","collectChannels","auditAction","isBinding","walkNodes","record","z","LayoutNodeSchema","ActionFragmentSchema","QuerySchema","ConfigSchema","REFRESH_MODES","MutationDefinitionSchema","SequenceSchema","whole","canvasTreeOf","encodeDelta","frameHash","spanClock","CLOSE_SIGNED_OUT","NovaEventSchema","declared","withFragments","createComponentRegistry","createLayoutStore","createShell","config","evaluate"],"mappings":";;;;;;;;;;;;;;AAeO,IAAM,WAAA,GAAc,CAAC,OAAA,KAA6D;AACvF,EAAA,MAAM,GAAA,uBAAU,GAAA,EAAY;AAC5B,EAAA,OAAO,MAAA,CAAO,QAA8C,OAAO,CAAA,CAAE,IAAI,CAAC,CAAC,GAAA,EAAK,KAAK,CAAA,KAAM;AACzF,IAAA,MAAM,UAAA,GAAa,OAAO,KAAA,KAAU,UAAA,GAAa,EAAE,EAAA,EAAI,GAAA,EAAK,WAAA,EAAa,EAAA,EAAI,OAAA,EAAS,KAAA,EAAM,GAAI,KAAA;AAChG,IAAA,IAAI,GAAA,CAAI,GAAA,CAAI,UAAA,CAAW,EAAE,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,CAAA,mCAAA,EAAsC,UAAA,CAAW,EAAE,CAAA,QAAA,CAAU,CAAA;AACzG,IAAA,GAAA,CAAI,GAAA,CAAI,WA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EAAiB,IAAI,GAAA,CAAI,IAAA,CAAK,eAAe,CAAA;AAAA,IAC7C,SAAA;AAAA,IACA,OAAO,OAAA,EAAQ;AAAA,IACf,WAAA,sBAAiB,GAAA,EAAI;AAAA,IACrB,YAAA,sBAAkB,GAAA,EAAI;AAAA,IACtB,UAAA,sBAAgB,GAAA,EAAI;AAAA,IACpB,QAAA,EAAU,KAAA;AAAA,IACV,KAAA,EAAO,KAAA;AAAA,IACP,OAAA,EAAS,KAAK,GAAA,EAAI;AAAA,IAClB,SAAA,EAAW,KAAK,GAAA,EAAI;AAAA,IACpB,MAAA,EAAQ,QAAQ,OAAA;AAAQ,GAC1B;AACA,EAAA,QAAA,CAAS,IAAA,GAAO,IAAA;AAEhB,EAAA,YAAA,CAAa,IAAA,EAAM,KAAA,CAAM,KAAA,GAAQ,EAAE,SAAA,EAAW,OAAA,EAAS,GAAA,EAAK,KAAA,EAAO,IAAA,CAAK,KAAA,EAAO,IAAA,EAAM,GAAG,OAAO,CAAA;AAC/F,EAAA,MAAA,CAAO,MAAM,KAAK,CAAA;AAElB,EAAA,IAAI,IAAA,KAAS,MAAA,IAAa,UAAA,KAAe,MAAA,EAAW;AAClD,IAAA,IAAA,CAAK,EAAE,IAAA,EAAM,aAAA,EAAe,eAAe,UAAA,CAAW,aAAA,EAAe,aAAa,UAAA,CAAW,WAAA,IAAe,MAAA,EAAQ,IAAA,EAAM,YAAY,EAAE,KAAA,EAAO,cAAc,SAAA,KAAc,IAAA,IAAQ,CAAA;AAAA,EACrL;AAEA,EAAA,OAAO,IAAA;AACT","file":"chunk-E6YAYR7G.cjs","sourcesContent":["import type { Sequence } from '@niscorp/strata';\nimport type { GenerateDsl, MapToShape, QueryResponse, ScopeBehaviors, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { Charter } from '@niscorp/charter';\nimport type { ActionDefinition, ActionFragment, CanvasConfig, FetchFn, FunctionDefinition, FunctionHandler, LayoutNode, Reconciler, Shell } from '@niscorp/nova';\nimport type { PhraseKeys, Phrasebook } from '@niscorp/nova/i18n';\nimport type { Feature } from '../feature';\nimport type { IdentityRecord } from '../identity';\n\nexport type LayoutVariant = { action: string; layout: LayoutNode };\n\nexport type { FunctionDefinition };\n\nexport type WrittenFunctions = readonly FunctionDefinition[] | Record<string, FunctionHandler>;\n\n// A handler is a map's value, keyed by its id; a list's values are definitions.\nexport const functionsIn = (written: WrittenFunctions): readonly FunctionDefinition[] => {\n const ids = new Set<string>();\n return Object.entries<FunctionDefinition | FunctionHandler>(written).map(([key, value]) => {\n const definition = typeof value === 'function' ? { id: key, description: '', execute: value } : value;\n if (ids.has(definition.id)) throw new Error(`moss: functions(session) returned \"${definition.id}\" twice.`);\n ids.add(definition.id);\n return definition;\n });\n};\n\nexport const functionsWarning = (written: WrittenFunctions): string | undefined => {\n const undescribed: string[] = [];\n for (const value of Object.values<FunctionDefinition | FunctionHandler>(written)) {\n if (typeof value === 'function') return '[moss] functions(session) returned a map of handlers, which is deprecated: return a list of { id, description, execute }.';\n if (value.description === '') undescribed.push(value.id);\n }\n return undescribed.length === 0 ? undefined : `[moss] functions with no description: ${undescribed.join(', ')}. Give each a description.`;\n};\n\nexport type NiscApp = {\n charter: Charter;\n assignments?: Record<string, readonly string[]>;\n wearable?: readonly (readonly string[])[];\n actions: Record<string, ActionDefinition>;\n layouts?: Record<string, LayoutVariant>;\n behaviors?: ScopeBehaviors;\n scope?: (principal: string | null, identity?: IdentityRecord) => Record<string, unknown>;\n identity?: {\n as?: string;\n resolve: (principal: string, read: (fingerprint: string, scope: Record<string, unknown>) => Promise<unknown>) => Promise<IdentityRecord>;\n };\n phrases?: (session: { principal: string | null; identity: Record<string, unknown>; wire: FetchFn }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;\n phraseKeys?: PhraseKeys;\n features?: readonly Feature[];\n entries?: readonly (SeedEntry | SeedMutation)[];\n resources?: Record<string, readonly string[] | { entities: readonly string[] }>;\n shell?: ShellManifest;\n pages?: Record<string, PageManifest>;\n grammars?: readonly Sequence[];\n // A map of handlers is deprecated: return a list of `{ id, description, execute }`.\n functions?: (session: FunctionSession) => WrittenFunctions;\n // Like `functions`, it runs before the shell finishes building: defer\n // anything that touches `session.shell`.\n onSession?: (session: FunctionSession) => void;\n runs?: RunSink;\n reconcilers?: Record<string, Reconciler>;\n reactions?: readonly {\n table: string;\n op?: 'insert' | 'update' | 'delete';\n run: (\n event: { fingerprint: string; table: string; op: 'insert' | 'update' | 'delete'; count: number; scope: Record<string, unknown> },\n tools: { deliver: (principal: string, channel: string, payload?: unknown) => boolean },\n ) => void;\n }[];\n};\n\nexport type RunTurn = {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string;\n calls?: ReadonlyArray<{ name: string; args: string }>;\n name?: string;\n};\n\nexport type RunRecord = {\n at: number;\n principal: string | null;\n shellId: string;\n agentId: string;\n agentPath: readonly string[];\n label: string;\n provider: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n // False when any step's tokens were counted rather than reported by the provider.\n reported: boolean;\n steps: number;\n elapsedMs: number;\n turns?: readonly RunTurn[];\n response?: string;\n outcome: 'ok' | 'failed';\n};\n\nexport type RunSink = (record: RunRecord, session: FunctionSession) => void;\n\nexport type ArtifactKind = 'layout' | 'action' | 'fragment' | 'read';\n\nexport type ArtifactVersion = {\n kind: ArtifactKind;\n id: string;\n save: string;\n createdAt: string;\n copiedFrom: string | null;\n // `null`: this version says none is in force.\n body: unknown;\n};\n\n// What the session's principal saved, and nobody else's: each call reads and\n// writes their rows alone.\nexport type SessionArtifacts = {\n save: (artifacts: readonly { kind: ArtifactKind; id?: string; body: unknown }[]) => Promise<{ save: string; artifacts: readonly { kind: ArtifactKind; id: string }[] }>;\n list: (kind?: ArtifactKind) => Promise<readonly ArtifactVersion[]>;\n history: (kind: ArtifactKind, id: string) => Promise<readonly ArtifactVersion[]>;\n restore: (kind: ArtifactKind, id: string, save: string) => Promise<{ save: string }>;\n reset: (kind: ArtifactKind, id: string) => Promise<{ save: string }>;\n};\n\nexport type DraftArtifact = { kind: ArtifactKind; id: string; body: unknown };\n\n// What is being generated in this one shell, before it is saved. What is added\n// is in the shell when the add answers. Nothing of it is kept anywhere else, and it is\n// gone when the shell is.\nexport type SessionDraft = {\n add: (artifacts: readonly { kind: ArtifactKind; id?: string; body: unknown }[]) => Promise<{ step: number; artifacts: readonly { kind: ArtifactKind; id: string }[] }>;\n list: () => readonly DraftArtifact[];\n remove: (kind: ArtifactKind, id: string) => Promise<{ step: number }>;\n // `0`: none of it.\n show: (step: number) => Promise<void>;\n discard: () => Promise<void>;\n save: () => Promise<{ save: string; artifacts: readonly { kind: ArtifactKind; id: string }[] }>;\n};\n\nexport type FunctionSession = {\n // The members that change what a shell is made of (`registerAction`,\n // `setLayout`, `addCanvas` and their kin) throw on this one.\n shell: Shell;\n artifacts: SessionArtifacts;\n draft: SessionDraft;\n principal: string | null;\n roles: readonly string[];\n identity: Record<string, unknown>;\n actions: readonly string[];\n wire: FetchFn;\n grant: (token: string) => void;\n revoke: () => Promise<void>;\n // `asked` is a query for vex to write, `{ intent, shape }`, or one that exists, replayed by its `fingerprint`.\n answerIntent: (\n writers: { generateDsl: GenerateDsl; mapToShape: MapToShape },\n asked: { intent: string; shape: unknown; context?: Record<string, unknown> } | { fingerprint: string; context?: Record<string, unknown> },\n ) => Promise<QueryResponse>;\n recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;\n // The app's functions this session may call: those its roles' `functions` grant.\n functions: () => readonly { id: string; description?: string }[];\n};\n\nexport type CanvasSeed = string | { action: string; input?: Record<string, unknown>; with?: string[] };\n// A list of seeds is candidates: only the first action the principal holds mounts.\nexport type ShellCanvas = Omit<CanvasConfig, 'initial'> & { initial?: CanvasSeed | CanvasSeed[] };\n\nexport type ShellManifest = {\n canvases: ShellCanvas[];\n layout?: LayoutNode;\n layoutStore?: Record<string, LayoutNode>;\n fragments?: Record<string, ActionFragment>;\n seeds?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n wire: FetchFn;\n }) => Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]>;\n components?: Record<string, { meta?: { description?: string; propsSchema?: unknown } }>;\n inputs?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n identity: Record<string, unknown>;\n wire: FetchFn;\n }) => Record<string, Record<string, unknown>> | Promise<Record<string, Record<string, unknown>>>;\n};\n\nexport type PageManifest = ShellManifest & {\n path: string;\n // The id of the canvas whose seed receives the path's parameters as input.\n params?: string;\n};\n\nexport const defineApp = (app: NiscApp): NiscApp => app;\n\nexport const actionLayoutRef = (actionId: string): string => `action/${actionId}`;\n\nexport const isActionLayoutRef = (name: string): boolean => name.startsWith('action/');\n\nexport const actionOfLayoutRef = (ref: string): string | undefined => (isActionLayoutRef(ref) ? ref.slice('action/'.length) : undefined);\n\n// The id of an action or a fragment somebody generated is moss's to give, and\n// begins with this. Nothing an app ships or hands over has such an id: the\n// charter grants by id, and one an app chose could stand in for a generated one.\nexport const GENERATED_ID_PREFIX = 'generated.';\n\nexport const FRAME_LAYOUT_REF = 'frame';\n\nexport const canvasLayoutRef = (canvasId: string): string => `canvas/${canvasId}`;\n\n// Why nothing an app writes has or names this name, where it is one moss keeps a layout under.\nexport const keptLayoutNameRefusal = (name: string): string | undefined => {\n if (isActionLayoutRef(name)) return 'a name beginning with \"action/\" is where the layout of that action is kept';\n if (name === FRAME_LAYOUT_REF) return `\"${FRAME_LAYOUT_REF}\" is where the layout of the shell is kept`;\n if (name.startsWith('canvas/')) return 'a name beginning with \"canvas/\" is where the layout of that canvas is kept';\n return undefined;\n};\n\nexport const entriesOf = (app: Pick<NiscApp, 'entries'>): readonly (SeedEntry | SeedMutation)[] => app.entries ?? [];\n\nexport const wearableOf = (app: Pick<NiscApp, 'wearable' | 'assignments'>): readonly (readonly string[])[] => {\n const declared = app.wearable;\n const source = declared ?? Object.values(app.assignments ?? {});\n const seen = new Map<string, readonly string[]>();\n for (const roles of source) {\n const key = [...roles].sort().join('\\0');\n if (!seen.has(key)) seen.set(key, roles);\n }\n return [...seen.values()];\n};\n","import { normalizeRole, resolvePrincipal, verifyCharter } from '@niscorp/charter';\nimport type { Charter, ClosureAuditor, VerifyReport } from '@niscorp/charter';\nimport { ActionDefinitionSchema, auditAction, collectChannels } from '@niscorp/nova';\nimport type { ActionDefinition, ActionFragment, LayoutNode } from '@niscorp/nova';\nimport { chainCycles, isRecord, walkNodes } from '@niscorp/nova/reflect';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { scopeProfiles } from '@niscorp/vex';\nimport type { SeedEntry, SeedMutation } from '@niscorp/vex';\nimport { z } from 'zod';\nimport { isBinding } from '@niscorp/nova/i18n';\nimport { GENERATED_ID_PREFIX, entriesOf, keptLayoutNameRefusal, wearableOf } from './app';\nimport type { LayoutVariant, NiscApp } from './app';\n\nexport type ManifestCandidate = {\n charter: Charter;\n actions: Readonly<Record<string, ActionDefinition>>;\n layouts: Readonly<Record<string, LayoutVariant>>;\n fragmentIds: ReadonlySet<string>;\n // The functions each fragment the shells ship calls: two shells may ship one under one id.\n fragmentCalls: readonly { id: string; calls: readonly string[] }[];\n // The app's functions, once a shell has been built and they are known.\n functionIds?: ReadonlySet<string>;\n wearable: readonly (readonly string[])[];\n grants: readonly string[];\n entries: readonly (SeedEntry | SeedMutation)[];\n profiles: ReadonlySet<string>;\n};\n\nexport type ShippedManifest = Pick<NiscApp, 'charter' | 'actions' | 'layouts' | 'wearable' | 'assignments' | 'entries' | 'behaviors' | 'shell' | 'pages'>;\n\nexport const candidateOf = (shipped: ShippedManifest, inForce: Pick<ManifestCandidate, 'actions' | 'entries'>, grants: readonly string[]): ManifestCandidate => ({\n charter: shipped.charter,\n actions: inForce.actions,\n layouts: shipped.layouts ?? {},\n fragmentIds: new Set([shipped.shell, ...Object.values(shipped.pages ?? {})].flatMap((shell) => Object.keys(shell?.fragments ?? {}))),\n fragmentCalls: [shipped.shell, ...Object.values(shipped.pages ?? {})].flatMap((shell) =>\n Object.entries(shell?.fragments ?? {}).map(([id, fragment]) => ({ id, calls: functionsCalledBy(fragment) })),\n ),\n wearable: wearableOf(shipped),\n grants,\n entries: inForce.entries,\n profiles: scopeProfiles(shipped.behaviors ?? {}),\n});\n\n// Fragments in force beside the ones the shells ship: what is published for everybody.\nexport const withFragments = (candidate: ManifestCandidate, fragments: Readonly<Record<string, ActionFragment>>): ManifestCandidate => ({\n ...candidate,\n fragmentIds: new Set([...candidate.fragmentIds, ...Object.keys(fragments)]),\n fragmentCalls: [...candidate.fragmentCalls, ...Object.entries(fragments).map(([id, fragment]) => ({ id, calls: functionsCalledBy(fragment) }))],\n});\n\nexport type ManifestCheck = 'actions' | 'charter' | 'functions' | 'reach' | 'variants';\n\nexport type ManifestReport = {\n errors: readonly { check: ManifestCheck; detail: string }[];\n said: readonly string[];\n charter: VerifyReport;\n};\n\nconst unreadActions = (actions: ManifestCandidate['actions']): { id: string; why: string }[] =>\n Object.entries(actions).flatMap(([id, definition]) => {\n if (exceedsDepth(definition)) return [{ id, why: depthRefusal() }];\n const parsed = ActionDefinitionSchema.safeParse(definition);\n if (parsed.success) return [];\n const first = parsed.error.issues[0];\n return [{ id, why: first === undefined ? 'no reason given' : `${first.path.join('.') || '(root)'}: ${first.message}` }];\n });\n\n// A node that is `{ ref }` and nothing else names a layout. What a component keeps in its props is its own, a `ref` there too.\nconst layoutsNamedIn = (node: unknown): string[] => {\n if (Array.isArray(node)) return node.flatMap(layoutsNamedIn);\n if (!isRecord(node)) return [];\n const ref = node['ref'];\n if (typeof ref === 'string' && Object.keys(node).length === 1) return [ref];\n return Object.entries(node).flatMap(([key, inner]) => (key === 'props' ? [] : layoutsNamedIn(inner)));\n};\n\n// Two layouts moss keeps that could name each other would be drawn inside each other without end: neither names one.\nconst keptLayoutNamedIn = (layout: unknown): string | undefined =>\n (typeof layout === 'string' ? [layout] : layoutsNamedIn(layout)).find((name) => keptLayoutNameRefusal(name) !== undefined);\n\nexport const layoutNameRefusal = (layout: unknown): string | undefined => {\n const named = keptLayoutNamedIn(layout);\n return named === undefined ? undefined : `names the layout \"${named}\": ${keptLayoutNameRefusal(named)}`;\n};\n\nconst layoutNameErrors = (actions: ManifestCandidate['actions']): string[] =>\n Object.entries(actions).flatMap(([id, definition]) => {\n const refusal = layoutNameRefusal(definition.layout);\n return refusal === undefined ? [] : [`\"${id}\" ${refusal}`];\n });\n\n// The id a definition carries is held to it as the one it is listed under is: a shell registers an action under the first.\nconst generatedIdErrors = (actions: ManifestCandidate['actions']): string[] =>\n Object.entries(actions).flatMap(([listed, definition]) => {\n const taken = [listed, definition.id].find((id) => id.startsWith(GENERATED_ID_PREFIX));\n return taken === undefined ? [] : [`\"${taken}\" begins with \"${GENERATED_ID_PREFIX}\", which is where what somebody generated is kept`];\n });\n\n// Nova keeps actions and fragments in one registry: a shell built with both under one id is refused there.\nconst fragmentIdErrors = (actions: ManifestCandidate['actions'], fragmentIds: ManifestCandidate['fragmentIds']): string[] =>\n Object.entries(actions).flatMap(([listed, definition]) => {\n const taken = [listed, definition.id].find((id) => fragmentIds.has(id));\n return taken === undefined ? [] : [`\"${taken}\" is the id of an action and of a fragment: an id names one of the two`];\n });\n\nconst reachErrors = (entries: ManifestCandidate['entries'], profiles: ReadonlySet<string>): string[] => {\n const unknown = entries.flatMap((entry) => (entry.reach !== undefined && !profiles.has(entry.reach) ? [`${entry.fingerprint} declares reach \"${entry.reach}\"`] : []));\n return unknown.length === 0 ? [] : [...unknown, `known profiles: ${[...profiles].join(', ') || '(none)'}`];\n};\n\n// A name with a template in it is worked out when it is called, from the action's data.\nconst functionsCalledBy = (definition: Pick<ActionDefinition, 'endpoints'>): string[] =>\n Object.values(definition.endpoints ?? {}).flatMap((endpoint) => ('fn' in endpoint && !endpoint.fn.includes('{{') ? [endpoint.fn] : []));\n\n// Who may wear what, as the variant check reads it: each role on its own, each\n// combination the app declares, and `public`.\nconst combinationsOf = (candidate: Pick<ManifestCandidate, 'charter' | 'wearable'>): readonly (readonly string[])[] => {\n const combinations = new Map<string, readonly string[]>();\n for (const roles of [...Object.keys(candidate.charter).map((role) => [role]), ...candidate.wearable, ['public']]) combinations.set([...roles].sort().join('\\0'), roles);\n return [...combinations.values()];\n};\n\n// A function an action calls is one its holder's roles grant, or the call fails when it is made.\nconst functionGrantErrors = (candidate: Pick<ManifestCandidate, 'charter' | 'actions' | 'fragmentCalls' | 'wearable'>): string[] => {\n const errors = new Set<string>();\n for (const roles of combinationsOf(candidate)) {\n let held: ReadonlySet<string>;\n try {\n held = resolvePrincipal(candidate.charter, Object.keys(candidate.actions), roles, 'actions');\n } catch {\n continue;\n }\n if (held.size === 0) continue;\n const calls = [\n ...[...held].flatMap((id) => functionsCalledBy(candidate.actions[id] ?? {}).map((fn) => ({ by: `\"${id}\"`, fn }))),\n ...candidate.fragmentCalls.flatMap(({ id, calls: fns }) => fns.map((fn) => ({ by: `the fragment \"${id}\", which any of them may wear`, fn }))),\n ];\n const granted = resolvePrincipal(candidate.charter, calls.map((call) => call.fn), roles, 'functions');\n const who = roles.map((role) => `\"${role}\"`).join(', ');\n for (const call of calls) {\n if (!granted.has(call.fn)) errors.add(`${who} hold ${call.by}, which calls \"${call.fn}\": their functions do not grant it`);\n }\n }\n return [...errors];\n};\n\nconst unknownFunctionErrors = (candidate: Pick<ManifestCandidate, 'actions' | 'fragmentCalls' | 'functionIds'>): string[] => {\n const known = candidate.functionIds;\n if (known === undefined) return [];\n return [\n ...Object.entries(candidate.actions).flatMap(([id, definition]) => functionsCalledBy(definition).map((fn) => ({ by: `\"${id}\"`, fn }))),\n ...candidate.fragmentCalls.flatMap(({ id, calls }) => calls.map((fn) => ({ by: `the fragment \"${id}\"`, fn }))),\n ].flatMap(({ by, fn }) => (known.has(fn) ? [] : [`${by} calls \"${fn}\", which the app has no function of`]));\n};\n\nconst everyFunctionGranted = (charter: Charter): string[] =>\n Object.entries(charter).flatMap(([role, def]) =>\n normalizeRole(def, 'functions').allow.includes('*')\n ? [`role \"${role}\" allows every function ('*'): the generated actions of the people who hold it, or a role that extends it, may call any it does not deny`]\n : [],\n );\n\nexport type EndlessChain = { path: string; through: readonly string[] };\n\nexport const endlessChains = (actions: Readonly<Record<string, ActionDefinition>>): EndlessChain[] =>\n chainCycles(actions).map((cycle) => ({ path: cycle.path, through: cycle.steps.map((step) => step.action) }));\n\nexport const verifyManifest = (candidate: ManifestCandidate): ManifestReport => {\n const unread = unreadActions(candidate.actions);\n const refused = new Set(unread.map((action) => action.id));\n // The checks below walk the definitions, and one no schema has read can\n // throw out of a walk, so they run over the ones that were read.\n const read: ManifestCandidate =\n refused.size === 0 ? candidate : { ...candidate, actions: Object.fromEntries(Object.entries(candidate.actions).filter(([id]) => !refused.has(id))) };\n const charter = verifyCharter(\n read.charter,\n { actions: Object.keys(read.actions), data: read.grants, layouts: Object.keys(read.layouts) },\n read.wearable,\n auditClosure(read.actions, read.layouts),\n );\n const found = (check: ManifestCheck, details: readonly string[]): ManifestReport['errors'] => details.map((detail) => ({ check, detail }));\n return {\n errors: [\n ...found('actions', unread.map((action) => `\"${action.id}\" is not an action nova reads: ${action.why}`)),\n ...found('actions', layoutNameErrors(read.actions)),\n ...found('actions', generatedIdErrors(read.actions)),\n ...found('actions', fragmentIdErrors(read.actions, read.fragmentIds)),\n ...found('charter', charter.errors.map((error) => `${error.rule}: ${error.detail}`)),\n ...found('functions', [...unknownFunctionErrors(read), ...functionGrantErrors(read)]),\n ...found('reach', reachErrors(read.entries, read.profiles)),\n ...found('variants', verifyVariants(read)),\n ],\n said: [\n ...endlessChains(read.actions).map((chain) => `a chain of steps that never ends: ${chain.path} — nova stops it at its budget when it runs (RUNAWAY_CHAIN)`),\n ...everyFunctionGranted(read.charter),\n ],\n charter,\n };\n};\n\nexport const verifiedAtBoot = (candidate: ManifestCandidate): ManifestReport => {\n const report = verifyManifest(candidate);\n for (const line of report.said) console.error(`[moss] ${line}`);\n const refused = refusalOf(report, 'boot');\n if (refused !== undefined) throw new Error(refused);\n return report;\n};\n\n// The charter's checks over the functions alone: what it finds without them is already said.\nexport const charterOverFunctions = (\n charter: Charter,\n universes: { actions: readonly string[]; data: readonly string[]; layouts: readonly string[] },\n ids: readonly string[],\n): { errors: string[]; warnings: string[] } => {\n const before = verifyCharter(charter, universes);\n const known = new Set([...before.errors, ...before.warnings].map((issue) => issue.detail));\n const after = verifyCharter(charter, { ...universes, functions: ids });\n return {\n errors: after.errors.flatMap((issue) => (known.has(issue.detail) ? [] : [`${issue.rule}: ${issue.detail}`])),\n warnings: after.warnings.flatMap((issue) => (known.has(issue.detail) ? [] : [issue.detail])),\n };\n};\n\nexport const verifyApp = (app: ShippedManifest, grants: readonly string[]): ManifestReport =>\n verifyManifest(candidateOf(app, { actions: app.actions, entries: entriesOf(app) }, grants));\n\nconst HEADLINES = {\n boot: {\n actions: 'Actions are not ones nova reads — refusing to serve:',\n charter: 'Charter is incoherent — refusing to serve:',\n functions: 'Actions call functions the app does not have, or that their holders’ charter does not grant — refusing to serve:',\n reach: 'Entries declare a reach no table offers — refusing to serve:',\n variants: 'Layout variants are incoherent — refusing to serve:',\n },\n publish: {\n actions: 'Publish refused — actions nova does not read:',\n charter: 'Publish refused — charter incoherent over what is published:',\n functions: 'Publish refused — actions call functions the app does not have, or that their holders’ charter does not grant:',\n reach: 'Publish refused — entries declare a reach no table offers:',\n variants: 'Publish refused — layout variants incoherent:',\n },\n refresh: {\n actions: 'Refresh refused — actions nova does not read:',\n charter: 'Refresh refused — charter incoherent over the new artifacts:',\n functions: 'Refresh refused — actions call functions the app does not have, or that their holders’ charter does not grant:',\n reach: 'Refresh refused — entries declare a reach no table offers:',\n variants: 'Refresh refused — layout variants incoherent:',\n },\n} as const;\n\nexport const refusalOf = (report: ManifestReport, moment: keyof typeof HEADLINES): string | undefined => {\n const first = report.errors[0];\n if (first === undefined) return undefined;\n const findings = report.errors.filter((error) => error.check === first.check).map((error) => ` ${error.detail}`);\n return [HEADLINES[moment][first.check], ...findings].join('\\n');\n};\n\nexport const verifyVariants = (app: Pick<NiscApp, 'charter' | 'actions' | 'layouts' | 'wearable' | 'assignments'>): string[] => {\n const variants = app.layouts ?? {};\n const ids = Object.keys(variants);\n if (ids.length === 0) return [];\n const errors: string[] = [];\n for (const [id, variant] of Object.entries(variants)) {\n if (app.actions[variant.action] === undefined) {\n errors.push(`layout variant \"${id}\" reshapes unknown action \"${variant.action}\"`);\n }\n const refusal = layoutNameRefusal(variant.layout);\n if (refusal !== undefined) errors.push(`layout variant \"${id}\" ${refusal}`);\n }\n const wearers = new Map<string, readonly string[]>();\n for (const role of Object.keys(app.charter)) wearers.set(`role \"${role}\"`, [role]);\n for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(', ')}]`, roles);\n wearers.set('the anonymous principal', ['public']);\n for (const [who, roles] of wearers) {\n let granted: ReadonlySet<string>;\n try {\n granted = resolvePrincipal(app.charter, ids, roles, 'layouts');\n } catch {\n // An unknown or cyclic role is the charter verifier's finding.\n continue;\n }\n const byAction = new Map<string, string[]>();\n for (const id of granted) {\n const variant = variants[id];\n if (variant !== undefined) byAction.set(variant.action, [...(byAction.get(variant.action) ?? []), id]);\n }\n for (const [action, held] of byAction) {\n if (held.length > 1) {\n errors.push(`${who} holds ${held.length} variants of \"${action}\" (${held.sort().join(', ')}) — one variant per action per principal`);\n }\n }\n }\n return errors;\n};\n\nexport const variantLayouts = (variants: Readonly<Record<string, LayoutVariant>>, held: Iterable<string>): ReadonlyMap<string, LayoutNode> => {\n const layouts = new Map<string, LayoutNode>();\n for (const id of held) {\n const variant = variants[id];\n if (variant !== undefined) layouts.set(variant.action, variant.layout);\n }\n return layouts;\n};\n\nexport const withVariants = (\n actions: Readonly<Record<string, ActionDefinition>>,\n ids: readonly string[],\n layouts: ReadonlyMap<string, LayoutNode>,\n): [string, ActionDefinition][] =>\n ids.flatMap((id): [string, ActionDefinition][] => {\n const definition = actions[id];\n if (definition === undefined) return [];\n const layout = layouts.get(id);\n return [[id, layout === undefined ? definition : { ...definition, layout }]];\n });\n\nexport const auditClosure = (definitions: Record<string, ActionDefinition>, variants: Record<string, LayoutVariant> = {}): ClosureAuditor => {\n return (grantedIds, layoutIds = []) => {\n const granted = withVariants(definitions, grantedIds, variantLayouts(variants, layoutIds)).map(([, definition]) => definition);\n const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));\n const channels = [\n ...new Set(\n granted.flatMap((definition) => {\n const found = collectChannels(definition);\n return [...found.emits, ...found.listens];\n }),\n ),\n ];\n const issues: string[] = [];\n for (const definition of granted) {\n const audit = auditAction(definition, { catalog, channels });\n if (audit.ok) continue;\n for (const issue of audit.issues) {\n // Only a push target outside the granted set is a closure break, and\n // a template target is resolved at run time, so it is not one.\n if (issue.includes('which is not in the catalog') && !issue.includes('{{')) issues.push(`${definition.id}: ${issue}`);\n }\n }\n return issues;\n };\n};\n\nexport type KitComponents = ReadonlyMap<string, { propsSchema?: unknown }>;\n\n// A binding string or a directive object resolves at render time, so its type\n// cannot be checked here. Top level only: one nested in a static value is not unwound.\nconst isDeferred = (value: unknown): boolean =>\n (typeof value === 'string' && isBinding(value)) || (isRecord(value) && Object.keys(value).some((key) => key.startsWith('$')));\n\nexport const layoutMisfits = (layout: unknown, components: KitComponents): string[] => {\n const found = new Set<string>();\n walkNodes(layout, (record) => {\n const name = record['component'];\n if (typeof name !== 'string') return;\n const spec = components.get(name);\n if (spec === undefined) {\n found.add(`layout uses \"${name}\", which this app has no component for`);\n return;\n }\n const schema = spec.propsSchema;\n const props = record['props'];\n if (!(schema instanceof z.ZodObject) || !isRecord(props)) return;\n const shape: Readonly<Record<string, z.core.$ZodType>> = schema.shape;\n for (const [key, value] of Object.entries(props)) {\n const prop = shape[key];\n if (prop === undefined) {\n found.add(`\"${name}\" has no prop \"${key}\"`);\n continue;\n }\n if (isDeferred(value)) continue;\n const check = z.safeParse(prop, value);\n if (!check.success) found.add(`\"${name}\" prop \"${key}\" — ${check.error.issues[0]?.message ?? 'invalid'}`);\n }\n });\n return [...found];\n};\n","import { z } from 'zod';\nimport { ActionDefinitionSchema, ActionFragmentSchema, LayoutNodeSchema } from '@niscorp/nova';\nimport { ConfigSchema } from '@niscorp/prism';\nimport { SequenceSchema, depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { MutationDefinitionSchema, QuerySchema, REFRESH_MODES } from '@niscorp/vex';\nimport { GENERATED_ID_PREFIX, keptLayoutNameRefusal } from './app';\nimport type { NiscApp } from './app';\n\nconst seam = z.custom<(...args: never[]) => unknown>((value) => typeof value === 'function', 'expected a function');\n\n// Depth is checked before a recursive schema reads the value: one nested a few\n// thousand levels deep would throw RangeError out of the parser instead of\n// coming back refused. `abort` keeps the schema from being asked.\nconst depthChecked = <Schema extends z.ZodType>(schema: Schema): z.ZodPipe<z.ZodUnknown, Schema> =>\n z\n .unknown()\n .refine((value) => !exceedsDepth(value), { message: depthRefusal(), abort: true })\n .pipe(schema);\n\nconst strings = z.array(z.string()).readonly();\nconst record = z.record(z.string(), z.unknown());\nconst layout = depthChecked(LayoutNodeSchema);\n\nconst LayoutVariantSchema = z.object({ action: z.string(), layout }).strict();\n\nconst CanvasSeedSchema = z.union([z.string(), z.object({ action: z.string(), input: record.optional(), with: strings.optional() }).strict()]);\n\nconst CanvasSchema = z\n .object({\n id: z.string(),\n mode: z.enum(['stack', 'list']).optional(),\n actionLayout: z.union([z.string(), layout]).optional(),\n initial: z.union([CanvasSeedSchema, z.array(CanvasSeedSchema)]).optional(),\n reconcile: z.string().optional(),\n })\n .strict();\n\nconst ComponentContractSchema = z.looseObject({ meta: z.looseObject({ description: z.string().optional() }).optional() });\n\nconst storedLayoutName = z.string().superRefine((name, ctx) => {\n const refusal = keptLayoutNameRefusal(name);\n if (refusal !== undefined) ctx.addIssue({ code: 'custom', message: refusal });\n});\n\nconst shippedFragmentId = z.string().refine((id) => !id.startsWith(GENERATED_ID_PREFIX), { message: `an id beginning with \"${GENERATED_ID_PREFIX}\" is where what somebody generated is kept` });\n\nconst shell = {\n canvases: z.array(CanvasSchema),\n layout: layout.optional(),\n layoutStore: z.record(storedLayoutName, layout).optional(),\n fragments: z.record(shippedFragmentId, depthChecked(ActionFragmentSchema)).optional(),\n seeds: seam.optional(),\n components: z.record(z.string(), ComponentContractSchema).optional(),\n inputs: seam.optional(),\n};\nconst ShellManifestSchema = z.object(shell).strict();\nconst PageManifestSchema = z.object({ ...shell, path: z.string(), params: z.string().optional() }).strict();\n\nconst entry = { fingerprint: z.string(), intent: z.string().optional(), reach: z.string().optional() };\nconst ReadEntrySchema = z\n .object({\n ...entry,\n shape: z.unknown().optional(),\n dsl: depthChecked(QuerySchema),\n mapping: depthChecked(ConfigSchema).optional(),\n refresh: z.enum(REFRESH_MODES).optional(),\n })\n .strict();\nconst WriteEntrySchema = z.object({ ...entry, mutation: depthChecked(MutationDefinitionSchema) }).strict();\nconst EntriesSchema = z.array(z.union([ReadEntrySchema, WriteEntrySchema]));\n\nconst FeatureSchema = z.looseObject({\n name: z.string(),\n tables: z.object({ names: strings, sequences: z.array(SequenceSchema).readonly().optional() }).strict().optional(),\n start: seam,\n});\n\nconst ReactionSchema = z.object({ table: z.string(), op: z.enum(['insert', 'update', 'delete']).optional(), run: seam }).strict();\n\nconst fields = {\n charter: record,\n assignments: z.record(z.string(), strings).optional(),\n wearable: z.array(strings).readonly().optional(),\n actions: z.record(z.string(), depthChecked(ActionDefinitionSchema)),\n layouts: z.record(z.string(), LayoutVariantSchema).optional(),\n behaviors: z.record(z.string(), record).optional(),\n scope: seam.optional(),\n identity: z.object({ as: z.string().optional(), resolve: seam }).strict().optional(),\n phrases: seam.optional(),\n phraseKeys: z.object({ props: strings.optional(), suffixes: strings.optional(), text: z.boolean().optional() }).strict().optional(),\n features: z.array(FeatureSchema).readonly().optional(),\n entries: EntriesSchema.readonly().optional(),\n resources: z.record(z.string(), z.union([strings, z.looseObject({ entities: strings })])).optional(),\n shell: ShellManifestSchema.optional(),\n pages: z.record(z.string(), PageManifestSchema).optional(),\n grammars: z.array(SequenceSchema).readonly().optional(),\n functions: seam.optional(),\n onSession: seam.optional(),\n runs: seam.optional(),\n reconcilers: z.record(z.string(), seam).optional(),\n reactions: z.array(ReactionSchema).readonly().optional(),\n} satisfies Record<keyof NiscApp, z.ZodType>;\n\nconst ManifestSchema = z\n .object(fields)\n .strict()\n .superRefine((app, ctx) => {\n const shells = [{ at: ['shell'], shell: app.shell }, ...Object.entries(app.pages ?? {}).map(([name, page]) => ({ at: ['pages', name], shell: page }))];\n for (const { at, shell } of shells) {\n for (const [index, canvas] of (shell?.canvases ?? []).entries()) {\n if (canvas.reconcile === undefined || Object.hasOwn(app.reconcilers ?? {}, canvas.reconcile)) continue;\n ctx.addIssue({ code: 'custom', path: [...at, 'canvases', index, 'reconcile'], message: `\"${canvas.reconcile}\" is not a reconciler the app hands over in \\`reconcilers\\`` });\n }\n }\n });\n\ntype Issue = z.core.$ZodIssue;\ntype Place = { path: readonly PropertyKey[]; message: string };\n\n// Of a union's branches, the one reported is the one that got furthest into the\n// value before it failed; on a tie, the one with the fewest complaints.\nconst placesOf = (issue: Issue, under: readonly PropertyKey[]): Place[] => {\n const path = [...under, ...issue.path];\n if (issue.code === 'invalid_key') return [{ path, message: issue.issues[0]?.message ?? issue.message }];\n if (issue.code !== 'invalid_union') return [{ path, message: issue.message }];\n const branches = issue.errors.map((branch) => branch.flatMap((inner) => placesOf(inner, path))).filter((branch) => branch.length > 0);\n const reach = (places: readonly Place[]): number => Math.max(...places.map((place) => place.path.length));\n const closer = (best: Place[], branch: Place[]): Place[] => (reach(branch) > reach(best) || (reach(branch) === reach(best) && branch.length < best.length) ? branch : best);\n const [first, ...others] = branches;\n return first === undefined ? [{ path, message: issue.message }] : others.reduce(closer, first);\n};\n\nconst misfitsOf = (error: z.ZodError, under: readonly PropertyKey[], whole: string): string[] =>\n error.issues.flatMap((issue) => placesOf(issue, under)).map((place) => `${place.path.map(String).join('.') || whole}: ${place.message}`);\n\nexport const manifestMisfits = (app: unknown): string[] => {\n const parsed = ManifestSchema.safeParse(app);\n return parsed.success ? [] : misfitsOf(parsed.error, [], '(the manifest)');\n};\n\nexport const entryMisfits = (entries: unknown): string[] => {\n const parsed = EntriesSchema.safeParse(entries);\n return parsed.success ? [] : misfitsOf(parsed.error, ['entries'], 'entries');\n};\n\n// A class instance is not data and stays unfrozen: a kit hands a component's\n// props over as a zod schema, which fills itself in as it is used.\nconst isData = (value: object): boolean => {\n if (Array.isArray(value)) return true;\n const made: unknown = Object.getPrototypeOf(value);\n return made === Object.prototype || made === null;\n};\n\nexport const freezeDeep = (data: unknown): void => {\n const seen = new Set<object>();\n const pending: unknown[] = [data];\n while (pending.length > 0) {\n const value = pending.pop();\n if (typeof value !== 'object' || value === null || !isData(value) || seen.has(value)) continue;\n seen.add(value);\n Object.freeze(value);\n for (const inner of Object.values(value)) pending.push(inner);\n }\n};\n\nexport const receiveManifest = (app: NiscApp): void => {\n // The `satisfies` fails the build where the schema reads a field more\n // narrowly than `NiscApp` declares it, which would otherwise refuse a boot.\n const misfits = manifestMisfits(app satisfies z.input<typeof ManifestSchema>);\n if (misfits.length > 0) throw new Error(['The manifest does not parse — refusing to serve:', ...misfits.map((misfit) => ` ${misfit}`)].join('\\n'));\n freezeDeep(app);\n};\n","import type { DraftArtifact, SessionDraft } from '../manifest';\nimport type { Live } from './host-state';\nimport type { DraftSaving } from './types';\n\n// Each step is the whole draft after it. `shown`: the step the shell shows, `0` for none of it.\nexport type DraftState = { steps: readonly (readonly DraftArtifact[])[]; shown: number };\n\nexport const noDraft = (): DraftState => ({ steps: [], shown: 0 });\n\nexport const draftedIn = (draft: DraftState): readonly DraftArtifact[] => draft.steps[draft.shown - 1] ?? [];\n\nexport const SHELL_GONE = 'moss: this session’s shell is gone, and its draft with it.';\n\nexport type DraftDeps = {\n saving: DraftSaving | undefined;\n liveOf: () => Live | undefined;\n // Has the shell take the draft as it is to be. The draft is that only once the shell has.\n adopt: (live: Live, next: DraftState) => Promise<void>;\n};\n\nexport const sessionDraftOn = ({ saving, liveOf, adopt }: DraftDeps): SessionDraft => {\n const standing = (): Live => {\n const live = liveOf();\n if (live === undefined) throw new Error('moss: a function touched the draft before the session finished building.');\n if (live.ended) throw new Error(SHELL_GONE);\n return live;\n };\n const savingOrRefuse = (): DraftSaving => {\n if (saving === undefined) throw new Error('moss: this shell host was given nothing to keep a draft with.');\n return saving;\n };\n\n // In turn: each call starts from the draft as the one before it left it.\n let turn: Promise<unknown> = Promise.resolve();\n const inTurn = <Answer>(run: () => Promise<Answer>): Promise<Answer> => {\n const answer = turn.then(run, run);\n turn = answer.catch(() => undefined);\n return answer;\n };\n\n // A step taken while an earlier one is shown goes on from that one: the steps after it are dropped.\n const stepped = async (live: Live, drafted: readonly DraftArtifact[]): Promise<number> => {\n const steps = [...live.draft.steps.slice(0, live.draft.shown), drafted];\n await adopt(live, { steps, shown: steps.length });\n return steps.length;\n };\n\n return {\n add: (artifacts) =>\n inTurn(async () => {\n const live = standing();\n const answered = await savingOrRefuse().add(artifacts, draftedIn(live.draft));\n return { step: await stepped(live, answered.drafted), artifacts: answered.added };\n }),\n list: () => draftedIn(standing().draft),\n remove: (kind, id) =>\n inTurn(async () => {\n const live = standing();\n const drafted = draftedIn(live.draft);\n if (!drafted.some((one) => one.kind === kind && one.id === id)) throw new Error(`moss: no ${String(kind)} \"${id}\" is in the draft.`);\n return { step: await stepped(live, drafted.filter((one) => one.kind !== kind || one.id !== id)) };\n }),\n show: (step) =>\n inTurn(async () => {\n const live = standing();\n const last = live.draft.steps.length;\n if (!Number.isInteger(step) || step < 0 || step > last) throw new Error(`moss: the draft has no step ${String(step)}. Its steps: 0 to ${last}.`);\n await adopt(live, { steps: live.draft.steps, shown: step });\n }),\n discard: () => inTurn(async () => adopt(standing(), noDraft())),\n save: () =>\n inTurn(async () => {\n const live = standing();\n const saved = await savingOrRefuse().save(draftedIn(live.draft));\n live.draft = noDraft();\n return saved;\n }),\n };\n};\n","import type { ActionDefinition, ActionFragment, FunctionHandler, LayoutNode, Shell } from '@niscorp/nova';\nimport type { SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { Emit } from '../runtime';\nimport type { DraftState } from './draft';\nimport type { ShellComposition, ShellConnection, ShellHostConfig, ShellOpening } from './types';\n\nexport type ShellLayouts = {\n layoutStore: Readonly<Record<string, LayoutNode>>;\n fragments: Readonly<Record<string, ActionFragment>>;\n};\n\nexport const layoutsOf = (made: Pick<ShellComposition, 'layoutStore' | 'fragments'>): ShellLayouts => ({\n layoutStore: made.layoutStore ?? {},\n fragments: made.fragments ?? {},\n});\n\n// An action's layout is kept in the shell's layout store and named by ref:\n// this is the definition as it was written, with the layout the store holds now.\nexport const withLayoutInPlace = (definition: ActionDefinition, store: Shell['layoutStore']): ActionDefinition => {\n const layout = definition.layout;\n return layout === undefined || typeof layout === 'string' ? definition : { ...definition, layout: store.resolveReferences(layout) };\n};\n\n// `held` is the map nova calls into, by reference: what a shell may call\n// follows the roles an adopt answers, as its actions do.\nexport type ShellFunctions = {\n all: Readonly<Record<string, FunctionHandler>>;\n held: Record<string, FunctionHandler>;\n descriptions: Readonly<Record<string, string>>;\n};\n\nexport const holdGranted = (functions: ShellFunctions, granted: ShellComposition['grantedFunctions']): void => {\n const callable = granted(Object.keys(functions.all));\n for (const name of Object.keys(functions.held)) if (!callable.has(name)) Reflect.deleteProperty(functions.held, name);\n for (const name of callable) {\n const handler = functions.all[name];\n if (handler !== undefined) functions.held[name] = handler;\n }\n};\n\nexport type Live = {\n shell: Shell;\n sessionShell: Shell;\n actionIds: ReadonlySet<string>;\n entries: ReadonlyMap<string, SeedEntry | SeedMutation> | undefined;\n layouts: ShellLayouts;\n slottedCanvases: ReadonlySet<string>;\n functions: ShellFunctions;\n draft: DraftState;\n connections: Set<ShellConnection>;\n sentByCanvas: Map<string, string>;\n sentFrame?: string;\n deltaReady: Set<ShellConnection>;\n flushing: boolean;\n ended: boolean;\n builtAt: number;\n idleSince: number | null;\n seeded: Promise<void>;\n};\n\nexport const canvasesOf = (live: Live): string[] => Object.keys(live.shell.getState().canvases);\n\n// Every holder addresses a shell through its cell, so a reset that replaces\n// `live` reaches them all.\nexport type Cell = {\n live: Live;\n token: string | null;\n principal: string | null;\n opening?: ShellOpening;\n resetting?: Promise<void>;\n hasWaitingReset?: boolean;\n // How many of the host's changes its shell reflects.\n changes: number;\n};\n\nexport type HostState = {\n config: ShellHostConfig;\n emit: Emit | undefined;\n kept: boolean;\n delta: boolean;\n durable: Map<string, Cell>;\n building: Map<string, Promise<Cell>>;\n living: Map<Live, Cell>;\n // How many times what is in force has changed since the host was made.\n changes: number;\n // Has one shell take its draft as it is to be, for whoever changes the draft to wait on.\n adoptDraft: (live: Live, next: DraftState) => Promise<void>;\n};\n\n// Disposing stays with the caller: the shell of a session that signs out\n// nobody is disposed when its last terminal leaves.\nexport const endShell = (host: HostState, live: Live): void => {\n live.ended = true;\n host.living.delete(live);\n};\n","import { canvasTreeOf } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport { encodeDelta, frameHash } from '../protocol';\nimport type { ServerMessage } from '../protocol';\nimport { canvasesOf } from './host-state';\nimport type { Live } from './host-state';\nimport type { ShellConnection } from './types';\n\nexport const treeOf = (live: Live, canvasId: string): RenderNode[] => canvasTreeOf(live.shell, canvasId);\n\nconst canvasMessage = (live: Live, canvasId: string): string => {\n const message: ServerMessage = { type: 'render', canvas: canvasId, tree: treeOf(live, canvasId) };\n return JSON.stringify(message);\n};\n\nexport const canvasMessageOf = (live: Live, canvasId: string): string | null => {\n try {\n return canvasMessage(live, canvasId);\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvasId}\" failed to render — holding its last tree:`, error);\n return null;\n }\n};\n\n// A delta has to be decisively smaller: the transport compresses both, and a\n// delta still costs the terminal a rebuild and a checksum.\nconst DELTA_CEILING = 0.6;\n\n// The encode costs by the size of the frames, not of the change, on the thread\n// every session shares: a longer frame goes whole.\nconst DELTA_MAX_FRAME = 64 * 1024;\n\nconst shorterAsDelta = (previous: string, next: string, canvasId: string): string | null => {\n if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;\n try {\n const ops = encodeDelta(previous, next);\n const message: ServerMessage = { type: 'render-delta', canvas: canvasId, ops, hash: frameHash(next) };\n const text = JSON.stringify(message);\n return text.length <= next.length * DELTA_CEILING ? text : null;\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvasId}\" failed to encode as a delta — sending it whole:`, error);\n return null;\n }\n};\n\nconst pass = (live: Live, delta: boolean): void => {\n if (live.ended) return;\n const canvases = canvasesOf(live);\n for (const gone of [...live.sentByCanvas.keys()].filter((canvasId) => !canvases.includes(canvasId))) {\n live.sentByCanvas.delete(gone);\n const empty = JSON.stringify({ type: 'render', canvas: gone, tree: [] } satisfies ServerMessage);\n for (const connection of live.connections) connection.send(empty);\n }\n for (const canvasId of canvases) {\n const next = canvasMessageOf(live, canvasId);\n const previous = live.sentByCanvas.get(canvasId);\n if (next === null || previous === next) continue;\n live.sentByCanvas.set(canvasId, next);\n const short = delta && previous !== undefined && live.deltaReady.size > 0 ? shorterAsDelta(previous, next, canvasId) : null;\n for (const connection of live.connections) {\n connection.send(short !== null && live.deltaReady.has(connection) ? short : next);\n }\n }\n // The frame goes after the canvases, so one that references a canvas rendered\n // in this pass finds its tree already delivered.\n let frame: string | undefined;\n try {\n frame = JSON.stringify({ type: 'frame', tree: live.shell.getShellRenderTree() } satisfies ServerMessage);\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render on a flush — leaving the last one in place:', error);\n }\n if (frame !== undefined && frame !== live.sentFrame) {\n live.sentFrame = frame;\n for (const connection of live.connections) connection.send(frame);\n }\n};\n\n// The second pass, a tick later, catches what settles after the last\n// notification (an instance's status, once its loads are in).\nexport const follow = (live: Live, delta: boolean): void => {\n const flush = (): void => {\n if (live.flushing) return;\n live.flushing = true;\n queueMicrotask(() => {\n live.flushing = false;\n pass(live, delta);\n setTimeout(() => pass(live, delta), 0);\n });\n };\n live.shell.onStateChange(flush);\n live.shell.onDataChange(flush);\n};\n\nexport const attach = (live: Live, connection: ShellConnection, wantsDelta: boolean): void => {\n live.connections.add(connection);\n if (wantsDelta) live.deltaReady.add(connection);\n live.idleSince = null;\n let frameTree: RenderNode[] | undefined;\n try {\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render — serving an empty arrangement:', error);\n }\n const frameMessage = JSON.stringify({ type: 'frame', tree: frameTree ?? [] } satisfies ServerMessage);\n connection.send(frameMessage);\n if (frameTree === undefined) {\n delete live.sentFrame;\n } else {\n // Attaching renders, and can pick up a change no pass has sent yet. The\n // baseline then moves, so the others are sent it too: a pass would find\n // nothing changed. The canvases below do the same, and a delta relies on it.\n if (live.sentFrame !== frameMessage) {\n for (const other of live.connections) if (other !== connection) other.send(frameMessage);\n }\n live.sentFrame = frameMessage;\n }\n for (const canvasId of canvasesOf(live)) {\n const next = canvasMessageOf(live, canvasId);\n if (next === null) continue;\n if (live.sentByCanvas.get(canvasId) !== next) {\n for (const other of live.connections) if (other !== connection) other.send(next);\n }\n live.sentByCanvas.set(canvasId, next);\n connection.send(next);\n }\n};\n\n// What `sentByCanvas` holds, not a fresh render: the connection ends level with the\n// baseline the others share, and stays delta-capable.\nexport const resync = (live: Live, connection: ShellConnection): void => {\n if (!live.connections.has(connection)) return;\n let frameTree: RenderNode[] = [];\n try {\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render on resync — serving an empty arrangement:', error);\n }\n connection.send(JSON.stringify({ type: 'frame', tree: frameTree } satisfies ServerMessage));\n for (const canvasId of canvasesOf(live)) {\n const current = live.sentByCanvas.get(canvasId) ?? canvasMessageOf(live, canvasId);\n if (current === null || current === undefined) continue;\n connection.send(current);\n }\n};\n","import { NovaEventSchema } from '@niscorp/nova';\nimport type { FetchFn, FunctionHandler, Shell } from '@niscorp/nova';\nimport type { FunctionSession } from '../manifest';\nimport { CLOSE_SIGNED_OUT } from '../protocol';\nimport type { ServerMessage } from '../protocol';\nimport { spanClock } from '../runtime';\nimport type { Emit } from '../runtime';\nimport { sessionDraftOn } from './draft';\nimport { endShell } from './host-state';\nimport type { Cell, HostState, Live } from './host-state';\nimport { attach, resync } from './stream';\nimport type { ShellSession } from './types';\n\nexport const instrumentFunctions = (\n fns: Record<string, FunctionHandler>,\n emit: Emit,\n principal: string | null,\n): Record<string, FunctionHandler> =>\n Object.fromEntries(\n Object.entries(fns).map(([name, handler]): [string, FunctionHandler] => [\n name,\n async (data, signal) => {\n const clock = spanClock();\n const hasPrincipal = principal !== null;\n try {\n const out = await handler(data, signal);\n emit({ name: 'fn.call', startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: 'ok', attributes: { fn: name, hasPrincipal } });\n return out;\n } catch (err) {\n emit({ name: 'fn.call', startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: 'error', attributes: { fn: name, hasPrincipal } });\n throw err;\n }\n },\n ]),\n );\n\nexport type ShellRef = { shell?: Shell; sessionShell?: Shell; live?: Live };\n\nconst grant = (shellRef: ShellRef, token: string): void => {\n const message = JSON.stringify({ type: 'session', token } satisfies ServerMessage);\n for (const connection of shellRef.live?.connections ?? []) {\n if (connection.seal === undefined) connection.send(message);\n else {\n void connection.seal(token).then(\n (sealed) => connection.send(JSON.stringify({ type: 'session', sealed } satisfies ServerMessage)),\n (error: unknown) => console.error('[moss] a sign-in could not be sealed, and was not handed over:', error),\n );\n }\n }\n};\n\n// The teardown waits a microtask, so the trigger that called this finishes\n// before its own shell is disposed.\nconst revoke = (host: HostState, shellRef: ShellRef, principal: string | null): Promise<void> => {\n const { config, durable } = host;\n const forgotten = config.revokeSessions !== undefined && principal !== null ? config.revokeSessions(principal) : Promise.resolve();\n // Logged here, so a caller that does not await leaves no unhandled rejection;\n // one that does still sees the failure.\n forgotten.catch((error: unknown) => console.error(`[moss] sign-out of ${principal ?? 'anonymous'} did not revoke its sessions:`, error));\n queueMicrotask(() => {\n const live = shellRef.live;\n if (live === undefined) return;\n endShell(host, live);\n // Only while the map still holds this shell: a reset since the sign-out\n // has put another in its cell.\n if (principal !== null && durable.get(principal)?.live === live) durable.delete(principal);\n for (const connection of [...live.connections]) connection.close(CLOSE_SIGNED_OUT, 'signed out');\n live.connections.clear();\n if (principal !== null) live.shell.dispose();\n });\n return forgotten;\n};\n\nexport const functionSessionFor = (\n host: HostState,\n who: { principal: string | null; roles: readonly string[]; scope: Record<string, unknown>; actions: readonly string[] },\n wire: FetchFn,\n shellRef: ShellRef,\n): FunctionSession => {\n const { config } = host;\n const { principal } = who;\n const artifacts = config.artifacts?.(principal);\n const session: FunctionSession = {\n get artifacts() {\n if (artifacts === undefined) throw new Error('moss: this shell host was given nothing to save with.');\n return artifacts;\n },\n draft: sessionDraftOn({ saving: config.draftSaving?.(principal), liveOf: () => shellRef.live, adopt: host.adoptDraft }),\n principal,\n roles: who.roles,\n identity: who.scope,\n actions: who.actions,\n wire,\n get shell(): Shell {\n if (shellRef.sessionShell === undefined) throw new Error('moss: a function touched the shell before the session finished building.');\n return shellRef.sessionShell;\n },\n grant: (token) => grant(shellRef, token),\n revoke: () => revoke(host, shellRef, principal),\n answerIntent: (writers, asked) =>\n config.answerIntent === undefined\n ? Promise.reject(new Error('moss: this shell host was given no way to answer an intent.'))\n : config.answerIntent(principal, writers, asked),\n recordRun: (run) => {\n config.hooks.runs?.({ ...run, at: Date.now(), principal, shellId: shellRef.shell?.id ?? '' }, session);\n },\n functions: () => {\n const functions = shellRef.live?.functions;\n return Object.keys(functions?.held ?? {}).map((id) => {\n const description = functions?.descriptions[id];\n return description === undefined ? { id } : { id, description };\n });\n },\n };\n return session;\n};\n\nexport const sessionOn = (host: HostState, cell: Cell, ephemeral: boolean, reset: (cell: Cell) => void): ShellSession => ({\n get shell(): Shell {\n return cell.live.sessionShell;\n },\n attach: (connection, options) => attach(cell.live, connection, host.delta && options?.delta === true),\n resync: (connection) => resync(cell.live, connection),\n detach: (connection) => {\n const live = cell.live;\n live.connections.delete(connection);\n live.deltaReady.delete(connection);\n if (live.connections.size > 0) return;\n live.idleSince = Date.now();\n if (!ephemeral) return;\n endShell(host, live);\n live.shell.dispose();\n },\n // An event without an origin goes to every instance of the shell, so one for\n // a canvas the shell does not have is dropped. An origin a terminal names\n // comes off the wire and is held to that canvas; with none named, the\n // canvas's active instance is the origin.\n dispatch: (canvas, event) => {\n const { shell } = cell.live;\n const state = shell.getState().canvases[canvas];\n if (state === undefined) return;\n const claimed = event['origin'];\n if (claimed !== undefined && (typeof claimed !== 'string' || !state.stack.some((item) => item.id === claimed))) return;\n const active = state.active;\n const parsed = NovaEventSchema.safeParse(claimed !== undefined || active === undefined ? event : { ...event, origin: active.id });\n if (parsed.success) shell.dispatch(parsed.data);\n },\n publish: (channel, payload) => cell.live.shell.publish(channel, payload),\n back: () => cell.live.shell.back(),\n popTo: (canvas: string, instance: string) => cell.live.shell.popTo(canvas, instance),\n reset: () => reset(cell),\n});\n","import { createComponentRegistry, createLayoutStore, createShell } from '@niscorp/nova';\nimport type { CanvasConfig, FunctionHandler, PublicActionRuntime, Reconciler, Shell } from '@niscorp/nova';\nimport { evaluate } from '@niscorp/prism';\nimport { functionsIn } from '../manifest';\nimport type { CanvasSeed, ShellCanvas } from '../manifest';\nimport { spanClock } from '../runtime';\nimport { noDraft } from './draft';\nimport { functionSessionFor, instrumentFunctions } from './sessions';\nimport type { ShellRef } from './sessions';\nimport { holdGranted, layoutsOf, withLayoutInPlace } from './host-state';\nimport type { HostState, Live, ShellFunctions } from './host-state';\nimport { follow } from './stream';\nimport type { ShellOpening } from './types';\n\nconst whole = new WeakMap<Shell, Shell>();\n\nconst refuse =\n (member: string) =>\n (): never => {\n throw new Error(\n `moss: ${member} was called on a session's shell. It changes what the shell is made of without moss: ` +\n 'what it adds is not verified, is in nobody\\'s catalog, and is gone when the shell is rebuilt. ' +\n 'Code that means to do that takes the whole shell: `unverifiedShell(session)`, from `@niscorp/moss/unverified`.',\n );\n };\n\n// Where an action's layout is kept is moss's own: app code reads a definition as it was written.\nconst runtimeAsWritten = (runtime: PublicActionRuntime, store: Shell['layoutStore']): PublicActionRuntime => ({\n get instance() {\n return runtime.instance;\n },\n get definition() {\n return withLayoutInPlace(runtime.definition, store);\n },\n getData: runtime.getData,\n setData: runtime.setData,\n render: runtime.render,\n onDataChange: runtime.onDataChange,\n onStatusChange: runtime.onStatusChange,\n});\n\nconst sessionShellOf = (shell: Shell): Shell => {\n const guarded: Shell = {\n ...shell,\n layoutStore: { ...shell.layoutStore, set: refuse('layoutStore.set'), delete: refuse('layoutStore.delete') },\n getRuntime: (instanceId) => {\n const runtime = shell.getRuntime(instanceId);\n return runtime === undefined ? undefined : runtimeAsWritten(runtime, shell.layoutStore);\n },\n registerAction: refuse('registerAction'),\n removeAction: refuse('removeAction'),\n addCanvas: refuse('addCanvas'),\n removeCanvas: refuse('removeCanvas'),\n setCanvasLayout: refuse('setCanvasLayout'),\n setLayout: refuse('setLayout'),\n setPhrases: refuse('setPhrases'),\n dispose: refuse('dispose'),\n };\n whole.set(guarded, shell);\n whole.set(shell, shell);\n return guarded;\n};\n\nexport const wholeShellOf = (sessionShell: Shell): Shell => {\n const shell = whole.get(sessionShell);\n if (shell === undefined) throw new Error('moss: this is not the shell of a session moss built.');\n return shell;\n};\n\nconst today = (): string => new Date().toISOString().slice(0, 10);\n\nconst mountedCanvases = (\n declared: readonly ShellCanvas[],\n granted: ReadonlySet<string>,\n inputs: Record<string, Record<string, unknown>>,\n given: ShellOpening['inputs'],\n): CanvasConfig[] =>\n declared.map((canvas) => {\n const declared = canvas.initial;\n const candidates = declared === undefined ? [] : Array.isArray(declared) ? declared : [declared];\n const seed = candidates.find((c) => granted.has(typeof c === 'string' ? c : c.action));\n if (seed === undefined) {\n const { initial: _dropped, ...rest } = canvas;\n return rest;\n }\n const action = typeof seed === 'string' ? seed : seed.action;\n const staticInput = typeof seed === 'string' ? {} : (seed.input ?? {});\n const withFragments = typeof seed === 'string' ? undefined : seed.with;\n return {\n ...canvas,\n initial: { action, input: { ...staticInput, ...(inputs[canvas.id] ?? {}), ...(given?.[canvas.id] ?? {}) }, ...(withFragments !== undefined ? { with: withFragments } : {}) },\n };\n });\n\nconst seedCanvases = (\n live: Live,\n declaredSeeds: Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]> | undefined,\n granted: ReadonlySet<string>,\n): void => {\n if (declaredSeeds === undefined) return;\n live.seeded = Promise.resolve(declaredSeeds)\n .then((byCanvas) => {\n if (live.ended) return;\n for (const [canvasId, seeds] of Object.entries(byCanvas ?? {})) {\n for (const seed of seeds) {\n const action = typeof seed === 'string' ? seed : seed.action;\n if (!granted.has(action)) continue;\n const input = typeof seed === 'string' ? undefined : seed.input;\n const withFragments = typeof seed === 'string' ? undefined : seed.with;\n try {\n // Not a navigation: `back` must not undo the screen somebody arrives on.\n live.shell.push(canvasId, action, input, withFragments, { history: false });\n } catch (error) {\n console.error(`[moss/shells] the seed \"${action}\" on canvas \"${canvasId}\" could not be pushed, and was skipped:`, error);\n }\n }\n }\n })\n .catch((error: unknown) => {\n console.error('[moss/shells] the seeds of a shell could not be derived, and none was pushed:', error);\n });\n};\n\nexport type BuildRequest = {\n token: string | null;\n principal: string | null;\n opening?: ShellOpening;\n reset: boolean;\n wanted: () => boolean;\n};\n\nexport const buildShell = async (host: HostState, asked: BuildRequest): Promise<Live | undefined> => {\n const { config, emit, kept, delta } = host;\n const { hooks } = config;\n const { token, principal, opening, reset, wanted } = asked;\n const buildClock = emit === undefined ? undefined : spanClock();\n const made = await config.composition(principal);\n if (!wanted()) return undefined;\n const ids = Object.keys(made.actions);\n const granted = new Set(ids);\n const inputs = (await hooks.inputs?.({ principal, actions: ids, roles: made.roles, identity: made.scope, wire: config.wire(token) })) ?? {};\n if (!wanted()) return undefined;\n const canvases = mountedCanvases(made.canvases, granted, inputs, opening?.inputs);\n\n const wire = config.wrapWire === undefined ? config.wire(token) : config.wrapWire(config.wire(token));\n const userId = principal ?? 'anonymous';\n\n const registry = createComponentRegistry();\n for (const [name, contract] of Object.entries(made.components)) registry.register(name, contract);\n\n const shellRef: ShellRef = {};\n const session = functionSessionFor(host, { principal, roles: made.roles, scope: made.scope, actions: ids }, wire, shellRef);\n\n const phrases = (await hooks.phrases?.({ principal, identity: made.scope, wire: config.wire(token) })) ?? {};\n if (!wanted()) return undefined;\n\n // No await between here and `shellRef.shell = shell`: app code defers its\n // first touch of `session.shell` by a microtask, which has to find the shell\n // there and still land before the shell's mount calls answer.\n const handlers: Record<string, FunctionHandler> = {};\n const descriptions: Record<string, string> = {};\n for (const { id, description, execute } of functionsIn(hooks.functions?.(session) ?? [])) {\n handlers[id] = execute;\n if (description !== '') descriptions[id] = description;\n }\n const functions: ShellFunctions = { all: emit === undefined ? handlers : instrumentFunctions(handlers, emit, principal), held: {}, descriptions };\n holdGranted(functions, made.grantedFunctions);\n if (kept) hooks.onSession?.(session);\n\n const layoutStore = createLayoutStore();\n for (const [refId, node] of Object.entries(made.layoutStore ?? {})) layoutStore.set(refId, node);\n\n // A reconciler is app code: it is handed the shell `session.shell` is, which refuses what would change what the\n // shell is made of. A mount can reconcile while the shell is still being made, so the guarded shell is made on demand.\n let guarded: Shell | undefined;\n const guardedOf = (shell: Shell): Shell => (guarded ??= sessionShellOf(shell));\n const reconcilers: Record<string, Reconciler> = {};\n for (const [name, reconcile] of Object.entries(hooks.reconcilers ?? {})) {\n reconcilers[name] = (reconciled, canvasId, desired, options) => reconcile(guardedOf(reconciled), canvasId, desired, options);\n }\n\n // Two builds from one seed mint the same instance ids: the shell a document\n // was rendered from, and the one the socket builds a moment later for the\n // same visitor.\n let minted = 0;\n const idSeed = opening?.seed;\n const shell = createShell({\n registry,\n canvases,\n layoutStore,\n ...(idSeed === undefined ? {} : { instanceIdFn: () => `act-${idSeed}-${(minted += 1)}` }),\n ...(made.frame !== undefined ? { canvasLayout: made.frame } : {}),\n actions: { ...made.actions },\n ...(made.fragments !== undefined ? { fragments: { ...made.fragments } } : {}),\n transform: (config, source) =>\n evaluate(config, source !== null && typeof source === 'object' && !Array.isArray(source) ? { ...source, userId, today: today() } : source),\n fetch: wire,\n functions: functions.held,\n ...(hooks.reconcilers === undefined ? {} : { reconcilers }),\n ...(config.limits?.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: config.limits.endpointTimeoutMs }),\n // An empty book is withheld: nova runs its phrase pass whenever one is given.\n ...(Object.keys(phrases).length === 0 ? {} : { phrases }),\n ...(config.phraseKeys === undefined ? {} : { phraseKeys: config.phraseKeys }),\n });\n const sessionShell = guardedOf(shell);\n shellRef.shell = shell;\n shellRef.sessionShell = sessionShell;\n\n const live: Live = {\n shell,\n sessionShell,\n actionIds: granted,\n entries: made.entries,\n layouts: layoutsOf(made),\n slottedCanvases: new Set(made.slottedCanvases),\n functions,\n draft: noDraft(),\n connections: new Set(),\n sentByCanvas: new Map(),\n deltaReady: new Set(),\n flushing: false,\n ended: false,\n builtAt: Date.now(),\n idleSince: Date.now(),\n seeded: Promise.resolve(),\n };\n shellRef.live = live;\n\n seedCanvases(live, hooks.seeds?.({ principal, actions: ids, roles: made.roles, wire }), granted);\n follow(live, delta);\n\n if (emit !== undefined && buildClock !== undefined) {\n emit({ name: 'shell.build', startUnixNano: buildClock.startUnixNano, endUnixNano: buildClock.endUnixNano(), status: 'ok', attributes: { reset, hasPrincipal: principal !== null } });\n }\n\n return live;\n};\n"]}
1
+ {"version":3,"sources":["../src/manifest/app.ts","../src/manifest/verify.ts","../src/manifest/schema.ts","../src/shells/draft.ts","../src/shells/host-state.ts","../src/shells/stream.ts","../src/shells/sessions.ts","../src/shells/build.ts"],"names":["shell","scopeProfiles","exceedsDepth","depthRefusal","ActionDefinitionSchema","isRecord","layout","entry","resolvePrincipal","charter","normalizeRole","chainCycles","verifyCharter","collectChannels","auditAction","isBinding","walkNodes","record","z","LayoutNodeSchema","ActionFragmentSchema","QuerySchema","ConfigSchema","REFRESH_MODES","MutationDefinitionSchema","SequenceSchema","whole","canvasTreeOf","encodeDelta","frameHash","spanClock","CLOSE_SIGNED_OUT","NovaEventSchema","declared","withFrag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MAAA,CAAO,MAAM,KAAK,CAAA;AAElB,EAAA,IAAI,IAAA,KAAS,MAAA,IAAa,UAAA,KAAe,MAAA,EAAW;AAClD,IAAA,IAAA,CAAK,EAAE,IAAA,EAAM,aAAA,EAAe,eAAe,UAAA,CAAW,aAAA,EAAe,aAAa,UAAA,CAAW,WAAA,IAAe,MAAA,EAAQ,IAAA,EAAM,YAAY,EAAE,KAAA,EAAO,cAAc,SAAA,KAAc,IAAA,IAAQ,CAAA;AAAA,EACrL;AAEA,EAAA,OAAO,IAAA;AACT","file":"chunk-6ZWMC2OV.cjs","sourcesContent":["import type { Sequence } from '@niscorp/strata';\nimport type { GenerateDsl, MapToShape, QueryResponse, ScopeBehaviors, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { Charter } from '@niscorp/charter';\nimport type { ActionDefinition, ActionFragment, CanvasConfig, FetchFn, FunctionDefinition, FunctionHandler, LayoutNode, Reconciler, Shell } from '@niscorp/nova';\nimport type { PhraseKeys, Phrasebook } from '@niscorp/nova/i18n';\nimport type { Feature } from '../feature';\nimport type { IdentityRecord } from '../identity';\n\nexport type LayoutVariant = { action: string; layout: LayoutNode };\n\nexport type { FunctionDefinition };\n\nexport type WrittenFunctions = readonly FunctionDefinition[] | Record<string, FunctionHandler>;\n\n// A handler is a map's value, keyed by its id; a list's values are definitions.\nexport const functionsIn = (written: WrittenFunctions): readonly FunctionDefinition[] => {\n const ids = new Set<string>();\n return Object.entries<FunctionDefinition | FunctionHandler>(written).map(([key, value]) => {\n const definition = typeof value === 'function' ? { id: key, description: '', execute: value } : value;\n if (ids.has(definition.id)) throw new Error(`moss: functions(session) returned \"${definition.id}\" twice.`);\n ids.add(definition.id);\n return definition;\n });\n};\n\nexport const functionsWarning = (written: WrittenFunctions): string | undefined => {\n const undescribed: string[] = [];\n for (const value of Object.values<FunctionDefinition | FunctionHandler>(written)) {\n if (typeof value === 'function') return '[moss] functions(session) returned a map of handlers, which is deprecated: return a list of { id, description, execute }.';\n if (value.description === '') undescribed.push(value.id);\n }\n return undescribed.length === 0 ? undefined : `[moss] functions with no description: ${undescribed.join(', ')}. Give each a description.`;\n};\n\nexport type NiscApp = {\n charter: Charter;\n assignments?: Record<string, readonly string[]>;\n wearable?: readonly (readonly string[])[];\n actions: Record<string, ActionDefinition>;\n layouts?: Record<string, LayoutVariant>;\n behaviors?: ScopeBehaviors;\n scope?: (principal: string | null, identity?: IdentityRecord) => Record<string, unknown>;\n identity?: {\n as?: string;\n resolve: (principal: string, read: (fingerprint: string, scope: Record<string, unknown>) => Promise<unknown>) => Promise<IdentityRecord>;\n };\n phrases?: (session: { principal: string | null; identity: Record<string, unknown>; wire: FetchFn }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;\n phraseKeys?: PhraseKeys;\n features?: readonly Feature[];\n entries?: readonly (SeedEntry | SeedMutation)[];\n resources?: Record<string, readonly string[] | { entities: readonly string[] }>;\n shell?: ShellManifest;\n pages?: Record<string, PageManifest>;\n grammars?: readonly Sequence[];\n // A map of handlers is deprecated: return a list of `{ id, description, execute }`.\n functions?: (session: FunctionSession) => WrittenFunctions;\n // Like `functions`, it runs before the shell finishes building: defer\n // anything that touches `session.shell`.\n onSession?: (session: FunctionSession) => void;\n runs?: RunSink;\n reconcilers?: Record<string, Reconciler>;\n reactions?: readonly {\n table: string;\n op?: 'insert' | 'update' | 'delete';\n run: (\n event: { fingerprint: string; table: string; op: 'insert' | 'update' | 'delete'; count: number; scope: Record<string, unknown> },\n tools: { deliver: (principal: string, channel: string, payload?: unknown) => boolean },\n ) => void;\n }[];\n};\n\nexport type RunTurn = {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string;\n calls?: ReadonlyArray<{ name: string; args: string }>;\n name?: string;\n};\n\nexport type RunRecord = {\n at: number;\n principal: string | null;\n shellId: string;\n agentId: string;\n agentPath: readonly string[];\n label: string;\n provider: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n // False when any step's tokens were counted rather than reported by the provider.\n reported: boolean;\n steps: number;\n elapsedMs: number;\n turns?: readonly RunTurn[];\n response?: string;\n outcome: 'ok' | 'failed';\n};\n\nexport type RunSink = (record: RunRecord, session: FunctionSession) => void;\n\nexport type ArtifactKind = 'layout' | 'action' | 'fragment' | 'read';\n\nexport type ArtifactVersion = {\n kind: ArtifactKind;\n id: string;\n save: string;\n createdAt: string;\n copiedFrom: string | null;\n // `null`: this version says none is in force.\n body: unknown;\n};\n\n// What the session's principal saved, and nobody else's: each call reads and\n// writes their rows alone.\nexport type SessionArtifacts = {\n save: (artifacts: readonly { kind: ArtifactKind; id?: string; body: unknown }[]) => Promise<{ save: string; artifacts: readonly { kind: ArtifactKind; id: string }[] }>;\n list: (kind?: ArtifactKind) => Promise<readonly ArtifactVersion[]>;\n history: (kind: ArtifactKind, id: string) => Promise<readonly ArtifactVersion[]>;\n restore: (kind: ArtifactKind, id: string, save: string) => Promise<{ save: string }>;\n reset: (kind: ArtifactKind, id: string) => Promise<{ save: string }>;\n};\n\nexport type DraftArtifact = { kind: ArtifactKind; id: string; body: unknown };\n\n// What is being generated in this one shell, before it is saved. What is added\n// is in the shell when the add answers. Nothing of it is kept anywhere else, and it is\n// gone when the shell is.\nexport type SessionDraft = {\n add: (artifacts: readonly { kind: ArtifactKind; id?: string; body: unknown }[]) => Promise<{ step: number; artifacts: readonly { kind: ArtifactKind; id: string }[] }>;\n list: () => readonly DraftArtifact[];\n remove: (kind: ArtifactKind, id: string) => Promise<{ step: number }>;\n // `0`: none of it.\n show: (step: number) => Promise<void>;\n discard: () => Promise<void>;\n save: () => Promise<{ save: string; artifacts: readonly { kind: ArtifactKind; id: string }[] }>;\n};\n\nexport type FunctionSession = {\n // The members that change what a shell is made of (`registerAction`,\n // `setLayout`, `addCanvas` and their kin) throw on this one.\n shell: Shell;\n artifacts: SessionArtifacts;\n draft: SessionDraft;\n principal: string | null;\n roles: readonly string[];\n identity: Record<string, unknown>;\n actions: readonly string[];\n wire: FetchFn;\n grant: (token: string) => void;\n revoke: () => Promise<void>;\n // `asked` is a query for vex to write, `{ intent, shape }`, or one that exists, replayed by its `fingerprint`.\n answerIntent: (\n writers: { generateDsl: GenerateDsl; mapToShape: MapToShape },\n asked: { intent: string; shape: unknown; context?: Record<string, unknown> } | { fingerprint: string; context?: Record<string, unknown> },\n ) => Promise<QueryResponse>;\n recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;\n // The app's functions this session may call: those its roles' `functions` grant.\n functions: () => readonly { id: string; description?: string }[];\n};\n\nexport type CanvasSeed = string | { action: string; input?: Record<string, unknown>; with?: string[] };\n// A list of seeds is candidates: only the first action the principal holds mounts.\nexport type ShellCanvas = Omit<CanvasConfig, 'initial'> & { initial?: CanvasSeed | CanvasSeed[] };\n\nexport type ShellManifest = {\n canvases: ShellCanvas[];\n layout?: LayoutNode;\n layoutStore?: Record<string, LayoutNode>;\n fragments?: Record<string, ActionFragment>;\n seeds?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n wire: FetchFn;\n }) => Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]>;\n components?: Record<string, { meta?: { description?: string; propsSchema?: unknown } }>;\n inputs?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n identity: Record<string, unknown>;\n wire: FetchFn;\n }) => Record<string, Record<string, unknown>> | Promise<Record<string, Record<string, unknown>>>;\n};\n\nexport type PageManifest = ShellManifest & {\n path: string;\n // The id of the canvas whose seed receives the path's parameters as input.\n params?: string;\n};\n\nexport const defineApp = (app: NiscApp): NiscApp => app;\n\nexport const actionLayoutRef = (actionId: string): string => `action/${actionId}`;\n\nexport const isActionLayoutRef = (name: string): boolean => name.startsWith('action/');\n\nexport const actionOfLayoutRef = (ref: string): string | undefined => (isActionLayoutRef(ref) ? ref.slice('action/'.length) : undefined);\n\n// The id of an action or a fragment somebody generated is moss's to give, and\n// begins with this. Nothing an app ships or hands over has such an id: the\n// charter grants by id, and one an app chose could stand in for a generated one.\nexport const GENERATED_ID_PREFIX = 'generated.';\n\nexport const FRAME_LAYOUT_REF = 'frame';\n\nexport const canvasLayoutRef = (canvasId: string): string => `canvas/${canvasId}`;\n\n// Why nothing an app writes has or names this name, where it is one moss keeps a layout under.\nexport const keptLayoutNameRefusal = (name: string): string | undefined => {\n if (isActionLayoutRef(name)) return 'a name beginning with \"action/\" is where the layout of that action is kept';\n if (name === FRAME_LAYOUT_REF) return `\"${FRAME_LAYOUT_REF}\" is where the layout of the shell is kept`;\n if (name.startsWith('canvas/')) return 'a name beginning with \"canvas/\" is where the layout of that canvas is kept';\n return undefined;\n};\n\nexport const entriesOf = (app: Pick<NiscApp, 'entries'>): readonly (SeedEntry | SeedMutation)[] => app.entries ?? [];\n\nexport const wearableOf = (app: Pick<NiscApp, 'wearable' | 'assignments'>): readonly (readonly string[])[] => {\n const declared = app.wearable;\n const source = declared ?? Object.values(app.assignments ?? {});\n const seen = new Map<string, readonly string[]>();\n for (const roles of source) {\n const key = [...roles].sort().join('\\0');\n if (!seen.has(key)) seen.set(key, roles);\n }\n return [...seen.values()];\n};\n","import { normalizeRole, resolvePrincipal, verifyCharter } from '@niscorp/charter';\nimport type { Charter, ClosureAuditor, VerifyReport } from '@niscorp/charter';\nimport { ActionDefinitionSchema, auditAction, collectChannels } from '@niscorp/nova';\nimport type { ActionDefinition, ActionFragment, LayoutNode } from '@niscorp/nova';\nimport { chainCycles, isRecord, walkNodes } from '@niscorp/nova/reflect';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { scopeProfiles } from '@niscorp/vex';\nimport type { SeedEntry, SeedMutation } from '@niscorp/vex';\nimport { z } from 'zod';\nimport { isBinding } from '@niscorp/nova/i18n';\nimport { GENERATED_ID_PREFIX, entriesOf, keptLayoutNameRefusal, wearableOf } from './app';\nimport type { LayoutVariant, NiscApp } from './app';\n\nexport type ManifestCandidate = {\n charter: Charter;\n actions: Readonly<Record<string, ActionDefinition>>;\n layouts: Readonly<Record<string, LayoutVariant>>;\n fragmentIds: ReadonlySet<string>;\n // The functions each fragment the shells ship calls: two shells may ship one under one id.\n fragmentCalls: readonly { id: string; calls: readonly string[] }[];\n // The app's functions, once a shell has been built and they are known.\n functionIds?: ReadonlySet<string>;\n wearable: readonly (readonly string[])[];\n grants: readonly string[];\n entries: readonly (SeedEntry | SeedMutation)[];\n profiles: ReadonlySet<string>;\n};\n\nexport type ShippedManifest = Pick<NiscApp, 'charter' | 'actions' | 'layouts' | 'wearable' | 'assignments' | 'entries' | 'behaviors' | 'shell' | 'pages'>;\n\nexport const candidateOf = (shipped: ShippedManifest, inForce: Pick<ManifestCandidate, 'actions' | 'entries'>, grants: readonly string[]): ManifestCandidate => ({\n charter: shipped.charter,\n actions: inForce.actions,\n layouts: shipped.layouts ?? {},\n fragmentIds: new Set([shipped.shell, ...Object.values(shipped.pages ?? {})].flatMap((shell) => Object.keys(shell?.fragments ?? {}))),\n fragmentCalls: [shipped.shell, ...Object.values(shipped.pages ?? {})].flatMap((shell) =>\n Object.entries(shell?.fragments ?? {}).map(([id, fragment]) => ({ id, calls: functionsCalledBy(fragment) })),\n ),\n wearable: wearableOf(shipped),\n grants,\n entries: inForce.entries,\n profiles: scopeProfiles(shipped.behaviors ?? {}),\n});\n\n// Fragments in force beside the ones the shells ship: what is published for everybody.\nexport const withFragments = (candidate: ManifestCandidate, fragments: Readonly<Record<string, ActionFragment>>): ManifestCandidate => ({\n ...candidate,\n fragmentIds: new Set([...candidate.fragmentIds, ...Object.keys(fragments)]),\n fragmentCalls: [...candidate.fragmentCalls, ...Object.entries(fragments).map(([id, fragment]) => ({ id, calls: functionsCalledBy(fragment) }))],\n});\n\nexport type ManifestCheck = 'actions' | 'charter' | 'functions' | 'reach' | 'variants';\n\nexport type ManifestReport = {\n errors: readonly { check: ManifestCheck; detail: string }[];\n said: readonly string[];\n charter: VerifyReport;\n};\n\nconst unreadActions = (actions: ManifestCandidate['actions']): { id: string; why: string }[] =>\n Object.entries(actions).flatMap(([id, definition]) => {\n if (exceedsDepth(definition)) return [{ id, why: depthRefusal() }];\n const parsed = ActionDefinitionSchema.safeParse(definition);\n if (parsed.success) return [];\n const first = parsed.error.issues[0];\n return [{ id, why: first === undefined ? 'no reason given' : `${first.path.join('.') || '(root)'}: ${first.message}` }];\n });\n\n// A node that is `{ ref }` and nothing else names a layout. What a component keeps in its props is its own, a `ref` there too.\nconst layoutsNamedIn = (node: unknown): string[] => {\n if (Array.isArray(node)) return node.flatMap(layoutsNamedIn);\n if (!isRecord(node)) return [];\n const ref = node['ref'];\n if (typeof ref === 'string' && Object.keys(node).length === 1) return [ref];\n return Object.entries(node).flatMap(([key, inner]) => (key === 'props' ? [] : layoutsNamedIn(inner)));\n};\n\n// Two layouts moss keeps that could name each other would be drawn inside each other without end: neither names one.\nconst keptLayoutNamedIn = (layout: unknown): string | undefined =>\n (typeof layout === 'string' ? [layout] : layoutsNamedIn(layout)).find((name) => keptLayoutNameRefusal(name) !== undefined);\n\nexport const layoutNameRefusal = (layout: unknown): string | undefined => {\n const named = keptLayoutNamedIn(layout);\n return named === undefined ? undefined : `names the layout \"${named}\": ${keptLayoutNameRefusal(named)}`;\n};\n\nconst layoutNameErrors = (actions: ManifestCandidate['actions']): string[] =>\n Object.entries(actions).flatMap(([id, definition]) => {\n const refusal = layoutNameRefusal(definition.layout);\n return refusal === undefined ? [] : [`\"${id}\" ${refusal}`];\n });\n\n// The id a definition carries is held to it as the one it is listed under is: a shell registers an action under the first.\nconst generatedIdErrors = (actions: ManifestCandidate['actions']): string[] =>\n Object.entries(actions).flatMap(([listed, definition]) => {\n const taken = [listed, definition.id].find((id) => id.startsWith(GENERATED_ID_PREFIX));\n return taken === undefined ? [] : [`\"${taken}\" begins with \"${GENERATED_ID_PREFIX}\", which is where what somebody generated is kept`];\n });\n\n// Nova keeps actions and fragments in one registry: a shell built with both under one id is refused there.\nconst fragmentIdErrors = (actions: ManifestCandidate['actions'], fragmentIds: ManifestCandidate['fragmentIds']): string[] =>\n Object.entries(actions).flatMap(([listed, definition]) => {\n const taken = [listed, definition.id].find((id) => fragmentIds.has(id));\n return taken === undefined ? [] : [`\"${taken}\" is the id of an action and of a fragment: an id names one of the two`];\n });\n\nconst reachErrors = (entries: ManifestCandidate['entries'], profiles: ReadonlySet<string>): string[] => {\n const unknown = entries.flatMap((entry) => (entry.reach !== undefined && !profiles.has(entry.reach) ? [`${entry.fingerprint} declares reach \"${entry.reach}\"`] : []));\n return unknown.length === 0 ? [] : [...unknown, `known profiles: ${[...profiles].join(', ') || '(none)'}`];\n};\n\n// A name with a template in it is worked out when it is called, from the action's data.\nconst functionsCalledBy = (definition: Pick<ActionDefinition, 'endpoints'>): string[] =>\n Object.values(definition.endpoints ?? {}).flatMap((endpoint) => ('fn' in endpoint && !endpoint.fn.includes('{{') ? [endpoint.fn] : []));\n\n// Who may wear what, as the variant check reads it: each role on its own, each\n// combination the app declares, and `public`.\nconst combinationsOf = (candidate: Pick<ManifestCandidate, 'charter' | 'wearable'>): readonly (readonly string[])[] => {\n const combinations = new Map<string, readonly string[]>();\n for (const roles of [...Object.keys(candidate.charter).map((role) => [role]), ...candidate.wearable, ['public']]) combinations.set([...roles].sort().join('\\0'), roles);\n return [...combinations.values()];\n};\n\n// A function an action calls is one its holder's roles grant, or the call fails when it is made.\nconst functionGrantErrors = (candidate: Pick<ManifestCandidate, 'charter' | 'actions' | 'fragmentCalls' | 'wearable'>): string[] => {\n const errors = new Set<string>();\n for (const roles of combinationsOf(candidate)) {\n let held: ReadonlySet<string>;\n try {\n held = resolvePrincipal(candidate.charter, Object.keys(candidate.actions), roles, 'actions');\n } catch {\n continue;\n }\n if (held.size === 0) continue;\n const calls = [\n ...[...held].flatMap((id) => functionsCalledBy(candidate.actions[id] ?? {}).map((fn) => ({ by: `\"${id}\"`, fn }))),\n ...candidate.fragmentCalls.flatMap(({ id, calls: fns }) => fns.map((fn) => ({ by: `the fragment \"${id}\", which any of them may wear`, fn }))),\n ];\n const granted = resolvePrincipal(candidate.charter, calls.map((call) => call.fn), roles, 'functions');\n const who = roles.map((role) => `\"${role}\"`).join(', ');\n for (const call of calls) {\n if (!granted.has(call.fn)) errors.add(`${who} hold ${call.by}, which calls \"${call.fn}\": their functions do not grant it`);\n }\n }\n return [...errors];\n};\n\nconst unknownFunctionErrors = (candidate: Pick<ManifestCandidate, 'actions' | 'fragmentCalls' | 'functionIds'>): string[] => {\n const known = candidate.functionIds;\n if (known === undefined) return [];\n return [\n ...Object.entries(candidate.actions).flatMap(([id, definition]) => functionsCalledBy(definition).map((fn) => ({ by: `\"${id}\"`, fn }))),\n ...candidate.fragmentCalls.flatMap(({ id, calls }) => calls.map((fn) => ({ by: `the fragment \"${id}\"`, fn }))),\n ].flatMap(({ by, fn }) => (known.has(fn) ? [] : [`${by} calls \"${fn}\", which the app has no function of`]));\n};\n\nconst everyFunctionGranted = (charter: Charter): string[] =>\n Object.entries(charter).flatMap(([role, def]) =>\n normalizeRole(def, 'functions').allow.includes('*')\n ? [`role \"${role}\" allows every function ('*'): the generated actions of the people who hold it, or a role that extends it, may call any it does not deny`]\n : [],\n );\n\nexport type EndlessChain = { path: string; through: readonly string[] };\n\nexport const endlessChains = (actions: Readonly<Record<string, ActionDefinition>>): EndlessChain[] =>\n chainCycles(actions).map((cycle) => ({ path: cycle.path, through: cycle.steps.map((step) => step.action) }));\n\nexport const verifyManifest = (candidate: ManifestCandidate): ManifestReport => {\n const unread = unreadActions(candidate.actions);\n const refused = new Set(unread.map((action) => action.id));\n // The checks below walk the definitions, and one no schema has read can\n // throw out of a walk, so they run over the ones that were read.\n const read: ManifestCandidate =\n refused.size === 0 ? candidate : { ...candidate, actions: Object.fromEntries(Object.entries(candidate.actions).filter(([id]) => !refused.has(id))) };\n const charter = verifyCharter(\n read.charter,\n { actions: Object.keys(read.actions), data: read.grants, layouts: Object.keys(read.layouts) },\n read.wearable,\n auditClosure(read.actions, read.layouts),\n );\n const found = (check: ManifestCheck, details: readonly string[]): ManifestReport['errors'] => details.map((detail) => ({ check, detail }));\n return {\n errors: [\n ...found('actions', unread.map((action) => `\"${action.id}\" is not an action nova reads: ${action.why}`)),\n ...found('actions', layoutNameErrors(read.actions)),\n ...found('actions', generatedIdErrors(read.actions)),\n ...found('actions', fragmentIdErrors(read.actions, read.fragmentIds)),\n ...found('charter', charter.errors.map((error) => `${error.rule}: ${error.detail}`)),\n ...found('functions', [...unknownFunctionErrors(read), ...functionGrantErrors(read)]),\n ...found('reach', reachErrors(read.entries, read.profiles)),\n ...found('variants', verifyVariants(read)),\n ],\n said: [\n ...endlessChains(read.actions).map((chain) => `a chain of steps that never ends: ${chain.path} — nova stops it at its budget when it runs (RUNAWAY_CHAIN)`),\n ...everyFunctionGranted(read.charter),\n ],\n charter,\n };\n};\n\nexport const verifiedAtBoot = (candidate: ManifestCandidate): ManifestReport => {\n const report = verifyManifest(candidate);\n for (const line of report.said) console.error(`[moss] ${line}`);\n const refused = refusalOf(report, 'boot');\n if (refused !== undefined) throw new Error(refused);\n return report;\n};\n\n// The charter's checks over the functions alone: what it finds without them is already said.\nexport const charterOverFunctions = (\n charter: Charter,\n universes: { actions: readonly string[]; data: readonly string[]; layouts: readonly string[] },\n ids: readonly string[],\n): { errors: string[]; warnings: string[] } => {\n const before = verifyCharter(charter, universes);\n const known = new Set([...before.errors, ...before.warnings].map((issue) => issue.detail));\n const after = verifyCharter(charter, { ...universes, functions: ids });\n return {\n errors: after.errors.flatMap((issue) => (known.has(issue.detail) ? [] : [`${issue.rule}: ${issue.detail}`])),\n warnings: after.warnings.flatMap((issue) => (known.has(issue.detail) ? [] : [issue.detail])),\n };\n};\n\nexport const verifyApp = (app: ShippedManifest, grants: readonly string[]): ManifestReport =>\n verifyManifest(candidateOf(app, { actions: app.actions, entries: entriesOf(app) }, grants));\n\nconst HEADLINES = {\n boot: {\n actions: 'Actions are not ones nova reads — refusing to serve:',\n charter: 'Charter is incoherent — refusing to serve:',\n functions: 'Actions call functions the app does not have, or that their holders’ charter does not grant — refusing to serve:',\n reach: 'Entries declare a reach no table offers — refusing to serve:',\n variants: 'Layout variants are incoherent — refusing to serve:',\n },\n publish: {\n actions: 'Publish refused — actions nova does not read:',\n charter: 'Publish refused — charter incoherent over what is published:',\n functions: 'Publish refused — actions call functions the app does not have, or that their holders’ charter does not grant:',\n reach: 'Publish refused — entries declare a reach no table offers:',\n variants: 'Publish refused — layout variants incoherent:',\n },\n refresh: {\n actions: 'Refresh refused — actions nova does not read:',\n charter: 'Refresh refused — charter incoherent over the new artifacts:',\n functions: 'Refresh refused — actions call functions the app does not have, or that their holders’ charter does not grant:',\n reach: 'Refresh refused — entries declare a reach no table offers:',\n variants: 'Refresh refused — layout variants incoherent:',\n },\n} as const;\n\nexport const refusalOf = (report: ManifestReport, moment: keyof typeof HEADLINES): string | undefined => {\n const first = report.errors[0];\n if (first === undefined) return undefined;\n const findings = report.errors.filter((error) => error.check === first.check).map((error) => ` ${error.detail}`);\n return [HEADLINES[moment][first.check], ...findings].join('\\n');\n};\n\nexport const verifyVariants = (app: Pick<NiscApp, 'charter' | 'actions' | 'layouts' | 'wearable' | 'assignments'>): string[] => {\n const variants = app.layouts ?? {};\n const ids = Object.keys(variants);\n if (ids.length === 0) return [];\n const errors: string[] = [];\n for (const [id, variant] of Object.entries(variants)) {\n if (app.actions[variant.action] === undefined) {\n errors.push(`layout variant \"${id}\" reshapes unknown action \"${variant.action}\"`);\n }\n const refusal = layoutNameRefusal(variant.layout);\n if (refusal !== undefined) errors.push(`layout variant \"${id}\" ${refusal}`);\n }\n const wearers = new Map<string, readonly string[]>();\n for (const role of Object.keys(app.charter)) wearers.set(`role \"${role}\"`, [role]);\n for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(', ')}]`, roles);\n wearers.set('the anonymous principal', ['public']);\n for (const [who, roles] of wearers) {\n let granted: ReadonlySet<string>;\n try {\n granted = resolvePrincipal(app.charter, ids, roles, 'layouts');\n } catch {\n // An unknown or cyclic role is the charter verifier's finding.\n continue;\n }\n const byAction = new Map<string, string[]>();\n for (const id of granted) {\n const variant = variants[id];\n if (variant !== undefined) byAction.set(variant.action, [...(byAction.get(variant.action) ?? []), id]);\n }\n for (const [action, held] of byAction) {\n if (held.length > 1) {\n errors.push(`${who} holds ${held.length} variants of \"${action}\" (${held.sort().join(', ')}) — one variant per action per principal`);\n }\n }\n }\n return errors;\n};\n\nexport const variantLayouts = (variants: Readonly<Record<string, LayoutVariant>>, held: Iterable<string>): ReadonlyMap<string, LayoutNode> => {\n const layouts = new Map<string, LayoutNode>();\n for (const id of held) {\n const variant = variants[id];\n if (variant !== undefined) layouts.set(variant.action, variant.layout);\n }\n return layouts;\n};\n\nexport const withVariants = (\n actions: Readonly<Record<string, ActionDefinition>>,\n ids: readonly string[],\n layouts: ReadonlyMap<string, LayoutNode>,\n): [string, ActionDefinition][] =>\n ids.flatMap((id): [string, ActionDefinition][] => {\n const definition = actions[id];\n if (definition === undefined) return [];\n const layout = layouts.get(id);\n return [[id, layout === undefined ? definition : { ...definition, layout }]];\n });\n\nexport const auditClosure = (definitions: Record<string, ActionDefinition>, variants: Record<string, LayoutVariant> = {}): ClosureAuditor => {\n return (grantedIds, layoutIds = []) => {\n const granted = withVariants(definitions, grantedIds, variantLayouts(variants, layoutIds)).map(([, definition]) => definition);\n const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));\n const channels = [\n ...new Set(\n granted.flatMap((definition) => {\n const found = collectChannels(definition);\n return [...found.emits, ...found.listens];\n }),\n ),\n ];\n const issues: string[] = [];\n for (const definition of granted) {\n const audit = auditAction(definition, { catalog, channels });\n if (audit.ok) continue;\n for (const issue of audit.issues) {\n // Only a push target outside the granted set is a closure break, and\n // a template target is resolved at run time, so it is not one.\n if (issue.includes('which is not in the catalog') && !issue.includes('{{')) issues.push(`${definition.id}: ${issue}`);\n }\n }\n return issues;\n };\n};\n\nexport type KitComponents = ReadonlyMap<string, { propsSchema?: unknown }>;\n\n// A binding string or a directive object resolves at render time, so its type\n// cannot be checked here. Top level only: one nested in a static value is not unwound.\nconst isDeferred = (value: unknown): boolean =>\n (typeof value === 'string' && isBinding(value)) || (isRecord(value) && Object.keys(value).some((key) => key.startsWith('$')));\n\nexport const layoutMisfits = (layout: unknown, components: KitComponents): string[] => {\n const found = new Set<string>();\n walkNodes(layout, (record) => {\n const name = record['component'];\n if (typeof name !== 'string') return;\n const spec = components.get(name);\n if (spec === undefined) {\n found.add(`layout uses \"${name}\", which this app has no component for`);\n return;\n }\n const schema = spec.propsSchema;\n const props = record['props'];\n if (!(schema instanceof z.ZodObject) || !isRecord(props)) return;\n const shape: Readonly<Record<string, z.core.$ZodType>> = schema.shape;\n for (const [key, value] of Object.entries(props)) {\n const prop = shape[key];\n if (prop === undefined) {\n found.add(`\"${name}\" has no prop \"${key}\"`);\n continue;\n }\n if (isDeferred(value)) continue;\n const check = z.safeParse(prop, value);\n if (!check.success) found.add(`\"${name}\" prop \"${key}\" — ${check.error.issues[0]?.message ?? 'invalid'}`);\n }\n });\n return [...found];\n};\n","import { z } from 'zod';\nimport { ActionDefinitionSchema, ActionFragmentSchema, LayoutNodeSchema } from '@niscorp/nova';\nimport { ConfigSchema } from '@niscorp/prism';\nimport { SequenceSchema, depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { MutationDefinitionSchema, QuerySchema, REFRESH_MODES } from '@niscorp/vex';\nimport { GENERATED_ID_PREFIX, keptLayoutNameRefusal } from './app';\nimport type { NiscApp } from './app';\n\nconst seam = z.custom<(...args: never[]) => unknown>((value) => typeof value === 'function', 'expected a function');\n\n// Depth is checked before a recursive schema reads the value: one nested a few\n// thousand levels deep would throw RangeError out of the parser instead of\n// coming back refused. `abort` keeps the schema from being asked.\nconst depthChecked = <Schema extends z.ZodType>(schema: Schema): z.ZodPipe<z.ZodUnknown, Schema> =>\n z\n .unknown()\n .refine((value) => !exceedsDepth(value), { message: depthRefusal(), abort: true })\n .pipe(schema);\n\nconst strings = z.array(z.string()).readonly();\nconst record = z.record(z.string(), z.unknown());\nconst layout = depthChecked(LayoutNodeSchema);\n\nconst LayoutVariantSchema = z.object({ action: z.string(), layout }).strict();\n\nconst CanvasSeedSchema = z.union([z.string(), z.object({ action: z.string(), input: record.optional(), with: strings.optional() }).strict()]);\n\nconst CanvasSchema = z\n .object({\n id: z.string(),\n mode: z.enum(['stack', 'list']).optional(),\n actionLayout: z.union([z.string(), layout]).optional(),\n initial: z.union([CanvasSeedSchema, z.array(CanvasSeedSchema)]).optional(),\n reconcile: z.string().optional(),\n })\n .strict();\n\nconst ComponentContractSchema = z.looseObject({ meta: z.looseObject({ description: z.string().optional() }).optional() });\n\nconst storedLayoutName = z.string().superRefine((name, ctx) => {\n const refusal = keptLayoutNameRefusal(name);\n if (refusal !== undefined) ctx.addIssue({ code: 'custom', message: refusal });\n});\n\nconst shippedFragmentId = z.string().refine((id) => !id.startsWith(GENERATED_ID_PREFIX), { message: `an id beginning with \"${GENERATED_ID_PREFIX}\" is where what somebody generated is kept` });\n\nconst shell = {\n canvases: z.array(CanvasSchema),\n layout: layout.optional(),\n layoutStore: z.record(storedLayoutName, layout).optional(),\n fragments: z.record(shippedFragmentId, depthChecked(ActionFragmentSchema)).optional(),\n seeds: seam.optional(),\n components: z.record(z.string(), ComponentContractSchema).optional(),\n inputs: seam.optional(),\n};\nconst ShellManifestSchema = z.object(shell).strict();\nconst PageManifestSchema = z.object({ ...shell, path: z.string(), params: z.string().optional() }).strict();\n\nconst entry = { fingerprint: z.string(), intent: z.string().optional(), reach: z.string().optional() };\nconst ReadEntrySchema = z\n .object({\n ...entry,\n shape: z.unknown().optional(),\n dsl: depthChecked(QuerySchema),\n mapping: depthChecked(ConfigSchema).optional(),\n refresh: z.enum(REFRESH_MODES).optional(),\n })\n .strict();\nconst WriteEntrySchema = z.object({ ...entry, mutation: depthChecked(MutationDefinitionSchema) }).strict();\nconst EntriesSchema = z.array(z.union([ReadEntrySchema, WriteEntrySchema]));\n\nconst FeatureSchema = z.looseObject({\n name: z.string(),\n tables: z.object({ names: strings, sequences: z.array(SequenceSchema).readonly().optional() }).strict().optional(),\n start: seam,\n});\n\nconst ReactionSchema = z.object({ table: z.string(), op: z.enum(['insert', 'update', 'delete']).optional(), run: seam }).strict();\n\nconst fields = {\n charter: record,\n assignments: z.record(z.string(), strings).optional(),\n wearable: z.array(strings).readonly().optional(),\n actions: z.record(z.string(), depthChecked(ActionDefinitionSchema)),\n layouts: z.record(z.string(), LayoutVariantSchema).optional(),\n behaviors: z.record(z.string(), record).optional(),\n scope: seam.optional(),\n identity: z.object({ as: z.string().optional(), resolve: seam }).strict().optional(),\n phrases: seam.optional(),\n phraseKeys: z.object({ props: strings.optional(), suffixes: strings.optional(), text: z.boolean().optional() }).strict().optional(),\n features: z.array(FeatureSchema).readonly().optional(),\n entries: EntriesSchema.readonly().optional(),\n resources: z.record(z.string(), z.union([strings, z.looseObject({ entities: strings })])).optional(),\n shell: ShellManifestSchema.optional(),\n pages: z.record(z.string(), PageManifestSchema).optional(),\n grammars: z.array(SequenceSchema).readonly().optional(),\n functions: seam.optional(),\n onSession: seam.optional(),\n runs: seam.optional(),\n reconcilers: z.record(z.string(), seam).optional(),\n reactions: z.array(ReactionSchema).readonly().optional(),\n} satisfies Record<keyof NiscApp, z.ZodType>;\n\nconst ManifestSchema = z\n .object(fields)\n .strict()\n .superRefine((app, ctx) => {\n const shells = [{ at: ['shell'], shell: app.shell }, ...Object.entries(app.pages ?? {}).map(([name, page]) => ({ at: ['pages', name], shell: page }))];\n for (const { at, shell } of shells) {\n for (const [index, canvas] of (shell?.canvases ?? []).entries()) {\n if (canvas.reconcile === undefined || Object.hasOwn(app.reconcilers ?? {}, canvas.reconcile)) continue;\n ctx.addIssue({ code: 'custom', path: [...at, 'canvases', index, 'reconcile'], message: `\"${canvas.reconcile}\" is not a reconciler the app hands over in \\`reconcilers\\`` });\n }\n }\n });\n\ntype Issue = z.core.$ZodIssue;\ntype Place = { path: readonly PropertyKey[]; message: string };\n\n// Of a union's branches, the one reported is the one that got furthest into the\n// value before it failed; on a tie, the one with the fewest complaints.\nconst placesOf = (issue: Issue, under: readonly PropertyKey[]): Place[] => {\n const path = [...under, ...issue.path];\n if (issue.code === 'invalid_key') return [{ path, message: issue.issues[0]?.message ?? issue.message }];\n if (issue.code !== 'invalid_union') return [{ path, message: issue.message }];\n const branches = issue.errors.map((branch) => branch.flatMap((inner) => placesOf(inner, path))).filter((branch) => branch.length > 0);\n const reach = (places: readonly Place[]): number => Math.max(...places.map((place) => place.path.length));\n const closer = (best: Place[], branch: Place[]): Place[] => (reach(branch) > reach(best) || (reach(branch) === reach(best) && branch.length < best.length) ? branch : best);\n const [first, ...others] = branches;\n return first === undefined ? [{ path, message: issue.message }] : others.reduce(closer, first);\n};\n\nconst misfitsOf = (error: z.ZodError, under: readonly PropertyKey[], whole: string): string[] =>\n error.issues.flatMap((issue) => placesOf(issue, under)).map((place) => `${place.path.map(String).join('.') || whole}: ${place.message}`);\n\nexport const manifestMisfits = (app: unknown): string[] => {\n const parsed = ManifestSchema.safeParse(app);\n return parsed.success ? [] : misfitsOf(parsed.error, [], '(the manifest)');\n};\n\nexport const entryMisfits = (entries: unknown): string[] => {\n const parsed = EntriesSchema.safeParse(entries);\n return parsed.success ? [] : misfitsOf(parsed.error, ['entries'], 'entries');\n};\n\n// A class instance is not data and stays unfrozen: a kit hands a component's\n// props over as a zod schema, which fills itself in as it is used.\nconst isData = (value: object): boolean => {\n if (Array.isArray(value)) return true;\n const made: unknown = Object.getPrototypeOf(value);\n return made === Object.prototype || made === null;\n};\n\nexport const freezeDeep = (data: unknown): void => {\n const seen = new Set<object>();\n const pending: unknown[] = [data];\n while (pending.length > 0) {\n const value = pending.pop();\n if (typeof value !== 'object' || value === null || !isData(value) || seen.has(value)) continue;\n seen.add(value);\n Object.freeze(value);\n for (const inner of Object.values(value)) pending.push(inner);\n }\n};\n\nexport const receiveManifest = (app: NiscApp): void => {\n // The `satisfies` fails the build where the schema reads a field more\n // narrowly than `NiscApp` declares it, which would otherwise refuse a boot.\n const misfits = manifestMisfits(app satisfies z.input<typeof ManifestSchema>);\n if (misfits.length > 0) throw new Error(['The manifest does not parse — refusing to serve:', ...misfits.map((misfit) => ` ${misfit}`)].join('\\n'));\n freezeDeep(app);\n};\n","import type { DraftArtifact, SessionDraft } from '../manifest';\nimport type { Live } from './host-state';\nimport type { DraftSaving } from './types';\n\n// Each step is the whole draft after it. `shown`: the step the shell shows, `0` for none of it.\nexport type DraftState = { steps: readonly (readonly DraftArtifact[])[]; shown: number };\n\nexport const noDraft = (): DraftState => ({ steps: [], shown: 0 });\n\nexport const draftedIn = (draft: DraftState): readonly DraftArtifact[] => draft.steps[draft.shown - 1] ?? [];\n\nexport const SHELL_GONE = 'moss: this session’s shell is gone, and its draft with it.';\n\nexport type DraftDeps = {\n saving: DraftSaving | undefined;\n liveOf: () => Live | undefined;\n // Has the shell take the draft as it is to be. The draft is that only once the shell has.\n adopt: (live: Live, next: DraftState) => Promise<void>;\n};\n\nexport const sessionDraftOn = ({ saving, liveOf, adopt }: DraftDeps): SessionDraft => {\n const standing = (): Live => {\n const live = liveOf();\n if (live === undefined) throw new Error('moss: a function touched the draft before the session finished building.');\n if (live.ended) throw new Error(SHELL_GONE);\n return live;\n };\n const savingOrRefuse = (): DraftSaving => {\n if (saving === undefined) throw new Error('moss: this shell host was given nothing to keep a draft with.');\n return saving;\n };\n\n // In turn: each call starts from the draft as the one before it left it.\n let turn: Promise<unknown> = Promise.resolve();\n const inTurn = <Answer>(run: () => Promise<Answer>): Promise<Answer> => {\n const answer = turn.then(run, run);\n turn = answer.catch(() => undefined);\n return answer;\n };\n\n // A step taken while an earlier one is shown goes on from that one: the steps after it are dropped.\n const stepped = async (live: Live, drafted: readonly DraftArtifact[]): Promise<number> => {\n const steps = [...live.draft.steps.slice(0, live.draft.shown), drafted];\n await adopt(live, { steps, shown: steps.length });\n return steps.length;\n };\n\n return {\n add: (artifacts) =>\n inTurn(async () => {\n const live = standing();\n const answered = await savingOrRefuse().add(artifacts, draftedIn(live.draft));\n return { step: await stepped(live, answered.drafted), artifacts: answered.added };\n }),\n list: () => draftedIn(standing().draft),\n remove: (kind, id) =>\n inTurn(async () => {\n const live = standing();\n const drafted = draftedIn(live.draft);\n if (!drafted.some((one) => one.kind === kind && one.id === id)) throw new Error(`moss: no ${String(kind)} \"${id}\" is in the draft.`);\n return { step: await stepped(live, drafted.filter((one) => one.kind !== kind || one.id !== id)) };\n }),\n show: (step) =>\n inTurn(async () => {\n const live = standing();\n const last = live.draft.steps.length;\n if (!Number.isInteger(step) || step < 0 || step > last) throw new Error(`moss: the draft has no step ${String(step)}. Its steps: 0 to ${last}.`);\n await adopt(live, { steps: live.draft.steps, shown: step });\n }),\n discard: () => inTurn(async () => adopt(standing(), noDraft())),\n save: () =>\n inTurn(async () => {\n const live = standing();\n const saved = await savingOrRefuse().save(draftedIn(live.draft));\n live.draft = noDraft();\n return saved;\n }),\n };\n};\n","import type { ActionDefinition, ActionFragment, FunctionHandler, LayoutNode, Shell } from '@niscorp/nova';\nimport type { SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { Emit } from '../runtime';\nimport type { DraftState } from './draft';\nimport type { ShellComposition, ShellConnection, ShellHostConfig, ShellOpening } from './types';\n\nexport type ShellLayouts = {\n layoutStore: Readonly<Record<string, LayoutNode>>;\n fragments: Readonly<Record<string, ActionFragment>>;\n};\n\nexport const layoutsOf = (made: Pick<ShellComposition, 'layoutStore' | 'fragments'>): ShellLayouts => ({\n layoutStore: made.layoutStore ?? {},\n fragments: made.fragments ?? {},\n});\n\n// An action's layout is kept in the shell's layout store and named by ref:\n// this is the definition as it was written, with the layout the store holds now.\nexport const withLayoutInPlace = (definition: ActionDefinition, store: Shell['layoutStore']): ActionDefinition => {\n const layout = definition.layout;\n return layout === undefined || typeof layout === 'string' ? definition : { ...definition, layout: store.resolveReferences(layout) };\n};\n\n// `held` is the map nova calls into, by reference: what a shell may call\n// follows the roles an adopt answers, as its actions do.\nexport type ShellFunctions = {\n all: Readonly<Record<string, FunctionHandler>>;\n held: Record<string, FunctionHandler>;\n descriptions: Readonly<Record<string, string>>;\n};\n\nexport const holdGranted = (functions: ShellFunctions, granted: ShellComposition['grantedFunctions']): void => {\n const callable = granted(Object.keys(functions.all));\n for (const name of Object.keys(functions.held)) if (!callable.has(name)) Reflect.deleteProperty(functions.held, name);\n for (const name of callable) {\n const handler = functions.all[name];\n if (handler !== undefined) functions.held[name] = handler;\n }\n};\n\nexport type Live = {\n shell: Shell;\n sessionShell: Shell;\n actionIds: ReadonlySet<string>;\n entries: ReadonlyMap<string, SeedEntry | SeedMutation> | undefined;\n layouts: ShellLayouts;\n slottedCanvases: ReadonlySet<string>;\n functions: ShellFunctions;\n draft: DraftState;\n connections: Set<ShellConnection>;\n sentByCanvas: Map<string, string>;\n sentFrame?: string;\n deltaReady: Set<ShellConnection>;\n flushing: boolean;\n ended: boolean;\n builtAt: number;\n idleSince: number | null;\n seeded: Promise<void>;\n};\n\nexport const canvasesOf = (live: Live): string[] => Object.keys(live.shell.getState().canvases);\n\n// Every holder addresses a shell through its cell, so a reset that replaces\n// `live` reaches them all.\nexport type Cell = {\n live: Live;\n token: string | null;\n principal: string | null;\n opening?: ShellOpening;\n resetting?: Promise<void>;\n hasWaitingReset?: boolean;\n // How many of the host's changes its shell reflects.\n changes: number;\n};\n\nexport type HostState = {\n config: ShellHostConfig;\n emit: Emit | undefined;\n kept: boolean;\n delta: boolean;\n durable: Map<string, Cell>;\n building: Map<string, Promise<Cell>>;\n living: Map<Live, Cell>;\n // How many times what is in force has changed since the host was made.\n changes: number;\n // Has one shell take its draft as it is to be, for whoever changes the draft to wait on.\n adoptDraft: (live: Live, next: DraftState) => Promise<void>;\n};\n\n// Disposing stays with the caller: the shell of a session that signs out\n// nobody is disposed when its last terminal leaves.\nexport const endShell = (host: HostState, live: Live): void => {\n live.ended = true;\n host.living.delete(live);\n};\n","import { canvasTreeOf } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport { encodeDelta, frameHash } from '../protocol';\nimport type { ServerMessage } from '../protocol';\nimport { canvasesOf } from './host-state';\nimport type { Live } from './host-state';\nimport type { ShellConnection } from './types';\n\nexport const treeOf = (live: Live, canvasId: string): RenderNode[] => canvasTreeOf(live.shell, canvasId);\n\nconst canvasMessage = (live: Live, canvasId: string): string => {\n const message: ServerMessage = { type: 'render', canvas: canvasId, tree: treeOf(live, canvasId) };\n return JSON.stringify(message);\n};\n\nexport const canvasMessageOf = (live: Live, canvasId: string): string | null => {\n try {\n return canvasMessage(live, canvasId);\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvasId}\" failed to render — holding its last tree:`, error);\n return null;\n }\n};\n\n// A delta has to be decisively smaller: the transport compresses both, and a\n// delta still costs the terminal a rebuild and a checksum.\nconst DELTA_CEILING = 0.6;\n\n// The encode costs by the size of the frames, not of the change, on the thread\n// every session shares: a longer frame goes whole.\nconst DELTA_MAX_FRAME = 64 * 1024;\n\nconst shorterAsDelta = (previous: string, next: string, canvasId: string): string | null => {\n if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;\n try {\n const ops = encodeDelta(previous, next);\n const message: ServerMessage = { type: 'render-delta', canvas: canvasId, ops, hash: frameHash(next) };\n const text = JSON.stringify(message);\n return text.length <= next.length * DELTA_CEILING ? text : null;\n } catch (error) {\n console.error(`[moss/shells] canvas \"${canvasId}\" failed to encode as a delta — sending it whole:`, error);\n return null;\n }\n};\n\nconst pass = (live: Live, delta: boolean): void => {\n if (live.ended) return;\n const canvases = canvasesOf(live);\n for (const gone of [...live.sentByCanvas.keys()].filter((canvasId) => !canvases.includes(canvasId))) {\n live.sentByCanvas.delete(gone);\n const empty = JSON.stringify({ type: 'render', canvas: gone, tree: [] } satisfies ServerMessage);\n for (const connection of live.connections) connection.send(empty);\n }\n for (const canvasId of canvases) {\n const next = canvasMessageOf(live, canvasId);\n const previous = live.sentByCanvas.get(canvasId);\n if (next === null || previous === next) continue;\n live.sentByCanvas.set(canvasId, next);\n const short = delta && previous !== undefined && live.deltaReady.size > 0 ? shorterAsDelta(previous, next, canvasId) : null;\n for (const connection of live.connections) {\n connection.send(short !== null && live.deltaReady.has(connection) ? short : next);\n }\n }\n // The frame goes after the canvases, so one that references a canvas rendered\n // in this pass finds its tree already delivered.\n let frame: string | undefined;\n try {\n frame = JSON.stringify({ type: 'frame', tree: live.shell.getShellRenderTree() } satisfies ServerMessage);\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render on a flush — leaving the last one in place:', error);\n }\n if (frame !== undefined && frame !== live.sentFrame) {\n live.sentFrame = frame;\n for (const connection of live.connections) connection.send(frame);\n }\n};\n\n// The second pass, a tick later, catches what settles after the last\n// notification (an instance's status, once its loads are in).\nexport const follow = (live: Live, delta: boolean): void => {\n const flush = (): void => {\n if (live.flushing) return;\n live.flushing = true;\n queueMicrotask(() => {\n live.flushing = false;\n pass(live, delta);\n setTimeout(() => pass(live, delta), 0);\n });\n };\n live.shell.onStateChange(flush);\n live.shell.onDataChange(flush);\n};\n\nexport const attach = (live: Live, connection: ShellConnection, wantsDelta: boolean): void => {\n live.connections.add(connection);\n if (wantsDelta) live.deltaReady.add(connection);\n live.idleSince = null;\n let frameTree: RenderNode[] | undefined;\n try {\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render — serving an empty arrangement:', error);\n }\n const frameMessage = JSON.stringify({ type: 'frame', tree: frameTree ?? [] } satisfies ServerMessage);\n connection.send(frameMessage);\n if (frameTree === undefined) {\n delete live.sentFrame;\n } else {\n // Attaching renders, and can pick up a change no pass has sent yet. The\n // baseline then moves, so the others are sent it too: a pass would find\n // nothing changed. The canvases below do the same, and a delta relies on it.\n if (live.sentFrame !== frameMessage) {\n for (const other of live.connections) if (other !== connection) other.send(frameMessage);\n }\n live.sentFrame = frameMessage;\n }\n for (const canvasId of canvasesOf(live)) {\n const next = canvasMessageOf(live, canvasId);\n if (next === null) continue;\n if (live.sentByCanvas.get(canvasId) !== next) {\n for (const other of live.connections) if (other !== connection) other.send(next);\n }\n live.sentByCanvas.set(canvasId, next);\n connection.send(next);\n }\n};\n\n// What `sentByCanvas` holds, not a fresh render: the connection ends level with the\n// baseline the others share, and stays delta-capable.\nexport const resync = (live: Live, connection: ShellConnection): void => {\n if (!live.connections.has(connection)) return;\n let frameTree: RenderNode[] = [];\n try {\n frameTree = live.shell.getShellRenderTree();\n } catch (error) {\n console.error('[moss/shells] the shell frame failed to render on resync — serving an empty arrangement:', error);\n }\n connection.send(JSON.stringify({ type: 'frame', tree: frameTree } satisfies ServerMessage));\n for (const canvasId of canvasesOf(live)) {\n const current = live.sentByCanvas.get(canvasId) ?? canvasMessageOf(live, canvasId);\n if (current === null || current === undefined) continue;\n connection.send(current);\n }\n};\n","import { NovaEventSchema } from '@niscorp/nova';\nimport type { FetchFn, FunctionHandler, Shell } from '@niscorp/nova';\nimport type { FunctionSession } from '../manifest';\nimport { CLOSE_SIGNED_OUT } from '../protocol';\nimport type { ServerMessage } from '../protocol';\nimport { spanClock } from '../runtime';\nimport type { Emit } from '../runtime';\nimport { sessionDraftOn } from './draft';\nimport { endShell } from './host-state';\nimport type { Cell, HostState, Live } from './host-state';\nimport { attach, resync } from './stream';\nimport type { ShellSession } from './types';\n\nexport const instrumentFunctions = (\n fns: Record<string, FunctionHandler>,\n emit: Emit,\n principal: string | null,\n): Record<string, FunctionHandler> =>\n Object.fromEntries(\n Object.entries(fns).map(([name, handler]): [string, FunctionHandler] => [\n name,\n async (data, signal) => {\n const clock = spanClock();\n const hasPrincipal = principal !== null;\n try {\n const out = await handler(data, signal);\n emit({ name: 'fn.call', startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: 'ok', attributes: { fn: name, hasPrincipal } });\n return out;\n } catch (err) {\n emit({ name: 'fn.call', startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: 'error', attributes: { fn: name, hasPrincipal } });\n throw err;\n }\n },\n ]),\n );\n\nexport type ShellRef = { shell?: Shell; sessionShell?: Shell; live?: Live };\n\nconst grant = (shellRef: ShellRef, token: string): void => {\n const message = JSON.stringify({ type: 'session', token } satisfies ServerMessage);\n for (const connection of shellRef.live?.connections ?? []) {\n if (connection.seal === undefined) connection.send(message);\n else {\n void connection.seal(token).then(\n (sealed) => connection.send(JSON.stringify({ type: 'session', sealed } satisfies ServerMessage)),\n (error: unknown) => console.error('[moss] a sign-in could not be sealed, and was not handed over:', error),\n );\n }\n }\n};\n\n// The teardown waits a microtask, so the trigger that called this finishes\n// before its own shell is disposed.\nconst revoke = (host: HostState, shellRef: ShellRef, principal: string | null): Promise<void> => {\n const { config, durable } = host;\n const forgotten = config.revokeSessions !== undefined && principal !== null ? config.revokeSessions(principal) : Promise.resolve();\n // Logged here, so a caller that does not await leaves no unhandled rejection;\n // one that does still sees the failure.\n forgotten.catch((error: unknown) => console.error(`[moss] sign-out of ${principal ?? 'anonymous'} did not revoke its sessions:`, error));\n queueMicrotask(() => {\n const live = shellRef.live;\n if (live === undefined) return;\n endShell(host, live);\n // Only while the map still holds this shell: a reset since the sign-out\n // has put another in its cell.\n if (principal !== null && durable.get(principal)?.live === live) durable.delete(principal);\n for (const connection of [...live.connections]) connection.close(CLOSE_SIGNED_OUT, 'signed out');\n live.connections.clear();\n if (principal !== null) live.shell.dispose();\n });\n return forgotten;\n};\n\nexport const functionSessionFor = (\n host: HostState,\n who: { principal: string | null; roles: readonly string[]; scope: Record<string, unknown>; actions: readonly string[] },\n wire: FetchFn,\n shellRef: ShellRef,\n): FunctionSession => {\n const { config } = host;\n const { principal } = who;\n const artifacts = config.artifacts?.(principal);\n const session: FunctionSession = {\n get artifacts() {\n if (artifacts === undefined) throw new Error('moss: this shell host was given nothing to save with.');\n return artifacts;\n },\n draft: sessionDraftOn({ saving: config.draftSaving?.(principal), liveOf: () => shellRef.live, adopt: host.adoptDraft }),\n principal,\n roles: who.roles,\n identity: who.scope,\n actions: who.actions,\n wire,\n get shell(): Shell {\n if (shellRef.sessionShell === undefined) throw new Error('moss: a function touched the shell before the session finished building.');\n return shellRef.sessionShell;\n },\n grant: (token) => grant(shellRef, token),\n revoke: () => revoke(host, shellRef, principal),\n answerIntent: (writers, asked) =>\n config.answerIntent === undefined\n ? Promise.reject(new Error('moss: this shell host was given no way to answer an intent.'))\n : config.answerIntent(principal, writers, asked),\n recordRun: (run) => {\n config.hooks.runs?.({ ...run, at: Date.now(), principal, shellId: shellRef.shell?.id ?? '' }, session);\n },\n functions: () => {\n const functions = shellRef.live?.functions;\n return Object.keys(functions?.held ?? {}).map((id) => {\n const description = functions?.descriptions[id];\n return description === undefined ? { id } : { id, description };\n });\n },\n };\n return session;\n};\n\nexport const sessionOn = (host: HostState, cell: Cell, ephemeral: boolean, reset: (cell: Cell) => void): ShellSession => ({\n get shell(): Shell {\n return cell.live.sessionShell;\n },\n attach: (connection, options) => attach(cell.live, connection, host.delta && options?.delta === true),\n resync: (connection) => resync(cell.live, connection),\n detach: (connection) => {\n const live = cell.live;\n live.connections.delete(connection);\n live.deltaReady.delete(connection);\n if (live.connections.size > 0) return;\n live.idleSince = Date.now();\n if (!ephemeral) return;\n endShell(host, live);\n live.shell.dispose();\n },\n // An event without an origin goes to every instance of the shell, so one for\n // a canvas the shell does not have is dropped. An origin a terminal names\n // comes off the wire and is held to that canvas; with none named, the\n // canvas's active instance is the origin.\n dispatch: (canvas, event) => {\n const { shell } = cell.live;\n const state = shell.getState().canvases[canvas];\n if (state === undefined) return;\n const claimed = event['origin'];\n if (claimed !== undefined && (typeof claimed !== 'string' || !state.stack.some((item) => item.id === claimed))) return;\n const active = state.active;\n const parsed = NovaEventSchema.safeParse(claimed !== undefined || active === undefined ? event : { ...event, origin: active.id });\n if (parsed.success) shell.dispatch(parsed.data);\n },\n publish: (channel, payload) => cell.live.shell.publish(channel, payload),\n back: () => cell.live.shell.back(),\n popTo: (canvas: string, instance: string) => cell.live.shell.popTo(canvas, instance),\n reset: () => reset(cell),\n});\n","import { createComponentRegistry, createLayoutStore, createShell } from '@niscorp/nova';\nimport type { CanvasConfig, FunctionHandler, PublicActionRuntime, Reconciler, Shell } from '@niscorp/nova';\nimport { evaluate } from '@niscorp/prism';\nimport { functionsIn } from '../manifest';\nimport type { CanvasSeed, ShellCanvas } from '../manifest';\nimport { spanClock } from '../runtime';\nimport { noDraft } from './draft';\nimport { functionSessionFor, instrumentFunctions } from './sessions';\nimport type { ShellRef } from './sessions';\nimport { holdGranted, layoutsOf, withLayoutInPlace } from './host-state';\nimport type { HostState, Live, ShellFunctions } from './host-state';\nimport { follow } from './stream';\nimport type { ShellOpening } from './types';\n\nconst whole = new WeakMap<Shell, Shell>();\n\nconst refuse =\n (member: string) =>\n (): never => {\n throw new Error(\n `moss: ${member} was called on a session's shell. It changes what the shell is made of without moss: ` +\n 'what it adds is not verified, is in nobody\\'s catalog, and is gone when the shell is rebuilt. ' +\n 'Code that means to do that takes the whole shell: `unverifiedShell(session)`, from `@niscorp/moss/unverified`.',\n );\n };\n\n// Where an action's layout is kept is moss's own: app code reads a definition as it was written.\nconst runtimeAsWritten = (runtime: PublicActionRuntime, store: Shell['layoutStore']): PublicActionRuntime => ({\n get instance() {\n return runtime.instance;\n },\n get definition() {\n return withLayoutInPlace(runtime.definition, store);\n },\n getData: runtime.getData,\n setData: runtime.setData,\n render: runtime.render,\n onDataChange: runtime.onDataChange,\n onStatusChange: runtime.onStatusChange,\n});\n\nconst sessionShellOf = (shell: Shell): Shell => {\n const guarded: Shell = {\n ...shell,\n layoutStore: { ...shell.layoutStore, set: refuse('layoutStore.set'), delete: refuse('layoutStore.delete') },\n getRuntime: (instanceId) => {\n const runtime = shell.getRuntime(instanceId);\n return runtime === undefined ? undefined : runtimeAsWritten(runtime, shell.layoutStore);\n },\n registerAction: refuse('registerAction'),\n removeAction: refuse('removeAction'),\n addCanvas: refuse('addCanvas'),\n removeCanvas: refuse('removeCanvas'),\n setCanvasLayout: refuse('setCanvasLayout'),\n setLayout: refuse('setLayout'),\n setPhrases: refuse('setPhrases'),\n dispose: refuse('dispose'),\n };\n whole.set(guarded, shell);\n whole.set(shell, shell);\n return guarded;\n};\n\nexport const wholeShellOf = (sessionShell: Shell): Shell => {\n const shell = whole.get(sessionShell);\n if (shell === undefined) throw new Error('moss: this is not the shell of a session moss built.');\n return shell;\n};\n\nconst today = (): string => new Date().toISOString().slice(0, 10);\n\nconst mountedCanvases = (\n declared: readonly ShellCanvas[],\n granted: ReadonlySet<string>,\n inputs: Record<string, Record<string, unknown>>,\n given: ShellOpening['inputs'],\n): CanvasConfig[] =>\n declared.map((canvas) => {\n const declared = canvas.initial;\n const candidates = declared === undefined ? [] : Array.isArray(declared) ? declared : [declared];\n const seed = candidates.find((c) => granted.has(typeof c === 'string' ? c : c.action));\n if (seed === undefined) {\n const { initial: _dropped, ...rest } = canvas;\n return rest;\n }\n const action = typeof seed === 'string' ? seed : seed.action;\n const staticInput = typeof seed === 'string' ? {} : (seed.input ?? {});\n const withFragments = typeof seed === 'string' ? undefined : seed.with;\n return {\n ...canvas,\n initial: { action, input: { ...staticInput, ...(inputs[canvas.id] ?? {}), ...(given?.[canvas.id] ?? {}) }, ...(withFragments !== undefined ? { with: withFragments } : {}) },\n };\n });\n\nconst seedCanvases = (\n live: Live,\n declaredSeeds: Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]> | undefined,\n granted: ReadonlySet<string>,\n): void => {\n if (declaredSeeds === undefined) return;\n live.seeded = Promise.resolve(declaredSeeds)\n .then((byCanvas) => {\n if (live.ended) return;\n for (const [canvasId, seeds] of Object.entries(byCanvas ?? {})) {\n for (const seed of seeds) {\n const action = typeof seed === 'string' ? seed : seed.action;\n if (!granted.has(action)) continue;\n const input = typeof seed === 'string' ? undefined : seed.input;\n const withFragments = typeof seed === 'string' ? undefined : seed.with;\n try {\n // Not a navigation: `back` must not undo the screen somebody arrives on.\n live.shell.push(canvasId, action, input, withFragments, { history: false });\n } catch (error) {\n console.error(`[moss/shells] the seed \"${action}\" on canvas \"${canvasId}\" could not be pushed, and was skipped:`, error);\n }\n }\n }\n })\n .catch((error: unknown) => {\n console.error('[moss/shells] the seeds of a shell could not be derived, and none was pushed:', error);\n });\n};\n\nexport type BuildRequest = {\n token: string | null;\n principal: string | null;\n opening?: ShellOpening;\n reset: boolean;\n wanted: () => boolean;\n};\n\nexport const buildShell = async (host: HostState, asked: BuildRequest): Promise<Live | undefined> => {\n const { config, emit, kept, delta } = host;\n const { hooks } = config;\n const { token, principal, opening, reset, wanted } = asked;\n const buildClock = emit === undefined ? undefined : spanClock();\n const made = await config.composition(principal);\n if (!wanted()) return undefined;\n const ids = Object.keys(made.actions);\n const granted = new Set(ids);\n const inputs = (await hooks.inputs?.({ principal, actions: ids, roles: made.roles, identity: made.scope, wire: config.wire(token) })) ?? {};\n if (!wanted()) return undefined;\n const canvases = mountedCanvases(made.canvases, granted, inputs, opening?.inputs);\n\n const wire = config.wrapWire === undefined ? config.wire(token) : config.wrapWire(config.wire(token));\n const userId = principal ?? 'anonymous';\n\n const registry = createComponentRegistry();\n for (const [name, contract] of Object.entries(made.components)) registry.register(name, contract);\n\n const shellRef: ShellRef = {};\n const session = functionSessionFor(host, { principal, roles: made.roles, scope: made.scope, actions: ids }, wire, shellRef);\n\n const phrases = (await hooks.phrases?.({ principal, identity: made.scope, wire: config.wire(token) })) ?? {};\n if (!wanted()) return undefined;\n\n // No await between here and `shellRef.shell = shell`: app code defers its\n // first touch of `session.shell` by a microtask, which has to find the shell\n // there and still land before the shell's mount calls answer.\n const handlers: Record<string, FunctionHandler> = {};\n const descriptions: Record<string, string> = {};\n for (const { id, description, execute } of functionsIn(hooks.functions?.(session) ?? [])) {\n handlers[id] = execute;\n if (description !== '') descriptions[id] = description;\n }\n const functions: ShellFunctions = { all: emit === undefined ? handlers : instrumentFunctions(handlers, emit, principal), held: {}, descriptions };\n holdGranted(functions, made.grantedFunctions);\n if (kept) hooks.onSession?.(session);\n\n const layoutStore = createLayoutStore();\n for (const [refId, node] of Object.entries(made.layoutStore ?? {})) layoutStore.set(refId, node);\n\n // A reconciler is app code: it is handed the shell `session.shell` is, which refuses what would change what the\n // shell is made of. A mount can reconcile while the shell is still being made, so the guarded shell is made on demand.\n let guarded: Shell | undefined;\n const guardedOf = (shell: Shell): Shell => (guarded ??= sessionShellOf(shell));\n const reconcilers: Record<string, Reconciler> = {};\n for (const [name, reconcile] of Object.entries(hooks.reconcilers ?? {})) {\n reconcilers[name] = (reconciled, canvasId, desired, options) => reconcile(guardedOf(reconciled), canvasId, desired, options);\n }\n\n // Two builds from one seed mint the same instance ids: the shell a document\n // was rendered from, and the one the socket builds a moment later for the\n // same visitor.\n let minted = 0;\n const idSeed = opening?.seed;\n const shell = createShell({\n registry,\n canvases,\n layoutStore,\n ...(idSeed === undefined ? {} : { instanceIdFn: () => `act-${idSeed}-${(minted += 1)}` }),\n ...(made.frame !== undefined ? { canvasLayout: made.frame } : {}),\n actions: { ...made.actions },\n ...(made.fragments !== undefined ? { fragments: { ...made.fragments } } : {}),\n transform: (config, source) =>\n evaluate(config, source !== null && typeof source === 'object' && !Array.isArray(source) ? { ...source, userId, today: today() } : source),\n fetch: wire,\n functions: functions.held,\n ...(hooks.reconcilers === undefined ? {} : { reconcilers }),\n ...(config.limits?.endpointTimeoutMs === undefined ? {} : { endpointTimeoutMs: config.limits.endpointTimeoutMs }),\n // An empty book is withheld: nova runs its phrase pass whenever one is given.\n ...(Object.keys(phrases).length === 0 ? {} : { phrases }),\n ...(config.phraseKeys === undefined ? {} : { phraseKeys: config.phraseKeys }),\n });\n const sessionShell = guardedOf(shell);\n shellRef.shell = shell;\n shellRef.sessionShell = sessionShell;\n\n const live: Live = {\n shell,\n sessionShell,\n actionIds: granted,\n entries: made.entries,\n layouts: layoutsOf(made),\n slottedCanvases: new Set(made.slottedCanvases),\n functions,\n draft: noDraft(),\n connections: new Set(),\n sentByCanvas: new Map(),\n deltaReady: new Set(),\n flushing: false,\n ended: false,\n builtAt: Date.now(),\n idleSince: Date.now(),\n seeded: Promise.resolve(),\n };\n shellRef.live = live;\n\n seedCanvases(live, hooks.seeds?.({ principal, actions: ids, roles: made.roles, wire }), granted);\n follow(live, delta);\n\n if (emit !== undefined && buildClock !== undefined) {\n emit({ name: 'shell.build', startUnixNano: buildClock.startUnixNano, endUnixNano: buildClock.endUnixNano(), status: 'ok', attributes: { reset, hasPrincipal: principal !== null } });\n }\n\n return live;\n};\n"]}