@akanjs/cli 3.1.1 → 3.1.2-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/.build-stamp +1 -1
  2. package/CodeAgent-dyc45f5w.js +11 -0
  3. package/{CodeAgentRpcHost-9g27hmer.js → CodeAgentRpcHost-6dzfkvsc.js} +1 -1
  4. package/CodeAgentRpcListener-tcwrdvst.js +182 -0
  5. package/{CodeTui-h6yz2kvq.js → CodeTui-q55b2zrn.js} +25 -8
  6. package/TunnelShare-hdq9h1hr.js +14 -0
  7. package/{agent.command-3r4jsck8.js → agent.command-20zaqe60.js} +18 -15
  8. package/akanCode.js +8 -7
  9. package/{application.command-g7xv6ad0.js → application.command-nd0fshsk.js} +11 -11
  10. package/{applicationBuildRunner-qvjnhr9j.js → applicationBuildRunner-s13x3zqb.js} +10 -9
  11. package/buildBatch.proc.js +6 -6
  12. package/{cloud.command-6ebygmhw.js → cloud.command-8kbddsz9.js} +25 -18
  13. package/cloud.script-hgvvajm3.js +27 -0
  14. package/code.command-625bg8s8.js +345 -0
  15. package/{context.command-svdh6b2w.js → context.command-p6haqjay.js} +19 -18
  16. package/context.runner-rsnqnk9j.js +27 -0
  17. package/{dependencyScanner-3afj2vt1.js → dependencyScanner-78sq8m4q.js} +2 -2
  18. package/{fileSys-wzzrntkw.js → fileSys-zpvt5gtf.js} +1 -1
  19. package/{guideline.command-qwp3tnjx.js → guideline.command-195g0h9a.js} +4 -4
  20. package/guidelines/agentRule/agentRule.instruction.md +22 -8
  21. package/guidelines/conventions/rules/auth.md +5 -4
  22. package/guidelines/conventions/rules/config.md +5 -1
  23. package/guidelines/conventions/rules/gates.md +2 -1
  24. package/guidelines/conventions/rules/module.md +1 -1
  25. package/guidelines/conventions/rules/server.md +8 -3
  26. package/guidelines/conventions/rules/ssr.md +2 -2
  27. package/guidelines/conventions/rules/tsx.md +2 -1
  28. package/guidelines/pageRule/pageRule.instruction.md +4 -4
  29. package/guidelines/runtimeRule/runtimeRule.instruction.md +35 -25
  30. package/guidelines/ssrRule/ssrRule.instruction.md +11 -10
  31. package/guidelines/transportRule/transportRule.instruction.md +5 -4
  32. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +1 -1
  33. package/incrementalBuilder.proc.js +4 -4
  34. package/{index-w4k2ragk.js → index-00a7j05x.js} +7 -7
  35. package/{index-w7q6h97v.js → index-0j1t1h2b.js} +3 -1
  36. package/{index-payhwt51.js → index-1h2jc0x3.js} +141 -67
  37. package/{index-vxmy1p4f.js → index-1qsd8ft1.js} +63 -123
  38. package/{index-s6da8ta9.js → index-2mwjshz5.js} +158 -51
  39. package/index-2nxk8wgs.js +266 -0
  40. package/{index-k5jbcxyh.js → index-2phm56a1.js} +49 -8
  41. package/{index-jje9qzyq.js → index-35j83zkd.js} +37 -3
  42. package/{index-m5n3ka0p.js → index-4am4dvmf.js} +13 -2
  43. package/index-75y7bcz4.js +28 -0
  44. package/{index-b8c289dx.js → index-7apsdr5g.js} +55 -12
  45. package/{index-8559hsz4.js → index-84h43kg6.js} +6 -5
  46. package/{index-eja64h28.js → index-9zy8479y.js} +5 -3
  47. package/{index-96wzdhfh.js → index-a1vb3x7t.js} +209 -36
  48. package/{index-52w0fvh8.js → index-bns3wcpc.js} +15 -0
  49. package/{index-am36s3jh.js → index-cjmjvg4r.js} +157 -117
  50. package/{index-1p0qbq3m.js → index-defp4gmb.js} +1 -1
  51. package/{index-4pdts00b.js → index-ewbmfarf.js} +10 -8
  52. package/{index-9rvcs76p.js → index-fhw7yq2d.js} +10 -10
  53. package/{index-8scw1pjk.js → index-g500c5j9.js} +178 -82
  54. package/{index-qxzrp5xt.js → index-g841cap9.js} +4 -4
  55. package/{index-qkkdhjm6.js → index-gr9thy79.js} +5 -5
  56. package/{index-4pf8g7ff.js → index-h7hehkw6.js} +3 -0
  57. package/{index-4mj92tsh.js → index-hm0tn7qv.js} +73 -68
  58. package/{index-r2wedvqn.js → index-j6eeh5d7.js} +1 -1
  59. package/{index-tgt2fnd6.js → index-j7hwy56s.js} +3 -3
  60. package/{index-rnphv731.js → index-jc2zbwra.js} +2 -2
  61. package/{index-z4b84y6k.js → index-khk05tsf.js} +1 -1
  62. package/{index-tvehn2sp.js → index-qd7xn2bk.js} +1 -1
  63. package/{index-266dewjs.js → index-qw6814m4.js} +53 -15
  64. package/{index-zcf6k8a5.js → index-raz588b3.js} +47 -12
  65. package/{index-at7bz0xq.js → index-s4nvxpzm.js} +2 -0
  66. package/{index-3yz30c07.js → index-sp0qsr7a.js} +114 -12
  67. package/{index-1shvxzt0.js → index-sveq36gh.js} +39 -42
  68. package/{index-r2w2eh93.js → index-t1t9wq9a.js} +4 -4
  69. package/index-t78230d7.js +191 -0
  70. package/{index-r0k3ham2.js → index-tgqameyb.js} +4 -4
  71. package/{index-dd44g6vz.js → index-tp56652m.js} +5 -5
  72. package/index-w15mg3km.js +389 -0
  73. package/{index-xq543a5y.js → index-y4kcmbt2.js} +2 -2
  74. package/index-yf9wc28h.js +52 -0
  75. package/{index-xqgwjz7a.js → index-zbrwnmf1.js} +9 -7
  76. package/{index-xxfy1jp2.js → index-zttm13c3.js} +4 -4
  77. package/index.js +24 -24
  78. package/{library.command-2853y6mk.js → library.command-63hgt9te.js} +4 -4
  79. package/{localRegistry.command-76ds31p4.js → localRegistry.command-g3f8k25t.js} +43 -23
  80. package/{module.command-yfnb0abs.js → module.command-r4sa2khp.js} +7 -6
  81. package/{package.command-d9s86hp9.js → package.command-96eheyvd.js} +5 -5
  82. package/package.json +2 -2
  83. package/{page.command-6a8a8rd1.js → page.command-gs6d841d.js} +4 -4
  84. package/{pipeline.command-rt3rwd2z.js → pipeline.command-wdfvdbfj.js} +3 -3
  85. package/{primitive.command-emcebgrq.js → primitive.command-dfsv4mpe.js} +8 -7
  86. package/{projectTypecheck-51m7eh1f.js → projectTypecheck-kqj1t6hb.js} +1 -1
  87. package/{prompter-hgcta8pb.js → prompter-qrwx1p17.js} +2 -2
  88. package/{quality.command-xtrk0n3x.js → quality.command-webzxee2.js} +6 -4
  89. package/{repair.command-51szxnxx.js → repair.command-3r3j1xre.js} +7 -6
  90. package/{scalar.command-8qv27t82.js → scalar.command-e8y47j6d.js} +6 -5
  91. package/skills/akan-agent/SKILL.md +8 -1
  92. package/skills/akan-code/SKILL.md +37 -11
  93. package/skills/akan-debug/SKILL.md +2 -1
  94. package/skills/akan-err/SKILL.md +2 -1
  95. package/skills/akan-query/SKILL.md +3 -2
  96. package/skills/akan-runtime/SKILL.md +3 -0
  97. package/{subspace.command-pn56pnh8.js → subspace.command-a1sf9n5a.js} +12 -10
  98. package/templates/appSample/lib/task/task.signal.ts +14 -9
  99. package/templates/appSample/srvkit/guards.ts +11 -0
  100. package/templates/service/__model__.dictionary.ts +3 -5
  101. package/templates/workspaceRoot/.gitignore.template +1 -0
  102. package/{tunnel.command-q2h0j2en.js → tunnel.command-dcb0wg93.js} +25 -13
  103. package/{verify.command-z1dsbmrt.js → verify.command-yyepccbh.js} +13 -11
  104. package/{workflow.command-r3y67jeq.js → workflow.command-z5pg9ay0.js} +12 -11
  105. package/{workspace.command-t2f0xsrw.js → workspace.command-d7x5jttw.js} +74 -47
  106. package/CodeAgent-35wnb7w5.js +0 -9
  107. package/CodeAgentRpcListener-7p7z5dd7.js +0 -97
  108. package/TunnelShare-xyjpa7gx.js +0 -14
  109. package/cloud.script-0s1jybd5.js +0 -26
  110. package/code.command-mpkm2emr.js +0 -167
  111. package/context.runner-ch0z3a8g.js +0 -26
  112. package/index-c6eggbee.js +0 -123
  113. package/index-ksfgqq1x.js +0 -49
@@ -5,17 +5,17 @@ import {
5
5
  AkanAppConfig,
6
6
  Executor,
7
7
  WorkspaceExecutor
8
- } from "./index-8scw1pjk.js";
8
+ } from "./index-g500c5j9.js";
9
9
  import {
10
10
  resolveAppId,
11
11
  targetHtmlFilename
12
12
  } from "./index-m9jj544v.js";
13
13
  import {
14
14
  CsrArtifactBuilder
15
- } from "./index-1shvxzt0.js";
15
+ } from "./index-sveq36gh.js";
16
16
  import {
17
17
  ExitCodeError
18
- } from "./index-eja64h28.js";
18
+ } from "./index-9zy8479y.js";
19
19
 
20
20
  // pkgs/@akanjs/devkit/mobile/desktopBin.ts
21
21
  import { chmod, mkdir, rename, rm, writeFile } from "fs/promises";
@@ -707,7 +707,7 @@ class NativeAppLine {
707
707
  // pkgs/@akanjs/devkit/mobile/nativeConfig.ts
708
708
  import { readFileSync } from "fs";
709
709
  import path6 from "path";
710
- import { trimSlashes } from "akanjs/common";
710
+ import { LocalePath, trimSlashes } from "akanjs/common";
711
711
 
712
712
  // pkgs/@akanjs/devkit/mobile/usageDescriptions.ts
713
713
  import { capitalize } from "akanjs/common";
@@ -741,6 +741,40 @@ class NativeConfig {
741
741
  "secure-storage",
742
742
  "haptics"
743
743
  ];
744
+ static defaultCsp = {
745
+ "default-src": ["'self'"],
746
+ "script-src": ["'self'", "'wasm-unsafe-eval'"],
747
+ "style-src": ["'self'", "'unsafe-inline'", "https:"],
748
+ "img-src": ["'self'", "blob:", "data:", "https:"],
749
+ "media-src": ["'self'", "blob:", "data:", "https:"],
750
+ "font-src": ["'self'", "data:", "https:"],
751
+ "connect-src": ["'self'", "blob:", "data:", "https:", "wss:"],
752
+ "worker-src": ["'self'", "blob:"],
753
+ "frame-src": ["'self'", "https:"],
754
+ "object-src": ["'none'"],
755
+ "base-uri": ["'self'"],
756
+ "form-action": ["'self'"]
757
+ };
758
+ static #fetchDirectives = [
759
+ "child-src",
760
+ "connect-src",
761
+ "fenced-frame-src",
762
+ "font-src",
763
+ "frame-src",
764
+ "img-src",
765
+ "manifest-src",
766
+ "media-src",
767
+ "object-src",
768
+ "prefetch-src",
769
+ "script-src",
770
+ "script-src-elem",
771
+ "script-src-attr",
772
+ "style-src",
773
+ "style-src-elem",
774
+ "style-src-attr",
775
+ "worker-src"
776
+ ];
777
+ static defaultOpenUrls = ["https://*:*", "mailto:*", "tel:*"];
744
778
  static builtinContributions = {
745
779
  camera: {
746
780
  permission: "camera",
@@ -775,11 +809,13 @@ class NativeConfig {
775
809
  webDir,
776
810
  contributions,
777
811
  locales,
812
+ i18n,
778
813
  env,
779
814
  platform,
780
815
  desktopServer,
781
816
  nativePlugins = [],
782
- desktopBin
817
+ desktopBin,
818
+ publicEnv = {}
783
819
  }) {
784
820
  const warnings = [];
785
821
  const applied = (target.permissions ?? []).flatMap((permission) => {
@@ -845,6 +881,8 @@ class NativeConfig {
845
881
  backgroundColorDark: typeof background === "string" ? undefined : background?.dark,
846
882
  devtools: target.devtools ? true : undefined
847
883
  });
884
+ const csp = NativeConfig.#csp(target, NativeConfig.#plainOrigins(publicEnv, env, !!desktopServer));
885
+ const openUrls = target.openUrls ?? NativeConfig.defaultOpenUrls;
848
886
  const config = {
849
887
  app: {
850
888
  id: resolveAppId(target.appId, platform),
@@ -859,11 +897,12 @@ class NativeConfig {
859
897
  {
860
898
  identifier: "app",
861
899
  description: `The plugins ${target.appName} ships, each with its default permissions`,
862
- permissions: pluginIds.map((id) => `${id}:default`)
900
+ permissions: pluginIds.map((id) => id === "opener" && !openUrls.includes("*") ? { identifier: "opener:default", allow: openUrls.map((url) => ({ url })) } : `${id}:default`)
863
901
  }
864
902
  ],
903
+ ...csp ? { security: { csp } } : {},
865
904
  ...Object.keys(usageDescriptions).length ? { usageDescriptions } : {},
866
- ...target.deepLinks?.schemes?.length || target.deepLinks?.domains?.length ? { deepLinks: NativeConfig.#deepLinks(target, locales) } : {},
905
+ ...target.deepLinks?.schemes?.length || target.deepLinks?.domains?.length ? { deepLinks: NativeConfig.#deepLinks(target, locales, i18n) } : {},
867
906
  ...native ? { native } : {},
868
907
  ...updates ? { updates } : {},
869
908
  ...pushAndroid ? {
@@ -885,6 +924,56 @@ class NativeConfig {
885
924
  };
886
925
  return { config, warnings };
887
926
  }
927
+ static #csp({ name, csp: setting }, plainOrigins) {
928
+ if (setting === false)
929
+ return;
930
+ if (typeof setting === "string") {
931
+ if (!setting.trim())
932
+ throw new Error(`Native target '${name}': csp "" is no policy; write \`csp: false\` to ship the page without one.`);
933
+ return setting;
934
+ }
935
+ const policy = Object.fromEntries(Object.entries(NativeConfig.defaultCsp).map(([directive, sources]) => [directive, [...sources]]));
936
+ const add = (directive, sources) => {
937
+ const list = policy[directive] ?? [];
938
+ policy[directive] = [...new Set([...list.filter((source) => source !== "'none'"), ...sources])];
939
+ };
940
+ add("connect-src", [...plainOrigins, ...plainOrigins.map((origin) => origin.replace(/^http/, "ws"))]);
941
+ add("img-src", plainOrigins);
942
+ add("media-src", plainOrigins);
943
+ const asked = new Map;
944
+ for (const [key, sources] of Object.entries(setting ?? {})) {
945
+ const directive = key.toLowerCase();
946
+ const list = typeof sources === "string" ? sources.split(/\s+/).filter(Boolean) : sources;
947
+ asked.set(directive, [...asked.get(directive) ?? [], ...list]);
948
+ }
949
+ const everywhere = asked.get("default-src") ?? [];
950
+ asked.delete("default-src");
951
+ if (everywhere.length) {
952
+ for (const directive of Object.keys(policy))
953
+ if (directive === "default-src" || directive !== "object-src" && NativeConfig.#fetchDirectives.includes(directive))
954
+ add(directive, everywhere);
955
+ }
956
+ const variant = /^(script|style)-src-(elem|attr)$/;
957
+ for (const [directive, sources] of [...asked].sort(([a], [b]) => Number(variant.test(a)) - Number(variant.test(b)))) {
958
+ const from = variant.test(directive) ? directive.replace(/-(elem|attr)$/, "") : NativeConfig.#fetchDirectives.includes(directive) ? "default-src" : null;
959
+ policy[directive] ??= [...from ? policy[from] ?? [] : []];
960
+ add(directive, sources);
961
+ }
962
+ return policy;
963
+ }
964
+ static #plainOrigins(publicEnv, env, carried) {
965
+ const origins = new Set;
966
+ const pinned = publicEnv.AKAN_PUBLIC_SERVER_URL;
967
+ if (pinned && URL.canParse(pinned) && new URL(pinned).protocol === "http:")
968
+ origins.add(new URL(pinned).origin);
969
+ const environment = publicEnv.AKAN_PUBLIC_ENV ?? env ?? "debug";
970
+ const mode = publicEnv.AKAN_PUBLIC_OPERATION_MODE ?? (environment === "local" ? "local" : "cloud");
971
+ if (mode === "local")
972
+ origins.add("http://localhost:*");
973
+ if (carried)
974
+ origins.add("http://127.0.0.1:*");
975
+ return [...origins];
976
+ }
888
977
  static #icon(icon, abs) {
889
978
  return typeof icon === "string" ? abs(icon) : { ...icon, image: abs(icon.image) };
890
979
  }
@@ -931,9 +1020,11 @@ class NativeConfig {
931
1020
  static #merged(contributed, own) {
932
1021
  return Object.assign({}, ...contributed, own);
933
1022
  }
934
- static #deepLinks(target, locales) {
1023
+ static #deepLinks(target, locales, i18n = { defaultLocale: "" }) {
935
1024
  const basePath = target.basePath ? trimSlashes(target.basePath) : "";
936
- const pathPrefixes = basePath ? locales.map((locale) => `/${locale}/${basePath}`) : undefined;
1025
+ const pathPrefixes = basePath ? [
1026
+ ...new Set(locales.flatMap((locale) => [LocalePath.join(locale, `/${basePath}`, i18n), `/${locale}/${basePath}`]))
1027
+ ] : undefined;
937
1028
  return {
938
1029
  ...target.deepLinks?.schemes?.length ? { schemes: target.deepLinks.schemes } : {},
939
1030
  ...target.deepLinks?.domains?.length ? { domains: target.deepLinks.domains.map((host) => pathPrefixes ? { host, pathPrefixes } : host) } : {}
@@ -994,7 +1085,8 @@ class NativePublicEnv {
994
1085
  "AKAN_PUBLIC_WS_PREFIX",
995
1086
  "AKAN_PUBLIC_RENDER_ENV",
996
1087
  "AKAN_PUBLIC_DEFAULT_LOCALE",
997
- "AKAN_PUBLIC_LOCALES"
1088
+ "AKAN_PUBLIC_LOCALES",
1089
+ "AKAN_PUBLIC_LOCALE_PREFIX"
998
1090
  ];
999
1091
  static #keyPattern = /^AKAN_PUBLIC_[A-Z0-9_]{1,128}$/;
1000
1092
  static #secretWords = ["SECRET", "TOKEN", "PASSWORD", "PRIVATE", "CREDENTIAL"];
@@ -1017,6 +1109,8 @@ class NativePublicEnv {
1017
1109
  return [`${key} names a ${word.toLowerCase()}, which a page bundle must not carry`];
1018
1110
  if (typeof value !== "string")
1019
1111
  return [`${key} is not a string`];
1112
+ if (/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/.test(value))
1113
+ return [`${key} holds a private key`];
1020
1114
  if (/[\u0000-\u001f\u007f]/.test(value))
1021
1115
  return [`${key} holds a control character`];
1022
1116
  return [];
@@ -1037,6 +1131,11 @@ class NativePublicEnv {
1037
1131
  return null;
1038
1132
  return NativePublicEnv.of(await file.json());
1039
1133
  }
1134
+ static async inlined(app) {
1135
+ const file = Bun.file(CsrArtifactBuilder.publicEnvPath(app));
1136
+ const env = await file.exists() ? await file.json() : process.env;
1137
+ return Object.fromEntries(Object.entries(env).flatMap(([key, value]) => key.startsWith("AKAN_PUBLIC_") && typeof value === "string" ? [[key, value]] : []));
1138
+ }
1040
1139
  static async recordedIn(bundleFile) {
1041
1140
  const file = Bun.file(bundleFile);
1042
1141
  if (!await file.exists())
@@ -1289,10 +1388,11 @@ class NativeApp {
1289
1388
  stageBin = true,
1290
1389
  arch
1291
1390
  }) {
1292
- const [appConfig, plugins, nativePlugins] = await Promise.all([
1391
+ const [appConfig, plugins, nativePlugins, publicEnv] = await Promise.all([
1293
1392
  this.app.getConfig(),
1294
1393
  this.app.collectPlugins(),
1295
- NativePluginFolders.of(this.app)
1394
+ NativePluginFolders.of(this.app),
1395
+ NativePublicEnv.inlined(this.app)
1296
1396
  ]);
1297
1397
  const desktop = platform === "macos" || platform === "windows" || platform === "linux";
1298
1398
  const carried = desktop && stageBin ? await new DesktopBin(this.app, appConfig).stage(this.binDir, arch) : [];
@@ -1302,9 +1402,11 @@ class NativeApp {
1302
1402
  webDir: this.web.dir,
1303
1403
  contributions: plugins.flatMap((plugin) => plugin.native ? [plugin.native] : []),
1304
1404
  locales: appConfig.i18n.locales,
1405
+ i18n: appConfig.i18n,
1305
1406
  env: this.env,
1306
1407
  platform,
1307
1408
  nativePlugins,
1409
+ publicEnv,
1308
1410
  ...server ? { desktopServer: server } : {},
1309
1411
  ...carried.length ? { desktopBin: this.binDir } : {}
1310
1412
  });
@@ -1,17 +1,18 @@
1
1
  // @bun
2
2
  import {
3
3
  resolveSsrPageEntriesForApp
4
- } from "./index-8scw1pjk.js";
4
+ } from "./index-g500c5j9.js";
5
5
  import {
6
+ createBarrelImportsPlugin,
6
7
  bundleDefine,
7
8
  CsrEntryFiles,
8
9
  PagesEntrySourceGenerator,
9
10
  PagesBundleBuilder
10
- } from "./index-xqgwjz7a.js";
11
+ } from "./index-zbrwnmf1.js";
11
12
 
12
13
  // pkgs/@akanjs/devkit/frontendBuild/csrArtifactBuilder.ts
13
14
  import { mkdir as mkdir2, rm as rm2, unlink as unlink2 } from "fs/promises";
14
- import path5 from "path";
15
+ import path4 from "path";
15
16
 
16
17
  // pkgs/@akanjs/devkit/transforms/browserDirnamePlugin.ts
17
18
  import path from "path";
@@ -113,12 +114,11 @@ class SideEffectImportOrder {
113
114
 
114
115
  // pkgs/@akanjs/devkit/frontendBuild/mcpAppViewBuilder.ts
115
116
  import { mkdir, readdir, rename, rm, unlink } from "fs/promises";
116
- import path4 from "path";
117
+ import path3 from "path";
117
118
  import { parseRouteModuleKey } from "akanjs/common";
118
119
 
119
120
  // pkgs/@akanjs/devkit/transforms/mcpAppPageTrimmer.ts
120
121
  import { realpathSync } from "fs";
121
- import path3 from "path";
122
122
  import ts3 from "typescript";
123
123
 
124
124
  // pkgs/@akanjs/devkit/transforms/pureLazyMarker.ts
@@ -143,7 +143,7 @@ class PureLazyMarker {
143
143
  static mark(source, filePath) {
144
144
  if (!source.includes("lazy("))
145
145
  return source;
146
- const kind = filePath.endsWith(".tsx") ? ts2.ScriptKind.TSX : ts2.ScriptKind.TS;
146
+ const kind = /\.[jt]sx$/.test(filePath) ? ts2.ScriptKind.TSX : ts2.ScriptKind.TS;
147
147
  const sourceFile = ts2.createSourceFile(filePath, source, ts2.ScriptTarget.Latest, true, kind);
148
148
  const starts = [];
149
149
  const visit = (node) => {
@@ -160,20 +160,9 @@ class PureLazyMarker {
160
160
  // pkgs/@akanjs/devkit/transforms/mcpAppPageTrimmer.ts
161
161
  class McpAppPageTrimmer {
162
162
  static #unused = new Set(["render", "head", "loading", "guard"]);
163
- static plugin(pagePaths) {
164
- return {
165
- name: "akan-mcp-app-page",
166
- setup(build) {
167
- if (!pagePaths.length)
168
- return;
169
- const loadedPaths = new Set(pagePaths.flatMap((pagePath) => [pagePath, McpAppPageTrimmer.#realPathOf(pagePath)]));
170
- const filter = new RegExp(`^(?:${[...loadedPaths].map((pagePath) => RegExp.escape(pagePath)).join("|")})$`);
171
- build.onLoad({ filter }, async (args) => ({
172
- contents: PureLazyMarker.mark(McpAppPageTrimmer.trim(await Bun.file(args.path).text(), args.path), args.path),
173
- loader: path3.extname(args.path).slice(1)
174
- }));
175
- }
176
- };
163
+ static pipe(pagePaths) {
164
+ const loadedPaths = new Set(pagePaths.flatMap((pagePath) => [pagePath, McpAppPageTrimmer.#realPathOf(pagePath)]));
165
+ return (source, { path: filePath }) => PureLazyMarker.mark(loadedPaths.has(filePath) ? McpAppPageTrimmer.trim(source, filePath) : source, filePath);
177
166
  }
178
167
  static trim(source, filePath) {
179
168
  const sourceFile = ts3.createSourceFile(filePath, source, ts3.ScriptTarget.Latest, true, ts3.ScriptKind.TSX);
@@ -223,7 +212,7 @@ class McpAppViewBuilder {
223
212
  this.#command = command;
224
213
  }
225
214
  get outputDir() {
226
- return this.#command === "build" ? path4.join(this.#app.dist.cwdPath, McpAppViewBuilder.dirName) : path4.join(this.#app.cwdPath, ".akan", "artifact", McpAppViewBuilder.dirName);
215
+ return this.#command === "build" ? path3.join(this.#app.dist.cwdPath, McpAppViewBuilder.dirName) : path3.join(this.#app.cwdPath, ".akan", "artifact", McpAppViewBuilder.dirName);
227
216
  }
228
217
  async build(pageEntries, { basePaths, cssAssets, options }) {
229
218
  const views = await McpAppViewBuilder.discover(pageEntries, basePaths);
@@ -233,18 +222,22 @@ class McpAppViewBuilder {
233
222
  }
234
223
  const stagingDir = `${this.outputDir}.next`;
235
224
  await rm(stagingDir, { recursive: true, force: true });
236
- const generatedDir = path4.join(this.#app.cwdPath, ".akan", "generated", McpAppViewBuilder.dirName);
225
+ const generatedDir = path3.join(this.#app.cwdPath, ".akan", "generated", McpAppViewBuilder.dirName);
237
226
  await rm(generatedDir, { recursive: true, force: true });
238
227
  await mkdir(generatedDir, { recursive: true });
239
228
  const files = Object.fromEntries(views.flatMap((view) => [
240
- [path4.join(generatedDir, `${view.name}.html`), McpAppViewBuilder.htmlOf(view)],
241
- [path4.join(generatedDir, `${view.name}.view.tsx`), McpAppViewBuilder.entryOf(view, generatedDir)]
229
+ [path3.join(generatedDir, `${view.name}.html`), McpAppViewBuilder.htmlOf(view)],
230
+ [path3.join(generatedDir, `${view.name}.view.tsx`), McpAppViewBuilder.entryOf(view, generatedDir)]
242
231
  ]));
243
232
  const pagePaths = [...new Set(views.map((view) => view.page.moduleAbsPath))];
244
233
  const result = await Bun.build({
245
234
  ...options,
246
- plugins: [...options.plugins, McpAppPageTrimmer.plugin(pagePaths), PureLazyMarker.plugin()],
247
- entrypoints: views.map((view) => path4.join(generatedDir, `${view.name}.html`)),
235
+ plugins: [
236
+ ...options.plugins,
237
+ await CsrArtifactBuilder.barrelImportsPlugin(this.#app, McpAppPageTrimmer.pipe(pagePaths)),
238
+ PureLazyMarker.plugin()
239
+ ],
240
+ entrypoints: views.map((view) => path3.join(generatedDir, `${view.name}.html`)),
248
241
  files,
249
242
  root: generatedDir,
250
243
  outdir: stagingDir
@@ -264,10 +257,10 @@ ${logs}` : ""}`);
264
257
  const names = new Set(views.map((view) => `${view.name}.html`));
265
258
  await mkdir(this.outputDir, { recursive: true });
266
259
  for (const name of names)
267
- await rename(path4.join(stagingDir, name), path4.join(this.outputDir, name));
260
+ await rename(path3.join(stagingDir, name), path3.join(this.outputDir, name));
268
261
  for (const name of await readdir(this.outputDir))
269
262
  if (!names.has(name))
270
- await rm(path4.join(this.outputDir, name), { recursive: true, force: true });
263
+ await rm(path3.join(this.outputDir, name), { recursive: true, force: true });
271
264
  const strays = await readdir(stagingDir);
272
265
  if (strays.length)
273
266
  this.#app.logger.warn(`[mcp-app-build] ${strays.join(", ")} reached no view; a view loads nothing beside its own file`);
@@ -326,7 +319,7 @@ ${logs}` : ""}`);
326
319
  }
327
320
  static entryOf(view, fromDir) {
328
321
  const specifier = (absPath) => {
329
- const relative = path4.relative(fromDir, absPath).split(path4.sep).join("/");
322
+ const relative = path3.relative(fromDir, absPath).split(path3.sep).join("/");
330
323
  return JSON.stringify(relative.startsWith(".") ? relative : `./${relative}`);
331
324
  };
332
325
  const importsOf = (entries, name) => entries.map((entry, idx) => `import ${name}${idx} from ${specifier(entry.moduleAbsPath)};
@@ -365,11 +358,11 @@ ${importsOf(view.rootOverrides, "rootOverride")}${importsOf(view.overrides, "ove
365
358
  return null;
366
359
  }
367
360
  async#inline(view, dir, cssAsset) {
368
- const htmlPath = path4.join(dir, `${view.name}.html`);
361
+ const htmlPath = path3.join(dir, `${view.name}.html`);
369
362
  let html = await Bun.file(htmlPath).text();
370
363
  if (cssAsset) {
371
- const artifactDir = path4.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan", "artifact");
372
- const css = await Bun.file(path4.join(artifactDir, cssAsset.cssRelPath)).text();
364
+ const artifactDir = path3.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan", "artifact");
365
+ const css = await Bun.file(path3.join(artifactDir, cssAsset.cssRelPath)).text();
373
366
  html = CsrArtifactBuilder.injectBeforeHeadEnd(html, CsrArtifactBuilder.createInlineStyle(css));
374
367
  } else
375
368
  this.#app.logger.warn(`[mcp-app-build] no compiled stylesheet for ${view.name}; its view ships without CSS`);
@@ -419,6 +412,7 @@ class CsrArtifactBuilder {
419
412
  const options = CsrArtifactBuilder.bundleOptions(this.#app, this.#command, akanConfig.optimizeImports);
420
413
  const result = await Bun.build({
421
414
  ...options,
415
+ plugins: [...options.plugins, await CsrArtifactBuilder.barrelImportsPlugin(this.#app)],
422
416
  entrypoints: htmlBasePaths.map((basePath) => this.#generatedPath(CsrArtifactBuilder.htmlFilename(basePath))),
423
417
  files: generatedFiles,
424
418
  root: this.#generatedDir,
@@ -465,8 +459,11 @@ ${logs}` : ""}`);
465
459
  plugins: [PagesBundleBuilder.createCssStubPlugin(), createBrowserDirnamePlugin(), SideEffectImportOrder.plugin()]
466
460
  };
467
461
  }
462
+ static async barrelImportsPlugin(app, pipeAfter) {
463
+ return await createBarrelImportsPlugin(app, { barrels: ["akanjs/ui"], pipeAfter });
464
+ }
468
465
  static publicEnvPath(app) {
469
- return path5.join(app.dist.cwdPath, ".akan", "artifact", "csr-public-env.json");
466
+ return path4.join(app.dist.cwdPath, ".akan", "artifact", "csr-public-env.json");
470
467
  }
471
468
  static async writePublicEnv(app, define) {
472
469
  const prefix = "process.env.";
@@ -484,20 +481,20 @@ ${logs}` : ""}`);
484
481
  return CsrEntryFiles.entryFilename(basePath);
485
482
  }
486
483
  static basePathOfHtml(htmlPath) {
487
- const name = path5.basename(htmlPath, ".html");
484
+ const name = path4.basename(htmlPath, ".html");
488
485
  return name === "index" ? "" : name;
489
486
  }
490
487
  get #outputDir() {
491
- return path5.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, this.#command === "build" ? "csr" : ".akan/artifact/csr");
488
+ return path4.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, this.#command === "build" ? "csr" : ".akan/artifact/csr");
492
489
  }
493
490
  get #generatedDir() {
494
- return path5.join(this.#app.cwdPath, ".akan/generated/csr");
491
+ return path4.join(this.#app.cwdPath, ".akan/generated/csr");
495
492
  }
496
493
  get #artifactDir() {
497
- return path5.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
494
+ return path4.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
498
495
  }
499
496
  #generatedPath(filename) {
500
- return path5.join(this.#generatedDir, filename);
497
+ return path4.join(this.#generatedDir, filename);
501
498
  }
502
499
  async#createEntryFile(basePath, pageEntries) {
503
500
  return [
@@ -530,7 +527,7 @@ void bootCsr(pages);
530
527
  async#loadCssAssets() {
531
528
  if (this.#cssAssets)
532
529
  return this.#cssAssets;
533
- const artifactFile = Bun.file(path5.join(this.#artifactDir, "base-artifact.json"));
530
+ const artifactFile = Bun.file(path4.join(this.#artifactDir, "base-artifact.json"));
534
531
  if (!await artifactFile.exists())
535
532
  return {};
536
533
  const artifact = await artifactFile.json();
@@ -545,7 +542,7 @@ void bootCsr(pages);
545
542
  const basePath = CsrArtifactBuilder.basePathOfHtml(htmlPath);
546
543
  const cssAsset = cssAssets[basePath];
547
544
  if (!cssAsset) {
548
- this.#app.logger.warn(`[csr-build] base-artifact.json has no compiled stylesheet for ${basePath || "root"}; ${path5.basename(htmlPath)} ships without CSS`);
545
+ this.#app.logger.warn(`[csr-build] base-artifact.json has no compiled stylesheet for ${basePath || "root"}; ${path4.basename(htmlPath)} ships without CSS`);
549
546
  }
550
547
  const inlined = await this.#inlineHtmlAssets(await htmlFile.text(), htmlPath, cssAsset);
551
548
  for (const filePath of inlined.jsFiles)
@@ -566,7 +563,7 @@ ${remainingAssets.join(`
566
563
  async#inlineHtmlAssets(html, htmlPath, cssAsset) {
567
564
  let next = html;
568
565
  if (cssAsset) {
569
- const css = await Bun.file(path5.join(this.#artifactDir, cssAsset.cssRelPath)).text();
566
+ const css = await Bun.file(path4.join(this.#artifactDir, cssAsset.cssRelPath)).text();
570
567
  next = CsrArtifactBuilder.injectBeforeHeadEnd(next, CsrArtifactBuilder.createInlineStyle(css));
571
568
  }
572
569
  const jsFiles = [];
@@ -636,7 +633,7 @@ ${CsrArtifactBuilder.escapeInlineScript(await loadScript(src))}
636
633
  throw new Error(`[csr-build] cannot inline external script: ${src}`);
637
634
  }
638
635
  const normalized = src.startsWith("/") ? src.slice(1) : src;
639
- return path5.resolve(path5.dirname(htmlPath), normalized);
636
+ return path4.resolve(path4.dirname(htmlPath), normalized);
640
637
  }
641
638
  }
642
639
 
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  runner,
4
4
  script
5
- } from "./index-eja64h28.js";
5
+ } from "./index-9zy8479y.js";
6
6
  import {
7
7
  ModuleExecutor
8
- } from "./index-8scw1pjk.js";
8
+ } from "./index-g500c5j9.js";
9
9
  import {
10
10
  sourceFile,
11
11
  moduleSourcePaths,
@@ -13,10 +13,10 @@ import {
13
13
  createPassedPrimitiveReport,
14
14
  bilingualLabelForField,
15
15
  bilingualDescriptionForField
16
- } from "./index-4mj92tsh.js";
16
+ } from "./index-hm0tn7qv.js";
17
17
  import {
18
18
  PageScript
19
- } from "./index-z4b84y6k.js";
19
+ } from "./index-khk05tsf.js";
20
20
  import {
21
21
  pluralizeName
22
22
  } from "./index-nz8prx9g.js";
@@ -0,0 +1,191 @@
1
+ // @bun
2
+ import {
3
+ GlobalConfig,
4
+ CloudApi
5
+ } from "./index-gr9thy79.js";
6
+
7
+ // pkgs/@akanjs/cli/tunnel/TunnelShare.ts
8
+ import { TunnelAgent } from "akanjs/server/tunnel";
9
+
10
+ // pkgs/@akanjs/cli/tunnel/TunnelGate.ts
11
+ var devRoutePrefixes = [
12
+ "/_akan/devtools",
13
+ "/_akan/signal",
14
+ "/_akan/constant",
15
+ "/_akan/deps",
16
+ "/_akan/dictionary",
17
+ "/_akan/hmr",
18
+ "/_akan/app",
19
+ "/_akan/ops"
20
+ ];
21
+ var handshakeHeaders = new Set([
22
+ "upgrade",
23
+ "connection",
24
+ "sec-websocket-key",
25
+ "sec-websocket-version",
26
+ "sec-websocket-extensions",
27
+ "sec-websocket-accept",
28
+ "sec-websocket-protocol"
29
+ ]);
30
+ var relayableCloseCode = (code) => code >= 3000 && code <= 4999 || code >= 1000 && code <= 1014 && ![1004, 1005, 1006].includes(code) ? code : 1001;
31
+
32
+ class TunnelGate {
33
+ static isDevRoute(pathname) {
34
+ let decoded;
35
+ try {
36
+ decoded = decodeURIComponent(pathname);
37
+ } catch {
38
+ return true;
39
+ }
40
+ const route = decoded.replace(/\/{2,}/g, "/").toLowerCase();
41
+ return route.endsWith(".map") || devRoutePrefixes.some((prefix) => route === prefix || route.startsWith(`${prefix}/`));
42
+ }
43
+ #target;
44
+ #server;
45
+ origin;
46
+ constructor(target) {
47
+ this.#target = target.replace(/\/$/, "");
48
+ this.#server = Bun.serve({
49
+ hostname: "127.0.0.1",
50
+ port: 0,
51
+ idleTimeout: 0,
52
+ fetch: (req, server) => this.#handle(req, server),
53
+ error: () => new Response("The local app did not answer", { status: 502 }),
54
+ websocket: {
55
+ idleTimeout: 0,
56
+ open: (ws) => {
57
+ ws.data.client = ws;
58
+ for (const message of ws.data.pending.splice(0))
59
+ ws.send(message);
60
+ if (ws.data.closed)
61
+ ws.close(relayableCloseCode(ws.data.closed.code), ws.data.closed.reason);
62
+ },
63
+ message: (ws, message) => {
64
+ if (ws.data.upstream.readyState === WebSocket.OPEN)
65
+ ws.data.upstream.send(message);
66
+ },
67
+ close: (ws, code, reason) => ws.data.upstream.close(relayableCloseCode(code), reason),
68
+ data: {}
69
+ }
70
+ });
71
+ this.origin = `http://127.0.0.1:${this.#server.port}`;
72
+ }
73
+ stop() {
74
+ this.#server.stop(true);
75
+ }
76
+ async#handle(req, server) {
77
+ const url = new URL(req.url);
78
+ if (TunnelGate.isDevRoute(url.pathname))
79
+ return new Response("Not Found", { status: 404 });
80
+ const target = `${this.#target}${url.pathname}${url.search}`;
81
+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket")
82
+ return await this.#upgrade(req, server, target);
83
+ const headers = new Headers(req.headers);
84
+ headers.delete("x-akan-debug");
85
+ return await fetch(target, {
86
+ method: req.method,
87
+ headers,
88
+ body: req.body,
89
+ redirect: "manual",
90
+ decompress: false,
91
+ duplex: "half"
92
+ });
93
+ }
94
+ async#upgrade(req, server, target) {
95
+ const protocols = (req.headers.get("sec-websocket-protocol") ?? "").split(",").map((one) => one.trim()).filter(Boolean);
96
+ const headers = {};
97
+ for (const [name, value] of req.headers)
98
+ if (!handshakeHeaders.has(name) && name !== "x-akan-debug")
99
+ headers[name] = value;
100
+ const upstream = new WebSocket(target.replace(/^http/, "ws"), {
101
+ headers,
102
+ ...protocols.length ? { protocols } : {}
103
+ });
104
+ upstream.binaryType = "arraybuffer";
105
+ const opened = await new Promise((resolve) => {
106
+ upstream.onopen = () => resolve(true);
107
+ upstream.onerror = () => resolve(false);
108
+ upstream.onclose = () => resolve(false);
109
+ });
110
+ if (!opened)
111
+ return new Response("The local app refused the websocket", { status: 502 });
112
+ const data = { upstream, client: null, pending: [], closed: null };
113
+ upstream.onmessage = (event) => {
114
+ if (data.client)
115
+ data.client.send(event.data);
116
+ else
117
+ data.pending.push(event.data);
118
+ };
119
+ upstream.onclose = (event) => {
120
+ data.closed = { code: event.code, reason: event.reason };
121
+ data.client?.close(relayableCloseCode(event.code), event.reason);
122
+ };
123
+ upstream.onerror = () => {
124
+ data.closed = { code: 1011, reason: "local app websocket error" };
125
+ data.client?.close(1011, data.closed.reason);
126
+ };
127
+ const upgraded = server.upgrade(req, {
128
+ data,
129
+ ...upstream.protocol ? { headers: { "Sec-WebSocket-Protocol": upstream.protocol } } : {}
130
+ });
131
+ if (upgraded)
132
+ return;
133
+ upstream.close();
134
+ return new Response("WebSocket upgrade failed", { status: 500 });
135
+ }
136
+ }
137
+
138
+ // pkgs/@akanjs/cli/tunnel/TunnelShare.ts
139
+ class TunnelShare2 {
140
+ #api;
141
+ #agent;
142
+ #gate;
143
+ grant;
144
+ #closed = false;
145
+ constructor(api, agent, grant, gate) {
146
+ this.#api = api;
147
+ this.#agent = agent;
148
+ this.grant = grant;
149
+ this.#gate = gate;
150
+ }
151
+ static async open(app, { workspace, host, port, ttlMinutes, devRoutes = false, onLost }) {
152
+ const api = await CloudApi.fromHost(workspace, await GlobalConfig.hostFor(workspace, host));
153
+ const grant = await api.requestTunnel({ name: app.name, ...ttlMinutes ? { ttlMinutes } : {} });
154
+ const appOrigin = `http://localhost:${port ?? await app.getDevPort()}`;
155
+ const gate = devRoutes ? null : new TunnelGate(appOrigin);
156
+ const agent = new TunnelAgent({
157
+ gatewayUrl: grant.gatewayUrl,
158
+ token: grant.token,
159
+ hostnames: [grant.hostname],
160
+ origin: gate?.origin ?? appOrigin,
161
+ name: app.name,
162
+ ...onLost ? { onLost } : {}
163
+ });
164
+ try {
165
+ await agent.start();
166
+ } catch (error) {
167
+ gate?.stop();
168
+ throw error;
169
+ }
170
+ return new TunnelShare2(api, agent, grant, gate);
171
+ }
172
+ static exposureNotice(appName, devRoutes) {
173
+ const reach = `Anyone with this URL reaches ${appName} on this machine, without signing in.`;
174
+ return devRoutes ? `${reach} --dev-routes also hands them devtools, the HMR socket and source maps.` : `${reach} Devtools, the HMR socket and source maps stay local; \`akan tunnel --dev-routes\` shares them too.`;
175
+ }
176
+ get url() {
177
+ return this.grant.url;
178
+ }
179
+ async close() {
180
+ if (this.#closed)
181
+ return;
182
+ this.#closed = true;
183
+ await this.#agent.stop("cli exited");
184
+ this.#gate?.stop();
185
+ try {
186
+ await this.#api.revokeTunnel(this.grant.code);
187
+ } catch {}
188
+ }
189
+ }
190
+
191
+ export { TunnelShare2 };