@hamur/adapter-angular 0.0.0-stage → 0.0.1

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.
Files changed (88) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +42 -2
  3. package/dist/chunks/browser-index-7h7x2xz2.js +131 -0
  4. package/dist/chunks/browser-index-nann848q.js +205 -0
  5. package/dist/chunks/browser-index-qn8q5fa2.js +580 -0
  6. package/dist/src/adapter.js +1073 -0
  7. package/dist/src/error-page.js +34 -0
  8. package/dist/src/index.js +1729 -0
  9. package/dist/src/keepalive.js +0 -0
  10. package/dist/src/runtime/client.js +21 -0
  11. package/dist/src/runtime/island.js +92 -0
  12. package/dist/src/runtime/server.js +175 -0
  13. package/dist/types/src/activation.d.ts +20 -0
  14. package/dist/types/src/adapter.d.ts +7 -0
  15. package/dist/types/src/app.d.ts +3 -0
  16. package/dist/types/src/async-data.d.ts +21 -0
  17. package/dist/types/src/client-parts.d.ts +32 -0
  18. package/dist/types/src/compile.d.ts +97 -0
  19. package/dist/types/src/context.d.ts +74 -0
  20. package/dist/types/src/data.d.ts +65 -0
  21. package/dist/types/src/definition.d.ts +13 -0
  22. package/dist/types/src/error-page.d.ts +5 -0
  23. package/dist/types/src/error.d.ts +4 -0
  24. package/dist/types/src/form.d.ts +65 -0
  25. package/dist/types/src/head.d.ts +12 -0
  26. package/dist/types/src/hmr.d.ts +14 -0
  27. package/dist/types/src/hydration.d.ts +16 -0
  28. package/dist/types/src/index.d.ts +24 -0
  29. package/dist/types/src/indicators.d.ts +69 -0
  30. package/dist/types/src/island.d.ts +39 -0
  31. package/dist/types/src/keepalive.d.ts +1 -0
  32. package/dist/types/src/link.d.ts +65 -0
  33. package/dist/types/src/markdown-page.d.ts +10 -0
  34. package/dist/types/src/markdown.d.ts +37 -0
  35. package/dist/types/src/mask.d.ts +12 -0
  36. package/dist/types/src/navigate.d.ts +14 -0
  37. package/dist/types/src/outlet.d.ts +71 -0
  38. package/dist/types/src/request.d.ts +31 -0
  39. package/dist/types/src/routing.d.ts +47 -0
  40. package/dist/types/src/runtime/client.d.ts +29 -0
  41. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  42. package/dist/types/src/runtime/hydration.d.ts +8 -0
  43. package/dist/types/src/runtime/island.d.ts +8 -0
  44. package/dist/types/src/runtime/server.d.ts +15 -0
  45. package/dist/types/src/server-island.d.ts +21 -0
  46. package/dist/types/src/state.d.ts +14 -0
  47. package/dist/types/src/svg.d.ts +15 -0
  48. package/dist/types/src/time.d.ts +37 -0
  49. package/dist/types/src/wrapper.d.ts +21 -0
  50. package/package.json +56 -4
  51. package/src/activation.ts +83 -0
  52. package/src/adapter.ts +107 -0
  53. package/src/app.ts +6 -0
  54. package/src/async-data.ts +105 -0
  55. package/src/client-parts.ts +127 -0
  56. package/src/compile.ts +959 -0
  57. package/src/context.ts +189 -0
  58. package/src/data.ts +389 -0
  59. package/src/definition.ts +144 -0
  60. package/src/error-page.ts +17 -0
  61. package/src/error.ts +15 -0
  62. package/src/form.ts +253 -0
  63. package/src/head.ts +63 -0
  64. package/src/hmr.ts +61 -0
  65. package/src/hydration.ts +120 -0
  66. package/src/index.ts +98 -0
  67. package/src/indicators.ts +251 -0
  68. package/src/island.ts +95 -0
  69. package/src/keepalive.ts +1 -0
  70. package/src/link.ts +251 -0
  71. package/src/markdown-page.ts +31 -0
  72. package/src/markdown.ts +170 -0
  73. package/src/mask.ts +36 -0
  74. package/src/navigate.ts +19 -0
  75. package/src/outlet.ts +344 -0
  76. package/src/request.ts +170 -0
  77. package/src/routing.ts +218 -0
  78. package/src/runtime/client.ts +140 -0
  79. package/src/runtime/contract.d.ts +4 -0
  80. package/src/runtime/hydration-dev.ts +18 -0
  81. package/src/runtime/hydration.ts +7 -0
  82. package/src/runtime/island.ts +109 -0
  83. package/src/runtime/server.ts +228 -0
  84. package/src/server-island.ts +54 -0
  85. package/src/state.ts +70 -0
  86. package/src/svg.ts +65 -0
  87. package/src/time.ts +108 -0
  88. package/src/wrapper.ts +187 -0
@@ -0,0 +1,21 @@
1
+ import { type OnInit, type TemplateRef } from "@angular/core";
2
+ import { HostWriter } from "./island.ts";
3
+ /**
4
+ * A component rendered on the server in its own request; the page holds `fallback`, the core swaps the answer in, and Angular
5
+ * never renders or hydrates it. While hydrating, the server's element keeps its attributes and nodes.
6
+ */
7
+ export declare class ServerIsland extends HostWriter implements OnInit {
8
+ /** The name of a component under `app/server-islands/`. */
9
+ readonly name: import("@angular/core/types/core.js").InputSignal<string>;
10
+ readonly props: import("@angular/core/types/core.js").InputSignal<Record<string, unknown> | undefined>;
11
+ /** Rendered with the page; replaced by the island's HTML once the browser has it. */
12
+ readonly fallback: import("@angular/core/types/core.js").InputSignal<TemplateRef<unknown> | undefined>;
13
+ private readonly app;
14
+ private readonly id;
15
+ private readonly tasks;
16
+ private readonly fail;
17
+ private readonly server;
18
+ private readonly kept;
19
+ constructor();
20
+ ngOnInit(): void;
21
+ }
@@ -0,0 +1,14 @@
1
+ import { type Signal, type WritableSignal } from "@angular/core";
2
+ import type { StateKey, SyncedStateOptions, UseCookieOptions } from "hamur/app";
3
+ /** A signal that reads `source` and writes through `write`: the store is the one value, the signal only follows it. */
4
+ export declare function writableOf<T>(source: Signal<T>, write: (value: T) => void): WritableSignal<T>;
5
+ /** The app's state under `key`, in the payload; `init` runs once per key. */
6
+ export declare function injectState<T>(key: StateKey<T>): WritableSignal<T>;
7
+ export declare function injectState<T>(key: string, init?: T | (() => T)): WritableSignal<T>;
8
+ /** A cookie of the request on the server and of `document.cookie` in the browser; a write sets it, `undefined` deletes it. */
9
+ export declare function injectCookie<T = string>(name: string, options: Omit<UseCookieOptions<T>, "app"> & {
10
+ default: () => T;
11
+ }): WritableSignal<T>;
12
+ export declare function injectCookie<T = string>(name: string, options?: Omit<UseCookieOptions<T>, "app">): WritableSignal<T | undefined>;
13
+ /** The value of `key` in the room, shared through the page's socket; `initial` until the first render is done. */
14
+ export declare function injectSyncedState<T>(key: string, initial: T, options?: SyncedStateOptions): WritableSignal<T>;
@@ -0,0 +1,15 @@
1
+ import type { SvgSource } from "hamur/adapter";
2
+ /**
3
+ * A standalone component with no selector, rendered with `NgComponentOutlet`; its only input is `title`. Each
4
+ * `{ id }` part is `uid + "-<id>"`, `uid` being `injectId()` of the instance, the same on the server and in hydration. Angular
5
+ * compiles the module with the app: the core writes it under `<buildDir>/svg` and the compile step finds it there.
6
+ */
7
+ declare function module(svg: SvgSource): {
8
+ contents: string;
9
+ extension: string;
10
+ };
11
+ export declare const svgComponent: {
12
+ types: string;
13
+ module: typeof module;
14
+ };
15
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `<time [hamurTime]="date">` writes the `datetime`, `data-locale` and `data-time-zone` attributes and the formatted text;
3
+ * `relative` refreshes the text every `relativeInterval` ms in the browser. The other inputs are the `Intl.DateTimeFormat` options.
4
+ */
5
+ export declare class Time {
6
+ readonly datetime: import("@angular/core/types/core.js").InputSignal<string | number | Date>;
7
+ readonly locale: import("@angular/core/types/core.js").InputSignal<string | undefined>;
8
+ readonly timeZone: import("@angular/core/types/core.js").InputSignal<string | undefined>;
9
+ readonly relative: import("@angular/core/types/core.js").InputSignalWithTransform<boolean, unknown>;
10
+ readonly relativeInterval: import("@angular/core/types/core.js").InputSignalWithTransform<number | undefined, unknown>;
11
+ readonly calendar: import("@angular/core/types/core.js").InputSignal<string | undefined>;
12
+ readonly dayPeriod: import("@angular/core/types/core.js").InputSignal<"long" | "narrow" | "short" | undefined>;
13
+ readonly numberingSystem: import("@angular/core/types/core.js").InputSignal<string | undefined>;
14
+ readonly dateStyle: import("@angular/core/types/core.js").InputSignal<"full" | "long" | "medium" | "short" | undefined>;
15
+ readonly timeStyle: import("@angular/core/types/core.js").InputSignal<"full" | "long" | "medium" | "short" | undefined>;
16
+ readonly hourCycle: import("@angular/core/types/core.js").InputSignal<"h11" | "h12" | "h23" | "h24" | undefined>;
17
+ readonly hour12: import("@angular/core/types/core.js").InputSignalWithTransform<boolean | undefined, unknown>;
18
+ readonly localeMatcher: import("@angular/core/types/core.js").InputSignal<"best fit" | "lookup" | undefined>;
19
+ readonly formatMatcher: import("@angular/core/types/core.js").InputSignal<"basic" | "best fit" | undefined>;
20
+ readonly weekday: import("@angular/core/types/core.js").InputSignal<"long" | "narrow" | "short" | undefined>;
21
+ readonly era: import("@angular/core/types/core.js").InputSignal<"long" | "narrow" | "short" | undefined>;
22
+ readonly year: import("@angular/core/types/core.js").InputSignal<"2-digit" | "numeric" | undefined>;
23
+ readonly month: import("@angular/core/types/core.js").InputSignal<"2-digit" | "long" | "narrow" | "numeric" | "short" | undefined>;
24
+ readonly day: import("@angular/core/types/core.js").InputSignal<"2-digit" | "numeric" | undefined>;
25
+ readonly hour: import("@angular/core/types/core.js").InputSignal<"2-digit" | "numeric" | undefined>;
26
+ readonly minute: import("@angular/core/types/core.js").InputSignal<"2-digit" | "numeric" | undefined>;
27
+ readonly second: import("@angular/core/types/core.js").InputSignal<"2-digit" | "numeric" | undefined>;
28
+ readonly fractionalSecondDigits: import("@angular/core/types/core.js").InputSignalWithTransform<1 | 2 | 3 | undefined, unknown>;
29
+ readonly timeZoneName: import("@angular/core/types/core.js").InputSignal<"long" | "longGeneric" | "longOffset" | "short" | "shortGeneric" | "shortOffset" | undefined>;
30
+ private readonly app;
31
+ private readonly route;
32
+ private readonly now;
33
+ private readonly props;
34
+ protected readonly view: import("@angular/core/types/_chrome_dev_tools_performance-chunk.js").Signal<import("hamur/adapter").TimeView>;
35
+ private readonly interval;
36
+ constructor();
37
+ }
@@ -0,0 +1,21 @@
1
+ import { type Type } from "@angular/core";
2
+ /** What a generated wrapper component calls: its inputs as they change, and once the first ones are set. */
3
+ export interface Controller {
4
+ set(name: string, value: unknown): void;
5
+ init(): void;
6
+ }
7
+ type Loaded = Type<unknown> | {
8
+ default: Type<unknown>;
9
+ };
10
+ /** The server side of a client-only component renders nothing. */
11
+ export declare function clientComponentOnServer(): Controller;
12
+ /**
13
+ * The client side of a client-only component: nothing in the hydration render, the file's chunk created inside the host once
14
+ * the first render is done, and at once after a client navigation. Its inputs are the real component's, set as they change.
15
+ */
16
+ export declare function clientComponentOnClient(load: () => Promise<Loaded>): Controller;
17
+ /** The server side of a server-only component: the component itself inside `hamur-component`, its props checked as the client sends them. */
18
+ export declare function serverComponentOnServer(name: string, component: Type<unknown>): Controller;
19
+ /** The client side of a server-only component: the server HTML, never hydrated; a new props text fetches it anew. */
20
+ export declare function serverComponentOnClient(name: string): Controller;
21
+ export {};
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@hamur/adapter-angular",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/productdevbook/hamur.git",
9
+ "directory": "packages/adapter-angular"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/types/src/index.d.ts",
14
+ "default": "./dist/src/index.js"
15
+ },
16
+ "./adapter": {
17
+ "types": "./dist/types/src/adapter.d.ts",
18
+ "default": "./dist/src/adapter.js"
19
+ },
20
+ "./error-page": {
21
+ "types": "./dist/types/src/error-page.d.ts",
22
+ "default": "./dist/src/error-page.js"
23
+ },
24
+ "./runtime/server": {
25
+ "types": "./dist/types/src/runtime/server.d.ts",
26
+ "default": "./dist/src/runtime/server.js"
27
+ },
28
+ "./runtime/client": {
29
+ "types": "./dist/types/src/runtime/client.d.ts",
30
+ "default": "./dist/src/runtime/client.js"
31
+ },
32
+ "./runtime/island": {
33
+ "types": "./dist/types/src/runtime/island.d.ts",
34
+ "default": "./dist/src/runtime/island.js"
35
+ },
36
+ "./runtime/keepalive": {
37
+ "types": "./dist/types/src/keepalive.d.ts",
38
+ "default": "./dist/src/keepalive.js"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "src"
45
+ ],
46
+ "dependencies": {},
47
+ "peerDependencies": {
48
+ "@angular/core": "^22.3.0",
49
+ "@angular/common": "^22.3.0",
50
+ "@angular/compiler": "^22.3.0",
51
+ "@angular/platform-browser": "^22.3.0",
52
+ "@angular/platform-server": "^22.3.0",
53
+ "@angular/compiler-cli": "^22.3.0",
54
+ "rxjs": "^7.8.2",
55
+ "typescript": "~6.0.3",
56
+ "hamur": "^0.0.1"
57
+ }
58
+ }
@@ -0,0 +1,83 @@
1
+ import { DestroyRef, InjectionToken, afterNextRender, assertInInjectionContext, inject } from "@angular/core"
2
+ import { onServer } from "./context.ts"
3
+
4
+ /** The shown state of one keep-alive wrapper and the `onPageActivated`/`onPageDeactivated` functions under it. */
5
+ export interface Activation {
6
+ hidden: boolean
7
+ readonly parent: Activation | undefined
8
+ readonly children: Set<Activation>
9
+ readonly on: Set<() => void>
10
+ readonly off: Set<() => void>
11
+ }
12
+
13
+ /** The nearest keep-alive wrapper above a component; absent when its page is not kept. */
14
+ export const HAMUR_ACTIVATION = new InjectionToken<Activation>("hamur activation")
15
+
16
+ export function activation(parent: Activation | undefined, hidden: boolean): Activation {
17
+ const own: Activation = { hidden, parent, children: new Set(), on: new Set(), off: new Set() }
18
+ parent?.children.add(own)
19
+ return own
20
+ }
21
+
22
+ export function detach(own: Activation): void {
23
+ own.parent?.children.delete(own)
24
+ }
25
+
26
+ /** Whether a page under `own` is on screen: no wrapper above it is hidden. */
27
+ export function shown(own: Activation | undefined): boolean {
28
+ return !own || (!own.hidden && shown(own.parent))
29
+ }
30
+
31
+ let queue: Array<{ shown: boolean; fn: () => void }> | undefined
32
+
33
+ /** Runs `fn` once the commit is done; within one commit every deactivation runs before any activation, so a hide comes before the show it makes room for. */
34
+ function later(isShown: boolean, fn: () => void): void {
35
+ if (!queue) {
36
+ queue = []
37
+ queueMicrotask(() => {
38
+ const run = queue!
39
+ queue = undefined
40
+ for (const item of run) if (!item.shown) item.fn()
41
+ for (const item of run) if (item.shown) item.fn()
42
+ })
43
+ }
44
+ queue.push({ shown: isShown, fn })
45
+ }
46
+
47
+ function fire(own: Activation, isShown: boolean): void {
48
+ for (const fn of isShown ? own.on : own.off) later(isShown, fn)
49
+ for (const child of own.children) if (!child.hidden) fire(child, isShown)
50
+ }
51
+
52
+ export function setHidden(own: Activation, hidden: boolean): void {
53
+ if (own.hidden === hidden) return
54
+ const before = shown(own)
55
+ own.hidden = hidden
56
+ if (shown(own) !== before) fire(own, !before)
57
+ }
58
+
59
+ /** Runs `fn` after the component's first render and each time its kept page is shown again. */
60
+ export function onPageActivated(fn: () => void): void {
61
+ assertInInjectionContext(onPageActivated)
62
+ const own = inject(HAMUR_ACTIVATION, { optional: true }) ?? undefined
63
+ const destroy = inject(DestroyRef)
64
+ const run = () => fn()
65
+ own?.on.add(run)
66
+ afterNextRender(() => {
67
+ if (shown(own)) later(true, run)
68
+ })
69
+ destroy.onDestroy(() => void own?.on.delete(run))
70
+ }
71
+
72
+ /** Runs `fn` each time its kept page is hidden and when the component is destroyed on screen. */
73
+ export function onPageDeactivated(fn: () => void): void {
74
+ assertInInjectionContext(onPageDeactivated)
75
+ if (onServer()) return
76
+ const own = inject(HAMUR_ACTIVATION, { optional: true }) ?? undefined
77
+ const run = () => fn()
78
+ own?.off.add(run)
79
+ inject(DestroyRef).onDestroy(() => {
80
+ own?.off.delete(run)
81
+ if (shown(own)) later(false, run)
82
+ })
83
+ }
package/src/adapter.ts ADDED
@@ -0,0 +1,107 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { dirname } from "node:path"
3
+ import type { BunPlugin } from "bun"
4
+ import { ADAPTER_CONTRACT, defineAdapter } from "hamur/adapter"
5
+ import type { ClientComponentSource, ServerComponentSource } from "hamur/adapter"
6
+ import { compileStep, hydrationStep, linkStep } from "./compile.ts"
7
+ import { angularHooks } from "./hmr.ts"
8
+ import { markdownComponent } from "./markdown-page.ts"
9
+ import { svgComponent } from "./svg.ts"
10
+
11
+ const ANGULAR = [
12
+ "@angular/core",
13
+ "@angular/common",
14
+ "@angular/compiler",
15
+ "@angular/platform-browser",
16
+ "@angular/platform-server",
17
+ "@angular/compiler-cli",
18
+ ] as const
19
+
20
+ interface Manifest {
21
+ version: string
22
+ peerDependencies?: Record<string, string>
23
+ }
24
+
25
+ const manifestOf = (name: string, from: string): { file: string; manifest: Manifest } => {
26
+ const file = Bun.resolveSync(`${name}/package.json`, from)
27
+ return { file, manifest: JSON.parse(readFileSync(file, "utf8")) as Manifest }
28
+ }
29
+
30
+ /** The core's peer check only asks that each peer resolves, so a wrong install would fail late inside the compiler. */
31
+ export function assertAngular(rootDir: string): void {
32
+ const core = manifestOf("@angular/core", rootDir).manifest.version
33
+ if (core.split(".")[0] !== "22")
34
+ throw new Error(
35
+ `@hamur/adapter-angular supports Angular 22: @angular/core ${core} is installed in ${rootDir}. Install it with: bun add ${ANGULAR.map((name) => `${name}@^22.3.0`).join(" ")}`,
36
+ )
37
+ for (const name of ANGULAR.slice(1)) {
38
+ const { version } = manifestOf(name, rootDir).manifest
39
+ if (version !== core)
40
+ throw new Error(
41
+ `@hamur/adapter-angular needs every @angular package at one version; found @angular/core ${core} and ${name} ${version} in ${rootDir}`,
42
+ )
43
+ }
44
+ const cli = manifestOf("@angular/compiler-cli", rootDir)
45
+ const range = cli.manifest.peerDependencies?.typescript ?? ">=6.0 <6.1"
46
+ let typescript: string
47
+ try {
48
+ typescript = manifestOf("typescript", dirname(cli.file)).manifest.version
49
+ } catch {
50
+ typescript = manifestOf("typescript", rootDir).manifest.version
51
+ }
52
+ if (!Bun.semver.satisfies(typescript, range))
53
+ throw new Error(
54
+ `@hamur/adapter-angular needs typescript 6.0 for the Angular compiler (its range is "${range}"); typescript ${typescript} is installed in ${rootDir}. Install it with: bun add -d typescript@~6.0.3`,
55
+ )
56
+ }
57
+
58
+ /** A build drops Angular's dev-mode and JIT branches; `hamur dev` sets none, Bun.serve's dev bundler ignores them. */
59
+ export function angularDefines(target: "client" | "server"): BunPlugin {
60
+ return {
61
+ name: "hamur-angular-define",
62
+ setup(build) {
63
+ build.config.define = {
64
+ ngDevMode: "false",
65
+ ngJitMode: "false",
66
+ ngI18nClosureMode: "false",
67
+ ngServerMode: target === "server" ? "true" : "false",
68
+ ...build.config.define,
69
+ }
70
+ },
71
+ }
72
+ }
73
+
74
+ /** The module of a client-only or server-only component is a marker; the compile step writes the wrapper once the program knows the real component. */
75
+ const wrapper =
76
+ (kind: "client" | "server") =>
77
+ (component: ClientComponentSource | ServerComponentSource): { contents: string; extension: string } => ({
78
+ contents: `/* hamur-angular-component ${JSON.stringify({ kind, name: component.name, target: component.target, ...(component.file === undefined ? {} : { file: component.file }) })} */\nexport default undefined;\n`,
79
+ extension: ".ts",
80
+ })
81
+
82
+ export default defineAdapter({
83
+ name: "angular",
84
+ contract: ADAPTER_CONTRACT,
85
+ extensions: [".ts"],
86
+ clientEntry: "@hamur/adapter-angular/runtime/client",
87
+ serverEntry: "@hamur/adapter-angular/runtime/server",
88
+ errorPage: "@hamur/adapter-angular/error-page",
89
+ islandEntry: "@hamur/adapter-angular/runtime/island",
90
+ plugins: (ctx) => {
91
+ assertAngular(ctx.rootDir)
92
+ return ctx.dev ? [] : [angularDefines(ctx.target)]
93
+ },
94
+ transforms: (ctx) => [
95
+ compileStep(ctx),
96
+ linkStep(ctx),
97
+ ...(ctx.dev && ctx.target === "client" ? [hydrationStep()] : []),
98
+ ],
99
+ hooks: angularHooks,
100
+ peers: [...ANGULAR, "rxjs", "typescript"],
101
+ stream: false,
102
+ trustedTypesPolicies: ["angular", "angular#unsafe-bypass"],
103
+ svgComponent,
104
+ markdownComponent,
105
+ clientComponent: { module: wrapper("client") },
106
+ serverComponent: { module: wrapper("server") },
107
+ })
package/src/app.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { Component } from "@angular/core"
2
+ import { Outlet } from "./outlet.ts"
3
+
4
+ /** The one Angular root, inside the core's root element; it renders the tree's first entry. */
5
+ @Component({ selector: "hamur-app", imports: [Outlet], template: "<hamur-outlet />" })
6
+ export class HamurApp {}
@@ -0,0 +1,105 @@
1
+ import { asyncDataKey, fetchKey, isPreviewMode } from "hamur/adapter"
2
+ import { $fetch } from "hamur/app"
3
+ import type { $Fetch, AppContext, AsyncDataOptions, FetchOptions } from "hamur/app"
4
+ import type { AsyncDataHandler, FetchRequest, GetCachedData, GetCachedDataCause, HandlerReference } from "hamur/adapter"
5
+
6
+ export const valueOf = <T>(value: T | (() => T)): T => (typeof value === "function" ? (value as () => T)() : value)
7
+
8
+ // A function is never a body to send, so a function `query` or `body` is a getter.
9
+ export function requestOf({ query, body, ...rest }: FetchRequest): FetchOptions {
10
+ const request: FetchOptions = rest
11
+ const resolvedQuery = valueOf(query)
12
+ const resolvedBody = valueOf(body)
13
+ if (resolvedQuery !== undefined) request.query = resolvedQuery
14
+ if (resolvedBody !== undefined) request.body = resolvedBody
15
+ return request
16
+ }
17
+
18
+ /** A getter `injectFetch` key; each key's handler fetches the url and request that key was made from. */
19
+ export function fetchSlots<R>(
20
+ url: string | (() => string),
21
+ options: FetchRequest,
22
+ fetcher: $Fetch = $fetch,
23
+ fixedKey?: string,
24
+ ): { keyOf: () => string; handlerFor: (key: string) => AsyncDataHandler<R> } {
25
+ const requests = new Map<string, { url: string; request: FetchOptions }>()
26
+ return {
27
+ keyOf() {
28
+ const target = valueOf(url)
29
+ const request = requestOf(options)
30
+ const key = fixedKey ?? fetchKey(target, request)
31
+ requests.set(key, { url: target, request })
32
+ return key
33
+ },
34
+ handlerFor(key) {
35
+ const { url: target, request } = requests.get(key)!
36
+ return ({ signal }) => fetcher<R>(target, { ...request, signal: signalOf(request.signal, signal) })
37
+ },
38
+ }
39
+ }
40
+
41
+ /** The key of `useAsyncData(fn, input)` for the input as it reads now; each key's handler calls `fn` with the input that key was made from. */
42
+ export function handlerSlots<R>(
43
+ app: AppContext,
44
+ fn: HandlerReference,
45
+ input: unknown,
46
+ ): { keyOf: () => string; handlerFor: (key: string) => AsyncDataHandler<R> } {
47
+ const inputs = new Map<string, unknown>()
48
+ return {
49
+ keyOf() {
50
+ const value = valueOf(input)
51
+ const key = asyncDataKey(fn, value)
52
+ inputs.set(key, value)
53
+ return key
54
+ },
55
+ handlerFor(key) {
56
+ const value = inputs.get(key)
57
+ return ({ signal }) =>
58
+ (fn as (input: unknown, init: { signal: AbortSignal; event: AppContext["event"] }) => Promise<R>)(value, {
59
+ signal,
60
+ event: app.event,
61
+ })
62
+ },
63
+ }
64
+ }
65
+
66
+ /** The restored payload entry's data while the app hydrates, else `undefined`. */
67
+ export function defaultGetCachedData<T>(key: string, app: AppContext): T | undefined {
68
+ if (!app.asyncData.hydrating || isPreviewMode(app)) return undefined
69
+ const entry = app.asyncData.get<T>(key)
70
+ return entry?.status === "success" ? entry.data : undefined
71
+ }
72
+
73
+ /** `refresh()`, `execute()` and a `watch` change: ask `getCachedData` with their cause, run `handler` when it has nothing. */
74
+ export function refreshCached<T, R>(
75
+ app: AppContext,
76
+ key: string,
77
+ handler: AsyncDataHandler<R>,
78
+ options: AsyncDataOptions<T, R>,
79
+ getCachedData: GetCachedData<T>,
80
+ cause: GetCachedDataCause,
81
+ ): Promise<void> {
82
+ const cached = getCachedData(key, app, { cause })
83
+ if (cached !== undefined) {
84
+ app.asyncData.fetch<T, R>(key, handler, { ...options, cached })
85
+ return Promise.resolve()
86
+ }
87
+ if (!app.asyncData.has(key)) app.asyncData.fetch<T, R>(key, handler, { ...options, immediate: false })
88
+ return app.asyncData.refresh(key, handler)
89
+ }
90
+
91
+ const kept = new WeakMap<object, Set<string>>()
92
+
93
+ // Nuxt purges no entry whose caller reads it back through its own getCachedData: the entry is that cache.
94
+ export function keepCached<T>(app: AppContext, key: string, getCachedData: GetCachedData<T>): void {
95
+ if (getCachedData === defaultGetCachedData) return
96
+ let keys = kept.get(app.asyncData)
97
+ if (!keys) kept.set(app.asyncData, (keys = new Set()))
98
+ if (keys.has(key)) return
99
+ keys.add(key)
100
+ app.asyncData.subscribe(key, () => {})
101
+ }
102
+
103
+ /** The run's signal, combined with a `signal` the caller gave to `injectFetch`. */
104
+ export const signalOf = (own: AbortSignal | undefined, run: AbortSignal): AbortSignal =>
105
+ own ? AbortSignal.any([own, run]) : run
@@ -0,0 +1,127 @@
1
+ import {
2
+ APP_ID,
3
+ DestroyRef,
4
+ Directive,
5
+ InjectionToken,
6
+ PendingTasks,
7
+ TemplateRef,
8
+ ViewContainerRef,
9
+ afterNextRender,
10
+ assertInInjectionContext,
11
+ computed,
12
+ inject,
13
+ signal,
14
+ type Resource,
15
+ type ResourceSnapshot,
16
+ type Signal,
17
+ } from "@angular/core"
18
+ import { checkTransitionName, prehydrate, settledOf } from "hamur/adapter"
19
+ import { HAMUR_APP, mode, onServer, required } from "./context.ts"
20
+
21
+ /**
22
+ * `<div *hamurDevOnly>…</div>` renders its template only in a dev build. A production client keeps the template's code:
23
+ * a component named in it is a static import of the compiled one.
24
+ */
25
+ @Directive({ selector: "[hamurDevOnly]" })
26
+ export class DevOnly {
27
+ constructor() {
28
+ if (mode.dev) inject(ViewContainerRef).createEmbeddedView(inject(TemplateRef))
29
+ }
30
+ }
31
+
32
+ const isThenable = (value: unknown): value is PromiseLike<unknown> =>
33
+ typeof (value as { then?: unknown } | null)?.then === "function"
34
+
35
+ /**
36
+ * The value of a promise a loader returned, as Angular's `Resource<T>`: read with `@if (value.hasValue()) … @else if
37
+ * (value.error()) … @else …`. On the server the render waits for it; `value()` throws the error of a rejected promise,
38
+ * as Angular's own resources do.
39
+ */
40
+ export function injectDeferred<T>(promise: PromiseLike<T> | T): Resource<Awaited<T>> {
41
+ assertInInjectionContext(injectDeferred)
42
+ type V = Awaited<T>
43
+ const snapshot = signal<ResourceSnapshot<V | undefined>>({ status: "loading", value: undefined })
44
+ const known = isThenable(promise) ? settledOf(promise) : ({ status: "fulfilled", value: promise } as const)
45
+ if (known)
46
+ snapshot.set(
47
+ known.status === "fulfilled"
48
+ ? { status: "resolved", value: known.value as V }
49
+ : { status: "error", error: errorOf(known.reason) },
50
+ )
51
+ else {
52
+ const done = onServer() ? inject(PendingTasks).add() : undefined
53
+ const destroyed = { value: false }
54
+ inject(DestroyRef).onDestroy(() => (destroyed.value = true))
55
+ Promise.resolve(promise as PromiseLike<V>).then(
56
+ (value) => {
57
+ if (!destroyed.value) snapshot.set({ status: "resolved", value })
58
+ done?.()
59
+ },
60
+ (reason: unknown) => {
61
+ if (!destroyed.value) snapshot.set({ status: "error", error: errorOf(reason) })
62
+ done?.()
63
+ },
64
+ )
65
+ }
66
+ const read = snapshot.asReadonly()
67
+ return {
68
+ value: computed(() => {
69
+ const current = read()
70
+ if (current.status === "error") throw current.error
71
+ return current.value
72
+ }),
73
+ status: computed(() => read().status),
74
+ error: computed(() => {
75
+ const current = read()
76
+ return current.status === "error" ? current.error : undefined
77
+ }),
78
+ isLoading: computed(() => read().status === "loading"),
79
+ snapshot: read,
80
+ hasValue: () => {
81
+ const current = read()
82
+ return current.status === "resolved"
83
+ },
84
+ } as unknown as Resource<V>
85
+ }
86
+
87
+ const errorOf = (reason: unknown): Error => (reason instanceof Error ? reason : new Error(String(reason)))
88
+
89
+ /** `false` on the server and until the first render of a hydrated page is done; `true` at once after a client navigation. */
90
+ export function injectHydrated(): Signal<boolean> {
91
+ assertInInjectionContext(injectHydrated)
92
+ const app = required(HAMUR_APP, "injectHydrated")
93
+ const hydrated = signal(typeof document !== "undefined" && !onServer() && !app.asyncData.hydrating)
94
+ const destroy = inject(DestroyRef)
95
+ afterNextRender(() => {
96
+ hydrated.set(!app.asyncData.hydrating)
97
+ destroy.onDestroy(app.hooks.hook("app:mounted", () => hydrated.set(true)))
98
+ })
99
+ return hydrated.asReadonly()
100
+ }
101
+
102
+ /** The counter `injectId` reads; a server-only component's render has one of its own, with a prefix, so it leaves the page's numbering alone. */
103
+ export const HAMUR_IDS = new InjectionToken<{ next: number; prefix: string }>("hamur ids", {
104
+ providedIn: "root",
105
+ factory: () => ({ next: 0, prefix: "" }),
106
+ })
107
+
108
+ /**
109
+ * An id that is the same in the server's HTML and in hydration, `<APP_ID>-<n>`: Angular 22 has no id function of
110
+ * its own, and the components of both renders are created in the same order.
111
+ */
112
+ export function injectId(): string {
113
+ assertInInjectionContext(injectId)
114
+ const counter = inject(HAMUR_IDS)
115
+ return `${counter.prefix}${inject(APP_ID)}-${counter.next++}`
116
+ }
117
+
118
+ /** The id for `data-hamur-p` on the element `fn` is called with, as an inline script before hydration; `undefined` in the browser. */
119
+ export function onPrehydrate(fn: (el: Element) => void): string | undefined {
120
+ assertInInjectionContext(onPrehydrate)
121
+ return prehydrate(required(HAMUR_APP, "onPrehydrate"), fn)
122
+ }
123
+
124
+ /** The `[style]` that names an element for a view transition. */
125
+ export function transitionName(name: string): { "view-transition-name": string } {
126
+ return { "view-transition-name": checkTransitionName(name) }
127
+ }