astronaut-cms 0.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -3
  3. package/dist/admin/THIRD_PARTY_LICENSES.md +7646 -0
  4. package/dist/admin/assets/assistant-DTlSNidc.js +235 -0
  5. package/dist/admin/assets/badge-BfN73-be.js +1 -0
  6. package/dist/admin/assets/changes-h1lmD7AA.js +1 -0
  7. package/dist/admin/assets/client-B4PWCmC4.js +5 -0
  8. package/dist/admin/assets/clsx-DB0hHKMi.js +1 -0
  9. package/dist/admin/assets/collapsible-item-zlnNAUdM.js +1 -0
  10. package/dist/admin/assets/collapsible-mcJ6G3X4.js +1 -0
  11. package/dist/admin/assets/collections._collection-D-rC9E9v.js +1 -0
  12. package/dist/admin/assets/collections._collection._entry-UD8hLmC1.js +52 -0
  13. package/dist/admin/assets/collections._collection.index-Cgc93hCD.js +1 -0
  14. package/dist/admin/assets/component-lookup-8lVQh8pl.js +4 -0
  15. package/dist/admin/assets/config-Pm_BHLNT.js +1 -0
  16. package/dist/admin/assets/copy-DxuErr3x.js +1 -0
  17. package/dist/admin/assets/css-BGIxQoYs.js +1 -0
  18. package/dist/admin/assets/css-DgaLhXQH.js +1 -0
  19. package/dist/admin/assets/diff-woXpYk--.js +1 -0
  20. package/dist/admin/assets/dist-DVv3ALC7.js +1 -0
  21. package/dist/admin/assets/dist-Dpyc1riS.js +1 -0
  22. package/dist/admin/assets/docx-BctAmX91.js +56 -0
  23. package/dist/admin/assets/editor-BauN0yXd.js +2 -0
  24. package/dist/admin/assets/empty-DAOUBpWb.js +1 -0
  25. package/dist/admin/assets/entry-link-DhcL6M5c.js +158 -0
  26. package/dist/admin/assets/error-banner-CNWZU5u_.js +161 -0
  27. package/dist/admin/assets/errors-DkJ5E_ak.js +1 -0
  28. package/dist/admin/assets/field-CbbZZGxO.js +41 -0
  29. package/dist/admin/assets/field-schema-CacrjSYw.js +1 -0
  30. package/dist/admin/assets/file-text-Ciz5Mr4S.js +1 -0
  31. package/dist/admin/assets/github-dark-C-LZuMrd.js +1 -0
  32. package/dist/admin/assets/github-light-EUqPIrTm.js +1 -0
  33. package/dist/admin/assets/highlighted-body-JLMTFACH-D1bycIV3.js +1 -0
  34. package/dist/admin/assets/html-CvFb5cGI.js +1 -0
  35. package/dist/admin/assets/javascript-BzbQS41l.js +1 -0
  36. package/dist/admin/assets/javascript-CpIGwZ_Y.js +1 -0
  37. package/dist/admin/assets/json-qhed-kSA.js +1 -0
  38. package/dist/admin/assets/jsx-Bz0zcwM4.js +1 -0
  39. package/dist/admin/assets/lib-CC_S4yjQ.js +21 -0
  40. package/dist/admin/assets/library-Da82FNwp.js +1 -0
  41. package/dist/admin/assets/list-skeleton-BXLP4Fak.js +1 -0
  42. package/dist/admin/assets/markdown-BYOwaDjH.js +1 -0
  43. package/dist/admin/assets/matchContext-BjW1F-Cq.js +2 -0
  44. package/dist/admin/assets/media-browser-DeKpWCUD.js +1 -0
  45. package/dist/admin/assets/media._library-DGnXJc0I.js +1 -0
  46. package/dist/admin/assets/mermaid-WFAXDIZX-CqFnahFh.js +1 -0
  47. package/dist/admin/assets/page-header-C2Uwa_yv.js +1 -0
  48. package/dist/admin/assets/pdf-BSEX-sd8.js +106 -0
  49. package/dist/admin/assets/python-gzcpVVnB.js +1 -0
  50. package/dist/admin/assets/react-CXnqG51l.js +1 -0
  51. package/dist/admin/assets/rolldown-runtime-BWaJ3C7D.js +1 -0
  52. package/dist/admin/assets/routes-Bx9rPcHA.js +1 -0
  53. package/dist/admin/assets/routes-D7tEdYGV.js +1 -0
  54. package/dist/admin/assets/save-actions-DrVgh3KH.js +32 -0
  55. package/dist/admin/assets/select-CMV39q80.js +1 -0
  56. package/dist/admin/assets/separator-C9bNKNSU.js +3 -0
  57. package/dist/admin/assets/shell-DBEiq06l.js +1 -0
  58. package/dist/admin/assets/shellscript-CLZ0U2zV.js +1 -0
  59. package/dist/admin/assets/skeleton-DTwTUSqm.js +1 -0
  60. package/dist/admin/assets/sql-CEbI0hMM.js +1 -0
  61. package/dist/admin/assets/syntax-DDPd1mQn.js +8 -0
  62. package/dist/admin/assets/toggle-B6ASf-kL.js +1 -0
  63. package/dist/admin/assets/toml-BPTmHmyx.js +1 -0
  64. package/dist/admin/assets/tsx-udAQXfEw.js +1 -0
  65. package/dist/admin/assets/typescript-bsJCZSQ-.js +1 -0
  66. package/dist/admin/assets/ui.module.css-BdAmwQeM.js +56 -0
  67. package/dist/admin/assets/use-entries-CrNqaMfa.js +1 -0
  68. package/dist/admin/assets/useSelector-Cs39W18m.js +1 -0
  69. package/dist/admin/assets/yaml-rwi0_p6S.js +1 -0
  70. package/dist/admin/assets/zwitch-Wwuax-dJ.js +1 -0
  71. package/dist/admin/bootstrap.d.ts +1 -0
  72. package/dist/admin/bootstrap.js +1 -0
  73. package/dist/admin/editor.d.ts +1065 -0
  74. package/dist/admin/editor.js +1 -0
  75. package/dist/server/THIRD_PARTY_LICENSES.md +49 -0
  76. package/dist/server/assets.d.ts +30 -0
  77. package/dist/server/assets.js +30 -0
  78. package/dist/server/chunks/anchors-DuZ1fokt.js +86 -0
  79. package/dist/server/chunks/auth-DJP9ryVd.js +44 -0
  80. package/dist/server/chunks/cms-markers-CUqrOnfA.js +78 -0
  81. package/dist/server/chunks/component-lookup-DAFg_Qg8.js +128 -0
  82. package/dist/server/chunks/config-BsOYly9a.d.ts +1210 -0
  83. package/dist/server/chunks/digest-tkKu_Wj5.js +753 -0
  84. package/dist/server/chunks/entry-checks-3SxhoHwH.js +608 -0
  85. package/dist/server/chunks/field-schema-CfdN75jT.js +48 -0
  86. package/dist/server/chunks/http-BnsNh57m.d.ts +35 -0
  87. package/dist/server/chunks/i18n-BPmx7ESy.d.ts +15 -0
  88. package/dist/server/chunks/index-CYbkNvu5.d.ts +22 -0
  89. package/dist/server/chunks/media-BhqUVVYY.js +223 -0
  90. package/dist/server/chunks/paths-CEW9fvg8.js +17 -0
  91. package/dist/server/chunks/paths-Dztx2eUw.js +13 -0
  92. package/dist/server/chunks/types-DkkewFTT.js +418 -0
  93. package/dist/server/chunks/types-Dkx4Xovf.d.ts +359 -0
  94. package/dist/server/chunks/types-Jew_-Qpp.d.ts +273 -0
  95. package/dist/server/chunks/user-config-CqNK-Ebs.js +292 -0
  96. package/dist/server/chunks/xml-D8qPILJU.js +81 -0
  97. package/dist/server/config.d.ts +3 -0
  98. package/dist/server/config.js +22 -0
  99. package/dist/server/content.d.ts +58 -0
  100. package/dist/server/content.js +83 -0
  101. package/dist/server/endpoint.d.ts +16 -0
  102. package/dist/server/endpoint.js +2726 -0
  103. package/dist/server/integration.d.ts +7 -0
  104. package/dist/server/integration.js +1187 -0
  105. package/dist/server/internal.d.ts +100 -0
  106. package/dist/server/internal.js +30 -0
  107. package/dist/server/server-local.d.ts +453 -0
  108. package/dist/server/server-local.js +336 -0
  109. package/dist/styles/THIRD_PARTY_LICENSES.md +193 -0
  110. package/dist/styles/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  111. package/dist/styles/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  112. package/dist/styles/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  113. package/dist/styles/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  114. package/dist/styles/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  115. package/dist/styles/styles.css +3 -0
  116. package/package.json +151 -5
  117. package/src/astro/Image.astro +28 -0
  118. package/src/astro/Video.astro +44 -0
  119. package/src/astro/admin.astro +137 -0
  120. package/src/astro/licenses.ts +5 -0
@@ -0,0 +1,1187 @@
1
+ import { a as API_PATTERN, c as GITLAB_CLIENT_SECRET_ENV, d as SESSION_SECRET_ENV, l as LICENSES_PATH, n as API_BASE, r as API_CALLBACK, s as GITHUB_CLIENT_SECRET_ENV } from "./chunks/auth-DJP9ryVd.js";
2
+ import { a as gatewayAddress, n as xmlList, o as gatewayEnv, r as parseRepo, t as parseXml } from "./chunks/xml-D8qPILJU.js";
3
+ import { S as conformTrailingSlash, h as megabytes, i as S3_SESSION_TOKEN_ENV, l as isLibraryFile, m as mediaPath, n as S3_ACCESS_KEY_ID_ENV, r as S3_SECRET_ACCESS_KEY_ENV, u as libraryDirectories, v as repoOnlyRefusal, w as trimSlashes, y as s3BaseUrl } from "./chunks/media-BhqUVVYY.js";
4
+ import { _ as getFileExtension, c as globEntry, n as DATA_FORMATS, r as DEFAULT_SORT, s as findSingleton, u as globRoots, v as parseContent, y as parseMultiEntryFile } from "./chunks/types-DkkewFTT.js";
5
+ import { n as componentEntries } from "./chunks/component-lookup-DAFg_Qg8.js";
6
+ import { i as zodToFieldSchema, t as processUserConfig } from "./chunks/user-config-CqNK-Ebs.js";
7
+ import { d as diagnostic, f as formatDiagnostic, l as objectShape } from "./chunks/field-schema-CfdN75jT.js";
8
+ import { a as localizedMarker, n as fileMarker, r as libraryImage, s as repoImageMarker } from "./chunks/cms-markers-CUqrOnfA.js";
9
+ import { a as libraryPathError, c as validateBody, f as errorMessage, i as collectionPatchSchema, n as collectionDataSchema, t as checkEntry, u as isAsset } from "./chunks/entry-checks-3SxhoHwH.js";
10
+ import { n as isWithin } from "./chunks/paths-Dztx2eUw.js";
11
+ import { n as stripMediaPrefix } from "./chunks/paths-CEW9fvg8.js";
12
+ import { defineCollection, defineComponent } from "./config.js";
13
+ import { existsSync, globSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { basename, extname, join, relative, resolve } from "pathe";
16
+ import { z } from "zod";
17
+ import { createRequestFromNodeRequest, writeResponse } from "astro/app/node";
18
+ import { createRunnableDevEnvironment, resolveConfig } from "vite";
19
+ import { envField } from "astro/config";
20
+ /** The same formats as a list, for the library glob's `{png,jpg,…}` brace pattern. */
21
+ var ASTRO_IMAGE_FORMATS = Object.keys({
22
+ png: true,
23
+ apng: true,
24
+ jpg: true,
25
+ jpeg: true,
26
+ webp: true,
27
+ avif: true,
28
+ gif: true,
29
+ svg: true,
30
+ tiff: true
31
+ });
32
+ // src/integration/dev-api.ts
33
+ /**
34
+ * The CMS API served from Node by `astro dev` itself, for local storage.
35
+ *
36
+ * An adapter may render on demand in a runtime other than Node, such as workerd
37
+ * for `@astrojs/cloudflare`, where `node:fs` cannot see the project. The working
38
+ * tree is only reachable from Node, so the API runs in a Node environment of its
39
+ * own and answers before the adapter's handler sees the request. Every adapter
40
+ * takes this path, so the demo exercises the one a Workers site runs.
41
+ */
42
+ /** The Vite environment the dev API runs in. */
43
+ var DEV_API_ENVIRONMENT = "astronaut_cms";
44
+ var devApiEnvironment = {
45
+ consumer: "server",
46
+ resolve: { noExternal: ["astronaut-cms"] },
47
+ dev: { createEnvironment: (name, config) => createRunnableDevEnvironment(name, config) }
48
+ };
49
+ /** Answers every request below `apiPath` from the dev API environment. */
50
+ function serveDevApi(server, apiPath) {
51
+ const environment = server.environments[DEV_API_ENVIRONMENT];
52
+ server.middlewares.use((req, res, next) => {
53
+ const path = req.url?.split("?")[0] ?? "";
54
+ if (path !== apiPath && !path.startsWith(`${apiPath}/`)) return next();
55
+ environment.runner.import("astronaut-cms/endpoint").then(({ handle }) => handle(createRequestFromNodeRequest(req), req.socket.remoteAddress)).then((response) => writeResponse(response, res)).catch(next);
56
+ });
57
+ }
58
+ // src/integration/component-codegen.ts
59
+ /** The module a site imports its MDX components and their props from. */
60
+ var COMPONENTS_MODULE = "astronaut-cms:components";
61
+ var quote = (value) => JSON.stringify(value);
62
+ function wrapperModule(name, file) {
63
+ return `---
64
+ import Component from ${quote(file)};
65
+ import { resolveProps } from "./props.ts";
66
+
67
+ const props = await resolveProps(${quote(name)}, Astro.props);
68
+ ---
69
+
70
+ {Astro.slots.has("default") ? <Component {...props}><slot /></Component> : <Component {...props} />}
71
+ `;
72
+ }
73
+ /**
74
+ * The modules behind {@link COMPONENTS_MODULE}, by file name: a wrapper per
75
+ * component that applies its schema before rendering it, and the index that
76
+ * exports them, each by name and all together as `mdxComponents`.
77
+ */
78
+ function componentModules(configPath, files) {
79
+ const names = Object.keys(files);
80
+ const modules = { "index.ts": [
81
+ ...names.map((name) => `import ${name} from "./${name}.astro";`),
82
+ `export { ${names.join(", ")} };`,
83
+ `export const mdxComponents = { ${names.join(", ")} };\n`
84
+ ].join("\n") };
85
+ if (!configPath || names.length === 0) return modules;
86
+ modules["props.ts"] = `\
87
+ import { components } from ${quote(configPath)};
88
+ import { resolveImage } from "astronaut-cms/assets";
89
+ import { propsResolver } from "astronaut-cms/internal";
90
+
91
+ export const resolveProps = propsResolver(components, resolveImage);
92
+ `;
93
+ for (const [name, file] of Object.entries(files)) modules[`${name}.astro`] = wrapperModule(name, file);
94
+ return modules;
95
+ }
96
+ /**
97
+ * Writes `modules` into `dir` and removes any other file there. A file whose
98
+ * content is unchanged is left alone, so the dev server reloads nothing.
99
+ */
100
+ function writeModules(dir, modules) {
101
+ mkdirSync(dir, { recursive: true });
102
+ for (const file of readdirSync(dir)) if (!Object.hasOwn(modules, file)) rmSync(join(dir, file));
103
+ for (const [file, content] of Object.entries(modules)) {
104
+ const path = join(dir, file);
105
+ if (!existsSync(path) || readFileSync(path, "utf-8") !== content) writeFileSync(path, content);
106
+ }
107
+ }
108
+ /**
109
+ * The declaration of {@link COMPONENTS_MODULE}, read off the type of the
110
+ * config's `components` export, which `typesDir` holds a relative import of.
111
+ */
112
+ function componentTypes(typesDir, configPath, names) {
113
+ const config = configPath && relative(typesDir, configPath);
114
+ return `declare module "${COMPONENTS_MODULE}" {
115
+ type Infer<Side extends "input" | "output"> = import("astronaut-cms/internal").InferComponentProps<${config ? `typeof import(${quote(config.startsWith(".") ? config : `./${config}`)}).components` : "{}"}, Side>;
116
+ type Input = Infer<"input">;
117
+ // As astro declares any \`.astro\` module, taking the props MDX writes and any attribute besides.
118
+ type Wrapper<Name extends keyof Input> = (props: Input[Name] & Record<string, unknown>) => any;
119
+
120
+ /** The props each component renders with, every default of its schema applied and every image resolved. */
121
+ export type ComponentProps = Infer<"output">;
122
+
123
+ /** Every component by name, for \`<Content components={mdxComponents} />\`. */
124
+ export const mdxComponents: { ${names.map((name) => `${name}: Wrapper<${quote(name)}>`).join("; ")} };
125
+ ${names.map((name) => ` export const ${name}: Wrapper<${quote(name)}>;\n`).join("")}}
126
+ `;
127
+ }
128
+ // src/integration/vite-plugin.ts
129
+ /**
130
+ * Stands the Node stubs in for `astronaut-cms/editor` wherever a module runs on
131
+ * the server: the integration loading `cms.config`, and the component wrappers
132
+ * importing it as the site renders. The admin's editor primitives would touch
133
+ * the DOM as they load there.
134
+ */
135
+ function editorStubPlugin() {
136
+ return {
137
+ name: "astronaut-cms:editor-stub",
138
+ enforce: "pre",
139
+ resolveId(id, importer) {
140
+ if (id !== "astronaut-cms/editor" || this.environment.config.consumer !== "server") return;
141
+ return this.resolve("astronaut-cms/internal", importer, { skipSelf: true });
142
+ }
143
+ };
144
+ }
145
+ function cmsVitePlugin(options) {
146
+ const { clientConfig, serverConfig, userConfigPath } = options;
147
+ const virtualModules = {
148
+ "virtual:astronaut-cms/server": `\
149
+ export const client = ${JSON.stringify(clientConfig)};
150
+ export const server = ${JSON.stringify(serverConfig)};
151
+ export const components = ${JSON.stringify(options.components)};`,
152
+ "virtual:astronaut-cms/local-storage": ({ devApi }) => generateLocalStorageModule(options, devApi),
153
+ "virtual:astronaut-cms/content": ({ watch }) => generateContentModule(clientConfig, options.rootDir, watch),
154
+ "virtual:astronaut-cms/user-config": generateUserConfigModule(userConfigPath, clientConfig),
155
+ "virtual:astronaut-cms/assets": `export const media = ${JSON.stringify(assetsMedia(clientConfig.media))};\n${generateAssetsModule(clientConfig.media)}`
156
+ };
157
+ return [
158
+ editorStubPlugin(),
159
+ {
160
+ name: "astronaut-cms:virtual-modules",
161
+ enforce: "pre",
162
+ resolveId(id) {
163
+ if (id === "astronaut-cms:components") return options.componentsEntry;
164
+ return id in virtualModules ? "\0" + id : void 0;
165
+ },
166
+ load(id) {
167
+ const module = id.startsWith("\0") ? virtualModules[id.slice(1)] : void 0;
168
+ if (typeof module !== "function") return module;
169
+ return module({
170
+ devApi: this.environment.name === DEV_API_ENVIRONMENT,
171
+ watch: (path) => this.addWatchFile(path)
172
+ });
173
+ },
174
+ onLog(_level, log) {
175
+ return !(log.code === "INEFFECTIVE_DYNAMIC_IMPORT" && log.ids?.includes("\0virtual:astronaut-cms/assets"));
176
+ }
177
+ },
178
+ {
179
+ name: "astronaut-cms:optimize-deps",
180
+ configEnvironment: (name) => ({ optimizeDeps: {
181
+ exclude: ["astronaut-cms/licenses"],
182
+ ...name !== "client" && { include: [
183
+ "astronaut-cms/assets",
184
+ "astronaut-cms/endpoint",
185
+ "astronaut-cms/internal"
186
+ ] }
187
+ } })
188
+ }
189
+ ];
190
+ }
191
+ /** What the site's resolver reads of the libraries, and so all a page that resolves an asset ships. */
192
+ function assetsMedia({ repo, s3 }) {
193
+ return {
194
+ repo: { directory: repo.directory },
195
+ s3: s3 && {
196
+ publicUrl: s3.publicUrl,
197
+ ...s3.directory != null && { directory: s3.directory }
198
+ }
199
+ };
200
+ }
201
+ function generateLocalStorageModule(options, devApi) {
202
+ return options.serverConfig.storage.type === "local" && devApi ? `export { LocalStorage } from "astronaut-cms/server-local";` : `export const LocalStorage = null;`;
203
+ }
204
+ function generateAssetsModule(media) {
205
+ const bases = libraryDirectories(media).map((dir) => join("/", dir));
206
+ return `\
207
+ export const images = import.meta.glob(${JSON.stringify(bases.map((base) => `${base}/**/*.{${ASTRO_IMAGE_FORMATS.join(",")}}`))}, { import: "default" });
208
+ export const files = import.meta.glob(${JSON.stringify(bases.map((base) => `${base}/**/*`))}, { query: "?url&no-inline", import: "default" });`;
209
+ }
210
+ function generateContentModule({ collections, contentI18n }, rootDir, watch) {
211
+ const sorts = {};
212
+ const fileOrder = {};
213
+ for (const { name, sort, loaderFileName } of Object.values(collections)) {
214
+ if (sort.by !== "id") sorts[name] = sort;
215
+ if (sort.by !== "file" || !loaderFileName) continue;
216
+ const path = join(rootDir, loaderFileName);
217
+ watch(path);
218
+ fileOrder[name] = existsSync(path) ? [...parseMultiEntryFile(readFileSync(path, "utf-8"), getFileExtension(path)).entries.keys()] : [];
219
+ }
220
+ return `\
221
+ export const sorts = ${JSON.stringify(sorts)};
222
+ export const fileOrder = ${JSON.stringify(fileOrder)};
223
+ export const contentI18n = ${JSON.stringify(contentI18n)};`;
224
+ }
225
+ function generateUserConfigModule(configPath, { contentI18n }) {
226
+ return `\
227
+ ${configPath ? `import * as config from ${JSON.stringify(configPath)};` : "const config = {};"}
228
+ import { processUserModule } from "astronaut-cms/internal";
229
+ export const { components, collectionIcons, links } = processUserModule(config, ${JSON.stringify(contentI18n)});`;
230
+ }
231
+ // src/integration/dev-middleware.ts
232
+ var SUPPRESS_WINDOW_MS = 5e3;
233
+ /**
234
+ * Requests that write, and therefore arm the window.
235
+ *
236
+ * Every CMS operation is a POST, so the method says nothing; the admin marks the
237
+ * ones that change content (see `WRITE_HEADER`), and an upload is a write by its
238
+ * path alone.
239
+ */
240
+ function isWrite(req) {
241
+ return req.headers["x-astronaut-cms-write"] != null || req.url?.includes(`/_astronaut-cms/api/upload`) === true;
242
+ }
243
+ /**
244
+ * Drops full-reload broadcasts on one environment while `isSuppressed()` holds,
245
+ * and leaves every other message alone.
246
+ *
247
+ * A reload is announced from more places than a single hook can see: Astro's
248
+ * `astro:hmr-reload` plugin, its `invalidateDataStore` (which fires when the
249
+ * content layer rewrites `.astro/data-store.json`, not from a `hotUpdate` at
250
+ * all), and any other plugin watching the files the CMS writes. Intercepting
251
+ * the message they all end in covers them together, and keeps the module
252
+ * invalidation each of them does on the way.
253
+ */
254
+ function suppressReloads(channel, isSuppressed) {
255
+ const send = channel.send.bind(channel);
256
+ channel.send = (...args) => {
257
+ const payload = args[0];
258
+ if (typeof payload === "object" && payload?.type === "full-reload" && isSuppressed()) return;
259
+ send(...args);
260
+ };
261
+ }
262
+ /**
263
+ * Every environment is patched, not just the client. Vite announces reloads per
264
+ * environment, and the SSR one is a module runner: a `full-reload` there makes
265
+ * it drop its evaluated modules and re-import its entrypoints, which fails on
266
+ * Astro's own `astro:server-app.js` and leaves the dev server unable to render.
267
+ *
268
+ * `apiPath` is where the dev server answers the API itself, or null when the
269
+ * adapter's route does.
270
+ */
271
+ function cmsDevPlugin(apiPath) {
272
+ let suppressReloadUntil = 0;
273
+ return {
274
+ name: "astronaut-cms:dev",
275
+ enforce: "post",
276
+ config: () => apiPath ? { environments: { [DEV_API_ENVIRONMENT]: devApiEnvironment } } : void 0,
277
+ configureServer(server) {
278
+ server.middlewares.use((req, res, next) => {
279
+ const arm = () => suppressReloadUntil = Date.now() + SUPPRESS_WINDOW_MS;
280
+ if (isWrite(req)) {
281
+ arm();
282
+ res.once("close", arm);
283
+ }
284
+ next();
285
+ });
286
+ if (apiPath) serveDevApi(server, apiPath);
287
+ for (const environment of Object.values(server.environments)) suppressReloads(environment.hot, () => Date.now() < suppressReloadUntil);
288
+ }
289
+ };
290
+ }
291
+ // src/integration/load-config.ts
292
+ /**
293
+ * The user's two config files, read in Node so the integration can see a live
294
+ * `content.config.ts` and `cms.config.ts` without an Astro build around them.
295
+ * Both lower to fully serializable manifests.
296
+ *
297
+ * They are loaded through Vite, as astro loads its own config, so an import
298
+ * resolves exactly as it does in the site: tsconfig `paths` included.
299
+ */
300
+ var ALIASES = [/^astro:content$/, /^astro\/loaders$/].map((find) => ({
301
+ find,
302
+ replacement: "astronaut-cms/internal"
303
+ }));
304
+ var RUNNER = "astronaut_cms_config";
305
+ /**
306
+ * Runs `load` against one throwaway Vite runner, so the configs share one
307
+ * resolved config and the modules they both import are evaluated once.
308
+ *
309
+ * A config that fails to load leaves the admin without collections and the
310
+ * build without the assets they reference, so the error is the integration's
311
+ * to raise rather than to degrade around.
312
+ */
313
+ async function withConfigImport(rootDir, load) {
314
+ const config = await resolveConfig({
315
+ configFile: false,
316
+ envDir: false,
317
+ root: rootDir,
318
+ logLevel: "error",
319
+ resolve: {
320
+ alias: ALIASES,
321
+ tsconfigPaths: true
322
+ },
323
+ plugins: [editorStubPlugin()],
324
+ oxc: { jsx: { runtime: "automatic" } },
325
+ environments: { [RUNNER]: {
326
+ consumer: "server",
327
+ dev: { moduleRunnerTransform: true },
328
+ resolve: {
329
+ external: true,
330
+ mainFields: [],
331
+ conditions: ["node"]
332
+ }
333
+ } }
334
+ }, "serve");
335
+ const environment = createRunnableDevEnvironment(RUNNER, config, { hot: false });
336
+ await environment.init();
337
+ await using cleanup = new AsyncDisposableStack();
338
+ cleanup.defer(() => environment.close());
339
+ return await load(async (path) => {
340
+ try {
341
+ return await environment.runner.import(path);
342
+ } catch (error) {
343
+ throw new Error(`astronaut-cms: failed to load ${path}: ${errorMessage(error)}`, { cause: error });
344
+ }
345
+ }, async (id, importer) => (await environment.pluginContainer.resolveId(id, importer))?.id ?? null);
346
+ }
347
+ var SCHEMA_HELPERS = { image: repoImageMarker };
348
+ /**
349
+ * A loader path as the CMS addresses entries, relative to the project root.
350
+ * astro accepts `./src/x`, `src/x`, an absolute path and a file URL alike, and
351
+ * the storage backends compare paths as plain strings.
352
+ */
353
+ function rootRelative(rootDir, path) {
354
+ if (path == null) return null;
355
+ return relative(rootDir, resolve(rootDir, typeof path === "string" ? path : fileURLToPath(path)));
356
+ }
357
+ /**
358
+ * Loads the user's content config and lowers every collection into a fully
359
+ * serializable {@link CollectionManifest}, each in astro's own id order until
360
+ * `cms.config` says otherwise.
361
+ */
362
+ async function loadCollections(load, rootDir, contentConfigPath, i18n, warn) {
363
+ const mod = await load(contentConfigPath);
364
+ const manifest = {};
365
+ for (const [name, collection] of Object.entries(mod.collections ?? {})) {
366
+ const rawSchema = typeof collection.schema === "function" ? collection.schema(SCHEMA_HELPERS) : collection.schema;
367
+ const loader = collection.loader;
368
+ if (loader?.__cmsFileName != null) {
369
+ const format = extname(loader.__cmsFileName).slice(1);
370
+ if (loader.__cmsCustomParser || !DATA_FORMATS.some((supported) => supported === format)) throw new Error(`Collection "${name}" uses file("${loader.__cmsFileName}") with a custom parser or unsupported format. The CMS can edit only JSON, YAML, and TOML file collections without a custom parser.`);
371
+ }
372
+ if (loader?.__cmsCustomId) warn(`Collection "${name}" passes its own generateId to glob(), which the CMS cannot mirror. The admin names its entries by astro's default ids, so a reference it writes may not resolve.`);
373
+ const source = {
374
+ loaderType: loader?.__cmsFileName != null ? "file" : "glob",
375
+ loaderPattern: loader?.__cmsPattern ?? null,
376
+ loaderBase: rootRelative(rootDir, loader?.__cmsBase)
377
+ };
378
+ manifest[name] = {
379
+ name,
380
+ type: collection.type === "data" ? "data" : "content",
381
+ schema: rawSchema == null ? null : zodToFieldSchema(rawSchema, i18n),
382
+ ...source,
383
+ loaderFileName: rootRelative(rootDir, loader?.__cmsFileName),
384
+ sort: DEFAULT_SORT,
385
+ singleton: findSingleton(source, i18n)
386
+ };
387
+ }
388
+ return manifest;
389
+ }
390
+ var SORTABLE_TYPES = /* @__PURE__ */ new Set([
391
+ "string",
392
+ "number",
393
+ "boolean",
394
+ "date",
395
+ "enum",
396
+ "literal",
397
+ "reference"
398
+ ]);
399
+ /**
400
+ * The content config's collections with the options `cms.config` gives them.
401
+ * An option naming no collection, a file order for entries that are separate
402
+ * files, or a field order by no comparable field, is a mistake the site would
403
+ * otherwise never notice.
404
+ */
405
+ function withOptions(manifest, options) {
406
+ const resolved = { ...manifest };
407
+ for (const [name, { sort, label, description }] of Object.entries(options)) {
408
+ const collection = resolved[name];
409
+ if (!collection) throw new Error(`cms.config collections: "${name}" is not a collection of the content config.`);
410
+ if (sort?.by === "file" && collection.loaderType !== "file") throw new Error(`cms.config collections: "${name}" cannot sort by file, which needs a file() collection. The entries of a glob() collection are separate files.`);
411
+ if (sort?.by === "field" && !SORTABLE_TYPES.has(objectShape(collection.schema)?.[sort.field]?.type)) throw new Error(`cms.config collections: "${name}" cannot sort by "${sort.field}", which needs a top-level field of type ${[...SORTABLE_TYPES].join(", ")}.`);
412
+ resolved[name] = {
413
+ ...collection,
414
+ sort: sort ?? collection.sort,
415
+ label,
416
+ description
417
+ };
418
+ }
419
+ return resolved;
420
+ }
421
+ /**
422
+ * Both configs, each empty when the site has none. The components are lowered
423
+ * into the same {@link ComponentManifest} the admin bundle builds for itself at
424
+ * runtime; the admin has to do its own pass because `icon` and `editor` are live
425
+ * React refs, and a build wants nothing but the lowered prop schemas. What the
426
+ * CMS can load but not mirror is reported through `warn`.
427
+ */
428
+ function loadConfigs(rootDir, paths, i18n, warn) {
429
+ return withConfigImport(rootDir, async (load, resolve) => {
430
+ const [collections, cms] = await Promise.all([paths.content ? loadCollections(load, rootDir, paths.content, i18n, warn) : {}, paths.cms ? load(paths.cms) : void 0]);
431
+ const manifest = withOptions(collections, cms?.collections ?? {});
432
+ return {
433
+ collections: manifest,
434
+ components: processUserConfig(cms?.components, i18n),
435
+ componentFiles: paths.cms ? await resolveComponents(cms?.components ?? {}, manifest, paths.cms, resolve) : {}
436
+ };
437
+ });
438
+ }
439
+ /**
440
+ * Each component's file, resolved as an import of `cms.config` itself, so the
441
+ * site's aliases apply. A missing one fails here rather than in the build of
442
+ * the wrapper that imports it, and so does a component that points editors to
443
+ * a collection the content config lacks, which would link nowhere.
444
+ */
445
+ async function resolveComponents(components, collections, configPath, resolve) {
446
+ const unique = new Map(componentEntries(components));
447
+ const files = await Promise.all(unique.entries().map(async ([name, { component, collections: targets = [] }]) => {
448
+ const unknown = targets.find((collection) => !Object.hasOwn(collections, collection));
449
+ if (unknown !== void 0) throw new Error(`cms.config components: ${name} lists "${unknown}", which is not a collection of the content config.`);
450
+ const file = component ? await resolve(component, configPath) : null;
451
+ if (!file || !existsSync(file)) throw new Error(`cms.config components: ${name} renders with ${component ? `"${component}", which names no file` : "no component"}. Set its \`component\` to the .astro file, such as "@/components/${name}.astro".`);
452
+ return [name, file];
453
+ }));
454
+ return Object.fromEntries(files);
455
+ }
456
+ // src/integration/resolve-config.ts
457
+ var DEFAULT_MOUNT_POINT = "/admin";
458
+ var DEFAULT_MEDIA_DIRECTORY = "src/assets";
459
+ /** The URL (and therefore content directory) segment of an astro locale entry. */
460
+ function localeSegment(locale) {
461
+ return typeof locale === "string" ? locale : locale.path;
462
+ }
463
+ /**
464
+ * Astro's `defaultLocale` names a *code*, while `locales` are addressed by their
465
+ * `path`. For `{ path: "english", codes: ["en"] }` the two differ.
466
+ * Entry ids are built from paths, so the default is mapped into the same
467
+ * namespace before it is used as one.
468
+ */
469
+ function localePath(code, astroI18n) {
470
+ for (const locale of astroI18n?.locales ?? []) if (typeof locale !== "string" && locale.codes.includes(code)) return locale.path;
471
+ return code;
472
+ }
473
+ function resolveContentI18n(config, astroI18n) {
474
+ if (config.i18n === false) return null;
475
+ const locales = config.i18n?.locales ?? astroI18n?.locales.map(localeSegment);
476
+ if (!locales?.length) return null;
477
+ const inherited = astroI18n?.defaultLocale && localePath(astroI18n.defaultLocale, astroI18n);
478
+ const defaultLocale = config.i18n?.defaultLocale ?? (inherited && locales.includes(inherited) ? inherited : locales[0]);
479
+ if (!defaultLocale) return null;
480
+ if (!locales.includes(defaultLocale)) throw new Error(`Content default locale "${defaultLocale}" is not in the configured locales.`);
481
+ return {
482
+ locales,
483
+ defaultLocale
484
+ };
485
+ }
486
+ var storageType = (config) => config.storage?.type ?? "local";
487
+ function resolveClientConfig(config, astroI18n, s3DevDirectory, collections) {
488
+ const type = storageType(config);
489
+ return {
490
+ mountPoint: config.mountPoint ?? DEFAULT_MOUNT_POINT,
491
+ storageType: type,
492
+ media: resolveClientMedia(config, s3DevDirectory),
493
+ locale: config.locale ?? "en",
494
+ contentI18n: resolveContentI18n(config, astroI18n),
495
+ previewUrl: config.previewUrl,
496
+ capabilities: {
497
+ publish: type !== "local",
498
+ update: type !== "local"
499
+ },
500
+ ...config.ai?.enabled && config.ai.models?.length && { ai: {
501
+ models: config.ai.models,
502
+ maxSteps: maxSteps(config),
503
+ ...isByok(config) && { byok: byokEndpoint(config.ai.gateway) }
504
+ } },
505
+ ...config.webmcp?.enabled && { webmcp: { originTrialToken: config.webmcp.originTrialToken } },
506
+ collections
507
+ };
508
+ }
509
+ /**
510
+ * Enough headroom for a print-quality master, low enough that a phone original
511
+ * does not enter the library at 12 MP. The quality ladder is what makes
512
+ * `maxFileSize` a threshold rather than a promise.
513
+ */
514
+ var DEFAULT_IMAGE_OPTIMIZATION = {
515
+ maxWidth: 2048,
516
+ maxHeight: 2048,
517
+ maxFileSize: 8388608,
518
+ format: null,
519
+ quality: .92,
520
+ minQuality: .5
521
+ };
522
+ /**
523
+ * What every library resolves alike. A library whose uploads the server holds
524
+ * in memory gets a default size limit.
525
+ */
526
+ function resolveLibrary(library, throughServer) {
527
+ const optimize = library?.optimizeImages;
528
+ return {
529
+ label: library?.label ?? null,
530
+ extensions: library?.allowedExtensions?.map((ext) => ext.toLowerCase()) ?? null,
531
+ minFileSize: library?.minFileSize ?? null,
532
+ maxFileSize: library?.maxFileSize ?? (throughServer ? 104857600 : null),
533
+ imageOptimization: optimize === false ? null : {
534
+ ...DEFAULT_IMAGE_OPTIMIZATION,
535
+ ...optimize
536
+ }
537
+ };
538
+ }
539
+ /**
540
+ * Enough for the admin to address a file, and nothing an object store could be
541
+ * reached with. `s3DevDirectory` only says where the store's bytes are during a
542
+ * dev run: the reference format is the store's either way, so it cannot differ
543
+ * between a dev run and the build.
544
+ */
545
+ function resolveClientMedia(config, s3DevDirectory) {
546
+ const { repo, s3 } = config.media ?? {};
547
+ return {
548
+ repo: {
549
+ ...resolveLibrary(repo, true),
550
+ directory: repo?.directory ?? DEFAULT_MEDIA_DIRECTORY
551
+ },
552
+ s3: s3 ? {
553
+ ...resolveLibrary(s3, s3DevDirectory != null),
554
+ publicUrl: trimSlashes(s3.publicUrl),
555
+ storeOrigin: s3BaseUrl(storeS3(s3)).origin,
556
+ ...s3DevDirectory != null && { directory: s3DevDirectory }
557
+ } : null
558
+ };
559
+ }
560
+ /**
561
+ * Server-only, imported by the injected route alone, so a bucket or endpoint
562
+ * never reaches the client.
563
+ */
564
+ function resolveMediaServer(config) {
565
+ const s3 = config.media?.s3;
566
+ if (!s3) return null;
567
+ return {
568
+ publicUrl: trimSlashes(s3.publicUrl),
569
+ prefix: s3.prefix ? `${trimSlashes(s3.prefix)}/` : "",
570
+ s3: storeS3(s3)
571
+ };
572
+ }
573
+ /** The R2 preset is the S3 API with Cloudflare's endpoint filled in. */
574
+ function storeS3(s3) {
575
+ if (s3.provider === "r2") return {
576
+ endpoint: `https://${s3.accountId}.r2.cloudflarestorage.com`,
577
+ pathStyle: true,
578
+ bucket: s3.bucket
579
+ };
580
+ return {
581
+ endpoint: trimSlashes(s3.endpoint),
582
+ region: s3.region,
583
+ pathStyle: s3.forcePathStyle ?? false,
584
+ bucket: s3.bucket
585
+ };
586
+ }
587
+ function resolveServerStorage(config, rootDir) {
588
+ const storage = config.storage;
589
+ if (storage?.type === "github") {
590
+ const { owner, repo } = parseRepo(storage.repo);
591
+ return {
592
+ type: "github",
593
+ owner,
594
+ repo,
595
+ branch: storage.branch ?? "main",
596
+ clientId: storage.clientId,
597
+ publishMode: storage.publishMode ?? "direct"
598
+ };
599
+ }
600
+ if (storage?.type === "gitlab") return {
601
+ type: "gitlab",
602
+ project: storage.project,
603
+ branch: storage.branch ?? "main",
604
+ instanceUrl: storage.instanceUrl ?? "https://gitlab.com",
605
+ clientId: storage.clientId,
606
+ scopes: storage.scopes ?? ["api"],
607
+ publishMode: storage.publishMode ?? "direct"
608
+ };
609
+ return {
610
+ type: "local",
611
+ rootDir
612
+ };
613
+ }
614
+ function resolveServerConfig(config, rootDir, media, trailingSlash) {
615
+ return {
616
+ trailingSlash,
617
+ storage: resolveServerStorage(config, rootDir),
618
+ media,
619
+ ai: resolveAiServer(config)
620
+ };
621
+ }
622
+ /** Defaults for {@link AiLimits}: generous for an editor, bounded for a bill. */
623
+ var DEFAULT_AI_LIMITS = {
624
+ maxRequestBytes: 1048576,
625
+ maxOutputTokens: 8192
626
+ };
627
+ var maxSteps = (config) => config.ai?.maxSteps ?? 24;
628
+ /** Where a browser holding the editor's own key sends inference, checked to be one by `validateAi`. */
629
+ function byokEndpoint(gateway) {
630
+ const address = gatewayAddress(gateway);
631
+ return address ? {
632
+ baseUrl: address.baseUrl,
633
+ headers: address.headers
634
+ } : void 0;
635
+ }
636
+ /** Whether the editor supplies the credential rather than the deployment. */
637
+ function isByok(config) {
638
+ return config.ai?.credentials === "byok";
639
+ }
640
+ /**
641
+ * Null when there is no relay to configure, which `byok` is one reason for: the
642
+ * route then has no gateway to reach and refuses, because inference never
643
+ * touches this deployment.
644
+ */
645
+ function resolveAiServer(config) {
646
+ if (!config.ai?.enabled || !config.ai.gateway || isByok(config)) return null;
647
+ return {
648
+ gateway: config.ai.gateway,
649
+ maxSteps: maxSteps(config),
650
+ limits: {
651
+ ...DEFAULT_AI_LIMITS,
652
+ ...config.ai.limits
653
+ }
654
+ };
655
+ }
656
+ // src/integration/env-schema.ts
657
+ /**
658
+ * The secrets the injected routes read, declared through `astro:env` so the site
659
+ * types them without declaring anything itself. Every one is optional: a host
660
+ * that injects secrets only at runtime (Workers, Netlify, Vercel) has none at
661
+ * build time, so a build with `validateSecrets` must not demand them, and the
662
+ * route names a missing one on the request that needs it.
663
+ */
664
+ function secretsSchema(config) {
665
+ const names = [];
666
+ const provider = config.storage?.type;
667
+ if (provider === "github" || provider === "gitlab") names.push(provider === "github" ? GITHUB_CLIENT_SECRET_ENV : GITLAB_CLIENT_SECRET_ENV, SESSION_SECRET_ENV);
668
+ if (config.media?.s3) names.push(S3_ACCESS_KEY_ID_ENV, S3_SECRET_ACCESS_KEY_ENV, S3_SESSION_TOKEN_ENV);
669
+ if (config.ai?.enabled && config.ai.gateway && !isByok(config)) names.push(...gatewayEnv(config.ai.gateway));
670
+ return Object.fromEntries(names.map((name) => [name, envField.string({
671
+ context: "server",
672
+ access: "secret",
673
+ optional: true
674
+ })]));
675
+ }
676
+ // src/integration/content-files.ts
677
+ /** Absolute paths of the files matching `patterns`, directories excluded. */
678
+ function globFiles(cwd, patterns) {
679
+ if (patterns.length === 0) return [];
680
+ return globSync(patterns, {
681
+ cwd,
682
+ withFileTypes: true
683
+ }).filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name));
684
+ }
685
+ /**
686
+ * Project-relative paths of the files a glob collection's loader loads in a
687
+ * format the CMS reads, exactly the ones the storage listing reports. Only the
688
+ * static prefix of each pattern is walked, and no dot directory, whose files
689
+ * astro never loads.
690
+ */
691
+ function loadedFiles(rootDir, collection) {
692
+ return globRoots(collection).flatMap(({ path, file }) => file ? [path].filter((literal) => existsSync(join(rootDir, literal))) : globFiles(join(rootDir, path), "**/*").map((found) => relative(rootDir, found))).filter((path) => globEntry(collection, path) !== null);
693
+ }
694
+ /** Every entry of every collection, each file read and each body walked once. */
695
+ function contentEntries(rootDir, collections, components) {
696
+ const entries = [];
697
+ for (const collection of Object.values(collections)) {
698
+ const isFile = collection.loaderType === "file";
699
+ const files = isFile ? [collection.loaderFileName ?? []].flat().filter((file) => existsSync(join(rootDir, file))) : loadedFiles(rootDir, collection);
700
+ for (const file of files) {
701
+ const raw = readFileSync(join(rootDir, file), "utf-8");
702
+ const format = getFileExtension(file);
703
+ if (isFile) {
704
+ for (const [id, data] of parseMultiEntryFile(raw, format).entries) entries.push({
705
+ collection,
706
+ file,
707
+ scope: `entry "${id}"`,
708
+ data,
709
+ body: null
710
+ });
711
+ continue;
712
+ }
713
+ const { data, body } = parseContent(raw, format);
714
+ entries.push({
715
+ collection,
716
+ file,
717
+ scope: "frontmatter",
718
+ data,
719
+ body: validateBody(body, format, components)
720
+ });
721
+ }
722
+ }
723
+ return entries;
724
+ }
725
+ // src/integration/sitemap-check.ts
726
+ /** A page sitemap. An index lists sitemaps rather than pages, so it reads as empty. */
727
+ var Sitemap = z.object({ urlset: z.object({ url: xmlList(z.object({ loc: z.string() })) }).optional() });
728
+ /**
729
+ * Whether a built sitemap lists a page under `adminPath`. Reading the output
730
+ * rather than the sitemap's options is what honors a `filter`, which is a
731
+ * function the sitemap keeps to itself. A sitemap written after this runs, by
732
+ * an integration listed later, is not seen.
733
+ */
734
+ function sitemapListsAdmin(outDir, adminPath) {
735
+ return globFiles(outDir, "sitemap-*.xml").some((file) => (parseXml(readFileSync(file, "utf-8"), Sitemap).urlset?.url ?? []).some(({ loc }) => {
736
+ const pathname = URL.parse(loc.trim())?.pathname;
737
+ return pathname !== void 0 && isWithin(pathname, adminPath);
738
+ }));
739
+ }
740
+ // src/integration/check-content.ts
741
+ /**
742
+ * The entries on disk that the admin would refuse to save, their data or their
743
+ * body, one line per finding. A developer can commit anything, but an editor who
744
+ * opens such an entry could not save it again without first removing what they
745
+ * did not write, so the build refuses it where the developer sees it instead.
746
+ */
747
+ function checkContent(entries, rootDir, media) {
748
+ return entries.flatMap(({ collection, file, scope, data, body }) => {
749
+ const { diagnostics, leaves } = checkEntry(collection, {
750
+ path: file,
751
+ data,
752
+ body
753
+ });
754
+ const where = body ? file : `${file} (${scope})`;
755
+ return [...diagnostics, ...assetProblems(leaves, file, rootDir, media)].map((d) => `${where}: ${formatDiagnostic(d)}`);
756
+ });
757
+ }
758
+ function isRegularFile(path) {
759
+ try {
760
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false;
761
+ } catch {
762
+ return false;
763
+ }
764
+ }
765
+ /**
766
+ * Every schema-declared asset has to name a file of the repository library, or
767
+ * a URL under the object store where the field admits one, since a page that
768
+ * renders it would otherwise fail on a path nothing can resolve.
769
+ */
770
+ function assetProblems(leaves, file, rootDir, media) {
771
+ return leaves.filter(isAsset).flatMap(({ kind, value, repoOnly, path }) => {
772
+ const location = mediaPath(value, media, file);
773
+ if (location?.library === "s3") return repoOnly ? [diagnostic(repoOnlyRefusal(value), path)] : [];
774
+ const key = location?.path;
775
+ return key !== void 0 && libraryPathError(key, media.repo.extensions) === null && isRegularFile(join(rootDir, media.repo.directory, key)) && (kind !== "image" || ASTRO_IMAGE_FORMATS.some((format) => format === getFileExtension(key))) ? [] : [diagnostic(`"${value}" cannot be resolved as a ${kind} in the media directory ("${media.repo.directory}").`, path)];
776
+ });
777
+ }
778
+ /**
779
+ * The missing files of every singleton. `required` holds its main file, which
780
+ * the site reads by its id, so a build without it would fail there instead, less
781
+ * legibly. `translations` holds the other languages', which fall back to it.
782
+ */
783
+ function missingSingletons(collections, entries) {
784
+ const present = new Set(entries.map((entry) => entry.file));
785
+ const singletons = Object.values(collections).flatMap(({ name, singleton }) => singleton ? [{
786
+ name,
787
+ ...singleton
788
+ }] : []);
789
+ const missing = (files, name) => files.filter(({ path }) => !present.has(path)).map(({ path }) => `${path}: the singleton collection "${name}" needs this file.`);
790
+ return {
791
+ required: singletons.flatMap(({ name, main }) => missing([main], name)),
792
+ translations: singletons.flatMap(({ name, translations }) => missing(translations, name))
793
+ };
794
+ }
795
+ // src/integration/prune-media.ts
796
+ /** Delete unlinked outputs whose complete source list belongs to the library. */
797
+ function pruneMedia(clientDir, inLibrary, emitted) {
798
+ const copies = /* @__PURE__ */ new Map();
799
+ for (const asset of emitted) {
800
+ if (asset.originalFileNames.length === 0 || !asset.originalFileNames.every(inLibrary)) continue;
801
+ const path = join(clientDir, asset.fileName);
802
+ if (existsSync(path)) copies.set(path, statSync(path).size);
803
+ }
804
+ if (copies.size === 0) return copies;
805
+ const names = new Map(copies.keys().map((path) => [path, [basename(path), encodeURIComponent(basename(path))]]));
806
+ for (const file of globFiles(clientDir, "**/*.{html,css,js,mjs,json,xml,txt,webmanifest}")) {
807
+ const text = readFileSync(file, "utf-8");
808
+ for (const [path, spellings] of names) if (spellings.some((name) => text.includes(name))) {
809
+ names.delete(path);
810
+ copies.delete(path);
811
+ }
812
+ if (copies.size === 0) return copies;
813
+ }
814
+ for (const path of copies.keys()) rmSync(path);
815
+ return copies;
816
+ }
817
+ // src/integration/media-graph.ts
818
+ var withoutQuery = (id) => id.split("?", 1)[0] ?? id;
819
+ function mediaGraph({ rootDir, srcDir, media, ignore }) {
820
+ const ignored = new Set(ignore.map(trimSlashes));
821
+ const repoDir = join(rootDir, media.repo.directory);
822
+ const inLibrary = (id) => {
823
+ const key = stripMediaPrefix(withoutQuery(id), repoDir);
824
+ return key != null && isLibraryFile(key, media.repo.extensions);
825
+ };
826
+ let onDemand = [];
827
+ let routeEntries = /* @__PURE__ */ new Set();
828
+ let onDemandMedia = false;
829
+ const emitted = [];
830
+ return {
831
+ plugins: [{
832
+ name: "astronaut-cms:media-graph",
833
+ apply: "build",
834
+ applyToEnvironment: (environment) => environment.name === "ssr",
835
+ async buildEnd() {
836
+ const [content, assets, ...routes] = await Promise.all([
837
+ this.resolve("astro:content"),
838
+ this.resolve("virtual:astronaut-cms/assets"),
839
+ ...onDemand.map(({ entrypoint }) => this.resolve(resolve(rootDir, entrypoint)))
840
+ ]);
841
+ const renders = (id) => inLibrary(id) || id === content?.id || id === assets?.id;
842
+ const stack = [...routes.flatMap((route) => route ? [route.id] : []), ...[...this.getModuleIds()].filter((id) => this.getModuleInfo(id)?.isEntry && id.startsWith(srcDir) && !routeEntries.has(withoutQuery(id)))];
843
+ const reaches = () => {
844
+ const seen = /* @__PURE__ */ new Set();
845
+ for (let id = stack.pop(); id != null; id = stack.pop()) {
846
+ if (seen.has(id)) continue;
847
+ seen.add(id);
848
+ if (renders(id)) return true;
849
+ const info = this.getModuleInfo(id);
850
+ if (info) stack.push(...info.importedIds, ...info.dynamicallyImportedIds);
851
+ }
852
+ return false;
853
+ };
854
+ onDemandMedia = routes.some((route) => !route || !this.getModuleInfo(route.id)) || reaches();
855
+ }
856
+ }, {
857
+ name: "astronaut-cms:media-graph-assets",
858
+ apply: "build",
859
+ generateBundle: {
860
+ order: "post",
861
+ handler(_, bundle) {
862
+ for (const item of Object.values(bundle)) if (item.type === "asset") emitted.push({
863
+ fileName: item.fileName,
864
+ originalFileNames: item.originalFileNames.map((name) => resolve(rootDir, name))
865
+ });
866
+ }
867
+ }
868
+ }],
869
+ get onDemand() {
870
+ return onDemand.map(({ pattern }) => pattern);
871
+ },
872
+ setRoutes(routes) {
873
+ routeEntries = new Set(routes.map(({ entrypoint }) => resolve(rootDir, entrypoint)));
874
+ onDemand = routes.filter((route) => !route.isPrerendered && route.origin !== "internal" && !ignored.has(trimSlashes(route.pattern)));
875
+ },
876
+ prune(clientDir, force) {
877
+ if (!force && onDemandMedia) return null;
878
+ return pruneMedia(clientDir, inLibrary, emitted);
879
+ }
880
+ };
881
+ }
882
+ // src/shared/tools/exposable.ts
883
+ /**
884
+ * Whether a collection can become a pair of tools at all.
885
+ *
886
+ * Both consumers of a tool name are strict about it and neither reports it
887
+ * usefully: an OpenAI-compatible gateway rejects the *whole* request over one
888
+ * bad name, so a single collection called "blog posts" takes the assistant down
889
+ * entirely, and `document.modelContext.registerTool` rejects a promise nobody is
890
+ * watching. A collection name is an object key in the user's `content.config`,
891
+ * so neither of those is exotic.
892
+ *
893
+ * Stated here rather than in either binding, because the answer decides two
894
+ * things at once: what the catalog offers, and what the integration tells the
895
+ * person who can actually fix it.
896
+ */
897
+ /**
898
+ * What a tool may be called, as the strictest of its consumers allows: WebMCP
899
+ * takes `[A-Za-z0-9_.-]` up to 128 characters, a gateway's function names take
900
+ * `[A-Za-z0-9_-]` up to 64, so the intersection is the rule.
901
+ */
902
+ var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
903
+ /** The two tools a collection gets, which is also what its name has to survive. */
904
+ var entryToolNames = (collection) => [`writeEntry_${collection}`, `editEntry_${collection}`];
905
+ /**
906
+ * Why this collection cannot be offered to an agent, or null when it can.
907
+ *
908
+ * The schema check is the round trip the browser makes. The manifest is lowered
909
+ * from Zod when the integration loads the content config and reconstructed on
910
+ * the other side, then described to an agent as JSON Schema. Running it once at
911
+ * build is how a schema that cannot survive that is reported to a person rather
912
+ * than discovered in a browser console.
913
+ */
914
+ function unexposable(name, col) {
915
+ const refused = entryToolNames(name).find((tool) => !TOOL_NAME_PATTERN.test(tool));
916
+ if (refused) return `"${refused}" is not a usable tool name (letters, digits, "_" and "-" only, at most 64 characters).`;
917
+ try {
918
+ for (const schema of [collectionDataSchema(col), collectionPatchSchema(col)]) z.toJSONSchema(schema, {
919
+ target: "draft-2020-12",
920
+ io: "input"
921
+ });
922
+ } catch (error) {
923
+ return `its schema cannot be described to an agent: ${errorMessage(error)}`;
924
+ }
925
+ return null;
926
+ }
927
+ // src/integration/index.ts
928
+ var CONFIG_EXTENSIONS = [
929
+ "ts",
930
+ "tsx",
931
+ "mts",
932
+ "js",
933
+ "jsx",
934
+ "mjs"
935
+ ];
936
+ var INTEGRATION_PATH = fileURLToPath(import.meta.url);
937
+ function findConfig(rootDir, base) {
938
+ for (const ext of CONFIG_EXTENSIONS) {
939
+ const candidate = join(rootDir, `${base}.${ext}`);
940
+ if (existsSync(candidate)) return candidate;
941
+ }
942
+ return null;
943
+ }
944
+ /**
945
+ * Astro only optimizes a remote image whose host it was told to trust, and the
946
+ * site already named that host as `publicUrl`, so it is authorized here rather
947
+ * than asked for again in `image.remotePatterns`.
948
+ */
949
+ function mediaRemotePattern(publicUrl) {
950
+ const url = new URL(publicUrl);
951
+ const pathname = trimSlashes(url.pathname);
952
+ return {
953
+ protocol: url.protocol.slice(0, -1),
954
+ hostname: url.hostname,
955
+ ...pathname && { pathname: `/${pathname}/**` }
956
+ };
957
+ }
958
+ /**
959
+ * Uploaded files are attacker-influenced bytes the site serves back, and some of
960
+ * the library's default types (SVG) are documents a browser will run. Serving
961
+ * them from the admin's own origin would make every upload a candidate for
962
+ * same-origin script in the CMS, so the two origins have to differ.
963
+ *
964
+ * Only checkable when the site declares its own URL; `site` is optional in Astro,
965
+ * so this is enforced where it is knowable and documented where it is not.
966
+ */
967
+ function validateMediaOrigin(publicUrl, site) {
968
+ const siteOrigin = site && new URL(site).origin;
969
+ if (!siteOrigin || new URL(publicUrl).origin !== siteOrigin) return;
970
+ throw new Error(`media: 'publicUrl' (${publicUrl}) must not share an origin with the site itself (${siteOrigin}). Uploaded files would be same-origin content in the admin; serve the library from its own host, e.g. a separate CDN subdomain.`);
971
+ }
972
+ var MIN_NODE_MAJOR = 26;
973
+ function validateNode() {
974
+ if (Number.parseInt(process.versions.node, 10) >= MIN_NODE_MAJOR) return;
975
+ throw new Error(`astronaut-cms: Node.js ${MIN_NODE_MAJOR} or newer is required, found ${process.versions.node}.`);
976
+ }
977
+ /** What an enabled assistant has to declare before any of it is resolved. */
978
+ function validateAi(config) {
979
+ if (!config.ai?.enabled) return;
980
+ if (!config.ai.models?.length) throw new Error("AI assistant: 'models' must list at least one gateway model id.");
981
+ if (!config.ai.gateway) throw new Error("AI assistant: 'gateway' is required (e.g. { type: \"netlify\" }).");
982
+ if (isByok(config) && !gatewayAddress(config.ai.gateway)?.byok) throw new Error(`AI assistant: credentials: "byok" needs a gateway a browser can call with the editor's key ("cloudflare" or "custom"), not "${config.ai.gateway.type}".`);
983
+ }
984
+ /** Everything an object-store library has to declare before it can be reached. */
985
+ function validateS3(config, site) {
986
+ const s3 = config.media?.s3;
987
+ if (!s3) return;
988
+ if (!s3.bucket) throw new Error("media.s3: 'bucket' is required.");
989
+ if (!s3.publicUrl) throw new Error("media.s3: 'publicUrl' is required, the base the library's keys are served under (e.g. 'https://cdn.example.com').");
990
+ validateMediaOrigin(s3.publicUrl, site);
991
+ if (s3.provider === "r2") {
992
+ if (!s3.accountId) throw new Error("media.s3: 'accountId' is required for R2, for the S3 API endpoint.");
993
+ } else if (!s3.endpoint) throw new Error("media.s3: 'endpoint' is required (e.g. 'https://s3.eu-central-1.amazonaws.com').");
994
+ }
995
+ /**
996
+ * Narrows `resolveImage` to the libraries the site configures, so the call
997
+ * sites of a site without an object store never handle a URL they cannot receive,
998
+ * and names the collections `cms.config` may point to.
999
+ */
1000
+ function registryTypes(s3, collections) {
1001
+ return `declare module "astronaut-cms/assets" {
1002
+ interface MediaRegistry {
1003
+ s3: ${s3};
1004
+ }
1005
+ }
1006
+
1007
+ declare module "astronaut-cms/config" {
1008
+ interface CollectionRegistry {
1009
+ name: ${collections.map((name) => JSON.stringify(name)).join(" | ") || "never"};
1010
+ }
1011
+ }
1012
+
1013
+ export {};
1014
+ `;
1015
+ }
1016
+ function cms(config = {}) {
1017
+ let adminPath = "/";
1018
+ let graph = null;
1019
+ let injectedTypes = [];
1020
+ return {
1021
+ name: "astronaut-cms",
1022
+ hooks: {
1023
+ "astro:config:setup": async ({ config: astroConfig, command, injectRoute, updateConfig, addWatchFile, createCodegenDir, logger }) => {
1024
+ validateNode();
1025
+ const rootDir = fileURLToPath(astroConfig.root);
1026
+ const configuredStorage = storageType(config);
1027
+ const s3 = config.media?.s3;
1028
+ const devStorage = command === "dev" && (config.localStorageInDev ?? true) && configuredStorage !== "local";
1029
+ const wantedDevDirectory = command === "dev" && s3 && s3.devDirectory !== false ? s3.devDirectory ?? ".astronaut-cms/s3" : null;
1030
+ const s3DevDirectory = devStorage || configuredStorage === "local" ? wantedDevDirectory : null;
1031
+ const effectiveConfig = {
1032
+ ...config,
1033
+ ...devStorage && { storage: { type: "local" } }
1034
+ };
1035
+ if (devStorage) logger.info(`Using local storage for "astro dev" (configured "${config.storage?.type}" backend will be used in build)`);
1036
+ if (wantedDevDirectory != null) logger.info(s3DevDirectory != null ? `Object-store library served from "${s3DevDirectory}" for "astro dev" (the bucket is used in build; references keep its URL format either way)` : `Editing the configured bucket in "astro dev": media.s3.devDirectory needs local storage, and this run uses "${configuredStorage}". Uploads and deletions here reach the bucket the deployed site serves.`);
1037
+ validateS3(effectiveConfig, astroConfig.site);
1038
+ validateAi(config);
1039
+ const deployable = configuredStorage !== "local";
1040
+ const admin = config.admin ?? deployable;
1041
+ if (admin && !deployable) throw new Error("astronaut-cms: 'admin' needs a Git backend, local storage only serves the admin in \"astro dev\". Configure 'storage' or remove 'admin'.");
1042
+ const storage = effectiveConfig.storage;
1043
+ if (storage?.type === "github") {
1044
+ if (!storage.repo) throw new Error("GitHub storage: 'repo' is required (e.g., 'owner/repo').");
1045
+ if (!storage.clientId) throw new Error("GitHub storage: 'clientId' is the GitHub App's client id.");
1046
+ } else if (storage?.type === "gitlab") {
1047
+ if (!storage.project) throw new Error("GitLab storage: 'project' is required (e.g., 'group/project').");
1048
+ if (!storage.clientId) throw new Error("GitLab storage: 'clientId' is required for OAuth.");
1049
+ }
1050
+ const mediaServer = s3DevDirectory != null ? null : resolveMediaServer(effectiveConfig);
1051
+ let userConfigPath = null;
1052
+ if (config.config) {
1053
+ userConfigPath = join(rootDir, config.config);
1054
+ if (!existsSync(userConfigPath)) throw new Error(`CMS config file not found at "${userConfigPath}" (specified as "${config.config}")`);
1055
+ logger.info(`Using CMS config at ${userConfigPath}`);
1056
+ } else {
1057
+ userConfigPath = findConfig(rootDir, "src/cms.config");
1058
+ if (userConfigPath) logger.info(`Found CMS config at ${userConfigPath}`);
1059
+ else logger.info("No cms.config found, using defaults");
1060
+ }
1061
+ const contentConfigPath = findConfig(rootDir, "src/content.config");
1062
+ if (contentConfigPath) logger.info(`Found content config at ${contentConfigPath}`);
1063
+ else logger.warn("No content.config found, collections will be empty");
1064
+ const { collections, components, componentFiles } = await loadConfigs(rootDir, {
1065
+ content: contentConfigPath,
1066
+ cms: userConfigPath
1067
+ }, resolveContentI18n(config, astroConfig.i18n), (message) => logger.warn(message));
1068
+ const codegenDir = fileURLToPath(createCodegenDir());
1069
+ writeModules(join(codegenDir, "components"), componentModules(userConfigPath, componentFiles));
1070
+ for (const path of [
1071
+ contentConfigPath,
1072
+ userConfigPath,
1073
+ INTEGRATION_PATH
1074
+ ]) if (path) addWatchFile(path);
1075
+ const clientConfig = resolveClientConfig(effectiveConfig, astroConfig.i18n, s3DevDirectory, collections);
1076
+ const mountPoint = clientConfig.mountPoint;
1077
+ adminPath = join("/", astroConfig.base, mountPoint);
1078
+ if (clientConfig.contentI18n) {
1079
+ const { locales, defaultLocale } = clientConfig.contentI18n;
1080
+ logger.info(`Multilingual content enabled for locales ${locales.join(", ")} (default: ${defaultLocale})`);
1081
+ }
1082
+ if (command === "build" || command === "dev") {
1083
+ const entries = contentEntries(rootDir, collections, components);
1084
+ const missing = missingSingletons(collections, entries);
1085
+ const list = (lines) => lines.map((line) => `- ${line}`).join("\n");
1086
+ const problems = [...checkContent(entries, rootDir, clientConfig.media), ...missing.required];
1087
+ if (missing.translations.length > 0) logger.warn(`Untranslated singletons, shown in the default language:\n${list(missing.translations)}`);
1088
+ if (problems.length > 0) {
1089
+ const report = `Content the CMS cannot save:\n${list(problems)}`;
1090
+ if (command === "build") throw new Error(`astronaut-cms: ${report}`);
1091
+ logger.warn(report);
1092
+ }
1093
+ }
1094
+ if (effectiveConfig.ai?.enabled || effectiveConfig.webmcp?.enabled) for (const [name, col] of Object.entries(collections)) {
1095
+ const reason = unexposable(name, col);
1096
+ if (reason) logger.warn(`Collection "${name}" cannot be edited by the assistant or a browser agent, and is left out of their tools (reading it still works): ${reason}`);
1097
+ }
1098
+ const serverConfig = resolveServerConfig(effectiveConfig, rootDir, mediaServer, astroConfig.trailingSlash);
1099
+ const devApi = command === "dev" && serverConfig.storage.type === "local";
1100
+ const { s3: s3Library } = clientConfig.media;
1101
+ injectedTypes = [{
1102
+ filename: "types.d.ts",
1103
+ content: registryTypes(s3Library != null, Object.keys(collections))
1104
+ }, {
1105
+ filename: "components.d.ts",
1106
+ content: componentTypes(codegenDir, userConfigPath, Object.keys(componentFiles))
1107
+ }];
1108
+ graph = mediaGraph({
1109
+ rootDir,
1110
+ srcDir: fileURLToPath(astroConfig.srcDir),
1111
+ media: clientConfig.media,
1112
+ ignore: [mountPoint, API_PATTERN]
1113
+ });
1114
+ updateConfig({
1115
+ ...s3Library && { image: { remotePatterns: [mediaRemotePattern(s3Library.publicUrl)] } },
1116
+ env: { schema: secretsSchema(config) },
1117
+ vite: {
1118
+ plugins: [
1119
+ ...cmsVitePlugin({
1120
+ clientConfig,
1121
+ serverConfig,
1122
+ userConfigPath,
1123
+ components,
1124
+ componentsEntry: join(codegenDir, "components/index.ts"),
1125
+ rootDir
1126
+ }),
1127
+ ...graph.plugins,
1128
+ ...command === "dev" ? [cmsDevPlugin(devApi ? join("/", astroConfig.base, API_BASE) : null)] : []
1129
+ ],
1130
+ optimizeDeps: {
1131
+ exclude: ["astronaut-cms"],
1132
+ ...userConfigPath && { entries: [userConfigPath] }
1133
+ }
1134
+ }
1135
+ });
1136
+ if (command !== "dev" && !admin) {
1137
+ logger.info(`Admin panel disabled for "${command}" (only available via "astro dev")`);
1138
+ return;
1139
+ }
1140
+ if (command === "build" && !astroConfig.adapter) throw new Error("astronaut-cms needs an SSR adapter: the CMS holds the repository session on the server, so its API routes have to render on demand. Add one (e.g. @astrojs/node, @astrojs/cloudflare, @astrojs/vercel, @astrojs/netlify) to astro.config.");
1141
+ injectRoute({
1142
+ pattern: mountPoint,
1143
+ entrypoint: "astronaut-cms/admin.astro",
1144
+ prerender: false
1145
+ });
1146
+ injectRoute({
1147
+ pattern: API_PATTERN,
1148
+ entrypoint: "astronaut-cms/endpoint",
1149
+ prerender: false
1150
+ });
1151
+ injectRoute({
1152
+ pattern: LICENSES_PATH,
1153
+ entrypoint: "astronaut-cms/licenses",
1154
+ prerender: true
1155
+ });
1156
+ logger.info(`Admin panel will be available at ${mountPoint}`);
1157
+ if (serverConfig.storage.type !== "local") {
1158
+ const callback = new URL(join("/", astroConfig.base, API_CALLBACK), astroConfig.site ?? "https://your-site.example").href;
1159
+ logger.info(`OAuth callback URL: ${conformTrailingSlash(callback, astroConfig.trailingSlash)}`);
1160
+ }
1161
+ if (config.ai?.enabled) logger.info(`AI assistant enabled${isByok(effectiveConfig) ? " (each editor brings their own key)" : ""}`);
1162
+ },
1163
+ "astro:config:done": ({ injectTypes }) => {
1164
+ for (const types of injectedTypes) injectTypes(types);
1165
+ },
1166
+ "astro:server:setup": ({ server }) => {
1167
+ server.watcher.add(INTEGRATION_PATH);
1168
+ },
1169
+ "astro:routes:resolved": ({ routes }) => graph?.setRoutes(routes),
1170
+ "astro:build:done": ({ dir, logger }) => {
1171
+ const clientDir = fileURLToPath(dir);
1172
+ if (sitemapListsAdmin(clientDir, adminPath)) logger.warn(`The sitemap lists the admin at ${adminPath}. Exclude it with sitemap({ filter: (page) => !new URL(page).pathname.startsWith("${adminPath}") }).`);
1173
+ const prune = config.media?.repo?.prune;
1174
+ if (!graph || prune === false) return;
1175
+ const removed = graph.prune(clientDir, prune === true);
1176
+ if (!removed) {
1177
+ logger.info(`Kept media library files because on-demand code (${graph.onDemand.join(", ") || "server islands"}) may render them. Set media.repo.prune to true if it never does.`);
1178
+ return;
1179
+ }
1180
+ if (removed.size === 0) return;
1181
+ const size = [...removed.values()].reduce((sum, bytes) => sum + bytes, 0);
1182
+ logger.info(`Removed ${removed.size} media library files no delivered file links (${megabytes(size)}).`);
1183
+ }
1184
+ }
1185
+ };
1186
+ }
1187
+ export { cms as default, defineCollection, defineComponent, fileMarker as file, libraryImage, localizedMarker as localized };