@adea-ai/app-framework 0.39.2 → 0.39.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.
Files changed (199) hide show
  1. package/README.md +158 -52
  2. package/dist/app/application.d.ts +0 -1
  3. package/dist/app/application.js +8 -6
  4. package/dist/app/create-application.js +3 -11
  5. package/dist/app/service-registry.d.ts +0 -1
  6. package/dist/app/service-registry.js +3 -3
  7. package/dist/app/value-guards.d.ts +2 -0
  8. package/dist/app/value-guards.js +6 -1
  9. package/dist/appearance/appearance-host.d.ts +1 -1
  10. package/dist/appearance/appearance-host.js +11 -2
  11. package/dist/appearance/appearance-preferences.d.ts +0 -1
  12. package/dist/appearance/custom-theme-import.d.ts +8 -2
  13. package/dist/appearance/custom-theme-import.js +58 -23
  14. package/dist/appearance/custom-theme-library.d.ts +3 -3
  15. package/dist/appearance/custom-theme-library.js +3 -3
  16. package/dist/appearance/theme-file-importer.d.ts +1 -1
  17. package/dist/appearance/theme-file-importer.js +2 -1
  18. package/dist/appearance/theme-library-mutation.d.ts +7 -0
  19. package/dist/appearance/theme-library-mutation.js +10 -2
  20. package/dist/appearance/theme-library-store.d.ts +17 -13
  21. package/dist/appearance/theme-library-store.js +35 -22
  22. package/dist/appearance/theme-record-adapter.js +1 -2
  23. package/dist/appearance/theme-registry.js +0 -1
  24. package/dist/cli/cli-runner.d.ts +3 -2
  25. package/dist/cli/cli-runner.js +5 -10
  26. package/dist/cli/release-assets-plan-cli.js +2 -2
  27. package/dist/cli/release-cut-cli.js +2 -3
  28. package/dist/cli/release-descriptor-staging-cli.js +2 -2
  29. package/dist/cli/release-finalize-cli.js +3 -3
  30. package/dist/cli/release-promote-cli.js +2 -2
  31. package/dist/cli/release-publish-cli.js +2 -2
  32. package/dist/cli/release-sign-cli.js +2 -1
  33. package/dist/cli/release-step-cli.js +2 -2
  34. package/dist/desktop/channel-proof.js +27 -11
  35. package/dist/desktop/client-assets.d.ts +6 -1
  36. package/dist/desktop/client-assets.js +16 -3
  37. package/dist/desktop/client-dev-proxy.d.ts +0 -2
  38. package/dist/desktop/client-dev-proxy.js +2 -2
  39. package/dist/desktop/desktop-client.js +2 -1
  40. package/dist/desktop/desktop-gateway.js +24 -82
  41. package/dist/desktop/desktop-host-websocket.d.ts +5 -1
  42. package/dist/desktop/desktop-host-websocket.js +9 -7
  43. package/dist/desktop/desktop-host.d.ts +5 -0
  44. package/dist/desktop/desktop-host.js +3 -0
  45. package/dist/desktop/desktop-stream.js +5 -10
  46. package/dist/desktop/typed-array-intrinsics.d.ts +6 -0
  47. package/dist/desktop/typed-array-intrinsics.js +13 -1
  48. package/dist/developer-app/developer-app.d.ts +1 -1
  49. package/dist/developer-app/developer-app.js +26 -13
  50. package/dist/framework-source.json +1 -1
  51. package/dist/installer/command-artifact.d.ts +1 -0
  52. package/dist/installer/command-artifact.js +47 -27
  53. package/dist/installer/installed-payload.js +3 -1
  54. package/dist/installer/installer-ci-bootstrap.js +5 -6
  55. package/dist/installer/installer-ci-preflight.js +3 -3
  56. package/dist/installer/installer-identity.d.ts +0 -22
  57. package/dist/installer/installer-identity.js +3 -53
  58. package/dist/installer/installer-image-mount.d.ts +0 -1
  59. package/dist/installer/installer-image-mount.js +1 -1
  60. package/dist/installer/installer-observation.d.ts +5 -5
  61. package/dist/installer/installer-observation.js +32 -47
  62. package/dist/installer/installer-process-cleanup.js +2 -2
  63. package/dist/installer/installer-renderer-evidence.js +7 -28
  64. package/dist/installer/installer-upgrade-command.js +8 -20
  65. package/dist/installer/installer-worker-guard.js +3 -3
  66. package/dist/native/cef-helper.js +4 -4
  67. package/dist/native/desktop-build.d.ts +0 -3
  68. package/dist/native/desktop-build.js +2 -2
  69. package/dist/native/electrobun-source-patch.d.ts +4 -0
  70. package/dist/native/electrobun-source-patch.js +5 -1
  71. package/dist/native/native-utilities.js +4 -3
  72. package/dist/native/pinned-download.d.ts +16 -0
  73. package/dist/native/pinned-download.js +42 -0
  74. package/dist/native/posix-launcher-build.js +15 -35
  75. package/dist/native/posix-tree-removal.js +21 -33
  76. package/dist/native/sidecar-services.d.ts +0 -2
  77. package/dist/native/sidecar-services.js +1 -1
  78. package/dist/native/sidecar.d.ts +3 -0
  79. package/dist/native/sidecar.js +15 -2
  80. package/dist/native/window-surface-store.js +3 -3
  81. package/dist/native/windows-extractor-build.d.ts +6 -16
  82. package/dist/native/windows-extractor-build.js +11 -14
  83. package/dist/release/feed-release-cut.d.ts +2 -6
  84. package/dist/release/feed-release-cut.js +5 -93
  85. package/dist/release/feed-state.js +1 -5
  86. package/dist/release/github-release-cut.js +5 -66
  87. package/dist/release/github-release-provenance.d.ts +2 -0
  88. package/dist/release/github-release-provenance.js +4 -7
  89. package/dist/release/github-release-publisher.js +2 -2
  90. package/dist/release/github-release-qualification.js +3 -3
  91. package/dist/release/local-release.d.ts +3 -3
  92. package/dist/release/local-release.js +12 -23
  93. package/dist/release/qualification-run.js +1 -1
  94. package/dist/release/release-assets-plan.js +1 -1
  95. package/dist/release/release-config.d.ts +7 -15
  96. package/dist/release/release-config.js +25 -29
  97. package/dist/release/release-cut-command.d.ts +1 -1
  98. package/dist/release/release-cut-command.js +1 -1
  99. package/dist/release/release-cut.d.ts +5 -32
  100. package/dist/release/release-cut.js +9 -55
  101. package/dist/release/release-descriptor-staging.js +3 -8
  102. package/dist/release/release-promotion.js +2 -1
  103. package/dist/release/release-publish-command.js +5 -15
  104. package/dist/release/release-qualification.js +1 -1
  105. package/dist/shared/bounded-body.d.ts +33 -0
  106. package/dist/shared/bounded-body.js +102 -0
  107. package/dist/shared/file-system.d.ts +12 -0
  108. package/dist/shared/file-system.js +40 -0
  109. package/dist/shell/app-shell.js +29 -14
  110. package/dist/shell/app-utilities.d.ts +2 -1
  111. package/dist/shell/app-utilities.js +2 -1
  112. package/dist/shell/application-menu.d.ts +1 -1
  113. package/dist/shell/application-menu.js +7 -3
  114. package/dist/shell/poll.d.ts +27 -0
  115. package/dist/shell/poll.js +88 -0
  116. package/dist/update-helper.bundle.js +268 -144
  117. package/dist/updates/channel-update-manager.js +0 -1
  118. package/dist/updates/desktop-updater.d.ts +9 -0
  119. package/dist/updates/desktop-updater.js +103 -50
  120. package/dist/updates/feed/release-feed.d.ts +7 -4
  121. package/dist/updates/feed/release-feed.js +3 -7
  122. package/dist/updates/feed/release-location.js +6 -26
  123. package/dist/updates/feed/release-version.d.ts +7 -2
  124. package/dist/updates/feed/release-version.js +9 -2
  125. package/dist/updates/feed/signed-release.d.ts +1 -1
  126. package/dist/updates/feed/signed-release.js +2 -2
  127. package/dist/updates/feed/update-discovery.js +2 -6
  128. package/dist/updates/helper/launch-gate-recovery.js +28 -78
  129. package/dist/updates/helper/resume-staging.d.ts +14 -3
  130. package/dist/updates/helper/resume-staging.js +23 -37
  131. package/dist/updates/helper/update-helper.d.ts +6 -2
  132. package/dist/updates/helper/update-helper.js +38 -33
  133. package/dist/updates/helper/update-resume.js +9 -6
  134. package/dist/updates/install/update-extraction.js +28 -8
  135. package/dist/updates/install/update-handoff-plan.d.ts +0 -1
  136. package/dist/updates/install/update-handoff-plan.js +3 -4
  137. package/dist/updates/install/update-swap-stage.js +1 -6
  138. package/dist/updates/install/update-swap.d.ts +5 -2
  139. package/dist/updates/install/update-swap.js +193 -72
  140. package/dist/updates/launch/helper-exit-wait.d.ts +6 -0
  141. package/dist/updates/launch/helper-exit-wait.js +18 -0
  142. package/dist/updates/launch/packaged-update-startup.js +8 -6
  143. package/dist/updates/launch/update-launch-gate.js +7 -14
  144. package/dist/updates/locks/stable-file.js +4 -1
  145. package/dist/updates/locks/update-helper-presence.d.ts +12 -0
  146. package/dist/updates/locks/update-helper-presence.js +27 -0
  147. package/dist/updates/retention/retention-cleanup.js +10 -9
  148. package/dist/updates/retention/retention-maintenance.d.ts +40 -0
  149. package/dist/updates/retention/retention-maintenance.js +95 -0
  150. package/dist/updates/retention/retention-prune-progress.js +4 -5
  151. package/dist/updates/retention/retirement-inventory.d.ts +13 -0
  152. package/dist/updates/retention/retirement-inventory.js +39 -31
  153. package/dist/updates/retention/retirement-records.d.ts +1 -4
  154. package/dist/updates/retention/retirement-records.js +18 -32
  155. package/dist/updates/retention/update-retention-marker.d.ts +4 -0
  156. package/dist/updates/retention/update-retention-marker.js +9 -14
  157. package/dist/updates/retention/update-retirement.d.ts +12 -0
  158. package/dist/updates/retention/update-retirement.js +59 -31
  159. package/dist/updates/update-adapter.d.ts +1 -23
  160. package/dist/updates/update-adapter.js +31 -24
  161. package/dist/updates/update-channel-store.d.ts +2 -1
  162. package/dist/updates/update-channel-store.js +6 -4
  163. package/dist/updates/update-manager.js +2 -2
  164. package/dist/updates/update-services.d.ts +1 -1
  165. package/dist/updates/update-services.js +9 -4
  166. package/dist/updates/update-state-store.d.ts +0 -2
  167. package/dist/updates/update-state-store.js +5 -12
  168. package/dist/updates/update-state.d.ts +6 -10
  169. package/dist/updates/update-state.js +1 -1
  170. package/dist/views/app-help.d.ts +1 -1
  171. package/dist/views/app-help.js +1 -3
  172. package/dist/views/appearance-surface.js +15 -8
  173. package/dist/views/update-surface.d.ts +1 -3
  174. package/dist/views/update-surface.js +2 -2
  175. package/package.json +18 -16
  176. package/src/app/application.tsx +13 -6
  177. package/src/appearance/appearance-host.tsx +17 -7
  178. package/src/appearance/appearance-preferences.ts +0 -1
  179. package/src/appearance/custom-theme-import.ts +99 -26
  180. package/src/appearance/custom-theme-library.ts +3 -2
  181. package/src/appearance/theme-file-importer.ts +3 -2
  182. package/src/appearance/theme-library-mutation.ts +20 -8
  183. package/src/appearance/theme-library-schema.ts +7 -0
  184. package/src/appearance/theme-library-store.ts +41 -26
  185. package/src/desktop/client-assets.ts +27 -12
  186. package/src/shell/app-shell.tsx +33 -13
  187. package/src/shell/app-utilities.tsx +7 -1
  188. package/src/shell/poll.ts +125 -0
  189. package/src/updates/feed/release-version.ts +11 -3
  190. package/src/updates/update-adapter.ts +27 -44
  191. package/src/updates/update-state.ts +7 -13
  192. package/src/views/app-help.tsx +1 -1
  193. package/src/views/appearance-surface.tsx +39 -11
  194. package/src/views/update-surface.tsx +0 -4
  195. package/templates/application/.github/workflows/release-assets.yml +2 -2
  196. package/templates/application/README.md +3 -3
  197. package/dist/native/cef-helper-download.d.ts +0 -1
  198. package/dist/native/cef-helper-download.js +0 -35
  199. package/src/desktop/client-response-lifecycle.ts +0 -305
@@ -2,7 +2,7 @@
2
2
  import { gitCli, originRepository } from "../release/local-provenance.js";
3
3
  import { runLocalPromotion } from "../release/local-release.js";
4
4
  import { runPromotionCommand } from "../release/release-promotion-command.js";
5
- import { readJsonFile, runCli } from "./cli-runner.js";
5
+ import { readReleaseConfig, runCli } from "./cli-runner.js";
6
6
  // src/cli/release-promote-cli.ts
7
7
  var local = process.argv[2] === "--local";
8
8
  await runCli("Unable to promote the release; check the trusted workflow or feed and release configuration.", async () => {
@@ -13,7 +13,7 @@ await runCli("Unable to promote the release; check the trusted workflow or feed
13
13
  "false",
14
14
  void 0
15
15
  ].includes(held)) throw new Error("Invalid workflow invocation");
16
- const config = await readJsonFile(path, 65536);
16
+ const config = await readReleaseConfig(path);
17
17
  const result = local ? await runLocalPromotion({
18
18
  config,
19
19
  out,
@@ -2,13 +2,13 @@
2
2
  import { gitCli } from "../release/local-provenance.js";
3
3
  import { hostReleasePlatform, localTagProvenance, stageLocalRelease } from "../release/local-release.js";
4
4
  import { runReleasePublishCommand } from "../release/release-publish-command.js";
5
- import { readJsonFile, runCli } from "./cli-runner.js";
5
+ import { readReleaseConfig, runCli } from "./cli-runner.js";
6
6
  // src/cli/release-publish-cli.ts
7
7
  var local = process.argv[2] === "--local";
8
8
  await runCli("Unable to publish release artifacts; check the trusted workflow or local checkout, receipts, signing configuration and staged bytes.", async () => {
9
9
  const [directory, configPath, out, ...extra] = process.argv.slice(local ? 3 : 2);
10
10
  if (!directory || !configPath || extra.length || !out !== !local) throw new Error("Invalid workflow invocation");
11
- const config = await readJsonFile(configPath, 65536);
11
+ const config = await readReleaseConfig(configPath);
12
12
  if (local) {
13
13
  const { RELEASE_TAG: tag, SOURCE_SHA: sourceSha } = process.env;
14
14
  if (!tag || !sourceSha) throw new Error("Missing local release identity");
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  import { signReleaseArtifact } from "../release/release-artifact.js";
3
- import { readJsonFile, runCli } from "./cli-runner.js";
3
+ import { readJsonFile } from "../shared/file-system.js";
4
+ import { runCli } from "./cli-runner.js";
4
5
  import { createPrivateKey } from "node:crypto";
5
6
  // src/cli/release-sign-cli.ts
6
7
  await runCli("Unable to sign release artifact; check the identity, archive and signing key.", async () => {
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  import { inspectStagedStep, qualifyStep, qualifyUpgradeStep, releasePlatform, selectRetainedStep, stageBuildStep } from "../release/release-steps.js";
3
- import { readJsonFile, runCli } from "./cli-runner.js";
3
+ import { readReleaseConfig, runCli } from "./cli-runner.js";
4
4
  // src/cli/release-step-cli.ts
5
5
  await runCli((error) => `Release step failed: ${error instanceof Error ? error.message : String(error)}`, async () => {
6
6
  const args = process.argv.slice(2);
@@ -13,7 +13,7 @@ await runCli((error) => `Release step failed: ${error instanceof Error ? error.m
13
13
  const [step, platform, directory, ...extra] = args;
14
14
  const tag = process.env.RELEASE_TAG;
15
15
  if (!tag || extra.length) throw new Error("Expected <step> <platform> [directory] and RELEASE_TAG");
16
- const config = await readJsonFile("release-config.json", 262144);
16
+ const config = await readReleaseConfig("release-config.json");
17
17
  if (typeof config !== "object" || config === null || typeof config.appName !== "string") throw new Error("release-config.json names no app");
18
18
  const context = {
19
19
  env: process.env,
@@ -3,6 +3,8 @@ import { containsAsciiControl } from "./string-policy.js";
3
3
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
4
  // src/desktop/channel-proof.ts
5
5
  var separator = "";
6
+ /** How far a proof's timestamp may be from the verifier's clock, either way. */
7
+ var MAX_SKEW_MS = 3e4;
6
8
  var field = (value) => typeof value === "string" && value.length > 0 && value.length <= 128 && !containsAsciiControl(value);
7
9
  /** Exact wire input used by Adea's current signed invoke bridge. */
8
10
  function legacyProofMessage(input, context = "adea-invoke-v1") {
@@ -23,12 +25,23 @@ function legacyProofMessage(input, context = "adea-invoke-v1") {
23
25
  */
24
26
  function createChannelProofVerifier(options) {
25
27
  const now = options.now ?? Date.now;
26
- const maxNonces = options.maxNonces ?? 4096;
28
+ const maxNonces = options.maxNonces ?? 16384;
27
29
  const maxBodyBytes = options.maxBodyBytes ?? 262144;
28
30
  const context = options.context ?? "adea-invoke-v1";
29
31
  if (!field(context) || !Number.isSafeInteger(maxNonces) || maxNonces < 1 || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new Error("Invalid channel proof configuration");
30
- const nonces = /* @__PURE__ */ new Map();
31
- let earliest = Infinity;
32
+ const nonces = /* @__PURE__ */ new Set();
33
+ const expiring = /* @__PURE__ */ new Map();
34
+ let sweptSecond = -Infinity;
35
+ const sweep = (at) => {
36
+ const second = Math.floor(at / 1e3);
37
+ if (second <= sweptSecond) return;
38
+ sweptSecond = second;
39
+ for (const [closes, keys] of expiring) {
40
+ if (closes >= second) continue;
41
+ for (const key of keys) nonces.delete(key);
42
+ expiring.delete(closes);
43
+ }
44
+ };
32
45
  return { verify(input) {
33
46
  if (!field(input?.channelId) || !field(input.credentialId) || !field(input.nonce) || typeof input.body !== "string" || Buffer.byteLength(input.body) > maxBodyBytes || typeof input.timestamp !== "string" || !/^\d{1,16}$/.test(input.timestamp) || typeof input.proof !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(input.proof)) return {
34
47
  ok: false,
@@ -36,7 +49,7 @@ function createChannelProofVerifier(options) {
36
49
  };
37
50
  const at = now();
38
51
  const timestamp = Number(input.timestamp);
39
- if (!Number.isSafeInteger(at) || !Number.isSafeInteger(timestamp) || Math.abs(at - timestamp) > 3e4) return {
52
+ if (!Number.isSafeInteger(at) || !Number.isSafeInteger(timestamp) || Math.abs(at - timestamp) > MAX_SKEW_MS) return {
40
53
  ok: false,
41
54
  code: "expired"
42
55
  };
@@ -67,11 +80,12 @@ function createChannelProofVerifier(options) {
67
80
  ok: false,
68
81
  code: "unauthenticated"
69
82
  };
70
- if (earliest < at) {
71
- earliest = Infinity;
72
- for (const [key, expiry] of nonces) if (expiry < at) nonces.delete(key);
73
- else if (expiry < earliest) earliest = expiry;
74
- }
83
+ sweep(at);
84
+ const closes = Math.floor((timestamp + MAX_SKEW_MS) / 1e3);
85
+ if (closes < sweptSecond) return {
86
+ ok: false,
87
+ code: "expired"
88
+ };
75
89
  const key = `${input.channelId}\0${input.credentialId}\0${input.nonce}`;
76
90
  if (nonces.has(key)) return {
77
91
  ok: false,
@@ -81,8 +95,10 @@ function createChannelProofVerifier(options) {
81
95
  ok: false,
82
96
  code: "capacity"
83
97
  };
84
- nonces.set(key, timestamp + 6e4);
85
- if (timestamp + 6e4 < earliest) earliest = timestamp + 6e4;
98
+ nonces.add(key);
99
+ const file = expiring.get(closes);
100
+ if (file) file.push(key);
101
+ else expiring.set(closes, [key]);
86
102
  return {
87
103
  ok: true,
88
104
  principal: channel.principal
@@ -1,6 +1,6 @@
1
1
  import { type ClientAssetFileLimit, type ClientAssetVerificationCache } from './client-asset-stream';
2
2
  export { createClientAssetFileLimit, createClientAssetVerificationCache, type ClientAssetFileLimit, type ClientAssetVerificationCache, } from './client-asset-stream';
3
- export { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetManifest, parseClientAssetManifest, snapshotClientAssetAllowlist, type ClientAssetManifest, } from './client-asset-manifest';
3
+ export { CLIENT_ASSET_MANIFEST_FILE } from './client-asset-manifest';
4
4
  export type ClientOptions = {
5
5
  root: string;
6
6
  deniedPaths?: readonly string[];
@@ -13,6 +13,11 @@ export type ClientOptions = {
13
13
  verificationCache?: ClientAssetVerificationCache;
14
14
  /** Admission limit shared by streamed GET bodies; readers past it wait without a descriptor. */
15
15
  openFileLimit?: ClientAssetFileLimit;
16
+ /**
17
+ * URL prefixes that hold only built assets, such as `/start-assets`. A missing path under one
18
+ * is a 404, never the SPA's index.html. `/assets` is always one.
19
+ */
20
+ assetPrefixes?: readonly string[];
16
21
  };
17
22
  /** A caller-owned, immutable client root kept available for the resolver's lifetime. */
18
23
  export type RetainedClientAssetRoot = Readonly<{
@@ -1,5 +1,5 @@
1
1
  import { createClientAssetFileLimit, createClientAssetStream, createClientAssetVerificationCache, verifyClientAssetCached, verifyClientAssetDigest } from "./client-asset-stream.js";
2
- import { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetManifest, parseClientAssetManifest, snapshotClientAssetAllowlist } from "./client-asset-manifest.js";
2
+ import { CLIENT_ASSET_MANIFEST_FILE, parseClientAssetManifest, snapshotClientAssetAllowlist } from "./client-asset-manifest.js";
3
3
  import { open, readFile, realpath, stat } from "node:fs/promises";
4
4
  import { extname, join, posix, relative, resolve, sep } from "node:path";
5
5
  import { createHash } from "node:crypto";
@@ -22,6 +22,14 @@ var MIME = {
22
22
  ".woff2": "font/woff2",
23
23
  ".wasm": "application/wasm"
24
24
  };
25
+ var ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
26
+ ".js",
27
+ ".mjs",
28
+ ".css",
29
+ ".map",
30
+ ".woff2",
31
+ ".wasm"
32
+ ]);
25
33
  var unavailable = (status = 404) => new Response(null, {
26
34
  status,
27
35
  headers: { "cache-control": "no-store" }
@@ -59,6 +67,11 @@ function deniedPrefixes(paths) {
59
67
  }
60
68
  return prefixes;
61
69
  }
70
+ var DEFAULT_ASSET_PREFIXES = ["/assets"];
71
+ function assetPrefixes(paths) {
72
+ if (!paths?.length) return DEFAULT_ASSET_PREFIXES;
73
+ return [...DEFAULT_ASSET_PREFIXES, ...deniedPrefixes(paths).filter((prefix) => prefix !== "/")];
74
+ }
62
75
  function clientPath(request) {
63
76
  try {
64
77
  const path = posix.normalize("/" + decodeURIComponent(new URL(request.url).pathname).replaceAll("\\", "/"));
@@ -187,7 +200,7 @@ async function serveClientInternal(request, options, onMissingRoot) {
187
200
  }
188
201
  if (!metadata?.isFile()) {
189
202
  const folded = logical.toLowerCase();
190
- if (folded === "/assets" || folded.startsWith("/assets/")) return unavailable();
203
+ if (ASSET_EXTENSIONS.has(extname(folded)) || assetPrefixes(options.assetPrefixes).some((prefix) => folded === prefix || folded.startsWith(prefix + "/"))) return unavailable();
191
204
  filePath = join(root, "index.html");
192
205
  metadata = await stat(filePath).catch(() => null);
193
206
  if (!metadata?.isFile()) return unavailable();
@@ -246,4 +259,4 @@ async function serveClientInternal(request, options, onMissingRoot) {
246
259
  ...request.method === "HEAD" ? { "content-length": String(body.byteLength) } : {}
247
260
  } });
248
261
  }
249
- export { CLIENT_ASSET_ASSET_PATTERN, CLIENT_ASSET_CHUNK_PATTERN, CLIENT_ASSET_MANIFEST_FILE, clientAssetAssetEvidenceKey, clientAssetChunkEvidenceKey, createClientAssetFileLimit, createClientAssetManifest, createClientAssetResolver, createClientAssetVerificationCache, loadClientAssetManifest, parseClientAssetManifest, serveClient, snapshotClientAssetAllowlist };
262
+ export { CLIENT_ASSET_MANIFEST_FILE, createClientAssetFileLimit, createClientAssetResolver, createClientAssetVerificationCache, loadClientAssetManifest, serveClient };
@@ -5,8 +5,6 @@
5
5
  * every client request to the dev server, and the HMR socket connects to the dev
6
6
  * server's own port directly.
7
7
  */
8
- /** The variable the developer app runner sets to the UI dev server origin. */
9
- export declare const CLIENT_DEV_URL_VARIABLE = "ADEA_CLIENT_DEV_URL";
10
8
  /**
11
9
  * The dev server origin to proxy the client to, or undefined when it is not set.
12
10
  * Only a bare loopback http origin is accepted, and never for a release build.
@@ -61,7 +61,7 @@ async function proxyClientDevRequest(request, devOrigin, transformHtml, fetchImp
61
61
  redirect: "manual"
62
62
  });
63
63
  } catch {
64
- return new Response("<!doctype html><meta http-equiv=\"refresh\" content=\"2\"><p>Waiting for the UI dev server…</p>", {
64
+ return new Response("<!doctype html><meta http-equiv=\"refresh\" content=\"1\"><p>Waiting for the UI dev server…</p>", {
65
65
  status: 502,
66
66
  headers: { "content-type": "text/html; charset=utf-8" }
67
67
  });
@@ -81,4 +81,4 @@ async function proxyClientDevRequest(request, devOrigin, transformHtml, fetchImp
81
81
  headers: responseHeaders
82
82
  });
83
83
  }
84
- export { CLIENT_DEV_URL_VARIABLE, proxyClientDevRequest, resolveClientDevOrigin };
84
+ export { proxyClientDevRequest, resolveClientDevOrigin };
@@ -212,7 +212,7 @@ function createDesktopClient(options = {}) {
212
212
  clearTimeout(timer);
213
213
  resolve({
214
214
  send(payload) {
215
- const length = typeof payload === "string" ? new TextEncoder().encode(payload).byteLength : payload instanceof ArrayBuffer ? payload.byteLength : Infinity;
215
+ const length = typeof payload === "string" ? payload.length * 3 <= 262144 ? payload.length : new TextEncoder().encode(payload).byteLength : payload instanceof ArrayBuffer ? payload.byteLength : Infinity;
216
216
  if (!isCurrent() || socket.readyState !== WebSocket.OPEN || length > 262144 || socket.bufferedAmount > 1048576) {
217
217
  socket.close();
218
218
  return false;
@@ -303,6 +303,7 @@ function createDesktopClient(options = {}) {
303
303
  if (session === active) session = void 0;
304
304
  throw new Error("Desktop channel is no longer active");
305
305
  }
306
+ if (result.status === 429) throw new Error("Desktop service is busy");
306
307
  if (!result.ok) throw new Error("Desktop service request failed");
307
308
  const value = await awaitWithAbort(result.json(), controller.signal);
308
309
  throwIfAborted();
@@ -2,6 +2,7 @@ import { createLoopbackPolicy, matchesLoopbackOrigin } from "./loopback-policy.j
2
2
  import { createChannelProofVerifier } from "./channel-proof.js";
3
3
  import { MAX_SERVICE_BODY_BYTES } from "../app/service-registry.js";
4
4
  import { isValidGatewayTimeoutMs } from "./gateway-limits.js";
5
+ import { BoundedBodyError, readBoundedBytes } from "../shared/bounded-body.js";
5
6
  // src/desktop/desktop-gateway.ts
6
7
  var response = (status) => new Response(null, {
7
8
  status,
@@ -14,92 +15,33 @@ var json = (value) => Response.json(value, { headers: {
14
15
  "cache-control": "no-store",
15
16
  "x-content-type-options": "nosniff"
16
17
  } });
17
- /** Read incrementally so the limit applies before the entire body is buffered. */
18
+ var strictUtf8 = new TextDecoder("utf-8", { fatal: true });
19
+ /** Read with the body limit, the read deadline and the caller's abort all applied while streaming. */
18
20
  async function readBody(request, limit, timeoutMs) {
19
- const declared = request.headers.get("content-length");
20
- if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > limit)) return { status: 413 };
21
- if (request.signal.aborted) return { status: 408 };
22
- const reader = request.body?.getReader();
23
- if (!reader) return {
24
- body: "",
25
- length: 0
26
- };
27
- let timedOut = false;
28
- let interrupted = false;
29
- let interruptActiveRead;
30
- const interrupt = (timeout) => {
31
- if (interrupted) return;
32
- interrupted = true;
33
- timedOut = timeout;
34
- reader.cancel().catch(() => {});
35
- interruptActiveRead?.();
36
- };
37
- const onAbort = () => interrupt(false);
38
- request.signal.addEventListener("abort", onAbort, { once: true });
39
- const timer = setTimeout(() => interrupt(true), timeoutMs);
40
- let bytes = /* @__PURE__ */ new Uint8Array(0);
41
- let length = 0;
42
- let pendingRead;
21
+ const reading = new AbortController();
22
+ const stop = () => reading.abort();
23
+ if (request.signal.aborted) stop();
24
+ else request.signal.addEventListener("abort", stop, { once: true });
25
+ const timer = setTimeout(stop, timeoutMs);
26
+ let bytes;
27
+ try {
28
+ bytes = await readBoundedBytes(request, limit, {
29
+ signal: reading.signal,
30
+ allowEmpty: true
31
+ });
32
+ } catch (error) {
33
+ return { status: error instanceof BoundedBodyError && error.reason === "aborted" ? 408 : 413 };
34
+ } finally {
35
+ clearTimeout(timer);
36
+ request.signal.removeEventListener("abort", stop);
37
+ }
43
38
  try {
44
- while (true) {
45
- if (interrupted) return { status: 408 };
46
- const read = reader.read();
47
- pendingRead = read;
48
- const outcome = await new Promise((resolve) => {
49
- let settled = false;
50
- const finish = (value) => {
51
- if (settled) return;
52
- settled = true;
53
- if (interruptActiveRead === onInterrupt) interruptActiveRead = void 0;
54
- resolve(value);
55
- };
56
- const onInterrupt = () => finish({ type: "interrupted" });
57
- interruptActiveRead = onInterrupt;
58
- read.then((value) => finish({
59
- type: "read",
60
- value
61
- }), (error) => finish({
62
- type: "error",
63
- error
64
- }));
65
- });
66
- if (interrupted || outcome.type === "interrupted") return { status: 408 };
67
- pendingRead = void 0;
68
- if (outcome.type === "error") throw outcome.error;
69
- const next = outcome.value;
70
- if (timedOut) return { status: 408 };
71
- if (next.done) break;
72
- const nextLength = length + next.value.byteLength;
73
- if (nextLength > limit) {
74
- reader.cancel().catch(() => {});
75
- return { status: 413 };
76
- }
77
- if (nextLength > bytes.byteLength) {
78
- const capacity = Math.min(limit, Math.max(nextLength, Math.max(1024, bytes.byteLength * 2)));
79
- const grown = new Uint8Array(capacity);
80
- grown.set(bytes.subarray(0, length));
81
- bytes = grown;
82
- }
83
- bytes.set(next.value, length);
84
- length = nextLength;
85
- }
86
- let body;
87
- try {
88
- body = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length));
89
- } catch {
90
- return { status: 400 };
91
- }
92
39
  return {
93
- body,
94
- length
40
+ body: strictUtf8.decode(bytes),
41
+ length: bytes.byteLength
95
42
  };
96
43
  } catch {
97
- return { status: timedOut || request.signal.aborted ? 408 : 413 };
98
- } finally {
99
- clearTimeout(timer);
100
- request.signal.removeEventListener("abort", onAbort);
101
- if (pendingRead) pendingRead.then(() => reader.releaseLock(), () => reader.releaseLock());
102
- else reader.releaseLock();
44
+ return { status: 400 };
103
45
  }
104
46
  }
105
47
  function parse(body) {
@@ -180,7 +122,7 @@ function createDesktopGateway(options) {
180
122
  proof: request.headers.get("x-adea-proof") ?? "",
181
123
  body
182
124
  });
183
- if (!result.ok) return response(401);
125
+ if (!result.ok) return response(result.code === "capacity" ? 429 : 401);
184
126
  if (typeof input.name !== "string") return response(400);
185
127
  if (received.length > options.services.maxBodyBytes(input.name)) return response(413);
186
128
  if (request.signal.aborted) return response(408);
@@ -5,6 +5,10 @@ type BunWebSocket = {
5
5
  send(payload: StreamPayload): number;
6
6
  };
7
7
  export declare const DESKTOP_STREAM_BACKPRESSURE_LIMIT: number;
8
- /** Adapt Bun's byte-count send result to the boolean contract used by streams. */
8
+ /**
9
+ * Adapt Bun's send status to the boolean contract used by streams: bytes sent (>0) and
10
+ * queued under backpressure (-1) succeed; 0 means dropped. Bun bounds the queue itself
11
+ * (`backpressureLimit` with `closeOnBackpressureLimit`), so -1 needs no drain tracking.
12
+ */
9
13
  export declare function sendDesktopStreamPayload(socket: BunWebSocket, payload: StreamPayload): boolean;
10
14
  export {};
@@ -12,17 +12,19 @@ function getTypedArrayByteLength(payload) {
12
12
  }
13
13
  }
14
14
  var DESKTOP_STREAM_BACKPRESSURE_LIMIT = 1048576;
15
- /** Adapt Bun's byte-count send result to the boolean contract used by streams. */
15
+ /**
16
+ * Adapt Bun's send status to the boolean contract used by streams: bytes sent (>0) and
17
+ * queued under backpressure (-1) succeed; 0 means dropped. Bun bounds the queue itself
18
+ * (`backpressureLimit` with `closeOnBackpressureLimit`), so -1 needs no drain tracking.
19
+ */
16
20
  function sendDesktopStreamPayload(socket, payload) {
17
21
  const byteLength = typeof payload === "string" ? payload.length : getTypedArrayByteLength(payload);
18
22
  if (byteLength === void 0) return false;
19
- if (!(byteLength === 0)) return socket.send(payload) > 0;
20
- const readyState = socket.readyState;
21
- if (readyState !== 1) return false;
23
+ if (!(byteLength === 0)) return socket.send(payload) !== 0;
24
+ if (socket.readyState !== 1) return false;
22
25
  const bufferedAmount = socket.getBufferedAmount();
23
26
  if (!Number.isFinite(bufferedAmount) || bufferedAmount < 0 || bufferedAmount > 1048576) return false;
24
- const sent = socket.send(payload);
25
- if (sent > 0) return true;
26
- return sent === 0 && readyState === 1 && bufferedAmount <= 1048576;
27
+ socket.send(payload);
28
+ return true;
27
29
  }
28
30
  export { DESKTOP_STREAM_BACKPRESSURE_LIMIT, sendDesktopStreamPayload };
@@ -37,6 +37,11 @@ type DesktopHostOptions<Principal, Window extends NativeWindow> = {
37
37
  streamClientAssets?: boolean;
38
38
  /** Streamed asset files held open at once (1-1024, default 32); later readers wait. */
39
39
  maxOpenClientAssetFiles?: number;
40
+ /**
41
+ * Seconds a connection may sit without traffic before the server closes it (1-255, default
42
+ * 10). It also bounds a reader that stops consuming a streamed asset. Invokes are exempt.
43
+ */
44
+ idleTimeoutSeconds?: number;
40
45
  /** Explicit content-verified cache allowlist; omitted assets and HTML stay no-store. */
41
46
  immutableClientAssets?: ReadonlyMap<string, string>;
42
47
  /** Caller-owned roots kept immutable and available until host responses finish. */
@@ -70,6 +70,8 @@ function createDesktopHost(options, lifecycle) {
70
70
  const dispatchTimeoutMs = options.dispatchTimeoutMs;
71
71
  if (!isValidGatewayTimeoutMs(dispatchTimeoutMs)) throw new Error("Invalid gateway limits");
72
72
  if (options.streamClientAssets !== void 0 && typeof options.streamClientAssets !== "boolean") throw new Error("Invalid desktop client asset policy");
73
+ const idleTimeoutSeconds = options.idleTimeoutSeconds ?? 10;
74
+ if (!Number.isSafeInteger(idleTimeoutSeconds) || idleTimeoutSeconds < 1 || idleTimeoutSeconds > 255) throw new Error("Invalid desktop host idle timeout");
73
75
  const clientAssetFileLimit = createClientAssetFileLimit(options.maxOpenClientAssetFiles ?? 32);
74
76
  const clientAssetVerificationCache = createClientAssetVerificationCache();
75
77
  const serveAssets = createClientAssetResolver({
@@ -126,6 +128,7 @@ function createDesktopHost(options, lifecycle) {
126
128
  server = Bun.serve({
127
129
  hostname: "127.0.0.1",
128
130
  port,
131
+ idleTimeout: idleTimeoutSeconds,
129
132
  async fetch(request, connection) {
130
133
  if (stopped || !origin || !loopbackPolicy || !gateway) return new Response(null, { status: 503 });
131
134
  const url = new URL(request.url);
@@ -1,4 +1,4 @@
1
- import { typedArrayBuffer, typedArrayByteLength, typedArrayByteOffset } from "./typed-array-intrinsics.js";
1
+ import { copyTypedArray, typedArrayBuffer, typedArrayByteLength, typedArrayByteOffset } from "./typed-array-intrinsics.js";
2
2
  import { createChannelProofVerifier } from "./channel-proof.js";
3
3
  import { types } from "node:util";
4
4
  import { Buffer } from "node:buffer";
@@ -10,11 +10,6 @@ function payloadSize(payload) {
10
10
  return Infinity;
11
11
  }
12
12
  }
13
- function copyBinary(payload, bytes) {
14
- const buffer = typedArrayBuffer(payload);
15
- const offset = typedArrayByteOffset(payload);
16
- return Uint8Array.from(new Uint8Array(buffer, offset, bytes));
17
- }
18
13
  /** Application-owned stream authorization and lifecycle, independent of the socket implementation. */
19
14
  function createDesktopStreams(options) {
20
15
  const now = options.now ?? Date.now;
@@ -103,7 +98,7 @@ function createDesktopStreams(options) {
103
98
  close();
104
99
  return false;
105
100
  }
106
- const bytes = payloadSize(payload);
101
+ const bytes = phase === "open" && typeof payload === "string" && payload.length * 3 <= maxFrameBytes ? payload.length : payloadSize(payload);
107
102
  if (bytes > maxFrameBytes) {
108
103
  close();
109
104
  return false;
@@ -115,7 +110,7 @@ function createDesktopStreams(options) {
115
110
  }
116
111
  let copy;
117
112
  try {
118
- copy = typeof payload === "string" ? payload : copyBinary(payload, bytes);
113
+ copy = typeof payload === "string" ? payload : copyTypedArray(payload, bytes);
119
114
  } catch {
120
115
  close();
121
116
  return false;
@@ -132,7 +127,7 @@ function createDesktopStreams(options) {
132
127
  let output = payload;
133
128
  if (typeof payload !== "string") {
134
129
  const buffer = typedArrayBuffer(payload);
135
- if (types.isSharedArrayBuffer(buffer)) output = copyBinary(payload, bytes);
130
+ if (types.isSharedArrayBuffer(buffer)) output = copyTypedArray(new Uint8Array(buffer, typedArrayByteOffset(payload), bytes), bytes);
136
131
  }
137
132
  if (socket.send(output) === true) return true;
138
133
  } catch {}
@@ -155,7 +150,7 @@ function createDesktopStreams(options) {
155
150
  }
156
151
  let copy;
157
152
  try {
158
- copy = typeof payload === "string" ? payload : copyBinary(payload, bytes);
153
+ copy = typeof payload === "string" ? payload : copyTypedArray(payload, bytes);
159
154
  } catch {
160
155
  close();
161
156
  return;
@@ -4,3 +4,9 @@ export declare function typedArrayBuffer(view: Uint8Array): ArrayBufferLike;
4
4
  export declare function typedArrayByteLength(view: Uint8Array): number;
5
5
  /** Read the internal byte-offset slot; invalid receivers (including proxies) throw. */
6
6
  export declare function typedArrayByteOffset(view: Uint8Array): number;
7
+ /**
8
+ * Copy a view's bytes into a new array through its internal slots. Unlike reading `buffer`,
9
+ * this does not make a small view allocate a separate backing store first. A view that
10
+ * changed length since `byteLength` was read throws instead of being truncated or padded.
11
+ */
12
+ export declare function copyTypedArray(view: Uint8Array, byteLength: number): Uint8Array;
@@ -4,6 +4,7 @@ var typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
4
4
  var typedArrayBufferGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
5
5
  var typedArrayByteLengthGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
6
6
  var typedArrayByteOffsetGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteOffset").get;
7
+ var typedArraySetMethod = typedArrayPrototype.set;
7
8
  /** Read the internal buffer slot; invalid receivers (including proxies) throw. */
8
9
  function typedArrayBuffer(view) {
9
10
  return typedArrayBufferGetter.call(view);
@@ -16,4 +17,15 @@ function typedArrayByteLength(view) {
16
17
  function typedArrayByteOffset(view) {
17
18
  return typedArrayByteOffsetGetter.call(view);
18
19
  }
19
- export { typedArrayBuffer, typedArrayByteLength, typedArrayByteOffset };
20
+ /**
21
+ * Copy a view's bytes into a new array through its internal slots. Unlike reading `buffer`,
22
+ * this does not make a small view allocate a separate backing store first. A view that
23
+ * changed length since `byteLength` was read throws instead of being truncated or padded.
24
+ */
25
+ function copyTypedArray(view, byteLength) {
26
+ if (typedArrayByteLength(view) !== byteLength) throw new RangeError("typed array length changed");
27
+ const copy = new Uint8Array(new ArrayBuffer(byteLength));
28
+ typedArraySetMethod.call(copy, view);
29
+ return copy;
30
+ }
31
+ export { copyTypedArray, typedArrayBuffer, typedArrayByteLength, typedArrayByteOffset };
@@ -32,7 +32,7 @@ export type DeveloperAppConfig = {
32
32
  directory: string;
33
33
  command: readonly string[];
34
34
  port: number;
35
- /** Paths fetched once before the window opens, so the first compile happens early. */
35
+ /** Paths fetched as soon as the dev server answers, so the first compile starts early. */
36
36
  warm?: readonly string[];
37
37
  env?: Readonly<Record<string, string>>;
38
38
  };
@@ -216,9 +216,18 @@ async function runDeveloperApp(config, options = {}) {
216
216
  child.on("exit", () => children.delete(child));
217
217
  return child;
218
218
  };
219
+ let stopping = false;
219
220
  const shutdown = (code) => {
220
- for (const child of children) stopGroup(child);
221
- process.exit(code);
221
+ if (stopping) return;
222
+ stopping = true;
223
+ let running = children.size;
224
+ if (running === 0) process.exit(code);
225
+ for (const child of children) {
226
+ child.once("exit", () => {
227
+ if (--running === 0) process.exit(code);
228
+ });
229
+ stopGroupWithin(child);
230
+ }
222
231
  };
223
232
  process.on("SIGINT", () => shutdown(0));
224
233
  process.on("SIGTERM", () => shutdown(0));
@@ -234,17 +243,19 @@ async function runDeveloperApp(config, options = {}) {
234
243
  shutdown(code ?? 1);
235
244
  });
236
245
  const origin = `http://127.0.0.1:${config.ui.port}`;
237
- log("developer app: starting the UI dev server…");
238
- for (;;) {
239
- try {
240
- const response = await fetch(origin + "/", { signal: AbortSignal.timeout(2e3) });
241
- await response.body?.cancel();
242
- if (response.status < 500) break;
243
- } catch {}
244
- await new Promise((done) => setTimeout(done, 100));
245
- }
246
- await Promise.all((config.ui.warm ?? []).map((path) => fetch(origin + path, { signal: AbortSignal.timeout(12e4) }).then((response) => response.arrayBuffer()).catch(() => void 0)));
247
- log(`developer app: UI on ${origin} (hot reload); starting ${identity.name}`);
246
+ log(`developer app: starting the UI dev server and ${identity.name} together…`);
247
+ const uiReady = (async () => {
248
+ for (;;) {
249
+ try {
250
+ const response = await fetch(origin + "/", { signal: AbortSignal.timeout(2e3) });
251
+ await response.body?.cancel();
252
+ if (response.status < 500) break;
253
+ } catch {}
254
+ await new Promise((done) => setTimeout(done, 100));
255
+ }
256
+ await Promise.all((config.ui.warm ?? []).map((path) => fetch(origin + path, { signal: AbortSignal.timeout(12e4) }).then((response) => response.arrayBuffer()).catch(() => void 0)));
257
+ log(`developer app: UI on ${origin} (hot reload)`);
258
+ })();
248
259
  let shell;
249
260
  let restarting = false;
250
261
  const shellEnv = developerAppShellEnv(config);
@@ -271,6 +282,7 @@ async function runDeveloperApp(config, options = {}) {
271
282
  restarting = true;
272
283
  running.once("exit", () => {
273
284
  restarting = false;
285
+ if (stopping) return;
274
286
  startShell();
275
287
  started();
276
288
  });
@@ -279,6 +291,7 @@ async function runDeveloperApp(config, options = {}) {
279
291
  });
280
292
  for (const folder of config.watch ?? ["src"]) watch(join(config.shellDirectory, folder), { recursive: true }, (_event, file) => onChange(file ? String(file) : null));
281
293
  startShell();
294
+ await uiReady;
282
295
  return new Promise(() => {});
283
296
  }
284
297
  var quote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
@@ -1 +1 @@
1
- {"version":"0.39.2","commit":"fea5e125f2bc439593e77b52f4b3660d57308b85"}
1
+ {"version":"0.39.4","commit":"d2410b715d3fc91dc7fe7b20814e9e92b66fb4a7"}
@@ -52,4 +52,5 @@ export declare function qualifyCommandArtifact(options: {
52
52
  version: string;
53
53
  env: Record<string, string | undefined>;
54
54
  settleMs?: number;
55
+ outputDrainMs?: number;
55
56
  }): Promise<CommandQualification>;