Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 20 additions & 5 deletions crates/oxc_angular_compiler/src/hmr/update_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ pub struct HmrUpdateModuleOptions<'a> {
/// This must be included to ensure the template function's constant references
/// match the component definition's consts array.
pub consts_js: Option<&'a str>,

/// Whether to include full component metadata.
pub include_full_metadata: bool,
}

/// Generate an HMR update module for a component.
Expand Down Expand Up @@ -94,8 +91,9 @@ pub fn generate_hmr_update_module_from_js(
declarations_js: Option<&str>,
consts_js: Option<&str>,
) -> String {
// Extract class name from component_id (format: "path@ClassName")
let class_name = component_id.split('@').nth(1).unwrap_or("Component");
// Extract class name from component_id (format: "path@ClassName"). The path
// can contain `@` (e.g. `node_modules/@scope/...`) but a class name cannot.
let class_name = component_id.rsplit_once('@').map_or("Component", |(_, name)| name);

generate_hmr_update_module_internal(
component_id,
Expand Down Expand Up @@ -270,6 +268,23 @@ mod tests {
assert!(result.contains("function MyComponent_UpdateMetadata(MyComponent"));
}

#[test]
fn test_class_name_extraction_path_with_at() {
for id in
["node_modules/@scope/pkg/src/a.ts@MyComponent", "packages/@a/@b/x.ts@MyComponent"]
{
let result = generate_hmr_update_module_from_js(id, "", None, None, None);
assert!(result.contains("function MyComponent_UpdateMetadata(MyComponent"), "{id}");
assert!(result.contains("MyComponent.ɵcmp ="), "{id}");
}
}

#[test]
fn test_class_name_extraction_no_at_falls_back() {
let result = generate_hmr_update_module_from_js("MyComponent", "", None, None, None);
assert!(result.contains("function Component_UpdateMetadata(Component"));
}

#[test]
fn test_generate_hmr_update_module_with_declarations() {
let declarations = "function App_For_1(rf, ctx) { }\nconst _c0 = [1, 2, 3];";
Expand Down
21 changes: 11 additions & 10 deletions napi/angular-compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ use napi_derive::napi;
use oxc_allocator::Allocator;
use oxc_angular_compiler::{
AngularVersion as RustAngularVersion, ChangeDetectionStrategy as RustChangeDetectionStrategy,
HostMetadataInput as RustHostMetadataInput, TransformOptions as RustTransformOptions,
ViewEncapsulation as RustViewEncapsulation,
HmrUpdateModuleOptions, HostMetadataInput as RustHostMetadataInput,
TransformOptions as RustTransformOptions, ViewEncapsulation as RustViewEncapsulation,
build_ctor_params_metadata_in as core_build_ctor_params_metadata,
build_decorator_metadata_array as core_build_decorator_metadata_array,
build_prop_decorators_metadata_in as core_build_prop_decorators_metadata,
compile_template_for_hmr, compile_template_to_js_with_options,
encapsulate_style as rust_encapsulate_style, generate_hmr_update_module_from_js,
generate_style_update_module,
encapsulate_style as rust_encapsulate_style, generate_hmr_update_module,
generate_hmr_update_module_from_js, generate_style_update_module,
};
use oxc_napi::OxcError;

Expand Down Expand Up @@ -600,13 +600,14 @@ pub fn compile_for_hmr_sync(
};

// Generate HMR module with declarations, encapsulated styles, and consts
let hmr_module = generate_hmr_update_module_from_js(
&component_id,
&template_js,
encapsulated_styles.as_deref(),
let hmr_module = generate_hmr_update_module(&HmrUpdateModuleOptions {
component_id: &component_id,
class_name: &component_name,
template_js: Some(&template_js),
styles: encapsulated_styles.as_deref(),
declarations_js,
output.consts_js.as_deref(),
);
consts_js: output.consts_js.as_deref(),
});

HmrCompileResult { hmr_module, component_id, template_js, errors: vec![] }
}
Expand Down
159 changes: 158 additions & 1 deletion napi/angular-compiler/test/hmr-hot-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'

import type { Plugin, ModuleNode, HmrContext } from 'vite'
import { normalizePath, resolveConfig } from 'vite'
import { normalizePath, parseSync, resolveConfig } from 'vite'
import { afterAll, beforeAll, describe, it, expect, vi } from 'vitest'

import { angular } from '../vite-plugin/index.js'
Expand Down Expand Up @@ -383,6 +383,76 @@ describe('pendingHmrUpdates race condition', () => {
expect(bBody).toContain('BComponent')
})

it('serves the HMR module for a component whose path contains @', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)

const scopedDir = join(tempDir, 'packages', '@company', 'app')
mkdirSync(scopedDir, { recursive: true })
const scopedPath = join(scopedDir, 'scoped.component.ts')
const source = `
import { Component } from '@angular/core';
@Component({ selector: 'app-scoped', template: '<p>S</p>' })
export class ScopedComponent {}
`
writeFileSync(scopedPath, source)

if (!plugin.transform || typeof plugin.transform === 'function') {
throw new Error('Expected plugin transform handler')
}
await plugin.transform.handler.call(
{ error() {}, warn() {}, addWatchFile() {} } as any,
source,
scopedPath,
)

writeFileSync(scopedPath, source.replace('<p>S</p>', '<p>S!</p>'))
const ctx = createMockHmrContext(scopedPath, [{ id: scopedPath }], mockServer)
await callHandleHotUpdate(plugin, ctx)

const middleware = (mockServer.middlewares.use as ReturnType<typeof vi.fn>).mock.calls[0]?.[0]
const body = await invokeAngularMiddleware(middleware, `${scopedPath}@ScopedComponent`)

expect(body).toContain('function ScopedComponent_UpdateMetadata(ScopedComponent')
expect(parseSync('hmr.js', body).errors).toEqual([])
})

it('serves the HMR module for a component whose path contains %', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)

const percentDir = join(tempDir, 'packages', '100%', 'app')
mkdirSync(percentDir, { recursive: true })
const percentPath = join(percentDir, 'percent.component.ts')
const source = `
import { Component } from '@angular/core';
@Component({ selector: 'app-pct', template: '<p>P</p>' })
export class PercentComponent {}
`
writeFileSync(percentPath, source)

if (!plugin.transform || typeof plugin.transform === 'function') {
throw new Error('Expected plugin transform handler')
}
await plugin.transform.handler.call(
{ error() {}, warn() {}, addWatchFile() {} } as any,
source,
percentPath,
)

writeFileSync(percentPath, source.replace('<p>P</p>', '<p>P!</p>'))
const ctx = createMockHmrContext(percentPath, [{ id: percentPath }], mockServer)
await callHandleHotUpdate(plugin, ctx)

// The middleware must decode the `c` param exactly once: a literal `%` in
// the path survives one decode but turns into an escape sequence under two.
const middleware = (mockServer.middlewares.use as ReturnType<typeof vi.fn>).mock.calls[0]?.[0]
const body = await invokeAngularMiddleware(middleware, `${percentPath}@PercentComponent`)

expect(body).toContain('function PercentComponent_UpdateMetadata(PercentComponent')
expect(parseSync('hmr.js', body).errors).toEqual([])
})

it("dispatches HMR for both components when only one component's inline styles change", async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)
Expand Down Expand Up @@ -527,6 +597,55 @@ describe('pendingHmrUpdates race condition', () => {
expect(dropBody2).toBe('')
})

it('prunes only the removed class when the file path contains @', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)

const scopedDir = join(tempDir, 'packages', '@company', 'prune')
mkdirSync(scopedDir, { recursive: true })
const stalePath = join(scopedDir, 'stale.component.ts')
const originalSource = `
import { Component } from '@angular/core';
@Component({ selector: 'app-keep', template: '<keep/>' })
export class KeepComponent {}
@Component({ selector: 'app-drop', template: '<drop/>' })
export class DropComponent {}
`
writeFileSync(stalePath, originalSource)

if (!plugin.transform || typeof plugin.transform === 'function') {
throw new Error('Expected plugin transform handler')
}
await plugin.transform.handler.call(
{ error() {}, warn() {}, addWatchFile() {} } as any,
originalSource,
stalePath,
)

writeFileSync(stalePath, originalSource.replace('<keep/>', '<keep-edited/>'))
const ctx = createMockHmrContext(stalePath, [{ id: stalePath }], mockServer)
await callHandleHotUpdate(plugin, ctx)

const reducedSource = `
import { Component } from '@angular/core';
@Component({ selector: 'app-keep', template: '<keep-edited/>' })
export class KeepComponent {}
`
writeFileSync(stalePath, reducedSource)
await plugin.transform.handler.call(
{ error() {}, warn() {}, addWatchFile() {} } as any,
reducedSource,
stalePath,
)

const middleware = (mockServer.middlewares.use as ReturnType<typeof vi.fn>).mock.calls[0]?.[0]

expect(await invokeAngularMiddleware(middleware, `${stalePath}@DropComponent`)).toBe('')
const keepBody = await invokeAngularMiddleware(middleware, `${stalePath}@KeepComponent`)
expect(keepBody).toContain('function KeepComponent_UpdateMetadata(KeepComponent')
expect(keepBody).toContain('keep-edited')
})

it('triggers full reload when a multi-component .ts changes outside template/styles', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)
Expand Down Expand Up @@ -2174,6 +2293,44 @@ describe('@ng/component endpoint resolves the styles per class', () => {
expect(body).toContain('styles: []')
})

// Vite hands `transform` forward-slash ids on every platform. The endpoint
// must look the file up by that same spelling, not a re-resolved one, or on
// Windows it serves nothing and never treats an empty style list as final.
it('serves the module for a forward-slash (Vite-normalized) component id', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithRealConfig(plugin)

const sibCssPath = normalizePath(join(appDir, 'ps-posix-sib.component.css'))
const posixPath = normalizePath(join(appDir, 'ps-posix.component.ts'))
writeFileSync(sibCssPath, '.PS_POSIX_SIB_MARKER { color: red; }')

const source = `
import { Component } from '@angular/core';
@Component({ selector: 'app-ps-posix', template: '<p>posix</p>', styles: [] })
export class PosixComponent {}
@Component({
selector: 'app-ps-posix-sib',
template: '<p>sib</p>',
styleUrls: ['./ps-posix-sib.component.css'],
})
export class PosixSiblingComponent {}
`
writeFileSync(posixPath, source)
await transformSource(plugin, source, posixPath)

writeFileSync(sibCssPath, '.PS_POSIX_SIB_MARKER { color: green; }')
const ctx = createMockHmrContext(sibCssPath, [{ id: sibCssPath }], mockServer)
await callHandleHotUpdate(plugin, ctx)
expectDispatched(mockServer, `${posixPath}@PosixComponent`)

const body = await invokeAngularMiddleware(
getMiddleware(mockServer),
`${posixPath}@PosixComponent`,
)
expect(body).toContain('function PosixComponent_UpdateMetadata(PosixComponent')
expect(body).toContain('styles: []')
})

it('serves both entries of a `styleUrls` array mixing a constant with a literal', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithRealConfig(plugin)
Expand Down
47 changes: 46 additions & 1 deletion napi/angular-compiler/test/ssr-hmr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@
* 2. `resolveId`/`load` hooks handle `@ng/component` as a safety net, returning
* an empty module so the module runner never crashes.
*/
import { parseSync } from 'vite'
import { describe, it, expect } from 'vitest'

import { compileForHmrSync, transformAngularFile } from '../index.js'
import {
compileForHmrSync,
generateHmrModule,
parseComponentId,
transformAngularFile,
} from '../index.js'

const COMPONENT_SOURCE = `
import { Component } from '@angular/core';
Expand Down Expand Up @@ -105,3 +111,42 @@ describe('Component style minification', () => {
expect(result.hmrModule).toContain('.container[_ngcontent-%COMP%]{color:red;background:0 0}')
})
})

describe('compileForHmrSync with @ in the file path', () => {
it.each(['node_modules/@scope/pkg/src/a.ts', 'packages/@a/@b/x.ts'])(
'names the update function after the class for %s',
(filePath) => {
const result = compileForHmrSync('<div></div>', 'Foo', filePath, null, {})

expect(result.componentId).toBe(`${filePath}@Foo`)
expect(result.hmrModule).toContain(
'export default function Foo_UpdateMetadata(Foo, ɵɵnamespaces) {',
)
expect(parseSync('hmr.js', result.hmrModule).errors).toEqual([])
},
)

it.each([
['node_modules/@scope/pkg/src/a.ts@Foo', 'node_modules/@scope/pkg/src/a.ts', 'Foo'],
['packages/@a/@b/x.ts@Foo', 'packages/@a/@b/x.ts', 'Foo'],
['Foo', 'Foo', ''],
])('parseComponentId splits %s on the last @', (id, filePath, className) => {
expect(parseComponentId(id)).toEqual({ filePath, className })
})

it('generateHmrModule names the update function after the class', () => {
const hmrModule = generateHmrModule('node_modules/@scope/pkg/src/a.ts@Foo', 'null')

expect(hmrModule).toContain('export default function Foo_UpdateMetadata(Foo, ɵɵnamespaces) {')
expect(parseSync('hmr.js', hmrModule).errors).toEqual([])
})

it('transformAngularFile emits a parseable HMR initializer with the full id', async () => {
const filePath = 'node_modules/@scope/pkg/src/app.component.ts'
const result = await transformAngularFile(COMPONENT_SOURCE, filePath, { hmr: true })

expect(result.errors).toHaveLength(0)
expect(result.code).toContain(encodeURIComponent(`${filePath}@AppComponent`))
expect(parseSync('app.component.js', result.code).errors).toEqual([])
})
})
Loading
Loading