@kurvball/rehearse 0.0.0-stage → 1.2.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 (266) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +102 -2
  3. package/dist/affected/affected.d.ts +22 -0
  4. package/dist/affected/affected.js +162 -0
  5. package/dist/affected/index.d.ts +1 -0
  6. package/dist/affected/index.js +1 -0
  7. package/dist/args.d.ts +12 -0
  8. package/dist/args.js +42 -0
  9. package/dist/cli.d.ts +4 -0
  10. package/dist/cli.js +100 -0
  11. package/dist/commands/check.d.ts +2 -0
  12. package/dist/commands/check.js +42 -0
  13. package/dist/commands/clean.d.ts +2 -0
  14. package/dist/commands/clean.js +37 -0
  15. package/dist/commands/command.d.ts +29 -0
  16. package/dist/commands/command.js +29 -0
  17. package/dist/commands/compare.d.ts +4 -0
  18. package/dist/commands/compare.js +84 -0
  19. package/dist/commands/drive.d.ts +2 -0
  20. package/dist/commands/drive.js +244 -0
  21. package/dist/commands/index.d.ts +3 -0
  22. package/dist/commands/index.js +32 -0
  23. package/dist/commands/init.d.ts +2 -0
  24. package/dist/commands/init.js +19 -0
  25. package/dist/commands/list.d.ts +2 -0
  26. package/dist/commands/list.js +69 -0
  27. package/dist/commands/open.d.ts +2 -0
  28. package/dist/commands/open.js +60 -0
  29. package/dist/commands/people.d.ts +2 -0
  30. package/dist/commands/people.js +49 -0
  31. package/dist/commands/run.d.ts +4 -0
  32. package/dist/commands/run.js +82 -0
  33. package/dist/commands/services.d.ts +28 -0
  34. package/dist/commands/services.js +51 -0
  35. package/dist/commands/stage.d.ts +7 -0
  36. package/dist/commands/stage.js +49 -0
  37. package/dist/commands/up.d.ts +3 -0
  38. package/dist/commands/up.js +77 -0
  39. package/dist/commands/validate.d.ts +2 -0
  40. package/dist/commands/validate.js +35 -0
  41. package/dist/commands/worlds.d.ts +2 -0
  42. package/dist/commands/worlds.js +15 -0
  43. package/dist/compare/announce.d.ts +6 -0
  44. package/dist/compare/announce.js +27 -0
  45. package/dist/compare/compare.d.ts +82 -0
  46. package/dist/compare/compare.js +310 -0
  47. package/dist/compare/diff.d.ts +15 -0
  48. package/dist/compare/diff.js +105 -0
  49. package/dist/compare/index.d.ts +4 -0
  50. package/dist/compare/index.js +4 -0
  51. package/dist/compare/setaside.d.ts +29 -0
  52. package/dist/compare/setaside.js +121 -0
  53. package/dist/compare/verdict.d.ts +21 -0
  54. package/dist/compare/verdict.js +30 -0
  55. package/dist/drive/aria.d.ts +8 -0
  56. package/dist/drive/aria.js +12 -0
  57. package/dist/drive/browser.d.ts +34 -0
  58. package/dist/drive/browser.js +216 -0
  59. package/dist/drive/daemon.d.ts +1 -0
  60. package/dist/drive/daemon.js +171 -0
  61. package/dist/drive/grammar.d.ts +93 -0
  62. package/dist/drive/grammar.js +303 -0
  63. package/dist/drive/index.d.ts +4 -0
  64. package/dist/drive/index.js +4 -0
  65. package/dist/drive/names.d.ts +24 -0
  66. package/dist/drive/names.js +97 -0
  67. package/dist/drive/state.d.ts +13 -0
  68. package/dist/drive/state.js +28 -0
  69. package/dist/errors.d.ts +26 -0
  70. package/dist/errors.js +32 -0
  71. package/dist/exec.d.ts +16 -0
  72. package/dist/exec.js +43 -0
  73. package/dist/git/checkout.d.ts +11 -0
  74. package/dist/git/checkout.js +84 -0
  75. package/dist/git/git.d.ts +7 -0
  76. package/dist/git/git.js +27 -0
  77. package/dist/git/index.d.ts +2 -0
  78. package/dist/git/index.js +2 -0
  79. package/dist/index.d.ts +18 -0
  80. package/dist/index.js +15 -0
  81. package/dist/kinds/all.d.ts +4 -0
  82. package/dist/kinds/all.js +4 -0
  83. package/dist/kinds/call/check.d.ts +29 -0
  84. package/dist/kinds/call/check.js +187 -0
  85. package/dist/kinds/call/definition.d.ts +16 -0
  86. package/dist/kinds/call/definition.js +33 -0
  87. package/dist/kinds/call/hurl.d.ts +65 -0
  88. package/dist/kinds/call/hurl.js +333 -0
  89. package/dist/kinds/call/kind.d.ts +8 -0
  90. package/dist/kinds/call/kind.js +122 -0
  91. package/dist/kinds/call/send.d.ts +32 -0
  92. package/dist/kinds/call/send.js +152 -0
  93. package/dist/kinds/call/words.d.ts +22 -0
  94. package/dist/kinds/call/words.js +24 -0
  95. package/dist/kinds/file/kind.d.ts +44 -0
  96. package/dist/kinds/file/kind.js +331 -0
  97. package/dist/kinds/file/layouts.d.ts +14 -0
  98. package/dist/kinds/file/layouts.js +103 -0
  99. package/dist/kinds/flow/kind.d.ts +21 -0
  100. package/dist/kinds/flow/kind.js +401 -0
  101. package/dist/kinds/flow/literal.d.ts +8 -0
  102. package/dist/kinds/flow/literal.js +148 -0
  103. package/dist/kinds/index.d.ts +10 -0
  104. package/dist/kinds/index.js +8 -0
  105. package/dist/kinds/kind.d.ts +57 -0
  106. package/dist/kinds/kind.js +21 -0
  107. package/dist/kinds/piece/canvas.d.ts +18 -0
  108. package/dist/kinds/piece/canvas.js +165 -0
  109. package/dist/kinds/piece/conventions.d.ts +12 -0
  110. package/dist/kinds/piece/conventions.js +101 -0
  111. package/dist/kinds/piece/csf.d.ts +10 -0
  112. package/dist/kinds/piece/csf.js +304 -0
  113. package/dist/kinds/piece/kind.d.ts +12 -0
  114. package/dist/kinds/piece/kind.js +297 -0
  115. package/dist/kinds/piece/server.d.ts +23 -0
  116. package/dist/kinds/piece/server.js +236 -0
  117. package/dist/manifest/fill.d.ts +4 -0
  118. package/dist/manifest/fill.js +7 -0
  119. package/dist/manifest/index.d.ts +5 -0
  120. package/dist/manifest/index.js +5 -0
  121. package/dist/manifest/init.d.ts +1 -0
  122. package/dist/manifest/init.js +47 -0
  123. package/dist/manifest/load.d.ts +7 -0
  124. package/dist/manifest/load.js +244 -0
  125. package/dist/manifest/types.d.ts +253 -0
  126. package/dist/manifest/types.js +7 -0
  127. package/dist/manifest/yaml.d.ts +5 -0
  128. package/dist/manifest/yaml.js +47 -0
  129. package/dist/people/index.d.ts +1 -0
  130. package/dist/people/index.js +1 -0
  131. package/dist/people/people.d.ts +39 -0
  132. package/dist/people/people.js +139 -0
  133. package/dist/run/cache.d.ts +20 -0
  134. package/dist/run/cache.js +98 -0
  135. package/dist/run/index.d.ts +4 -0
  136. package/dist/run/index.js +3 -0
  137. package/dist/run/observation.d.ts +27 -0
  138. package/dist/run/observation.js +1 -0
  139. package/dist/run/session.d.ts +32 -0
  140. package/dist/run/session.js +258 -0
  141. package/dist/run/vars.d.ts +3 -0
  142. package/dist/run/vars.js +13 -0
  143. package/dist/scenarios/area.d.ts +6 -0
  144. package/dist/scenarios/area.js +37 -0
  145. package/dist/scenarios/files.d.ts +9 -0
  146. package/dist/scenarios/files.js +26 -0
  147. package/dist/scenarios/glob.d.ts +6 -0
  148. package/dist/scenarios/glob.js +106 -0
  149. package/dist/scenarios/index.d.ts +4 -0
  150. package/dist/scenarios/index.js +4 -0
  151. package/dist/scenarios/read.d.ts +18 -0
  152. package/dist/scenarios/read.js +54 -0
  153. package/dist/scenarios/scenario.d.ts +34 -0
  154. package/dist/scenarios/scenario.js +10 -0
  155. package/dist/schema.d.ts +14 -0
  156. package/dist/schema.js +122 -0
  157. package/dist/services/index.d.ts +2 -0
  158. package/dist/services/index.js +2 -0
  159. package/dist/services/registry.d.ts +23 -0
  160. package/dist/services/registry.js +49 -0
  161. package/dist/services/service.d.ts +22 -0
  162. package/dist/services/service.js +284 -0
  163. package/dist/stage/api.d.ts +28 -0
  164. package/dist/stage/api.js +206 -0
  165. package/dist/stage/client/client/api.js +11 -0
  166. package/dist/stage/client/client/index.js +1 -0
  167. package/dist/stage/client/features/canvas/call.js +65 -0
  168. package/dist/stage/client/features/canvas/context.js +1 -0
  169. package/dist/stage/client/features/canvas/file.js +36 -0
  170. package/dist/stage/client/features/canvas/flow.js +59 -0
  171. package/dist/stage/client/features/canvas/index.js +1 -0
  172. package/dist/stage/client/features/canvas/observed.js +8 -0
  173. package/dist/stage/client/features/canvas/parts.js +24 -0
  174. package/dist/stage/client/features/canvas/piece.js +31 -0
  175. package/dist/stage/client/features/canvas/reach.js +6 -0
  176. package/dist/stage/client/features/canvas/views.js +16 -0
  177. package/dist/stage/client/features/list/index.js +1 -0
  178. package/dist/stage/client/features/list/list.js +53 -0
  179. package/dist/stage/client/features/list/reach.js +10 -0
  180. package/dist/stage/client/features/scenario/heading.js +14 -0
  181. package/dist/stage/client/features/scenario/index.js +1 -0
  182. package/dist/stage/client/features/scenario/reach.js +9 -0
  183. package/dist/stage/client/features/scenario/scenario.js +145 -0
  184. package/dist/stage/client/features/try/index.js +1 -0
  185. package/dist/stage/client/features/try/reach.js +12 -0
  186. package/dist/stage/client/features/try/try.js +65 -0
  187. package/dist/stage/client/index.html +16 -0
  188. package/dist/stage/client/main.js +24 -0
  189. package/dist/stage/client/primitives/busy.js +6 -0
  190. package/dist/stage/client/primitives/focus.js +21 -0
  191. package/dist/stage/client/primitives/h.js +25 -0
  192. package/dist/stage/client/primitives/index.js +6 -0
  193. package/dist/stage/client/primitives/keyed.js +16 -0
  194. package/dist/stage/client/primitives/say.js +6 -0
  195. package/dist/stage/client/primitives/state.js +21 -0
  196. package/dist/stage/client/primitives/types.js +1 -0
  197. package/dist/stage/client/primitives/verdicts.js +8 -0
  198. package/dist/stage/client/stage.css +652 -0
  199. package/dist/stage/compared.d.ts +20 -0
  200. package/dist/stage/compared.js +58 -0
  201. package/dist/stage/files.d.ts +4 -0
  202. package/dist/stage/files.js +59 -0
  203. package/dist/stage/guard.d.ts +3 -0
  204. package/dist/stage/guard.js +20 -0
  205. package/dist/stage/http.d.ts +12 -0
  206. package/dist/stage/http.js +34 -0
  207. package/dist/stage/index.d.ts +1 -0
  208. package/dist/stage/index.js +1 -0
  209. package/dist/stage/sending.d.ts +18 -0
  210. package/dist/stage/sending.js +66 -0
  211. package/dist/stage/server.d.ts +31 -0
  212. package/dist/stage/server.js +250 -0
  213. package/dist/version.d.ts +2 -0
  214. package/dist/version.js +5 -0
  215. package/dist/worlds/define.d.ts +16 -0
  216. package/dist/worlds/define.js +45 -0
  217. package/dist/worlds/index.d.ts +2 -0
  218. package/dist/worlds/index.js +2 -0
  219. package/dist/worlds/worlds.d.ts +15 -0
  220. package/dist/worlds/worlds.js +46 -0
  221. package/llms.txt +46 -0
  222. package/package.json +84 -3
  223. package/schema/v1/announce.schema.json +28 -0
  224. package/schema/v1/check.schema.json +67 -0
  225. package/schema/v1/clean.schema.json +19 -0
  226. package/schema/v1/common.schema.json +210 -0
  227. package/schema/v1/comparison.schema.json +298 -0
  228. package/schema/v1/dependents.schema.json +30 -0
  229. package/schema/v1/drive.schema.json +112 -0
  230. package/schema/v1/error.schema.json +26 -0
  231. package/schema/v1/file-scenario.schema.json +175 -0
  232. package/schema/v1/flow.schema.json +216 -0
  233. package/schema/v1/init.schema.json +20 -0
  234. package/schema/v1/list.schema.json +70 -0
  235. package/schema/v1/manifest.schema.json +430 -0
  236. package/schema/v1/observation.schema.json +388 -0
  237. package/schema/v1/open.schema.json +14 -0
  238. package/schema/v1/people.schema.json +88 -0
  239. package/schema/v1/samples/announce.yaml +5 -0
  240. package/schema/v1/samples/check.json +13 -0
  241. package/schema/v1/samples/clean.json +1 -0
  242. package/schema/v1/samples/comparison.json +83 -0
  243. package/schema/v1/samples/dependents.json +7 -0
  244. package/schema/v1/samples/drive.json +10 -0
  245. package/schema/v1/samples/error.json +10 -0
  246. package/schema/v1/samples/file-scenario.yaml +13 -0
  247. package/schema/v1/samples/flow.yaml +13 -0
  248. package/schema/v1/samples/init.json +1 -0
  249. package/schema/v1/samples/list.json +24 -0
  250. package/schema/v1/samples/manifest.yaml +55 -0
  251. package/schema/v1/samples/observation.json +49 -0
  252. package/schema/v1/samples/open.json +6 -0
  253. package/schema/v1/samples/people.json +11 -0
  254. package/schema/v1/samples/services.json +27 -0
  255. package/schema/v1/samples/stage.json +6 -0
  256. package/schema/v1/samples/try.json +13 -0
  257. package/schema/v1/samples/up.json +16 -0
  258. package/schema/v1/samples/validate.json +7 -0
  259. package/schema/v1/samples/worlds.json +21 -0
  260. package/schema/v1/services.schema.json +72 -0
  261. package/schema/v1/stage.schema.json +14 -0
  262. package/schema/v1/try.schema.json +56 -0
  263. package/schema/v1/up.schema.json +55 -0
  264. package/schema/v1/validate.schema.json +40 -0
  265. package/schema/v1/worlds.schema.json +33 -0
  266. package/skill/rehearse/SKILL.md +148 -0
@@ -0,0 +1,284 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { connect, createServer } from 'node:net';
4
+ import path from 'node:path';
5
+ import { RehearseError } from '../errors.js';
6
+ import { sh, tail } from '../exec.js';
7
+ import { fill, fillEnv } from '../manifest/index.js';
8
+ import { alive, checkoutKey, forget, remember, runningServices, stateDir } from './registry.js';
9
+ const POLL_MS = 250;
10
+ const STOP_MS = 5_000;
11
+ export function freePort() {
12
+ return new Promise((resolve, reject) => {
13
+ const server = createServer();
14
+ server.unref();
15
+ server.once('error', reject);
16
+ server.listen(0, '127.0.0.1', () => {
17
+ const address = server.address();
18
+ const port = typeof address === 'object' && address ? address.port : 0;
19
+ server.close(() => resolve(port));
20
+ });
21
+ });
22
+ }
23
+ const portTaken = (port) => new Promise((resolve) => {
24
+ const socket = connect({ port, host: '127.0.0.1' });
25
+ socket.once('connect', () => {
26
+ socket.destroy();
27
+ resolve(true);
28
+ });
29
+ socket.once('error', () => resolve(false));
30
+ });
31
+ export function standinsFor(m, service, real) {
32
+ for (const name of real)
33
+ if (!m.standins[name])
34
+ throw new RehearseError('usage', `There is no stand-in “${name}” to replace with the real one.`, {
35
+ exit: 2,
36
+ });
37
+ return Object.values(m.standins)
38
+ .filter((s) => s.services === null || s.services.includes(service))
39
+ .map((standin) => {
40
+ const isReal = real.has(standin.name);
41
+ if (isReal && standin.real === null)
42
+ throw new RehearseError('no_real', `The stand-in ${standin.name} has no real one to choose locally: its manifest entry names no \`real\`.`);
43
+ return { standin, real: isReal };
44
+ });
45
+ }
46
+ const logDir = (m) => path.join(stateDir(m.dir), 'logs');
47
+ export const logOf = (m, name, checkout) => path.join(logDir(m), `${name}@${checkoutKey(checkout)}.log`);
48
+ function signalledIfStillThere(pid, signal) {
49
+ try {
50
+ process.kill(pid, signal);
51
+ return true;
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ function killGroup(pid, signal) {
58
+ if (!signalledIfStillThere(-pid, signal))
59
+ signalledIfStillThere(pid, signal);
60
+ }
61
+ async function readyNow(ready, vars, env, cwd, log, port) {
62
+ if (ready === null)
63
+ return port === null ? true : portTaken(port);
64
+ if ('http' in ready) {
65
+ try {
66
+ const r = await fetch(fill(ready.http, vars), {
67
+ signal: AbortSignal.timeout(2_000),
68
+ redirect: 'manual',
69
+ });
70
+ await r.body?.cancel();
71
+ return r.status < 500;
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ }
77
+ if ('command' in ready)
78
+ return (await sh(fill(ready.command, vars), { cwd, env, timeoutMs: 15_000 })).code === 0;
79
+ try {
80
+ return new RegExp(ready.log).test(readFileSync(log, 'utf8'));
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ export async function liveServices(m, checkout = null) {
87
+ const out = [];
88
+ for (const r of runningServices(m.dir)) {
89
+ if (checkout !== null && path.resolve(r.checkout) !== path.resolve(checkout))
90
+ continue;
91
+ if (alive(r.pid)) {
92
+ out.push(r);
93
+ continue;
94
+ }
95
+ const s = m.services[r.name];
96
+ const vars = readyVarsOf(m, r);
97
+ const answers = s?.ready
98
+ ? await readyNow(s.ready, vars, r.env ?? {}, s.cwd ? path.resolve(r.checkout, s.cwd) : r.checkout, '', r.port)
99
+ : r.port !== null
100
+ ? await portTaken(r.port)
101
+ : false;
102
+ if (answers)
103
+ out.push(r);
104
+ else
105
+ forget(m.dir, r.name, r.checkout);
106
+ }
107
+ return out;
108
+ }
109
+ export const restartable = (r) => !!(r.up && r.down && r.daemon);
110
+ function readyVarsOf(m, r) {
111
+ return {
112
+ checkout: r.checkout,
113
+ manifest: m.dir,
114
+ ...(r.scratch && { scratch: r.scratch }),
115
+ ...(r.world && { world: r.world }),
116
+ ...(r.port !== null && { port: String(r.port) }),
117
+ ...(r.url && { url: r.url }),
118
+ };
119
+ }
120
+ export async function restart(m, r) {
121
+ const s = m.services[r.name];
122
+ if (!s || !restartable(r))
123
+ return null;
124
+ const cwd = s.cwd ? path.resolve(r.checkout, s.cwd) : r.checkout;
125
+ const env = r.env ?? {};
126
+ await sh(r.down, { cwd, env, timeoutMs: 60_000 });
127
+ const up = await sh(r.up, { cwd, env, timeoutMs: s.timeoutMs });
128
+ const upSaidThisTime = logOf(m, s.name, r.checkout);
129
+ writeFileSync(upSaidThisTime, `${up.stdout}${up.stderr}`);
130
+ if (up.code !== 0)
131
+ return `${s.name} didn't come up again (exit ${up.code}): ${tail(up.stderr || up.stdout)}`;
132
+ const vars = readyVarsOf(m, r);
133
+ const begun = Date.now();
134
+ while (!(await readyNow(s.ready, vars, env, cwd, upSaidThisTime, r.port))) {
135
+ if (Date.now() - begun > s.timeoutMs)
136
+ return `${s.name} wasn't ready again after ${Math.round(s.timeoutMs / 1000)} seconds.`;
137
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
138
+ }
139
+ return null;
140
+ }
141
+ const startedHereNotHandedOver = new Map();
142
+ const keyOf = (r) => `${r.name}@${path.resolve(r.checkout)}`;
143
+ export const release = (r) => startedHereNotHandedOver.delete(keyOf(r));
144
+ export async function downStartedHere() {
145
+ for (const { m, r } of [...startedHereNotHandedOver.values()].toReversed())
146
+ await bringDown(m, r).catch(() => undefined);
147
+ }
148
+ export async function bringUp(m, s, checkout, options) {
149
+ const already = runningServices(m.dir).find((r) => r.name === s.name && path.resolve(r.checkout) === path.resolve(checkout));
150
+ if (already) {
151
+ if (alive(already.pid) || !s.ready)
152
+ return already;
153
+ if (await readyNow(s.ready, {
154
+ ...(already.url && { url: already.url }),
155
+ ...(already.port !== null && { port: String(already.port) }),
156
+ }, already.env ?? {}, s.cwd ? path.resolve(checkout, s.cwd) : checkout, '', already.port))
157
+ return already;
158
+ forget(m.dir, already.name, already.checkout);
159
+ }
160
+ let port = null;
161
+ if (s.port === 'auto')
162
+ port = await freePort();
163
+ else if (typeof s.port === 'number') {
164
+ port = s.port;
165
+ if (await portTaken(port))
166
+ throw new RehearseError('service', `${s.name} listens on port ${port}, and something already answers there. Stop it, or give the service port: auto.`);
167
+ }
168
+ const standins = standinsFor(m, s.name, options.real);
169
+ const cwd = s.cwd ? path.resolve(checkout, s.cwd) : checkout;
170
+ if (!existsSync(cwd))
171
+ throw new RehearseError('service', `${s.name} runs in ${cwd}, which isn't there.`);
172
+ mkdirSync(path.join(stateDir(m.dir), 'scratch'), { recursive: true });
173
+ const scratch = mkdtempSync(path.join(stateDir(m.dir), 'scratch', `${s.name}-${checkoutKey(checkout)}-`));
174
+ const vars = {
175
+ ...options.vars,
176
+ checkout,
177
+ manifest: m.dir,
178
+ scratch,
179
+ ...(options.world !== null && { world: options.world }),
180
+ ...(port !== null && { port: String(port) }),
181
+ };
182
+ const url = s.url === null ? null : fill(s.url, vars);
183
+ if (url !== null)
184
+ vars.url = url;
185
+ const env = {
186
+ ...fillEnv(s.env, vars),
187
+ ...Object.assign({}, ...standins.map(({ standin, real }) => fillEnv(real ? standin.real.env : standin.env, vars))),
188
+ ...(s.isolate && { [s.isolate.env]: scratch }),
189
+ ...(port !== null && { PORT: String(port) }),
190
+ REHEARSE_SCRATCH: scratch,
191
+ };
192
+ mkdirSync(logDir(m), { recursive: true });
193
+ const log = logOf(m, s.name, checkout);
194
+ const out = openSync(log, 'w');
195
+ const command = fill(s.up, vars);
196
+ options.progress?.(`Bringing ${s.name} up in ${checkout}: ${command}`);
197
+ const child = spawn('/bin/sh', ['-c', command], {
198
+ cwd,
199
+ env: { ...process.env, ...env },
200
+ stdio: ['ignore', out, out],
201
+ detached: true,
202
+ });
203
+ closeSync(out);
204
+ let exited;
205
+ child.on('exit', (code) => (exited = code));
206
+ child.on('error', () => (exited = 127));
207
+ child.unref();
208
+ const pid = child.pid;
209
+ if (pid === undefined) {
210
+ rmSync(scratch, { recursive: true, force: true });
211
+ throw new RehearseError('service', `${s.name} didn't start: \`${command}\`.`);
212
+ }
213
+ const running = {
214
+ name: s.name,
215
+ checkout,
216
+ pid,
217
+ port,
218
+ url,
219
+ since: new Date().toISOString(),
220
+ down: s.down === null ? null : fill(s.down, vars),
221
+ scratch,
222
+ standins: standins.map(({ standin, real }) => (real ? `${standin.name}:real` : standin.name)),
223
+ up: command,
224
+ env,
225
+ world: options.world,
226
+ starting: true,
227
+ };
228
+ remember(m.dir, running);
229
+ startedHereNotHandedOver.set(keyOf(running), { m, r: running });
230
+ const begun = Date.now();
231
+ const said = () => tail(readFileSync(log, 'utf8'), 4);
232
+ const giveUp = async (why) => {
233
+ await bringDown(m, running);
234
+ throw new RehearseError('service', why);
235
+ };
236
+ for (;;) {
237
+ if (exited !== undefined && exited !== 0)
238
+ return giveUp(`${s.name} stopped before it was ready (exit ${exited}): ${said() || 'it said nothing'}. Its log: ${log}`);
239
+ if (await readyNow(s.ready, vars, env, cwd, log, port))
240
+ break;
241
+ if (Date.now() - begun > s.timeoutMs)
242
+ return giveUp(`${s.name} wasn't ready after ${Math.round(s.timeoutMs / 1000)} seconds. ${said() ? `It last said: ${said()}. ` : ''}Its log: ${log}`);
243
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
244
+ }
245
+ running.starting = false;
246
+ running.daemon = exited === 0;
247
+ remember(m.dir, running);
248
+ options.progress?.(`${s.name} is ready${url ? ` at ${url}` : ''} (${Date.now() - begun} ms).`);
249
+ return running;
250
+ }
251
+ export async function bringDown(m, r, progress) {
252
+ if (r.down) {
253
+ const s = m.services[r.name];
254
+ const cwd = s?.cwd ? path.resolve(r.checkout, s.cwd) : r.checkout;
255
+ await sh(r.down, {
256
+ cwd,
257
+ timeoutMs: 30_000,
258
+ env: r.env ?? (r.scratch && s?.isolate ? { [s.isolate.env]: r.scratch } : {}),
259
+ });
260
+ }
261
+ killGroup(r.pid, 'SIGTERM');
262
+ const begun = Date.now();
263
+ while (alive(r.pid) && Date.now() - begun < STOP_MS)
264
+ await new Promise((resolve) => setTimeout(resolve, 100));
265
+ if (alive(r.pid))
266
+ killGroup(r.pid, 'SIGKILL');
267
+ if (r.scratch)
268
+ rmSync(r.scratch, { recursive: true, force: true });
269
+ forget(m.dir, r.name, r.checkout);
270
+ startedHereNotHandedOver.delete(keyOf(r));
271
+ progress?.(`${r.name} is down (${r.checkout}).`);
272
+ }
273
+ export async function makeRoom(m, checkout, progress) {
274
+ const others = runningServices(m.dir).filter((r) => path.resolve(r.checkout) !== path.resolve(checkout));
275
+ const sets = [...new Set(others.map((r) => path.resolve(r.checkout)))];
276
+ const over = sets.length + 1 - m.budget.services;
277
+ if (over <= 0)
278
+ return;
279
+ for (const set of sets.slice(0, over)) {
280
+ progress?.(`The budget allows ${m.budget.services} set${m.budget.services === 1 ? '' : 's'} of services at once: stopping those in ${set}.`);
281
+ for (const r of others.filter((x) => path.resolve(x.checkout) === set))
282
+ await bringDown(m, r, progress);
283
+ }
284
+ }
@@ -0,0 +1,28 @@
1
+ import type { Manifest } from '../manifest/index.ts';
2
+ import { type Observation } from '../run/index.ts';
3
+ import { type Scenario } from '../scenarios/index.ts';
4
+ import type { LastCompared } from './compared.ts';
5
+ import { type Handler, type Side } from './http.ts';
6
+ import type { ServicesForSending } from './sending.ts';
7
+ export interface StageScope {
8
+ m: Manifest;
9
+ asked: {
10
+ repo: string;
11
+ cwd: string;
12
+ head: string | null;
13
+ base: string | null;
14
+ progress: (line: string) => void;
15
+ };
16
+ head: {
17
+ path: string;
18
+ ref: string | null;
19
+ };
20
+ baseRef: string;
21
+ checkoutOf(side: Side): Promise<string>;
22
+ scenarioOn(side: Side, id: string): Promise<Scenario | null>;
23
+ runs: Map<string, Observation>;
24
+ compared: LastCompared;
25
+ sending: ServicesForSending;
26
+ triesFile: string;
27
+ }
28
+ export declare function apiOf(s: StageScope): Record<string, Handler>;
@@ -0,0 +1,206 @@
1
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { compare, lineOf } from '../compare/index.js';
3
+ import { RehearseError } from '../errors.js';
4
+ import { infoOf } from '../git/index.js';
5
+ import { scrub } from '../people/index.js';
6
+ import { runSide } from '../run/index.js';
7
+ import { readScenarios, refOf } from '../scenarios/index.js';
8
+ import { validate } from '../schema.js';
9
+ import { bodyOf, personIn, sideOf, str, worldIn } from './http.js';
10
+ const readObservation = (file) => {
11
+ if (!file)
12
+ return null;
13
+ try {
14
+ return JSON.parse(readFileSync(file, 'utf8'));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ };
20
+ const triesIn = (triesFile, id) => {
21
+ if (!existsSync(triesFile))
22
+ return [];
23
+ return readFileSync(triesFile, 'utf8')
24
+ .split('\n')
25
+ .filter(Boolean)
26
+ .map((l) => JSON.parse(l))
27
+ .filter((t) => t.scenario === id)
28
+ .toReversed();
29
+ };
30
+ export function apiOf(s) {
31
+ const { m, head, baseRef, runs, compared } = s;
32
+ const worldOf = (v) => worldIn(m, v);
33
+ const personOf = (v) => personIn(m, v);
34
+ return {
35
+ 'GET /api/index': async () => {
36
+ const read = await readScenarios(m, head.path);
37
+ const { whole: w, partial: p } = compared.reread();
38
+ const c = w.comparison ?? p.comparison;
39
+ const scenarios = read.scenarios.map((sc) => ({
40
+ ...refOf(sc),
41
+ world: sc.world,
42
+ person: sc.person,
43
+ service: sc.service,
44
+ verdict: compared.newerEntryOf(sc.id)?.verdict ?? null,
45
+ }));
46
+ const entries = read.scenarios.flatMap((sc) => compared.newerEntryOf(sc.id) ?? []);
47
+ const since = compared.someComparedOnItsOwnSince(w.at);
48
+ const tally = () => {
49
+ const n = {
50
+ same: 0,
51
+ said: 0,
52
+ announced: 0,
53
+ edited: 0,
54
+ unsaid: 0,
55
+ new: 0,
56
+ fails: 0,
57
+ failsOnBoth: 0,
58
+ gone: w.comparison?.counts.gone ?? 0,
59
+ notRun: w.comparison?.counts.notRun ?? 0,
60
+ };
61
+ for (const e of entries) {
62
+ n[e.verdict] += 1;
63
+ if (e.verdict === 'said' && e.said)
64
+ n[e.said] += 1;
65
+ if (e.verdict === 'fails' && e.failsOnBase)
66
+ n.failsOnBoth += 1;
67
+ }
68
+ return lineOf(n);
69
+ };
70
+ return {
71
+ v: 1,
72
+ manifest: m.file,
73
+ head: infoOf(m, head.path, head.ref),
74
+ base: { ref: baseRef, commit: c?.base.checkout.commit ?? null },
75
+ line: w.comparison && !since
76
+ ? w.comparison.line
77
+ : entries.length === 0
78
+ ? null
79
+ : w.comparison
80
+ ? tally()
81
+ : `${entries.length} of ${scenarios.length} compared · ${tally()}`,
82
+ comparedAt: c ? new Date(w.comparison ? w.at : p.at).toISOString() : null,
83
+ scenarios,
84
+ gone: c?.gone ?? [],
85
+ refused: read.refused,
86
+ people: Object.keys(m.people),
87
+ person: m.defaults.person,
88
+ worlds: Object.keys(m.worlds),
89
+ world: m.defaults.world,
90
+ };
91
+ },
92
+ 'GET /api/scenario': async (_req, url) => {
93
+ const id = url.searchParams.get('id') ?? '';
94
+ const sc = await s.scenarioOn('head', id);
95
+ const entry = compared.newerEntryOf(id);
96
+ if (!sc && !entry)
97
+ throw new RehearseError('no_scenario', `There is no scenario “${id}”.`);
98
+ const spec = sc?.kind === 'call'
99
+ ? {
100
+ text: sc.spec.call.lines.join('\n'),
101
+ request: `${sc.spec.call.method} ${sc.spec.call.url}`,
102
+ }
103
+ : (sc?.spec ?? null);
104
+ return {
105
+ v: 1,
106
+ scenario: sc
107
+ ? { ...refOf(sc), world: sc.world, person: sc.person, service: sc.service }
108
+ : entry.scenario,
109
+ spec,
110
+ comparison: entry,
111
+ base: runs.get(`base|${id}`) ?? readObservation(entry?.observations.base ?? null),
112
+ head: runs.get(`head|${id}`) ?? readObservation(entry?.observations.head ?? null),
113
+ tries: triesIn(s.triesFile, id),
114
+ };
115
+ },
116
+ 'POST /api/run': async (req) => {
117
+ const b = await bodyOf(req);
118
+ const id = str(b.id) ?? '';
119
+ const side = sideOf(b.side);
120
+ const world = worldOf(b.world);
121
+ const as = personOf(b.person);
122
+ const checkout = await s.checkoutOf(side);
123
+ const sc = await s.scenarioOn(side, id);
124
+ if (!sc)
125
+ throw new RehearseError('no_scenario', `The ${side} has no scenario “${id}”.`);
126
+ await s.sending.takeDown();
127
+ const run = await runSide(m, checkout, [sc], {
128
+ world,
129
+ as,
130
+ real: new Set(),
131
+ keepUp: false,
132
+ progress: s.asked.progress,
133
+ ref: side === 'base' ? baseRef : head.ref,
134
+ });
135
+ const ob = run.observations.get(id);
136
+ if (!ob) {
137
+ const why = run.broke ?? run.notRun[0];
138
+ throw new RehearseError('not_run', `It didn't run on the ${side}${why ? ` (${why.step}): ${why.says}` : '.'}`);
139
+ }
140
+ runs.set(`${side}|${id}`, ob);
141
+ return ob;
142
+ },
143
+ 'POST /api/compare': async (req) => {
144
+ const b = await bodyOf(req);
145
+ const id = str(b.id) ?? '';
146
+ const world = worldOf(b.world);
147
+ const as = personOf(b.person);
148
+ if (!(await s.scenarioOn('head', id)) && !compared.newerEntryOf(id))
149
+ throw new RehearseError('no_scenario', `There is no scenario “${id}”.`);
150
+ await s.sending.takeDown();
151
+ const c = await compare(m, {
152
+ repo: s.asked.repo,
153
+ cwd: s.asked.cwd,
154
+ head: s.asked.head,
155
+ base: s.asked.base,
156
+ ids: [id],
157
+ affected: false,
158
+ announce: null,
159
+ said: [],
160
+ fresh: false,
161
+ world,
162
+ as,
163
+ real: new Set(),
164
+ progress: s.asked.progress,
165
+ });
166
+ const entry = c.scenarios.find((e) => e.scenario.id === id) ?? null;
167
+ if (entry) {
168
+ runs.delete(`base|${id}`);
169
+ runs.delete(`head|${id}`);
170
+ }
171
+ return { v: 1, line: c.line, base: c.base, head: c.head, entry, notRun: c.notRun };
172
+ },
173
+ 'POST /api/try': async (req) => {
174
+ const b = await bodyOf(req);
175
+ const id = str(b.id) ?? '';
176
+ if (typeof b.works !== 'boolean')
177
+ throw new RehearseError('usage', 'Say whether it works: works is true or false.');
178
+ const entry = compared.newerEntryOf(id);
179
+ if (!entry && !(await s.scenarioOn('head', id)))
180
+ throw new RehearseError('no_scenario', `There is no scenario “${id}”.`);
181
+ const c = compared.latest();
182
+ const line = {
183
+ v: 1,
184
+ scenario: id,
185
+ works: b.works,
186
+ note: typeof b.note === 'string' ? scrub(b.note.slice(0, 4000), s.sending.tokens()) : '',
187
+ world: worldOf(b.world),
188
+ person: personOf(b.person),
189
+ mode: str(b.mode) ?? 'head',
190
+ verdict: entry?.verdict ?? null,
191
+ base: c?.base.checkout.commit ?? null,
192
+ head: infoOf(m, head.path, head.ref).commit,
193
+ at: new Date().toISOString(),
194
+ };
195
+ const invalid = validate('try', line);
196
+ if (invalid.length)
197
+ throw new RehearseError('usage', invalid[0].says);
198
+ appendFileSync(s.triesFile, `${JSON.stringify(line)}\n`);
199
+ return line;
200
+ },
201
+ 'GET /api/tries': async (_req, url) => ({
202
+ v: 1,
203
+ tries: triesIn(s.triesFile, url.searchParams.get('id') ?? ''),
204
+ }),
205
+ };
206
+ }
@@ -0,0 +1,11 @@
1
+ const refusedByTheStage = (answer) => answer.ok === false && answer.error !== undefined;
2
+ export async function api(path, body) {
3
+ const r = await fetch(path, body === undefined
4
+ ? {}
5
+ : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
6
+ const json = (await r.json());
7
+ if (!r.ok || refusedByTheStage(json))
8
+ throw new Error(json.error?.says ?? `The stage answered ${r.status}.`);
9
+ return json;
10
+ }
11
+ export const fileUrl = (file) => `/files?path=${encodeURIComponent(file)}`;
@@ -0,0 +1 @@
1
+ export { api, fileUrl } from './api.js';
@@ -0,0 +1,65 @@
1
+ import { api } from '../../client/index.js';
2
+ import { disableKeepingFocus, enableAgain, h, say, state } from '../../primitives/index.js';
3
+ import { differencesOrCompare, failuresOf, pretty, sideObs } from './parts.js';
4
+ const callEditsKeptAcrossDraws = new Map();
5
+ function answerOf(ctx, o, title) {
6
+ const seen = o?.observed;
7
+ if (!o || !seen)
8
+ return h('div', {}, h('h3', {}, title), o ? (failuresOf(o) ?? ctx.notRunYet('head')) : h('p', { class: 'note' }, 'Not run yet.'));
9
+ const ok = typeof seen.status === 'number' && seen.status < 400;
10
+ return h('div', {}, h('h3', {}, title), h('div', { class: 'answer-head' }, h('span', { class: `code-badge ${ok ? 'ok' : 'bad'}` }, String(seen.status ?? '—')), h('span', {}, seen.contentType ?? ''), h('span', { class: 'note' }, seen.who ? `as ${seen.who}` : '')), h('pre', {}, pretty(seen.body)), failuresOf(o));
11
+ }
12
+ export const callView = (ctx) => {
13
+ if (ctx.mode === 'diff')
14
+ return h('div', {}, differencesOrCompare(ctx), h('div', { class: 'split' }, answerOf(ctx, ctx.detail.base, 'On the base'), answerOf(ctx, ctx.detail.head, 'On the head')));
15
+ const side = ctx.mode;
16
+ const id = ctx.detail.scenario.id;
17
+ const editor = h('textarea', {
18
+ class: 'code',
19
+ 'aria-label': 'The call, in Hurl',
20
+ spellcheck: 'false',
21
+ 'data-key': 'call',
22
+ oninput: (e) => void callEditsKeptAcrossDraws.set(id, e.target.value),
23
+ }, callEditsKeptAcrossDraws.get(id) ?? String(ctx.detail.spec?.text ?? ''));
24
+ const out = h('div', {}, answerOf(ctx, sideObs(ctx, side), side === 'base' ? 'On the base' : 'On the head'));
25
+ const send = h('button', { class: 'btn primary', type: 'button', 'data-key': 'send' }, `Send to the ${side}`);
26
+ let sending = false;
27
+ send.addEventListener('click', () => {
28
+ if (sending)
29
+ return;
30
+ sending = true;
31
+ disableKeepingFocus(send);
32
+ out.replaceChildren(h('p', { class: 'status' }, `Sending to the ${side}…`));
33
+ say(`Sending to the ${side}…`);
34
+ api('/api/send', { id, side, text: editor.value, world: state.world, person: state.person })
35
+ .then((a) => {
36
+ out.replaceChildren(answerOf(ctx, {
37
+ ok: a.failures.length === 0,
38
+ failures: a.failures,
39
+ broke: null,
40
+ observed: { kind: 'call', ...a },
41
+ }, `Sent to the ${side}`));
42
+ say(`Sent to the ${side}${a.status === null ? '' : `: ${a.status}`}.`);
43
+ })
44
+ .catch((e) => {
45
+ out.replaceChildren(h('p', { class: 'error' }, e.message));
46
+ say(e.message);
47
+ })
48
+ .finally(() => {
49
+ sending = false;
50
+ enableAgain(send);
51
+ });
52
+ });
53
+ const own = String(ctx.detail.spec?.text ?? '');
54
+ const putBack = h('button', {
55
+ class: 'btn',
56
+ type: 'button',
57
+ 'data-key': 'put-back',
58
+ onclick: () => {
59
+ callEditsKeptAcrossDraws.delete(id);
60
+ editor.value = own;
61
+ editor.focus();
62
+ },
63
+ }, 'Put back');
64
+ return h('div', { class: 'split' }, h('div', {}, h('h3', {}, 'Request'), editor, h('p', {}, send, ' ', putBack)), out);
65
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import { fileUrl } from '../../client/index.js';
2
+ import { h } from '../../primitives/index.js';
3
+ import { differencesOrCompare, failuresOf, markLinesNotIn, pretty, sideObs } from './parts.js';
4
+ function outputView(o, other) {
5
+ if (o.layout === 'missing')
6
+ return h('p', { class: 'error' }, `${o.file} wasn't written.`);
7
+ if (o.layout === 'skip')
8
+ return h('p', { class: 'note' }, 'Not compared: the scenario says to skip it.');
9
+ if (o.rows && o.columns) {
10
+ const columns = o.columns;
11
+ return h('table', { class: 'rows' }, h('thead', {}, h('tr', {}, h('th', {}, '#'), columns.map((c) => h('th', {}, c)))), h('tbody', {}, o.rows.map((r, i) => h('tr', {}, h('td', {}, String(i + 1)), columns.map((c, j) => {
12
+ const was = other?.rows?.[i]?.[other.columns?.indexOf(c) ?? -1];
13
+ const changed = other !== null && was !== undefined && was !== r[j];
14
+ return h('td', { class: changed ? 'changed' : null }, r[j] ?? '', changed ? h('span', { class: 'was' }, `was ${was}`) : null);
15
+ })))));
16
+ }
17
+ if (o.entries)
18
+ return h('div', {}, o.entries.map((e) => h('div', {}, h('h3', {}, e.file), outputView(e, other?.entries?.find((x) => x.file === e.file) ?? null))));
19
+ if (o.json !== undefined)
20
+ return h('pre', {}, pretty(o.json));
21
+ const text = (o.lines ?? []).join('\n');
22
+ const theirs = other?.lines ? other.lines.join('\n') : null;
23
+ return theirs === null ? h('pre', {}, text) : markLinesNotIn(text, theirs, 'in');
24
+ }
25
+ const outputsOf = (o) => (o?.observed?.outputs ?? []);
26
+ export const fileView = (ctx) => {
27
+ const side = ctx.mode === 'diff' ? 'head' : ctx.mode;
28
+ const o = sideObs(ctx, side);
29
+ if (!o)
30
+ return ctx.notRunYet(side);
31
+ const theirs = ctx.mode === 'diff' ? outputsOf(ctx.detail.base) : null;
32
+ const input = o.artifacts?.find((a) => a.kind === 'input');
33
+ return h('div', {}, ctx.mode === 'diff' ? differencesOrCompare(ctx) : null, input
34
+ ? h('p', { class: 'note' }, 'Input: ', h('a', { href: fileUrl(input.path), target: '_blank' }, input.path.split('/').at(-1) ?? input.path))
35
+ : null, failuresOf(o), outputsOf(o).map((out) => h('div', {}, h('h3', {}, ctx.mode === 'diff' ? `${out.file}, on the head, against the base` : out.file), outputView(out, theirs ? (theirs.find((x) => x.file === out.file) ?? null) : null))));
36
+ };