Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/egg/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ export { Singleton, type SingletonCreateMethod, type SingletonOptions } from '@e
export * from './lib/error/index.ts';

// export loggers
export type { LoggerLevel, EggLogger, EggLogger as Logger } from 'egg-logger';
export { EggLogger as Logger } from 'egg-logger';
export type { LoggerLevel, EggLogger } from 'egg-logger';
Comment thread
killagu marked this conversation as resolved.

// export httpClients
export * from './lib/core/httpclient.ts';
Expand Down
5 changes: 5 additions & 0 deletions packages/egg/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ export interface HttpClientConfig {
*/
export type PowerPartial<T> = PartialDeep<T>;

// Some applications use this framework type name in decorated fields without
// `import type`; keep a runtime export available for decorator metadata and
// bundler static export validation while the interface below remains the type.
export const EggAppConfig: ObjectConstructor = Object;

export interface EggAppConfig extends EggCoreAppConfig {
workerStartTimeout: number;
baseDir: string;
Expand Down
2 changes: 2 additions & 0 deletions packages/egg/test/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ exports[`should expose properties 1`] = `
"Controller": [Function],
"CookieLimitExceedError": [Function],
"Cookies": [Function],
"EggAppConfig": [Function],
"EggApplicationCore": [Function],
"EggQualifier": [Function],
"EggType": {
Expand Down Expand Up @@ -70,6 +71,7 @@ exports[`should expose properties 1`] = `
"LifecyclePreDestroy": [Function],
"LifecyclePreInject": [Function],
"LifecyclePreLoad": [Function],
"Logger": [Function],
"Master": [Function],
"MessageUnhandledRejectionError": [Function],
"MetadataUtil": [Function],
Expand Down
2 changes: 2 additions & 0 deletions packages/egg/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ import * as egg from '../src/index.ts';
test('should expose properties', () => {
expect(egg).toMatchSnapshot();
expect(egg.Context).toBeDefined();
expect(egg.EggAppConfig).toBe(Object);
expect(egg.Logger).toBeDefined();
});
1 change: 0 additions & 1 deletion tools/egg-bundler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@
},
"dependencies": {
"@eggjs/core": "workspace:*",
"@eggjs/utils": "workspace:*",
"@utoo/pack": "catalog:",
"execa": "catalog:",
"tsx": "catalog:"
Expand Down
26 changes: 22 additions & 4 deletions tools/egg-bundler/src/lib/EntryGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export class EntryGenerator {
}

const manifestJson = JSON.stringify(manifest, null, 2);
const frameworkSpec = JSON.stringify(this.#framework);
const frameworkSpec = JSON.stringify(this.#toFrameworkImportSpecifier());

const externalBlock =
externalSpecs.length > 0
Expand All @@ -215,7 +215,6 @@ for (const [key, spec] of __EXTERNAL_SPECS) {
import path from 'node:path';

import { ManifestStore } from '@eggjs/core';
import { setBundleModuleLoader } from '@eggjs/utils';
import { startEgg } from ${frameworkSpec};

${importLines.join('\n')}
Expand All @@ -239,11 +238,14 @@ for (const [rel, mod] of Object.entries(__BUNDLE_MAP_REL)) {
__BUNDLE_MAP[rel] = mod;
}

const __bundleGlobalThis = globalThis as typeof globalThis & {
__EGG_BUNDLE_MODULE_LOADER__?: (filepath: string) => unknown;
};
ManifestStore.setBundleStore(ManifestStore.fromBundle(MANIFEST_DATA as any, __baseDir));
setBundleModuleLoader((filepath) => {
__bundleGlobalThis.__EGG_BUNDLE_MODULE_LOADER__ = (filepath) => {
const key = filepath.split(path.sep).join('/');
return __BUNDLE_MAP[key];
});
};
Comment thread
killagu marked this conversation as resolved.

startEgg({ baseDir: __baseDir, mode: 'single' }).then((app) => {
const port = process.env.PORT || app.config.cluster?.listen?.port || 7001;
Expand All @@ -259,6 +261,22 @@ startEgg({ baseDir: __baseDir, mode: 'single' }).then((app) => {
`;
}

#toFrameworkImportSpecifier(): string {
if (!path.isAbsolute(this.#framework)) return this.#framework;
const packageName = this.#packageNameFromDir(this.#framework);
return packageName ?? this.#toImportSpecifier(this.#framework);
}
Comment thread
killagu marked this conversation as resolved.

#packageNameFromDir(dir: string): string | undefined {
try {
const req = createRequire(path.join(dir, 'package.json'));
const pkg = req(path.join(dir, 'package.json')) as { name?: unknown };
return typeof pkg.name === 'string' && pkg.name ? pkg.name : undefined;
} catch {
return undefined;
}
}

#toImportSpecifier(absPath: string): string {
// Prefer a relative specifier from the entry output dir to keep the
// bundled paths portable across machines (absolute paths would leak
Expand Down
28 changes: 28 additions & 0 deletions tools/egg-bundler/src/lib/ExternalsResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ interface PackageJson {
readonly dependencies?: Record<string, string>;
readonly optionalDependencies?: Record<string, string>;
readonly peerDependencies?: Record<string, string>;
readonly peerDependenciesMeta?: Record<string, { optional?: boolean }>;
readonly scripts?: Record<string, string>;
readonly exports?: unknown;
}
Expand Down Expand Up @@ -55,6 +56,7 @@ export class ExternalsResolver {
if (await this.#shouldExternalize(name, optionalDeps, peerDeps)) {
result[name] = name;
}
await this.#addMissingOptionalPeerExternals(name, result);
}

for (const name of peerDeps) {
Expand All @@ -65,6 +67,21 @@ export class ExternalsResolver {
return result;
}

async #addMissingOptionalPeerExternals(name: string, result: Record<string, string>): Promise<void> {
const pkgDir = await this.#findPackageDir(name);
if (!pkgDir) return;
const pkg = await this.#readPackageJson(pkgDir);
const peerDependencies = pkg.peerDependencies ?? {};
const peerDependenciesMeta = pkg.peerDependenciesMeta ?? {};
for (const peerName of Object.keys(peerDependencies)) {
if (result[peerName]) continue;
if (this.#inline.has(peerName) && !this.#force.has(peerName)) continue;
if (!peerDependenciesMeta[peerName]?.optional) continue;
if (await this.#findPackageDir(peerName)) continue;
result[peerName] = peerName;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
}

async #shouldExternalize(
name: string,
optionalDeps: ReadonlySet<string>,
Expand All @@ -76,10 +93,21 @@ export class ExternalsResolver {
const pkgDir = await this.#findPackageDir(name);
if (!pkgDir) return false;
const pkg = await this.#readPackageJson(pkgDir);
if (await this.#hasMissingOptionalPeerDependencies(pkg)) return true;
if (await this.#hasNativeBinary(pkgDir, pkg)) return true;
return false;
}

async #hasMissingOptionalPeerDependencies(pkg: PackageJson): Promise<boolean> {
const peerDependencies = pkg.peerDependencies ?? {};
const peerDependenciesMeta = pkg.peerDependenciesMeta ?? {};
for (const peerName of Object.keys(peerDependencies)) {
if (!peerDependenciesMeta[peerName]?.optional) continue;
if (!(await this.#findPackageDir(peerName))) return true;
}
return false;
}

async #findPackageDir(name: string): Promise<string | undefined> {
const cached = this.#packageDirCache.get(name);
if (cached) return cached;
Expand Down
22 changes: 19 additions & 3 deletions tools/egg-bundler/test/EntryGenerator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,9 @@ describe('EntryGenerator', () => {
const worker = await fs.readFile(result.workerEntry, 'utf8');

expect(worker).toContain("import { ManifestStore } from '@eggjs/core'");
expect(worker).toContain("import { setBundleModuleLoader } from '@eggjs/utils'");
expect(worker).toContain('import { startEgg } from "egg"');
expect(worker).toContain('ManifestStore.setBundleStore(ManifestStore.fromBundle(MANIFEST_DATA');
expect(worker).toContain('setBundleModuleLoader(');
expect(worker).toContain('__EGG_BUNDLE_MODULE_LOADER__');
expect(worker).toContain("startEgg({ baseDir: __baseDir, mode: 'single' })");
});

Expand Down Expand Up @@ -244,7 +243,7 @@ describe('EntryGenerator', () => {

expect(extractImports(worker).length).toBe(0);
expect(worker).toContain("startEgg({ baseDir: __baseDir, mode: 'single' })");
expect(worker).toContain('setBundleModuleLoader(');
expect(worker).toContain('__EGG_BUNDLE_MODULE_LOADER__');
expect(worker).toContain('ManifestStore.setBundleStore');
});

Expand Down Expand Up @@ -284,6 +283,23 @@ describe('EntryGenerator', () => {
expect(worker).not.toContain('import { startEgg } from "egg"');
});

it('uses the package name for an absolute framework directory with package metadata', async () => {
const frameworkDir = path.join(tmpDir, 'node_modules/custom-egg');
await fs.mkdir(frameworkDir, { recursive: true });
await fs.writeFile(path.join(frameworkDir, 'package.json'), JSON.stringify({ name: 'custom-egg' }));

const gen = new EntryGenerator({
baseDir: tmpDir,
framework: frameworkDir,
manifestLoader: createFakeLoader(makeManifest()),
});
const result = await gen.generate();
const worker = await fs.readFile(result.workerEntry, 'utf8');

expect(worker).toContain('import { startEgg } from "custom-egg"');
expect(worker).not.toContain(frameworkDir);
});

it('produces byte-identical worker output across independent baseDir runs (T17 determinism baseline)', async () => {
const manifest = makeManifest({
extensions: {
Expand Down
16 changes: 16 additions & 0 deletions tools/egg-bundler/test/ExternalsResolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ describe('ExternalsResolver', () => {
const result = await new ExternalsResolver({ baseDir: basicApp }).resolve();
expect(result['optional-only']).toBe('optional-only');
});

it('externalizes missing optional peerDependencies declared by installed dependencies', async () => {
const result = await new ExternalsResolver({ baseDir: basicApp }).resolve();
expect(result['optional-peer-host']).toBe('optional-peer-host');
expect(result['missing-optional-peer']).toBe('missing-optional-peer');
expect(result['required-peer']).toBeUndefined();
expect(result['normal-js']).toBeUndefined();
});
});

describe('negative cases', () => {
Expand Down Expand Up @@ -154,6 +162,14 @@ describe('ExternalsResolver', () => {
expect(result['optional-only']).toBeUndefined();
});

it('inline removes a missing optional peerDependency from externals', async () => {
const result = await new ExternalsResolver({
baseDir: basicApp,
inline: ['missing-optional-peer'],
}).resolve();
expect(result['missing-optional-peer']).toBeUndefined();
});

it('force can still externalize framework and helper packages explicitly', async () => {
const result = await new ExternalsResolver({
baseDir: basicApp,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import path from 'node:path';

import { ManifestStore } from '@eggjs/core';
import { setBundleModuleLoader } from '@eggjs/utils';
import { startEgg } from "egg";

import * as __m0 from "../../app/controller/home.ts";
Expand Down Expand Up @@ -67,11 +66,14 @@ for (const [rel, mod] of Object.entries(__BUNDLE_MAP_REL)) {
__BUNDLE_MAP[rel] = mod;
}

const __bundleGlobalThis = globalThis as typeof globalThis & {
__EGG_BUNDLE_MODULE_LOADER__?: (filepath: string) => unknown;
};
ManifestStore.setBundleStore(ManifestStore.fromBundle(MANIFEST_DATA as any, __baseDir));
setBundleModuleLoader((filepath) => {
__bundleGlobalThis.__EGG_BUNDLE_MODULE_LOADER__ = (filepath) => {
const key = filepath.split(path.sep).join('/');
return __BUNDLE_MAP[key];
});
};

startEgg({ baseDir: __baseDir, mode: 'single' }).then((app) => {
const port = process.env.PORT || app.config.cluster?.listen?.port || 7001;
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"native-dotnode": "1.0.0",
"native-prebuilds": "1.0.0",
"native-scripts": "1.0.0",
"normal-js": "1.0.0"
"normal-js": "1.0.0",
"optional-peer-host": "1.0.0"
},
"peerDependencies": {
"peer-only": "1.0.0"
Expand Down
Loading