@unbase-app/cli 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +31 -6
- package/README.md +104 -18
- package/agents/astro.md +20 -3
- package/agents/next.md +21 -1
- package/agents/vite-react.md +19 -1
- package/bin/unbase.mjs +53 -3
- package/lib/analytics.mjs +142 -0
- package/lib/args.mjs +19 -7
- package/lib/compare.mjs +18 -11
- package/lib/config-edit.mjs +8 -3
- package/lib/frameworks/astro.mjs +55 -5
- package/lib/frameworks/index.mjs +7 -0
- package/lib/frameworks/next.mjs +41 -4
- package/lib/frameworks/vite-react.mjs +36 -6
- package/lib/init.mjs +25 -4
- package/lib/next-config.mjs +12 -1
- package/lib/page.mjs +193 -0
- package/lib/readers.mjs +915 -34
- package/lib/uninstall.mjs +21 -3
- package/lib/versions.mjs +18 -8
- package/lib/vite-config.mjs +4 -2
- package/package.json +4 -3
package/lib/readers.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
// readSettings supabase/functions/unbase-projects/settings.ts (read_settings)
|
|
8
8
|
// registryOf supabase/functions/unbase-projects/pages.ts (list_pages)
|
|
9
9
|
// core supabase/functions/_shared/pages-core.mjs (= kit/pages/core.mjs)
|
|
10
|
+
// csp supabase/functions/_shared/csp.ts (analytics' collector in a CSP)
|
|
10
11
|
// ============================================================================
|
|
11
12
|
var __defProp = Object.defineProperty;
|
|
12
13
|
var __export = (target, all) => {
|
|
@@ -184,6 +185,7 @@ var frameworkPackage = (id) => FRAMEWORK_PACKAGES.find((f) => f.id === id) ?? nu
|
|
|
184
185
|
|
|
185
186
|
// supabase/functions/unbase-projects/detect.ts
|
|
186
187
|
var ADAPTERS = [astro];
|
|
188
|
+
var HTML = { id: "html", name: "HTML", version: null, major: null };
|
|
187
189
|
var FRAMEWORKS = [
|
|
188
190
|
{ id: "astro", name: "Astro", dep: "astro", public: "PUBLIC_" },
|
|
189
191
|
{ id: "next", name: "Next.js", dep: "next", public: "NEXT_PUBLIC_" },
|
|
@@ -256,8 +258,8 @@ function packageManager(repo, appPath, root) {
|
|
|
256
258
|
const found = LOCKFILES.find(([file]) => repo.paths.includes(join(folder, file)));
|
|
257
259
|
if (found) return found[1];
|
|
258
260
|
}
|
|
259
|
-
const
|
|
260
|
-
return typeof
|
|
261
|
+
const field2 = root?.pkg.packageManager;
|
|
262
|
+
return typeof field2 === "string" ? field2.split("@")[0] || null : null;
|
|
261
263
|
}
|
|
262
264
|
function cmsOf(repo, app, root) {
|
|
263
265
|
const deps = { ...root?.deps ?? {}, ...app.deps };
|
|
@@ -393,7 +395,7 @@ async function detect(repo, branch, truncated, appPath) {
|
|
|
393
395
|
} else {
|
|
394
396
|
return empty;
|
|
395
397
|
}
|
|
396
|
-
if (!chosen) return { ...empty, app_path: "" };
|
|
398
|
+
if (!chosen) return { ...empty, app_path: "", framework: !all.length && repo.paths.includes("index.html") ? HTML : null };
|
|
397
399
|
const fw = frameworkOf(chosen.deps);
|
|
398
400
|
const adapter = fw ? ADAPTERS.find((a) => a.framework === fw.id) ?? null : null;
|
|
399
401
|
const found = adapter ? await adapter.detect(repo, chosen) : { text: null, site: null, project: null };
|
|
@@ -419,7 +421,7 @@ async function detect(repo, branch, truncated, appPath) {
|
|
|
419
421
|
}
|
|
420
422
|
|
|
421
423
|
// supabase/functions/_shared/html-head.ts
|
|
422
|
-
var headPointer = (
|
|
424
|
+
var headPointer = (field2) => `/head/${field2}`;
|
|
423
425
|
var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
424
426
|
function decodeValue(raw) {
|
|
425
427
|
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();
|
|
@@ -525,10 +527,10 @@ function readHead(html) {
|
|
|
525
527
|
if (image) out.image = image;
|
|
526
528
|
const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
|
|
527
529
|
const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
|
|
528
|
-
for (const [
|
|
530
|
+
for (const [field2, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
|
|
529
531
|
const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
|
|
530
532
|
const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
|
|
531
|
-
if (href && href.value.trim() && plain(href.value)) out[
|
|
533
|
+
if (href && href.value.trim() && plain(href.value)) out[field2] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
|
|
532
534
|
}
|
|
533
535
|
return out;
|
|
534
536
|
}
|
|
@@ -539,7 +541,9 @@ __export(pages_core_exports, {
|
|
|
539
541
|
DRAFTABLE: () => DRAFTABLE,
|
|
540
542
|
KIT: () => KIT,
|
|
541
543
|
KITS: () => KITS,
|
|
544
|
+
PAGE_ACTION_FRAMEWORKS: () => PAGE_ACTION_FRAMEWORKS,
|
|
542
545
|
PAGE_FILE: () => PAGE_FILE,
|
|
546
|
+
REDIRECTS_SINCE: () => REDIRECTS_SINCE,
|
|
543
547
|
deployContext: () => deployContext,
|
|
544
548
|
discover: () => discover,
|
|
545
549
|
draftCheck: () => draftCheck,
|
|
@@ -548,19 +552,27 @@ __export(pages_core_exports, {
|
|
|
548
552
|
importGraph: () => importGraph,
|
|
549
553
|
kitFiles: () => kitFiles,
|
|
550
554
|
kitInstalled: () => kitInstalled,
|
|
555
|
+
kitRedirects: () => kitRedirects,
|
|
551
556
|
leakPrints: () => leakPrints,
|
|
552
557
|
leaksIn: () => leaksIn,
|
|
553
558
|
linksTo: () => linksTo,
|
|
554
559
|
listTools: () => listTools,
|
|
560
|
+
lowestVersion: () => lowestVersion,
|
|
555
561
|
mediaGenerators: () => mediaGenerators,
|
|
556
562
|
normalisePath: () => normalisePath,
|
|
557
563
|
ownedContent: () => ownedContent,
|
|
564
|
+
pageActions: () => pageActions,
|
|
558
565
|
parsePageFile: () => parsePageFile,
|
|
566
|
+
planPage: () => planPage,
|
|
567
|
+
redirectsFor: () => redirectsFor,
|
|
559
568
|
removeRoutes: () => removeRoutes,
|
|
560
569
|
resolveImport: () => resolveImport,
|
|
561
570
|
segmentFiles: () => segmentFiles,
|
|
562
571
|
sentences: () => sentences,
|
|
572
|
+
siteRedirects: () => siteRedirects,
|
|
573
|
+
slugOf: () => slugOf,
|
|
563
574
|
stripComments: () => stripComments,
|
|
575
|
+
validAddress: () => validAddress,
|
|
564
576
|
withoutInContentMap: () => withoutInContentMap,
|
|
565
577
|
withoutInPageList: () => withoutInPageList,
|
|
566
578
|
withoutInSitemap: () => withoutInSitemap
|
|
@@ -583,11 +595,11 @@ function normalisePath(p) {
|
|
|
583
595
|
return s || "/";
|
|
584
596
|
}
|
|
585
597
|
function parsePageFile(text) {
|
|
586
|
-
if (text == null) return { ok: true, exists: false, pages: {} };
|
|
598
|
+
if (text == null) return { ok: true, exists: false, pages: {}, redirects: {} };
|
|
587
599
|
const fail = (error) => ({ ok: (
|
|
588
600
|
/** @type {const} */
|
|
589
601
|
false
|
|
590
|
-
), exists: true, error, pages: {} });
|
|
602
|
+
), exists: true, error, pages: {}, redirects: {} });
|
|
591
603
|
let data;
|
|
592
604
|
try {
|
|
593
605
|
data = JSON.parse(text);
|
|
@@ -602,10 +614,21 @@ function parsePageFile(text) {
|
|
|
602
614
|
if (!address2.startsWith("/")) return fail(`${address2}: an address starts with /`);
|
|
603
615
|
if (!isObject(entry)) return fail(`${address2}: not an object`);
|
|
604
616
|
if (entry.draft !== void 0 && typeof entry.draft !== "boolean") return fail(`${address2}: draft is true or false`);
|
|
605
|
-
|
|
617
|
+
if (entry.name !== void 0 && typeof entry.name !== "string") return fail(`${address2}: name is text`);
|
|
618
|
+
out[normalisePath(address2)] = { ...entry.draft === void 0 ? {} : { draft: entry.draft }, ...entry.name ? { name: entry.name } : {} };
|
|
606
619
|
}
|
|
607
|
-
|
|
620
|
+
const redirects = data.redirects ?? {};
|
|
621
|
+
if (!isObject(redirects)) return fail("`redirects` is not an object");
|
|
622
|
+
const sends2 = {};
|
|
623
|
+
for (const [from, to] of Object.entries(redirects)) {
|
|
624
|
+
if (!from.startsWith("/")) return fail(`redirects: ${from}: an address starts with /`);
|
|
625
|
+
if (typeof to !== "string" || !to.startsWith("/")) return fail(`redirects: ${from}: goes to an address that starts with /`);
|
|
626
|
+
if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
|
|
627
|
+
sends2[normalisePath(from)] = normalisePath(to);
|
|
628
|
+
}
|
|
629
|
+
return { ok: true, exists: true, pages: out, redirects: sends2 };
|
|
608
630
|
}
|
|
631
|
+
var REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
|
|
609
632
|
var draftPaths = (file) => Object.keys(file.pages).filter((p) => file.pages[p].draft === true).sort();
|
|
610
633
|
var CONTEXTS = /* @__PURE__ */ new Set(["production", "preview", "development"]);
|
|
611
634
|
function deployContext({ env = {}, command = "build" } = {}) {
|
|
@@ -1068,7 +1091,7 @@ function siteReads(paths, text, importers) {
|
|
|
1068
1091
|
if (target.endsWith(".json")) push(jsonOf, f, target);
|
|
1069
1092
|
}
|
|
1070
1093
|
}
|
|
1071
|
-
const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports };
|
|
1094
|
+
const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads.byName };
|
|
1072
1095
|
siteReadsOf.set(importers, site);
|
|
1073
1096
|
return site;
|
|
1074
1097
|
}
|
|
@@ -1331,6 +1354,624 @@ function withoutInContentMap(json, files) {
|
|
|
1331
1354
|
}
|
|
1332
1355
|
return JSON.stringify(map);
|
|
1333
1356
|
}
|
|
1357
|
+
var PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
|
|
1358
|
+
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" };
|
|
1359
|
+
function lowestVersion(spec) {
|
|
1360
|
+
if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
|
|
1361
|
+
const m = spec.trim().replace(/^[\^~>=v\s]+/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
|
1362
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
1363
|
+
}
|
|
1364
|
+
var atLeast = (have, want) => {
|
|
1365
|
+
for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] > want[i];
|
|
1366
|
+
return true;
|
|
1367
|
+
};
|
|
1368
|
+
function kitRedirects({ framework, text }) {
|
|
1369
|
+
if (!kitInstalled({ framework, text })) return false;
|
|
1370
|
+
let pkg = null;
|
|
1371
|
+
try {
|
|
1372
|
+
pkg = JSON.parse(text("package.json") ?? "null");
|
|
1373
|
+
} catch {
|
|
1374
|
+
}
|
|
1375
|
+
const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
|
|
1376
|
+
return (KITS[String(framework)] ?? []).some((name) => {
|
|
1377
|
+
const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
|
|
1378
|
+
const since = REDIRECTS_SINCE[name];
|
|
1379
|
+
const have = lowestVersion(spec);
|
|
1380
|
+
return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
1383
|
+
function slugOf(name) {
|
|
1384
|
+
return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
|
|
1385
|
+
}
|
|
1386
|
+
var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
|
|
1387
|
+
function validAddress(p) {
|
|
1388
|
+
const at2 = normalisePath(p);
|
|
1389
|
+
if (at2.length > 200) return false;
|
|
1390
|
+
if (at2 === "/") return true;
|
|
1391
|
+
return at2.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
|
|
1392
|
+
}
|
|
1393
|
+
var under = (path, at2) => at2 === "/" ? path !== "/" : path.startsWith(`${at2}/`);
|
|
1394
|
+
var within2 = (path, at2) => path === at2 || under(path, at2);
|
|
1395
|
+
var moveAddress = (path, from, to) => path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`);
|
|
1396
|
+
var parentOf = (p) => p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/")));
|
|
1397
|
+
var lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
|
|
1398
|
+
function siteRedirects({ framework, text }) {
|
|
1399
|
+
const out = /* @__PURE__ */ new Set();
|
|
1400
|
+
try {
|
|
1401
|
+
const v = JSON.parse(text("vercel.json") ?? "null");
|
|
1402
|
+
for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
|
|
1403
|
+
} catch {
|
|
1404
|
+
}
|
|
1405
|
+
for (const c of CONFIGS[String(framework)] ?? []) {
|
|
1406
|
+
const src = stripComments(text(c) ?? "");
|
|
1407
|
+
if (framework === "astro") {
|
|
1408
|
+
const at2 = src.search(/\bredirects\s*:\s*\{/);
|
|
1409
|
+
if (at2 < 0) continue;
|
|
1410
|
+
const body = braced(src, src.indexOf("{", at2)) ?? "";
|
|
1411
|
+
for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
|
|
1412
|
+
} else if (framework === "next") {
|
|
1413
|
+
for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
return out;
|
|
1417
|
+
}
|
|
1418
|
+
function sends(source, path) {
|
|
1419
|
+
if (REST.test(source)) {
|
|
1420
|
+
const base = normalisePath(source.replace(REST, ""));
|
|
1421
|
+
return within2(path, base);
|
|
1422
|
+
}
|
|
1423
|
+
return source === path || matchesPattern(source, path);
|
|
1424
|
+
}
|
|
1425
|
+
function matchesPattern(source, path) {
|
|
1426
|
+
if (!/\[|:/.test(source)) return false;
|
|
1427
|
+
const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => i % 2 ? part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+" : escape(part)).join("")}$`);
|
|
1428
|
+
return re.test(path);
|
|
1429
|
+
}
|
|
1430
|
+
function changedPageFile(before, change) {
|
|
1431
|
+
let data = {};
|
|
1432
|
+
try {
|
|
1433
|
+
data = before == null ? {} : JSON.parse(before) ?? {};
|
|
1434
|
+
} catch {
|
|
1435
|
+
data = {};
|
|
1436
|
+
}
|
|
1437
|
+
if (!isObject(data)) data = {};
|
|
1438
|
+
if (!isObject(data.pages)) data.pages = {};
|
|
1439
|
+
const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
|
|
1440
|
+
change(data.pages, redirects);
|
|
1441
|
+
for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
|
|
1442
|
+
if (Object.keys(redirects).length) data.redirects = redirects;
|
|
1443
|
+
else delete data.redirects;
|
|
1444
|
+
const empty = !Object.keys(data.pages).length && !data.redirects && Object.keys(data).length === 1;
|
|
1445
|
+
if (before == null && empty) return null;
|
|
1446
|
+
const after = `${JSON.stringify(data, null, 2)}
|
|
1447
|
+
`;
|
|
1448
|
+
return after === before ? null : after;
|
|
1449
|
+
}
|
|
1450
|
+
function repoint(redirects, from, to) {
|
|
1451
|
+
for (const [source, dest] of Object.entries(redirects)) {
|
|
1452
|
+
const rest = REST.test(dest);
|
|
1453
|
+
const base = rest ? normalisePath(dest.replace(REST, "")) : dest;
|
|
1454
|
+
if (within2(base, from)) redirects[source] = rest ? `${moveAddress(base, from, to)}${dest.slice(dest.lastIndexOf("/"))}` : moveAddress(base, from, to);
|
|
1455
|
+
}
|
|
1456
|
+
for (const [source, dest] of Object.entries(redirects)) {
|
|
1457
|
+
const base = REST.test(source) ? normalisePath(source.replace(REST, "")) : source;
|
|
1458
|
+
if (to && within2(to, base) && sends(source, to)) delete redirects[source];
|
|
1459
|
+
else if (source === dest) delete redirects[source];
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
var SPECIFIER = /((?:\bfrom|\bimport|\brequire)\s*\(?\s*)(["'])([^"'\n]+)\2/g;
|
|
1463
|
+
var MD_LAYOUT = /^(layout:\s*)(["']?)([^"'\n]+?)\2\s*$/m;
|
|
1464
|
+
var relativeSpec = (fromFile, target) => {
|
|
1465
|
+
const from = dirname(fromFile).split("/").filter(Boolean);
|
|
1466
|
+
const to = target.split("/");
|
|
1467
|
+
let i = 0;
|
|
1468
|
+
while (i < from.length && i < to.length - 1 && from[i] === to[i]) i++;
|
|
1469
|
+
const up = from.length - i;
|
|
1470
|
+
const rest = to.slice(i).join("/");
|
|
1471
|
+
return up ? `${"../".repeat(up)}${rest}` : `./${rest}`;
|
|
1472
|
+
};
|
|
1473
|
+
function specFor(fromFile, target, old, oldTarget) {
|
|
1474
|
+
const index = /\/index\.[a-z]+$/.test(oldTarget) && !/\/index(\.[a-z]+)?$/.test(old);
|
|
1475
|
+
const ext = /\.[a-z]+$/.test(old.split("/").pop() ?? "") && old.endsWith(oldTarget.slice(oldTarget.lastIndexOf(".")));
|
|
1476
|
+
let t = target;
|
|
1477
|
+
if (index) t = dirname(target);
|
|
1478
|
+
else if (!ext) t = target.replace(/\.[a-z]+$/, "");
|
|
1479
|
+
if (old.startsWith("@/") && t.startsWith("src/")) return `@/${t.slice(4)}`;
|
|
1480
|
+
return relativeSpec(fromFile, t);
|
|
1481
|
+
}
|
|
1482
|
+
function respecified(src, was, now, moves, have) {
|
|
1483
|
+
const fix = (spec) => {
|
|
1484
|
+
const target = resolveImport(was, spec, have);
|
|
1485
|
+
if (!target) return spec;
|
|
1486
|
+
const next = moves.get(target) ?? target;
|
|
1487
|
+
if (next === target && was === now) return spec;
|
|
1488
|
+
if (!spec.startsWith(".") && next === target) return spec;
|
|
1489
|
+
return specFor(now, next, spec, target);
|
|
1490
|
+
};
|
|
1491
|
+
let out = src.replace(SPECIFIER, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
|
|
1492
|
+
if (/\.mdx?$/.test(now)) out = out.replace(MD_LAYOUT, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
|
|
1493
|
+
return out;
|
|
1494
|
+
}
|
|
1495
|
+
var QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
|
|
1496
|
+
var MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
|
|
1497
|
+
function relinked(src, from, to, markdown) {
|
|
1498
|
+
const swap = (address2) => {
|
|
1499
|
+
const bare = address2.replace(/[#?][\s\S]*$/, "");
|
|
1500
|
+
const tail = address2.slice(bare.length);
|
|
1501
|
+
const slash = bare.length > 1 && bare.endsWith("/") ? "/" : "";
|
|
1502
|
+
const clean = slash ? bare.slice(0, -1) : bare;
|
|
1503
|
+
if (clean === from) return `${to}${to === "/" ? "" : slash}${tail}`;
|
|
1504
|
+
if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
|
|
1505
|
+
return address2;
|
|
1506
|
+
};
|
|
1507
|
+
let out = src.replace(QUOTED, (m, q, address2) => `${q}${swap(address2)}`);
|
|
1508
|
+
if (markdown) out = out.replace(MD_LINK, (m, a, address2, b) => `${a}${swap(address2)}${b}`);
|
|
1509
|
+
return out;
|
|
1510
|
+
}
|
|
1511
|
+
function blankStrings(src) {
|
|
1512
|
+
let out = "";
|
|
1513
|
+
let i = 0;
|
|
1514
|
+
while (i < src.length) {
|
|
1515
|
+
const c = src[i];
|
|
1516
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
1517
|
+
const j = stringEnd(src, i);
|
|
1518
|
+
out += c + blank(src.slice(i + 1, j - 1)) + (j - 1 > i ? src[j - 1] : "");
|
|
1519
|
+
i = j;
|
|
1520
|
+
continue;
|
|
1521
|
+
}
|
|
1522
|
+
out += c;
|
|
1523
|
+
i++;
|
|
1524
|
+
}
|
|
1525
|
+
return out;
|
|
1526
|
+
}
|
|
1527
|
+
var routesBase = (file) => file.startsWith("src/pages/") ? "src/pages" : file.startsWith("pages/") ? "pages" : file.startsWith("src/app/") ? "src/app" : file.startsWith("app/") ? "app" : null;
|
|
1528
|
+
function destination(page, to, discovered) {
|
|
1529
|
+
const base = routesBase(page.file);
|
|
1530
|
+
if (!base) return null;
|
|
1531
|
+
const ext = page.file.slice(page.file.lastIndexOf("."));
|
|
1532
|
+
if (base.endsWith("app")) {
|
|
1533
|
+
const dir = dirname(page.file);
|
|
1534
|
+
const parent = parentOf(to);
|
|
1535
|
+
const sameParent = parent === parentOf(page.path);
|
|
1536
|
+
const parentPage = parent === null ? null : discovered.pages.find((p) => p.path === parent && p.file && routesBase(p.file) === base);
|
|
1537
|
+
const parentDir = sameParent ? dirname(dir) : parentPage ? dirname(parentPage.file) : `${base}${parent === "/" ? "" : parent}`;
|
|
1538
|
+
const newDir2 = to === "/" ? base : `${parentDir}/${lastOf(to)}`;
|
|
1539
|
+
return { file: `${newDir2}/${page.file.slice(dir.length + 1)}`, dir, newDir: newDir2, folder: true };
|
|
1540
|
+
}
|
|
1541
|
+
const index = /(^|\/)index\.[a-z]+$/.test(page.file);
|
|
1542
|
+
const oldDir = `${base}${page.path === "/" ? "" : page.path}`;
|
|
1543
|
+
const newDir = `${base}${to === "/" ? "" : to}`;
|
|
1544
|
+
return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
|
|
1545
|
+
}
|
|
1546
|
+
function appSegmentOwn(dir, paths) {
|
|
1547
|
+
return paths.filter((p) => {
|
|
1548
|
+
if (dirname(p) === dir) return true;
|
|
1549
|
+
if (!p.startsWith(`${dir}/`)) return false;
|
|
1550
|
+
const first = p.slice(dir.length + 1).split("/")[0];
|
|
1551
|
+
return first.startsWith("_");
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
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";
|
|
1555
|
+
function routePathAttr(src, router) {
|
|
1556
|
+
const tag = src.slice(router.start, router.end);
|
|
1557
|
+
const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
|
|
1558
|
+
if (!m) return null;
|
|
1559
|
+
const value = m.slice(2).find((v) => v !== void 0) ?? "";
|
|
1560
|
+
const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
|
|
1561
|
+
return { value, start: valueAt, end: valueAt + value.length };
|
|
1562
|
+
}
|
|
1563
|
+
function planPage(request, input) {
|
|
1564
|
+
const { framework, text } = input;
|
|
1565
|
+
const paths = input.paths.filter((p) => !SKIP2.test(p));
|
|
1566
|
+
const no = (reason, detail) => ({ ok: (
|
|
1567
|
+
/** @type {const} */
|
|
1568
|
+
false
|
|
1569
|
+
), reason, ...detail ? { detail } : {} });
|
|
1570
|
+
const action = request.action;
|
|
1571
|
+
if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
|
|
1572
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
|
|
1573
|
+
const at2 = normalisePath(request.path);
|
|
1574
|
+
const discovered = input.found ?? discover({ framework, paths, text });
|
|
1575
|
+
const page = discovered.pages.find((p) => p.path === at2);
|
|
1576
|
+
if (!page) {
|
|
1577
|
+
const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at2));
|
|
1578
|
+
return template ? no("template", template.path) : no("missing");
|
|
1579
|
+
}
|
|
1580
|
+
if (page.kind === "template") return no("template", page.path);
|
|
1581
|
+
if (!page.file || page.reason === "unparsed") return no("unparsed");
|
|
1582
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1583
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
1584
|
+
const below = discovered.pages.filter((p) => under(p.path, at2));
|
|
1585
|
+
const have = new Set(paths);
|
|
1586
|
+
const importers = input.importers ?? importGraph(paths, text);
|
|
1587
|
+
const live = request.live === true;
|
|
1588
|
+
const redirects = live ? kitRedirects({ framework, text }) : false;
|
|
1589
|
+
const ownRedirects = siteRedirects({ framework, text });
|
|
1590
|
+
const taken = (p) => discovered.pages.some((q) => q.path === p) || [...ownRedirects].some((s) => sends(s, p));
|
|
1591
|
+
const writes = /* @__PURE__ */ new Map();
|
|
1592
|
+
const write = (w) => writes.set(w.path, w);
|
|
1593
|
+
const current = (p) => writes.has(p) ? writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null) : text(p);
|
|
1594
|
+
const links = /* @__PURE__ */ new Set();
|
|
1595
|
+
const unlinked = /* @__PURE__ */ new Set();
|
|
1596
|
+
const moves = [];
|
|
1597
|
+
const renamed = [];
|
|
1598
|
+
let to = null;
|
|
1599
|
+
const redirectChanges = {};
|
|
1600
|
+
const collections = (() => {
|
|
1601
|
+
try {
|
|
1602
|
+
return JSON.parse(text(COLLECTIONS) ?? "null");
|
|
1603
|
+
} catch {
|
|
1604
|
+
return null;
|
|
1605
|
+
}
|
|
1606
|
+
})();
|
|
1607
|
+
const collectionsAfter = isObject(collections) ? { ...collections } : null;
|
|
1608
|
+
if (action === "rename") {
|
|
1609
|
+
if (at2 === "/") return no("home");
|
|
1610
|
+
const target = request.to == null ? at2 : normalisePath(request.to);
|
|
1611
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1612
|
+
if (target !== at2 && within2(target, at2)) return no("address", target);
|
|
1613
|
+
if (target !== at2 && taken(target)) return no("taken", target);
|
|
1614
|
+
if (target !== at2 && live && !redirects) return no("no_redirects");
|
|
1615
|
+
to = target;
|
|
1616
|
+
const moved = /* @__PURE__ */ new Map();
|
|
1617
|
+
if (target !== at2) {
|
|
1618
|
+
if (framework === "vite-react") {
|
|
1619
|
+
const src = text(page.router.file) ?? "";
|
|
1620
|
+
const attr = routePathAttr(src, page.router);
|
|
1621
|
+
if (!attr) return no("unparsed", "index route");
|
|
1622
|
+
if (!attr.value.startsWith("/")) {
|
|
1623
|
+
const parent = normalisePath(at2.slice(0, at2.length - normalisePath(attr.value).length));
|
|
1624
|
+
if (parent !== "/" && !under(target, parent)) return no("unparsed", "a route inside another route keeps its parent");
|
|
1625
|
+
const rel = parent === "/" ? target.slice(1) : target.slice(parent.length + 1);
|
|
1626
|
+
write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
|
|
1627
|
+
}
|
|
1628
|
+
} else {
|
|
1629
|
+
const dest = destination(page, target, discovered);
|
|
1630
|
+
if (!dest) return no("unparsed");
|
|
1631
|
+
for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
|
|
1632
|
+
moved.set(page.file, dest.file);
|
|
1633
|
+
for (const [from, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
|
|
1634
|
+
for (const [from, next] of moved) {
|
|
1635
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
1636
|
+
const content = src == null ? null : respecified(src, from, next, moved, have);
|
|
1637
|
+
write(content == null || content === src ? { path: next, from } : { path: next, content });
|
|
1638
|
+
write({ path: from, deleted: true });
|
|
1639
|
+
}
|
|
1640
|
+
for (const p of paths) {
|
|
1641
|
+
if (moved.has(p) || !CODE.test(p)) continue;
|
|
1642
|
+
const src = text(p);
|
|
1643
|
+
if (!src) continue;
|
|
1644
|
+
const out = respecified(src, p, p, moved, have);
|
|
1645
|
+
if (out !== src) write({ path: p, content: out });
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
for (const p of paths) {
|
|
1649
|
+
if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
1650
|
+
const where = moved.get(p) ?? p;
|
|
1651
|
+
const src = current(where);
|
|
1652
|
+
if (!src) continue;
|
|
1653
|
+
const out = relinked(src, at2, target, /\.mdx?$/.test(p));
|
|
1654
|
+
if (out === src) continue;
|
|
1655
|
+
write({ path: where, content: out });
|
|
1656
|
+
if (!moved.has(p)) links.add(where);
|
|
1657
|
+
}
|
|
1658
|
+
moves.push({ from: at2, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at2, target) })));
|
|
1659
|
+
for (const [from, next] of moved) renamed.push({ from, to: next });
|
|
1660
|
+
}
|
|
1661
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1662
|
+
if (target !== at2) {
|
|
1663
|
+
for (const key of Object.keys(pages)) {
|
|
1664
|
+
if (!within2(key, at2)) continue;
|
|
1665
|
+
pages[moveAddress(key, at2, target)] = { ...pages[key], ...pages[moveAddress(key, at2, target)] ?? {} };
|
|
1666
|
+
delete pages[key];
|
|
1667
|
+
}
|
|
1668
|
+
const before = { ...sendsOn };
|
|
1669
|
+
if (live) {
|
|
1670
|
+
sendsOn[at2] = target;
|
|
1671
|
+
if (below.length) sendsOn[`${at2}/[...path]`] = `${target}/[...path]`;
|
|
1672
|
+
}
|
|
1673
|
+
repoint(sendsOn, at2, target);
|
|
1674
|
+
for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1675
|
+
}
|
|
1676
|
+
if (request.name !== void 0) {
|
|
1677
|
+
const entry = pages[target] ?? {};
|
|
1678
|
+
if (request.name) entry.name = String(request.name).trim().slice(0, 120);
|
|
1679
|
+
else delete entry.name;
|
|
1680
|
+
pages[target] = entry;
|
|
1681
|
+
}
|
|
1682
|
+
});
|
|
1683
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1684
|
+
if (!writes.size) return no("same");
|
|
1685
|
+
}
|
|
1686
|
+
if (action === "duplicate") {
|
|
1687
|
+
if (framework === "vite-react" && page.reason === "nested") return no("nested");
|
|
1688
|
+
let target;
|
|
1689
|
+
if (request.to != null) {
|
|
1690
|
+
target = normalisePath(request.to);
|
|
1691
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1692
|
+
if (taken(target)) return no("taken", target);
|
|
1693
|
+
} else {
|
|
1694
|
+
const base = at2 === "/" ? "/home-copy" : `${at2}-copy`;
|
|
1695
|
+
target = base;
|
|
1696
|
+
for (let n = 2; taken(target) && n < 100; n++) target = `${base}-${n}`;
|
|
1697
|
+
}
|
|
1698
|
+
to = target;
|
|
1699
|
+
const content = ownedContent(page, { paths, text, importers });
|
|
1700
|
+
if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
|
|
1701
|
+
const own = new Set(content.files);
|
|
1702
|
+
const reads = siteReads(paths, text, importers);
|
|
1703
|
+
const ownCodeFiles = ownCode(page, importers, reads.imports);
|
|
1704
|
+
const pageReads = reads.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set(), whole: /* @__PURE__ */ new Set(), helped: /* @__PURE__ */ new Set() };
|
|
1705
|
+
const imported = new Set(reads.jsonOf.get(page.file) ?? []);
|
|
1706
|
+
const copies = /* @__PURE__ */ new Map();
|
|
1707
|
+
const rebinds = [];
|
|
1708
|
+
const newId = slugOf(lastOf(target)) || "copy";
|
|
1709
|
+
const freeFile = (dir, base, ext) => {
|
|
1710
|
+
let f = `${dir}/${base}${ext}`;
|
|
1711
|
+
for (let n = 2; (have.has(f) || [...writes.keys()].includes(f) || [...copies.values()].includes(f)) && n < 100; n++) f = `${dir}/${base}-${n}${ext}`;
|
|
1712
|
+
return f;
|
|
1713
|
+
};
|
|
1714
|
+
for (const f of own) {
|
|
1715
|
+
if (reads.isRoute(f)) continue;
|
|
1716
|
+
if (imported.has(f)) {
|
|
1717
|
+
copies.set(f, freeFile(dirname(f), `${f.slice(f.lastIndexOf("/") + 1, -5)}-${newId}`, ".json"));
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
const collection = collectionOfFile(f, reads.collections);
|
|
1721
|
+
const id = f.slice(f.lastIndexOf("/") + 1, -5);
|
|
1722
|
+
const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
|
|
1723
|
+
const entry = `${collection}/${id}`;
|
|
1724
|
+
if (pageReads.entries.has(entry) && folder) {
|
|
1725
|
+
const next = freeFile(dirname(f), newId, ".json");
|
|
1726
|
+
copies.set(f, next);
|
|
1727
|
+
rebinds.push({ kind: "entry", name: id, collection, next: next.slice(next.lastIndexOf("/") + 1, -5) });
|
|
1728
|
+
} else if (pageReads.names.has(id) && id !== collection && folder) {
|
|
1729
|
+
const next = freeFile(dirname(f), newId, ".json");
|
|
1730
|
+
copies.set(f, next);
|
|
1731
|
+
rebinds.push({ kind: "name", name: id, next: next.slice(next.lastIndexOf("/") + 1, -5) });
|
|
1732
|
+
} else {
|
|
1733
|
+
return no("content_bound", f);
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
if (content.unknown) return no("content_bound", "content it reads that Unbase cannot place");
|
|
1737
|
+
for (const m of ownCodeFiles) {
|
|
1738
|
+
if (m === page.file) continue;
|
|
1739
|
+
const r = reads.readsByFile.get(m);
|
|
1740
|
+
if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && [...own].some((f) => !reads.isRoute(f))) return no("content_bound", m);
|
|
1741
|
+
}
|
|
1742
|
+
const rebind = (src) => {
|
|
1743
|
+
let out = src;
|
|
1744
|
+
for (const r of rebinds) {
|
|
1745
|
+
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`);
|
|
1746
|
+
else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
|
|
1747
|
+
}
|
|
1748
|
+
for (const [f, next] of copies) {
|
|
1749
|
+
if (!imported.has(f)) continue;
|
|
1750
|
+
out = out.replace(SPECIFIER, (m, lead, q, spec) => resolveImport(page.file, spec, have) === f ? `${lead}${q}${spec.slice(0, spec.lastIndexOf("/") + 1)}${next.slice(next.lastIndexOf("/") + 1)}${q}` : m);
|
|
1751
|
+
}
|
|
1752
|
+
return out;
|
|
1753
|
+
};
|
|
1754
|
+
if (framework === "vite-react") {
|
|
1755
|
+
const router = page.router.file;
|
|
1756
|
+
const src = current(router) ?? "";
|
|
1757
|
+
const attr = routePathAttr(src, page.router);
|
|
1758
|
+
if (!attr) return no("unparsed", "index route");
|
|
1759
|
+
let name = componentName(target);
|
|
1760
|
+
for (let n = 2; new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(src) && n < 100; n++) name = `${componentName(target)}${n}`;
|
|
1761
|
+
const ext = page.file.slice(page.file.lastIndexOf("."));
|
|
1762
|
+
const file = freeFile(dirname(page.file), name, ext);
|
|
1763
|
+
const original = text(page.file) ?? "";
|
|
1764
|
+
write({ path: file, content: rebind(respecified(original, page.file, file, /* @__PURE__ */ new Map([[page.file, file]]), have)) });
|
|
1765
|
+
const comp = page.router.component;
|
|
1766
|
+
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"));
|
|
1767
|
+
if (!statement) return no("unparsed", "its import");
|
|
1768
|
+
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}`);
|
|
1769
|
+
const value = attr.value.startsWith("/") ? target : (() => {
|
|
1770
|
+
const parent = normalisePath(at2.slice(0, at2.length - normalisePath(attr.value).length));
|
|
1771
|
+
return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
|
|
1772
|
+
})();
|
|
1773
|
+
if (value === null) return no("unparsed", "a route inside another route keeps its parent");
|
|
1774
|
+
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}`);
|
|
1775
|
+
const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
|
|
1776
|
+
const at1 = page.router.end;
|
|
1777
|
+
let out = `${src.slice(0, at1)}
|
|
1778
|
+
${indent}${newTag}${src.slice(at1)}`;
|
|
1779
|
+
const lineEnd = statement.index + statement[0].length;
|
|
1780
|
+
out = `${out.slice(0, lineEnd)}
|
|
1781
|
+
${added}${out.slice(lineEnd)}`;
|
|
1782
|
+
write({ path: router, content: out });
|
|
1783
|
+
} else {
|
|
1784
|
+
const dest = destination(page, target, discovered);
|
|
1785
|
+
if (!dest) return no("unparsed");
|
|
1786
|
+
const along = framework === "next" && routesBase(page.file).endsWith("app") && at2 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
|
|
1787
|
+
const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
|
|
1788
|
+
for (const next of moved.values()) if (have.has(next)) return no("taken", next);
|
|
1789
|
+
for (const [from, next] of moved) {
|
|
1790
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
1791
|
+
if (src == null) {
|
|
1792
|
+
write({ path: next, from });
|
|
1793
|
+
continue;
|
|
1794
|
+
}
|
|
1795
|
+
let out = respecified(src, from, next, moved, have);
|
|
1796
|
+
if (from === page.file) out = rebind(out);
|
|
1797
|
+
write(out === src ? { path: next, from } : { path: next, content: out });
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
for (const [f, next] of copies) {
|
|
1801
|
+
write({ path: next, from: f });
|
|
1802
|
+
if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
|
|
1803
|
+
}
|
|
1804
|
+
for (const f of own) {
|
|
1805
|
+
if (!reads.isRoute(f)) continue;
|
|
1806
|
+
const src = text(f) ?? "";
|
|
1807
|
+
const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
|
|
1808
|
+
write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at2)}(")`), `$1${target}$2`) });
|
|
1809
|
+
if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
|
|
1810
|
+
}
|
|
1811
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
|
|
1812
|
+
const entry = { ...request.drafts ? { draft: true } : {}, ...request.name ? { name: String(request.name).trim().slice(0, 120) } : {} };
|
|
1813
|
+
if (Object.keys(entry).length) pages[target] = entry;
|
|
1814
|
+
});
|
|
1815
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1816
|
+
}
|
|
1817
|
+
if (action === "delete") {
|
|
1818
|
+
if (at2 === "/") return no("home");
|
|
1819
|
+
if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
|
|
1820
|
+
let target = null;
|
|
1821
|
+
if (live && request.redirect !== null) {
|
|
1822
|
+
if (request.redirect !== void 0) {
|
|
1823
|
+
target = normalisePath(request.redirect);
|
|
1824
|
+
if (within2(target, at2) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
|
|
1825
|
+
} else {
|
|
1826
|
+
for (let p = parentOf(at2); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
|
|
1827
|
+
target = target ?? "/";
|
|
1828
|
+
}
|
|
1829
|
+
if (!redirects) return no("no_redirects");
|
|
1830
|
+
}
|
|
1831
|
+
to = target;
|
|
1832
|
+
if (framework === "vite-react") {
|
|
1833
|
+
const router = page.router.file;
|
|
1834
|
+
const src = current(router) ?? "";
|
|
1835
|
+
let { start, end } = page.router;
|
|
1836
|
+
const lineStart = src.lastIndexOf("\n", start - 1) + 1;
|
|
1837
|
+
const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
|
|
1838
|
+
if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
|
|
1839
|
+
start = lineStart;
|
|
1840
|
+
end = Math.min(src.length, lineEnd + 1);
|
|
1841
|
+
}
|
|
1842
|
+
let out = src.slice(0, start) + src.slice(end);
|
|
1843
|
+
const comp = page.router.component;
|
|
1844
|
+
const rest = blankStrings(stripComments(out));
|
|
1845
|
+
const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
|
|
1846
|
+
if (uses <= 1) {
|
|
1847
|
+
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");
|
|
1848
|
+
out = out.replace(re, "");
|
|
1849
|
+
if ([...importers.get(page.file) ?? []].every((f) => f === router)) write({ path: page.file, deleted: true });
|
|
1850
|
+
}
|
|
1851
|
+
write({ path: router, content: out });
|
|
1852
|
+
} else {
|
|
1853
|
+
const dir = dirname(page.file);
|
|
1854
|
+
const files2 = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
|
|
1855
|
+
for (const f of files2) write({ path: f, deleted: true });
|
|
1856
|
+
}
|
|
1857
|
+
const content = ownedContent(page, { paths, text, importers });
|
|
1858
|
+
for (const f of content.files) {
|
|
1859
|
+
write({ path: f, deleted: true });
|
|
1860
|
+
if (collectionsAfter) delete collectionsAfter[f];
|
|
1861
|
+
}
|
|
1862
|
+
for (const f of linksTo(at2, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
|
|
1863
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1864
|
+
delete pages[at2];
|
|
1865
|
+
const before = { ...sendsOn };
|
|
1866
|
+
if (target) sendsOn[at2] = target;
|
|
1867
|
+
if (target) repoint(sendsOn, at2, target);
|
|
1868
|
+
else for (const [s, d] of Object.entries(sendsOn)) if (d === at2) delete sendsOn[s];
|
|
1869
|
+
for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1870
|
+
});
|
|
1871
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1872
|
+
}
|
|
1873
|
+
if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
|
|
1874
|
+
const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
1875
|
+
write({ path: COLLECTIONS, content: `${JSON.stringify(sorted, null, 2)}
|
|
1876
|
+
` });
|
|
1877
|
+
}
|
|
1878
|
+
const files = [...writes.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
1879
|
+
const message = action === "rename" ? to === at2 ? `Unbase: rename ${at2}` : `Unbase: move ${at2} to ${to}` : action === "duplicate" ? `Unbase: duplicate ${at2} as ${to}` : `Unbase: delete ${at2}${to ? ` (visitors go to ${to})` : ""}`;
|
|
1880
|
+
return { ok: true, action, path: at2, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
|
|
1881
|
+
}
|
|
1882
|
+
function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers }) {
|
|
1883
|
+
const kept = paths.filter((p) => !SKIP2.test(p));
|
|
1884
|
+
const discovered = found ?? discover({ framework, paths: kept, text });
|
|
1885
|
+
const graph = importers ?? importGraph(kept, text);
|
|
1886
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1887
|
+
const redirects = kitRedirects({ framework, text });
|
|
1888
|
+
const reads = siteReads(kept, text, graph);
|
|
1889
|
+
const out = {};
|
|
1890
|
+
const no = (reason, detail) => ({ ok: (
|
|
1891
|
+
/** @type {const} */
|
|
1892
|
+
false
|
|
1893
|
+
), reason, ...detail ? { detail } : {} });
|
|
1894
|
+
const yes = { ok: (
|
|
1895
|
+
/** @type {const} */
|
|
1896
|
+
true
|
|
1897
|
+
) };
|
|
1898
|
+
for (const page of discovered.pages) {
|
|
1899
|
+
if (page.path.includes(" ")) continue;
|
|
1900
|
+
const below = discovered.pages.filter((p) => under(p.path, page.path));
|
|
1901
|
+
const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
|
|
1902
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
|
|
1903
|
+
out[page.path] = all(no("framework"));
|
|
1904
|
+
continue;
|
|
1905
|
+
}
|
|
1906
|
+
if (!pageFile.ok) {
|
|
1907
|
+
out[page.path] = all(no("invalid"));
|
|
1908
|
+
continue;
|
|
1909
|
+
}
|
|
1910
|
+
if (page.kind === "template") {
|
|
1911
|
+
out[page.path] = all(no("template"));
|
|
1912
|
+
continue;
|
|
1913
|
+
}
|
|
1914
|
+
if (!page.file || page.reason === "unparsed") {
|
|
1915
|
+
out[page.path] = all(no("unparsed"));
|
|
1916
|
+
continue;
|
|
1917
|
+
}
|
|
1918
|
+
const onLive = live.has(page.path);
|
|
1919
|
+
let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
|
|
1920
|
+
if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
|
|
1921
|
+
const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
|
|
1922
|
+
let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
|
|
1923
|
+
if (duplicate.ok) {
|
|
1924
|
+
const content = ownedContent(page, { paths: kept, text, importers: graph });
|
|
1925
|
+
const pageReads = reads.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
|
|
1926
|
+
const imported = new Set(reads.jsonOf.get(page.file) ?? []);
|
|
1927
|
+
if (content.unregistered.length) duplicate = no("content_unregistered", content.unregistered.join(", "));
|
|
1928
|
+
else if (content.unknown) duplicate = no("content_bound");
|
|
1929
|
+
else
|
|
1930
|
+
for (const f of content.files) {
|
|
1931
|
+
if (reads.isRoute(f) || imported.has(f)) continue;
|
|
1932
|
+
const collection = collectionOfFile(f, reads.collections);
|
|
1933
|
+
const id = f.slice(f.lastIndexOf("/") + 1, -5);
|
|
1934
|
+
const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
|
|
1935
|
+
const bound = !folder || !(pageReads.entries.has(`${collection}/${id}`) || pageReads.names.has(id) && id !== collection);
|
|
1936
|
+
if (bound) {
|
|
1937
|
+
duplicate = no("content_bound", f);
|
|
1938
|
+
break;
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
if (duplicate.ok) {
|
|
1942
|
+
const mine = ownCode(page, graph, reads.imports);
|
|
1943
|
+
for (const m of mine) {
|
|
1944
|
+
if (m === page.file) continue;
|
|
1945
|
+
const r = reads.readsByFile.get(m);
|
|
1946
|
+
if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && content.files.some((f) => !reads.isRoute(f))) {
|
|
1947
|
+
duplicate = no("content_bound", m);
|
|
1948
|
+
break;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
out[page.path] = { rename, duplicate, delete: remove, under: below.length };
|
|
1954
|
+
}
|
|
1955
|
+
return { redirects, actions: out };
|
|
1956
|
+
}
|
|
1957
|
+
function redirectsFor(framework, pageFile, pagePaths = []) {
|
|
1958
|
+
const pages = new Set(pagePaths.map(normalisePath));
|
|
1959
|
+
const list = [];
|
|
1960
|
+
const skipped = [];
|
|
1961
|
+
for (const [source, destination2] of Object.entries(pageFile.redirects ?? {})) {
|
|
1962
|
+
const prefix = REST.test(source);
|
|
1963
|
+
const base = prefix ? normalisePath(source.replace(REST, "")) : source;
|
|
1964
|
+
if (!prefix && pages.has(source)) {
|
|
1965
|
+
skipped.push(source);
|
|
1966
|
+
continue;
|
|
1967
|
+
}
|
|
1968
|
+
const destBase = prefix ? normalisePath(destination2.replace(REST, "")) : destination2;
|
|
1969
|
+
if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination2, permanent: true });
|
|
1970
|
+
else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
|
|
1971
|
+
else list.push({ source, destination: destination2 });
|
|
1972
|
+
}
|
|
1973
|
+
return { list, skipped };
|
|
1974
|
+
}
|
|
1334
1975
|
|
|
1335
1976
|
// supabase/functions/_shared/next-metadata.ts
|
|
1336
1977
|
var ID = /[A-Za-z0-9_$]/;
|
|
@@ -1667,6 +2308,22 @@ var SCHEMAS = `${CONTENT}/.schemas`;
|
|
|
1667
2308
|
var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
|
|
1668
2309
|
var AT_ONCE2 = 8;
|
|
1669
2310
|
var MAX_ROUTE_FILES = 300;
|
|
2311
|
+
var NEXT_AT_ONCE = 16;
|
|
2312
|
+
function limited(n) {
|
|
2313
|
+
let running = 0;
|
|
2314
|
+
const waiting = [];
|
|
2315
|
+
return async (work) => {
|
|
2316
|
+
if (running < n) running++;
|
|
2317
|
+
else await new Promise((go) => waiting.push(go));
|
|
2318
|
+
try {
|
|
2319
|
+
return await work();
|
|
2320
|
+
} finally {
|
|
2321
|
+
const next = waiting.shift();
|
|
2322
|
+
if (next) next();
|
|
2323
|
+
else running--;
|
|
2324
|
+
}
|
|
2325
|
+
};
|
|
2326
|
+
}
|
|
1670
2327
|
async function inTurns(items, work) {
|
|
1671
2328
|
const out = new Array(items.length);
|
|
1672
2329
|
let next = 0;
|
|
@@ -1694,12 +2351,12 @@ function valueOf(v, kind) {
|
|
|
1694
2351
|
}
|
|
1695
2352
|
function fieldsOf(names, data, allowed, file, base) {
|
|
1696
2353
|
const fields = {};
|
|
1697
|
-
for (const [
|
|
2354
|
+
for (const [field2, { name, kind }] of Object.entries(names)) {
|
|
1698
2355
|
const value = valueOf(data?.[name], kind);
|
|
1699
2356
|
const there = data?.[name] !== void 0;
|
|
1700
2357
|
if (there && value === null) continue;
|
|
1701
2358
|
if (!there && !allowed[name]) continue;
|
|
1702
|
-
fields[
|
|
2359
|
+
fields[field2] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
|
|
1703
2360
|
}
|
|
1704
2361
|
return fields;
|
|
1705
2362
|
}
|
|
@@ -1717,9 +2374,9 @@ async function viteSettings(repo, appPath) {
|
|
|
1717
2374
|
if (text === null) return null;
|
|
1718
2375
|
const head = readHead(text);
|
|
1719
2376
|
const site = {};
|
|
1720
|
-
for (const [
|
|
2377
|
+
for (const [field2, at2, kind] of HEAD_SETTINGS) {
|
|
1721
2378
|
const found = head[at2];
|
|
1722
|
-
if (found) site[
|
|
2379
|
+
if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at2), kind, exists: true, value: found.value };
|
|
1723
2380
|
}
|
|
1724
2381
|
return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
|
|
1725
2382
|
}
|
|
@@ -1755,7 +2412,7 @@ async function readSettings(repo, appPath, framework = null) {
|
|
|
1755
2412
|
pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
|
|
1756
2413
|
});
|
|
1757
2414
|
const dir = files[0] ? files[0].slice(appPath ? appPath.length + 1 : 0).replace(/\/[^/]+$/, "") : `${CONTENT}/${collection}`;
|
|
1758
|
-
const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([
|
|
2415
|
+
const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
|
|
1759
2416
|
routes = { dir, fields };
|
|
1760
2417
|
}
|
|
1761
2418
|
const siteCollection = [...schemas].find(([, s]) => s["x-instellingen"] === "site");
|
|
@@ -1786,8 +2443,9 @@ async function nextSettings(repo, appPath) {
|
|
|
1786
2443
|
const paths = repo.paths.filter((p) => p.startsWith(root)).map((p) => p.slice(root.length));
|
|
1787
2444
|
const have = new Set(paths);
|
|
1788
2445
|
const texts = /* @__PURE__ */ new Map();
|
|
2446
|
+
const turn = limited(NEXT_AT_ONCE);
|
|
1789
2447
|
const read = (p) => {
|
|
1790
|
-
if (!texts.has(p)) texts.set(p, repo.read(join(appPath, p)));
|
|
2448
|
+
if (!texts.has(p)) texts.set(p, turn(() => repo.read(join(appPath, p))));
|
|
1791
2449
|
return texts.get(p);
|
|
1792
2450
|
};
|
|
1793
2451
|
const { pages: found } = discover({ framework: "next", paths, text: () => null });
|
|
@@ -1802,28 +2460,34 @@ async function nextSettings(repo, appPath) {
|
|
|
1802
2460
|
const specs = importsOf(src);
|
|
1803
2461
|
if (specs.some(isCmsModule)) return true;
|
|
1804
2462
|
if (!depth) return false;
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
if (target && await readsCms(target, depth - 1, seen)) return true;
|
|
1808
|
-
}
|
|
1809
|
-
return false;
|
|
2463
|
+
const targets = specs.map((s) => resolveIn(file, s, have)).filter((t) => t !== null);
|
|
2464
|
+
return (await Promise.all(targets.map((t) => readsCms(t, depth - 1, seen)))).some(Boolean);
|
|
1810
2465
|
};
|
|
1811
2466
|
const reasonOf = async (file, reason) => reason === "computed" && /\bgenerateMetadata\b/.test(await read(file) ?? "") && await readsCms(file) ? "cms" : reason;
|
|
1812
2467
|
const out = {};
|
|
1813
2468
|
const refused = {};
|
|
1814
|
-
const answers = await
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
2469
|
+
const [answers, layoutRead] = await Promise.all([
|
|
2470
|
+
Promise.all(
|
|
2471
|
+
pages.map(async (p) => {
|
|
2472
|
+
const file = p.file;
|
|
2473
|
+
if (!NEXT_PAGE.test(file)) return { p, file, read: null, reason: null };
|
|
2474
|
+
const src = await read(file);
|
|
2475
|
+
const r = src === null ? null : pageMetaFields(src);
|
|
2476
|
+
return { p, file, read: r, reason: r?.refused ? await reasonOf(file, r.refused) : null };
|
|
2477
|
+
})
|
|
2478
|
+
),
|
|
2479
|
+
layout ? read(layout).then(async (src) => {
|
|
2480
|
+
const r = src === null ? null : siteMetaFields(src);
|
|
2481
|
+
return { read: r, reason: r?.refused ? await reasonOf(layout, r.refused) : null };
|
|
2482
|
+
}) : null
|
|
2483
|
+
]);
|
|
2484
|
+
for (const { p, file, read: r, reason } of answers) {
|
|
1821
2485
|
if (!r) {
|
|
1822
2486
|
refused[p.path] = { file, reason: "unsupported" };
|
|
1823
2487
|
continue;
|
|
1824
2488
|
}
|
|
1825
2489
|
if (r.refused) {
|
|
1826
|
-
refused[p.path] = { file, reason:
|
|
2490
|
+
refused[p.path] = { file, reason: reason ?? r.refused };
|
|
1827
2491
|
continue;
|
|
1828
2492
|
}
|
|
1829
2493
|
if (r.fields.socialImage && drawnImage(file, have)) {
|
|
@@ -1837,9 +2501,8 @@ async function nextSettings(repo, appPath) {
|
|
|
1837
2501
|
if (computed.length) refused[p.path] = { file, reason: "computed", fields: Object.fromEntries(computed) };
|
|
1838
2502
|
}
|
|
1839
2503
|
let site = null;
|
|
1840
|
-
if (layout) {
|
|
1841
|
-
const
|
|
1842
|
-
const r = src === null ? null : siteMetaFields(src);
|
|
2504
|
+
if (layout && layoutRead) {
|
|
2505
|
+
const r = layoutRead.read;
|
|
1843
2506
|
if (r?.fields.socialImage && drawnImage(layout, have)) {
|
|
1844
2507
|
delete r.fields.socialImage;
|
|
1845
2508
|
r.computed.socialImage = "computed";
|
|
@@ -1849,7 +2512,7 @@ async function nextSettings(repo, appPath) {
|
|
|
1849
2512
|
for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_SITE_FIELDS[k]] = settingOf(layout, f);
|
|
1850
2513
|
if (Object.keys(fields).length) site = fields;
|
|
1851
2514
|
const computed = Object.entries(r.computed).map(([k, why]) => [NEXT_SITE_FIELDS[k], why]);
|
|
1852
|
-
if (r.refused) refused.site = { file: layout, reason:
|
|
2515
|
+
if (r.refused) refused.site = { file: layout, reason: layoutRead.reason ?? r.refused };
|
|
1853
2516
|
else if (computed.length) refused.site = { file: layout, reason: "computed", fields: Object.fromEntries(computed) };
|
|
1854
2517
|
}
|
|
1855
2518
|
}
|
|
@@ -1909,8 +2572,226 @@ function registryOf(input) {
|
|
|
1909
2572
|
truncated
|
|
1910
2573
|
};
|
|
1911
2574
|
}
|
|
2575
|
+
|
|
2576
|
+
// supabase/functions/_shared/csp.ts
|
|
2577
|
+
var csp_exports = {};
|
|
2578
|
+
__export(csp_exports, {
|
|
2579
|
+
COLLECTOR: () => COLLECTOR,
|
|
2580
|
+
COLLECTOR_ORIGIN: () => COLLECTOR_ORIGIN,
|
|
2581
|
+
CSP_FILES: () => CSP_FILES,
|
|
2582
|
+
blockingIn: () => blockingIn,
|
|
2583
|
+
cspElsewhere: () => cspElsewhere,
|
|
2584
|
+
directivesOf: () => directivesOf,
|
|
2585
|
+
onlyCollectorChanged: () => onlyCollectorChanged,
|
|
2586
|
+
policiesIn: () => policiesIn,
|
|
2587
|
+
policyAllows: () => policyAllows,
|
|
2588
|
+
withCollector: () => withCollector,
|
|
2589
|
+
withCollectorIn: () => withCollectorIn,
|
|
2590
|
+
withoutCollector: () => withoutCollector,
|
|
2591
|
+
withoutCollectorIn: () => withoutCollectorIn
|
|
2592
|
+
});
|
|
2593
|
+
var COLLECTOR = "https://unbase.app/e";
|
|
2594
|
+
var COLLECTOR_ORIGIN = new URL(COLLECTOR).origin;
|
|
2595
|
+
var CSP_FILES = ["vercel.json", "public/_headers"];
|
|
2596
|
+
var HEADER = /^content-security-policy$/i;
|
|
2597
|
+
function directivesOf(policy) {
|
|
2598
|
+
const out = [];
|
|
2599
|
+
let at2 = 0;
|
|
2600
|
+
for (const part of policy.split(";")) {
|
|
2601
|
+
const lead = part.length - part.trimStart().length;
|
|
2602
|
+
const text = part.trim();
|
|
2603
|
+
if (text) {
|
|
2604
|
+
const [name, ...sources] = text.split(/\s+/);
|
|
2605
|
+
out.push({ name: name.toLowerCase(), sources, start: at2 + lead, end: at2 + lead + text.length });
|
|
2606
|
+
}
|
|
2607
|
+
at2 += part.length + 1;
|
|
2608
|
+
}
|
|
2609
|
+
return out;
|
|
2610
|
+
}
|
|
2611
|
+
var governing = (ds) => ds.find((d) => d.name === "connect-src") ?? ds.find((d) => d.name === "default-src") ?? null;
|
|
2612
|
+
function sourceAllows(source, endpoint) {
|
|
2613
|
+
const s = source.toLowerCase();
|
|
2614
|
+
const url = new URL(endpoint);
|
|
2615
|
+
if (s === "*" || s === "https:") return true;
|
|
2616
|
+
if (s.startsWith("'")) return false;
|
|
2617
|
+
const m = /^(?:(https?):\/\/)?([^/:]+)(?::(\d+|\*))?(\/.*)?$/.exec(s);
|
|
2618
|
+
if (!m) return false;
|
|
2619
|
+
const [, scheme, host, port, path] = m;
|
|
2620
|
+
if (scheme && scheme !== "https" && scheme !== "http") return false;
|
|
2621
|
+
const hostOk = host === url.hostname || host.startsWith("*.") && url.hostname.endsWith(host.slice(1));
|
|
2622
|
+
if (!hostOk) return false;
|
|
2623
|
+
if (port && port !== "*" && port !== "443") return false;
|
|
2624
|
+
if (!path) return true;
|
|
2625
|
+
return path.endsWith("/") ? url.pathname.startsWith(path) : url.pathname === path;
|
|
2626
|
+
}
|
|
2627
|
+
function policyAllows(policy, endpoint = COLLECTOR) {
|
|
2628
|
+
const d = governing(directivesOf(policy));
|
|
2629
|
+
return !d || d.sources.some((s) => sourceAllows(s, endpoint));
|
|
2630
|
+
}
|
|
2631
|
+
function withCollector(policy, origin = COLLECTOR_ORIGIN) {
|
|
2632
|
+
if (policyAllows(policy, `${origin}${new URL(COLLECTOR).pathname}`)) return policy;
|
|
2633
|
+
const ds = directivesOf(policy);
|
|
2634
|
+
const connect = ds.find((d) => d.name === "connect-src");
|
|
2635
|
+
if (connect) {
|
|
2636
|
+
const rest = connect.sources.filter((s) => s.toLowerCase() !== "'none'");
|
|
2637
|
+
return `${policy.slice(0, connect.start)}${["connect-src", ...rest, origin].join(" ")}${policy.slice(connect.end)}`;
|
|
2638
|
+
}
|
|
2639
|
+
const fallback = ds.find((d) => d.name === "default-src");
|
|
2640
|
+
const sources = fallback.sources.filter((s) => s.toLowerCase() !== "'none'");
|
|
2641
|
+
const body = policy.replace(/[\s;]*$/, "");
|
|
2642
|
+
return `${body}; ${["connect-src", ...sources, origin].join(" ")}${policy.slice(body.length)}`;
|
|
2643
|
+
}
|
|
2644
|
+
function withoutCollector(policy, origin = COLLECTOR_ORIGIN) {
|
|
2645
|
+
const ds = directivesOf(policy);
|
|
2646
|
+
const connect = ds.find((d) => d.name === "connect-src");
|
|
2647
|
+
const own = (s) => s.toLowerCase().replace(/\/+$/, "") === origin.toLowerCase();
|
|
2648
|
+
if (!connect || !connect.sources.some(own)) return policy;
|
|
2649
|
+
const rest = connect.sources.filter((s) => !own(s));
|
|
2650
|
+
const fallback = ds.find((d) => d.name === "default-src");
|
|
2651
|
+
const plain2 = (list) => list.filter((s) => s.toLowerCase() !== "'none'").join(" ");
|
|
2652
|
+
if (fallback && plain2(rest) === plain2(fallback.sources)) {
|
|
2653
|
+
const before = policy.slice(0, connect.start);
|
|
2654
|
+
const cut = before.lastIndexOf(";");
|
|
2655
|
+
if (cut >= 0) return `${policy.slice(0, cut)}${policy.slice(connect.end)}`;
|
|
2656
|
+
return policy.slice(connect.end).replace(/^\s*;\s*/, "");
|
|
2657
|
+
}
|
|
2658
|
+
return `${policy.slice(0, connect.start)}${["connect-src", ...rest.length ? rest : ["'none'"]].join(" ")}${policy.slice(connect.end)}`;
|
|
2659
|
+
}
|
|
2660
|
+
var plainPolicy = (policy) => {
|
|
2661
|
+
const ds = directivesOf(withoutCollector(policy));
|
|
2662
|
+
return ds.map((d) => [d.name, ...d.sources].join(" ")).join("; ");
|
|
2663
|
+
};
|
|
2664
|
+
function jsonTree(text) {
|
|
2665
|
+
JSON.parse(text);
|
|
2666
|
+
let i = 0;
|
|
2667
|
+
const ws = () => {
|
|
2668
|
+
while (i < text.length && /\s/.test(text[i])) i++;
|
|
2669
|
+
};
|
|
2670
|
+
const value = () => {
|
|
2671
|
+
ws();
|
|
2672
|
+
const start = i;
|
|
2673
|
+
const c = text[i];
|
|
2674
|
+
if (c === "{" || c === "[") {
|
|
2675
|
+
const close = c === "{" ? "}" : "]";
|
|
2676
|
+
i++;
|
|
2677
|
+
const entries = [];
|
|
2678
|
+
const items = [];
|
|
2679
|
+
ws();
|
|
2680
|
+
while (text[i] !== close) {
|
|
2681
|
+
if (c === "{") {
|
|
2682
|
+
const key = value();
|
|
2683
|
+
ws();
|
|
2684
|
+
i++;
|
|
2685
|
+
entries.push({ key: key.value, value: value() });
|
|
2686
|
+
} else items.push(value());
|
|
2687
|
+
ws();
|
|
2688
|
+
if (text[i] === ",") i++;
|
|
2689
|
+
ws();
|
|
2690
|
+
}
|
|
2691
|
+
i++;
|
|
2692
|
+
return c === "{" ? { type: "object", start, end: i, entries } : { type: "array", start, end: i, items };
|
|
2693
|
+
}
|
|
2694
|
+
if (c === '"') {
|
|
2695
|
+
i++;
|
|
2696
|
+
while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
|
|
2697
|
+
i++;
|
|
2698
|
+
return { type: "string", start, end: i, value: JSON.parse(text.slice(start, i)) };
|
|
2699
|
+
}
|
|
2700
|
+
while (i < text.length && /[^\s,\]}]/.test(text[i])) i++;
|
|
2701
|
+
return { type: "literal", start, end: i };
|
|
2702
|
+
};
|
|
2703
|
+
return value();
|
|
2704
|
+
}
|
|
2705
|
+
var field = (node, key) => node?.type === "object" ? node.entries.find((e) => e.key === key)?.value : void 0;
|
|
2706
|
+
function vercelPolicies(text) {
|
|
2707
|
+
const out = [];
|
|
2708
|
+
const rules = field(jsonTree(text), "headers");
|
|
2709
|
+
if (rules?.type !== "array") return out;
|
|
2710
|
+
for (const rule of rules.items) {
|
|
2711
|
+
const source = field(rule, "source");
|
|
2712
|
+
const headers = field(rule, "headers");
|
|
2713
|
+
if (headers?.type !== "array") continue;
|
|
2714
|
+
for (const h of headers.items) {
|
|
2715
|
+
const key = field(h, "key");
|
|
2716
|
+
const value = field(h, "value");
|
|
2717
|
+
if (key?.type === "string" && HEADER.test(key.value) && value?.type === "string")
|
|
2718
|
+
out.push({ file: "vercel.json", source: source?.type === "string" ? source.value : "", value: value.value, start: value.start, end: value.end });
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
return out;
|
|
2722
|
+
}
|
|
2723
|
+
var HEADERS_LINE = /^([ \t]+)(content-security-policy)([ \t]*:[ \t]*)(.*?)([ \t]*)$/i;
|
|
2724
|
+
function headersPolicies(text) {
|
|
2725
|
+
const out = [];
|
|
2726
|
+
let path = "";
|
|
2727
|
+
let at2 = 0;
|
|
2728
|
+
text.split("\n").forEach((line, n) => {
|
|
2729
|
+
const plain2 = line.replace(/\r$/, "");
|
|
2730
|
+
if (/^\S/.test(plain2) && !plain2.startsWith("#")) path = plain2.trim();
|
|
2731
|
+
const m = HEADERS_LINE.exec(plain2);
|
|
2732
|
+
if (m) {
|
|
2733
|
+
const start = at2 + m[1].length + m[2].length + m[3].length;
|
|
2734
|
+
out.push({ file: "public/_headers", source: path, value: m[4], start, end: start + m[4].length, line: n + 1 });
|
|
2735
|
+
}
|
|
2736
|
+
at2 += line.length + 1;
|
|
2737
|
+
});
|
|
2738
|
+
return out;
|
|
2739
|
+
}
|
|
2740
|
+
function policiesIn(file, text) {
|
|
2741
|
+
if (text === null) return { policies: [], invalid: false };
|
|
2742
|
+
try {
|
|
2743
|
+
if (file.endsWith("vercel.json")) return { policies: vercelPolicies(text), invalid: false };
|
|
2744
|
+
if (file.endsWith("_headers")) return { policies: headersPolicies(text), invalid: false };
|
|
2745
|
+
} catch {
|
|
2746
|
+
return { policies: [], invalid: true };
|
|
2747
|
+
}
|
|
2748
|
+
return { policies: [], invalid: false };
|
|
2749
|
+
}
|
|
2750
|
+
var blockingIn = (file, text, endpoint = COLLECTOR) => policiesIn(file, text).policies.filter((p) => !policyAllows(p.value, endpoint));
|
|
2751
|
+
function edited(file, text, change) {
|
|
2752
|
+
const { policies } = policiesIn(file, text);
|
|
2753
|
+
let out = text;
|
|
2754
|
+
for (const p of [...policies].sort((a, b) => b.start - a.start)) {
|
|
2755
|
+
const next = change(p.value);
|
|
2756
|
+
if (next === p.value) continue;
|
|
2757
|
+
const literal = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
|
|
2758
|
+
out = `${out.slice(0, p.start)}${literal}${out.slice(p.end)}`;
|
|
2759
|
+
}
|
|
2760
|
+
return out;
|
|
2761
|
+
}
|
|
2762
|
+
var withCollectorIn = (file, text, origin = COLLECTOR_ORIGIN) => edited(file, text, (p) => withCollector(p, origin));
|
|
2763
|
+
var withoutCollectorIn = (file, text, origin = COLLECTOR_ORIGIN) => edited(file, text, (p) => withoutCollector(p, origin));
|
|
2764
|
+
function onlyCollectorChanged(file, before, after) {
|
|
2765
|
+
if (before === null || after === null) return false;
|
|
2766
|
+
const a = policiesIn(file, before);
|
|
2767
|
+
const b = policiesIn(file, after);
|
|
2768
|
+
if (a.invalid || b.invalid) return false;
|
|
2769
|
+
const plain2 = (text) => edited(file, text, plainPolicy);
|
|
2770
|
+
if (file.endsWith("vercel.json")) {
|
|
2771
|
+
try {
|
|
2772
|
+
return JSON.stringify(JSON.parse(plain2(before))) === JSON.stringify(JSON.parse(plain2(after)));
|
|
2773
|
+
} catch {
|
|
2774
|
+
return false;
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
return plain2(before) === plain2(after);
|
|
2778
|
+
}
|
|
2779
|
+
var CODE2 = /\.(m?[jt]sx?|c[jt]s|astro|html?|vue|svelte|toml|ya?ml)$/;
|
|
2780
|
+
function cspElsewhere(path, text) {
|
|
2781
|
+
if (!text || CSP_FILES.includes(path) || path.includes("node_modules/") || !CODE2.test(path)) return null;
|
|
2782
|
+
if (/http-?equiv\s*=\s*\{?\s*["'`]content-security-policy/i.test(text)) return "a <meta http-equiv> tag";
|
|
2783
|
+
if (/content-security-policy/i.test(text)) {
|
|
2784
|
+
if (/(^|\/)next\.config\.[mc]?[jt]s$/.test(path)) return "next.config's headers()";
|
|
2785
|
+
if (/(^|\/)netlify\.toml$/.test(path)) return "netlify.toml's headers";
|
|
2786
|
+
if (/(^|\/)middleware\.[mc]?[jt]s$/.test(path)) return "a middleware";
|
|
2787
|
+
return "a Content-Security-Policy header";
|
|
2788
|
+
}
|
|
2789
|
+
if (/(^|\/)astro\.config\.[mc]?[jt]s$/.test(path) && /\bcsp\s*:/.test(text)) return "Astro's own CSP (its `csp` option)";
|
|
2790
|
+
return null;
|
|
2791
|
+
}
|
|
1912
2792
|
export {
|
|
1913
2793
|
pages_core_exports as core,
|
|
2794
|
+
csp_exports as csp,
|
|
1914
2795
|
detect,
|
|
1915
2796
|
readSettings,
|
|
1916
2797
|
registryFiles,
|