@ultimat3/cli 31.0.0 → 31.2.0

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 (49) hide show
  1. package/CLAUDE.md +6 -1
  2. package/package.json +29 -29
  3. package/src/affected-base.ts +51 -0
  4. package/src/affected.ts +29 -10
  5. package/src/binding-names.ts +124 -0
  6. package/src/browser-transport.ts +28 -0
  7. package/src/ci-log.ts +76 -13
  8. package/src/cmd-affected-spec.ts +7 -3
  9. package/src/cmd-affected.ts +91 -77
  10. package/src/cmd-ci.ts +6 -3
  11. package/src/cmd-doctor.ts +8 -0
  12. package/src/cmd-exercise.ts +13 -1
  13. package/src/cmd-pr-spec.ts +1 -1
  14. package/src/cmd-pr.ts +72 -1
  15. package/src/cmd-shot.ts +13 -271
  16. package/src/cmd-test-spec.ts +2 -2
  17. package/src/cmd-upgrade.ts +28 -4
  18. package/src/cmd-verify-spec.ts +2 -2
  19. package/src/doctor-typescript.ts +31 -0
  20. package/src/error-codes-package.ts +38 -0
  21. package/src/error-codes.ts +7 -21
  22. package/src/mcp-errors-shot.ts +49 -0
  23. package/src/mcp-errors.ts +7 -41
  24. package/src/measure-scope.ts +17 -4
  25. package/src/messages-gate.ts +6 -0
  26. package/src/messages-upgrade.ts +2 -0
  27. package/src/offline-ports.ts +106 -0
  28. package/src/output.ts +21 -3
  29. package/src/pr-activity.ts +150 -0
  30. package/src/pr-bots.ts +109 -0
  31. package/src/pr-threads.ts +7 -2
  32. package/src/prerender.ts +2 -2
  33. package/src/runtime-storage-boot.ts +41 -7
  34. package/src/shot-gpu.ts +61 -0
  35. package/src/shot-route.ts +95 -0
  36. package/src/shot-run.ts +189 -0
  37. package/src/shot-verdict.ts +5 -0
  38. package/src/templates/scaffold-repo.ts +2 -1
  39. package/src/templates/sign-in-oidc.ts +24 -9
  40. package/src/transport-calls.ts +7 -3
  41. package/src/transport-values.ts +59 -0
  42. package/src/tsconfig-aliases.ts +85 -0
  43. package/src/typescript-floor.ts +83 -0
  44. package/src/upgrade-report.ts +8 -1
  45. package/src/verify-changed-scope.ts +3 -2
  46. package/src/verify-checks.ts +2 -0
  47. package/src/workspace-external-deps.ts +164 -0
  48. package/wiki/CLI-Reference.md +12 -8
  49. package/wiki/Upgrading.md +24 -5
@@ -1,13 +1,19 @@
1
1
  // Single responsibility: the storage disk a boot installs — s3 when `S3_ENDPOINT` names one, the
2
- // embedded local disk otherwise — and the two refusals that must come before the first upload
3
- // rather than after it. Split from `runtime-services.ts` at its 500-line ceiling.
2
+ // embedded local disk otherwise, NONE when the app already declared its own — and the two refusals
3
+ // that must come before the first upload rather than after it. Split from `runtime-services.ts`.
4
4
 
5
5
  // why: Bun has no `mkdir`; the embedded root must exist before the disk is handed out.
6
6
  import { mkdirSync } from 'node:fs';
7
7
  import { isLocal, renderThrowable, resolveEnvironment } from '@ultimat3/core';
8
8
  import { configuredHttp, defineHttpConfig } from '@ultimat3/http';
9
- import type { Storage } from '@ultimat3/storage';
10
- import { defineStorage, localDriver, s3Driver, usesDevStorageSecret } from '@ultimat3/storage';
9
+ import type { Storage, StorageConfig } from '@ultimat3/storage';
10
+ import {
11
+ definedStorage,
12
+ defineStorage,
13
+ localDriver,
14
+ s3Driver,
15
+ usesDevStorageSecret,
16
+ } from '@ultimat3/storage';
11
17
  import type { StorageDriver } from '@ultimat3/storage/adapter';
12
18
  import { LocalDiskUnsafeError, StorageUnwritableError } from './errors';
13
19
  import type { DevServices, Env } from './runtime-bindings';
@@ -15,6 +21,30 @@ import { s3PathStyleOf } from './runtime-s3-path-style';
15
21
 
16
22
  const FILE_SCHEME = 'file://';
17
23
 
24
+ /**
25
+ * Every registry a boot in this process installed. `definedStorage()` holding one of these is a
26
+ * previous boot's default (a second `startServices` in one process), replaced; holding anything
27
+ * else is the app's own `defineStorage()`, kept.
28
+ */
29
+ const bootInstalled = new WeakSet<Storage>();
30
+
31
+ function bootDefine(config: StorageConfig): Storage {
32
+ const installed = defineStorage(config);
33
+ bootInstalled.add(installed);
34
+ return installed;
35
+ }
36
+
37
+ /**
38
+ * The registry an app module declared before this boot ran, or `undefined`. `runtime.ts` is
39
+ * imported before `startServices`, and an app module it reaches that calls
40
+ * `defineStorage({ disks: { uploads, evidence } })` has already run: the boot's one-disk
41
+ * `defineStorage` replaced it, and every disk but the boot's was `X_STORAGE_DISK_UNKNOWN`.
42
+ */
43
+ function appDeclared(): Storage | undefined {
44
+ const current = definedStorage();
45
+ return current === undefined || bootInstalled.has(current) ? undefined : current;
46
+ }
47
+
18
48
  /**
19
49
  * The most one request to this server carries — `http.maxRequestBodyBytes` as the server resolves
20
50
  * it, read at each signing because the boot builds its disk before the app's `configureHttp` runs.
@@ -39,11 +69,15 @@ export const servedRequestCeiling = (): number =>
39
69
  * to run a container, so this reports what to do instead of what went wrong.
40
70
  */
41
71
  export function startStorage(services: DevServices, env: Env, override?: StorageDriver): Storage {
72
+ // Before every arm, the override included: "several disks are the app's `defineStorage()`, which
73
+ // wins" (`PortValues.storage`). The app's disks carry their own refusals (`localDriver`'s).
74
+ const declared = appDeclared();
75
+ if (declared !== undefined) return declared;
42
76
  // First arm, not a branch beside the two below: `runtime.ts` handing the boot a driver has
43
77
  // already answered "which disk", and re-deriving one from `S3_ENDPOINT` would be a second answer.
44
78
  // Registered under the driver's own name — its signed URLs hang off that key (`defineStorage`).
45
79
  if (override !== undefined) {
46
- return defineStorage({ disks: { [override.name]: override }, default: override.name });
80
+ return bootDefine({ disks: { [override.name]: override }, default: override.name });
47
81
  }
48
82
  const binding = services.storage;
49
83
 
@@ -55,7 +89,7 @@ export function startStorage(services: DevServices, env: Env, override?: Storage
55
89
  'set S3_BUCKET to the bucket name, or unset S3_ENDPOINT to use the embedded disk',
56
90
  );
57
91
  }
58
- return defineStorage({
92
+ return bootDefine({
59
93
  disks: {
60
94
  object: s3Driver({
61
95
  bucket,
@@ -107,5 +141,5 @@ export function startStorage(services: DevServices, env: Env, override?: Storage
107
141
  // `maxRequestBytes`: a signed PUT lands on THIS server, so a grant it could never accept in one
108
142
  // request is refused at signing, naming the multipart grant.
109
143
  const disk = localDriver({ root, env, maxRequestBytes: servedRequestCeiling });
110
- return defineStorage({ disks: { local: disk }, default: 'local' });
144
+ return bootDefine({ disks: { local: disk }, default: 'local' });
111
145
  }
@@ -0,0 +1,61 @@
1
+ // The GPU backend the photographed page could reach, read from `navigator.gpu` inside the page.
2
+ // A WebGPU canvas that came out blank on a headless machine with no adapter is a fact about the
3
+ // machine, not the app — and a picture alone cannot tell the two apart. Recorded, never gating.
4
+
5
+ import type { StandardSchemaV1 } from '@ultimat3/schema';
6
+ import { t, validate } from '@ultimat3/schema';
7
+ import type { JsonValue } from './output';
8
+
9
+ export interface ShotGpu {
10
+ /** `navigator.gpu` exists — the browser exposes WebGPU at all. */
11
+ readonly api: boolean;
12
+ /** `requestAdapter()` answered an adapter: WebGPU is usable on this page, on this machine. */
13
+ readonly available: boolean;
14
+ /** The adapter's `info` (vendor, architecture, device, description), or `null` with none. */
15
+ readonly adapter: string | null;
16
+ /** A software adapter (SwiftShader and kin): it renders, at a speed no user sees. */
17
+ readonly fallback: boolean;
18
+ }
19
+
20
+ /**
21
+ * An expression, never a closure: `CdpPageLike.evaluate` takes the string form and awaits the
22
+ * promise. `requestAdapter()` is raced against a bound so a browser that never answers cannot
23
+ * hold a capture whose picture is already taken. `adapter.info` is current Chrome; older ones
24
+ * spell the flag `isFallbackAdapter` on the adapter, which is why both are read.
25
+ */
26
+ export const GPU_PROBE =
27
+ '(async function(){var g=navigator.gpu;' +
28
+ 'if(!g)return{api:false,available:false,adapter:null,fallback:false};var a=null;' +
29
+ 'try{a=await Promise.race([g.requestAdapter(),' +
30
+ 'new Promise(function(r){setTimeout(function(){r(null);},2000);})]);}catch(e){a=null;}' +
31
+ 'if(!a)return{api:true,available:false,adapter:null,fallback:false};var i=a.info||{};' +
32
+ 'var n=[i.vendor,i.architecture,i.device,i.description].filter(function(s){return !!s;})' +
33
+ '.join(" ");return{api:true,available:true,adapter:n===""?null:n,' +
34
+ 'fallback:!!(a.isFallbackAdapter||i.isFallbackAdapter)};})()';
35
+
36
+ const gpuProbeSchema: StandardSchemaV1<unknown, ShotGpu> = t.object({
37
+ api: t.boolean,
38
+ available: t.boolean,
39
+ adapter: t.nullable(t.string),
40
+ fallback: t.boolean,
41
+ }) as unknown as StandardSchemaV1<unknown, ShotGpu>;
42
+
43
+ /** Parsed, never cast: a page can answer anything. `null` for a shape that does not fit. */
44
+ export function parseGpuProbe(value: unknown): ShotGpu | null {
45
+ const result = validate(gpuProbeSchema, value);
46
+ return result.issues === undefined ? result.value : null;
47
+ }
48
+
49
+ /** `null` when the page refused the probe — "not read" is never reported as "no GPU". */
50
+ export const readShotGpu = (page: {
51
+ evaluate(expression: string): Promise<unknown>;
52
+ }): Promise<ShotGpu | null> =>
53
+ page
54
+ .evaluate(GPU_PROBE)
55
+ .then(parseGpuProbe)
56
+ .catch(() => null);
57
+
58
+ export const gpuJson = (gpu: ShotGpu | null | undefined): JsonValue =>
59
+ gpu === null || gpu === undefined
60
+ ? null
61
+ : { api: gpu.api, available: gpu.available, adapter: gpu.adapter, fallback: gpu.fallback };
@@ -0,0 +1,95 @@
1
+ // `x shot`'s subject: the one route argument read and refused before anything boots, and the
2
+ // directory name a route photographs into. A path on the app, never a URL — the SSRF shape
3
+ // `allowHosts` exists to refuse is refused here, at the argument, where the reader can see why.
4
+
5
+ import { BadFlagError, MissingPositionalError } from './errors';
6
+
7
+ /** A directory name a route can never escape: everything that is not a letter or digit is a dash. */
8
+ export function shotSlug(route: string): string {
9
+ const slug = route.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');
10
+ return slug === '' ? 'root' : slug.toLowerCase();
11
+ }
12
+
13
+ const pathOf = (url: string): string => {
14
+ try {
15
+ return new URL(url).pathname;
16
+ } catch {
17
+ return '/';
18
+ }
19
+ };
20
+
21
+ /**
22
+ * A reserved name (RFC 2606) that resolves nowhere, so the origin check below can never be
23
+ * satisfied by an accident of what the app's own host happens to be.
24
+ */
25
+ const ROUTE_BASE = 'http://route.invalid';
26
+
27
+ /**
28
+ * Where a browser would actually go. The refusal above reads `scheme:` and nothing else, and this
29
+ * is the question it was standing in for: a path is a path only if resolving it lands back on the
30
+ * origin it was resolved against.
31
+ */
32
+ const resolvedOrigin = (path: string): string => {
33
+ try {
34
+ return new URL(path, ROUTE_BASE).origin;
35
+ } catch {
36
+ // A path `new URL` will not parse is one no browser will fetch either, and reporting it as the
37
+ // origin it is not is the honest answer here.
38
+ return '';
39
+ }
40
+ };
41
+
42
+ const refuseRoute = (reason: string): never => {
43
+ throw new BadFlagError({
44
+ flag: 'route',
45
+ command: 'shot',
46
+ reason,
47
+ // A placeholder, because there is nothing safe to substitute: unlike an absolute URL, an
48
+ // origin-escaping route carries no path the caller can be assumed to have meant.
49
+ fix: 'x shot /<path> --json',
50
+ });
51
+ };
52
+
53
+ /**
54
+ * A path on the app, never a URL. `x shot https://example.com` would photograph somebody else's
55
+ * site through a headless browser inside your network, which is the SSRF shape `allowHosts` exists
56
+ * to refuse — so it is refused here, at the argument, where the reader can still see why.
57
+ *
58
+ * `scheme:` was the ONLY spelling refused until 2026-08-22, and it is one of four: `//evil/x` is a
59
+ * protocol-relative URL, `\evil\x` is the same thing to every URL parser (a backslash IS a slash
60
+ * for a special scheme), and a TAB inside the path is deleted by the parser before the host is
61
+ * read, so `/⇥/evil/x` becomes `//evil/x`. Each one reached `new URL(route, server.url)` and came
62
+ * back pointed at another host. `allowHostsFrom` one layer down could not catch any of them: it
63
+ * allows a HOSTNAME, and the hostname it is given is the one the page has already left — which is
64
+ * how `x shot //localhost:9200/_cat/indices` photographed whatever else was on the dev box.
65
+ */
66
+ export function readRoute(raw: string | undefined): string {
67
+ if (raw === undefined || raw.trim() === '') {
68
+ throw new MissingPositionalError({ command: 'shot', positional: 'route', example: 'x shot /' });
69
+ }
70
+ const route = raw.trim();
71
+ if (/^[a-z][a-z0-9+.-]*:/i.test(route)) {
72
+ throw new BadFlagError({
73
+ flag: 'route',
74
+ command: 'shot',
75
+ reason: `"${route}" is an absolute URL; x shot photographs a route of the app under test`,
76
+ // The path out of the URL when it parses — the refusal's own fix line has to be runnable,
77
+ // and `new URL('http://')` throws, so the fallback is the route every app has.
78
+ fix: `x shot ${pathOf(route)} --json`,
79
+ });
80
+ }
81
+ const path = route.startsWith('/') ? route : `/${route}`;
82
+ // Its own refusal rather than folded into the origin check: `/a\b` stays on this origin and is
83
+ // still not the route that was typed — the verdict would record `/a\b` beside a picture of
84
+ // `/a/b`, which is the artifact lying about its own subject.
85
+ if (path.includes('\\')) {
86
+ return refuseRoute(`"${route}" contains a backslash, which a URL parser reads as "/"`);
87
+ }
88
+ const origin = resolvedOrigin(path);
89
+ if (origin !== ROUTE_BASE) {
90
+ return refuseRoute(
91
+ `"${route}" is not a path on the app: a browser resolves it to ${origin === '' ? 'no URL at all' : origin}`,
92
+ );
93
+ }
94
+ return path;
95
+ }
@@ -0,0 +1,189 @@
1
+ // One route photographed: boot (or find) the server, drive the page, settle the islands, take the
2
+ // picture and write `shot.png` beside the `verdict.json` that gates. The driver and the boot are
3
+ // arguments, so `bun test` proves the whole capture with no Chrome.
4
+
5
+ import { mkdirSync } from 'node:fs'; // why: Bun has no recursive directory create.
6
+ import { join } from 'node:path'; // why: Bun exposes no path-join primitive.
7
+ import { systemClock } from '@ultimat3/core/adapter';
8
+ import type { ShotColorScheme, ShotDriver, ShotPage, ShotSession } from './browser-launcher-port';
9
+ import { type ShotCookiePair, shotCookies } from './shot-cookie';
10
+ import { readShotGpu } from './shot-gpu';
11
+ import { acceptLanguageHeaders } from './shot-locale';
12
+ import type { ShotServer } from './shot-server';
13
+ import { allowHostsFrom } from './shot-server';
14
+ import { SETTLE_POLL_MS, settleIslands } from './shot-settle';
15
+ import { themeChoiceExpression } from './shot-theme';
16
+ import type { IslandCount, ShotArtifacts } from './shot-verdict';
17
+ import {
18
+ buildVerdict,
19
+ documentStatus,
20
+ ISLAND_PROBE,
21
+ parseIslandProbe,
22
+ verdictJson,
23
+ } from './shot-verdict';
24
+
25
+ export const SHOT_IMAGE = 'shot.png';
26
+ export const SHOT_VERDICT = 'verdict.json';
27
+
28
+ export interface ShotRun {
29
+ readonly route: string;
30
+ readonly outDir: string;
31
+ readonly driver: ShotDriver;
32
+ readonly boot: () => Promise<ShotServer>;
33
+ readonly settleMs: number;
34
+ readonly timeoutMs: number;
35
+ readonly fullPage: boolean;
36
+ /**
37
+ * `--allow-hosts`, verbatim. The app's own host is added once the server is up and never here:
38
+ * with `--port 0` the port — and therefore the origin — does not exist until after the boot.
39
+ */
40
+ readonly extraHosts?: string | undefined;
41
+ /**
42
+ * The theme the picture is of. Two things happen BEFORE navigation, because the boot script runs
43
+ * inline and nothing after `goto` can reach it: `prefers-color-scheme` is emulated so the boot's
44
+ * "system" branch answers the same on every box, AND the scheme is stored as the visitor's
45
+ * choice under `THEME_STORAGE_KEY` (`shot-theme.ts`), because an app with `theme.defaultMode`
46
+ * set answers that before the OS and only a stored choice beats it (issue #489). Absent means
47
+ * neither: the box's own preference and the app's own default — what `x shot` has always done,
48
+ * and the point of `defaultMode` — and `ui.shot` names one explicitly for exactly that reason.
49
+ */
50
+ readonly colorScheme?: ShotColorScheme | undefined;
51
+ /** CSS pixels the page is laid out in; absent is the driver's default. */
52
+ readonly viewport?: { readonly width: number; readonly height: number } | undefined;
53
+ /**
54
+ * Sent as `Accept-Language` on every request. The command always sets it — `--locale`, or the
55
+ * app's default locale — so a picture never depends on the language of the machine's Chrome.
56
+ */
57
+ readonly acceptLanguage?: string | undefined;
58
+ /**
59
+ * `--cookie`: set before the first navigation, each for the server's own URL once it is up —
60
+ * so a consent banner (or any cookie-held choice) is decided in the picture.
61
+ */
62
+ readonly cookies?: readonly ShotCookiePair[] | undefined;
63
+ readonly now?: (() => Date) | undefined;
64
+ /**
65
+ * `--expect-status`: the document status this shot is ok with — `404` to photograph the not-found
66
+ * page on purpose. Absent means any 2xx, and anything else fails the verdict with the status.
67
+ */
68
+ readonly expectStatus?: number | undefined;
69
+ /**
70
+ * Something to do with the page AFTER the islands settled and BEFORE the picture — `ui.inspect`
71
+ * reads the DOM here, on the one navigation the picture already paid for. `settle` re-runs the
72
+ * island poll (an action that mounts something changes the count the verdict reports); the
73
+ * caller who never calls it gets the count from the first settle.
74
+ */
75
+ readonly act?:
76
+ | ((page: ShotPage, settle: () => Promise<IslandCount | null>) => Promise<void>)
77
+ | undefined;
78
+ /**
79
+ * The clock the settle window runs on — the same seam `SettleOptions.sleep` and
80
+ * `InteractDeps.sleep` take, and the reason they had none on this path: `settleMs` was a
81
+ * `Bun.sleep` here, so a caller that injected a sleep everywhere else still paid the real
82
+ * 2000 ms window in wall time once per `runShot`, and a test doing it twice raced its own
83
+ * per-test timeout on a slower box. Absent is `Bun.sleep`: production waits for real.
84
+ */
85
+ readonly sleep?: ((ms: number) => Promise<void>) | undefined;
86
+ }
87
+
88
+ /** Nothing here may replace the failure that caused it, so a teardown throw is swallowed. */
89
+ const quietly = async (stop: () => Promise<void>): Promise<void> => {
90
+ await stop().catch(() => undefined);
91
+ };
92
+
93
+ /**
94
+ * Boot (or find) the server, photograph one route, write both artifacts. The driver and the boot
95
+ * are ARGUMENTS: `bun test` drives this with `fakeBrowser()` and a stub server, so the whole
96
+ * command is proved on a machine with no Chrome — which this command is explicitly excluded from
97
+ * the gate for needing.
98
+ */
99
+ export async function runShot(options: ShotRun): Promise<ShotArtifacts> {
100
+ const server = await options.boot();
101
+ const sleep = options.sleep ?? ((ms: number): Promise<void> => Bun.sleep(ms));
102
+ let session: ShotSession | undefined;
103
+ try {
104
+ const requestedUrl = new URL(options.route, server.url).toString();
105
+ session = await options.driver.open({
106
+ name: 'x shot',
107
+ // The host the picture is of, plus whatever the caller named. Never `*`: a headless browser
108
+ // inside your network is the widest SSRF surface an app can own, and a screenshot command is
109
+ // not the place to open it by default. Every refusal lands in the verdict's `refused` count.
110
+ rules: { allowHosts: allowHostsFrom(server.url, options.extraHosts) },
111
+ clock: systemClock,
112
+ timeoutMs: options.timeoutMs,
113
+ ...(options.viewport === undefined ? {} : { viewport: options.viewport }),
114
+ ...(options.acceptLanguage === undefined
115
+ ? {}
116
+ : { headers: acceptLanguageHeaders(options.acceptLanguage) }),
117
+ ...(options.cookies === undefined || options.cookies.length === 0
118
+ ? {}
119
+ : { cookies: shotCookies(options.cookies, new URL(server.url).toString()) }),
120
+ });
121
+ const page = session.page;
122
+ if (options.colorScheme !== undefined) {
123
+ await page.colorScheme(options.colorScheme);
124
+ const choice = themeChoiceExpression(options.colorScheme);
125
+ if (choice !== undefined) await page.prepare(choice);
126
+ }
127
+ await page.goto(requestedUrl, { timeout: options.timeoutMs });
128
+ // Read NOW as well as at capture: the network ring is bounded, and a page that fires a few
129
+ // hundred requests while it settles evicts the document entry the verdict needs.
130
+ const landedStatus = documentStatus(page.network(), page.url());
131
+ if (options.settleMs > 0) await sleep(options.settleMs);
132
+ // A probe may answer nothing (a page refusing evaluation, a driver with no JS engine): `null`
133
+ // says so, where a `0` would claim "no islands". `gpu` is read the same way, after the picture.
134
+ const probe = (): Promise<IslandCount | null> =>
135
+ page
136
+ .evaluate(ISLAND_PROBE)
137
+ .then(parseIslandProbe)
138
+ .catch(() => null);
139
+ // The same budget again, no new flag: `settleMs` is when the runtime CALLS `import()`, so a
140
+ // mount gets as long to settle as the runtime got to start it; `--settle 0` still gets none.
141
+ const settle = (): Promise<IslandCount | null> =>
142
+ settleIslands(probe, { windowMs: options.settleMs, pollMs: SETTLE_POLL_MS, sleep });
143
+ let islands = await settle();
144
+ if (options.act !== undefined) {
145
+ await options.act(page, async () => {
146
+ islands = await settle();
147
+ return islands;
148
+ });
149
+ }
150
+ const bytes = await page.screenshot({ fullPage: options.fullPage });
151
+ // Read AFTER the capture, so an error logged while the page settled ships with its picture —
152
+ // and copied BEFORE the gpu probe: `requestAdapter()` may take seconds, and a page that
153
+ // redirects meanwhile must not have its new URL or its new logs reported beside the old picture.
154
+ const captured = {
155
+ finalUrl: page.url(),
156
+ capturedAt: (options.now ?? (() => new Date()))().toISOString(),
157
+ console: [...page.console()],
158
+ pageErrors: [...page.pageErrors()],
159
+ pageErrorsDropped: page.pageErrorsDropped(),
160
+ network: [...page.network()],
161
+ networkDropped: page.networkDropped(),
162
+ };
163
+ const gpu = await readShotGpu(page);
164
+ const verdict = buildVerdict({
165
+ route: options.route,
166
+ requestedUrl,
167
+ server: server.origin,
168
+ screenshot: SHOT_IMAGE,
169
+ bytes,
170
+ ...captured,
171
+ islands,
172
+ gpu,
173
+ landedStatus,
174
+ ...(options.expectStatus === undefined ? {} : { expectStatus: options.expectStatus }),
175
+ });
176
+ mkdirSync(options.outDir, { recursive: true });
177
+ const image = join(options.outDir, SHOT_IMAGE);
178
+ const verdictFile = join(options.outDir, SHOT_VERDICT);
179
+ await Bun.write(image, bytes);
180
+ await Bun.write(verdictFile, `${JSON.stringify(verdictJson(verdict), null, 2)}\n`);
181
+ return { verdict, image, verdictFile };
182
+ } finally {
183
+ // Bound to a const: narrowing a `let` does not survive into the closure below, and the session
184
+ // has to be closed from inside one so a teardown throw cannot replace the real failure.
185
+ const open = session;
186
+ if (open !== undefined) await quietly(() => open.close());
187
+ await quietly(() => server.stop());
188
+ }
189
+ }
@@ -9,6 +9,8 @@ import { t, validate } from '@ultimat3/schema';
9
9
  import type { ConsoleLine, NetworkEntry, PageError } from './browser-launcher-port';
10
10
  import { msg } from './messages';
11
11
  import type { JsonValue } from './output';
12
+ import type { ShotGpu } from './shot-gpu';
13
+ import { gpuJson } from './shot-gpu';
12
14
 
13
15
  /**
14
16
  * The one expression that counts islands, and it counts TWO different facts because they are two
@@ -156,6 +158,8 @@ export interface ShotInput {
156
158
  readonly landedStatus?: number | null | undefined;
157
159
  /** `--expect-status`: the one status this shot is ok with. Absent means any 2xx. */
158
160
  readonly expectStatus?: number | undefined;
161
+ /** The GPU backend the page could reach (`shot-gpu.ts`); absent or `null` when not read. */
162
+ readonly gpu?: ShotGpu | null | undefined;
159
163
  }
160
164
 
161
165
  export interface ShotVerdict extends ShotInput {
@@ -324,6 +328,7 @@ export function verdictJson(verdict: ShotVerdict): JsonValue {
324
328
  })),
325
329
  },
326
330
  islands: islandJson(verdict.islands),
331
+ gpu: gpuJson(verdict.gpu),
327
332
  network: {
328
333
  requests: verdict.network.length,
329
334
  refused: verdict.refused,
@@ -38,8 +38,9 @@ const BIOME_VERSION = '2.6.3';
38
38
  * constant and TypeScript's was a literal buried in a dependency block, so the framework moved to
39
39
  * 7.x and every `x new` kept scaffolding `^6.0.3`. `scaffold-repo.test.ts` now pins this against
40
40
  * the repo's own root `package.json`, so the next bump cannot leave the scaffold behind in silence.
41
+ * Exported for `typescript-floor.ts`: `x upgrade` and `x doctor` hold an EXISTING app to it.
41
42
  */
42
- const TYPESCRIPT_VERSION = '^7.0.2';
43
+ export const TYPESCRIPT_VERSION = '^7.0.2';
43
44
 
44
45
  /**
45
46
  * The Solid runtime every island and `@ultimat3/ui` component renders with, exact for the reason
@@ -46,6 +46,7 @@ import {
46
46
  defineAuth,
47
47
  discoverOAuthProvider,
48
48
  hasOAuthProvider,
49
+ OAUTH_CALLBACK_ROUTE_PATH,
49
50
  type OAuthLoginRoutes,
50
51
  oauthLogin,
51
52
  oauthStartPath,
@@ -58,6 +59,13 @@ export const OIDC_PROVIDER = '${provider}';
58
59
  export const OIDC_ISSUER_ENV = '${oidcEnvPrefix(provider)}_ISSUER';
59
60
  /** Where the sign-in page sends a browser: the start leg, \`${oauthStartPath(provider)}\`. */
60
61
  export const OIDC_START_PATH = oauthStartPath(OIDC_PROVIDER);
62
+ /**
63
+ * The callback leg's mount AND the \`redirect_uri\` the issuer must have registered: one value,
64
+ * handed to \`oauthLogin({ callbackPath })\` below and mounted by \`sign-in-routes.ts\`. The
65
+ * framework's default; set it (e.g. \`'/auth/oauth/:provider/callback'\`) to keep a URI an IdP
66
+ * already holds, and both move together.
67
+ */
68
+ export const OIDC_CALLBACK_PATH: string = OAUTH_CALLBACK_ROUTE_PATH;
61
69
 
62
70
  type Env = Readonly<Record<string, string | undefined>>;
63
71
 
@@ -77,7 +85,10 @@ export const oidcLegs = (env: Env = process.env): Promise<OAuthLoginRoutes> => {
77
85
  if (!hasOAuthProvider(OIDC_PROVIDER)) {
78
86
  registerOAuthProvider(await discoverOAuthProvider({ id: OIDC_PROVIDER, issuer }));
79
87
  }
80
- return oauthLogin(signInAuth(), { successPath: AFTER_SIGN_IN });
88
+ return oauthLogin(signInAuth(), {
89
+ successPath: AFTER_SIGN_IN,
90
+ callbackPath: OIDC_CALLBACK_PATH,
91
+ });
81
92
  })().catch((error: unknown) => {
82
93
  legs = undefined;
83
94
  throw error;
@@ -111,10 +122,12 @@ unitTest('a discovery that fails is refused, and the next sign-in tries again',
111
122
 
112
123
  const routesSource =
113
124
  (): string => `// The two OIDC legs as plain HTTP routes — \`runtime.ts\` hands them to both boots. Plain routes,
114
- // not actions: the callback is a redirect protocol whose shape the provider fixes.
115
- import { OAUTH_CALLBACK_ROUTE_PATH, OAUTH_START_ROUTE_PATH } from '@ultimat3/auth';
125
+ // not actions: the callback is a redirect protocol whose shape the provider fixes. The callback is
126
+ // mounted at \`OIDC_CALLBACK_PATH\` — the \`callbackPath\` \`oauthLogin\` was handed, so its
127
+ // \`callback.path\` — never at a constant of its own: the mount and the \`redirect_uri\` move together.
128
+ import { OAUTH_START_ROUTE_PATH } from '@ultimat3/auth';
116
129
  import type { Route } from '@ultimat3/http';
117
- import { oidcLegs } from './oidc';
130
+ import { OIDC_CALLBACK_PATH, oidcLegs } from './oidc';
118
131
 
119
132
  const leg = (name: 'start' | 'callback', path: string): Route => ({
120
133
  method: 'GET',
@@ -126,20 +139,22 @@ const leg = (name: 'start' | 'callback', path: string): Route => ({
126
139
 
127
140
  export const signInRoutes: readonly Route[] = [
128
141
  leg('start', OAUTH_START_ROUTE_PATH),
129
- leg('callback', OAUTH_CALLBACK_ROUTE_PATH),
142
+ leg('callback', OIDC_CALLBACK_PATH),
130
143
  ];
131
144
  `;
132
145
 
133
146
  const routesTest =
134
- (): string => `// Both legs are mounted, public, at the framework's one declaration of where they live.
135
- import { OAUTH_CALLBACK_ROUTE_PATH, OAUTH_START_ROUTE_PATH } from '@ultimat3/auth';
147
+ (): string => `// Both legs are mounted, public: the start leg at the framework's path, the callback at the one
148
+ // \`oauthLogin\` is handed as \`callbackPath\` — so the mount is the \`redirect_uri\` the IdP holds.
149
+ import { OAUTH_START_ROUTE_PATH } from '@ultimat3/auth';
136
150
  import { expect, unitTest } from '@ultimat3/testing';
151
+ import { OIDC_CALLBACK_PATH } from './oidc';
137
152
  import { signInRoutes } from './sign-in-routes';
138
153
 
139
- unitTest('the start and callback legs are public GET routes at the framework paths', () => {
154
+ unitTest('the start and callback legs are public GET routes at the paths oauthLogin serves', () => {
140
155
  expect(signInRoutes.map((route) => [route.method, route.path, route.meta.auth])).toEqual([
141
156
  ['GET', OAUTH_START_ROUTE_PATH, 'public'],
142
- ['GET', OAUTH_CALLBACK_ROUTE_PATH, 'public'],
157
+ ['GET', OIDC_CALLBACK_PATH, 'public'],
143
158
  ]);
144
159
  });
145
160
  `;
@@ -3,6 +3,7 @@
3
3
  // rule has to leave alone is a fixture string. Which file may hold which shape is the caller's.
4
4
 
5
5
  import { maskLiterals } from '@ultimat3/core';
6
+ import { destructuredNames } from './binding-names';
6
7
  import { lineIndex } from './ts-scan';
7
8
 
8
9
  export type TransportShape = 'fetch' | 'websocket' | 'xhr' | 'eventsource';
@@ -30,7 +31,7 @@ const FETCH = new RegExp(String.raw`(?<![\w$.])(${GLOBAL}?)fetch\s*\(`, 'g');
30
31
 
31
32
  /**
32
33
  * Whether the file binds `fetch` itself — a `const`/`let`/`var`/`function`, an import, a
33
- * destructured declaration or a parameter — which makes a BARE `fetch(` its own function, not the
34
+ * destructuring that binds that NAME (`binding-names.ts`) or a parameter — which makes a BARE `fetch(` its own function, not the
34
35
  * page's. `packages/action/src/idempotency-postgres.ts` calls a local `fetch(key)`. Per file, not
35
36
  * per scope: a floor, and the one direction it errs is silence on a file that shadows the global
36
37
  * AND calls it bare. `globalThis.fetch(` is reported regardless.
@@ -38,8 +39,11 @@ const FETCH = new RegExp(String.raw`(?<![\w$.])(${GLOBAL}?)fetch\s*\(`, 'g');
38
39
  export function bindsFetch(code: string): boolean {
39
40
  return (
40
41
  /\b(?:const|let|var|function)\s+fetch\b/.test(code) ||
41
- /\bimport\s+[^;]*\bfetch\b[^;]*\bfrom\b/.test(code) ||
42
- /\b(?:const|let|var)\s*\{[^}]*\bfetch\b[^}]*\}\s*=/.test(code) ||
42
+ // `import { fetch }` and `import { f as fetch }` bind it; `import { fetch as f }` binds `f`.
43
+ /\bimport\s+[^;]*(?<!\bas\s+)\bfetch\b(?!\s+as\b)[^;]*\bfrom\b/.test(code) ||
44
+ /\bimport\s+[^;]*\bas\s+fetch\b[^;]*\bfrom\b/.test(code) ||
45
+ // By the NAME a pattern binds: `{ fetch: f }` reads the property and binds `f`.
46
+ destructuredNames(code).has('fetch') ||
43
47
  /\(\s*(?:[\w$]+\s*(?::[^,()]+)?,\s*)*fetch\s*[?:,)=][^()]*\)\s*(?::[^={;]+)?(?:=>|\{)/.test(
44
48
  code,
45
49
  )
@@ -0,0 +1,59 @@
1
+ // The global `fetch` handed on as a VALUE in one file's text — `rpc({ fetch })`, `fetch: fetch`,
2
+ // `const f = window.fetch`, `make(globalThis.fetch)` — the bypass `transportCalls` cannot see: the
3
+ // call happens in the module it was passed to, as `options.fetch(url)`, a property no rule reads.
4
+ // Pure, beside `transport-calls.ts`; the caller decides which file may hold it.
5
+
6
+ import { maskLiterals } from '@ultimat3/core';
7
+ import type { TransportCall } from './transport-calls';
8
+ import { bindsFetch } from './transport-calls';
9
+ import { lineIndex } from './ts-scan';
10
+
11
+ /**
12
+ * `fetch` not after `.`/a word char (a property on another object, `prefetch`), optionally behind
13
+ * the global object, not followed by a word char (`fetchUser`) — and never a call, which is
14
+ * `transportCalls`' finding already.
15
+ */
16
+ const VALUE =
17
+ /(?<![\w$.])((?:(?:globalThis|window|self)\s*\.\s*)?)fetch(?![\w$])(?!\s*(?:\?\.\s*)?\()/g;
18
+
19
+ /** Every blank from `lastIndex` on, sticky: the scan stops at the next token, never the file end. */
20
+ const BLANK = /\s*/y;
21
+
22
+ /** The last non-blank character before `index`, or `''`. */
23
+ function before(masked: string, index: number): string {
24
+ for (let at = index - 1; at >= 0; at -= 1) {
25
+ const char = masked[at] ?? '';
26
+ if (!/\s/.test(char)) return char;
27
+ }
28
+ return '';
29
+ }
30
+
31
+ /** Where the name sits is no value: a type, an object/interface key, an assignment target. */
32
+ function isNotAValue(masked: string, start: number, end: number): boolean {
33
+ // `typeof fetch`, `typeof globalThis.fetch` — a type position (or a feature probe, no request).
34
+ if (/\btypeof\s*$/.test(masked.slice(Math.max(0, start - 12), start))) return true;
35
+ // Through every blank: masking turned comments into spaces, so `fetch /* c */ :` is a key too.
36
+ BLANK.lastIndex = end;
37
+ BLANK.test(masked);
38
+ const after = masked.slice(BLANK.lastIndex, BLANK.lastIndex + 3);
39
+ // `{ fetch: impl }`, `fetch?: Fn` — a key; `a ? fetch : b` is the ternary's value.
40
+ if (/^\??\s*:(?!:)/.test(after) && before(masked, start) !== '?') return true;
41
+ // `window.fetch = wrapped`, `<C fetch={…}>` — the name is written to, not read.
42
+ return /^=(?![=>])/.test(after);
43
+ }
44
+
45
+ export function fetchValues(source: string): readonly TransportCall[] {
46
+ if (!source.includes('fetch')) return [];
47
+ // Comments and strings blanked, offsets kept: `'fetch'` in a message is not the global.
48
+ const masked = maskLiterals(source);
49
+ const lineAt = lineIndex(masked);
50
+ const shadowed = bindsFetch(masked);
51
+ const values: TransportCall[] = [];
52
+ for (const found of masked.matchAll(VALUE)) {
53
+ const global = (found[1] ?? '').replace(/\s/g, '');
54
+ if (global === '' && shadowed) continue;
55
+ if (isNotAValue(masked, found.index, found.index + found[0].length)) continue;
56
+ values.push({ shape: 'fetch', line: lineAt(found.index), spelled: `${global}fetch` });
57
+ }
58
+ return values;
59
+ }