@ferax564/noma-cli 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +199 -0
  3. package/bin/noma.mjs +8 -0
  4. package/dist/ast.d.ts +111 -0
  5. package/dist/ast.js +23 -0
  6. package/dist/ast.js.map +1 -0
  7. package/dist/book.d.ts +56 -0
  8. package/dist/book.js +120 -0
  9. package/dist/book.js.map +1 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +573 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/diff.d.ts +29 -0
  14. package/dist/diff.js +77 -0
  15. package/dist/diff.js.map +1 -0
  16. package/dist/fmt.d.ts +1 -0
  17. package/dist/fmt.js +105 -0
  18. package/dist/fmt.js.map +1 -0
  19. package/dist/ids.d.ts +15 -0
  20. package/dist/ids.js +27 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +20 -0
  23. package/dist/index.js +12 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/inline.d.ts +14 -0
  26. package/dist/inline.js +83 -0
  27. package/dist/inline.js.map +1 -0
  28. package/dist/loader.d.ts +12 -0
  29. package/dist/loader.js +59 -0
  30. package/dist/loader.js.map +1 -0
  31. package/dist/parser.d.ts +7 -0
  32. package/dist/parser.js +434 -0
  33. package/dist/parser.js.map +1 -0
  34. package/dist/patch.d.ts +61 -0
  35. package/dist/patch.js +530 -0
  36. package/dist/patch.js.map +1 -0
  37. package/dist/renderer-html.d.ts +44 -0
  38. package/dist/renderer-html.js +929 -0
  39. package/dist/renderer-html.js.map +1 -0
  40. package/dist/renderer-json.d.ts +5 -0
  41. package/dist/renderer-json.js +4 -0
  42. package/dist/renderer-json.js.map +1 -0
  43. package/dist/renderer-llm.d.ts +29 -0
  44. package/dist/renderer-llm.js +275 -0
  45. package/dist/renderer-llm.js.map +1 -0
  46. package/dist/renderer-noma.d.ts +10 -0
  47. package/dist/renderer-noma.js +179 -0
  48. package/dist/renderer-noma.js.map +1 -0
  49. package/dist/renderer-site.d.ts +11 -0
  50. package/dist/renderer-site.js +175 -0
  51. package/dist/renderer-site.js.map +1 -0
  52. package/dist/validator.d.ts +24 -0
  53. package/dist/validator.js +699 -0
  54. package/dist/validator.js.map +1 -0
  55. package/dist/verify.d.ts +10 -0
  56. package/dist/verify.js +141 -0
  57. package/dist/verify.js.map +1 -0
  58. package/package.json +83 -0
  59. package/schemas/ast.schema.json +187 -0
  60. package/schemas/capability.schema.json +70 -0
  61. package/schemas/patch-op.schema.json +92 -0
  62. package/schemas/patch-transaction.schema.json +28 -0
  63. package/schemas/transcript.schema.json +95 -0
  64. package/src/ast.ts +152 -0
  65. package/src/book.ts +162 -0
  66. package/src/cli.ts +595 -0
  67. package/src/diff.ts +108 -0
  68. package/src/fmt.ts +126 -0
  69. package/src/ids.ts +42 -0
  70. package/src/index.ts +20 -0
  71. package/src/inline.ts +92 -0
  72. package/src/loader.ts +55 -0
  73. package/src/parser.ts +501 -0
  74. package/src/patch.ts +646 -0
  75. package/src/renderer-html.ts +1047 -0
  76. package/src/renderer-json.ts +9 -0
  77. package/src/renderer-llm.ts +320 -0
  78. package/src/renderer-noma.ts +220 -0
  79. package/src/renderer-site.ts +245 -0
  80. package/src/validator.ts +733 -0
  81. package/src/verify.ts +157 -0
  82. package/themes/dark.css +382 -0
  83. package/themes/default.css +537 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ferax564
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,199 @@
1
+ # Noma
2
+
3
+ > **Readable source for beautiful agent artifacts.**
4
+
5
+ Noma is a plain-text format for books, docs, research, dashboards, and webpages. It is:
6
+
7
+ - readable like Markdown
8
+ - structured like data
9
+ - renderable like HTML
10
+ - printable like PDF
11
+ - editable by AI agents at the **block level** — not via full-file rewrites
12
+
13
+ ```
14
+ .noma → typed AST → HTML / PDF / JSON / LLM context
15
+ ```
16
+
17
+ **Live site:** <https://ferax564.github.io/noma/> — landing page, demo gallery, rendered HTML/PDF/LLM/JSON for every example, full docs.
18
+
19
+ ## Why
20
+
21
+ Markdown is excellent for prose, weak for grids, cards, claims, plots, citations, and stable agent edits. HTML is the opposite — great as a render target, unpleasant as long-term source. Noma sits between them: a small directive syntax that compiles to clean semantic HTML, prints cleanly to PDF, exports a deterministic LLM-friendly form, and gives agents stable block IDs they can patch without rewriting whole files.
22
+
23
+ See [`docs/direction.noma`](docs/direction.noma) for the full positioning and [PLAN.md §23](PLAN.md) for the three-layer model and the central design test every feature must pass.
24
+
25
+ ## Hello, Noma
26
+
27
+ ```noma
28
+ ---
29
+ title: ASML Investment Thesis
30
+ ---
31
+
32
+ # ASML Investment Thesis
33
+
34
+ ::claim{id="asml-euv-moat" confidence=0.82}
35
+ ASML has a durable moat because it is the only supplier of EUV lithography systems at scale.
36
+ ::
37
+
38
+ ::evidence{for="asml-euv-moat" source="annual-report-2025"}
39
+ ASML continues to report strong demand for EUV systems from leading-edge customers.
40
+ ::
41
+
42
+ ::grid{columns=2}
43
+ :::card{title="Bull Case"}
44
+ EUV demand stays structurally high.
45
+ :::
46
+
47
+ :::card{title="Bear Case"}
48
+ Export restrictions and cyclicality.
49
+ :::
50
+ ::
51
+ ```
52
+
53
+ That's the whole language — directive blocks (`::name{attrs} ... ::`), Markdown-ish inline text, YAML frontmatter, and stable block IDs.
54
+
55
+ ## Quick start
56
+
57
+ Install the public CLI:
58
+
59
+ ```bash
60
+ npm install -g @ferax564/noma-cli
61
+ noma --version
62
+ noma init my-spec
63
+ noma render my-spec/demo.noma --to html --out my-spec/demo.html
64
+ ```
65
+
66
+ From a checkout:
67
+
68
+ ```bash
69
+ git clone https://github.com/ferax564/noma.git
70
+ cd noma
71
+ npm install
72
+
73
+ # render one demo to HTML / LLM / JSON / .noma source
74
+ npm run noma -- render examples/agent-plan.noma --to html --out dist/agent-plan.html
75
+ npm run noma -- render examples/agent-plan.noma --to llm
76
+ npm run noma -- render examples/agent-plan.noma --to llm --select claim,evidence,risk --exclude dataset --budget 12000
77
+ npm run noma -- render examples/agent-plan.noma --to json
78
+ npm run noma -- render examples/agent-plan.noma --to noma # AST → .noma roundtrip
79
+ npm run noma -- ids examples/book/book.noma.yml # global ID + alias map for agents
80
+
81
+ # pick a theme
82
+ npm run noma -- render examples/research-thesis.noma --to html --theme dark
83
+
84
+ # render a multi-file book (chapters resolved relative to the manifest)
85
+ npm run noma -- render examples/book/book.noma.yml --to html --out dist/book.html
86
+
87
+ # block-level patch — agent-safe edits, no full-file rewrite
88
+ npm run noma -- patch examples/thesis.noma \
89
+ --op '{"op":"update_attribute","id":"asml-euv-moat","key":"confidence","value":0.95}' \
90
+ --inplace
91
+
92
+ # validate a document
93
+ npm run noma -- check examples/research-thesis.noma
94
+
95
+ # render in GitHub Actions
96
+ # - uses: ferax564/noma@v0.11.0
97
+ # with:
98
+ # input: docs/spec.noma
99
+ # output: dist/spec.html
100
+
101
+ # build the full site (examples + docs + book + dark-theme demo + landing + PDFs)
102
+ npm run build:site
103
+ open dist/index.html
104
+
105
+ # re-align pipe tables in source (idempotent; skips fenced code blocks)
106
+ npm run noma -- fmt examples/research-thesis.noma --inplace
107
+ ```
108
+
109
+ ## Block-level edits
110
+
111
+ Agents and CI pipelines patch single blocks instead of rewriting whole files. Seven operations cover the editing flows that matter:
112
+
113
+ ```bash
114
+ noma patch thesis.noma --op '{"op":"replace_block","id":"claim-x","content":"::claim{id=\"claim-x\" confidence=0.9}\nNew body.\n::"}'
115
+ noma patch thesis.noma --op '{"op":"replace_body","id":"claim-x","content":"Sharper body text."}'
116
+ noma patch thesis.noma --op '{"op":"update_heading","id":"risk-section","title":"Known Risks"}'
117
+ noma patch thesis.noma --op '{"op":"add_block","parent":"risks","content":"::risk{id=\"r1\" severity=\"high\" owner=\"me\"}\nNew risk.\n::"}'
118
+ noma patch thesis.noma --op '{"op":"delete_block","id":"deprecated"}'
119
+ noma patch thesis.noma --op '{"op":"update_attribute","id":"claim-x","key":"confidence","value":0.85}'
120
+ noma patch thesis.noma --op '{"op":"rename_id","from":"claim-x","to":"claim-renamed"}'
121
+ noma patch thesis.noma --ops patch-transaction.json --inplace
122
+ ```
123
+
124
+ `rename_id` retargets reference attributes such as `for=`, `parent=`, `dataset=`, `block=`, and `ref=`, plus `[[wikilink]]` references across the document. The source-preserving patch path rewrites only the addressed line range or inserted block, so unrelated bytes stay byte-identical. See [`docs/agent-protocol.noma`](docs/agent-protocol.noma) and [`docs/compatibility.noma`](docs/compatibility.noma).
125
+
126
+ ## GitHub Action
127
+
128
+ Render and upload a Noma artifact from any repository:
129
+
130
+ ```yaml
131
+ name: Render docs
132
+
133
+ on: [push, pull_request]
134
+
135
+ jobs:
136
+ noma:
137
+ runs-on: ubuntu-latest
138
+ steps:
139
+ - uses: actions/checkout@v4
140
+ - uses: ferax564/noma@v0.11.0
141
+ with:
142
+ input: docs/spec.noma
143
+ output: dist/spec.html
144
+ to: html
145
+ strict: true
146
+ artifact-name: spec-preview
147
+ ```
148
+
149
+ The action installs the CLI from the checked-out action ref by default, runs `noma check`, renders the requested target, and uploads the result with `actions/upload-artifact`. Use `to: site` when `input` is a book manifest and `output` is a directory. For explicit dependency control, set `cli-package` to any npm package spec or `cli-version` to an `@ferax564/noma-cli` npm version range.
150
+
151
+ ## Demos
152
+
153
+ Three artifacts that exercise the full block surface end-to-end. Each renders to HTML, PDF, LLM context, and JSON AST from a single `.noma` source. For the workflow narrative behind them, see the [case studies](docs/case-studies.noma).
154
+
155
+ | Demo | What it shows | Live |
156
+ | ---- | ------------- | ---- |
157
+ | **Agent planning artifact** ([source](examples/agent-plan.noma)) | Q3 roadmap decision — options, decision matrix, claims/evidence/risks, agent tasks, copy-as-prompt buttons | [HTML](https://ferax564.github.io/noma/examples/agent-plan.html) · [PDF](https://ferax564.github.io/noma/examples/agent-plan.pdf) · [LLM](https://ferax564.github.io/noma/examples/agent-plan.llm.txt) · [JSON](https://ferax564.github.io/noma/examples/agent-plan.json) |
158
+ | **Technical documentation** ([source](examples/tech-doc.noma)) | CLI reference page — tabs, callouts, code blocks, architecture diagram, cross-links | [HTML](https://ferax564.github.io/noma/examples/tech-doc.html) · [PDF](https://ferax564.github.io/noma/examples/tech-doc.pdf) · [LLM](https://ferax564.github.io/noma/examples/tech-doc.llm.txt) · [JSON](https://ferax564.github.io/noma/examples/tech-doc.json) |
159
+ | **Investment thesis** ([source](examples/research-thesis.noma)) | Vertical-AI thesis — claims with confidence scores, counterevidence, risks, datasets, plots, quarterly review tasks | [HTML](https://ferax564.github.io/noma/examples/research-thesis.html) · [PDF](https://ferax564.github.io/noma/examples/research-thesis.pdf) · [LLM](https://ferax564.github.io/noma/examples/research-thesis.llm.txt) · [JSON](https://ferax564.github.io/noma/examples/research-thesis.json) |
160
+
161
+ ## Guides for adoption
162
+
163
+ - [Case studies](docs/case-studies.noma) — agent-refreshable research memo, decision artifact, technical-doc publishing, and memory workflow.
164
+ - [Comparison guide](docs/comparison.noma) — when to choose Noma vs Markdown, MDX, raw HTML, or collaborative docs.
165
+ - [Agent editing guide](docs/agent-guide.noma) — the safe loop for ID discovery, patch transactions, validation, and strict rendering.
166
+ - [Starter templates](docs/templates.noma) — copyable research memo, decision record, technical spec, and agent refresh templates under `examples/templates/`.
167
+
168
+ ## What ships today
169
+
170
+ - `@ferax564/noma-cli` (this package) — hand-written parser with no parser-combinator dependency. Supports directive blocks, frontmatter, headings, lists, code, quotes, GitHub-style tables, and inline markdown. The parser is exported alongside the CLI; `import { parse } from "@ferax564/noma-cli"` works in any Node 20+ project.
171
+ - Typed AST in `src/ast.ts` — discriminated union, exhaustively switched everywhere.
172
+ - HTML renderer with a default CSS theme + a `dark` alternate (`--theme dark`), a print stylesheet, and per-block `{variant="..."}` styling. Native rendering for grids, cards, tabs, callouts, claims/evidence/risks, decisions, open questions, datasets, real inline-data plots (line + bar SVG, no JS), agent tasks, export buttons, controls, tables, the new `::table` directive, and `::state_change` deltas. `::html` / `::svg` / `::script` escape hatches can be blocked with `--no-unsafe`; `--strict` also omits external CDN runtimes for math, diagrams, and Plotly.
173
+ - LLM renderer — deterministic plain-text output for context windows; escape-hatch bodies always stripped. Supports `--select`, `--exclude`, and `--budget` for scoped agent context.
174
+ - JSON renderer — full AST export.
175
+ - `.noma` source printer — AST → `.noma` (roundtrip-safe). Backs `noma render --to noma`; source-preserving `noma patch` rewrites addressed spans directly.
176
+ - `noma fmt` — re-aligns GitHub-style pipe tables in source; respects pipes inside `` `code spans` `` and `\|` escapes; leaves everything else byte-identical.
177
+ - Validator — wikilink references resolve across paragraphs, quotes, list items, headings, table cells, and book chapters. Default rules: duplicate IDs, broken references (incl. wikilinks), plot/figure issues, plot/dataset linkage (`plot-unknown-dataset`, `plot-unknown-column`), `plot-mixed-delimiters`, claim-without-evidence, risk-without-owner, decision-without-status, agent-task-without-scope, stale-citation, escape-hatch-untrusted, evidence-missing-for, state_change shape rules, and `out-of-profile-directive` when a `profile` is declared. Per-block opt-out with the `noverify` flag.
178
+ - Profiles — declare `profile: research | technical | minimal` in frontmatter as a contract about which directives the document uses; downstream tools can narrow safely.
179
+ - Plot/dataset linkage — `::plot{dataset="<id>" column="<name>" xcolumn="<name>"}` resolves against sibling `::dataset` blocks at render time.
180
+ - Citation staleness — global default 365 days, override via frontmatter `stale_citation_days`, per-citation `stale_after_days=N`, or CLI `--stale-days <n>`.
181
+ - CLI — `noma --version`, `noma init`, `noma parse | render | ids | schema | check | export | patch | fmt`. Patch ops include `replace_block`, `replace_body`, `update_heading`, `add_block`, `delete_block`, `update_attribute`, and `rename_id`, plus transaction-shaped `--ops` files with optional pre/post validation.
182
+ - GitHub Action — `uses: ferax564/noma@v0.11.0` validates, renders, and uploads HTML/LLM/JSON/Noma/site artifacts in CI.
183
+ - Book manifests (`book.noma.yml`) + multi-file rendering. CLI auto-detects manifest extension; chapters resolve relative to its directory.
184
+ - Starter templates under `examples/templates/` for research memos, decision records, technical specs, and agent refresh packs.
185
+ - Seven examples: three demos (agent-plan, tech-doc, research-thesis), the original thesis/landing/book-chapter, and the `examples/book/` 3-chapter book.
186
+ - Ten docs (all written in Noma): direction, spec, compatibility, getting started, agent patch protocol, architecture, comparison guide, case studies, agent editing guide, and starter templates.
187
+ - Hand-crafted HTML landing page (`site/index.html`).
188
+ - PDF demo exports via Puppeteer.
189
+ - GitHub Pages deployment on every push to `main`.
190
+
191
+ See [`PLAN.md`](PLAN.md) for the long-term vision, [`docs/direction.noma`](docs/direction.noma) for the positioning, [`docs/spec.noma`](docs/spec.noma) for the format spec, and [`CHANGELOG.md`](CHANGELOG.md) for what changed when.
192
+
193
+ ## Status
194
+
195
+ **Status:** v0.11.0 — first public `@ferax564/*` release line. v0.11 adds bundled JSON Schemas via `noma schema <name>`, source-preserving `replace_body` and `update_heading` patch ops, `parent=` retargeting for `rename_id`, package manifest hardening for public scoped publish, a packed-CLI smoke gate, the compatibility policy, adoption guides, and namespaced directive parsing groundwork for future community packs. Carries the v0.9.0 experimental `@ferax564/noma-agent-sdk` v0.1.0 unchanged. See [`CHANGELOG.md`](CHANGELOG.md) and `PLAN.md` §24.20 for the full release tracker.
196
+
197
+ ## License
198
+
199
+ MIT © 2026 ferax564
package/bin/noma.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // Production CLI entry — loads the compiled dist build.
3
+ // During development use `npm run noma -- ...` (which goes through tsx).
4
+ import("../dist/cli.js").catch((err) => {
5
+ console.error("noma: failed to load CLI. Did you run `npm run build`?");
6
+ console.error(err);
7
+ process.exit(1);
8
+ });
package/dist/ast.d.ts ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Noma AST — single source of truth.
3
+ *
4
+ * Renderers and the validator must import types from this file. Adding a new
5
+ * node variant requires extending the `Node` union and updating every
6
+ * renderer's switch (the compiler will tell you where).
7
+ */
8
+ export type AttrValue = string | number | boolean;
9
+ export type Attrs = Record<string, AttrValue>;
10
+ export interface Position {
11
+ line: number;
12
+ column: number;
13
+ }
14
+ interface NodeBase {
15
+ /** Stable, user-facing identifier when set. Auto-generated for headings. */
16
+ id?: string;
17
+ /**
18
+ * Additional IDs that resolve to this node. Populated by:
19
+ * • frontmatter `aliases:` list (attaches to chapter root section)
20
+ * • chapter filename slug in book mode
21
+ * • path-scoped heading ID in book mode (registers the bare slug as alias)
22
+ */
23
+ aliases?: string[];
24
+ /** Source position of the node's first character. */
25
+ pos?: Position;
26
+ /**
27
+ * 1-based last source line covered by this node (inclusive). Populated by
28
+ * the parser; used by `patchSource` to splice ranges without re-rendering
29
+ * the rest of the document.
30
+ */
31
+ endLine?: number;
32
+ }
33
+ export interface DocumentNode extends NodeBase {
34
+ type: "document";
35
+ meta: Record<string, unknown>;
36
+ children: Node[];
37
+ }
38
+ export interface FrontmatterNode extends NodeBase {
39
+ type: "frontmatter";
40
+ /** Parsed YAML object (string keys → arbitrary values). */
41
+ data: Record<string, unknown>;
42
+ /** Raw frontmatter source text (between the --- fences, exclusive). */
43
+ raw: string;
44
+ }
45
+ export interface SectionNode extends NodeBase {
46
+ type: "section";
47
+ level: number;
48
+ title: string;
49
+ children: Node[];
50
+ }
51
+ export interface ParagraphNode extends NodeBase {
52
+ type: "paragraph";
53
+ content: string;
54
+ }
55
+ export interface CodeNode extends NodeBase {
56
+ type: "code";
57
+ lang?: string;
58
+ content: string;
59
+ }
60
+ export interface ListNode extends NodeBase {
61
+ type: "list";
62
+ ordered: boolean;
63
+ items: ListItemNode[];
64
+ }
65
+ export interface ListItemNode extends NodeBase {
66
+ type: "list_item";
67
+ content: string;
68
+ }
69
+ export interface QuoteNode extends NodeBase {
70
+ type: "quote";
71
+ content: string;
72
+ }
73
+ export interface ThematicBreakNode extends NodeBase {
74
+ type: "thematic_break";
75
+ }
76
+ export type TableAlign = "left" | "center" | "right" | null;
77
+ export interface TableNode extends NodeBase {
78
+ type: "table";
79
+ /** Header cells (one row). Inline markdown is preserved as plain strings. */
80
+ header: string[];
81
+ /** Per-column alignment from the separator row (`:---`, `:---:`, `---:`). */
82
+ align: TableAlign[];
83
+ /** Body rows, each with one entry per column. */
84
+ rows: string[][];
85
+ }
86
+ /**
87
+ * Generic block directive — covers every typed semantic block (claim, evidence,
88
+ * grid, card, plot, dataset, agent_task, ...). Renderers dispatch on `name`.
89
+ */
90
+ export interface DirectiveNode extends NodeBase {
91
+ type: "directive";
92
+ name: string;
93
+ attrs: Attrs;
94
+ /** Inline body text (when the block has no nested children). */
95
+ body?: string;
96
+ /** Nested directive children (grids, cards, etc.). */
97
+ children: Node[];
98
+ }
99
+ export type Node = DocumentNode | SectionNode | FrontmatterNode | ParagraphNode | CodeNode | ListNode | ListItemNode | QuoteNode | ThematicBreakNode | TableNode | DirectiveNode;
100
+ export type BlockNode = Exclude<Node, ListItemNode | FrontmatterNode>;
101
+ export interface Diagnostic {
102
+ severity: "error" | "warning" | "info";
103
+ code: string;
104
+ message: string;
105
+ pos?: Position;
106
+ nodeId?: string;
107
+ }
108
+ export declare const isDirective: (n: Node) => n is DirectiveNode;
109
+ export declare const isSection: (n: Node) => n is SectionNode;
110
+ export declare function walk(node: Node): Generator<Node>;
111
+ export {};
package/dist/ast.js ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Noma AST — single source of truth.
3
+ *
4
+ * Renderers and the validator must import types from this file. Adding a new
5
+ * node variant requires extending the `Node` union and updating every
6
+ * renderer's switch (the compiler will tell you where).
7
+ */
8
+ export const isDirective = (n) => n.type === "directive";
9
+ export const isSection = (n) => n.type === "section";
10
+ export function* walk(node) {
11
+ yield node;
12
+ if (node.type === "document" ||
13
+ node.type === "section" ||
14
+ node.type === "directive") {
15
+ for (const child of node.children)
16
+ yield* walk(child);
17
+ }
18
+ else if (node.type === "list") {
19
+ for (const item of node.items)
20
+ yield* walk(item);
21
+ }
22
+ }
23
+ //# sourceMappingURL=ast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast.js","sourceRoot":"","sources":["../src/ast.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAmIH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAO,EAAsB,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC;AACnF,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,CAAO,EAAoB,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC;AAE7E,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,IAAU;IAC9B,MAAM,IAAI,CAAC;IACX,IACE,IAAI,CAAC,IAAI,KAAK,UAAU;QACxB,IAAI,CAAC,IAAI,KAAK,SAAS;QACvB,IAAI,CAAC,IAAI,KAAK,WAAW,EACzB,CAAC;QACD,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ;YAAE,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACxD,CAAC;SAAM,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAChC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK;YAAE,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnD,CAAC;AACH,CAAC"}
package/dist/book.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { DocumentNode, SectionNode } from "./ast.js";
2
+ /**
3
+ * Shape of `book.yml` manifests. Note: YAML keys are snake_case (`trusted_publishing`),
4
+ * read directly from the manifest map. The typed shape below covers fields the
5
+ * loader/renderer consume by name; unrecognised keys pass through untouched.
6
+ *
7
+ * Recognised security-posture keys (read at the render path, not surfaced as
8
+ * typed fields):
9
+ * - `trusted_publishing: true` — implies `--no-unsafe` for every render driven
10
+ * by this manifest. Disables `::html`, `::svg`, `::script` escape hatches.
11
+ * The manifest is the final word; no CLI flag re-enables them once the
12
+ * manifest forbids them.
13
+ */
14
+ export interface BookManifest {
15
+ title?: string;
16
+ author?: string;
17
+ chapters: string[];
18
+ outputs?: {
19
+ html?: {
20
+ theme?: string;
21
+ math?: "katex" | "none";
22
+ };
23
+ llm?: Record<string, unknown>;
24
+ pdf?: Record<string, unknown>;
25
+ };
26
+ }
27
+ export interface LoadedChapter {
28
+ /** Path-safe chapter slug derived from filename (or root H1 id). */
29
+ slug: string;
30
+ /** Source path of the chapter file (absolute). */
31
+ source: string;
32
+ /** Parsed chapter document with scoped IDs applied. */
33
+ doc: DocumentNode;
34
+ }
35
+ /**
36
+ * Load a YAML book manifest and assemble a single DocumentNode by
37
+ * concatenating each chapter's parsed AST. Chapter file paths are
38
+ * resolved relative to the manifest's directory.
39
+ */
40
+ export declare function loadBook(manifestPath: string): DocumentNode;
41
+ /**
42
+ * Load every chapter listed in a book manifest as a separate DocumentNode,
43
+ * applying chapter-scoped heading IDs in book mode. Used by the multi-page
44
+ * site renderer; loadBook() concatenates the same set into one doc.
45
+ */
46
+ export declare function loadBookChapters(manifestPath: string): {
47
+ manifest: Record<string, unknown>;
48
+ chapters: LoadedChapter[];
49
+ baseDir: string;
50
+ };
51
+ export declare function isBookManifestPath(path: string): boolean;
52
+ /**
53
+ * Pull the implicit chapter list off a fully-loaded document for TOC
54
+ * purposes. Each top-level h1 section is treated as a chapter heading.
55
+ */
56
+ export declare function listChapters(doc: DocumentNode): SectionNode[];
package/dist/book.js ADDED
@@ -0,0 +1,120 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, resolve } from "node:path";
3
+ import yaml from "js-yaml";
4
+ import { walk } from "./ast.js";
5
+ import { parse } from "./parser.js";
6
+ import { inlineDatasetSources } from "./loader.js";
7
+ /**
8
+ * Load a YAML book manifest and assemble a single DocumentNode by
9
+ * concatenating each chapter's parsed AST. Chapter file paths are
10
+ * resolved relative to the manifest's directory.
11
+ */
12
+ export function loadBook(manifestPath) {
13
+ const absManifest = resolve(manifestPath);
14
+ const raw = readFileSync(absManifest, "utf8");
15
+ const parsed = yaml.load(raw);
16
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
17
+ throw new Error(`book manifest must be a YAML object: ${manifestPath}`);
18
+ }
19
+ const manifest = parsed;
20
+ const chapters = Array.isArray(manifest.chapters)
21
+ ? manifest.chapters.filter((c) => typeof c === "string")
22
+ : [];
23
+ if (chapters.length === 0) {
24
+ throw new Error(`book manifest has no chapters: ${manifestPath}`);
25
+ }
26
+ const baseDir = dirname(absManifest);
27
+ const meta = {};
28
+ if (typeof manifest.title === "string")
29
+ meta.title = manifest.title;
30
+ if (typeof manifest.author === "string")
31
+ meta.author = manifest.author;
32
+ meta.book = {
33
+ chapters: chapters.length,
34
+ manifest: manifestPath,
35
+ };
36
+ const children = [];
37
+ const loaded = loadChapters(chapters, baseDir);
38
+ for (const ch of loaded) {
39
+ for (const child of ch.doc.children)
40
+ children.push(child);
41
+ }
42
+ return { type: "document", meta, children };
43
+ }
44
+ /**
45
+ * Load every chapter listed in a book manifest as a separate DocumentNode,
46
+ * applying chapter-scoped heading IDs in book mode. Used by the multi-page
47
+ * site renderer; loadBook() concatenates the same set into one doc.
48
+ */
49
+ export function loadBookChapters(manifestPath) {
50
+ const absManifest = resolve(manifestPath);
51
+ const raw = readFileSync(absManifest, "utf8");
52
+ const parsed = yaml.load(raw);
53
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
54
+ throw new Error(`book manifest must be a YAML object: ${manifestPath}`);
55
+ }
56
+ const manifest = parsed;
57
+ const chapterPaths = Array.isArray(manifest.chapters)
58
+ ? manifest.chapters.filter((c) => typeof c === "string")
59
+ : [];
60
+ if (chapterPaths.length === 0) {
61
+ throw new Error(`book manifest has no chapters: ${manifestPath}`);
62
+ }
63
+ const baseDir = dirname(absManifest);
64
+ return { manifest, chapters: loadChapters(chapterPaths, baseDir), baseDir };
65
+ }
66
+ function loadChapters(chapterPaths, baseDir) {
67
+ const out = [];
68
+ for (const chapter of chapterPaths) {
69
+ const chapterPath = isAbsolute(chapter) ? chapter : resolve(baseDir, chapter);
70
+ const source = readFileSync(chapterPath, "utf8");
71
+ const doc = parse(source, { filename: chapterPath });
72
+ inlineDatasetSources(doc, dirname(chapterPath));
73
+ const slug = chapterSlug(chapterPath, doc);
74
+ scopeHeadingIds(doc, slug);
75
+ out.push({ slug, source: chapterPath, doc });
76
+ }
77
+ return out;
78
+ }
79
+ function chapterSlug(chapterPath, doc) {
80
+ const root = doc.children.find((n) => n.type === "section" && n.level === 1);
81
+ if (root && root.id)
82
+ return root.id;
83
+ const base = chapterPath.replace(/\\/g, "/").split("/").pop() ?? chapterPath;
84
+ const stem = base.replace(/\.noma$/i, "").replace(/^\d+[-_]/, "");
85
+ return stem.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-|-$/g, "");
86
+ }
87
+ /**
88
+ * In book mode, every heading slug is path-prefixed by its chapter root.
89
+ * `# Risk Premia 3` + `## Risks` → `risk-premia-3` and `risk-premia-3/risks`.
90
+ * Original (un-prefixed) ID is kept as an alias on the same node so any
91
+ * legacy `[[risks]]` writes still resolve to the first occurrence.
92
+ */
93
+ function scopeHeadingIds(doc, chapterSlug) {
94
+ for (const node of walk(doc)) {
95
+ if (node.type !== "section")
96
+ continue;
97
+ if (node.level === 1)
98
+ continue;
99
+ if (!node.id)
100
+ continue;
101
+ if (node.id.startsWith(`${chapterSlug}/`))
102
+ continue;
103
+ const original = node.id;
104
+ node.id = `${chapterSlug}/${original}`;
105
+ const aliases = new Set(node.aliases ?? []);
106
+ aliases.add(original);
107
+ node.aliases = [...aliases];
108
+ }
109
+ }
110
+ export function isBookManifestPath(path) {
111
+ return /\.ya?ml$/i.test(path);
112
+ }
113
+ /**
114
+ * Pull the implicit chapter list off a fully-loaded document for TOC
115
+ * purposes. Each top-level h1 section is treated as a chapter heading.
116
+ */
117
+ export function listChapters(doc) {
118
+ return doc.children.filter((n) => n.type === "section" && n.level === 1);
119
+ }
120
+ //# sourceMappingURL=book.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"book.js","sourceRoot":"","sources":["../src/book.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,IAAI,MAAM,SAAS,CAAC;AAE3B,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAkCnD;;;;GAIG;AACH,MAAM,UAAU,QAAQ,CAAC,YAAoB;IAC3C,MAAM,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1C,MAAM,GAAG,GAAG,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9B,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,O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