@niscorp/moss 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/DESIGN.md +84 -19
  3. package/DOCS.md +170 -35
  4. package/README.md +2 -2
  5. package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
  6. package/dist/chunk-4T6KAXBP.js.map +1 -0
  7. package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
  8. package/dist/chunk-HOZID4EM.js.map +1 -0
  9. package/dist/{chunk-ZP3C53AC.js → chunk-R3QMJ3JF.js} +744 -661
  10. package/dist/chunk-R3QMJ3JF.js.map +1 -0
  11. package/dist/chunk-U3UR5AOQ.js +103 -0
  12. package/dist/chunk-U3UR5AOQ.js.map +1 -0
  13. package/dist/client/node.cjs +1 -1
  14. package/dist/client/node.cjs.map +1 -1
  15. package/dist/client/node.js +1 -1
  16. package/dist/client/node.js.map +1 -1
  17. package/dist/client.cjs +60 -26
  18. package/dist/client.cjs.map +1 -1
  19. package/dist/client.d.cts +6 -1
  20. package/dist/client.d.ts +6 -1
  21. package/dist/client.js +2 -2
  22. package/dist/{document-D9khv9jI.d.cts → document-DhWxieUc.d.cts} +22 -3
  23. package/dist/{document-D9khv9jI.d.ts → document-DhWxieUc.d.ts} +22 -3
  24. package/dist/index.cjs +786 -583
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +19 -3
  27. package/dist/index.d.ts +19 -3
  28. package/dist/index.js +2 -2
  29. package/dist/node.cjs +379 -230
  30. package/dist/node.cjs.map +1 -1
  31. package/dist/node.d.cts +2 -1
  32. package/dist/node.d.ts +2 -1
  33. package/dist/node.js +3 -3
  34. package/dist/terminal/index.cjs +60 -26
  35. package/dist/terminal/index.cjs.map +1 -1
  36. package/dist/terminal/index.js +2 -2
  37. package/dist/vite.cjs +103 -28
  38. package/dist/vite.cjs.map +1 -1
  39. package/dist/vite.d.cts +1 -1
  40. package/dist/vite.d.ts +1 -1
  41. package/dist/vite.js +14 -9
  42. package/dist/vite.js.map +1 -1
  43. package/package.json +12 -12
  44. package/dist/chunk-J72N3EMJ.js.map +0 -1
  45. package/dist/chunk-SUVDISEG.js +0 -64
  46. package/dist/chunk-SUVDISEG.js.map +0 -1
  47. package/dist/chunk-ZOEUEMDX.js.map +0 -1
  48. package/dist/chunk-ZP3C53AC.js.map +0 -1
@@ -0,0 +1,103 @@
1
+ import { renderDocument, createServer } from './chunk-R3QMJ3JF.js';
2
+ import { SUBPROTOCOL } from './chunk-HOZID4EM.js';
3
+ import { readFile } from 'fs/promises';
4
+ import { relative, extname, join } from 'path';
5
+ import { serve as serve$1 } from '@hono/node-server';
6
+ import { serveStatic } from '@hono/node-server/serve-static';
7
+ import { WebSocketServer } from 'ws';
8
+
9
+ var MAX_MESSAGE_BYTES = 256 * 1024;
10
+ var attachSocket = (httpServer, accept, path = "/socket", options) => {
11
+ const wss = new WebSocketServer({
12
+ noServer: true,
13
+ perMessageDeflate: options?.compression ?? true,
14
+ maxPayload: options?.maxMessageBytes ?? MAX_MESSAGE_BYTES,
15
+ // Of what a terminal offers, `nisc` is answered and nothing else: the
16
+ // other entry is its token (socket.ts), which is not said back.
17
+ handleProtocols: (offered) => offered.has(SUBPROTOCOL) ? SUBPROTOCOL : false
18
+ });
19
+ const answers = /* @__PURE__ */ new WeakMap();
20
+ wss.on("headers", (headers, req) => {
21
+ for (const cookie of answers.get(req) ?? []) headers.push(`Set-Cookie: ${cookie}`);
22
+ });
23
+ httpServer.on("upgrade", (req, socket, head) => {
24
+ const url = req.url ?? "/";
25
+ if (new URL(url, "http://nisc.local").pathname !== path) return;
26
+ socket.on("error", () => {
27
+ });
28
+ let ws;
29
+ let answered = false;
30
+ let cookies = [];
31
+ const answer = () => {
32
+ if (answered) return ws;
33
+ answered = true;
34
+ answers.set(req, cookies);
35
+ wss.handleUpgrade(req, socket, head, (opened) => {
36
+ ws = opened;
37
+ opened.on("error", (error) => {
38
+ console.warn(`[moss/node] a connection was closed on what it sent: ${error.message}`);
39
+ });
40
+ });
41
+ return ws;
42
+ };
43
+ accept(url, {
44
+ send: (text) => void answer()?.send(text),
45
+ close: (code, reason) => void answer()?.close(code, reason),
46
+ onMessage: (fn) => void answer()?.on("message", (data) => fn(String(data))),
47
+ onClose: (fn) => {
48
+ const opened = answer();
49
+ if (opened === void 0) queueMicrotask(fn);
50
+ else opened.on("close", () => fn());
51
+ },
52
+ upgrade: {
53
+ offered: String(req.headers["sec-websocket-protocol"] ?? "").split(",").map((entry) => entry.trim()),
54
+ origin: req.headers.origin ?? null,
55
+ host: req.headers.host ?? null,
56
+ cookie: req.headers.cookie ?? null,
57
+ answer: (given) => void (cookies = given)
58
+ }
59
+ }).catch((error) => {
60
+ console.error("[moss/node] a connection escaped accept:", error);
61
+ try {
62
+ answer()?.close(1011, "accept failed");
63
+ } catch {
64
+ }
65
+ });
66
+ });
67
+ };
68
+ var MOSS_PATHS = /^\/(api|catalog|socket|operator|integrations)(\/|$)/;
69
+ var mountSite = (server, config) => {
70
+ const { dist, owned = MOSS_PATHS, ...drawing } = config;
71
+ const root = relative(process.cwd(), dist) || ".";
72
+ const files = serveStatic({ root });
73
+ server.use("/*", async (c, next) => {
74
+ const path = c.req.path;
75
+ if (owned.test(path) || path === "/" || path === "/index.html" || server.page(path) !== void 0) return next();
76
+ return files(c, next);
77
+ });
78
+ server.get("*", async (c) => {
79
+ if (owned.test(c.req.path)) return c.notFound();
80
+ if (extname(c.req.path) !== "" && c.req.path !== "/index.html" && server.page(c.req.path) === void 0) return c.notFound();
81
+ const template = await readFile(join(dist, "index.html"), "utf8");
82
+ const page = await renderDocument({
83
+ ...drawing,
84
+ server,
85
+ template,
86
+ request: { path: c.req.path === "/index.html" ? "/" : c.req.path, cookie: c.req.header("cookie") ?? null, host: c.req.header("host") ?? null }
87
+ });
88
+ return c.html(page.html, 200, page.headers);
89
+ });
90
+ };
91
+ var serve = async (app, runtime) => {
92
+ const server = await createServer(app, runtime);
93
+ const port = runtime.port ?? 8787;
94
+ const httpServer = serve$1({ fetch: server.fetch, port });
95
+ attachSocket(httpServer, server.socket, "/socket", { ...runtime.socketCompression !== void 0 ? { compression: runtime.socketCompression } : {} });
96
+ console.log(`moss serving http://localhost:${port}`);
97
+ console.log(`surfaces: GET /catalog \xB7 GET|POST /api/vex \xB7 GET|POST /api/<resource>/vex \xB7 ws://localhost:${port}/socket`);
98
+ return server;
99
+ };
100
+
101
+ export { MOSS_PATHS, attachSocket, mountSite, serve };
102
+ //# sourceMappingURL=chunk-U3UR5AOQ.js.map
103
+ //# sourceMappingURL=chunk-U3UR5AOQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node.ts"],"names":["listen"],"mappings":";;;;;;;;AAwCA,IAAM,oBAAoB,GAAA,GAAM,IAAA;AAMzB,IAAM,eAAe,CAC1B,UAAA,EACA,MAAA,EACA,IAAA,GAAO,WACP,OAAA,KACS;AACT,EAAA,MAAM,GAAA,GAAM,IAAI,eAAA,CAAgB;AAAA,IAC9B,QAAA,EAAU,IAAA;AAAA,IACV,iBAAA,EAAmB,SAAS,WAAA,IAAe,IAAA;AAAA,IAC3C,UAAA,EAAY,SAAS,eAAA,IAAmB,iBAAA;AAAA;AAAA;AAAA,IAGxC,iBAAiB,CAAC,OAAA,KAAa,QAAQ,GAAA,CAAI,WAAW,IAAI,WAAA,GAAc;AAAA,GACzE,CAAA;AAED,EAAA,MAAM,OAAA,uBAAc,OAAA,EAA4C;AAChE,EAAA,GAAA,CAAI,EAAA,CAAG,SAAA,EAAW,CAAC,OAAA,EAAS,GAAA,KAAQ;AAClC,IAAA,KAAA,MAAW,MAAA,IAAU,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA,IAAK,EAAC,EAAG,OAAA,CAAQ,IAAA,CAAK,CAAA,YAAA,EAAe,MAAM,CAAA,CAAE,CAAA;AAAA,EACnF,CAAC,CAAA;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AA,EAAQ,EAAE,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA,IAAK,IAAA,EAAM,IAAA,EAAM,EAAE,GAAA,CAAI,MAAA,CAAO,MAAM,CAAA,IAAK,IAAA;AAAK,KAC9I,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-U3UR5AOQ.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 { WebSocket as ServerSocket } 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 { SUBPROTOCOL } from './socket';\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 LARGEST MESSAGE A CONNECTION MAY SEND, in bytes, unless the host says\n// otherwise (`options.maxMessageBytes`). Told nothing, `ws` takes 100 MiB — and\n// what a terminal sends is an event: a press, a typed value, one row handed\n// back. A few KB. Whatever a message carries, the server then keeps (the value\n// in the shell, and again in the last frame it sent) and sends back down in\n// every later frame of that canvas, so this is what ONE connection, signed in\n// or not, can make the process hold and re-send: about 1.5 MB at this limit,\n// 48 MB for a 16 MiB value. Compression is no bound — 64 MB of one letter is\n// 60 KB on the wire — so the count is of the message once inflated. A message\n// over it closes that connection with 1009, and nothing else.\nconst MAX_MESSAGE_BYTES = 256 * 1024;\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>; maxMessageBytes?: number },\n): void => {\n const wss = new WebSocketServer({\n noServer: true,\n perMessageDeflate: options?.compression ?? true,\n maxPayload: options?.maxMessageBytes ?? MAX_MESSAGE_BYTES,\n // Of what a terminal offers, `nisc` is answered and nothing else: the\n // other entry is its token (socket.ts), which is not said back.\n handleProtocols: (offered) => (offered.has(SUBPROTOCOL) ? SUBPROTOCOL : false),\n });\n // The cookies moss answers an upgrade with ride the 101 itself.\n const answers = new WeakMap<IncomingMessage, readonly string[]>();\n wss.on('headers', (headers, req) => {\n for (const cookie of answers.get(req) ?? []) headers.push(`Set-Cookie: ${cookie}`);\n });\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 // THE REQUEST IS ANSWERED ONCE MOSS HAS DECIDED WHO IS ASKING, because the\n // answer is the one thing that can write a browser's session cookie\n // (session-cookie.ts). Until then the raw socket is nobody's to listen to,\n // and a peer that resets it would be an 'error' thrown out of Node — the\n // whole process. Heard here, it is that request's alone.\n socket.on('error', () => {});\n let ws: ServerSocket | undefined;\n let answered = false;\n // The first use of the connection answers the request, with the cookies\n // moss has named by then — which is as soon as it has decided who is\n // asking, or is refusing the terminal outright. A request `ws` will not\n // upgrade (a bad key, a peer already gone) leaves no websocket: nothing is\n // sent to it, and it is closed already.\n let cookies: readonly string[] = [];\n const answer = (): ServerSocket | undefined => {\n if (answered) return ws;\n answered = true;\n answers.set(req, cookies);\n wss.handleUpgrade(req, socket, head, (opened) => {\n ws = opened;\n // `ws` reports what it refuses from a client — a malformed frame, a\n // message over its size limit — as an 'error' on that connection, having\n // already closed it with the status that says why (1002, 1009). An\n // 'error' nobody listens for is thrown by Node, out of the socket's own\n // data handler where nothing can catch it: one bad frame from one\n // client took the process, and every session on it, down. Heard here it\n // is that connection's alone, and the close it already got is the answer.\n opened.on('error', (error) => {\n console.warn(`[moss/node] a connection was closed on what it sent: ${error.message}`);\n });\n });\n return ws;\n };\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) => void answer()?.send(text),\n close: (code, reason) => void answer()?.close(code, reason),\n onMessage: (fn) => void answer()?.on('message', (data) => fn(String(data))),\n onClose: (fn) => {\n const opened = answer();\n if (opened === undefined) queueMicrotask(fn);\n else opened.on('close', () => fn());\n },\n upgrade: {\n offered: String(req.headers['sec-websocket-protocol'] ?? '').split(',').map((entry) => entry.trim()),\n origin: req.headers.origin ?? null,\n host: req.headers.host ?? null,\n cookie: req.headers.cookie ?? null,\n answer: (given) => void (cookies = given),\n },\n }).catch((error: unknown) => {\n console.error('[moss/node] a connection escaped accept:', error);\n try {\n answer()?.close(1011, 'accept failed');\n } catch {\n // already gone\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' | 'site' | '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, host: c.req.header('host') ?? 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"]}
@@ -32,7 +32,7 @@ var nodeEnv = (config) => {
32
32
  }
33
33
  }
34
34
  },
35
- socket: (url) => new WebSocket(url),
35
+ socket: ({ url, offered }) => new WebSocket(url, offered),
36
36
  defaultUrl: () => config.url
37
37
  };
38
38
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/node.ts"],"names":["join","homedir","readFileSync","mkdirSync","dirname","writeFileSync","rmSync"],"mappings":";;;;;;;AAcO,IAAM,OAAA,GAAU,CAAC,MAAA,KAAyD;AAG/E,EAAA,MAAM,YAAY,MAAA,CAAO,SAAA,IAAaA,UAAKC,UAAA,EAAQ,EAAG,SAAS,OAAO,CAAA;AACtE,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ;AAAA,MACN,MAAM,MAAM;AACV,QAAA,IAAI;AACF,UAAA,MAAM,GAAA,GAAMC,eAAA,CAAa,SAAA,EAAW,MAAM,EAAE,IAAA,EAAK;AACjD,UAAA,OAAO,GAAA,KAAQ,KAAK,IAAA,GAAO,GAAA;AAAA,QAC7B,CAAA,CAAA,MAAQ;AACN,UAAA,OAAO,IAAA;AAAA,QACT;AAAA,MACF,CAAA;AAAA,MACA,IAAA,EAAM,CAAC,KAAA,KAAU;AACf,QAAA,IAAI;AACF,UAAAC,YAAA,CAAUC,aAAQ,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AACjD,UAAAC,gBAAA,CAAc,SAAA,EAAW,GAAG,KAAK;AAAA,CAAA,EAAM,MAAM,CAAA;AAAA,QAC/C,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF,CAAA;AAAA,MACA,OAAO,MAAM;AACX,QAAA,IAAI;AACF,UAAAC,SAAA,CAAO,SAAA,EAAW,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,QACnC,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,KACF;AAAA,IACA,MAAA,EAAQ,CAAC,GAAA,KAAQ,IAAI,UAAU,GAAG,CAAA;AAAA,IAClC,UAAA,EAAY,MAAM,MAAA,CAAO;AAAA,GAC3B;AACF","file":"node.cjs","sourcesContent":["import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { WireEnv } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node host env — the wire on a plain Node (or Bun) process: the token\n// in a file instead of localStorage, the runtime's WHATWG WebSocket, and an\n// explicit url (a process has no location to derive one from). Wire-side,\n// this is the whole difference between a browser terminal and a TTY one.\n// Its own entry (`@niscorp/moss/client/node`) so node builtins never enter\n// a browser bundle.\n// ═══════════════════════════════════════════════════════════════\n\nexport const nodeEnv = (config: { url: string; tokenFile?: string }): WireEnv => {\n // Apps sharing a machine should namespace their own file; the default is\n // one moss session per user.\n const tokenFile = config.tokenFile ?? join(homedir(), '.moss', 'token');\n return {\n tokens: {\n load: () => {\n try {\n const raw = readFileSync(tokenFile, 'utf8').trim();\n return raw === '' ? null : raw;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n mkdirSync(dirname(tokenFile), { recursive: true });\n writeFileSync(tokenFile, `${token}\\n`, 'utf8');\n } catch {\n /* unwritable — the session lives for this process only */\n }\n },\n clear: () => {\n try {\n rmSync(tokenFile, { force: true });\n } catch {\n /* nothing stored, nothing to clear */\n }\n },\n },\n socket: (url) => new WebSocket(url),\n defaultUrl: () => config.url,\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/client/node.ts"],"names":["join","homedir","readFileSync","mkdirSync","dirname","writeFileSync","rmSync"],"mappings":";;;;;;;AAcO,IAAM,OAAA,GAAU,CAAC,MAAA,KAAyD;AAG/E,EAAA,MAAM,YAAY,MAAA,CAAO,SAAA,IAAaA,UAAKC,UAAA,EAAQ,EAAG,SAAS,OAAO,CAAA;AACtE,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ;AAAA,MACN,MAAM,MAAM;AACV,QAAA,IAAI;AACF,UAAA,MAAM,GAAA,GAAMC,eAAA,CAAa,SAAA,EAAW,MAAM,EAAE,IAAA,EAAK;AACjD,UAAA,OAAO,GAAA,KAAQ,KAAK,IAAA,GAAO,GAAA;AAAA,QAC7B,CAAA,CAAA,MAAQ;AACN,UAAA,OAAO,IAAA;AAAA,QACT;AAAA,MACF,CAAA;AAAA,MACA,IAAA,EAAM,CAAC,KAAA,KAAU;AACf,QAAA,IAAI;AACF,UAAAC,YAAA,CAAUC,aAAQ,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AACjD,UAAAC,gBAAA,CAAc,SAAA,EAAW,GAAG,KAAK;AAAA,CAAA,EAAM,MAAM,CAAA;AAAA,QAC/C,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF,CAAA;AAAA,MACA,OAAO,MAAM;AACX,QAAA,IAAI;AACF,UAAAC,SAAA,CAAO,SAAA,EAAW,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,QACnC,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,KACF;AAAA,IACA,MAAA,EAAQ,CAAC,EAAE,GAAA,EAAK,SAAQ,KAAM,IAAI,SAAA,CAAU,GAAA,EAAK,OAAO,CAAA;AAAA,IACxD,UAAA,EAAY,MAAM,MAAA,CAAO;AAAA,GAC3B;AACF","file":"node.cjs","sourcesContent":["import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { WireEnv } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node host env — the wire on a plain Node (or Bun) process: the token\n// in a file instead of localStorage, the runtime's WHATWG WebSocket, and an\n// explicit url (a process has no location to derive one from). Wire-side,\n// this is the whole difference between a browser terminal and a TTY one.\n// Its own entry (`@niscorp/moss/client/node`) so node builtins never enter\n// a browser bundle.\n// ═══════════════════════════════════════════════════════════════\n\nexport const nodeEnv = (config: { url: string; tokenFile?: string }): WireEnv => {\n // Apps sharing a machine should namespace their own file; the default is\n // one moss session per user.\n const tokenFile = config.tokenFile ?? join(homedir(), '.moss', 'token');\n return {\n tokens: {\n load: () => {\n try {\n const raw = readFileSync(tokenFile, 'utf8').trim();\n return raw === '' ? null : raw;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n mkdirSync(dirname(tokenFile), { recursive: true });\n writeFileSync(tokenFile, `${token}\\n`, 'utf8');\n } catch {\n /* unwritable — the session lives for this process only */\n }\n },\n clear: () => {\n try {\n rmSync(tokenFile, { force: true });\n } catch {\n /* nothing stored, nothing to clear */\n }\n },\n },\n socket: ({ url, offered }) => new WebSocket(url, offered),\n defaultUrl: () => config.url,\n };\n};\n"]}
@@ -30,7 +30,7 @@ var nodeEnv = (config) => {
30
30
  }
31
31
  }
32
32
  },
33
- socket: (url) => new WebSocket(url),
33
+ socket: ({ url, offered }) => new WebSocket(url, offered),
34
34
  defaultUrl: () => config.url
35
35
  };
36
36
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/node.ts"],"names":[],"mappings":";;;;;AAcO,IAAM,OAAA,GAAU,CAAC,MAAA,KAAyD;AAG/E,EAAA,MAAM,YAAY,MAAA,CAAO,SAAA,IAAa,KAAK,OAAA,EAAQ,EAAG,SAAS,OAAO,CAAA;AACtE,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ;AAAA,MACN,MAAM,MAAM;AACV,QAAA,IAAI;AACF,UAAA,MAAM,GAAA,GAAM,YAAA,CAAa,SAAA,EAAW,MAAM,EAAE,IAAA,EAAK;AACjD,UAAA,OAAO,GAAA,KAAQ,KAAK,IAAA,GAAO,GAAA;AAAA,QAC7B,CAAA,CAAA,MAAQ;AACN,UAAA,OAAO,IAAA;AAAA,QACT;AAAA,MACF,CAAA;AAAA,MACA,IAAA,EAAM,CAAC,KAAA,KAAU;AACf,QAAA,IAAI;AACF,UAAA,SAAA,CAAU,QAAQ,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AACjD,UAAA,aAAA,CAAc,SAAA,EAAW,GAAG,KAAK;AAAA,CAAA,EAAM,MAAM,CAAA;AAAA,QAC/C,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF,CAAA;AAAA,MACA,OAAO,MAAM;AACX,QAAA,IAAI;AACF,UAAA,MAAA,CAAO,SAAA,EAAW,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,QACnC,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,KACF;AAAA,IACA,MAAA,EAAQ,CAAC,GAAA,KAAQ,IAAI,UAAU,GAAG,CAAA;AAAA,IAClC,UAAA,EAAY,MAAM,MAAA,CAAO;AAAA,GAC3B;AACF","file":"node.js","sourcesContent":["import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { WireEnv } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node host env — the wire on a plain Node (or Bun) process: the token\n// in a file instead of localStorage, the runtime's WHATWG WebSocket, and an\n// explicit url (a process has no location to derive one from). Wire-side,\n// this is the whole difference between a browser terminal and a TTY one.\n// Its own entry (`@niscorp/moss/client/node`) so node builtins never enter\n// a browser bundle.\n// ═══════════════════════════════════════════════════════════════\n\nexport const nodeEnv = (config: { url: string; tokenFile?: string }): WireEnv => {\n // Apps sharing a machine should namespace their own file; the default is\n // one moss session per user.\n const tokenFile = config.tokenFile ?? join(homedir(), '.moss', 'token');\n return {\n tokens: {\n load: () => {\n try {\n const raw = readFileSync(tokenFile, 'utf8').trim();\n return raw === '' ? null : raw;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n mkdirSync(dirname(tokenFile), { recursive: true });\n writeFileSync(tokenFile, `${token}\\n`, 'utf8');\n } catch {\n /* unwritable — the session lives for this process only */\n }\n },\n clear: () => {\n try {\n rmSync(tokenFile, { force: true });\n } catch {\n /* nothing stored, nothing to clear */\n }\n },\n },\n socket: (url) => new WebSocket(url),\n defaultUrl: () => config.url,\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/client/node.ts"],"names":[],"mappings":";;;;;AAcO,IAAM,OAAA,GAAU,CAAC,MAAA,KAAyD;AAG/E,EAAA,MAAM,YAAY,MAAA,CAAO,SAAA,IAAa,KAAK,OAAA,EAAQ,EAAG,SAAS,OAAO,CAAA;AACtE,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ;AAAA,MACN,MAAM,MAAM;AACV,QAAA,IAAI;AACF,UAAA,MAAM,GAAA,GAAM,YAAA,CAAa,SAAA,EAAW,MAAM,EAAE,IAAA,EAAK;AACjD,UAAA,OAAO,GAAA,KAAQ,KAAK,IAAA,GAAO,GAAA;AAAA,QAC7B,CAAA,CAAA,MAAQ;AACN,UAAA,OAAO,IAAA;AAAA,QACT;AAAA,MACF,CAAA;AAAA,MACA,IAAA,EAAM,CAAC,KAAA,KAAU;AACf,QAAA,IAAI;AACF,UAAA,SAAA,CAAU,QAAQ,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AACjD,UAAA,aAAA,CAAc,SAAA,EAAW,GAAG,KAAK;AAAA,CAAA,EAAM,MAAM,CAAA;AAAA,QAC/C,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF,CAAA;AAAA,MACA,OAAO,MAAM;AACX,QAAA,IAAI;AACF,UAAA,MAAA,CAAO,SAAA,EAAW,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,QACnC,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,KACF;AAAA,IACA,MAAA,EAAQ,CAAC,EAAE,GAAA,EAAK,SAAQ,KAAM,IAAI,SAAA,CAAU,GAAA,EAAK,OAAO,CAAA;AAAA,IACxD,UAAA,EAAY,MAAM,MAAA,CAAO;AAAA,GAC3B;AACF","file":"node.js","sourcesContent":["import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { WireEnv } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The Node host env — the wire on a plain Node (or Bun) process: the token\n// in a file instead of localStorage, the runtime's WHATWG WebSocket, and an\n// explicit url (a process has no location to derive one from). Wire-side,\n// this is the whole difference between a browser terminal and a TTY one.\n// Its own entry (`@niscorp/moss/client/node`) so node builtins never enter\n// a browser bundle.\n// ═══════════════════════════════════════════════════════════════\n\nexport const nodeEnv = (config: { url: string; tokenFile?: string }): WireEnv => {\n // Apps sharing a machine should namespace their own file; the default is\n // one moss session per user.\n const tokenFile = config.tokenFile ?? join(homedir(), '.moss', 'token');\n return {\n tokens: {\n load: () => {\n try {\n const raw = readFileSync(tokenFile, 'utf8').trim();\n return raw === '' ? null : raw;\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n mkdirSync(dirname(tokenFile), { recursive: true });\n writeFileSync(tokenFile, `${token}\\n`, 'utf8');\n } catch {\n /* unwritable — the session lives for this process only */\n }\n },\n clear: () => {\n try {\n rmSync(tokenFile, { force: true });\n } catch {\n /* nothing stored, nothing to clear */\n }\n },\n },\n socket: ({ url, offered }) => new WebSocket(url, offered),\n defaultUrl: () => config.url,\n };\n};\n"]}
package/dist/client.cjs CHANGED
@@ -3,8 +3,24 @@
3
3
  require('@niscorp/nova');
4
4
 
5
5
  // src/socket.ts
6
- var PROTOCOL = 1;
7
- var PROTOCOL_MIN = 1;
6
+
7
+ // src/session-cookie.ts
8
+ var DEFAULT_TOKEN_KEY = "nisc.token";
9
+ var nameOf = (key, port) => `${key}${port === "" ? "" : `.${port}`}`;
10
+ var heldCookieName = (key = DEFAULT_TOKEN_KEY, port = "") => encodeURIComponent(`${nameOf(key, port)}.held`);
11
+
12
+ // src/socket.ts
13
+ var PROTOCOL = 2;
14
+ var PROTOCOL_MIN = 2;
15
+ var SUBPROTOCOL = "nisc";
16
+ var TOKEN_OFFER = "nisc.token.";
17
+ var SEALED_OFFER = "nisc.sealed.";
18
+ var offerToken = (token, sealed = null) => {
19
+ const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];
20
+ if (token === null) return offer;
21
+ const bytes = String.fromCharCode(...new TextEncoder().encode(token));
22
+ return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`];
23
+ };
8
24
  var CLOSE_INVALID_TOKEN = 4401;
9
25
  var CLOSE_SIGNED_OUT = 4403;
10
26
  var CLOSE_PROTOCOL_MISMATCH = 4426;
@@ -59,21 +75,11 @@ var readDocumentSnapshot = (doc = document) => {
59
75
  var EMPTY = { frame: [], trees: /* @__PURE__ */ new Map() };
60
76
  var browserEnv = (config = {}) => {
61
77
  const tokenKey = config.tokenKey ?? "nisc.token";
62
- const mirror = (token) => {
63
- if (config.cookie !== true) return;
64
- try {
65
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
66
- document.cookie = token === null ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}` : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;
67
- } catch {
68
- }
69
- };
70
78
  return {
71
79
  tokens: {
72
80
  load: () => {
73
81
  try {
74
- const token = window.localStorage.getItem(tokenKey);
75
- mirror(token);
76
- return token;
82
+ return window.localStorage.getItem(tokenKey);
77
83
  } catch {
78
84
  return null;
79
85
  }
@@ -83,17 +89,27 @@ var browserEnv = (config = {}) => {
83
89
  window.localStorage.setItem(tokenKey, token);
84
90
  } catch {
85
91
  }
86
- mirror(token);
87
92
  },
88
93
  clear: () => {
89
94
  try {
90
95
  window.localStorage.removeItem(tokenKey);
91
96
  } catch {
92
97
  }
93
- mirror(null);
94
- }
98
+ try {
99
+ document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
100
+ } catch {
101
+ }
102
+ },
103
+ held: () => {
104
+ try {
105
+ return document.cookie.split("; ").includes(`${heldCookieName(tokenKey, window.location.port)}=1`);
106
+ } catch {
107
+ return false;
108
+ }
109
+ },
110
+ ...config.tokenKey !== void 0 ? { key: tokenKey } : {}
95
111
  },
96
- socket: (url) => new WebSocket(url),
112
+ socket: ({ url, offered }) => new WebSocket(url, offered),
97
113
  defaultUrl: () => {
98
114
  const scheme = window.location.protocol === "https:" ? "wss" : "ws";
99
115
  return `${scheme}://${window.location.host}/socket`;
@@ -103,12 +119,15 @@ var browserEnv = (config = {}) => {
103
119
  var createWire = (config = {}) => {
104
120
  const env = config.env ?? browserEnv();
105
121
  let token = env.tokens.load();
106
- const initial = config.initial !== void 0 && config.initial.principal === (token !== null) ? config.initial : void 0;
122
+ const initial = config.initial !== void 0 && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : void 0;
107
123
  let snapshot = initial === void 0 ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };
108
124
  let seed = initial?.seed;
109
125
  const path = config.path ?? config.initial?.path;
110
126
  let status = "connecting";
111
127
  let incompatible = false;
128
+ let leaving = false;
129
+ let sealed = null;
130
+ let unsealed = false;
112
131
  let socket = null;
113
132
  let retry;
114
133
  let attempts = 0;
@@ -133,14 +152,15 @@ var createWire = (config = {}) => {
133
152
  if (disposed) return;
134
153
  setStatus("connecting");
135
154
  bases.clear();
136
- const params = [];
137
- if (token !== null) params.push(`token=${encodeURIComponent(token)}`);
138
- params.push(`protocol=${PROTOCOL}`);
155
+ const params = [`protocol=${PROTOCOL}`];
156
+ if (env.tokens.key !== void 0) params.push(`key=${encodeURIComponent(env.tokens.key)}`);
157
+ if (leaving) params.push("leave=1");
158
+ if (env.tokens.held !== void 0 && !unsealed) params.push("sealed=1");
139
159
  if (config.delta === true) params.push("delta=1");
140
160
  if (seed !== void 0) params.push(`seed=${encodeURIComponent(seed)}`);
141
161
  seed = void 0;
142
162
  if (path !== void 0) params.push(`path=${encodeURIComponent(path)}`);
143
- const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join("&")}` : ""}`);
163
+ const ws = env.socket({ url: `${url()}?${params.join("&")}`, offered: offerToken(token, sealed) });
144
164
  socket = ws;
145
165
  ws.onopen = () => {
146
166
  attempts = 0;
@@ -176,13 +196,25 @@ var createWire = (config = {}) => {
176
196
  publishSnapshot({ ...snapshot, frame: data.tree });
177
197
  } else if (data.type === "session" && typeof data.token === "string") {
178
198
  become(data.token);
199
+ } else if (data.type === "session" && typeof data.sealed === "string") {
200
+ become(null, data.sealed);
179
201
  } else if (data.type === "error") {
202
+ if (data.code === "seal_not_kept") unsealed = true;
180
203
  console.warn(`[moss/wire] server error${data.code !== void 0 ? ` (${data.code})` : ""}: ${data.message ?? ""}`);
181
204
  } else if (data.type === "hello" && (data.protocol ?? 1) < PROTOCOL_MIN) {
182
205
  console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}\u2013${PROTOCOL}. The server has not been updated yet.`);
183
206
  incompatible = true;
184
207
  ws.close();
185
- } else if (data.type !== "hello" && data.type !== "catalog") {
208
+ } else if (data.type === "hello") {
209
+ leaving = false;
210
+ sealed = null;
211
+ if (token !== null && env.tokens.held !== void 0) {
212
+ if (env.tokens.held()) {
213
+ env.tokens.clear();
214
+ token = null;
215
+ } else env.tokens.save(token);
216
+ }
217
+ } else if (data.type !== "catalog") {
186
218
  console.warn(`[moss/wire] unhandled server message: ${data.type}`);
187
219
  }
188
220
  };
@@ -194,6 +226,7 @@ var createWire = (config = {}) => {
194
226
  }
195
227
  setStatus("closed");
196
228
  if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {
229
+ leaving = e.code === CLOSE_SIGNED_OUT;
197
230
  become(null);
198
231
  return;
199
232
  }
@@ -207,9 +240,10 @@ var createWire = (config = {}) => {
207
240
  const delay = ceiling / 2 + Math.random() * (ceiling / 2);
208
241
  retry = setTimeout(connect, delay);
209
242
  };
210
- const become = (next) => {
211
- if (next === null) env.tokens.clear();
212
- else env.tokens.save(next);
243
+ const become = (next, handedSealed = null) => {
244
+ sealed = handedSealed;
245
+ if (handedSealed !== null) ; else if (next === null) env.tokens.clear();
246
+ else if (env.tokens.held === void 0) env.tokens.save(next);
213
247
  token = next;
214
248
  clearTimeout(retry);
215
249
  attempts = 0;