@akanjs/devkit 3.3.0-rc.61 → 3.3.0-rc.63

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.
@@ -11,6 +11,8 @@ import { AkanAppConfig, AkanLibConfig, deriveDefaultAppId } from "./akanConfig";
11
11
  import {
12
12
  BUN_IMAGE_PIN,
13
13
  DEFAULT_DOCKER_IMAGE,
14
+ DOCKER_BASE_PACKAGES,
15
+ DOCKER_BASE_RUNS,
14
16
  DOCKER_INIT,
15
17
  DOCKERFILE_FORMAT,
16
18
  dockerfileLayoutOf,
@@ -488,6 +490,7 @@ describe("AkanAppConfig", () => {
488
490
  postRuns: ["echo post"],
489
491
  command: ["bun", "main.js"],
490
492
  crossBuild: true,
493
+ baseSetup: true,
491
494
  env: { REGION: "seoul", EDGE_MODE: "camera", AKAN_PUBLIC_OPERATION_MODE: "edge" },
492
495
  },
493
496
  });
@@ -541,6 +544,34 @@ describe("AkanAppConfig", () => {
541
544
  expect(later?.sections.get("warm")).toEqual(["RUN true"]);
542
545
  });
543
546
 
547
+ test("baseSetup false leaves the base step to the image, which then has to be named for every architecture", () => {
548
+ const configOf = (docker: object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
549
+ const baseOf = (docker: object) => dockerfileLayoutOf(configOf(docker).dockerfile)?.sections.get("base");
550
+
551
+ expect(baseOf({})).toEqual([
552
+ `FROM ${DEFAULT_DOCKER_IMAGE}`,
553
+ `RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ${DOCKER_BASE_PACKAGES.join(" ")} && rm -rf /var/lib/apt/lists/*`,
554
+ "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
555
+ "ARG TARGETARCH",
556
+ ]);
557
+ expect(baseOf({})?.slice(1, -1)).toEqual(DOCKER_BASE_RUNS.map((run) => `RUN ${run}`));
558
+ expect(baseOf({ image: "registry.example.com/akan-base:1", baseSetup: false })).toEqual([
559
+ "FROM registry.example.com/akan-base:1",
560
+ "ARG TARGETARCH",
561
+ ]);
562
+ const edge = configOf({ variants: { edge: { image: "registry.example.com/akan-base:1", baseSetup: false } } });
563
+ expect(edge.dockerfile).toContain("apt-get update");
564
+ expect(edge.dockerfileFor("main", { variant: "edge" })).not.toContain("apt-get");
565
+
566
+ expect(() => configOf({ baseSetup: false })).toThrow("docker.baseSetup is false, so docker.image has to name");
567
+ expect(() => configOf({ baseSetup: false, image: { amd64: "registry.example.com/akan-base:1" } })).toThrow(
568
+ "for every architecture",
569
+ );
570
+ expect(() => configOf({ variants: { edge: { baseSetup: false } } })).toThrow(
571
+ "docker.variants.edge.baseSetup is false",
572
+ );
573
+ });
574
+
544
575
  test("the akanConfig entry carries the generator, for a tool that checks its edits against the installed one", async () => {
545
576
  const entry = await import("./index");
546
577
  expect(entry.dockerfileOf).toBe(dockerfileOf);
@@ -568,6 +599,7 @@ describe("AkanAppConfig", () => {
568
599
  postRuns: [],
569
600
  command: ["bun", "main.js"],
570
601
  crossBuild: false,
602
+ baseSetup: true,
571
603
  env: {},
572
604
  });
573
605
  });
@@ -1353,13 +1385,19 @@ describe("AkanAppConfig.from", () => {
1353
1385
  const libConfigPath = path.join(root, "libs/extlib/akan.config.ts");
1354
1386
  fs.mkdirSync(path.join(root, "apps/extapp"), { recursive: true });
1355
1387
  fs.mkdirSync(path.join(root, "libs/extlib"), { recursive: true });
1356
- fs.writeFileSync(path.join(root, "apps/extapp/akan.config.ts"), "export default {};\n");
1388
+ fs.writeFileSync(
1389
+ path.join(root, "apps/extapp/akan.config.ts"),
1390
+ "export default { preview: { signIn: async () => ({ jwt: 'token' }), examples: ['/chat/1'] } };\n",
1391
+ );
1357
1392
  fs.writeFileSync(libConfigPath, "export default { externalLibs: ['first'] };\n");
1358
1393
  fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "extrepo", version: "1.0.0" }));
1359
1394
  fs.writeFileSync(path.join(root, ".env"), "AKAN_PUBLIC_REPO_NAME=extrepo\nAKAN_PUBLIC_SERVE_DOMAIN=ext.test\n");
1360
1395
  const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot: root, repoName: "extrepo" });
1361
1396
  const app = AppExecutor.from(workspace, "extapp");
1362
- expect((await AkanAppConfig.from(app)).externalLibs).toEqual(["first"]);
1397
+ const config = await AkanAppConfig.from(app);
1398
+ expect(config.externalLibs).toEqual(["first"]);
1399
+ expect(config.preview.examples).toEqual(["/chat/1"]);
1400
+ expect(await config.preview.signIn?.({ origin: "http://localhost:8282", as: null })).toEqual({ jwt: "token" });
1363
1401
 
1364
1402
  fs.writeFileSync(libConfigPath, "export default { externalLibs: ['second'] };\n");
1365
1403
  expect((await AkanAppConfig.from(app, { bustImportCache: true })).externalLibs).toEqual(["second"]);
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import type { AkanPlugin } from "akanjs";
4
+ import type { AkanPlugin, AkanPreviewConfig } from "akanjs";
5
5
  import { DatabaseModes, normalizeRoutePrefix } from "akanjs/base";
6
6
  import { type AkanI18nConfig, resolveAkanI18nConfig, trimSlashes } from "akanjs/common";
7
7
  import type { AkanImageConfig } from "akanjs/server";
@@ -9,6 +9,7 @@ import type { App, Lib } from "../commandDecorators";
9
9
  import { WorkspaceExecutor } from "../executors/workspaceExecutor";
10
10
  import type { BaseDevEnv, PackageJson } from "../workspace/types";
11
11
  import { AkanBin } from "./akanBin";
12
+ import { AkanPreview } from "./akanPreview";
12
13
  import { AkanWorkers, type LibWorkers } from "./akanWorkers";
13
14
  import { DesktopServerConfig } from "./desktopServerConfig";
14
15
  import { dockerfileOf, resolveDocker, resolveDockerVariants } from "./dockerImage";
@@ -184,6 +185,8 @@ export class AkanAppConfig implements AppConfigResult {
184
185
  libs: string[];
185
186
  /** Live-only: plugins declared in this app's `akan.config.ts` (never serialized). */
186
187
  plugins: AkanPlugin[];
188
+ /** Live-only: `akan preview` reads it from this app's `akan.config.ts` (never serialized). */
189
+ preview: AkanPreviewConfig = {};
187
190
  domains = new Set<string>();
188
191
  subRoutes = new Map<string, Set<string>>();
189
192
  basePaths = new Set<string>();
@@ -507,17 +510,29 @@ export class AkanAppConfig implements AppConfigResult {
507
510
  const {
508
511
  plugins,
509
512
  pipeline: _pipeline,
513
+ preview,
510
514
  ...config
511
515
  } = (resolved ?? {}) as AppConfigDeclaration & {
512
516
  plugins?: AkanPlugin[];
513
517
  pipeline?: unknown;
518
+ preview?: unknown;
514
519
  };
515
520
  if ("subspace" in config)
516
521
  throw new Error(
517
522
  `apps/${app.name}/akan.config.ts declares \`subspace\`, a workspace setting: it belongs in the workspace root akan.config.ts.`,
518
523
  );
519
524
  const libContributions = await AkanAppConfig.#collectLibContributions(app, libs, bustImportCache);
520
- return new AkanAppConfig(app, libs, rootPackageJson, config, baseDevEnv, plugins ?? [], libContributions);
525
+ const appConfig = new AkanAppConfig(
526
+ app,
527
+ libs,
528
+ rootPackageJson,
529
+ config,
530
+ baseDevEnv,
531
+ plugins ?? [],
532
+ libContributions,
533
+ );
534
+ appConfig.preview = AkanPreview.parse(preview, `apps/${app.name}/akan.config.ts`);
535
+ return appConfig;
521
536
  }
522
537
  //* Every workspace lib is read, not just this app's lib deps: narrowing the set needs the dependency
523
538
  //* scan, and the incremental page rebundle re-reads this config on every file change.
@@ -0,0 +1,28 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { AkanPreview } from "./akanPreview";
3
+
4
+ const owner = "apps/demo/akan.config.ts";
5
+
6
+ describe("AkanPreview.parse", () => {
7
+ test("keeps the sign-in function and the example paths, and reads a missing section as empty", () => {
8
+ const signIn = async () => ({ jwt: "token" });
9
+ expect(AkanPreview.parse(undefined, owner)).toEqual({});
10
+ expect(AkanPreview.parse({}, owner)).toEqual({});
11
+ expect(AkanPreview.parse({ signIn, examples: ["/chat/1?tab=files"] }, owner)).toEqual({
12
+ signIn,
13
+ examples: ["/chat/1?tab=files"],
14
+ });
15
+ });
16
+
17
+ test("refuses a section it cannot read, naming the file and the key", () => {
18
+ expect(() => AkanPreview.parse([], owner)).toThrow(`${owner} declares \`preview\`, which has to be an object`);
19
+ expect(() => AkanPreview.parse({ login: () => null }, owner)).toThrow(
20
+ "preview.login; it takes signIn and examples",
21
+ );
22
+ expect(() => AkanPreview.parse({ signIn: "/api/signin" }, owner)).toThrow(
23
+ "preview.signIn, which has to be a function",
24
+ );
25
+ for (const examples of ["/chat/1", ["chat/1"], ["//host/chat/1"], [1]])
26
+ expect(() => AkanPreview.parse({ examples }, owner)).toThrow("preview.examples, which has to list paths");
27
+ });
28
+ });
@@ -0,0 +1,24 @@
1
+ import type { AkanPreviewConfig } from "./types";
2
+
3
+ export class AkanPreview {
4
+ static parse(value: unknown, owner: string): AkanPreviewConfig {
5
+ if (value === undefined) return {};
6
+ if (typeof value !== "object" || value === null || Array.isArray(value))
7
+ throw new Error(`[preview] ${owner} declares \`preview\`, which has to be an object: { signIn, examples }`);
8
+ const { signIn, examples, ...unknown } = value as Record<string, unknown>;
9
+ const [stray] = Object.keys(unknown);
10
+ if (stray) throw new Error(`[preview] ${owner} declares preview.${stray}; it takes signIn and examples`);
11
+ if (signIn !== undefined && typeof signIn !== "function")
12
+ throw new Error(`[preview] ${owner} declares preview.signIn, which has to be a function`);
13
+ if (examples !== undefined && !(Array.isArray(examples) && examples.every(AkanPreview.#isPath)))
14
+ throw new Error(`[preview] ${owner} declares preview.examples, which has to list paths that start with "/"`);
15
+ return {
16
+ ...(signIn ? { signIn: signIn as AkanPreviewConfig["signIn"] } : {}),
17
+ ...(examples ? { examples: examples as string[] } : {}),
18
+ };
19
+ }
20
+
21
+ static #isPath(value: unknown) {
22
+ return typeof value === "string" && value.startsWith("/") && !value.startsWith("//");
23
+ }
24
+ }
@@ -19,6 +19,12 @@ export const DEFAULT_DOCKER_IMAGE = `oven/bun:${BUN_IMAGE_PIN.version}-slim@${BU
19
19
  export const DOCKER_RUN_USER = "1000:1000";
20
20
  //? Bun as PID 1 never waits for a process re-parented to it, which stays defunct; `-s` reaps under another init too.
21
21
  export const DOCKER_INIT = ["tini", "-s", "--"];
22
+ export const DOCKER_BASE_PACKAGES = ["ca-certificates", "tzdata", "tini"] as const;
23
+ //? Every generated image runs these on its base; an image built with them is one `baseSetup: false` can start from.
24
+ export const DOCKER_BASE_RUNS = [
25
+ `apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ${DOCKER_BASE_PACKAGES.join(" ")} && rm -rf /var/lib/apt/lists/*`,
26
+ "ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
27
+ ];
22
28
  //? The directories the server writes, its code staying read-only; an empty named volume mounted on one takes its owner.
23
29
  export const DOCKER_WRITE_DIRS = [
24
30
  "/workspace/sqlite",
@@ -100,7 +106,7 @@ const dockerfileSectionOf = (section: DockerfileSection, instructions: string[])
100
106
  instructions.length ? [`${DOCKERFILE_MARK}${section}`, ...instructions] : [];
101
107
 
102
108
  export const dockerfileOf = (docker: DockerImageConfig, { env, lockfile, guard }: DockerfileParts) => {
103
- const { image, preRuns, postRuns, command, crossBuild } = docker;
109
+ const { image, preRuns, postRuns, command, crossBuild, baseSetup } = docker;
104
110
  const install = dockerInstallScripts(docker, lockfile);
105
111
  return [
106
112
  `${DOCKERFILE_HEAD}${DOCKERFILE_FORMAT}`,
@@ -118,8 +124,7 @@ export const dockerfileOf = (docker: DockerImageConfig, { env, lockfile, guard }
118
124
  ...dockerfileSectionOf("base", [
119
125
  dockerImageScript(image),
120
126
  ...(guard ? [guard] : []),
121
- "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*",
122
- "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
127
+ ...(baseSetup ? dockerRunScripts(DOCKER_BASE_RUNS) : []),
123
128
  "ARG TARGETARCH",
124
129
  ]),
125
130
  ...dockerfileSectionOf("pre-runs", dockerRunScripts(preRuns)),
@@ -173,29 +178,37 @@ const dockerVariantNamePattern = /^[a-z][a-z0-9-]*$/;
173
178
  const resolveDockerImage = (
174
179
  docker: Partial<DockerImageConfig>,
175
180
  libDocker: LibDockerConfig,
176
- envOwner: string,
181
+ owner: string,
177
182
  ): DockerImageConfig => {
178
183
  const env = docker.env ?? {};
179
184
  for (const [key, value] of Object.entries(env)) {
180
185
  if (!dockerEnvKeyPattern.test(key))
181
- throw new Error(`[docker] ${envOwner} names "${key}", which is not an environment variable name`);
186
+ throw new Error(`[docker] ${owner}.env names "${key}", which is not an environment variable name`);
182
187
  if (/[\r\n]/.test(value))
183
- throw new Error(`[docker] ${envOwner}.${key} holds a line break, which an ENV line cannot carry`);
188
+ throw new Error(`[docker] ${owner}.env.${key} holds a line break, which an ENV line cannot carry`);
184
189
  }
190
+ const { image } = docker;
191
+ const baseSetup = docker.baseSetup ?? true;
192
+ //? The pinned default has no tini, the entrypoint: an image skipping the base step without one never starts.
193
+ if (!baseSetup && (!image || (typeof image !== "string" && archs.some((arch) => !image[arch]))))
194
+ throw new Error(
195
+ `[docker] ${owner}.baseSetup is false, so ${owner}.image has to name an image built with the base step, for every architecture`,
196
+ );
185
197
  return {
186
- image: docker.image ?? DEFAULT_DOCKER_IMAGE,
198
+ image: image ?? DEFAULT_DOCKER_IMAGE,
187
199
  preRuns: dedupeDockerRuns([...libDocker.preRuns, ...(docker.preRuns ?? [])]),
188
200
  installRuns: dedupeDockerRuns([...libDocker.installRuns, ...(docker.installRuns ?? [])]),
189
201
  postRuns: dedupeDockerRuns([...libDocker.postRuns, ...(docker.postRuns ?? [])]),
190
202
  command: docker.command ?? ["bun", "main.js"],
191
203
  crossBuild: docker.crossBuild ?? false,
204
+ baseSetup,
192
205
  env,
193
206
  };
194
207
  };
195
208
 
196
209
  /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
197
210
  export const resolveDocker = (docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig =>
198
- typeof docker === "string" ? docker : resolveDockerImage(docker ?? {}, libDocker, "docker.env");
211
+ typeof docker === "string" ? docker : resolveDockerImage(docker ?? {}, libDocker, "docker");
199
212
 
200
213
  export const resolveDockerVariants = (
201
214
  docker: DockerOption | undefined,
@@ -210,7 +223,7 @@ export const resolveDockerVariants = (
210
223
  `[docker] docker.variants names "${name}", which cannot end a file name: use lowercase letters, digits and "-"`,
211
224
  );
212
225
  const env = { ...base.env, ...variant.env };
213
- return [name, resolveDockerImage({ ...base, ...variant, env }, libDocker, `docker.variants.${name}.env`)];
226
+ return [name, resolveDockerImage({ ...base, ...variant, env }, libDocker, `docker.variants.${name}`)];
214
227
  }),
215
228
  );
216
229
  };
@@ -1,5 +1,6 @@
1
1
  export * from "./akanBin";
2
2
  export * from "./akanConfig";
3
+ export * from "./akanPreview";
3
4
  export * from "./akanWorkers";
4
5
  export * from "./akanWorkspaceConfig";
5
6
  export * from "./dockerImage";
@@ -22,6 +22,8 @@ export type {
22
22
  AkanNativeValue,
23
23
  AkanPlugin,
24
24
  AkanPluginNativeConfig,
25
+ AkanPreviewConfig,
26
+ AkanPreviewSignIn,
25
27
  AkanRouteConfig,
26
28
  AkanScanInfo,
27
29
  AkanSyncContext,
@@ -24,8 +24,13 @@ the server errors logged meanwhile, console errors and warnings, and layout smel
24
24
  opens its path and query the same way, always on the app's dev server, with a note when it names another
25
25
  server: use it for an endpoint mounted outside the API prefix. A page `--changed` finds opens as a page even at
26
26
  a server route's path, under the same locale rule, and `/en` and `/en/` open once.
27
- `--changed` adds the pages your uncommitted page and layout edits reach. A dynamic route needs a concrete
28
- path (`/memo/1`); `akan context --app <app>` lists every route with its params and search names.
27
+ `--changed` adds the pages your uncommitted page and layout edits reach. A dynamic route opens at the first
28
+ `preview.examples` path of `akan.config.ts` that fits it (`["/memo/1"]`, no locale), else type a concrete
29
+ one; `akan context --app <app>` lists every route with its params and search names.
30
+ - A page behind a sign-in opens through `preview.signIn({ origin, as })` in `akan.config.ts`, called once per
31
+ run: it returns the sign-in `Response` (its `Set-Cookie` pairs become every page's cookies) or the cookies by
32
+ name, and reads the account from `process.env`. `--as <name>` reaches it as `as`; `--anonymous` skips it.
33
+ With none declared a guarded page shows its redirect: add it, or say "not opened signed in".
29
34
  - The viewport is a 390x844 phone; `--desktop` is 1280x800. `--csr` loads each page in the CSR boot the native
30
35
  shells load. `--screenshot` saves a PNG per page under `local/apps/<app>/runtime/preview/`, for a model
31
36
  that reads images. `--format json` gives the same report as data.
@@ -64,6 +64,9 @@ File names, stages, the `.render()` order and what a route file must never do ar
64
64
  that answers everyone alike, lets the server keep the page.
65
65
  - Loading: `.loading(() => <Skeleton />)` on a page or layout is what that level shows until its `.render()` and the
66
66
  levels below it resolve; the levels above it stream first.
67
+ - A page left on screen while its next path loads (`/chat/a` to `/chat/b` under an awaiting layout):
68
+ `.loading(fn, { atPress: true })` shows the fallback after 150 ms of waiting on the server (`{ atPress: { delayMs } }`).
69
+ `page()` only; never on Back, Forward or a held page. It is the path being left's fallback: draw it from no argument.
67
70
  - `router.notFound()` from `.guard()`, `.head()` or `.render()` answers 404 with the nearest layout's `.notFound()`
68
71
  above it (an unmatched URL: the deepest layout covering it), else the built-in 404.
69
72
  - A layout's own 404 and error views: `.notFound(({ pathname }) => …)` and `.error(({ error }) => …)` on `layout()`
@@ -73,7 +76,7 @@ File names, stages, the `.render()` order and what a route file must never do ar
73
76
  locale under `i18n.localePrefix: "as-needed"`. It renders an `<a>` and takes its attributes; `activeClassName`
74
77
  marks the current one from the press, before its page arrives; an `active` prop from a layout's render is late.
75
78
  - An SSR page still loading: `pendingClassName` / `data-pending` on its `Link`, and `usePendingNavigation()`
76
- (`akanjs/client`) for its `{ path, searchParams }`, `null` once the page is drawn.
79
+ (`akanjs/client`) for its `{ path, searchParams }`, `null` once the page is drawn and for a page already held.
77
80
  - From a handler: `router.push(href)` / `router.replace(href)`; in a server stage, `router.redirect(href)`.
78
81
  - A page state a push opens in the query (a record in `?id=`): close it with `router.backOrReplace(href)`, never
79
82
  `router.back()` or a `renderMode` branch. A CSR or native stack rewrites a push that keeps the pathname rather than
@@ -15,7 +15,7 @@ the agent guide's Path Rules table.
15
15
  | --- | --- |
16
16
  | API only, or no CSR bundle for native apps | `web: false`, `web: { csr: false }` |
17
17
  | Move the API or websocket mount | `new AkanApp({ prefix, websocketPrefix })` in `main.ts`, mirrored in `api: { … }`; read with `getApiPrefix()` / `getWsPrefix()` |
18
- | The production image | `docker: string \| { image, preRuns, installRuns, postRuns, command, crossBuild, env, variants }` |
18
+ | The production image | `docker: string \| { image, preRuns, installRuns, postRuns, command, crossBuild, baseSetup, env, variants }` |
19
19
  | iOS, Android, desktop | the `native` section; `desktop: { server: true }` carries the server |
20
20
  | SQLite, several databases, a cluster | `database: { modes: [...] }` (`single`, `multiple`, `cluster`), picked by `AKAN_DATABASE_MODE` |
21
21
  | A secret of `env/env.server.<env>.ts` in a deployed server | nothing to declare: `akan build` leaves it out and the server reads it from a variable named after its key path; `akan secret-env <app> --env <env>` lists them |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.61",
3
+ "version": "3.3.0-rc.63",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.61",
53
+ "@akanjs/language": "3.3.0-rc.63",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.61",
62
+ "akanjs": "3.3.0-rc.63",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",
@@ -1,6 +1,14 @@
1
1
  import { PreviewChrome, type PreviewEngine } from "./PreviewChrome";
2
2
 
3
+ export interface PreviewSession {
4
+ /** A document of the pages' origin, where the cookies are written before a page opens. */
5
+ url: string;
6
+ /** `name=value` pairs. */
7
+ cookies: string[];
8
+ }
9
+
3
10
  export interface PreviewProbeOptions {
11
+ session?: PreviewSession | null;
4
12
  screenshot?: boolean;
5
13
  width?: number;
6
14
  height?: number;
@@ -67,6 +75,7 @@ export class PreviewView {
67
75
  static async probe(
68
76
  url: string,
69
77
  {
78
+ session = null,
70
79
  screenshot = false,
71
80
  width = 1280,
72
81
  height = 800,
@@ -90,6 +99,10 @@ export class PreviewView {
90
99
  deadline,
91
100
  new Error(`Timed out ${what} ${url}; the dev server may be rebuilding or stuck.`),
92
101
  );
102
+ if (session?.cookies.length) {
103
+ await within(view.navigate(session.url), "opening the session for");
104
+ await within(view.evaluate(PreviewView.cookieExpression(session.cookies)), "opening the session for");
105
+ }
93
106
  let page = await PreviewView.#load(view, url, settleMs, within);
94
107
  //? Right after a save the first load can render nothing (`[rscClient] module not loaded`); the next one has it.
95
108
  if (page.empty) {
@@ -99,7 +112,7 @@ export class PreviewView {
99
112
  const result: PreviewProbeResult = {
100
113
  url,
101
114
  finalUrl: page.href,
102
- status: page.status ?? (await PreviewView.#statusOf(page.href, deadline)),
115
+ status: page.status ?? (await PreviewView.#statusOf(page.href, deadline, session?.cookies ?? [])),
103
116
  title: page.title,
104
117
  text: page.text,
105
118
  consoleErrors: logs.filter((line) => line.startsWith("error")),
@@ -162,12 +175,21 @@ export class PreviewView {
162
175
  }
163
176
 
164
177
  //? webkit has no Navigation Timing `responseStatus`, so the status comes from asking the server again, unredirected.
165
- static async #statusOf(href: string, deadline: number) {
178
+ static async #statusOf(href: string, deadline: number, cookies: string[]) {
166
179
  const left = Math.max(1, deadline - Date.now());
167
- const response = await fetch(href, { redirect: "manual", signal: AbortSignal.timeout(left) }).catch(() => null);
180
+ const response = await fetch(href, {
181
+ redirect: "manual",
182
+ signal: AbortSignal.timeout(left),
183
+ ...(cookies.length ? { headers: { Cookie: cookies.join("; ") } } : {}),
184
+ }).catch(() => null);
168
185
  return response?.status ?? null;
169
186
  }
170
187
 
188
+ //? Written from a document: the webkit backend has no cookie API, and a page sends a cookie its script set like any other.
189
+ static cookieExpression(cookies: string[]) {
190
+ return `(() => { for (const pair of ${JSON.stringify(cookies)}) document.cookie = pair + "; Path=/; SameSite=Lax"; return true; })()`;
191
+ }
192
+
171
193
  static async #within<T>(work: Promise<T>, deadline: number, expiry: Error): Promise<T> {
172
194
  let timer: ReturnType<typeof setTimeout> | undefined;
173
195
  const expired = new Promise<never>((_, reject) => {