@sigil-dev/grimoire 0.9.21 → 0.9.23

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +22 -10
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +871 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +211 -80
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +1 -1
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +799 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,91 +1,91 @@
1
- /**
2
- * Cache warming for a production server.
3
- *
4
- * Two independent costs land on whoever visits first after a boot: importing
5
- * each route's module (compiling it, and everything it imports), and whatever
6
- * the route's own load functions cache in memory. `preloadModules` pays the
7
- * first at startup; `startWarming` pays the second by requesting configured
8
- * paths through the real request handler, so the app's own caches fill exactly
9
- * as a visitor would fill them.
10
- *
11
- * Each `sigil start` worker is its own process with its own memory, which is
12
- * why this lives in the server and not in a script that hits the public URL:
13
- * one request would warm one worker and leave the rest cold.
14
- */
15
-
16
- export interface WarmConfig {
17
- /** Paths requested after startup, one at a time, e.g. ["/costumes", "/songs"]. */
18
- paths?: string[];
19
- /** Request them again this often (ms) so in-memory TTL caches never lapse. */
20
- every?: number;
21
- /** Import every route module before the server accepts traffic. Default true. */
22
- preload?: boolean;
23
- }
24
-
25
- type Loader = (path: string) => Promise<unknown>;
26
-
27
- export async function preloadModules(
28
- files: string[],
29
- load: Loader,
30
- warn: (msg: string, err: unknown) => void,
31
- ): Promise<number> {
32
- const unique = [...new Set(files)];
33
- const results = await Promise.allSettled(unique.map((f) => load(f)));
34
- let loaded = 0;
35
- results.forEach((r, i) => {
36
- if (r.status === "fulfilled") loaded++;
37
- else warn(`could not preload ${unique[i]}:`, r.reason);
38
- });
39
- return loaded;
40
- }
41
-
42
- export interface Warmer {
43
- stop(): void;
44
- /** Resolves when the first pass over `paths` has finished. */
45
- firstPass: Promise<void>;
46
- }
47
-
48
- export function startWarming(opts: {
49
- paths: string[];
50
- every?: number;
51
- origin: string;
52
- headers?: Record<string, string>;
53
- handle: (req: Request) => Promise<Response>;
54
- log: (msg: string) => void;
55
- }): Warmer {
56
- const { paths, every, origin, headers, handle, log } = opts;
57
- let stopped = false;
58
-
59
- async function pass(): Promise<void> {
60
- for (const path of paths) {
61
- if (stopped) return;
62
- const t0 = performance.now();
63
- try {
64
- const res = await handle(new Request(new URL(path, origin), { headers }));
65
- // drain the body: a streamed page and its deferred data only
66
- // finish (and only fill their caches) when someone reads it all
67
- await res.arrayBuffer();
68
- log(`warmed ${path} (${res.status}) in ${Math.round(performance.now() - t0)}ms`);
69
- } catch (e) {
70
- log(`warming ${path} failed: ${e instanceof Error ? e.message : String(e)}`);
71
- }
72
- }
73
- }
74
-
75
- const firstPass = pass();
76
- let timer: ReturnType<typeof setInterval> | undefined;
77
- if (every && every > 0) {
78
- timer = setInterval(() => {
79
- void pass();
80
- }, every);
81
- // a warm timer must never keep a stopping process alive
82
- (timer as { unref?: () => void }).unref?.();
83
- }
84
- return {
85
- firstPass,
86
- stop() {
87
- stopped = true;
88
- if (timer) clearInterval(timer);
89
- },
90
- };
91
- }
1
+ /**
2
+ * Cache warming for a production server.
3
+ *
4
+ * Two independent costs land on whoever visits first after a boot: importing
5
+ * each route's module (compiling it, and everything it imports), and whatever
6
+ * the route's own load functions cache in memory. `preloadModules` pays the
7
+ * first at startup; `startWarming` pays the second by requesting configured
8
+ * paths through the real request handler, so the app's own caches fill exactly
9
+ * as a visitor would fill them.
10
+ *
11
+ * Each `sigil start` worker is its own process with its own memory, which is
12
+ * why this lives in the server and not in a script that hits the public URL:
13
+ * one request would warm one worker and leave the rest cold.
14
+ */
15
+
16
+ export interface WarmConfig {
17
+ /** Paths requested after startup, one at a time, e.g. ["/costumes", "/songs"]. */
18
+ paths?: string[];
19
+ /** Request them again this often (ms) so in-memory TTL caches never lapse. */
20
+ every?: number;
21
+ /** Import every route module before the server accepts traffic. Default true. */
22
+ preload?: boolean;
23
+ }
24
+
25
+ type Loader = (path: string) => Promise<unknown>;
26
+
27
+ export async function preloadModules(
28
+ files: string[],
29
+ load: Loader,
30
+ warn: (msg: string, err: unknown) => void,
31
+ ): Promise<number> {
32
+ const unique = [...new Set(files)];
33
+ const results = await Promise.allSettled(unique.map((f) => load(f)));
34
+ let loaded = 0;
35
+ results.forEach((r, i) => {
36
+ if (r.status === "fulfilled") loaded++;
37
+ else warn(`could not preload ${unique[i]}:`, r.reason);
38
+ });
39
+ return loaded;
40
+ }
41
+
42
+ export interface Warmer {
43
+ stop(): void;
44
+ /** Resolves when the first pass over `paths` has finished. */
45
+ firstPass: Promise<void>;
46
+ }
47
+
48
+ export function startWarming(opts: {
49
+ paths: string[];
50
+ every?: number;
51
+ origin: string;
52
+ headers?: Record<string, string>;
53
+ handle: (req: Request) => Promise<Response>;
54
+ log: (msg: string) => void;
55
+ }): Warmer {
56
+ const { paths, every, origin, headers, handle, log } = opts;
57
+ let stopped = false;
58
+
59
+ async function pass(): Promise<void> {
60
+ for (const path of paths) {
61
+ if (stopped) return;
62
+ const t0 = performance.now();
63
+ try {
64
+ const res = await handle(new Request(new URL(path, origin), { headers }));
65
+ // drain the body: a streamed page and its deferred data only
66
+ // finish (and only fill their caches) when someone reads it all
67
+ await res.arrayBuffer();
68
+ log(`warmed ${path} (${res.status}) in ${Math.round(performance.now() - t0)}ms`);
69
+ } catch (e) {
70
+ log(`warming ${path} failed: ${e instanceof Error ? e.message : String(e)}`);
71
+ }
72
+ }
73
+ }
74
+
75
+ const firstPass = pass();
76
+ let timer: ReturnType<typeof setInterval> | undefined;
77
+ if (every && every > 0) {
78
+ timer = setInterval(() => {
79
+ void pass();
80
+ }, every);
81
+ // a warm timer must never keep a stopping process alive
82
+ (timer as { unref?: () => void }).unref?.();
83
+ }
84
+ return {
85
+ firstPass,
86
+ stop() {
87
+ stopped = true;
88
+ if (timer) clearInterval(timer);
89
+ },
90
+ };
91
+ }
@@ -1,27 +1,27 @@
1
- /**
2
- * Adds headers to a response. Sets them in place when it can: rebuilding
3
- * from `response.body` would turn a body Bun types itself (a string, a
4
- * file) into a stream that is sent with no Content-Type, which browsers
5
- * treat as a download. A response whose headers are locked (one from
6
- * fetch) is rebuilt, keeping its type.
7
- */
8
- export function withHeaders(
9
- response: Response,
10
- set: Iterable<[string, string]>,
11
- append: Iterable<[string, string]> = [],
12
- ): Response {
13
- try {
14
- for (const [k, v] of set) response.headers.set(k, v);
15
- for (const [k, v] of append) response.headers.append(k, v);
16
- return response;
17
- } catch {
18
- const headers = new Headers(response.headers);
19
- for (const [k, v] of set) headers.set(k, v);
20
- for (const [k, v] of append) headers.append(k, v);
21
- return new Response(response.body, {
22
- status: response.status,
23
- statusText: response.statusText,
24
- headers,
25
- });
26
- }
27
- }
1
+ /**
2
+ * Adds headers to a response. Sets them in place when it can: rebuilding
3
+ * from `response.body` would turn a body Bun types itself (a string, a
4
+ * file) into a stream that is sent with no Content-Type, which browsers
5
+ * treat as a download. A response whose headers are locked (one from
6
+ * fetch) is rebuilt, keeping its type.
7
+ */
8
+ export function withHeaders(
9
+ response: Response,
10
+ set: Iterable<[string, string]>,
11
+ append: Iterable<[string, string]> = [],
12
+ ): Response {
13
+ try {
14
+ for (const [k, v] of set) response.headers.set(k, v);
15
+ for (const [k, v] of append) response.headers.append(k, v);
16
+ return response;
17
+ } catch {
18
+ const headers = new Headers(response.headers);
19
+ for (const [k, v] of set) headers.set(k, v);
20
+ for (const [k, v] of append) headers.append(k, v);
21
+ return new Response(response.body, {
22
+ status: response.status,
23
+ statusText: response.statusText,
24
+ headers,
25
+ });
26
+ }
27
+ }
@@ -1,72 +1,74 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
3
- import type { GrimoireConfig, GrimoirePlugin, WorkerMode } from "../types";
4
- import { createServer } from "./index";
5
-
6
- export interface WorkerOptions {
7
- config: GrimoireConfig;
8
- plugins: GrimoirePlugin[];
9
- secret: string;
10
- mode: WorkerMode;
11
- }
12
-
13
- export async function startWorker(options: WorkerOptions) {
14
- const { secret, plugins } = options;
15
-
16
- const workerAuthPlugin: GrimoirePlugin = {
17
- name: "__grimoire-worker-auth",
18
- async onRequest(req, next) {
19
- if (req.headers.get("X-Grimoire-Internal") !== secret) {
20
- return new Response("Forbidden", { status: 403 });
21
- }
22
- return next();
23
- },
24
- };
25
-
26
- return createServer({
27
- ...options.config,
28
- plugins: [workerAuthPlugin, ...plugins],
29
- _skipBuild: true,
30
- _warmHeaders: { "X-Grimoire-Internal": secret },
31
- });
32
- }
33
-
34
- // bootstrap when spawned by coordinator
35
- if (process.env.GRIMOIRE_INTERNAL_SECRET) {
36
- const secret = process.env.GRIMOIRE_INTERNAL_SECRET;
37
- const port = Number(process.env.GRIMOIRE_WORKER_PORT ?? 3001);
38
- const cwd = process.cwd();
39
-
40
- // a config that fails to load must fail the worker, not run on defaults
41
- const configFile = join(cwd, "sigil.config.ts");
42
- const config: GrimoireConfig = existsSync(configFile)
43
- ? ((await import(configFile)).default ?? {})
44
- : {};
45
-
46
- // Forced, not defaulted. The worker re-reads sigil.config.ts from disk
47
- // rather than trusting what the CLI passed, so a `dev: true` left in the
48
- // config reaches the request handler — which gates the HMR socket, the
49
- // dependency-source endpoints, and /__grimoire__/open, that spawns an
50
- // editor on the host from a query string. Overriding here as well as in
51
- // the CLI is deliberate: the CLI's copy is not the one that binds.
52
- //
53
- // The worker is only ever spawned by `sigil start` or `sigil preview`.
54
- // `sigil dev` runs in-process and never gets here, which is why forcing
55
- // this cannot disable HMR for anyone.
56
- let finalConfig: GrimoireConfig = { ...config, port, host: "127.0.0.1" };
57
- const plugins = finalConfig.plugins ?? [];
58
- for (const plugin of plugins) {
59
- finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
60
- }
61
- // Last, so a plugin config hook cannot turn it back on either.
62
- finalConfig = { ...finalConfig, dev: false };
63
-
64
- await startWorker({
65
- config: finalConfig,
66
- plugins,
67
- secret,
68
- mode: (process.env.GRIMOIRE_MODE ?? "full") as WorkerMode,
69
- });
70
-
71
- process.send?.({ ready: true });
72
- }
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { GrimoireConfig, GrimoirePlugin, WorkerMode } from "../types";
4
+ import { createServer } from "./index";
5
+
6
+ export interface WorkerOptions {
7
+ config: GrimoireConfig;
8
+ plugins: GrimoirePlugin[];
9
+ secret: string;
10
+ mode: WorkerMode;
11
+ }
12
+
13
+ export async function startWorker(options: WorkerOptions) {
14
+ const { secret, plugins } = options;
15
+
16
+ const workerAuthPlugin: GrimoirePlugin = {
17
+ name: "__grimoire-worker-auth",
18
+ async onRequest(req, next) {
19
+ if (req.headers.get("X-Grimoire-Internal") !== secret) {
20
+ return new Response("Forbidden", { status: 403 });
21
+ }
22
+ return next();
23
+ },
24
+ };
25
+
26
+ return createServer({
27
+ ...options.config,
28
+ plugins: [workerAuthPlugin, ...plugins],
29
+ _skipBuild: true,
30
+ _behindCoordinator: true,
31
+ _forceProduction: true,
32
+ _warmHeaders: { "X-Grimoire-Internal": secret },
33
+ });
34
+ }
35
+
36
+ // bootstrap when spawned by coordinator
37
+ if (process.env.GRIMOIRE_INTERNAL_SECRET) {
38
+ const secret = process.env.GRIMOIRE_INTERNAL_SECRET;
39
+ const port = Number(process.env.GRIMOIRE_WORKER_PORT ?? 3001);
40
+ const cwd = process.cwd();
41
+
42
+ // a config that fails to load must fail the worker, not run on defaults
43
+ const configFile = join(cwd, "sigil.config.ts");
44
+ const config: GrimoireConfig = existsSync(configFile)
45
+ ? ((await import(configFile)).default ?? {})
46
+ : {};
47
+
48
+ // Forced, not defaulted. The worker re-reads sigil.config.ts from disk
49
+ // rather than trusting what the CLI passed, so a `dev: true` left in the
50
+ // config reaches the request handler — which gates the HMR socket, the
51
+ // dependency-source endpoints, and /__grimoire__/open, that spawns an
52
+ // editor on the host from a query string. Overriding here as well as in
53
+ // the CLI is deliberate: the CLI's copy is not the one that binds.
54
+ //
55
+ // The worker is only ever spawned by `sigil start` or `sigil preview`.
56
+ // `sigil dev` runs in-process and never gets here, which is why forcing
57
+ // this cannot disable HMR for anyone.
58
+ let finalConfig: GrimoireConfig = { ...config, port, host: "127.0.0.1" };
59
+ const plugins = finalConfig.plugins ?? [];
60
+ for (const plugin of plugins) {
61
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
62
+ }
63
+ // Last, so a plugin config hook cannot turn it back on either.
64
+ finalConfig = { ...finalConfig, dev: false };
65
+
66
+ await startWorker({
67
+ config: finalConfig,
68
+ plugins,
69
+ secret,
70
+ mode: (process.env.GRIMOIRE_MODE ?? "full") as WorkerMode,
71
+ });
72
+
73
+ process.send?.({ ready: true });
74
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Preload for component tests: `sigil test` passes this to `bun test`.
3
+ *
4
+ * Gives a test file what a browser would: DOM globals, the compiler in `dom`
5
+ * mode so `.tsx` components import and run, and the `$env/*` modules. It also
6
+ * unmounts whatever a test rendered when the test ends.
7
+ *
8
+ * Route and server tests (`*.server.test.ts`) do not use this: they run
9
+ * the app on the server through `@sigil-dev/grimoire/testing/server`, which
10
+ * compiles for the server instead. The two cannot share a process, because a
11
+ * module compiles once, so `sigil test` runs them as separate passes.
12
+ */
13
+ import { afterEach } from "bun:test";
14
+ import { sigil } from "@sigil-dev/compiler/bun";
15
+ import { Window } from "happy-dom";
16
+ import { ENV_MODULE, envModuleSource } from "../env/modules";
17
+ import { cleanup } from "./index";
18
+
19
+ const window = new Window({ url: "http://localhost/" });
20
+ const g = globalThis as Record<string, unknown>;
21
+ for (const name of [
22
+ "window",
23
+ "document",
24
+ "navigator",
25
+ "location",
26
+ "history",
27
+ "Node",
28
+ "Element",
29
+ "HTMLElement",
30
+ "SVGElement",
31
+ "Text",
32
+ "Comment",
33
+ "DocumentFragment",
34
+ "Event",
35
+ "CustomEvent",
36
+ "MouseEvent",
37
+ "KeyboardEvent",
38
+ "InputEvent",
39
+ "FocusEvent",
40
+ "MutationObserver",
41
+ "getComputedStyle",
42
+ "requestAnimationFrame",
43
+ "cancelAnimationFrame",
44
+ "DOMParser",
45
+ ] as const) {
46
+ const value = (window as unknown as Record<string, unknown>)[name];
47
+ if (value !== undefined) g[name] = value;
48
+ }
49
+ g.window = window;
50
+
51
+ Bun.plugin(sigil({ mode: "dom" }));
52
+
53
+ // `$env/*` for browser code: public values are readable, private ones throw
54
+ // when imported, exactly as in the browser build.
55
+ Bun.plugin({
56
+ name: "sigil-test-env",
57
+ setup(build) {
58
+ for (const specifier of [
59
+ "$env/static/public",
60
+ "$env/static/private",
61
+ "$env/dynamic/public",
62
+ "$env/dynamic/private",
63
+ ]) {
64
+ if (!ENV_MODULE.test(specifier)) continue;
65
+ build.module(specifier, () => ({
66
+ contents: envModuleSource(specifier, "browser"),
67
+ loader: "js",
68
+ }));
69
+ }
70
+ },
71
+ });
72
+
73
+ afterEach(cleanup);
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Test helpers for components and for the functions a route is made of.
3
+ *
4
+ * ```tsx
5
+ * import { expect, test } from "bun:test";
6
+ * import { render, click, tick } from "@sigil-dev/grimoire/testing";
7
+ * import { Counter } from "./Counter.tsx";
8
+ *
9
+ * test("counts", async () => {
10
+ * const { $, text } = render(Counter, { start: 1 });
11
+ * click($("button")!);
12
+ * await tick();
13
+ * expect(text()).toContain("2");
14
+ * });
15
+ * ```
16
+ *
17
+ * Run with `sigil test`. Component tests need the DOM preload that command
18
+ * adds; for routes see `@sigil-dev/grimoire/testing/server`.
19
+ */
20
+ import { insert, tick, withEffectScope } from "@sigil-dev/runtime";
21
+ import { createCookies } from "../server/cookie-utils";
22
+ import type { Cookies } from "../server/hooks";
23
+
24
+ export { tick };
25
+
26
+ export interface Rendered {
27
+ /** The element the component was rendered into. */
28
+ container: HTMLElement;
29
+ /** First element matching a selector inside the render. */
30
+ $(selector: string): HTMLElement | null;
31
+ /** Every element matching a selector inside the render. */
32
+ $$(selector: string): HTMLElement[];
33
+ /** The rendered text. */
34
+ text(): string;
35
+ /** The rendered markup. */
36
+ html(): string;
37
+ /** Remove it and stop its effects. Done for you after each test. */
38
+ unmount(): void;
39
+ }
40
+
41
+ const mounted = new Set<() => void>();
42
+
43
+ /**
44
+ * Render a component into the document, the way a client-side navigation
45
+ * would: a fresh render, with effects live.
46
+ *
47
+ * Each call gets its own container, so one test can render several things.
48
+ */
49
+ export function render<P extends object>(
50
+ Component: (props: P) => unknown,
51
+ props: P = {} as P,
52
+ ): Rendered {
53
+ const container = document.createElement("div");
54
+ document.body.appendChild(container);
55
+ const stop = withEffectScope(() => {
56
+ insert(container, Component(props));
57
+ });
58
+ const unmount = () => {
59
+ stop();
60
+ container.remove();
61
+ mounted.delete(unmount);
62
+ };
63
+ mounted.add(unmount);
64
+ return {
65
+ container,
66
+ $: (selector) => container.querySelector<HTMLElement>(selector),
67
+ $$: (selector) =>
68
+ Array.from(container.querySelectorAll<HTMLElement>(selector)),
69
+ text: () => container.textContent ?? "",
70
+ html: () => container.innerHTML,
71
+ unmount,
72
+ };
73
+ }
74
+
75
+ /** Unmount everything rendered so far. The DOM preload runs this after each test. */
76
+ export function cleanup(): void {
77
+ for (const unmount of [...mounted]) unmount();
78
+ }
79
+
80
+ /** Click an element, with the bubbling a real click has. */
81
+ export function click(el: Element): void {
82
+ el.dispatchEvent(
83
+ new MouseEvent("click", { bubbles: true, cancelable: true }),
84
+ );
85
+ }
86
+
87
+ /** Type into an input or textarea: set its value and fire `input`, as a user would. */
88
+ export function type(el: Element, value: string): void {
89
+ (el as HTMLInputElement).value = value;
90
+ el.dispatchEvent(new Event("input", { bubbles: true }));
91
+ }
92
+
93
+ /** Fire any event on an element. */
94
+ export function fire(el: Element, type: string, init: EventInit = {}): void {
95
+ el.dispatchEvent(
96
+ new Event(type, { bubbles: true, cancelable: true, ...init }),
97
+ );
98
+ }
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // the arguments of load functions and actions
102
+ // ---------------------------------------------------------------------------
103
+
104
+ export interface ContextOptions {
105
+ params?: Record<string, string>;
106
+ /** Path or URL. A path is resolved against `http://localhost`. */
107
+ url?: string;
108
+ method?: string;
109
+ headers?: Record<string, string>;
110
+ /** A form submission: fields are sent url-encoded. */
111
+ form?: Record<string, string>;
112
+ /** A JSON body. */
113
+ json?: unknown;
114
+ locals?: Record<string, unknown>;
115
+ /** Cookies the request carries. */
116
+ cookies?: Record<string, string>;
117
+ /** What `fetch` inside the function does. Defaults to the real one. */
118
+ fetch?: typeof fetch;
119
+ /** What `parent()` resolves to. */
120
+ parent?: Record<string, unknown>;
121
+ }
122
+
123
+ export type TestContext = ReturnType<typeof context>;
124
+
125
+ /**
126
+ * The argument a `load`, an action or a `+server.ts` handler receives, so the
127
+ * function can be called directly:
128
+ *
129
+ * ```ts
130
+ * const data = await load(context({ params: { id: "7" } }));
131
+ * ```
132
+ *
133
+ * `cookies` is the real implementation; `cookies.toHeaders()` lists what the
134
+ * function set, for assertions.
135
+ */
136
+ export function context(options: ContextOptions = {}) {
137
+ const url = new URL(options.url ?? "/", "http://localhost");
138
+ const headers = new Headers(options.headers);
139
+ if (options.cookies) {
140
+ headers.set(
141
+ "cookie",
142
+ Object.entries(options.cookies)
143
+ .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
144
+ .join("; "),
145
+ );
146
+ }
147
+ let body: BodyInit | undefined;
148
+ if (options.form) {
149
+ body = new URLSearchParams(options.form);
150
+ headers.set("content-type", "application/x-www-form-urlencoded");
151
+ } else if (options.json !== undefined) {
152
+ body = JSON.stringify(options.json);
153
+ headers.set("content-type", "application/json");
154
+ }
155
+ const method = options.method ?? (body ? "POST" : "GET");
156
+ const request = new Request(url, { method, headers, body });
157
+ const cookies: Cookies & { toHeaders(): string[] } = createCookies(
158
+ headers.get("cookie") ?? "",
159
+ );
160
+ return {
161
+ request,
162
+ url,
163
+ params: options.params ?? {},
164
+ locals: (options.locals ?? {}) as App.Locals,
165
+ cookies,
166
+ fetch: options.fetch ?? globalThis.fetch,
167
+ parent: async () => options.parent ?? {},
168
+ };
169
+ }