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