@open-qa/qa 0.0.0-stage → 0.1.0-alpha.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 (313) hide show
  1. package/LICENSE +204 -0
  2. package/NOTICE +7 -0
  3. package/THIRD_PARTY.md +12 -0
  4. package/THIRD_PARTY_NOTICES.md +11 -0
  5. package/drizzle/0000_qa_core.sql +158 -0
  6. package/drizzle/0001_run_health.sql +3 -0
  7. package/drizzle/0002_bounded_cleanup.sql +5 -0
  8. package/drizzle/0003_step_replay_cache.sql +9 -0
  9. package/drizzle/0004_credential_expiry.sql +1 -0
  10. package/drizzle/0005_server_api.sql +19 -0
  11. package/drizzle/0006_submission_created.sql +3 -0
  12. package/drizzle/0007_findings.sql +19 -0
  13. package/drizzle/0008_classification_labels.sql +14 -0
  14. package/drizzle/0009_job_queue.sql +20 -0
  15. package/drizzle/0010_result_notifications.sql +13 -0
  16. package/drizzle/0011_result_notification_retries.sql +5 -0
  17. package/drizzle/0012_result_notification_flows.sql +44 -0
  18. package/drizzle/0013_flow_quarantine.sql +35 -0
  19. package/drizzle/0014_run_budgets.sql +2 -0
  20. package/drizzle/0015_flow_lifecycle.sql +9 -0
  21. package/drizzle/0016_open_qa_classification.sql +28 -0
  22. package/drizzle/meta/0000_snapshot.json +1002 -0
  23. package/drizzle/meta/0001_snapshot.json +1021 -0
  24. package/drizzle/meta/0002_snapshot.json +1027 -0
  25. package/drizzle/meta/0003_snapshot.json +1081 -0
  26. package/drizzle/meta/0004_snapshot.json +1087 -0
  27. package/drizzle/meta/0005_snapshot.json +1210 -0
  28. package/drizzle/meta/0006_snapshot.json +1244 -0
  29. package/drizzle/meta/0007_snapshot.json +1353 -0
  30. package/drizzle/meta/0008_snapshot.json +1435 -0
  31. package/drizzle/meta/0009_snapshot.json +1587 -0
  32. package/drizzle/meta/0010_snapshot.json +1675 -0
  33. package/drizzle/meta/0011_snapshot.json +1692 -0
  34. package/drizzle/meta/0012_snapshot.json +1818 -0
  35. package/drizzle/meta/0013_snapshot.json +2016 -0
  36. package/drizzle/meta/0014_snapshot.json +2028 -0
  37. package/drizzle/meta/0015_snapshot.json +2064 -0
  38. package/drizzle/meta/0016_snapshot.json +2076 -0
  39. package/drizzle/meta/_journal.json +125 -0
  40. package/package.json +118 -4
  41. package/problem-matcher.json +32 -0
  42. package/src/adapters/db-lease-pool.d.ts +25 -0
  43. package/src/adapters/db-lease-pool.js +293 -0
  44. package/src/adapters/dir-artifact-store.d.ts +9 -0
  45. package/src/adapters/dir-artifact-store.js +64 -0
  46. package/src/adapters/e2b-agent.d.ts +7 -0
  47. package/src/adapters/e2b-agent.js +94 -0
  48. package/src/adapters/e2b-artifacts.d.ts +3 -0
  49. package/src/adapters/e2b-artifacts.js +66 -0
  50. package/src/adapters/e2b-bounded.d.ts +1 -0
  51. package/src/adapters/e2b-bounded.js +19 -0
  52. package/src/adapters/e2b-client.d.ts +33 -0
  53. package/src/adapters/e2b-client.js +114 -0
  54. package/src/adapters/e2b-executor.d.ts +26 -0
  55. package/src/adapters/e2b-executor.js +194 -0
  56. package/src/adapters/e2b-lifetime.d.ts +20 -0
  57. package/src/adapters/e2b-lifetime.js +73 -0
  58. package/src/adapters/e2b-prune.d.ts +13 -0
  59. package/src/adapters/e2b-prune.js +42 -0
  60. package/src/adapters/file-replay-cache.d.ts +14 -0
  61. package/src/adapters/file-replay-cache.js +120 -0
  62. package/src/adapters/file-run-store.d.ts +175 -0
  63. package/src/adapters/file-run-store.js +280 -0
  64. package/src/adapters/fixed-lease-pool.d.ts +10 -0
  65. package/src/adapters/fixed-lease-pool.js +237 -0
  66. package/src/adapters/gcs/artifact-store.d.ts +49 -0
  67. package/src/adapters/gcs/artifact-store.js +247 -0
  68. package/src/adapters/gcs/client.d.ts +22 -0
  69. package/src/adapters/gcs/client.js +106 -0
  70. package/src/adapters/gcs/download.d.ts +9 -0
  71. package/src/adapters/gcs/download.js +43 -0
  72. package/src/adapters/gcs/index.d.ts +8 -0
  73. package/src/adapters/gcs/index.js +23 -0
  74. package/src/adapters/gcs/periodic-flush.d.ts +5 -0
  75. package/src/adapters/gcs/periodic-flush.js +16 -0
  76. package/src/adapters/gcs/pg-catalog.d.ts +16 -0
  77. package/src/adapters/gcs/pg-catalog.js +149 -0
  78. package/src/adapters/gcs/replay-completeness.d.ts +1 -0
  79. package/src/adapters/gcs/replay-completeness.js +65 -0
  80. package/src/adapters/gcs/scan-upload.d.ts +10 -0
  81. package/src/adapters/gcs/scan-upload.js +26 -0
  82. package/src/adapters/index.d.ts +5 -0
  83. package/src/adapters/index.js +12 -0
  84. package/src/adapters/lease-transaction.d.ts +2 -0
  85. package/src/adapters/lease-transaction.js +61 -0
  86. package/src/adapters/local-credential-resolver.d.ts +5 -0
  87. package/src/adapters/local-credential-resolver.js +15 -0
  88. package/src/adapters/local-env.d.ts +1 -0
  89. package/src/adapters/local-env.js +37 -0
  90. package/src/adapters/local-files.d.ts +17 -0
  91. package/src/adapters/local-files.js +150 -0
  92. package/src/adapters/pg-classification-store.d.ts +58 -0
  93. package/src/adapters/pg-classification-store.js +112 -0
  94. package/src/adapters/pg-replay-cache.d.ts +16 -0
  95. package/src/adapters/pg-replay-cache.js +111 -0
  96. package/src/adapters/pg-run-store.d.ts +58 -0
  97. package/src/adapters/pg-run-store.js +399 -0
  98. package/src/adapters/resource-pools.d.ts +2 -0
  99. package/src/adapters/resource-pools.js +28 -0
  100. package/src/adapters/secret-manager-credential-resolver.d.ts +44 -0
  101. package/src/adapters/secret-manager-credential-resolver.js +102 -0
  102. package/src/artifact-scan.d.ts +21 -0
  103. package/src/artifact-scan.js +139 -0
  104. package/src/budget-confirmation.d.ts +23 -0
  105. package/src/budget-confirmation.js +43 -0
  106. package/src/cache-command.d.ts +7 -0
  107. package/src/cache-command.js +107 -0
  108. package/src/classification-command.d.ts +14 -0
  109. package/src/classification-command.js +72 -0
  110. package/src/classification-diff.d.ts +10 -0
  111. package/src/classification-diff.js +47 -0
  112. package/src/classification-model.d.ts +17 -0
  113. package/src/classification-model.js +51 -0
  114. package/src/classification-notifier.d.ts +21 -0
  115. package/src/classification-notifier.js +34 -0
  116. package/src/classify-runs.d.ts +31 -0
  117. package/src/classify-runs.js +138 -0
  118. package/src/cli-program.d.ts +9 -0
  119. package/src/cli-program.js +172 -0
  120. package/src/cli.d.ts +2 -0
  121. package/src/cli.js +12 -0
  122. package/src/commands.d.ts +7 -0
  123. package/src/commands.js +17 -0
  124. package/src/credential-references.d.ts +24 -0
  125. package/src/credential-references.js +33 -0
  126. package/src/db/commands.d.ts +1 -0
  127. package/src/db/commands.js +34 -0
  128. package/src/db/credentials.d.ts +16 -0
  129. package/src/db/credentials.js +73 -0
  130. package/src/db/database.d.ts +12 -0
  131. package/src/db/database.js +135 -0
  132. package/src/db/event-chunks.d.ts +405 -0
  133. package/src/db/event-chunks.js +74 -0
  134. package/src/db/fencing.d.ts +8 -0
  135. package/src/db/fencing.js +16 -0
  136. package/src/db/flow-status.d.ts +41 -0
  137. package/src/db/flow-status.js +208 -0
  138. package/src/db/index.d.ts +12 -0
  139. package/src/db/index.js +24 -0
  140. package/src/db/queries.d.ts +73 -0
  141. package/src/db/queries.js +122 -0
  142. package/src/db/resources.d.ts +14 -0
  143. package/src/db/resources.js +61 -0
  144. package/src/db/schema.d.ts +3532 -0
  145. package/src/db/schema.js +501 -0
  146. package/src/demo-command.d.ts +1 -0
  147. package/src/demo-command.js +50 -0
  148. package/src/doctor-command.d.ts +15 -0
  149. package/src/doctor-command.js +275 -0
  150. package/src/doctor-summary.d.ts +2 -0
  151. package/src/doctor-summary.js +31 -0
  152. package/src/draft-api.d.ts +460 -0
  153. package/src/draft-api.js +333 -0
  154. package/src/draft-command.d.ts +10 -0
  155. package/src/draft-command.js +73 -0
  156. package/src/draft-hooks.d.ts +3 -0
  157. package/src/draft-hooks.js +33 -0
  158. package/src/draft-pages.d.ts +11 -0
  159. package/src/draft-pages.js +82 -0
  160. package/src/engine.d.ts +105 -0
  161. package/src/engine.js +323 -0
  162. package/src/execution-snapshot.d.ts +21 -0
  163. package/src/execution-snapshot.js +141 -0
  164. package/src/flow-check.d.ts +9 -0
  165. package/src/flow-check.js +68 -0
  166. package/src/flow-lifecycle.d.ts +6 -0
  167. package/src/flow-lifecycle.js +61 -0
  168. package/src/flow-lint.d.ts +8 -0
  169. package/src/flow-lint.js +73 -0
  170. package/src/flow-loader.d.ts +219 -0
  171. package/src/flow-loader.js +236 -0
  172. package/src/flow-source.d.ts +2 -0
  173. package/src/flow-source.js +6 -0
  174. package/src/flows-api.d.ts +1 -0
  175. package/src/flows-api.js +12 -0
  176. package/src/heal-notification.d.ts +16 -0
  177. package/src/heal-notification.js +62 -0
  178. package/src/hooks/api.d.ts +29 -0
  179. package/src/hooks/api.js +15 -0
  180. package/src/hooks/consumer.d.ts +18 -0
  181. package/src/hooks/consumer.js +98 -0
  182. package/src/hooks/loader.d.ts +6 -0
  183. package/src/hooks/loader.js +28 -0
  184. package/src/hooks/registry.d.ts +22 -0
  185. package/src/hooks/registry.js +23 -0
  186. package/src/hooks/runner.d.ts +19 -0
  187. package/src/hooks/runner.js +279 -0
  188. package/src/hooks/session-cache.d.ts +16 -0
  189. package/src/hooks/session-cache.js +42 -0
  190. package/src/hooks/session-store.d.ts +20 -0
  191. package/src/hooks/session-store.js +95 -0
  192. package/src/hooks/worker.d.ts +1 -0
  193. package/src/hooks/worker.js +84 -0
  194. package/src/http-stage-client.d.ts +367 -0
  195. package/src/http-stage-client.js +190 -0
  196. package/src/independent-model.d.ts +22 -0
  197. package/src/independent-model.js +215 -0
  198. package/src/lifecycle-command.d.ts +15 -0
  199. package/src/lifecycle-command.js +190 -0
  200. package/src/local-command.d.ts +3 -0
  201. package/src/local-command.js +27 -0
  202. package/src/local-host-executor.d.ts +38 -0
  203. package/src/local-host-executor.js +196 -0
  204. package/src/open-command.d.ts +7 -0
  205. package/src/open-command.js +39 -0
  206. package/src/operations-api.d.ts +2 -0
  207. package/src/operations-api.js +6 -0
  208. package/src/personas.d.ts +2 -0
  209. package/src/personas.js +61 -0
  210. package/src/program-runner.d.ts +3 -0
  211. package/src/program-runner.js +263 -0
  212. package/src/program-sandbox.py +75 -0
  213. package/src/program-scratch.d.ts +2 -0
  214. package/src/program-scratch.js +48 -0
  215. package/src/program-worker.mjs +101 -0
  216. package/src/public-id.d.ts +2 -0
  217. package/src/public-id.js +5 -0
  218. package/src/public-report-url.d.ts +1 -0
  219. package/src/public-report-url.js +18 -0
  220. package/src/publication-check.d.ts +1 -0
  221. package/src/publication-check.js +31 -0
  222. package/src/quarantine-command.d.ts +9 -0
  223. package/src/quarantine-command.js +69 -0
  224. package/src/remote-command.d.ts +30 -0
  225. package/src/remote-command.js +156 -0
  226. package/src/replay-image.d.ts +1 -0
  227. package/src/replay-image.js +35 -0
  228. package/src/report/assets.d.ts +1 -0
  229. package/src/report/assets.js +5 -0
  230. package/src/report/browser.css +414 -0
  231. package/src/report/browser.d.ts +1 -0
  232. package/src/report/browser.js +219 -0
  233. package/src/report/data.d.ts +1 -0
  234. package/src/report/data.js +4 -0
  235. package/src/report/generate.d.ts +1 -0
  236. package/src/report/generate.js +54 -0
  237. package/src/report/load.d.ts +870 -0
  238. package/src/report/load.js +139 -0
  239. package/src/report/resource-table.d.ts +2 -0
  240. package/src/report/resource-table.js +4 -0
  241. package/src/report/status-icon.d.ts +2 -0
  242. package/src/report/status-icon.js +20 -0
  243. package/src/report/style.css +413 -0
  244. package/src/result-notifier.d.ts +121 -0
  245. package/src/result-notifier.js +230 -0
  246. package/src/result-transports.d.ts +12 -0
  247. package/src/result-transports.js +150 -0
  248. package/src/run-command.d.ts +32 -0
  249. package/src/run-command.js +493 -0
  250. package/src/run-setup-error.d.ts +11 -0
  251. package/src/run-setup-error.js +18 -0
  252. package/src/sandboxes-command.d.ts +9 -0
  253. package/src/sandboxes-command.js +29 -0
  254. package/src/screen-proxy.d.ts +5 -0
  255. package/src/screen-proxy.js +79 -0
  256. package/src/screen-url.d.ts +18 -0
  257. package/src/screen-url.js +54 -0
  258. package/src/server/app.d.ts +29 -0
  259. package/src/server/app.js +350 -0
  260. package/src/server/auth.d.ts +33 -0
  261. package/src/server/auth.js +113 -0
  262. package/src/server/credentials.d.ts +30 -0
  263. package/src/server/credentials.js +77 -0
  264. package/src/server/errors.d.ts +9 -0
  265. package/src/server/errors.js +26 -0
  266. package/src/server/index.d.ts +35 -0
  267. package/src/server/index.js +96 -0
  268. package/src/server/maintenance.d.ts +13 -0
  269. package/src/server/maintenance.js +54 -0
  270. package/src/server/repository.d.ts +534 -0
  271. package/src/server/repository.js +219 -0
  272. package/src/setup-command.d.ts +10 -0
  273. package/src/setup-command.js +52 -0
  274. package/src/stage-environment.d.ts +1 -0
  275. package/src/stage-environment.js +35 -0
  276. package/src/stage-supervisor.mjs +95 -0
  277. package/src/studio-command.d.ts +7 -0
  278. package/src/studio-command.js +47 -0
  279. package/src/studio-control.d.ts +5 -0
  280. package/src/studio-control.js +207 -0
  281. package/src/studio-review.d.ts +24 -0
  282. package/src/studio-review.js +64 -0
  283. package/src/studio-worker.d.ts +1 -0
  284. package/src/studio-worker.js +48 -0
  285. package/src/system-config.d.ts +7 -0
  286. package/src/system-config.js +70 -0
  287. package/src/terminal-reporter.d.ts +13 -0
  288. package/src/terminal-reporter.js +93 -0
  289. package/src/vendor/gmail.d.ts +45 -0
  290. package/src/vendor/gmail.js +193 -0
  291. package/src/watch-command.d.ts +16 -0
  292. package/src/watch-command.js +93 -0
  293. package/src/watch-state.d.ts +4 -0
  294. package/src/watch-state.js +53 -0
  295. package/src/worker/execution-error.d.ts +5 -0
  296. package/src/worker/execution-error.js +10 -0
  297. package/src/worker/execution.d.ts +24 -0
  298. package/src/worker/execution.js +190 -0
  299. package/src/worker/index.d.ts +8 -0
  300. package/src/worker/index.js +40 -0
  301. package/src/worker/prune.d.ts +3 -0
  302. package/src/worker/prune.js +22 -0
  303. package/src/worker/quarantine-notifications.d.ts +8 -0
  304. package/src/worker/quarantine-notifications.js +89 -0
  305. package/src/worker/queue.d.ts +65 -0
  306. package/src/worker/queue.js +438 -0
  307. package/src/worker/result-notifications.d.ts +28 -0
  308. package/src/worker/result-notifications.js +347 -0
  309. package/src/worker/store.d.ts +4 -0
  310. package/src/worker/store.js +46 -0
  311. package/src/worker/worker.d.ts +21 -0
  312. package/src/worker/worker.js +140 -0
  313. package/README.md +0 -3
@@ -0,0 +1,18 @@
1
+ import { HookRegistry, type HookRegistryOptions } from "./registry.js";
2
+ export declare class ConsumerRegistryError extends Error {
3
+ }
4
+ export declare function consumerManifest(root: string): Promise<{
5
+ file: string;
6
+ module: string;
7
+ exportName: string;
8
+ publicEnv: string[];
9
+ hooks: string[];
10
+ } | undefined>;
11
+ export declare function readConsumerManifest(root: string): {
12
+ file: string;
13
+ module: string;
14
+ exportName: string;
15
+ publicEnv: string[];
16
+ hooks: string[];
17
+ } | undefined;
18
+ export declare function loadConsumerRegistry(root: string, options?: HookRegistryOptions): Promise<HookRegistry>;
@@ -0,0 +1,98 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { stat } from "node:fs/promises";
3
+ import { isAbsolute, join, relative } from "node:path";
4
+ import { tsImport } from "tsx/esm/api";
5
+ import { pathToFileURL } from "node:url";
6
+ import { z } from "zod";
7
+ import { HookRegistry } from "./registry.js";
8
+ class ConsumerRegistryError extends Error {
9
+ }
10
+ const schema = z.strictObject({
11
+ module: z.string().regex(/^\.\/[\w./-]+\.ts$/),
12
+ exportName: z.string().regex(/^[a-zA-Z_$][\w$]*$/),
13
+ publicEnv: z.array(z.string().regex(/^[A-Z_][A-Z0-9_]*$/)).default([]),
14
+ hooks: z.array(z.string().regex(/^[a-zA-Z][\w-]*\.[a-zA-Z_$][\w$-]*$/))
15
+ });
16
+ async function consumerManifest(root) {
17
+ return readConsumerManifest(root);
18
+ }
19
+ function readConsumerManifest(root) {
20
+ let content;
21
+ let directory;
22
+ try {
23
+ const canonicalRoot = realpathSync(root);
24
+ directory = realpathSync(join(root, "hooks"));
25
+ const manifestFile = realpathSync(join(directory, "registry.json"));
26
+ assertInside(canonicalRoot, directory);
27
+ assertInside(directory, manifestFile);
28
+ content = readFileSync(manifestFile, "utf8");
29
+ } catch (error) {
30
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
31
+ if (error instanceof ConsumerRegistryError) throw error;
32
+ throw new ConsumerRegistryError("Cannot read consumer hook registry");
33
+ }
34
+ let value;
35
+ try {
36
+ value = JSON.parse(content);
37
+ } catch {
38
+ throw new ConsumerRegistryError("Invalid consumer hook registry");
39
+ }
40
+ const parsed = schema.safeParse(value);
41
+ if (!parsed.success) throw new ConsumerRegistryError("Invalid consumer hook registry");
42
+ const manifest = parsed.data;
43
+ const names = /* @__PURE__ */ new Set();
44
+ for (const name of manifest.hooks) {
45
+ if (names.has(name)) throw new ConsumerRegistryError(`Duplicate hook name: ${name}`);
46
+ names.add(name);
47
+ }
48
+ let file;
49
+ try {
50
+ file = realpathSync(join(directory, manifest.module));
51
+ } catch {
52
+ throw new ConsumerRegistryError("Cannot read consumer registry module");
53
+ }
54
+ assertInside(directory, file);
55
+ return { ...manifest, file };
56
+ }
57
+ async function loadConsumerRegistry(root, options = {}) {
58
+ const manifest = await consumerManifest(root);
59
+ if (!manifest) return new HookRegistry();
60
+ let registry;
61
+ try {
62
+ const tsconfig = join(root, "tsconfig.json");
63
+ const hasConfig = await stat(tsconfig).then(
64
+ () => true,
65
+ () => false
66
+ );
67
+ const module = await tsImport(pathToFileURL(manifest.file).href, {
68
+ parentURL: import.meta.url,
69
+ tsconfig: hasConfig ? tsconfig : false
70
+ });
71
+ const factory = module[manifest.exportName];
72
+ if (typeof factory !== "function") throw new ConsumerRegistryError();
73
+ registry = factory(options);
74
+ if (!registry || typeof registry.get !== "function" || typeof registry.names !== "function" || !registry.services)
75
+ throw new ConsumerRegistryError();
76
+ } catch (error) {
77
+ if (process.env.OPEN_QA_DEBUG === "1")
78
+ console.error("Consumer hook registry initialization failed:", error);
79
+ const duplicate = error instanceof Error && /^Duplicate hook name: ([a-zA-Z][\w-]*\.[a-zA-Z_$][\w$-]*)$/.exec(error.message);
80
+ if (duplicate && manifest.hooks.includes(duplicate[1]))
81
+ throw new ConsumerRegistryError(`Duplicate hook name: ${duplicate[1]}`);
82
+ throw new ConsumerRegistryError("Cannot initialize consumer hook registry");
83
+ }
84
+ if (registry.names().length !== manifest.hooks.length || manifest.hooks.some((name) => !registry.get(name)))
85
+ throw new ConsumerRegistryError("Consumer hook registry does not match its manifest");
86
+ return registry;
87
+ }
88
+ function assertInside(parent, child) {
89
+ const path = relative(parent, child);
90
+ if (path === ".." || path.startsWith("../") || isAbsolute(path))
91
+ throw new ConsumerRegistryError("Consumer registry must be inside the hooks directory");
92
+ }
93
+ export {
94
+ ConsumerRegistryError,
95
+ consumerManifest,
96
+ loadConsumerRegistry,
97
+ readConsumerManifest
98
+ };
@@ -0,0 +1,6 @@
1
+ export declare class HookResolutionError extends Error {
2
+ }
3
+ export declare function resolveHook(root: string, name: string): Promise<{
4
+ file: string;
5
+ exportName: string;
6
+ }>;
@@ -0,0 +1,28 @@
1
+ import { realpath } from "node:fs/promises";
2
+ import { isAbsolute, join, relative } from "node:path";
3
+ class HookResolutionError extends Error {
4
+ }
5
+ function inside(root, path) {
6
+ const rel = relative(root, path);
7
+ return rel !== ".." && !rel.startsWith("../") && !isAbsolute(rel);
8
+ }
9
+ async function resolveHook(root, name) {
10
+ const match = /^([a-zA-Z][a-zA-Z0-9_-]*)\.([a-zA-Z_$][\w$]*)$/.exec(name);
11
+ if (!match) throw new HookResolutionError(`Invalid hook name: ${name}`);
12
+ const canonicalRoot = await realpath(root);
13
+ let directory;
14
+ let file;
15
+ try {
16
+ directory = await realpath(join(canonicalRoot, "hooks"));
17
+ file = await realpath(join(directory, `${match[1]}.ts`));
18
+ } catch {
19
+ throw new HookResolutionError(`Unknown hook: ${name}`);
20
+ }
21
+ if (!inside(canonicalRoot, directory) || !inside(directory, file))
22
+ throw new HookResolutionError(`Hook file is outside the hooks directory: ${name}`);
23
+ return { file, exportName: match[2] };
24
+ }
25
+ export {
26
+ HookResolutionError,
27
+ resolveHook
28
+ };
@@ -0,0 +1,22 @@
1
+ import type { HookCall, HookContext, HookResult } from "@open-qa/qa-engine";
2
+ import type { JsonObject } from "@open-qa/qa-engine/protocol";
3
+ export type HostHook = (call: HookCall, context: HookContext, signal?: AbortSignal) => Promise<HookResult | void>;
4
+ export interface HookServices {
5
+ signIn?: (context: HookContext, actor: string, account: string, signal?: AbortSignal) => Promise<Record<string, JsonObject>>;
6
+ lease?: (context: HookContext, actor: string) => JsonObject;
7
+ setup?: (env: NodeJS.ProcessEnv) => Record<string, string>;
8
+ doctor?: (target?: string) => string[];
9
+ publicError?: (error: unknown) => string | undefined;
10
+ }
11
+ export interface HookRegistryOptions {
12
+ env?: NodeJS.ProcessEnv;
13
+ }
14
+ export type HookRegistryFactory = (options: HookRegistryOptions) => HookRegistry;
15
+ export declare class HookRegistry {
16
+ readonly services: HookServices;
17
+ private readonly hooks;
18
+ constructor(services?: HookServices);
19
+ register(name: string, hook: HostHook): this;
20
+ get(name: string): HostHook | undefined;
21
+ names(): string[];
22
+ }
@@ -0,0 +1,23 @@
1
+ class HookRegistry {
2
+ constructor(services = {}) {
3
+ this.services = services;
4
+ }
5
+ services;
6
+ hooks = /* @__PURE__ */ new Map();
7
+ register(name, hook) {
8
+ if (!/^[a-zA-Z][\w-]*\.[a-zA-Z_$][\w$-]*$/.test(name))
9
+ throw new Error(`Invalid hook name: ${name}`);
10
+ if (this.hooks.has(name)) throw new Error(`Duplicate hook name: ${name}`);
11
+ this.hooks.set(name, hook);
12
+ return this;
13
+ }
14
+ get(name) {
15
+ return this.hooks.get(name);
16
+ }
17
+ names() {
18
+ return [...this.hooks.keys()];
19
+ }
20
+ }
21
+ export {
22
+ HookRegistry
23
+ };
@@ -0,0 +1,19 @@
1
+ import type { HookCall, HookContext, HookRunner, HookResult } from "@open-qa/qa-engine";
2
+ import { HookRegistry } from "./registry.js";
3
+ export interface FileHookRunnerOptions {
4
+ root: string;
5
+ registry?: HookRegistry;
6
+ env?: NodeJS.ProcessEnv;
7
+ hostEnv?: NodeJS.ProcessEnv;
8
+ abortGraceMs?: number;
9
+ timeoutMs?: number;
10
+ }
11
+ export declare class FileHookRunner implements HookRunner {
12
+ private readonly options;
13
+ private registry;
14
+ constructor(options: FileHookRunnerOptions);
15
+ private consumer;
16
+ run(call: HookCall, context: HookContext, signal?: AbortSignal): Promise<HookResult>;
17
+ private signIn;
18
+ private execute;
19
+ }
@@ -0,0 +1,279 @@
1
+ import { fork } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { leaseVariables } from "@open-qa/qa-engine";
4
+ import { controlSchemas, jsonObjectSchema } from "@open-qa/qa-engine/protocol";
5
+ import { ConsumerRegistryError, loadConsumerRegistry } from "./consumer.js";
6
+ import { HookResolutionError, resolveHook } from "./loader.js";
7
+ import { SessionCacheError } from "./session-store.js";
8
+ class FileHookRunner {
9
+ constructor(options) {
10
+ this.options = options;
11
+ }
12
+ options;
13
+ registry;
14
+ consumer() {
15
+ return this.registry ??= this.options.registry ? Promise.resolve(this.options.registry) : loadConsumerRegistry(this.options.root, { env: this.options.hostEnv });
16
+ }
17
+ async run(call, context, signal) {
18
+ signal?.throwIfAborted();
19
+ const external = signal;
20
+ const deadline = new AbortController();
21
+ const timer = setTimeout(
22
+ () => deadline.abort(),
23
+ this.options.timeoutMs ?? (context.phase === "teardown" ? 6e4 : 18e4)
24
+ );
25
+ signal = AbortSignal.any([deadline.signal, ...signal ? [signal] : []]);
26
+ let registry;
27
+ try {
28
+ registry = await raceAbort(this.consumer(), signal);
29
+ signal.throwIfAborted();
30
+ const registered = registry.get(call.hook);
31
+ if (registered) {
32
+ const result2 = await raceAbort(registered(call, context, signal), signal);
33
+ signal.throwIfAborted();
34
+ return result2 ?? {};
35
+ }
36
+ const hook = await resolveHook(this.options.root, call.hook);
37
+ signal?.throwIfAborted();
38
+ const result = await this.execute(hook, call, context, registry, signal);
39
+ signal?.throwIfAborted();
40
+ return result;
41
+ } catch (error) {
42
+ external?.throwIfAborted();
43
+ if (error instanceof HookResolutionError || error instanceof ConsumerRegistryError)
44
+ throw error;
45
+ const reason = registry?.services.publicError?.(error) ?? (error instanceof SessionCacheError ? error.message : void 0);
46
+ if (reason)
47
+ throw new Error(
48
+ `Hook ${deadline.signal.aborted ? "timed out" : "failed"}: ${call.hook}: ${reason}`
49
+ );
50
+ if (deadline.signal.aborted) throw new Error(`Hook timed out: ${call.hook}`);
51
+ throw new Error(`Hook failed: ${call.hook}`);
52
+ } finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+ async signIn(registry, context, actor, account, signal) {
57
+ if (!registry.services.signIn) throw new Error("Browser sign-in service is not registered");
58
+ return registry.services.signIn(context, actor, account, signal);
59
+ }
60
+ execute(hook, call, context, registry, signal) {
61
+ return new Promise((resolve, reject) => {
62
+ const operations = new AbortController();
63
+ const child = fork(fileURLToPath(new URL("./worker.js", import.meta.url)), [], {
64
+ cwd: this.options.root,
65
+ execArgv: ["--import", import.meta.resolve("tsx")],
66
+ env: { PATH: process.env.PATH, ...this.options.env },
67
+ detached: true,
68
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
69
+ // Advanced serialization preserves invalid JSON values until the boundary validator.
70
+ serialization: "advanced"
71
+ });
72
+ let result;
73
+ const storageStates = {};
74
+ const active = /* @__PURE__ */ new Set();
75
+ const requests = /* @__PURE__ */ new Map();
76
+ let failed = false;
77
+ let authError;
78
+ let unknownHook = false;
79
+ let stopping = false;
80
+ let timer;
81
+ const stop = () => {
82
+ if (stopping) return;
83
+ stopping = true;
84
+ clearTimeout(timer);
85
+ operations.abort();
86
+ if (child.pid !== void 0) {
87
+ try {
88
+ process.kill(-child.pid, "SIGKILL");
89
+ } catch (error) {
90
+ if (!(error instanceof Error && "code" in error && error.code === "ESRCH"))
91
+ reject(error);
92
+ }
93
+ }
94
+ };
95
+ const send = (message) => {
96
+ if (child.connected) child.send(message, () => {
97
+ });
98
+ };
99
+ const cancel = () => {
100
+ operations.abort();
101
+ send({ type: "abort" });
102
+ timer ??= setTimeout(stop, this.options.abortGraceMs ?? 250);
103
+ };
104
+ signal?.addEventListener("abort", cancel, { once: true });
105
+ child.on("message", (raw) => {
106
+ if (stopping) return;
107
+ const parsed = jsonObjectSchema.safeParse(raw);
108
+ if (!parsed.success) {
109
+ failed = true;
110
+ stop();
111
+ return;
112
+ }
113
+ const message = parsed.data;
114
+ if (message.type === "result") {
115
+ const value = jsonObjectSchema.safeParse(message.vars);
116
+ if (value.success) result = value.data;
117
+ else failed = true;
118
+ stop();
119
+ } else if (message.type === "failed") {
120
+ unknownHook = message.reason === "unknown-hook";
121
+ failed = true;
122
+ stop();
123
+ } else if (message.type === "cancel" && typeof message.id === "number") {
124
+ requests.get(message.id)?.abort();
125
+ } else if ((message.type === "stage" || message.type === "signIn") && typeof message.id === "number" && typeof message.method === "string") {
126
+ const abort = new AbortController();
127
+ const requestSignal = AbortSignal.any([operations.signal, abort.signal]);
128
+ const id = message.id;
129
+ requests.set(id, abort);
130
+ const work = (message.type === "stage" ? stageCall(context, message.method, message.request, requestSignal) : this.signIn(
131
+ registry,
132
+ context,
133
+ String(message.request?.actor),
134
+ String(message.request?.account),
135
+ requestSignal
136
+ ).then((states) => {
137
+ requestSignal.throwIfAborted();
138
+ Object.assign(storageStates, states);
139
+ return {};
140
+ })).then(
141
+ (data) => {
142
+ if (!stopping) send({ type: "response", id: message.id, ok: true, data });
143
+ },
144
+ (error) => {
145
+ if (message.type === "signIn") authError = error;
146
+ if (!stopping)
147
+ send({
148
+ type: "response",
149
+ id: message.id,
150
+ ok: false
151
+ });
152
+ }
153
+ ).finally(() => {
154
+ requests.delete(id);
155
+ active.delete(work);
156
+ });
157
+ active.add(work);
158
+ } else {
159
+ failed = true;
160
+ stop();
161
+ }
162
+ });
163
+ child.once("error", () => {
164
+ failed = true;
165
+ stop();
166
+ });
167
+ child.once("close", async () => {
168
+ stop();
169
+ await Promise.allSettled([...active]);
170
+ signal?.removeEventListener("abort", cancel);
171
+ if (signal?.aborted) reject(signal.reason);
172
+ else if (unknownHook) reject(new HookResolutionError(`Unknown hook: ${call.hook}`));
173
+ else if (failed || result === void 0)
174
+ reject(authError ?? new Error(`Hook failed: ${call.hook}`));
175
+ else resolve({ vars: result, storageStates });
176
+ });
177
+ if (signal?.aborted) cancel();
178
+ else {
179
+ const actor = Object.keys(context.actors).find(
180
+ (name) => context.actors[name]?.kind !== "system"
181
+ );
182
+ const lease = actor === void 0 ? void 0 : context.leases[actor];
183
+ send({
184
+ type: "start",
185
+ ...hook,
186
+ context: {
187
+ runId: context.runId,
188
+ attempt: context.attempt,
189
+ phase: context.phase,
190
+ leases: context.leases,
191
+ run: {
192
+ id: context.runId,
193
+ marker: context.marker ?? context.runId,
194
+ attempt: context.attempt
195
+ },
196
+ lease: {
197
+ ...leaseVariables(lease, context.leases.$flow, actor),
198
+ ...lease?.resources,
199
+ ...actor !== void 0 && registry.services.lease?.(context, actor)
200
+ },
201
+ actors: context.actors,
202
+ target: context.target,
203
+ views: context.views,
204
+ stageViews: context.stageViews,
205
+ params: call.params ?? {},
206
+ vars: context.vars
207
+ }
208
+ });
209
+ }
210
+ });
211
+ }
212
+ }
213
+ async function stageCall(context, method, request, signal) {
214
+ signal.throwIfAborted();
215
+ const { stage } = context;
216
+ switch (method) {
217
+ case "openView":
218
+ return { ...await stage.openView(controlSchemas.openView.request.parse(request), signal) };
219
+ case "renderView":
220
+ return {
221
+ ...await stage.renderView(controlSchemas.renderView.request.parse(request), signal)
222
+ };
223
+ case "closeView":
224
+ return {
225
+ ...await stage.closeView(controlSchemas.closeView.request.parse(request), signal)
226
+ };
227
+ case "expect":
228
+ return { ...await stage.expect(controlSchemas.expect.request.parse(request), signal) };
229
+ case "recordStart":
230
+ return {
231
+ ...await stage.recordStart(controlSchemas.recordStart.request.parse(request), signal)
232
+ };
233
+ case "recordStop":
234
+ return {
235
+ ...await stage.recordStop(controlSchemas.recordStop.request.parse(request), signal)
236
+ };
237
+ case "flushArtifacts":
238
+ return {
239
+ ...await stage.flushArtifacts(
240
+ controlSchemas.flushArtifacts.request.parse(request),
241
+ signal
242
+ )
243
+ };
244
+ case "health":
245
+ return { ...await stage.health(signal) };
246
+ default:
247
+ throw new Error("Unknown hook stage method");
248
+ }
249
+ }
250
+ function raceAbort(work, signal) {
251
+ return new Promise((resolve, reject) => {
252
+ let fallback;
253
+ const cleanup = () => {
254
+ signal.removeEventListener("abort", abort);
255
+ clearImmediate(fallback);
256
+ };
257
+ const abort = () => {
258
+ fallback = setImmediate(() => {
259
+ cleanup();
260
+ reject(signal.reason);
261
+ });
262
+ };
263
+ signal.addEventListener("abort", abort, { once: true });
264
+ work.then(
265
+ (value) => {
266
+ cleanup();
267
+ resolve(value);
268
+ },
269
+ (error) => {
270
+ cleanup();
271
+ reject(error);
272
+ }
273
+ );
274
+ if (signal.aborted) abort();
275
+ });
276
+ }
277
+ export {
278
+ FileHookRunner
279
+ };
@@ -0,0 +1,16 @@
1
+ import type { JsonObject } from "@open-qa/qa-engine/protocol";
2
+ import { type SessionStore } from "./session-store.js";
3
+ export interface CachedSession {
4
+ expiresAt: number;
5
+ storageState: JsonObject;
6
+ }
7
+ export declare const SESSION_EXPIRY_MARGIN_MS: number;
8
+ export declare class SessionCache {
9
+ private readonly now;
10
+ private readonly store;
11
+ private readonly sessions;
12
+ constructor(now?: () => number, store?: SessionStore | null);
13
+ getOrCreate(target: string, account: string, login: (signal?: AbortSignal) => Promise<CachedSession>, signal?: AbortSignal, validate?: (session: CachedSession, signal?: AbortSignal) => Promise<boolean>): Promise<CachedSession>;
14
+ invalidate(target: string, account: string): Promise<void>;
15
+ private key;
16
+ }
@@ -0,0 +1,42 @@
1
+ import { FileSessionStore } from "./session-store.js";
2
+ const SESSION_EXPIRY_MARGIN_MS = 5 * 6e4;
3
+ class SessionCache {
4
+ constructor(now = Date.now, store = new FileSessionStore()) {
5
+ this.now = now;
6
+ this.store = store;
7
+ }
8
+ now;
9
+ store;
10
+ sessions = /* @__PURE__ */ new Map();
11
+ async getOrCreate(target, account, login, signal, validate) {
12
+ signal?.throwIfAborted();
13
+ const key = this.key(target, account);
14
+ const cached = this.store ? await this.store.read(key) : this.sessions.get(key);
15
+ signal?.throwIfAborted();
16
+ if (cached && cached.expiresAt - SESSION_EXPIRY_MARGIN_MS > this.now()) {
17
+ const valid = !validate || await validate(structuredClone(cached), signal);
18
+ signal?.throwIfAborted();
19
+ if (valid) return structuredClone(cached);
20
+ }
21
+ await this.invalidate(target, account);
22
+ const session = await login(signal);
23
+ signal?.throwIfAborted();
24
+ if (!Number.isFinite(session.expiresAt) || session.expiresAt <= this.now())
25
+ throw new Error("Sign-in returned an expired session");
26
+ if (this.store) await this.store.write(key, session, signal);
27
+ else this.sessions.set(key, structuredClone(session));
28
+ return structuredClone(session);
29
+ }
30
+ async invalidate(target, account) {
31
+ const key = this.key(target, account);
32
+ if (this.store) await this.store.remove(key);
33
+ this.sessions.delete(key);
34
+ }
35
+ key(target, account) {
36
+ return JSON.stringify([new URL(target).origin, account]);
37
+ }
38
+ }
39
+ export {
40
+ SESSION_EXPIRY_MARGIN_MS,
41
+ SessionCache
42
+ };
@@ -0,0 +1,20 @@
1
+ import type { CachedSession } from "./session-cache.js";
2
+ export declare class SessionCacheError extends Error {
3
+ constructor(path: string, directory?: boolean);
4
+ }
5
+ export interface SessionStore {
6
+ read(key: string): Promise<CachedSession | undefined>;
7
+ write(key: string, session: CachedSession, signal?: AbortSignal): Promise<void>;
8
+ remove(key: string): Promise<void>;
9
+ }
10
+ export declare class FileSessionStore implements SessionStore {
11
+ private readonly directory;
12
+ constructor(directory?: string);
13
+ read(key: string): Promise<CachedSession | undefined>;
14
+ private readLocal;
15
+ write(key: string, session: CachedSession, signal?: AbortSignal): Promise<void>;
16
+ remove(key: string): Promise<void>;
17
+ private checkDirectory;
18
+ private hash;
19
+ private path;
20
+ }
@@ -0,0 +1,95 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, rename, rm } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { z } from "zod";
7
+ import { jsonObjectSchema } from "@open-qa/qa-engine/protocol";
8
+ const sessionSchema = z.object({ expiresAt: z.number().finite(), storageState: jsonObjectSchema });
9
+ class SessionCacheError extends Error {
10
+ constructor(path, directory = false) {
11
+ super(
12
+ directory ? `Session cache directory must be private (0700): ${path}. Fix its ownership and permissions, then retry.` : `Cannot read private session cache: ${path}. Delete this file and retry.`
13
+ );
14
+ }
15
+ }
16
+ class FileSessionStore {
17
+ directory;
18
+ constructor(directory) {
19
+ this.directory = directory ?? join(homedir(), ".open-qa", "sessions");
20
+ }
21
+ async read(key) {
22
+ return this.readLocal(key);
23
+ }
24
+ async readLocal(key) {
25
+ if (!await this.checkDirectory()) return void 0;
26
+ let file;
27
+ try {
28
+ file = await open(this.path(key), constants.O_RDONLY | constants.O_NOFOLLOW);
29
+ const stat = await file.stat();
30
+ if (!stat.isFile() || stat.nlink !== 1 || !privateMode(stat, 384))
31
+ throw new Error("Session cache file must be private (0600)");
32
+ const parsed = sessionSchema.safeParse(JSON.parse(await file.readFile("utf8")));
33
+ if (!parsed.success) throw new Error("Invalid session cache");
34
+ return parsed.data;
35
+ } catch (error) {
36
+ if (hasCode(error, "ENOENT")) return void 0;
37
+ throw new SessionCacheError(this.path(key));
38
+ } finally {
39
+ await file?.close();
40
+ }
41
+ }
42
+ async write(key, session, signal) {
43
+ signal?.throwIfAborted();
44
+ await mkdir(this.directory, { recursive: true, mode: 448 });
45
+ await this.checkDirectory();
46
+ const temporary = join(this.directory, `.${this.hash(key)}.${randomUUID()}.tmp`);
47
+ try {
48
+ const file = await open(temporary, "wx", 384);
49
+ try {
50
+ await file.writeFile(JSON.stringify(session));
51
+ await file.sync();
52
+ } finally {
53
+ await file.close();
54
+ }
55
+ signal?.throwIfAborted();
56
+ await rename(temporary, this.path(key));
57
+ if (signal?.aborted) {
58
+ await this.remove(key);
59
+ signal.throwIfAborted();
60
+ }
61
+ } finally {
62
+ await rm(temporary, { force: true });
63
+ }
64
+ }
65
+ async remove(key) {
66
+ if (await this.checkDirectory()) await rm(this.path(key), { force: true });
67
+ }
68
+ async checkDirectory() {
69
+ try {
70
+ const stat = await lstat(this.directory);
71
+ if (!stat.isDirectory() || !privateMode(stat, 448))
72
+ throw new Error("Session cache directory must be private (0700)");
73
+ return true;
74
+ } catch (error) {
75
+ if (hasCode(error, "ENOENT")) return false;
76
+ throw new SessionCacheError(this.directory, true);
77
+ }
78
+ }
79
+ hash(key) {
80
+ return createHash("sha256").update(key).digest("hex");
81
+ }
82
+ path(key) {
83
+ return join(this.directory, `${this.hash(key)}.json`);
84
+ }
85
+ }
86
+ function privateMode(stat, mode) {
87
+ return (stat.mode & 4095) === mode && (!process.getuid || stat.uid === process.getuid());
88
+ }
89
+ function hasCode(error, code) {
90
+ return error instanceof Error && "code" in error && error.code === code;
91
+ }
92
+ export {
93
+ FileSessionStore,
94
+ SessionCacheError
95
+ };
@@ -0,0 +1 @@
1
+ export {};