@vite-hub/cms 0.0.0-stage → 0.3.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 +201 -0
- package/README.md +74 -2
- package/dist/access.d.ts +69 -0
- package/dist/access.js +119 -0
- package/dist/index-eur9QR7_.d.ts +51 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +61 -0
- package/dist/options-CIxG4vtI.js +96 -0
- package/dist/vite.d.ts +374 -0
- package/dist/vite.js +960 -0
- package/package.json +103 -3
package/dist/vite.js
ADDED
|
@@ -0,0 +1,960 @@
|
|
|
1
|
+
import { a as cmsStoreOf, i as cmsOptionsProblem, n as cmsOptionKeys, o as cmsErrorDiagnostics, r as cmsOptionProblem, t as cmsGitHubDefaults } from "./options-CIxG4vtI.js";
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, join, parse, relative, resolve } from "node:path";
|
|
4
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { findContentEntry } from "@vite-hub/source/vite";
|
|
7
|
+
import { parseAst } from "vite";
|
|
8
|
+
//#region ../internal/dist/build/vite.js
|
|
9
|
+
const projectRootDirectoryMarkers = [
|
|
10
|
+
["server", "agents"],
|
|
11
|
+
["server", "channels"],
|
|
12
|
+
["server", "connections"],
|
|
13
|
+
["server", "browsers"],
|
|
14
|
+
["server", "emails"],
|
|
15
|
+
["server", "schedules"],
|
|
16
|
+
["server", "workspaces"]
|
|
17
|
+
];
|
|
18
|
+
const projectRootFileMarkers = [
|
|
19
|
+
["package.json"],
|
|
20
|
+
["nuxt.config.ts"],
|
|
21
|
+
["nuxt.config.mts"],
|
|
22
|
+
["nuxt.config.js"],
|
|
23
|
+
["nuxt.config.mjs"]
|
|
24
|
+
];
|
|
25
|
+
const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
26
|
+
/**
|
|
27
|
+
* Server directories that ViteHub scans for Definitions. The first entry is the application.
|
|
28
|
+
* Later entries are Nuxt layers in Nuxt priority order.
|
|
29
|
+
*/
|
|
30
|
+
const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
|
|
31
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
32
|
+
const resolvedRoot = resolve(root);
|
|
33
|
+
const temporaryRoot = resolve(tmpdir());
|
|
34
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
35
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
36
|
+
if (basename(resolvedRoot) === "app") {
|
|
37
|
+
const parent = dirname(resolvedRoot);
|
|
38
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
39
|
+
"nuxt.config.ts",
|
|
40
|
+
"nuxt.config.mts",
|
|
41
|
+
"nuxt.config.js",
|
|
42
|
+
"nuxt.config.mjs"
|
|
43
|
+
]))) return parent;
|
|
44
|
+
}
|
|
45
|
+
let current = resolvedRoot;
|
|
46
|
+
while (true) {
|
|
47
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
48
|
+
if (hasProjectRootMarker(current)) return current;
|
|
49
|
+
const parent = dirname(current);
|
|
50
|
+
if (parent === current) return resolvedRoot;
|
|
51
|
+
current = parent;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
55
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
56
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (error.code !== "ENOENT") throw error;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
function hasProjectRootMarker(root) {
|
|
63
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
64
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
65
|
+
}
|
|
66
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
67
|
+
for (const marker of markers) {
|
|
68
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
69
|
+
try {
|
|
70
|
+
if (statSync(resolve(root, ...path)).isFile()) return true;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.code !== "ENOENT") throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region ../internal/dist/object.js
|
|
79
|
+
/** A non-null object that is not an array. Functions do not pass. */
|
|
80
|
+
function isRecord(value) {
|
|
81
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
85
|
+
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
86
|
+
function normalizeWindowsPath(input = "") {
|
|
87
|
+
if (!input) return input;
|
|
88
|
+
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
89
|
+
}
|
|
90
|
+
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
|
91
|
+
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
92
|
+
function cwd() {
|
|
93
|
+
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
|
|
94
|
+
return "/";
|
|
95
|
+
}
|
|
96
|
+
const resolve$1 = function(...arguments_) {
|
|
97
|
+
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
|
98
|
+
let resolvedPath = "";
|
|
99
|
+
let resolvedAbsolute = false;
|
|
100
|
+
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
|
101
|
+
const path = index >= 0 ? arguments_[index] : cwd();
|
|
102
|
+
if (!path || path.length === 0) continue;
|
|
103
|
+
resolvedPath = `${path}/${resolvedPath}`;
|
|
104
|
+
resolvedAbsolute = isAbsolute(path);
|
|
105
|
+
}
|
|
106
|
+
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
107
|
+
if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
|
|
108
|
+
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
109
|
+
};
|
|
110
|
+
function normalizeString(path, allowAboveRoot) {
|
|
111
|
+
let res = "";
|
|
112
|
+
let lastSegmentLength = 0;
|
|
113
|
+
let lastSlash = -1;
|
|
114
|
+
let dots = 0;
|
|
115
|
+
let char = null;
|
|
116
|
+
for (let index = 0; index <= path.length; ++index) {
|
|
117
|
+
if (index < path.length) char = path[index];
|
|
118
|
+
else if (char === "/") break;
|
|
119
|
+
else char = "/";
|
|
120
|
+
if (char === "/") {
|
|
121
|
+
if (lastSlash === index - 1 || dots === 1);
|
|
122
|
+
else if (dots === 2) {
|
|
123
|
+
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
124
|
+
if (res.length > 2) {
|
|
125
|
+
const lastSlashIndex = res.lastIndexOf("/");
|
|
126
|
+
if (lastSlashIndex === -1) {
|
|
127
|
+
res = "";
|
|
128
|
+
lastSegmentLength = 0;
|
|
129
|
+
} else {
|
|
130
|
+
res = res.slice(0, lastSlashIndex);
|
|
131
|
+
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
132
|
+
}
|
|
133
|
+
lastSlash = index;
|
|
134
|
+
dots = 0;
|
|
135
|
+
continue;
|
|
136
|
+
} else if (res.length > 0) {
|
|
137
|
+
res = "";
|
|
138
|
+
lastSegmentLength = 0;
|
|
139
|
+
lastSlash = index;
|
|
140
|
+
dots = 0;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (allowAboveRoot) {
|
|
145
|
+
res += res.length > 0 ? "/.." : "..";
|
|
146
|
+
lastSegmentLength = 2;
|
|
147
|
+
}
|
|
148
|
+
} else {
|
|
149
|
+
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
|
|
150
|
+
else res = path.slice(lastSlash + 1, index);
|
|
151
|
+
lastSegmentLength = index - lastSlash - 1;
|
|
152
|
+
}
|
|
153
|
+
lastSlash = index;
|
|
154
|
+
dots = 0;
|
|
155
|
+
} else if (char === "." && dots !== -1) ++dots;
|
|
156
|
+
else dots = -1;
|
|
157
|
+
}
|
|
158
|
+
return res;
|
|
159
|
+
}
|
|
160
|
+
const isAbsolute = function(p) {
|
|
161
|
+
return _IS_ABSOLUTE_RE.test(p);
|
|
162
|
+
};
|
|
163
|
+
const relative$1 = function(from, to) {
|
|
164
|
+
const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
165
|
+
const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
166
|
+
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
|
|
167
|
+
const _fromCopy = [..._from];
|
|
168
|
+
for (const segment of _fromCopy) {
|
|
169
|
+
if (_to[0] !== segment) break;
|
|
170
|
+
_from.shift();
|
|
171
|
+
_to.shift();
|
|
172
|
+
}
|
|
173
|
+
return [..._from.map(() => ".."), ..._to].join("/");
|
|
174
|
+
};
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region ../internal/dist/contributions.js
|
|
177
|
+
function isThenable(value) {
|
|
178
|
+
return typeof value.then === "function";
|
|
179
|
+
}
|
|
180
|
+
async function flattenPlugins(value, plugins, seen) {
|
|
181
|
+
if (Array.isArray(value)) {
|
|
182
|
+
for (const item of value) await flattenPlugins(item, plugins, seen);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (!isRecord(value) || seen.has(value)) return;
|
|
186
|
+
seen.add(value);
|
|
187
|
+
if (isThenable(value)) {
|
|
188
|
+
await flattenPlugins(await value, plugins, seen);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
plugins.push(value);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
|
|
195
|
+
* list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
|
|
196
|
+
* filter this list, because `vitehub()` nests its plugins in an array.
|
|
197
|
+
*/
|
|
198
|
+
async function flattenPluginOptions(plugins) {
|
|
199
|
+
const flattened = [];
|
|
200
|
+
await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
|
|
201
|
+
return flattened;
|
|
202
|
+
}
|
|
203
|
+
//#endregion
|
|
204
|
+
//#region ../internal/dist/inspect.js
|
|
205
|
+
function relativeDefinitionFile(projectRoot, file) {
|
|
206
|
+
return relative$1(projectRoot, file).replaceAll("\\", "/");
|
|
207
|
+
}
|
|
208
|
+
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
209
|
+
new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
|
|
210
|
+
new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
|
|
211
|
+
//#endregion
|
|
212
|
+
//#region src/database-lookup.injected.ts
|
|
213
|
+
/**
|
|
214
|
+
* Generated module source that reads the Database of the cms preset. The build loads the generated module without the
|
|
215
|
+
* app's Databases, and `useDatabase()` throws for a missing one, so the module keeps the error and throws it on first
|
|
216
|
+
* use. The text runs in the generated module, not here, so its error stays plain.
|
|
217
|
+
*/
|
|
218
|
+
function renderDatabaseLookup(database) {
|
|
219
|
+
const missing = `[vitehub] The Content cms preset needs Database ${JSON.stringify(database)}, but it is not configured at runtime. Enable database in vitehub() and keep its Database Definition.`;
|
|
220
|
+
return [
|
|
221
|
+
"let database",
|
|
222
|
+
`try { database = useDatabase(${JSON.stringify(database)}).db }`,
|
|
223
|
+
"catch (error) {",
|
|
224
|
+
" database = new Proxy({}, {",
|
|
225
|
+
" get() {",
|
|
226
|
+
` throw new Error(${JSON.stringify(missing)}, { cause: error })`,
|
|
227
|
+
" },",
|
|
228
|
+
" })",
|
|
229
|
+
"}"
|
|
230
|
+
];
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/build.ts
|
|
234
|
+
/** Import paths that select the `cms` preset in `server/content.ts`. */
|
|
235
|
+
const cmsPresetModules = ["vite-hub/cms", "@vite-hub/cms"];
|
|
236
|
+
function isNode(value) {
|
|
237
|
+
return value !== null && Object(value) === value && String(Reflect.get(Object(value), "type")) === Reflect.get(Object(value), "type");
|
|
238
|
+
}
|
|
239
|
+
/** Drop type-only and grouping wrappers such as `x satisfies T`, `x as T`, and `(x)`. */
|
|
240
|
+
function unwrap(node) {
|
|
241
|
+
let current = node;
|
|
242
|
+
while (isNode(current) && [
|
|
243
|
+
"ParenthesizedExpression",
|
|
244
|
+
"TSAsExpression",
|
|
245
|
+
"TSSatisfiesExpression",
|
|
246
|
+
"TSNonNullExpression",
|
|
247
|
+
"TSTypeAssertion"
|
|
248
|
+
].includes(current.type)) current = current.expression;
|
|
249
|
+
return current;
|
|
250
|
+
}
|
|
251
|
+
function propertyName(node) {
|
|
252
|
+
if (node.type !== "Property" || node.computed === true) return;
|
|
253
|
+
const key = node.key;
|
|
254
|
+
if (!isNode(key)) return;
|
|
255
|
+
if (key.type === "Identifier") return String(key.name);
|
|
256
|
+
if (key.type === "Literal" && String(key.value) === key.value) return key.value;
|
|
257
|
+
}
|
|
258
|
+
function stringValue(node) {
|
|
259
|
+
const value = unwrap(node);
|
|
260
|
+
if (!isNode(value)) return;
|
|
261
|
+
if (value.type === "Literal" && String(value.value) === value.value) return value.value;
|
|
262
|
+
if (value.type === "TemplateLiteral" && Array.isArray(value.expressions) && !value.expressions.length && Array.isArray(value.quasis) && value.quasis.length === 1) {
|
|
263
|
+
const quasi = value.quasis[0];
|
|
264
|
+
const cooked = isNode(quasi) ? Reflect.get(Object(quasi.value), "cooked") : void 0;
|
|
265
|
+
if (String(cooked) === cooked) return cooked;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function displayPath(file, projectRoot) {
|
|
269
|
+
return JSON.stringify(relative(projectRoot, file).replaceAll("\\", "/"));
|
|
270
|
+
}
|
|
271
|
+
/** The build cannot read how the Definition selects the preset. */
|
|
272
|
+
function presetError(file, projectRoot, message) {
|
|
273
|
+
return cmsErrorDiagnostics.CONTENT_B0001({ message: `[vitehub] ${displayPath(file, projectRoot)}: ${message}` });
|
|
274
|
+
}
|
|
275
|
+
/** The app lacks something the preset needs. */
|
|
276
|
+
function cmsRequirementError(file, projectRoot, message) {
|
|
277
|
+
return cmsErrorDiagnostics.CONTENT_B0002({ message: `[vitehub] ${displayPath(file, projectRoot)} uses the Content cms preset: ${message}` });
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Read how `server/content.ts` selects the `cms` preset. The build cannot run the Definition, so the preset must be
|
|
281
|
+
* imported from `vite-hub/cms` or `@vite-hub/cms` and passed as `extends: cms` or `extends: [cms, { ... }]` with string
|
|
282
|
+
* literal options. Returns undefined when the file does not import the preset.
|
|
283
|
+
*/
|
|
284
|
+
function readCmsPresetUsage(source, file, projectRoot, parseAst) {
|
|
285
|
+
return readCmsPresetUsageInternal(source, file, projectRoot, parseAst, /* @__PURE__ */ new Set(), "default");
|
|
286
|
+
}
|
|
287
|
+
/** `exportName` is the export that holds the Content Definition: `default` in `server/content.ts`, or the name that it re-exports. */
|
|
288
|
+
function readCmsPresetUsageInternal(source, file, projectRoot, parseAst, seen, exportName) {
|
|
289
|
+
const resolvedFile = resolve(file);
|
|
290
|
+
if (seen.has(resolvedFile)) return;
|
|
291
|
+
seen.add(resolvedFile);
|
|
292
|
+
const program = parseAst(source, { lang: /\.[cm]?tsx$/.test(file) ? "tsx" : /\.[cm]?jsx$/.test(file) ? "jsx" : /\.[cm]?ts$/.test(file) ? "ts" : "js" });
|
|
293
|
+
if (!isNode(program)) return;
|
|
294
|
+
for (const statement of Array.isArray(program.body) ? program.body : []) {
|
|
295
|
+
if (!isNode(statement) || statement.type !== "ExportNamedDeclaration" || !isNode(statement.source)) continue;
|
|
296
|
+
let targetExport;
|
|
297
|
+
for (const specifier of Array.isArray(statement.specifiers) ? statement.specifiers : []) {
|
|
298
|
+
if (!isNode(specifier) || specifier.type !== "ExportSpecifier" || !isNode(specifier.exported) || !isNode(specifier.local)) continue;
|
|
299
|
+
if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === exportName) targetExport = String(specifier.local.type === "Identifier" ? specifier.local.name : specifier.local.value);
|
|
300
|
+
}
|
|
301
|
+
const specifier = statement.source.value;
|
|
302
|
+
if (!targetExport || typeof specifier !== "string" || !specifier.startsWith(".")) continue;
|
|
303
|
+
const base = resolve(file, "..", specifier);
|
|
304
|
+
const target = [
|
|
305
|
+
base,
|
|
306
|
+
...[
|
|
307
|
+
".ts",
|
|
308
|
+
".tsx",
|
|
309
|
+
".js",
|
|
310
|
+
".jsx",
|
|
311
|
+
".mts",
|
|
312
|
+
".cts",
|
|
313
|
+
".mjs",
|
|
314
|
+
".cjs"
|
|
315
|
+
].map((ext) => `${base}${ext}`),
|
|
316
|
+
...[
|
|
317
|
+
"index.ts",
|
|
318
|
+
"index.tsx",
|
|
319
|
+
"index.js",
|
|
320
|
+
"index.jsx",
|
|
321
|
+
"index.mts",
|
|
322
|
+
"index.cts",
|
|
323
|
+
"index.mjs",
|
|
324
|
+
"index.cjs"
|
|
325
|
+
].map((name) => join(base, name))
|
|
326
|
+
].find((candidate) => existsSync(candidate));
|
|
327
|
+
if (target) {
|
|
328
|
+
const usage = readCmsPresetUsageInternal(readFileSync(target, "utf8"), target, projectRoot, parseAst, seen, targetExport);
|
|
329
|
+
if (usage) return usage;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
for (const statement of Array.isArray(program.body) ? program.body : []) {
|
|
333
|
+
if (exportName === "default") break;
|
|
334
|
+
if (!isNode(statement) || statement.type !== "ExportAllDeclaration" || !isNode(statement.source)) continue;
|
|
335
|
+
const specifier = statement.source.value;
|
|
336
|
+
if (typeof specifier !== "string" || !specifier.startsWith(".")) continue;
|
|
337
|
+
const base = resolve(file, "..", specifier);
|
|
338
|
+
const target = [
|
|
339
|
+
base,
|
|
340
|
+
...[
|
|
341
|
+
".ts",
|
|
342
|
+
".tsx",
|
|
343
|
+
".js",
|
|
344
|
+
".jsx",
|
|
345
|
+
".mts",
|
|
346
|
+
".cts",
|
|
347
|
+
".mjs",
|
|
348
|
+
".cjs"
|
|
349
|
+
].map((ext) => `${base}${ext}`),
|
|
350
|
+
...[
|
|
351
|
+
"index.ts",
|
|
352
|
+
"index.tsx",
|
|
353
|
+
"index.js",
|
|
354
|
+
"index.jsx",
|
|
355
|
+
"index.mts",
|
|
356
|
+
"index.cts",
|
|
357
|
+
"index.mjs",
|
|
358
|
+
"index.cjs"
|
|
359
|
+
].map((name) => join(base, name))
|
|
360
|
+
].find((candidate) => existsSync(candidate));
|
|
361
|
+
if (target) {
|
|
362
|
+
const usage = readCmsPresetUsageInternal(readFileSync(target, "utf8"), target, projectRoot, parseAst, seen, exportName);
|
|
363
|
+
if (usage) return usage;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (!cmsPresetModules.some((module) => source.includes(module))) return;
|
|
367
|
+
const bindings = /* @__PURE__ */ new Set();
|
|
368
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
369
|
+
for (const statement of Array.isArray(program.body) ? program.body : []) {
|
|
370
|
+
if (!isNode(statement) || statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
|
|
371
|
+
const from = isNode(statement.source) ? statement.source.value : void 0;
|
|
372
|
+
if (String(from) !== from || !cmsPresetModules.includes(from)) continue;
|
|
373
|
+
for (const specifier of Array.isArray(statement.specifiers) ? statement.specifiers : []) {
|
|
374
|
+
if (!isNode(specifier) || !isNode(specifier.local) || specifier.importKind === "type") continue;
|
|
375
|
+
const local = String(specifier.local.name);
|
|
376
|
+
if (specifier.type === "ImportDefaultSpecifier") bindings.add(local);
|
|
377
|
+
else if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(local);
|
|
378
|
+
else if (specifier.type === "ImportSpecifier" && isNode(specifier.imported)) {
|
|
379
|
+
const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
380
|
+
if (imported === "cms" || imported === "default") bindings.add(local);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (!bindings.size && !namespaces.size) return;
|
|
385
|
+
const defineContentBindings = /* @__PURE__ */ new Set();
|
|
386
|
+
for (const statement of Array.isArray(program.body) ? program.body : []) {
|
|
387
|
+
if (!isNode(statement) || statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
|
|
388
|
+
const from = isNode(statement.source) ? statement.source.value : void 0;
|
|
389
|
+
if (from !== "vite-hub/content" && from !== "@vite-hub/content") continue;
|
|
390
|
+
for (const specifier of Array.isArray(statement.specifiers) ? statement.specifiers : []) {
|
|
391
|
+
if (!isNode(specifier) || specifier.type !== "ImportSpecifier" || !isNode(specifier.local) || !isNode(specifier.imported)) continue;
|
|
392
|
+
if ((specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "defineContent") defineContentBindings.add(String(specifier.local.name));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const isPreset = (node) => {
|
|
396
|
+
const value = unwrap(node);
|
|
397
|
+
if (!isNode(value)) return false;
|
|
398
|
+
if (value.type === "Identifier") return bindings.has(String(value.name));
|
|
399
|
+
if (value.type !== "MemberExpression" || value.computed === true || !isNode(value.object) || !isNode(value.property)) return false;
|
|
400
|
+
return value.object.type === "Identifier" && namespaces.has(String(value.object.name)) && (value.property.name === "cms" || value.property.name === "default");
|
|
401
|
+
};
|
|
402
|
+
const exportedContentBindings = /* @__PURE__ */ new Set();
|
|
403
|
+
for (const statement of Array.isArray(program.body) ? program.body : []) {
|
|
404
|
+
if (!isNode(statement)) continue;
|
|
405
|
+
if (statement.type === "ExportDefaultDeclaration") {
|
|
406
|
+
const value = unwrap(statement.declaration);
|
|
407
|
+
if (exportName === "default" && isNode(value) && value.type === "Identifier") exportedContentBindings.add(String(value.name));
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
if (statement.type !== "ExportNamedDeclaration" || isNode(statement.source)) continue;
|
|
411
|
+
const declaration = statement.declaration;
|
|
412
|
+
if (isNode(declaration) && declaration.type === "VariableDeclaration") {
|
|
413
|
+
for (const declarator of Array.isArray(declaration.declarations) ? declaration.declarations : []) if (isNode(declarator) && isNode(declarator.id) && declarator.id.type === "Identifier" && declarator.id.name === exportName) exportedContentBindings.add(String(declarator.id.name));
|
|
414
|
+
}
|
|
415
|
+
for (const specifier of Array.isArray(statement.specifiers) ? statement.specifiers : []) {
|
|
416
|
+
if (!isNode(specifier) || specifier.type !== "ExportSpecifier" || !isNode(specifier.local) || !isNode(specifier.exported)) continue;
|
|
417
|
+
if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === exportName) exportedContentBindings.add(String(specifier.local.name));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
let contentOptions;
|
|
421
|
+
for (const statement of Array.isArray(program.body) ? program.body : []) {
|
|
422
|
+
if (!isNode(statement)) continue;
|
|
423
|
+
if (statement.type === "ExportDefaultDeclaration") {
|
|
424
|
+
const init = unwrap(statement.declaration);
|
|
425
|
+
if (exportName === "default" && isNode(init) && init.type === "CallExpression" && isNode(init.callee) && init.callee.type === "Identifier" && defineContentBindings.has(String(init.callee.name))) {
|
|
426
|
+
const argument = unwrap(Array.isArray(init.arguments) ? init.arguments[0] : void 0);
|
|
427
|
+
if (isNode(argument) && argument.type === "ObjectExpression") contentOptions = argument;
|
|
428
|
+
}
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
432
|
+
if (!isNode(declaration) || declaration.type !== "VariableDeclaration") continue;
|
|
433
|
+
for (const declarator of Array.isArray(declaration.declarations) ? declaration.declarations : []) {
|
|
434
|
+
if (!isNode(declarator) || !isNode(declarator.id) || declarator.id.type !== "Identifier" || !exportedContentBindings.has(String(declarator.id.name))) continue;
|
|
435
|
+
const init = unwrap(declarator.init);
|
|
436
|
+
if (!isNode(init) || init.type !== "CallExpression" || !isNode(init.callee) || init.callee.type !== "Identifier" || !defineContentBindings.has(String(init.callee.name))) continue;
|
|
437
|
+
const argument = unwrap(Array.isArray(init.arguments) ? init.arguments[0] : void 0);
|
|
438
|
+
if (isNode(argument) && argument.type === "ObjectExpression") contentOptions = argument;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const selections = [];
|
|
442
|
+
if (contentOptions) for (const property of Array.isArray(contentOptions.properties) ? contentOptions.properties : []) {
|
|
443
|
+
if (!isNode(property) || propertyName(property) !== "extends") continue;
|
|
444
|
+
const value = unwrap(property.value);
|
|
445
|
+
if (isPreset(value)) selections.push(value);
|
|
446
|
+
else if (isNode(value) && value.type === "ArrayExpression" && Array.isArray(value.elements) && isPreset(value.elements[0])) selections.push(value);
|
|
447
|
+
}
|
|
448
|
+
const usage = `Pass it as defineContent({ extends: cms }) or defineContent({ extends: [cms, { ${cmsOptionKeys.join(", ")} }] }) in the exported content Definition.`;
|
|
449
|
+
if (!selections.length) throw presetError(file, projectRoot, `imports the Content cms preset but does not select it with extends. ${usage}`);
|
|
450
|
+
if (selections.length > 1) throw presetError(file, projectRoot, `selects the Content cms preset more than once. ${usage}`);
|
|
451
|
+
const selection = selections[0];
|
|
452
|
+
let ownPolicy;
|
|
453
|
+
for (const property of Array.isArray(contentOptions?.properties) ? contentOptions.properties : []) {
|
|
454
|
+
if (!isNode(property)) continue;
|
|
455
|
+
if (property.type === "SpreadElement") {
|
|
456
|
+
ownPolicy = "unknown";
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (propertyName(property) !== "authorize") continue;
|
|
460
|
+
const value = unwrap(property.value);
|
|
461
|
+
ownPolicy = isNode(value) && (value.type === "Identifier" && value.name === "undefined" || value.type === "UnaryExpression" && value.operator === "void") ? void 0 : true;
|
|
462
|
+
}
|
|
463
|
+
const access = ownPolicy ? { authorize: ownPolicy } : {};
|
|
464
|
+
if (!isNode(selection) || selection.type !== "ArrayExpression") return {
|
|
465
|
+
file,
|
|
466
|
+
options: {},
|
|
467
|
+
...access
|
|
468
|
+
};
|
|
469
|
+
const elements = Array.isArray(selection.elements) ? selection.elements : [];
|
|
470
|
+
const optionsNode = unwrap(elements[1]);
|
|
471
|
+
if (elements.length !== 2 || !isNode(optionsNode) || optionsNode.type !== "ObjectExpression") throw presetError(file, projectRoot, `the cms preset tuple must be [cms, { ... }] with an object literal. ${usage}`);
|
|
472
|
+
const options = {};
|
|
473
|
+
for (const property of Array.isArray(optionsNode.properties) ? optionsNode.properties : []) {
|
|
474
|
+
const key = isNode(property) ? propertyName(property) : void 0;
|
|
475
|
+
if (!isNode(property) || key === void 0 || property.kind !== "init" || property.method === true) throw presetError(file, projectRoot, "cms preset options must be plain properties with string literal values, because the build reads them without running the file.");
|
|
476
|
+
if (!cmsOptionKeys.includes(key)) throw presetError(file, projectRoot, `unknown cms preset option ${JSON.stringify(key)}. Use ${cmsOptionKeys.join(", ")}.`);
|
|
477
|
+
const valueNode = unwrap(property.value);
|
|
478
|
+
if (isNode(valueNode) && valueNode.type === "Identifier" && valueNode.name === "undefined") continue;
|
|
479
|
+
const value = stringValue(valueNode);
|
|
480
|
+
if (value === void 0) throw presetError(file, projectRoot, `cms preset option ${JSON.stringify(key)} must be a string literal, because the build reads it without running the file.`);
|
|
481
|
+
const problem = cmsOptionProblem(key, value);
|
|
482
|
+
if (problem) throw presetError(file, projectRoot, `cms preset option ${JSON.stringify(key)} ${problem}`);
|
|
483
|
+
Reflect.set(options, key, value);
|
|
484
|
+
}
|
|
485
|
+
const problem = cmsOptionsProblem(options);
|
|
486
|
+
if (problem) throw presetError(file, projectRoot, `cms preset ${problem}`);
|
|
487
|
+
return {
|
|
488
|
+
file,
|
|
489
|
+
options,
|
|
490
|
+
...access
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
/** Pick the Database, Blob store, and Workspace name that the preset uses. Fails with the option to set. */
|
|
494
|
+
function resolveCmsPresetPlan(usage, databases, projectRoot) {
|
|
495
|
+
const store = cmsStoreOf(usage.options);
|
|
496
|
+
const stored = store === "github" ? {
|
|
497
|
+
store,
|
|
498
|
+
github: githubPlan(usage.options)
|
|
499
|
+
} : {
|
|
500
|
+
store,
|
|
501
|
+
blob: usage.options.blob ?? "default"
|
|
502
|
+
};
|
|
503
|
+
const workspace = usage.options.workspace ?? "content";
|
|
504
|
+
const choices = databases.names.length ? [...databases.names].sort().map((name) => JSON.stringify(name)).join(", ") : "none";
|
|
505
|
+
if (usage.options.database !== void 0) {
|
|
506
|
+
if (!databases.names.includes(usage.options.database)) throw cmsRequirementError(usage.file, projectRoot, `option database is ${JSON.stringify(usage.options.database)}, but no Database Definition has that name. Database Definitions: ${choices}.`);
|
|
507
|
+
return {
|
|
508
|
+
...usage,
|
|
509
|
+
...stored,
|
|
510
|
+
database: usage.options.database,
|
|
511
|
+
databaseReason: "option",
|
|
512
|
+
workspace
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
const resolution = databases.resolveDefault(databases.names);
|
|
516
|
+
if (resolution.status === "none") return {
|
|
517
|
+
...usage,
|
|
518
|
+
...stored,
|
|
519
|
+
database: "default",
|
|
520
|
+
databaseReason: "implicit",
|
|
521
|
+
workspace
|
|
522
|
+
};
|
|
523
|
+
if (resolution.status === "ambiguous") throw cmsRequirementError(usage.file, projectRoot, `it needs one Database, but the app has several and none is named "default": ${choices}. Choose one with extends: [cms, { database: ${JSON.stringify(resolution.names[0])} }].`);
|
|
524
|
+
return {
|
|
525
|
+
...usage,
|
|
526
|
+
...stored,
|
|
527
|
+
database: resolution.name,
|
|
528
|
+
databaseReason: resolution.reason,
|
|
529
|
+
workspace
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
function githubPlan(options) {
|
|
533
|
+
return {
|
|
534
|
+
...options.repo === void 0 ? {} : { repo: options.repo },
|
|
535
|
+
branch: options.branch ?? cmsGitHubDefaults.branch,
|
|
536
|
+
draftBranch: options.draftBranch ?? cmsGitHubDefaults.draftBranch,
|
|
537
|
+
root: options.root ?? cmsGitHubDefaults.root,
|
|
538
|
+
publish: options.publish ?? cmsGitHubDefaults.publish
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
/** Read the Definition file and its preset usage. */
|
|
542
|
+
async function readCmsPresetUsageFile(file, projectRoot, parseAst) {
|
|
543
|
+
return readCmsPresetUsage(await readFile(file, "utf8"), resolve(file), projectRoot, parseAst);
|
|
544
|
+
}
|
|
545
|
+
const contentFilePattern = /^content\.[cm]?[jt]s$/;
|
|
546
|
+
/**
|
|
547
|
+
* Whether `server/content.ts` selects the `cms` preset, read synchronously so `vitehub()` can enable Workspace,
|
|
548
|
+
* Database, and Blob while Vite filters plugins. Returns false when the file is missing or ambiguous; the Source and
|
|
549
|
+
* Content plugins report those cases.
|
|
550
|
+
*/
|
|
551
|
+
function usesCmsPresetSync(input, parseAst) {
|
|
552
|
+
return cmsPresetStoreSync(input, parseAst) !== void 0;
|
|
553
|
+
}
|
|
554
|
+
/** The selected preset store, without executing the Content Definition. */
|
|
555
|
+
function cmsPresetStoreSync(input, parseAst) {
|
|
556
|
+
const root = resolve(input.projectRoot);
|
|
557
|
+
const files = (input.serverDirs?.map((directory) => resolve(root, directory)) ?? [resolve(root, "server")]).flatMap((directory) => {
|
|
558
|
+
try {
|
|
559
|
+
return readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && contentFilePattern.test(entry.name)).map((entry) => join(directory, entry.name));
|
|
560
|
+
} catch {
|
|
561
|
+
return [];
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
if (files.length !== 1) return void 0;
|
|
565
|
+
const file = files[0];
|
|
566
|
+
const source = readFileSync(file, "utf8");
|
|
567
|
+
if (lastPresetCheck?.file !== file || lastPresetCheck.source !== source) {
|
|
568
|
+
const usage = readCmsPresetUsage(source, file, root, parseAst);
|
|
569
|
+
lastPresetCheck = {
|
|
570
|
+
file,
|
|
571
|
+
source,
|
|
572
|
+
store: usage ? cmsStoreOf(usage.options) : void 0
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
return lastPresetCheck.store;
|
|
576
|
+
}
|
|
577
|
+
let lastPresetCheck;
|
|
578
|
+
/** Export of the generated module that holds the Workspace Definition. */
|
|
579
|
+
const cmsWorkspaceExport = "contentWorkspace";
|
|
580
|
+
/**
|
|
581
|
+
* The generated Workspace Definition module. It only reads the Database registry and creates a lazy store when it
|
|
582
|
+
* loads, so the build can load it to bundle Workspace assets. The GitHub store reads its token on first use.
|
|
583
|
+
*/
|
|
584
|
+
function renderCmsWorkspaceModule(plan, imports) {
|
|
585
|
+
if (plan.store === "github" && plan.github) return renderGitHubWorkspaceModule(plan, plan.github, imports);
|
|
586
|
+
return [
|
|
587
|
+
"// Generated by @vite-hub/cms for the cms preset in server/content.ts. Do not edit.",
|
|
588
|
+
`import { blob } from ${JSON.stringify(imports.blob)}`,
|
|
589
|
+
`import { useDatabase } from ${JSON.stringify(imports.database)}`,
|
|
590
|
+
`import { defineWorkspace } from ${JSON.stringify(imports.workspace)}`,
|
|
591
|
+
`import { createBlobDatabaseWorkspaceStore } from ${JSON.stringify(imports.blobDatabase)}`,
|
|
592
|
+
"",
|
|
593
|
+
...renderDatabaseLookup(plan.database),
|
|
594
|
+
"",
|
|
595
|
+
`export const ${cmsWorkspaceExport} = defineWorkspace({`,
|
|
596
|
+
" store: createBlobDatabaseWorkspaceStore({",
|
|
597
|
+
` blob: blob.store(${JSON.stringify(plan.blob ?? "default")}),`,
|
|
598
|
+
" database,",
|
|
599
|
+
` workspace: ${JSON.stringify(plan.workspace)},`,
|
|
600
|
+
" }),",
|
|
601
|
+
"})",
|
|
602
|
+
""
|
|
603
|
+
].join("\n");
|
|
604
|
+
}
|
|
605
|
+
function renderGitHubWorkspaceModule(plan, github, imports) {
|
|
606
|
+
return [
|
|
607
|
+
"// Generated by @vite-hub/cms for the cms preset in server/content.ts. Do not edit.",
|
|
608
|
+
`import { useDatabase } from ${JSON.stringify(imports.database)}`,
|
|
609
|
+
`import { defineWorkspace } from ${JSON.stringify(imports.workspace)}`,
|
|
610
|
+
"",
|
|
611
|
+
"// The Database holds editor sessions only. Documents and their history live in the repository.",
|
|
612
|
+
...renderDatabaseLookup(plan.database),
|
|
613
|
+
"",
|
|
614
|
+
`export const ${cmsWorkspaceExport} = defineWorkspace({`,
|
|
615
|
+
" store: {",
|
|
616
|
+
" driver: \"github\",",
|
|
617
|
+
...github.repo ? [` repository: ${JSON.stringify(github.repo)},`] : [],
|
|
618
|
+
` branch: ${JSON.stringify(github.branch)},`,
|
|
619
|
+
` root: ${JSON.stringify(github.root)},`,
|
|
620
|
+
` refs: { published: ${JSON.stringify(github.branch)}, draft: ${JSON.stringify(github.draftBranch)} },`,
|
|
621
|
+
" database,",
|
|
622
|
+
" },",
|
|
623
|
+
" rules: { \"**\": { write: false } },",
|
|
624
|
+
"})",
|
|
625
|
+
""
|
|
626
|
+
].join("\n");
|
|
627
|
+
}
|
|
628
|
+
//#endregion
|
|
629
|
+
//#region src/cli.ts
|
|
630
|
+
const rolesUsage = "vitehub cms roles [--json]";
|
|
631
|
+
function renderActions(actions) {
|
|
632
|
+
return actions?.length ? actions.join(", ") : "-";
|
|
633
|
+
}
|
|
634
|
+
/** Prints each CMS role with its `content` and `comment` permissions. `--json` prints them as JSON. */
|
|
635
|
+
async function runCmsRoles(args, streams) {
|
|
636
|
+
const unknown = args.find((arg) => arg !== "--json");
|
|
637
|
+
if (unknown !== void 0) {
|
|
638
|
+
streams.stderr.write(`Unknown argument ${JSON.stringify(unknown)}. Usage: ${rolesUsage}\n`);
|
|
639
|
+
return 1;
|
|
640
|
+
}
|
|
641
|
+
const { cmsRoles } = await import("./access.js");
|
|
642
|
+
const roles = Object.entries(cmsRoles).map(([name, role]) => ({
|
|
643
|
+
name,
|
|
644
|
+
content: [...role.statements.content ?? []],
|
|
645
|
+
comment: [...role.statements.comment ?? []]
|
|
646
|
+
}));
|
|
647
|
+
if (args.includes("--json")) {
|
|
648
|
+
streams.stdout.write(`${JSON.stringify({ roles }, null, 2)}\n`);
|
|
649
|
+
return 0;
|
|
650
|
+
}
|
|
651
|
+
const rows = [[
|
|
652
|
+
"Role",
|
|
653
|
+
"Content",
|
|
654
|
+
"Comments"
|
|
655
|
+
], ...roles.map((role) => [
|
|
656
|
+
role.name,
|
|
657
|
+
renderActions(role.content),
|
|
658
|
+
renderActions(role.comment)
|
|
659
|
+
])];
|
|
660
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
661
|
+
for (const row of rows) streams.stdout.write(`${row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()}\n`);
|
|
662
|
+
streams.stdout.write([
|
|
663
|
+
"",
|
|
664
|
+
"Roles live in user.role of the Better Auth admin plugin, admin(cmsAccess). Several roles are separated by commas.",
|
|
665
|
+
"New users get user, which has no CMS permission. admin also has every user and session permission of Better Auth.",
|
|
666
|
+
"Change a role with auth.api.setRole() or in the Console Auth section.",
|
|
667
|
+
""
|
|
668
|
+
].join("\n"));
|
|
669
|
+
return 0;
|
|
670
|
+
}
|
|
671
|
+
/** The `vitehub cms` commands. */
|
|
672
|
+
function createCmsCliContributor() {
|
|
673
|
+
return { namespaces: [{
|
|
674
|
+
defaultFeature: "roles",
|
|
675
|
+
description: "Inspect the CMS roles and their permissions.",
|
|
676
|
+
features: [{
|
|
677
|
+
description: "List each CMS role with the Content and Comments actions it allows.",
|
|
678
|
+
name: "roles",
|
|
679
|
+
run: async (args, context) => await runCmsRoles(args, context),
|
|
680
|
+
usage: rolesUsage
|
|
681
|
+
}],
|
|
682
|
+
name: "cms"
|
|
683
|
+
}] };
|
|
684
|
+
}
|
|
685
|
+
//#endregion
|
|
686
|
+
//#region src/vite.ts
|
|
687
|
+
const CMS_VITE_PLUGIN_NAME = "@vite-hub/cms/vite";
|
|
688
|
+
/** Generated Workspace Definition module of the `cms` preset, relative to the project root. */
|
|
689
|
+
const cmsWorkspaceModulePath = ".vitehub/content/workspace.mjs";
|
|
690
|
+
/**
|
|
691
|
+
* Whether `server/content.ts` selects the `cms` preset. `vitehub()` reads it while Vite filters plugins, so the
|
|
692
|
+
* preset turns on Workspace, Database, and Blob without settings. Reads the file without running it.
|
|
693
|
+
*/
|
|
694
|
+
function usesCms(input) {
|
|
695
|
+
return usesCmsPresetSync(input, parseAst);
|
|
696
|
+
}
|
|
697
|
+
/** The selected CMS store, so framework integrations enable only the services it needs. */
|
|
698
|
+
function cmsStore(input) {
|
|
699
|
+
return cmsPresetStoreSync(input, parseAst);
|
|
700
|
+
}
|
|
701
|
+
const defaultImports = {
|
|
702
|
+
blob: "@vite-hub/blob",
|
|
703
|
+
blobDatabase: "@vite-hub/workspace/blob-database",
|
|
704
|
+
contentDatabase: "@vite-hub/content/database",
|
|
705
|
+
database: "@vite-hub/database",
|
|
706
|
+
workspace: "@vite-hub/workspace"
|
|
707
|
+
};
|
|
708
|
+
const workspacePluginName = "@vite-hub/workspace/vite";
|
|
709
|
+
const databasePluginName = "@vite-hub/database/vite";
|
|
710
|
+
const blobPluginName = "@vite-hub/blob/vite";
|
|
711
|
+
async function writeFileIfChanged(file, contents) {
|
|
712
|
+
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
713
|
+
await mkdir(dirname(file), { recursive: true });
|
|
714
|
+
await writeFile(file, contents, "utf8");
|
|
715
|
+
}
|
|
716
|
+
function absoluteDirs(root, directories) {
|
|
717
|
+
return directories?.map((directory) => resolve(root, directory));
|
|
718
|
+
}
|
|
719
|
+
function pluginByName(config, name) {
|
|
720
|
+
return config.plugins.find((plugin) => plugin.name === name);
|
|
721
|
+
}
|
|
722
|
+
function databaseDiscoveryRoot(plugins, fallback) {
|
|
723
|
+
const database = plugins?.find((plugin) => Reflect.get(Object(plugin), "name") === databasePluginName);
|
|
724
|
+
const api = Reflect.get(Object(database), "api");
|
|
725
|
+
const getProjectRoot = Reflect.get(Object(api), "getProjectRoot");
|
|
726
|
+
if (typeof getProjectRoot === "function") {
|
|
727
|
+
const rootDir = Reflect.apply(getProjectRoot, void 0, []);
|
|
728
|
+
if (typeof rootDir === "string") return rootDir;
|
|
729
|
+
}
|
|
730
|
+
const getConfig = Reflect.get(Object(api), "getConfig");
|
|
731
|
+
if (typeof getConfig === "function") {
|
|
732
|
+
const rootDir = Reflect.get(Object(Reflect.apply(getConfig, database, [])), "rootDir");
|
|
733
|
+
if (typeof rootDir === "string") return rootDir;
|
|
734
|
+
}
|
|
735
|
+
return fallback;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* The other plugins of the app. `vitehub()` nests the CMS plugin in an array, and the Database contributions that
|
|
739
|
+
* the hooks collect would call the hook again through that nested copy, so flatten first.
|
|
740
|
+
*/
|
|
741
|
+
async function pluginsWithoutCms(plugins) {
|
|
742
|
+
return (await flattenPluginOptions(plugins)).filter((plugin) => Reflect.get(plugin, "name") !== CMS_VITE_PLUGIN_NAME);
|
|
743
|
+
}
|
|
744
|
+
/** Store names of the Blob plugin, or false when Blob is off. */
|
|
745
|
+
function blobStoreNames(plugin) {
|
|
746
|
+
if (!plugin) return false;
|
|
747
|
+
const getConfig = Reflect.get(Object(Reflect.get(plugin, "api")), "getConfig");
|
|
748
|
+
if (!(getConfig instanceof Function)) return false;
|
|
749
|
+
const blob = Reflect.get(Object(Reflect.apply(getConfig, void 0, [])), "blob");
|
|
750
|
+
if (blob === null || Object(blob) !== blob) return false;
|
|
751
|
+
const stores = Reflect.get(Object(blob), "stores");
|
|
752
|
+
return stores !== null && Object(stores) === stores ? Object.keys(Object(stores)) : ["default"];
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* CMS build integration. When `server/content.ts` selects the `cms` preset, it contributes the preset's Workspace
|
|
756
|
+
* through `vitehub.workspaces`, and the Workspace history tables through `vitehub.databases`. When the app has no
|
|
757
|
+
* Database Definition, the tables go to the implicit `default` Database of `@vite-hub/database`. It checks that Workspace, Database, and Blob are enabled, and restarts the
|
|
758
|
+
* dev server when the selection changes. Apps without the preset are unaffected.
|
|
759
|
+
*/
|
|
760
|
+
function hubCms(options = {}) {
|
|
761
|
+
const imports = {
|
|
762
|
+
...defaultImports,
|
|
763
|
+
...options.imports
|
|
764
|
+
};
|
|
765
|
+
let projectRoot;
|
|
766
|
+
let serverDirs;
|
|
767
|
+
let resolvedPlugins;
|
|
768
|
+
async function resolvePlan(input) {
|
|
769
|
+
const root = resolve(input.projectRoot);
|
|
770
|
+
const file = await findContentEntry({
|
|
771
|
+
projectRoot: root,
|
|
772
|
+
serverDirs: input.serverDirs?.slice()
|
|
773
|
+
});
|
|
774
|
+
if (!file) return;
|
|
775
|
+
const usage = await readCmsPresetUsageFile(file, root, parseAst);
|
|
776
|
+
if (!usage) return;
|
|
777
|
+
const { discoverDatabaseDefinitions, resolveDefaultDatabase } = await import("@vite-hub/database/config");
|
|
778
|
+
return resolveCmsPresetPlan(usage, {
|
|
779
|
+
names: [...discoverDatabaseDefinitions(resolve(input.databaseRoot ?? root), { serverDirs: absoluteDirs(root, input.serverDirs) }).map((definition) => definition.name), ...(input.contributedDefinitions ?? []).map((definition) => definition.name)],
|
|
780
|
+
resolveDefault: resolveDefaultDatabase
|
|
781
|
+
}, root);
|
|
782
|
+
}
|
|
783
|
+
return {
|
|
784
|
+
name: CMS_VITE_PLUGIN_NAME,
|
|
785
|
+
enforce: "post",
|
|
786
|
+
api: { resolvePlan },
|
|
787
|
+
vitehub: {
|
|
788
|
+
cli: async () => {
|
|
789
|
+
if (!await findContentEntry({
|
|
790
|
+
projectRoot: projectRoot ?? process.cwd(),
|
|
791
|
+
serverDirs
|
|
792
|
+
})) return;
|
|
793
|
+
return createCmsCliContributor();
|
|
794
|
+
},
|
|
795
|
+
inspect: async () => {
|
|
796
|
+
const root = projectRoot ?? process.cwd();
|
|
797
|
+
const file = await findContentEntry({
|
|
798
|
+
projectRoot: root,
|
|
799
|
+
serverDirs
|
|
800
|
+
});
|
|
801
|
+
const usage = file ? await readCmsPresetUsageFile(file, root, parseAst) : void 0;
|
|
802
|
+
if (!usage) return;
|
|
803
|
+
return { definitions: [{
|
|
804
|
+
kind: "cms",
|
|
805
|
+
label: "CMS",
|
|
806
|
+
list: () => [{
|
|
807
|
+
fields: [
|
|
808
|
+
{
|
|
809
|
+
label: "Store",
|
|
810
|
+
value: cmsStoreOf(usage.options)
|
|
811
|
+
},
|
|
812
|
+
{
|
|
813
|
+
label: "Workspace",
|
|
814
|
+
value: usage.options.workspace ?? "content"
|
|
815
|
+
},
|
|
816
|
+
{
|
|
817
|
+
label: "Access",
|
|
818
|
+
value: usage.authorize === "unknown" ? "Indeterminate (object spread may supply authorize)" : usage.authorize ? "The app's defineContent({ authorize })" : usage.options.access === "roles" ? "CMS roles of the Better Auth admin plugin (vitehub cms roles)" : "No policy (all actions denied)"
|
|
819
|
+
}
|
|
820
|
+
],
|
|
821
|
+
file: relativeDefinitionFile(root, usage.file),
|
|
822
|
+
name: usage.options.workspace ?? "content",
|
|
823
|
+
source: "server-content"
|
|
824
|
+
}]
|
|
825
|
+
}] };
|
|
826
|
+
},
|
|
827
|
+
async workspaces(context) {
|
|
828
|
+
const projectRoot = context.projectRoot ?? context.root;
|
|
829
|
+
const otherPlugins = await pluginsWithoutCms(context.plugins);
|
|
830
|
+
const databaseRoot = databaseDiscoveryRoot(otherPlugins, projectRoot);
|
|
831
|
+
const { collectDatabaseContributions } = await import("@vite-hub/database/vite");
|
|
832
|
+
const contributed = await collectDatabaseContributions(otherPlugins, {
|
|
833
|
+
root: context.root,
|
|
834
|
+
rootDir: databaseRoot,
|
|
835
|
+
projectRoot,
|
|
836
|
+
serverDirs: context.serverDirs ?? serverDirs,
|
|
837
|
+
plugins: otherPlugins
|
|
838
|
+
});
|
|
839
|
+
const plan = await resolvePlan({
|
|
840
|
+
databaseRoot,
|
|
841
|
+
projectRoot,
|
|
842
|
+
serverDirs: context.serverDirs ?? serverDirs,
|
|
843
|
+
contributedDefinitions: contributed.definitions
|
|
844
|
+
});
|
|
845
|
+
const module = resolve(projectRoot, cmsWorkspaceModulePath);
|
|
846
|
+
if (!plan) {
|
|
847
|
+
await rm(module, { force: true });
|
|
848
|
+
return [];
|
|
849
|
+
}
|
|
850
|
+
await writeFileIfChanged(module, renderCmsWorkspaceModule(plan, imports));
|
|
851
|
+
return [{
|
|
852
|
+
definition: {
|
|
853
|
+
export: cmsWorkspaceExport,
|
|
854
|
+
module
|
|
855
|
+
},
|
|
856
|
+
name: plan.workspace,
|
|
857
|
+
reason: "Stores the documents of the Content cms preset."
|
|
858
|
+
}];
|
|
859
|
+
},
|
|
860
|
+
async databases(context) {
|
|
861
|
+
const root = projectRoot ?? context.projectRoot ?? context.rootDir ?? context.root ?? process.cwd();
|
|
862
|
+
const otherPlugins = await pluginsWithoutCms(resolvedPlugins ?? context.plugins);
|
|
863
|
+
const { collectDatabaseContributions } = await import("@vite-hub/database/vite");
|
|
864
|
+
const contributed = await collectDatabaseContributions(otherPlugins, {
|
|
865
|
+
...context,
|
|
866
|
+
rootDir: context.rootDir ?? root,
|
|
867
|
+
projectRoot: context.projectRoot ?? root,
|
|
868
|
+
plugins: otherPlugins
|
|
869
|
+
});
|
|
870
|
+
const plan = await resolvePlan({
|
|
871
|
+
databaseRoot: context.rootDir ?? root,
|
|
872
|
+
projectRoot: root,
|
|
873
|
+
serverDirs: serverDirs ?? context.serverDirs?.slice(),
|
|
874
|
+
contributedDefinitions: contributed.definitions
|
|
875
|
+
});
|
|
876
|
+
if (!plan) return [];
|
|
877
|
+
return [...plan.store === "github" ? [] : [{
|
|
878
|
+
database: plan.database,
|
|
879
|
+
definition: {
|
|
880
|
+
export: "workspaceHistorySchema",
|
|
881
|
+
module: imports.blobDatabase
|
|
882
|
+
},
|
|
883
|
+
name: "content-history",
|
|
884
|
+
reason: "Stores the history of Content documents."
|
|
885
|
+
}], ...imports.contentDatabase ? [{
|
|
886
|
+
database: plan.database,
|
|
887
|
+
definition: {
|
|
888
|
+
export: "contentSessionsSchema",
|
|
889
|
+
module: imports.contentDatabase
|
|
890
|
+
},
|
|
891
|
+
name: "content-sessions",
|
|
892
|
+
reason: "Stores presence and edit leases of Content documents."
|
|
893
|
+
}] : []];
|
|
894
|
+
}
|
|
895
|
+
},
|
|
896
|
+
config: {
|
|
897
|
+
order: "pre",
|
|
898
|
+
handler(config) {
|
|
899
|
+
const viteConfig = config;
|
|
900
|
+
projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(viteConfig.root || process.cwd());
|
|
901
|
+
serverDirs = viteConfig[VITEHUB_SERVER_DIRS]?.slice();
|
|
902
|
+
}
|
|
903
|
+
},
|
|
904
|
+
async configResolved(config) {
|
|
905
|
+
const viteConfig = config;
|
|
906
|
+
resolvedPlugins = config.plugins;
|
|
907
|
+
projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root);
|
|
908
|
+
serverDirs = viteConfig["__vitehubServerDirs"]?.slice() ?? serverDirs;
|
|
909
|
+
const plan = await resolvePlan({
|
|
910
|
+
databaseRoot: config.root,
|
|
911
|
+
projectRoot,
|
|
912
|
+
serverDirs
|
|
913
|
+
});
|
|
914
|
+
if (!plan) return;
|
|
915
|
+
const missing = [
|
|
916
|
+
pluginByName(config, workspacePluginName) ? void 0 : "workspace",
|
|
917
|
+
pluginByName(config, databasePluginName) || viteConfig["__vitehubNitroConfigContext"] ? void 0 : "database",
|
|
918
|
+
plan.store === "github" || blobStoreNames(pluginByName(config, blobPluginName)) ? void 0 : "blob"
|
|
919
|
+
].filter(Boolean);
|
|
920
|
+
if (missing.length) {
|
|
921
|
+
const setting = missing.map((name) => `${name}: true`).join(", ");
|
|
922
|
+
throw cmsRequirementError(plan.file, projectRoot, `it needs ${missing.join(", ")} enabled. Set vitehub({ ${setting} }) in your Vite config.`);
|
|
923
|
+
}
|
|
924
|
+
if (plan.store === "github" || plan.blob === void 0) return;
|
|
925
|
+
const stores = blobStoreNames(pluginByName(config, blobPluginName)) || [];
|
|
926
|
+
if (!stores.includes(plan.blob)) throw cmsRequirementError(plan.file, projectRoot, `it stores files in Blob store ${JSON.stringify(plan.blob)}, which is not configured. Blob stores: ${stores.map((name) => JSON.stringify(name)).join(", ")}. Choose one with extends: [cms, { blob: ${JSON.stringify(stores[0])} }] or add the store to vitehub({ blob }).`);
|
|
927
|
+
},
|
|
928
|
+
configureServer(server) {
|
|
929
|
+
const root = projectRoot;
|
|
930
|
+
if (!root) return;
|
|
931
|
+
const directories = absoluteDirs(root, serverDirs) ?? [resolve(root, "server")];
|
|
932
|
+
let current = describePlan();
|
|
933
|
+
async function describePlan() {
|
|
934
|
+
try {
|
|
935
|
+
return JSON.stringify(await resolvePlan({
|
|
936
|
+
databaseRoot: server.config.root,
|
|
937
|
+
projectRoot: root,
|
|
938
|
+
serverDirs
|
|
939
|
+
}) ?? null);
|
|
940
|
+
} catch (error) {
|
|
941
|
+
return `error:${error instanceof Error ? error.message : String(error)}`;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
const onChange = (file) => {
|
|
945
|
+
const path = resolve(file);
|
|
946
|
+
if (!directories.some((directory) => dirname(path) === directory) || !/[\\/]content\.[cm]?[jt]s$/.test(path)) return;
|
|
947
|
+
const previous = current;
|
|
948
|
+
current = describePlan();
|
|
949
|
+
Promise.all([previous, current]).then(async ([before, after]) => {
|
|
950
|
+
if (before !== after) await server.restart();
|
|
951
|
+
}).catch((error) => server.config.logger.error(String(error)));
|
|
952
|
+
};
|
|
953
|
+
server.watcher.on("add", onChange);
|
|
954
|
+
server.watcher.on("change", onChange);
|
|
955
|
+
server.watcher.on("unlink", onChange);
|
|
956
|
+
}
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
//#endregion
|
|
960
|
+
export { CMS_VITE_PLUGIN_NAME, cmsPresetModules, cmsStore, cmsWorkspaceModulePath, createCmsCliContributor, hubCms as default, hubCms, readCmsPresetUsage, renderCmsWorkspaceModule, resolveCmsPresetPlan, usesCms };
|