nuxi
Version:
Nuxt CLI
1,196 lines (1,195 loc) • 36.7 kB
JavaScript
import "./chunk-Vs_PY4HZ.mjs";
import { t as defineCommand } from "./dist-B03QHgrC.mjs";
import { n as colors } from "./consola.DXBYu-KD-qSGefJ79.mjs";
import "./utils-MaFlCoS1.mjs";
import { i as h } from "./dist-BkNIIgFa.mjs";
import { o as logLevelArgs, t as cwdArgs } from "./_shared-D6pJgr6t.mjs";
import { t as runCommand } from "./run-CwixkrKi.mjs";
import { _ as q, a as Ee, d as ie, f as me, l as ft, m as ue, n as logger } from "./logger-CtlB9piy.mjs";
import { a as join$1, c as resolve$1, o as normalize$1 } from "./pathe.M-eThtNZ-BfnU2wdd.mjs";
import { a as resolveModulePath, r as relativeToProcess } from "./kit-Bx45zdA5.mjs";
import { n as joinURL } from "./dist-n2x8nSvK.mjs";
import { r as readPackageJSON } from "./dist-BPzTdxaO.mjs";
import { i as require_semver, t as getNuxtVersion } from "./versions-Bq8QDcwV.mjs";
import { r as detectPackageManager, t as addDependency } from "./dist-bPNZE3kQ.mjs";
import { i as $fetch, n as fetchModules, r as getRegistryFromContent, t as checkNuxtCompatibility } from "./_utils-CpQw4j1K.mjs";
import { t as prepare_default } from "./prepare-BhN-kzKt.mjs";
import { dirname, extname, join } from "node:path";
import process from "node:process";
import * as fs$1 from "node:fs";
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { mkdir, readFile, writeFile } from "node:fs/promises";
//#region ../../node_modules/.pnpm/fzf@0.5.2/node_modules/fzf/dist/fzf.es.js
var import_semver = require_semver();
/** @license
* fzf v0.5.2
* Copyright (c) 2021 Ajit
* Licensed under BSD 3-Clause
*/
const normalized = {
216: "O",
223: "s",
248: "o",
273: "d",
295: "h",
305: "i",
320: "l",
322: "l",
359: "t",
383: "s",
384: "b",
385: "B",
387: "b",
390: "O",
392: "c",
393: "D",
394: "D",
396: "d",
398: "E",
400: "E",
402: "f",
403: "G",
407: "I",
409: "k",
410: "l",
412: "M",
413: "N",
414: "n",
415: "O",
421: "p",
427: "t",
429: "t",
430: "T",
434: "V",
436: "y",
438: "z",
477: "e",
485: "g",
544: "N",
545: "d",
549: "z",
564: "l",
565: "n",
566: "t",
567: "j",
570: "A",
571: "C",
572: "c",
573: "L",
574: "T",
575: "s",
576: "z",
579: "B",
580: "U",
581: "V",
582: "E",
583: "e",
584: "J",
585: "j",
586: "Q",
587: "q",
588: "R",
589: "r",
590: "Y",
591: "y",
592: "a",
593: "a",
595: "b",
596: "o",
597: "c",
598: "d",
599: "d",
600: "e",
603: "e",
604: "e",
605: "e",
606: "e",
607: "j",
608: "g",
609: "g",
610: "G",
613: "h",
614: "h",
616: "i",
618: "I",
619: "l",
620: "l",
621: "l",
623: "m",
624: "m",
625: "m",
626: "n",
627: "n",
628: "N",
629: "o",
633: "r",
634: "r",
635: "r",
636: "r",
637: "r",
638: "r",
639: "r",
640: "R",
641: "R",
642: "s",
647: "t",
648: "t",
649: "u",
651: "v",
652: "v",
653: "w",
654: "y",
655: "Y",
656: "z",
657: "z",
663: "c",
665: "B",
666: "e",
667: "G",
668: "H",
669: "j",
670: "k",
671: "L",
672: "q",
686: "h",
867: "a",
868: "e",
869: "i",
870: "o",
871: "u",
872: "c",
873: "d",
874: "h",
875: "m",
876: "r",
877: "t",
878: "v",
879: "x",
7424: "A",
7427: "B",
7428: "C",
7429: "D",
7431: "E",
7432: "e",
7433: "i",
7434: "J",
7435: "K",
7436: "L",
7437: "M",
7438: "N",
7439: "O",
7440: "O",
7441: "o",
7442: "o",
7443: "o",
7446: "o",
7447: "o",
7448: "P",
7449: "R",
7450: "R",
7451: "T",
7452: "U",
7453: "u",
7454: "u",
7455: "m",
7456: "V",
7457: "W",
7458: "Z",
7522: "i",
7523: "r",
7524: "u",
7525: "v",
7834: "a",
7835: "s",
8305: "i",
8341: "h",
8342: "k",
8343: "l",
8344: "m",
8345: "n",
8346: "p",
8347: "s",
8348: "t",
8580: "c"
};
for (let i = "̀".codePointAt(0); i <= "ͯ".codePointAt(0); ++i) {
const diacritic = String.fromCodePoint(i);
for (const asciiChar of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
const withDiacriticCodePoint = (asciiChar + diacritic).normalize().codePointAt(0);
if (withDiacriticCodePoint > 126) normalized[withDiacriticCodePoint] = asciiChar;
}
}
const ranges = {
a: [7844, 7863],
e: [7870, 7879],
o: [7888, 7907],
u: [7912, 7921]
};
for (const lowerChar of Object.keys(ranges)) {
const upperChar = lowerChar.toUpperCase();
for (let i = ranges[lowerChar][0]; i <= ranges[lowerChar][1]; ++i) normalized[i] = i % 2 === 0 ? upperChar : lowerChar;
}
function normalizeRune(rune) {
if (rune < 192 || rune > 8580) return rune;
const normalizedChar = normalized[rune];
if (normalizedChar !== void 0) return normalizedChar.codePointAt(0);
return rune;
}
function toShort(number) {
return number;
}
function toInt(number) {
return number;
}
function maxInt16(num1, num2) {
return num1 > num2 ? num1 : num2;
}
const strToRunes = (str) => str.split("").map((s) => s.codePointAt(0));
const whitespaceRunes = new Set(" \f\n\r \v\xA0 \u2028\u2029 ".split("").map((v) => v.codePointAt(0)));
for (let codePoint = " ".codePointAt(0); codePoint <= " ".codePointAt(0); codePoint++) whitespaceRunes.add(codePoint);
const MAX_ASCII = "".codePointAt(0);
const CAPITAL_A_RUNE = "A".codePointAt(0);
const CAPITAL_Z_RUNE = "Z".codePointAt(0);
const SMALL_A_RUNE = "a".codePointAt(0);
const SMALL_Z_RUNE = "z".codePointAt(0);
const NUMERAL_ZERO_RUNE = "0".codePointAt(0);
const NUMERAL_NINE_RUNE = "9".codePointAt(0);
function indexAt(index, max, forward) {
if (forward) return index;
return max - index - 1;
}
const SCORE_MATCH = 16, SCORE_GAP_START = -3, SCORE_GAP_EXTENTION = -1, BONUS_BOUNDARY = SCORE_MATCH / 2, BONUS_NON_WORD = SCORE_MATCH / 2, BONUS_CAMEL_123 = BONUS_BOUNDARY + SCORE_GAP_EXTENTION, BONUS_CONSECUTIVE = -(SCORE_GAP_START + SCORE_GAP_EXTENTION), BONUS_FIRST_CHAR_MULTIPLIER = 2;
function createPosSet(withPos) {
if (withPos) return /* @__PURE__ */ new Set();
return null;
}
function alloc16(offset, slab2, size) {
if (slab2 !== null && slab2.i16.length > offset + size) {
const subarray = slab2.i16.subarray(offset, offset + size);
return [offset + size, subarray];
}
return [offset, new Int16Array(size)];
}
function alloc32(offset, slab2, size) {
if (slab2 !== null && slab2.i32.length > offset + size) {
const subarray = slab2.i32.subarray(offset, offset + size);
return [offset + size, subarray];
}
return [offset, new Int32Array(size)];
}
function charClassOfAscii(rune) {
if (rune >= SMALL_A_RUNE && rune <= SMALL_Z_RUNE) return 1;
else if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) return 2;
else if (rune >= NUMERAL_ZERO_RUNE && rune <= NUMERAL_NINE_RUNE) return 4;
else return 0;
}
function charClassOfNonAscii(rune) {
const char = String.fromCodePoint(rune);
if (char !== char.toUpperCase()) return 1;
else if (char !== char.toLowerCase()) return 2;
else if (char.match(/\p{Number}/gu) !== null) return 4;
else if (char.match(/\p{Letter}/gu) !== null) return 3;
return 0;
}
function charClassOf(rune) {
if (rune <= MAX_ASCII) return charClassOfAscii(rune);
return charClassOfNonAscii(rune);
}
function bonusFor(prevClass, currClass) {
if (prevClass === 0 && currClass !== 0) return BONUS_BOUNDARY;
else if (prevClass === 1 && currClass === 2 || prevClass !== 4 && currClass === 4) return BONUS_CAMEL_123;
else if (currClass === 0) return BONUS_NON_WORD;
return 0;
}
function bonusAt(input, idx) {
if (idx === 0) return BONUS_BOUNDARY;
return bonusFor(charClassOf(input[idx - 1]), charClassOf(input[idx]));
}
function trySkip(input, caseSensitive, char, from) {
let rest = input.slice(from);
let idx = rest.indexOf(char);
if (idx === 0) return from;
if (!caseSensitive && char >= SMALL_A_RUNE && char <= SMALL_Z_RUNE) {
if (idx > 0) rest = rest.slice(0, idx);
const uidx = rest.indexOf(char - 32);
if (uidx >= 0) idx = uidx;
}
if (idx < 0) return -1;
return from + idx;
}
function isAscii(runes) {
for (const rune of runes) if (rune >= 128) return false;
return true;
}
function asciiFuzzyIndex(input, pattern, caseSensitive) {
if (!isAscii(input)) return 0;
if (!isAscii(pattern)) return -1;
let firstIdx = 0, idx = 0;
for (let pidx = 0; pidx < pattern.length; pidx++) {
idx = trySkip(input, caseSensitive, pattern[pidx], idx);
if (idx < 0) return -1;
if (pidx === 0 && idx > 0) firstIdx = idx - 1;
idx++;
}
return firstIdx;
}
const fuzzyMatchV2 = (caseSensitive, normalize, forward, input, pattern, withPos, slab2) => {
const M = pattern.length;
if (M === 0) return [{
start: 0,
end: 0,
score: 0
}, createPosSet(withPos)];
const N = input.length;
if (slab2 !== null && N * M > slab2.i16.length) return fuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos);
const idx = asciiFuzzyIndex(input, pattern, caseSensitive);
if (idx < 0) return [{
start: -1,
end: -1,
score: 0
}, null];
let offset16 = 0, offset32 = 0, H0 = null, C0 = null, B = null, F = null;
[offset16, H0] = alloc16(offset16, slab2, N);
[offset16, C0] = alloc16(offset16, slab2, N);
[offset16, B] = alloc16(offset16, slab2, N);
[offset32, F] = alloc32(offset32, slab2, M);
const [, T] = alloc32(offset32, slab2, N);
for (let i = 0; i < T.length; i++) T[i] = input[i];
let maxScore = toShort(0), maxScorePos = 0;
let pidx = 0, lastIdx = 0;
const pchar0 = pattern[0];
let pchar = pattern[0], prevH0 = toShort(0), prevCharClass = 0, inGap = false;
let Tsub = T.subarray(idx);
let H0sub = H0.subarray(idx).subarray(0, Tsub.length), C0sub = C0.subarray(idx).subarray(0, Tsub.length), Bsub = B.subarray(idx).subarray(0, Tsub.length);
for (let [off, char] of Tsub.entries()) {
let charClass = null;
if (char <= MAX_ASCII) {
charClass = charClassOfAscii(char);
if (!caseSensitive && charClass === 2) char += 32;
} else {
charClass = charClassOfNonAscii(char);
if (!caseSensitive && charClass === 2) char = String.fromCodePoint(char).toLowerCase().codePointAt(0);
if (normalize) char = normalizeRune(char);
}
Tsub[off] = char;
const bonus = bonusFor(prevCharClass, charClass);
Bsub[off] = bonus;
prevCharClass = charClass;
if (char === pchar) {
if (pidx < M) {
F[pidx] = toInt(idx + off);
pidx++;
pchar = pattern[Math.min(pidx, M - 1)];
}
lastIdx = idx + off;
}
if (char === pchar0) {
const score = SCORE_MATCH + bonus * BONUS_FIRST_CHAR_MULTIPLIER;
H0sub[off] = score;
C0sub[off] = 1;
if (M === 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
maxScore = score;
maxScorePos = idx + off;
if (forward && bonus === BONUS_BOUNDARY) break;
}
inGap = false;
} else {
if (inGap) H0sub[off] = maxInt16(prevH0 + SCORE_GAP_EXTENTION, 0);
else H0sub[off] = maxInt16(prevH0 + SCORE_GAP_START, 0);
C0sub[off] = 0;
inGap = true;
}
prevH0 = H0sub[off];
}
if (pidx !== M) return [{
start: -1,
end: -1,
score: 0
}, null];
if (M === 1) {
const result = {
start: maxScorePos,
end: maxScorePos + 1,
score: maxScore
};
if (!withPos) return [result, null];
const pos2 = /* @__PURE__ */ new Set();
pos2.add(maxScorePos);
return [result, pos2];
}
const f0 = F[0];
const width = lastIdx - f0 + 1;
let H = null;
[offset16, H] = alloc16(offset16, slab2, width * M);
{
const toCopy = H0.subarray(f0, lastIdx + 1);
for (const [i, v] of toCopy.entries()) H[i] = v;
}
let [, C] = alloc16(offset16, slab2, width * M);
{
const toCopy = C0.subarray(f0, lastIdx + 1);
for (const [i, v] of toCopy.entries()) C[i] = v;
}
const Fsub = F.subarray(1);
const Psub = pattern.slice(1).slice(0, Fsub.length);
for (const [off, f] of Fsub.entries()) {
let inGap2 = false;
const pchar2 = Psub[off], pidx2 = off + 1, row = pidx2 * width, Tsub2 = T.subarray(f, lastIdx + 1), Bsub2 = B.subarray(f).subarray(0, Tsub2.length), Csub = C.subarray(row + f - f0).subarray(0, Tsub2.length), Cdiag = C.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hsub = H.subarray(row + f - f0).subarray(0, Tsub2.length), Hdiag = H.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hleft = H.subarray(row + f - f0 - 1).subarray(0, Tsub2.length);
Hleft[0] = 0;
for (const [off2, char] of Tsub2.entries()) {
const col = off2 + f;
let s1 = 0, s2 = 0, consecutive = 0;
if (inGap2) s2 = Hleft[off2] + SCORE_GAP_EXTENTION;
else s2 = Hleft[off2] + SCORE_GAP_START;
if (pchar2 === char) {
s1 = Hdiag[off2] + SCORE_MATCH;
let b = Bsub2[off2];
consecutive = Cdiag[off2] + 1;
if (b === BONUS_BOUNDARY) consecutive = 1;
else if (consecutive > 1) b = maxInt16(b, maxInt16(BONUS_CONSECUTIVE, B[col - consecutive + 1]));
if (s1 + b < s2) {
s1 += Bsub2[off2];
consecutive = 0;
} else s1 += b;
}
Csub[off2] = consecutive;
inGap2 = s1 < s2;
const score = maxInt16(maxInt16(s1, s2), 0);
if (pidx2 === M - 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
maxScore = score;
maxScorePos = col;
}
Hsub[off2] = score;
}
}
const pos = createPosSet(withPos);
let j = f0;
if (withPos && pos !== null) {
let i = M - 1;
j = maxScorePos;
let preferMatch = true;
while (true) {
const I = i * width, j0 = j - f0, s = H[I + j0];
let s1 = 0, s2 = 0;
if (i > 0 && j >= F[i]) s1 = H[I - width + j0 - 1];
if (j > F[i]) s2 = H[I + j0 - 1];
if (s > s1 && (s > s2 || s === s2 && preferMatch)) {
pos.add(j);
if (i === 0) break;
i--;
}
preferMatch = C[I + j0] > 1 || I + width + j0 + 1 < C.length && C[I + width + j0 + 1] > 0;
j--;
}
}
return [{
start: j,
end: maxScorePos + 1,
score: maxScore
}, pos];
};
function calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos) {
let pidx = 0, score = 0, inGap = false, consecutive = 0, firstBonus = toShort(0);
const pos = createPosSet(withPos);
let prevCharClass = 0;
if (sidx > 0) prevCharClass = charClassOf(text[sidx - 1]);
for (let idx = sidx; idx < eidx; idx++) {
let rune = text[idx];
const charClass = charClassOf(rune);
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) rune += 32;
else if (rune > MAX_ASCII) rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
if (normalize) rune = normalizeRune(rune);
if (rune === pattern[pidx]) {
if (withPos && pos !== null) pos.add(idx);
score += SCORE_MATCH;
let bonus = bonusFor(prevCharClass, charClass);
if (consecutive === 0) firstBonus = bonus;
else {
if (bonus === BONUS_BOUNDARY) firstBonus = bonus;
bonus = maxInt16(maxInt16(bonus, firstBonus), BONUS_CONSECUTIVE);
}
if (pidx === 0) score += bonus * BONUS_FIRST_CHAR_MULTIPLIER;
else score += bonus;
inGap = false;
consecutive++;
pidx++;
} else {
if (inGap) score += SCORE_GAP_EXTENTION;
else score += SCORE_GAP_START;
inGap = true;
consecutive = 0;
firstBonus = 0;
}
prevCharClass = charClass;
}
return [score, pos];
}
const fuzzyMatchV1 = (caseSensitive, normalize, forward, text, pattern, withPos, slab2) => {
if (pattern.length === 0) return [{
start: 0,
end: 0,
score: 0
}, null];
if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) return [{
start: -1,
end: -1,
score: 0
}, null];
let pidx = 0, sidx = -1, eidx = -1;
const lenRunes = text.length;
const lenPattern = pattern.length;
for (let index = 0; index < lenRunes; index++) {
let rune = text[indexAt(index, lenRunes, forward)];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) rune += 32;
else if (rune > MAX_ASCII) rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
if (normalize) rune = normalizeRune(rune);
const pchar = pattern[indexAt(pidx, lenPattern, forward)];
if (rune === pchar) {
if (sidx < 0) sidx = index;
pidx++;
if (pidx === lenPattern) {
eidx = index + 1;
break;
}
}
}
if (sidx >= 0 && eidx >= 0) {
pidx--;
for (let index = eidx - 1; index >= sidx; index--) {
let rune = text[indexAt(index, lenRunes, forward)];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) rune += 32;
else if (rune > MAX_ASCII) rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
const pchar = pattern[indexAt(pidx, lenPattern, forward)];
if (rune === pchar) {
pidx--;
if (pidx < 0) {
sidx = index;
break;
}
}
}
if (!forward) {
const sidxTemp = sidx;
sidx = lenRunes - eidx;
eidx = lenRunes - sidxTemp;
}
const [score, pos] = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos);
return [{
start: sidx,
end: eidx,
score
}, pos];
}
return [{
start: -1,
end: -1,
score: 0
}, null];
};
const exactMatchNaive = (caseSensitive, normalize, forward, text, pattern, withPos, slab2) => {
if (pattern.length === 0) return [{
start: 0,
end: 0,
score: 0
}, null];
const lenRunes = text.length;
const lenPattern = pattern.length;
if (lenRunes < lenPattern) return [{
start: -1,
end: -1,
score: 0
}, null];
if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) return [{
start: -1,
end: -1,
score: 0
}, null];
let pidx = 0;
let bestPos = -1, bonus = toShort(0), bestBonus = toShort(-1);
for (let index = 0; index < lenRunes; index++) {
const index_ = indexAt(index, lenRunes, forward);
let rune = text[index_];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) rune += 32;
else if (rune > MAX_ASCII) rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
if (normalize) rune = normalizeRune(rune);
const pidx_ = indexAt(pidx, lenPattern, forward);
if (pattern[pidx_] === rune) {
if (pidx_ === 0) bonus = bonusAt(text, index_);
pidx++;
if (pidx === lenPattern) {
if (bonus > bestBonus) {
bestPos = index;
bestBonus = bonus;
}
if (bonus === BONUS_BOUNDARY) break;
index -= pidx - 1;
pidx = 0;
bonus = 0;
}
} else {
index -= pidx;
pidx = 0;
bonus = 0;
}
}
if (bestPos >= 0) {
let sidx = 0, eidx = 0;
if (forward) {
sidx = bestPos - lenPattern + 1;
eidx = bestPos + 1;
} else {
sidx = lenRunes - (bestPos + 1);
eidx = lenRunes - (bestPos - lenPattern + 1);
}
const [score] = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false);
return [{
start: sidx,
end: eidx,
score
}, null];
}
return [{
start: -1,
end: -1,
score: 0
}, null];
};
const SLAB_16_SIZE = 100 * 1024;
const SLAB_32_SIZE = 2048;
function makeSlab(size16, size32) {
return {
i16: new Int16Array(size16),
i32: new Int32Array(size32)
};
}
const slab = makeSlab(SLAB_16_SIZE, SLAB_32_SIZE);
const buildPatternForBasicMatch = (query, casing, normalize) => {
let caseSensitive = false;
switch (casing) {
case "smart-case":
if (query.toLowerCase() !== query) caseSensitive = true;
break;
case "case-sensitive":
caseSensitive = true;
break;
case "case-insensitive":
query = query.toLowerCase();
caseSensitive = false;
break;
}
let queryRunes = strToRunes(query);
if (normalize) queryRunes = queryRunes.map(normalizeRune);
return {
queryRunes,
caseSensitive
};
};
function getResultFromScoreMap(scoreMap, limit) {
const scoresInDesc = Object.keys(scoreMap).map((v) => parseInt(v, 10)).sort((a, b) => b - a);
let result = [];
for (const score of scoresInDesc) {
result = result.concat(scoreMap[score]);
if (result.length >= limit) break;
}
return result;
}
function getBasicMatchIter(scoreMap, queryRunes, caseSensitive) {
return (idx) => {
const itemRunes = this.runesList[idx];
if (queryRunes.length > itemRunes.length) return;
let [match, positions] = this.algoFn(caseSensitive, this.opts.normalize, this.opts.forward, itemRunes, queryRunes, true, slab);
if (match.start === -1) return;
if (this.opts.fuzzy === false) {
positions = /* @__PURE__ */ new Set();
for (let position = match.start; position < match.end; ++position) positions.add(position);
}
const scoreKey = this.opts.sort ? match.score : 0;
if (scoreMap[scoreKey] === void 0) scoreMap[scoreKey] = [];
scoreMap[scoreKey].push({
item: this.items[idx],
...match,
positions: positions != null ? positions : /* @__PURE__ */ new Set()
});
};
}
function basicMatch(query) {
const { queryRunes, caseSensitive } = buildPatternForBasicMatch(query, this.opts.casing, this.opts.normalize);
const scoreMap = {};
const iter2 = getBasicMatchIter.bind(this)(scoreMap, queryRunes, caseSensitive);
for (let i = 0, len = this.runesList.length; i < len; ++i) iter2(i);
return getResultFromScoreMap(scoreMap, this.opts.limit);
}
const defaultOpts = {
limit: Infinity,
selector: (v) => v,
casing: "smart-case",
normalize: true,
fuzzy: "v2",
tiebreakers: [],
sort: true,
forward: true
};
var BaseFinder = class {
constructor(list, ...optionsTuple) {
this.opts = {
...defaultOpts,
...optionsTuple[0]
};
this.items = list;
this.runesList = list.map((item) => strToRunes(this.opts.selector(item).normalize()));
this.algoFn = exactMatchNaive;
switch (this.opts.fuzzy) {
case "v2":
this.algoFn = fuzzyMatchV2;
break;
case "v1":
this.algoFn = fuzzyMatchV1;
break;
}
}
};
const syncDefaultOpts = {
...defaultOpts,
match: basicMatch
};
var SyncFinder = class extends BaseFinder {
constructor(list, ...optionsTuple) {
super(list, ...optionsTuple);
this.opts = {
...syncDefaultOpts,
...optionsTuple[0]
};
}
find(query) {
if (query.length === 0 || this.items.length === 0) return this.items.slice(0, this.opts.limit).map(createResultItemWithEmptyPos);
query = query.normalize();
return postProcessResultItems(this.opts.match.bind(this)(query), this.opts);
}
};
({ ...defaultOpts });
const createResultItemWithEmptyPos = (item) => ({
item,
start: -1,
end: -1,
score: 0,
positions: /* @__PURE__ */ new Set()
});
function postProcessResultItems(result, opts) {
if (opts.sort) {
const { selector } = opts;
result.sort((a, b) => {
if (a.score === b.score) for (const tiebreaker of opts.tiebreakers) {
const diff = tiebreaker(a, b, selector);
if (diff !== 0) return diff;
}
return 0;
});
}
if (Number.isFinite(opts.limit)) result.splice(opts.limit);
return result;
}
function byLengthAsc(a, b, selector) {
return selector(a.item).length - selector(b.item).length;
}
var Fzf = class {
constructor(list, ...optionsTuple) {
this.finder = new SyncFinder(list, ...optionsTuple);
this.find = this.finder.find.bind(this.finder);
}
};
//#endregion
//#region src/commands/module/_autocomplete.ts
const TRAILING_DOT_RE = /\.$/;
/**
* Interactive fuzzy search for selecting Nuxt modules
* Returns object with selected module npm package names and cancellation status
*/
async function selectModulesAutocomplete(options) {
const { modules, message = "Search and select modules:" } = options;
if (!h) {
logger.warn("Interactive module selection requires a TTY. Skipping.");
return {
selected: [],
cancelled: false
};
}
const sortedModules = modules.toSorted((a, b) => {
if (a.type === "official" && b.type !== "official") return -1;
if (a.type !== "official" && b.type === "official") return 1;
return a.npm.localeCompare(b.npm);
});
const fzf = new Fzf(sortedModules, {
selector: (m) => `${m.npm} ${m.name} ${m.category}`,
casing: "case-insensitive",
tiebreakers: [byLengthAsc]
});
const clackOptions = sortedModules.map((m) => ({
value: m.npm,
label: m.npm,
hint: m.description.replace(TRAILING_DOT_RE, "")
}));
const filter = (search, option) => {
if (!search) return true;
return fzf.find(search).some((r) => r.item.npm === option.value);
};
const result = await ie({
message,
options: clackOptions,
filter,
required: false
});
if (q(result)) return {
selected: [],
cancelled: true
};
return {
selected: result,
cancelled: false
};
}
//#endregion
//#region ../../node_modules/.pnpm/c12@3.3.4_magicast@0.5.2/node_modules/c12/dist/update.mjs
const SUPPORTED_EXTENSIONS = Object.freeze([
".js",
".ts",
".mjs",
".cjs",
".mts",
".cts",
".json",
".jsonc",
".json5",
".yaml",
".yml",
".toml"
]);
const UPDATABLE_EXTS = [
".js",
".ts",
".mjs",
".cjs",
".mts",
".cts"
];
/**
* @experimental Update a config file or create a new one.
*/
async function updateConfig(opts) {
const { parseModule } = await import("./dist-VQPAbvb_.mjs");
let configFile = tryResolve(`./${opts.configFile}`, opts.cwd, SUPPORTED_EXTENSIONS) || tryResolve(`./.config/${opts.configFile}`, opts.cwd, SUPPORTED_EXTENSIONS) || tryResolve(`./.config/${opts.configFile.split(".")[0]}`, opts.cwd, SUPPORTED_EXTENSIONS);
let created = false;
if (!configFile) {
configFile = join$1(opts.cwd, opts.configFile + (opts.createExtension || ".ts"));
const createResult = await opts.onCreate?.({ configFile }) ?? true;
if (!createResult) throw new Error("Config file creation aborted.");
const content = typeof createResult === "string" ? createResult : `export default {}\n`;
await mkdir(dirname(configFile), { recursive: true });
await writeFile(configFile, content, "utf8");
created = true;
}
const ext = extname(configFile);
if (!UPDATABLE_EXTS.includes(ext)) throw new Error(`Unsupported config file extension: ${ext} (${configFile}) (supported: ${UPDATABLE_EXTS.join(", ")})`);
const _module = parseModule(await readFile(configFile, "utf8"), opts.magicast);
const defaultExport = _module.exports.default;
if (!defaultExport) throw new Error("Default export is missing in the config file!");
const configObj = defaultExport.$type === "function-call" ? defaultExport.$args[0] : defaultExport;
await opts.onUpdate?.(configObj);
await writeFile(configFile, _module.generate().code);
return {
configFile,
created
};
}
function tryResolve(path, cwd, extensions) {
const res = resolveModulePath(path, {
try: true,
from: join$1(cwd, "/"),
extensions,
suffixes: ["", "/index"],
cache: false
});
return res ? normalize$1(res) : void 0;
}
//#endregion
//#region src/commands/module/add.ts
const PROTOCOL_RE = /^https?:\/\//;
const TRAILING_SLASH_RE = /\/$/;
const REGEX_SPECIAL_RE = /[.*+?^${}()|[\]\\]/g;
var add_default = defineCommand({
meta: {
name: "add",
description: "Add Nuxt modules"
},
args: {
...cwdArgs,
...logLevelArgs,
moduleName: {
type: "positional",
description: "Specify one or more modules to install by name, separated by spaces"
},
skipInstall: {
type: "boolean",
description: "Skip npm install"
},
skipConfig: {
type: "boolean",
description: "Skip nuxt.config.ts update"
},
dev: {
type: "boolean",
description: "Install modules as dev dependencies"
}
},
async setup(ctx) {
const cwd = resolve$1(ctx.args.cwd);
let modules = ctx.args._.map((e) => e.trim()).filter(Boolean);
const projectPkg = await readPackageJSON(cwd).catch(() => ({}));
if (!projectPkg.dependencies?.nuxt && !projectPkg.devDependencies?.nuxt) {
logger.warn(`No ${colors.cyan("nuxt")} dependency detected in ${colors.cyan(relativeToProcess(cwd))}.`);
const shouldContinue = await ue({
message: `Do you want to continue anyway?`,
initialValue: false
});
if (q(shouldContinue) || shouldContinue !== true) process.exit(1);
}
if (modules.length === 0) {
const modulesSpinner = ft();
modulesSpinner.start("Fetching available modules");
const [allModules, nuxtVersion] = await Promise.all([fetchModules(), getNuxtVersion(cwd)]);
const compatibleModules = allModules.filter((m) => !m.compatibility.nuxt || checkNuxtCompatibility(m, nuxtVersion));
modulesSpinner.stop("Modules loaded");
const result = await selectModulesAutocomplete({
modules: compatibleModules,
message: "Search modules to add (Esc to finish):"
});
if (result.selected.length === 0) {
me("No modules selected.");
process.exit(0);
}
modules = result.selected;
}
const resolvedModules = [];
for (const moduleName of modules) {
const resolvedModule = await resolveModule(moduleName, cwd);
if (resolvedModule) resolvedModules.push(resolvedModule);
}
if (resolvedModules.length === 0) {
me("No modules to add.");
process.exit(1);
}
logger.info(`Resolved ${resolvedModules.map((x) => colors.cyan(x.pkgName)).join(", ")}, adding module${resolvedModules.length > 1 ? "s" : ""}...`);
await addModules(resolvedModules, {
...ctx.args,
cwd
}, projectPkg);
if (!ctx.args.skipInstall) await runCommand(prepare_default, Object.entries(ctx.args).filter(([k]) => k in cwdArgs || k in logLevelArgs).map(([k, v]) => `--${k}=${v}`));
}
});
async function addModules(modules, { skipInstall = false, skipConfig = false, cwd, dev = false }, projectPkg) {
if (!skipInstall) {
const installedModules = [];
const notInstalledModules = [];
const dependencies = new Set([...Object.keys(projectPkg.dependencies || {}), ...Object.keys(projectPkg.devDependencies || {})]);
for (const module of modules) if (dependencies.has(module.pkgName)) installedModules.push(module);
else notInstalledModules.push(module);
if (installedModules.length > 0) {
const installedModulesList = installedModules.map((module) => colors.cyan(module.pkgName)).join(", ");
const are = installedModules.length > 1 ? "are" : "is";
logger.info(`${installedModulesList} ${are} already installed`);
}
if (notInstalledModules.length > 0) {
const isDev = Boolean(projectPkg.devDependencies?.nuxt) || dev;
const notInstalledModulesList = notInstalledModules.map((module) => colors.cyan(module.pkg)).join(", ");
const dependency = notInstalledModules.length > 1 ? "dependencies" : "dependency";
const a = notInstalledModules.length > 1 ? "" : " a";
logger.info(`Installing ${notInstalledModulesList} as${a}${isDev ? " development" : ""} ${dependency}`);
const packageManager = await detectPackageManager(cwd);
if (await addDependency(notInstalledModules.map((module) => module.pkg), {
cwd,
dev: isDev,
installPeerDependencies: true,
packageManager,
workspace: packageManager?.name === "pnpm" && existsSync(resolve$1(cwd, "pnpm-workspace.yaml"))
}).then(() => true).catch(async (error) => {
logger.error(String(error));
const result = await ue({
message: `Install failed for ${notInstalledModules.map((module) => colors.cyan(module.pkg)).join(", ")}. Do you want to continue adding the module${notInstalledModules.length > 1 ? "s" : ""} to ${colors.cyan("nuxt.config")}?`,
initialValue: false
});
if (q(result)) return false;
return result;
}) !== true) return;
}
}
if (!skipConfig) await updateConfig({
cwd,
configFile: "nuxt.config",
async onCreate() {
logger.info(`Creating ${colors.cyan("nuxt.config.ts")}`);
return getDefaultNuxtConfig();
},
async onUpdate(config) {
if (!config.modules) config.modules = [];
for (const resolved of modules) {
if (config.modules.includes(resolved.pkgName)) {
logger.info(`${colors.cyan(resolved.pkgName)} is already in the ${colors.cyan("modules")}`);
continue;
}
logger.info(`Adding ${colors.cyan(resolved.pkgName)} to the ${colors.cyan("modules")}`);
config.modules.push(resolved.pkgName);
}
}
}).catch((error) => {
logger.error(`Failed to update ${colors.cyan("nuxt.config")}: ${error.message}`);
logger.error(`Please manually add ${colors.cyan(modules.map((module) => module.pkgName).join(", "))} to the ${colors.cyan("modules")} in ${colors.cyan("nuxt.config.ts")}`);
return null;
});
}
function getDefaultNuxtConfig() {
return `
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: []
})`;
}
const packageRegex = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?([a-z0-9-~][a-z0-9-._~]*)(@[^@]+)?$/;
async function resolveModule(moduleName, cwd) {
let pkgName = moduleName;
let pkgVersion;
const reMatch = moduleName.match(packageRegex);
if (reMatch) {
if (reMatch[3]) {
pkgName = `${reMatch[1] || ""}${reMatch[2] || ""}`;
pkgVersion = reMatch[3].slice(1);
}
} else {
logger.error(`Invalid package name ${colors.cyan(pkgName)}.`);
return false;
}
const matchedModule = (await fetchModules().catch((err) => {
logger.warn(`Cannot search in the Nuxt Modules database: ${err}`);
return [];
})).find((module) => module.name === moduleName || pkgVersion && module.name === pkgName || module.npm === pkgName || module.aliases?.includes(pkgName));
if (matchedModule?.npm) pkgName = matchedModule.npm;
if (matchedModule && matchedModule.compatibility.nuxt) {
const nuxtVersion = await getNuxtVersion(cwd);
if (!checkNuxtCompatibility(matchedModule, nuxtVersion)) {
logger.warn(`The module ${colors.cyan(pkgName)} is not compatible with Nuxt ${colors.cyan(nuxtVersion)} (requires ${colors.cyan(matchedModule.compatibility.nuxt)})`);
const shouldContinue = await ue({
message: "Do you want to continue installing incompatible version?",
initialValue: false
});
if (q(shouldContinue) || !shouldContinue) return false;
}
const versionMap = matchedModule.compatibility.versionMap;
if (versionMap) {
for (const [_nuxtVersion, _moduleVersion] of Object.entries(versionMap)) if ((0, import_semver.satisfies)(nuxtVersion, _nuxtVersion)) {
if (!pkgVersion) pkgVersion = _moduleVersion;
else {
logger.warn(`Recommended version of ${colors.cyan(pkgName)} for Nuxt ${colors.cyan(nuxtVersion)} is ${colors.cyan(_moduleVersion)} but you have requested ${colors.cyan(pkgVersion)}.`);
const result = await Ee({
message: "Choose a version:",
options: [{
value: _moduleVersion,
label: _moduleVersion
}, {
value: pkgVersion,
label: pkgVersion
}]
});
if (q(result)) return false;
pkgVersion = result;
}
break;
}
}
}
let version = pkgVersion || "latest";
const meta = await detectNpmRegistry(pkgName.startsWith("@") ? pkgName.split("/")[0] : null);
const headers = {};
if (meta.authToken) headers.Authorization = `Bearer ${meta.authToken}`;
const pkgDetails = await $fetch(joinURL(meta.registry, `${pkgName}`), { headers }).catch(() => null);
if (!pkgDetails) {
logger.error(`Failed to fetch package details for ${colors.cyan(pkgName)}.`);
return false;
}
if (pkgDetails["dist-tags"]?.[version]) version = pkgDetails["dist-tags"][version];
else version = Object.keys(pkgDetails.versions)?.findLast((v) => (0, import_semver.satisfies)(v, version)) || version;
const pkg = pkgDetails.versions[version] || {};
const pkgDependencies = Object.assign(pkg.dependencies || {}, pkg.devDependencies || {});
if (!pkgDependencies.nuxt && !pkgDependencies["nuxt-edge"] && !pkgDependencies["@nuxt/kit"]) {
logger.warn(`It seems that ${colors.cyan(pkgName)} is not a Nuxt module.`);
const shouldContinue = await ue({
message: `Do you want to continue installing ${colors.cyan(pkgName)} anyway?`,
initialValue: false
});
if (q(shouldContinue) || !shouldContinue) return false;
}
return {
nuxtModule: matchedModule,
pkg: `${pkgName}@${version}`,
pkgName,
pkgVersion: version
};
}
function getNpmrcPaths() {
const userNpmrcPath = join(homedir(), ".npmrc");
return [join(process.cwd(), ".npmrc"), userNpmrcPath];
}
async function getAuthToken(registry) {
const paths = getNpmrcPaths();
const registryHost = registry.replace(PROTOCOL_RE, "").replace(TRAILING_SLASH_RE, "").replace(REGEX_SPECIAL_RE, "\\$&");
const authTokenRegex = new RegExp(`^//${registryHost}/:_authToken=(.+)$`, "m");
for (const npmrcPath of paths) {
let fd;
try {
fd = await fs$1.promises.open(npmrcPath, "r");
if (await fd.stat().then((r) => r.isFile())) {
const authTokenMatch = (await fd.readFile("utf-8")).match(authTokenRegex)?.[1];
if (authTokenMatch) return authTokenMatch.trim();
}
} catch {} finally {
await fd?.close();
}
}
return null;
}
async function detectNpmRegistry(scope) {
const registry = await getRegistry(scope);
return {
registry,
authToken: await getAuthToken(registry)
};
}
async function getRegistry(scope) {
if (process.env.COREPACK_NPM_REGISTRY) return process.env.COREPACK_NPM_REGISTRY;
const registry = await getRegistryFromFile(getNpmrcPaths(), scope);
if (registry) process.env.COREPACK_NPM_REGISTRY = registry;
return registry || "https://registry.npmjs.org";
}
async function getRegistryFromFile(paths, scope) {
for (const npmrcPath of paths) {
let fd;
try {
fd = await fs$1.promises.open(npmrcPath, "r");
if (await fd.stat().then((r) => r.isFile())) {
const registry = getRegistryFromContent(await fd.readFile("utf-8"), scope);
if (registry) return registry;
}
} catch {} finally {
await fd?.close();
}
}
return null;
}
//#endregion
export { add_default as default, selectModulesAutocomplete as t };