diff --git a/package.json b/package.json index 889ae4e4..22313656 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "@angular-devkit/core": "~22.2.0", "@angular-devkit/schematics": "~22.2.0", "@chialab/esbuild-plugin-commonjs": "^0.19.0", - "@softarc/native-federation": "4.9.0-next.0", + "@softarc/native-federation": "~4.9.0", "@softarc/native-federation-orchestrator": "^4.8.0", "es-module-shims": "^2.8.0", "esbuild": "^0.28.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a269425..f9d7362c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -25,11 +25,11 @@ importers: specifier: ^0.19.0 version: 0.19.1 '@softarc/native-federation': - specifier: 4.9.0-next.0 - version: 4.9.0-next.0 + specifier: ~4.9.0 + version: 4.9.0 '@softarc/native-federation-orchestrator': specifier: ^4.8.0 - version: 4.8.0(@softarc/native-federation@4.9.0-next.0) + version: 4.8.0(@softarc/native-federation@4.9.0) es-module-shims: specifier: ^2.8.0 version: 2.8.4 @@ -1574,8 +1574,8 @@ packages: '@softarc/native-federation': optional: true - '@softarc/native-federation@4.9.0-next.0': - resolution: {integrity: sha512-7Hy3xTr4pkyqCSdTHAsoUoIlky5B1ln0Sfl4BXRw+Mw5+jgzIe5op1xCGGdVgbjXQiSOnK3SGVHiFaRGnbTjVg==, tarball: https://registry.npmjs.org/@softarc/native-federation/-/native-federation-4.9.0-next.0.tgz} + '@softarc/native-federation@4.9.0': + resolution: {integrity: sha512-XwXxZprCd69C6DC0NFBTLqqpVVvcwzhTU+Nka4Mom/1av6ofTHYcZAu/tcr22Rtenj87LB2LN/uEAMbWLiHgkg==, tarball: https://registry.npmjs.org/@softarc/native-federation/-/native-federation-4.9.0.tgz} '@softarc/sheriff-core@0.20.0': resolution: {integrity: sha512-dTm5dOUMOGTV3ql7ZIuI8rE+gZawIcJLEluqRYX3KDVJ215vfUzpC9LlSL4pTW0lAAeNLelmPZBzY57jLvOPpg==, tarball: https://registry.npmjs.org/@softarc/sheriff-core/-/sheriff-core-0.20.0.tgz} @@ -3474,21 +3474,20 @@ snapshots: '@clack/core@1.4.3': dependencies: - fast-wrap-ansi: 0.2.0 + fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 '@clack/prompts@1.7.0': dependencies: '@clack/core': 1.4.3 fast-string-width: 3.0.2 - fast-wrap-ansi: 0.2.0 + fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 '@emnapi/core@1.11.2': dependencies: '@emnapi/wasi-threads': 1.2.2 tslib: 2.8.1 - optional: true '@emnapi/core@1.4.5': dependencies: @@ -3504,7 +3503,6 @@ snapshots: '@emnapi/runtime@1.11.2': dependencies: tslib: 2.8.1 - optional: true '@emnapi/runtime@1.4.5': dependencies: @@ -3522,7 +3520,6 @@ snapshots: '@emnapi/wasi-threads@1.2.2': dependencies: tslib: 2.8.1 - optional: true '@emnapi/wasi-threads@2.0.1': dependencies: @@ -3836,8 +3833,8 @@ snapshots: '@napi-rs/wasm-runtime@0.2.4': dependencies: - '@emnapi/core': 1.4.5 - '@emnapi/runtime': 1.4.5 + '@emnapi/core': 1.11.2 + '@emnapi/runtime': 1.11.2 '@tybys/wasm-util': 0.9.0 '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)': @@ -4261,19 +4258,18 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.65.0': optional: true - '@softarc/native-federation-orchestrator@4.8.0(@softarc/native-federation@4.9.0-next.0)': + '@softarc/native-federation-orchestrator@4.8.0(@softarc/native-federation@4.9.0)': dependencies: semver: 7.8.5 optionalDependencies: - '@softarc/native-federation': 4.9.0-next.0 + '@softarc/native-federation': 4.9.0 - '@softarc/native-federation@4.9.0-next.0': + '@softarc/native-federation@4.9.0': dependencies: '@jridgewell/sourcemap-codec': 1.6.0 '@softarc/sheriff-core': 0.20.0(typescript@6.0.3) chalk: 6.0.1 es-module-lexer: 2.3.2 - esbuild: 0.28.2 tinyglobby: 0.2.17 typescript: 6.0.3 diff --git a/src/builders/build/builder.ts b/src/builders/build/builder.ts index d56bb603..fdc40789 100644 --- a/src/builders/build/builder.ts +++ b/src/builders/build/builder.ts @@ -27,7 +27,6 @@ import { type JsonObject } from "@angular-devkit/core"; import { buildForFederation, createFederationCache, - type FederationInfo, getExternals, normalizeFederationOptions, rebuildForFederation, @@ -35,6 +34,7 @@ import { } from "@softarc/native-federation"; import { AbortedError, + collectOutputFiles, createNfWatcher, linkedSharedDirs, logger, @@ -495,9 +495,8 @@ export async function* runBuilder( fs.mkdirSync(federationOutputPath, { recursive: true }); } - let federationResult: FederationInfo; try { - federationResult = await buildForFederation( + await buildForFederation( normalized.config, normalized.options, externals, @@ -523,7 +522,7 @@ export async function* runBuilder( i18n, localeFilter, path.join(outputOptions.base, outputOptions.browser), - federationResult, + collectOutputFiles(normalized.options.federationCache).map((f) => f.fileName), context.workspaceRoot, ); logger.measure(start, "To translate the artifacts."); @@ -610,7 +609,7 @@ export async function* runBuilder( if (nfWatcher) nfWatcher.clear(); - federationResult = await rebuildForFederation( + await rebuildForFederation( normalized.config, normalized.options, externals, @@ -629,7 +628,7 @@ export async function* runBuilder( i18n, localeFilter, path.join(outputOptions.base, outputOptions.browser), - federationResult, + collectOutputFiles(normalized.options.federationCache).map((f) => f.fileName), context.workspaceRoot, ); } diff --git a/src/builders/build/i18n.integration.spec.ts b/src/builders/build/i18n.integration.spec.ts index f8f104d9..9b2a6114 100644 --- a/src/builders/build/i18n.integration.spec.ts +++ b/src/builders/build/i18n.integration.spec.ts @@ -1,6 +1,5 @@ import * as fs from 'fs'; import * as path from 'path'; -import type { FederationInfo } from '@softarc/native-federation'; import { translateFederationArtifacts, type I18nConfig } from './i18n.js'; @@ -44,22 +43,21 @@ describe('translateFederationArtifacts with the real localize-translate CLI', () write(sourceFile('cmp.js'), 'export const t = $localize`:@@greeting:Hello`;'); write(sourceFile('chunk.js'), 'export const c = $localize`:@@greeting:Hello`;'); write(sourceFile('chunk.css'), 'a{}'); + write(sourceFile('chunk.js.map'), '{"version":3}'); // Angular's own output sits in the same folder and must be left alone write(sourceFile('main.js'), 'export const m = $localize`:@@greeting:Hello`;'); const i18n: I18nConfig = { sourceLocale: 'en', locales: { de: translation } }; - const federationResult = { - shared: [], - exposes: [{ outFileName: 'cmp.js' }], - chunks: { c1: ['chunk.js', 'chunk.css'] }, - } as unknown as FederationInfo; + // core reports every file it wrote, chunks of non-dense bundles and source maps included + const federationFiles = ['cmp.js', 'chunk.js', 'chunk.css', 'chunk.js.map']; - translateFederationArtifacts(i18n, true, 'dist/browser', federationResult, workspaceRoot); + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, workspaceRoot); const de = (name: string) => fs.readFileSync(path.join(browser, 'de', name), 'utf8'); expect(de('cmp.js')).toContain('Hallo'); expect(de('chunk.js')).toContain('Hallo'); expect(de('chunk.css')).toBe('a{}'); + expect(de('chunk.js.map')).toBe('{"version":3}'); expect(fs.existsSync(path.join(browser, 'de', 'main.js'))).toBe(false); }); @@ -71,14 +69,8 @@ describe('translateFederationArtifacts with the real localize-translate CLI', () write(path.join(browser, 'en', 'remoteEntry.json'), '{}'); const i18n: I18nConfig = { sourceLocale: 'en', locales: { de: translation } }; - const federationResult = { - shared: [], - exposes: [{ outFileName: 'missing.js' }], - chunks: {}, - } as unknown as FederationInfo; - expect(() => - translateFederationArtifacts(i18n, true, 'dist/browser', federationResult, workspaceRoot) + translateFederationArtifacts(i18n, true, 'dist/browser', ['missing.js'], workspaceRoot) ).toThrow(/ENOENT/); }); }); diff --git a/src/builders/build/i18n.spec.ts b/src/builders/build/i18n.spec.ts index 0b9e7490..8427e88b 100644 --- a/src/builders/build/i18n.spec.ts +++ b/src/builders/build/i18n.spec.ts @@ -2,7 +2,6 @@ import * as fs from 'fs'; import { execFileSync } from 'child_process'; import { logger } from '@softarc/native-federation/internal'; import type { BuilderContext } from '@angular-devkit/architect'; -import type { FederationInfo } from '@softarc/native-federation'; import { getI18nConfig, @@ -34,11 +33,7 @@ const infoSpy = vi.spyOn(logger, 'info').mockImplementation(() => undefined); const debugSpy = vi.spyOn(logger, 'debug').mockImplementation(() => undefined); const errorSpy = vi.spyOn(logger, 'error').mockImplementation(() => undefined); -const federationResult = { - shared: [{ outFileName: 'dep1.js' }], - exposes: [{ outFileName: 'cmp.js' }], - chunks: { c1: ['chunk1.js'] }, -} as unknown as FederationInfo; +const federationFiles = ['dep1.js', 'cmp.js', 'chunk1.js']; afterEach(() => { vi.clearAllMocks(); @@ -91,7 +86,7 @@ describe('translateFederationArtifacts', () => { }); it('does nothing when no configured locale matches the requested ones', async () => { - translateFederationArtifacts(i18n, ['es'], 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(i18n, ['es'], 'dist/browser', federationFiles, '/ws'); expect(execFileSync).not.toHaveBeenCalled(); expect(fs.mkdirSync).not.toHaveBeenCalled(); @@ -99,7 +94,7 @@ describe('translateFederationArtifacts', () => { }); it('filters to the intersection of requested and configured locales', async () => { - translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); const args = localizeArgs(); const targets = args.slice(args.indexOf('--target-locales') + 1, args.indexOf('-l')); @@ -107,7 +102,7 @@ describe('translateFederationArtifacts', () => { }); it('builds the localize-translate command from the federation output files', async () => { - translateFederationArtifacts(i18n, true, 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, '/ws'); const [file, args] = vi.mocked(execFileSync).mock.calls[0]!; // the CLI script is run with node, not through a shell @@ -137,7 +132,7 @@ describe('translateFederationArtifacts', () => { .map(([from, to]) => [posix(String(from)), posix(String(to))]); it('stages the federation output files from the source locale folder', () => { - translateFederationArtifacts(i18n, true, 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, '/ws'); expect(fs.mkdirSync).toHaveBeenCalledWith(expect.stringMatching(/\.input$/), { recursive: true, @@ -149,32 +144,9 @@ describe('translateFederationArtifacts', () => { ]); }); - it('collects dense shared entries when denseExternals is enabled', () => { - const denseResult = { - shared: [{ entries: { esm: 'dep1.js', legacy: 'dep1.legacy.js' } }], - exposes: [{ outFileName: 'cmp.js' }], - chunks: { c1: ['chunk1.js'] }, - } as unknown as FederationInfo; - - translateFederationArtifacts(i18n, true, 'dist/browser', denseResult, '/ws'); - - expect(stagedFiles().map(([from]) => from!.split('/').pop())).toEqual([ - 'dep1.js', - 'dep1.legacy.js', - 'cmp.js', - 'chunk1.js', - ]); - }); - it('runs localize-translate once, however many files there are', () => { const manyFiles = Array.from({ length: 1000 }, (_, i) => `chunk-${i}-${'x'.repeat(40)}.js`); - const bigResult = { - shared: [], - exposes: [], - chunks: { c1: [...manyFiles, manyFiles[0]!] }, - } as unknown as FederationInfo; - - translateFederationArtifacts(i18n, true, 'dist/browser', bigResult, '/ws'); + translateFederationArtifacts(i18n, true, 'dist/browser', [...manyFiles, manyFiles[0]!], '/ws'); expect(execFileSync).toHaveBeenCalledTimes(1); expect(valueAfter(localizeArgs(), '-s')).toBe('**/*'); @@ -189,7 +161,7 @@ describe('translateFederationArtifacts', () => { locales: { de: 'm.de.xlf' }, }; - translateFederationArtifacts(objLocaleI18n, true, 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(objLocaleI18n, true, 'dist/browser', federationFiles, '/ws'); expect(valueAfter(localizeArgs(), '-l')).toBe('en-US'); }); @@ -198,14 +170,14 @@ describe('translateFederationArtifacts', () => { // outputPath.browser can be customised (or empty) in angular.json it('translates under the configured browser output folder instead of "browser"', () => { - translateFederationArtifacts(i18n, ['de'], 'dist/web', federationResult, '/ws'); + translateFederationArtifacts(i18n, ['de'], 'dist/web', federationFiles, '/ws'); expect(stagedFiles()[0]![0]).toBe('/ws/dist/web/en/dep1.js'); expect(mkdirTargets()).toContain('/ws/dist/web/de'); }); it('writes the locale folders directly under the base when the browser folder is empty', () => { - translateFederationArtifacts(i18n, ['de'], 'dist', federationResult, '/ws'); + translateFederationArtifacts(i18n, ['de'], 'dist', federationFiles, '/ws'); expect(stagedFiles()[0]![0]).toBe('/ws/dist/en/dep1.js'); expect(mkdirTargets()).toContain('/ws/dist/de'); @@ -217,7 +189,7 @@ describe('translateFederationArtifacts', () => { { locales: { de: 'm.de.xlf' } }, true, 'dist/browser', - federationResult, + federationFiles, '/ws' ); @@ -230,7 +202,7 @@ describe('translateFederationArtifacts', () => { }); it('creates a dist folder and copies the remoteEntry for each target locale', async () => { - translateFederationArtifacts(i18n, true, 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, '/ws'); const mkdirPaths = vi.mocked(fs.mkdirSync).mock.calls.map(c => String(c[0])); expect(mkdirPaths.some(p => p.endsWith('browser/de'))).toBe(true); @@ -247,7 +219,7 @@ describe('translateFederationArtifacts', () => { }); it('resolves output, binary and cwd against workspaceRoot', async () => { - translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); const [, args, opts] = vi.mocked(execFileSync).mock.calls[0]!; expect(posix(args![0])).toContain('/ws/node_modules/@angular/localize/'); @@ -266,7 +238,7 @@ describe('translateFederationArtifacts', () => { locales: { de: { translation: 'm.de.xlf', subPath: 'deutsch' }, fr: 'm.fr.xlf' }, }; - translateFederationArtifacts(subPathI18n, true, 'dist/browser', federationResult, '/ws'); + translateFederationArtifacts(subPathI18n, true, 'dist/browser', federationFiles, '/ws'); const args = localizeArgs(); // localize-translate reads the staged files, which come from the source subPath, but writes per locale code @@ -299,7 +271,7 @@ describe('translateFederationArtifacts', () => { }); expect(() => - translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationResult, '/ws') + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws') ).toThrow('localize boom'); expect(errorSpy).toHaveBeenCalledWith('localize boom'); diff --git a/src/builders/build/i18n.ts b/src/builders/build/i18n.ts index 382db7c1..c015dbc7 100644 --- a/src/builders/build/i18n.ts +++ b/src/builders/build/i18n.ts @@ -5,7 +5,6 @@ import { createRequire } from 'module'; import os from 'os'; import path from 'path'; import fs from 'fs'; -import type { FederationInfo } from '@softarc/native-federation'; type WorkspaceConfig = { i18n?: I18nConfig; @@ -61,7 +60,7 @@ export function translateFederationArtifacts( i18n: I18nConfig, localize: boolean | string[], outputPath: string, - federationResult: FederationInfo, + federationFiles: string[], workspaceRoot: string ) { outputPath = path.resolve(workspaceRoot, outputPath); @@ -89,14 +88,6 @@ export function translateFederationArtifacts( const stagingPath = fs.mkdtempSync(path.join(os.tmpdir(), 'nf-i18n-')); const translationOutPath = path.join(stagingPath, '{{LOCALE}}'); - const federationFiles = [ - ...federationResult.shared.flatMap(s => - 'entries' in s ? Object.values(s.entries) : [s.outFileName] - ), - ...federationResult.exposes.map(e => e.outFileName), - ...Object.values(federationResult.chunks ?? {}).flat(), - ]; - const localePath = (locale: string) => path.join(outputPath, getLocaleSubPath(i18n, locale)); const sourceLocalePath = localePath(sourceLocale); diff --git a/src/tools/esbuild/angular-bundler.spec.ts b/src/tools/esbuild/angular-bundler.spec.ts index b915a8e3..74086c08 100644 --- a/src/tools/esbuild/angular-bundler.spec.ts +++ b/src/tools/esbuild/angular-bundler.spec.ts @@ -48,10 +48,7 @@ function makeOptions(overrides: Partial = {}) { tsConfigPath: 'apps/example/tsconfig.app.json', mappedPaths: {}, cache: { bundlerCache: { loadResultCache: {} }, cachePath: '/cache' }, - dev: false, - isMappingOrExposed: true, hash: false, - optimizedMappings: false, ...overrides, } as unknown as NormalizedContextOptions; } diff --git a/src/tools/esbuild/angular-esbuild-adapter.spec.ts b/src/tools/esbuild/angular-esbuild-adapter.spec.ts index 0e0cc770..b2acff93 100644 --- a/src/tools/esbuild/angular-esbuild-adapter.spec.ts +++ b/src/tools/esbuild/angular-esbuild-adapter.spec.ts @@ -23,6 +23,9 @@ const sharedBundleSettings = { target: ['chrome120'], sourcemap: false as const, const externalsCacheKey = { adapter: 'adapter@1.0.0', options: { target: 'chrome120' } }; const ngBuilderOptions = {} as never; +const mapping = { kind: 'mapping' } as never; +const exposed = { kind: 'exposed' } as never; +const shared = { kind: 'shared' } as never; const context = { workspaceRoot: '/ws' } as never; function makeCtx() { @@ -42,8 +45,6 @@ function normalizedWith(overrides: Record = {}) { external: [], outdir: '/out', cache: { bundlerCache: { invalidate: vi.fn(), loadResultCache: {} }, cachePath: '/c' }, - dev: false, - isMappingOrExposed: true, hash: false, ...overrides, }; @@ -76,12 +77,9 @@ describe('createAngularBuildAdapter', () => { }); it('bundles shared externals with the same settings the cache key was built from', async () => { - vi.mocked(normalizeContextOptions).mockReturnValue( - normalizedWith({ isMappingOrExposed: false }) as never - ); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('browser-shared', {} as never); + await adapter.setup('browser-shared', shared); expect(createNodeModulesEsbuildContext).toHaveBeenCalledWith( expect.anything(), @@ -103,24 +101,46 @@ describe('createAngularBuildAdapter', () => { ); }); - it('uses the Angular esbuild context for mapping/exposed builds and caches it', async () => { + it('uses the Angular esbuild context for mapping and exposed builds', async () => { const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); - // second setup with the same name is a no-op - await adapter.setup('remote', {} as never); + await adapter.setup('mapping-bundle', mapping); + await adapter.setup('remote', exposed); + expect(createAngularEsbuildContext).toHaveBeenCalledWith(expect.anything(), 'mapping-bundle'); expect(createAngularEsbuildContext).toHaveBeenCalledWith(expect.anything(), 'remote'); expect(createNodeModulesEsbuildContext).not.toHaveBeenCalled(); }); - it('uses the node_modules context when the build is not a mapping/exposed', async () => { - vi.mocked(normalizeContextOptions).mockReturnValue( - normalizedWith({ isMappingOrExposed: false }) as never - ); + // core 4.9 contract (core#203): a second setup under the same name replaces the context. + it('disposes the old context before setting up the same name again', async () => { + const oldCtx = makeCtx(); + let releasePlugin!: () => void; + const oldPluginDisposed = new Promise(resolve => (releasePlugin = resolve)); + vi.mocked(createAngularEsbuildContext).mockResolvedValueOnce({ + ctx: oldCtx as never, + pluginDisposed: oldPluginDisposed, + }); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); + await adapter.setup('remote', exposed); - await adapter.setup('deps', {} as never); + const replacing = adapter.setup('remote', exposed); + await new Promise(resolve => setTimeout(resolve, 0)); + // #47: the new compiler plugin must not start before the old one reset Angular's TS state + expect(oldCtx.dispose).toHaveBeenCalledTimes(1); + expect(createAngularEsbuildContext).toHaveBeenCalledTimes(1); + + releasePlugin(); + await replacing; + expect(createAngularEsbuildContext).toHaveBeenCalledTimes(2); + await adapter.build('remote'); + expect(oldCtx.rebuild).not.toHaveBeenCalled(); + }); + + it('uses the node_modules context for shared builds', async () => { + const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); + + await adapter.setup('deps', shared); expect(createNodeModulesEsbuildContext).toHaveBeenCalledTimes(1); expect(createAngularEsbuildContext).not.toHaveBeenCalled(); @@ -133,7 +153,7 @@ describe('createAngularBuildAdapter', () => { vi.mocked(fs.readFileSync).mockReturnValue('' as never); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); expect(fs.writeFileSync).not.toHaveBeenCalled(); expect(fs.readFileSync).not.toHaveBeenCalled(); @@ -141,7 +161,7 @@ describe('createAngularBuildAdapter', () => { it('rebuilds, writes output files and returns their paths', async () => { const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); const result = await adapter.build('remote'); @@ -171,7 +191,7 @@ describe('createAngularBuildAdapter', () => { } as never); vi.mocked(entriesByOutputName).mockReturnValue(new Map([['chunk-BBBB.js', 'chunk.js']])); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); const result = await adapter.build('remote'); @@ -202,7 +222,7 @@ describe('createAngularBuildAdapter', () => { pluginDisposed: Promise.resolve(), } as never); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); await adapter.build('remote'); @@ -228,7 +248,7 @@ describe('createAngularBuildAdapter', () => { pluginDisposed: Promise.resolve(), } as never); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); const result = await adapter.build('remote'); @@ -246,7 +266,7 @@ describe('createAngularBuildAdapter', () => { const normalized = normalizedWith(); vi.mocked(normalizeContextOptions).mockReturnValue(normalized as never); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); await adapter.build('remote', { modifiedFiles: ['a.ts'] }); @@ -255,7 +275,7 @@ describe('createAngularBuildAdapter', () => { it('throws AbortedError when the signal is already aborted', async () => { const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); await expect( adapter.build('remote', { signal: { aborted: true } as AbortSignal }) @@ -269,7 +289,7 @@ describe('createAngularBuildAdapter', () => { pluginDisposed: Promise.resolve(), }); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('remote', {} as never); + await adapter.setup('remote', exposed); await adapter.dispose(); @@ -294,12 +314,9 @@ describe('createAngularBuildAdapter', () => { }); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('mapping-bundle', {} as never); - await adapter.setup('mapping-or-exposed', {} as never); - vi.mocked(normalizeContextOptions).mockReturnValue( - normalizedWith({ isMappingOrExposed: false }) as never - ); - await adapter.setup('browser-shared', {} as never); + await adapter.setup('mapping-bundle', mapping); + await adapter.setup('mapping-or-exposed', exposed); + await adapter.setup('browser-shared', shared); await adapter.disposeFederationContexts(); @@ -319,7 +336,7 @@ describe('createAngularBuildAdapter', () => { pluginDisposed, }); const adapter = await createAngularBuildAdapter(ngBuilderOptions, context); - await adapter.setup('mapping-bundle', {} as never); + await adapter.setup('mapping-bundle', mapping); let done = false; const disposing = adapter.disposeFederationContexts().then(() => (done = true)); diff --git a/src/tools/esbuild/angular-esbuild-adapter.ts b/src/tools/esbuild/angular-esbuild-adapter.ts index f45beb17..cf9875a9 100644 --- a/src/tools/esbuild/angular-esbuild-adapter.ts +++ b/src/tools/esbuild/angular-esbuild-adapter.ts @@ -4,7 +4,6 @@ import { type NFBuildAdapter, type NFBuildAdapterResult, type NFBuildAdapterOptions, - type NFBuildAdapterContext, type FederationCache, type EntryPoint, } from '@softarc/native-federation'; @@ -22,8 +21,11 @@ import { resolveSharedBundleSettings } from './shared-bundle-settings.js'; import { normalizeContextOptions } from '../../utils/normalize-context-options.js'; import type { NfInternalOptions } from '../../builders/build/schema.js'; -interface EsbuildContextResult extends NFBuildAdapterContext { +interface EsbuildContextResult { + ctx: esbuild.BuildContext; pluginDisposed: Promise; + kind: NFBuildAdapterOptions['kind']; + outdir: string; cache: FederationCache; entryPoints: EntryPoint[]; } @@ -62,11 +64,13 @@ export async function createAngularBuildAdapter( const externalsCacheKey = createExternalsCacheKey(sharedBundleSettings); const bundleContextCache = new Map(); - const disposeWhere = async (matches: (entry: EsbuildContextResult) => boolean) => { + const disposeWhere = async ( + matches: (entry: EsbuildContextResult, name: string) => boolean + ) => { const disposals: Promise[] = []; for (const [name, entry] of bundleContextCache) { - if (!matches(entry)) continue; + if (!matches(entry, name)) continue; bundleContextCache.delete(name); disposals.push( (async () => { @@ -84,7 +88,7 @@ export async function createAngularBuildAdapter( if (!bundleContextCache.has(name)) throw new Error(`Could not dispose of non-existing build '${name}'`); - await disposeWhere(entry => entry.name === name); + await disposeWhere((_, entryName) => entryName === name); return; } @@ -92,30 +96,27 @@ export async function createAngularBuildAdapter( await esbuild.stop(); }; - const disposeFederationContexts = () => disposeWhere(entry => entry.isMappingOrExposed); + const disposeFederationContexts = () => disposeWhere(entry => entry.kind !== 'shared'); const setup = async ( name: string, adapterOptions: NFBuildAdapterOptions ): Promise => { - if (bundleContextCache.has(name)) { - return; - } + if (bundleContextCache.has(name)) await dispose(name); const normalizedOptions = normalizeContextOptions(ngBuilderOptions, context, adapterOptions); - const { ctx, pluginDisposed } = normalizedOptions.isMappingOrExposed - ? await createAngularEsbuildContext(normalizedOptions, name) - : await createNodeModulesEsbuildContext(normalizedOptions, sharedBundleSettings); + const { ctx, pluginDisposed } = + adapterOptions.kind === 'shared' + ? await createNodeModulesEsbuildContext(normalizedOptions, sharedBundleSettings) + : await createAngularEsbuildContext(normalizedOptions, name); bundleContextCache.set(name, { ctx, pluginDisposed, + kind: adapterOptions.kind, outdir: normalizedOptions.outdir, cache: normalizedOptions.cache, - isMappingOrExposed: normalizedOptions.isMappingOrExposed, - dev: normalizedOptions.dev, - name, entryPoints: normalizedOptions.entryPoints, }); }; diff --git a/src/utils/normalize-context-options.spec.ts b/src/utils/normalize-context-options.spec.ts index 0a192ba7..43481dad 100644 --- a/src/utils/normalize-context-options.spec.ts +++ b/src/utils/normalize-context-options.spec.ts @@ -11,12 +11,9 @@ describe('normalizeContextOptions', () => { tsConfigPath: 'tsconfig.json', mappedPaths: { foo: 'bar' }, cache: { cachePath: '/cache' }, - dev: true, - isMappingOrExposed: true, hash: true, chunks: true, platform: 'node', - optimizedMappings: true, } as never; it('passes through the provided options unchanged', () => { @@ -31,29 +28,17 @@ describe('normalizeContextOptions', () => { tsConfigPath: 'tsconfig.json', mappedPaths: { foo: 'bar' }, cache: { cachePath: '/cache' }, - dev: true, - isMappingOrExposed: true, hash: true, chunks: true, platform: 'node', - optimizedMappings: true, }); }); - it('coerces truthy/falsy flags to real booleans', () => { - const adapterOptions = { - ...(baseAdapterOptions as object), - dev: undefined, - isMappingOrExposed: undefined, - hash: undefined, - optimizedMappings: undefined, - } as never; + it('coerces a missing hash flag to false', () => { + const adapterOptions = { ...(baseAdapterOptions as object), hash: undefined } as never; const result = normalizeContextOptions(builderOptions, context, adapterOptions); - expect(result.dev).toBe(false); - expect(result.isMappingOrExposed).toBe(false); expect(result.hash).toBe(false); - expect(result.optimizedMappings).toBe(false); }); }); diff --git a/src/utils/normalize-context-options.ts b/src/utils/normalize-context-options.ts index c109009b..f744a27a 100644 --- a/src/utils/normalize-context-options.ts +++ b/src/utils/normalize-context-options.ts @@ -18,12 +18,9 @@ export interface NormalizedContextOptions { tsConfigPath?: string; mappedPaths: PathToImport; cache: FederationCache; - dev: boolean; - isMappingOrExposed: boolean; hash: boolean; chunks?: boolean; platform?: 'browser' | 'node'; - optimizedMappings: boolean; } export function normalizeContextOptions( @@ -40,11 +37,8 @@ export function normalizeContextOptions( tsConfigPath: adapterOptions.tsConfigPath, mappedPaths: adapterOptions.mappedPaths, cache: adapterOptions.cache, - dev: !!adapterOptions.dev, - isMappingOrExposed: !!adapterOptions.isMappingOrExposed, hash: !!adapterOptions.hash, chunks: adapterOptions.chunks, platform: adapterOptions.platform, - optimizedMappings: !!adapterOptions.optimizedMappings, }; }