@junejs/server 0.1.3 → 0.2.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.
Files changed (128) hide show
  1. package/assets/icon-latin.LICENSE.txt +92 -0
  2. package/assets/icon-latin.ttf +0 -0
  3. package/dist/adapter-DcZ-W1-7.d.ts +62 -0
  4. package/dist/adapter.d.ts +2 -56
  5. package/dist/adapter.js +62 -5
  6. package/dist/agent-compile.d.ts +38 -0
  7. package/dist/agent-compile.js +145 -0
  8. package/dist/agent-discover.d.ts +4 -4
  9. package/dist/agent-discover.js +30 -44
  10. package/dist/agent-durable.d.ts +94 -19
  11. package/dist/agent-durable.js +647 -32
  12. package/dist/agent-native.d.ts +44 -13
  13. package/dist/agent-native.js +264 -27
  14. package/dist/app.d.ts +5 -5
  15. package/dist/app.js +42 -10
  16. package/dist/blob.d.ts +4 -5
  17. package/dist/build.d.ts +8 -30
  18. package/dist/build.js +135 -296
  19. package/dist/client-bundle.d.ts +8 -9
  20. package/dist/client-bundle.js +1 -1
  21. package/dist/config-freeze-CyXvNqi2.d.ts +17 -0
  22. package/dist/config-freeze.d.ts +2 -0
  23. package/dist/config-freeze.js +54 -0
  24. package/dist/config-loader.d.ts +3 -4
  25. package/dist/connection-auth.d.ts +38 -0
  26. package/dist/connection-auth.js +31 -0
  27. package/dist/content-freeze-CyiW2fRK.d.ts +4 -0
  28. package/dist/content-freeze.d.ts +2 -0
  29. package/dist/content-freeze.js +83 -0
  30. package/dist/content.d.ts +22 -9
  31. package/dist/content.js +43 -3
  32. package/dist/core-version.d.ts +4 -0
  33. package/dist/core-version.js +12 -0
  34. package/dist/css-modules-ambient.d.ts +2 -1
  35. package/dist/css-modules.d.ts +10 -11
  36. package/dist/css.d.ts +9 -10
  37. package/dist/d1-migrate.d.ts +6 -7
  38. package/dist/d1-migrate.js +3 -2
  39. package/dist/db.d.ts +2 -2
  40. package/dist/deploy.d.ts +3 -4
  41. package/dist/deploy.js +3 -2
  42. package/dist/dev-reload.d.ts +3 -4
  43. package/dist/dev.d.ts +8 -5
  44. package/dist/dev.js +40 -9
  45. package/dist/favicon.d.ts +37 -0
  46. package/dist/favicon.js +248 -0
  47. package/dist/host.d.ts +6 -5
  48. package/dist/host.js +2 -1
  49. package/dist/icon-letter.d.ts +3 -0
  50. package/dist/icon-letter.js +8 -0
  51. package/dist/index.d.ts +11 -5
  52. package/dist/index.js +9 -3
  53. package/dist/instrumentation.d.ts +2 -3
  54. package/dist/instrumentation.js +2 -1
  55. package/dist/island-registry.d.ts +6 -7
  56. package/dist/isolate-local.d.ts +5 -0
  57. package/dist/isolate-local.js +12 -0
  58. package/dist/kv.d.ts +3 -4
  59. package/dist/llms-links.d.ts +9 -0
  60. package/dist/llms-links.js +65 -0
  61. package/dist/manifest-CwTT1zVs.d.ts +11 -0
  62. package/dist/manifest.d.ts +2 -0
  63. package/dist/manifest.js +113 -0
  64. package/dist/negotiate.d.ts +4 -3
  65. package/dist/negotiate.js +24 -14
  66. package/dist/{pipeline-CCp9idQ4.d.ts → pipeline-BHUjBO0G.d.ts} +13 -1
  67. package/dist/pipeline.d.ts +2 -2
  68. package/dist/pipeline.js +286 -35
  69. package/dist/resources.d.ts +5 -6
  70. package/dist/route-rank.d.ts +6 -7
  71. package/dist/route-scan-BMbBzPIB.d.ts +20 -0
  72. package/dist/route-scan.d.ts +2 -0
  73. package/dist/route-scan.js +100 -0
  74. package/dist/router.d.ts +12 -13
  75. package/dist/router.js +51 -38
  76. package/dist/rsc-build.d.ts +6 -7
  77. package/dist/rsc-bundle.d.ts +6 -7
  78. package/dist/rsc-manifest.d.ts +5 -6
  79. package/dist/rsc-runtime/flight-render-routes.d.ts +3 -4
  80. package/dist/rsc-runtime/flight-render.d.ts +2 -3
  81. package/dist/rsc-runtime/flight-to-html.d.ts +2 -3
  82. package/dist/rsc-runtime/flight-to-html.js +3 -2
  83. package/dist/rsc-runtime/rsc-worker.js +11 -8
  84. package/dist/rsc-runtime/rsdw-shims.d.ts +2 -1
  85. package/dist/segment.d.ts +4 -5
  86. package/dist/sqlite-driver.d.ts +11 -11
  87. package/dist/sqlite-driver.js +17 -4
  88. package/dist/static-files.d.ts +4 -5
  89. package/dist/tsconfig-jsx.d.ts +4 -4
  90. package/dist/tsconfig-jsx.js +1 -1
  91. package/dist/turn-events.d.ts +4 -0
  92. package/dist/turn-events.js +46 -0
  93. package/dist/web-manifest.d.ts +5 -0
  94. package/dist/web-manifest.js +42 -0
  95. package/dist/worker-2qbQjj2c.d.ts +64 -0
  96. package/dist/worker.d.ts +2 -57
  97. package/dist/worker.js +69 -27
  98. package/package.json +22 -9
  99. package/src/adapter.ts +84 -3
  100. package/src/agent-compile.ts +271 -0
  101. package/src/agent-discover.ts +77 -63
  102. package/src/agent-durable.ts +998 -30
  103. package/src/agent-native.ts +370 -35
  104. package/src/app.ts +75 -6
  105. package/src/build.ts +230 -446
  106. package/src/config-freeze.ts +109 -0
  107. package/src/connection-auth.ts +101 -0
  108. package/src/content-freeze.ts +151 -0
  109. package/src/content.ts +55 -4
  110. package/src/core-version.ts +34 -0
  111. package/src/dev.ts +41 -8
  112. package/src/favicon.ts +325 -0
  113. package/src/host.ts +4 -3
  114. package/src/icon-letter.ts +14 -0
  115. package/src/index.ts +22 -0
  116. package/src/isolate-local.ts +33 -0
  117. package/src/llms-links.ts +96 -0
  118. package/src/manifest.ts +130 -0
  119. package/src/negotiate.ts +39 -15
  120. package/src/pipeline.ts +494 -44
  121. package/src/route-scan.ts +161 -0
  122. package/src/router.ts +66 -54
  123. package/src/rsc-runtime/rsc-worker.tsx +5 -4
  124. package/src/sqlite-driver.ts +36 -6
  125. package/src/tsconfig-jsx.ts +2 -2
  126. package/src/turn-events.ts +43 -0
  127. package/src/web-manifest.ts +38 -0
  128. package/src/worker.ts +131 -35
package/src/build.ts CHANGED
@@ -6,45 +6,53 @@
6
6
  // SAME pipeline as dev (pipeline.ts), so its surfaces are byte-equivalent —
7
7
  // proven by test/parity.test.ts, not hoped for.
8
8
  //
9
- // Two entry points:
10
- // buildManifest(appRoot) → an in-process WorkerManifest (freeze only; used by
11
- // the parity test and by prerender — same render path as the bundle).
12
- // juneBuild(appRoot) → the full build: content freeze + generated entry +
13
- // Rolldown bundle (workerd conditions, binary externals) +
14
- // prerender-through-the-worker + wrangler config.
9
+ // The build's separable stages live in sibling modules (re-exported here so
10
+ // consumers keep one import root):
11
+ // route-scan.ts — app/ + .june/routes/ discovery and merge (scanAppRoutes)
12
+ // content-freeze.ts — content/ → app/_content.ts (generateContent)
13
+ // config-freeze.ts — june.config.ts → serializable worker bits (freezeConfig)
14
+ // manifest.ts — the in-process freeze (buildManifest; parity + prerender)
15
+ // This file keeps the full-build orchestration: juneBuild = content freeze +
16
+ // generated entry + Rolldown bundle (workerd conditions, binary externals) +
17
+ // prerender-through-the-worker + wrangler config.
15
18
  //
16
19
  // REMINDER #4: nothing in the worker graph may statically import node:*. The
17
20
  // content freeze (content/*.md → app/_content.ts) is what removes fs from the
18
21
  // dynamic route's graph; the worker reads frozen data, never the filesystem.
19
22
 
20
- import { execFileSync } from "node:child_process";
21
23
  import { createHash } from "node:crypto";
22
24
  import { existsSync, lstatSync } from "node:fs";
23
- import { copyFile, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
25
+ import { copyFile, mkdir, readdir, rm, writeFile } from "node:fs/promises";
24
26
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
25
- import { pathToFileURL } from "node:url";
26
27
 
27
- import { findJuneConfigPath, loadJuneConfig } from "./config-loader";
28
- import { resolveAgent, resolveClientRouter, resolveSpeculationRules } from "@junejs/core/config";
29
- import type { ContentSource, JuneConfig } from "@junejs/core/config";
28
+ import { loadJuneConfig } from "./config-loader";
30
29
  import { buildLinkHeader } from "@junejs/core/discovery";
30
+ import { PRERENDER_ORIGIN } from "@junejs/core/document";
31
31
  import { localeHref } from "@junejs/core/i18n";
32
- import { routeFromModule, type BrandedRoute } from "@junejs/core/route";
33
- import { workers, vercel, deno, staticSite, type JuneAdapter, type ResourcePlan } from "./adapter";
34
- import type { DocumentConfig } from "@junejs/core/document";
35
- import { generateContentModule } from "./content";
36
- import { createWorker, type WorkerManifest } from "./worker";
32
+ import type { BrandedRoute } from "@junejs/core/route";
33
+ import type { ResourcePlan } from "./adapter";
34
+ import { generateAgentModule } from "./agent-compile";
35
+ import { freezeConfig, resolveDeployAdapter, workerName } from "./config-freeze";
36
+ import { generateContent } from "./content-freeze";
37
+ import { GENERATED_ICONS, googleFontFetcher, publicFileCheck, renderIcons, resolveIcons } from "./favicon";
38
+ import { createWorker } from "./worker";
39
+ import { buildManifest, importLayout, type ImportedLayout } from "./manifest";
37
40
  import { findMiddlewareFile } from "./router";
41
+ import { scanAppRoutes } from "./route-scan";
38
42
  import { resolveBoundary } from "./segment";
39
- import type { ExtraHandler, LayoutComponent, LoadingComponent, ResourceHandler } from "./pipeline";
40
- import { findClientEntry, bundleClientToFile, CLIENT_SCRIPT_URL } from "./client-bundle";
43
+ import { findClientEntry, bundleClientToFile } from "./client-bundle";
41
44
  import { RESERVED_PREFIX } from "./static-files";
42
45
  import { jsxTransform } from "./tsconfig-jsx";
43
46
  import { generateIslandRegistry } from "./island-registry";
44
47
  import { buildRsc, findRscRoutes } from "./rsc-build";
45
- import { cssTargets, findGlobalCss, globalCssUsesTailwind, minifyCss, processCss, STYLES_URL } from "./css";
48
+ import { cssTargets, minifyCss, processCss } from "./css";
46
49
  import { buildModuleCss, rolldownCssModulesPlugin, registerCssModules } from "./css-modules";
47
50
 
51
+ export { scanRoutes, scanAppRoutes, type RouteEntry } from "./route-scan";
52
+ export { generateContent } from "./content-freeze";
53
+ export { freezeConfig, normalizeBase, resolveDeployAdapter, workerName } from "./config-freeze";
54
+ export { buildManifest } from "./manifest";
55
+
48
56
  export type BuildResult = {
49
57
  outFile: string;
50
58
  routes: string[];
@@ -53,412 +61,12 @@ export type BuildResult = {
53
61
  prerendered: string[];
54
62
  };
55
63
 
56
- // The segment layout CHAIN root→leaf: every directory level (route groups
57
- // included) may contribute a layout.* that wraps routes below it.
58
- type RouteEntry = {
59
- path: string;
60
- file: string;
61
- dynamic: boolean;
62
- resource?: boolean; // a route.* resource route (raw-Response handler), not a page
63
- generated?: boolean; // scanned from .june/routes/ — ranks after every app/ route, as in dev
64
- layouts: string[];
65
- loading?: string; // nearest loading.tsx up the tree → streaming Suspense fallback
66
- };
67
-
68
- const PAGE_BASENAMES = new Set(["page", "index"]);
69
- const ROUTE_EXTS = [".tsx", ".jsx", ".ts", ".js"];
70
-
71
- const isRouteGroup = (name: string) => /^\(.+\)$/.test(name);
72
-
73
64
  // Bun built-ins (`bun`, `bun:sqlite`, …) exist only at the Bun runtime and must never enter the
74
65
  // workerd graph. Marking them external keeps rolldown from constant-folding the `const x = "bun";
75
66
  // import(x)` runtime guard (in @junejs/core's cache.ts) and warning UNRESOLVED_IMPORT. Exported so
76
67
  // the build keeps externalizing them — see test/build-externals.test.ts.
77
68
  export const isBunSpecifier = (id: string): boolean => id === "bun" || id.startsWith("bun:");
78
69
 
79
- // Resolve the deploy adapter from config. An explicit `adapter` INSTANCE wins; otherwise the
80
- // `target` NAME selects the matching built-in — so a DECLARATIVE config (e.g. kura.toml, which
81
- // can't express a `vercel()` call) can pick any target by string, not just "static". "workers" is
82
- // the default. Kept in lockstep with deploy.ts's own target→deployer switch so a build for one
83
- // target is never deployed as another. vercel()/deno() take their opts (runtime/regions, org/app)
84
- // which JuneConfig.deploy doesn't carry yet, so they use defaults here.
85
- export function resolveDeployAdapter(deploy: JuneConfig["deploy"]): JuneAdapter {
86
- if (deploy?.adapter) return deploy.adapter as JuneAdapter;
87
- switch (deploy?.target) {
88
- case "static":
89
- return staticSite();
90
- case "vercel":
91
- return vercel();
92
- case "deno":
93
- return deno();
94
- default:
95
- return workers({ name: deploy?.name, domain: deploy?.domain });
96
- }
97
- }
98
-
99
- function segmentFile(dir: string, base: string): string | undefined {
100
- return ROUTE_EXTS.map((e) => join(dir, `${base}${e}`)).find(existsSync);
101
- }
102
-
103
- // Walk app/ for page.* files → route paths (mirrors router.ts conventions:
104
- // route groups vanish from URLs, `_`-prefixed entries are private), carrying the
105
- // layout chain accumulated from each directory level.
106
- export async function scanRoutes(
107
- appDir: string,
108
- dir = appDir,
109
- layouts: string[] = [],
110
- out: RouteEntry[] = [],
111
- loading?: string,
112
- ): Promise<RouteEntry[]> {
113
- const ownLayout = segmentFile(dir, "layout");
114
- const chain = ownLayout ? [...layouts, ownLayout] : layouts;
115
- const nearestLoading = segmentFile(dir, "loading") ?? loading;
116
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
117
- for (const e of entries) {
118
- if (e.name.startsWith("_") || e.name.startsWith(".")) continue;
119
- const full = join(dir, e.name);
120
- if (e.isDirectory()) {
121
- await scanRoutes(appDir, full, chain, out, nearestLoading);
122
- continue;
123
- }
124
- const ext = e.name.match(/\.[^.]+$/)?.[0] ?? "";
125
- if (!ROUTE_EXTS.includes(ext)) continue;
126
- const base = basename(e.name, ext);
127
- const resource = base === "route";
128
- if (!PAGE_BASENAMES.has(base) && !resource) continue;
129
- const relDir = relative(appDir, dir);
130
- const segments = relDir === "" ? [] : relDir.split(sep).filter((s) => !isRouteGroup(s));
131
- const path = "/" + segments.join("/");
132
- out.push({
133
- path: path === "/" ? "/" : path,
134
- file: full,
135
- dynamic: /\[.+\]/.test(path),
136
- resource,
137
- layouts: chain,
138
- loading: nearestLoading,
139
- });
140
- }
141
- return out;
142
- }
143
-
144
- // content/<collection>/*.md → app/_content.ts (the build-time content manifest).
145
- // This is the FREEZE that removes node:fs from the worker graph: routes import
146
- // frozen entries from ./_content instead of reading the filesystem at request.
147
- //
148
- // Extra sources (config `content.sources`) merge dirs OUTSIDE `content/` into named
149
- // collections — the docs-as-code seam (a repo's own `docs/` feeds the site directly).
150
- // Their dirs resolve against the app root, so "../docs" reaches a sibling directory.
151
- //
152
- // Locale buckets are DECLARED, not guessed: only dirs named in config i18n
153
- // (defaultLocale + locales keys) split off as locale mirrors. Guessing by shape
154
- // (the old BCP-47 regex) silently swallowed any 2–3-letter folder — `cli/`,
155
- // `sdk/`, `api/`, `faq/` all read as locales and vanished from the default set.
156
- // No i18n config ⇒ NO buckets (an undeclared locale is not a locale). The regex
157
- // remains only as the fallback when the config itself cannot be loaded.
158
- export async function generateContent(appRoot: string): Promise<string[]> {
159
- const contentDir = join(appRoot, "content");
160
- // app/ is the output dir for _content.ts (and the seed). Ensure it exists so the now-always
161
- // write can't throw an opaque ENOENT when called standalone (e.g. `june gen`); the full build's
162
- // own "no app/ directory" check runs earlier, so this never masks that clearer error.
163
- await mkdir(join(appRoot, "app"), { recursive: true });
164
- const emit = async (sources: ContentSource[], knownLocales: readonly string[] | undefined): Promise<string[]> => {
165
- // Emission (incl. the per-locale layout and source merging) lives in ./content so it's
166
- // pure and unit-testable; this stays the thin fs wrapper.
167
- const { code, names } = generateContentModule(contentDir, knownLocales, sources);
168
- // Always write, even with zero collections: `code` still carries the canonical ContentEntry
169
- // type, which is the single source of truth the bootstrap seed appends its stubs against (an
170
- // app with no local content/ — docs-as-code — needs this valid empty module to exist).
171
- await writeFile(join(appRoot, "app", "_content.ts"), code);
172
- return names;
173
- };
174
- const resolveSources = (sources: ContentSource[]): ContentSource[] =>
175
- sources.map((s) => ({ ...s, dir: resolve(appRoot, s.dir) }));
176
- const declaredLocales = (config: JuneConfig): string[] =>
177
- config.i18n ? [...new Set([config.i18n.defaultLocale, ...Object.keys(config.i18n.locales)])] : [];
178
- // Learn sources + locales from june.config.ts — TOLERANTLY. A wrapper-generated config (e.g.
179
- // Kura's) imports app/_content.ts, which does not exist before the FIRST freeze. So on a failed
180
- // config load: generate a default scan to create that import's target, then re-probe the config
181
- // and regenerate with the real sources/locales. Self-healing, no bootstrap flag. Content errors
182
- // from emit() (slug collision, missing source dir) stay loud — only the CONFIG LOAD is tolerated.
183
- let config: JuneConfig | null = null;
184
- try {
185
- config = await loadJuneConfig(appRoot);
186
- } catch {
187
- /* two-pass below */
188
- }
189
- if (config) return emit(resolveSources(config.content?.sources ?? []), declaredLocales(config));
190
- // Pass 1 (throwaway when the probe succeeds): legacy regex locale detection, since the
191
- // declared set is unknowable without the config. emit() writes app/_content.ts with the
192
- // canonical ContentEntry type plus a `const` per collection FOUND — but a docs-as-code app
193
- // keeps ALL content in external content.sources with NO local content/, so it finds zero
194
- // collections and thus emits no EXPORTS (no `DOCS`). seedContentImports then appends stubs for
195
- // the exact names the config imports (e.g. Kura's `import { DOCS }`), so the re-probe can load.
196
- const names = await emit([], undefined);
197
- await seedContentImports(appRoot);
198
- const probed = probeConfigFresh(appRoot);
199
- if (probed === null) {
200
- console.warn("[june gen] june.config.ts failed to load — content.sources/i18n locales (if any) not applied");
201
- return names;
202
- }
203
- return emit(resolveSources(probed.sources), probed.locales);
204
- }
205
-
206
- // Bootstrap seed: ensure app/_content.ts exports every name the config imports from it, so the
207
- // re-probe's config load resolves BEFORE the first real freeze. A docs-as-code app (content only
208
- // in external content.sources, no local content/) leaves Pass 1's default scan empty — nothing
209
- // seeds the collections — so here we append stubs for the EXACT named imports the config takes
210
- // from the app/_content module (a bare `import { DOCS }` of it → `export const DOCS = []`). The
211
- // caller's emit() already wrote the module's canonical ContentEntry type (even when empty), so the
212
- // stubs type against that single source of truth. Overwritten by the real freeze that follows a
213
- // successful probe; a no-op once content exists.
214
- async function seedContentImports(appRoot: string): Promise<void> {
215
- const cfgPath = findJuneConfigPath(appRoot);
216
- if (!cfgPath) return;
217
- const contentFile = join(appRoot, "app", "_content.ts");
218
- const current = existsSync(contentFile) ? await readFile(contentFile, "utf8") : "";
219
- const cfgSrc = await readFile(cfgPath, "utf8");
220
- // Only stub valid JS identifiers — a name carrying comments/other tokens (rare, but valid TS)
221
- // must never reach `new RegExp(...)` (would throw) or the emitted stub (would be invalid TS).
222
- const isIdent = (s: string): boolean => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s);
223
- // A Set so a name matched more than once (e.g. a comment mentioning the import + the real one)
224
- // yields ONE stub — a duplicate `export const <name>` would be invalid TS. Also skip names the
225
- // module already exports.
226
- const seen = new Set<string>();
227
- const stubs: string[] = [];
228
- // Each named `import { A, B as C }` the config takes from the app/_content module → stub each.
229
- // The `(?:\.\w+)?` tolerates an explicit extension (`app/_content.ts`/`.js`/`.mjs`), which
230
- // NodeNext / verbatimModuleSyntax configs require — else the import goes undetected and unstubbed.
231
- for (const m of cfgSrc.matchAll(/import\s*(?:type\s+)?\{([^}]*)\}\s*from\s*["'][^"']*app\/_content(?:\.\w+)?["']/g)) {
232
- // Strip block + line comments from the specifier list BEFORE splitting: a valid
233
- // `{ DOCS /* keep */ }` must still yield the identifier `DOCS` (not be dropped), and a comment
234
- // could otherwise carry a `,` that breaks the split. Then drop `type` markers per specifier.
235
- const inner = (m[1] ?? "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
236
- for (const part of inner.split(",")) {
237
- const name = part.replace(/\btype\b/g, "").split(/\s+as\s+/).pop()?.trim();
238
- if (!name || !isIdent(name) || seen.has(name)) continue;
239
- seen.add(name);
240
- // Escape before interpolating: a valid identifier may contain `$`, a regex metachar (an
241
- // anchor), which would corrupt the already-exported check. The stub below uses the raw name.
242
- const reName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
243
- if (!new RegExp(`export (?:const|function|type) ${reName}\\b`).test(current)) {
244
- stubs.push(`export const ${name}: ContentEntry[] = [];`);
245
- }
246
- }
247
- }
248
- if (stubs.length) await writeFile(contentFile, current + stubs.join("\n") + "\n");
249
- }
250
-
251
- // Re-probe ONLY the content-relevant config (sources + declared i18n locales) in a FRESH
252
- // subprocess. The bootstrap retry can't re-import in-process: a failed ESM load is cached as
253
- // errored, and Bun also caches the failed RESOLUTION of the config's own imports — so a
254
- // same-process retry (even cache-busted) re-rejects after the missing app/_content.ts appears.
255
- // A child process has a clean module map, and both fields are plain JSON, so they survive the
256
- // pipe. Returns null when the config is genuinely broken.
257
- function probeConfigFresh(appRoot: string): { sources: ContentSource[]; locales: string[] } | null {
258
- const path = findJuneConfigPath(appRoot);
259
- if (!path) return { sources: [], locales: [] };
260
- // Markers isolate the JSON from anything the config prints at import time. `.then` (not TLA)
261
- // so the eval works as CJS under both `bun -e` and `node -e`; execArgv carries loader flags
262
- // (e.g. --experimental-strip-types) so the child can read the same TS config the parent does.
263
- const code =
264
- `import(${JSON.stringify(pathToFileURL(path).href)}).then(` +
265
- `(m) => { const c = m.default ?? {}; process.stdout.write("\\n__JUNE_CONTENT__" + JSON.stringify({ ` +
266
- `sources: c.content?.sources ?? [], ` +
267
- `locales: c.i18n ? [...new Set([c.i18n.defaultLocale, ...Object.keys(c.i18n.locales ?? {})])] : [] ` +
268
- `}) + "__END__"); }, () => process.exit(42));`;
269
- try {
270
- const out = execFileSync(process.execPath, [...process.execArgv, "-e", code], {
271
- encoding: "utf8",
272
- stdio: ["ignore", "pipe", "ignore"],
273
- });
274
- const m = out.match(/__JUNE_CONTENT__(.*?)__END__/s);
275
- return m ? (JSON.parse(m[1]!) as { sources: ContentSource[]; locales: string[] }) : null;
276
- } catch {
277
- return null;
278
- }
279
- }
280
-
281
- // Freeze june.config.ts → the serializable bits the worker inlines.
282
- export async function freezeConfig(appRoot: string): Promise<{
283
- document: DocumentConfig;
284
- agent: WorkerManifest["agent"];
285
- i18n: WorkerManifest["i18n"];
286
- earlyHints: string[];
287
- buildExternal: string[];
288
- }> {
289
- const cfg = await loadJuneConfig(appRoot);
290
- // An app with a client entry gets the islands runtime URL frozen into its
291
- // document. Detected HERE (not just in juneBuild) so the prerender path —
292
- // which re-freezes through buildManifest — sets the SAME clientScript, keeping
293
- // prerendered pages byte-equivalent to the live worker (parity).
294
- // Client entry: app/_client.* wins; fall back to .june/routes/_client.* (framework slot).
295
- const hasClient =
296
- findClientEntry(join(appRoot, "app")) !== undefined ||
297
- findClientEntry(join(appRoot, ".june", "routes")) !== undefined;
298
- const hasCss = findGlobalCss(join(appRoot, "app")) !== null;
299
- return {
300
- document: {
301
- site: cfg.site ?? {},
302
- speculationRules: resolveSpeculationRules(cfg.speculation ?? undefined),
303
- speculationDelivery: "inline",
304
- viewTransitions: cfg.viewTransitions ?? true,
305
- // Default the baseline reset OFF when the app uses Tailwind (its Preflight is the reset).
306
- cssReset: cfg.cssReset ?? !globalCssUsesTailwind(join(appRoot, "app")),
307
- clientRouter: resolveClientRouter(cfg.clientRouter),
308
- clientScript: hasClient ? CLIENT_SCRIPT_URL : null,
309
- styles: hasCss ? STYLES_URL : null,
310
- // Deploy subpath (JuneConfig.basePath). Frozen so the document prefixes its
311
- // asset URLs; the prerender path re-freezes through buildManifest and gets the
312
- // same value, keeping static pages' asset links correct under the subpath.
313
- basePath: normalizeBase(cfg.basePath),
314
- },
315
- agent: resolveAgent(cfg.agent),
316
- // Pass i18n through as-is: the in-process buildManifest keeps a resolveLocale
317
- // hook (parity test), and the codegen JSON.stringify below drops the function
318
- // (worker hook support is the codegen pass — see the manifest field comment).
319
- i18n: cfg.i18n,
320
- earlyHints: cfg.earlyHints ?? [],
321
- buildExternal: cfg.build?.external ?? [],
322
- };
323
- }
324
-
325
- // A deploy basePath is stored with a leading slash and no trailing slash; empty
326
- // ("" — the default) means a root deploy. So "/openab/docs/" → "/openab/docs",
327
- // "openab" → "/openab", undefined → "".
328
- export function normalizeBase(base?: string): string {
329
- if (!base) return "";
330
- const b = base.startsWith("/") ? base : `/${base}`;
331
- return b.endsWith("/") ? b.slice(0, -1) : b;
332
- }
333
-
334
- type ImportedLayout = { component: LayoutComponent; boundary: boolean };
335
- async function importLayout(file: string): Promise<ImportedLayout | null> {
336
- const mod = (await import(pathToFileURL(file).href)) as {
337
- default?: LayoutComponent;
338
- segmentBoundary?: unknown;
339
- };
340
- return typeof mod.default === "function"
341
- ? { component: mod.default, boundary: mod.segmentBoundary === true }
342
- : null;
343
- }
344
-
345
- // A wrangler-valid worker name from a package name or directory name. Wrangler requires lowercase
346
- // [a-z0-9-] not starting/ending with a dash — so a SCOPED package name (`@scope/pkg`) must lose its
347
- // scope (else the `@` sanitizes to a leading dash and wrangler rejects the config). Drop the scope,
348
- // lowercase, collapse non-alphanumerics to single dashes, trim edge dashes; fall back to "app" if
349
- // nothing survives (e.g. an all-punctuation name). Exported for tests.
350
- export function workerName(raw: string): string {
351
- return (
352
- raw
353
- .replace(/^@[^/]+\//, "")
354
- .toLowerCase()
355
- .replace(/[^a-z0-9-]+/g, "-")
356
- .replace(/^-+|-+$/g, "") || "app"
357
- );
358
- }
359
-
360
- // The FREEZE, in-process: import route modules + layouts, build the manifest a
361
- // createWorker() can run immediately. Used by prerender and by the parity test
362
- // (its render path is identical to the Rolldown-bundled worker).
363
- export async function buildManifest(appRoot: string): Promise<WorkerManifest> {
364
- const appDir = join(appRoot, "app");
365
- const juneRoutesDir = join(appRoot, ".june", "routes");
366
- const frozen = await freezeConfig(appRoot);
367
-
368
- // Merge routes: app/ takes priority over .june/routes/ (app/ is the escape hatch).
369
- // .june/routes/ is the convention slot for framework-generated routes (e.g. kura
370
- // writes its docs/search/og routes there so the user never manages boilerplate).
371
- const appRoutes = await scanRoutes(appDir);
372
- const frameworkRoutes = existsSync(juneRoutesDir) ? await scanRoutes(juneRoutesDir) : [];
373
- const appPaths = new Set(appRoutes.map((r) => r.path));
374
- const scanned = [
375
- ...appRoutes,
376
- ...frameworkRoutes.filter((r) => !appPaths.has(r.path)).map((r) => ({ ...r, generated: true })),
377
- ].sort((a, b) => a.path.localeCompare(b.path));
378
- const generatedRoutes = scanned.filter((r) => r.generated).map((r) => r.path);
379
-
380
- const layoutCache = new Map<string, ImportedLayout | null>();
381
- const loadCached = async (f: string): Promise<ImportedLayout | null> => {
382
- if (!layoutCache.has(f)) layoutCache.set(f, await importLayout(f));
383
- return layoutCache.get(f) ?? null;
384
- };
385
- // The chain (root→leaf) + boundary index + shell key, via the SHARED resolver
386
- // (the one place the deepest-wins rule lives), so the frozen manifest and the
387
- // dev resolver can't drift — the parity contract.
388
- const componentsFor = async (
389
- files: string[],
390
- ): Promise<{ chain: LayoutComponent[]; boundaryIndex: number | null; key: string | null }> => {
391
- const items = [];
392
- for (const f of files) {
393
- const c = await loadCached(f);
394
- items.push({ file: f, entry: c?.component ?? null, boundary: !!c?.boundary });
395
- }
396
- return resolveBoundary(items);
397
- };
398
-
399
- const loadingCache = new Map<string, LoadingComponent | null>();
400
- const loadingFor = async (file?: string): Promise<LoadingComponent | undefined> => {
401
- if (!file) return undefined;
402
- if (!loadingCache.has(file)) {
403
- const loaded = await importLayout(file);
404
- loadingCache.set(file, loaded ? (loaded.component as LoadingComponent) : null);
405
- }
406
- return loadingCache.get(file) ?? undefined;
407
- };
408
-
409
- const routes: Record<string, BrandedRoute> = {};
410
- const dynamicRoutes: Array<{ pattern: string; def: BrandedRoute }> = [];
411
- const resourceRoutes: Array<{ pattern: string; handler: ResourceHandler }> = [];
412
- const layoutChains: Record<string, LayoutComponent[]> = {};
413
- const layoutBoundaries: Record<string, { index: number; key: string }> = {};
414
- const loadings: Record<string, LoadingComponent> = {};
415
-
416
- for (const r of scanned) {
417
- const mod = await import(pathToFileURL(r.file).href);
418
- // Resource route (route.*): the default export is the Response handler.
419
- if (r.resource) {
420
- const handler = (mod as { default?: unknown }).default;
421
- if (typeof handler === "function") resourceRoutes.push({ pattern: r.path, handler: handler as ResourceHandler });
422
- continue;
423
- }
424
- const def = routeFromModule(mod);
425
- if (!def) continue;
426
- const { chain, boundaryIndex, key } = await componentsFor(r.layouts);
427
- const loading = await loadingFor(r.loading);
428
- if (r.dynamic) {
429
- dynamicRoutes.push({ pattern: r.path, def });
430
- layoutChains[r.path] = chain;
431
- } else {
432
- routes[r.path] = def;
433
- layoutChains[r.path] = chain;
434
- }
435
- if (boundaryIndex !== null && key !== null) layoutBoundaries[r.path] = { index: boundaryIndex, key };
436
- if (loading) loadings[r.path] = loading;
437
- }
438
-
439
- let extra: ExtraHandler | undefined;
440
- const extraFile = findMiddlewareFile(appDir);
441
- if (extraFile) {
442
- const mod = (await import(pathToFileURL(extraFile).href)) as { default?: unknown };
443
- if (typeof mod.default === "function") extra = mod.default as ExtraHandler;
444
- }
445
-
446
- return {
447
- routes,
448
- dynamicRoutes,
449
- resourceRoutes,
450
- ...(generatedRoutes.length ? { generatedRoutes } : {}),
451
- layoutChains,
452
- layoutBoundaries,
453
- loadings,
454
- document: frozen.document,
455
- agent: frozen.agent,
456
- i18n: frozen.i18n,
457
- earlyHints: frozen.earlyHints,
458
- extra,
459
- };
460
- }
461
-
462
70
  function importPath(fromDir: string, file: string): string {
463
71
  const p = relative(fromDir, file).split(sep).join("/").replace(/\.[^.]+$/, "");
464
72
  return p.startsWith(".") ? p : `./${p}`;
@@ -490,14 +98,7 @@ export async function juneBuild(
490
98
 
491
99
  const contentCollections = await generateContent(appRoot);
492
100
  // Same merge as buildManifest: app/ takes priority over .june/routes/.
493
- const juneRoutesDir2 = join(appRoot, ".june", "routes");
494
- const appRoutes2 = await scanRoutes(appDir);
495
- const frameworkRoutes2 = existsSync(juneRoutesDir2) ? await scanRoutes(juneRoutesDir2) : [];
496
- const appPaths2 = new Set(appRoutes2.map((r) => r.path));
497
- const routes = [
498
- ...appRoutes2,
499
- ...frameworkRoutes2.filter((r) => !appPaths2.has(r.path)).map((r) => ({ ...r, generated: true })),
500
- ].sort((a, b) => a.path.localeCompare(b.path));
101
+ const routes = await scanAppRoutes(appRoot);
501
102
  if (routes.length === 0) throw new Error(`no page.* routes found under ${appDir} or .june/routes/`);
502
103
 
503
104
  const frozen = await freezeConfig(appRoot);
@@ -524,6 +125,52 @@ export async function juneBuild(
524
125
  config: fullConfig,
525
126
  });
526
127
 
128
+ // ---- durable agent (the F7 mount): compile app/agent → _agent.gen.ts ------
129
+ // The generated entry mounts the compiled module statically (fs discovery
130
+ // can't run on workerd) and exports the per-session Durable Object class.
131
+ // Only a target with Durable Objects can host the session actor — elsewhere
132
+ // the agent surface is skipped with a notice, and an app without an agent/
133
+ // directory emits a byte-identical entry (the parity guarantee).
134
+ const agentDir = join(appDir, frozen.agent.runtime.dir);
135
+ let agentModule: { file: string } | null = null;
136
+ if (frozen.agent.runtime.enabled) {
137
+ const generated = generateAgentModule(agentDir);
138
+ if (generated && adapter.capabilities.durableObjects) {
139
+ agentModule = generated;
140
+ } else if (generated) {
141
+ console.warn(
142
+ `[june build] app/${frozen.agent.runtime.dir}/ found, but the ${adapter.name}() target has no Durable Objects — the durable agent is not mounted.`,
143
+ );
144
+ }
145
+ }
146
+ if (agentModule) {
147
+ // The generated DO's model is Claude, and workerd has no runtime module
148
+ // resolution — the SDK must be a real dependency of the app so the entry's
149
+ // STATIC import bundles it (@junejs/core treats it as an optional peer; the
150
+ // adapter's own lazy import can never be bundled). Fail the build with the
151
+ // fix, never ship a worker whose first model turn dies on a bare import.
152
+ // An explicit node_modules walk, not a resolver API: the check must behave
153
+ // identically on every host (Bun.resolveSync missed a symlinked scoped
154
+ // package on Linux CI that it found on macOS), and Rolldown does its own
155
+ // resolution at bundle time anyway — this is a preflight, not the resolver.
156
+ const sdkResolvable = (fromDir: string): boolean => {
157
+ // Absolute first: with a relative root (juneBuild(".")), dirname(".") is
158
+ // still "." and the walk would stop before reaching a hoisted parent.
159
+ for (let d = resolve(fromDir); ; ) {
160
+ if (existsSync(join(d, "node_modules", "@anthropic-ai", "sdk", "package.json"))) return true;
161
+ const parent = dirname(d);
162
+ if (parent === d) return false;
163
+ d = parent;
164
+ }
165
+ };
166
+ if (!sdkResolvable(appRoot)) {
167
+ throw new Error(
168
+ `app/${frozen.agent.runtime.dir}/ mounts a durable agent whose model is Claude — ` +
169
+ `add the SDK to the app so it bundles for workerd: bun add @anthropic-ai/sdk`,
170
+ );
171
+ }
172
+ }
173
+
527
174
  // Compile the global stylesheet ONCE and content-hash it: the built worker and
528
175
  // prerendered HTML link `/global.<hash>.css`, served immutable (cache forever,
529
176
  // a content change ships a new URL → no revalidation, no stale window). Dev
@@ -673,7 +320,9 @@ export async function juneBuild(
673
320
  // The Link header is frozen here from the same builder the pipeline uses, so
674
321
  // the static and dynamic surfaces advertise identically. The adapter wraps the
675
322
  // portable pipeline for its target (workers() → withAssets).
676
- const linkHeader = buildLinkHeader(frozen.agent);
323
+ // (catalogs: the same publication rule as the pipeline's catalogOrigin — a
324
+ // basePath site publishes no /.well-known catalog, so it links none.)
325
+ const linkHeader = buildLinkHeader(frozen.agent, { catalogs: !frozen.document.basePath });
677
326
  const adapterEntry = adapter.entry({ linkHeader });
678
327
 
679
328
  // Resources (when declared) are bound from the worker's env (env.DB → D1) by
@@ -700,11 +349,15 @@ export async function juneBuild(
700
349
  } else if (hasResources) {
701
350
  imports.push(`import { bindWorkerResources } from "@junejs/server/resources";`);
702
351
  }
703
- const resourcesField = tursoDb
704
- ? `\n resources: memoizeResources({ db: turso() }),`
352
+ // One expression, TWO instances: the pipeline (createWorker) and the durable
353
+ // agent's DO each open their own provider — the DO is a separate isolate whose
354
+ // env must not be captured by the worker-side memoization.
355
+ const resourcesExpr = tursoDb
356
+ ? `memoizeResources({ db: turso() })`
705
357
  : hasResources
706
- ? `\n resources: bindWorkerResources(${JSON.stringify(resourceFlags)}),`
707
- : "";
358
+ ? `bindWorkerResources(${JSON.stringify(resourceFlags)})`
359
+ : null;
360
+ const resourcesField = resourcesExpr ? `\n resources: ${resourcesExpr},` : "";
708
361
 
709
362
  // Opt-in Tier-3 data layer: import its installDataLayer from the declared module
710
363
  // and call it at worker boot — the prod twin of the dev host's dataLayer.install()
@@ -732,10 +385,56 @@ export async function juneBuild(
732
385
  }
733
386
  const servicesField = servicesModule ? `\n services: __appServices,` : "";
734
387
 
388
+ // Durable agent: import the compiled agent module + the DO shell pieces, set
389
+ // agentName on the manifest (what activates createWorker's chat routing), and
390
+ // export the DO class the adapter's wrangler binding names. cloudflare:workers
391
+ // is a workerd runtime module — external to the bundle (see the predicate below).
392
+ if (agentModule) {
393
+ imports.push(`import __agentModule from ${JSON.stringify(importPath(genDir, agentModule.file))};`);
394
+ imports.push(`import { assembleDurable } from "@junejs/core/agent-config";`);
395
+ imports.push(`import { anthropic } from "@junejs/core/agent-models";`);
396
+ imports.push(`import { AgentDurableObject } from "@junejs/server/agent-durable";`);
397
+ imports.push(`import { DurableObject } from "cloudflare:workers";`);
398
+ // STATIC so Rolldown bundles the SDK (the adapter's own import is a
399
+ // non-literal lazy specifier — deliberately unbundleable); injected via
400
+ // anthropic({ client }), which skips that lazy path entirely.
401
+ imports.push(`import Anthropic from "@anthropic-ai/sdk";`);
402
+ }
403
+ // Assembled BEFORE createWorker: the manifest consumes the channels (worker-
404
+ // side webhook routing) and the DO class consumes the full definition.
405
+ const agentPreamble = agentModule ? `\nconst __agentDef = assembleDurable(__agentModule);\n` : "";
406
+ const agentNameField = agentModule ? `\n agentName: __agentModule.config.name,\n agentChannels: __agentDef.channels,` : "";
407
+ const doClass = agentModule
408
+ ? `
409
+ // The durable agent: one Durable Object per session, the compiled agent/
410
+ // directory as its definition — adapted tools (+ read_skill when skills exist),
411
+ // the assembled system prompt, channel factories resolved with the DO's own
412
+ // env, and the app's declared resources opened from THIS isolate's env (lazily,
413
+ // at the first turn — the same ambient db a tool sees in native dev). Model:
414
+ // Anthropic over a statically bundled client (workerd cannot resolve a bare
415
+ // import at runtime), keyed by the ANTHROPIC_API_KEY secret — a missing secret
416
+ // surfaces as the SDK's own clear construction error on the first agent request.
417
+ export class JuneAgentDO extends DurableObject {
418
+ #agent = new AgentDurableObject(this.ctx, {
419
+ ...__agentDef,
420
+ model: anthropic({ model: __agentModule.config.model, client: new Anthropic({ apiKey: (this.env as { ANTHROPIC_API_KEY?: string }).ANTHROPIC_API_KEY }) }),
421
+ env: this.env,${resourcesExpr ? `\n resources: ${resourcesExpr},` : ""}${servicesModule ? "\n services: __appServices(this.env)," : ""}
422
+ });
423
+ fetch(req: Request): Promise<Response> {
424
+ return this.#agent.fetch(req);
425
+ }
426
+ // Delivers input announcements left undelivered — a failed hook's retry, or the watchdog (#260).
427
+ alarm(): Promise<void> {
428
+ return this.#agent.alarm();
429
+ }
430
+ }
431
+ `
432
+ : "";
433
+
735
434
  const entry = `// AUTO-GENERATED by \`june build\` — do not edit. Regenerate: june build .
736
435
  ${adapterEntry.imports.join("\n")}
737
436
  ${imports.join("\n")}
738
- ${dataLayerBoot}
437
+ ${dataLayerBoot}${agentPreamble}
739
438
  const pipeline = createWorker({
740
439
  routes: {
741
440
  ${statics.join("\n")}
@@ -750,12 +449,12 @@ ${chains.join("\n")}
750
449
  ${loadings.join("\n")}
751
450
  },
752
451
  document: ${JSON.stringify(frozen.document, null, 2).replace(/\n/g, "\n ")},
753
- agent: ${JSON.stringify(frozen.agent)},${frozen.i18n ? `\n i18n: ${JSON.stringify(frozen.i18n)},` : ""}
452
+ agent: ${JSON.stringify(frozen.agent)},${agentNameField}${frozen.i18n ? `\n i18n: ${JSON.stringify(frozen.i18n)},` : ""}
754
453
  earlyHints: ${JSON.stringify(frozen.earlyHints)},${builtExtraFile ? "\n extra," : ""}${resourcesField}${servicesField}
755
454
  });
756
455
 
757
456
  ${adapterEntry.wrap("pipeline")}
758
- `;
457
+ ${doClass}`;
759
458
  const entryFile = join(genDir, "worker-entry.tsx");
760
459
  await writeFile(entryFile, entry);
761
460
 
@@ -782,6 +481,8 @@ ${adapterEntry.wrap("pipeline")}
782
481
  external: (id: string) => {
783
482
  // Bun built-ins exist only at Bun runtime, never in the workerd graph (see isBunSpecifier).
784
483
  if (isBunSpecifier(id)) return true;
484
+ // workerd runtime modules (the durable-agent entry imports cloudflare:workers).
485
+ if (id.startsWith("cloudflare:")) return true;
785
486
  // Binary assets stay external — wrangler's CompiledWasm/Data rules own them.
786
487
  if (/\.(wasm|ttf|otf|woff2?|png|jpe?g|avif|webp)$/.test(id)) return true;
787
488
  // Merge: adapter.buildExternal (target-specific, e.g. workers-og for the
@@ -817,7 +518,16 @@ ${adapterEntry.wrap("pipeline")}
817
518
  if (cssAsset) manifest.document.styles = `/${cssAsset}`; // prerendered HTML links the hashed sheet
818
519
  if (clientAsset) manifest.document.clientScript = `/${clientAsset}`;
819
520
  if (moduleCssAsset) manifest.document.moduleStyles = `/${moduleCssAsset}`;
820
- const worker = createWorker(manifest);
521
+ // A static site has no server: /mcp (and the WebMCP tools that proxy to it)
522
+ // and the HTTP API (POST /api/<id>, /openapi.json) do not exist there. Render
523
+ // with both projected out, so the published files advertise only what is
524
+ // deployed: llms.txt drops its MCP and HTTP API sections, the catalogs and the
525
+ // generated skill list neither, pages register no WebMCP tools.
526
+ const isStatic = adapter.capabilities.runtime === "static";
527
+ if (isStatic) manifest.agent = { ...manifest.agent, mcp: false, api: false, webmcp: false };
528
+ // The static() target prerenders its sitemap too; that build is where the
529
+ // route contract lets `staticPaths` run, so its sitemap lists those pages.
530
+ const worker = createWorker(manifest, { staticBuild: isStatic });
821
531
  let hasAssets = false;
822
532
 
823
533
  // ---- public/ → assets/ : verbatim static files (favicon, images, fonts) ----
@@ -855,11 +565,29 @@ ${adapterEntry.wrap("pipeline")}
855
565
  if (publicFiles.length) hasAssets = true;
856
566
  }
857
567
 
568
+ // ---- default PNG icons: apple-touch-icon.png, icon.png, favicon.ico -----
569
+ // Only when the app brings no icon of its own (the frozen document already
570
+ // links them — same resolveIcons call). Listed with publicFiles so adapters
571
+ // with a separate static tier (vercel) place them like any public/ file.
572
+ const site = frozen.document.site;
573
+ if (resolveIcons(site, publicFileCheck(publicDir)).generate) {
574
+ const icons = await renderIcons({
575
+ site,
576
+ fetchFont: googleFontFetcher(join(appRoot, "node_modules", ".cache", "june", "fonts")),
577
+ warn: (msg) => console.warn(msg),
578
+ });
579
+ await mkdir(assetsDir, { recursive: true }); // an app with no public/ has none yet
580
+ for (const file of GENERATED_ICONS) {
581
+ await writeFile(join(assetsDir, file), icons[file]);
582
+ publicFiles.push(file);
583
+ }
584
+ hasAssets = true;
585
+ }
586
+
858
587
  // static() target: prerender EVERY route (not just opted-in ones) + enumerate
859
588
  // dynamic routes via their staticPaths, and write <stem>/index.html so clean URLs
860
589
  // resolve on a dumb file host with no rewrite server. Other targets keep the
861
590
  // opt-in `prerender: true` behavior and the flat <stem>.html naming (byte-identical).
862
- const isStatic = adapter.capabilities.runtime === "static";
863
591
  const i18n = frozen.i18n;
864
592
 
865
593
  // Render ONE route pathname through the worker → HTML (+ .md/.json projections).
@@ -884,7 +612,7 @@ ${adapterEntry.wrap("pipeline")}
884
612
  if (def.md !== false) targets.push([mdReq, mdFile]); // .md/.json stay flat (exact-path negotiation)
885
613
  if (typeof def.json === "function") targets.push([jsonReq, jsonFile]);
886
614
  for (const [rp, file] of targets) {
887
- const res = await worker.fetch(new Request(`https://prerender.june${rp}`));
615
+ const res = await worker.fetch(new Request(`${PRERENDER_ORIGIN}${rp}`));
888
616
  if (!res.ok) throw new Error(`prerender ${rp} → ${res.status}`);
889
617
  const dest = join(assetsDir, file);
890
618
  await mkdir(dirname(dest), { recursive: true });
@@ -896,6 +624,17 @@ ${adapterEntry.wrap("pipeline")}
896
624
 
897
625
  // Locale variants a static route is emitted at: no i18n → [path]; with i18n → one
898
626
  // per locale (defaultLocale keeps the bare path, others get their localeHref prefix).
627
+ // A static build is ONE file tree on ONE host: a locale on its own domain has no
628
+ // path in it (and a basePath can't apply there), so say so instead of failing
629
+ // later with a prerender 404.
630
+ if (isStatic && i18n) {
631
+ const onDomain = Object.keys(i18n.locales).filter((l) => i18n.locales[l]!.domain);
632
+ if (onDomain.length) {
633
+ throw new Error(
634
+ `[june build] the static() target serves one host, so i18n locales with their own domain are not supported (${onDomain.join(", ")}). Give them a path prefix instead, e.g. { path: "/${onDomain[0]}" }.`,
635
+ );
636
+ }
637
+ }
899
638
  const localeVariants = (path: string): string[] =>
900
639
  isStatic && i18n
901
640
  ? [...new Set(Object.keys(i18n.locales).map((l) => localeHref(i18n, path, l)))]
@@ -916,6 +655,9 @@ ${adapterEntry.wrap("pipeline")}
916
655
  const sp = dyn.def.staticPaths;
917
656
  if (!sp) continue;
918
657
  const paths = typeof sp === "function" ? await sp() : sp;
658
+ // Resolve a producer ONCE: the prerendered sitemap below reads this same
659
+ // def, so it lists exactly the set prerendered here without a second call.
660
+ dyn.def.staticPaths = paths;
919
661
  for (const p of paths) await prerenderOne(p, dyn.def);
920
662
  }
921
663
  // Framework surfaces the worker would otherwise generate on the fly. Guarded on
@@ -923,18 +665,53 @@ ${adapterEntry.wrap("pipeline")}
923
665
  // skips its file rather than failing the build.
924
666
  const extra: Array<[string, string]> = [
925
667
  ["/favicon.svg", "favicon.svg"],
668
+ ["/manifest.webmanifest", "manifest.webmanifest"],
926
669
  ["/llms.txt", "llms.txt"],
927
670
  ["/sitemap.xml", "sitemap.xml"],
928
671
  ];
929
- for (const [reqPath, file] of extra) {
930
- const res = await worker.fetch(new Request(`https://prerender.june${reqPath}`));
672
+ // A sitemap needs absolute URLs, and the prerender host is a placeholder: with
673
+ // no public origin configured the pipeline answers 404 for it (and the loop
674
+ // below skips it), so say why rather than silently ship no sitemap.
675
+ if (manifest.agent.discovery && !manifest.document.site.url && !manifest.document.deployOrigin) {
676
+ console.warn(
677
+ "[june build] no sitemap.xml: set site.url (or deploy.domain) in june.config.ts so its URLs are absolute.",
678
+ );
679
+ }
680
+ // The agent catalogs (ARD, Agent Skills) — JSON/Markdown files a static host
681
+ // can serve as-is — only when this site publishes them: agent discovery on, a
682
+ // root deploy (a basePath site doesn't own /.well-known), and a known public
683
+ // origin (the files name absolute URLs). Same rule as the pipeline's
684
+ // catalogOrigin, stated here too so an app catch-all route can never answer
685
+ // these paths into the build. The generated skill's path carries its name, so
686
+ // it is read back from the index.
687
+ const doc = manifest.document;
688
+ if (manifest.agent.discovery && !doc.basePath && (doc.site.url || doc.deployOrigin)) {
689
+ extra.push(
690
+ ["/.well-known/ai-catalog.json", ".well-known/ai-catalog.json"],
691
+ ["/.well-known/ard.json", ".well-known/ard.json"],
692
+ ["/.well-known/agent-skills/index.json", ".well-known/agent-skills/index.json"],
693
+ );
694
+ }
695
+ for (let i = 0; i < extra.length; i++) {
696
+ const [reqPath, file] = extra[i]!;
697
+ const res = await worker.fetch(new Request(`${PRERENDER_ORIGIN}${reqPath}`));
931
698
  if (!res.ok) continue;
932
- await writeFile(join(assetsDir, file), Buffer.from(await res.arrayBuffer()));
699
+ const bytes = Buffer.from(await res.arrayBuffer());
700
+ await mkdir(dirname(join(assetsDir, file)), { recursive: true });
701
+ await writeFile(join(assetsDir, file), bytes);
933
702
  hasAssets = true;
703
+ if (file.endsWith("agent-skills/index.json")) {
704
+ const index = JSON.parse(bytes.toString("utf8")) as { skills?: Array<{ url?: string }> };
705
+ for (const s of index.skills ?? []) {
706
+ if (!s.url) continue;
707
+ const p = new URL(s.url, PRERENDER_ORIGIN).pathname;
708
+ extra.push([p, p.slice(1)]);
709
+ }
710
+ }
934
711
  }
935
712
  // 404.html — GitHub Pages serves it for any unmatched URL. A deliberately-missing
936
713
  // path renders June's not-found HTML (body is written regardless of the 404 status).
937
- const nf = await worker.fetch(new Request("https://prerender.june/__june_not_found__"));
714
+ const nf = await worker.fetch(new Request(`${PRERENDER_ORIGIN}/__june_not_found__`));
938
715
  await writeFile(join(assetsDir, "404.html"), Buffer.from(await nf.arrayBuffer()));
939
716
  hasAssets = true;
940
717
  }
@@ -969,16 +746,23 @@ ${adapterEntry.wrap("pipeline")}
969
746
  const defaultName = workerName(pkgName ?? basename(appRoot));
970
747
  // A declared D1-backed db (sqlite/d1) → a D1 binding named DB (the name
971
748
  // bindWorkerResources reads). turso() connects from env, not a binding — no plan.
972
- const plan: ResourcePlan =
973
- resourcesCfg?.db && resourcesCfg.db.kind !== "turso"
749
+ const plan: ResourcePlan = {
750
+ ...(resourcesCfg?.db && resourcesCfg.db.kind !== "turso"
974
751
  ? { db: { binding: "DB", databaseName: `${defaultName}-db` } }
975
- : {};
752
+ : {}),
753
+ // The durable agent's DO binding — the name createWorker reads (env.AGENT)
754
+ // and the class the generated entry exports.
755
+ ...(agentModule ? { agent: { binding: "AGENT", className: "JuneAgentDO" } } : {}),
756
+ };
976
757
  await adapter.emit({ appRoot, outDir, hasAssets, linkHeader, config: fullConfig, plan, defaultName, publicFiles });
977
758
  if (plan.db) {
978
759
  console.log(
979
760
  ` ↳ d1 binding "${plan.db.binding}" emitted — set database_id in wrangler.jsonc (wrangler d1 create ${plan.db.databaseName})`,
980
761
  );
981
762
  }
763
+ if (plan.agent) {
764
+ console.log(` ↳ durable agent mounted (${plan.agent.className} → env.${plan.agent.binding}; chat at ${frozen.agent.runtime.chat.path})`);
765
+ }
982
766
 
983
767
  return {
984
768
  outFile,