brumate 0.2.0 → 0.4.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.
- package/README.md +2 -2
- package/check.d.ts +49 -0
- package/dist/{boot-D-IdPy7B.d.ts → boot-DLlRmD9z.d.ts} +11 -10
- package/dist/cli.js +275 -15
- package/dist/cli.js.map +1 -1
- package/dist/client-BvDsC6Qr.js +3463 -0
- package/dist/client-BvDsC6Qr.js.map +1 -0
- package/dist/client-DBwL2wKQ.d.ts +669 -0
- package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
- package/dist/client-routes-BtGpYCef.js.map +1 -0
- package/dist/{cookies-Av5WFmcf.js → cookies-Cnbf4w-S.js} +15 -7
- package/dist/cookies-Cnbf4w-S.js.map +1 -0
- package/dist/{defer-D0bo1Gqx.js → defer-CKWZLv2K.js} +8 -4
- package/dist/defer-CKWZLv2K.js.map +1 -0
- package/dist/devtools-4uTPwR_v.js +597 -0
- package/dist/devtools-4uTPwR_v.js.map +1 -0
- package/dist/devtools-panel-Be9pxYgv.js +1994 -0
- package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
- package/dist/events-LgLdp1R7.js +114 -0
- package/dist/events-LgLdp1R7.js.map +1 -0
- package/dist/features-CHY5Ekku.js +30 -0
- package/dist/features-CHY5Ekku.js.map +1 -0
- package/dist/files-WW4RlajL.js +506 -0
- package/dist/files-WW4RlajL.js.map +1 -0
- package/dist/forms-j1xPAR14.d.ts +281 -0
- package/dist/forms-nXK7-Lv_.js +440 -0
- package/dist/forms-nXK7-Lv_.js.map +1 -0
- package/dist/highlight.d.ts +17 -0
- package/dist/highlight.js +278 -0
- package/dist/highlight.js.map +1 -0
- package/dist/html-BtKRyi7g.js +305 -0
- package/dist/html-BtKRyi7g.js.map +1 -0
- package/dist/html-Bw9Qwu6F.d.ts +107 -0
- package/dist/index.d.ts +142 -11
- package/dist/index.js +641 -106
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BJtACnQp.js → inspect-Y6y4uNZp.js} +4333 -681
- package/dist/inspect-Y6y4uNZp.js.map +1 -0
- package/dist/{loader-B18i3_-T.js → loader-BjKGJzLN.js} +21 -14
- package/dist/loader-BjKGJzLN.js.map +1 -0
- package/dist/logo-DQ_OYhBi.js +10 -0
- package/dist/logo-DQ_OYhBi.js.map +1 -0
- package/dist/{navigate-BwuZveDF.js → navigate-CfOr-TRF.js} +130 -24
- package/dist/navigate-CfOr-TRF.js.map +1 -0
- package/dist/nesting-DA5vJw9X.js +265 -0
- package/dist/nesting-DA5vJw9X.js.map +1 -0
- package/dist/produce-B7X9ori9.js +402 -0
- package/dist/produce-B7X9ori9.js.map +1 -0
- package/dist/produce-DIgHBVwL.d.ts +148 -0
- package/dist/{rpc-B-Zkn6Ch.js → rpc-Q-XkLwFh.js} +28 -13
- package/dist/rpc-Q-XkLwFh.js.map +1 -0
- package/dist/runtime/batch.js +9 -7
- package/dist/runtime/batch.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +4 -4
- package/dist/runtime/devtools.d.ts +172 -5
- package/dist/runtime/devtools.js +3 -1
- package/dist/runtime/env.js +14 -2
- package/dist/runtime/env.js.map +1 -1
- package/dist/runtime/events.d.ts +38 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/forms.d.ts +2 -0
- package/dist/runtime/forms.js +1 -0
- package/dist/runtime/gather.d.ts +25 -0
- package/dist/runtime/gather.js +33 -0
- package/dist/runtime/gather.js.map +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +5 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +4 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +5 -4
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +75 -2
- package/dist/runtime/signals.js +44 -2
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +18 -3
- package/dist/runtime/testing.js +150 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/runtime/values.d.ts +2 -0
- package/dist/runtime/values.js +24 -0
- package/dist/runtime/values.js.map +1 -0
- package/dist/{server-BA9SJ2Vm.d.ts → server-BvPIg9pT.d.ts} +363 -32
- package/dist/{server-BqfM95r1.js → server-DjyOVJtJ.js} +1309 -220
- package/dist/server-DjyOVJtJ.js.map +1 -0
- package/dist/{static-loader-BzE9SRaj.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
- package/dist/static-loader-BZR17hSw.js +312 -0
- package/dist/static-loader-BZR17hSw.js.map +1 -0
- package/dist/{stream-JaMHMdBD.js → stream-BP5AVmg5.js} +182 -17
- package/dist/stream-BP5AVmg5.js.map +1 -0
- package/dist/values-B8C7CLvG.d.ts +63 -0
- package/dist/vite.d.ts +20 -20
- package/dist/vite.js +2031 -539
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +951 -0
- package/forms/forms.brm.ts +141 -0
- package/package.json +41 -3
- package/skills/brumate/SKILL.md +58 -0
- package/skills/brumate/references/errors.md +2078 -0
- package/skills/brumate/references/events.md +117 -0
- package/skills/brumate/references/signals.md +61 -0
- package/skills/brumate/references/state.md +235 -0
- package/skills/brumate/references/syntax.md +250 -0
- package/types.d.ts +4 -4
- package/dist/client-C0UCNL3J.js +0 -1643
- package/dist/client-C0UCNL3J.js.map +0 -1
- package/dist/client-MD0ZmcFR.d.ts +0 -354
- package/dist/client-routes-JTbGtukf.js.map +0 -1
- package/dist/cookies-Av5WFmcf.js.map +0 -1
- package/dist/defer-D0bo1Gqx.js.map +0 -1
- package/dist/devtools-C50VH8gZ.js +0 -113
- package/dist/devtools-C50VH8gZ.js.map +0 -1
- package/dist/devtools-panel-AYjfwPhj.js +0 -435
- package/dist/devtools-panel-AYjfwPhj.js.map +0 -1
- package/dist/events-BKWRqtMg.js +0 -52
- package/dist/events-BKWRqtMg.js.map +0 -1
- package/dist/files-Bnn1JqHx.js +0 -192
- package/dist/files-Bnn1JqHx.js.map +0 -1
- package/dist/html-bHZbkK-h.js +0 -170
- package/dist/html-bHZbkK-h.js.map +0 -1
- package/dist/html-y1q7-t7D.d.ts +0 -60
- package/dist/inspect-BJtACnQp.js.map +0 -1
- package/dist/loader-B18i3_-T.js.map +0 -1
- package/dist/navigate-BwuZveDF.js.map +0 -1
- package/dist/produce-CWfJ4byV.js +0 -167
- package/dist/produce-CWfJ4byV.js.map +0 -1
- package/dist/produce-D4K7qpaL.d.ts +0 -72
- package/dist/rpc-B-Zkn6Ch.js.map +0 -1
- package/dist/server-BqfM95r1.js.map +0 -1
- package/dist/static-loader-DOygOFj5.js +0 -216
- package/dist/static-loader-DOygOFj5.js.map +0 -1
- package/dist/stream-JaMHMdBD.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../../src/runtime/nodes.ts","../../src/runtime/testing.ts"],"sourcesContent":["// Finds where whole nodes end in markup that arrives in pieces.\n\nconst VOID = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * The end of the last whole node at the top level of markup that streams in,\n * so a chunk that ends inside a tag, the text of a script or a template\n * waits for the rest. A `>` in an attribute or a script does not end a node.\n */\nexport function wholeNodes(markup: string): number {\n const tag = /<(\\/?)([a-zA-Z][\\w-]*)(?:[^>\"']|\"[^\"]*\"|'[^']*')*>/g;\n const lower = markup.toLowerCase();\n let depth = 0;\n let end = 0;\n let match: RegExpExecArray | null;\n while ((match = tag.exec(markup))) {\n const [whole, closing, name] = match;\n const element = name!.toLowerCase();\n if (!closing && element === 'script') {\n // The text of a script is not markup, and ends only at `</script`.\n const close = lower.indexOf('</script', tag.lastIndex);\n const after = close < 0 ? -1 : markup.indexOf('>', close);\n if (after < 0) {\n return end;\n }\n tag.lastIndex = after + 1;\n } else if (!VOID.has(element) && !whole.endsWith('/>')) {\n depth += closing ? -1 : 1;\n }\n if (depth === 0) {\n end = tag.lastIndex;\n }\n }\n return end;\n}\n","// Renders a component on the server and resumes it in the DOM of a test, as\n// a page does: the HTML and the state first, then the loader, which loads\n// client code when an event fires. `visit` does the same for a route, with\n// the requests of the page answered by the routes of the app.\n\nimport type { ClientModule } from './client.ts';\nimport { start } from './loader.ts';\nimport { wholeNodes } from './nodes.ts';\nimport { handleRequest, render } from './server.ts';\nimport type { Component, EntryMiddleware, RenderOptions } from './server.ts';\n\n/** The middleware of files of server functions, by function ID. */\ntype FileMiddleware = Record<string, EntryMiddleware>;\n\nexport interface TestingOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n}\n\n/** What a test does with the page, as a user does. */\nexport interface Actions {\n /** The first element that matches a selector. Throws if none does. */\n get: (selector: string) => HTMLElement;\n /** The text of the first element that matches a selector. */\n text: (selector: string) => string;\n /** Clicks an element. */\n click: (selector: string) => void;\n /** Types a value into a field, and fires `input`. */\n input: (selector: string, value: string) => void;\n /** Submits a form, as its submit button does. */\n submit: (selector: string) => void;\n /**\n * Retries an assertion until it passes. The first event of a test loads\n * client code, so its effects arrive a moment later.\n */\n waitFor: (assertion: () => void, timeout?: number) => Promise<void>;\n}\n\nexport interface Mounted extends Actions {\n /** The element that holds the component. */\n container: HTMLElement;\n /** Stops the loader and removes the component. */\n unmount: () => void;\n}\n\n/** The actions on the elements inside `root`. */\nfunction actions(root: ParentNode): Actions {\n const get = (selector: string): HTMLElement => {\n const element = root.querySelector<HTMLElement>(selector);\n if (!element) {\n throw new Error(`No element matches ${selector}`);\n }\n return element;\n };\n return {\n get,\n text: (selector) => get(selector).textContent ?? '',\n click: (selector) => get(selector).click(),\n input: (selector, value) => {\n const field = get(selector) as HTMLInputElement;\n field.value = value;\n field.dispatchEvent(new Event('input', { bubbles: true }));\n },\n submit: (selector) => {\n get(selector).dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));\n },\n waitFor: async (assertion, timeout = 2000) => {\n const until = Date.now() + timeout;\n for (;;) {\n try {\n assertion();\n return;\n } catch (error) {\n if (Date.now() > until) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- It waits between tries.\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n },\n };\n}\n\n/**\n * Runs an inline script, as a browser does when it adds one. The DOM of a\n * test does not run scripts. The script is `document.currentScript` while it\n * runs, so a state record hands its script to the core.\n */\nfunction run(script: Element): void {\n Object.defineProperty(document, 'currentScript', { configurable: true, value: script });\n try {\n // oxlint-disable-next-line no-eval -- The script is a state record or the swap code from the server.\n (0, eval)(script.textContent!);\n } finally {\n delete (document as { currentScript?: unknown }).currentScript;\n }\n}\n\n/**\n * Appends markup that streams in later, such as a `#loading` body, and runs\n * its inline scripts in order.\n */\nfunction append(container: HTMLElement, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n // A copy, because appending moves nodes out of the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const node of [...template.content.childNodes]) {\n container.append(node);\n if (node.nodeName === 'SCRIPT' && !(node as Element).hasAttribute('type')) {\n run(node as Element);\n }\n }\n}\n\n/** Renders a component on the server and resumes it in the document of a test. */\nexport type Mount = <P>(\n component: Component<P>,\n props: P,\n renderOptions?: RenderOptions,\n) => Promise<Mounted>;\n\n/** Mounts so far, so each starts its scope IDs at a number of its own. */\nlet mounts = 0;\n/** The loader that the mounts of the document share, and how many mounts use it. */\nlet loader: { stop: () => void; users: number } | undefined;\n\n/** Returns `mount`, which loads client modules with `options.load`. */\nexport function createMount(options: TestingOptions): Mount {\n /**\n * Renders a component on the server, puts it in the document with its\n * state, and starts the loader. Markup that streams in later is added as\n * it arrives.\n */\n return async function mount<P>(\n component: Component<P>,\n props: P,\n renderOptions: RenderOptions = {},\n ): Promise<Mounted> {\n // IDs of their own, so two mounts in a file do not share scopes or state references.\n const base = renderOptions.base ?? ++mounts * 1_000_000;\n const { html, state, pending } = await render(component, props, { ...renderOptions, base });\n const container = document.createElement('div');\n container.innerHTML = html + state;\n document.body.append(container);\n // The page state, which waits for the core.\n container.querySelectorAll('script[b-state]').forEach(run);\n // One loader for the document, as a page has, however many mounts are in it.\n loader ??= {\n stop: start({ load: options.load, rpc: options.rpc, navigate: false, preload: false }),\n users: 0,\n };\n loader.users++;\n let mounted = true;\n const stop = (): void => {\n if (!mounted || !loader) {\n return;\n }\n mounted = false;\n if (--loader.users === 0) {\n loader.stop();\n loader = undefined;\n }\n };\n void (async () => {\n for await (const chunk of pending) {\n append(container, chunk);\n }\n })();\n return {\n container,\n ...actions(container),\n unmount: () => {\n stop();\n container.remove();\n // The core forgets the scopes of this mount, so a refresh later does not load its memos.\n void import('./client.ts').then((core) => core.removeRoot(String(base)));\n },\n };\n };\n}\n\n/** Server functions by ID, as `functions` of `virtual:brumate/server` has them. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport type ServerFunctions = Record<string, (...args: any[]) => unknown>;\n\nexport interface AnswerOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** Called with the ID of each call, such as `issues_1a2b#toggleStar`, before it runs. */\n onCall?: (id: string) => void;\n /** The middleware of the entry, which runs before each call. `virtual:brumate/testing` passes the app's. */\n middleware?: EntryMiddleware;\n /**\n * The middleware of each `'use server'` file, by function ID, or a\n * function that imports them. `virtual:brumate/testing` passes them.\n */\n fileMiddleware?: FileMiddleware | (() => Promise<FileMiddleware>);\n}\n\n/** What `run` of `AsyncLocalStorage` looks like, the part that `answerCalls` uses. */\ninterface Storage {\n run: <T>(store: string, callback: () => T) => T;\n getStore: () => string | undefined;\n}\n\nlet storage: Promise<Storage | undefined> | undefined;\n\n/**\n * Tells the calls that a server function makes while it is answered. Node\n * has `AsyncLocalStorage`. Elsewhere, such as in a browser, there is none,\n * and nested calls are not told apart.\n */\nfunction callStorage(): Promise<Storage | undefined> {\n storage ??= import('node:async_hooks').then(\n ({ AsyncLocalStorage }) => new AsyncLocalStorage<string>() as Storage,\n () => undefined,\n );\n return storage;\n}\n\n/**\n * Answers the server function calls of the page in the test, with\n * `functions`, through the same request and answer as a server. Calls go\n * through `fetch`, so it replaces `fetch` until the returned function\n * restores it. Other requests go to the `fetch` from before.\n *\n * `functions` can be a function that returns them, so they are imported on\n * the first call. A server function that calls a server function through\n * `fetch`, as a browser stub does, throws: it would call itself without end.\n */\nexport function answerCalls(\n functions: ServerFunctions | (() => Promise<ServerFunctions>),\n options: AnswerOptions = {},\n): () => void {\n const prefix = options.rpc ?? '/_brumate';\n const original = globalThis.fetch;\n let loaded: Promise<ServerFunctions> | undefined;\n /** The error of a call that a server function made through `fetch`. */\n let failure: Error | undefined;\n const answer = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = globalThis.location?.href ?? 'http://localhost/';\n const url = new URL(input instanceof Request ? input.url : String(input), base);\n if (!url.pathname.startsWith(`${prefix}/`)) {\n return original(input, init);\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n const calls = await callStorage();\n const caller = calls?.getStore();\n if (caller !== undefined) {\n // The outer call answers with a generic error, so the error goes to its caller too.\n failure ??= new Error(\n `The server function \"${caller}\" called \"${id}\" through fetch, as a browser stub does. In a test, server code imports the server code of a 'use server' file: import components with ?brumate-server, and answer calls with the functions of virtual:brumate/server`,\n );\n throw failure;\n }\n options.onCall?.(id);\n loaded ??= Promise.resolve(typeof functions === 'function' ? functions() : functions);\n const registry = await loaded;\n const request = input instanceof Request ? new Request(input, init) : new Request(url, init);\n const guards = options.fileMiddleware;\n const fileMiddleware = typeof guards === 'function' ? await guards() : guards;\n const handle = (): Promise<Response | undefined> =>\n handleRequest(registry, request, prefix, { middleware: options.middleware, fileMiddleware });\n const response = await (calls ? calls.run(id, handle) : handle());\n if (failure) {\n const error = failure;\n failure = undefined;\n throw error;\n }\n return response ?? original(input, init);\n };\n globalThis.fetch = answer as typeof fetch;\n return () => {\n // A later `answerCalls` or stub keeps its own `fetch`.\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n };\n}\n\n/** Answers a request as the server of the app does, or undefined when nothing does. */\nexport type RequestHandler = (request: Request) => Promise<Response | undefined>;\n\nexport interface VisitorOptions extends TestingOptions {\n /** Answers the requests for pages, forms without scripts, `#defer` bodies and endpoints. */\n routes: () => Promise<RequestHandler>;\n /** Answers server function calls. */\n calls: () => Promise<RequestHandler>;\n}\n\nexport interface VisitOptions {\n /** Cookies that the browser has before the first request, by name. */\n cookies?: Record<string, string>;\n /** Headers of every request, such as `accept-language`. */\n headers?: HeadersInit;\n}\n\nexport interface Visited extends Actions {\n /** The path and the query of the page, such as `/issues?q=bug`. It changes with client navigation. */\n readonly url: string;\n /** The status of the first page. */\n status: number;\n /** The cookies that the browser has now, by name. */\n readonly cookies: Record<string, string>;\n /** Stops the loader, puts `fetch` back and empties the document. */\n close: () => void;\n}\n\n/** Visits a path of the app, as a browser that runs scripts does. */\nexport type Visit = (path: string, options?: VisitOptions) => Promise<Visited>;\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Reads the `set-cookie` headers of a response into the cookies of the browser. */\nfunction storeCookies(jar: Map<string, string>, response: Response): void {\n for (const header of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = header.split(';');\n const equals = pair.indexOf('=');\n const name = pair.slice(0, equals).trim();\n if (equals < 1) {\n continue;\n }\n const gone = attributes.some((attribute) => {\n const [key = '', value = ''] = attribute.trim().split('=');\n const lower = key.toLowerCase();\n return (\n (lower === 'max-age' && Number(value) <= 0) ||\n (lower === 'expires' && Date.parse(value) <= Date.now())\n );\n });\n if (gone) {\n jar.delete(name);\n } else {\n jar.set(name, pair.slice(equals + 1).trim());\n }\n }\n}\n\n/** The page that a visit holds, so a new visit closes the one before. */\nlet visited: Visited | undefined;\n\n/** Returns `visit`, which answers the requests of the page with the routes of the app. */\nexport function createVisit(options: VisitorOptions): Visit {\n const prefix = options.rpc ?? '/_brumate';\n /**\n * Answers the path with the routes of the app, puts the page in the\n * document, and starts the loader with client navigation. Links, forms,\n * server function calls and `#defer` requests of the page go to the same\n * routes, without a server, with the cookies that the answers set.\n */\n return async function visit(path, visitOptions = {}) {\n visited?.close();\n const jar = new Map(Object.entries(visitOptions.cookies ?? {}));\n const original = globalThis.fetch;\n const origin = location.origin;\n history.replaceState(null, '', new URL(path, origin));\n\n // A browser follows redirects, sends its cookies, and keeps the ones that the answers set.\n const answer = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n let url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== origin) {\n return original(input, init);\n }\n let method = (\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n ).toUpperCase();\n let body = init?.body ?? undefined;\n const extra = new Headers(input instanceof Request ? input.headers : undefined);\n new Headers(init?.headers).forEach((value, name) => extra.set(name, value));\n for (let hops = 0; ; hops++) {\n const request = new Request(url, { method, body, signal: init?.signal ?? null });\n // Set after the request is made, since a DOM environment drops these from its init.\n new Headers(visitOptions.headers).forEach((value, name) =>\n request.headers.set(name, value),\n );\n extra.forEach((value, name) => request.headers.set(name, value));\n if (jar.size > 0) {\n request.headers.set(\n 'cookie',\n [...jar].map(([name, value]) => `${name}=${value}`).join('; '),\n );\n }\n if (method !== 'GET' && method !== 'HEAD') {\n request.headers.set('origin', origin);\n }\n const handle = url.pathname.startsWith(`${prefix}/`) ? options.calls : options.routes;\n const answered = handle().then((handler) => handler(request));\n // oxlint-disable-next-line no-await-in-loop -- Each redirect is a request of its own.\n const response = (await answered) ?? new Response('Not found', { status: 404 });\n storeCookies(jar, response);\n const location = response.headers.get('location');\n if (!REDIRECTS.has(response.status) || !location || init?.redirect === 'manual') {\n Object.defineProperty(response, 'url', { value: url.href });\n return response;\n }\n if (hops === 20) {\n throw new TypeError(`Too many redirects from ${path}`);\n }\n url = new URL(location, url);\n // As in fetch: 303 asks for the page with GET, and so do 301 and 302 after a POST.\n // 307 and 308 send the request again as it was.\n if (\n (response.status === 303 && method !== 'HEAD') ||\n (method === 'POST' && (response.status === 301 || response.status === 302))\n ) {\n method = 'GET';\n body = undefined;\n extra.delete('content-type');\n }\n }\n };\n globalThis.fetch = answer as typeof fetch;\n\n // The DOM of a test does not run scripts, so the ones that the page adds run here, once each.\n const ran = new WeakSet<Element>();\n const runOnce = (script: Element): void => {\n if (!ran.has(script) && !script.hasAttribute('src') && !script.hasAttribute('type')) {\n ran.add(script);\n run(script);\n }\n };\n const scripts = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeName === 'SCRIPT') {\n runOnce(node as Element);\n } else if (node instanceof Element) {\n node.querySelectorAll('script').forEach(runOnce);\n }\n }\n }\n });\n\n const response = await answer(path);\n // The page is at the URL of the last redirect.\n history.replaceState(null, '', response.url);\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n let html = '';\n let end = -1;\n let done = false;\n while (end < 0 && !done) {\n // oxlint-disable-next-line no-await-in-loop -- The page arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n html += chunk.value ?? '';\n end = html.search(/<\\/html>/i);\n }\n const cut = end < 0 ? html.length : end + '</html>'.length;\n const page = new DOMParser().parseFromString(html.slice(0, cut), 'text/html');\n for (const name of document.documentElement.getAttributeNames()) {\n document.documentElement.removeAttribute(name);\n }\n for (const attribute of page.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n document.head.replaceChildren(\n ...[...page.head.childNodes].map((node) => document.importNode(node, true)),\n );\n document.body.replaceChildren(\n ...[...page.body.childNodes].map((node) => document.importNode(node, true)),\n );\n document.querySelectorAll('script').forEach(runOnce);\n scripts.observe(document, { childList: true, subtree: true });\n\n const stop = start({ load: options.load, rpc: prefix, navigate: true, preload: false });\n let rest = html.slice(cut);\n let open = true;\n void (async () => {\n while (!done) {\n // oxlint-disable-next-line no-await-in-loop -- Later markup arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n rest += chunk.value ?? '';\n // A chunk can end inside a tag, a script or a template, so only whole nodes move in.\n const last = done ? rest.length : wholeNodes(rest);\n if (last > 0 && open) {\n // The observer runs its scripts.\n const template = document.createElement('template');\n template.innerHTML = rest.slice(0, last);\n document.body.append(template.content);\n rest = rest.slice(last);\n }\n }\n })();\n\n const current: Visited = {\n ...actions(document),\n get url() {\n return location.pathname + location.search;\n },\n status: response.status,\n get cookies() {\n return Object.fromEntries(jar);\n },\n close: () => {\n if (!open) {\n return;\n }\n open = false;\n visited = undefined;\n stop();\n scripts.disconnect();\n reader.cancel().catch(() => {});\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n // The core forgets the page, so the next visit starts its IDs again.\n void import('./client.ts').then((core) => core.leavePage());\n document.head.replaceChildren();\n document.body.replaceChildren();\n },\n };\n visited = current;\n return current;\n };\n}\n"],"mappings":";;;AAEA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,WAAW,QAAwB;CACjD,MAAM,MAAM;CACZ,MAAM,QAAQ,OAAO,YAAY;CACjC,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,IAAI;CACJ,OAAQ,QAAQ,IAAI,KAAK,MAAM,GAAI;EACjC,MAAM,CAAC,OAAO,SAAS,QAAQ;EAC/B,MAAM,UAAU,KAAM,YAAY;EAClC,IAAI,CAAC,WAAW,YAAY,UAAU;GAEpC,MAAM,QAAQ,MAAM,QAAQ,aAAY,IAAI,SAAS;GACrD,MAAM,QAAQ,QAAQ,IAAI,KAAK,OAAO,QAAQ,KAAK,KAAK;GACxD,IAAI,QAAQ,GACV,OAAO;GAET,IAAI,YAAY,QAAQ;EAC1B,OA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ACX,IAAI,CAAC,MACH;IAEF,OAAO;IACP,UAAU,KAAA;IACV,KAAK;IACL,QAAQ,WAAW;IACnB,OAAO,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;IAC9B,IAAI,WAAW,UAAU,QACvB,WAAW,QAAQ;IAGrB,OAAY,cAAc,CAAC,MAAM,SAAS,KAAK,UAAU,CAAC;IAC1D,SAAS,KAAK,gBAAgB;IAC9B,SAAS,KAAK,gBAAgB;GAChC;EACF;EACA,UAAU;EACV,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../../src/runtime/nodes.ts","../../src/runtime/testing.ts"],"sourcesContent":["// Finds where whole nodes end in markup that arrives in pieces.\n\nconst VOID = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * The end of the last whole node at the top level of markup that streams in,\n * so a chunk that ends inside a tag, the text of a script or a template\n * waits for the rest. A `>` in an attribute or a script does not end a node.\n */\nexport function wholeNodes(markup: string): number {\n const tag = /<(\\/?)([a-zA-Z][\\w-]*)(?:[^>\"']|\"[^\"]*\"|'[^']*')*>/g;\n const lower = markup.toLowerCase();\n let depth = 0;\n let end = 0;\n let match: RegExpExecArray | null;\n while ((match = tag.exec(markup))) {\n const [whole, closing, name] = match;\n const element = name!.toLowerCase();\n if (!closing && element === 'script') {\n // The text of a script is not markup, and ends only at `</script`.\n const close = lower.indexOf('</script', tag.lastIndex);\n const after = close < 0 ? -1 : markup.indexOf('>', close);\n if (after < 0) {\n return end;\n }\n tag.lastIndex = after + 1;\n } else if (!VOID.has(element) && !whole.endsWith('/>')) {\n depth += closing ? -1 : 1;\n }\n if (depth === 0) {\n end = tag.lastIndex;\n }\n }\n return end;\n}\n","// Renders a component on the server and resumes it in the DOM of a test, as\n// a page does: the HTML and the state first, then the loader, which loads\n// client code when an event fires. `visit` does the same for a route, with\n// the requests of the page answered by the routes of the app.\n//\n// The triggers of `$client`, `#client` and `#defer` fire as follows:\n// - 'load' fires when the loader starts.\n// - 'visible' fires when the IntersectionObserver that `mount` and `visit`\n// install reports the element, which it does at once unless the test keeps\n// the element out of view.\n// - 'idle' fires as in a browser that has no requestIdleCallback, which\n// includes happy-dom: on a timer after the page starts. The loader decides\n// this, so a test needs no action for it.\n\nimport type { ClientModule } from './client.ts';\nimport { start } from './loader.ts';\nimport { wholeNodes } from './nodes.ts';\nimport { handleRequest, render } from './server.ts';\nimport type { Component, EntryMiddleware, RenderOptions } from './server.ts';\n\n/** The middleware of files of server functions, by function ID. */\ntype FileMiddleware = Record<string, EntryMiddleware>;\n\nexport interface TestingOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n}\n\n/** What a test does with the page, as a user does. */\nexport interface Actions {\n /** The first element that matches a selector. Throws if none does. */\n get: (selector: string) => HTMLElement;\n /** The text of the first element that matches a selector. */\n text: (selector: string) => string;\n /** Clicks an element. */\n click: (selector: string) => void;\n /** Types a value into a field, and fires `input`. */\n input: (selector: string, value: string) => void;\n /** Submits a form, as its submit button does. */\n submit: (selector: string) => void;\n /**\n * Brings the elements that match a selector into view, so what waits for\n * them with the 'visible' trigger runs. See `offscreen`.\n */\n reveal: (selector: string) => void;\n /**\n * Retries an assertion until it passes. The first event of a test loads\n * client code, so its effects arrive a moment later.\n */\n waitFor: (assertion: () => void, timeout?: number) => Promise<void>;\n}\n\nexport interface Mounted extends Actions {\n /** The element that holds the component. */\n container: HTMLElement;\n /** Stops the loader and removes the component. */\n unmount: () => void;\n}\n\n/** The elements that the test keeps out of view, and the observers that wait for them. */\ninterface View {\n /** The selectors of `offscreen`, one entry for each mount or visit. */\n hidden: Set<{ selector: string }>;\n /** The elements that the test brought into view. */\n revealed: WeakSet<Element>;\n /** Reports an element to the observers that wait for it, as visible. */\n waiting: Set<{ element: Element; report: () => void }>;\n users: number;\n original: typeof IntersectionObserver | undefined;\n}\n\nlet view: View | undefined;\n\n/** Reports an element that waits out of view, as visible. */\nfunction reveal(element: Element): void {\n view?.revealed.add(element);\n for (const entry of view?.waiting ?? []) {\n if (entry.element === element) {\n view!.waiting.delete(entry);\n entry.report();\n }\n }\n}\n\n/**\n * Replaces the IntersectionObserver of the environment with one that reports\n * each element it observes as visible, except the ones that match a selector\n * of `offscreen`. happy-dom has an observer that never reports. Returns what\n * puts the observer of the environment back.\n */\nfunction watchView(offscreen: string | undefined): () => void {\n if (!view) {\n const current: View = {\n hidden: new Set(),\n revealed: new WeakSet(),\n waiting: new Set(),\n users: 0,\n original: globalThis.IntersectionObserver,\n };\n class Reporting {\n readonly #callback: IntersectionObserverCallback;\n readonly #entries = new Set<{ element: Element; report: () => void }>();\n readonly root = null;\n readonly rootMargin = '0px';\n readonly thresholds = [0];\n constructor(callback: IntersectionObserverCallback) {\n this.#callback = callback;\n }\n observe(element: Element): void {\n const report = (): void => {\n const rect = element.getBoundingClientRect();\n this.#callback(\n [\n {\n target: element,\n isIntersecting: true,\n intersectionRatio: 1,\n boundingClientRect: rect,\n intersectionRect: rect,\n rootBounds: null,\n time: performance.now(),\n },\n ],\n this as unknown as IntersectionObserver,\n );\n };\n const entry = { element, report };\n this.#entries.add(entry);\n let isHidden = false;\n if (!current.revealed.has(element)) {\n for (const { selector } of current.hidden) {\n if (element.matches(selector)) {\n isHidden = true;\n break;\n }\n }\n }\n if (isHidden) {\n current.waiting.add(entry);\n } else {\n queueMicrotask(() => {\n if (this.#entries.has(entry)) {\n report();\n }\n });\n }\n }\n unobserve(element: Element): void {\n for (const entry of this.#entries) {\n if (entry.element === element) {\n this.#entries.delete(entry);\n current.waiting.delete(entry);\n }\n }\n }\n disconnect(): void {\n for (const entry of this.#entries) {\n current.waiting.delete(entry);\n }\n this.#entries.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n globalThis.IntersectionObserver = Reporting as unknown as typeof IntersectionObserver;\n view = current;\n }\n const current = view;\n current.users++;\n // One entry for each user, so two mounts that keep out the same selector do not clear each other.\n const hidden = { selector: offscreen ?? '' };\n if (offscreen !== undefined) {\n current.hidden.add(hidden);\n }\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n current.hidden.delete(hidden);\n if (--current.users === 0) {\n if (current.original) {\n globalThis.IntersectionObserver = current.original;\n } else {\n delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n }\n current.waiting.clear();\n view = undefined;\n }\n };\n}\n\n/** The actions on the elements inside `root`. */\nfunction actions(root: ParentNode): Actions {\n function get(selector: string): HTMLElement {\n const element = root.querySelector<HTMLElement>(selector);\n if (!element) {\n throw new Error(`No element matches ${selector}`);\n }\n return element;\n }\n return {\n get,\n text: (selector) => get(selector).textContent ?? '',\n click: (selector) => get(selector).click(),\n input: (selector, value) => {\n const field = get(selector) as HTMLInputElement;\n field.value = value;\n field.dispatchEvent(new Event('input', { bubbles: true }));\n },\n submit: (selector) => {\n get(selector).dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));\n },\n reveal: (selector) => {\n for (const element of root.querySelectorAll(selector)) {\n reveal(element);\n }\n },\n waitFor: async (assertion, timeout = 2000) => {\n const until = Date.now() + timeout;\n for (;;) {\n try {\n assertion();\n return;\n } catch (error) {\n if (Date.now() > until) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- It waits between tries.\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n },\n };\n}\n\n/**\n * Runs an inline script, as a browser does when it adds one. The DOM of a\n * test does not run scripts. The script is `document.currentScript` while it\n * runs, so a state record hands its script to the core.\n */\nfunction run(script: Element): void {\n Object.defineProperty(document, 'currentScript', { configurable: true, value: script });\n try {\n // oxlint-disable-next-line no-eval -- The script is a state record or the swap code from the server.\n (0, eval)(script.textContent!);\n } finally {\n delete (document as { currentScript?: unknown }).currentScript;\n }\n}\n\n/**\n * Appends markup that streams in later, such as a `#loading` body, and runs\n * its inline scripts in order.\n */\nfunction append(container: HTMLElement, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n // A copy, because appending moves nodes out of the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const node of [...template.content.childNodes]) {\n container.append(node);\n if (node.nodeName === 'SCRIPT' && !(node as Element).hasAttribute('type')) {\n run(node as Element);\n }\n }\n}\n\n/** Renders a component on the server and resumes it in the document of a test. */\nexport type Mount = <P>(\n component: Component<P>,\n props: P,\n renderOptions?: MountRenderOptions,\n) => Promise<Mounted>;\n\n/** The options of `render`, and the elements to keep out of view. */\nexport interface MountRenderOptions extends RenderOptions {\n /**\n * A selector of elements that stay out of view, for a test of what waits\n * for them with the 'visible' trigger. `reveal` brings them into view.\n */\n offscreen?: string;\n}\n\n/** Mounts so far, so each starts its scope IDs at a number of its own. */\nlet mounts = 0;\n/** The loader that the mounts of the document share, and how many mounts use it. */\nlet loader: { stop: () => void; users: number } | undefined;\n\n/** Returns `mount`, which loads client modules with `options.load`. */\nexport function createMount(options: TestingOptions): Mount {\n /**\n * Renders a component on the server, puts it in the document with its\n * state, and starts the loader. Markup that streams in later is added as\n * it arrives.\n */\n return async function mount<P>(\n component: Component<P>,\n props: P,\n { offscreen, ...renderOptions }: MountRenderOptions = {},\n ): Promise<Mounted> {\n // IDs of their own, so two mounts in a file do not share scopes or state references.\n const base = renderOptions.base ?? ++mounts * 1_000_000;\n const { html, state, pending } = await render(component, props, { ...renderOptions, base });\n const unwatch = watchView(offscreen);\n const container = document.createElement('div');\n container.innerHTML = html + state;\n document.body.append(container);\n // The page state, which waits for the core.\n for (const script of container.querySelectorAll('script[b-state]')) {\n run(script);\n }\n // One loader for the document, as a page has, however many mounts are in it.\n loader ??= {\n stop: start({ load: options.load, rpc: options.rpc, navigate: false }),\n users: 0,\n };\n loader.users++;\n let mounted = true;\n function stop(): void {\n if (!mounted || !loader) {\n return;\n }\n mounted = false;\n unwatch();\n if (--loader.users === 0) {\n loader.stop();\n loader = undefined;\n }\n }\n void (async () => {\n for await (const chunk of pending) {\n append(container, chunk);\n }\n })();\n return {\n container,\n ...actions(container),\n unmount: () => {\n stop();\n container.remove();\n // The core forgets the scopes of this mount, so a refresh later does not load its memos.\n void import('./client.ts').then((core) => core.removeRoot(String(base)));\n },\n };\n };\n}\n\n/** Server functions by ID, as `functions` of `virtual:brumate/server` has them. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport type ServerFunctions = Record<string, (...args: any[]) => unknown>;\n\nexport interface AnswerOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** Called with the ID of each call, such as `issues_1a2b#toggleStar`, before it runs. */\n onCall?: (id: string) => void;\n /** The middleware of the entry, which runs before each call. `virtual:brumate/testing` passes the app's. */\n middleware?: EntryMiddleware;\n /**\n * The middleware of each `'use server'` file, by function ID, or a\n * function that imports them. `virtual:brumate/testing` passes them.\n */\n fileMiddleware?: FileMiddleware | (() => Promise<FileMiddleware>);\n}\n\n/** What `run` of `AsyncLocalStorage` looks like, the part that `answerCalls` uses. */\ninterface Storage {\n run: <T>(store: string, callback: () => T) => T;\n getStore: () => string | undefined;\n}\n\nlet storage: Promise<Storage | undefined> | undefined;\n\n/**\n * Tells the calls that a server function makes while it is answered. Node\n * has `AsyncLocalStorage`. Elsewhere, such as in a browser, there is none,\n * and nested calls are not told apart.\n */\nfunction callStorage(): Promise<Storage | undefined> {\n storage ??= import('node:async_hooks').then(\n ({ AsyncLocalStorage }) => new AsyncLocalStorage<string>() as Storage,\n () => undefined,\n );\n return storage;\n}\n\n/**\n * Answers the server function calls of the page in the test, with\n * `functions`, through the same request and answer as a server. Calls go\n * through `fetch`, so it replaces `fetch` until the returned function\n * restores it. Other requests go to the `fetch` from before.\n *\n * `functions` can be a function that returns them, so they are imported on\n * the first call. A server function that calls a server function through\n * `fetch`, as a browser stub does, throws: it would call itself without end.\n */\nexport function answerCalls(\n functions: ServerFunctions | (() => Promise<ServerFunctions>),\n options: AnswerOptions = {},\n): () => void {\n const prefix = options.rpc ?? '/_brumate';\n const original = globalThis.fetch;\n let loaded: Promise<ServerFunctions> | undefined;\n /** The error of a call that a server function made through `fetch`. */\n let failure: Error | undefined;\n async function answer(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const base = globalThis.location?.href ?? 'http://localhost/';\n const url = new URL(input instanceof Request ? input.url : String(input), base);\n if (!url.pathname.startsWith(`${prefix}/`)) {\n return original(input, init);\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n const calls = await callStorage();\n const caller = calls?.getStore();\n if (caller !== undefined) {\n // The outer call answers with a generic error, so the error goes to its caller too.\n failure ??= new Error(\n `The server function \"${caller}\" called \"${id}\" through fetch, as a browser stub does. In a test, server code imports the server code of a 'use server' file: import components with ?brumate-server, and answer calls with the functions of virtual:brumate/server`,\n );\n throw failure;\n }\n options.onCall?.(id);\n loaded ??= Promise.resolve(typeof functions === 'function' ? functions() : functions);\n const registry = await loaded;\n const request = input instanceof Request ? new Request(input, init) : new Request(url, init);\n const guards = options.fileMiddleware;\n const fileMiddleware = typeof guards === 'function' ? await guards() : guards;\n function handle(): Promise<Response | undefined> {\n return handleRequest(registry, request, prefix, {\n middleware: options.middleware,\n fileMiddleware,\n });\n }\n const response = await (calls ? calls.run(id, handle) : handle());\n if (failure) {\n const error = failure;\n failure = undefined;\n throw error;\n }\n return response ?? original(input, init);\n }\n globalThis.fetch = answer as typeof fetch;\n return () => {\n // A later `answerCalls` or stub keeps its own `fetch`.\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n };\n}\n\n/** Answers a request as the server of the app does, or undefined when nothing does. */\nexport type RequestHandler = (request: Request) => Promise<Response | undefined>;\n\nexport interface VisitorOptions extends TestingOptions {\n /** Answers the requests for pages, forms without scripts, `#defer` bodies and endpoints. */\n routes: () => Promise<RequestHandler>;\n /** Answers server function calls. */\n calls: () => Promise<RequestHandler>;\n}\n\nexport interface VisitOptions {\n /** Cookies that the browser has before the first request, by name. */\n cookies?: Record<string, string>;\n /** Headers of every request, such as `accept-language`. */\n headers?: HeadersInit;\n /** A selector of elements that stay out of view until `reveal` brings them in. */\n offscreen?: string;\n}\n\nexport interface Visited extends Actions {\n /** The path and the query of the page, such as `/issues?q=bug`. It changes with client navigation. */\n readonly url: string;\n /** The status of the first page. */\n status: number;\n /** The cookies that the browser has now, by name. */\n readonly cookies: Record<string, string>;\n /** Stops the loader, puts `fetch` back and empties the document. */\n close: () => void;\n}\n\n/** Visits a path of the app, as a browser that runs scripts does. */\nexport type Visit = (path: string, options?: VisitOptions) => Promise<Visited>;\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Reads the `set-cookie` headers of a response into the cookies of the browser. */\nfunction storeCookies(jar: Map<string, string>, response: Response): void {\n for (const header of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = header.split(';');\n const equals = pair.indexOf('=');\n const name = pair.slice(0, equals).trim();\n if (equals < 1) {\n continue;\n }\n let gone = false;\n for (const attribute of attributes) {\n const [key = '', value = ''] = attribute.trim().split('=');\n const lower = key.toLowerCase();\n if (\n (lower === 'max-age' && Number(value) <= 0) ||\n (lower === 'expires' && Date.parse(value) <= Date.now())\n ) {\n gone = true;\n break;\n }\n }\n if (gone) {\n jar.delete(name);\n } else {\n jar.set(name, pair.slice(equals + 1).trim());\n }\n }\n}\n\n/** The page that a visit holds, so a new visit closes the one before. */\nlet visited: Visited | undefined;\n\n/** Returns `visit`, which answers the requests of the page with the routes of the app. */\nexport function createVisit(options: VisitorOptions): Visit {\n const prefix = options.rpc ?? '/_brumate';\n /**\n * Answers the path with the routes of the app, puts the page in the\n * document, and starts the loader with client navigation. Links, forms,\n * server function calls and `#defer` requests of the page go to the same\n * routes, without a server, with the cookies that the answers set.\n */\n return async function visit(path, visitOptions = {}) {\n visited?.close();\n const jar = new Map(Object.entries(visitOptions.cookies ?? {}));\n const original = globalThis.fetch;\n const origin = location.origin;\n history.replaceState(null, '', new URL(path, origin));\n\n // A browser follows redirects, sends its cookies, and keeps the ones that the answers set.\n async function answer(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n let url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== origin) {\n return original(input, init);\n }\n let method = (\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n ).toUpperCase();\n let body = init?.body ?? undefined;\n const extra = new Headers(input instanceof Request ? input.headers : undefined);\n for (const [name, value] of new Headers(init?.headers)) {\n extra.set(name, value);\n }\n for (let hops = 0; ; hops++) {\n const request = new Request(url, { method, body, signal: init?.signal ?? null });\n // Set after the request is made, since a DOM environment drops these from its init.\n for (const [name, value] of new Headers(visitOptions.headers)) {\n request.headers.set(name, value);\n }\n for (const [name, value] of extra) {\n request.headers.set(name, value);\n }\n if (jar.size > 0) {\n const cookies: string[] = [];\n for (const [name, value] of jar) {\n cookies.push(`${name}=${value}`);\n }\n request.headers.set('cookie', cookies.join('; '));\n }\n if (method !== 'GET' && method !== 'HEAD') {\n request.headers.set('origin', origin);\n }\n const handle = url.pathname.startsWith(`${prefix}/`) ? options.calls : options.routes;\n const answered = handle().then((handler) => handler(request));\n // oxlint-disable-next-line no-await-in-loop -- Each redirect is a request of its own.\n const response = (await answered) ?? new Response('Not found', { status: 404 });\n storeCookies(jar, response);\n const location = response.headers.get('location');\n if (!REDIRECTS.has(response.status) || !location || init?.redirect === 'manual') {\n Object.defineProperty(response, 'url', { value: url.href });\n return response;\n }\n if (hops === 20) {\n throw new TypeError(`Too many redirects from ${path}`);\n }\n url = new URL(location, url);\n // As in fetch: 303 asks for the page with GET, and so do 301 and 302 after a POST.\n // 307 and 308 send the request again as it was.\n if (\n (response.status === 303 && method !== 'HEAD') ||\n (method === 'POST' && (response.status === 301 || response.status === 302))\n ) {\n method = 'GET';\n body = undefined;\n extra.delete('content-type');\n }\n }\n }\n globalThis.fetch = answer as typeof fetch;\n\n // The DOM of a test does not run scripts, so the ones that the page adds run here, once each.\n const ran = new WeakSet<Element>();\n function runOnce(script: Element): void {\n if (!ran.has(script) && !script.hasAttribute('src') && !script.hasAttribute('type')) {\n ran.add(script);\n run(script);\n }\n }\n const scripts = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeName === 'SCRIPT') {\n runOnce(node as Element);\n } else if (node instanceof Element) {\n for (const script of node.querySelectorAll('script')) {\n runOnce(script);\n }\n }\n }\n }\n });\n\n const response = await answer(path);\n // The page is at the URL of the last redirect.\n history.replaceState(null, '', response.url);\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n let html = '';\n let end = -1;\n let done = false;\n while (end < 0 && !done) {\n // oxlint-disable-next-line no-await-in-loop -- The page arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n html += chunk.value ?? '';\n end = html.search(/<\\/html>/i);\n }\n const cut = end < 0 ? html.length : end + '</html>'.length;\n const page = new DOMParser().parseFromString(html.slice(0, cut), 'text/html');\n for (const name of document.documentElement.getAttributeNames()) {\n document.documentElement.removeAttribute(name);\n }\n for (const attribute of page.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n const headNodes: Node[] = [];\n for (const node of page.head.childNodes) {\n headNodes.push(document.importNode(node, true));\n }\n document.head.replaceChildren(...headNodes);\n const bodyNodes: Node[] = [];\n for (const node of page.body.childNodes) {\n bodyNodes.push(document.importNode(node, true));\n }\n document.body.replaceChildren(...bodyNodes);\n for (const script of document.querySelectorAll('script')) {\n runOnce(script);\n }\n scripts.observe(document, { childList: true, subtree: true });\n\n const unwatch = watchView(visitOptions.offscreen);\n const stop = start({ load: options.load, rpc: prefix, navigate: true });\n let rest = html.slice(cut);\n let open = true;\n void (async () => {\n while (!done) {\n // oxlint-disable-next-line no-await-in-loop -- Later markup arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n rest += chunk.value ?? '';\n // A chunk can end inside a tag, a script or a template, so only whole nodes move in.\n const last = done ? rest.length : wholeNodes(rest);\n if (last > 0 && open) {\n // The observer runs its scripts.\n const template = document.createElement('template');\n template.innerHTML = rest.slice(0, last);\n document.body.append(template.content);\n rest = rest.slice(last);\n }\n }\n })();\n\n const current: Visited = {\n ...actions(document),\n get url() {\n return location.pathname + location.search;\n },\n status: response.status,\n get cookies() {\n return Object.fromEntries(jar);\n },\n close: () => {\n if (!open) {\n return;\n }\n open = false;\n visited = undefined;\n stop();\n unwatch();\n scripts.disconnect();\n reader.cancel().catch(() => {});\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n // The core forgets the page, so the next visit starts its IDs again.\n void import('./client.ts').then((core) => core.leavePage());\n document.head.replaceChildren();\n document.body.replaceChildren();\n },\n };\n visited = current;\n return current;\n };\n}\n"],"mappings":";;;AAEA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,WAAW,QAAwB;CACjD,MAAM,MAAM;CACZ,MAAM,QAAQ,OAAO,YAAY;CACjC,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,IAAI;CACJ,OAAQ,QAAQ,IAAI,KAAK,MAAM,GAAI;EACjC,MAAM,CAAC,OAAO,SAAS,QAAQ;EAC/B,MAAM,UAAU,KAAM,YAAY;EAClC,IAAI,CAAC,WAAW,YAAY,UAAU;GAEpC,MAAM,QAAQ,MAAM,QAAQ,aAAY,IAAI,SAAS;GACrD,MAAM,QAAQ,QAAQ,IAAI,KAAK,OAAO,QAAQ,KAAK,KAAK;GACxD,IAAI,QAAQ,GACV,OAAO;GAET,IAAI,YAAY,QAAQ;EAC1B,OAAO,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,MAAM,SAAS,IAAI,GACnD,SAAS,UAAU,KAAK;EAE1B,IAAI,UAAU,GACZ,MAAM,IAAI;CAEd;CACA,OAAO;AACT;;;ACyBA,IAAI;;AAGJ,SAAS,OAAO,SAAwB;CACtC,MAAM,SAAS,IAAI,OAAO;CAC1B,KAAK,MAAM,SA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|
|
6
|
+
* ```ts
|
|
7
|
+
* export const plugins = [
|
|
8
|
+
* definePlugin({
|
|
9
|
+
* tag: 'app/money',
|
|
10
|
+
* test: (value) => value instanceof Money,
|
|
11
|
+
* toData: (money: Money) => [money.amount, money.currency],
|
|
12
|
+
* fromData: ([amount, currency]) => new Money(amount, currency),
|
|
13
|
+
* }),
|
|
14
|
+
* ];
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
function definePlugin(plugin) {
|
|
18
|
+
if (!plugin.tag || plugin.tag.startsWith("brumate/")) throw new Error(`A plugin needs a tag of its own, such as 'app/money', and "${plugin.tag}" is not one`);
|
|
19
|
+
return plugin;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { definePlugin };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=values.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"values.js","names":[],"sources":["../../src/runtime/values.ts"],"sourcesContent":["// `brumate/serial`: plugins for values of the app, such as a class, so the\n// page state and server function calls can hold them. An entry of the app,\n// `src/serial.ts`, exports them as `plugins`. This module has no code of\n// seroval, so the browser loads it with the entry and nothing more.\n\n/**\n * How a value of the app becomes data that brumate can send, and back.\n * `data` can hold anything that brumate sends, such as numbers, strings,\n * arrays, plain objects and dates.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- The data of a plugin is any value that brumate sends.\nexport interface ValuePlugin<T = any, D = any> {\n /** A name of the plugin that no other plugin has, such as `app/money`. */\n tag: string;\n /** True for a value of the plugin, such as `value instanceof Money`. */\n test: (value: unknown) => boolean;\n /** The data of a value, such as `[money.amount, money.currency]`. */\n toData: (value: T) => D;\n /** Makes the value again from its data, in the browser or on the server. */\n fromData: (data: D) => T;\n}\n\n/**\n * Makes a plugin for a value of the app. Export it from the entry,\n * `src/serial.ts`, in `plugins`:\n *\n * ```ts\n * export const plugins = [\n * definePlugin({\n * tag: 'app/money',\n * test: (value) => value instanceof Money,\n * toData: (money: Money) => [money.amount, money.currency],\n * fromData: ([amount, currency]) => new Money(amount, currency),\n * }),\n * ];\n * ```\n */\nexport function definePlugin<T, D>(plugin: ValuePlugin<T, D>): ValuePlugin<T, D> {\n if (!plugin.tag || plugin.tag.startsWith('brumate/')) {\n throw new Error(\n `A plugin needs a tag of its own, such as 'app/money', and \"${plugin.tag}\" is not one`,\n );\n }\n return plugin;\n}\n\n/** The exports of the serial entry, `src/serial.ts`. Each is optional. */\nexport interface SerialEntry {\n /** Plugins for values of the app, which `definePlugin` makes. */\n plugins?: readonly ValuePlugin[];\n /**\n * The features of seroval that are off, as its `Feature` flags. Brumate\n * turns off `ErrorPrototypeStack` and `RegExp`, and warns when the entry\n * turns one of them on.\n */\n disabledFeatures?: number;\n /** How deep a value can be. Deeper values throw instead of being sent. */\n depthLimit?: number;\n}\n\n/**\n * The values that plugins of the app send, for the type checker. Add each\n * class to it, so a signal or memo can hold one:\n *\n * ```ts\n * declare module 'brumate/serial' {\n * interface SendableValues {\n * money: Money;\n * }\n * }\n * ```\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- Apps add to it with declaration merging.\nexport interface SendableValues {}\n\n/** A value that a plugin of the app sends. */\nexport type AppValue = SendableValues[keyof SendableValues];\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,SAAgB,aAAmB,QAA8C;CAC/E,IAAI,CAAC,OAAO,OAAO,OAAO,IAAI,WAAW,UAAU,GACjD,MAAM,IAAI,MACR,8DAA8D,OAAO,IAAI,aAC3E;CAEF,OAAO;AACT"}
|