@crombolo/render 0.36.2 → 0.38.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/render",
3
- "version": "0.36.2",
3
+ "version": "0.38.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. TSX server rendering and the published-content model for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -19,6 +19,8 @@
19
19
  "type": "module",
20
20
  "exports": {
21
21
  ".": "./src/index.ts",
22
+ "./navigation": "./src/navigation.ts",
23
+ "./headers": "./src/headers.ts",
22
24
  "./jsx-runtime": "./src/jsx-runtime.ts",
23
25
  "./jsx-dev-runtime": "./src/jsx-runtime.ts",
24
26
  "./loose/jsx-runtime": "./src/loose/jsx-runtime.ts",
@@ -32,7 +34,8 @@
32
34
  "access": "public"
33
35
  },
34
36
  "dependencies": {
35
- "@crombolo/core": "0.36.2",
37
+ "@crombolo/common": "0.38.1",
38
+ "@crombolo/core": "0.38.1",
36
39
  "@types/react": "^19.3.0"
37
40
  }
38
41
  }
@@ -1,15 +1,12 @@
1
1
  /**
2
- * What a page needs to call a bundle's member and public routes (story 186):
3
- * the anti-forgery meta tag, and the script that sends it back.
4
- * `docs/bundles.md`, Part 3.
2
+ * What a page needs to call the site's route handlers as a signed-in member
3
+ * (stories 186 and 211): the anti-forgery meta tag, and the script that sends
4
+ * it back. docs/rendering.md, "Route handlers".
5
5
  */
6
6
  import { currentAntiforgery } from './context.ts'
7
7
  import { RawHtml } from './html.ts'
8
8
  import { element } from './jsx-runtime.ts'
9
9
 
10
- /** Where a bundle's member and public routes answer: `/crombolo/bundle/<id>/<path>`. */
11
- export const BUNDLE_SITE_PATH = '/crombolo/bundle'
12
-
13
10
  /** The header a cookie-authenticated member write carries. */
14
11
  export const ANTIFORGERY_HEADER = 'Crombolo-Antiforgery'
15
12
 
@@ -31,7 +28,7 @@ export function AntiforgeryMeta(): RawHtml {
31
28
  * `crombolo.fetch(input, init)`: `fetch`, with the page's anti-forgery token
32
29
  * on requests to this site. Never sent to another origin.
33
30
  */
34
- export const BUNDLE_SCRIPT = `/* crombolo bundle routes: fetch with the member's anti-forgery token */
31
+ export const BUNDLE_SCRIPT = `/* crombolo: fetch with the member's anti-forgery token, for the site's routes */
35
32
  (function () {
36
33
  var crombolo = (window.crombolo = window.crombolo || {})
37
34
  if (crombolo.fetch) return
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The component stack of a template error (story 214): which components were
3
+ * rendering when it was thrown, outermost first, `homePage › Layout › Card`.
4
+ * Recorded only where error details are shown, by a tracker the JSX runtime
5
+ * calls for each component.
6
+ */
7
+ import { AsyncLocalStorage } from 'node:async_hooks'
8
+ import { type Child, COMPONENT_TRACKER, isPromise } from './jsx-runtime.ts'
9
+
10
+ const STACK = Symbol.for('crombolo.componentStack')
11
+ const owners = new AsyncLocalStorage<readonly string[]>()
12
+
13
+ function tag(error: unknown, chain: readonly string[]): unknown {
14
+ // The innermost component tags it first; the ones around it leave that alone.
15
+ if (error !== null && typeof error === 'object' && !(STACK in error))
16
+ Object.defineProperty(error, STACK, { value: chain })
17
+ return error
18
+ }
19
+
20
+ /** Runs a component's render with its name on the stack, tagging what it throws. */
21
+ export function trackComponent<T>(name: string, call: () => T): T {
22
+ if (!tracking()) return call()
23
+ const chain = [...(owners.getStore() ?? []), name]
24
+ try {
25
+ const result = owners.run(chain, call)
26
+ return (
27
+ isPromise(result)
28
+ ? (result as Promise<unknown>).then(undefined, (error: unknown) => {
29
+ throw tag(error, chain)
30
+ })
31
+ : result
32
+ ) as T
33
+ } catch (error) {
34
+ throw tag(error, chain)
35
+ }
36
+ }
37
+
38
+ /** Starts recording component stacks in this process. */
39
+ export function enableComponentStack(): void {
40
+ ;(globalThis as Record<symbol, unknown>)[COMPONENT_TRACKER] = (name: string, call: () => Child) =>
41
+ trackComponent(name, call)
42
+ }
43
+
44
+ function tracking(): boolean {
45
+ return (globalThis as Record<symbol, unknown>)[COMPONENT_TRACKER] !== undefined
46
+ }
47
+
48
+ /** The components that were rendering when this was thrown, outermost first. */
49
+ export function componentStackOf(error: unknown): readonly string[] | undefined {
50
+ return error !== null && typeof error === 'object'
51
+ ? ((error as Record<symbol, unknown>)[STACK] as readonly string[] | undefined)
52
+ : undefined
53
+ }
package/src/context.ts CHANGED
@@ -13,6 +13,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'
13
13
  import type { Child } from './jsx-runtime.ts'
14
14
  import type { PageProps } from './model.ts'
15
15
  import type { SiteSearchPort } from './search.ts'
16
+ import type { Metadata } from './seo.ts'
16
17
 
17
18
  interface RenderScope {
18
19
  page: PageProps | undefined
@@ -29,6 +30,21 @@ interface RenderScope {
29
30
  preview?: boolean
30
31
  /** The signed-in member's anti-forgery token, for `<AntiforgeryMeta />`. */
31
32
  antiforgery?: string
33
+ /** The request's own values, for `cookies()` and `headers()`; empty for a static page. */
34
+ request?: RequestValues
35
+ /** The site's services as the visitor, for `site()`. */
36
+ site?: () => unknown
37
+ /** Set once the page reads anything that depends on who is asking (story 206). */
38
+ personal?: { value: boolean }
39
+ /** What the page's `generateMetadata` returned, for `<SeoHead>`. */
40
+ metadata?: { value?: Metadata }
41
+ /** Set once anything on the page renders an island, so the loader is linked (story 209). */
42
+ islands?: { used: boolean }
43
+ }
44
+
45
+ /** What `cookies()` and `headers()` read: the request's, or nothing for a static page. */
46
+ export interface RequestValues {
47
+ headers: Headers
32
48
  }
33
49
 
34
50
  /** Loads `components/blocks/<alias>.tsx`'s default export, or nothing when there is none. */
@@ -42,6 +58,11 @@ export interface RenderScopeOptions {
42
58
  blockComponent?: BlockComponentLoader
43
59
  preview?: boolean
44
60
  antiforgery?: string
61
+ request?: RequestValues
62
+ site?: () => unknown
63
+ personal?: { value: boolean }
64
+ metadata?: { value?: Metadata }
65
+ islands?: { used: boolean }
45
66
  }
46
67
 
47
68
  /**
@@ -62,6 +83,14 @@ export function renderScope<T>(
62
83
  return store.run({ page, ...options, contexts: new Map(), ids: { next: 0 } }, render)
63
84
  }
64
85
 
86
+ /**
87
+ * Runs a route handler (story 211): 206's `cookies()`, `headers()` and `site()`
88
+ * read this request, and there is no page.
89
+ */
90
+ export function requestScope<T>(request: RequestValues, site: () => unknown, run: () => T): T {
91
+ return store.run({ page: undefined, request, site, contexts: new Map(), ids: { next: 0 } }, run)
92
+ }
93
+
65
94
  /** Runs an e-mail template's render: ids and context work, and there is no page. */
66
95
  export function emailScope<T>(render: () => T): T {
67
96
  return store.run({ page: undefined, email: true, contexts: new Map(), ids: { next: 0 } }, render)
@@ -152,13 +181,7 @@ export function createContext<T>(defaultValue: T): Context<T> {
152
181
  const contexts = new Map(outer?.contexts)
153
182
  contexts.set(key, value)
154
183
  return store.run(
155
- {
156
- page: outer?.page,
157
- email: outer?.email,
158
- search: outer?.search,
159
- contexts,
160
- ids: outer?.ids ?? { next: 0 },
161
- },
184
+ { ...outer, page: outer?.page, contexts, ids: outer?.ids ?? { next: 0 } },
162
185
  children,
163
186
  )
164
187
  }
@@ -180,3 +203,41 @@ export function blockComponentLoader(): BlockComponentLoader | undefined {
180
203
  export function isPreview(): boolean {
181
204
  return store.getStore()?.preview === true
182
205
  }
206
+
207
+ /** Records that the page depends on who is asking, so it is never shared. */
208
+ export function markPersonal(): void {
209
+ const personal = store.getStore()?.personal
210
+ if (personal) personal.value = true
211
+ }
212
+
213
+ /** The request's values for `cookies()` and `headers()`, which name themselves as `caller`. */
214
+ export function currentRequest(caller: string): RequestValues {
215
+ const scope = within(caller)
216
+ if (scope.email) throw new Error(`${caller} was called while ${NO_PAGE_IN_EMAIL}`)
217
+ markPersonal()
218
+ return scope.request ?? { headers: new Headers() }
219
+ }
220
+
221
+ /** The language of the page rendering, or null outside a page. */
222
+ export function currentCulture(): string | null {
223
+ return store.getStore()?.page?.culture ?? null
224
+ }
225
+
226
+ /** The site's services for this render, built by the server for whoever is asking. */
227
+ export function currentSite(caller: string): unknown {
228
+ const scope = within(caller)
229
+ if (scope.email) throw new Error(`${caller} was called while ${NO_PAGE_IN_EMAIL}`)
230
+ if (!scope.site) throw new Error(`${caller} has no site services in this render.`)
231
+ return scope.site()
232
+ }
233
+
234
+ /** What the page's `generateMetadata` returned, when it has one. */
235
+ export function currentMetadata(): Metadata | undefined {
236
+ return store.getStore()?.metadata?.value
237
+ }
238
+
239
+ /** Records that the page holds an island, so it links the island loader. */
240
+ export function markIslands(): void {
241
+ const islands = store.getStore()?.islands
242
+ if (islands) islands.used = true
243
+ }
package/src/headers.ts ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The request a page is rendering for, as `next/headers` offers it: `cookies()`
3
+ * and `headers()`, both read-only. Reading either makes the page personal, so
4
+ * it is never shared (story 206).
5
+ */
6
+ import type { ReadonlyRequestCookies, RequestCookie } from '@crombolo/common'
7
+ import { currentRequest } from './context.ts'
8
+
9
+ export type { ReadonlyRequestCookies, RequestCookie } from '@crombolo/common'
10
+
11
+ /** The request's headers, read-only: `get`, `has` and iteration. */
12
+ export interface ReadonlyHeaders extends Iterable<[string, string]> {
13
+ get(name: string): string | null
14
+ has(name: string): boolean
15
+ entries(): IterableIterator<[string, string]>
16
+ keys(): IterableIterator<string>
17
+ values(): IterableIterator<string>
18
+ forEach(callback: (value: string, name: string) => void): void
19
+ }
20
+
21
+ function parseCookies(header: string | null): RequestCookie[] {
22
+ if (!header) return []
23
+ const found: RequestCookie[] = []
24
+ for (const part of header.split(';')) {
25
+ const at = part.indexOf('=')
26
+ if (at <= 0) continue
27
+ const name = part.slice(0, at).trim()
28
+ const raw = part
29
+ .slice(at + 1)
30
+ .trim()
31
+ .replace(/^"(.*)"$/, '$1')
32
+ let value = raw
33
+ try {
34
+ value = decodeURIComponent(raw)
35
+ } catch {}
36
+ if (name) found.push({ name, value })
37
+ }
38
+ return found
39
+ }
40
+
41
+ function readonlyCookies(header: string | null): ReadonlyRequestCookies {
42
+ const all = parseCookies(header)
43
+ const first = new Map<string, RequestCookie>()
44
+ for (const cookie of all) if (!first.has(cookie.name)) first.set(cookie.name, cookie)
45
+ return Object.freeze({
46
+ get: (name: string) => first.get(name),
47
+ getAll: (name?: string) => (name === undefined ? [...all] : all.filter((c) => c.name === name)),
48
+ has: (name: string) => first.has(name),
49
+ size: first.size,
50
+ [Symbol.iterator]: () => first.entries(),
51
+ })
52
+ }
53
+
54
+ function readonlyHeaders(source: Headers): ReadonlyHeaders {
55
+ const copy = new Headers(source)
56
+ return Object.freeze({
57
+ get: (name: string) => copy.get(name),
58
+ has: (name: string) => copy.has(name),
59
+ entries: () => copy.entries(),
60
+ keys: () => copy.keys(),
61
+ values: () => copy.values(),
62
+ forEach: (callback: (value: string, name: string) => void) =>
63
+ copy.forEach((value, name) => {
64
+ callback(value, name)
65
+ }),
66
+ [Symbol.iterator]: () => copy.entries(),
67
+ })
68
+ }
69
+
70
+ /** The request's cookies; empty on a page that exports `dynamic = 'force-static'`. */
71
+ export function cookies(): Promise<ReadonlyRequestCookies> {
72
+ try {
73
+ return Promise.resolve(readonlyCookies(currentRequest('cookies()').headers.get('cookie')))
74
+ } catch (error) {
75
+ return Promise.reject(error)
76
+ }
77
+ }
78
+
79
+ /** The request's headers; empty on a page that exports `dynamic = 'force-static'`. */
80
+ export function headers(): Promise<ReadonlyHeaders> {
81
+ try {
82
+ return Promise.resolve(readonlyHeaders(currentRequest('headers()').headers))
83
+ } catch (error) {
84
+ return Promise.reject(error)
85
+ }
86
+ }
package/src/index.ts CHANGED
@@ -1,14 +1,18 @@
1
1
  export * from './blocks.ts'
2
2
  export * from './bundle-script.ts'
3
3
  export * from './cache-policy.ts'
4
+ export * from './component-stack.ts'
4
5
  export * from './context.ts'
5
6
  export * from './email.ts'
6
7
  export * from './excerpt.ts'
7
8
  export * from './form-script.ts'
8
9
  export * from './forms.ts'
9
10
  export * from './html.ts'
11
+ export * from './islands.ts'
12
+ export * from './islands-loader.ts'
10
13
  export * from './jsx-attributes.ts'
11
14
  export * from './jsx-runtime.ts'
15
+ export * from './live-reload.ts'
12
16
  export * from './media.ts'
13
17
  export * from './media-cache.ts'
14
18
  export * from './menus.ts'
@@ -19,6 +23,7 @@ export * from './renderer.ts'
19
23
  export * from './search.ts'
20
24
  export * from './seo.ts'
21
25
  export * from './sign-in.ts'
26
+ export * from './site.ts'
22
27
  export * from './sitemap.ts'
23
28
  export * from './snapshots.ts'
24
29
  export * from './url-segment.ts'
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The island loader, served at `/crombolo/islands.js` (story 209). It finds
3
+ * every `<crombolo-island>`, waits for its `data-load` condition, imports its
4
+ * module through the generation's manifest, and mounts it: a client
5
+ * component with React, an `<Island>` module through its `mount` function.
6
+ *
7
+ * Written as a function and served as its source, so a test can run it with
8
+ * stand-ins for the browser. A file, never inline, so a page with islands
9
+ * works under `script-src 'self'`.
10
+ */
11
+
12
+ /** What the loader needs from the browser. */
13
+ export interface LoaderEnvironment {
14
+ document: {
15
+ querySelector(selector: string): { getAttribute(name: string): string | null } | null
16
+ querySelectorAll(selector: string): ArrayLike<IslandElement>
17
+ }
18
+ importModule(url: string): Promise<Record<string, unknown>>
19
+ fetchJson(url: string): Promise<IslandManifest>
20
+ IntersectionObserver?: new (
21
+ callback: (entries: Array<{ isIntersecting: boolean; target: unknown }>) => void,
22
+ options?: { rootMargin?: string },
23
+ ) => { observe(target: unknown): void; unobserve(target: unknown): void }
24
+ requestIdleCallback?: (callback: () => void) => void
25
+ setTimeout(callback: () => void, ms: number): unknown
26
+ console: { error(...values: unknown[]): void }
27
+ }
28
+
29
+ /** The element an island renders as, as far as the loader touches it. */
30
+ export interface IslandElement {
31
+ dataset: Record<string, string | undefined>
32
+ querySelector(selector: string): { textContent: string | null; innerHTML: string } | null
33
+ cloneNode(deep: boolean): {
34
+ querySelectorAll(selector: string): ArrayLike<{ remove(): void }>
35
+ innerHTML: string
36
+ }
37
+ replaceChildren(): void
38
+ }
39
+
40
+ /** What a generation's build, or a Vite manifest made over, says: where each island's code is. */
41
+ export interface IslandManifest {
42
+ /** The module that mounts a React component: `mount(Component, element, props, childrenHtml)`. */
43
+ react?: string
44
+ modules: Record<string, string>
45
+ }
46
+
47
+ export function islandLoader(env: LoaderEnvironment): void {
48
+ const meta = env.document.querySelector('meta[name="crombolo-islands"]')
49
+ const manifestUrl = meta?.getAttribute('content')
50
+ if (!manifestUrl) return
51
+ let manifest: Promise<IslandManifest> | undefined
52
+ const modules = new Map<string, Promise<Record<string, unknown>>>()
53
+ const load = (url: string) => {
54
+ let pending = modules.get(url)
55
+ if (!pending) {
56
+ pending = env.importModule(url)
57
+ modules.set(url, pending)
58
+ }
59
+ return pending
60
+ }
61
+
62
+ /** What the server rendered as the island's content, less its props and carried children. */
63
+ const shownHtml = (element: IslandElement): string => {
64
+ const copy = element.cloneNode(true)
65
+ const extras = copy.querySelectorAll(
66
+ ':scope > script[type="application/json"], :scope > template[data-children]',
67
+ )
68
+ for (let i = 0; i < extras.length; i++) extras[i]?.remove()
69
+ return copy.innerHTML
70
+ }
71
+
72
+ const mount = async (element: IslandElement): Promise<void> => {
73
+ if (element.dataset.mounted) return
74
+ element.dataset.mounted = 'true'
75
+ const name = element.dataset.module ?? '?'
76
+ try {
77
+ manifest ??= env.fetchJson(manifestUrl)
78
+ const built = await manifest
79
+ const url = built.modules[name]
80
+ if (!url) throw new Error(`no browser code was built for it`)
81
+ const props = JSON.parse(
82
+ element.querySelector(':scope > script[type="application/json"]')?.textContent || '{}',
83
+ ) as Record<string, unknown>
84
+ const mode = element.dataset.children
85
+ const childrenHtml =
86
+ mode === 'template'
87
+ ? (element.querySelector(':scope > template[data-children]')?.innerHTML ?? null)
88
+ : mode === 'inline'
89
+ ? shownHtml(element)
90
+ : null
91
+ const module = await load(url)
92
+ if (element.dataset.kind === 'mount') {
93
+ const mountIt = module.default as (target: unknown, props: unknown) => unknown
94
+ element.replaceChildren()
95
+ await mountIt(element, props)
96
+ return
97
+ }
98
+ if (!built.react) throw new Error('the React mount module was not built')
99
+ const react = await load(built.react)
100
+ const component = module[element.dataset.export ?? 'default']
101
+ if (typeof component !== 'function')
102
+ throw new Error(`it has no export "${element.dataset.export}"`)
103
+ ;(react.mount as (c: unknown, e: unknown, p: unknown, h: string | null) => void)(
104
+ component,
105
+ element,
106
+ props,
107
+ childrenHtml,
108
+ )
109
+ } catch (error) {
110
+ // Its fallback stays; nothing else on the page is touched.
111
+ env.console.error(`The island ${name} could not load:`, error)
112
+ }
113
+ }
114
+
115
+ const islands = env.document.querySelectorAll('crombolo-island')
116
+ let observer: InstanceType<NonNullable<LoaderEnvironment['IntersectionObserver']>> | undefined
117
+ for (let i = 0; i < islands.length; i++) {
118
+ const element = islands[i] as IslandElement
119
+ const when = element.dataset.load
120
+ if (when === 'load') void mount(element)
121
+ else if (when === 'idle') {
122
+ const later = () => void mount(element)
123
+ if (env.requestIdleCallback) env.requestIdleCallback(later)
124
+ else env.setTimeout(later, 200)
125
+ } else if (env.IntersectionObserver) {
126
+ observer ??= new env.IntersectionObserver(
127
+ (entries) => {
128
+ for (const entry of entries)
129
+ if (entry.isIntersecting) {
130
+ observer?.unobserve(entry.target)
131
+ void mount(entry.target as IslandElement)
132
+ }
133
+ },
134
+ { rootMargin: '200px' },
135
+ )
136
+ observer.observe(element)
137
+ } else void mount(element)
138
+ }
139
+ }
140
+
141
+ /** The script `/crombolo/islands.js` serves. */
142
+ export const ISLAND_LOADER_SCRIPT = `/* crombolo islands (story 209) */
143
+ (${islandLoader.toString()})({
144
+ document,
145
+ importModule: (url) => import(url),
146
+ fetchJson: (url) => fetch(url).then((r) => { if (!r.ok) throw new Error(r.status + ' for ' + url); return r.json() }),
147
+ IntersectionObserver: window.IntersectionObserver,
148
+ requestIdleCallback: window.requestIdleCallback ? window.requestIdleCallback.bind(window) : undefined,
149
+ setTimeout: window.setTimeout.bind(window),
150
+ console,
151
+ })
152
+ `