@conloca/cli 0.2.6 → 0.3.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 (3) hide show
  1. package/README.md +2 -1
  2. package/dist/conloca.js +1213 -442
  3. package/package.json +8 -8
package/dist/conloca.js CHANGED
@@ -2044,9 +2044,9 @@ function useColor() {
2044
2044
  var program = new Command;
2045
2045
 
2046
2046
  // src/commands/asset-add.ts
2047
- import { existsSync as existsSync7 } from "node:fs";
2048
- import { readFile as readFile12 } from "node:fs/promises";
2049
- import { basename as basename4, join as join15, relative as relative6, resolve as resolve8 } from "node:path";
2047
+ import { existsSync as existsSync8 } from "node:fs";
2048
+ import { readFile as readFile14 } from "node:fs/promises";
2049
+ import { basename as basename4, join as join17, relative as relative7, resolve as resolve8 } from "node:path";
2050
2050
  import { pathToFileURL as pathToFileURL2 } from "node:url";
2051
2051
  import { AssetOperations } from "@conloca/content-api/node";
2052
2052
 
@@ -2183,6 +2183,7 @@ function parseObjectEntries(objectText) {
2183
2183
  return null;
2184
2184
  const body = objectText.slice(1, -1);
2185
2185
  const entries = new Map;
2186
+ const shorthands = new Set;
2186
2187
  let hasSpread = false;
2187
2188
  let i = 0;
2188
2189
  while (i < body.length) {
@@ -2197,7 +2198,11 @@ function parseObjectEntries(objectText) {
2197
2198
  }
2198
2199
  const keyMatch = /^(?:([$A-Za-z_][$\w]*)|'([^']*)'|"([^"]*)")\s*:/.exec(body.slice(i));
2199
2200
  if (!keyMatch) {
2200
- i = skipValue(body, i);
2201
+ const end = skipValue(body, i);
2202
+ const word = body.slice(i, end).trim();
2203
+ if (/^[$A-Za-z_][$\w]*$/u.test(word))
2204
+ shorthands.add(word);
2205
+ i = end;
2201
2206
  continue;
2202
2207
  }
2203
2208
  const valueStart = i + keyMatch[0].length;
@@ -2205,7 +2210,7 @@ function parseObjectEntries(objectText) {
2205
2210
  entries.set(keyMatch[1] ?? keyMatch[2] ?? keyMatch[3] ?? "", body.slice(valueStart, valueEnd).trim());
2206
2211
  i = valueEnd;
2207
2212
  }
2208
- return { entries, hasSpread };
2213
+ return { entries, shorthands, hasSpread };
2209
2214
  }
2210
2215
  function stringLiteral(raw) {
2211
2216
  const match = /^(?:'([^'\\]*)'|"([^"\\]*)")$/.exec(raw.trim());
@@ -2230,6 +2235,127 @@ function callOptions(configText, name) {
2230
2235
 
2231
2236
  // src/lib/connect/astro-config.ts
2232
2237
  import { generateCode, parseExpression, parseModule } from "magicast";
2238
+
2239
+ // src/lib/is-record.ts
2240
+ function isRecord(value) {
2241
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2242
+ }
2243
+
2244
+ // src/lib/connect/site-domain.ts
2245
+ import { addressSiteName, isValidSiteBase } from "@conloca/content-api";
2246
+
2247
+ // src/lib/connect/step.ts
2248
+ import { mkdir, writeFile } from "node:fs/promises";
2249
+ import { dirname } from "node:path";
2250
+ var SCALAR_ARRAY = /^(.*)\[\n[^[\]{}]*?\n\s*\](.*)$/gm;
2251
+ var INLINE_ARRAY = /\[[^\n[\]{}]*[^\s[\]{}][^\n[\]{}]*\]/;
2252
+ var PRINT_WIDTH = 80;
2253
+ function jsonLike(before, value) {
2254
+ const indent = /^[ \t]+/m.exec(before)?.[0];
2255
+ let json = JSON.stringify(value, null, indent);
2256
+ if (INLINE_ARRAY.test(before)) {
2257
+ json = json.replace(SCALAR_ARRAY, (block, head, tail) => {
2258
+ const items = block.slice(head.length + 1, block.length - tail.length - 1).trim().split(/,\n\s*/);
2259
+ const line = `${head}[${items.join(", ")}]${tail}`;
2260
+ return line.length <= PRINT_WIDTH ? line : block;
2261
+ });
2262
+ }
2263
+ return `${json}${before.endsWith(`
2264
+ `) ? `
2265
+ ` : ""}`;
2266
+ }
2267
+ async function writeEdits(edits) {
2268
+ await Promise.all(edits.map(async (edit) => {
2269
+ await mkdir(dirname(edit.path), { recursive: true });
2270
+ await writeFile(edit.path, edit.after, "utf8");
2271
+ }));
2272
+ }
2273
+
2274
+ // src/lib/connect/site-domain.ts
2275
+ function isSitesConfig(value) {
2276
+ return isRecord(value) && isRecord(value.sites) && Object.values(value.sites).every((site) => isRecord(site) && Array.isArray(site.locales) && typeof site.defaultLocale === "string" && (site.domains === undefined || isRecord(site.domains)) && (site.base === undefined || typeof site.base === "string"));
2277
+ }
2278
+ function siteBase(base) {
2279
+ const leading = base === null || base.startsWith("/") ? base ?? "/" : `/${base}`;
2280
+ return leading.endsWith("/") ? leading : `${leading}/`;
2281
+ }
2282
+ function writeSiteAddress(input) {
2283
+ const { path, text, site } = input;
2284
+ const url = URL.canParse(site) ? new URL(site) : null;
2285
+ if (url?.protocol !== "https:") {
2286
+ return { state: "needs-you", message: `Astro's site must be an https URL, got ${site}`, edits: [] };
2287
+ }
2288
+ const base = siteBase(input.base);
2289
+ if (!isValidSiteBase(base)) {
2290
+ return {
2291
+ state: "needs-you",
2292
+ message: `Astro's base ${input.base} is not a path the editor can open`,
2293
+ edits: []
2294
+ };
2295
+ }
2296
+ let config;
2297
+ try {
2298
+ config = JSON.parse(text);
2299
+ } catch {
2300
+ return { state: "failed", message: `${path} is not valid JSON`, edits: [] };
2301
+ }
2302
+ if (!isSitesConfig(config)) {
2303
+ return { state: "failed", message: `${path} has no readable sites map`, edits: [] };
2304
+ }
2305
+ const name = addressSiteName(config);
2306
+ const entry = name === null ? undefined : config.sites[name];
2307
+ if (name === null || entry === undefined) {
2308
+ return {
2309
+ state: "needs-you",
2310
+ message: `${path} lists several sites and none is named default; add the domain to the right one yourself`,
2311
+ lines: [`"domains": { "<locale>": "${url.hostname}" }`, ...base === "/" ? [] : [`"base": "${base}"`]],
2312
+ edits: []
2313
+ };
2314
+ }
2315
+ const host = url.hostname;
2316
+ const locale = entry.defaultLocale;
2317
+ const domain = entry.domains?.[locale];
2318
+ const kept = [
2319
+ ...domain !== undefined && domain !== host ? [`domains.${locale} is ${domain}, not ${host}`] : [],
2320
+ ...entry.base !== undefined && entry.base !== base ? [`base is ${entry.base}, not ${base}`] : []
2321
+ ];
2322
+ if (kept.length === 0 && domain !== undefined && (entry.base !== undefined || base === "/")) {
2323
+ return { state: "done", message: `site '${name}' already lists ${host}`, edits: [] };
2324
+ }
2325
+ entry.domains = { ...entry.domains, [locale]: host };
2326
+ if (base !== "/" || entry.base !== undefined)
2327
+ entry.base = base;
2328
+ const edits = [{ path, before: text, after: jsonLike(text, config) }];
2329
+ if (kept.length > 0) {
2330
+ return {
2331
+ state: "differs",
2332
+ message: `site '${name}' in ${path}: ${kept.join("; ")} (kept yours)`,
2333
+ edits: [],
2334
+ replacement: edits
2335
+ };
2336
+ }
2337
+ return {
2338
+ state: "changed",
2339
+ message: `wrote ${host}${base === "/" ? "" : ` and base ${base}`} into site '${name}'`,
2340
+ edits
2341
+ };
2342
+ }
2343
+ function siteUrlOf(sitesText) {
2344
+ let config;
2345
+ try {
2346
+ config = JSON.parse(sitesText);
2347
+ } catch {
2348
+ return null;
2349
+ }
2350
+ if (!isSitesConfig(config))
2351
+ return null;
2352
+ const name = addressSiteName(config);
2353
+ const entry = name === null ? undefined : config.sites[name];
2354
+ const domain = entry?.domains?.[entry.defaultLocale];
2355
+ return domain === undefined ? null : `https://${domain}`;
2356
+ }
2357
+
2358
+ // src/lib/connect/astro-config.ts
2233
2359
  var REMOVED_OPTIONS = new Set([
2234
2360
  "buildToken",
2235
2361
  "publicBaseUrl",
@@ -2332,6 +2458,56 @@ function removedKeyOptions(text) {
2332
2458
  return null;
2333
2459
  return names.flatMap((name) => name !== null && REMOVED_OPTIONS.has(name) ? [name] : []);
2334
2460
  }
2461
+ function withoutPreviewBuildOptions(text, names) {
2462
+ let mod;
2463
+ try {
2464
+ mod = parseModule(text);
2465
+ } catch {
2466
+ return "computed";
2467
+ }
2468
+ const program = mod.$ast;
2469
+ if (program.type !== "Program")
2470
+ return "computed";
2471
+ const config = configObject(program);
2472
+ const value = config === null ? undefined : property(config, "integrations")?.value;
2473
+ const elements = value?.type === "ArrayExpression" ? value.elements : [];
2474
+ const call = elements[callIndex(elements, localName(importLocals(program), IMPORTS.editorPage))];
2475
+ const [options] = call?.type === "CallExpression" ? call.arguments : [];
2476
+ const previewBuild = options?.type === "ObjectExpression" ? property(options, "previewBuild")?.value : undefined;
2477
+ if (previewBuild?.type !== "ObjectExpression")
2478
+ return "computed";
2479
+ const removed = previewBuild.properties.filter((p) => names.has(propertyName(p) ?? ""));
2480
+ if (removed.length === 0)
2481
+ return null;
2482
+ previewBuild.properties = previewBuild.properties.filter((p) => !removed.includes(p));
2483
+ const callees = removed.flatMap((p) => p.type === "ObjectProperty" && p.value.type === "CallExpression" && p.value.callee.type === "Identifier" ? [p.value.callee.name] : []);
2484
+ const code = program.body.filter((statement) => statement.type !== "ImportDeclaration");
2485
+ for (const local of callees) {
2486
+ if (!namesIdentifier(code, local))
2487
+ delete mod.imports[local];
2488
+ }
2489
+ return { after: printModule(mod, text) };
2490
+ }
2491
+ var NOT_CODE = new Set([
2492
+ "loc",
2493
+ "start",
2494
+ "end",
2495
+ "original",
2496
+ "tokens",
2497
+ "comments",
2498
+ "leadingComments",
2499
+ "trailingComments",
2500
+ "extra"
2501
+ ]);
2502
+ function namesIdentifier(node, name) {
2503
+ if (Array.isArray(node))
2504
+ return node.some((child) => namesIdentifier(child, name));
2505
+ if (!isRecord(node))
2506
+ return false;
2507
+ if (node.type === "Identifier" && node.name === name)
2508
+ return true;
2509
+ return Object.entries(node).some(([key, child]) => !NOT_CODE.has(key) && namesIdentifier(child, name));
2510
+ }
2335
2511
  function pasteLines(repoUri) {
2336
2512
  return [
2337
2513
  `import react from '${IMPORTS.react.from}';`,
@@ -2554,6 +2730,45 @@ function readAstroSite(text) {
2554
2730
  const base = readAstroOption(text, "base");
2555
2731
  return site === undefined || base === undefined ? "computed" : { site, base };
2556
2732
  }
2733
+ function addAstroSiteStep(input) {
2734
+ const { path, text } = input;
2735
+ if (input.adapter !== "@astrojs/vercel" && input.adapter !== "@astrojs/netlify") {
2736
+ return { state: "skipped", message: `${input.adapter} needs no site for previews`, edits: [] };
2737
+ }
2738
+ const current = readAstroSite(text);
2739
+ if (current === "computed")
2740
+ return { state: "skipped", message: "astro.config computes its site", edits: [] };
2741
+ if (current.site !== null)
2742
+ return { state: "done", message: `astro.config sets site ${current.site}`, edits: [] };
2743
+ const given = input.siteUrl ?? siteUrlOf(input.sitesText);
2744
+ const parsed = given !== null && URL.canParse(given) ? new URL(given) : null;
2745
+ if (given !== null && parsed?.protocol !== "https:") {
2746
+ return { state: "needs-you", message: `Astro's site must be an https URL, got ${given}`, edits: [] };
2747
+ }
2748
+ const url = parsed?.origin ?? null;
2749
+ const shown = url ?? "<your production URL>";
2750
+ const message = `astro.config sets no site, so your own pages leave the preview (302) instead of staying in it; site: '${shown}' fixes that and also changes canonical, sitemap, RSS and Open Graph URLs on your live pages`;
2751
+ const lines = [`site: '${shown}',`];
2752
+ let config = null;
2753
+ try {
2754
+ config = url === null ? null : parseModule(text);
2755
+ } catch {
2756
+ config = null;
2757
+ }
2758
+ const program = config?.$ast;
2759
+ const object = program?.type === "Program" ? configObject(program) : null;
2760
+ if (config === null || object === null)
2761
+ return { state: "needs-you", message, lines, edits: [] };
2762
+ object.properties.unshift(...objectProperties(`site: '${url}'`));
2763
+ return {
2764
+ state: "differs",
2765
+ message,
2766
+ lines,
2767
+ edits: [],
2768
+ replacement: [{ path, before: text, after: printModule(config, text) }],
2769
+ question: `Set site to ${shown} in astro.config? It changes canonical, sitemap, RSS and Open Graph URLs on your live pages.`
2770
+ };
2771
+ }
2557
2772
  function dataSchemaLines(assetsPath) {
2558
2773
  return [
2559
2774
  "import { schemaTypia } from './typia-vite.mjs';",
@@ -2666,14 +2881,14 @@ function messageOf(error) {
2666
2881
  }
2667
2882
 
2668
2883
  // src/commands/data.ts
2669
- import { existsSync as existsSync6 } from "node:fs";
2670
- import { readFile as readFile11 } from "node:fs/promises";
2671
- import { join as join14, relative as relative5, resolve as resolve7 } from "node:path";
2884
+ import { existsSync as existsSync7 } from "node:fs";
2885
+ import { readFile as readFile13 } from "node:fs/promises";
2886
+ import { join as join16, relative as relative6, resolve as resolve7 } from "node:path";
2672
2887
 
2673
2888
  // src/lib/connect/data-schemas.ts
2674
2889
  import { existsSync as existsSync3 } from "node:fs";
2675
2890
  import { readFile as readFile2 } from "node:fs/promises";
2676
- import { dirname as dirname2, join as join3, relative, resolve as resolve3, sep } from "node:path";
2891
+ import { dirname as dirname3, join as join3, relative, resolve as resolve3, sep } from "node:path";
2677
2892
  import { parseModule as parseModule2 } from "magicast";
2678
2893
 
2679
2894
  // src/templates/project-files.ts
@@ -2856,18 +3071,13 @@ Working with a coding agent? \`.claude/skills/conloca/SKILL.md\` teaches it Conl
2856
3071
  `;
2857
3072
  }
2858
3073
 
2859
- // src/lib/is-record.ts
2860
- function isRecord(value) {
2861
- return typeof value === "object" && value !== null && !Array.isArray(value);
2862
- }
2863
-
2864
3074
  // src/lib/project-template.ts
2865
3075
  import { readFile } from "node:fs/promises";
2866
3076
  import { basename as basename2 } from "node:path";
2867
3077
 
2868
3078
  // src/lib/package-manager.ts
2869
3079
  import { existsSync as existsSync2 } from "node:fs";
2870
- import { dirname, join as join2, resolve as resolve2 } from "node:path";
3080
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
2871
3081
  var PACKAGE_MANAGERS = ["bun", "npm", "pnpm", "yarn"];
2872
3082
  function isPackageManager(value) {
2873
3083
  return PACKAGE_MANAGERS.includes(value);
@@ -2918,13 +3128,13 @@ var LOCKFILES = [
2918
3128
  ];
2919
3129
  function lockfileInstall(projectDir, repoRoot, exists = existsSync2) {
2920
3130
  const root = resolve2(repoRoot);
2921
- for (let dir = resolve2(projectDir);; dir = dirname(dir)) {
3131
+ for (let dir = resolve2(projectDir);; dir = dirname2(dir)) {
2922
3132
  for (const [name, packageManager] of LOCKFILES) {
2923
3133
  const lockfile = join2(dir, name);
2924
3134
  if (exists(lockfile))
2925
3135
  return { packageManager, lockfile, installDir: dir };
2926
3136
  }
2927
- if (dir === root || dir === dirname(dir))
3137
+ if (dir === root || dir === dirname2(dir))
2928
3138
  return null;
2929
3139
  }
2930
3140
  }
@@ -2932,7 +3142,7 @@ function lockfileInstall(projectDir, repoRoot, exists = existsSync2) {
2932
3142
  // src/lib/project-template.ts
2933
3143
  var THIRD_PARTY_VERSIONS = {
2934
3144
  astro: "^7.3.1",
2935
- "@astrojs/node": "^11.1.5",
3145
+ "@astrojs/node": "11.1.9",
2936
3146
  "@astrojs/react": "^6.0.5",
2937
3147
  "@puckeditor/core": "^0.23.0",
2938
3148
  "@vitejs/plugin-react": "^5.2.0",
@@ -2942,8 +3152,35 @@ var THIRD_PARTY_VERSIONS = {
2942
3152
  "@ttsc/unplugin": "0.35.0",
2943
3153
  ttsc: "0.35.0"
2944
3154
  };
3155
+ var ADAPTER_VERSIONS = {
3156
+ "@astrojs/vercel": "11.0.18",
3157
+ "@astrojs/netlify": "8.2.11",
3158
+ "@astrojs/cloudflare": "14.3.2",
3159
+ "@astrojs/node": "11.1.9"
3160
+ };
2945
3161
  var DEV_ONLY = new Set(["@ttsc/unplugin", "ttsc"]);
2946
3162
  var MANIFEST_CANDIDATES = ["../package.json", "../../package.json"];
3163
+ async function withWorkspacePins(manifest, location) {
3164
+ const pinsOf = async (specs) => {
3165
+ if (specs === undefined)
3166
+ return;
3167
+ const pins = await Promise.all(Object.entries(specs).map(async ([name, spec]) => {
3168
+ if (!spec.startsWith("workspace:"))
3169
+ return [name, spec];
3170
+ const sibling = JSON.parse(await readFile(new URL(`../${basename2(name)}/package.json`, location), "utf-8"));
3171
+ if (typeof sibling.version !== "string") {
3172
+ throw new Error(`could not read the version of workspace package ${name}`);
3173
+ }
3174
+ return [name, sibling.version];
3175
+ }));
3176
+ return Object.fromEntries(pins);
3177
+ };
3178
+ const [dependencies, peerDependencies] = await Promise.all([
3179
+ pinsOf(manifest.dependencies),
3180
+ pinsOf(manifest.peerDependencies)
3181
+ ]);
3182
+ return { version: manifest.version, dependencies, peerDependencies };
3183
+ }
2947
3184
  async function readCliManifest() {
2948
3185
  for (const candidate of MANIFEST_CANDIDATES) {
2949
3186
  let manifest;
@@ -2953,11 +3190,7 @@ async function readCliManifest() {
2953
3190
  continue;
2954
3191
  }
2955
3192
  if (typeof manifest.version === "string") {
2956
- return {
2957
- version: manifest.version,
2958
- dependencies: manifest.dependencies,
2959
- peerDependencies: manifest.peerDependencies
2960
- };
3193
+ return withWorkspacePins({ version: manifest.version, dependencies: manifest.dependencies, peerDependencies: manifest.peerDependencies }, new URL(candidate, import.meta.url));
2961
3194
  }
2962
3195
  }
2963
3196
  throw new Error("could not read the version of @conloca/cli from its own package.json");
@@ -2970,8 +3203,7 @@ var SCAFFOLD_CONLOCA_PACKAGES = ["@conloca/astro-cms", "@conloca/content-api"];
2970
3203
  function conlocaRange(manifest, name) {
2971
3204
  if (name === "@conloca/cli")
2972
3205
  return manifest.version;
2973
- const declared = manifest.dependencies?.[name] ?? manifest.peerDependencies?.[name];
2974
- return declared?.startsWith("workspace:") ? manifest.version : declared;
3206
+ return manifest.dependencies?.[name] ?? manifest.peerDependencies?.[name];
2975
3207
  }
2976
3208
  function renderPackageJson(input) {
2977
3209
  const dependencies = {};
@@ -3059,7 +3291,7 @@ async function contentConfigStep(projectDir, schemasPath) {
3059
3291
  const { findContentConfig } = await import("@conloca/astro-cms/checks");
3060
3292
  const found = findContentConfig(projectDir);
3061
3293
  const path = found ?? join3(projectDir, "src", "content.config.ts");
3062
- const target = relative(dirname2(path), resolve3(projectDir, schemasPath).replace(/\.[cm]?[jt]sx?$/, ""));
3294
+ const target = relative(dirname3(path), resolve3(projectDir, schemasPath).replace(/\.[cm]?[jt]sx?$/, ""));
3063
3295
  const specifier = target.startsWith(`..${sep}`) ? target.split(sep).join("/") : `./${target.split(sep).join("/")}`;
3064
3296
  if (found === null) {
3065
3297
  const after = CONTENT_CONFIG_TEMPLATE.replace("'./schemas/data'", `'${specifier}'`);
@@ -3148,33 +3380,6 @@ async function wireDataSchemas(projectDir) {
3148
3380
  return edits.length === 0 && packages.length === 0 ? { state: "done", message: "the data schemas and the media folder are wired", edits, packages } : { state: "changed", message: notes.join("; "), edits, packages };
3149
3381
  }
3150
3382
 
3151
- // src/lib/connect/step.ts
3152
- import { mkdir, writeFile } from "node:fs/promises";
3153
- import { dirname as dirname3 } from "node:path";
3154
- var SCALAR_ARRAY = /^(.*)\[\n[^[\]{}]*?\n\s*\](.*)$/gm;
3155
- var INLINE_ARRAY = /\[[^\n[\]{}]*[^\s[\]{}][^\n[\]{}]*\]/;
3156
- var PRINT_WIDTH = 80;
3157
- function jsonLike(before, value) {
3158
- const indent = /^[ \t]+/m.exec(before)?.[0];
3159
- let json = JSON.stringify(value, null, indent);
3160
- if (INLINE_ARRAY.test(before)) {
3161
- json = json.replace(SCALAR_ARRAY, (block, head, tail) => {
3162
- const items = block.slice(head.length + 1, block.length - tail.length - 1).trim().split(/,\n\s*/);
3163
- const line = `${head}[${items.join(", ")}]${tail}`;
3164
- return line.length <= PRINT_WIDTH ? line : block;
3165
- });
3166
- }
3167
- return `${json}${before.endsWith(`
3168
- `) ? `
3169
- ` : ""}`;
3170
- }
3171
- async function writeEdits(edits) {
3172
- await Promise.all(edits.map(async (edit) => {
3173
- await mkdir(dirname3(edit.path), { recursive: true });
3174
- await writeFile(edit.path, edit.after, "utf8");
3175
- }));
3176
- }
3177
-
3178
3383
  // src/lib/data-write.ts
3179
3384
  import { join as join5 } from "node:path";
3180
3385
  import { FileSystemContentAPI as FileSystemContentAPI2 } from "@conloca/content-api/node";
@@ -3293,8 +3498,16 @@ async function updatePage(input) {
3293
3498
  }
3294
3499
  const ext = manifest.type === "mdx" ? "mdx" : "vxjson";
3295
3500
  const filePath = pageFilePath(contentRoot, site, manifest.collection, localized.pathname, locale, ext);
3501
+ await input.afterWrite?.();
3502
+ await assertWriteSurvived(api, { id: manifest.id, locale, etag: result.etag, filePath });
3296
3503
  return { id: manifest.id, pathname: localized.pathname, filePath };
3297
3504
  }
3505
+ async function assertWriteSurvived(api, write) {
3506
+ const { survived } = await api.verifyOwnWrite(write.id, write.locale, write.etag ?? "");
3507
+ if (!survived) {
3508
+ throw new PageWriteError("write_failed", `your write to ${write.filePath} was overwritten by another writer; re-run the command`);
3509
+ }
3510
+ }
3298
3511
 
3299
3512
  // src/lib/data-write.ts
3300
3513
  function dataFilePath(contentRoot, collection, name, locale) {
@@ -3335,7 +3548,10 @@ async function updateDataEntry(input) {
3335
3548
  if (!result.success) {
3336
3549
  throw new PageWriteError("write_failed", result.error?.message ?? `Update failed (${result.reason ?? "unknown reason"})`);
3337
3550
  }
3338
- return { id: manifest.id, filePath: dataFilePath(contentRoot, collection, localized.name, locale) };
3551
+ const filePath = dataFilePath(contentRoot, collection, localized.name, locale);
3552
+ await input.afterWrite?.();
3553
+ await assertWriteSurvived(api, { id: manifest.id, locale, etag: result.etag, filePath });
3554
+ return { id: manifest.id, filePath };
3339
3555
  }
3340
3556
 
3341
3557
  // src/lib/json-input.ts
@@ -3358,9 +3574,9 @@ async function readJsonInput(source, flag) {
3358
3574
 
3359
3575
  // src/commands/connect.ts
3360
3576
  import { execFile as execFileCallback2, spawn } from "node:child_process";
3361
- import { existsSync as existsSync5 } from "node:fs";
3362
- import { readFile as readFile10 } from "node:fs/promises";
3363
- import { join as join13, relative as relative4, resolve as resolve6, sep as sep2 } from "node:path";
3577
+ import { existsSync as existsSync6 } from "node:fs";
3578
+ import { readFile as readFile12 } from "node:fs/promises";
3579
+ import { join as join15, relative as relative5, resolve as resolve6, sep as sep3 } from "node:path";
3364
3580
  import { createInterface } from "node:readline/promises";
3365
3581
  import { promisify as promisify2 } from "node:util";
3366
3582
  import { EDITOR_HOST_PROTOCOL } from "@conloca/content-api/editor-host";
@@ -3401,14 +3617,216 @@ async function listAstroProjects(repoRoot) {
3401
3617
  return found;
3402
3618
  }
3403
3619
 
3620
+ // src/lib/connect/adapter.ts
3621
+ import { parseExpression as parseExpression2, parseModule as parseModule3 } from "magicast";
3622
+
3623
+ // src/lib/versions.ts
3624
+ import { readFile as readFile5 } from "node:fs/promises";
3625
+ import { dirname as dirname4, join as join7 } from "node:path";
3626
+ var D8_SINCE = "0.2.6-next.0";
3627
+ async function installedVersion(name, projectDir, installDir) {
3628
+ for (let dir = projectDir;; dir = dirname4(dir)) {
3629
+ const version = await readFile5(join7(dir, "node_modules", name, "package.json"), "utf8").then((text) => {
3630
+ let value;
3631
+ try {
3632
+ value = JSON.parse(text);
3633
+ } catch {
3634
+ return;
3635
+ }
3636
+ if (!isRecord(value))
3637
+ return;
3638
+ return typeof value.version === "string" ? value.version : null;
3639
+ }, () => {
3640
+ return;
3641
+ });
3642
+ if (version !== undefined)
3643
+ return version;
3644
+ if (dir === installDir || dir === dirname4(dir))
3645
+ return null;
3646
+ }
3647
+ }
3648
+ var NUMERIC = /^\d+$/;
3649
+ function compareIdentifiers(a, b) {
3650
+ const aNumeric = NUMERIC.test(a);
3651
+ const bNumeric = NUMERIC.test(b);
3652
+ if (aNumeric && bNumeric)
3653
+ return Number(a) - Number(b);
3654
+ if (aNumeric !== bNumeric)
3655
+ return aNumeric ? -1 : 1;
3656
+ return a < b ? -1 : a > b ? 1 : 0;
3657
+ }
3658
+ function compareVersions(a, b) {
3659
+ const [aCore = "", ...aPre] = a.split("+")[0]?.split("-") ?? [];
3660
+ const [bCore = "", ...bPre] = b.split("+")[0]?.split("-") ?? [];
3661
+ const aParts = aCore.split(".").map(Number);
3662
+ const bParts = bCore.split(".").map(Number);
3663
+ for (let i = 0;i < 3; i++) {
3664
+ const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
3665
+ if (diff !== 0)
3666
+ return diff;
3667
+ }
3668
+ const aIds = aPre.length > 0 ? aPre.join("-").split(".") : [];
3669
+ const bIds = bPre.length > 0 ? bPre.join("-").split(".") : [];
3670
+ if (aIds.length === 0 || bIds.length === 0)
3671
+ return bIds.length - aIds.length;
3672
+ for (let i = 0;i < Math.min(aIds.length, bIds.length); i++) {
3673
+ const diff = compareIdentifiers(aIds[i] ?? "", bIds[i] ?? "");
3674
+ if (diff !== 0)
3675
+ return diff;
3676
+ }
3677
+ return aIds.length - bIds.length;
3678
+ }
3679
+ function versionFloor(spec) {
3680
+ return spec.match(/\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/)?.[0] ?? null;
3681
+ }
3682
+ var SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"];
3683
+ function conlocaDependencies(manifest) {
3684
+ return SECTIONS.flatMap((section) => {
3685
+ const deps = manifest[section];
3686
+ if (!isRecord(deps))
3687
+ return [];
3688
+ return Object.entries(deps).flatMap(([name, spec]) => name.startsWith("@conloca/") && typeof spec === "string" ? [{ section, name, spec }] : []);
3689
+ });
3690
+ }
3691
+
3692
+ // src/lib/connect/adapter.ts
3693
+ var HOST_ADAPTERS = {
3694
+ vercel: { name: "@astrojs/vercel", call: "vercel" },
3695
+ netlify: { name: "@astrojs/netlify", call: "netlify" },
3696
+ cloudflare: { name: "@astrojs/cloudflare", call: "cloudflare" },
3697
+ node: { name: "@astrojs/node", call: "node" }
3698
+ };
3699
+ var ADAPTER_ASTRO_FLOORS = {
3700
+ "@astrojs/vercel": "7.0.0",
3701
+ "@astrojs/netlify": "7.0.0",
3702
+ "@astrojs/cloudflare": "7.2.0",
3703
+ "@astrojs/node": "7.2.1"
3704
+ };
3705
+ var needs = (message) => ({ state: "needs-you", message, edits: [] });
3706
+ function expression(code) {
3707
+ return parseExpression2(code).$ast;
3708
+ }
3709
+ function excludePreview(options, base) {
3710
+ const isr = property(options, "isr");
3711
+ if (isr === undefined || isr.value.type === "BooleanLiteral" && !isr.value.value)
3712
+ return false;
3713
+ const entry = `/^${`${base.replace(/\/+$/u, "")}/_conloca/preview`.replaceAll("/", "\\/")}(\\/.*)?$/`;
3714
+ if (isr.value.type === "BooleanLiteral") {
3715
+ const replaced = expression(`({ exclude: [${entry}] })`);
3716
+ if (replaced.type !== "ObjectExpression")
3717
+ return false;
3718
+ isr.value = replaced;
3719
+ return true;
3720
+ }
3721
+ if (isr.value.type !== "ObjectExpression")
3722
+ return false;
3723
+ const exclude = property(isr.value, "exclude");
3724
+ if (exclude === undefined) {
3725
+ isr.value.properties.push(...objectProperties(`exclude: [${entry}]`));
3726
+ return true;
3727
+ }
3728
+ if (exclude.value.type !== "ArrayExpression")
3729
+ return false;
3730
+ const listed = exclude.value.elements.some((e) => e?.type === "RegExpLiteral" && e.pattern.includes("_conloca"));
3731
+ const regex = expression(entry);
3732
+ if (listed || regex.type !== "RegExpLiteral")
3733
+ return false;
3734
+ exclude.value.elements.push(regex);
3735
+ return true;
3736
+ }
3737
+ function addAdapterStep(input) {
3738
+ const { path, text, host } = input;
3739
+ if (host === "cloudflare-d3" || host === "static-only") {
3740
+ return { state: "skipped", message: `${host} takes no adapter`, edits: [] };
3741
+ }
3742
+ const { name, call } = HOST_ADAPTERS[host];
3743
+ const floor = ADAPTER_ASTRO_FLOORS[name];
3744
+ if (input.astroVersion !== "" && compareVersions(input.astroVersion, floor) < 0) {
3745
+ return needs(`${name} needs astro ${floor} or later; this site has ${input.astroVersion}: update astro first`);
3746
+ }
3747
+ let mod;
3748
+ try {
3749
+ mod = parseModule3(text);
3750
+ } catch {
3751
+ return needs(`${path} does not parse, so connect does not add ${call}(): add it by hand`);
3752
+ }
3753
+ const program = mod.$ast;
3754
+ const config = program.type === "Program" ? configObject(program) : null;
3755
+ if (program.type !== "Program" || config === null) {
3756
+ return needs(`${path} is not a plain defineConfig({...}), so connect does not add ${call}(): add it by hand`);
3757
+ }
3758
+ const site = readAstroSite(text);
3759
+ const base = site === "computed" ? "/" : site.base ?? "/";
3760
+ const locals = importLocals(program);
3761
+ const notes = [];
3762
+ const adapter = property(config, "adapter");
3763
+ if (adapter === undefined) {
3764
+ const build = property(config, "build")?.value;
3765
+ const format = build?.type === "ObjectExpression" ? property(build, "format")?.value : undefined;
3766
+ const fileFormat = format?.type === "StringLiteral" && format.value === "file";
3767
+ if (host === "vercel" && fileFormat) {
3768
+ const warning = "build.format 'file' becomes 'directory' under @astrojs/vercel, so page addresses lose their .html";
3769
+ if (input.yes)
3770
+ return needs(`${warning}: remove the option, or run connect in a terminal to accept`);
3771
+ notes.push(`warning: ${warning}`);
3772
+ }
3773
+ const bound = locals.get(call);
3774
+ if (bound !== undefined && bound !== `${name}#default`) {
3775
+ return needs(`${path} already names something ${call}, so connect does not add ${name}: add it by hand`);
3776
+ }
3777
+ if (bound === undefined)
3778
+ mod.imports.$append({ from: name, imported: "default", local: call });
3779
+ config.properties.push(...objectProperties(host === "node" ? `adapter: ${call}({ mode: 'standalone' })` : `adapter: ${call}()`));
3780
+ notes.push(`added ${call}() from ${name}`);
3781
+ } else {
3782
+ const value = adapter.value;
3783
+ const callee = value.type === "CallExpression" && value.callee.type === "Identifier" ? value.callee.name : null;
3784
+ if (value.type !== "CallExpression" || callee === null || !locals.get(callee)?.startsWith(`${name}#`)) {
3785
+ return needs(`astro.config's adapter is not ${name}, which ${host} needs for draft previews; pass --host if ${host} is wrong`);
3786
+ }
3787
+ const [options] = value.arguments;
3788
+ if (host === "vercel" && options?.type === "ObjectExpression" && excludePreview(options, base)) {
3789
+ notes.push("excluded the preview route from isr");
3790
+ }
3791
+ }
3792
+ if (host === "netlify" && property(config, "session") === undefined) {
3793
+ config.properties.push(...objectProperties("session: false"));
3794
+ notes.push("session: false");
3795
+ }
3796
+ const security = property(config, "security");
3797
+ const needsDomains = security === undefined || security.value.type === "ObjectExpression" && property(security.value, "allowedDomains") === undefined;
3798
+ if (host === "node" && needsDomains && input.siteDomains.length === 0) {
3799
+ return needs("sites.json names no domain for security.allowedDomains, and without it every preview entry fails behind a TLS proxy: add the site's domains to sites.json, then run again");
3800
+ }
3801
+ if (host === "node") {
3802
+ const domains = input.siteDomains.map((hostname) => `{ hostname: ${JSON.stringify(hostname)}, protocol: 'https' }`);
3803
+ const allowed = `allowedDomains: [${domains.join(", ")}]`;
3804
+ if (security === undefined) {
3805
+ config.properties.push(...objectProperties(`security: { ${allowed} }`));
3806
+ notes.push("security.allowedDomains");
3807
+ } else if (security.value.type === "ObjectExpression" && property(security.value, "allowedDomains") === undefined) {
3808
+ security.value.properties.push(...objectProperties(allowed));
3809
+ notes.push("security.allowedDomains");
3810
+ }
3811
+ }
3812
+ const after = notes.length === 0 ? text : printModule(mod, text);
3813
+ const refusal = input.configRefusal?.(after, name, base) ?? null;
3814
+ if (refusal !== null)
3815
+ return needs(refusal);
3816
+ if (after === text) {
3817
+ return { state: "done", message: `astro.config has ${call}() with the options draft previews need`, edits: [] };
3818
+ }
3819
+ return { state: "changed", message: notes.join("; "), edits: [{ path, before: text, after }] };
3820
+ }
3821
+
3404
3822
  // src/lib/connect/cf-plan.ts
3405
3823
  import { findNodeAtLocation, parseTree } from "jsonc-parser";
3406
3824
 
3407
3825
  // src/lib/connect/preview-deploy.ts
3408
3826
  import { createHash } from "node:crypto";
3409
3827
  import { existsSync as existsSync4 } from "node:fs";
3410
- import { readFile as readFile5 } from "node:fs/promises";
3411
- import { basename as basename3, join as join7 } from "node:path";
3828
+ import { readFile as readFile6 } from "node:fs/promises";
3829
+ import { basename as basename3, join as join8 } from "node:path";
3412
3830
  import { applyEdits, modify, parse } from "jsonc-parser";
3413
3831
  var DISPATCHER_MAIN = ".conloca/dispatcher/index.mjs";
3414
3832
  var PREVIEW_LIMIT = { name: "conlocaPreviewLimit", simple: { limit: 60, period: 10 } };
@@ -3443,26 +3861,53 @@ function withoutPreviewLimit(block) {
3443
3861
  return null;
3444
3862
  return kept.length === 0 ? undefined : kept;
3445
3863
  }
3446
- function previewSetupOf(integration, astro, base) {
3864
+ function previewSetupOf(integration, astro, base, code) {
3447
3865
  if (integration.state !== "literal")
3448
3866
  return { kind: "off" };
3449
3867
  const raw = integration.entries.get("previewBuild");
3450
3868
  if (raw === undefined || raw.trim() === "false")
3451
3869
  return { kind: "off" };
3452
3870
  const prefix = `${(base ?? "/").replace(/\/+$/u, "")}/_conloca/preview`;
3453
- if (/\bseparate\s*:\s*true\b/u.test(raw))
3454
- return { kind: "d4", prefix };
3455
- const ownAdapter = astro.state === "literal" && astro.entries.has("adapter");
3456
- return /\badapter\b/u.test(raw) || ownAdapter ? { kind: "d2" } : { kind: "d3", prefix };
3871
+ const { separate, adapter: misplaced } = previewBuildKeys(raw);
3872
+ const refusal = "remove previewBuild.adapter: drafts render through the adapter in astro.config's adapter option";
3873
+ const adapter = siteAdapterOf(astro, code);
3874
+ if (separate && (adapter === "@astrojs/vercel" || adapter === "@astrojs/netlify")) {
3875
+ return {
3876
+ kind: "off",
3877
+ refusal: `previewBuild.separate is not supported with ${adapter}: the separate preview build would write its output where ${adapter} deploys the live site. Remove separate: true; with ${adapter} drafts render in the site's own build.`
3878
+ };
3879
+ }
3880
+ if (separate)
3881
+ return misplaced ? { kind: "d4", prefix, refusal } : { kind: "d4", prefix };
3882
+ if (misplaced)
3883
+ return { kind: "off", refusal };
3884
+ if (adapter === undefined)
3885
+ return { kind: "d3", prefix };
3886
+ return adapter === "other" ? { kind: "off" } : { kind: "d8", prefix, adapter };
3887
+ }
3888
+ function previewBuildKeys(raw) {
3889
+ const parsed = parseObjectEntries(raw.trim());
3890
+ if (parsed === null)
3891
+ return { separate: false, adapter: false };
3892
+ const adapter = parsed.entries.has("adapter") || parsed.shorthands.has("adapter");
3893
+ return { separate: parsed.entries.get("separate") === "true", adapter };
3894
+ }
3895
+ function siteAdapterOf(astro, code) {
3896
+ const own = astro.state === "literal" ? astro.entries.get("adapter") : undefined;
3897
+ if (own === undefined)
3898
+ return;
3899
+ const call = /^\s*([\w$]+)\s*\(/u.exec(own)?.[1];
3900
+ const source = call === undefined ? undefined : new RegExp(`\\bimport\\s+${call.replaceAll("$", "\\$")}\\s+from\\s+['"]([^'"]+)['"]`, "u").exec(code)?.[1];
3901
+ return Object.values(HOST_ADAPTERS).find((entry) => entry.name === source)?.name ?? "other";
3457
3902
  }
3458
3903
  async function readWranglerFile(projectDir) {
3459
- const jsonc = ["wrangler.jsonc", "wrangler.json"].map((name) => join7(projectDir, name)).find((path) => existsSync4(path));
3904
+ const jsonc = ["wrangler.jsonc", "wrangler.json"].map((name) => join8(projectDir, name)).find((path) => existsSync4(path));
3460
3905
  if (jsonc !== undefined)
3461
- return { kind: "jsonc", path: jsonc, text: await readFile5(jsonc, "utf8") };
3462
- const toml = join7(projectDir, "wrangler.toml");
3906
+ return { kind: "jsonc", path: jsonc, text: await readFile6(jsonc, "utf8") };
3907
+ const toml = join8(projectDir, "wrangler.toml");
3463
3908
  return existsSync4(toml) ? { kind: "toml", path: toml } : { kind: "none" };
3464
3909
  }
3465
- var needs = (message, lines = []) => ({
3910
+ var needs2 = (message, lines = []) => ({
3466
3911
  state: "needs-you",
3467
3912
  message,
3468
3913
  lines,
@@ -3486,7 +3931,7 @@ function d4Lines(buildCommand, exec) {
3486
3931
  function d4Step(input, file, config, prefix) {
3487
3932
  const name = basename3(file.path);
3488
3933
  if (!isRecord(config) || typeof config.name !== "string")
3489
- return needs(`${name} names no Cloudflare Worker`);
3934
+ return needs2(`${name} names no Cloudflare Worker`);
3490
3935
  const env = isRecord(config.env) ? config.env : {};
3491
3936
  let after = file.text;
3492
3937
  if (env.preview === undefined) {
@@ -3506,7 +3951,7 @@ function d4Step(input, file, config, prefix) {
3506
3951
  const scriptless = removed || config.main === undefined;
3507
3952
  if (scriptless && (listed === true || kept.length > 0)) {
3508
3953
  const entries = listed === true ? "run_worker_first: true" : kept.map(shown).join(", ");
3509
- return needs(`${name}: ${entries} needs a Worker script, and a separate preview deploy (D4) leaves the main deploy with none: remove ${listed === true ? "it" : "those entries"} (and the on-demand routes they serve), or set main to a script of your own`);
3954
+ return needs2(`${name}: ${entries} needs a Worker script, and a separate preview deploy (D4) leaves the main deploy with none: remove ${listed === true ? "it" : "those entries"} (and the on-demand routes they serve), or set main to a script of your own`);
3510
3955
  }
3511
3956
  if (removed)
3512
3957
  after = setIn(after, ["main"], undefined);
@@ -3531,65 +3976,125 @@ function d4Step(input, file, config, prefix) {
3531
3976
  edits
3532
3977
  };
3533
3978
  }
3534
- function previewDeployStep(input) {
3535
- const { file, setup } = input;
3536
- if (setup.kind !== "d3" && setup.kind !== "d4") {
3979
+ function d8Step(input, prefix, adapter) {
3980
+ if (adapter === "@astrojs/vercel") {
3981
+ return needs2("Vercel: rate-limit the preview route in the project firewall", [
3982
+ `Firewall → Add rule → If Request Path starts with ${prefix}/ → Rate Limit, ${PREVIEW_LIMIT.simple.limit} requests per ${PREVIEW_LIMIT.simple.period} seconds per IP → Deny`
3983
+ ]);
3984
+ }
3985
+ if (adapter === "@astrojs/netlify") {
3986
+ return needs2("Netlify: rate-limit the preview route", [
3987
+ `Rate limiting rule: path ${prefix}/*, 60 requests per 60 seconds per IP`,
3988
+ "every missing URL on this site, images included, runs your site's function"
3989
+ ]);
3990
+ }
3991
+ if (adapter === "@astrojs/node") {
3992
+ return needs2("your own server: drafts render in the site server", [
3993
+ "start the server with `node dist/server/entry.mjs`"
3994
+ ]);
3995
+ }
3996
+ const { file } = input;
3997
+ if (file.kind !== "jsonc") {
3998
+ return needs2(file.kind === "toml" ? "wrangler.toml can't carry the preview routing: convert it to wrangler.jsonc, then run `conloca connect` again" : "this project has no wrangler.jsonc for the preview routing");
3999
+ }
4000
+ const name = basename3(file.path);
4001
+ if (input.routes === null) {
4002
+ return needs2(`${name}: the preview routing needs the routes a build reports`, ["conloca connect --update --yes"]);
4003
+ }
4004
+ const base = prefix.slice(0, -"/_conloca/preview".length);
4005
+ const runtime = new Set([...previewOwnEntries(prefix), `${base}/_server-islands/*`]);
4006
+ if (input.routes.some((entry) => !runtime.has(entry))) {
3537
4007
  return {
3538
- state: "skipped",
3539
- message: "previewBuild serves no static-site preview (D3) or separate deploy (D4)",
4008
+ state: "done",
4009
+ message: `${name}: the Cloudflare Worker already gets every miss, the preview included`,
3540
4010
  edits: []
3541
4011
  };
3542
4012
  }
4013
+ const config = parse(file.text, [], { allowTrailingComma: true });
4014
+ if (!isRecord(config))
4015
+ return needs2(`${name} is not a JSON object`);
4016
+ const assets = isRecord(config.assets) ? config.assets : {};
4017
+ const listed = assets.run_worker_first;
4018
+ if (listed !== undefined && listed !== true && !Array.isArray(listed)) {
4019
+ return needs2(`${name} has its own run_worker_first; add ${JSON.stringify(input.routes)} to it`);
4020
+ }
4021
+ const current = Array.isArray(listed) ? listed : [];
4022
+ const missing = listed === true ? [] : input.routes.filter((entry) => !current.includes(entry));
4023
+ if (current.length + missing.length > MAX_WORKER_FIRST) {
4024
+ return needs2(`${name}: run_worker_first would have more than ${MAX_WORKER_FIRST} entries, Cloudflare's cap; merge some into wider patterns`);
4025
+ }
4026
+ let after = file.text;
4027
+ if (missing.length > 0)
4028
+ after = setIn(after, ["assets", "run_worker_first"], [...current, ...missing]);
4029
+ const handling = input.negotiate404 || assets.not_found_handling === "none" ? "none" : "404-page";
4030
+ if (assets.not_found_handling !== handling)
4031
+ after = setIn(after, ["assets", "not_found_handling"], handling);
4032
+ if (after === file.text) {
4033
+ return { state: "done", message: `${name} routes the preview through the Cloudflare adapter`, edits: [] };
4034
+ }
4035
+ return {
4036
+ state: "changed",
4037
+ message: `${name}: the preview runs on ${prefix}/* through the Cloudflare adapter, misses get ${handling === "none" ? 'the Cloudflare Worker (not_found_handling "none")' : "the 404 page"}`,
4038
+ edits: [{ path: file.path, before: file.text, after }]
4039
+ };
4040
+ }
4041
+ function previewDeployStep(input) {
4042
+ const { file, setup } = input;
4043
+ if (setup.kind === "off") {
4044
+ return { state: "skipped", message: "previewBuild serves no draft preview", edits: [] };
4045
+ }
4046
+ if (setup.kind === "d8")
4047
+ return d8Step(input, setup.prefix, setup.adapter);
3543
4048
  const pair = [setup.prefix, `${setup.prefix}/*`];
3544
4049
  const wanted = [...pair, ...(input.routes ?? []).filter((r) => !r.startsWith(setup.prefix))];
3545
4050
  if (file.kind === "none") {
3546
- return needs("this project has no wrangler.jsonc: draft previews of a static site run on Cloudflare Workers, so deploy it to Cloudflare Workers with one");
4051
+ return needs2("this project has no wrangler.jsonc: draft previews of a static site run on Cloudflare Workers, so deploy it to Cloudflare Workers with one");
3547
4052
  }
3548
4053
  if (file.kind === "toml") {
3549
- return needs("wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then run `conloca connect` again");
4054
+ return needs2("wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then run `conloca connect` again");
3550
4055
  }
3551
4056
  const config = parse(file.text, [], { allowTrailingComma: true });
3552
4057
  const name = basename3(file.path);
3553
4058
  if (!isRecord(config))
3554
- return needs(`${name} is not a JSON object`);
4059
+ return needs2(`${name} is not a JSON object`);
3555
4060
  if (config.pages_build_output_dir !== undefined) {
3556
- return needs(`${name} configures Cloudflare Pages; draft previews need Cloudflare Workers with static assets`);
4061
+ return needs2(`${name} configures Cloudflare Pages; draft previews need Cloudflare Workers with static assets`);
3557
4062
  }
3558
4063
  if (setup.kind === "d4")
3559
4064
  return d4Step(input, file, config, setup.prefix);
3560
4065
  const envs = isRecord(config.env) ? config.env : {};
3561
4066
  for (const [envName, block] of Object.entries(envs)) {
3562
4067
  if (isRecord(block) && (block.main !== undefined || block.assets !== undefined)) {
3563
- return needs(`${name}: env.${envName} sets main or assets, which replaces the dispatcher's; remove them from the env block`);
4068
+ return needs2(`${name}: env.${envName} sets main or assets, which replaces the dispatcher's; remove them from the env block`);
3564
4069
  }
3565
4070
  }
3566
4071
  const assets = isRecord(config.assets) ? config.assets : {};
3567
4072
  if (config.main !== undefined && config.main !== DISPATCHER_MAIN) {
3568
- return needs(`${name} sets its own main (${shown(config.main)}); the preview dispatcher needs main: "${DISPATCHER_MAIN}"`);
4073
+ return needs2(`${name} sets its own main (${shown(config.main)}); the preview dispatcher needs main: "${DISPATCHER_MAIN}"`);
3569
4074
  }
3570
4075
  if (assets.not_found_handling === "single-page-application") {
3571
- return needs(`${name} uses single-page-application 404 handling, which serves index.html for every miss; previews need "404-page" (or "none")`);
4076
+ return needs2(`${name} uses single-page-application 404 handling, which serves index.html for every miss; previews need "404-page" (or "none")`);
3572
4077
  }
3573
4078
  const listed = assets.run_worker_first;
3574
4079
  const everything = listed === true;
3575
4080
  if (!everything && listed !== undefined && !(Array.isArray(listed) && listed.includes(`${setup.prefix}/*`))) {
3576
- return needs(`${name} has its own run_worker_first; add ${JSON.stringify(wanted)} to it`);
4081
+ return needs2(`${name} has its own run_worker_first; add ${JSON.stringify(wanted)} to it`);
3577
4082
  }
3578
4083
  const current = Array.isArray(listed) ? listed : [];
3579
4084
  const excluded = current.find((entry) => typeof entry === "string" && entry.startsWith("!") && entry.slice(1).startsWith(setup.prefix));
3580
4085
  if (typeof excluded === "string") {
3581
- return needs(`${name}: run_worker_first excludes the preview route (${excluded}); remove that entry`);
4086
+ return needs2(`${name}: run_worker_first excludes the preview route (${excluded}); remove that entry`);
3582
4087
  }
3583
4088
  const missing = everything ? [] : wanted.filter((entry) => !current.includes(entry));
3584
4089
  if (current.length + missing.length > MAX_WORKER_FIRST) {
3585
- return needs(`${name}: run_worker_first would have more than ${MAX_WORKER_FIRST} entries, Cloudflare's cap; merge some into wider patterns`);
4090
+ return needs2(`${name}: run_worker_first would have more than ${MAX_WORKER_FIRST} entries, Cloudflare's cap; merge some into wider patterns`);
3586
4091
  }
3587
4092
  if (assets.binding !== undefined && assets.binding !== "ASSETS") {
3588
- return needs(`${name} binds the assets as ${shown(assets.binding)}; the preview dispatcher reads them as ASSETS`);
4093
+ return needs2(`${name} binds the assets as ${shown(assets.binding)}; the preview dispatcher reads them as ASSETS`);
3589
4094
  }
3590
4095
  const directory = assets.directory;
3591
4096
  if (directory !== undefined && !(typeof directory === "string" && ["dist", "./dist", "dist/", "./dist/"].includes(directory))) {
3592
- return needs(`${name} serves ${shown(directory)}; the static site and the dispatcher are served from ./dist`);
4097
+ return needs2(`${name} serves ${shown(directory)}; the static site and the dispatcher are served from ./dist`);
3593
4098
  }
3594
4099
  let after = file.text;
3595
4100
  const wrote = [];
@@ -3688,18 +4193,18 @@ function sharedQuotaRoutes(routes, prefix) {
3688
4193
  }
3689
4194
 
3690
4195
  // src/lib/connect/framing.ts
3691
- import { readFile as readFile6 } from "node:fs/promises";
3692
- import { join as join9, relative as relative2 } from "node:path";
4196
+ import { readFile as readFile7 } from "node:fs/promises";
4197
+ import { join as join10, relative as relative2 } from "node:path";
3693
4198
  import { editorUiOrigin, parentRoot } from "@conloca/content-api/editor-host";
3694
4199
 
3695
4200
  // src/lib/project-module.ts
3696
4201
  import { createRequire } from "node:module";
3697
- import { join as join8 } from "node:path";
4202
+ import { join as join9 } from "node:path";
3698
4203
  import { pathToFileURL } from "node:url";
3699
4204
  async function importFromProject(projectDir, specifier) {
3700
4205
  let entry;
3701
4206
  try {
3702
- entry = createRequire(join8(projectDir, "package.json")).resolve(specifier);
4207
+ entry = createRequire(join9(projectDir, "package.json")).resolve(specifier);
3703
4208
  } catch {
3704
4209
  return "missing";
3705
4210
  }
@@ -3722,7 +4227,7 @@ async function loadFramingHelpers(projectDir) {
3722
4227
  }
3723
4228
  var HEADERS_FILE = "public/_headers";
3724
4229
  async function readText(path) {
3725
- return readFile6(path, "utf8").catch(() => null);
4230
+ return readFile7(path, "utf8").catch(() => null);
3726
4231
  }
3727
4232
  function vercelWithRules(text, snippets) {
3728
4233
  let vercel;
@@ -3757,11 +4262,11 @@ async function framingStep(projectDir, endpoint) {
3757
4262
  }
3758
4263
  const snippets = helpers.framingSnippets(editorRoot);
3759
4264
  const blockers = await helpers.findFramingBlockers(projectDir);
3760
- const headersPath = join9(projectDir, HEADERS_FILE);
3761
- const vercelPath = join9(projectDir, "vercel.json");
4265
+ const headersPath = join10(projectDir, HEADERS_FILE);
4266
+ const vercelPath = join10(projectDir, "vercel.json");
3762
4267
  const [headers, netlify, vercel] = await Promise.all([
3763
4268
  readText(headersPath),
3764
- readText(join9(projectDir, "netlify.toml")),
4269
+ readText(join10(projectDir, "netlify.toml")),
3765
4270
  readText(vercelPath)
3766
4271
  ]);
3767
4272
  const headersRule = netlify === null ? snippets.cloudflareHeaders : snippets.netlifyHeaders;
@@ -3820,9 +4325,107 @@ ${headersRule}`;
3820
4325
  };
3821
4326
  }
3822
4327
 
4328
+ // src/lib/connect/host.ts
4329
+ import { existsSync as existsSync5 } from "node:fs";
4330
+ import { readdir, readFile as readFile8, stat } from "node:fs/promises";
4331
+ import { dirname as dirname5, isAbsolute, join as join11, relative as relative3, sep as sep2 } from "node:path";
4332
+ import { parse as parse2 } from "jsonc-parser";
4333
+ var HOST_CHOICES = "vercel|netlify|cloudflare|node";
4334
+ var D2_ENTRY = ".conloca/preview-server/server/entry.mjs";
4335
+ var D8_ENTRY = "dist/server/entry.mjs";
4336
+ var NODE_ENTRIES = [D8_ENTRY, D2_ENTRY];
4337
+ var STARTER_MAX_BYTES = 1024 * 1024;
4338
+ function foldersUp(projectDir, repoRoot) {
4339
+ const folders = [];
4340
+ for (let dir = projectDir;; dir = dirname5(dir)) {
4341
+ const rel = relative3(repoRoot, dir);
4342
+ if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel))
4343
+ break;
4344
+ folders.push(dir);
4345
+ if (rel === "" || dirname5(dir) === dir)
4346
+ break;
4347
+ }
4348
+ return folders;
4349
+ }
4350
+ var startsEntry = (text) => NODE_ENTRIES.some((entry) => text.includes(entry));
4351
+ function startsServer(name, text) {
4352
+ if (name.startsWith("Dockerfile")) {
4353
+ return text.split(`
4354
+ `).some((line) => /^\s*(CMD|ENTRYPOINT)\b/i.test(line) && startsEntry(line));
4355
+ }
4356
+ if (name === "Procfile" || name === "fly.toml")
4357
+ return startsEntry(text);
4358
+ const pkg = parse2(text);
4359
+ const scripts = isRecord(pkg) && isRecord(pkg.scripts) ? Object.values(pkg.scripts) : [];
4360
+ return scripts.some((script) => typeof script === "string" && startsEntry(script));
4361
+ }
4362
+ var isStarterFile = (name) => name.startsWith("Dockerfile") || ["Procfile", "fly.toml", "package.json"].includes(name);
4363
+ async function nodeStarters(dir) {
4364
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
4365
+ const names = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).filter(isStarterFile);
4366
+ const starts = await Promise.all(names.map(async (name) => {
4367
+ const path = join11(dir, name);
4368
+ if ((await stat(path)).size > STARTER_MAX_BYTES)
4369
+ return false;
4370
+ return startsServer(name, await readFile8(path, "utf8"));
4371
+ }));
4372
+ return names.filter((_, index) => starts[index]).map((name) => join11(dir, name));
4373
+ }
4374
+ async function detectHost(input) {
4375
+ const UNKNOWN = {
4376
+ ok: false,
4377
+ reason: "unknown",
4378
+ message: `can't tell where this site deploys: pass --host ${HOST_CHOICES}`
4379
+ };
4380
+ if (input.flag !== undefined)
4381
+ return { ok: true, host: input.flag, evidence: ["--host"] };
4382
+ const folders = foldersUp(input.projectDir, input.repoRoot);
4383
+ if (folders.length === 0)
4384
+ return UNKNOWN;
4385
+ const wrangler = await readWranglerFile(input.projectDir);
4386
+ const name = (path) => relative3(input.repoRoot, path) || path;
4387
+ if (wrangler.kind === "jsonc") {
4388
+ const config = parse2(wrangler.text);
4389
+ if (isRecord(config) && config.main === DISPATCHER_MAIN) {
4390
+ return { ok: true, host: "cloudflare-d3", evidence: [name(wrangler.path)] };
4391
+ }
4392
+ }
4393
+ const evidence = [];
4394
+ const code = input.astroText.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gmu, "");
4395
+ const adapter = /@astrojs\/(vercel|netlify|cloudflare|node)\b/u.exec(code)?.[1];
4396
+ if (adapter === "vercel" || adapter === "netlify" || adapter === "cloudflare" || adapter === "node") {
4397
+ evidence.push({ host: adapter, source: "astro.config" });
4398
+ }
4399
+ const starters = await Promise.all(folders.map(nodeStarters));
4400
+ for (const [index, dir] of folders.entries()) {
4401
+ if (existsSync5(join11(dir, "vercel.json")))
4402
+ evidence.push({ host: "vercel", source: name(join11(dir, "vercel.json")) });
4403
+ if (existsSync5(join11(dir, "netlify.toml"))) {
4404
+ evidence.push({ host: "netlify", source: name(join11(dir, "netlify.toml")) });
4405
+ }
4406
+ for (const path of starters[index] ?? [])
4407
+ evidence.push({ host: "node", source: name(path), starter: true });
4408
+ }
4409
+ if (wrangler.kind !== "none")
4410
+ evidence.push({ host: "cloudflare", source: name(wrangler.path) });
4411
+ const [first] = evidence;
4412
+ const nodeUnstarted = evidence.every((item) => item.host === "node" && !item.starter);
4413
+ if (first === undefined || nodeUnstarted)
4414
+ return UNKNOWN;
4415
+ const other = evidence.find((item) => item.host !== first.host);
4416
+ if (other !== undefined) {
4417
+ return {
4418
+ ok: false,
4419
+ reason: "conflict",
4420
+ message: `${first.source} names ${first.host} but ${other.source} deploys to ${other.host}: pass --host ${HOST_CHOICES}`
4421
+ };
4422
+ }
4423
+ return { ok: true, host: first.host, evidence: evidence.map((item) => item.source) };
4424
+ }
4425
+
3823
4426
  // src/lib/connect/leftovers.ts
3824
- import { readdir, readFile as readFile7 } from "node:fs/promises";
3825
- import { join as join10, relative as relative3 } from "node:path";
4427
+ import { readdir as readdir2, readFile as readFile9 } from "node:fs/promises";
4428
+ import { join as join12, relative as relative4 } from "node:path";
3826
4429
 
3827
4430
  // src/lib/legacy-key.ts
3828
4431
  var LEGACY_KEY_NAME = "CONLOCA_BUILD_TOKEN";
@@ -3956,16 +4559,16 @@ function deletionDiff(path, text, deleted) {
3956
4559
 
3957
4560
  // src/lib/connect/leftovers.ts
3958
4561
  async function leftoversStep(repoRoot) {
3959
- const folder = join10(repoRoot, ".github", "workflows");
3960
- const names = (await readdir(folder).catch(() => [])).filter((name) => /\.ya?ml$/.test(name));
4562
+ const folder = join12(repoRoot, ".github", "workflows");
4563
+ const names = (await readdir2(folder).catch(() => [])).filter((name) => /\.ya?ml$/.test(name));
3961
4564
  names.sort();
3962
- const texts = await Promise.all(names.map((name) => readFile7(join10(folder, name), "utf8").catch(() => null)));
4565
+ const texts = await Promise.all(names.map((name) => readFile9(join12(folder, name), "utf8").catch(() => null)));
3963
4566
  const edits = [];
3964
4567
  const manual = [];
3965
4568
  for (const [index, name] of names.entries()) {
3966
- const path = join10(folder, name);
4569
+ const path = join12(folder, name);
3967
4570
  const text = texts[index] ?? null;
3968
- const finding = text === null ? null : legacyKeyFinding(relative3(repoRoot, path), text);
4571
+ const finding = text === null ? null : legacyKeyFinding(relative4(repoRoot, path), text);
3969
4572
  if (text === null || finding === null)
3970
4573
  continue;
3971
4574
  if (finding.deleted.length > 0) {
@@ -3993,80 +4596,9 @@ async function leftoversStep(repoRoot) {
3993
4596
  } : { state: "done", message: "no workflow names the old build key", edits: [] };
3994
4597
  }
3995
4598
 
3996
- // src/lib/connect/site-domain.ts
3997
- import { addressSiteName, isValidSiteBase } from "@conloca/content-api";
3998
- function isSitesConfig(value) {
3999
- return isRecord(value) && isRecord(value.sites) && Object.values(value.sites).every((site) => isRecord(site) && Array.isArray(site.locales) && typeof site.defaultLocale === "string" && (site.domains === undefined || isRecord(site.domains)) && (site.base === undefined || typeof site.base === "string"));
4000
- }
4001
- function siteBase(base) {
4002
- const leading = base === null || base.startsWith("/") ? base ?? "/" : `/${base}`;
4003
- return leading.endsWith("/") ? leading : `${leading}/`;
4004
- }
4005
- function writeSiteAddress(input) {
4006
- const { path, text, site } = input;
4007
- const url = URL.canParse(site) ? new URL(site) : null;
4008
- if (url?.protocol !== "https:") {
4009
- return { state: "needs-you", message: `Astro's site must be an https URL, got ${site}`, edits: [] };
4010
- }
4011
- const base = siteBase(input.base);
4012
- if (!isValidSiteBase(base)) {
4013
- return {
4014
- state: "needs-you",
4015
- message: `Astro's base ${input.base} is not a path the editor can open`,
4016
- edits: []
4017
- };
4018
- }
4019
- let config;
4020
- try {
4021
- config = JSON.parse(text);
4022
- } catch {
4023
- return { state: "failed", message: `${path} is not valid JSON`, edits: [] };
4024
- }
4025
- if (!isSitesConfig(config)) {
4026
- return { state: "failed", message: `${path} has no readable sites map`, edits: [] };
4027
- }
4028
- const name = addressSiteName(config);
4029
- const entry = name === null ? undefined : config.sites[name];
4030
- if (name === null || entry === undefined) {
4031
- return {
4032
- state: "needs-you",
4033
- message: `${path} lists several sites and none is named default; add the domain to the right one yourself`,
4034
- lines: [`"domains": { "<locale>": "${url.hostname}" }`, ...base === "/" ? [] : [`"base": "${base}"`]],
4035
- edits: []
4036
- };
4037
- }
4038
- const host = url.hostname;
4039
- const locale = entry.defaultLocale;
4040
- const domain = entry.domains?.[locale];
4041
- const kept = [
4042
- ...domain !== undefined && domain !== host ? [`domains.${locale} is ${domain}, not ${host}`] : [],
4043
- ...entry.base !== undefined && entry.base !== base ? [`base is ${entry.base}, not ${base}`] : []
4044
- ];
4045
- if (kept.length === 0 && domain !== undefined && (entry.base !== undefined || base === "/")) {
4046
- return { state: "done", message: `site '${name}' already lists ${host}`, edits: [] };
4047
- }
4048
- entry.domains = { ...entry.domains, [locale]: host };
4049
- if (base !== "/" || entry.base !== undefined)
4050
- entry.base = base;
4051
- const edits = [{ path, before: text, after: jsonLike(text, config) }];
4052
- if (kept.length > 0) {
4053
- return {
4054
- state: "differs",
4055
- message: `site '${name}' in ${path}: ${kept.join("; ")} (kept yours)`,
4056
- edits: [],
4057
- replacement: edits
4058
- };
4059
- }
4060
- return {
4061
- state: "changed",
4062
- message: `wrote ${host}${base === "/" ? "" : ` and base ${base}`} into site '${name}'`,
4063
- edits
4064
- };
4065
- }
4066
-
4067
4599
  // src/lib/sites-config.ts
4068
- import { readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises";
4069
- import { join as join11 } from "node:path";
4600
+ import { readFile as readFile10, writeFile as writeFile2 } from "node:fs/promises";
4601
+ import { join as join13 } from "node:path";
4070
4602
  var DEFAULT_LOCALES = ["en"];
4071
4603
  function newSitesConfig(siteName) {
4072
4604
  return {
@@ -4075,11 +4607,11 @@ function newSitesConfig(siteName) {
4075
4607
  };
4076
4608
  }
4077
4609
  async function ensureSiteInSitesConfig(contentPath, siteName) {
4078
- const path = join11(contentPath, "sites.json");
4610
+ const path = join13(contentPath, "sites.json");
4079
4611
  let sitesConfig = { sites: {}, globalLocales: [...DEFAULT_LOCALES] };
4080
4612
  let existed = false;
4081
4613
  try {
4082
- const parsed = JSON.parse(await readFile8(path, "utf-8"));
4614
+ const parsed = JSON.parse(await readFile10(path, "utf-8"));
4083
4615
  if (parsed.sites) {
4084
4616
  sitesConfig = parsed;
4085
4617
  } else {
@@ -4095,59 +4627,25 @@ async function ensureSiteInSitesConfig(contentPath, siteName) {
4095
4627
  `, "utf-8");
4096
4628
  return { path, existed, added: true };
4097
4629
  }
4098
-
4099
- // src/lib/versions.ts
4100
- var NUMERIC = /^\d+$/;
4101
- function compareIdentifiers(a, b) {
4102
- const aNumeric = NUMERIC.test(a);
4103
- const bNumeric = NUMERIC.test(b);
4104
- if (aNumeric && bNumeric)
4105
- return Number(a) - Number(b);
4106
- if (aNumeric !== bNumeric)
4107
- return aNumeric ? -1 : 1;
4108
- return a < b ? -1 : a > b ? 1 : 0;
4109
- }
4110
- function compareVersions(a, b) {
4111
- const [aCore = "", ...aPre] = a.split("+")[0]?.split("-") ?? [];
4112
- const [bCore = "", ...bPre] = b.split("+")[0]?.split("-") ?? [];
4113
- const aParts = aCore.split(".").map(Number);
4114
- const bParts = bCore.split(".").map(Number);
4115
- for (let i = 0;i < 3; i++) {
4116
- const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
4117
- if (diff !== 0)
4118
- return diff;
4119
- }
4120
- const aIds = aPre.length > 0 ? aPre.join("-").split(".") : [];
4121
- const bIds = bPre.length > 0 ? bPre.join("-").split(".") : [];
4122
- if (aIds.length === 0 || bIds.length === 0)
4123
- return bIds.length - aIds.length;
4124
- for (let i = 0;i < Math.min(aIds.length, bIds.length); i++) {
4125
- const diff = compareIdentifiers(aIds[i] ?? "", bIds[i] ?? "");
4126
- if (diff !== 0)
4127
- return diff;
4630
+ function siteDomainsOf(sitesText) {
4631
+ let parsed;
4632
+ try {
4633
+ parsed = JSON.parse(sitesText);
4634
+ } catch {
4635
+ return [];
4128
4636
  }
4129
- return aIds.length - bIds.length;
4130
- }
4131
- function versionFloor(spec) {
4132
- return spec.match(/\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/)?.[0] ?? null;
4133
- }
4134
- var SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"];
4135
- function conlocaDependencies(manifest) {
4136
- return SECTIONS.flatMap((section) => {
4137
- const deps = manifest[section];
4138
- if (!isRecord(deps))
4139
- return [];
4140
- return Object.entries(deps).flatMap(([name, spec]) => name.startsWith("@conloca/") && typeof spec === "string" ? [{ section, name, spec }] : []);
4141
- });
4637
+ const sites = isRecord(parsed) && isRecord(parsed.sites) ? Object.values(parsed.sites) : [];
4638
+ const domains = sites.flatMap((site) => isRecord(site) && isRecord(site.domains) ? Object.values(site.domains).filter((d) => typeof d === "string") : []);
4639
+ return [...new Set(domains)];
4142
4640
  }
4143
4641
 
4144
4642
  // src/commands/setup.ts
4145
- import { mkdir as mkdir2, readFile as readFile9, writeFile as writeFile3 } from "node:fs/promises";
4146
- import { join as join12, resolve as resolve5 } from "node:path";
4643
+ import { mkdir as mkdir2, readFile as readFile11, writeFile as writeFile3 } from "node:fs/promises";
4644
+ import { join as join14, resolve as resolve5 } from "node:path";
4147
4645
  import { stampSkill } from "@conloca/content-api/skill-stamp";
4148
4646
 
4149
4647
  // src/templates/conloca-skill.md
4150
- var conloca_skill_default = "---\nname: conloca\ndescription: Load when working on an Astro site using Conloca CMS — @conloca/* packages, .vxjson content, sites.json.\n---\n\n# Conloca CMS\n\nConloca stores pages as `.vxjson` files (visual pages built from Puck components) and `.mdx` files under `content/`, and\nrenders them through the `@conloca/astro-cms` Astro integration. The visual editor lives at `/__cms` on the dev server\nonly.\n\n## First move: `conloca doctor`\n\nFor any Conloca problem — blank page, 404 on a content page, editor not loading, build failure — run this before reading\nsource:\n\n```bash\nconloca doctor # human-readable report\nconloca doctor --json # single {ok, problems} object on stdout\n```\n\n`conloca <command>` in this skill means `npx @conloca/cli@<version> <command>`: use the exact version a Conloca prompt\ngave you, `@latest` when none did. Never run a different version than the prompt names.\n\nIt checks the content directory (sites.json complete, site directories present, every content file indexes cleanly) and,\nwhen an astro.config is present, the Astro wiring: content config, conlocaCMS import and options, react() order, peer\ndependencies, tsconfig jsx, prerender under server output, Conloca pages hidden behind a `src/pages` file, static pages\nwith no Conloca pages, and siteStyles. Each problem names the broken file and the fix. It is read-only and exits 1 on\nerrors; warnings alone exit 0.\n\nNew project from an empty directory? `conloca create <dir>` writes and installs the whole wired site. An existing Astro\nsite: `conloca connect` installs the packages, wires `astro.config` and writes the site's domain for the workspace\neditor; `conloca astro setup` only scaffolds the starter files.\n\n## Upgrading Conloca\n\nTo move a site to a newer Conloca release:\n\n1. In the site's folder run `npx @conloca/cli@latest upgrade` (or the exact version a Conloca prompt gave you). It\n raises each `@conloca/*` package to the version that CLI release pins in one install, applies the changes between\n versions, refreshes this skill and runs `conloca doctor`. `--dry-run` shows the diffs and changes nothing, `--json`\n prints one object on stdout, `--project <dir>` picks the site folder.\n2. Exit `2`: it lists what a person must change first; nothing was touched. Make those changes, then run it again.\n3. Exit `1`: it failed and put `package.json`, the lockfile and every changed file back. Fix what it names, run the\n install command its message gives when `node_modules` needs it, and run it again.\n4. A `SKILL.new.md` beside a skill means that skill had local edits, so the new text was written next to it: merge it\n into the skill by hand, then delete `SKILL.new.md`.\n5. Review `git diff`, run the build, then commit and push yourself — the command never commits or pushes.\n\nNever edit `@conloca/*` versions by hand: each package has its own version, and `upgrade` moves them to the versions one\nCLI release pins.\n\n## The files a working site needs\n\n- `astro.config.mjs` — registers `react()` and `conlocaCMS(...)`\n- `src/content.config.ts` — declares the content collections (without it every content page 404s)\n- `content/sites.json` — sites with their `locales` and `defaultLocale`, plus `globalLocales`\n- `src/puck.config.tsx` — registers the Puck components pages are built from\n- `src/layouts/Layout.astro` — the page layout content pages render into\n- `src/components/puck/*` and `src/schemas/data.ts` — starter components and data-collection schemas\n\nRun `conloca astro setup` inside an existing Astro project. It scaffolds the content config, components, schemas, page\nlayout, and content directories, preserving existing generated files. It adds the default site to `sites.json` when\nmissing. It prints the `astro.config` wiring rather than writing that file: merge the printed options into the existing\nconfig, then run `conloca doctor` to verify the result — or run `conloca connect`, which writes the wiring itself.\n`conloca init . <site-name>` adds another site to sites.json.\n\n## Install: the exact package set\n\n```bash\nnpm install @conloca/astro-cms @conloca/content-api @conloca/mdx @puckeditor/core @astrojs/react @vitejs/plugin-react typia\nnpm install -D ttsc @ttsc/unplugin\n```\n\n`@puckeditor/core` is what the generated components import — there is no other Puck package to install.\n\nttsc compiles with native TypeScript 7, and only one the site declares: a TypeScript 5 or 6 already installed (a\nworkspace root's) keeps the package manager from adding 7 as ttsc's peer. Add `typescript@^7.0.2`, or, keeping\nTypeScript 5 or 6 as `@astrojs/check` requires, an alias:\n`npm install -D typescript@^6.0.3 '@typescript/native@npm:typescript@^7.0.2'`.\n\n## Canonical astro.config.mjs\n\nThe minimal working config, matching what `conloca astro setup` prints:\n\n```js\nimport react from '@astrojs/react';\nimport { conlocaCMS } from '@conloca/astro-cms/node';\nimport { defineConfig } from 'astro/config';\nimport { schemaTypia } from './typia-vite.mjs';\n\nexport default defineConfig({\n integrations: [\n react(),\n conlocaCMS({\n contentRoot: './content',\n puckConfigPath: './src/puck.config.tsx',\n schemasPath: './src/schemas/data.ts',\n layout: './src/layouts/Layout.astro',\n }),\n ],\n vite: { plugins: [...schemaTypia()] },\n});\n```\n\n`react()` must come before `conlocaCMS()` — doctor checks the order. `src/schemas/data.ts` declares each data collection\nas a TypeScript type plus its generated Typia validator (`typia.plain.createValidatePrune<T>()`) and form metadata\n(`typia.json.schema<T>()`); `typia-vite.mjs` is the native transform that generates them, so it must stay in\n`vite.plugins`. And `src/content.config.ts`:\n\n```ts\nimport { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';\nimport { dataSchemas } from './schemas/data';\n\nexport const collections = {\n pages: conlocaPages(),\n ...conlocaData({ dataSchemas }),\n ...conlocaFragments(),\n};\n```\n\nEvery collection is declared here by name — content the config does not name fails the build instead of silently not\nbuilding.\n\n## Where errors appear\n\n- `astro dev` runs in the foreground: config and integration errors print to the terminal running it, and page errors\n also show in the browser error overlay. There is no separate log command — read that terminal.\n- A page referencing a Puck component type missing from puck.config.tsx serves HTTP 200 with a blank region and a clean\n browser console. The signal is `[Conloca] Page references N component type(s) missing from your Puck config: ...` in\n the dev-server or build terminal.\n- `conloca doctor` finds them before a build: C14 warns about every component type or prop a page stores that the Puck\n config does not declare.\n- The editor at `/__cms` exists only on the dev server. A production build without it is not a bug.\n\n## Writing content from the command line\n\nNever hand-write files under `content/`, and do not reach for HTTP endpoints: these commands write what the editor\nwrites, so the result is editable at `/__cms` right away. Each takes `--json` for a machine-readable result.\n\n```bash\nconloca page create --site default --collection pages --pathname /about --title 'About us' --content about.json\nconloca page update /about --description 'Who we are' --image /media/hero.jpg\nconloca data create site --name contact --data contact.json\nconloca data update site contact --data - < contact.json\nconloca asset add ~/Pictures/hero.jpg --alt 'Fresh bread on the counter'\n```\n\n- `page create` — a new page. `--content` takes Puck data `{ root, content, zones }` from a file or `-` (stdin), never\n inline JSON; `--description`, `--image`, `--canonical` and `--robots` fill its page settings.\n- `page update` — change an existing page, found by id or pathname; only the flags given change, and an empty value\n (`--robots ''`) clears a field.\n- `data create` / `data update` — a shared entry (contact details, a header menu): a JSON object from a file or\n `--data -`. `data update` replaces the entry's whole object: send every field, not just the changed one. Declare the\n collection's type in `src/schemas/data.ts`; the first `data create` wires the data schemas.\n- `asset add` — an image into the media folder; it prints the reference an image field stores, e.g. `/media/hero.jpg`.\n\nA layout reads a shared entry by name:\n\n```ts\nimport { getCollection } from 'astro:content';\nimport { conlocaDataEntry } from '@conloca/astro-cms/collections';\nimport { dataSchemas } from '../schemas/data';\n\nconst contact = conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'contact', 'en');\ncontact.phone; // typed by the `site` schema\n```\n\nA missing name, or one saved in several locales with none given, throws and fails the build instead of rendering empty.\n\nEntries a page's blocks list (team, testimonials) bind to the route with\n`routing.routes.<name>.dataBindings.collections`; a block's Puck `resolveData` then reads them from\n`metadata.collections.<name>`.\n\nAfter writing content, run the build: it validates every entry against its schema.\n\n## Routing\n\n- `layout: './src/layouts/Layout.astro'` alone injects a catch-all `/[...slug]` route over the `pages` collection, with\n `prerender: true` and `fallback: '404'`.\n- Passing `routing` replaces that default route entirely and the top-level `layout` is then ignored — name it per route\n instead: `routing: { routes: { pages: { pattern: '/[...slug]', layout: './src/layouts/Layout.astro' } } }`.\n- `routing: true` is the same default catch-all with no layout.\n- `fallback: '404'` returns a bare 404 when no content matches the pattern; `'passthrough'` hands the miss back to Astro\n so the site's own `/404` page renders, with a real 404 status.\n- Trap: a `src/pages` file always wins over a Conloca page at the same path, and Astro says nothing. Doctor warns when\n one hides a page; delete the file in the same change that makes the Conloca page live.\n\n## Adding Conloca to an existing Astro site\n\n- Switching to `output: 'server'`: first add `export const prerender = true` to every existing file under `src/pages/`,\n then flip the output — otherwise those pages silently stop being static. Doctor errors on files that miss it.\n- Existing `.mdx` content: set the site's `mdxPages` path in `content/sites.json` (relative to the project root, e.g.\n `./src/content/docs`). `.mdx` files under it surface in the CMS as pages of that site; the default locale lives at\n `<mdxPages>/<slug>.mdx`, other locales at `<mdxPages>/<locale>/<slug>.mdx`.\n- Plain `.md` files are never adopted — only `.mdx` and `.vxjson` are recognized as pages. Rename `.md` to `.mdx` to\n bring a file under management.\n\n## Converting an existing Astro page\n\nUse this when the user names existing `src/pages` routes to make editable. Convert only those routes.\n\n1. Run `conloca upgrade` (with the version your prompt gave, as defined above). Stop and report if it or\n `conloca doctor` fails: the commands below ship in that release.\n2. Run `conloca routes` and check each named route is listed. Dynamic routes (`[slug].astro`, content collection pages)\n and non-default-locale routes are out of scope and never listed.\n3. Before changing anything, run `conloca compare --reset --routes /a,/b` with exactly the routes the user named; it\n builds the site and saves a fresh baseline.\n4. Run `conloca components --json` to see the components the site already has.\n5. Port each section of the page to a React component in `src/components/puck/` whose editable text and images are\n fields. `.astro` components cannot be Puck components: port, do not reuse. Scoped `<style>` moves into a stylesheet\n listed in `siteStyles`; `<script>` and `client:` islands keep working through `withHydration()`; links stay links;\n images that become fields go into the assets folder with `conloca asset add`.\n6. Render the page through the layout the original used: point `conlocaCMS` (or a per-route layout) at it and adapt it\n to the props Conloca passes (`title`, `description`, `page`).\n7. Text from data files (like `src/data/*.ts`): per-page text goes into the page; values shared across pages go into\n data entries, moved once, on the first conversion that needs them. Every importer of those values (pages, layout,\n endpoints, browser components through props) then reads the same data entries, so there is one copy. Pages the user\n did not name may change only there, and their output must stay identical.\n8. The shared header and footer stay code in the layout. Their texts and links (menu items, footer links, contact\n details) move into a data entry the layout reads. Fragments are for prose blocks placed inside pages.\n9. Read a shared entry by a fixed name and fail the build when it is missing or duplicated:\n `conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'header', 'en').menu` throws in both cases.\n10. Write all content through the CLI: `conloca page create` / `conloca page update` (with `--content` and the metadata\n flags), `conloca data create` / `conloca data update`, `conloca asset add`. Never hand-write content files.\n11. Delete the old `.astro` file in the same change that makes the Conloca page live. A `src/pages` file always wins\n over a Conloca page at the same path, so the page cannot be seen before that; `conloca compare` is the check, not\n the browser.\n12. Run `conloca compare` again. Every route you did not convert must be identical (its linked stylesheets too); every\n converted route must keep its text, links, `<head>` tags and status; a route that became a Conloca page without\n being named fails. Fix and rerun until it passes, then run `conloca doctor`.\n13. Report every changed file, every page you were not asked to convert whose code changed, every allowed change\n `conloca compare` listed (for example island props that now carry shared values), and anything that could not be\n converted faithfully.\n\nThe workspace also has an MCP server for editing content remotely: pages, fragments and data entries on pushed branches.\nIt cannot change code, upload media or publish. Use the address the editor's prompt gives you; never guess or hardcode\none. Setup and limits: https://conloca.com/workspace-mcp/.\n\n## Custom Puck components\n\nFollow the generated examples in `src/components/puck/` — that is the one proven path:\n\n1. Write a render component plus a `ComponentConfig` wrapped in `withLayout` from `src/components/ComponentLayout.tsx`,\n mirroring the generated `HeadingComponent.tsx` / `Heading.tsx` pair.\n2. Register the component and its Props type in `src/puck.config.tsx`: add it to the `Components` type and the\n `components` map (and optionally a `categories` entry).\n3. Types come from `@puckeditor/core`. If `.tsx` components misrender or fail typecheck, set tsconfig\n `\"jsx\": \"react-jsx\"` — doctor's advisory warning covers this.\n\nA component referenced by stored content but not registered renders blank — see \"Where errors appear\".\n\n## Known limits — by design, do not fight them\n\n- MDX fragments render prose only.\n `Unknown component <X>: fragments render as plain content and cannot use React components.` is intentional: fragment\n content is treated as untrusted, so `{...}` expressions and `import`/`export` statements are rejected too. Do not try\n to sneak components in.\n- Unknown Puck component types render as nothing; the dev-server or build console names them. The fix is registering the\n type in `puck.config.tsx`, not editing the stored content.\n";
4648
+ var conloca_skill_default = "---\nname: conloca\ndescription: Load when working on an Astro site using Conloca CMS — @conloca/* packages, .vxjson content, sites.json.\n---\n\n# Conloca CMS\n\nConloca stores pages as `.vxjson` files (visual pages built from Puck components) and `.mdx` files under `content/`, and\nrenders them through the `@conloca/astro-cms` Astro integration. The visual editor lives at `/__cms` on the dev server\nonly.\n\n## First move: `conloca doctor`\n\nFor any Conloca problem — blank page, 404 on a content page, editor not loading, build failure — run this before reading\nsource:\n\n```bash\nconloca doctor # human-readable report\nconloca doctor --json # single {ok, problems} object on stdout\n```\n\n`conloca <command>` in this skill means `npx @conloca/cli@<version> <command>`: use the exact version a Conloca prompt\ngave you, `@latest` when none did. Never run a different version than the prompt names.\n\nIt checks the content directory (sites.json complete, site directories present, every content file indexes cleanly) and,\nwhen an astro.config is present, the Astro wiring: content config, conlocaCMS import and options, react() order, peer\ndependencies, tsconfig jsx, prerender under server output, Conloca pages hidden behind a `src/pages` file, static pages\nwith no Conloca pages, and siteStyles. Each problem names the broken file and the fix. It is read-only and exits 1 on\nerrors; warnings alone exit 0.\n\nNew project from an empty directory? `conloca create <dir>` writes and installs the whole wired site. An existing Astro\nsite: `conloca connect` installs the packages, wires `astro.config` and writes the site's domain for the workspace\neditor; `conloca astro setup` only scaffolds the starter files.\n\n## Upgrading Conloca\n\nTo move a site to a newer Conloca release:\n\n1. In the site's folder run `npx @conloca/cli@latest upgrade` (or the exact version a Conloca prompt gave you). It\n raises each `@conloca/*` package to the version that CLI release pins in one install, applies the changes between\n versions, refreshes this skill and runs `conloca doctor`. `--dry-run` shows the diffs and changes nothing, `--json`\n prints one object on stdout, `--project <dir>` picks the site folder.\n2. Exit `2`: it lists what a person must change first; nothing was touched. Make those changes, then run it again.\n3. Exit `1`: it failed and put `package.json`, the lockfile and every changed file back. Fix what it names, run the\n install command its message gives when `node_modules` needs it, and run it again.\n4. A `SKILL.new.md` beside a skill means that skill had local edits, so the new text was written next to it: merge it\n into the skill by hand, then delete `SKILL.new.md`.\n5. Review `git diff`, run the build, then commit and push yourself — the command never commits or pushes.\n\nNever edit `@conloca/*` versions by hand: each package has its own version, and `upgrade` moves them to the versions one\nCLI release pins.\n\nDraft previews: updating `@conloca/cloud-astro` moves a site that previewed from its own server (D2), or an\n`@astrojs/cloudflare` server-rendered site, to drafts rendered in the site's own build (d8) on its next build. `upgrade`\nmakes the edits explicit: the start command becomes `node dist/server/entry.mjs` and the `previewBuild` options d8\nignores go. Preview tabs opened before the update stop working; editors reopen Preview.\n\n## The files a working site needs\n\n- `astro.config.mjs` — registers `react()` and `conlocaCMS(...)`\n- `src/content.config.ts` — declares the content collections (without it every content page 404s)\n- `content/sites.json` — sites with their `locales` and `defaultLocale`, plus `globalLocales`\n- `src/puck.config.tsx` — registers the Puck components pages are built from\n- `src/layouts/Layout.astro` — the page layout content pages render into\n- `src/components/puck/*` and `src/schemas/data.ts` — starter components and data-collection schemas\n\nRun `conloca astro setup` inside an existing Astro project. It scaffolds the content config, components, schemas, page\nlayout, and content directories, preserving existing generated files. It adds the default site to `sites.json` when\nmissing. It prints the `astro.config` wiring rather than writing that file: merge the printed options into the existing\nconfig, then run `conloca doctor` to verify the result — or run `conloca connect`, which writes the wiring itself.\n`conloca init . <site-name>` adds another site to sites.json.\n\n## Install: the exact package set\n\n```bash\nnpm install @conloca/astro-cms @conloca/content-api @conloca/mdx @puckeditor/core @astrojs/react @vitejs/plugin-react typia\nnpm install -D ttsc @ttsc/unplugin\n```\n\n`@puckeditor/core` is what the generated components import — there is no other Puck package to install.\n\nttsc compiles with native TypeScript 7, and only one the site declares: a TypeScript 5 or 6 already installed (a\nworkspace root's) keeps the package manager from adding 7 as ttsc's peer. Add `typescript@^7.0.2`, or, keeping\nTypeScript 5 or 6 as `@astrojs/check` requires, an alias:\n`npm install -D typescript@^6.0.3 '@typescript/native@npm:typescript@^7.0.2'`.\n\n## Canonical astro.config.mjs\n\nThe minimal working config, matching what `conloca astro setup` prints:\n\n```js\nimport react from '@astrojs/react';\nimport { conlocaCMS } from '@conloca/astro-cms/node';\nimport { defineConfig } from 'astro/config';\nimport { schemaTypia } from './typia-vite.mjs';\n\nexport default defineConfig({\n integrations: [\n react(),\n conlocaCMS({\n contentRoot: './content',\n puckConfigPath: './src/puck.config.tsx',\n schemasPath: './src/schemas/data.ts',\n layout: './src/layouts/Layout.astro',\n }),\n ],\n vite: { plugins: [...schemaTypia()] },\n});\n```\n\n`react()` must come before `conlocaCMS()` — doctor checks the order. `src/schemas/data.ts` declares each data collection\nas a TypeScript type plus its generated Typia validator (`typia.plain.createValidatePrune<T>()`) and form metadata\n(`typia.json.schema<T>()`); `typia-vite.mjs` is the native transform that generates them, so it must stay in\n`vite.plugins`. And `src/content.config.ts`:\n\n```ts\nimport { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';\nimport { dataSchemas } from './schemas/data';\n\nexport const collections = {\n pages: conlocaPages(),\n ...conlocaData({ dataSchemas }),\n ...conlocaFragments(),\n};\n```\n\nEvery collection is declared here by name — content the config does not name fails the build instead of silently not\nbuilding.\n\n## Where errors appear\n\n- `astro dev` runs in the foreground: config and integration errors print to the terminal running it, and page errors\n also show in the browser error overlay. There is no separate log command — read that terminal.\n- A page referencing a Puck component type missing from puck.config.tsx serves HTTP 200 with a blank region and a clean\n browser console. The signal is `[Conloca] Page references N component type(s) missing from your Puck config: ...` in\n the dev-server or build terminal.\n- `conloca doctor` finds them before a build: C14 warns about every component type or prop a page stores that the Puck\n config does not declare.\n- The editor at `/__cms` exists only on the dev server. A production build without it is not a bug.\n\n## Writing content from the command line\n\nNever hand-write files under `content/`, and do not reach for HTTP endpoints: these commands write what the editor\nwrites, so the result is editable at `/__cms` right away. Each takes `--json` for a machine-readable result.\n\n```bash\nconloca page create --site default --collection pages --pathname /about --title 'About us' --content about.json\nconloca page update /about --description 'Who we are' --image /media/hero.jpg\nconloca data create site --name contact --data contact.json\nconloca data update site contact --data - < contact.json\nconloca asset add ~/Pictures/hero.jpg --alt 'Fresh bread on the counter'\n```\n\n- `page create` — a new page. `--content` takes Puck data `{ root, content, zones }` from a file or `-` (stdin), never\n inline JSON; `--description`, `--image`, `--canonical` and `--robots` fill its page settings.\n- `page update` — change an existing page, found by id or pathname; only the flags given change, and an empty value\n (`--robots ''`) clears a field.\n- `data create` / `data update` — a shared entry (contact details, a header menu): a JSON object from a file or\n `--data -`. `data update` replaces the entry's whole object: send every field, not just the changed one. Declare the\n collection's type in `src/schemas/data.ts`; the first `data create` wires the data schemas.\n- `asset add` — an image into the media folder; it prints the reference an image field stores, e.g. `/media/hero.jpg`.\n\nA layout reads a shared entry by name:\n\n```ts\nimport { getCollection } from 'astro:content';\nimport { conlocaDataEntry } from '@conloca/astro-cms/collections';\nimport { dataSchemas } from '../schemas/data';\n\nconst contact = conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'contact', 'en');\ncontact.phone; // typed by the `site` schema\n```\n\nA missing name, or one saved in several locales with none given, throws and fails the build instead of rendering empty.\n\nEntries a page's blocks list (team, testimonials) bind to the route with\n`routing.routes.<name>.dataBindings.collections`; a block's Puck `resolveData` then reads them from\n`metadata.collections.<name>`.\n\nAfter writing content, run the build: it validates every entry against its schema.\n\n## Editing while the dev server runs\n\nThe CLI and the editor at `/__cms` write the same files, so both can run at once:\n\n- Every write names the version of the page it read. A write against a version someone changed since is merged with that\n change: edits to different fields, blocks or list items with ids both land.\n- A write is refused, with nothing written, only when both changed the same field to different values, when it renames\n the page, or when the version it names is unknown to the writer (e.g. the editor after a dev-server restart). A\n refused command exits with the error: re-run it, and it reads the page again. The editor shows the clash instead of\n overwriting.\n- Writes to one file take a short lock, so a command and an editor save never interleave. A command whose write another\n writer replaced before it exited fails with \"overwritten by another writer\": re-run it.\n\n## Routing\n\n- `layout: './src/layouts/Layout.astro'` alone injects a catch-all `/[...slug]` route over the `pages` collection, with\n `prerender: true` and `fallback: '404'`.\n- Passing `routing` replaces that default route entirely and the top-level `layout` is then ignored — name it per route\n instead: `routing: { routes: { pages: { pattern: '/[...slug]', layout: './src/layouts/Layout.astro' } } }`.\n- `routing: true` is the same default catch-all with no layout.\n- `fallback: '404'` returns a bare 404 when no content matches the pattern; `'passthrough'` hands the miss back to Astro\n so the site's own `/404` page renders, with a real 404 status.\n- Trap: a `src/pages` file always wins over a Conloca page at the same path, and Astro says nothing. Doctor warns when\n one hides a page; delete the file in the same change that makes the Conloca page live.\n\n## Adding Conloca to an existing Astro site\n\n- Switching to `output: 'server'`: first add `export const prerender = true` to every existing file under `src/pages/`,\n then flip the output — otherwise those pages silently stop being static. Doctor errors on files that miss it.\n- Existing `.mdx` content: set the site's `mdxPages` path in `content/sites.json` (relative to the project root, e.g.\n `./src/content/docs`). `.mdx` files under it surface in the CMS as pages of that site; the default locale lives at\n `<mdxPages>/<slug>.mdx`, other locales at `<mdxPages>/<locale>/<slug>.mdx`.\n- Plain `.md` files are never adopted — only `.mdx` and `.vxjson` are recognized as pages. Rename `.md` to `.mdx` to\n bring a file under management.\n\n## Converting an existing Astro page\n\nUse this when the user names existing `src/pages` routes to make editable. Convert only those routes.\n\n1. Run `conloca upgrade` (with the version your prompt gave, as defined above). Stop and report if it or\n `conloca doctor` fails: the commands below ship in that release.\n2. Run `conloca routes` and check each named route is listed. Dynamic routes (`[slug].astro`, content collection pages)\n and non-default-locale routes are out of scope and never listed.\n3. Before changing anything, run `conloca compare --reset --routes /a,/b` with exactly the routes the user named; it\n builds the site and saves a fresh baseline.\n4. Run `conloca components --json` to see the components the site already has.\n5. Port each section of the page to a React component in `src/components/puck/` whose editable text and images are\n fields. `.astro` components cannot be Puck components: port, do not reuse. Scoped `<style>` moves into a stylesheet\n listed in `siteStyles`; `<script>` and `client:` islands keep working through `withHydration()`; links stay links;\n images that become fields go into the assets folder with `conloca asset add`.\n6. Render the page through the layout the original used: point `conlocaCMS` (or a per-route layout) at it and adapt it\n to the props Conloca passes (`title`, `description`, `page`).\n7. Text from data files (like `src/data/*.ts`): per-page text goes into the page; values shared across pages go into\n data entries, moved once, on the first conversion that needs them. Every importer of those values (pages, layout,\n endpoints, browser components through props) then reads the same data entries, so there is one copy. Pages the user\n did not name may change only there, and their output must stay identical.\n8. The shared header and footer stay code in the layout. Their texts and links (menu items, footer links, contact\n details) move into a data entry the layout reads. Fragments are for content blocks placed inside pages: markdown plus\n the site's fragment components (see \"Fragment components\").\n9. Read a shared entry by a fixed name and fail the build when it is missing or duplicated:\n `conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'header', 'en').menu` throws in both cases.\n10. Write all content through the CLI: `conloca page create` / `conloca page update` (with `--content` and the metadata\n flags), `conloca data create` / `conloca data update`, `conloca asset add`. Never hand-write content files.\n11. Delete the old `.astro` file in the same change that makes the Conloca page live. A `src/pages` file always wins\n over a Conloca page at the same path, so the page cannot be seen before that; `conloca compare` is the check, not\n the browser.\n12. Run `conloca compare` again. Every route you did not convert must be identical (its linked stylesheets too); every\n converted route must keep its text, links, `<head>` tags and status; a route that became a Conloca page without\n being named fails. Fix and rerun until it passes, then run `conloca doctor`.\n13. Report every changed file, every page you were not asked to convert whose code changed, every allowed change\n `conloca compare` listed (for example island props that now carry shared values), and anything that could not be\n converted faithfully.\n\nThe workspace also has an MCP server for editing content remotely: pages, fragments and data entries on pushed branches.\nIt cannot change code, upload media or publish. Use the address the editor's prompt gives you; never guess or hardcode\none. Setup and limits: https://conloca.com/workspace-mcp/. Its `get_component_vocabulary` lists the components a\nfragment may use. Every change it makes to a fragment is checked like a save in the editor. On the default branch the\ncomponents are those of the deployed production build, so one added since is refused until that build is deployed. On\nanother branch they are checked only against a deploy of that branch's exact head; otherwise, as when the deployed build\npredates fragment components, the change is stored and the answer gives `vocabularyNotChecked` with the reason.\n\n## Custom Puck components\n\nFollow the generated examples in `src/components/puck/` — that is the one proven path:\n\n1. Write a render component plus a `ComponentConfig` wrapped in `withLayout` from `src/components/ComponentLayout.tsx`,\n mirroring the generated `HeadingComponent.tsx` / `Heading.tsx` pair.\n2. Register the component and its Props type in `src/puck.config.tsx`: add it to the `Components` type and the\n `components` map (and optionally a `categories` entry).\n3. Types come from `@puckeditor/core`. If `.tsx` components misrender or fail typecheck, set tsconfig\n `\"jsx\": \"react-jsx\"` — doctor's advisory warning covers this.\n\nA component referenced by stored content but not registered renders blank — see \"Where errors appear\".\n\n## Fragment components\n\nA fragment is MDX: markdown plus the components the site declares for fragments. Declare them in one render module and\nname it in `conlocaCMS({ fragmentComponentsPath: './src/fragment-components.tsx' })`:\n\n```tsx\n// src/fragment-components.tsx — loaded by the page render, so import no editor code here.\nimport { defineFragmentComponents } from '@conloca/mdx/render';\nimport type { ReactNode } from 'react';\n\nfunction Callout({ children }: { children?: ReactNode }) {\n return <aside className=\"callout\">{children}</aside>;\n}\n\nexport const fragmentComponents = defineFragmentComponents({ components: { Callout } });\n```\n\n- `elements` restyles the HTML markdown produces (`elements: { h2: SectionHeading }`); `outline` makes a component a\n contents entry.\n- An `mdxComponents` descriptor of the same name (from `schemasPath`) gives the component its label, insert hint and\n settings fields. A component without one is still offered, with no settings.\n- Authors write `<Callout>text</Callout>`, or `<Name prop=\"text\" />` without children. Prop values are JSON (`{3}`,\n `{[\"a\", \"b\"]}`); there are no `import` lines, `{…}` expressions, `style` or `on*` props.\n- Components render static HTML. For an interactive one, wrap it with `withHydration(Component, 'visible')` from\n `@conloca/astro-cms/hydration` in its own file and import it into the render module by name.\n- A published or scheduled (not expired) fragment that uses a component the module does not declare fails `astro build`,\n naming the fragment, its file and line: `<X> is not in ./src/fragment-components.tsx`. The fix is declaring the\n component, not editing the fragment. If the module cannot load outside Astro, the build only warns.\n\nAll rules: https://conloca.com/configuration/ (`fragmentComponentsPath`) and https://conloca.com/packages/mdx/ (\"Server:\nFragment Components\").\n\n## Known limits — by design, do not fight them\n\n- Fragment content never runs code: `{...}` expressions, `import`/`export` lines, `<script>`, `style` and `on*`\n attributes are rejected or dropped. Put behavior in a fragment component, never in the fragment.\n- Unknown Puck component types render as nothing; the dev-server or build console names them. The fix is registering the\n type in `puck.config.tsx`, not editing the stored content.\n";
4151
4649
 
4152
4650
  // src/commands/setup.ts
4153
4651
  var DEFAULT_SITE_NAME = "default";
@@ -4755,18 +5253,18 @@ async function setup(projectPath = ".", siteName = DEFAULT_SITE_NAME, options =
4755
5253
  const dataSchemas = options.dataSchemas !== false;
4756
5254
  try {
4757
5255
  const absolutePath = resolve5(projectPath);
4758
- const srcDir = join12(absolutePath, "src");
5256
+ const srcDir = join14(absolutePath, "src");
4759
5257
  console.log(`Setting up Conloca for Astro...
4760
5258
  `);
4761
- const contentDir = join12(absolutePath, "content");
5259
+ const contentDir = join14(absolutePath, "content");
4762
5260
  const dirs = [
4763
5261
  contentDir,
4764
- join12(contentDir, siteName, "pages"),
4765
- join12(srcDir, "components"),
4766
- join12(srcDir, "components", "puck"),
4767
- join12(srcDir, "layouts"),
4768
- ...dataSchemas ? [join12(srcDir, "schemas")] : [],
4769
- join12(absolutePath, ".claude", "skills", "conloca")
5262
+ join14(contentDir, siteName, "pages"),
5263
+ join14(srcDir, "components"),
5264
+ join14(srcDir, "components", "puck"),
5265
+ join14(srcDir, "layouts"),
5266
+ ...dataSchemas ? [join14(srcDir, "schemas")] : [],
5267
+ join14(absolutePath, ".claude", "skills", "conloca")
4770
5268
  ];
4771
5269
  for (const dir of dirs) {
4772
5270
  await mkdir2(dir, { recursive: true });
@@ -4775,29 +5273,29 @@ async function setup(projectPath = ".", siteName = DEFAULT_SITE_NAME, options =
4775
5273
  const skipped = [];
4776
5274
  async function writeIfNotExists(filePath, content, description) {
4777
5275
  try {
4778
- await readFile9(filePath);
5276
+ await readFile11(filePath);
4779
5277
  skipped.push(description);
4780
5278
  } catch {
4781
5279
  await writeFile3(filePath, content, "utf-8");
4782
5280
  created.push(description);
4783
5281
  }
4784
5282
  }
4785
- await writeIfNotExists(join12(srcDir, "components", "ComponentLayout.tsx"), COMPONENT_LAYOUT_TEMPLATE, "src/components/ComponentLayout.tsx");
4786
- await writeIfNotExists(join12(srcDir, "components", "Section.tsx"), SECTION_TEMPLATE, "src/components/Section.tsx");
4787
- await writeIfNotExists(join12(srcDir, "components", "puck", "HeadingComponent.tsx"), HEADING_COMPONENT_TEMPLATE, "src/components/puck/HeadingComponent.tsx");
4788
- await writeIfNotExists(join12(srcDir, "components", "puck", "Heading.tsx"), HEADING_TEMPLATE, "src/components/puck/Heading.tsx");
4789
- await writeIfNotExists(join12(srcDir, "components", "puck", "TextComponent.tsx"), TEXT_COMPONENT_TEMPLATE, "src/components/puck/TextComponent.tsx");
4790
- await writeIfNotExists(join12(srcDir, "components", "puck", "Text.tsx"), TEXT_TEMPLATE, "src/components/puck/Text.tsx");
4791
- await writeIfNotExists(join12(srcDir, "components", "puck", "Flex.tsx"), FLEX_TEMPLATE, "src/components/puck/Flex.tsx");
4792
- await writeIfNotExists(join12(srcDir, "components", "puck", "Grid.tsx"), GRID_TEMPLATE, "src/components/puck/Grid.tsx");
4793
- await writeIfNotExists(join12(srcDir, "puck.config.tsx"), PUCK_CONFIG_TEMPLATE, "src/puck.config.tsx");
5283
+ await writeIfNotExists(join14(srcDir, "components", "ComponentLayout.tsx"), COMPONENT_LAYOUT_TEMPLATE, "src/components/ComponentLayout.tsx");
5284
+ await writeIfNotExists(join14(srcDir, "components", "Section.tsx"), SECTION_TEMPLATE, "src/components/Section.tsx");
5285
+ await writeIfNotExists(join14(srcDir, "components", "puck", "HeadingComponent.tsx"), HEADING_COMPONENT_TEMPLATE, "src/components/puck/HeadingComponent.tsx");
5286
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Heading.tsx"), HEADING_TEMPLATE, "src/components/puck/Heading.tsx");
5287
+ await writeIfNotExists(join14(srcDir, "components", "puck", "TextComponent.tsx"), TEXT_COMPONENT_TEMPLATE, "src/components/puck/TextComponent.tsx");
5288
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Text.tsx"), TEXT_TEMPLATE, "src/components/puck/Text.tsx");
5289
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Flex.tsx"), FLEX_TEMPLATE, "src/components/puck/Flex.tsx");
5290
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Grid.tsx"), GRID_TEMPLATE, "src/components/puck/Grid.tsx");
5291
+ await writeIfNotExists(join14(srcDir, "puck.config.tsx"), PUCK_CONFIG_TEMPLATE, "src/puck.config.tsx");
4794
5292
  if (dataSchemas) {
4795
- await writeIfNotExists(join12(srcDir, "schemas", "data.ts"), DATA_SCHEMAS_TEMPLATE, "src/schemas/data.ts");
4796
- await writeIfNotExists(join12(absolutePath, "typia-vite.mjs"), TYPIA_VITE_TEMPLATE, "typia-vite.mjs");
4797
- await writeIfNotExists(join12(absolutePath, "tsconfig.typia.json"), TYPIA_TSCONFIG_TEMPLATE, "tsconfig.typia.json");
5293
+ await writeIfNotExists(join14(srcDir, "schemas", "data.ts"), DATA_SCHEMAS_TEMPLATE, "src/schemas/data.ts");
5294
+ await writeIfNotExists(join14(absolutePath, "typia-vite.mjs"), TYPIA_VITE_TEMPLATE, "typia-vite.mjs");
5295
+ await writeIfNotExists(join14(absolutePath, "tsconfig.typia.json"), TYPIA_TSCONFIG_TEMPLATE, "tsconfig.typia.json");
4798
5296
  }
4799
- await writeIfNotExists(join12(srcDir, "layouts", "Layout.astro"), PAGE_LAYOUT_TEMPLATE, "src/layouts/Layout.astro");
4800
- await writeIfNotExists(join12(absolutePath, ".claude", "skills", "conloca", "SKILL.md"), stampSkill(conloca_skill_default, (await readCliManifest()).version), ".claude/skills/conloca/SKILL.md");
5297
+ await writeIfNotExists(join14(srcDir, "layouts", "Layout.astro"), PAGE_LAYOUT_TEMPLATE, "src/layouts/Layout.astro");
5298
+ await writeIfNotExists(join14(absolutePath, ".claude", "skills", "conloca", "SKILL.md"), stampSkill(conloca_skill_default, (await readCliManifest()).version), ".claude/skills/conloca/SKILL.md");
4801
5299
  const sites = await ensureSiteInSitesConfig(contentDir, siteName);
4802
5300
  if (sites.added) {
4803
5301
  created.push(sites.existed ? `content/sites.json (added site: ${siteName})` : "content/sites.json");
@@ -4904,7 +5402,7 @@ async function gitText(args, cwd) {
4904
5402
  }
4905
5403
  }
4906
5404
  async function readText2(path) {
4907
- return readFile10(path, "utf8").catch(() => null);
5405
+ return readFile12(path, "utf8").catch(() => null);
4908
5406
  }
4909
5407
  function listsWrangler(packageJson) {
4910
5408
  try {
@@ -4919,7 +5417,7 @@ function isStrings(value) {
4919
5417
  }
4920
5418
  async function readWorkerFirstList(projectDir) {
4921
5419
  try {
4922
- const value = JSON.parse(await readText2(join13(projectDir, ".conloca", "dispatcher", "run_worker_first.json")) ?? "");
5420
+ const value = JSON.parse(await readText2(join15(projectDir, ".conloca", "dispatcher", "run_worker_first.json")) ?? "");
4923
5421
  return isStrings(value) ? value : null;
4924
5422
  } catch {
4925
5423
  return null;
@@ -4936,14 +5434,14 @@ async function askPlan(io) {
4936
5434
  }
4937
5435
  }
4938
5436
  function isInside(path, folder) {
4939
- return path === folder || path.startsWith(`${folder}${sep2}`);
5437
+ return path === folder || path.startsWith(`${folder}${sep3}`);
4940
5438
  }
4941
5439
  async function pickProject(start, repoRoot, options, io) {
4942
- const projects = repoRoot === null ? ASTRO_CONFIG_FILES.filter((name) => existsSync5(join13(start, name))).slice(0, 1).map((name) => ({ dir: start, configFile: join13(start, name) })) : (await listAstroProjects(repoRoot)).map((project) => ({
4943
- dir: join13(repoRoot, project.dir),
4944
- configFile: join13(repoRoot, project.configFile)
5440
+ const projects = repoRoot === null ? ASTRO_CONFIG_FILES.filter((name) => existsSync6(join15(start, name))).slice(0, 1).map((name) => ({ dir: start, configFile: join15(start, name) })) : (await listAstroProjects(repoRoot)).map((project) => ({
5441
+ dir: join15(repoRoot, project.dir),
5442
+ configFile: join15(repoRoot, project.configFile)
4945
5443
  }));
4946
- const name = (dir) => relative4(start, dir) || ".";
5444
+ const name = (dir) => relative5(start, dir) || ".";
4947
5445
  if (options.project !== undefined) {
4948
5446
  const target = resolve6(start, options.project);
4949
5447
  const found = projects.find((project) => project.dir === target);
@@ -4970,8 +5468,8 @@ async function pickProject(start, repoRoot, options, io) {
4970
5468
  edits: []
4971
5469
  };
4972
5470
  }
4973
- async function packagesStep(projectDir, commands) {
4974
- const path = join13(projectDir, "package.json");
5471
+ async function packagesStep(projectDir, commands, extra = [], reinstall = []) {
5472
+ const path = join15(projectDir, "package.json");
4975
5473
  const text = await readText2(path);
4976
5474
  const unreadable = {
4977
5475
  id: "packages",
@@ -4993,10 +5491,13 @@ async function packagesStep(projectDir, commands) {
4993
5491
  const range = conlocaRange(cli, name);
4994
5492
  return range === undefined ? [] : [[name, range]];
4995
5493
  }),
4996
- ...PEER_PACKAGES.map((name) => [name, THIRD_PARTY_VERSIONS[name]])
5494
+ ...PEER_PACKAGES.map((name) => [name, THIRD_PARTY_VERSIONS[name]]),
5495
+ ...extra
4997
5496
  ];
4998
5497
  const missing = wanted.filter(([name]) => !(name in dependencies) && !(name in devDependencies));
4999
- if (missing.length === 0) {
5498
+ const updated = reinstall.filter(([name]) => !missing.some(([other]) => other === name));
5499
+ const installed = [...missing, ...updated];
5500
+ if (installed.length === 0) {
5000
5501
  return { id: "packages", result: { state: "done", message: "every package is in package.json", edits: [] } };
5001
5502
  }
5002
5503
  const entries = Object.entries({ ...dependencies, ...Object.fromEntries(missing) });
@@ -5006,16 +5507,19 @@ async function packagesStep(projectDir, commands) {
5006
5507
  id: "packages",
5007
5508
  result: {
5008
5509
  state: "changed",
5009
- message: `added ${missing.map(([name]) => name).join(", ")}`,
5010
- edits: [{ path, before: text, after: jsonLike(text, { ...manifest, dependencies: added }) }]
5510
+ message: [
5511
+ ...missing.length > 0 ? [`added ${missing.map(([name]) => name).join(", ")}`] : [],
5512
+ ...updated.map(([name, range]) => `updates ${name} to ${range}, the release with draft previews in the site build`)
5513
+ ].join("; "),
5514
+ edits: missing.length > 0 ? [{ path, before: text, after: jsonLike(text, { ...manifest, dependencies: added }) }] : []
5011
5515
  },
5012
- command: `${commands.add} ${missing.map(([name, range]) => `'${name}@${range}'`).join(" ")}`
5516
+ command: `${commands.add} ${installed.map(([name, range]) => `'${name}@${range}'`).join(" ")}`
5013
5517
  };
5014
5518
  }
5015
5519
  async function olderPackages(projectDir, cli) {
5016
5520
  let manifest;
5017
5521
  try {
5018
- manifest = JSON.parse(await readText2(join13(projectDir, "package.json")) ?? "");
5522
+ manifest = JSON.parse(await readText2(join15(projectDir, "package.json")) ?? "");
5019
5523
  } catch {
5020
5524
  return [];
5021
5525
  }
@@ -5028,6 +5532,111 @@ async function olderPackages(projectDir, cli) {
5028
5532
  return floor !== null && wanted !== null && compareVersions(floor, wanted) < 0 ? [`${name} ${floor}`] : [];
5029
5533
  });
5030
5534
  }
5535
+ var HOST_QUESTION = "Where does this site deploy? [vercel/netlify/cloudflare/node]";
5536
+ var STATIC_ONLY = "this host runs no functions: use a separate Cloudflare preview deploy (previewBuild: { separate: true }) or go without preview";
5537
+ var STATIC_NODE = "a static site on your own server has no server to render drafts: use a separate Cloudflare preview deploy (previewBuild: { separate: true }) or add @astrojs/node and start dist/server/entry.mjs, then run connect with --host node";
5538
+ function hasD8Refusals(value) {
5539
+ return isRecord(value) && typeof value.d8ConfigRefusal === "function" && typeof value.d8EdgeRefusal === "function";
5540
+ }
5541
+ var ADAPTER_HOSTS = {
5542
+ "@astrojs/vercel": "vercel",
5543
+ "@astrojs/netlify": "netlify",
5544
+ "@astrojs/cloudflare": "cloudflare",
5545
+ "@astrojs/node": "node"
5546
+ };
5547
+ function declaredFloor(manifestText, name) {
5548
+ let manifest;
5549
+ try {
5550
+ manifest = JSON.parse(manifestText ?? "");
5551
+ } catch {
5552
+ return null;
5553
+ }
5554
+ if (!isRecord(manifest))
5555
+ return null;
5556
+ const spec = [manifest.dependencies, manifest.devDependencies].map((deps) => isRecord(deps) ? deps[name] : undefined).find((value) => typeof value === "string");
5557
+ return typeof spec === "string" ? versionFloor(spec) : null;
5558
+ }
5559
+ function previewOff(result) {
5560
+ return { step: { id: "adapter", result }, preview: { kind: "off" }, extra: [], reinstall: [] };
5561
+ }
5562
+ function needsYou(message) {
5563
+ return { state: "needs-you", message, edits: [] };
5564
+ }
5565
+ async function adapterSetup(input) {
5566
+ const { preview, projectDir, options, io } = input;
5567
+ const keep = (step) => ({ step, preview, extra: [], reinstall: [] });
5568
+ const installed = (name) => installedVersion(name, projectDir, input.repoRoot);
5569
+ const loaded = await importFromProject(projectDir, "@conloca/cloud-astro/node");
5570
+ const configRefusal = hasD8Refusals(loaded) ? (text, name, base) => loaded.d8ConfigRefusal(text, name, base) ?? loaded.d8EdgeRefusal(undefined, text, name) : undefined;
5571
+ const addAdapter = async (host) => {
5572
+ const declared = declaredFloor(input.manifestText, HOST_ADAPTERS[host].name) !== null;
5573
+ const astroVersion = declared ? "" : await installed("astro") ?? declaredFloor(input.manifestText, "astro") ?? "";
5574
+ return addAdapterStep({
5575
+ path: input.configFile,
5576
+ text: input.text,
5577
+ host,
5578
+ siteDomains: siteDomainsOf(input.sitesText),
5579
+ astroVersion,
5580
+ yes: options.yes,
5581
+ ...configRefusal === undefined ? {} : { configRefusal }
5582
+ });
5583
+ };
5584
+ const interactive = io.isTTY && !options.yes && !options.dryRun;
5585
+ let answer = await detectHost({
5586
+ projectDir,
5587
+ repoRoot: input.repoRoot,
5588
+ astroText: input.text,
5589
+ ...options.host === undefined ? {} : { flag: options.host }
5590
+ });
5591
+ if (preview.kind === "d8") {
5592
+ const host = ADAPTER_HOSTS[preview.adapter];
5593
+ if (!answer.ok && answer.reason === "conflict")
5594
+ return previewOff(needsYou(answer.message));
5595
+ const matches = answer.ok && (answer.host === host || host === "cloudflare" && answer.host === "cloudflare-d3");
5596
+ if (answer.ok && !matches) {
5597
+ return previewOff(needsYou(`astro.config uses ${preview.adapter}, but ${answer.evidence.join(", ")} says the site deploys to ${answer.host}: pass --host ${host} if the adapter is right`));
5598
+ }
5599
+ if (!answer.ok && host === "node") {
5600
+ return previewOff(needsYou("can't tell that your own server starts dist/server/entry.mjs: pass --host node if it does"));
5601
+ }
5602
+ const current = await installed("@conloca/cloud-astro");
5603
+ if (current === null || compareVersions(current, D8_SINCE) < 0) {
5604
+ return previewOff(needsYou(`the installed @conloca/cloud-astro (${current ?? "none"}) renders no drafts in the site's own build: run conloca upgrade, then connect again`));
5605
+ }
5606
+ if (configRefusal === undefined) {
5607
+ return previewOff(needsYou("couldn't load the preview checks of this project's @conloca/cloud-astro: install its packages, then run connect again"));
5608
+ }
5609
+ return keep({ id: "adapter", result: await addAdapter(host) });
5610
+ }
5611
+ if (!answer.ok && answer.reason === "unknown" && interactive) {
5612
+ const reply = (await io.ask(HOST_QUESTION)).trim().toLowerCase();
5613
+ if (reply === "vercel" || reply === "netlify" || reply === "cloudflare" || reply === "node") {
5614
+ answer = { ok: true, host: reply, evidence: ["your answer"] };
5615
+ }
5616
+ }
5617
+ if (!answer.ok)
5618
+ return previewOff(needsYou(answer.message));
5619
+ const { host } = answer;
5620
+ if (host === "cloudflare" || host === "cloudflare-d3")
5621
+ return keep(null);
5622
+ if (host === "static-only")
5623
+ return previewOff(needsYou(STATIC_ONLY));
5624
+ if (host === "node")
5625
+ return previewOff(needsYou(STATIC_NODE));
5626
+ const result = await addAdapter(host);
5627
+ if (result.state !== "changed")
5628
+ return previewOff(result);
5629
+ const { name } = HOST_ADAPTERS[host];
5630
+ const current = await installed("@conloca/cloud-astro");
5631
+ const range = conlocaRange(await readCliManifest(), "@conloca/cloud-astro");
5632
+ const stale = range !== undefined && (current === null || compareVersions(current, D8_SINCE) < 0);
5633
+ return {
5634
+ step: { id: "adapter", result },
5635
+ preview: { kind: "d8", prefix: preview.prefix, adapter: name },
5636
+ extra: [[name, ADAPTER_VERSIONS[name]]],
5637
+ reinstall: stale ? [["@conloca/cloud-astro", range]] : []
5638
+ };
5639
+ }
5031
5640
  async function siteIdOf(sitesPath) {
5032
5641
  try {
5033
5642
  const parsed = JSON.parse(await readText2(sitesPath) ?? "");
@@ -5040,7 +5649,7 @@ async function buildStep(projectDir, siteId, command, io) {
5040
5649
  if (!await io.run(command, projectDir, { CONLOCA_CONNECT: "1" })) {
5041
5650
  return { state: "failed", message: `${command} failed; fix the build, then run connect again`, edits: [] };
5042
5651
  }
5043
- const folder = ["dist", join13("dist", "client")].map((output) => join13(projectDir, output, "_conloca", "editor")).find((candidate) => existsSync5(join13(candidate, "index.html")));
5652
+ const folder = ["dist", join15("dist", "client")].map((output) => join15(projectDir, output, "_conloca", "editor")).find((candidate) => existsSync6(join15(candidate, "index.html")));
5044
5653
  if (folder === undefined) {
5045
5654
  return {
5046
5655
  state: "failed",
@@ -5048,11 +5657,11 @@ async function buildStep(projectDir, siteId, command, io) {
5048
5657
  edits: []
5049
5658
  };
5050
5659
  }
5051
- const where = relative4(projectDir, folder);
5660
+ const where = relative5(projectDir, folder);
5052
5661
  const missing = { state: "failed", message: `${where}/conloca.json is missing or not JSON`, edits: [] };
5053
5662
  let info;
5054
5663
  try {
5055
- info = JSON.parse(await readText2(join13(folder, "conloca.json")) ?? "");
5664
+ info = JSON.parse(await readText2(join15(folder, "conloca.json")) ?? "");
5056
5665
  } catch {
5057
5666
  return missing;
5058
5667
  }
@@ -5075,7 +5684,7 @@ async function buildStep(projectDir, siteId, command, io) {
5075
5684
  return { state: "done", message: `the build wrote the editor page to ${where} for site ${siteId}`, edits: [] };
5076
5685
  }
5077
5686
  function patchOf(edit, start) {
5078
- const name = relative4(start, edit.path);
5687
+ const name = relative5(start, edit.path);
5079
5688
  return createTwoFilesPatch(edit.before === null ? "/dev/null" : name, name, edit.before ?? "", edit.after);
5080
5689
  }
5081
5690
  function exitCodeOf(report) {
@@ -5111,7 +5720,7 @@ async function runConnect(path, options, io) {
5111
5720
  id: "project",
5112
5721
  result: {
5113
5722
  state: "done",
5114
- message: repoUri === null ? `Astro project ${relative4(start, projectDir) || "."}; the editor needs the repository on GitHub, and this checkout has no GitHub origin` : `Astro project ${relative4(start, projectDir) || "."} in ${repoUri}`,
5723
+ message: repoUri === null ? `Astro project ${relative5(start, projectDir) || "."}; the editor needs the repository on GitHub, and this checkout has no GitHub origin` : `Astro project ${relative5(start, projectDir) || "."} in ${repoUri}`,
5115
5724
  edits: []
5116
5725
  }
5117
5726
  };
@@ -5119,7 +5728,7 @@ async function runConnect(path, options, io) {
5119
5728
  const to = cli.version;
5120
5729
  const older = await olderPackages(projectDir, cli);
5121
5730
  if (older.length > 0) {
5122
- const name = relative4(start, projectDir) || ".";
5731
+ const name = relative5(start, projectDir) || ".";
5123
5732
  const target = name === "." ? "" : ` ${name}`;
5124
5733
  const message = `this site's @conloca packages (${older.join(", ")}) are older than the versions this CLI (${to}) pins: upgrade them first`;
5125
5734
  console.log(`needs-you: ${message}`);
@@ -5138,14 +5747,7 @@ async function runConnect(path, options, io) {
5138
5747
  next: NEXT
5139
5748
  };
5140
5749
  }
5141
- const packages = await packagesStep(projectDir, commands);
5142
- if (!options.install && packages.command !== undefined) {
5143
- packages.result = { state: "skipped", message: `not installed (--no-install): run ${packages.command}`, edits: [] };
5144
- packages.command = undefined;
5145
- }
5146
- if (options.update)
5147
- packages.command = undefined;
5148
- const configText = await readFile10(picked.configFile, "utf8");
5750
+ const configText = await readFile12(picked.configFile, "utf8");
5149
5751
  const code = stripComments(configText);
5150
5752
  const cmsOptions = callOptions(code, "conlocaCMS");
5151
5753
  const config = {
@@ -5154,15 +5756,47 @@ async function runConnect(path, options, io) {
5154
5756
  };
5155
5757
  const starter = !options.update && cmsOptions.state === "no-call" && config.result.state === "changed";
5156
5758
  if (starter) {
5157
- const contentConfig = join13(projectDir, "src", "content.config.ts");
5158
- if (!existsSync5(contentConfig))
5759
+ const contentConfig = join15(projectDir, "src", "content.config.ts");
5760
+ if (!existsSync6(contentConfig))
5159
5761
  config.result.edits.push({ path: contentConfig, before: null, after: CONTENT_CONFIG });
5160
5762
  config.result.message += "; writes the starter components and Puck config (conloca astro setup)";
5161
5763
  }
5162
5764
  const rootOption = cmsOptions.state === "literal" ? stringLiteral(cmsOptions.entries.get("contentRoot") ?? "") : null;
5163
- const sitesPath = join13(rootOption === null ? contentRootOf(projectDir) : resolve6(projectDir, rootOption), "sites.json");
5765
+ const sitesPath = join15(rootOption === null ? contentRootOf(projectDir) : resolve6(projectDir, rootOption), "sites.json");
5164
5766
  const astroSite = readAstroSite(configText);
5165
- const site = options.siteUrl ?? (astroSite === "computed" ? null : astroSite.site);
5767
+ const found = previewSetupOf(callOptions(code, "conlocaCloud"), callOptions(code, "defineConfig"), astroSite === "computed" ? null : astroSite.base, code);
5768
+ const sitesText = await readText2(sitesPath) ?? "";
5769
+ const manifestPath = join15(projectDir, "package.json");
5770
+ const manifestText = await readText2(manifestPath);
5771
+ const wiredText = config.result.edits.find((edit) => edit.path === picked.configFile)?.after ?? configText;
5772
+ const adapterPlan = !options.update && (found.kind === "d3" || found.kind === "d8") ? await adapterSetup({
5773
+ preview: found.kind === "d8" ? found : { kind: "d3", prefix: found.prefix },
5774
+ projectDir,
5775
+ repoRoot: root,
5776
+ configFile: picked.configFile,
5777
+ text: wiredText,
5778
+ sitesText,
5779
+ manifestText,
5780
+ options,
5781
+ io
5782
+ }) : null;
5783
+ const preview = adapterPlan?.preview ?? found;
5784
+ const refusal = found.kind === "off" || found.kind === "d4" ? found.refusal : undefined;
5785
+ const refused = options.update ? undefined : refusal;
5786
+ const adapter = adapterPlan?.step ?? (refused === undefined ? null : { id: "adapter", result: needsYou(refused) });
5787
+ const adapterEdit = adapter?.result.edits.find((edit) => edit.path === picked.configFile);
5788
+ const siteStep = preview.kind === "d8" ? {
5789
+ id: "site",
5790
+ result: addAstroSiteStep({
5791
+ path: picked.configFile,
5792
+ text: adapterEdit?.after ?? wiredText,
5793
+ sitesText,
5794
+ adapter: preview.adapter,
5795
+ siteUrl: options.siteUrl
5796
+ })
5797
+ } : null;
5798
+ const proposed = siteStep?.result.state === "differs" ? siteUrlOf(sitesText) : null;
5799
+ const site = options.siteUrl ?? (astroSite === "computed" ? null : astroSite.site ?? proposed);
5166
5800
  let address;
5167
5801
  if (site === null) {
5168
5802
  address = {
@@ -5185,14 +5819,17 @@ async function runConnect(path, options, io) {
5185
5819
  edit.before = null;
5186
5820
  address = { id: "address", result };
5187
5821
  }
5822
+ const packages = await packagesStep(projectDir, commands, adapterPlan?.extra, adapterPlan?.reinstall);
5823
+ if (!options.install && packages.command !== undefined) {
5824
+ packages.result = { state: "skipped", message: `not installed (--no-install): run ${packages.command}`, edits: [] };
5825
+ packages.command = undefined;
5826
+ }
5827
+ if (options.update)
5828
+ packages.command = undefined;
5188
5829
  const framing = { id: "framing", result: await framingStep(projectDir, undefined) };
5189
5830
  const framingAfterInstall = !options.update && framing.result.state === "skipped" && packages.command !== undefined;
5190
5831
  const leftovers = { id: "leftovers", result: await leftoversStep(root) };
5191
5832
  const build = { id: "build", result: { state: "skipped", message: "", edits: [] } };
5192
- const preview = previewSetupOf(callOptions(code, "conlocaCloud"), callOptions(code, "defineConfig"), astroSite === "computed" ? null : astroSite.base);
5193
- const sitesText = await readText2(sitesPath) ?? "";
5194
- const manifestPath = join13(projectDir, "package.json");
5195
- const manifestText = await readText2(manifestPath);
5196
5833
  const recorded = recordedCfPlan(manifestText);
5197
5834
  const wranglerRunner = listsWrangler(manifestText) ? commands.exec : "npx";
5198
5835
  let plan = preview.kind === "d3" ? options.cfPlan ?? recorded : undefined;
@@ -5212,7 +5849,7 @@ async function runConnect(path, options, io) {
5212
5849
  });
5213
5850
  const wranglerBefore = await readWranglerFile(projectDir);
5214
5851
  const deploy = { id: "preview", result: previewStep(wranglerBefore, null) };
5215
- const withPreview = preview.kind === "d3" || preview.kind === "d4";
5852
+ const withPreview = preview.kind !== "off";
5216
5853
  const deferD3 = preview.kind === "d3" && plan === undefined;
5217
5854
  if (deferD3) {
5218
5855
  deploy.result = { state: "done", message: "the preview settings wait for your Cloudflare plan", edits: [] };
@@ -5226,7 +5863,18 @@ async function runConnect(path, options, io) {
5226
5863
  edits: [...deploy.result.edits, planEdit]
5227
5864
  };
5228
5865
  }
5229
- const steps = options.update ? [project, deploy, build] : [project, packages, config, address, framing, ...withPreview ? [deploy] : [], build, leftovers];
5866
+ const steps = options.update ? [project, deploy, build] : [
5867
+ project,
5868
+ packages,
5869
+ config,
5870
+ ...adapter === null ? [] : [adapter],
5871
+ ...siteStep === null ? [] : [siteStep],
5872
+ address,
5873
+ framing,
5874
+ ...withPreview ? [deploy] : [],
5875
+ build,
5876
+ leftovers
5877
+ ];
5230
5878
  for (const step of steps) {
5231
5879
  for (const edit of step.result.edits)
5232
5880
  console.log(patchOf(edit, start));
@@ -5244,7 +5892,18 @@ async function runConnect(path, options, io) {
5244
5892
  }
5245
5893
  if (starter)
5246
5894
  await setup(projectDir, DEFAULT_SITE_NAME, { dataSchemas: false });
5247
- await writeEdits(steps.flatMap((step) => step === packages ? [] : step.result.edits.filter((edit) => edit !== planEdit)));
5895
+ await writeEdits(steps.flatMap((step) => step === packages || step === adapter ? [] : step.result.edits.filter((edit) => edit !== planEdit)));
5896
+ const uninstalled = (adapterPlan?.extra.length ?? 0) > 0 && (packages.result.state === "failed" || packages.result.state === "skipped");
5897
+ if (adapter !== null && uninstalled) {
5898
+ adapter.result = {
5899
+ state: "needs-you",
5900
+ message: `${adapter.result.message} (not written: the adapter package is not installed)`,
5901
+ edits: []
5902
+ };
5903
+ if (siteStep !== null)
5904
+ siteStep.result = { ...siteStep.result, state: "needs-you", replacement: [] };
5905
+ } else if (adapter !== null)
5906
+ await writeEdits(adapter.result.edits);
5248
5907
  if (plan !== undefined && planEdit !== null) {
5249
5908
  const fresh = cfPlanEdit(manifestPath, await readText2(manifestPath) ?? "", plan);
5250
5909
  if (fresh !== null)
@@ -5257,7 +5916,7 @@ async function runConnect(path, options, io) {
5257
5916
  continue;
5258
5917
  for (const edit of replacement)
5259
5918
  console.log(patchOf(edit, start));
5260
- if (await io.confirm(`Replace your value (${step.result.message})?`)) {
5919
+ if (await io.confirm(step.result.question ?? `Replace your value (${step.result.message})?`)) {
5261
5920
  await writeEdits(replacement);
5262
5921
  step.result = { state: "changed", message: `replaced: ${step.result.message}`, edits: replacement };
5263
5922
  }
@@ -5282,6 +5941,11 @@ async function runConnect(path, options, io) {
5282
5941
  step.result.message += ` (not written: ${why})`;
5283
5942
  }
5284
5943
  }
5944
+ if (siteStep?.result.state === "differs" && !(accepted && io.isTTY && !options.yes))
5945
+ siteStep.result.state = "needs-you";
5946
+ if ((adapterPlan?.extra.length ?? 0) > 0 && adapter?.result.state === "needs-you") {
5947
+ deploy.result = { state: "skipped", message: "the deploy step follows once the adapter is written", edits: [] };
5948
+ }
5285
5949
  const siteId = await siteIdOf(sitesPath);
5286
5950
  const blocked = options.update ? undefined : [packages, config].find((step) => !["done", "changed", "differs"].includes(step.result.state));
5287
5951
  if (!options.build)
@@ -5293,7 +5957,8 @@ async function runConnect(path, options, io) {
5293
5957
  else
5294
5958
  build.result = await buildStep(projectDir, siteId, `${commands.run} build`, io);
5295
5959
  const planEdits = planEdit === null ? [] : [planEdit];
5296
- if (preview.kind === "d3" && plan !== undefined && build.result.state === "done") {
5960
+ const routed = preview.kind === "d3" && plan !== undefined || preview.kind === "d8" && preview.adapter === "@astrojs/cloudflare";
5961
+ if (routed && build.result.state === "done") {
5297
5962
  const routes = await readWorkerFirstList(projectDir);
5298
5963
  const shared = plan === "free" ? sharedQuotaRoutes(routes, preview.prefix) : [];
5299
5964
  if (routes === null) {
@@ -5343,11 +6008,11 @@ async function runConnect(path, options, io) {
5343
6008
  }
5344
6009
  const report = {
5345
6010
  ok: steps.every((step) => step.result.state !== "failed" && step.result.state !== "needs-you"),
5346
- project: relative4(start, projectDir) || ".",
6011
+ project: relative5(start, projectDir) || ".",
5347
6012
  siteId,
5348
6013
  packageManager,
5349
6014
  steps: steps.map((step) => {
5350
- const files = step.result.edits.map((edit) => relative4(start, edit.path));
6015
+ const files = step.result.edits.map((edit) => relative5(start, edit.path));
5351
6016
  return {
5352
6017
  id: step.id,
5353
6018
  state: step.result.state,
@@ -5434,7 +6099,7 @@ async function ensureDataWiring(projectDir, options) {
5434
6099
  `));
5435
6100
  }
5436
6101
  await writeEdits(wiring.edits);
5437
- const files = wiring.edits.map((edit) => relative5(dir, edit.path));
6102
+ const files = wiring.edits.map((edit) => relative6(dir, edit.path));
5438
6103
  if (wiring.packages.length === 0)
5439
6104
  return { files };
5440
6105
  const up = await gitText(["rev-parse", "--show-cdup"], dir);
@@ -5449,18 +6114,18 @@ async function ensureDataWiring(projectDir, options) {
5449
6114
  return { files };
5450
6115
  }
5451
6116
  async function undeclaredDataWarning(projectDir, collection) {
5452
- const configFile = ASTRO_CONFIG_FILES.map((name) => join14(projectDir, name)).find((path) => existsSync6(path));
6117
+ const configFile = ASTRO_CONFIG_FILES.map((name) => join16(projectDir, name)).find((path) => existsSync7(path));
5453
6118
  if (configFile === undefined)
5454
6119
  return null;
5455
- const options = callOptions(stripComments(await readFile11(configFile, "utf8")), "conlocaCMS");
6120
+ const options = callOptions(stripComments(await readFile13(configFile, "utf8")), "conlocaCMS");
5456
6121
  const schemasPath = options.state === "literal" ? stringLiteral(options.entries.get("schemasPath") ?? "") : null;
5457
6122
  if (schemasPath === null)
5458
6123
  return null;
5459
6124
  const path = resolve7(projectDir, schemasPath);
5460
- const text = await readFile11(path, "utf8");
6125
+ const text = await readFile13(path, "utf8");
5461
6126
  if (text.includes(`${collection}:`))
5462
6127
  return null;
5463
- return `${relative5(projectDir, path)} declares no data collection "${collection}", so the build fails on this entry. ` + "Add a type for it and a defineHostSchema entry to dataSchemas.";
6128
+ return `${relative6(projectDir, path)} declares no data collection "${collection}", so the build fails on this entry. ` + "Add a type for it and a defineHostSchema entry to dataSchemas.";
5464
6129
  }
5465
6130
  async function dataCreate(collection, directory, options) {
5466
6131
  const { json } = options;
@@ -5476,7 +6141,7 @@ async function dataCreate(collection, directory, options) {
5476
6141
  title: options.title,
5477
6142
  data
5478
6143
  }));
5479
- const relPath = relative5(process.cwd(), written.filePath);
6144
+ const relPath = relative6(process.cwd(), written.filePath);
5480
6145
  const warning = await undeclaredDataWarning(projectDir, collection).catch(() => null);
5481
6146
  if (json) {
5482
6147
  console.log(JSON.stringify({
@@ -5513,7 +6178,7 @@ async function dataUpdate(collection, ref, directory, options) {
5513
6178
  title: options.title,
5514
6179
  data
5515
6180
  }));
5516
- const relPath = relative5(process.cwd(), written.filePath);
6181
+ const relPath = relative6(process.cwd(), written.filePath);
5517
6182
  if (json) {
5518
6183
  console.log(JSON.stringify({ ok: true, id: written.id, path: relPath }));
5519
6184
  } else {
@@ -5527,10 +6192,10 @@ async function dataUpdate(collection, ref, directory, options) {
5527
6192
 
5528
6193
  // src/commands/asset-add.ts
5529
6194
  async function readMediaOptions(projectDir, json) {
5530
- const configFile = ASTRO_CONFIG_FILES.map((name) => join15(projectDir, name)).find((path) => existsSync7(path));
6195
+ const configFile = ASTRO_CONFIG_FILES.map((name) => join17(projectDir, name)).find((path) => existsSync8(path));
5531
6196
  if (configFile === undefined)
5532
6197
  fail(json, `no astro.config in ${projectDir}`);
5533
- const text = await readFile12(configFile, "utf8");
6198
+ const text = await readFile14(configFile, "utf8");
5534
6199
  const options = callOptions(stripComments(text), "conlocaCMS");
5535
6200
  const assetsPath = options.state === "literal" ? stringLiteral(options.entries.get("assetsPath") ?? "") : null;
5536
6201
  if (assetsPath === null)
@@ -5547,7 +6212,7 @@ async function assetAdd(file, directory, options) {
5547
6212
  const { json } = options;
5548
6213
  try {
5549
6214
  const projectDir = resolve8(directory);
5550
- const bytes = await readFile12(file).catch((error) => {
6215
+ const bytes = await readFile14(file).catch((error) => {
5551
6216
  if (error.code === "ENOENT")
5552
6217
  fail(json, `no file ${file}`);
5553
6218
  throw error;
@@ -5565,7 +6230,7 @@ async function assetAdd(file, directory, options) {
5565
6230
  const { filename, folder = "/" } = uploaded.asset;
5566
6231
  const stored = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
5567
6232
  const ref = `${refBase}/${stored}`;
5568
- const path = relative6(process.cwd(), join15(assetsFolder, stored));
6233
+ const path = relative7(process.cwd(), join17(assetsFolder, stored));
5569
6234
  if (json) {
5570
6235
  console.log(JSON.stringify({
5571
6236
  ok: true,
@@ -5588,14 +6253,14 @@ async function assetAdd(file, directory, options) {
5588
6253
  }
5589
6254
 
5590
6255
  // src/commands/compare.ts
5591
- import { existsSync as existsSync9 } from "node:fs";
5592
- import { copyFile, mkdir as mkdir3, readdir as readdir4, readFile as readFile16, rm, stat, writeFile as writeFile4 } from "node:fs/promises";
5593
- import { dirname as dirname4, join as join20, parse as parse2, relative as relative9, resolve as resolve9, sep as sep5 } from "node:path";
6256
+ import { existsSync as existsSync10 } from "node:fs";
6257
+ import { copyFile, mkdir as mkdir3, readdir as readdir5, readFile as readFile18, rm, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
6258
+ import { dirname as dirname6, join as join22, parse as parse3, relative as relative10, resolve as resolve9, sep as sep6 } from "node:path";
5594
6259
  import { readSitesConfig as readSitesConfig2 } from "@conloca/content-api/node";
5595
6260
 
5596
6261
  // src/lib/page-compare.ts
5597
- import { readdir as readdir2, readFile as readFile13 } from "node:fs/promises";
5598
- import { basename as basename5, extname, join as join16, relative as relative7, sep as sep3 } from "node:path";
6262
+ import { readdir as readdir3, readFile as readFile15 } from "node:fs/promises";
6263
+ import { basename as basename5, extname, join as join18, relative as relative8, sep as sep4 } from "node:path";
5599
6264
  import { parseHTML } from "linkedom";
5600
6265
  var TEXT_EXTENSIONS = new Set([".html", ".htm", ".xml", ".json", ".txt", ".svg", ".webmanifest", ".css"]);
5601
6266
  var BUNDLE_RELS = new Set(["stylesheet", "modulepreload", "preload", "prefetch"]);
@@ -5681,8 +6346,8 @@ async function compareOutputs(input) {
5681
6346
  const kind = input.convertedRoutes.has(route) ? "converted" : "untouched";
5682
6347
  const result = { route, kind, differences: [], allowed: [] };
5683
6348
  const [old, now] = await Promise.all([
5684
- readFile13(join16(input.baselineDir, file)),
5685
- readFile13(join16(input.currentDir, current))
6349
+ readFile15(join18(input.baselineDir, file)),
6350
+ readFile15(join18(input.currentDir, current))
5686
6351
  ]);
5687
6352
  if (!TEXT_EXTENSIONS.has(extname(file))) {
5688
6353
  if (!old.equals(now))
@@ -5731,7 +6396,7 @@ async function compareUntouched(dirs, oldText, newText, result, html) {
5731
6396
  result.differences.push(message);
5732
6397
  }
5733
6398
  async function readStylesheet(dir, href) {
5734
- const text = await readFile13(join16(dir, href.replace(/[?#].*$/, "")), "utf-8").catch(() => null);
6399
+ const text = await readFile15(join18(dir, href.replace(/[?#].*$/, "")), "utf-8").catch(() => null);
5735
6400
  return text === null ? null : normalizeOutput(text);
5736
6401
  }
5737
6402
  function withoutIslandProps(html) {
@@ -5777,12 +6442,12 @@ function without(list, other) {
5777
6442
  });
5778
6443
  }
5779
6444
  async function routeFiles(dir) {
5780
- const entries = await readdir2(dir, { recursive: true, withFileTypes: true });
6445
+ const entries = await readdir3(dir, { recursive: true, withFileTypes: true });
5781
6446
  const files = new Map;
5782
6447
  for (const entry of entries) {
5783
6448
  if (!entry.isFile())
5784
6449
  continue;
5785
- const file = relative7(dir, join16(entry.parentPath, entry.name)).split(sep3).join("/");
6450
+ const file = relative8(dir, join18(entry.parentPath, entry.name)).split(sep4).join("/");
5786
6451
  if (isComparedOutputFile(file))
5787
6452
  files.set(routeOfOutputFile(file), file);
5788
6453
  }
@@ -5790,7 +6455,7 @@ async function routeFiles(dir) {
5790
6455
  }
5791
6456
 
5792
6457
  // src/lib/site-routes.ts
5793
- import { join as join17 } from "node:path";
6458
+ import { join as join19 } from "node:path";
5794
6459
  import { ContentIndex, FileSystemReaderBackend } from "@conloca/content-api/node";
5795
6460
  var CONTENT_GLOB = "{**/*.{vxjson,mdx},data/**/*.json}";
5796
6461
  function pagesOf(index, contentRoot, sites) {
@@ -5807,7 +6472,7 @@ function pagesOf(index, contentRoot, sites) {
5807
6472
  defaultLocale: locale === sites.sites[site]?.defaultLocale,
5808
6473
  pathname: version.pathname,
5809
6474
  type: manifest.type,
5810
- file: join17(contentRoot, version.sourcePath ?? "")
6475
+ file: join19(contentRoot, version.sourcePath ?? "")
5811
6476
  });
5812
6477
  }
5813
6478
  }
@@ -5823,7 +6488,7 @@ async function readConlocaPages(contentRoot, sites) {
5823
6488
  async function readFileRoutes(projectDir, config, sites, site) {
5824
6489
  const { collectStaticPageRoutes, nonDefaultLocalesOf } = await import("@conloca/astro-cms/checks");
5825
6490
  const routes = await collectStaticPageRoutes({
5826
- pagesDir: join17(projectDir, "src", "pages"),
6491
+ pagesDir: join19(projectDir, "src", "pages"),
5827
6492
  serverOutput: config.serverOutput,
5828
6493
  nonDefaultLocales: nonDefaultLocalesOf(sites, site, config.i18n)
5829
6494
  });
@@ -5844,9 +6509,9 @@ function siteRoutes(fileRoutes, pages, site) {
5844
6509
  }
5845
6510
 
5846
6511
  // src/commands/doctor-astro.ts
5847
- import { existsSync as existsSync8 } from "node:fs";
5848
- import { readdir as readdir3, readFile as readFile15 } from "node:fs/promises";
5849
- import { join as join19, relative as relative8, sep as sep4 } from "node:path";
6512
+ import { existsSync as existsSync9 } from "node:fs";
6513
+ import { readdir as readdir4, readFile as readFile17 } from "node:fs/promises";
6514
+ import { join as join21, relative as relative9, sep as sep5 } from "node:path";
5850
6515
 
5851
6516
  // src/lib/page-components.ts
5852
6517
  import { isSlotContent } from "@conloca/astro-cms/checks";
@@ -5908,12 +6573,12 @@ function componentFindings(puckData, manifest) {
5908
6573
  }
5909
6574
 
5910
6575
  // src/lib/project-dependencies.ts
5911
- import { readFile as readFile14 } from "node:fs/promises";
5912
- import { join as join18 } from "node:path";
6576
+ import { readFile as readFile16 } from "node:fs/promises";
6577
+ import { join as join20 } from "node:path";
5913
6578
  async function readProjectDependencies(projectDir) {
5914
6579
  let raw;
5915
6580
  try {
5916
- raw = await readFile14(join18(projectDir, "package.json"), "utf-8");
6581
+ raw = await readFile16(join20(projectDir, "package.json"), "utf-8");
5917
6582
  } catch {
5918
6583
  return "missing";
5919
6584
  }
@@ -5938,7 +6603,7 @@ async function readProjectDependencies(projectDir) {
5938
6603
 
5939
6604
  // src/commands/doctor-astro.ts
5940
6605
  function findAstroConfig(projectDir) {
5941
- return ASTRO_CONFIG_FILES.map((name) => join19(projectDir, name)).find((path) => existsSync8(path));
6606
+ return ASTRO_CONFIG_FILES.map((name) => join21(projectDir, name)).find((path) => existsSync9(path));
5942
6607
  }
5943
6608
  function astroOutputOf(configText) {
5944
6609
  const keyMatch = /\boutput\s*:/.exec(configText);
@@ -6065,7 +6730,7 @@ async function checkContentConfig(projectDir) {
6065
6730
  level: "error",
6066
6731
  message: `no content config found — without it every CMS page 404s; create src/content.config.ts:
6067
6732
  ${CONTENT_CONFIG_SNIPPET}`,
6068
- path: join19(projectDir, "src", "content.config.ts")
6733
+ path: join21(projectDir, "src", "content.config.ts")
6069
6734
  });
6070
6735
  } else if (problem === "not-wired") {
6071
6736
  outcome.problems.push({
@@ -6232,7 +6897,7 @@ function checkReactIntegration(projectDir, configText, pkg) {
6232
6897
  outcome.problems.push({
6233
6898
  check: "C7",
6234
6899
  level: "error",
6235
- message: `@astrojs/react is not declared — no package.json found at ${join19(projectDir, "package.json")}; add @astrojs/react to the project's dependencies`
6900
+ message: `@astrojs/react is not declared — no package.json found at ${join21(projectDir, "package.json")}; add @astrojs/react to the project's dependencies`
6236
6901
  });
6237
6902
  } else if (pkg === "unreadable") {
6238
6903
  outcome.problems.push({
@@ -6315,10 +6980,10 @@ function checkPeers(pkg) {
6315
6980
  }
6316
6981
  async function checkTsconfigJsx(projectDir) {
6317
6982
  const outcome = outcomeOf("C9");
6318
- const path = join19(projectDir, "tsconfig.json");
6983
+ const path = join21(projectDir, "tsconfig.json");
6319
6984
  let raw;
6320
6985
  try {
6321
- raw = await readFile15(path, "utf-8");
6986
+ raw = await readFile17(path, "utf-8");
6322
6987
  } catch {
6323
6988
  outcome.problems.push({
6324
6989
  check: "C9",
@@ -6367,11 +7032,11 @@ async function checkPrerender(projectDir, configText) {
6367
7032
  outcome.skipped = "output is not 'server'";
6368
7033
  return outcome;
6369
7034
  }
6370
- const pagesDir = join19(projectDir, "src", "pages");
6371
- const names = await readdir3(pagesDir, { recursive: true }).catch(() => []);
7035
+ const pagesDir = join21(projectDir, "src", "pages");
7036
+ const names = await readdir4(pagesDir, { recursive: true }).catch(() => []);
6372
7037
  for (const name of names.filter((entry) => PAGE_FILE_RE.test(entry)).sort()) {
6373
- const filePath = join19(pagesDir, name);
6374
- const text = await readFile15(filePath, "utf-8").catch(() => null);
7038
+ const filePath = join21(pagesDir, name);
7039
+ const text = await readFile17(filePath, "utf-8").catch(() => null);
6375
7040
  if (text === null) {
6376
7041
  outcome.problems.push({
6377
7042
  check: "C10",
@@ -6407,7 +7072,7 @@ function checkHiddenPages(projectDir, options, fileRoutes, pages, site) {
6407
7072
  check: "C11",
6408
7073
  level: "warn",
6409
7074
  message: `${file} hides the Conloca page ${route} (${pageId}) — a src/pages file always wins over a Conloca page at the same path; delete the file in the same change that makes the Conloca page live`,
6410
- path: join19(projectDir, file)
7075
+ path: join21(projectDir, file)
6411
7076
  });
6412
7077
  }
6413
7078
  return outcome;
@@ -6430,7 +7095,7 @@ function checkHasPages(fileRoutes, pages) {
6430
7095
  return outcome;
6431
7096
  }
6432
7097
  async function readPuckData(file) {
6433
- const text = await readFile15(file, "utf-8").catch(() => null);
7098
+ const text = await readFile17(file, "utf-8").catch(() => null);
6434
7099
  if (text === null)
6435
7100
  return;
6436
7101
  try {
@@ -6463,7 +7128,7 @@ async function checkPageComponents(projectDir, options, pages) {
6463
7128
  }
6464
7129
  const contentRoot = contentRootOf(projectDir);
6465
7130
  for (const { page, puckData } of filled) {
6466
- const file = relative8(contentRoot, page.file).split(sep4).join("/");
7131
+ const file = relative9(contentRoot, page.file).split(sep5).join("/");
6467
7132
  for (const { component, field } of componentFindings(puckData, manifest)) {
6468
7133
  const fields = Object.keys(manifest.components[component]?.fields ?? {}).join(", ") || "none";
6469
7134
  outcome.problems.push({
@@ -6491,7 +7156,7 @@ async function checkSiteStyles(projectDir, cms, conlocaCloud, pages) {
6491
7156
  }
6492
7157
  if (pages.length === 0)
6493
7158
  return outcome;
6494
- const names = await readdir3(join19(projectDir, "src"), { recursive: true }).catch((error) => error.code === "ENOENT" ? [] : `src/ could not be read (${error.code ?? error.message})`);
7159
+ const names = await readdir4(join21(projectDir, "src"), { recursive: true }).catch((error) => error.code === "ENOENT" ? [] : `src/ could not be read (${error.code ?? error.message})`);
6495
7160
  if (typeof names === "string") {
6496
7161
  outcome.skipped = names;
6497
7162
  return outcome;
@@ -6499,7 +7164,7 @@ async function checkSiteStyles(projectDir, cms, conlocaCloud, pages) {
6499
7164
  const stylesheets = names.filter((name) => STYLESHEET_RE.test(name));
6500
7165
  if (stylesheets.length === 0)
6501
7166
  return outcome;
6502
- const first = stylesheets.reduce((a, b) => b < a ? b : a).split(sep4).join("/");
7167
+ const first = stylesheets.reduce((a, b) => b < a ? b : a).split(sep5).join("/");
6503
7168
  outcome.problems.push({
6504
7169
  check: "C15",
6505
7170
  level: "warn",
@@ -6517,7 +7182,7 @@ async function runAstroChecks(projectDir, sites, pages) {
6517
7182
  skipped: "no astro.config found"
6518
7183
  }));
6519
7184
  }
6520
- const source = await readFile15(configPath, "utf-8").catch(() => null);
7185
+ const source = await readFile17(configPath, "utf-8").catch(() => null);
6521
7186
  if (source === null) {
6522
7187
  const problem = {
6523
7188
  check: "C5",
@@ -6557,8 +7222,8 @@ function isBaseline(value) {
6557
7222
  return typeof value === "object" && value !== null && !Array.isArray(value) && isStringArray(value.chosenRoutes) && isStringArray(value.conlocaRoutes) && isStringArray(value.hiddenRoutes);
6558
7223
  }
6559
7224
  async function filesUnder(dir) {
6560
- const entries = await readdir4(dir, { recursive: true, withFileTypes: true }).catch(() => []);
6561
- return entries.filter((entry) => entry.isFile()).map((entry) => relative9(dir, join20(entry.parentPath, entry.name)).split(sep5).join("/"));
7225
+ const entries = await readdir5(dir, { recursive: true, withFileTypes: true }).catch(() => []);
7226
+ return entries.filter((entry) => entry.isFile()).map((entry) => relative10(dir, join22(entry.parentPath, entry.name)).split(sep6).join("/"));
6562
7227
  }
6563
7228
  async function compare(directory, options) {
6564
7229
  const { json } = options;
@@ -6566,7 +7231,7 @@ async function compare(directory, options) {
6566
7231
  const configPath = findAstroConfig(projectDir);
6567
7232
  if (configPath === undefined)
6568
7233
  fail(json, `no astro.config found in ${projectDir} — run it in the Astro project`);
6569
- const source = await readFile16(configPath, "utf-8").catch(() => null);
7234
+ const source = await readFile18(configPath, "utf-8").catch(() => null);
6570
7235
  if (source === null)
6571
7236
  fail(json, `could not read ${configPath} — check its file permissions`);
6572
7237
  const configText = stripComments(source);
@@ -6574,12 +7239,12 @@ async function compare(directory, options) {
6574
7239
  const notRoute = chosen?.find((route) => !route.startsWith("/"));
6575
7240
  if (notRoute !== undefined)
6576
7241
  fail(json, `--routes takes routes starting with /, separated by commas; got ${notRoute}`);
6577
- const baselineRoot = join20(projectDir, "node_modules", ".cache", "conloca-compare");
6578
- const baselinePath = join20(baselineRoot, "baseline.json");
6579
- const outputRoot = join20(baselineRoot, "output");
7242
+ const baselineRoot = join22(projectDir, "node_modules", ".cache", "conloca-compare");
7243
+ const baselinePath = join22(baselineRoot, "baseline.json");
7244
+ const outputRoot = join22(baselineRoot, "output");
6580
7245
  if (options.reset)
6581
7246
  await rm(baselineRoot, { recursive: true, force: true });
6582
- const baselineText = await readFile16(baselinePath, "utf-8").catch(() => null);
7247
+ const baselineText = await readFile18(baselinePath, "utf-8").catch(() => null);
6583
7248
  let baseline = null;
6584
7249
  if (baselineText !== null) {
6585
7250
  let parsed = null;
@@ -6599,16 +7264,16 @@ async function compare(directory, options) {
6599
7264
  if (site === undefined)
6600
7265
  fail(json, "no sites are configured in sites.json", "site");
6601
7266
  const startedAt = Date.now();
6602
- const packageManager = lockfileInstall(projectDir, parse2(projectDir).root)?.packageManager ?? "npm";
7267
+ const packageManager = lockfileInstall(projectDir, parse3(projectDir).root)?.packageManager ?? "npm";
6603
7268
  const buildCommand = `${packageManagerCommands(packageManager).run} build`;
6604
7269
  if (!await terminalIo(json).run(buildCommand, projectDir)) {
6605
7270
  fail(json, `${buildCommand} failed; fix the build, then run conloca compare again`);
6606
7271
  }
6607
- const serverLayout = existsSync9(join20(projectDir, "dist", "server")) && existsSync9(join20(projectDir, "dist", "client"));
7272
+ const serverLayout = existsSync10(join22(projectDir, "dist", "server")) && existsSync10(join22(projectDir, "dist", "client"));
6608
7273
  const outName = serverLayout ? "dist/client" : "dist";
6609
- const outDir = join20(projectDir, outName);
7274
+ const outDir = join22(projectDir, outName);
6610
7275
  const outFiles = await filesUnder(outDir);
6611
- const htmlTimes = await Promise.all(outFiles.filter((file) => file.endsWith(".html")).map(async (file) => (await stat(join20(outDir, file))).mtimeMs));
7276
+ const htmlTimes = await Promise.all(outFiles.filter((file) => file.endsWith(".html")).map(async (file) => (await stat2(join22(outDir, file))).mtimeMs));
6612
7277
  if (!htmlTimes.some((time) => time >= startedAt)) {
6613
7278
  fail(json, "the build wrote no fresh HTML to dist or dist/client; conloca compare reads only those folders");
6614
7279
  }
@@ -6621,8 +7286,8 @@ async function compare(directory, options) {
6621
7286
  const saved = outFiles.filter((file) => isComparedOutputFile(file) || file.startsWith("_astro/") && file.endsWith(".css"));
6622
7287
  await rm(baselineRoot, { recursive: true, force: true });
6623
7288
  await Promise.all(saved.map(async (file) => {
6624
- await mkdir3(dirname4(join20(outputRoot, file)), { recursive: true });
6625
- await copyFile(join20(outDir, file), join20(outputRoot, file));
7289
+ await mkdir3(dirname6(join22(outputRoot, file)), { recursive: true });
7290
+ await copyFile(join22(outDir, file), join22(outputRoot, file));
6626
7291
  }));
6627
7292
  const chosenRoutes = chosen ?? [];
6628
7293
  const hiddenRoutes = hiddenNow.map((route) => route.route);
@@ -6684,7 +7349,7 @@ async function compare(directory, options) {
6684
7349
  }
6685
7350
 
6686
7351
  // src/commands/components.ts
6687
- import { readFile as readFile17 } from "node:fs/promises";
7352
+ import { readFile as readFile19 } from "node:fs/promises";
6688
7353
  import { resolve as resolve10 } from "node:path";
6689
7354
  async function components(directory, options) {
6690
7355
  const { json } = options;
@@ -6692,7 +7357,7 @@ async function components(directory, options) {
6692
7357
  const configPath = findAstroConfig(projectDir);
6693
7358
  if (configPath === undefined)
6694
7359
  fail(json, `no astro.config found in ${projectDir} — run it in the Astro project`);
6695
- const source = await readFile17(configPath, "utf-8").catch(() => null);
7360
+ const source = await readFile19(configPath, "utf-8").catch(() => null);
6696
7361
  if (source === null)
6697
7362
  fail(json, `could not read ${configPath} — check its file permissions`);
6698
7363
  const result = await readSiteComponents(projectDir, callOptions(stripComments(source), "conlocaCMS"));
@@ -6717,23 +7382,23 @@ async function components(directory, options) {
6717
7382
 
6718
7383
  // src/commands/create.ts
6719
7384
  import { execFile as execFileCallback4, spawn as spawn2 } from "node:child_process";
6720
- import { mkdir as mkdir4, readdir as readdir6, writeFile as writeFile5 } from "node:fs/promises";
6721
- import { dirname as dirname6, join as join23, relative as relative10, resolve as resolve13 } from "node:path";
7385
+ import { mkdir as mkdir4, readdir as readdir7, writeFile as writeFile5 } from "node:fs/promises";
7386
+ import { dirname as dirname8, join as join25, relative as relative11, resolve as resolve13 } from "node:path";
6722
7387
  import { promisify as promisify4 } from "node:util";
6723
7388
 
6724
7389
  // src/commands/doctor.ts
6725
7390
  import { execFile as execFileCallback3 } from "node:child_process";
6726
- import { readdir as readdir5, readFile as readFile19, stat as stat2 } from "node:fs/promises";
6727
- import { join as join22, resolve as resolve12 } from "node:path";
7391
+ import { readdir as readdir6, readFile as readFile21, stat as stat3 } from "node:fs/promises";
7392
+ import { join as join24, resolve as resolve12 } from "node:path";
6728
7393
  import { promisify as promisify3 } from "node:util";
6729
7394
  import { invalidLocaleMessage, isContentLocale } from "@conloca/content-api/content-path";
6730
7395
  import { ContentIndex as ContentIndex2, FileSystemReaderBackend as FileSystemReaderBackend2 } from "@conloca/content-api/node";
6731
7396
 
6732
7397
  // src/commands/doctor-extensions.ts
6733
- import { existsSync as existsSync10 } from "node:fs";
6734
- import { readFile as readFile18 } from "node:fs/promises";
7398
+ import { existsSync as existsSync11 } from "node:fs";
7399
+ import { readFile as readFile20 } from "node:fs/promises";
6735
7400
  import { createRequire as createRequire2 } from "node:module";
6736
- import { dirname as dirname5, join as join21, resolve as resolve11 } from "node:path";
7401
+ import { dirname as dirname7, join as join23, resolve as resolve11 } from "node:path";
6737
7402
  import { pathToFileURL as pathToFileURL3 } from "node:url";
6738
7403
  var DOCTOR_CONTRACT_VERSION = 1;
6739
7404
  var SEAM_CHECK_ID = "EXT";
@@ -6753,10 +7418,10 @@ function resolveManifestPath(require2, projectDir, name) {
6753
7418
  } catch {
6754
7419
  let dir = projectDir;
6755
7420
  for (;; ) {
6756
- const candidate = join21(dir, "node_modules", name, "package.json");
6757
- if (existsSync10(candidate))
7421
+ const candidate = join23(dir, "node_modules", name, "package.json");
7422
+ if (existsSync11(candidate))
6758
7423
  return candidate;
6759
- const parent = dirname5(dir);
7424
+ const parent = dirname7(dir);
6760
7425
  if (parent === dir)
6761
7426
  return null;
6762
7427
  dir = parent;
@@ -6767,7 +7432,7 @@ async function discoverExtensions(projectDir) {
6767
7432
  const pkg = await readProjectDependencies(projectDir);
6768
7433
  if (pkg === "missing" || pkg === "unreadable")
6769
7434
  return [];
6770
- const require2 = createRequire2(join21(projectDir, "package.json"));
7435
+ const require2 = createRequire2(join23(projectDir, "package.json"));
6771
7436
  const manifests = [];
6772
7437
  for (const name of [...pkg.deps].sort()) {
6773
7438
  const manifestPath = resolveManifestPath(require2, projectDir, name);
@@ -6775,14 +7440,14 @@ async function discoverExtensions(projectDir) {
6775
7440
  continue;
6776
7441
  let manifest;
6777
7442
  try {
6778
- manifest = JSON.parse(await readFile18(manifestPath, "utf-8"));
7443
+ manifest = JSON.parse(await readFile20(manifestPath, "utf-8"));
6779
7444
  } catch {
6780
7445
  continue;
6781
7446
  }
6782
7447
  const entry = isRecord(manifest) && isRecord(manifest.conloca) ? manifest.conloca.doctor : undefined;
6783
7448
  if (typeof entry !== "string" || entry === "")
6784
7449
  continue;
6785
- manifests.push({ name, dir: dirname5(manifestPath), entry });
7450
+ manifests.push({ name, dir: dirname7(manifestPath), entry });
6786
7451
  }
6787
7452
  return manifests;
6788
7453
  }
@@ -6853,12 +7518,12 @@ function counted(count, noun) {
6853
7518
  return count === 1 ? `1 ${noun}` : `${count} ${noun}s`;
6854
7519
  }
6855
7520
  async function checkSitesFile(contentRoot) {
6856
- const path = join22(contentRoot, "sites.json");
7521
+ const path = join24(contentRoot, "sites.json");
6857
7522
  const problems = [];
6858
7523
  const outcome = { id: "C3", label: "sites.json is present and complete", problems };
6859
7524
  let raw;
6860
7525
  try {
6861
- raw = await readFile19(path, "utf-8");
7526
+ raw = await readFile21(path, "utf-8");
6862
7527
  } catch {
6863
7528
  problems.push({
6864
7529
  check: "C3",
@@ -6934,8 +7599,8 @@ async function checkSiteDirs(contentRoot, config) {
6934
7599
  return outcome;
6935
7600
  }
6936
7601
  for (const site of Object.keys(config.sites)) {
6937
- const pagesPath = join22(contentRoot, site, "pages");
6938
- const stats = await stat2(pagesPath).catch(() => null);
7602
+ const pagesPath = join24(contentRoot, site, "pages");
7603
+ const stats = await stat3(pagesPath).catch(() => null);
6939
7604
  if (!stats?.isDirectory()) {
6940
7605
  problems.push({
6941
7606
  check: "C4",
@@ -6945,7 +7610,7 @@ async function checkSiteDirs(contentRoot, config) {
6945
7610
  });
6946
7611
  }
6947
7612
  }
6948
- const entries = await readdir5(contentRoot, { withFileTypes: true }).catch(() => []);
7613
+ const entries = await readdir6(contentRoot, { withFileTypes: true }).catch(() => []);
6949
7614
  for (const entry of entries) {
6950
7615
  if (!entry.isDirectory() || RESERVED_CONTENT_DIRS.has(entry.name) || Object.hasOwn(config.sites, entry.name))
6951
7616
  continue;
@@ -6953,7 +7618,7 @@ async function checkSiteDirs(contentRoot, config) {
6953
7618
  check: "C4",
6954
7619
  level: "warn",
6955
7620
  message: `directory "${entry.name}" has no sites.json entry — any pages inside are invisible to the CMS`,
6956
- path: join22(contentRoot, entry.name)
7621
+ path: join24(contentRoot, entry.name)
6957
7622
  });
6958
7623
  }
6959
7624
  return outcome;
@@ -6973,7 +7638,7 @@ async function checkContentIndex(contentRoot, config) {
6973
7638
  check: "C12",
6974
7639
  level: "error",
6975
7640
  message: `${message} (${reason})`,
6976
- path: join22(contentRoot, path)
7641
+ path: join24(contentRoot, path)
6977
7642
  });
6978
7643
  }
6979
7644
  });
@@ -7074,7 +7739,7 @@ async function doctor(directory, options) {
7074
7739
  var execFile4 = promisify4(execFileCallback4);
7075
7740
  var SITE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
7076
7741
  async function assertEmptyDirectory(directory) {
7077
- const entries = await readdir6(directory).catch((error) => {
7742
+ const entries = await readdir7(directory).catch((error) => {
7078
7743
  if (error.code === "ENOENT")
7079
7744
  return [];
7080
7745
  throw error;
@@ -7095,8 +7760,8 @@ async function writeTemplate(directory, name, pm, siteName) {
7095
7760
  [".github/workflows/conloca.yml", renderWorkflow(pm)]
7096
7761
  ];
7097
7762
  for (const [file, content] of files) {
7098
- const path = join23(directory, file);
7099
- await mkdir4(dirname6(path), { recursive: true });
7763
+ const path = join25(directory, file);
7764
+ await mkdir4(dirname8(path), { recursive: true });
7100
7765
  await writeFile5(path, content, "utf-8");
7101
7766
  }
7102
7767
  return files.map(([file]) => file);
@@ -7126,7 +7791,7 @@ async function writeHomePage(directory, contentRoot, siteName, name) {
7126
7791
  zones: {}
7127
7792
  }
7128
7793
  });
7129
- return relative10(directory, written.filePath);
7794
+ return relative11(directory, written.filePath);
7130
7795
  }
7131
7796
  function runInstall(pm, directory, quiet) {
7132
7797
  const [command, ...args] = packageManagerCommands(pm).install.split(" ");
@@ -7153,7 +7818,7 @@ async function buildProject(directory, name, pm, options) {
7153
7818
  const { json } = options;
7154
7819
  await assertEmptyDirectory(directory);
7155
7820
  await mkdir4(directory, { recursive: true });
7156
- const contentRoot = join23(directory, "content");
7821
+ const contentRoot = join25(directory, "content");
7157
7822
  const created = await withStdoutRedirected(json, async () => {
7158
7823
  const files = await writeTemplate(directory, name, pm, options.site);
7159
7824
  files.push(...await setup(directory, options.site));
@@ -7184,7 +7849,7 @@ Created ${name} in ${result.directory} (${result.created.length} files)`);
7184
7849
  const commands = packageManagerCommands(result.packageManager);
7185
7850
  console.log(`
7186
7851
  Next:`);
7187
- const step = relative10(process.cwd(), result.directory) || ".";
7852
+ const step = relative11(process.cwd(), result.directory) || ".";
7188
7853
  const target = step.startsWith("..") ? result.directory : step;
7189
7854
  console.log(` cd ${/\s/.test(target) ? `'${target}'` : target}`);
7190
7855
  if (result.install !== "done")
@@ -7231,11 +7896,11 @@ async function create(target, options) {
7231
7896
 
7232
7897
  // src/commands/init.ts
7233
7898
  import { mkdir as mkdir5 } from "node:fs/promises";
7234
- import { join as join24 } from "node:path";
7899
+ import { join as join26 } from "node:path";
7235
7900
  async function init(directory, siteName) {
7236
7901
  const contentPath = contentRootOf(directory);
7237
7902
  try {
7238
- const contentDirs = [contentPath, join24(contentPath, siteName, "pages"), join24(contentPath, "fragments", "shared")];
7903
+ const contentDirs = [contentPath, join26(contentPath, siteName, "pages"), join26(contentPath, "fragments", "shared")];
7239
7904
  for (const dir of contentDirs) {
7240
7905
  await mkdir5(dir, { recursive: true });
7241
7906
  console.log(` Created: ${dir}`);
@@ -7253,7 +7918,7 @@ async function init(directory, siteName) {
7253
7918
  ✓ Initialized Conloca content structure for site '${siteName}' in ${contentPath}`);
7254
7919
  console.log(`
7255
7920
  Next steps:`);
7256
- console.log(` 1. Create your first page in ${join24(contentPath, siteName, "pages")}`);
7921
+ console.log(` 1. Create your first page in ${join26(contentPath, siteName, "pages")}`);
7257
7922
  console.log(` 2. Run 'conloca doctor' to check the setup`);
7258
7923
  console.log(` 3. Point the conlocaCMS() contentRoot option at ${contentPath}`);
7259
7924
  } catch (error) {
@@ -7264,8 +7929,8 @@ Next steps:`);
7264
7929
  }
7265
7930
 
7266
7931
  // src/commands/page-create.ts
7267
- import { readFile as readFile20 } from "node:fs/promises";
7268
- import { relative as relative11, resolve as resolve14 } from "node:path";
7932
+ import { readFile as readFile22 } from "node:fs/promises";
7933
+ import { relative as relative12, resolve as resolve14 } from "node:path";
7269
7934
  function metaFlagsOf(options) {
7270
7935
  if (options.canonical && !URL.canParse(options.canonical.trim())) {
7271
7936
  throw new PageWriteError("invalid_input", "--canonical must be an absolute URL", "--canonical");
@@ -7299,11 +7964,11 @@ function toCliMessage(error, directory, options) {
7299
7964
  async function undeclaredCollectionWarning(directory, collection) {
7300
7965
  const { findContentConfig } = await import("@conloca/astro-cms/checks");
7301
7966
  const configPath = findContentConfig(resolve14(directory));
7302
- const text = configPath === null ? null : await readFile20(configPath, "utf-8").catch(() => null);
7967
+ const text = configPath === null ? null : await readFile22(configPath, "utf-8").catch(() => null);
7303
7968
  const declared = text === null ? null : declaredPageCollections(text);
7304
7969
  if (configPath === null || declared === null || declared.has(collection))
7305
7970
  return null;
7306
- return `${relative11(process.cwd(), configPath)} declares no page collection "${collection}", so the build fails on this page. Declare it with conlocaPages({ collection: '${collection}' }) and give it a route in conlocaCMS({ routing }).`;
7971
+ return `${relative12(process.cwd(), configPath)} declares no page collection "${collection}", so the build fails on this page. Declare it with conlocaPages({ collection: '${collection}' }) and give it a route in conlocaCMS({ routing }).`;
7307
7972
  }
7308
7973
  async function pageCreate(directory, options) {
7309
7974
  try {
@@ -7333,7 +7998,7 @@ async function createPage(directory, options) {
7333
7998
  }
7334
7999
  throw error;
7335
8000
  }
7336
- const relPath = relative11(process.cwd(), written.filePath);
8001
+ const relPath = relative12(process.cwd(), written.filePath);
7337
8002
  const warning = await undeclaredCollectionWarning(directory, options.collection).catch(() => null);
7338
8003
  if (json) {
7339
8004
  console.log(JSON.stringify({ ok: true, id: written.id, path: relPath, ...warning ? { warnings: [warning] } : {} }));
@@ -7347,7 +8012,7 @@ async function createPage(directory, options) {
7347
8012
  }
7348
8013
 
7349
8014
  // src/commands/page-update.ts
7350
- import { relative as relative12 } from "node:path";
8015
+ import { relative as relative13 } from "node:path";
7351
8016
  async function pageUpdate(ref, directory, options) {
7352
8017
  const { json } = options;
7353
8018
  try {
@@ -7360,7 +8025,7 @@ async function pageUpdate(ref, directory, options) {
7360
8025
  puckData,
7361
8026
  meta: metaFlagsOf(options)
7362
8027
  }));
7363
- const relPath = relative12(process.cwd(), written.filePath);
8028
+ const relPath = relative13(process.cwd(), written.filePath);
7364
8029
  if (json) {
7365
8030
  console.log(JSON.stringify({ ok: true, id: written.id, path: relPath }));
7366
8031
  } else {
@@ -7373,7 +8038,7 @@ async function pageUpdate(ref, directory, options) {
7373
8038
  }
7374
8039
 
7375
8040
  // src/commands/routes.ts
7376
- import { readFile as readFile21 } from "node:fs/promises";
8041
+ import { readFile as readFile23 } from "node:fs/promises";
7377
8042
  import { resolve as resolve15 } from "node:path";
7378
8043
  import { readSitesConfig as readSitesConfig3 } from "@conloca/content-api/node";
7379
8044
  async function routes(directory, options) {
@@ -7382,7 +8047,7 @@ async function routes(directory, options) {
7382
8047
  const configPath = findAstroConfig(projectDir);
7383
8048
  if (configPath === undefined)
7384
8049
  fail(json, `no astro.config found in ${projectDir} — run it in the Astro project`);
7385
- const source = await readFile21(configPath, "utf-8").catch(() => null);
8050
+ const source = await readFile23(configPath, "utf-8").catch(() => null);
7386
8051
  if (source === null)
7387
8052
  fail(json, `could not read ${configPath} — check its file permissions`);
7388
8053
  const configText = stripComments(source);
@@ -7410,14 +8075,14 @@ async function routes(directory, options) {
7410
8075
  }
7411
8076
 
7412
8077
  // src/commands/upgrade.ts
7413
- import { existsSync as existsSync12 } from "node:fs";
7414
- import { readFile as readFile24, rm as rm2, rmdir, writeFile as writeFile6 } from "node:fs/promises";
7415
- import { basename as basename6, dirname as dirname8, join as join27, relative as relative15, resolve as resolve16 } from "node:path";
8078
+ import { existsSync as existsSync13 } from "node:fs";
8079
+ import { readFile as readFile26, rm as rm2, rmdir, writeFile as writeFile6 } from "node:fs/promises";
8080
+ import { basename as basename6, dirname as dirname10, join as join29, relative as relative16, resolve as resolve17 } from "node:path";
7416
8081
 
7417
8082
  // src/lib/migrations.ts
7418
- import { existsSync as existsSync11 } from "node:fs";
7419
- import { readFile as readFile22 } from "node:fs/promises";
7420
- import { join as join25, relative as relative13 } from "node:path";
8083
+ import { existsSync as existsSync12 } from "node:fs";
8084
+ import { readdir as readdir8, readFile as readFile24 } from "node:fs/promises";
8085
+ import { join as join27, relative as relative14, resolve as resolve16 } from "node:path";
7421
8086
  var SEVERITY = ["done", "changed", "needs-you", "failed"];
7422
8087
  function removedNames(source) {
7423
8088
  const passed = removedKeyOptions(source);
@@ -7427,10 +8092,10 @@ function removedNames(source) {
7427
8092
  return [...REMOVED_OPTIONS].filter((name) => name !== "fragmentPreviewRoute" && new RegExp(`\\b${name}\\b`).test(code));
7428
8093
  }
7429
8094
  async function removedOptionsStep(projectDir, repoRoot) {
7430
- const path = ASTRO_CONFIG_FILES.map((name) => join25(projectDir, name)).find((file) => existsSync11(file));
8095
+ const path = ASTRO_CONFIG_FILES.map((name) => join27(projectDir, name)).find((file) => existsSync12(file));
7431
8096
  if (path === undefined)
7432
8097
  return null;
7433
- const text = await readFile22(path, "utf8");
8098
+ const text = await readFile24(path, "utf8");
7434
8099
  const names = removedNames(text);
7435
8100
  if (names.length === 0)
7436
8101
  return null;
@@ -7438,7 +8103,7 @@ async function removedOptionsStep(projectDir, repoRoot) {
7438
8103
  if (wired.edits.some((edit) => removedNames(edit.after).length === 0)) {
7439
8104
  return { state: "changed", message: wired.message, edits: wired.edits };
7440
8105
  }
7441
- const file = relative13(repoRoot, path);
8106
+ const file = relative14(repoRoot, path);
7442
8107
  return {
7443
8108
  state: "needs-you",
7444
8109
  message: `remove ${names.join(", ")} from conlocaCloud() in ${file}; @conloca/cloud-astro no longer accepts them`,
@@ -7473,7 +8138,113 @@ var dataSchemas = {
7473
8138
  description: "wire data entries and uploaded media: schemas, conlocaData() and the Typia packages",
7474
8139
  plan: ({ projectDir }) => wireDataSchemas(projectDir)
7475
8140
  };
7476
- var MIGRATIONS = [keyless, dataSchemas];
8141
+ var DEAD_PREVIEW_OPTIONS = new Set(["adapter", "config", "outDir", "required"]);
8142
+ var D8_NOTES = [
8143
+ "open preview tabs from before this upgrade stop working; editors reopen Preview",
8144
+ "the preview mode already changed when @conloca/cloud-astro was updated: the next build serves d8, or turns preview off while previewBuild.adapter remains"
8145
+ ];
8146
+ async function startCommandEdits(dirs) {
8147
+ const listed = await Promise.all(dirs.map(async (dir) => (await readdir8(dir, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isFile()).filter(({ name }) => isStarterFile(name)).map(({ name }) => join27(dir, name))));
8148
+ const paths = listed.flat();
8149
+ const texts = await Promise.all(paths.map((path) => readFile24(path, "utf8")));
8150
+ return paths.flatMap((path, index) => {
8151
+ const before = texts[index] ?? "";
8152
+ return before.includes(D2_ENTRY) ? [{ path, before, after: before.replaceAll(D2_ENTRY, D8_ENTRY) }] : [];
8153
+ });
8154
+ }
8155
+ var done = (message) => ({ state: "done", message, edits: [], packages: [] });
8156
+ var needs3 = (message) => ({ state: "needs-you", message, edits: [], packages: [] });
8157
+ var d8 = {
8158
+ id: "d8",
8159
+ package: "@conloca/cloud-astro",
8160
+ since: D8_SINCE,
8161
+ description: "move draft preview into the site's own build (d8)",
8162
+ async plan({ projectDir, repoRoot }) {
8163
+ const path = ASTRO_CONFIG_FILES.map((name) => join27(projectDir, name)).find((file) => existsSync12(file));
8164
+ if (path === undefined)
8165
+ return done("no astro.config");
8166
+ const text = await readFile24(path, "utf8");
8167
+ const code = stripComments(text);
8168
+ const integration = callOptions(code, "conlocaCloud");
8169
+ const raw = integration.state === "literal" ? integration.entries.get("previewBuild") : undefined;
8170
+ if (raw === undefined || raw.trim() === "false")
8171
+ return done("no draft preview build to move");
8172
+ const adapter = siteAdapterOf(callOptions(code, "defineConfig"), code);
8173
+ const keys = previewBuildKeys(raw);
8174
+ const own = parseObjectEntries(raw.trim());
8175
+ const previewAdapter = own === null ? undefined : siteAdapterOf({ state: "literal", entries: own.entries, hasSpread: false }, code);
8176
+ if (adapter === undefined && previewAdapter === "@astrojs/cloudflare" && !keys.separate) {
8177
+ return needs3([
8178
+ "a static site previews next to itself on Cloudflare (D3): remove previewBuild.adapter and run conloca connect",
8179
+ ...D8_NOTES
8180
+ ].join("; "));
8181
+ }
8182
+ if (adapter === undefined && keys.adapter && !keys.separate) {
8183
+ return needs3([
8184
+ "a static site on its own server has no same-address preview: use previewBuild: { separate: true } (a Cloudflare preview deploy) or remove previewBuild",
8185
+ ...D8_NOTES
8186
+ ].join("; "));
8187
+ }
8188
+ const file = relative14(repoRoot, path);
8189
+ const setup = previewSetupOf(integration, callOptions(code, "defineConfig"), null, code);
8190
+ if (setup.kind === "d4" && keys.adapter) {
8191
+ const dropped = withoutPreviewBuildOptions(text, new Set(["adapter"]));
8192
+ if (dropped === null)
8193
+ return done("no D2 preview server to move");
8194
+ if (dropped === "computed")
8195
+ return needs3(`remove adapter from previewBuild in conlocaCloud() in ${file}`);
8196
+ return {
8197
+ state: "changed",
8198
+ message: "removed previewBuild.adapter, which the build refuses: the separate preview deploy builds with the adapter in astro.config",
8199
+ edits: [{ path, before: text, after: dropped.after }],
8200
+ packages: []
8201
+ };
8202
+ }
8203
+ const d2 = setup.kind === "off" && setup.refusal !== undefined && !keys.separate;
8204
+ if (!d2 && setup.kind !== "d8")
8205
+ return done("no D2 preview server to move");
8206
+ const dropped = withoutPreviewBuildOptions(text, DEAD_PREVIEW_OPTIONS);
8207
+ if (dropped === "computed" && [...DEAD_PREVIEW_OPTIONS].some((name) => new RegExp(`\\b${name}\\s*:`, "u").test(raw))) {
8208
+ return needs3(`remove adapter, config, outDir and required from previewBuild in conlocaCloud() in ${file}: drafts render in the site's own build`);
8209
+ }
8210
+ let after = typeof dropped === "object" && dropped !== null ? dropped.after : text;
8211
+ const notes = after === text ? [] : ["removed the previewBuild options the site build ignores"];
8212
+ let starts = [];
8213
+ if (adapter === "@astrojs/node") {
8214
+ const cms = callOptions(code, "conlocaCMS");
8215
+ const root = cms.state === "literal" ? stringLiteral(cms.entries.get("contentRoot") ?? "") : null;
8216
+ const sites = join27(root === null ? contentRootOf(projectDir) : resolve16(projectDir, root), "sites.json");
8217
+ const sitesText = await readFile24(sites, "utf8").catch(() => "");
8218
+ const node = addAdapterStep({
8219
+ path,
8220
+ text: after,
8221
+ host: "node",
8222
+ siteDomains: siteDomainsOf(sitesText),
8223
+ astroVersion: "",
8224
+ yes: true
8225
+ });
8226
+ if (node.state === "needs-you")
8227
+ return needs3([node.message, ...D8_NOTES].join("; "));
8228
+ if (node.state === "changed")
8229
+ notes.push("added security.allowedDomains");
8230
+ after = node.edits[0]?.after ?? after;
8231
+ starts = await startCommandEdits(foldersUp(projectDir, repoRoot));
8232
+ if (starts.length > 0)
8233
+ notes.push(`the start command is now ${D8_ENTRY}`);
8234
+ for (const edit of starts) {
8235
+ if (edit.after.includes(".conloca/preview-server")) {
8236
+ notes.push(`${relative14(repoRoot, edit.path)} still names .conloca/preview-server: make sure dist/server is in the image`);
8237
+ }
8238
+ }
8239
+ }
8240
+ const edits = [...after === text ? [] : [{ path, before: text, after }], ...starts];
8241
+ if (edits.length === 0)
8242
+ return done("draft preview already renders in the site's own build (d8)");
8243
+ const reminder = adapter === "@astrojs/node" ? [`if your host's dashboard, or any other file, starts ${D2_ENTRY}, change it to ${D8_ENTRY}`] : [];
8244
+ return { state: "changed", message: [...notes, ...reminder, ...D8_NOTES].join("; "), edits, packages: [] };
8245
+ }
8246
+ };
8247
+ var MIGRATIONS = [keyless, dataSchemas, d8];
7477
8248
  function migrationsSince(floors, migrations = MIGRATIONS) {
7478
8249
  return migrations.filter((migration) => {
7479
8250
  const floor = floors.get(migration.package);
@@ -7482,10 +8253,10 @@ function migrationsSince(floors, migrations = MIGRATIONS) {
7482
8253
  }
7483
8254
 
7484
8255
  // src/lib/skills.ts
7485
- import { readFile as readFile23 } from "node:fs/promises";
7486
- import { dirname as dirname7, join as join26, relative as relative14 } from "node:path";
8256
+ import { readFile as readFile25 } from "node:fs/promises";
8257
+ import { dirname as dirname9, join as join28, relative as relative15 } from "node:path";
7487
8258
  import { isUneditedSkill, stampSkill as stampSkill2 } from "@conloca/content-api/skill-stamp";
7488
- var CONLOCA_SKILL_PATH = join26(".claude", "skills", "conloca", "SKILL.md");
8259
+ var CONLOCA_SKILL_PATH = join28(".claude", "skills", "conloca", "SKILL.md");
7489
8260
  var LEGACY_CONLOCA_SKILL_CHECKSUMS = [
7490
8261
  "12a3b71e53d712fb2245e157c99c088df3841dc1d2e6332a9e17f23d306a8159",
7491
8262
  "f879c60b510ddf2fd7af781d60dd8c5cd6b4b8c7cbd9057fbd4d70fac6222ead",
@@ -7508,7 +8279,7 @@ async function projectPackageSkill(projectDir) {
7508
8279
  }
7509
8280
  }
7510
8281
  async function refresh(skill) {
7511
- const before = await readFile23(skill.path, "utf8").catch(() => null);
8282
+ const before = await readFile25(skill.path, "utf8").catch(() => null);
7512
8283
  if (before?.replaceAll(`\r
7513
8284
  `, `
7514
8285
  `) === skill.text)
@@ -7516,16 +8287,16 @@ async function refresh(skill) {
7516
8287
  if (before === null || isUneditedSkill(before, skill.legacyChecksums)) {
7517
8288
  return { edit: { path: skill.path, before, after: skill.text } };
7518
8289
  }
7519
- const beside = join26(dirname7(skill.path), "SKILL.new.md");
8290
+ const beside = join28(dirname9(skill.path), "SKILL.new.md");
7520
8291
  return {
7521
- edit: { path: beside, before: await readFile23(beside, "utf8").catch(() => null), after: skill.text },
8292
+ edit: { path: beside, before: await readFile25(beside, "utf8").catch(() => null), after: skill.text },
7522
8293
  kept: beside
7523
8294
  };
7524
8295
  }
7525
8296
  async function planSkillRefresh(projectDir, version) {
7526
8297
  const skills = [
7527
8298
  {
7528
- path: join26(projectDir, CONLOCA_SKILL_PATH),
8299
+ path: join28(projectDir, CONLOCA_SKILL_PATH),
7529
8300
  text: stampSkill2(conloca_skill_default, version),
7530
8301
  legacyChecksums: LEGACY_CONLOCA_SKILL_CHECKSUMS
7531
8302
  }
@@ -7536,7 +8307,7 @@ async function planSkillRefresh(projectDir, version) {
7536
8307
  const skipped = packageSkill instanceof Error ? `; skipped the page of @conloca/cloud-astro, which failed to load (${packageSkill.message})` : "";
7537
8308
  const results = await Promise.all(skills.map(refresh));
7538
8309
  const edits = results.flatMap((result) => result.edit === undefined ? [] : [result.edit]);
7539
- const kept = results.flatMap((result) => result.kept === undefined ? [] : [relative14(projectDir, result.kept)]);
8310
+ const kept = results.flatMap((result) => result.kept === undefined ? [] : [relative15(projectDir, result.kept)]);
7540
8311
  if (kept.length > 0) {
7541
8312
  return {
7542
8313
  state: "differs",
@@ -7545,7 +8316,7 @@ async function planSkillRefresh(projectDir, version) {
7545
8316
  };
7546
8317
  }
7547
8318
  if (edits.length > 0) {
7548
- const paths = edits.map((edit) => relative14(projectDir, edit.path)).join(" and ");
8319
+ const paths = edits.map((edit) => relative15(projectDir, edit.path)).join(" and ");
7549
8320
  return { state: "changed", message: `refreshed ${paths}${skipped}`, edits };
7550
8321
  }
7551
8322
  return { state: "done", message: `the agent skills are current${skipped}`, edits };
@@ -7555,14 +8326,14 @@ async function planSkillRefresh(projectDir, version) {
7555
8326
  var OVERRIDE_FIELDS = ["overrides", "resolutions"];
7556
8327
  async function readManifest(path) {
7557
8328
  try {
7558
- const text = await readFile24(path, "utf8");
8329
+ const text = await readFile26(path, "utf8");
7559
8330
  const value = JSON.parse(text);
7560
8331
  return isRecord(value) ? { path, text, value } : null;
7561
8332
  } catch {
7562
8333
  return null;
7563
8334
  }
7564
8335
  }
7565
- function needsYou(message) {
8336
+ function needsYou2(message) {
7566
8337
  return { state: "needs-you", message, edits: [] };
7567
8338
  }
7568
8339
  function targetOf(cli, name) {
@@ -7573,7 +8344,7 @@ async function refusalOf(manifests, installed, installDir, cli) {
7573
8344
  const entries = manifests.flatMap((manifest) => conlocaDependencies(manifest.value));
7574
8345
  const pinned = entries.find((entry) => entry.spec.includes(":") || entry.spec.includes("/"));
7575
8346
  if (pinned !== undefined) {
7576
- return needsYou(`${pinned.name} is "${pinned.spec}", which a version range cannot replace: set it to a version, then run upgrade again`);
8347
+ return needsYou2(`${pinned.name} is "${pinned.spec}", which a version range cannot replace: set it to a version, then run upgrade again`);
7577
8348
  }
7578
8349
  for (const manifest of manifests) {
7579
8350
  const pnpm = manifest.value.pnpm;
@@ -7582,12 +8353,12 @@ async function refusalOf(manifests, installed, installDir, cli) {
7582
8353
  isRecord(pnpm) ? pnpm.overrides : undefined
7583
8354
  ];
7584
8355
  if (fields.some((field) => field !== undefined && JSON.stringify(field).includes("@conloca/"))) {
7585
- return needsYou(`${manifest.path} pins @conloca packages in overrides or resolutions: remove them first`);
8356
+ return needsYou2(`${manifest.path} pins @conloca packages in overrides or resolutions: remove them first`);
7586
8357
  }
7587
8358
  }
7588
- const workspace = await readFile24(join27(installDir, "pnpm-workspace.yaml"), "utf8").catch(() => "");
8359
+ const workspace = await readFile26(join29(installDir, "pnpm-workspace.yaml"), "utf8").catch(() => "");
7589
8360
  if (workspace.includes("@conloca/")) {
7590
- return needsYou("pnpm-workspace.yaml names @conloca packages (a catalog or override): remove them first");
8361
+ return needsYou2("pnpm-workspace.yaml names @conloca packages (a catalog or override): remove them first");
7591
8362
  }
7592
8363
  const floors = [
7593
8364
  ...entries.map((entry) => ({ name: entry.name, floor: versionFloor(entry.spec) })),
@@ -7596,7 +8367,7 @@ async function refusalOf(manifests, installed, installDir, cli) {
7596
8367
  for (const { name, floor } of floors) {
7597
8368
  const target = targetOf(cli, name);
7598
8369
  if (floor !== null && target !== null && compareVersions(floor, target) > 0) {
7599
- return needsYou(`${name} is at ${floor}, newer than ${target}, which this CLI (${cli.version}) pins; never moving a site back: run npx @conloca/cli@latest upgrade`);
8370
+ return needsYou2(`${name} is at ${floor}, newer than ${target}, which this CLI (${cli.version}) pins; never moving a site back: run npx @conloca/cli@latest upgrade`);
7600
8371
  }
7601
8372
  }
7602
8373
  return null;
@@ -7625,7 +8396,7 @@ function manifestEditsOf(manifests, ranges, added) {
7625
8396
  function reportOf(plan) {
7626
8397
  const { start, steps, report } = plan;
7627
8398
  report.steps = steps.map((step) => {
7628
- const files = step.result.edits.map((edit) => relative15(start, edit.path));
8399
+ const files = step.result.edits.map((edit) => relative16(start, edit.path));
7629
8400
  return {
7630
8401
  id: step.id,
7631
8402
  state: step.result.state,
@@ -7651,10 +8422,10 @@ async function runMigrationPlan(migration, projectDir, repoRoot) {
7651
8422
  }
7652
8423
  }
7653
8424
  async function planUpgrade(path, options, io, cli, migrations) {
7654
- const start = resolve16(path);
8425
+ const start = resolve17(path);
7655
8426
  const to = cli.version;
7656
8427
  const up = await gitText(["rev-parse", "--show-cdup"], start);
7657
- const gitRoot = up === null ? null : resolve16(start, up);
8428
+ const gitRoot = up === null ? null : resolve17(start, up);
7658
8429
  const report = {
7659
8430
  ok: false,
7660
8431
  project: ".",
@@ -7675,20 +8446,20 @@ async function planUpgrade(path, options, io, cli, migrations) {
7675
8446
  const found = lockfileInstall(projectDir, repoRoot);
7676
8447
  const install = found ?? {
7677
8448
  packageManager: "npm",
7678
- lockfile: join27(projectDir, "package-lock.json"),
8449
+ lockfile: join29(projectDir, "package-lock.json"),
7679
8450
  installDir: projectDir
7680
8451
  };
7681
8452
  const commands = packageManagerCommands(install.packageManager);
7682
- report.project = relative15(start, projectDir) || ".";
8453
+ report.project = relative16(start, projectDir) || ".";
7683
8454
  report.packageManager = install.packageManager;
7684
8455
  const steps = [
7685
8456
  { id: "project", result: { state: "done", message: `Astro project ${report.project}`, edits: [] } }
7686
8457
  ];
7687
8458
  const stop = (id, result) => reportOf({ start, steps: [...steps, { id, result }], report });
7688
- const project = await readManifest(join27(projectDir, "package.json"));
8459
+ const project = await readManifest(join29(projectDir, "package.json"));
7689
8460
  if (project === null)
7690
8461
  return stop("packages", { state: "failed", message: `no readable package.json in ${report.project}`, edits: [] });
7691
- const workspace = install.installDir === projectDir ? null : await readManifest(join27(install.installDir, "package.json"));
8462
+ const workspace = install.installDir === projectDir ? null : await readManifest(join29(install.installDir, "package.json"));
7692
8463
  const manifests = workspace === null ? [project] : [project, workspace];
7693
8464
  if (conlocaDependencies(project.value).length === 0) {
7694
8465
  return stop("packages", {
@@ -7758,16 +8529,7 @@ async function planUpgrade(path, options, io, cli, migrations) {
7758
8529
  }
7759
8530
  async function installedVersions(manifests, projectDir, installDir) {
7760
8531
  const names = new Set(manifests.flatMap((manifest) => conlocaDependencies(manifest.value).map((entry) => entry.name)));
7761
- return Promise.all([...names].map(async (name) => {
7762
- for (let dir = projectDir;; dir = dirname8(dir)) {
7763
- const manifest = await readManifest(join27(dir, "node_modules", name, "package.json"));
7764
- if (manifest !== null) {
7765
- return { name, version: typeof manifest.value.version === "string" ? manifest.value.version : null };
7766
- }
7767
- if (dir === installDir || dir === dirname8(dir))
7768
- return { name, version: null };
7769
- }
7770
- }));
8532
+ return Promise.all([...names].map(async (name) => ({ name, version: await installedVersion(name, projectDir, installDir) })));
7771
8533
  }
7772
8534
  async function versionsStep(plan) {
7773
8535
  const installed = await installedVersions(plan.manifests, plan.projectDir, plan.install.installDir);
@@ -7791,7 +8553,7 @@ async function applyMigration(migration, plan, save) {
7791
8553
  if (result.state !== "done" && result.state !== "changed") {
7792
8554
  return { ...result, state: "failed", message: `on writing: ${result.message}` };
7793
8555
  }
7794
- const current = await Promise.all(result.edits.map((edit) => readFile24(edit.path, "utf8").catch(() => null)));
8556
+ const current = await Promise.all(result.edits.map((edit) => readFile26(edit.path, "utf8").catch(() => null)));
7795
8557
  const stale = result.edits.filter((edit, index) => current[index] !== edit.before).map((edit) => edit.path);
7796
8558
  if (stale.length > 0)
7797
8559
  return { ...result, state: "failed", message: `${stale.join(", ")} changed since the dry run` };
@@ -7805,14 +8567,14 @@ async function applyUpgrade(plan, io) {
7805
8567
  const folders = new Set;
7806
8568
  const save = async (paths) => {
7807
8569
  const fresh = paths.filter((path) => !journal.has(path));
7808
- const contents = await Promise.all(fresh.map((path) => readFile24(path).catch((error) => {
8570
+ const contents = await Promise.all(fresh.map((path) => readFile26(path).catch((error) => {
7809
8571
  if (error.code === "ENOENT")
7810
8572
  return null;
7811
8573
  throw error;
7812
8574
  })));
7813
8575
  for (const [index, path] of fresh.entries()) {
7814
8576
  journal.set(path, contents[index] ?? null);
7815
- for (let dir = dirname8(path);!existsSync12(dir); dir = dirname8(dir))
8577
+ for (let dir = dirname10(path);!existsSync13(dir); dir = dirname10(dir))
7816
8578
  folders.add(dir);
7817
8579
  }
7818
8580
  };
@@ -7853,9 +8615,9 @@ async function applyUpgrade(plan, io) {
7853
8615
  const failed = steps.find((step) => step.result.state === "failed");
7854
8616
  if (failed !== undefined && (plan.manifestEdits.length > 0 || journal.size > saved)) {
7855
8617
  const lockfile = basename6(install.lockfile);
7856
- const created = plan.noLockfile && existsSync12(install.lockfile);
8618
+ const created = plan.noLockfile && existsSync13(install.lockfile);
7857
8619
  const unrestored = await restoreJournal(journal, folders);
7858
- report.unrestored = unrestored.map((path) => relative15(start, path));
8620
+ report.unrestored = unrestored.map((path) => relative16(start, path));
7859
8621
  report.restored = unrestored.length === 0;
7860
8622
  const reinstall = plan.noLockfile ? commands.install : commands.frozenInstall;
7861
8623
  const manifests = plan.manifests.length === 1 ? "package.json" : `${plan.manifests.length} package.json files`;
@@ -7874,7 +8636,7 @@ async function restoreJournal(journal, folders = []) {
7874
8636
  try {
7875
8637
  if (saved !== null)
7876
8638
  await writeFile6(path, saved);
7877
- else if (existsSync12(path))
8639
+ else if (existsSync13(path))
7878
8640
  await rm2(path);
7879
8641
  return [];
7880
8642
  } catch {
@@ -7908,6 +8670,7 @@ async function upgrade(path, options) {
7908
8670
  }
7909
8671
 
7910
8672
  // src/cli.ts
8673
+ var CONNECT_HOSTS = ["vercel", "netlify", "cloudflare", "node"];
7911
8674
  var program2 = new Command;
7912
8675
  program2.name("conloca").usage("<command> [options]").helpOption("-h, --help", "Show this help message").addHelpText("after", `
7913
8676
  Run 'conloca <command> --help' for help on a single command.`);
@@ -7977,16 +8740,22 @@ exists too (a server adapter), else dist. The baseline stays in
7977
8740
  node_modules/.cache until --reset. Never commits. Exits 1 when anything differs.`).action(async (path, options) => {
7978
8741
  await compare(path, { routes: options.routes, reset: options.reset === true, json: options.json === true });
7979
8742
  });
7980
- program2.command("connect").argument("[path]", "Folder of the Astro site, or of the repository holding it", ".").option("--project <dir>", "Astro project to set up, when the repository has several").option("--site-url <url>", "The address the site is deployed at, when astro.config sets no `site`").option("--yes", "Accept every change without asking (no terminal needed)").option("--dry-run", "Show the changes, write nothing").option("--no-install", "Do not install packages; print the command instead").option("--no-build", "Skip the local build check").option("--update", "Refresh the draft preview settings in wrangler.jsonc from a fresh build, and nothing else").addOption(new Option("--cf-plan <plan>", "Your Cloudflare Workers plan, for draft previews of a static site (asked on a terminal otherwise)").choices(["free", "paid"])).option("--negotiate-404", 'Send every miss to the draft preview dispatcher (not_found_handling "none"), for middleware that negotiates responses').option("--json", "One JSON report on stdout").description("Set up an Astro site's editor page for your workspace editor").addHelpText("after", `
8743
+ program2.command("connect").argument("[path]", "Folder of the Astro site, or of the repository holding it", ".").option("--project <dir>", "Astro project to set up, when the repository has several").option("--site-url <url>", "The address the site is deployed at, when astro.config sets no `site`").option("--yes", "Accept every change without asking (no terminal needed)").option("--dry-run", "Show the changes, write nothing").option("--no-install", "Do not install packages; print the command instead").option("--no-build", "Skip the local build check").option("--update", "Refresh the draft preview settings in wrangler.jsonc from a fresh build, and nothing else").addOption(new Option("--cf-plan <plan>", "Your Cloudflare Workers plan, for draft previews of a static site (asked on a terminal otherwise)").choices(["free", "paid"])).addOption(new Option("--host <host>", "Where the site deploys, for draft previews (detected from its files otherwise)").choices(CONNECT_HOSTS)).option("--negotiate-404", 'Send every miss to the draft preview dispatcher (not_found_handling "none"), for middleware that negotiates responses').option("--json", "One JSON report on stdout").description("Set up an Astro site's editor page for your workspace editor").addHelpText("after", `
7981
8744
  Adds @conloca/astro-cms, @conloca/cloud-astro and their React peers with the
7982
8745
  project's own package manager, wires react(), conlocaCMS() and conlocaCloud()
7983
8746
  into astro.config, writes the site's domain into sites.json, allows the
7984
8747
  workspace editor to frame the editor page where a committed header forbids
7985
8748
  it, builds the site once to prove the editor page is there, and removes the
7986
8749
  old build key from workflows. With previewBuild in conlocaCloud(), it also
7987
- writes the draft preview settings into wrangler.jsonc; --update refreshes only
7988
- those, from a fresh build, --cf-plan answers the plan question without a
7989
- terminal, and --negotiate-404 sends every miss to the preview dispatcher.
8750
+ finds where the site deploys (--host names it), adds that host's official
8751
+ Astro adapter so drafts render in the site's own build (Vercel, Netlify), and
8752
+ prints the host's deploy step, or writes the draft preview settings into
8753
+ wrangler.jsonc on Cloudflare; --update refreshes only those, from a fresh
8754
+ build, and never adds an adapter, --cf-plan answers the plan question without
8755
+ a terminal, and --negotiate-404 sends every miss to the preview dispatcher.
8756
+ On Vercel and Netlify, an astro.config without site gets site proposed from
8757
+ sites.json (or --site-url) and asked for first, since site changes canonical,
8758
+ sitemap, RSS and Open Graph URLs; --yes never writes it.
7990
8759
  Every change is shown as a diff first; in a terminal it asks before it writes
7991
8760
  (and, for a static site previewing next to itself, once for your Cloudflare
7992
8761
  plan), --yes accepts, and without a terminal or --yes nothing is written. A
@@ -7994,6 +8763,7 @@ value you set yourself is kept and reported as "differs".
7994
8763
  Never commits, pushes or deploys. A site whose @conloca packages are older
7995
8764
  than this CLI is handed to 'conloca upgrade' with nothing written (exit 2).
7996
8765
  Exits 0 when done, 1 when a step failed, 2 when a step needs you.`).action(async (path, options) => {
8766
+ const host = CONNECT_HOSTS.find((choice) => choice === options.host);
7997
8767
  await connect(path, {
7998
8768
  project: options.project,
7999
8769
  siteUrl: options.siteUrl,
@@ -8004,7 +8774,8 @@ Exits 0 when done, 1 when a step failed, 2 when a step needs you.`).action(async
8004
8774
  json: options.json === true,
8005
8775
  update: options.update === true,
8006
8776
  negotiate404: options.negotiate404 === true,
8007
- ...isCfPlan(options.cfPlan) ? { cfPlan: options.cfPlan } : {}
8777
+ ...isCfPlan(options.cfPlan) ? { cfPlan: options.cfPlan } : {},
8778
+ ...host === undefined ? {} : { host }
8008
8779
  });
8009
8780
  });
8010
8781
  program2.command("upgrade").argument("[path]", "Folder of the Astro site, or of the repository holding it", ".").option("--project <dir>", "Astro project to upgrade, when the repository has several").option("--dry-run", "Show the changes, write nothing").option("--json", "One JSON report on stdout").description("Bring every @conloca package of the site to the version this CLI pins").addHelpText("after", `