diff --git a/scripts/build-platform-package.mjs b/scripts/build-platform-package.mjs index 0648270..f3e3741 100644 --- a/scripts/build-platform-package.mjs +++ b/scripts/build-platform-package.mjs @@ -173,6 +173,7 @@ export async function buildPlatformPackage({ name: `@cometix/claude-code-${platform}`, version, description: `Claude Code Node.js restored — ${platform}`, + ...(splitEsm ? { type: 'module' } : {}), os: [os], cpu: [cpu], files: ['cli.js', 'vendor/'], diff --git a/scripts/esm-chunk-patch.mjs b/scripts/esm-chunk-patch.mjs index ef52d9e..9aa2748 100644 --- a/scripts/esm-chunk-patch.mjs +++ b/scripts/esm-chunk-patch.mjs @@ -620,9 +620,10 @@ export function rewritePluginTestEnv(code) { const POLYFILL_MODULE = 'bun-polyfill.mjs'; const ESM_PRELUDE = [ - 'import{createRequire as __ccCreateRequire}from"module";', + 'import{createRequire as __ccCreateRequire,enableCompileCache as __ccEnableCompileCache}from"module";', 'import{fileURLToPath as __ccFileURLToPath}from"url";', 'import{dirname as __ccPathDirname}from"path";', + 'try{__ccEnableCompileCache?.()}catch{}', 'const require=__ccCreateRequire(import.meta.url);', 'const __filename=__ccFileURLToPath(import.meta.url);', 'const __dirname=__ccPathDirname(__filename);', @@ -644,6 +645,963 @@ export function buildPolyfillModule(polyfillSource) { return ESM_PRELUDE + polyfillSource.replace(/^#![^\n]*\n/, '') + ESM_HELPERS; } +// ────────────────────────────────────────────── +// E10: Startup performance rewrites (Windows & cross-platform) +// +// 1. rewriteWindowsWhere: replace synchronous where.exe execFileSync in $Br +// with pure-JS globalThis.__ccFindExecutableCandidates while keeping +// upstream's cwd exclusion (pQn), extension check, and host cache. +// 2. rewriteWindowsProcessCreationTime: use background-warmed self process +// start time for process.pid, replace slow WMI Get-CimInstance with +// Get-Process, and add 1ms tick tolerance in GEe for WMI/Get-Process +// precision compatibility. +// 3. rewriteUdsSweep: defer stale .tmp session key sweep (Ee) off the +// critical path during UDS inbox initialization. +// 4. rewriteParallelReplImports: load AppRoot and REPL chunks concurrently +// with Promise.all instead of sequentially awaiting them. +// 5. rewriteSystemCaCertCache: use disk-cached X509 validTo timestamps +// (__ccGetCertValidTo) when filtering system CA certificates. +// 6. pruneRedundantBareImports: remove bare `import "./chunk-x.js"` edges +// that are already in the transitive closure of earlier imports in the +// same module, preserving exact DFS post-order evaluation while cutting +// ~84% of redundant ESM linker edges. +// ────────────────────────────────────────────── + +export function rewriteWindowsWhere(code) { + if (!code.includes('"where.exe"') || !code.includes('windowsHide')) { + return { code, rewritten: 0 }; + } + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + (function visit(node) { + if (node.type === 'VariableDeclarator' && node.init?.type === 'CallExpression') { + const filterCall = node.init; + const splitCall = filterCall.callee?.type === 'MemberExpression' && + filterCall.callee.property?.name === 'filter' + ? filterCall.callee.object : null; + const trimCall = splitCall?.type === 'CallExpression' && + splitCall.callee?.type === 'MemberExpression' && + splitCall.callee.property?.name === 'split' + ? splitCall.callee.object : null; + const execCall = trimCall?.type === 'CallExpression' && + trimCall.callee?.type === 'MemberExpression' && + trimCall.callee.property?.name === 'trim' + ? trimCall.callee.object : null; + const argArr = execCall?.type === 'CallExpression' ? execCall.arguments?.[1] : null; + if (argArr?.type === 'ArrayExpression' && + argArr.elements.length === 1 && + argArr.elements[0] && + code.slice(execCall.start, execCall.end).includes('windowsHide')) { + const cmdExpr = code.slice(argArr.elements[0].start, argArr.elements[0].end); + const origExpr = code.slice(filterCall.start, filterCall.end); + edits.push({ + start: filterCall.start, + end: filterCall.end, + text: `(globalThis.__ccFindExecutableCandidates?globalThis.__ccFindExecutableCandidates(${cmdExpr},{includeCwd:!0,firstOnly:!0,throwOnEmpty:!0}):${origExpr})`, + }); + } + } + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +export function rewriteWindowsProcessCreationTime(code) { + if (!code.includes('Win32_Process') || !code.includes('CreationDate')) { + return { code, rewritten: 0 }; + } + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + (function visit(node) { + if (node.type === 'FunctionDeclaration' && + node.params.length >= 1 && + node.params[0]?.type === 'Identifier' && + node.body?.type === 'BlockStatement' && + code.slice(node.body.start, node.body.end).includes('CreationDate.Ticks')) { + const pidParam = node.params[0].name; + const envParam = node.params[1]?.type === 'Identifier' ? node.params[1].name : null; + const guard = node.async + ? `if(${pidParam}===process.pid&&${envParam ? `${envParam}===void 0&&` : ''}globalThis.__ccGetSelfProcStart){let _s=await globalThis.__ccGetSelfProcStart();if(_s)return _s}` + : `if(${pidParam}===process.pid&&globalThis.__ccSelfProcStartTicks)return globalThis.__ccSelfProcStartTicks;`; + edits.push({ start: node.body.start + 1, end: node.body.start + 1, text: guard }); + } + + if (node.type === 'TemplateLiteral' && node.expressions.length === 1) { + const raw = code.slice(node.start, node.end); + if (raw.includes('Get-CimInstance Win32_Process -Filter') && raw.includes('.CreationDate')) { + const expr = code.slice(node.expressions[0].start, node.expressions[0].end); + const replaced = raw + .replace( + `(Get-CimInstance Win32_Process -Filter \\\\"ProcessId=\${${expr}}\\\\").CreationDate.Ticks`, + `(Get-Process -Id \${${expr}}).StartTime.Ticks`, + ) + .replace( + `(Get-CimInstance Win32_Process -Filter "ProcessId=\${${expr}}").CreationDate.Ticks`, + `(Get-Process -Id \${${expr}}).StartTime.Ticks`, + ) + .replace( + `(Get-CimInstance Win32_Process -Filter "ProcessId=\${${expr}}").CreationDate`, + `(Get-Process -Id \${${expr}}).StartTime`, + ); + if (replaced !== raw) { + edits.push({ start: node.start, end: node.end, text: replaced }); + } + } + } + + if (node.type === 'LogicalExpression' && node.operator === '&&') { + const rhs = node.right; + if (rhs?.type === 'BinaryExpression' && + rhs.operator === '!==' && + rhs.left?.type === 'BinaryExpression' && + rhs.left.operator === '>' && + rhs.left.right?.type === 'Literal' && + rhs.left.right.value === 300000000000000000 && + rhs.right?.type === 'BinaryExpression' && + rhs.right.operator === '>' && + rhs.right.right?.type === 'Literal' && + rhs.right.right.value === 300000000000000000) { + const lhsVar = code.slice(rhs.left.left.start, rhs.left.left.end); + const rhsVar = code.slice(rhs.right.left.start, rhs.right.left.end); + const origRhs = code.slice(rhs.start, rhs.end); + edits.push({ + start: rhs.start, + end: rhs.end, + text: `(${origRhs}||Math.abs(${lhsVar}-${rhsVar})<1e4)`, + }); + } + } + + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +export function rewriteUdsSweep(code) { + if (!code.includes('sweepPermitted')) return { code, rewritten: 0 }; + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + (function visit(node) { + if (node.type === 'FunctionDeclaration' && node.async && node.body?.type === 'BlockStatement') { + let sweepVar = null; + for (const param of node.params) { + if (param.type === 'ObjectPattern') { + for (const prop of param.properties) { + if (prop.type === 'Property' && + (prop.key.name ?? prop.key.value) === 'sweepPermitted' && + prop.value?.type === 'Identifier') { + sweepVar = prop.value.name; + } + } + } + } + if (sweepVar) { + (function findSweepAwait(sub) { + if (sub.type === 'AwaitExpression' && + sub.argument?.type === 'CallExpression' && + sub.argument.arguments.length === 2 && + sub.argument.arguments[1]?.type === 'Identifier' && + sub.argument.arguments[1].name === sweepVar) { + const callExpr = code.slice(sub.argument.start, sub.argument.end); + edits.push({ + start: sub.start, + end: sub.end, + text: `(${sweepVar}&&setTimeout(()=>{${callExpr}.catch(()=>{})},2e3).unref?.())`, + }); + return; + } + for (const k of Object.keys(sub)) { + const ch = sub[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') findSweepAwait(it); + } else if (ch && typeof ch.type === 'string') { + findSweepAwait(ch); + } + } + })(node.body); + } + } + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +function hasObjectPatternKey(pattern, keyName) { + return pattern?.type === 'ObjectPattern' && + pattern.properties.some((p) => p.type === 'Property' && (p.key.name ?? p.key.value) === keyName); +} + +export function rewriteParallelReplImports(code) { + const hasReplPair = code.includes('AppRoot') && code.includes('REPL'); + const hasOnboardingCreateRoot = code.includes('createRoot') && code.includes('showSetupScreens'); + const hasInteractiveSetup = code.includes('startPreviewBrowserDiscovery') && code.includes('action_before_setup'); + const hasPostRender = code.includes('waitUntilExit') && code.includes('runBeforeInteractiveShutdown'); + const hasDeferTelemetry = code.includes('maybePrewarmRecallIndex') && code.includes('setImmediate('); + const hasCliInteractiveEntry = code.includes('startCapturingEarlyInput') && + code.includes('configureZodForStartup') && + code.includes('cli_before_main_import'); + if (!hasReplPair && !hasOnboardingCreateRoot && !hasInteractiveSetup && + !hasPostRender && !hasDeferTelemetry && !hasCliInteractiveEntry) { + return { code, rewritten: 0 }; + } + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + let setupScreensSpec = null; + let createRootSpec = null; + if (hasOnboardingCreateRoot) { + (function findSpecs(n) { + if (n.type === 'VariableDeclarator' && + n.id?.type === 'Identifier' && + n.init?.type === 'ArrowFunctionExpression' && + n.init.body?.type === 'CallExpression' && + n.init.body.callee?.name === '__ccRequire' && + n.init.body.arguments?.[0]?.type === 'Literal') { + const spec = n.init.body.arguments[0].value; + if (code.includes(`${n.id.name}().showSetupScreens`)) { + setupScreensSpec = spec; + } + } + if (n.type === 'FunctionDeclaration' && + n.async && + code.slice(n.start, n.end).includes('Running showSetupScreens()')) { + (function findCreateRoot(sub) { + if (sub.type === 'VariableDeclarator' && + hasObjectPatternKey(sub.id, 'createRoot') && + sub.init?.type === 'AwaitExpression' && + sub.init.argument?.type === 'ImportExpression' && + sub.init.argument.source?.type === 'Literal') { + createRootSpec = sub.init.argument.source.value; + } + for (const k of Object.keys(sub)) { + const ch = sub[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') findCreateRoot(it); + } else if (ch && typeof ch.type === 'string') { + findCreateRoot(ch); + } + } + })(n); + } + for (const k of Object.keys(n)) { + const ch = n[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') findSpecs(it); + } else if (ch && typeof ch.type === 'string') { + findSpecs(ch); + } + } + })(ast); + } + + let cliSpecs = null; + if (hasCliInteractiveEntry) { + const found = {}; + (function scanCliImports(n) { + if (n.type === 'VariableDeclarator' && + n.init?.type === 'AwaitExpression' && + n.init.argument?.type === 'ImportExpression' && + n.init.argument.source?.type === 'Literal') { + const spec = n.init.argument.source.value; + for (const k of ['enableConfigs', 'NON_REPL_SUBCOMMANDS', 'main']) { + if (hasObjectPatternKey(n.id, k)) found[k] = spec; + } + } + if (n.type === 'CallExpression' && + n.callee?.type === 'MemberExpression' && + n.callee.property?.name === 'configureZodForStartup' && + n.callee.object?.type === 'AwaitExpression' && + n.callee.object.argument?.type === 'ImportExpression' && + n.callee.object.argument.source?.type === 'Literal') { + found.configureZodForStartup = n.callee.object.argument.source.value; + } + for (const k of Object.keys(n)) { + const ch = n[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') scanCliImports(it); + } else if (ch && typeof ch.type === 'string') { + scanCliImports(ch); + } + } + })(ast); + if (found.enableConfigs && found.configureZodForStartup && found.main) { + cliSpecs = found; + } + } + + const edits = []; + (function visit(node) { + if (cliSpecs && + node.type === 'IfStatement' && + code.slice(node.test.start, node.test.end).includes('process.stdin.isTTY') && + code.slice(node.test.start, node.test.end).includes('process.stdout.isTTY') && + node.consequent?.type === 'BlockStatement' && + node.consequent.body.length > 0) { + const firstStmt = node.consequent.body[0]; + if (firstStmt.type === 'VariableDeclaration') { + for (const d of firstStmt.declarations) { + if (hasObjectPatternKey(d.id, 'startCapturingEarlyInput') && + hasObjectPatternKey(d.id, 'consumeEarlyInput') && + d.init?.type === 'AwaitExpression' && + d.init.argument?.type === 'ImportExpression') { + const origAwait = code.slice(d.init.start, d.init.end); + const preloads = [ + `import(${JSON.stringify(cliSpecs.enableConfigs)})`, + ...(cliSpecs.NON_REPL_SUBCOMMANDS ? [`import(${JSON.stringify(cliSpecs.NON_REPL_SUBCOMMANDS)})`] : []), + `import(${JSON.stringify(cliSpecs.configureZodForStartup)}).then((_z)=>{_z.configureZodForStartup();return import(${JSON.stringify(cliSpecs.main)})})`, + ]; + edits.push({ + start: d.init.start, + end: d.init.end, + text: `(Promise.all([${preloads.join(',')}]).catch(()=>{}),${origAwait})`, + }); + } + } + } + } + + if (hasReplPair && node.type === 'FunctionDeclaration' && node.async && node.body?.type === 'BlockStatement') { + for (const stmt of node.body.body) { + if (stmt.type === 'VariableDeclaration' && stmt.declarations.length >= 2) { + for (let i = 0; i < stmt.declarations.length - 1; i++) { + const d0 = stmt.declarations[i]; + const d1 = stmt.declarations[i + 1]; + if (hasObjectPatternKey(d0.id, 'AppRoot') && + hasObjectPatternKey(d1.id, 'REPL') && + d0.init?.type === 'AwaitExpression' && + d0.init.argument?.type === 'ImportExpression' && + d1.init?.type === 'AwaitExpression' && + d1.init.argument?.type === 'ImportExpression') { + const id0 = code.slice(d0.id.start, d0.id.end); + const id1 = code.slice(d1.id.start, d1.id.end); + const imp0 = code.slice(d0.init.argument.start, d0.init.argument.end); + const imp1 = code.slice(d1.init.argument.start, d1.init.argument.end); + edits.push({ + start: node.start, + end: node.start, + text: `globalThis.__ccPreloadRepl??=()=>{let _p=Promise.all([${imp0},${imp1}]);return _p.catch(()=>{}),globalThis.__ccPreloadRepl=()=>_p,_p};`, + }); + edits.push({ + start: d0.start, + end: d1.end, + text: `[${id0},${id1}]=await(globalThis.__ccPreloadRepl?globalThis.__ccPreloadRepl():Promise.all([${imp0},${imp1}]))`, + }); + i++; + } + } + } + } + } + + if (hasOnboardingCreateRoot && node.type === 'VariableDeclaration') { + for (const d of node.declarations) { + if (hasObjectPatternKey(d.id, 'createRoot') && + d.init?.type === 'AwaitExpression' && + d.init.argument?.type === 'ImportExpression') { + const origAwait = code.slice(d.init.start, d.init.end); + edits.push({ + start: d.init.start, + end: d.init.end, + text: `(globalThis.__ccPreloadRepl?.(),${origAwait})`, + }); + } + } + } + + if (hasInteractiveSetup) { + if (node.type === 'CallExpression' && + node.callee?.type === 'MemberExpression' && + node.callee.property?.name === 'startPreviewBrowserDiscovery') { + const origCall = code.slice(node.start, node.end); + edits.push({ + start: node.start, + end: node.end, + text: `(globalThis.__ccIsInteractive=!0,${origCall})`, + }); + } + if (node.type === 'VariableDeclarator' && + hasObjectPatternKey(node.id, 'setup') && + node.init?.type === 'AwaitExpression' && + node.init.argument?.type === 'ImportExpression') { + const origAwait = code.slice(node.init.start, node.init.end); + const extraPreloads = []; + if (createRootSpec) extraPreloads.push(`import(${JSON.stringify(createRootSpec)}).catch(()=>{})`); + if (setupScreensSpec) extraPreloads.push(`import(${JSON.stringify(setupScreensSpec)}).catch(()=>{})`); + const preloadExpr = extraPreloads.length > 0 + ? `(globalThis.__ccPreloadRepl?.(),${extraPreloads.join(',')})` + : `globalThis.__ccPreloadRepl?.()`; + edits.push({ + start: node.init.start, + end: node.init.end, + text: `(globalThis.__ccIsInteractive&&${preloadExpr},${origAwait})`, + }); + } + } + + if (hasDeferTelemetry && + node.type === 'CallExpression' && + node.callee?.type === 'Identifier' && + node.callee.name === 'setImmediate' && + node.arguments?.length === 2 && + node.arguments[0]?.type === 'Identifier' && + node.arguments[1]?.type === 'Identifier') { + const fnName = node.arguments[0].name; + const argName = node.arguments[1].name; + edits.push({ + start: node.start, + end: node.end, + text: `setTimeout(${fnName},1500,${argName}).unref?.()`, + }); + } + + if (hasPostRender && + node.type === 'FunctionDeclaration' && + node.async && + node.body?.type === 'BlockStatement' && + code.slice(node.start, node.end).includes('waitUntilExit') && + code.slice(node.start, node.end).includes('runBeforeInteractiveShutdown')) { + const stmts = node.body.body; + if (stmts.length >= 2 && + stmts[1].type === 'ExpressionStatement' && + stmts[1].expression?.type === 'SequenceExpression' && + stmts[1].expression.expressions.length === 2) { + const [e0, e1] = stmts[1].expression.expressions; + if (e0.type === 'CallExpression' && + e0.arguments.length === 0 && + e1.type === 'CallExpression' && + e1.arguments.length >= 2) { + const call1 = code.slice(e1.start, e1.end); + edits.push({ + start: e1.start, + end: e1.end, + text: `setImmediate(()=>${call1})`, + }); + } + } + } + + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +export function rewriteNoopSlowOpUsing(code) { + if (!code.includes('using ')) return { code, rewritten: 0 }; + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + (function visit(node) { + if (node.type === 'VariableDeclaration' && + node.kind === 'using' && + node.declarations.length === 1 && + node.declarations[0].id?.type === 'Identifier' && + node.declarations[0].init?.type === 'TaggedTemplateExpression') { + edits.push({ start: node.start, end: node.end, text: '' }); + } + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +export function rewriteSystemCaCertCache(code) { + if (!code.includes('X509Certificate') || !code.includes('validTo')) { + return { code, rewritten: 0 }; + } + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + (function visit(node) { + if (node.type === 'VariableDeclaration' && node.declarations.length === 2) { + const [d0, d1] = node.declarations; + if (d0.id?.type === 'Identifier' && + d1.id?.type === 'Identifier' && + d0.init?.type === 'NewExpression' && + d0.init.arguments?.length === 1 && + d1.init?.type === 'CallExpression' && + d1.init.callee?.type === 'MemberExpression' && + d1.init.callee.property?.name === 'getTime' && + d1.init.callee.object?.type === 'NewExpression' && + d1.init.callee.object.callee?.name === 'Date' && + d1.init.callee.object.arguments?.[0]?.type === 'MemberExpression' && + d1.init.callee.object.arguments[0].object?.name === d0.id.name && + d1.init.callee.object.arguments[0].property?.name === 'validTo') { + const outVar = d1.id.name; + const ctorExpr = code.slice(d0.init.callee.start, d0.init.callee.end); + const certExpr = code.slice(d0.init.arguments[0].start, d0.init.arguments[0].end); + edits.push({ + start: d0.start, + end: d1.end, + text: `${outVar}=globalThis.__ccGetCertValidTo?globalThis.__ccGetCertValidTo(${certExpr},${ctorExpr}):new Date(new ${ctorExpr}(${certExpr}).validTo).getTime()`, + }); + } + } + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +export function rewriteEnvConfigCache(code) { + if (!code.includes('CLAUDE_CODE_LAZY_ENV_GETTERS') || !code.includes('Object.defineProperties')) { + return { code, rewritten: 0 }; + } + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + (function visit(node) { + if (node.type === 'FunctionDeclaration' && + node.params.length === 3 && + node.params.every((p) => p.type === 'Identifier') && + node.body?.type === 'BlockStatement' && + node.body.body.length === 2 && + node.body.body[1]?.type === 'ReturnStatement' && + node.body.body[1].argument?.type === 'ArrowFunctionExpression') { + const fnText = code.slice(node.start, node.end); + const [p0, p1, p2] = node.params.map((p) => p.name); + if (fnText.includes(`process.env[${p0}]`) && fnText.includes(`${p1}.parse(`)) { + const fnName = node.id.name; + edits.push({ + start: node.start, + end: node.end, + text: `var __ccEnvGen=1,__ccEnvTick=!1;function ${fnName}(${p0},${p1},${p2}){let E=${p2},r,g=0;return()=>{if(g===__ccEnvGen)return r;if(!__ccEnvTick)__ccEnvTick=!0,queueMicrotask(()=>{__ccEnvTick=!1;__ccEnvGen++});let n=process.env[${p0}];if(n!==E)r=${p1}.parse(n),E=n;return g=__ccEnvGen,r}}`, + }); + } + } + + if (node.type === 'FunctionDeclaration' && + node.params.length === 3 && + code.slice(node.start, node.end).includes('Object.defineProperties') && + code.slice(node.start, node.end).includes('delete process.env[')) { + (function patchMutators(sub) { + if (sub.type === 'Property' && + (sub.key?.name === 'set' || sub.key?.name === 'unset') && + sub.value?.type === 'ObjectExpression') { + for (const prop of sub.value.properties) { + if (prop.type === 'Property' && + prop.key?.name === 'value' && + prop.value?.type === 'ArrowFunctionExpression' && + prop.value.body?.type === 'BlockStatement') { + edits.push({ + start: prop.value.body.start + 1, + end: prop.value.body.start + 1, + text: '__ccEnvGen++;', + }); + } + } + } + for (const k of Object.keys(sub)) { + const ch = sub[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') patchMutators(it); + } else if (ch && typeof ch.type === 'string') { + patchMutators(ch); + } + } + })(node.body); + } + + for (const key of Object.keys(node)) { + const child = node[key]; + if (Array.isArray(child)) { + for (const item of child) if (item && typeof item.type === 'string') visit(item); + } else if (child && typeof child.type === 'string') { + visit(child); + } + } + })(ast); + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +export function rewriteLazyEngineInitAndModelPicker(code) { + const hasEngineInit = code.includes('initializationResult:') && code.includes('unavailableModels:'); + const hasModelGate = code.includes('model_unavailable_gate') && code.includes('claude-vscode'); + if (!hasEngineInit && !hasModelGate) { + return { code, rewritten: 0 }; + } + let ast; + try { + ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' }); + } catch { + return { code, rewritten: 0 }; + } + + const edits = []; + if (hasEngineInit) { + for (const rawStmt of ast.body) { + const stmt = rawStmt.type === 'ExportNamedDeclaration' && rawStmt.declaration + ? rawStmt.declaration + : rawStmt; + if (stmt.type === 'FunctionDeclaration' && + stmt.body?.type === 'BlockStatement' && + stmt.body.body.length > 0 && + code.slice(stmt.start, stmt.end).includes('initializationResult:') && + code.slice(stmt.start, stmt.end).includes('supportedModels:')) { + const firstStmt = stmt.body.body[0]; + if (firstStmt.type === 'VariableDeclaration' && firstStmt.declarations.length >= 1) { + const d0 = firstStmt.declarations[0]; + if (d0.id?.type === 'Identifier' && + d0.init?.type === 'CallExpression' && + code.slice(d0.init.start, d0.init.end).includes('unavailableModels:')) { + const initVar = d0.id.name; + const initCall = code.slice(d0.init.start, d0.init.end); + edits.push({ + start: d0.start, + end: d0.end, + text: `__ccLazy_${initVar},${initVar}=()=>__ccLazy_${initVar}??=${initCall}`, + }); + (function replaceRefs(sub) { + if (sub.type === 'Property' && + sub.key?.type === 'Identifier' && + ['initializationResult', 'accountInfo', 'supportedModels', 'supportedCommands', 'supportedAgents'].includes(sub.key.name)) { + (function replaceId(expr) { + if (expr.type === 'Identifier' && expr.name === initVar) { + edits.push({ start: expr.start, end: expr.end, text: `${initVar}()` }); + return; + } + if (expr.type === 'MemberExpression' && !expr.computed && expr.object?.type === 'Identifier' && expr.object.name === initVar) { + edits.push({ start: expr.object.start, end: expr.object.end, text: `${initVar}()` }); + return; + } + for (const k of Object.keys(expr)) { + const ch = expr[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') replaceId(it); + } else if (ch && typeof ch.type === 'string') { + replaceId(ch); + } + } + })(sub.value); + return; + } + for (const k of Object.keys(sub)) { + const ch = sub[k]; + if (Array.isArray(ch)) { + for (const it of ch) if (it && typeof it.type === 'string') replaceRefs(it); + } else if (ch && typeof ch.type === 'string') { + replaceRefs(ch); + } + } + })(stmt.body); + } + } + } + } + } + + if (hasModelGate) { + let gateFnName = null; + let gateGuardText = null; + for (const stmt of ast.body) { + if (stmt.type === 'FunctionDeclaration' && + stmt.params.length === 1 && + stmt.body?.type === 'BlockStatement' && + stmt.body.body.length > 0 && + code.slice(stmt.start, stmt.end).includes('model_unavailable_gate')) { + const s0 = stmt.body.body[0]; + if (s0.type === 'IfStatement' && code.slice(s0.start, s0.end).includes('CLAUDE_CODE_ENTRYPOINT')) { + gateFnName = stmt.id.name; + gateGuardText = code.slice(s0.start, s0.end); + } + } + } + for (const stmt of ast.body) { + if (gateFnName && + gateGuardText && + stmt.type === 'FunctionDeclaration' && + stmt.params.length === 0 && + stmt.body?.type === 'BlockStatement' && + stmt.body.body.length === 1 && + stmt.body.body[0].type === 'ReturnStatement' && + stmt.body.body[0].argument?.type === 'CallExpression' && + stmt.body.body[0].argument.callee?.name === gateFnName) { + edits.push({ + start: stmt.body.body[0].start, + end: stmt.body.body[0].start, + text: gateGuardText, + }); + } + if (stmt.type === 'FunctionDeclaration' && + stmt.params.length === 1 && + stmt.params[0]?.type === 'Identifier' && + stmt.body?.type === 'BlockStatement' && + stmt.body.body.length === 3 && + code.slice(stmt.start, stmt.end).includes('"fable[1m]"') && + code.slice(stmt.start, stmt.end).includes('new RegExp(')) { + const s1 = stmt.body.body[1]; + const s2 = stmt.body.body[2]; + if (s1.type === 'VariableDeclaration' && + s2.type === 'ReturnStatement') { + const declCode = code.slice(s1.declarations[0].init.start, s1.declarations[0].init.end); + const idName = s1.declarations[0].id.name; + const retExpr = code.slice(s2.argument.start, s2.argument.end); + const newReIdx = retExpr.indexOf('.exec('); + if (newReIdx !== -1 && retExpr.startsWith('new RegExp(')) { + const reCtor = retExpr.slice(0, newReIdx); + const execTail = retExpr.slice(newReIdx); + edits.push({ + start: stmt.start, + end: stmt.start, + text: `var __ccFableRe,__ccFableModels;`, + }); + edits.push({ + start: s1.start, + end: s2.end, + text: `let _m=y4().models;if(_m!==__ccFableModels||!__ccFableRe){let ${idName}=${declCode};__ccFableRe=${reCtor};__ccFableModels=_m}return __ccFableRe${execTail}`, + }); + } + } + } + } + } + + if (edits.length === 0) return { code, rewritten: 0 }; + let out = code; + for (const e of edits.sort((a, b) => b.start - a.start)) { + out = out.slice(0, e.start) + e.text + out.slice(e.end); + } + return { code: out, rewritten: edits.length }; +} + +const CHUNK_IMPORT_RE = /import\s*(?:([^;"'()]+)\s*from\s*)?"(\.\/chunk-[^"]+\.js)";[ \t]*\r?\n?/g; + +export function pruneRedundantBareImports(fileMap) { + const origGraph = new Map(); + const emptyMods = new Set(); + for (const [mod, code] of fileMap) { + if (code.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '').trim() === '') { + emptyMods.add(mod); + } + const imports = []; + for (const m of code.matchAll(CHUNK_IMPORT_RE)) { + imports.push({ + bare: !m[1], + spec: m[2], + start: m.index, + end: m.index + m[0].length, + }); + } + origGraph.set(mod, imports); + } + + // Tarjan's strongly connected components so cycles (e.g. from hoisted + // top-level requires) are condensed cleanly before computing reachability. + let index = 0; + const indices = new Map(); + const lowlink = new Map(); + const onStack = new Set(); + const stack = []; + const sccOf = new Map(); + const sccNodes = new Map(); + let sccCount = 0; + + function strongconnect(v) { + indices.set(v, index); + lowlink.set(v, index); + index++; + stack.push(v); + onStack.add(v); + for (const imp of (origGraph.get(v) || [])) { + const w = imp.spec; + if (!origGraph.has(w)) continue; + if (!indices.has(w)) { + strongconnect(w); + lowlink.set(v, Math.min(lowlink.get(v), lowlink.get(w))); + } else if (onStack.has(w)) { + lowlink.set(v, Math.min(lowlink.get(v), indices.get(w))); + } + } + if (lowlink.get(v) === indices.get(v)) { + const scc = []; + let w; + do { + w = stack.pop(); + onStack.delete(w); + scc.push(w); + sccOf.set(w, sccCount); + } while (w !== v); + sccNodes.set(sccCount, scc); + sccCount++; + } + } + + for (const mod of origGraph.keys()) { + if (!indices.has(mod)) strongconnect(mod); + } + + const sccClosureMemo = new Map(); + const toDropByMod = new Map(); + + function getSccClosure(id) { + if (sccClosureMemo.has(id)) return sccClosureMemo.get(id); + const nodes = sccNodes.get(id); + const covered = new Set(nodes); + sccClosureMemo.set(id, covered); + + if (nodes.length === 1) { + const mod = nodes[0]; + const drops = []; + for (const imp of (origGraph.get(mod) || [])) { + if (imp.bare && (covered.has(imp.spec) || emptyMods.has(imp.spec))) { + drops.push(imp); + continue; + } + const childScc = sccOf.get(imp.spec); + if (childScc !== undefined) { + for (const c of getSccClosure(childScc)) covered.add(c); + } + } + if (drops.length > 0) toDropByMod.set(mod, drops); + } else { + for (const mod of nodes) { + for (const imp of (origGraph.get(mod) || [])) { + const childScc = sccOf.get(imp.spec); + if (childScc !== undefined && childScc !== id) { + for (const c of getSccClosure(childScc)) covered.add(c); + } + } + } + } + return covered; + } + + for (let i = 0; i < sccCount; i++) getSccClosure(i); + + let prunedImports = 0; + let touchedFiles = 0; + for (const [mod, drops] of toDropByMod) { + let code = fileMap.get(mod); + for (let i = drops.length - 1; i >= 0; i--) { + const d = drops[i]; + code = code.slice(0, d.start) + code.slice(d.end); + } + fileMap.set(mod, code); + prunedImports += drops.length; + touchedFiles++; + } + + return { prunedImports, touchedFiles }; +} + // ────────────────────────────────────────────── // P1–P10 on split builds // @@ -674,10 +1632,15 @@ export async function patchSplitEsm({ extractDir, entryRel = 'cli.js' }) { const stats = { files: files.length, specifiers: 0, literals: 0, metaRequire: 0, rebrand: 0, hoisted: 0, hooksWorkers: 0, hooksWorkerUrls: 0, nodeFetch: 0, - importMeta: 0, pluginTestMarkers: 0, pluginTests: 0, ast: {}, + importMeta: 0, pluginTestMarkers: 0, pluginTests: 0, + winWhere: 0, winProcStart: 0, udsSweep: 0, parallelRepl: 0, caCertCache: 0, noopSlowOp: 0, + envConfigCache: 0, lazyEngineModel: 0, prunedBareImports: 0, + ast: {}, }; let leftover = 0; const bunOnly = []; + const fileMap = new Map(); + const beforeMap = new Map(); // Locate every patch site before touching anything, so a required one that // moved or disappeared surfaces as a report line instead of a zero counter. @@ -689,6 +1652,8 @@ export async function patchSplitEsm({ extractDir, entryRel = 'cli.js' }) { const path = join(extractDir, rel); const before = await readFile(path, 'utf8'); const prefix = prefixFor(dirname(rel)); + const normRel = './' + rel.split(sep).join('/'); + beforeMap.set(normRel, { path, before }); // Hoisting reads the BunFS specifiers, so it has to run before they are // rewritten — and before E3, which turns import.meta.require into a call @@ -723,6 +1688,38 @@ export async function patchSplitEsm({ extractDir, entryRel = 'cli.js' }) { code = metaProps.code; stats.importMeta += metaProps.rewritten; + const winWhere = rewriteWindowsWhere(code); + code = winWhere.code; + stats.winWhere += winWhere.rewritten; + + const winProc = rewriteWindowsProcessCreationTime(code); + code = winProc.code; + stats.winProcStart += winProc.rewritten; + + const udsSweep = rewriteUdsSweep(code); + code = udsSweep.code; + stats.udsSweep += udsSweep.rewritten; + + const parRepl = rewriteParallelReplImports(code); + code = parRepl.code; + stats.parallelRepl += parRepl.rewritten; + + const caCache = rewriteSystemCaCertCache(code); + code = caCache.code; + stats.caCertCache += caCache.rewritten; + + const slowOp = rewriteNoopSlowOpUsing(code); + code = slowOp.code; + stats.noopSlowOp += slowOp.rewritten; + + const envCache = rewriteEnvConfigCache(code); + code = envCache.code; + stats.envConfigCache += envCache.rewritten; + + const lazyEngine = rewriteLazyEngineInitAndModelPicker(code); + code = lazyEngine.code; + stats.lazyEngineModel += lazyEngine.rewritten; + if (mayContainPatchSite(code)) { const result = astPatch(code, 'module'); if (result.replacementCount > 0) { @@ -748,11 +1745,19 @@ export async function patchSplitEsm({ extractDir, entryRel = 'cli.js' }) { stats.rebrand++; } - if (code !== before) await writeFile(path, code); + fileMap.set(normRel, code); leftover += (code.match(new RegExp(ROOT_ALT, 'g')) || []).length; for (const name of bunOnlyImportMeta(code)) bunOnly.push(`${rel}: import.meta.${name}`); } + const pruned = pruneRedundantBareImports(fileMap); + stats.prunedBareImports = pruned.prunedImports; + + for (const [normRel, code] of fileMap) { + const info = beforeMap.get(normRel); + if (info && code !== info.before) await writeFile(info.path, code); + } + // Checked on what is about to ship, after every rewrite. An import.meta // property Node does not define reads as undefined without complaint, so // nothing downstream catches it — 2.1.281 shipped five such reads and diff --git a/scripts/fetch-and-process.mjs b/scripts/fetch-and-process.mjs index 742edaf..2d7a1ed 100644 --- a/scripts/fetch-and-process.mjs +++ b/scripts/fetch-and-process.mjs @@ -285,7 +285,8 @@ export async function fetchAndProcess({ process.exit(1); } console.log(` ✓ ${platform} — ${st.specifiers.toLocaleString()} specifiers, ` + - `${st.literals} runtime paths, ${st.nodeFetch} node-fetch, ${st.importMeta} import.meta, ${st.leftover} leftover`); + `${st.literals} runtime paths, ${st.nodeFetch} node-fetch, ${st.importMeta} import.meta, ` + + `${st.prunedBareImports.toLocaleString()} pruned bare imports, ${st.leftover} leftover`); extractions[platform] = { extractDir, entryRel, binPath }; } else { // Single-CJS: one file in, one patched file out. diff --git a/scripts/node-compat-patch.mjs b/scripts/node-compat-patch.mjs index 676a8f1..52ebbba 100644 --- a/scripts/node-compat-patch.mjs +++ b/scripts/node-compat-patch.mjs @@ -373,9 +373,9 @@ export function astPatch(code, sourceType = 'script') { }); // P5b: inject binary availability check after the env-check if-statement - // Uses "which" on unix, "where" on windows. If both bfs+ugrep are - // found, shadow mode proceeds; otherwise DP() returns false → Tool mode. - const binCheck = `if(typeof globalThis.__dpBinOk>"u"){try{let _wc=process.platform==="win32"?"where":"which";${REQ}("child_process").execFileSync(_wc,["bfs"],{encoding:"utf8",timeout:2e3});${REQ}("child_process").execFileSync(_wc,["ugrep"],{encoding:"utf8",timeout:2e3});globalThis.__dpBinOk=!0}catch{globalThis.__dpBinOk=!1}}if(!globalThis.__dpBinOk)return!1;`; + // Prefer pure-JS Bun.which when polyfill is loaded; fall back to which/where. + // If both bfs+ugrep are found, shadow mode proceeds; otherwise DP() returns false → Tool mode. + const binCheck = `if(typeof globalThis.__dpBinOk>"u"){try{if(typeof globalThis.Bun?.which==="function"){globalThis.__dpBinOk=Boolean(globalThis.Bun.which("bfs")&&globalThis.Bun.which("ugrep"))}else{let _wc=process.platform==="win32"?"where":"which";${REQ}("child_process").execFileSync(_wc,["bfs"],{encoding:"utf8",timeout:2e3});${REQ}("child_process").execFileSync(_wc,["ugrep"],{encoding:"utf8",timeout:2e3});globalThis.__dpBinOk=!0}}catch{globalThis.__dpBinOk=!1}}if(!globalThis.__dpBinOk)return!1;`; replacements.push({ start: s1.end, end: s1.end, @@ -406,11 +406,11 @@ export function astPatch(code, sourceType = 'script') { // Inject before the `return[` statement that builds the shell function array. // The return statement is always present and unique within AF_. - // We insert a try/catch that resolves the system binary via `which` - // and overwrites M (the fallback path variable). + // We insert a try/catch that resolves the system binary via `Bun.which` + // (or `which`/`where`) and overwrites M (the fallback path variable). const returnIdx = code.indexOf('return[', node.start); if (returnIdx !== -1 && returnIdx < node.end) { - const injection = `try{let _wc=process.platform==="win32"?"where":"which",_w=${REQ}("child_process").execFileSync(_wc,[${paramTarget}],{encoding:"utf8",timeout:2e3}).trim();if(_w&&${REQ}("fs").existsSync(_w))M=_w}catch{}`; + const injection = `try{let _w=typeof globalThis.Bun?.which==="function"?globalThis.Bun.which(${paramTarget}):${REQ}("child_process").execFileSync(process.platform==="win32"?"where":"which",[${paramTarget}],{encoding:"utf8",timeout:2e3}).trim().split(/\\r?\\n/)[0];if(_w&&${REQ}("fs").existsSync(_w))M=_w}catch{}`; replacements.push({ start: returnIdx, end: returnIdx, replacement: injection }); stats.p8 = true; } diff --git a/templates/bun-polyfill.js b/templates/bun-polyfill.js index 117a620..098681b 100644 --- a/templates/bun-polyfill.js +++ b/templates/bun-polyfill.js @@ -3,16 +3,288 @@ // Provides compatible implementations of Bun-specific APIs used by Claude Code 2.1.200+ if (typeof globalThis.Bun === "undefined") { + // Enable V8 bytecode compile cache as early as possible so dynamically + // imported split-ESM chunks (chunk-14fc6qh5.js, AppRoot, REPL, etc.) are + // cached on disk across invocations without requiring NODE_COMPILE_CACHE. + try { require("module").enableCompileCache?.(); } catch {} + + // Upstream's env config module supports a lazy Proxy mode behind this flag, + // avoiding ~500 eager Object.defineProperty calls during module evaluation. + process.env.CLAUDE_CODE_LAZY_ENV_GETTERS ??= "1"; + const crypto = require("crypto"); const cp = require("child_process"); const fs = require("fs"); const net = require("net"); + const os = require("os"); + const path = require("path"); const http = require("http"); const https = require("https"); const { Readable } = require("stream"); const util = require("util"); const { Worker: NodeWorker, isMainThread, parentPort } = require("node:worker_threads"); + // ────────────────────────────────────────────── + // Windows startup helpers: + // 1. Pre-warm self process creation time in the background during Stage 1 + // so Stage 5 UDS inbox / peer session checks resolve in 0ms instead of + // blocking for ~610-1,000ms on a cold PowerShell WMI query. + // 2. Disk-backed X509 validTo timestamp cache so system CA store filtering + // does not re-instantiate ~150 X509Certificate objects synchronously. + // 3. Pure-JS executable candidate lookup (__ccFindExecutableCandidates) + // used by both Bun.which and the patched Windows $Br lookup. + // ────────────────────────────────────────────── + if (process.platform === "win32" && isMainThread) { + const argv2 = process.argv[2] || ""; + const isFastExit = argv2 === "--version" || argv2 === "-v" || argv2 === "-V" || + argv2 === "--help" || argv2 === "-h"; + if (!isFastExit) { + let selfProcChild = null; + const selfProcPromise = new Promise((resolve) => { + try { + selfProcChild = cp.execFile( + "powershell.exe", + ["-NoProfile", "-Command", `(Get-Process -Id ${process.pid}).StartTime.Ticks`], + { timeout: 5000, windowsHide: true }, + (err, stdout) => { + selfProcChild = null; + const val = !err && stdout ? String(stdout).trim() || undefined : undefined; + if (val) globalThis.__ccSelfProcStartTicks = val; + resolve(val); + } + ); + selfProcChild.unref?.(); + } catch { + resolve(undefined); + } + }); + globalThis.__ccGetSelfProcStart = () => { + selfProcChild?.ref?.(); + return selfProcPromise; + }; + } + } + + let _caCache = null; + let _caCacheDirty = false; + let _caCacheFlushScheduled = false; + const _caCachePath = path.join(os.tmpdir(), "claude-code-ca-validto-v1.json"); + + function _fastCertKey(str) { + const s = String(str); + const len = s.length; + let h1 = 0x811c9dc5; + let h2 = 0x9e3779b9; + const step = len > 512 ? 4 : 1; + for (let i = 0; i < len; i += step) { + const c = s.charCodeAt(i); + h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0; + h2 = Math.imul(h2 ^ c, 0x85ebca6b) >>> 0; + } + return `${h1.toString(36)}_${h2.toString(36)}_${len.toString(36)}`; + } + + globalThis.__ccGetCertValidTo = function __ccGetCertValidTo(certPem, X509Ctor) { + if (_caCache === null) { + try { + const raw = fs.readFileSync(_caCachePath, "utf8"); + const parsed = JSON.parse(raw); + _caCache = parsed && typeof parsed === "object" ? parsed : {}; + } catch { + _caCache = {}; + } + } + const key = _fastCertKey(certPem); + const cached = _caCache[key]; + if (typeof cached === "number") { + return cached === -1 ? NaN : cached; + } + let ms = NaN; + try { + const cert = new X509Ctor(certPem); + ms = new Date(cert.validTo).getTime(); + } catch {} + _caCache[key] = Number.isNaN(ms) ? -1 : ms; + _caCacheDirty = true; + if (!_caCacheFlushScheduled) { + _caCacheFlushScheduled = true; + setImmediate(() => { + _caCacheFlushScheduled = false; + if (!_caCacheDirty || !_caCache) return; + _caCacheDirty = false; + try { + const keys = Object.keys(_caCache); + if (keys.length > 2048) { + for (let i = 0; i < keys.length - 1024; i++) delete _caCache[keys[i]]; + } + fs.writeFileSync(_caCachePath, JSON.stringify(_caCache)); + } catch {} + }).unref?.(); + } + return ms; + }; + + try { + const _tls = require("tls"); + const _origGetCACerts = _tls.getCACertificates; + if (typeof _origGetCACerts === "function") { + const _sysCaCachePath = path.join(os.tmpdir(), "claude-code-system-ca-v1.json"); + let _sysCaMem = null; + _tls.getCACertificates = function getCACertificates(type) { + if (type === "system") { + if (_sysCaMem) return _sysCaMem; + try { + const st = fs.statSync(_sysCaCachePath, { throwIfNoEntry: false }); + if (st && Date.now() - st.mtimeMs < 86_400_000) { + const parsed = JSON.parse(fs.readFileSync(_sysCaCachePath, "utf8")); + if (Array.isArray(parsed)) { + _sysCaMem = parsed; + return parsed; + } + } + } catch {} + const certs = _origGetCACerts.call(this, type); + if (Array.isArray(certs)) { + _sysCaMem = certs; + setImmediate(() => { + try { fs.writeFileSync(_sysCaCachePath, JSON.stringify(certs)); } catch {} + }).unref?.(); + } + return certs; + } + return _origGetCACerts.apply(this, arguments); + }; + } + } catch {} + + function isExecutableFile(filePath, isWin) { + try { + const st = fs.statSync(filePath, { throwIfNoEntry: false }); + if (!st || !st.isFile()) return false; + if (!isWin) { + fs.accessSync(filePath, fs.constants.X_OK); + if (process.getuid?.() === 0 && (st.mode & 0o111) === 0) return false; + } + return true; + } catch { + return false; + } + } + + function findExecutableCandidates(cmd, opts = {}) { + if (!cmd || typeof cmd !== "string") { + if (opts?.throwOnEmpty) { + const err = new Error("not found"); + err.status = 1; + throw err; + } + return []; + } + const cleanCmd = cmd.trim().replace(/^"+|"+$/g, ""); + if (!cleanCmd) { + if (opts?.throwOnEmpty) { + const err = new Error("not found"); + err.status = 1; + throw err; + } + return []; + } + const isWin = opts?.platform ? opts.platform === "win32" : process.platform === "win32"; + const pathMod = process.platform === "win32" ? path.win32 : path; + const pathDelim = isWin ? ";" : path.delimiter; + const cwd = opts?.cwd || process.cwd(); + const pathEnv = opts?.PATH !== undefined + ? String(opts.PATH ?? "") + : String(process.env.PATH ?? (isWin ? process.env.Path : "") ?? ""); + const pathextRaw = opts?.PATHEXT !== undefined + ? String(opts.PATHEXT ?? "") + : String(process.env.PATHEXT ?? (isWin ? process.env.Pathext : "") ?? ".COM;.EXE;.BAT;.CMD"); + const exts = isWin + ? pathextRaw + .split(";") + .map((x) => x.trim().toLowerCase()) + .filter(Boolean) + .map((x) => (x.startsWith(".") ? x : "." + x)) + : [""]; + const firstOnly = Boolean(opts?.firstOnly); + const results = []; + const seen = new Set(); + + const pushIfExec = (candidate) => { + const normKey = isWin ? candidate.toLowerCase() : candidate; + if (seen.has(normKey)) return false; + if (isExecutableFile(candidate, isWin)) { + seen.add(normKey); + results.push(candidate); + return true; + } + return false; + }; + + const hasSep = cleanCmd.includes("/") || (isWin && cleanCmd.includes("\\")); + if (hasSep) { + const base = pathMod.isAbsolute(cleanCmd) ? cleanCmd : pathMod.resolve(cwd, cleanCmd); + if (isWin) { + const lower = cleanCmd.toLowerCase(); + const dotIdx = lower.lastIndexOf("."); + const cmdExt = dotIdx > 0 ? lower.slice(dotIdx) : ""; + const names = cmdExt && exts.includes(cmdExt) + ? [base, ...exts.map((e) => base + e)] + : [...exts.map((e) => base + e), base]; + for (const cand of names) { + if (pushIfExec(cand) && firstOnly) return results; + } + } else { + pushIfExec(base); + } + } else { + const rawDirs = pathEnv ? pathEnv.split(pathDelim) : []; + const includeCwd = Boolean(opts?.includeCwd); + if (includeCwd) rawDirs.unshift(cwd); + const absCwd = pathMod.resolve(cwd); + const normCwd = isWin ? absCwd.toLowerCase() : absCwd; + const lower = cleanCmd.toLowerCase(); + const dotIdx = lower.lastIndexOf("."); + const cmdExt = dotIdx > 0 ? lower.slice(dotIdx) : ""; + const hasKnownWinExt = isWin && Boolean(cmdExt && exts.includes(cmdExt)); + const seenDirs = new Set(); + + for (const rawDir of rawDirs) { + const dir = isWin ? rawDir.trim().replace(/^"+|"+$/g, "") : rawDir.trim(); + if (!dir) continue; + const absDir = pathMod.isAbsolute(dir) ? pathMod.normalize(dir) : pathMod.resolve(cwd, dir); + const normDir = isWin ? absDir.toLowerCase() : absDir; + if (seenDirs.has(normDir)) continue; + seenDirs.add(normDir); + const isCwdDir = includeCwd && normDir === normCwd; + const shouldStopOnHit = firstOnly && !isCwdDir; + if (isWin) { + if (hasKnownWinExt) { + if (pushIfExec(pathMod.join(absDir, cleanCmd)) && shouldStopOnHit) return results; + } else { + for (const ext of exts) { + if (pushIfExec(pathMod.join(absDir, cleanCmd + ext))) { + if (shouldStopOnHit) return results; + if (firstOnly && isCwdDir) break; + } + } + } + } else { + if (pushIfExec(pathMod.join(absDir, cleanCmd)) && shouldStopOnHit) return results; + } + } + } + + if (results.length === 0 && opts?.throwOnEmpty) { + const err = new Error("not found"); + err.status = 1; + throw err; + } + return results; + } + + globalThis.__ccFindExecutableCandidates = findExecutableCandidates; + // ────────────────────────────────────────────── // Web Worker surface for the function-hooks host // @@ -340,9 +612,16 @@ if (typeof globalThis.Bun === "undefined") { }; bunHash.toString = () => "function hash() { [native code] }"; - // Load Anthropic-compatible ink implementations (bundled from source) - let _inkCompat = null; - try { _inkCompat = require("./bun-ink-compat.cjs"); } catch {} + // Load Anthropic-compatible ink implementations lazily on first call + let _inkCompat; + function getInkCompat() { + if (_inkCompat === undefined) { + try { _inkCompat = require("./bun-ink-compat.cjs"); } catch { _inkCompat = null; } + } + return _inkCompat; + } + + const _whichCache = new Map(); const ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; @@ -1390,18 +1669,21 @@ if (typeof globalThis.Bun === "undefined") { deepEquals, stripANSI: (str) => { - if (_inkCompat?.stripANSI) return _inkCompat.stripANSI(str); + const ink = getInkCompat(); + if (ink?.stripANSI) return ink.stripANSI(str); return typeof str === "string" ? str.replace(ANSI_RE, "") : str; }, stringWidth: (str, opts) => { - if (_inkCompat?.stringWidth) return _inkCompat.stringWidth(str); + const ink = getInkCompat(); + if (ink?.stringWidth) return ink.stringWidth(str); if (!str) return 0; return str.replace(ANSI_RE, "").length; }, wrapAnsi: (str, cols, opts) => { - if (_inkCompat?.wrapAnsi) return _inkCompat.wrapAnsi(str, cols, opts); + const ink = getInkCompat(); + if (ink?.wrapAnsi) return ink.wrapAnsi(str, cols, opts); if (!str || cols <= 0) return str; return str; }, @@ -1410,7 +1692,8 @@ if (typeof globalThis.Bun === "undefined") { // drops the frame and panels sit on stale content — the task output pane // showing "Loading output…" indefinitely. sliceAnsi: (str, start, end) => { - if (_inkCompat?.sliceAnsi) return _inkCompat.sliceAnsi(str, start, end); + const ink = getInkCompat(); + if (ink?.sliceAnsi) return ink.sliceAnsi(str, start, end); return typeof str === "string" ? str.slice(start, end) : str; }, @@ -1446,7 +1729,8 @@ if (typeof globalThis.Bun === "undefined") { JSONL: { parseChunk: null }, - which: (cmd) => { + which: (cmd, opts) => { + if (!cmd || typeof cmd !== "string") return null; // Vendor directory lookup for bundled binaries. // Restores the semantics of USE_BUILTIN_RIPGREP: // unset/1/true (default) → prefer vendor rg, fall back to system PATH @@ -1454,13 +1738,12 @@ if (typeof globalThis.Bun === "undefined") { // In Bun SEA mode, builtin rg lived inside the multicall binary via // Bun.isStandaloneExecutable. After SEA extraction for Node.js, the // embedded branch never fires, so vendor lookup happens here instead. - if (cmd === "rg" || cmd === "rg.exe") { + if ((cmd === "rg" || cmd === "rg.exe") && opts?.PATH === undefined) { const useBuiltin = process.env.USE_BUILTIN_RIPGREP; const disabled = useBuiltin !== undefined && ["0", "false", "no", "off"].includes(String(useBuiltin).toLowerCase().trim()); if (!disabled) { try { - const path = require("path"); const archDir = process.arch + "-" + process.platform; const bin = process.platform === "win32" ? "rg.exe" : "rg"; const vendorPath = path.join(__dirname, "vendor", "ripgrep", archDir, bin); @@ -1468,13 +1751,31 @@ if (typeof globalThis.Bun === "undefined") { } catch {} } } - // System PATH lookup (execFileSync avoids shell injection vs execSync) - try { - const whichCmd = process.platform === "win32" ? "where" : "which"; - return cp.execFileSync(whichCmd, [cmd], - { encoding: "utf8", stdio: ["pipe", "pipe", "ignore"], timeout: 5000 } - ).trim().split("\n")[0] || null; - } catch { return null; } + // Pure-JS PATH lookup with in-memory memoization (zero subprocess spawns) + const isWin = process.platform === "win32"; + const pathEnv = opts?.PATH !== undefined + ? String(opts.PATH ?? "") + : String(process.env.PATH ?? (isWin ? process.env.Path : "") ?? ""); + const pathextEnv = isWin + ? String(opts?.PATHEXT ?? process.env.PATHEXT ?? process.env.Pathext ?? ".COM;.EXE;.BAT;.CMD") + : ""; + const cwd = opts?.cwd || process.cwd(); + const cacheKey = `${cmd}\0${pathEnv}\0${pathextEnv}\0${cwd}`; + if (_whichCache.has(cacheKey)) { + const cached = _whichCache.get(cacheKey); + if (cached === null || isExecutableFile(cached, isWin)) return cached; + _whichCache.delete(cacheKey); + } + const hits = findExecutableCandidates(cmd, { + PATH: pathEnv, + PATHEXT: pathextEnv, + cwd, + firstOnly: true, + }); + const resolved = hits[0] || null; + if (_whichCache.size >= 512) _whichCache.clear(); + _whichCache.set(cacheKey, resolved); + return resolved; }, spawn: bunSpawn, diff --git a/test/startup-perf-patches.test.mjs b/test/startup-perf-patches.test.mjs new file mode 100644 index 0000000..406f70c --- /dev/null +++ b/test/startup-perf-patches.test.mjs @@ -0,0 +1,323 @@ +import assert from 'node:assert/strict'; +import { X509Certificate } from 'node:crypto'; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { delimiter, join } from 'node:path'; +import test from 'node:test'; +import { pathToFileURL } from 'node:url'; +import * as acorn from 'acorn'; +import { + buildPolyfillModule, + pruneRedundantBareImports, + rewriteEnvConfigCache, + rewriteLazyEngineInitAndModelPicker, + rewriteNoopSlowOpUsing, + rewriteParallelReplImports, + rewriteSystemCaCertCache, + rewriteUdsSweep, + rewriteWindowsProcessCreationTime, + rewriteWindowsWhere, +} from '../scripts/esm-chunk-patch.mjs'; +import { astPatch } from '../scripts/node-compat-patch.mjs'; + +test.before(async () => { + const dir = await mkdtemp(join(tmpdir(), 'cc-startup-polyfill-')); + const path = join(dir, 'bun-polyfill.mjs'); + const source = await readFile(new URL('../templates/bun-polyfill.js', import.meta.url), 'utf8'); + await writeFile(path, buildPolyfillModule(source)); + await import(pathToFileURL(path).href); + await rm(dir, { recursive: true, force: true }); +}); + +test('polyfill sets CLAUDE_CODE_LAZY_ENV_GETTERS default to 1', () => { + assert.equal(process.env.CLAUDE_CODE_LAZY_ENV_GETTERS, '1'); +}); + +test('Bun.which and __ccFindExecutableCandidates resolve executables without spawning', async (t) => { + const dir = await mkdtemp(join(tmpdir(), 'cc-which-')); + t.after(() => rm(dir, { recursive: true, force: true })); + + const binA = join(dir, 'bin-a'); + const binB = join(dir, 'bin-b'); + await mkdir(binA, { recursive: true }); + await mkdir(binB, { recursive: true }); + + // Windows mode test (cross-platform via opts.platform = 'win32') + const winToolA = join(binA, 'mytool.cmd'); + const winToolB = join(binB, 'mytool.exe'); + await writeFile(winToolA, '@echo off\r\n'); + await writeFile(winToolB, 'MZ'); + + const winCandidates = globalThis.__ccFindExecutableCandidates('mytool', { + platform: 'win32', + PATH: `"${binA}";${binB}`, + PATHEXT: '.COM;.EXE;.BAT;.CMD', + cwd: dir, + }); + assert.deepEqual(winCandidates, [winToolA, winToolB]); + + // With includeCwd + firstOnly, keeps the cwd match (so $Br knows cwd had a shadow) + // and stops right after the first non-cwd PATH match (skipping binB). + const cwdShadow = join(dir, 'mytool.exe'); + await writeFile(cwdShadow, 'MZ'); + const firstNonCwd = globalThis.__ccFindExecutableCandidates('mytool', { + platform: 'win32', + PATH: `"${binA}";${binB}`, + PATHEXT: '.COM;.EXE;.BAT;.CMD', + cwd: dir, + includeCwd: true, + firstOnly: true, + }); + assert.deepEqual(firstNonCwd, [cwdShadow, winToolA]); + + // Empty lookup with throwOnEmpty sets status=1 (matching where.exe miss) + assert.throws( + () => globalThis.__ccFindExecutableCandidates('nonexistent-tool-xyz', { + platform: 'win32', + PATH: binA, + throwOnEmpty: true, + }), + (err) => err && err.status === 1, + ); + + if (process.platform !== 'win32') { + const posixTool = join(binA, 'my-posix-tool'); + await writeFile(posixTool, '#!/bin/sh\necho ok\n'); + await chmod(posixTool, 0o755); + + const found = Bun.which('my-posix-tool', { PATH: `${binA}${delimiter}${binB}`, cwd: dir }); + assert.equal(found, posixTool); + assert.equal(Bun.which('missing-posix-tool', { PATH: binA, cwd: dir }), null); + } +}); + +test('rewriteWindowsWhere replaces where.exe execFileSync while preserving cwd exclusion and extension filter', () => { + const sample = [ + 'function $Br(e,t=!1){', + 'let c=rQn("SYSTEMROOT")||"C:\\\\Windows",d=m(c,"System32","where.exe");', + 'try{let i=p(d,[e],{stdio:"pipe",encoding:"utf8",timeout:h,windowsHide:!0,env:process.env}).trim().split(/\\r?\\n/).filter(Boolean),a=process.cwd(),l=!1;', + 'for(let r of i){if(u(r))continue;if(pQn(r,a)){l=!0;continue}if(!b(r))continue;return n.remember(e,r),r}', + 'if(i.length>0&&!l)n.remember(e,null);return null}catch(s){if(v(s))n.remember(e,null);return null}}', + ].join(''); + const { code, rewritten } = rewriteWindowsWhere(sample); + assert.equal(rewritten, 1); + assert.ok(code.includes('globalThis.__ccFindExecutableCandidates(e,{includeCwd:!0,firstOnly:!0,throwOnEmpty:!0})')); + assert.ok(code.includes('if(pQn(r,a)){l=!0;continue}')); + assert.doesNotThrow(() => acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })); +}); + +test('rewriteWindowsProcessCreationTime rewrites WMI CreationDate to Get-Process StartTime and adds 1ms tolerance', async () => { + const sample = [ + 'function YWe(e){try{if(u())return KUt(e)?.toString();return smn(`powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\\\"ProcessId=${e}\\\\").CreationDate.Ticks"`,{timeout:1000})?.trim()||void 0}catch{return}}', + 'function GEe(e,t){if(t===e)return!0;let n=Number(e),r=Number(t);return Number.isFinite(n)&&Number.isFinite(r)&&n>300000000000000000!==r>300000000000000000}', + 'async function S(e,t){let n=t===void 0?{}:{env:t,extendEnv:!1};try{let o="powershell.exe";let s=await ct(o,["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.Ticks`],{timeout:1e4,...n});return s.stdout?.trim()}catch{return}}', + 'async function mQe(e){let r=await ct("powershell.exe",["-NoProfile","-Command",`[DateTimeOffset]::new((Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate).ToUnixTimeMilliseconds()`],{timeout:1000});return r}', + 'export{YWe,GEe,S};', + ].join(''); + const { code, rewritten } = rewriteWindowsProcessCreationTime(sample); + assert.equal(rewritten, 6); + assert.ok(!code.includes('CreationDate')); + assert.ok(code.includes('(Get-Process -Id ${e}).StartTime.Ticks')); + assert.ok(code.includes('Math.abs(n-r)<1e4')); + assert.doesNotThrow(() => acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const mod = await import(`data:text/javascript,${encodeURIComponent(code)}`); + // WMI truncates last digit to 0 (e.g. 638982123456789000 vs 638982123456789007) + assert.equal(mod.GEe('638982123456789000', '638982123456789007'), true); + // Different processes separated by > 1ms (e.g. 50,000 ticks = 5ms) must not match + assert.equal(mod.GEe('638982123456700000', '638982123456750000'), false); +}); + +test('rewriteUdsSweep defers stale .tmp sweep off the critical startup path', () => { + const sample = 'async function o2s(e,n,r,{sweepPermitted:i}){let c=Qte();await pe(c,{recursive:!0,mode:448}),await Ee(c,i);return c}'; + const { code, rewritten } = rewriteUdsSweep(sample); + assert.equal(rewritten, 1); + assert.ok(code.includes('setTimeout(()=>{Ee(c,i).catch(()=>{})},2e3).unref?.()')); + assert.doesNotThrow(() => acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })); +}); + +test('rewriteParallelReplImports converts sequential AppRoot/REPL imports and wires interactive preload', () => { + const sampleRepl = 'async function h5s(d,a,r,s){let{AppRoot:i}=await import("./chunk-pxd59j4h.js"),{REPL:n}=await import("./chunk-z2sjg6vz.js");return[i,n]}'; + const outRepl = rewriteParallelReplImports(sampleRepl); + assert.equal(outRepl.rewritten, 2); + assert.ok(outRepl.code.includes('globalThis.__ccPreloadRepl??=')); + assert.ok(outRepl.code.includes('let[{AppRoot:i},{REPL:n}]=await(globalThis.__ccPreloadRepl?globalThis.__ccPreloadRepl():Promise.all([import("./chunk-pxd59j4h.js"),import("./chunk-z2sjg6vz.js")]));')); + assert.doesNotThrow(() => acorn.parse(outRepl.code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const sampleSetup = 'async function kYr(){if(!we()){let h=req();h.startPreviewBrowserDiscovery()}yo("action_before_setup");let{setup:_d}=await import("./chunk-g6swey1c.js");return _d}'; + const outSetup = rewriteParallelReplImports(sampleSetup); + assert.equal(outSetup.rewritten, 2); + assert.ok(outSetup.code.includes('(globalThis.__ccIsInteractive=!0,h.startPreviewBrowserDiscovery())')); + assert.ok(outSetup.code.includes('(globalThis.__ccIsInteractive&&globalThis.__ccPreloadRepl?.(),await import("./chunk-g6swey1c.js"))')); + assert.doesNotThrow(() => acorn.parse(outSetup.code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const sampleOnboarding = 'async function Zi(){let{createRoot:ko}=await import("./chunk-c71b3689.js");t("showSetupScreens");return ko}'; + const outOnboarding = rewriteParallelReplImports(sampleOnboarding); + assert.equal(outOnboarding.rewritten, 1); + assert.ok(outOnboarding.code.includes('(globalThis.__ccPreloadRepl?.(),await import("./chunk-c71b3689.js"))')); + assert.doesNotThrow(() => acorn.parse(outOnboarding.code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const sampleTzr = [ + 'async function tzr(o,d,h,M,C){let k=AF(o,d);XDo(),wYr(h,M,C);', + 'await Promise.race([o.waitUntilExit()]);await rwr.of(h.host).runBeforeInteractiveShutdown()}', + ].join(''); + const outTzr = rewriteParallelReplImports(sampleTzr); + assert.equal(outTzr.rewritten, 1); + assert.ok(outTzr.code.includes('XDo(),setImmediate(()=>wYr(h,M,C));')); + assert.doesNotThrow(() => acorn.parse(outTzr.code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const sampleOtel = 'function O3s(o,R,b){import("./chunk-g6swey1c.js").then((_)=>_.maybePrewarmRecallIndex(o));setImmediate(KDe,b)}'; + const outOtel = rewriteParallelReplImports(sampleOtel); + assert.equal(outOtel.rewritten, 1); + assert.ok(outOtel.code.includes('setTimeout(KDe,1500,b).unref?.()')); + assert.doesNotThrow(() => acorn.parse(outOtel.code, { ecmaVersion: 'latest', sourceType: 'module' })); +}); + +test('rewriteNoopSlowOpUsing strips no-op tagged template using declarations', () => { + const sample = 'function _(e,n,r){using i=Wh`JSON.stringify(${Ae(e)})`;return JSON.stringify(e,n,r)}'; + const { code, rewritten } = rewriteNoopSlowOpUsing(sample); + assert.equal(rewritten, 1); + assert.equal(code, 'function _(e,n,r){return JSON.stringify(e,n,r)}'); + assert.doesNotThrow(() => acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })); +}); + +test('rewriteSystemCaCertCache uses __ccGetCertValidTo cache and preserves expired cert filtering', async () => { + const sample = [ + 'export function Ln(e,Ue){', + 'let{X509Certificate:n}=Ue("crypto"),r=Date.now(),o=0,s=e.filter((i)=>{try{let c=new n(i),u=new Date(c.validTo).getTime();if(Number.isNaN(u)||u>r)return!0;return o++,!1}catch{return!0}});', + 'return{s,o}}', + ].join(''); + const { code, rewritten } = rewriteSystemCaCertCache(sample); + assert.equal(rewritten, 1); + assert.ok(code.includes('globalThis.__ccGetCertValidTo(i,n)')); + assert.doesNotThrow(() => acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const mod = await import(`data:text/javascript,${encodeURIComponent(code)}`); + let ctorCalls = 0; + class FakeX509 { + constructor(pem) { + ctorCalls++; + this.validTo = pem.includes('EXPIRED') ? '2020-01-01T00:00:00Z' : '2099-01-01T00:00:00Z'; + } + } + const nonce = `${Date.now()}_${Math.random()}`; + const certs = [ + `-----BEGIN CERTIFICATE-----\nVALID_TEST_CERT_${nonce}\n-----END CERTIFICATE-----`, + `-----BEGIN CERTIFICATE-----\nEXPIRED_TEST_CERT_${nonce}\n-----END CERTIFICATE-----`, + ]; + const first = mod.Ln(certs, () => ({ X509Certificate: FakeX509 })); + assert.equal(first.s.length, 1); + assert.equal(first.o, 1); + assert.equal(ctorCalls, 2); + + // Second invocation hits the cache without constructing FakeX509 again + const second = mod.Ln(certs, () => ({ X509Certificate: FakeX509 })); + assert.equal(second.s.length, 1); + assert.equal(second.o, 1); + assert.equal(ctorCalls, 2); +}); + +test('pruneRedundantBareImports removes transitive and empty-chunk bare imports while preserving exact DFS post-order', () => { + const fileMap = new Map([ + ['./chunk-empty.js', '// @bun @bytecode\n// comment only\n'], + ['./chunk-leaf.js', 'export const x = 1;\n'], + ['./chunk-mid.js', 'import { x } from "./chunk-leaf.js";\nexport const y = x + 1;\n'], + ['./chunk-top.js', 'import "./chunk-empty.js";\nimport { y } from "./chunk-mid.js";\nimport "./chunk-leaf.js";\nimport "./chunk-leaf.js";\nexport { y };\n'], + ]); + const { prunedImports, touchedFiles } = pruneRedundantBareImports(fileMap); + assert.equal(prunedImports, 3); + assert.equal(touchedFiles, 1); + assert.equal(fileMap.get('./chunk-top.js'), 'import { y } from "./chunk-mid.js";\nexport { y };\n'); +}); + +test('P5 and P8 use Bun.which when available', () => { + const p5Src = 'function DP(){if(!isEnvTruthy("true"))return!1;return process.env.CLAUDE_CODE_ENTRYPOINT}'; + const p5Out = astPatch(p5Src, 'module'); + assert.equal(p5Out.stats.p5, true); + assert.ok(p5Out.code.includes('globalThis.Bun.which("bfs")')); + + const p8Src = 'function AF_(e,t){let M="/path/claude";return["ARGV0=bfs","_cc_bin","command"]}'; + const p8Out = astPatch(p8Src, 'module'); + assert.equal(p8Out.stats.p8, true); + assert.ok(p8Out.code.includes('globalThis.Bun.which(t)')); +}); + +test('rewriteEnvConfigCache caches process.env reads within a microtask turn and invalidates on set/unset', async () => { + const sample = [ + 'var PN="CLAUDE_CODE_LAZY_ENV_GETTERS";', + 'function N5(t,o,_=!0){let E={};return Object.defineProperties(E,{set:{value:(r,n)=>{process.env[r]=String(n)}},unset:{value:(r)=>{delete process.env[r]}}}),E}', + 'function Et(t,o,_){let E=_,r;return()=>{let n=process.env[t];if(n!==E)r=o.parse(n),E=n;return r}}', + 'export{N5,Et};', + ].join(''); + const { code, rewritten } = rewriteEnvConfigCache(sample); + assert.equal(rewritten, 3); + assert.ok(code.includes('__ccEnvGen')); + assert.doesNotThrow(() => acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const mod = await import(`data:text/javascript,${encodeURIComponent(code)}`); + let parseCount = 0; + const schema = { parse: (v) => { parseCount++; return v ?? 'default'; } }; + const cfg = mod.N5({}, null); + const getter = mod.Et('CC_TEST_ENV_CACHE_VAR', schema, cfg); + delete process.env.CC_TEST_ENV_CACHE_VAR; + + assert.equal(getter(), 'default'); + assert.equal(getter(), 'default'); + assert.equal(parseCount, 1); + + cfg.set('CC_TEST_ENV_CACHE_VAR', 'updated'); + assert.equal(getter(), 'updated'); + assert.equal(parseCount, 2); + + cfg.unset('CC_TEST_ENV_CACHE_VAR'); + assert.equal(getter(), 'default'); + assert.equal(parseCount, 3); +}); + +test('rewriteLazyEngineInitAndModelPicker defers Vet init, short-circuits EUn, and memoizes Wc RegExp', async () => { + const sampleEngine = [ + 'function Ys(e){return{models:e.models??[],unavailable_models:e.unavailableModels??[],account:e.account}}', + 'export function Vet({commands:r=[],models:o=[],unavailableModels:n=[],agents:f=[],account:h={},outputStyle:S,availableOutputStyles:T}){', + 'let Ee=Ys({commands:typeof r==="function"?r():r,models:typeof o==="function"?o():o,unavailableModels:typeof n==="function"?n():n,agents:typeof f==="function"?f():f,account:h,outputStyle:S,availableOutputStyles:T}),It=1;', + 'return{initializationResult:()=>Promise.resolve(Ee),accountInfo:()=>Promise.resolve(Ee.account),supportedModels:()=>Promise.resolve(typeof o==="function"?o():Ee.models),supportedCommands:()=>Promise.resolve(typeof r==="function"?r():Ee.commands),supportedAgents:()=>Promise.resolve(typeof f==="function"?f():Ee.agents)}}', + ].join(''); + const outEngine = rewriteLazyEngineInitAndModelPicker(sampleEngine); + assert.ok(outEngine.rewritten >= 6); + assert.doesNotThrow(() => acorn.parse(outEngine.code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const engineMod = await import(`data:text/javascript,${encodeURIComponent(outEngine.code)}`); + let modelsCalled = 0; + let unavailCalled = 0; + const handle = engineMod.Vet({ + models: () => { modelsCalled++; return ['m1']; }, + unavailableModels: () => { unavailCalled++; return ['u1']; }, + account: { id: 'acc' }, + }); + // Neither models() nor unavailableModels() runs synchronously during Vet() creation! + assert.equal(modelsCalled, 0); + assert.equal(unavailCalled, 0); + const initRes = await handle.initializationResult(); + assert.deepEqual(initRes.models, ['m1']); + assert.equal(modelsCalled, 1); + assert.equal(unavailCalled, 1); + + const sampleModel = [ + 'var zb=new Set(["claude-vscode"]),a={CLAUDE_CODE_ENTRYPOINT:"cli"},bl="fable-default";', + 'let peCalls=0,y4Calls=0;const list=[{id:"claude-fable-4",family:"fable"}];', + 'function y4(){y4Calls++;return{models:list}}', + 'function _Pe(){peCalls++;return[{disabled:!0}]}', + 'function Kho(e){if(!zb.has(a.CLAUDE_CODE_ENTRYPOINT??""))return[];let r=e.length;return g("model_unavailable_gate",r),e}', + 'function EUn(){return Kho(_Pe())}', + 'function Wc(e){if(e==="fable"||e==="fable[1m]"){return bl}let r=y4().models.filter((s)=>s.family==="fable").map((s)=>s.id).sort((s,h)=>h.length-s.length);return new RegExp(`(?:^|[./])(${r.join("|")})(?:[-@]\\\\d{8})?$`,"i").exec(e)?.[1]?.toLowerCase()}', + 'export{EUn,Wc,peCalls,y4Calls};', + ].join(''); + const outModel = rewriteLazyEngineInitAndModelPicker(sampleModel); + assert.equal(outModel.rewritten, 3); + assert.doesNotThrow(() => acorn.parse(outModel.code, { ecmaVersion: 'latest', sourceType: 'module' })); + + const modelMod = await import(`data:text/javascript,${encodeURIComponent(outModel.code)}`); + assert.deepEqual(modelMod.EUn(), []); + assert.equal(modelMod.peCalls, 0); + assert.equal(modelMod.Wc('claude-fable-4-20260101'), 'claude-fable-4'); + assert.equal(modelMod.Wc('claude-fable-4-20260101'), 'claude-fable-4'); +});