aktion-runtime 0.5.7 → 0.5.9

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/testing.js CHANGED
@@ -2188,6 +2188,839 @@ function isCompiledProgram(value) {
2188
2188
  const candidate = value;
2189
2189
  return candidate.__aktionCompiled === COMPILED_PROGRAM_VERSION && typeof candidate.source === "string" && typeof candidate.path === "string" && !!candidate.program && Array.isArray(candidate.program.statements);
2190
2190
  }
2191
+ function defineCompiledProgram(compiled) {
2192
+ return compiled;
2193
+ }
2194
+ const INDENT = " ";
2195
+ const SAFE_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2196
+ const NEEDS_DOUBLE_QUOTE = /[\\"]/;
2197
+ function printProgram(program) {
2198
+ const lines = [];
2199
+ let prev = null;
2200
+ for (const stmt of program.statements) {
2201
+ if (prev && needsBlankLineBetween(prev, stmt)) lines.push("");
2202
+ lines.push(printStatement(stmt, 0));
2203
+ prev = stmt;
2204
+ }
2205
+ return lines.join("\n") + "\n";
2206
+ }
2207
+ function needsBlankLineBetween(prev, next) {
2208
+ const heavy = /* @__PURE__ */ new Set([
2209
+ "ComponentDeclaration",
2210
+ "EffectDeclaration",
2211
+ "ActionDeclaration",
2212
+ "HookDeclaration"
2213
+ ]);
2214
+ if (heavy.has(prev.kind) || heavy.has(next.kind)) return true;
2215
+ return false;
2216
+ }
2217
+ function printStatement(stmt, indent) {
2218
+ const pad = INDENT.repeat(indent);
2219
+ const exp = "exported" in stmt && stmt.exported ? "export " : "";
2220
+ switch (stmt.kind) {
2221
+ case "Import": {
2222
+ const specs = stmt.specifiers.map((s) => {
2223
+ const imported = s.isState ? `$${s.imported}` : s.imported;
2224
+ if (s.local === s.imported) return imported;
2225
+ const local2 = s.isState ? `$${s.local}` : s.local;
2226
+ return `${imported} as ${local2}`;
2227
+ }).join(", ");
2228
+ return `${pad}import { ${specs} } from "${stmt.source}"`;
2229
+ }
2230
+ case "Assignment": {
2231
+ const lhs = stmt.isState ? `$${stmt.identifier}` : stmt.identifier;
2232
+ const expr = printExpression(stmt.expression, indent);
2233
+ return `${pad}${exp}${lhs} = ${expr}`;
2234
+ }
2235
+ case "ComponentDeclaration": {
2236
+ const params = stmt.params.map(printDeclParam).join(", ");
2237
+ const head = `${pad}${exp}function ${stmt.name}(${params}) {`;
2238
+ const body = printBlock(stmt.body.body, indent + 1);
2239
+ return body.length > 0 ? `${head}
2240
+ ${body}
2241
+ ${pad}}` : `${head}
2242
+ ${pad}}`;
2243
+ }
2244
+ case "EffectDeclaration": {
2245
+ const deps = stmt.triggers.map(printTrigger).filter((s) => s.length > 0);
2246
+ if (stmt.rateLimit) {
2247
+ deps.push(`"${stmt.rateLimit.kind}(${stmt.rateLimit.ms})"`);
2248
+ }
2249
+ const body = printBlock(stmt.body.body, indent + 1);
2250
+ const depsArray = `[${deps.join(", ")}]`;
2251
+ return `${pad}$effect(() => {
2252
+ ${body}
2253
+ ${pad}}, ${depsArray})`;
2254
+ }
2255
+ case "ActionDeclaration": {
2256
+ const params = stmt.params.map(printDeclParam).join(", ");
2257
+ const head = `${pad}${exp}function ${stmt.name}(${params}) {`;
2258
+ const body = printBlock(stmt.body.body, indent + 1);
2259
+ return `${head}
2260
+ ${body}
2261
+ ${pad}}`;
2262
+ }
2263
+ case "HookDeclaration": {
2264
+ const params = stmt.params.map(printDeclParam).join(", ");
2265
+ const head = `${pad}${exp}function $${stmt.name}(${params}) {`;
2266
+ const body = printBlock(stmt.body.body, indent + 1);
2267
+ return `${head}
2268
+ ${body}
2269
+ ${pad}}`;
2270
+ }
2271
+ case "Await": {
2272
+ return `${pad}await ${printExpression(stmt.argument, indent)}`;
2273
+ }
2274
+ case "Return": {
2275
+ return stmt.argument ? `${pad}return ${printExpression(stmt.argument, indent)}` : `${pad}return`;
2276
+ }
2277
+ case "ExpressionStatement": {
2278
+ return `${pad}${printExpression(stmt.expression, indent)}`;
2279
+ }
2280
+ case "IfStatement": {
2281
+ const test = printExpression(stmt.test, indent);
2282
+ const cons = `{
2283
+ ${printBlock(stmt.consequent.body, indent + 1)}
2284
+ ${pad}}`;
2285
+ if (!stmt.alternate) return `${pad}if (${test}) ${cons}`;
2286
+ const alt = stmt.alternate.kind === "IfStatement" ? printStatement(stmt.alternate, indent).trimStart() : `{
2287
+ ${printBlock(stmt.alternate.body, indent + 1)}
2288
+ ${pad}}`;
2289
+ return `${pad}if (${test}) ${cons} else ${alt}`;
2290
+ }
2291
+ case "SwitchStatement": {
2292
+ const disc = printExpression(stmt.discriminant, indent);
2293
+ const cases = stmt.cases.map((c) => printSwitchCase(c, indent + 1)).join("\n");
2294
+ return `${pad}switch (${disc}) {
2295
+ ${cases}
2296
+ ${pad}}`;
2297
+ }
2298
+ case "ForOfStatement": {
2299
+ const iter = printExpression(stmt.iterable, indent);
2300
+ const body = `{
2301
+ ${printBlock(stmt.body.body, indent + 1)}
2302
+ ${pad}}`;
2303
+ return `${pad}for (let ${stmt.item} of ${iter}) ${body}`;
2304
+ }
2305
+ case "ForClassicStatement": {
2306
+ const init = stmt.init ? printStatement(stmt.init, 0).trimStart() : "";
2307
+ const test = stmt.test ? printExpression(stmt.test, indent) : "";
2308
+ const update = stmt.update ? printExpression(stmt.update, indent) : "";
2309
+ const body = `{
2310
+ ${printBlock(stmt.body.body, indent + 1)}
2311
+ ${pad}}`;
2312
+ return `${pad}for (${init}; ${test}; ${update}) ${body}`;
2313
+ }
2314
+ case "WhileStatement": {
2315
+ const test = printExpression(stmt.test, indent);
2316
+ const body = `{
2317
+ ${printBlock(stmt.body.body, indent + 1)}
2318
+ ${pad}}`;
2319
+ return `${pad}while (${test}) ${body}`;
2320
+ }
2321
+ case "DoWhileStatement": {
2322
+ const test = printExpression(stmt.test, indent);
2323
+ const body = `{
2324
+ ${printBlock(stmt.body.body, indent + 1)}
2325
+ ${pad}}`;
2326
+ return `${pad}do ${body} while (${test})`;
2327
+ }
2328
+ case "ForInStatement": {
2329
+ const iter = printExpression(stmt.iterable, indent);
2330
+ const body = `{
2331
+ ${printBlock(stmt.body.body, indent + 1)}
2332
+ ${pad}}`;
2333
+ return `${pad}for (let ${stmt.item} in ${iter}) ${body}`;
2334
+ }
2335
+ case "DestructureStatement": {
2336
+ const open = stmt.patternKind === "array" ? "[" : "{";
2337
+ const close = stmt.patternKind === "array" ? "]" : "}";
2338
+ const parts = stmt.bindings.map((b) => {
2339
+ const lead = b.rest ? "..." : "";
2340
+ const keyed = b.sourceKey ? `${b.sourceKey}: ${b.name}` : b.name || "";
2341
+ const def = b.defaultValue ? ` = ${printExpression(b.defaultValue, indent)}` : "";
2342
+ return `${lead}${keyed}${def}`;
2343
+ });
2344
+ const expr = printExpression(stmt.expression, indent);
2345
+ return `${pad}let ${open}${parts.join(", ")}${close} = ${expr}`;
2346
+ }
2347
+ case "BreakStatement":
2348
+ return `${pad}break`;
2349
+ case "ContinueStatement":
2350
+ return `${pad}continue`;
2351
+ case "ThrowStatement":
2352
+ return `${pad}throw ${printExpression(stmt.argument, indent)}`;
2353
+ case "TryStatement": {
2354
+ const block = `{
2355
+ ${printBlock(stmt.block.body, indent + 1)}
2356
+ ${pad}}`;
2357
+ let out = `${pad}try ${block}`;
2358
+ if (stmt.catchBlock) {
2359
+ const catchHead = stmt.catchParam ? ` (${stmt.catchParam})` : "";
2360
+ const catchBody = `{
2361
+ ${printBlock(stmt.catchBlock.body, indent + 1)}
2362
+ ${pad}}`;
2363
+ out += ` catch${catchHead} ${catchBody}`;
2364
+ }
2365
+ if (stmt.finallyBlock) {
2366
+ const finBody = `{
2367
+ ${printBlock(stmt.finallyBlock.body, indent + 1)}
2368
+ ${pad}}`;
2369
+ out += ` finally ${finBody}`;
2370
+ }
2371
+ return out;
2372
+ }
2373
+ }
2374
+ }
2375
+ function printDeclParam(p) {
2376
+ if (p.defaultValue) {
2377
+ return `${p.name} = ${printExpression(p.defaultValue, 0)}`;
2378
+ }
2379
+ return p.name;
2380
+ }
2381
+ function printTrigger(t) {
2382
+ if (t.kind === "lifecycle") return `"${t.name}"`;
2383
+ if (t.kind === "every") return `"every(${t.intervalMs})"`;
2384
+ if (t.kind === "state") return `$${t.name}`;
2385
+ return "";
2386
+ }
2387
+ function printBlock(stmts, indent) {
2388
+ return stmts.map((s) => printStatement(s, indent)).join("\n");
2389
+ }
2390
+ function printExpression(expr, indent) {
2391
+ switch (expr.kind) {
2392
+ case "Literal":
2393
+ return printLiteral(expr.value);
2394
+ case "Identifier":
2395
+ return expr.name;
2396
+ case "StateRef":
2397
+ return `$${expr.name}`;
2398
+ case "Array": {
2399
+ if (expr.elements.length === 0) return "[]";
2400
+ const items = expr.elements.map((e) => printExpression(e, indent));
2401
+ const inline = `[${items.join(", ")}]`;
2402
+ if (inline.length <= 80 && !items.some((s) => s.includes("\n"))) return inline;
2403
+ const pad = INDENT.repeat(indent + 1);
2404
+ return `[
2405
+ ${items.map((s) => `${pad}${s}`).join(",\n")}
2406
+ ${INDENT.repeat(indent)}]`;
2407
+ }
2408
+ case "Object": {
2409
+ if (expr.properties.length === 0) return "{}";
2410
+ const items = expr.properties.map((p) => printObjectProp(p, indent));
2411
+ const inline = `{ ${items.join(", ")} }`;
2412
+ if (inline.length <= 80 && !items.some((s) => s.includes("\n"))) return inline;
2413
+ const pad = INDENT.repeat(indent + 1);
2414
+ return `{
2415
+ ${items.map((s) => `${pad}${s}`).join(",\n")}
2416
+ ${INDENT.repeat(indent)}}`;
2417
+ }
2418
+ case "Member": {
2419
+ const obj = printExpression(expr.object, indent);
2420
+ const dot = expr.optional ? "?." : ".";
2421
+ if (expr.property) return `${obj}${dot}${expr.property}`;
2422
+ if (expr.computed) {
2423
+ const inner = printExpression(expr.computed, indent);
2424
+ return expr.optional ? `${obj}?.[${inner}]` : `${obj}[${inner}]`;
2425
+ }
2426
+ return obj;
2427
+ }
2428
+ case "Unary":
2429
+ return `${expr.operator}${printExpression(expr.argument, indent)}`;
2430
+ case "Binary":
2431
+ return `${printExpression(expr.left, indent)} ${expr.operator} ${printExpression(expr.right, indent)}`;
2432
+ case "Ternary":
2433
+ return `${printExpression(expr.test, indent)} ? ${printExpression(expr.consequent, indent)} : ${printExpression(expr.alternate, indent)}`;
2434
+ case "Call":
2435
+ return printCall(expr.callee, expr.arguments, indent);
2436
+ case "MethodCall": {
2437
+ const target = printExpression(expr.object, indent);
2438
+ const sep = expr.optional ? "?." : ".";
2439
+ return printCall(`${target}${sep}${expr.method}`, expr.arguments, indent);
2440
+ }
2441
+ case "Invoke": {
2442
+ const callee = printExpression(expr.callee, indent);
2443
+ const sep = expr.optional ? "?." : "";
2444
+ return printCall(`${callee}${sep}`, expr.arguments, indent);
2445
+ }
2446
+ case "New": {
2447
+ const callee = printExpression(expr.callee, indent);
2448
+ return `new ${printCall(callee, expr.arguments, indent)}`;
2449
+ }
2450
+ case "BuiltinCall":
2451
+ return printCall(`@${expr.name}`, expr.arguments, indent);
2452
+ case "Template":
2453
+ return printTemplate(expr.quasis, expr.expressions, indent);
2454
+ case "Spread":
2455
+ return `...${printExpression(expr.argument, indent)}`;
2456
+ case "Lambda": {
2457
+ const params = expr.params.map((p) => {
2458
+ const prefix = p.rest ? "..." : "";
2459
+ return p.defaultValue ? `${prefix}${p.name} = ${printExpression(p.defaultValue, indent)}` : `${prefix}${p.name}`;
2460
+ }).join(", ");
2461
+ const head = expr.params.length === 1 && !expr.params[0].defaultValue && !expr.params[0].rest ? expr.params[0].name : `(${params})`;
2462
+ return `${head} => ${printExpression(expr.body, indent)}`;
2463
+ }
2464
+ case "Block":
2465
+ return `{
2466
+ ${printBlock(expr.body, indent + 1)}
2467
+ ${INDENT.repeat(indent)}}`;
2468
+ }
2469
+ }
2470
+ function printCall(callee, args, indent) {
2471
+ if (args.length === 0) return `${callee}()`;
2472
+ const parts = args.map((a) => printExpression(a, indent));
2473
+ const inline = `${callee}(${parts.join(", ")})`;
2474
+ if (inline.length <= 80 && !parts.some((s) => s.includes("\n"))) return inline;
2475
+ const pad = INDENT.repeat(indent + 1);
2476
+ return `${callee}(
2477
+ ${parts.map((s) => `${pad}${s}`).join(",\n")}
2478
+ ${INDENT.repeat(indent)})`;
2479
+ }
2480
+ function printSwitchCase(c, indent) {
2481
+ const pad = INDENT.repeat(indent);
2482
+ const body = c.body.map((s) => printStatement(s, indent + 1)).join("\n");
2483
+ if (c.test === null) {
2484
+ return `${pad}default:
2485
+ ${body}
2486
+ ${printStatement({ kind: "ExpressionStatement", expression: { kind: "Identifier", name: "break" } }, indent + 1)}`;
2487
+ }
2488
+ return `${pad}case ${printExpression(c.test, indent)}:
2489
+ ${body}
2490
+ ${INDENT.repeat(indent + 1)}break`;
2491
+ }
2492
+ function printObjectProp(prop, indent) {
2493
+ if (prop.spread) return `...${printExpression(prop.value, indent)}`;
2494
+ const value = printExpression(prop.value, indent);
2495
+ if (prop.value.kind === "Identifier" && prop.value.name === prop.key && SAFE_IDENT.test(prop.key)) {
2496
+ return prop.key;
2497
+ }
2498
+ const key = SAFE_IDENT.test(prop.key) ? prop.key : printStringLiteral(prop.key);
2499
+ return `${key}: ${value}`;
2500
+ }
2501
+ function printLiteral(value) {
2502
+ if (value === null) return "null";
2503
+ if (typeof value === "string") return printStringLiteral(value);
2504
+ if (typeof value === "boolean") return value ? "true" : "false";
2505
+ return String(value);
2506
+ }
2507
+ function printStringLiteral(value) {
2508
+ if (NEEDS_DOUBLE_QUOTE.test(value)) {
2509
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
2510
+ return `"${escaped}"`;
2511
+ }
2512
+ return `"${value}"`;
2513
+ }
2514
+ function printTemplate(quasis, expressions, indent) {
2515
+ const parts = [];
2516
+ for (let i = 0; i < quasis.length; i += 1) {
2517
+ parts.push(quasis[i] ?? "");
2518
+ if (i < expressions.length) {
2519
+ parts.push("${");
2520
+ parts.push(printExpression(expressions[i], indent));
2521
+ parts.push("}");
2522
+ }
2523
+ }
2524
+ return `\`${parts.join("")}\``;
2525
+ }
2526
+ function linkProgram(entrySource, entryPath, resolver) {
2527
+ const modules = /* @__PURE__ */ new Map();
2528
+ const order = [];
2529
+ const visiting = /* @__PURE__ */ new Set();
2530
+ const diagnostics = [];
2531
+ let nextId = 0;
2532
+ const fail = (path, line, column, message) => {
2533
+ diagnostics.push({
2534
+ line,
2535
+ column,
2536
+ message: path === entryPath ? message : `${path}: ${message}`,
2537
+ severity: "error"
2538
+ });
2539
+ };
2540
+ function load(path, sourceOverride) {
2541
+ const existing = modules.get(path);
2542
+ if (existing) return existing;
2543
+ if (visiting.has(path)) return void 0;
2544
+ visiting.add(path);
2545
+ let src;
2546
+ if (sourceOverride !== null) {
2547
+ src = sourceOverride;
2548
+ } else {
2549
+ try {
2550
+ src = resolver.load(path);
2551
+ } catch {
2552
+ visiting.delete(path);
2553
+ fail(entryPath, 0, 0, `Failed to load imported module "${path}".`);
2554
+ return void 0;
2555
+ }
2556
+ }
2557
+ const program = parse(src);
2558
+ const rec = {
2559
+ id: nextId++,
2560
+ path,
2561
+ program,
2562
+ edges: [],
2563
+ declaredPlain: /* @__PURE__ */ new Set(),
2564
+ declaredState: /* @__PURE__ */ new Set(),
2565
+ exportedPlain: /* @__PURE__ */ new Set(),
2566
+ exportedState: /* @__PURE__ */ new Set(),
2567
+ renamePlain: /* @__PURE__ */ new Map(),
2568
+ renameState: /* @__PURE__ */ new Map()
2569
+ };
2570
+ modules.set(path, rec);
2571
+ buildSymbolTable(rec);
2572
+ for (const stmt of program.statements) {
2573
+ if (stmt.kind !== "Import") continue;
2574
+ const resolved = resolver.resolve(stmt.source, path);
2575
+ rec.edges.push({ stmt, resolvedPath: resolved });
2576
+ if (resolved === null) {
2577
+ fail(path, stmt.loc?.line ?? 0, stmt.loc?.column ?? 0, `Cannot resolve import "${stmt.source}".`);
2578
+ continue;
2579
+ }
2580
+ load(resolved, null);
2581
+ }
2582
+ visiting.delete(path);
2583
+ order.push(path);
2584
+ return rec;
2585
+ }
2586
+ load(entryPath, entrySource);
2587
+ for (const rec of modules.values()) {
2588
+ if (rec.path === entryPath) continue;
2589
+ for (const name of rec.declaredPlain) rec.renamePlain.set(name, `__a${rec.id}_${name}`);
2590
+ for (const name of rec.declaredState) rec.renameState.set(name, `__a${rec.id}_${name}`);
2591
+ }
2592
+ for (const rec of modules.values()) {
2593
+ for (const { stmt, resolvedPath } of rec.edges) {
2594
+ if (resolvedPath === null) continue;
2595
+ const src = modules.get(resolvedPath);
2596
+ if (!src) continue;
2597
+ for (const spec of stmt.specifiers) {
2598
+ const line = stmt.loc?.line ?? 0;
2599
+ const column = stmt.loc?.column ?? 0;
2600
+ if (spec.isState) {
2601
+ if (!src.exportedState.has(spec.imported)) {
2602
+ fail(rec.path, line, column, `"${stmt.source}" does not export \`$${spec.imported}\`.`);
2603
+ continue;
2604
+ }
2605
+ rec.renameState.set(spec.local, src.renameState.get(spec.imported) ?? `__a${src.id}_${spec.imported}`);
2606
+ } else {
2607
+ if (!src.exportedPlain.has(spec.imported)) {
2608
+ fail(rec.path, line, column, `"${stmt.source}" does not export \`${spec.imported}\`.`);
2609
+ continue;
2610
+ }
2611
+ rec.renamePlain.set(spec.local, src.renamePlain.get(spec.imported) ?? `__a${src.id}_${spec.imported}`);
2612
+ }
2613
+ }
2614
+ }
2615
+ }
2616
+ const merged = [];
2617
+ for (const path of order) {
2618
+ const rec = modules.get(path);
2619
+ const renamer = makeRenamer(rec);
2620
+ for (const stmt of rec.program.statements) {
2621
+ if (stmt.kind === "Import") continue;
2622
+ renamer.renameTopLevel(stmt);
2623
+ stripExported(stmt);
2624
+ if (stmt.kind === "EffectDeclaration" && rec.path !== entryPath) {
2625
+ stmt.name = `__effect_a${rec.id}_${stmt.name.replace(/^__effect_/, "")}`;
2626
+ }
2627
+ merged.push(stmt);
2628
+ }
2629
+ }
2630
+ const entryRec = modules.get(entryPath);
2631
+ return {
2632
+ program: { statements: merged, errors: entryRec ? entryRec.program.errors : [] },
2633
+ diagnostics,
2634
+ dependencies: order.filter((p) => p !== entryPath)
2635
+ };
2636
+ }
2637
+ function buildSymbolTable(rec) {
2638
+ for (const stmt of rec.program.statements) {
2639
+ switch (stmt.kind) {
2640
+ case "Assignment":
2641
+ if (stmt.isState) {
2642
+ rec.declaredState.add(stmt.identifier);
2643
+ if (stmt.exported) rec.exportedState.add(stmt.identifier);
2644
+ } else {
2645
+ rec.declaredPlain.add(stmt.identifier);
2646
+ if (stmt.exported) rec.exportedPlain.add(stmt.identifier);
2647
+ }
2648
+ break;
2649
+ case "ComponentDeclaration":
2650
+ case "ActionDeclaration":
2651
+ rec.declaredPlain.add(stmt.name);
2652
+ if (stmt.exported) rec.exportedPlain.add(stmt.name);
2653
+ break;
2654
+ case "HookDeclaration":
2655
+ rec.declaredState.add(stmt.name);
2656
+ if (stmt.exported) rec.exportedState.add(stmt.name);
2657
+ break;
2658
+ case "DestructureStatement":
2659
+ for (const b of stmt.bindings) if (b.name) rec.declaredPlain.add(b.name);
2660
+ break;
2661
+ }
2662
+ }
2663
+ }
2664
+ function stripExported(stmt) {
2665
+ if (stmt.kind === "Assignment" || stmt.kind === "ComponentDeclaration" || stmt.kind === "ActionDeclaration" || stmt.kind === "HookDeclaration") {
2666
+ delete stmt.exported;
2667
+ }
2668
+ }
2669
+ function makeRenamer(rec) {
2670
+ const shadow = [];
2671
+ const shadowed = (name) => {
2672
+ for (const set of shadow) if (set.has(name)) return true;
2673
+ return false;
2674
+ };
2675
+ const rPlain = (name) => shadowed(name) ? name : rec.renamePlain.get(name) ?? name;
2676
+ const rState = (name) => rec.renameState.get(name) ?? name;
2677
+ const push = (names) => {
2678
+ shadow.push(new Set(names));
2679
+ };
2680
+ const pop = () => {
2681
+ shadow.pop();
2682
+ };
2683
+ const patternNames = (p) => p.bindings.map((b) => b.name).filter((n) => !!n);
2684
+ const paramNames = (params) => {
2685
+ const out = [];
2686
+ for (const p of params) {
2687
+ if (p.name) out.push(p.name);
2688
+ if (p.pattern) out.push(...patternNames(p.pattern));
2689
+ }
2690
+ return out;
2691
+ };
2692
+ const renameParamDefaults = (params) => {
2693
+ for (const p of params) if (p.defaultValue) renameExpr(p.defaultValue);
2694
+ };
2695
+ function renameExpr(expr) {
2696
+ switch (expr.kind) {
2697
+ case "Literal":
2698
+ return;
2699
+ case "Identifier":
2700
+ expr.name = rPlain(expr.name);
2701
+ return;
2702
+ case "StateRef":
2703
+ expr.name = rState(expr.name);
2704
+ return;
2705
+ case "Array":
2706
+ for (const el2 of expr.elements) renameExpr(el2);
2707
+ return;
2708
+ case "Object":
2709
+ for (const prop of expr.properties) {
2710
+ if (prop.computedKey) renameExpr(prop.computedKey);
2711
+ renameExpr(prop.value);
2712
+ }
2713
+ return;
2714
+ case "Member":
2715
+ renameExpr(expr.object);
2716
+ if (expr.computed) renameExpr(expr.computed);
2717
+ return;
2718
+ case "Unary":
2719
+ renameExpr(expr.argument);
2720
+ return;
2721
+ case "Binary":
2722
+ renameExpr(expr.left);
2723
+ renameExpr(expr.right);
2724
+ return;
2725
+ case "Ternary":
2726
+ renameExpr(expr.test);
2727
+ renameExpr(expr.consequent);
2728
+ renameExpr(expr.alternate);
2729
+ return;
2730
+ case "Call":
2731
+ expr.callee = rPlain(expr.callee);
2732
+ for (const a of expr.arguments) renameExpr(a);
2733
+ return;
2734
+ case "MethodCall":
2735
+ renameExpr(expr.object);
2736
+ for (const a of expr.arguments) renameExpr(a);
2737
+ return;
2738
+ case "Invoke":
2739
+ renameExpr(expr.callee);
2740
+ for (const a of expr.arguments) renameExpr(a);
2741
+ return;
2742
+ case "BuiltinCall":
2743
+ for (const a of expr.arguments) renameExpr(a);
2744
+ return;
2745
+ case "New":
2746
+ renameExpr(expr.callee);
2747
+ for (const a of expr.arguments) renameExpr(a);
2748
+ return;
2749
+ case "Template":
2750
+ for (const e of expr.expressions) renameExpr(e);
2751
+ return;
2752
+ case "Spread":
2753
+ renameExpr(expr.argument);
2754
+ return;
2755
+ case "Lambda":
2756
+ push(paramNames(expr.params));
2757
+ renameParamDefaults(expr.params);
2758
+ renameExpr(expr.body);
2759
+ pop();
2760
+ return;
2761
+ case "Block":
2762
+ renameBlock(expr);
2763
+ return;
2764
+ }
2765
+ }
2766
+ function renameBlock(block) {
2767
+ push([]);
2768
+ const scope = shadow[shadow.length - 1];
2769
+ for (const stmt of block.body) {
2770
+ renameStatement(stmt, false);
2771
+ addBlockLocals(stmt, scope);
2772
+ }
2773
+ pop();
2774
+ }
2775
+ function addBlockLocals(stmt, scope) {
2776
+ if (stmt.kind === "DestructureStatement") {
2777
+ for (const b of stmt.bindings) if (b.name) scope.add(b.name);
2778
+ } else if (stmt.kind === "ComponentDeclaration" || stmt.kind === "ActionDeclaration") {
2779
+ scope.add(stmt.name);
2780
+ }
2781
+ }
2782
+ function renameTopLevel(stmt) {
2783
+ if (stmt.kind === "DestructureStatement") {
2784
+ renameExpr(stmt.expression);
2785
+ for (const b of stmt.bindings) {
2786
+ if (b.defaultValue) renameExpr(b.defaultValue);
2787
+ b.name = rPlain(b.name);
2788
+ }
2789
+ return;
2790
+ }
2791
+ renameStatement(stmt, true);
2792
+ }
2793
+ function renameStatement(stmt, topLevel) {
2794
+ switch (stmt.kind) {
2795
+ case "Import":
2796
+ return;
2797
+ case "Assignment":
2798
+ stmt.identifier = stmt.isState ? rState(stmt.identifier) : rPlain(stmt.identifier);
2799
+ renameExpr(stmt.expression);
2800
+ return;
2801
+ case "ComponentDeclaration":
2802
+ case "ActionDeclaration":
2803
+ stmt.name = rPlain(stmt.name);
2804
+ push(paramNames(stmt.params));
2805
+ renameParamDefaults(stmt.params);
2806
+ renameBlock(stmt.body);
2807
+ pop();
2808
+ return;
2809
+ case "HookDeclaration":
2810
+ stmt.name = rState(stmt.name);
2811
+ push(paramNames(stmt.params));
2812
+ renameParamDefaults(stmt.params);
2813
+ renameBlock(stmt.body);
2814
+ pop();
2815
+ return;
2816
+ case "EffectDeclaration":
2817
+ for (const t of stmt.triggers) if (t.kind === "state") t.name = rState(t.name);
2818
+ renameBlock(stmt.body);
2819
+ return;
2820
+ case "Await":
2821
+ renameExpr(stmt.argument);
2822
+ return;
2823
+ case "Return":
2824
+ if (stmt.argument) renameExpr(stmt.argument);
2825
+ return;
2826
+ case "ExpressionStatement":
2827
+ renameExpr(stmt.expression);
2828
+ return;
2829
+ case "IfStatement":
2830
+ renameExpr(stmt.test);
2831
+ renameBlock(stmt.consequent);
2832
+ if (stmt.alternate) {
2833
+ if (stmt.alternate.kind === "IfStatement") renameStatement(stmt.alternate, false);
2834
+ else renameBlock(stmt.alternate);
2835
+ }
2836
+ return;
2837
+ case "SwitchStatement":
2838
+ renameExpr(stmt.discriminant);
2839
+ for (const c of stmt.cases) {
2840
+ if (c.test) renameExpr(c.test);
2841
+ for (const s of c.body) renameStatement(s, false);
2842
+ }
2843
+ return;
2844
+ case "ForOfStatement": {
2845
+ renameExpr(stmt.iterable);
2846
+ const names = [stmt.item];
2847
+ if (stmt.index) names.push(stmt.index);
2848
+ if (stmt.destructure) names.push(...stmt.destructure);
2849
+ push(names);
2850
+ renameBlock(stmt.body);
2851
+ pop();
2852
+ return;
2853
+ }
2854
+ case "ForInStatement":
2855
+ renameExpr(stmt.iterable);
2856
+ push([stmt.item]);
2857
+ renameBlock(stmt.body);
2858
+ pop();
2859
+ return;
2860
+ case "ForClassicStatement": {
2861
+ const initNames = [];
2862
+ if (stmt.init && stmt.init.kind === "Assignment" && stmt.init.identifier) {
2863
+ initNames.push(stmt.init.identifier);
2864
+ }
2865
+ push(initNames);
2866
+ if (stmt.init) renameStatement(stmt.init, false);
2867
+ if (stmt.test) renameExpr(stmt.test);
2868
+ if (stmt.update) renameExpr(stmt.update);
2869
+ renameBlock(stmt.body);
2870
+ pop();
2871
+ return;
2872
+ }
2873
+ case "WhileStatement":
2874
+ case "DoWhileStatement":
2875
+ renameExpr(stmt.test);
2876
+ renameBlock(stmt.body);
2877
+ return;
2878
+ case "DestructureStatement":
2879
+ renameExpr(stmt.expression);
2880
+ for (const b of stmt.bindings) if (b.defaultValue) renameExpr(b.defaultValue);
2881
+ if (topLevel) for (const b of stmt.bindings) b.name = rPlain(b.name);
2882
+ return;
2883
+ case "ThrowStatement":
2884
+ renameExpr(stmt.argument);
2885
+ return;
2886
+ case "TryStatement":
2887
+ renameBlock(stmt.block);
2888
+ if (stmt.catchBlock) {
2889
+ push(stmt.catchParam ? [stmt.catchParam] : []);
2890
+ renameBlock(stmt.catchBlock);
2891
+ pop();
2892
+ }
2893
+ if (stmt.finallyBlock) renameBlock(stmt.finallyBlock);
2894
+ return;
2895
+ case "BreakStatement":
2896
+ case "ContinueStatement":
2897
+ return;
2898
+ }
2899
+ }
2900
+ return { renameTopLevel };
2901
+ }
2902
+ function isUrl(spec) {
2903
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(spec);
2904
+ }
2905
+ function normalizeSegments(parts) {
2906
+ const out = [];
2907
+ for (const part of parts) {
2908
+ if (part === "" || part === ".") continue;
2909
+ if (part === "..") out.pop();
2910
+ else out.push(part);
2911
+ }
2912
+ return out.join("/");
2913
+ }
2914
+ function dirOf(path) {
2915
+ const slash = path.lastIndexOf("/");
2916
+ return slash < 0 ? "" : path.slice(0, slash);
2917
+ }
2918
+ function resolveSpecifier(spec, importerPath) {
2919
+ if (isUrl(spec)) {
2920
+ try {
2921
+ return new URL(spec).href;
2922
+ } catch {
2923
+ return null;
2924
+ }
2925
+ }
2926
+ if (isUrl(importerPath)) {
2927
+ try {
2928
+ return new URL(spec, importerPath).href;
2929
+ } catch {
2930
+ return null;
2931
+ }
2932
+ }
2933
+ if (spec.startsWith("/")) {
2934
+ return normalizeSegments(spec.split("/"));
2935
+ }
2936
+ if (spec.startsWith("./") || spec.startsWith("../")) {
2937
+ return normalizeSegments(`${dirOf(importerPath)}/${spec}`.split("/"));
2938
+ }
2939
+ return null;
2940
+ }
2941
+ function createMemoryResolver(files) {
2942
+ return {
2943
+ resolve: (spec, importer) => resolveSpecifier(spec, importer),
2944
+ load: (path) => {
2945
+ const src = files[path];
2946
+ if (src === void 0) throw new Error(`not found: ${path}`);
2947
+ return src;
2948
+ }
2949
+ };
2950
+ }
2951
+ async function defaultFetch(url) {
2952
+ if (typeof fetch !== "function") {
2953
+ throw new Error("global fetch is unavailable; cannot load URL imports");
2954
+ }
2955
+ const res = await fetch(url);
2956
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
2957
+ return res.text();
2958
+ }
2959
+ async function linkProject(options) {
2960
+ const { entry, files } = options;
2961
+ const fetchImpl = options.fetch ?? defaultFetch;
2962
+ const fetchDiagnostics = [];
2963
+ const sources = { ...files };
2964
+ const seen = /* @__PURE__ */ new Set();
2965
+ async function walk(path) {
2966
+ if (seen.has(path)) return;
2967
+ seen.add(path);
2968
+ if (sources[path] === void 0) {
2969
+ if (isUrl(path)) {
2970
+ try {
2971
+ sources[path] = await fetchImpl(path);
2972
+ } catch (err) {
2973
+ fetchDiagnostics.push({
2974
+ line: 0,
2975
+ column: 0,
2976
+ message: `Failed to fetch module "${path}": ${err.message ?? err}`,
2977
+ severity: "error"
2978
+ });
2979
+ return;
2980
+ }
2981
+ } else {
2982
+ return;
2983
+ }
2984
+ }
2985
+ let program;
2986
+ try {
2987
+ program = parse(sources[path]);
2988
+ } catch {
2989
+ return;
2990
+ }
2991
+ const children = [];
2992
+ for (const stmt of program.statements) {
2993
+ if (stmt.kind !== "Import") continue;
2994
+ const resolved = resolveSpecifier(stmt.source, path);
2995
+ if (resolved !== null) children.push(walk(resolved));
2996
+ }
2997
+ await Promise.all(children);
2998
+ }
2999
+ if (sources[entry] === void 0) {
3000
+ return {
3001
+ program: { statements: [], errors: [] },
3002
+ source: "",
3003
+ diagnostics: [
3004
+ { line: 0, column: 0, message: `Entry module "${entry}" was not found.`, severity: "error" }
3005
+ ],
3006
+ dependencies: []
3007
+ };
3008
+ }
3009
+ await walk(entry);
3010
+ const linked = linkProgram(sources[entry], entry, createMemoryResolver(sources));
3011
+ let source;
3012
+ try {
3013
+ source = printProgram(linked.program);
3014
+ } catch {
3015
+ source = sources[entry];
3016
+ }
3017
+ return {
3018
+ program: linked.program,
3019
+ source,
3020
+ diagnostics: [...fetchDiagnostics, ...linked.diagnostics],
3021
+ dependencies: linked.dependencies
3022
+ };
3023
+ }
2191
3024
  function applyDelta(source, ops) {
2192
3025
  const warnings = [];
2193
3026
  const stateUpdates = {};
@@ -21315,6 +22148,7 @@ input, textarea, select, button { color: inherit; font-family: inherit; }
21315
22148
 
21316
22149
  .rui-badge {
21317
22150
  display: inline-flex;
22151
+ width: fit-content;
21318
22152
  align-items: center;
21319
22153
  border-radius: var(--rui-radius-pill);
21320
22154
  padding: 2px 10px;
@@ -21331,6 +22165,7 @@ input, textarea, select, button { color: inherit; font-family: inherit; }
21331
22165
 
21332
22166
  .rui-tag {
21333
22167
  display: inline-flex;
22168
+ width: fit-content;
21334
22169
  align-items: center;
21335
22170
  gap: 4px;
21336
22171
  border-radius: var(--rui-radius-pill);
@@ -28802,6 +29637,7 @@ const ATTRIBUTE_THEME = "theme";
28802
29637
  const ATTRIBUTE_STREAMING = "streaming";
28803
29638
  const ATTRIBUTE_RESPONSE = "response";
28804
29639
  const ATTRIBUTE_SHOW_ERRORS = "showerrors";
29640
+ const ATTRIBUTE_SRC = "src";
28805
29641
  const STATE_ROUTE = "route";
28806
29642
  function buildRouteObject(router) {
28807
29643
  const path = router.getPath();
@@ -28925,6 +29761,25 @@ class AktionElement extends HTMLElement {
28925
29761
  */
28926
29762
  __publicField(this, "forceFullRender", false);
28927
29763
  __publicField(this, "parseErrors", []);
29764
+ /**
29765
+ * Diagnostics raised while loading a program from the `src` attribute
29766
+ * (fetch / link failures, unresolved imports). Tracked separately from
29767
+ * `parseErrors` so they survive the `replan()` that mounting the linked
29768
+ * program triggers, and are merged into the error banner + `error` event.
29769
+ */
29770
+ __publicField(this, "srcDiagnostics", []);
29771
+ /**
29772
+ * Monotonic token guarding overlapping `src` loads. A rapid `src` change
29773
+ * (or a reconnect mid-fetch) bumps the token so a stale in-flight load
29774
+ * resolves into a no-op instead of clobbering the current program.
29775
+ */
29776
+ __publicField(this, "srcLoadToken", 0);
29777
+ /**
29778
+ * True once `connectedCallback` has run at least once. Lets
29779
+ * `attributeChangedCallback` distinguish the initial attribute upgrade
29780
+ * (handled by `connectedCallback`) from a genuine later `src` change.
29781
+ */
29782
+ __publicField(this, "hasConnected", false);
28928
29783
  /**
28929
29784
  * Token keys most recently applied by an in-script `$theme({...})`
28930
29785
  * declaration. We remember them so the next render can clear stale
@@ -29023,10 +29878,12 @@ class AktionElement extends HTMLElement {
29023
29878
  ATTRIBUTE_THEME,
29024
29879
  ATTRIBUTE_STREAMING,
29025
29880
  ATTRIBUTE_RESPONSE,
29026
- ATTRIBUTE_SHOW_ERRORS
29881
+ ATTRIBUTE_SHOW_ERRORS,
29882
+ ATTRIBUTE_SRC
29027
29883
  ];
29028
29884
  }
29029
29885
  connectedCallback() {
29886
+ this.hasConnected = true;
29030
29887
  ensureFontAwesomeLoaded(this.root);
29031
29888
  this.registerWithDevtools();
29032
29889
  this.applyThemeFromAttribute();
@@ -29036,6 +29893,11 @@ class AktionElement extends HTMLElement {
29036
29893
  this.setResponse(responseAttr);
29037
29894
  return;
29038
29895
  }
29896
+ const srcAttr = this.getAttribute(ATTRIBUTE_SRC);
29897
+ if (srcAttr && !this.currentResponse) {
29898
+ void this.loadFromSrc(srcAttr);
29899
+ return;
29900
+ }
29039
29901
  if (!this.currentResponse) {
29040
29902
  const fallback = (this.textContent ?? "").trim();
29041
29903
  if (fallback) {
@@ -29070,6 +29932,9 @@ class AktionElement extends HTMLElement {
29070
29932
  const next = value ?? "";
29071
29933
  if (next !== this.currentResponse) this.setResponse(next);
29072
29934
  }
29935
+ if (name === ATTRIBUTE_SRC) {
29936
+ if (this.hasConnected && value) void this.loadFromSrc(value);
29937
+ }
29073
29938
  }
29074
29939
  /**
29075
29940
  * Register HTTP interceptors used by the Aktion 0.5 HTTP layer (§22.1 of
@@ -29091,6 +29956,7 @@ class AktionElement extends HTMLElement {
29091
29956
  this.state.rebind([]);
29092
29957
  this.renderer.reset();
29093
29958
  this.parseErrors = [];
29959
+ this.srcDiagnostics = [];
29094
29960
  this.scheduleRender();
29095
29961
  }
29096
29962
  /**
@@ -29156,6 +30022,7 @@ class AktionElement extends HTMLElement {
29156
30022
  this.state.rebind([]);
29157
30023
  this.renderer.reset();
29158
30024
  this.parseErrors = [];
30025
+ this.srcDiagnostics = [];
29159
30026
  this.state.hydrate(payload.state);
29160
30027
  this.scheduleRender();
29161
30028
  }
@@ -29185,6 +30052,7 @@ class AktionElement extends HTMLElement {
29185
30052
  this.state.rebind([]);
29186
30053
  this.renderer.reset();
29187
30054
  this.parseErrors = [];
30055
+ this.srcDiagnostics = [];
29188
30056
  if (state) this.state.hydrate(state);
29189
30057
  this.scheduleRender();
29190
30058
  }
@@ -29195,6 +30063,88 @@ class AktionElement extends HTMLElement {
29195
30063
  get sourceId() {
29196
30064
  return this.compiledSourceId;
29197
30065
  }
30066
+ /** Current `src` attribute value, or `null` when none is set. */
30067
+ get src() {
30068
+ return this.getAttribute(ATTRIBUTE_SRC);
30069
+ }
30070
+ set src(value) {
30071
+ if (value === null) this.removeAttribute(ATTRIBUTE_SRC);
30072
+ else this.setAttribute(ATTRIBUTE_SRC, value);
30073
+ }
30074
+ /**
30075
+ * Load the program from an external `.aktion` file referenced by the `src`
30076
+ * attribute. The entry is fetched relative to the document, linked through
30077
+ * the in-browser project linker (so an entry that `import`s other modules
30078
+ * resolves and fetches its whole graph), and mounted as a compiled program.
30079
+ *
30080
+ * A monotonic token guards against overlapping loads: a rapid `src` change
30081
+ * or a reconnect mid-fetch bumps the token, so a stale in-flight load
30082
+ * resolves into a no-op instead of clobbering the current program. Fetch /
30083
+ * link failures and unresolved imports surface through the same error banner
30084
+ * and `error` event as parse errors.
30085
+ */
30086
+ async loadFromSrc(src) {
30087
+ const token = this.srcLoadToken += 1;
30088
+ this.srcDiagnostics = [];
30089
+ let entryUrl;
30090
+ try {
30091
+ const base = typeof document !== "undefined" ? document.baseURI : void 0;
30092
+ entryUrl = new URL(src, base).href;
30093
+ } catch {
30094
+ this.reportSrcError(`Invalid src "${src}".`);
30095
+ return;
30096
+ }
30097
+ let entryText;
30098
+ try {
30099
+ if (typeof fetch !== "function") throw new Error("global fetch is unavailable");
30100
+ const response = await fetch(entryUrl);
30101
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
30102
+ entryText = await response.text();
30103
+ } catch (err) {
30104
+ if (this.isStaleSrcLoad(token)) return;
30105
+ this.reportSrcError(`Failed to load "${src}": ${errorMessage(err)}`);
30106
+ return;
30107
+ }
30108
+ if (this.isStaleSrcLoad(token)) return;
30109
+ let result;
30110
+ try {
30111
+ result = await linkProject({ entry: entryUrl, files: { [entryUrl]: entryText } });
30112
+ } catch (err) {
30113
+ if (this.isStaleSrcLoad(token)) return;
30114
+ this.reportSrcError(`Failed to link "${src}": ${errorMessage(err)}`);
30115
+ return;
30116
+ }
30117
+ if (this.isStaleSrcLoad(token)) return;
30118
+ this.mountCompiled(
30119
+ defineCompiledProgram({
30120
+ __aktionCompiled: COMPILED_PROGRAM_VERSION,
30121
+ program: result.program,
30122
+ source: result.source,
30123
+ path: entryUrl
30124
+ })
30125
+ );
30126
+ this.srcDiagnostics = result.diagnostics.filter((d) => d.severity !== "warning").map((d) => d.line > 0 ? `Line ${d.line}: ${d.message}` : d.message);
30127
+ }
30128
+ /** A `src` load is stale if a newer one started or the element detached. */
30129
+ isStaleSrcLoad(token) {
30130
+ return token !== this.srcLoadToken || !this.isConnected;
30131
+ }
30132
+ /**
30133
+ * Surface a `src`-loading failure: record it, refresh the banner, and
30134
+ * bubble an `error` event so host pages can react (mirrors how parse
30135
+ * errors are reported).
30136
+ */
30137
+ reportSrcError(message) {
30138
+ if (!this.srcDiagnostics.includes(message)) {
30139
+ this.srcDiagnostics = [...this.srcDiagnostics, message];
30140
+ }
30141
+ this.updateErrorBanner();
30142
+ this.dispatchEvent(new CustomEvent("error", {
30143
+ detail: { errors: [{ line: 0, column: 0, message }] },
30144
+ bubbles: true,
30145
+ composed: true
30146
+ }));
30147
+ }
29198
30148
  /** Append a streaming chunk and re-render. */
29199
30149
  appendChunk(chunk) {
29200
30150
  if (chunk === null || chunk === void 0) return;
@@ -29239,6 +30189,7 @@ class AktionElement extends HTMLElement {
29239
30189
  this.renderer.reset();
29240
30190
  this.programDirty = true;
29241
30191
  this.parseErrors = [];
30192
+ this.srcDiagnostics = [];
29242
30193
  this.errorEl.hidden = true;
29243
30194
  this.errorEl.replaceChildren();
29244
30195
  this.rootEl.replaceChildren();
@@ -29623,16 +30574,17 @@ class AktionElement extends HTMLElement {
29623
30574
  }
29624
30575
  }
29625
30576
  updateErrorBanner() {
29626
- if (!this.showErrors || this.streaming || this.parseErrors.length === 0) {
30577
+ const messages = [...this.parseErrors, ...this.srcDiagnostics];
30578
+ if (!this.showErrors || this.streaming || messages.length === 0) {
29627
30579
  this.errorEl.hidden = true;
29628
30580
  this.errorEl.replaceChildren();
29629
30581
  return;
29630
30582
  }
29631
30583
  this.errorEl.hidden = false;
29632
30584
  const title = document.createElement("div");
29633
- title.textContent = `${this.parseErrors.length} parse issue${this.parseErrors.length === 1 ? "" : "s"} (rendered partial UI):`;
30585
+ title.textContent = `${messages.length} parse issue${messages.length === 1 ? "" : "s"} (rendered partial UI):`;
29634
30586
  const list = document.createElement("ul");
29635
- for (const message of this.parseErrors.slice(0, 5)) {
30587
+ for (const message of messages.slice(0, 5)) {
29636
30588
  const li = document.createElement("li");
29637
30589
  li.textContent = message;
29638
30590
  list.append(li);
@@ -29685,6 +30637,10 @@ function parseBooleanAttribute(value) {
29685
30637
  if (normalized === ATTRIBUTE_SHOW_ERRORS) return true;
29686
30638
  return false;
29687
30639
  }
30640
+ function errorMessage(err) {
30641
+ if (err instanceof Error && err.message) return err.message;
30642
+ return String(err);
30643
+ }
29688
30644
  function defineElement() {
29689
30645
  if (!customElements.get(AktionElement.tagName)) {
29690
30646
  customElements.define(AktionElement.tagName, AktionElement);