@nova-energy/openamx 0.11.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -10
- package/dist/cli.js +5 -5
- package/dist/editor/completion.js +199 -6
- package/dist/editor/highlighting.js +63 -4
- package/dist/editor/moduleAnalysis.js +8 -2
- package/dist/editor/refactoring.js +5 -2
- package/dist/editor/sourceRanges.js +3 -1
- package/dist/editor/symbols.js +195 -30
- package/dist/formatter/formatAmx.js +83 -7
- package/dist/parser/parseExpression.js +82 -3
- package/dist/parser/parseIf.js +180 -0
- package/dist/parser/parseStatements.js +232 -7
- package/dist/renderer/diagramBrowserEntry.js +255 -0
- package/dist/renderer/diagramBrowserRuntime.js +2 -0
- package/dist/renderer/diagramHtml.js +47 -0
- package/dist/renderer/narrativeModel.js +36 -11
- package/dist/renderer/renderHtml.js +95 -41
- package/dist/renderer/reportDocx.js +38 -16
- package/dist/renderer/reportPdf.js +122 -35
- package/dist/renderer/reportPreparation.js +97 -23
- package/dist/renderer/reportSequence.js +29 -0
- package/dist/renderer/staticDiagram.js +94 -0
- package/dist/runtime/diagramModel.js +455 -0
- package/dist/runtime/environment.js +8 -0
- package/dist/runtime/evaluateExpression.js +194 -10
- package/dist/runtime/inputData.js +20 -18
- package/dist/runtime/moduleLoader.js +76 -4
- package/dist/runtime/outputData.js +18 -12
- package/dist/runtime/standardLibrary.js +208 -1
- package/dist/runtime/valueSerialization.js +12 -0
- package/dist/typechecker/checkDocument.js +496 -16
- package/package.json +1 -1
|
@@ -4,8 +4,11 @@ import { existsSync, realpathSync } from 'node:fs';
|
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { formatAmxValue } from '../runtime/valueSerialization';
|
|
7
8
|
import { createChartViewModel } from './chartModel';
|
|
8
9
|
import { fitNarrativeImage } from './narrativeModel';
|
|
10
|
+
import { orderedReportSequence } from './reportSequence';
|
|
11
|
+
import { renderStaticDiagramSvg } from './staticDiagram';
|
|
9
12
|
const packagedFontRoot = fileURLToPath(new URL('./pdfmake-fonts/', import.meta.url));
|
|
10
13
|
const fontRoot = existsSync(resolve(packagedFontRoot, 'Roboto-Regular.ttf'))
|
|
11
14
|
? packagedFontRoot
|
|
@@ -49,9 +52,24 @@ function preparePreparedPdfReport(report, renderChart, context) {
|
|
|
49
52
|
margin: [0, 0, 0, 16]
|
|
50
53
|
});
|
|
51
54
|
}
|
|
52
|
-
for (const
|
|
55
|
+
for (const entry of orderedReportSequence(report)) {
|
|
56
|
+
if (entry.type === 'diagram') {
|
|
57
|
+
const model = entry.diagram.model;
|
|
58
|
+
const rendered = renderStaticDiagramSvg(model);
|
|
59
|
+
const dimensions = fitNarrativeImage({ width: rendered.width, height: rendered.height }, { maxWidth: 493, maxHeight: 650 });
|
|
60
|
+
content.push({
|
|
61
|
+
stack: [
|
|
62
|
+
{ text: model.title, style: 'heading' },
|
|
63
|
+
{ text: model.description, style: 'caption' },
|
|
64
|
+
{ svg: rendered.svg, width: dimensions.width }
|
|
65
|
+
],
|
|
66
|
+
unbreakable: true
|
|
67
|
+
});
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const item = entry.item;
|
|
53
71
|
if (item.type === 'narrative')
|
|
54
|
-
addNarrativeBlocks(content, item.markdown, context);
|
|
72
|
+
addNarrativeBlocks(content, item.markdown, context, identity.imageWidth);
|
|
55
73
|
else if (item.type === 'source')
|
|
56
74
|
content.push({ text: item.text, style: 'source' });
|
|
57
75
|
else
|
|
@@ -77,18 +95,17 @@ function preparePreparedPdfReport(report, renderChart, context) {
|
|
|
77
95
|
}
|
|
78
96
|
};
|
|
79
97
|
}
|
|
80
|
-
function addNarrativeBlocks(content, blocks, context) {
|
|
98
|
+
function addNarrativeBlocks(content, blocks, context, imageWidth) {
|
|
81
99
|
for (const block of blocks) {
|
|
82
100
|
if (block.type === 'heading') {
|
|
83
|
-
content.
|
|
84
|
-
text: inlineRuns(block.children, context),
|
|
101
|
+
addInlineContent(content, block.children, context, imageWidth, {
|
|
85
102
|
style: block.depth === 1 ? 'title' : 'heading',
|
|
86
103
|
...(block.depth > 1 ? { fontSize: Math.max(9, 16 - block.depth) } : {}),
|
|
87
104
|
id: block.id
|
|
88
105
|
});
|
|
89
106
|
}
|
|
90
107
|
else if (block.type === 'paragraph') {
|
|
91
|
-
content
|
|
108
|
+
addInlineContent(content, block.children, context, imageWidth, { margin: [0, 0, 0, 7] });
|
|
92
109
|
}
|
|
93
110
|
else if (block.type === 'code') {
|
|
94
111
|
content.push({ text: block.text, style: 'code', preserveLeadingSpaces: true });
|
|
@@ -96,14 +113,18 @@ function addNarrativeBlocks(content, blocks, context) {
|
|
|
96
113
|
else if (block.type === 'list') {
|
|
97
114
|
const items = block.items.map(item => {
|
|
98
115
|
const children = [];
|
|
99
|
-
addNarrativeBlocks(children, item.blocks, context);
|
|
116
|
+
addNarrativeBlocks(children, item.blocks, context, imageWidth);
|
|
100
117
|
if (item.checked !== undefined && children.length > 0) {
|
|
101
118
|
const first = children[0];
|
|
119
|
+
const marker = item.checked ? '[x] ' : '[ ] ';
|
|
102
120
|
if (isPlainRecord(first) && Array.isArray(first.text)) {
|
|
103
|
-
first.text = [{ text:
|
|
121
|
+
first.text = [{ text: marker }, ...first.text];
|
|
104
122
|
}
|
|
105
123
|
else if (isPlainRecord(first) && typeof first.text === 'string') {
|
|
106
|
-
first.text = `${
|
|
124
|
+
first.text = `${marker}${first.text}`;
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
children.unshift({ text: marker });
|
|
107
128
|
}
|
|
108
129
|
}
|
|
109
130
|
return children.length === 1 ? children[0] : children;
|
|
@@ -114,15 +135,26 @@ function addNarrativeBlocks(content, blocks, context) {
|
|
|
114
135
|
}
|
|
115
136
|
else if (block.type === 'blockquote') {
|
|
116
137
|
const quoted = [];
|
|
117
|
-
addNarrativeBlocks(quoted, block.blocks, context);
|
|
138
|
+
addNarrativeBlocks(quoted, block.blocks, context, imageWidth);
|
|
118
139
|
content.push({ stack: quoted, style: 'blockquote' });
|
|
119
140
|
}
|
|
120
141
|
else if (block.type === 'table') {
|
|
121
|
-
const cell = (children, header, alignment) =>
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
142
|
+
const cell = (children, header, alignment) => {
|
|
143
|
+
const segments = splitInlineImages(children, context);
|
|
144
|
+
const common = {
|
|
145
|
+
...(header ? { bold: true, fillColor: '#e7eee8' } : {}),
|
|
146
|
+
...(alignment ? { alignment } : {})
|
|
147
|
+
};
|
|
148
|
+
if (!segments.some(segment => segment.type === 'image')) {
|
|
149
|
+
return { text: inlineRuns(children, context), ...common };
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
stack: segments.map(segment => segment.type === 'image'
|
|
153
|
+
? imageRun(segment.image, segment.style, { maxWidth: 150, maxHeight: 150 }, imageWidth)
|
|
154
|
+
: { text: inlineRuns(segment.inlines, context) }),
|
|
155
|
+
...common
|
|
156
|
+
};
|
|
157
|
+
};
|
|
126
158
|
content.push({
|
|
127
159
|
table: {
|
|
128
160
|
headerRows: 1,
|
|
@@ -169,22 +201,84 @@ function inlineRuns(inlines, context, style = {}) {
|
|
|
169
201
|
runs.push(...inlineRuns(inline.children, context, nestedStyle));
|
|
170
202
|
}
|
|
171
203
|
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
|
-
};
|
|
204
|
+
const linkStyle = pdfLinkStyle(inline.link, context, style);
|
|
178
205
|
runs.push(...inlineRuns(inline.children, context, linkStyle));
|
|
179
206
|
}
|
|
180
|
-
else if (inline.type === 'image') {
|
|
181
|
-
runs.push(imageRun(inline.image, style));
|
|
182
|
-
}
|
|
183
207
|
}
|
|
184
208
|
return runs;
|
|
185
209
|
}
|
|
186
|
-
function
|
|
187
|
-
const
|
|
210
|
+
function splitInlineImages(inlines, context, imageStyle = {}) {
|
|
211
|
+
const segments = [];
|
|
212
|
+
let pending = [];
|
|
213
|
+
const flushText = () => {
|
|
214
|
+
if (pending.length > 0)
|
|
215
|
+
segments.push({ type: 'text', inlines: pending });
|
|
216
|
+
pending = [];
|
|
217
|
+
};
|
|
218
|
+
for (const inline of inlines) {
|
|
219
|
+
if (inline.type === 'image') {
|
|
220
|
+
flushText();
|
|
221
|
+
segments.push({ type: 'image', image: inline.image, style: imageStyle });
|
|
222
|
+
}
|
|
223
|
+
else if (inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete' || inline.type === 'link') {
|
|
224
|
+
const childImageStyle = inline.type === 'link'
|
|
225
|
+
? pdfLinkStyle(inline.link, context, imageStyle)
|
|
226
|
+
: imageStyle;
|
|
227
|
+
for (const child of splitInlineImages(inline.children, context, childImageStyle)) {
|
|
228
|
+
if (child.type === 'image') {
|
|
229
|
+
flushText();
|
|
230
|
+
segments.push(child);
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
pending.push({ ...inline, children: child.inlines });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
pending.push(inline);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
flushText();
|
|
242
|
+
return segments;
|
|
243
|
+
}
|
|
244
|
+
function addInlineContent(content, inlines, context, imageWidth, options) {
|
|
245
|
+
const segments = splitInlineImages(inlines, context);
|
|
246
|
+
if (segments.length === 0) {
|
|
247
|
+
content.push({ text: inlineRuns(inlines, context), ...options });
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
let first = true;
|
|
251
|
+
for (const segment of segments) {
|
|
252
|
+
if (segment.type === 'image') {
|
|
253
|
+
const node = imageRun(segment.image, segment.style, undefined, imageWidth);
|
|
254
|
+
if (options.id !== undefined && first)
|
|
255
|
+
node.id = options.id;
|
|
256
|
+
if (options.margin !== undefined)
|
|
257
|
+
node.margin = options.margin;
|
|
258
|
+
content.push(node);
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
const textOptions = { ...options };
|
|
262
|
+
if (!first)
|
|
263
|
+
delete textOptions.id;
|
|
264
|
+
content.push({ text: inlineRuns(segment.inlines, context), ...textOptions });
|
|
265
|
+
}
|
|
266
|
+
first = false;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function pdfLinkStyle(link, context, style) {
|
|
270
|
+
return {
|
|
271
|
+
...style,
|
|
272
|
+
...(link.type === 'external' ? { link: link.href } : {}),
|
|
273
|
+
...(link.type === 'internal' ? { linkToDestination: link.targetId } : {}),
|
|
274
|
+
...(link.type === 'local' ? { link: localLinkUri(link, context) } : {})
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
function imageRun(image, style, maximum = { maxWidth: 493, maxHeight: 739 }, imageWidth) {
|
|
278
|
+
const pdfWidth = imageWidth?.unit === 'px'
|
|
279
|
+
? { value: imageWidth.value * 0.75, unit: 'px' }
|
|
280
|
+
: imageWidth;
|
|
281
|
+
const dimensions = fitNarrativeImage(image, maximum, pdfWidth);
|
|
188
282
|
return {
|
|
189
283
|
image: image.dataUri,
|
|
190
284
|
width: dimensions.width,
|
|
@@ -222,7 +316,7 @@ function addTable(content, emission) {
|
|
|
222
316
|
const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
|
|
223
317
|
const body = [
|
|
224
318
|
columns.map(column => ({ text: column.label, bold: true, fillColor: '#e7eee8' })),
|
|
225
|
-
...emission.data.map(value => columns.map(column =>
|
|
319
|
+
...emission.data.map(value => columns.map(column => formatAmxValue(isRecord(value) ? value[column.field] : null)))
|
|
226
320
|
];
|
|
227
321
|
content.push({ text: caption, style: 'heading' });
|
|
228
322
|
content.push({ table: { headerRows: 1, keepWithHeaderRows: 1, widths: columns.map(() => '*'), body }, layout: 'lightHorizontalLines', fontSize: 8 });
|
|
@@ -243,7 +337,7 @@ function addChart(content, emission, identity, renderChart) {
|
|
|
243
337
|
widths: model.table.headings.map(() => '*'),
|
|
244
338
|
body: [
|
|
245
339
|
model.table.headings.map(text => ({ text, bold: true, fillColor: '#e7eee8' })),
|
|
246
|
-
...model.table.rows.map(row => row.values.map(
|
|
340
|
+
...model.table.rows.map(row => row.values.map(value => formatAmxValue(value)))
|
|
247
341
|
]
|
|
248
342
|
},
|
|
249
343
|
layout: 'lightHorizontalLines',
|
|
@@ -305,10 +399,3 @@ function assertSupportedSvg(svg) {
|
|
|
305
399
|
function isRecord(value) {
|
|
306
400
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
307
401
|
}
|
|
308
|
-
function valueToString(value) {
|
|
309
|
-
if (value === null || value === undefined)
|
|
310
|
-
return '';
|
|
311
|
-
if (Array.isArray(value))
|
|
312
|
-
return value.map(valueToString).join(', ');
|
|
313
|
-
return String(value);
|
|
314
|
-
}
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { existsSync, lstatSync, readFileSync } from 'node:fs';
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
2
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
|
-
import {
|
|
9
|
-
import { prepareNarratives } from './narrativeModel';
|
|
8
|
+
import { formatAmxValue } from '../runtime/valueSerialization';
|
|
9
|
+
import { parseNarrativeImageWidth, prepareNarratives } from './narrativeModel';
|
|
10
10
|
import { canonicalDirectory, hasSymlink, isContained } from './reportPaths';
|
|
11
|
-
const REPORT_FIELDS = new Set(['organization', 'logo', 'logoAlt', 'accent', 'author', 'status', 'classification', 'footer', 'sourceVisible']);
|
|
12
|
-
const TEXT_LIMITS = { organization: 120, logoAlt: 120, author: 120, status: 80, classification: 80, footer: 300 };
|
|
11
|
+
const REPORT_FIELDS = new Set(['organization', 'logo', 'logoAlt', 'stylesheet', 'accent', 'author', 'status', 'classification', 'footer', 'sourceVisible', 'imageWidth']);
|
|
12
|
+
const TEXT_LIMITS = { organization: 120, logoAlt: 120, stylesheet: 240, author: 120, status: 80, classification: 80, footer: 300, imageWidth: 16 };
|
|
13
|
+
const STYLESHEET_BYTE_LIMIT = 256 * 1024;
|
|
13
14
|
export async function prepareReport(doc, env, options = {}) {
|
|
14
15
|
const projectReport = readProjectReport(options.projectRoot);
|
|
15
16
|
const frontMatter = asRecord((doc.metadata ?? {}).report, 'Invalid report frontmatter', options.file);
|
|
@@ -24,7 +25,7 @@ export async function prepareReport(doc, env, options = {}) {
|
|
|
24
25
|
projectRoot: options.projectRoot,
|
|
25
26
|
interpolate: (expression, line) => {
|
|
26
27
|
const value = evaluateExpression(parseExpression(expression, line === undefined ? undefined : { line, column: 1 }), env, options.file);
|
|
27
|
-
return
|
|
28
|
+
return formatAmxValue(value);
|
|
28
29
|
}
|
|
29
30
|
});
|
|
30
31
|
const emissionsByNode = new Map();
|
|
@@ -33,7 +34,23 @@ export async function prepareReport(doc, env, options = {}) {
|
|
|
33
34
|
emissions.push(emission);
|
|
34
35
|
emissionsByNode.set(emission.documentNodeIndex, emissions);
|
|
35
36
|
}
|
|
37
|
+
const diagramsByNode = new Map();
|
|
38
|
+
const importedDiagrams = [];
|
|
39
|
+
const entryPath = options.file ? canonicalFilePath(options.file) : undefined;
|
|
40
|
+
for (const emission of env.diagramEmissions) {
|
|
41
|
+
const model = emission.model;
|
|
42
|
+
if (entryPath && model.file && canonicalFilePath(model.file) !== entryPath) {
|
|
43
|
+
importedDiagrams.push(model);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const diagrams = diagramsByNode.get(model.documentNodeIndex) ?? [];
|
|
47
|
+
diagrams.push(model);
|
|
48
|
+
diagramsByNode.set(model.documentNodeIndex, diagrams);
|
|
49
|
+
}
|
|
50
|
+
const firstExecutableNode = doc.nodes.findIndex(node => node.type === 'executableCodeBlock');
|
|
36
51
|
const items = [];
|
|
52
|
+
const diagrams = [];
|
|
53
|
+
let diagramOrder = 0;
|
|
37
54
|
let narrativeIndex = 0;
|
|
38
55
|
for (const [index, node] of doc.nodes.entries()) {
|
|
39
56
|
if (node.type === 'narrative') {
|
|
@@ -52,12 +69,34 @@ export async function prepareReport(doc, env, options = {}) {
|
|
|
52
69
|
continue;
|
|
53
70
|
if (identity.sourceVisible)
|
|
54
71
|
items.push(Object.freeze({ type: 'source', text: formatAmx(node.content) }));
|
|
55
|
-
|
|
56
|
-
|
|
72
|
+
if (index === firstExecutableNode) {
|
|
73
|
+
for (const model of importedDiagrams) {
|
|
74
|
+
diagrams.push(Object.freeze({ model, beforeItemIndex: items.length, order: diagramOrder++ }));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const blockEmissions = [
|
|
78
|
+
...(emissionsByNode.get(index) ?? []).map(emission => ({ type: 'view', emission, statementIndex: emission.statementIndex })),
|
|
79
|
+
...(diagramsByNode.get(index) ?? []).map(model => ({ type: 'diagram', model, statementIndex: model.statementIndex }))
|
|
80
|
+
].sort((left, right) => left.statementIndex - right.statementIndex);
|
|
81
|
+
for (const emission of blockEmissions) {
|
|
82
|
+
if (emission.type === 'view')
|
|
83
|
+
items.push(Object.freeze({ type: 'view', emission: emission.emission }));
|
|
84
|
+
else
|
|
85
|
+
diagrams.push(Object.freeze({ model: emission.model, beforeItemIndex: items.length, order: diagramOrder++ }));
|
|
86
|
+
}
|
|
57
87
|
}
|
|
58
88
|
const metadata = doc.metadata ?? {};
|
|
59
89
|
const title = typeof metadata.title === 'string' && metadata.title.trim() ? metadata.title.trim() : 'OpenAMX Document';
|
|
60
|
-
return Object.freeze({
|
|
90
|
+
return Object.freeze({
|
|
91
|
+
title,
|
|
92
|
+
identity,
|
|
93
|
+
items: Object.freeze(items),
|
|
94
|
+
...(diagrams.length ? { diagrams: Object.freeze(diagrams) } : {})
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
function canonicalFilePath(file) {
|
|
98
|
+
const path = existsSync(file) ? realpathSync(file) : resolve(file);
|
|
99
|
+
return process.platform === 'win32' ? path.toLocaleLowerCase('en-US') : path;
|
|
61
100
|
}
|
|
62
101
|
function readProjectReport(projectRoot) {
|
|
63
102
|
if (!projectRoot)
|
|
@@ -85,11 +124,12 @@ function readProjectReport(projectRoot) {
|
|
|
85
124
|
}
|
|
86
125
|
export function validateReportSettings(report, projectRoot, file) {
|
|
87
126
|
validateReport(report, file ?? '.openamx/project.json', file);
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
127
|
+
const validations = [];
|
|
128
|
+
if (typeof report.logo === 'string')
|
|
129
|
+
validations.push(prepareLogo(report.logo, String(report.logoAlt ?? ''), projectRoot, file));
|
|
130
|
+
if (typeof report.stylesheet === 'string')
|
|
131
|
+
validations.push(Promise.resolve(readReportStylesheet(report.stylesheet, projectRoot, file)));
|
|
132
|
+
return Promise.all(validations).then(() => undefined);
|
|
93
133
|
}
|
|
94
134
|
function validateReport(report, location, file) {
|
|
95
135
|
for (const [key, value] of Object.entries(report)) {
|
|
@@ -107,6 +147,12 @@ function validateReport(report, location, file) {
|
|
|
107
147
|
fail('AMX6001', `Report ${key} contains invalid text`, file ?? location);
|
|
108
148
|
if (TEXT_LIMITS[key] !== undefined && [...text].length > TEXT_LIMITS[key])
|
|
109
149
|
fail('AMX6001', `Report ${key} exceeds its length limit`, file ?? location);
|
|
150
|
+
if (key === 'imageWidth' && !parseNarrativeImageWidth(text)) {
|
|
151
|
+
fail('AMX6001', 'Report imageWidth must be a positive pixel width up to 4096px or a percentage from 1% to 100%', file ?? location);
|
|
152
|
+
}
|
|
153
|
+
if (key === 'stylesheet' && !isValidStylesheetPath(text)) {
|
|
154
|
+
fail('AMX6001', 'Report stylesheet must be a project-relative .css path', file ?? location);
|
|
155
|
+
}
|
|
110
156
|
}
|
|
111
157
|
if (report.logoAlt !== undefined && report.logo === undefined)
|
|
112
158
|
fail('AMX6001', 'Report logoAlt requires a logo', file ?? location);
|
|
@@ -119,17 +165,54 @@ async function resolveIdentity(projectReport, frontMatter, options) {
|
|
|
119
165
|
const merged = { ...projectReport, ...frontMatter };
|
|
120
166
|
const logoPath = typeof merged.logo === 'string' ? merged.logo.trim() : undefined;
|
|
121
167
|
const logo = logoPath ? await prepareLogo(logoPath, String(merged.logoAlt ?? ''), options.projectRoot, options.file) : undefined;
|
|
168
|
+
const stylesheetPath = typeof merged.stylesheet === 'string' ? merged.stylesheet.trim() : undefined;
|
|
169
|
+
const stylesheetCss = stylesheetPath && options.includeStylesheet !== false
|
|
170
|
+
? readReportStylesheet(stylesheetPath, options.projectRoot, options.file, options.stylesheetOverlay)
|
|
171
|
+
: undefined;
|
|
122
172
|
return Object.freeze({
|
|
123
173
|
organization: text(merged.organization),
|
|
124
174
|
logo,
|
|
175
|
+
stylesheetCss,
|
|
125
176
|
accent: effectiveReportAccent(text(merged.accent) ?? '#146C94'),
|
|
126
177
|
author: text(merged.author),
|
|
127
178
|
status: text(merged.status),
|
|
128
179
|
classification: text(merged.classification),
|
|
129
180
|
footer: text(merged.footer),
|
|
181
|
+
imageWidth: typeof merged.imageWidth === 'string' ? parseNarrativeImageWidth(merged.imageWidth) : undefined,
|
|
130
182
|
sourceVisible: merged.sourceVisible === undefined ? true : merged.sourceVisible
|
|
131
183
|
});
|
|
132
184
|
}
|
|
185
|
+
export function readReportStylesheet(path, projectRoot, file, overlay) {
|
|
186
|
+
if (!projectRoot)
|
|
187
|
+
fail('AMX6001', 'A report stylesheet requires an explicit project root', file);
|
|
188
|
+
if (!isValidStylesheetPath(path))
|
|
189
|
+
fail('AMX6001', 'Report stylesheet must be a project-relative .css path', file);
|
|
190
|
+
const root = canonicalDirectory(projectRoot);
|
|
191
|
+
const candidate = resolve(root, path);
|
|
192
|
+
if (!isContained(root, candidate) || hasSymlink(root, candidate) || !existsSync(candidate) || !lstatSync(candidate).isFile()) {
|
|
193
|
+
fail('AMX6001', 'Report stylesheet must be a contained regular file', file);
|
|
194
|
+
}
|
|
195
|
+
const overlayText = overlay?.get(candidate);
|
|
196
|
+
const bytes = overlayText === undefined ? readFileSync(candidate) : Buffer.from(overlayText, 'utf8');
|
|
197
|
+
if (bytes.byteLength > STYLESHEET_BYTE_LIMIT)
|
|
198
|
+
fail('AMX6001', 'Report stylesheet exceeds 256 KiB', file);
|
|
199
|
+
try {
|
|
200
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
fail('AMX6001', 'Report stylesheet must be valid UTF-8', file);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function isValidStylesheetPath(path) {
|
|
207
|
+
return path.length > 0
|
|
208
|
+
&& path.length <= 240
|
|
209
|
+
&& path.endsWith('.css')
|
|
210
|
+
&& !path.startsWith('/')
|
|
211
|
+
&& !path.includes('\\')
|
|
212
|
+
&& !path.includes(':')
|
|
213
|
+
&& !/[\u0000-\u001f\u007f]/u.test(path)
|
|
214
|
+
&& path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..' && !segment.startsWith('.'));
|
|
215
|
+
}
|
|
133
216
|
async function prepareLogo(path, alt, projectRoot, file) {
|
|
134
217
|
if (!projectRoot)
|
|
135
218
|
fail('AMX6001', 'A report logo requires an explicit project root', file);
|
|
@@ -163,15 +246,6 @@ async function prepareLogo(path, alt, projectRoot, file) {
|
|
|
163
246
|
fail('AMX6001', 'Report logo is not a supported image', file);
|
|
164
247
|
}
|
|
165
248
|
}
|
|
166
|
-
function valueToString(value) {
|
|
167
|
-
if (value === null || value === undefined)
|
|
168
|
-
return '';
|
|
169
|
-
if (Array.isArray(value))
|
|
170
|
-
return value.map(valueToString).join(', ');
|
|
171
|
-
if (isMeasurement(value))
|
|
172
|
-
return `${String(value.value)} ${value.unit.text}`;
|
|
173
|
-
return String(value);
|
|
174
|
-
}
|
|
175
249
|
function asRecord(value, message, file) {
|
|
176
250
|
if (value === undefined)
|
|
177
251
|
return {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export function orderedReportSequence(report) {
|
|
2
|
+
const diagramsByPosition = new Map();
|
|
3
|
+
const seenOrders = new Set();
|
|
4
|
+
for (const diagram of report.diagrams ?? []) {
|
|
5
|
+
if (!Number.isInteger(diagram.beforeItemIndex)
|
|
6
|
+
|| diagram.beforeItemIndex < 0
|
|
7
|
+
|| diagram.beforeItemIndex > report.items.length) {
|
|
8
|
+
throw new Error(`Prepared diagram has invalid insertion position ${diagram.beforeItemIndex}.`);
|
|
9
|
+
}
|
|
10
|
+
if (!Number.isInteger(diagram.order) || diagram.order < 0 || seenOrders.has(diagram.order)) {
|
|
11
|
+
throw new Error(`Prepared diagram has invalid or duplicate order ${diagram.order}.`);
|
|
12
|
+
}
|
|
13
|
+
seenOrders.add(diagram.order);
|
|
14
|
+
const diagrams = diagramsByPosition.get(diagram.beforeItemIndex) ?? [];
|
|
15
|
+
diagrams.push(diagram);
|
|
16
|
+
diagramsByPosition.set(diagram.beforeItemIndex, diagrams);
|
|
17
|
+
}
|
|
18
|
+
const sequence = [];
|
|
19
|
+
for (let itemIndex = 0; itemIndex <= report.items.length; itemIndex++) {
|
|
20
|
+
const diagrams = diagramsByPosition.get(itemIndex) ?? [];
|
|
21
|
+
diagrams.sort((left, right) => left.order - right.order);
|
|
22
|
+
for (const diagram of diagrams)
|
|
23
|
+
sequence.push({ type: 'diagram', diagram });
|
|
24
|
+
const item = report.items[itemIndex];
|
|
25
|
+
if (item)
|
|
26
|
+
sequence.push({ type: 'item', item });
|
|
27
|
+
}
|
|
28
|
+
return sequence;
|
|
29
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import sharp from 'sharp';
|
|
3
|
+
import { evaluateDiagramFrame } from '../runtime/diagramModel';
|
|
4
|
+
const MAX_SVG_EDGE = 1200;
|
|
5
|
+
export function renderStaticDiagramSvg(model) {
|
|
6
|
+
const { width: canvasWidth, height: canvasHeight } = model.canvas;
|
|
7
|
+
if (!Number.isFinite(canvasWidth) || canvasWidth <= 0 || !Number.isFinite(canvasHeight) || canvasHeight <= 0) {
|
|
8
|
+
throw new Error(`Diagram '${model.name}' has invalid canvas dimensions.`);
|
|
9
|
+
}
|
|
10
|
+
const frame = evaluateDiagramFrame(model, model.timeline.from);
|
|
11
|
+
const scale = Math.min(MAX_SVG_EDGE / canvasWidth, MAX_SVG_EDGE / canvasHeight);
|
|
12
|
+
const width = canvasWidth * scale;
|
|
13
|
+
const height = canvasHeight * scale;
|
|
14
|
+
if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
|
|
15
|
+
throw new Error(`Diagram '${model.name}' cannot be represented with finite SVG dimensions.`);
|
|
16
|
+
}
|
|
17
|
+
const title = escapeXml(model.title);
|
|
18
|
+
const description = escapeXml(model.description);
|
|
19
|
+
const content = frame.elements.map(element => renderElement(element)).join('');
|
|
20
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${formatNumber(width)}" height="${formatNumber(height)}" viewBox="0 0 ${formatNumber(canvasWidth)} ${formatNumber(canvasHeight)}" preserveAspectRatio="xMidYMid meet" role="img" aria-labelledby="diagram-title diagram-description"><title id="diagram-title">${title}</title><desc id="diagram-description">${description}</desc><g transform="translate(0 ${formatNumber(canvasHeight)}) scale(1 -1)">${content}</g></svg>`;
|
|
21
|
+
return Object.freeze({ svg, width, height });
|
|
22
|
+
}
|
|
23
|
+
export async function rasterizeStaticDiagramSvg(svg) {
|
|
24
|
+
const { data, info } = await sharp(Buffer.from(svg, 'utf8')).png().toBuffer({ resolveWithObject: true });
|
|
25
|
+
if (info.width <= 0 || info.height <= 0)
|
|
26
|
+
throw new Error('Rasterized diagram has invalid pixel dimensions.');
|
|
27
|
+
return Object.freeze({ bytes: Uint8Array.from(data), width: info.width, height: info.height });
|
|
28
|
+
}
|
|
29
|
+
function renderElement(element) {
|
|
30
|
+
const stroke = escapeXml(element.primitive === 'text' ? 'none' : element.stroke);
|
|
31
|
+
const fill = escapeXml(element.primitive === 'text'
|
|
32
|
+
? element.fill
|
|
33
|
+
: element.primitive === 'line' ? 'none' : element.fill ?? 'none');
|
|
34
|
+
const lineWidth = element.primitive === 'text' ? 0 : element.lineWidth;
|
|
35
|
+
switch (element.primitive) {
|
|
36
|
+
case 'line': {
|
|
37
|
+
const line = `<line x1="${formatNumber(element.x1)}" y1="${formatNumber(element.y1)}" x2="${formatNumber(element.x2)}" y2="${formatNumber(element.y2)}" stroke="${stroke}" stroke-width="${formatNumber(lineWidth)}" fill="none"/>`;
|
|
38
|
+
return `${line}${renderArrow(element, 'start')}${renderArrow(element, 'end')}`;
|
|
39
|
+
}
|
|
40
|
+
case 'rectangle':
|
|
41
|
+
return `<rect x="${formatNumber(element.x)}" y="${formatNumber(element.y)}" width="${formatNumber(element.width)}" height="${formatNumber(element.height)}" stroke="${stroke}" stroke-width="${formatNumber(lineWidth)}" fill="${fill}"/>`;
|
|
42
|
+
case 'circle':
|
|
43
|
+
return `<circle cx="${formatNumber(element.cx)}" cy="${formatNumber(element.cy)}" r="${formatNumber(element.r)}" stroke="${stroke}" stroke-width="${formatNumber(lineWidth)}" fill="${fill}"/>`;
|
|
44
|
+
case 'text':
|
|
45
|
+
return `<text x="${formatNumber(element.x)}" y="${formatNumber(element.y)}" transform="translate(0 ${formatNumber(element.y * 2)}) scale(1 -1)" fill="${fill}">${escapeXml(element.value)}</text>`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function renderArrow(element, end) {
|
|
49
|
+
if (element.arrow !== end && element.arrow !== 'both')
|
|
50
|
+
return '';
|
|
51
|
+
const tipX = end === 'start' ? element.x1 : element.x2;
|
|
52
|
+
const tipY = end === 'start' ? element.y1 : element.y2;
|
|
53
|
+
const tailX = end === 'start' ? element.x2 : element.x1;
|
|
54
|
+
const tailY = end === 'start' ? element.y2 : element.y1;
|
|
55
|
+
const dx = tipX - tailX;
|
|
56
|
+
const dy = tipY - tailY;
|
|
57
|
+
const length = Math.hypot(dx, dy);
|
|
58
|
+
if (length === 0)
|
|
59
|
+
return '';
|
|
60
|
+
const size = Math.max(4, element.lineWidth * 4);
|
|
61
|
+
const ux = dx / length;
|
|
62
|
+
const uy = dy / length;
|
|
63
|
+
const baseX = tipX - ux * size;
|
|
64
|
+
const baseY = tipY - uy * size;
|
|
65
|
+
const halfWidth = size * 0.45;
|
|
66
|
+
const leftX = baseX - uy * halfWidth;
|
|
67
|
+
const leftY = baseY + ux * halfWidth;
|
|
68
|
+
const rightX = baseX + uy * halfWidth;
|
|
69
|
+
const rightY = baseY - ux * halfWidth;
|
|
70
|
+
return `<polygon points="${formatNumber(tipX)},${formatNumber(tipY)} ${formatNumber(leftX)},${formatNumber(leftY)} ${formatNumber(rightX)},${formatNumber(rightY)}" fill="${escapeXml(element.stroke)}"/>`;
|
|
71
|
+
}
|
|
72
|
+
function formatNumber(value) {
|
|
73
|
+
if (!Number.isFinite(value))
|
|
74
|
+
throw new Error('Static diagram contains non-finite geometry.');
|
|
75
|
+
return Object.is(value, -0) ? '0' : String(value);
|
|
76
|
+
}
|
|
77
|
+
function escapeXml(value) {
|
|
78
|
+
for (const character of value) {
|
|
79
|
+
const codePoint = character.codePointAt(0);
|
|
80
|
+
if (!(codePoint === 0x9 || codePoint === 0xA || codePoint === 0xD
|
|
81
|
+
|| (codePoint >= 0x20 && codePoint <= 0xD7FF)
|
|
82
|
+
|| (codePoint >= 0xE000 && codePoint <= 0xFFFD)
|
|
83
|
+
|| (codePoint >= 0x10000 && codePoint <= 0x10FFFF))) {
|
|
84
|
+
throw new Error('Diagram text contains a character that cannot be represented in SVG/XML.');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return value.replace(/[&<>"']/g, character => ({
|
|
88
|
+
'&': '&',
|
|
89
|
+
'<': '<',
|
|
90
|
+
'>': '>',
|
|
91
|
+
'"': '"',
|
|
92
|
+
"'": '''
|
|
93
|
+
})[character]);
|
|
94
|
+
}
|