@nova-energy/openamx 0.0.0-stage → 0.10.1

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.
Files changed (42) hide show
  1. package/COMMERCIAL-LICENSE.md +74 -0
  2. package/LICENSE.md +660 -0
  3. package/README.md +513 -2
  4. package/dist/ast/types.js +2 -0
  5. package/dist/cli.js +186 -0
  6. package/dist/diagnostics/errors.js +94 -0
  7. package/dist/editor/completion.js +313 -0
  8. package/dist/editor/highlighting.js +224 -0
  9. package/dist/editor/moduleAnalysis.js +206 -0
  10. package/dist/editor/refactoring.js +46 -0
  11. package/dist/editor/sourceRanges.js +50 -0
  12. package/dist/editor/symbols.js +203 -0
  13. package/dist/formatter/formatAmx.js +79 -0
  14. package/dist/index.js +10 -0
  15. package/dist/parser/parseDocument.js +114 -0
  16. package/dist/parser/parseExpression.js +768 -0
  17. package/dist/parser/parseFor.js +53 -0
  18. package/dist/parser/parseFrontMatter.js +65 -0
  19. package/dist/parser/parseStatements.js +667 -0
  20. package/dist/parser/stringScanner.js +71 -0
  21. package/dist/renderer/chartModel.js +476 -0
  22. package/dist/renderer/renderHtml.js +383 -0
  23. package/dist/renderer/reportDocx.js +163 -0
  24. package/dist/renderer/reportPdf.js +202 -0
  25. package/dist/renderer/reportPreparation.js +208 -0
  26. package/dist/runtime/csvTextSerialization.js +8 -0
  27. package/dist/runtime/dataText.js +191 -0
  28. package/dist/runtime/docxDestination.js +55 -0
  29. package/dist/runtime/environment.js +105 -0
  30. package/dist/runtime/evaluateDocument.js +32 -0
  31. package/dist/runtime/evaluateExpression.js +888 -0
  32. package/dist/runtime/externalUnits.js +91 -0
  33. package/dist/runtime/inputData.js +508 -0
  34. package/dist/runtime/measurement.js +110 -0
  35. package/dist/runtime/moduleLoader.js +279 -0
  36. package/dist/runtime/outputData.js +303 -0
  37. package/dist/runtime/pdfDestination.js +57 -0
  38. package/dist/runtime/standardLibrary.js +145 -0
  39. package/dist/typechecker/checkDocument.js +1282 -0
  40. package/dist/typechecker/declarationRegistry.js +7 -0
  41. package/dist/typechecker/dimensionTypes.js +1 -0
  42. package/package.json +33 -4
@@ -0,0 +1,383 @@
1
+ /// <reference path="../types/echarts-runtime.d.ts" />
2
+ import { randomBytes } from 'node:crypto';
3
+ import echartsBrowserRuntime from 'echarts/dist/echarts.min.js' with { type: 'text' };
4
+ import { marked } from 'marked';
5
+ import sanitizeHtml from 'sanitize-html';
6
+ import { AmxError } from '../diagnostics/errors';
7
+ import { parseExpression } from '../parser/parseExpression';
8
+ import { evaluateExpression } from '../runtime/evaluateExpression';
9
+ import { evaluateDocumentEnvironment } from '../runtime/evaluateDocument';
10
+ import { formatAmx } from '../formatter/formatAmx';
11
+ import { createChartViewModel } from './chartModel';
12
+ const REPORT_MARKDOWN_POLICY = {
13
+ allowedTags: [
14
+ 'a', 'blockquote', 'br', 'code', 'del', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
15
+ 'hr', 'li', 'ol', 'p', 'pre', 'span', 'strong', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'ul'
16
+ ],
17
+ allowedAttributes: { code: ['class'] },
18
+ allowedSchemes: [],
19
+ allowProtocolRelative: false,
20
+ parseStyleAttributes: false,
21
+ disallowedTagsMode: 'discard',
22
+ enforceHtmlBoundary: true,
23
+ transformTags: { a: sanitizeHtml.simpleTransform('span', {}, true) }
24
+ };
25
+ /**
26
+ * Render an OpenAmxDocument to a complete standalone HTML5 document.
27
+ *
28
+ * - Executes all executable blocks once before rendering any document nodes.
29
+ * - Resolves narrative expressions against the final shared environment.
30
+ * - Post-substitution narrative is rendered with marked (headings, paragraphs, bullets).
31
+ * - Executable blocks are rendered as escaped, formatted source at their source position.
32
+ * - Frontmatter metadata.title (if string) is used for <title>; otherwise "OpenAMX Document".
33
+ * - Output is deterministic for the supported Markdown subset.
34
+ * - Errors inside {{ }} (e.g. AMX1004) are surfaced with the same AmxError semantics.
35
+ */
36
+ export function renderHtml(doc, file, env, options) {
37
+ const environment = env ?? evaluateDocumentEnvironment(doc, file);
38
+ const resolvedReport = resolveReportIdentity(doc, options?.report);
39
+ const emissionsByNode = new Map();
40
+ for (const emission of environment.viewEmissions) {
41
+ const emissions = emissionsByNode.get(emission.documentNodeIndex) ?? [];
42
+ emissions.push(emission);
43
+ emissionsByNode.set(emission.documentNodeIndex, emissions);
44
+ }
45
+ const bodyFragments = [];
46
+ const sourceVisible = resolvedReport.sourceVisible !== false;
47
+ const header = renderReportHeader(resolvedReport, file);
48
+ if (header) {
49
+ bodyFragments.push(header);
50
+ }
51
+ for (const [nodeIndex, node] of doc.nodes.entries()) {
52
+ if (node.type === 'narrative') {
53
+ const substituted = substituteInlines(node.content, environment, file, node.source?.line);
54
+ const htmlFragment = renderSafeMarkdown(substituted);
55
+ bodyFragments.push(htmlFragment);
56
+ }
57
+ else if (node.type === 'executableCodeBlock') {
58
+ if (sourceVisible) {
59
+ const formatted = formatAmx(node.content);
60
+ bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(formatted)}</code></pre>`);
61
+ }
62
+ for (const emission of emissionsByNode.get(nodeIndex) ?? []) {
63
+ bodyFragments.push(renderViewEmission(emission, resolvedReport));
64
+ }
65
+ }
66
+ }
67
+ const title = doc.metadata && typeof doc.metadata.title === 'string'
68
+ ? String(doc.metadata.title)
69
+ : 'OpenAMX Document';
70
+ const bodyHtml = bodyFragments.join('');
71
+ const escapedTitle = escapeHtml(title);
72
+ const hasViews = environment.viewEmissions.length > 0;
73
+ const nonce = hasViews || !!resolvedReport.accent ? randomBytes(18).toString('base64') : '';
74
+ const accentStyle = safeAccentStyle(resolvedReport.accent, nonce);
75
+ const viewAssets = hasViews ? renderViewAssets(nonce) : '';
76
+ return `<!doctype html>
77
+ <html>
78
+ <head>
79
+ <meta charset="utf-8">
80
+ ${renderContentSecurityPolicy(nonce, hasViews)}
81
+ <title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
82
+ </head>
83
+ <body>
84
+ ${bodyHtml}</body>
85
+ </html>`;
86
+ }
87
+ export function renderPreparedHtml(report) {
88
+ const bodyFragments = [];
89
+ const identity = report.identity;
90
+ const metadata = [
91
+ identity.organization,
92
+ identity.author && `Author: ${identity.author}`,
93
+ identity.status && `Status: ${identity.status}`,
94
+ identity.classification && `Classification: ${identity.classification}`
95
+ ].filter((value) => Boolean(value));
96
+ if (identity.logo || metadata.length > 0) {
97
+ const logo = identity.logo ? `<img class="openamx-report-logo" src="${escapeHtml(identity.logo.dataUri)}" alt="${escapeHtml(identity.logo.alt)}" />` : '';
98
+ bodyFragments.push(`<header class="openamx-report-header"><div class="openamx-report-identity">${logo}<div class="openamx-report-meta">${metadata.map(value => `<div class="openamx-report-attr">${escapeHtml(value)}</div>`).join('')}</div></div></header>`);
99
+ }
100
+ for (const item of report.items) {
101
+ if (item.type === 'narrative')
102
+ bodyFragments.push(renderSafeMarkdown(item.text));
103
+ else if (item.type === 'source')
104
+ bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(item.text)}</code></pre>`);
105
+ else
106
+ bodyFragments.push(renderViewEmission(item.emission, identity));
107
+ }
108
+ if (identity.footer)
109
+ bodyFragments.push(`<footer class="openamx-report-footer">${escapeHtml(identity.footer)}</footer>`);
110
+ const hasViews = report.items.some(item => item.type === 'view');
111
+ const nonce = hasViews || identity.accent !== '#146C94' ? randomBytes(18).toString('base64') : '';
112
+ const accentStyle = safeAccentStyle(identity.accent, nonce);
113
+ const viewAssets = hasViews ? renderViewAssets(nonce) : '';
114
+ return `<!doctype html>
115
+ <html>
116
+ <head>
117
+ <meta charset="utf-8">
118
+ ${renderContentSecurityPolicy(nonce, hasViews)}
119
+ <title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
120
+ </head>
121
+ <body>
122
+ ${bodyFragments.join('')}</body>
123
+ </html>`;
124
+ }
125
+ function renderViewEmission(emission, identity) {
126
+ if (emission.kind === 'table')
127
+ return renderTable(emission);
128
+ return renderChart(emission, identity);
129
+ }
130
+ function renderSafeMarkdown(markdown) {
131
+ return sanitizeHtml(marked.parse(markdown), REPORT_MARKDOWN_POLICY);
132
+ }
133
+ function renderTable(emission) {
134
+ const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
135
+ const columns = emission.declaration.options.filter(option => option.type === 'tableColumnOption');
136
+ const id = viewId(emission);
137
+ const rows = emission.data.filter(isRecordValue);
138
+ const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
139
+ const header = columns.map(column => `<th scope="col" aria-sort="none"><button type="button" data-sort="${escapeHtml(column.field)}">${escapeHtml(column.label)}</button></th>`).join('');
140
+ const body = rows.map((row, index) => `<tr data-row-index="${index}">${columns.map(column => `<td>${escapeHtml(valueToString(row[column.field]))}</td>`).join('')}</tr>`).join('');
141
+ const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${escapeHtml(valueToString(row[column.field]))}</td>`).join('')}</tr>`).join('');
142
+ const payload = safeJson({ columns: columns.map(column => ({ field: column.field, label: column.label })), rows });
143
+ return `<section class="openamx-view openamx-table" data-view="${id}" aria-labelledby="${id}-caption">
144
+ <h2 id="${id}-caption" class="sr-only">${escapeHtml(caption)}</h2>
145
+ <div class="openamx-table-controls"><label>Filter <input type="search" data-filter aria-controls="${id}-interactive"></label><label>Rows <select data-page-size aria-controls="${id}-interactive"><option>10</option><option selected>25</option><option>50</option></select></label></div>
146
+ <p class="openamx-status" data-status aria-live="polite"></p>
147
+ <table id="${id}-interactive"><caption>${escapeHtml(caption)}</caption><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>
148
+ <nav class="openamx-pagination" aria-label="${escapeHtml(caption)} pages"><button type="button" data-page="previous" aria-label="Previous page">Previous</button><span data-page-label></span><button type="button" data-page="next" aria-label="Next page">Next</button></nav>
149
+ <script type="application/json" id="${id}-data">${payload}</script>
150
+ <div class="openamx-print-view"><table><caption>${escapeHtml(caption)}</caption><thead><tr>${columns.map(column => `<th scope="col">${escapeHtml(column.label)}</th>`).join('')}</tr></thead><tbody>${printBody}</tbody></table></div>
151
+ </section>`;
152
+ }
153
+ function renderChart(emission, identity) {
154
+ const accent = identity.accent && /^#[0-9A-Fa-f]{6}$/.test(identity.accent) ? identity.accent : '#146C94';
155
+ const model = createChartViewModel(emission, { accent });
156
+ const browserModel = serializeChartModel(model);
157
+ const id = model.table.id;
158
+ const titleId = `${id}-title`;
159
+ const descriptionId = `${id}-description`;
160
+ const summaryId = `${id}-summary`;
161
+ const seriesControls = model.series.length > 1
162
+ ? `<div class="openamx-chart-legend" role="group" aria-label="Chart series">${model.series.map(series => `<button type="button" class="openamx-legend-toggle" data-series="${escapeHtml(series.name)}" aria-pressed="true"><span aria-hidden="true" style="--series-color:${escapeHtml(series.color)}"></span>${escapeHtml(series.name)}</button>`).join('')}</div>`
163
+ : '';
164
+ const zoomControls = browserModel.zoomable
165
+ ? `<div class="openamx-chart-controls" role="group" aria-label="Chart zoom controls"><button type="button" data-zoom="out" aria-label="Zoom out">Zoom out</button><button type="button" data-zoom="in" aria-label="Zoom in">Zoom in</button><button type="button" data-zoom="reset">Reset zoom</button></div>`
166
+ : '';
167
+ const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${escapeHtml(valueToString(value))}</td>`).join('')}</tr>`).join('');
168
+ const data = safeJson(browserModel);
169
+ return `<figure class="openamx-view openamx-chart" id="${id}-figure" data-openamx-chart aria-labelledby="${titleId}" aria-describedby="${descriptionId} ${summaryId}">
170
+ <figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
171
+ <p id="${summaryId}" class="sr-only">${escapeHtml(model.accessibility.summary)}</p>
172
+ ${seriesControls}${zoomControls}
173
+ <div id="${id}-plot" class="openamx-chart-plot" role="img" aria-label="${escapeHtml(model.title)}" aria-describedby="${descriptionId} ${summaryId} ${id}-table-caption"></div>
174
+ <table class="openamx-chart-data" id="${id}"><caption id="${id}-table-caption">${escapeHtml(model.table.caption)}</caption><thead><tr>${model.table.headings.map(value => `<th scope="col">${escapeHtml(value)}</th>`).join('')}</tr></thead><tbody>${textRows}</tbody></table>
175
+ <script type="application/json" data-chart-model>${data}</script>
176
+ </figure>`;
177
+ }
178
+ function serializeChartModel(model) {
179
+ const formatterPaths = [];
180
+ const option = projectSerializable(model.option, '$', formatterPaths);
181
+ const zoomable = model.kind === 'scatter' || (model.kind === 'line' && model.option.xAxis !== undefined
182
+ && !isCategoryAxis(model.option.xAxis));
183
+ if (zoomable) {
184
+ const zoom = [{ type: 'inside', xAxisIndex: 0, ...(model.kind === 'scatter' ? { yAxisIndex: 0 } : {}), filterMode: 'none', zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }];
185
+ optionProperty(option, 'dataZoom', zoom);
186
+ }
187
+ return {
188
+ kind: model.kind,
189
+ title: model.title,
190
+ description: model.description,
191
+ dimensions: model.dimensions,
192
+ option,
193
+ formatterPaths,
194
+ table: model.table,
195
+ series: model.series,
196
+ axes: model.axes,
197
+ accessibility: model.accessibility,
198
+ plottedPointCount: model.plottedPointCount,
199
+ ...(model.emptyState ? { emptyState: model.emptyState } : {}),
200
+ ...(model.dateTimePresentation ? { dateTimePresentation: model.dateTimePresentation } : {}),
201
+ zoomable
202
+ };
203
+ }
204
+ function projectSerializable(value, path, formatterPaths) {
205
+ if (typeof value === 'function') {
206
+ const allowed = path === '$.tooltip.formatter'
207
+ || /\.(xAxis|yAxis)(\.\d+)?\.axisLabel\.formatter$/.test(path)
208
+ || /\.(xAxis|yAxis)(\.\d+)?\.axisPointer\.label\.formatter$/.test(path);
209
+ if (!allowed)
210
+ throw new Error(`Unsupported function in chart model at ${path}.`);
211
+ formatterPaths.push(path);
212
+ return undefined;
213
+ }
214
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
215
+ return value;
216
+ if (typeof value === 'number') {
217
+ if (!Number.isFinite(value))
218
+ throw new Error(`Non-finite chart value at ${path}.`);
219
+ return value;
220
+ }
221
+ if (Array.isArray(value)) {
222
+ return value.map((item, index) => projectSerializable(item, `${path}.${index}`, formatterPaths) ?? null);
223
+ }
224
+ if (typeof value === 'object') {
225
+ const projected = {};
226
+ for (const [key, item] of Object.entries(value)) {
227
+ const itemPath = `${path}.${key}`;
228
+ const itemProjection = projectSerializable(item, itemPath, formatterPaths);
229
+ if (itemProjection !== undefined)
230
+ projected[key] = itemProjection;
231
+ }
232
+ return projected;
233
+ }
234
+ if (value === undefined)
235
+ return undefined;
236
+ throw new Error(`Unsupported chart model value at ${path}.`);
237
+ }
238
+ function optionProperty(option, key, value) {
239
+ if (option === null || Array.isArray(option) || typeof option !== 'object')
240
+ throw new Error('Chart option projection is not an object.');
241
+ option[key] = value;
242
+ }
243
+ function isCategoryAxis(axis) {
244
+ const first = Array.isArray(axis) ? axis[0] : axis;
245
+ return first?.type === 'category' || first?.type === undefined;
246
+ }
247
+ function viewId(emission) {
248
+ return `openamx-view-${emission.documentNodeIndex}-${emission.statementIndex}`;
249
+ }
250
+ function isRecordValue(value) {
251
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
252
+ }
253
+ function safeJson(value) {
254
+ return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');
255
+ }
256
+ function renderContentSecurityPolicy(nonce, hasViews) {
257
+ const scripts = hasViews ? `'nonce-${nonce}'` : "'none'";
258
+ const styles = hasViews || nonce ? `'nonce-${nonce}'` : "'none'";
259
+ const styleAttributes = hasViews ? "; style-src-attr 'unsafe-inline'" : '';
260
+ return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${scripts}; style-src ${styles}${styleAttributes}; img-src data:; font-src data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; worker-src 'none'; media-src 'none'">`;
261
+ }
262
+ function safeAccentStyle(accent, nonce) {
263
+ if (!accent || !/^#[0-9A-Fa-f]{6}$/.test(accent) || accent.toLowerCase() === '#146c94')
264
+ return '';
265
+ return `<style nonce="${nonce}">:root{--openamx-accent:${accent};}</style>`;
266
+ }
267
+ function renderChartBootstrap() {
268
+ return `(()=>{
269
+ const charts=new Map();
270
+ const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char]));
271
+ const iso=value=>{const date=new Date(typeof value==='number'?value:Date.parse(value));return Number.isNaN(date.getTime())?'':date.toISOString()};
272
+ const locate=(object,path)=>path.slice(2).split('.').reduce((current,key)=>current==null?undefined:current[/^\\d+$/.test(key)?Number(key):key],object);
273
+ const rowLabel=(value,model)=>{const row=model.table.rows.find(item=>item.id===String(value));return row?String(row.values[0]??''):String(value??'')};
274
+ const axisLabel=(value,model)=>model.dateTimePresentation?iso(value):rowLabel(value,model);
275
+ const formatTooltip=(input,model)=>{const entries=(Array.isArray(input)?input:[input]).filter(item=>item&&typeof item==='object');return entries.map(entry=>{const series=model.series.find(item=>item.id===entry.seriesId||item.name===entry.seriesName);const values=Array.isArray(entry.value)?entry.value:[];if(model.kind==='scatter'){const x=values[0]??null,y=values[1]??null;const xUnit=model.axes.find(item=>item.role==='x')?.name,yUnit=model.axes.find(item=>item.role==='y')?.name;return '<div><strong>'+escapeHtml(entry.seriesName||'')+'</strong><br>x: '+escapeHtml(x)+(xUnit?' '+escapeHtml(xUnit):'')+'<br>y: '+escapeHtml(y)+(yUnit?' '+escapeHtml(yUnit):'')+'</div>'}const rawCategory=entry.axisValue??values[0]??entry.name;const category=model.dateTimePresentation?iso(rawCategory):rowLabel(rawCategory,model);const value=model.kind==='line'?values[1]:entry.value;const categoryUnit=model.kind==='line'?model.axes.find(item=>item.role==='x')?.name:undefined;const coordinate=escapeHtml(category)+(categoryUnit?' '+escapeHtml(categoryUnit):'');return '<div><strong>'+escapeHtml(entry.seriesName||'')+'</strong><br>'+coordinate+': '+escapeHtml(value)+(series?.unit?.text?' '+escapeHtml(series.unit.text):'')+'</div>'}).join('')};
276
+ const setZoom=(chart,zoom)=>{const current=chart.getOption().dataZoom?.[0]??{start:0,end:100};chart.setOption({dataZoom:[{...current,...zoom}]})};
277
+ const restoreFormatters=model=>{for(const path of model.formatterPaths){const key=path.split('.').at(-1),parentPath=path.slice(0,path.lastIndexOf('.')),parent=locate(model.option,parentPath);if(!parent)throw new Error('Chart formatter path is invalid.');if(path==='$.tooltip.formatter')parent[key]=params=>formatTooltip(params,model);else if(parentPath.endsWith('.axisPointer.label'))parent[key]=params=>iso(params?.value);else parent[key]=value=>axisLabel(value,model)}};
278
+ const initialize=root=>{const payloadNode=root.querySelector('[data-chart-model]'),plot=root.querySelector('.openamx-chart-plot');if(!payloadNode||!plot)return;const model=JSON.parse(payloadNode.textContent||'null');restoreFormatters(model);const chart=echarts.init(plot,null,{renderer:'canvas'});chart.setOption(model.option);root.querySelectorAll('[data-series]').forEach(button=>button.addEventListener('click',()=>chart.dispatchAction({type:'legendToggleSelect',name:button.dataset.series})));chart.on('legendselectchanged',event=>root.querySelectorAll('[data-series]').forEach(button=>button.setAttribute('aria-pressed',String(event.selected?.[button.dataset.series]!==false))));root.querySelectorAll('[data-zoom]').forEach(button=>button.addEventListener('click',()=>{const current=chart.getOption().dataZoom?.[0]??{start:0,end:100},span=(current.end??100)-(current.start??0);if(button.dataset.zoom==='reset')setZoom(chart,{start:0,end:100});else{const next=Math.max(5,Math.min(100,span*(button.dataset.zoom==='in'?.75:1.33))),center=((current.start??0)+(current.end??100))/2;setZoom(chart,{start:Math.max(0,center-next/2),end:Math.min(100,center+next/2)})}}));const resizeObserver=new ResizeObserver(()=>chart.resize());resizeObserver.observe(plot);charts.set(root,{chart,resizeObserver})};
279
+ const dispose=root=>{const item=charts.get(root);if(!item)return;item.resizeObserver.disconnect();item.chart.dispose();charts.delete(root)};
280
+ const start=()=>{
281
+ document.querySelectorAll('[data-openamx-chart]').forEach(initialize);
282
+ const mutationObserver=new MutationObserver(()=>{for(const root of charts.keys())if(!document.documentElement.contains(root))dispose(root)});mutationObserver.observe(document.documentElement,{childList:true,subtree:true});
283
+ window.addEventListener('pagehide',()=>{for(const root of charts.keys())dispose(root);mutationObserver.disconnect()},{once:true});
284
+ };
285
+ if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
286
+ })();`;
287
+ }
288
+ function renderViewAssets(nonce) {
289
+ const assets = `<style>
290
+ .openamx-view{margin:1.5rem 0}.openamx-view table{border-collapse:collapse;width:100%}.openamx-view th,.openamx-view td{border:1px solid #a8b3bd;padding:.4rem;text-align:left}.openamx-view th button{font:inherit;font-weight:700;background:none;border:0;padding:0;cursor:pointer}.openamx-table-controls{display:flex;gap:1rem;flex-wrap:wrap;margin:.5rem 0}.openamx-status{min-height:1.4em}.openamx-pagination{display:flex;gap:.75rem;align-items:center;margin:.5rem 0}.openamx-chart svg{display:block;width:100%;max-width:40rem;height:auto;border:1px solid #a8b3bd}.openamx-chart figcaption{display:flex;flex-direction:column;gap:.25rem}.openamx-chart-data{margin-top:.75rem}.openamx-print-view,.openamx-print-chart{display:none}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media print{.openamx-table-controls,.openamx-status,.openamx-pagination,.openamx-table>table,.openamx-chart>svg,.openamx-chart-data{display:none}.openamx-print-view,.openamx-print-chart{display:block}.openamx-view{break-inside:avoid}.openamx-view th{background:#eee}.openamx-view thead{display:table-header-group}}
291
+ </style>
292
+ <script>
293
+ document.addEventListener('DOMContentLoaded',()=>{for(const root of document.querySelectorAll('[data-view].openamx-table')){const table=root.querySelector('table[id$="-interactive"]'),body=table?.querySelector('tbody'),filter=root.querySelector('[data-filter]'),size=root.querySelector('[data-page-size]'),status=root.querySelector('[data-status]'),pageLabel=root.querySelector('[data-page-label]');if(!table||!body||!filter||!size||!status||!pageLabel)continue;const payload=JSON.parse(document.getElementById(root.dataset.view+'-data').textContent),rows=[...body.querySelectorAll('tr')],original=rows.map((row,index)=>({row,index,text:row.textContent?.toLowerCase()??''}));let page=0,pageSize=25,sortField='',ascending=true;const update=()=>{let visible=original.filter(item=>item.text.includes(filter.value.toLowerCase()));if(sortField){visible.sort((a,b)=>{const av=payload.rows[a.index][sortField],bv=payload.rows[b.index][sortField];if(av===null&&bv!==null)return 1;if(av!==null&&bv===null)return -1;let result=av===bv?0:av<bv?-1:1;return (ascending?result:-result)||a.index-b.index})}visible.forEach(item=>body.appendChild(item.row));const pages=Math.max(1,Math.ceil(visible.length/pageSize));page=Math.min(page,pages-1);rows.forEach(row=>row.hidden=true);visible.slice(page*pageSize,(page+1)*pageSize).forEach(item=>item.row.hidden=false);status.textContent=visible.length===0?(filter.value?'No matching rows':'No rows'):'Showing '+(page*pageSize+1)+'-'+Math.min((page+1)*pageSize,visible.length)+' of '+visible.length+' rows';pageLabel.textContent='Page '+(page+1)+' of '+pages;root.querySelector('[data-page="previous"]').disabled=page===0;root.querySelector('[data-page="next"]').disabled=page>=pages-1};filter.addEventListener('input',()=>{page=0;update()});size.addEventListener('change',()=>{pageSize=Number(size.value);page=0;update()});root.querySelectorAll('[data-sort]').forEach(button=>button.addEventListener('click',()=>{const next=button.dataset.sort??'';ascending=sortField===next?!ascending:true;sortField=next;table.querySelectorAll('th').forEach(th=>th.setAttribute('aria-sort',th.querySelector('button')===button?(ascending?'ascending':'descending'):'none'));page=0;update()}));root.querySelector('[data-page="previous"]').addEventListener('click',()=>{page--;update()});root.querySelector('[data-page="next"]').addEventListener('click',()=>{page++;update()});update()}});
294
+ </script>`;
295
+ return assets
296
+ .replace('<style>', `<style nonce="${nonce}">`)
297
+ .replace('<script>', `<script nonce="${nonce}">`)
298
+ .replace('</script>', `</script><style nonce="${nonce}">.openamx-chart-plot{width:100%;min-width:320px;height:360px}.openamx-chart-legend,.openamx-chart-controls{display:flex;align-items:center;flex-wrap:wrap;gap:.5rem;margin:.5rem 0}.openamx-legend-toggle{display:inline-flex;align-items:center;gap:.4rem}.openamx-legend-toggle span{width:.75rem;height:.75rem;border-radius:50%;background:var(--series-color);flex:none}.openamx-legend-toggle[aria-pressed="false"]{opacity:.55}@media print{.openamx-chart-controls,.openamx-chart-legend{display:none!important}.openamx-chart-plot{min-width:0;break-inside:avoid}.openamx-chart-data{display:table!important}}</style><script nonce="${nonce}">${echartsBrowserRuntime}</script><script nonce="${nonce}">${renderChartBootstrap()}</script>`);
299
+ }
300
+ function renderReportHeader(report, _file) {
301
+ const org = report.organization?.trim();
302
+ const author = report.author?.trim();
303
+ const status = report.status?.trim();
304
+ const classification = report.classification?.trim();
305
+ const footer = report.footer?.trim();
306
+ const logo = report.logo?.trim();
307
+ if (!org && !author && !status && !classification && !logo && !footer) {
308
+ return '';
309
+ }
310
+ const logoMarkup = logo ? `<img class="openamx-report-logo" src="${escapeHtml(logo)}" alt="${escapeHtml(report.logoAlt ?? 'Report logo')}" />` : '';
311
+ const meta = [
312
+ org ? `<div class="openamx-report-attr">${escapeHtml(org)}</div>` : '',
313
+ author ? `<div class="openamx-report-attr">Author: ${escapeHtml(author)}</div>` : '',
314
+ status ? `<div class="openamx-report-attr">Status: ${escapeHtml(status)}</div>` : '',
315
+ classification ? `<div class="openamx-report-attr">Classification: ${escapeHtml(classification)}</div>` : '',
316
+ footer ? `<div class="openamx-report-attr">${escapeHtml(footer)}</div>` : '',
317
+ ].filter(Boolean).join('');
318
+ return `<header class="openamx-report-header"><div class="openamx-report-identity">${logoMarkup}<div class="openamx-report-meta">${meta || '<div class="openamx-report-attr">OpenAMX report</div>'}</div></div></header>`;
319
+ }
320
+ function resolveReportIdentity(doc, override) {
321
+ const metadata = (doc.metadata ?? {});
322
+ const frontMatterReport = isRecord(metadata.report) ? metadata.report : {};
323
+ const merged = { ...frontMatterReport, ...override };
324
+ const sourceVisible = merged.sourceVisible === undefined ? true : Boolean(merged.sourceVisible);
325
+ const logo = typeof merged.logo === 'string' ? merged.logo : undefined;
326
+ if (logo)
327
+ throw new AmxError({ code: 'AMX6001', message: 'Logo reports require shared report preparation' });
328
+ return {
329
+ organization: stringOrUndefined(merged.organization),
330
+ logo: undefined,
331
+ logoAlt: stringOrUndefined(merged.logoAlt),
332
+ accent: stringOrUndefined(merged.accent),
333
+ author: stringOrUndefined(merged.author),
334
+ status: stringOrUndefined(merged.status),
335
+ classification: stringOrUndefined(merged.classification),
336
+ footer: stringOrUndefined(merged.footer),
337
+ sourceVisible,
338
+ };
339
+ }
340
+ function stringOrUndefined(value) {
341
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
342
+ }
343
+ function isRecord(value) {
344
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
345
+ }
346
+ function substituteInlines(content, env, file, narrativeLine) {
347
+ // Non-nested {{ expr }} substitution. Expressions cannot contain literal "}}" per v0.1.
348
+ return content.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_full, exprText) => {
349
+ const trimmed = exprText.trim();
350
+ if (trimmed.length === 0) {
351
+ return '';
352
+ }
353
+ // Attach approximate source for better diagnostics (narrative block start line).
354
+ const source = narrativeLine !== undefined ? { line: narrativeLine, column: 1 } : undefined;
355
+ const exprNode = parseExpression(trimmed, source);
356
+ const value = evaluateExpression(exprNode, env, file);
357
+ return escapeHtml(valueToString(value));
358
+ });
359
+ }
360
+ function valueToString(v) {
361
+ if (v === null || v === undefined)
362
+ return '';
363
+ if (typeof v === 'string')
364
+ return v;
365
+ if (typeof v === 'number') {
366
+ // Present integers without trailing .0 for natural readability in text.
367
+ return Number.isInteger(v) ? String(v) : String(v);
368
+ }
369
+ if (typeof v === 'boolean')
370
+ return String(v); // "true" / "false"
371
+ if (Array.isArray(v)) {
372
+ // Simple deterministic representation for lists inside narrative text.
373
+ return v.map(valueToString).join(', ');
374
+ }
375
+ return String(v);
376
+ }
377
+ function escapeHtml(s) {
378
+ return s
379
+ .replace(/&/g, '&amp;')
380
+ .replace(/</g, '&lt;')
381
+ .replace(/>/g, '&gt;')
382
+ .replace(/"/g, '&quot;');
383
+ }
@@ -0,0 +1,163 @@
1
+ import { Document, HeadingLevel, ImageRun, Packer, Paragraph, Table, TableCell, TableRow, TextRun, Footer } from 'docx';
2
+ export function prepareDocxReport(report) {
3
+ return preparePreparedDocxReport(report);
4
+ }
5
+ export async function serializeDocxReport(report) {
6
+ return Uint8Array.from(await Packer.toBuffer(report.document));
7
+ }
8
+ function preparePreparedDocxReport(report) {
9
+ const children = [];
10
+ const identity = report.identity;
11
+ if (identity.logo || identity.organization || identity.author || identity.status || identity.classification) {
12
+ const runs = [];
13
+ if (identity.logo)
14
+ runs.push(new ImageRun({ type: 'png', data: identity.logo.bytes, transformation: { width: 120, height: 48 }, altText: { title: identity.logo.alt, description: identity.logo.alt, name: 'Report logo' } }));
15
+ const metadata = [identity.organization, identity.author && `Author: ${identity.author}`, identity.status && `Status: ${identity.status}`, identity.classification && `Classification: ${identity.classification}`].filter((value) => Boolean(value));
16
+ if (metadata.length > 0)
17
+ runs.push(new TextRun({ text: `${runs.length ? '\n' : ''}${metadata.join('\n')}`, bold: true }));
18
+ children.push(new Paragraph({ children: runs }));
19
+ }
20
+ for (const item of report.items) {
21
+ if (item.type === 'narrative')
22
+ addNarrativeText(children, item.text);
23
+ else if (item.type === 'source')
24
+ children.push(new Paragraph({ style: 'Normal', children: [new TextRun({ text: item.text, font: 'Courier New', size: 18 })] }));
25
+ else
26
+ addEmission(children, item.emission);
27
+ }
28
+ return {
29
+ document: new Document({
30
+ title: report.title,
31
+ creator: identity.author ?? 'OpenAMX',
32
+ description: 'Editable OpenAMX report',
33
+ sections: [{ children, footers: identity.footer ? { default: new Footer({ children: [new Paragraph({ text: identity.footer })] }) } : undefined }]
34
+ })
35
+ };
36
+ }
37
+ function addNarrativeText(children, narrative) {
38
+ let paragraphLines = [];
39
+ const flushParagraph = () => {
40
+ if (paragraphLines.length > 0) {
41
+ children.push(new Paragraph(paragraphLines.join(' ')));
42
+ paragraphLines = [];
43
+ }
44
+ };
45
+ for (const line of narrative.split(/\r?\n/)) {
46
+ const trimmed = line.trim();
47
+ if (trimmed === '<!-- page-break -->') {
48
+ flushParagraph();
49
+ children.push(new Paragraph({ text: '', pageBreakBefore: true }));
50
+ }
51
+ else if (/^#{1,6}\s+/.test(trimmed)) {
52
+ flushParagraph();
53
+ const level = Math.min(6, (trimmed.match(/^#+/) ?? ['#'])[0].length);
54
+ children.push(new Paragraph({
55
+ text: trimmed.replace(/^#+\s+/, ''),
56
+ heading: headingLevel(level)
57
+ }));
58
+ }
59
+ else if (/^[-*]\s+/.test(trimmed)) {
60
+ flushParagraph();
61
+ children.push(new Paragraph({
62
+ text: trimmed.replace(/^[-*]\s+/, ''),
63
+ bullet: { level: 0 }
64
+ }));
65
+ }
66
+ else if (trimmed === '') {
67
+ flushParagraph();
68
+ }
69
+ else {
70
+ paragraphLines.push(line.trim());
71
+ }
72
+ }
73
+ flushParagraph();
74
+ }
75
+ function addEmission(children, emission) {
76
+ if (emission.kind === 'table')
77
+ addTable(children, emission);
78
+ else
79
+ addChart(children, emission);
80
+ }
81
+ function addTable(children, emission) {
82
+ const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
83
+ const columns = emission.declaration.options.filter(option => option.type === 'tableColumnOption');
84
+ const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
85
+ children.push(new Paragraph({ text: caption, heading: HeadingLevel.HEADING_2 }));
86
+ const header = new TableRow({ children: columns.map(column => tableCell(column.label, true)) });
87
+ const rows = emission.data.map(value => new TableRow({
88
+ children: columns.map(column => tableCell(isRecord(value) ? valueToString(value[column.field]) : ''))
89
+ }));
90
+ children.push(new Table({ rows: [header, ...rows] }));
91
+ }
92
+ function addChart(children, emission) {
93
+ const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
94
+ const description = emission.declaration.options.find(option => option.type === 'viewDescriptionOption');
95
+ const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
96
+ const detail = description?.type === 'viewDescriptionOption' ? description.value : `${emission.kind} chart`;
97
+ const rows = chartRows(emission);
98
+ children.push(new Paragraph({ text: caption, heading: HeadingLevel.HEADING_2 }));
99
+ children.push(new Paragraph(detail));
100
+ if (rows.length > 0) {
101
+ children.push(new Paragraph({
102
+ children: [new ImageRun({
103
+ type: 'svg',
104
+ data: new TextEncoder().encode(chartSvg(rows)),
105
+ transformation: { width: 480, height: 180 },
106
+ fallback: { type: 'png', data: transparentPng }
107
+ })]
108
+ }));
109
+ }
110
+ else {
111
+ children.push(new Paragraph('No data'));
112
+ }
113
+ const headings = emission.headings ? [...emission.headings] : emission.declaration.kind === 'scatter'
114
+ ? ['x', 'y', 'group']
115
+ : ['label', ...emission.declaration.options.filter(option => option.type === 'chartSeriesOption').map(option => option.label)];
116
+ const tableRows = [
117
+ new TableRow({ children: headings.map(heading => tableCell(heading, true)) }),
118
+ ...rows.map(row => new TableRow({ children: row.map(value => tableCell(valueToString(value))) }))
119
+ ];
120
+ children.push(new Table({ rows: tableRows }));
121
+ }
122
+ function tableCell(value, bold = false) {
123
+ return new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: value, bold })] })] });
124
+ }
125
+ function chartRows(emission) {
126
+ const options = emission.declaration.options;
127
+ const category = options.find(option => option.type === 'chartFieldOption' && option.role === 'category');
128
+ const x = options.find(option => option.type === 'chartFieldOption' && option.role === 'x');
129
+ const y = options.find(option => option.type === 'chartFieldOption' && option.role === 'y');
130
+ const group = options.find(option => option.type === 'chartFieldOption' && option.role === 'group');
131
+ const series = options.filter(option => option.type === 'chartSeriesOption');
132
+ const labels = emission.labels ?? emission.data.map((_value, index) => String(index + 1));
133
+ return emission.data.map((value, index) => {
134
+ if (isRecord(value)) {
135
+ if (emission.declaration.kind === 'scatter')
136
+ return [value[x?.type === 'chartFieldOption' ? x.field : 'x'], value[y?.type === 'chartFieldOption' ? y.field : 'y'], group?.type === 'chartFieldOption' ? value[group.field] : ''];
137
+ return [category?.type === 'chartFieldOption' ? value[category.field] : labels[index], ...series.map(option => option.type === 'chartSeriesOption' && option.field ? value[option.field] : null)];
138
+ }
139
+ return [labels[index], value];
140
+ });
141
+ }
142
+ function chartSvg(rows) {
143
+ const values = rows.flatMap(row => row.slice(1)).filter((value) => typeof value === 'number' && Number.isFinite(value));
144
+ const max = Math.max(1, ...values.map(value => Math.abs(value)));
145
+ const bars = rows.flatMap((row, rowIndex) => row.slice(1).map((value, seriesIndex) => typeof value === 'number'
146
+ ? `<rect x="${40 + rowIndex * 560 / Math.max(1, rows.length) + seriesIndex * 14}" y="${145 - value / max * 105}" width="12" height="${Math.max(0, value / max * 105)}" fill="${['#146c94', '#d97706', '#15803d'][seriesIndex % 3]}"/>`
147
+ : '')).join('');
148
+ return `<svg width="600" height="160" viewBox="0 0 600 160" xmlns="http://www.w3.org/2000/svg"><line x1="40" y1="145" x2="580" y2="145" stroke="#58675d"/>${bars}</svg>`;
149
+ }
150
+ const transparentPng = Uint8Array.from(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'));
151
+ function headingLevel(level) {
152
+ return [HeadingLevel.HEADING_1, HeadingLevel.HEADING_2, HeadingLevel.HEADING_3, HeadingLevel.HEADING_4, HeadingLevel.HEADING_5, HeadingLevel.HEADING_6][level - 1];
153
+ }
154
+ function isRecord(value) {
155
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
156
+ }
157
+ function valueToString(value) {
158
+ if (value === null || value === undefined)
159
+ return '(null)';
160
+ if (Array.isArray(value))
161
+ return value.map(valueToString).join(', ');
162
+ return String(value);
163
+ }