mirror of
https://github.com/sern-handler/website
synced 2026-06-23 16:22:26 +00:00
feat: migrate to starlight
This commit is contained in:
19
node_modules/astro/dist/cli/add/babel.d.ts
generated
vendored
Normal file
19
node_modules/astro/dist/cli/add/babel.d.ts
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
17
node_modules/astro/dist/cli/add/babel.js
generated
vendored
Normal file
17
node_modules/astro/dist/cli/add/babel.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
import generator from "@babel/generator";
|
||||
import parser from "@babel/parser";
|
||||
import traverse from "@babel/traverse";
|
||||
import * as t from "@babel/types";
|
||||
const visit = traverse.default;
|
||||
async function generate(ast) {
|
||||
const astToText = generator.default;
|
||||
const { code } = astToText(ast);
|
||||
return code;
|
||||
}
|
||||
const parse = (code) => parser.parse(code, { sourceType: "unambiguous", plugins: ["typescript"] });
|
||||
export {
|
||||
generate,
|
||||
parse,
|
||||
t,
|
||||
visit
|
||||
};
|
||||
2
node_modules/astro/dist/cli/add/imports.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/cli/add/imports.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import { t } from './babel.js';
|
||||
export declare function ensureImport(root: t.File, importDeclaration: t.ImportDeclaration): void;
|
||||
34
node_modules/astro/dist/cli/add/imports.js
generated
vendored
Normal file
34
node_modules/astro/dist/cli/add/imports.js
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
import { t, visit } from "./babel.js";
|
||||
function ensureImport(root, importDeclaration) {
|
||||
let specifiersToFind = [...importDeclaration.specifiers];
|
||||
visit(root, {
|
||||
ImportDeclaration(path) {
|
||||
if (path.node.source.value === importDeclaration.source.value) {
|
||||
path.node.specifiers.forEach(
|
||||
(specifier) => specifiersToFind.forEach((specifierToFind, i) => {
|
||||
if (specifier.type !== specifierToFind.type)
|
||||
return;
|
||||
if (specifier.local.name === specifierToFind.local.name) {
|
||||
specifiersToFind.splice(i, 1);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (specifiersToFind.length === 0)
|
||||
return;
|
||||
visit(root, {
|
||||
Program(path) {
|
||||
const declaration = t.importDeclaration(specifiersToFind, importDeclaration.source);
|
||||
const latestImport = path.get("body").filter((statement) => statement.isImportDeclaration()).pop();
|
||||
if (latestImport)
|
||||
latestImport.insertAfter(declaration);
|
||||
else
|
||||
path.unshiftContainer("body", declaration);
|
||||
}
|
||||
});
|
||||
}
|
||||
export {
|
||||
ensureImport
|
||||
};
|
||||
13
node_modules/astro/dist/cli/add/index.d.ts
generated
vendored
Normal file
13
node_modules/astro/dist/cli/add/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface AddOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
interface IntegrationInfo {
|
||||
id: string;
|
||||
packageName: string;
|
||||
dependencies: [name: string, version: string][];
|
||||
type: 'integration' | 'adapter';
|
||||
}
|
||||
export declare function add(names: string[], { flags }: AddOptions): Promise<void>;
|
||||
export declare function validateIntegrations(integrations: string[]): Promise<IntegrationInfo[]>;
|
||||
export {};
|
||||
926
node_modules/astro/dist/cli/add/index.js
generated
vendored
Normal file
926
node_modules/astro/dist/cli/add/index.js
generated
vendored
Normal file
@@ -0,0 +1,926 @@
|
||||
import fsMod, { existsSync, promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import boxen from "boxen";
|
||||
import { diffWords } from "diff";
|
||||
import { execa } from "execa";
|
||||
import { bold, cyan, dim, green, magenta, red, yellow } from "kleur/colors";
|
||||
import ora from "ora";
|
||||
import preferredPM from "preferred-pm";
|
||||
import prompts from "prompts";
|
||||
import maxSatisfying from "semver/ranges/max-satisfying.js";
|
||||
import {
|
||||
loadTSConfig,
|
||||
resolveConfig,
|
||||
resolveConfigPath,
|
||||
resolveRoot
|
||||
} from "../../core/config/index.js";
|
||||
import {
|
||||
defaultTSConfig,
|
||||
presets,
|
||||
updateTSConfigForFramework
|
||||
} from "../../core/config/tsconfig.js";
|
||||
import * as msg from "../../core/messages.js";
|
||||
import { printHelp } from "../../core/messages.js";
|
||||
import { appendForwardSlash } from "../../core/path.js";
|
||||
import { apply as applyPolyfill } from "../../core/polyfill.js";
|
||||
import { ensureProcessNodeEnv, parseNpmName } from "../../core/util.js";
|
||||
import { eventCliSession, telemetry } from "../../events/index.js";
|
||||
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
|
||||
import { fetchPackageJson, fetchPackageVersions } from "../install-package.js";
|
||||
import { generate, parse, t, visit } from "./babel.js";
|
||||
import { ensureImport } from "./imports.js";
|
||||
import { wrapDefaultExport } from "./wrapper.js";
|
||||
const ALIASES = /* @__PURE__ */ new Map([
|
||||
["solid", "solid-js"],
|
||||
["tailwindcss", "tailwind"]
|
||||
]);
|
||||
const STUBS = {
|
||||
ASTRO_CONFIG: `import { defineConfig } from 'astro/config';
|
||||
// https://astro.build/config
|
||||
export default defineConfig({});`,
|
||||
TAILWIND_CONFIG: `/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
`,
|
||||
SVELTE_CONFIG: `import { vitePreprocess } from '@astrojs/svelte';
|
||||
|
||||
export default {
|
||||
preprocess: vitePreprocess(),
|
||||
}
|
||||
`,
|
||||
LIT_NPMRC: `# Lit libraries are required to be hoisted due to dependency issues.
|
||||
public-hoist-pattern[]=*lit*
|
||||
`,
|
||||
DB_CONFIG: `import { defineDb } from 'astro:db';
|
||||
|
||||
// https://astro.build/db/config
|
||||
export default defineDb({
|
||||
tables: {}
|
||||
});
|
||||
`,
|
||||
DB_SEED: `import { db } from 'astro:db';
|
||||
|
||||
// https://astro.build/db/seed
|
||||
export default async function seed() {
|
||||
// TODO
|
||||
}
|
||||
`
|
||||
};
|
||||
const OFFICIAL_ADAPTER_TO_IMPORT_MAP = {
|
||||
netlify: "@astrojs/netlify",
|
||||
vercel: "@astrojs/vercel/serverless",
|
||||
cloudflare: "@astrojs/cloudflare",
|
||||
node: "@astrojs/node"
|
||||
};
|
||||
async function add(names, { flags }) {
|
||||
ensureProcessNodeEnv("production");
|
||||
applyPolyfill();
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
const { userConfig } = await resolveConfig(inlineConfig, "add");
|
||||
telemetry.record(eventCliSession("add", userConfig));
|
||||
if (flags.help || names.length === 0) {
|
||||
printHelp({
|
||||
commandName: "astro add",
|
||||
usage: "[...integrations] [...adapters]",
|
||||
tables: {
|
||||
Flags: [
|
||||
["--yes", "Accept all prompts."],
|
||||
["--help", "Show this help message."]
|
||||
],
|
||||
"UI Frameworks": [
|
||||
["react", "astro add react"],
|
||||
["preact", "astro add preact"],
|
||||
["vue", "astro add vue"],
|
||||
["svelte", "astro add svelte"],
|
||||
["solid-js", "astro add solid-js"],
|
||||
["lit", "astro add lit"],
|
||||
["alpinejs", "astro add alpinejs"]
|
||||
],
|
||||
"Documentation Frameworks": [["starlight", "astro add starlight"]],
|
||||
"SSR Adapters": [
|
||||
["netlify", "astro add netlify"],
|
||||
["vercel", "astro add vercel"],
|
||||
["deno", "astro add deno"],
|
||||
["cloudflare", "astro add cloudflare"],
|
||||
["node", "astro add node"]
|
||||
],
|
||||
Others: [
|
||||
["db", "astro add db"],
|
||||
["tailwind", "astro add tailwind"],
|
||||
["mdx", "astro add mdx"],
|
||||
["markdoc", "astro add markdoc"],
|
||||
["partytown", "astro add partytown"],
|
||||
["sitemap", "astro add sitemap"]
|
||||
]
|
||||
},
|
||||
description: `For more integrations, check out: ${cyan("https://astro.build/integrations")}`
|
||||
});
|
||||
return;
|
||||
}
|
||||
const cwd = flags.root;
|
||||
const logger = createLoggerFromFlags(flags);
|
||||
const integrationNames = names.map((name) => ALIASES.has(name) ? ALIASES.get(name) : name);
|
||||
const integrations = await validateIntegrations(integrationNames);
|
||||
let installResult = await tryToInstallIntegrations({ integrations, cwd, flags, logger });
|
||||
const rootPath = resolveRoot(cwd);
|
||||
const root = pathToFileURL(rootPath);
|
||||
root.href = appendForwardSlash(root.href);
|
||||
switch (installResult) {
|
||||
case 1 /* updated */: {
|
||||
if (integrations.find((integration) => integration.id === "tailwind")) {
|
||||
await setupIntegrationConfig({
|
||||
root,
|
||||
logger,
|
||||
flags,
|
||||
integrationName: "Tailwind",
|
||||
possibleConfigFiles: [
|
||||
"./tailwind.config.cjs",
|
||||
"./tailwind.config.mjs",
|
||||
"./tailwind.config.ts",
|
||||
"./tailwind.config.mts",
|
||||
"./tailwind.config.cts",
|
||||
"./tailwind.config.js"
|
||||
],
|
||||
defaultConfigFile: "./tailwind.config.mjs",
|
||||
defaultConfigContent: STUBS.TAILWIND_CONFIG
|
||||
});
|
||||
}
|
||||
if (integrations.find((integration) => integration.id === "svelte")) {
|
||||
await setupIntegrationConfig({
|
||||
root,
|
||||
logger,
|
||||
flags,
|
||||
integrationName: "Svelte",
|
||||
possibleConfigFiles: ["./svelte.config.js", "./svelte.config.cjs", "./svelte.config.mjs"],
|
||||
defaultConfigFile: "./svelte.config.js",
|
||||
defaultConfigContent: STUBS.SVELTE_CONFIG
|
||||
});
|
||||
}
|
||||
if (integrations.find((integration) => integration.id === "db")) {
|
||||
if (!existsSync(new URL("./db/", root))) {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta(
|
||||
`Astro will scaffold ${green("./db/config.ts")}${magenta(" and ")}${green(
|
||||
"./db/seed.ts"
|
||||
)}${magenta(" files.")}`
|
||||
)}
|
||||
`
|
||||
);
|
||||
if (await askToContinue({ flags })) {
|
||||
await fs.mkdir(new URL("./db", root));
|
||||
await Promise.all([
|
||||
fs.writeFile(new URL("./db/config.ts", root), STUBS.DB_CONFIG, { encoding: "utf-8" }),
|
||||
fs.writeFile(new URL("./db/seed.ts", root), STUBS.DB_SEED, { encoding: "utf-8" })
|
||||
]);
|
||||
} else {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
Astro DB requires additional configuration. Please refer to https://astro.build/db/config`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.debug("add", `Using existing db configuration`);
|
||||
}
|
||||
}
|
||||
if (integrations.find((integration) => integration.id === "lit") && (await preferredPM(fileURLToPath(root)))?.name === "pnpm") {
|
||||
await setupIntegrationConfig({
|
||||
root,
|
||||
logger,
|
||||
flags,
|
||||
integrationName: "Lit",
|
||||
possibleConfigFiles: ["./.npmrc"],
|
||||
defaultConfigFile: "./.npmrc",
|
||||
defaultConfigContent: STUBS.LIT_NPMRC
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 2 /* cancelled */: {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
msg.cancelled(
|
||||
`Dependencies ${bold("NOT")} installed.`,
|
||||
`Be sure to install them manually before continuing!`
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 3 /* failure */: {
|
||||
throw createPrettyError(new Error(`Unable to install dependencies`));
|
||||
}
|
||||
case 0 /* none */:
|
||||
break;
|
||||
}
|
||||
const rawConfigPath = await resolveConfigPath({
|
||||
root: rootPath,
|
||||
configFile: flags.config,
|
||||
fs: fsMod
|
||||
});
|
||||
let configURL = rawConfigPath ? pathToFileURL(rawConfigPath) : void 0;
|
||||
if (configURL) {
|
||||
logger.debug("add", `Found config at ${configURL}`);
|
||||
} else {
|
||||
logger.info("add", `Unable to locate a config file, generating one for you.`);
|
||||
configURL = new URL("./astro.config.mjs", root);
|
||||
await fs.writeFile(fileURLToPath(configURL), STUBS.ASTRO_CONFIG, { encoding: "utf-8" });
|
||||
}
|
||||
let ast = null;
|
||||
try {
|
||||
ast = await parseAstroConfig(configURL);
|
||||
logger.debug("add", "Parsed astro config");
|
||||
const defineConfig = t.identifier("defineConfig");
|
||||
ensureImport(
|
||||
ast,
|
||||
t.importDeclaration(
|
||||
[t.importSpecifier(defineConfig, defineConfig)],
|
||||
t.stringLiteral("astro/config")
|
||||
)
|
||||
);
|
||||
wrapDefaultExport(ast, defineConfig);
|
||||
logger.debug("add", "Astro config ensured `defineConfig`");
|
||||
for (const integration of integrations) {
|
||||
if (isAdapter(integration)) {
|
||||
const officialExportName = OFFICIAL_ADAPTER_TO_IMPORT_MAP[integration.id];
|
||||
if (officialExportName) {
|
||||
await setAdapter(ast, integration, officialExportName);
|
||||
} else {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta(
|
||||
`Check our deployment docs for ${bold(
|
||||
integration.packageName
|
||||
)} to update your "adapter" config.`
|
||||
)}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
await addIntegration(ast, integration);
|
||||
}
|
||||
logger.debug("add", `Astro config added integration ${integration.id}`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.debug("add", "Error parsing/modifying astro config: ", err);
|
||||
throw createPrettyError(err);
|
||||
}
|
||||
let configResult;
|
||||
if (ast) {
|
||||
try {
|
||||
configResult = await updateAstroConfig({
|
||||
configURL,
|
||||
ast,
|
||||
flags,
|
||||
logger,
|
||||
logAdapterInstructions: integrations.some(isAdapter)
|
||||
});
|
||||
} catch (err) {
|
||||
logger.debug("add", "Error updating astro config", err);
|
||||
throw createPrettyError(err);
|
||||
}
|
||||
}
|
||||
switch (configResult) {
|
||||
case 2 /* cancelled */: {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
msg.cancelled(`Your configuration has ${bold("NOT")} been updated.`)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 0 /* none */: {
|
||||
const pkgURL = new URL("./package.json", configURL);
|
||||
if (existsSync(fileURLToPath(pkgURL))) {
|
||||
const { dependencies = {}, devDependencies = {} } = await fs.readFile(fileURLToPath(pkgURL)).then((res) => JSON.parse(res.toString()));
|
||||
const deps = Object.keys(Object.assign(dependencies, devDependencies));
|
||||
const missingDeps = integrations.filter(
|
||||
(integration) => !deps.includes(integration.packageName)
|
||||
);
|
||||
if (missingDeps.length === 0) {
|
||||
logger.info("SKIP_FORMAT", msg.success(`Configuration up-to-date.`));
|
||||
break;
|
||||
}
|
||||
}
|
||||
logger.info("SKIP_FORMAT", msg.success(`Configuration up-to-date.`));
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const list = integrations.map((integration) => ` - ${integration.packageName}`).join("\n");
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
msg.success(
|
||||
`Added the following integration${integrations.length === 1 ? "" : "s"} to your project:
|
||||
${list}`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
const updateTSConfigResult = await updateTSConfig(cwd, logger, integrations, flags);
|
||||
switch (updateTSConfigResult) {
|
||||
case 0 /* none */: {
|
||||
break;
|
||||
}
|
||||
case 2 /* cancelled */: {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
msg.cancelled(`Your TypeScript configuration has ${bold("NOT")} been updated.`)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 3 /* failure */: {
|
||||
throw new Error(
|
||||
`Unknown error parsing tsconfig.json or jsconfig.json. Could not update TypeScript settings.`
|
||||
);
|
||||
}
|
||||
default:
|
||||
logger.info("SKIP_FORMAT", msg.success(`Successfully updated TypeScript settings`));
|
||||
}
|
||||
}
|
||||
function isAdapter(integration) {
|
||||
return integration.type === "adapter";
|
||||
}
|
||||
async function parseAstroConfig(configURL) {
|
||||
const source = await fs.readFile(fileURLToPath(configURL), { encoding: "utf-8" });
|
||||
const result = parse(source);
|
||||
if (!result)
|
||||
throw new Error("Unknown error parsing astro config");
|
||||
if (result.errors.length > 0)
|
||||
throw new Error("Error parsing astro config: " + JSON.stringify(result.errors));
|
||||
return result;
|
||||
}
|
||||
const toIdent = (name) => {
|
||||
const ident = name.trim().replace(/[-_./]?astro(?:js)?[-_.]?/g, "").replace(/\.js/, "").replace(/[.\-_/]+([a-zA-Z])/g, (_, w) => w.toUpperCase()).replace(/^[^a-zA-Z$_]+/, "");
|
||||
return `${ident[0].toLowerCase()}${ident.slice(1)}`;
|
||||
};
|
||||
function createPrettyError(err) {
|
||||
err.message = `Astro could not update your astro.config.js file safely.
|
||||
Reason: ${err.message}
|
||||
|
||||
You will need to add these integration(s) manually.
|
||||
Documentation: https://docs.astro.build/en/guides/integrations-guide/`;
|
||||
return err;
|
||||
}
|
||||
async function addIntegration(ast, integration) {
|
||||
const integrationId = t.identifier(toIdent(integration.id));
|
||||
ensureImport(
|
||||
ast,
|
||||
t.importDeclaration(
|
||||
[t.importDefaultSpecifier(integrationId)],
|
||||
t.stringLiteral(integration.packageName)
|
||||
)
|
||||
);
|
||||
visit(ast, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-shadow
|
||||
ExportDefaultDeclaration(path2) {
|
||||
if (!t.isCallExpression(path2.node.declaration))
|
||||
return;
|
||||
const configObject = path2.node.declaration.arguments[0];
|
||||
if (!t.isObjectExpression(configObject))
|
||||
return;
|
||||
let integrationsProp = configObject.properties.find((prop) => {
|
||||
if (prop.type !== "ObjectProperty")
|
||||
return false;
|
||||
if (prop.key.type === "Identifier") {
|
||||
if (prop.key.name === "integrations")
|
||||
return true;
|
||||
}
|
||||
if (prop.key.type === "StringLiteral") {
|
||||
if (prop.key.value === "integrations")
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
const integrationCall = t.callExpression(integrationId, []);
|
||||
if (!integrationsProp) {
|
||||
configObject.properties.push(
|
||||
t.objectProperty(t.identifier("integrations"), t.arrayExpression([integrationCall]))
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (integrationsProp.value.type !== "ArrayExpression")
|
||||
throw new Error("Unable to parse integrations");
|
||||
const existingIntegrationCall = integrationsProp.value.elements.find(
|
||||
(expr) => t.isCallExpression(expr) && t.isIdentifier(expr.callee) && expr.callee.name === integrationId.name
|
||||
);
|
||||
if (existingIntegrationCall)
|
||||
return;
|
||||
integrationsProp.value.elements.push(integrationCall);
|
||||
}
|
||||
});
|
||||
}
|
||||
async function setAdapter(ast, adapter, exportName) {
|
||||
const adapterId = t.identifier(toIdent(adapter.id));
|
||||
ensureImport(
|
||||
ast,
|
||||
t.importDeclaration([t.importDefaultSpecifier(adapterId)], t.stringLiteral(exportName))
|
||||
);
|
||||
visit(ast, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-shadow
|
||||
ExportDefaultDeclaration(path2) {
|
||||
if (!t.isCallExpression(path2.node.declaration))
|
||||
return;
|
||||
const configObject = path2.node.declaration.arguments[0];
|
||||
if (!t.isObjectExpression(configObject))
|
||||
return;
|
||||
let outputProp = configObject.properties.find((prop) => {
|
||||
if (prop.type !== "ObjectProperty")
|
||||
return false;
|
||||
if (prop.key.type === "Identifier") {
|
||||
if (prop.key.name === "output")
|
||||
return true;
|
||||
}
|
||||
if (prop.key.type === "StringLiteral") {
|
||||
if (prop.key.value === "output")
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (!outputProp) {
|
||||
configObject.properties.push(
|
||||
t.objectProperty(t.identifier("output"), t.stringLiteral("server"))
|
||||
);
|
||||
}
|
||||
let adapterProp = configObject.properties.find((prop) => {
|
||||
if (prop.type !== "ObjectProperty")
|
||||
return false;
|
||||
if (prop.key.type === "Identifier") {
|
||||
if (prop.key.name === "adapter")
|
||||
return true;
|
||||
}
|
||||
if (prop.key.type === "StringLiteral") {
|
||||
if (prop.key.value === "adapter")
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
let adapterCall;
|
||||
switch (adapter.id) {
|
||||
case "node": {
|
||||
adapterCall = t.callExpression(adapterId, [
|
||||
t.objectExpression([
|
||||
t.objectProperty(t.identifier("mode"), t.stringLiteral("standalone"))
|
||||
])
|
||||
]);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
adapterCall = t.callExpression(adapterId, []);
|
||||
}
|
||||
}
|
||||
if (!adapterProp) {
|
||||
configObject.properties.push(t.objectProperty(t.identifier("adapter"), adapterCall));
|
||||
return;
|
||||
}
|
||||
adapterProp.value = adapterCall;
|
||||
}
|
||||
});
|
||||
}
|
||||
var UpdateResult = /* @__PURE__ */ ((UpdateResult2) => {
|
||||
UpdateResult2[UpdateResult2["none"] = 0] = "none";
|
||||
UpdateResult2[UpdateResult2["updated"] = 1] = "updated";
|
||||
UpdateResult2[UpdateResult2["cancelled"] = 2] = "cancelled";
|
||||
UpdateResult2[UpdateResult2["failure"] = 3] = "failure";
|
||||
return UpdateResult2;
|
||||
})(UpdateResult || {});
|
||||
async function updateAstroConfig({
|
||||
configURL,
|
||||
ast,
|
||||
flags,
|
||||
logger,
|
||||
logAdapterInstructions
|
||||
}) {
|
||||
const input = await fs.readFile(fileURLToPath(configURL), { encoding: "utf-8" });
|
||||
let output = await generate(ast);
|
||||
const comment = "// https://astro.build/config";
|
||||
const defaultExport = "export default defineConfig";
|
||||
output = output.replace(`
|
||||
${comment}`, "");
|
||||
output = output.replace(`${defaultExport}`, `
|
||||
${comment}
|
||||
${defaultExport}`);
|
||||
if (input === output) {
|
||||
return 0 /* none */;
|
||||
}
|
||||
const diff = getDiffContent(input, output);
|
||||
if (!diff) {
|
||||
return 0 /* none */;
|
||||
}
|
||||
const message = `
|
||||
${boxen(diff, {
|
||||
margin: 0.5,
|
||||
padding: 0.5,
|
||||
borderStyle: "round",
|
||||
title: configURL.pathname.split("/").pop()
|
||||
})}
|
||||
`;
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta("Astro will make the following changes to your config file:")}
|
||||
${message}`
|
||||
);
|
||||
if (logAdapterInstructions) {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
magenta(
|
||||
` For complete deployment options, visit
|
||||
${bold(
|
||||
"https://docs.astro.build/en/guides/deploy/"
|
||||
)}
|
||||
`
|
||||
)
|
||||
);
|
||||
}
|
||||
if (await askToContinue({ flags })) {
|
||||
await fs.writeFile(fileURLToPath(configURL), output, { encoding: "utf-8" });
|
||||
logger.debug("add", `Updated astro config`);
|
||||
return 1 /* updated */;
|
||||
} else {
|
||||
return 2 /* cancelled */;
|
||||
}
|
||||
}
|
||||
async function getInstallIntegrationsCommand({
|
||||
integrations,
|
||||
logger,
|
||||
cwd = process.cwd()
|
||||
}) {
|
||||
const pm = await preferredPM(cwd);
|
||||
logger.debug("add", `package manager: ${JSON.stringify(pm)}`);
|
||||
if (!pm)
|
||||
return null;
|
||||
const dependencies = await convertIntegrationsToInstallSpecifiers(integrations);
|
||||
switch (pm.name) {
|
||||
case "npm":
|
||||
return { pm: "npm", command: "install", flags: [], dependencies };
|
||||
case "yarn":
|
||||
return { pm: "yarn", command: "add", flags: [], dependencies };
|
||||
case "pnpm":
|
||||
return { pm: "pnpm", command: "add", flags: [], dependencies };
|
||||
case "bun":
|
||||
return { pm: "bun", command: "add", flags: [], dependencies };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async function convertIntegrationsToInstallSpecifiers(integrations) {
|
||||
const ranges = {};
|
||||
for (let { packageName, dependencies } of integrations) {
|
||||
ranges[packageName] = "*";
|
||||
for (const [name, range] of dependencies) {
|
||||
ranges[name] = range;
|
||||
}
|
||||
}
|
||||
return Promise.all(
|
||||
Object.entries(ranges).map(([name, range]) => resolveRangeToInstallSpecifier(name, range))
|
||||
);
|
||||
}
|
||||
async function resolveRangeToInstallSpecifier(name, range) {
|
||||
const versions = await fetchPackageVersions(name);
|
||||
if (versions instanceof Error)
|
||||
return name;
|
||||
const stableVersions = versions.filter((v) => !v.includes("-"));
|
||||
const maxStable = maxSatisfying(stableVersions, range);
|
||||
return `${name}@^${maxStable}`;
|
||||
}
|
||||
const INHERITED_FLAGS = /* @__PURE__ */ new Set([
|
||||
"P",
|
||||
"save-prod",
|
||||
"D",
|
||||
"save-dev",
|
||||
"E",
|
||||
"save-exact",
|
||||
"no-save"
|
||||
]);
|
||||
async function tryToInstallIntegrations({
|
||||
integrations,
|
||||
cwd,
|
||||
flags,
|
||||
logger
|
||||
}) {
|
||||
const installCommand = await getInstallIntegrationsCommand({ integrations, cwd, logger });
|
||||
const inheritedFlags = Object.entries(flags).map(([flag]) => {
|
||||
if (flag == "_")
|
||||
return;
|
||||
if (INHERITED_FLAGS.has(flag)) {
|
||||
if (flag.length === 1)
|
||||
return `-${flag}`;
|
||||
return `--${flag}`;
|
||||
}
|
||||
}).filter(Boolean).flat();
|
||||
if (installCommand === null) {
|
||||
return 0 /* none */;
|
||||
} else {
|
||||
const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
|
||||
"",
|
||||
...installCommand.flags,
|
||||
...inheritedFlags
|
||||
].join(" ")} ${cyan(installCommand.dependencies.join(" "))}`;
|
||||
const message = `
|
||||
${boxen(coloredOutput, {
|
||||
margin: 0.5,
|
||||
padding: 0.5,
|
||||
borderStyle: "round"
|
||||
})}
|
||||
`;
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta("Astro will run the following command:")}
|
||||
${dim(
|
||||
"If you skip this step, you can always run it yourself later"
|
||||
)}
|
||||
${message}`
|
||||
);
|
||||
if (await askToContinue({ flags })) {
|
||||
const spinner = ora("Installing dependencies...").start();
|
||||
try {
|
||||
await execa(
|
||||
installCommand.pm,
|
||||
[
|
||||
installCommand.command,
|
||||
...installCommand.flags,
|
||||
...inheritedFlags,
|
||||
...installCommand.dependencies
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
// reset NODE_ENV to ensure install command run in dev mode
|
||||
env: { NODE_ENV: void 0 }
|
||||
}
|
||||
);
|
||||
spinner.succeed();
|
||||
return 1 /* updated */;
|
||||
} catch (err) {
|
||||
spinner.fail();
|
||||
logger.debug("add", "Error installing dependencies", err);
|
||||
console.error("\n", err.stdout || err.message, "\n");
|
||||
return 3 /* failure */;
|
||||
}
|
||||
} else {
|
||||
return 2 /* cancelled */;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function validateIntegrations(integrations) {
|
||||
const spinner = ora("Resolving packages...").start();
|
||||
try {
|
||||
const integrationEntries = await Promise.all(
|
||||
integrations.map(async (integration) => {
|
||||
const parsed = parseIntegrationName(integration);
|
||||
if (!parsed) {
|
||||
throw new Error(`${bold(integration)} does not appear to be a valid package name!`);
|
||||
}
|
||||
let { scope, name, tag } = parsed;
|
||||
let pkgJson;
|
||||
let pkgType;
|
||||
if (scope && scope !== "@astrojs") {
|
||||
pkgType = "third-party";
|
||||
} else {
|
||||
const firstPartyPkgCheck = await fetchPackageJson("@astrojs", name, tag);
|
||||
if (firstPartyPkgCheck instanceof Error) {
|
||||
if (firstPartyPkgCheck.message) {
|
||||
spinner.warn(yellow(firstPartyPkgCheck.message));
|
||||
}
|
||||
spinner.warn(yellow(`${bold(integration)} is not an official Astro package.`));
|
||||
const response = await prompts({
|
||||
type: "confirm",
|
||||
name: "askToContinue",
|
||||
message: "Continue?",
|
||||
initial: true
|
||||
});
|
||||
if (!response.askToContinue) {
|
||||
throw new Error(
|
||||
`No problem! Find our official integrations at ${cyan(
|
||||
"https://astro.build/integrations"
|
||||
)}`
|
||||
);
|
||||
}
|
||||
spinner.start("Resolving with third party packages...");
|
||||
pkgType = "third-party";
|
||||
} else {
|
||||
pkgType = "first-party";
|
||||
pkgJson = firstPartyPkgCheck;
|
||||
}
|
||||
}
|
||||
if (pkgType === "third-party") {
|
||||
const thirdPartyPkgCheck = await fetchPackageJson(scope, name, tag);
|
||||
if (thirdPartyPkgCheck instanceof Error) {
|
||||
if (thirdPartyPkgCheck.message) {
|
||||
spinner.warn(yellow(thirdPartyPkgCheck.message));
|
||||
}
|
||||
throw new Error(`Unable to fetch ${bold(integration)}. Does the package exist?`);
|
||||
} else {
|
||||
pkgJson = thirdPartyPkgCheck;
|
||||
}
|
||||
}
|
||||
const resolvedScope = pkgType === "first-party" ? "@astrojs" : scope;
|
||||
const packageName = `${resolvedScope ? `${resolvedScope}/` : ""}${name}`;
|
||||
let dependencies = [
|
||||
[pkgJson["name"], `^${pkgJson["version"]}`]
|
||||
];
|
||||
if (pkgJson["peerDependencies"]) {
|
||||
const meta = pkgJson["peerDependenciesMeta"] || {};
|
||||
for (const peer in pkgJson["peerDependencies"]) {
|
||||
const optional = meta[peer]?.optional || false;
|
||||
const isAstro = peer === "astro";
|
||||
if (!optional && !isAstro) {
|
||||
dependencies.push([peer, pkgJson["peerDependencies"][peer]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let integrationType;
|
||||
const keywords = Array.isArray(pkgJson["keywords"]) ? pkgJson["keywords"] : [];
|
||||
if (keywords.includes("astro-integration")) {
|
||||
integrationType = "integration";
|
||||
} else if (keywords.includes("astro-adapter")) {
|
||||
integrationType = "adapter";
|
||||
} else {
|
||||
throw new Error(
|
||||
`${bold(
|
||||
packageName
|
||||
)} doesn't appear to be an integration or an adapter. Find our official integrations at ${cyan(
|
||||
"https://astro.build/integrations"
|
||||
)}`
|
||||
);
|
||||
}
|
||||
return { id: integration, packageName, dependencies, type: integrationType };
|
||||
})
|
||||
);
|
||||
spinner.succeed();
|
||||
return integrationEntries;
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
spinner.fail(e.message);
|
||||
process.exit(1);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function updateTSConfig(cwd = process.cwd(), logger, integrationsInfo, flags) {
|
||||
const integrations = integrationsInfo.map(
|
||||
(integration) => integration.id
|
||||
);
|
||||
const firstIntegrationWithTSSettings = integrations.find(
|
||||
(integration) => presets.has(integration)
|
||||
);
|
||||
if (!firstIntegrationWithTSSettings) {
|
||||
return 0 /* none */;
|
||||
}
|
||||
let inputConfig = await loadTSConfig(cwd);
|
||||
let inputConfigText = "";
|
||||
if (inputConfig === "invalid-config" || inputConfig === "unknown-error") {
|
||||
return 3 /* failure */;
|
||||
} else if (inputConfig === "missing-config") {
|
||||
logger.debug("add", "Couldn't find tsconfig.json or jsconfig.json, generating one");
|
||||
inputConfig = {
|
||||
tsconfig: defaultTSConfig,
|
||||
tsconfigFile: path.join(cwd, "tsconfig.json"),
|
||||
rawConfig: defaultTSConfig
|
||||
};
|
||||
} else {
|
||||
inputConfigText = JSON.stringify(inputConfig.rawConfig, null, 2);
|
||||
}
|
||||
const configFileName = path.basename(inputConfig.tsconfigFile);
|
||||
const outputConfig = updateTSConfigForFramework(
|
||||
inputConfig.rawConfig,
|
||||
firstIntegrationWithTSSettings
|
||||
);
|
||||
const output = JSON.stringify(outputConfig, null, 2);
|
||||
const diff = getDiffContent(inputConfigText, output);
|
||||
if (!diff) {
|
||||
return 0 /* none */;
|
||||
}
|
||||
const message = `
|
||||
${boxen(diff, {
|
||||
margin: 0.5,
|
||||
padding: 0.5,
|
||||
borderStyle: "round",
|
||||
title: configFileName
|
||||
})}
|
||||
`;
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta(`Astro will make the following changes to your ${configFileName}:`)}
|
||||
${message}`
|
||||
);
|
||||
const conflictingIntegrations = [...Object.keys(presets).filter((config) => config !== "vue")];
|
||||
const hasConflictingIntegrations = integrations.filter((integration) => presets.has(integration)).length > 1 && integrations.filter((integration) => conflictingIntegrations.includes(integration)).length > 0;
|
||||
if (hasConflictingIntegrations) {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
red(
|
||||
` ${bold(
|
||||
"Caution:"
|
||||
)} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold(
|
||||
firstIntegrationWithTSSettings
|
||||
)} were used.
|
||||
More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time
|
||||
`
|
||||
)
|
||||
);
|
||||
}
|
||||
if (await askToContinue({ flags })) {
|
||||
await fs.writeFile(inputConfig.tsconfigFile, output, {
|
||||
encoding: "utf-8"
|
||||
});
|
||||
logger.debug("add", `Updated ${configFileName} file`);
|
||||
return 1 /* updated */;
|
||||
} else {
|
||||
return 2 /* cancelled */;
|
||||
}
|
||||
}
|
||||
function parseIntegrationName(spec) {
|
||||
const result = parseNpmName(spec);
|
||||
if (!result)
|
||||
return;
|
||||
let { scope, name } = result;
|
||||
let tag = "latest";
|
||||
if (scope) {
|
||||
name = name.replace(scope + "/", "");
|
||||
}
|
||||
if (name.includes("@")) {
|
||||
const tagged = name.split("@");
|
||||
name = tagged[0];
|
||||
tag = tagged[1];
|
||||
}
|
||||
return { scope, name, tag };
|
||||
}
|
||||
async function askToContinue({ flags }) {
|
||||
if (flags.yes || flags.y)
|
||||
return true;
|
||||
const response = await prompts({
|
||||
type: "confirm",
|
||||
name: "askToContinue",
|
||||
message: "Continue?",
|
||||
initial: true
|
||||
});
|
||||
return Boolean(response.askToContinue);
|
||||
}
|
||||
function getDiffContent(input, output) {
|
||||
let changes = [];
|
||||
for (const change of diffWords(input, output)) {
|
||||
let lines = change.value.trim().split("\n").slice(0, change.count);
|
||||
if (lines.length === 0)
|
||||
continue;
|
||||
if (change.added) {
|
||||
if (!change.value.trim())
|
||||
continue;
|
||||
changes.push(change.value);
|
||||
}
|
||||
}
|
||||
if (changes.length === 0) {
|
||||
return null;
|
||||
}
|
||||
let diffed = output;
|
||||
for (let newContent of changes) {
|
||||
const coloredOutput = newContent.split("\n").map((ln) => ln ? green(ln) : "").join("\n");
|
||||
diffed = diffed.replace(newContent, coloredOutput);
|
||||
}
|
||||
return diffed;
|
||||
}
|
||||
async function setupIntegrationConfig(opts) {
|
||||
const logger = opts.logger;
|
||||
const possibleConfigFiles = opts.possibleConfigFiles.map(
|
||||
(p) => fileURLToPath(new URL(p, opts.root))
|
||||
);
|
||||
let alreadyConfigured = false;
|
||||
for (const possibleConfigPath of possibleConfigFiles) {
|
||||
if (existsSync(possibleConfigPath)) {
|
||||
alreadyConfigured = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!alreadyConfigured) {
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}
|
||||
`
|
||||
);
|
||||
if (await askToContinue({ flags: opts.flags })) {
|
||||
await fs.writeFile(
|
||||
fileURLToPath(new URL(opts.defaultConfigFile, opts.root)),
|
||||
opts.defaultConfigContent,
|
||||
{
|
||||
encoding: "utf-8"
|
||||
}
|
||||
);
|
||||
logger.debug("add", `Generated default ${opts.defaultConfigFile} file`);
|
||||
}
|
||||
} else {
|
||||
logger.debug("add", `Using existing ${opts.integrationName} configuration`);
|
||||
}
|
||||
}
|
||||
export {
|
||||
add,
|
||||
validateIntegrations
|
||||
};
|
||||
2
node_modules/astro/dist/cli/add/wrapper.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/cli/add/wrapper.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import { t } from './babel.js';
|
||||
export declare function wrapDefaultExport(ast: t.File, functionIdentifier: t.Identifier): void;
|
||||
15
node_modules/astro/dist/cli/add/wrapper.js
generated
vendored
Normal file
15
node_modules/astro/dist/cli/add/wrapper.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import { t, visit } from "./babel.js";
|
||||
function wrapDefaultExport(ast, functionIdentifier) {
|
||||
visit(ast, {
|
||||
ExportDefaultDeclaration(path) {
|
||||
if (!t.isExpression(path.node.declaration))
|
||||
return;
|
||||
if (t.isCallExpression(path.node.declaration) && t.isIdentifier(path.node.declaration.callee) && path.node.declaration.callee.name === functionIdentifier.name)
|
||||
return;
|
||||
path.node.declaration = t.callExpression(functionIdentifier, [path.node.declaration]);
|
||||
}
|
||||
});
|
||||
}
|
||||
export {
|
||||
wrapDefaultExport
|
||||
};
|
||||
6
node_modules/astro/dist/cli/build/index.d.ts
generated
vendored
Normal file
6
node_modules/astro/dist/cli/build/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface BuildOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function build({ flags }: BuildOptions): Promise<void>;
|
||||
export {};
|
||||
24
node_modules/astro/dist/cli/build/index.js
generated
vendored
Normal file
24
node_modules/astro/dist/cli/build/index.js
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
import _build from "../../core/build/index.js";
|
||||
import { printHelp } from "../../core/messages.js";
|
||||
import { flagsToAstroInlineConfig } from "../flags.js";
|
||||
async function build({ flags }) {
|
||||
if (flags?.help || flags?.h) {
|
||||
printHelp({
|
||||
commandName: "astro build",
|
||||
usage: "[...flags]",
|
||||
tables: {
|
||||
Flags: [
|
||||
["--outDir <directory>", `Specify the output directory for the build.`],
|
||||
["--help (-h)", "See all available flags."]
|
||||
]
|
||||
},
|
||||
description: `Builds your site for deployment.`
|
||||
});
|
||||
return;
|
||||
}
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
await _build(inlineConfig, { force: flags.force ?? false });
|
||||
}
|
||||
export {
|
||||
build
|
||||
};
|
||||
2
node_modules/astro/dist/cli/check/index.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/cli/check/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import type { Arguments } from 'yargs-parser';
|
||||
export declare function check(flags: Arguments): Promise<boolean | void>;
|
||||
36
node_modules/astro/dist/cli/check/index.js
generated
vendored
Normal file
36
node_modules/astro/dist/cli/check/index.js
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
import path from "node:path";
|
||||
import { ensureProcessNodeEnv } from "../../core/util.js";
|
||||
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
|
||||
import { getPackage } from "../install-package.js";
|
||||
async function check(flags) {
|
||||
ensureProcessNodeEnv("production");
|
||||
const logger = createLoggerFromFlags(flags);
|
||||
const getPackageOpts = { skipAsk: flags.yes || flags.y, cwd: flags.root };
|
||||
const checkPackage = await getPackage(
|
||||
"@astrojs/check",
|
||||
logger,
|
||||
getPackageOpts,
|
||||
["typescript"]
|
||||
);
|
||||
const typescript = await getPackage("typescript", logger, getPackageOpts);
|
||||
if (!checkPackage || !typescript) {
|
||||
logger.error(
|
||||
"check",
|
||||
"The `@astrojs/check` and `typescript` packages are required for this command to work. Please manually install them into your project and try again."
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { default: sync } = await import("../../core/sync/index.js");
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
const exitCode = await sync(inlineConfig);
|
||||
if (exitCode !== 0) {
|
||||
process.exit(exitCode);
|
||||
}
|
||||
const { check: checker, parseArgsAsCheckConfig } = checkPackage;
|
||||
const config = parseArgsAsCheckConfig(process.argv);
|
||||
logger.info("check", `Getting diagnostics for Astro files in ${path.resolve(config.root)}...`);
|
||||
return await checker(config);
|
||||
}
|
||||
export {
|
||||
check
|
||||
};
|
||||
4
node_modules/astro/dist/cli/db/index.d.ts
generated
vendored
Normal file
4
node_modules/astro/dist/cli/db/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
import type { Arguments } from 'yargs-parser';
|
||||
export declare function db({ flags }: {
|
||||
flags: Arguments;
|
||||
}): Promise<void>;
|
||||
24
node_modules/astro/dist/cli/db/index.js
generated
vendored
Normal file
24
node_modules/astro/dist/cli/db/index.js
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
import { resolveConfig } from "../../core/config/config.js";
|
||||
import { apply as applyPolyfill } from "../../core/polyfill.js";
|
||||
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
|
||||
import { getPackage } from "../install-package.js";
|
||||
async function db({ flags }) {
|
||||
applyPolyfill();
|
||||
const logger = createLoggerFromFlags(flags);
|
||||
const getPackageOpts = { skipAsk: flags.yes || flags.y, cwd: flags.root };
|
||||
const dbPackage = await getPackage("@astrojs/db", logger, getPackageOpts, []);
|
||||
if (!dbPackage) {
|
||||
logger.error(
|
||||
"check",
|
||||
"The `@astrojs/db` package is required for this command to work. Please manually install it in your project and try again."
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { cli } = dbPackage;
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
const { astroConfig } = await resolveConfig(inlineConfig, "build");
|
||||
await cli({ flags, config: astroConfig });
|
||||
}
|
||||
export {
|
||||
db
|
||||
};
|
||||
6
node_modules/astro/dist/cli/dev/index.d.ts
generated
vendored
Normal file
6
node_modules/astro/dist/cli/dev/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface DevOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function dev({ flags }: DevOptions): Promise<import("../../core/dev/dev.js").DevServer | undefined>;
|
||||
export {};
|
||||
30
node_modules/astro/dist/cli/dev/index.js
generated
vendored
Normal file
30
node_modules/astro/dist/cli/dev/index.js
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
import { cyan } from "kleur/colors";
|
||||
import devServer from "../../core/dev/index.js";
|
||||
import { printHelp } from "../../core/messages.js";
|
||||
import { flagsToAstroInlineConfig } from "../flags.js";
|
||||
async function dev({ flags }) {
|
||||
if (flags.help || flags.h) {
|
||||
printHelp({
|
||||
commandName: "astro dev",
|
||||
usage: "[...flags]",
|
||||
tables: {
|
||||
Flags: [
|
||||
["--port", `Specify which port to run on. Defaults to 4321.`],
|
||||
["--host", `Listen on all addresses, including LAN and public addresses.`],
|
||||
["--host <custom-address>", `Expose on a network IP address at <custom-address>`],
|
||||
["--open", "Automatically open the app in the browser on server start"],
|
||||
["--help (-h)", "See all available flags."]
|
||||
]
|
||||
},
|
||||
description: `Check ${cyan(
|
||||
"https://docs.astro.build/en/reference/cli-reference/#astro-dev"
|
||||
)} for more information.`
|
||||
});
|
||||
return;
|
||||
}
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
return await devServer(inlineConfig);
|
||||
}
|
||||
export {
|
||||
dev
|
||||
};
|
||||
6
node_modules/astro/dist/cli/docs/index.d.ts
generated
vendored
Normal file
6
node_modules/astro/dist/cli/docs/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface DocsOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function docs({ flags }: DocsOptions): Promise<import("execa").ExecaReturnValue<string> | undefined>;
|
||||
export {};
|
||||
18
node_modules/astro/dist/cli/docs/index.js
generated
vendored
Normal file
18
node_modules/astro/dist/cli/docs/index.js
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import { printHelp } from "../../core/messages.js";
|
||||
import { openInBrowser } from "./open.js";
|
||||
async function docs({ flags }) {
|
||||
if (flags.help || flags.h) {
|
||||
printHelp({
|
||||
commandName: "astro docs",
|
||||
tables: {
|
||||
Flags: [["--help (-h)", "See all available flags."]]
|
||||
},
|
||||
description: `Launches the Astro Docs website directly from the terminal.`
|
||||
});
|
||||
return;
|
||||
}
|
||||
return await openInBrowser("https://docs.astro.build/");
|
||||
}
|
||||
export {
|
||||
docs
|
||||
};
|
||||
2
node_modules/astro/dist/cli/docs/open.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/cli/docs/open.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import type { ExecaChildProcess } from 'execa';
|
||||
export declare function openInBrowser(url: string): Promise<ExecaChildProcess>;
|
||||
28
node_modules/astro/dist/cli/docs/open.js
generated
vendored
Normal file
28
node_modules/astro/dist/cli/docs/open.js
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
import { execa } from "execa";
|
||||
const getPlatformSpecificCommand = () => {
|
||||
const isGitPod = Boolean(process.env.GITPOD_REPO_ROOT);
|
||||
const platform = isGitPod ? "gitpod" : process.platform;
|
||||
switch (platform) {
|
||||
case "android":
|
||||
case "linux":
|
||||
return ["xdg-open"];
|
||||
case "darwin":
|
||||
return ["open"];
|
||||
case "win32":
|
||||
return ["cmd", ["/c", "start"]];
|
||||
case "gitpod":
|
||||
return ["/ide/bin/remote-cli/gitpod-code", ["--openExternal"]];
|
||||
default:
|
||||
throw new Error(
|
||||
`It looks like your platform ("${platform}") isn't supported!
|
||||
To view Astro's docs, please visit https://docs.astro.build`
|
||||
);
|
||||
}
|
||||
};
|
||||
async function openInBrowser(url) {
|
||||
const [command, args = []] = getPlatformSpecificCommand();
|
||||
return execa(command, [...args, encodeURI(url)]);
|
||||
}
|
||||
export {
|
||||
openInBrowser
|
||||
};
|
||||
9
node_modules/astro/dist/cli/flags.d.ts
generated
vendored
Normal file
9
node_modules/astro/dist/cli/flags.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { Arguments as Flags } from 'yargs-parser';
|
||||
import type { AstroInlineConfig } from '../@types/astro.js';
|
||||
import { Logger } from '../core/logger/core.js';
|
||||
export declare function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig;
|
||||
/**
|
||||
* The `logging` is usually created from an `AstroInlineConfig`, but some flows like `add`
|
||||
* doesn't read the AstroConfig directly, so we create a `logging` object from the CLI flags instead.
|
||||
*/
|
||||
export declare function createLoggerFromFlags(flags: Flags): Logger;
|
||||
36
node_modules/astro/dist/cli/flags.js
generated
vendored
Normal file
36
node_modules/astro/dist/cli/flags.js
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Logger } from "../core/logger/core.js";
|
||||
import { nodeLogDestination } from "../core/logger/node.js";
|
||||
function flagsToAstroInlineConfig(flags) {
|
||||
return {
|
||||
// Inline-only configs
|
||||
configFile: typeof flags.config === "string" ? flags.config : void 0,
|
||||
mode: typeof flags.mode === "string" ? flags.mode : void 0,
|
||||
logLevel: flags.verbose ? "debug" : flags.silent ? "silent" : void 0,
|
||||
// Astro user configs
|
||||
root: typeof flags.root === "string" ? flags.root : void 0,
|
||||
site: typeof flags.site === "string" ? flags.site : void 0,
|
||||
base: typeof flags.base === "string" ? flags.base : void 0,
|
||||
outDir: typeof flags.outDir === "string" ? flags.outDir : void 0,
|
||||
server: {
|
||||
port: typeof flags.port === "number" ? flags.port : void 0,
|
||||
host: typeof flags.host === "string" || typeof flags.host === "boolean" ? flags.host : void 0,
|
||||
open: typeof flags.open === "string" || typeof flags.open === "boolean" ? flags.open : void 0
|
||||
}
|
||||
};
|
||||
}
|
||||
function createLoggerFromFlags(flags) {
|
||||
const logging = {
|
||||
dest: nodeLogDestination,
|
||||
level: "info"
|
||||
};
|
||||
if (flags.verbose) {
|
||||
logging.level = "debug";
|
||||
} else if (flags.silent) {
|
||||
logging.level = "silent";
|
||||
}
|
||||
return new Logger(logging);
|
||||
}
|
||||
export {
|
||||
createLoggerFromFlags,
|
||||
flagsToAstroInlineConfig
|
||||
};
|
||||
2
node_modules/astro/dist/cli/index.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/cli/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/** The primary CLI action */
|
||||
export declare function cli(args: string[]): Promise<void>;
|
||||
177
node_modules/astro/dist/cli/index.js
generated
vendored
Normal file
177
node_modules/astro/dist/cli/index.js
generated
vendored
Normal file
@@ -0,0 +1,177 @@
|
||||
import * as colors from "kleur/colors";
|
||||
import yargs from "yargs-parser";
|
||||
import { ASTRO_VERSION } from "../core/constants.js";
|
||||
async function printAstroHelp() {
|
||||
const { printHelp } = await import("../core/messages.js");
|
||||
printHelp({
|
||||
commandName: "astro",
|
||||
usage: "[command] [...flags]",
|
||||
headline: "Build faster websites.",
|
||||
tables: {
|
||||
Commands: [
|
||||
["add", "Add an integration."],
|
||||
["build", "Build your project and write it to disk."],
|
||||
["check", "Check your project for errors."],
|
||||
["db", "Manage your Astro database."],
|
||||
["dev", "Start the development server."],
|
||||
["docs", "Open documentation in your web browser."],
|
||||
["info", "List info about your current Astro setup."],
|
||||
["preview", "Preview your build locally."],
|
||||
["sync", "Generate content collection types."],
|
||||
["preferences", "Configure user preferences."],
|
||||
["telemetry", "Configure telemetry settings."]
|
||||
],
|
||||
"Studio Commands": [
|
||||
["login", "Authenticate your machine with Astro Studio."],
|
||||
["logout", "End your authenticated session with Astro Studio."],
|
||||
["link", "Link this project directory to an Astro Studio project."]
|
||||
],
|
||||
"Global Flags": [
|
||||
["--config <path>", "Specify your config file."],
|
||||
["--root <path>", "Specify your project root folder."],
|
||||
["--site <url>", "Specify your project site."],
|
||||
["--base <pathname>", "Specify your project base."],
|
||||
["--verbose", "Enable verbose logging."],
|
||||
["--silent", "Disable all logging."],
|
||||
["--version", "Show the version number and exit."],
|
||||
["--help", "Show this help message."]
|
||||
]
|
||||
}
|
||||
});
|
||||
}
|
||||
function printVersion() {
|
||||
console.log();
|
||||
console.log(` ${colors.bgGreen(colors.black(` astro `))} ${colors.green(`v${ASTRO_VERSION}`)}`);
|
||||
}
|
||||
function resolveCommand(flags) {
|
||||
const cmd = flags._[2];
|
||||
if (flags.version)
|
||||
return "version";
|
||||
const supportedCommands = /* @__PURE__ */ new Set([
|
||||
"add",
|
||||
"sync",
|
||||
"telemetry",
|
||||
"preferences",
|
||||
"dev",
|
||||
"build",
|
||||
"preview",
|
||||
"check",
|
||||
"docs",
|
||||
"db",
|
||||
"info",
|
||||
"login",
|
||||
"loutout",
|
||||
"link",
|
||||
"init"
|
||||
]);
|
||||
if (supportedCommands.has(cmd)) {
|
||||
return cmd;
|
||||
}
|
||||
return "help";
|
||||
}
|
||||
async function runCommand(cmd, flags) {
|
||||
switch (cmd) {
|
||||
case "help":
|
||||
await printAstroHelp();
|
||||
return;
|
||||
case "version":
|
||||
printVersion();
|
||||
return;
|
||||
case "info": {
|
||||
const { printInfo } = await import("./info/index.js");
|
||||
await printInfo({ flags });
|
||||
return;
|
||||
}
|
||||
case "docs": {
|
||||
const { docs } = await import("./docs/index.js");
|
||||
await docs({ flags });
|
||||
return;
|
||||
}
|
||||
case "telemetry": {
|
||||
const { update } = await import("./telemetry/index.js");
|
||||
const subcommand = flags._[3]?.toString();
|
||||
await update(subcommand, { flags });
|
||||
return;
|
||||
}
|
||||
case "sync": {
|
||||
const { sync } = await import("./sync/index.js");
|
||||
const exitCode = await sync({ flags });
|
||||
return process.exit(exitCode);
|
||||
}
|
||||
case "preferences": {
|
||||
const { preferences } = await import("./preferences/index.js");
|
||||
const [subcommand, key, value] = flags._.slice(3).map((v) => v.toString());
|
||||
const exitCode = await preferences(subcommand, key, value, { flags });
|
||||
return process.exit(exitCode);
|
||||
}
|
||||
}
|
||||
if (flags.verbose) {
|
||||
const { enableVerboseLogging } = await import("../core/logger/node.js");
|
||||
enableVerboseLogging();
|
||||
}
|
||||
const { notify } = await import("./telemetry/index.js");
|
||||
await notify();
|
||||
switch (cmd) {
|
||||
case "add": {
|
||||
const { add } = await import("./add/index.js");
|
||||
const packages = flags._.slice(3);
|
||||
await add(packages, { flags });
|
||||
return;
|
||||
}
|
||||
case "db":
|
||||
case "login":
|
||||
case "logout":
|
||||
case "link":
|
||||
case "init": {
|
||||
const { db } = await import("./db/index.js");
|
||||
await db({ flags });
|
||||
return;
|
||||
}
|
||||
case "dev": {
|
||||
const { dev } = await import("./dev/index.js");
|
||||
const server = await dev({ flags });
|
||||
if (server) {
|
||||
return await new Promise(() => {
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "build": {
|
||||
const { build } = await import("./build/index.js");
|
||||
await build({ flags });
|
||||
return;
|
||||
}
|
||||
case "preview": {
|
||||
const { preview } = await import("./preview/index.js");
|
||||
const server = await preview({ flags });
|
||||
if (server) {
|
||||
return await server.closed();
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "check": {
|
||||
const { check } = await import("./check/index.js");
|
||||
const checkServer = await check(flags);
|
||||
if (flags.watch) {
|
||||
return await new Promise(() => {
|
||||
});
|
||||
} else {
|
||||
return process.exit(checkServer ? 1 : 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(`Error running ${cmd} -- no command found.`);
|
||||
}
|
||||
async function cli(args) {
|
||||
const flags = yargs(args, { boolean: ["global"], alias: { g: "global" } });
|
||||
const cmd = resolveCommand(flags);
|
||||
try {
|
||||
await runCommand(cmd, flags);
|
||||
} catch (err) {
|
||||
const { throwAndExit } = await import("./throw-and-exit.js");
|
||||
await throwAndExit(cmd, err);
|
||||
}
|
||||
}
|
||||
export {
|
||||
cli
|
||||
};
|
||||
11
node_modules/astro/dist/cli/info/index.d.ts
generated
vendored
Normal file
11
node_modules/astro/dist/cli/info/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
import type { AstroConfig, AstroUserConfig } from '../../@types/astro.js';
|
||||
interface InfoOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function getInfoOutput({ userConfig, print, }: {
|
||||
userConfig: AstroUserConfig | AstroConfig;
|
||||
print: boolean;
|
||||
}): Promise<string>;
|
||||
export declare function printInfo({ flags }: InfoOptions): Promise<void>;
|
||||
export {};
|
||||
117
node_modules/astro/dist/cli/info/index.js
generated
vendored
Normal file
117
node_modules/astro/dist/cli/info/index.js
generated
vendored
Normal file
@@ -0,0 +1,117 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { arch, platform } from "node:os";
|
||||
import * as colors from "kleur/colors";
|
||||
import prompts from "prompts";
|
||||
import { resolveConfig } from "../../core/config/index.js";
|
||||
import { ASTRO_VERSION } from "../../core/constants.js";
|
||||
import { apply as applyPolyfill } from "../../core/polyfill.js";
|
||||
import { flagsToAstroInlineConfig } from "../flags.js";
|
||||
async function getInfoOutput({
|
||||
userConfig,
|
||||
print
|
||||
}) {
|
||||
const rows = [
|
||||
["Astro", `v${ASTRO_VERSION}`],
|
||||
["Node", process.version],
|
||||
["System", getSystem()],
|
||||
["Package Manager", getPackageManager()]
|
||||
];
|
||||
try {
|
||||
rows.push(["Output", userConfig.output ?? "static"]);
|
||||
rows.push(["Adapter", userConfig.adapter?.name ?? "none"]);
|
||||
const integrations = (userConfig?.integrations ?? []).filter(Boolean).flat().map((i) => i?.name).filter(Boolean);
|
||||
rows.push(["Integrations", integrations.length > 0 ? integrations : "none"]);
|
||||
} catch {
|
||||
}
|
||||
let output = "";
|
||||
for (const [label, value] of rows) {
|
||||
output += printRow(label, value, print);
|
||||
}
|
||||
return output.trim();
|
||||
}
|
||||
async function printInfo({ flags }) {
|
||||
applyPolyfill();
|
||||
const { userConfig } = await resolveConfig(flagsToAstroInlineConfig(flags), "info");
|
||||
const output = await getInfoOutput({ userConfig, print: true });
|
||||
await copyToClipboard(output);
|
||||
}
|
||||
async function copyToClipboard(text) {
|
||||
const system = platform();
|
||||
let command = "";
|
||||
if (system === "darwin") {
|
||||
command = "pbcopy";
|
||||
} else if (system === "win32") {
|
||||
command = "clip";
|
||||
} else {
|
||||
try {
|
||||
const output = execSync("which xclip", { encoding: "utf8" });
|
||||
if (output[0] !== "/") {
|
||||
return;
|
||||
}
|
||||
command = "xclip -sel clipboard -l 1";
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log();
|
||||
const { shouldCopy } = await prompts({
|
||||
type: "confirm",
|
||||
name: "shouldCopy",
|
||||
message: "Copy to clipboard?",
|
||||
initial: true
|
||||
});
|
||||
if (!shouldCopy)
|
||||
return;
|
||||
try {
|
||||
execSync(command, {
|
||||
input: text.trim(),
|
||||
encoding: "utf8"
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(
|
||||
colors.red(`
|
||||
Sorry, something went wrong!`) + ` Please copy the text above manually.`
|
||||
);
|
||||
}
|
||||
}
|
||||
const PLATFORM_TO_OS = {
|
||||
darwin: "macOS",
|
||||
win32: "Windows",
|
||||
linux: "Linux"
|
||||
};
|
||||
function getSystem() {
|
||||
const system = PLATFORM_TO_OS[platform()] ?? platform();
|
||||
return `${system} (${arch()})`;
|
||||
}
|
||||
function getPackageManager() {
|
||||
if (!process.env.npm_config_user_agent) {
|
||||
return "unknown";
|
||||
}
|
||||
const specifier = process.env.npm_config_user_agent.split(" ")[0];
|
||||
const name = specifier.substring(0, specifier.lastIndexOf("/"));
|
||||
return name === "npminstall" ? "cnpm" : name;
|
||||
}
|
||||
const MAX_PADDING = 25;
|
||||
function printRow(label, value, print) {
|
||||
const padding = MAX_PADDING - label.length;
|
||||
const [first, ...rest] = Array.isArray(value) ? value : [value];
|
||||
let plaintext = `${label}${" ".repeat(padding)}${first}`;
|
||||
let richtext = `${colors.bold(label)}${" ".repeat(padding)}${colors.green(first)}`;
|
||||
if (rest.length > 0) {
|
||||
for (const entry of rest) {
|
||||
plaintext += `
|
||||
${" ".repeat(MAX_PADDING)}${entry}`;
|
||||
richtext += `
|
||||
${" ".repeat(MAX_PADDING)}${colors.green(entry)}`;
|
||||
}
|
||||
}
|
||||
plaintext += "\n";
|
||||
if (print) {
|
||||
console.log(richtext);
|
||||
}
|
||||
return plaintext;
|
||||
}
|
||||
export {
|
||||
getInfoOutput,
|
||||
printInfo
|
||||
};
|
||||
17
node_modules/astro/dist/cli/install-package.d.ts
generated
vendored
Normal file
17
node_modules/astro/dist/cli/install-package.d.ts
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
import { type Logger } from '../core/logger/core.js';
|
||||
type GetPackageOptions = {
|
||||
skipAsk?: boolean;
|
||||
optional?: boolean;
|
||||
cwd?: string;
|
||||
};
|
||||
export declare function getPackage<T>(packageName: string, logger: Logger, options: GetPackageOptions, otherDeps?: string[]): Promise<T | undefined>;
|
||||
/**
|
||||
* Get the command to execute and download a package (e.g. `npx`, `yarn dlx`, `pnpx`, etc.)
|
||||
* @param packageManager - Optional package manager to use. If not provided, Astro will attempt to detect the preferred package manager.
|
||||
* @returns The command to execute and download a package
|
||||
*/
|
||||
export declare function getExecCommand(packageManager?: string): Promise<string>;
|
||||
export declare function fetchPackageJson(scope: string | undefined, name: string, tag: string): Promise<Record<string, any> | Error>;
|
||||
export declare function fetchPackageVersions(packageName: string): Promise<string[] | Error>;
|
||||
export declare function getRegistry(): Promise<string>;
|
||||
export {};
|
||||
201
node_modules/astro/dist/cli/install-package.js
generated
vendored
Normal file
201
node_modules/astro/dist/cli/install-package.js
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import boxen from "boxen";
|
||||
import ci from "ci-info";
|
||||
import { execa } from "execa";
|
||||
import { bold, cyan, dim, magenta } from "kleur/colors";
|
||||
import ora from "ora";
|
||||
import preferredPM from "preferred-pm";
|
||||
import prompts from "prompts";
|
||||
import resolvePackage from "resolve";
|
||||
import whichPm from "which-pm";
|
||||
import {} from "../core/logger/core.js";
|
||||
const require2 = createRequire(import.meta.url);
|
||||
async function getPackage(packageName, logger, options, otherDeps = []) {
|
||||
try {
|
||||
if (packageName === "@astrojs/db") {
|
||||
const packageJsonLoc = require2.resolve(packageName + "/package.json", {
|
||||
paths: [options.cwd ?? process.cwd()]
|
||||
});
|
||||
const packageLoc = pathToFileURL(packageJsonLoc.replace(`package.json`, "dist/index.js"));
|
||||
const packageImport2 = await import(packageLoc.toString());
|
||||
return packageImport2;
|
||||
}
|
||||
await tryResolve(packageName, options.cwd ?? process.cwd());
|
||||
const packageImport = await import(packageName);
|
||||
return packageImport;
|
||||
} catch (e) {
|
||||
if (options.optional)
|
||||
return void 0;
|
||||
let message = `To continue, Astro requires the following dependency to be installed: ${bold(
|
||||
packageName
|
||||
)}.`;
|
||||
if (ci.isCI) {
|
||||
message += ` Packages cannot be installed automatically in CI environments.`;
|
||||
}
|
||||
logger.info("SKIP_FORMAT", message);
|
||||
if (ci.isCI) {
|
||||
return void 0;
|
||||
}
|
||||
const result = await installPackage([packageName, ...otherDeps], options, logger);
|
||||
if (result) {
|
||||
const packageImport = await import(packageName);
|
||||
return packageImport;
|
||||
} else {
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
function tryResolve(packageName, cwd) {
|
||||
return new Promise((resolve, reject) => {
|
||||
resolvePackage(
|
||||
packageName,
|
||||
{
|
||||
basedir: cwd
|
||||
},
|
||||
(err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(0);
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
function getInstallCommand(packages, packageManager) {
|
||||
switch (packageManager) {
|
||||
case "npm":
|
||||
return { pm: "npm", command: "install", flags: [], dependencies: packages };
|
||||
case "yarn":
|
||||
return { pm: "yarn", command: "add", flags: [], dependencies: packages };
|
||||
case "pnpm":
|
||||
return { pm: "pnpm", command: "add", flags: [], dependencies: packages };
|
||||
case "bun":
|
||||
return { pm: "bun", command: "add", flags: [], dependencies: packages };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async function getExecCommand(packageManager) {
|
||||
if (!packageManager) {
|
||||
packageManager = (await preferredPM(process.cwd()))?.name ?? "npm";
|
||||
}
|
||||
switch (packageManager) {
|
||||
case "npm":
|
||||
return "npx";
|
||||
case "yarn":
|
||||
return "yarn dlx";
|
||||
case "pnpm":
|
||||
return "pnpx";
|
||||
case "bun":
|
||||
return "bunx";
|
||||
default:
|
||||
return "npx";
|
||||
}
|
||||
}
|
||||
async function installPackage(packageNames, options, logger) {
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const packageManager = (await whichPm(cwd))?.name ?? "npm";
|
||||
const installCommand = getInstallCommand(packageNames, packageManager);
|
||||
if (!installCommand) {
|
||||
return false;
|
||||
}
|
||||
const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
|
||||
"",
|
||||
...installCommand.flags
|
||||
].join(" ")} ${cyan(installCommand.dependencies.join(" "))}`;
|
||||
const message = `
|
||||
${boxen(coloredOutput, {
|
||||
margin: 0.5,
|
||||
padding: 0.5,
|
||||
borderStyle: "round"
|
||||
})}
|
||||
`;
|
||||
logger.info(
|
||||
"SKIP_FORMAT",
|
||||
`
|
||||
${magenta("Astro will run the following command:")}
|
||||
${dim(
|
||||
"If you skip this step, you can always run it yourself later"
|
||||
)}
|
||||
${message}`
|
||||
);
|
||||
let response;
|
||||
if (options.skipAsk) {
|
||||
response = true;
|
||||
} else {
|
||||
response = (await prompts({
|
||||
type: "confirm",
|
||||
name: "askToContinue",
|
||||
message: "Continue?",
|
||||
initial: true
|
||||
})).askToContinue;
|
||||
}
|
||||
if (Boolean(response)) {
|
||||
const spinner = ora("Installing dependencies...").start();
|
||||
try {
|
||||
await execa(
|
||||
installCommand.pm,
|
||||
[installCommand.command, ...installCommand.flags, ...installCommand.dependencies],
|
||||
{ cwd }
|
||||
);
|
||||
spinner.succeed();
|
||||
return true;
|
||||
} catch (err) {
|
||||
logger.debug("add", "Error installing dependencies", err);
|
||||
spinner.fail();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
async function fetchPackageJson(scope, name, tag) {
|
||||
const packageName = `${scope ? `${scope}/` : ""}${name}`;
|
||||
const registry = await getRegistry();
|
||||
const res = await fetch(`${registry}/${packageName}/${tag}`);
|
||||
if (res.status >= 200 && res.status < 300) {
|
||||
return await res.json();
|
||||
} else if (res.status === 404) {
|
||||
return new Error();
|
||||
} else {
|
||||
return new Error(`Failed to fetch ${registry}/${packageName}/${tag} - GET ${res.status}`);
|
||||
}
|
||||
}
|
||||
async function fetchPackageVersions(packageName) {
|
||||
const registry = await getRegistry();
|
||||
const res = await fetch(`${registry}/${packageName}`, {
|
||||
headers: { accept: "application/vnd.npm.install-v1+json" }
|
||||
});
|
||||
if (res.status >= 200 && res.status < 300) {
|
||||
return await res.json().then((data) => Object.keys(data.versions));
|
||||
} else if (res.status === 404) {
|
||||
return new Error();
|
||||
} else {
|
||||
return new Error(`Failed to fetch ${registry}/${packageName} - GET ${res.status}`);
|
||||
}
|
||||
}
|
||||
let _registry;
|
||||
async function getRegistry() {
|
||||
if (_registry)
|
||||
return _registry;
|
||||
const fallback = "https://registry.npmjs.org";
|
||||
const packageManager = (await preferredPM(process.cwd()))?.name || "npm";
|
||||
try {
|
||||
const { stdout } = await execa(packageManager, ["config", "get", "registry"]);
|
||||
_registry = stdout?.trim()?.replace(/\/$/, "") || fallback;
|
||||
if (!new URL(_registry).host)
|
||||
_registry = fallback;
|
||||
} catch (e) {
|
||||
_registry = fallback;
|
||||
}
|
||||
return _registry;
|
||||
}
|
||||
export {
|
||||
fetchPackageJson,
|
||||
fetchPackageVersions,
|
||||
getExecCommand,
|
||||
getPackage,
|
||||
getRegistry
|
||||
};
|
||||
8
node_modules/astro/dist/cli/preferences/index.d.ts
generated
vendored
Normal file
8
node_modules/astro/dist/cli/preferences/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface PreferencesOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
declare const PREFERENCES_SUBCOMMANDS: readonly ["get", "set", "enable", "disable", "delete", "reset", "list"];
|
||||
export type Subcommand = (typeof PREFERENCES_SUBCOMMANDS)[number];
|
||||
export declare function preferences(subcommand: string, key: string, value: string | undefined, { flags }: PreferencesOptions): Promise<number>;
|
||||
export {};
|
||||
298
node_modules/astro/dist/cli/preferences/index.js
generated
vendored
Normal file
298
node_modules/astro/dist/cli/preferences/index.js
generated
vendored
Normal file
@@ -0,0 +1,298 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { bgGreen, black, bold, dim, yellow } from "kleur/colors";
|
||||
import { formatWithOptions } from "node:util";
|
||||
import dlv from "dlv";
|
||||
import { flattie } from "flattie";
|
||||
import { resolveConfig } from "../../core/config/config.js";
|
||||
import { createSettings } from "../../core/config/settings.js";
|
||||
import { collectErrorMetadata } from "../../core/errors/dev/utils.js";
|
||||
import * as msg from "../../core/messages.js";
|
||||
import { apply as applyPolyfill } from "../../core/polyfill.js";
|
||||
import { DEFAULT_PREFERENCES } from "../../preferences/defaults.js";
|
||||
import { coerce, isValidKey } from "../../preferences/index.js";
|
||||
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
|
||||
const PREFERENCES_SUBCOMMANDS = [
|
||||
"get",
|
||||
"set",
|
||||
"enable",
|
||||
"disable",
|
||||
"delete",
|
||||
"reset",
|
||||
"list"
|
||||
];
|
||||
function isValidSubcommand(subcommand) {
|
||||
return PREFERENCES_SUBCOMMANDS.includes(subcommand);
|
||||
}
|
||||
async function preferences(subcommand, key, value, { flags }) {
|
||||
applyPolyfill();
|
||||
if (!isValidSubcommand(subcommand) || flags?.help || flags?.h) {
|
||||
msg.printHelp({
|
||||
commandName: "astro preferences",
|
||||
usage: "[command]",
|
||||
tables: {
|
||||
Commands: [
|
||||
["list", "Pretty print all current preferences"],
|
||||
["list --json", "Log all current preferences as a JSON object"],
|
||||
["get [key]", "Log current preference value"],
|
||||
["set [key] [value]", "Update preference value"],
|
||||
["reset [key]", "Reset preference value to default"],
|
||||
["enable [key]", "Set a boolean preference to true"],
|
||||
["disable [key]", "Set a boolean preference to false"]
|
||||
],
|
||||
Flags: [
|
||||
[
|
||||
"--global",
|
||||
"Scope command to global preferences (all Astro projects) rather than the current project"
|
||||
]
|
||||
]
|
||||
}
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
const logger = createLoggerFromFlags(flags);
|
||||
const { astroConfig } = await resolveConfig(inlineConfig ?? {}, "dev");
|
||||
const settings = await createSettings(astroConfig, fileURLToPath(astroConfig.root));
|
||||
const opts = {
|
||||
location: flags.global ? "global" : void 0,
|
||||
json: flags.json
|
||||
};
|
||||
if (subcommand === "list") {
|
||||
return listPreferences(settings, opts);
|
||||
}
|
||||
if (subcommand === "enable" || subcommand === "disable") {
|
||||
key = `${key}.enabled`;
|
||||
}
|
||||
if (!isValidKey(key)) {
|
||||
logger.error("preferences", `Unknown preference "${key}"
|
||||
`);
|
||||
return 1;
|
||||
}
|
||||
if (subcommand === "set" && value === void 0) {
|
||||
const type = typeof dlv(DEFAULT_PREFERENCES, key);
|
||||
console.error(
|
||||
msg.formatErrorMessage(
|
||||
collectErrorMetadata(new Error(`Please provide a ${type} value for "${key}"`)),
|
||||
true
|
||||
)
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
switch (subcommand) {
|
||||
case "get":
|
||||
return getPreference(settings, key, opts);
|
||||
case "set":
|
||||
return setPreference(settings, key, value, opts);
|
||||
case "reset":
|
||||
case "delete":
|
||||
return resetPreference(settings, key, opts);
|
||||
case "enable":
|
||||
return enablePreference(settings, key, opts);
|
||||
case "disable":
|
||||
return disablePreference(settings, key, opts);
|
||||
}
|
||||
}
|
||||
async function getPreference(settings, key, { location = "project" }) {
|
||||
try {
|
||||
let value = await settings.preferences.get(key, { location });
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
if (Object.keys(value).length === 0) {
|
||||
value = dlv(DEFAULT_PREFERENCES, key);
|
||||
console.log(msg.preferenceDefaultIntro(key));
|
||||
}
|
||||
prettyPrint({ [key]: value });
|
||||
return 0;
|
||||
}
|
||||
if (value === void 0) {
|
||||
const defaultValue = await settings.preferences.get(key);
|
||||
console.log(msg.preferenceDefault(key, defaultValue));
|
||||
return 0;
|
||||
}
|
||||
console.log(msg.preferenceGet(key, value));
|
||||
return 0;
|
||||
} catch {
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
async function setPreference(settings, key, value, { location }) {
|
||||
try {
|
||||
const defaultType = typeof dlv(DEFAULT_PREFERENCES, key);
|
||||
if (typeof coerce(key, value) !== defaultType) {
|
||||
throw new Error(`${key} expects a "${defaultType}" value!`);
|
||||
}
|
||||
await settings.preferences.set(key, coerce(key, value), { location });
|
||||
console.log(msg.preferenceSet(key, value));
|
||||
return 0;
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
console.error(msg.formatErrorMessage(collectErrorMetadata(e), true));
|
||||
return 1;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
async function enablePreference(settings, key, { location }) {
|
||||
try {
|
||||
await settings.preferences.set(key, true, { location });
|
||||
console.log(msg.preferenceEnabled(key.replace(".enabled", "")));
|
||||
return 0;
|
||||
} catch {
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
async function disablePreference(settings, key, { location }) {
|
||||
try {
|
||||
await settings.preferences.set(key, false, { location });
|
||||
console.log(msg.preferenceDisabled(key.replace(".enabled", "")));
|
||||
return 0;
|
||||
} catch {
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
async function resetPreference(settings, key, { location }) {
|
||||
try {
|
||||
await settings.preferences.set(key, void 0, { location });
|
||||
console.log(msg.preferenceReset(key));
|
||||
return 0;
|
||||
} catch {
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
function annotate(flat, annotation) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(flat).map(([key, value]) => [key, { annotation, value }])
|
||||
);
|
||||
}
|
||||
function userValues(flatDefault, flatProject, flatGlobal) {
|
||||
const result = {};
|
||||
for (const key of Object.keys(flatDefault)) {
|
||||
if (key in flatProject) {
|
||||
result[key] = {
|
||||
value: flatProject[key],
|
||||
annotation: ""
|
||||
};
|
||||
if (key in flatGlobal) {
|
||||
result[key].annotation += ` (also modified globally)`;
|
||||
}
|
||||
} else if (key in flatGlobal) {
|
||||
result[key] = { value: flatGlobal[key], annotation: "(global)" };
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async function listPreferences(settings, { location, json }) {
|
||||
if (json) {
|
||||
const resolved = await settings.preferences.getAll();
|
||||
console.log(JSON.stringify(resolved, null, 2));
|
||||
return 0;
|
||||
}
|
||||
const { global, project, fromAstroConfig, defaults } = await settings.preferences.list({
|
||||
location
|
||||
});
|
||||
const flatProject = flattie(project);
|
||||
const flatGlobal = flattie(global);
|
||||
const flatDefault = flattie(defaults);
|
||||
const flatUser = userValues(flatDefault, flatProject, flatGlobal);
|
||||
const userKeys = Object.keys(flatUser);
|
||||
if (userKeys.length > 0) {
|
||||
const badge = bgGreen(black(` Your Preferences `));
|
||||
const table = formatTable(flatUser, ["Preference", "Value"]);
|
||||
console.log(["", badge, table].join("\n"));
|
||||
} else {
|
||||
const badge = bgGreen(black(` Your Preferences `));
|
||||
const message = dim("No preferences set");
|
||||
console.log(["", badge, "", message].join("\n"));
|
||||
}
|
||||
const flatUnset = annotate(Object.assign({}, flatDefault), "");
|
||||
for (const key of userKeys) {
|
||||
delete flatUnset[key];
|
||||
}
|
||||
const unsetKeys = Object.keys(flatUnset);
|
||||
if (unsetKeys.length > 0) {
|
||||
const badge = bgGreen(black(` Default Preferences `));
|
||||
const table = formatTable(flatUnset, ["Preference", "Value"]);
|
||||
console.log(["", badge, table].join("\n"));
|
||||
} else {
|
||||
const badge = bgGreen(black(` Default Preferences `));
|
||||
const message = dim("All preferences have been set");
|
||||
console.log(["", badge, "", message].join("\n"));
|
||||
}
|
||||
if (fromAstroConfig.devToolbar?.enabled === false && flatUser["devToolbar.enabled"]?.value !== false) {
|
||||
console.log(
|
||||
yellow(
|
||||
"The dev toolbar is currently disabled. To enable it, set devToolbar: {enabled: true} in your astroConfig file."
|
||||
)
|
||||
);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function prettyPrint(value) {
|
||||
const flattened = flattie(value);
|
||||
const table = formatTable(flattened, ["Preference", "Value"]);
|
||||
console.log(table);
|
||||
}
|
||||
const chars = {
|
||||
h: "\u2500",
|
||||
hThick: "\u2501",
|
||||
hThickCross: "\u253F",
|
||||
v: "\u2502",
|
||||
vRight: "\u251C",
|
||||
vRightThick: "\u251D",
|
||||
vLeft: "\u2524",
|
||||
vLeftThick: "\u2525",
|
||||
hTop: "\u2534",
|
||||
hBottom: "\u252C",
|
||||
topLeft: "\u256D",
|
||||
topRight: "\u256E",
|
||||
bottomLeft: "\u2570",
|
||||
bottomRight: "\u256F"
|
||||
};
|
||||
function annotatedFormat(mv) {
|
||||
return mv.annotation ? `${mv.value} ${mv.annotation}` : mv.value.toString();
|
||||
}
|
||||
function formatAnnotated(mv, style = (v) => v.toString()) {
|
||||
return mv.annotation ? `${style(mv.value)} ${dim(mv.annotation)}` : style(mv.value);
|
||||
}
|
||||
function formatTable(object, columnLabels) {
|
||||
const [colA, colB] = columnLabels;
|
||||
const colALength = [colA, ...Object.keys(object)].reduce(longest, 0) + 3;
|
||||
const colBLength = [colB, ...Object.values(object).map(annotatedFormat)].reduce(longest, 0) + 3;
|
||||
function formatRow(i2, a, b, style = (v) => v.toString()) {
|
||||
return `${dim(chars.v)} ${style(a)} ${space(colALength - a.length - 2)} ${dim(
|
||||
chars.v
|
||||
)} ${formatAnnotated(b, style)} ${space(colBLength - annotatedFormat(b).length - 3)} ${dim(
|
||||
chars.v
|
||||
)}`;
|
||||
}
|
||||
const top = dim(
|
||||
`${chars.topLeft}${chars.h.repeat(colALength + 1)}${chars.hBottom}${chars.h.repeat(
|
||||
colBLength
|
||||
)}${chars.topRight}`
|
||||
);
|
||||
const bottom = dim(
|
||||
`${chars.bottomLeft}${chars.h.repeat(colALength + 1)}${chars.hTop}${chars.h.repeat(
|
||||
colBLength
|
||||
)}${chars.bottomRight}`
|
||||
);
|
||||
const divider = dim(
|
||||
`${chars.vRightThick}${chars.hThick.repeat(colALength + 1)}${chars.hThickCross}${chars.hThick.repeat(colBLength)}${chars.vLeftThick}`
|
||||
);
|
||||
const rows = [top, formatRow(-1, colA, { value: colB, annotation: "" }, bold), divider];
|
||||
let i = 0;
|
||||
for (const [key, value] of Object.entries(object)) {
|
||||
rows.push(formatRow(i, key, value, (v) => formatWithOptions({ colors: true }, v)));
|
||||
i++;
|
||||
}
|
||||
rows.push(bottom);
|
||||
return rows.join("\n");
|
||||
}
|
||||
function space(len) {
|
||||
return " ".repeat(len);
|
||||
}
|
||||
const longest = (a, b) => {
|
||||
const { length: len } = b.toString();
|
||||
return a > len ? a : len;
|
||||
};
|
||||
export {
|
||||
preferences
|
||||
};
|
||||
6
node_modules/astro/dist/cli/preview/index.d.ts
generated
vendored
Normal file
6
node_modules/astro/dist/cli/preview/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface PreviewOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function preview({ flags }: PreviewOptions): Promise<import("../../@types/astro.js").PreviewServer | undefined>;
|
||||
export {};
|
||||
30
node_modules/astro/dist/cli/preview/index.js
generated
vendored
Normal file
30
node_modules/astro/dist/cli/preview/index.js
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
import { cyan } from "kleur/colors";
|
||||
import { printHelp } from "../../core/messages.js";
|
||||
import previewServer from "../../core/preview/index.js";
|
||||
import { flagsToAstroInlineConfig } from "../flags.js";
|
||||
async function preview({ flags }) {
|
||||
if (flags?.help || flags?.h) {
|
||||
printHelp({
|
||||
commandName: "astro preview",
|
||||
usage: "[...flags]",
|
||||
tables: {
|
||||
Flags: [
|
||||
["--port", `Specify which port to run on. Defaults to 4321.`],
|
||||
["--host", `Listen on all addresses, including LAN and public addresses.`],
|
||||
["--host <custom-address>", `Expose on a network IP address at <custom-address>`],
|
||||
["--open", "Automatically open the app in the browser on server start"],
|
||||
["--help (-h)", "See all available flags."]
|
||||
]
|
||||
},
|
||||
description: `Starts a local server to serve your static dist/ directory. Check ${cyan(
|
||||
"https://docs.astro.build/en/reference/cli-reference/#astro-preview"
|
||||
)} for more information.`
|
||||
});
|
||||
return;
|
||||
}
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
return await previewServer(inlineConfig);
|
||||
}
|
||||
export {
|
||||
preview
|
||||
};
|
||||
6
node_modules/astro/dist/cli/sync/index.d.ts
generated
vendored
Normal file
6
node_modules/astro/dist/cli/sync/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface SyncOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function sync({ flags }: SyncOptions): Promise<import("../../core/sync/index.js").ProcessExit>;
|
||||
export {};
|
||||
22
node_modules/astro/dist/cli/sync/index.js
generated
vendored
Normal file
22
node_modules/astro/dist/cli/sync/index.js
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
import { printHelp } from "../../core/messages.js";
|
||||
import _sync from "../../core/sync/index.js";
|
||||
import { flagsToAstroInlineConfig } from "../flags.js";
|
||||
async function sync({ flags }) {
|
||||
if (flags?.help || flags?.h) {
|
||||
printHelp({
|
||||
commandName: "astro sync",
|
||||
usage: "[...flags]",
|
||||
tables: {
|
||||
Flags: [["--help (-h)", "See all available flags."]]
|
||||
},
|
||||
description: `Generates TypeScript types for all Astro modules.`
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
const inlineConfig = flagsToAstroInlineConfig(flags);
|
||||
const exitCode = await _sync(inlineConfig);
|
||||
return exitCode;
|
||||
}
|
||||
export {
|
||||
sync
|
||||
};
|
||||
7
node_modules/astro/dist/cli/telemetry/index.d.ts
generated
vendored
Normal file
7
node_modules/astro/dist/cli/telemetry/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import type yargs from 'yargs-parser';
|
||||
interface TelemetryOptions {
|
||||
flags: yargs.Arguments;
|
||||
}
|
||||
export declare function notify(): Promise<void>;
|
||||
export declare function update(subcommand: string, { flags }: TelemetryOptions): Promise<void>;
|
||||
export {};
|
||||
48
node_modules/astro/dist/cli/telemetry/index.js
generated
vendored
Normal file
48
node_modules/astro/dist/cli/telemetry/index.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import * as msg from "../../core/messages.js";
|
||||
import { telemetry } from "../../events/index.js";
|
||||
import { createLoggerFromFlags } from "../flags.js";
|
||||
async function notify() {
|
||||
await telemetry.notify(() => {
|
||||
console.log(msg.telemetryNotice() + "\n");
|
||||
return true;
|
||||
});
|
||||
}
|
||||
async function update(subcommand, { flags }) {
|
||||
const isValid = ["enable", "disable", "reset"].includes(subcommand);
|
||||
const logger = createLoggerFromFlags(flags);
|
||||
if (flags.help || flags.h || !isValid) {
|
||||
msg.printHelp({
|
||||
commandName: "astro telemetry",
|
||||
usage: "[command]",
|
||||
tables: {
|
||||
Commands: [
|
||||
["enable", "Enable anonymous data collection."],
|
||||
["disable", "Disable anonymous data collection."],
|
||||
["reset", "Reset anonymous data collection settings."]
|
||||
]
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
switch (subcommand) {
|
||||
case "enable": {
|
||||
telemetry.setEnabled(true);
|
||||
logger.info("SKIP_FORMAT", msg.telemetryEnabled());
|
||||
return;
|
||||
}
|
||||
case "disable": {
|
||||
telemetry.setEnabled(false);
|
||||
logger.info("SKIP_FORMAT", msg.telemetryDisabled());
|
||||
return;
|
||||
}
|
||||
case "reset": {
|
||||
telemetry.clear();
|
||||
logger.info("SKIP_FORMAT", msg.telemetryReset());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
export {
|
||||
notify,
|
||||
update
|
||||
};
|
||||
2
node_modules/astro/dist/cli/throw-and-exit.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/cli/throw-and-exit.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/** Display error and exit */
|
||||
export declare function throwAndExit(cmd: string, err: unknown): Promise<void>;
|
||||
24
node_modules/astro/dist/cli/throw-and-exit.js
generated
vendored
Normal file
24
node_modules/astro/dist/cli/throw-and-exit.js
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
import { collectErrorMetadata } from "../core/errors/dev/index.js";
|
||||
import { isAstroConfigZodError } from "../core/errors/errors.js";
|
||||
import { createSafeError } from "../core/errors/index.js";
|
||||
import { debug } from "../core/logger/core.js";
|
||||
import { formatErrorMessage } from "../core/messages.js";
|
||||
import { eventError, telemetry } from "../events/index.js";
|
||||
async function throwAndExit(cmd, err) {
|
||||
if (isAstroConfigZodError(err))
|
||||
return;
|
||||
let telemetryPromise;
|
||||
let errorMessage;
|
||||
function exitWithErrorMessage() {
|
||||
console.error(errorMessage);
|
||||
process.exit(1);
|
||||
}
|
||||
const errorWithMetadata = collectErrorMetadata(createSafeError(err));
|
||||
telemetryPromise = telemetry.record(eventError({ cmd, err: errorWithMetadata, isFatal: true }));
|
||||
errorMessage = formatErrorMessage(errorWithMetadata, true);
|
||||
setTimeout(exitWithErrorMessage, 400);
|
||||
await telemetryPromise.catch((err2) => debug("telemetry", `record() error: ${err2.message}`)).then(exitWithErrorMessage);
|
||||
}
|
||||
export {
|
||||
throwAndExit
|
||||
};
|
||||
Reference in New Issue
Block a user