Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
47 changes: 24 additions & 23 deletions packages/egg/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Helper from './app/extend/helper.ts';
import { BaseContextClass } from './lib/core/base_context_class.ts';
import { startEgg, type SingleModeApplication, type SingleModeAgent } from './lib/start.ts';
import { EggAppConfig, type EggAppConfig as EggAppConfigType } from './lib/types.ts';

// export extends
export { Helper };
Expand All @@ -16,28 +17,27 @@ export * from './lib/types.ts';
export * from './lib/define.ts';

// alias EggAppConfig to Config
export type {
/**
* Egg Application Config, can be injected into Proto, e.g. SingletonProto/ContextProto/HttpController.
*
* Usage:
* ```ts
* import { Inject, Config } from 'egg';
*
* @SingletonProto()
* class FooService {
* @Inject()
* config: Config;
*
* async bar() {
* console.log(this.config.env);
* }
* }
* ```
* @since 4.1.0
*/
EggAppConfig as Config,
} from './lib/types.ts';
export const Config: typeof EggAppConfig = EggAppConfig;
/**
* Egg Application Config, can be injected into Proto, e.g. SingletonProto/ContextProto/HttpController.
*
* Usage:
* ```ts
* import { Inject, Config } from 'egg';
*
* @SingletonProto()
* class FooService {
* @Inject()
* config: Config;
*
* async bar() {
* console.log(this.config.env);
* }
* }
* ```
* @since 4.1.0
*/
export type Config = EggAppConfigType;

export * from './lib/start.ts';

Expand All @@ -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
3 changes: 3 additions & 0 deletions packages/egg/test/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ exports[`should expose properties 1`] = `
"Boot": [Function],
"ClusterAgentWorkerError": [Function],
"ClusterWorkerExceptionError": [Function],
"Config": [Function],
"Context": [Function],
"ContextHttpClient": [Function],
"ContextProto": [Function],
"Controller": [Function],
"CookieLimitExceedError": [Function],
"Cookies": [Function],
"EggAppConfig": [Function],
"EggApplicationCore": [Function],
"EggQualifier": [Function],
"EggType": {
Expand Down Expand Up @@ -70,6 +72,7 @@ exports[`should expose properties 1`] = `
"LifecyclePreDestroy": [Function],
"LifecyclePreInject": [Function],
"LifecyclePreLoad": [Function],
"Logger": [Function],
"Master": [Function],
"MessageUnhandledRejectionError": [Function],
"MetadataUtil": [Function],
Expand Down
7 changes: 6 additions & 1 deletion packages/egg/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import assert from 'node:assert/strict';

import { test, expect } from 'vitest';

import * as egg from '../src/index.ts';

test('should expose properties', () => {
expect(egg).toMatchSnapshot();
expect(egg.Context).toBeDefined();
assert.ok(egg.Context);
assert.strictEqual(egg.Config, Object);
assert.strictEqual(egg.EggAppConfig, Object);
assert.ok(egg.Logger);
});
8 changes: 5 additions & 3 deletions tools/egg-bundler/docs/output-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ node worker.js
```

The worker entry installs `ManifestStore.setBundleStore(...)` and
`setBundleModuleLoader(...)` before calling `startEgg({ baseDir, mode: 'single' })`,
so all framework file discovery and module resolution is served from the
inlined bundle map — no `fs.readdir` scanning at runtime.
`globalThis.__EGG_BUNDLE_MODULE_LOADER__` before calling
`startEgg({ baseDir, mode: 'single' })`, so framework module resolution for
bundled files is served from the inlined bundle map, avoiding `fs.readdir` for
bundled framework file discovery. Application code and plugins may still use
`fs` for resources such as config, views, or assets.

## `bundle-manifest.json`

Expand Down
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
41 changes: 35 additions & 6 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 @@ -51,6 +52,7 @@ export class ExternalsResolver {

for (const name of deps) {
if (this.#inline.has(name) && !this.#force.has(name)) continue;
await this.#addMissingOptionalPeerExternals(name, result);
if (result[name]) continue;
if (await this.#shouldExternalize(name, optionalDeps, peerDeps)) {
result[name] = name;
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, pkgDir)) continue;
result[peerName] = peerName;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
}

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

async #findPackageDir(name: string): Promise<string | undefined> {
const cached = this.#packageDirCache.get(name);
async #hasMissingOptionalPeerDependencies(pkgDir: string, 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, pkgDir))) return true;
}
return false;
}

async #findPackageDir(name: string, fromDir = this.#baseDir): Promise<string | undefined> {
const cacheKey = `${fromDir}\0${name}`;
const cached = this.#packageDirCache.get(cacheKey);
if (cached) return cached;
const result = this.#findPackageDirUncached(name);
this.#packageDirCache.set(name, result);
const result = this.#findPackageDirUncached(name, fromDir);
this.#packageDirCache.set(cacheKey, result);
return result;
}

async #findPackageDirUncached(name: string): Promise<string | undefined> {
let dir = this.#baseDir;
async #findPackageDirUncached(name: string, fromDir: string): Promise<string | undefined> {
let dir = fromDir;
while (true) {
const candidate = path.join(dir, 'node_modules', name);
try {
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
Loading
Loading