@air-jam/devtools 0.9.3 → 1.0.0-beta.1

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 (263) hide show
  1. package/README.md +60 -0
  2. package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
  3. package/dist/chunk-2O67AXCU.js.map +1 -0
  4. package/dist/chunk-AO3ZDXF6.js +142 -0
  5. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  6. package/dist/chunk-ART5TEYT.js +472 -0
  7. package/dist/chunk-ART5TEYT.js.map +1 -0
  8. package/dist/chunk-ASC2CK2R.js +77 -0
  9. package/dist/chunk-ASC2CK2R.js.map +1 -0
  10. package/dist/chunk-E3UZZGAV.js +50 -0
  11. package/dist/chunk-E3UZZGAV.js.map +1 -0
  12. package/dist/chunk-EJTE7UKX.js +64 -0
  13. package/dist/chunk-EJTE7UKX.js.map +1 -0
  14. package/dist/chunk-ESFKNN75.js +110 -0
  15. package/dist/chunk-ESFKNN75.js.map +1 -0
  16. package/dist/chunk-EU7A6PXW.js +1339 -0
  17. package/dist/chunk-EU7A6PXW.js.map +1 -0
  18. package/dist/chunk-FN7E6EA7.js +549 -0
  19. package/dist/chunk-FN7E6EA7.js.map +1 -0
  20. package/dist/chunk-GDFAWHGA.js +190 -0
  21. package/dist/chunk-GDFAWHGA.js.map +1 -0
  22. package/dist/chunk-HZUGBH4Y.js +347 -0
  23. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  24. package/dist/chunk-ITKAOEGX.js +93 -0
  25. package/dist/chunk-ITKAOEGX.js.map +1 -0
  26. package/dist/chunk-JBCUTWRI.js +897 -0
  27. package/dist/chunk-JBCUTWRI.js.map +1 -0
  28. package/dist/chunk-JSI5S4WP.js +1174 -0
  29. package/dist/chunk-JSI5S4WP.js.map +1 -0
  30. package/dist/chunk-L4D675BG.js +97 -0
  31. package/dist/chunk-L4D675BG.js.map +1 -0
  32. package/dist/chunk-M6CJ7GQC.js +133 -0
  33. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  34. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  35. package/dist/chunk-MEIMOSZC.js.map +1 -0
  36. package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
  37. package/dist/chunk-O3XG3FNL.js.map +1 -0
  38. package/dist/chunk-OM6SCJ7H.js +18 -0
  39. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  40. package/dist/chunk-PKD4WVX5.js +63 -0
  41. package/dist/chunk-PKD4WVX5.js.map +1 -0
  42. package/dist/chunk-PMBLXGFM.js +3384 -0
  43. package/dist/chunk-PMBLXGFM.js.map +1 -0
  44. package/dist/chunk-PMNE5GIN.js +279 -0
  45. package/dist/chunk-PMNE5GIN.js.map +1 -0
  46. package/dist/chunk-QAWI64VR.js +148 -0
  47. package/dist/chunk-QAWI64VR.js.map +1 -0
  48. package/dist/chunk-QGADSPHZ.js +449 -0
  49. package/dist/chunk-QGADSPHZ.js.map +1 -0
  50. package/dist/chunk-SPYN66UV.js +338 -0
  51. package/dist/chunk-SPYN66UV.js.map +1 -0
  52. package/dist/context.d.ts +9 -3
  53. package/dist/context.js +2 -1
  54. package/dist/controller.d.ts +33 -7
  55. package/dist/controller.js +18 -8
  56. package/dist/dependencies.d.ts +44 -0
  57. package/dist/dependencies.js +10 -0
  58. package/dist/dev.d.ts +9 -3
  59. package/dist/dev.js +3 -4
  60. package/dist/game-builds.d.ts +200 -0
  61. package/dist/game-builds.js +16 -0
  62. package/dist/game-builds.js.map +1 -0
  63. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  64. package/dist/game-runs.d.ts +1452 -0
  65. package/dist/game-runs.js +76 -0
  66. package/dist/game-runs.js.map +1 -0
  67. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  68. package/dist/game-session-broker.d.ts +4 -57
  69. package/dist/game-session-broker.js +33 -228
  70. package/dist/game-session-broker.js.map +1 -1
  71. package/dist/game-session.d.ts +3931 -10
  72. package/dist/game-session.js +186 -15
  73. package/dist/game-session.js.map +1 -1
  74. package/dist/game-settings.d.ts +16 -0
  75. package/dist/game-settings.js +237 -0
  76. package/dist/game-settings.js.map +1 -0
  77. package/dist/games.d.ts +11 -4
  78. package/dist/games.js +4 -2
  79. package/dist/harness/visual.d.ts +34 -151
  80. package/dist/harness/visual.js +6 -1
  81. package/dist/logs.d.ts +8 -2
  82. package/dist/logs.js +3 -4
  83. package/dist/logs.js.map +1 -1
  84. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  85. package/dist/mcp-config.js +2 -1
  86. package/dist/mcp-config.js.map +1 -1
  87. package/dist/platform-auth.d.ts +8 -111
  88. package/dist/platform-auth.js +9 -1
  89. package/dist/platform-game-analytics.d.ts +51 -0
  90. package/dist/platform-game-analytics.js +49 -0
  91. package/dist/platform-game-analytics.js.map +1 -0
  92. package/dist/platform-game-app-id.d.ts +46 -0
  93. package/dist/platform-game-app-id.js +93 -0
  94. package/dist/platform-game-app-id.js.map +1 -0
  95. package/dist/platform-game-media.d.ts +40 -2
  96. package/dist/platform-game-media.js +1 -1
  97. package/dist/platform-games.d.ts +24 -2
  98. package/dist/platform-games.js +16 -84
  99. package/dist/platform-games.js.map +1 -1
  100. package/dist/quality.d.ts +9 -3
  101. package/dist/quality.js +3 -4
  102. package/dist/quality.js.map +1 -1
  103. package/dist/release.d.ts +226 -16
  104. package/dist/release.js +18 -1331
  105. package/dist/release.js.map +1 -1
  106. package/dist/rooms-check.d.ts +90 -0
  107. package/dist/rooms-check.js +717 -0
  108. package/dist/rooms-check.js.map +1 -0
  109. package/dist/source-tree-contract.d.ts +16 -0
  110. package/dist/source-tree-contract.js +13 -0
  111. package/dist/source-tree-contract.js.map +1 -0
  112. package/dist/testing.d.ts +464 -0
  113. package/dist/testing.js +27 -0
  114. package/dist/testing.js.map +1 -0
  115. package/dist/tooling/describe-game.js +54 -0
  116. package/dist/tooling/describe-game.js.map +1 -0
  117. package/dist/tooling/game-session-broker.js +28 -0
  118. package/dist/tooling/game-session-broker.js.map +1 -0
  119. package/dist/tooling/hold-runtime-host.js +769 -67
  120. package/dist/tooling/hold-runtime-host.js.map +1 -1
  121. package/dist/tooling/list-visual-scenarios.js +18 -55
  122. package/dist/tooling/list-visual-scenarios.js.map +1 -1
  123. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  124. package/dist/tooling/process-scope-guard.d.ts +2 -0
  125. package/dist/tooling/process-scope-guard.js +388 -0
  126. package/dist/tooling/process-scope-guard.js.map +1 -0
  127. package/dist/tooling/process-scope-windows.ps1 +148 -0
  128. package/dist/tooling/rooms-check-device.d.ts +2 -0
  129. package/dist/tooling/rooms-check-device.js +498 -0
  130. package/dist/tooling/rooms-check-device.js.map +1 -0
  131. package/dist/tooling/run-headless-room.d.ts +2 -0
  132. package/dist/tooling/run-headless-room.js +287 -0
  133. package/dist/tooling/run-headless-room.js.map +1 -0
  134. package/dist/tooling/run-test-profile.d.ts +2 -0
  135. package/dist/tooling/run-test-profile.js +181 -0
  136. package/dist/tooling/run-test-profile.js.map +1 -0
  137. package/dist/tooling/run-visual-capture.js +70 -34
  138. package/dist/tooling/run-visual-capture.js.map +1 -1
  139. package/dist/tooling/seal-game-build.d.ts +2 -0
  140. package/dist/tooling/seal-game-build.js +120 -0
  141. package/dist/tooling/seal-game-build.js.map +1 -0
  142. package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
  143. package/dist/types-DyRD-ym1.d.ts +141 -0
  144. package/dist/visual.d.ts +9 -3
  145. package/dist/visual.js +24 -68
  146. package/dist/visual.js.map +1 -1
  147. package/package.json +51 -14
  148. package/src/bounded-response.ts +28 -0
  149. package/src/built-game-runtime.ts +152 -0
  150. package/src/context.ts +2 -13
  151. package/src/controller-protocol.ts +22 -0
  152. package/src/controller.ts +747 -597
  153. package/src/current-room-host.ts +166 -0
  154. package/src/decision-provider.ts +102 -0
  155. package/src/dependencies.ts +176 -0
  156. package/src/dependency-install-contract.ts +12 -0
  157. package/src/dev.ts +46 -50
  158. package/src/game-action-observation.ts +11 -1
  159. package/src/game-build-protocol.ts +72 -0
  160. package/src/game-build.ts +483 -0
  161. package/src/game-run-owner.ts +2358 -0
  162. package/src/game-run-protocol.ts +448 -0
  163. package/src/game-run-record.ts +92 -0
  164. package/src/game-run-replay.ts +95 -0
  165. package/src/game-run-watch.ts +155 -0
  166. package/src/game-session-broker.ts +689 -197
  167. package/src/game-session-operations.ts +61 -0
  168. package/src/game-session-protocol.ts +180 -0
  169. package/src/game-session-runtime.ts +861 -0
  170. package/src/game-session.ts +164 -417
  171. package/src/game-settings.ts +295 -0
  172. package/src/games.ts +88 -92
  173. package/src/harness/visual/browser.ts +100 -0
  174. package/src/harness/visual/controller-observation.ts +181 -0
  175. package/src/harness/visual/runner.ts +24 -21
  176. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  177. package/src/harness/visual/scenario-contract.ts +1 -2
  178. package/src/harness/visual/scenario-helpers.ts +5 -1
  179. package/src/harness/visual/screencast.ts +155 -0
  180. package/src/harness/visual/session.ts +72 -41
  181. package/src/harness/visual/types.ts +8 -5
  182. package/src/headless-room-protocol.ts +112 -0
  183. package/src/headless-room.ts +222 -0
  184. package/src/helper-channel.ts +229 -0
  185. package/src/helper-scripts.ts +25 -5
  186. package/src/installed-dependencies.ts +74 -0
  187. package/src/managed-process-scope.ts +481 -0
  188. package/src/node-process-environment.ts +10 -0
  189. package/src/platform-auth.ts +194 -55
  190. package/src/platform-game-analytics.ts +50 -0
  191. package/src/platform-game-app-id.ts +99 -0
  192. package/src/platform-games.ts +13 -111
  193. package/src/policy-artifact-contract.ts +52 -0
  194. package/src/policy-artifacts.ts +134 -0
  195. package/src/process-scope-admission.ts +50 -0
  196. package/src/process-scope-protocol.ts +66 -0
  197. package/src/process-scope.ts +327 -0
  198. package/src/release.ts +28 -42
  199. package/src/rooms-check-fleet.ts +194 -0
  200. package/src/rooms-check-link.ts +138 -0
  201. package/src/rooms-check-protocol.ts +244 -0
  202. package/src/rooms-check.ts +797 -0
  203. package/src/runtime-owner-protocol.ts +106 -18
  204. package/src/source-tree-contract.ts +70 -0
  205. package/src/source-tree.ts +84 -0
  206. package/src/test-profile-process.ts +153 -0
  207. package/src/test-profile-protocol.ts +116 -0
  208. package/src/testing.ts +430 -0
  209. package/src/tooling/declaration-hook.ts +52 -0
  210. package/src/tooling/describe-game.ts +49 -0
  211. package/src/tooling/game-session-broker.ts +7 -0
  212. package/src/tooling/hold-runtime-host.ts +255 -38
  213. package/src/tooling/list-visual-scenarios.ts +19 -62
  214. package/src/tooling/load-game.ts +79 -0
  215. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  216. package/src/tooling/process-scope-guard.ts +213 -0
  217. package/src/tooling/process-scope-windows.ps1 +148 -0
  218. package/src/tooling/rooms-check-device.ts +493 -0
  219. package/src/tooling/run-headless-room.ts +326 -0
  220. package/src/tooling/run-test-profile.ts +190 -0
  221. package/src/tooling/run-visual-capture.ts +37 -23
  222. package/src/tooling/runtime-owner-actions.ts +23 -0
  223. package/src/tooling/seal-game-build.ts +118 -0
  224. package/src/tooling/visual-pack.ts +10 -45
  225. package/src/types.ts +54 -77
  226. package/src/visual.ts +14 -22
  227. package/src/windows-process-scopes.ts +189 -0
  228. package/dist/agent.d.ts +0 -15
  229. package/dist/agent.js +0 -19
  230. package/dist/chunk-5YAARMW5.js +0 -36
  231. package/dist/chunk-5YAARMW5.js.map +0 -1
  232. package/dist/chunk-6WQODT37.js +0 -1019
  233. package/dist/chunk-6WQODT37.js.map +0 -1
  234. package/dist/chunk-CKFT2ZJE.js.map +0 -1
  235. package/dist/chunk-ER3Q2C4G.js +0 -358
  236. package/dist/chunk-ER3Q2C4G.js.map +0 -1
  237. package/dist/chunk-GUEZP773.js.map +0 -1
  238. package/dist/chunk-HIDNI56E.js +0 -33
  239. package/dist/chunk-HIDNI56E.js.map +0 -1
  240. package/dist/chunk-QKXS5D35.js +0 -43
  241. package/dist/chunk-QKXS5D35.js.map +0 -1
  242. package/dist/chunk-S4LSCEVE.js +0 -261
  243. package/dist/chunk-S4LSCEVE.js.map +0 -1
  244. package/dist/chunk-VKMJO6VN.js.map +0 -1
  245. package/dist/chunk-WFUR3MXY.js +0 -67
  246. package/dist/chunk-WFUR3MXY.js.map +0 -1
  247. package/dist/chunk-XEMR7KUE.js +0 -361
  248. package/dist/chunk-XEMR7KUE.js.map +0 -1
  249. package/dist/chunk-ZLPD7FY5.js +0 -191
  250. package/dist/chunk-ZLPD7FY5.js.map +0 -1
  251. package/dist/tooling/agent-contract.js +0 -193
  252. package/dist/tooling/agent-contract.js.map +0 -1
  253. package/dist/tooling/inspect-airjam-agent.js +0 -37
  254. package/dist/tooling/inspect-airjam-agent.js.map +0 -1
  255. package/src/agent.ts +0 -380
  256. package/src/tooling/agent-contract.ts +0 -232
  257. package/src/tooling/agent-declaration.ts +0 -36
  258. package/src/tooling/airjam-agent-inspection.ts +0 -45
  259. package/src/tooling/airjam-agent.ts +0 -118
  260. package/src/tooling/inspect-airjam-agent.ts +0 -20
  261. /package/dist/{agent.js.map → dependencies.js.map} +0 -0
  262. /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
  263. /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
package/dist/release.js CHANGED
@@ -1,1336 +1,23 @@
1
1
  import {
2
- requestPlatformMachineApi,
3
- resolvePlatformMachineAuth
4
- } from "./chunk-VKMJO6VN.js";
5
- import {
6
- runCommandResult
7
- } from "./chunk-5YAARMW5.js";
8
- import {
9
- detectProjectContext,
10
- pathExists,
11
- readPackageJson,
12
- resolveCandidatePath,
13
- resolveCanonicalPath
14
- } from "./chunk-S4LSCEVE.js";
15
-
16
- // src/release.ts
17
- import {
18
- platformMachineCreateReleaseDraftResultSchema,
19
- platformMachineFinalizeReleaseUploadResultSchema,
20
- platformMachineGetReleaseResultSchema,
21
- platformMachineListOwnedGamesResultSchema,
22
- platformMachineListReleasesResultSchema,
23
- platformMachinePublishReleaseResultSchema,
24
- platformMachineRequestReleaseGenerationExportResultSchema,
25
- platformMachineRequestReleaseUploadTargetResultSchema
26
- } from "@air-jam/sdk/platform-machine";
27
- import {
28
- HOSTED_RELEASE_CONTROLLER_PATH,
29
- HOSTED_RELEASE_ENTRY_PATH,
30
- HOSTED_RELEASE_HOST_PATH,
31
- HOSTED_RELEASE_MANIFEST_PATH,
32
- createHostedReleaseArtifactManifest,
33
- hostedReleaseArtifactManifestSchema
34
- } from "@air-jam/sdk/release";
35
- import { createHash } from "crypto";
36
- import { createWriteStream } from "fs";
37
- import {
38
- copyFile,
39
- mkdir,
40
- mkdtemp,
41
- open,
42
- readFile,
43
- readdir,
44
- rm,
45
- stat,
46
- writeFile
47
- } from "fs/promises";
48
- import os from "os";
49
- import path from "path";
50
- import * as yauzl from "yauzl";
51
- import yazl from "yazl";
52
- var IGNORED_ARCHIVE_PATHS = ["__MACOSX/", ".DS_Store"];
53
- var VENDORED_FONT_ASSET_DIR = "assets/airjam-vendored/fonts";
54
- var REMOTE_FONT_STYLESHEET_HOSTS = /* @__PURE__ */ new Set(["fonts.googleapis.com"]);
55
- var REMOTE_FONT_ASSET_HOSTS = /* @__PURE__ */ new Set(["fonts.gstatic.com"]);
56
- var REMOTE_CSS_IMPORT_PATTERN = /@import\s*(?:url\(\s*)?(?<quote>["']?)(?<url>https?:\/\/[^"')\s]+)\k<quote>\s*\)?\s*;/g;
57
- var REMOTE_CSS_URL_PATTERN = /url\(\s*(?<quote>["']?)(?<url>https?:\/\/[^"')\s]+)\k<quote>\s*\)/g;
58
- var FONT_ASSET_EXTENSION_PATTERN = /\.(woff2?|ttf|otf|eot)(?:[?#].*)?$/i;
59
- var CSS_EXTENSION_PATTERN = /\.css(?:[?#].*)?$/i;
60
- var FONT_FETCH_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
61
- var DEFAULT_RELEASE_PROCESSING_TIMEOUT_MS = 10 * 60 * 1e3;
62
- var RELEASE_PROCESSING_POLL_INTERVAL_MS = 2e3;
63
- var wait = async (durationMs) => new Promise((resolve) => setTimeout(resolve, durationMs));
64
- var sanitizePathSegment = (value) => value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
65
- var parsePackageManagerField = (value) => {
66
- const normalized = value?.trim().toLowerCase() ?? "";
67
- if (normalized.startsWith("pnpm@")) {
68
- return "pnpm";
69
- }
70
- if (normalized.startsWith("npm@")) {
71
- return "npm";
72
- }
73
- if (normalized.startsWith("yarn@")) {
74
- return "yarn";
75
- }
76
- if (normalized.startsWith("bun@")) {
77
- return "bun";
78
- }
79
- return "unknown";
80
- };
81
- var resolvePackageManager = async (targetDir) => {
82
- const packageJson = await readPackageJson(targetDir);
83
- const packageManagerFromField = parsePackageManagerField(
84
- packageJson?.value.packageManager
85
- );
86
- if (packageManagerFromField !== "unknown") {
87
- return packageManagerFromField;
88
- }
89
- const context = await detectProjectContext({ cwd: targetDir });
90
- return context.packageManager;
91
- };
92
- var getDefaultReleaseBundlePath = ({
93
- projectDir,
94
- packageName,
95
- packageVersion
96
- }) => {
97
- const normalizedReleaseLabel = sanitizePathSegment(packageVersion || "dev");
98
- const normalizedPackageName = sanitizePathSegment(
99
- packageName || "airjam-game"
100
- );
101
- return path.join(
102
- projectDir,
103
- ".airjam",
104
- "releases",
105
- normalizedReleaseLabel,
106
- `${normalizedPackageName}-hosted-release.zip`
107
- );
108
- };
109
- var readConfiguredControllerPath = async (configPath) => {
110
- if (!configPath || !await pathExists(configPath)) {
111
- return null;
112
- }
113
- const source = await readFile(configPath, "utf8");
114
- const match = source.match(/controllerPath\s*:\s*["'`](?<path>[^"'`]+)["'`]/);
115
- return match?.groups?.path?.trim() || null;
116
- };
117
- var getLocalAirJamConfigPath = async (projectDir) => resolveCandidatePath(projectDir, [
118
- "src/airjam.config.ts",
119
- "src/airjam.config.tsx",
120
- "src/airjam.config.js",
121
- "src/airjam.config.mjs",
122
- "airjam.config.ts",
123
- "airjam.config.tsx",
124
- "airjam.config.js",
125
- "airjam.config.mjs"
126
- ]);
127
- var collectDirectoryFiles = async (sourceDir) => {
128
- const entries = await readdir(sourceDir);
129
- const files = [];
130
- for (const entry of entries) {
131
- const absolutePath = path.join(sourceDir, entry);
132
- const entryStats = await stat(absolutePath);
133
- if (entryStats.isDirectory()) {
134
- files.push(...await collectDirectoryFiles(absolutePath));
135
- continue;
136
- }
137
- files.push(absolutePath);
138
- }
139
- return files;
140
- };
141
- var hashContent = (value) => createHash("sha256").update(value).digest("hex").slice(0, 16);
142
- var ensurePosixRelativePath = (fromDir, toPath) => path.relative(fromDir, toPath).replace(/\\/g, "/");
143
- var ensureExplicitRelativeUrl = (value) => {
144
- if (!value || value.startsWith("./") || value.startsWith("../")) {
145
- return value;
146
- }
147
- return `./${value}`;
148
- };
149
- var isRemoteFontStylesheetUrl = (value) => {
150
- try {
151
- const url = new URL(value);
152
- return REMOTE_FONT_STYLESHEET_HOSTS.has(url.hostname) || CSS_EXTENSION_PATTERN.test(url.pathname);
153
- } catch {
154
- return false;
155
- }
156
- };
157
- var isRemoteFontAssetUrl = (value) => {
158
- try {
159
- const url = new URL(value);
160
- return REMOTE_FONT_ASSET_HOSTS.has(url.hostname) || FONT_ASSET_EXTENSION_PATTERN.test(url.pathname);
161
- } catch {
162
- return false;
163
- }
164
- };
165
- var inferFileExtensionFromContentType = (contentType) => {
166
- if (!contentType) {
167
- return null;
168
- }
169
- const normalized = contentType.toLowerCase();
170
- if (normalized.includes("text/css")) {
171
- return ".css";
172
- }
173
- if (normalized.includes("font/woff2")) {
174
- return ".woff2";
175
- }
176
- if (normalized.includes("font/woff")) {
177
- return ".woff";
178
- }
179
- if (normalized.includes("font/ttf")) {
180
- return ".ttf";
181
- }
182
- if (normalized.includes("font/otf")) {
183
- return ".otf";
184
- }
185
- if (normalized.includes("application/vnd.ms-fontobject")) {
186
- return ".eot";
187
- }
188
- if (normalized.includes("application/octet-stream")) {
189
- return null;
190
- }
191
- return null;
192
- };
193
- var inferFileExtensionFromUrl = (value) => {
194
- try {
195
- const { pathname } = new URL(value);
196
- const matched = pathname.match(/\.(woff2?|ttf|otf|eot|css)$/i);
197
- return matched ? matched[0].toLowerCase() : null;
198
- } catch {
199
- return null;
200
- }
201
- };
202
- var fetchRemoteAsset = async (value) => {
203
- const response = await fetch(value, {
204
- headers: {
205
- "user-agent": FONT_FETCH_USER_AGENT
206
- }
207
- });
208
- if (!response.ok) {
209
- throw new Error(
210
- `Failed to fetch remote font asset ${value} (${response.status}).`
211
- );
212
- }
213
- const buffer = Buffer.from(await response.arrayBuffer());
214
- return {
215
- buffer,
216
- contentType: response.headers.get("content-type")
217
- };
218
- };
219
- var rewriteCssAsync = async ({
220
- css,
221
- replacePattern,
222
- replacer
223
- }) => {
224
- const pieces = [];
225
- let lastIndex = 0;
226
- let match;
227
- const pattern = new RegExp(replacePattern.source, replacePattern.flags);
228
- while ((match = pattern.exec(css)) !== null) {
229
- const matchedText = match[0];
230
- const index = match.index;
231
- pieces.push(css.slice(lastIndex, index));
232
- pieces.push(await replacer(match));
233
- lastIndex = index + matchedText.length;
234
- }
235
- pieces.push(css.slice(lastIndex));
236
- return pieces.join("");
237
- };
238
- var vendorRemoteFontAsset = async ({
239
- assetUrl,
240
- bundleRoot,
241
- state
242
- }) => {
243
- const cached = state.assetByUrl.get(assetUrl);
244
- if (cached) {
245
- return cached;
246
- }
247
- const { buffer, contentType } = await fetchRemoteAsset(assetUrl);
248
- const extension = inferFileExtensionFromContentType(contentType) || inferFileExtensionFromUrl(assetUrl) || ".bin";
249
- const fileName = `${hashContent(assetUrl)}${extension}`;
250
- const relativePath = path.posix.join(VENDORED_FONT_ASSET_DIR, fileName);
251
- const absolutePath = path.join(bundleRoot, relativePath);
252
- await mkdir(path.dirname(absolutePath), { recursive: true });
253
- await writeFile(absolutePath, buffer);
254
- state.assetByUrl.set(assetUrl, relativePath);
255
- return relativePath;
256
- };
257
- var vendorRemoteFontStylesheet = async ({
258
- stylesheetUrl,
259
- bundleRoot,
260
- state
261
- }) => {
262
- const cached = state.cssByUrl.get(stylesheetUrl);
263
- if (cached) {
264
- return cached;
265
- }
266
- const { buffer, contentType } = await fetchRemoteAsset(stylesheetUrl);
267
- if (contentType && !contentType.toLowerCase().includes("text/css")) {
268
- throw new Error(
269
- `Expected remote stylesheet ${stylesheetUrl} to return CSS but received ${contentType}.`
270
- );
271
- }
272
- const stylesheetText = buffer.toString("utf8");
273
- const rewrittenCss = await rewriteCssAsync({
274
- css: stylesheetText,
275
- replacePattern: REMOTE_CSS_URL_PATTERN,
276
- replacer: async (match) => {
277
- const remoteUrl = match.groups?.url?.trim();
278
- if (!remoteUrl) {
279
- return match[0];
280
- }
281
- const absoluteUrl = new URL(remoteUrl, stylesheetUrl).toString();
282
- const assetPath = await vendorRemoteFontAsset({
283
- assetUrl: absoluteUrl,
284
- bundleRoot,
285
- state
286
- });
287
- return `url("./${path.posix.basename(assetPath)}")`;
288
- }
289
- });
290
- const relativePath = path.posix.join(
291
- VENDORED_FONT_ASSET_DIR,
292
- `${hashContent(stylesheetUrl)}.css`
293
- );
294
- const absolutePath = path.join(bundleRoot, relativePath);
295
- await mkdir(path.dirname(absolutePath), { recursive: true });
296
- await writeFile(absolutePath, rewrittenCss, "utf8");
297
- state.cssByUrl.set(stylesheetUrl, relativePath);
298
- return relativePath;
299
- };
300
- var vendorCssFontDependencies = async ({
301
- bundleRoot
302
- }) => {
303
- const files = await collectDirectoryFiles(bundleRoot);
304
- const cssFiles = files.filter((filePath) => filePath.endsWith(".css"));
305
- const state = {
306
- cssByUrl: /* @__PURE__ */ new Map(),
307
- assetByUrl: /* @__PURE__ */ new Map()
308
- };
309
- for (const cssFilePath of cssFiles) {
310
- const originalCss = await readFile(cssFilePath, "utf8");
311
- const cssDir = path.dirname(cssFilePath);
312
- let rewrittenCss = await rewriteCssAsync({
313
- css: originalCss,
314
- replacePattern: REMOTE_CSS_IMPORT_PATTERN,
315
- replacer: async (match) => {
316
- const remoteUrl = match.groups?.url?.trim();
317
- if (!remoteUrl || !isRemoteFontStylesheetUrl(remoteUrl)) {
318
- return match[0];
319
- }
320
- const vendoredStylesheet = await vendorRemoteFontStylesheet({
321
- stylesheetUrl: remoteUrl,
322
- bundleRoot,
323
- state
324
- });
325
- const relativeImport = ensureExplicitRelativeUrl(
326
- ensurePosixRelativePath(
327
- cssDir,
328
- path.join(bundleRoot, vendoredStylesheet)
329
- )
330
- );
331
- return `@import url("${relativeImport}");`;
332
- }
333
- });
334
- rewrittenCss = await rewriteCssAsync({
335
- css: rewrittenCss,
336
- replacePattern: REMOTE_CSS_URL_PATTERN,
337
- replacer: async (match) => {
338
- const remoteUrl = match.groups?.url?.trim();
339
- if (!remoteUrl || !isRemoteFontAssetUrl(remoteUrl)) {
340
- return match[0];
341
- }
342
- const vendoredAsset = await vendorRemoteFontAsset({
343
- assetUrl: remoteUrl,
344
- bundleRoot,
345
- state
346
- });
347
- const relativeAssetPath = ensureExplicitRelativeUrl(
348
- ensurePosixRelativePath(cssDir, path.join(bundleRoot, vendoredAsset))
349
- );
350
- return `url("${relativeAssetPath}")`;
351
- }
352
- });
353
- if (rewrittenCss !== originalCss) {
354
- await writeFile(cssFilePath, rewrittenCss, "utf8");
355
- }
356
- }
357
- };
358
- var materializeBundleSourceTree = async ({
359
- sourceDir
360
- }) => {
361
- const tempRoot = await mkdtemp(
362
- path.join(os.tmpdir(), "airjam-hosted-release-bundle-")
363
- );
364
- const bundleRoot = path.join(tempRoot, "dist");
365
- const files = await collectDirectoryFiles(sourceDir);
366
- for (const sourcePath of files) {
367
- const relativePath = path.relative(sourceDir, sourcePath);
368
- const targetPath = path.join(bundleRoot, relativePath);
369
- await mkdir(path.dirname(targetPath), { recursive: true });
370
- await copyFile(sourcePath, targetPath);
371
- }
372
- await vendorCssFontDependencies({ bundleRoot });
373
- return bundleRoot;
374
- };
375
- var isIgnoredArchiveEntry = (archivePath) => IGNORED_ARCHIVE_PATHS.some(
376
- (ignoredPath) => archivePath === ignoredPath || archivePath.startsWith(ignoredPath) || archivePath.endsWith(`/${ignoredPath}`)
377
- );
378
- var hasPathTraversal = (value) => {
379
- const segments = value.split("/");
380
- return segments.some(
381
- (segment) => segment.length === 0 || segment === "." || segment === ".."
382
- );
383
- };
384
- var normalizeArchiveEntryPath = (rawPath) => {
385
- const canonicalPath = rawPath.replaceAll("\\", "/").trim();
386
- if (!canonicalPath || canonicalPath.includes("\0")) {
387
- throw new Error("Release archive contains an invalid empty entry path.");
388
- }
389
- const isDirectory = canonicalPath.endsWith("/");
390
- const normalizedPath = path.posix.normalize(
391
- isDirectory ? canonicalPath.slice(0, -1) : canonicalPath
392
- );
393
- if (!normalizedPath || normalizedPath === "." || path.posix.isAbsolute(normalizedPath) || normalizedPath.startsWith("../") || normalizedPath === ".." || hasPathTraversal(normalizedPath)) {
394
- throw new Error(
395
- `Release archive entry escapes the allowed root: ${rawPath}`
396
- );
397
- }
398
- return {
399
- archivePath: normalizedPath,
400
- isDirectory
401
- };
402
- };
403
- var getUnixMode = (entry) => {
404
- const mode = entry.externalFileAttributes >>> 16;
405
- return mode === 0 ? null : mode;
406
- };
407
- var isZipSymlink = (entry) => {
408
- const unixMode = getUnixMode(entry);
409
- if (unixMode === null) {
410
- return false;
411
- }
412
- return (unixMode & 61440) === 40960;
413
- };
414
- var buildArgsByPackageManager = {
415
- npm: ["run", "build"],
416
- pnpm: ["build"],
417
- yarn: ["build"],
418
- bun: ["run", "build"]
419
- };
420
- var resolveBuildCommand = (packageManager) => {
421
- return packageManager === "unknown" ? null : {
422
- command: packageManager,
423
- args: [...buildArgsByPackageManager[packageManager]]
424
- };
425
- };
426
- var runBuild = async ({
427
- projectDir,
428
- packageManager
429
- }) => {
430
- const buildCommand = resolveBuildCommand(packageManager);
431
- if (!buildCommand) {
432
- return {
433
- command: "unknown",
434
- args: [],
435
- cwd: projectDir,
436
- exitCode: null,
437
- signal: null,
438
- stdout: "",
439
- stderr: "Unknown package manager. Cannot run build script.",
440
- durationMs: 0,
441
- ok: false
442
- };
443
- }
444
- return runCommandResult({
445
- command: buildCommand.command,
446
- args: buildCommand.args,
447
- cwd: projectDir
448
- });
449
- };
450
- var createIssue = (code, severity, message, issuePath = null) => ({
451
- code,
452
- severity,
453
- message,
454
- path: issuePath
455
- });
456
- var openZipFile = async (archiveBuffer) => new Promise((resolve, reject) => {
457
- yauzl.fromBuffer(
458
- archiveBuffer,
459
- {
460
- lazyEntries: true,
461
- validateEntrySizes: true,
462
- strictFileNames: false
463
- },
464
- (error, zipFile) => {
465
- if (error) {
466
- reject(error);
467
- return;
468
- }
469
- if (!zipFile) {
470
- reject(new Error("Could not open release archive."));
471
- return;
472
- }
473
- resolve(zipFile);
474
- }
475
- );
476
- });
477
- var openZipEntryReadStream = async (zipFile, entry) => new Promise((resolve, reject) => {
478
- zipFile.openReadStream(entry, (error, stream) => {
479
- if (error) {
480
- reject(error);
481
- return;
482
- }
483
- if (!stream) {
484
- reject(new Error(`Could not open zip entry stream: ${entry.fileName}`));
485
- return;
486
- }
487
- resolve(stream);
488
- });
489
- });
490
- var readStreamBuffer = async (stream) => new Promise((resolve, reject) => {
491
- const chunks = [];
492
- stream.on("data", (chunk) => {
493
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
494
- });
495
- stream.on("end", () => resolve(Buffer.concat(chunks)));
496
- stream.on("error", reject);
497
- });
498
- var resolveArchiveRoot = (archivePaths) => {
499
- if (archivePaths.includes(HOSTED_RELEASE_ENTRY_PATH)) {
500
- return {
501
- entryPath: HOSTED_RELEASE_ENTRY_PATH,
502
- wrapperDirectory: null
503
- };
504
- }
505
- const topLevelSegments = new Set(
506
- archivePaths.map((archivePath) => archivePath.split("/")[0])
507
- );
508
- if (topLevelSegments.size !== 1) {
509
- throw new Error(
510
- "Release archive must contain a root index.html or a single top-level wrapper directory."
511
- );
512
- }
513
- const [wrapperDirectory] = [...topLevelSegments];
514
- if (!archivePaths.includes(`${wrapperDirectory}/${HOSTED_RELEASE_ENTRY_PATH}`)) {
515
- throw new Error(
516
- "Release archive wrapper directory must contain index.html at its root."
517
- );
518
- }
519
- return {
520
- entryPath: HOSTED_RELEASE_ENTRY_PATH,
521
- wrapperDirectory
522
- };
523
- };
524
- var inspectProjectRelease = async ({
525
- projectDir,
526
- distDir,
527
- packageManager
528
- }) => {
529
- const packageJson = await readPackageJson(projectDir);
530
- const configPath = await getLocalAirJamConfigPath(projectDir);
531
- const configSource = configPath ? await readFile(configPath, "utf8").catch(() => "") : "";
532
- const controllerPath = await readConfiguredControllerPath(configPath) ?? null;
533
- const distExists = await pathExists(distDir);
534
- const distEntryExists = distExists ? await pathExists(path.join(distDir, HOSTED_RELEASE_ENTRY_PATH)) : false;
535
- const issues = [];
536
- if (!configPath) {
537
- issues.push(
538
- createIssue(
539
- "missing-config",
540
- "error",
541
- "Hosted releases require src/airjam.config.ts so tooling can inspect the game contract."
542
- )
543
- );
544
- }
545
- if (!packageJson?.value.scripts?.build) {
546
- issues.push(
547
- createIssue(
548
- "missing-build-script",
549
- "error",
550
- 'Hosted releases require a "build" script in package.json.',
551
- packageJson?.path ?? null
552
- )
553
- );
554
- }
555
- if (controllerPath && controllerPath !== HOSTED_RELEASE_CONTROLLER_PATH) {
556
- issues.push(
557
- createIssue(
558
- "invalid-controller-path",
559
- "error",
560
- `Hosted Air Jam bundles require controllerPath to be ${HOSTED_RELEASE_CONTROLLER_PATH}. This project is configured for ${controllerPath}.`,
561
- configPath
562
- )
563
- );
564
- }
565
- if (!/\bgameMetadata\b/.test(configSource)) {
566
- issues.push(
567
- createIssue(
568
- "missing-game-metadata",
569
- "warning",
570
- "No gameMetadata export was detected in airjam.config.ts. Hosted release submission can still bundle locally, but dashboard prefill and catalog metadata will be incomplete.",
571
- configPath
572
- )
573
- );
574
- }
575
- if (distExists && !distEntryExists) {
576
- issues.push(
577
- createIssue(
578
- "invalid-dist-entry",
579
- "warning",
580
- `Current build output is missing ${HOSTED_RELEASE_ENTRY_PATH} at ${distDir}. Run the build before validating or bundling.`,
581
- distDir
582
- )
583
- );
584
- }
585
- return {
586
- projectDir,
587
- packageJsonPath: packageJson?.path ?? null,
588
- packageName: packageJson?.value.name ?? null,
589
- packageVersion: packageJson?.value.version ?? null,
590
- packageManager,
591
- configPath,
592
- buildScript: packageJson?.value.scripts?.build ?? null,
593
- metadataExportLikely: /\bgameMetadata\b/.test(configSource),
594
- controllerPath,
595
- distDir,
596
- distExists,
597
- distEntryExists,
598
- recommendedBundlePath: getDefaultReleaseBundlePath({
599
- projectDir,
600
- packageName: packageJson?.value.name ?? null,
601
- packageVersion: packageJson?.value.version ?? null
602
- }),
603
- canBundle: !issues.some((issue) => issue.severity === "error"),
604
- issues,
605
- hostedContract: {
606
- entryPath: HOSTED_RELEASE_ENTRY_PATH,
607
- manifestPath: HOSTED_RELEASE_MANIFEST_PATH,
608
- hostPath: HOSTED_RELEASE_HOST_PATH,
609
- controllerPath: HOSTED_RELEASE_CONTROLLER_PATH
610
- }
611
- };
612
- };
613
- var validateProjectBuildOutput = async ({
614
- projectDir,
615
- distDir,
616
- packageManager,
617
- skipBuild
618
- }) => {
619
- const doctor = await inspectProjectRelease({
620
- projectDir,
621
- distDir,
622
- packageManager
623
- });
624
- const issues = [...doctor.issues];
625
- let buildResult = null;
626
- if (!skipBuild && doctor.buildScript) {
627
- buildResult = await runBuild({ projectDir, packageManager });
628
- if (!buildResult.ok) {
629
- issues.push(
630
- createIssue(
631
- "build-failed",
632
- "error",
633
- `Build failed for hosted release validation.
634
- ${buildResult.stderr || buildResult.stdout || "Unknown build failure."}`,
635
- doctor.packageJsonPath
636
- )
637
- );
638
- }
639
- }
640
- const distExists = await pathExists(distDir);
641
- const distEntryExists = distExists ? await pathExists(path.join(distDir, HOSTED_RELEASE_ENTRY_PATH)) : false;
642
- if (!distExists) {
643
- issues.push(
644
- createIssue(
645
- "missing-dist",
646
- "error",
647
- `Build output directory not found at ${distDir}. Run the build first or pass --dist-dir.`,
648
- distDir
649
- )
650
- );
651
- }
652
- if (distExists && !distEntryExists) {
653
- issues.push(
654
- createIssue(
655
- "missing-dist-entry",
656
- "error",
657
- `Hosted bundle build output must contain ${HOSTED_RELEASE_ENTRY_PATH} at ${distDir}.`,
658
- distDir
659
- )
660
- );
661
- }
662
- let fileCount = 0;
663
- let extractedSizeBytes = 0;
664
- if (distExists) {
665
- const files = await collectDirectoryFiles(distDir);
666
- fileCount = files.length + 1;
667
- for (const filePath of files) {
668
- const fileStats = await stat(filePath);
669
- extractedSizeBytes += fileStats.size;
670
- }
671
- extractedSizeBytes += Buffer.byteLength(
672
- `${JSON.stringify(createHostedReleaseArtifactManifest(), null, 2)}
673
- `,
674
- "utf8"
675
- );
676
- }
677
- return {
678
- buildResult,
679
- validation: {
680
- source: {
681
- kind: "project",
682
- projectDir,
683
- distDir,
684
- bundlePath: null
685
- },
686
- ok: !issues.some((issue) => issue.severity === "error"),
687
- issues,
688
- manifest: createHostedReleaseArtifactManifest(),
689
- entryPath: distEntryExists ? HOSTED_RELEASE_ENTRY_PATH : null,
690
- wrapperDirectory: null,
691
- fileCount,
692
- extractedSizeBytes
693
- }
694
- };
695
- };
696
- var validateBundleArchive = async (bundlePath) => {
697
- const issues = [];
698
- if (!await pathExists(bundlePath)) {
699
- return {
700
- source: {
701
- kind: "bundle",
702
- projectDir: null,
703
- distDir: null,
704
- bundlePath
705
- },
706
- ok: false,
707
- issues: [
708
- createIssue(
709
- "missing-bundle",
710
- "error",
711
- `Hosted release bundle not found at ${bundlePath}.`,
712
- bundlePath
713
- )
714
- ],
715
- manifest: null,
716
- entryPath: null,
717
- wrapperDirectory: null,
718
- fileCount: 0,
719
- extractedSizeBytes: 0
720
- };
721
- }
722
- const archiveBuffer = await readFile(bundlePath);
723
- const zipFile = await openZipFile(archiveBuffer);
724
- const archivePaths = [];
725
- const manifestCandidates = /* @__PURE__ */ new Map();
726
- let fileCount = 0;
727
- let extractedSizeBytes = 0;
728
- await new Promise((resolve, reject) => {
729
- zipFile.readEntry();
730
- zipFile.on("entry", (entry) => {
731
- try {
732
- if (isZipSymlink(entry)) {
733
- reject(
734
- new Error(
735
- `Release archive cannot contain symbolic links: ${entry.fileName}`
736
- )
737
- );
738
- return;
739
- }
740
- const normalized = normalizeArchiveEntryPath(entry.fileName);
741
- if (isIgnoredArchiveEntry(normalized.archivePath)) {
742
- zipFile.readEntry();
743
- return;
744
- }
745
- if (normalized.isDirectory) {
746
- zipFile.readEntry();
747
- return;
748
- }
749
- archivePaths.push(normalized.archivePath);
750
- fileCount += 1;
751
- extractedSizeBytes += entry.uncompressedSize;
752
- if (normalized.archivePath.endsWith(`/${HOSTED_RELEASE_MANIFEST_PATH}`) || normalized.archivePath === HOSTED_RELEASE_MANIFEST_PATH) {
753
- void openZipEntryReadStream(zipFile, entry).then(readStreamBuffer).then((buffer) => {
754
- manifestCandidates.set(normalized.archivePath, buffer);
755
- zipFile.readEntry();
756
- }).catch(reject);
757
- return;
758
- }
759
- zipFile.readEntry();
760
- } catch (error) {
761
- reject(error);
762
- }
763
- });
764
- zipFile.once("end", resolve);
765
- zipFile.once("error", reject);
766
- }).finally(() => {
767
- zipFile.close();
768
- });
769
- try {
770
- const root = resolveArchiveRoot(
771
- archivePaths.filter((archivePath) => !archivePath.endsWith("/"))
772
- );
773
- const manifestPath = root.wrapperDirectory ? `${root.wrapperDirectory}/${HOSTED_RELEASE_MANIFEST_PATH}` : HOSTED_RELEASE_MANIFEST_PATH;
774
- const manifestBuffer = manifestCandidates.get(manifestPath);
775
- if (!manifestBuffer) {
776
- issues.push(
777
- createIssue(
778
- "missing-manifest",
779
- "error",
780
- `Release archive must include ${HOSTED_RELEASE_MANIFEST_PATH} for Air Jam hosted releases.`,
781
- bundlePath
782
- )
783
- );
784
- }
785
- let manifest = null;
786
- if (manifestBuffer) {
787
- try {
788
- manifest = hostedReleaseArtifactManifestSchema.parse(
789
- JSON.parse(manifestBuffer.toString("utf8"))
790
- );
791
- } catch {
792
- issues.push(
793
- createIssue(
794
- "invalid-manifest",
795
- "error",
796
- `Hosted release manifest must match the Air Jam hosted artifact contract at ${HOSTED_RELEASE_MANIFEST_PATH}.`,
797
- bundlePath
798
- )
799
- );
800
- }
801
- }
802
- return {
803
- source: {
804
- kind: "bundle",
805
- projectDir: null,
806
- distDir: null,
807
- bundlePath
808
- },
809
- ok: !issues.some((issue) => issue.severity === "error"),
810
- issues,
811
- manifest,
812
- entryPath: root.entryPath,
813
- wrapperDirectory: root.wrapperDirectory,
814
- fileCount,
815
- extractedSizeBytes
816
- };
817
- } catch (error) {
818
- issues.push(
819
- createIssue(
820
- "invalid-bundle-layout",
821
- "error",
822
- error instanceof Error ? error.message : "Invalid hosted release archive.",
823
- bundlePath
824
- )
825
- );
826
- return {
827
- source: {
828
- kind: "bundle",
829
- projectDir: null,
830
- distDir: null,
831
- bundlePath
832
- },
833
- ok: false,
834
- issues,
835
- manifest: null,
836
- entryPath: null,
837
- wrapperDirectory: null,
838
- fileCount,
839
- extractedSizeBytes
840
- };
841
- }
842
- };
843
- var writeHostedReleaseBundle = async ({
844
- sourceDir,
845
- outputFile
846
- }) => {
847
- const bundleSourceDir = await materializeBundleSourceTree({ sourceDir });
848
- try {
849
- const files = await collectDirectoryFiles(bundleSourceDir);
850
- const zipFile = new yazl.ZipFile();
851
- await mkdir(path.dirname(outputFile), { recursive: true });
852
- const output = createWriteStream(outputFile);
853
- const closePromise = new Promise((resolve, reject) => {
854
- output.on("close", resolve);
855
- output.on("error", reject);
856
- zipFile.outputStream.on("error", reject);
857
- });
858
- zipFile.outputStream.pipe(output);
859
- for (const filePath of files) {
860
- const relativePath = path.relative(bundleSourceDir, filePath).replace(/\\/g, "/");
861
- if (!relativePath || relativePath === HOSTED_RELEASE_MANIFEST_PATH) {
862
- continue;
863
- }
864
- zipFile.addFile(filePath, relativePath);
865
- }
866
- zipFile.addBuffer(
867
- Buffer.from(
868
- `${JSON.stringify(createHostedReleaseArtifactManifest(), null, 2)}
869
- `,
870
- "utf8"
871
- ),
872
- HOSTED_RELEASE_MANIFEST_PATH
873
- );
874
- zipFile.end();
875
- await closePromise;
876
- } finally {
877
- await rm(path.dirname(bundleSourceDir), { recursive: true, force: true });
878
- }
879
- };
880
- var inspectLocalRelease = async ({
881
- cwd = process.cwd(),
882
- distDir
883
- } = {}) => {
884
- const projectDir = await resolveCanonicalPath(cwd);
885
- const resolvedDistDir = path.resolve(projectDir, distDir || "dist");
886
- const context = await detectProjectContext({ cwd: projectDir });
887
- const packageManager = await resolvePackageManager(projectDir);
888
- if (context.mode === "monorepo" && context.rootDir === projectDir) {
889
- return {
890
- projectDir,
891
- packageJsonPath: context.packageJsonPath,
892
- packageName: context.packageJson?.name ?? null,
893
- packageVersion: context.packageJson?.version ?? null,
894
- packageManager,
895
- configPath: null,
896
- buildScript: null,
897
- metadataExportLikely: false,
898
- controllerPath: null,
899
- distDir: resolvedDistDir,
900
- distExists: await pathExists(resolvedDistDir),
901
- distEntryExists: await pathExists(
902
- path.join(resolvedDistDir, HOSTED_RELEASE_ENTRY_PATH)
903
- ),
904
- recommendedBundlePath: getDefaultReleaseBundlePath({
905
- projectDir,
906
- packageName: context.packageJson?.name ?? null,
907
- packageVersion: context.packageJson?.version ?? null
908
- }),
909
- canBundle: false,
910
- issues: [
911
- createIssue(
912
- "unsupported-monorepo-project",
913
- "error",
914
- "Local hosted release bundling currently supports standalone Air Jam game projects only. Use a generated project directory for doctor/validate/bundle/submit, or use remote release list/inspect/publish tools from the monorepo.",
915
- context.packageJsonPath
916
- )
917
- ],
918
- hostedContract: {
919
- entryPath: HOSTED_RELEASE_ENTRY_PATH,
920
- manifestPath: HOSTED_RELEASE_MANIFEST_PATH,
921
- hostPath: HOSTED_RELEASE_HOST_PATH,
922
- controllerPath: HOSTED_RELEASE_CONTROLLER_PATH
923
- }
924
- };
925
- }
926
- return inspectProjectRelease({
927
- projectDir,
928
- distDir: resolvedDistDir,
929
- packageManager
930
- });
931
- };
932
- var validateLocalRelease = async ({
933
- cwd = process.cwd(),
934
- distDir,
935
- bundlePath,
936
- skipBuild = false
937
- } = {}) => {
938
- const projectDir = await resolveCanonicalPath(cwd);
939
- if (bundlePath) {
940
- return validateBundleArchive(path.resolve(projectDir, bundlePath));
941
- }
942
- const resolvedDistDir = path.resolve(projectDir, distDir || "dist");
943
- const packageManager = await resolvePackageManager(projectDir);
944
- const { validation } = await validateProjectBuildOutput({
945
- projectDir,
946
- distDir: resolvedDistDir,
947
- packageManager,
948
- skipBuild
949
- });
950
- return validation;
951
- };
952
- var bundleLocalRelease = async ({
953
- cwd = process.cwd(),
954
- distDir,
955
- out,
956
- skipBuild = false
957
- } = {}) => {
958
- const projectDir = await resolveCanonicalPath(cwd);
959
- const resolvedDistDir = path.resolve(projectDir, distDir || "dist");
960
- const doctor = await inspectLocalRelease({
961
- cwd: projectDir,
962
- distDir: resolvedDistDir
963
- });
964
- if (!doctor.canBundle) {
965
- const summary = doctor.issues.filter((issue) => issue.severity === "error").map((issue) => `- ${issue.message}`).join("\n");
966
- throw new Error(`Hosted release bundle cannot be created:
967
- ${summary}`);
968
- }
969
- const { buildResult, validation: projectValidation } = await validateProjectBuildOutput({
970
- projectDir,
971
- distDir: resolvedDistDir,
972
- packageManager: doctor.packageManager,
973
- skipBuild
974
- });
975
- if (!projectValidation.ok) {
976
- const summary = projectValidation.issues.filter((issue) => issue.severity === "error").map((issue) => `- ${issue.message}`).join("\n");
977
- throw new Error(`Hosted release bundle validation failed:
978
- ${summary}`);
979
- }
980
- const outputFile = out ? path.resolve(projectDir, out) : doctor.recommendedBundlePath;
981
- await writeHostedReleaseBundle({
982
- sourceDir: resolvedDistDir,
983
- outputFile
984
- });
985
- const bundleValidation = await validateBundleArchive(outputFile);
986
- if (!bundleValidation.ok) {
987
- const summary = bundleValidation.issues.filter((issue) => issue.severity === "error").map((issue) => `- ${issue.message}`).join("\n");
988
- throw new Error(`Hosted release bundle validation failed:
989
- ${summary}`);
990
- }
991
- return {
992
- projectDir,
993
- distDir: resolvedDistDir,
994
- outputFile,
995
- built: !skipBuild,
996
- buildResult,
997
- validation: bundleValidation
998
- };
999
- };
1000
- var uploadReleaseBundle = async ({
1001
- bundlePath,
1002
- upload
1003
- }) => {
1004
- const archive = await readFile(bundlePath);
1005
- const response = await fetch(upload.url, {
1006
- method: upload.method,
1007
- headers: upload.headers,
1008
- body: archive
1009
- });
1010
- if (!response.ok) {
1011
- throw new Error(
1012
- `Release generation upload failed with status ${response.status}.`
1013
- );
1014
- }
1015
- };
1016
- var listPlatformReleaseTargets = async ({
1017
- platformUrl,
1018
- token
1019
- } = {}) => {
1020
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1021
- return requestPlatformMachineApi({
1022
- baseUrl: resolved.baseUrl,
1023
- pathname: "/api/cli/games",
1024
- token: resolved.token,
1025
- schema: platformMachineListOwnedGamesResultSchema
1026
- });
1027
- };
1028
- var listPlatformReleases = async ({
1029
- platformUrl,
1030
- token,
1031
- slugOrId
1032
- }) => {
1033
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1034
- return requestPlatformMachineApi({
1035
- baseUrl: resolved.baseUrl,
1036
- pathname: `/api/cli/games/${encodeURIComponent(slugOrId)}/releases`,
1037
- token: resolved.token,
1038
- schema: platformMachineListReleasesResultSchema
1039
- });
1040
- };
1041
- var inspectPlatformRelease = async ({
1042
- platformUrl,
1043
- token,
1044
- releaseId
1045
- }) => {
1046
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1047
- return requestPlatformMachineApi({
1048
- baseUrl: resolved.baseUrl,
1049
- pathname: `/api/cli/releases/${encodeURIComponent(releaseId)}`,
1050
- token: resolved.token,
1051
- schema: platformMachineGetReleaseResultSchema
1052
- });
1053
- };
1054
- var publishPlatformRelease = async ({
1055
- platformUrl,
1056
- token,
1057
- releaseId
1058
- }) => {
1059
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1060
- return requestPlatformMachineApi({
1061
- baseUrl: resolved.baseUrl,
1062
- pathname: `/api/cli/releases/${encodeURIComponent(releaseId)}/publish`,
1063
- method: "POST",
1064
- token: resolved.token,
1065
- schema: platformMachinePublishReleaseResultSchema
1066
- });
1067
- };
1068
- var uploadPlatformReleaseGeneration = async ({
1069
- platformUrl,
1070
- token,
1071
- releaseId,
1072
- cwd = process.cwd(),
1073
- bundlePath
1074
- }) => {
1075
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1076
- const effectiveBundlePath = path.resolve(cwd, bundlePath);
1077
- const archive = await stat(effectiveBundlePath);
1078
- if (!archive.isFile()) {
1079
- throw new Error(`Release bundle is not a file: ${effectiveBundlePath}`);
1080
- }
1081
- const uploadTarget = await requestPlatformMachineApi({
1082
- baseUrl: resolved.baseUrl,
1083
- pathname: `/api/cli/releases/${encodeURIComponent(releaseId)}/upload-target`,
1084
- method: "POST",
1085
- token: resolved.token,
1086
- body: {
1087
- originalFilename: path.basename(effectiveBundlePath),
1088
- sizeBytes: archive.size
1089
- },
1090
- schema: platformMachineRequestReleaseUploadTargetResultSchema
1091
- });
1092
- await uploadReleaseBundle({
1093
- bundlePath: effectiveBundlePath,
1094
- upload: uploadTarget.upload
1095
- });
1096
- return { ...uploadTarget, bundlePath: effectiveBundlePath };
1097
- };
1098
- var finalizePlatformReleaseGeneration = async ({
1099
- platformUrl,
1100
- token,
1101
- releaseId,
1102
- generationId
1103
- }) => {
1104
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1105
- return requestPlatformMachineApi({
1106
- baseUrl: resolved.baseUrl,
1107
- pathname: `/api/cli/releases/${encodeURIComponent(releaseId)}/generations/${encodeURIComponent(generationId)}/finalize`,
1108
- method: "POST",
1109
- token: resolved.token,
1110
- schema: platformMachineFinalizeReleaseUploadResultSchema
1111
- });
1112
- };
1113
- var exportPlatformReleaseGeneration = async ({
1114
- platformUrl,
1115
- token,
1116
- releaseId,
1117
- generationId,
1118
- cwd = process.cwd(),
1119
- out
1120
- }) => {
1121
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1122
- const target = await requestPlatformMachineApi({
1123
- baseUrl: resolved.baseUrl,
1124
- pathname: `/api/cli/releases/${encodeURIComponent(releaseId)}/generations/${encodeURIComponent(generationId)}/export`,
1125
- method: "POST",
1126
- token: resolved.token,
1127
- schema: platformMachineRequestReleaseGenerationExportResultSchema
1128
- });
1129
- const expectedSize = target.generation.observedSizeBytes ?? target.generation.declaredSizeBytes;
1130
- const outputFile = path.resolve(cwd, out ?? target.download.filename);
1131
- await mkdir(path.dirname(outputFile), { recursive: true });
1132
- const destination = await open(outputFile, "wx");
1133
- let sizeBytes = 0;
1134
- let completed = false;
1135
- try {
1136
- const response = await fetch(target.download.url, {
1137
- method: target.download.method
1138
- });
1139
- if (!response.ok) {
1140
- throw new Error(
1141
- `Release generation export failed with status ${response.status}.`
1142
- );
1143
- }
1144
- if (!response.body) {
1145
- throw new Error("Release generation export returned no response body.");
1146
- }
1147
- const reader = response.body.getReader();
1148
- let streamFinished = false;
1149
- try {
1150
- while (true) {
1151
- const chunk = await reader.read();
1152
- if (chunk.done) {
1153
- streamFinished = true;
1154
- break;
1155
- }
1156
- const bytes = Buffer.from(chunk.value);
1157
- sizeBytes += bytes.length;
1158
- if (sizeBytes > expectedSize) {
1159
- throw new Error(
1160
- `Release generation export size mismatch: expected ${expectedSize} bytes, received more than ${expectedSize} bytes.`
1161
- );
1162
- }
1163
- let offset = 0;
1164
- while (offset < bytes.length) {
1165
- const { bytesWritten } = await destination.write(
1166
- bytes,
1167
- offset,
1168
- bytes.length - offset
1169
- );
1170
- if (bytesWritten === 0) {
1171
- throw new Error(
1172
- "Release generation export could not make progress writing the archive."
1173
- );
1174
- }
1175
- offset += bytesWritten;
1176
- }
1177
- }
1178
- } finally {
1179
- if (!streamFinished) {
1180
- await reader.cancel().catch(() => void 0);
1181
- }
1182
- reader.releaseLock();
1183
- }
1184
- if (sizeBytes !== expectedSize) {
1185
- throw new Error(
1186
- `Release generation export size mismatch: expected ${expectedSize} bytes, received ${sizeBytes}.`
1187
- );
1188
- }
1189
- await destination.sync();
1190
- completed = true;
1191
- } finally {
1192
- await destination.close();
1193
- if (!completed) {
1194
- await rm(outputFile, { force: true });
1195
- }
1196
- }
1197
- return {
1198
- ...target,
1199
- outputFile,
1200
- sizeBytes
1201
- };
1202
- };
1203
- var waitForPlatformReleaseGeneration = async ({
1204
- platformUrl,
1205
- token,
1206
- releaseId,
1207
- generationId,
1208
- timeoutMs = DEFAULT_RELEASE_PROCESSING_TIMEOUT_MS,
1209
- pollIntervalMs = RELEASE_PROCESSING_POLL_INTERVAL_MS
1210
- }) => {
1211
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) {
1212
- throw new Error("Release processing timeout must be a positive integer.");
1213
- }
1214
- if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 1) {
1215
- throw new Error(
1216
- "Release processing poll interval must be a positive integer."
1217
- );
1218
- }
1219
- const deadline = Date.now() + timeoutMs;
1220
- while (true) {
1221
- const inspected = await inspectPlatformRelease({
1222
- platformUrl,
1223
- token,
1224
- releaseId
1225
- });
1226
- const generation = inspected.release.generations.find(
1227
- (candidate) => candidate.id === generationId
1228
- );
1229
- if (!generation) {
1230
- throw new Error(
1231
- `Release ${releaseId} no longer contains generation ${generationId}.`
1232
- );
1233
- }
1234
- if (generation.status === "ready" && (inspected.release.status === "ready" || inspected.release.status === "live") && inspected.release.promotedGenerationId === generationId) {
1235
- return inspected.release;
1236
- }
1237
- if (generation.status === "failed" || generation.status === "abandoned" || inspected.release.status === "failed" || inspected.release.status === "quarantined" || inspected.release.status === "archived") {
1238
- const failedJob = inspected.release.jobs.find(
1239
- (job) => job.generationId === generationId && (job.status === "failed" || job.status === "canceled")
1240
- );
1241
- const errorSuffix = failedJob?.lastErrorCode ? ` (${failedJob.lastErrorCode})` : "";
1242
- throw new Error(
1243
- `Release generation ${generationId} ended with release ${inspected.release.status} and generation ${generation.status}${errorSuffix}. Inspect release ${releaseId} for its checks and job history.`
1244
- );
1245
- }
1246
- if (Date.now() >= deadline) {
1247
- throw new Error(
1248
- `Timed out waiting for release generation ${generationId}. Processing remains durable; inspect release ${releaseId} to continue.`
1249
- );
1250
- }
1251
- await wait(Math.min(pollIntervalMs, Math.max(1, deadline - Date.now())));
1252
- }
1253
- };
1254
- var submitPlatformRelease = async ({
1255
- platformUrl,
1256
- token,
1257
- slugOrId,
1258
- versionLabel,
1259
- cwd = process.cwd(),
1260
- distDir,
1261
- bundlePath,
1262
- skipBuild = false,
1263
- waitForProcessing = false,
1264
- processingTimeoutMs = DEFAULT_RELEASE_PROCESSING_TIMEOUT_MS,
1265
- processingPollIntervalMs = RELEASE_PROCESSING_POLL_INTERVAL_MS,
1266
- publish = false
1267
- }) => {
1268
- const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1269
- const effectiveBundlePath = bundlePath ? path.resolve(cwd, bundlePath) : (await bundleLocalRelease({
1270
- cwd,
1271
- distDir,
1272
- skipBuild
1273
- })).outputFile;
1274
- const createdDraft = await requestPlatformMachineApi({
1275
- baseUrl: resolved.baseUrl,
1276
- pathname: "/api/cli/releases",
1277
- method: "POST",
1278
- token: resolved.token,
1279
- body: {
1280
- slugOrId,
1281
- ...versionLabel?.trim() ? { versionLabel: versionLabel.trim() } : {}
1282
- },
1283
- schema: platformMachineCreateReleaseDraftResultSchema
1284
- });
1285
- const uploadTarget = await uploadPlatformReleaseGeneration({
1286
- platformUrl: resolved.baseUrl,
1287
- token: resolved.token,
1288
- releaseId: createdDraft.release.id,
1289
- bundlePath: effectiveBundlePath
1290
- });
1291
- const submitted = await finalizePlatformReleaseGeneration({
1292
- platformUrl: resolved.baseUrl,
1293
- token: resolved.token,
1294
- releaseId: createdDraft.release.id,
1295
- generationId: uploadTarget.generation.id
1296
- });
1297
- const shouldWaitForProcessing = waitForProcessing || publish;
1298
- const processedRelease = shouldWaitForProcessing ? await waitForPlatformReleaseGeneration({
1299
- platformUrl: resolved.baseUrl,
1300
- token: resolved.token,
1301
- releaseId: createdDraft.release.id,
1302
- generationId: uploadTarget.generation.id,
1303
- timeoutMs: processingTimeoutMs,
1304
- pollIntervalMs: processingPollIntervalMs
1305
- }) : null;
1306
- let publishedRelease = null;
1307
- if (publish) {
1308
- if (processedRelease?.status !== "ready") {
1309
- throw new Error(
1310
- `Release ${createdDraft.release.id} is ${processedRelease?.status ?? submitted.release.status} and cannot be published.`
1311
- );
1312
- }
1313
- const published = await requestPlatformMachineApi({
1314
- baseUrl: resolved.baseUrl,
1315
- pathname: `/api/cli/releases/${encodeURIComponent(createdDraft.release.id)}/publish`,
1316
- method: "POST",
1317
- token: resolved.token,
1318
- schema: platformMachinePublishReleaseResultSchema
1319
- });
1320
- publishedRelease = published.release;
1321
- }
1322
- return {
1323
- bundlePath: effectiveBundlePath,
1324
- createdRelease: createdDraft.release,
1325
- createdGeneration: uploadTarget.generation,
1326
- submittedRelease: submitted.release,
1327
- submittedGeneration: submitted.generation,
1328
- processingJob: submitted.job,
1329
- processedRelease,
1330
- publishedRelease
1331
- };
1332
- };
2
+ archivePlatformRelease,
3
+ bundleLocalRelease,
4
+ exportPlatformReleaseGeneration,
5
+ finalizePlatformReleaseGeneration,
6
+ inspectLocalRelease,
7
+ inspectPlatformRelease,
8
+ listPlatformReleaseTargets,
9
+ listPlatformReleases,
10
+ publishPlatformRelease,
11
+ submitPlatformRelease,
12
+ uploadPlatformReleaseGeneration,
13
+ validateLocalRelease,
14
+ waitForPlatformReleaseGeneration
15
+ } from "./chunk-EU7A6PXW.js";
16
+ import "./chunk-2O67AXCU.js";
17
+ import "./chunk-ART5TEYT.js";
18
+ import "./chunk-PKD4WVX5.js";
1333
19
  export {
20
+ archivePlatformRelease,
1334
21
  bundleLocalRelease,
1335
22
  exportPlatformReleaseGeneration,
1336
23
  finalizePlatformReleaseGeneration,