|
| 1 | +import { expect, test } from 'vitest'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { parseSync } from 'oxc-parser'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Every CLI invocation eagerly evaluates the static import closure of |
| 8 | + * `src/cli.ts`. Importing `node:http` (or `node:https`) for a VALUE inside that |
| 9 | + * closure initializes undici and, under `NODE_USE_SYSTEM_CA=1`, the platform |
| 10 | + * trust store as well -- ~79ms added to every warm command on macOS, including |
| 11 | + * ones that never speak HTTP (the default daemon transport is a `node:net` |
| 12 | + * socket). The HTTP daemon transport, remote-artifact upload and download all |
| 13 | + * load these modules on demand instead. |
| 14 | + * |
| 15 | + * "On demand" is a claim about SCOPE, not about syntax, which is why this reads |
| 16 | + * the AST rather than matching import forms. Two shapes evaluate the module |
| 17 | + * during module evaluation while looking lazy or looking like nothing at all: |
| 18 | + * a bare side-effect `import 'node:http'` (binds no names, still evaluates), |
| 19 | + * and a dynamic `import('node:http')` sitting at module top level rather than |
| 20 | + * inside a function -- including `.then(...)` and an immediately-invoked |
| 21 | + * top-level function. A dynamic import is lazy only when its nearest enclosing |
| 22 | + * function scope is not the module itself. Type-only imports and re-exports are |
| 23 | + * erased at build and stay allowed. |
| 24 | + * |
| 25 | + * Known limitation: a top-level function that is invoked indirectly at load |
| 26 | + * time (stored, then called by another top-level statement) reads as lazy here. |
| 27 | + * Direct top-level invocation -- `(() => { ... })()` -- is detected. |
| 28 | + */ |
| 29 | + |
| 30 | +const srcRoot = path.resolve(import.meta.dirname, '..'); |
| 31 | +const LAZY_HTTP_MODULES = new Set(['node:http', 'node:https']); |
| 32 | +const FUNCTION_NODES = new Set([ |
| 33 | + 'FunctionDeclaration', |
| 34 | + 'FunctionExpression', |
| 35 | + 'ArrowFunctionExpression', |
| 36 | +]); |
| 37 | +const WORKSPACE_SPECIFIER = /^(@agent-device\/[^/]+)(\/.*)?$/; |
| 38 | + |
| 39 | +type AstNode = { type?: string; [key: string]: unknown }; |
| 40 | + |
| 41 | +type ParsedModuleRecord = ReturnType<typeof parseSync>['module']; |
| 42 | + |
| 43 | +/** Static specifiers this file causes to be EVALUATED (not type-only). */ |
| 44 | +function staticEvaluatedRefs(module: ParsedModuleRecord): string[] { |
| 45 | + const refs: string[] = []; |
| 46 | + for (const staticImport of module.staticImports) { |
| 47 | + // No entries at all is a side-effect import (`import 'x'`), which always |
| 48 | + // evaluates. Otherwise it evaluates unless every binding is type-only. |
| 49 | + const evaluates = |
| 50 | + staticImport.entries.length === 0 || staticImport.entries.some((entry) => !entry.isType); |
| 51 | + if (evaluates) refs.push(staticImport.moduleRequest.value); |
| 52 | + } |
| 53 | + for (const staticExport of module.staticExports) { |
| 54 | + for (const entry of staticExport.entries) { |
| 55 | + if (entry.moduleRequest && !entry.isType) refs.push(entry.moduleRequest.value); |
| 56 | + } |
| 57 | + } |
| 58 | + return refs; |
| 59 | +} |
| 60 | + |
| 61 | +function unwrapParentheses(node: unknown): AstNode | null { |
| 62 | + let current = node as AstNode | null; |
| 63 | + while (current?.type === 'ParenthesizedExpression') |
| 64 | + current = current.expression as AstNode | null; |
| 65 | + return current; |
| 66 | +} |
| 67 | + |
| 68 | +/** The body of a function invoked right where it is defined, if this is that call. */ |
| 69 | +function immediatelyInvokedBody(node: AstNode): unknown { |
| 70 | + if (node.type !== 'CallExpression') return null; |
| 71 | + const callee = unwrapParentheses(node.callee); |
| 72 | + return callee && FUNCTION_NODES.has(String(callee.type)) ? callee.body : null; |
| 73 | +} |
| 74 | + |
| 75 | +function dynamicImportSpecifier(node: AstNode): string | null { |
| 76 | + if (node.type !== 'ImportExpression') return null; |
| 77 | + const source = node.source as { type?: string; value?: unknown } | undefined; |
| 78 | + return source?.type === 'Literal' && typeof source.value === 'string' ? source.value : null; |
| 79 | +} |
| 80 | + |
| 81 | +function recordDynamicImport(record: AstNode, eager: boolean, found: string[]): void { |
| 82 | + if (!eager) return; |
| 83 | + const specifier = dynamicImportSpecifier(record); |
| 84 | + if (specifier !== null) found.push(specifier); |
| 85 | +} |
| 86 | + |
| 87 | +/** Descends into a node's children, dropping `eager` on the way into a function body. */ |
| 88 | +function visitChildren(record: AstNode, eager: boolean, found: string[]): void { |
| 89 | + const childEager = eager && !FUNCTION_NODES.has(String(record.type)); |
| 90 | + for (const [key, value] of Object.entries(record)) { |
| 91 | + if (key !== 'type') collectEagerDynamicImports(value, childEager, found); |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +/** Walks the AST, collecting only `import()` calls reached without entering a function. */ |
| 96 | +function collectEagerDynamicImports(node: unknown, eager: boolean, found: string[]): void { |
| 97 | + if (Array.isArray(node)) { |
| 98 | + for (const child of node) collectEagerDynamicImports(child, eager, found); |
| 99 | + return; |
| 100 | + } |
| 101 | + if (!node || typeof node !== 'object') return; |
| 102 | + const record = node as AstNode; |
| 103 | + recordDynamicImport(record, eager, found); |
| 104 | + // An immediately-invoked function runs now, so its body inherits `eager`. |
| 105 | + const invokedBody = immediatelyInvokedBody(record); |
| 106 | + if (invokedBody) collectEagerDynamicImports(invokedBody, eager, found); |
| 107 | + visitChildren(record, eager, found); |
| 108 | +} |
| 109 | + |
| 110 | +/** Every specifier this file evaluates at load time, static or dynamic. */ |
| 111 | +function eagerlyEvaluatedModules(fileName: string, source: string): string[] { |
| 112 | + const parsed = parseSync(fileName, source); |
| 113 | + const dynamic: string[] = []; |
| 114 | + collectEagerDynamicImports(parsed.program, true, dynamic); |
| 115 | + return [...new Set([...staticEvaluatedRefs(parsed.module), ...dynamic])]; |
| 116 | +} |
| 117 | + |
| 118 | +function resolveRelative(fromFile: string, specifier: string): string | null { |
| 119 | + const candidate = path.resolve(path.dirname(fromFile), specifier); |
| 120 | + if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate; |
| 121 | + for (const suffix of ['.ts', '.tsx', '/index.ts']) { |
| 122 | + if (fs.existsSync(`${candidate}${suffix}`)) return `${candidate}${suffix}`; |
| 123 | + } |
| 124 | + return null; |
| 125 | +} |
| 126 | + |
| 127 | +/** `@agent-device/<pkg>` -> that package's directory, keyed by its declared name. */ |
| 128 | +function readWorkspacePackageDirs(): Map<string, string> { |
| 129 | + const packagesRoot = path.resolve(srcRoot, '..', 'packages'); |
| 130 | + const dirs = new Map<string, string>(); |
| 131 | + for (const entry of fs.readdirSync(packagesRoot)) { |
| 132 | + const manifestPath = path.join(packagesRoot, entry, 'package.json'); |
| 133 | + if (!fs.existsSync(manifestPath)) continue; |
| 134 | + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as { name?: string }; |
| 135 | + if (manifest.name) dirs.set(manifest.name, path.join(packagesRoot, entry)); |
| 136 | + } |
| 137 | + return dirs; |
| 138 | +} |
| 139 | + |
| 140 | +type ExportTarget = { default?: string; types?: string } | string; |
| 141 | + |
| 142 | +function readExportTarget(packageDir: string, subpath: string): string | undefined { |
| 143 | + const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8')) as { |
| 144 | + exports?: Record<string, ExportTarget>; |
| 145 | + }; |
| 146 | + const target = manifest.exports?.[subpath]; |
| 147 | + if (typeof target === 'string') return target; |
| 148 | + return target?.default ?? target?.types; |
| 149 | +} |
| 150 | + |
| 151 | +/** |
| 152 | + * Workspace subpath imports are followed too: a package the CLI evaluates can |
| 153 | + * pull `node:http` in just as effectively as a file under src/, and stopping the |
| 154 | + * walk at the package boundary would be the same blind spot in a new place. |
| 155 | + */ |
| 156 | +function resolveWorkspace(specifier: string, packageDirs: Map<string, string>): string | null { |
| 157 | + const match = WORKSPACE_SPECIFIER.exec(specifier); |
| 158 | + const packageName = match?.[1]; |
| 159 | + const packageDir = packageName ? packageDirs.get(packageName) : undefined; |
| 160 | + if (!packageDir) return null; |
| 161 | + const target = readExportTarget(packageDir, `.${match?.[2] ?? ''}`); |
| 162 | + if (!target) return null; |
| 163 | + const resolved = path.resolve(packageDir, target); |
| 164 | + return fs.existsSync(resolved) ? resolved : null; |
| 165 | +} |
| 166 | + |
| 167 | +/** Every repo file evaluated as a consequence of importing `src/cli.ts`. */ |
| 168 | +function eagerClosureOfCli(): string[] { |
| 169 | + const packageDirs = readWorkspacePackageDirs(); |
| 170 | + const queue = [path.join(srcRoot, 'cli.ts')]; |
| 171 | + const visited = new Set<string>(); |
| 172 | + while (queue.length > 0) { |
| 173 | + const current = queue.pop(); |
| 174 | + if (!current || visited.has(current)) continue; |
| 175 | + visited.add(current); |
| 176 | + for (const specifier of eagerlyEvaluatedModules(current, fs.readFileSync(current, 'utf8'))) { |
| 177 | + const resolved = specifier.startsWith('.') |
| 178 | + ? resolveRelative(current, specifier) |
| 179 | + : resolveWorkspace(specifier, packageDirs); |
| 180 | + if (resolved) queue.push(resolved); |
| 181 | + } |
| 182 | + } |
| 183 | + return [...visited]; |
| 184 | +} |
| 185 | + |
| 186 | +test.for([ |
| 187 | + // --- static forms --- |
| 188 | + { form: 'side-effect import', code: `import 'node:http';`, eager: true }, |
| 189 | + { form: 'default value import', code: `import http from 'node:http';`, eager: true }, |
| 190 | + { form: 'namespace import', code: `import * as http from 'node:http';`, eager: true }, |
| 191 | + { form: 'named value import', code: `import { request } from 'node:http';`, eager: true }, |
| 192 | + { form: 'value re-export', code: `export { request } from 'node:http';`, eager: true }, |
| 193 | + { form: 'star re-export', code: `export * from 'node:http';`, eager: true }, |
| 194 | + { |
| 195 | + form: 'mixed value + type import', |
| 196 | + code: `import http, { type IncomingMessage } from 'node:http';`, |
| 197 | + eager: true, |
| 198 | + }, |
| 199 | + { form: 'type-only default import', code: `import type http from 'node:http';`, eager: false }, |
| 200 | + { |
| 201 | + form: 'type-only named import', |
| 202 | + code: `import { type IncomingMessage } from 'node:http';`, |
| 203 | + eager: false, |
| 204 | + }, |
| 205 | + { |
| 206 | + form: 'type-only re-export', |
| 207 | + code: `export type { IncomingMessage } from 'node:http';`, |
| 208 | + eager: false, |
| 209 | + }, |
| 210 | + // --- dynamic import: scope decides, not syntax --- |
| 211 | + { form: 'top-level await import', code: `const m = await import('node:http');`, eager: true }, |
| 212 | + { form: 'top-level import().then', code: `import('node:http').then((m) => m);`, eager: true }, |
| 213 | + { |
| 214 | + form: 'top-level immediately-invoked arrow', |
| 215 | + code: `(async () => { await import('node:http'); })();`, |
| 216 | + eager: true, |
| 217 | + }, |
| 218 | + { |
| 219 | + form: 'function-declaration-local import', |
| 220 | + code: `async function load() { return await import('node:http'); }`, |
| 221 | + eager: false, |
| 222 | + }, |
| 223 | + { |
| 224 | + form: 'arrow-local import', |
| 225 | + code: `const load = async () => await import('node:http');`, |
| 226 | + eager: false, |
| 227 | + }, |
| 228 | + { |
| 229 | + form: 'method-local import', |
| 230 | + code: `class K { async load() { await import('node:http'); } }`, |
| 231 | + eager: false, |
| 232 | + }, |
| 233 | + { |
| 234 | + form: 'ternary inside a function (the shipped lazy-load shape)', |
| 235 | + code: `async function load(s: boolean) { |
| 236 | + return s ? (await import('node:https')).default : (await import('node:http')).default; |
| 237 | + }`, |
| 238 | + eager: false, |
| 239 | + }, |
| 240 | +])('$form is eager=$eager', ({ code, eager }) => { |
| 241 | + const refs = eagerlyEvaluatedModules('fixture.ts', code); |
| 242 | + expect(refs.includes('node:http') || refs.includes('node:https')).toBe(eager); |
| 243 | +}); |
| 244 | + |
| 245 | +test('the CLI startup import closure never evaluates node:http or node:https', () => { |
| 246 | + const offenders: string[] = []; |
| 247 | + for (const file of eagerClosureOfCli()) { |
| 248 | + for (const specifier of eagerlyEvaluatedModules(file, fs.readFileSync(file, 'utf8'))) { |
| 249 | + if (LAZY_HTTP_MODULES.has(specifier)) { |
| 250 | + offenders.push(`${path.relative(srcRoot, file)} -> ${specifier}`); |
| 251 | + } |
| 252 | + } |
| 253 | + } |
| 254 | + |
| 255 | + expect( |
| 256 | + offenders, |
| 257 | + 'Load node:http / node:https on demand instead: evaluating either one here costs every warm ' + |
| 258 | + 'CLI command ~79ms of undici + system-CA initialization.', |
| 259 | + ).toEqual([]); |
| 260 | +}); |
| 261 | + |
| 262 | +test('the CLI startup import closure is reachable and crosses the package boundary', () => { |
| 263 | + // Guards the test above from silently passing because the walk found nothing: |
| 264 | + // a resolver that returned null for everything would leave both the src side |
| 265 | + // and the workspace side of the closure empty while the guard stayed green. |
| 266 | + const closure = eagerClosureOfCli(); |
| 267 | + expect(closure.length).toBeGreaterThan(50); |
| 268 | + expect( |
| 269 | + closure.filter((file) => file.includes(`${path.sep}packages${path.sep}`)).length, |
| 270 | + ).toBeGreaterThan(0); |
| 271 | +}); |
0 commit comments