@unframework.dev/target-angular 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,90 @@
1
+ import { outputBindings, setInputs } from "./client.js";
2
+ import { angularComponent } from "./component.js";
3
+ import { ErrorHandler, createComponent, provideZonelessChangeDetection } from "@angular/core";
4
+ import { createApplication, provideClientHydration, withNoIncrementalHydration } from "@angular/platform-browser";
5
+ /** Angular's hydration errors and warnings: NG0500 to NG0507 (`NG05xx`). */
6
+ const HYDRATION_CODE = /NG050\d/;
7
+ /** Records what Angular reports during and after hydration: a hydration error is a mismatch. */
8
+ var RecordingErrorHandler = class extends ErrorHandler {
9
+ mismatches = [];
10
+ handleError(error) {
11
+ const message = error instanceof Error ? error.message : String(error);
12
+ if (HYDRATION_CODE.test(message)) this.mismatches.push(message);
13
+ else super.handleError(error);
14
+ }
15
+ };
16
+ /**
17
+ * Hydrates `html` (from `renderForHydration`) as a zoneless application with
18
+ * `provideClientHydration()`: the hydration marker (`<!--nghm-->`) and the state script
19
+ * (`ng-state`) go where Angular reads them, as direct children of `<body>`, and the host element
20
+ * into the container, where `createComponent` takes it as its host and hydrates the view the
21
+ * server's `ngh` annotations describe. An NG05xx error, thrown while the component is created
22
+ * or reported through the `ErrorHandler` in a later change detection, and the NG0505 warning
23
+ * that hydration never started, are mismatches. The marker and the script are removed once the
24
+ * component has hydrated, so the next test's hydration never reads them.
25
+ */
26
+ const hydrate = async (component, container, html, options) => {
27
+ const type = angularComponent(component);
28
+ const template = document.createElement("template");
29
+ template.innerHTML = html;
30
+ const moved = [];
31
+ for (const node of Array.from(template.content.childNodes)) {
32
+ const marker = node.nodeType === Node.COMMENT_NODE && node.nodeValue === "nghm";
33
+ const state = node instanceof HTMLScriptElement && node.id === "ng-state";
34
+ if (!marker && !state) continue;
35
+ moved.push(node);
36
+ if (marker) document.body.prepend(node);
37
+ else document.body.append(node);
38
+ }
39
+ const host = template.content.firstElementChild;
40
+ if (!host) throw new Error(`Angular hydrate: the server rendered no host element:\n${html}`);
41
+ container.append(template.content);
42
+ const errors = new RecordingErrorHandler();
43
+ const { warn } = console;
44
+ console.warn = (...args) => {
45
+ const message = args.map(String).join(" ");
46
+ if (/NG0505/.test(message)) errors.mismatches.push(message);
47
+ warn(...args);
48
+ };
49
+ const app = await createApplication({ providers: [
50
+ provideZonelessChangeDetection(),
51
+ provideClientHydration(withNoIncrementalHydration()),
52
+ {
53
+ provide: ErrorHandler,
54
+ useValue: errors
55
+ }
56
+ ] });
57
+ const inputs = /* @__PURE__ */ new Set();
58
+ let ref;
59
+ try {
60
+ ref = createComponent(type, {
61
+ environmentInjector: app.injector,
62
+ hostElement: host,
63
+ bindings: outputBindings(options.on, options.events)
64
+ });
65
+ setInputs(ref, inputs, options.props ?? {});
66
+ app.attachView(ref.hostView);
67
+ await app.whenStable();
68
+ } catch (error) {
69
+ app.destroy();
70
+ host.remove();
71
+ throw error;
72
+ } finally {
73
+ console.warn = warn;
74
+ for (const node of moved) node.remove();
75
+ }
76
+ const settle = () => app.whenStable();
77
+ return {
78
+ settle,
79
+ async rerender(props) {
80
+ setInputs(ref, inputs, props);
81
+ await settle();
82
+ },
83
+ async unmount() {
84
+ app.destroy();
85
+ host.remove();
86
+ },
87
+ takeMismatches: () => errors.mismatches.splice(0)
88
+ };
89
+ };
90
+ export { hydrate };
@@ -7,6 +7,7 @@ const toolchain = {
7
7
  vite: viteConfig,
8
8
  client: "@unframework.dev/target-angular/toolchain/client",
9
9
  server: "@unframework.dev/target-angular/toolchain/server",
10
+ hydrate: "@unframework.dev/target-angular/toolchain/hydrate",
10
11
  frameworkCompile,
11
12
  frameworkEmit,
12
13
  typecheck,
@@ -1,8 +1,14 @@
1
- import { SsrRenderer } from "@unframework.dev/codegen";
1
+ import { HydrationRenderer, SsrRenderer } from "@unframework.dev/codegen";
2
2
  /**
3
3
  * Renders a component on Angular's server platform and returns the content of `<body>`: the
4
4
  * component's host element (`<uf-x style="display: contents;">`) and its content. Inputs are
5
5
  * set before the first change detection; `createComponent` adds neither `ng-version` nor
6
6
  * `ng-server-context`, which `bootstrapApplication` would.
7
7
  */
8
- export declare const renderToString: SsrRenderer;
8
+ export declare const renderToString: SsrRenderer;
9
+ /**
10
+ * Renders the server HTML the hydrate adapter hydrates (L12, ADR-0095): the same render with
11
+ * `provideClientHydration()`, whose `<body>` holds the host with its `ngh` annotation, the
12
+ * hydration marker (`<!--nghm-->`) and the state script (`ng-state`) the client reads.
13
+ */
14
+ export declare const renderForHydration: HydrationRenderer;
@@ -1,7 +1,7 @@
1
1
  import { angularComponent } from "./component.js";
2
2
  import { DOCUMENT, createComponent, provideZonelessChangeDetection } from "@angular/core";
3
- import { createApplication } from "@angular/platform-browser";
4
- import { renderApplication } from "@angular/platform-server";
3
+ import { createApplication, provideClientHydration, withNoIncrementalHydration } from "@angular/platform-browser";
4
+ import { provideServerRendering, renderApplication } from "@angular/platform-server";
5
5
  /** The document the component renders into; only its body is returned. */
6
6
  const DOCUMENT_HTML = "<html><head></head><body></body></html>";
7
7
  /**
@@ -10,10 +10,29 @@ const DOCUMENT_HTML = "<html><head></head><body></body></html>";
10
10
  * set before the first change detection; `createComponent` adds neither `ng-version` nor
11
11
  * `ng-server-context`, which `bootstrapApplication` would.
12
12
  */
13
- const renderToString = async (component, options) => {
13
+ const renderToString = (component, options) => oneAtATime(() => render(component, options, false));
14
+ /**
15
+ * Renders the server HTML the hydrate adapter hydrates (L12, ADR-0095): the same render with
16
+ * `provideClientHydration()`, whose `<body>` holds the host with its `ngh` annotation, the
17
+ * hydration marker (`<!--nghm-->`) and the state script (`ng-state`) the client reads.
18
+ */
19
+ const renderForHydration = (component, options) => oneAtATime(() => render(component, options, true));
20
+ /** The renders queued in this module instance. */
21
+ let queue = Promise.resolve();
22
+ /**
23
+ * Runs renders one at a time. A hydrate project renders for several pages at once (ADR-0095),
24
+ * and two `renderApplication` calls that overlap lose a render's transfer state: its HTML then
25
+ * has no `ng-state` script, and the client does not hydrate (NG0505).
26
+ */
27
+ function oneAtATime(run) {
28
+ const result = queue.then(run, run);
29
+ queue = result.then(() => void 0, () => void 0);
30
+ return result;
31
+ }
32
+ async function render(component, options, hydration) {
14
33
  const type = angularComponent(component);
15
34
  const html = await renderApplication(async (context) => {
16
- const app = await createApplication({ providers: [provideZonelessChangeDetection()] }, context);
35
+ const app = await createApplication({ providers: [provideZonelessChangeDetection(), ...hydration ? [provideClientHydration(withNoIncrementalHydration()), provideServerRendering()] : []] }, context);
17
36
  const ref = createComponent(type, { environmentInjector: app.injector });
18
37
  for (const [name, value] of Object.entries(options.props ?? {})) ref.setInput(name, value);
19
38
  app.attachView(ref.hostView);
@@ -27,5 +46,5 @@ const renderToString = async (component, options) => {
27
46
  const body = /<body[^>]*>([\s\S]*)<\/body>/.exec(html);
28
47
  if (!body) throw new Error(`Angular rendered a document without a <body>: ${html}`);
29
48
  return body[1];
30
- };
31
- export { renderToString };
49
+ }
50
+ export { renderForHydration, renderToString };
@@ -26,6 +26,22 @@ async function viteConfig(mode, context) {
26
26
  tsconfig: analogTsconfig(context.toolchainDir),
27
27
  jit: false
28
28
  }).map(sourcemapPluginOnFileNames)];
29
+ if (mode === "hydrate") return {
30
+ plugins: [...plugins, {
31
+ ...angularSsrLinker(tools),
32
+ applyToEnvironment: isServer
33
+ }],
34
+ resolve: { dedupe: [...RUNTIME, "@angular/platform-server"] },
35
+ environments: { ssr: { resolve: { external: ["rxjs"] } } },
36
+ optimizeDeps: {
37
+ include: [
38
+ "@angular/core",
39
+ "@angular/common",
40
+ "@angular/platform-browser"
41
+ ],
42
+ rolldownOptions: { plugins: [angularLinker(tools)] }
43
+ }
44
+ };
29
45
  if (mode === "browser") return {
30
46
  plugins,
31
47
  resolve: { dedupe: RUNTIME },
@@ -45,6 +61,10 @@ async function viteConfig(mode, context) {
45
61
  test: { pool: "forks" }
46
62
  };
47
63
  }
64
+ /** Whether an environment runs on the server: every environment but the page's. */
65
+ function isServer(environment) {
66
+ return environment.config.consumer === "server";
67
+ }
48
68
  /** Analog's plugin that compiles, under Vitest, the `.ts` modules Angular did not. */
49
69
  const ANALOG_SOURCEMAP_PLUGIN = "@analogjs/vitest-angular-sourcemap-plugin";
50
70
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unframework.dev/target-angular",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "The Angular 22 target of the Unframework compiler: emits idiomatic Angular components from the portable IR, declares their capabilities, and provides the toolchain the tests use.",
5
5
  "keywords": [
6
6
  "angular",
@@ -33,6 +33,10 @@
33
33
  "types": "./dist/toolchain/client.d.ts",
34
34
  "default": "./dist/toolchain/client.js"
35
35
  },
36
+ "./toolchain/hydrate": {
37
+ "types": "./dist/toolchain/hydrate.d.ts",
38
+ "default": "./dist/toolchain/hydrate.js"
39
+ },
36
40
  "./toolchain/server": {
37
41
  "types": "./dist/toolchain/server.d.ts",
38
42
  "default": "./dist/toolchain/server.js"
@@ -43,8 +47,8 @@
43
47
  "access": "public"
44
48
  },
45
49
  "dependencies": {
46
- "@unframework.dev/codegen": "0.1.3",
47
- "@unframework.dev/ir": "0.1.1"
50
+ "@unframework.dev/codegen": "0.2.0",
51
+ "@unframework.dev/ir": "0.2.0"
48
52
  },
49
53
  "devDependencies": {
50
54
  "@angular/common": "22.2.1",