install-source.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
  2. import path from 'node:path';
  3. import spawn from 'cross-spawn';
  4. import { parseMcodeVersion } from './release.js';
  5. import { isManagedMcodeInstallRoot } from './service.js';
  6. import type { McodeUpdateOperationOptions } from './progress.js';
  7. export const MCODE_INTERNAL_NPM_REGISTRY = 'https://npmmirror.example.invalid/';
  8. export const MCODE_PUBLIC_NPM_REGISTRY = 'https://registry.npmjs.org/';
  9. export const MCODE_PUBLIC_NPM_MIRROR_REGISTRY = 'https://registry.npmmirror.com/';
  10. const REGISTRY_FETCH_TIMEOUT_MS = 30_000;
  11. const MCODE_PACKAGE_BASENAME = 'code';
  12. const MCODE_INTERNAL_SCOPE = '@minimax';
  13. const MCODE_PUBLIC_SCOPE = '@minimax-ai';
  14. // Public packaging rewrites this marker together with the bundled package identity.
  15. const MCODE_EMBEDDED_PACKAGE_NAME = '@minimax-ai/code' as McodeNpmPackageName;
  16. export type McodeNpmDistTag = 'latest' | 'test' | 'preview';
  17. export type McodeNpmPackageName = '@minimax/code' | '@minimax-ai/code';
  18. type TuiBuildEnvironment = 'test' | 'staging' | 'prod';
  19. declare const __TUI_BUILD_ENV__: TuiBuildEnvironment | undefined;
  20. declare const __TUI_NPM_DIST_TAG__: McodeNpmDistTag | undefined;
  21. export type McodePackageManagerInstallSource =
  22. | 'npm-global'
  23. | 'npm-prefix'
  24. | 'pnpm-global'
  25. | 'yarn-global'
  26. | 'bun-global';
  27. export type McodeInstallSource =
  28. | 'managed-installer'
  29. | McodePackageManagerInstallSource
  30. | 'unsupported';
  31. export interface McodePackageManagerCommand {
  32. readonly executable: string;
  33. readonly args: readonly string[];
  34. readonly display: string;
  35. }
  36. export interface McodeNpmPrefixInstall {
  37. readonly executable: string;
  38. readonly packageName: McodeNpmPackageName;
  39. readonly prefix: string;
  40. readonly registry: string;
  41. }
  42. export type McodePackageManagerRunOptions = McodeUpdateOperationOptions;
  43. export interface McodeNpmDistribution {
  44. readonly packageName: McodeNpmPackageName;
  45. readonly registry: string;
  46. }
  47. export interface ResolveLatestMcodeRegistryVersionDependencies {
  48. readonly platform: NodeJS.Platform;
  49. readonly run: (command: string, args: readonly string[]) => Promise<string>;
  50. readonly distribution: McodeNpmDistribution;
  51. readonly npmExecutable: string;
  52. readonly environment: NodeJS.ProcessEnv;
  53. readonly runtimeExecutable: string;
  54. }
  55. export interface DetectMcodeInstallSourceDependencies {
  56. readonly installRoot: string;
  57. readonly platform: NodeJS.Platform;
  58. readonly packageRoot: () => string | undefined;
  59. readonly npmGlobalPrefix: () => Promise<string>;
  60. readonly managedInstall: (installRoot: string) => boolean;
  61. readonly prefixInstall: () => McodeNpmPrefixInstall | undefined;
  62. }
  63. export async function detectMcodeInstallSource(
  64. dependencies: Partial<DetectMcodeInstallSourceDependencies> & { installRoot: string },
  65. ): Promise<McodeInstallSource> {
  66. const platform = dependencies.platform ?? process.platform;
  67. const resolved: DetectMcodeInstallSourceDependencies = {
  68. installRoot: dependencies.installRoot,
  69. platform,
  70. packageRoot: dependencies.packageRoot ?? resolveMcodePackageRoot,
  71. npmGlobalPrefix:
  72. dependencies.npmGlobalPrefix ??
  73. (() => runText(platform === 'win32' ? 'npm.cmd' : 'npm', ['prefix', '--global'])),
  74. managedInstall: dependencies.managedInstall ?? isManagedMcodeInstallRoot,
  75. prefixInstall: dependencies.prefixInstall ?? resolveMcodeNpmPrefixInstall,
  76. };
  77. if (resolved.managedInstall(resolved.installRoot)) return 'managed-installer';
  78. if (resolved.prefixInstall()) return 'npm-prefix';
  79. const packageRoot = resolved.packageRoot();
  80. if (!packageRoot) return 'unsupported';
  81. const heuristic = classifyMcodeInstallPath(packageRoot);
  82. if (heuristic) return heuristic;
  83. try {
  84. return classifyNpmGlobalInstall(packageRoot, await resolved.npmGlobalPrefix(), platform);
  85. } catch {
  86. return 'unsupported';
  87. }
  88. }
  89. export function classifyMcodeInstallPath(
  90. packageRoot: string,
  91. ): McodePackageManagerInstallSource | undefined {
  92. const normalized = packageRoot.replaceAll('\\', '/').toLocaleLowerCase();
  93. if (
  94. /\/pnpm\/global\/(?:v11\/[^/]+|[^/]+)\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)
  95. ) {
  96. return 'pnpm-global';
  97. }
  98. if (
  99. /\/(?:\.config\/yarn|\.yarn)\/global\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)
  100. ) {
  101. return 'yarn-global';
  102. }
  103. if (/\/\.bun\/install\/global\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)) {
  104. return 'bun-global';
  105. }
  106. if (
  107. /\/lib\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized) ||
  108. /\/npm\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)
  109. ) {
  110. return 'npm-global';
  111. }
  112. return undefined;
  113. }
  114. export function resolveMcodeNpmDistribution(
  115. packageName: McodeNpmPackageName = resolveMcodePackageName() ?? MCODE_EMBEDDED_PACKAGE_NAME,
  116. registry?: string,
  117. ): McodeNpmDistribution {
  118. if (packageName === mcodePackageName(MCODE_INTERNAL_SCOPE)) {
  119. const resolvedRegistry = registry ? new URL(registry).href : MCODE_INTERNAL_NPM_REGISTRY;
  120. if (resolvedRegistry === MCODE_INTERNAL_NPM_REGISTRY) {
  121. return { packageName, registry: resolvedRegistry };
  122. }
  123. throw new Error(`Unsupported MCode npm registry: ${resolvedRegistry}`);
  124. }
  125. if (packageName === mcodePackageName(MCODE_PUBLIC_SCOPE)) {
  126. const resolvedRegistry = registry ? new URL(registry).href : MCODE_PUBLIC_NPM_REGISTRY;
  127. if (
  128. resolvedRegistry === MCODE_PUBLIC_NPM_REGISTRY ||
  129. resolvedRegistry === MCODE_PUBLIC_NPM_MIRROR_REGISTRY
  130. ) {
  131. return { packageName, registry: resolvedRegistry };
  132. }
  133. throw new Error(`Unsupported MCode npm registry: ${resolvedRegistry}`);
  134. }
  135. throw new Error(`Unsupported MCode npm package: ${String(packageName)}`);
  136. }
  137. export function resolveMcodeNpmDistTag(
  138. environment: TuiBuildEnvironment | undefined = readEmbeddedTuiBuildEnvironment(),
  139. embeddedTag: McodeNpmDistTag | undefined = readEmbeddedTuiNpmDistTag(),
  140. ): McodeNpmDistTag {
  141. if (embeddedTag) return embeddedTag;
  142. if (environment === 'test') return 'test';
  143. if (environment === 'staging') return 'preview';
  144. return 'latest';
  145. }
  146. export function classifyNpmGlobalInstall(
  147. packageRoot: string,
  148. globalPrefix: string,
  149. platform: NodeJS.Platform = process.platform,
  150. ): McodeInstallSource {
  151. const normalizedRoot = normalizeResolvedPath(packageRoot, platform);
  152. const platformPath = platform === 'win32' ? path.win32 : path.posix;
  153. const packageName =
  154. mcodePackageNameFromPath(packageRoot) ?? mcodePackageName(MCODE_INTERNAL_SCOPE);
  155. const candidates =
  156. platform === 'win32'
  157. ? [platformPath.join(globalPrefix, 'node_modules', packageName)]
  158. : [
  159. platformPath.join(globalPrefix, 'lib', 'node_modules', packageName),
  160. platformPath.join(globalPrefix, 'node_modules', packageName),
  161. ];
  162. return candidates.some(
  163. (candidate) => normalizeResolvedPath(candidate, platform) === normalizedRoot,
  164. )
  165. ? 'npm-global'
  166. : 'unsupported';
  167. }
  168. export function buildMcodePackageManagerCommand(
  169. source: McodePackageManagerInstallSource,
  170. version: string,
  171. platform: NodeJS.Platform = process.platform,
  172. distribution: McodeNpmDistribution = resolveMcodeNpmDistribution(),
  173. prefixInstall?: McodeNpmPrefixInstall,
  174. ): McodePackageManagerCommand {
  175. const targetVersion = ['latest', 'preview', 'test'].includes(version)
  176. ? version
  177. : parseMcodeVersion(version);
  178. const target = `${distribution.packageName}@${targetVersion}`;
  179. const registryArgs = ['--registry', distribution.registry] as const;
  180. const registryDisplay = `--registry ${distribution.registry}`;
  181. const npmInstallArgs = [
  182. '--ignore-scripts=false',
  183. '--include=optional',
  184. `--allow-scripts=${distribution.packageName},better-sqlite3`,
  185. ];
  186. const npmInstallDisplay = npmInstallArgs.join(' ');
  187. switch (source) {
  188. case 'npm-prefix': {
  189. if (!prefixInstall) throw new Error('MCode npm prefix ownership metadata is missing.');
  190. if (
  191. prefixInstall.packageName !== distribution.packageName ||
  192. new URL(prefixInstall.registry).href !== distribution.registry
  193. ) {
  194. throw new Error('MCode npm prefix ownership does not match the installed package.');
  195. }
  196. return {
  197. executable: prefixInstall.executable,
  198. args: [
  199. 'install',
  200. '--global',
  201. '--prefix',
  202. prefixInstall.prefix,
  203. target,
  204. ...npmInstallArgs,
  205. ...registryArgs,
  206. ],
  207. display:
  208. `${prefixInstall.executable} install --global --prefix ${prefixInstall.prefix} ` +
  209. `${target} ${npmInstallDisplay} ${registryDisplay}`,
  210. };
  211. }
  212. case 'npm-global':
  213. return {
  214. executable: platform === 'win32' ? 'npm.cmd' : 'npm',
  215. args: ['install', '--global', target, ...npmInstallArgs, ...registryArgs],
  216. display: `npm install --global ${target} ${npmInstallDisplay} ${registryDisplay}`,
  217. };
  218. case 'pnpm-global':
  219. return {
  220. executable: platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
  221. args: ['add', '--global', target, ...registryArgs],
  222. display: `pnpm add --global ${target} ${registryDisplay}`,
  223. };
  224. case 'yarn-global':
  225. return {
  226. executable: platform === 'win32' ? 'yarn.cmd' : 'yarn',
  227. args: ['global', 'add', target, ...registryArgs],
  228. display: `yarn global add ${target} ${registryDisplay}`,
  229. };
  230. case 'bun-global':
  231. return {
  232. executable: platform === 'win32' ? 'bun.exe' : 'bun',
  233. args: ['add', '--global', target, ...registryArgs],
  234. display: `bun add --global ${target} ${registryDisplay}`,
  235. };
  236. }
  237. }
  238. export async function resolveLatestMcodeRegistryVersion(
  239. tag: McodeNpmDistTag,
  240. dependencies: Partial<ResolveLatestMcodeRegistryVersionDependencies> = {},
  241. ): Promise<string> {
  242. const platform = dependencies.platform ?? process.platform;
  243. const distribution = dependencies.distribution ?? resolveMcodeNpmDistribution();
  244. const run =
  245. dependencies.run ??
  246. ((executable, args) => {
  247. const command = { executable, args, display: executable };
  248. const bound = dependencies.runtimeExecutable
  249. ? bindMcodeNpmCommandToRuntime(command, dependencies.runtimeExecutable)
  250. : command;
  251. return runText(bound.executable, bound.args, dependencies.environment);
  252. });
  253. const npmExecutable = dependencies.npmExecutable ?? (platform === 'win32' ? 'npm.cmd' : 'npm');
  254. const output = await run(npmExecutable, [
  255. 'view',
  256. `${distribution.packageName}@${tag}`,
  257. 'version',
  258. '--json',
  259. '--registry',
  260. distribution.registry,
  261. '--fetch-timeout',
  262. String(REGISTRY_FETCH_TIMEOUT_MS),
  263. ]);
  264. let version: unknown;
  265. try {
  266. version = JSON.parse(output);
  267. } catch {
  268. version = output.trim();
  269. }
  270. if (Array.isArray(version)) {
  271. if (version.length !== 1) {
  272. throw new Error('MCode registry returned an invalid latest version.');
  273. }
  274. version = version[0];
  275. }
  276. if (typeof version !== 'string') {
  277. throw new Error('MCode registry returned an invalid latest version.');
  278. }
  279. const parsed = parseMcodeVersion(version);
  280. if (tag === 'latest' && parsed.includes('-')) {
  281. throw new Error('MCode latest must resolve to a stable semantic version.');
  282. }
  283. return parsed;
  284. }
  285. function readEmbeddedTuiBuildEnvironment(): TuiBuildEnvironment | undefined {
  286. if (typeof __TUI_BUILD_ENV__ === 'undefined') return undefined;
  287. return __TUI_BUILD_ENV__;
  288. }
  289. function readEmbeddedTuiNpmDistTag(): McodeNpmDistTag | undefined {
  290. if (typeof __TUI_NPM_DIST_TAG__ === 'undefined') return undefined;
  291. return __TUI_NPM_DIST_TAG__;
  292. }
  293. export function bindMcodeNpmCommandToRuntime(
  294. command: McodePackageManagerCommand,
  295. runtimeExecutable: string,
  296. ): McodePackageManagerCommand {
  297. const npmExecutable = realpathSync(command.executable);
  298. const npmDirectory = path.dirname(npmExecutable);
  299. // Unix npm is normally a symlink to npm-cli.js. Windows npm.cmd prefers its
  300. // adjacent node.exe over PATH, so bypass that shim and invoke the JS entry.
  301. const candidates = [
  302. ...(path.basename(npmExecutable) === 'npm-cli.js' ? [npmExecutable] : []),
  303. path.join(npmDirectory, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
  304. path.join(npmDirectory, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
  305. ];
  306. const npmCli = candidates.find((file) => existsSync(file) && statSync(file).isFile());
  307. if (!npmCli)
  308. throw new Error(`Cannot locate npm-cli.js for the owned npm executable: ${command.executable}`);
  309. return { ...command, executable: runtimeExecutable, args: [npmCli, ...command.args] };
  310. }
  311. export function createMcodeNpmRuntimeEnvironment(
  312. environment: NodeJS.ProcessEnv,
  313. runtimeExecutable: string,
  314. platform: NodeJS.Platform = process.platform,
  315. ): NodeJS.ProcessEnv {
  316. const platformPath = platform === 'win32' ? path.win32 : path.posix;
  317. const result = { ...environment };
  318. // Windows environment keys are case-insensitive. Keep only one PATH key so Node and
  319. // cross-spawn cannot choose a different inherited spelling.
  320. const pathKeys = Object.keys(result)
  321. .filter((key) => (platform === 'win32' ? key.toLowerCase() === 'path' : key === 'PATH'))
  322. .sort();
  323. const inheritedPath = result[pathKeys[0] ?? 'PATH'];
  324. for (const key of pathKeys) delete result[key];
  325. result.PATH = [platformPath.dirname(runtimeExecutable), inheritedPath]
  326. .filter(Boolean)
  327. .join(platformPath.delimiter);
  328. return result;
  329. }
  330. export function runMcodePackageManagerCommand(
  331. command: McodePackageManagerCommand,
  332. environment: NodeJS.ProcessEnv = process.env,
  333. options: McodePackageManagerRunOptions = {},
  334. ): Promise<void> {
  335. return new Promise((resolve, reject) => {
  336. let settled = false;
  337. const child = spawn(command.executable, [...command.args], {
  338. env: environment,
  339. shell: false,
  340. stdio: ['ignore', 'pipe', 'pipe'],
  341. windowsHide: true,
  342. });
  343. const stdout: Buffer[] = [];
  344. const stderr: Buffer[] = [];
  345. child.stdout?.on('data', (chunk: Buffer) => {
  346. stdout.push(chunk);
  347. notifyPackageManagerOutput(options, chunk);
  348. });
  349. child.stderr?.on('data', (chunk: Buffer) => {
  350. stderr.push(chunk);
  351. notifyPackageManagerOutput(options, chunk);
  352. });
  353. child.once('error', (error) => {
  354. if (settled) return;
  355. settled = true;
  356. reject(error);
  357. });
  358. child.once('exit', (code, signal) => {
  359. if (settled) return;
  360. settled = true;
  361. if (code === 0) {
  362. resolve();
  363. return;
  364. }
  365. const details = Buffer.concat([...stderr, ...stdout])
  366. .toString('utf8')
  367. .trim();
  368. reject(
  369. new Error(
  370. `${command.executable} failed (${
  371. signal ? `signal ${signal}` : `exit ${String(code)}`
  372. })${details ? `: ${details}` : ''}`,
  373. ),
  374. );
  375. });
  376. });
  377. }
  378. function notifyPackageManagerOutput(options: McodePackageManagerRunOptions, chunk: Buffer): void {
  379. try {
  380. options.onOutput?.(chunk.toString('utf8'));
  381. } catch {
  382. // Progress rendering must never change the package-manager result.
  383. }
  384. }
  385. export function resolveMcodePackageName(
  386. entryFile = process.argv[1],
  387. ): McodeNpmPackageName | undefined {
  388. return resolveMcodePackageIdentity(entryFile)?.packageName;
  389. }
  390. export function isInternalMcodePackageName(packageName: string | undefined): boolean {
  391. return packageName === mcodePackageName(MCODE_INTERNAL_SCOPE);
  392. }
  393. export function resolveInstalledMcodePackageVersion(
  394. entryFile = process.argv[1],
  395. ): string | undefined {
  396. return resolveMcodePackageIdentity(entryFile)?.version;
  397. }
  398. export function resolveMcodeNpmPrefixInstall(
  399. entryFile = process.argv[1],
  400. platform: NodeJS.Platform = process.platform,
  401. nodeExecutable = process.execPath,
  402. ): McodeNpmPrefixInstall | undefined {
  403. const identity = resolveMcodePackageIdentity(entryFile);
  404. if (!identity) return undefined;
  405. const platformPath = platform === 'win32' ? path.win32 : path.posix;
  406. const nodeModules = platformPath.dirname(platformPath.dirname(identity.packageRoot));
  407. if (platformPath.basename(nodeModules).toLocaleLowerCase() !== 'node_modules') return undefined;
  408. const nodeModulesParent = platformPath.dirname(nodeModules);
  409. const packagePrefix =
  410. platform !== 'win32' && platformPath.basename(nodeModulesParent) === 'lib'
  411. ? platformPath.dirname(nodeModulesParent)
  412. : nodeModulesParent;
  413. const receipt = findNpmPrefixReceipt(packagePrefix, identity.packageRoot, platform, platformPath);
  414. if (receipt) {
  415. if (receipt.packageName !== identity.packageName) return undefined;
  416. return receipt;
  417. }
  418. if (platformPath.basename(packagePrefix).toLocaleLowerCase() !== '.minimax-code')
  419. return undefined;
  420. const adjacentNpm = platformPath.join(
  421. platformPath.dirname(nodeExecutable),
  422. platform === 'win32' ? 'npm.cmd' : 'npm',
  423. );
  424. if (!existsSync(adjacentNpm)) return undefined;
  425. const distribution = resolveMcodeNpmDistribution(identity.packageName);
  426. return {
  427. executable: adjacentNpm,
  428. packageName: identity.packageName,
  429. prefix: packagePrefix,
  430. registry: distribution.registry,
  431. };
  432. }
  433. function resolveMcodePackageRoot(entryFile = process.argv[1]): string | undefined {
  434. return resolveMcodePackageIdentity(entryFile)?.packageRoot;
  435. }
  436. function resolveMcodePackageIdentity(
  437. entryFile: string | undefined,
  438. ): { packageName: McodeNpmPackageName; packageRoot: string; version?: string } | undefined {
  439. if (!entryFile) return undefined;
  440. let current: string;
  441. try {
  442. const resolved = realpathSync(entryFile);
  443. current = statSync(resolved).isDirectory() ? resolved : path.dirname(resolved);
  444. } catch {
  445. return undefined;
  446. }
  447. for (;;) {
  448. const manifestFile = path.join(current, 'package.json');
  449. if (existsSync(manifestFile)) {
  450. try {
  451. const manifest = JSON.parse(readFileSync(manifestFile, 'utf8')) as {
  452. name?: unknown;
  453. version?: unknown;
  454. };
  455. const packageName = parseMcodePackageName(manifest.name);
  456. if (packageName) {
  457. return {
  458. packageName,
  459. packageRoot: current,
  460. ...(typeof manifest.version === 'string' ? { version: manifest.version } : {}),
  461. };
  462. }
  463. } catch {
  464. return undefined;
  465. }
  466. }
  467. const parent = path.dirname(current);
  468. if (parent === current) return undefined;
  469. current = parent;
  470. }
  471. }
  472. function findNpmPrefixReceipt(
  473. packagePrefix: string,
  474. packageRoot: string,
  475. platform: NodeJS.Platform,
  476. platformPath: typeof path.posix | typeof path.win32,
  477. ): McodeNpmPrefixInstall | undefined {
  478. let candidate = packagePrefix;
  479. for (let depth = 0; depth < 3; depth += 1) {
  480. const receipt = readNpmPrefixReceipt(
  481. candidate,
  482. packagePrefix,
  483. packageRoot,
  484. platform,
  485. platformPath,
  486. );
  487. if (receipt) return receipt;
  488. const parent = platformPath.dirname(candidate);
  489. if (parent === candidate) break;
  490. candidate = parent;
  491. }
  492. return undefined;
  493. }
  494. function readNpmPrefixReceipt(
  495. prefix: string,
  496. packagePrefix: string,
  497. packageRoot: string,
  498. platform: NodeJS.Platform,
  499. platformPath: typeof path.posix | typeof path.win32,
  500. ): McodeNpmPrefixInstall | undefined {
  501. try {
  502. const raw = readFileSync(platformPath.join(prefix, 'install.json'), 'utf8').replace(
  503. /^\uFEFF/u,
  504. '',
  505. );
  506. const value = JSON.parse(raw) as {
  507. schemaVersion?: unknown;
  508. product?: unknown;
  509. updateOwner?: unknown;
  510. packageManager?: unknown;
  511. packageName?: unknown;
  512. registry?: unknown;
  513. distTag?: unknown;
  514. prefix?: unknown;
  515. npmExecutable?: unknown;
  516. layoutVersion?: unknown;
  517. releasesDirectory?: unknown;
  518. currentFile?: unknown;
  519. };
  520. const packageName = parseMcodePackageName(value.packageName);
  521. const legacyLayout = value.schemaVersion === 1 && value.layoutVersion === undefined;
  522. const versionedLayout =
  523. value.schemaVersion === 2 &&
  524. value.layoutVersion === 2 &&
  525. value.releasesDirectory === 'releases' &&
  526. value.currentFile === 'current';
  527. if (
  528. (!legacyLayout && !versionedLayout) ||
  529. value.product !== 'minimax-code' ||
  530. value.updateOwner !== 'npm-prefix' ||
  531. value.packageManager !== 'npm' ||
  532. !packageName ||
  533. typeof value.registry !== 'string' ||
  534. value.distTag !== 'latest' ||
  535. typeof value.prefix !== 'string' ||
  536. typeof value.npmExecutable !== 'string'
  537. ) {
  538. return undefined;
  539. }
  540. const distribution = resolveMcodeNpmDistribution(packageName, value.registry);
  541. if (
  542. normalizeResolvedPath(value.prefix, platform) !== normalizeResolvedPath(prefix, platform) ||
  543. new URL(value.registry).href !== distribution.registry ||
  544. !existsSync(value.npmExecutable)
  545. ) {
  546. return undefined;
  547. }
  548. if (
  549. legacyLayout &&
  550. normalizeResolvedPath(packagePrefix, platform) !== normalizeResolvedPath(prefix, platform)
  551. ) {
  552. return undefined;
  553. }
  554. if (versionedLayout) {
  555. const expectedReleasesRoot = platformPath.join(prefix, 'releases');
  556. const relativeRelease = platformPath.relative(expectedReleasesRoot, packagePrefix);
  557. if (
  558. !relativeRelease ||
  559. relativeRelease.startsWith('..') ||
  560. platformPath.isAbsolute(relativeRelease) ||
  561. relativeRelease.includes(platformPath.sep) ||
  562. !/^[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(relativeRelease) ||
  563. !isResolvedPathInside(packagePrefix, packageRoot, platformPath)
  564. ) {
  565. return undefined;
  566. }
  567. }
  568. return {
  569. executable: value.npmExecutable,
  570. packageName,
  571. prefix,
  572. registry: distribution.registry,
  573. };
  574. } catch {
  575. return undefined;
  576. }
  577. }
  578. function isResolvedPathInside(
  579. root: string,
  580. candidate: string,
  581. platformPath: typeof path.posix | typeof path.win32,
  582. ): boolean {
  583. const relative = platformPath.relative(
  584. platformPath.resolve(root),
  585. platformPath.resolve(candidate),
  586. );
  587. return relative !== '' && !relative.startsWith('..') && !platformPath.isAbsolute(relative);
  588. }
  589. function parseMcodePackageName(value: unknown): McodeNpmPackageName | undefined {
  590. if (value === mcodePackageName(MCODE_INTERNAL_SCOPE)) return value as McodeNpmPackageName;
  591. if (value === mcodePackageName(MCODE_PUBLIC_SCOPE)) return value as McodeNpmPackageName;
  592. return undefined;
  593. }
  594. function mcodePackageName(scope: string): McodeNpmPackageName {
  595. return `${scope}/${MCODE_PACKAGE_BASENAME}` as McodeNpmPackageName;
  596. }
  597. function mcodePackageNameFromPath(packageRoot: string): McodeNpmPackageName | undefined {
  598. const normalized = packageRoot.replaceAll('\\', '/');
  599. const segments = normalized.split('/');
  600. if (segments.at(-1) !== MCODE_PACKAGE_BASENAME) return undefined;
  601. return parseMcodePackageName(`${segments.at(-2)}/${MCODE_PACKAGE_BASENAME}`);
  602. }
  603. function normalizeResolvedPath(value: string, platform: NodeJS.Platform): string {
  604. let resolved: string;
  605. try {
  606. resolved = realpathSync(value);
  607. } catch {
  608. resolved = (platform === 'win32' ? path.win32 : path.posix).resolve(value);
  609. }
  610. return platform === 'win32' ? resolved.toLocaleLowerCase() : resolved;
  611. }
  612. function runText(
  613. command: string,
  614. args: readonly string[],
  615. environment: NodeJS.ProcessEnv = process.env,
  616. ): Promise<string> {
  617. return new Promise((resolve, reject) => {
  618. let settled = false;
  619. const child = spawn(command, [...args], {
  620. env: environment,
  621. shell: false,
  622. stdio: ['ignore', 'pipe', 'pipe'],
  623. windowsHide: true,
  624. });
  625. const stdout: Buffer[] = [];
  626. const stderr: Buffer[] = [];
  627. child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk));
  628. child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk));
  629. child.once('error', (error) => {
  630. if (settled) return;
  631. settled = true;
  632. reject(error);
  633. });
  634. child.once('exit', (code, signal) => {
  635. if (settled) return;
  636. settled = true;
  637. if (code === 0) {
  638. resolve(Buffer.concat(stdout).toString('utf8').trim());
  639. return;
  640. }
  641. const details = Buffer.concat([...stderr, ...stdout])
  642. .toString('utf8')
  643. .trim();
  644. reject(
  645. new Error(
  646. `${command} failed (${
  647. signal ? `signal ${signal}` : `exit ${String(code)}`
  648. })${details ? `: ${details}` : ''}`,
  649. ),
  650. );
  651. });
  652. });
  653. }