tweakcc-fixed 1.0.5 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +0,0 @@
1
- import{$ as e,D as t,S as n,c as r,d as i,et as a,f as o,l as s,m as c,n as l,r as u,tt as d,x as f}from"./config-5W52dXMg.mjs";import{Box as p,Text as m,render as h,useInput as g}from"ink";import _,{useState as ee}from"react";import*as te from"node:os";import v from"node:os";import*as y from"node:fs/promises";import b from"node:fs/promises";import x from"path";import{jsx as S,jsxs as C}from"react/jsx-runtime";import ne from"which";import{globbySync as w}from"globby";const re=(()=>{let e=[],t=process.platform==`win32`?v.homedir().replace(/\\/g,`/`):v.homedir(),n=`node_modules/@anthropic-ai/claude-code`,r=(t,n=!1)=>{if(n)try{let n=w(t,{onlyFiles:!1});e.push({pattern:t,isGlob:!0,expandedPaths:n})}catch(n){n instanceof Error&&`code`in n&&(n.code===`EACCES`||n.code===`EPERM`)?o(`Permission denied accessing: ${t} (${n.code})`):o(`Error expanding glob pattern "${t}": ${n instanceof Error?n.message:String(n)}`),e.push({pattern:t,isGlob:!0,expandedPaths:[]})}else e.push({pattern:t,isGlob:!1,expandedPaths:[t]})};return r(`${v.homedir()}/.claude/local/${n}`),process.env.NPM_PREFIX&&r(`${process.env.NPM_PREFIX}/lib/${n}`),process.env.N_PREFIX&&r(`${process.env.N_PREFIX}/lib/${n}`),process.env.VOLTA_HOME&&r(`${process.env.VOLTA_HOME}/lib/${n}`),process.env.FNM_DIR&&r(`${process.env.FNM_DIR}/lib/${n}`),process.env.NVM_DIR&&r(`${process.env.NVM_DIR}/lib/${n}`),process.env.NODENV_ROOT&&r(`${process.env.NODENV_ROOT}/versions/*/lib/${n}`,!0),process.env.NVS_HOME&&r(`${process.env.NVS_HOME}/node/*/*/lib/${n}`,!0),process.env.ASDF_DATA_DIR&&r(`${process.env.ASDF_DATA_DIR}/installs/nodejs/*/lib/${n}`,!0),process.platform==`win32`?(r(`${t}/AppData/Local/Volta/tools/image/packages/@anthropic-ai/claude-code/${n}`),r(`${t}/AppData/Roaming/npm/${n}`),r(`${t}/AppData/Roaming/nvm/*/${n}`,!0),r(`${t}/AppData/Local/Yarn/config/global/${n}`),r(`${t}/AppData/Local/pnpm/global/*/${n}`,!0),r(`C:/nvm4w/nodejs/${n}`),r(`${t}/n/versions/node/*/lib/${n}`,!0),r(`${t}/AppData/Roaming/Yarn/config/global/${n}`),r(`${t}/AppData/Roaming/pnpm-global/${n}`),r(`${t}/AppData/Roaming/pnpm-global/*/${n}`,!0),r(`${t}/.bun/install/global/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/AppData/Local/Bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/AppData/Local/fnm_multishells/*/node_modules/${n}`,!0),r(`${t}/AppData/Local/mise/installs/node/*/${n}`,!0),r(`${t}/AppData/Local/mise/installs/npm-anthropic-ai-claude-code/*/${n}`,!0)):(process.platform==`darwin`&&(r(`${t}/Library/${n}`),r(`/opt/local/lib/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/Library/Caches/bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0)),r(`${t}/.local/lib/${n}`),r(`${t}/.local/share/${n}`),r(`${t}/.npm-global/lib/${n}`),r(`${t}/.npm-packages/lib/${n}`),r(`${t}/.npm/lib/${n}`),r(`${t}/npm/lib/${n}`),r(`/etc/${n}`),r(`/lib/${n}`),r(`/opt/node/lib/${n}`),r(`/usr/lib/${n}`),r(`/usr/local/lib/${n}`),r(`/usr/share/${n}`),r(`/var/lib/${n}`),r(`/opt/homebrew/lib/${n}`),r(`${t}/.linuxbrew/lib/${n}`),r(`${t}/.config/yarn/global/${n}`),r(`${t}/.yarn/global/${n}`),r(`${t}/.bun/install/global/${n}`),r(`${t}/.pnpm-global/${n}`),r(`${t}/.pnpm-global/*/${n}`,!0),r(`${t}/pnpm-global/${n}`),r(`${t}/pnpm-global/*/${n}`,!0),r(`${t}/.local/share/pnpm/global/${n}`),r(`${t}/.local/share/pnpm/global/*/${n}`,!0),r(`${t}/.bun/install/global/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/.local/share/bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`/usr/local/n/versions/node/*/lib/${n}`,!0),r(`${t}/n/versions/node/*/lib/${n}`,!0),r(`${t}/n/lib/${n}`),r(`${t}/.volta/tools/image/node/*/lib/${n}`,!0),r(`${t}/.fnm/node-versions/*/installation/lib/${n}`,!0),r(`${t}/.local/state/fnm_multishells/*/lib/${n}`,!0),r(`/usr/local/nvm/versions/node/*/lib/${n}`,!0),r(`/usr/local/share/nvm/versions/node/*/lib/${n}`,!0),r(`${t}/.nvm/versions/node/*/lib/${n}`,!0),r(`${t}/.nodenv/versions/*/lib/${n}`,!0),r(`${t}/.nvs/*/lib/${n}`,!0),r(`${t}/.asdf/installs/nodejs/*/lib/${n}`,!0),process.env.MISE_DATA_DIR&&r(`${process.env.MISE_DATA_DIR}/installs/node/*/lib/${n}`,!0),r(`${t}/.local/share/mise/installs/node/*/lib/${n}`,!0),process.env.MISE_DATA_DIR&&r(`${process.env.MISE_DATA_DIR}/installs/npm-anthropic-ai-claude-code/*/lib/${n}`,!0),r(`${t}/.local/share/mise/installs/npm-anthropic-ai-claude-code/*/lib/${n}`,!0)),process.platform==`win32`&&e.forEach(e=>{e.pattern=e.pattern.replace(/\//g,`\\`),e.expandedPaths=e.expandedPaths.map(e=>e.replace(/\//g,`\\`))}),e})().flatMap(e=>e.expandedPaths),ie=(()=>{let e=process.platform===`win32`?v.homedir().replace(/\\/g,`/`):v.homedir(),t=[],n=(e,n=!1)=>{if(n)try{let n=w(e,{onlyFiles:!0});t.push({pattern:e,isGlob:!0,expandedPaths:n})}catch(n){n instanceof Error&&`code`in n&&(n.code===`EACCES`||n.code===`EPERM`)?o(`Permission denied accessing: ${e} (${n.code})`):o(`Error expanding glob pattern "${e}": ${n instanceof Error?n.message:String(n)}`),t.push({pattern:e,isGlob:!0,expandedPaths:[]})}else t.push({pattern:e,isGlob:!1,expandedPaths:[e]})};return n(`${e}/.local/bin/claude`),n(`${e}/.local/share/claude/versions/*`,!0),process.platform===`win32`&&t.forEach(e=>{e.pattern=e.pattern.replace(/\//g,`\\`),e.expandedPaths=e.expandedPaths.map(e=>e.replace(/\//g,`\\`))}),t})().flatMap(e=>e.expandedPaths);var T=class extends Error{constructor(e){super(e),this.name=`InstallationDetectionError`}};let E=null;async function ae(){return E||=(async()=>{try{let{WASMagic:e}=await import(`wasmagic`);return await e.create()}catch(e){return o(`WASMagic initialization failed (likely SIMD unsupported on this CPU):`,e),o(`Using fallback file type detection`),null}})(),E}const oe=Buffer.from([127,69,76,70]),se=Buffer.from([254,237,250,206]),ce=Buffer.from([254,237,250,207]),D=Buffer.from([206,250,237,254]),O=Buffer.from([207,250,237,254]),k=Buffer.from([202,254,186,190]),A=Buffer.from([77,90]);function j(e){if(e.length===0)return null;if(e[0]===35&&e[1]===33&&e.subarray(0,Math.min(256,e.length)).toString(`utf8`).split(`
2
- `)[0].includes(`node`))return o(`detectFileTypeFallback: Detected JavaScript via shebang`),`javascript`;if(e.length>=4){let t=e.subarray(0,4);if(t.equals(oe))return o(`detectFileTypeFallback: Detected ELF binary`),`binary`;if(t.equals(se)||t.equals(ce)||t.equals(D)||t.equals(O)||t.equals(k))return o(`detectFileTypeFallback: Detected Mach-O binary`),`binary`}if(e.length>=2&&e.subarray(0,2).equals(A))return o(`detectFileTypeFallback: Detected PE binary`),`binary`;let t=Math.min(512,e.length),n=0,r=0;for(let i=0;i<t;i++){let t=e[i];(t>=32&&t<=126||t===9||t===10||t===13)&&n++,t===0&&r++}if(r>0)return o(`detectFileTypeFallback: Detected binary (${r} null bytes in first ${t} bytes)`),`binary`;let i=n/t;return i>.9?(o(`detectFileTypeFallback: Detected JavaScript via text heuristic (${Math.round(i*100)}% printable)`),`javascript`):(o(`detectFileTypeFallback: Unknown file type (${Math.round(i*100)}% printable)`),null)}async function M(e,t=4096){try{let n=await b.open(e,`r`);try{let e=Buffer.allocUnsafe(t),{bytesRead:r}=await n.read({buffer:e,position:0,length:t});return r<=0?null:e.subarray(0,r)}finally{await n.close()}}catch(e){return o(`Failed to read file prefix:`,e),null}}async function N(e){let t=await d(e);return t?(o(`maybeResolveNixWrapper: resolved Nix wrapper ${e} -> ${t}`),t):e}async function P(e){try{let t=await b.realpath(e);o(`resolvePathToInstallationType: ${e} -> ${t}`);let n=await M(t);if(!n)return o(`resolvePathToInstallationType: Could not read file prefix`),null;let r=await ae();if(r&&typeof r.detect==`function`){let e=r.detect(n)||null;if(e){let n=e.toLowerCase();return o(`resolvePathToInstallationType: Detected mime type: ${n}`),n.includes(`javascript`)?{kind:`npm-based`,resolvedPath:t}:n.startsWith(`text/`)?(o(`resolvePathToInstallationType: Unrecognized file type`),null):{kind:`native-binary`,resolvedPath:await N(t)}}}o(`resolvePathToInstallationType: Using fallback file type detection`);let i=j(n);return i===`javascript`?{kind:`npm-based`,resolvedPath:t}:i===`binary`?{kind:`native-binary`,resolvedPath:await N(t)}:(o(`resolvePathToInstallationType: Fallback could not determine file type`),null)}catch(e){return o(`resolvePathToInstallationType: Error:`,e),null}}async function F(){try{let e=await ne(`claude`);return o(`getClaudeFromPath: Found claude at ${e}`),e}catch{return o(`getClaudeFromPath: claude not found on PATH`),null}}function I(e){let t=/\bVERSION:"(\d+\.\d+\.\d+)"/g,n=new Map,r;for(;(r=t.exec(e))!==null;){let e=r[1];n.set(e,(n.get(e)||0)+1)}if(n.size===0)return null;let i=0,a;for(let[e,t]of n.entries())o(`Found version ${e} with ${t} occurrences`),t>i&&(i=t,a=e);return a&&o(`Extracted version ${a} (${i} occurrences)`),a||null}async function L(e){let t=I(await b.readFile(e,`utf8`));if(!t)throw Error(`No VERSION strings found in JS file: ${e}`);return t}async function R(t){let{data:n}=await e(t);if(!n)throw Error(`Could not extract JS from native binary: ${t}`);let r=I(n.toString(`utf8`));if(!r)throw Error(`No VERSION strings found in extracted JS from: ${t}`);return r}function z(e){let t=x.basename(e).match(/^(\d+\.\d+\.\d+)$/);return t?t[1]:null}async function B(e,t){let n=z(e);return n?(o(`extractVersion: Got version ${n} from filename`),n):t===`npm-based`?L(e):R(e)}async function V(){let e=[],t=new Set;for(let n of re){let r=x.join(n,`cli.js`);if(!t.has(r))try{if(await c(r)){o(`collectCandidates: Found cli.js at ${r}`);let n=await L(r);e.push({path:r,kind:`npm-based`,version:n}),t.add(r)}}catch(e){o(`collectCandidates: Error checking ${r}:`,e)}}for(let n of ie)if(!t.has(n))try{if(await c(n)){let r=await N(n);o(`collectCandidates: Found native binary at ${n}${r===n?``:` (resolved -> ${r})`}`);let i=await B(r,`native-binary`);e.push({path:r,kind:`native-binary`,version:i}),t.add(n)}}catch(e){o(`collectCandidates: Error checking ${n}:`,e)}return[...e].sort((e,t)=>i(e.version,t.version))}function H(e){return e.map(e=>` • ${e.path} (${e.kind}, v${e.version})`).join(`
3
- `)}function U(e){return` 2. Set ccInstallationPath in your config file (${u}):
4
-
5
- {
6
- "ccInstallationPath": "${e}"
7
- }`}function W(e){return` 1. Set the TWEAKCC_CC_INSTALLATION_PATH environment variable:
8
-
9
- export TWEAKCC_CC_INSTALLATION_PATH="${e}"`}function G(e){let t=e[0]?.path||`/path/to/claude`;return`Multiple Claude Code installations found.
10
-
11
- Found installations:
12
- ${H(e)}
13
-
14
- To specify which installation to use, either:
15
-
16
- ${W(t)}
17
-
18
- ${U(t)}`}function K(){return`Could not find Claude Code installation.
19
-
20
- To fix this, either:
21
-
22
- ${W(`/path/to/claude`)}
23
-
24
- ${U(`/path/to/claude`)}
25
-
26
- 3. Install Claude Code:
27
- • npm install -g @anthropic-ai/claude-code
28
- • Or download from https://claude.ai/download`}function q(e,t,n,r){return t===`npm-based`?{cliPath:e,version:n,source:r}:{nativeInstallationPath:e,version:n,source:r}}async function J(e,t){let r=process.env.TWEAKCC_CC_INSTALLATION_PATH?.trim();if(r&&r.length>0){if(o(`Checking TWEAKCC_CC_INSTALLATION_PATH: ${r}`),!await c(r))throw new T(`TWEAKCC_CC_INSTALLATION_PATH is set to '${r}' but file does not exist.`);let e=await P(r);if(!e)throw new T(`Unable to detect installation type from TWEAKCC_CC_INSTALLATION_PATH value '${r}'.\nExpected a Claude Code cli.js file or native binary.`);let t=await B(e.resolvedPath,e.kind);return n()&&e.kind===`npm-based`&&o(`SHA256 hash: ${await f(e.resolvedPath)}`),o(`Using Claude Code from TWEAKCC_CC_INSTALLATION_PATH: ${e.resolvedPath} (${e.kind}, v${t})`),q(e.resolvedPath,e.kind,t,`env-var`)}if(e.ccInstallationPath){let t=e.ccInstallationPath;if(o(`Checking ccInstallationPath: ${t}`),!await c(t))throw new T(`ccInstallationPath is set to '${t}' but file does not exist.`);let r=await P(t);if(!r)throw new T(`Unable to detect installation type from configured ccInstallationPath '${t}'.\nExpected a Claude Code cli.js file or native binary.`);let i=await B(r.resolvedPath,r.kind);return n()&&r.kind===`npm-based`&&o(`SHA256 hash: ${await f(r.resolvedPath)}`),o(`Using Claude Code from ccInstallationPath: ${r.resolvedPath} (${r.kind}, v${i})`),q(r.resolvedPath,r.kind,i,`config`)}let i=await F();if(i){o(`Checking claude on PATH: ${i}`);let e=await P(i);if(!e)o(`Unable to detect installation type from 'claude' on PATH (${i}). Falling back to hardcoded search paths.`);else{let t=await B(e.resolvedPath,e.kind);return n()&&e.kind===`npm-based`&&o(`SHA256 hash: ${await f(e.resolvedPath)}`),o(`Using Claude Code from PATH: ${e.resolvedPath} (${e.kind}, v${t})`),q(e.resolvedPath,e.kind,t,`path`)}}o(`Collecting candidates from hardcoded search paths...`);let a=await V();if(a.length===0){if(t.interactive)return null;throw new T(K())}if(a.length===1){let e=a[0];return o(`Using single candidate: ${e.path} (${e.kind}, v${e.version})`),q(e.path,e.kind,e.version,`search-paths`)}if(!t.interactive)throw new T(G(a));return{version:``,source:`search-paths`,_pendingCandidates:a}}function Y(e){return e._pendingCandidates||null}async function le(e){return o(`Saving selected installation to config: ${e.path}`),await s(t=>{t.ccInstallationPath=e.path}),q(e.path,e.kind,e.version,`config`)}function ue(){return K()}function X({candidates:e,onSelect:t,onCancel:n}){let[r,i]=ee(0);return g((a,o)=>{o.escape?n?n():process.exit(0):o.upArrow?i(t=>t>0?t-1:e.length-1):o.downArrow?i(t=>t<e.length-1?t+1:0):o.return&&t(e[r])}),C(p,{flexDirection:`column`,children:[S(m,{bold:!0,color:`yellow`,children:`No claude executable was found in PATH, but multiple Claude Code installations were found on this machine. Please select one:`}),S(m,{children:` `}),e.map((e,t)=>C(p,{children:[C(m,{bold:t===r,color:t===r?`cyan`:void 0,children:[t===r?`❯ `:` `,e.path]}),C(m,{dimColor:!0,children:[` `,`(`,e.kind,`, v`,e.version,`)`]})]},e.path)),S(m,{children:` `}),C(m,{children:[`Your choice will be saved to`,` `,S(m,{color:`blue`,children:`ccInstallationPath`}),` in`,` `,C(m,{color:`blue`,children:[l.replace(te.homedir(),`~`),`/config.json`]}),`.`]}),S(m,{children:` `}),S(m,{dimColor:!0,children:`Use ↑↓ arrows to navigate, Enter to select, Esc to quit`})]})}function Z(e){return{path:e.path,version:e.version,kind:e.kind===`npm-based`?`npm`:`native`}}function Q(e){let t=e.cliPath??e.nativeInstallationPath;if(!t)throw Error(`Installation info has neither cliPath nor nativeInstallationPath`);return{path:t,version:e.version,kind:e.cliPath?`npm`:`native`}}async function de(){return(await V()).map(Z)}async function fe(e={}){if(e.path){let t=await P(e.path);if(!t)throw Error(`Unable to detect installation type from path '${e.path}'. Expected a Claude Code cli.js file or native binary.\n`);let n=await B(t.resolvedPath,t.kind);return{path:t.resolvedPath,version:n,kind:t.kind===`npm-based`?`npm`:`native`}}let t=await J(await r(),{interactive:!0});if(!t)throw Error(`Could not find Claude Code installation. Install Claude Code or specify the path explicitly.`);let n=Y(t);if(n){if(!e.interactive){let e=n.map(e=>` • ${e.path} (${e.kind}, v${e.version})`).join(`
29
- `);throw Error(`Multiple Claude Code installations found:\n${e}\n\nPass { interactive: true } to show a picker, or { path: "..." } to specify explicitly.\nAlternatively, set "ccInstallationPath" in ${u} to the path to a Claude Code installation.`)}let t=await $(n.map(Z));if(!t)throw Error(`No installation selected.`);return t}return Q(t)}async function $(e){let t=e.map(e=>({path:e.path,version:e.version,kind:e.kind===`npm`?`npm-based`:`native-binary`}));return new Promise((e,n)=>{let r,i=()=>{try{r.unmount()}catch{}process.stdin.ref()},a=t=>{i(),e(Z(t))},o=()=>{i(),e(null)};try{r=h(_.createElement(X,{candidates:t,onSelect:a,onCancel:o}),{exitOnCtrlC:!1}),r.waitUntilExit().catch(e=>{i(),n(e instanceof Error?e:Error(String(e)))})}catch(e){process.stdin.ref(),n(e instanceof Error?e:Error(String(e)))}})}async function pe(t){if(t.kind===`native`){let{data:n,clearBytecode:r}=await e(t.path);if(!n)throw Error(`Failed to extract JavaScript from native installation: ${t.path}`);return{content:n.toString(`utf8`),clearBytecode:r}}else return{content:await y.readFile(t.path,{encoding:`utf8`}),clearBytecode:!1}}async function me(e,n,r){if(e.kind===`native`){let t=Buffer.from(n,`utf8`);await a(e.path,t,e.path,r)}else await t(e.path,n,`patch`)}export{fe as a,J as c,le as d,$ as i,ue as l,me as n,X as o,de as r,T as s,pe as t,Y as u};
@@ -1,4 +0,0 @@
1
- import{S as e,f as t}from"./config-5W52dXMg.mjs";import n from"node:os";import r from"node:fs";import i from"node:path";import{execFileSync as a,execSync as o}from"node:child_process";import s from"node-lief";function c(e){try{if(r.statSync(e).size>2e5)return null;s.logging.disable();let n=s.parse(e);if(!n.symbols().some(e=>{let t=e.name;return t===`execv`||t===`_execv`}))return t(`resolveNixBinaryWrapper: no execv import found, not a Nix wrapper`),null;t(`resolveNixBinaryWrapper: execv import found, checking for Nix wrapper DOCSTRING`);let i=null;if(n.format===`ELF`){let e=n.sections().find(e=>e.name===`.rodata`);e&&(i=e.content)}else if(n.format===`MachO`){let e=n.getSegment(`__TEXT`);if(e){let t=e.getSection(`__cstring`);t&&(i=t.content)}}if(!i||i.length===0)return t(`resolveNixBinaryWrapper: could not read string section`),null;let a=i.toString(`utf-8`),o=a.match(/makeCWrapper\s+'(\/nix\/store\/[^']+)'/);if(o){let e=o[1];return t(`resolveNixBinaryWrapper: found wrapped executable via DOCSTRING: ${e}`),e}let c=a.match(/makeCWrapper\s+(\/nix\/store\/\S+)/);if(c){let e=c[1];return t(`resolveNixBinaryWrapper: found wrapped executable via unquoted DOCSTRING: ${e}`),e}let l=a.match(/\/nix\/store\/[^\0\n\r]+/g);if(l){for(let e of l)if(e.includes(`/bin/`))return t(`resolveNixBinaryWrapper: found wrapped executable via /bin/ heuristic: ${e}`),e}return t(`resolveNixBinaryWrapper: has execv but no Nix store paths found`),null}catch(e){return t(`resolveNixBinaryWrapper: error during detection:`,e),null}}const l=Buffer.from(`
2
- ---- Bun! ----
3
- `);function u(e,t){return e.subarray(t.offset,t.offset+t.length)}function d(e,t){return{offset:e.readUInt32LE(t),length:e.readUInt32LE(t+4)}}function f(e){return e.endsWith(`/claude`)||e===`claude`||e.endsWith(`/claude.exe`)||e===`claude.exe`||e.endsWith(`/src/entrypoints/cli.js`)||e===`src/entrypoints/cli.js`}function p(e){let n=e%52==0,r=e%36==0;return n&&!r?52:r&&!n?36:n&&r?(t(`detectModuleStructSize: Ambiguous module list length ${e}, assuming new format`),52):(t(`detectModuleStructSize: Module list length ${e} doesn't cleanly divide by either struct size, assuming new format`),52)}function m(e,t,n,r){let i=u(e,t.modulesPtr),a=Math.floor(i.length/n);for(let t=0;t<a;t++){let a=g(i,t*n,n),o=r(a,u(e,a.name).toString(`utf-8`),t);if(o!==void 0)return o}}function h(e){let t=0,n=e.readBigUInt64LE(t);t+=8;let r=d(e,t);t+=8;let i=e.readUInt32LE(t);t+=4;let a=d(e,t);return t+=8,{byteCount:n,modulesPtr:r,entryPointId:i,compileExecArgvPtr:a,flags:e.readUInt32LE(t)}}function g(e,t,n){let r=t,i=d(e,r);r+=8;let a=d(e,r);r+=8;let o=d(e,r);r+=8;let s=d(e,r);r+=8;let c,l;n===52?(c=d(e,r),r+=8,l=d(e,r),r+=8):(c={offset:0,length:0},l={offset:0,length:0});let u=e.readUInt8(r);r+=1;let f=e.readUInt8(r);r+=1;let p=e.readUInt8(r);r+=1;let m=e.readUInt8(r);return{name:i,contents:a,sourcemap:o,bytecode:s,moduleInfo:c,bytecodeOriginPath:l,encoding:u,loader:f,moduleFormat:p,side:m}}function _(e){if(e.length<32+l.length)throw Error(`BUN data is too small to contain trailer and offsets`);let n=e.length-l.length,r=e.subarray(n);if(t(`parseBunDataBlob: Expected trailer: ${l.toString(`hex`)}`),t(`parseBunDataBlob: Got trailer: ${r.toString(`hex`)}`),!r.equals(l))throw t(`Expected: ${l.toString(`hex`)}`),t(`Got: ${r.toString(`hex`)}`),Error(`BUN trailer bytes do not match trailer`);let i=e.length-32-l.length,a=h(e.subarray(i,i+32));return{bunOffsets:a,bunData:e,moduleStructSize:p(a.modulesPtr.length)}}function v(e){if(e.length<4)throw Error(`Section data too small`);t(`extractBunDataFromSection: sectionData.length=${e.length}`);let n=e.readUInt32LE(0),r=4+n,i=e.length>=8?Number(e.readBigUInt64LE(0)):0,a=8+i;t(`extractBunDataFromSection: u32 header would give size=${n}, expected total=${r}`),t(`extractBunDataFromSection: u64 header would give size=${i}, expected total=${a}`);let o,s;if(e.length>=8&&a<=e.length&&a>=e.length-4096)o=8,s=i,t(`extractBunDataFromSection: detected u64 header format (Bun >= 1.3.4)`);else if(r<=e.length&&r>=e.length-4096)o=4,s=n,t(`extractBunDataFromSection: detected u32 header format (Bun < 1.3.4)`);else throw Error(`Cannot determine section header format: sectionData.length=${e.length}, u64 would expect ${a}, u32 would expect ${r}`);t(`extractBunDataFromSection: bunDataSize from header=${s}`);let c=e.subarray(o,o+s);t(`extractBunDataFromSection: bunDataContent.length=${c.length}`);let{bunOffsets:l,bunData:u,moduleStructSize:d}=_(c);return{bunOffsets:l,bunData:u,sectionHeaderSize:o,moduleStructSize:d}}function y(e){try{let n=e.getSection(`.bun`);if(!n)return t(`extractBunDataFromELFSection: .bun section not found`),null;let r=n.content;if(r.length<8)return t(`extractBunDataFromELFSection: .bun section too small`),null;t(`extractBunDataFromELFSection: .bun section found, size=${r.length}`);let i=v(r);return t(`extractBunDataFromELFSection: successfully extracted data`),i}catch(e){return t(`extractBunDataFromELFSection: failed to extract:`,e),null}}function b(e){if(!e.hasOverlay)throw Error(`ELF binary has no overlay data`);let n=e.overlay;if(t(`extractBunDataFromELFOverlay: Overlay size=${n.length} bytes`),n.length<l.length+8+32)throw Error(`ELF overlay data is too small`);let r=n.readBigUInt64LE(n.length-8);if(t(`extractBunDataFromELFOverlay: Total byte count from tail=${r}`),r<4096n||r>2n**32n-1n)throw Error(`ELF total byte count is out of range: ${r}`);let i=n.length-8-l.length,a=n.subarray(i,n.length-8);if(t(`extractBunDataFromELFOverlay: Expected trailer: ${l.toString(`hex`)}`),t(`extractBunDataFromELFOverlay: Got trailer: ${a.toString(`hex`)}`),!a.equals(l))throw Error(`BUN trailer bytes do not match trailer`);let o=n.length-8-l.length-32,s=n.subarray(o,n.length-8-l.length),c=h(s);t(`extractBunDataFromELFOverlay: Offsets.byteCount=${c.byteCount}`);let u=typeof c.byteCount==`bigint`?c.byteCount:BigInt(c.byteCount);if(u>=r)throw Error(`ELF total byte count is out of range`);let d=8+l.length+32,f=n.length-d-Number(u),m=n.subarray(f,n.length-d);return t(`extractBunDataFromELFOverlay: Extracted ${m.length} bytes of data`),{bunOffsets:c,bunData:Buffer.concat([m,s,a]),moduleStructSize:p(c.modulesPtr.length)}}function x(e){let t=e.getSegment(`__BUN`);if(!t)throw Error(`__BUN segment not found`);let n=t.getSection(`__bun`);if(!n)throw Error(`__bun section not found`);return v(n.content)}function S(e){let t=e.sections().find(e=>e.name===`.bun`);if(!t)throw Error(`.bun section not found`);return v(t.content)}function C(e){switch(t(`getBunData: Binary format detected as ${e.format}`),e.format){case`MachO`:return x(e);case`PE`:return S(e);case`ELF`:{let n=e,r=y(n);return r?(t(`getBunData: Using new ELF .bun section format`),r):(t(`getBunData: Falling back to legacy ELF overlay format`),b(n))}default:{let t=e;throw Error(`Unsupported binary format: ${t.format}`)}}}function w(e){let o=r.mkdtempSync(i.join(n.tmpdir(),`tweakcc-npm-`));try{t(`fetchNpmSource: Downloading @anthropic-ai/claude-code@${e}`),a(`npm`,[`pack`,`@anthropic-ai/claude-code@${e}`,`--pack-destination`,o],{stdio:`pipe`,timeout:3e4,cwd:o});let n=r.readdirSync(o).find(e=>e.endsWith(`.tgz`));if(!n)return t(`fetchNpmSource: No .tgz file found after npm pack`),null;a(`tar`,[`xzf`,i.join(o,n),`package/cli.js`],{stdio:`pipe`,timeout:3e4,cwd:o});let s=i.join(o,`package`,`cli.js`);if(!r.existsSync(s))return t(`fetchNpmSource: cli.js not found in extracted package`),null;let c=r.readFileSync(s);return t(`fetchNpmSource: Got cli.js, ${c.length} bytes`),c}catch(e){return t(`fetchNpmSource: Failed to fetch npm source:`,e),null}finally{try{r.rmSync(o,{recursive:!0,force:!0})}catch{}}}function T(e,n){try{s.logging.disable();let{bunOffsets:r,bunData:i,moduleStructSize:a}=C(s.parse(e));t(`extractClaudeJsFromNativeInstallation: Got bunData, size=${i.length} bytes, moduleStructSize=${a}`);let o=m(i,r,a,(e,n,r)=>{if(t(`extractClaudeJsFromNativeInstallation: Module ${r}: ${n}`),!f(n))return;let a=u(i,e.contents);return t(`extractClaudeJsFromNativeInstallation: Found claude module, contents length=${a.length}`),a.length>0?a:void 0});if(o){if(o.subarray(0,30).toString(`utf8`).startsWith(`// @bun @bytecode`))if(t(`extractClaudeJsFromNativeInstallation: Extracted content is Bun bytecode — falling back to npm source`),n){let e=w(n);if(e)return t(`extractClaudeJsFromNativeInstallation: Using npm source (${e.length} bytes) instead of bytecode`),{data:e,clearBytecode:!0};t(`extractClaudeJsFromNativeInstallation: npm source fetch failed, returning bytecode content as-is`)}else t(`extractClaudeJsFromNativeInstallation: No version provided, cannot fetch npm source`);return{data:o,clearBytecode:!1}}return t(`extractClaudeJsFromNativeInstallation: claude module not found in any module`),{data:null,clearBytecode:!1}}catch(e){return t(`extractClaudeJsFromNativeInstallation: Error during extraction:`,e),{data:null,clearBytecode:!1}}}function E(e,t,n,r,i){let a=[],o=[];m(e,t,r,(t,s)=>{let c=u(e,t.name),l,d;n&&f(s)?(l=n,d=i?Buffer.alloc(0):u(e,t.bytecode)):(l=u(e,t.contents),d=u(e,t.bytecode));let p=u(e,t.sourcemap),m=u(e,t.moduleInfo),h=u(e,t.bytecodeOriginPath);o.push({name:c,contents:l,sourcemap:p,bytecode:d,moduleInfo:m,bytecodeOriginPath:h,encoding:t.encoding,loader:t.loader,moduleFormat:t.moduleFormat,side:t.side}),r===52?a.push(c,l,p,d,m,h):a.push(c,l,p,d)});let s=r===52?6:4,c=0,d=[];for(let e of a)d.push({offset:c,length:e.length}),c+=e.length+1;let p=c,h=o.length*r;c+=h;let g=u(e,t.compileExecArgvPtr),_=c,v=g.length;c+=v+1;let y=c;c+=32;let b=c;c+=l.length;let x=Buffer.allocUnsafe(c);x.fill(0);let S=0;for(let{offset:e,length:t}of d)t>0&&a[S].copy(x,e,0,t),x[e+t]=0,S++;v>0&&(g.copy(x,_,0,v),x[_+v]=0);for(let e=0;e<o.length;e++){let t=o[e],n=e*s,i={name:d[n],contents:d[n+1],sourcemap:d[n+2],bytecode:d[n+3],moduleInfo:r===52?d[n+4]:{offset:0,length:0},bytecodeOriginPath:r===52?d[n+5]:{offset:0,length:0},encoding:t.encoding,loader:t.loader,moduleFormat:t.moduleFormat,side:t.side},a=p+e*r;x.writeUInt32LE(i.name.offset,a),x.writeUInt32LE(i.name.length,a+4),a+=8,x.writeUInt32LE(i.contents.offset,a),x.writeUInt32LE(i.contents.length,a+4),a+=8,x.writeUInt32LE(i.sourcemap.offset,a),x.writeUInt32LE(i.sourcemap.length,a+4),a+=8,x.writeUInt32LE(i.bytecode.offset,a),x.writeUInt32LE(i.bytecode.length,a+4),a+=8,r===52&&(x.writeUInt32LE(i.moduleInfo.offset,a),x.writeUInt32LE(i.moduleInfo.length,a+4),a+=8,x.writeUInt32LE(i.bytecodeOriginPath.offset,a),x.writeUInt32LE(i.bytecodeOriginPath.length,a+4),a+=8),x.writeUInt8(i.encoding,a),x.writeUInt8(i.loader,a+1),x.writeUInt8(i.moduleFormat,a+2),x.writeUInt8(i.side,a+3)}let C={byteCount:y,modulesPtr:{offset:p,length:h},entryPointId:t.entryPointId,compileExecArgvPtr:{offset:_,length:v},flags:t.flags},w=y,T=typeof C.byteCount==`bigint`?C.byteCount:BigInt(C.byteCount);return x.writeBigUInt64LE(T,w),w+=8,x.writeUInt32LE(C.modulesPtr.offset,w),x.writeUInt32LE(C.modulesPtr.length,w+4),w+=8,x.writeUInt32LE(C.entryPointId,w),w+=4,x.writeUInt32LE(C.compileExecArgvPtr.offset,w),x.writeUInt32LE(C.compileExecArgvPtr.length,w+4),w+=8,x.writeUInt32LE(C.flags,w),l.copy(x,b),x}function D(e,t,n,i=!0){let a=t+`.tmp`;if(e.write(a),i){let e=r.statSync(n);r.chmodSync(a,e.mode)}try{r.renameSync(a,t)}catch(e){try{r.existsSync(a)&&r.unlinkSync(a)}catch{}throw e instanceof Error&&`code`in e&&(e.code===`ETXTBSY`||e.code===`EBUSY`||e.code===`EPERM`)?Error(`Cannot update the Claude executable while it is running.
4
- Please close all Claude instances and try again.`):e}}function O(e,t=8){let n=Buffer.allocUnsafe(t+e.length);return t===8?n.writeBigUInt64LE(BigInt(e.length),0):n.writeUInt32LE(e.length,0),e.copy(n,t),n}function k(n,r,i,a,c){try{t(`repackMachO: Has code signature: ${n.hasCodeSignature}`),n.hasCodeSignature&&(t(`repackMachO: Removing code signature...`),n.removeSignature());let l=n.getSegment(`__BUN`);if(!l)throw Error(`__BUN segment not found`);let u=l.getSection(`__bun`);if(!u)throw Error(`__bun section not found`);let d=O(i,c);t(`repackMachO: Original section size: ${u.size}`),t(`repackMachO: Original segment fileSize: ${l.fileSize}`),t(`repackMachO: Original segment virtualSize: ${l.virtualSize}`),t(`repackMachO: New data size: ${d.length}`),t(`repackMachO: Using header size: ${c}`);let f=d.length-Number(u.size);if(f>0){let e=n.header.cpuType===s.MachO.Header.CPU_TYPE.ARM64,r=e?16384:4096,i=Math.ceil(f/r)*r;t(`repackMachO: CPU type: ${e?`ARM64`:`x86_64`}`),t(`repackMachO: Page size: ${r} bytes`),t(`repackMachO: Need to expand by ${f} bytes`),t(`repackMachO: Rounding up to page-aligned: ${i} bytes`);let a=n.extendSegment(l,i);if(t(`repackMachO: extendSegment returned: ${a}`),!a)throw Error(`Failed to extend __BUN segment`);t(`repackMachO: Section size after extend: ${u.size}`),t(`repackMachO: Segment fileSize after extend: ${l.fileSize}`),t(`repackMachO: Segment virtualSize after extend: ${l.virtualSize}`)}u.content=d,u.size=BigInt(d.length),t(`repackMachO: Final section size: ${u.size}`),t(`repackMachO: Writing modified binary to ${a}...`),D(n,a,r);try{t(`repackMachO: Re-signing binary with ad-hoc signature...`),o(`codesign -s - -f "${a}"`,{stdio:e()?`inherit`:`ignore`}),t(`repackMachO: Code signing completed successfully`)}catch(e){console.warn(`Warning: Failed to re-sign binary. The binary may not run correctly on macOS:`,e)}t(`repackMachO: Write completed successfully`)}catch(e){throw console.error(`repackMachO failed:`,e),e}}function A(e,n,r,i,a){try{let o=e.sections().find(e=>e.name===`.bun`);if(!o)throw Error(`.bun section not found`);let s=O(r,a);t(`repackPE: Original section size: ${o.size}, virtual size: ${o.virtualSize}`),t(`repackPE: New data size: ${s.length}`),t(`repackPE: Using header size: ${a}`),o.content=s,o.virtualSize=BigInt(s.length),o.size=BigInt(s.length),t(`repackPE: Writing modified binary to ${i}...`),D(e,i,n,!1),t(`repackPE: Write completed successfully`)}catch(e){throw console.error(`repackPE failed:`,e),e}}const j=16384;function M(e,n,r,i,a){try{let o=e.getSection(`.bun`);if(!o)throw Error(`.bun section not found`);let s=O(r,a);t(`repackELFSection: Original section size: ${o.size}`),t(`repackELFSection: New section data size: ${s.length}`);let c=o.virtualAddress,l=e.segments(),u=l.find(e=>e.type===`LOAD`&&e.flags===4&&e.virtualAddress===c);if(!u)throw Error(`.bun PT_LOAD segment not found (looking for LOAD with vaddr=0x${c.toString(16)})`);t(`repackELFSection: Found .bun segment: vaddr=0x${u.virtualAddress.toString(16)}, filesz=0x${u.fileSize.toString(16)}, memsz=0x${u.virtualSize.toString(16)}`);let d=Buffer.alloc(8);d.writeBigUInt64LE(c);let f=null,p=l.find(e=>e.type===`LOAD`&&(e.flags&2)!=0);if(p){let e=p.content,n=Number(p.virtualAddress),r=Math.ceil(n/j)*j;for(let i=r;i<n+e.length-8;i+=j){let r=i-n;if(e.subarray(r,r+8).equals(d)){f=BigInt(i),t(`repackELFSection: BUN_COMPILED at vaddr 0x${f.toString(16)} (offset ${r} in RW segment)`);break}}}if(f===null)throw Error(`Could not find original BUN_COMPILED location in binary`);o.content=s;let m=Number(u.alignment),h=BigInt(Math.ceil(s.length/m)*m);u.fileSize=h,u.virtualSize=h,t(`repackELFSection: Updated segment: filesz=0x${u.fileSize.toString(16)}, memsz=0x${u.virtualSize.toString(16)}`);let g=Buffer.alloc(8);g.writeBigUInt64LE(c),e.patchAddress(f,g),t(`repackELFSection: Patched BUN_COMPILED at vaddr 0x${f.toString(16)} -> 0x${c.toString(16)}`),D(e,i,n),t(`repackELFSection: Write completed successfully`)}catch(e){throw console.error(`repackELFSection failed:`,e),e}}function N(e,n,r,i){try{let a=Buffer.allocUnsafe(r.length+8);r.copy(a,0),a.writeBigUInt64LE(BigInt(r.length),r.length),t(`repackELFOverlay: Setting overlay data (${a.length} bytes)`),e.overlay=a,t(`repackELFOverlay: Writing modified binary to ${i}...`),D(e,i,n),t(`repackELFOverlay: Write completed successfully`)}catch(e){throw console.error(`repackELFOverlay failed:`,e),e}}function P(e,t,n,r){s.logging.disable();let i=s.parse(e),{bunOffsets:a,bunData:o,sectionHeaderSize:c,moduleStructSize:l}=C(i),u=E(o,a,t,l,r);switch(i.format){case`MachO`:if(!c)throw Error(`sectionHeaderSize is required for Mach-O binaries`);k(i,e,u,n,c);break;case`PE`:if(!c)throw Error(`sectionHeaderSize is required for PE binaries`);A(i,e,u,n,c);break;case`ELF`:c?M(i,e,u,n,c):N(i,e,u,n);break;default:{let e=i;throw Error(`Unsupported binary format: ${e.format}`)}}}export{T as extractClaudeJsFromNativeInstallation,P as repackNativeInstallation,c as resolveNixBinaryWrapper};