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