@air-jam/devtools 0.0.0-stage → 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 (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/dist/chunk-2O67AXCU.js +470 -0
  4. package/dist/chunk-2O67AXCU.js.map +1 -0
  5. package/dist/chunk-AO3ZDXF6.js +142 -0
  6. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  7. package/dist/chunk-ART5TEYT.js +472 -0
  8. package/dist/chunk-ART5TEYT.js.map +1 -0
  9. package/dist/chunk-ASC2CK2R.js +77 -0
  10. package/dist/chunk-ASC2CK2R.js.map +1 -0
  11. package/dist/chunk-E3UZZGAV.js +50 -0
  12. package/dist/chunk-E3UZZGAV.js.map +1 -0
  13. package/dist/chunk-EJTE7UKX.js +64 -0
  14. package/dist/chunk-EJTE7UKX.js.map +1 -0
  15. package/dist/chunk-ESFKNN75.js +110 -0
  16. package/dist/chunk-ESFKNN75.js.map +1 -0
  17. package/dist/chunk-EU7A6PXW.js +1339 -0
  18. package/dist/chunk-EU7A6PXW.js.map +1 -0
  19. package/dist/chunk-FN7E6EA7.js +549 -0
  20. package/dist/chunk-FN7E6EA7.js.map +1 -0
  21. package/dist/chunk-GDFAWHGA.js +190 -0
  22. package/dist/chunk-GDFAWHGA.js.map +1 -0
  23. package/dist/chunk-HZUGBH4Y.js +347 -0
  24. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  25. package/dist/chunk-ITKAOEGX.js +93 -0
  26. package/dist/chunk-ITKAOEGX.js.map +1 -0
  27. package/dist/chunk-JBCUTWRI.js +897 -0
  28. package/dist/chunk-JBCUTWRI.js.map +1 -0
  29. package/dist/chunk-JSI5S4WP.js +1174 -0
  30. package/dist/chunk-JSI5S4WP.js.map +1 -0
  31. package/dist/chunk-L4D675BG.js +97 -0
  32. package/dist/chunk-L4D675BG.js.map +1 -0
  33. package/dist/chunk-M6CJ7GQC.js +133 -0
  34. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  35. package/dist/chunk-MEIMOSZC.js +749 -0
  36. package/dist/chunk-MEIMOSZC.js.map +1 -0
  37. package/dist/chunk-O3XG3FNL.js +1014 -0
  38. package/dist/chunk-O3XG3FNL.js.map +1 -0
  39. package/dist/chunk-OM6SCJ7H.js +18 -0
  40. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  41. package/dist/chunk-PKD4WVX5.js +63 -0
  42. package/dist/chunk-PKD4WVX5.js.map +1 -0
  43. package/dist/chunk-PMBLXGFM.js +3384 -0
  44. package/dist/chunk-PMBLXGFM.js.map +1 -0
  45. package/dist/chunk-PMNE5GIN.js +279 -0
  46. package/dist/chunk-PMNE5GIN.js.map +1 -0
  47. package/dist/chunk-QAWI64VR.js +148 -0
  48. package/dist/chunk-QAWI64VR.js.map +1 -0
  49. package/dist/chunk-QGADSPHZ.js +449 -0
  50. package/dist/chunk-QGADSPHZ.js.map +1 -0
  51. package/dist/chunk-SPYN66UV.js +338 -0
  52. package/dist/chunk-SPYN66UV.js.map +1 -0
  53. package/dist/context.d.ts +19 -0
  54. package/dist/context.js +10 -0
  55. package/dist/context.js.map +1 -0
  56. package/dist/controller.d.ts +67 -0
  57. package/dist/controller.js +40 -0
  58. package/dist/controller.js.map +1 -0
  59. package/dist/dependencies.d.ts +44 -0
  60. package/dist/dependencies.js +10 -0
  61. package/dist/dependencies.js.map +1 -0
  62. package/dist/dev.d.ts +21 -0
  63. package/dist/dev.js +19 -0
  64. package/dist/dev.js.map +1 -0
  65. package/dist/game-builds.d.ts +200 -0
  66. package/dist/game-builds.js +16 -0
  67. package/dist/game-builds.js.map +1 -0
  68. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  69. package/dist/game-runs.d.ts +1452 -0
  70. package/dist/game-runs.js +76 -0
  71. package/dist/game-runs.js.map +1 -0
  72. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  73. package/dist/game-session-broker.d.ts +4 -0
  74. package/dist/game-session-broker.js +40 -0
  75. package/dist/game-session-broker.js.map +1 -0
  76. package/dist/game-session.d.ts +3934 -0
  77. package/dist/game-session.js +195 -0
  78. package/dist/game-session.js.map +1 -0
  79. package/dist/game-settings.d.ts +16 -0
  80. package/dist/game-settings.js +237 -0
  81. package/dist/game-settings.js.map +1 -0
  82. package/dist/games.d.ts +28 -0
  83. package/dist/games.js +16 -0
  84. package/dist/games.js.map +1 -0
  85. package/dist/harness/visual.d.ts +204 -0
  86. package/dist/harness/visual.js +46 -0
  87. package/dist/harness/visual.js.map +1 -0
  88. package/dist/logs.d.ts +15 -0
  89. package/dist/logs.js +57 -0
  90. package/dist/logs.js.map +1 -0
  91. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  92. package/dist/mcp-config.d.ts +63 -0
  93. package/dist/mcp-config.js +191 -0
  94. package/dist/mcp-config.js.map +1 -0
  95. package/dist/platform-auth.d.ts +9 -0
  96. package/dist/platform-auth.js +45 -0
  97. package/dist/platform-auth.js.map +1 -0
  98. package/dist/platform-game-analytics.d.ts +51 -0
  99. package/dist/platform-game-analytics.js +49 -0
  100. package/dist/platform-game-analytics.js.map +1 -0
  101. package/dist/platform-game-app-id.d.ts +46 -0
  102. package/dist/platform-game-app-id.js +93 -0
  103. package/dist/platform-game-app-id.js.map +1 -0
  104. package/dist/platform-game-media.d.ts +347 -0
  105. package/dist/platform-game-media.js +168 -0
  106. package/dist/platform-game-media.js.map +1 -0
  107. package/dist/platform-games.d.ts +87 -0
  108. package/dist/platform-games.js +183 -0
  109. package/dist/platform-games.js.map +1 -0
  110. package/dist/quality.d.ts +16 -0
  111. package/dist/quality.js +62 -0
  112. package/dist/quality.js.map +1 -0
  113. package/dist/release.d.ts +1304 -0
  114. package/dist/release.js +34 -0
  115. package/dist/release.js.map +1 -0
  116. package/dist/rooms-check.d.ts +90 -0
  117. package/dist/rooms-check.js +717 -0
  118. package/dist/rooms-check.js.map +1 -0
  119. package/dist/source-tree-contract.d.ts +16 -0
  120. package/dist/source-tree-contract.js +13 -0
  121. package/dist/source-tree-contract.js.map +1 -0
  122. package/dist/testing.d.ts +464 -0
  123. package/dist/testing.js +27 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/tooling/describe-game.d.ts +2 -0
  126. package/dist/tooling/describe-game.js +54 -0
  127. package/dist/tooling/describe-game.js.map +1 -0
  128. package/dist/tooling/game-session-broker.d.ts +2 -0
  129. package/dist/tooling/game-session-broker.js +28 -0
  130. package/dist/tooling/game-session-broker.js.map +1 -0
  131. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  132. package/dist/tooling/hold-runtime-host.js +931 -0
  133. package/dist/tooling/hold-runtime-host.js.map +1 -0
  134. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  135. package/dist/tooling/list-visual-scenarios.js +25 -0
  136. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  137. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  138. package/dist/tooling/managed-dev-supervisor.js +51 -0
  139. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  140. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  141. package/dist/tooling/process-scope-guard.d.ts +2 -0
  142. package/dist/tooling/process-scope-guard.js +388 -0
  143. package/dist/tooling/process-scope-guard.js.map +1 -0
  144. package/dist/tooling/process-scope-windows.ps1 +148 -0
  145. package/dist/tooling/rooms-check-device.d.ts +2 -0
  146. package/dist/tooling/rooms-check-device.js +498 -0
  147. package/dist/tooling/rooms-check-device.js.map +1 -0
  148. package/dist/tooling/run-headless-room.d.ts +2 -0
  149. package/dist/tooling/run-headless-room.js +287 -0
  150. package/dist/tooling/run-headless-room.js.map +1 -0
  151. package/dist/tooling/run-test-profile.d.ts +2 -0
  152. package/dist/tooling/run-test-profile.js +181 -0
  153. package/dist/tooling/run-test-profile.js.map +1 -0
  154. package/dist/tooling/run-visual-capture.d.ts +2 -0
  155. package/dist/tooling/run-visual-capture.js +203 -0
  156. package/dist/tooling/run-visual-capture.js.map +1 -0
  157. package/dist/tooling/seal-game-build.d.ts +2 -0
  158. package/dist/tooling/seal-game-build.js +120 -0
  159. package/dist/tooling/seal-game-build.js.map +1 -0
  160. package/dist/types-CdYrgrG_.d.ts +1036 -0
  161. package/dist/types-DyRD-ym1.d.ts +141 -0
  162. package/dist/visual.d.ts +21 -0
  163. package/dist/visual.js +219 -0
  164. package/dist/visual.js.map +1 -0
  165. package/package.json +150 -3
  166. package/src/bounded-response.ts +28 -0
  167. package/src/built-game-runtime.ts +152 -0
  168. package/src/commands.ts +40 -0
  169. package/src/context.ts +218 -0
  170. package/src/controller-protocol.ts +22 -0
  171. package/src/controller.ts +1526 -0
  172. package/src/current-room-host.ts +166 -0
  173. package/src/decision-provider.ts +102 -0
  174. package/src/dependencies.ts +176 -0
  175. package/src/dependency-install-contract.ts +12 -0
  176. package/src/dev.ts +995 -0
  177. package/src/fs-utils.ts +93 -0
  178. package/src/game-action-observation.ts +106 -0
  179. package/src/game-build-protocol.ts +72 -0
  180. package/src/game-build.ts +483 -0
  181. package/src/game-run-owner.ts +2358 -0
  182. package/src/game-run-protocol.ts +448 -0
  183. package/src/game-run-record.ts +92 -0
  184. package/src/game-run-replay.ts +95 -0
  185. package/src/game-run-watch.ts +155 -0
  186. package/src/game-session-broker.ts +793 -0
  187. package/src/game-session-operations.ts +61 -0
  188. package/src/game-session-protocol.ts +180 -0
  189. package/src/game-session-runtime.ts +861 -0
  190. package/src/game-session.ts +206 -0
  191. package/src/game-settings.ts +295 -0
  192. package/src/games.ts +262 -0
  193. package/src/harness/visual/browser.ts +100 -0
  194. package/src/harness/visual/controller-observation.ts +181 -0
  195. package/src/harness/visual/prefab-contract.ts +29 -0
  196. package/src/harness/visual/prefab-runner.ts +178 -0
  197. package/src/harness/visual/runner.ts +549 -0
  198. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  199. package/src/harness/visual/scenario-contract.ts +8 -0
  200. package/src/harness/visual/scenario-helpers.ts +67 -0
  201. package/src/harness/visual/screencast.ts +155 -0
  202. package/src/harness/visual/session.ts +400 -0
  203. package/src/harness/visual/types.ts +184 -0
  204. package/src/harness/visual.ts +7 -0
  205. package/src/headless-room-protocol.ts +112 -0
  206. package/src/headless-room.ts +222 -0
  207. package/src/helper-channel.ts +229 -0
  208. package/src/helper-scripts.ts +69 -0
  209. package/src/installed-dependencies.ts +74 -0
  210. package/src/logs.ts +67 -0
  211. package/src/managed-process-scope.ts +481 -0
  212. package/src/mcp-config.ts +262 -0
  213. package/src/node-process-environment.ts +10 -0
  214. package/src/platform-auth.ts +594 -0
  215. package/src/platform-game-analytics.ts +50 -0
  216. package/src/platform-game-app-id.ts +99 -0
  217. package/src/platform-game-media.ts +209 -0
  218. package/src/platform-games.ts +217 -0
  219. package/src/policy-artifact-contract.ts +52 -0
  220. package/src/policy-artifacts.ts +134 -0
  221. package/src/process-scope-admission.ts +50 -0
  222. package/src/process-scope-protocol.ts +66 -0
  223. package/src/process-scope.ts +327 -0
  224. package/src/quality.ts +82 -0
  225. package/src/release.ts +1683 -0
  226. package/src/rooms-check-fleet.ts +194 -0
  227. package/src/rooms-check-link.ts +138 -0
  228. package/src/rooms-check-protocol.ts +244 -0
  229. package/src/rooms-check.ts +797 -0
  230. package/src/runtime-owner-protocol.ts +218 -0
  231. package/src/source-tree-contract.ts +70 -0
  232. package/src/source-tree.ts +84 -0
  233. package/src/test-profile-process.ts +153 -0
  234. package/src/test-profile-protocol.ts +116 -0
  235. package/src/testing.ts +430 -0
  236. package/src/tooling/declaration-hook.ts +52 -0
  237. package/src/tooling/describe-game.ts +49 -0
  238. package/src/tooling/game-session-broker.ts +7 -0
  239. package/src/tooling/hold-runtime-host.ts +441 -0
  240. package/src/tooling/list-visual-scenarios.ts +21 -0
  241. package/src/tooling/load-game.ts +79 -0
  242. package/src/tooling/managed-dev-supervisor.ts +71 -0
  243. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  244. package/src/tooling/process-scope-guard.ts +213 -0
  245. package/src/tooling/process-scope-windows.ps1 +148 -0
  246. package/src/tooling/rooms-check-device.ts +493 -0
  247. package/src/tooling/run-headless-room.ts +326 -0
  248. package/src/tooling/run-test-profile.ts +190 -0
  249. package/src/tooling/run-visual-capture.ts +231 -0
  250. package/src/tooling/runtime-owner-actions.ts +65 -0
  251. package/src/tooling/seal-game-build.ts +118 -0
  252. package/src/tooling/visual-pack.ts +11 -0
  253. package/src/types.ts +928 -0
  254. package/src/visual.ts +296 -0
  255. package/src/windows-process-scopes.ts +189 -0
  256. package/src/workspace-contract.ts +32 -0
@@ -0,0 +1,151 @@
1
+ import type { RuntimeInspectionContract } from "@air-jam/sdk/runtime-inspection";
2
+ import type { Browser } from "playwright-core";
3
+ import type { z } from "zod";
4
+ import {
5
+ AIR_JAM_RUNTIME_OWNER_CAPTURE_FRAME,
6
+ type runtimeOwnerCapturePortSchema,
7
+ type runtimeOwnerObservedControllerSchema,
8
+ } from "../../runtime-owner-protocol.js";
9
+ import { openControllerObservation } from "./controller-observation.js";
10
+
11
+ type ControllerObservation = Awaited<
12
+ ReturnType<typeof openControllerObservation>
13
+ >;
14
+ type Entry = {
15
+ opening?: Promise<ControllerObservation>;
16
+ observation?: ControllerObservation;
17
+ queued: number;
18
+ abort: AbortController;
19
+ pending: z.infer<typeof runtimeOwnerCapturePortSchema>[];
20
+ delivery: Promise<void>;
21
+ error?: unknown;
22
+ closing?: Promise<void>;
23
+ onError: (error: Error) => void;
24
+ };
25
+
26
+ /** How many room messages may wait for the page before the observation fails. */
27
+ const PENDING_DELIVERIES = 256;
28
+
29
+ // Both one-shot captures and live watching mirror existing players through this owner.
30
+ export class RuntimeControllerObservations {
31
+ private entries = new Map<string, Entry>();
32
+ constructor(
33
+ private readonly options: {
34
+ browser: Browser;
35
+ readInspection: () => Promise<RuntimeInspectionContract | null>;
36
+ send: (message: unknown) => void;
37
+ },
38
+ ) {}
39
+ async open(
40
+ requestId: string,
41
+ context: z.infer<typeof runtimeOwnerObservedControllerSchema>,
42
+ onError: Entry["onError"],
43
+ ) {
44
+ if (this.entries.has(requestId))
45
+ throw new Error("Controller observation already exists.");
46
+ const entry: Entry = {
47
+ queued: 0,
48
+ abort: new AbortController(),
49
+ pending: [],
50
+ delivery: Promise.resolve(),
51
+ onError,
52
+ };
53
+ this.entries.set(requestId, entry);
54
+ entry.opening = (async () => {
55
+ const inspection = await this.options.readInspection();
56
+ if (inspection?.role !== "host" || inspection.roomId !== context.roomId)
57
+ throw new Error("Observation belongs to another host room.");
58
+ const observation = await openControllerObservation({
59
+ browser: this.options.browser,
60
+ signal: entry.abort.signal,
61
+ controllerJoinUrl: inspection.joinUrl,
62
+ harnessSessionId: context.harnessSessionId,
63
+ roomId: context.roomId,
64
+ onPortMessage: (message) =>
65
+ this.options.send({
66
+ type: AIR_JAM_RUNTIME_OWNER_CAPTURE_FRAME,
67
+ requestId,
68
+ message,
69
+ }),
70
+ });
71
+ entry.observation = observation;
72
+ for (const event of entry.pending.splice(0)) this.deliver(event);
73
+ await observation.ready;
74
+ await entry.delivery;
75
+ if (entry.error) throw entry.error;
76
+ return observation;
77
+ })();
78
+ try {
79
+ return await entry.opening;
80
+ } catch (error) {
81
+ try {
82
+ await this.close(requestId);
83
+ } catch (cleanupError) {
84
+ throw new AggregateError(
85
+ [error, cleanupError],
86
+ "Controller observation failed and cleanup was not confirmed.",
87
+ );
88
+ }
89
+ throw error;
90
+ }
91
+ }
92
+ private fail(entry: Entry, error: unknown) {
93
+ if (entry.error) return;
94
+ entry.error = error;
95
+ entry.onError(error instanceof Error ? error : new Error(String(error)));
96
+ }
97
+ deliver(event: z.infer<typeof runtimeOwnerCapturePortSchema>) {
98
+ const entry = this.entries.get(event.requestId);
99
+ if (!entry || entry.error || entry.closing) return;
100
+ if (entry.pending.length + entry.queued >= PENDING_DELIVERIES) {
101
+ this.fail(
102
+ entry,
103
+ new Error("Controller observation event allowance exceeded."),
104
+ );
105
+ return;
106
+ }
107
+ if (!entry.observation) {
108
+ entry.pending.push(event);
109
+ return;
110
+ }
111
+ const observation = entry.observation;
112
+ entry.queued++;
113
+ entry.delivery = entry.delivery
114
+ .then(() => {
115
+ if (!entry.closing && !entry.error)
116
+ return observation.deliver(event.message);
117
+ })
118
+ .catch((error: unknown) => {
119
+ if (!entry.closing) this.fail(entry, error);
120
+ })
121
+ .finally(() => {
122
+ entry.queued--;
123
+ });
124
+ }
125
+ async close(requestId: string) {
126
+ const entry = this.entries.get(requestId);
127
+ if (!entry) return;
128
+ entry.abort.abort();
129
+ return (entry.closing ??= (async () => {
130
+ try {
131
+ await entry.opening?.catch(() => undefined);
132
+ await entry.observation?.close();
133
+ await entry.delivery;
134
+ } finally {
135
+ this.entries.delete(requestId);
136
+ }
137
+ })());
138
+ }
139
+
140
+ async closeAll() {
141
+ const results = await Promise.allSettled(
142
+ [...this.entries.keys()].map((id) => this.close(id)),
143
+ );
144
+ const failed = results.filter((result) => result.status === "rejected");
145
+ if (failed.length)
146
+ throw new AggregateError(
147
+ failed.map((result) => result.reason),
148
+ "Controller observation cleanup failed.",
149
+ );
150
+ }
151
+ }
@@ -0,0 +1,8 @@
1
+ import type { AnyAirJamAgentContract } from "@air-jam/sdk/core";
2
+ import type { VisualScenario, VisualScenarioPack } from "./types.js";
3
+
4
+ export const defineVisualScenarios = <
5
+ TAgent extends AnyAirJamAgentContract,
6
+ >(pack: {
7
+ scenarios: ReadonlyArray<VisualScenario<TAgent>>;
8
+ }): VisualScenarioPack<TAgent> => pack;
@@ -0,0 +1,67 @@
1
+ import { fixedControllerOrientation } from "@air-jam/sdk/metadata";
2
+ import type { VisualScenarioContext, VisualViewport } from "./types.js";
3
+
4
+ export const STANDARD_HOST_VIEWPORTS = [
5
+ ["mac-desktop", { width: 3016, height: 1504 }],
6
+ ["desktop", { width: 1440, height: 1024 }],
7
+ ["tablet", { width: 1024, height: 1180 }],
8
+ ] as const satisfies readonly [string, VisualViewport][];
9
+
10
+ export const STANDARD_CONTROLLER_VIEWPORTS = [
11
+ ["mobile", { width: 390, height: 844 }],
12
+ ["small-mobile", { width: 360, height: 640 }],
13
+ ] as const satisfies readonly [string, VisualViewport][];
14
+
15
+ export const STANDARD_CONTROLLER_LANDSCAPE_VIEWPORTS = [
16
+ ["mobile", { width: 844, height: 390 }],
17
+ ["small-mobile", { width: 640, height: 360 }],
18
+ ] as const satisfies readonly [string, VisualViewport][];
19
+
20
+ export const captureStandardSurfaces = async (
21
+ context: VisualScenarioContext,
22
+ options?: {
23
+ controllerOrientation?: "portrait" | "landscape";
24
+ },
25
+ ): Promise<void> => {
26
+ for (const [viewportName, viewport] of STANDARD_HOST_VIEWPORTS) {
27
+ await context.captureHost(viewportName, viewport);
28
+ }
29
+
30
+ await context.ensureControllerInteractive();
31
+ const controllerOrientation =
32
+ fixedControllerOrientation(context.inputModalities ?? []) ??
33
+ options?.controllerOrientation ??
34
+ "portrait";
35
+ const controllerViewports =
36
+ controllerOrientation === "landscape"
37
+ ? STANDARD_CONTROLLER_LANDSCAPE_VIEWPORTS
38
+ : STANDARD_CONTROLLER_VIEWPORTS;
39
+ context.note(
40
+ `Captured controller surfaces in ${controllerOrientation} orientation.`,
41
+ );
42
+ for (const [viewportName, viewport] of controllerViewports) {
43
+ await context.captureController(viewportName, viewport);
44
+ }
45
+ };
46
+
47
+ export const waitForHostText = async (
48
+ context: VisualScenarioContext,
49
+ text: string | RegExp,
50
+ timeout = 30_000,
51
+ ): Promise<void> => {
52
+ await context.host.game
53
+ .getByText(text)
54
+ .first()
55
+ .waitFor({ state: "visible", timeout });
56
+ };
57
+
58
+ export const waitForControllerText = async (
59
+ context: VisualScenarioContext,
60
+ text: string | RegExp,
61
+ timeout = 30_000,
62
+ ): Promise<void> => {
63
+ await context.controller.game
64
+ .getByText(text)
65
+ .first()
66
+ .waitFor({ state: "visible", timeout });
67
+ };
@@ -0,0 +1,155 @@
1
+ import type { Page } from "playwright-core";
2
+ import {
3
+ GAME_WATCH_HEARTBEAT_MS,
4
+ MAXIMUM_GAME_WATCH_FRAME_BASE64,
5
+ type GameRunWatchEvent,
6
+ } from "../../game-run-watch.js";
7
+
8
+ export function jpegDimensions(data: string) {
9
+ const bytes = Buffer.from(data, "base64");
10
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8)
11
+ throw new Error("Run watch received a non-JPEG frame.");
12
+ let offset = 2;
13
+ while (offset + 4 <= bytes.length) {
14
+ if (bytes[offset] !== 0xff) throw new Error("Invalid JPEG marker.");
15
+ const marker = bytes[offset + 1];
16
+ const length = bytes.readUInt16BE(offset + 2);
17
+ if (length < 2 || offset + 2 + length > bytes.length) break;
18
+ if ([0xc0, 0xc1, 0xc2].includes(marker)) {
19
+ if (length < 8) break;
20
+ return {
21
+ width: bytes.readUInt16BE(offset + 7),
22
+ height: bytes.readUInt16BE(offset + 5),
23
+ };
24
+ }
25
+ offset += length + 2;
26
+ }
27
+ throw new Error("Run watch JPEG dimensions are unavailable.");
28
+ }
29
+
30
+ export async function startGameScreencast({
31
+ page,
32
+ send,
33
+ onError,
34
+ onReady,
35
+ }: {
36
+ page: Page;
37
+ send: (event: GameRunWatchEvent, sent: (error: Error | null) => void) => void;
38
+ onError: (error: Error) => void;
39
+ onReady: (dimensions: { width: number; height: number }) => void;
40
+ }) {
41
+ const viewport = page.viewportSize();
42
+ if (!viewport)
43
+ throw new Error("Run watch requires an explicit capture viewport.");
44
+ const scale = Math.min(1, 1280 / Math.max(viewport.width, viewport.height));
45
+ const connection = await page.context().newCDPSession(page);
46
+ let closed = false;
47
+ let sending = false;
48
+ let pending: GameRunWatchEvent | undefined;
49
+ let heartbeat: GameRunWatchEvent | undefined;
50
+ let sequence = 0;
51
+ let lastFrameSeq: number | null = null;
52
+ const acknowledgements: number[] = [];
53
+ let acknowledgementTimer: ReturnType<typeof setTimeout> | undefined;
54
+ let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
55
+ let nextAcknowledgementAt = 0;
56
+ const acknowledge = () => {
57
+ if (closed || acknowledgementTimer || !acknowledgements.length) return;
58
+ acknowledgementTimer = setTimeout(
59
+ () => {
60
+ acknowledgementTimer = undefined;
61
+ if (closed) return;
62
+ const sessionId = acknowledgements.shift();
63
+ if (sessionId === undefined) return;
64
+ nextAcknowledgementAt = performance.now() + 1000 / 15;
65
+ void connection
66
+ .send("Page.screencastFrameAck", { sessionId })
67
+ .then(acknowledge, (error: Error) => {
68
+ if (!closed) onError(error);
69
+ });
70
+ },
71
+ Math.max(0, nextAcknowledgementAt - performance.now()),
72
+ );
73
+ };
74
+ const flush = () => {
75
+ if (closed || sending) return;
76
+ const event = heartbeat ?? pending;
77
+ if (!event) return;
78
+ if (event.type === "frame") pending = undefined;
79
+ else heartbeat = undefined;
80
+ sending = true;
81
+ send(event, (error) => {
82
+ sending = false;
83
+ if (closed) return;
84
+ if (error) {
85
+ onError(error);
86
+ return;
87
+ }
88
+ flush();
89
+ });
90
+ };
91
+ const pageClosed = () => {
92
+ if (!closed) onError(new Error("Watched game surface closed."));
93
+ };
94
+ page.once("close", pageClosed);
95
+ connection.on("Page.screencastFrame", (frame) => {
96
+ if (closed) return;
97
+ if (acknowledgements.length >= 4) {
98
+ onError(new Error("Run watch capture flow control exceeded."));
99
+ return;
100
+ }
101
+ acknowledgements.push(frame.sessionId);
102
+ acknowledge();
103
+ try {
104
+ if (frame.data.length > MAXIMUM_GAME_WATCH_FRAME_BASE64)
105
+ throw new Error("Run watch frame exceeds its transfer allowance.");
106
+ if (frame.metadata.timestamp === undefined)
107
+ throw new Error("Run watch frame is missing its capture timestamp.");
108
+ if (sequence === 0) {
109
+ onReady(jpegDimensions(frame.data));
110
+ heartbeatTimer = setInterval(() => {
111
+ heartbeat = { type: "heartbeat", at: Date.now(), lastFrameSeq };
112
+ flush();
113
+ }, GAME_WATCH_HEARTBEAT_MS);
114
+ }
115
+ lastFrameSeq = sequence++;
116
+ pending = {
117
+ type: "frame",
118
+ seq: lastFrameSeq,
119
+ capturedAt: frame.metadata.timestamp * 1000,
120
+ data: frame.data,
121
+ };
122
+ flush();
123
+ } catch (error) {
124
+ onError(error instanceof Error ? error : new Error(String(error)));
125
+ }
126
+ });
127
+ const close = async () => {
128
+ if (closed) return;
129
+ closed = true;
130
+ clearInterval(heartbeatTimer);
131
+ clearTimeout(acknowledgementTimer);
132
+ acknowledgements.length = 0;
133
+ pending = undefined;
134
+ heartbeat = undefined;
135
+ page.off("close", pageClosed);
136
+ try {
137
+ await connection.detach();
138
+ } catch (error) {
139
+ if (!page.isClosed()) throw error;
140
+ }
141
+ };
142
+ try {
143
+ await connection.send("Page.startScreencast", {
144
+ format: "jpeg",
145
+ quality: 75,
146
+ maxWidth: Math.floor(viewport.width * scale),
147
+ maxHeight: Math.floor(viewport.height * scale),
148
+ everyNthFrame: 1,
149
+ });
150
+ return { close };
151
+ } catch (error) {
152
+ await close();
153
+ throw error;
154
+ }
155
+ }