vite-plugin-decap-cms 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,419 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+
33
+ // src/index.ts
34
+ import { stringify } from "yaml";
35
+
36
+ // src/util.ts
37
+ import { execSync } from "child_process";
38
+ function getGitData() {
39
+ const executeGit = (command) => {
40
+ try {
41
+ return execSync(command).toString("utf8").replace(/[\n\r\s]+$/, "");
42
+ } catch (e) {
43
+ }
44
+ };
45
+ return {
46
+ get branch() {
47
+ return executeGit("git rev-parse --abbrev-ref HEAD");
48
+ },
49
+ get commitSha() {
50
+ return executeGit("git rev-parse HEAD");
51
+ }
52
+ };
53
+ }
54
+ function createField(widget, data) {
55
+ return __spreadProps(__spreadValues({}, data), {
56
+ widget
57
+ });
58
+ }
59
+ function createFolderCollection(data) {
60
+ return data;
61
+ }
62
+ function createFile(data) {
63
+ return data;
64
+ }
65
+ function createFileCollection(data) {
66
+ return data;
67
+ }
68
+ function createOverwriteableField(widget, data, overwrites) {
69
+ if (overwrites != void 0) {
70
+ const toAdd = (key) => {
71
+ if ((overwrites == null ? void 0 : overwrites[key]) != void 0 && data[key] !== overwrites[key])
72
+ data[key] = overwrites[key];
73
+ };
74
+ for (const key of Object.keys(overwrites)) {
75
+ if (key !== "hidden") {
76
+ toAdd(key);
77
+ }
78
+ }
79
+ }
80
+ if ((overwrites == null ? void 0 : overwrites.hidden) && widget !== "hidden")
81
+ return createField("hidden", data);
82
+ else
83
+ return __spreadProps(__spreadValues({}, data), {
84
+ widget
85
+ });
86
+ }
87
+ var VitePress = class {
88
+ /**
89
+ * Create fields for:
90
+ * - navbar
91
+ * - sidebar
92
+ * - aside
93
+ * - outline
94
+ * - lastUpdated
95
+ * - editLink
96
+ * - footer
97
+ * - pageClass
98
+ *
99
+ * Does not create the default page fields, such as title and description.
100
+ * @param options Options for overwriting field data
101
+ * @see https://vitepress.dev/reference/frontmatter-config#default-theme-only
102
+ */
103
+ static createDefaultThemeNormalPageFields(options) {
104
+ const { overwrites } = options != null ? options : {};
105
+ return [
106
+ createOverwriteableField("boolean", {
107
+ name: "navbar",
108
+ label: "Whether to display the navbar",
109
+ default: true,
110
+ required: false
111
+ }, overwrites == null ? void 0 : overwrites.navbar),
112
+ createOverwriteableField("boolean", {
113
+ name: "sidebar",
114
+ label: "Whether to display the sidebar",
115
+ default: true
116
+ }, overwrites == null ? void 0 : overwrites.sidebar),
117
+ // TODO: add aside 'left' option
118
+ createOverwriteableField("boolean", {
119
+ name: "aside",
120
+ label: "Whether to display the aside container",
121
+ default: true
122
+ }, overwrites == null ? void 0 : overwrites.aside),
123
+ // TODO: add support for [number, number] | 'deep' | false
124
+ createOverwriteableField("number", {
125
+ name: "outline",
126
+ label: "The header levels in the outline",
127
+ default: 2
128
+ }, overwrites == null ? void 0 : overwrites.outline),
129
+ // TODO: add support for Date
130
+ createOverwriteableField("boolean", {
131
+ name: "lastUpdated",
132
+ label: "Whether to display last updated text",
133
+ default: true
134
+ }, overwrites == null ? void 0 : overwrites.lastUpdated),
135
+ createOverwriteableField("boolean", {
136
+ name: "editLink",
137
+ label: "Whether to display edit link text",
138
+ default: true
139
+ }, overwrites == null ? void 0 : overwrites.editLink),
140
+ createOverwriteableField("boolean", {
141
+ name: "footer",
142
+ label: "Whether to display footer text",
143
+ default: true
144
+ }, overwrites == null ? void 0 : overwrites.footer),
145
+ createOverwriteableField("string", {
146
+ name: "pageClass",
147
+ label: "Page class",
148
+ required: false
149
+ }, overwrites == null ? void 0 : overwrites.pageClass)
150
+ ];
151
+ }
152
+ /**
153
+ * Create fields for:
154
+ * - title
155
+ * - titleTemplate
156
+ * - description
157
+ * - head
158
+ * @param options.overwrites Overwrite data, such as labels, for the fields
159
+ * @see https://vitepress.dev/reference/frontmatter-config
160
+ */
161
+ static createDefaultPageFields(options) {
162
+ var _a;
163
+ const { additionalFields, overwrites } = options != null ? options : {};
164
+ const fields = [
165
+ createOverwriteableField("string", {
166
+ name: "title",
167
+ label: "Title"
168
+ }, overwrites == null ? void 0 : overwrites.title),
169
+ createOverwriteableField("string", {
170
+ name: "titleTemplate",
171
+ label: "Title template",
172
+ required: false
173
+ }, overwrites == null ? void 0 : overwrites.titleTemplate),
174
+ createOverwriteableField("text", {
175
+ name: "description",
176
+ label: "Description",
177
+ required: false
178
+ }, overwrites == null ? void 0 : overwrites.description),
179
+ createOverwriteableField("list", {
180
+ name: "head",
181
+ label: "Head"
182
+ }, overwrites == null ? void 0 : overwrites.head)
183
+ ];
184
+ return fields.concat(additionalFields != null ? additionalFields : []).concat(createOverwriteableField("markdown", __spreadProps(__spreadValues({}, (_a = options == null ? void 0 : options.markdownOptions) != null ? _a : {}), {
185
+ name: "body",
186
+ label: "Page content"
187
+ }), overwrites == null ? void 0 : overwrites.body));
188
+ }
189
+ static createDefaultPageFolderCollection(name, folder, options) {
190
+ const _a = options != null ? options : {}, { collection } = _a, fieldsOptions = __objRest(_a, ["collection"]);
191
+ const fields = this.createDefaultPageFields(fieldsOptions);
192
+ return createFolderCollection(__spreadProps(__spreadValues({
193
+ name,
194
+ label: name,
195
+ folder
196
+ }, collection != null ? collection : {}), {
197
+ fields
198
+ }));
199
+ }
200
+ static createDefaultPageFile(name, file, options) {
201
+ const _a = options != null ? options : {}, { collection } = _a, fieldsOptions = __objRest(_a, ["collection"]);
202
+ const fields = this.createDefaultPageFields(fieldsOptions);
203
+ return createFile(__spreadProps(__spreadValues({
204
+ name,
205
+ file,
206
+ label: name
207
+ }, collection != null ? collection : {}), {
208
+ fields
209
+ }));
210
+ }
211
+ static createDefaultPageFileCollection(name, files, options) {
212
+ var _a;
213
+ return createFileCollection(__spreadProps(__spreadValues({
214
+ name,
215
+ label: name
216
+ }, (_a = options == null ? void 0 : options.collection) != null ? _a : {}), {
217
+ files: files.map((params) => this.createDefaultPageFile(...params))
218
+ }));
219
+ }
220
+ };
221
+
222
+ // src/files/config.ts
223
+ var objToSnakeCase = (obj) => {
224
+ const ignoredKeys = ["i18n"];
225
+ const camelToSnakeCase = (str) => str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
226
+ return Object.fromEntries(
227
+ Object.entries(obj).map(([k, v]) => [ignoredKeys.includes(k) ? k : camelToSnakeCase(k), v])
228
+ );
229
+ };
230
+ function getBooleanFromEnv(value, command) {
231
+ return value === "dev" ? command === "serve" : value === "prod" ? command === "build" : value != null ? value : false;
232
+ }
233
+ function resolveBackend(options, command) {
234
+ const _a = options, { local, name } = _a, backend = __objRest(_a, ["local", "name"]);
235
+ const branch = "useCurrentBranch" in options && getBooleanFromEnv(options.useCurrentBranch, command) ? getGitData().branch : "branch" in backend ? backend.branch : void 0;
236
+ delete backend.useCurrentBranch;
237
+ const resolved = {
238
+ local_backend: typeof local === "object" ? objToSnakeCase(local) : getBooleanFromEnv(local, command),
239
+ backend: __spreadProps(__spreadValues({}, objToSnakeCase(backend)), {
240
+ branch,
241
+ name
242
+ })
243
+ };
244
+ return resolved;
245
+ }
246
+ function createConfigFile(config, command) {
247
+ const _a = config, { backend, collections } = _a, options = __objRest(_a, ["backend", "collections"]);
248
+ return __spreadProps(__spreadValues(__spreadValues({}, resolveBackend(backend, command)), objToSnakeCase(options)), {
249
+ collections: collections.map((col) => {
250
+ if ("fields" in col) {
251
+ const _a2 = col, { fields } = _a2, data = __objRest(_a2, ["fields"]);
252
+ return __spreadProps(__spreadValues({}, objToSnakeCase(data)), {
253
+ fields: fields.map(objToSnakeCase)
254
+ });
255
+ } else if ("files" in col) {
256
+ const _b = col, { files } = _b, data = __objRest(_b, ["files"]);
257
+ return __spreadProps(__spreadValues({}, objToSnakeCase(data)), {
258
+ files: files.map((file) => {
259
+ const _a3 = file, { fields } = _a3, _data = __objRest(_a3, ["fields"]);
260
+ return __spreadProps(__spreadValues({}, objToSnakeCase(_data)), {
261
+ fields: fields.map(objToSnakeCase)
262
+ });
263
+ })
264
+ });
265
+ } else
266
+ throw new Error("Missing either fields or files property in collection");
267
+ })
268
+ });
269
+ }
270
+
271
+ // src/script.ts
272
+ function createScript(options) {
273
+ const _a = options, {
274
+ useManualInitialization,
275
+ onGenerated: onGenerated,
276
+ onInitialized
277
+ } = _a, eventHooks = __objRest(_a, [
278
+ "useManualInitialization",
279
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
280
+ "onGenerated",
281
+ "onInitialized"
282
+ ]);
283
+ const events = Object.keys(eventHooks).map((hookName) => {
284
+ const hook = eventHooks[hookName];
285
+ if (!hook)
286
+ return null;
287
+ else {
288
+ const name = hookName.slice(2)[0].toLowerCase() + hookName.slice(3);
289
+ return `CMS.registerEventListener({ name: '${name}', handler: data => { function ${hook.toString()}; ${hookName}({ app: CMS, ...data }) } })`;
290
+ }
291
+ }).join("\n");
292
+ return `
293
+ <script>
294
+ ${useManualInitialization ? "window.CMS_MANUAL_INIT = true;" : ""}
295
+ ${onInitialized != void 0 ? `window.onload = () => { function ${onInitialized.toString()}; onInitialized({ app: CMS }) }` : ""}
296
+ ${events}
297
+ </script>`;
298
+ }
299
+
300
+ // src/files/index.ts
301
+ function resolveCdnRoute(options) {
302
+ const getUrl = (host = "https://unpkg.com/", version = "3.1.3") => {
303
+ return `${host.endsWith("/") ? host : host + "/"}decap-cms@^${version}/dist/decap-cms.js`;
304
+ };
305
+ return typeof options === "boolean" ? options ? getUrl() : void 0 : typeof options === "string" ? options : options != void 0 ? getUrl(options.base, options.version) : void 0;
306
+ }
307
+ function getIndexFeatures(options) {
308
+ var _a, _b;
309
+ function useNetlifyIdentity(options2) {
310
+ return options2.config.backend.name === "git-gateway";
311
+ }
312
+ return {
313
+ cdn_route: resolveCdnRoute(options.load == void 0 || options.load.method === "cdn" ? (_b = (_a = options.load) == null ? void 0 : _a.options) != null ? _b : true : void 0),
314
+ custom_logo: "logoUrl" in options.config ? options.config.logoUrl != void 0 : "logo_url" in options.config ? options.config.logo_url != void 0 : false,
315
+ netlify_identity: useNetlifyIdentity(options),
316
+ config_route: options.config.dir ? options.config.dir + (!options.config.dir.endsWith("/") ? "/" : "") + "config.yml" : void 0
317
+ };
318
+ }
319
+ function createIndexFile(_options) {
320
+ var _a, _b;
321
+ const features = getIndexFeatures(_options);
322
+ const options = _options.login;
323
+ const identifyScript = '<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>';
324
+ return `<!DOCTYPE html>
325
+ <html>
326
+ <head>
327
+ <meta charset="utf-8" />
328
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
329
+ <meta name="robots" content="noindex" />
330
+ <title>${(_a = options == null ? void 0 : options.title) != null ? _a : "Content Manager"}</title>${features.netlify_identity ? identifyScript : ""}
331
+ ${features.config_route ? `<link href="${features.config_route}" type="text/yaml" rel="cms-config-url">` : ""}
332
+ ${((_b = options == null ? void 0 : options.head) != null ? _b : []).join("\n" + " ".repeat(8))}
333
+ </head>
334
+ <body>
335
+ ${features.cdn_route ? `<script src="${features.cdn_route}"></script>` : ""}
336
+ ${_options.script ? createScript(_options.script) : ""}
337
+ </body>
338
+ </html>${features.custom_logo ? `
339
+
340
+ <style>
341
+ span[class*='CustomIconWrapper'] {
342
+ width: auto;
343
+ }
344
+ </style>` : ""}`;
345
+ }
346
+
347
+ // src/files.ts
348
+ import { mkdir, writeFile } from "fs/promises";
349
+ import { resolve, isAbsolute, sep } from "path";
350
+ function resolveDir(publicDir, dir) {
351
+ return dir ? isAbsolute(dir) ? dir : resolve(dir) : publicDir;
352
+ }
353
+ async function writeToFolder(folder, options) {
354
+ const dir = folder + (options.subfolder ? sep + options.subfolder : "");
355
+ await mkdir(dir, { recursive: true });
356
+ for (const file of options.files.filter((f) => !f.skip)) {
357
+ await writeFile(dir + sep + file.name, file.content, {
358
+ encoding: "utf-8"
359
+ });
360
+ }
361
+ }
362
+
363
+ // src/index.ts
364
+ function validateLoadOptions(options) {
365
+ var _a;
366
+ const valid = ["npm", "cdn"].includes((_a = options == null ? void 0 : options.method) != null ? _a : "cdn");
367
+ if (!valid)
368
+ throw new Error("Invalid load options for decap-cms provided");
369
+ }
370
+ async function updateConfig(options, config) {
371
+ var _a, _b, _c, _d, _e, _f;
372
+ validateLoadOptions(options.load);
373
+ const loginFile = createIndexFile(options);
374
+ const configFile = createConfigFile(options.config, config.command);
375
+ await writeToFolder(
376
+ resolveDir(config.publicDir, options.dir),
377
+ {
378
+ subfolder: "admin",
379
+ files: [
380
+ { name: "index.html", content: loginFile },
381
+ { name: "config.yml", content: stringify(configFile, (_a = options.yml) == null ? void 0 : _a.replacer, (_b = options.yml) == null ? void 0 : _b.options) }
382
+ // { name: 'npm.js', content: createCustomScript(), skip: options.load?.method !== 'npm' },
383
+ ]
384
+ }
385
+ );
386
+ await ((_d = (_c = options.script) == null ? void 0 : _c.onConfigUpdated) == null ? void 0 : _d.call(_c));
387
+ if (config.command === "build") {
388
+ await ((_f = (_e = options.script) == null ? void 0 : _e.onGenerated) == null ? void 0 : _f.call(_e));
389
+ }
390
+ }
391
+ function VitePluginDecapCMS(options) {
392
+ let stored = null;
393
+ const debug = (...str) => {
394
+ if (options.debug)
395
+ console.debug(str);
396
+ };
397
+ return {
398
+ name: "vite-plugin-decap-cms",
399
+ async configResolved(config) {
400
+ const isUpdated = stored != null ? stored.command !== config.command || stored.publicDir !== config.publicDir : true;
401
+ if (isUpdated) {
402
+ await updateConfig(options, config);
403
+ stored = config;
404
+ debug("\nUpdated Decap CMS configuration");
405
+ } else {
406
+ debug("\nSkipped updating Decap CMS");
407
+ }
408
+ }
409
+ };
410
+ }
411
+ export {
412
+ VitePress,
413
+ createField,
414
+ createFile,
415
+ createFileCollection,
416
+ createFolderCollection,
417
+ VitePluginDecapCMS as default,
418
+ getGitData
419
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "vite-plugin-decap-cms",
3
+ "version": "0.1.0",
4
+ "description": "Simplify the configuration of Decap cms for Vite projects",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "vite",
9
+ "vite-plugin",
10
+ "decap-cms"
11
+ ],
12
+ "homepage": "https://github.com/ghostrider-05/vite-plugin-decap-cms",
13
+ "bugs": "https://github.com/ghostrider-05/vite-plugin-decap-cms/issues",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/ghostrider-05/vite-plugin-decap-cms"
17
+ },
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "require": "./dist/index.cjs",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "main": "./dist/index.cjs",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsup src/index.ts --dts --format cjs,esm"
33
+ },
34
+ "dependencies": {
35
+ "yaml": "^2.4.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "18",
39
+ "@typescript-eslint/eslint-plugin": "^7.1.1",
40
+ "@typescript-eslint/parser": "^7.1.1",
41
+ "decap-cms-core": "^3.3.3",
42
+ "eslint": "^8.54.0",
43
+ "tsup": "^8.0.2",
44
+ "typescript": "^5.3.2",
45
+ "vite": "^5.0.2",
46
+ "vitest": "^0.34.6",
47
+ "vue": "^3.3.9"
48
+ },
49
+ "optionalDependencies": {
50
+ "decap-cms-app": "^3.1.2"
51
+ }
52
+ }