@fugood/bricks-ctor 2.25.0-beta.60 → 2.25.0-beta.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/package.json +4 -28
  2. package/tools/deploy.ts +19 -176
  3. package/tools/mcp-server.ts +16 -33
  4. package/tools/postinstall.ts +21 -292
  5. package/tools/pull.ts +15 -195
  6. package/tools/push-config.ts +18 -113
  7. package/tools/simulator.ts +19 -148
  8. package/compile/__tests__/config-diff.test.js +0 -100
  9. package/compile/__tests__/index.test.js +0 -461
  10. package/compile/__tests__/util.test.js +0 -450
  11. package/compile/action-name-map.ts +0 -1079
  12. package/compile/config-diff.ts +0 -155
  13. package/compile/index.ts +0 -1594
  14. package/compile/util.ts +0 -482
  15. package/index.ts +0 -6
  16. package/skills/bricks-ctor/SKILL.md +0 -38
  17. package/skills/bricks-ctor/references/animation.md +0 -160
  18. package/skills/bricks-ctor/references/architecture-patterns.md +0 -88
  19. package/skills/bricks-ctor/references/automations.md +0 -232
  20. package/skills/bricks-ctor/references/buttress.md +0 -245
  21. package/skills/bricks-ctor/references/data-calculation.md +0 -252
  22. package/skills/bricks-ctor/references/local-sync.md +0 -129
  23. package/skills/bricks-ctor/references/media-flow.md +0 -165
  24. package/skills/bricks-ctor/references/remote-data-bank.md +0 -196
  25. package/skills/bricks-ctor/references/simulator.md +0 -132
  26. package/skills/bricks-ctor/references/source-editing-tools.md +0 -81
  27. package/skills/bricks-ctor/references/standby-transition.md +0 -124
  28. package/skills/bricks-ctor/references/verification-toolchain.md +0 -200
  29. package/skills/bricks-design/SKILL.md +0 -171
  30. package/skills/bricks-design/references/architecture-truths.md +0 -132
  31. package/skills/bricks-design/references/avoiding-complexity.md +0 -91
  32. package/skills/bricks-design/references/design-critique.md +0 -195
  33. package/skills/bricks-design/references/design-languages.md +0 -265
  34. package/skills/bricks-design/references/performance.md +0 -116
  35. package/skills/bricks-design/references/presentation-and-slideshow.md +0 -137
  36. package/skills/bricks-design/references/translating-inputs.md +0 -152
  37. package/skills/bricks-design/references/variations-and-tweaks.md +0 -124
  38. package/skills/bricks-design/references/when-the-brief-is-branded.md +0 -284
  39. package/skills/bricks-design/references/when-the-brief-is-vague.md +0 -85
  40. package/skills/bricks-design/references/workflow.md +0 -134
  41. package/skills/bricks-ux/SKILL.md +0 -114
  42. package/skills/bricks-ux/references/accessibility.md +0 -162
  43. package/skills/bricks-ux/references/flow-states.md +0 -175
  44. package/skills/bricks-ux/references/interaction-archetypes.md +0 -189
  45. package/skills/bricks-ux/references/monitoring-screens.md +0 -153
  46. package/skills/bricks-ux/references/pressable-composition.md +0 -126
  47. package/skills/bricks-ux/references/user-journey.md +0 -168
  48. package/skills/bricks-ux/references/ux-critique.md +0 -256
  49. package/skills/rive-marketplace/SKILL.md +0 -99
  50. package/tools/__tests__/_cli-error.test.ts +0 -35
  51. package/tools/__tests__/_mcp-config.test.ts +0 -67
  52. package/tools/__tests__/pull.test.ts +0 -108
  53. package/tools/_cli-error.ts +0 -17
  54. package/tools/_edits-log.ts +0 -41
  55. package/tools/_git-author.ts +0 -37
  56. package/tools/_last-pushed-commit.ts +0 -28
  57. package/tools/_mcp-config.ts +0 -42
  58. package/tools/_shell.ts +0 -180
  59. package/tools/icons/.gitattributes +0 -1
  60. package/tools/icons/fa6pro-glyphmap.json +0 -4686
  61. package/tools/icons/fa6pro-meta.json +0 -1
  62. package/tools/mcp-env.ts +0 -13
  63. package/tools/mcp-tools/__tests__/data-calc-editing.test.js +0 -516
  64. package/tools/mcp-tools/__tests__/entry-editing.test.js +0 -866
  65. package/tools/mcp-tools/__tests__/huggingface.test.ts +0 -49
  66. package/tools/mcp-tools/__tests__/icons.test.ts +0 -21
  67. package/tools/mcp-tools/__tests__/mcp-env.test.js +0 -19
  68. package/tools/mcp-tools/_editing-helpers.ts +0 -98
  69. package/tools/mcp-tools/_verify.ts +0 -50
  70. package/tools/mcp-tools/compile.ts +0 -104
  71. package/tools/mcp-tools/data-calc-editing.ts +0 -1311
  72. package/tools/mcp-tools/entry-editing.ts +0 -2297
  73. package/tools/mcp-tools/huggingface.ts +0 -772
  74. package/tools/mcp-tools/icons.ts +0 -97
  75. package/tools/mcp-tools/lottie.ts +0 -102
  76. package/tools/mcp-tools/media.ts +0 -113
  77. package/tools/simulator-main.mjs +0 -488
  78. package/tools/simulator-preload.cjs +0 -16
  79. package/types/animation.d.ts +0 -116
  80. package/types/automation.d.ts +0 -231
  81. package/types/brick-base.d.ts +0 -80
  82. package/types/bricks/Camera.d.ts +0 -246
  83. package/types/bricks/Chart.d.ts +0 -372
  84. package/types/bricks/GenerativeMedia.d.ts +0 -290
  85. package/types/bricks/Icon.d.ts +0 -98
  86. package/types/bricks/Image.d.ts +0 -126
  87. package/types/bricks/Items.d.ts +0 -480
  88. package/types/bricks/Lottie.d.ts +0 -168
  89. package/types/bricks/Maps.d.ts +0 -262
  90. package/types/bricks/QrCode.d.ts +0 -117
  91. package/types/bricks/Rect.d.ts +0 -150
  92. package/types/bricks/RichText.d.ts +0 -131
  93. package/types/bricks/Rive.d.ts +0 -220
  94. package/types/bricks/Scene3D.d.ts +0 -676
  95. package/types/bricks/Sketch.d.ts +0 -256
  96. package/types/bricks/Slideshow.d.ts +0 -201
  97. package/types/bricks/Svg.d.ts +0 -99
  98. package/types/bricks/Text.d.ts +0 -148
  99. package/types/bricks/TextInput.d.ts +0 -242
  100. package/types/bricks/Video.d.ts +0 -242
  101. package/types/bricks/VideoStreaming.d.ts +0 -112
  102. package/types/bricks/WebRtcStream.d.ts +0 -65
  103. package/types/bricks/WebView.d.ts +0 -168
  104. package/types/bricks/index.d.ts +0 -23
  105. package/types/canvas.d.ts +0 -82
  106. package/types/common.d.ts +0 -141
  107. package/types/data-calc-command/base.d.ts +0 -57
  108. package/types/data-calc-command/collection.d.ts +0 -418
  109. package/types/data-calc-command/color.d.ts +0 -432
  110. package/types/data-calc-command/constant.d.ts +0 -50
  111. package/types/data-calc-command/datetime.d.ts +0 -147
  112. package/types/data-calc-command/file.d.ts +0 -129
  113. package/types/data-calc-command/index.d.ts +0 -13
  114. package/types/data-calc-command/iteratee.d.ts +0 -23
  115. package/types/data-calc-command/logictype.d.ts +0 -190
  116. package/types/data-calc-command/math.d.ts +0 -275
  117. package/types/data-calc-command/object.d.ts +0 -119
  118. package/types/data-calc-command/sandbox.d.ts +0 -66
  119. package/types/data-calc-command/string.d.ts +0 -407
  120. package/types/data-calc-script.d.ts +0 -21
  121. package/types/data-calc.d.ts +0 -12
  122. package/types/data.d.ts +0 -97
  123. package/types/generators/AlarmClock.d.ts +0 -110
  124. package/types/generators/Assistant.d.ts +0 -640
  125. package/types/generators/BleCentral.d.ts +0 -247
  126. package/types/generators/BlePeripheral.d.ts +0 -208
  127. package/types/generators/CanvasMap.d.ts +0 -74
  128. package/types/generators/CastlesPay.d.ts +0 -87
  129. package/types/generators/DataBank.d.ts +0 -160
  130. package/types/generators/File.d.ts +0 -432
  131. package/types/generators/GraphQl.d.ts +0 -132
  132. package/types/generators/Http.d.ts +0 -222
  133. package/types/generators/HttpServer.d.ts +0 -230
  134. package/types/generators/Information.d.ts +0 -103
  135. package/types/generators/Intent.d.ts +0 -168
  136. package/types/generators/Iterator.d.ts +0 -108
  137. package/types/generators/Keyboard.d.ts +0 -105
  138. package/types/generators/LlmAnthropicCompat.d.ts +0 -212
  139. package/types/generators/LlmAppleBuiltin.d.ts +0 -159
  140. package/types/generators/LlmGgml.d.ts +0 -903
  141. package/types/generators/LlmMediaTekNeuroPilot.d.ts +0 -235
  142. package/types/generators/LlmMlx.d.ts +0 -228
  143. package/types/generators/LlmOnnx.d.ts +0 -213
  144. package/types/generators/LlmOpenAiCompat.d.ts +0 -312
  145. package/types/generators/LlmQualcommAiEngine.d.ts +0 -247
  146. package/types/generators/Mcp.d.ts +0 -637
  147. package/types/generators/McpServer.d.ts +0 -289
  148. package/types/generators/MediaFlow.d.ts +0 -170
  149. package/types/generators/MqttBroker.d.ts +0 -141
  150. package/types/generators/MqttClient.d.ts +0 -141
  151. package/types/generators/Question.d.ts +0 -408
  152. package/types/generators/RealtimeTranscription.d.ts +0 -287
  153. package/types/generators/RerankerGgml.d.ts +0 -195
  154. package/types/generators/SerialPort.d.ts +0 -151
  155. package/types/generators/SoundPlayer.d.ts +0 -94
  156. package/types/generators/SoundRecorder.d.ts +0 -139
  157. package/types/generators/SpeechToTextGgml.d.ts +0 -424
  158. package/types/generators/SpeechToTextOnnx.d.ts +0 -236
  159. package/types/generators/SpeechToTextPlatform.d.ts +0 -85
  160. package/types/generators/SqLite.d.ts +0 -159
  161. package/types/generators/Step.d.ts +0 -107
  162. package/types/generators/SttAppleBuiltin.d.ts +0 -153
  163. package/types/generators/Tcp.d.ts +0 -126
  164. package/types/generators/TcpServer.d.ts +0 -147
  165. package/types/generators/TextToSpeechAppleBuiltin.d.ts +0 -127
  166. package/types/generators/TextToSpeechGgml.d.ts +0 -221
  167. package/types/generators/TextToSpeechOnnx.d.ts +0 -178
  168. package/types/generators/TextToSpeechOpenAiLike.d.ts +0 -121
  169. package/types/generators/ThermalPrinter.d.ts +0 -193
  170. package/types/generators/Tick.d.ts +0 -83
  171. package/types/generators/Udp.d.ts +0 -120
  172. package/types/generators/VadGgml.d.ts +0 -260
  173. package/types/generators/VadOnnx.d.ts +0 -231
  174. package/types/generators/VadTraditional.d.ts +0 -138
  175. package/types/generators/VectorStore.d.ts +0 -257
  176. package/types/generators/Watchdog.d.ts +0 -107
  177. package/types/generators/WebCrawler.d.ts +0 -103
  178. package/types/generators/WebRtc.d.ts +0 -181
  179. package/types/generators/WebSocket.d.ts +0 -148
  180. package/types/generators/index.d.ts +0 -57
  181. package/types/index.d.ts +0 -13
  182. package/types/subspace.d.ts +0 -60
  183. package/types/switch.d.ts +0 -51
  184. package/types/system.d.ts +0 -707
  185. package/utils/__tests__/calc.test.js +0 -25
  186. package/utils/__tests__/id.test.js +0 -154
  187. package/utils/calc.ts +0 -130
  188. package/utils/data.ts +0 -495
  189. package/utils/event-props.ts +0 -912
  190. package/utils/id.ts +0 -133
@@ -1,1311 +0,0 @@
1
- import generateModule from '@babel/generator'
2
- import { parse, parseExpression } from '@babel/parser'
3
- import * as t from '@babel/types'
4
- import { parse as parseSandboxModule } from 'acorn'
5
- import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
6
- import { format as formatWithOxfmt } from 'oxfmt'
7
- import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
8
- import path from 'node:path'
9
- import { z } from 'zod'
10
-
11
- import { verifyProject } from './_verify'
12
- import {
13
- ensureBricksCtorImport,
14
- getObjectProperty,
15
- getStringProperty,
16
- insertImport,
17
- isRecord,
18
- makeObjectKey,
19
- oxfmtOptions,
20
- projectRelativePath,
21
- removeObjectProperty,
22
- setObjectProperty,
23
- } from './_editing-helpers'
24
- import { appendEditRecord, editProvenance } from '../_edits-log'
25
-
26
- const generate = (generateModule as any).default || generateModule
27
-
28
- type ParsedFile = {
29
- ast: t.File
30
- source: string
31
- absPath: string
32
- relPath: string
33
- }
34
-
35
- type ExportEntry = {
36
- name: string
37
- object?: t.ObjectExpression
38
- id?: string
39
- alias?: string
40
- typeName?: string
41
- }
42
-
43
- type ReferenceResolution = {
44
- input: string
45
- id?: string
46
- alias?: string
47
- varName: string
48
- sameFile: boolean
49
- importSource?: string
50
- }
51
-
52
- type EditContext = {
53
- projectDir: string
54
- parsed: ParsedFile
55
- references: ReferenceResolution[]
56
- typeImports: Set<string>
57
- valueImports: Set<string>
58
- }
59
-
60
- type CalcTarget = {
61
- parsed: ParsedFile
62
- object: t.ObjectExpression
63
- slug: string
64
- sandboxFile: string
65
- }
66
-
67
- class DataCalcEditingError extends Error {
68
- code: string
69
- details?: Record<string, unknown>
70
- isMcpError: boolean
71
-
72
- constructor(
73
- code: string,
74
- message: string,
75
- details?: Record<string, unknown>,
76
- isMcpError = false,
77
- ) {
78
- super(message)
79
- this.name = 'DataCalcEditingError'
80
- this.code = code
81
- this.details = details
82
- this.isMcpError = isMcpError
83
- }
84
- }
85
-
86
- const resolveProjectPath = (projectDir: string, file: string) => {
87
- if (path.isAbsolute(file)) {
88
- throw new DataCalcEditingError('invalid_file', 'File must be project-relative', { file })
89
- }
90
-
91
- const absPath = path.resolve(projectDir, file)
92
- const relative = path.relative(projectDir, absPath)
93
- if (relative.startsWith('..') || path.isAbsolute(relative)) {
94
- throw new DataCalcEditingError('invalid_file', 'File must stay inside the project directory', {
95
- file,
96
- })
97
- }
98
- return absPath
99
- }
100
-
101
- const parseFileSource = (source: string, relPath: string) => {
102
- try {
103
- return parse(source, {
104
- sourceType: 'module',
105
- plugins: ['typescript', 'topLevelAwait'],
106
- errorRecovery: false,
107
- })
108
- } catch (err: any) {
109
- throw new DataCalcEditingError(
110
- 'parse_failed',
111
- `Cannot parse ${relPath} as TypeScript: ${err.message}. Edit this file directly.`,
112
- { file: relPath },
113
- true,
114
- )
115
- }
116
- }
117
-
118
- const readParsedFile = async (projectDir: string, absPath: string): Promise<ParsedFile> => {
119
- const source = await readFile(absPath, 'utf8')
120
- const relPath = projectRelativePath(projectDir, absPath)
121
- return {
122
- source,
123
- ast: parseFileSource(source, relPath),
124
- absPath,
125
- relPath,
126
- }
127
- }
128
-
129
- const getExportEntries = (ast: t.File): ExportEntry[] =>
130
- ast.program.body.flatMap((statement) => {
131
- if (!t.isExportNamedDeclaration(statement)) return []
132
- if (!t.isVariableDeclaration(statement.declaration)) return []
133
- return statement.declaration.declarations.flatMap((declarator) => {
134
- if (!t.isIdentifier(declarator.id)) return []
135
-
136
- const typeAnnotation = declarator.id.typeAnnotation
137
- let typeName: string | undefined
138
- if (
139
- t.isTSTypeAnnotation(typeAnnotation) &&
140
- t.isTSTypeReference(typeAnnotation.typeAnnotation) &&
141
- t.isIdentifier(typeAnnotation.typeAnnotation.typeName)
142
- ) {
143
- typeName = typeAnnotation.typeAnnotation.typeName.name
144
- }
145
-
146
- const object = t.isObjectExpression(declarator.init) ? declarator.init : undefined
147
- return [
148
- {
149
- name: declarator.id.name,
150
- object,
151
- id: object ? getStringProperty(object, 'id') : undefined,
152
- alias: object ? getStringProperty(object, 'alias') : undefined,
153
- typeName,
154
- },
155
- ]
156
- })
157
- })
158
-
159
- const getCalcDirFromSubspaceDir = (subspaceDir: string) => path.join(subspaceDir, 'data-calc')
160
-
161
- const getSubspaceDirFromCalcFile = (absPath: string) => {
162
- const parts = absPath.split(path.sep)
163
- const index = parts.findIndex((part) => /^subspace-\d+$/.test(part))
164
- if (index < 0) {
165
- throw new DataCalcEditingError(
166
- 'invalid_file',
167
- 'Data-calc file must be inside subspaces/subspace-N/data-calc',
168
- { file: absPath },
169
- )
170
- }
171
- return parts.slice(0, index + 1).join(path.sep)
172
- }
173
-
174
- const resolveSubspaceDir = (projectDir: string, subspace?: string | number) => {
175
- if (subspace == null || subspace === '') return path.join(projectDir, 'subspaces/subspace-0')
176
- if (typeof subspace === 'number') {
177
- return path.join(projectDir, 'subspaces', `subspace-${subspace}`)
178
- }
179
-
180
- const normalized = String(subspace)
181
- if (/^\d+$/.test(normalized)) return path.join(projectDir, 'subspaces', `subspace-${normalized}`)
182
- if (/^subspace-\d+$/.test(normalized)) return path.join(projectDir, 'subspaces', normalized)
183
- if (normalized.includes('/')) return resolveProjectPath(projectDir, normalized)
184
-
185
- throw new DataCalcEditingError(
186
- 'unsupported_subspace',
187
- `Unsupported subspace locator: ${normalized}`,
188
- {
189
- subspace: normalized,
190
- },
191
- )
192
- }
193
-
194
- const calcSlugFromFile = (absPath: string) => {
195
- const basename = path.basename(absPath)
196
- const match = /^data-calculation-(.+)\.ts$/.exec(basename)
197
- if (!match) {
198
- throw new DataCalcEditingError('invalid_file', 'Expected data-calculation-{slug}.ts file', {
199
- file: absPath,
200
- })
201
- }
202
- return match[1]
203
- }
204
-
205
- const getDataCalcFiles = async (dataCalcDir: string) => {
206
- const entries = await readdir(dataCalcDir, { withFileTypes: true }).catch(() => [])
207
- return entries
208
- .filter(
209
- (entry) =>
210
- entry.isFile() &&
211
- /^data-calculation-.+\.ts$/.test(entry.name) &&
212
- !entry.name.endsWith('.sandbox.ts'),
213
- )
214
- .map((entry) => path.join(dataCalcDir, entry.name))
215
- .sort()
216
- }
217
-
218
- const extractCalcObject = (parsed: ParsedFile) => {
219
- const entries = getExportEntries(parsed.ast)
220
- const calcEntry = entries.find((entry) => entry.name === 'dataCalculation')
221
- if (!calcEntry || !calcEntry.object) {
222
- throw new DataCalcEditingError(
223
- 'fallback_recommended',
224
- `Data calc ${parsed.relPath} is not a single exported object literal. Edit this file directly for this one.`,
225
- { file: parsed.relPath, check: 'export const dataCalculation object literal' },
226
- )
227
- }
228
-
229
- const typename = getStringProperty(calcEntry.object, '__typename')
230
- if (typename !== 'DataCalculationScript') {
231
- throw new DataCalcEditingError(
232
- 'fallback_recommended',
233
- `Data calc ${parsed.relPath} is ${typename || 'not DataCalculationScript'}. DataCalculationMap is out of scope; edit this file directly.`,
234
- { file: parsed.relPath, typename },
235
- )
236
- }
237
-
238
- return calcEntry.object
239
- }
240
-
241
- const getCodeExpression = (object: t.ObjectExpression): t.Expression | null => {
242
- const value = getObjectProperty(object, 'code')?.value
243
- return value && t.isExpression(value) ? value : null
244
- }
245
-
246
- // Sibling sandbox files only: a plain `./name.sandbox.js` basename. Anything else
247
- // (nested paths, ../ traversal, non-sandbox files) is not ours to rewrite or delete.
248
- const isSandboxFilename = (value: string) => /^(\.\/)?[^/\\]+\.sandbox\.js$/.test(value)
249
-
250
- const readCodeUrlFilename = (code: t.Expression | null | undefined) => {
251
- const expression = t.isAwaitExpression(code) ? code.argument : code
252
- if (!t.isCallExpression(expression)) return null
253
- const firstArg = expression.arguments[0]
254
- if (!t.isNewExpression(firstArg)) return null
255
- if (!t.isIdentifier(firstArg.callee) || firstArg.callee.name !== 'URL') return null
256
- const filenameArg = firstArg.arguments[0]
257
- if (!t.isStringLiteral(filenameArg)) return null
258
- return filenameArg.value
259
- }
260
-
261
- const sandboxFilenameFromCodeExpression = (
262
- code: t.Expression | null | undefined,
263
- fallbackSlug: string,
264
- ) => {
265
- const filename = readCodeUrlFilename(code)
266
- if (!filename || !isSandboxFilename(filename)) {
267
- return `data-calculation-${fallbackSlug}.sandbox.js`
268
- }
269
- return filename.replace(/^\.\//, '')
270
- }
271
-
272
- const isRecognizedCodeExpression = (code: t.Expression | null | undefined) => {
273
- if (!code) return false
274
- if (t.isStringLiteral(code) || t.isTemplateLiteral(code)) return true
275
- const filename = readCodeUrlFilename(code)
276
- return filename != null && isSandboxFilename(filename)
277
- }
278
-
279
- const resolveCalcTarget = async (projectDir: string, input: any): Promise<CalcTarget> => {
280
- let absPath: string | undefined
281
-
282
- if (input.file) {
283
- absPath = resolveProjectPath(projectDir, input.file)
284
- } else {
285
- const subspaceDir = resolveSubspaceDir(projectDir, input.subspace)
286
- const calcDir = getCalcDirFromSubspaceDir(subspaceDir)
287
- const files = await getDataCalcFiles(calcDir)
288
- const calc = input.calc
289
- if (!calc) {
290
- throw new DataCalcEditingError('missing_calc', 'Provide file or subspace+calc')
291
- }
292
-
293
- for (const file of files) {
294
- if (calc === calcSlugFromFile(file)) {
295
- absPath = file
296
- break
297
- }
298
- // Tolerate unparseable / non-Script siblings while scanning: they only opt out
299
- // of alias/id matching here; standard-style checks run on the resolved target.
300
- try {
301
- const parsed = await readParsedFile(projectDir, file)
302
- const entry = getExportEntries(parsed.ast).find((item) => item.name === 'dataCalculation')
303
- if (entry && (calc === entry.alias || calc === entry.id)) {
304
- absPath = file
305
- break
306
- }
307
- } catch {
308
- continue
309
- }
310
- }
311
- }
312
-
313
- if (!absPath) {
314
- throw new DataCalcEditingError('calc_not_found', `Data calc not found: ${input.calc}`, {
315
- calc: input.calc,
316
- subspace: input.subspace ?? 'subspace-0',
317
- })
318
- }
319
-
320
- const parsed = await readParsedFile(projectDir, absPath)
321
- const object = extractCalcObject(parsed)
322
- const slug = calcSlugFromFile(absPath)
323
- const sandboxFile = sandboxFilenameFromCodeExpression(getCodeExpression(object), slug)
324
- return { parsed, object, slug, sandboxFile }
325
- }
326
-
327
- const relativeImportSource = (fromFile: string, toFile: string) => {
328
- let rel = path.relative(path.dirname(fromFile), toFile).replace(/\\/g, '/')
329
- if (!rel.startsWith('.')) rel = `./${rel}`
330
- return rel.replace(/\.(ts|tsx|js|jsx)$/, '')
331
- }
332
-
333
- const ensureNamespaceImport = (parsed: ParsedFile, source: string, preferredLocal: string) => {
334
- for (const statement of parsed.ast.program.body) {
335
- if (!t.isImportDeclaration(statement) || statement.source.value !== source) continue
336
- const namespace = statement.specifiers.find(
337
- (specifier): specifier is t.ImportNamespaceSpecifier =>
338
- t.isImportNamespaceSpecifier(specifier),
339
- )
340
- if (namespace) return namespace.local.name
341
- }
342
-
343
- const declaration = t.importDeclaration(
344
- [t.importNamespaceSpecifier(t.identifier(preferredLocal))],
345
- t.stringLiteral(source),
346
- )
347
- insertImport(parsed.ast, declaration)
348
- return preferredLocal
349
- }
350
-
351
- const ensureReadFileImport = (ast: t.File) => {
352
- for (const statement of ast.program.body) {
353
- if (!t.isImportDeclaration(statement) || statement.source.value !== 'node:fs/promises') {
354
- continue
355
- }
356
- const hasReadFile = statement.specifiers.some(
357
- (specifier) =>
358
- t.isImportSpecifier(specifier) &&
359
- t.isIdentifier(specifier.imported) &&
360
- specifier.imported.name === 'readFile',
361
- )
362
- if (!hasReadFile) {
363
- statement.specifiers.push(
364
- t.importSpecifier(t.identifier('readFile'), t.identifier('readFile')),
365
- )
366
- }
367
- return
368
- }
369
-
370
- insertImport(
371
- ast,
372
- t.importDeclaration(
373
- [t.importSpecifier(t.identifier('readFile'), t.identifier('readFile'))],
374
- t.stringLiteral('node:fs/promises'),
375
- ),
376
- )
377
- }
378
-
379
- const applyPendingImports = (ctx: EditContext) => {
380
- ensureBricksCtorImport(ctx.parsed.ast, 'type', ctx.typeImports)
381
- ensureBricksCtorImport(ctx.parsed.ast, 'value', ctx.valueImports)
382
- }
383
-
384
- const resolveDataReference = async (
385
- projectDir: string,
386
- currentFile: string,
387
- ref: string,
388
- subspace?: string | number,
389
- ): Promise<ReferenceResolution> => {
390
- const currentSubspaceDir = getSubspaceDirFromCalcFile(currentFile)
391
- const targetSubspaceDir =
392
- subspace == null ? currentSubspaceDir : resolveSubspaceDir(projectDir, subspace)
393
- const dataFile = path.join(targetSubspaceDir, 'data.ts')
394
- const parsed = await readParsedFile(projectDir, dataFile)
395
- const matches = getExportEntries(parsed.ast).filter(
396
- (entry) => entry.name === ref || entry.id === ref || entry.alias === ref,
397
- )
398
-
399
- if (matches.length === 0) {
400
- throw new DataCalcEditingError('reference_not_found', `Data reference not found: ${ref}`, {
401
- ref,
402
- subspace: path.basename(targetSubspaceDir),
403
- })
404
- }
405
- if (matches.length > 1) {
406
- throw new DataCalcEditingError('ambiguous_reference', `Data reference is ambiguous: ${ref}`, {
407
- ref,
408
- matches: matches.map((match) => ({
409
- file: projectRelativePath(projectDir, dataFile),
410
- entry: match.name,
411
- id: match.id,
412
- alias: match.alias,
413
- })),
414
- })
415
- }
416
-
417
- const sameFile = path.resolve(dataFile) === path.resolve(currentFile)
418
- return {
419
- input: ref,
420
- id: matches[0].id,
421
- alias: matches[0].alias,
422
- varName: matches[0].name,
423
- sameFile,
424
- importSource: sameFile ? undefined : relativeImportSource(currentFile, dataFile),
425
- }
426
- }
427
-
428
- const dataGetterExpression = async (input: any, ctx: EditContext): Promise<t.Expression> => {
429
- if (isRecord(input) && typeof input.expr === 'string') {
430
- return parseExpression(input.expr, { plugins: ['typescript'] }) as t.Expression
431
- }
432
-
433
- const ref = typeof input === 'string' ? input : isRecord(input) ? input.ref : undefined
434
- if (typeof ref !== 'string' || !ref) {
435
- throw new DataCalcEditingError('invalid_ref', 'Data getter requires a data ref string')
436
- }
437
-
438
- const resolved = await resolveDataReference(
439
- ctx.projectDir,
440
- ctx.parsed.absPath,
441
- ref,
442
- isRecord(input) ? (input.subspace as any) : undefined,
443
- )
444
- const local = resolved.sameFile
445
- ? 'data'
446
- : ensureNamespaceImport(ctx.parsed, resolved.importSource || '../data', 'data')
447
- ctx.references.push(resolved)
448
- return t.arrowFunctionExpression(
449
- [],
450
- t.memberExpression(t.identifier(local), t.identifier(resolved.varName)),
451
- )
452
- }
453
-
454
- const nullableDataGetterExpression = async (value: any, ctx: EditContext) => {
455
- if (value == null) return t.nullLiteral()
456
- return dataGetterExpression(value, ctx)
457
- }
458
-
459
- // Alias-keyed makeId calls hash to the same uuid regardless of declaration order, so
460
- // recompiles stay stable when sibling entries are added or removed.
461
- const makeIdCallExpression = (idType: string, alias?: string) =>
462
- t.callExpression(
463
- t.identifier('makeId'),
464
- alias ? [t.stringLiteral(idType), t.stringLiteral(alias)] : [t.stringLiteral(idType)],
465
- )
466
-
467
- // True when another calc anywhere in the project already uses the alias — the aliased
468
- // makeId form would collide at compile time.
469
- const aliasUsedInCalcs = async (projectDir: string, alias: string) => {
470
- const subspacesDir = path.join(projectDir, 'subspaces')
471
- const entries = await readdir(subspacesDir, { withFileTypes: true }).catch(() => [])
472
- for (const entry of entries) {
473
- if (!entry.isDirectory() || !/^subspace-\d+$/.test(entry.name)) continue
474
- const files = await getDataCalcFiles(path.join(subspacesDir, entry.name, 'data-calc'))
475
- for (const file of files) {
476
- try {
477
- const parsed = await readParsedFile(projectDir, file)
478
- const calcEntry = getExportEntries(parsed.ast).find(
479
- (item) => item.name === 'dataCalculation',
480
- )
481
- if (calcEntry?.alias === alias) return true
482
- } catch {
483
- continue
484
- }
485
- }
486
- }
487
- return false
488
- }
489
-
490
- // Required by the DataCalculationScript type; unsetting them yields a calc that
491
- // crashes compile with an unrelated-looking error instead of a clear refusal here.
492
- const requiredCalcFields = new Set([
493
- '__typename',
494
- 'id',
495
- 'code',
496
- 'enableAsync',
497
- 'inputs',
498
- 'output',
499
- 'outputs',
500
- 'error',
501
- ])
502
-
503
- const makeCodeReadFileExpression = (sandboxFile: string) =>
504
- t.awaitExpression(
505
- t.callExpression(t.identifier('readFile'), [
506
- t.newExpression(t.identifier('URL'), [
507
- t.stringLiteral(`./${sandboxFile}`),
508
- t.memberExpression(
509
- t.metaProperty(t.identifier('import'), t.identifier('meta')),
510
- t.identifier('url'),
511
- ),
512
- ]),
513
- t.stringLiteral('utf8'),
514
- ]),
515
- )
516
-
517
- const expressionFromInput = async (input: any, ctx: EditContext): Promise<t.Expression> => {
518
- if (isRecord(input)) {
519
- if (typeof input.expr === 'string') {
520
- return parseExpression(input.expr, { plugins: ['typescript'] }) as t.Expression
521
- }
522
- if (typeof input.ref === 'string') return dataGetterExpression(input, ctx)
523
- }
524
- if (input === null) return t.nullLiteral()
525
- if (input === undefined) return t.identifier('undefined')
526
- if (typeof input === 'string') return t.stringLiteral(input)
527
- if (typeof input === 'number') return t.numericLiteral(input)
528
- if (typeof input === 'boolean') return t.booleanLiteral(input)
529
- if (Array.isArray(input)) {
530
- return t.arrayExpression(
531
- await Promise.all(input.map((value) => expressionFromInput(value, ctx))),
532
- )
533
- }
534
- if (isRecord(input)) {
535
- const properties = await Promise.all(
536
- Object.entries(input).map(async ([key, value]) =>
537
- t.objectProperty(makeObjectKey(key), await expressionFromInput(value, ctx)),
538
- ),
539
- )
540
- return t.objectExpression(properties)
541
- }
542
- throw new DataCalcEditingError('invalid_value', `Unsupported value: ${String(input)}`)
543
- }
544
-
545
- const printAndFormat = async (parsed: ParsedFile) => {
546
- const generated = generate(parsed.ast, { comments: true }, parsed.source).code
547
- const formatted = await formatWithOxfmt(parsed.absPath, generated, oxfmtOptions)
548
- if (formatted.errors.length > 0) {
549
- throw new DataCalcEditingError('format_failed', `oxfmt failed for ${parsed.relPath}`, {
550
- file: parsed.relPath,
551
- errors: formatted.errors,
552
- })
553
- }
554
- return formatted.code
555
- }
556
-
557
- const writeParsedFile = async (parsed: ParsedFile) => {
558
- const code = await printAndFormat(parsed)
559
- parseFileSource(code, parsed.relPath)
560
- await writeFile(parsed.absPath, code)
561
- return code
562
- }
563
-
564
- const responseFor = (result: any): any => ({
565
- content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
566
- isError: result.isError || undefined,
567
- })
568
-
569
- const referenceInputDetails = (references: ReferenceResolution[]) =>
570
- references.map((reference) => ({
571
- input: reference.input,
572
- id: reference.id,
573
- alias: reference.alias,
574
- entry: reference.varName,
575
- }))
576
-
577
- const runOperation = async (
578
- projectDir: string,
579
- tool: string,
580
- input: any,
581
- operation: () => Promise<any>,
582
- ) => {
583
- const startedAt = new Date().toISOString()
584
- const provenance = editProvenance()
585
- try {
586
- const result = await operation()
587
- await appendEditRecord(projectDir, {
588
- ts: startedAt,
589
- tool,
590
- input,
591
- provenance,
592
- outcome: result.outcome,
593
- summary: result.summary,
594
- result,
595
- })
596
- return result
597
- } catch (err: any) {
598
- const isMcpError = err instanceof DataCalcEditingError
599
- const outcome =
600
- isMcpError && err.code === 'fallback_recommended' ? 'fallback_recommended' : 'error'
601
- const result = {
602
- outcome,
603
- // Fallback recommendations are guidance, not MCP errors (mirrors entry-editing).
604
- isError: outcome === 'error',
605
- error: {
606
- code: isMcpError ? err.code : 'unexpected_error',
607
- message: err.message,
608
- details: isMcpError ? err.details : undefined,
609
- },
610
- summary: `${tool} failed: ${err.message}`,
611
- }
612
- await appendEditRecord(projectDir, {
613
- ts: startedAt,
614
- tool,
615
- input,
616
- provenance,
617
- outcome: result.outcome,
618
- summary: result.summary,
619
- error: result.error,
620
- }).catch(() => undefined)
621
- return result
622
- }
623
- }
624
-
625
- const slugify = (value: string) => {
626
- const slug = value
627
- .trim()
628
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
629
- .toLowerCase()
630
- .replace(/[^a-z0-9]+/g, '-')
631
- .replace(/^-+|-+$/g, '')
632
- return slug || 'calc'
633
- }
634
-
635
- const nextFreeSlug = async (dataCalcDir: string, preferred?: string) => {
636
- const existing = new Set((await getDataCalcFiles(dataCalcDir)).map(calcSlugFromFile))
637
- if (preferred) {
638
- let slug = slugify(preferred)
639
- if (!existing.has(slug)) return slug
640
- let index = 1
641
- while (existing.has(`${slug}-${index}`)) index += 1
642
- return `${slug}-${index}`
643
- }
644
-
645
- let index = 0
646
- while (existing.has(String(index))) index += 1
647
- return String(index)
648
- }
649
-
650
- // Compile unwraps the sandbox with the same acorn parse (compile/index.ts
651
- // compileScriptCalculationCode, ecmaVersion 2020) and silently falls back to the raw
652
- // wrapped string when it fails, so an unparseable sandbox must be rejected here.
653
- const sandboxParses = (source: string) => {
654
- try {
655
- parseSandboxModule(source, { sourceType: 'module', ecmaVersion: 2020 })
656
- return true
657
- } catch {
658
- return false
659
- }
660
- }
661
-
662
- const wrapSandboxCode = (code?: string) => {
663
- const body = code ?? ''
664
- if (/export\s+(async\s+)?function\s+main\s*\(/.test(body)) {
665
- const wrapped = body.endsWith('\n') ? body : `${body}\n`
666
- if (!sandboxParses(wrapped)) {
667
- throw new DataCalcEditingError(
668
- 'invalid_code',
669
- 'Sandbox code does not parse as a module (note: top-level await requires export async function main)',
670
- )
671
- }
672
- return wrapped
673
- }
674
- const trimmed = body.trim()
675
- if (!trimmed) return 'export function main() {\n}\n'
676
- // Bodies using top-level await (enableAsync mode) only parse inside an async main;
677
- // compile unwraps either wrapper form to the same script body.
678
- for (const asyncPrefix of ['', 'async ']) {
679
- const wrapped = `export ${asyncPrefix}function main() {\n${trimmed}\n}\n`
680
- if (sandboxParses(wrapped)) return wrapped
681
- }
682
- throw new DataCalcEditingError(
683
- 'invalid_code',
684
- 'Sandbox code does not parse as a script body (statements with top-level return)',
685
- )
686
- }
687
-
688
- const regenerateDataCalcIndex = async (projectDir: string, dataCalcDir: string) => {
689
- await mkdir(dataCalcDir, { recursive: true })
690
- const files = await getDataCalcFiles(dataCalcDir)
691
- const imports = files
692
- .map((file, index) => {
693
- const slug = calcSlugFromFile(file)
694
- return `import { dataCalculation as dataCalculation${index} } from './data-calculation-${slug}'`
695
- })
696
- .join('\n')
697
- const list = files.map((_, index) => `dataCalculation${index}`).join(',\n ')
698
- const source = `${imports}
699
-
700
- export const dataCalculation = [
701
- ${list}
702
- ]
703
- `
704
- const indexPath = path.join(dataCalcDir, 'index.ts')
705
- const parsed: ParsedFile = {
706
- absPath: indexPath,
707
- relPath: projectRelativePath(projectDir, indexPath),
708
- source,
709
- ast: parseFileSource(source, projectRelativePath(projectDir, indexPath)),
710
- }
711
- await writeParsedFile(parsed)
712
- return projectRelativePath(projectDir, indexPath)
713
- }
714
-
715
- const getDefaultExportObject = (ast: t.File) => {
716
- for (const statement of ast.program.body) {
717
- if (!t.isExportDefaultDeclaration(statement)) continue
718
- const declaration = statement.declaration
719
- if (t.isObjectExpression(declaration)) return declaration
720
- if (t.isTSAsExpression(declaration) && t.isObjectExpression(declaration.expression)) {
721
- return declaration.expression
722
- }
723
- }
724
- return null
725
- }
726
-
727
- const ensureSubspaceRootDataCalcImport = async (
728
- projectDir: string,
729
- subspaceDir: string,
730
- ): Promise<{ touched?: string; warning?: string } | null> => {
731
- const indexPath = path.join(subspaceDir, 'index.ts')
732
- const relPath = projectRelativePath(projectDir, indexPath)
733
- const source = await readFile(indexPath, 'utf8').catch((err: any) => {
734
- if (err?.code === 'ENOENT') return null
735
- throw err
736
- })
737
- if (source == null) {
738
- return { warning: `${relPath} not found; wire the data-calc import manually` }
739
- }
740
-
741
- const parsed = await readParsedFile(projectDir, indexPath)
742
- const object = getDefaultExportObject(parsed.ast)
743
- if (!object) {
744
- return {
745
- warning: `${relPath} has no default-export object; wire the data-calc import manually`,
746
- }
747
- }
748
-
749
- const property = getObjectProperty(object, 'dataCalculation')
750
- if (property && t.isIdentifier(property.value)) return null
751
- if (property && !(t.isArrayExpression(property.value) && property.value.elements.length === 0)) {
752
- // Only the codegen minimal-subspace shape (dataCalculation: []) is safe to rewire;
753
- // replacing any other value (inline calcs, spreads) would silently drop config.
754
- return {
755
- warning: `${relPath} has a non-empty dataCalculation value; wire the data-calc import manually`,
756
- }
757
- }
758
-
759
- const alreadyImported = parsed.ast.program.body.some(
760
- (statement) =>
761
- t.isImportDeclaration(statement) &&
762
- (statement.source.value === './data-calc' || statement.source.value === './data-calc/index'),
763
- )
764
- if (!alreadyImported) {
765
- insertImport(
766
- parsed.ast,
767
- t.importDeclaration(
768
- [t.importSpecifier(t.identifier('dataCalculation'), t.identifier('dataCalculation'))],
769
- t.stringLiteral('./data-calc'),
770
- ),
771
- )
772
- }
773
-
774
- if (!property) {
775
- const dataCalculationProperty = t.objectProperty(
776
- t.identifier('dataCalculation'),
777
- t.identifier('dataCalculation'),
778
- )
779
- dataCalculationProperty.shorthand = true
780
- object.properties.push(dataCalculationProperty)
781
- } else {
782
- property.value = t.identifier('dataCalculation')
783
- if (t.isIdentifier(property.key)) property.shorthand = true
784
- }
785
-
786
- await writeParsedFile(parsed)
787
- return { touched: parsed.relPath }
788
- }
789
-
790
- const buildIoObject = async (field: 'inputs' | 'outputs', input: any, ctx: EditContext) => {
791
- if (!input.key) {
792
- throw new DataCalcEditingError('missing_key', `${field} item requires key`)
793
- }
794
- if (input.data == null) {
795
- throw new DataCalcEditingError('missing_data', `${field} item requires data`)
796
- }
797
- const properties: t.ObjectProperty[] = [
798
- t.objectProperty(t.identifier('key'), t.stringLiteral(input.key)),
799
- t.objectProperty(t.identifier('data'), await dataGetterExpression(input.data, ctx)),
800
- ]
801
- if (field === 'inputs') {
802
- properties.push(
803
- t.objectProperty(t.identifier('trigger'), t.booleanLiteral(input.trigger !== false)),
804
- )
805
- }
806
- return t.objectExpression(properties)
807
- }
808
-
809
- const buildIoArrayExpression = async (
810
- field: 'inputs' | 'outputs',
811
- items: any[],
812
- ctx: EditContext,
813
- ) => {
814
- if (field === 'inputs') {
815
- const keys = new Set<string>()
816
- for (const item of items) {
817
- if (keys.has(item?.key)) {
818
- throw new DataCalcEditingError('duplicate_key', `Input key already exists: ${item.key}`, {
819
- key: item.key,
820
- })
821
- }
822
- keys.add(item?.key)
823
- }
824
- }
825
- return t.arrayExpression(await Promise.all(items.map((item) => buildIoObject(field, item, ctx))))
826
- }
827
-
828
- const getOrCreateArrayProperty = (object: t.ObjectExpression, key: string) => {
829
- const existing = getObjectProperty(object, key)
830
- if (existing) {
831
- if (!t.isArrayExpression(existing.value)) {
832
- throw new DataCalcEditingError(
833
- 'fallback_recommended',
834
- `${key} is not an array. Edit this file directly.`,
835
- )
836
- }
837
- return existing.value
838
- }
839
- const array = t.arrayExpression([])
840
- object.properties.push(t.objectProperty(t.identifier(key), array))
841
- return array
842
- }
843
-
844
- const findIoIndex = (array: t.ArrayExpression, target: { key?: string; index?: number }) => {
845
- if (typeof target.index === 'number') return target.index
846
- if (!target.key) return -1
847
- const matches = array.elements
848
- .map((element, index) => ({ element, index }))
849
- .filter(
850
- ({ element }) =>
851
- t.isObjectExpression(element) && getStringProperty(element, 'key') === target.key,
852
- )
853
- if (matches.length > 1) {
854
- throw new DataCalcEditingError('ambiguous_key', `IO key is ambiguous: ${target.key}`, {
855
- key: target.key,
856
- count: matches.length,
857
- })
858
- }
859
- return matches[0]?.index ?? -1
860
- }
861
-
862
- const assertInputKeyUnique = (array: t.ArrayExpression, key: string, ignoreIndex?: number) => {
863
- const duplicate = array.elements.some(
864
- (element, index) =>
865
- index !== ignoreIndex &&
866
- t.isObjectExpression(element) &&
867
- getStringProperty(element, 'key') === key,
868
- )
869
- if (duplicate) {
870
- throw new DataCalcEditingError('duplicate_key', `Input key already exists: ${key}`, { key })
871
- }
872
- }
873
-
874
- const buildCalcObject = async (
875
- input: any,
876
- sandboxFile: string,
877
- ctx: EditContext,
878
- stableIdAlias?: string,
879
- ) => {
880
- ctx.typeImports.add('DataCalculationScript')
881
- ctx.valueImports.add('makeId')
882
- ensureReadFileImport(ctx.parsed.ast)
883
-
884
- const properties: t.ObjectProperty[] = [
885
- t.objectProperty(t.identifier('__typename'), t.stringLiteral('DataCalculationScript')),
886
- t.objectProperty(
887
- t.identifier('id'),
888
- input.id
889
- ? t.stringLiteral(input.id)
890
- : makeIdCallExpression('property_bank_calc', stableIdAlias),
891
- ),
892
- ]
893
- if (input.alias)
894
- properties.push(t.objectProperty(t.identifier('alias'), t.stringLiteral(input.alias)))
895
- if (input.title != null)
896
- properties.push(t.objectProperty(t.identifier('title'), t.stringLiteral(input.title)))
897
- if (input.description != null) {
898
- properties.push(
899
- t.objectProperty(t.identifier('description'), t.stringLiteral(input.description)),
900
- )
901
- }
902
- if (input.note != null)
903
- properties.push(t.objectProperty(t.identifier('note'), t.stringLiteral(input.note)))
904
-
905
- properties.push(t.objectProperty(t.identifier('code'), makeCodeReadFileExpression(sandboxFile)))
906
- properties.push(
907
- t.objectProperty(t.identifier('enableAsync'), t.booleanLiteral(!!input.enableAsync)),
908
- )
909
- if (input.triggerMode != null) {
910
- properties.push(
911
- t.objectProperty(t.identifier('triggerMode'), t.stringLiteral(input.triggerMode)),
912
- )
913
- }
914
-
915
- properties.push(
916
- t.objectProperty(
917
- t.identifier('inputs'),
918
- await buildIoArrayExpression('inputs', input.inputs || [], ctx),
919
- ),
920
- )
921
- properties.push(
922
- t.objectProperty(t.identifier('output'), await nullableDataGetterExpression(input.output, ctx)),
923
- )
924
- properties.push(
925
- t.objectProperty(
926
- t.identifier('outputs'),
927
- await buildIoArrayExpression('outputs', input.outputs || [], ctx),
928
- ),
929
- )
930
- properties.push(
931
- t.objectProperty(t.identifier('error'), await nullableDataGetterExpression(input.error, ctx)),
932
- )
933
-
934
- return t.objectExpression(properties)
935
- }
936
-
937
- const createCalcParsedFile = (projectDir: string, absPath: string): ParsedFile => {
938
- const relPath = projectRelativePath(projectDir, absPath)
939
- const source = 'export const dataCalculation = {}\n'
940
- const ast = parseFileSource(source, relPath)
941
- ast.program.body = []
942
- return { ast, source, absPath, relPath }
943
- }
944
-
945
- const newDataCalc = async (projectDir: string, input: any) =>
946
- runOperation(projectDir, 'new_data_calc', input, async () => {
947
- const subspaceDir = resolveSubspaceDir(projectDir, input.subspace)
948
- const dataCalcDir = getCalcDirFromSubspaceDir(subspaceDir)
949
- await mkdir(dataCalcDir, { recursive: true })
950
- const slug = await nextFreeSlug(dataCalcDir, input.alias)
951
- const sandboxFile = `data-calculation-${slug}.sandbox.js`
952
- const calcPath = path.join(dataCalcDir, `data-calculation-${slug}.ts`)
953
- const sandboxPath = path.join(dataCalcDir, sandboxFile)
954
- const parsed = createCalcParsedFile(projectDir, calcPath)
955
- const ctx: EditContext = {
956
- projectDir,
957
- parsed,
958
- references: [],
959
- typeImports: new Set(),
960
- valueImports: new Set(),
961
- }
962
- const stableIdAlias =
963
- !input.id &&
964
- typeof input.alias === 'string' &&
965
- input.alias &&
966
- !(await aliasUsedInCalcs(projectDir, input.alias))
967
- ? input.alias
968
- : undefined
969
- const object = await buildCalcObject(input, sandboxFile, ctx, stableIdAlias)
970
- const declarator = t.variableDeclarator(t.identifier('dataCalculation'), object)
971
- ;(declarator.id as t.Identifier).typeAnnotation = t.tsTypeAnnotation(
972
- t.tsTypeReference(t.identifier('DataCalculationScript')),
973
- )
974
- parsed.ast.program.body.push(
975
- t.exportNamedDeclaration(t.variableDeclaration('const', [declarator])),
976
- )
977
- applyPendingImports(ctx)
978
-
979
- await writeFile(sandboxPath, wrapSandboxCode(input.code))
980
- await writeParsedFile(parsed)
981
- const touchedSites = [
982
- { file: projectRelativePath(projectDir, calcPath), action: 'create_calc' },
983
- { file: projectRelativePath(projectDir, sandboxPath), action: 'write_sandbox' },
984
- ]
985
- touchedSites.push({
986
- file: await regenerateDataCalcIndex(projectDir, dataCalcDir),
987
- action: 'regenerate_index',
988
- })
989
- const rootWiring = await ensureSubspaceRootDataCalcImport(projectDir, subspaceDir)
990
- if (rootWiring?.touched) {
991
- touchedSites.push({ file: rootWiring.touched, action: 'wire_subspace_index' })
992
- }
993
-
994
- const verify = await verifyProject(projectDir, input.verify)
995
- return {
996
- file: projectRelativePath(projectDir, calcPath),
997
- subspace: path.basename(subspaceDir),
998
- calc: slug,
999
- idExpression:
1000
- input.id ??
1001
- (stableIdAlias
1002
- ? `makeId('property_bank_calc', '${stableIdAlias}')`
1003
- : "makeId('property_bank_calc')"),
1004
- outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1005
- touchedSites,
1006
- ...(rootWiring?.warning ? { warnings: [rootWiring.warning] } : {}),
1007
- verify,
1008
- references: referenceInputDetails(ctx.references),
1009
- summary: `created data calc ${slug} in ${path.basename(subspaceDir)} -> ${verify.status}`,
1010
- }
1011
- })
1012
-
1013
- const editDataCalc = async (projectDir: string, input: any) =>
1014
- runOperation(projectDir, 'edit_data_calc', input, async () => {
1015
- const target = await resolveCalcTarget(projectDir, input)
1016
- const ctx: EditContext = {
1017
- projectDir,
1018
- parsed: target.parsed,
1019
- references: [],
1020
- typeImports: new Set(),
1021
- valueImports: new Set(),
1022
- }
1023
- const touchedSites: Array<Record<string, unknown>> = []
1024
-
1025
- for (const [key, value] of Object.entries(input.set || {})) {
1026
- if (key === 'output' || key === 'error') {
1027
- setObjectProperty(target.object, key, await nullableDataGetterExpression(value, ctx))
1028
- } else if (key === 'inputs' || key === 'outputs') {
1029
- if (!Array.isArray(value)) {
1030
- throw new DataCalcEditingError('invalid_value', `${key} must be an array of IO items`)
1031
- }
1032
- setObjectProperty(target.object, key, await buildIoArrayExpression(key, value, ctx))
1033
- } else if (key === 'code') {
1034
- throw new DataCalcEditingError(
1035
- 'invalid_field',
1036
- 'Set code via the dedicated code parameter so it stays normalized to the sandbox file',
1037
- )
1038
- } else {
1039
- setObjectProperty(target.object, key, await expressionFromInput(value, ctx))
1040
- }
1041
- }
1042
- for (const key of input.unset || []) {
1043
- if (requiredCalcFields.has(key)) {
1044
- throw new DataCalcEditingError('invalid_field', `Cannot unset required field: ${key}`, {
1045
- field: key,
1046
- })
1047
- }
1048
- removeObjectProperty(target.object, key)
1049
- }
1050
-
1051
- if (input.code != null) {
1052
- const codeExpression = getCodeExpression(target.object)
1053
- if (!isRecognizedCodeExpression(codeExpression)) {
1054
- throw new DataCalcEditingError(
1055
- 'fallback_recommended',
1056
- `Data calc ${target.parsed.relPath} has an unsupported code expression. Edit this file directly for this one.`,
1057
- { file: target.parsed.relPath, field: 'code' },
1058
- )
1059
- }
1060
- const sandboxFile = target.sandboxFile
1061
- const sandboxPath = path.join(path.dirname(target.parsed.absPath), sandboxFile)
1062
- await writeFile(sandboxPath, wrapSandboxCode(input.code))
1063
- ensureReadFileImport(target.parsed.ast)
1064
- setObjectProperty(target.object, 'code', makeCodeReadFileExpression(sandboxFile))
1065
- touchedSites.push({
1066
- file: projectRelativePath(projectDir, sandboxPath),
1067
- action: 'write_sandbox',
1068
- })
1069
- }
1070
-
1071
- applyPendingImports(ctx)
1072
- await writeParsedFile(target.parsed)
1073
- touchedSites.unshift({ file: target.parsed.relPath, action: 'edit_calc' })
1074
- const verify = await verifyProject(projectDir, input.verify)
1075
- return {
1076
- file: target.parsed.relPath,
1077
- calc: target.slug,
1078
- outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1079
- touchedSites,
1080
- verify,
1081
- references: referenceInputDetails(ctx.references),
1082
- summary: `edited data calc ${target.slug} -> ${verify.status}`,
1083
- }
1084
- })
1085
-
1086
- const editDataCalcIo = async (projectDir: string, input: any) =>
1087
- runOperation(projectDir, 'edit_data_calc_io', input, async () => {
1088
- const target = await resolveCalcTarget(projectDir, input)
1089
- const ctx: EditContext = {
1090
- projectDir,
1091
- parsed: target.parsed,
1092
- references: [],
1093
- typeImports: new Set(),
1094
- valueImports: new Set(),
1095
- }
1096
- const field = input.field as 'inputs' | 'outputs'
1097
- const array = getOrCreateArrayProperty(target.object, field)
1098
- const op = input.op
1099
-
1100
- if (op === 'clear') {
1101
- array.elements = []
1102
- } else if (op === 'remove') {
1103
- const index = findIoIndex(array, input)
1104
- if (index < 0 || index >= array.elements.length) {
1105
- throw new DataCalcEditingError('invalid_index', 'remove requires a valid key or index')
1106
- }
1107
- array.elements.splice(index, 1)
1108
- } else if (op === 'add' || op === 'replace') {
1109
- const index = op === 'replace' ? findIoIndex(array, input) : input.index
1110
- if (op === 'replace' && (index < 0 || index >= array.elements.length)) {
1111
- throw new DataCalcEditingError('invalid_index', 'replace requires a valid key or index')
1112
- }
1113
- if (
1114
- op === 'add' &&
1115
- typeof index === 'number' &&
1116
- (index < 0 || index > array.elements.length)
1117
- ) {
1118
- throw new DataCalcEditingError('invalid_index', 'add index out of range', { index })
1119
- }
1120
- if (field === 'inputs')
1121
- assertInputKeyUnique(array, input.key, op === 'replace' ? index : undefined)
1122
- const item = await buildIoObject(field, input, ctx)
1123
- if (op === 'replace') array.elements[index] = item
1124
- else array.elements.splice(typeof index === 'number' ? index : array.elements.length, 0, item)
1125
- } else {
1126
- throw new DataCalcEditingError('invalid_op', `Unsupported edit_data_calc_io op: ${op}`)
1127
- }
1128
-
1129
- applyPendingImports(ctx)
1130
- await writeParsedFile(target.parsed)
1131
- const verify = await verifyProject(projectDir, input.verify)
1132
- return {
1133
- file: target.parsed.relPath,
1134
- calc: target.slug,
1135
- outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1136
- change: { field, op, key: input.key, index: input.index },
1137
- verify,
1138
- references: referenceInputDetails(ctx.references),
1139
- summary: `${op} ${field} on data calc ${target.slug} -> ${verify.status}`,
1140
- }
1141
- })
1142
-
1143
- const removeDataCalc = async (projectDir: string, input: any) =>
1144
- runOperation(projectDir, 'remove_data_calc', input, async () => {
1145
- const target = await resolveCalcTarget(projectDir, input)
1146
- const dataCalcDir = path.dirname(target.parsed.absPath)
1147
- const sandboxPath = path.join(dataCalcDir, target.sandboxFile)
1148
- await rm(target.parsed.absPath, { force: true })
1149
- await rm(sandboxPath, { force: true })
1150
- const indexRelPath = await regenerateDataCalcIndex(projectDir, dataCalcDir)
1151
- const verify = await verifyProject(projectDir, input.verify)
1152
- return {
1153
- file: target.parsed.relPath,
1154
- calc: target.slug,
1155
- outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1156
- touchedSites: [
1157
- { file: target.parsed.relPath, action: 'delete_calc' },
1158
- { file: projectRelativePath(projectDir, sandboxPath), action: 'delete_sandbox' },
1159
- { file: indexRelPath, action: 'regenerate_index' },
1160
- ],
1161
- verify,
1162
- summary: `removed data calc ${target.slug} -> ${verify.status}`,
1163
- }
1164
- })
1165
-
1166
- const valueSchema = z
1167
- .any()
1168
- .describe(
1169
- 'Value grammar: JSON literals, bare data ref strings for output/error/IO data, { ref, subspace }, or { expr: "raw TypeScript expression" }.',
1170
- )
1171
- const fileSchema = z
1172
- .string()
1173
- .describe(
1174
- 'Project-relative data-calc file path, for example subspaces/subspace-0/data-calc/data-calculation-total.ts.',
1175
- )
1176
- const subspaceSchema = z
1177
- .union([z.string(), z.number()])
1178
- .describe(
1179
- 'Subspace locator. Defaults to subspace-0; accepts 0, "0", "subspace-0", or a project-relative subspace path.',
1180
- )
1181
- const calcSchema = z
1182
- .string()
1183
- .describe('Data calc locator inside the subspace: alias, explicit string id, or filename slug.')
1184
- const verifySchema = z
1185
- .boolean()
1186
- .describe(
1187
- 'Override compile verification. Defaults to BRICKS_CTOR_MCP_EDIT_VERIFY, otherwise true.',
1188
- )
1189
- const targetSchema = {
1190
- file: fileSchema.optional(),
1191
- subspace: subspaceSchema.optional(),
1192
- calc: calcSchema.optional(),
1193
- verify: verifySchema.optional(),
1194
- }
1195
- const ioItemSchema = z
1196
- .object({
1197
- key: z.string().describe('Sandbox input/output key, for example "price" or "total".'),
1198
- data: valueSchema.describe('Data ref as alias/id/varName, { ref, subspace }, or { expr }.'),
1199
- trigger: z.boolean().describe('Inputs only; defaults true.').optional(),
1200
- })
1201
- .describe('DataCalculationScript IO item.')
1202
-
1203
- export function register(server: McpServer, projectDir: string) {
1204
- server.tool(
1205
- 'new_data_calc',
1206
- 'Create a standard DataCalculationScript in data-calc/{calc}.ts plus its sandbox JS file, regenerate data-calc/index.ts, and wire minimal subspace indexes.',
1207
- {
1208
- subspace: subspaceSchema.optional(),
1209
- alias: z.string().describe('Optional alias; also drives the filename slug.').optional(),
1210
- title: z.string().describe('Optional title.').optional(),
1211
- description: z.string().describe('Optional description.').optional(),
1212
- note: z.string().describe('Optional script note.').optional(),
1213
- triggerMode: z
1214
- .enum(['auto', 'manual'])
1215
- .describe('Optional trigger mode; omitted by default.')
1216
- .optional(),
1217
- enableAsync: z
1218
- .boolean()
1219
- .describe('Whether the sandbox main may be async. Defaults false.')
1220
- .optional(),
1221
- code: z
1222
- .string()
1223
- .describe(
1224
- 'Sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.',
1225
- )
1226
- .optional(),
1227
- inputs: z
1228
- .array(ioItemSchema)
1229
- .describe('Initial script inputs. Input keys must be unique.')
1230
- .optional(),
1231
- outputs: z
1232
- .array(ioItemSchema)
1233
- .describe('Initial fan-out outputs. Output keys may repeat.')
1234
- .optional(),
1235
- output: valueSchema.describe('Single output data ref or null.').optional(),
1236
- error: valueSchema.describe('Error output data ref or null.').optional(),
1237
- id: z
1238
- .string()
1239
- .describe(
1240
- "Optional explicit id. Defaults to source expression makeId('property_bank_calc').",
1241
- )
1242
- .optional(),
1243
- verify: verifySchema.optional(),
1244
- },
1245
- async (input: any) => responseFor(await newDataCalc(projectDir, input)),
1246
- )
1247
-
1248
- server.tool(
1249
- 'edit_data_calc',
1250
- 'Edit DataCalculationScript scalar fields, output/error refs, or sandbox code. Code edits normalize inline code to sandbox file-form.',
1251
- {
1252
- ...targetSchema,
1253
- set: z
1254
- .record(
1255
- z
1256
- .string()
1257
- .describe(
1258
- 'Top-level field path such as title, description, note, alias, triggerMode, enableAsync, output, or error.',
1259
- ),
1260
- valueSchema,
1261
- )
1262
- .describe(
1263
- 'Fields to set. output/error accept bare data ref strings, { ref, subspace }, { expr }, or null; inputs/outputs accept whole replacement arrays of { key, data, trigger? }. Use the code parameter for code.',
1264
- )
1265
- .optional(),
1266
- unset: z.array(z.string()).describe('Top-level fields to remove.').optional(),
1267
- code: z
1268
- .string()
1269
- .describe(
1270
- 'Replacement sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.',
1271
- )
1272
- .optional(),
1273
- },
1274
- async (input: any) => responseFor(await editDataCalc(projectDir, input)),
1275
- )
1276
-
1277
- server.tool(
1278
- 'edit_data_calc_io',
1279
- 'Edit DataCalculationScript inputs or outputs arrays. Inputs require unique keys; outputs may repeat keys for fan-out.',
1280
- {
1281
- ...targetSchema,
1282
- field: z.enum(['inputs', 'outputs']).describe('Which IO array to edit.'),
1283
- op: z.enum(['add', 'remove', 'replace', 'clear']).describe('Array operation.'),
1284
- key: z
1285
- .string()
1286
- .describe('IO key target. Ambiguous repeated output keys must use index.')
1287
- .optional(),
1288
- index: z.number().describe('Zero-based IO index target or add insertion index.').optional(),
1289
- data: valueSchema
1290
- .describe('For add/replace: data ref as string, { ref, subspace }, or { expr }.')
1291
- .optional(),
1292
- trigger: z.boolean().describe('Inputs only; defaults true.').optional(),
1293
- },
1294
- async (input: any) => responseFor(await editDataCalcIo(projectDir, input)),
1295
- )
1296
-
1297
- server.tool(
1298
- 'remove_data_calc',
1299
- 'Remove a standard DataCalculationScript .ts file plus its sandbox file and regenerate data-calc/index.ts. No reverse cascade is needed.',
1300
- targetSchema,
1301
- async (input: any) => responseFor(await removeDataCalc(projectDir, input)),
1302
- )
1303
- }
1304
-
1305
- export const __test__ = {
1306
- newDataCalc,
1307
- editDataCalc,
1308
- editDataCalcIo,
1309
- removeDataCalc,
1310
- resolveCalcTarget,
1311
- }