@ai-matrx/code-runtime 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1196 @@
1
+ "use client";
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ GATE_LISTS: () => GATE_LISTS,
35
+ SCOPE_ENTRIES: () => SCOPE_ENTRIES,
36
+ buildDangerousGlobalStubs: () => buildDangerousGlobalStubs,
37
+ buildScope: () => buildScope,
38
+ compile: () => compile,
39
+ compileAsync: () => compileAsync,
40
+ compileSource: () => compileSource,
41
+ componentSourceGate: () => componentSourceGate,
42
+ coreEntryPaths: () => coreEntryPaths,
43
+ createCompileCache: () => createCompileCache,
44
+ createUnresolvedImportStandIn: () => createUnresolvedImportStandIn,
45
+ defaultCompileCache: () => defaultCompileCache,
46
+ defaultComponentEntries: () => defaultComponentEntries,
47
+ describeUnresolved: () => describeUnresolved,
48
+ detectEntries: () => detectEntries,
49
+ executeGraph: () => executeGraph,
50
+ gate: () => gate,
51
+ getScopeEntry: () => getScopeEntry,
52
+ kindComponentCompiler: () => kindComponentCompiler,
53
+ listScopeEntries: () => listScopeEntries,
54
+ listScopeEntryPaths: () => listScopeEntryPaths,
55
+ prepareScope: () => prepareScope,
56
+ provideScopeModules: () => provideScopeModules,
57
+ readUnresolvedImportMark: () => readUnresolvedImportMark,
58
+ resetScopeModules: () => resetScopeModules,
59
+ transformFiles: () => transformFiles
60
+ });
61
+ module.exports = __toCommonJS(src_exports);
62
+
63
+ // src/gate-lists.json
64
+ var gate_lists_default = {
65
+ _comment: [
66
+ "CANONICAL, MACHINE-READABLE source-gate lists for stored code compiled by @ai-matrx/code-runtime.",
67
+ "ONE list per rule, sorted, byte-comparable across runtimes. Three guards keep the copies honest:",
68
+ " - src/gate.test.ts asserts allowedImports equals listScopeEntryPaths() sorted",
69
+ " (the documented scope registry is the truth);",
70
+ " - aidream packages/matrx-ai/tests/test_component_source_gate_parity.py asserts the Python",
71
+ " twins in kind_shared.py equal these arrays;",
72
+ " - the database trigger's parity test asserts the trigger names every entry of every",
73
+ " security list below."
74
+ ],
75
+ allowedImports: [
76
+ "@/applets",
77
+ "@/components/Markdown",
78
+ "@/components/MarkdownStream",
79
+ "@/components/agent-copy/CopyButtons",
80
+ "@/components/agent-copy/CopyForAiButton",
81
+ "@/components/kind-kit/KindHeaderBar",
82
+ "@/components/kind-kit/KindPanel",
83
+ "@/components/kind-kit/KindPanelGrid",
84
+ "@/components/kind-kit/SortableList",
85
+ "@/components/kind-kit/StreamingSkeleton",
86
+ "@/components/kind-kit/TagList",
87
+ "@/components/mardown",
88
+ "@/components/markdown",
89
+ "@/components/official/icons/IconResolver",
90
+ "@/components/ui/accordion",
91
+ "@/components/ui/alert",
92
+ "@/components/ui/avatar",
93
+ "@/components/ui/badge",
94
+ "@/components/ui/button",
95
+ "@/components/ui/card",
96
+ "@/components/ui/checkbox",
97
+ "@/components/ui/collapsible",
98
+ "@/components/ui/dialog",
99
+ "@/components/ui/dropdown-menu",
100
+ "@/components/ui/input",
101
+ "@/components/ui/label",
102
+ "@/components/ui/popover",
103
+ "@/components/ui/progress",
104
+ "@/components/ui/radio-group",
105
+ "@/components/ui/scroll-area",
106
+ "@/components/ui/select",
107
+ "@/components/ui/separator",
108
+ "@/components/ui/sheet",
109
+ "@/components/ui/skeleton",
110
+ "@/components/ui/slider",
111
+ "@/components/ui/switch",
112
+ "@/components/ui/table",
113
+ "@/components/ui/tabs",
114
+ "@/components/ui/textarea",
115
+ "@/components/ui/tooltip",
116
+ "@/lib/utils",
117
+ "@ai-matrx/applets/react",
118
+ "@ai-matrx/design-system",
119
+ "@ai-matrx/design-system/controls",
120
+ "@ai-matrx/icons",
121
+ "@react-three/fiber",
122
+ "date-fns",
123
+ "lodash",
124
+ "lucide-react",
125
+ "motion/react",
126
+ "react",
127
+ "react-katex",
128
+ "react-pdf",
129
+ "recharts",
130
+ "three",
131
+ "xlsx"
132
+ ],
133
+ bannedGlobals: [
134
+ "EventSource",
135
+ "WebSocket",
136
+ "XMLHttpRequest",
137
+ "fetch",
138
+ "importScripts",
139
+ "localStorage",
140
+ "sessionStorage"
141
+ ],
142
+ bannedCallables: [
143
+ "Function",
144
+ "eval"
145
+ ],
146
+ bannedMemberAccess: [
147
+ "EventSource",
148
+ "Function",
149
+ "WebSocket",
150
+ "XMLHttpRequest",
151
+ "cookie",
152
+ "eval",
153
+ "fetch",
154
+ "importScripts",
155
+ "sendBeacon"
156
+ ],
157
+ bannedMemberCalls: [
158
+ "constructor"
159
+ ],
160
+ bannedComputedAccess: [
161
+ "globalThis",
162
+ "self",
163
+ "window"
164
+ ],
165
+ bannedSyntax: [
166
+ "dynamicImport"
167
+ ]
168
+ };
169
+
170
+ // src/gate.ts
171
+ var GATE_ALLOWED_IMPORTS = gate_lists_default.allowedImports;
172
+ var GATE_BANNED_GLOBALS = gate_lists_default.bannedGlobals;
173
+ var GATE_BANNED_CALLABLES = gate_lists_default.bannedCallables;
174
+ var GATE_BANNED_MEMBER_ACCESS = gate_lists_default.bannedMemberAccess;
175
+ var GATE_BANNED_MEMBER_CALLS = gate_lists_default.bannedMemberCalls;
176
+ var GATE_BANNED_COMPUTED_ACCESS = gate_lists_default.bannedComputedAccess;
177
+ var GATE_BANNED_SYNTAX = gate_lists_default.bannedSyntax;
178
+ var GATE_LISTS = gate_lists_default;
179
+ var IMPORT_RE = /^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm;
180
+ var EXPORT_FROM_RE = /^\s*export\s+(?:\*|\{[^}]*\})\s+from\s+['"]([^'"]+)['"]/gm;
181
+ var DYNAMIC_IMPORT_RE = /(?<![.\w$])import\s*\(/g;
182
+ function escapeForRegExp(value) {
183
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
184
+ }
185
+ function lineAt(source, index) {
186
+ let line = 1;
187
+ for (let i = 0; i < index && i < source.length; i++) {
188
+ if (source.charCodeAt(i) === 10) line++;
189
+ }
190
+ return line;
191
+ }
192
+ function resolveRelativePath(fromFile, specifier) {
193
+ const base = fromFile.split("/").slice(0, -1);
194
+ for (const part of specifier.split("/")) {
195
+ if (part === "" || part === ".") continue;
196
+ if (part === "..") base.pop();
197
+ else base.push(part);
198
+ }
199
+ return base.join("/");
200
+ }
201
+ var RESOLVE_SUFFIXES = ["", ".tsx", ".ts", ".jsx", ".js", ".json", "/index.tsx", "/index.ts", "/index.jsx", "/index.js"];
202
+ function resolveRelativeFile(files, fromFile, specifier) {
203
+ const target = resolveRelativePath(fromFile, specifier);
204
+ for (const suffix of RESOLVE_SUFFIXES) {
205
+ const candidate = `${target}${suffix}`;
206
+ if (Object.prototype.hasOwnProperty.call(files, candidate)) return candidate;
207
+ }
208
+ return null;
209
+ }
210
+ var ALLOWED_SENTENCE = "Rewrite it using only the documented scope (react, lucide-react, recharts, @ai-matrx/design-system/controls, @ai-matrx/design-system, @/lib/utils, @/components/ui/*, @/components/kind-kit/*, CopyButtons/CopyForAiButton, Markdown) or a file of this component.";
211
+ function importFindings(files, file, source) {
212
+ const out = [];
213
+ const allowed = new Set(GATE_ALLOWED_IMPORTS);
214
+ for (const re of [IMPORT_RE, EXPORT_FROM_RE]) {
215
+ re.lastIndex = 0;
216
+ let match;
217
+ while ((match = re.exec(source)) !== null) {
218
+ const path = match[1] ?? "";
219
+ const line = lineAt(source, match.index + match[0].indexOf(path));
220
+ if (path.startsWith("./") || path.startsWith("../")) {
221
+ if (!resolveRelativeFile(files, file, path)) {
222
+ out.push({
223
+ rule: "relative-import-missing",
224
+ file,
225
+ line,
226
+ severity: "refuse",
227
+ message: `This file imports "${path}", but no file of this component has that name. Add the file or fix the path.`
228
+ });
229
+ }
230
+ continue;
231
+ }
232
+ if (!allowed.has(path)) {
233
+ out.push({
234
+ rule: "import-not-allowed",
235
+ file,
236
+ line,
237
+ severity: "refuse",
238
+ message: `This component imports "${path}", which is outside the sandbox scope, so it would render as a marked placeholder. ${ALLOWED_SENTENCE}`
239
+ });
240
+ }
241
+ }
242
+ }
243
+ DYNAMIC_IMPORT_RE.lastIndex = 0;
244
+ const dyn = DYNAMIC_IMPORT_RE.exec(source);
245
+ if (dyn) {
246
+ out.push({
247
+ rule: "dynamicImport",
248
+ file,
249
+ line: lineAt(source, dyn.index),
250
+ severity: "refuse",
251
+ message: "This component uses a dynamic import(). The in-page compiler has no module loader, so the call would either fail at render or reach code nobody vetted. Import from the scope at the top of the file instead."
252
+ });
253
+ }
254
+ return out;
255
+ }
256
+ function bannedGlobalMessage(name) {
257
+ return `This component uses "${name}", which components stored in the database may not use. They run inside the signed-in page, so anything that reaches the network, browser storage, or the JavaScript evaluator could read or send the reader's data. Render what the Shape hands you in props.data and use a Shape action for anything the component needs from the server.`;
258
+ }
259
+ function bannedMemberCallMessage(name) {
260
+ return `This component uses ".${name}(", which components stored in the database may not use. Calling a value's constructor reaches the JavaScript evaluator, so it could run code nobody reviewed inside the signed-in page. Write the logic out directly instead.`;
261
+ }
262
+ function bannedComputedAccessMessage(name) {
263
+ return `This component uses "${name}[", which components stored in the database may not use. Looking a property up by a computed name hides which browser capability the component reaches, so no review can tell whether it is safe. Name what you need directly, or use props.data and a Shape action for anything the component needs from the server.`;
264
+ }
265
+ function globalFindings(file, code) {
266
+ const out = [];
267
+ const push = (rule, re, message) => {
268
+ const m = re.exec(code);
269
+ if (m) out.push({ rule, file, line: lineAt(code, m.index), severity: "refuse", message });
270
+ };
271
+ for (const name of GATE_BANNED_GLOBALS) {
272
+ push("bannedGlobal", new RegExp(`(?<![.\\w$])${escapeForRegExp(name)}\\b`), bannedGlobalMessage(name));
273
+ }
274
+ for (const name of GATE_BANNED_CALLABLES) {
275
+ const e = escapeForRegExp(name);
276
+ push("bannedCallable", new RegExp(`\\bnew\\s+${e}\\s*\\(|(?<![.\\w$])${e}\\s*\\(`), bannedGlobalMessage(name));
277
+ }
278
+ for (const name of GATE_BANNED_MEMBER_ACCESS) {
279
+ push("bannedMemberAccess", new RegExp(`\\.\\s*${escapeForRegExp(name)}\\b`), bannedGlobalMessage(name));
280
+ }
281
+ for (const name of GATE_BANNED_MEMBER_CALLS) {
282
+ push("bannedMemberCall", new RegExp(`\\.\\s*${escapeForRegExp(name)}\\s*\\(`), bannedMemberCallMessage(name));
283
+ }
284
+ for (const name of GATE_BANNED_COMPUTED_ACCESS) {
285
+ const e = escapeForRegExp(name);
286
+ push("bannedComputedAccess", new RegExp(`(?<![.\\w$])${e}\\s*\\[|\\.\\s*${e}\\s*\\[`), bannedComputedAccessMessage(name));
287
+ }
288
+ return out;
289
+ }
290
+ function gate(files) {
291
+ const out = [];
292
+ for (const [file, source] of Object.entries(files)) {
293
+ if (/\.(html?|json|css|md)$/i.test(file)) continue;
294
+ const code = source ?? "";
295
+ out.push(...importFindings(files, file, code), ...globalFindings(file, code));
296
+ }
297
+ return out;
298
+ }
299
+ function componentSourceGate(source, options) {
300
+ if ((options?.flavor ?? "").toLowerCase() === "html") return null;
301
+ const finding = gate({ "component.tsx": source ?? "" }).find((f) => f.severity === "refuse");
302
+ return finding ? finding.message : null;
303
+ }
304
+
305
+ // src/scope/entries.ts
306
+ var REACT_EXPORTS = [
307
+ "useState",
308
+ "useEffect",
309
+ "useMemo",
310
+ "useCallback",
311
+ "useRef",
312
+ "useReducer",
313
+ "useContext",
314
+ "useId",
315
+ "useTransition",
316
+ "useDeferredValue",
317
+ "useLayoutEffect",
318
+ "Fragment"
319
+ ];
320
+ function ui(name, exports, description) {
321
+ return { path: `@/components/ui/${name}`, strategy: "named", exports, core: true, owner: "package", description };
322
+ }
323
+ function markdownAlias(path, description) {
324
+ return { path, strategy: "named", exportMap: { default: "MarkdownStream" }, core: true, owner: "host", description };
325
+ }
326
+ function kindKit(name, exports, description) {
327
+ return { path: `@/components/kind-kit/${name}`, strategy: "named", exports, owner: "host", description };
328
+ }
329
+ var SCOPE_ENTRIES = [
330
+ // ── Core ─────────────────────────────────────────────────────────────────
331
+ { path: "react", strategy: "named", exports: REACT_EXPORTS, exportMap: { default: "React" }, core: true, owner: "package", description: "React core (hooks, Fragment)" },
332
+ { path: "lucide-react", strategy: "spread", safeProxy: true, core: true, owner: "package", description: "Lucide icons; a missing name renders a marked placeholder" },
333
+ { path: "@ai-matrx/icons", strategy: "named", exports: ["DynamicIcon", "renderIcon", "getIconComponent"], core: true, owner: "package", description: "DynamicIcon: any icon by string name" },
334
+ { path: "@/components/official/icons/IconResolver", strategy: "named", exports: ["DynamicIcon", "renderIcon", "getIconComponent"], core: true, owner: "package", description: "Legacy alias of @ai-matrx/icons" },
335
+ { path: "@/lib/utils", strategy: "named", exports: ["cn"], core: true, owner: "package", description: "cn(): className merge" },
336
+ // ── The primary UI set ───────────────────────────────────────────────────
337
+ { path: "@ai-matrx/design-system/controls", strategy: "spread", core: true, owner: "package", description: "THE controls: Button, Field, SearchField, Select, SegmentedControl, Tabs, Badge, Switch, Textarea, EmptyState\u2026" },
338
+ { path: "@ai-matrx/design-system", strategy: "spread", owner: "package", description: "Design-system surfaces: Card, Dialog, Popover, Tooltip, Table, Accordion\u2026" },
339
+ // ── Copy actions ─────────────────────────────────────────────────────────
340
+ { path: "@/components/agent-copy/CopyButtons", strategy: "named", exports: ["CopyButtons"], owner: "host", description: "Copy / Copy-for-AI / JSON / Export bar from caller-supplied builders" },
341
+ { path: "@/components/agent-copy/CopyForAiButton", strategy: "named", exports: ["CopyForAiButton"], owner: "host", description: "Single Copy-for-AI action" },
342
+ // ── kind-kit ─────────────────────────────────────────────────────────────
343
+ kindKit("SortableList", ["SortableList"], "Drag-to-reorder list with arrow fallback and onRemove"),
344
+ kindKit("KindPanelGrid", ["KindPanelGrid"], "Content-aware auto-fit grid of equal-height panels"),
345
+ kindKit("KindPanel", ["KindPanel"], "Compact panel: header + overflow menu, subline, body, footer"),
346
+ kindKit("KindHeaderBar", ["KindHeaderBar"], "Kind title + stats + copy bar"),
347
+ kindKit("StreamingSkeleton", ["StreamingSkeleton", "useStreamingValue", "streamList", "streamText"], "Streaming skeletons + tolerant partial-value reads"),
348
+ kindKit("TagList", ["KeywordChip", "TagList"], "Wrapping chips with select, remove, inline edit, add"),
349
+ // ── Markdown (one renderer, four spellings stored code uses) ─────────────
350
+ markdownAlias("@/components/MarkdownStream", "MarkdownStream: the one markdown renderer"),
351
+ markdownAlias("@/components/Markdown", "MarkdownStream (legacy path)"),
352
+ markdownAlias("@/components/markdown", "MarkdownStream (lowercase path)"),
353
+ markdownAlias("@/components/mardown", "MarkdownStream (common misspelling)"),
354
+ // ── Legacy UI aliases (each = the design-system export the app re-exports) ─
355
+ ui("button", ["Button"], "Button"),
356
+ ui("input", ["Input"], "Input"),
357
+ ui("textarea", ["Textarea"], "Textarea"),
358
+ ui("card", ["Card", "CardAction", "CardContent", "CardDescription", "CardFooter", "CardHeader", "CardTitle"], "Card family"),
359
+ ui("label", ["Label"], "Label"),
360
+ ui("select", ["Select", "SelectContent", "SelectGroup", "SelectItem", "SelectLabel", "SelectScrollDownButton", "SelectScrollUpButton", "SelectSeparator", "SelectValue", "selectTriggerVariants", "SelectTrigger", "SelectTriggerLegacy"], "Select family"),
361
+ ui("slider", ["Slider"], "Slider"),
362
+ ui("switch", ["Switch"], "Switch"),
363
+ ui("tabs", ["Tabs", "TabsContent", "TabsList", "TabsTrigger", "TabsTriggerCore", "TabsListLegacy", "TabsTriggerLegacy", "TabsTriggerCoreLegacy"], "Tabs family"),
364
+ ui("badge", ["Badge"], "Badge"),
365
+ ui("tooltip", ["Tooltip", "TooltipContent", "TooltipProvider", "TooltipTrigger"], "Tooltip family"),
366
+ ui("accordion", ["Accordion", "AccordionContent", "AccordionItem", "AccordionTrigger", "useAccordionSize"], "Accordion family"),
367
+ ui("collapsible", ["Collapsible", "CollapsibleContent", "CollapsibleTrigger"], "Collapsible family"),
368
+ ui("progress", ["Progress"], "Progress bar"),
369
+ ui("separator", ["Separator"], "Separator"),
370
+ ui("scroll-area", ["ScrollArea", "ScrollBar"], "ScrollArea"),
371
+ ui("dialog", ["Dialog", "DialogClose", "DialogContent", "DialogContentPrimitive", "DialogDescription", "DialogFooter", "DialogHeader", "DialogOverlay", "DialogPortal", "DialogTitle", "DialogTrigger", "useDialogContainer"], "Dialog family"),
372
+ ui("sheet", ["Sheet", "SheetPortal", "SheetOverlay", "SheetTrigger", "SheetClose", "SheetContent", "SheetHeader", "SheetFooter", "SheetTitle", "SheetDescription"], "Sheet family"),
373
+ ui("dropdown-menu", ["DropdownMenu", "DropdownMenuCheckboxItem", "DropdownMenuContent", "DropdownMenuGroup", "DropdownMenuItem", "DropdownMenuLabel", "DropdownMenuPortal", "DropdownMenuRadioGroup", "DropdownMenuRadioItem", "DropdownMenuSeparator", "DropdownMenuShortcut", "DropdownMenuSub", "DropdownMenuSubContent", "DropdownMenuSubTrigger", "DropdownMenuTrigger"], "Dropdown menu family"),
374
+ ui("table", ["Table", "TableBody", "TableCaption", "TableCell", "TableFooter", "TableHead", "TableHeader", "TableRow"], "Table family"),
375
+ ui("checkbox", ["Checkbox"], "Checkbox"),
376
+ ui("radio-group", ["RadioGroup", "RadioGroupItem"], "Radio group"),
377
+ ui("popover", ["Popover", "PopoverTrigger", "PopoverContent", "PopoverAnchor"], "Popover family"),
378
+ ui("avatar", ["Avatar", "AvatarFallback", "AvatarImage"], "Avatar family"),
379
+ ui("alert", ["Alert", "AlertDescription", "AlertTitle", "alertVariants"], "Alert family"),
380
+ ui("skeleton", ["Skeleton"], "Skeleton"),
381
+ // ── Applet parts ─────────────────────────────────────────────────────────
382
+ { path: "@/applets", strategy: "named", exports: ["DataPage", "Applet"], owner: "host", description: "A table-built page and a nested Applet (legacy path; becomes @ai-matrx/applets/react)" },
383
+ { path: "@ai-matrx/applets/react", strategy: "spread", owner: "host", description: "The Applet hooks: useRows, useJob, useValue, useAction, <Kind>, <Pages>, navigate\u2026" },
384
+ // ── Heavy libraries (loaded only when referenced) ────────────────────────
385
+ { path: "recharts", strategy: "spread", owner: "package", provides: ["ResponsiveContainer", "LineChart", "BarChart", "AreaChart", "PieChart", "RadarChart", "ScatterChart", "ComposedChart", "RadialBarChart"], description: "Charts (recharts)" },
386
+ { path: "motion/react", strategy: "spread", owner: "host", provides: ["motion", "AnimatePresence", "useAnimate", "useInView"], description: "Animation (motion)" },
387
+ { path: "react-katex", strategy: "spread", owner: "host", provides: ["BlockMath", "InlineMath"], description: "Math typesetting (KaTeX)" },
388
+ { path: "react-pdf", strategy: "named", exports: ["Document", "Page", "Outline"], owner: "host", provides: ["Document", "Page", "Outline"], description: "PDF viewing (react-pdf)" },
389
+ { path: "xlsx", strategy: "namespace", namespaceName: "XLSX", owner: "host", provides: ["XLSX"], description: "Workbooks (xlsx)" },
390
+ { path: "@react-three/fiber", strategy: "spread", owner: "host", provides: ["Canvas", "useFrame", "useThree", "useLoader"], description: "3D React renderer" },
391
+ { path: "three", strategy: "namespace", namespaceName: "THREE", owner: "host", provides: ["THREE"], description: "3D engine (three.js)" },
392
+ { path: "date-fns", strategy: "namespace", namespaceName: "dateFns", owner: "host", provides: ["dateFns"], description: "Date utilities (date-fns)" },
393
+ { path: "lodash", strategy: "namespace", namespaceName: "_", owner: "host", provides: ["_"], description: "Utility helpers (lodash)" }
394
+ ];
395
+ var BY_PATH = new Map(SCOPE_ENTRIES.map((e) => [e.path, e]));
396
+ function getScopeEntry(path) {
397
+ return BY_PATH.get(path);
398
+ }
399
+ function listScopeEntryPaths() {
400
+ return SCOPE_ENTRIES.map((e) => e.path);
401
+ }
402
+ function listScopeEntries() {
403
+ return SCOPE_ENTRIES;
404
+ }
405
+ function defaultComponentEntries() {
406
+ return SCOPE_ENTRIES.filter((e) => !e.provides || e.path === "recharts").map((e) => e.path);
407
+ }
408
+ function coreEntryPaths() {
409
+ return SCOPE_ENTRIES.filter((e) => e.core).map((e) => e.path);
410
+ }
411
+ function detectEntries(files) {
412
+ const needed = new Set(coreEntryPaths());
413
+ const code = Object.values(files).join("\n");
414
+ const imported = /* @__PURE__ */ new Set();
415
+ for (const m of code.matchAll(/from\s+['"]([^'"]+)['"]/g)) if (m[1]) imported.add(m[1]);
416
+ for (const entry of SCOPE_ENTRIES) {
417
+ if (entry.core) continue;
418
+ if (imported.has(entry.path)) needed.add(entry.path);
419
+ else if (entry.provides?.some((id) => new RegExp(`(?<![\\w$.])${id.replace(/[$]/g, "\\$")}\\b`).test(code))) {
420
+ needed.add(entry.path);
421
+ }
422
+ }
423
+ return SCOPE_ENTRIES.map((e) => e.path).filter((p) => needed.has(p));
424
+ }
425
+
426
+ // src/scope/build.ts
427
+ var ReactModule2 = __toESM(require("react"), 1);
428
+
429
+ // src/scope/modules.ts
430
+ var ReactModule = __toESM(require("react"), 1);
431
+ var LucideModule = __toESM(require("lucide-react"), 1);
432
+ var IconsModule = __toESM(require("@ai-matrx/icons"), 1);
433
+ var DesignSystem = __toESM(require("@ai-matrx/design-system"), 1);
434
+ var Controls = __toESM(require("@ai-matrx/design-system/controls"), 1);
435
+ var STORE_KEY = /* @__PURE__ */ Symbol.for("ai-matrx.code-runtime.modules");
436
+ function store() {
437
+ const g = globalThis;
438
+ let s = g[STORE_KEY];
439
+ if (!s) {
440
+ s = { announced: /* @__PURE__ */ new Set(), provided: /* @__PURE__ */ new Map(), loaded: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), failed: /* @__PURE__ */ new Map() };
441
+ g[STORE_KEY] = s;
442
+ }
443
+ return s;
444
+ }
445
+ var ds = DesignSystem;
446
+ var controls = Controls;
447
+ var LEGACY_UI_MODULE = {
448
+ ...ds,
449
+ Button: controls.Button,
450
+ Textarea: controls.Textarea,
451
+ Switch: controls.Switch,
452
+ SelectTrigger: controls.SelectTrigger,
453
+ SelectTriggerLegacy: ds.SelectTrigger,
454
+ TabsList: controls.TabsList,
455
+ TabsTrigger: controls.TabsTrigger,
456
+ TabsListLegacy: ds.TabsList,
457
+ TabsTriggerLegacy: ds.TabsTrigger
458
+ };
459
+ function packageLoader(path) {
460
+ if (path === "react") return () => ReactModule;
461
+ if (path === "lucide-react") return () => LucideModule;
462
+ if (path === "@ai-matrx/icons" || path === "@/components/official/icons/IconResolver") return () => IconsModule;
463
+ if (path === "@ai-matrx/design-system") return () => DesignSystem;
464
+ if (path === "@ai-matrx/design-system/controls") return () => Controls;
465
+ if (path === "@/lib/utils") return () => ({ cn: ds.cn });
466
+ if (path.startsWith("@/components/ui/")) return () => LEGACY_UI_MODULE;
467
+ if (path === "recharts") return () => import("recharts");
468
+ return null;
469
+ }
470
+ function provideScopeModules(map) {
471
+ const s = store();
472
+ for (const [path, loader] of Object.entries(map)) {
473
+ if (!getScopeEntry(path)) {
474
+ throw new Error(
475
+ `[code-runtime] "${path}" is not a documented scope entry. Add it to the registry in @ai-matrx/code-runtime (scope/entries.ts) with a description first.`
476
+ );
477
+ }
478
+ s.provided.set(path, loader);
479
+ s.loaded.delete(path);
480
+ s.pending.delete(path);
481
+ s.failed.delete(path);
482
+ }
483
+ }
484
+ function isPromiseLike(value) {
485
+ return !!value && typeof value.then === "function";
486
+ }
487
+ function loaderFor(path) {
488
+ return store().provided.get(path) ?? packageLoader(path);
489
+ }
490
+ function readScopeModule(path) {
491
+ const s = store();
492
+ if (s.loaded.has(path)) return { state: "ready", module: s.loaded.get(path) };
493
+ const failed = s.failed.get(path);
494
+ if (failed) return { state: "failed", message: failed };
495
+ if (s.pending.has(path)) return { state: "pending" };
496
+ const loader = loaderFor(path);
497
+ if (!loader) return { state: "missing" };
498
+ try {
499
+ const value = loader();
500
+ if (isPromiseLike(value)) {
501
+ const promise = Promise.resolve(value).then(
502
+ (mod) => {
503
+ s.loaded.set(path, mod);
504
+ s.pending.delete(path);
505
+ return mod;
506
+ },
507
+ (err) => {
508
+ s.failed.set(path, err instanceof Error ? err.message : String(err));
509
+ s.pending.delete(path);
510
+ return void 0;
511
+ }
512
+ );
513
+ s.pending.set(path, promise);
514
+ return { state: "pending" };
515
+ }
516
+ s.loaded.set(path, value);
517
+ return { state: "ready", module: value };
518
+ } catch (err) {
519
+ const message = err instanceof Error ? err.message : String(err);
520
+ s.failed.set(path, message);
521
+ return { state: "failed", message };
522
+ }
523
+ }
524
+ async function prepareScopeModules(paths) {
525
+ const s = store();
526
+ for (const path of paths) readScopeModule(path);
527
+ await Promise.all(paths.map((p) => s.pending.get(p)).filter((p) => !!p));
528
+ }
529
+ function announceFailedModule(path, message) {
530
+ const s = store();
531
+ if (s.announced.has(path)) return;
532
+ s.announced.add(path);
533
+ console.error(`[code-runtime] The scope entry "${path}" failed to load (${message}); code that imports it renders marked placeholders.`);
534
+ }
535
+ function resetScopeModules() {
536
+ const s = store();
537
+ s.announced.clear();
538
+ s.provided.clear();
539
+ s.loaded.clear();
540
+ s.pending.clear();
541
+ s.failed.clear();
542
+ }
543
+
544
+ // src/scope/stand-in.ts
545
+ var React = __toESM(require("react"), 1);
546
+ var UNRESOLVED_IMPORT_MARK = /* @__PURE__ */ Symbol.for("matrx.sandbox.unresolvedImport");
547
+ function readUnresolvedImportMark(value) {
548
+ if (!value || typeof value !== "object" && typeof value !== "function") return null;
549
+ const mark = value[UNRESOLVED_IMPORT_MARK];
550
+ return mark && typeof mark === "object" ? mark : null;
551
+ }
552
+ function createUnresolvedImportStandIn(identifier, importPath = null) {
553
+ const tip = importPath ? `Not found: ${identifier} in "${importPath}"` : `Not found: ${identifier}`;
554
+ const StandIn = React.forwardRef(({ children }, ref) => {
555
+ const chip = React.createElement(
556
+ "span",
557
+ {
558
+ ref,
559
+ title: tip,
560
+ "aria-label": tip,
561
+ role: "note",
562
+ "data-unresolved-import": identifier,
563
+ "data-import-path": importPath ?? void 0,
564
+ className: "inline-flex items-center gap-0.5 rounded border border-dashed border-destructive/60 px-1 align-middle font-mono text-[10px] leading-4 text-destructive"
565
+ },
566
+ React.createElement(
567
+ "svg",
568
+ {
569
+ width: 10,
570
+ height: 10,
571
+ viewBox: "0 0 24 24",
572
+ fill: "none",
573
+ stroke: "currentColor",
574
+ strokeWidth: 2.5,
575
+ strokeLinecap: "round",
576
+ strokeLinejoin: "round",
577
+ "aria-hidden": true
578
+ },
579
+ React.createElement("path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" }),
580
+ React.createElement("line", { x1: 12, y1: 9, x2: 12, y2: 13 }),
581
+ React.createElement("line", { x1: 12, y1: 17, x2: 12.01, y2: 17 })
582
+ ),
583
+ identifier
584
+ );
585
+ return children == null ? chip : React.createElement(React.Fragment, null, chip, children);
586
+ });
587
+ StandIn.displayName = `UnresolvedImport(${identifier})`;
588
+ Object.defineProperty(StandIn, UNRESOLVED_IMPORT_MARK, {
589
+ value: { identifier, importPath },
590
+ enumerable: false
591
+ });
592
+ return StandIn;
593
+ }
594
+ function describeUnresolved(entry) {
595
+ if (entry.identifier === "*") return `"${entry.importPath}" (not in this scope)`;
596
+ return entry.importPath ? `${entry.identifier} from "${entry.importPath}"` : entry.identifier;
597
+ }
598
+ function stripLiteralsForScan(code) {
599
+ return code.replace(/"(?:[^"\\]|\\.)*"/g, '""').replace(/'(?:[^'\\]|\\.)*'/g, "''").replace(/`(?:[^`\\]|\\.)*`/gs, "``");
600
+ }
601
+ function extractJsxComponentIdentifiers(codeForScanning) {
602
+ const components = /* @__PURE__ */ new Set();
603
+ const patterns = [
604
+ // `(?![\w$.])`: `<C.Button>` names the namespace `C`, which is an
605
+ // import or a declaration, never a bare missing component.
606
+ /React\.createElement\s*\(\s*([A-Z][a-zA-Z0-9]*)(?![\w$.])/g,
607
+ /\.default\.createElement\s*\(\s*([A-Z][a-zA-Z0-9]*)(?![\w$.])/g,
608
+ /\bjsxs?\s*\(\s*([A-Z][a-zA-Z0-9]*)(?![\w$.])/g
609
+ ];
610
+ for (const pattern of patterns) {
611
+ let match;
612
+ while ((match = pattern.exec(codeForScanning)) !== null) {
613
+ if (match[1]) components.add(match[1]);
614
+ }
615
+ }
616
+ return components;
617
+ }
618
+ var PATCH_SCOPE_SKIP_IDENTIFIERS = /* @__PURE__ */ new Set([
619
+ "React",
620
+ "Object",
621
+ "Array",
622
+ "String",
623
+ "Number",
624
+ "Boolean",
625
+ "Date",
626
+ "Math",
627
+ "JSON",
628
+ "Promise",
629
+ "Error",
630
+ "TypeError",
631
+ "RangeError",
632
+ "RegExp",
633
+ "Map",
634
+ "Set",
635
+ "WeakMap",
636
+ "WeakSet",
637
+ "Symbol",
638
+ "Proxy",
639
+ "Reflect",
640
+ "Intl",
641
+ "URL",
642
+ "FormData",
643
+ "Headers",
644
+ "Request",
645
+ "Response",
646
+ "AbortController",
647
+ "HTMLElement",
648
+ "SVGElement",
649
+ "Event",
650
+ "MouseEvent",
651
+ "KeyboardEvent",
652
+ "HTMLInputElement",
653
+ "HTMLTextAreaElement",
654
+ "HTMLSelectElement",
655
+ "HTMLButtonElement",
656
+ "HTMLDivElement",
657
+ "HTMLFormElement",
658
+ "Node",
659
+ "Element",
660
+ "Document",
661
+ "Window",
662
+ "Infinity",
663
+ "NaN",
664
+ "Fragment"
665
+ ]);
666
+
667
+ // src/scope/build.ts
668
+ function recordUnresolved(state, entry) {
669
+ if (!state.unresolved.some((e) => e.identifier === entry.identifier && e.importPath === entry.importPath)) {
670
+ state.unresolved.push(entry);
671
+ }
672
+ }
673
+ function asRecord(value) {
674
+ return value && (typeof value === "object" || typeof value === "function") ? value : {};
675
+ }
676
+ function ownKeys(mod) {
677
+ try {
678
+ return Object.keys(mod);
679
+ } catch {
680
+ return [];
681
+ }
682
+ }
683
+ function createSafeModuleProxy(importPath, moduleExports, state) {
684
+ const target = { ...moduleExports, __esModule: true };
685
+ return new Proxy(target, {
686
+ get(t, prop) {
687
+ if (typeof prop !== "string") return Reflect.get(t, prop);
688
+ if (prop in t) return t[prop];
689
+ if (prop.startsWith("_") || prop === "default" || prop === "then") return void 0;
690
+ if (/^[A-Z]/.test(prop)) {
691
+ const fallback = createUnresolvedImportStandIn(prop, importPath);
692
+ t[prop] = fallback;
693
+ recordUnresolved(state, { identifier: prop, importPath });
694
+ return fallback;
695
+ }
696
+ return void 0;
697
+ },
698
+ has(t, prop) {
699
+ if (typeof prop === "string" && /^[A-Z]/.test(prop)) return true;
700
+ return prop in t;
701
+ }
702
+ });
703
+ }
704
+ function moduleView(entry, mod, state) {
705
+ if (entry.strategy === "namespace") {
706
+ const ns = asRecord(mod.default ?? mod);
707
+ return { ...ns, default: ns, __esModule: true };
708
+ }
709
+ if (entry.safeProxy) return createSafeModuleProxy(entry.path, mod, state);
710
+ const view = { ...mod, __esModule: true };
711
+ for (const [moduleKey, scopeKey] of Object.entries(entry.exportMap ?? {})) {
712
+ const value = moduleKey === "default" ? mod.default ?? mod : mod[moduleKey];
713
+ view[scopeKey] = value;
714
+ if (moduleKey === "default") view.default = value;
715
+ }
716
+ if (!("default" in view)) view.default = mod.default;
717
+ return view;
718
+ }
719
+ function applyToFlatScope(entry, mod, values) {
720
+ if (entry.strategy === "namespace") {
721
+ if (entry.namespaceName) values[entry.namespaceName] = mod.default ?? mod;
722
+ return;
723
+ }
724
+ if (entry.strategy === "spread") {
725
+ for (const key of ownKeys(mod)) {
726
+ if (key === "default" || key === "__esModule") continue;
727
+ values[key] = mod[key];
728
+ }
729
+ return;
730
+ }
731
+ for (const name of entry.exports ?? []) values[name] = mod[name];
732
+ for (const [moduleKey, scopeKey] of Object.entries(entry.exportMap ?? {})) {
733
+ values[scopeKey] = moduleKey === "default" ? mod.default ?? mod : mod[moduleKey];
734
+ }
735
+ }
736
+ function buildDangerousGlobalStubs() {
737
+ const stubs = {};
738
+ for (const name of [...gate_lists_default.bannedGlobals, ...gate_lists_default.bannedCallables]) {
739
+ stubs[name] = function bannedGlobal() {
740
+ throw new Error(
741
+ `This component tried to use "${name}". Components stored in the database run inside the signed-in page and may not reach the network, browser storage, or the JavaScript evaluator. Render what the Shape hands you in props.data, and use a Shape action for anything you need from the server.`
742
+ );
743
+ };
744
+ }
745
+ return stubs;
746
+ }
747
+ function buildScopeState(spec) {
748
+ const state = { values: {}, modules: /* @__PURE__ */ new Map(), safeProxyPaths: /* @__PURE__ */ new Map(), unresolved: [], pending: [] };
749
+ const R = ReactModule2;
750
+ state.values.React = R;
751
+ for (const hook of ["useState", "useEffect", "useMemo", "useCallback", "useRef"]) state.values[hook] = R[hook];
752
+ state.modules.set("react", { ...R, default: R, __esModule: true });
753
+ for (const path of spec.entries ?? []) {
754
+ const entry = getScopeEntry(path);
755
+ if (!entry) {
756
+ recordUnresolved(state, { identifier: "*", importPath: path });
757
+ continue;
758
+ }
759
+ const read = readScopeModule(path);
760
+ if (read.state === "pending") {
761
+ state.pending.push(path);
762
+ continue;
763
+ }
764
+ if (read.state === "missing") {
765
+ continue;
766
+ }
767
+ if (read.state === "failed") {
768
+ announceFailedModule(path, read.message);
769
+ continue;
770
+ }
771
+ const mod = asRecord(read.module);
772
+ const view = moduleView(entry, mod, state);
773
+ state.modules.set(path, view);
774
+ if (entry.safeProxy) {
775
+ state.safeProxyPaths.set(path, { proxy: view, keys: new Set(ownKeys(mod)) });
776
+ }
777
+ applyToFlatScope(entry, mod, state.values);
778
+ }
779
+ if (state.values.MarkdownStream && !state.values.Markdown) state.values.Markdown = state.values.MarkdownStream;
780
+ if (!state.values.DynamicIcon) {
781
+ const icons = readScopeModule("@ai-matrx/icons");
782
+ if (icons.state === "ready") {
783
+ const m = asRecord(icons.module);
784
+ state.values.DynamicIcon = m.DynamicIcon;
785
+ state.values.renderIcon = m.renderIcon;
786
+ state.values.getIconComponent = m.getIconComponent;
787
+ }
788
+ }
789
+ const overrides = spec.overrides ?? {};
790
+ Object.assign(state.values, overrides);
791
+ if (Object.keys(overrides).length > 0) {
792
+ for (const [path, view] of state.modules) {
793
+ const entry = getScopeEntry(path);
794
+ for (const [moduleKey, scopeKey] of Object.entries(entry?.exportMap ?? {})) {
795
+ if (!(scopeKey in overrides)) continue;
796
+ view[scopeKey] = overrides[scopeKey];
797
+ if (moduleKey === "default") view.default = overrides[scopeKey];
798
+ else view[moduleKey] = overrides[scopeKey];
799
+ }
800
+ for (const name of entry?.exports ?? []) {
801
+ if (name in overrides) view[name] = overrides[name];
802
+ }
803
+ }
804
+ }
805
+ if (spec.shadowDangerousGlobals) Object.assign(state.values, buildDangerousGlobalStubs());
806
+ return state;
807
+ }
808
+ function buildScope(spec) {
809
+ return { ...buildScopeState(spec).values };
810
+ }
811
+ function patchMissingJsx(identifiers, state, declared, skip) {
812
+ for (const identifier of identifiers) {
813
+ if (skip.has(identifier) || identifier in state.values || declared.has(identifier)) continue;
814
+ let provided = false;
815
+ for (const [, { proxy, keys }] of state.safeProxyPaths) {
816
+ if (!keys.has(identifier)) continue;
817
+ const value = proxy[identifier];
818
+ if (value !== void 0) {
819
+ state.values[identifier] = value;
820
+ const mark = readUnresolvedImportMark(value);
821
+ if (mark) recordUnresolved(state, mark);
822
+ provided = true;
823
+ break;
824
+ }
825
+ }
826
+ if (provided) continue;
827
+ state.values[identifier] = createUnresolvedImportStandIn(identifier);
828
+ recordUnresolved(state, { identifier, importPath: null });
829
+ }
830
+ }
831
+
832
+ // src/execute-core.ts
833
+ var IDENTIFIER_RE = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
834
+ function missingModule(path) {
835
+ const target = { __esModule: true };
836
+ return new Proxy(target, {
837
+ get(t, prop) {
838
+ if (typeof prop !== "string") return Reflect.get(t, prop);
839
+ if (prop in t) return t[prop];
840
+ if (prop === "then" || prop.startsWith("_")) return void 0;
841
+ if (prop === "default" || /^[A-Z]/.test(prop)) {
842
+ const fallback = createUnresolvedImportStandIn(prop === "default" ? path.split("/").pop() ?? path : prop, path);
843
+ t[prop] = fallback;
844
+ return fallback;
845
+ }
846
+ return void 0;
847
+ }
848
+ });
849
+ }
850
+ function bindImports(mod, allFiles, state) {
851
+ for (const binding of mod.importBindings) {
852
+ const { source, imported, local } = binding;
853
+ if (source.startsWith("./") || source.startsWith("../")) {
854
+ if (!resolveRelativeFile(allFiles, mod.file, source)) {
855
+ recordUnresolved(state, { identifier: imported === "*" ? `* as ${local}` : imported, importPath: source });
856
+ }
857
+ continue;
858
+ }
859
+ const view = state.modules.get(source);
860
+ if (!view) {
861
+ recordUnresolved(state, {
862
+ identifier: imported === "*" ? `* as ${local}` : imported === "default" ? local : imported,
863
+ importPath: source
864
+ });
865
+ continue;
866
+ }
867
+ if (imported === "*") continue;
868
+ if (imported === "default") {
869
+ if (view.default === void 0) {
870
+ view.default = createUnresolvedImportStandIn(local, source);
871
+ recordUnresolved(state, { identifier: local, importPath: source });
872
+ }
873
+ continue;
874
+ }
875
+ let present;
876
+ try {
877
+ present = view[imported] !== void 0;
878
+ } catch {
879
+ present = false;
880
+ }
881
+ if (!present) {
882
+ if (/^[A-Z]/.test(imported)) view[imported] = createUnresolvedImportStandIn(imported, source);
883
+ recordUnresolved(state, { identifier: imported === local ? local : `${imported} as ${local}`, importPath: source });
884
+ }
885
+ }
886
+ }
887
+ var CONVENTIONAL_NAMES = /^(App|Main|Page|Component|Demo|Example|Root)$/;
888
+ function pickCandidate(candidates, rule) {
889
+ if (rule === "conventional") {
890
+ const preferred = [...candidates].reverse().find((name) => CONVENTIONAL_NAMES.test(name));
891
+ if (preferred) return preferred;
892
+ }
893
+ return candidates[candidates.length - 1];
894
+ }
895
+ function reportOnce(options, unresolved) {
896
+ if (unresolved.length === 0) return;
897
+ const origin = options?.origin ?? "code-runtime";
898
+ if (options?.onUnresolved) {
899
+ try {
900
+ options.onUnresolved(origin, unresolved);
901
+ } catch {
902
+ }
903
+ return;
904
+ }
905
+ console.warn(`[code-runtime] ${origin}: ${unresolved.map(describeUnresolved).join(", ")} could not be resolved; each renders as a marked placeholder.`);
906
+ }
907
+ function executeGraph(graph, spec, options) {
908
+ const state = buildScopeState(spec);
909
+ const blocking = state.pending.filter((path) => {
910
+ const entry = getScopeEntry(path);
911
+ return Object.values(graph.modules).some(
912
+ (m) => m.importBindings.some((b) => b.source === path) || (entry?.provides ?? []).some((id) => new RegExp(`(?<![\\w$.])${id.replace(/[$]/g, "\\$")}\\b`).test(m.code))
913
+ );
914
+ });
915
+ if (blocking.length > 0) {
916
+ return {
917
+ ok: false,
918
+ error: {
919
+ code: "scope_not_ready",
920
+ message: `The scope entries ${blocking.join(", ")} are still loading. Call prepareScope(spec) before compiling.`,
921
+ retryable: true
922
+ }
923
+ };
924
+ }
925
+ const fileSet = new Set(Object.keys(graph.modules));
926
+ const allFiles = Object.fromEntries([...fileSet].map((f) => [f, ""]));
927
+ for (const mod of Object.values(graph.modules)) bindImports(mod, allFiles, state);
928
+ for (const mod of Object.values(graph.modules)) {
929
+ const ids = extractJsxComponentIdentifiers(stripLiteralsForScan(mod.code));
930
+ patchMissingJsx(ids, state, new Set(mod.declaredTopLevel), PATCH_SCOPE_SKIP_IDENTIFIERS);
931
+ }
932
+ const cache = /* @__PURE__ */ new Map();
933
+ let current = graph.entry;
934
+ const run = (file) => {
935
+ const cached = cache.get(file);
936
+ if (cached) return cached.exports;
937
+ const mod = graph.modules[file];
938
+ if (!mod) return missingModule(file);
939
+ const module2 = { exports: {} };
940
+ const record = { exports: module2.exports, done: false };
941
+ cache.set(file, record);
942
+ const declared = new Set(mod.declaredTopLevel);
943
+ const paramNames = Object.keys(state.values).filter(
944
+ (k) => IDENTIFIER_RE.test(k) && !k.startsWith("__") && !declared.has(k) && k !== "require" && k !== "module" && k !== "exports"
945
+ );
946
+ const paramValues = paramNames.map((k) => state.values[k]);
947
+ const requireFn = (specifier) => {
948
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
949
+ const target = resolveRelativeFile(allFiles, file, specifier);
950
+ if (!target) return missingModule(specifier);
951
+ const prev = current;
952
+ current = target;
953
+ try {
954
+ return run(target);
955
+ } finally {
956
+ current = prev;
957
+ }
958
+ }
959
+ return state.modules.get(specifier) ?? missingModule(specifier);
960
+ };
961
+ const candidate = file === graph.entry ? pickCandidate(mod.componentCandidates, options?.componentCandidate) : void 0;
962
+ const tail = candidate ? `
963
+ ;return typeof ${candidate} !== "undefined" ? ${candidate} : undefined;` : "";
964
+ const factory = new Function(...paramNames, "require", "module", "exports", `${mod.code}${tail}`);
965
+ const returned = factory(...paramValues, requireFn, module2, module2.exports);
966
+ if (module2.exports !== record.exports) record.exports = module2.exports;
967
+ if (returned !== void 0 && record.exports.default === void 0) {
968
+ record.exports.__candidate = returned;
969
+ }
970
+ record.done = true;
971
+ return record.exports;
972
+ };
973
+ try {
974
+ const exportsOfEntry = run(graph.entry);
975
+ const Component = exportsOfEntry.default ?? exportsOfEntry.__candidate;
976
+ const unresolved = [...state.unresolved];
977
+ reportOnce(options, unresolved);
978
+ if (typeof Component !== "function" && !(Component && typeof Component === "object" && "$$typeof" in Component)) {
979
+ return {
980
+ ok: false,
981
+ error: {
982
+ code: "no_component",
983
+ message: "This code compiled but returned nothing to render. Export a React component as the default export of the entry file.",
984
+ retryable: false,
985
+ diagnostic: graph.entry
986
+ }
987
+ };
988
+ }
989
+ return {
990
+ ok: true,
991
+ Component,
992
+ unresolved: unresolved.map(describeUnresolved),
993
+ unresolvedImports: unresolved
994
+ };
995
+ } catch (err) {
996
+ const message = err instanceof Error ? err.message : String(err);
997
+ return {
998
+ ok: false,
999
+ error: {
1000
+ code: "evaluation_error",
1001
+ message: fileSet.size > 1 ? `${current}: ${message}` : message,
1002
+ retryable: false,
1003
+ diagnostic: current
1004
+ }
1005
+ };
1006
+ }
1007
+ }
1008
+
1009
+ // src/transform-core.ts
1010
+ var import_standalone = require("@babel/standalone");
1011
+ function collectImportsPlugin(sink) {
1012
+ return function collectImports() {
1013
+ return {
1014
+ name: "code-runtime-collect-imports",
1015
+ visitor: {
1016
+ ImportDeclaration(path) {
1017
+ const { node } = path;
1018
+ if (node.importKind === "type") return;
1019
+ const source = node.source?.value ?? "";
1020
+ for (const specifier of node.specifiers ?? []) {
1021
+ if (specifier.importKind === "type") continue;
1022
+ const local = specifier.local?.name;
1023
+ if (!local) continue;
1024
+ if (specifier.type === "ImportNamespaceSpecifier") sink.push({ local, source, imported: "*" });
1025
+ else if (specifier.type === "ImportDefaultSpecifier") sink.push({ local, source, imported: "default" });
1026
+ else sink.push({ local, source, imported: specifier.imported?.name ?? specifier.imported?.value ?? local });
1027
+ }
1028
+ }
1029
+ }
1030
+ };
1031
+ };
1032
+ }
1033
+ function collectTopLevelPlugin(declared, candidates) {
1034
+ return function collectTopLevel() {
1035
+ return {
1036
+ name: "code-runtime-collect-top-level",
1037
+ visitor: {
1038
+ Program: {
1039
+ enter(path) {
1040
+ for (const [name, binding] of Object.entries(path.scope.bindings)) {
1041
+ const kind = binding?.kind;
1042
+ if (kind === "module" || kind === "param") continue;
1043
+ declared.add(name);
1044
+ if (/^[A-Z]/.test(name)) candidates.push(name);
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ };
1050
+ };
1051
+ }
1052
+ function languageOf(file) {
1053
+ const m = /\.([a-z]+)$/i.exec(file);
1054
+ const ext = (m?.[1] ?? "tsx").toLowerCase();
1055
+ if (ext === "ts" || ext === "mts" || ext === "cts") return "ts";
1056
+ if (ext === "tsx") return "tsx";
1057
+ if (ext === "jsx") return "jsx";
1058
+ if (ext === "js" || ext === "mjs" || ext === "cjs") return "js";
1059
+ if (ext === "json") return "json";
1060
+ return "text";
1061
+ }
1062
+ function transformModule(file, source) {
1063
+ const lang = languageOf(file);
1064
+ if (lang === "json") {
1065
+ JSON.parse(source);
1066
+ return { file, code: `module.exports = ${source};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };
1067
+ }
1068
+ if (lang === "text") {
1069
+ return { file, code: `module.exports = ${JSON.stringify(source)};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };
1070
+ }
1071
+ const declared = /* @__PURE__ */ new Set();
1072
+ const candidates = [];
1073
+ const importBindings = [];
1074
+ const filename = lang === "js" ? file.replace(/\.(m|c)?js$/i, ".jsx") : file;
1075
+ const result = (0, import_standalone.transform)(source, {
1076
+ filename: /\.[a-z]+$/i.test(filename) ? filename : `${filename}.tsx`,
1077
+ presets: [["react", { runtime: "classic" }], "typescript"],
1078
+ plugins: [
1079
+ collectImportsPlugin(importBindings),
1080
+ collectTopLevelPlugin(declared, candidates),
1081
+ ["transform-modules-commonjs", { strictMode: false }]
1082
+ ],
1083
+ sourceType: "module",
1084
+ babelrc: false,
1085
+ configFile: false
1086
+ });
1087
+ return {
1088
+ file,
1089
+ code: result?.code ?? "",
1090
+ declaredTopLevel: [...declared],
1091
+ componentCandidates: candidates,
1092
+ importBindings
1093
+ };
1094
+ }
1095
+ function transformFiles(files, entry) {
1096
+ if (!Object.prototype.hasOwnProperty.call(files, entry)) {
1097
+ return {
1098
+ ok: false,
1099
+ error: { code: "entry_missing", message: `The entry file "${entry}" is not one of this component's files.`, retryable: false }
1100
+ };
1101
+ }
1102
+ const modules = {};
1103
+ for (const [file, source] of Object.entries(files)) {
1104
+ try {
1105
+ modules[file] = transformModule(file, source ?? "");
1106
+ } catch (err) {
1107
+ const message = err instanceof Error ? err.message : String(err);
1108
+ return {
1109
+ ok: false,
1110
+ error: {
1111
+ code: "compile_error",
1112
+ message: Object.keys(files).length > 1 ? `${file}: ${message}` : message,
1113
+ retryable: false,
1114
+ diagnostic: file
1115
+ }
1116
+ };
1117
+ }
1118
+ }
1119
+ return { ok: true, graph: { entry, modules } };
1120
+ }
1121
+
1122
+ // src/compile.ts
1123
+ function compile(files, entry, scope, options) {
1124
+ const transformed = transformFiles(files, entry);
1125
+ if (!transformed.ok) return transformed;
1126
+ return executeGraph(transformed.graph, scope, options);
1127
+ }
1128
+ function prepareScope(spec) {
1129
+ return prepareScopeModules(spec.entries);
1130
+ }
1131
+ async function compileAsync(files, entry, scope, options) {
1132
+ await prepareScope(scope);
1133
+ return compile(files, entry, scope, options);
1134
+ }
1135
+ function compileSource(code, scope, options) {
1136
+ return compile({ "component.tsx": code }, "component.tsx", scope, options);
1137
+ }
1138
+
1139
+ // src/cache.ts
1140
+ function createCompileCache() {
1141
+ const entries = /* @__PURE__ */ new Map();
1142
+ const keyOf = (id, version) => `${id}\0${version ?? ""}`;
1143
+ return {
1144
+ get(id, version, compileFn) {
1145
+ const key = keyOf(id, version);
1146
+ const hit = entries.get(key);
1147
+ if (hit) return hit;
1148
+ const result = compileFn();
1149
+ if (result.ok || !result.error.retryable) entries.set(key, result);
1150
+ return result;
1151
+ },
1152
+ peek(id, version) {
1153
+ return entries.get(keyOf(id, version));
1154
+ },
1155
+ invalidate(id) {
1156
+ const prefix = `${id}\0`;
1157
+ for (const key of [...entries.keys()]) if (key.startsWith(prefix)) entries.delete(key);
1158
+ },
1159
+ clear() {
1160
+ entries.clear();
1161
+ },
1162
+ get size() {
1163
+ return entries.size;
1164
+ }
1165
+ };
1166
+ }
1167
+ var DEFAULT_KEY = /* @__PURE__ */ Symbol.for("ai-matrx.code-runtime.cache");
1168
+ function defaultCompileCache() {
1169
+ const g = globalThis;
1170
+ let cache = g[DEFAULT_KEY];
1171
+ if (!cache) {
1172
+ cache = createCompileCache();
1173
+ g[DEFAULT_KEY] = cache;
1174
+ }
1175
+ return cache;
1176
+ }
1177
+
1178
+ // src/kind.ts
1179
+ function kindComponentCompiler(options = {}) {
1180
+ return (args) => {
1181
+ if (!args.code || !args.code.trim()) return { Component: null, error: null };
1182
+ const compileOptions = { origin: options.origin?.() ?? "kind-component" };
1183
+ if (options.onUnresolved) compileOptions.onUnresolved = options.onUnresolved;
1184
+ const result = compileSource(
1185
+ args.code,
1186
+ {
1187
+ entries: args.allowedImports,
1188
+ shadowDangerousGlobals: true,
1189
+ ...options.overrides ? { overrides: options.overrides } : {}
1190
+ },
1191
+ compileOptions
1192
+ );
1193
+ return result.ok ? { Component: result.Component, error: null } : { Component: null, error: result.error.message };
1194
+ };
1195
+ }
1196
+ //# sourceMappingURL=index.cjs.map