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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 [fullname]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # vite-plugin-decap-cms
2
+
3
+ > A Vite plugin to connect Decap CMS
4
+
5
+ ![NPM Version](https://img.shields.io/npm/v/vite-plugin-decap-cms)
6
+ ![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-decap-cms)
7
+ ![GitHub Issues or Pull Requests](https://img.shields.io/github/issues/ghostrider-05/vite-plugin-decap-cms)
8
+
9
+
10
+ > [!DANGER] Unstable version
11
+ > This plugin has not reached a stable version, 1.0.0, and can include breaking changes following the semver specification. This plugin is open for contributions, both for code, suggestions and (missing) documentation.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pnpm add vite-plugin-decap-cms -D
17
+ npm install vite-plugin-decap-cms -D
18
+ yarn add vite-plugin-decap-cms -D
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```ts
24
+ // vite.config.ts
25
+ import { defineConfig } from 'vite'
26
+ import decap, {
27
+ createFolderCollection,
28
+ createField,
29
+ } from 'vite-plugin-decap-cms'
30
+
31
+ export default defineConfig({
32
+ publicDir: 'public',
33
+ plugins: [
34
+ decap({
35
+ config: {
36
+ backend: {
37
+ name: 'test-repo',
38
+ },
39
+ mediaFolder: '/src/public/',
40
+ collections: [
41
+ createFolderCollection({
42
+ name: 'test',
43
+ label: 'Test collection',
44
+ folder: 'test',
45
+ fields: [
46
+ createField('markdown', { name: 'body' }),
47
+ ],
48
+ }),
49
+ ]
50
+ }
51
+ })
52
+ ],
53
+ })
54
+ ```
55
+
56
+ ## Example
57
+
58
+ See [the documentation](https://vite-plugin-decap.pages.dev) for an example
59
+
60
+ ## Development
61
+
62
+ ```sh
63
+ npm run docs:dev
64
+ npm run cms:dev
65
+ ```
66
+
67
+ ## License
68
+
69
+ [MIT](LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,446 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __objRest = (source, exclude) => {
24
+ var target = {};
25
+ for (var prop in source)
26
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
+ target[prop] = source[prop];
28
+ if (source != null && __getOwnPropSymbols)
29
+ for (var prop of __getOwnPropSymbols(source)) {
30
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
+ target[prop] = source[prop];
32
+ }
33
+ return target;
34
+ };
35
+ var __export = (target, all) => {
36
+ for (var name in all)
37
+ __defProp(target, name, { get: all[name], enumerable: true });
38
+ };
39
+ var __copyProps = (to, from, except, desc) => {
40
+ if (from && typeof from === "object" || typeof from === "function") {
41
+ for (let key of __getOwnPropNames(from))
42
+ if (!__hasOwnProp.call(to, key) && key !== except)
43
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
44
+ }
45
+ return to;
46
+ };
47
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48
+
49
+ // src/index.ts
50
+ var src_exports = {};
51
+ __export(src_exports, {
52
+ VitePress: () => VitePress,
53
+ createField: () => createField,
54
+ createFile: () => createFile,
55
+ createFileCollection: () => createFileCollection,
56
+ createFolderCollection: () => createFolderCollection,
57
+ default: () => VitePluginDecapCMS,
58
+ getGitData: () => getGitData
59
+ });
60
+ module.exports = __toCommonJS(src_exports);
61
+ var import_yaml = require("yaml");
62
+
63
+ // src/util.ts
64
+ var import_child_process = require("child_process");
65
+ function getGitData() {
66
+ const executeGit = (command) => {
67
+ try {
68
+ return (0, import_child_process.execSync)(command).toString("utf8").replace(/[\n\r\s]+$/, "");
69
+ } catch (e) {
70
+ }
71
+ };
72
+ return {
73
+ get branch() {
74
+ return executeGit("git rev-parse --abbrev-ref HEAD");
75
+ },
76
+ get commitSha() {
77
+ return executeGit("git rev-parse HEAD");
78
+ }
79
+ };
80
+ }
81
+ function createField(widget, data) {
82
+ return __spreadProps(__spreadValues({}, data), {
83
+ widget
84
+ });
85
+ }
86
+ function createFolderCollection(data) {
87
+ return data;
88
+ }
89
+ function createFile(data) {
90
+ return data;
91
+ }
92
+ function createFileCollection(data) {
93
+ return data;
94
+ }
95
+ function createOverwriteableField(widget, data, overwrites) {
96
+ if (overwrites != void 0) {
97
+ const toAdd = (key) => {
98
+ if ((overwrites == null ? void 0 : overwrites[key]) != void 0 && data[key] !== overwrites[key])
99
+ data[key] = overwrites[key];
100
+ };
101
+ for (const key of Object.keys(overwrites)) {
102
+ if (key !== "hidden") {
103
+ toAdd(key);
104
+ }
105
+ }
106
+ }
107
+ if ((overwrites == null ? void 0 : overwrites.hidden) && widget !== "hidden")
108
+ return createField("hidden", data);
109
+ else
110
+ return __spreadProps(__spreadValues({}, data), {
111
+ widget
112
+ });
113
+ }
114
+ var VitePress = class {
115
+ /**
116
+ * Create fields for:
117
+ * - navbar
118
+ * - sidebar
119
+ * - aside
120
+ * - outline
121
+ * - lastUpdated
122
+ * - editLink
123
+ * - footer
124
+ * - pageClass
125
+ *
126
+ * Does not create the default page fields, such as title and description.
127
+ * @param options Options for overwriting field data
128
+ * @see https://vitepress.dev/reference/frontmatter-config#default-theme-only
129
+ */
130
+ static createDefaultThemeNormalPageFields(options) {
131
+ const { overwrites } = options != null ? options : {};
132
+ return [
133
+ createOverwriteableField("boolean", {
134
+ name: "navbar",
135
+ label: "Whether to display the navbar",
136
+ default: true,
137
+ required: false
138
+ }, overwrites == null ? void 0 : overwrites.navbar),
139
+ createOverwriteableField("boolean", {
140
+ name: "sidebar",
141
+ label: "Whether to display the sidebar",
142
+ default: true
143
+ }, overwrites == null ? void 0 : overwrites.sidebar),
144
+ // TODO: add aside 'left' option
145
+ createOverwriteableField("boolean", {
146
+ name: "aside",
147
+ label: "Whether to display the aside container",
148
+ default: true
149
+ }, overwrites == null ? void 0 : overwrites.aside),
150
+ // TODO: add support for [number, number] | 'deep' | false
151
+ createOverwriteableField("number", {
152
+ name: "outline",
153
+ label: "The header levels in the outline",
154
+ default: 2
155
+ }, overwrites == null ? void 0 : overwrites.outline),
156
+ // TODO: add support for Date
157
+ createOverwriteableField("boolean", {
158
+ name: "lastUpdated",
159
+ label: "Whether to display last updated text",
160
+ default: true
161
+ }, overwrites == null ? void 0 : overwrites.lastUpdated),
162
+ createOverwriteableField("boolean", {
163
+ name: "editLink",
164
+ label: "Whether to display edit link text",
165
+ default: true
166
+ }, overwrites == null ? void 0 : overwrites.editLink),
167
+ createOverwriteableField("boolean", {
168
+ name: "footer",
169
+ label: "Whether to display footer text",
170
+ default: true
171
+ }, overwrites == null ? void 0 : overwrites.footer),
172
+ createOverwriteableField("string", {
173
+ name: "pageClass",
174
+ label: "Page class",
175
+ required: false
176
+ }, overwrites == null ? void 0 : overwrites.pageClass)
177
+ ];
178
+ }
179
+ /**
180
+ * Create fields for:
181
+ * - title
182
+ * - titleTemplate
183
+ * - description
184
+ * - head
185
+ * @param options.overwrites Overwrite data, such as labels, for the fields
186
+ * @see https://vitepress.dev/reference/frontmatter-config
187
+ */
188
+ static createDefaultPageFields(options) {
189
+ var _a;
190
+ const { additionalFields, overwrites } = options != null ? options : {};
191
+ const fields = [
192
+ createOverwriteableField("string", {
193
+ name: "title",
194
+ label: "Title"
195
+ }, overwrites == null ? void 0 : overwrites.title),
196
+ createOverwriteableField("string", {
197
+ name: "titleTemplate",
198
+ label: "Title template",
199
+ required: false
200
+ }, overwrites == null ? void 0 : overwrites.titleTemplate),
201
+ createOverwriteableField("text", {
202
+ name: "description",
203
+ label: "Description",
204
+ required: false
205
+ }, overwrites == null ? void 0 : overwrites.description),
206
+ createOverwriteableField("list", {
207
+ name: "head",
208
+ label: "Head"
209
+ }, overwrites == null ? void 0 : overwrites.head)
210
+ ];
211
+ return fields.concat(additionalFields != null ? additionalFields : []).concat(createOverwriteableField("markdown", __spreadProps(__spreadValues({}, (_a = options == null ? void 0 : options.markdownOptions) != null ? _a : {}), {
212
+ name: "body",
213
+ label: "Page content"
214
+ }), overwrites == null ? void 0 : overwrites.body));
215
+ }
216
+ static createDefaultPageFolderCollection(name, folder, options) {
217
+ const _a = options != null ? options : {}, { collection } = _a, fieldsOptions = __objRest(_a, ["collection"]);
218
+ const fields = this.createDefaultPageFields(fieldsOptions);
219
+ return createFolderCollection(__spreadProps(__spreadValues({
220
+ name,
221
+ label: name,
222
+ folder
223
+ }, collection != null ? collection : {}), {
224
+ fields
225
+ }));
226
+ }
227
+ static createDefaultPageFile(name, file, options) {
228
+ const _a = options != null ? options : {}, { collection } = _a, fieldsOptions = __objRest(_a, ["collection"]);
229
+ const fields = this.createDefaultPageFields(fieldsOptions);
230
+ return createFile(__spreadProps(__spreadValues({
231
+ name,
232
+ file,
233
+ label: name
234
+ }, collection != null ? collection : {}), {
235
+ fields
236
+ }));
237
+ }
238
+ static createDefaultPageFileCollection(name, files, options) {
239
+ var _a;
240
+ return createFileCollection(__spreadProps(__spreadValues({
241
+ name,
242
+ label: name
243
+ }, (_a = options == null ? void 0 : options.collection) != null ? _a : {}), {
244
+ files: files.map((params) => this.createDefaultPageFile(...params))
245
+ }));
246
+ }
247
+ };
248
+
249
+ // src/files/config.ts
250
+ var objToSnakeCase = (obj) => {
251
+ const ignoredKeys = ["i18n"];
252
+ const camelToSnakeCase = (str) => str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
253
+ return Object.fromEntries(
254
+ Object.entries(obj).map(([k, v]) => [ignoredKeys.includes(k) ? k : camelToSnakeCase(k), v])
255
+ );
256
+ };
257
+ function getBooleanFromEnv(value, command) {
258
+ return value === "dev" ? command === "serve" : value === "prod" ? command === "build" : value != null ? value : false;
259
+ }
260
+ function resolveBackend(options, command) {
261
+ const _a = options, { local, name } = _a, backend = __objRest(_a, ["local", "name"]);
262
+ const branch = "useCurrentBranch" in options && getBooleanFromEnv(options.useCurrentBranch, command) ? getGitData().branch : "branch" in backend ? backend.branch : void 0;
263
+ delete backend.useCurrentBranch;
264
+ const resolved = {
265
+ local_backend: typeof local === "object" ? objToSnakeCase(local) : getBooleanFromEnv(local, command),
266
+ backend: __spreadProps(__spreadValues({}, objToSnakeCase(backend)), {
267
+ branch,
268
+ name
269
+ })
270
+ };
271
+ return resolved;
272
+ }
273
+ function createConfigFile(config, command) {
274
+ const _a = config, { backend, collections } = _a, options = __objRest(_a, ["backend", "collections"]);
275
+ return __spreadProps(__spreadValues(__spreadValues({}, resolveBackend(backend, command)), objToSnakeCase(options)), {
276
+ collections: collections.map((col) => {
277
+ if ("fields" in col) {
278
+ const _a2 = col, { fields } = _a2, data = __objRest(_a2, ["fields"]);
279
+ return __spreadProps(__spreadValues({}, objToSnakeCase(data)), {
280
+ fields: fields.map(objToSnakeCase)
281
+ });
282
+ } else if ("files" in col) {
283
+ const _b = col, { files } = _b, data = __objRest(_b, ["files"]);
284
+ return __spreadProps(__spreadValues({}, objToSnakeCase(data)), {
285
+ files: files.map((file) => {
286
+ const _a3 = file, { fields } = _a3, _data = __objRest(_a3, ["fields"]);
287
+ return __spreadProps(__spreadValues({}, objToSnakeCase(_data)), {
288
+ fields: fields.map(objToSnakeCase)
289
+ });
290
+ })
291
+ });
292
+ } else
293
+ throw new Error("Missing either fields or files property in collection");
294
+ })
295
+ });
296
+ }
297
+
298
+ // src/script.ts
299
+ function createScript(options) {
300
+ const _a = options, {
301
+ useManualInitialization,
302
+ onGenerated: onGenerated,
303
+ onInitialized
304
+ } = _a, eventHooks = __objRest(_a, [
305
+ "useManualInitialization",
306
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
307
+ "onGenerated",
308
+ "onInitialized"
309
+ ]);
310
+ const events = Object.keys(eventHooks).map((hookName) => {
311
+ const hook = eventHooks[hookName];
312
+ if (!hook)
313
+ return null;
314
+ else {
315
+ const name = hookName.slice(2)[0].toLowerCase() + hookName.slice(3);
316
+ return `CMS.registerEventListener({ name: '${name}', handler: data => { function ${hook.toString()}; ${hookName}({ app: CMS, ...data }) } })`;
317
+ }
318
+ }).join("\n");
319
+ return `
320
+ <script>
321
+ ${useManualInitialization ? "window.CMS_MANUAL_INIT = true;" : ""}
322
+ ${onInitialized != void 0 ? `window.onload = () => { function ${onInitialized.toString()}; onInitialized({ app: CMS }) }` : ""}
323
+ ${events}
324
+ </script>`;
325
+ }
326
+
327
+ // src/files/index.ts
328
+ function resolveCdnRoute(options) {
329
+ const getUrl = (host = "https://unpkg.com/", version = "3.1.3") => {
330
+ return `${host.endsWith("/") ? host : host + "/"}decap-cms@^${version}/dist/decap-cms.js`;
331
+ };
332
+ return typeof options === "boolean" ? options ? getUrl() : void 0 : typeof options === "string" ? options : options != void 0 ? getUrl(options.base, options.version) : void 0;
333
+ }
334
+ function getIndexFeatures(options) {
335
+ var _a, _b;
336
+ function useNetlifyIdentity(options2) {
337
+ return options2.config.backend.name === "git-gateway";
338
+ }
339
+ return {
340
+ 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),
341
+ custom_logo: "logoUrl" in options.config ? options.config.logoUrl != void 0 : "logo_url" in options.config ? options.config.logo_url != void 0 : false,
342
+ netlify_identity: useNetlifyIdentity(options),
343
+ config_route: options.config.dir ? options.config.dir + (!options.config.dir.endsWith("/") ? "/" : "") + "config.yml" : void 0
344
+ };
345
+ }
346
+ function createIndexFile(_options) {
347
+ var _a, _b;
348
+ const features = getIndexFeatures(_options);
349
+ const options = _options.login;
350
+ const identifyScript = '<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>';
351
+ return `<!DOCTYPE html>
352
+ <html>
353
+ <head>
354
+ <meta charset="utf-8" />
355
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
356
+ <meta name="robots" content="noindex" />
357
+ <title>${(_a = options == null ? void 0 : options.title) != null ? _a : "Content Manager"}</title>${features.netlify_identity ? identifyScript : ""}
358
+ ${features.config_route ? `<link href="${features.config_route}" type="text/yaml" rel="cms-config-url">` : ""}
359
+ ${((_b = options == null ? void 0 : options.head) != null ? _b : []).join("\n" + " ".repeat(8))}
360
+ </head>
361
+ <body>
362
+ ${features.cdn_route ? `<script src="${features.cdn_route}"></script>` : ""}
363
+ ${_options.script ? createScript(_options.script) : ""}
364
+ </body>
365
+ </html>${features.custom_logo ? `
366
+
367
+ <style>
368
+ span[class*='CustomIconWrapper'] {
369
+ width: auto;
370
+ }
371
+ </style>` : ""}`;
372
+ }
373
+
374
+ // src/files.ts
375
+ var import_promises = require("fs/promises");
376
+ var import_path = require("path");
377
+ function resolveDir(publicDir, dir) {
378
+ return dir ? (0, import_path.isAbsolute)(dir) ? dir : (0, import_path.resolve)(dir) : publicDir;
379
+ }
380
+ async function writeToFolder(folder, options) {
381
+ const dir = folder + (options.subfolder ? import_path.sep + options.subfolder : "");
382
+ await (0, import_promises.mkdir)(dir, { recursive: true });
383
+ for (const file of options.files.filter((f) => !f.skip)) {
384
+ await (0, import_promises.writeFile)(dir + import_path.sep + file.name, file.content, {
385
+ encoding: "utf-8"
386
+ });
387
+ }
388
+ }
389
+
390
+ // src/index.ts
391
+ function validateLoadOptions(options) {
392
+ var _a;
393
+ const valid = ["npm", "cdn"].includes((_a = options == null ? void 0 : options.method) != null ? _a : "cdn");
394
+ if (!valid)
395
+ throw new Error("Invalid load options for decap-cms provided");
396
+ }
397
+ async function updateConfig(options, config) {
398
+ var _a, _b, _c, _d, _e, _f;
399
+ validateLoadOptions(options.load);
400
+ const loginFile = createIndexFile(options);
401
+ const configFile = createConfigFile(options.config, config.command);
402
+ await writeToFolder(
403
+ resolveDir(config.publicDir, options.dir),
404
+ {
405
+ subfolder: "admin",
406
+ files: [
407
+ { name: "index.html", content: loginFile },
408
+ { name: "config.yml", content: (0, import_yaml.stringify)(configFile, (_a = options.yml) == null ? void 0 : _a.replacer, (_b = options.yml) == null ? void 0 : _b.options) }
409
+ // { name: 'npm.js', content: createCustomScript(), skip: options.load?.method !== 'npm' },
410
+ ]
411
+ }
412
+ );
413
+ await ((_d = (_c = options.script) == null ? void 0 : _c.onConfigUpdated) == null ? void 0 : _d.call(_c));
414
+ if (config.command === "build") {
415
+ await ((_f = (_e = options.script) == null ? void 0 : _e.onGenerated) == null ? void 0 : _f.call(_e));
416
+ }
417
+ }
418
+ function VitePluginDecapCMS(options) {
419
+ let stored = null;
420
+ const debug = (...str) => {
421
+ if (options.debug)
422
+ console.debug(str);
423
+ };
424
+ return {
425
+ name: "vite-plugin-decap-cms",
426
+ async configResolved(config) {
427
+ const isUpdated = stored != null ? stored.command !== config.command || stored.publicDir !== config.publicDir : true;
428
+ if (isUpdated) {
429
+ await updateConfig(options, config);
430
+ stored = config;
431
+ debug("\nUpdated Decap CMS configuration");
432
+ } else {
433
+ debug("\nSkipped updating Decap CMS");
434
+ }
435
+ }
436
+ };
437
+ }
438
+ // Annotate the CommonJS export names for ESM import in node:
439
+ 0 && (module.exports = {
440
+ VitePress,
441
+ createField,
442
+ createFile,
443
+ createFileCollection,
444
+ createFolderCollection,
445
+ getGitData
446
+ });