fix(coding): resolve packaged Pi imports from runtime root
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { findPackageJSON } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
@@ -14,12 +15,36 @@ const runtimeRoot = runtimeRootFromArgs(process.argv.slice(2));
|
||||
const runtimeModule = (...segments) => pathToFileURL(path.join(runtimeRoot, ...segments)).href;
|
||||
const runtimePackageUrl = pathToFileURL(path.join(runtimeRoot, 'package.json')).href;
|
||||
|
||||
async function runtimePackageModule(packageName) {
|
||||
const packageJsonPath = findPackageJSON(packageName, runtimePackageUrl);
|
||||
if (!packageJsonPath) throw new Error(`Runtime package is unavailable: ${packageName}`);
|
||||
const packageRoot = path.dirname(packageJsonPath);
|
||||
const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8'));
|
||||
const rootExport = packageJson.exports?.['.'];
|
||||
const entry = (
|
||||
typeof rootExport === 'string'
|
||||
? rootExport
|
||||
: rootExport?.import
|
||||
) ?? packageJson.module ?? packageJson.main;
|
||||
if (typeof entry !== 'string' || !entry.trim()) {
|
||||
throw new Error(`Runtime package import entry is unavailable: ${packageName}`);
|
||||
}
|
||||
const entryPath = path.resolve(packageRoot, entry);
|
||||
const entryRelative = path.relative(packageRoot, entryPath);
|
||||
if (!entryRelative || entryRelative === '..' || entryRelative.startsWith(`..${path.sep}`)
|
||||
|| path.isAbsolute(entryRelative)) {
|
||||
throw new Error(`Runtime package import entry escapes its package: ${packageName}`);
|
||||
}
|
||||
return pathToFileURL(entryPath).href;
|
||||
}
|
||||
|
||||
const outputGuard = await import(runtimeModule('dist', 'core', 'output-guard.js'));
|
||||
outputGuard.takeOverStdout();
|
||||
const piAiModule = await runtimePackageModule('@earendil-works/pi-ai');
|
||||
|
||||
const [pi, piAi, httpDispatcher, jsonEvents, jsonl, themeModule, shellModule] = await Promise.all([
|
||||
import(runtimeModule('dist', 'index.js')),
|
||||
import(import.meta.resolve('@earendil-works/pi-ai', runtimePackageUrl)),
|
||||
import(piAiModule),
|
||||
import(runtimeModule('dist', 'core', 'http-dispatcher.js')),
|
||||
import(runtimeModule('dist', 'modes', 'json-event.js')),
|
||||
import(runtimeModule('dist', 'modes', 'rpc', 'jsonl.js')),
|
||||
|
||||
Reference in New Issue
Block a user