@niscorp/cli 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,156 @@
1
1
  # @niscorp/cli
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2076f80: `session.draft.add` is what `session.draft.put` was. **Breaking.**
8
+
9
+ BREAKING — approved by moccadroid, 2026-10-18: rename `session.draft.put(...)` to `session.draft.add(...)`. Nothing else about it changes: it takes what `save` takes, what is added is in that one shell when the add answers, and `save`, `discard`, `show`, `remove` and `list` are as they were.
10
+
11
+ - cdc89cc: `server.checkFunctions()` reads the app's functions and refuses what is wrong with them before anyone is served. **Breaking.**
12
+
13
+ BREAKING — approved by moccadroid, 2026-10-18: `serve` of `@niscorp/moss/node`, and `nisc dev`, `nisc build`, `nisc check` and `nisc start`, refuse to come up on an action that calls a function the app has no function of, a charter `functions` deny that matches nothing, or two functions under one id. An app that hands a function only to signed-in sessions, with a shipped action calling it, hands it to every session (the function refuses whom it must), or is refused.
14
+
15
+ An app's functions are known only once a session is: `functions(session)` is called for each shell, and a session hook may reach for the server object, which the app holds only once `createServer` has answered. So the check is the app's to call, once it holds the server and before it listens; `serve` of `@niscorp/moss/node` calls it, and so do `nisc dev`, `nisc build`, `nisc check` and `nisc start` after the project's `boot`; each closes what it built where it refuses. It builds nobody's shell once, after everything is in force, and drops it. What that call returned is checked, and it refuses on:
16
+ - **an action, or a fragment a shell ships, that calls a function the app does not have**: `"home" calls "auth.leave", which the app has no function of`. Before, the call failed when a person pressed the button. An app with no `functions` has none. A set of actions handed over while the app runs is held to the same at that refresh.
17
+ - **a charter `functions` deny that matches nothing**: `Charter is incoherent over the app’s functions — refusing to serve:`.
18
+ - **two functions under one id**: `moss: functions(session) returned "auth.leave" twice.`
19
+
20
+ What the charter only warns of (a grant that names no function, a function no role grants), the functions with no description, and a map of handlers are said at that point, once.
21
+
22
+ The cost is one anonymous shell built, as any visitor who is not signed in causes. Every check reads nobody's functions: an app that hands a function only to signed-in sessions is refused where an action calls it.
23
+
24
+ ### Patch Changes
25
+
26
+ - edd3271: `session.answerIntent(writers, asked)` also replays a query that exists: `asked` may be `{ fingerprint, context }`.
27
+
28
+ It is answered as the caller, as an intent is, with what vex knows of the query: the context keys it binds, the ones the call left out (`meta.missingContext`), its warnings. The wire answers a replay with the rows alone. A model that proves a query before it builds on it learns from this why a replay came back empty.
29
+
30
+ - f461b98: What a person generated and nobody has used for long enough is deleted, with `runtime.artifactsUnusedMs`.
31
+ - A version of an artifact a person saved is stamped as used (`artifacts.last_used_at`, migration `nisc.moss/6`) when a shell is built for them, once an hour at most, through the same vex entries and row rule as the save itself.
32
+ - A sweep runs as the server comes up and then every hour: every artifact of a person whose newest version was neither saved nor used within `artifactsUnusedMs` is deleted, every version of it, and the saves left empty with them. What is published for everybody (`*`) never ages; what the build ships is not a row.
33
+ - Without the setting nothing is deleted. `0` or less refuses the boot.
34
+ - The sweep is one raw statement in moss (`data/aging.ts`), entered in the raw-SQL ledger: vex keeps every statement of its own to one principal's rows, and the sweep crosses them all.
35
+
36
+ - 37422bf: `server.defaults(publisher)` publishes every kind a person saves: an action, a fragment and a read, beside a layout.
37
+ - **An action or a fragment is given its id by whoever publishes it**, as a shipped one has one: `server.defaults(who).save([{ kind: 'action', id: 'promo', body }])`. One without an id is refused (`moss: a published action is given its id by whoever publishes it: name it.`), and so is one under `generated.`. The charter grants it by that id: a new id needs a grant, and one that is a shipped action's or fragment's replaces the build's for everybody until it is reset.
38
+ - **A read vex wrote is published under its fingerprint**, `save([{ kind: 'read', id: '<fingerprint>' }])`, and is answered to everybody, nobody signed in included, after what the caller saved themselves. One under the fingerprint of a shipped entry is refused. A generated action anybody saves may replay it.
39
+ - **Checked as a person's save is, as the publisher, and then as a manifest.** An action's `fn:` calls are ones the publisher's roles grant and its reads ones they may replay; then the whole set in force is verified as a set handed over is, and a holder whose roles do not grant a call refuses the publish: `Publish refused — actions call functions the app does not have, or that their holders’ charter does not grant:`.
40
+ - **A default that no longer passes under a new build is left out, and the build's copies stand**, with a line said once per read of the rows: `[moss] what is published for everybody is left out, and the build’s copies stand: …`.
41
+ - `publishedArtifacts(saved, publisher)` of the running manifest takes who publishes, for the roles and reads a publish is held to; `server.defaults` resolves them from the publisher's principal.
42
+
43
+ - Updated dependencies [edd3271]
44
+ - Updated dependencies [f461b98]
45
+ - Updated dependencies [2076f80]
46
+ - Updated dependencies [cdc89cc]
47
+ - Updated dependencies [37422bf]
48
+ - Updated dependencies [63b9ab5]
49
+ - Updated dependencies [6a62604]
50
+ - @niscorp/moss@0.8.0
51
+ - @niscorp/nova@0.5.0
52
+
53
+ ## 0.7.0
54
+
55
+ ### Minor Changes
56
+
57
+ - e9b987e: Moss holds an app's entries itself, in memory, and copies none into `vex_cache`. `server.replaceEntries(source, entries)` hands a set of entries over while a server runs. **Breaking.**
58
+
59
+ BREAKING — approved by moccadroid, 2026-10-12: an app that runs a vex engine of its own over `runtime.cache` gives that engine the entries it replays (`seedCache(cache, entries)`), and an app that wrote an entry into that table for moss to serve hands it over with `server.replaceEntries(source, entries)`.
60
+ - **Where a fingerprint resolves.** The entries an app ships are read from the build at every boot and held by the running manifest, compiled as vex replays them. The engine asks it first, and the cache table (`vex_cache`, or what `runtime.cache` hands over) only for what vex wrote itself while the app runs, such as a query `session.answerIntent` wrote. A boot still refuses an entry vex cannot run.
61
+ - **Nothing is copied into the cache table, and a row in it that no request wrote is not replayed.** Until now every entry was written there at each boot, and a replay resolved in the table. Moss now answers from the table only for a row vex wrote for a request (it carries that request's hash). The rows an earlier release wrote stay where they are and are answered from no longer: an entry the app stopped shipping is refused (`cache_miss`), where it went on answering before. Moss deletes none of them.
62
+ - **`server.replaceEntries(source, entries)`** is new, and is to entries what `server.replaceActions` is to actions: a named set, replaced whole, checked before it is taken (the schema the manifest's entries are read by, vex's authoring lint for a write, the reach it declares), frozen, and this process's alone. An entry of a set is replayed in place of one the app shipped under the same fingerprint.
63
+ - **The list of fingerprints** a feature or a discovery is told of holds the entries in force and the queries vex wrote. An app whose `runtime.cache` could not list its rows (vex's tiered cache) was told of none; it is told of the entries in force now.
64
+ - **`nisc migrate`** is as it was. Its pass for an entry that already did not fit before a run asks the cache table for a copy of that entry. Moss writes no such copy from this release on, so in a database only moss writes to, an entry first shipped from now on gets no pass. A copy an earlier release wrote, or one the app writes itself for an engine of its own, still gives one.
65
+ - **What a discovery says of an entry of the app.** `createdAt` is when this process compiled it, and `lastUsedAt` is not said: a replay of an entry moss holds stamps nothing. Both came from the row in the table before.
66
+ - **The refusal for a set that is not the caller's** says `the set "…"` where it said `the set of actions "…"`: a set holds entries too.
67
+ - The CLI and `@niscorp/nisc` change in the moss they bring; `AGENTS.md` says where entries are held.
68
+
69
+ - fc96c47: `functions(session)` returns a list of `FunctionDefinition`, `{ id, description, execute }`, and `session.functions()` lists each function a session may call with its description.
70
+
71
+ ```ts
72
+ functions: (session) => [
73
+ {
74
+ id: 'notes.archive',
75
+ description: 'Archives one of the person’s notes. Send { id }.',
76
+ execute: async ({ id }, signal) => archive(session, id, signal),
77
+ },
78
+ ],
79
+ ```
80
+
81
+ - **`id`** is what the charter's `functions` and every `fn:` endpoint name. **`execute`** is what an `fn:` endpoint calls, `(data, signal) => Promise<unknown>`, as a handler in the map was. **`description`** says what it does and what to send, for the model that writes a call to it: `session.functions()` answers `[{ id: 'notes.archive', description: '…' }]`.
82
+ - **Two functions under one id are refused** when a shell is built: `moss: functions(session) returned "auth.leave" twice.`
83
+ - **A map of handlers by id still works, and is deprecated.** The first shell a process builds says once what to change, read off what that session was given: `[moss] functions(session) returned a map of handlers, which is deprecated: return a list of { id, description, execute }.`, or, for a list, `[moss] functions with no description: auth.leave. Give each a description.` An empty description counts as none; such a function, and one given by a map, is listed by its id alone.
84
+ - `FunctionDefinition` is exported, for a helper that returns some of an app's functions.
85
+
86
+ For whoever upgrades an app, person or agent: turn the map into a list, one `{ id, description, execute }` for each handler, the id being its key; a helper that returns part of the map returns part of the list, and the parts are joined with `[...a, ...b]`. Write each description as what the function does and what to send.
87
+
88
+ - 9e6a7c3: The charter decides which of an app's functions a principal may call. **Breaking.**
89
+
90
+ BREAKING — approved by moccadroid, 2026-10-14: give every role of the charter a `functions` part, the functions its actions call, or `functions: ['*']` to keep calling all of them; a role written as a list (`member: ['home', 'settings']`) becomes `member: { actions: ['home', 'settings'], functions: [...] }`.
91
+ - **A shell holds only the functions its principal's roles grant** (`functions`, beside `actions`, `data` and `layouts`, with the same globs, `extends` and `deny`). A role with no `functions` may call none. Before, every shell held every function. A living shell follows the roles an adopt answers, as its actions do.
92
+ - **The boot is refused, with the list of what to grant**, where a role on its own, a combination people wear, or `public` holds an action (or the shells ship a fragment) that calls a function its grants miss: `"member" hold "chrome.topbar", which calls "auth.leave": their functions do not grant it`. A name with a template in it is decided when it is called.
93
+ - **`'*'` is said at boot**: `role "member" allows every function ('*'): the generated actions of the people who hold it, or a role that extends it, may call any it does not deny`.
94
+ - **A grant that names no function** (a typo) is said at the first shell a process builds, with a deny that matches nothing and a function no role grants: the names of the app's functions are known once `functions(session)` has run, and are read as that first session's.
95
+ - **A generated action or fragment may call a function its owner's roles grant**, named written out; one they do not grant is refused when it is saved and left out when a shell is built. `session.functions()` lists the functions a session may call, `{ id, description? }`, for the model that writes one.
96
+ - `@niscorp/charter` has the `functions` section, and `verifyCharter` checks it where a `functions` universe is handed in.
97
+
98
+ For whoever upgrades an app, person or agent: boot it. The refusal lists, per role combination, each function an action calls that the charter does not grant. Add those names to the `functions` of the role that holds the action, or `['*']` to the roles whose people may call everything. This is the app's permissions table: write it deliberately, and do not generate it.
99
+
100
+ - b7fabdb: Moss keeps every action's layout in the shell's layout store, under `action/<id>`. A layout that changes now reaches a screen that is already open. **Breaking.**
101
+
102
+ BREAKING — approved by moccadroid, 2026-10-12 (`action/`) and 2026-10-13 (`frame`, `canvas/`): a manifest's `layoutStore` declares no name beginning with `action/` or `canvas/` and not the name `frame`, no action's layout and no layout variant names one of those by ref, and code that takes the whole shell (`unverifiedShell(session)`) to read an action's layout off a definition reads it from the layout store (`shell.layoutStore.get('action/<id>')`).
103
+ - **An open screen follows a layout that changed, with its data kept.** A set of actions handed over with `server.replaceActions` used to reach only a screen opened afterwards: an instance that was open kept the layout it was opened with. What an open instance still keeps is the rest of its definition (its data's shape, its endpoints, its triggers).
104
+ - **Where the layout is kept does not show to an app.** An app writes an action's layout in its definition as before. `server.actions()` answers it as written, and so does a definition read off a session's shell (`session.shell.getRuntime(id).definition`), with the layout the screen is drawn with now in place. Inside nova's own shell, which `unverifiedShell(session)` hands out, the definition names its layout by `{ ref: 'action/<id>' }` and the store holds the layout, or the layout variant the person's roles hold. An action with no layout, or one whose `layout` is the name of a stored layout, is handed over as it is.
105
+ - **A session's shell hands out its layout store to read.** `set` and `delete` on `session.shell.layoutStore` throw, as `setLayout` does. They went through before.
106
+ - **`action/` is moss's in a layout store.** A manifest whose `layoutStore` declares a name beginning with it, in the app's shell or in a page, refuses the boot and says where. So does an action's layout or a layout variant that names one, at boot and when a set of actions is handed over: a layout cannot be drawn inside itself.
107
+ - **The layout of an action that leaves a shell is taken out of its store.**
108
+ - **The shell's own layout and a canvas's are kept in the store too**, under `frame` and `canvas/<id>`, and the shell draws each by that name. An app writes `layout` and a canvas's `actionLayout` as before, and a screen is drawn as before; one that is the name of a stored layout is handed over as it is. A manifest whose `layoutStore` declares `frame`, or a name beginning with `canvas/`, in the app's shell or in a page, refuses the boot and says where. So does an action's layout or a layout variant that names one of them, at boot and when a set of actions is handed over. A layout is named by a node that is `{ ref }` and nothing else: a `ref` a component carries, on its node or in its props, names none.
109
+ - **Whether a page can still do something is read through every ref.** A layout a screen names by `{ ref }` is read where the store holds it, so a two-way bound field in a stored layout the app names itself makes its page live. It was missed before, and such a page was reported as a file.
110
+ - The CLI and `@niscorp/nisc` change in the moss they bring.
111
+
112
+ ### Patch Changes
113
+
114
+ - 4dc982a: Moss keeps what was generated while the app runs for the person who saved it (a layout, an action, a fragment), and a layout an app publishes for everybody.
115
+ - **`session.artifacts`, on the session an app's functions are handed.** `save`, `list`, `history`, `restore` and `reset`. A layout is saved for the action it is for (`{ kind: 'layout', body: { ref: 'action/<id>', layout, use? } }`). It is the session's principal's alone, gets its id from moss, and is drawn on their screens while it is marked `use: true`; their open screens follow at once, with their data kept. Who may save is the charter's: the function that calls it is the app's, and the charter says who holds the action that calls that function. A session nobody is signed in to saves nothing.
116
+ - **A row is its principal's, and vex keeps it so.** Moss reads and writes the two tables as the caller, under one row rule: a caller reads and writes only the rows whose `principal` is their `userId`, and a row they insert or update carries it. No call names whose rows are meant. The same rule is part of the policy an app's charter compiles to, so a role that is granted the tables, by name or by a wildcard, reaches its own rows there and nobody else's. A row of `artifact_saves` is moss's alone to make: an app's entry that inserts or updates one is refused. An app's `behaviors` that name `artifacts` or `artifact_saves` refuse the boot.
117
+ - **`server.defaults(publisher)`, on the server: what is published for everybody.** The same five calls and the same body. A published layout is drawn for everybody who holds its action; every living shell adopts it at once, and every other process follows the generation pointer, which a publish moves. It is kept as the rows of one principal no caller is (`*`), under the same row rule, with who published in `created_by`. No session can publish: only the app's own server code reaches the call, and the charter says who holds the action that makes it. One read of what is published answers every shell a process builds: a boot makes it, and the first shell after a publish there or a move of the pointer makes it again.
118
+ - **`session.artifacts` also keeps an action and a fragment** (`kind: 'action'`, `kind: 'fragment'`). Moss gives the id, `generated.` and a uuid; a body that names another is refused. It is its owner's alone: it is in the shells built for them and in nobody else's, and in no catalog. What it defines replays reads and calls the functions its owner's roles grant: each endpoint is a `POST` to the app's vex route naming one fingerprint of a read the app ships or was handed and its owner may replay, or of a read vex wrote that its owner saved, or an `fn:` endpoint to a function its owner's roles grant (see the charter's `functions`); a write, a query a model wrote that nobody saved and every other address are refused, and so is a generated action that opens an action its owner does not hold. Moss checks the artifact; once it is in a shell it is an action or a fragment like any other, on nova's channels and in nova's merge of a fragment into the action it is wrapped around. It is checked at the save and at every shell, and one that no longer passes is left out with a line. `session.actions`, and the `actions` the `inputs` and `seeds` hooks are handed, are the ids the shell was built with, so they hold a principal's generated actions too.
119
+ - **`session.draft`, on the same session: what is being generated in one shell, before it is saved.** `put` takes what `save` takes, runs the same check with the draft laid over what is in force and against what that one shell can draw, and answers when that shell has it, so a function puts an action and opens it on its next line. `list`, `remove` and `discard`; each put or removal is a numbered step, and `show(step)` has the shell show the draft as it was after it; `save` is one save of all of it under the ids it had. A draft is in no other shell, is saved nowhere, and is gone when its shell is.
120
+ - **An id beginning with `generated.` is moss's to give.** A boot and `replaceActions` refuse an action under one, and the manifest's parse refuses a shell's fragment under one.
121
+ - **No caller's `userId` is `*`, and no caller's scope carries `artifactSavedBy`.** For one whose sign-in or `scope` says either, no shell is built and `/api/vex` answers 500.
122
+ - **Under an action's ref a shell draws**, the first of these there is: the person's own layout marked in use, the layout variant their roles hold, the published layout marked in use, the build's.
123
+ - **Every save is a version, and moss changes and deletes none.** Going back to a version is a new save that holds a copy of it; a reset is a new save that says none is in force, and the layout under it is drawn again.
124
+ - **A layout is checked when it is saved and when a shell is built**: its shape, that the action it is for has a layout of its own and is held by whom it is saved for, its components against what the app's shells have, that it names no ref moss keeps a layout under (`action/…`, `canvas/…`, `frame`), and what nova's audit finds of its action with the layout in place and not of the action as it is built. A save is refused with a sentence. A saved layout that no longer passes is left out with a line in the log, and what is under it is drawn.
125
+ - **Two tables, in migration `nisc.moss/5`: `artifact_saves` and `artifacts`.** A deployment that boots with `migrations: 'verify'` runs `nisc migrate` first, as for every migration. An app whose database already has a table by either name renames its own before it takes this release.
126
+ - **The fabric carries one more message, `adopt`**: it names a principal and tells a process to bring the shells it holds for them level. A process that runs an earlier release drops it as a message it does not know, as it drops every such message.
127
+ - **The layouts of the app's own shell are saved the same way: its own under `ref: 'frame'`, a canvas's under `ref: 'canvas/<id>'`**, by a session for its principal and by `server.defaults` for everybody. The app's own shell draws the person's own in use, else the published one, else the one its manifest declares; their open screen follows at once. A page draws the layout it declares. A shell manifest with no `layout`, or a canvas with no `actionLayout` of its own, has none to take the place of, and a save for it is refused. It is checked as a layout for an action is, against the components of the app's own shell and without nova's audit. A frame that leaves a canvas of the shell out is saved as it is: that canvas is drawn nowhere.
128
+ - **A canvas that only a layout's slot draws goes when the slot goes.** Nova gives a shell a canvas when something is first pushed onto it. Where a layout in force for a principal holds a canvas slot with a written-out `canvasId` for a canvas their shell's manifest does not declare, and then no layout does (the saved layout was reset, the action left the shell), an open shell loses that canvas with what is mounted on it. It stayed before, drawn nowhere. The canvases a manifest declares are never taken out, and moss gives a shell none.
129
+ - **A read vex wrote is kept the same way** (`{ kind: 'read', id: 'fp_…' }`, no body): moss takes the query and the Prism config of its mapping from vex's table. It is answered to the person who saved it and to nobody else (never to a caller nobody is signed in for), held to vex's limits as a query vex wrote is, it survives a schema change that does not touch what it reads, and their generated actions may replay it. One whose query no longer runs is left out with a line, with the generated actions that replay it. Moss's data layer hands vex's table only what vex wrote for a request: a saved read vex replays is not copied into it.
130
+ - Not built yet: publishing an action, a fragment or a read; a layout of a page's shell.
131
+ - The CLI and `@niscorp/nisc` change in the moss they bring. `AGENTS.md` gains rule 7b: how a layout, an action or a fragment generated while the app runs is saved or kept in a draft, how a layout is published for everybody, and that the charter decides who may do either.
132
+
133
+ - c7c4f9b: A nova shell keeps actions and fragments in one registry. **Breaking.**
134
+
135
+ BREAKING — approved by moccadroid, 2026-10-13: `shell.registerFragment` is gone, and an action and a fragment no longer share an id.
136
+ - **`shell.registerAction(definition)` takes an action or a fragment**, told apart by the fragment's `kind: 'fragment'`, and **`shell.removeAction(id)` takes either out**. There was no call to take a fragment out. Taken out, a fragment is unknown to a later `with: [...]`; an instance that was opened with it keeps the definition it was composed into, and `back` skips a position that was opened with it, as it skips one it cannot put back.
137
+ - **A fragment handed to `createShell` is validated**, as an action is: one that does not parse throws `DefinitionValidationError` at construction. Only `registerFragment` validated one before.
138
+ - **An id names an action or a fragment, never both.** `createShell` and `registerAction` throw `DefinitionValidationError` for an id that is already the other kind's.
139
+ - Opening a fragment by itself still throws `UnknownActionError`, and a `with: [...]` that names an action still throws `UnknownFragmentError`. `ShellConfig` keeps `actions` and `fragments`.
140
+ - **Moss:** a fragment that is no longer answered for a principal is taken out of their open shell, as an action is. A boot, and a set of actions handed over, refuse an action under the id of a fragment a shell ships. On a session's own shell, `registerAction` (refused there as before) is the one call that would take a fragment.
141
+
142
+ **What to change:** `shell.registerFragment(fragment)` becomes `shell.registerAction(fragment)`. Give an action and a fragment that share an id two ids.
143
+
144
+ - Updated dependencies [0a7beae]
145
+ - Updated dependencies [e9b987e]
146
+ - Updated dependencies [fc96c47]
147
+ - Updated dependencies [9e6a7c3]
148
+ - Updated dependencies [b7fabdb]
149
+ - Updated dependencies [4dc982a]
150
+ - Updated dependencies [c7c4f9b]
151
+ - @niscorp/moss@0.7.0
152
+ - @niscorp/nova@0.4.0
153
+
3
154
  ## 0.6.0
4
155
 
5
156
  ### Minor Changes
package/README.md CHANGED
@@ -55,7 +55,7 @@ page in the manifest), and what each one needs once it has been drawn.
55
55
 
56
56
  | Field | |
57
57
  |---|---|
58
- | `boot` | stand the app up: `{ server, close? }` |
58
+ | `boot` | stand the app up: `{ server, close? }`; `nisc` then calls `server.checkFunctions()`, which refuses an action calling a function the app does not have before anything is drawn or served |
59
59
  | `draw` | a terminal that draws a screen to a string (moss's `terminal/react/server`, `/vue/server`, `/dom/server`) |
60
60
  | `htmlAttributes?` | what the kit would put on `<html>` from an effect (a palette, a scheme) |
61
61
  | `site?` | the address the site is served at (`"https://example.com"`). With it, every path's document says its own canonical address — see "The head of each page" |
package/bin/nisc.js CHANGED
@@ -1,9 +1,4 @@
1
1
  #!/usr/bin/env node
2
- // The `nisc` command's launcher — a file that exists BEFORE the package is
3
- // built. A package manager links a bin when it installs, and in this workspace
4
- // that happens before anything is compiled: with the bin pointing at dist/
5
- // directly, a fresh checkout installed, found no file to link, and every
6
- // script that says `nisc` then failed with "command not found". This file is
7
- // in the repository, so the link is always made; the command itself is what it
8
- // imports.
2
+ // A committed file, not one in dist/: a package manager links a bin when it
3
+ // installs, which in this workspace is before anything is built.
9
4
  import '../dist/cli.js';
package/dist/adopt.js CHANGED
@@ -30,7 +30,7 @@ var main = async () => {
30
30
  const [root, asked, answered] = process.argv.slice(2);
31
31
  if (root === void 0 || asked === void 0 || answered === void 0) throw new Error("usage: adopt <root> <pages.json> <answer.json>");
32
32
  standDom(root);
33
- const { isShellProject, loadProject } = await import('./project-CH37UEL7.js');
33
+ const { isShellProject, loadProject } = await import('./project-3LJPDFX2.js');
34
34
  const project = await loadProject(root);
35
35
  if (!isShellProject(project)) throw new Error("nisc: this app has no shell of its own to adopt with.");
36
36
  const pages = JSON.parse(readFileSync(asked, "utf8"));
package/dist/adopt.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adopt.ts"],"names":["require","window"],"mappings":";;;;;;;AAsBA,IAAM,QAAA,GAAW,EAAA;AACjB,IAAM,aAAA,GAAgB,GAAA;AAEtB,IAAM,KAAA,GAAQ,CAAC,EAAA,KAA8B,IAAI,OAAA,CAAQ,CAAC,IAAA,KAAS,UAAA,CAAW,IAAA,EAAM,EAAE,CAAC,CAAA;AAEvF,IAAM,QAAA,GAAW,CAAC,IAAA,KAAuB;AACvC,EAAA,MAAMA,QAAAA,GAAU,aAAA,CAAc,IAAA,CAAK,IAAA,EAAM,cAAc,CAAC,CAAA;AACxD,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAUA,SAAQ,OAAO,CAAA;AAAA,EAC3B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uFAAA,EAA0F,IAAI,CAAA,oBAAA,CAAsB,CAAA;AAAA,EACtI;AACA,EAAA,MAAM,WAAA,GAAuB,OAAA,KAAY,IAAA,IAAQ,OAAO,OAAA,KAAY,WAAW,OAAA,CAAQ,GAAA,CAAI,OAAA,EAAS,OAAO,CAAA,GAAI,MAAA;AAC/G,EAAA,IAAI,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;AAAA,EACL,MAAM,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA;AAAA,EACpB,CAAC,KAAA,KAAmB;AAClB,IAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,EAAG,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC;AAAA,CAAI,CAAA;AAClF,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"adopt.js","sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { format } from 'node:util';\nimport { shellSettled } from '@niscorp/nova';\n\n// ═══════════════════════════════════════════════════════════════\n// THE ADOPTION CHECK — a process of its own (see ./shell-site).\n//\n// node adopt.js <app root> <pages.json> <answer.json>\n//\n// It is a page: a DOM stands before anything of the app's is loaded, exactly as\n// in a browser. Then, per path: the markup a build drew goes into a root, the\n// app's own boot runs again, and the app's own `adopt` is called over the two —\n// the call its browser entry makes. Whatever the adapter complains about (an\n// error logged, an error raised on the window, a root that was rebuilt into\n// something else) is written down, in its own words.\n//\n// The DOM is the app's: jsdom, found from the app's root. The command carries\n// none.\n// ═══════════════════════════════════════════════════════════════\n\nconst QUIET_MS = 60;\nconst ADOPT_WAIT_MS = 10_000;\n\nconst pause = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));\n\nconst standDom = (root: string): void => {\n const require = createRequire(join(root, 'package.json'));\n let library: unknown;\n try {\n library = require('jsdom');\n } catch {\n throw new Error(`nisc: the adoption check needs a DOM, and this app has no jsdom installed (looked from ${root}). pnpm add -D jsdom`);\n }\n const constructor: unknown = library !== null && typeof library === 'object' ? Reflect.get(library, 'JSDOM') : undefined;\n if (typeof constructor !== 'function') throw new Error('nisc: jsdom exports no JSDOM.');\n const dom: unknown = Reflect.construct(constructor, ['<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true }]);\n const window: unknown = dom !== null && typeof dom === 'object' ? Reflect.get(dom, 'window') : undefined;\n if (window === null || typeof window !== 'object') throw new Error('nisc: jsdom made no window.');\n // Everything a page has and this process does not. What the process already\n // has (timers, fetch, URL) stays its own.\n for (const name of ['window', 'document', ...Object.getOwnPropertyNames(window)]) {\n if (name in globalThis) continue;\n Object.defineProperty(globalThis, name, { configurable: true, get: () => Reflect.get(window, name) });\n }\n};\n\nconst main = async (): Promise<void> => {\n const [root, asked, answered] = process.argv.slice(2);\n if (root === undefined || asked === undefined || answered === undefined) throw new Error('usage: adopt <root> <pages.json> <answer.json>');\n standDom(root);\n // only now: the app's modules load into a world that has a DOM\n const { isShellProject, loadProject } = await import('./project');\n const project = await loadProject(root);\n if (!isShellProject(project)) throw new Error('nisc: this app has no shell of its own to adopt with.');\n\n const pages: unknown = JSON.parse(readFileSync(asked, 'utf8'));\n if (!Array.isArray(pages)) throw new Error('nisc: no pages to adopt.');\n\n // one ear for the whole run, pointed at the path being adopted\n let complaints: string[] = [];\n const short = (text: string): string => (text.length > 600 ? `${text.slice(0, 600)}…` : text);\n console.error = (...args: unknown[]): void => {\n complaints.push(short(format(...args)));\n };\n window.addEventListener('error', (event) => {\n complaints.push(short(event.message));\n event.preventDefault();\n });\n\n const out: { path: string; complaints: string[] }[] = [];\n for (const page of pages) {\n const path: unknown = page !== null && typeof page === 'object' ? Reflect.get(page, 'path') : undefined;\n const screen: unknown = page !== null && typeof page === 'object' ? Reflect.get(page, 'screen') : undefined;\n if (typeof path !== 'string' || typeof screen !== 'string') continue;\n complaints = [];\n const mine = complaints;\n try {\n document.body.innerHTML = '<div id=\"root\"></div>';\n const element = document.getElementById('root');\n if (element === null) throw new Error('no root');\n element.innerHTML = screen;\n const parsed = element.innerHTML;\n const booted = await project.shell({ path });\n // the page's entry waits for its own screen before it adopts; so does this\n if (!(await shellSettled(booted.shell, { waitMs: ADOPT_WAIT_MS }))) mine.push('the page’s own boot was still loading when it came to adopt');\n await project.adopt(element, booted.shell);\n // An adapter that REBUILDS its root (the DOM adapter) has done so by now:\n // what it built must be what was there. One that adopts in place (React,\n // Vue) says what it found wrong a moment later, through the ear above.\n if (element.innerHTML !== parsed) mine.push('what the page’s boot drew is not the markup it was handed');\n await pause(QUIET_MS);\n await booted.close?.();\n } catch (error) {\n mine.push(error instanceof Error ? error.message : String(error));\n }\n out.push({ path, complaints: mine });\n }\n writeFileSync(answered, JSON.stringify(out));\n};\n\nmain().then(\n () => process.exit(0),\n (error: unknown) => {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n },\n);\n"]}
1
+ {"version":3,"sources":["../src/adopt.ts"],"names":["require","window"],"mappings":";;;;;;;AAMA,IAAM,QAAA,GAAW,EAAA;AACjB,IAAM,aAAA,GAAgB,GAAA;AAEtB,IAAM,KAAA,GAAQ,CAAC,EAAA,KAA8B,IAAI,OAAA,CAAQ,CAAC,IAAA,KAAS,UAAA,CAAW,IAAA,EAAM,EAAE,CAAC,CAAA;AAEvF,IAAM,QAAA,GAAW,CAAC,IAAA,KAAuB;AACvC,EAAA,MAAMA,QAAAA,GAAU,aAAA,CAAc,IAAA,CAAK,IAAA,EAAM,cAAc,CAAC,CAAA;AACxD,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAUA,SAAQ,OAAO,CAAA;AAAA,EAC3B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uFAAA,EAA0F,IAAI,CAAA,oBAAA,CAAsB,CAAA;AAAA,EACtI;AACA,EAAA,MAAM,WAAA,GAAuB,OAAA,KAAY,IAAA,IAAQ,OAAO,OAAA,KAAY,WAAW,OAAA,CAAQ,GAAA,CAAI,OAAA,EAAS,OAAO,CAAA,GAAI,MAAA;AAC/G,EAAA,IAAI,OAAO,WAAA,KAAgB,UAAA,EAAY,MAAM,IAAI,MAAM,+BAA+B,CAAA;AACtF,EAAA,MAAM,GAAA,GAAe,OAAA,CAAQ,SAAA,CAAU,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O,MAAM,CAAA,EAAG,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC;AAAA,CAAI,CAAA;AAClF,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"adopt.js","sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { format } from 'node:util';\nimport { shellSettled } from '@niscorp/nova';\n\nconst QUIET_MS = 60;\nconst ADOPT_WAIT_MS = 10_000;\n\nconst pause = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));\n\nconst standDom = (root: string): void => {\n const require = createRequire(join(root, 'package.json'));\n let library: unknown;\n try {\n library = require('jsdom');\n } catch {\n throw new Error(`nisc: the adoption check needs a DOM, and this app has no jsdom installed (looked from ${root}). pnpm add -D jsdom`);\n }\n const constructor: unknown = library !== null && typeof library === 'object' ? Reflect.get(library, 'JSDOM') : undefined;\n if (typeof constructor !== 'function') throw new Error('nisc: jsdom exports no JSDOM.');\n const dom: unknown = Reflect.construct(constructor, ['<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true }]);\n const window: unknown = dom !== null && typeof dom === 'object' ? Reflect.get(dom, 'window') : undefined;\n if (window === null || typeof window !== 'object') throw new Error('nisc: jsdom made no window.');\n for (const name of ['window', 'document', ...Object.getOwnPropertyNames(window)]) {\n if (name in globalThis) continue;\n Object.defineProperty(globalThis, name, { configurable: true, get: () => Reflect.get(window, name) });\n }\n};\n\nconst main = async (): Promise<void> => {\n const [root, asked, answered] = process.argv.slice(2);\n if (root === undefined || asked === undefined || answered === undefined) throw new Error('usage: adopt <root> <pages.json> <answer.json>');\n standDom(root);\n // only now: the app's modules load into a world that has a DOM\n const { isShellProject, loadProject } = await import('./project');\n const project = await loadProject(root);\n if (!isShellProject(project)) throw new Error('nisc: this app has no shell of its own to adopt with.');\n\n const pages: unknown = JSON.parse(readFileSync(asked, 'utf8'));\n if (!Array.isArray(pages)) throw new Error('nisc: no pages to adopt.');\n\n let complaints: string[] = [];\n const short = (text: string): string => (text.length > 600 ? `${text.slice(0, 600)}…` : text);\n console.error = (...args: unknown[]): void => {\n complaints.push(short(format(...args)));\n };\n window.addEventListener('error', (event) => {\n complaints.push(short(event.message));\n event.preventDefault();\n });\n\n const out: { path: string; complaints: string[] }[] = [];\n for (const page of pages) {\n const path: unknown = page !== null && typeof page === 'object' ? Reflect.get(page, 'path') : undefined;\n const screen: unknown = page !== null && typeof page === 'object' ? Reflect.get(page, 'screen') : undefined;\n if (typeof path !== 'string' || typeof screen !== 'string') continue;\n complaints = [];\n const mine = complaints;\n try {\n document.body.innerHTML = '<div id=\"root\"></div>';\n const element = document.getElementById('root');\n if (element === null) throw new Error('no root');\n element.innerHTML = screen;\n const parsed = element.innerHTML;\n const booted = await project.shell({ path });\n if (!(await shellSettled(booted.shell, { waitMs: ADOPT_WAIT_MS }))) mine.push('the page’s own boot was still loading when it came to adopt');\n await project.adopt(element, booted.shell);\n // An adapter that rebuilds its root (the DOM adapter) has done so by now.\n // One that adopts in place (React, Vue) reports a mismatch a moment\n // later, as a logged or raised error: the pause waits for it.\n if (element.innerHTML !== parsed) mine.push('what the page’s boot drew is not the markup it was handed');\n await pause(QUIET_MS);\n await booted.close?.();\n } catch (error) {\n mine.push(error instanceof Error ? error.message : String(error));\n }\n out.push({ path, complaints: mine });\n }\n writeFileSync(answered, JSON.stringify(out));\n};\n\nmain().then(\n () => process.exit(0),\n (error: unknown) => {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n },\n);\n"]}
@@ -42,5 +42,5 @@ var loadProject = async (root) => {
42
42
  };
43
43
 
44
44
  export { configFileOf, isProject, isShellProject, loadProject };
45
- //# sourceMappingURL=chunk-I2SDNSH5.js.map
46
- //# sourceMappingURL=chunk-I2SDNSH5.js.map
45
+ //# sourceMappingURL=chunk-Z2PJ5QB7.js.map
46
+ //# sourceMapp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"chunk-Z2PJ5QB7.js","sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { DocumentConfig, MossServer, NiscApp, NiscRuntime } from '@niscorp/moss';\nimport type { Shell } from '@niscorp/nova';\n\ntype Common = {\n // Default `dist`, relative to the root.\n dist?: string;\n // Default `page`: a <style> in index.html. `file` is for a Content-Security-Policy that forbids inline styles.\n stylesheet?: 'page' | 'file';\n // Default `src/dev/all-checks.ts`.\n checks?: string;\n site?: string;\n};\n\nexport type NiscMossProject = Common & {\n boot: () => Promise<{ server: MossServer; close?: () => void | Promise<void> }>;\n draw: DocumentConfig['draw'];\n htmlAttributes?: DocumentConfig['htmlAttributes'];\n // Default `nisc.token`.\n tokenKey?: string;\n // Default: `/`, and every page whose path has no parameter.\n paths?: (server: MossServer) => readonly string[] | Promise<readonly string[]>;\n // `nisc start` registers these before the site's catch-all.\n routes?: (server: MossServer) => void | Promise<void>;\n // For `nisc migrate`. `runtime` opens the environment and nothing else:\n // tables it migrated itself are changed before the step can check them.\n app?: NiscApp;\n runtime?: () => Promise<NiscRuntime & { close?: () => void | Promise<void> }>;\n dev?: {\n // The token `/dev/as/<who>` stores; `null` is nobody of that name.\n signIn?: (server: MossServer, who: string) => string | null | Promise<string | null>;\n // Default: this machine only. With it, anybody who can reach the dev server signs in as anybody.\n signInFromNetwork?: boolean;\n // Default: `src/app`, `src/server`, `src/db`, `src/ui` and the config.\n watch?: RegExp;\n // Paths that go to the app server and not to vite. Default: moss's own\n // prefixes; an app with routes of its own names those and its own.\n owned?: RegExp;\n };\n};\n\nexport type NiscShellProject = Common & {\n // Called more than once per path (a build boots twice to compare, and once\n // more inside a DOM to adopt), so it must not memoize.\n shell: (request: { path: string }) => Promise<{ shell: Shell; close?: () => void | Promise<void> }>;\n draw: (shell: Shell) => string | Promise<string>;\n // `root` already holds the drawn markup: the browser entry's own call (`hydrateRoot`, `createSSRApp().mount`, nova's `mountShell`).\n adopt: (root: HTMLElement, shell: Shell) => void | Promise<void>;\n htmlAttributes?: (shell: Shell) => Record<string, string>;\n // Default: `/`.\n paths?: () => readonly string[] | Promise<readonly string[]>;\n // Default 5000. Past it the build fails.\n waitMs?: number;\n};\n\nexport type NiscProject = NiscMossProject | NiscShellProject;\n\nconst CONFIG_NAMES = ['nisc.config.ts', 'nisc.config.mts', 'nisc.config.js', 'nisc.config.mjs'];\n\nconst has = (value: object, key: string): boolean => typeof Reflect.get(value, key) === 'function';\n\nexport const isShellProject = (project: NiscProject): project is NiscShellProject => 'shell' in project;\n\nexport const isProject = (value: unknown): value is NiscProject => {\n if (value === null || typeof value !== 'object' || !has(value, 'draw')) return false;\n const [moss, own] = [has(value, 'boot'), has(value, 'shell')];\n return moss !== own && (moss || has(value, 'adopt'));\n};\n\nconst isSite = (value: unknown): boolean => {\n if (typeof value !== 'string') return false;\n try {\n return ['http:', 'https:'].includes(new URL(value).protocol);\n } catch {\n return false;\n }\n};\n\nexport const configFileOf = (root: string): string | undefined => CONFIG_NAMES.find((name) => existsSync(join(root, name)));\n\nexport const loadProject = async (root: string): Promise<NiscProject> => {\n const name = configFileOf(root);\n const file = name === undefined ? undefined : join(root, name);\n if (file === undefined) {\n throw new Error(`nisc: no nisc.config.ts in ${root}. It exports \\`project\\`: how the app boots, and how one of its screens is drawn.`);\n }\n const { tsImport } = await import('tsx/esm/api');\n const tsconfig = join(root, 'tsconfig.json');\n const loaded: unknown = await tsImport(pathToFileURL(file).href, { parentURL: import.meta.url, ...(existsSync(tsconfig) ? { tsconfig } : {}) });\n const project: unknown = loaded !== null && typeof loaded === 'object' ? Reflect.get(loaded, 'project') : undefined;\n if (!isProject(project)) {\n throw new Error(\n `nisc: ${file} does not export a \\`project\\` the command can run. It hands over EITHER \\`boot\\` + \\`draw\\` (an app behind moss) OR \\`shell\\` + \\`draw\\` + \\`adopt\\` (an app with its own shell).`,\n );\n }\n if (project.site !== undefined && !isSite(project.site)) {\n throw new Error(`nisc: ${file} gives \\`site\\` as ${JSON.stringify(project.site)} — it is the address the site is served at, whole: \"https://example.com\".`);\n }\n return project;\n};\n"]}
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { loadProject, isShellProject, configFileOf, isProject } from './chunk-I2SDNSH5.js';
1
+ import { loadProject, isShellProject, configFileOf, isProject } from './chunk-Z2PJ5QB7.js';
2
2
  import { resolve, join, sep, extname, dirname } from 'path';
3
3
  import { spawn, spawnSync } from 'child_process';
4
4
  import { existsSync, statSync, readFileSync, rmSync, cpSync, mkdirSync, writeFileSync, mkdtempSync } from 'fs';
@@ -38,6 +38,12 @@ var mossPlugin = async (configFile, dev2) => {
38
38
  const project = Reflect.get(loaded, "project");
39
39
  if (!isProject(project) || isShellProject(project)) throw new Error(`nisc: ${configFile} no longer describes an app behind moss.`);
40
40
  const booted = await project.boot();
41
+ try {
42
+ await booted.server.checkFunctions();
43
+ } catch (error) {
44
+ await booted.close?.();
45
+ throw error;
46
+ }
41
47
  const signIn = project.dev?.signIn;
42
48
  return {
43
49
  server: booted.server,
@@ -500,6 +506,7 @@ var survey = async (options, project) => {
500
506
  const { exportDocuments } = await import('@niscorp/moss');
501
507
  const booted = await project.boot();
502
508
  try {
509
+ await booted.server.checkFunctions();
503
510
  const paths = project.paths === void 0 ? defaultPaths(booted.server.pages) : await project.paths(booted.server);
504
511
  return await exportDocuments({
505
512
  server: booted.server,
@@ -588,6 +595,12 @@ var start = async (options) => {
588
595
  }
589
596
  const { attachSocket, mountSite, MOSS_PATHS } = await import('@niscorp/moss/node');
590
597
  const booted = await project.boot();
598
+ try {
599
+ await booted.server.checkFunctions();
600
+ } catch (error) {
601
+ await booted.close?.();
602
+ throw error;
603
+ }
591
604
  await project.routes?.(booted.server);
592
605
  mountSite(booted.server, {
593
606
  dist,
@@ -698,8 +711,8 @@ var main = async () => {
698
711
  return command === void 0 || command === "help" || command === "--help" ? 0 : 1;
699
712
  };
700
713
  main().then(
701
- // An app's own handles (a database, a timer) must not keep a finished command
702
- // open: a command that is done says so and leaves.
714
+ // An explicit exit: an app's own handles (a database, a timer) would keep a
715
+ // finished command open.
703
716
  (code) => process.exit(code),
704
717
  (error) => {
705
718
  console.error(error instanceof Error ? error.message : error);
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dev.ts","../src/routes.ts","../src/shell-site.ts","../src/site.ts","../src/stylesheet.ts","../src/commands.ts","../src/cli.ts"],"names":["dev","join","pad","why","existsSync","resolve","sep","statSync","readFileSync","writeFileSync","require","createRequire","dirname","spawnSync","rmSync","httpServer","url"],"mappings":";;;;;;;;;;;;;AA2BA,IAAM,SAAA,GAAY,CAAC,KAAA,KACjB,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,OAAA,CAAQ,GAAA,CAAI,KAAA,EAAO,cAAc,CAAA,KAAM,UAAA;AAG/F,IAAM,MAAA,GAAS,OAAO,IAAA,KAAmC;AACvD,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,cAAc,IAAA,CAAK,IAAA,EAAM,cAAc,CAAC,CAAA,CAAE,QAAQ,MAAM,CAAA;AAAA,EAClE,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kDAAA,EAAqD,IAAI,CAAA,EAAA,CAAI,CAAA;AAAA,EAC/E;AACA,EAAA,MAAM,MAAA,GAAkB,MAAM,OAAO,aAAA,CAAc,KAAK,CAAA,CAAE,IAAA,CAAA;AAC1D,EAAA,IAAI,CAAC,UAAU,MAAM,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,MAAA,EAAS,KAAK,CAAA,aAAA,CAAe,CAAA;AACrE,EAAA,OAAO,MAAA;AACT,CAAA;AAIO,IAAM,kBAAA,GAAqB,CAACA,IAAAA,MAAkG;AAAA,EACnI,GAAIA,MAAK,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAOA,IAAAA,CAAI,KAAA,EAAM,GAAI,E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M,UAAU,KAAK,CAAA;AAC5D,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"cli.js","sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { configFileOf, isProject, isShellProject, loadProject } from './project';\nimport type { NiscMossProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// `nisc dev` — the app's own vite, started from here.\n//\n// An app with its own shell is a vite app and nothing more. An app behind moss\n// also needs its server inside that dev process, and that is moss's plugin\n// (`@niscorp/moss/vite`): added here, fed from the app's nisc.config.ts — the\n// same boot and the same drawing `nisc build` and `nisc start` use, loaded\n// through vite so an edit is a fresh boot. The app's vite.config.ts stays what\n// it is: its framework's plugin, its aliases.\n// ═══════════════════════════════════════════════════════════════\n\n// What is used of the app's vite — described here rather than imported, since\n// the vite is the app's and its types are the app's too.\ntype DevServer = {\n listen: () => Promise<unknown>;\n printUrls: () => void;\n resolvedUrls: { local: string[] } | null;\n close: () => Promise<void>;\n};\ntype ViteApi = { createServer: (config: { root: string; server?: { port: number }; plugins: unknown[] }) => Promise<DevServer> };\n\nconst isViteApi = (value: unknown): value is ViteApi =>\n value !== null && typeof value === 'object' && typeof Reflect.get(value, 'createServer') === 'function';\n\n// The app's vite — the command carries none of its own.\nconst viteOf = async (root: string): Promise<ViteApi> => {\n let entry: string;\n try {\n entry = createRequire(join(root, 'package.json')).resolve('vite');\n } catch {\n throw new Error(`nisc: this app has no vite installed (looked from ${root}).`);\n }\n const loaded: unknown = await import(pathToFileURL(entry).href);\n if (!isViteApi(loaded)) throw new Error(`nisc: ${entry} is not vite.`);\n return loaded;\n};\n\n// What of the config's `dev` block the plugin is told when it is made. Read\n// once, when the command starts: changing one takes a restart of `nisc dev`.\nexport const devPluginOptionsOf = (dev: NiscMossProject['dev']): { watch?: RegExp; owned?: RegExp; signInFromNetwork?: boolean } => ({\n ...(dev?.watch !== undefined ? { watch: dev.watch } : {}),\n ...(dev?.owned !== undefined ? { owned: dev.owned } : {}),\n ...(dev?.signInFromNetwork !== undefined ? { signInFromNetwork: dev.signInFromNetwork } : {}),\n});\n\n// moss's dev plugin, fed from the config as vite loads it.\nconst mossPlugin = async (configFile: string, dev: NiscMossProject['dev']): Promise<unknown> => {\n const { mossDev } = await import('@niscorp/moss/vite');\n return mossDev({\n label: 'nisc',\n ...devPluginOptionsOf(dev),\n app: async (load) => {\n const loaded = await load(`/${configFile}`);\n const project: unknown = Reflect.get(loaded, 'project');\n if (!isProject(project) || isShellProject(project)) throw new Error(`nisc: ${configFile} no longer describes an app behind moss.`);\n const booted = await project.boot();\n const signIn = project.dev?.signIn;\n return {\n server: booted.server,\n ...(booted.close !== undefined ? { close: booted.close } : {}),\n draw: project.draw,\n ...(project.htmlAttributes !== undefined ? { htmlAttributes: project.htmlAttributes } : {}),\n ...(project.site !== undefined ? { site: project.site } : {}),\n ...(project.tokenKey !== undefined ? { tokenKey: project.tokenKey } : {}),\n ...(signIn !== undefined ? { signIn: (who: string) => signIn(booted.server, who) } : {}),\n };\n },\n });\n};\n\nexport const devServer = async (options: { root: string; port?: number }): Promise<{ url: string; close: () => Promise<void> }> => {\n const project = await loadProject(options.root);\n const configFile = configFileOf(options.root);\n const vite = await viteOf(options.root);\n const server = await vite.createServer({\n root: options.root,\n ...(options.port !== undefined ? { server: { port: options.port } } : {}),\n plugins: isShellProject(project) || configFile === undefined ? [] : [await mossPlugin(configFile, project.dev)],\n });\n await server.listen();\n server.printUrls();\n const url = server.resolvedUrls?.local[0] ?? `http://localhost:${options.port ?? 5173}/`;\n return { url, close: () => server.close() };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // what the screen's head held, and the actions that said it — absent when\n // the screen has no head and the document's is the template's own\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n","import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. A page's <head> is a node in a\n// layout (nova's `nova:head`, holding the elements a head holds). It is read\n// off the same shell the markup was drawn from and written into the template's\n// <head>; a path whose screen has none goes out with the template's. A head\n// that holds what it may not — something that runs, or styles — FAILS the\n// build like any other check. With a `site` in the config, each path is given\n// its own canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // what the first screen's head held, and the actions that said it — absent\n // when the screen has no head and the file's is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","import { constants, createBrotliCompress, createGzip } from 'node:zlib';\nimport type { BrotliCompress, Gzip } from 'node:zlib';\n\n// ═══════════════════════════════════════════════════════════════\n// WHAT `nisc start` PUTS AROUND AN APP — either kind.\n//\n// `start` hands a listener one handler: an app with its own shell's\n// (./shell-site), or the moss server's. This wraps that handler, so the two\n// things below are said once, here, for both — and nothing inside moss or the\n// shell's own handler knows them.\n//\n// WHAT A BROWSER MAY KEEP (`withCaching`). What the bundler writes under\n// assets/ is named by its content: it is kept for a year and never asked\n// about again. Every other file is asked about each time, and answered 304\n// when it has not changed. An answer that already says for itself — every\n// drawn document does (who may keep a page follows from who asked) — is left\n// exactly as it is.\n//\n// HOW IT TRAVELS (`withCompression`). Text a browser reads goes out\n// compressed, brotli or gzip by what was asked for, a piece at a time as the\n// handler produces it — an answer that streams still streams.\n//\n// The app server's own paths (`except`: moss's /api, /catalog, …) are passed\n// through untouched: what they answer is theirs to say.\n// ═══════════════════════════════════════════════════════════════\n\n// A handler as a listener calls it: the request, and whatever else the listener\n// hands over (the Node request and response, for moss) — passed on as given.\nexport type SiteHandler<Rest extends readonly unknown[] = []> = (request: Request, ...rest: Rest) => Response | Promise<Response>;\n\nexport type SiteOptions = {\n // Paths whose answers are not the site's: left exactly as the handler made them.\n except?: RegExp;\n};\n\n// what the bundler writes is named by its content\nconst KEPT_PATHS = /^\\/assets\\//;\nconst KEPT_FOREVER = 'public, max-age=31536000, immutable';\n\nexport const withCaching =\n <Rest extends readonly unknown[]>(handler: SiteHandler<Rest>, options: SiteOptions = {}): SiteHandler<Rest> =>\n async (request, ...rest) => {\n const response = await handler(request, ...rest);\n if ((request.method !== 'GET' && request.method !== 'HEAD') || response.status !== 200) return response;\n const path = new URL(request.url).pathname;\n if (options.except?.test(path) === true) return response;\n if (response.headers.has('cache-control')) return response;\n\n const headers = new Headers(response.headers);\n if (KEPT_PATHS.test(path)) {\n headers.set('cache-control', KEPT_FOREVER);\n return new Response(response.body, { status: 200, headers });\n }\n headers.set('cache-control', 'no-cache');\n const [since, modified] = [request.headers.get('if-modified-since'), headers.get('last-modified')];\n if (since !== null && modified !== null && Date.parse(since) >= Date.parse(modified)) {\n await response.body?.cancel();\n headers.delete('content-length');\n return new Response(null, { status: 304, headers });\n }\n return new Response(response.body, { status: 200, headers });\n };\n\n// Text a browser reads — and nothing that is a conversation (an event stream).\nconst COMPRESSIBLE = /^(text\\/(?!event-stream)|application\\/(json|javascript|xml|manifest\\+json|wasm)|image\\/svg\\+xml)/i;\n// under this, the headers cost more than the saving\nconst SMALL_BYTES = 1024;\n// fast enough to do per answer, and already smaller than gzip's best\nconst BROTLI_QUALITY = 5;\n\ntype Encoding = 'br' | 'gzip';\n\n// What the asker takes, best first. `q=0` is a refusal.\nconst encodingFor = (header: string | null): Encoding | undefined => {\n const offered = new Map<string, number>();\n for (const part of (header ?? '').toLowerCase().split(',')) {\n const [name = '', ...parameters] = part.split(';').map((piece) => piece.trim());\n const weight = parameters.find((parameter) => parameter.startsWith('q='));\n if (name !== '') offered.set(name, weight === undefined ? 1 : Number(weight.slice(2)));\n }\n if ((offered.get('br') ?? 0) > 0) return 'br';\n if ((offered.get('gzip') ?? 0) > 0) return 'gzip';\n return undefined;\n};\n\n// Flushed after every piece written: what goes in comes out, compressed, before\n// the next piece is asked for. That is what keeps a streamed answer streaming.\nconst compressorFor = (encoding: Encoding): BrotliCompress | Gzip =>\n encoding === 'br'\n ? createBrotliCompress({ flush: constants.BROTLI_OPERATION_FLUSH, params: { [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY } })\n : createGzip({ flush: constants.Z_SYNC_FLUSH });\n\n// A body, compressed as it is read. `whole` is handed all of it once it has\n// gone out complete — never for a body that was cut short.\nconst compressedBody = (source: ReadableStream<Uint8Array>, encoding: Encoding, whole?: (bytes: Buffer<ArrayBuffer>) => void): ReadableStream<Uint8Array> => {\n const reader = source.getReader();\n const compressor = compressorFor(encoding);\n const pieces: Buffer[] = [];\n // whoever was reading has stopped: nothing more may be handed to them\n let isLetGo = false;\n let finished: () => void = () => undefined;\n const ended = new Promise<void>((done) => {\n finished = done;\n });\n return new ReadableStream<Uint8Array>({\n start: (controller) => {\n compressor.on('data', (piece: Buffer) => {\n if (isLetGo) return;\n if (whole !== undefined) pieces.push(piece);\n controller.enqueue(piece);\n });\n compressor.on('end', () => {\n if (!isLetGo) {\n whole?.(Buffer.concat(pieces));\n controller.close();\n }\n finished();\n });\n compressor.on('error', (error) => {\n if (!isLetGo) controller.error(error);\n finished();\n });\n },\n pull: async () => {\n // a source that fails takes the compressor with it; the failure is the reader's to hear\n const { done, value } = await reader.read().catch((error: unknown) => {\n compressor.destroy();\n throw error;\n });\n if (done) {\n compressor.end();\n return ended;\n }\n return new Promise<void>((taken) => {\n compressor.write(value, () => taken());\n });\n },\n cancel: async (reason) => {\n isLetGo = true;\n compressor.destroy();\n await reader.cancel(reason);\n },\n });\n};\n\nexport const withCompression = <Rest extends readonly unknown[]>(handler: SiteHandler<Rest>, options: SiteOptions = {}): SiteHandler<Rest> => {\n // An answer that says it will never change is compressed once: what it came\n // to is remembered, by what was asked for and how. Bounded by what the built\n // folder holds under assets/.\n const remembered = new Map<string, Buffer<ArrayBuffer>>();\n return async (request, ...rest) => {\n const response = await handler(request, ...rest);\n if (request.method !== 'GET' || response.status !== 200 || response.body === null) return response;\n const path = new URL(request.url).pathname;\n if (options.except?.test(path) === true) return response;\n if (!COMPRESSIBLE.test(response.headers.get('content-type') ?? '')) return response;\n if (response.headers.has('content-encoding') || /no-transform/i.test(response.headers.get('cache-control') ?? '')) return response;\n\n // From here the answer depends on what was asked for, compressed or not —\n // whatever keeps a copy has to be told.\n const headers = new Headers(response.headers);\n const varies = (headers.get('vary') ?? '').toLowerCase().split(',').map((name) => name.trim());\n if (!varies.includes('accept-encoding')) headers.append('vary', 'Accept-Encoding');\n\n const encoding = encodingFor(request.headers.get('accept-encoding'));\n const length = headers.get('content-length');\n if (encoding === undefined || (length !== null && Number(length) < SMALL_BYTES)) return new Response(response.body, { status: 200, headers });\n\n headers.set('content-encoding', encoding);\n headers.delete('content-length');\n // the bytes are no longer those bytes\n const etag = headers.get('etag');\n if (etag !== null && !etag.startsWith('W/')) headers.set('etag', `W/${etag}`);\n\n if (!/\\bimmutable\\b/i.test(headers.get('cache-control') ?? '')) return new Response(compressedBody(response.body, encoding), { status: 200, headers });\n const key = `${encoding} ${path} ${headers.get('last-modified') ?? ''}`;\n const known = remembered.get(key);\n if (known === undefined) return new Response(compressedBody(response.body, encoding, (bytes) => remembered.set(key, bytes)), { status: 200, headers });\n await response.body.cancel();\n headers.set('content-length', String(known.length));\n return new Response(known, { status: 200, headers });\n };\n};\n\n// Both, in the order they apply: said what may be kept, then compressed.\nexport const siteHandler = <Rest extends readonly unknown[]>(handler: SiteHandler<Rest>, options: SiteOptions = {}): SiteHandler<Rest> =>\n withCompression(withCaching(handler, options), options);\n","import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';\nimport { join, resolve, sep } from 'node:path';\n\n// ═══════════════════════════════════════════════════════════════\n// THE STYLESHEET GOES IN THE PAGE.\n//\n// A drawn page arrives as markup, and a browser paints none of it until it has\n// the stylesheet. As a file of its own that is a second round trip before the\n// first paint. So once the bundler is done, the page it wrote (`index.html`,\n// the template every drawn page is made from) has each stylesheet it links\n// written into it as a <style>, and one response paints the page.\n//\n// It is done ONCE, to the file in the built folder — every reader of that file\n// (`build`, `export`, `start`, moss's document) then hands out the same head\n// without knowing any of this. The stylesheet's own file stays where it is.\n//\n// A link is left as it is, and the build says so, when moving the stylesheet\n// could change what it means: a link that says more than where the file is (a\n// `media`, a `title`), a file that is not in the built folder, a stylesheet\n// that names another file relative to itself.\n// ═══════════════════════════════════════════════════════════════\n\n// What became of each stylesheet link the page had.\nexport type StylesheetReport = {\n // now in the page: where it was linked from, and how much text that is\n inPage: readonly { href: string; bytes: number }[];\n // left as a file, and why\n left: readonly { href: string; why: string }[];\n};\n\nexport type StylesheetRewrite = StylesheetReport & { html: string };\n\nconst attributesOf = (tag: string): Record<string, string> => {\n const found: Record<string, string> = {};\n // past `<link`\n for (const match of tag.slice(5).matchAll(/([^\\s\"'<>/=]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+)))?/g)) {\n const name = match[1];\n if (name !== undefined) found[name.toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? '';\n }\n return found;\n};\n\n// what a link may say and still be only \"this stylesheet, from here\"\nconst PLAIN = new Set(['rel', 'href', 'crossorigin']);\n\n// A url() that points at the same thing from a page at any path: an absolute\n// path, a full address, a data: or blob: URI, a fragment.\nconst isPortableUrl = (url: string): boolean => url === '' || /^(\\/|data:|blob:|https?:|#)/i.test(url);\n\n// Why a stylesheet cannot move into a page — nothing, when it can.\nconst whyStylesheetStays = (css: string): string | undefined => {\n if (/@import\\b/i.test(css)) return 'it imports another stylesheet';\n for (const match of css.matchAll(/url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)]*?))\\s*\\)/gi)) {\n const url = (match[1] ?? match[2] ?? match[3] ?? '').trim();\n if (!isPortableUrl(url)) return `it names a file relative to itself (${url})`;\n }\n return undefined;\n};\n\n// The page, with every stylesheet it links by a plain local path written into\n// it. `read` answers a stylesheet's text by its href, or nothing when the built\n// folder has no such file. Pure: a second pass over its own output changes\n// nothing.\nexport const stylesheetInPage = (html: string, read: (href: string) => string | undefined): StylesheetRewrite => {\n const inPage: { href: string; bytes: number }[] = [];\n const left: { href: string; why: string }[] = [];\n const rewritten = html.replace(/<link\\b[^>]*>/gi, (tag) => {\n const attributes = attributesOf(tag);\n if ((attributes['rel'] ?? '').toLowerCase() !== 'stylesheet') return tag;\n const href = attributes['href'] ?? '';\n const stays = (why: string): string => {\n left.push({ href, why });\n return tag;\n };\n const extra = Object.keys(attributes).filter((name) => !PLAIN.has(name));\n if (extra.length > 0) return stays(`its link says more than where it is (${extra.join(', ')})`);\n if (!href.startsWith('/') || href.startsWith('//') || /[?#]/.test(href)) return stays('it is not a path into the built folder');\n const css = read(href);\n if (css === undefined) return stays('it is not in the built folder');\n const why = whyStylesheetStays(css);\n if (why !== undefined) return stays(why);\n inPage.push({ href, bytes: Buffer.byteLength(css) });\n // A <style> ends at the first `</style`, whatever CSS thinks it is inside.\n // `\\/` is the same character to CSS, and not that to the HTML parser.\n return `<style>${css.replace(/<\\/(style)/gi, '<\\\\/$1')}</style>`;\n });\n return { html: rewritten, inPage, left };\n};\n\n// The same, over the built folder: its index.html rewritten where it stands.\n// Nothing to do (no page, no stylesheet link) is nothing done.\nexport const writeStylesheetIntoPage = (dist: string): StylesheetReport => {\n const page = join(dist, 'index.html');\n if (!existsSync(page)) return { inPage: [], left: [] };\n const base = resolve(dist);\n const read = (href: string): string | undefined => {\n const file = resolve(base, `.${href}`);\n return file.startsWith(base + sep) && existsSync(file) && statSync(file).isFile() ? readFileSync(file, 'utf8') : undefined;\n };\n const html = readFileSync(page, 'utf8');\n const rewrite = stylesheetInPage(html, read);\n if (rewrite.html !== html) writeFileSync(page, rewrite.html);\n return { inPage: rewrite.inPage, left: rewrite.left };\n};\n","import { spawn, spawnSync } from 'node:child_process';\nimport { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { dirname, join, resolve } from 'node:path';\nimport { serve } from '@hono/node-server';\nimport type { ExportedDocument } from '@niscorp/moss';\nimport { devServer } from './dev';\nimport { isShellProject, loadProject } from './project';\nimport type { NiscMossProject, NiscProject, NiscShellProject } from './project';\nimport { defaultPaths, fileOf, routeTable } from './routes';\nimport { shellRouteTable, shellSite, surveyShell } from './shell-site';\nimport type { ShellRouteReport } from './shell-site';\nimport { siteHandler } from './site';\nimport { writeStylesheetIntoPage } from './stylesheet';\n\n// ═══════════════════════════════════════════════════════════════\n// What `nisc` does. Each command is the app's own machinery, run in order:\n//\n// dev the app's own vite, with the app server inside it when it has one\n// build bundle the terminal and write its stylesheet into its page, then\n// draw every path once and say how each is served — a file, or a server\n// export build, then write every path as a file: the whole site as a folder\n// start serve the built terminal from the app's own process, pages drawn —\n// compressed, and with what a browser may keep said (./site)\n// check the app's check suite\n// migrate apply the tables' pending migrations, if the app's entries fit what\n// they leave\n//\n// Nothing here knows an app. How it boots and how a screen is drawn come from\n// its nisc.config.ts. An app behind moss hands over its server, and which paths\n// exist and what each needs come from that (`server.pages`, `exportDocuments`).\n// An app with its own shell hands over its boot, and every path is drawn from\n// that and checked (./shell-site). Moss is loaded only for the first kind — an\n// app without it does not have it installed.\n// ═══════════════════════════════════════════════════════════════\n\nexport type CommandOptions = {\n // the app's root (where nisc.config.ts is)\n root: string;\n // export: where the files go (default `out`), relative to the root\n out?: string;\n // export: write the site even though some path wants a server behind it\n allowLive?: boolean;\n // start: the port (default $PORT, then 8787)\n port?: number;\n // build/export: skip the bundler (the terminal is already built)\n skipBundle?: boolean;\n // migrate: do all of it, then roll it back\n dryRun?: boolean;\n print?: (line: string) => void;\n};\n\nconst say = (options: CommandOptions): ((line: string) => void) => options.print ?? ((line) => console.log(line));\n\n// A tool the APP has installed, found from the app's own root — the command\n// carries no bundler and no test runner of its own.\nconst toolOf = (root: string, name: string, bin: string): string => {\n const require = createRequire(join(root, 'package.json'));\n let manifestPath: string;\n try {\n manifestPath = require.resolve(`${name}/package.json`);\n } catch {\n throw new Error(`nisc: this app has no ${name} installed (looked from ${root}).`);\n }\n const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf8'));\n const bins: unknown = manifest !== null && typeof manifest === 'object' ? Reflect.get(manifest, 'bin') : undefined;\n const relative: unknown = typeof bins === 'string' ? bins : bins !== null && typeof bins === 'object' ? Reflect.get(bins, bin) : undefined;\n if (typeof relative !== 'string') throw new Error(`nisc: ${name} ships no \"${bin}\" command.`);\n return join(dirname(manifestPath), relative);\n};\n\nconst distOf = (root: string, project: NiscProject): string => resolve(root, project.dist ?? 'dist');\n\n// The app's own vite, and then the one thing done to what it wrote: the page's\n// stylesheet goes into the page (./stylesheet). A terminal that is already built\n// (`skipBundle`) is taken as it is.\nconst bundle = (options: CommandOptions, project: NiscProject): void => {\n const result = spawnSync(process.execPath, [toolOf(options.root, 'vite', 'vite'), 'build'], { cwd: options.root, stdio: 'inherit' });\n if (result.status !== 0) throw new Error('nisc: the bundler failed — nothing was drawn.');\n if (project.stylesheet === 'file') return;\n const print = say(options);\n const { inPage, left } = writeStylesheetIntoPage(distOf(options.root, project));\n if (inPage.length + left.length > 0) print('');\n for (const sheet of inPage) print(`nisc: ${sheet.href} is in the page (${(sheet.bytes / 1024).toFixed(1)} kB) — one response paints it`);\n for (const sheet of left) print(`nisc: ${sheet.href} stays a file — ${sheet.why}`);\n if (inPage.length > 0) print(\" A Content-Security-Policy that forbids inline styles would refuse it: `stylesheet: 'file'` in nisc.config.ts keeps it a file.\");\n};\n\n// `start` tells browsers to keep what is under /assets/ for a year — right for\n// what the bundler writes there, named by its content. The bundler also copies\n// the app's public/ as it is, so a file of the app's own under public/assets/\n// would be kept just as long, under a name that says nothing about its content.\nconst warnOfOwnAssets = (options: CommandOptions): void => {\n if (!existsSync(join(options.root, 'public', 'assets'))) return;\n say(options)('nisc: public/assets/ holds files of your own. `nisc start` has browsers keep everything under /assets/ for a year, so a change to one of them will not be seen under the same name — keep them elsewhere in public/.');\n};\n\n// index.html says where the page lives, once — and every path is written from\n// it. With more than one path and no `site`, each file would name that one\n// address as its own, which tells a search engine they are all copies of it.\nconst warnOfOneAddress = (options: CommandOptions, project: NiscProject, template: string, paths: number): void => {\n if (project.site !== undefined || paths < 2 || !/<link\\b[^>]*\\brel\\s*=\\s*[\"']?canonical\\b/i.test(template)) return;\n say(options)('');\n say(options)(`nisc: index.html names one canonical address and this app has ${paths} paths — every file would say it lives there.`);\n say(options)(' `site: \"https://…\"` in nisc.config.ts gives each path its own.');\n};\n\n// Stand the app up, draw every path once for nobody, let the app go.\nconst templateOf =(options: CommandOptions, project: NiscProject): string => {\n const template = join(distOf(options.root, project), 'index.html');\n if (!existsSync(template)) throw new Error(`nisc: no built terminal at ${template} — run \\`nisc build\\`.`);\n return readFileSync(template, 'utf8');\n};\n\nconst survey = async (options: CommandOptions, project: NiscMossProject): Promise<ExportedDocument[]> => {\n const template = templateOf(options, project);\n const { exportDocuments } = await import('@niscorp/moss');\n const booted = await project.boot();\n try {\n const paths = project.paths === undefined ? defaultPaths(booted.server.pages) : await project.paths(booted.server);\n return await exportDocuments({\n server: booted.server,\n template,\n draw: project.draw,\n ...(project.htmlAttributes !== undefined ? { htmlAttributes: project.htmlAttributes } : {}),\n ...(project.site !== undefined ? { site: project.site } : {}),\n ...(project.tokenKey !== undefined ? { tokenKey: project.tokenKey } : {}),\n paths,\n });\n } finally {\n await booted.close?.();\n }\n};\n\n// What a build found, either way round: every path, and whether the build holds.\nexport type BuildResult =\n | { kind: 'moss'; ok: boolean; routes: ExportedDocument[] }\n | { kind: 'shell'; ok: boolean; routes: ShellRouteReport[] };\n\nconst buildShell = async (options: CommandOptions, project: NiscShellProject): Promise<BuildResult> => {\n const template = templateOf(options, project);\n const routes = await surveyShell(options.root, project, template);\n say(options)('');\n say(options)(shellRouteTable(routes));\n warnOfOneAddress(options, project, template, routes.length);\n return { kind: 'shell', ok: routes.every((route) => route.problems.length === 0), routes };\n};\n\nexport const build = async (options: CommandOptions): Promise<BuildResult> => {\n const project = await loadProject(options.root);\n if (options.skipBundle !== true) bundle(options, project);\n warnOfOwnAssets(options);\n if (isShellProject(project)) return buildShell(options, project);\n const routes = await survey(options, project);\n say(options)('');\n say(options)(routeTable(routes));\n warnOfOneAddress(options, project, templateOf(options, project), routes.length);\n return { kind: 'moss', ok: routes.every((route) => route.drawn), routes };\n};\n\nconst write = (options: CommandOptions, project: NiscProject, out: string, routes: readonly { path: string; html: string }[]): void => {\n rmSync(out, { recursive: true, force: true });\n cpSync(distOf(options.root, project), out, { recursive: true });\n for (const route of routes) {\n const file = join(out, fileOf(route.path));\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, route.html);\n }\n say(options)('');\n say(options)(`nisc: ${routes.length} paths written to ${out}`);\n};\n\n// The whole site as a folder. A path that wants a server behind it is not\n// something a folder can be — so unless the caller says a server will stand\n// beside the files (`allowLive`), nothing is written and the table says why.\n//\n// An app with its own shell has no such path: the shell is in the page, so a\n// folder is all of it. What stops ITS files is a check that did not hold.\nexport const exportSite = async (options: CommandOptions): Promise<{ written: boolean; result: BuildResult; out: string }> => {\n const project = await loadProject(options.root);\n const result = await build(options);\n const out = resolve(options.root, options.out ?? 'out');\n if (result.kind === 'shell') {\n if (!result.ok) {\n const failed = result.routes.filter((route) => route.problems.length > 0);\n say(options)('');\n say(options)(`nisc: ${failed.length} of ${result.routes.length} paths did not hold (${failed.map((route) => route.path).join(', ')}). Nothing was written.`);\n return { written: false, result, out };\n }\n write(options, project, out, result.routes);\n return { written: true, result, out };\n }\n const routes = result.routes;\n const live = routes.filter((route) => route.live || !route.drawn);\n if (live.length > 0 && options.allowLive !== true) {\n say(options)('');\n say(options)(`nisc: ${live.length} of ${routes.length} paths cannot be a file alone (${live.map((route) => route.path).join(', ')}).`);\n say(options)(' Nothing was written. With a server beside the files they still work: `nisc export --allow-live`.');\n return { written: false, result, out };\n }\n write(options, project, out, routes);\n return { written: true, result, out };\n};\n\nconst listening = async (httpServer: ReturnType<typeof serve>, options: CommandOptions): Promise<string> => {\n await new Promise<void>((up) => httpServer.once('listening', () => up()));\n const address = httpServer.address();\n const port = address !== null && typeof address === 'object' ? (address satisfies AddressInfo).port : options.port;\n return `http://localhost:${port}`;\n};\n\nexport const start = async (options: CommandOptions): Promise<{ url: string; close: () => Promise<void> }> => {\n const project = await loadProject(options.root);\n const dist = distOf(options.root, project);\n if (!existsSync(join(dist, 'index.html'))) throw new Error(`nisc: no built terminal in ${dist} — run \\`nisc build\\`.`);\n const port = options.port ?? Number(process.env['PORT'] ?? 8787);\n if (isShellProject(project)) {\n // no server shell, no socket: each path's first answer is its screen, drawn\n // from a boot of the app's own, and the page's shell takes it from there\n const httpServer = serve({ fetch: siteHandler(shellSite(project, dist)), port });\n const url = await listening(httpServer, options);\n say(options)(`nisc: serving ${url} — the built app, each path’s first screen drawn; the shell is the page’s own`);\n return { url, close: async () => void httpServer.close() };\n }\n const { attachSocket, mountSite, MOSS_PATHS } = await import('@niscorp/moss/node');\n const booted = await project.boot();\n await project.routes?.(booted.server);\n mountSite(booted.server, {\n dist,\n draw: project.draw,\n ...(project.htmlAttributes !== undefined ? { htmlAttributes: project.htmlAttributes } : {}),\n ...(project.site !== undefined ? { site: project.site } : {}),\n ...(project.tokenKey !== undefined ? { tokenKey: project.tokenKey } : {}),\n });\n // what the app server answers itself is its own to say; the rest is the site\n const httpServer = serve({ fetch: siteHandler(booted.server.fetch, { except: MOSS_PATHS }), port });\n attachSocket(httpServer, booted.server.socket);\n const url = await listening(httpServer, options);\n say(options)(`nisc: serving ${url} — the built terminal, its pages drawn; the socket at /socket`);\n return {\n url,\n close: async () => {\n httpServer.close();\n await booted.close?.();\n },\n };\n};\n\n// The tables, moved — by moss (`migrateTables`), which refuses a run that would\n// leave an entry of the manifest not fitting. A refusal is thrown with its\n// reasons, and nothing was applied. What a run that lands took away is said.\nexport const migrate = async (options: CommandOptions): Promise<void> => {\n const project = await loadProject(options.root);\n if (isShellProject(project) || project.app === undefined || project.runtime === undefined) {\n throw new Error('nisc: `nisc migrate` needs `app` and `runtime` in nisc.config.ts — the manifest, and the environment it runs on.');\n }\n const { migrateTables } = await import('@niscorp/moss');\n const print = say(options);\n const isDryRun = options.dryRun === true;\n const runtime = await project.runtime();\n try {\n const report = await migrateTables(runtime, project.app, isDryRun ? { dryRun: true } : {});\n if (report.applied.length === 0) print('nisc: nothing to migrate');\n else print(isDryRun ? `nisc: would apply ${report.applied.length} — rolled back, nothing changed` : `nisc: applied ${report.applied.length}`);\n for (const migration of report.applied) print(` ${migration.ref} ${migration.description}`);\n if (report.removed.length > 0) print(`nisc: this run removes ${report.removed.join(', ')}`);\n if (report.retyped.length > 0) print(`nisc: this run changes the type of ${report.retyped.join(', ')}`);\n if (report.alreadyBroken.length > 0) print('nisc: not fitting before this run either, and seeded as they are — said, not refused:');\n for (const entry of report.alreadyBroken) print(` ${entry}`);\n } finally {\n await runtime.close?.();\n }\n};\n\n// The two that hand over to a tool of the app's own and stay out of the way.\nconst handOver = (options: CommandOptions, tool: string, args: readonly string[]): Promise<number> =>\n new Promise((done) => {\n const child = spawn(process.execPath, [tool, ...args], { cwd: options.root, stdio: 'inherit' });\n child.once('exit', (code) => done(code ?? 1));\n });\n\nexport const dev = (options: CommandOptions): Promise<{ url: string; close: () => Promise<void> }> =>\n devServer({ root: options.root, ...(options.port !== undefined ? { port: options.port } : {}) });\n\nexport const check = async (options: CommandOptions): Promise<number> => {\n const project = await loadProject(options.root);\n return handOver(options, toolOf(options.root, 'tsx', 'tsx'), [project.checks ?? 'src/dev/all-checks.ts']);\n};\n","import { resolve } from 'node:path';\nimport { build, check, dev, exportSite, migrate, start } from './commands';\nimport type { CommandOptions } from './commands';\n\n// ═══════════════════════════════════════════════════════════════\n// nisc — the command line. It parses, and hands over to ./commands.\n// ═══════════════════════════════════════════════════════════════\n\nconst USAGE = `nisc — the command for a nisc application\n\n nisc dev the app's dev server — its vite, with the app server inside\n nisc build bundle the app, draw every path, and check what was drawn\n nisc export build, then write every path as a file (the site as a folder)\n nisc start serve the built app, each path's first screen drawn\n nisc check the app's check suite\n nisc migrate apply the tables' pending migrations, if the app's entries fit the result\n\n --root <dir> the app's root (default: here) — where nisc.config.ts is\n --out <dir> export: where the files go (default: out)\n --allow-live export: write even though some path wants a server behind it\n --port <n> dev, start: the port (start: $PORT, then 8787)\n --skip-bundle build, export: the terminal is already built\n --check migrate: do all of it, then roll it back\n\nAn app says in nisc.config.ts how it boots and how one of its screens is drawn.\nBehind moss (boot + draw): which paths exist and what each needs is read off the\nserver. With its own shell (shell + draw + adopt): every path is drawn from the\napp's own boot, and a file is written only if the page's boot picks it up clean.`;\n\nconst valueAfter = (args: readonly string[], flag: string): string | undefined => {\n const at = args.indexOf(flag);\n return at < 0 ? undefined : args[at + 1];\n};\n\nconst main = async (): Promise<number> => {\n const [command, ...args] = process.argv.slice(2);\n const port = valueAfter(args, '--port');\n const out = valueAfter(args, '--out');\n const options: CommandOptions = {\n root: resolve(valueAfter(args, '--root') ?? process.cwd()),\n ...(out !== undefined ? { out } : {}),\n ...(port !== undefined ? { port: Number(port) } : {}),\n allowLive: args.includes('--allow-live'),\n skipBundle: args.includes('--skip-bundle'),\n };\n\n if (command === 'dev' || command === 'start') {\n const served = command === 'dev' ? await dev(options) : await start(options);\n const stop = (): void => {\n void served.close().finally(() => process.exit(0));\n };\n process.on('SIGINT', stop);\n process.on('SIGTERM', stop);\n // stays up until it is told to stop\n return new Promise<number>(() => undefined);\n }\n if (command === 'check') return check(options);\n if (command === 'migrate') {\n await migrate({ ...options, dryRun: args.includes('--check') });\n return 0;\n }\n if (command === 'build') {\n return (await build(options)).ok ? 0 : 1;\n }\n if (command === 'export') return (await exportSite(options)).written ? 0 : 1;\n console.log(USAGE);\n return command === undefined || command === 'help' || command === '--help' ? 0 : 1;\n};\n\nmain().then(\n // An app's own handles (a database, a timer) must not keep a finished command\n // open: a command that is done says so and leaves.\n (code) => process.exit(code),\n (error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exit(1);\n },\n);\n"]}
1
+ {"version":3,"sources":["../src/dev.ts","../src/routes.ts","../src/shell-site.ts","../src/site.ts","../src/stylesheet.ts","../src/commands.ts","../src/cli.ts"],"names":["dev","join","pad","why","existsSync","resolve","sep","statSync","readFileSync","writeFileSync","require","createRequire","dirname","spawnSync","rmSync","httpServer","url"],"mappings":";;;;;;;;;;;;;AAgBA,IAAM,SAAA,GAAY,CAAC,KAAA,KACjB,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,OAAA,CAAQ,GAAA,CAAI,KAAA,EAAO,cAAc,CAAA,KAAM,UAAA;AAE/F,IAAM,MAAA,GAAS,OAAO,IAAA,KAAmC;AACvD,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,cAAc,IAAA,CAAK,IAAA,EAAM,cAAc,CAAC,CAAA,CAAE,QAAQ,MAAM,CAAA;AAAA,EAClE,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kDAAA,EAAqD,IAAI,CAAA,EAA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EAAA,IAAI,YAAY,SAAA,EAAW;AACzB,IAAA,MAAM,OAAA,CAAQ,EAAE,GAAG,OAAA,EAAS,QAAQ,IAAA,CAAK,QAAA,CAAS,SAAS,CAAA,EAAG,CAAA;AAC9D,IAAA,OAAO,CAAA;AAAA,EACT;AACA,EAAA,IAAI,YAAY,OAAA,EAAS;AACvB,IAAA,OAAA,CAAQ,MAAM,KAAA,CAAM,OAAO,CAAA,EAAG,KAAK,CAAA,GAAI,CAAA;AAAA,EACzC;AACA,EAAA,IAAI,OAAA,KAAY,UAAU,OAAA,CAAQ,MAAM,WAAW,OAAO,CAAA,EAAG,UAAU,CAAA,GAAI,CAAA;AAC3E,EAAA,OAAA,CAAQ,IAAI,KAAK,CAAA;AACjB,EAAA,OAAO,YAAY,MAAA,IAAa,OAAA,KAAY,MAAA,IAAU,OAAA,KAAY,WAAW,CAAA,GAAI,CAAA;AACnF,CAAA;AAEA,IAAA,EAAK,CAAE,IAAA;AAAA;AAAA;AAAA,EAGL,CAAC,IAAA,KAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA;AAAA,EAC3B,CAAC,KAAA,KAAmB;AAClB,IAAA,OAAA,CAAQ,KAAA,CAAM,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,UAAU,KAAK,CAAA;AAC5D,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"cli.js","sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { configFileOf, isProject, isShellProject, loadProject } from './project';\nimport type { NiscMossProject } from './project';\n\n// Declared here rather than imported: vite is the app's dependency, and so are\n// its types.\ntype DevServer = {\n listen: () => Promise<unknown>;\n printUrls: () => void;\n resolvedUrls: { local: string[] } | null;\n close: () => Promise<void>;\n};\ntype ViteApi = { createServer: (config: { root: string; server?: { port: number }; plugins: unknown[] }) => Promise<DevServer> };\n\nconst isViteApi = (value: unknown): value is ViteApi =>\n value !== null && typeof value === 'object' && typeof Reflect.get(value, 'createServer') === 'function';\n\nconst viteOf = async (root: string): Promise<ViteApi> => {\n let entry: string;\n try {\n entry = createRequire(join(root, 'package.json')).resolve('vite');\n } catch {\n throw new Error(`nisc: this app has no vite installed (looked from ${root}).`);\n }\n const loaded: unknown = await import(pathToFileURL(entry).href);\n if (!isViteApi(loaded)) throw new Error(`nisc: ${entry} is not vite.`);\n return loaded;\n};\n\n// Read once, when the command starts: a change to one takes a restart of\n// `nisc dev`, unlike the rest of the config, which vite reloads.\nexport const devPluginOptionsOf = (dev: NiscMossProject['dev']): { watch?: RegExp; owned?: RegExp; signInFromNetwork?: boolean } => ({\n ...(dev?.watch !== undefined ? { watch: dev.watch } : {}),\n ...(dev?.owned !== undefined ? { owned: dev.owned } : {}),\n ...(dev?.signInFromNetwork !== undefined ? { signInFromNetwork: dev.signInFromNetwork } : {}),\n});\n\nconst mossPlugin = async (configFile: string, dev: NiscMossProject['dev']): Promise<unknown> => {\n const { mossDev } = await import('@niscorp/moss/vite');\n return mossDev({\n label: 'nisc',\n ...devPluginOptionsOf(dev),\n app: async (load) => {\n const loaded = await load(`/${configFile}`);\n const project: unknown = Reflect.get(loaded, 'project');\n if (!isProject(project) || isShellProject(project)) throw new Error(`nisc: ${configFile} no longer describes an app behind moss.`);\n const booted = await project.boot();\n try {\n await booted.server.checkFunctions();\n } catch (error) {\n await booted.close?.();\n throw error;\n }\n const signIn = project.dev?.signIn;\n return {\n server: booted.server,\n ...(booted.close !== undefined ? { close: booted.close } : {}),\n draw: project.draw,\n ...(project.htmlAttributes !== undefined ? { htmlAttributes: project.htmlAttributes } : {}),\n ...(project.site !== undefined ? { site: project.site } : {}),\n ...(project.tokenKey !== undefined ? { tokenKey: project.tokenKey } : {}),\n ...(signIn !== undefined ? { signIn: (who: string) => signIn(booted.server, who) } : {}),\n };\n },\n });\n};\n\nexport const devServer = async (options: { root: string; port?: number }): Promise<{ url: string; close: () => Promise<void> }> => {\n const project = await loadProject(options.root);\n const configFile = configFileOf(options.root);\n const vite = await viteOf(options.root);\n const server = await vite.createServer({\n root: options.root,\n ...(options.port !== undefined ? { server: { port: options.port } } : {}),\n plugins: isShellProject(project) || configFile === undefined ? [] : [await mossPlugin(configFile, project.dev)],\n });\n await server.listen();\n server.printUrls();\n const url = server.resolvedUrls?.local[0] ?? `http://localhost:${options.port ?? 5173}/`;\n return { url, close: () => server.close() };\n};\n","export type RouteReport = {\n path: string;\n page?: string;\n drawn: boolean;\n live: boolean;\n why: readonly string[];\n drawnWith: readonly string[];\n settled: boolean;\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n","import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n html: string;\n problems: readonly string[];\n actions: readonly string[];\n opensWith: readonly string[];\n callsLater: readonly string[];\n listens: readonly string[];\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// The adoption check runs in a process of its own (./adopt): a DOM has to exist\n// before the app's modules load, because an adapter decides what it is running\n// in when it is imported.\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","import { constants, createBrotliCompress, createGzip } from 'node:zlib';\nimport type { BrotliCompress, Gzip } from 'node:zlib';\n\nexport type SiteHandler<Rest extends readonly unknown[] = []> = (request: Request, ...rest: Rest) => Response | Promise<Response>;\n\nexport type SiteOptions = {\n except?: RegExp;\n};\n\nconst KEPT_PATHS = /^\\/assets\\//;\nconst KEPT_FOREVER = 'public, max-age=31536000, immutable';\n\nexport const withCaching =\n <Rest extends readonly unknown[]>(handler: SiteHandler<Rest>, options: SiteOptions = {}): SiteHandler<Rest> =>\n async (request, ...rest) => {\n const response = await handler(request, ...rest);\n if ((request.method !== 'GET' && request.method !== 'HEAD') || response.status !== 200) return response;\n const path = new URL(request.url).pathname;\n if (options.except?.test(path) === true) return response;\n if (response.headers.has('cache-control')) return response;\n\n const headers = new Headers(response.headers);\n if (KEPT_PATHS.test(path)) {\n headers.set('cache-control', KEPT_FOREVER);\n return new Response(response.body, { status: 200, headers });\n }\n headers.set('cache-control', 'no-cache');\n const [since, modified] = [request.headers.get('if-modified-since'), headers.get('last-modified')];\n if (since !== null && modified !== null && Date.parse(since) >= Date.parse(modified)) {\n await response.body?.cancel();\n headers.delete('content-length');\n return new Response(null, { status: 304, headers });\n }\n return new Response(response.body, { status: 200, headers });\n };\n\nconst COMPRESSIBLE = /^(text\\/(?!event-stream)|application\\/(json|javascript|xml|manifest\\+json|wasm)|image\\/svg\\+xml)/i;\nconst SMALL_BYTES = 1024;\n// fast enough to do per answer, and already smaller than gzip's best\nconst BROTLI_QUALITY = 5;\n\ntype Encoding = 'br' | 'gzip';\n\nconst encodingFor = (header: string | null): Encoding | undefined => {\n const offered = new Map<string, number>();\n for (const part of (header ?? '').toLowerCase().split(',')) {\n const [name = '', ...parameters] = part.split(';').map((piece) => piece.trim());\n const weight = parameters.find((parameter) => parameter.startsWith('q='));\n if (name !== '') offered.set(name, weight === undefined ? 1 : Number(weight.slice(2)));\n }\n if ((offered.get('br') ?? 0) > 0) return 'br';\n if ((offered.get('gzip') ?? 0) > 0) return 'gzip';\n return undefined;\n};\n\n// Flushed after every piece written: that is what keeps a streamed answer streaming.\nconst compressorFor = (encoding: Encoding): BrotliCompress | Gzip =>\n encoding === 'br'\n ? createBrotliCompress({ flush: constants.BROTLI_OPERATION_FLUSH, params: { [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY } })\n : createGzip({ flush: constants.Z_SYNC_FLUSH });\n\nconst compressedBody = (source: ReadableStream<Uint8Array>, encoding: Encoding, whole?: (bytes: Buffer<ArrayBuffer>) => void): ReadableStream<Uint8Array> => {\n const reader = source.getReader();\n const compressor = compressorFor(encoding);\n const pieces: Buffer[] = [];\n let isLetGo = false;\n let finished: () => void = () => undefined;\n const ended = new Promise<void>((done) => {\n finished = done;\n });\n return new ReadableStream<Uint8Array>({\n start: (controller) => {\n compressor.on('data', (piece: Buffer) => {\n if (isLetGo) return;\n if (whole !== undefined) pieces.push(piece);\n controller.enqueue(piece);\n });\n compressor.on('end', () => {\n if (!isLetGo) {\n whole?.(Buffer.concat(pieces));\n controller.close();\n }\n finished();\n });\n compressor.on('error', (error) => {\n if (!isLetGo) controller.error(error);\n finished();\n });\n },\n pull: async () => {\n const { done, value } = await reader.read().catch((error: unknown) => {\n compressor.destroy();\n throw error;\n });\n if (done) {\n compressor.end();\n return ended;\n }\n return new Promise<void>((taken) => {\n compressor.write(value, () => taken());\n });\n },\n cancel: async (reason) => {\n isLetGo = true;\n compressor.destroy();\n await reader.cancel(reason);\n },\n });\n};\n\nexport const withCompression = <Rest extends readonly unknown[]>(handler: SiteHandler<Rest>, options: SiteOptions = {}): SiteHandler<Rest> => {\n // No eviction: only an answer that says it will never change is remembered,\n // which is bounded by what the built folder holds under assets/.\n const remembered = new Map<string, Buffer<ArrayBuffer>>();\n return async (request, ...rest) => {\n const response = await handler(request, ...rest);\n if (request.method !== 'GET' || response.status !== 200 || response.body === null) return response;\n const path = new URL(request.url).pathname;\n if (options.except?.test(path) === true) return response;\n if (!COMPRESSIBLE.test(response.headers.get('content-type') ?? '')) return response;\n if (response.headers.has('content-encoding') || /no-transform/i.test(response.headers.get('cache-control') ?? '')) return response;\n\n // From here the answer depends on what was asked for, compressed or not: a\n // cache has to be told.\n const headers = new Headers(response.headers);\n const varies = (headers.get('vary') ?? '').toLowerCase().split(',').map((name) => name.trim());\n if (!varies.includes('accept-encoding')) headers.append('vary', 'Accept-Encoding');\n\n const encoding = encodingFor(request.headers.get('accept-encoding'));\n const length = headers.get('content-length');\n if (encoding === undefined || (length !== null && Number(length) < SMALL_BYTES)) return new Response(response.body, { status: 200, headers });\n\n headers.set('content-encoding', encoding);\n headers.delete('content-length');\n // A strong etag promises the exact bytes, and compression changes them.\n const etag = headers.get('etag');\n if (etag !== null && !etag.startsWith('W/')) headers.set('etag', `W/${etag}`);\n\n if (!/\\bimmutable\\b/i.test(headers.get('cache-control') ?? '')) return new Response(compressedBody(response.body, encoding), { status: 200, headers });\n const key = `${encoding} ${path} ${headers.get('last-modified') ?? ''}`;\n const known = remembered.get(key);\n if (known === undefined) return new Response(compressedBody(response.body, encoding, (bytes) => remembered.set(key, bytes)), { status: 200, headers });\n await response.body.cancel();\n headers.set('content-length', String(known.length));\n return new Response(known, { status: 200, headers });\n };\n};\n\nexport const siteHandler = <Rest extends readonly unknown[]>(handler: SiteHandler<Rest>, options: SiteOptions = {}): SiteHandler<Rest> =>\n withCompression(withCaching(handler, options), options);\n","import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';\nimport { join, resolve, sep } from 'node:path';\n\nexport type StylesheetReport = {\n inPage: readonly { href: string; bytes: number }[];\n left: readonly { href: string; why: string }[];\n};\n\nexport type StylesheetRewrite = StylesheetReport & { html: string };\n\nconst attributesOf = (tag: string): Record<string, string> => {\n const found: Record<string, string> = {};\n for (const match of tag.slice(5).matchAll(/([^\\s\"'<>/=]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+)))?/g)) {\n const name = match[1];\n if (name !== undefined) found[name.toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? '';\n }\n return found;\n};\n\nconst PLAIN = new Set(['rel', 'href', 'crossorigin']);\n\nconst isPortableUrl = (url: string): boolean => url === '' || /^(\\/|data:|blob:|https?:|#)/i.test(url);\n\nconst whyStylesheetStays = (css: string): string | undefined => {\n if (/@import\\b/i.test(css)) return 'it imports another stylesheet';\n for (const match of css.matchAll(/url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)]*?))\\s*\\)/gi)) {\n const url = (match[1] ?? match[2] ?? match[3] ?? '').trim();\n if (!isPortableUrl(url)) return `it names a file relative to itself (${url})`;\n }\n return undefined;\n};\n\nexport const stylesheetInPage = (html: string, read: (href: string) => string | undefined): StylesheetRewrite => {\n const inPage: { href: string; bytes: number }[] = [];\n const left: { href: string; why: string }[] = [];\n const rewritten = html.replace(/<link\\b[^>]*>/gi, (tag) => {\n const attributes = attributesOf(tag);\n if ((attributes['rel'] ?? '').toLowerCase() !== 'stylesheet') return tag;\n const href = attributes['href'] ?? '';\n const stays = (why: string): string => {\n left.push({ href, why });\n return tag;\n };\n const extra = Object.keys(attributes).filter((name) => !PLAIN.has(name));\n if (extra.length > 0) return stays(`its link says more than where it is (${extra.join(', ')})`);\n if (!href.startsWith('/') || href.startsWith('//') || /[?#]/.test(href)) return stays('it is not a path into the built folder');\n const css = read(href);\n if (css === undefined) return stays('it is not in the built folder');\n const why = whyStylesheetStays(css);\n if (why !== undefined) return stays(why);\n inPage.push({ href, bytes: Buffer.byteLength(css) });\n // A <style> ends at the first `</style`, whatever CSS thinks it is inside.\n // `\\/` is the same character to CSS, and not that to the HTML parser.\n return `<style>${css.replace(/<\\/(style)/gi, '<\\\\/$1')}</style>`;\n });\n return { html: rewritten, inPage, left };\n};\n\nexport const writeStylesheetIntoPage = (dist: string): StylesheetReport => {\n const page = join(dist, 'index.html');\n if (!existsSync(page)) return { inPage: [], left: [] };\n const base = resolve(dist);\n const read = (href: string): string | undefined => {\n const file = resolve(base, `.${href}`);\n return file.startsWith(base + sep) && existsSync(file) && statSync(file).isFile() ? readFileSync(file, 'utf8') : undefined;\n };\n const html = readFileSync(page, 'utf8');\n const rewrite = stylesheetInPage(html, read);\n if (rewrite.html !== html) writeFileSync(page, rewrite.html);\n return { inPage: rewrite.inPage, left: rewrite.left };\n};\n","import { spawn, spawnSync } from 'node:child_process';\nimport { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { dirname, join, resolve } from 'node:path';\nimport { serve } from '@hono/node-server';\nimport type { ExportedDocument } from '@niscorp/moss';\nimport { devServer } from './dev';\nimport { isShellProject, loadProject } from './project';\nimport type { NiscMossProject, NiscProject, NiscShellProject } from './project';\nimport { defaultPaths, fileOf, routeTable } from './routes';\nimport { shellRouteTable, shellSite, surveyShell } from './shell-site';\nimport type { ShellRouteReport } from './shell-site';\nimport { siteHandler } from './site';\nimport { writeStylesheetIntoPage } from './stylesheet';\n\n// Moss is loaded by a dynamic import, and only for an app behind it: an app\n// with its own shell does not have it installed.\n\nexport type CommandOptions = {\n root: string;\n out?: string;\n allowLive?: boolean;\n port?: number;\n skipBundle?: boolean;\n dryRun?: boolean;\n print?: (line: string) => void;\n};\n\nconst say = (options: CommandOptions): ((line: string) => void) => options.print ?? ((line) => console.log(line));\n\nconst toolOf = (root: string, name: string, bin: string): string => {\n const require = createRequire(join(root, 'package.json'));\n let manifestPath: string;\n try {\n manifestPath = require.resolve(`${name}/package.json`);\n } catch {\n throw new Error(`nisc: this app has no ${name} installed (looked from ${root}).`);\n }\n const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf8'));\n const bins: unknown = manifest !== null && typeof manifest === 'object' ? Reflect.get(manifest, 'bin') : undefined;\n const relative: unknown = typeof bins === 'string' ? bins : bins !== null && typeof bins === 'object' ? Reflect.get(bins, bin) : undefined;\n if (typeof relative !== 'string') throw new Error(`nisc: ${name} ships no \"${bin}\" command.`);\n return join(dirname(manifestPath), relative);\n};\n\nconst distOf = (root: string, project: NiscProject): string => resolve(root, project.dist ?? 'dist');\n\nconst bundle = (options: CommandOptions, project: NiscProject): void => {\n const result = spawnSync(process.execPath, [toolOf(options.root, 'vite', 'vite'), 'build'], { cwd: options.root, stdio: 'inherit' });\n if (result.status !== 0) throw new Error('nisc: the bundler failed — nothing was drawn.');\n if (project.stylesheet === 'file') return;\n const print = say(options);\n const { inPage, left } = writeStylesheetIntoPage(distOf(options.root, project));\n if (inPage.length + left.length > 0) print('');\n for (const sheet of inPage) print(`nisc: ${sheet.href} is in the page (${(sheet.bytes / 1024).toFixed(1)} kB) — one response paints it`);\n for (const sheet of left) print(`nisc: ${sheet.href} stays a file — ${sheet.why}`);\n if (inPage.length > 0) print(\" A Content-Security-Policy that forbids inline styles would refuse it: `stylesheet: 'file'` in nisc.config.ts keeps it a file.\");\n};\n\nconst warnOfOwnAssets = (options: CommandOptions): void => {\n if (!existsSync(join(options.root, 'public', 'assets'))) return;\n say(options)('nisc: public/assets/ holds files of your own. `nisc start` has browsers keep everything under /assets/ for a year, so a change to one of them will not be seen under the same name — keep them elsewhere in public/.');\n};\n\nconst warnOfOneAddress = (options: CommandOptions, project: NiscProject, template: string, paths: number): void => {\n if (project.site !== undefined || paths < 2 || !/<link\\b[^>]*\\brel\\s*=\\s*[\"']?canonical\\b/i.test(template)) return;\n say(options)('');\n say(options)(`nisc: index.html names one canonical address and this app has ${paths} paths — every file would say it lives there.`);\n say(options)(' `site: \"https://…\"` in nisc.config.ts gives each path its own.');\n};\n\nconst templateOf =(options: CommandOptions, project: NiscProject): string => {\n const template = join(distOf(options.root, project), 'index.html');\n if (!existsSync(template)) throw new Error(`nisc: no built terminal at ${template} — run \\`nisc build\\`.`);\n return readFileSync(template, 'utf8');\n};\n\nconst survey = async (options: CommandOptions, project: NiscMossProject): Promise<ExportedDocument[]> => {\n const template = templateOf(options, project);\n const { exportDocuments } = await import('@niscorp/moss');\n const booted = await project.boot();\n try {\n await booted.server.checkFunctions();\n const paths = project.paths === undefined ? defaultPaths(booted.server.pages) : await project.paths(booted.server);\n return await exportDocuments({\n server: booted.server,\n template,\n draw: project.draw,\n ...(project.htmlAttributes !== undefined ? { htmlAttributes: project.htmlAttributes } : {}),\n ...(project.site !== undefined ? { site: project.site } : {}),\n ...(project.tokenKey !== undefined ? { tokenKey: project.tokenKey } : {}),\n paths,\n });\n } finally {\n await booted.close?.();\n }\n};\n\nexport type BuildResult =\n | { kind: 'moss'; ok: boolean; routes: ExportedDocument[] }\n | { kind: 'shell'; ok: boolean; routes: ShellRouteReport[] };\n\nconst buildShell = async (options: CommandOptions, project: NiscShellProject): Promise<BuildResult> => {\n const template = templateOf(options, project);\n const routes = await surveyShell(options.root, project, template);\n say(options)('');\n say(options)(shellRouteTable(routes));\n warnOfOneAddress(options, project, template, routes.length);\n return { kind: 'shell', ok: routes.every((route) => route.problems.length === 0), routes };\n};\n\nexport const build = async (options: CommandOptions): Promise<BuildResult> => {\n const project = await loadProject(options.root);\n if (options.skipBundle !== true) bundle(options, project);\n warnOfOwnAssets(options);\n if (isShellProject(project)) return buildShell(options, project);\n const routes = await survey(options, project);\n say(options)('');\n say(options)(routeTable(routes));\n warnOfOneAddress(options, project, templateOf(options, project), routes.length);\n return { kind: 'moss', ok: routes.every((route) => route.drawn), routes };\n};\n\nconst write = (options: CommandOptions, project: NiscProject, out: string, routes: readonly { path: string; html: string }[]): void => {\n rmSync(out, { recursive: true, force: true });\n cpSync(distOf(options.root, project), out, { recursive: true });\n for (const route of routes) {\n const file = join(out, fileOf(route.path));\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, route.html);\n }\n say(options)('');\n say(options)(`nisc: ${routes.length} paths written to ${out}`);\n};\n\nexport const exportSite = async (options: CommandOptions): Promise<{ written: boolean; result: BuildResult; out: string }> => {\n const project = await loadProject(options.root);\n const result = await build(options);\n const out = resolve(options.root, options.out ?? 'out');\n if (result.kind === 'shell') {\n if (!result.ok) {\n const failed = result.routes.filter((route) => route.problems.length > 0);\n say(options)('');\n say(options)(`nisc: ${failed.length} of ${result.routes.length} paths did not hold (${failed.map((route) => route.path).join(', ')}). Nothing was written.`);\n return { written: false, result, out };\n }\n write(options, project, out, result.routes);\n return { written: true, result, out };\n }\n const routes = result.routes;\n const live = routes.filter((route) => route.live || !route.drawn);\n if (live.length > 0 && options.allowLive !== true) {\n say(options)('');\n say(options)(`nisc: ${live.length} of ${routes.length} paths cannot be a file alone (${live.map((route) => route.path).join(', ')}).`);\n say(options)(' Nothing was written. With a server beside the files they still work: `nisc export --allow-live`.');\n return { written: false, result, out };\n }\n write(options, project, out, routes);\n return { written: true, result, out };\n};\n\nconst listening = async (httpServer: ReturnType<typeof serve>, options: CommandOptions): Promise<string> => {\n await new Promise<void>((up) => httpServer.once('listening', () => up()));\n const address = httpServer.address();\n const port = address !== null && typeof address === 'object' ? (address satisfies AddressInfo).port : options.port;\n return `http://localhost:${port}`;\n};\n\nexport const start = async (options: CommandOptions): Promise<{ url: string; close: () => Promise<void> }> => {\n const project = await loadProject(options.root);\n const dist = distOf(options.root, project);\n if (!existsSync(join(dist, 'index.html'))) throw new Error(`nisc: no built terminal in ${dist} — run \\`nisc build\\`.`);\n const port = options.port ?? Number(process.env['PORT'] ?? 8787);\n if (isShellProject(project)) {\n const httpServer = serve({ fetch: siteHandler(shellSite(project, dist)), port });\n const url = await listening(httpServer, options);\n say(options)(`nisc: serving ${url} — the built app, each path’s first screen drawn; the shell is the page’s own`);\n return { url, close: async () => void httpServer.close() };\n }\n const { attachSocket, mountSite, MOSS_PATHS } = await import('@niscorp/moss/node');\n const booted = await project.boot();\n try {\n await booted.server.checkFunctions();\n } catch (error) {\n await booted.close?.();\n throw error;\n }\n await project.routes?.(booted.server);\n mountSite(booted.server, {\n dist,\n draw: project.draw,\n ...(project.htmlAttributes !== undefined ? { htmlAttributes: project.htmlAttributes } : {}),\n ...(project.site !== undefined ? { site: project.site } : {}),\n ...(project.tokenKey !== undefined ? { tokenKey: project.tokenKey } : {}),\n });\n const httpServer = serve({ fetch: siteHandler(booted.server.fetch, { except: MOSS_PATHS }), port });\n attachSocket(httpServer, booted.server.socket);\n const url = await listening(httpServer, options);\n say(options)(`nisc: serving ${url} — the built terminal, its pages drawn; the socket at /socket`);\n return {\n url,\n close: async () => {\n httpServer.close();\n await booted.close?.();\n },\n };\n};\n\nexport const migrate = async (options: CommandOptions): Promise<void> => {\n const project = await loadProject(options.root);\n if (isShellProject(project) || project.app === undefined || project.runtime === undefined) {\n throw new Error('nisc: `nisc migrate` needs `app` and `runtime` in nisc.config.ts — the manifest, and the environment it runs on.');\n }\n const { migrateTables } = await import('@niscorp/moss');\n const print = say(options);\n const isDryRun = options.dryRun === true;\n const runtime = await project.runtime();\n try {\n const report = await migrateTables(runtime, project.app, isDryRun ? { dryRun: true } : {});\n if (report.applied.length === 0) print('nisc: nothing to migrate');\n else print(isDryRun ? `nisc: would apply ${report.applied.length} — rolled back, nothing changed` : `nisc: applied ${report.applied.length}`);\n for (const migration of report.applied) print(` ${migration.ref} ${migration.description}`);\n if (report.removed.length > 0) print(`nisc: this run removes ${report.removed.join(', ')}`);\n if (report.retyped.length > 0) print(`nisc: this run changes the type of ${report.retyped.join(', ')}`);\n if (report.alreadyBroken.length > 0) print('nisc: not fitting before this run either, and seeded as they are — said, not refused:');\n for (const entry of report.alreadyBroken) print(` ${entry}`);\n } finally {\n await runtime.close?.();\n }\n};\n\nconst handOver = (options: CommandOptions, tool: string, args: readonly string[]): Promise<number> =>\n new Promise((done) => {\n const child = spawn(process.execPath, [tool, ...args], { cwd: options.root, stdio: 'inherit' });\n child.once('exit', (code) => done(code ?? 1));\n });\n\nexport const dev = (options: CommandOptions): Promise<{ url: string; close: () => Promise<void> }> =>\n devServer({ root: options.root, ...(options.port !== undefined ? { port: options.port } : {}) });\n\nexport const check = async (options: CommandOptions): Promise<number> => {\n const project = await loadProject(options.root);\n return handOver(options, toolOf(options.root, 'tsx', 'tsx'), [project.checks ?? 'src/dev/all-checks.ts']);\n};\n","import { resolve } from 'node:path';\nimport { build, check, dev, exportSite, migrate, start } from './commands';\nimport type { CommandOptions } from './commands';\n\nconst USAGE = `nisc — the command for a nisc application\n\n nisc dev the app's dev server — its vite, with the app server inside\n nisc build bundle the app, draw every path, and check what was drawn\n nisc export build, then write every path as a file (the site as a folder)\n nisc start serve the built app, each path's first screen drawn\n nisc check the app's check suite\n nisc migrate apply the tables' pending migrations, if the app's entries fit the result\n\n --root <dir> the app's root (default: here) — where nisc.config.ts is\n --out <dir> export: where the files go (default: out)\n --allow-live export: write even though some path wants a server behind it\n --port <n> dev, start: the port (start: $PORT, then 8787)\n --skip-bundle build, export: the terminal is already built\n --check migrate: do all of it, then roll it back\n\nAn app says in nisc.config.ts how it boots and how one of its screens is drawn.\nBehind moss (boot + draw): which paths exist and what each needs is read off the\nserver. With its own shell (shell + draw + adopt): every path is drawn from the\napp's own boot, and a file is written only if the page's boot picks it up clean.`;\n\nconst valueAfter = (args: readonly string[], flag: string): string | undefined => {\n const at = args.indexOf(flag);\n return at < 0 ? undefined : args[at + 1];\n};\n\nconst main = async (): Promise<number> => {\n const [command, ...args] = process.argv.slice(2);\n const port = valueAfter(args, '--port');\n const out = valueAfter(args, '--out');\n const options: CommandOptions = {\n root: resolve(valueAfter(args, '--root') ?? process.cwd()),\n ...(out !== undefined ? { out } : {}),\n ...(port !== undefined ? { port: Number(port) } : {}),\n allowLive: args.includes('--allow-live'),\n skipBundle: args.includes('--skip-bundle'),\n };\n\n if (command === 'dev' || command === 'start') {\n const served = command === 'dev' ? await dev(options) : await start(options);\n const stop = (): void => {\n void served.close().finally(() => process.exit(0));\n };\n process.on('SIGINT', stop);\n process.on('SIGTERM', stop);\n return new Promise<number>(() => undefined);\n }\n if (command === 'check') return check(options);\n if (command === 'migrate') {\n await migrate({ ...options, dryRun: args.includes('--check') });\n return 0;\n }\n if (command === 'build') {\n return (await build(options)).ok ? 0 : 1;\n }\n if (command === 'export') return (await exportSite(options)).written ? 0 : 1;\n console.log(USAGE);\n return command === undefined || command === 'help' || command === '--help' ? 0 : 1;\n};\n\nmain().then(\n // An explicit exit: an app's own handles (a database, a timer) would keep a\n // finished command open.\n (code) => process.exit(code),\n (error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exit(1);\n },\n);\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;;;;;;;AAgDO,IAAM,YAAA,GAAe,uBAAA;AAsB5B,IAAM,eAAA,GAAkB,CAAC,KAAA,KAA0B,KAAA,CAAM,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,QAAQ,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM,CAAA;AAIrH,IAAM,WAAA,GAAc,CAAC,QAAA,EAAkB,MAAA,EAAgB,aAAqC,EAAC,EAAG,OAAO,YAAA,KAAyB;AACrI,EAAA,MAAM,OAAA,GAAU,OAAO,OAAA,CAAQ,UAAU,EACtC,GAAA,CAAI,CAAC,CAAC,I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,GAAA,CAAI,IAAA,EAAM,MAAA,CAAO,IAAA,GAAO,CAAC,CAAC,CAAA,EAAGA,IAAAA,CAAI,GAAA,CAAI,MAAA,EAAQ,MAAA,CAAO,MAAA,GAAS,CAAC,CAAC,CAAA,CAAA;AAChI,IAAA,MAAM,CAAC,KAAA,EAAO,GAAG,IAAI,CAAA,GAAI,CAAC,GAAI,GAAA,CAAI,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,IAAI,KAAA,GAAQ,CAAC,gCAAgC,CAAA,EAAI,GAAG,IAAI,IAAI,CAAA;AACjH,IAAA,KAAA,CAAM,KAAK,CAAA,EAAG,IAAI,CAAA,EAAG,KAAA,IAAS,EAAE,CAAA,CAAE,CAAA;AAClC,IAAA,KAAA,MAAW,IAAA,IAAQ,IAAA,EAAM,KAAA,CAAM,IAAA,CAAK,CAAA,EAAG,GAAA,CAAI,MAAA,CAAO,IAAA,CAAK,MAAM,CAAC,CAAA,EAAG,IAAI,CAAA,CAAE,CAAA;AAAA,EACzE;AACA,EAAA,KAAA,CAAM,KAAK,EAAE,CAAA;AACb,EAAA,KAAA,CAAM,KAAK,sFAAiF,CAAA;AAC5F,EAAA,KAAA,CAAM,KAAK,2EAAsE,CAAA;AACjF,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"index.cjs","sourcesContent":["import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. A page's <head> is a node in a\n// layout (nova's `nova:head`, holding the elements a head holds). It is read\n// off the same shell the markup was drawn from and written into the template's\n// <head>; a path whose screen has none goes out with the template's. A head\n// that holds what it may not — something that runs, or styles — FAILS the\n// build like any other check. With a `site` in the config, each path is given\n// its own canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // what the first screen's head held, and the actions that said it — absent\n // when the screen has no head and the file's is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // what the screen's head held, and the actions that said it — absent when\n // the screen has no head and the document's is the template's own\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
1
+ {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;;;;;;;AAaO,IAAM,YAAA,GAAe,uBAAA;AAa5B,IAAM,eAAA,GAAkB,CAAC,KAAA,KAA0B,KAAA,CAAM,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,QAAQ,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM,CAAA;AAErH,IAAM,WAAA,GAAc,CAAC,QAAA,EAAkB,MAAA,EAAgB,aAAqC,EAAC,EAAG,OAAO,YAAA,KAAyB;AACrI,EAAA,MAAM,OAAA,GAAU,OAAO,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AAA,GAAO,CAAC,CAAC,CAAA,EAAGA,IAAAA,CAAI,GAAA,CAAI,IAAA,EAAM,MAAA,CAAO,IAAA,GAAO,CAAC,CAAC,CAAA,EAAGA,IAAAA,CAAI,GAAA,CAAI,MAAA,EAAQ,MAAA,CAAO,MAAA,GAAS,CAAC,CAAC,CAAA,CAAA;AAChI,IAAA,MAAM,CAAC,KAAA,EAAO,GAAG,IAAI,CAAA,GAAI,CAAC,GAAI,GAAA,CAAI,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,IAAI,KAAA,GAAQ,CAAC,gCAAgC,CAAA,EAAI,GAAG,IAAI,IAAI,CAAA;AACjH,IAAA,KAAA,CAAM,KAAK,CAAA,EAAG,IAAI,CAAA,EAAG,KAAA,IAAS,EAAE,CAAA,CAAE,CAAA;AAClC,IAAA,KAAA,MAAW,IAAA,IAAQ,IAAA,EAAM,KAAA,CAAM,IAAA,CAAK,CAAA,EAAG,GAAA,CAAI,MAAA,CAAO,IAAA,CAAK,MAAM,CAAC,CAAA,EAAG,IAAI,CAAA,CAAE,CAAA;AAAA,EACzE;AACA,EAAA,KAAA,CAAM,KAAK,EAAE,CAAA;AACb,EAAA,KAAA,CAAM,KAAK,sFAAiF,CAAA;AAC5F,EAAA,KAAA,CAAM,KAAK,2EAAsE,CAAA;AACjF,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"index.cjs","sourcesContent":["import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n html: string;\n problems: readonly string[];\n actions: readonly string[];\n opensWith: readonly string[];\n callsLater: readonly string[];\n listens: readonly string[];\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// The adoption check runs in a process of its own (./adopt): a DOM has to exist\n// before the app's modules load, because an adapter decides what it is running\n// in when it is imported.\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","export type RouteReport = {\n path: string;\n page?: string;\n drawn: boolean;\n live: boolean;\n why: readonly string[];\n drawnWith: readonly string[];\n settled: boolean;\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
package/dist/index.js.map CHANGED
@@ -1 +1 @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AAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"index.js","sourcesContent":["import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\n// ═══════════════════════════════════════════════════════════════\n// AN APP WITH ITS OWN SHELL, DRAWN AHEAD OF TIME.\n//\n// The shell lives in the page. A build runs the app's own boot where there is\n// no browser, waits for the screen to be whole, and has the app's adapter draw\n// it to markup; the page's boot then picks that markup up and from there the\n// app is what it always was. No server holds a shell at any point.\n//\n// A file is a claim — \"this is the page\" — so a build does not write one it has\n// not checked. Per path, and each one FAILS the build:\n//\n// drawn the app booted and its screen drew to markup that is not empty\n// whole nothing was still loading when it was drawn\n// same twice a second boot draws the same markup, byte for byte, and says\n// the same head — or the page's own boot would not match what\n// the file says\n// adopted inside a DOM, a third boot picks the markup up and the\n// adapter complains about nothing\n//\n// And one that holds by construction: the boot is handed a path and nothing\n// else, so a file is only ever the screen as nobody in particular sees it.\n//\n// What a build cannot fail on, it reports: what the screen opened with (those\n// answers are in the markup as they were at build), what it can still call, and\n// what it waits on.\n//\n// THE HEAD OF EACH FILE IS ITS SCREEN'S OWN. A page's <head> is a node in a\n// layout (nova's `nova:head`, holding the elements a head holds). It is read\n// off the same shell the markup was drawn from and written into the template's\n// <head>; a path whose screen has none goes out with the template's. A head\n// that holds what it may not — something that runs, or styles — FAILS the\n// build like any other check. With a `site` in the config, each path is given\n// its own canonical address.\n// ═══════════════════════════════════════════════════════════════\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n // the whole document; the template as it is when the screen could not be drawn\n html: string;\n // every check that did not hold — empty is a file that may be written\n problems: readonly string[];\n // the actions on the first screen\n actions: readonly string[];\n // endpoints answered while the screen opened: their answers are in the markup\n // as they were when it was drawn\n opensWith: readonly string[];\n // endpoints the first screen can still call once it is in the page\n callsLater: readonly string[];\n // channels the first screen waits on\n listens: readonly string[];\n // what the first screen's head held, and the actions that said it — absent\n // when the screen has no head and the file's is the template's own\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\n// The screen, in the app's own index.html: inside the empty root, with whatever\n// the kit would have put on <html>.\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\n// What the first screen is made of, read off the definitions of what is mounted.\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\n// A drawn screen as the document it goes out in: the screen in the root, and\n// what it says about itself in the head.\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\n// One boot, one draw, and the app let go again.\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// ── adopted ──\n//\n// The one check that needs a browser's world. A DOM has to exist BEFORE the\n// app's modules load (an adapter decides what it is running in when it is\n// imported), so it runs in a process of its own: ./adopt stands a DOM up, loads\n// the same config, and for each path puts the markup in a root and makes the\n// app's own `adopt` call over a fresh boot.\n\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\n// Every path, checked.\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n // only what is worth adopting: a screen that drew, whole\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\n// Where two draws part, in a few words — enough to find it.\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\n// ── served ──\n//\n// The same draw, per request: the first answer to a path is its screen, and\n// everything else in the built folder is a file. No checks here — a build made\n// them; a screen that will not draw goes out as the template, and the page's\n// own boot paints it as it did before any of this existed.\n//\n// What a browser may keep of all this, and how it travels, is not said here:\n// `start` puts that around this handler (./site), as it does around moss's.\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n // How big it is and when it last changed — what `start` needs to say\n // what a browser may keep, and to answer \"has it changed?\" (./site).\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n // a name with an extension that is not there is a missing file, not a page\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The paths an app has, where each one's file goes, and the table a build\n// prints. Pure: no server, no disk — the command hands these what it found.\n// ═══════════════════════════════════════════════════════════════\n\n// What a build learned about one path (moss's `ExportedDocument`, without the\n// markup).\nexport type RouteReport = {\n path: string;\n // the page the path led to; absent: the app's own shell\n page?: string;\n drawn: boolean;\n // something on it can still happen — it wants a server behind it\n live: boolean;\n why: readonly string[];\n // reads whose answers are in the markup as they were when it was drawn\n drawnWith: readonly string[];\n settled: boolean;\n // what the screen's head held, and the actions that said it — absent when\n // the screen has no head and the document's is the template's own\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\n// `/`, and every page whose path names no parameter. A parameterised page has\n// as many paths as there are rows; those are the app's to list.\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\n// Where a path's file goes under the output directory: `/` is index.html, and\n// every other path is a folder with an index.html in it — what every static\n// host serves for that path without being told to.\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\n// The table. One row per path: whether a file is the whole of it, or a server\n// has to stand behind it — and, in the build's own words, why.\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n // Said only by an app that has a head somewhere: then a path without one is\n // going out under the template's, and that may not be what was meant.\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
1
+ {"version":3,"sources":["../src/shell-site.ts","../src/routes.ts"],"names":["pad"],"mappings":";;;;;;;;;;AAaO,IAAM,YAAA,GAAe,uBAAA;AAa5B,IAAM,eAAA,GAAkB,CAAC,KAAA,KAA0B,KAAA,CAAM,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,QAAQ,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM,CAAA;AAErH,IAAM,WAAA,GAAc,CAAC,QAAA,EAAkB,MAAA,EAAgB,aAAqC,EAAC,EAAG,OAAO,YAAA,KAAyB;AACrI,EAAA,MAAM,OAAA,GAAU,OAAO,OAAA,CAAQ,UAAU,EACtC,GAAA,CAAI,CAAC,CAAC,IAAA,EAAM,KAAK,MAAM,CAAA,CAAA,EAAI,IAAI,KAAK,eAAA,CAAgB,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA,CAC7D,KAAK,EAAE,CAAA;AACV,EAAA,OACE,QAAA,CAEG,OAAA,CAAQ,IAAA,EAAM,MAAM,IAAA,CAAK,QAAQ,SAAA,EAAW,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,MAAA,CAAQ,CAAC,EACrE,OAAA,CAAQ,eAAA,EAAiB,CAAC,KAAA,EAAO,QAAA,KAAsB,OAAA,KAAY,EAAA,GAAK,KAAA,GAAQ,CAAA,KAAA,EAAQ,QAAQ,CAAA,EAAG,OAAO,CAAA,CAAA,CAAI,CAAA;AAErH;AA2HA,IAAM,GAAA,GAAM,CAAC,IAAA,EAAc,KAAA,KAA0B,IAAA,GAAO,GAAA,CAAI,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAA,GAAQ,IAAA,CAAK,MAAM,CAAC,CAAA;AAEhG,IAAM,eAAA,GAAkB,CAAC,MAAA,KAAgD;AAC9E,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAA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AA,CAAM,KAAK,2EAAsE,CAAA;AACjF,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"index.js","sourcesContent":["import { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { shellSettled, shellView } from '@niscorp/nova';\nimport type { Shell } from '@niscorp/nova';\nimport { headOf, placeHead } from '@niscorp/nova/document';\nimport type { ScreenHead } from '@niscorp/nova/document';\nimport { livenessOf } from '@niscorp/nova/reflect';\nimport type { NiscShellProject } from './project';\n\nconst DEFAULT_BUILD_WAIT_MS = 5000;\nexport const DEFAULT_ROOT = '<div id=\"root\"></div>';\n\nexport type ShellRouteReport = {\n path: string;\n html: string;\n problems: readonly string[];\n actions: readonly string[];\n opensWith: readonly string[];\n callsLater: readonly string[];\n listens: readonly string[];\n head?: ScreenHead;\n};\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n\nexport const placeScreen = (template: string, screen: string, attributes: Record<string, string> = {}, root = DEFAULT_ROOT): string => {\n const written = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('');\n return (\n template\n // functions, both, so nothing in the screen is read as a replacement pattern\n .replace(root, () => root.replace('></div>', () => `>${screen}</div>`))\n .replace(/<html([^>]*)>/, (whole, existing: string) => (written === '' ? whole : `<html${existing}${written}>`))\n );\n};\n\nconst factsOf = (shell: Shell): Pick<ShellRouteReport, 'actions' | 'opensWith' | 'callsLater' | 'listens'> => {\n const [actions, opensWith, callsLater, listens] = [new Set<string>(), new Set<string>(), new Set<string>(), new Set<string>()];\n for (const canvas of Object.values(shell.getState().canvases)) {\n for (const instance of canvas.stack) {\n const definition = shell.getRuntime(instance.id)?.definition;\n if (definition === undefined) continue;\n actions.add(definition.id);\n const liveness = livenessOf(definition);\n for (const channel of liveness.listens) listens.add(channel);\n for (const endpoint of liveness.endpoints) {\n const label = `${definition.id}.${endpoint.name}${endpoint.kind === 'fn' ? ' (a function)' : endpoint.url !== undefined ? ` (${endpoint.url})` : ''}`;\n if (endpoint.onOpen) opensWith.add(label);\n if (endpoint.later) callsLater.add(label);\n }\n }\n }\n const sorted = (set: Set<string>): string[] => [...set].sort();\n return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };\n};\n\ntype Drawn = { screen: string; whole: boolean; attributes: Record<string, string>; head: ScreenHead | undefined; facts: ReturnType<typeof factsOf> };\n\nconst documentOf = (project: NiscShellProject, template: string, path: string, drawn: Drawn): string =>\n placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.elements, { ...(project.site !== undefined ? { site: project.site } : {}), path });\n\nconst drawOnce = async (project: NiscShellProject, path: string): Promise<Drawn> => {\n const booted = await project.shell({ path });\n try {\n const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });\n const screen = await project.draw(booted.shell);\n return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };\n } finally {\n await booted.close?.();\n }\n};\n\nconst said = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// The adoption check runs in a process of its own (./adopt): a DOM has to exist\n// before the app's modules load, because an adapter decides what it is running\n// in when it is imported.\ntype Adoption = { path: string; complaints: string[] };\n\nconst isAdoption = (value: unknown): value is Adoption =>\n value !== null &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'path') === 'string' &&\n Array.isArray(Reflect.get(value, 'complaints'));\n\nconst adoptAll = (root: string, pages: readonly { path: string; screen: string }[]): Adoption[] => {\n if (pages.length === 0) return [];\n const here = dirname(fileURLToPath(import.meta.url));\n // built: beside this file. From source (the package's own tests): in dist.\n const entry = [join(here, 'adopt.js'), join(here, '..', 'dist', 'adopt.js')].find((candidate) => existsSync(candidate));\n if (entry === undefined) throw new Error('nisc: the adoption check is not built (packages/cli/dist/adopt.js).');\n const scratch = mkdtempSync(join(tmpdir(), 'nisc-adopt-'));\n try {\n const [asked, answered] = [join(scratch, 'pages.json'), join(scratch, 'adopted.json')];\n writeFileSync(asked, JSON.stringify(pages));\n const result = spawnSync(process.execPath, [entry, root, asked, answered], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' });\n if (!existsSync(answered)) {\n const why = result.stderr.trim().split('\\n').slice(-6).join('\\n');\n return pages.map((page) => ({ path: page.path, complaints: [`the adoption check could not run${why === '' ? '' : ` — ${why}`}`] }));\n }\n const parsed: unknown = JSON.parse(readFileSync(answered, 'utf8'));\n return Array.isArray(parsed) ? parsed.filter(isAdoption) : [];\n } finally {\n rmSync(scratch, { recursive: true, force: true });\n }\n};\n\nexport const surveyShell = async (root: string, project: NiscShellProject, template: string): Promise<ShellRouteReport[]> => {\n if (!template.includes(DEFAULT_ROOT)) {\n throw new Error(`nisc: the built index.html has no empty root (${DEFAULT_ROOT}) — that is where a screen goes.`);\n }\n const paths = project.paths === undefined ? ['/'] : await project.paths();\n const none = { actions: [], opensWith: [], callsLater: [], listens: [] };\n\n const first: { path: string; drawn?: Drawn; problems: string[] }[] = [];\n for (const path of paths) {\n const problems: string[] = [];\n let drawn: Drawn | undefined;\n try {\n drawn = await drawOnce(project, path);\n if (drawn.screen.trim() === '') problems.push('drawn: it drew to nothing');\n if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);\n for (const why of drawn.head?.refused ?? []) problems.push(`head: ${why}`);\n const again = await drawOnce(project, path);\n if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);\n const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];\n if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);\n } catch (error) {\n problems.push(`drawn: ${said(error)}`);\n }\n first.push({ path, ...(drawn !== undefined ? { drawn } : {}), problems });\n }\n\n const adoptable = first.flatMap((route) => (route.drawn !== undefined && route.drawn.whole && route.drawn.screen.trim() !== '' ? [{ path: route.path, screen: route.drawn.screen }] : []));\n const adoptions = new Map(adoptAll(root, adoptable).map((adoption) => [adoption.path, adoption.complaints]));\n\n return first.map((route) => {\n const asked = adoptable.some((page) => page.path === route.path);\n const complaints = asked ? (adoptions.get(route.path) ?? ['the adoption check said nothing about it']) : [];\n const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];\n return {\n path: route.path,\n html: route.drawn === undefined ? template : documentOf(project, template, route.path, route.drawn),\n problems,\n ...(route.drawn?.facts ?? none),\n ...(route.drawn?.head !== undefined ? { head: route.drawn.head } : {}),\n };\n });\n};\n\nconst differenceOf = (a: string, b: string): string => {\n let at = 0;\n while (at < a.length && at < b.length && a[at] === b[at]) at += 1;\n const around = (text: string): string => JSON.stringify(text.slice(Math.max(0, at - 30), at + 50));\n return ` — at character ${at}: ${around(a)} then ${around(b)}`;\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const shellRouteTable = (routes: readonly ShellRouteReport[]): string => {\n const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;\n const lines = [` ${pad('Route', width)}First screen`];\n const indent = ' '.repeat(width + 2);\n const says = (route: ShellRouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const headNote = (route: ShellRouteReport): string =>\n says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own';\n for (const route of routes) {\n const ok = route.problems.length === 0;\n const notes = ok\n ? [\n `drawn · whole · same twice · adopted${route.actions.length > 0 ? ` (${route.actions.join(', ')})` : ''}`,\n ...(route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(', ')} — in the file as answered at build`] : []),\n ...(route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(', ')}`] : []),\n ...(route.listens.length > 0 ? [`waits on ${route.listens.join(', ')}`] : []),\n ...(headed ? [headNote(route)] : []),\n ]\n : route.problems;\n const [head, ...rest] = notes;\n lines.push(`${ok ? '○' : '✗'} ${pad(route.path, width)}${head ?? ''}`);\n for (const note of rest) lines.push(`${indent}${note}`);\n }\n lines.push('');\n lines.push('○ a file: the first screen, drawn for nobody in particular; the page’s own shell picks it up');\n lines.push('✗ not written: a check did not hold');\n return lines.join('\\n');\n};\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.woff': 'font/woff',\n '.wasm': 'application/wasm',\n '.data': 'application/octet-stream',\n '.map': 'application/json; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n};\n\nexport const shellSite = (project: NiscShellProject, dist: string): ((request: Request) => Promise<Response>) => {\n const base = resolve(dist);\n return async (request) => {\n const path = decodeURIComponent(new URL(request.url).pathname);\n if (path !== '/' && path !== '/index.html') {\n const file = resolve(base, `.${path}`);\n const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : undefined;\n if (stats?.isFile() === true) {\n return new Response(readFileSync(file), {\n headers: { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', 'content-length': String(stats.size), 'last-modified': stats.mtime.toUTCString() },\n });\n }\n if (extname(path) !== '') return new Response('not found', { status: 404 });\n }\n const template = readFileSync(join(base, 'index.html'), 'utf8');\n const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' };\n try {\n const at = path === '/index.html' ? '/' : path;\n return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });\n } catch (error) {\n console.error(`[nisc] \"${path}\" could not be drawn — serving it undrawn:`, error);\n return new Response(template, { headers });\n }\n };\n};\n","export type RouteReport = {\n path: string;\n page?: string;\n drawn: boolean;\n live: boolean;\n why: readonly string[];\n drawnWith: readonly string[];\n settled: boolean;\n head?: { elements: readonly unknown[]; actions: readonly string[] };\n};\n\nexport const defaultPaths = (pages: readonly { name: string; path: string }[]): string[] => [\n '/',\n ...pages\n .map((page) => page.path)\n .filter((path) => !path.split('/').some((segment) => segment.startsWith(':')))\n .sort(),\n];\n\nexport const fileOf = (path: string): string => {\n const segments = path.split('?')[0]?.split('/').filter((segment) => segment !== '') ?? [];\n if (segments.some((segment) => segment === '..' || segment === '.')) throw new Error(`nisc: \"${path}\" is not a path a file can be written for.`);\n return [...segments, 'index.html'].join('/');\n};\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - text.length));\n\nexport const routeTable = (routes: readonly RouteReport[]): string => {\n const says = (route: RouteReport): boolean => (route.head?.elements.length ?? 0) > 0;\n const headed = routes.some(says);\n const rows = routes.map((route) => {\n const mark = !route.drawn ? '✗' : route.live ? '●' : '○';\n const what = route.page === undefined ? 'the app' : `page ${route.page}`;\n const served = !route.drawn ? 'not drawn' : route.live ? 'server' : 'file';\n const notes = [\n ...(route.drawn ? route.why : ['it could not be drawn — it goes out as the undrawn template']),\n ...(route.drawn && !route.settled ? ['it was still loading when the wait ran out — drawn with what it had'] : []),\n ...(route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(', ')} — as it answered at build`] : []),\n ];\n const head = headed && route.drawn ? [says(route) ? `head: its own, said by ${route.head?.actions.join(', ') || 'the shell’s chrome'}` : 'head: the template’s own'] : [];\n return { mark, path: route.path, what, served, notes, head };\n });\n const widths = {\n path: Math.max(5, ...rows.map((row) => row.path.length)),\n what: Math.max(4, ...rows.map((row) => row.what.length)),\n served: Math.max(9, ...rows.map((row) => row.served.length)),\n };\n const lines = [` ${pad('Route', widths.path + 2)}${pad('What', widths.what + 2)}${pad('Served as', widths.served + 2)}Because`];\n for (const row of rows) {\n const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;\n const [first, ...rest] = [...(row.notes.length > 0 ? row.notes : ['nothing on it can still happen']), ...row.head];\n lines.push(`${head}${first ?? ''}`);\n for (const note of rest) lines.push(`${' '.repeat(head.length)}${note}`);\n }\n lines.push('');\n lines.push('○ file drawn once, for nobody in particular; nothing on it can still happen');\n lines.push('● server something on it can still happen; it wants moss behind it');\n return lines.join('\\n');\n};\n"]}
@@ -0,0 +1,3 @@
1
+ export { configFileOf, isProject, isShellProject, loadProject } from './chunk-Z2PJ5QB7.js';
2
+ //# sourceMappingURL=project-3LJPDFX2.js.map
3
+ //# sourceMappingURL=project-3LJPDFX2.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"project-CH37UEL7.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"project-3LJPDFX2.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niscorp/cli",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "nisc — the command for a nisc application: dev, build, export, start. One config file says how the app boots and how its pages are drawn; the command does the rest.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -39,8 +39,8 @@
39
39
  "node": ">=22.12"
40
40
  },
41
41
  "peerDependencies": {
42
- "@niscorp/moss": "^0.6.0",
43
- "@niscorp/nova": "^0.3.0"
42
+ "@niscorp/moss": "^0.8.0",
43
+ "@niscorp/nova": "^0.5.0"
44
44
  },
45
45
  "peerDependenciesMeta": {
46
46
  "@niscorp/moss": {
@@ -58,8 +58,8 @@
58
58
  "tsup": "^8.5.1",
59
59
  "typescript": "^6.0.2",
60
60
  "vitest": "^4.1.2",
61
- "@niscorp/moss": "^0.6.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OAAA,CAAQ,IAAI,CAAC,CAAA,8EAAA,CAA2E,CAAA;AAAA,EAC5J;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-I2SDNSH5.js","sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { DocumentConfig, MossServer, NiscApp, NiscRuntime } from '@niscorp/moss';\nimport type { Shell } from '@niscorp/nova';\n\n// ═══════════════════════════════════════════════════════════════\n// WHAT AN APP SAYS ABOUT ITSELF — `nisc.config.ts`, at the app's root, exporting\n// `project`. What only the app knows: how it stands up, and how one of its\n// screens is drawn. Everything the command does is derived from those.\n//\n// An app is one of two things, and its config says which by what it hands over.\n//\n// BEHIND MOSS — the shell lives on the server. The config hands over the\n// server; which paths exist and what each needs is read off its manifest.\n//\n// export const project: NiscProject = {\n// boot: async () => ({ server: (await boot()).server }),\n// draw: (snapshot) => renderSnapshot({ snapshot, registry, slotWrapper }),\n// };\n//\n// ITS OWN SHELL — the shell lives in the page (AGENTS.md, \"the client-degrade\n// path\"). The config hands over the app's own boot, the SAME one its browser\n// entry runs. A build runs it where there is no browser, draws the screen to\n// markup, and the page's boot picks that markup up.\n//\n// export const project: NiscShellProject = {\n// shell: async () => ({ shell: (await boot()).shell }),\n// draw: (shell) => renderToString(createElement(Screen, { shell })),\n// adopt: (root, shell) => { hydrateRoot(root, createElement(Screen, { shell })); },\n// };\n// ═══════════════════════════════════════════════════════════════\n\ntype Common = {\n // Where the bundler writes the terminal (default `dist`), relative to the root.\n dist?: string;\n // Where the built page's stylesheet goes. `page` (the default): written into\n // index.html as a <style>, so the first response paints the screen. `file`:\n // left as the bundler linked it — what a Content-Security-Policy that forbids\n // inline styles needs.\n stylesheet?: 'page' | 'file';\n // The app's check suite, for `nisc check` (default `src/dev/all-checks.ts`).\n checks?: string;\n // The address the site is served at (\"https://example.com\"). With it, every\n // path's document says its own canonical address. Without it, where a\n // document lives is left as index.html says — for every path alike.\n site?: string;\n};\n\nexport type NiscMossProject = Common & {\n // Stand the app up: the moss server, and how to let it go again. The same boot\n // the app's dev server and its checks run.\n boot: () => Promise<{ server: MossServer; close?: () => void | Promise<void> }>;\n // A terminal that draws one screen to a string — the app's kit bound to one of\n // moss's server targets (`@niscorp/moss/terminal/react/server`, …).\n draw: DocumentConfig['draw'];\n // What the kit would put on <html> from an effect (a palette, a scheme).\n htmlAttributes?: DocumentConfig['htmlAttributes'];\n // The wire's token key, when it is not `nisc.token`.\n tokenKey?: string;\n // The paths to build. Default: `/`, and every page whose path has no\n // parameter. A page with parameters (\"/docs/:slug\") has as many paths as there\n // are rows, and only the app knows them — list them here (`server.executeAs`\n // runs a seeded read as a charter role).\n paths?: (server: MossServer) => readonly string[] | Promise<readonly string[]>;\n // Routes of the app's own that a served site needs before the catch-all — a\n // sign-in handoff, a webhook. `nisc start` registers them first.\n routes?: (server: MossServer) => void | Promise<void>;\n // What only `nisc migrate` uses: the manifest, and the environment it runs\n // on — opened by the command, and let go by it (`close`). The step applies\n // the tables' pending migrations and checks the manifest's entries against\n // what they leave; it stands no server up. `runtime` opens and nothing\n // else: tables it migrated itself are changed before the step can check them.\n app?: NiscApp;\n runtime?: () => Promise<NiscRuntime & { close?: () => void | Promise<void> }>;\n // What only `nisc dev` uses.\n dev?: {\n // A signed-in URL in development: `/dev/as/<who>` stores the token this\n // mints and goes to `/`. `null` is nobody of that name. It exists in the\n // dev server and nowhere else.\n signIn?: (server: MossServer, who: string) => string | null | Promise<string | null>;\n // Let `/dev/as/<who>` answer a device other than this machine (default:\n // this machine only). Anybody who can reach the dev server then signs in\n // as anybody.\n signInFromNetwork?: boolean;\n // Which changed files re-boot the app server (default: `src/app`,\n // `src/server`, `src/db`, `src/ui` and the config).\n watch?: RegExp;\n // Which paths go to the app server and not to vite (default: moss's own\n // prefixes). An app with routes of its own under another prefix names\n // moss's prefixes and its own.\n owned?: RegExp;\n };\n};\n\nexport type NiscShellProject = Common & {\n // One fresh copy of the app's shell, for one path — the boot the browser entry\n // runs. It is handed the path and NOTHING ELSE: there is no credential to pass\n // and no way to pass one, so what a build draws is the screen as nobody in\n // particular sees it. Called more than once per path (the build boots twice\n // to compare, and once more inside a DOM to adopt), so it must not memoize.\n shell: (request: { path: string }) => Promise<{ shell: Shell; close?: () => void | Promise<void> }>;\n // Draw a shell to markup where there is no browser: the app's kit through an\n // adapter's string target (`react-dom/server`, `vue/server-renderer`,\n // `@niscorp/nova/adapters/dom/server`).\n draw: (shell: Shell) => string | Promise<string>;\n // Pick the markup up: `root` already holds it, `shell` is the page's own. The\n // SAME call the browser entry makes (`hydrateRoot`, `createSSRApp().mount`,\n // nova's `mountShell`). A build runs it inside a DOM and fails on anything it\n // complains about.\n adopt: (root: HTMLElement, shell: Shell) => void | Promise<void>;\n // What the kit would put on <html> from an effect (a palette, a scheme).\n htmlAttributes?: (shell: Shell) => Record<string, string>;\n // The paths to build (default: `/`). An app that maps paths to actions lists\n // its own — only it knows them.\n paths?: () => readonly string[] | Promise<readonly string[]>;\n // How long a build waits for a screen to be whole (default 5000ms). Past it\n // the build FAILS: a file that says \"loading\" is not the page.\n waitMs?: number;\n};\n\n// What a config exports. Written against one of the two names above, a config's\n// callbacks are typed for it (`draw`'s argument is a snapshot in one and a shell\n// in the other).\nexport type NiscProject = NiscMossProject | NiscShellProject;\n\nconst CONFIG_NAMES = ['nisc.config.ts', 'nisc.config.mts', 'nisc.config.js', 'nisc.config.mjs'];\n\nconst has = (value: object, key: string): boolean => typeof Reflect.get(value, key) === 'function';\n\nexport const isShellProject = (project: NiscProject): project is NiscShellProject => 'shell' in project;\n\nexport const isProject = (value: unknown): value is NiscProject => {\n if (value === null || typeof value !== 'object' || !has(value, 'draw')) return false;\n const [moss, own] = [has(value, 'boot'), has(value, 'shell')];\n // one or the other — a config that hands over both has not said which it is\n return moss !== own && (moss || has(value, 'adopt'));\n};\n\n// An address a document can be said to live at: http or https, and whole.\nconst isSite = (value: unknown): boolean => {\n if (typeof value !== 'string') return false;\n try {\n return ['http:', 'https:'].includes(new URL(value).protocol);\n } catch {\n return false;\n }\n};\n\n// The config's file name, if the app has one.\nexport const configFileOf = (root: string): string | undefined => CONFIG_NAMES.find((name) => existsSync(join(root, name)));\n\n// Load the app's config through tsx, so it is TypeScript with the app's own\n// tsconfig (its path aliases included) — the way the app's checks already run.\nexport const loadProject = async (root: string): Promise<NiscProject> => {\n const name = configFileOf(root);\n const file = name === undefined ? undefined : join(root, name);\n if (file === undefined) {\n throw new Error(`nisc: no nisc.config.ts in ${root}. It exports \\`project\\`: how the app boots, and how one of its screens is drawn.`);\n }\n const { tsImport } = await import('tsx/esm/api');\n const tsconfig = join(root, 'tsconfig.json');\n const loaded: unknown = await tsImport(pathToFileURL(file).href, { parentURL: import.meta.url, ...(existsSync(tsconfig) ? { tsconfig } : {}) });\n const project: unknown = loaded !== null && typeof loaded === 'object' ? Reflect.get(loaded, 'project') : undefined;\n if (!isProject(project)) {\n throw new Error(\n `nisc: ${file} does not export a \\`project\\` the command can run. It hands over EITHER \\`boot\\` + \\`draw\\` (an app behind moss) OR \\`shell\\` + \\`draw\\` + \\`adopt\\` (an app with its own shell).`,\n );\n }\n if (project.site !== undefined && !isSite(project.site)) {\n throw new Error(`nisc: ${file} gives \\`site\\` as ${JSON.stringify(project.site)} — it is the address the site is served at, whole: \"https://example.com\".`);\n }\n return project;\n};\n"]}
@@ -1,3 +0,0 @@
1
- export { configFileOf, isProject, isShellProject, loadProject } from './chunk-I2SDNSH5.js';
2
- //# sourceMappingURL=project-CH37UEL7.js.map
3
- //# sourceMappingURL=project-CH37UEL7.js.map