@indispec/fs-compat 0.0.0-stage → 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.
@@ -0,0 +1,409 @@
1
+ // Feature-history projection.
2
+ //
3
+ // The interpreter records a flat execution trace (`trace.js`). A CAD editor shows a *tree*:
4
+ // one row per authored feature, with its fields, its source span and its children. This module
5
+ // turns the trace plus the AST into that tree, and it is the only place that decides what a
6
+ // row is — the UI renders rows, it never re-derives them.
7
+ //
8
+ // Rules that keep it honest (docs/CAD.md §7):
9
+ // - the tree is derived per evaluation; nothing here is persisted or synced;
10
+ // - a field is editable only when its source value is a literal or `literal * unit`, and the
11
+ // span of that literal is what an edit replaces — expressions are shown, not editable;
12
+ // - rows generated by loops or helper functions are marked so the UI cannot offer structural
13
+ // edits (reorder/delete) that the source cannot express;
14
+ // - assembly rows are projected from the recorded instance list, because an instance's
15
+ // transform is data the program computed, not a call argument.
16
+
17
+ import { classifyBuiltin } from './trace.js'
18
+
19
+ /** Human labels for history kinds. */
20
+ const KIND_LABELS = {
21
+ sketch: 'Sketch',
22
+ op: 'Feature',
23
+ modifier: 'Modify',
24
+ property: 'Property',
25
+ report: 'Report',
26
+ instance: 'Instance',
27
+ import: 'Import',
28
+ feature: 'Feature',
29
+ }
30
+
31
+ const STATEMENT_KINDS = new Set([
32
+ 'VarDecl', 'ConstDecl', 'ExprStmt', 'Assign', 'If', 'For', 'Return',
33
+ 'Block', 'FuncDecl', 'EnumDecl', 'Annotation', 'Skip',
34
+ ])
35
+
36
+ /**
37
+ * Walk every node of a parsed AST.
38
+ *
39
+ * @param {unknown} node AST node, array of nodes or plain value.
40
+ * @param {(node: {kind: string}) => void} visit Called for every node carrying a `kind`.
41
+ */
42
+ function walkAst(node, visit) {
43
+ if (!node || typeof node !== 'object') return
44
+ if (Array.isArray(node)) {
45
+ for (const item of node) walkAst(item, visit)
46
+ return
47
+ }
48
+ if (typeof node.kind === 'string') visit(node)
49
+ for (const key of Object.keys(node)) {
50
+ if (key === 'kind' || key === 'line' || key === 'start' || key === 'end') continue
51
+ const value = node[key]
52
+ if (value && typeof value === 'object') walkAst(value, visit)
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Index an AST for projection: call nodes by span start, and every statement span.
58
+ *
59
+ * @param {unknown[]} ast Parsed module.
60
+ * @returns {{ calls: Map<number, any>, statements: Array<{ start: number, end: number }> }}
61
+ */
62
+ function indexAst(ast) {
63
+ const calls = new Map()
64
+ const statements = []
65
+ walkAst(ast, (node) => {
66
+ if (node.kind === 'Call' && typeof node.start === 'number') calls.set(node.start, node)
67
+ if (STATEMENT_KINDS.has(node.kind) && typeof node.start === 'number') {
68
+ statements.push({ start: node.start, end: node.end })
69
+ }
70
+ })
71
+ return { calls, statements }
72
+ }
73
+
74
+ /**
75
+ * The narrowest statement containing a character offset.
76
+ *
77
+ * Structural edits (move/suppress) patch whole statements, so every row needs the statement
78
+ * it belongs to, not just the call expression.
79
+ *
80
+ * @param {Array<{ start: number, end: number }>} statements Statement spans.
81
+ * @param {{ start: number, end: number }} span Row span.
82
+ * @returns {{ start: number, end: number } | null} Enclosing statement, or null.
83
+ */
84
+ function enclosingStatement(statements, span) {
85
+ let best = null
86
+ for (const statement of statements) {
87
+ if (statement.start <= span.start && span.end <= statement.end) {
88
+ if (!best || statement.end - statement.start < best.end - best.start) best = statement
89
+ }
90
+ }
91
+ return best
92
+ }
93
+
94
+ /**
95
+ * Humanise a builtin/host operation name for the history tree.
96
+ *
97
+ * @param {string} op Operation name (`opExtrude`, `newSketchOnPlane`, `setProperty`, …).
98
+ * @returns {string} Display label.
99
+ */
100
+ export function humanizeOp(op) {
101
+ /** @type {Record<string, string>} */
102
+ const special = {
103
+ newSketchOnPlane: 'Sketch',
104
+ newSketch: 'Sketch',
105
+ skSolve: 'Solve sketch',
106
+ setProperty: 'Property',
107
+ opDeleteBodies: 'Delete bodies',
108
+ instance: 'Instance',
109
+ importStep: 'Import STEP',
110
+ importAsset: 'Import',
111
+ }
112
+ if (special[op]) return special[op]
113
+ const base = op.startsWith('op') ? op.slice(2) : op
114
+ const spaced = base.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
115
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
116
+ }
117
+
118
+ /**
119
+ * Describe one definition-map value by what the source can support.
120
+ *
121
+ * @param {{ kind: string, start?: number, end?: number, op?: string, l?: any, r?: any, e?: any }} node Value AST node.
122
+ * @param {string} source Source text the spans index into.
123
+ * @returns {{ kind: string, text: string, literal: { start: number, end: number } | null }}
124
+ * Field kind, display text, and the literal span an edit would replace.
125
+ */
126
+ function describeValue(node, source) {
127
+ if (!node) return { kind: 'unknown', text: '', literal: null }
128
+ const text = typeof node.start === 'number' && typeof node.end === 'number'
129
+ ? source.slice(node.start, node.end)
130
+ : ''
131
+ const literal = typeof node.start === 'number' ? { start: node.start, end: node.end } : null
132
+ if (node.kind === 'Num') return { kind: 'number', text, literal }
133
+ if (node.kind === 'Str') return { kind: 'text', text, literal: null }
134
+ if (node.kind === 'Bool') return { kind: 'boolean', text, literal: null }
135
+ if (node.kind === 'Un' && node.op === '-' && node.e?.kind === 'Num') {
136
+ return { kind: 'number', text, literal }
137
+ }
138
+ // `40 * millimeter` / `-3 * inch`: the traceable knob is the numeric literal.
139
+ if (node.kind === 'Bin' && node.op === '*' && node.l?.kind === 'Num' && node.r) {
140
+ return { kind: 'quantity', text, literal: { start: node.l.start, end: node.l.end } }
141
+ }
142
+ if (node.kind === 'Bin' && node.op === '*' && node.l?.kind === 'Un' && node.l.e?.kind === 'Num') {
143
+ return { kind: 'quantity', text, literal: { start: node.l.start, end: node.l.end } }
144
+ }
145
+ if (node.kind === 'Ident') return { kind: 'reference', text, literal: null }
146
+ if (node.kind === 'Member') return { kind: 'reference', text, literal: null }
147
+ if (node.kind === 'MapLit') return { kind: 'map', text, literal: null }
148
+ if (node.kind === 'ArrayLit') return { kind: 'list', text, literal: null }
149
+ if (node.kind === 'Call') return { kind: 'call', text, literal: null }
150
+ return { kind: 'expression', text, literal: null }
151
+ }
152
+
153
+ /**
154
+ * Fields of one call's definition map literal.
155
+ *
156
+ * @param {any} call AST `Call` node recorded for the row.
157
+ * @param {string} source Source text.
158
+ * @returns {Array<object>} Field descriptors for the inspector/form.
159
+ */
160
+ function fieldsOfCall(call, source) {
161
+ const definition = call?.args?.[2]
162
+ if (!definition || definition.kind !== 'MapLit') return []
163
+ return definition.pairs.map(([keyNode, valueNode]) => {
164
+ const key = keyNode?.kind === 'Str'
165
+ ? String(keyNode.value)
166
+ : keyNode?.kind === 'Ident'
167
+ ? keyNode.name
168
+ : (source.slice(keyNode?.start ?? 0, keyNode?.end ?? 0) || '(value)')
169
+ const described = describeValue(valueNode, source)
170
+ return {
171
+ key,
172
+ line: valueNode?.line ?? null,
173
+ value: described.text,
174
+ valueKind: described.kind,
175
+ /** Span an edit replaces, or null when the value is computed (not editable). */
176
+ literal: described.literal,
177
+ editable: described.literal !== null,
178
+ }
179
+ })
180
+ }
181
+
182
+ /**
183
+ * Project the flat trace into the feature-history tree the editor renders.
184
+ *
185
+ * @param {Array<any>} trace Trace entries from `runFeature(..., { trace: true })`.
186
+ * @param {object} [options]
187
+ * @param {unknown[]|null} [options.ast] Parsed module (needed for fields and statement spans).
188
+ * @param {string} [options.source] Source text the spans index into.
189
+ * @param {'feature'|'op'} [options.granularity] Group by authored feature (default) or show every op.
190
+ * @param {boolean} [options.includeReports] Include `reportFeature*` notes as rows.
191
+ * @param {boolean} [options.includeSketches] Include sketch creation as rows.
192
+ * @returns {Array<object>} History rows in execution order, with children.
193
+ */
194
+ export function projectFeatureList(trace, {
195
+ ast = null,
196
+ source = '',
197
+ granularity = 'feature',
198
+ includeReports = false,
199
+ includeSketches = true,
200
+ } = {}) {
201
+ const { calls, statements } = indexAst(ast ?? [])
202
+ /**
203
+ * Provenance per call site. A call node executed more than once is either a loop (same
204
+ * helper invocation re-running) or a helper called several times (different invocation).
205
+ * Both mean "generated", but only the loop case is reorder-able in the source.
206
+ */
207
+ const perCall = new Map()
208
+ for (const entry of trace) {
209
+ if (!entry.span) continue
210
+ const info = perCall.get(entry.span.start) ?? { count: 0, chains: new Set() }
211
+ info.count += 1
212
+ info.chains.add((entry.frames ?? []).map((frame) => frame.id ?? '?').join('>'))
213
+ perCall.set(entry.span.start, info)
214
+ }
215
+
216
+ /**
217
+ * One projected row for a trace entry.
218
+ *
219
+ * @param {any} entry Trace entry.
220
+ * @returns {object} Row without children.
221
+ */
222
+ const makeRow = (entry) => {
223
+ const call = calls.get(entry.span?.start ?? -1) ?? null
224
+ const statement = entry.span ? enclosingStatement(statements, entry.span) : null
225
+ const callInfo = entry.span ? perCall.get(entry.span.start) : null
226
+ const generatedBy = !callInfo || callInfo.count <= 1
227
+ ? null
228
+ : callInfo.chains.size === 1 ? 'loop' : 'repeat'
229
+ const path = entry.path ?? []
230
+ const row = {
231
+ /** Anchor identity: the runtime id path when the call had one. */
232
+ id: entry.id ?? `entry:${entry.seq}`,
233
+ seq: entry.seq,
234
+ kind: entry.kind,
235
+ kindLabel: KIND_LABELS[entry.kind] ?? entry.kind,
236
+ op: entry.op,
237
+ title: humanizeOp(entry.op),
238
+ /** Last id-path segment — the authored operation name (`ex`, `u1`, …). */
239
+ name: path.length ? path[path.length - 1] : null,
240
+ /** The helper invocation that owns this operation (`outer`, `o`, …), when there is one. */
241
+ owner: path.length >= 3 ? path[path.length - 2] : null,
242
+ path,
243
+ line: entry.span?.line ?? null,
244
+ span: entry.span ? { start: entry.span.start, end: entry.span.end } : null,
245
+ /** Whole-statement span for move/suppress patches; null when only the expression is known. */
246
+ statement: statement ? { start: statement.start, end: statement.end } : null,
247
+ /** Helper call frames that produced this row (outermost first). */
248
+ frames: (entry.frames ?? []).map((frame) => ({
249
+ callee: frame.callee,
250
+ id: frame.id,
251
+ line: frame.span?.line ?? null,
252
+ span: frame.span ? { start: frame.span.start, end: frame.span.end } : null,
253
+ })),
254
+ /** `loop`/`repeat`/`helper` when the row is generated rather than a direct unique call. */
255
+ generatedBy: generatedBy ?? ((entry.frames?.length ?? 0) > 0 ? 'helper' : null),
256
+ produced: entry.produced ?? 0,
257
+ bodies: entry.bodies ?? 0,
258
+ fields: fieldsOfCall(call, source),
259
+ children: [],
260
+ }
261
+ row.editable = row.fields.some((field) => field.editable)
262
+ // Structural edits patch the statement, so they survive repetition; reordering does not,
263
+ // because the statement is one authored line that expands to several features.
264
+ row.structural = row.statement !== null
265
+ row.reorderable = row.structural && row.generatedBy === null
266
+ return row
267
+ }
268
+
269
+ /** Units in execution order: one row, or a run of rows sharing a feature id. */
270
+ const units = []
271
+ for (const entry of trace) {
272
+ if (!includeReports && entry.kind === 'report') continue
273
+ if (!includeSketches && entry.kind === 'sketch') continue
274
+ const row = makeRow(entry)
275
+ const groupKey = granularity === 'op' || (entry.path?.length ?? 0) <= 1 ? null : entry.path[1]
276
+ if (groupKey === null) {
277
+ // A modifier/property with no id of its own applies to the body being built: it belongs
278
+ // to the preceding feature row rather than becoming a sibling.
279
+ const last = units[units.length - 1]
280
+ if (last && last.kind === 'group') last.entries.push(row)
281
+ else units.push({ kind: 'single', row })
282
+ continue
283
+ }
284
+ const last = units[units.length - 1]
285
+ if (last && last.kind === 'group' && last.key === groupKey) last.entries.push(row)
286
+ else units.push({ kind: 'group', key: groupKey, entries: [row] })
287
+ }
288
+
289
+ /** @type {Array<object>} */
290
+ const rows = []
291
+ for (const unit of units) {
292
+ if (unit.kind === 'single') {
293
+ rows.push(unit.row)
294
+ continue
295
+ }
296
+ const entries = unit.entries
297
+ const primary = entries.filter((entry) => entry.kind !== 'property' && entry.kind !== 'report')
298
+ // A feature that is a single direct call with its own id needs no wrapper row; properties
299
+ // applied to the same body (setProperty has no id) become its children.
300
+ if (primary.length <= 1 && (primary.length === 0 || primary[0].path.length === 2)) {
301
+ const row = primary[0] ?? entries[0]
302
+ row.children = entries.filter((entry) => entry !== row)
303
+ rows.push(row)
304
+ continue
305
+ }
306
+ const action = entries.find((entry) => entry.kind !== 'sketch') ?? entries[0]
307
+ rows.push({
308
+ id: unit.key,
309
+ seq: entries[0].seq,
310
+ kind: 'feature',
311
+ kindLabel: 'Feature',
312
+ op: action.op,
313
+ title: humanizeOp(action.op ?? ''),
314
+ name: unit.key,
315
+ owner: null,
316
+ path: [entries[0].path[0], unit.key],
317
+ line: entries[0].line,
318
+ span: entries[0].span,
319
+ statement: entries[0].statement,
320
+ frames: entries[0].frames,
321
+ generatedBy: entries[0].generatedBy,
322
+ produced: entries.reduce((total, entry) => total + (entry.produced ?? 0), 0),
323
+ bodies: entries[entries.length - 1].bodies,
324
+ fields: action.fields,
325
+ children: entries,
326
+ grouped: true,
327
+ editable: entries.some((entry) => entry.editable),
328
+ structural: entries.some((entry) => entry.structural),
329
+ reorderable: entries.some((entry) => entry.reorderable),
330
+ })
331
+ }
332
+ return rows
333
+ }
334
+
335
+ /**
336
+ * Project a recorded assembly's instances into editable rows.
337
+ *
338
+ * @param {Array<any>} instances `AssemblyScene.toJSON()` output.
339
+ * @returns {Array<object>} Instance rows with part reference, placement and inspector fields.
340
+ */
341
+ export function projectAssemblyList(instances) {
342
+ return (instances ?? []).map((instance) => ({
343
+ id: instance.id,
344
+ seq: instance.seq,
345
+ kind: 'instance',
346
+ kindLabel: 'Instance',
347
+ title: instance.name ?? instance.part?.name ?? 'Instance',
348
+ name: instance.name,
349
+ part: instance.part,
350
+ /** Translation in mm. */
351
+ translate: instance.xf?.t ?? [0, 0, 0],
352
+ /** Row-major 3x3 rotation. */
353
+ rotation: instance.xf?.m ?? [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
354
+ fields: Object.entries(instance.definition ?? {}).map(([key, value]) => ({
355
+ key,
356
+ value: typeof value === 'string' ? value : JSON.stringify(value),
357
+ editable: false,
358
+ })),
359
+ }))
360
+ }
361
+
362
+ /**
363
+ * Quantity roll-up for an assembly: one line per referenced part.
364
+ *
365
+ * @param {Array<any>} instances `AssemblyScene.toJSON()` output.
366
+ * @returns {Array<{ part: string, hash: string|null, count: number, pages: string[] }>} BOM lines.
367
+ */
368
+ export function assemblyBom(instances) {
369
+ /** @type {Map<string, { part: string, hash: string|null, count: number, pages: string[] }>} */
370
+ const lines = new Map()
371
+ for (const instance of instances ?? []) {
372
+ const part = instance.part ?? {}
373
+ const key = `${part.name ?? '(unnamed)'}@${part.hash ?? ''}`
374
+ const line = lines.get(key) ?? { part: part.name ?? '(unnamed)', hash: part.hash ?? null, count: 0, pages: [] }
375
+ line.count += 1
376
+ if (part.page && !line.pages.includes(part.page)) line.pages.push(part.page)
377
+ lines.set(key, line)
378
+ }
379
+ return [...lines.values()]
380
+ }
381
+
382
+ /**
383
+ * Render a projected tree as plain text (CLI, logs, tests).
384
+ *
385
+ * @param {Array<object>} rows Rows from {@link projectFeatureList}.
386
+ * @param {{ fields?: boolean }} [options] Include definition fields.
387
+ * @returns {string} Indented tree.
388
+ */
389
+ export function formatFeatureTree(rows, { fields = false } = {}) {
390
+ const lines = []
391
+ const render = (row, depth) => {
392
+ const indent = ' '.repeat(depth)
393
+ const where = row.line != null ? ` :${row.line}` : ''
394
+ const produced = row.produced ? ` [${row.produced} body]` : ''
395
+ const generated = row.generatedBy ? ` (${row.generatedBy})` : ''
396
+ const owner = row.owner ? ` · ${row.owner}` : ''
397
+ lines.push(`${indent}${row.name ?? row.title}${owner} — ${row.kindLabel}${where}${produced}${generated}`)
398
+ if (fields) {
399
+ for (const field of row.fields) {
400
+ lines.push(`${indent} ${field.key} = ${field.value}${field.editable ? '' : ' (expression)'}`)
401
+ }
402
+ }
403
+ for (const child of row.children ?? []) render(child, depth + 1)
404
+ }
405
+ for (const row of rows) render(row, 0)
406
+ return lines.join('\n')
407
+ }
408
+
409
+ export { classifyBuiltin }