@niscorp/cli 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @niscorp/cli
2
2
 
3
+ ## 0.2.3
4
+
5
+ ### Patch Changes
6
+
7
+ - af903c6: A page's head is its screen's own. `nisc export` wrote every path with the built `index.html`'s `<head>`, so a site with more than one page shipped each of them under the front page's title, description, preview card and canonical address.
8
+
9
+ What a screen says about itself is now a node in a layout: nova's `nova:head`, with `title`, `description`, `image`, `kind` and `structured` bound to the action's data like any other node's props. It draws nothing — no adapter builds an element for it, no registry has to hold it, and a component is never handed one as a child — and it rides in the render tree, so it reaches a shell in the page, a snapshot a server drew and the trees on a wire alike. `headOf(api)` reads it off any of them; with more than one on the screen the last one speaks.
10
+ - **nova** — `HEAD_NAME`, `HeadPropsSchema`, `HEAD_META`, `headOf`, `isHeadNode`; and `@niscorp/nova/document`: `placeHead` writes a head into an HTML document (the tag that said the same thing is replaced, a missing one is added before `</head>`, everything else is left as it was; values are escaped) and `createTitleKeeper` keeps a tab's title on it. The DOM, React and Vue adapters keep the title on the head as the screen moves, and give the page's own back when the screen has none.
11
+ - **cli** — `build`, `export` and `start` write each path's document with its screen's head. "Same twice" also fails a boot that says a different head the second time, and the route table says whose head each path goes out with once an app has one. New config field `site`: the address the site is served at. With it every path says its own canonical address (`<link rel="canonical">`, `og:url`) and a head's picture gets a whole address; a build with several paths, a canonical tag in `index.html` and no `site` says so.
12
+ - **moss** — `renderDocument` and `exportDocuments` do the same from the snapshot (`site` on the config, `head` on the result), and the terminal keeps the tab's title off the wire for every render target.
13
+ - **create-nisc** — the two own-shell templates say their welcome screen's head.
14
+
15
+ **What to change:** nothing. An app with no `nova:head` node and no `site` is built, served and drawn exactly as before. An app that rewrote its exported files to give each page a head can delete that step: put the node in the layout and set `site`.
16
+
17
+ ## 0.2.2
18
+
19
+ ### Patch Changes
20
+
21
+ - 8a04243: `nisc start` says what a browser may keep, and compresses what it sends — for an app with its own shell and an app behind moss alike. What the bundler wrote under `/assets/` goes out `public, max-age=31536000, immutable`; every other file is `no-cache` and answered `304` when it has not changed (an app with its own shell sent neither a validator nor a `Cache-Control` before, so a browser downloaded everything again on every visit). Documents, scripts, stylesheets, JSON, SVG and wasm go out brotli- or gzip-compressed, a piece at a time, with `Vary: Accept-Encoding`; the app server's own paths (`/api`, `/catalog`, …) are left alone. `nisc build` says so when it finds files of the app's own under `public/assets/`, which would be kept for a year under a name that says nothing about their content.
22
+ - 8a04243: `nisc build` writes the built page's stylesheet into the page. Once the app's vite has bundled, each stylesheet `dist/index.html` links by a plain local path is written into it as a `<style>`, so a drawn page paints from one response instead of waiting on a second request for its look. It is done once, to the file in `dist/`, so `build`, `export`, `start` and moss's document all hand out the same head; the stylesheet's own file stays. A link is left as it is, and the build says why, when the link says more than where the file is, the file is not in `dist/`, or the stylesheet names another file relative to itself.
23
+
24
+ **What to change:** an app whose host sends a `Content-Security-Policy` that forbids inline styles sets `stylesheet: 'file'` in `nisc.config.ts` — otherwise the page loses its look. Nothing else changes for an app; with `--skip-bundle` the page is taken as it is.
25
+
3
26
  ## 0.2.1
4
27
 
5
28
  ### Patch Changes
package/README.md CHANGED
@@ -57,9 +57,11 @@ page in the manifest), and what each one needs once it has been drawn.
57
57
  | `boot` | stand the app up: `{ server, close? }` |
58
58
  | `draw` | a terminal that draws a screen to a string (moss's `terminal/react/server`, `/vue/server`, `/dom/server`) |
59
59
  | `htmlAttributes?` | what the kit would put on `<html>` from an effect (a palette, a scheme) |
60
+ | `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" |
60
61
  | `paths?` | the paths to build. Default: `/` and every page whose path has no parameter. A page like `/docs/:slug` has as many paths as there are rows — list them here (`server.executeAs` runs a seeded read as a charter role) |
61
62
  | `routes?` | routes of the app's own that `nisc start` registers before the site (a sign-in handoff, a webhook) |
62
63
  | `dist?` | where the bundler writes the terminal (default `dist`) |
64
+ | `stylesheet?` | where the built page's stylesheet goes: `'page'` (the default — written into `index.html`, see `nisc build`) or `'file'` (left as the bundler linked it) |
63
65
  | `checks?` | the check suite `nisc check` runs (default `src/dev/all-checks.ts`) |
64
66
  | `tokenKey?` | the wire's token key, when it is not `nisc.token` |
65
67
  | `dev?` | what only `nisc dev` uses: `dev.signIn(server, who)` mints a token for `/dev/as/<who>` (`null`: nobody of that name) |
@@ -112,14 +114,51 @@ at all — nova's DOM adapter, `renderToString` from
112
114
  | `draw` | the shell, drawn to a string |
113
115
  | `adopt` | `(root, shell)` — the page picking the markup up |
114
116
  | `htmlAttributes?` | what the kit would put on `<html>` from an effect |
117
+ | `site?` | the address the site is served at (`"https://example.com"`) — see "The head of each page" |
115
118
  | `paths?` | the paths to build (default `/`) — an app that maps paths to actions lists its own |
116
119
  | `waitMs?` | how long a build waits for a screen to be whole (default 5000) |
117
- | `dist?`, `checks?` | as above |
120
+ | `dist?`, `stylesheet?`, `checks?` | as above |
118
121
 
119
122
  The built `index.html` must hold the empty root, `<div id="root"></div>` — that
120
123
  is where a screen goes. The adoption check needs a DOM: `jsdom`, installed in
121
124
  the app.
122
125
 
126
+ ### The head of each page
127
+
128
+ Either kind. A page's title, its description and the card shown where a link
129
+ to it is pasted are things its **screen says about itself** — so they are a
130
+ node in a layout, bound to the action's data like everything else on the
131
+ screen. Nova's `nova:head` draws nothing:
132
+
133
+ ```typescript
134
+ { component: 'nova:head', props: { title: '$.page.title', description: '$.page.lead', image: '$.page.cover', kind: 'article' } }
135
+ ```
136
+
137
+ `build`, `export` and `start` read it off the screen they drew and write it
138
+ into the built `index.html`'s `<head>`: what it says takes the place of the tag
139
+ that said the same thing (the `<title>`, the description, `og:title`,
140
+ `og:description`, `og:type`, `og:image`, a JSON-LD script for `structured`),
141
+ and a tag the page does not have yet is added. Everything it does not speak of
142
+ is left as `index.html` has it — the icon, the viewport, `og:site_name`. A
143
+ path whose screen has no head node goes out with `index.html`'s own, and a
144
+ build of an app that has one somewhere says which is which. Nothing is
145
+ registered and no code is written: the app names no tag.
146
+
147
+ With more than one on the screen (a dialog opened over a page) the last one
148
+ speaks, whole. In the page the tab's title follows the same node as the screen
149
+ moves, and goes back to `index.html`'s when the screen has none.
150
+
151
+ **Where a page lives is not its screen's to say.** A layout never holds its own
152
+ address. `site` in the config is the address the site is served at; with it,
153
+ every path's document says its own canonical address (`<link rel="canonical">`
154
+ and `og:url`), and a picture a head names is given a whole address. Without
155
+ it, `index.html`'s canonical tag goes out in every file as it is — which, for
156
+ every path but one, names another page. A build with more than one path says
157
+ so.
158
+
159
+ An app with no head node and no `site` is built exactly as it was before
160
+ either existed.
161
+
123
162
  The config is TypeScript, loaded with the app's own `tsconfig.json` — path
124
163
  aliases included. `nisc.config.mts`, `.js` and `.mjs` are found too. A config
125
164
  that hands over both `boot` and `shell` has not said which it is, and is
@@ -127,6 +166,28 @@ refused.
127
166
 
128
167
  ## `nisc build`
129
168
 
169
+ **Either kind: the stylesheet goes in the page.** A drawn page arrives as
170
+ markup, and a browser paints none of it until it has the stylesheet — as a file
171
+ of its own, a second round trip before the first paint. So once the app's vite
172
+ has bundled, the `index.html` it wrote has each stylesheet it links written
173
+ into it as a `<style>`, and one response paints the page. It is done once, to
174
+ the file in `dist/`, so `build`, `export`, `start` and moss's document all hand
175
+ out the same head. The stylesheet's own file stays in `dist/`.
176
+
177
+ ```
178
+ nisc: /assets/index-DALMMv7I.css is in the page (0.7 kB) — one response paints it
179
+ ```
180
+
181
+ A link is left as it is, and the build says why, when moving the stylesheet
182
+ could change what it means: the link says more than where the file is (a
183
+ `media`, a `title`), the file is not in `dist/` (another origin, a vite `base`),
184
+ or the stylesheet names another file relative to itself (`url(font.woff2)`,
185
+ `@import`). Vite writes those as absolute paths, which survive.
186
+
187
+ `stylesheet: 'file'` in the config turns it off — what an app needs when its
188
+ host sends a `Content-Security-Policy` that forbids inline styles. With
189
+ `--skip-bundle` the page is taken as it is: whoever built it finished it.
190
+
130
191
  **An app with its own shell.** Bundles the app, then for every path boots it,
131
192
  draws it, and checks what it drew:
132
193
 
@@ -142,7 +203,7 @@ draws it, and checks what it drew:
142
203
  |---|---|
143
204
  | **drawn** | the boot threw, or the screen drew to nothing |
144
205
  | **whole** | something was still loading when `waitMs` ran out — a file that says "loading" is not the page |
145
- | **same twice** | a second boot drew different markup (it says where they part) — the page's boot would not match the file |
206
+ | **same twice** | a second boot drew different markup, or said a different head (it says where they part) — the page's boot would not match the file |
146
207
  | **adopted** | inside a DOM, a third boot ran the app's own `adopt` over the markup and the adapter complained: a hydration error, or a rebuilt root that is not what it was handed |
147
208
 
148
209
  And one that holds by construction: `shell` is handed a path and nothing else,
@@ -197,6 +258,11 @@ will stand beside the files — the socket at `/socket` on the same origin —
197
258
  `--allow-live` writes the site anyway: each such file is a true first screen,
198
259
  and its terminal connects.
199
260
 
261
+ A folder carries no headers, so what a browser may keep of it is the host's to
262
+ say. What `nisc start` says is the rule to give it: everything under `/assets/`
263
+ kept for a year (`public, max-age=31536000, immutable`), everything else asked
264
+ about each time (`no-cache`).
265
+
200
266
  ## `nisc start`
201
267
 
202
268
  **An app with its own shell:** serves the built folder, and answers each path
@@ -207,7 +273,30 @@ as the app answers now, not as it answered at build. No shell is kept.
207
273
  every page **drawn for whoever is asking** — the app's own screen at `/`, a
208
274
  manifest page at its path. A signed-in person gets their screen in the markup
209
275
  (`private, no-store`); nobody gets the page as nobody sees it. `--port <n>`, or
210
- `$PORT`, default 8787.
276
+ `$PORT`, default 8787. A name with an extension that is neither a file in
277
+ `dist/` nor a page is a missing file, answered 404 — never a screen.
278
+
279
+ **Either kind**, around the app's handler:
280
+
281
+ - **What a browser may keep.** What the bundler wrote under `/assets/` is named
282
+ by its content: `public, max-age=31536000, immutable` — kept for a year, not
283
+ asked about again. Every other file is `no-cache`: asked about each time, and
284
+ answered `304` when it has not changed. An answer that already says for
285
+ itself is left alone — a drawn document does (`no-cache` for nobody,
286
+ `private, no-store` for somebody).
287
+ - **How it travels.** Text a browser reads — the document, scripts,
288
+ stylesheets, JSON, SVG, wasm — goes out compressed, brotli or gzip by what
289
+ was asked for (`Vary: Accept-Encoding`), a piece at a time: an answer that
290
+ streams still streams. Fonts and images are already compressed and are left
291
+ alone, and so is an event stream.
292
+
293
+ Neither touches the app server's own paths (`/api`, `/catalog`, `/socket`,
294
+ `/operator`, `/integrations`): what those answer is theirs to say.
295
+
296
+ The bundler copies the app's `public/` into `dist/` as it is. A file of the
297
+ app's own under `public/assets/` would be kept for a year under a name that
298
+ says nothing about its content — `nisc build` says so when it finds one. Keep
299
+ such files elsewhere in `public/`.
211
300
 
212
301
  ## `nisc dev`
213
302
 
@@ -241,7 +330,7 @@ with the app's own `tsx`. Its exit code is the suite's.
241
330
  | `--root <dir>` | the app's root (default: the current directory) |
242
331
  | `--out <dir>` | `export`: where the files go (default `out`) |
243
332
  | `--allow-live` | `export`: write even though some path wants a server |
244
- | `--skip-bundle` | `build`, `export`: the terminal is already built |
333
+ | `--skip-bundle` | `build`, `export`: the terminal is already built — it is neither bundled nor has its stylesheet written into its page |
245
334
  | `--port <n>` | `dev`, `start`: the port (`start`: `$PORT`, then 8787) |
246
335
 
247
336
  ## License
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-PODTS3SZ.js');
33
+ const { isShellProject, loadProject } = await import('./project-RTSKTGE3.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"));
@@ -11,6 +11,14 @@ var isProject = (value) => {
11
11
  const [moss, own] = [has(value, "boot"), has(value, "shell")];
12
12
  return moss !== own && (moss || has(value, "adopt"));
13
13
  };
14
+ var isSite = (value) => {
15
+ if (typeof value !== "string") return false;
16
+ try {
17
+ return ["http:", "https:"].includes(new URL(value).protocol);
18
+ } catch {
19
+ return false;
20
+ }
21
+ };
14
22
  var configFileOf = (root) => CONFIG_NAMES.find((name) => existsSync(join(root, name)));
15
23
  var loadProject = async (root) => {
16
24
  const name = configFileOf(root);
@@ -27,9 +35,12 @@ var loadProject = async (root) => {
27
35
  `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).`
28
36
  );
29
37
  }
38
+ if (project.site !== void 0 && !isSite(project.site)) {
39
+ throw new Error(`nisc: ${file} gives \`site\` as ${JSON.stringify(project.site)} \u2014 it is the address the site is served at, whole: "https://example.com".`);
40
+ }
30
41
  return project;
31
42
  };
32
43
 
33
44
  export { configFileOf, isProject, isShellProject, loadProject };
34
- //# sourceMappingURL=chunk-MRNC4GI5.js.map
35
- //# sourceMappingURL=chunk-MRNC4GI5.js.map
45
+ //# sourceMappingURL=chunk-DFB5BOHX.js.map
46
+ //# sourceMappingURL=chunk-DFB5BOHX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/project.ts"],"names":[],"mappings":";;;;;AA6GA,IAAM,YAAA,GAAe,CAAC,gBAAA,EAAkB,iBAAA,EAAmB,kBAAkB,iBAAiB,CAAA;AAE9F,IAAM,GAAA,GAAM,CAAC,KAAA,EAAe,GAAA,KAAyB,OAAO,OAAA,CAAQ,GAAA,CAAI,KAAA,EAAO,GAAG,CAAA,KAAM,UAAA;AAEjF,IAAM,cAAA,GAAiB,CAAC,OAAA,KAAsD,OAAA,IAAW;AAEzF,IAAM,SAAA,GAAY,CAAC,KAAA,KAAyC;AACjE,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,GAAA,CAAI,KAAA,EAAO,MAAM,CAAA,EAAG,OAAO,KAAA;AAC/E,EAAA,MAAM,CAAC,IAAA,EAAM,GAAG,CAAA,GAAI,CAAC,GAAA,CAAI,KAAA,EAAO,MAAM,CAAA,EAAG,GAAA,CAAI,KAAA,EAAO,OAAO,CAAC,CAAA;AAE5D,EAAA,OAAO,IAAA,KAAS,GAAA,KAAQ,IAAA,IAAQ,GAAA,CAAI,OAAO,OAAO,CAAA,CAAA;AACpD;AAGA,IAAM,MAAA,GAAS,CAAC,KAAA,KAA4B;AAC1C,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,IAAI;AACF,IAAA,OAAO,CAAC,SAAS,QAAQ,CAAA,CAAE,SAAS,IAAI,GAAA,CAAI,KAAK,CAAA,CAAE,QAAQ,CAAA;AAAA,EAC7D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF,CAAA;AAGO,IAAM,YAAA,GAAe,CAAC,IAAA,KAAqC,YAAA,CAAa,IAAA,CAAK,CAAC,IAAA,KAAS,UAAA,CAAW,IAAA,CAAK,IAAA,EAAM,IAAI,CAAC,CAAC;AAInH,IAAM,WAAA,GAAc,OAAO,IAAA,KAAuC;AACvE,EAAA,MAAM,IAAA,GAAO,aAAa,IAAI,CAAA;AAC9B,EAAA,MAAM,OAAO,IAAA,KAAS,MAAA,GAAY,MAAA,GAAY,IAAA,CAAK,MAAM,IAAI,CAAA;AAC7D,EAAA,IAAI,SAAS,MAAA,EAAW;AACtB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,IAAI,CAAA,iFAAA,CAAmF,CAAA;AAAA,EACvI;AACA,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAM,OAAO,aAAa,CAAA;AAC/C,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,IAAA,EAAM,eAAe,CAAA;AAC3C,EAAA,MAAM,MAAA,GAAkB,MAAM,QAAA,CAAS,aAAA,CAAc,IAAI,CAAA,CAAE,IAAA,EAAM,EAAE,SAAA,EAAW,MAAA,CAAA,IAAA,CAAY,KAAK,GAAI,UAAA,CAAW,QAAQ,CAAA,GAAI,EAAE,UAAS,GAAI,IAAK,CAAA;AAC9I,EAAA,MAAM,OAAA,GAAmB,MAAA,KAAW,IAAA,IAAQ,OAAO,MAAA,KAAW,WAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,SAAS,CAAA,GAAI,MAAA;AAC1G,EAAA,IAAI,CAAC,SAAA,CAAU,OAAO,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,SAAS,IAAI,CAAA,kLAAA;AAAA,KACf;AAAA,EACF;AACA,EAAA,IAAI,QAAQ,IAAA,KAAS,MAAA,IAAa,CAAC,MAAA,CAAO,OAAA,CAAQ,IAAI,CAAA,EAAG;AACvD,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,MAAA,EAAS,IAAI,CAAA,mBAAA,EAAsB,KAAK,SAAA,CAAU,OAAA,CAAQ,IAAI,CAAC,CAAA,8EAAA,CAA2E,CAAA;AAAA,EAC5J;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-DFB5BOHX.js","sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { DocumentConfig, MossServer } 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, and a picture a screen's\n // head names is given a whole one. Without it, where a document lives is left\n // 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 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 };\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"]}
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { loadProject, isShellProject, configFileOf, isProject } from './chunk-MRNC4GI5.js';
1
+ import { loadProject, isShellProject, configFileOf, isProject } from './chunk-DFB5BOHX.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';
@@ -6,8 +6,10 @@ import { createRequire } from 'module';
6
6
  import { serve } from '@hono/node-server';
7
7
  import { pathToFileURL, fileURLToPath } from 'url';
8
8
  import { tmpdir } from 'os';
9
- import { shellSettled } from '@niscorp/nova';
9
+ import { shellSettled, shellView } from '@niscorp/nova';
10
+ import { placeHead, headOf } from '@niscorp/nova/document';
10
11
  import { livenessOf } from '@niscorp/nova/reflect';
12
+ import { createBrotliCompress, constants, createGzip } from 'zlib';
11
13
 
12
14
  var isViteApi = (value) => value !== null && typeof value === "object" && typeof Reflect.get(value, "createServer") === "function";
13
15
  var viteOf = async (root) => {
@@ -36,6 +38,7 @@ var mossPlugin = async (configFile) => {
36
38
  ...booted.close !== void 0 ? { close: booted.close } : {},
37
39
  draw: project.draw,
38
40
  ...project.htmlAttributes !== void 0 ? { htmlAttributes: project.htmlAttributes } : {},
41
+ ...project.site !== void 0 ? { site: project.site } : {},
39
42
  ...project.tokenKey !== void 0 ? { tokenKey: project.tokenKey } : {},
40
43
  ...signIn !== void 0 ? { signIn: (who) => signIn(booted.server, who) } : {}
41
44
  };
@@ -69,6 +72,7 @@ var fileOf = (path) => {
69
72
  };
70
73
  var pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
71
74
  var routeTable = (routes) => {
75
+ const headed = routes.some((route) => route.head !== void 0);
72
76
  const rows = routes.map((route) => {
73
77
  const mark = !route.drawn ? "\u2717" : route.live ? "\u25CF" : "\u25CB";
74
78
  const what = route.page === void 0 ? "the app" : `page ${route.page}`;
@@ -78,7 +82,8 @@ var routeTable = (routes) => {
78
82
  ...route.drawn && !route.settled ? ["it was still loading when the wait ran out \u2014 drawn with what it had"] : [],
79
83
  ...route.drawnWith.length > 0 ? [`drawn with ${route.drawnWith.join(", ")} \u2014 as it answered at build`] : []
80
84
  ];
81
- return { mark, path: route.path, what, served, notes };
85
+ const head = headed && route.drawn ? [route.head === void 0 ? "head: the template\u2019s own" : `head: its own, said by ${route.head.action ?? "the shell\u2019s chrome"}`] : [];
86
+ return { mark, path: route.path, what, served, notes, head };
82
87
  });
83
88
  const widths = {
84
89
  path: Math.max(5, ...rows.map((row) => row.path.length)),
@@ -88,7 +93,7 @@ var routeTable = (routes) => {
88
93
  const lines = [` ${pad("Route", widths.path + 2)}${pad("What", widths.what + 2)}${pad("Served as", widths.served + 2)}Because`];
89
94
  for (const row of rows) {
90
95
  const head = `${row.mark} ${pad(row.path, widths.path + 2)}${pad(row.what, widths.what + 2)}${pad(row.served, widths.served + 2)}`;
91
- const [first, ...rest] = row.notes.length > 0 ? row.notes : ["nothing on it can still happen"];
96
+ const [first, ...rest] = [...row.notes.length > 0 ? row.notes : ["nothing on it can still happen"], ...row.head];
92
97
  lines.push(`${head}${first ?? ""}`);
93
98
  for (const note of rest) lines.push(`${" ".repeat(head.length)}${note}`);
94
99
  }
@@ -123,12 +128,13 @@ var factsOf = (shell) => {
123
128
  const sorted = (set) => [...set].sort();
124
129
  return { actions: sorted(actions), opensWith: sorted(opensWith), callsLater: sorted(callsLater), listens: sorted(listens) };
125
130
  };
131
+ var documentOf = (project, template, path, drawn) => placeHead(placeScreen(template, drawn.screen, drawn.attributes), drawn.head?.head, { ...project.site !== void 0 ? { site: project.site } : {}, path });
126
132
  var drawOnce = async (project, path) => {
127
133
  const booted = await project.shell({ path });
128
134
  try {
129
135
  const whole = await shellSettled(booted.shell, { waitMs: project.waitMs ?? DEFAULT_BUILD_WAIT_MS });
130
136
  const screen = await project.draw(booted.shell);
131
- return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, facts: factsOf(booted.shell) };
137
+ return { screen, whole, attributes: project.htmlAttributes?.(booted.shell) ?? {}, head: headOf(shellView(booted.shell).api), facts: factsOf(booted.shell) };
132
138
  } finally {
133
139
  await booted.close?.();
134
140
  }
@@ -171,6 +177,8 @@ var surveyShell = async (root, project, template) => {
171
177
  if (!drawn.whole) problems.push(`whole: it was still loading after ${project.waitMs ?? DEFAULT_BUILD_WAIT_MS}ms`);
172
178
  const again = await drawOnce(project, path);
173
179
  if (again.screen !== drawn.screen) problems.push(`same twice: a second boot drew different markup${differenceOf(drawn.screen, again.screen)}`);
180
+ const [head, headAgain] = [JSON.stringify(drawn.head ?? null), JSON.stringify(again.head ?? null)];
181
+ if (headAgain !== head) problems.push(`same twice: a second boot said a different head${differenceOf(head, headAgain)}`);
174
182
  } catch (error) {
175
183
  problems.push(`drawn: ${said(error)}`);
176
184
  }
@@ -184,9 +192,10 @@ var surveyShell = async (root, project, template) => {
184
192
  const problems = [...route.problems, ...complaints.map((complaint) => `adopted: ${complaint}`)];
185
193
  return {
186
194
  path: route.path,
187
- html: route.drawn === void 0 ? template : placeScreen(template, route.drawn.screen, route.drawn.attributes),
195
+ html: route.drawn === void 0 ? template : documentOf(project, template, route.path, route.drawn),
188
196
  problems,
189
- ...route.drawn?.facts ?? none
197
+ ...route.drawn?.facts ?? none,
198
+ ...route.drawn?.head !== void 0 ? { head: route.drawn.head } : {}
190
199
  };
191
200
  });
192
201
  };
@@ -201,13 +210,16 @@ var shellRouteTable = (routes) => {
201
210
  const width = Math.max(5, ...routes.map((route) => route.path.length)) + 2;
202
211
  const lines = [` ${pad2("Route", width)}First screen`];
203
212
  const indent = " ".repeat(width + 2);
213
+ const headed = routes.some((route) => route.head !== void 0);
214
+ const headNote = (route) => route.head === void 0 ? "head: the template\u2019s own" : `head: its own, said by ${route.head.action ?? "the shell\u2019s chrome"}`;
204
215
  for (const route of routes) {
205
216
  const ok = route.problems.length === 0;
206
217
  const notes = ok ? [
207
218
  `drawn \xB7 whole \xB7 same twice \xB7 adopted${route.actions.length > 0 ? ` (${route.actions.join(", ")})` : ""}`,
208
219
  ...route.opensWith.length > 0 ? [`opened with ${route.opensWith.join(", ")} \u2014 in the file as answered at build`] : [],
209
220
  ...route.callsLater.length > 0 ? [`can still call ${route.callsLater.join(", ")}`] : [],
210
- ...route.listens.length > 0 ? [`waits on ${route.listens.join(", ")}`] : []
221
+ ...route.listens.length > 0 ? [`waits on ${route.listens.join(", ")}`] : [],
222
+ ...headed ? [headNote(route)] : []
211
223
  ] : route.problems;
212
224
  const [head, ...rest] = notes;
213
225
  lines.push(`${ok ? "\u25CB" : "\u2717"} ${pad2(route.path, width)}${head ?? ""}`);
@@ -243,22 +255,193 @@ var shellSite = (project, dist) => {
243
255
  const path = decodeURIComponent(new URL(request.url).pathname);
244
256
  if (path !== "/" && path !== "/index.html") {
245
257
  const file = resolve(base, `.${path}`);
246
- if ((file === base || file.startsWith(base + sep)) && existsSync(file) && statSync(file).isFile()) {
247
- return new Response(readFileSync(file), { headers: { "content-type": TYPES[extname(file)] ?? "application/octet-stream" } });
258
+ const stats = file === base || file.startsWith(base + sep) ? statSync(file, { throwIfNoEntry: false }) : void 0;
259
+ if (stats?.isFile() === true) {
260
+ return new Response(readFileSync(file), {
261
+ headers: { "content-type": TYPES[extname(file)] ?? "application/octet-stream", "content-length": String(stats.size), "last-modified": stats.mtime.toUTCString() }
262
+ });
248
263
  }
249
264
  if (extname(path) !== "") return new Response("not found", { status: 404 });
250
265
  }
251
266
  const template = readFileSync(join(base, "index.html"), "utf8");
252
267
  const headers = { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" };
253
268
  try {
254
- const drawn = await drawOnce(project, path === "/index.html" ? "/" : path);
255
- return new Response(placeScreen(template, drawn.screen, drawn.attributes), { headers });
269
+ const at = path === "/index.html" ? "/" : path;
270
+ return new Response(documentOf(project, template, at, await drawOnce(project, at)), { headers });
256
271
  } catch (error) {
257
272
  console.error(`[nisc] "${path}" could not be drawn \u2014 serving it undrawn:`, error);
258
273
  return new Response(template, { headers });
259
274
  }
260
275
  };
261
276
  };
277
+ var KEPT_PATHS = /^\/assets\//;
278
+ var KEPT_FOREVER = "public, max-age=31536000, immutable";
279
+ var withCaching = (handler, options = {}) => async (request, ...rest) => {
280
+ const response = await handler(request, ...rest);
281
+ if (request.method !== "GET" && request.method !== "HEAD" || response.status !== 200) return response;
282
+ const path = new URL(request.url).pathname;
283
+ if (options.except?.test(path) === true) return response;
284
+ if (response.headers.has("cache-control")) return response;
285
+ const headers = new Headers(response.headers);
286
+ if (KEPT_PATHS.test(path)) {
287
+ headers.set("cache-control", KEPT_FOREVER);
288
+ return new Response(response.body, { status: 200, headers });
289
+ }
290
+ headers.set("cache-control", "no-cache");
291
+ const [since, modified] = [request.headers.get("if-modified-since"), headers.get("last-modified")];
292
+ if (since !== null && modified !== null && Date.parse(since) >= Date.parse(modified)) {
293
+ await response.body?.cancel();
294
+ headers.delete("content-length");
295
+ return new Response(null, { status: 304, headers });
296
+ }
297
+ return new Response(response.body, { status: 200, headers });
298
+ };
299
+ var COMPRESSIBLE = /^(text\/(?!event-stream)|application\/(json|javascript|xml|manifest\+json|wasm)|image\/svg\+xml)/i;
300
+ var SMALL_BYTES = 1024;
301
+ var BROTLI_QUALITY = 5;
302
+ var encodingFor = (header) => {
303
+ const offered = /* @__PURE__ */ new Map();
304
+ for (const part of (header ?? "").toLowerCase().split(",")) {
305
+ const [name = "", ...parameters] = part.split(";").map((piece) => piece.trim());
306
+ const weight = parameters.find((parameter) => parameter.startsWith("q="));
307
+ if (name !== "") offered.set(name, weight === void 0 ? 1 : Number(weight.slice(2)));
308
+ }
309
+ if ((offered.get("br") ?? 0) > 0) return "br";
310
+ if ((offered.get("gzip") ?? 0) > 0) return "gzip";
311
+ return void 0;
312
+ };
313
+ var compressorFor = (encoding) => encoding === "br" ? createBrotliCompress({ flush: constants.BROTLI_OPERATION_FLUSH, params: { [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY } }) : createGzip({ flush: constants.Z_SYNC_FLUSH });
314
+ var compressedBody = (source, encoding, whole) => {
315
+ const reader = source.getReader();
316
+ const compressor = compressorFor(encoding);
317
+ const pieces = [];
318
+ let isLetGo = false;
319
+ let finished = () => void 0;
320
+ const ended = new Promise((done) => {
321
+ finished = done;
322
+ });
323
+ return new ReadableStream({
324
+ start: (controller) => {
325
+ compressor.on("data", (piece) => {
326
+ if (isLetGo) return;
327
+ if (whole !== void 0) pieces.push(piece);
328
+ controller.enqueue(piece);
329
+ });
330
+ compressor.on("end", () => {
331
+ if (!isLetGo) {
332
+ whole?.(Buffer.concat(pieces));
333
+ controller.close();
334
+ }
335
+ finished();
336
+ });
337
+ compressor.on("error", (error) => {
338
+ if (!isLetGo) controller.error(error);
339
+ finished();
340
+ });
341
+ },
342
+ pull: async () => {
343
+ const { done, value } = await reader.read().catch((error) => {
344
+ compressor.destroy();
345
+ throw error;
346
+ });
347
+ if (done) {
348
+ compressor.end();
349
+ return ended;
350
+ }
351
+ return new Promise((taken) => {
352
+ compressor.write(value, () => taken());
353
+ });
354
+ },
355
+ cancel: async (reason) => {
356
+ isLetGo = true;
357
+ compressor.destroy();
358
+ await reader.cancel(reason);
359
+ }
360
+ });
361
+ };
362
+ var withCompression = (handler, options = {}) => {
363
+ const remembered = /* @__PURE__ */ new Map();
364
+ return async (request, ...rest) => {
365
+ const response = await handler(request, ...rest);
366
+ if (request.method !== "GET" || response.status !== 200 || response.body === null) return response;
367
+ const path = new URL(request.url).pathname;
368
+ if (options.except?.test(path) === true) return response;
369
+ if (!COMPRESSIBLE.test(response.headers.get("content-type") ?? "")) return response;
370
+ if (response.headers.has("content-encoding") || /no-transform/i.test(response.headers.get("cache-control") ?? "")) return response;
371
+ const headers = new Headers(response.headers);
372
+ const varies = (headers.get("vary") ?? "").toLowerCase().split(",").map((name) => name.trim());
373
+ if (!varies.includes("accept-encoding")) headers.append("vary", "Accept-Encoding");
374
+ const encoding = encodingFor(request.headers.get("accept-encoding"));
375
+ const length = headers.get("content-length");
376
+ if (encoding === void 0 || length !== null && Number(length) < SMALL_BYTES) return new Response(response.body, { status: 200, headers });
377
+ headers.set("content-encoding", encoding);
378
+ headers.delete("content-length");
379
+ const etag = headers.get("etag");
380
+ if (etag !== null && !etag.startsWith("W/")) headers.set("etag", `W/${etag}`);
381
+ if (!/\bimmutable\b/i.test(headers.get("cache-control") ?? "")) return new Response(compressedBody(response.body, encoding), { status: 200, headers });
382
+ const key = `${encoding} ${path} ${headers.get("last-modified") ?? ""}`;
383
+ const known = remembered.get(key);
384
+ if (known === void 0) return new Response(compressedBody(response.body, encoding, (bytes) => remembered.set(key, bytes)), { status: 200, headers });
385
+ await response.body.cancel();
386
+ headers.set("content-length", String(known.length));
387
+ return new Response(known, { status: 200, headers });
388
+ };
389
+ };
390
+ var siteHandler = (handler, options = {}) => withCompression(withCaching(handler, options), options);
391
+ var attributesOf = (tag) => {
392
+ const found = {};
393
+ for (const match of tag.slice(5).matchAll(/([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {
394
+ const name = match[1];
395
+ if (name !== void 0) found[name.toLowerCase()] = match[2] ?? match[3] ?? match[4] ?? "";
396
+ }
397
+ return found;
398
+ };
399
+ var PLAIN = /* @__PURE__ */ new Set(["rel", "href", "crossorigin"]);
400
+ var isPortableUrl = (url) => url === "" || /^(\/|data:|blob:|https?:|#)/i.test(url);
401
+ var whyStylesheetStays = (css) => {
402
+ if (/@import\b/i.test(css)) return "it imports another stylesheet";
403
+ for (const match of css.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi)) {
404
+ const url = (match[1] ?? match[2] ?? match[3] ?? "").trim();
405
+ if (!isPortableUrl(url)) return `it names a file relative to itself (${url})`;
406
+ }
407
+ return void 0;
408
+ };
409
+ var stylesheetInPage = (html, read) => {
410
+ const inPage = [];
411
+ const left = [];
412
+ const rewritten = html.replace(/<link\b[^>]*>/gi, (tag) => {
413
+ const attributes = attributesOf(tag);
414
+ if ((attributes["rel"] ?? "").toLowerCase() !== "stylesheet") return tag;
415
+ const href = attributes["href"] ?? "";
416
+ const stays = (why2) => {
417
+ left.push({ href, why: why2 });
418
+ return tag;
419
+ };
420
+ const extra = Object.keys(attributes).filter((name) => !PLAIN.has(name));
421
+ if (extra.length > 0) return stays(`its link says more than where it is (${extra.join(", ")})`);
422
+ if (!href.startsWith("/") || href.startsWith("//") || /[?#]/.test(href)) return stays("it is not a path into the built folder");
423
+ const css = read(href);
424
+ if (css === void 0) return stays("it is not in the built folder");
425
+ const why = whyStylesheetStays(css);
426
+ if (why !== void 0) return stays(why);
427
+ inPage.push({ href, bytes: Buffer.byteLength(css) });
428
+ return `<style>${css.replace(/<\/(style)/gi, "<\\/$1")}</style>`;
429
+ });
430
+ return { html: rewritten, inPage, left };
431
+ };
432
+ var writeStylesheetIntoPage = (dist) => {
433
+ const page = join(dist, "index.html");
434
+ if (!existsSync(page)) return { inPage: [], left: [] };
435
+ const base = resolve(dist);
436
+ const read = (href) => {
437
+ const file = resolve(base, `.${href}`);
438
+ return file.startsWith(base + sep) && existsSync(file) && statSync(file).isFile() ? readFileSync(file, "utf8") : void 0;
439
+ };
440
+ const html = readFileSync(page, "utf8");
441
+ const rewrite = stylesheetInPage(html, read);
442
+ if (rewrite.html !== html) writeFileSync(page, rewrite.html);
443
+ return { inPage: rewrite.inPage, left: rewrite.left };
444
+ };
262
445
 
263
446
  // src/commands.ts
264
447
  var say = (options) => options.print ?? ((line) => console.log(line));
@@ -277,9 +460,26 @@ var toolOf = (root, name, bin) => {
277
460
  return join(dirname(manifestPath), relative);
278
461
  };
279
462
  var distOf = (root, project) => resolve(root, project.dist ?? "dist");
280
- var bundle = (options) => {
463
+ var bundle = (options, project) => {
281
464
  const result = spawnSync(process.execPath, [toolOf(options.root, "vite", "vite"), "build"], { cwd: options.root, stdio: "inherit" });
282
465
  if (result.status !== 0) throw new Error("nisc: the bundler failed \u2014 nothing was drawn.");
466
+ if (project.stylesheet === "file") return;
467
+ const print = say(options);
468
+ const { inPage, left } = writeStylesheetIntoPage(distOf(options.root, project));
469
+ if (inPage.length + left.length > 0) print("");
470
+ for (const sheet of inPage) print(`nisc: ${sheet.href} is in the page (${(sheet.bytes / 1024).toFixed(1)} kB) \u2014 one response paints it`);
471
+ for (const sheet of left) print(`nisc: ${sheet.href} stays a file \u2014 ${sheet.why}`);
472
+ 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.");
473
+ };
474
+ var warnOfOwnAssets = (options) => {
475
+ if (!existsSync(join(options.root, "public", "assets"))) return;
476
+ 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 \u2014 keep them elsewhere in public/.");
477
+ };
478
+ var warnOfOneAddress = (options, project, template, paths) => {
479
+ if (project.site !== void 0 || paths < 2 || !/<link\b[^>]*\brel\s*=\s*["']?canonical\b/i.test(template)) return;
480
+ say(options)("");
481
+ say(options)(`nisc: index.html names one canonical address and this app has ${paths} paths \u2014 every file would say it lives there.`);
482
+ say(options)(' `site: "https://\u2026"` in nisc.config.ts gives each path its own.');
283
483
  };
284
484
  var templateOf = (options, project) => {
285
485
  const template = join(distOf(options.root, project), "index.html");
@@ -297,6 +497,7 @@ var survey = async (options, project) => {
297
497
  template,
298
498
  draw: project.draw,
299
499
  ...project.htmlAttributes !== void 0 ? { htmlAttributes: project.htmlAttributes } : {},
500
+ ...project.site !== void 0 ? { site: project.site } : {},
300
501
  ...project.tokenKey !== void 0 ? { tokenKey: project.tokenKey } : {},
301
502
  paths
302
503
  });
@@ -305,18 +506,22 @@ var survey = async (options, project) => {
305
506
  }
306
507
  };
307
508
  var buildShell = async (options, project) => {
308
- const routes = await surveyShell(options.root, project, templateOf(options, project));
509
+ const template = templateOf(options, project);
510
+ const routes = await surveyShell(options.root, project, template);
309
511
  say(options)("");
310
512
  say(options)(shellRouteTable(routes));
513
+ warnOfOneAddress(options, project, template, routes.length);
311
514
  return { kind: "shell", ok: routes.every((route) => route.problems.length === 0), routes };
312
515
  };
313
516
  var build = async (options) => {
314
517
  const project = await loadProject(options.root);
315
- if (options.skipBundle !== true) bundle(options);
518
+ if (options.skipBundle !== true) bundle(options, project);
519
+ warnOfOwnAssets(options);
316
520
  if (isShellProject(project)) return buildShell(options, project);
317
521
  const routes = await survey(options, project);
318
522
  say(options)("");
319
523
  say(options)(routeTable(routes));
524
+ warnOfOneAddress(options, project, templateOf(options, project), routes.length);
320
525
  return { kind: "moss", ok: routes.every((route) => route.drawn), routes };
321
526
  };
322
527
  var write = (options, project, out, routes) => {
@@ -367,21 +572,22 @@ var start = async (options) => {
367
572
  if (!existsSync(join(dist, "index.html"))) throw new Error(`nisc: no built terminal in ${dist} \u2014 run \`nisc build\`.`);
368
573
  const port = options.port ?? Number(process.env["PORT"] ?? 8787);
369
574
  if (isShellProject(project)) {
370
- const httpServer2 = serve({ fetch: shellSite(project, dist), port });
575
+ const httpServer2 = serve({ fetch: siteHandler(shellSite(project, dist)), port });
371
576
  const url2 = await listening(httpServer2, options);
372
577
  say(options)(`nisc: serving ${url2} \u2014 the built app, each path\u2019s first screen drawn; the shell is the page\u2019s own`);
373
578
  return { url: url2, close: async () => void httpServer2.close() };
374
579
  }
375
- const { attachSocket, mountSite } = await import('@niscorp/moss/node');
580
+ const { attachSocket, mountSite, MOSS_PATHS } = await import('@niscorp/moss/node');
376
581
  const booted = await project.boot();
377
582
  await project.routes?.(booted.server);
378
583
  mountSite(booted.server, {
379
584
  dist,
380
585
  draw: project.draw,
381
586
  ...project.htmlAttributes !== void 0 ? { htmlAttributes: project.htmlAttributes } : {},
587
+ ...project.site !== void 0 ? { site: project.site } : {},
382
588
  ...project.tokenKey !== void 0 ? { tokenKey: project.tokenKey } : {}
383
589
  });
384
- const httpServer = serve({ fetch: booted.server.fetch, port });
590
+ const httpServer = serve({ fetch: siteHandler(booted.server.fetch, { except: MOSS_PATHS }), port });
385
591
  attachSocket(httpServer, booted.server.socket);
386
592
  const url = await listening(httpServer, options);
387
593
  say(options)(`nisc: serving ${url} \u2014 the built terminal, its pages drawn; the socket at /socket`);