@unbase-app/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1918 @@
1
+ // ============================================================================
2
+ // GENERATED by kit/cli/scripts/readers.mjs; do not edit. Regenerate with
3
+ // node kit/cli/scripts/readers.mjs
4
+ //
5
+ // Unbase's readers, bundled from the Edge Functions' own source:
6
+ // detect supabase/functions/unbase-projects/detect.ts (detectRepo)
7
+ // readSettings supabase/functions/unbase-projects/settings.ts (read_settings)
8
+ // registryOf supabase/functions/unbase-projects/pages.ts (list_pages)
9
+ // core supabase/functions/_shared/pages-core.mjs (= kit/pages/core.mjs)
10
+ // ============================================================================
11
+ var __defProp = Object.defineProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // supabase/functions/unbase-projects/adapter.ts
18
+ function within(paths, appPath) {
19
+ if (!appPath) return paths;
20
+ const prefix = `${appPath}/`;
21
+ return paths.filter((p) => p.startsWith(prefix)).map((p) => p.slice(prefix.length));
22
+ }
23
+ var join = (appPath, path) => appPath ? `${appPath}/${path}` : path;
24
+
25
+ // supabase/functions/unbase-projects/adapters/astro.ts
26
+ var LITERAL_IN_CODE = 200;
27
+ var PAGE_CAP = 60;
28
+ var PAGE = /\.(astro|md|mdx|html)$/;
29
+ var TECHNICAL = /^(class|class:list|style|href|src|srcset|sizes|d|viewbox|points|transform|media|rel|sandbox|allow|id|for|type|name|lang|role|slot|loading|decoding|fetchpriority|width|height|is:.*|client:.*|set:.*|define:vars|data-.*)$/i;
30
+ function stripExpressions(source) {
31
+ let out = "";
32
+ let depth = 0;
33
+ for (let i = 0; i < source.length; i++) {
34
+ const c = source[i];
35
+ if (c === "{") depth++;
36
+ else if (c === "}") depth = Math.max(0, depth - 1);
37
+ else if (depth === 0) out += c;
38
+ }
39
+ return out;
40
+ }
41
+ var prose = (value) => new RegExp("\\p{L}{2,}", "u").test(value) && /\s\S/.test(value.trim());
42
+ function literalText(source) {
43
+ let rest = source;
44
+ let count = 0;
45
+ const front = /^\s*---\r?\n([\s\S]*?)\r?\n---/.exec(rest);
46
+ if (front) {
47
+ for (const m of front[1].matchAll(/(["'`])((?:\\.|(?!\1)[^\\])*)\1/g)) {
48
+ const value = m[2];
49
+ if (!value.includes("${") && !/^[./@~]/.test(value) && (value.match(/\s+/g)?.length ?? 0) >= 2 && prose(value)) count += value.trim().length;
50
+ }
51
+ rest = rest.slice(front[0].length);
52
+ }
53
+ rest = rest.replace(/<script\b[\s\S]*?<\/script>/gi, " ").replace(/<style\b[\s\S]*?<\/style>/gi, " ").replace(/<!--[\s\S]*?-->/g, " ");
54
+ rest = stripExpressions(rest);
55
+ for (const tag of rest.matchAll(/<[A-Za-z][^>]*>/g)) {
56
+ for (const attr of tag[0].matchAll(/([A-Za-z_:][-A-Za-z0-9_:.]*)\s*=\s*(["'])(.*?)\2/g)) {
57
+ if (!TECHNICAL.test(attr[1]) && prose(attr[3])) count += attr[3].trim().length;
58
+ }
59
+ }
60
+ const text = rest.replace(/<[^>]*>/g, " ").replace(/&[a-z]+;|&#\d+;/gi, " ").replace(/\s+/g, " ").trim();
61
+ return count + text.replace(/\s/g, "").length;
62
+ }
63
+ function groupOf(pagePath) {
64
+ const [first, ...more] = pagePath.split("/");
65
+ if (more.length) return first;
66
+ const name = first.replace(PAGE, "");
67
+ return name === "index" ? "/" : name;
68
+ }
69
+ function spread(groups, cap) {
70
+ const queues = [...groups.values()].map((pages) => [...pages]);
71
+ const picked = [];
72
+ while (picked.length < cap && queues.some((q) => q.length)) {
73
+ for (const q of queues) {
74
+ const next = q.shift();
75
+ if (next && picked.length < cap) picked.push(next);
76
+ }
77
+ }
78
+ return picked;
79
+ }
80
+ async function textLocation(repo, app, files) {
81
+ const collections = [
82
+ ...new Set(
83
+ files.filter((p) => p.startsWith("src/content/")).map((p) => p.split("/")).filter((parts) => parts.length > 3 && !parts[2].startsWith(".")).map((parts) => parts[2])
84
+ )
85
+ ].sort();
86
+ const pages = files.filter((p) => p.startsWith("src/pages/") && PAGE.test(p)).map((p) => p.slice("src/pages/".length));
87
+ const groups = /* @__PURE__ */ new Map();
88
+ for (const page of pages.sort()) {
89
+ const g = groupOf(page);
90
+ groups.set(g, [...groups.get(g) ?? [], page]);
91
+ }
92
+ const literal = /* @__PURE__ */ new Map();
93
+ await Promise.all(
94
+ spread(groups, PAGE_CAP).map(async (page) => {
95
+ const source = await repo.read(join(app.path, `src/pages/${page}`));
96
+ if (source !== null) literal.set(page, literalText(source));
97
+ })
98
+ );
99
+ const result = [...groups].map(([group, list]) => {
100
+ const total = list.reduce((sum, p) => sum + (literal.get(p) ?? 0), 0);
101
+ return { group, pages: list.length, literal: total, in: total > LITERAL_IN_CODE ? "code" : "content" };
102
+ });
103
+ const inCode = result.filter((g) => g.in === "code").length;
104
+ const summary = inCode === 0 && collections.length ? "content" : inCode === result.length || !collections.length ? "code" : "partial";
105
+ return { summary, collections, groups: result };
106
+ }
107
+ var KEY = /^[a-z0-9][a-z0-9-]{0,39}$/;
108
+ async function configValue(repo, app, files, option) {
109
+ for (const path of [join(app.path, "comment-modus.json"), "comment-modus.json"]) {
110
+ const text = await repo.read(path).catch(() => null);
111
+ if (!text) continue;
112
+ try {
113
+ const value = JSON.parse(text)?.[option];
114
+ if (typeof value === "string" && KEY.test(value)) return value;
115
+ } catch {
116
+ }
117
+ }
118
+ const source = await configSource(repo, app, files);
119
+ const found = source && new RegExp(`\\b(?:commentModus|unbase)\\s*\\(\\s*\\{[^}]*?\\b${option}\\s*:\\s*["']([a-z0-9][a-z0-9-]{0,39})["']`).exec(source)?.[1];
120
+ return found || null;
121
+ }
122
+ async function configSource(repo, app, files) {
123
+ const config = files.find((p) => /^astro\.config\.(mjs|js|ts|mts|cjs)$/.test(p));
124
+ return config ? await repo.read(join(app.path, config)) : null;
125
+ }
126
+ var COMMENTS_OFF = /\bunbase\s*\(\s*\{[^}]*?\bcomments\s*:\s*false\b/;
127
+ var astro = {
128
+ id: "astro",
129
+ framework: "astro",
130
+ async detect(repo, app) {
131
+ const files = within(repo.paths, app.path);
132
+ const [text, site, project, config] = await Promise.all([
133
+ textLocation(repo, app, files),
134
+ configValue(repo, app, files, "site"),
135
+ configValue(repo, app, files, "project"),
136
+ configSource(repo, app, files)
137
+ ]);
138
+ return { text, site, project, commentsOff: !!config && COMMENTS_OFF.test(config) };
139
+ }
140
+ };
141
+
142
+ // supabase/functions/_shared/framework-packages.ts
143
+ var COMMENT_MODE = "@jens4m/comment-modus";
144
+ var FRAMEWORK_PACKAGES = [
145
+ {
146
+ id: "astro",
147
+ packages: ["@unbase-app/astro"],
148
+ configs: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
149
+ config: "astro.config",
150
+ call: "unbase()",
151
+ agents: "agents/astro.md",
152
+ replaces: [COMMENT_MODE, "@jens4m/unbase-pages"],
153
+ // unbase({ project: commentModusConfig.project, … }): the config imports comment-modus.json.
154
+ comments: { calls: ["unbase"], options: true, readsLink: false },
155
+ schemas: "src/content/.schemas/"
156
+ },
157
+ {
158
+ // One package: the draft-pages kit and comment mode's loader in a Vite plugin (kit/vite).
159
+ id: "vite-react",
160
+ packages: ["@unbase-app/vite"],
161
+ configs: ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
162
+ config: "vite.config",
163
+ call: "unbase()",
164
+ agents: "agents/vite-react.md",
165
+ // The kit's own Vite plugin under its name before K5, which unbase() takes the place of.
166
+ replaces: ["@jens4m/unbase-pages"],
167
+ // unbase({ project?, comments? }); unbaseComments() is comment mode alone. Reads comment-modus.json itself.
168
+ comments: { calls: ["unbase", "unbaseComments"], options: true, readsLink: true }
169
+ },
170
+ {
171
+ // One package: the draft-pages kit's core and comment mode's loader, one wrapper around next.config (kit/next).
172
+ id: "next",
173
+ packages: ["@unbase-app/next"],
174
+ configs: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
175
+ config: "next.config",
176
+ call: "withUnbase(\u2026)",
177
+ agents: "agents/next.md",
178
+ // withUnbase(nextConfig): its argument is the site's own config. Reads comment-modus.json itself.
179
+ comments: { calls: ["withUnbase"], options: false, readsLink: true },
180
+ loader: { file: "instrumentation-client", before: "16.3" }
181
+ }
182
+ ];
183
+ var frameworkPackage = (id) => FRAMEWORK_PACKAGES.find((f) => f.id === id) ?? null;
184
+
185
+ // supabase/functions/unbase-projects/detect.ts
186
+ var ADAPTERS = [astro];
187
+ var FRAMEWORKS = [
188
+ { id: "astro", name: "Astro", dep: "astro", public: "PUBLIC_" },
189
+ { id: "next", name: "Next.js", dep: "next", public: "NEXT_PUBLIC_" },
190
+ { id: "nuxt", name: "Nuxt", dep: "nuxt", public: "NUXT_PUBLIC_" },
191
+ { id: "sveltekit", name: "SvelteKit", dep: "@sveltejs/kit", public: "PUBLIC_" },
192
+ { id: "react-router", name: "React Router", dep: "@react-router/dev", public: "VITE_" },
193
+ { id: "remix", name: "Remix", dep: "@remix-run/react", public: "VITE_" },
194
+ { id: "gatsby", name: "Gatsby", dep: "gatsby", public: "GATSBY_" },
195
+ { id: "vite-react", name: "Vite + React", dep: "vite", also: "react", public: "VITE_" }
196
+ ];
197
+ var STORABLE = /^(PUBLIC|NEXT_PUBLIC|VITE)_[A-Z0-9_]{1,60}$/;
198
+ var CMS = [
199
+ { id: "sanity", name: "Sanity", deps: /^(sanity|@sanity\/.+|next-sanity)$/, config: /(^|\/)sanity\.config\.(ts|js|mjs|tsx|jsx)$/ },
200
+ { id: "contentful", name: "Contentful", deps: /^contentful(-management)?$/ },
201
+ { id: "storyblok", name: "Storyblok", deps: /^(@storyblok\/.+|storyblok-js-client)$/ },
202
+ { id: "payload", name: "Payload", deps: /^(payload|@payloadcms\/.+)$/, config: /(^|\/)payload\.config\.(ts|js)$/ },
203
+ { id: "decap", name: "Decap CMS", deps: /^(decap-cms(-app)?|netlify-cms(-app)?)$/, config: /(^|\/)public\/admin\/config\.ya?ml$/ },
204
+ { id: "tina", name: "TinaCMS", deps: /^(tinacms|@tinacms\/.+)$/, config: /(^|\/)tina\/config\.(ts|js|tsx)$/ },
205
+ { id: "keystatic", name: "Keystatic", deps: /^@keystatic\/.+$/, config: /(^|\/)keystatic\.config\.(ts|tsx|js)$/ },
206
+ { id: "prismic", name: "Prismic", deps: /^@prismicio\/.+$/ },
207
+ { id: "strapi", name: "Strapi", deps: /^@strapi\/.+$/ },
208
+ { id: "directus", name: "Directus", deps: /^@directus\/.+$/ },
209
+ { id: "builder", name: "Builder.io", deps: /^@builder\.io\/.+$/ },
210
+ { id: "datocms", name: "DatoCMS", deps: /^(datocms-.+|@datocms\/.+)$/ }
211
+ ];
212
+ var SERVICES = [
213
+ { id: "supabase", name: "Supabase", deps: /^@supabase\/.+$/ },
214
+ { id: "firebase", name: "Firebase", deps: /^(firebase|firebase-admin|@firebase\/.+)$/ },
215
+ { id: "mapbox", name: "Mapbox", deps: /^(mapbox-gl|react-map-gl|@mapbox\/.+)$/ },
216
+ { id: "google-maps", name: "Google Maps", deps: /^(@react-google-maps\/api|@googlemaps\/.+|@vis\.gl\/react-google-maps)$/ },
217
+ { id: "stripe", name: "Stripe", deps: /^(stripe|@stripe\/.+)$/ },
218
+ { id: "clerk", name: "Clerk", deps: /^@clerk\/.+$/ },
219
+ { id: "auth0", name: "Auth0", deps: /^(@auth0\/.+|auth0)$/ },
220
+ { id: "algolia", name: "Algolia", deps: /^(algoliasearch|react-instantsearch.*|@algolia\/.+)$/ },
221
+ { id: "resend", name: "Resend", deps: /^resend$/ },
222
+ { id: "sentry", name: "Sentry", deps: /^@sentry\/.+$/ },
223
+ { id: "posthog", name: "PostHog", deps: /^(posthog-js|posthog-node)$/ },
224
+ { id: "mailchimp", name: "Mailchimp", deps: /^@mailchimp\/.+$/ }
225
+ ];
226
+ var LOCKFILES = [
227
+ ["package-lock.json", "npm"],
228
+ ["pnpm-lock.yaml", "pnpm"],
229
+ ["yarn.lock", "yarn"],
230
+ ["bun.lock", "bun"],
231
+ ["bun.lockb", "bun"]
232
+ ];
233
+ var PACKAGE_JSON_CAP = 30;
234
+ function versionOf(range) {
235
+ const m = /(\d+)(\.\d+)?(\.\d+)?/.exec(range ?? "");
236
+ return m ? { version: m[0], major: Number(m[1]) } : { version: null, major: null };
237
+ }
238
+ var depsOf = (pkg) => ({ ...pkg.devDependencies ?? {}, ...pkg.dependencies ?? {} });
239
+ var frameworkOf = (deps) => FRAMEWORKS.find((f) => f.dep in deps && (!f.also || f.also in deps)) ?? null;
240
+ async function readJson(repo, path) {
241
+ const text = await repo.read(path);
242
+ if (!text) return null;
243
+ try {
244
+ return JSON.parse(text);
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+ async function packages(repo) {
250
+ const paths = repo.paths.filter((p) => (p === "package.json" || p.endsWith("/package.json")) && !p.includes("node_modules/")).filter((p) => p.split("/").length <= 4).sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b)).slice(0, PACKAGE_JSON_CAP);
251
+ const read = await Promise.all(paths.map(async (p) => ({ path: p.replace(/\/?package\.json$/, ""), pkg: await readJson(repo, p) })));
252
+ return read.filter((r) => r.pkg).map((r) => ({ path: r.path, pkg: r.pkg, deps: depsOf(r.pkg) }));
253
+ }
254
+ function packageManager(repo, appPath, root) {
255
+ for (const folder of appPath ? [appPath, ""] : [""]) {
256
+ const found = LOCKFILES.find(([file]) => repo.paths.includes(join(folder, file)));
257
+ if (found) return found[1];
258
+ }
259
+ const field = root?.pkg.packageManager;
260
+ return typeof field === "string" ? field.split("@")[0] || null : null;
261
+ }
262
+ function cmsOf(repo, app, root) {
263
+ const deps = { ...root?.deps ?? {}, ...app.deps };
264
+ const files = within(repo.paths, app.path);
265
+ 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 }) => ({
266
+ id,
267
+ name
268
+ }));
269
+ }
270
+ var SOURCE = /\.(m?[jt]sx?|cjs|astro|vue|svelte)$/;
271
+ var SKIP = /(^|\/)(node_modules|dist|build|out|coverage|public|\.next|\.astro|\.vercel|\.output|\.svelte-kit|\.turbo)\//;
272
+ var TESTS = /(^|\/)(__tests__|tests?)\/|\.(test|spec)\.[^/]+$/;
273
+ var EXAMPLE = /(^|\/)\.env(\.[a-z]+)*\.(example|sample|template)$/;
274
+ var LIKELY = /(^|\/)([^/]*(env|config|settings|constants|client|sanity|supabase|firebase|stripe|mapbox|map|analytics|auth|mail|search|cms|api)[^/]*|layout|_app|_document|main|root)\.[^/]+$/i;
275
+ var CONFIG = /(^|\/)(next|astro|vite|nuxt|svelte|remix|gatsby|react-router)\.config\.[^/]+$/;
276
+ var SERVER = /(^|\/)(api|server)\/|\.server\.[^/]+$/;
277
+ var SOURCE_CAP = 30;
278
+ var AT_ONCE = 8;
279
+ var NAMES_CAP = 100;
280
+ var PROVIDED = /* @__PURE__ */ new Set(["NODE_ENV", "MODE", "DEV", "PROD", "SSR", "BASE_URL", "SITE", "ASSETS_PREFIX", "NEXT_RUNTIME", "NEXT_PHASE", "PORT", "HOST", "HOSTNAME", "CI", "TZ", "PWD", "HOME", "CONTEXT", "URL", "DEPLOY_URL"]);
281
+ var PROVIDED_PREFIX = /^(VERCEL|NETLIFY|CF_PAGES|RENDER|RAILWAY|UNBASE|npm)_/;
282
+ var NAME = /^[A-Z_][A-Z0-9_]*$/;
283
+ var ACCESS = [/process\.env\.([A-Z_][A-Z0-9_]*)/g, /process\.env\[\s*["'`]([A-Z_][A-Z0-9_]*)["'`]\s*\]/g, /import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g];
284
+ var GROUPS = [/\{([^{}]*)\}\s*=\s*(?:process\.env|import\.meta\.env|loadEnv\s*\()/g, /import\s*\{([^{}]*)\}\s*from\s*["']\$env\/(?:static|dynamic)\/(?:public|private)["']/g];
285
+ function namesIn(text) {
286
+ const out = /* @__PURE__ */ new Set();
287
+ for (const re of ACCESS) for (const m of text.matchAll(re)) out.add(m[1]);
288
+ for (const re of GROUPS) {
289
+ for (const m of text.matchAll(re)) {
290
+ for (const part of m[1].split(",")) {
291
+ const key = part.replace(/^\s*\.\.\./, "").split(/[:=]/)[0].trim().replace(/\s+as\s+\w+$/, "");
292
+ if (NAME.test(key)) out.add(key);
293
+ }
294
+ }
295
+ }
296
+ return [...out];
297
+ }
298
+ function namesInExample(text) {
299
+ return [...text.matchAll(/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=/gm)].map((m) => m[1]);
300
+ }
301
+ var provided = (name) => PROVIDED.has(name) || PROVIDED_PREFIX.test(name);
302
+ function isPublic(name, framework) {
303
+ if (!STORABLE.test(name)) return false;
304
+ const fw = FRAMEWORKS.find((f) => f.id === framework);
305
+ return fw ? name.startsWith(fw.public) : true;
306
+ }
307
+ async function settingsOf(repo, appPath, framework) {
308
+ const inApp = within(repo.paths, appPath).map((p) => join(appPath, p));
309
+ const examples = [.../* @__PURE__ */ new Set([...inApp.filter((p) => EXAMPLE.test(p)), ...repo.paths.filter((p) => !p.includes("/") && EXAMPLE.test(p))])];
310
+ const sources = inApp.filter((p) => SOURCE.test(p) && !SKIP.test(p) && !TESTS.test(p) && (CONFIG.test(p) || LIKELY.test(p) || SERVER.test(p))).sort((a, b) => Number(!CONFIG.test(a)) - Number(!CONFIG.test(b)) || a.split("/").length - b.split("/").length || a.localeCompare(b));
311
+ const read = sources.slice(0, SOURCE_CAP);
312
+ const seen = /* @__PURE__ */ new Map();
313
+ const note = (name, file, example = false) => {
314
+ if (provided(name)) return;
315
+ const s = seen.get(name) ?? { files: [], example: false };
316
+ if (file && s.files.length < 3 && !s.files.includes(file)) s.files.push(file);
317
+ if (example) s.example = true;
318
+ seen.set(name, s);
319
+ };
320
+ let next = 0;
321
+ await Promise.all(
322
+ Array.from({ length: Math.min(AT_ONCE, read.length) }, async () => {
323
+ while (next < read.length) {
324
+ const path = read[next++];
325
+ const text = await repo.read(path);
326
+ if (text) for (const name of namesIn(text)) note(name, path);
327
+ }
328
+ })
329
+ );
330
+ for (const path of examples) {
331
+ const text = await repo.read(path);
332
+ if (text) for (const name of namesInExample(text)) note(name, null, true);
333
+ }
334
+ const settings = [...seen.entries()].map(([name, s]) => ({ name, public: isPublic(name, framework), files: s.files, example: s.example })).sort((a, b) => Number(b.public) - Number(a.public) || a.name.localeCompare(b.name)).slice(0, NAMES_CAP);
335
+ return { settings, truncated: sources.length > SOURCE_CAP || seen.size > NAMES_CAP };
336
+ }
337
+ var IMAGE_CONFIGS = {
338
+ next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"],
339
+ astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js"]
340
+ };
341
+ var IMAGE_HOSTS_CAP = 10;
342
+ var HOST = /^(\*\.)?([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/;
343
+ var imageConfigsOf = (appPath, framework) => (IMAGE_CONFIGS[framework ?? ""] ?? []).map((f) => join(appPath, f));
344
+ function imageHostsIn(text) {
345
+ const found = [];
346
+ for (const m of text.matchAll(/\bhostname\s*:\s*["'`]([^"'`\s]+)["'`]/g)) found.push(m[1]);
347
+ for (const m of text.matchAll(/new\s+URL\(\s*["'`]https?:\/\/([^/"'`\s:]+)/g)) found.push(m[1]);
348
+ for (const m of text.matchAll(/\bdomains\s*:\s*\[([^\]]*)\]/g)) {
349
+ if (!m[1].includes("{")) for (const s of m[1].matchAll(/["'`]([^"'`\s]+)["'`]/g)) found.push(s[1]);
350
+ }
351
+ const hosts = found.map((h) => h.toLowerCase().replace(/^\*\*\./, "*.")).filter((h) => HOST.test(h));
352
+ return [...new Set(hosts)].slice(0, IMAGE_HOSTS_CAP);
353
+ }
354
+ async function imageHostsOf(read, paths) {
355
+ for (const path of paths) {
356
+ const text = await read(path);
357
+ if (text !== null) return imageHostsIn(text);
358
+ }
359
+ return [];
360
+ }
361
+ function servicesOf(app, root) {
362
+ const deps = Object.keys({ ...root?.deps ?? {}, ...app.deps });
363
+ return [...CMS, ...SERVICES].filter((s) => deps.some((d) => s.deps.test(d))).map(({ id, name }) => ({ id, name }));
364
+ }
365
+ async function detect(repo, branch, truncated, appPath) {
366
+ const all = await packages(repo);
367
+ const root = all.find((a) => a.path === "");
368
+ const apps = all.filter((a) => frameworkOf(a.deps)).map((a) => ({ path: a.path, framework: frameworkOf(a.deps).id }));
369
+ const empty = {
370
+ branch,
371
+ truncated,
372
+ apps,
373
+ app_path: null,
374
+ framework: null,
375
+ adapter: null,
376
+ package_manager: null,
377
+ cms: [],
378
+ comment_modus: { state: "absent" },
379
+ text: null,
380
+ settings: [],
381
+ settings_truncated: false,
382
+ services: [],
383
+ image_hosts: []
384
+ };
385
+ let chosen;
386
+ if (appPath !== void 0) {
387
+ chosen = all.find((a) => a.path === appPath && frameworkOf(a.deps)) ?? (appPath === "" ? root : void 0);
388
+ if (!chosen) throw new RangeError("app_path");
389
+ } else if (apps.length === 1) {
390
+ chosen = all.find((a) => a.path === apps[0].path);
391
+ } else if (apps.length === 0) {
392
+ chosen = root;
393
+ } else {
394
+ return empty;
395
+ }
396
+ if (!chosen) return { ...empty, app_path: "" };
397
+ const fw = frameworkOf(chosen.deps);
398
+ const adapter = fw ? ADAPTERS.find((a) => a.framework === fw.id) ?? null : null;
399
+ const found = adapter ? await adapter.detect(repo, chosen) : { text: null, site: null, project: null };
400
+ const cmRange = chosen.deps[COMMENT_MODE] ?? root?.deps[COMMENT_MODE];
401
+ const carrier = fw && frameworkPackage(fw.id)?.comments ? frameworkPackage(fw.id).packages[0] ?? null : null;
402
+ const carried = !!carrier && !!(chosen.deps[carrier] ?? root?.deps[carrier]) && !found.commentsOff;
403
+ const { settings, truncated: settingsTruncated } = await settingsOf(repo, chosen.path, fw?.id ?? null);
404
+ const imageHosts = await imageHostsOf(repo.read, imageConfigsOf(chosen.path, fw?.id ?? null).filter((p) => repo.paths.includes(p)));
405
+ return {
406
+ ...empty,
407
+ app_path: chosen.path,
408
+ framework: fw ? { id: fw.id, name: fw.name, ...versionOf(chosen.deps[fw.dep]) } : null,
409
+ adapter: adapter?.id ?? null,
410
+ package_manager: packageManager(repo, chosen.path, root),
411
+ cms: cmsOf(repo, chosen, root),
412
+ comment_modus: cmRange || carried ? { state: "installed", version: cmRange ? versionOf(cmRange).version : null, site: found.site, project: found.project } : { state: "absent" },
413
+ text: found.text,
414
+ settings,
415
+ settings_truncated: settingsTruncated,
416
+ services: servicesOf(chosen, root),
417
+ image_hosts: imageHosts
418
+ };
419
+ }
420
+
421
+ // supabase/functions/_shared/html-head.ts
422
+ var headPointer = (field) => `/head/${field}`;
423
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
424
+ function decodeValue(raw) {
425
+ 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();
426
+ }
427
+ function tagsIn(html, from, until) {
428
+ const out = [];
429
+ let i = from;
430
+ while (i < until) {
431
+ const lt = html.indexOf("<", i);
432
+ if (lt < 0 || lt >= until) break;
433
+ if (html.startsWith("<!--", lt)) {
434
+ const close = html.indexOf("-->", lt + 4);
435
+ i = close < 0 ? until : close + 3;
436
+ continue;
437
+ }
438
+ const name = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(lt, lt + 64))?.[1];
439
+ if (!name) {
440
+ i = lt + 1;
441
+ continue;
442
+ }
443
+ const attrs = [];
444
+ let j = lt + 1 + name.length;
445
+ let end = -1;
446
+ while (j < html.length) {
447
+ const c = html[j];
448
+ if (c === ">") {
449
+ end = j + 1;
450
+ break;
451
+ }
452
+ if (/[\s/]/.test(c)) {
453
+ j++;
454
+ continue;
455
+ }
456
+ const m = /^([^\s"'>/=]+)(\s*=\s*)?/.exec(html.slice(j, j + 256));
457
+ if (!m) {
458
+ j++;
459
+ continue;
460
+ }
461
+ j += m[0].length;
462
+ if (!m[2]) {
463
+ attrs.push({ name: m[1].toLowerCase(), value: "", start: j, end: j, quote: null });
464
+ continue;
465
+ }
466
+ const q = html[j];
467
+ if (q === '"' || q === "'") {
468
+ const close = html.indexOf(q, j + 1);
469
+ if (close < 0) break;
470
+ attrs.push({ name: m[1].toLowerCase(), value: html.slice(j + 1, close), start: j + 1, end: close, quote: q });
471
+ j = close + 1;
472
+ } else {
473
+ const bare = /^[^\s>]*/.exec(html.slice(j))[0];
474
+ attrs.push({ name: m[1].toLowerCase(), value: bare, start: j, end: j + bare.length, quote: null });
475
+ j += bare.length;
476
+ }
477
+ }
478
+ if (end < 0) break;
479
+ out.push({ name: name.toLowerCase(), start: lt, end, attrs });
480
+ i = end;
481
+ if (/^(script|style)$/i.test(name)) {
482
+ const close = html.toLowerCase().indexOf(`</${name.toLowerCase()}`, end);
483
+ i = close < 0 ? until : close;
484
+ }
485
+ }
486
+ return out;
487
+ }
488
+ var attrOf = (tag, name) => tag.attrs.find((a) => a.name === name);
489
+ var spanOf = (a) => ({ start: a.start, end: a.end, mode: "attr", quote: a.quote });
490
+ var plain = (raw) => !/[{}]|<%|%>/.test(raw);
491
+ function readHead(html) {
492
+ const out = {};
493
+ const lower = html.toLowerCase();
494
+ const headAt = lower.search(/<head[\s>]/);
495
+ const bodyAt = lower.search(/<body[\s>]/);
496
+ const headEnd = lower.indexOf("</head");
497
+ const until = headEnd >= 0 ? headEnd : bodyAt >= 0 ? bodyAt : html.length;
498
+ if (headAt < 0) return out;
499
+ const htmlTag = tagsIn(html, 0, headAt).find((t) => t.name === "html");
500
+ const lang = htmlTag && attrOf(htmlTag, "lang");
501
+ if (lang && lang.value.trim() && plain(lang.value)) out.language = { value: decodeValue(lang.value), spans: [spanOf(lang)] };
502
+ const tags = tagsIn(html, headAt, until);
503
+ const metas = tags.filter((t) => t.name === "meta");
504
+ 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);
505
+ const fromMeta = (key, copies) => {
506
+ const found = meta(key);
507
+ if (found.length !== 1 || !plain(found[0].value) || !found[0].value.trim()) return void 0;
508
+ const value = decodeValue(found[0].value);
509
+ return { value, spans: [spanOf(found[0]), ...copiesOf(value, copies)] };
510
+ };
511
+ const copiesOf = (value, keys) => keys.flatMap((k) => meta(k)).filter((a) => plain(a.value) && decodeValue(a.value) === value).map(spanOf);
512
+ const titles = tags.filter((t) => t.name === "title");
513
+ if (titles.length === 1) {
514
+ const t = titles[0];
515
+ const close = lower.indexOf("</title", t.end);
516
+ const raw = close >= 0 ? html.slice(t.end, close) : "";
517
+ if (close >= 0 && raw.trim() && !raw.includes("<") && plain(raw)) {
518
+ const value = decodeValue(raw);
519
+ out.title = { value, spans: [{ start: t.end, end: close, mode: "text", quote: null }, ...copiesOf(value, ["og:title", "twitter:title"])] };
520
+ }
521
+ }
522
+ const description = fromMeta("description", ["og:description", "twitter:description"]);
523
+ if (description) out.description = description;
524
+ const image = fromMeta("og:image", ["twitter:image"]);
525
+ if (image) out.image = image;
526
+ const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
527
+ const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
528
+ for (const [field, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
529
+ const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
530
+ const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
531
+ if (href && href.value.trim() && plain(href.value)) out[field] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
532
+ }
533
+ return out;
534
+ }
535
+
536
+ // supabase/functions/_shared/pages-core.mjs
537
+ var pages_core_exports = {};
538
+ __export(pages_core_exports, {
539
+ DRAFTABLE: () => DRAFTABLE,
540
+ KIT: () => KIT,
541
+ KITS: () => KITS,
542
+ PAGE_FILE: () => PAGE_FILE,
543
+ deployContext: () => deployContext,
544
+ discover: () => discover,
545
+ draftCheck: () => draftCheck,
546
+ draftPaths: () => draftPaths,
547
+ draftPlan: () => draftPlan,
548
+ importGraph: () => importGraph,
549
+ kitFiles: () => kitFiles,
550
+ kitInstalled: () => kitInstalled,
551
+ leakPrints: () => leakPrints,
552
+ leaksIn: () => leaksIn,
553
+ linksTo: () => linksTo,
554
+ listTools: () => listTools,
555
+ mediaGenerators: () => mediaGenerators,
556
+ normalisePath: () => normalisePath,
557
+ ownedContent: () => ownedContent,
558
+ parsePageFile: () => parsePageFile,
559
+ removeRoutes: () => removeRoutes,
560
+ resolveImport: () => resolveImport,
561
+ segmentFiles: () => segmentFiles,
562
+ sentences: () => sentences,
563
+ stripComments: () => stripComments,
564
+ withoutInContentMap: () => withoutInContentMap,
565
+ withoutInPageList: () => withoutInPageList,
566
+ withoutInSitemap: () => withoutInSitemap
567
+ });
568
+ var PAGE_FILE = "unbase.pages.json";
569
+ var KIT = "@unbase-app/pages";
570
+ var KITS = {
571
+ astro: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
572
+ "vite-react": [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
573
+ next: ["@unbase-app/next"]
574
+ };
575
+ var DRAFTABLE = Object.keys(KITS);
576
+ var EXTS = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".mts", ".astro", ".vue", ".svelte", ".json"];
577
+ var CODE = /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html)$/;
578
+ var SKIP2 = /(^|\/)(node_modules|dist|build|\.git|\.astro|\.next|\.vercel|\.output)(\/|$)/;
579
+ var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
580
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
581
+ function normalisePath(p) {
582
+ const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
583
+ return s || "/";
584
+ }
585
+ function parsePageFile(text) {
586
+ if (text == null) return { ok: true, exists: false, pages: {} };
587
+ const fail = (error) => ({ ok: (
588
+ /** @type {const} */
589
+ false
590
+ ), exists: true, error, pages: {} });
591
+ let data;
592
+ try {
593
+ data = JSON.parse(text);
594
+ } catch {
595
+ return fail("not valid JSON");
596
+ }
597
+ if (!isObject(data)) return fail("the file is not an object");
598
+ const pages = data.pages ?? {};
599
+ if (!isObject(pages)) return fail("`pages` is not an object");
600
+ const out = {};
601
+ for (const [address2, entry] of Object.entries(pages)) {
602
+ if (!address2.startsWith("/")) return fail(`${address2}: an address starts with /`);
603
+ if (!isObject(entry)) return fail(`${address2}: not an object`);
604
+ if (entry.draft !== void 0 && typeof entry.draft !== "boolean") return fail(`${address2}: draft is true or false`);
605
+ out[normalisePath(address2)] = entry.draft === void 0 ? {} : { draft: entry.draft };
606
+ }
607
+ return { ok: true, exists: true, pages: out };
608
+ }
609
+ var draftPaths = (file) => Object.keys(file.pages).filter((p) => file.pages[p].draft === true).sort();
610
+ var CONTEXTS = /* @__PURE__ */ new Set(["production", "preview", "development"]);
611
+ function deployContext({ env = {}, command = "build" } = {}) {
612
+ const own = env.UNBASE_DEPLOY_CONTEXT;
613
+ if (own) return CONTEXTS.has(own) ? { context: (
614
+ /** @type {any} */
615
+ own
616
+ ), source: "UNBASE_DEPLOY_CONTEXT" } : { context: "production", source: `UNBASE_DEPLOY_CONTEXT=${own} (unknown)` };
617
+ if (command === "dev") return { context: "development", source: "dev server" };
618
+ const vercel = env.VERCEL_ENV;
619
+ if (vercel) return { context: vercel === "preview" ? "preview" : vercel === "development" ? "development" : "production", source: `VERCEL_ENV=${vercel}` };
620
+ if (env.NETLIFY === "true" && env.CONTEXT) {
621
+ const c = env.CONTEXT;
622
+ return { context: c === "deploy-preview" || c === "branch-deploy" ? "preview" : c === "dev" ? "development" : "production", source: `CONTEXT=${c}` };
623
+ }
624
+ return { context: "production", source: "no deployment context (counts as production)" };
625
+ }
626
+ function stringEnd(src, i) {
627
+ const q = src[i];
628
+ let j = i + 1;
629
+ while (j < src.length) {
630
+ const c = src[j];
631
+ if (c === "\\") {
632
+ j += 2;
633
+ continue;
634
+ }
635
+ if (c === q) return j + 1;
636
+ if (c === "\n" && q !== "`") return i + 1;
637
+ j++;
638
+ }
639
+ return src.length;
640
+ }
641
+ function stripComments(src) {
642
+ let out = "";
643
+ let i = 0;
644
+ while (i < src.length) {
645
+ const c = src[i];
646
+ const d = src[i + 1];
647
+ if (c === "/" && d === "/") {
648
+ while (i < src.length && src[i] !== "\n") {
649
+ out += " ";
650
+ i++;
651
+ }
652
+ continue;
653
+ }
654
+ if (c === "/" && d === "*") {
655
+ const end = src.indexOf("*/", i + 2);
656
+ const stop = end < 0 ? src.length : end + 2;
657
+ out += src.slice(i, stop).replace(/[^\n]/g, " ");
658
+ i = stop;
659
+ continue;
660
+ }
661
+ if (c === '"' || c === "'" || c === "`") {
662
+ const j = stringEnd(src, i);
663
+ out += src.slice(i, j);
664
+ i = j;
665
+ continue;
666
+ }
667
+ out += c;
668
+ i++;
669
+ }
670
+ return out;
671
+ }
672
+ var dirname = (p) => p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "";
673
+ function joinRelative(dir, spec) {
674
+ const parts = dir ? dir.split("/") : [];
675
+ for (const s of spec.split("/")) {
676
+ if (s === "." || s === "") continue;
677
+ if (s === "..") parts.pop();
678
+ else parts.push(s);
679
+ }
680
+ return parts.join("/");
681
+ }
682
+ function resolveImport(from, spec, have) {
683
+ let base;
684
+ if (spec.startsWith("@/")) base = `src/${spec.slice(2)}`;
685
+ else if (spec.startsWith("./") || spec.startsWith("../")) base = joinRelative(dirname(from), spec);
686
+ else return null;
687
+ base = base.replace(/\?.*$/, "");
688
+ for (const c of [base, ...EXTS.map((e) => base + e), ...EXTS.map((e) => `${base}/index${e}`)]) if (have.has(c)) return c;
689
+ return null;
690
+ }
691
+ var IMPORTS = [
692
+ /(?:import|export)\s+(?:type\s+)?[\w$*{}\s,]*?\s*from\s*["']([^"']+)["']/g,
693
+ /import\s*["']([^"']+)["']/g,
694
+ /import\(\s*["']([^"']+)["']\s*\)/g,
695
+ /require\(\s*["']([^"']+)["']\s*\)/g
696
+ ];
697
+ function importGraph(paths, text) {
698
+ const have = new Set(paths);
699
+ const importers = /* @__PURE__ */ new Map();
700
+ for (const p of paths) {
701
+ if (!CODE.test(p) || SKIP2.test(p)) continue;
702
+ const src = text(p);
703
+ if (!src) continue;
704
+ for (const re of IMPORTS) {
705
+ re.lastIndex = 0;
706
+ for (const m of src.matchAll(re)) {
707
+ const target = resolveImport(p, m[1], have);
708
+ if (!target || target === p) continue;
709
+ if (!importers.has(target)) importers.set(target, /* @__PURE__ */ new Set());
710
+ importers.get(target).add(p);
711
+ }
712
+ }
713
+ }
714
+ return importers;
715
+ }
716
+ var address = (segments) => normalisePath(segments.join("/"));
717
+ var unlisted = (s) => s.startsWith("_") || s.startsWith("@") || s.startsWith("(.");
718
+ var routeGroup = (s) => /^\([^.)][^)]*\)$/.test(s);
719
+ function astroPages(paths) {
720
+ const out = [];
721
+ const ext = /\.(astro|md|mdx|html)$/;
722
+ for (const p of paths) {
723
+ if (!p.startsWith("src/pages/") || !ext.test(p)) continue;
724
+ const segments = p.slice("src/pages/".length).replace(ext, "").split("/");
725
+ if (segments.some((s) => s.startsWith("_"))) continue;
726
+ if (segments.at(-1) === "index") segments.pop();
727
+ if (segments.length === 1 && /^(404|500)$/.test(segments[0])) continue;
728
+ out.push({ path: address(segments), kind: segments.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
729
+ }
730
+ return out;
731
+ }
732
+ function nextPages(paths) {
733
+ const out = [];
734
+ const ext = /\.(tsx|ts|jsx|js|mdx|md)$/;
735
+ for (const base of ["app/", "src/app/"]) {
736
+ for (const p of paths) {
737
+ if (!p.startsWith(base)) continue;
738
+ const segments = p.slice(base.length).split("/");
739
+ const file = segments.pop();
740
+ if (!/^page\./.test(file) || !ext.test(file) || segments.some(unlisted)) continue;
741
+ const kept = segments.filter((s) => !routeGroup(s));
742
+ out.push({ path: address(kept), kind: kept.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
743
+ }
744
+ }
745
+ for (const base of ["pages/", "src/pages/"]) {
746
+ for (const p of paths) {
747
+ if (!p.startsWith(base) || !ext.test(p)) continue;
748
+ const segments = p.slice(base.length).replace(ext, "").split("/");
749
+ if (segments[0] === "api" || segments.some(unlisted)) continue;
750
+ if (segments.at(-1) === "index") segments.pop();
751
+ if (segments.length === 1 && /^(404|500)$/.test(segments[0])) continue;
752
+ out.push({ path: address(segments), kind: segments.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
753
+ }
754
+ }
755
+ return out;
756
+ }
757
+ function tagEnd(src, from) {
758
+ let depth = 0;
759
+ let i = from;
760
+ while (i < src.length) {
761
+ const c = src[i];
762
+ if (c === '"' || c === "'" || c === "`") {
763
+ i = stringEnd(src, i);
764
+ continue;
765
+ }
766
+ if (c === "{") depth++;
767
+ else if (c === "}") depth--;
768
+ else if (depth === 0 && c === "/" && src[i + 1] === ">") return { end: i + 2, selfClosing: true };
769
+ else if (depth === 0 && c === ">") return { end: i + 1, selfClosing: false };
770
+ i++;
771
+ }
772
+ return null;
773
+ }
774
+ function braced(src, i) {
775
+ let depth = 0;
776
+ for (let j = i; j < src.length; j++) {
777
+ const c = src[j];
778
+ if (c === '"' || c === "'" || c === "`") {
779
+ j = stringEnd(src, j) - 1;
780
+ continue;
781
+ }
782
+ if (c === "{") depth++;
783
+ else if (c === "}" && --depth === 0) return src.slice(i + 1, j);
784
+ }
785
+ return null;
786
+ }
787
+ function pathAttr(attrs) {
788
+ const m = attrs.match(/(?:^|\s)path\s*=\s*/);
789
+ if (!m) return null;
790
+ const rest = attrs.slice(m.index + m[0].length);
791
+ const lit = rest.match(/^"([^"]*)"|^'([^']*)'|^\{\s*"([^"]*)"\s*\}|^\{\s*'([^']*)'\s*\}|^\{\s*`([^`$]*)`\s*\}/);
792
+ if (!lit) return false;
793
+ return lit.slice(1).find((v) => v !== void 0) ?? "";
794
+ }
795
+ function componentAttr(attrs) {
796
+ const comp = attrs.match(/(?:^|\s)Component\s*=\s*\{\s*([A-Z][\w$]*)\s*\}/);
797
+ if (comp) return comp[1];
798
+ const m = attrs.match(/(?:^|\s)element\s*=\s*\{/);
799
+ if (!m) return null;
800
+ const inner = braced(attrs, m.index + m[0].length - 1);
801
+ if (inner === null) return null;
802
+ const el = inner.trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/);
803
+ return el ? el[1] : null;
804
+ }
805
+ function importedComponents(src) {
806
+ const out = /* @__PURE__ */ new Map();
807
+ for (const m of src.matchAll(/import\s+([A-Za-z_$][\w$]*)\s*(?:,\s*\{[^}]*\})?\s*from\s*["']([^"']+)["']/g)) out.set(m[1], { spec: m[2], kind: "default" });
808
+ for (const m of src.matchAll(/(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:React\.)?lazy\(\s*(?:async\s*)?\(\)\s*=>\s*import\(\s*["']([^"']+)["']\s*\)\s*\)/g))
809
+ out.set(m[1], { spec: m[2], kind: "lazy" });
810
+ return out;
811
+ }
812
+ function reactRouterPages(paths, text, only = paths) {
813
+ const have = new Set(paths);
814
+ const pages = [];
815
+ let notFound = null;
816
+ for (const file of only) {
817
+ if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP2.test(file)) continue;
818
+ const raw = text(file);
819
+ if (!raw || !raw.includes("<Route") || !/from\s*["']react-router(-dom)?["']/.test(raw)) continue;
820
+ const src = stripComments(raw);
821
+ const imports = importedComponents(src);
822
+ const events = [];
823
+ for (const m of src.matchAll(/<Route(?=[\s/>])/g)) events.push({ at: m.index });
824
+ for (const m of src.matchAll(/<\/Route\s*>/g)) events.push({ at: m.index, close: true });
825
+ events.sort((a, b) => a.at - b.at);
826
+ const stack = [];
827
+ for (const e of events) {
828
+ if (e.close) {
829
+ stack.pop();
830
+ continue;
831
+ }
832
+ const tag = tagEnd(src, e.at + "<Route".length);
833
+ if (!tag) break;
834
+ const attrs = src.slice(e.at + "<Route".length, tag.end - (tag.selfClosing ? 2 : 1));
835
+ const parent = stack.at(-1) ?? "";
836
+ const index = /(?:^|\s)index(?=\s|$|=\{\s*true\s*\})/.test(attrs);
837
+ const p = pathAttr(attrs);
838
+ const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
839
+ if (!tag.selfClosing) stack.push(typeof full === "string" ? full : parent);
840
+ if (full === null) continue;
841
+ const component = componentAttr(attrs);
842
+ const imported = component ? imports.get(component) : void 0;
843
+ const target = imported ? resolveImport(file, imported.spec, have) : null;
844
+ if (full === false) {
845
+ pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
846
+ continue;
847
+ }
848
+ if (full === "/*" || full.endsWith("/*") || full === "*") {
849
+ if (full === "/*" && target) notFound = target;
850
+ continue;
851
+ }
852
+ const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
853
+ if (target && imported && component) page.router = { file, start: e.at, end: tag.end, component, importKind: imported.kind };
854
+ if (!tag.selfClosing) page.reason = "nested";
855
+ else if (!target) page.reason = "unparsed";
856
+ pages.push(page);
857
+ }
858
+ }
859
+ return { pages, notFound };
860
+ }
861
+ function removeRoutes({ file, code, paths, text, drop }) {
862
+ const { pages } = reactRouterPages(paths, (p) => p === file ? code : text(p), [file]);
863
+ const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
864
+ spans.sort((a, b) => b.start - a.start);
865
+ let out = code;
866
+ for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
867
+ return { code: out, removed: spans.map((s) => s.path) };
868
+ }
869
+ function discover({ framework, paths, text }) {
870
+ const kept = paths.filter((p) => !SKIP2.test(p));
871
+ const found = framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : { pages: [], notFound: null };
872
+ const seen = /* @__PURE__ */ new Set();
873
+ 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);
874
+ return { pages, notFound: found.notFound };
875
+ }
876
+ var CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
877
+ var CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
878
+ var COLLECTIONS = "src/content/.schemas/collecties.json";
879
+ function contentNames(paths, text) {
880
+ const files = /* @__PURE__ */ new Map();
881
+ const add = (name, f) => {
882
+ if (!files.has(name)) files.set(name, /* @__PURE__ */ new Set());
883
+ files.get(name).add(f);
884
+ };
885
+ let collections = {};
886
+ try {
887
+ collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
888
+ } catch {
889
+ }
890
+ for (const f of paths) {
891
+ if (!CONTENT_JSON.test(f)) continue;
892
+ add(f.slice(f.lastIndexOf("/") + 1, -".json".length), f);
893
+ const named = collections[f];
894
+ add(typeof named === "string" ? named : f.slice("src/content/".length).split("/")[0].replace(/\.json$/, ""), f);
895
+ }
896
+ return files;
897
+ }
898
+ function collectionOfFile(f, collections) {
899
+ const named = collections[f];
900
+ return typeof named === "string" ? named : f.slice("src/content/".length).split("/")[0].replace(/\.json$/, "");
901
+ }
902
+ function ownCode(page, importers, imports) {
903
+ const own = /* @__PURE__ */ new Set([page.file]);
904
+ const queue = [page.file];
905
+ while (queue.length) {
906
+ for (const target of imports.get(queue.pop()) ?? []) {
907
+ if (own.has(target) || ![...importers.get(target)].every((f) => own.has(f) || f === page.router?.file)) continue;
908
+ own.add(target);
909
+ queue.push(target);
910
+ }
911
+ }
912
+ return own;
913
+ }
914
+ var ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
915
+ function contentReads(paths, text) {
916
+ const code = /* @__PURE__ */ new Map();
917
+ for (const p of paths) {
918
+ if (!CODE.test(p) || SKIP2.test(p)) continue;
919
+ const src = text(p);
920
+ if (src) code.set(p, stripComments(src));
921
+ }
922
+ const astro2 = ASTRO_READS.join("|");
923
+ const byName = new Set(ASTRO_READS);
924
+ const entryOf = /* @__PURE__ */ new Map();
925
+ const fixed = /* @__PURE__ */ new Map();
926
+ const bodies = /* @__PURE__ */ new Map();
927
+ const spans = /* @__PURE__ */ new Map();
928
+ const DIRECT = new RegExp(`\\b(?:${astro2})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
929
+ const addFixed = (name, whole, entry) => {
930
+ if (!fixed.has(name)) fixed.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
931
+ if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
932
+ else fixed.get(name).whole.add(whole);
933
+ };
934
+ for (const [p, src] of code) {
935
+ if (!/\.(ts|mts|js|mjs)$/.test(p)) continue;
936
+ for (const m of src.matchAll(/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::[^=]*)?=>/g)) {
937
+ const name = m[1] ?? m[3];
938
+ const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
939
+ let at2 = m.index + m[0].length;
940
+ while (/\s/.test(src[at2] ?? "")) at2++;
941
+ const block = src.indexOf("{", at2);
942
+ const braces = src[at2] === "{" ? at2 : m[1] && block > 0 ? block : -1;
943
+ const body = braces >= 0 ? braced(src, braces) ?? "" : src.slice(at2, src.slice(at2).search(/;|\n\s*\n|$/) + at2);
944
+ const start = braces >= 0 ? braces + 1 : at2;
945
+ if (!spans.has(p)) spans.set(p, []);
946
+ spans.get(p).push([start, start + body.length]);
947
+ if (first && new RegExp(`\\b(?:${astro2})\\(\\s*${escape(first)}\\b`).test(body)) {
948
+ byName.add(name);
949
+ const entry = new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1];
950
+ if (entry) entryOf.set(name, entry);
951
+ }
952
+ bodies.set(name, body);
953
+ for (const d of body.matchAll(DIRECT)) addFixed(name, d[1], d[2]);
954
+ }
955
+ }
956
+ for (const [name, body] of bodies) {
957
+ for (const fn of byName) {
958
+ if (fn === name || ASTRO_READS.includes(fn)) continue;
959
+ for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
960
+ }
961
+ }
962
+ const calls = new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))]));
963
+ for (let grew = true; grew; ) {
964
+ grew = false;
965
+ for (const [name, called] of calls) {
966
+ for (const other of called) {
967
+ const read = fixed.get(other);
968
+ if (other === name || !read) continue;
969
+ if (!fixed.has(name)) fixed.set(name, { whole: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() });
970
+ const mine = fixed.get(name);
971
+ const before = mine.whole.size + mine.entries.size;
972
+ read.whole.forEach((c) => mine.whole.add(c));
973
+ read.entries.forEach((e) => mine.entries.add(e));
974
+ if (mine.whole.size + mine.entries.size > before) grew = true;
975
+ }
976
+ }
977
+ }
978
+ const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
979
+ return { code, byName, byNameCall, entryOf, fixed, astro: astro2, spans };
980
+ }
981
+ var CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
982
+ var IDENTIFIER = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
983
+ var DEFINITION = /function\s+([A-Za-z_$][\w$]*)|const\s+([A-Za-z_$][\w$]*)\s*=/g;
984
+ function blankRanges(src, ranges) {
985
+ if (!ranges.length) return src;
986
+ let out = "";
987
+ let at2 = 0;
988
+ for (const [start, end] of [...ranges].sort((a, b) => a[0] - b[0])) {
989
+ if (end <= at2) continue;
990
+ const from = Math.max(start, at2);
991
+ out += src.slice(at2, from) + blank(src.slice(from, end));
992
+ at2 = end;
993
+ }
994
+ return out + src.slice(at2);
995
+ }
996
+ var IMPORT_STATEMENT = /\bimport\s+(?:type\s+)?[\s\S]*?\bfrom\s*["'][^"'\n]+["']/g;
997
+ var blank = (s) => s.replace(/[^\n]/g, " ");
998
+ function readsIn(src, reads, path = null) {
999
+ const code = blankRanges(src, reads.spans?.get(path) ?? []).replace(IMPORT_STATEMENT, blank);
1000
+ const names = /* @__PURE__ */ new Set();
1001
+ const entries = /* @__PURE__ */ new Set();
1002
+ const whole = /* @__PURE__ */ new Set();
1003
+ const helped = /* @__PURE__ */ new Set();
1004
+ for (const m of code.matchAll(reads.byNameCall)) {
1005
+ const [, fn, first, entry, other] = m;
1006
+ if (reads.entryOf?.has(fn)) entries.add(`${first}/${reads.entryOf.get(fn)}`);
1007
+ else if (entry) entries.add(`${first}/${entry}`);
1008
+ else if (other && ASTRO_READS.includes(fn)) whole.add(first);
1009
+ else if (fn === "getCollection") whole.add(first);
1010
+ else names.add(first);
1011
+ }
1012
+ const mentions = /* @__PURE__ */ new Map();
1013
+ for (const [name] of code.matchAll(IDENTIFIER)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
1014
+ const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
1015
+ for (const [name, n] of mentions) {
1016
+ const read = reads.fixed.get(name);
1017
+ if (!read || n - (defined.has(name) ? 1 : 0) <= 0) continue;
1018
+ read.whole.forEach((c) => whole.add(c));
1019
+ read.entries.forEach((e) => helped.add(e));
1020
+ }
1021
+ return { names, entries, whole, helped };
1022
+ }
1023
+ var siteReadsOf = /* @__PURE__ */ new WeakMap();
1024
+ function siteReads(paths, text, importers) {
1025
+ const kept = siteReadsOf.get(importers);
1026
+ if (kept) return kept;
1027
+ let collections = {};
1028
+ try {
1029
+ collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
1030
+ } catch {
1031
+ }
1032
+ const reads = contentReads(paths, text);
1033
+ const readsByFile = /* @__PURE__ */ new Map();
1034
+ for (const [p, src] of reads.code) if (!CONTENT_CONFIG.test(p)) readsByFile.set(p, readsIn(src, reads, p));
1035
+ const counts = { names: /* @__PURE__ */ new Map(), entries: /* @__PURE__ */ new Map(), whole: /* @__PURE__ */ new Map() };
1036
+ const count = (kind, keys) => keys.forEach((k) => counts[kind].set(k, (counts[kind].get(k) ?? 0) + 1));
1037
+ for (const r of readsByFile.values()) {
1038
+ count("names", r.names);
1039
+ count("entries", /* @__PURE__ */ new Set([...r.entries, ...r.helped]));
1040
+ count("whole", r.whole);
1041
+ }
1042
+ const names = contentNames(paths, text);
1043
+ const byEntry = /* @__PURE__ */ new Map();
1044
+ const byCollection = /* @__PURE__ */ new Map();
1045
+ const namesOf = /* @__PURE__ */ new Map();
1046
+ const routeOf = /* @__PURE__ */ new Map();
1047
+ const routes = /* @__PURE__ */ new Set();
1048
+ const push = (map, k, v) => map.has(k) ? map.get(k).push(v) : map.set(k, [v]);
1049
+ for (const f of paths) {
1050
+ if (!CONTENT_JSON.test(f)) continue;
1051
+ const c = collectionOfFile(f, collections);
1052
+ push(byEntry, `${c}/${f.slice(f.lastIndexOf("/") + 1, -5)}`, f);
1053
+ push(byCollection, c, f);
1054
+ try {
1055
+ const d = JSON.parse(text(f) ?? "null");
1056
+ if (!isObject(d)) continue;
1057
+ if (typeof (d.pad ?? d.path) === "string" && String(d.pad ?? d.path).startsWith("/")) routes.add(f);
1058
+ for (const a of /* @__PURE__ */ new Set([d.pad, d.path])) if (typeof a === "string") push(routeOf, a, f);
1059
+ } catch {
1060
+ }
1061
+ }
1062
+ for (const [n, fs] of names) for (const f of fs) push(namesOf, f, n);
1063
+ const jsonOf = /* @__PURE__ */ new Map();
1064
+ const imports = /* @__PURE__ */ new Map();
1065
+ for (const [target, by] of importers) {
1066
+ for (const f of by) {
1067
+ push(imports, f, target);
1068
+ if (target.endsWith(".json")) push(jsonOf, f, target);
1069
+ }
1070
+ }
1071
+ const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports };
1072
+ siteReadsOf.set(importers, site);
1073
+ return site;
1074
+ }
1075
+ function readsContent(page, { paths, text }) {
1076
+ const have = new Set(paths);
1077
+ const seen = /* @__PURE__ */ new Set();
1078
+ const visit = (file) => {
1079
+ if (seen.has(file)) return false;
1080
+ seen.add(file);
1081
+ const src = text(file) ?? "";
1082
+ if (/from\s*["']astro:content["']/.test(src)) return true;
1083
+ for (const m of src.matchAll(IMPORTS[0])) {
1084
+ const target = resolveImport(file, m[1], have);
1085
+ if (target && /\.(ts|mts|js|mjs)$/.test(target) && visit(target)) return true;
1086
+ }
1087
+ return false;
1088
+ };
1089
+ return visit(page.file);
1090
+ }
1091
+ function ownedContent(page, { paths, text, importers }) {
1092
+ const own = /* @__PURE__ */ new Set();
1093
+ const shared = /* @__PURE__ */ new Set();
1094
+ const unregistered = /* @__PURE__ */ new Set();
1095
+ if (!page.file) return { files: [], shared: [], unregistered: [], unknown: false };
1096
+ const site = siteReads(paths, text, importers);
1097
+ const { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute } = site;
1098
+ for (const target of site.jsonOf.get(page.file) ?? []) {
1099
+ const others = [...importers.get(target)].filter((f) => f !== page.file && f !== page.router?.file);
1100
+ (others.length ? shared : own).add(target);
1101
+ }
1102
+ const fileOf = (entry) => {
1103
+ const [collection, id] = entry.split("/");
1104
+ return byEntry.get(`${collection}/${id}`) ?? [];
1105
+ };
1106
+ const mine = ownCode(page, importers, site.imports);
1107
+ const named = /* @__PURE__ */ new Set();
1108
+ const entries = /* @__PURE__ */ new Set();
1109
+ const helped = /* @__PURE__ */ new Set();
1110
+ const wholeMine = /* @__PURE__ */ new Set();
1111
+ const minus = { names: /* @__PURE__ */ new Map(), entries: /* @__PURE__ */ new Map(), whole: /* @__PURE__ */ new Map() };
1112
+ const less = (kind, keys) => keys.forEach((k) => minus[kind].set(k, (minus[kind].get(k) ?? 0) + 1));
1113
+ for (const p of mine) {
1114
+ const r = readsByFile.get(p);
1115
+ if (!r) continue;
1116
+ r.names.forEach((n) => names.has(n) ? named.add(n) : unregistered.add(n));
1117
+ r.entries.forEach((e) => entries.add(e));
1118
+ r.helped.forEach((e) => helped.add(e));
1119
+ r.whole.forEach((c) => wholeMine.add(c));
1120
+ less("names", r.names);
1121
+ less("entries", /* @__PURE__ */ new Set([...r.entries, ...r.helped]));
1122
+ less("whole", r.whole);
1123
+ }
1124
+ const has = (kind) => ({ has: (k) => (counts[kind].get(k) ?? 0) - (minus[kind].get(k) ?? 0) > 0 });
1125
+ const elsewhere = { names: has("names"), entries: has("entries"), whole: has("whole") };
1126
+ const readElsewhere = (f) => elsewhere.whole.has(collectionOfFile(f, collections)) || (namesOf.get(f) ?? []).some((n) => elsewhere.names.has(n));
1127
+ for (const n of named) for (const f of names.get(n)) if (!isRoute(f)) (elsewhere.names.has(n) || readElsewhere(f) ? shared : own).add(f);
1128
+ for (const e of entries) for (const f of fileOf(e)) if (!isRoute(f)) (elsewhere.entries.has(e) || readElsewhere(f) ? shared : own).add(f);
1129
+ for (const e of helped) for (const f of fileOf(e)) if (!isRoute(f) && !elsewhere.entries.has(e) && !readElsewhere(f)) own.add(f);
1130
+ for (const c of wholeMine) if (!elsewhere.whole.has(c)) {
1131
+ for (const f of byCollection.get(c) ?? []) if (!isRoute(f) && !readElsewhere(f) && !elsewhere.entries.has(`${c}/${f.slice(f.lastIndexOf("/") + 1, -5)}`)) own.add(f);
1132
+ }
1133
+ const read = own.size > 0;
1134
+ for (const f of routeOf.get(page.path) ?? []) if (!shared.has(f)) own.add(f);
1135
+ for (const f of shared) own.delete(f);
1136
+ return {
1137
+ files: [...own].sort(),
1138
+ shared: [...shared].sort(),
1139
+ unregistered: [...unregistered].sort(),
1140
+ unknown: !read && !shared.size && !unregistered.size && readsContent(page, { paths, text })
1141
+ };
1142
+ }
1143
+ var MEDIA = ["satori", "@vercel/og", "astro-og-canvas", "og-img", "@resvg/resvg-js", "astro-opengraph-images"];
1144
+ function mediaGenerators(text) {
1145
+ let pkg = null;
1146
+ try {
1147
+ pkg = JSON.parse(text("package.json") ?? "null");
1148
+ } catch {
1149
+ }
1150
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
1151
+ return MEDIA.filter((m) => m in deps);
1152
+ }
1153
+ var LIST_TOOLS = { next: ["next-sitemap"] };
1154
+ function listTools(framework, text) {
1155
+ const tools = LIST_TOOLS[String(framework)] ?? [];
1156
+ if (!tools.length) return [];
1157
+ let pkg = null;
1158
+ try {
1159
+ pkg = JSON.parse(text("package.json") ?? "null");
1160
+ } catch {
1161
+ }
1162
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
1163
+ return tools.filter((t) => t in deps);
1164
+ }
1165
+ function draftCheck(path, { framework, paths, text, found, importers }) {
1166
+ const at2 = normalisePath(path);
1167
+ const no = (reason, detail) => ({ ok: (
1168
+ /** @type {const} */
1169
+ false
1170
+ ), path: at2, reason, ...detail ? { detail } : {} });
1171
+ if (!DRAFTABLE.includes(String(framework))) return no("framework");
1172
+ if (at2 === "/") return no("home");
1173
+ const media = mediaGenerators(text);
1174
+ if (media.length) return no("generated_media", media.join(", "));
1175
+ const lists = listTools(framework, text);
1176
+ if (lists.length) return no("page_list", lists.join(", "));
1177
+ const discovered = found ?? discover({ framework, paths, text });
1178
+ const page = discovered.pages.find((p) => p.path === at2);
1179
+ if (!page) {
1180
+ const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at2));
1181
+ return template ? no("template", template.path) : no("missing");
1182
+ }
1183
+ if (page.kind === "template") return no("template", page.path);
1184
+ if (page.reason) return no(page.reason);
1185
+ if (!page.file) return no("unparsed");
1186
+ if (framework === "next") {
1187
+ const beside = segmentFiles(page.file, paths);
1188
+ if (beside.length) return no("segment", beside.join(", "));
1189
+ }
1190
+ const graph = importers ?? importGraph(paths, text);
1191
+ const by = [...graph.get(page.file) ?? []].filter((f) => f !== page.router?.file);
1192
+ if (by.length) return no("shared", by.sort().join(", "));
1193
+ const twice = discovered.pages.find((p) => p !== page && p.file === page.file);
1194
+ if (twice) return no("shared", twice.path);
1195
+ const content = ownedContent(page, { paths, text, importers: graph });
1196
+ if (content.shared.length) return no("shared", content.shared.join(", "));
1197
+ if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
1198
+ if (content.unknown) return no("content_unknown");
1199
+ return { ok: true, path: at2, page, content: content.files };
1200
+ }
1201
+ var SEGMENT_FILE = /^(layout|template|loading|error|global-error|not-found|forbidden|unauthorized|default|route|sitemap|manifest|robots|(?:opengraph-image|twitter-image|icon|apple-icon)\d*)(\.alt)?\.[a-z]+$/;
1202
+ function segmentFiles(file, paths) {
1203
+ if (!/(^|\/)page\.[a-z]+$/.test(file)) return [];
1204
+ const dir = dirname(file);
1205
+ return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
1206
+ }
1207
+ function templateMatches(template, path) {
1208
+ const t = template.split("/");
1209
+ const p = path.split("/");
1210
+ 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));
1211
+ return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
1212
+ }
1213
+ function draftPlan({ framework, paths, text, pageFile }) {
1214
+ if (!pageFile.ok) return { checks: [], failed: [{ ok: (
1215
+ /** @type {const} */
1216
+ false
1217
+ ), path: PAGE_FILE, reason: "invalid", detail: pageFile.error }] };
1218
+ const found = discover({ framework, paths, text });
1219
+ const importers = importGraph(paths, text);
1220
+ const checks = draftPaths(pageFile).map((p) => draftCheck(p, { framework, paths, text, found, importers }));
1221
+ return { checks, failed: checks.filter((c) => !c.ok), found, importers };
1222
+ }
1223
+ var APP_SOURCE = /^(src|app|pages|components|lib)\//;
1224
+ function linksTo(path, { paths, text, own = [] }) {
1225
+ if (path === "/") return [];
1226
+ const mine = new Set(own);
1227
+ return [...linkIndex(paths, text).get(path) ?? []].filter((p) => !mine.has(p)).sort();
1228
+ }
1229
+ var linkIndexOf = /* @__PURE__ */ new WeakMap();
1230
+ var QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
1231
+ function linkIndex(paths, text) {
1232
+ const kept = linkIndexOf.get(text);
1233
+ if (kept?.paths === paths) return kept.index;
1234
+ const index = /* @__PURE__ */ new Map();
1235
+ for (const p of paths) {
1236
+ if (SKIP2.test(p) || !APP_SOURCE.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
1237
+ for (const [, , quoted] of (text(p) ?? "").matchAll(QUOTED_ADDRESS)) {
1238
+ const bare = quoted.replace(/[#?][\s\S]*$/, "");
1239
+ const address2 = bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare;
1240
+ if (!index.has(address2)) index.set(address2, /* @__PURE__ */ new Set());
1241
+ index.get(address2).add(p);
1242
+ }
1243
+ }
1244
+ linkIndexOf.set(text, { paths, index });
1245
+ return index;
1246
+ }
1247
+ var CONFIGS = {
1248
+ astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
1249
+ "vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
1250
+ next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"]
1251
+ };
1252
+ var kitFiles = (framework) => ["package.json", ...CONFIGS[String(framework)] ?? []];
1253
+ function kitInstalled({ framework, text }) {
1254
+ let pkg = null;
1255
+ try {
1256
+ pkg = JSON.parse(text("package.json") ?? "null");
1257
+ } catch {
1258
+ }
1259
+ if (!pkg) return false;
1260
+ const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
1261
+ return (KITS[String(framework)] ?? []).some((name) => !!(pkg.dependencies?.[name] || pkg.devDependencies?.[name]) && configs.some((c) => c.includes(name)));
1262
+ }
1263
+ var normal = (s) => s.replace(/\s+/g, " ");
1264
+ function sentences(src) {
1265
+ const out = [];
1266
+ for (const m of normal(src).matchAll(/[\p{L}\p{N}][\p{L}\p{N} ,.!?;'’-]*/gu)) {
1267
+ const run = m[0].trim();
1268
+ const words = run.split(" ");
1269
+ if (run.length < 24 || words.length < 4) continue;
1270
+ const plain2 = words.filter((w) => new RegExp("^(\\p{Lu}?\\p{Ll}+|\\p{Lu}+)[,.!?;]?$", "u").test(w)).length;
1271
+ if (plain2 / words.length < 0.75) continue;
1272
+ const piece = run.split(/['’]|[^\x20-\x7e]/).map((s) => s.trim()).sort((a, b) => b.length - a.length)[0];
1273
+ if (piece && piece.length >= 20 && piece.split(" ").length >= 3) out.push(piece);
1274
+ }
1275
+ return out;
1276
+ }
1277
+ function jsonStrings(text) {
1278
+ const out = [];
1279
+ const walk = (v) => {
1280
+ if (typeof v === "string") out.push(v);
1281
+ else if (Array.isArray(v)) v.forEach(walk);
1282
+ else if (isObject(v)) Object.values(v).forEach(walk);
1283
+ };
1284
+ try {
1285
+ walk(JSON.parse(text));
1286
+ } catch {
1287
+ }
1288
+ return out;
1289
+ }
1290
+ function leakPrints(check, { paths, text, max = 24 }) {
1291
+ if (!check.ok) return [];
1292
+ const mine = /* @__PURE__ */ new Set([check.page.file, ...check.content]);
1293
+ const candidates = /* @__PURE__ */ new Set();
1294
+ const own = stripComments(text(check.page.file) ?? "").replace(/<!--[\s\S]*?-->/g, " ");
1295
+ for (const s of sentences(own)) candidates.add(s);
1296
+ for (const f of check.content) for (const v of jsonStrings(text(f) ?? "")) for (const s of sentences(v)) candidates.add(s);
1297
+ if (!candidates.size) return [];
1298
+ const others = paths.filter((p) => !mine.has(p) && !SKIP2.test(p) && (CODE.test(p) || p.endsWith(".json"))).map((p) => normal(text(p) ?? "")).join("\n");
1299
+ return [...candidates].filter((s) => !others.includes(s)).sort((a, b) => b.length - a.length || (a < b ? -1 : 1)).slice(0, max);
1300
+ }
1301
+ var leaksIn = (output, prints) => {
1302
+ const text = normal(output);
1303
+ return prints.filter((p) => text.includes(p));
1304
+ };
1305
+ function withoutInSitemap(xml, drafts) {
1306
+ return xml.replace(/<url>[\s\S]*?<\/url>/g, (block) => {
1307
+ const loc = block.match(/<loc>\s*([^<\s]+)\s*<\/loc>/)?.[1];
1308
+ if (!loc) return block;
1309
+ let path;
1310
+ try {
1311
+ path = normalisePath(new URL(loc, "https://x.invalid").pathname);
1312
+ } catch {
1313
+ return block;
1314
+ }
1315
+ return drafts.includes(path) ? "" : block;
1316
+ });
1317
+ }
1318
+ function withoutInPageList(json, drafts) {
1319
+ const list = JSON.parse(json);
1320
+ return Array.isArray(list) ? JSON.stringify(list.filter((p) => !drafts.includes(normalisePath(p?.path ?? "")))) : json;
1321
+ }
1322
+ function withoutInContentMap(json, files) {
1323
+ const map = JSON.parse(json);
1324
+ if (!isObject(map)) return json;
1325
+ const gone = new Set(files);
1326
+ for (const [key, value] of Object.entries(map)) {
1327
+ if (isObject(value)) {
1328
+ for (const f of Object.keys(value)) if (gone.has(f)) delete value[f];
1329
+ }
1330
+ if (Array.isArray(value)) map[key] = value.filter((v) => !(typeof v === "string" && gone.has(v)));
1331
+ }
1332
+ return JSON.stringify(map);
1333
+ }
1334
+
1335
+ // supabase/functions/_shared/next-metadata.ts
1336
+ var ID = /[A-Za-z0-9_$]/;
1337
+ function skip(src, i) {
1338
+ for (; ; ) {
1339
+ while (i < src.length && /\s/.test(src[i])) i++;
1340
+ if (src.startsWith("//", i)) {
1341
+ const e = src.indexOf("\n", i);
1342
+ i = e < 0 ? src.length : e + 1;
1343
+ } else if (src.startsWith("/*", i)) {
1344
+ const e = src.indexOf("*/", i + 2);
1345
+ i = e < 0 ? src.length : e + 2;
1346
+ } else return i;
1347
+ }
1348
+ }
1349
+ function stringEnd2(src, i) {
1350
+ const q = src[i];
1351
+ for (let j = i + 1; j < src.length; j++) {
1352
+ const c = src[j];
1353
+ if (c === "\\") j++;
1354
+ else if (c === q) return j + 1;
1355
+ else if (c === "\n" && q !== "`") return -1;
1356
+ else if (q === "`" && c === "$" && src[j + 1] === "{") {
1357
+ let depth = 0;
1358
+ for (j += 1; j < src.length; j++) {
1359
+ if (src[j] === "{") depth++;
1360
+ else if (src[j] === "}" && --depth === 0) break;
1361
+ else if (src[j] === '"' || src[j] === "'" || src[j] === "`") {
1362
+ const e = stringEnd2(src, j);
1363
+ if (e < 0) return -1;
1364
+ j = e - 1;
1365
+ }
1366
+ }
1367
+ }
1368
+ }
1369
+ return -1;
1370
+ }
1371
+ var ESC = { n: "\n", t: " ", r: "\r", b: "\b", f: "\f", v: "\v", 0: "\0" };
1372
+ function unescape(s) {
1373
+ let out = "";
1374
+ for (let i = 0; i < s.length; i++) {
1375
+ const c = s[i];
1376
+ if (c !== "\\") {
1377
+ out += c;
1378
+ continue;
1379
+ }
1380
+ const d = s[++i];
1381
+ if (d === void 0) return null;
1382
+ if (d in ESC) out += ESC[d];
1383
+ else if (d === "u") {
1384
+ const m = /^\{([0-9a-f]+)\}|^([0-9a-f]{4})/i.exec(s.slice(i + 1));
1385
+ if (!m) return null;
1386
+ out += String.fromCodePoint(parseInt(m[1] ?? m[2], 16));
1387
+ i += m[0].length;
1388
+ } else if (d === "x") {
1389
+ const m = /^[0-9a-f]{2}/i.exec(s.slice(i + 1));
1390
+ if (!m) return null;
1391
+ out += String.fromCharCode(parseInt(m[0], 16));
1392
+ i += 2;
1393
+ } else if (d === "\n") {
1394
+ } else out += d;
1395
+ }
1396
+ return out;
1397
+ }
1398
+ function expressionEnd(src, i) {
1399
+ let depth = 0;
1400
+ for (let j = i; j < src.length; j++) {
1401
+ const c = src[j];
1402
+ if (c === '"' || c === "'" || c === "`") {
1403
+ const e = stringEnd2(src, j);
1404
+ if (e < 0) return src.length;
1405
+ j = e - 1;
1406
+ } else if (src.startsWith("//", j) || src.startsWith("/*", j)) j = skip(src, j) - 1;
1407
+ else if (c === "{" || c === "[" || c === "(") depth++;
1408
+ else if (c === "}" || c === "]" || c === ")") {
1409
+ if (depth === 0) return j;
1410
+ depth--;
1411
+ } else if ((c === "," || c === ";") && depth === 0) return j;
1412
+ }
1413
+ return src.length;
1414
+ }
1415
+ function parseValue(src, i) {
1416
+ const start = skip(src, i);
1417
+ const c = src[start];
1418
+ let node;
1419
+ if (c === "{") node = parseObject(src, start);
1420
+ else if (c === "[") node = parseArray(src, start);
1421
+ else if (c === '"' || c === "'" || c === "`") {
1422
+ const end = stringEnd2(src, start);
1423
+ const raw = end < 0 ? null : src.slice(start + 1, end - 1);
1424
+ const value = raw === null || c === "`" && raw.includes("${") ? null : unescape(raw);
1425
+ node = value === null ? { type: "other", start, end: end < 0 ? src.length : end } : { type: "string", value, quote: c, inner: { start: start + 1, end: end - 1 }, start, end };
1426
+ } else {
1427
+ const word = /^(true|false)(?![A-Za-z0-9_$])/.exec(src.slice(start, start + 6));
1428
+ node = word ? { type: "boolean", value: word[1] === "true", start, end: start + word[1].length } : { type: "other", start, end: start };
1429
+ }
1430
+ const after = skip(src, node.end);
1431
+ const next = src[after];
1432
+ if (node.type === "other" || next !== "," && next !== "}" && next !== "]" && next !== ")" && next !== ";" && next !== void 0 && !/^(satisfies|as)\b/.test(src.slice(after))) {
1433
+ return { type: "other", start, end: expressionEnd(src, start) };
1434
+ }
1435
+ return node;
1436
+ }
1437
+ function parseObject(src, open) {
1438
+ const props = [];
1439
+ let spread2 = false;
1440
+ let i = open + 1;
1441
+ for (; ; ) {
1442
+ i = skip(src, i);
1443
+ if (i >= src.length) return { type: "other", start: open, end: src.length };
1444
+ if (src[i] === "}") return { type: "object", props, spread: spread2, start: open, end: i + 1 };
1445
+ const start = i;
1446
+ if (src.startsWith("...", i)) {
1447
+ spread2 = true;
1448
+ i = expressionEnd(src, i);
1449
+ props.push({ key: null, start, end: i, value: null });
1450
+ } else {
1451
+ let key = null;
1452
+ if (src[i] === '"' || src[i] === "'") {
1453
+ const e = stringEnd2(src, i);
1454
+ if (e < 0) return { type: "other", start: open, end: expressionEnd(src, open) };
1455
+ key = unescape(src.slice(i + 1, e - 1));
1456
+ i = e;
1457
+ } else if (ID.test(src[i])) {
1458
+ const m = /^[A-Za-z0-9_$]+/.exec(src.slice(i));
1459
+ key = m[0];
1460
+ i += m[0].length;
1461
+ } else {
1462
+ i = expressionEnd(src, i);
1463
+ props.push({ key: null, start, end: i, value: null });
1464
+ if (src[i] === ",") i++;
1465
+ continue;
1466
+ }
1467
+ i = skip(src, i);
1468
+ if (src[i] === ":") {
1469
+ const value = parseValue(src, i + 1);
1470
+ props.push({ key, start, end: value.end, value });
1471
+ i = value.end;
1472
+ } else {
1473
+ i = expressionEnd(src, start);
1474
+ props.push({ key, start, end: i, value: { type: "other", start, end: i } });
1475
+ }
1476
+ }
1477
+ i = skip(src, i);
1478
+ if (src[i] === ",") i++;
1479
+ else if (src[i] !== "}") return { type: "other", start: open, end: expressionEnd(src, open) };
1480
+ }
1481
+ }
1482
+ function parseArray(src, open) {
1483
+ const items = [];
1484
+ let i = open + 1;
1485
+ for (; ; ) {
1486
+ i = skip(src, i);
1487
+ if (i >= src.length) return { type: "other", start: open, end: src.length };
1488
+ if (src[i] === "]") return { type: "array", items, start: open, end: i + 1 };
1489
+ const value = src.startsWith("...", i) ? { type: "other", start: i, end: expressionEnd(src, i) } : parseValue(src, i);
1490
+ items.push(value);
1491
+ i = skip(src, value.end);
1492
+ if (src[i] === ",") i++;
1493
+ else if (src[i] !== "]") return { type: "other", start: open, end: expressionEnd(src, open) };
1494
+ }
1495
+ }
1496
+ function codeOnly(src) {
1497
+ let out = "";
1498
+ for (let i = 0; i < src.length; ) {
1499
+ const c = src[i];
1500
+ if (src.startsWith("//", i) || src.startsWith("/*", i)) {
1501
+ const e = skip(src, i);
1502
+ out += src.slice(i, e).replace(/[^\n]/g, " ");
1503
+ i = e;
1504
+ } else if (c === '"' || c === "'" || c === "`") {
1505
+ const e = stringEnd2(src, i);
1506
+ const end = e < 0 ? i + 1 : e;
1507
+ out += c + src.slice(i + 1, end - 1).replace(/[^\n]/g, " ") + (end - 1 > i ? src[end - 1] : "");
1508
+ i = end;
1509
+ } else {
1510
+ out += c;
1511
+ i++;
1512
+ }
1513
+ }
1514
+ return out;
1515
+ }
1516
+ var CMS2 = /sanity|contentful|storyblok|prismic|datocms|payload|strapi|directus|builder\.io|keystatic|tina|hygraph|graphcms|wordpress|ghost|cms/i;
1517
+ var isCmsModule = (spec) => CMS2.test(spec);
1518
+ var importsOf = (src) => [...src.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']/gm), ...src.matchAll(/^\s*import\s*["']([^"']+)["']/gm)].map((m) => m[1]);
1519
+ function afterImports(src, code) {
1520
+ let at2 = 0;
1521
+ const directive = /^\s*(["'])use [a-z]+\1;?[^\S\n]*\n?/.exec(src);
1522
+ if (directive) at2 = directive[0].length;
1523
+ for (const m of code.matchAll(/^import\b/gm)) {
1524
+ const end = expressionEnd(src, m.index);
1525
+ const semi = src[end] === ";" ? end + 1 : end;
1526
+ at2 = Math.max(at2, semi);
1527
+ }
1528
+ return at2;
1529
+ }
1530
+ function readMetadata(src) {
1531
+ const code = codeOnly(src);
1532
+ if (/^\s*(["'])use client\1/.test(src)) return { kind: "refused", reason: "unsupported" };
1533
+ if (/\bexport\s+(async\s+)?function\s+generateMetadata\b|\bexport\s+(const|let|var)\s+generateMetadata\b/.test(code)) {
1534
+ return { kind: "refused", reason: importsOf(src).some(isCmsModule) ? "cms" : "computed" };
1535
+ }
1536
+ const m = /\bexport\s+(?:const|let|var)\s+metadata\b\s*(?::\s*[^=;]+?)?\s*=/.exec(code);
1537
+ if (m) {
1538
+ const value = parseValue(src, m.index + m[0].length);
1539
+ return value.type === "object" ? { kind: "literal", object: value, at: m.index } : { kind: "refused", reason: "computed" };
1540
+ }
1541
+ if (/\bexport\s*\{[^}]*\bmetadata\b[^}]*\}|\bexport\s+\*\s+from\b/.test(code)) return { kind: "refused", reason: "computed" };
1542
+ return { kind: "none", insertAt: afterImports(src, code) };
1543
+ }
1544
+ var NOINDEX = "/metadata/robots/noindex";
1545
+ var LANG = "/html/lang";
1546
+ var prop = (o, key) => o?.type === "object" ? [...o.props].reverse().find((p) => p.key === key) : void 0;
1547
+ function at(object, path) {
1548
+ let node = object;
1549
+ for (const step of path) {
1550
+ if (!node) return void 0;
1551
+ if (node.type === "object") node = prop(node, step)?.value;
1552
+ else if (node.type === "array" && /^\d+$/.test(step)) node = node.items[Number(step)];
1553
+ else return node.type === "other" ? null : void 0;
1554
+ }
1555
+ return node;
1556
+ }
1557
+ function textField(object, paths, create) {
1558
+ for (const p of paths) {
1559
+ const node2 = object ? at(object, p.split("/")) : void 0;
1560
+ if (node2 === void 0) continue;
1561
+ if (node2?.type === "string") return { pointer: `/metadata/${p}`, kind: "text", exists: true, value: node2.value };
1562
+ return null;
1563
+ }
1564
+ if (!create) return null;
1565
+ const steps = create.split("/");
1566
+ let node = object;
1567
+ for (const s of steps.slice(0, -1)) {
1568
+ if (!node) break;
1569
+ if (node.type !== "object") return null;
1570
+ node = prop(node, s)?.value;
1571
+ }
1572
+ if (node && node.type !== "object") return null;
1573
+ return { pointer: `/metadata/${create}`, kind: "text", exists: false, value: null };
1574
+ }
1575
+ function imageField(object) {
1576
+ const og = object ? prop(object, "openGraph")?.value : void 0;
1577
+ if (og !== void 0 && og?.type !== "object") return null;
1578
+ const images = og ? prop(og, "images")?.value : void 0;
1579
+ if (images === void 0) return { pointer: "/metadata/openGraph/images", kind: "image", exists: false, value: null };
1580
+ const one = images?.type === "array" ? images.items.length === 1 ? images.items[0] : null : images;
1581
+ const path = images?.type === "array" ? "openGraph/images/0" : "openGraph/images";
1582
+ if (one?.type === "string") return { pointer: `/metadata/${path}`, kind: "image", exists: true, value: one.value };
1583
+ const url = one?.type === "object" ? prop(one, "url")?.value : null;
1584
+ if (url?.type === "string") return { pointer: `/metadata/${path}/url`, kind: "image", exists: true, value: url.value };
1585
+ return null;
1586
+ }
1587
+ function noindexField(object) {
1588
+ const robots = object ? prop(object, "robots")?.value : void 0;
1589
+ if (robots === void 0) return { pointer: NOINDEX, kind: "boolean", exists: false, value: null };
1590
+ if (robots?.type !== "object") return null;
1591
+ const index = prop(robots, "index")?.value;
1592
+ if (index === void 0) return robots.spread ? null : { pointer: NOINDEX, kind: "boolean", exists: false, value: null };
1593
+ return index?.type === "boolean" ? { pointer: NOINDEX, kind: "boolean", exists: true, value: String(!index.value) } : null;
1594
+ }
1595
+ function langOf(src) {
1596
+ const code = codeOnly(src);
1597
+ const tag = /<html\b/.exec(code);
1598
+ if (!tag) return null;
1599
+ const close = code.indexOf(">", tag.index);
1600
+ const attrs = code.slice(tag.index, close < 0 ? code.length : close);
1601
+ const m = /\slang\s*=\s*(["'])/.exec(attrs);
1602
+ if (!m) return null;
1603
+ const open = tag.index + m.index + m[0].length;
1604
+ const end = src.indexOf(m[1], open);
1605
+ if (end < 0 || /[{}\n]/.test(src.slice(open, end))) return null;
1606
+ return { field: { pointer: LANG, kind: "text", exists: true, value: src.slice(open, end) }, inner: { start: open, end } };
1607
+ }
1608
+ function pageMetaFields(src) {
1609
+ const read = readMetadata(src);
1610
+ if (read.kind === "refused") return { fields: {}, refused: read.reason, computed: {} };
1611
+ const object = read.kind === "literal" ? read.object : null;
1612
+ const wanted = {
1613
+ title: textField(object, ["title/absolute", "title"], "title"),
1614
+ description: textField(object, ["description"], "description"),
1615
+ socialImage: imageField(object),
1616
+ noindex: noindexField(object)
1617
+ };
1618
+ const fields = {};
1619
+ const computed = {};
1620
+ for (const [k, f] of Object.entries(wanted)) {
1621
+ if (f) fields[k] = f;
1622
+ else computed[k] = "computed";
1623
+ }
1624
+ return { fields, refused: null, computed };
1625
+ }
1626
+ function siteMetaFields(src) {
1627
+ const read = readMetadata(src);
1628
+ const lang = langOf(src);
1629
+ if (read.kind === "refused") return { fields: lang ? { language: lang.field } : {}, refused: read.reason, computed: {} };
1630
+ const object = read.kind === "literal" ? read.object : null;
1631
+ const wanted = {
1632
+ // The name only where the code has it: a new one would change no title.
1633
+ name: textField(object, ["applicationName", "openGraph/siteName"], null),
1634
+ description: textField(object, ["description"], "description"),
1635
+ socialImage: imageField(object),
1636
+ language: lang?.field ?? null
1637
+ };
1638
+ const fields = {};
1639
+ const computed = {};
1640
+ const named = !!object && ["applicationName", "openGraph/siteName"].some((p) => at(object, p.split("/")) !== void 0);
1641
+ for (const [k, f] of Object.entries(wanted)) {
1642
+ if (f) fields[k] = f;
1643
+ else if (k !== "name" || named) computed[k] = "computed";
1644
+ }
1645
+ return { fields, refused: null, computed };
1646
+ }
1647
+
1648
+ // supabase/functions/unbase-projects/settings.ts
1649
+ var PAGE_FIELDS = {
1650
+ title: { name: "titel", kind: "text" },
1651
+ description: { name: "beschrijving", kind: "text" },
1652
+ socialImage: { name: "ogImage", kind: "image" },
1653
+ noindex: { name: "noindex", kind: "boolean" },
1654
+ siteSearch: { name: "zoeken", kind: "boolean" }
1655
+ };
1656
+ var SITE_FIELDS = {
1657
+ name: { name: "naam", kind: "text" },
1658
+ description: { name: "beschrijving", kind: "text" },
1659
+ language: { name: "taal", kind: "text" },
1660
+ faviconLight: { name: "favicon", kind: "image" },
1661
+ faviconDark: { name: "faviconDonker", kind: "image" },
1662
+ socialImage: { name: "ogImage", kind: "image" },
1663
+ analyticsId: { name: "googleAnalytics", kind: "text" }
1664
+ };
1665
+ var CONTENT = "src/content";
1666
+ var SCHEMAS = `${CONTENT}/.schemas`;
1667
+ var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
1668
+ var AT_ONCE2 = 8;
1669
+ var MAX_ROUTE_FILES = 300;
1670
+ async function inTurns(items, work) {
1671
+ const out = new Array(items.length);
1672
+ let next = 0;
1673
+ await Promise.all(
1674
+ Array.from({ length: Math.min(AT_ONCE2, items.length) }, async () => {
1675
+ while (next < items.length) {
1676
+ const i = next++;
1677
+ out[i] = await work(items[i]);
1678
+ }
1679
+ })
1680
+ );
1681
+ return out;
1682
+ }
1683
+ var parse = (text) => {
1684
+ if (text === null) return null;
1685
+ try {
1686
+ return JSON.parse(text);
1687
+ } catch {
1688
+ return null;
1689
+ }
1690
+ };
1691
+ function valueOf(v, kind) {
1692
+ if (kind === "boolean") return typeof v === "boolean" ? String(v) : null;
1693
+ return typeof v === "string" ? v : null;
1694
+ }
1695
+ function fieldsOf(names, data, allowed, file, base) {
1696
+ const fields = {};
1697
+ for (const [field, { name, kind }] of Object.entries(names)) {
1698
+ const value = valueOf(data?.[name], kind);
1699
+ const there = data?.[name] !== void 0;
1700
+ if (there && value === null) continue;
1701
+ if (!there && !allowed[name]) continue;
1702
+ fields[field] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
1703
+ }
1704
+ return fields;
1705
+ }
1706
+ var VITE_DOCUMENT = "index.html";
1707
+ var HEAD_SETTINGS = [
1708
+ ["name", "title", "text"],
1709
+ ["description", "description", "text"],
1710
+ ["language", "language", "text"],
1711
+ ["faviconLight", "favicon", "image"],
1712
+ ["faviconDark", "faviconDark", "image"],
1713
+ ["socialImage", "image", "image"]
1714
+ ];
1715
+ async function viteSettings(repo, appPath) {
1716
+ const text = await repo.read(join(appPath, VITE_DOCUMENT));
1717
+ if (text === null) return null;
1718
+ const head = readHead(text);
1719
+ const site = {};
1720
+ for (const [field, at2, kind] of HEAD_SETTINGS) {
1721
+ const found = head[at2];
1722
+ if (found) site[field] = { file: VITE_DOCUMENT, pointer: headPointer(at2), kind, exists: true, value: found.value };
1723
+ }
1724
+ return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
1725
+ }
1726
+ async function readSettings(repo, appPath, framework = null) {
1727
+ if (framework === "vite-react") return viteSettings(repo, appPath);
1728
+ if (framework === "next") return nextSettings(repo, appPath);
1729
+ const at2 = (p) => join(appPath, p);
1730
+ const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at2(SCHEMAS)}/`) && p.endsWith(".schema.json"));
1731
+ if (!schemaPaths.length) return null;
1732
+ const named = (p) => p.slice(at2(SCHEMAS).length + 1, -".schema.json".length);
1733
+ const schemas = /* @__PURE__ */ new Map();
1734
+ const [map, ...read] = await inTurns([at2(`${SCHEMAS}/collecties.json`), ...schemaPaths], (p) => repo.read(p));
1735
+ schemaPaths.forEach((p, i) => {
1736
+ const s = parse(read[i] ?? null);
1737
+ if (s && typeof s === "object") schemas.set(named(p), s);
1738
+ });
1739
+ const elsewhere = parse(map ?? null) ?? {};
1740
+ const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at2(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at2(SCHEMAS)}/`));
1741
+ const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at2(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
1742
+ const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
1743
+ const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
1744
+ const pages = {};
1745
+ let routes = null;
1746
+ if (routeCollection) {
1747
+ const [collection, schema] = routeCollection;
1748
+ const allowed = schema.properties.seo?.properties ?? {};
1749
+ const files = filesOf(collection).slice(0, MAX_ROUTE_FILES);
1750
+ const datas = await inTurns(files, async (p) => parse(await repo.read(p)));
1751
+ files.forEach((file, i) => {
1752
+ const data = datas[i];
1753
+ if (!data || typeof data.pad !== "string" || !ROUTE.test(data.pad)) return;
1754
+ const seo = data.seo && typeof data.seo === "object" && !Array.isArray(data.seo) ? data.seo : {};
1755
+ pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
1756
+ });
1757
+ 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(([field, { name, kind }]) => ({ field, pointer: `/seo/${name}`, kind }));
1759
+ routes = { dir, fields };
1760
+ }
1761
+ const siteCollection = [...schemas].find(([, s]) => s["x-instellingen"] === "site");
1762
+ let site = null;
1763
+ const siteFile = siteCollection && filesOf(siteCollection[0])[0];
1764
+ if (siteCollection && siteFile) {
1765
+ const data = parse(await repo.read(siteFile));
1766
+ if (data && typeof data === "object" && !Array.isArray(data)) {
1767
+ site = fieldsOf(SITE_FIELDS, data, siteCollection[1].properties ?? {}, siteFile.slice(appPath ? appPath.length + 1 : 0), "");
1768
+ }
1769
+ }
1770
+ if (!Object.keys(pages).length && !routes && !site) return null;
1771
+ return { pages, routes, site };
1772
+ }
1773
+ var NEXT_PAGE = /^(src\/)?app\/(.*\/)?page\.(tsx|ts|jsx|js)$/;
1774
+ var NEXT_ROOT_LAYOUT = /^(src\/)?app\/layout\.(tsx|ts|jsx|js)$/;
1775
+ var CMS_DEPTH = 2;
1776
+ var NEXT_PAGE_FIELDS = { title: "title", description: "description", socialImage: "socialImage", noindex: "noindex" };
1777
+ var NEXT_SITE_FIELDS = { name: "name", description: "description", socialImage: "socialImage", language: "language" };
1778
+ var settingOf = (file, f) => ({ file, pointer: f.pointer, kind: f.kind, exists: f.exists, value: f.value });
1779
+ var drawnImage = (file, have) => {
1780
+ const dir = file.replace(/[^/]*$/, "");
1781
+ return [...have].some((p) => p.startsWith(dir) && /^opengraph-image\d*\.[a-z]+$/.test(p.slice(dir.length)));
1782
+ };
1783
+ var resolveIn = (from, spec, have) => resolveImport(from, spec, have) ?? (spec.startsWith("@/") ? resolveImport("", `./${spec.slice(2)}`, have) : null);
1784
+ async function nextSettings(repo, appPath) {
1785
+ const root = appPath ? `${appPath}/` : "";
1786
+ const paths = repo.paths.filter((p) => p.startsWith(root)).map((p) => p.slice(root.length));
1787
+ const have = new Set(paths);
1788
+ const texts = /* @__PURE__ */ new Map();
1789
+ const read = (p) => {
1790
+ if (!texts.has(p)) texts.set(p, repo.read(join(appPath, p)));
1791
+ return texts.get(p);
1792
+ };
1793
+ const { pages: found } = discover({ framework: "next", paths, text: () => null });
1794
+ const pages = found.filter((p) => p.kind === "file" && p.file).slice(0, MAX_ROUTE_FILES);
1795
+ const layout = paths.find((p) => NEXT_ROOT_LAYOUT.test(p)) ?? null;
1796
+ if (!pages.some((p) => NEXT_PAGE.test(p.file)) && !layout) return null;
1797
+ const readsCms = async (file, depth = CMS_DEPTH, seen = /* @__PURE__ */ new Set()) => {
1798
+ if (seen.has(file)) return false;
1799
+ seen.add(file);
1800
+ const src = await read(file);
1801
+ if (!src) return false;
1802
+ const specs = importsOf(src);
1803
+ if (specs.some(isCmsModule)) return true;
1804
+ if (!depth) return false;
1805
+ for (const s of specs) {
1806
+ const target = resolveIn(file, s, have);
1807
+ if (target && await readsCms(target, depth - 1, seen)) return true;
1808
+ }
1809
+ return false;
1810
+ };
1811
+ const reasonOf = async (file, reason) => reason === "computed" && /\bgenerateMetadata\b/.test(await read(file) ?? "") && await readsCms(file) ? "cms" : reason;
1812
+ const out = {};
1813
+ const refused = {};
1814
+ const answers = await inTurns(pages, async (p) => {
1815
+ const file = p.file;
1816
+ if (!NEXT_PAGE.test(file)) return { p, file, read: null };
1817
+ const src = await read(file);
1818
+ return { p, file, read: src === null ? null : pageMetaFields(src) };
1819
+ });
1820
+ for (const { p, file, read: r } of answers) {
1821
+ if (!r) {
1822
+ refused[p.path] = { file, reason: "unsupported" };
1823
+ continue;
1824
+ }
1825
+ if (r.refused) {
1826
+ refused[p.path] = { file, reason: await reasonOf(file, r.refused) };
1827
+ continue;
1828
+ }
1829
+ if (r.fields.socialImage && drawnImage(file, have)) {
1830
+ delete r.fields.socialImage;
1831
+ r.computed.socialImage = "computed";
1832
+ }
1833
+ const fields = {};
1834
+ for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_PAGE_FIELDS[k]] = settingOf(file, f);
1835
+ out[p.path] = fields;
1836
+ const computed = Object.entries(r.computed).map(([k, why]) => [NEXT_PAGE_FIELDS[k], why]);
1837
+ if (computed.length) refused[p.path] = { file, reason: "computed", fields: Object.fromEntries(computed) };
1838
+ }
1839
+ let site = null;
1840
+ if (layout) {
1841
+ const src = await read(layout);
1842
+ const r = src === null ? null : siteMetaFields(src);
1843
+ if (r?.fields.socialImage && drawnImage(layout, have)) {
1844
+ delete r.fields.socialImage;
1845
+ r.computed.socialImage = "computed";
1846
+ }
1847
+ if (r) {
1848
+ const fields = {};
1849
+ for (const [k, f] of Object.entries(r.fields)) if (f) fields[NEXT_SITE_FIELDS[k]] = settingOf(layout, f);
1850
+ if (Object.keys(fields).length) site = fields;
1851
+ const computed = Object.entries(r.computed).map(([k, why]) => [NEXT_SITE_FIELDS[k], why]);
1852
+ if (r.refused) refused.site = { file: layout, reason: await reasonOf(layout, r.refused) };
1853
+ else if (computed.length) refused.site = { file: layout, reason: "computed", fields: Object.fromEntries(computed) };
1854
+ }
1855
+ }
1856
+ return { pages: out, routes: null, site, refused };
1857
+ }
1858
+
1859
+ // supabase/functions/unbase-projects/pages.ts
1860
+ var MAX_PAGES = 2e3;
1861
+ 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;
1862
+ var LATER = { ok: false, reason: "later" };
1863
+ function registryOf(input) {
1864
+ const { framework, staged, truncated } = input;
1865
+ const byPath = new Map(input.files.map((f) => [f.path, f.text]));
1866
+ const paths = [...byPath.keys()].sort();
1867
+ const text = (p) => byPath.get(p) ?? null;
1868
+ const pageFile = parsePageFile(text(PAGE_FILE));
1869
+ const flags = pageFile.pages;
1870
+ const kit = kitInstalled({ framework, text });
1871
+ const found = discover({ framework, paths, text });
1872
+ const importers = importGraph(paths, text);
1873
+ const draftable = DRAFTABLE.includes(String(framework));
1874
+ const draft = (path) => {
1875
+ const c = draftCheck(path, { framework, paths, text, found, importers });
1876
+ const no = (reason, detail) => ({ capability: { ok: false, reason, ...detail ? { detail } : {} }, own: [] });
1877
+ if (!c.ok && (c.reason === "home" || c.reason === "template")) return no(c.reason, c.detail);
1878
+ if (!draftable) return no("framework");
1879
+ if (!kit) return no("kit_missing");
1880
+ if (!staged) return no("not_staged");
1881
+ if (truncated) return no("too_large");
1882
+ if (!c.ok) return no(c.reason, c.detail);
1883
+ return { capability: { ok: true }, own: c.content };
1884
+ };
1885
+ const pages = found.pages.filter((p) => !p.path.includes(" ")).slice(0, MAX_PAGES).map((p) => {
1886
+ const d = p.kind === "template" ? { capability: { ok: false, reason: "template" }, own: [] } : draft(p.path);
1887
+ const own = [p.file, ...d.own].filter((f) => !!f);
1888
+ return {
1889
+ path: p.path,
1890
+ kind: p.kind,
1891
+ file: p.file,
1892
+ flag: flags[p.path]?.draft ?? null,
1893
+ capabilities: { draft: d.capability, rename: LATER, duplicate: LATER, delete: LATER },
1894
+ links: p.kind === "template" ? [] : linksTo(p.path, { paths, text, own })
1895
+ };
1896
+ });
1897
+ const drafts = !pageFile.ok ? [{ path: PAGE_FILE, ok: false, reason: "invalid", detail: pageFile.error }] : draftPaths(pageFile).map((path) => {
1898
+ const { capability } = draft(path);
1899
+ return capability.ok ? { path, ok: true } : { path, ...capability };
1900
+ });
1901
+ const file = input.appPath ? `${input.appPath.replace(/\/+$/, "")}/${PAGE_FILE}` : PAGE_FILE;
1902
+ return {
1903
+ framework,
1904
+ kit,
1905
+ staged,
1906
+ pageFile: { file, exists: pageFile.exists, ok: pageFile.ok, ...pageFile.ok ? {} : { error: pageFile.error } },
1907
+ pages,
1908
+ drafts,
1909
+ truncated
1910
+ };
1911
+ }
1912
+ export {
1913
+ pages_core_exports as core,
1914
+ detect,
1915
+ readSettings,
1916
+ registryFiles,
1917
+ registryOf
1918
+ };