@nova-energy/openamx 0.12.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 +39 -9
- package/dist/cli.js +5 -5
- package/dist/editor/completion.js +104 -2
- package/dist/editor/highlighting.js +27 -1
- package/dist/editor/refactoring.js +4 -1
- package/dist/editor/sourceRanges.js +2 -1
- package/dist/editor/symbols.js +104 -45
- package/dist/formatter/formatAmx.js +83 -7
- package/dist/parser/parseExpression.js +68 -3
- package/dist/parser/parseStatements.js +147 -0
- 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 +6 -0
- package/dist/runtime/evaluateExpression.js +78 -2
- package/dist/runtime/moduleLoader.js +60 -2
- package/dist/runtime/standardLibrary.js +208 -1
- package/dist/runtime/valueSerialization.js +12 -0
- package/dist/typechecker/checkDocument.js +242 -3
- package/package.json +1 -1
|
@@ -2,21 +2,25 @@ import { AlignmentType, Bookmark, BorderStyle, Document, ExternalHyperlink, Head
|
|
|
2
2
|
import { ChartRun } from 'docx/charts';
|
|
3
3
|
import { realpathSync } from 'node:fs';
|
|
4
4
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { formatAmxValue } from '../runtime/valueSerialization';
|
|
5
6
|
import { createChartViewModel } from './chartModel';
|
|
6
7
|
import { fitNarrativeImage } from './narrativeModel';
|
|
8
|
+
import { orderedReportSequence } from './reportSequence';
|
|
9
|
+
import { rasterizeStaticDiagramSvg, renderStaticDiagramSvg } from './staticDiagram';
|
|
7
10
|
const TABLE_WIDTH_TWIPS = 9_026;
|
|
8
11
|
// ChartRun uses 15 twips per CSS pixel; leave one pixel of page-width clearance.
|
|
9
12
|
const DOCX_CHART_WIDTH_PIXELS = Math.floor(TABLE_WIDTH_TWIPS / 15) - 1;
|
|
13
|
+
const DOCX_DIAGRAM_MAX_HEIGHT_PIXELS = 700;
|
|
10
14
|
const IMAGE_WIDTH_PIXELS = 601;
|
|
11
15
|
const IMAGE_HEIGHT_PIXELS = 864;
|
|
12
16
|
const MAX_BOOKMARK_NAME_LENGTH = 40;
|
|
13
|
-
export function prepareDocxReport(report, context) {
|
|
17
|
+
export async function prepareDocxReport(report, context) {
|
|
14
18
|
return preparePreparedDocxReport(report, context);
|
|
15
19
|
}
|
|
16
20
|
export async function serializeDocxReport(report) {
|
|
17
21
|
return Uint8Array.from(await Packer.toBuffer(report.document));
|
|
18
22
|
}
|
|
19
|
-
function preparePreparedDocxReport(report, exportContext) {
|
|
23
|
+
async function preparePreparedDocxReport(report, exportContext) {
|
|
20
24
|
const children = [];
|
|
21
25
|
const identity = report.identity;
|
|
22
26
|
if (identity.logo || identity.organization || identity.author || identity.status || identity.classification) {
|
|
@@ -32,10 +36,16 @@ function preparePreparedDocxReport(report, exportContext) {
|
|
|
32
36
|
const bookmarks = headingBookmarks(report.items.flatMap(item => item.type === 'narrative' ? item.markdown : []), usedBookmarkNames);
|
|
33
37
|
const numbering = [];
|
|
34
38
|
let nextListReference = 0;
|
|
35
|
-
for (const
|
|
39
|
+
for (const entry of orderedReportSequence(report)) {
|
|
40
|
+
if (entry.type === 'diagram') {
|
|
41
|
+
children.push(...await renderDiagram(entry.diagram.model));
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const item = entry.item;
|
|
36
45
|
if (item.type === 'narrative') {
|
|
37
46
|
const context = {
|
|
38
47
|
exportContext,
|
|
48
|
+
imageWidth: identity.imageWidth,
|
|
39
49
|
bookmarks,
|
|
40
50
|
numbering,
|
|
41
51
|
quoteDepth: 0,
|
|
@@ -58,6 +68,22 @@ function preparePreparedDocxReport(report, exportContext) {
|
|
|
58
68
|
})
|
|
59
69
|
};
|
|
60
70
|
}
|
|
71
|
+
async function renderDiagram(model) {
|
|
72
|
+
const rendered = renderStaticDiagramSvg(model);
|
|
73
|
+
const png = await rasterizeStaticDiagramSvg(rendered.svg);
|
|
74
|
+
const transformation = fitNarrativeImage({ width: png.width, height: png.height }, { maxWidth: DOCX_CHART_WIDTH_PIXELS, maxHeight: DOCX_DIAGRAM_MAX_HEIGHT_PIXELS });
|
|
75
|
+
const image = new ImageRun({
|
|
76
|
+
type: 'png',
|
|
77
|
+
data: png.bytes,
|
|
78
|
+
transformation,
|
|
79
|
+
altText: { name: model.name, title: model.title, description: model.description }
|
|
80
|
+
});
|
|
81
|
+
return [
|
|
82
|
+
new Paragraph({ text: model.title, heading: HeadingLevel.HEADING_2, keepNext: true }),
|
|
83
|
+
new Paragraph({ text: model.description, keepNext: true }),
|
|
84
|
+
new Paragraph({ children: [image], alignment: AlignmentType.CENTER, keepLines: true })
|
|
85
|
+
];
|
|
86
|
+
}
|
|
61
87
|
function renderBlocks(blocks, context, nextListReference) {
|
|
62
88
|
return blocks.flatMap(block => renderBlock(block, context, nextListReference));
|
|
63
89
|
}
|
|
@@ -210,8 +236,8 @@ function inlineChildren(inlines, context, style = {}) {
|
|
|
210
236
|
children.push(...inlineChildren(inline.children, context, nestedStyle));
|
|
211
237
|
}
|
|
212
238
|
else if (inline.type === 'link') {
|
|
213
|
-
const linkChildren = inlineChildren(inline.children, context, { ...style, color: '0563C1', underline: {} });
|
|
214
239
|
const link = inline.link;
|
|
240
|
+
const linkChildren = inlineChildren(inline.children, context, link.type === 'amx' ? style : { ...style, color: '0563C1', underline: {} });
|
|
215
241
|
if (link.type === 'external') {
|
|
216
242
|
children.push(new ExternalHyperlink({ link: link.href, children: linkChildren }));
|
|
217
243
|
}
|
|
@@ -222,12 +248,15 @@ function inlineChildren(inlines, context, style = {}) {
|
|
|
222
248
|
else
|
|
223
249
|
children.push(...linkChildren);
|
|
224
250
|
}
|
|
251
|
+
else if (link.type === 'amx') {
|
|
252
|
+
children.push(...linkChildren);
|
|
253
|
+
}
|
|
225
254
|
else {
|
|
226
255
|
children.push(new ExternalHyperlink({ link: localLinkUri(link, context.exportContext), children: linkChildren }));
|
|
227
256
|
}
|
|
228
257
|
}
|
|
229
258
|
else if (inline.type === 'image') {
|
|
230
|
-
children.push(narrativeImageRun(inline.image));
|
|
259
|
+
children.push(narrativeImageRun(inline.image, context.imageWidth));
|
|
231
260
|
}
|
|
232
261
|
}
|
|
233
262
|
return children;
|
|
@@ -248,8 +277,8 @@ function codeChildren(text) {
|
|
|
248
277
|
});
|
|
249
278
|
return runs.length > 0 ? runs : [new TextRun({ text: '', font: 'Consolas', size: 18 })];
|
|
250
279
|
}
|
|
251
|
-
function narrativeImageRun(image) {
|
|
252
|
-
const dimensions = fitNarrativeImage(image, { maxWidth: IMAGE_WIDTH_PIXELS, maxHeight: IMAGE_HEIGHT_PIXELS });
|
|
280
|
+
function narrativeImageRun(image, imageWidth) {
|
|
281
|
+
const dimensions = fitNarrativeImage(image, { maxWidth: IMAGE_WIDTH_PIXELS, maxHeight: IMAGE_HEIGHT_PIXELS }, imageWidth);
|
|
253
282
|
return new ImageRun({
|
|
254
283
|
type: image.format === 'jpeg' ? 'jpg' : 'png',
|
|
255
284
|
data: image.dataUri,
|
|
@@ -344,7 +373,7 @@ function addTable(children, emission) {
|
|
|
344
373
|
children.push(new Paragraph({ text: caption, heading: HeadingLevel.HEADING_2 }));
|
|
345
374
|
const header = new TableRow({ children: columns.map(column => tableCell(column.label, true)) });
|
|
346
375
|
const rows = emission.data.map(value => new TableRow({
|
|
347
|
-
children: columns.map(column => tableCell(isRecord(value) ?
|
|
376
|
+
children: columns.map(column => tableCell(isRecord(value) ? formatAmxValue(value[column.field], '(null)') : ''))
|
|
348
377
|
}));
|
|
349
378
|
children.push(new Table({ rows: [header, ...rows] }));
|
|
350
379
|
}
|
|
@@ -496,7 +525,7 @@ function addChartTable(children, model) {
|
|
|
496
525
|
});
|
|
497
526
|
const rows = model.table.rows.map(row => new TableRow({
|
|
498
527
|
cantSplit: true,
|
|
499
|
-
children: row.values.map(value => tableCell(
|
|
528
|
+
children: row.values.map(value => tableCell(formatAmxValue(value, '(null)')))
|
|
500
529
|
}));
|
|
501
530
|
children.push(new Paragraph({ text: model.table.caption, heading: HeadingLevel.HEADING_3 }));
|
|
502
531
|
const columnCount = Math.max(1, model.table.headings.length);
|
|
@@ -716,10 +745,3 @@ function headingLevel(level) {
|
|
|
716
745
|
function isRecord(value) {
|
|
717
746
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
718
747
|
}
|
|
719
|
-
function valueToString(value) {
|
|
720
|
-
if (value === null || value === undefined)
|
|
721
|
-
return '(null)';
|
|
722
|
-
if (Array.isArray(value))
|
|
723
|
-
return value.map(valueToString).join(', ');
|
|
724
|
-
return String(value);
|
|
725
|
-
}
|
|
@@ -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
|
+
}
|