@nova-energy/openamx 0.0.0-stage → 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.
- package/COMMERCIAL-LICENSE.md +74 -0
- package/LICENSE.md +660 -0
- package/README.md +537 -3
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +197 -0
- package/dist/diagnostics/errors.js +94 -0
- package/dist/editor/completion.js +313 -0
- package/dist/editor/highlighting.js +224 -0
- package/dist/editor/moduleAnalysis.js +206 -0
- package/dist/editor/refactoring.js +46 -0
- package/dist/editor/sourceRanges.js +50 -0
- package/dist/editor/symbols.js +203 -0
- package/dist/formatter/formatAmx.js +79 -0
- package/dist/index.js +10 -0
- package/dist/parser/parseDocument.js +114 -0
- package/dist/parser/parseExpression.js +768 -0
- package/dist/parser/parseFor.js +53 -0
- package/dist/parser/parseFrontMatter.js +65 -0
- package/dist/parser/parseStatements.js +667 -0
- package/dist/parser/stringScanner.js +71 -0
- package/dist/renderer/chartModel.js +476 -0
- package/dist/renderer/narrativeModel.js +561 -0
- package/dist/renderer/renderHtml.js +521 -0
- package/dist/renderer/reportDocx.js +725 -0
- package/dist/renderer/reportPaths.js +31 -0
- package/dist/renderer/reportPdf.js +314 -0
- package/dist/renderer/reportPreparation.js +196 -0
- package/dist/runtime/csvTextSerialization.js +8 -0
- package/dist/runtime/dataText.js +191 -0
- package/dist/runtime/docxDestination.js +55 -0
- package/dist/runtime/environment.js +105 -0
- package/dist/runtime/evaluateDocument.js +32 -0
- package/dist/runtime/evaluateExpression.js +888 -0
- package/dist/runtime/externalUnits.js +91 -0
- package/dist/runtime/inputData.js +508 -0
- package/dist/runtime/measurement.js +110 -0
- package/dist/runtime/moduleLoader.js +279 -0
- package/dist/runtime/outputData.js +303 -0
- package/dist/runtime/pdfDestination.js +57 -0
- package/dist/runtime/standardLibrary.js +145 -0
- package/dist/typechecker/checkDocument.js +1282 -0
- package/dist/typechecker/declarationRegistry.js +7 -0
- package/dist/typechecker/dimensionTypes.js +1 -0
- package/package.json +33 -4
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import * as echarts from 'echarts';
|
|
2
|
+
import pdfmake from 'pdfmake';
|
|
3
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { createChartViewModel } from './chartModel';
|
|
8
|
+
import { fitNarrativeImage } from './narrativeModel';
|
|
9
|
+
const packagedFontRoot = fileURLToPath(new URL('./pdfmake-fonts/', import.meta.url));
|
|
10
|
+
const fontRoot = existsSync(resolve(packagedFontRoot, 'Roboto-Regular.ttf'))
|
|
11
|
+
? packagedFontRoot
|
|
12
|
+
: resolve(dirname(createRequire(import.meta.url).resolve('pdfmake')), '../fonts/Roboto');
|
|
13
|
+
pdfmake.setUrlAccessPolicy(() => false);
|
|
14
|
+
pdfmake.setLocalAccessPolicy((filePath) => filePath.startsWith(fontRoot));
|
|
15
|
+
pdfmake.setFonts({
|
|
16
|
+
Roboto: {
|
|
17
|
+
normal: resolve(fontRoot, 'Roboto-Regular.ttf'),
|
|
18
|
+
bold: resolve(fontRoot, 'Roboto-Medium.ttf'),
|
|
19
|
+
italics: resolve(fontRoot, 'Roboto-Italic.ttf'),
|
|
20
|
+
bolditalics: resolve(fontRoot, 'Roboto-MediumItalic.ttf')
|
|
21
|
+
}
|
|
22
|
+
});
|
|
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);
|
|
27
|
+
}
|
|
28
|
+
export async function serializePdfReport(report) {
|
|
29
|
+
const pdf = pdfmake.createPdf(report.definition);
|
|
30
|
+
const buffer = await pdf.getBuffer();
|
|
31
|
+
return Uint8Array.from(buffer);
|
|
32
|
+
}
|
|
33
|
+
function preparePreparedPdfReport(report, renderChart, context) {
|
|
34
|
+
const content = [];
|
|
35
|
+
const identity = report.identity;
|
|
36
|
+
const metadata = [
|
|
37
|
+
identity.organization,
|
|
38
|
+
identity.author && `Author: ${identity.author}`,
|
|
39
|
+
identity.status && `Status: ${identity.status}`,
|
|
40
|
+
identity.classification && `Classification: ${identity.classification}`
|
|
41
|
+
].filter((value) => Boolean(value));
|
|
42
|
+
if (identity.logo || metadata.length > 0) {
|
|
43
|
+
content.push({
|
|
44
|
+
columns: [
|
|
45
|
+
identity.logo ? { image: identity.logo.dataUri, fit: [120, 48], alt: identity.logo.alt } : {},
|
|
46
|
+
{ stack: metadata.map(text => ({ text, style: 'metadata' })) }
|
|
47
|
+
],
|
|
48
|
+
columnGap: 12,
|
|
49
|
+
margin: [0, 0, 0, 16]
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
for (const item of report.items) {
|
|
53
|
+
if (item.type === 'narrative')
|
|
54
|
+
addNarrativeBlocks(content, item.markdown, context);
|
|
55
|
+
else if (item.type === 'source')
|
|
56
|
+
content.push({ text: item.text, style: 'source' });
|
|
57
|
+
else
|
|
58
|
+
addEmission(content, item.emission, identity, renderChart);
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
definition: {
|
|
62
|
+
info: { title: report.title, author: identity.author ?? 'OpenAMX' },
|
|
63
|
+
pageSize: 'A4',
|
|
64
|
+
pageMargins: [51, 51, 51, 51],
|
|
65
|
+
defaultStyle: { font: 'Roboto', fontSize: 9, color: '#18282D' },
|
|
66
|
+
footer: (currentPage, pageCount) => ({ text: [identity.footer, `${currentPage} / ${pageCount}`].filter(Boolean).join(' | '), alignment: 'right', margin: [0, 0, 51, 24], fontSize: 8 }),
|
|
67
|
+
styles: {
|
|
68
|
+
title: { fontSize: 20, bold: true, color: identity.accent, margin: [0, 0, 0, 10] },
|
|
69
|
+
heading: { fontSize: 14, bold: true, color: identity.accent, margin: [0, 14, 0, 6] },
|
|
70
|
+
source: { font: 'Roboto', fontSize: 8, color: '#405459', margin: [0, 5, 0, 10] },
|
|
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] },
|
|
74
|
+
metadata: { fontSize: 9, color: '#18282D', margin: [0, 0, 0, 2] }
|
|
75
|
+
},
|
|
76
|
+
content
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
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' });
|
|
119
|
+
}
|
|
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
|
+
});
|
|
139
|
+
}
|
|
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
|
+
});
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
content.push({ text: '', pageBreak: 'before' });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
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);
|
|
212
|
+
}
|
|
213
|
+
function addEmission(content, emission, identity, renderChart) {
|
|
214
|
+
if (emission.kind === 'table')
|
|
215
|
+
addTable(content, emission);
|
|
216
|
+
else
|
|
217
|
+
addChart(content, emission, identity, renderChart);
|
|
218
|
+
}
|
|
219
|
+
function addTable(content, emission) {
|
|
220
|
+
const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
|
|
221
|
+
const columns = emission.declaration.options.filter(option => option.type === 'tableColumnOption');
|
|
222
|
+
const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
|
|
223
|
+
const body = [
|
|
224
|
+
columns.map(column => ({ text: column.label, bold: true, fillColor: '#e7eee8' })),
|
|
225
|
+
...emission.data.map(value => columns.map(column => valueToString(isRecord(value) ? value[column.field] : null)))
|
|
226
|
+
];
|
|
227
|
+
content.push({ text: caption, style: 'heading' });
|
|
228
|
+
content.push({ table: { headerRows: 1, keepWithHeaderRows: 1, widths: columns.map(() => '*'), body }, layout: 'lightHorizontalLines', fontSize: 8 });
|
|
229
|
+
}
|
|
230
|
+
function addChart(content, emission, identity, renderChart) {
|
|
231
|
+
const model = createChartViewModel(emission, identity);
|
|
232
|
+
content.push({
|
|
233
|
+
stack: [
|
|
234
|
+
{ text: model.title, style: 'heading' },
|
|
235
|
+
{ text: model.description, style: 'caption' },
|
|
236
|
+
{ svg: renderChart(model), width: 470 }
|
|
237
|
+
],
|
|
238
|
+
unbreakable: true
|
|
239
|
+
});
|
|
240
|
+
content.push({
|
|
241
|
+
table: {
|
|
242
|
+
headerRows: 1,
|
|
243
|
+
widths: model.table.headings.map(() => '*'),
|
|
244
|
+
body: [
|
|
245
|
+
model.table.headings.map(text => ({ text, bold: true, fillColor: '#e7eee8' })),
|
|
246
|
+
...model.table.rows.map(row => row.values.map(valueToString))
|
|
247
|
+
]
|
|
248
|
+
},
|
|
249
|
+
layout: 'lightHorizontalLines',
|
|
250
|
+
fontSize: 8
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function renderStaticChart(model) {
|
|
254
|
+
const chart = echarts.init(null, undefined, {
|
|
255
|
+
renderer: 'svg',
|
|
256
|
+
ssr: true,
|
|
257
|
+
width: model.dimensions.width,
|
|
258
|
+
height: model.dimensions.height
|
|
259
|
+
});
|
|
260
|
+
try {
|
|
261
|
+
const tooltip = model.option.tooltip;
|
|
262
|
+
chart.setOption({
|
|
263
|
+
...model.option,
|
|
264
|
+
animation: false,
|
|
265
|
+
title: { ...model.option.title, show: false },
|
|
266
|
+
xAxis: centerNamedAxis(model.option.xAxis, model.emptyState !== undefined),
|
|
267
|
+
yAxis: centerNamedAxis(model.option.yAxis, model.emptyState !== undefined),
|
|
268
|
+
tooltip: Array.isArray(tooltip)
|
|
269
|
+
? tooltip.map(item => ({ ...item, show: false }))
|
|
270
|
+
: { ...tooltip, show: false }
|
|
271
|
+
});
|
|
272
|
+
const svg = chart.renderToSVGString();
|
|
273
|
+
assertSupportedSvg(svg);
|
|
274
|
+
return svg;
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
chart.dispose();
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function centerNamedAxis(axis, hide) {
|
|
281
|
+
const adjust = (item) => {
|
|
282
|
+
if (item === null || typeof item !== 'object')
|
|
283
|
+
return item;
|
|
284
|
+
const named = 'name' in item && typeof item.name === 'string'
|
|
285
|
+
? { ...item, nameLocation: 'middle' }
|
|
286
|
+
: { ...item };
|
|
287
|
+
if (!hide)
|
|
288
|
+
return named;
|
|
289
|
+
return {
|
|
290
|
+
...named,
|
|
291
|
+
show: false,
|
|
292
|
+
axisLine: { ...('axisLine' in named && named.axisLine && typeof named.axisLine === 'object' ? named.axisLine : {}), show: false }
|
|
293
|
+
};
|
|
294
|
+
};
|
|
295
|
+
return Array.isArray(axis) ? axis.map(adjust) : adjust(axis);
|
|
296
|
+
}
|
|
297
|
+
function assertSupportedSvg(svg) {
|
|
298
|
+
const supportedElements = new Set(['svg', 'g', 'path', 'rect', 'circle', 'text', 'defs', 'clipPath', 'style']);
|
|
299
|
+
const elements = [...svg.matchAll(/<([A-Za-z][A-Za-z0-9:-]*)\b/g)].map(match => match[1]);
|
|
300
|
+
const unsupported = [...new Set(elements.filter(element => !supportedElements.has(element)))];
|
|
301
|
+
if (!svg.startsWith('<svg') || unsupported.length > 0) {
|
|
302
|
+
throw new Error(`ECharts PDF SVG uses unsupported output${unsupported.length ? `: ${unsupported.join(', ')}` : ''}`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function isRecord(value) {
|
|
306
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
307
|
+
}
|
|
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
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import sharp from 'sharp';
|
|
4
|
+
import { AmxError } from '../diagnostics/errors';
|
|
5
|
+
import { formatAmx } from '../formatter/formatAmx';
|
|
6
|
+
import { parseExpression } from '../parser/parseExpression';
|
|
7
|
+
import { evaluateExpression } from '../runtime/evaluateExpression';
|
|
8
|
+
import { isMeasurement } from '../runtime/measurement';
|
|
9
|
+
import { prepareNarratives } from './narrativeModel';
|
|
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 };
|
|
13
|
+
export async function prepareReport(doc, env, options = {}) {
|
|
14
|
+
const projectReport = readProjectReport(options.projectRoot);
|
|
15
|
+
const frontMatter = asRecord((doc.metadata ?? {}).report, 'Invalid report frontmatter', options.file);
|
|
16
|
+
validateReport(projectReport, '.openamx/project.json', options.projectRoot);
|
|
17
|
+
validateReport(frontMatter, 'frontmatter', options.file);
|
|
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
|
+
});
|
|
30
|
+
const emissionsByNode = new Map();
|
|
31
|
+
for (const emission of env.viewEmissions) {
|
|
32
|
+
const emissions = emissionsByNode.get(emission.documentNodeIndex) ?? [];
|
|
33
|
+
emissions.push(emission);
|
|
34
|
+
emissionsByNode.set(emission.documentNodeIndex, emissions);
|
|
35
|
+
}
|
|
36
|
+
const items = [];
|
|
37
|
+
let narrativeIndex = 0;
|
|
38
|
+
for (const [index, node] of doc.nodes.entries()) {
|
|
39
|
+
if (node.type === 'narrative') {
|
|
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
|
+
}));
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (node.type !== 'executableCodeBlock')
|
|
52
|
+
continue;
|
|
53
|
+
if (identity.sourceVisible)
|
|
54
|
+
items.push(Object.freeze({ type: 'source', text: formatAmx(node.content) }));
|
|
55
|
+
for (const emission of emissionsByNode.get(index) ?? [])
|
|
56
|
+
items.push(Object.freeze({ type: 'view', emission }));
|
|
57
|
+
}
|
|
58
|
+
const metadata = doc.metadata ?? {};
|
|
59
|
+
const title = typeof metadata.title === 'string' && metadata.title.trim() ? metadata.title.trim() : 'OpenAMX Document';
|
|
60
|
+
return Object.freeze({ title, identity, items: Object.freeze(items) });
|
|
61
|
+
}
|
|
62
|
+
function readProjectReport(projectRoot) {
|
|
63
|
+
if (!projectRoot)
|
|
64
|
+
return {};
|
|
65
|
+
const root = canonicalDirectory(projectRoot);
|
|
66
|
+
const configPath = resolve(root, '.openamx', 'project.json');
|
|
67
|
+
if (!existsSync(configPath))
|
|
68
|
+
return {};
|
|
69
|
+
let config;
|
|
70
|
+
try {
|
|
71
|
+
config = asRecord(JSON.parse(readFileSync(configPath, 'utf8')), 'Invalid project configuration', configPath);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error instanceof AmxError)
|
|
75
|
+
throw error;
|
|
76
|
+
fail('AMX6001', 'Invalid project configuration', configPath);
|
|
77
|
+
}
|
|
78
|
+
for (const key of Object.keys(config)) {
|
|
79
|
+
if (!['version', 'inputs', 'report'].includes(key))
|
|
80
|
+
fail('AMX6001', `Unknown project configuration key '${key}'`, configPath);
|
|
81
|
+
}
|
|
82
|
+
if (config.version !== 1 || !asPlainRecord(config.inputs))
|
|
83
|
+
fail('AMX6001', 'Project configuration requires version 1 and an inputs mapping', configPath);
|
|
84
|
+
return config.report === undefined ? {} : asRecord(config.report, 'Project report must be an object', configPath);
|
|
85
|
+
}
|
|
86
|
+
export function validateReportSettings(report, projectRoot, file) {
|
|
87
|
+
validateReport(report, file ?? '.openamx/project.json', file);
|
|
88
|
+
if (report.logo === undefined)
|
|
89
|
+
return Promise.resolve();
|
|
90
|
+
if (typeof report.logo !== 'string')
|
|
91
|
+
return Promise.resolve();
|
|
92
|
+
return prepareLogo(report.logo, String(report.logoAlt ?? ''), projectRoot, file).then(() => undefined);
|
|
93
|
+
}
|
|
94
|
+
function validateReport(report, location, file) {
|
|
95
|
+
for (const [key, value] of Object.entries(report)) {
|
|
96
|
+
if (!REPORT_FIELDS.has(key))
|
|
97
|
+
fail('AMX6001', `Unknown report field '${key}'`, file ?? location);
|
|
98
|
+
if (key === 'sourceVisible') {
|
|
99
|
+
if (typeof value !== 'boolean')
|
|
100
|
+
fail('AMX6001', 'Report sourceVisible must be a Boolean', file ?? location);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (typeof value !== 'string')
|
|
104
|
+
fail('AMX6001', `Report ${key} must be a string`, file ?? location);
|
|
105
|
+
const text = value.trim();
|
|
106
|
+
if (!text || /[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/u.test(text))
|
|
107
|
+
fail('AMX6001', `Report ${key} contains invalid text`, file ?? location);
|
|
108
|
+
if (TEXT_LIMITS[key] !== undefined && [...text].length > TEXT_LIMITS[key])
|
|
109
|
+
fail('AMX6001', `Report ${key} exceeds its length limit`, file ?? location);
|
|
110
|
+
}
|
|
111
|
+
if (report.logoAlt !== undefined && report.logo === undefined)
|
|
112
|
+
fail('AMX6001', 'Report logoAlt requires a logo', file ?? location);
|
|
113
|
+
if (report.accent !== undefined && (typeof report.accent !== 'string' || !/^#[0-9A-Fa-f]{6}$/.test(report.accent)))
|
|
114
|
+
fail('AMX6001', 'Report accent must use #RRGGBB', file ?? location);
|
|
115
|
+
}
|
|
116
|
+
async function resolveIdentity(projectReport, frontMatter, options) {
|
|
117
|
+
if (frontMatter.logo !== undefined && frontMatter.logoAlt === undefined)
|
|
118
|
+
fail('AMX6001', 'A frontmatter logo override requires logoAlt', options.file);
|
|
119
|
+
const merged = { ...projectReport, ...frontMatter };
|
|
120
|
+
const logoPath = typeof merged.logo === 'string' ? merged.logo.trim() : undefined;
|
|
121
|
+
const logo = logoPath ? await prepareLogo(logoPath, String(merged.logoAlt ?? ''), options.projectRoot, options.file) : undefined;
|
|
122
|
+
return Object.freeze({
|
|
123
|
+
organization: text(merged.organization),
|
|
124
|
+
logo,
|
|
125
|
+
accent: effectiveReportAccent(text(merged.accent) ?? '#146C94'),
|
|
126
|
+
author: text(merged.author),
|
|
127
|
+
status: text(merged.status),
|
|
128
|
+
classification: text(merged.classification),
|
|
129
|
+
footer: text(merged.footer),
|
|
130
|
+
sourceVisible: merged.sourceVisible === undefined ? true : merged.sourceVisible
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
async function prepareLogo(path, alt, projectRoot, file) {
|
|
134
|
+
if (!projectRoot)
|
|
135
|
+
fail('AMX6001', 'A report logo requires an explicit project root', file);
|
|
136
|
+
if (!alt.trim())
|
|
137
|
+
fail('AMX6001', 'A report logo requires descriptive logoAlt', file);
|
|
138
|
+
if (!/^[A-Za-z0-9._/-]+\.(png|jpg)$/.test(path) || path.includes('..') || path.includes('//') || path.startsWith('/') || path.includes('\\'))
|
|
139
|
+
fail('AMX6001', 'Report logo must be a contained .png or .jpg path', file);
|
|
140
|
+
const root = canonicalDirectory(projectRoot);
|
|
141
|
+
const candidate = resolve(root, path);
|
|
142
|
+
if (!isContained(root, candidate) || hasSymlink(root, candidate) || !existsSync(candidate) || !lstatSync(candidate).isFile())
|
|
143
|
+
fail('AMX6001', 'Report logo must be a contained regular file', file);
|
|
144
|
+
const bytes = readFileSync(candidate);
|
|
145
|
+
if (bytes.byteLength > 256 * 1024)
|
|
146
|
+
fail('AMX6001', 'Report logo exceeds 256 KiB', file);
|
|
147
|
+
try {
|
|
148
|
+
const image = sharp(bytes, { animated: false, limitInputPixels: 1_048_576 });
|
|
149
|
+
const metadata = await image.metadata();
|
|
150
|
+
const expectedFormat = path.endsWith('.jpg') ? 'jpeg' : 'png';
|
|
151
|
+
if (metadata.format !== expectedFormat)
|
|
152
|
+
fail('AMX6001', 'Report logo file extension does not match its image format', file);
|
|
153
|
+
if (!metadata.width || !metadata.height || metadata.width > 1024 || metadata.height > 1024 || metadata.width * metadata.height > 1_048_576 || (metadata.pages ?? 1) > 1)
|
|
154
|
+
fail('AMX6001', 'Report logo dimensions are invalid', file);
|
|
155
|
+
const sanitized = await image.rotate().png().toBuffer();
|
|
156
|
+
if (sanitized.byteLength > 1024 * 1024)
|
|
157
|
+
fail('AMX6002', 'Sanitized report logo exceeds 1 MiB', file);
|
|
158
|
+
return Object.freeze({ bytes: Uint8Array.from(sanitized), alt: alt.trim(), dataUri: `data:image/png;base64,${sanitized.toString('base64')}` });
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (error instanceof AmxError)
|
|
162
|
+
throw error;
|
|
163
|
+
fail('AMX6001', 'Report logo is not a supported image', file);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
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
|
+
function asRecord(value, message, file) {
|
|
176
|
+
if (value === undefined)
|
|
177
|
+
return {};
|
|
178
|
+
if (!asPlainRecord(value))
|
|
179
|
+
fail('AMX6001', message, file);
|
|
180
|
+
return value;
|
|
181
|
+
}
|
|
182
|
+
function asPlainRecord(value) {
|
|
183
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
184
|
+
}
|
|
185
|
+
function text(value) {
|
|
186
|
+
return typeof value === 'string' ? value.trim() || undefined : undefined;
|
|
187
|
+
}
|
|
188
|
+
export function effectiveReportAccent(accent) {
|
|
189
|
+
const channels = [accent.slice(1, 3), accent.slice(3, 5), accent.slice(5, 7)].map(value => Number.parseInt(value, 16) / 255);
|
|
190
|
+
const luminance = channels.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
|
|
191
|
+
.reduce((total, value, index) => total + value * [0.2126, 0.7152, 0.0722][index], 0);
|
|
192
|
+
return (1.05 / (luminance + 0.05)) >= 4.5 ? accent : '#146C94';
|
|
193
|
+
}
|
|
194
|
+
function fail(code, message, file) {
|
|
195
|
+
throw new AmxError({ code, message, file });
|
|
196
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function serializeCsvText(rows) {
|
|
2
|
+
const records = rows.map(row => row.map(cell => {
|
|
3
|
+
const value = cell.value;
|
|
4
|
+
const quote = cell.quoted || value === '' || /[",\r\n]/.test(value) || /^\s|\s$/.test(value);
|
|
5
|
+
return quote ? `"${value.replace(/"/g, '""')}"` : value;
|
|
6
|
+
}).join(','));
|
|
7
|
+
return `${records.join('\n')}\n`;
|
|
8
|
+
}
|