@unbase-app/cli 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/readers.mjs CHANGED
@@ -92,15 +92,15 @@ async function textLocation(repo, app, files) {
92
92
  const g = groupOf(page);
93
93
  groups.set(g, [...groups.get(g) ?? [], page]);
94
94
  }
95
- const literal2 = /* @__PURE__ */ new Map();
95
+ const literal4 = /* @__PURE__ */ new Map();
96
96
  await Promise.all(
97
97
  spread(groups, PAGE_CAP).map(async (page) => {
98
98
  const source = await repo.read(join(app.path, `src/pages/${page}`));
99
- if (source !== null) literal2.set(page, literalText(source));
99
+ if (source !== null) literal4.set(page, literalText(source));
100
100
  })
101
101
  );
102
102
  const result = [...groups].map(([group, list]) => {
103
- const total = list.reduce((sum, p) => sum + (literal2.get(p) ?? 0), 0);
103
+ const total = list.reduce((sum, p) => sum + (literal4.get(p) ?? 0), 0);
104
104
  return { group, pages: list.length, literal: total, in: total > LITERAL_IN_CODE ? "code" : "content" };
105
105
  });
106
106
  const inCode = result.filter((g) => g.in === "code").length;
@@ -272,9 +272,27 @@ function packageManager(repo, appPath, root) {
272
272
  const field2 = root?.pkg.packageManager;
273
273
  return typeof field2 === "string" ? field2.split("@")[0] || null : null;
274
274
  }
275
- function cmsOf(repo, app, root) {
276
- const deps = { ...root?.deps ?? {}, ...app.deps };
277
- const files = within(repo.paths, app.path);
275
+ function linkedOf(app, all) {
276
+ const byName = /* @__PURE__ */ new Map();
277
+ for (const a of all) if (typeof a.pkg.name === "string" && a.path !== app.path) byName.set(a.pkg.name, a);
278
+ const linked = [];
279
+ const seen = /* @__PURE__ */ new Set([app.path]);
280
+ const queue = [app];
281
+ while (queue.length) {
282
+ for (const dep of Object.keys(queue.shift().deps)) {
283
+ const found = byName.get(dep);
284
+ if (!found || seen.has(found.path)) continue;
285
+ seen.add(found.path);
286
+ linked.push(found);
287
+ queue.push(found);
288
+ }
289
+ }
290
+ return linked;
291
+ }
292
+ var allDeps = (app, root, linked) => ({ ...root?.deps ?? {}, ...Object.assign({}, ...linked.map((l) => l.deps)), ...app.deps });
293
+ function cmsOf(repo, app, root, linked) {
294
+ const deps = allDeps(app, root, linked);
295
+ const files = [app, ...linked].flatMap((a) => within(repo.paths, a.path));
278
296
  return CMS.filter((c) => Object.keys(deps).some((d) => c.deps.test(d)) || c.config && files.some((f) => c.config.test(f))).map(({ id, name }) => ({
279
297
  id,
280
298
  name
@@ -371,8 +389,8 @@ async function imageHostsOf(read, paths) {
371
389
  }
372
390
  return [];
373
391
  }
374
- function servicesOf(app, root) {
375
- const deps = Object.keys({ ...root?.deps ?? {}, ...app.deps });
392
+ function servicesOf(app, root, linked) {
393
+ const deps = Object.keys(allDeps(app, root, linked));
376
394
  return [...CMS, ...SERVICES].filter((s) => deps.some((d) => s.deps.test(d))).map(({ id, name }) => ({ id, name }));
377
395
  }
378
396
  async function detect(repo, branch, truncated, appPath) {
@@ -409,6 +427,7 @@ async function detect(repo, branch, truncated, appPath) {
409
427
  }
410
428
  if (!chosen) return { ...empty, app_path: "", framework: !all.length && repo.paths.includes("index.html") ? HTML : null };
411
429
  const fw = frameworkOf(chosen.deps);
430
+ const linked = linkedOf(chosen, all);
412
431
  const adapter = fw ? ADAPTERS.find((a) => a.framework === fw.id) ?? null : null;
413
432
  const found = adapter ? await adapter.detect(repo, chosen) : { text: null, site: null, project: null };
414
433
  const cmName = COMMENT_MODES.find((n) => chosen.deps[n] ?? root?.deps[n]);
@@ -423,148 +442,42 @@ async function detect(repo, branch, truncated, appPath) {
423
442
  framework: fw ? { id: fw.id, name: fw.name, ...versionOf(chosen.deps[fw.dep]) } : null,
424
443
  adapter: adapter?.id ?? null,
425
444
  package_manager: packageManager(repo, chosen.path, root),
426
- cms: cmsOf(repo, chosen, root),
445
+ cms: cmsOf(repo, chosen, root, linked),
427
446
  comment_modus: cmRange || carried ? { state: "installed", version: cmRange ? versionOf(cmRange).version : null, site: found.site, project: found.project } : { state: "absent" },
428
447
  text: found.text,
429
448
  settings,
430
449
  settings_truncated: settingsTruncated,
431
- services: servicesOf(chosen, root),
450
+ services: servicesOf(chosen, root, linked),
432
451
  image_hosts: imageHosts,
433
452
  other_host: otherHostOf(repo.paths, chosen.path)
434
453
  };
435
454
  }
436
455
 
437
- // supabase/functions/_shared/html-head.ts
438
- var headPointer = (field2) => `/head/${field2}`;
439
- var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
440
- function decodeValue(raw) {
441
- return raw.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&([a-z]+);/gi, (m, n) => ENTITIES[n.toLowerCase()] ?? m).replace(/\s+/g, " ").trim();
442
- }
443
- function tagsIn(html, from, until) {
444
- const out = [];
445
- let i = from;
446
- while (i < until) {
447
- const lt = html.indexOf("<", i);
448
- if (lt < 0 || lt >= until) break;
449
- if (html.startsWith("<!--", lt)) {
450
- const close = html.indexOf("-->", lt + 4);
451
- i = close < 0 ? until : close + 3;
452
- continue;
453
- }
454
- const name = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(lt, lt + 64))?.[1];
455
- if (!name) {
456
- i = lt + 1;
457
- continue;
458
- }
459
- const attrs = [];
460
- let j = lt + 1 + name.length;
461
- let end = -1;
462
- while (j < html.length) {
463
- const c = html[j];
464
- if (c === ">") {
465
- end = j + 1;
466
- break;
467
- }
468
- if (/[\s/]/.test(c)) {
469
- j++;
470
- continue;
471
- }
472
- const m = /^([^\s"'>/=]+)(\s*=\s*)?/.exec(html.slice(j, j + 256));
473
- if (!m) {
474
- j++;
475
- continue;
476
- }
477
- j += m[0].length;
478
- if (!m[2]) {
479
- attrs.push({ name: m[1].toLowerCase(), value: "", start: j, end: j, quote: null });
480
- continue;
481
- }
482
- const q = html[j];
483
- if (q === '"' || q === "'") {
484
- const close = html.indexOf(q, j + 1);
485
- if (close < 0) break;
486
- attrs.push({ name: m[1].toLowerCase(), value: html.slice(j + 1, close), start: j + 1, end: close, quote: q });
487
- j = close + 1;
488
- } else {
489
- const bare = /^[^\s>]*/.exec(html.slice(j))[0];
490
- attrs.push({ name: m[1].toLowerCase(), value: bare, start: j, end: j + bare.length, quote: null });
491
- j += bare.length;
492
- }
493
- }
494
- if (end < 0) break;
495
- out.push({ name: name.toLowerCase(), start: lt, end, attrs });
496
- i = end;
497
- if (/^(script|style)$/i.test(name)) {
498
- const close = html.toLowerCase().indexOf(`</${name.toLowerCase()}`, end);
499
- i = close < 0 ? until : close;
500
- }
501
- }
502
- return out;
503
- }
504
- var attrOf = (tag, name) => tag.attrs.find((a) => a.name === name);
505
- var spanOf = (a) => ({ start: a.start, end: a.end, mode: "attr", quote: a.quote });
506
- var plain = (raw) => !/[{}]|<%|%>/.test(raw);
507
- function readHead(html) {
508
- const out = {};
509
- const lower = html.toLowerCase();
510
- const headAt = lower.search(/<head[\s>]/);
511
- const bodyAt = lower.search(/<body[\s>]/);
512
- const headEnd = lower.indexOf("</head");
513
- const until = headEnd >= 0 ? headEnd : bodyAt >= 0 ? bodyAt : html.length;
514
- if (headAt < 0) return out;
515
- const htmlTag = tagsIn(html, 0, headAt).find((t) => t.name === "html");
516
- const lang = htmlTag && attrOf(htmlTag, "lang");
517
- if (lang && lang.value.trim() && plain(lang.value)) out.language = { value: decodeValue(lang.value), spans: [spanOf(lang)] };
518
- const tags = tagsIn(html, headAt, until);
519
- const metas = tags.filter((t) => t.name === "meta");
520
- const meta = (key) => metas.filter((t) => [attrOf(t, "name")?.value, attrOf(t, "property")?.value].some((v) => v?.trim().toLowerCase() === key)).map((t) => attrOf(t, "content")).filter((a) => !!a);
521
- const fromMeta = (key, copies) => {
522
- const found = meta(key);
523
- if (found.length !== 1 || !plain(found[0].value) || !found[0].value.trim()) return void 0;
524
- const value = decodeValue(found[0].value);
525
- return { value, spans: [spanOf(found[0]), ...copiesOf(value, copies)] };
526
- };
527
- const copiesOf = (value, keys) => keys.flatMap((k) => meta(k)).filter((a) => plain(a.value) && decodeValue(a.value) === value).map(spanOf);
528
- const titles = tags.filter((t) => t.name === "title");
529
- if (titles.length === 1) {
530
- const t = titles[0];
531
- const close = lower.indexOf("</title", t.end);
532
- const raw = close >= 0 ? html.slice(t.end, close) : "";
533
- if (close >= 0 && raw.trim() && !raw.includes("<") && plain(raw)) {
534
- const value = decodeValue(raw);
535
- out.title = { value, spans: [{ start: t.end, end: close, mode: "text", quote: null }, ...copiesOf(value, ["og:title", "twitter:title"])] };
536
- }
537
- }
538
- const description = fromMeta("description", ["og:description", "twitter:description"]);
539
- if (description) out.description = description;
540
- const image = fromMeta("og:image", ["twitter:image"]);
541
- if (image) out.image = image;
542
- const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
543
- const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
544
- for (const [field2, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
545
- const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
546
- const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
547
- if (href && href.value.trim() && plain(href.value)) out[field2] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
548
- }
549
- return out;
550
- }
551
-
552
456
  // supabase/functions/_shared/pages-core.mjs
553
457
  var pages_core_exports = {};
554
458
  __export(pages_core_exports, {
555
459
  DRAFTABLE: () => DRAFTABLE,
556
460
  KIT: () => KIT,
557
461
  KITS: () => KITS,
462
+ OBJECT_ROUTES_SINCE: () => OBJECT_ROUTES_SINCE,
558
463
  PAGE_ACTION_FRAMEWORKS: () => PAGE_ACTION_FRAMEWORKS,
559
464
  PAGE_FILE: () => PAGE_FILE,
465
+ PAGE_OPERATIONS: () => PAGE_OPERATIONS,
560
466
  REDIRECTS_SINCE: () => REDIRECTS_SINCE,
467
+ VERCEL_JSON: () => VERCEL_JSON,
468
+ adapterOf: () => adapterOf,
469
+ createCapability: () => createCapability,
470
+ createdAddress: () => createdAddress,
561
471
  deployContext: () => deployContext,
562
472
  discover: () => discover,
563
473
  draftCheck: () => draftCheck,
564
474
  draftPaths: () => draftPaths,
565
475
  draftPlan: () => draftPlan,
476
+ dynamicSegment: () => dynamicSegment,
566
477
  folderPaths: () => folderPaths,
478
+ hostedVercelJson: () => hostedVercelJson,
567
479
  importGraph: () => importGraph,
480
+ isPattern: () => isPattern,
568
481
  kitFiles: () => kitFiles,
569
482
  kitInstalled: () => kitInstalled,
570
483
  kitRedirects: () => kitRedirects,
@@ -574,52 +487,173 @@ __export(pages_core_exports, {
574
487
  listTools: () => listTools,
575
488
  lowestVersion: () => lowestVersion,
576
489
  mediaGenerators: () => mediaGenerators,
490
+ noRedirects: () => noRedirects,
577
491
  normalisePath: () => normalisePath,
578
492
  ownedContent: () => ownedContent,
579
493
  pageActions: () => pageActions,
580
494
  parsePageFile: () => parsePageFile,
581
495
  planPage: () => planPage,
582
496
  planRedirect: () => planRedirect,
497
+ redirectMode: () => redirectMode,
583
498
  redirectsFor: () => redirectsFor,
584
499
  removeRoutes: () => removeRoutes,
500
+ requestOf: () => requestOf,
585
501
  resolveImport: () => resolveImport,
502
+ routeTest: () => routeTest,
586
503
  segmentFiles: () => segmentFiles,
587
504
  sentences: () => sentences,
588
505
  siteRedirectList: () => siteRedirectList,
589
506
  siteRedirects: () => siteRedirects,
590
507
  slugOf: () => slugOf,
591
508
  stripComments: () => stripComments,
509
+ templateMatches: () => templateMatches,
510
+ templateTest: () => templateTest,
592
511
  validAddress: () => validAddress,
593
512
  withoutInContentMap: () => withoutInContentMap,
594
513
  withoutInPageList: () => withoutInPageList,
595
514
  withoutInSitemap: () => withoutInSitemap
596
515
  });
516
+
517
+ // supabase/functions/_shared/pages-address.mjs
518
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
519
+ function normalisePath(p) {
520
+ const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
521
+ return s || "/";
522
+ }
523
+ function slugOf(name) {
524
+ return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
525
+ }
526
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
527
+ function validAddress(p) {
528
+ const at3 = normalisePath(p);
529
+ if (at3.length > 200) return false;
530
+ if (at3 === "/") return true;
531
+ return at3.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
532
+ }
533
+ var isPattern = (path) => /[[\]:*]/.test(path);
534
+ function dynamicSegment(segment) {
535
+ if (segment === "*") return { name: "", rest: true };
536
+ const bracket = segment.match(/^\[{1,2}(\.\.\.)?([^\]]+?)\]{1,2}$/);
537
+ if (bracket) return { name: (
538
+ /** @type {string} */
539
+ bracket[2]
540
+ ), rest: !!bracket[1] };
541
+ const colon = segment.match(/^:([^?]+)\??$/);
542
+ return colon ? { name: (
543
+ /** @type {string} */
544
+ colon[1]
545
+ ), rest: false } : null;
546
+ }
547
+ function routeTest(pattern) {
548
+ let re = "";
549
+ for (const segment of pattern.split("/").filter(Boolean)) {
550
+ const d = dynamicSegment(segment);
551
+ if (!d) {
552
+ re += `/${escape(segment)}`;
553
+ continue;
554
+ }
555
+ const optional = segment.startsWith("[[") || segment.endsWith("?");
556
+ if (d.rest) re += optional ? "(?:/[^/]+)*" : "(?:/[^/]+)+";
557
+ else re += optional ? "(?:/[^/]+)?" : "/[^/]+";
558
+ }
559
+ return new RegExp(`^${re || "/"}/?$`);
560
+ }
561
+ function templateMatches(template, path) {
562
+ const t = template.split("/");
563
+ const p = path.split("/");
564
+ if (t.at(-1)?.startsWith("[...") || t.at(-1) === "*") return p.length >= t.length - 1 && t.slice(0, -1).every((s, i) => s === p[i] || /^(\[|:)/.test(s));
565
+ return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
566
+ }
567
+ function redirectMatches(source, path) {
568
+ if (!/\[|:/.test(source)) return false;
569
+ const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => i % 2 ? part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+" : escape(part)).join("")}$`);
570
+ return re.test(path);
571
+ }
572
+ function templateTest(pattern) {
573
+ const segment = (s) => /^\[\[?\.\.\./.test(s) || s === "*" ? ".+" : /^\[.+\]$/.test(s) || s.startsWith(":") ? "[^/]+" : escape(s);
574
+ return new RegExp(`^${pattern.split("/").map(segment).join("/")}$`);
575
+ }
576
+
577
+ // supabase/functions/_shared/pages-core.mjs
597
578
  var PAGE_FILE = "unbase.pages.json";
598
579
  var KIT = "@unbase-app/pages";
599
- var KITS = {
600
- astro: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
601
- "vite-react": [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
602
- next: ["@unbase-app/next"]
580
+ var ADAPTERS2 = {
581
+ astro: {
582
+ kits: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
583
+ configs: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
584
+ listTools: [],
585
+ discover: (kept) => ({ pages: astroPages(kept), notFound: null }),
586
+ acts: true,
587
+ routeLines: false,
588
+ segments: false,
589
+ configSources: astroConfigSources,
590
+ configRedirects: astroConfigRedirects,
591
+ starter: astroStarter
592
+ },
593
+ "vite-react": {
594
+ kits: [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
595
+ configs: ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
596
+ listTools: [],
597
+ discover: (kept, text) => reactRouterPages(kept, text),
598
+ acts: true,
599
+ routeLines: true,
600
+ segments: false,
601
+ redirect: ({ prefix, source, base, destBase }) => ({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix }),
602
+ canCreate: (discovered, kept, text) => siblingRoutes(discovered, text).length ? { ok: true } : { ok: false, reason: "routes_unread" },
603
+ starter: reactRouterStarter
604
+ },
605
+ next: {
606
+ kits: ["@unbase-app/next"],
607
+ configs: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
608
+ listTools: ["next-sitemap"],
609
+ discover: (kept) => ({ pages: nextPages(kept), notFound: null }),
610
+ acts: true,
611
+ routeLines: false,
612
+ segments: true,
613
+ configSources: nextConfigSources,
614
+ configRedirects: nextConfigRedirects,
615
+ redirect: ({ prefix, source, destination: destination2, base, destBase }) => ({
616
+ source: prefix ? `${base === "/" ? "" : base}/:path*` : source,
617
+ destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination2,
618
+ permanent: true
619
+ }),
620
+ canCreate: (discovered, kept) => discovered.pages.some((p) => p.file && routesBase(p.file)) || kept.some((p) => /^(src\/)?app\/layout\.(tsx|jsx|js|ts)$/.test(p)) ? { ok: true } : { ok: false, reason: "unparsed" },
621
+ starter: nextStarter
622
+ },
623
+ html: {
624
+ kits: [],
625
+ configs: [],
626
+ listTools: [],
627
+ discover: (kept) => ({ pages: htmlPages(kept), notFound: null }),
628
+ acts: true,
629
+ routeLines: false,
630
+ segments: false,
631
+ destination: (page, to) => htmlDestination(page, to),
632
+ folderDirs: (at3, below) => below.length && below.every((p) => p.file?.startsWith(`${at3.slice(1)}/`)) ? [at3.slice(1)] : null,
633
+ links: (p) => /\.html?$/.test(p),
634
+ relativeLinks: true,
635
+ canCreate: (discovered) => discovered.pages.length ? { ok: true } : { ok: false, reason: "unparsed" },
636
+ starter: htmlStarter
637
+ }
603
638
  };
639
+ var adapterOf = (framework) => Object.prototype.hasOwnProperty.call(ADAPTERS2, String(framework)) ? ADAPTERS2[String(framework)] : null;
640
+ var FRAMEWORKS2 = Object.keys(ADAPTERS2);
641
+ var KITS = Object.fromEntries(FRAMEWORKS2.filter((f) => ADAPTERS2[f].kits.length).map((f) => [f, ADAPTERS2[f].kits]));
604
642
  var DRAFTABLE = Object.keys(KITS);
605
643
  var EXTS = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".mts", ".astro", ".vue", ".svelte", ".json"];
606
644
  var CODE = /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html)$/;
607
645
  var SKIP2 = /(^|\/)(node_modules|dist|build|\.git|\.astro|\.next|\.vercel|\.output)(\/|$)/;
608
646
  var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
609
- var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
610
- function normalisePath(p) {
611
- const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
612
- return s || "/";
613
- }
647
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
614
648
  function parsePageFile(text) {
615
- if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
649
+ if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {}, hosted: {} };
616
650
  const fail = (error) => ({ ok: (
617
651
  /** @type {const} */
618
652
  false
619
653
  ), exists: (
620
654
  /** @type {const} */
621
655
  true
622
- ), error, pages: {}, folders: {}, redirects: {} });
656
+ ), error, pages: {}, folders: {}, redirects: {}, hosted: {} });
623
657
  let data;
624
658
  try {
625
659
  data = JSON.parse(text);
@@ -645,16 +679,20 @@ function parsePageFile(text) {
645
679
  if (!isObject(entry) || entry.name !== void 0 && typeof entry.name !== "string") return fail(`folders: ${address2}: name is text`);
646
680
  if (entry.name) folders[normalisePath(address2)] = { name: entry.name };
647
681
  }
648
- const redirects = data.redirects ?? {};
649
- if (!isObject(redirects)) return fail("`redirects` is not an object");
650
- const sends2 = {};
651
- for (const [from, to] of Object.entries(redirects)) {
652
- if (!from.startsWith("/")) return fail(`redirects: ${from}: an address starts with /`);
653
- if (typeof to !== "string" || !to.startsWith("/")) return fail(`redirects: ${from}: goes to an address that starts with /`);
654
- if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
655
- sends2[normalisePath(from)] = normalisePath(to);
682
+ const maps = [];
683
+ for (const key of ["redirects", "hosted"]) {
684
+ const given = data[key] ?? {};
685
+ if (!isObject(given)) return fail(`\`${key}\` is not an object`);
686
+ const sends2 = {};
687
+ for (const [from, to] of Object.entries(given)) {
688
+ if (!from.startsWith("/")) return fail(`${key}: ${from}: an address starts with /`);
689
+ if (typeof to !== "string" || !to.startsWith("/")) return fail(`${key}: ${from}: goes to an address that starts with /`);
690
+ if (REST.test(from) !== REST.test(to)) return fail(`${key}: ${from}: both ends end in /[...path], or neither`);
691
+ sends2[normalisePath(from)] = normalisePath(to);
692
+ }
693
+ maps.push(sends2);
656
694
  }
657
- return { ok: true, exists: true, pages: out, folders, redirects: sends2 };
695
+ return { ok: true, exists: true, pages: out, folders, redirects: maps[0], hosted: maps[1] };
658
696
  }
659
697
  var REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
660
698
  var draftPaths = (file) => Object.keys(file.pages).filter((p) => file.pages[p].draft === true).sort();
@@ -880,14 +918,212 @@ function importedComponents(src) {
880
918
  out.set(m[1], { spec: m[2], kind: "lazy" });
881
919
  return out;
882
920
  }
921
+ var ROUTER_CALL = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/g;
922
+ var MAKES_ROUTER = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/;
923
+ var IMPORTS_ROUTER = /from\s*["']react-router(-dom)?["']/;
924
+ var skipWs = (src, i) => {
925
+ while (i < src.length && /\s/.test(src[i])) i++;
926
+ return i;
927
+ };
928
+ function closing(src, i) {
929
+ let depth = 0;
930
+ for (let j = i; j < src.length; j++) {
931
+ const c = src[j];
932
+ if (c === '"' || c === "'" || c === "`") {
933
+ j = stringEnd(src, j) - 1;
934
+ continue;
935
+ }
936
+ if (c === "{" || c === "[" || c === "(") depth++;
937
+ else if ((c === "}" || c === "]" || c === ")") && --depth === 0) return j + 1;
938
+ }
939
+ return src.length;
940
+ }
941
+ function valueEnd(src, i, end) {
942
+ let depth = 0;
943
+ while (i < end) {
944
+ const c = src[i];
945
+ if (c === '"' || c === "'" || c === "`") {
946
+ i = stringEnd(src, i);
947
+ continue;
948
+ }
949
+ if (c === "{" || c === "[" || c === "(") depth++;
950
+ else if (c === "}" || c === "]" || c === ")") {
951
+ if (depth === 0) return i;
952
+ depth--;
953
+ } else if (c === "," && depth === 0) return i;
954
+ i++;
955
+ }
956
+ return i;
957
+ }
958
+ function arrayElements(src, at3) {
959
+ const end = closing(src, at3) - 1;
960
+ const out = [];
961
+ let i = at3 + 1;
962
+ while (i < end) {
963
+ i = skipWs(src, i);
964
+ if (i >= end) break;
965
+ if (src[i] === ",") {
966
+ i++;
967
+ continue;
968
+ }
969
+ const stop = valueEnd(src, i, end);
970
+ let e = stop;
971
+ while (e > i && /\s/.test(src[e - 1])) e--;
972
+ if (e > i) out.push({ start: i, end: src[i] === "{" ? closing(src, i) : e });
973
+ i = stop;
974
+ }
975
+ return out;
976
+ }
977
+ function objectEntries(src, at3) {
978
+ const end = closing(src, at3) - 1;
979
+ const out = [];
980
+ let i = at3 + 1;
981
+ while (i < end) {
982
+ i = skipWs(src, i);
983
+ if (i >= end) break;
984
+ if (src[i] === ",") {
985
+ i++;
986
+ continue;
987
+ }
988
+ const stop = valueEnd(src, i, end);
989
+ const key = src.slice(i, stop).match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:\s*/);
990
+ if (key) {
991
+ const valueStart = i + key[0].length;
992
+ let e = stop;
993
+ while (e > valueStart && /\s/.test(src[e - 1])) e--;
994
+ out.push({ key: key[2], valueStart, valueEnd: e });
995
+ }
996
+ i = stop;
997
+ }
998
+ return out;
999
+ }
1000
+ function literalString(value) {
1001
+ const lit = value.trim().match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/);
1002
+ return lit ? lit.slice(1).find((v) => v !== void 0) ?? "" : false;
1003
+ }
1004
+ function arrayDeclared(src, name) {
1005
+ const m = new RegExp(`(?:^|[;\\s])(?:export\\s+)?(?:const|let|var)\\s+${escape2(name)}\\s*(?::[^=;]+)?=\\s*`).exec(src);
1006
+ if (!m) return null;
1007
+ const at3 = skipWs(src, m.index + m[0].length);
1008
+ return src[at3] === "[" ? at3 : null;
1009
+ }
1010
+ function defaultArray(src) {
1011
+ const m = src.match(/\bexport\s+default\s+/);
1012
+ if (!m) return null;
1013
+ const at3 = skipWs(src, m.index + m[0].length);
1014
+ if (src[at3] === "[") return at3;
1015
+ const name = src.slice(at3).match(/^([A-Za-z_$][\w$]*)\s*;?/)?.[1];
1016
+ return name ? arrayDeclared(src, name) : null;
1017
+ }
1018
+ function importOf(src, name) {
1019
+ for (const m of src.matchAll(/import\s+(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\{([^}]*)\})?\s*from\s*["']([^"']+)["']/g)) {
1020
+ if (m[1] === name) return { spec: m[3], exported: null };
1021
+ for (const part of (m[2] ?? "").split(",")) {
1022
+ const [exported, local] = part.trim().split(/\s+as\s+/);
1023
+ if ((local ?? exported) === name && exported) return { spec: m[3], exported };
1024
+ }
1025
+ }
1026
+ return null;
1027
+ }
1028
+ function routeArrays(paths, text, have) {
1029
+ const out = /* @__PURE__ */ new Map();
1030
+ const add = (f, at3) => out.set(f, [.../* @__PURE__ */ new Set([...out.get(f) ?? [], at3])]);
1031
+ for (const file of paths) {
1032
+ if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP2.test(file)) continue;
1033
+ const raw = text(file);
1034
+ if (!raw || !IMPORTS_ROUTER.test(raw) || !MAKES_ROUTER.test(raw)) continue;
1035
+ const src = stripComments(raw);
1036
+ for (const m of src.matchAll(ROUTER_CALL)) {
1037
+ const i = skipWs(src, m.index + m[0].length);
1038
+ if (src[i] === "[") {
1039
+ add(file, i);
1040
+ continue;
1041
+ }
1042
+ const name = src.slice(i).match(/^([A-Za-z_$][\w$]*)\s*[,)]/)?.[1];
1043
+ if (!name) continue;
1044
+ const local = arrayDeclared(src, name);
1045
+ if (local !== null) {
1046
+ add(file, local);
1047
+ continue;
1048
+ }
1049
+ const imp = importOf(src, name);
1050
+ const target = imp ? resolveImport(file, imp.spec, have) : null;
1051
+ const other = target ? text(target) : null;
1052
+ if (!other) continue;
1053
+ const tsrc = stripComments(other);
1054
+ const at3 = imp.exported ? arrayDeclared(tsrc, imp.exported) : defaultArray(tsrc);
1055
+ if (at3 !== null) add(target, at3);
1056
+ }
1057
+ }
1058
+ return out;
1059
+ }
1060
+ function routeObjectPages({ file, src, at: at3, parent, have, imports, pages, found }) {
1061
+ for (const el of arrayElements(src, at3)) {
1062
+ if (src[el.start] !== "{") continue;
1063
+ const entries = objectEntries(src, el.start);
1064
+ const value = (key) => {
1065
+ const e = entries.find((x) => x.key === key);
1066
+ return e ? src.slice(e.valueStart, e.valueEnd) : null;
1067
+ };
1068
+ const index = /^true$/.test((value("index") ?? "").trim());
1069
+ const pathValue = value("path");
1070
+ const p = pathValue === null ? null : literalString(pathValue);
1071
+ const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
1072
+ const childrenEntry = entries.find((x) => x.key === "children");
1073
+ const childAt = childrenEntry && src[childrenEntry.valueStart] === "[" ? childrenEntry.valueStart : null;
1074
+ const children = childAt !== null && arrayElements(src, childAt).length > 0;
1075
+ let component = null;
1076
+ let importKind = null;
1077
+ let target = null;
1078
+ let spec = null;
1079
+ const comp = (value("Component") ?? "").trim().match(/^([A-Z][\w$]*)$/)?.[1] ?? (value("element") ?? "").trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/)?.[1];
1080
+ if (comp) {
1081
+ const imported = imports.get(comp);
1082
+ if (imported) {
1083
+ component = comp;
1084
+ importKind = imported.kind;
1085
+ target = resolveImport(file, imported.spec, have);
1086
+ }
1087
+ } else {
1088
+ const lazy = (value("lazy") ?? "").match(/import\(\s*(["'])([^"']+)\1\s*\)/);
1089
+ if (lazy) {
1090
+ spec = lazy[2];
1091
+ importKind = "inline";
1092
+ target = resolveImport(file, spec, have);
1093
+ }
1094
+ }
1095
+ if (full === false) pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
1096
+ else if (full !== null) {
1097
+ if (full === "/*" || full.endsWith("/*") || full === "*") {
1098
+ if (full === "/*" && target) found.notFound = target;
1099
+ } else {
1100
+ const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
1101
+ if (target && importKind) page.router = { file, start: el.start, end: el.end, component, importKind, object: true, ...spec ? { spec } : {} };
1102
+ if (children) page.reason = "nested";
1103
+ else if (!target) page.reason = "unparsed";
1104
+ pages.push(page);
1105
+ }
1106
+ }
1107
+ if (childAt !== null) routeObjectPages({ file, src, at: childAt, parent: typeof full === "string" ? full : parent, have, imports, pages, found });
1108
+ }
1109
+ }
883
1110
  function reactRouterPages(paths, text, only = paths) {
884
1111
  const have = new Set(paths);
885
1112
  const pages = [];
886
- let notFound = null;
1113
+ const found = { notFound: null };
1114
+ const arrays = routeArrays(paths, text, have);
1115
+ for (const file of only) {
1116
+ const starts = arrays.get(file);
1117
+ if (!starts?.length) continue;
1118
+ const src = stripComments(text(file) ?? "");
1119
+ const imports = importedComponents(src);
1120
+ for (const at3 of starts) routeObjectPages({ file, src, at: at3, parent: "", have, imports, pages, found });
1121
+ }
1122
+ let notFound = found.notFound;
887
1123
  for (const file of only) {
888
1124
  if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP2.test(file)) continue;
889
1125
  const raw = text(file);
890
- if (!raw || !raw.includes("<Route") || !/from\s*["']react-router(-dom)?["']/.test(raw)) continue;
1126
+ if (!raw || !raw.includes("<Route") || !IMPORTS_ROUTER.test(raw)) continue;
891
1127
  const src = stripComments(raw);
892
1128
  const imports = importedComponents(src);
893
1129
  const events = [];
@@ -929,9 +1165,17 @@ function reactRouterPages(paths, text, only = paths) {
929
1165
  }
930
1166
  return { pages, notFound };
931
1167
  }
1168
+ function routeSpan(src, router) {
1169
+ if (!router.object) return { start: router.start, end: router.end };
1170
+ let end = router.end;
1171
+ let i = router.end;
1172
+ while (i < src.length && (src[i] === " " || src[i] === " ")) i++;
1173
+ if (src[i] === ",") end = i + 1;
1174
+ return { start: router.start, end };
1175
+ }
932
1176
  function removeRoutes({ file, code, paths, text, drop }) {
933
1177
  const { pages } = reactRouterPages(paths, (p) => p === file ? code : text(p), [file]);
934
- const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
1178
+ const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...routeSpan(code, p.router) }));
935
1179
  spans.sort((a, b) => b.start - a.start);
936
1180
  let out = code;
937
1181
  for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
@@ -939,7 +1183,7 @@ function removeRoutes({ file, code, paths, text, drop }) {
939
1183
  }
940
1184
  function discover({ framework, paths, text }) {
941
1185
  const kept = paths.filter((p) => !SKIP2.test(p));
942
- const found = framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : framework === "html" ? { pages: htmlPages(kept), notFound: null } : { pages: [], notFound: null };
1186
+ const found = adapterOf(framework)?.discover(kept, text) ?? { pages: [], notFound: null };
943
1187
  const seen = /* @__PURE__ */ new Set();
944
1188
  const pages = found.pages.filter((p) => seen.has(p.path) ? false : (seen.add(p.path), true)).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
945
1189
  return { pages, notFound: found.notFound };
@@ -1011,7 +1255,7 @@ function contentReads(paths, text) {
1011
1255
  for (; ; ) {
1012
1256
  let grew = false;
1013
1257
  if (names.length) {
1014
- const naming = new RegExp(names.map(escape).join("|"));
1258
+ const naming = new RegExp(names.map(escape2).join("|"));
1015
1259
  for (const [p, src] of files) {
1016
1260
  if (picked.has(p) || !naming.test(src)) continue;
1017
1261
  picked.add(p);
@@ -1041,8 +1285,8 @@ function parseCode(p, src) {
1041
1285
  const body = braces >= 0 ? braced(code, braces) ?? "" : code.slice(at3, code.slice(at3).search(/;|\n\s*\n|$/) + at3);
1042
1286
  const start = braces >= 0 ? braces + 1 : at3;
1043
1287
  const naming = ASTRO_NAMED.test(body);
1044
- const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape(first)}\\b`).test(body));
1045
- const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : void 0;
1288
+ const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape2(first)}\\b`).test(body));
1289
+ const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape2(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : void 0;
1046
1290
  const direct = naming ? Array.from(body.matchAll(DIRECT), (d) => [d[1], d[2]]) : [];
1047
1291
  fns.push({ name, start, end: start + body.length, body, byName, entry, direct });
1048
1292
  }
@@ -1079,7 +1323,7 @@ function readsOver(files, parsed = /* @__PURE__ */ new Map()) {
1079
1323
  for (const [name, body] of bodies) {
1080
1324
  for (const fn of byName) {
1081
1325
  if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
1082
- for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
1326
+ for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape2(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
1083
1327
  }
1084
1328
  }
1085
1329
  const calls = fixed2.size ? new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))])) : /* @__PURE__ */ new Map();
@@ -1098,8 +1342,8 @@ function readsOver(files, parsed = /* @__PURE__ */ new Map()) {
1098
1342
  }
1099
1343
  }
1100
1344
  }
1101
- const helpers = fixed2.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed2.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
1102
- const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
1345
+ const helpers = fixed2.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed2.keys()].sort((a, b) => b.length - a.length).map(escape2).join("|")})(?![\\w$])`, "g") : null;
1346
+ const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape2).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
1103
1347
  return { code, byName, byNameCall, entryOf, fixed: fixed2, astro: astro2, spans, helpers };
1104
1348
  }
1105
1349
  var CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
@@ -1277,9 +1521,8 @@ function mediaGenerators(text) {
1277
1521
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
1278
1522
  return MEDIA.filter((m) => m in deps);
1279
1523
  }
1280
- var LIST_TOOLS = { next: ["next-sitemap"] };
1281
1524
  function listTools(framework, text) {
1282
- const tools = LIST_TOOLS[String(framework)] ?? [];
1525
+ const tools = adapterOf(framework)?.listTools ?? [];
1283
1526
  if (!tools.length) return [];
1284
1527
  let pkg = null;
1285
1528
  try {
@@ -1310,7 +1553,8 @@ function draftCheck(path, { framework, paths, text, found, importers }) {
1310
1553
  if (page.kind === "template") return no("template", page.path);
1311
1554
  if (page.reason) return no(page.reason);
1312
1555
  if (!page.file) return no("unparsed");
1313
- if (framework === "next") {
1556
+ if (page.router?.object && !kitAtLeast({ framework, text }, OBJECT_ROUTES_SINCE)) return no("kit_old", "route objects");
1557
+ if (adapterOf(framework)?.segments) {
1314
1558
  const beside = segmentFiles(page.file, paths);
1315
1559
  if (beside.length) return no("segment", beside.join(", "));
1316
1560
  }
@@ -1331,12 +1575,6 @@ function segmentFiles(file, paths) {
1331
1575
  const dir = dirname(file);
1332
1576
  return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
1333
1577
  }
1334
- function templateMatches(template, path) {
1335
- const t = template.split("/");
1336
- const p = path.split("/");
1337
- if (t.at(-1)?.startsWith("[...") || t.at(-1) === "*") return p.length >= t.length - 1 && t.slice(0, -1).every((s, i) => s === p[i] || /^(\[|:)/.test(s));
1338
- return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
1339
- }
1340
1578
  function draftPlan({ framework, paths, text, pageFile }) {
1341
1579
  if (!pageFile.ok) return { checks: [], failed: [{ ok: (
1342
1580
  /** @type {const} */
@@ -1348,34 +1586,44 @@ function draftPlan({ framework, paths, text, pageFile }) {
1348
1586
  return { checks, failed: checks.filter((c) => !c.ok), found, importers };
1349
1587
  }
1350
1588
  var APP_SOURCE = /^(src|app|pages|components|lib)\//;
1351
- function linksTo(path, { paths, text, own = [] }) {
1589
+ function linksTo(path, { paths, text, own = [], framework = null }) {
1352
1590
  if (path === "/") return [];
1353
1591
  const mine = new Set(own);
1354
- return [...linkIndex(paths, text).get(path) ?? []].filter((p) => !mine.has(p)).sort();
1592
+ return [...linkIndex(paths, text, adapterOf(framework)).get(path) ?? []].filter((p) => !mine.has(p)).sort();
1355
1593
  }
1356
1594
  var linkIndexOf = /* @__PURE__ */ new WeakMap();
1357
1595
  var QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
1358
- function linkIndex(paths, text) {
1359
- const kept = linkIndexOf.get(text);
1596
+ function linkIndex(paths, text, adapter = null) {
1597
+ const kind = adapter?.links ? "site" : "app";
1598
+ const kept = linkIndexOf.get(text)?.[kind];
1360
1599
  if (kept?.paths === paths) return kept.index;
1361
1600
  const index = /* @__PURE__ */ new Map();
1601
+ const add = (address2, p) => {
1602
+ if (!index.has(address2)) index.set(address2, /* @__PURE__ */ new Set());
1603
+ index.get(address2).add(p);
1604
+ };
1605
+ const linkFile = adapter?.links ?? ((p) => APP_SOURCE.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
1362
1606
  for (const p of paths) {
1363
- if (SKIP2.test(p) || !APP_SOURCE.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
1364
- for (const [, , quoted] of (text(p) ?? "").matchAll(QUOTED_ADDRESS)) {
1607
+ if (SKIP2.test(p) || !linkFile(p)) continue;
1608
+ const raw = text(p) ?? "";
1609
+ const src = blankRanges(raw, codeRanges(raw, p));
1610
+ for (const [, , quoted] of src.matchAll(QUOTED_ADDRESS)) {
1365
1611
  const bare = quoted.replace(/[#?][\s\S]*$/, "");
1366
- const address2 = bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare;
1367
- if (!index.has(address2)) index.set(address2, /* @__PURE__ */ new Set());
1368
- index.get(address2).add(p);
1612
+ add(bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare, p);
1613
+ }
1614
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) {
1615
+ for (const [, , , url] of src.matchAll(URL_ATTRIBUTE)) {
1616
+ const bare = url.replace(/[#?][\s\S]*$/, "");
1617
+ if (!relativeUrl(url) || !bare) continue;
1618
+ const address2 = servedAddress(resolvedUrl(dirname(p), bare), bare.endsWith("/"));
1619
+ if (address2 !== null) add(address2, p);
1620
+ }
1369
1621
  }
1370
1622
  }
1371
- linkIndexOf.set(text, { paths, index });
1623
+ linkIndexOf.set(text, { ...linkIndexOf.get(text) ?? {}, [kind]: { paths, index } });
1372
1624
  return index;
1373
1625
  }
1374
- var CONFIGS = {
1375
- astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
1376
- "vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
1377
- next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"]
1378
- };
1626
+ var CONFIGS = Object.fromEntries(FRAMEWORKS2.filter((f) => ADAPTERS2[f].configs.length).map((f) => [f, ADAPTERS2[f].configs]));
1379
1627
  var kitFiles = (framework) => ["package.json", ...CONFIGS[String(framework)] ?? []];
1380
1628
  function kitInstalled({ framework, text }) {
1381
1629
  let pkg = null;
@@ -1458,7 +1706,7 @@ function withoutInContentMap(json, files) {
1458
1706
  }
1459
1707
  return JSON.stringify(map);
1460
1708
  }
1461
- var PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
1709
+ var PAGE_ACTION_FRAMEWORKS = FRAMEWORKS2.filter((f) => ADAPTERS2[f].acts);
1462
1710
  var REDIRECTS_SINCE = { "@unbase-app/pages": "0.4.0", "@unbase-app/astro": "0.3.0", "@unbase-app/vite": "0.3.0", "@unbase-app/next": "0.3.0" };
1463
1711
  function lowestVersion(spec) {
1464
1712
  if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
@@ -1470,6 +1718,10 @@ var atLeast = (have, want) => {
1470
1718
  return true;
1471
1719
  };
1472
1720
  function kitRedirects({ framework, text }) {
1721
+ return kitAtLeast({ framework, text }, REDIRECTS_SINCE);
1722
+ }
1723
+ var OBJECT_ROUTES_SINCE = { "@unbase-app/vite": "0.4.0", "@unbase-app/pages": "0.5.0" };
1724
+ function kitAtLeast({ framework, text }, since) {
1473
1725
  if (!kitInstalled({ framework, text })) return false;
1474
1726
  let pkg = null;
1475
1727
  try {
@@ -1479,59 +1731,107 @@ function kitRedirects({ framework, text }) {
1479
1731
  const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
1480
1732
  return (KITS[String(framework)] ?? []).some((name) => {
1481
1733
  const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
1482
- const since = REDIRECTS_SINCE[name];
1734
+ const want = since[name];
1483
1735
  const have = lowestVersion(spec);
1484
- return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
1736
+ return !!want && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(want));
1485
1737
  });
1486
1738
  }
1487
- function slugOf(name) {
1488
- return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
1739
+ var VERCEL_JSON = "vercel.json";
1740
+ function redirectMode({ framework, text, host = null, found, paths }) {
1741
+ const adapter = adapterOf(framework);
1742
+ if (!adapter?.acts) return null;
1743
+ const pages = (found ?? (paths ? discover({ framework, paths, text }) : { pages: [] })).pages;
1744
+ const objects = pages.some((p) => p.router?.object);
1745
+ if (!objects && kitRedirects({ framework, text })) return "package";
1746
+ const noPackage = !(KITS[String(framework)] ?? []).length;
1747
+ return host === "vercel" && (noPackage || objects) ? "host" : null;
1748
+ }
1749
+ function noRedirects({ framework, objects = false }) {
1750
+ const noPackage = !(KITS[String(framework)] ?? []).length;
1751
+ return noPackage || objects ? "host_redirects" : "no_redirects";
1752
+ }
1753
+ function vercelRedirectOf(from, to) {
1754
+ const side = (p) => {
1755
+ if (!REST.test(p)) return p;
1756
+ const base = normalisePath(p.replace(REST, ""));
1757
+ return `${base === "/" ? "" : base}/:path*`;
1758
+ };
1759
+ return { source: side(from), destination: side(to), permanent: true };
1489
1760
  }
1490
- var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
1491
- function validAddress(p) {
1492
- const at3 = normalisePath(p);
1493
- if (at3.length > 200) return false;
1494
- if (at3 === "/") return true;
1495
- return at3.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
1761
+ var vercelKey = (r) => `${r?.source}\0${r?.destination}`;
1762
+ function hostedMirrors(text) {
1763
+ const file = parsePageFile(text(PAGE_FILE));
1764
+ return new Set(Object.entries(file.ok ? file.hosted : {}).map(([f, t]) => vercelKey(vercelRedirectOf(f, t))));
1496
1765
  }
1497
- var under = (path, at3) => at3 === "/" ? path !== "/" : path.startsWith(`${at3}/`);
1498
- var within2 = (path, at3) => path === at3 || under(path, at3);
1766
+ function hostedVercelJson(before, was, now) {
1767
+ if (JSON.stringify(Object.entries(was)) === JSON.stringify(Object.entries(now))) return { content: null };
1768
+ let data = {};
1769
+ if (before != null) {
1770
+ try {
1771
+ data = JSON.parse(before);
1772
+ } catch {
1773
+ return { error: "vercel.json is not valid JSON" };
1774
+ }
1775
+ if (!isObject(data)) return { error: "vercel.json is not an object" };
1776
+ }
1777
+ const mine = new Set(Object.entries(was).map(([f, t]) => vercelKey(vercelRedirectOf(f, t))));
1778
+ const list = Array.isArray(data.redirects) ? data.redirects : [];
1779
+ const kept = list.filter((r) => !(isObject(r) && mine.has(vercelKey(r))));
1780
+ const added = Object.entries(now).map(([f, t]) => vercelRedirectOf(f, t));
1781
+ const next = { ...data };
1782
+ if (kept.length || added.length) next.redirects = [...kept, ...added];
1783
+ else delete next.redirects;
1784
+ if (before == null && !Object.keys(next).length) return { content: null };
1785
+ const indent = before?.match(/\n(\t| +)"/)?.[1] ?? " ";
1786
+ const after = `${JSON.stringify(next, null, indent)}
1787
+ `;
1788
+ return { content: after === before ? null : after };
1789
+ }
1790
+ function hostedWrite(text, pageBefore, pageAfter) {
1791
+ const was = parsePageFile(pageBefore).hosted ?? {};
1792
+ const now = pageAfter == null ? was : parsePageFile(pageAfter).hosted ?? {};
1793
+ if (JSON.stringify(was) === JSON.stringify(now)) return null;
1794
+ const out = hostedVercelJson(text(VERCEL_JSON), was, now);
1795
+ if ("error" in out) return out;
1796
+ return out.content === null ? null : { path: VERCEL_JSON, content: out.content };
1797
+ }
1798
+ var under = (path, at3) => at3 === "/" ? path !== "/" : path.startsWith(`${at3}/`);
1799
+ var within2 = (path, at3) => path === at3 || under(path, at3);
1499
1800
  var moveAddress = (path, from, to) => path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`);
1500
1801
  var parentOf = (p) => p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/")));
1501
1802
  var lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
1502
1803
  function siteRedirects({ framework, text }) {
1503
1804
  const out = /* @__PURE__ */ new Set();
1504
1805
  try {
1505
- const v = JSON.parse(text("vercel.json") ?? "null");
1506
- for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
1806
+ const v = JSON.parse(text(VERCEL_JSON) ?? "null");
1807
+ const mine = hostedMirrors(text);
1808
+ for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string" && !mine.has(vercelKey(r))) out.add(normalisePath(r.source));
1507
1809
  } catch {
1508
1810
  }
1509
- for (const c of CONFIGS[String(framework)] ?? []) {
1510
- const src = stripComments(text(c) ?? "");
1511
- if (framework === "astro") {
1512
- const at3 = src.search(/\bredirects\s*:\s*\{/);
1513
- if (at3 < 0) continue;
1514
- const body = braced(src, src.indexOf("{", at3)) ?? "";
1515
- for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
1516
- } else if (framework === "next") {
1517
- for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
1518
- }
1811
+ const adapter = adapterOf(framework);
1812
+ for (const c of adapter?.configs ?? []) {
1813
+ if (!adapter.configSources) continue;
1814
+ for (const source of adapter.configSources(stripComments(text(c) ?? ""))) out.add(normalisePath(source));
1519
1815
  }
1520
1816
  return out;
1521
1817
  }
1818
+ function astroConfigSources(src) {
1819
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
1820
+ if (at3 < 0) return [];
1821
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
1822
+ return [...body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)].map((m) => m[1]);
1823
+ }
1824
+ function nextConfigSources(src) {
1825
+ return [...src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)].map((m) => m[1]);
1826
+ }
1522
1827
  function sends(source, path) {
1523
1828
  if (REST.test(source)) {
1524
1829
  const base = normalisePath(source.replace(REST, ""));
1525
1830
  return within2(path, base);
1526
1831
  }
1527
- return source === path || matchesPattern(source, path);
1528
- }
1529
- function matchesPattern(source, path) {
1530
- if (!/\[|:/.test(source)) return false;
1531
- const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => i % 2 ? part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+" : escape(part)).join("")}$`);
1532
- return re.test(path);
1832
+ return source === path || redirectMatches(source, path);
1533
1833
  }
1534
- function changedPageFile(before, change) {
1834
+ function changedPageFile(before, change, key = "redirects") {
1535
1835
  let data = {};
1536
1836
  try {
1537
1837
  data = before == null ? {} : JSON.parse(before) ?? {};
@@ -1540,16 +1840,16 @@ function changedPageFile(before, change) {
1540
1840
  }
1541
1841
  if (!isObject(data)) data = {};
1542
1842
  if (!isObject(data.pages)) data.pages = {};
1543
- const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
1843
+ const redirects = isObject(data[key]) ? { ...data[key] } : {};
1544
1844
  const folders = isObject(data.folders) ? { ...data.folders } : {};
1545
1845
  change(data.pages, redirects, folders);
1546
1846
  for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
1547
1847
  for (const [k, v] of Object.entries(folders)) if (!isObject(v) || !v.name) delete folders[k];
1548
1848
  if (Object.keys(folders).length) data.folders = folders;
1549
1849
  else delete data.folders;
1550
- if (Object.keys(redirects).length) data.redirects = redirects;
1551
- else delete data.redirects;
1552
- const empty = !Object.keys(data.pages).length && !data.redirects && !data.folders && Object.keys(data).length === 1;
1850
+ if (Object.keys(redirects).length) data[key] = redirects;
1851
+ else delete data[key];
1852
+ const empty = !Object.keys(data.pages).length && !data.redirects && !data.hosted && !data.folders && Object.keys(data).length === 1;
1553
1853
  if (before == null && empty) return null;
1554
1854
  const after = `${JSON.stringify(data, null, 2)}
1555
1855
  `;
@@ -1602,7 +1902,42 @@ function respecified(src, was, now, moves, have) {
1602
1902
  }
1603
1903
  var QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
1604
1904
  var MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
1605
- function relinked(src, from, to, markdown) {
1905
+ function codeRanges(src, file) {
1906
+ const out = [];
1907
+ if (/\.mdx?$/.test(file)) {
1908
+ let at3 = 0;
1909
+ let open = null;
1910
+ let start = 0;
1911
+ for (const line of src.split("\n")) {
1912
+ const fence = line.match(/^ {0,3}(`{3,}|~{3,})/);
1913
+ if (!open && fence) {
1914
+ open = fence[1];
1915
+ start = at3;
1916
+ } else if (open && fence && fence[1][0] === open[0] && fence[1].length >= open.length && !line.slice(fence[0].length).trim()) {
1917
+ out.push([start, at3 + line.length]);
1918
+ open = null;
1919
+ }
1920
+ at3 += line.length + 1;
1921
+ }
1922
+ if (open) out.push([start, src.length]);
1923
+ for (const m of blankRanges(src, out).matchAll(/(`+)(?!`)(.+?)(?<!`)\1(?!`)/g)) out.push([m.index, m.index + m[0].length]);
1924
+ }
1925
+ if (/\.(html?|astro|mdx)$/.test(file)) for (const m of src.matchAll(/<(pre|code)\b[\s\S]*?<\/\1\s*>/gi)) out.push([m.index, m.index + m[0].length]);
1926
+ return out.sort((a, b) => a[0] - b[0]);
1927
+ }
1928
+ function outside(src, ranges, change) {
1929
+ if (!ranges.length) return change(src);
1930
+ let out = "";
1931
+ let at3 = 0;
1932
+ for (const [start, end] of ranges) {
1933
+ if (end <= at3) continue;
1934
+ out += change(src.slice(at3, Math.max(at3, start))) + src.slice(Math.max(at3, start), end);
1935
+ at3 = end;
1936
+ }
1937
+ return out + change(src.slice(at3));
1938
+ }
1939
+ function relinked(src, from, to, file) {
1940
+ const markdown = /\.mdx?$/.test(file);
1606
1941
  const swap = (address2) => {
1607
1942
  const bare = address2.replace(/[#?][\s\S]*$/, "");
1608
1943
  const tail = address2.slice(bare.length);
@@ -1612,10 +1947,13 @@ function relinked(src, from, to, markdown) {
1612
1947
  if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
1613
1948
  return address2;
1614
1949
  };
1615
- let out = src.replace(QUOTED, (m, q, address2) => `${q}${swap(address2)}`);
1616
- if (markdown) out = out.replace(MD_LINK, (m, a, address2, b) => `${a}${swap(address2)}${b}`);
1617
- return out;
1950
+ return outside(src, codeRanges(src, file), (piece) => {
1951
+ let out = piece.replace(QUOTED, (m, q, address2) => `${q}${swap(address2)}`);
1952
+ if (markdown) out = out.replace(MD_LINK, (m, a, address2, b) => `${a}${swap(address2)}${b}`);
1953
+ return out;
1954
+ });
1618
1955
  }
1956
+ var linkFileOf = (adapter) => adapter?.links ?? ((p) => APP_SOURCE.test(p) && !CONTENT_CONFIG.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
1619
1957
  function blankStrings(src) {
1620
1958
  let out = "";
1621
1959
  let i = 0;
@@ -1651,6 +1989,105 @@ function destination(page, to, discovered) {
1651
1989
  const newDir = `${base}${to === "/" ? "" : to}`;
1652
1990
  return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
1653
1991
  }
1992
+ function htmlDestination(page, to) {
1993
+ const folder = /(^|\/)index\.html?$/.test(page.file);
1994
+ const dir = folder ? dirname(page.file) : page.file;
1995
+ if (to.endsWith(".html") || to.endsWith(".htm")) {
1996
+ if (folder) return null;
1997
+ return { file: to.slice(1), dir, newDir: to.slice(1), folder: false };
1998
+ }
1999
+ return { file: `${to.slice(1)}/index.html`, dir, newDir: to.slice(1), folder };
2000
+ }
2001
+ var URL_ATTRIBUTE = /(\s(?:href|src|action|poster)\s*=\s*)(["'])([^"']*)\2/gi;
2002
+ var relativeUrl = (url) => !!url && !/^(?:[a-z][a-z0-9+.-]*:|\/|#|\?|\{|\$)/i.test(url);
2003
+ function resolvedUrl(dir, url) {
2004
+ const segments = dir ? dir.split("/") : [];
2005
+ for (const s of url.split("/")) {
2006
+ if (s === "..") segments.pop();
2007
+ else if (s && s !== ".") segments.push(s);
2008
+ }
2009
+ return segments.join("/");
2010
+ }
2011
+ function servedAddress(path, slash) {
2012
+ if (path === "" || path === "index.html" || path === "index.htm") return "/";
2013
+ if (/\/index\.html?$/.test(path)) return `/${path.replace(/\/index\.html?$/, "")}`;
2014
+ if (slash || /\.html?$/.test(path) || !/\.[a-z0-9]+$/i.test(path.split("/").pop() ?? "")) return `/${path}`;
2015
+ return null;
2016
+ }
2017
+ function relativeTo(dir, target) {
2018
+ const from = dir ? dir.split("/") : [];
2019
+ const folder = target === "" || target.endsWith("/");
2020
+ const parts = target.replace(/\/$/, "").split("/").filter(Boolean);
2021
+ const tdir = folder ? parts : parts.slice(0, -1);
2022
+ const base = folder ? "" : parts.at(-1) ?? "";
2023
+ let i = 0;
2024
+ while (i < from.length && i < tdir.length && from[i] === tdir[i]) i++;
2025
+ const rest = tdir.slice(i);
2026
+ const out = `${"../".repeat(from.length - i)}${rest.length ? `${rest.join("/")}/` : ""}${base}`;
2027
+ return out || "./";
2028
+ }
2029
+ function htmlRelinked(src, was, now, change, moved) {
2030
+ return src.replace(URL_ATTRIBUTE, (m, lead, q, url) => {
2031
+ if (!relativeUrl(url)) return m;
2032
+ const bare = url.replace(/[#?][\s\S]*$/, "");
2033
+ if (!bare) return m;
2034
+ const tail = url.slice(bare.length);
2035
+ const slash = bare.endsWith("/");
2036
+ const path = resolvedUrl(dirname(was), bare);
2037
+ let target = null;
2038
+ const address2 = servedAddress(path, slash);
2039
+ if (change && address2 !== null && (address2 === change.from || under(address2, change.from))) {
2040
+ const next2 = moveAddress(address2, change.from, change.to);
2041
+ const index = /(^|\/)index\.html?$/.test(path);
2042
+ if (next2.endsWith(".html") || next2.endsWith(".htm")) target = next2.slice(1);
2043
+ else if (index) target = next2 === "/" ? "index.html" : `${next2.slice(1)}/index.html`;
2044
+ else target = next2 === "/" ? "" : `${next2.slice(1)}/`;
2045
+ if (!slash && !index && !target.endsWith("/") && !/\.html?$/.test(target)) target = target.replace(/\/$/, "");
2046
+ } else if (moved?.has(path)) target = moved.get(path);
2047
+ else if (was === now) return m;
2048
+ else target = slash && path ? `${path}/` : path;
2049
+ const next = relativeTo(dirname(now), target);
2050
+ return next === bare ? m : `${lead}${q}${next}${tail}${q}`;
2051
+ });
2052
+ }
2053
+ function htmlStarter({ discovered, text, target, name, segments, files, fileTaken, no }) {
2054
+ const shellPage = discovered.pages.find((p) => p.path === "/") ?? discovered.pages.find((p) => p.file);
2055
+ const shell = shellPage ? text(shellPage.file) : null;
2056
+ if (!shell) return no("unparsed");
2057
+ const file = /\.html?$/.test(target) ? target.slice(1) : `${segments}/index.html`;
2058
+ if (fileTaken(file)) return no("taken", file);
2059
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2060
+ const h1 = mostClass(discovered.pages.map((p) => text(p.file) ?? ""), "h1", "class");
2061
+ const heading = `<h1${h1 ? ` class="${esc(h1)}"` : ""}>${esc(name)}</h1>`;
2062
+ let out = shell;
2063
+ out = /<title\b[^>]*>[\s\S]*?<\/title>/i.test(out) ? out.replace(/(<title\b[^>]*>)[\s\S]*?(<\/title>)/i, `$1${esc(name)}$2`) : out.replace(/(\s*)<\/head>/i, `$1 <title>${esc(name)}</title>$1</head>`);
2064
+ out = out.replace(/[ \t]*<meta\s[^>]*name\s*=\s*["']description["'][^>]*>[ \t]*\r?\n?/i, "");
2065
+ const indentAt = (i) => out.slice(out.lastIndexOf("\n", i - 1) + 1, i).match(/^[ \t]*/)?.[0] ?? "";
2066
+ const main = /(<main\b[^>]*>)([\s\S]*?)(<\/main>)/i.exec(out);
2067
+ if (main) {
2068
+ const indent = indentAt(main.index);
2069
+ out = `${out.slice(0, main.index)}${main[1]}
2070
+ ${indent} ${heading}
2071
+ ${indent}${main[3]}${out.slice(main.index + main[0].length)}`;
2072
+ } else {
2073
+ const body = /(<body\b[^>]*>)([\s\S]*?)(<\/body>)/i.exec(out);
2074
+ if (!body) return no("unparsed");
2075
+ const inner = body[2];
2076
+ const header = /<header\b[\s\S]*?<\/header>/i.exec(inner);
2077
+ const footer = /<footer\b[\s\S]*?<\/footer>/i.exec(inner);
2078
+ const indent = inner.match(/\n([ \t]*)\S/)?.[1] ?? " ";
2079
+ const start = header ? header.index + header[0].length : 0;
2080
+ const end = footer ? footer.index : inner.length;
2081
+ const scripts = [...inner.slice(start, end).matchAll(/<script\b[\s\S]*?<\/script>/gi)].map((m) => m[0]);
2082
+ const block = ["<main>", ` ${heading}`, "</main>", ...scripts].map((l) => `${indent}${l}`).join("\n");
2083
+ const head = header ? inner.slice(0, start) : "";
2084
+ const tail = footer ? `
2085
+ ${indent}${inner.slice(end)}` : inner.match(/\s*$/)?.[0] ?? "\n";
2086
+ out = `${out.slice(0, body.index)}${body[1]}${head}
2087
+ ${block}${tail}${body[3]}${out.slice(body.index + body[0].length)}`;
2088
+ }
2089
+ files.push({ path: file, content: htmlRelinked(out, shellPage.file, file, null, null) });
2090
+ }
1654
2091
  function appSegmentOwn(dir, paths) {
1655
2092
  return paths.filter((p) => {
1656
2093
  if (dirname(p) === dir) return true;
@@ -1661,6 +2098,16 @@ function appSegmentOwn(dir, paths) {
1661
2098
  }
1662
2099
  var componentName = (address2) => (lastOf(address2) || "Home").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("").replace(/^(\d)/, "Page$1") || "Page";
1663
2100
  function routePathAttr(src, router) {
2101
+ if (router.object) {
2102
+ const clean = stripComments(src);
2103
+ const entry = objectEntries(clean, router.start).find((e) => e.key === "path");
2104
+ if (!entry) return null;
2105
+ const raw = src.slice(entry.valueStart, entry.valueEnd);
2106
+ const value2 = literalString(raw);
2107
+ if (value2 === false) return null;
2108
+ const start = entry.valueStart + 1;
2109
+ return { value: value2, start, end: start + value2.length };
2110
+ }
1664
2111
  const tag = src.slice(router.start, router.end);
1665
2112
  const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
1666
2113
  if (!m) return null;
@@ -1668,25 +2115,51 @@ function routePathAttr(src, router) {
1668
2115
  const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
1669
2116
  return { value, start: valueAt, end: valueAt + value.length };
1670
2117
  }
2118
+ function routeCopy({ src, router, routerFile, attr, value, name, file, original }) {
2119
+ let tag = src.slice(router.start, attr.start) + value + src.slice(attr.end, router.end);
2120
+ let statement = null;
2121
+ let added = null;
2122
+ if (router.importKind === "inline") {
2123
+ tag = tag.replace(/(import\(\s*)(["'])([^"']+)\2/, (m, lead, q, spec) => `${lead}${q}${specFor(routerFile, file, spec, original)}${q}`);
2124
+ } else {
2125
+ const comp = router.component;
2126
+ statement = router.importKind === "lazy" ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape2(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m")) : src.match(new RegExp(`^.*import\\s+${escape2(comp)}\\b[^\\n]*$`, "m"));
2127
+ if (!statement) return { ok: false, reason: "unparsed", detail: "its import" };
2128
+ added = statement[0].replace(new RegExp(`(?<![\\w$])${escape2(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(routerFile, file, spec, original)}${q}`);
2129
+ tag = tag.replace(new RegExp(`(<|\\{\\s*|Component\\s*:\\s*)${escape2(comp)}(?![\\w$])`, "g"), `$1${name}`);
2130
+ }
2131
+ const indent = src.slice(src.lastIndexOf("\n", router.start) + 1, router.start).match(/^\s*/)?.[0] ?? "";
2132
+ let out = `${src.slice(0, router.end)}${router.object ? "," : ""}
2133
+ ${indent}${tag}${src.slice(router.end)}`;
2134
+ if (statement) {
2135
+ const lineEnd = statement.index + statement[0].length;
2136
+ out = `${out.slice(0, lineEnd)}
2137
+ ${added}${out.slice(lineEnd)}`;
2138
+ }
2139
+ return { ok: true, code: out };
2140
+ }
1671
2141
  function planPage(request, input) {
1672
2142
  const { framework, text } = input;
2143
+ const adapter = adapterOf(framework);
1673
2144
  const paths = input.paths.filter((p) => !SKIP2.test(p));
1674
- const no = (reason, detail) => ({ ok: (
2145
+ const no = (reason, detail2) => ({ ok: (
1675
2146
  /** @type {const} */
1676
2147
  false
1677
- ), reason, ...detail ? { detail } : {} });
2148
+ ), reason, ...detail2 ? { detail: detail2 } : {} });
1678
2149
  const action = request.action;
1679
- if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
1680
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
2150
+ if (!["rename", "duplicate", "delete", "create"].includes(action)) return no("invalid", action);
2151
+ if (!adapter?.acts) return no("framework");
1681
2152
  const at3 = normalisePath(request.path);
1682
2153
  const discovered = input.found ?? discover({ framework, paths, text });
2154
+ if (action === "create") return planCreate(request, { framework, paths, text, discovered });
1683
2155
  const page = discovered.pages.find((p) => p.path === at3);
1684
- if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at3))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
2156
+ if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at3))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers, host: input.host ?? null });
1685
2157
  if (!page) {
1686
2158
  const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at3));
1687
2159
  return template ? no("template", template.path) : no("missing");
1688
2160
  }
1689
- if (page.kind === "template") return no("template", page.path);
2161
+ const detail = page.kind === "template" && action === "delete" && !adapter?.routeLines ? input.details?.[at3] ?? null : null;
2162
+ if (page.kind === "template" && !detail) return no("template", page.path);
1690
2163
  if (!page.file || page.reason === "unparsed") return no("unparsed");
1691
2164
  const pageFile = parsePageFile(text(PAGE_FILE));
1692
2165
  if (!pageFile.ok) return no("invalid", pageFile.error);
@@ -1694,7 +2167,19 @@ function planPage(request, input) {
1694
2167
  const have = new Set(paths);
1695
2168
  const importers = input.importers ?? importGraph(paths, text);
1696
2169
  const live = request.live === true;
1697
- const redirects = live ? kitRedirects({ framework, text }) : false;
2170
+ const mode = redirectMode({ framework, text, host: input.host ?? null, found: discovered });
2171
+ const redirects = live ? mode !== null : false;
2172
+ const sendKey = mode === "host" ? "hosted" : "redirects";
2173
+ const cannotMove = () => no(noRedirects({ framework, objects: discovered.pages.some((p) => p.router?.object) }), page.router?.object ? "route objects" : void 0);
2174
+ const writePageFile = (content) => {
2175
+ if (content === null) return null;
2176
+ write({ path: PAGE_FILE, content });
2177
+ if (sendKey !== "hosted") return null;
2178
+ const mirror = hostedWrite(text, text(PAGE_FILE), content);
2179
+ if (mirror && "error" in mirror) return no("invalid", mirror.error);
2180
+ if (mirror) write(mirror);
2181
+ return null;
2182
+ };
1698
2183
  const ownRedirects = siteRedirects({ framework, text });
1699
2184
  const taken = (p) => discovered.pages.some((q) => q.path === p) || [...ownRedirects].some((s) => sends(s, p));
1700
2185
  const writes = /* @__PURE__ */ new Map();
@@ -1720,11 +2205,11 @@ function planPage(request, input) {
1720
2205
  if (!validAddress(target) || target === "/") return no("address", target);
1721
2206
  if (target !== at3 && within2(target, at3)) return no("address", target);
1722
2207
  if (target !== at3 && taken(target)) return no("taken", target);
1723
- if (target !== at3 && live && !redirects) return no("no_redirects");
2208
+ if (target !== at3 && live && !redirects) return cannotMove();
1724
2209
  to = target;
1725
2210
  const moved = /* @__PURE__ */ new Map();
1726
2211
  if (target !== at3) {
1727
- if (framework === "vite-react") {
2212
+ if (adapter?.routeLines) {
1728
2213
  const src = text(page.router.file) ?? "";
1729
2214
  const attr = routePathAttr(src, page.router);
1730
2215
  if (!attr) return no("unparsed", "index route");
@@ -1735,7 +2220,7 @@ function planPage(request, input) {
1735
2220
  write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
1736
2221
  }
1737
2222
  } else {
1738
- const dest = destination(page, target, discovered);
2223
+ const dest = (adapter?.destination ?? destination)(page, target, discovered);
1739
2224
  if (!dest) return no("unparsed");
1740
2225
  for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
1741
2226
  moved.set(page.file, dest.file);
@@ -1754,12 +2239,14 @@ function planPage(request, input) {
1754
2239
  if (out !== src) write({ path: p, content: out });
1755
2240
  }
1756
2241
  }
2242
+ const linkFile = linkFileOf(adapter);
1757
2243
  for (const p of paths) {
1758
- if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
2244
+ if (!linkFile(p)) continue;
1759
2245
  const where = moved.get(p) ?? p;
1760
2246
  const src = current(where);
1761
2247
  if (!src) continue;
1762
- const out = relinked(src, at3, target, /\.mdx?$/.test(p));
2248
+ let out = relinked(src, at3, target, p);
2249
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at3, to: target }, moved);
1763
2250
  if (out === src) continue;
1764
2251
  write({ path: where, content: out });
1765
2252
  if (!moved.has(p)) links.add(where);
@@ -1788,12 +2275,13 @@ function planPage(request, input) {
1788
2275
  else delete entry.name;
1789
2276
  pages[target] = entry;
1790
2277
  }
1791
- });
1792
- if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
2278
+ }, sendKey);
2279
+ const refused = writePageFile(pageFileText);
2280
+ if (refused) return refused;
1793
2281
  if (!writes.size) return no("same");
1794
2282
  }
1795
2283
  if (action === "duplicate") {
1796
- if (framework === "vite-react" && page.reason === "nested") return no("nested");
2284
+ if (adapter?.routeLines && page.reason === "nested") return no("nested");
1797
2285
  let target;
1798
2286
  if (request.to != null) {
1799
2287
  target = normalisePath(request.to);
@@ -1851,8 +2339,8 @@ function planPage(request, input) {
1851
2339
  const rebind = (src) => {
1852
2340
  let out = src;
1853
2341
  for (const r of rebinds) {
1854
- if (r.kind === "entry") out = out.replace(new RegExp(`(\\bgetEntry\\(\\s*["']${escape(r.collection)}["']\\s*,\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1855
- else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads2.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
2342
+ if (r.kind === "entry") out = out.replace(new RegExp(`(\\bgetEntry\\(\\s*["']${escape2(r.collection)}["']\\s*,\\s*)(["'])${escape2(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
2343
+ else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads2.byName].map(escape2).join("|")})\\(\\s*)(["'])${escape2(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1856
2344
  }
1857
2345
  for (const [f, next] of copies) {
1858
2346
  if (!imported.has(f)) continue;
@@ -1860,7 +2348,7 @@ function planPage(request, input) {
1860
2348
  }
1861
2349
  return out;
1862
2350
  };
1863
- if (framework === "vite-react") {
2351
+ if (adapter?.routeLines) {
1864
2352
  const router = page.router.file;
1865
2353
  const src = current(router) ?? "";
1866
2354
  const attr = routePathAttr(src, page.router);
@@ -1871,28 +2359,18 @@ function planPage(request, input) {
1871
2359
  const file = freeFile(dirname(page.file), name, ext);
1872
2360
  const original = text(page.file) ?? "";
1873
2361
  write({ path: file, content: rebind(respecified(original, page.file, file, /* @__PURE__ */ new Map([[page.file, file]]), have)) });
1874
- const comp = page.router.component;
1875
- const statement = page.router.importKind === "lazy" ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m")) : src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
1876
- if (!statement) return no("unparsed", "its import");
1877
- const added = statement[0].replace(new RegExp(`(?<![\\w$])${escape(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(router, file, spec, page.file)}${q}`);
1878
2362
  const value = attr.value.startsWith("/") ? target : (() => {
1879
2363
  const parent = normalisePath(at3.slice(0, at3.length - normalisePath(attr.value).length));
1880
2364
  return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
1881
2365
  })();
1882
2366
  if (value === null) return no("unparsed", "a route inside another route keeps its parent");
1883
- const newTag = (src.slice(page.router.start, attr.start) + value + src.slice(attr.end, page.router.end)).replace(new RegExp(`(<|\\{\\s*)${escape(comp)}(?![\\w$])`, "g"), `$1${name}`);
1884
- const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
1885
- const at1 = page.router.end;
1886
- let out = `${src.slice(0, at1)}
1887
- ${indent}${newTag}${src.slice(at1)}`;
1888
- const lineEnd = statement.index + statement[0].length;
1889
- out = `${out.slice(0, lineEnd)}
1890
- ${added}${out.slice(lineEnd)}`;
1891
- write({ path: router, content: out });
2367
+ const added = routeCopy({ src, router: page.router, routerFile: router, attr, value, name, file, original: page.file });
2368
+ if (!added.ok) return added;
2369
+ write({ path: router, content: added.code });
1892
2370
  } else {
1893
- const dest = destination(page, target, discovered);
2371
+ const dest = (adapter?.destination ?? destination)(page, target, discovered);
1894
2372
  if (!dest) return no("unparsed");
1895
- const along = framework === "next" && routesBase(page.file).endsWith("app") && at3 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
2373
+ const along = adapter?.segments && routesBase(page.file).endsWith("app") && at3 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
1896
2374
  const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
1897
2375
  for (const next of moved.values()) if (have.has(next)) return no("taken", next);
1898
2376
  for (const [from, next] of moved) {
@@ -1903,6 +2381,7 @@ ${added}${out.slice(lineEnd)}`;
1903
2381
  }
1904
2382
  let out = respecified(src, from, next, moved, have);
1905
2383
  if (from === page.file) out = rebind(out);
2384
+ if (adapter?.relativeLinks && /\.html?$/.test(from)) out = htmlRelinked(out, from, next, null, moved);
1906
2385
  write(out === src ? { path: next, from } : { path: next, content: out });
1907
2386
  }
1908
2387
  }
@@ -1914,7 +2393,7 @@ ${added}${out.slice(lineEnd)}`;
1914
2393
  if (!reads2.isRoute(f)) continue;
1915
2394
  const src = text(f) ?? "";
1916
2395
  const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
1917
- write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at3)}(")`), `$1${target}$2`) });
2396
+ write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape2(at3)}(")`), `$1${target}$2`) });
1918
2397
  if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1919
2398
  }
1920
2399
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
@@ -1926,22 +2405,23 @@ ${added}${out.slice(lineEnd)}`;
1926
2405
  if (action === "delete") {
1927
2406
  if (at3 === "/") return no("home");
1928
2407
  if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
2408
+ const gone = detail ? [...new Set((request.addresses ?? []).map(normalisePath))].filter((p) => templateMatches(at3, p)).sort() : [at3];
1929
2409
  let target = null;
1930
- if (live && request.redirect !== null) {
2410
+ if (live && gone.length && request.redirect !== null) {
1931
2411
  if (request.redirect !== void 0) {
1932
2412
  target = normalisePath(request.redirect);
1933
- if (within2(target, at3) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
2413
+ if (within2(target, at3) || gone.includes(target) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1934
2414
  } else {
1935
2415
  for (let p = parentOf(at3); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
1936
2416
  target = target ?? "/";
1937
2417
  }
1938
- if (!redirects) return no("no_redirects");
2418
+ if (!redirects) return cannotMove();
1939
2419
  }
1940
2420
  to = target;
1941
- if (framework === "vite-react") {
2421
+ if (adapter?.routeLines) {
1942
2422
  const router = page.router.file;
1943
2423
  const src = current(router) ?? "";
1944
- let { start, end } = page.router;
2424
+ let { start, end } = routeSpan(src, page.router);
1945
2425
  const lineStart = src.lastIndexOf("\n", start - 1) + 1;
1946
2426
  const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
1947
2427
  if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
@@ -1950,34 +2430,46 @@ ${added}${out.slice(lineEnd)}`;
1950
2430
  }
1951
2431
  let out = src.slice(0, start) + src.slice(end);
1952
2432
  const comp = page.router.component;
1953
- const rest = blankStrings(stripComments(out));
1954
- const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
1955
- if (uses <= 1) {
1956
- const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
1957
- out = out.replace(re, "");
2433
+ if (page.router.importKind === "inline") {
1958
2434
  if ([...importers.get(page.file) ?? []].every((f) => f === router)) write({ path: page.file, deleted: true });
2435
+ } else {
2436
+ const rest = blankStrings(stripComments(out));
2437
+ const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape2(comp)}(?![\\w$])`, "g"))].length;
2438
+ if (uses <= 1) {
2439
+ const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape2(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape2(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
2440
+ out = out.replace(re, "");
2441
+ if ([...importers.get(page.file) ?? []].every((f) => f === router)) write({ path: page.file, deleted: true });
2442
+ }
1959
2443
  }
1960
2444
  write({ path: router, content: out });
1961
2445
  } else {
1962
2446
  const dir = dirname(page.file);
1963
- const files2 = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
2447
+ const files2 = adapter?.segments && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
1964
2448
  for (const f of files2) write({ path: f, deleted: true });
1965
2449
  }
2450
+ const keep = new Set(detail?.keep ?? []);
1966
2451
  const content = ownedContent(page, { paths, text, importers });
1967
- for (const f of content.files) {
2452
+ const owned = content.files.filter((f) => !keep.has(f));
2453
+ for (const f of owned) {
1968
2454
  write({ path: f, deleted: true });
1969
2455
  if (collectionsAfter) delete collectionsAfter[f];
1970
2456
  }
1971
- for (const f of linksTo(at3, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
2457
+ for (const f of linksTo(at3, { paths, text, own: [page.file, ...owned], framework })) unlinked.add(f);
2458
+ const was = (d) => d === at3 || !!detail && templateMatches(at3, d);
1972
2459
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1973
- delete pages[at3];
2460
+ for (const key of Object.keys(pages)) if (was(key)) delete pages[key];
1974
2461
  const before = { ...sendsOn };
1975
- if (target) sendsOn[at3] = target;
1976
- if (target) repoint(sendsOn, at3, target);
1977
- else for (const [s, d] of Object.entries(sendsOn)) if (d === at3) delete sendsOn[s];
2462
+ if (target) {
2463
+ for (const p of gone) sendsOn[p] = target;
2464
+ for (const p of gone) repoint(sendsOn, p, target);
2465
+ if (detail) {
2466
+ for (const [s, d] of Object.entries(sendsOn)) if (was(d)) s === target ? delete sendsOn[s] : sendsOn[s] = target;
2467
+ }
2468
+ } else for (const [s, d] of Object.entries(sendsOn)) if (was(d)) delete sendsOn[s];
1978
2469
  for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1979
- });
1980
- if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
2470
+ }, sendKey);
2471
+ const refused = writePageFile(pageFileText);
2472
+ if (refused) return refused;
1981
2473
  }
1982
2474
  if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
1983
2475
  const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
@@ -1990,6 +2482,267 @@ ${added}${out.slice(lineEnd)}`;
1990
2482
  const message = action === "rename" ? to === at3 ? `Unbase: rename ${at3}` : `Unbase: move ${at3} to ${to}` : action === "duplicate" ? `Unbase: duplicate ${at3} as ${to}` : `Unbase: delete ${at3}${to ? ` (visitors go to ${to})` : ""}`;
1991
2483
  return { ok: true, action, path: at3, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
1992
2484
  }
2485
+ function mostClass(sources, tag, attr, keep = () => true) {
2486
+ const count = /* @__PURE__ */ new Map();
2487
+ for (const src of sources) {
2488
+ for (const m of src.matchAll(new RegExp(`<${tag}\\b[^>]*\\s${attr}="([^"{]+)"`, "g"))) {
2489
+ const c = m[1].trim();
2490
+ if (c && keep(c)) count.set(c, (count.get(c) ?? 0) + 1);
2491
+ }
2492
+ }
2493
+ return [...count].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0]?.[0] ?? null;
2494
+ }
2495
+ var holdsWidth = (c) => /(^|\s)(container|wrap|wrapper|inner|max-w-\S+|mx-auto)(\s|$)/.test(c);
2496
+ var literal = (s) => JSON.stringify(String(s));
2497
+ function siblingRoutes(discovered, text) {
2498
+ return discovered.pages.filter((p) => {
2499
+ if (p.kind !== "route" || p.reason || !p.router || !p.file) return false;
2500
+ const attr = routePathAttr(text(p.router.file) ?? "", p.router);
2501
+ return !!attr && attr.value !== "*" && !attr.value.endsWith("/*");
2502
+ });
2503
+ }
2504
+ function createCapability({ framework, paths, text, found }) {
2505
+ const no = (reason, detail) => ({ ok: (
2506
+ /** @type {const} */
2507
+ false
2508
+ ), reason, ...detail ? { detail } : {} });
2509
+ const adapter = adapterOf(framework);
2510
+ if (!adapter?.acts) return no("framework");
2511
+ const pageFile = parsePageFile(text(PAGE_FILE));
2512
+ if (!pageFile.ok) return no("invalid", pageFile.error);
2513
+ const kept = paths.filter((p) => !SKIP2.test(p));
2514
+ const discovered = found ?? discover({ framework, paths: kept, text });
2515
+ return adapter.canCreate?.(discovered, kept, text) ?? { ok: true };
2516
+ }
2517
+ function wrapOfPage(src) {
2518
+ const imports = [...src.matchAll(/^import\s+(?:([A-Za-z_$][\w$]*)\s*(?:,\s*\{([^}]*)\})?|\{([^}]*)\})\s+from\s+["']([^"']+)["'];?[^\n]*$/gm)].map((m) => ({
2519
+ line: m[0],
2520
+ names: [m[1], ...(m[2] ?? m[3] ?? "").split(",").map((x) => x.trim().split(/\s+as\s+/).pop())].filter(Boolean)
2521
+ }));
2522
+ const used = (n) => new RegExp(`<${escape2(n)}[\\s/>]`).test(src);
2523
+ const names = imports.flatMap((i) => i.names);
2524
+ const lineOf = (n) => imports.find((i) => i.names.includes(n))?.line;
2525
+ const layout = names.find((n) => /Layout$/.test(n) && used(n)) ?? null;
2526
+ if (layout) return { key: `layout:${lineOf(layout)}`, layout, header: null, footer: null, outer: null, imports: [lineOf(layout)] };
2527
+ const header = names.find((n) => /^(Header|Navbar|NavBar|Nav|Navigation|SiteHeader)$/.test(n) && used(n)) ?? null;
2528
+ const footer = names.find((n) => /^(Footer|SiteFooter)$/.test(n) && used(n)) ?? null;
2529
+ if (!header && !footer) return { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
2530
+ const outer = src.match(/return\s*\(\s*<([a-z][\w-]*)((?:\s+className="[^"]*")?)\s*>/);
2531
+ const imports2 = [...new Set([header, footer].filter(Boolean).map(lineOf))];
2532
+ const outerTag = outer ? `${outer[1]}${outer[2]}` : null;
2533
+ return { key: `chrome:${imports2.join("|")}:${outerTag}`, layout: null, header, footer, outer: outerTag, imports: imports2 };
2534
+ }
2535
+ function wrapOfPages(sources) {
2536
+ const seen = /* @__PURE__ */ new Map();
2537
+ for (const src of sources) {
2538
+ const w = wrapOfPage(src);
2539
+ const had = seen.get(w.key) ?? { n: 0, w };
2540
+ had.n++;
2541
+ seen.set(w.key, had);
2542
+ }
2543
+ const best = [...seen.values()].sort((a, b) => b.n - a.n || (a.w.key === "none" ? 1 : b.w.key === "none" ? -1 : 0))[0];
2544
+ return best?.w ?? { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
2545
+ }
2546
+ function astroStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2547
+ const own = discovered.pages.filter((p) => p.file && p.file.startsWith("src/pages/") && p.file.endsWith(".astro"));
2548
+ const sources = own.map((p) => text(p.file) ?? "");
2549
+ const layouts = /* @__PURE__ */ new Map();
2550
+ own.forEach((p, i) => {
2551
+ for (const m of sources[i].matchAll(/import\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']*layouts?\/[^"']+\.astro)["']/g)) {
2552
+ const spec = m[2];
2553
+ const abs = spec.startsWith(".") ? joinRelative(dirname(p.file), spec) : spec.replace(/^[@~]\//, "src/").replace(/^@layouts\//, "src/layouts/");
2554
+ const seen = layouts.get(abs) ?? { n: 0, local: m[1], alias: spec.startsWith(".") ? null : spec };
2555
+ seen.n++;
2556
+ layouts.set(abs, seen);
2557
+ }
2558
+ });
2559
+ const best = [...layouts].sort((a, b) => b[1].n - a[1].n || (a[0] < b[0] ? -1 : 1))[0];
2560
+ const file = paths.some((p) => p.startsWith(`src/pages/${segments}/`)) ? `src/pages/${segments}/index.astro` : `src/pages/${segments}.astro`;
2561
+ if (fileTaken(file)) return no("taken", file);
2562
+ const h1 = mostClass(sources, "h1", "class");
2563
+ const box = mostClass(sources, "(?:main|section|div)", "class", holdsWidth);
2564
+ const heading = `<h1${h1 ? ` class=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2565
+ const body = [`<main${box ? ` class=${literal(box)}` : ""}>`, ` ${heading}`, "</main>"];
2566
+ let src;
2567
+ if (best) {
2568
+ const [abs, use] = best;
2569
+ const layoutSrc = text(abs) ?? "";
2570
+ const tag = /^[A-Z]/.test(use.local) ? use.local : "Layout";
2571
+ const spec = use.alias ?? relativeSpec(file, abs);
2572
+ const metadata = /\bmetadata\b/.test(layoutSrc) && !/\btitle\s*[?:]/.test(layoutSrc);
2573
+ const props = metadata ? " metadata={metadata}" : /\btitle\b/.test(layoutSrc) ? ` title={${literal(name)}}` : "";
2574
+ const front = [`import ${tag} from ${literal(spec)};`, ...metadata ? [`const metadata = { title: ${literal(name)} };`] : []];
2575
+ src = ["---", ...front, "---", "", `<${tag}${props}>`, ...body.map((l) => ` ${l}`), `</${tag}>`, ""].join("\n");
2576
+ } else {
2577
+ src = [
2578
+ "---",
2579
+ `const title = ${literal(name)};`,
2580
+ "---",
2581
+ "",
2582
+ `<html lang="en">`,
2583
+ " <head>",
2584
+ ` <meta charset="utf-8" />`,
2585
+ ` <meta name="viewport" content="width=device-width" />`,
2586
+ " <title>{title}</title>",
2587
+ " </head>",
2588
+ " <body>",
2589
+ ...body.map((l) => ` ${l}`),
2590
+ " </body>",
2591
+ "</html>",
2592
+ ""
2593
+ ].join("\n");
2594
+ }
2595
+ files.push({ path: file, content: src });
2596
+ }
2597
+ function nextStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2598
+ const own = discovered.pages.filter((p) => p.file && routesBase(p.file));
2599
+ const sources = own.map((p) => text(p.file) ?? "");
2600
+ const inApp = own.find((p) => routesBase(p.file).endsWith("app"));
2601
+ const inPages = own.find((p) => !routesBase(p.file).endsWith("app"));
2602
+ const appBase = inApp ? routesBase(inApp.file) : paths.some((p) => /^src\/app\/layout\./.test(p)) ? "src/app" : paths.some((p) => /^app\/layout\./.test(p)) ? "app" : null;
2603
+ const pagesBase = inPages ? routesBase(inPages.file) : null;
2604
+ const exts = own.map((p) => p.file.slice(p.file.lastIndexOf("."))).filter((e) => /^\.(tsx|jsx|js)$/.test(e));
2605
+ const ext = exts.includes(".tsx") || !exts.length ? ".tsx" : exts.includes(".jsx") ? ".jsx" : ".js";
2606
+ const typed = ext === ".tsx";
2607
+ const h1 = mostClass(sources, "h1", "className");
2608
+ const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
2609
+ const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2610
+ if (appBase) {
2611
+ const file = `${appBase}/${segments}/page${ext}`;
2612
+ if (fileTaken(file)) return no("taken", file);
2613
+ const lines = [
2614
+ ...typed ? [`import type { Metadata } from "next";`, ""] : [],
2615
+ `export const metadata${typed ? ": Metadata" : ""} = { title: ${literal(name)} };`,
2616
+ "",
2617
+ "export default function Page() {",
2618
+ " return (",
2619
+ ` <main${box ? ` className=${literal(box)}` : ""}>`,
2620
+ ` ${heading}`,
2621
+ " </main>",
2622
+ " );",
2623
+ "}",
2624
+ ""
2625
+ ];
2626
+ files.push({ path: file, content: lines.join("\n") });
2627
+ } else if (pagesBase) {
2628
+ const file = paths.some((p) => p.startsWith(`${pagesBase}/${segments}/`)) ? `${pagesBase}/${segments}/index${ext}` : `${pagesBase}/${segments}${ext}`;
2629
+ if (fileTaken(file)) return no("taken", file);
2630
+ const lines = [
2631
+ `import Head from "next/head";`,
2632
+ "",
2633
+ "export default function Page() {",
2634
+ " return (",
2635
+ " <>",
2636
+ " <Head>",
2637
+ ` <title>{${literal(name)}}</title>`,
2638
+ " </Head>",
2639
+ ` <main${box ? ` className=${literal(box)}` : ""}>`,
2640
+ ` ${heading}`,
2641
+ " </main>",
2642
+ " </>",
2643
+ " );",
2644
+ "}",
2645
+ ""
2646
+ ];
2647
+ files.push({ path: file, content: lines.join("\n") });
2648
+ } else return no("unparsed");
2649
+ }
2650
+ function reactRouterStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2651
+ const siblings = siblingRoutes(discovered, text);
2652
+ const parent = parentOf(target);
2653
+ const placement = (p) => {
2654
+ const src2 = text(p.router.file) ?? "";
2655
+ const attr2 = routePathAttr(src2, p.router);
2656
+ if (!attr2) return null;
2657
+ if (attr2.value.startsWith("/")) return { src: src2, attr: attr2, value: target };
2658
+ const base = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr2.value).length));
2659
+ if (base !== "/" && !under(target, base)) return null;
2660
+ return { src: src2, attr: attr2, value: base === "/" ? target.slice(1) : target.slice(base.length + 1) };
2661
+ };
2662
+ const ranked = [...siblings.filter((p) => parentOf(p.path) === parent), ...siblings.filter((p) => parentOf(p.path) === "/"), ...siblings];
2663
+ const sibling = ranked.find((p) => placement(p));
2664
+ if (!sibling) return no("routes_unread");
2665
+ const { src, attr, value } = placement(sibling);
2666
+ const router = sibling.router.file;
2667
+ let comp = componentName(target);
2668
+ for (let n = 2; new RegExp(`(?<![\\w$])${comp}(?![\\w$])`).test(src) && n < 100; n++) comp = `${componentName(target)}${n}`;
2669
+ const ext = sibling.file.slice(sibling.file.lastIndexOf("."));
2670
+ let file = `${dirname(sibling.file)}/${comp}${ext}`;
2671
+ for (let n = 2; fileTaken(file) && n < 100; n++) file = `${dirname(sibling.file)}/${comp}${n}${ext}`;
2672
+ const wrap = wrapOfPages(siblings.filter((p) => dirname(p.file) === dirname(sibling.file)).map((p) => text(p.file) ?? ""));
2673
+ const sources = siblings.map((p) => text(p.file) ?? "");
2674
+ const h1 = mostClass(sources, "h1", "className");
2675
+ const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
2676
+ const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2677
+ const main = (indent) => [`${indent}<main${box ? ` className=${literal(box)}` : ""}>`, `${indent} ${heading}`, `${indent}</main>`];
2678
+ let jsx;
2679
+ const wrapImports = wrap.imports;
2680
+ if (wrap.layout) jsx = [` <${wrap.layout}>`, ...main(" "), ` </${wrap.layout}>`];
2681
+ else if (wrap.header || wrap.footer) {
2682
+ const open = wrap.outer ? `<${wrap.outer}>` : "<>";
2683
+ const close = wrap.outer ? `</${wrap.outer.split(/\s/)[0]}>` : "</>";
2684
+ jsx = [` ${open}`, ...wrap.header ? [` <${wrap.header} />`] : [], ...main(" "), ...wrap.footer ? [` <${wrap.footer} />`] : [], ` ${close}`];
2685
+ } else jsx = main(" ");
2686
+ const page = [...wrapImports, ...wrapImports.length ? [""] : [], `export default function ${comp}() {`, " return (", ...jsx, " );", "}", ""].join("\n");
2687
+ files.push({ path: file, content: page });
2688
+ const added = routeCopy({ src, router: sibling.router, routerFile: router, attr, value, name: comp, file, original: sibling.file });
2689
+ if (!added.ok) return added;
2690
+ files.push({ path: router, content: added.code });
2691
+ }
2692
+ function planCreate(request, { framework, paths, text, discovered }) {
2693
+ const no = (reason, detail) => ({ ok: (
2694
+ /** @type {const} */
2695
+ false
2696
+ ), reason, ...detail ? { detail } : {} });
2697
+ const target = normalisePath(request.path);
2698
+ const name = String(request.name ?? "").trim().slice(0, 120) || componentName(target);
2699
+ if (target === "/" || !validAddress(target)) return no("address", target);
2700
+ const capability = createCapability({ framework, paths, text, found: discovered });
2701
+ if (!capability.ok) return capability;
2702
+ const pageFile = parsePageFile(text(PAGE_FILE));
2703
+ const ownRedirects = siteRedirects({ framework, text });
2704
+ if (discovered.pages.some((q) => q.path === target) || [...ownRedirects].some((s) => sends(s, target))) return no("taken", target);
2705
+ const have = new Set(paths);
2706
+ const files = [];
2707
+ const fileTaken = (f) => have.has(f) || files.some((w) => w.path === f);
2708
+ const segments = target.slice(1);
2709
+ const refused = adapterOf(framework)?.starter?.({ discovered, text, paths, target, name, segments, files, fileTaken, no });
2710
+ if (refused) return refused;
2711
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
2712
+ pages[target] = { ...pages[target] ?? {}, ...request.drafts ? { draft: true } : {}, name };
2713
+ });
2714
+ if (pageFileText !== null && pageFile.ok) files.push({ path: PAGE_FILE, content: pageFileText });
2715
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
2716
+ return { ok: true, action: "create", path: target, to: target, files, redirects: {}, links: [], unlinked: [], moves: [], renamed: [], message: `Unbase: new page ${target}` };
2717
+ }
2718
+ var PAGE_OPERATIONS = ["create_page", "rename", "move", "duplicate", "delete", "rename_folder", "reorder", "set_page", "set_site"];
2719
+ function createdAddress(op) {
2720
+ const slug = slugOf(op?.slug ?? op?.name ?? "");
2721
+ if (!slug) return null;
2722
+ const parent = op.parent ? normalisePath(op.parent) : "/";
2723
+ return normalisePath(`${parent === "/" ? "" : parent}/${slug}`);
2724
+ }
2725
+ function requestOf(op) {
2726
+ if (!op || typeof op !== "object") return null;
2727
+ switch (op.op) {
2728
+ case "create_page": {
2729
+ const path = createdAddress(op);
2730
+ return path ? { action: "create", path, name: op.name } : null;
2731
+ }
2732
+ case "rename":
2733
+ return { action: "rename", path: op.path, name: op.name };
2734
+ case "move":
2735
+ return { action: "rename", path: op.path, to: op.to };
2736
+ case "rename_folder":
2737
+ return { action: "rename", path: op.path, ...op.to !== void 0 ? { to: op.to } : {}, ...op.name !== void 0 ? { name: op.name } : {} };
2738
+ case "duplicate":
2739
+ return { action: "duplicate", path: op.path, ...op.to !== void 0 ? { to: op.to } : {}, ...op.name !== void 0 ? { name: op.name } : {} };
2740
+ case "delete":
2741
+ return { action: "delete", path: op.path, ...op.redirect !== void 0 ? { redirect: op.redirect } : {} };
2742
+ default:
2743
+ return null;
2744
+ }
2745
+ }
1993
2746
  function folderPaths(pages) {
1994
2747
  const own = new Set(pages.map((p) => p.path));
1995
2748
  const out = /* @__PURE__ */ new Set();
@@ -2021,7 +2774,8 @@ function folderDirs(at3, below) {
2021
2774
  }
2022
2775
  return dirs.size ? [...dirs].sort() : null;
2023
2776
  }
2024
- function planFolder(request, { framework, paths, text, discovered, importers: given }) {
2777
+ function planFolder(request, { framework, paths, text, discovered, importers: given, host = null }) {
2778
+ const adapter = adapterOf(framework);
2025
2779
  const no = (reason, detail) => ({ ok: (
2026
2780
  /** @type {const} */
2027
2781
  false
@@ -2037,7 +2791,9 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2037
2791
  const ownRedirects = siteRedirects({ framework, text });
2038
2792
  if (target !== at3 && (discovered.pages.some((p) => within2(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
2039
2793
  const live = request.live === true;
2040
- if (target !== at3 && live && !kitRedirects({ framework, text })) return no("no_redirects");
2794
+ const mode = redirectMode({ framework, text, host, found: discovered });
2795
+ const sendKey = mode === "host" ? "hosted" : "redirects";
2796
+ if (target !== at3 && live && mode === null) return no(noRedirects({ framework, objects: below.some((p) => p.router?.object) }));
2041
2797
  const have = new Set(paths);
2042
2798
  const writes = /* @__PURE__ */ new Map();
2043
2799
  const write = (w) => writes.set(w.path, w);
@@ -2046,7 +2802,7 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2046
2802
  const moved = /* @__PURE__ */ new Map();
2047
2803
  const redirectChanges = {};
2048
2804
  if (target !== at3) {
2049
- if (framework === "vite-react") {
2805
+ if (adapter?.routeLines) {
2050
2806
  const edits = /* @__PURE__ */ new Map();
2051
2807
  for (const p of below) {
2052
2808
  if (!p.router) return no("unparsed", p.path);
@@ -2069,10 +2825,10 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2069
2825
  write({ path: file, content: out });
2070
2826
  }
2071
2827
  } else {
2072
- const dirs = folderDirs(at3, below);
2828
+ const dirs = (adapter?.folderDirs ?? folderDirs)(at3, below);
2073
2829
  if (!dirs) return no("unparsed", at3);
2074
2830
  for (const dir of dirs) {
2075
- const newDir = `${dirname(dir)}/${lastOf(target)}`;
2831
+ const newDir = dirname(dir) ? `${dirname(dir)}/${lastOf(target)}` : lastOf(target);
2076
2832
  for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
2077
2833
  }
2078
2834
  for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
@@ -2092,12 +2848,14 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2092
2848
  if (out !== src) write({ path: p, content: out });
2093
2849
  }
2094
2850
  }
2851
+ const linkFile = linkFileOf(adapter);
2095
2852
  for (const p of paths) {
2096
- if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
2853
+ if (!linkFile(p)) continue;
2097
2854
  const where = moved.get(p) ?? p;
2098
2855
  const src = current(where);
2099
2856
  if (!src) continue;
2100
- const out = relinked(src, at3, target, /\.mdx?$/.test(p));
2857
+ let out = relinked(src, at3, target, p);
2858
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at3, to: target }, moved);
2101
2859
  if (out === src) continue;
2102
2860
  write({ path: where, content: out });
2103
2861
  if (!moved.has(p)) links.add(where);
@@ -2125,8 +2883,13 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2125
2883
  if (name) folders[target] = { name };
2126
2884
  else delete folders[target];
2127
2885
  }
2128
- });
2129
- if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
2886
+ }, sendKey);
2887
+ if (pageFileText !== null) {
2888
+ write({ path: PAGE_FILE, content: pageFileText });
2889
+ const mirror = sendKey === "hosted" ? hostedWrite(text, text(PAGE_FILE), pageFileText) : null;
2890
+ if (mirror && "error" in mirror) return no("invalid", mirror.error);
2891
+ if (mirror) write(mirror);
2892
+ }
2130
2893
  if (!writes.size) return no("same");
2131
2894
  const files = [...writes.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
2132
2895
  const moves = target === at3 ? [] : [{ from: at3, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at3, target) }))];
@@ -2134,12 +2897,14 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2134
2897
  const message = target === at3 ? `Unbase: rename ${at3}` : `Unbase: move ${at3} to ${target}`;
2135
2898
  return { ok: true, action: "rename", path: at3, to: target, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [], moves, renamed, message, folder: true };
2136
2899
  }
2137
- function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers }) {
2900
+ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers, details = {}, host = null }) {
2901
+ const adapter = adapterOf(framework);
2138
2902
  const kept = paths.filter((p) => !SKIP2.test(p));
2139
2903
  const discovered = found ?? discover({ framework, paths: kept, text });
2140
2904
  const graph = importers ?? importGraph(kept, text);
2141
2905
  const pageFile = parsePageFile(text(PAGE_FILE));
2142
- const redirects = kitRedirects({ framework, text });
2906
+ const redirects = redirectMode({ framework, text, host, found: discovered }) !== null;
2907
+ const cannotMove = (objects) => noRedirects({ framework, objects: objects || discovered.pages.some((p) => p.router?.object) });
2143
2908
  const reads2 = siteReads(kept, text, graph);
2144
2909
  const out = {};
2145
2910
  const no = (reason, detail) => ({ ok: (
@@ -2154,7 +2919,7 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2154
2919
  if (page.path.includes(" ")) continue;
2155
2920
  const below = discovered.pages.filter((p) => under(p.path, page.path));
2156
2921
  const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
2157
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
2922
+ if (!adapter?.acts) {
2158
2923
  out[page.path] = all(no("framework"));
2159
2924
  continue;
2160
2925
  }
@@ -2163,7 +2928,8 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2163
2928
  continue;
2164
2929
  }
2165
2930
  if (page.kind === "template") {
2166
- out[page.path] = all(no("template"));
2931
+ const detail = !!details[page.path] && !adapter?.routeLines && !!page.file && page.reason !== "unparsed";
2932
+ out[page.path] = detail ? { rename: no("template"), duplicate: no("template"), delete: below.length ? no("nested", below.map((p) => p.path).join(", ")) : yes, under: below.length } : all(no("template"));
2167
2933
  continue;
2168
2934
  }
2169
2935
  if (!page.file || page.reason === "unparsed") {
@@ -2171,10 +2937,10 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2171
2937
  continue;
2172
2938
  }
2173
2939
  const onLive = live.has(page.path);
2174
- let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
2175
- if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
2940
+ let rename = page.path === "/" ? no("home") : onLive && !redirects ? no(cannotMove(!!page.router?.object), page.router?.object ? "route objects" : void 0) : yes;
2941
+ if (rename.ok && adapter?.routeLines && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
2176
2942
  const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
2177
- let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
2943
+ let duplicate = adapter?.routeLines && page.reason === "nested" ? no("nested") : yes;
2178
2944
  if (duplicate.ok) {
2179
2945
  const content = ownedContent(page, { paths: kept, text, importers: graph });
2180
2946
  const pageReads = reads2.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
@@ -2210,13 +2976,14 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2210
2976
  const folders = {};
2211
2977
  for (const at3 of folderPaths(discovered.pages)) {
2212
2978
  const below = discovered.pages.filter((p) => under(p.path, at3));
2213
- let rename = !PAGE_ACTION_FRAMEWORKS.includes(String(framework)) ? no("framework") : !pageFile.ok ? no("invalid") : yes;
2214
- if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && !redirects) rename = no("no_redirects");
2215
- if (rename.ok && framework === "vite-react" && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
2216
- if (rename.ok && framework !== "vite-react" && !folderDirs(at3, below)) rename = no("unparsed", at3);
2979
+ let rename = !adapter?.acts ? no("framework") : !pageFile.ok ? no("invalid") : yes;
2980
+ if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && !redirects) rename = no(cannotMove(below.some((p) => p.router?.object)));
2981
+ if (rename.ok && adapter?.routeLines && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
2982
+ if (rename.ok && !adapter?.routeLines && !(adapter?.folderDirs ?? folderDirs)(at3, below)) rename = no("unparsed", at3);
2217
2983
  folders[at3] = { rename, under: below.length };
2218
2984
  }
2219
- return { redirects, actions: out, folders };
2985
+ const redirectsWhy = redirects ? null : cannotMove(false);
2986
+ return { redirects, redirectsWhy, actions: out, folders, create: createCapability({ framework, paths: kept, text, found: discovered }) };
2220
2987
  }
2221
2988
  function redirectsFor(framework, pageFile, pagePaths = []) {
2222
2989
  const pages = new Set(pagePaths.map(normalisePath));
@@ -2230,36 +2997,40 @@ function redirectsFor(framework, pageFile, pagePaths = []) {
2230
2997
  continue;
2231
2998
  }
2232
2999
  const destBase = prefix ? normalisePath(destination2.replace(REST, "")) : destination2;
2233
- if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination2, permanent: true });
2234
- else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
2235
- else list.push({ source, destination: destination2 });
3000
+ const shape = adapterOf(framework)?.redirect;
3001
+ list.push(shape ? shape({ prefix, source, destination: destination2, base, destBase }) : { source, destination: destination2 });
2236
3002
  }
2237
3003
  return { list, skipped };
2238
3004
  }
2239
3005
  function siteRedirectList({ framework, text }) {
2240
3006
  const out = [];
2241
3007
  try {
2242
- const v = JSON.parse(text("vercel.json") ?? "null");
3008
+ const v = JSON.parse(text(VERCEL_JSON) ?? "null");
3009
+ const mine = hostedMirrors(text);
2243
3010
  for (const r of Array.isArray(v?.redirects) ? v.redirects : []) {
2244
- if (typeof r?.source === "string" && typeof r?.destination === "string") out.push({ from: r.source, to: r.destination, file: "vercel.json" });
3011
+ if (typeof r?.source === "string" && typeof r?.destination === "string" && !mine.has(vercelKey(r))) out.push({ from: r.source, to: r.destination, file: VERCEL_JSON });
2245
3012
  }
2246
3013
  } catch {
2247
3014
  }
2248
- for (const c of CONFIGS[String(framework)] ?? []) {
2249
- const src = stripComments(text(c) ?? "");
2250
- if (framework === "astro") {
2251
- const at3 = src.search(/\bredirects\s*:\s*\{/);
2252
- if (at3 < 0) continue;
2253
- const body = braced(src, src.indexOf("{", at3)) ?? "";
2254
- const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
2255
- for (const m of body.matchAll(entry)) out.push({ from: m[1], to: m[2] ?? m[3], file: c });
2256
- } else if (framework === "next") {
2257
- for (const m of src.matchAll(/\{[^{}]*\}/g)) {
2258
- const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
2259
- const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
2260
- if (from && to) out.push({ from, to, file: c });
2261
- }
2262
- }
3015
+ const adapter = adapterOf(framework);
3016
+ for (const c of adapter?.configs ?? []) {
3017
+ if (adapter.configRedirects) out.push(...adapter.configRedirects(stripComments(text(c) ?? ""), c));
3018
+ }
3019
+ return out;
3020
+ }
3021
+ function astroConfigRedirects(src, file) {
3022
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
3023
+ if (at3 < 0) return [];
3024
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
3025
+ const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
3026
+ return [...body.matchAll(entry)].map((m) => ({ from: m[1], to: m[2] ?? m[3], file }));
3027
+ }
3028
+ function nextConfigRedirects(src, file) {
3029
+ const out = [];
3030
+ for (const m of src.matchAll(/\{[^{}]*\}/g)) {
3031
+ const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
3032
+ const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
3033
+ if (from && to) out.push({ from, to, file });
2263
3034
  }
2264
3035
  return out;
2265
3036
  }
@@ -2269,35 +3040,40 @@ function redirectEnd(p) {
2269
3040
  const base = normalisePath(prefix ? s.replace(REST, "").replace(/\/(…|\.\.\.|\*)$/, "") : s);
2270
3041
  return { base, prefix, key: prefix ? `${base === "/" ? "" : base}/[...path]` : base };
2271
3042
  }
2272
- function planRedirect(request, { framework, paths, text, found }) {
3043
+ function planRedirect(request, { framework, paths, text, found, host = null }) {
3044
+ const adapter = adapterOf(framework);
2273
3045
  const no = (reason, detail) => ({ ok: (
2274
3046
  /** @type {const} */
2275
3047
  false
2276
3048
  ), reason, ...detail ? { detail } : {} });
2277
3049
  const action = request.action;
2278
3050
  if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
2279
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
3051
+ if (!adapter?.acts) return no("framework");
2280
3052
  const pageFile = parsePageFile(text(PAGE_FILE));
2281
3053
  if (!pageFile.ok) return no("invalid", pageFile.error);
2282
3054
  const from = redirectEnd(request.from);
2283
3055
  const was = request.was != null ? redirectEnd(request.was) : from;
2284
- if (action !== "add" && !(was.key in pageFile.redirects)) return no("missing", was.key);
3056
+ const discoveredAll = found ?? discover({ framework, paths: paths.filter((p) => !SKIP2.test(p)), text });
3057
+ const mode = redirectMode({ framework, text, host, found: discoveredAll });
3058
+ const key = action !== "add" && was.key in pageFile.hosted ? "hosted" : action !== "add" && was.key in pageFile.redirects ? "redirects" : mode === "host" ? "hosted" : "redirects";
3059
+ const all = { ...pageFile.redirects, ...pageFile.hosted };
3060
+ if (action !== "add" && !(was.key in all)) return no("missing", was.key);
2285
3061
  const changes = {};
2286
3062
  let to = null;
2287
3063
  if (action !== "remove") {
2288
- if (!kitRedirects({ framework, text })) return no("no_redirects");
3064
+ if (mode === null || key === "hosted" !== (mode === "host")) return no(noRedirects({ framework, objects: discoveredAll.pages.some((p) => p.router?.object) }));
2289
3065
  if (from.base === "/" || !validAddress(from.base)) return no("address", request.from);
2290
3066
  const end = redirectEnd(request.to);
2291
3067
  if (!validAddress(end.base)) return no("address", request.to);
2292
- const discovered = found ?? discover({ framework, paths: paths.filter((p) => !SKIP2.test(p)), text });
3068
+ const discovered = discoveredAll;
2293
3069
  const isPage = (p) => discovered.pages.some((q) => q.kind === "template" ? templateMatches(q.path, p) : q.path === p);
2294
3070
  if (from.prefix ? discovered.pages.some((q) => within2(q.path, from.base)) : isPage(from.base)) return no("page", from.base);
2295
- if (from.key !== was.key && from.key in pageFile.redirects) return no("exists", from.key);
2296
- if (action === "add" && from.key in pageFile.redirects) return no("exists", from.key);
3071
+ if (from.key !== was.key && from.key in all) return no("exists", from.key);
3072
+ if (action === "add" && from.key in all) return no("exists", from.key);
2297
3073
  const own = [...siteRedirects({ framework, text })].find((s) => sends(s, from.base));
2298
3074
  if (own) return no("redirect_conflict", own);
2299
3075
  let dest = end.base;
2300
- const others = { ...pageFile.redirects };
3076
+ const others = { ...pageFile[key] };
2301
3077
  delete others[was.key];
2302
3078
  for (let hops = 0; hops < 20; hops++) {
2303
3079
  const next = Object.entries(others).find(([s]) => !REST.test(s) && s === dest);
@@ -2318,14 +3094,20 @@ function planRedirect(request, { framework, paths, text, found }) {
2318
3094
  }
2319
3095
  }
2320
3096
  for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) changes[k] = sendsOn[k] ?? null;
2321
- });
3097
+ }, key);
2322
3098
  if (content === null) return no("same");
3099
+ const files = [{ path: PAGE_FILE, content }];
3100
+ if (key === "hosted") {
3101
+ const mirror = hostedWrite(text, text(PAGE_FILE), content);
3102
+ if (mirror && "error" in mirror) return no("invalid", mirror.error);
3103
+ if (mirror) files.push(mirror);
3104
+ }
2323
3105
  const shown2 = (k) => k.replace(REST, "/\u2026");
2324
3106
  const message = action === "remove" ? `Unbase: remove redirect ${shown2(was.key)}` : `Unbase: redirect ${shown2(from.key)} to ${shown2(to)}`;
2325
3107
  return { ok: (
2326
3108
  /** @type {const} */
2327
3109
  true
2328
- ), action, from: from.key, to, was: was.key, files: [{ path: PAGE_FILE, content }], redirects: changes, message };
3110
+ ), action, from: from.key, to, was: was.key, files, redirects: changes, message };
2329
3111
  }
2330
3112
 
2331
3113
  // supabase/functions/_shared/next-metadata.ts
@@ -2580,6 +3362,14 @@ function imageField(object) {
2580
3362
  if (url?.type === "string") return { pointer: `/metadata/${path}/url`, kind: "image", exists: true, value: url.value };
2581
3363
  return null;
2582
3364
  }
3365
+ function iconField(object) {
3366
+ const icons = object ? prop(object, "icons")?.value : void 0;
3367
+ if (icons === void 0) return { pointer: "/metadata/icons", kind: "image", exists: false, value: null };
3368
+ if (icons?.type === "string") return { pointer: "/metadata/icons", kind: "image", exists: true, value: icons.value };
3369
+ const icon = icons?.type === "object" ? prop(icons, "icon")?.value : void 0;
3370
+ if (icon?.type === "string") return { pointer: "/metadata/icons/icon", kind: "image", exists: true, value: icon.value };
3371
+ return null;
3372
+ }
2583
3373
  function noindexField(object) {
2584
3374
  const robots = object ? prop(object, "robots")?.value : void 0;
2585
3375
  if (robots === void 0) return { pointer: NOINDEX, kind: "boolean", exists: false, value: null };
@@ -2588,81 +3378,847 @@ function noindexField(object) {
2588
3378
  if (index === void 0) return robots.spread ? null : { pointer: NOINDEX, kind: "boolean", exists: false, value: null };
2589
3379
  return index?.type === "boolean" ? { pointer: NOINDEX, kind: "boolean", exists: true, value: String(!index.value) } : null;
2590
3380
  }
2591
- function langOf(src) {
2592
- const code = codeOnly(src);
2593
- const tag = /<html\b/.exec(code);
2594
- if (!tag) return null;
2595
- const close = code.indexOf(">", tag.index);
2596
- const attrs = code.slice(tag.index, close < 0 ? code.length : close);
2597
- const m = /\slang\s*=\s*(["'])/.exec(attrs);
2598
- if (!m) return null;
2599
- const open = tag.index + m.index + m[0].length;
2600
- const end = src.indexOf(m[1], open);
2601
- if (end < 0 || /[{}\n]/.test(src.slice(open, end))) return null;
2602
- return { field: { pointer: LANG, kind: "text", exists: true, value: src.slice(open, end) }, inner: { start: open, end } };
3381
+ function langOf(src) {
3382
+ const code = codeOnly(src);
3383
+ const tag = /<html\b/.exec(code);
3384
+ if (!tag) return null;
3385
+ const close = code.indexOf(">", tag.index);
3386
+ const attrs = code.slice(tag.index, close < 0 ? code.length : close);
3387
+ const m = /\slang\s*=\s*(["'])/.exec(attrs);
3388
+ if (!m) return null;
3389
+ const open = tag.index + m.index + m[0].length;
3390
+ const end = src.indexOf(m[1], open);
3391
+ if (end < 0 || /[{}\n]/.test(src.slice(open, end))) return null;
3392
+ return { field: { pointer: LANG, kind: "text", exists: true, value: src.slice(open, end) }, inner: { start: open, end } };
3393
+ }
3394
+ function pageMetaFields(src) {
3395
+ const read = readMetadata(src);
3396
+ if (read.kind === "refused") return { fields: {}, refused: read.reason, computed: {} };
3397
+ const object = read.kind === "literal" ? read.object : null;
3398
+ const wanted = {
3399
+ title: textField(object, ["title/absolute", "title"], "title"),
3400
+ description: textField(object, ["description"], "description"),
3401
+ socialImage: imageField(object),
3402
+ noindex: noindexField(object)
3403
+ };
3404
+ const fields = {};
3405
+ const computed = {};
3406
+ for (const [k, f] of Object.entries(wanted)) {
3407
+ if (f) fields[k] = f;
3408
+ else computed[k] = "computed";
3409
+ }
3410
+ return { fields, refused: null, computed };
3411
+ }
3412
+ var TITLE_DEFAULT = "title/default";
3413
+ var SITE_NAME_PATHS = ["applicationName", "openGraph/siteName", TITLE_DEFAULT, "title"];
3414
+ function siteMetaFields(src) {
3415
+ const read = readMetadata(src);
3416
+ const lang = langOf(src);
3417
+ if (read.kind === "refused") return { fields: lang ? { language: lang.field } : {}, refused: read.reason, computed: {} };
3418
+ const object = read.kind === "literal" ? read.object : null;
3419
+ const wanted = {
3420
+ // The name only where the code has it: a new one would change no title. Its application name or
3421
+ // share name first; else the layout's title, the one every page without its own shows: a string,
3422
+ // or `title.default` (whose `title.template` a new name follows: writeMetadata).
3423
+ name: textField(object, SITE_NAME_PATHS, null),
3424
+ description: textField(object, ["description"], "description"),
3425
+ socialImage: imageField(object),
3426
+ language: lang?.field ?? null,
3427
+ favicon: iconField(object)
3428
+ };
3429
+ const fields = {};
3430
+ const computed = {};
3431
+ const named = !!object && SITE_NAME_PATHS.some((p) => at(object, p.split("/")) !== void 0);
3432
+ for (const [k, f] of Object.entries(wanted)) {
3433
+ if (f) fields[k] = f;
3434
+ else if (k !== "name" || named) computed[k] = "computed";
3435
+ }
3436
+ return { fields, refused: null, computed };
3437
+ }
3438
+
3439
+ // supabase/functions/_shared/astro-meta.ts
3440
+ var PROP_OF = { socialImage: "image", noindex: "noindex" };
3441
+ var prop2 = (o, key) => [...o.props].reverse().find((p) => p.key === key);
3442
+ function frontmatter(src) {
3443
+ const open = /^\s*---[ \t]*\r?\n/.exec(src);
3444
+ if (!open) return null;
3445
+ const close = src.indexOf("\n---", open[0].length - 1);
3446
+ if (close < 0) return null;
3447
+ return { start: open[0].length, end: close + 1 };
3448
+ }
3449
+ function objectConst(src, name, from, to) {
3450
+ const code = codeOnly(src.slice(0, to));
3451
+ const re = new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${name}\\b\\s*(?::[^=;]+?)?\\s*=`, "g");
3452
+ re.lastIndex = from;
3453
+ const m = re.exec(code);
3454
+ if (!m || m.index >= to) return null;
3455
+ const node = parseValue(src, m.index + m[0].length);
3456
+ return node.type === "object" ? node : "computed";
3457
+ }
3458
+ function fieldOf(o, key, pointer, add) {
3459
+ const p = prop2(o, key);
3460
+ if (!p) return add && !o.spread ? { pointer, exists: false, value: null } : null;
3461
+ return p.value?.type === "string" ? { pointer, exists: true, value: p.value.value } : "computed";
3462
+ }
3463
+ function layoutElement(src) {
3464
+ const fm = frontmatter(src);
3465
+ if (!fm) return null;
3466
+ const head = src.slice(fm.start, fm.end);
3467
+ const imports = /* @__PURE__ */ new Map();
3468
+ for (const m of head.matchAll(/import\s+([A-Z][\w$]*)\s+from\s*["']([^"']+\.astro)["']/g)) imports.set(m[1], m[2]);
3469
+ const body = fm.end + src.slice(fm.end).indexOf("---") + 3;
3470
+ const tag = /<([A-Z][\w$.]*)(?=[\s/>])/g;
3471
+ tag.lastIndex = body;
3472
+ for (let m = tag.exec(src); m; m = tag.exec(src)) {
3473
+ if (!imports.has(m[1])) continue;
3474
+ const parsed = attrsOf(src, m.index + m[0].length);
3475
+ if (!parsed) return null;
3476
+ return { name: m[1], file: imports.get(m[1]), start: m.index, end: parsed.end, attrs: parsed.attrs };
3477
+ }
3478
+ return null;
3479
+ }
3480
+ function attrsOf(src, i) {
3481
+ const attrs = [];
3482
+ for (; ; ) {
3483
+ i = skip(src, i);
3484
+ if (src[i] === ">") return { attrs, end: i, selfClosing: false };
3485
+ if (src.startsWith("/>", i)) return { attrs, end: i, selfClosing: true };
3486
+ if (src[i] === "{") {
3487
+ const close = braceEnd(src, i);
3488
+ if (close < 0) return null;
3489
+ i = close + 1;
3490
+ continue;
3491
+ }
3492
+ const name = /^[A-Za-z_:@][\w:.-]*/.exec(src.slice(i, i + 128))?.[0];
3493
+ if (!name) return null;
3494
+ const start = i;
3495
+ i += name.length;
3496
+ let j = skip(src, i);
3497
+ if (src[j] !== "=") {
3498
+ attrs.push({ name, start, end: i, value: null });
3499
+ continue;
3500
+ }
3501
+ j = skip(src, j + 1);
3502
+ const q = src[j];
3503
+ if (q === '"' || q === "'" || q === "`") {
3504
+ const close = src.indexOf(q, j + 1);
3505
+ if (close < 0) return null;
3506
+ attrs.push({ name, start, end: close + 1, value: { kind: "string", inner: { start: j + 1, end: close }, quote: q, text: src.slice(j + 1, close) } });
3507
+ i = close + 1;
3508
+ } else if (q === "{") {
3509
+ const close = braceEnd(src, j);
3510
+ if (close < 0) return null;
3511
+ const node = parseValue(src, j + 1);
3512
+ const literalValue2 = node.type === "string" && node.quote !== "`" && skip(src, node.end) === close ? node.value : null;
3513
+ attrs.push({ name, start, end: close + 1, value: { kind: "expr", literal: literalValue2, start: j, end: close + 1 } });
3514
+ i = close + 1;
3515
+ } else return null;
3516
+ }
3517
+ }
3518
+ function braceEnd(src, i) {
3519
+ let depth = 0;
3520
+ for (let j = i; j < src.length; j++) {
3521
+ const c = src[j];
3522
+ if (c === '"' || c === "'" || c === "`") {
3523
+ const close = src.indexOf(c, j + 1);
3524
+ if (close < 0) return -1;
3525
+ j = close;
3526
+ } else if (c === "{") depth++;
3527
+ else if (c === "}" && --depth === 0) return j;
3528
+ }
3529
+ return -1;
3530
+ }
3531
+ function layoutProps(src) {
3532
+ const fm = frontmatter(src);
3533
+ if (!fm) return null;
3534
+ const code = codeOnly(src.slice(0, fm.end));
3535
+ const m = /\b(?:const|let|var)\s*\{/g;
3536
+ m.lastIndex = fm.start;
3537
+ for (let hit = m.exec(code); hit; hit = m.exec(code)) {
3538
+ const open = hit.index + hit[0].length - 1;
3539
+ const close = braceEnd(src, open);
3540
+ if (close < 0 || !/^\s*\}\s*=\s*Astro\.props\b/.test(src.slice(close))) continue;
3541
+ const out = /* @__PURE__ */ new Map();
3542
+ let i = open + 1;
3543
+ while (i < close) {
3544
+ i = skip(src, i);
3545
+ const key = /^(?:\.\.\.)?[A-Za-z_$][\w$]*/.exec(src.slice(i, close))?.[0];
3546
+ if (!key) break;
3547
+ i += key.length;
3548
+ i = skip(src, i);
3549
+ if (src[i] === ":") {
3550
+ i = skip(src, i + 1);
3551
+ if (src[i] === "{" || src[i] === "[") i = braceEnd(src.replace(/\[/g, "{").replace(/\]/g, "}"), i) + 1;
3552
+ else i += /^[A-Za-z_$][\w$]*/.exec(src.slice(i))?.[0].length ?? 0;
3553
+ i = skip(src, i);
3554
+ }
3555
+ let def = { default: null };
3556
+ if (src[i] === "=") {
3557
+ i = skip(src, i + 1);
3558
+ const value = parseValue(src, i);
3559
+ if (value.type === "string") def = { default: value.value, start: value.inner.start, end: value.inner.end, quote: value.quote };
3560
+ i = value.end;
3561
+ }
3562
+ if (!key.startsWith("...")) out.set(key, def);
3563
+ i = skip(src, i);
3564
+ if (src[i] === ",") i++;
3565
+ }
3566
+ return out;
3567
+ }
3568
+ return null;
3569
+ }
3570
+ function astroPageFields(src, accepts) {
3571
+ const fields = {};
3572
+ const computed = {};
3573
+ const fm = frontmatter(src);
3574
+ const el = layoutElement(src);
3575
+ const meta = fm ? objectConst(src, "metadata", fm.start, fm.end) : null;
3576
+ const handed = !!el && el.attrs.some((a) => a.name === "metadata" && a.value?.kind === "expr" && /^\s*\{\s*metadata\s*\}\s*$/.test(src.slice(a.value.start, a.value.end)));
3577
+ for (const f of ["title", "description"]) {
3578
+ if (meta && meta !== "computed" && handed) {
3579
+ const got = fieldOf(meta, f, `/astro/metadata/${f}`, true);
3580
+ if (got === "computed") computed[f] = "computed";
3581
+ else if (got) fields[f] = got;
3582
+ continue;
3583
+ }
3584
+ const attr = el?.attrs.find((a) => a.name === f);
3585
+ if (attr?.value?.kind === "string") fields[f] = { pointer: `/astro/props/${f}`, exists: true, value: attr.value.text };
3586
+ else if (attr?.value?.kind === "expr") {
3587
+ if (attr.value.literal !== null) fields[f] = { pointer: `/astro/props/${f}`, exists: true, value: attr.value.literal };
3588
+ else computed[f] = "computed";
3589
+ } else if (el && accepts?.has(f)) fields[f] = { pointer: `/astro/props/${f}`, exists: false, value: null };
3590
+ }
3591
+ if (!(meta && meta !== "computed" && handed)) {
3592
+ const image = el?.attrs.find((a) => a.name === PROP_OF.socialImage);
3593
+ const pointer = `/astro/props/${PROP_OF.socialImage}`;
3594
+ if (image?.value?.kind === "string") fields.socialImage = { pointer, exists: true, value: image.value.text };
3595
+ else if (image?.value?.kind === "expr") {
3596
+ if (image.value.literal !== null) fields.socialImage = { pointer, exists: true, value: image.value.literal };
3597
+ else computed.socialImage = "computed";
3598
+ } else if (el && !image && accepts?.has(PROP_OF.socialImage)) fields.socialImage = { pointer, exists: false, value: null };
3599
+ const flag = el?.attrs.find((a) => a.name === PROP_OF.noindex);
3600
+ const at3 = `/astro/props/${PROP_OF.noindex}`;
3601
+ const said = flag?.value?.kind === "expr" ? src.slice(flag.value.start + 1, flag.value.end - 1).trim() : null;
3602
+ if (flag && flag.value === null) fields.noindex = { pointer: at3, exists: true, value: "true" };
3603
+ else if (said === "true" || said === "false") fields.noindex = { pointer: at3, exists: true, value: said };
3604
+ else if (flag) computed.noindex = "computed";
3605
+ else if (el && accepts?.has(PROP_OF.noindex)) fields.noindex = { pointer: at3, exists: false, value: null };
3606
+ }
3607
+ return { fields, computed, layout: el?.file ?? null };
3608
+ }
3609
+ function layoutDefaults(src) {
3610
+ const props = layoutProps(src);
3611
+ const out = {};
3612
+ const title = props?.get("title");
3613
+ const description = props?.get("description");
3614
+ if (title?.default != null) out.name = { pointer: "/astro/default/title", exists: true, value: title.default };
3615
+ if (description?.default != null) out.description = { pointer: "/astro/default/description", exists: true, value: description.default };
3616
+ return out;
3617
+ }
3618
+ function layoutModuleRefs(src) {
3619
+ const fm = frontmatter(src);
3620
+ if (!fm) return [];
3621
+ const head = src.slice(fm.start, fm.end);
3622
+ const out = [];
3623
+ for (const m of head.matchAll(/import\s*\{([^}]+)\}\s*from\s*["'](\.{1,2}\/[^"']+|~\/[^"']+|@\/[^"']+)["']/g)) {
3624
+ for (const part of m[1].split(",")) {
3625
+ const [orig, alias] = part.trim().split(/\s+as\s+/);
3626
+ const local = (alias ?? orig ?? "").trim();
3627
+ if (!local) continue;
3628
+ const used = (k) => new RegExp(`\\b${local}\\.${k}\\b`).test(src);
3629
+ const name = ["name", "title", "siteName"].find(used) ?? null;
3630
+ const description = used("description") ? "description" : null;
3631
+ if (name || description) out.push({ exportName: (orig ?? local).trim(), spec: m[2], name, description });
3632
+ }
3633
+ }
3634
+ return out;
3635
+ }
3636
+ function moduleField(src, exportName, key) {
3637
+ const o = objectConst(src, exportName, 0, src.length);
3638
+ if (!o) return null;
3639
+ if (o === "computed") return "computed";
3640
+ const exported = new RegExp(`\\bexport\\s+(?:const|let|var)\\s+${exportName}\\b|\\bexport\\s*\\{[^}]*\\b${exportName}\\b`).test(codeOnly(src));
3641
+ if (!exported) return null;
3642
+ return fieldOf(o, key, `/module/${exportName}/${key}`, false);
3643
+ }
3644
+ function yamlScalar(src, parent, key) {
3645
+ const lines = src.split("\n");
3646
+ let offset = 0;
3647
+ let inside = false;
3648
+ for (const line of lines) {
3649
+ const start = offset;
3650
+ offset += line.length + 1;
3651
+ if (/^\S/.test(line)) {
3652
+ inside = new RegExp(`^${parent}:\\s*(#.*)?$`).test(line);
3653
+ continue;
3654
+ }
3655
+ if (!inside) continue;
3656
+ const m = new RegExp(`^(\\s+)${key}:[ \\t]*`).exec(line);
3657
+ if (!m) continue;
3658
+ const at3 = start + m[0].length;
3659
+ const rest = line.slice(m[0].length);
3660
+ if (!rest.trim() || /^[|>&*!\[{]/.test(rest)) return "computed";
3661
+ const q = rest[0];
3662
+ if (q === '"' || q === "'") {
3663
+ const close = q === '"' ? /^"((?:\\.|[^"\\])*)"/.exec(rest) : /^'((?:''|[^'])*)'/.exec(rest);
3664
+ if (!close) return "computed";
3665
+ const value = q === '"' ? JSON.parse(`"${close[1]}"`) : close[1].replace(/''/g, "'");
3666
+ return { start: at3, end: at3 + close[0].length, value, style: q };
3667
+ }
3668
+ const plain2 = rest.replace(/\s+#.*$/, "").trimEnd();
3669
+ return { start: at3, end: at3 + plain2.length, value: plain2, style: "plain" };
3670
+ }
3671
+ return null;
3672
+ }
3673
+ function yamlField(src, parent, key) {
3674
+ const s = yamlScalar(src, parent, key);
3675
+ if (s === null || s === "computed") return s;
3676
+ return { pointer: `/yaml/${parent}/${key}`, exists: true, value: s.value };
3677
+ }
3678
+
3679
+ // supabase/functions/unbase-projects/settings-content.ts
3680
+ var PAGE_FIELDS = {
3681
+ title: { name: "titel", kind: "text" },
3682
+ description: { name: "beschrijving", kind: "text" },
3683
+ socialImage: { name: "ogImage", kind: "image" },
3684
+ noindex: { name: "noindex", kind: "boolean" },
3685
+ siteSearch: { name: "zoeken", kind: "boolean" }
3686
+ };
3687
+ var SITE_FIELDS = {
3688
+ name: { name: "naam", kind: "text" },
3689
+ description: { name: "beschrijving", kind: "text" },
3690
+ language: { name: "taal", kind: "text" },
3691
+ faviconLight: { name: "favicon", kind: "image" },
3692
+ faviconDark: { name: "faviconDonker", kind: "image" },
3693
+ socialImage: { name: "ogImage", kind: "image" },
3694
+ analyticsId: { name: "googleAnalytics", kind: "text" }
3695
+ };
3696
+ var CONTENT = "src/content";
3697
+ var SCHEMAS = `${CONTENT}/.schemas`;
3698
+ var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
3699
+ var AT_ONCE2 = 8;
3700
+ var MAX_ROUTE_FILES = 300;
3701
+ async function inTurns(items, work) {
3702
+ const out = new Array(items.length);
3703
+ let next = 0;
3704
+ await Promise.all(
3705
+ Array.from({ length: Math.min(AT_ONCE2, items.length) }, async () => {
3706
+ while (next < items.length) {
3707
+ const i = next++;
3708
+ out[i] = await work(items[i]);
3709
+ }
3710
+ })
3711
+ );
3712
+ return out;
3713
+ }
3714
+ var parse = (text) => {
3715
+ if (text === null) return null;
3716
+ try {
3717
+ return JSON.parse(text);
3718
+ } catch {
3719
+ return null;
3720
+ }
3721
+ };
3722
+ function valueOf(v, kind) {
3723
+ if (kind === "boolean") return typeof v === "boolean" ? String(v) : null;
3724
+ return typeof v === "string" ? v : null;
3725
+ }
3726
+ function fieldsOf(names, data, allowed, file, base) {
3727
+ const fields = {};
3728
+ for (const [field2, { name, kind }] of Object.entries(names)) {
3729
+ const value = valueOf(data?.[name], kind);
3730
+ const there = data?.[name] !== void 0;
3731
+ if (there && value === null) continue;
3732
+ if (!there && !allowed[name]) continue;
3733
+ fields[field2] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
3734
+ }
3735
+ return fields;
3736
+ }
3737
+ async function contentSettings(repo, appPath) {
3738
+ const at3 = (p) => join(appPath, p);
3739
+ const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at3(SCHEMAS)}/`) && p.endsWith(".schema.json"));
3740
+ if (!schemaPaths.length) return null;
3741
+ const named = (p) => p.slice(at3(SCHEMAS).length + 1, -".schema.json".length);
3742
+ const schemas = /* @__PURE__ */ new Map();
3743
+ const [legacyMap, map, ...read] = await inTurns([at3(`${SCHEMAS}/collecties.json`), at3(`${SCHEMAS}/collections.json`), ...schemaPaths], (p) => repo.read(p));
3744
+ schemaPaths.forEach((p, i) => {
3745
+ const s = parse(read[i] ?? null);
3746
+ if (s && typeof s === "object") schemas.set(named(p), s);
3747
+ });
3748
+ const elsewhere = { ...parse(legacyMap ?? null) ?? {}, ...parse(map ?? null) ?? {} };
3749
+ const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at3(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at3(SCHEMAS)}/`));
3750
+ const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at3(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
3751
+ const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
3752
+ const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
3753
+ const pages = {};
3754
+ let routes = null;
3755
+ if (routeCollection) {
3756
+ const [collection, schema] = routeCollection;
3757
+ const allowed = schema.properties.seo?.properties ?? {};
3758
+ const files = filesOf(collection).slice(0, MAX_ROUTE_FILES);
3759
+ const datas = await inTurns(files, async (p) => parse(await repo.read(p)));
3760
+ files.forEach((file, i) => {
3761
+ const data = datas[i];
3762
+ if (!data || typeof data.pad !== "string" || !ROUTE.test(data.pad)) return;
3763
+ const seo = data.seo && typeof data.seo === "object" && !Array.isArray(data.seo) ? data.seo : {};
3764
+ pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
3765
+ });
3766
+ const dir = files[0] ? files[0].slice(appPath ? appPath.length + 1 : 0).replace(/\/[^/]+$/, "") : `${CONTENT}/${collection}`;
3767
+ const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
3768
+ routes = { dir, fields, ...schema["x-item-fields"] === true ? { itemFields: true } : {} };
3769
+ }
3770
+ const siteCollection = [...schemas].find(([, s]) => (s["x-settings"] ?? s["x-instellingen"]) === "site");
3771
+ let site = null;
3772
+ const siteFile = siteCollection && filesOf(siteCollection[0])[0];
3773
+ if (siteCollection && siteFile) {
3774
+ const data = parse(await repo.read(siteFile));
3775
+ if (data && typeof data === "object" && !Array.isArray(data)) {
3776
+ site = fieldsOf(SITE_FIELDS, data, siteCollection[1].properties ?? {}, siteFile.slice(appPath ? appPath.length + 1 : 0), "");
3777
+ }
3778
+ }
3779
+ if (!Object.keys(pages).length && !routes && !site) return null;
3780
+ return { pages, routes, site };
3781
+ }
3782
+
3783
+ // supabase/functions/_shared/html-head.ts
3784
+ var headPointer = (field2) => `/head/${field2}`;
3785
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
3786
+ function decodeValue(raw) {
3787
+ return raw.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&([a-z]+);/gi, (m, n) => ENTITIES[n.toLowerCase()] ?? m).replace(/\s+/g, " ").trim();
3788
+ }
3789
+ function tagsIn(html, from, until) {
3790
+ const out = [];
3791
+ let i = from;
3792
+ while (i < until) {
3793
+ const lt = html.indexOf("<", i);
3794
+ if (lt < 0 || lt >= until) break;
3795
+ if (html.startsWith("<!--", lt)) {
3796
+ const close = html.indexOf("-->", lt + 4);
3797
+ i = close < 0 ? until : close + 3;
3798
+ continue;
3799
+ }
3800
+ const name = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(lt, lt + 64))?.[1];
3801
+ if (!name) {
3802
+ i = lt + 1;
3803
+ continue;
3804
+ }
3805
+ const attrs = [];
3806
+ let j = lt + 1 + name.length;
3807
+ let end = -1;
3808
+ while (j < html.length) {
3809
+ const c = html[j];
3810
+ if (c === ">") {
3811
+ end = j + 1;
3812
+ break;
3813
+ }
3814
+ if (/[\s/]/.test(c)) {
3815
+ j++;
3816
+ continue;
3817
+ }
3818
+ const m = /^([^\s"'>/=]+)(\s*=\s*)?/.exec(html.slice(j, j + 256));
3819
+ if (!m) {
3820
+ j++;
3821
+ continue;
3822
+ }
3823
+ j += m[0].length;
3824
+ if (!m[2]) {
3825
+ attrs.push({ name: m[1].toLowerCase(), value: "", start: j, end: j, quote: null });
3826
+ continue;
3827
+ }
3828
+ const q = html[j];
3829
+ if (q === '"' || q === "'") {
3830
+ const close = html.indexOf(q, j + 1);
3831
+ if (close < 0) break;
3832
+ attrs.push({ name: m[1].toLowerCase(), value: html.slice(j + 1, close), start: j + 1, end: close, quote: q });
3833
+ j = close + 1;
3834
+ } else {
3835
+ const bare = /^[^\s>]*/.exec(html.slice(j))[0];
3836
+ attrs.push({ name: m[1].toLowerCase(), value: bare, start: j, end: j + bare.length, quote: null });
3837
+ j += bare.length;
3838
+ }
3839
+ }
3840
+ if (end < 0) break;
3841
+ out.push({ name: name.toLowerCase(), start: lt, end, attrs });
3842
+ i = end;
3843
+ if (/^(script|style)$/i.test(name)) {
3844
+ const close = html.toLowerCase().indexOf(`</${name.toLowerCase()}`, end);
3845
+ i = close < 0 ? until : close;
3846
+ }
3847
+ }
3848
+ return out;
3849
+ }
3850
+ var attrOf = (tag, name) => tag.attrs.find((a) => a.name === name);
3851
+ var spanOf = (a) => ({ start: a.start, end: a.end, mode: "attr", quote: a.quote });
3852
+ var plain = (raw) => !/[{}]|<%|%>/.test(raw);
3853
+ function readHead(html, opts = {}) {
3854
+ const out = {};
3855
+ const lower = html.toLowerCase();
3856
+ const headAt = opts.anywhere ? 0 : lower.search(/<head[\s>]/);
3857
+ const bodyAt = lower.search(/<body[\s>]/);
3858
+ const headEnd = lower.indexOf("</head");
3859
+ const until = opts.anywhere ? html.length : headEnd >= 0 ? headEnd : bodyAt >= 0 ? bodyAt : html.length;
3860
+ if (headAt < 0) return out;
3861
+ const htmlTag = opts.anywhere ? void 0 : tagsIn(html, 0, headAt).find((t) => t.name === "html");
3862
+ const lang = htmlTag && attrOf(htmlTag, "lang");
3863
+ if (lang && lang.value.trim() && plain(lang.value)) out.language = { value: decodeValue(lang.value), spans: [spanOf(lang)] };
3864
+ const tags = tagsIn(html, headAt, until);
3865
+ const metas = tags.filter((t) => t.name === "meta");
3866
+ const meta = (key) => metas.filter((t) => [attrOf(t, "name")?.value, attrOf(t, "property")?.value].some((v) => v?.trim().toLowerCase() === key)).map((t) => attrOf(t, "content")).filter((a) => !!a);
3867
+ const fromMeta = (key, copies) => {
3868
+ const found = meta(key);
3869
+ if (found.length !== 1 || !plain(found[0].value) || !found[0].value.trim()) return void 0;
3870
+ const value = decodeValue(found[0].value);
3871
+ return { value, spans: [spanOf(found[0]), ...copiesOf(value, copies)] };
3872
+ };
3873
+ const copiesOf = (value, keys) => keys.flatMap((k) => meta(k)).filter((a) => plain(a.value) && decodeValue(a.value) === value).map(spanOf);
3874
+ const titles = tags.filter((t) => t.name === "title");
3875
+ if (titles.length === 1) {
3876
+ const t = titles[0];
3877
+ const close = lower.indexOf("</title", t.end);
3878
+ const raw = close >= 0 ? html.slice(t.end, close) : "";
3879
+ if (close >= 0 && raw.trim() && !raw.includes("<") && plain(raw)) {
3880
+ const value = decodeValue(raw);
3881
+ out.title = { value, spans: [{ start: t.end, end: close, mode: "text", quote: null }, ...copiesOf(value, ["og:title", "twitter:title"])] };
3882
+ }
3883
+ }
3884
+ const description = fromMeta("description", ["og:description", "twitter:description"]);
3885
+ if (description) out.description = description;
3886
+ const robots = meta("robots");
3887
+ if (robots.length === 1 && plain(robots[0].value)) {
3888
+ const raw = decodeValue(robots[0].value);
3889
+ out.noindex = { value: String(robotsWords(raw).includes("noindex")), spans: [spanOf(robots[0])], raw };
3890
+ }
3891
+ if (opts.anywhere) return out;
3892
+ const image = fromMeta("og:image", ["twitter:image"]);
3893
+ if (image) out.image = image;
3894
+ const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
3895
+ const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
3896
+ for (const [field2, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
3897
+ const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
3898
+ const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
3899
+ if (href && href.value.trim() && plain(href.value)) out[field2] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
3900
+ }
3901
+ return out;
3902
+ }
3903
+ var robotsWords = (content) => content.split(",").map((w) => w.trim().toLowerCase()).filter(Boolean);
3904
+ function skipCode(src, i) {
3905
+ const c = src[i];
3906
+ if (c === "/" && src[i + 1] === "/") {
3907
+ const e = src.indexOf("\n", i);
3908
+ return e < 0 ? src.length : e + 1;
3909
+ }
3910
+ if (c === "/" && src[i + 1] === "*") {
3911
+ const e = src.indexOf("*/", i + 2);
3912
+ return e < 0 ? -1 : e + 2;
3913
+ }
3914
+ for (let j = i + 1; j < src.length; j++) {
3915
+ const d = src[j];
3916
+ if (d === "\\") j++;
3917
+ else if (d === c) return j + 1;
3918
+ else if (d === "\n" && c !== "`") return -1;
3919
+ else if (c === "`" && d === "$" && src[j + 1] === "{") {
3920
+ let depth = 0;
3921
+ for (j += 1; j < src.length; j++) {
3922
+ if (src[j] === "{") depth++;
3923
+ else if (src[j] === "}" && --depth === 0) break;
3924
+ }
3925
+ }
3926
+ }
3927
+ return -1;
3928
+ }
3929
+ function closing2(src, open) {
3930
+ const pair = src[open] === "(" ? ["(", ")"] : ["{", "}"];
3931
+ let depth = 0;
3932
+ for (let i = open; i < src.length; i++) {
3933
+ const c = src[i];
3934
+ if (c === '"' || c === "'" || c === "`" || c === "/" && (src[i + 1] === "/" || src[i + 1] === "*")) {
3935
+ const e = skipCode(src, i);
3936
+ if (e < 0) return -1;
3937
+ i = e - 1;
3938
+ continue;
3939
+ }
3940
+ if (c === pair[0]) depth++;
3941
+ else if (c === pair[1] && --depth === 0) return i;
3942
+ }
3943
+ return -1;
3944
+ }
3945
+ var skipSpace = (src, i) => {
3946
+ while (i < src.length && /\s/.test(src[i])) i++;
3947
+ return i;
3948
+ };
3949
+ function insideRoot(src, i) {
3950
+ i = skipSpace(src, i);
3951
+ if (src[i] === "(") i = skipSpace(src, i + 1);
3952
+ if (src[i] !== "<") return null;
3953
+ const lineStart = src.lastIndexOf("\n", i) + 1;
3954
+ const own = /^[ \t]*/.exec(src.slice(lineStart))[0];
3955
+ if (src[i + 1] === ">") return { at: i + 2, indent: `${own} ` };
3956
+ if (!/^<[A-Za-z][\w.:-]*/.test(src.slice(i, i + 64))) return null;
3957
+ for (let j = i + 1; j < src.length; j++) {
3958
+ const c = src[j];
3959
+ if (c === '"' || c === "'") {
3960
+ const e = src.indexOf(c, j + 1);
3961
+ if (e < 0) return null;
3962
+ j = e;
3963
+ } else if (c === "{") {
3964
+ const e = closing2(src, j);
3965
+ if (e < 0) return null;
3966
+ j = e;
3967
+ } else if (c === "/" && src[j + 1] === ">") return null;
3968
+ else if (c === ">") return { at: j + 1, indent: `${own} ` };
3969
+ }
3970
+ return null;
3971
+ }
3972
+ function topReturn(src, open) {
3973
+ let depth = 0;
3974
+ for (let i = open; i < src.length; i++) {
3975
+ const c = src[i];
3976
+ if (c === '"' || c === "'" || c === "`" || c === "/" && (src[i + 1] === "/" || src[i + 1] === "*")) {
3977
+ const e = skipCode(src, i);
3978
+ if (e < 0) return null;
3979
+ i = e - 1;
3980
+ continue;
3981
+ }
3982
+ if (c === "{") depth++;
3983
+ else if (c === "}" && --depth === 0) return null;
3984
+ else if (depth === 1 && src.startsWith("return", i) && !/[\w$]/.test(src[i - 1] ?? "") && !/[\w$]/.test(src[i + 6] ?? "")) {
3985
+ const j = skipSpace(src, i + 6);
3986
+ if (src[j] === "(" || src[j] === "<") return j;
3987
+ }
3988
+ }
3989
+ return null;
3990
+ }
3991
+ function bodyAfter(src, paren, arrow) {
3992
+ const close = closing2(src, paren);
3993
+ if (close < 0) return null;
3994
+ let i = close + 1;
3995
+ const brace = src.indexOf(arrow ? "=>" : "{", i);
3996
+ if (brace < 0) return null;
3997
+ if (!arrow) return { block: brace };
3998
+ i = skipSpace(src, brace + 2);
3999
+ return src[i] === "{" ? { block: i } : { concise: i };
4000
+ }
4001
+ function componentRootAt(src) {
4002
+ let fn = null;
4003
+ const direct = /\bexport\s+default\s+(?:async\s+)?function\b\s*[A-Za-z_$]?[\w$]*\s*\(/.exec(src);
4004
+ if (direct) fn = bodyAfter(src, direct.index + direct[0].length - 1, false);
4005
+ else {
4006
+ const ref = /\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*$/m.exec(src)?.[1];
4007
+ if (!ref) return null;
4008
+ const decl = new RegExp(`\\bfunction\\s+${ref}\\s*\\(`).exec(src);
4009
+ if (decl) fn = bodyAfter(src, decl.index + decl[0].length - 1, false);
4010
+ else {
4011
+ const arrow = new RegExp(`\\b(?:const|let|var)\\s+${ref}\\s*(?::[^=]+)?=\\s*(?:async\\s*)?\\(`).exec(src);
4012
+ if (!arrow) return null;
4013
+ fn = bodyAfter(src, arrow.index + arrow[0].length - 1, true);
4014
+ }
4015
+ }
4016
+ if (!fn) return null;
4017
+ if ("concise" in fn) return insideRoot(src, fn.concise);
4018
+ const jsx = topReturn(src, fn.block);
4019
+ return jsx === null ? null : insideRoot(src, jsx);
4020
+ }
4021
+ var addable = (field2, opts) => field2 === "title" || field2 === "description" || field2 === "noindex" || field2 === "image" && !opts.anywhere;
4022
+
4023
+ // supabase/functions/_shared/settings-documents.ts
4024
+ var VITE_DOCUMENT = /(^|\/)index\.html$/;
4025
+ var COMPONENT = /^(src\/)?(?!.*(^|\/)\.)[A-Za-z0-9_@()[\] ./-]*\.(jsx|tsx)$/;
4026
+ var PAGES_ROUTER = /^(src\/)?pages\/(?!api\/)(?!.*(^|\/)\.)[A-Za-z0-9_@()[\] ./-]*\.(jsx|tsx|js|ts)$/;
4027
+ var HTML2 = /^(?!.*(^|\/)\.)[A-Za-z0-9_@()[\] ./-]*\.html?$/;
4028
+ var ASTRO_FILE = /^(src\/)?(?!.*(^|\/)\.)[A-Za-z0-9_@()[\] ./-]*\.astro$/;
4029
+ var HEAD_DOCUMENTS = {
4030
+ "vite-react": (file) => VITE_DOCUMENT.test(file) ? {} : COMPONENT.test(file) ? { anywhere: true, jsx: true, add: true } : null,
4031
+ html: (file) => HTML2.test(file) ? { add: true } : null,
4032
+ next: (file) => PAGES_ROUTER.test(file) ? { jsx: true, add: true } : null,
4033
+ astro: (file) => ASTRO_FILE.test(file) ? {} : null
4034
+ };
4035
+ function headOptionsOf(framework, file) {
4036
+ if (!framework || !Object.hasOwn(HEAD_DOCUMENTS, framework) || file.split("/").includes("..")) return null;
4037
+ return HEAD_DOCUMENTS[framework](file);
4038
+ }
4039
+
4040
+ // supabase/functions/unbase-projects/settings-astro.ts
4041
+ var READ_AT_ONCE = 16;
4042
+ var YAML_CONFIGS = ["src/config.yaml", "src/config.yml", "config.yaml"];
4043
+ var KIND = { title: "text", description: "text", socialImage: "image", noindex: "boolean", siteSearch: "boolean" };
4044
+ var settingOf = (file, f, kind = "text") => ({ file, pointer: f.pointer, kind, exists: f.exists, value: f.value });
4045
+ var HEAD_SETTINGS = [
4046
+ ["faviconLight", "favicon"],
4047
+ ["faviconDark", "faviconDark"],
4048
+ ["socialImage", "image"]
4049
+ ];
4050
+ function resolve(from, spec, have) {
4051
+ if (/^[~@]\//.test(spec)) return resolveImport("", `./src/${spec.slice(2)}`, have);
4052
+ return resolveImport(from, spec, have);
2603
4053
  }
2604
- function pageMetaFields(src) {
2605
- const read = readMetadata(src);
2606
- if (read.kind === "refused") return { fields: {}, refused: read.reason, computed: {} };
2607
- const object = read.kind === "literal" ? read.object : null;
2608
- const wanted = {
2609
- title: textField(object, ["title/absolute", "title"], "title"),
2610
- description: textField(object, ["description"], "description"),
2611
- socialImage: imageField(object),
2612
- noindex: noindexField(object)
4054
+ async function astroSettings(repo, appPath) {
4055
+ const content = await contentSettings(repo, appPath);
4056
+ if (content) return content;
4057
+ const root = appPath ? `${appPath}/` : "";
4058
+ const paths = repo.paths.filter((p) => p.startsWith(root)).map((p) => p.slice(root.length));
4059
+ const have = new Set(paths);
4060
+ const texts = /* @__PURE__ */ new Map();
4061
+ const readAll = async (list) => {
4062
+ const todo = [...new Set(list)].filter((p) => !texts.has(p));
4063
+ for (let i = 0; i < todo.length; i += READ_AT_ONCE) {
4064
+ const batch = todo.slice(i, i + READ_AT_ONCE);
4065
+ const got = await Promise.all(batch.map((p) => repo.read(join(appPath, p))));
4066
+ batch.forEach((p, j) => texts.set(p, got[j] ?? null));
4067
+ }
2613
4068
  };
2614
- const fields = {};
2615
- const computed = {};
2616
- for (const [k, f] of Object.entries(wanted)) {
2617
- if (f) fields[k] = f;
2618
- else computed[k] = "computed";
4069
+ const { pages: found } = discover({ framework: "astro", paths, text: () => null });
4070
+ const pages = found.filter((p) => p.kind === "file" && /\.astro$/.test(p.file ?? "")).slice(0, MAX_ROUTE_FILES).map((p) => ({ path: p.path, file: p.file }));
4071
+ if (!pages.length) return null;
4072
+ await readAll(pages.map((p) => p.file));
4073
+ const layoutOf = /* @__PURE__ */ new Map();
4074
+ for (const p of pages) {
4075
+ const src = texts.get(p.file);
4076
+ const spec = src ? astroPageFields(src, null).layout : null;
4077
+ layoutOf.set(p.file, spec ? resolve(p.file, spec, have) : null);
4078
+ }
4079
+ await readAll([...layoutOf.values()].filter((l) => !!l));
4080
+ const accepts = (layout) => {
4081
+ const props = layout ? layoutProps(texts.get(layout) ?? "") : null;
4082
+ return props ? new Set(props.keys()) : null;
4083
+ };
4084
+ const out = {};
4085
+ const refused = {};
4086
+ for (const p of pages) {
4087
+ const src = texts.get(p.file);
4088
+ if (!src) continue;
4089
+ const r = astroPageFields(src, accepts(layoutOf.get(p.file) ?? null));
4090
+ const fields = {};
4091
+ for (const [k, f] of Object.entries(r.fields)) if (f) fields[k] = settingOf(p.file, f, KIND[k]);
4092
+ if (Object.keys(fields).length) out[p.path] = fields;
4093
+ if (Object.keys(r.computed).length) refused[p.path] = { file: p.file, reason: "computed", fields: r.computed };
4094
+ else if (!Object.keys(fields).length) refused[p.path] = { file: p.file, reason: "unsupported" };
2619
4095
  }
2620
- return { fields, refused: null, computed };
2621
- }
2622
- function siteMetaFields(src) {
2623
- const read = readMetadata(src);
2624
- const lang = langOf(src);
2625
- if (read.kind === "refused") return { fields: lang ? { language: lang.field } : {}, refused: read.reason, computed: {} };
2626
- const object = read.kind === "literal" ? read.object : null;
2627
- const wanted = {
2628
- // The name only where the code has it: a new one would change no title.
2629
- name: textField(object, ["applicationName", "openGraph/siteName"], null),
2630
- description: textField(object, ["description"], "description"),
2631
- socialImage: imageField(object),
2632
- language: lang?.field ?? null
4096
+ const counts = /* @__PURE__ */ new Map();
4097
+ for (const l of layoutOf.values()) if (l) counts.set(l, (counts.get(l) ?? 0) + 1);
4098
+ const main = [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
4099
+ const yaml = YAML_CONFIGS.find((p) => have.has(p)) ?? null;
4100
+ await readAll([...yaml ? [yaml] : []]);
4101
+ const site = {};
4102
+ const take = (field2, file, f) => {
4103
+ if (!site[field2] && f && f !== "computed") site[field2] = settingOf(file, f);
2633
4104
  };
2634
- const fields = {};
2635
- const computed = {};
2636
- const named = !!object && ["applicationName", "openGraph/siteName"].some((p) => at(object, p.split("/")) !== void 0);
2637
- for (const [k, f] of Object.entries(wanted)) {
2638
- if (f) fields[k] = f;
2639
- else if (k !== "name" || named) computed[k] = "computed";
4105
+ const yamlSrc = yaml ? texts.get(yaml) : null;
4106
+ if (yaml && yamlSrc) {
4107
+ take("name", yaml, yamlField(yamlSrc, "site", "name"));
4108
+ take("description", yaml, yamlField(yamlSrc, "metadata", "description"));
4109
+ }
4110
+ const layoutSrc = main ? texts.get(main) : null;
4111
+ if (main && layoutSrc && (!site.name || !site.description)) {
4112
+ const refs = layoutModuleRefs(layoutSrc);
4113
+ const files = refs.map((r) => ({ r, file: resolve(main, r.spec, have) })).filter((x) => !!x.file);
4114
+ await readAll(files.map((x) => x.file));
4115
+ for (const { r, file } of files) {
4116
+ const src = texts.get(file);
4117
+ if (!src) continue;
4118
+ if (r.name) take("name", file, moduleField(src, r.exportName, r.name));
4119
+ if (r.description) take("description", file, moduleField(src, r.exportName, r.description));
4120
+ }
4121
+ const defaults = layoutDefaults(layoutSrc);
4122
+ if (defaults.name) take("name", main, defaults.name);
4123
+ if (defaults.description) take("description", main, defaults.description);
2640
4124
  }
2641
- return { fields, refused: null, computed };
4125
+ const opts = main ? headOptionsOf("astro", main) : null;
4126
+ if (main && layoutSrc && opts) {
4127
+ const head = readHead(layoutSrc, opts);
4128
+ for (const [field2, at3] of HEAD_SETTINGS) {
4129
+ const found2 = head[at3];
4130
+ if (found2 && !site[field2]) site[field2] = { file: main, pointer: headPointer(at3), kind: "image", exists: true, value: found2.value };
4131
+ }
4132
+ }
4133
+ return { pages: out, routes: null, site: Object.keys(site).length ? site : null, refused };
2642
4134
  }
2643
4135
 
2644
- // supabase/functions/unbase-projects/settings.ts
2645
- var PAGE_FIELDS = {
2646
- title: { name: "titel", kind: "text" },
2647
- description: { name: "beschrijving", kind: "text" },
2648
- socialImage: { name: "ogImage", kind: "image" },
2649
- noindex: { name: "noindex", kind: "boolean" },
2650
- siteSearch: { name: "zoeken", kind: "boolean" }
4136
+ // supabase/functions/unbase-projects/settings-html.ts
4137
+ var HOME = "index.html";
4138
+ var PAGE_SETTINGS = [
4139
+ ["title", "title", "text"],
4140
+ ["description", "description", "text"],
4141
+ ["socialImage", "image", "image"],
4142
+ ["noindex", "noindex", "boolean"]
4143
+ ];
4144
+ var SITE_SETTINGS = [
4145
+ ["name", "title", "text"],
4146
+ ["description", "description", "text"],
4147
+ ["language", "language", "text"],
4148
+ ["faviconLight", "favicon", "image"],
4149
+ ["faviconDark", "faviconDark", "image"],
4150
+ ["socialImage", "image", "image"]
4151
+ ];
4152
+ var TAGGED = {
4153
+ title: /<title[\s>]/i,
4154
+ description: /<meta[^>]*name\s*=\s*["']?description/i,
4155
+ image: /<meta[^>]*property\s*=\s*["']?og:image["'\s>]/i,
4156
+ noindex: /<meta[^>]*name\s*=\s*["']?robots/i
2651
4157
  };
2652
- var SITE_FIELDS = {
2653
- name: { name: "naam", kind: "text" },
2654
- description: { name: "beschrijving", kind: "text" },
2655
- language: { name: "taal", kind: "text" },
2656
- faviconLight: { name: "favicon", kind: "image" },
2657
- faviconDark: { name: "faviconDonker", kind: "image" },
2658
- socialImage: { name: "ogImage", kind: "image" },
2659
- analyticsId: { name: "googleAnalytics", kind: "text" }
4158
+ function fieldsOf2(file, text, wanted) {
4159
+ const opts = headOptionsOf("html", file) ?? {};
4160
+ const head = readHead(text, opts);
4161
+ const hasHead = /<head[\s>]/i.test(text) && /<\/head/i.test(text);
4162
+ const out = {};
4163
+ for (const [field2, at3, kind] of wanted) {
4164
+ const found = head[at3];
4165
+ if (found) out[field2] = { file, pointer: headPointer(at3), kind, exists: true, value: found.value };
4166
+ else if (opts.add && hasHead && addable(at3, opts) && TAGGED[at3] && !TAGGED[at3].test(text)) out[field2] = { file, pointer: headPointer(at3), kind, exists: false, value: null };
4167
+ }
4168
+ return out;
4169
+ }
4170
+ async function htmlSettings(repo, appPath) {
4171
+ const root = appPath ? `${appPath}/` : "";
4172
+ const paths = repo.paths.filter((p) => p.startsWith(root)).map((p) => p.slice(root.length));
4173
+ const { pages: found } = discover({ framework: "html", paths, text: () => null });
4174
+ const pages = found.filter((p) => p.kind !== "template" && p.file).slice(0, MAX_ROUTE_FILES);
4175
+ if (!pages.length) return null;
4176
+ const texts = await Promise.all(pages.map((p) => repo.read(join(appPath, p.file))));
4177
+ const out = {};
4178
+ const refused = {};
4179
+ let site = null;
4180
+ pages.forEach((p, i) => {
4181
+ const text = texts[i];
4182
+ if (text === null) return;
4183
+ const fields = fieldsOf2(p.file, text, PAGE_SETTINGS);
4184
+ if (Object.keys(fields).length) out[p.path] = fields;
4185
+ else refused[p.path] = { file: p.file, reason: "unsupported" };
4186
+ if (p.file === HOME) {
4187
+ const own = fieldsOf2(p.file, text, SITE_SETTINGS);
4188
+ const there = Object.fromEntries(Object.entries(own).filter(([, f]) => f.exists));
4189
+ if (Object.keys(there).length) site = there;
4190
+ }
4191
+ });
4192
+ return { pages: out, routes: null, site, refused };
4193
+ }
4194
+
4195
+ // supabase/functions/unbase-projects/settings-next.ts
4196
+ var PAGES_APP = /^(src\/)?pages\/_app\.(jsx|tsx|js|ts)$/;
4197
+ var PAGES_DOCUMENT = /^(src\/)?pages\/_document\.(jsx|tsx|js|ts)$/;
4198
+ var TAGGED2 = {
4199
+ title: /<title[\s>]/,
4200
+ description: /name=["']description["']/,
4201
+ language: /<Html[^>]*\slang=/,
4202
+ favicon: /<link[^>]*rel=["'][^"']*\bicon\b/,
4203
+ faviconDark: /<link[^>]*rel=["'][^"']*\bicon\b[^>]*prefers-color-scheme/,
4204
+ image: /property=["']og:image["']/,
4205
+ noindex: /name=["']robots["']/
2660
4206
  };
2661
- var CONTENT = "src/content";
2662
- var SCHEMAS = `${CONTENT}/.schemas`;
2663
- var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
2664
- var AT_ONCE2 = 8;
2665
- var MAX_ROUTE_FILES = 300;
4207
+ function headFields(file, src, wanted) {
4208
+ const opts = headOptionsOf("next", file);
4209
+ if (!opts || !/<Head[\s>]/.test(src) || !/<\/Head\s*>/.test(src)) return null;
4210
+ const head = readHead(src, opts);
4211
+ const fields = {};
4212
+ const computed = {};
4213
+ for (const [field2, at3, kind] of wanted) {
4214
+ const there = head[at3];
4215
+ if (there) fields[field2] = { file, pointer: headPointer(at3), kind, exists: true, value: there.value };
4216
+ else if (TAGGED2[at3].test(src)) computed[field2] = "computed";
4217
+ else if (opts.add && (at3 === "title" || at3 === "description" || at3 === "image" || at3 === "noindex")) fields[field2] = { file, pointer: headPointer(at3), kind, exists: false, value: null };
4218
+ }
4219
+ return { fields, computed };
4220
+ }
4221
+ var ICON_FILE = /^(src\/)?app\/(favicon\.ico|icon\d*\.(ico|png|jpe?g|svg|gif|webp|avif)|icon\.(js|jsx|ts|tsx))$/;
2666
4222
  var NEXT_AT_ONCE = 16;
2667
4223
  function limited(n) {
2668
4224
  let running = 0;
@@ -2679,115 +4235,12 @@ function limited(n) {
2679
4235
  }
2680
4236
  };
2681
4237
  }
2682
- async function inTurns(items, work) {
2683
- const out = new Array(items.length);
2684
- let next = 0;
2685
- await Promise.all(
2686
- Array.from({ length: Math.min(AT_ONCE2, items.length) }, async () => {
2687
- while (next < items.length) {
2688
- const i = next++;
2689
- out[i] = await work(items[i]);
2690
- }
2691
- })
2692
- );
2693
- return out;
2694
- }
2695
- var parse = (text) => {
2696
- if (text === null) return null;
2697
- try {
2698
- return JSON.parse(text);
2699
- } catch {
2700
- return null;
2701
- }
2702
- };
2703
- function valueOf(v, kind) {
2704
- if (kind === "boolean") return typeof v === "boolean" ? String(v) : null;
2705
- return typeof v === "string" ? v : null;
2706
- }
2707
- function fieldsOf(names, data, allowed, file, base) {
2708
- const fields = {};
2709
- for (const [field2, { name, kind }] of Object.entries(names)) {
2710
- const value = valueOf(data?.[name], kind);
2711
- const there = data?.[name] !== void 0;
2712
- if (there && value === null) continue;
2713
- if (!there && !allowed[name]) continue;
2714
- fields[field2] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
2715
- }
2716
- return fields;
2717
- }
2718
- var VITE_DOCUMENT = "index.html";
2719
- var HEAD_SETTINGS = [
2720
- ["name", "title", "text"],
2721
- ["description", "description", "text"],
2722
- ["language", "language", "text"],
2723
- ["faviconLight", "favicon", "image"],
2724
- ["faviconDark", "faviconDark", "image"],
2725
- ["socialImage", "image", "image"]
2726
- ];
2727
- async function viteSettings(repo, appPath) {
2728
- const text = await repo.read(join(appPath, VITE_DOCUMENT));
2729
- if (text === null) return null;
2730
- const head = readHead(text);
2731
- const site = {};
2732
- for (const [field2, at3, kind] of HEAD_SETTINGS) {
2733
- const found = head[at3];
2734
- if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at3), kind, exists: true, value: found.value };
2735
- }
2736
- return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
2737
- }
2738
- async function readSettings(repo, appPath, framework = null) {
2739
- if (framework === "vite-react") return viteSettings(repo, appPath);
2740
- if (framework === "next") return nextSettings(repo, appPath);
2741
- const at3 = (p) => join(appPath, p);
2742
- const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at3(SCHEMAS)}/`) && p.endsWith(".schema.json"));
2743
- if (!schemaPaths.length) return null;
2744
- const named = (p) => p.slice(at3(SCHEMAS).length + 1, -".schema.json".length);
2745
- const schemas = /* @__PURE__ */ new Map();
2746
- const [legacyMap, map, ...read] = await inTurns([at3(`${SCHEMAS}/collecties.json`), at3(`${SCHEMAS}/collections.json`), ...schemaPaths], (p) => repo.read(p));
2747
- schemaPaths.forEach((p, i) => {
2748
- const s = parse(read[i] ?? null);
2749
- if (s && typeof s === "object") schemas.set(named(p), s);
2750
- });
2751
- const elsewhere = { ...parse(legacyMap ?? null) ?? {}, ...parse(map ?? null) ?? {} };
2752
- const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at3(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at3(SCHEMAS)}/`));
2753
- const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at3(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
2754
- const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
2755
- const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
2756
- const pages = {};
2757
- let routes = null;
2758
- if (routeCollection) {
2759
- const [collection, schema] = routeCollection;
2760
- const allowed = schema.properties.seo?.properties ?? {};
2761
- const files = filesOf(collection).slice(0, MAX_ROUTE_FILES);
2762
- const datas = await inTurns(files, async (p) => parse(await repo.read(p)));
2763
- files.forEach((file, i) => {
2764
- const data = datas[i];
2765
- if (!data || typeof data.pad !== "string" || !ROUTE.test(data.pad)) return;
2766
- const seo = data.seo && typeof data.seo === "object" && !Array.isArray(data.seo) ? data.seo : {};
2767
- pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
2768
- });
2769
- const dir = files[0] ? files[0].slice(appPath ? appPath.length + 1 : 0).replace(/\/[^/]+$/, "") : `${CONTENT}/${collection}`;
2770
- const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
2771
- routes = { dir, fields };
2772
- }
2773
- const siteCollection = [...schemas].find(([, s]) => (s["x-settings"] ?? s["x-instellingen"]) === "site");
2774
- let site = null;
2775
- const siteFile = siteCollection && filesOf(siteCollection[0])[0];
2776
- if (siteCollection && siteFile) {
2777
- const data = parse(await repo.read(siteFile));
2778
- if (data && typeof data === "object" && !Array.isArray(data)) {
2779
- site = fieldsOf(SITE_FIELDS, data, siteCollection[1].properties ?? {}, siteFile.slice(appPath ? appPath.length + 1 : 0), "");
2780
- }
2781
- }
2782
- if (!Object.keys(pages).length && !routes && !site) return null;
2783
- return { pages, routes, site };
2784
- }
2785
4238
  var NEXT_PAGE = /^(src\/)?app\/(.*\/)?page\.(tsx|ts|jsx|js)$/;
2786
4239
  var NEXT_ROOT_LAYOUT = /^(src\/)?app\/layout\.(tsx|ts|jsx|js)$/;
2787
4240
  var CMS_DEPTH = 2;
2788
4241
  var NEXT_PAGE_FIELDS = { title: "title", description: "description", socialImage: "socialImage", noindex: "noindex" };
2789
- var NEXT_SITE_FIELDS = { name: "name", description: "description", socialImage: "socialImage", language: "language" };
2790
- var settingOf = (file, f) => ({ file, pointer: f.pointer, kind: f.kind, exists: f.exists, value: f.value });
4242
+ var NEXT_SITE_FIELDS = { name: "name", description: "description", socialImage: "socialImage", language: "language", favicon: "faviconLight" };
4243
+ var settingOf2 = (file, f) => ({ file, pointer: f.pointer, kind: f.kind, exists: f.exists, value: f.value });
2791
4244
  var drawnImage = (file, have) => {
2792
4245
  const dir = file.replace(/[^/]*$/, "");
2793
4246
  return [...have].some((p) => p.startsWith(dir) && /^opengraph-image\d*\.[a-z]+$/.test(p.slice(dir.length)));
@@ -2806,7 +4259,7 @@ async function nextSettings(repo, appPath) {
2806
4259
  const { pages: found } = discover({ framework: "next", paths, text: () => null });
2807
4260
  const pages = found.filter((p) => p.kind === "file" && p.file).slice(0, MAX_ROUTE_FILES);
2808
4261
  const layout = paths.find((p) => NEXT_ROOT_LAYOUT.test(p)) ?? null;
2809
- if (!pages.some((p) => NEXT_PAGE.test(p.file)) && !layout) return null;
4262
+ if (!pages.length && !layout) return null;
2810
4263
  const readsCms = async (file, depth = CMS_DEPTH, seen = /* @__PURE__ */ new Set()) => {
2811
4264
  if (seen.has(file)) return false;
2812
4265
  seen.add(file);
@@ -2821,11 +4274,26 @@ async function nextSettings(repo, appPath) {
2821
4274
  const reasonOf = async (file, reason) => reason === "computed" && /\bgenerateMetadata\b/.test(await read(file) ?? "") && await readsCms(file) ? "cms" : reason;
2822
4275
  const out = {};
2823
4276
  const refused = {};
4277
+ const pagesRouter = pages.filter((p) => !NEXT_PAGE.test(p.file));
4278
+ const routerPages = await Promise.all(pagesRouter.map(async (p) => ({ p, src: await read(p.file) })));
4279
+ for (const { p, src } of routerPages) {
4280
+ const r = src === null ? null : headFields(p.file, src, [
4281
+ ["title", "title", "text"],
4282
+ ["description", "description", "text"],
4283
+ ["socialImage", "image", "image"],
4284
+ ["noindex", "noindex", "boolean"]
4285
+ ]);
4286
+ if (!r || !Object.keys(r.fields).length) {
4287
+ refused[p.path] = { file: p.file, reason: r && Object.keys(r.computed).length ? "computed" : "unsupported" };
4288
+ continue;
4289
+ }
4290
+ out[p.path] = r.fields;
4291
+ if (Object.keys(r.computed).length) refused[p.path] = { file: p.file, reason: "computed", fields: r.computed };
4292
+ }
2824
4293
  const [answers, layoutRead] = await Promise.all([
2825
4294
  Promise.all(
2826
- pages.map(async (p) => {
4295
+ pages.filter((p) => NEXT_PAGE.test(p.file)).map(async (p) => {
2827
4296
  const file = p.file;
2828
- if (!NEXT_PAGE.test(file)) return { p, file, read: null, reason: null };
2829
4297
  const src = await read(file);
2830
4298
  const r = src === null ? null : pageMetaFields(src);
2831
4299
  return { p, file, read: r, reason: r?.refused ? await reasonOf(file, r.refused) : null };
@@ -2850,7 +4318,7 @@ async function nextSettings(repo, appPath) {
2850
4318
  r.computed.socialImage = "computed";
2851
4319
  }
2852
4320
  const fields = {};
2853
- for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_PAGE_FIELDS[k]] = settingOf(file, f);
4321
+ for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_PAGE_FIELDS[k]] = settingOf2(file, f);
2854
4322
  out[p.path] = fields;
2855
4323
  const computed = Object.entries(r.computed).map(([k, why]) => [NEXT_PAGE_FIELDS[k], why]);
2856
4324
  if (computed.length) refused[p.path] = { file, reason: "computed", fields: Object.fromEntries(computed) };
@@ -2862,18 +4330,133 @@ async function nextSettings(repo, appPath) {
2862
4330
  delete r.fields.socialImage;
2863
4331
  r.computed.socialImage = "computed";
2864
4332
  }
4333
+ const iconFile = paths.some((p) => ICON_FILE.test(p));
4334
+ if (r && iconFile) delete r.fields.favicon;
2865
4335
  if (r) {
2866
4336
  const fields = {};
2867
- for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_SITE_FIELDS[k]] = settingOf(layout, f);
4337
+ for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_SITE_FIELDS[k]] = settingOf2(layout, f);
2868
4338
  if (Object.keys(fields).length) site = fields;
2869
4339
  const computed = Object.entries(r.computed).map(([k, why]) => [NEXT_SITE_FIELDS[k], why]);
4340
+ if (iconFile) computed.push(["faviconLight", "file"]);
2870
4341
  if (r.refused) refused.site = { file: layout, reason: layoutRead.reason ?? r.refused };
2871
4342
  else if (computed.length) refused.site = { file: layout, reason: "computed", fields: Object.fromEntries(computed) };
2872
4343
  }
2873
4344
  }
4345
+ if (!layout) {
4346
+ const app = paths.find((p) => PAGES_APP.test(p));
4347
+ const doc = paths.find((p) => PAGES_DOCUMENT.test(p));
4348
+ const [appSrc, docSrc] = await Promise.all([app ? read(app) : null, doc ? read(doc) : null]);
4349
+ const SITE_HEAD = [
4350
+ ["faviconLight", "favicon", "image"],
4351
+ ["faviconDark", "faviconDark", "image"],
4352
+ ["socialImage", "image", "image"]
4353
+ ];
4354
+ const fromApp = app && appSrc ? headFields(app, appSrc, [["name", "title", "text"], ["description", "description", "text"], ...SITE_HEAD]) : null;
4355
+ const fromDoc = doc && docSrc ? headFields(doc, docSrc, [["description", "description", "text"], ["language", "language", "text"], ...SITE_HEAD]) : null;
4356
+ const fields = {};
4357
+ for (const r of [fromApp, fromDoc]) for (const [k, f] of Object.entries(r?.fields ?? {})) if (f.exists && !fields[k]) fields[k] = f;
4358
+ if (Object.keys(fields).length) site = fields;
4359
+ }
2874
4360
  return { pages: out, routes: null, site, refused };
2875
4361
  }
2876
4362
 
4363
+ // supabase/functions/unbase-projects/settings-vite.ts
4364
+ var VITE_DOCUMENT2 = "index.html";
4365
+ var HEAD_SETTINGS2 = [
4366
+ ["name", "title", "text"],
4367
+ ["description", "description", "text"],
4368
+ ["language", "language", "text"],
4369
+ ["faviconLight", "favicon", "image"],
4370
+ ["faviconDark", "faviconDark", "image"],
4371
+ ["socialImage", "image", "image"]
4372
+ ];
4373
+ var PAGE_SETTINGS2 = [
4374
+ ["title", "title", "text"],
4375
+ ["description", "description", "text"],
4376
+ ["noindex", "noindex", "boolean"]
4377
+ ];
4378
+ var IN_CODE = {
4379
+ title: /<title[\s>]/i,
4380
+ description: /<meta[^>]*name=["']description/i,
4381
+ noindex: /<meta[^>]*name=["']robots/i
4382
+ };
4383
+ var ROUTER_FILE = /^(src\/)?((App|app|main|index|router|routes|Router|Routes|AppRoutes)\.(jsx|tsx|js|ts)|(routes|router)\/[^/]+\.(jsx|tsx|js|ts))$/;
4384
+ var MAX_ROUTER_FILES = 24;
4385
+ var READ_AT_ONCE2 = 16;
4386
+ function reactMajor(pkg) {
4387
+ if (!pkg) return null;
4388
+ try {
4389
+ const json = JSON.parse(pkg);
4390
+ const spec = json?.dependencies?.react ?? json?.devDependencies?.react ?? json?.peerDependencies?.react;
4391
+ const m = typeof spec === "string" ? /(\d+)(?:\.\d+)?/.exec(spec.replace(/^npm:react@/, "")) : null;
4392
+ return m ? Number(m[1]) : null;
4393
+ } catch {
4394
+ return null;
4395
+ }
4396
+ }
4397
+ async function viteSettings(repo, appPath) {
4398
+ const root = appPath ? `${appPath}/` : "";
4399
+ const paths = repo.paths.filter((p) => p.startsWith(root)).map((p) => p.slice(root.length));
4400
+ const [text, pkg] = await Promise.all([repo.read(join(appPath, VITE_DOCUMENT2)), repo.read(join(appPath, "package.json"))]);
4401
+ const site = {};
4402
+ if (text !== null) {
4403
+ const head = readHead(text);
4404
+ for (const [field2, at3, kind] of HEAD_SETTINGS2) {
4405
+ const found2 = head[at3];
4406
+ if (found2) site[field2] = { file: VITE_DOCUMENT2, pointer: headPointer(at3), kind, exists: true, value: found2.value };
4407
+ }
4408
+ }
4409
+ const files = /* @__PURE__ */ new Map();
4410
+ const readAll = async (list) => {
4411
+ for (let i = 0; i < list.length; i += READ_AT_ONCE2) {
4412
+ const batch = list.slice(i, i + READ_AT_ONCE2).filter((p) => !files.has(p));
4413
+ const got = await Promise.all(batch.map((p) => repo.read(join(appPath, p))));
4414
+ batch.forEach((p, j) => files.set(p, got[j] ?? null));
4415
+ }
4416
+ };
4417
+ const textOf2 = (p) => files.get(p) ?? null;
4418
+ await readAll(paths.filter((x) => ROUTER_FILE.test(x)).slice(0, MAX_ROUTER_FILES));
4419
+ const { pages: found } = discover({ framework: "vite-react", paths, text: textOf2 });
4420
+ const routes = found.filter((p) => p.kind === "route" && p.file && !p.reason).slice(0, MAX_ROUTE_FILES).map((p) => ({ path: p.path, file: p.file }));
4421
+ await readAll([...new Set(routes.map((r) => r.file))]);
4422
+ const react19 = (reactMajor(pkg) ?? 0) >= 19;
4423
+ const pages = {};
4424
+ const refused = {};
4425
+ for (const r of routes) {
4426
+ const src = textOf2(r.file);
4427
+ const opts = headOptionsOf("vite-react", r.file);
4428
+ if (src === null || !opts) continue;
4429
+ const head = readHead(src, opts);
4430
+ const addable2 = react19 && componentRootAt(src) !== null;
4431
+ const fields = {};
4432
+ const why = {};
4433
+ for (const [field2, at3, kind] of PAGE_SETTINGS2) {
4434
+ const there = head[at3];
4435
+ if (there) fields[field2] = { file: r.file, pointer: headPointer(at3), kind, exists: true, value: there.value };
4436
+ else if (IN_CODE[at3].test(src)) why[field2] = "computed";
4437
+ else if (addable2) fields[field2] = { file: r.file, pointer: headPointer(at3), kind, exists: false, value: null };
4438
+ else why[field2] = "unsupported";
4439
+ }
4440
+ why.socialImage = "site";
4441
+ if (Object.keys(fields).length) pages[r.path] = fields;
4442
+ if (Object.keys(why).length) refused[r.path] = { file: r.file, reason: Object.keys(fields).length ? "computed" : Object.values(why)[0] ?? "unsupported", fields: why };
4443
+ }
4444
+ if (!Object.keys(site).length && !Object.keys(pages).length) return null;
4445
+ return { pages, routes: null, site: Object.keys(site).length ? site : null, refused, previews: "site" };
4446
+ }
4447
+
4448
+ // supabase/functions/unbase-projects/settings.ts
4449
+ var SETTINGS_READERS = {
4450
+ astro: astroSettings,
4451
+ "vite-react": viteSettings,
4452
+ next: nextSettings,
4453
+ html: htmlSettings
4454
+ };
4455
+ async function readSettings(repo, appPath, framework = null) {
4456
+ const reader = framework && Object.hasOwn(SETTINGS_READERS, framework) ? SETTINGS_READERS[framework] : contentSettings;
4457
+ return reader(repo, appPath);
4458
+ }
4459
+
2877
4460
  // supabase/functions/unbase-projects/pages.ts
2878
4461
  var MAX_PAGES = 2e3;
2879
4462
  var registryFiles = (path) => /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html)$/.test(path) || /(^|\/)(opengraph-image|twitter-image|icon|apple-icon)\d*\.(png|jpe?g|gif|svg|ico|webp|avif)$/.test(path) || /^src\/content\/[\s\S]*\.json$/.test(path) || path === "package.json" || path === PAGE_FILE;
@@ -3109,8 +4692,8 @@ function edited(file, text, change) {
3109
4692
  for (const p of [...policies].sort((a, b) => b.start - a.start)) {
3110
4693
  const next = change(p.value);
3111
4694
  if (next === p.value) continue;
3112
- const literal2 = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
3113
- out = `${out.slice(0, p.start)}${literal2}${out.slice(p.end)}`;
4695
+ const literal4 = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
4696
+ out = `${out.slice(0, p.start)}${literal4}${out.slice(p.end)}`;
3114
4697
  }
3115
4698
  return out;
3116
4699
  }
@@ -3148,7 +4731,7 @@ function cspElsewhere(path, text) {
3148
4731
  // supabase/functions/_shared/binding.mjs
3149
4732
  var binding_exports = {};
3150
4733
  __export(binding_exports, {
3151
- ADAPTERS: () => ADAPTERS2,
4734
+ ADAPTERS: () => ADAPTERS3,
3152
4735
  ASTRO: () => ASTRO,
3153
4736
  GATE_COLLECTIONS: () => GATE_COLLECTIONS,
3154
4737
  GATE_PAGES: () => GATE_PAGES,
@@ -3168,6 +4751,7 @@ __export(binding_exports, {
3168
4751
  imageShows: () => imageShows,
3169
4752
  itemsIn: () => itemsIn,
3170
4753
  loaded: () => loaded,
4754
+ newFieldShows: () => newFieldShows,
3171
4755
  newItemShows: () => newItemShows,
3172
4756
  noCopiedContent: () => noCopiedContent,
3173
4757
  parseHtml: () => parseHtml,
@@ -3216,10 +4800,10 @@ var NEXT = {
3216
4800
  // next/image: `/_next/image?url=%2Fimages%2Fbike.jpg&w=640&q=75`.
3217
4801
  images: [{ query: "url" }]
3218
4802
  };
3219
- var ADAPTERS2 = { astro: ASTRO, next: NEXT };
4803
+ var ADAPTERS3 = { astro: ASTRO, next: NEXT };
3220
4804
  var CODE3 = /\.(astro|tsx?|jsx?|mts|mjs|vue|svelte|mdx?)$/;
3221
4805
  var CONFIG2 = /content\.config\./;
3222
- var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
4806
+ var escape3 = (s) => s.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
3223
4807
  var escapeText = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3224
4808
  var stripComments2 = (code) => code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
3225
4809
  function balanced(code, open) {
@@ -3240,13 +4824,13 @@ function balanced(code, open) {
3240
4824
  }
3241
4825
  return null;
3242
4826
  }
3243
- var literal = (s) => {
4827
+ var literal3 = (s) => {
3244
4828
  const t = s.trim();
3245
4829
  const m = t.match(/^(["'`])([\s\S]*)\1$/);
3246
4830
  return m && (m[1] === "`" || !m[2].includes(m[1])) ? m[2] : null;
3247
4831
  };
3248
4832
  var fixed = (s) => {
3249
- const v = literal(s);
4833
+ const v = literal3(s);
3250
4834
  return v !== null && !v.includes("${") ? v : null;
3251
4835
  };
3252
4836
  function argumentsOf(inner) {
@@ -3281,7 +4865,7 @@ function readerFunctionFiles(adapter, paths, root = "") {
3281
4865
  function readerFunctions({ files, adapter, root = "" }) {
3282
4866
  const out = [];
3283
4867
  for (const shape of helperShapes(adapter)) {
3284
- const calls = new RegExp(`\\b(${shape.calls.map(escape2).join("|")})\\s*\\(\\s*([^,)]+)\\s*(?:,\\s*([^,)]+))?`);
4868
+ const calls = new RegExp(`\\b(${shape.calls.map(escape3).join("|")})\\s*\\(\\s*([^,)]+)\\s*(?:,\\s*([^,)]+))?`);
3285
4869
  for (const { path, text } of files) {
3286
4870
  if (!path.startsWith(root)) continue;
3287
4871
  const rel = path.slice(root.length);
@@ -3296,7 +4880,7 @@ function readerFunctions({ files, adapter, root = "" }) {
3296
4880
  const call = body.match(calls);
3297
4881
  if (!call) continue;
3298
4882
  const which = (arg) => {
3299
- const lit = literal(arg);
4883
+ const lit = literal3(arg);
3300
4884
  if (lit !== null) return { name: lit };
3301
4885
  const i = params.indexOf(arg.trim());
3302
4886
  return i >= 0 ? { arg: i } : null;
@@ -3312,11 +4896,11 @@ function readerFunctions({ files, adapter, root = "" }) {
3312
4896
  }
3313
4897
  function directReads(shape, text) {
3314
4898
  if (shape.kind === "call") {
3315
- const re = new RegExp(`(?:${shape.names.map(escape2).join("|")})\\s*[${escape2(shape.open)}]\\s*["'\`]([^"'\`\\n]+)["'\`]`, "g");
4899
+ const re = new RegExp(`(?:${shape.names.map(escape3).join("|")})\\s*[${escape3(shape.open)}]\\s*["'\`]([^"'\`\\n]+)["'\`]`, "g");
3316
4900
  return Array.from(text.matchAll(re), (m) => m[1]);
3317
4901
  }
3318
4902
  if (shape.kind === "folder") {
3319
- const root = escape2(shape.root);
4903
+ const root = escape3(shape.root);
3320
4904
  const re = new RegExp(`["'\`]${root}["'\`]\\s*,\\s*["'\`]([^"'\`\\n]+)["'\`]|["'\`]${root}/([^"'\`/\\n]+)["'\`/]`, "g");
3321
4905
  return Array.from(text.matchAll(re), (m) => m[1] ?? m[2]);
3322
4906
  }
@@ -3325,9 +4909,9 @@ function directReads(shape, text) {
3325
4909
  function readsPattern(adapter, collection) {
3326
4910
  const parts = [];
3327
4911
  for (const s of shapes(adapter)) {
3328
- const name = escape2(collection);
3329
- if (s.kind === "call") parts.push(`(?:${s.names.map(escape2).join("|")})\\s*[${escape2(s.open)}]\\s*["'\`]${name}["'\`]`);
3330
- if (s.kind === "folder") parts.push(`["'\`]${escape2(s.root)}["'\`]\\s*,\\s*["'\`]${name}["'\`]|["'\`]${escape2(s.root)}/${name}["'\`/]`);
4912
+ const name = escape3(collection);
4913
+ if (s.kind === "call") parts.push(`(?:${s.names.map(escape3).join("|")})\\s*[${escape3(s.open)}]\\s*["'\`]${name}["'\`]`);
4914
+ if (s.kind === "folder") parts.push(`["'\`]${escape3(s.root)}["'\`]\\s*,\\s*["'\`]${name}["'\`]|["'\`]${escape3(s.root)}/${name}["'\`/]`);
3331
4915
  }
3332
4916
  return new RegExp(parts.length ? parts.join("|") : "(?!)");
3333
4917
  }
@@ -3340,7 +4924,7 @@ function reads({ files, adapter, collections, functions }) {
3340
4924
  if (!collectionName(r.collection) || keep && !keep.has(r.collection)) return;
3341
4925
  out.set(JSON.stringify([r.file, r.collection, r.via, r.call ?? "", r.entry ?? ""]), r);
3342
4926
  };
3343
- const callOf = helpers.length ? new RegExp(`(?<![\\w$.])(${[...new Set(helpers.map((h) => h.call))].map(escape2).join("|")})\\s*\\(`, "g") : null;
4927
+ const callOf = helpers.length ? new RegExp(`(?<![\\w$.])(${[...new Set(helpers.map((h) => h.call))].map(escape3).join("|")})\\s*\\(`, "g") : null;
3344
4928
  for (const { path, text } of files) {
3345
4929
  if (!CODE3.test(path) || CONFIG2.test(path) || !text) continue;
3346
4930
  for (const s of shapes(adapter)) for (const name of directReads(s, text)) add({ file: path, collection: name, via: s.kind });
@@ -3722,11 +5306,11 @@ function elementsOf(html) {
3722
5306
  };
3723
5307
  const body = find(root, "body") ?? root;
3724
5308
  const out = [];
3725
- const outside = (e) => OUT.test(e.tag) || e.attrs.id === "comment-modus" || e.attrs.id === "comment-modus-schil" || "data-cm-ignore" in e.attrs || "data-cm-negeer" in e.attrs || "data-unbase-layer" in e.attrs;
5309
+ const outside2 = (e) => OUT.test(e.tag) || e.attrs.id === "comment-modus" || e.attrs.id === "comment-modus-schil" || "data-cm-ignore" in e.attrs || "data-cm-negeer" in e.attrs || "data-unbase-layer" in e.attrs;
3726
5310
  const walk = (n, place, depth) => {
3727
5311
  const seen = /* @__PURE__ */ new Map();
3728
5312
  for (const c of n.children) {
3729
- if (typeof c === "string" || outside(c)) continue;
5313
+ if (typeof c === "string" || outside2(c)) continue;
3730
5314
  const k = seen.get(c.tag) ?? 0;
3731
5315
  seen.set(c.tag, k + 1);
3732
5316
  const at3 = `${place ? `${place}/` : ""}${c.tag}:${k}`;
@@ -3898,7 +5482,7 @@ function fieldUse({ text, fields }) {
3898
5482
  if (FIELD_NAME.test(name)) taken.add(name);
3899
5483
  }
3900
5484
  }
3901
- return (fields ?? []).map((f) => f.key).filter((k, i, all) => FIELD_NAME.test(k) && all.indexOf(k) === i).filter((k) => taken.has(k) || new RegExp(`\\??\\.\\s*${escape2(k)}(?![\\w$])|\\[\\s*["'\`]${escape2(k)}["'\`]\\s*\\]`).test(code));
5485
+ return (fields ?? []).map((f) => f.key).filter((k, i, all) => FIELD_NAME.test(k) && all.indexOf(k) === i).filter((k) => taken.has(k) || new RegExp(`\\??\\.\\s*${escape3(k)}(?![\\w$])|\\[\\s*["'\`]${escape3(k)}["'\`]\\s*\\]`).test(code));
3902
5486
  }
3903
5487
  var isCode = (path) => CODE3.test(path) && !CONFIG2.test(path);
3904
5488
  function importedBy(importers) {
@@ -4059,16 +5643,18 @@ function tagsIn2(text) {
4059
5643
  var untag = (text) => String(text ?? "").replace(TAG, "").replace(TAG_CHAR, "").replace(/\uDB40(?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC01-\uDC7F]/g, "");
4060
5644
  function tagItem({ collection, id, data, fields = [] }) {
4061
5645
  const esc = (k) => k.replace(/~/g, "~0").replace(/\//g, "~1");
4062
- const walk = (value, pointer, field2) => {
5646
+ const walk = (value, pointer, field2, picture = false) => {
4063
5647
  if (typeof value === "string") {
4064
5648
  const v = value.trim();
4065
5649
  if (!field2 || !TAGGED_TYPES.includes(field2.type) || !v || /[\u{E0000}-\u{E007F}]/u.test(value) || /^(?:[a-z][a-z0-9+.-]*:|\/|#|www\.)/i.test(v)) return value;
5650
+ if (picture || !new RegExp("\\p{L}", "u").test(v)) return value;
4066
5651
  const tag = tagOf({ collection, id, pointer });
4067
5652
  return tag ? value + tag : value;
4068
5653
  }
4069
5654
  if (Array.isArray(value)) return field2?.type === "list" ? value.map((v, i) => walk(v, `${pointer}/${i}`, { type: "group", fields: field2.fields ?? [] })) : value;
4070
5655
  if (value && typeof value === "object" && field2 && (field2.type === "group" || field2.type === "item")) {
4071
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v, `${pointer}/${esc(k)}`, (field2.fields ?? []).find((f) => f.key === k) ?? null)]));
5656
+ const pictureGroup = field2.type === "group" && (field2.fields ?? []).some((f) => f.type === "image");
5657
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v, `${pointer}/${esc(k)}`, (field2.fields ?? []).find((f) => f.key === k) ?? null, pictureGroup)]));
4072
5658
  }
4073
5659
  return value;
4074
5660
  };
@@ -4250,20 +5836,42 @@ function itemsIn({ html, collections, adapter, uses = {}, formats = [] }) {
4250
5836
  };
4251
5837
  const bind = (it, pointer, extra = {}) => ({ binding: { collection: it.collection, item: it.id, field: pointer }, key: keyOf(it, pointer), ...extra });
4252
5838
  const ownText = (node) => node.children.filter((c) => typeof c === "string").join("");
5839
+ const escKey = (k) => k.replace(/~/g, "~0").replace(/\//g, "~1");
5840
+ const slots = (it, type) => {
5841
+ const out2 = [];
5842
+ for (const f of it.fields) {
5843
+ if (!reads2(it.collection, f.key)) continue;
5844
+ if (f.type === type) out2.push({ pointer: `/${escKey(f.key)}`, value: it.data?.[f.key] });
5845
+ else if (f.type === "group") {
5846
+ for (const g of f.fields ?? []) if (g.type === type) out2.push({ pointer: `/${escKey(f.key)}/${escKey(g.key)}`, value: it.data?.[f.key]?.[g.key] });
5847
+ }
5848
+ }
5849
+ return out2.map((s) => ({ ...s, value: s.value && typeof s.value === "object" && typeof s.value.src === "string" ? s.value.src : s.value }));
5850
+ };
5851
+ const itemOfNode = (node) => {
5852
+ const own = new Set(Object.values(node.attrs).flatMap((v) => tagsIn2(v).map((r) => `${r.collection}/${r.id}`)));
5853
+ return own.size === 1 ? [...own][0] : own.size ? null : cardItem(node.parent);
5854
+ };
4253
5855
  for (const e of elementsOf(root)) {
4254
5856
  const node = e.node;
5857
+ if (node.tag === "a" && typeof node.attrs.href === "string" && node.attrs.href.trim()) {
5858
+ const href = untag(node.attrs.href).trim();
5859
+ const itemKey2 = itemOfNode(node);
5860
+ const it2 = itemKey2 ? items.get(itemKey2) : null;
5861
+ const fit = it2 ? slots(it2, "link").filter((s) => typeof s.value === "string" && s.value.trim() === href) : [];
5862
+ if (it2 && fit.length === 1 && it2.file) stamp(node, { "data-unbase-cms": `${it2.collection}/${it2.id}`, "data-unbase-cms-href": keyOf(it2, fit[0].pointer) });
5863
+ }
4255
5864
  if (node.tag === "img") {
4256
5865
  const src = node.attrs.src ?? "";
4257
5866
  if (!src) continue;
4258
- const own2 = new Set(Object.values(node.attrs).flatMap((v) => tagsIn2(v).map((r) => `${r.collection}/${r.id}`)));
4259
- const itemKey2 = own2.size === 1 ? [...own2][0] : own2.size ? null : cardItem(node.parent);
4260
- const showing = (it3) => it3.fields.filter((f) => f.type === "image" && reads2(it3.collection, f.key) && imageShows(src, it3.data?.[f.key], adapter)).map((f) => f.key);
5867
+ const itemKey2 = itemOfNode(node);
5868
+ const showing = (it3) => slots(it3, "image").filter((s) => imageShows(src, s.value, adapter)).map((s) => s.pointer);
4261
5869
  const it2 = itemKey2 ? items.get(itemKey2) : null;
4262
5870
  if (it2) {
4263
5871
  const fit = showing(it2);
4264
- if (fit.length === 1) list(e, { text: "", ...bind(it2, `/${fit[0]}`, { image: true }) }, it2);
5872
+ if (fit.length === 1) list(e, { text: "", ...bind(it2, fit[0], { image: true }) }, it2);
4265
5873
  else if (fit.length > 1) list(e, { text: "", reason: "ambiguous", candidates: fit.length }, it2);
4266
- else if (it2.fields.some((f) => f.type === "image" && reads2(it2.collection, f.key))) list(e, { text: "", reason: "unproven" }, it2);
5874
+ else if (slots(it2, "image").length) list(e, { text: "", reason: "unproven" }, it2);
4267
5875
  } else {
4268
5876
  const anywhere = [...items.values()].flatMap((x) => showing(x));
4269
5877
  if (anywhere.length) list(e, { text: "", reason: anywhere.length > 1 ? "ambiguous" : "unproven", candidates: anywhere.length }, null);
@@ -4345,6 +5953,40 @@ function itemsIn({ html, collections, adapter, uses = {}, formats = [] }) {
4345
5953
  const bound = elements.filter((e) => e.binding).length;
4346
5954
  return { html: untag(out), elements, bound, unbound: elements.length - bound, cards };
4347
5955
  }
5956
+ var addedKind = (f) => TAGGED_TYPES.includes(f.type) ? "text" : f.type === "image" || f.type === "group" && (f.fields ?? []).some((g) => g.type === "image") ? "image" : null;
5957
+ function newFieldShows({ collection, added, draft, renders, collections, adapter, uses = {}, formats = [] }) {
5958
+ const withItem = collections.map((c) => c.name === collection ? { ...c, items: [...(c.items ?? []).filter((i) => i.id !== draft.id), { id: draft.id, file: draft.file, data: draft.data }] } : c);
5959
+ const pages = renders.filter((r) => typeof r.html === "string" && r.html.length > 0);
5960
+ const bound = new Map(pages.map((p) => [p.path, itemsIn({ html: p.html, collections: withItem, adapter, uses, formats }).elements]));
5961
+ const textOfPage = new Map(pages.map((p) => [p.path, untag(wholeText(parseHtml(p.html)))]));
5962
+ const stemOfPath = (p) => (String(p ?? "").split(/[?#]/)[0].split("/").pop() ?? "").replace(/\.[^.]+$/, "").toLowerCase();
5963
+ const pictureAt = (f) => {
5964
+ const v = draft.data?.[f.key];
5965
+ if (f.type === "image") return typeof v === "string" ? v : typeof v?.src === "string" ? v.src : null;
5966
+ const sub = (f.fields ?? []).find((g) => g.type === "image");
5967
+ return sub && typeof v?.[sub.key] === "string" ? v[sub.key] : null;
5968
+ };
5969
+ return added.map((f) => {
5970
+ const kind = addedKind(f);
5971
+ const base = { key: f.key, type: f.type, bound: false, live: false, pages: [] };
5972
+ if (!kind) return { ...base, shows: null, reason: "unchecked" };
5973
+ const value = kind === "text" ? draft.data?.[f.key] : pictureAt(f);
5974
+ if (typeof value !== "string" || !value.trim()) return { ...base, shows: null, reason: "no-test-value" };
5975
+ if (!pages.length) return { ...base, shows: null, reason: "not-rendered" };
5976
+ const shown2 = [];
5977
+ let isBound = false;
5978
+ let live = false;
5979
+ for (const p of pages) {
5980
+ const mine = (bound.get(p.path) ?? []).filter((e) => e.binding && e.binding.collection === collection && e.binding.item === draft.id && (e.binding.field === `/${f.key}` || e.binding.field.startsWith(`/${f.key}/`)));
5981
+ const seen = mine.length > 0 || (kind === "text" ? (textOfPage.get(p.path) ?? "").includes(collapse(untag(value))) : [...p.html.matchAll(/<(?:img|source)\b[^>]*>/gi)].some((m) => m[0].toLowerCase().includes(stemOfPath(value))));
5982
+ if (!seen) continue;
5983
+ shown2.push(p.path);
5984
+ if (mine.length) isBound = true;
5985
+ if (mine.some((e) => e.exact)) live = true;
5986
+ }
5987
+ return { ...base, shows: shown2.length > 0, bound: isBound, live, pages: shown2, ...shown2.length && !isBound ? { reason: "unbound" } : {} };
5988
+ });
5989
+ }
4348
5990
  export {
4349
5991
  binding_exports as binding,
4350
5992
  pages_core_exports as core,