kirbyup 3.2.1 → 3.4.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.
@@ -1,931 +0,0 @@
1
- import * as fs from 'node:fs';
2
- import { existsSync } from 'node:fs';
3
- import * as fsp from 'node:fs/promises';
4
- import { readFile } from 'node:fs/promises';
5
- import vuePlugin from '@vitejs/plugin-vue2';
6
- import vueJsxPlugin from '@vitejs/plugin-vue2-jsx';
7
- import { consola } from 'consola';
8
- import { colors } from 'consola/utils';
9
- import { resolve, join, normalize, relative, dirname, basename } from 'pathe';
10
- import { debounce } from 'perfect-debounce';
11
- import externalGlobals from 'rollup-plugin-external-globals';
12
- import { createLogger, createServer, build as build$1, mergeConfig } from 'vite';
13
- import fullReloadPlugin from 'vite-plugin-full-reload';
14
- import * as vueCompilerSfc from 'vue/compiler-sfc';
15
- import { loadConfig as loadConfig$1 } from 'c12';
16
- import postcssDirPseudoClass from 'postcss-dir-pseudo-class';
17
- import postcssrc from 'postcss-load-config';
18
- import postcssLogical from 'postcss-logical';
19
- import MagicString from 'magic-string';
20
- import { createRequire } from 'node:module';
21
- import 'child_process';
22
- import 'path';
23
- import 'process';
24
- import 'stream';
25
- import 'readline';
26
- import { Buffer as Buffer$1 } from 'node:buffer';
27
- import { promisify } from 'node:util';
28
- import { gzip } from 'node:zlib';
29
-
30
- const name = "kirbyup";
31
- const version = "3.2.1";
32
-
33
- function loadConfig(cwd = process.cwd()) {
34
- return loadConfig$1({
35
- cwd,
36
- name: "kirbyup",
37
- rcFile: false,
38
- packageJson: false
39
- });
40
- }
41
- async function resolvePostCSSConfig(cwd) {
42
- try {
43
- return await postcssrc(void 0, void 0, { stopDir: cwd });
44
- } catch (error) {
45
- if (!error.message.includes("No PostCSS Config found"))
46
- throw error;
47
- return {
48
- plugins: [postcssLogical(), postcssDirPseudoClass()]
49
- };
50
- }
51
- }
52
-
53
- class PrettyError extends Error {
54
- constructor(message) {
55
- super(message);
56
- this.name = this.constructor.name;
57
- if (typeof Error.captureStackTrace === "function")
58
- Error.captureStackTrace(this, this.constructor);
59
- else
60
- this.stack = new Error(message).stack;
61
- }
62
- }
63
- function handleError(error) {
64
- consola.error(error.message);
65
- process.exitCode = 1;
66
- }
67
-
68
- function kirbyupBuildCleanupPlugin(options) {
69
- let config;
70
- let devIndexPath;
71
- return {
72
- name: "kirbyup:build-cleanup",
73
- configResolved(resolvedConfig) {
74
- config = resolvedConfig;
75
- devIndexPath = resolve(config.root, options.outDir, "index.dev.mjs");
76
- },
77
- writeBundle() {
78
- if (fs.existsSync(devIndexPath))
79
- fs.unlinkSync(devIndexPath);
80
- }
81
- };
82
- }
83
-
84
- const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//g;
85
- const singlelineCommentsRE = /\/\/.*/g;
86
- const HMR_RUNTIME_ID = "\0plugin-vue2:hmr-runtime";
87
- const JSX_HMR_RUNTIME_ID = "plugin-vue2-jsx:hmr-runtime";
88
- function isHmrRuntimeId(id) {
89
- return id === HMR_RUNTIME_ID || id === JSX_HMR_RUNTIME_ID;
90
- }
91
- const __INJECTED_HMR_CODE__ = `
92
- /** - injected by kirbyup - */
93
- for (const methodName of ['rerender', 'reload']) {
94
- const original = __VUE_HMR_RUNTIME__[methodName]
95
-
96
- __VUE_HMR_RUNTIME__[methodName] = function (id, updatedDef) {
97
- const key = updatedDef?.__file ? '__file' : updatedDef?.__hmrId ? '__hmrId' : null
98
-
99
- if (key) {
100
- const pluginComponents = window.panel.plugins.components
101
- // const usedComponentDefs = window.panel.app.$options.components
102
- const usedComponentDefs = window.panel.app._vnode.componentInstance.$options.components // #33
103
-
104
- for (const componentName in pluginComponents) {
105
- if (updatedDef[key] === pluginComponents[componentName][key]) {
106
- const usedDefinition = usedComponentDefs[componentName].options
107
-
108
- if (map[id].options !== usedDefinition)
109
- map[id].options = usedDefinition
110
-
111
- if (typeof map[id].options.$_isSection !== 'boolean')
112
- map[id].options.$_isSection = /^k-.*-section$/.test(componentName)
113
-
114
- break
115
- }
116
- }
117
- }
118
-
119
- return original.apply(this, arguments)
120
- }
121
- }
122
-
123
- function $_applyKirbyModifications(activeDef, newDef) {
124
- const usedComponentDefs = window.panel.app.$options.components
125
-
126
- if (newDef.template)
127
- newDef.render = null
128
-
129
- if (activeDef.$_isSection)
130
- newDef.$_isSection = true
131
- if (newDef.$_isSection && !newDef.mixins?.[0]?.methods?.load)
132
- newDef.mixins = [activeDef.mixins[0], ...(newDef.mixins || [])]
133
-
134
- if (typeof newDef.extends === 'string') {
135
- if (newDef.extends === activeDef.extends?.options?.name) {
136
- newDef.extends = activeDef.extends
137
- }
138
- else if (usedComponentDefs[newDef.extends]) {
139
- newDef.extends = usedComponentDefs[newDef.extends].extend({
140
- options: newDef,
141
- components: { ...usedComponentDefs, ...(newDef.components || {}) },
142
- })
143
- }
144
- else { newDef.extends = null }
145
- }
146
- }
147
- /** -- */
148
- `;
149
-
150
- function kirbyupGlobImportPlugin() {
151
- let config;
152
- return {
153
- name: "kirbyup:glob-import",
154
- configResolved(resolvedConfig) {
155
- config = resolvedConfig;
156
- },
157
- async transform(code) {
158
- if (!code.includes("kirbyup.import"))
159
- return;
160
- const kirbyupImportRE = /\bkirbyup\.import\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*\)/g;
161
- const noCommentsCode = code.replace(multilineCommentsRE, (m) => " ".repeat(m.length)).replace(singlelineCommentsRE, (m) => " ".repeat(m.length));
162
- let s;
163
- let match;
164
- while (match = kirbyupImportRE.exec(noCommentsCode)) {
165
- const { 0: exp, 1: rawPath, index } = match;
166
- if (!s)
167
- s = new MagicString(code);
168
- s.overwrite(
169
- index,
170
- index + exp.length,
171
- `kirbyup.import(import.meta.glob(${rawPath}, { eager: true }))`
172
- );
173
- }
174
- if (s) {
175
- return {
176
- code: s.toString(),
177
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : void 0
178
- };
179
- }
180
- }
181
- };
182
- }
183
-
184
- const require = createRequire(import.meta.url);
185
- var St = Object.create;
186
- var $ = Object.defineProperty;
187
- var kt = Object.getOwnPropertyDescriptor;
188
- var Tt = Object.getOwnPropertyNames;
189
- var At = Object.getPrototypeOf, Rt = Object.prototype.hasOwnProperty;
190
- var h = /* @__PURE__ */ ((t) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(t, {
191
- get: (e, n) => (typeof require < "u" ? require : e)[n]
192
- }) : t)(function(t) {
193
- if (typeof require < "u") return require.apply(this, arguments);
194
- throw Error('Dynamic require of "' + t + '" is not supported');
195
- });
196
- var l = (t, e) => () => (e || t((e = { exports: {} }).exports, e), e.exports);
197
- var $t = (t, e, n, r) => {
198
- if (e && typeof e == "object" || typeof e == "function")
199
- for (let s of Tt(e))
200
- !Rt.call(t, s) && s !== n && $(t, s, { get: () => e[s], enumerable: !(r = kt(e, s)) || r.enumerable });
201
- return t;
202
- };
203
- var Nt = (t, e, n) => (n = t != null ? St(At(t)) : {}, $t(
204
- // If the importer is in node compatibility mode or this is not an ESM
205
- // file that has been converted to a CommonJS file using a Babel-
206
- // compatible transform (i.e. "__esModule" has not been set), then set
207
- // "default" to the CommonJS "module.exports" for node compatibility.
208
- $(n, "default", { value: t, enumerable: true }) ,
209
- t
210
- ));
211
-
212
- // node_modules/isexe/windows.js
213
- var W = l((Se, H) => {
214
- H.exports = z;
215
- z.sync = Wt;
216
- var j = h("fs");
217
- function Ht(t, e) {
218
- var n = e.pathExt !== void 0 ? e.pathExt : process.env.PATHEXT;
219
- if (!n || (n = n.split(";"), n.indexOf("") !== -1))
220
- return true;
221
- for (var r = 0; r < n.length; r++) {
222
- var s = n[r].toLowerCase();
223
- if (s && t.substr(-s.length).toLowerCase() === s)
224
- return true;
225
- }
226
- return false;
227
- }
228
- function F(t, e, n) {
229
- return !t.isSymbolicLink() && !t.isFile() ? false : Ht(e, n);
230
- }
231
- function z(t, e, n) {
232
- j.stat(t, function(r, s) {
233
- n(r, r ? false : F(s, t, e));
234
- });
235
- }
236
- function Wt(t, e) {
237
- return F(j.statSync(t), t, e);
238
- }
239
- });
240
-
241
- // node_modules/isexe/mode.js
242
- var X = l((ke, B) => {
243
- B.exports = K;
244
- K.sync = Dt;
245
- var D = h("fs");
246
- function K(t, e, n) {
247
- D.stat(t, function(r, s) {
248
- n(r, r ? false : M(s, e));
249
- });
250
- }
251
- function Dt(t, e) {
252
- return M(D.statSync(t), e);
253
- }
254
- function M(t, e) {
255
- return t.isFile() && Kt(t, e);
256
- }
257
- function Kt(t, e) {
258
- var n = t.mode, r = t.uid, s = t.gid, o = e.uid !== void 0 ? e.uid : process.getuid && process.getuid(), i = e.gid !== void 0 ? e.gid : process.getgid && process.getgid(), a = parseInt("100", 8), c = parseInt("010", 8), u = parseInt("001", 8), f = a | c, p = n & u || n & c && s === i || n & a && r === o || n & f && o === 0;
259
- return p;
260
- }
261
- });
262
-
263
- // node_modules/isexe/index.js
264
- var U = l((Ae, G) => {
265
- h("fs"); var v;
266
- process.platform === "win32" || global.TESTING_WINDOWS ? v = W() : v = X();
267
- G.exports = y;
268
- y.sync = Mt;
269
- function y(t, e, n) {
270
- if (typeof e == "function" && (n = e, e = {}), !n) {
271
- if (typeof Promise != "function")
272
- throw new TypeError("callback not provided");
273
- return new Promise(function(r, s) {
274
- y(t, e || {}, function(o, i) {
275
- o ? s(o) : r(i);
276
- });
277
- });
278
- }
279
- v(t, e || {}, function(r, s) {
280
- r && (r.code === "EACCES" || e && e.ignoreErrors) && (r = null, s = false), n(r, s);
281
- });
282
- }
283
- function Mt(t, e) {
284
- try {
285
- return v.sync(t, e || {});
286
- } catch (n) {
287
- if (e && e.ignoreErrors || n.code === "EACCES")
288
- return false;
289
- throw n;
290
- }
291
- }
292
- });
293
-
294
- // node_modules/which/which.js
295
- var et = l((Re, tt) => {
296
- var g = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys", Y = h("path"), Bt = g ? ";" : ":", V = U(), J = (t) => Object.assign(new Error(`not found: ${t}`), { code: "ENOENT" }), Q = (t, e) => {
297
- let n = e.colon || Bt, r = t.match(/\//) || g && t.match(/\\/) ? [""] : [
298
- // windows always checks the cwd first
299
- ...g ? [process.cwd()] : [],
300
- ...(e.path || process.env.PATH || /* istanbul ignore next: very unusual */
301
- "").split(n)
302
- ], s = g ? e.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "", o = g ? s.split(n) : [""];
303
- return g && t.indexOf(".") !== -1 && o[0] !== "" && o.unshift(""), {
304
- pathEnv: r,
305
- pathExt: o,
306
- pathExtExe: s
307
- };
308
- }, Z = (t, e, n) => {
309
- typeof e == "function" && (n = e, e = {}), e || (e = {});
310
- let { pathEnv: r, pathExt: s, pathExtExe: o } = Q(t, e), i = [], a = (u) => new Promise((f, p) => {
311
- if (u === r.length)
312
- return e.all && i.length ? f(i) : p(J(t));
313
- let d = r[u], w = /^".*"$/.test(d) ? d.slice(1, -1) : d, m = Y.join(w, t), b = !w && /^\.[\\\/]/.test(t) ? t.slice(0, 2) + m : m;
314
- f(c(b, u, 0));
315
- }), c = (u, f, p) => new Promise((d, w) => {
316
- if (p === s.length)
317
- return d(a(f + 1));
318
- let m = s[p];
319
- V(u + m, { pathExt: o }, (b, Ot) => {
320
- if (!b && Ot)
321
- if (e.all)
322
- i.push(u + m);
323
- else
324
- return d(u + m);
325
- return d(c(u, f, p + 1));
326
- });
327
- });
328
- return n ? a(0).then((u) => n(null, u), n) : a(0);
329
- }, Xt = (t, e) => {
330
- e = e || {};
331
- let { pathEnv: n, pathExt: r, pathExtExe: s } = Q(t, e), o = [];
332
- for (let i = 0; i < n.length; i++) {
333
- let a = n[i], c = /^".*"$/.test(a) ? a.slice(1, -1) : a, u = Y.join(c, t), f = !c && /^\.[\\\/]/.test(t) ? t.slice(0, 2) + u : u;
334
- for (let p = 0; p < r.length; p++) {
335
- let d = f + r[p];
336
- try {
337
- if (V.sync(d, { pathExt: s }))
338
- if (e.all)
339
- o.push(d);
340
- else
341
- return d;
342
- } catch {
343
- }
344
- }
345
- }
346
- if (e.all && o.length)
347
- return o;
348
- if (e.nothrow)
349
- return null;
350
- throw J(t);
351
- };
352
- tt.exports = Z;
353
- Z.sync = Xt;
354
- });
355
-
356
- // node_modules/path-key/index.js
357
- var rt = l(($e, _) => {
358
- var nt = (t = {}) => {
359
- let e = t.env || process.env;
360
- return (t.platform || process.platform) !== "win32" ? "PATH" : Object.keys(e).reverse().find((r) => r.toUpperCase() === "PATH") || "Path";
361
- };
362
- _.exports = nt;
363
- _.exports.default = nt;
364
- });
365
-
366
- // node_modules/cross-spawn/lib/util/resolveCommand.js
367
- var ct = l((Ne, it) => {
368
- var st = h("path"), Gt = et(), Ut = rt();
369
- function ot(t, e) {
370
- let n = t.options.env || process.env, r = process.cwd(), s = t.options.cwd != null, o = s && process.chdir !== void 0 && !process.chdir.disabled;
371
- if (o)
372
- try {
373
- process.chdir(t.options.cwd);
374
- } catch {
375
- }
376
- let i;
377
- try {
378
- i = Gt.sync(t.command, {
379
- path: n[Ut({ env: n })],
380
- pathExt: e ? st.delimiter : void 0
381
- });
382
- } catch {
383
- } finally {
384
- o && process.chdir(r);
385
- }
386
- return i && (i = st.resolve(s ? t.options.cwd : "", i)), i;
387
- }
388
- function Yt(t) {
389
- return ot(t) || ot(t, true);
390
- }
391
- it.exports = Yt;
392
- });
393
-
394
- // node_modules/cross-spawn/lib/util/escape.js
395
- var ut = l((qe, P) => {
396
- var C = /([()\][%!^"`<>&|;, *?])/g;
397
- function Vt(t) {
398
- return t = t.replace(C, "^$1"), t;
399
- }
400
- function Jt(t, e) {
401
- return t = `${t}`, t = t.replace(/(\\*)"/g, '$1$1\\"'), t = t.replace(/(\\*)$/, "$1$1"), t = `"${t}"`, t = t.replace(C, "^$1"), e && (t = t.replace(C, "^$1")), t;
402
- }
403
- P.exports.command = Vt;
404
- P.exports.argument = Jt;
405
- });
406
-
407
- // node_modules/shebang-regex/index.js
408
- var lt = l((Ie, at) => {
409
- at.exports = /^#!(.*)/;
410
- });
411
-
412
- // node_modules/shebang-command/index.js
413
- var dt = l((Le, pt) => {
414
- var Qt = lt();
415
- pt.exports = (t = "") => {
416
- let e = t.match(Qt);
417
- if (!e)
418
- return null;
419
- let [n, r] = e[0].replace(/#! ?/, "").split(" "), s = n.split("/").pop();
420
- return s === "env" ? r : r ? `${s} ${r}` : s;
421
- };
422
- });
423
-
424
- // node_modules/cross-spawn/lib/util/readShebang.js
425
- var ht = l((je, ft) => {
426
- var O = h("fs"), Zt = dt();
427
- function te(t) {
428
- let n = Buffer.alloc(150), r;
429
- try {
430
- r = O.openSync(t, "r"), O.readSync(r, n, 0, 150, 0), O.closeSync(r);
431
- } catch {
432
- }
433
- return Zt(n.toString());
434
- }
435
- ft.exports = te;
436
- });
437
-
438
- // node_modules/cross-spawn/lib/parse.js
439
- var wt = l((Fe, Et) => {
440
- var ee = h("path"), mt = ct(), gt = ut(), ne = ht(), re = process.platform === "win32", se = /\.(?:com|exe)$/i, oe = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
441
- function ie(t) {
442
- t.file = mt(t);
443
- let e = t.file && ne(t.file);
444
- return e ? (t.args.unshift(t.file), t.command = e, mt(t)) : t.file;
445
- }
446
- function ce(t) {
447
- if (!re)
448
- return t;
449
- let e = ie(t), n = !se.test(e);
450
- if (t.options.forceShell || n) {
451
- let r = oe.test(e);
452
- t.command = ee.normalize(t.command), t.command = gt.command(t.command), t.args = t.args.map((o) => gt.argument(o, r));
453
- let s = [t.command].concat(t.args).join(" ");
454
- t.args = ["/d", "/s", "/c", `"${s}"`], t.command = process.env.comspec || "cmd.exe", t.options.windowsVerbatimArguments = true;
455
- }
456
- return t;
457
- }
458
- function ue(t, e, n) {
459
- e && !Array.isArray(e) && (n = e, e = null), e = e ? e.slice(0) : [], n = Object.assign({}, n);
460
- let r = {
461
- command: t,
462
- args: e,
463
- options: n,
464
- file: void 0,
465
- original: {
466
- command: t,
467
- args: e
468
- }
469
- };
470
- return n.shell ? r : ce(r);
471
- }
472
- Et.exports = ue;
473
- });
474
-
475
- // node_modules/cross-spawn/lib/enoent.js
476
- var bt = l((ze, vt) => {
477
- var S = process.platform === "win32";
478
- function k(t, e) {
479
- return Object.assign(new Error(`${e} ${t.command} ENOENT`), {
480
- code: "ENOENT",
481
- errno: "ENOENT",
482
- syscall: `${e} ${t.command}`,
483
- path: t.command,
484
- spawnargs: t.args
485
- });
486
- }
487
- function ae(t, e) {
488
- if (!S)
489
- return;
490
- let n = t.emit;
491
- t.emit = function(r, s) {
492
- if (r === "exit") {
493
- let o = xt(s, e);
494
- if (o)
495
- return n.call(t, "error", o);
496
- }
497
- return n.apply(t, arguments);
498
- };
499
- }
500
- function xt(t, e) {
501
- return S && t === 1 && !e.file ? k(e.original, "spawn") : null;
502
- }
503
- function le(t, e) {
504
- return S && t === 1 && !e.file ? k(e.original, "spawnSync") : null;
505
- }
506
- vt.exports = {
507
- hookChildProcess: ae,
508
- verifyENOENT: xt,
509
- verifyENOENTSync: le,
510
- notFoundError: k
511
- };
512
- });
513
-
514
- // node_modules/cross-spawn/index.js
515
- var Ct = l((He, E) => {
516
- var yt = h("child_process"), T = wt(), A = bt();
517
- function _t(t, e, n) {
518
- let r = T(t, e, n), s = yt.spawn(r.command, r.args, r.options);
519
- return A.hookChildProcess(s, r), s;
520
- }
521
- function pe(t, e, n) {
522
- let r = T(t, e, n), s = yt.spawnSync(r.command, r.args, r.options);
523
- return s.error = s.error || A.verifyENOENTSync(s.status, r), s;
524
- }
525
- E.exports = _t;
526
- E.exports.spawn = _t;
527
- E.exports.sync = pe;
528
- E.exports._parse = T;
529
- E.exports._enoent = A;
530
- });
531
-
532
- // src/main.ts
533
- Nt(Ct());
534
-
535
- async function findup(cwd, match, options = {}) {
536
- const segments = normalize(cwd).split("/");
537
- while (segments.length > 0) {
538
- const path = segments.join("/") || "/";
539
- const result = await match(path);
540
- if (result || !options.includeParentDirs) {
541
- return result;
542
- }
543
- segments.pop();
544
- }
545
- }
546
- function parsePackageManagerField(packageManager) {
547
- const [name, _version] = (packageManager || "").split("@");
548
- const [version, buildMeta] = _version?.split("+") || [];
549
- if (name && name !== "-" && /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
550
- return { name, version, buildMeta };
551
- }
552
- const sanitized = name.replace(/\W+/g, "");
553
- const warnings = [
554
- `Abnormal characters found in \`packageManager\` field, sanitizing from \`${name}\` to \`${sanitized}\``
555
- ];
556
- return {
557
- name: sanitized,
558
- version,
559
- buildMeta,
560
- warnings
561
- };
562
- }
563
-
564
- const packageManagers = [
565
- {
566
- name: "npm",
567
- command: "npm",
568
- lockFile: "package-lock.json"
569
- },
570
- {
571
- name: "pnpm",
572
- command: "pnpm",
573
- lockFile: "pnpm-lock.yaml",
574
- files: ["pnpm-workspace.yaml"]
575
- },
576
- {
577
- name: "bun",
578
- command: "bun",
579
- lockFile: ["bun.lockb", "bun.lock"]
580
- },
581
- {
582
- name: "yarn",
583
- command: "yarn",
584
- lockFile: "yarn.lock",
585
- files: [".yarnrc.yml"]
586
- },
587
- {
588
- name: "deno",
589
- command: "deno",
590
- lockFile: "deno.lock",
591
- files: ["deno.json"]
592
- }
593
- ];
594
- async function detectPackageManager(cwd, options = {}) {
595
- const detected = await findup(
596
- resolve(cwd || "."),
597
- async (path) => {
598
- if (!options.ignorePackageJSON) {
599
- const packageJSONPath = join(path, "package.json");
600
- if (existsSync(packageJSONPath)) {
601
- const packageJSON = JSON.parse(
602
- await readFile(packageJSONPath, "utf8")
603
- );
604
- if (packageJSON?.packageManager) {
605
- const {
606
- name,
607
- version = "0.0.0",
608
- buildMeta,
609
- warnings
610
- } = parsePackageManagerField(packageJSON.packageManager);
611
- if (name) {
612
- const majorVersion = version.split(".")[0];
613
- const packageManager = packageManagers.find(
614
- (pm) => pm.name === name && pm.majorVersion === majorVersion
615
- ) || packageManagers.find((pm) => pm.name === name);
616
- return {
617
- name,
618
- command: name,
619
- version,
620
- majorVersion,
621
- buildMeta,
622
- warnings,
623
- files: packageManager?.files,
624
- lockFile: packageManager?.lockFile
625
- };
626
- }
627
- }
628
- }
629
- const denoJSONPath = join(path, "deno.json");
630
- if (existsSync(denoJSONPath)) {
631
- return packageManagers.find((pm) => pm.name === "deno");
632
- }
633
- }
634
- if (!options.ignoreLockFile) {
635
- for (const packageManager of packageManagers) {
636
- const detectionsFiles = [
637
- packageManager.lockFile,
638
- packageManager.files
639
- ].flat().filter(Boolean);
640
- if (detectionsFiles.some((file) => existsSync(resolve(path, file)))) {
641
- return {
642
- ...packageManager
643
- };
644
- }
645
- }
646
- }
647
- },
648
- {
649
- includeParentDirs: options.includeParentDirs ?? true
650
- }
651
- );
652
- if (!detected && !options.ignoreArgv) {
653
- const scriptArg = process.argv[1];
654
- if (scriptArg) {
655
- for (const packageManager of packageManagers) {
656
- const re = new RegExp(`[/\\\\]\\.?${packageManager.command}`);
657
- if (re.test(scriptArg)) {
658
- return packageManager;
659
- }
660
- }
661
- }
662
- }
663
- return detected;
664
- }
665
-
666
- function kirbyupHmrPlugin(options) {
667
- let config;
668
- let entry;
669
- let devIndexPath;
670
- return {
671
- name: "kirbyup:hmr",
672
- apply: "serve",
673
- configResolved(resolvedConfig) {
674
- config = resolvedConfig;
675
- entry = resolve(config.root, options.entry);
676
- devIndexPath = resolve(config.root, options.outDir || "", "index.dev.mjs");
677
- },
678
- transform(code, id) {
679
- if (isHmrRuntimeId(id)) {
680
- return code.replace(
681
- // https://github.com/vitejs/vite-plugin-vue2/blob/8de73ea6b8a1df4c14308da2885db195dacc2b14/src/utils/hmrRuntime.ts#L173
682
- /^.*=\s*record\.Ctor\.super\.extend\(options\)/m,
683
- "$_applyKirbyModifications(record.Ctor.options, options) // injected by kirbyup\n$&"
684
- ) + __INJECTED_HMR_CODE__;
685
- }
686
- },
687
- configureServer(server) {
688
- if (!server.httpServer)
689
- return;
690
- server.httpServer.once("listening", async () => {
691
- const entryPath = entry.replace(`${config.root}/`, "");
692
- const { address, family, port } = server.httpServer.address();
693
- const hostname = family === "IPv6" ? `[${address}]` : address;
694
- const baseUrl = `http://${hostname}:${port}${config.base}`;
695
- const entryUrl = new URL(entryPath, baseUrl).href;
696
- const pm = await detectPackageManager(config.root);
697
- await fsp.writeFile(devIndexPath, getViteProxyModule(entryUrl, pm));
698
- });
699
- },
700
- closeBundle() {
701
- if (fs.existsSync(devIndexPath))
702
- fs.unlinkSync(devIndexPath);
703
- }
704
- };
705
- }
706
- function getViteProxyModule(entryUrl, packageManager) {
707
- const pm = packageManager?.name || "npm";
708
- return `
709
- try {
710
- await import("${entryUrl}");
711
- } catch (err) {
712
- console.error(
713
- "[kirbyup] Couldn't connect to the development server. Run \`${pm} run serve\` to start Vite or build the plugin with \`${pm} run build\` so Kirby uses the production version."
714
- );
715
- throw err;
716
- }
717
- `.trimStart();
718
- }
719
-
720
- function toArray(array) {
721
- array ??= [];
722
- return Array.isArray(array) ? array : [array];
723
- }
724
- const compress = promisify(gzip);
725
- async function getCompressedSize(code) {
726
- const size = (await compress(typeof code === "string" ? code : Buffer$1.from(code))).length / 1024;
727
- return ` / gzip: ${size.toFixed(2)} KiB`;
728
- }
729
- async function printFileInfo(root, outDir, filePath, content, type, maxLength) {
730
- const prettyOutDir = `${normalize(relative(root, resolve(root, outDir)))}/`;
731
- const kibs = content.length / 1024;
732
- const compressedSize = await getCompressedSize(content);
733
- const writeColor = type === "chunk" ? colors.cyan : colors.magenta;
734
- consola.log(
735
- colors.white(colors.dim(prettyOutDir)) + writeColor(filePath.padEnd(maxLength + 2)) + colors.dim(`${kibs.toFixed(2)} kB${compressedSize}`)
736
- );
737
- }
738
-
739
- let resolvedKirbyupConfig;
740
- let resolvedPostCssConfig;
741
- const logLevel = "warn";
742
- const logger = createLogger(logLevel);
743
- const loggerWarn = logger.warn;
744
- logger.warn = (msg, options) => {
745
- if (msg.includes("(!) build.outDir"))
746
- return;
747
- loggerWarn(msg, options);
748
- };
749
- function getViteConfig(command, options) {
750
- const aliasDir = resolve(options.cwd, dirname(options.entry));
751
- const { alias = {}, vite, extendViteConfig } = resolvedKirbyupConfig;
752
- const userConfig = vite ?? extendViteConfig ?? {};
753
- const sharedConfig = {
754
- resolve: {
755
- alias: {
756
- "~/": `${aliasDir}/`,
757
- "@/": `${aliasDir}/`,
758
- ...alias
759
- }
760
- },
761
- plugins: [
762
- // Explicitly pass the compiler, since the plugin's resolving of the compiler
763
- // looks in the current directory and breaks `npx kirbyup`
764
- vuePlugin({ compiler: vueCompilerSfc }),
765
- vueJsxPlugin(),
766
- kirbyupGlobImportPlugin(),
767
- { ...externalGlobals({ vue: "Vue" }), enforce: "post" }
768
- ],
769
- build: {
770
- copyPublicDir: false
771
- },
772
- css: {
773
- postcss: resolvedPostCssConfig
774
- },
775
- envDir: options.cwd,
776
- envPrefix: ["VITE_", "KIRBYUP_"],
777
- customLogger: logger,
778
- logLevel
779
- };
780
- if (command === "serve") {
781
- const { port, watch } = options;
782
- const serveConfig = mergeConfig(sharedConfig, {
783
- plugins: [
784
- kirbyupHmrPlugin(options),
785
- watch && fullReloadPlugin(watch)
786
- ].filter(Boolean),
787
- // Input needs to be specified so dependency pre-bundling works
788
- build: {
789
- rollupOptions: {
790
- input: resolve(options.cwd, options.entry)
791
- }
792
- },
793
- // Specify origin so asset URLs include Vite server host
794
- server: {
795
- port,
796
- strictPort: true,
797
- origin: `http://localhost:${port}`
798
- }
799
- });
800
- return mergeConfig(serveConfig, userConfig);
801
- }
802
- const mode = options.watch ? "development" : "production";
803
- const buildConfig = mergeConfig(sharedConfig, {
804
- mode,
805
- plugins: [kirbyupBuildCleanupPlugin(options)],
806
- build: {
807
- lib: {
808
- entry: resolve(options.cwd, options.entry),
809
- formats: ["iife"],
810
- name: "kirbyupExport",
811
- fileName: () => "index.js"
812
- },
813
- minify: mode === "production",
814
- outDir: options.outDir,
815
- emptyOutDir: false,
816
- rollupOptions: {
817
- output: {
818
- assetFileNames: "index.[ext]"
819
- }
820
- }
821
- }
822
- });
823
- return mergeConfig(buildConfig, userConfig);
824
- }
825
- async function generate(options) {
826
- const config = getViteConfig("build", options);
827
- let result;
828
- try {
829
- result = await build$1(config);
830
- } catch (error) {
831
- consola.error("Build failed");
832
- if (config.mode === "production")
833
- throw error;
834
- }
835
- if (result && !options.watch) {
836
- const { output } = toArray(result)[0];
837
- let longest = 0;
838
- for (const file in output) {
839
- const l = output[file].fileName.length;
840
- if (l > longest)
841
- longest = l;
842
- }
843
- for (const { fileName, type, code } of output) {
844
- await printFileInfo(
845
- options.cwd,
846
- options.outDir,
847
- fileName,
848
- code ?? await fsp.readFile(resolve(options.outDir, fileName), "utf8"),
849
- type,
850
- longest
851
- );
852
- }
853
- }
854
- return result;
855
- }
856
- async function build(options) {
857
- assertEntryExists(options);
858
- const { cwd } = options;
859
- const { config, configFile } = await loadConfig(cwd);
860
- resolvedKirbyupConfig = config ?? {};
861
- resolvedPostCssConfig = await resolvePostCSSConfig(cwd);
862
- {
863
- consola.log(colors.green(`${name} v${version}`));
864
- consola.start(`Building ${colors.cyan(options.entry)}`);
865
- }
866
- if (options.watch)
867
- consola.info("Running in watch mode");
868
- const debouncedBuild = debounce(async () => {
869
- generate(options).catch(handleError);
870
- }, 100);
871
- const startWatcher = async () => {
872
- if (!options.watch)
873
- return;
874
- const { watch } = await import('chokidar');
875
- const ignored = [
876
- "**/{.git,node_modules}/**",
877
- // Always ignore dist files
878
- "index.{css,js}"
879
- ];
880
- const watchPaths = typeof options.watch === "boolean" ? dirname(options.entry) : Array.isArray(options.watch) ? options.watch.filter(
881
- (path) => typeof path === "string"
882
- ) : options.watch;
883
- consola.info(
884
- `Watching for changes in ${toArray(watchPaths).map((i) => colors.cyan(i)).join(", ")}`
885
- );
886
- const watcher = watch(watchPaths, {
887
- ignoreInitial: true,
888
- ignorePermissionErrors: true,
889
- ignored,
890
- cwd
891
- });
892
- if (configFile)
893
- watcher.add(configFile);
894
- watcher.on("all", async (type, file) => {
895
- const absolutePath = resolve(cwd, file);
896
- if (configFile === absolutePath) {
897
- resolvedKirbyupConfig = (await loadConfig(cwd)).config ?? {};
898
- consola.info(
899
- `${colors.cyan(basename(file))} changed, setting new config`
900
- );
901
- } else {
902
- consola.log(`${colors.green(type)} ${colors.white(colors.dim(file))}`);
903
- }
904
- debouncedBuild();
905
- });
906
- };
907
- await generate(options);
908
- consola.success("Build successful");
909
- startWatcher();
910
- }
911
- async function serve(options) {
912
- assertEntryExists(options);
913
- const { cwd } = options;
914
- const { config } = await loadConfig(cwd);
915
- resolvedKirbyupConfig = config ?? {};
916
- resolvedPostCssConfig = await resolvePostCSSConfig(cwd);
917
- {
918
- consola.log(colors.green(`${name} v${version}`));
919
- consola.info("Starting development server...");
920
- }
921
- const server = await createServer(getViteConfig("serve", options));
922
- await server.listen();
923
- consola.success(`Server is listening on :${server.config.server.port}`);
924
- return server;
925
- }
926
- function assertEntryExists(options) {
927
- if (!fs.existsSync(resolve(options.cwd, options.entry)))
928
- throw new PrettyError(`Cannot find "${options.entry}"`);
929
- }
930
-
931
- export { build as b, handleError as h, name as n, serve as s, version as v };