okno 1.0.0-beta.37 → 1.0.0-beta.39

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,955 @@
1
+ import { join as _, relative as H, sep as U, dirname as N, resolve as ue } from "node:path";
2
+ import { readdir as E, readFile as we, writeFile as be } from "node:fs/promises";
3
+ import { existsSync as $, readFileSync as v, readdirSync as se, statSync as Se, realpathSync as Oe, writeFileSync as R, mkdirSync as W, unlinkSync as B, renameSync as ve } from "node:fs";
4
+ import { execSync as oe } from "node:child_process";
5
+ import { fileURLToPath as je } from "node:url";
6
+ import { p as Z } from "./parse-tlTHgSSs.js";
7
+ import { o as Ae } from "./order-bAkdncZC.js";
8
+ import { simpleGit as fe } from "simple-git";
9
+ import { b as ee, a as Te, e as xe } from "./encode-BfJY0Xy5.js";
10
+ import { applyKeyChanges as me, setStringsSchema as Re, saveFields as Pe, setLocales as Ee, setName as Me, setUrl as Ne, renameSlug as Ie, reorderKind as We, setLayout as Fe, setCollectionOrder as Le, setDrafts as Ue, deleteSchemaEntry as Ce, scaffoldEntry as ze, fieldsToContent as Je, EngineError as Ve } from "./engine/index.js";
11
+ const Be = /* @__PURE__ */ new Set([".astro", ".svelte", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".vue"]), Ge = /* @__PURE__ */ new Set([
12
+ "node_modules",
13
+ ".astro",
14
+ ".svelte-kit",
15
+ ".next",
16
+ ".nuxt",
17
+ ".vite",
18
+ "dist",
19
+ "build",
20
+ ".git",
21
+ ".turbo"
22
+ ]);
23
+ async function Y(e, n) {
24
+ const s = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']okno[:/]${n}["']`, "g"), i = /* @__PURE__ */ new Set();
25
+ async function u(c) {
26
+ let p;
27
+ try {
28
+ p = await E(c, { withFileTypes: !0 });
29
+ } catch {
30
+ return;
31
+ }
32
+ for (const f of p) {
33
+ if (f.name.startsWith(".") && f.name !== "." || Ge.has(f.name)) continue;
34
+ const a = _(c, f.name);
35
+ if (f.isDirectory()) {
36
+ await u(a);
37
+ continue;
38
+ }
39
+ const t = f.name.lastIndexOf(".");
40
+ if (t === -1) continue;
41
+ const r = f.name.slice(t);
42
+ if (!Be.has(r)) continue;
43
+ let o;
44
+ try {
45
+ o = await we(a, "utf-8");
46
+ } catch {
47
+ continue;
48
+ }
49
+ if (!(!o.includes(`okno:${n}`) && !o.includes(`okno/${n}`)))
50
+ for (const m of o.matchAll(s)) {
51
+ const d = m[1] ?? "";
52
+ for (const h of d.split(",")) {
53
+ const y = h.trim().split(/\s+as\s+/)[0]?.trim();
54
+ y && /^[A-Za-z_$][\w$]*$/.test(y) && i.add(y);
55
+ }
56
+ }
57
+ }
58
+ }
59
+ return await u(e), i;
60
+ }
61
+ async function bt(e, n) {
62
+ const s = await et(e), i = new Map(s.map((l) => [l.name, l.first])), u = Ye(e), c = [
63
+ "// Auto-generated by okno. Do not edit.",
64
+ "",
65
+ "/** A wrapped content value that can be spread onto elements and rendered as text. */",
66
+ "type OknoValue<T = unknown> = {",
67
+ ' readonly "data-okno": string',
68
+ " toString(): string",
69
+ // NB: NO `[Symbol.toPrimitive]` in the TYPE. Svelte 5's element-attribute type
70
+ // carries a symbol index signature for attachments (`[key: symbol]: Attachment`),
71
+ // and a `(hint: string) => string` toPrimitive isn't assignable to it — so a
72
+ // `{...field}` spread would fail type-check on every element. The runtime keeps
73
+ // Symbol.toPrimitive (see runtime/wrap.ts) so `{field}` / String(field) still
74
+ // coerce; `toString()` covers the static string-coercion the type needs.
75
+ " onedit(callback: (value: T) => void): () => void",
76
+ " /** Re-root reads at a locale; no-op when unset or on the default locale. Returns the SAME wrapped shape (not `this`, which would drop array element types). */",
77
+ " locale(code?: string | null): OknoWrapped<T>",
78
+ " /** `true` when this field/reference actually holds a value — every read is a truthy wrapper, so `entry.ref ? …` can't tell set from unset. */",
79
+ " readonly exists: boolean",
80
+ "}",
81
+ "",
82
+ "/** The explicit reorder handle — spread `.drag` on a semantic wrapper (`<li {...item.drag}>`, `<tr {...item.drag}>`) when the item's own element can't be the direct child of the reorder container. Emits the same `data-okno-item` boundary as the bare `{...item}` spread; the editor resolves the OUTERMOST element carrying it as the drag unit, so both a wrapper's `.drag` and an inner `{...item}` can coexist. Present on every array item (leaf AND block). */",
83
+ 'type OknoDrag = { readonly drag: { readonly "data-okno-item": string } }',
84
+ "/** The reorder hook carried directly on a LEAF array item's bare spread (`{...item}`), so a leaf multiple needs no separate `{...item.drag}` in the common case. */",
85
+ 'type OknoDragItem = { readonly "data-okno-item": string }',
86
+ "/** One array member. A LEAF (media/link/text) is spread bare — `{...item}` — so it carries `data-okno-item` for reorder AND still exposes `.drag` as an escape hatch (for a semantic wrapper). A BLOCK/reference member has inner fields, so its bare `{...item}` would dump field keys; it spreads content fields on its wrapper plus `.drag` for reorder. */",
87
+ "type OknoArrayItem<U> =",
88
+ " U extends string | number | boolean",
89
+ " ? OknoWrapped<U> & OknoDragItem & OknoDrag",
90
+ " : U extends { src: string }",
91
+ " ? OknoWrapped<U> & OknoDragItem & OknoDrag",
92
+ " : U extends { url: string; text: string }",
93
+ " ? OknoWrapped<U> & OknoDragItem & OknoDrag",
94
+ " : OknoWrapped<U> & OknoDrag",
95
+ "",
96
+ "/** A media value's `.image` handle — a spreadable bundle for a framework image component (Astro `<Image {...cover.image}>`): build-optimized `src` (from `okno/files`), plus alt/dimensions and the edit hook. Use `<img {...cover}>` for the raw/universal path. `src` is loose (framework's shape, e.g. Astro `ImageMetadata`) so okno stays framework-agnostic. */",
97
+ 'type OknoImage = { src: any; alt: string; width?: number; height?: number; readonly "data-okno": string }',
98
+ "",
99
+ "/** Recursively wraps content types so values are spreadable/renderable. Media (`{src}`) and link (`{url,text}`) objects keep RAW attribute values so `<img {...media}>` / `<a {...link}>` type-check; media also exposes `.image`; other objects expose wrapped fields + the data-okno hook. Array items carry `data-okno-item` on the bare spread (leaf multiples) AND expose `.drag` (the explicit reorder handle, for block wrappers or a leaf's semantic wrapper). */",
100
+ "type OknoWrapped<T> =",
101
+ " T extends string | number | boolean",
102
+ " ? OknoValue<T> & { readonly value: T }",
103
+ " : T extends ReadonlyArray<infer U>",
104
+ " ? OknoArrayItem<U>[]",
105
+ " : T extends { src: string }",
106
+ ' ? Omit<T, "focal"> & OknoValue<T> & { readonly image: OknoImage } & (T extends { focal: infer F } ? { readonly focal: OknoWrapped<F> } : {})',
107
+ " : T extends { url: string; text: string }",
108
+ " ? { href: string; target?: string; rel?: string } & OknoValue<T>",
109
+ " : T extends Record<string, unknown>",
110
+ ' ? { [K in keyof T]: K extends "href" ? string : OknoWrapped<T[K]> } & OknoValue<T>',
111
+ " : OknoValue<T>",
112
+ "",
113
+ "/** Content referenced in code but not yet scaffolded — shape unknown, so every field is a flat leaf. Nested access (`home.hero.title`) is a type error on purpose: okno fields are flat (dividers organize the editor, they don't nest data). Use a Block for nested shapes. */",
114
+ "type OknoUnscaffolded = OknoWrapped<Record<string, unknown>>",
115
+ "",
116
+ "/** Authorship + timestamp metadata Okno writes on every entry (page, collection item, global). Read-only — never edit or spread; it's the data your own `.sort()` uses. Each is wrapped, so render `{a.updated.date}` and compare `String(a.updated.date)`. */",
117
+ "type OknoStamp = { readonly date: string; readonly author: string }",
118
+ "type OknoMeta = {",
119
+ " readonly created: OknoWrapped<OknoStamp>",
120
+ " readonly updated: OknoWrapped<OknoStamp>",
121
+ "}",
122
+ ""
123
+ ], p = ([, l]) => l?.type === "reference" && typeof l.collection == "string" && i.has(l.collection), f = ([, l]) => l?.type === "enum", a = ([l, g]) => {
124
+ const k = (Array.isArray(g?.options) ? g.options : []).map((w) => typeof w == "string" ? w : w?.value).filter((w) => typeof w == "string"), S = `{ name: string; value: ${k.length ? k.map((w) => JSON.stringify(w)).join(" | ") : "string"} }`;
125
+ return `${l}: ${g.multiple ? `${S}[]` : S}`;
126
+ }, t = (l) => `typeof import("./collections/${l}/${i.get(l)}").default`, r = (l) => {
127
+ const g = u?.collections?.[l]?.url;
128
+ return typeof g == "string" && g.trim() ? " & { href: string }" : "";
129
+ }, o = (l, g) => {
130
+ const k = t(l), b = u?.collections?.[l]?.fields, S = b ? Object.entries(b) : [], w = S.filter(p), O = S.filter(f);
131
+ if (w.length === 0 && O.length === 0) return `${k}${r(l)}`;
132
+ const j = [...w, ...O].map(([P]) => `"${P}"`).join(" | "), A = new Set(g).add(l), C = [
133
+ ...w.map(([P, I]) => {
134
+ const M = I.collection, x = g.has(M) ? t(M) : o(M, A);
135
+ return `${P}: ${I.multiple ? `(${x})[]` : x}`;
136
+ }),
137
+ ...O.map(a)
138
+ ].join("; ");
139
+ return `Omit<${k}, ${j}> & { ${C} }${r(l)}`;
140
+ }, m = (l, g, k) => {
141
+ const b = `typeof import("${k}").default`, S = u?.[l]?.[g]?.fields, w = S ? Object.entries(S) : [], O = w.filter(p), j = w.filter(f), A = '"created" | "updated"', C = l === "collections" ? r(g) : "";
142
+ if (O.length === 0 && j.length === 0)
143
+ return `OknoWrapped<Omit<${b}, ${A}>${C}> & OknoMeta`;
144
+ const P = l === "collections" ? /* @__PURE__ */ new Set([g]) : /* @__PURE__ */ new Set(), I = `${[...O, ...j].map(([x]) => `"${x}"`).join(" | ")} | ${A}`, M = [
145
+ ...O.map(([x, V]) => {
146
+ const z = V.collection, ce = P.has(z) ? t(z) : o(z, P);
147
+ return `${x}: ${V.multiple ? `(${ce})[]` : ce}`;
148
+ }),
149
+ ...j.map(a)
150
+ ].join("; ");
151
+ return `OknoWrapped<Omit<${b}, ${I}> & { ${M} }${C}> & OknoMeta`;
152
+ }, [d, h, y] = await Promise.all([
153
+ Y(n, "pages"),
154
+ Y(n, "globals"),
155
+ Y(n, "collections")
156
+ ]);
157
+ c.push(
158
+ ...de("okno:pages", "pages", await te(_(e, "pages")), d, m)
159
+ ), c.push(...Qe(s, y, m)), c.push(
160
+ ...de("okno:globals", "globals", await te(_(e, "globals")), h, m)
161
+ ), c.push(...Ze(De(e), qe(u))), c.push(...Ke()), c.push(...He());
162
+ for (const l of ["pages", "collections", "globals", "locales", "strings", "content"])
163
+ c.push(`declare module "okno/${l}" {`, ` export * from "okno:${l}";`, "}", "");
164
+ await be(_(e, "modules.d.ts"), c.join(`
165
+ `));
166
+ }
167
+ function de(e, n, s, i, u) {
168
+ const c = /* @__PURE__ */ new Set(), p = [];
169
+ for (const f of s)
170
+ p.push(` export const ${f}: ${u(n, f, `./${n}/${f}`)}`), c.add(f);
171
+ for (const f of i)
172
+ c.has(f) || p.push(` export const ${f}: OknoUnscaffolded`);
173
+ return [`declare module "${e}" {`, ...p, "}", ""];
174
+ }
175
+ function Ke() {
176
+ return [
177
+ 'declare module "okno:locales" {',
178
+ ' /** A configured language. `id` is the BCP-47 tag (e.g. "zh-Hant"), `name` the display label, `slug` the URL segment you map into routing. `link(url)` returns this page\'s hreflang <link> descriptor — spread onto a <link> (pass Astro.url for an absolute href). Okno owns no routing; you map these. */',
179
+ " export interface OknoLocale {",
180
+ " id: string",
181
+ " name: string",
182
+ " slug: string",
183
+ ' link(url: URL | string): { rel: "alternate"; hreflang: string; href: string }',
184
+ " }",
185
+ " /** The configured languages; `locales.default` is the base-locale entry. Empty (`.default` undefined) when no languages are configured. */",
186
+ " export const locales: OknoLocale[] & { default: OknoLocale }",
187
+ "}",
188
+ ""
189
+ ];
190
+ }
191
+ function He() {
192
+ return [
193
+ 'declare module "okno:content" {',
194
+ ' /** Unified content namespace — `import * as okno from "okno:content"` then `okno.pages.home`, `okno.globals.nav`, `okno.collections.articles`, `okno.strings.nav.home`. */',
195
+ ' export * as pages from "okno:pages"',
196
+ ' export * as globals from "okno:globals"',
197
+ ' export * as collections from "okno:collections"',
198
+ ' export { strings } from "okno:strings"',
199
+ "}",
200
+ ""
201
+ ];
202
+ }
203
+ function Ze(e, n) {
204
+ const s = e.length ? `${Xe(e, n)}` : "any", i = e.length ? `
205
+ locale(code?: string | null): ${s}` : "";
206
+ return [
207
+ 'declare module "okno:strings" {',
208
+ " /** The UI-strings store. A plain leaf is string-like (spread `{...s.nav.home}` for the edit hook, render `{s.nav.home}` for the text); a SLOTTED leaf is a `(params) => …` function — call it, then spread/render the result (`{...s.cart.items({count})}`). `.locale(code)` re-roots the whole tree at a language. */",
209
+ ` export const strings: ${e.length ? `${s} & {${i}
210
+ }` : "any"}`,
211
+ "}",
212
+ ""
213
+ ];
214
+ }
215
+ function Xe(e, n) {
216
+ const s = { children: /* @__PURE__ */ new Map() };
217
+ for (const p of e) {
218
+ let f = s;
219
+ for (const a of p.split(".")) {
220
+ let t = f.children.get(a);
221
+ t || (t = { children: /* @__PURE__ */ new Map() }, f.children.set(a, t)), f = t;
222
+ }
223
+ }
224
+ const i = (p) => p === "text" ? "string" : "number", u = (p) => {
225
+ const f = n[p];
226
+ return !f || Object.keys(f).length === 0 ? "OknoValue<string>" : `(p: { ${Object.entries(f).map(([t, r]) => `${JSON.stringify(t)}: ${i(r)}`).join("; ")} }) => OknoValue<string>`;
227
+ }, c = (p, f) => p.children.size === 0 ? u(f) : `{ ${[...p.children.entries()].map(
228
+ ([t, r]) => `${JSON.stringify(t)}: ${c(r, f ? `${f}.${t}` : t)}`
229
+ ).join("; ")} }`;
230
+ return c(s, "");
231
+ }
232
+ function qe(e) {
233
+ const n = {}, s = e?.strings;
234
+ if (!s || typeof s != "object" || Array.isArray(s)) return n;
235
+ for (const [i, u] of Object.entries(s)) {
236
+ const c = u?.slots;
237
+ if (!c || typeof c != "object" || Array.isArray(c)) continue;
238
+ const p = {};
239
+ for (const [f, a] of Object.entries(c))
240
+ (a === "text" || a === "number" || a === "count") && (p[f] = a);
241
+ Object.keys(p).length && (n[i] = p);
242
+ }
243
+ return n;
244
+ }
245
+ function Qe(e, n, s) {
246
+ const i = /* @__PURE__ */ new Set(), u = [];
247
+ for (const c of e) {
248
+ const p = s("collections", c.name, `./collections/${c.name}/${c.first}`);
249
+ u.push(` export const ${c.name}: (${p} & OknoDrag)[]`), i.add(c.name);
250
+ }
251
+ for (const c of n)
252
+ i.has(c) || u.push(` export const ${c}: OknoUnscaffolded[]`);
253
+ return ['declare module "okno:collections" {', ...u, "}", ""];
254
+ }
255
+ function Ye(e) {
256
+ const n = _(e, "schema.ts");
257
+ if (!$(n)) return null;
258
+ try {
259
+ let s = v(n, "utf8");
260
+ const i = s.indexOf("export default");
261
+ return i === -1 ? null : (s = s.slice(i + 14).replace(/\bas const\b/g, "").replace(/\bsatisfies\s+[A-Za-z0-9_.]+/g, "").trim(), s.endsWith(";") && (s = s.slice(0, -1).trim()), JSON.parse(s));
262
+ } catch {
263
+ return null;
264
+ }
265
+ }
266
+ function De(e) {
267
+ const n = _(e, "strings.ts");
268
+ if (!$(n)) return [];
269
+ try {
270
+ let s = v(n, "utf8");
271
+ const i = s.indexOf("export default");
272
+ if (i === -1) return [];
273
+ s = s.slice(i + 14).replace(/\bas const\b/g, "").replace(/\bsatisfies\s+[A-Za-z0-9_.]+/g, "").trim(), s.endsWith(";") && (s = s.slice(0, -1).trim());
274
+ const u = JSON.parse(s);
275
+ return u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u) : [];
276
+ } catch {
277
+ return [];
278
+ }
279
+ }
280
+ async function et(e) {
281
+ const n = _(e, "collections");
282
+ if (!$(n)) return [];
283
+ const s = (await E(n, { withFileTypes: !0 })).filter((u) => u.isDirectory()), i = [];
284
+ for (const u of s) {
285
+ const c = await te(_(n, u.name));
286
+ c.length > 0 && i.push({ name: u.name, first: c[0] });
287
+ }
288
+ return i;
289
+ }
290
+ async function te(e) {
291
+ return $(e) ? (await E(e)).filter((s) => s.endsWith(".ts") && s !== "index.ts" && s !== "modules.d.ts").map((s) => s.replace(".ts", "")) : [];
292
+ }
293
+ function re(e) {
294
+ try {
295
+ return oe(e, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
296
+ } catch {
297
+ return null;
298
+ }
299
+ }
300
+ function tt() {
301
+ const e = re("git rev-parse --abbrev-ref HEAD");
302
+ if (e && e !== "HEAD") return e;
303
+ const n = process.env;
304
+ return n.CF_PAGES_BRANCH || // Cloudflare Pages
305
+ n.VERCEL_GIT_COMMIT_REF || // Vercel
306
+ n.BRANCH || // Netlify
307
+ n.GITHUB_REF_NAME || // GitHub Actions
308
+ "main";
309
+ }
310
+ function St() {
311
+ const e = re("git remote get-url origin");
312
+ if (!e) return null;
313
+ const n = e.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/);
314
+ return n ? `${n[1]}/${n[2]}@${tt()}` : null;
315
+ }
316
+ function Ot() {
317
+ const e = re("git rev-parse --show-toplevel");
318
+ return e ? H(e, process.cwd()).split(U).join("/") : "";
319
+ }
320
+ const ae = '__oknoSetImages(import.meta.glob("/okno/files/**/*.{png,jpg,jpeg,webp,avif,gif,svg,tiff}", { eager: false }))', pe = N(je(import.meta.url)), nt = [
321
+ ue(pe, "./runtime/wrap.js"),
322
+ // bundled at dist/ (Vite plugin chunk)
323
+ ue(pe, "../runtime/wrap.js")
324
+ // bundled at dist/next/ (Next entry)
325
+ ];
326
+ function vt() {
327
+ for (const e of nt)
328
+ if ($(e)) return v(e, "utf-8");
329
+ return null;
330
+ }
331
+ function jt() {
332
+ return [
333
+ 'export * as pages from "okno:pages"',
334
+ 'export * as globals from "okno:globals"',
335
+ 'export * as collections from "okno:collections"',
336
+ 'export { strings } from "okno:strings"'
337
+ ].join(`
338
+ `);
339
+ }
340
+ function q(e) {
341
+ const n = _(e, "schema.ts");
342
+ if (!$(n)) return null;
343
+ try {
344
+ const i = Z(v(n, "utf-8"))?.locales?.supported;
345
+ if (!Array.isArray(i) || i.length === 0) return null;
346
+ const u = i.map((c) => typeof c == "string" ? c : c?.id).filter((c) => typeof c == "string");
347
+ return u.length ? new Set(u) : null;
348
+ } catch {
349
+ return null;
350
+ }
351
+ }
352
+ function K(e, n) {
353
+ return n ? n.has(e) : rt.test(e);
354
+ }
355
+ function st(e) {
356
+ for (const n of [e, "en"])
357
+ try {
358
+ const s = new Intl.DisplayNames([n], { type: "language" }).of(e);
359
+ if (s && s !== e) return s;
360
+ } catch {
361
+ }
362
+ return e;
363
+ }
364
+ async function ie(e) {
365
+ return $(e) ? (await E(e)).filter((s) => s.endsWith(".ts") && s !== "index.ts") : [];
366
+ }
367
+ function ot(e) {
368
+ const n = _(e, "schema.ts"), s = {}, i = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Set();
369
+ if (!$(n)) return { orders: s, draftsOff: i, schedulingOff: u };
370
+ try {
371
+ const p = Z(v(n, "utf-8"))?.collections ?? {};
372
+ for (const [f, a] of Object.entries(p))
373
+ Array.isArray(a?.order) && (s[f] = a.order.filter((t) => typeof t == "string")), a?.drafts === !1 && i.add(f), a?.scheduling === !1 && u.add(f);
374
+ } catch {
375
+ }
376
+ return { orders: s, draftsOff: i, schedulingOff: u };
377
+ }
378
+ const rt = /^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i, Q = (e) => e.replace(/[^a-zA-Z0-9]/g, "_");
379
+ function le(e) {
380
+ return e.replace(".ts", "").replace(/-/g, "_");
381
+ }
382
+ function ye(e) {
383
+ return e.replace(".ts", "").replace(/-/g, "_");
384
+ }
385
+ function X(e) {
386
+ return e.replace(".ts", "");
387
+ }
388
+ function At(e) {
389
+ const n = _(e, "schema.ts");
390
+ let s = [], i = "";
391
+ if ($(n))
392
+ try {
393
+ const u = Z(v(n, "utf-8")), c = u?.locales?.supported;
394
+ Array.isArray(c) && (s = c.map((p) => typeof p == "string" ? { id: p } : p).filter((p) => !!p && typeof p.id == "string").map((p) => ({
395
+ id: p.id,
396
+ name: p.name || st(p.id),
397
+ // Preserve an intentionally empty slug (= no URL prefix for the default).
398
+ slug: typeof p.slug == "string" ? p.slug : p.id.toLowerCase()
399
+ })), i = typeof u.locales.default == "string" ? u.locales.default : s[0]?.id ?? "");
400
+ } catch {
401
+ }
402
+ return [
403
+ `const __raw = ${JSON.stringify(s)}`,
404
+ `const __def = ${JSON.stringify(i)}`,
405
+ // Swap the locale prefix on a path (empty slug = no prefix). Best-effort,
406
+ // matches the editor's own resolver; fully translated paths = dev's own tags.
407
+ "function __swap(pathname, slug) {",
408
+ ' const norm = (pathname || "/").replace(/\\/+$/, "") || "/"',
409
+ ' const segs = norm.split("/").filter(Boolean)',
410
+ " const known = __raw.find((l) => l.slug && l.slug === segs[0])",
411
+ ' const rest = known ? "/" + segs.slice(1).join("/") : norm',
412
+ ' const r = rest === "" ? "/" : rest',
413
+ " if (!slug) return r",
414
+ ' return r === "/" ? "/" + slug : "/" + slug + r',
415
+ "}",
416
+ 'const __origin = (url) => (typeof url === "object" && url !== null ? url.origin : "")',
417
+ 'const __path = (url) => (typeof url === "object" && url !== null ? url.pathname : String(url || "/"))',
418
+ "/** The configured languages — an array of { id, name, slug, link(url) }.",
419
+ " * link(url) → this entry's hreflang <link> descriptor (spread onto a <link>;",
420
+ " * pass Astro.url for an absolute href). `locales.default` is the base entry. */",
421
+ "export const locales = __raw.map((l) => ({",
422
+ " ...l,",
423
+ ' link: (url) => ({ rel: "alternate", hreflang: l.id, href: __origin(url) + __swap(__path(url), l.slug) }),',
424
+ "}))",
425
+ // `.default` = the base-locale entry (same object reference as in the array).
426
+ "locales.default = locales.find((l) => l.id === __def) || locales[0]"
427
+ ].join(`
428
+ `);
429
+ }
430
+ async function Tt(e) {
431
+ const n = _(e, "strings.ts");
432
+ if (!$(n))
433
+ return [
434
+ 'import { __oknoMakeStrings } from "okno:runtime"',
435
+ 'export const strings = __oknoMakeStrings({}, {}, "")'
436
+ ].join(`
437
+ `);
438
+ const s = _(e, "schema.ts"), i = $(s), u = q(e), c = _(e, "strings"), p = [];
439
+ if ($(c)) {
440
+ const o = await E(c, { withFileTypes: !0 });
441
+ for (const m of o) {
442
+ if (!m.isFile() || !m.name.endsWith(".ts") || m.name === "index.ts") continue;
443
+ const d = m.name.replace(/\.ts$/, "");
444
+ K(d, u) && p.push(d);
445
+ }
446
+ }
447
+ const f = [
448
+ 'import { __oknoMakeStrings, __oknoLocalize, __oknoExpandStrings } from "okno:runtime"',
449
+ `import _strings_default from "${n}"`
450
+ ];
451
+ i && f.push(`import __schema from "${s}"`);
452
+ const a = i ? "__schema?.strings" : "{}", t = i ? "__schema?.locales?.default" : '""';
453
+ if (p.length === 0)
454
+ return f.push(`export const strings = __oknoMakeStrings(__oknoExpandStrings(_strings_default), ${a}, ${t})`), f.join(`
455
+ `);
456
+ const r = [];
457
+ for (const o of p) {
458
+ const m = Q(o);
459
+ f.push(`import _strings_${m} from "${_(c, o + ".ts")}"`), r.push(`"${o}": __oknoExpandStrings(_strings_${m})`);
460
+ }
461
+ return f.push("const _strings_base = __oknoExpandStrings(_strings_default)"), f.push(`const _strings_localized = __oknoLocalize(_strings_base, { ${r.join(", ")} })`), f.push(`export const strings = __oknoMakeStrings(_strings_localized, ${a}, ${t})`), f.join(`
462
+ `);
463
+ }
464
+ async function xt(e, n = /* @__PURE__ */ new Set()) {
465
+ const s = _(e, "pages"), i = _(e, "schema.ts"), u = $(i), c = [
466
+ 'import { __oknoWrap, __oknoLocalize, __oknoResolveRefs, __oknoResolveEnums, __oknoSetImages, __oknoSetRoutes } from "okno:runtime"',
467
+ ae
468
+ ];
469
+ u && (c.push('import * as __collections from "okno:collections"'), c.push(`import __schema from "${i}"`), c.push("__oknoSetRoutes(__schema)"));
470
+ let p = "[]";
471
+ const f = (t, r) => {
472
+ if (!u) return `_${t}`;
473
+ const o = `__schema?.pages?.["${r}"]?.fields`;
474
+ return `__oknoResolveEnums(__oknoResolveRefs(_${t}, ${o}, __collections, ${p}), ${o}, ${p})`;
475
+ }, a = /* @__PURE__ */ new Set();
476
+ if ($(s)) {
477
+ const t = q(e), o = (await E(s, { withFileTypes: !0 })).filter((d) => d.isDirectory() && K(d.name, t)).map((d) => d.name);
478
+ p = JSON.stringify(o);
479
+ const m = await ie(s);
480
+ for (const d of m) {
481
+ const h = le(d), y = ye(d), l = X(d), g = _(s, d);
482
+ if (o.length === 0) {
483
+ c.push(`import _${h} from "${g}"`), c.push(`export const ${y} = __oknoWrap(${f(h, l)}, "${l}")`), a.add(y);
484
+ continue;
485
+ }
486
+ const k = [`import _${h}_default from "${g}"`], b = [];
487
+ for (const S of o) {
488
+ const w = _(s, S, d);
489
+ if ($(w)) {
490
+ const O = Q(S);
491
+ k.push(`import _${h}_${O} from "${w}"`), b.push(`"${S}": _${h}_${O}`);
492
+ }
493
+ }
494
+ c.push(...k), c.push(`const _${h} = __oknoLocalize(_${h}_default, { ${b.join(", ")} })`), c.push(`export const ${y} = __oknoWrap(${f(h, l)}, "${l}")`), a.add(y);
495
+ }
496
+ }
497
+ for (const t of n)
498
+ a.has(t) || c.push(`export const ${t} = __oknoWrap(null, "${t}")`);
499
+ return c.join(`
500
+ `);
501
+ }
502
+ async function Rt(e, n = /* @__PURE__ */ new Set(), s = !1) {
503
+ const i = _(e, "collections");
504
+ if (!$(i)) {
505
+ const l = [];
506
+ for (const g of n) {
507
+ const k = g.replace(/-/g, "_");
508
+ l.push(`export const ${k} = []`);
509
+ }
510
+ return l.join(`
511
+ `) || "export {}";
512
+ }
513
+ const u = q(e), c = await E(i, { withFileTypes: !0 }), p = c.filter((l) => l.isDirectory() && K(l.name, u)).map((l) => l.name), f = c.filter((l) => l.isDirectory() && !p.includes(l.name)).map((l) => l.name), a = JSON.stringify(p);
514
+ for (const l of f) {
515
+ const g = await E(_(i, l), { withFileTypes: !0 }).catch(() => []);
516
+ for (const k of g)
517
+ k.isDirectory() && K(k.name, u) && console.warn(
518
+ `[okno] "collections/${l}/${k.name}/" looks like a misplaced locale folder. Collection locale overrides go at "collections/${k.name}/${l}/<slug>.ts" (locale right after "collections/"). This folder will NOT be localized.`
519
+ );
520
+ }
521
+ const { orders: t, draftsOff: r, schedulingOff: o } = ot(e), m = _(e, "schema.ts"), d = $(m), h = [
522
+ 'import { __oknoWrap, __oknoLocalize, __oknoResolveRefs, __oknoResolveEnums, __oknoSetImages, __oknoSetRoutes, __oknoVisible } from "okno:runtime"',
523
+ ae
524
+ ];
525
+ d && (h.push(`import __schema from "${m}"`), h.push("__oknoSetRoutes(__schema)"));
526
+ const y = [];
527
+ for (const l of f) {
528
+ const g = _(i, l), k = Ae(await ie(g), X, t[l]), b = l.replace(/-/g, "_"), S = s && !r.has(l), w = s && !o.has(l), O = [];
529
+ for (const j of k) {
530
+ const A = `_${b}_${le(j)}`, C = X(j), P = _(g, j);
531
+ if (p.length === 0)
532
+ h.push(`import ${A} from "${P}"`);
533
+ else {
534
+ const I = [`import ${A}_default from "${P}"`], M = [];
535
+ for (const x of p) {
536
+ const V = _(i, x, l, j);
537
+ if ($(V)) {
538
+ const z = Q(x);
539
+ I.push(`import ${A}_${z} from "${V}"`), M.push(`"${x}": ${A}_${z}`);
540
+ }
541
+ }
542
+ h.push(...I), h.push(`const ${A} = __oknoLocalize(${A}_default, { ${M.join(", ")} })`);
543
+ }
544
+ O.push({ varName: A, itemName: C });
545
+ }
546
+ h.push(`const __oknoRaw_${b} = [${O.map((j) => j.varName).join(", ")}]`), y.push({ name: l, safe: b, draftsOn: S, schedulingOn: w, items: O });
547
+ }
548
+ d && h.push(`const __oknoNs = { ${y.map((l) => `${l.safe}: __oknoRaw_${l.safe}`).join(", ")} }`);
549
+ for (const l of y) {
550
+ const g = `__schema?.collections?.["${l.name}"]?.fields`, k = (w) => d ? `__oknoResolveEnums(__oknoResolveRefs(${w.varName}, ${g}, __oknoNs, ${a}), ${g}, ${a})` : w.varName, b = [];
551
+ l.draftsOn && b.push('e[0]?.status !== "draft"'), l.schedulingOn && b.push("__oknoVisible(e[0])");
552
+ const S = b.length ? `[${l.items.map((w) => `[${w.varName}, ${k(w)}, ${JSON.stringify(w.itemName)}]`).join(", ")}].filter((e) => ${b.join(" && ")}).map((e, __i) => __oknoWrap(e[1], "${l.name}." + e[2], "${l.name}." + __i))` : `[${l.items.map((w, O) => `__oknoWrap(${k(w)}, "${l.name}.${w.itemName}", "${l.name}.${O}")`).join(", ")}]`;
553
+ h.push(`export const ${l.safe} = ${S}`);
554
+ }
555
+ return h.join(`
556
+ `);
557
+ }
558
+ async function Pt(e, n = /* @__PURE__ */ new Set()) {
559
+ const s = _(e, "globals"), i = _(e, "schema.ts"), u = $(i), c = [
560
+ 'import { __oknoWrap, __oknoLocalize, __oknoResolveRefs, __oknoResolveEnums, __oknoSetImages, __oknoSetRoutes } from "okno:runtime"',
561
+ ae
562
+ ];
563
+ u && (c.push('import * as __collections from "okno:collections"'), c.push(`import __schema from "${i}"`), c.push("__oknoSetRoutes(__schema)"));
564
+ let p = "[]";
565
+ const f = (t, r) => {
566
+ if (!u) return `_${t}`;
567
+ const o = `__schema?.globals?.["${r}"]?.fields`;
568
+ return `__oknoResolveEnums(__oknoResolveRefs(_${t}, ${o}, __collections, ${p}), ${o}, ${p})`;
569
+ }, a = /* @__PURE__ */ new Set();
570
+ if ($(s)) {
571
+ const t = q(e), o = (await E(s, { withFileTypes: !0 })).filter((d) => d.isDirectory() && K(d.name, t)).map((d) => d.name);
572
+ p = JSON.stringify(o);
573
+ const m = await ie(s);
574
+ for (const d of m) {
575
+ const h = le(d), y = ye(d), l = X(d), g = _(s, d);
576
+ if (o.length === 0) {
577
+ c.push(`import _${h} from "${g}"`), c.push(`export const ${y} = __oknoWrap(${f(h, l)}, "${l}")`), a.add(y);
578
+ continue;
579
+ }
580
+ const k = [`import _${h}_default from "${g}"`], b = [];
581
+ for (const S of o) {
582
+ const w = _(s, S, d);
583
+ if ($(w)) {
584
+ const O = Q(S);
585
+ k.push(`import _${h}_${O} from "${w}"`), b.push(`"${S}": _${h}_${O}`);
586
+ }
587
+ }
588
+ c.push(...k), c.push(`const _${h} = __oknoLocalize(_${h}_default, { ${b.join(", ")} })`), c.push(`export const ${y} = __oknoWrap(${f(h, l)}, "${l}")`), a.add(y);
589
+ }
590
+ }
591
+ for (const t of n)
592
+ a.has(t) || c.push(`export const ${t} = __oknoWrap(null, "${t}")`);
593
+ return c.join(`
594
+ `);
595
+ }
596
+ const $e = /* @__PURE__ */ new Map();
597
+ function L(e) {
598
+ $e.set(e, Date.now());
599
+ }
600
+ function Et(e) {
601
+ const n = $e.get(e);
602
+ return n !== void 0 && Date.now() - n < 3e3;
603
+ }
604
+ const at = ["pages", "collections", "globals"];
605
+ function F(e, n) {
606
+ if (!n || n.includes("..") || n.includes("\0") || n.startsWith("/") || !n.endsWith(".ts")) return null;
607
+ const s = _(e, n);
608
+ return s !== e && !s.startsWith(e + U) ? null : s;
609
+ }
610
+ function J(e, n) {
611
+ if (!n || n.includes("..") || n.includes("\0") || n.startsWith("/")) return null;
612
+ const s = _(e, n);
613
+ return s !== e && !s.startsWith(e + U) ? null : s;
614
+ }
615
+ function it(e) {
616
+ const n = {}, s = (u) => {
617
+ if ($(u))
618
+ for (const c of se(u, { withFileTypes: !0 })) {
619
+ const p = _(u, c.name);
620
+ if (c.isDirectory()) s(p);
621
+ else if (c.name.endsWith(".ts") && c.name !== "index.ts") {
622
+ const f = H(e, p).split(U).join("/");
623
+ n[f] = v(p, "utf-8");
624
+ }
625
+ }
626
+ };
627
+ for (const u of at) s(_(e, u));
628
+ const i = _(e, "strings.ts");
629
+ return $(i) && (n["strings.ts"] = v(i, "utf-8")), s(_(e, "strings")), n;
630
+ }
631
+ function ke(e) {
632
+ const n = _(e, "files"), s = [], i = (u) => {
633
+ if ($(u))
634
+ for (const c of se(u, { withFileTypes: !0 })) {
635
+ const p = _(u, c.name);
636
+ if (c.isDirectory()) i(p);
637
+ else if (c.name !== ".okno-tree.json") {
638
+ const f = H(n, p).split(U).join("/");
639
+ s.push({ path: `files/${f}`, filename: c.name, size: Se(p).size });
640
+ }
641
+ }
642
+ };
643
+ return i(n), s;
644
+ }
645
+ function lt(e) {
646
+ const n = _(e, "schema.ts"), s = _(e, "users.json"), i = _(e, "origins.json");
647
+ return {
648
+ schema: $(n) ? v(n, "utf-8") : null,
649
+ users: $(s) ? v(s, "utf-8") : null,
650
+ origins: $(i) ? v(i, "utf-8") : null,
651
+ content: it(e),
652
+ files: ke(e)
653
+ };
654
+ }
655
+ const he = (e) => e.replace(/[^a-zA-Z0-9._-]/g, "-"), ge = (e) => e.split("/").map((n) => n.replace(/[^a-zA-Z0-9._-]/g, "-")).filter((n) => n && n !== "-" && n !== "..").join("/");
656
+ function T(e) {
657
+ const n = _(e, "schema.ts");
658
+ let s = `import type { Schema } from "okno"
659
+
660
+ `, i = {};
661
+ if ($(n)) {
662
+ const u = v(n, "utf-8"), c = u.indexOf("export default");
663
+ c > 0 && (s = u.slice(0, c));
664
+ try {
665
+ i = Z(u) ?? {};
666
+ } catch {
667
+ i = {};
668
+ }
669
+ }
670
+ return { schema: i, header: s };
671
+ }
672
+ function ct(e, n, s) {
673
+ R(_(e, "schema.ts"), Te(n, s));
674
+ }
675
+ function ut(e, n, s, i, u) {
676
+ const c = _(e, n), p = new Set(u), f = [];
677
+ if (!$(c) || Object.keys(i).length === 0 && p.size === 0) return f;
678
+ const a = [], t = (r) => {
679
+ for (const o of se(r, { withFileTypes: !0 })) {
680
+ const m = _(r, o.name);
681
+ o.isDirectory() ? t(m) : o.name === `${s}.ts` && a.push(m);
682
+ }
683
+ };
684
+ t(c);
685
+ for (const r of a) {
686
+ let o;
687
+ try {
688
+ o = Z(v(r, "utf-8"));
689
+ } catch {
690
+ continue;
691
+ }
692
+ let m, d = !1;
693
+ if (Array.isArray(o))
694
+ m = o.map((y) => {
695
+ if (y && typeof y == "object" && !Array.isArray(y)) {
696
+ const l = me(y, i, p);
697
+ return l.changed && (d = !0), l.out;
698
+ }
699
+ return y;
700
+ });
701
+ else if (o && typeof o == "object") {
702
+ const y = me(o, i, p);
703
+ m = y.out, d = y.changed;
704
+ } else
705
+ continue;
706
+ if (!d) continue;
707
+ L(r), R(r, ee(m));
708
+ const h = H(e, r).split(U).join("/");
709
+ f.push({ rel: h, abs: r }), console.log(`[okno] field-change migrated content: ${h}`, { renames: i, deletes: u });
710
+ }
711
+ return f;
712
+ }
713
+ let D;
714
+ function ne(e) {
715
+ return D || (D = oe("git rev-parse --show-toplevel", { cwd: e, encoding: "utf-8" }).trim()), D;
716
+ }
717
+ function _e(e) {
718
+ return H(ne(e), Oe(e)).split(U).join("/");
719
+ }
720
+ let G;
721
+ function ft(e) {
722
+ if (G !== void 0) return G;
723
+ try {
724
+ G = oe("git config user.name", { cwd: e, encoding: "utf-8" }).trim() || "local";
725
+ } catch {
726
+ G = "local";
727
+ }
728
+ return G;
729
+ }
730
+ async function Mt(e, n) {
731
+ const { method: s, route: i } = n, u = { files: [], modules: [] }, c = (t, r) => {
732
+ const o = t.split("/")[0];
733
+ o !== "pages" && o !== "collections" && o !== "globals" || (u.modules.push(o), u.files.push(r));
734
+ }, p = () => u.modules.push("pages", "collections", "globals"), f = (t, r) => {
735
+ ct(e, t, r), p();
736
+ }, a = (t, r) => ({ status: t, body: r, invalidation: u });
737
+ try {
738
+ if (s === "GET" && i === "content") return a(200, lt(e));
739
+ if (s === "POST" && i === "content/save") {
740
+ const { path: t, content: r, created: o, author: m } = await n.json();
741
+ if (!t || !r) return a(400, { error: "Missing path or content" });
742
+ const d = F(e, t);
743
+ if (!d) return a(400, { error: "Invalid path" });
744
+ const h = xe(r, { now: (/* @__PURE__ */ new Date()).toISOString(), author: m || ft(e), created: o });
745
+ return W(N(d), { recursive: !0 }), L(d), R(d, h), c(t, d), a(200, { ok: !0, commit: { fileSha: "" } });
746
+ }
747
+ if (s === "POST" && i === "content/delete") {
748
+ const t = (await n.json())?.path;
749
+ if (!t) return a(400, { error: "Missing path" });
750
+ const r = F(e, t);
751
+ return r ? ($(r) && (B(r), c(t, r)), a(200, { ok: !0 })) : a(400, { error: "Invalid path" });
752
+ }
753
+ if (s === "POST" && i === "strings/save") {
754
+ const { path: t, content: r } = await n.json();
755
+ if (!t || !r || typeof r != "object") return a(400, { error: "Missing path or content" });
756
+ if (t !== "strings.ts" && !/^strings\/[^/]+\.ts$/.test(t)) return a(400, { error: "Invalid strings path" });
757
+ const o = F(e, t);
758
+ return o ? (W(N(o), { recursive: !0 }), L(o), R(o, ee(r)), u.modules.push("strings", "content"), u.files.push(o), a(200, { ok: !0, commit: { fileSha: "" } })) : a(400, { error: "Invalid path" });
759
+ }
760
+ if (s === "POST" && i === "strings/set-schema") {
761
+ const { strings: t } = await n.json();
762
+ if (t != null && (typeof t != "object" || Array.isArray(t))) return a(400, { error: "Invalid strings" });
763
+ const { schema: r, header: o } = T(e);
764
+ return Re(r, t), f(r, o), u.modules.push("strings", "content"), a(200, { ok: !0, commit: { fileSha: "" }, schema: r });
765
+ }
766
+ if (s === "GET" && i === "publish-state")
767
+ try {
768
+ const t = fe(ne(e)), r = await t.status(), o = _e(e), m = (l) => l.startsWith(o + "/"), d = r.files.map((l) => l.path).filter(m);
769
+ let h = [];
770
+ if (r.ahead > 0)
771
+ try {
772
+ h = (await t.raw(["diff", "--name-only", "@{u}...HEAD", "--", o])).split(`
773
+ `).map((g) => g.trim()).filter(Boolean);
774
+ } catch {
775
+ }
776
+ const y = Array.from(/* @__PURE__ */ new Set([...d, ...h]));
777
+ return a(200, { pendingPublish: d.length > 0 || r.ahead > 0, changed: y });
778
+ } catch {
779
+ return a(200, { pendingPublish: !1 });
780
+ }
781
+ if (s === "POST" && i === "publish") {
782
+ const t = fe(ne(e)), r = _e(e);
783
+ await t.raw(["add", "-A", "--", r]);
784
+ const o = await t.status(), m = o.staged.length > 0;
785
+ let d = !1;
786
+ m && (await t.commit("okno: publish content"), d = !0);
787
+ let h = !1, y = null;
788
+ try {
789
+ (d || o.ahead > 0) && (await t.push(), h = !0);
790
+ } catch (l) {
791
+ y = l instanceof Error ? l.message.split(`
792
+ `)[0] : String(l);
793
+ }
794
+ return a(200, { ok: !0, alreadyUpToDate: !d && o.ahead === 0, committed: d, pushed: h, pushError: y });
795
+ }
796
+ if (s === "POST" && i === "schema/save-fields") {
797
+ const { kind: t, name: r, fields: o, renames: m, deletes: d } = await n.json();
798
+ if (!t || !r || !o) return a(400, { error: "Missing kind, name or fields" });
799
+ const { schema: h, header: y } = T(e);
800
+ Pe(h, t, r, o), f(h, y);
801
+ const l = m && typeof m == "object" ? m : {}, g = Array.isArray(d) ? d : [];
802
+ if (Object.keys(l).length > 0 || g.length > 0)
803
+ for (const { rel: k, abs: b } of ut(e, t, r, l, g)) c(k, b);
804
+ return a(200, { ok: !0, commit: { fileSha: "" }, schema: h });
805
+ }
806
+ if (s === "POST" && i === "schema/set-locales") {
807
+ const t = (await n.json())?.locales, { schema: r, header: o } = T(e);
808
+ return Ee(r, t), f(r, o), a(200, { ok: !0, commit: { fileSha: "" } });
809
+ }
810
+ if (s === "POST" && i === "schema/set-name") {
811
+ const { kind: t, slug: r, name: o } = await n.json();
812
+ if (!t || !r || !o) return a(400, { error: "Missing kind, slug or name" });
813
+ const { schema: m, header: d } = T(e);
814
+ return Me(m, t, r, o), f(m, d), a(200, { ok: !0, commit: { fileSha: "" } });
815
+ }
816
+ if (s === "POST" && i === "schema/set-url") {
817
+ const { kind: t, slug: r, url: o } = await n.json();
818
+ if (!t || !r) return a(400, { error: "Missing kind or slug" });
819
+ const { schema: m, header: d } = T(e);
820
+ return Ne(m, t, r, o), f(m, d), a(200, { ok: !0, commit: { fileSha: "" } });
821
+ }
822
+ if (s === "POST" && i === "schema/rename-slug") {
823
+ const { kind: t, from: r, to: o } = await n.json();
824
+ if (!t || !r || !o) return a(400, { error: "Missing kind, from or to" });
825
+ const { schema: m, header: d } = T(e), { unchanged: h } = Ie(m, t, r, o);
826
+ if (h) return a(200, { ok: !0, unchanged: !0 });
827
+ f(m, d);
828
+ const y = `${t}/${r}.ts`, l = `${t}/${o}.ts`, g = F(e, y), k = F(e, l);
829
+ return g && k && $(g) && (W(N(k), { recursive: !0 }), L(g), L(k), R(k, v(g)), B(g), c(y, g), c(l, k)), a(200, { ok: !0, commit: { fileSha: "" }, schema: m, from: r, to: o, kind: t });
830
+ }
831
+ if (s === "POST" && i === "schema/reorder") {
832
+ const { kind: t, order: r } = await n.json();
833
+ if (!t || !Array.isArray(r)) return a(400, { error: "Missing kind or order" });
834
+ const { schema: o, header: m } = T(e);
835
+ return We(o, t, r), f(o, m), a(200, { ok: !0, commit: { fileSha: "" }, schema: o });
836
+ }
837
+ if (s === "POST" && i === "schema/set-layout") {
838
+ const { kind: t, layout: r } = await n.json();
839
+ if (!t || !Array.isArray(r)) return a(400, { error: "Missing kind or layout" });
840
+ const { schema: o, header: m } = T(e);
841
+ return Fe(o, t, r), f(o, m), a(200, { ok: !0, commit: { fileSha: "" }, schema: o });
842
+ }
843
+ if (s === "POST" && i === "collections/set-order") {
844
+ const { name: t, order: r } = await n.json();
845
+ if (!t || !Array.isArray(r)) return a(400, { error: "Missing name or order" });
846
+ const { schema: o, header: m } = T(e);
847
+ return Le(o, t, r), f(o, m), a(200, { ok: !0, commit: { fileSha: "" }, schema: o });
848
+ }
849
+ if (s === "POST" && i === "collections/set-drafts") {
850
+ const { name: t, drafts: r } = await n.json();
851
+ if (!t || typeof r != "boolean") return a(400, { error: "Missing name or drafts" });
852
+ const { schema: o, header: m } = T(e);
853
+ return Ue(o, t, r), f(o, m), a(200, { ok: !0, commit: { fileSha: "" }, schema: o });
854
+ }
855
+ if (s === "POST" && i === "schema/delete-entry") {
856
+ const { kind: t, name: r } = await n.json();
857
+ if (!t || !r) return a(400, { error: "Missing kind or name" });
858
+ const { schema: o, header: m } = T(e);
859
+ Ce(o, t, r), f(o, m);
860
+ const d = `${t}/${r}.ts`, h = F(e, d);
861
+ return h && $(h) && (L(h), B(h), c(d, h)), a(200, { ok: !0, commit: { fileSha: "" }, schema: o });
862
+ }
863
+ if (s === "POST" && i === "setup/scaffold-page") {
864
+ const { name: t, kind: r, fields: o, label: m } = await n.json();
865
+ if (!t || !r) return a(400, { error: "Missing name or kind" });
866
+ const d = o ?? [], { schema: h, header: y } = T(e);
867
+ if (ze(h, t, r, d, m), f(h, y), r !== "blocks") {
868
+ const l = `${r}/${t}.ts`, g = F(e, l);
869
+ if (g) {
870
+ const k = r === "collections" ? `export default []
871
+ ` : ee(Je(d));
872
+ W(N(g), { recursive: !0 }), L(g), R(g, k), c(l, g);
873
+ }
874
+ }
875
+ return a(200, { ok: !0 });
876
+ }
877
+ if (s === "GET" && i === "files") {
878
+ const t = _(e, "files", ".okno-tree.json");
879
+ return a(200, {
880
+ files: ke(e),
881
+ manifest: $(t) ? v(t, "utf-8") : null
882
+ });
883
+ }
884
+ if (s === "POST" && i === "files/blob") {
885
+ const t = he(decodeURIComponent(n.header("x-okno-filename") || "")), r = n.header("x-okno-dir") ? decodeURIComponent(n.header("x-okno-dir")) : "";
886
+ if (!t || t === "-") return a(400, { error: "Invalid filename" });
887
+ const o = ge(r), m = o ? `${o}/${t}` : t, d = J(e, `files/${m}`);
888
+ if (!d) return a(400, { error: "Invalid path" });
889
+ const h = await n.binary();
890
+ return h.length === 0 ? a(400, { error: "Empty body" }) : (W(N(d), { recursive: !0 }), R(d, h), a(200, { ok: !0, blobSha: "", path: `files/${m}`, filename: t }));
891
+ }
892
+ if (s === "POST" && i === "files/commit") return a(200, { ok: !0 });
893
+ if (s === "POST" && i === "files/upload") {
894
+ const { filename: t, content: r, dir: o } = await n.json();
895
+ if (!t || r == null) return a(400, { error: "Missing filename or content" });
896
+ const m = he(t);
897
+ if (!m || m === "-") return a(400, { error: "Invalid filename" });
898
+ const d = ge(o ?? ""), h = d ? `${d}/${m}` : m, y = J(e, `files/${h}`);
899
+ return y ? (W(N(y), { recursive: !0 }), R(y, Buffer.from(r, "base64")), a(200, { ok: !0, path: `files/${h}`, filename: m, commit: { fileSha: "" } })) : a(400, { error: "Invalid path" });
900
+ }
901
+ if (s === "POST" && i === "files/delete") {
902
+ const t = (await n.json())?.path;
903
+ if (!t) return a(400, { error: "Missing path" });
904
+ const r = J(e, t);
905
+ return r ? ($(r) && B(r), a(200, { ok: !0 })) : a(400, { error: "Invalid path" });
906
+ }
907
+ if (s === "POST" && i === "files/delete-many") {
908
+ const t = (await n.json())?.paths;
909
+ if (!Array.isArray(t)) return a(400, { error: "Missing paths" });
910
+ for (const r of t) {
911
+ const o = J(e, String(r));
912
+ o && $(o) && B(o);
913
+ }
914
+ return a(200, { ok: !0 });
915
+ }
916
+ if (s === "POST" && i === "files/rename") {
917
+ const { from: t, to: r } = await n.json();
918
+ if (!t || !r) return a(400, { error: "Missing from or to" });
919
+ const o = J(e, t), m = J(e, r);
920
+ return !o || !m ? a(400, { error: "Invalid path" }) : $(o) ? (W(N(m), { recursive: !0 }), ve(o, m), a(200, { ok: !0, commit: { fileSha: "" } })) : a(404, { error: "Source not found" });
921
+ }
922
+ if (s === "POST" && i === "users/save") {
923
+ const t = (await n.json())?.users;
924
+ return Array.isArray(t) ? (R(_(e, "users.json"), JSON.stringify(t, null, " ") + `
925
+ `), a(200, { ok: !0, commit: { fileSha: "" } })) : a(400, { error: "Missing users" });
926
+ }
927
+ if (s === "POST" && i === "origins/save") {
928
+ const t = (await n.json())?.origins;
929
+ if (!Array.isArray(t) || t.some((o) => typeof o != "string")) return a(400, { error: "Missing origins" });
930
+ const r = [...new Set(t.map((o) => o.trim()).filter(Boolean))];
931
+ return R(_(e, "origins.json"), JSON.stringify(r, null, " ") + `
932
+ `), a(200, { ok: !0, origins: r, commit: { fileSha: "" } });
933
+ }
934
+ return null;
935
+ } catch (t) {
936
+ return t instanceof Ve ? { status: t.status, body: { error: t.message } } : { status: 500, body: { error: t instanceof Error ? t.message : String(t) } };
937
+ }
938
+ }
939
+ export {
940
+ ae as I,
941
+ Rt as a,
942
+ xt as b,
943
+ Pt as c,
944
+ Tt as d,
945
+ At as e,
946
+ jt as f,
947
+ vt as g,
948
+ Ot as h,
949
+ St as i,
950
+ bt as j,
951
+ Mt as k,
952
+ Et as l,
953
+ lt as m,
954
+ Y as s
955
+ };