@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,144 @@
1
+ /** What a client-only or server-only component's wrapper copies from the real component: its selectors (as the compiler wrote them) and the public names of its inputs. */
2
+ export interface ComponentDefinition {
3
+ /** The text of the `selectors` array, valid JSON. */
4
+ selectors: string
5
+ inputs: string[]
6
+ }
7
+
8
+ const QUOTES = new Set(['"', "'", "`"])
9
+ const OPENERS = new Set(["{", "[", "("])
10
+ const CLOSERS = new Set(["}", "]", ")"])
11
+
12
+ function endOfString(text: string, start: number): number {
13
+ const quote = text[start]
14
+ for (let i = start + 1; i < text.length; i++) {
15
+ if (text[i] === "\\") i++
16
+ else if (text[i] === quote) return i + 1
17
+ }
18
+ return text.length
19
+ }
20
+
21
+ function skipComment(text: string, at: number): number | undefined {
22
+ if (text[at] !== "/") return undefined
23
+ if (text[at + 1] === "/") {
24
+ const end = text.indexOf("\n", at)
25
+ return end === -1 ? text.length : end
26
+ }
27
+ if (text[at + 1] === "*") {
28
+ const end = text.indexOf("*/", at + 2)
29
+ return end === -1 ? text.length : end + 2
30
+ }
31
+ return undefined
32
+ }
33
+
34
+ /** The index of the first `,` or closing bracket at depth 0 from `from`: the end of an expression inside a literal. */
35
+ function endOfExpression(text: string, from: number): number {
36
+ let depth = 0
37
+ for (let i = from; i < text.length; i++) {
38
+ const char = text[i]!
39
+ if (QUOTES.has(char)) i = endOfString(text, i) - 1
40
+ else if (skipComment(text, i) !== undefined) i = skipComment(text, i)! - 1
41
+ else if (OPENERS.has(char)) depth++
42
+ else if (CLOSERS.has(char)) {
43
+ if (depth === 0) return i
44
+ depth--
45
+ } else if (char === "," && depth === 0) return i
46
+ }
47
+ return text.length
48
+ }
49
+
50
+ /** The index after the bracket that closes the one at `open`. */
51
+ function endOfLiteral(text: string, open: number): number {
52
+ let depth = 0
53
+ for (let i = open; i < text.length; i++) {
54
+ const char = text[i]!
55
+ if (QUOTES.has(char)) i = endOfString(text, i) - 1
56
+ else if (skipComment(text, i) !== undefined) i = skipComment(text, i)! - 1
57
+ else if (OPENERS.has(char)) depth++
58
+ else if (CLOSERS.has(char) && --depth === 0) return i + 1
59
+ }
60
+ return text.length
61
+ }
62
+
63
+ /** The top-level `key: value` entries of the object literal `object` (its text, braces included). */
64
+ function entriesOf(object: string): Array<[string, string]> {
65
+ const found: Array<[string, string]> = []
66
+ let i = 1
67
+ while (i < object.length) {
68
+ while (i < object.length && /[\s,]/.test(object[i]!)) i++
69
+ if (object[i] === "}" || i >= object.length) break
70
+ const comment = skipComment(object, i)
71
+ if (comment !== undefined) {
72
+ i = comment
73
+ continue
74
+ }
75
+ let key: string
76
+ if (QUOTES.has(object[i]!)) {
77
+ const end = endOfString(object, i)
78
+ key = object.slice(i + 1, end - 1)
79
+ i = end
80
+ } else {
81
+ const match = /^[\w$]+/.exec(object.slice(i))
82
+ if (!match) break
83
+ key = match[0]
84
+ i += key.length
85
+ }
86
+ while (/\s/.test(object[i] ?? "")) i++
87
+ if (object[i] !== ":") {
88
+ i = endOfExpression(object, i)
89
+ continue
90
+ }
91
+ const end = endOfExpression(object, i + 1)
92
+ found.push([key, object.slice(i + 1, end).trim()])
93
+ i = end
94
+ }
95
+ return found
96
+ }
97
+
98
+ const FIRST_STRING = /"((?:[^"\\]|\\.)*)"/
99
+
100
+ /**
101
+ * The selectors and the public input names of the first component the compiler defined in `code`, the JavaScript the
102
+ * Angular program emitted for a file. `undefined` when `code` defines no component.
103
+ */
104
+ export function readDefinition(code: string): ComponentDefinition | undefined {
105
+ const call = code.indexOf("ɵɵdefineComponent(")
106
+ if (call === -1) return undefined
107
+ const open = code.indexOf("{", call)
108
+ if (open === -1) return undefined
109
+ const entries = new Map(entriesOf(code.slice(open, endOfLiteral(code, open))))
110
+ const selectors = entries.get("selectors")
111
+ if (selectors === undefined) return undefined
112
+ const inputs = entries.get("inputs")
113
+ const names =
114
+ inputs === undefined
115
+ ? []
116
+ : entriesOf(inputs).map(([key, value]) => {
117
+ if (value.startsWith('"')) return JSON.parse(value) as string
118
+ const first = FIRST_STRING.exec(value)
119
+ return first ? (JSON.parse(`"${first[1]}"`) as string) : key
120
+ })
121
+ JSON.parse(selectors)
122
+ return { selectors, inputs: names }
123
+ }
124
+
125
+ /** The `selector` of a component from its compiled `selectors`: an element name, attributes and classes, one selector for each list. */
126
+ export function selectorOf(selectors: string): string {
127
+ const lists = JSON.parse(selectors) as Array<Array<string | number>>
128
+ return lists
129
+ .map(([tag, ...rest]) => {
130
+ let text = String(tag)
131
+ for (let i = 0; i < rest.length; i += 2) {
132
+ const name = rest[i]
133
+ if (name === 8) {
134
+ for (const name of rest.slice(i + 1)) text += `.${String(name)}`
135
+ break
136
+ }
137
+ if (typeof name !== "string") throw new Error(`a selector with :not() cannot be a wrapper: ${selectors}`)
138
+ const value = rest[i + 1]
139
+ text += value === "" ? `[${name}]` : `[${name}=${JSON.stringify(String(value))}]`
140
+ }
141
+ return text
142
+ })
143
+ .join(", ")
144
+ }
@@ -0,0 +1,17 @@
1
+ import { Component, input } from "@angular/core"
2
+ import type { ErrorPageProps } from "hamur/app"
3
+
4
+ @Component({
5
+ template: `<main style="font-family: system-ui, sans-serif; text-align: center; padding: 4rem 1rem">
6
+ <h1 style="font-size: 4rem; margin: 0">{{ error().status }}</h1>
7
+ <p>{{ error().message }}</p>
8
+ @if (error().stack) {
9
+ <pre>{{ error().stack }}</pre>
10
+ }
11
+ <a href="/">Back home</a>
12
+ </main>`,
13
+ })
14
+ export default class DefaultErrorPage {
15
+ readonly error = input.required<ErrorPageProps>()
16
+ readonly clearError = input<() => void>()
17
+ }
package/src/error.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { DestroyRef, assertInInjectionContext, computed, inject, signal, untracked, type Signal } from "@angular/core"
2
+ import type { ErrorPageProps } from "hamur/app"
3
+ import { HAMUR_APP, HAMUR_CAUGHT, HAMUR_ROUTE, required } from "./context.ts"
4
+
5
+ /** The error a route boundary or not-found component shows, below it too; else the app's error, `null` when there is none. */
6
+ export function injectError(): Signal<ErrorPageProps | null> {
7
+ assertInInjectionContext(injectError)
8
+ const caught = inject(HAMUR_CAUGHT, { optional: true })
9
+ if (caught) return signal(caught).asReadonly()
10
+ const store = required(HAMUR_APP, "injectError").error
11
+ const route = required(HAMUR_ROUTE, "injectError")
12
+ const error = signal((store ? store.get() : untracked(route).error) as ErrorPageProps | undefined)
13
+ if (store) inject(DestroyRef).onDestroy(store.subscribe(() => error.set(store.get())))
14
+ return computed(() => error() ?? null)
15
+ }
package/src/form.ts ADDED
@@ -0,0 +1,253 @@
1
+ import {
2
+ DestroyRef,
3
+ Directive,
4
+ ElementRef,
5
+ InjectionToken,
6
+ assertInInjectionContext,
7
+ booleanAttribute,
8
+ computed,
9
+ effect,
10
+ inject,
11
+ input,
12
+ signal,
13
+ untracked,
14
+ type Signal,
15
+ } from "@angular/core"
16
+ import {
17
+ IDLE_FORM_STATUS,
18
+ assertFormMethod,
19
+ createActionRunner,
20
+ createFormStatus,
21
+ functionFormAction,
22
+ linkActionRunner,
23
+ optimisticSource,
24
+ restoredResult,
25
+ runFunctionForm,
26
+ } from "hamur/adapter"
27
+ import type { ActionOptions, ActionRunner, FormStatus, FormStatusStore, Handler } from "hamur/adapter"
28
+ import { createForm, enhance } from "hamur/app"
29
+ import type {
30
+ ActionFailure,
31
+ EnhanceOptions,
32
+ FieldsOf,
33
+ HamurError,
34
+ HandlerFormInstance,
35
+ PendingRun,
36
+ RouteLocation,
37
+ } from "hamur/app"
38
+ import {
39
+ HAMUR_APP,
40
+ HAMUR_HREF,
41
+ HAMUR_PAYLOAD,
42
+ HAMUR_ROUTE,
43
+ HAMUR_ROUTER,
44
+ detachedHref,
45
+ onServer,
46
+ required,
47
+ } from "./context.ts"
48
+
49
+ type FormHandler = Handler<any, any>
50
+ type FormAction = string | RouteLocation | FormHandler
51
+
52
+ /** The status of the `Form` a component is created in: what `injectFormStatus` reads and `injectAction` links to. */
53
+ const FORM_STATUS = new InjectionToken<FormStatusStore>("hamur form status")
54
+
55
+ const handlerStateOf = (payload: Signal<unknown> | null) =>
56
+ (payload?.() as { handlerState?: unknown } | undefined)?.handlerState
57
+
58
+ /**
59
+ * `<form hamurForm>`. The host bindings write what the other adapters' `Form` writes on its
60
+ * `<form>`; with a handler it posts to the page with `_fn=<id>` without JavaScript and calls the handler's stub with it.
61
+ */
62
+ @Directive({
63
+ selector: "form[hamurForm]",
64
+ providers: [{ provide: FORM_STATUS, useFactory: createFormStatus }],
65
+ host: {
66
+ "data-hamur-form": "",
67
+ "[attr.method]": "methodAttribute()",
68
+ "[attr.action]": "target()",
69
+ "[attr.enctype]": "encType()",
70
+ "[attr.data-hamur-replace]": "flag(replace())",
71
+ "[attr.data-hamur-reset]": "flag(reset())",
72
+ "[attr.data-hamur-reload]": "flag(reloadDocument())",
73
+ "[attr.data-hamur-refresh]": "refresh() === false ? 'false' : null",
74
+ "[attr.data-hamur-restore]": "restore() ? null : 'false'",
75
+ },
76
+ })
77
+ export class Form {
78
+ readonly action = input<FormAction | undefined, FormAction | "" | undefined>(undefined, {
79
+ alias: "hamurForm",
80
+ transform: (value) => (value === "" ? undefined : value),
81
+ })
82
+ readonly method = input<"get" | "post">()
83
+ readonly encType = input<"application/x-www-form-urlencoded" | "multipart/form-data">()
84
+ readonly replace = input(false, { transform: booleanAttribute })
85
+ readonly reset = input(false, { transform: booleanAttribute })
86
+ readonly reloadDocument = input(false, { transform: booleanAttribute })
87
+ readonly refresh = input<boolean | undefined, unknown>(undefined, {
88
+ transform: (value: unknown) => (value === undefined ? undefined : booleanAttribute(value)),
89
+ })
90
+ readonly restore = input(true, { transform: booleanAttribute })
91
+ readonly instance = input<string | number>()
92
+
93
+ private readonly app = inject(HAMUR_APP, { optional: true })
94
+ private readonly route = inject(HAMUR_ROUTE, { optional: true })
95
+ private readonly router = inject(HAMUR_ROUTER, { optional: true })
96
+ private readonly resolve = inject(HAMUR_HREF, { optional: true }) ?? detachedHref
97
+ private readonly status = inject(FORM_STATUS)
98
+ private readonly element = inject<ElementRef<HTMLFormElement>>(ElementRef).nativeElement
99
+
100
+ protected readonly methodAttribute = computed(() => (typeof this.action() === "function" ? "post" : "get"))
101
+ protected readonly target = computed(() => {
102
+ const action = this.action()
103
+ assertFormMethod(action, this.method())
104
+ const page = this.route ? this.route().fullPath.replace(/#.*$/, "") : undefined
105
+ if (typeof action === "function") return functionFormAction(action, this.resolve(page ?? "/"), this.instance())
106
+ return action !== undefined ? this.resolve(action) : page !== undefined ? this.resolve(page) : undefined
107
+ })
108
+
109
+ private readonly posts = computed(() => typeof this.action() === "function")
110
+
111
+ constructor() {
112
+ const browser = !onServer()
113
+ effect((onCleanup) => {
114
+ if (!browser) return
115
+ const posts = this.posts()
116
+ onCleanup(untracked(() => enhance(this.element, this.enhanceOptions(posts))))
117
+ })
118
+ }
119
+
120
+ private enhanceOptions(posts: boolean): EnhanceOptions {
121
+ const { status } = this
122
+ return {
123
+ onSubmit: (args) => status.submitted(args.formData),
124
+ ...(posts && this.app
125
+ ? { call: (input: Record<string, unknown>, formData: FormData) => this.post(input, formData) }
126
+ : {}),
127
+ }
128
+ }
129
+
130
+ /** The handler, `refresh` and `instance` of the moment of the submission, as `action` and `_fn` show them. */
131
+ private post(input: Record<string, unknown>, formData: FormData) {
132
+ const action = this.action()
133
+ const { app, router, status } = this
134
+ if (typeof action !== "function" || !app) return Promise.resolve(false)
135
+ return runFunctionForm(app, action, input, formData, () => router?.refresh() ?? Promise.resolve(), status, {
136
+ refresh: this.refresh(),
137
+ instance: this.instance(),
138
+ })
139
+ }
140
+
141
+ protected flag(value: boolean): "" | null {
142
+ return value ? "" : null
143
+ }
144
+ }
145
+
146
+ /** The run of the `Form` the component is created in; idle outside one. */
147
+ export function injectFormStatus(): Signal<FormStatus> {
148
+ assertInInjectionContext(injectFormStatus)
149
+ const store = inject(FORM_STATUS, { optional: true })
150
+ if (!store) return signal(IDLE_FORM_STATUS).asReadonly()
151
+ const status = signal(store.get())
152
+ inject(DestroyRef).onDestroy(store.subscribe(() => status.set(store.get())))
153
+ return status.asReadonly()
154
+ }
155
+
156
+ /** What `injectForm(fn)` and its `for(key)` return: the field helpers, and the store's values as signals. */
157
+ export interface InjectFormInstance<I, O> {
158
+ readonly fields: FieldsOf<I>
159
+ /** True while a run of this handler and instance is in `pendingRuns`. */
160
+ readonly pending: Signal<boolean>
161
+ /** What the last run returned, a `fail()` included. */
162
+ readonly result: Signal<O | undefined>
163
+ }
164
+
165
+ export interface InjectFormResult<I, O> extends InjectFormInstance<I, O> {
166
+ /** The store of `injectAction(fn, { instance: key })`. */
167
+ for(key: string | number): InjectFormInstance<I, O>
168
+ }
169
+
170
+ /** The field helpers of `fn`'s input and the store of its runs; a field's reads follow the store too. */
171
+ export function injectForm<I, O>(fn: Handler<I, O>): InjectFormResult<I, O> {
172
+ assertInInjectionContext(injectForm)
173
+ const payload = inject(HAMUR_PAYLOAD, { optional: true })
174
+ const version = signal(0)
175
+ const form = createForm(fn, {
176
+ app: inject(HAMUR_APP, { optional: true }),
177
+ submitted: () => ({ handlerState: handlerStateOf(payload) }),
178
+ track: () => void version(),
179
+ })
180
+ inject(DestroyRef).onDestroy(form.subscribe(() => version.set(form.version())))
181
+ const signals = (instance: HandlerFormInstance<I, O>): InjectFormInstance<I, O> => ({
182
+ fields: instance.fields,
183
+ pending: computed(() => instance.pending),
184
+ result: computed(() => instance.result),
185
+ })
186
+ const instances = new Map<string | number, InjectFormInstance<I, O>>()
187
+ return {
188
+ ...signals(form),
189
+ for(key) {
190
+ let instance = instances.get(key)
191
+ if (!instance) instances.set(key, (instance = signals(form.for(key))))
192
+ return instance
193
+ },
194
+ }
195
+ }
196
+
197
+ export interface InjectActionResult<I, O> {
198
+ readonly run: ActionRunner<I, O>["run"]
199
+ readonly state: Signal<O | undefined>
200
+ readonly pending: Signal<boolean>
201
+ readonly error: Signal<HamurError | undefined>
202
+ readonly failure: Signal<ActionFailure | undefined>
203
+ reset(): void
204
+ }
205
+
206
+ /** Runs `fn` one call after another; below a `Form` of `fn` it shows that form's posts. */
207
+ export function injectAction<I, O>(
208
+ fn: Handler<I, O>,
209
+ options: ActionOptions<O> & { instance?: string | number } = {},
210
+ ): InjectActionResult<I, O> {
211
+ assertInInjectionContext(injectAction)
212
+ const router = required(HAMUR_ROUTER, "injectAction")
213
+ const app = inject(HAMUR_APP, { optional: true })
214
+ const { instance } = options
215
+ const runner = createActionRunner(fn, {
216
+ app,
217
+ instance,
218
+ options: () => options,
219
+ refresh: () => router.refresh(),
220
+ restored: restoredResult<O>(handlerStateOf(inject(HAMUR_PAYLOAD, { optional: true })), fn.id, instance),
221
+ })
222
+ const snapshot = signal(runner.get())
223
+ const destroy = inject(DestroyRef)
224
+ destroy.onDestroy(runner.subscribe(() => snapshot.set(runner.get())))
225
+ const below = inject(FORM_STATUS, { optional: true })
226
+ if (below) destroy.onDestroy(below.owner.link(fn.id, runner, instance))
227
+ else if (app) destroy.onDestroy(linkActionRunner(app, fn.id, runner, instance))
228
+ return {
229
+ run: runner.run,
230
+ reset: runner.reset,
231
+ state: computed(() => snapshot().state),
232
+ pending: computed(() => snapshot().pending),
233
+ error: computed(() => snapshot().error),
234
+ failure: computed(() => snapshot().failure),
235
+ }
236
+ }
237
+
238
+ /** `value` while no handler call runs, else `reduce(value, the running calls)`. */
239
+ export function injectOptimistic<T, A = PendingRun>(
240
+ value: T | (() => T),
241
+ reduce: (current: T, pending: A[]) => T,
242
+ ): Signal<T> {
243
+ assertInInjectionContext(injectOptimistic)
244
+ const source = optimisticSource(inject(HAMUR_APP, { optional: true }))
245
+ const pending = signal(source.get())
246
+ inject(DestroyRef).onDestroy(source.subscribe(() => pending.set(source.get())))
247
+ const read = typeof value === "function" ? (value as () => T) : () => value as T
248
+ return computed(() => {
249
+ const runs = pending()
250
+ const current = read()
251
+ return runs.length ? reduce(current, runs as unknown as A[]) : current
252
+ })
253
+ }
package/src/head.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { DestroyRef, assertInInjectionContext, effect, inject, untracked } from "@angular/core"
2
+ import { sanitizeHead, seoMetaToHead } from "hamur/adapter"
3
+ import type { HeadInput, HeadSafeInput, SeoMetaInput } from "hamur/app"
4
+ import { HAMUR_APP, HAMUR_LEVEL_DISPOSE, onServer, required } from "./context.ts"
5
+
6
+ type ServerHeadInput = Omit<HeadInput, "title" | "titleTemplate">
7
+ type ServerSeoMetaInput = Omit<SeoMetaInput, "title" | "titleTemplate">
8
+ type Input<T> = T | (() => T)
9
+
10
+ const resolve = <T>(input: Input<T>): T => (typeof input === "function" ? (input as () => T)() : input)
11
+
12
+ /** An entry of the request's head, patched when the signals its function reads change and removed with the component; the server's head is the request's, so nothing is removed there. */
13
+ export function injectHead(input: Input<HeadInput>): void {
14
+ assertInInjectionContext(injectHead)
15
+ const head = required(HAMUR_APP, "injectHead").head
16
+ const server = onServer()
17
+ const entry = head.push(untracked(() => resolve(input)))
18
+ if (!server) {
19
+ let disposed = false
20
+ const dispose = () => {
21
+ if (disposed) return
22
+ disposed = true
23
+ entry.dispose()
24
+ head.apply()
25
+ }
26
+ inject(DestroyRef).onDestroy(dispose)
27
+ inject(HAMUR_LEVEL_DISPOSE, { optional: true })?.(dispose)
28
+ }
29
+ effect(() => {
30
+ const next = resolve(input)
31
+ untracked(() => {
32
+ entry.patch(next)
33
+ if (!server) head.apply()
34
+ })
35
+ })
36
+ }
37
+
38
+ export function injectSeoMeta(input: Input<SeoMetaInput>): void {
39
+ assertInInjectionContext(injectSeoMeta)
40
+ injectHead(() => seoMetaToHead(resolve(input)))
41
+ }
42
+
43
+ export function injectHeadSafe(input: Input<HeadSafeInput>): void {
44
+ assertInInjectionContext(injectHeadSafe)
45
+ injectHead(() => sanitizeHead(resolve(input)))
46
+ }
47
+
48
+ /** Tags written for the server render only; the browser does nothing. */
49
+ export function injectServerHead(input: Input<ServerHeadInput>): void {
50
+ assertInInjectionContext(injectServerHead)
51
+ const head = required(HAMUR_APP, "injectServerHead").head
52
+ if (!onServer()) return
53
+ const entry = head.push(
54
+ untracked(() => resolve(input)),
55
+ { server: true },
56
+ )
57
+ if (typeof input === "function") effect(() => entry.patch(resolve(input)))
58
+ }
59
+
60
+ export function injectServerSeoMeta(input: Input<ServerSeoMetaInput>): void {
61
+ assertInInjectionContext(injectServerSeoMeta)
62
+ injectServerHead(() => seoMetaToHead(resolve(input)))
63
+ }
package/src/hmr.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type {} from "hamur"
2
+ import type { Adapter } from "hamur/adapter"
3
+ import { addDevServerHandler, useDevChannel, useHamur, type DevChange, type HamurContext } from "hamur/kit"
4
+ import { devProgramOf, releaseDevProgram, setDevBaseURL } from "./compile.ts"
5
+
6
+ declare module "hamur" {
7
+ interface HamurDevEvents {
8
+ "angular:component-update": { id: string; timestamp: number }
9
+ }
10
+ }
11
+
12
+ /** Per context, Angular's decoded component id to the last update module stored for it. */
13
+ const stores = new WeakMap<HamurContext, Map<string, string>>()
14
+
15
+ const NO_STORE = { "content-type": "text/javascript", "cache-control": "no-store" }
16
+
17
+ /**
18
+ * `modules:done` serves `/@ng/component`; `dev:change` sends the update, or lists the components
19
+ * that read the file as dependents with `hmr` off, and with it on those a template error is shown in; `close` drops the program.
20
+ */
21
+ export const angularHooks: NonNullable<Adapter["hooks"]> = {
22
+ "modules:done": () => {
23
+ const hamur = useHamur()
24
+ const { dev, devServer, rootDir, buildDir, app } = hamur.options
25
+ if (!dev || !devServer.hmr) return
26
+ setDevBaseURL(rootDir, buildDir, app.baseURL)
27
+ const updates = new Map<string, string>()
28
+ stores.set(hamur, updates)
29
+ addDevServerHandler({
30
+ route: "/@ng/component",
31
+ handler: (request) => {
32
+ if (request.method !== "GET") return undefined
33
+ const id = new URL(request.url).searchParams.get("c")
34
+ if (id === null) return undefined
35
+ return new Response(updates.get(id) ?? "", { headers: NO_STORE })
36
+ },
37
+ })
38
+ },
39
+ "dev:change": async (change: DevChange) => {
40
+ const hamur = useHamur()
41
+ const { dev, devServer, rootDir, buildDir } = hamur.options
42
+ const program = dev ? devProgramOf(rootDir, buildDir) : undefined
43
+ if (!program) return
44
+ if (!devServer.hmr) {
45
+ change.dependents.push(...program.dependentsOf(change.file))
46
+ return
47
+ }
48
+ const { updates, reload } = await program.hotUpdate(change.file)
49
+ change.dependents.push(...reload)
50
+ const store = stores.get(hamur)
51
+ if (!updates.length || !store) return
52
+ const timestamp = Date.now()
53
+ for (const { id, code } of updates) store.set(decodeURIComponent(id), code)
54
+ const channel = useDevChannel()
55
+ for (const { id } of updates) channel.send("angular:component-update", { id, timestamp })
56
+ },
57
+ close: () => {
58
+ const { rootDir, buildDir } = useHamur().options
59
+ releaseDevProgram(rootDir, buildDir)
60
+ },
61
+ }
@@ -0,0 +1,120 @@
1
+ import type { HydrationMismatch } from "hamur/adapter/dev"
2
+
3
+ const CODES = /^(NG0(?:500|501|502|509)): During hydration/
4
+ const MARKER = "<-- AT THIS LOCATION"
5
+ const HOST = "hamur-app"
6
+ const FOOTER_COMPONENT = /check the "([^"]+)" component/
7
+ const MORE = / Find more at \S+$/
8
+ const OPENING = /^\s*<([a-z][\w-]*)((?:\s+[^\s=<>]+="[^"]*")*)>/
9
+ const ATTRIBUTE = /([^\s=<>]+)="([^"]*)"/g
10
+
11
+ /** The parts of an element `angularMismatch` reads, so a test can pass a plain object tree. */
12
+ export interface MismatchElement {
13
+ readonly localName: string
14
+ readonly id?: string
15
+ readonly parentElement: MismatchElement | null
16
+ readonly children: ArrayLike<MismatchElement>
17
+ getAttribute(name: string): string | null
18
+ querySelectorAll(selector: string): ArrayLike<MismatchElement>
19
+ }
20
+
21
+ const reported = new WeakSet<object>()
22
+
23
+ const paragraphs = (message: string) => message.split("\n\n").map((part) => part.replace(/^\n+/, ""))
24
+
25
+ function after(parts: string[], label: string): string | undefined {
26
+ const index = parts.indexOf(label)
27
+ return index < 0 ? undefined : parts[index + 1]?.trimEnd()
28
+ }
29
+
30
+ function afterHeader(parts: string[]): string | undefined {
31
+ const next = parts[1]
32
+ return next?.includes(MARKER) ? next.trimEnd() : undefined
33
+ }
34
+
35
+ // Angular's describeRNode shows an attribute value without whitespace, cut at 50 characters.
36
+ const shorten = (value: string) => {
37
+ const flat = value.replace(/\s+/g, "")
38
+ return flat.length > 50 ? `${flat.slice(0, 49)}…` : flat
39
+ }
40
+
41
+ function step(element: MismatchElement): string {
42
+ const same = Array.from(element.parentElement?.children ?? []).filter(
43
+ (child) => child.localName === element.localName,
44
+ )
45
+ return same.length > 1 ? `${element.localName}:nth-of-type(${same.indexOf(element) + 1})` : element.localName
46
+ }
47
+
48
+ function pathOf(root: MismatchElement, element: MismatchElement): string {
49
+ const chain: MismatchElement[] = []
50
+ for (let current: MismatchElement | null = element; current && current !== root; current = current.parentElement)
51
+ chain.unshift(current)
52
+ return [root.id ? `#${root.id}` : root.localName, ...chain.map(step)].join(" > ")
53
+ }
54
+
55
+ function describes(element: MismatchElement, tag: string, attributes: string): boolean {
56
+ if (element.localName !== tag) return false
57
+ for (const [, name, value] of attributes.matchAll(ATTRIBUTE)) {
58
+ const actual = element.getAttribute(name!)
59
+ if (actual === null || shorten(actual) !== value) return false
60
+ }
61
+ return true
62
+ }
63
+
64
+ /** The element on the marker line of Angular's "actual" outline, or its parent when the marker is on a text or comment node. */
65
+ function locate(root: MismatchElement, actual: string): MismatchElement | undefined {
66
+ const lines = actual.split("\n")
67
+ const at = lines.findIndex((line) => line.includes(MARKER))
68
+ if (at < 0) return undefined
69
+ const own = OPENING.exec(lines[at]!)
70
+ const parent = at > 0 ? OPENING.exec(lines[0]!) : null
71
+ const wanted = own ?? parent
72
+ if (!wanted) return undefined
73
+ const [, tag, attributes] = wanted
74
+ const found = Array.from(root.querySelectorAll(tag!)).find(
75
+ (element) =>
76
+ !reported.has(element) &&
77
+ describes(element, tag!, attributes!) &&
78
+ (!own || !parent || element.parentElement?.localName === parent[1]),
79
+ )
80
+ if (found) reported.add(found)
81
+ return found
82
+ }
83
+
84
+ /** The first element whose component class is `name`, through the `ng` debug global of a development build. */
85
+ function hostOf(root: MismatchElement, name: string): MismatchElement | undefined {
86
+ const ng = (globalThis as { ng?: { getComponent?(element: unknown): { constructor: { name: string } } | null } }).ng
87
+ const read = ng?.getComponent
88
+ if (!read) return undefined
89
+ return Array.from(root.querySelectorAll("*")).find((element) => read(element)?.constructor.name === name)
90
+ }
91
+
92
+ /**
93
+ * The report of a hydration mismatch Angular detected (NG0500, NG0501, NG0502 and NG0509 of the hydration, read from
94
+ * the message alone); any other error, a serialization error included, is `undefined`. `root` holds `<hamur-app>`; without it
95
+ * the report has Angular's outlines and the path of the app host.
96
+ */
97
+ export function angularMismatch(
98
+ error: unknown,
99
+ route: string,
100
+ root: MismatchElement | undefined = typeof document === "undefined"
101
+ ? undefined
102
+ : ((document.querySelector(HOST)?.parentElement ?? undefined) as MismatchElement | undefined),
103
+ ): HydrationMismatch | undefined {
104
+ if (!(error instanceof Error)) return undefined
105
+ const code = CODES.exec(error.message)?.[1]
106
+ if (!code) return undefined
107
+ const parts = paragraphs(error.message)
108
+ const named = FOOTER_COMPONENT.exec(error.message)?.[1]
109
+ const client =
110
+ after(parts, "Angular expected this DOM:") ?? (code === "NG0502" ? afterHeader(parts) : undefined) ?? ""
111
+ const server = after(parts, "Actual DOM is:") ?? (code === "NG0501" ? afterHeader(parts) : undefined) ?? ""
112
+ const element = root && ((server ? locate(root, server) : undefined) ?? (named ? hostOf(root, named) : undefined))
113
+ return {
114
+ component: named ?? route,
115
+ path: root && element ? pathOf(root, element) : `#__hamur > ${HOST}`,
116
+ server,
117
+ client,
118
+ reason: parts[0]!.split("\n")[0]!.replace(MORE, ""),
119
+ }
120
+ }