@niscorp/moss 0.2.1 → 0.2.3

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.
package/README.md CHANGED
@@ -4,22 +4,26 @@ The nisc application server. A principal logs in, a charter resolves, and what a
4
4
 
5
5
  Moss does not host code and guard it. It serves *existence*: a resolved catalog **is** the application. The warehouse kiosk granted two actions is not a locked-down app; it is a two-action app. There is nothing else to render, invoke, or attack.
6
6
 
7
- > Early stages. The data/policy plane, the socket, per-principal server shells, ring-2 served layout variants, the in-process function seam, and the canvas terminal (the wire plus swappable render targets) are built and tested — except the terminal's render targets, which have no tests yet. The fn *host* (`/fns`), the artifact library, the projection model, and scale-out are specified and pending. See [DESIGN.md](DESIGN.md) for the thesis and the unbuilt ladder.
7
+ > On npm, and still early. The data/policy plane, the socket, per-principal server shells, ring-2 served layout variants, the in-process function seam, server-drawn documents and pages, and the canvas terminal (the wire plus swappable render targets) are built and tested — except the ink render target, which has no tests yet. The fn *host* (`/fns`), the artifact library, the projection model, and scale-out are specified and pending. See [DESIGN.md](DESIGN.md) for the thesis and the unbuilt ladder.
8
8
 
9
9
  ## Install
10
10
 
11
11
  ```bash
12
- pnpm add @niscorp/moss zod
13
- # everything moss composes (charter, vex, nova, prism, hono, the Node
14
- # listener) comes with it as regular dependencies. The one optional peer
15
- # pair is React, needed only for the ./terminal/react render target:
16
- pnpm add react react-dom
17
- # (or Vue, needed only for the ./terminal/vue render target: pnpm add vue)
12
+ pnpm add @niscorp/moss @niscorp/charter @niscorp/nova @niscorp/prism @niscorp/strata @niscorp/tide @niscorp/vex zod
13
+ # the nisc packages moss composes and zod are required peers — the app owns
14
+ # the one copy of each. hono, the Node listener and ws come with moss as
15
+ # regular dependencies. The optional peers, each needed by one subpath only:
16
+ pnpm add react react-dom # ./terminal/react (and its /server)
17
+ pnpm add vue # ./terminal/vue (and its /server)
18
+ pnpm add ink react # ./terminal/ink
19
+ pnpm add -D vite # ./vite
18
20
  ```
19
21
 
22
+ Node ≥ 22.12.
23
+
20
24
  ## The shape
21
25
 
22
- An app hands moss its **artifacts** (`defineApp`) and an **environment** (`NiscRuntime` — a database, optionally a cache and a session verifier). Everything mechanical is derived: the data layer from the schema, per-principal policy and catalogs from the charter, the server shells from the manifest. The server refuses to boot on an incoherent charter.
26
+ An app hands moss its **artifacts** (`defineApp`) and an **environment** (`NiscRuntime` — a database and how a session token is verified, optionally a cache). Everything mechanical is derived: the data layer from the schema, per-principal policy and catalogs from the charter, the server shells from the manifest. The server refuses to boot on an incoherent charter.
23
27
 
24
28
  ```typescript
25
29
  import { defineApp } from '@niscorp/moss';
@@ -41,7 +45,9 @@ const app = defineApp({
41
45
  functions, // the in-process fn seam (agents, sign-in) — optional
42
46
  });
43
47
 
44
- const server = await serve(app, { pool, db, port: 3000 });
48
+ const server = await serve(app, { pool, db, session: 'sessions', port: 3000 });
49
+ // `session` is required: 'sessions' (moss's stored credential), 'dev-open'
50
+ // (every well-formed token trusted — harnesses), or the app's own verifier.
45
51
  // boot refusal here (createServer runs inside serve); HTTP + ws in one
46
52
  ```
47
53
 
@@ -125,7 +131,7 @@ never in moss core.
125
131
  ## Subpaths
126
132
 
127
133
  - **`@niscorp/moss`** — the server: `defineApp`, `createServer`, the resolution and shell-host internals, the socket protocol types.
128
- - **`@niscorp/moss/node`** — the Node listener: `serve` + `attachSocket` (raw `ws`). Bun swaps this file, never the app.
134
+ - **`@niscorp/moss/node`** — the Node listener: `serve` + `attachSocket` (raw `ws`), and `mountSite(server, { dist, draw })` — the built terminal served by the same process, every page drawn. Bun swaps this file, never the app.
129
135
  - **`@niscorp/moss/vite`** — `mossDev({ app })`: the app server inside vite's dev process — loaded through vite (an edit re-boots it), the socket attached once, pages drawn, moss's paths answered, a dev-only `/dev/as/<who>`. `nisc dev` adds it for an app behind moss; `vite` is an optional peer.
130
136
  - **`@niscorp/moss/client`** — the wire: `createWire()`, the app end of the socket. Plain TypeScript, zero React, zero globals — the host comes in as a `WireEnv` (default: `browserEnv()`, localStorage + location).
131
137
  - **`@niscorp/moss/client/node`** — the Node host env: `nodeEnv({ url, tokenFile? })` runs the same wire on a plain Node (or Bun) process — token in a file, the runtime's WHATWG WebSocket.
@@ -133,6 +139,7 @@ never in moss core.
133
139
  - **`@niscorp/moss/terminal/react`** — the React render target: `reactTarget({ root, registry, slotWrapper? })` binds the app's component registry to the wire via nova's React adapter.
134
140
  - **`@niscorp/moss/terminal/vue`** — the Vue render target: `vueTarget({ root, registry, slotWrapper? })` binds the app's Vue component registry to the wire via nova's Vue adapter; updates re-render reactively, never remount.
135
141
  - **`@niscorp/moss/terminal/dom`** — the plain-DOM render target: `domTarget({ root })` renders with nova's DOM adapter and default kit. Zero framework.
142
+ - **`@niscorp/moss/terminal/react/server`**, **`/vue/server`**, **`/dom/server`** — `renderSnapshot(...)`: a shell snapshot drawn to a string by the same kit, for `renderDocument`'s `draw`.
136
143
  - **`@niscorp/moss/terminal/tty`** — the line-terminal render target: `ttyTarget({ input, output })` runs the app as a REPL in a real terminal — served frames print as text with numbered markers, typing acts on them (numbers tap, words fill), and the same events ride the wire. Zero framework, zero DOM.
137
144
  - **`@niscorp/moss/terminal/ink`** — the full-screen terminal render target: `inkTarget()` runs the app as a TUI — nova's Ink kit on the React adapter's walker. Same `[n]` addressing as the REPL (typed digits click/flip/focus), plus Tab/arrows and live typing. ESM-only, like ink.
138
145
 
@@ -144,10 +151,12 @@ never in moss core.
144
151
 
145
152
  ## Tables and documents, versioned
146
153
 
147
- moss creates no table on its own: its tables (`MOSS_SEQUENCE`,
148
- `SESSIONS_SEQUENCE`, `TIDE_SEQUENCE`) and the vex cache's go through one
149
- [strata](../strata/README.md) ledger run at boot — once, recorded, refused if
150
- the ledger was edited or written by newer code. `migrations: 'verify'` on the
154
+ moss creates no table on its own: its tables (`MOSS_SEQUENCE`, plus
155
+ `SESSIONS_SEQUENCE` when the runtime's `session` is `'sessions'`) and the vex
156
+ cache's go through one [strata](../strata/README.md) ledger run at boot — once,
157
+ recorded, refused if the ledger was edited or written by newer code. The tide
158
+ store's tables (`TIDE_SEQUENCE`) go through the same ledger when
159
+ `createTideStore(pool)` is called. `migrations: 'verify'` on the
151
160
  runtime refuses to boot with anything pending. Stored integration actions carry
152
161
  a grammar stamp and are upgraded at boot, at intake and on read — through
153
162
  nova's and Prism's grammars plus the app's own (`NiscApp.grammars`); a bundle or
@@ -1,6 +1,6 @@
1
1
  import { renderDocument, createServer } from './chunk-2AHJ6VDR.js';
2
2
  import { readFile } from 'fs/promises';
3
- import { relative, join } from 'path';
3
+ import { relative, extname, join } from 'path';
4
4
  import { serve as serve$1 } from '@hono/node-server';
5
5
  import { serveStatic } from '@hono/node-server/serve-static';
6
6
  import { WebSocketServer } from 'ws';
@@ -38,6 +38,7 @@ var mountSite = (server, config) => {
38
38
  });
39
39
  server.get("*", async (c) => {
40
40
  if (owned.test(c.req.path)) return c.notFound();
41
+ if (extname(c.req.path) !== "" && c.req.path !== "/index.html" && server.page(c.req.path) === void 0) return c.notFound();
41
42
  const template = await readFile(join(dist, "index.html"), "utf8");
42
43
  const page = await renderDocument({
43
44
  ...drawing,
@@ -59,5 +60,5 @@ var serve = async (app, runtime) => {
59
60
  };
60
61
 
61
62
  export { MOSS_PATHS, attachSocket, mountSite, serve };
62
- //# sourceMappingURL=chunk-5S7TBULB.js.map
63
- //# sourceMappingURL=chunk-5S7TBULB.js.map
63
+ //# sourceMappingURL=chunk-JBRD2TDQ.js.map
64
+ //# sourceMappingURL=chunk-JBRD2TDQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node.ts"],"names":["listen"],"mappings":";;;;;;;AAgCO,IAAM,eAAe,CAC1B,UAAA,EACA,MAAA,EACA,IAAA,GAAO,WACP,OAAA,KACS;AACT,EAAA,MAAM,GAAA,GAAM,IAAI,eAAA,CAAgB,EAAE,QAAA,EAAU,MAAM,iBAAA,EAAmB,OAAA,EAAS,WAAA,IAAe,IAAA,EAAM,CAAA;AACnG,EAAA,UAAA,C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AAO,QAAQ,KAAK,IAAA;AAAK,KAC1G,CAAA;AACD,IAAA,OAAO,EAAE,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,GAAA,EAAK,KAAK,OAAO,CAAA;AAAA,EAC5C,CAAC,CAAA;AACH;AAEO,IAAM,KAAA,GAAQ,OAAO,GAAA,EAAc,OAAA,KAAkE;AAC1G,EAAA,MAAM,MAAA,GAAS,MAAM,YAAA,CAAa,GAAA,EAAK,OAAO,CAAA;AAC9C,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,IAAQ,IAAA;AAC7B,EAAA,MAAM,aAAaA,OAAA,CAAO,EAAE,OAAO,MAAA,CAAO,KAAA,EAAO,MAAM,CAAA;AACvD,EAAA,YAAA,CAAa,YAAY,MAAA,CAAO,MAAA,EAAQ,SAAA,EAAW,EAAE,GAAI,OAAA,CAAQ,iBAAA,KAAsB,MAAA,GAAY,EAAE,aAAa,OAAA,CAAQ,iBAAA,EAAkB,GAAI,IAAK,CAAA;AACrJ,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiC,IAAI,CAAA,CAAE,CAAA;AACnD,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,oGAAA,EAA8F,IAAI,CAAA,OAAA,CAAS,CAAA;AACvH,EAAA,OAAO,MAAA;AACT","file":"chunk-JBRD2TDQ.js","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { extname, join, relative } from 'node:path';\nimport { serve as listen } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport { WebSocketServer } from 'ws';\nimport type { IncomingMessage } from 'node:http';\nimport type { Duplex } from 'node:stream';\nimport { createServer } from './server';\nimport type { MossServer } from './server';\nimport type { NiscApp } from './app';\nimport type { NiscRuntime } from './runtime';\nimport type { SocketAccept } from './socket';\nimport { renderDocument } from './document';\nimport type { DocumentConfig } from './document';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node entry — runtime-specific by design: the transport is a seam, so\n// the Bun flip swaps this file, never the app. Two exports: the\n// websocket transport for hosts that run their own listener (the dev\n// checks, vite), and the batteries-included `serve`.\n// ═══════════════════════════════════════════════════════════════\n\n// Anything that emits Node upgrade events — http.Server structurally, so\n// the @hono/node-server return type needs no narrowing.\ntype Upgradeable = {\n on: (event: 'upgrade', handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void) => unknown;\n};\n\n// The `ws` half of the transport seam: RFC 6455 stays library-handled\n// (permessage-deflate on by default — see `runtime.socketCompression`); the\n// protocol above the seam is nisc's own (../socket.ts) and identical on every\n// runtime.\nexport const attachSocket = (\n httpServer: Upgradeable,\n accept: SocketAccept,\n path = '/socket',\n options?: { compression?: boolean | Record<string, unknown> },\n): void => {\n const wss = new WebSocketServer({ noServer: true, perMessageDeflate: options?.compression ?? true });\n httpServer.on('upgrade', (req, socket, head) => {\n const url = req.url ?? '/';\n // Not ours: leave it for whichever other listener owns it (vite's HMR\n // upgrade rides the same server in dev).\n if (new URL(url, 'http://nisc.local').pathname !== path) return;\n wss.handleUpgrade(req, socket, head, (ws) => {\n // accept promises to handle its own failures (see socket.ts). This is\n // the floor under that promise: an await added there without a guard\n // degrades to one logged close here instead of an unhandled rejection\n // taking every session on the box down with it.\n accept(url, {\n send: (text) => ws.send(text),\n close: (code, reason) => ws.close(code, reason),\n onMessage: (fn) => ws.on('message', (data) => fn(String(data))),\n onClose: (fn) => ws.on('close', () => fn()),\n }).catch((error: unknown) => {\n console.error('[moss/node] a connection escaped accept:', error);\n try {\n ws.close(1011, 'accept failed');\n } catch {\n // already gone\n }\n });\n });\n });\n};\n\n// THE BUILT TERMINAL, served by the same process as the app — one origin, so the\n// socket is `/socket` wherever the page came from.\n//\n// `dist` is what the app's bundler wrote: index.html and its assets. Every GET\n// that nothing registered earlier answers is a file from it, or a PAGE:\n// index.html with the caller's screen drawn into it (./document) — the app's own\n// for `/`, one of the manifest's pages for a path that leads to one. index.html\n// itself is never served as a file: it is the template, and goes out drawn.\n//\n// A name with an extension that is neither a file in `dist` nor a page of the\n// manifest is a MISSING FILE, and is answered 404 — not with a screen. A browser\n// holding a page from before a deploy asks for that page's script by its old\n// name; what it needs back is \"gone\", not a document that is not a script.\n//\n// Register the app's own routes FIRST; this is the catch-all. `owned` names the\n// prefixes that are never a page (default: moss's own surfaces) — an unknown\n// path under one is a 404, not a screen.\nexport type SiteConfig = Pick<DocumentConfig, 'draw' | 'htmlAttributes' | 'tokenKey' | 'waitMs'> & {\n dist: string;\n owned?: RegExp;\n};\n\n// The paths the app server answers itself; everything else is the site's.\nexport const MOSS_PATHS = /^\\/(api|catalog|socket|operator|integrations)(\\/|$)/;\n\nexport const mountSite = (server: MossServer, config: SiteConfig): void => {\n const { dist, owned = MOSS_PATHS, ...drawing } = config;\n // serveStatic resolves `root` against the working directory.\n const root = relative(process.cwd(), dist) || '.';\n const files = serveStatic({ root });\n server.use('/*', async (c, next) => {\n const path = c.req.path;\n if (owned.test(path) || path === '/' || path === '/index.html' || server.page(path) !== undefined) return next();\n return files(c, next);\n });\n server.get('*', async (c) => {\n if (owned.test(c.req.path)) return c.notFound();\n // the static server above found no such file, and no page is at this path\n if (extname(c.req.path) !== '' && c.req.path !== '/index.html' && server.page(c.req.path) === undefined) return c.notFound();\n const template = await readFile(join(dist, 'index.html'), 'utf8');\n const page = await renderDocument({\n ...drawing,\n server,\n template,\n request: { path: c.req.path === '/index.html' ? '/' : c.req.path, cookie: c.req.header('cookie') ?? null },\n });\n return c.html(page.html, 200, page.headers);\n });\n};\n\nexport const serve = async (app: NiscApp, runtime: NiscRuntime & { port?: number }): Promise<MossServer> => {\n const server = await createServer(app, runtime);\n const port = runtime.port ?? 8787;\n const httpServer = listen({ fetch: server.fetch, port });\n attachSocket(httpServer, server.socket, '/socket', { ...(runtime.socketCompression !== undefined ? { compression: runtime.socketCompression } : {}) });\n console.log(`moss serving http://localhost:${port}`);\n console.log(`surfaces: GET /catalog · GET|POST /api/vex · GET|POST /api/<resource>/vex · ws://localhost:${port}/socket`);\n return server;\n};\n"]}
@@ -593,6 +593,13 @@ type NiscApp = {
593
593
  wire: FetchFn;
594
594
  }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;
595
595
  phraseKeys?: PhraseKeys;
596
+ /**
597
+ * @deprecated Never called. Which integrations are live for a principal's
598
+ * tenant is `installed` on the record `identity.resolve` returns; without
599
+ * `identity`, every registered integration is live for everybody. Kept on
600
+ * the type so a manifest that still names it compiles — and it stays: a
601
+ * manifest that works is not broken to tidy a type.
602
+ */
596
603
  installedIntegrations?: (principal: string | null) => readonly string[] | Promise<readonly string[]>;
597
604
  integrationActor?: (integration: string, actsFor: string) => string | null | Promise<string | null>;
598
605
  attachable?: Record<string, Record<string, string>>;
@@ -593,6 +593,13 @@ type NiscApp = {
593
593
  wire: FetchFn;
594
594
  }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;
595
595
  phraseKeys?: PhraseKeys;
596
+ /**
597
+ * @deprecated Never called. Which integrations are live for a principal's
598
+ * tenant is `installed` on the record `identity.resolve` returns; without
599
+ * `identity`, every registered integration is live for everybody. Kept on
600
+ * the type so a manifest that still names it compiles — and it stays: a
601
+ * manifest that works is not broken to tidy a type.
602
+ */
596
603
  installedIntegrations?: (principal: string | null) => readonly string[] | Promise<readonly string[]>;
597
604
  integrationActor?: (integration: string, actsFor: string) => string | null | Promise<string | null>;
598
605
  attachable?: Record<string, Record<string, string>>;