@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 692 lines 29.7 KB
Raw
1 import {
2 chmodSync,
3 existsSync,
4 mkdirSync,
5 readdirSync,
6 readFileSync,
7 rmSync,
8 writeFileSync,
9 } from "node:fs";
10 import os from "node:os";
11 import path from "node:path";
12 /**
13 * Scripted terminal demo of the Alchemy CLI, recorded with tcut
14 * (https://github.com/AmanVarshney01/tcut).
15 *
16 * tcut demo.video.ts # record + render out/alchemy-cli.mp4
17 * tcut test demo.video.ts # replay fast, assertions only (no video)
18 * tcut render out/alchemy-cli.cast … # re-render the last recording, no shell
19 *
20 * The run never touches your real `~/.alchemy`: it starts from an EMPTY
21 * throwaway `ALCHEMY_HOME` and follows a brand-new user in order, one title
22 * card (`t.slide`, tcut ≥ 1.3) and mp4 chapter per step: connect Cloudflare
23 * through the `alchemy profile` TUI (OAuth,
24 * granted in tcut's browser pane), `alchemy dev`, `alchemy deploy`, an
25 * out-of-band edit caught and fixed by `alchemy drift`, and `alchemy destroy`.
26 * Stack state stays in this directory's `.alchemy/`; everything the demo
27 * deploys is destroyed at the end.
28 *
29 * Inputs (environment):
30 * CLOUDFLARE_ACCOUNT_NAME (env or ./.env, optional)
31 * The account to arrow down to in the picker when the login sees
32 * several accounts; defaults to the account id.
33 * CLOUDFLARE_LOGIN_EMAIL / CLOUDFLARE_LOGIN_PASSWORD (env or ./.env)
34 * Dashboard login for the Cloudflare account used on camera. If unset,
35 * the script waits (up to 4 min) for you to sign in by hand in the
36 * browser window; either way it clicks through the consent page.
37 * CLOUDFLARE_API_TOKEN / CLOUDFLARE_ACCOUNT_ID
38 * API token for the OFF-camera pre-flight that destroys anything a
39 * previous take left behind. Falls back to the token stored in the
40 * real `testing` profile. Written to a gitignored `demo.env` that only
41 * `--env-file demo.env` reads, so the value never lands in the `.cast`.
42 *
43 * The CLI opens the OAuth URL with `open`; a shim on the recorded shell's
44 * PATH captures that URL for tcut's browser instead of your real browser.
45 *
46 * `alchemy dev` never returns on its own — the script drives it like a user
47 * would (edit a file, watch the reload) and then sends Ctrl+C.
48 */
49 import { defineVideo } from "termcut";
50
51 const here = path.dirname(new URL(import.meta.url).pathname);
52 const realHome = path.join(os.homedir(), ".alchemy");
53 const demoHome = path.join(os.tmpdir(), "alchemy-cli-demo-home");
54 const shimDir = path.join(os.tmpdir(), "alchemy-cli-demo-bin");
55 const oauthUrlFile = path.join(shimDir, "oauth-url");
56 const apiFile = path.join(here, "src", "Api.ts");
57 const envFile = path.join(here, "demo.env");
58 /**
59 * `KEY=value` lines from this directory's gitignored `.env`, if present.
60 *
61 * Bun auto-loads the same file into `process.env`, but with shell semantics:
62 * `$WORD` gets expanded and `#` starts a comment, which silently mangles a
63 * password containing either. Values are read verbatim here and take
64 * precedence over `process.env` for exactly the keys the file defines.
65 */
66 const dotenv: Record<string, string> = Object.fromEntries(
67 (existsSync(path.join(here, ".env"))
68 ? readFileSync(path.join(here, ".env"), "utf8").split("\n")
69 : []
70 )
71 .map((line) => line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/))
72 .filter((m): m is RegExpMatchArray => m !== null)
73 .map(([, key, value]) => [key, value!.replace(/^(["'])(.*)\1$/, "$2")]),
74 );
75 const env = (key: string) => dotenv[key] ?? process.env[key];
76 const login = {
77 email: env("CLOUDFLARE_LOGIN_EMAIL"),
78 password: env("CLOUDFLARE_LOGIN_PASSWORD"),
79 };
80 /** Matches the local provider's ready line; group 1 is the served URL. */
81 const STARTED = /Started in \d+ms → (http:\/\/localhost:\d+\/)/;
82
83 /**
84 * Resolves once `url` (our worker's favicon route) answers with the worker's
85 * own empty 404 three times in a row. Cloudflare's "not provisioned yet" page
86 * is also a 404, but carries an `error code: 1042` body.
87 */
88 const waitForWorker = async (url: string, attempts = 90) => {
89 let streak = 0;
90 for (let i = 0; i < attempts; i++) {
91 const ok = await fetch(url, { signal: AbortSignal.timeout(5_000) })
92 .then(async (r) => r.status === 404 && (await r.text()) === "")
93 .catch(() => false);
94 streak = ok ? streak + 1 : 0;
95 if (streak === 3) return;
96 await new Promise((resolve) => setTimeout(resolve, 1000));
97 }
98 throw new Error(`${url} did not come up after ${attempts}s`);
99 };
100
101 /**
102 * Write `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` to `demo.env`
103 * (gitignored, removed after the take). The on-camera setup command reads
104 * them through `--env-file demo.env`, so the value is never typed and never
105 * lands in the `.cast`; no other command loads the file, so deploy/dev
106 * authenticate through the profile rather than the environment.
107 *
108 * Returns the credentials for the script's own out-of-band API call (the
109 * drift step).
110 */
111 const writeCredentialEnvFile = () => {
112 let token = env("CLOUDFLARE_API_TOKEN");
113 let accountId = env("CLOUDFLARE_ACCOUNT_ID");
114 if (!token || !accountId) {
115 const stored = JSON.parse(
116 readFileSync(path.join(realHome, "profiles", "testing", "cloudflare.json"), "utf8"),
117 ).values as Record<string, string>;
118 if (stored.credentialType !== "apiToken") {
119 throw new Error(
120 "set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID (the 'testing' profile has no stored API token to fall back on)",
121 );
122 }
123 token = stored.apiToken!;
124 accountId = stored.accountId!;
125 }
126 // The account id is also how the script picks the account if the OAuth
127 // login can see more than one; it is public enough (the dashboard prints it).
128 process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
129 writeFileSync(envFile, `CLOUDFLARE_API_TOKEN=${token}\nCLOUDFLARE_ACCOUNT_ID=${accountId}\n`, {
130 mode: 0o600,
131 });
132 return { token, accountId };
133 };
134
135 const connectCloudflare = (profile: string) =>
136 `alchemy profile edit --profile ${profile} --add Cloudflare --method stored --set apiToken=env:CLOUDFLARE_API_TOKEN --set accountId=env:CLOUDFLARE_ACCOUNT_ID --env-file demo.env`;
137
138 /**
139 * The deployed `Visits` KV namespace, read from the stack's local state
140 * (`alchemy deploy` targets the `live_<user>` stage).
141 */
142 const deployedVisitsNamespace = () => {
143 const stackDir = path.join(here, ".alchemy", "state", "Demo");
144 const stage = readdirSync(stackDir).find((name) => name.startsWith("live_"));
145 if (stage === undefined) {
146 throw new Error(`no live stage under ${stackDir}`);
147 }
148 const state = JSON.parse(readFileSync(path.join(stackDir, stage, "Visits.json"), "utf8")) as {
149 attr: { title: string; namespaceId: string; accountId: string };
150 };
151 return state.attr;
152 };
153
154 /** Direct Cloudflare API access to one KV namespace, bypassing alchemy. */
155 const kvNamespaceApi = (credentials: { token: string; accountId: string }, namespaceId: string) => {
156 const call = async (init: RequestInit) => {
157 const response = await fetch(
158 `https://api.cloudflare.com/client/v4/accounts/${credentials.accountId}/storage/kv/namespaces/${namespaceId}`,
159 {
160 ...init,
161 headers: {
162 Authorization: `Bearer ${credentials.token}`,
163 "Content-Type": "application/json",
164 },
165 },
166 );
167 const body = (await response.json()) as { result: { title: string } };
168 if (!response.ok) {
169 throw new Error(
170 `KV namespace ${namespaceId}: ${init.method} failed with ${response.status} ${JSON.stringify(body)}`,
171 );
172 }
173 return body.result;
174 };
175 return {
176 title: async () => (await call({ method: "GET" })).title,
177 /**
178 * Rename the namespace behind alchemy's back — what a teammate clicking
179 * around the dashboard would do. This is the drift the demo detects and
180 * repairs.
181 */
182 rename: (title: string) => call({ method: "PUT", body: JSON.stringify({ title }) }),
183 };
184 };
185
186 /** Fresh, empty `ALCHEMY_HOME`. */
187 const seedDemoHome = () => {
188 rmSync(demoHome, { recursive: true, force: true });
189 mkdirSync(demoHome, { recursive: true });
190 };
191
192 /**
193 * `open` shim: instead of launching the system browser, record the URL so the
194 * script can hand it to tcut's browser pane.
195 */
196 const seedOpenShim = () => {
197 rmSync(shimDir, { recursive: true, force: true });
198 mkdirSync(shimDir, { recursive: true });
199 const shim = path.join(shimDir, "open");
200 writeFileSync(shim, `#!/bin/sh\nprintf '%s' "$1" > ${oauthUrlFile}\n`);
201 chmodSync(shim, 0o755);
202 };
203
204 const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
205
206 /** The authorization URL the CLI asked `open` to launch. */
207 const waitForOAuthUrl = async (attempts = 240) => {
208 for (let i = 0; i < attempts; i++) {
209 if (existsSync(oauthUrlFile)) return readFileSync(oauthUrlFile, "utf8");
210 await sleep(250);
211 }
212 throw new Error("the CLI never opened the OAuth URL");
213 };
214
215 /**
216 * Cloudflare's login page is a React form; set the controlled inputs through
217 * the native value setter (so React sees the change) and submit.
218 */
219 const signInScript = (email: string, password: string) => `(() => {
220 const set = (selector, value) => {
221 const el = document.querySelector(selector);
222 if (!el) return false;
223 Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(el, value);
224 el.dispatchEvent(new Event("input", { bubbles: true }));
225 el.dispatchEvent(new Event("change", { bubbles: true }));
226 return true;
227 };
228 return set("#email", ${JSON.stringify(email)}) && set("#password", ${JSON.stringify(password)});
229 })()`;
230
231 /** True once both controlled inputs actually hold the values we set. */
232 const signInFilledScript = (email: string, password: string) =>
233 `document.querySelector("#email")?.value === ${JSON.stringify(email)} &&
234 document.querySelector("#password")?.value === ${JSON.stringify(password)}`;
235
236 /**
237 * True once the login page's Turnstile widget has produced its token. Without
238 * it Cloudflare answers a perfectly good password with "Incorrect email or
239 * password", so the submit has to wait for it. (`login_challenge` is a
240 * different, always-populated field — don't match on `*challenge*`.)
241 */
242 const turnstileReadyScript = `[...document.querySelectorAll(
243 'input[name="cf_challenge_response"], input[name="cf-turnstile-response"]'
244 )].some((el) => el.value.length > 0)`;
245
246 /**
247 * The account row to pick on the consent screen's "Select account(s)" step:
248 * the configured account name, or whichever row comes first.
249 */
250 const accountButtonPattern = (() => {
251 const name = env("CLOUDFLARE_ACCOUNT_NAME");
252 return name
253 ? new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, "i")
254 : /^(?!Review permissions$|Cancel$).+/;
255 })();
256
257 /** Click the first button whose text matches (consent pages vary in markup). */
258 const clickButtonScript = (pattern: RegExp) => `(() => {
259 const el = [...document.querySelectorAll("button, input[type=submit], a[role=button]")]
260 .find((b) => ${pattern}.test((b.innerText || b.value || "").trim()));
261 if (!el) return false;
262 el.click();
263 return true;
264 })()`;
265
266 /** Logical frame size (rendered at 2x); the 110x32 grid is centred inside. */
267 const VIDEO = { width: 1368, height: 816 };
268
269 export default defineVideo(
270 {
271 output: ["out/alchemy-cli.mp4"],
272 shell: "zsh",
273 cols: 110,
274 rows: 32,
275 width: VIDEO.width,
276 height: VIDEO.height,
277 theme: "catppuccin-mocha",
278 typingSpeed: "15ms",
279 typingJitter: 0.3,
280 waitTimeout: "180s",
281 endPause: "2s",
282 requires: ["curl"],
283 // A real browser window, composited over the terminal only while
284 // focused — used for the OAuth grant and to show the local dev server.
285 // Sized to the video so it takes the whole frame when it is in front.
286 browser: { position: "overlay", ...VIDEO, offset: { x: 0, y: 0 } },
287 },
288 async (t) => {
289 seedDemoHome();
290 seedOpenShim();
291 const credentials = writeCredentialEnvFile();
292 const originalApi = readFileSync(apiFile, "utf8");
293
294 /**
295 * A full-screen transition card between steps (`t.slide`, tcut ≥ 1.3),
296 * drawn at render time in real typography and faded in and out. It also
297 * records an mp4 chapter of the same name (`--chapters`,
298 * `--split-chapters`), and the screen is cleared behind the card so the
299 * next step starts fresh.
300 */
301 let step = 0;
302 const slide = async (heading: string, subtitle: string) => {
303 step += 1;
304 await t.caption(null);
305 await t.slide(heading, {
306 eyebrow: String(step),
307 subtitle,
308 duration: "2.2s",
309 fade: "400ms",
310 during: async () => {
311 // `run` waits for a fresh prompt, which never comes when the screen
312 // is already just a prompt (clear redraws nothing new).
313 const lines = t
314 .screen()
315 .split("\n")
316 .filter((l) => l.trim());
317 if (lines.length > 1) await t.run("clear");
318 },
319 });
320 };
321
322 /**
323 * A subtitle over the bottom of the terminal (`t.caption`, tcut ≥ 1.4) for
324 * the moments where the screen alone doesn't say what is happening. Drawn
325 * at render time, never typed into the PTY; stays up until the next
326 * caption, `caption(null)`, or the next slide.
327 */
328 const caption = (text: string, duration?: string) =>
329 t.caption(text, { style: "classic", fontSize: 26, duration });
330
331 try {
332 // Off-camera: point the CLI at the empty home, put the `open` shim and
333 // the workspace `alchemy` bin on PATH, and make sure nothing is left
334 // from a previous take.
335 await t.hide(async () => {
336 await t.run(
337 `export ALCHEMY_HOME=${JSON.stringify(demoHome)} PATH="${shimDir}:$PWD/node_modules/.bin:$PATH"`,
338 );
339 // The CLI falls back to plain output when it detects a coding agent
340 // (CURSOR_AGENT, CLAUDECODE, …) or CI in the environment, and drops
341 // colors under NO_COLOR; the demo is about the TUI, so force both on
342 // regardless of who launched tcut.
343 await t.run(
344 "unset CI CURSOR_AGENT CLAUDECODE CLAUDE_CODE NO_COLOR FORCE_COLOR; export ALCHEMY_TUI=1",
345 );
346 // tcut's pty has no TERM_PROGRAM, so terminal-capability detection
347 // assumes OSC 8 hyperlinks are unsupported and the CLI falls back to
348 // printing every URL in full after its label (the OAuth URL is ~1KB).
349 // Real terminals (Ghostty, iTerm2, kitty, …) render the link inline.
350 await t.run("export FORCE_HYPERLINK=1");
351 // A previous take may have left a live stack behind: tear it down with
352 // a temporary profile before the home is wiped for the on-camera setup.
353 await t.run(`${connectCloudflare("default")} --no-input`);
354 await t.run("alchemy destroy --yes --no-input >/dev/null 2>&1 || true");
355 // Local state (including the dev stage's emulated resources) and the
356 // demo home start from scratch so every take plays out the same way.
357 const home = JSON.stringify(demoHome);
358 await t.run(`rm -rf .alchemy ${home} && mkdir -p ${home}`);
359 await t.run("clear");
360 });
361
362 // ── 1. Connect to Cloudflare ─────────────────────────────────────────
363 await slide("Connect Cloudflare", "alchemy profile · sign in with OAuth");
364 await t.type("alchemy profile");
365 await t.enter();
366 await t.wait(/e edit/, { scope: "screen" });
367 await caption("A fresh machine: one empty profile, no providers connected yet");
368 await t.sleep("2.5s");
369
370 // Nothing is connected yet — add Cloudflare from the edit screen.
371 await caption("e edits the profile — space marks a provider to add");
372 await t.type("e");
373 await t.wait(/esc back/, { scope: "screen" });
374 await t.sleep("2s");
375 await t.down(2);
376 await t.sleep("600ms");
377 await t.type(" ");
378 await t.wait(/Cloudflare\s+add/, { scope: "screen" });
379 await t.sleep("1.2s");
380 await t.enter();
381
382 // OAuth (the recommended method), basic scopes.
383 await t.wait(/Cloudflare authentication method/, { scope: "screen" });
384 await caption("OAuth is the recommended method — no API token to paste");
385 await t.sleep("2s");
386 await t.enter();
387 await t.wait(/Cloudflare OAuth scopes/, { scope: "screen" });
388 await caption("Pick the scopes the token should have");
389 await t.sleep("1.5s");
390 await t.down();
391 await t.sleep("600ms");
392 await t.enter();
393
394 // The CLI hands the grant URL to `open` — our shim catches it and the
395 // grant happens in the browser pane, exactly as it would in a real tab.
396 await t.wait(/waiting for browser authorization/, { scope: "screen" });
397 await caption("The CLI opens Cloudflare's consent page in the browser");
398 const oauthUrl = await waitForOAuthUrl().catch((error) => {
399 throw new Error(`${error.message}\n--- screen ---\n${t.screen()}`);
400 });
401 await t.sleep("2s");
402 await caption("Sign in and authorize — the grant is handed back to the CLI");
403 await t.browser.goto(oauthUrl);
404 await t.focus("browser");
405 const consentPage = /Select account\(s\)|Authorize/i;
406 await t.browser.waitFor(new RegExp(`Sign in to Cloudflare|${consentPage.source}`, "i"), {
407 timeout: "60s",
408 });
409 const pageText = async () =>
410 String(await t.browser.evaluate("document.body.innerText").catch(() => ""));
411 if (/Sign in to Cloudflare/i.test(await pageText())) {
412 if (login.email && login.password) {
413 // The form is React-controlled and re-renders while it hydrates and
414 // while Turnstile runs, so a fill can be dropped: verify the inputs
415 // hold our values and the challenge token exists before submitting,
416 // and retry if Cloudflare rejects a half-filled submission.
417 for (let attempt = 1; attempt <= 3; attempt++) {
418 await t.sleep("1.5s");
419 for (let i = 0; i < 10; i++) {
420 await t.browser.evaluate(signInScript(login.email, login.password));
421 await t.sleep("400ms");
422 if (
423 (await t.browser.evaluate(signInFilledScript(login.email, login.password))) === true
424 )
425 break;
426 }
427 let turnstile = false;
428 for (let i = 0; i < 60 && !turnstile; i++) {
429 turnstile = (await t.browser.evaluate(turnstileReadyScript)) === true;
430 if (!turnstile) await t.sleep("500ms");
431 }
432 if (!turnstile) console.error("turnstile token never appeared; submitting anyway");
433 await t.sleep("500ms");
434 await t.browser.click('[data-testid="login-submit-button"]');
435 let rejected = false;
436 for (let i = 0; i < 40; i++) {
437 await t.sleep("500ms");
438 const text = await pageText();
439 if (/Incorrect email or password/i.test(text)) {
440 rejected = true;
441 break;
442 }
443 if (text.trim() !== "" && !/Sign in to Cloudflare/i.test(text)) break;
444 }
445 if (!rejected) break;
446 console.error(
447 `cloudflare rejected the sign-in (attempt ${attempt}); retrying`,
448 `\n url: ${t.browser.url}`,
449 `\n hidden inputs: ${await t.browser.evaluate(
450 `JSON.stringify([...document.querySelectorAll("input[type=hidden]")].map((i) => [i.name, i.value.length]))`,
451 )}`,
452 `\n page: ${(await pageText()).replace(/\s+/g, " ").slice(0, 400)}`,
453 );
454 }
455 }
456 // Either the credentials just submitted, or a human signs in now.
457 await t.browser.waitFor(consentPage, { timeout: "240s" });
458 }
459 // Cloudflare's consent has two steps when the login can see several
460 // accounts: pick the account the grant covers, review the permissions,
461 // then authorize. With a single account it opens on the review step.
462 if (/Select account\(s\)/i.test(await pageText())) {
463 await t.sleep("2s");
464 await t.browser.evaluate(clickButtonScript(accountButtonPattern));
465 await t.sleep("1.2s");
466 await t.browser.evaluate(clickButtonScript(/^Review permissions$/i));
467 await t.browser.waitFor(/^Authorize$/im, { timeout: "60s" });
468 }
469 await t.sleep("2.5s");
470 await t.browser.evaluate(clickButtonScript(/^Authorize$/i));
471 // Cloudflare redirects to alchemy.run/auth/callback, which relays the
472 // code to the CLI's localhost listener and lands on the success page.
473 // The relay pings localhost with a cross-scheme fetch first; when the
474 // embedded browser refuses that, the page offers a plain link to the
475 // local callback instead — take it.
476 await t.browser.waitFor(
477 /Authentication Complete|Authentication Error|Couldn't connect to your local|Cloudflare did not authorize/i,
478 { timeout: "60s" },
479 );
480 if (/Couldn't connect to your local/i.test(await pageText())) {
481 await t.browser.click("#relay-local");
482 await t.browser.waitFor(/Authentication Complete|Authentication Error/i, {
483 timeout: "60s",
484 });
485 }
486 await t.sleep("2s");
487 await t.focus("terminal");
488
489 // Back in the terminal the callback has landed and the account is bound.
490 await t.wait(/Cloudflare added|Select a Cloudflare account/, {
491 scope: "screen",
492 });
493 if (/Select a Cloudflare account/.test(t.screen())) {
494 await caption("The login can see several accounts — pick the one this profile is for");
495 await t.sleep("1.5s");
496 // Arrow down to the configured account (the focused row starts with
497 // ❯) instead of typing into the filter; the first row is the default.
498 const wanted = env("CLOUDFLARE_ACCOUNT_NAME") ?? process.env.CLOUDFLARE_ACCOUNT_ID;
499 const focused = () =>
500 t
501 .screen()
502 .split("\n")
503 .find((line) => /^\s*❯/.test(line)) ?? "";
504 for (let i = 0; i < 8 && wanted && !focused().includes(wanted); i++) {
505 await t.down();
506 await t.sleep("400ms");
507 }
508 await t.sleep("600ms");
509 await t.enter();
510 await t.wait(/Cloudflare added/, { scope: "screen" });
511 }
512 // Hold on the dashboard: one profile, one connected provider.
513 await caption(
514 "Connected — auth method, token expiry and account id, stored under ~/.alchemy/profiles",
515 );
516 await t.sleep("3.5s");
517 await t.type("q");
518 await t.wait();
519 await t.sleep("1s");
520
521 // ── 2. Launch alchemy dev ────────────────────────────────────────────
522 await slide("Launch alchemy dev", "local emulation · plan view · live reload");
523 await t.type("alchemy dev");
524 await t.enter();
525 await t.wait(STARTED, { scope: "screen" });
526 await caption("The Worker, KV and R2 all run locally — the widget shows the stack's outputs");
527 await t.sleep("2s");
528
529 // The widget opens on the stack's output; ←/→ flips it to the plan
530 // that was just applied. Show the plan — three local resources, all
531 // created — then come back to the output.
532 const showDevPlan = async (pattern: RegExp, text: string) => {
533 await caption("→ flips the widget to the plan that was just applied");
534 await t.sleep("1s");
535 await t.right();
536 await t.wait(/show output/, { scope: "screen" });
537 await t.expect(pattern, { scope: "screen" });
538 await caption(text);
539 await t.sleep("4s");
540 await caption("← back to the outputs");
541 await t.sleep("800ms");
542 await t.left();
543 await t.wait(/show plan/, { scope: "screen" });
544 await t.sleep("1.5s");
545 };
546 await showDevPlan(
547 /Cloudflare\.KV\.Namespace\).*created/,
548 "Three resources created, all emulated locally",
549 );
550
551 // Hit the local worker in a browser — at the URL the CLI actually
552 // printed, never a guess (another dev server may own the default port).
553 const devUrl = t.screen().match(STARTED)?.[1];
554 if (devUrl === undefined) {
555 throw new Error("local dev URL not found in the terminal output");
556 }
557 await caption("Open the local URL");
558 await t.sleep("800ms");
559 await t.browser.goto(devUrl);
560 await t.focus("browser");
561 await t.sleep("3s");
562 await t.focus("terminal");
563 await t.sleep("1s");
564
565 // Change the greeting while dev is running — the stack reloads and the
566 // worker restarts.
567 await caption(
568 "Editing src/Api.ts while dev runs — the stack reloads and the Worker restarts",
569 );
570 await t.sleep("1.2s");
571 writeFileSync(
572 apiFile,
573 originalApi.replace(
574 'const GREETING = "Hello from Alchemy";',
575 'const GREETING = "Hello from alchemy dev";',
576 ),
577 );
578 await t.wait(/restarting instance/, { scope: "screen" });
579 await t.wait(/Started in \d+ms[^]*Started in \d+ms/, {
580 scope: "screen",
581 });
582 if (!t.screen().split("Started in").pop()!.includes(devUrl)) {
583 throw new Error("worker restarted on a different URL");
584 }
585 await t.sleep("1.5s");
586 // The reload's plan: only the Worker changed, KV and R2 untouched.
587 await showDevPlan(
588 /Cloudflare\.Worker\)/,
589 "Only the Worker was updated — KV and R2 untouched",
590 );
591
592 await caption("Reload the page: the new greeting");
593 await t.sleep("800ms");
594 await t.browser.reload();
595 await t.focus("browser");
596 await t.sleep("3s");
597 await t.focus("terminal");
598 await t.sleep("1.5s");
599
600 // alchemy dev parks forever — Ctrl+C shuts it down.
601 await caption("Ctrl+C stops dev and tears the local resources down");
602 await t.sleep("800ms");
603 await t.ctrl("c");
604 await t.wait();
605 // Put the source back so the deploy ships the original greeting.
606 writeFileSync(apiFile, originalApi);
607 await t.sleep("1s");
608
609 // ── 3. Deploy to the cloud ───────────────────────────────────────────
610 await slide("Deploy to the cloud", "alchemy deploy · review the plan · confirm");
611 await t.type("alchemy deploy");
612 await t.enter();
613 await t.wait(/Deploy\?/, { scope: "screen" });
614 await caption(
615 "The same stack, now against the real Cloudflare account — review the plan, Enter to confirm",
616 );
617 await t.sleep("3.5s");
618 await t.enter();
619 await caption("Creating the Worker, the KV namespace and the R2 bucket for real");
620 await t.wait();
621 await t.expect(/Stack deployed/, { scope: "scrollback" });
622 await caption("Deployed — the outputs are the live workers.dev URL and the bucket name");
623 await t.sleep("2.5s");
624
625 const url = t.scrollback().match(/https:\/\/[a-z0-9.-]+\.workers\.dev/)?.[0];
626 if (url === undefined) {
627 throw new Error("deployed URL not found in the terminal output");
628 }
629 // A fresh workers.dev subdomain takes a few seconds to start serving
630 // (Cloudflare error 1042 until then). Poll from the script — not the
631 // recorded shell — on a route that leaves the visit counter alone, so
632 // the visible curls read 1 and 2.
633 await waitForWorker(`${url}/favicon.ico`);
634 await caption("Hit the live Worker — the visit counter is backed by KV");
635 await t.run(`curl -s ${url}`);
636 await t.expect(/"visits":1/);
637 await t.sleep("1s");
638 await t.run(`curl -s ${url}`);
639 await t.expect(/"visits":2/);
640 await t.sleep("2s");
641
642 // ── 4. Detect and repair drift ───────────────────────────────────────
643 // Off camera, "someone" renames the KV namespace in the dashboard.
644 const visits = deployedVisitsNamespace();
645 const visitsApi = kvNamespaceApi(credentials, visits.namespaceId);
646 await visitsApi.rename("renamed-in-the-dashboard");
647 await slide(
648 "Detect and repair drift",
649 "alchemy drift · a namespace renamed in the dashboard",
650 );
651 await caption("Meanwhile, someone renamed the KV namespace in the Cloudflare dashboard…");
652 await t.sleep("2.5s");
653 await t.type("alchemy drift");
654 await t.enter();
655 await t.wait(/Drift detected/, { scope: "screen" });
656 await t.expect(/renamed-in-the-dashboard/, { scope: "screen" });
657 await caption("drift re-reads the cloud and diffs it against the stack: the title changed");
658 await t.sleep("4s");
659 // Cancel is preselected; ← moves to Repair.
660 await caption("Repair puts the resource back the way the code declares it");
661 await t.left();
662 await t.sleep("1s");
663 await t.enter();
664 await caption("Applying the repair");
665 await t.wait();
666 await t.expect(/Stack deployed/, { scope: "screen" });
667 await caption("Repaired — one update, nothing else touched");
668 await t.sleep("2.5s");
669 if ((await visitsApi.title()) !== visits.title) {
670 throw new Error("drift repair did not restore the namespace title");
671 }
672
673 // ── 5. Tear down ─────────────────────────────────────────────────────
674 await slide("Tear it down", "alchemy destroy");
675 await t.type("alchemy destroy");
676 await t.enter();
677 await t.wait(/Destroy\?/, { scope: "screen" });
678 await caption("destroy shows everything it is about to delete before asking");
679 await t.sleep("2.5s");
680 await t.type("y");
681 await caption("Deleting the Worker, the KV namespace and the R2 bucket");
682 await t.wait();
683 await t.expect(/Stack destroyed/, { scope: "scrollback" });
684 await caption("All gone — the account is back to where it started");
685 await t.sleep("2s");
686 } finally {
687 writeFileSync(apiFile, originalApi);
688 rmSync(envFile, { force: true });
689 rmSync(shimDir, { recursive: true, force: true });
690 }
691 },
692 );