@cs-object/react 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,2189 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __objRest = (source, exclude) => {
24
+ var target = {};
25
+ for (var prop in source)
26
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
+ target[prop] = source[prop];
28
+ if (source != null && __getOwnPropSymbols)
29
+ for (var prop of __getOwnPropSymbols(source)) {
30
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
+ target[prop] = source[prop];
32
+ }
33
+ return target;
34
+ };
35
+ var __export = (target, all) => {
36
+ for (var name in all)
37
+ __defProp(target, name, { get: all[name], enumerable: true });
38
+ };
39
+ var __copyProps = (to, from, except, desc) => {
40
+ if (from && typeof from === "object" || typeof from === "function") {
41
+ for (let key of __getOwnPropNames(from))
42
+ if (!__hasOwnProp.call(to, key) && key !== except)
43
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
44
+ }
45
+ return to;
46
+ };
47
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48
+
49
+ // src/index.ts
50
+ var index_exports = {};
51
+ __export(index_exports, {
52
+ AsciiMathView: () => AsciiMathView,
53
+ DocumentPreparationError: () => DocumentPreparationError,
54
+ FormulaSheet: () => FormulaSheet,
55
+ PreparedFormulaSheet: () => PreparedFormulaSheet,
56
+ prepareExecutionDocument: () => prepareExecutionDocument,
57
+ prepareLegacyDocument: () => prepareLegacyDocument,
58
+ printFormulaSheet: () => printFormulaSheet
59
+ });
60
+ module.exports = __toCommonJS(index_exports);
61
+
62
+ // src/formula-sheet/tokens.ts
63
+ var headerTextClass = "font-['Plus_Jakarta_Sans'] text-[12px] text-black/50";
64
+ var valueTextClass = "font-['KaTeX_Main'] text-[16.335px]";
65
+ var FORMULA_SHEET_SPACER_CELL_CLASS = "w-[1.5%] p-[3px]";
66
+ var FORMULA_SHEET_DESCRIPTION_CELL_CLASS = `flex w-[37%] flex-col justify-start py-[3px] ${headerTextClass}`;
67
+ var FORMULA_SHEET_COMMENT_CELL_CLASS = `flex w-[23.5%] flex-col justify-start py-[3px] text-right ${headerTextClass}`;
68
+ var FORMULA_SHEET_SYMBOL_CELL_BASE_CLASS = "flex w-[14%] min-w-[14%] items-center justify-end overflow-visible border-r border-gray-300";
69
+ var FORMULA_SHEET_SYMBOL_CELL_HEADER_CLASS = `p-[3px] ${headerTextClass}`;
70
+ var FORMULA_SHEET_SYMBOL_CELL_VALUE_CLASS = `p-[3px] pr-[5px] ${valueTextClass}`;
71
+ var FORMULA_SHEET_VALUE_CELL_BASE_CLASS = "flex w-[14.5%] items-center justify-end border-r border-gray-300";
72
+ var FORMULA_SHEET_VALUE_CELL_HEADER_CLASS = `p-[3px] ${headerTextClass}`;
73
+ var FORMULA_SHEET_VALUE_CELL_VALUE_CLASS = `p-[3px] ${valueTextClass}`;
74
+ var FORMULA_SHEET_UNIT_CELL_BASE_CLASS = "flex w-[9.5%] items-center overflow-hidden";
75
+ var FORMULA_SHEET_UNIT_CELL_HEADER_CLASS = `p-[3px] ${headerTextClass}`;
76
+ var FORMULA_SHEET_UNIT_CELL_VALUE_CLASS = "p-[5px]";
77
+
78
+ // src/formula-sheet/cells/FormulaSheetCommentCell.tsx
79
+ var import_jsx_runtime = require("react/jsx-runtime");
80
+ var FormulaSheetCommentCell = ({
81
+ children,
82
+ className = ""
83
+ }) => {
84
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `${FORMULA_SHEET_COMMENT_CELL_CLASS} ${className}`, children });
85
+ };
86
+
87
+ // src/formula-sheet/cells/FormulaSheetDescriptionCell.tsx
88
+ var import_jsx_runtime2 = require("react/jsx-runtime");
89
+ var FormulaSheetDescriptionCell = ({
90
+ children,
91
+ className = ""
92
+ }) => {
93
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: `${FORMULA_SHEET_DESCRIPTION_CELL_CLASS} ${className}`, children });
94
+ };
95
+
96
+ // src/formula-sheet/cells/FormulaSheetSpacerCell.tsx
97
+ var import_jsx_runtime3 = require("react/jsx-runtime");
98
+ var FormulaSheetSpacerCell = ({
99
+ className = ""
100
+ }) => {
101
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: `${FORMULA_SHEET_SPACER_CELL_CLASS} ${className}` });
102
+ };
103
+
104
+ // src/formula-sheet/cells/FormulaSheetSymbolCell.tsx
105
+ var import_jsx_runtime4 = require("react/jsx-runtime");
106
+ var FormulaSheetSymbolCell = ({
107
+ children,
108
+ className = "",
109
+ initColumn = false
110
+ }) => {
111
+ const variantClass = initColumn ? FORMULA_SHEET_SYMBOL_CELL_HEADER_CLASS : FORMULA_SHEET_SYMBOL_CELL_VALUE_CLASS;
112
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
113
+ "div",
114
+ {
115
+ className: `${FORMULA_SHEET_SYMBOL_CELL_BASE_CLASS} ${variantClass} ${className}`,
116
+ children
117
+ }
118
+ );
119
+ };
120
+
121
+ // src/formula-sheet/cells/FormulaSheetUnitCell.tsx
122
+ var import_jsx_runtime5 = require("react/jsx-runtime");
123
+ var FormulaSheetUnitCell = ({
124
+ children,
125
+ className = "",
126
+ initColumn = false
127
+ }) => {
128
+ const variantClass = initColumn ? FORMULA_SHEET_UNIT_CELL_HEADER_CLASS : FORMULA_SHEET_UNIT_CELL_VALUE_CLASS;
129
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
130
+ "div",
131
+ {
132
+ className: `${FORMULA_SHEET_UNIT_CELL_BASE_CLASS} ${variantClass} ${className}`,
133
+ children
134
+ }
135
+ );
136
+ };
137
+
138
+ // src/formula-sheet/cells/FormulaSheetValueCell.tsx
139
+ var import_jsx_runtime6 = require("react/jsx-runtime");
140
+ var FormulaSheetValueCell = ({
141
+ children,
142
+ className = "",
143
+ initColumn = false
144
+ }) => {
145
+ const variantClass = initColumn ? FORMULA_SHEET_VALUE_CELL_HEADER_CLASS : FORMULA_SHEET_VALUE_CELL_VALUE_CLASS;
146
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
147
+ "div",
148
+ {
149
+ className: `${FORMULA_SHEET_VALUE_CELL_BASE_CLASS} ${variantClass} ${className}`,
150
+ children
151
+ }
152
+ );
153
+ };
154
+
155
+ // src/formula-sheet/FormulaSheetHeader.tsx
156
+ var import_jsx_runtime7 = require("react/jsx-runtime");
157
+ var FormulaSheetHeader = () => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("header", { className: "min-w-0", children: [
158
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("h2", { className: "text-[18px] font-semibold text-black", children: "Calculations" }),
159
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "flex min-w-0 flex-row border-t border-gray-300", children: [
160
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FormulaSheetSpacerCell, {}),
161
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FormulaSheetDescriptionCell, { children: "Description" }),
162
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FormulaSheetSymbolCell, { initColumn: true, children: "Symbol Name" }),
163
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FormulaSheetValueCell, { initColumn: true, children: "Value" }),
164
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FormulaSheetUnitCell, { initColumn: true, children: "Unit" }),
165
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FormulaSheetCommentCell, { children: "Comment" })
166
+ ] })
167
+ ] });
168
+
169
+ // src/formula-sheet/FormulaSheetItemIndex.tsx
170
+ var import_jsx_runtime8 = require("react/jsx-runtime");
171
+ var FormulaSheetItemIndex = ({
172
+ index
173
+ }) => {
174
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("span", { "data-formula-sheet-item-index": "true", className: "tabular-nums", children: [
175
+ index,
176
+ "."
177
+ ] });
178
+ };
179
+
180
+ // src/formula-sheet/FormulaSheetSectionRow.tsx
181
+ var import_jsx_runtime9 = require("react/jsx-runtime");
182
+ var FormulaSheetSectionRow = ({
183
+ sheetItemIndex,
184
+ item: section
185
+ }) => {
186
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "flex flex-col", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "block flex-1 border-t border-gray-300 px-[3mm] py-[5px] font-['Plus_Jakarta_Sans'] text-[13px] font-semibold text-black/80 min-md:px-0", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("span", { children: [
187
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FormulaSheetItemIndex, { index: sheetItemIndex }),
188
+ " ",
189
+ section.title || "Untitled Section"
190
+ ] }) }) });
191
+ };
192
+
193
+ // src/ascii-math/AsciiMathView.tsx
194
+ var import_core2 = require("@cs-object/core");
195
+
196
+ // src/ascii-math/NotationMathmlView.tsx
197
+ var import_core = require("@cs-object/core");
198
+
199
+ // src/mathml/constants.ts
200
+ var MATHML_FONT_SIZE = "15px";
201
+
202
+ // src/ascii-math/NotationMathmlView.tsx
203
+ var import_jsx_runtime10 = require("react/jsx-runtime");
204
+ var fenceCharacters = {
205
+ round: ["(", ")"],
206
+ square: ["[", "]"]
207
+ };
208
+ var flattenTransparentGroups = (expression) => expression.flatMap(
209
+ (node) => node.kind === "group" && node.fence === "none" ? flattenTransparentGroups(node.body) : [node]
210
+ );
211
+ var NotationMathmlView = (_a) => {
212
+ var _b = _a, {
213
+ expression,
214
+ identifierMathVariant
215
+ } = _b, mathProps = __objRest(_b, [
216
+ "expression",
217
+ "identifierMathVariant"
218
+ ]);
219
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mrow", __spreadProps(__spreadValues({}, mathProps), { children: flattenTransparentGroups(expression).map((node, index) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
220
+ NotationNodeMathmlView,
221
+ {
222
+ node,
223
+ identifierMathVariant
224
+ },
225
+ `${node.kind}-${index}`
226
+ )) }));
227
+ };
228
+ var NotationGroupMathmlView = ({
229
+ group,
230
+ identifierMathVariant
231
+ }) => {
232
+ if (group.fence === "none") {
233
+ const nodes = flattenTransparentGroups(group.body);
234
+ const onlyNode = nodes[0];
235
+ if (nodes.length === 1 && onlyNode !== void 0) {
236
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
237
+ NotationNodeMathmlView,
238
+ {
239
+ node: onlyNode,
240
+ identifierMathVariant
241
+ }
242
+ );
243
+ }
244
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
245
+ NotationMathmlView,
246
+ {
247
+ expression: group.body,
248
+ identifierMathVariant
249
+ }
250
+ );
251
+ }
252
+ const [opening, closing] = fenceCharacters[group.fence];
253
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("mrow", { children: [
254
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mo", { fence: "true", children: opening }),
255
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
256
+ NotationMathmlView,
257
+ {
258
+ expression: group.body,
259
+ identifierMathVariant
260
+ }
261
+ ),
262
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mo", { fence: "true", children: closing })
263
+ ] });
264
+ };
265
+ var NotationNodeMathmlView = ({
266
+ node,
267
+ identifierMathVariant
268
+ }) => {
269
+ const renderNode = (child) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
270
+ NotationNodeMathmlView,
271
+ {
272
+ node: child,
273
+ identifierMathVariant
274
+ }
275
+ );
276
+ switch (node.kind) {
277
+ case "identifier":
278
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mi", { mathvariant: identifierMathVariant, children: node.value });
279
+ case "number":
280
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mn", { children: node.value });
281
+ case "operator":
282
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mo", { children: node.value });
283
+ case "text":
284
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mtext", { children: node.value });
285
+ case "group":
286
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
287
+ NotationGroupMathmlView,
288
+ {
289
+ group: node,
290
+ identifierMathVariant
291
+ }
292
+ );
293
+ case "fraction":
294
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("mfrac", { children: [
295
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mstyle", { style: { fontSize: MATHML_FONT_SIZE }, children: renderNode(node.numerator) }),
296
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("mstyle", { style: { fontSize: MATHML_FONT_SIZE }, children: renderNode(node.denominator) })
297
+ ] });
298
+ case "subscript":
299
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("msub", { children: [
300
+ renderNode(node.base),
301
+ renderNode(node.subscript)
302
+ ] });
303
+ case "superscript":
304
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("msup", { children: [
305
+ renderNode(node.base),
306
+ renderNode(node.superscript)
307
+ ] });
308
+ case "subsup":
309
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("msubsup", { children: [
310
+ renderNode(node.base),
311
+ renderNode(node.subscript),
312
+ renderNode(node.superscript)
313
+ ] });
314
+ default:
315
+ return (0, import_core.assertNever)(node);
316
+ }
317
+ };
318
+
319
+ // src/ascii-math/AsciiMathView.tsx
320
+ var import_jsx_runtime11 = require("react/jsx-runtime");
321
+ var AsciiMathView = (_a) => {
322
+ var _b = _a, {
323
+ expression,
324
+ identifierMathVariant,
325
+ optional
326
+ } = _b, mathProps = __objRest(_b, [
327
+ "expression",
328
+ "identifierMathVariant",
329
+ "optional"
330
+ ]);
331
+ const parsed = (0, import_core2.parseNotation)(expression);
332
+ if (!parsed.ok) {
333
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("mi", __spreadProps(__spreadValues({ mathcolor: "red" }, mathProps), { children: optional && expression.length === 0 ? "" : "?" }));
334
+ }
335
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
336
+ NotationMathmlView,
337
+ __spreadValues({
338
+ expression: parsed.value,
339
+ identifierMathVariant
340
+ }, mathProps)
341
+ );
342
+ };
343
+
344
+ // src/mathml/props.ts
345
+ var defaultMathBlockProps = {
346
+ style: {
347
+ // fontFamily: 'Latin Modern Math',
348
+ fontSize: MATHML_FONT_SIZE,
349
+ display: "inline-flex",
350
+ flexWrap: "wrap",
351
+ rowGap: "15px",
352
+ borderWidth: "0px",
353
+ borderColor: "#FFFFFF",
354
+ mathStyle: "normal"
355
+ }
356
+ };
357
+
358
+ // src/mathml/GlyphMathBlock.tsx
359
+ var import_jsx_runtime12 = require("react/jsx-runtime");
360
+ var GlyphMathBlock = (_a) => {
361
+ var _b = _a, {
362
+ glyph,
363
+ mathProps
364
+ } = _b, props = __objRest(_b, [
365
+ "glyph",
366
+ "mathProps"
367
+ ]);
368
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("math", __spreadProps(__spreadValues(__spreadValues({}, defaultMathBlockProps), mathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(AsciiMathView, __spreadValues({ expression: glyph }, props)) }));
369
+ };
370
+
371
+ // src/mathml/UnitMathBlock.tsx
372
+ var import_jsx_runtime13 = require("react/jsx-runtime");
373
+ var UnitMathBlock = ({
374
+ unit,
375
+ mathProps,
376
+ optional
377
+ }) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("math", __spreadProps(__spreadValues(__spreadValues({}, defaultMathBlockProps), mathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
378
+ AsciiMathView,
379
+ {
380
+ expression: unit,
381
+ identifierMathVariant: "normal",
382
+ optional
383
+ }
384
+ ) }));
385
+
386
+ // src/formula-sheet/FormulaSheetSymbolRow.tsx
387
+ var import_core9 = require("@cs-object/core");
388
+
389
+ // src/formula-sheet/FormulaSheetResultCell.tsx
390
+ var import_core3 = require("@cs-object/core");
391
+ var import_jsx_runtime14 = require("react/jsx-runtime");
392
+ var FormulaSheetResultCell = ({
393
+ literal
394
+ }) => {
395
+ const formattedValue = (0, import_core3.sheetLiteralToDisplayString)(literal);
396
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(FormulaSheetValueCell, { children: (0, import_core3.isSheetLiteralEmpty)(literal) ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { className: "rounded-sm bg-orange-500 px-1.5 py-0 text-black opacity-70", children: "NaN" }) : formattedValue });
397
+ };
398
+
399
+ // src/formula-sheet/FormulaSheetValueTree.tsx
400
+ var import_core8 = require("@cs-object/core");
401
+
402
+ // src/mathml/symbol-value/ValueTreeMathmlRenderer.tsx
403
+ var import_core7 = require("@cs-object/core");
404
+
405
+ // src/mathml/function-renderers.tsx
406
+ var import_jsx_runtime15 = require("react/jsx-runtime");
407
+ var baseStyle = { fontSize: MATHML_FONT_SIZE, textAlign: "left" };
408
+ var fontSizeStyle = { fontSize: MATHML_FONT_SIZE };
409
+ var ConditionalFunctionMathml = ({
410
+ argCnd,
411
+ argTrue,
412
+ argFalse
413
+ }) => {
414
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mrow", { style: baseStyle, children: [
415
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mo", { style: fontSizeStyle, children: "{" }),
416
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mtable", { columnalign: "left", style: baseStyle, children: [
417
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mtr", { style: fontSizeStyle, children: [
418
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mtd", { style: __spreadProps(__spreadValues({}, baseStyle), { paddingRight: "0.5em" }), children: argTrue }),
419
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mtd", { style: baseStyle, children: [
420
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mtext", { style: fontSizeStyle, children: "if " }),
421
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mspace", { width: "5px" }),
422
+ argCnd
423
+ ] })
424
+ ] }),
425
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mtr", { style: fontSizeStyle, children: [
426
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mtd", { style: __spreadProps(__spreadValues({}, baseStyle), { paddingRight: "0.5em" }), children: argFalse }),
427
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mtd", { style: baseStyle, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mtext", { style: fontSizeStyle, children: "otherwise." }) })
428
+ ] })
429
+ ] })
430
+ ] });
431
+ };
432
+ var FractionFunctionMathml = ({
433
+ numerator,
434
+ denominator
435
+ }) => {
436
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mfrac", { children: [
437
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mstyle", { style: { fontSize: MATHML_FONT_SIZE }, children: numerator }),
438
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mstyle", { style: { fontSize: MATHML_FONT_SIZE }, children: denominator })
439
+ ] });
440
+ };
441
+ var PowerFunctionMathml = ({
442
+ base,
443
+ exponent
444
+ }) => {
445
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("msup", { children: [
446
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mstyle", { style: { fontSize: MATHML_FONT_SIZE }, children: base }),
447
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mstyle", { style: { scale: "0.8" }, children: exponent })
448
+ ] });
449
+ };
450
+ var SquareRootFunctionMathml = ({
451
+ value
452
+ }) => {
453
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("msqrt", { children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mstyle", { style: { padding: "3px", fontSize: MATHML_FONT_SIZE }, children: value }) });
454
+ };
455
+ var AbsoluteValueFunctionMathml = ({
456
+ value
457
+ }) => {
458
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mrow", { style: fontSizeStyle, children: [
459
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mo", { fence: "true", stretchy: "true", children: "|" }),
460
+ value,
461
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mo", { fence: "true", stretchy: "true", children: "|" })
462
+ ] });
463
+ };
464
+ var UnaryMinusFunctionMathml = ({
465
+ value
466
+ }) => {
467
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("mrow", { style: { fontSize: MATHML_FONT_SIZE }, children: [
468
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("mo", { style: { fontSize: MATHML_FONT_SIZE }, children: "-" }),
469
+ value
470
+ ] });
471
+ };
472
+ var renderSpecialValueFunction = ({
473
+ functionId,
474
+ argReactNodes
475
+ }) => {
476
+ if (functionId === "fg.abs" && argReactNodes.length === 1) {
477
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(AbsoluteValueFunctionMathml, { value: argReactNodes[0] });
478
+ }
479
+ if (functionId === "fg.sqrt" && argReactNodes.length === 1) {
480
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(SquareRootFunctionMathml, { value: argReactNodes[0] });
481
+ }
482
+ if (functionId === "fg.uminus" && argReactNodes.length === 1) {
483
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(UnaryMinusFunctionMathml, { value: argReactNodes[0] });
484
+ }
485
+ if (functionId === "fg.cnd" && argReactNodes.length === 3) {
486
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
487
+ ConditionalFunctionMathml,
488
+ {
489
+ argCnd: argReactNodes[0],
490
+ argTrue: argReactNodes[1],
491
+ argFalse: argReactNodes[2]
492
+ }
493
+ );
494
+ }
495
+ if (functionId === "fg.divide" && argReactNodes.length === 2) {
496
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
497
+ FractionFunctionMathml,
498
+ {
499
+ numerator: argReactNodes[0],
500
+ denominator: argReactNodes[1]
501
+ }
502
+ );
503
+ }
504
+ if (functionId === "fg.pow" && argReactNodes.length === 2) {
505
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
506
+ PowerFunctionMathml,
507
+ {
508
+ base: argReactNodes[0],
509
+ exponent: argReactNodes[1]
510
+ }
511
+ );
512
+ }
513
+ return void 0;
514
+ };
515
+
516
+ // src/mathml/symbol-value/components.tsx
517
+ var import_core4 = require("@cs-object/core");
518
+ var import_react = require("react");
519
+ var import_jsx_runtime16 = require("react/jsx-runtime");
520
+ var isDraftPositionValid = ({
521
+ draft,
522
+ position
523
+ }) => {
524
+ return !Number.isNaN(position) && position >= 0 && position <= draft.length;
525
+ };
526
+ var stableReactNodeKey = (node) => {
527
+ var _a, _b;
528
+ if (node === null) {
529
+ return "null";
530
+ }
531
+ if (node === void 0) {
532
+ return "undefined";
533
+ }
534
+ if (typeof node === "string" || typeof node === "number") {
535
+ return String(node);
536
+ }
537
+ if (typeof node === "boolean") {
538
+ return node ? "true" : "false";
539
+ }
540
+ if ((0, import_react.isValidElement)(node)) {
541
+ if (node.key != null) {
542
+ return String(node.key);
543
+ }
544
+ if (typeof node.type === "string") {
545
+ return node.type;
546
+ }
547
+ const maybeNamed = node.type;
548
+ return (_b = (_a = maybeNamed.displayName) != null ? _a : maybeNamed.name) != null ? _b : "component";
549
+ }
550
+ return "node";
551
+ };
552
+ var SymbolValueRootMathmlView = ({
553
+ children
554
+ }) => {
555
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("math", { children: children != null ? children : "Tree Without Root" });
556
+ };
557
+ var SymbolValueDraftMathmlView = ({
558
+ draft,
559
+ position
560
+ }) => {
561
+ const textStyle = { fontSize: MATHML_FONT_SIZE };
562
+ return position !== void 0 && isDraftPositionValid({ draft, position }) ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)("mrow", { style: { fontSize: MATHML_FONT_SIZE }, children: [
563
+ position > 0 && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mtext", { style: textStyle, children: draft.substring(0, position) }),
564
+ position < draft.length && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mtext", { style: textStyle, children: draft.substring(position) })
565
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mrow", { style: { fontSize: MATHML_FONT_SIZE }, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mtext", { style: textStyle, children: draft }) });
566
+ };
567
+ var SymbolValueLiteralMathmlView = ({
568
+ literal
569
+ }) => {
570
+ const mathProps = {
571
+ style: { fontSize: MATHML_FONT_SIZE }
572
+ };
573
+ switch (literal == null ? void 0 : literal.kind) {
574
+ case void 0:
575
+ case "empty":
576
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mi", __spreadProps(__spreadValues({}, mathProps), { children: "\u25A2" }));
577
+ case "boolean":
578
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mi", __spreadProps(__spreadValues({}, mathProps), { children: literal.value ? "true" : "false" }));
579
+ case "number":
580
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mn", __spreadProps(__spreadValues({}, mathProps), { children: (0, import_core4.formatNumerical)(literal.value) }));
581
+ case "string":
582
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mtext", __spreadProps(__spreadValues({}, mathProps), { children: literal.value }));
583
+ default:
584
+ return (0, import_core4.assertNever)(literal);
585
+ }
586
+ };
587
+ var SymbolValueGlyphMathmlView = ({
588
+ glyph
589
+ }) => {
590
+ const mathProps = {};
591
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(AsciiMathView, __spreadValues({ expression: glyph }, mathProps));
592
+ };
593
+ var SymbolValueGroupMathmlView = ({
594
+ prefix,
595
+ children,
596
+ cursor,
597
+ empty = "omit"
598
+ }) => {
599
+ const mathProps = {
600
+ mathbackground: cursor ? "lightgray" : void 0
601
+ };
602
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)("mrow", __spreadProps(__spreadValues({}, mathProps), { children: [
603
+ prefix,
604
+ (children.length > 0 || empty === "fence") && /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_jsx_runtime16.Fragment, { children: [
605
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mo", { fence: "true", children: "(" }),
606
+ children.flatMap((child, argIndex, arr) => {
607
+ const next = arr[argIndex + 1];
608
+ const separatorKey = `sep-${stableReactNodeKey(child)}-to-${stableReactNodeKey(next)}`;
609
+ return [
610
+ child,
611
+ ...argIndex < arr.length - 1 ? [
612
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mo", { separator: "true", children: "," }, separatorKey)
613
+ ] : []
614
+ ];
615
+ }),
616
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mo", { fence: "true", children: ")" })
617
+ ] })
618
+ ] }));
619
+ };
620
+ var SymbolValueBinaryOperatorMathmlView = ({
621
+ operator,
622
+ argLeft,
623
+ argRight
624
+ }) => {
625
+ const spacing = operator.id === "fg.and" || operator.id === "fg.or" ? "0.3em" : void 0;
626
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)("mrow", { children: [
627
+ argLeft,
628
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("mo", { lspace: spacing, rspace: spacing, children: operator.glyph }),
629
+ argRight
630
+ ] });
631
+ };
632
+
633
+ // src/mathml/symbol-value/literal-display.ts
634
+ var import_core5 = require("@cs-object/core");
635
+ var displayedLiteralDraft = ({
636
+ node,
637
+ literalsAsDrafts
638
+ }) => {
639
+ var _a;
640
+ return (literalsAsDrafts || (0, import_core5.isSheetLiteralEmpty)(node.value)) && ((_a = node.draft) != null ? _a : "").length > 0 ? node.draft : void 0;
641
+ };
642
+
643
+ // src/mathml/symbol-value/operand-grouping.ts
644
+ var import_core6 = require("@cs-object/core");
645
+ var requiresExplicitOperandGroup = ({
646
+ sheet,
647
+ node,
648
+ numerical,
649
+ literalsAsDrafts,
650
+ parentFunctionId,
651
+ argumentIndex
652
+ }) => {
653
+ var _a;
654
+ let literal;
655
+ let draft;
656
+ switch (node.kind) {
657
+ case "literal":
658
+ draft = displayedLiteralDraft({ node, literalsAsDrafts });
659
+ literal = node.value;
660
+ break;
661
+ case "symbol":
662
+ literal = numerical ? (_a = (0, import_core6.getSymbolById)(sheet, node.symbolId)) == null ? void 0 : _a.valueTree.result : void 0;
663
+ break;
664
+ case "function":
665
+ break;
666
+ default: {
667
+ const exhaustive = node;
668
+ return exhaustive;
669
+ }
670
+ }
671
+ const negative = draft !== void 0 ? /^\s*[-−]/u.test(draft) : (literal == null ? void 0 : literal.kind) === "number" && (literal.value < 0 || Object.is(literal.value, -0));
672
+ return argumentIndex === 0 && (parentFunctionId === "fg.pow" && (node.kind === "function" || negative) || parentFunctionId === "fg.uminus" && node.kind === "function") || argumentIndex === 1 && (parentFunctionId === "fg.add" || parentFunctionId === "fg.multiply" || parentFunctionId === "fg.subtract") && (negative || node.kind === "function" && node.functionId === "fg.uminus");
673
+ };
674
+
675
+ // src/mathml/symbol-value/ValueTreeMathmlRenderer.tsx
676
+ var import_jsx_runtime17 = require("react/jsx-runtime");
677
+ var ValueTreeMathmlRenderer = ({
678
+ sheet,
679
+ valueTree,
680
+ viewOptions,
681
+ noRootContainer
682
+ }) => {
683
+ const rootNode = (0, import_core7.getValueNodeByKeyOrUndefined)(valueTree, valueTree.rootKey);
684
+ if (!rootNode) {
685
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_jsx_runtime17.Fragment, { children: "Empty Value" });
686
+ }
687
+ const rootValue = /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
688
+ ValueTreeNodeMathmlView,
689
+ {
690
+ sheet,
691
+ valueTree,
692
+ node: rootNode,
693
+ viewOptions
694
+ }
695
+ );
696
+ return noRootContainer ? rootValue : /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueRootMathmlView, { children: rootValue });
697
+ };
698
+ var ValueTreeNodeMathmlView = ({
699
+ sheet,
700
+ valueTree,
701
+ node,
702
+ viewOptions
703
+ }) => {
704
+ var _a;
705
+ if (node.kind === "literal") {
706
+ const draft = displayedLiteralDraft({
707
+ node,
708
+ literalsAsDrafts: viewOptions.literalsAsDrafts
709
+ });
710
+ if (draft !== void 0) {
711
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueDraftMathmlView, { draft });
712
+ }
713
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueLiteralMathmlView, { literal: node.value });
714
+ }
715
+ if (node.kind === "symbol") {
716
+ const nodeSymbol = (0, import_core7.getSymbolById)(sheet, node.symbolId);
717
+ if (!viewOptions.numerical) {
718
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueGlyphMathmlView, { glyph: (nodeSymbol == null ? void 0 : nodeSymbol.glyph) || "" });
719
+ }
720
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
721
+ SymbolValueLiteralMathmlView,
722
+ {
723
+ literal: (_a = nodeSymbol == null ? void 0 : nodeSymbol.valueTree.result) != null ? _a : (0, import_core7.emptyLiteral)()
724
+ }
725
+ );
726
+ }
727
+ if (node.kind === "function") {
728
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
729
+ ValueTreeFunctionMathmlView,
730
+ {
731
+ sheet,
732
+ valueTree,
733
+ node,
734
+ viewOptions
735
+ }
736
+ );
737
+ }
738
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_jsx_runtime17.Fragment, { children: "Error (Unknown value-tree node)" });
739
+ };
740
+ var ValueTreeFunctionMathmlView = ({
741
+ sheet,
742
+ valueTree,
743
+ node,
744
+ viewOptions
745
+ }) => {
746
+ if (node.kind !== "function") {
747
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_jsx_runtime17.Fragment, { children: "Error (Expected function value-tree node)" });
748
+ }
749
+ const argNodes = node.argKeys.map(
750
+ (argKey) => (0, import_core7.getValueNodeByKey)(valueTree, argKey)
751
+ );
752
+ const argReactNodes = argNodes.map((argNode, index) => {
753
+ const rendered = /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
754
+ ValueTreeNodeMathmlView,
755
+ {
756
+ sheet,
757
+ valueTree,
758
+ node: argNode,
759
+ viewOptions
760
+ },
761
+ argNode.key
762
+ );
763
+ const grouped = requiresExplicitOperandGroup({
764
+ sheet,
765
+ node: argNode,
766
+ numerical: Boolean(viewOptions.numerical),
767
+ literalsAsDrafts: Boolean(viewOptions.literalsAsDrafts),
768
+ parentFunctionId: node.functionId,
769
+ argumentIndex: index
770
+ });
771
+ return grouped ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueGroupMathmlView, { cursor: void 0, children: [rendered] }, argNode.key) : rendered;
772
+ });
773
+ const specialFunction = renderSpecialValueFunction({
774
+ functionId: node.functionId,
775
+ argReactNodes
776
+ });
777
+ if (specialFunction) {
778
+ return specialFunction;
779
+ }
780
+ const operator = (0, import_core7.getFunctionBinaryOperatorById)(node.functionId);
781
+ if (operator && argNodes.length > 2 && (node.functionId === "fg.and" || node.functionId === "fg.or")) {
782
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("mrow", { children: argReactNodes.map((argument, index) => {
783
+ const child = argNodes[index];
784
+ const childOperator = child.kind === "function" ? (0, import_core7.getFunctionBinaryOperatorById)(child.functionId) : void 0;
785
+ const grouped = childOperator !== void 0 && childOperator.priority < operator.priority;
786
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("mrow", { children: [
787
+ index > 0 && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("mo", { form: "infix", lspace: "0.3em", rspace: "0.3em", children: operator.glyph }),
788
+ grouped ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueGroupMathmlView, { cursor: void 0, children: [argument] }) : argument
789
+ ] }, child.key);
790
+ }) });
791
+ }
792
+ if (operator && argNodes.length === 2) {
793
+ const [argOperatorLeft, argOperatorRight] = argNodes.map(
794
+ (argNode) => argNode.kind === "function" ? (0, import_core7.getFunctionBinaryOperatorById)(argNode.functionId) : void 0
795
+ );
796
+ const implicitParenthesisLeft = argOperatorLeft && argOperatorLeft.priority < operator.priority;
797
+ const implicitParenthesisRight = argOperatorRight && argOperatorRight.priority <= operator.priority;
798
+ const argLeft = implicitParenthesisLeft ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueGroupMathmlView, { cursor: void 0, children: [argReactNodes[0]] }) : argReactNodes[0];
799
+ const argRight = implicitParenthesisRight ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueGroupMathmlView, { cursor: void 0, children: [argReactNodes[1]] }) : argReactNodes[1];
800
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
801
+ SymbolValueBinaryOperatorMathmlView,
802
+ {
803
+ operator,
804
+ argLeft,
805
+ argRight
806
+ }
807
+ );
808
+ }
809
+ const nodeFunction = (0, import_core7.getFunctionSpec)(node.functionId);
810
+ const functionNameGlyph = (nodeFunction == null ? void 0 : nodeFunction.glyph) || "";
811
+ const groupPrefix = node.functionId === "fg.noop" ? "" : node.functionId === "fg.stub" ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueDraftMathmlView, { draft: "" }) : /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(SymbolValueGlyphMathmlView, { glyph: functionNameGlyph });
812
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
813
+ SymbolValueGroupMathmlView,
814
+ {
815
+ prefix: groupPrefix,
816
+ cursor: void 0,
817
+ empty: node.functionId === "fg.pi" || node.functionId === "fg.noop" || node.functionId === "fg.stub" ? "omit" : "fence",
818
+ children: node.argKeys.map((key) => (0, import_core7.getValueNodeByKey)(valueTree, key)).map((argNode) => /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
819
+ ValueTreeNodeMathmlView,
820
+ {
821
+ sheet,
822
+ valueTree,
823
+ node: argNode,
824
+ viewOptions
825
+ },
826
+ `${argNode.key}`
827
+ ))
828
+ }
829
+ );
830
+ };
831
+
832
+ // src/mathml/symbol-value/SymbolValueMathmlView.tsx
833
+ var import_jsx_runtime18 = require("react/jsx-runtime");
834
+ var SymbolValueMathmlView = ({
835
+ sheet,
836
+ valueTree,
837
+ viewOptions,
838
+ noRootContainer
839
+ }) => {
840
+ return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
841
+ ValueTreeMathmlRenderer,
842
+ {
843
+ sheet,
844
+ valueTree,
845
+ viewOptions,
846
+ noRootContainer
847
+ }
848
+ );
849
+ };
850
+
851
+ // src/mathml/SymbolValueMathBlock.tsx
852
+ var import_jsx_runtime19 = require("react/jsx-runtime");
853
+ var SymbolValueMathBlock = ({
854
+ sheet,
855
+ symbol,
856
+ mathProps,
857
+ showGlyph,
858
+ showSymbolic,
859
+ showNumeric
860
+ }) => {
861
+ var _a, _b;
862
+ const baseMathProps = __spreadProps(__spreadValues(__spreadValues({}, defaultMathBlockProps), mathProps), {
863
+ // Use MathML display attribute (not CSS) for cross-browser compatibility
864
+ display: "inline",
865
+ style: __spreadProps(__spreadValues(__spreadValues({}, defaultMathBlockProps.style), mathProps == null ? void 0 : mathProps.style), {
866
+ // Remove CSS display since we're using MathML display attribute
867
+ display: void 0,
868
+ fontSize: ((_a = defaultMathBlockProps.style) == null ? void 0 : _a.fontSize) || ((_b = mathProps == null ? void 0 : mathProps.style) == null ? void 0 : _b.fontSize) || MATHML_FONT_SIZE
869
+ })
870
+ });
871
+ const divProps = {
872
+ style: {
873
+ display: "inline-flex",
874
+ alignItems: "flex-start",
875
+ margin: "5px 0px",
876
+ minWidth: "0",
877
+ flexShrink: "0"
878
+ }
879
+ };
880
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { children: [
881
+ showGlyph && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("div", __spreadProps(__spreadValues({}, divProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("math", __spreadProps(__spreadValues({}, baseMathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mrow", { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(AsciiMathView, { expression: symbol.glyph }) }) })) })),
882
+ showSymbolic && showGlyph && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("div", __spreadProps(__spreadValues({}, divProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("math", __spreadProps(__spreadValues({}, baseMathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mrow", { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mo", { className: "px-1 py-2", children: "=" }) }) })) })),
883
+ showSymbolic && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("div", __spreadProps(__spreadValues({}, divProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("math", __spreadProps(__spreadValues({}, baseMathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mrow", { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
884
+ SymbolValueMathmlView,
885
+ {
886
+ sheet,
887
+ valueTree: symbol.valueTree,
888
+ noRootContainer: true,
889
+ viewOptions: { literalsAsDrafts: true }
890
+ }
891
+ ) }) })) })),
892
+ showNumeric && (showGlyph || showSymbolic) && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("div", __spreadProps(__spreadValues({}, divProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("math", __spreadProps(__spreadValues({}, baseMathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mrow", { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mo", { className: "px-1 py-2", children: "=" }) }) })) })),
893
+ showNumeric && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("div", __spreadProps(__spreadValues({}, divProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("math", __spreadProps(__spreadValues({}, baseMathProps), { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("mrow", { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
894
+ SymbolValueMathmlView,
895
+ {
896
+ sheet,
897
+ valueTree: symbol.valueTree,
898
+ noRootContainer: true,
899
+ viewOptions: { numerical: true, literalsAsDrafts: true }
900
+ }
901
+ ) }) })) }))
902
+ ] });
903
+ };
904
+
905
+ // src/formula-sheet/FormulaSheetValueTree.tsx
906
+ var import_jsx_runtime20 = require("react/jsx-runtime");
907
+ var additionTerms = (tree, key, ancestors = /* @__PURE__ */ new Set()) => {
908
+ if (ancestors.has(key)) {
909
+ throw new Error(`Recursive formula node '${key}'`);
910
+ }
911
+ const node = tree.nodes.find((node2) => node2.key === key);
912
+ if ((node == null ? void 0 : node.kind) !== "function" || node.functionId !== "fg.add" || node.argKeys.length !== 2) {
913
+ return [key];
914
+ }
915
+ const [left, right] = node.argKeys;
916
+ if (!(left && right)) {
917
+ return [key];
918
+ }
919
+ return [...additionTerms(tree, left, /* @__PURE__ */ new Set([...ancestors, key])), right];
920
+ };
921
+ var hasActiveSymbol = (tree) => {
922
+ const nodes = new Map(tree.nodes.map((node) => [node.key, node]));
923
+ const pending = [tree.rootKey];
924
+ const visited = /* @__PURE__ */ new Set();
925
+ while (pending.length > 0) {
926
+ const key = pending.pop();
927
+ if (key === void 0 || visited.has(key)) continue;
928
+ visited.add(key);
929
+ const node = nodes.get(key);
930
+ if ((node == null ? void 0 : node.kind) === "symbol") return true;
931
+ if ((node == null ? void 0 : node.kind) === "function") pending.push(...node.argKeys);
932
+ }
933
+ return false;
934
+ };
935
+ var FormulaSheetValueTree = ({
936
+ sheet,
937
+ symbol
938
+ }) => {
939
+ const showSymbolic = hasActiveSymbol(symbol.valueTree);
940
+ const terms = additionTerms(symbol.valueTree, symbol.valueTree.rootKey);
941
+ if (terms.length > 4) {
942
+ return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("div", { className: "cso-long-formula", children: (showSymbolic ? [false, true] : [true]).map((numerical) => (
943
+ // biome-ignore lint/a11y/useSemanticElements: This labels a formula group, not a fieldset of form controls.
944
+ /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
945
+ "div",
946
+ {
947
+ className: "cso-formula-terms",
948
+ role: "group",
949
+ "aria-label": numerical ? "Substitution" : "Formula",
950
+ children: terms.map((rootKey, index) => {
951
+ const node = symbol.valueTree.nodes.find(
952
+ (node2) => node2.key === rootKey
953
+ );
954
+ const operator = (node == null ? void 0 : node.kind) === "function" ? (0, import_core8.getFunctionBinaryOperatorById)(node.functionId) : void 0;
955
+ const grouped = operator !== void 0 && (operator.priority < import_core8.SheetOperatorPriority.AddSubtract || index > 0 && operator.priority === import_core8.SheetOperatorPriority.AddSubtract) || node !== void 0 && requiresExplicitOperandGroup({
956
+ sheet,
957
+ node,
958
+ numerical,
959
+ literalsAsDrafts: true,
960
+ parentFunctionId: "fg.add",
961
+ argumentIndex: index === 0 ? 0 : 1
962
+ });
963
+ return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("span", { className: "cso-formula-term", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)("math", { display: "inline", children: [
964
+ index === 0 && /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(AsciiMathView, { expression: symbol.glyph }),
965
+ /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("mo", { children: index === 0 ? "=" : "+" }),
966
+ grouped && /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("mo", { children: "(" }),
967
+ /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
968
+ SymbolValueMathmlView,
969
+ {
970
+ sheet,
971
+ valueTree: __spreadProps(__spreadValues({}, symbol.valueTree), { rootKey }),
972
+ noRootContainer: true,
973
+ viewOptions: { numerical, literalsAsDrafts: true }
974
+ }
975
+ ),
976
+ grouped && /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("mo", { children: ")" })
977
+ ] }) }, `${index}-${rootKey}`);
978
+ })
979
+ },
980
+ String(numerical)
981
+ )
982
+ )) });
983
+ }
984
+ return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
985
+ SymbolValueMathBlock,
986
+ {
987
+ sheet,
988
+ symbol,
989
+ showGlyph: true,
990
+ showSymbolic,
991
+ showNumeric: true
992
+ }
993
+ );
994
+ };
995
+
996
+ // src/formula-sheet/FormulaSheetSymbolRow.tsx
997
+ var import_jsx_runtime21 = require("react/jsx-runtime");
998
+ var FormulaSheetSymbolRow = ({
999
+ sheet,
1000
+ sheetItemIndex,
1001
+ item: symbol
1002
+ }) => {
1003
+ var _a, _b;
1004
+ const { glyph: symbolGlyph } = symbol;
1005
+ const symbolUnit = (_a = symbol.unit) != null ? _a : "";
1006
+ const symbolDescription = symbol.description;
1007
+ const symbolComment = (_b = symbol.comment) != null ? _b : "";
1008
+ const rootNode = (0, import_core9.getValueNodeByKey)(
1009
+ symbol.valueTree,
1010
+ symbol.valueTree.rootKey
1011
+ );
1012
+ const symbolIsSolidLiteral = rootNode.kind === "literal";
1013
+ return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "cso-symbol-row flex min-w-0 flex-col", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "min-w-0", children: [
1014
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "flex min-w-0 border-t border-gray-300", children: [
1015
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetSpacerCell, {}),
1016
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetDescriptionCell, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("span", { children: [
1017
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetItemIndex, { index: sheetItemIndex }),
1018
+ " ",
1019
+ symbolDescription
1020
+ ] }) }),
1021
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetSymbolCell, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
1022
+ GlyphMathBlock,
1023
+ {
1024
+ glyph: symbolGlyph,
1025
+ mathProps: { className: "shrink-0" }
1026
+ }
1027
+ ) }),
1028
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetResultCell, { literal: symbol.valueTree.result }),
1029
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetUnitCell, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(UnitMathBlock, { unit: symbolUnit, optional: true }) }),
1030
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetCommentCell, { children: symbolComment || " " })
1031
+ ] }),
1032
+ !symbolIsSolidLiteral && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "flex min-w-0", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "w-full min-w-0 overflow-visible border-t border-gray-300 text-[14px]", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "my-2 flex min-w-0", children: [
1033
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetSpacerCell, {}),
1034
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "min-w-0 max-w-full flex-1 overflow-visible", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(FormulaSheetValueTree, { sheet, symbol }) })
1035
+ ] }) }) })
1036
+ ] }) });
1037
+ };
1038
+
1039
+ // src/formula-sheet/FormulaSheetItem.tsx
1040
+ var import_jsx_runtime22 = require("react/jsx-runtime");
1041
+ var FormulaSheetItem = ({
1042
+ sheet,
1043
+ item,
1044
+ sheetItemIndex
1045
+ }) => {
1046
+ return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)("div", { className: "relative min-w-0", children: [
1047
+ item.kind === "section" && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
1048
+ FormulaSheetSectionRow,
1049
+ {
1050
+ sheet,
1051
+ sheetItemIndex,
1052
+ item: item.section
1053
+ }
1054
+ ),
1055
+ item.kind === "symbol" && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
1056
+ FormulaSheetSymbolRow,
1057
+ {
1058
+ sheet,
1059
+ sheetItemIndex,
1060
+ item: item.symbol
1061
+ }
1062
+ )
1063
+ ] });
1064
+ };
1065
+
1066
+ // src/FormulaSheet.tsx
1067
+ var import_core10 = require("@cs-object/core");
1068
+ var import_jsx_runtime23 = require("react/jsx-runtime");
1069
+ var getFormulaSheetItemKey = (item, sheetItemIndex) => `${sheetItemIndex}-${item.kind}-${item.kind === "section" ? item.section.id : item.symbol.id}`;
1070
+ var FormulaSheet = ({ sheet }) => {
1071
+ const sheetItems = (0, import_core10.getRootSectionItems)(sheet);
1072
+ return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(
1073
+ "article",
1074
+ {
1075
+ "data-formula-sheet": "true",
1076
+ className: "flex min-h-[297mm] w-[210mm] min-w-[210mm] max-w-none flex-col items-stretch border border-gray-300 bg-white p-[5mm] [&_*:focus-visible]:outline-hidden",
1077
+ children: [
1078
+ /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(FormulaSheetHeader, {}),
1079
+ sheetItems.map((item, sheetItemIndex) => /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
1080
+ FormulaSheetItem,
1081
+ {
1082
+ sheet,
1083
+ item,
1084
+ sheetItemIndex
1085
+ },
1086
+ getFormulaSheetItemKey(item, sheetItemIndex)
1087
+ ))
1088
+ ]
1089
+ }
1090
+ );
1091
+ };
1092
+
1093
+ // src/formula-sheet/print.ts
1094
+ var DEFAULT_FORMULA_SHEET_SELECTOR = "[data-formula-sheet]";
1095
+ var FORMULA_SHEET_PRINT_BODY_CLASS = "formula-sheet-printing";
1096
+ var FORMULA_SHEET_PRINT_ROOT_ATTRIBUTE = "data-formula-sheet-print-root";
1097
+ var PRINT_CLEANUP_DELAY_MS = 1e3;
1098
+ var IMAGE_PREPARATION_TIMEOUT_MS = 15e3;
1099
+ var getBrowserPrintGlobals = () => {
1100
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof window.print !== "function" || !document.body) {
1101
+ return void 0;
1102
+ }
1103
+ return { document, window };
1104
+ };
1105
+ var resolvePrintTarget = (document2, target) => {
1106
+ var _a, _b;
1107
+ if (typeof target === "string") {
1108
+ return (_a = document2.querySelector(target)) != null ? _a : void 0;
1109
+ }
1110
+ return (_b = target != null ? target : document2.querySelector(DEFAULT_FORMULA_SHEET_SELECTOR)) != null ? _b : void 0;
1111
+ };
1112
+ var printFormulaSheet = (options = {}) => {
1113
+ const browser = getBrowserPrintGlobals();
1114
+ if (!browser) {
1115
+ return false;
1116
+ }
1117
+ if (browser.document.querySelector(`[${FORMULA_SHEET_PRINT_ROOT_ATTRIBUTE}]`)) {
1118
+ return false;
1119
+ }
1120
+ const target = resolvePrintTarget(browser.document, options.target);
1121
+ if (!target) {
1122
+ return false;
1123
+ }
1124
+ const printRoot = browser.document.createElement("div");
1125
+ const printClone = target.cloneNode(true);
1126
+ const originalTitle = options.title === void 0 ? void 0 : browser.document.title;
1127
+ let cleanedUp = false;
1128
+ let cleanupTimeout;
1129
+ let preparationTimeout;
1130
+ const cleanup = () => {
1131
+ if (cleanedUp) {
1132
+ return;
1133
+ }
1134
+ cleanedUp = true;
1135
+ if (cleanupTimeout !== void 0) {
1136
+ browser.window.clearTimeout(cleanupTimeout);
1137
+ }
1138
+ if (preparationTimeout !== void 0) {
1139
+ browser.window.clearTimeout(preparationTimeout);
1140
+ }
1141
+ browser.window.removeEventListener("afterprint", cleanup);
1142
+ printRoot.remove();
1143
+ browser.document.body.classList.remove(FORMULA_SHEET_PRINT_BODY_CLASS);
1144
+ if (originalTitle !== void 0) {
1145
+ browser.document.title = originalTitle;
1146
+ }
1147
+ };
1148
+ printRoot.setAttribute(FORMULA_SHEET_PRINT_ROOT_ATTRIBUTE, "true");
1149
+ printRoot.appendChild(printClone);
1150
+ browser.document.body.appendChild(printRoot);
1151
+ browser.document.body.classList.add(FORMULA_SHEET_PRINT_BODY_CLASS);
1152
+ if (options.title !== void 0) {
1153
+ browser.document.title = options.title;
1154
+ }
1155
+ browser.window.addEventListener("afterprint", cleanup, { once: true });
1156
+ const printReady = () => {
1157
+ if (cleanedUp) {
1158
+ return;
1159
+ }
1160
+ if (preparationTimeout !== void 0) {
1161
+ browser.window.clearTimeout(preparationTimeout);
1162
+ }
1163
+ cleanupTimeout = browser.window.setTimeout(cleanup, PRINT_CLEANUP_DELAY_MS);
1164
+ try {
1165
+ browser.window.print();
1166
+ } catch (error) {
1167
+ cleanup();
1168
+ throw error;
1169
+ }
1170
+ };
1171
+ const images = Array.from(printClone.querySelectorAll("img"));
1172
+ if (images.length === 0) {
1173
+ printReady();
1174
+ } else {
1175
+ const preparationFailed = (error) => {
1176
+ var _a;
1177
+ if (cleanedUp) {
1178
+ return;
1179
+ }
1180
+ cleanup();
1181
+ (_a = options.onError) == null ? void 0 : _a.call(options, error);
1182
+ };
1183
+ preparationTimeout = browser.window.setTimeout(() => {
1184
+ preparationFailed(
1185
+ new Error("Image preparation timed out before printing.")
1186
+ );
1187
+ }, IMAGE_PREPARATION_TIMEOUT_MS);
1188
+ void Promise.all(
1189
+ images.map((image) => Promise.resolve().then(() => image.decode()))
1190
+ ).then(() => {
1191
+ var _a;
1192
+ try {
1193
+ printReady();
1194
+ } catch (error) {
1195
+ (_a = options.onError) == null ? void 0 : _a.call(options, error);
1196
+ }
1197
+ }, preparationFailed);
1198
+ }
1199
+ return true;
1200
+ };
1201
+
1202
+ // src/PreparedFormulaSheet.tsx
1203
+ var import_core11 = require("@cs-object/core");
1204
+
1205
+ // src/EngineeringMetadata.tsx
1206
+ var import_jsx_runtime24 = require("react/jsx-runtime");
1207
+ var ContextValue = ({
1208
+ value
1209
+ }) => {
1210
+ switch (value.kind) {
1211
+ case "text":
1212
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { "data-engineering-value": value.path, children: String(value.value) });
1213
+ case "math":
1214
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
1215
+ "span",
1216
+ {
1217
+ "data-engineering-value": value.path,
1218
+ "data-engineering-notation": "math",
1219
+ "data-engineering-source": value.value,
1220
+ children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(GlyphMathBlock, { glyph: value.value })
1221
+ }
1222
+ );
1223
+ case "list":
1224
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("ul", { children: value.items.map((item, index) => (
1225
+ // biome-ignore lint/suspicious/noArrayIndexKey: prepared order identifies repeated entries
1226
+ /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ContextValue, { value: item }) }, index)
1227
+ )) });
1228
+ case "record":
1229
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("dl", { children: value.entries.map((entry) => /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { children: [
1230
+ /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("dt", { children: entry.label }),
1231
+ /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("dd", { children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ContextValue, { value: entry.value }) })
1232
+ ] }, entry.label)) });
1233
+ default: {
1234
+ const exhaustive = value;
1235
+ return exhaustive;
1236
+ }
1237
+ }
1238
+ };
1239
+ var EngineeringMetadata = ({
1240
+ entries,
1241
+ subject
1242
+ }) => entries.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("dl", { className: "cso-engineering-context", children: entries.map(({ label, path, value }) => /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { "data-engineering-field": path, children: [
1243
+ /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("dt", { children: [
1244
+ subject && /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment, { children: [
1245
+ subject,
1246
+ ": "
1247
+ ] }),
1248
+ label
1249
+ ] }),
1250
+ /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("dd", { children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ContextValue, { value }) })
1251
+ ] }, path)) }) : null;
1252
+
1253
+ // src/PreparedFormulaSheet.tsx
1254
+ var import_jsx_runtime25 = require("react/jsx-runtime");
1255
+ var mathSheet = (document2) => (0, import_core11.createSheetFromCalculationSourceObject)(
1256
+ {
1257
+ schemaVersion: "1.0.0",
1258
+ title: document2.title,
1259
+ source: { id: "prepared-math", metadata: {} },
1260
+ rootSectionIds: document2.rootSectionIds,
1261
+ sections: document2.sections.map((section) => ({
1262
+ id: section.id,
1263
+ title: section.title,
1264
+ items: section.items.flatMap((item) => {
1265
+ if (item.kind === "section") {
1266
+ return [{ kind: "section", id: item.id }];
1267
+ }
1268
+ if (item.kind === "symbol") {
1269
+ return [{ kind: "symbol", symbol: item.symbol }];
1270
+ }
1271
+ if (item.kind === "symbolRef") {
1272
+ return [{ kind: "symbolRef", id: item.id }];
1273
+ }
1274
+ return [];
1275
+ })
1276
+ })),
1277
+ detachedItems: document2.detachedSymbols.map((symbol) => ({
1278
+ kind: "symbol",
1279
+ symbol
1280
+ }))
1281
+ },
1282
+ { id: "prepared-math", label: document2.title }
1283
+ ).sheet;
1284
+ var requiredItem = (items, id) => {
1285
+ const item = items.get(id);
1286
+ if (!item) {
1287
+ throw new Error(`Missing prepared item '${id}'`);
1288
+ }
1289
+ return item;
1290
+ };
1291
+ var PreparedFormulaSheet = ({
1292
+ document: input,
1293
+ showSourceDetails = true
1294
+ }) => {
1295
+ const document2 = import_core11.PreparedDocumentSchema.parse(input);
1296
+ const sheet = mathSheet(document2);
1297
+ const sections = new Map(
1298
+ document2.sections.map((section) => [section.id, section])
1299
+ );
1300
+ const assets = new Map(
1301
+ document2.assets.map((asset) => [asset.asset.id, asset])
1302
+ );
1303
+ const symbols = new Map(sheet.symbols.map((symbol) => [symbol.id, symbol]));
1304
+ let symbolIndex = 0;
1305
+ const renderSection = (section) => /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
1306
+ "section",
1307
+ {
1308
+ "data-section-id": section.id,
1309
+ className: "cso-section",
1310
+ children: [
1311
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
1312
+ "h2",
1313
+ {
1314
+ "data-source-placement": section.sourcePlacementId,
1315
+ className: "cso-section-heading",
1316
+ children: section.title
1317
+ }
1318
+ ),
1319
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(EngineeringMetadata, { entries: section.context }),
1320
+ section.items.map((item) => {
1321
+ switch (item.kind) {
1322
+ case "section": {
1323
+ const child = requiredItem(sections, item.id);
1324
+ return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
1325
+ "div",
1326
+ {
1327
+ "data-source-placement": item.sourcePlacementId,
1328
+ children: [
1329
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(EngineeringMetadata, { entries: item.context }),
1330
+ renderSection(child)
1331
+ ]
1332
+ },
1333
+ item.sourcePlacementId
1334
+ );
1335
+ }
1336
+ case "text": {
1337
+ return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
1338
+ "div",
1339
+ {
1340
+ "data-source-placement": item.sourcePlacementId,
1341
+ className: "cso-text",
1342
+ children: [
1343
+ item.text.content,
1344
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(EngineeringMetadata, { entries: item.context })
1345
+ ]
1346
+ },
1347
+ item.sourcePlacementId
1348
+ );
1349
+ }
1350
+ case "figure": {
1351
+ const asset = requiredItem(assets, item.figure.assetId);
1352
+ return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
1353
+ "figure",
1354
+ {
1355
+ "data-source-placement": item.sourcePlacementId,
1356
+ "data-asset-sha256": asset.asset.sha256,
1357
+ className: "cso-figure",
1358
+ children: [
1359
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
1360
+ "img",
1361
+ {
1362
+ src: asset.dataUrl,
1363
+ alt: item.figure.alt,
1364
+ style: item.figure.width === void 0 ? void 0 : { width: item.figure.width }
1365
+ }
1366
+ ),
1367
+ item.figure.caption && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("figcaption", { children: item.figure.caption }),
1368
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(EngineeringMetadata, { entries: item.context })
1369
+ ]
1370
+ },
1371
+ item.sourcePlacementId
1372
+ );
1373
+ }
1374
+ case "symbol":
1375
+ case "symbolRef": {
1376
+ const symbolId = item.kind === "symbol" ? item.symbol.id : item.id;
1377
+ const symbol = requiredItem(symbols, symbolId);
1378
+ const index = symbolIndex++;
1379
+ return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
1380
+ "div",
1381
+ {
1382
+ "data-source-placement": item.sourcePlacementId,
1383
+ "data-symbol-id": symbolId,
1384
+ className: "cso-symbol-placement",
1385
+ children: [
1386
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(EngineeringMetadata, { entries: item.context }),
1387
+ item.operands.map(({ symbolId: id, context }) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
1388
+ EngineeringMetadata,
1389
+ {
1390
+ entries: context,
1391
+ subject: /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(import_jsx_runtime25.Fragment, { children: [
1392
+ "Operand",
1393
+ " ",
1394
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
1395
+ GlyphMathBlock,
1396
+ {
1397
+ glyph: requiredItem(symbols, id).glyph
1398
+ }
1399
+ )
1400
+ ] })
1401
+ },
1402
+ id
1403
+ )),
1404
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
1405
+ FormulaSheetSymbolRow,
1406
+ {
1407
+ sheet,
1408
+ item: symbol,
1409
+ sheetItemIndex: index
1410
+ }
1411
+ )
1412
+ ]
1413
+ },
1414
+ item.sourcePlacementId
1415
+ );
1416
+ }
1417
+ default: {
1418
+ const exhaustive = item;
1419
+ return exhaustive;
1420
+ }
1421
+ }
1422
+ })
1423
+ ]
1424
+ },
1425
+ section.id
1426
+ );
1427
+ return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
1428
+ "article",
1429
+ {
1430
+ "data-formula-sheet": "true",
1431
+ "data-prepared-document": "true",
1432
+ className: "cso-document",
1433
+ children: [
1434
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("header", { className: "cso-document-header", children: [
1435
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("h1", { children: document2.title }),
1436
+ showSourceDetails && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("p", { children: document2.source.kind === "legacy" ? "Development preservation rendering. Numerical agreement has not been verified." : "Execution-bound document. Numerical verification is reported separately." }),
1437
+ showSourceDetails && document2.source.kind === "execution" && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("p", { children: [
1438
+ "Function ",
1439
+ document2.source.function,
1440
+ ". Inputs",
1441
+ " ",
1442
+ Object.entries(document2.source.resolvedInputs).map(
1443
+ ([key, value]) => `${key} = ${Object.is(value, -0) ? "-0" : value}`
1444
+ ).join(", "),
1445
+ "."
1446
+ ] })
1447
+ ] }),
1448
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(EngineeringMetadata, { entries: document2.context }),
1449
+ document2.rootSectionIds.map((id) => {
1450
+ const section = sections.get(id);
1451
+ if (!section) {
1452
+ throw new Error(`Missing prepared root '${id}'`);
1453
+ }
1454
+ return renderSection(section);
1455
+ })
1456
+ ]
1457
+ }
1458
+ );
1459
+ };
1460
+
1461
+ // src/prepare-document.ts
1462
+ var import_core13 = require("@cs-object/core");
1463
+
1464
+ // src/active-symbols.ts
1465
+ var activeSymbolIds = (initialIds, definitionsById) => {
1466
+ var _a;
1467
+ const reachableSymbolIds = new Set(initialIds);
1468
+ for (const id of reachableSymbolIds) {
1469
+ const symbol = definitionsById.get(id);
1470
+ if (!symbol) continue;
1471
+ const nodes = new Map(
1472
+ symbol.valueTree.nodes.map((node) => [node.key, node])
1473
+ );
1474
+ const pending = [symbol.valueTree.rootKey];
1475
+ const visited = /* @__PURE__ */ new Set();
1476
+ while (pending.length > 0) {
1477
+ const key = pending.pop();
1478
+ if (key === void 0 || visited.has(key)) continue;
1479
+ visited.add(key);
1480
+ const node = nodes.get(key);
1481
+ if ((node == null ? void 0 : node.mode) === "SYMBOL" && node.symbol) {
1482
+ reachableSymbolIds.add(node.symbol.id);
1483
+ } else if ((node == null ? void 0 : node.mode) === "FUNCTION") {
1484
+ pending.push(...((_a = node.funcArgs) != null ? _a : []).map((argument) => argument.key));
1485
+ }
1486
+ }
1487
+ }
1488
+ return reachableSymbolIds;
1489
+ };
1490
+
1491
+ // src/prepare-context.ts
1492
+ var import_core12 = require("@cs-object/core");
1493
+ var fields = /* @__PURE__ */ new Map([
1494
+ ["purpose", "Purpose"],
1495
+ ["explanation", "Explanation"],
1496
+ ["method", "Method"],
1497
+ ["criteria", "Criteria"],
1498
+ ["applicability", "Applicability"],
1499
+ ["tolerances", "Tolerances"],
1500
+ ["description", "Description"],
1501
+ ["assumptions", "Assumptions"],
1502
+ ["assumption", "Assumption"],
1503
+ ["designBasis", "Design basis"],
1504
+ ["limitations", "Limitations"],
1505
+ ["designStandard", "Design standard"],
1506
+ ["standard", "Standard"],
1507
+ ["references", "References"],
1508
+ ["reference", "Reference"],
1509
+ ["notes", "Notes"],
1510
+ ["note", "Note"],
1511
+ ["comment", "Comment"],
1512
+ ["credit", "Credit"],
1513
+ ["license", "License"]
1514
+ ]);
1515
+ var pointer = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
1516
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1517
+ var evidenceKeys = /* @__PURE__ */ new Set([
1518
+ "localId",
1519
+ "invocationId",
1520
+ "location",
1521
+ "key",
1522
+ "draft",
1523
+ "tags",
1524
+ "valueTree",
1525
+ "nodes",
1526
+ "rootKey",
1527
+ "funcSpec",
1528
+ "funcArgs",
1529
+ "owner",
1530
+ "acl",
1531
+ "canEdit",
1532
+ "canShare",
1533
+ "__typename",
1534
+ "__proto__",
1535
+ "constructor"
1536
+ ]);
1537
+ var evidenceRole = /audit|review|approv|checked|submission|verification|transport/i;
1538
+ var engineeringChild = (key) => !(evidenceKeys.has(key) || evidenceRole.test(key));
1539
+ var contextValue = (value, path) => {
1540
+ if (value === null || value === "") {
1541
+ return void 0;
1542
+ }
1543
+ if (Array.isArray(value)) {
1544
+ const items = value.flatMap((entry, index) => {
1545
+ const selected = contextValue(entry, `${path}/${index}`);
1546
+ return selected ? [selected] : [];
1547
+ });
1548
+ return items.length > 0 ? { kind: "list", items } : void 0;
1549
+ }
1550
+ if (typeof value === "object") {
1551
+ const entries = Object.entries(value).flatMap(([key, entry]) => {
1552
+ if (!engineeringChild(key)) {
1553
+ return [];
1554
+ }
1555
+ const selected = contextValue(entry, `${path}/${pointer(key)}`);
1556
+ return selected ? [{ label: key, value: selected }] : [];
1557
+ });
1558
+ return entries.length > 0 ? { kind: "record", entries } : void 0;
1559
+ }
1560
+ return { kind: "text", value, path };
1561
+ };
1562
+ var engineeringFields = (value, path) => {
1563
+ if (value === void 0) {
1564
+ return [];
1565
+ }
1566
+ const object = import_core12.HistoricalReviewSchema.shape.originalFields.parse(value);
1567
+ return Object.entries(object).flatMap(([key, value2]) => {
1568
+ const sourcePath = `${path}/${pointer(key)}`;
1569
+ if (key === "additionalFields" && record(value2)) {
1570
+ return engineeringFields(value2, sourcePath);
1571
+ }
1572
+ const label = fields.get(key);
1573
+ const selected = label ? contextValue(value2, sourcePath) : void 0;
1574
+ return label && selected ? [{ label, value: selected, path: sourcePath }] : [];
1575
+ });
1576
+ };
1577
+ var prepareDocumentContext = (document2) => {
1578
+ const definitions = new Map([
1579
+ ...document2.sections.flatMap(
1580
+ (section, sectionIndex) => section.items.flatMap(
1581
+ (item, itemIndex) => item.kind === "symbol" ? [
1582
+ [
1583
+ item.symbol.id,
1584
+ {
1585
+ symbol: item.symbol,
1586
+ path: `/sections/${sectionIndex}/items/${itemIndex}/symbol`
1587
+ }
1588
+ ]
1589
+ ] : []
1590
+ )
1591
+ ),
1592
+ ...document2.detachedSymbols.map(
1593
+ (symbol, index) => [symbol.id, { symbol, path: `/detachedSymbols/${index}` }]
1594
+ )
1595
+ ]);
1596
+ const placed = new Set(
1597
+ document2.sections.flatMap(
1598
+ (section) => section.items.flatMap(
1599
+ (item) => item.kind === "symbol" ? [item.symbol.id] : item.kind === "symbolRef" ? [item.id] : []
1600
+ )
1601
+ )
1602
+ );
1603
+ const symbols = new Map(
1604
+ [...definitions].map(([id, definition]) => [id, definition.symbol])
1605
+ );
1606
+ const symbolContext = (id) => {
1607
+ const definition = definitions.get(id);
1608
+ if (!definition) {
1609
+ throw new Error(`Missing prepared symbol '${id}'`);
1610
+ }
1611
+ return engineeringFields(
1612
+ definition.symbol.metadata,
1613
+ `${definition.path}/metadata`
1614
+ );
1615
+ };
1616
+ const operandContext = (symbolId) => {
1617
+ const definition = definitions.get(symbolId);
1618
+ if (!definition) {
1619
+ throw new Error(`Missing prepared operand '${symbolId}'`);
1620
+ }
1621
+ const context = ["description", "unit", "comment"].flatMap(
1622
+ (key) => {
1623
+ const value = definition.symbol[key];
1624
+ if (value === void 0 || value === "") {
1625
+ return [];
1626
+ }
1627
+ const path = `${definition.path}/${key}`;
1628
+ return key === "unit" ? [{ label: "Unit", path, value: { kind: "math", path, value } }] : engineeringFields({ [key]: value }, definition.path);
1629
+ }
1630
+ );
1631
+ return { symbolId, context: [...context, ...symbolContext(symbolId)] };
1632
+ };
1633
+ return __spreadProps(__spreadValues({}, document2), {
1634
+ context: engineeringFields(document2.sourceMetadata, "/sourceMetadata"),
1635
+ sections: document2.sections.map((section, sectionIndex) => __spreadProps(__spreadValues({}, section), {
1636
+ context: engineeringFields(
1637
+ section.metadata,
1638
+ `/sections/${sectionIndex}/metadata`
1639
+ ),
1640
+ items: section.items.map((item, itemIndex) => {
1641
+ const path = `/sections/${sectionIndex}/items/${itemIndex}/contextSource`;
1642
+ const context = [
1643
+ "metadata",
1644
+ "contentMetadata",
1645
+ "additionalFields"
1646
+ ].flatMap(
1647
+ (key) => {
1648
+ var _a;
1649
+ return engineeringFields((_a = item.contextSource) == null ? void 0 : _a[key], `${path}/${key}`);
1650
+ }
1651
+ );
1652
+ if (item.kind !== "symbol" && item.kind !== "symbolRef") {
1653
+ return __spreadProps(__spreadValues({}, item), { context });
1654
+ }
1655
+ const id = item.kind === "symbol" ? item.symbol.id : item.id;
1656
+ return __spreadProps(__spreadValues({}, item), {
1657
+ context: [...symbolContext(id), ...context],
1658
+ operands: [...activeSymbolIds([id], symbols)].filter((id2) => !placed.has(id2)).map(operandContext)
1659
+ });
1660
+ })
1661
+ }))
1662
+ });
1663
+ };
1664
+
1665
+ // src/prepare-document.ts
1666
+ var DocumentPreparationError = class extends Error {
1667
+ constructor(diagnostics) {
1668
+ super(diagnostics.map((diagnostic) => diagnostic.message).join("\n"));
1669
+ this.name = "DocumentPreparationError";
1670
+ this.diagnostics = diagnostics;
1671
+ }
1672
+ };
1673
+ function fail(code, message) {
1674
+ throw new DocumentPreparationError([{ code, message, stage: "document" }]);
1675
+ }
1676
+ var pointerKey = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
1677
+ var assertDocumentJson = (value, path, ancestors = /* @__PURE__ */ new Set()) => {
1678
+ if (value === null || typeof value === "string" || typeof value === "boolean")
1679
+ return;
1680
+ if (typeof value === "number" && Number.isFinite(value)) return;
1681
+ if (typeof value !== "object" || value === null || ancestors.has(value) || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).some(
1682
+ (key) => Object.prototype.propertyIsEnumerable.call(value, key)
1683
+ )) {
1684
+ fail(
1685
+ "NON_JSON_DOCUMENT_FIELD",
1686
+ `Document field '${path}' must contain finite JSON values without cycles or custom objects`
1687
+ );
1688
+ }
1689
+ ancestors.add(value);
1690
+ if (Array.isArray(value)) {
1691
+ if (Object.keys(value).length !== value.length)
1692
+ fail(
1693
+ "NON_JSON_DOCUMENT_FIELD",
1694
+ `Document array '${path}' must be dense and contain only indexed values`
1695
+ );
1696
+ for (let index = 0; index < value.length; index++)
1697
+ assertDocumentJson(value[index], `${path}/${index}`, ancestors);
1698
+ } else {
1699
+ for (const [key, entry] of Object.entries(value))
1700
+ assertDocumentJson(entry, `${path}/${pointerKey(key)}`, ancestors);
1701
+ }
1702
+ ancestors.delete(value);
1703
+ };
1704
+ var restoreContentFields = (cso, original) => __spreadProps(__spreadValues({}, cso), {
1705
+ sections: cso.sections.map((section, sectionIndex) => __spreadProps(__spreadValues({}, section), {
1706
+ items: section.items.map((item, index) => {
1707
+ var _a;
1708
+ const raw = (_a = original.sections[sectionIndex]) == null ? void 0 : _a.items[index];
1709
+ if (item.kind === "text" && (raw == null ? void 0 : raw.kind) === "text")
1710
+ return __spreadProps(__spreadValues({}, item), { text: __spreadValues(__spreadValues({}, item.text), raw.text) });
1711
+ if (item.kind === "figure" && (raw == null ? void 0 : raw.kind) === "figure")
1712
+ return __spreadProps(__spreadValues({}, item), { figure: __spreadValues(__spreadValues({}, item.figure), raw.figure) });
1713
+ return item;
1714
+ })
1715
+ }))
1716
+ });
1717
+ var parseContent = (schema, value) => {
1718
+ const parsed = schema.safeParse(value);
1719
+ if (!parsed.success) {
1720
+ throw new DocumentPreparationError(
1721
+ (0, import_core13.contractIssuesToDiagnostics)(parsed.error.issues).map((diagnostic) => __spreadProps(__spreadValues({}, diagnostic), {
1722
+ stage: "document"
1723
+ }))
1724
+ );
1725
+ }
1726
+ return parsed.data;
1727
+ };
1728
+ var parseHistoricalReview = (value) => {
1729
+ assertDocumentJson(value, "/historicalReview");
1730
+ return parseContent(import_core13.HistoricalReviewSchema, value);
1731
+ };
1732
+ var parseDocument = (candidate) => parseContent(import_core13.PreparedDocumentSchema, candidate);
1733
+ var reachableSections = (cso) => {
1734
+ const sections = new Map(
1735
+ cso.sections.map((section) => [section.id, section])
1736
+ );
1737
+ const visited = /* @__PURE__ */ new Set();
1738
+ const ordered = [];
1739
+ const visit = (id) => {
1740
+ if (visited.has(id)) {
1741
+ fail(
1742
+ "DUPLICATE_SECTION_PLACEMENT",
1743
+ `Section '${id}' is repeated or recursive`
1744
+ );
1745
+ }
1746
+ const section = sections.get(id);
1747
+ if (!section) {
1748
+ return fail("UNRESOLVED_DOCUMENT_SECTION", `Section '${id}' is missing`);
1749
+ }
1750
+ visited.add(id);
1751
+ ordered.push(section);
1752
+ for (const item of section.items) {
1753
+ if (item.kind === "section") {
1754
+ visit(item.id);
1755
+ }
1756
+ }
1757
+ };
1758
+ for (const id of cso.rootSectionIds) {
1759
+ visit(id);
1760
+ }
1761
+ return ordered;
1762
+ };
1763
+ var symbolDefinitions = (cso) => {
1764
+ var _a;
1765
+ return [
1766
+ ...cso.sections.flatMap(
1767
+ (section) => section.items.flatMap(
1768
+ (item) => item.kind === "symbol" ? [item.symbol] : []
1769
+ )
1770
+ ),
1771
+ ...((_a = cso.detachedItems) != null ? _a : []).flatMap(
1772
+ (item) => item.kind === "symbol" ? [item.symbol] : []
1773
+ )
1774
+ ];
1775
+ };
1776
+ var assertExtensionFields = (cso) => {
1777
+ var _a;
1778
+ const fields2 = (record2, names, path) => {
1779
+ for (const [key, value] of Object.entries(record2)) {
1780
+ if (names.includes(key))
1781
+ assertDocumentJson(value, `${path}/${pointerKey(key)}`);
1782
+ }
1783
+ };
1784
+ fields2(cso.source, ["metadata"], "/source");
1785
+ if (cso.source.origin)
1786
+ fields2(cso.source.origin, ["metadata"], "/source/origin");
1787
+ const contentFields = (item, path) => {
1788
+ fields2(item, ["metadata"], path);
1789
+ if (item.kind === "text" || item.kind === "figure") {
1790
+ const content = item.kind === "text" ? item.text : item.figure;
1791
+ if (content) assertDocumentJson(content, `${path}/${item.kind}`);
1792
+ }
1793
+ };
1794
+ cso.sections.forEach((section, index) => {
1795
+ const path = `/sections/${index}`;
1796
+ fields2(section, ["metadata"], path);
1797
+ section.items.forEach((item, itemIndex) => {
1798
+ const itemPath = `${path}/items/${itemIndex}`;
1799
+ contentFields(item, itemPath);
1800
+ });
1801
+ });
1802
+ (_a = cso.detachedItems) == null ? void 0 : _a.forEach((item, index) => {
1803
+ contentFields(item, `/detachedItems/${index}`);
1804
+ });
1805
+ symbolDefinitions(cso).forEach((symbol, index) => {
1806
+ const path = `/definitions/${index}`;
1807
+ fields2(symbol, ["aliases", "metadata"], path);
1808
+ fields2(symbol.valueTree, ["metadata"], `${path}/valueTree`);
1809
+ symbol.valueTree.nodes.forEach((node, nodeIndex) => {
1810
+ fields2(
1811
+ node,
1812
+ ["metadata", "tags"],
1813
+ `${path}/valueTree/nodes/${nodeIndex}`
1814
+ );
1815
+ });
1816
+ });
1817
+ };
1818
+ var placementId = (sectionId, index) => JSON.stringify([sectionId, index]);
1819
+ var itemFields = (item) => {
1820
+ var _a, _b, _c, _d, _e;
1821
+ if (item.kind === "text") {
1822
+ return {
1823
+ kind: item.kind,
1824
+ id: item.id,
1825
+ text: { content: (_a = item.text) == null ? void 0 : _a.content }
1826
+ };
1827
+ }
1828
+ if (item.kind === "figure") {
1829
+ return {
1830
+ kind: item.kind,
1831
+ id: item.id,
1832
+ figure: {
1833
+ assetId: (_b = item.figure) == null ? void 0 : _b.assetId,
1834
+ caption: (_c = item.figure) == null ? void 0 : _c.caption,
1835
+ alt: (_d = item.figure) == null ? void 0 : _d.alt,
1836
+ width: (_e = item.figure) == null ? void 0 : _e.width
1837
+ }
1838
+ };
1839
+ }
1840
+ const _f = item, { metadata: _ } = _f, fields2 = __objRest(_f, ["metadata"]);
1841
+ return __spreadValues(__spreadValues({}, fields2), item.kind === "symbol" || item.kind === "symbolRef" ? { operands: [] } : {});
1842
+ };
1843
+ var retainedMetadata = (metadata, executionContext) => {
1844
+ if (!metadata || !executionContext || Object.keys(metadata).length === 0)
1845
+ return metadata;
1846
+ const authored = Object.fromEntries(
1847
+ Object.entries(metadata).filter(
1848
+ ([key]) => !["localId", "invocationId", "location"].includes(key)
1849
+ )
1850
+ );
1851
+ return Object.keys(authored).length > 0 ? authored : void 0;
1852
+ };
1853
+ var symbolMetadataHistory = (cso, executionContext = false) => {
1854
+ const definitions = symbolDefinitions(cso);
1855
+ const definitionsById = new Map(
1856
+ definitions.map((symbol) => [symbol.id, symbol])
1857
+ );
1858
+ const placedSymbolIds = new Set(
1859
+ reachableSections(cso).flatMap(
1860
+ (section) => section.items.flatMap(
1861
+ (item) => item.kind === "symbol" ? [item.symbol.id] : item.kind === "symbolRef" ? [item.id] : []
1862
+ )
1863
+ )
1864
+ );
1865
+ const reachableSymbolIds = activeSymbolIds(placedSymbolIds, definitionsById);
1866
+ const historicalDefinitions = definitions.flatMap((symbol) => {
1867
+ var _a;
1868
+ if (!reachableSymbolIds.has(symbol.id)) return [];
1869
+ const metadata = retainedMetadata(symbol.metadata, executionContext);
1870
+ const additionalFields = Object.fromEntries(
1871
+ Object.entries(symbol).filter(
1872
+ ([key, value]) => (["glyphPlaintext", "aliases"].includes(key) || ["description", "unit", "comment"].includes(key) && (!placedSymbolIds.has(symbol.id) || value === "")) && value !== void 0
1873
+ )
1874
+ );
1875
+ const treeMetadata = retainedMetadata(
1876
+ symbol.valueTree.metadata,
1877
+ executionContext
1878
+ );
1879
+ const nodesByKey = new Map(
1880
+ symbol.valueTree.nodes.map((node) => [node.key, node])
1881
+ );
1882
+ const active = /* @__PURE__ */ new Set();
1883
+ const pending = [symbol.valueTree.rootKey];
1884
+ while (pending.length > 0) {
1885
+ const key = pending.pop();
1886
+ if (key === void 0 || active.has(key)) continue;
1887
+ active.add(key);
1888
+ const node = nodesByKey.get(key);
1889
+ if ((node == null ? void 0 : node.mode) === "FUNCTION")
1890
+ pending.push(...((_a = node.funcArgs) != null ? _a : []).map((arg) => arg.key));
1891
+ }
1892
+ const nodes = symbol.valueTree.nodes.flatMap((node) => {
1893
+ if (!active.has(node.key)) return [];
1894
+ const nodeMetadata = retainedMetadata(node.metadata, executionContext);
1895
+ const context2 = __spreadValues(__spreadValues(__spreadValues({}, node.draft !== void 0 ? { draft: node.draft } : {}), node.tags !== void 0 ? { tags: node.tags } : {}), nodeMetadata !== void 0 ? { metadata: nodeMetadata } : {});
1896
+ return Object.keys(context2).length > 0 ? [__spreadValues({ key: node.key }, context2)] : [];
1897
+ });
1898
+ const valueTree = __spreadValues(__spreadValues({}, treeMetadata !== void 0 ? { metadata: treeMetadata } : {}), nodes.length > 0 ? { nodes } : {});
1899
+ const context = __spreadValues(__spreadValues(__spreadValues({}, metadata !== void 0 ? { metadata } : {}), Object.keys(additionalFields).length > 0 ? { additionalFields } : {}), Object.keys(valueTree).length > 0 ? { valueTree } : {});
1900
+ return Object.keys(context).length > 0 ? [__spreadValues({ id: symbol.id, glyph: symbol.glyph }, context)] : [];
1901
+ });
1902
+ const symbolHistory = historicalDefinitions.filter(
1903
+ (symbol) => placedSymbolIds.has(symbol.id)
1904
+ );
1905
+ const referencedSymbolHistory = historicalDefinitions.filter(
1906
+ (symbol) => !placedSymbolIds.has(symbol.id)
1907
+ );
1908
+ return { definitions, symbolHistory, referencedSymbolHistory };
1909
+ };
1910
+ var consumedContentFields = (item, executionContext) => {
1911
+ if (item.kind === "text") return ["content", "metadata"];
1912
+ if (executionContext)
1913
+ return ["assetId", "caption", "alt", "width", "metadata"];
1914
+ return ["originalUrl", "width", "metadata"];
1915
+ };
1916
+ var retainItemContextSource = (item, executionContext = false) => {
1917
+ const metadata = retainedMetadata(item.metadata, executionContext);
1918
+ const content = item.kind === "text" ? item.text : item.kind === "figure" ? item.figure : void 0;
1919
+ const hasContentMetadata = content !== void 0 && Object.hasOwn(content, "metadata");
1920
+ const consumed = consumedContentFields(item, executionContext);
1921
+ const additionalFields = content ? Object.fromEntries(
1922
+ Object.entries(content).filter(([key]) => !consumed.includes(key))
1923
+ ) : {};
1924
+ if (metadata === void 0 && !hasContentMetadata && Object.keys(additionalFields).length === 0) {
1925
+ return void 0;
1926
+ }
1927
+ return __spreadValues(__spreadValues(__spreadValues({}, metadata !== void 0 ? { metadata } : {}), hasContentMetadata ? { contentMetadata: content == null ? void 0 : content.metadata } : {}), Object.keys(additionalFields).length > 0 ? { additionalFields } : {});
1928
+ };
1929
+ var itemMetadataHistory = (cso, executionContext = false) => reachableSections(cso).flatMap(
1930
+ (section) => section.items.flatMap((item, index) => {
1931
+ const contextSource = retainItemContextSource(item, executionContext);
1932
+ return contextSource ? [
1933
+ __spreadValues({
1934
+ id: item.kind === "symbol" ? item.symbol.id : item.id,
1935
+ kind: item.kind,
1936
+ sourcePlacementId: placementId(section.id, index)
1937
+ }, contextSource)
1938
+ ] : [];
1939
+ })
1940
+ );
1941
+ var resolveExecutionPlacementProvenance = (execution, item) => {
1942
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1943
+ const symbolId = item.kind === "symbol" ? item.symbol.id : item.kind === "symbolRef" ? item.id : void 0;
1944
+ const definition = execution.invocations.flatMap((invocation) => invocation.symbols).find((symbol) => symbol.symbolId === symbolId);
1945
+ const targetSection = item.kind === "section" ? execution.cso.sections.find((target) => target.id === item.id) : void 0;
1946
+ const targetInvocation = targetSection && execution.invocations.find(
1947
+ (invocation) => {
1948
+ var _a2;
1949
+ return invocation.id === ((_a2 = targetSection.metadata) == null ? void 0 : _a2.invocationId);
1950
+ }
1951
+ );
1952
+ const metadata = (_a = item.metadata) != null ? _a : item.kind === "symbol" ? item.symbol.metadata : void 0;
1953
+ const definitionInvocation = definition && execution.invocations.find(
1954
+ (invocation) => invocation.symbols.includes(definition)
1955
+ );
1956
+ const targetCallSite = targetInvocation && "callSite" in targetInvocation ? targetInvocation.callSite : void 0;
1957
+ const definitionLocation = item.kind === "symbol" ? definition == null ? void 0 : definition.definitionLocation : void 0;
1958
+ return {
1959
+ localId: (_d = (_c = (_b = targetSection == null ? void 0 : targetSection.metadata) == null ? void 0 : _b.localId) != null ? _c : definition == null ? void 0 : definition.localId) != null ? _d : metadata == null ? void 0 : metadata.localId,
1960
+ invocationId: (_g = (_f = (_e = targetSection == null ? void 0 : targetSection.metadata) == null ? void 0 : _e.invocationId) != null ? _f : definitionInvocation == null ? void 0 : definitionInvocation.id) != null ? _g : metadata == null ? void 0 : metadata.invocationId,
1961
+ location: (_i = (_h = metadata == null ? void 0 : metadata.location) != null ? _h : targetCallSite) != null ? _i : definitionLocation
1962
+ };
1963
+ };
1964
+ var prepareExecutionDocument = (options) => {
1965
+ var _a, _c;
1966
+ const execution = parseContent(import_core13.ExecutionPayloadSchema, options.execution);
1967
+ assertExtensionFields(options.execution.cso);
1968
+ for (const review of (_a = options.historicalReviews) != null ? _a : [])
1969
+ assertDocumentJson(review, "/historicalReview");
1970
+ const cso = restoreContentFields(execution.cso, options.execution.cso);
1971
+ if (Object.hasOwn(cso.source, "metadata"))
1972
+ assertDocumentJson(cso.source.metadata, "/source/metadata");
1973
+ const assets = options.assets.map(
1974
+ (asset) => parseContent(import_core13.ResolvedAssetSchema, asset)
1975
+ );
1976
+ for (const resolved of assets) {
1977
+ const declared = execution.assets.find(
1978
+ (asset) => asset.id === resolved.asset.id
1979
+ );
1980
+ if (!declared || JSON.stringify(import_core13.AssetRecordSchema.parse(declared)) !== JSON.stringify(resolved.asset)) {
1981
+ fail(
1982
+ "DOCUMENT_ASSET_BINDING_MISMATCH",
1983
+ `Captured asset '${resolved.asset.id}' differs from the execution asset record`
1984
+ );
1985
+ }
1986
+ }
1987
+ const sections = reachableSections(cso).map((section) => {
1988
+ var _a2, _b2, _c2;
1989
+ return {
1990
+ id: section.id,
1991
+ title: section.title,
1992
+ sourcePlacementId: placementId(section.id, "heading"),
1993
+ context: [],
1994
+ localId: (_a2 = section.metadata) == null ? void 0 : _a2.localId,
1995
+ invocationId: (_b2 = section.metadata) == null ? void 0 : _b2.invocationId,
1996
+ location: (_c2 = section.metadata) == null ? void 0 : _c2.location,
1997
+ metadata: retainedMetadata(section.metadata, true),
1998
+ items: section.items.map((item, index) => {
1999
+ return __spreadValues(__spreadProps(__spreadValues({}, itemFields(item)), {
2000
+ context: [],
2001
+ contextSource: retainItemContextSource(item, true),
2002
+ sourcePlacementId: placementId(section.id, index)
2003
+ }), resolveExecutionPlacementProvenance(execution, item));
2004
+ })
2005
+ };
2006
+ });
2007
+ const displayed = new Set(
2008
+ sections.flatMap(
2009
+ (section) => section.items.flatMap(
2010
+ (item) => item.kind === "symbol" ? [item.symbol.id] : []
2011
+ )
2012
+ )
2013
+ );
2014
+ const { definitions, symbolHistory, referencedSymbolHistory } = symbolMetadataHistory(cso, true);
2015
+ const itemHistory = itemMetadataHistory(cso, true);
2016
+ const contentHistory = itemHistory.filter(
2017
+ (item) => item.kind === "text" || item.kind === "figure"
2018
+ );
2019
+ const placementHistory = itemHistory.filter(
2020
+ (item) => item.kind !== "text" && item.kind !== "figure"
2021
+ );
2022
+ const _b = cso.source, { metadata: _sourceMetadata } = _b, sourceProvenance = __objRest(_b, ["metadata"]);
2023
+ const document2 = parseDocument({
2024
+ documentVersion: "2",
2025
+ context: [],
2026
+ source: __spreadValues({
2027
+ kind: "execution"
2028
+ }, (0, import_core13.executionBindingFrom)(execution)),
2029
+ sourceMetadata: cso.source.metadata,
2030
+ title: cso.title,
2031
+ rootSectionIds: cso.rootSectionIds,
2032
+ sections,
2033
+ detachedSymbols: definitions.filter((symbol) => !displayed.has(symbol.id)),
2034
+ assets,
2035
+ historicalReviews: [
2036
+ parseHistoricalReview({
2037
+ scope: "historical",
2038
+ originalSource: {
2039
+ id: execution.entry.moduleId,
2040
+ sha256: execution.entry.sourceHash,
2041
+ format: "CalculationSourceObject execution"
2042
+ },
2043
+ attribution: "Source provenance and authored metadata from the captured source. Review fields are historical and do not approve this execution or rendering.",
2044
+ originalFields: __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
2045
+ source: sourceProvenance
2046
+ }, (() => {
2047
+ const sections2 = reachableSections(cso).flatMap((section) => {
2048
+ const metadata = retainedMetadata(section.metadata, true);
2049
+ return metadata !== void 0 ? [{ id: section.id, title: section.title, metadata }] : [];
2050
+ });
2051
+ return sections2.length > 0 ? { sections: sections2 } : {};
2052
+ })()), symbolHistory.length > 0 ? { symbols: symbolHistory } : {}), referencedSymbolHistory.length > 0 ? { referencedSymbols: referencedSymbolHistory } : {}), contentHistory.length > 0 ? { content: contentHistory } : {}), placementHistory.length > 0 ? { placements: placementHistory } : {})
2053
+ }),
2054
+ ...(_c = options.historicalReviews) != null ? _c : []
2055
+ ]
2056
+ });
2057
+ return parseContent(import_core13.BoundPreparedDocumentSchema, {
2058
+ execution,
2059
+ document: prepareDocumentContext(document2)
2060
+ }).document;
2061
+ };
2062
+ var legacyFigure = (options, manifest, item, sourcePlacementId) => {
2063
+ var _a, _b, _c, _d, _e, _f;
2064
+ const entry = manifest.entries.find(
2065
+ (entry2) => entry2.originalFixtureSha256 === options.fixtureSha256 && entry2.figureId === item.id
2066
+ );
2067
+ if (!entry) {
2068
+ return fail(
2069
+ "UNRESOLVED_LEGACY_FIGURE",
2070
+ `Original figure '${item.id}' has no recovered asset mapping`
2071
+ );
2072
+ }
2073
+ if (((_a = item.figure) == null ? void 0 : _a.originalUrl) !== entry.originalUrl) {
2074
+ return fail(
2075
+ "LEGACY_FIGURE_URL_MISMATCH",
2076
+ `Figure '${item.id}' original URL differs from its manifest`
2077
+ );
2078
+ }
2079
+ const asset = options.assets.find(
2080
+ (resolved) => resolved.asset.sha256 === entry.contentSha256 && resolved.asset.path === entry.localPath
2081
+ );
2082
+ if (!asset) {
2083
+ return fail(
2084
+ "UNRESOLVED_DOCUMENT_ASSET",
2085
+ `Original figure '${item.id}' captured bytes are missing`
2086
+ );
2087
+ }
2088
+ return parseContent(import_core13.PreparedDocumentItemSchema, {
2089
+ kind: "figure",
2090
+ id: item.id,
2091
+ sourcePlacementId,
2092
+ context: [],
2093
+ contextSource: retainItemContextSource(item),
2094
+ figure: __spreadValues({
2095
+ assetId: asset.asset.id,
2096
+ caption: (_c = (_b = entry.additions) == null ? void 0 : _b.caption) != null ? _c : "",
2097
+ alt: (_e = (_d = entry.additions) == null ? void 0 : _d.alt) != null ? _e : ""
2098
+ }, ((_f = item.figure) == null ? void 0 : _f.width) !== void 0 ? { width: item.figure.width } : {})
2099
+ });
2100
+ };
2101
+ var prepareLegacyDocument = (options) => {
2102
+ var _a, _b, _c, _d;
2103
+ const cso = restoreContentFields(
2104
+ parseContent(import_core13.CalculationSourceObjectSchema, options.cso),
2105
+ options.cso
2106
+ );
2107
+ assertExtensionFields(options.cso);
2108
+ for (const review of (_a = options.historicalReviews) != null ? _a : [])
2109
+ assertDocumentJson(review, "/historicalReview");
2110
+ const manifest = parseContent(import_core13.LegacyAssetManifestSchema, options.manifest);
2111
+ const sections = reachableSections(cso).map(
2112
+ (section) => parseContent(import_core13.PreparedDocumentSectionSchema, {
2113
+ id: section.id,
2114
+ title: section.title,
2115
+ sourcePlacementId: placementId(section.id, "heading"),
2116
+ context: [],
2117
+ metadata: section.metadata,
2118
+ items: section.items.map((item, index) => {
2119
+ const sourcePlacementId = placementId(section.id, index);
2120
+ if (item.kind === "figure") {
2121
+ return legacyFigure(options, manifest, item, sourcePlacementId);
2122
+ }
2123
+ return parseContent(import_core13.PreparedDocumentItemSchema, __spreadProps(__spreadValues({}, itemFields(item)), {
2124
+ sourcePlacementId,
2125
+ context: [],
2126
+ contextSource: retainItemContextSource(item)
2127
+ }));
2128
+ })
2129
+ })
2130
+ );
2131
+ const displayed = new Set(
2132
+ sections.flatMap(
2133
+ (section) => section.items.flatMap(
2134
+ (item) => item.kind === "symbol" ? [item.symbol.id] : []
2135
+ )
2136
+ )
2137
+ );
2138
+ const { definitions, symbolHistory, referencedSymbolHistory } = symbolMetadataHistory(cso);
2139
+ const itemHistory = itemMetadataHistory(cso);
2140
+ const contentHistory = itemHistory.filter(
2141
+ (item) => item.kind === "text" || item.kind === "figure"
2142
+ );
2143
+ const placementHistory = itemHistory.filter(
2144
+ (item) => item.kind !== "text" && item.kind !== "figure"
2145
+ );
2146
+ const historical = parseHistoricalReview({
2147
+ scope: "historical",
2148
+ originalSource: {
2149
+ id: options.fixtureId,
2150
+ sha256: options.fixtureSha256,
2151
+ format: (_c = (_b = cso.source.origin) == null ? void 0 : _b.format) != null ? _c : "CalculationSourceObject"
2152
+ },
2153
+ attribution: "Historical source metadata. It does not approve this rendering or a current execution.",
2154
+ originalFields: __spreadValues(__spreadValues(__spreadValues(__spreadValues({
2155
+ source: cso.source,
2156
+ sections: reachableSections(cso).map(({ id, title, metadata }) => __spreadValues({
2157
+ id,
2158
+ title
2159
+ }, metadata ? { metadata } : {}))
2160
+ }, contentHistory.length > 0 ? { content: contentHistory } : {}), placementHistory.length > 0 ? { placements: placementHistory } : {}), symbolHistory.length > 0 ? { symbols: symbolHistory } : {}), referencedSymbolHistory.length > 0 ? { referencedSymbols: referencedSymbolHistory } : {})
2161
+ });
2162
+ const document2 = parseDocument({
2163
+ documentVersion: "2",
2164
+ context: [],
2165
+ source: {
2166
+ kind: "legacy",
2167
+ fixtureId: options.fixtureId,
2168
+ fixtureSha256: options.fixtureSha256
2169
+ },
2170
+ title: cso.title,
2171
+ sourceMetadata: cso.source.metadata,
2172
+ rootSectionIds: cso.rootSectionIds,
2173
+ sections,
2174
+ detachedSymbols: definitions.filter((symbol) => !displayed.has(symbol.id)),
2175
+ assets: options.assets,
2176
+ historicalReviews: [historical, ...(_d = options.historicalReviews) != null ? _d : []]
2177
+ });
2178
+ return parseDocument(prepareDocumentContext(document2));
2179
+ };
2180
+ // Annotate the CommonJS export names for ESM import in node:
2181
+ 0 && (module.exports = {
2182
+ AsciiMathView,
2183
+ DocumentPreparationError,
2184
+ FormulaSheet,
2185
+ PreparedFormulaSheet,
2186
+ prepareExecutionDocument,
2187
+ prepareLegacyDocument,
2188
+ printFormulaSheet
2189
+ });