@niscorp/moss 0.1.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.
- package/DESIGN.md +592 -0
- package/DOCS.md +943 -0
- package/LICENSE +202 -0
- package/README.md +155 -0
- package/dist/chunk-2AHJ6VDR.js +3314 -0
- package/dist/chunk-2AHJ6VDR.js.map +1 -0
- package/dist/chunk-EMRDIZLY.js +99 -0
- package/dist/chunk-EMRDIZLY.js.map +1 -0
- package/dist/chunk-HF6IGQ74.js +3342 -0
- package/dist/chunk-HF6IGQ74.js.map +1 -0
- package/dist/chunk-J72N3EMJ.js +238 -0
- package/dist/chunk-J72N3EMJ.js.map +1 -0
- package/dist/chunk-SK4PDGEE.js +55 -0
- package/dist/chunk-SK4PDGEE.js.map +1 -0
- package/dist/chunk-ZOEUEMDX.js +251 -0
- package/dist/chunk-ZOEUEMDX.js.map +1 -0
- package/dist/client/node.cjs +42 -0
- package/dist/client/node.cjs.map +1 -0
- package/dist/client/node.d.cts +9 -0
- package/dist/client/node.d.ts +9 -0
- package/dist/client/node.js +40 -0
- package/dist/client/node.js.map +1 -0
- package/dist/client.cjs +275 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +52 -0
- package/dist/client.d.ts +52 -0
- package/dist/client.js +4 -0
- package/dist/client.js.map +1 -0
- package/dist/document-BEn2zXah.d.cts +993 -0
- package/dist/document-BEn2zXah.d.ts +993 -0
- package/dist/index.cjs +3716 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +104 -0
- package/dist/index.d.ts +104 -0
- package/dist/index.js +96 -0
- package/dist/index.js.map +1 -0
- package/dist/node.cjs +3309 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +28 -0
- package/dist/node.d.ts +28 -0
- package/dist/node.js +64 -0
- package/dist/node.js.map +1 -0
- package/dist/slots-Do9ScG7v.d.cts +37 -0
- package/dist/slots-Do9ScG7v.d.ts +37 -0
- package/dist/terminal/dom/index.cjs +34 -0
- package/dist/terminal/dom/index.cjs.map +1 -0
- package/dist/terminal/dom/index.d.cts +11 -0
- package/dist/terminal/dom/index.d.ts +11 -0
- package/dist/terminal/dom/index.js +32 -0
- package/dist/terminal/dom/index.js.map +1 -0
- package/dist/terminal/dom/server.cjs +16 -0
- package/dist/terminal/dom/server.cjs.map +1 -0
- package/dist/terminal/dom/server.d.cts +14 -0
- package/dist/terminal/dom/server.d.ts +14 -0
- package/dist/terminal/dom/server.js +14 -0
- package/dist/terminal/dom/server.js.map +1 -0
- package/dist/terminal/index.cjs +346 -0
- package/dist/terminal/index.cjs.map +1 -0
- package/dist/terminal/index.d.cts +32 -0
- package/dist/terminal/index.d.ts +32 -0
- package/dist/terminal/index.js +100 -0
- package/dist/terminal/index.js.map +1 -0
- package/dist/terminal/ink/index.d.ts +33 -0
- package/dist/terminal/ink/index.js +189 -0
- package/dist/terminal/ink/index.js.map +1 -0
- package/dist/terminal/react/index.cjs +87 -0
- package/dist/terminal/react/index.cjs.map +1 -0
- package/dist/terminal/react/index.d.cts +15 -0
- package/dist/terminal/react/index.d.ts +15 -0
- package/dist/terminal/react/index.js +35 -0
- package/dist/terminal/react/index.js.map +1 -0
- package/dist/terminal/react/server.cjs +79 -0
- package/dist/terminal/react/server.cjs.map +1 -0
- package/dist/terminal/react/server.d.cts +16 -0
- package/dist/terminal/react/server.d.ts +16 -0
- package/dist/terminal/react/server.js +28 -0
- package/dist/terminal/react/server.js.map +1 -0
- package/dist/terminal/tty/index.cjs +201 -0
- package/dist/terminal/tty/index.cjs.map +1 -0
- package/dist/terminal/tty/index.d.cts +18 -0
- package/dist/terminal/tty/index.d.ts +18 -0
- package/dist/terminal/tty/index.js +199 -0
- package/dist/terminal/tty/index.js.map +1 -0
- package/dist/terminal/vue/index.cjs +104 -0
- package/dist/terminal/vue/index.cjs.map +1 -0
- package/dist/terminal/vue/index.d.cts +23 -0
- package/dist/terminal/vue/index.d.ts +23 -0
- package/dist/terminal/vue/index.js +3 -0
- package/dist/terminal/vue/index.js.map +1 -0
- package/dist/terminal/vue/server.cjs +88 -0
- package/dist/terminal/vue/server.cjs.map +1 -0
- package/dist/terminal/vue/server.d.cts +18 -0
- package/dist/terminal/vue/server.d.ts +18 -0
- package/dist/terminal/vue/server.js +21 -0
- package/dist/terminal/vue/server.js.map +1 -0
- package/package.json +213 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/telemetry.ts","../src/socket.ts","../src/delta.ts"],"names":[],"mappings":";;;AA0DO,IAAM,YAAY,CAAC,SAAA,KACxB,cAAc,MAAA,GACV,MAAA,GACA,CAAC,IAAA,KAAS;AACR,EAAA,IAAI;AACF,IAAA,SAAA,CAAU,KAAK,IAAI,CAAA;AAAA,EACrB,SAAS,GAAA,EAAK;AACZ,IAAA,OAAA,CAAQ,KAAA,CAAM,oBAAoB,GAAG,CAAA;AAAA,EACvC;AACF;AAON,IAAM,YAAA,GAAe,MAAe,OAAO,WAAA,KAAgB,cAAc,WAAA,CAAY,GAAA,EAAI,GAAI,IAAA,CAAK,GAAA,EAAI;AAE/F,IAAM,YAAY,MAAiB;AACxC,EAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,GAAA,EAAI,GAAI,GAAA;AACnC,EAAA,MAAM,KAAK,YAAA,EAAa;AACxB,EAAA,OAAO,EAAE,eAAe,WAAA,EAAa,MAAM,iBAAiB,YAAA,EAAa,GAAI,MAAM,GAAA,EAAI;AACzF;ACmBO,IAAM,QAAA,GAAW;AACjB,IAAM,YAAA,GAAe;AAGrB,IAAM,mBAAA,GAAsB;AAI5B,IAAM,gBAAA,GAAmB;AAMzB,IAAM,kBAAA,GAAqB;AAK3B,IAAM,uBAAA,GAA0B;AAwChC,IAAM,wBAAwB,EAAA,GAAK;AAU1C,IAAM,KAAA,GAAQ,CAAC,IAAA,KAAiD;AAC9D,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,GAAiB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AACtC,I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,GAAA,IAAO,GAAG,CAAC,CAAA;AACX,MAAA;AAAA,IACF;AACA,IAAA,MAAM,GAAG,MAAA,EAAQ,MAAM,CAAA,GAAI,EAAA;AAC3B,IAAA,IAAI,SAAS,CAAA,IAAK,MAAA,GAAS,KAAK,MAAA,GAAS,MAAA,GAAS,KAAK,MAAA,EAAQ;AAC7D,MAAA,MAAM,IAAI,MAAM,CAAA,iBAAA,EAAoB,MAAM,IAAI,MAAM,CAAA,sBAAA,EAAyB,IAAA,CAAK,MAAM,CAAA,CAAE,CAAA;AAAA,IAC5F;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,MAAA,GAAS,MAAM,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,GAAA;AACT;AAUO,IAAM,SAAA,GAAY,CAAC,IAAA,KAAyB;AACjD,EAAA,IAAI,IAAA,GAAO,UAAA;AACX,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,MAAA,EAAQ,KAAK,CAAA,EAAG;AACvC,IAAA,IAAA,IAAQ,IAAA,CAAK,WAAW,CAAC,CAAA;AACzB,IAAA,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,QAAU,CAAA;AAAA,EACnC;AACA,EAAA,OAAO,IAAA,KAAS,CAAA;AAClB","file":"chunk-ZOEUEMDX.js","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// Telemetry — moss's one observability surface, and the SOLE owner of the\n// span shape. Every service a Midas deployment runs is a moss process; moss\n// is the choke point every engine fact passes through, so moss is where a\n// deployment learns how long a vex execution took, which fingerprint is slow,\n// how often a policy refuses, how many shells are resident. Instrumenting here\n// means a service written tomorrow is observed the day it boots, with no code\n// in the service — the same argument the engine boundary makes for queries.\n//\n// The sink is a deployment decision, not an application one, so the hook lives\n// on the runtime (runtime.ts) beside the other operational knobs. Unset, no\n// span is ever built: every emission site guards on `emit !== undefined`, and\n// an optional call short-circuits its argument, so a hot path with no sink\n// allocates nothing.\n//\n// STRUCTURAL FACTS ONLY. A span carries identifiers and measurements — a\n// fingerprint, a duration, a status — never a payload, a context value, a row,\n// or a principal beyond presence (`hasPrincipal`). The stream must be safe to\n// ship to a third-party backend without a privacy review per span. moss builds\n// every span here from what a seam reports; a seam reports facts, moss decides\n// what of them is safe to name.\n// ═══════════════════════════════════════════════════════════════\n\n// The span, shaped after the OpenTelemetry data model — not the SDK, just the\n// shape, so any OTLP backend ingests a JSON mapping of it with no translation.\nexport type TelemetrySpan = {\n // 'vex.execute' | 'fn.call' | 'shell.build' | 'socket.upgrade' |\n // 'socket.close' | 'integration.call' | …\n name: string;\n // Epoch nanoseconds, millisecond-anchored with a sub-millisecond monotonic\n // span between them. JS numbers cannot hold epoch nanos exactly — the low\n // ~8 bits are lossy — which is far below the millisecond scale of what is\n // measured here, and an exporter re-quantises anyway.\n startUnixNano: number;\n endUnixNano: number;\n // 'refused' is a policy/intake NO — a normal outcome, distinct from a fault.\n status: 'ok' | 'error' | 'refused';\n // Identifiers and measurements. Never a payload, name, address, or context\n // value; a principal appears only as `hasPrincipal`.\n attributes: Record<string, string | number | boolean>;\n // Trace stitching — unused in v1 (no cross-process traceparent yet), carried\n // so a sampler and a propagator can arrive without a shape change.\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n};\n\n// The runtime hook. `emit` is fire-and-forget: never awaited, and wrapped\n// (`emitterOf`) so a slow or throwing sink costs the request nothing.\nexport type Telemetry = {\n emit: (span: TelemetrySpan) => void;\n};\n\nexport type Emit = (span: TelemetrySpan) => void;\n\n// The one safe emitter every seam derives. `undefined` when no sink is\n// configured — the signal each site guards on to build no span at all. When a\n// sink is present, its throw is contained here, never the caller's.\nexport const emitterOf = (telemetry: Telemetry | undefined): Emit | undefined =>\n telemetry === undefined\n ? undefined\n : (span) => {\n try {\n telemetry.emit(span);\n } catch (err) {\n console.error('[moss:telemetry]', err);\n }\n };\n\n// A span's clock: the start stamped once, elapsed read on demand — so one clock\n// serves both a short handshake span and a whole-connection span from the same\n// origin. Millisecond-anchored start, sub-millisecond monotonic elapsed.\nexport type SpanClock = { startUnixNano: number; endUnixNano: () => number };\n\nconst elapsedClock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nexport const spanClock = (): SpanClock => {\n const startUnixNano = Date.now() * 1e6;\n const t0 = elapsedClock();\n return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };\n};\n","import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions; everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n | { type: 'session'; token: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N`, beside the\n// token — known before the first frame is sent); one that says nothing speaks 1,\n// which is every terminal built before the question existed. Outside the range\n// the connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\nexport const PROTOCOL = 1;\nexport const PROTOCOL_MIN = 1;\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const token = params.get('token');\n let principal: string | null = null;\n if (token !== null && token !== '') {\n principal = await ctx.session(token);\n if (principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var os = require('os');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
|
|
7
|
+
// src/client/node.ts
|
|
8
|
+
var nodeEnv = (config) => {
|
|
9
|
+
const tokenFile = config.tokenFile ?? path.join(os.homedir(), ".moss", "token");
|
|
10
|
+
return {
|
|
11
|
+
tokens: {
|
|
12
|
+
load: () => {
|
|
13
|
+
try {
|
|
14
|
+
const raw = fs.readFileSync(tokenFile, "utf8").trim();
|
|
15
|
+
return raw === "" ? null : raw;
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
save: (token) => {
|
|
21
|
+
try {
|
|
22
|
+
fs.mkdirSync(path.dirname(tokenFile), { recursive: true });
|
|
23
|
+
fs.writeFileSync(tokenFile, `${token}
|
|
24
|
+
`, "utf8");
|
|
25
|
+
} catch {
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
clear: () => {
|
|
29
|
+
try {
|
|
30
|
+
fs.rmSync(tokenFile, { force: true });
|
|
31
|
+
} catch {
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
socket: (url) => new WebSocket(url),
|
|
36
|
+
defaultUrl: () => config.url
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
exports.nodeEnv = nodeEnv;
|
|
41
|
+
//# sourceMappingURL=node.cjs.map
|
|
42
|
+
//# sourceMappingURL=node.cjs.map
|
|
@@ -0,0 +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"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
|
|
2
|
+
import { homedir } from 'os';
|
|
3
|
+
import { join, dirname } from 'path';
|
|
4
|
+
|
|
5
|
+
// src/client/node.ts
|
|
6
|
+
var nodeEnv = (config) => {
|
|
7
|
+
const tokenFile = config.tokenFile ?? join(homedir(), ".moss", "token");
|
|
8
|
+
return {
|
|
9
|
+
tokens: {
|
|
10
|
+
load: () => {
|
|
11
|
+
try {
|
|
12
|
+
const raw = readFileSync(tokenFile, "utf8").trim();
|
|
13
|
+
return raw === "" ? null : raw;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
save: (token) => {
|
|
19
|
+
try {
|
|
20
|
+
mkdirSync(dirname(tokenFile), { recursive: true });
|
|
21
|
+
writeFileSync(tokenFile, `${token}
|
|
22
|
+
`, "utf8");
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
clear: () => {
|
|
27
|
+
try {
|
|
28
|
+
rmSync(tokenFile, { force: true });
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
socket: (url) => new WebSocket(url),
|
|
34
|
+
defaultUrl: () => config.url
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export { nodeEnv };
|
|
39
|
+
//# sourceMappingURL=node.js.map
|
|
40
|
+
//# sourceMappingURL=node.js.map
|
|
@@ -0,0 +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"]}
|
package/dist/client.cjs
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
require('@niscorp/nova');
|
|
4
|
+
|
|
5
|
+
// src/socket.ts
|
|
6
|
+
var PROTOCOL = 1;
|
|
7
|
+
var PROTOCOL_MIN = 1;
|
|
8
|
+
var CLOSE_INVALID_TOKEN = 4401;
|
|
9
|
+
var CLOSE_SIGNED_OUT = 4403;
|
|
10
|
+
var CLOSE_PROTOCOL_MISMATCH = 4426;
|
|
11
|
+
|
|
12
|
+
// src/delta.ts
|
|
13
|
+
var applyDelta = (base, ops) => {
|
|
14
|
+
let out = "";
|
|
15
|
+
for (const op of ops) {
|
|
16
|
+
if (op[0] === 1) {
|
|
17
|
+
out += op[1];
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const [, offset, length] = op;
|
|
21
|
+
if (offset < 0 || length < 0 || offset + length > base.length) {
|
|
22
|
+
throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);
|
|
23
|
+
}
|
|
24
|
+
out += base.slice(offset, offset + length);
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
};
|
|
28
|
+
var frameHash = (text) => {
|
|
29
|
+
let hash = 2166136261;
|
|
30
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
31
|
+
hash ^= text.charCodeAt(i);
|
|
32
|
+
hash = Math.imul(hash, 16777619);
|
|
33
|
+
}
|
|
34
|
+
return hash >>> 0;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/client/index.ts
|
|
38
|
+
var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
|
|
39
|
+
var readDocumentSnapshot = (doc = document) => {
|
|
40
|
+
try {
|
|
41
|
+
const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;
|
|
42
|
+
if (text === void 0 || text === null || text === "") return void 0;
|
|
43
|
+
const parsed = JSON.parse(text);
|
|
44
|
+
if (parsed === null || typeof parsed !== "object") return void 0;
|
|
45
|
+
const { frame, trees, seed, principal, path, live } = parsed;
|
|
46
|
+
if (!Array.isArray(frame) || trees === null || typeof trees !== "object" || typeof principal !== "boolean") return void 0;
|
|
47
|
+
return {
|
|
48
|
+
frame,
|
|
49
|
+
trees,
|
|
50
|
+
principal,
|
|
51
|
+
...typeof seed === "string" ? { seed } : {},
|
|
52
|
+
...typeof path === "string" ? { path } : {},
|
|
53
|
+
...typeof live === "boolean" ? { live } : {}
|
|
54
|
+
};
|
|
55
|
+
} catch {
|
|
56
|
+
return void 0;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
var EMPTY = { frame: [], trees: /* @__PURE__ */ new Map() };
|
|
60
|
+
var browserEnv = (config = {}) => {
|
|
61
|
+
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
|
+
return {
|
|
71
|
+
tokens: {
|
|
72
|
+
load: () => {
|
|
73
|
+
try {
|
|
74
|
+
const token = window.localStorage.getItem(tokenKey);
|
|
75
|
+
mirror(token);
|
|
76
|
+
return token;
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
save: (token) => {
|
|
82
|
+
try {
|
|
83
|
+
window.localStorage.setItem(tokenKey, token);
|
|
84
|
+
} catch {
|
|
85
|
+
}
|
|
86
|
+
mirror(token);
|
|
87
|
+
},
|
|
88
|
+
clear: () => {
|
|
89
|
+
try {
|
|
90
|
+
window.localStorage.removeItem(tokenKey);
|
|
91
|
+
} catch {
|
|
92
|
+
}
|
|
93
|
+
mirror(null);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
socket: (url) => new WebSocket(url),
|
|
97
|
+
defaultUrl: () => {
|
|
98
|
+
const scheme = window.location.protocol === "https:" ? "wss" : "ws";
|
|
99
|
+
return `${scheme}://${window.location.host}/socket`;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
var createWire = (config = {}) => {
|
|
104
|
+
const env = config.env ?? browserEnv();
|
|
105
|
+
let token = env.tokens.load();
|
|
106
|
+
const initial = config.initial !== void 0 && config.initial.principal === (token !== null) ? config.initial : void 0;
|
|
107
|
+
let snapshot = initial === void 0 ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };
|
|
108
|
+
let seed = initial?.seed;
|
|
109
|
+
const path = config.path ?? config.initial?.path;
|
|
110
|
+
let status = "connecting";
|
|
111
|
+
let incompatible = false;
|
|
112
|
+
let socket = null;
|
|
113
|
+
let retry;
|
|
114
|
+
let attempts = 0;
|
|
115
|
+
let disposed = false;
|
|
116
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
117
|
+
const publishSnapshot = (next) => {
|
|
118
|
+
snapshot = next;
|
|
119
|
+
for (const listener of listeners) listener();
|
|
120
|
+
};
|
|
121
|
+
const setStatus = (next) => {
|
|
122
|
+
if (status === next) return;
|
|
123
|
+
status = next;
|
|
124
|
+
for (const listener of listeners) listener();
|
|
125
|
+
};
|
|
126
|
+
const url = () => config.url ?? env.defaultUrl();
|
|
127
|
+
const send = (message) => {
|
|
128
|
+
if (socket === null || status !== "open") return;
|
|
129
|
+
socket.send(JSON.stringify(message));
|
|
130
|
+
};
|
|
131
|
+
const bases = /* @__PURE__ */ new Map();
|
|
132
|
+
const connect = () => {
|
|
133
|
+
if (disposed) return;
|
|
134
|
+
setStatus("connecting");
|
|
135
|
+
bases.clear();
|
|
136
|
+
const params = [];
|
|
137
|
+
if (token !== null) params.push(`token=${encodeURIComponent(token)}`);
|
|
138
|
+
params.push(`protocol=${PROTOCOL}`);
|
|
139
|
+
if (config.delta === true) params.push("delta=1");
|
|
140
|
+
if (seed !== void 0) params.push(`seed=${encodeURIComponent(seed)}`);
|
|
141
|
+
seed = void 0;
|
|
142
|
+
if (path !== void 0) params.push(`path=${encodeURIComponent(path)}`);
|
|
143
|
+
const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join("&")}` : ""}`);
|
|
144
|
+
socket = ws;
|
|
145
|
+
ws.onopen = () => {
|
|
146
|
+
attempts = 0;
|
|
147
|
+
setStatus("open");
|
|
148
|
+
};
|
|
149
|
+
ws.onmessage = (e) => {
|
|
150
|
+
const text = String(e.data);
|
|
151
|
+
const data = JSON.parse(text);
|
|
152
|
+
if (data.type === "render" && data.canvas !== void 0 && data.tree !== void 0) {
|
|
153
|
+
if (config.delta === true) bases.set(data.canvas, text);
|
|
154
|
+
publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });
|
|
155
|
+
} else if (data.type === "render-delta" && data.canvas !== void 0 && data.ops !== void 0 && data.hash !== void 0) {
|
|
156
|
+
const base = bases.get(data.canvas);
|
|
157
|
+
let rebuilt = null;
|
|
158
|
+
if (base !== void 0) {
|
|
159
|
+
try {
|
|
160
|
+
const candidate = applyDelta(base, data.ops);
|
|
161
|
+
rebuilt = frameHash(candidate) === data.hash ? candidate : null;
|
|
162
|
+
} catch {
|
|
163
|
+
rebuilt = null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (rebuilt === null) {
|
|
167
|
+
console.warn(`[moss/wire] canvas "${data.canvas}": delta did not rebuild the server's frame \u2014 resyncing.`);
|
|
168
|
+
bases.delete(data.canvas);
|
|
169
|
+
send({ type: "resync" });
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const frame = JSON.parse(rebuilt);
|
|
173
|
+
bases.set(data.canvas, rebuilt);
|
|
174
|
+
publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });
|
|
175
|
+
} else if (data.type === "frame" && data.tree !== void 0) {
|
|
176
|
+
publishSnapshot({ ...snapshot, frame: data.tree });
|
|
177
|
+
} else if (data.type === "session" && typeof data.token === "string") {
|
|
178
|
+
become(data.token);
|
|
179
|
+
} else if (data.type === "error") {
|
|
180
|
+
console.warn(`[moss/wire] server error${data.code !== void 0 ? ` (${data.code})` : ""}: ${data.message ?? ""}`);
|
|
181
|
+
} else if (data.type === "hello" && (data.protocol ?? 1) < PROTOCOL_MIN) {
|
|
182
|
+
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
|
+
incompatible = true;
|
|
184
|
+
ws.close();
|
|
185
|
+
} else if (data.type !== "hello" && data.type !== "catalog") {
|
|
186
|
+
console.warn(`[moss/wire] unhandled server message: ${data.type}`);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
ws.onclose = (e) => {
|
|
190
|
+
if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {
|
|
191
|
+
incompatible = true;
|
|
192
|
+
setStatus("incompatible");
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
setStatus("closed");
|
|
196
|
+
if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {
|
|
197
|
+
become(null);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (!disposed) scheduleReconnect();
|
|
201
|
+
};
|
|
202
|
+
};
|
|
203
|
+
const RECONNECT_CAP_MS = 3e4;
|
|
204
|
+
const scheduleReconnect = () => {
|
|
205
|
+
const ceiling = Math.min(RECONNECT_CAP_MS, 1e3 * 2 ** attempts);
|
|
206
|
+
attempts += 1;
|
|
207
|
+
const delay = ceiling / 2 + Math.random() * (ceiling / 2);
|
|
208
|
+
retry = setTimeout(connect, delay);
|
|
209
|
+
};
|
|
210
|
+
const become = (next) => {
|
|
211
|
+
if (next === null) env.tokens.clear();
|
|
212
|
+
else env.tokens.save(next);
|
|
213
|
+
token = next;
|
|
214
|
+
clearTimeout(retry);
|
|
215
|
+
attempts = 0;
|
|
216
|
+
publishSnapshot(EMPTY);
|
|
217
|
+
const old = socket;
|
|
218
|
+
socket = null;
|
|
219
|
+
if (old !== null) {
|
|
220
|
+
old.onclose = null;
|
|
221
|
+
old.close();
|
|
222
|
+
}
|
|
223
|
+
connect();
|
|
224
|
+
};
|
|
225
|
+
if (initial?.live === false) status = "static";
|
|
226
|
+
else connect();
|
|
227
|
+
return {
|
|
228
|
+
subscribe: (listener) => {
|
|
229
|
+
listeners.add(listener);
|
|
230
|
+
return () => listeners.delete(listener);
|
|
231
|
+
},
|
|
232
|
+
snapshot: () => snapshot,
|
|
233
|
+
status: () => status,
|
|
234
|
+
dispatch: (canvasId, event) => send({ type: "event", canvas: canvasId, event }),
|
|
235
|
+
publish: (channel, payload) => send(payload === void 0 ? { type: "publish", channel } : { type: "publish", channel, payload }),
|
|
236
|
+
// Only on an open socket, and deliberately not queued: a back pressed while
|
|
237
|
+
// the connection is down is a gesture about a screen the person is no
|
|
238
|
+
// longer being served, and replaying it on reconnect would move them
|
|
239
|
+
// somewhere they asked to go some seconds and one outage ago.
|
|
240
|
+
back: () => {
|
|
241
|
+
if (socket === null || status !== "open") return;
|
|
242
|
+
send({ type: "back" });
|
|
243
|
+
},
|
|
244
|
+
// Same posture as `back`: only on an open socket, never queued. A jump
|
|
245
|
+
// replayed on reconnect would move somebody to where they wanted to be
|
|
246
|
+
// one outage ago.
|
|
247
|
+
popTo: (canvas, instance) => {
|
|
248
|
+
if (socket === null || status !== "open") return;
|
|
249
|
+
send({ type: "popTo", canvas, instance });
|
|
250
|
+
},
|
|
251
|
+
reset: () => {
|
|
252
|
+
if (disposed) return;
|
|
253
|
+
if (socket !== null && status === "open") {
|
|
254
|
+
send({ type: "reset" });
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
clearTimeout(retry);
|
|
258
|
+
attempts = 0;
|
|
259
|
+
connect();
|
|
260
|
+
},
|
|
261
|
+
dispose: () => {
|
|
262
|
+
disposed = true;
|
|
263
|
+
status = "closed";
|
|
264
|
+
clearTimeout(retry);
|
|
265
|
+
socket?.close();
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
exports.SNAPSHOT_ELEMENT_ID = SNAPSHOT_ELEMENT_ID;
|
|
271
|
+
exports.browserEnv = browserEnv;
|
|
272
|
+
exports.createWire = createWire;
|
|
273
|
+
exports.readDocumentSnapshot = readDocumentSnapshot;
|
|
274
|
+
//# sourceMappingURL=client.cjs.map
|
|
275
|
+
//# sourceMappingURL=client.cjs.map
|