@nowline/export 0.0.0-dev.20260603150914.g70caedb

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Lolay, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,79 @@
1
+ import type { ResolvedFontPair } from '@nowline/export-core';
2
+ import { type ThemeName } from '@nowline/layout';
3
+ export type { PdfOrientation, ResolvedFontPair } from '@nowline/export-core';
4
+ export type { ThemeName } from '@nowline/layout';
5
+ /** The eight canonical export formats. Every surface produces exactly these. */
6
+ export type ExportFormat = 'svg' | 'png' | 'pdf' | 'html' | 'mermaid' | 'xlsx' | 'msproj' | 'json';
7
+ /**
8
+ * The only environment-specific seam in the kernel. The host supplies I/O —
9
+ * reading source/include/asset files and the resvg wasm bytes — and nothing
10
+ * else. Every implementation must return identical bytes for identical inputs;
11
+ * the host contributes I/O only, never a byte of the artifact (see
12
+ * specs/export-determinism.md § Invariant).
13
+ */
14
+ export interface HostEnv {
15
+ /** Read a source / include / asset text file as UTF-8. Drives `include` resolution. */
16
+ readSource(path: string): Promise<string>;
17
+ /** Read a binary asset (logos, icons) referenced by the roadmap. */
18
+ readAsset(path: string): Promise<Uint8Array>;
19
+ /** Return the `resvg.wasm` bytes used by the PNG rasterizer. */
20
+ loadWasm(): Promise<ArrayBuffer>;
21
+ }
22
+ /**
23
+ * Everything the kernel needs that is neither the source text nor host I/O.
24
+ * `today`, `locale`, `theme`, and `fonts` are explicit inputs — never ambient
25
+ * reads of the system clock, time zone, or `navigator.language` — so the output
26
+ * bytes are a pure function of (source, these inputs, pinned toolchain version).
27
+ */
28
+ export interface RenderInputs {
29
+ /**
30
+ * Absolute path to the `.nowline` source file. Used as the base for
31
+ * resolving relative `include` directives and relative asset references.
32
+ * For in-memory sources with no includes/assets, pass any stable path
33
+ * string (e.g. `'/dev/null/unnamed.nowline'`).
34
+ */
35
+ sourcePath: string;
36
+ /** Now-line date. Always an explicit UTC midnight; never `Date.now()`. Omit to suppress the now-line. */
37
+ today?: Date;
38
+ /** Locale tag used to format timeline tick labels. Explicit; never the host's. */
39
+ locale: string;
40
+ /** Theme (light / dark / grayscale). */
41
+ theme: ThemeName;
42
+ /**
43
+ * Pinned font byte buffers — canonical export embeds the bundled DejaVu
44
+ * pair. Required for formats that rasterize or embed fonts (png, pdf).
45
+ * Optional for text-only formats (svg, html, json, mermaid, msproj, xlsx).
46
+ */
47
+ fonts?: ResolvedFontPair;
48
+ /** Optional fixed canvas width in px. */
49
+ width?: number;
50
+ /** Drop `<a>` links from the rendered SVG. */
51
+ noLinks?: boolean;
52
+ /** Treat render warnings (e.g. missing assets) as hard errors. */
53
+ strict?: boolean;
54
+ /** PDF page size — a preset name or a custom dimensions string. */
55
+ pageSize?: string;
56
+ /** PDF orientation. */
57
+ orientation?: import('@nowline/export-core').PdfOrientation;
58
+ /** PDF margin in points. */
59
+ marginPt?: number;
60
+ /** PNG pixel-density multiplier (default 2). */
61
+ pngScale?: number;
62
+ /** MS Project start-date override (YYYY-MM-DD). */
63
+ msprojStart?: string;
64
+ }
65
+ /**
66
+ * Produce the export artifact for `source` in `format`. This is the single
67
+ * code path to any exported artifact — no surface re-implements a stage.
68
+ *
69
+ * Text formats (svg / json / html / mermaid / msproj) are returned as UTF-8
70
+ * bytes; binary formats (png / pdf / xlsx) as their native bytes. Returning
71
+ * Uint8Array for every format keeps the determinism gate able to `sha256` one
72
+ * value per (fixture, format).
73
+ *
74
+ * Note: PNG rasterizes via @nowline/export-png (native resvg-js) until s4
75
+ * swaps it to @resvg/resvg-wasm. The `host.loadWasm()` seam is reserved for
76
+ * that swap and is not called here yet.
77
+ */
78
+ export declare function exportDocument(source: string, format: ExportFormat, inputs: RenderInputs, host: HostEnv): Promise<Uint8Array>;
79
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAgB,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAKhE,YAAY,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7E,YAAY,EAAE,SAAS,EAAE,M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EACd,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,YAAY,EACpB,IAAI,EAAE,OAAO,GACd,OAAO,CAAC,UAAU,CAAC,CAqFrB"}
package/dist/index.js ADDED
@@ -0,0 +1,258 @@
1
+ // @nowline/export — the shared export kernel.
2
+ //
3
+ // The single code path from `.nowline` source to any of the eight export
4
+ // artifacts (parse → resolve includes → layout → renderSvg → format adapter).
5
+ // Every surface — the CLI, the `@nowline/mcp` server, the VS Code extension,
6
+ // and the Free/Pro web apps — runs this same code with the same inputs, so
7
+ // they all produce byte-for-byte identical output for the same source and the
8
+ // same pinned toolchain version.
9
+ //
10
+ // Spec: specs/export-determinism.md (the byte-identity precedent and the
11
+ // HostEnv / RenderInputs contract this surface implements).
12
+ //
13
+ // Plan: s2 implements the kernel pipeline (parse → resolve → layout →
14
+ // renderSvg → format dispatch). s4 swaps export-png to resvg-wasm.
15
+ import { collectDocumentDiagnostics, createNowlineServices, resolveIncludes, } from '@nowline/core';
16
+ import { layoutRoadmap } from '@nowline/layout';
17
+ import { renderSvg } from '@nowline/renderer';
18
+ import { URI } from 'langium';
19
+ let cachedServices;
20
+ let docCounter = 0;
21
+ function getExportServices() {
22
+ if (!cachedServices)
23
+ cachedServices = createNowlineServices();
24
+ return cachedServices;
25
+ }
26
+ function freshUri() {
27
+ // Always mint a fresh URI — re-using one lets Langium mutate the prior
28
+ // document in place, causing spurious diagnostics on repeated exports.
29
+ return URI.parse(`memory:///kernel-${++docCounter}.nowline`);
30
+ }
31
+ // ---- Inline JSON serializer ---------------------------------------------------
32
+ //
33
+ // Equivalent to packages/cli/src/convert/schema.ts. Inlined here so the kernel
34
+ // has no dependency on @nowline/cli.
35
+ const JSON_SCHEMA_VERSION = '1';
36
+ const CONTAINER_KEYS = new Set(['$container', '$containerProperty', '$containerIndex']);
37
+ const RUNTIME_KEYS = new Set(['$cstNode', '$document']);
38
+ function isAstNode(v) {
39
+ return (v !== null && typeof v === 'object' && typeof v.$type === 'string');
40
+ }
41
+ function serializeNode(node, includePositions) {
42
+ const out = { $type: node.$type };
43
+ if (includePositions && node.$cstNode) {
44
+ const cst = node.$cstNode;
45
+ out.$position = {
46
+ start: {
47
+ line: cst.range.start.line + 1,
48
+ column: cst.range.start.character + 1,
49
+ offset: cst.offset,
50
+ },
51
+ end: {
52
+ line: cst.range.end.line + 1,
53
+ column: cst.range.end.character + 1,
54
+ offset: cst.end,
55
+ },
56
+ };
57
+ }
58
+ for (const [key, value] of Object.entries(node)) {
59
+ if (key.startsWith('$') || CONTAINER_KEYS.has(key) || RUNTIME_KEYS.has(key))
60
+ continue;
61
+ out[key] = serializeValue(value, includePositions);
62
+ }
63
+ return out;
64
+ }
65
+ function serializeValue(value, includePositions) {
66
+ if (value === null || value === undefined)
67
+ return value;
68
+ if (Array.isArray(value))
69
+ return value.map((v) => serializeValue(v, includePositions));
70
+ if (isAstNode(value))
71
+ return serializeNode(value, includePositions);
72
+ if (typeof value === 'object') {
73
+ const out = {};
74
+ for (const [k, v] of Object.entries(value)) {
75
+ if (k.startsWith('$') || CONTAINER_KEYS.has(k) || RUNTIME_KEYS.has(k))
76
+ continue;
77
+ out[k] = serializeValue(v, includePositions);
78
+ }
79
+ return out;
80
+ }
81
+ return value;
82
+ }
83
+ function serializeDocumentToJson(document, source, sourcePath) {
84
+ const ast = document.parseResult.value;
85
+ return JSON.stringify({
86
+ $nowlineSchema: JSON_SCHEMA_VERSION,
87
+ file: { uri: `file://${sourcePath}`, source },
88
+ ast: serializeNode(ast, true),
89
+ }, null, 2);
90
+ }
91
+ // ---- MIME inference ----------------------------------------------------------
92
+ function guessMime(ref) {
93
+ const ext = ref.slice(ref.lastIndexOf('.')).toLowerCase();
94
+ if (ext === '.svg')
95
+ return 'image/svg+xml';
96
+ if (ext === '.png')
97
+ return 'image/png';
98
+ if (ext === '.jpg' || ext === '.jpeg')
99
+ return 'image/jpeg';
100
+ if (ext === '.webp')
101
+ return 'image/webp';
102
+ return 'application/octet-stream';
103
+ }
104
+ async function stageDocument(source, inputs, host) {
105
+ const services = getExportServices();
106
+ const uri = freshUri();
107
+ const doc = services.shared.workspace.LangiumDocumentFactory.fromString(source, uri);
108
+ await services.shared.workspace.DocumentBuilder.build([doc], { validation: true });
109
+ const errors = [];
110
+ for (const raw of collectDocumentDiagnostics(doc)) {
111
+ if (raw.origin === 'lexer') {
112
+ errors.push(raw.error.message);
113
+ }
114
+ else if (raw.origin === 'parser') {
115
+ errors.push(raw.error.message);
116
+ }
117
+ else if (raw.diagnostic.severity === 1 /* DiagnosticSeverity.Error */) {
118
+ errors.push(raw.diagnostic.message);
119
+ }
120
+ }
121
+ if (errors.length > 0) {
122
+ throw new Error(`@nowline/export: validation errors in ${inputs.sourcePath}: ${errors.join('; ')}`);
123
+ }
124
+ const ast = doc.parseResult.value;
125
+ const resolved = await resolveIncludes(ast, inputs.sourcePath, {
126
+ services: services.Nowline,
127
+ readFile: host.readSource.bind(host),
128
+ });
129
+ for (const diag of resolved.diagnostics) {
130
+ if (diag.severity === 'error') {
131
+ throw new Error(`@nowline/export: include error in ${inputs.sourcePath}: ${diag.message}`);
132
+ }
133
+ }
134
+ const model = layoutRoadmap(ast, resolved, {
135
+ theme: inputs.theme,
136
+ today: inputs.today,
137
+ width: inputs.width,
138
+ locale: inputs.locale,
139
+ });
140
+ const assetResolver = async (ref) => {
141
+ const bytes = await host.readAsset(ref);
142
+ return { bytes, mime: guessMime(ref) };
143
+ };
144
+ const warnings = [];
145
+ const svg = await renderSvg(model, {
146
+ assetResolver,
147
+ noLinks: inputs.noLinks ?? false,
148
+ strict: inputs.strict ?? false,
149
+ warn: (msg) => warnings.push(msg),
150
+ });
151
+ if (inputs.strict && warnings.length > 0) {
152
+ throw new Error(`@nowline/export: render warnings (--strict): ${warnings.join('; ')}`);
153
+ }
154
+ return {
155
+ svg,
156
+ exportInputs: {
157
+ model,
158
+ ast,
159
+ resolved,
160
+ sourcePath: inputs.sourcePath,
161
+ today: inputs.today,
162
+ },
163
+ document: doc,
164
+ source,
165
+ };
166
+ }
167
+ // ---- Text encoding -----------------------------------------------------------
168
+ const encoder = new TextEncoder();
169
+ function toUtf8(text) {
170
+ return encoder.encode(text);
171
+ }
172
+ // ---- Public API --------------------------------------------------------------
173
+ /**
174
+ * Produce the export artifact for `source` in `format`. This is the single
175
+ * code path to any exported artifact — no surface re-implements a stage.
176
+ *
177
+ * Text formats (svg / json / html / mermaid / msproj) are returned as UTF-8
178
+ * bytes; binary formats (png / pdf / xlsx) as their native bytes. Returning
179
+ * Uint8Array for every format keeps the determinism gate able to `sha256` one
180
+ * value per (fixture, format).
181
+ *
182
+ * Note: PNG rasterizes via @nowline/export-png (native resvg-js) until s4
183
+ * swaps it to @resvg/resvg-wasm. The `host.loadWasm()` seam is reserved for
184
+ * that swap and is not called here yet.
185
+ */
186
+ export async function exportDocument(source, format, inputs, host) {
187
+ if (typeof source !== 'string') {
188
+ throw new TypeError('@nowline/export: source must be a string.');
189
+ }
190
+ if (typeof host?.readSource !== 'function' ||
191
+ typeof host.readAsset !== 'function' ||
192
+ typeof host.loadWasm !== 'function') {
193
+ throw new TypeError('@nowline/export: host must implement the HostEnv interface.');
194
+ }
195
+ if (!(inputs?.today instanceof Date) && inputs?.today !== undefined) {
196
+ throw new TypeError('@nowline/export: inputs.today must be a Date (UTC midnight) or undefined.');
197
+ }
198
+ if (typeof inputs?.sourcePath !== 'string' || inputs.sourcePath.length === 0) {
199
+ throw new TypeError('@nowline/export: inputs.sourcePath must be a non-empty string.');
200
+ }
201
+ const stage = await stageDocument(source, inputs, host);
202
+ if (format === 'svg') {
203
+ return toUtf8(stage.svg);
204
+ }
205
+ if (format === 'json') {
206
+ return toUtf8(serializeDocumentToJson(stage.document, stage.source, inputs.sourcePath));
207
+ }
208
+ if (format === 'html') {
209
+ const mod = await import('@nowline/export-html');
210
+ const html = await mod.exportHtml(stage.exportInputs, stage.svg);
211
+ return toUtf8(html);
212
+ }
213
+ if (format === 'mermaid') {
214
+ const mod = await import('@nowline/export-mermaid');
215
+ const md = mod.exportMermaid(stage.exportInputs);
216
+ return toUtf8(md);
217
+ }
218
+ if (format === 'msproj') {
219
+ const mod = await import('@nowline/export-msproj');
220
+ const xml = mod.exportMsProjXml(stage.exportInputs, {
221
+ startDate: inputs.msprojStart,
222
+ });
223
+ return toUtf8(xml);
224
+ }
225
+ if (format === 'xlsx') {
226
+ const mod = await import('@nowline/export-xlsx');
227
+ const bytes = await mod.exportXlsx(stage.exportInputs, { generated: inputs.today });
228
+ return bytes;
229
+ }
230
+ if (format === 'png') {
231
+ if (!inputs.fonts) {
232
+ throw new TypeError('@nowline/export: inputs.fonts is required for png format.');
233
+ }
234
+ const wasmBytes = await host.loadWasm();
235
+ const pngMod = await import('@nowline/export-png');
236
+ await pngMod.initPngWasm(wasmBytes);
237
+ const bytes = await pngMod.exportPng(stage.exportInputs, stage.svg, {
238
+ scale: inputs.pngScale ?? 2,
239
+ fonts: inputs.fonts,
240
+ });
241
+ return bytes;
242
+ }
243
+ if (format === 'pdf') {
244
+ if (!inputs.fonts) {
245
+ throw new TypeError('@nowline/export: inputs.fonts is required for pdf format.');
246
+ }
247
+ const mod = await import('@nowline/export-pdf');
248
+ const bytes = await mod.exportPdf(stage.exportInputs, stage.svg, {
249
+ pageSize: inputs.pageSize,
250
+ orientation: inputs.orientation,
251
+ marginPt: inputs.marginPt,
252
+ fonts: inputs.fonts,
253
+ });
254
+ return bytes;
255
+ }
256
+ throw new Error(`@nowline/export: unsupported format "${format}".`);
257
+ }
258
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,EAAE;AACF,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,iCAAiC;AACjC,EAAE;AACF,yEAAyE;AACzE,4DAA4D;AAC5D,EAAE;AACF,sEAAsE;AACtE,mEAAmE;AAEnE,OAAO,EACH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/B,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,KAAK,EAAE,MAAM,CAAC,KAAK;SACtB,CAAC,CAAC;QACH,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,MAAgB,IAAI,CAAC,CAAC;AAClF,CAAC"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@nowline/export",
3
+ "version": "0.0.0-dev.20260603150914.g70caedb",
4
+ "description": "Nowline export kernel — the single parse→resolve→layout→renderSvg→format code path shared by every surface for byte-identical export output",
5
+ "license": "Apache-2.0",
6
+ "engines": {
7
+ "node": ">=22",
8
+ "pnpm": ">=11"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist/",
21
+ "src/"
22
+ ],
23
+ "dependencies": {
24
+ "@nowline/core": "0.0.0-dev.20260603150914.g70caedb",
25
+ "@nowline/export-core": "0.0.0-dev.20260603150914.g70caedb",
26
+ "@nowline/export-mermaid": "0.0.0-dev.20260603150914.g70caedb",
27
+ "@nowline/export-html": "0.0.0-dev.20260603150914.g70caedb",
28
+ "@nowline/export-msproj": "0.0.0-dev.20260603150914.g70caedb",
29
+ "@nowline/export-pdf": "0.0.0-dev.20260603150914.g70caedb",
30
+ "@nowline/export-png": "0.0.0-dev.20260603150914.g70caedb",
31
+ "@nowline/export-xlsx": "0.0.0-dev.20260603150914.g70caedb",
32
+ "@nowline/renderer": "0.0.0-dev.20260603150914.g70caedb",
33
+ "@nowline/layout": "0.0.0-dev.20260603150914.g70caedb"
34
+ },
35
+ "peerDependencies": {
36
+ "langium": "~4.2.4"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^25.9.1",
40
+ "langium": "~4.2.4",
41
+ "typescript": "^6.0.3"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -b tsconfig.json",
45
+ "watch": "tsc -b tsconfig.json --watch"
46
+ }
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,409 @@
1
+ // @nowline/export — the shared export kernel.
2
+ //
3
+ // The single code path from `.nowline` source to any of the eight export
4
+ // artifacts (parse → resolve includes → layout → renderSvg → format adapter).
5
+ // Every surface — the CLI, the `@nowline/mcp` server, the VS Code extension,
6
+ // and the Free/Pro web apps — runs this same code with the same inputs, so
7
+ // they all produce byte-for-byte identical output for the same source and the
8
+ // same pinned toolchain version.
9
+ //
10
+ // Spec: specs/export-determinism.md (the byte-identity precedent and the
11
+ // HostEnv / RenderInputs contract this surface implements).
12
+ //
13
+ // Plan: s2 implements the kernel pipeline (parse → resolve → layout →
14
+ // renderSvg → format dispatch). s4 swaps export-png to resvg-wasm.
15
+
16
+ import {
17
+ collectDocumentDiagnostics,
18
+ createNowlineServices,
19
+ type NowlineFile,
20
+ type NowlineServices,
21
+ resolveIncludes,
22
+ } from '@nowline/core';
23
+ import type { ExportInputs, ResolvedFontPair } from '@nowline/export-core';
24
+ import { layoutRoadmap, type ThemeName } from '@nowline/layout';
25
+ import { type AssetResolver, renderSvg } from '@nowline/renderer';
26
+ import type { AstNode, LangiumDocument } from 'langium';
27
+ import { URI } from 'langium';
28
+
29
+ export type { PdfOrientation, ResolvedFontPair } from '@nowline/export-core';
30
+ export type { ThemeName } from '@nowline/layout';
31
+
32
+ /** The eight canonical export formats. Every surface produces exactly these. */
33
+ export type ExportFormat = 'svg' | 'png' | 'pdf' | 'html' | 'mermaid' | 'xlsx' | 'msproj' | 'json';
34
+
35
+ /**
36
+ * The only environment-specific seam in the kernel. The host supplies I/O —
37
+ * reading source/include/asset files and the resvg wasm bytes — and nothing
38
+ * else. Every implementation must return identical bytes for identical inputs;
39
+ * the host contributes I/O only, never a byte of the artifact (see
40
+ * specs/export-determinism.md § Invariant).
41
+ */
42
+ export interface HostEnv {
43
+ /** Read a source / include / asset text file as UTF-8. Drives `include` resolution. */
44
+ readSource(path: string): Promise<string>;
45
+ /** Read a binary asset (logos, icons) referenced by the roadmap. */
46
+ readAsset(path: string): Promise<Uint8Array>;
47
+ /** Return the `resvg.wasm` bytes used by the PNG rasterizer. */
48
+ loadWasm(): Promise<ArrayBuffer>;
49
+ }
50
+
51
+ /**
52
+ * Everything the kernel needs that is neither the source text nor host I/O.
53
+ * `today`, `locale`, `theme`, and `fonts` are explicit inputs — never ambient
54
+ * reads of the system clock, time zone, or `navigator.language` — so the output
55
+ * bytes are a pure function of (source, these inputs, pinned toolchain version).
56
+ */
57
+ export interface RenderInputs {
58
+ /**
59
+ * Absolute path to the `.nowline` source file. Used as the base for
60
+ * resolving relative `include` directives and relative asset references.
61
+ * For in-memory sources with no includes/assets, pass any stable path
62
+ * string (e.g. `'/dev/null/unnamed.nowline'`).
63
+ */
64
+ sourcePath: string;
65
+ /** Now-line date. Always an explicit UTC midnight; never `Date.now()`. Omit to suppress the now-line. */
66
+ today?: Date;
67
+ /** Locale tag used to format timeline tick labels. Explicit; never the host's. */
68
+ locale: string;
69
+ /** Theme (light / dark / grayscale). */
70
+ theme: ThemeName;
71
+ /**
72
+ * Pinned font byte buffers — canonical export embeds the bundled DejaVu
73
+ * pair. Required for formats that rasterize or embed fonts (png, pdf).
74
+ * Optional for text-only formats (svg, html, json, mermaid, msproj, xlsx).
75
+ */
76
+ fonts?: ResolvedFontPair;
77
+
78
+ // ---- layout / render knobs ------------------------------------------
79
+ /** Optional fixed canvas width in px. */
80
+ width?: number;
81
+ /** Drop `<a>` links from the rendered SVG. */
82
+ noLinks?: boolean;
83
+ /** Treat render warnings (e.g. missing assets) as hard errors. */
84
+ strict?: boolean;
85
+
86
+ // ---- format-specific options ----------------------------------------
87
+ /** PDF page size — a preset name or a custom dimensions string. */
88
+ pageSize?: string;
89
+ /** PDF orientation. */
90
+ orientation?: import('@nowline/export-core').PdfOrientation;
91
+ /** PDF margin in points. */
92
+ marginPt?: number;
93
+ /** PNG pixel-density multiplier (default 2). */
94
+ pngScale?: number;
95
+ /** MS Project start-date override (YYYY-MM-DD). */
96
+ msprojStart?: string;
97
+ }
98
+
99
+ // ---- Langium services singleton -----------------------------------------------
100
+ //
101
+ // One dedicated service instance for the export kernel, independent of the
102
+ // browser preview singleton. Mirrors the CLI pattern (packages/cli/src/core/parse.ts).
103
+
104
+ type Services = {
105
+ shared: ReturnType<typeof createNowlineServices>['shared'];
106
+ Nowline: NowlineServices;
107
+ };
108
+
109
+ let cachedServices: Services | undefined;
110
+ let docCounter = 0;
111
+
112
+ function getExportServices(): Services {
113
+ if (!cachedServices) cachedServices = createNowlineServices();
114
+ return cachedServices;
115
+ }
116
+
117
+ function freshUri(): URI {
118
+ // Always mint a fresh URI — re-using one lets Langium mutate the prior
119
+ // document in place, causing spurious diagnostics on repeated exports.
120
+ return URI.parse(`memory:///kernel-${++docCounter}.nowline`);
121
+ }
122
+
123
+ // ---- Inline JSON serializer ---------------------------------------------------
124
+ //
125
+ // Equivalent to packages/cli/src/convert/schema.ts. Inlined here so the kernel
126
+ // has no dependency on @nowline/cli.
127
+
128
+ const JSON_SCHEMA_VERSION = '1';
129
+ const CONTAINER_KEYS = new Set(['$container', '$containerProperty', '$containerIndex']);
130
+ const RUNTIME_KEYS = new Set(['$cstNode', '$document']);
131
+
132
+ function isAstNode(v: unknown): v is AstNode {
133
+ return (
134
+ v !== null && typeof v === 'object' && typeof (v as { $type?: unknown }).$type === 'string'
135
+ );
136
+ }
137
+
138
+ function serializeNode(node: AstNode, includePositions: boolean): Record<string, unknown> {
139
+ const out: Record<string, unknown> = { $type: node.$type };
140
+ if (includePositions && node.$cstNode) {
141
+ const cst = node.$cstNode;
142
+ out.$position = {
143
+ start: {
144
+ line: cst.range.start.line + 1,
145
+ column: cst.range.start.character + 1,
146
+ offset: cst.offset,
147
+ },
148
+ end: {
149
+ line: cst.range.end.line + 1,
150
+ column: cst.range.end.character + 1,
151
+ offset: cst.end,
152
+ },
153
+ };
154
+ }
155
+ for (const [key, value] of Object.entries(node)) {
156
+ if (key.startsWith('$') || CONTAINER_KEYS.has(key) || RUNTIME_KEYS.has(key)) continue;
157
+ out[key] = serializeValue(value, includePositions);
158
+ }
159
+ return out;
160
+ }
161
+
162
+ function serializeValue(value: unknown, includePositions: boolean): unknown {
163
+ if (value === null || value === undefined) return value;
164
+ if (Array.isArray(value)) return value.map((v) => serializeValue(v, includePositions));
165
+ if (isAstNode(value)) return serializeNode(value, includePositions);
166
+ if (typeof value === 'object') {
167
+ const out: Record<string, unknown> = {};
168
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
169
+ if (k.startsWith('$') || CONTAINER_KEYS.has(k) || RUNTIME_KEYS.has(k)) continue;
170
+ out[k] = serializeValue(v, includePositions);
171
+ }
172
+ return out;
173
+ }
174
+ return value;
175
+ }
176
+
177
+ function serializeDocumentToJson(
178
+ document: LangiumDocument<NowlineFile>,
179
+ source: string,
180
+ sourcePath: string,
181
+ ): string {
182
+ const ast = document.parseResult.value;
183
+ return JSON.stringify(
184
+ {
185
+ $nowlineSchema: JSON_SCHEMA_VERSION,
186
+ file: { uri: `file://${sourcePath}`, source },
187
+ ast: serializeNode(ast, true),
188
+ },
189
+ null,
190
+ 2,
191
+ );
192
+ }
193
+
194
+ // ---- MIME inference ----------------------------------------------------------
195
+
196
+ function guessMime(ref: string): string {
197
+ const ext = ref.slice(ref.lastIndexOf('.')).toLowerCase();
198
+ if (ext === '.svg') return 'image/svg+xml';
199
+ if (ext === '.png') return 'image/png';
200
+ if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
201
+ if (ext === '.webp') return 'image/webp';
202
+ return 'application/octet-stream';
203
+ }
204
+
205
+ // ---- Staged pipeline ---------------------------------------------------------
206
+
207
+ interface StageResult {
208
+ svg: string;
209
+ exportInputs: ExportInputs;
210
+ document: LangiumDocument<NowlineFile>;
211
+ source: string;
212
+ }
213
+
214
+ async function stageDocument(
215
+ source: string,
216
+ inputs: RenderInputs,
217
+ host: HostEnv,
218
+ ): Promise<StageResult> {
219
+ const services = getExportServices();
220
+ const uri = freshUri();
221
+
222
+ const doc = services.shared.workspace.LangiumDocumentFactory.fromString<NowlineFile>(
223
+ source,
224
+ uri,
225
+ );
226
+ await services.shared.workspace.DocumentBuilder.build([doc], { validation: true });
227
+
228
+ const errors: string[] = [];
229
+ for (const raw of collectDocumentDiagnostics(doc)) {
230
+ if (raw.origin === 'lexer') {
231
+ errors.push(raw.error.message);
232
+ } else if (raw.origin === 'parser') {
233
+ errors.push(raw.error.message);
234
+ } else if (raw.diagnostic.severity === 1 /* DiagnosticSeverity.Error */) {
235
+ errors.push(raw.diagnostic.message);
236
+ }
237
+ }
238
+ if (errors.length > 0) {
239
+ throw new Error(
240
+ `@nowline/export: validation errors in ${inputs.sourcePath}: ${errors.join('; ')}`,
241
+ );
242
+ }
243
+
244
+ const ast = doc.parseResult.value;
245
+
246
+ const resolved = await resolveIncludes(ast, inputs.sourcePath, {
247
+ services: services.Nowline,
248
+ readFile: host.readSource.bind(host),
249
+ });
250
+ for (const diag of resolved.diagnostics) {
251
+ if (diag.severity === 'error') {
252
+ throw new Error(
253
+ `@nowline/export: include error in ${inputs.sourcePath}: ${diag.message}`,
254
+ );
255
+ }
256
+ }
257
+
258
+ const model = layoutRoadmap(ast, resolved, {
259
+ theme: inputs.theme,
260
+ today: inputs.today,
261
+ width: inputs.width,
262
+ locale: inputs.locale,
263
+ });
264
+
265
+ const assetResolver: AssetResolver = async (ref: string) => {
266
+ const bytes = await host.readAsset(ref);
267
+ return { bytes, mime: guessMime(ref) };
268
+ };
269
+
270
+ const warnings: string[] = [];
271
+ const svg = await renderSvg(model, {
272
+ assetResolver,
273
+ noLinks: inputs.noLinks ?? false,
274
+ strict: inputs.strict ?? false,
275
+ warn: (msg) => warnings.push(msg),
276
+ });
277
+
278
+ if (inputs.strict && warnings.length > 0) {
279
+ throw new Error(`@nowline/export: render warnings (--strict): ${warnings.join('; ')}`);
280
+ }
281
+
282
+ return {
283
+ svg,
284
+ exportInputs: {
285
+ model,
286
+ ast,
287
+ resolved,
288
+ sourcePath: inputs.sourcePath,
289
+ today: inputs.today,
290
+ },
291
+ document: doc,
292
+ source,
293
+ };
294
+ }
295
+
296
+ // ---- Text encoding -----------------------------------------------------------
297
+
298
+ const encoder = new TextEncoder();
299
+
300
+ function toUtf8(text: string): Uint8Array {
301
+ return encoder.encode(text);
302
+ }
303
+
304
+ // ---- Public API --------------------------------------------------------------
305
+
306
+ /**
307
+ * Produce the export artifact for `source` in `format`. This is the single
308
+ * code path to any exported artifact — no surface re-implements a stage.
309
+ *
310
+ * Text formats (svg / json / html / mermaid / msproj) are returned as UTF-8
311
+ * bytes; binary formats (png / pdf / xlsx) as their native bytes. Returning
312
+ * Uint8Array for every format keeps the determinism gate able to `sha256` one
313
+ * value per (fixture, format).
314
+ *
315
+ * Note: PNG rasterizes via @nowline/export-png (native resvg-js) until s4
316
+ * swaps it to @resvg/resvg-wasm. The `host.loadWasm()` seam is reserved for
317
+ * that swap and is not called here yet.
318
+ */
319
+ export async function exportDocument(
320
+ source: string,
321
+ format: ExportFormat,
322
+ inputs: RenderInputs,
323
+ host: HostEnv,
324
+ ): Promise<Uint8Array> {
325
+ if (typeof source !== 'string') {
326
+ throw new TypeError('@nowline/export: source must be a string.');
327
+ }
328
+ if (
329
+ typeof host?.readSource !== 'function' ||
330
+ typeof host.readAsset !== 'function' ||
331
+ typeof host.loadWasm !== 'function'
332
+ ) {
333
+ throw new TypeError('@nowline/export: host must implement the HostEnv interface.');
334
+ }
335
+ if (!(inputs?.today instanceof Date) && inputs?.today !== undefined) {
336
+ throw new TypeError(
337
+ '@nowline/export: inputs.today must be a Date (UTC midnight) or undefined.',
338
+ );
339
+ }
340
+ if (typeof inputs?.sourcePath !== 'string' || inputs.sourcePath.length === 0) {
341
+ throw new TypeError('@nowline/export: inputs.sourcePath must be a non-empty string.');
342
+ }
343
+
344
+ const stage = await stageDocument(source, inputs, host);
345
+
346
+ if (format === 'svg') {
347
+ return toUtf8(stage.svg);
348
+ }
349
+
350
+ if (format === 'json') {
351
+ return toUtf8(serializeDocumentToJson(stage.document, stage.source, inputs.sourcePath));
352
+ }
353
+
354
+ if (format === 'html') {
355
+ const mod = await import('@nowline/export-html');
356
+ const html = await mod.exportHtml(stage.exportInputs, stage.svg);
357
+ return toUtf8(html);
358
+ }
359
+
360
+ if (format === 'mermaid') {
361
+ const mod = await import('@nowline/export-mermaid');
362
+ const md = mod.exportMermaid(stage.exportInputs);
363
+ return toUtf8(md);
364
+ }
365
+
366
+ if (format === 'msproj') {
367
+ const mod = await import('@nowline/export-msproj');
368
+ const xml = mod.exportMsProjXml(stage.exportInputs, {
369
+ startDate: inputs.msprojStart,
370
+ });
371
+ return toUtf8(xml);
372
+ }
373
+
374
+ if (format === 'xlsx') {
375
+ const mod = await import('@nowline/export-xlsx');
376
+ const bytes = await mod.exportXlsx(stage.exportInputs, { generated: inputs.today });
377
+ return bytes;
378
+ }
379
+
380
+ if (format === 'png') {
381
+ if (!inputs.fonts) {
382
+ throw new TypeError('@nowline/export: inputs.fonts is required for png format.');
383
+ }
384
+ const wasmBytes = await host.loadWasm();
385
+ const pngMod = await import('@nowline/export-png');
386
+ await pngMod.initPngWasm(wasmBytes);
387
+ const bytes = await pngMod.exportPng(stage.exportInputs, stage.svg, {
388
+ scale: inputs.pngScale ?? 2,
389
+ fonts: inputs.fonts,
390
+ });
391
+ return bytes;
392
+ }
393
+
394
+ if (format === 'pdf') {
395
+ if (!inputs.fonts) {
396
+ throw new TypeError('@nowline/export: inputs.fonts is required for pdf format.');
397
+ }
398
+ const mod = await import('@nowline/export-pdf');
399
+ const bytes = await mod.exportPdf(stage.exportInputs, stage.svg, {
400
+ pageSize: inputs.pageSize,
401
+ orientation: inputs.orientation,
402
+ marginPt: inputs.marginPt,
403
+ fonts: inputs.fonts,
404
+ });
405
+ return bytes;
406
+ }
407
+
408
+ throw new Error(`@nowline/export: unsupported format "${format as string}".`);
409
+ }