@nova-energy/openamx 0.10.1 → 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.
@@ -0,0 +1,31 @@
1
+ import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs';
2
+ import { relative, resolve, sep } from 'node:path';
3
+ import { AmxError } from '../diagnostics/errors';
4
+ export function canonicalDirectory(path, message = 'Project root must be an existing directory') {
5
+ try {
6
+ const canonical = realpathSync(path);
7
+ if (!statSync(canonical).isDirectory()) {
8
+ throw new AmxError({ code: 'AMX6001', message, file: path });
9
+ }
10
+ return canonical;
11
+ }
12
+ catch (error) {
13
+ if (error instanceof AmxError)
14
+ throw error;
15
+ throw new AmxError({ code: 'AMX6001', message, file: path });
16
+ }
17
+ }
18
+ export function isContained(root, candidate) {
19
+ const relation = relative(root, candidate);
20
+ return relation !== '..' && !relation.startsWith(`..${sep}`) && relation !== '';
21
+ }
22
+ export function hasSymlink(root, candidate) {
23
+ const relation = relative(root, candidate);
24
+ let current = root;
25
+ for (const segment of relation.split(sep)) {
26
+ current = resolve(current, segment);
27
+ if (existsSync(current) && lstatSync(current).isSymbolicLink())
28
+ return true;
29
+ }
30
+ return false;
31
+ }
@@ -1,10 +1,11 @@
1
1
  import * as echarts from 'echarts';
2
2
  import pdfmake from 'pdfmake';
3
- import { existsSync } from 'node:fs';
3
+ import { existsSync, realpathSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
- import { dirname, resolve } from 'node:path';
5
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { createChartViewModel } from './chartModel';
8
+ import { fitNarrativeImage } from './narrativeModel';
8
9
  const packagedFontRoot = fileURLToPath(new URL('./pdfmake-fonts/', import.meta.url));
9
10
  const fontRoot = existsSync(resolve(packagedFontRoot, 'Roboto-Regular.ttf'))
10
11
  ? packagedFontRoot
@@ -19,15 +20,17 @@ pdfmake.setFonts({
19
20
  bolditalics: resolve(fontRoot, 'Roboto-MediumItalic.ttf')
20
21
  }
21
22
  });
22
- export function preparePdfReport(report, renderChart = renderStaticChart) {
23
- return preparePreparedPdfReport(report, renderChart);
23
+ export function preparePdfReport(report, renderChartOrContext = renderStaticChart, context) {
24
+ const renderChart = typeof renderChartOrContext === 'function' ? renderChartOrContext : renderStaticChart;
25
+ const exportContext = typeof renderChartOrContext === 'function' ? context : renderChartOrContext;
26
+ return preparePreparedPdfReport(report, renderChart, exportContext);
24
27
  }
25
28
  export async function serializePdfReport(report) {
26
29
  const pdf = pdfmake.createPdf(report.definition);
27
30
  const buffer = await pdf.getBuffer();
28
31
  return Uint8Array.from(buffer);
29
32
  }
30
- function preparePreparedPdfReport(report, renderChart) {
33
+ function preparePreparedPdfReport(report, renderChart, context) {
31
34
  const content = [];
32
35
  const identity = report.identity;
33
36
  const metadata = [
@@ -48,7 +51,7 @@ function preparePreparedPdfReport(report, renderChart) {
48
51
  }
49
52
  for (const item of report.items) {
50
53
  if (item.type === 'narrative')
51
- addNarrativeText(content, item.text);
54
+ addNarrativeBlocks(content, item.markdown, context);
52
55
  else if (item.type === 'source')
53
56
  content.push({ text: item.text, style: 'source' });
54
57
  else
@@ -66,37 +69,146 @@ function preparePreparedPdfReport(report, renderChart) {
66
69
  heading: { fontSize: 14, bold: true, color: identity.accent, margin: [0, 14, 0, 6] },
67
70
  source: { font: 'Roboto', fontSize: 8, color: '#405459', margin: [0, 5, 0, 10] },
68
71
  caption: { fontSize: 8, color: '#405459', margin: [0, 3, 0, 6] },
72
+ code: { font: 'Roboto', fontSize: 8, background: '#f1f4f5', margin: [0, 3, 0, 8] },
73
+ blockquote: { color: '#405459', margin: [12, 2, 0, 8] },
69
74
  metadata: { fontSize: 9, color: '#18282D', margin: [0, 0, 0, 2] }
70
75
  },
71
76
  content
72
77
  }
73
78
  };
74
79
  }
75
- function addNarrativeText(content, narrative) {
76
- const lines = narrative.split(/\r?\n/);
77
- let paragraph = [];
78
- const flush = () => {
79
- if (paragraph.length > 0)
80
- content.push({ text: paragraph.join(' '), margin: [0, 0, 0, 7] });
81
- paragraph = [];
82
- };
83
- for (const line of lines) {
84
- if (line.trim() === '<!-- page-break -->') {
85
- flush();
86
- content.push({ text: '', pageBreak: 'before' });
80
+ function addNarrativeBlocks(content, blocks, context) {
81
+ for (const block of blocks) {
82
+ if (block.type === 'heading') {
83
+ content.push({
84
+ text: inlineRuns(block.children, context),
85
+ style: block.depth === 1 ? 'title' : 'heading',
86
+ ...(block.depth > 1 ? { fontSize: Math.max(9, 16 - block.depth) } : {}),
87
+ id: block.id
88
+ });
89
+ }
90
+ else if (block.type === 'paragraph') {
91
+ content.push({ text: inlineRuns(block.children, context), margin: [0, 0, 0, 7] });
92
+ }
93
+ else if (block.type === 'code') {
94
+ content.push({ text: block.text, style: 'code', preserveLeadingSpaces: true });
95
+ }
96
+ else if (block.type === 'list') {
97
+ const items = block.items.map(item => {
98
+ const children = [];
99
+ addNarrativeBlocks(children, item.blocks, context);
100
+ if (item.checked !== undefined && children.length > 0) {
101
+ const first = children[0];
102
+ if (isPlainRecord(first) && Array.isArray(first.text)) {
103
+ first.text = [{ text: item.checked ? '[x] ' : '[ ] ' }, ...first.text];
104
+ }
105
+ else if (isPlainRecord(first) && typeof first.text === 'string') {
106
+ first.text = `${item.checked ? '[x] ' : '[ ] '}${first.text}`;
107
+ }
108
+ }
109
+ return children.length === 1 ? children[0] : children;
110
+ });
111
+ content.push(block.ordered
112
+ ? { ol: items, ...(block.start === undefined ? {} : { start: block.start }), margin: [0, 0, 0, 7] }
113
+ : { ul: items, margin: [0, 0, 0, 7] });
114
+ }
115
+ else if (block.type === 'blockquote') {
116
+ const quoted = [];
117
+ addNarrativeBlocks(quoted, block.blocks, context);
118
+ content.push({ stack: quoted, style: 'blockquote' });
87
119
  }
88
- else if (/^#{1,6}\s+/.test(line)) {
89
- flush();
90
- content.push({ text: line.replace(/^#{1,6}\s+/, ''), style: line.startsWith('# ') ? 'title' : 'heading' });
120
+ else if (block.type === 'table') {
121
+ const cell = (children, header, alignment) => ({
122
+ text: inlineRuns(children, context),
123
+ ...(header ? { bold: true, fillColor: '#e7eee8' } : {}),
124
+ ...(alignment ? { alignment } : {})
125
+ });
126
+ content.push({
127
+ table: {
128
+ headerRows: 1,
129
+ keepWithHeaderRows: 1,
130
+ widths: block.header.map(() => '*'),
131
+ body: [
132
+ block.header.map((children, index) => cell(children, true, block.align[index])),
133
+ ...block.rows.map(row => row.map((children, index) => cell(children, false, block.align[index])))
134
+ ]
135
+ },
136
+ layout: 'lightHorizontalLines',
137
+ fontSize: 8
138
+ });
91
139
  }
92
- else if (line.trim() === '') {
93
- flush();
140
+ else if (block.type === 'horizontalRule') {
141
+ content.push({
142
+ canvas: [{ type: 'line', x1: 0, y1: 2, x2: 493, y2: 2, lineWidth: 0.5, lineColor: '#9AA8AC' }],
143
+ margin: [0, 6, 0, 6]
144
+ });
94
145
  }
95
146
  else {
96
- paragraph.push(line.trim());
147
+ content.push({ text: '', pageBreak: 'before' });
97
148
  }
98
149
  }
99
- flush();
150
+ }
151
+ function inlineRuns(inlines, context, style = {}) {
152
+ const runs = [];
153
+ for (const inline of inlines) {
154
+ if (inline.type === 'text') {
155
+ runs.push({ text: inline.text, ...style });
156
+ }
157
+ else if (inline.type === 'lineBreak') {
158
+ runs.push({ text: '\n', ...style });
159
+ }
160
+ else if (inline.type === 'inlineCode') {
161
+ runs.push({ text: inline.text, font: 'Roboto', background: '#f1f4f5', ...style });
162
+ }
163
+ else if (inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete') {
164
+ const nestedStyle = inline.type === 'strong'
165
+ ? { ...style, bold: true }
166
+ : inline.type === 'emphasis'
167
+ ? { ...style, italics: true }
168
+ : { ...style, decoration: 'lineThrough' };
169
+ runs.push(...inlineRuns(inline.children, context, nestedStyle));
170
+ }
171
+ else if (inline.type === 'link') {
172
+ const linkStyle = {
173
+ ...style,
174
+ ...(inline.link.type === 'external' ? { link: inline.link.href } : {}),
175
+ ...(inline.link.type === 'internal' ? { linkToDestination: inline.link.targetId } : {}),
176
+ ...(inline.link.type === 'local' ? { link: localLinkUri(inline.link, context) } : {})
177
+ };
178
+ runs.push(...inlineRuns(inline.children, context, linkStyle));
179
+ }
180
+ else if (inline.type === 'image') {
181
+ runs.push(imageRun(inline.image, style));
182
+ }
183
+ }
184
+ return runs;
185
+ }
186
+ function imageRun(image, style) {
187
+ const dimensions = fitNarrativeImage(image, { maxWidth: 493, maxHeight: 739 });
188
+ return {
189
+ image: image.dataUri,
190
+ width: dimensions.width,
191
+ height: dimensions.height,
192
+ alt: image.alt,
193
+ ...style
194
+ };
195
+ }
196
+ function localLinkUri(link, context) {
197
+ if (!context)
198
+ throw new Error('PDF local links require validated source-document and final-destination context.');
199
+ if (link.sourceBase !== 'document-directory')
200
+ throw new Error('PDF local link has an unsupported source base.');
201
+ const sourceDirectory = realpathSync(dirname(resolve(context.sourceDocumentPath)));
202
+ const outputDirectory = dirname(resolve(context.destinationPath));
203
+ const sourceTarget = resolve(sourceDirectory, ...link.path.split('/'));
204
+ const relativePath = relative(outputDirectory, sourceTarget);
205
+ if (!relativePath || isAbsolute(relativePath))
206
+ throw new Error('PDF local link target cannot be represented relative to the final PDF destination.');
207
+ const encodedPath = relativePath.split(sep).map(segment => encodeURIComponent(segment)).join('/');
208
+ return `${encodedPath}${link.query === undefined ? '' : `?${link.query}`}${link.fragment === undefined ? '' : `#${link.fragment}`}`;
209
+ }
210
+ function isPlainRecord(value) {
211
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
100
212
  }
101
213
  function addEmission(content, emission, identity, renderChart) {
102
214
  if (emission.kind === 'table')
@@ -1,11 +1,13 @@
1
- import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
- import { relative, resolve, sep } from 'node:path';
1
+ import { existsSync, lstatSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
3
  import sharp from 'sharp';
4
4
  import { AmxError } from '../diagnostics/errors';
5
5
  import { formatAmx } from '../formatter/formatAmx';
6
6
  import { parseExpression } from '../parser/parseExpression';
7
7
  import { evaluateExpression } from '../runtime/evaluateExpression';
8
8
  import { isMeasurement } from '../runtime/measurement';
9
+ import { prepareNarratives } from './narrativeModel';
10
+ import { canonicalDirectory, hasSymlink, isContained } from './reportPaths';
9
11
  const REPORT_FIELDS = new Set(['organization', 'logo', 'logoAlt', 'accent', 'author', 'status', 'classification', 'footer', 'sourceVisible']);
10
12
  const TEXT_LIMITS = { organization: 120, logoAlt: 120, author: 120, status: 80, classification: 80, footer: 300 };
11
13
  export async function prepareReport(doc, env, options = {}) {
@@ -14,6 +16,17 @@ export async function prepareReport(doc, env, options = {}) {
14
16
  validateReport(projectReport, '.openamx/project.json', options.projectRoot);
15
17
  validateReport(frontMatter, 'frontmatter', options.file);
16
18
  const identity = await resolveIdentity(projectReport, frontMatter, options);
19
+ const narrativeSources = doc.nodes.flatMap(node => node.type === 'narrative'
20
+ ? [{ content: node.content, line: node.source?.line }]
21
+ : []);
22
+ const narratives = await prepareNarratives(narrativeSources, {
23
+ file: options.file,
24
+ projectRoot: options.projectRoot,
25
+ interpolate: (expression, line) => {
26
+ const value = evaluateExpression(parseExpression(expression, line === undefined ? undefined : { line, column: 1 }), env, options.file);
27
+ return valueToString(value);
28
+ }
29
+ });
17
30
  const emissionsByNode = new Map();
18
31
  for (const emission of env.viewEmissions) {
19
32
  const emissions = emissionsByNode.get(emission.documentNodeIndex) ?? [];
@@ -21,9 +34,18 @@ export async function prepareReport(doc, env, options = {}) {
21
34
  emissionsByNode.set(emission.documentNodeIndex, emissions);
22
35
  }
23
36
  const items = [];
37
+ let narrativeIndex = 0;
24
38
  for (const [index, node] of doc.nodes.entries()) {
25
39
  if (node.type === 'narrative') {
26
- items.push(Object.freeze({ type: 'narrative', text: substituteInlines(node.content, env, options.file, node.source?.line) }));
40
+ const narrative = narratives[narrativeIndex++];
41
+ if (!narrative)
42
+ throw new Error('Prepared narrative order does not match the source document');
43
+ items.push(Object.freeze({
44
+ type: 'narrative',
45
+ text: narrative.text,
46
+ markdown: narrative.blocks,
47
+ diagnostics: narrative.diagnostics
48
+ }));
27
49
  continue;
28
50
  }
29
51
  if (node.type !== 'executableCodeBlock')
@@ -141,13 +163,6 @@ async function prepareLogo(path, alt, projectRoot, file) {
141
163
  fail('AMX6001', 'Report logo is not a supported image', file);
142
164
  }
143
165
  }
144
- function substituteInlines(content, env, file, line) {
145
- return content.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_full, expression) => {
146
- if (!expression.trim())
147
- return '';
148
- return valueToString(evaluateExpression(parseExpression(expression.trim(), line === undefined ? undefined : { line, column: 1 }), env, file));
149
- });
150
- }
151
166
  function valueToString(value) {
152
167
  if (value === null || value === undefined)
153
168
  return '';
@@ -176,33 +191,6 @@ export function effectiveReportAccent(accent) {
176
191
  .reduce((total, value, index) => total + value * [0.2126, 0.7152, 0.0722][index], 0);
177
192
  return (1.05 / (luminance + 0.05)) >= 4.5 ? accent : '#146C94';
178
193
  }
179
- function canonicalDirectory(path) {
180
- try {
181
- const canonical = realpathSync(path);
182
- if (!statSync(canonical).isDirectory())
183
- fail('AMX6001', 'Project root must be an existing directory', path);
184
- return canonical;
185
- }
186
- catch (error) {
187
- if (error instanceof AmxError)
188
- throw error;
189
- fail('AMX6001', 'Project root must be an existing directory', path);
190
- }
191
- }
192
- function isContained(root, candidate) {
193
- const relation = relative(root, candidate);
194
- return relation !== '..' && !relation.startsWith(`..${sep}`) && relation !== '';
195
- }
196
- function hasSymlink(root, candidate) {
197
- const relation = relative(root, candidate);
198
- let current = root;
199
- for (const segment of relation.split(sep)) {
200
- current = resolve(current, segment);
201
- if (existsSync(current) && lstatSync(current).isSymbolicLink())
202
- return true;
203
- }
204
- return false;
205
- }
206
194
  function fail(code, message, file) {
207
195
  throw new AmxError({ code, message, file });
208
196
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nova-energy/openamx",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "OpenAMX is an open-source, text-based, computable document format for engineering knowledge.",
5
5
  "type": "module",
6
6
  "bin": {