🎉 initiate project *astro_rewrite*

This commit is contained in:
sindrekjelsrud 2023-07-19 21:31:30 +02:00
parent ffd4d5e86c
commit 2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions

18
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
View 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
View 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
View 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
};

15
node_modules/astro/dist/cli/add/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,15 @@
import type yargs from 'yargs-parser';
import { type LogOptions } from '../../core/logger/core.js';
interface AddOptions {
logging: LogOptions;
flags: yargs.Arguments;
}
interface IntegrationInfo {
id: string;
packageName: string;
dependencies: [name: string, version: string][];
type: 'integration' | 'adapter';
}
export declare function add(names: string[], { flags, logging }: AddOptions): Promise<void>;
export declare function validateIntegrations(integrations: string[]): Promise<IntegrationInfo[]>;
export {};

833
node_modules/astro/dist/cli/add/index.js generated vendored Normal file
View file

@ -0,0 +1,833 @@
import boxen from "boxen";
import { diffWords } from "diff";
import { execa } from "execa";
import { bold, cyan, dim, green, magenta, red, yellow } from "kleur/colors";
import fsMod, { existsSync, promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import ora from "ora";
import preferredPM from "preferred-pm";
import prompts from "prompts";
import { loadTSConfig, resolveConfigPath } from "../../core/config/index.js";
import {
defaultTSConfig,
presets,
updateTSConfigForFramework
} from "../../core/config/tsconfig.js";
import { debug, info } from "../../core/logger/core.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 { parseNpmName } from "../../core/util.js";
import { eventCliSession, telemetry } from "../../events/index.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 ASTRO_CONFIG_STUB = `import { defineConfig } from 'astro/config';
export default defineConfig({});`;
const TAILWIND_CONFIG_STUB = `/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
theme: {
extend: {},
},
plugins: [],
}
`;
const SVELTE_CONFIG_STUB = `import { vitePreprocess } from '@astrojs/svelte';
export default {
preprocess: vitePreprocess(),
};
`;
const LIT_NPMRC_STUB = `# Lit libraries are required to be hoisted due to dependency issues.
public-hoist-pattern[]=*lit*
`;
const OFFICIAL_ADAPTER_TO_IMPORT_MAP = {
netlify: "@astrojs/netlify/functions",
vercel: "@astrojs/vercel/serverless",
cloudflare: "@astrojs/cloudflare",
node: "@astrojs/node",
deno: "@astrojs/deno"
};
async function getRegistry() {
var _a, _b;
const packageManager = ((_a = await preferredPM(process.cwd())) == null ? void 0 : _a.name) || "npm";
try {
const { stdout } = await execa(packageManager, ["config", "get", "registry"]);
return ((_b = stdout == null ? void 0 : stdout.trim()) == null ? void 0 : _b.replace(/\/$/, "")) || "https://registry.npmjs.org";
} catch (e) {
return "https://registry.npmjs.org";
}
}
async function add(names, { flags, logging }) {
var _a;
telemetry.record(eventCliSession("add"));
applyPolyfill();
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"],
["alpine", "astro add alpine"]
],
"SSR Adapters": [
["netlify", "astro add netlify"],
["vercel", "astro add vercel"],
["deno", "astro add deno"],
["cloudflare", "astro add cloudflare"],
["node", "astro add node"]
],
Others: [
["tailwind", "astro add tailwind"],
["image", "astro add image"],
["mdx", "astro add mdx"],
["partytown", "astro add partytown"],
["sitemap", "astro add sitemap"],
["prefetch", "astro add prefetch"]
]
},
description: `For more integrations, check out: ${cyan("https://astro.build/integrations")}`
});
return;
}
const cwd = flags.root;
const integrationNames = names.map((name) => ALIASES.has(name) ? ALIASES.get(name) : name);
const integrations = await validateIntegrations(integrationNames);
let installResult = await tryToInstallIntegrations({ integrations, cwd, flags, logging });
const root = pathToFileURL(cwd ? path.resolve(cwd) : process.cwd());
root.href = appendForwardSlash(root.href);
switch (installResult) {
case 1 /* updated */: {
if (integrations.find((integration) => integration.id === "tailwind")) {
await setupIntegrationConfig({
root,
logging,
flags,
integrationName: "Tailwind",
possibleConfigFiles: [
"./tailwind.config.cjs",
"./tailwind.config.mjs",
"./tailwind.config.js"
],
defaultConfigFile: "./tailwind.config.cjs",
defaultConfigContent: TAILWIND_CONFIG_STUB
});
}
if (integrations.find((integration) => integration.id === "svelte")) {
await setupIntegrationConfig({
root,
logging,
flags,
integrationName: "Svelte",
possibleConfigFiles: ["./svelte.config.js", "./svelte.config.cjs", "./svelte.config.mjs"],
defaultConfigFile: "./svelte.config.js",
defaultConfigContent: SVELTE_CONFIG_STUB
});
}
if (integrations.find((integration) => integration.id === "lit") && ((_a = await preferredPM(fileURLToPath(root))) == null ? void 0 : _a.name) === "pnpm") {
await setupIntegrationConfig({
root,
logging,
flags,
integrationName: "Lit",
possibleConfigFiles: ["./.npmrc"],
defaultConfigFile: "./.npmrc",
defaultConfigContent: LIT_NPMRC_STUB
});
}
break;
}
case 2 /* cancelled */: {
info(
logging,
null,
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`));
}
}
const rawConfigPath = await resolveConfigPath({ cwd, flags, fs: fsMod });
let configURL = rawConfigPath ? pathToFileURL(rawConfigPath) : void 0;
if (configURL) {
debug("add", `Found config at ${configURL}`);
} else {
info(logging, "add", `Unable to locate a config file, generating one for you.`);
configURL = new URL("./astro.config.mjs", root);
await fs.writeFile(fileURLToPath(configURL), ASTRO_CONFIG_STUB, { encoding: "utf-8" });
}
if (configURL == null ? void 0 : configURL.pathname.endsWith("package.json")) {
throw new Error(
`Unable to use "astro add" with package.json configuration. Try migrating to \`astro.config.mjs\` and try again.`
);
}
let ast = null;
try {
ast = await parseAstroConfig(configURL);
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);
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 {
info(
logging,
null,
`
${magenta(
`Check our deployment docs for ${bold(
integration.packageName
)} to update your "adapter" config.`
)}`
);
}
} else {
await addIntegration(ast, integration);
}
debug("add", `Astro config added integration ${integration.id}`);
}
} catch (err) {
debug("add", "Error parsing/modifying astro config: ", err);
throw createPrettyError(err);
}
let configResult;
if (ast) {
try {
configResult = await updateAstroConfig({
configURL,
ast,
flags,
logging,
logAdapterInstructions: integrations.some(isAdapter)
});
} catch (err) {
debug("add", "Error updating astro config", err);
throw createPrettyError(err);
}
}
switch (configResult) {
case 2 /* cancelled */: {
info(logging, null, 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) {
info(logging, null, msg.success(`Configuration up-to-date.`));
break;
}
}
info(logging, null, msg.success(`Configuration up-to-date.`));
break;
}
default: {
const list = integrations.map((integration) => ` - ${integration.packageName}`).join("\n");
info(
logging,
null,
msg.success(
`Added the following integration${integrations.length === 1 ? "" : "s"} to your project:
${list}`
)
);
}
}
const updateTSConfigResult = await updateTSConfig(cwd, logging, integrations, flags);
switch (updateTSConfigResult) {
case 0 /* none */: {
break;
}
case 2 /* cancelled */: {
info(
logging,
null,
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:
info(logging, null, 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,
logging,
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()
})}
`;
info(
logging,
null,
`
${magenta("Astro will make the following changes to your config file:")}
${message}`
);
if (logAdapterInstructions) {
info(
logging,
null,
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" });
debug("add", `Updated astro config`);
return 1 /* updated */;
} else {
return 2 /* cancelled */;
}
}
async function getInstallIntegrationsCommand({
integrations,
cwd = process.cwd()
}) {
const pm = await preferredPM(cwd);
debug("add", `package manager: ${JSON.stringify(pm)}`);
if (!pm)
return null;
let dependencies = integrations.map((i) => [[i.packageName, null], ...i.dependencies]).flat(1).filter((dep, i, arr) => arr.findIndex((d) => d[0] === dep[0]) === i).map(
([name, version]) => version === null ? name : `${name}@${version.split(/\s*\|\|\s*/).pop()}`
).sort();
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 };
default:
return null;
}
}
async function tryToInstallIntegrations({
integrations,
cwd,
flags,
logging
}) {
const installCommand = await getInstallIntegrationsCommand({ integrations, cwd });
if (installCommand === null) {
return 0 /* none */;
} else {
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"
})}
`;
info(
logging,
null,
`
${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, ...installCommand.dependencies],
{ cwd }
);
spinner.succeed();
return 1 /* updated */;
} catch (err) {
debug("add", "Error installing dependencies", err);
spinner.fail();
return 3 /* failure */;
}
} else {
return 2 /* cancelled */;
}
}
}
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 === 404) {
return new Error();
} else {
return await res.json();
}
}
async function validateIntegrations(integrations) {
const spinner = ora("Resolving packages...").start();
try {
const integrationEntries = await Promise.all(
integrations.map(async (integration) => {
var _a;
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) {
spinner.warn(
yellow(`${bold(integration)} is not an official Astro package. Use at your own risk!`)
);
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) {
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 = ((_a = meta[peer]) == null ? void 0 : _a.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(), logging, integrationsInfo, flags) {
const integrations = integrationsInfo.map(
(integration) => integration.id
);
const firstIntegrationWithTSSettings = integrations.find(
(integration) => presets.has(integration)
);
if (!firstIntegrationWithTSSettings) {
return 0 /* none */;
}
const inputConfig = loadTSConfig(cwd, false);
const configFileName = inputConfig.exists ? inputConfig.path.split("/").pop() : "tsconfig.json";
if (inputConfig.reason === "invalid-config") {
return 3 /* failure */;
}
if (inputConfig.reason === "not-found") {
debug("add", "Couldn't find tsconfig.json or jsconfig.json, generating one");
}
const outputConfig = updateTSConfigForFramework(
inputConfig.exists ? inputConfig.config : defaultTSConfig,
firstIntegrationWithTSSettings
);
const input = inputConfig.exists ? JSON.stringify(inputConfig.config, null, 2) : "";
const output = JSON.stringify(outputConfig, null, 2);
const diff = getDiffContent(input, output);
if (!diff) {
return 0 /* none */;
}
const message = `
${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: "round",
title: configFileName
})}
`;
info(
logging,
null,
`
${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) {
info(
logging,
null,
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 == null ? void 0 : inputConfig.path) ?? path.join(cwd, "tsconfig.json"), output, {
encoding: "utf-8"
});
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 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) {
info(
opts.logging,
null,
`
${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"
}
);
debug("add", `Generated default ${opts.defaultConfigFile} file`);
}
} else {
debug("add", `Using existing ${opts.integrationName} configuration`);
}
}
export {
add,
validateIntegrations
};

2
node_modules/astro/dist/cli/add/wrapper.d.ts generated vendored Normal file
View 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
View 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
};

8
node_modules/astro/dist/cli/build/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
import type yargs from 'yargs-parser';
import type { LogOptions } from '../../core/logger/core.js';
interface BuildOptions {
flags: yargs.Arguments;
logging: LogOptions;
}
export declare function build({ flags, logging }: BuildOptions): Promise<void>;
export {};

16
node_modules/astro/dist/cli/build/index.js generated vendored Normal file
View file

@ -0,0 +1,16 @@
import _build from "../../core/build/index.js";
import { loadSettings } from "../load-settings.js";
async function build({ flags, logging }) {
const settings = await loadSettings({ cmd: "build", flags, logging });
if (!settings)
return;
await _build(settings, {
flags,
logging,
teardownCompiler: true,
mode: flags.mode
});
}
export {
build
};

83
node_modules/astro/dist/cli/check/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,83 @@
/// <reference types="node" />
import { AstroCheck } from '@astrojs/language-server';
import fs from 'node:fs';
import type { Arguments as Flags } from 'yargs-parser';
import type { AstroSettings } from '../../@types/astro';
import type { LogOptions } from '../../core/logger/core.js';
import type { ProcessExit, SyncOptions } from '../../core/sync';
export type CheckPayload = {
/**
* Flags passed via CLI
*/
flags: Flags;
/**
* Logging options
*/
logging: LogOptions;
};
/**
*
* Types of response emitted by the checker
*/
export declare enum CheckResult {
/**
* Operation finished without errors
*/
ExitWithSuccess = 0,
/**
* Operation finished with errors
*/
ExitWithError = 1,
/**
* The consumer should not terminate the operation
*/
Listen = 2
}
/**
* Checks `.astro` files for possible errors.
*
* If the `--watch` flag is provided, the command runs indefinitely and provides diagnostics
* when `.astro` files are modified.
*
* Every time an astro files is modified, content collections are also generated.
*
* @param {CheckPayload} options Options passed {@link AstroChecker}
* @param {Flags} options.flags Flags coming from the CLI
* @param {LogOptions} options.logging Logging options
*/
export declare function check({ logging, flags }: CheckPayload): Promise<AstroChecker | undefined>;
type CheckerConstructor = {
diagnosticChecker: AstroCheck;
isWatchMode: boolean;
syncCli: (settings: AstroSettings, options: SyncOptions) => Promise<ProcessExit>;
settings: Readonly<AstroSettings>;
logging: Readonly<LogOptions>;
fileSystem: typeof fs;
};
/**
* Responsible to check files - classic or watch mode - and report diagnostics.
*
* When in watch mode, the class does a whole check pass, and then starts watching files.
* When a change occurs to an `.astro` file, the checker builds content collections again and lint all the `.astro` files.
*/
export declare class AstroChecker {
#private;
constructor({ diagnosticChecker, isWatchMode, syncCli, settings, fileSystem, logging, }: CheckerConstructor);
/**
* Check all `.astro` files once and then finishes the operation.
*/
check(): Promise<CheckResult>;
/**
* Check all `.astro` files and then start watching for changes.
*/
watch(): Promise<CheckResult>;
/**
* Stops the watch. It terminates the inner server.
*/
stop(): Promise<void>;
/**
* Whether the checker should run in watch mode
*/
get isWatchMode(): boolean;
}
export {};

270
node_modules/astro/dist/cli/check/index.js generated vendored Normal file
View file

@ -0,0 +1,270 @@
import {
AstroCheck,
DiagnosticSeverity
} from "@astrojs/language-server";
import glob from "fast-glob";
import { bold, dim, red, yellow } from "kleur/colors";
import { createRequire } from "module";
import fs from "node:fs";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import ora from "ora";
import { debug, info } from "../../core/logger/core.js";
import { printHelp } from "../../core/messages.js";
import { loadSettings } from "../load-settings.js";
import { printDiagnostic } from "./print.js";
var CheckResult = /* @__PURE__ */ ((CheckResult2) => {
CheckResult2[CheckResult2["ExitWithSuccess"] = 0] = "ExitWithSuccess";
CheckResult2[CheckResult2["ExitWithError"] = 1] = "ExitWithError";
CheckResult2[CheckResult2["Listen"] = 2] = "Listen";
return CheckResult2;
})(CheckResult || {});
const ASTRO_GLOB_PATTERN = "**/*.astro";
async function check({ logging, flags }) {
if (flags.help || flags.h) {
printHelp({
commandName: "astro check",
usage: "[...flags]",
tables: {
Flags: [
["--watch", "Watch Astro files for changes and re-run checks."],
["--help (-h)", "See all available flags."]
]
},
description: `Runs diagnostics against your project and reports errors to the console.`
});
return;
}
const settings = await loadSettings({ cmd: "check", flags, logging });
if (!settings)
return;
const checkFlags = parseFlags(flags);
if (checkFlags.watch) {
info(logging, "check", "Checking files in watch mode");
} else {
info(logging, "check", "Checking files");
}
const { syncCli } = await import("../../core/sync/index.js");
const root = settings.config.root;
const require2 = createRequire(import.meta.url);
const diagnosticChecker = new AstroCheck(
root.toString(),
require2.resolve("typescript/lib/tsserverlibrary.js", {
paths: [root.toString()]
})
);
return new AstroChecker({
syncCli,
settings,
fileSystem: fs,
logging,
diagnosticChecker,
isWatchMode: checkFlags.watch
});
}
class AstroChecker {
#diagnosticsChecker;
#shouldWatch;
#syncCli;
#settings;
#logging;
#fs;
#watcher;
#filesCount;
#updateDiagnostics;
constructor({
diagnosticChecker,
isWatchMode,
syncCli,
settings,
fileSystem,
logging
}) {
this.#diagnosticsChecker = diagnosticChecker;
this.#shouldWatch = isWatchMode;
this.#syncCli = syncCli;
this.#logging = logging;
this.#settings = settings;
this.#fs = fileSystem;
this.#filesCount = 0;
}
/**
* Check all `.astro` files once and then finishes the operation.
*/
async check() {
return await this.#checkAllFiles(true);
}
/**
* Check all `.astro` files and then start watching for changes.
*/
async watch() {
await this.#checkAllFiles(true);
await this.#watch();
return 2 /* Listen */;
}
/**
* Stops the watch. It terminates the inner server.
*/
async stop() {
var _a;
await ((_a = this.#watcher) == null ? void 0 : _a.close());
}
/**
* Whether the checker should run in watch mode
*/
get isWatchMode() {
return this.#shouldWatch;
}
async #openDocuments() {
this.#filesCount = await openAllDocuments(
this.#settings.config.root,
[],
this.#diagnosticsChecker
);
}
/**
* Lint all `.astro` files, and report the result in console. Operations executed, in order:
* 1. Compile content collections.
* 2. Optionally, traverse the file system for `.astro` files and saves their paths.
* 3. Get diagnostics for said files and print the result in console.
*
* @param openDocuments Whether the operation should open all `.astro` files
*/
async #checkAllFiles(openDocuments) {
const processExit = await this.#syncCli(this.#settings, {
logging: this.#logging,
fs: this.#fs
});
if (processExit === 1)
return processExit;
let spinner = ora(
` Getting diagnostics for Astro files in ${fileURLToPath(this.#settings.config.root)}\u2026`
).start();
if (openDocuments) {
await this.#openDocuments();
}
let diagnostics = await this.#diagnosticsChecker.getDiagnostics();
spinner.succeed();
let brokenDownDiagnostics = this.#breakDownDiagnostics(diagnostics);
this.#logDiagnosticsSeverity(brokenDownDiagnostics);
return brokenDownDiagnostics.errors > 0 ? 1 /* ExitWithError */ : 0 /* ExitWithSuccess */;
}
#checkForDiagnostics() {
clearTimeout(this.#updateDiagnostics);
this.#updateDiagnostics = setTimeout(async () => await this.#checkAllFiles(false), 500);
}
/**
* This function is responsible to attach events to the server watcher
*/
async #watch() {
const { default: chokidar } = await import("chokidar");
this.#watcher = chokidar.watch(
join(fileURLToPath(this.#settings.config.root), ASTRO_GLOB_PATTERN),
{
ignored: ["**/node_modules/**"],
ignoreInitial: true
}
);
this.#watcher.on("add", (file) => {
this.#addDocument(file);
this.#filesCount += 1;
this.#checkForDiagnostics();
});
this.#watcher.on("change", (file) => {
this.#addDocument(file);
this.#checkForDiagnostics();
});
this.#watcher.on("unlink", (file) => {
this.#diagnosticsChecker.removeDocument(file);
this.#filesCount -= 1;
this.#checkForDiagnostics();
});
}
/**
* Add a document to the diagnostics checker
* @param filePath Path to the file
*/
#addDocument(filePath) {
const text = fs.readFileSync(filePath, "utf-8");
this.#diagnosticsChecker.upsertDocument({
uri: pathToFileURL(filePath).toString(),
text
});
}
/**
* Logs the result of the various diagnostics
*
* @param result Result emitted by AstroChecker.#breakDownDiagnostics
*/
#logDiagnosticsSeverity(result) {
info(
this.#logging,
"diagnostics",
[
bold(`Result (${this.#filesCount} file${this.#filesCount === 1 ? "" : "s"}): `),
bold(red(`${result.errors} ${result.errors === 1 ? "error" : "errors"}`)),
bold(yellow(`${result.warnings} ${result.warnings === 1 ? "warning" : "warnings"}`)),
dim(`${result.hints} ${result.hints === 1 ? "hint" : "hints"}
`)
].join(`
${dim("-")} `)
);
}
/**
* It loops through all diagnostics and break down diagnostics that are errors, warnings or hints.
*/
#breakDownDiagnostics(diagnostics) {
let result = {
errors: 0,
warnings: 0,
hints: 0
};
diagnostics.forEach((diag) => {
diag.diagnostics.forEach((d) => {
info(this.#logging, "diagnostics", `
${printDiagnostic(diag.fileUri, diag.text, d)}`);
switch (d.severity) {
case DiagnosticSeverity.Error: {
result.errors++;
break;
}
case DiagnosticSeverity.Warning: {
result.warnings++;
break;
}
case DiagnosticSeverity.Hint: {
result.hints++;
break;
}
}
});
});
return result;
}
}
async function openAllDocuments(workspaceUri, filePathsToIgnore, checker) {
const files = await glob(ASTRO_GLOB_PATTERN, {
cwd: fileURLToPath(workspaceUri),
ignore: ["node_modules/**"].concat(filePathsToIgnore.map((ignore) => `${ignore}/**`)),
absolute: true
});
for (const file of files) {
debug("check", `Adding file ${file} to the list of files to check.`);
const text = fs.readFileSync(file, "utf-8");
checker.upsertDocument({
uri: pathToFileURL(file).toString(),
text
});
}
return files.length;
}
function parseFlags(flags) {
return {
watch: flags.watch ?? false
};
}
export {
AstroChecker,
CheckResult,
check
};

2
node_modules/astro/dist/cli/check/print.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
import { type Diagnostic } from '@astrojs/language-server';
export declare function printDiagnostic(filePath: string, text: string, diag: Diagnostic): string;

95
node_modules/astro/dist/cli/check/print.js generated vendored Normal file
View file

@ -0,0 +1,95 @@
import { DiagnosticSeverity, offsetAt } from "@astrojs/language-server";
import {
bgRed,
bgWhite,
bgYellow,
black,
bold,
cyan,
gray,
red,
white,
yellow
} from "kleur/colors";
import { fileURLToPath } from "node:url";
import stringWidth from "string-width";
function printDiagnostic(filePath, text, diag) {
let result = [];
const realStartLine = diag.range.start.line + 1;
const realStartCharacter = diag.range.start.character + 1;
const IDEFilePath = `${bold(cyan(fileURLToPath(filePath)))}:${bold(yellow(realStartLine))}:${bold(
yellow(realStartCharacter)
)}`;
result.push(
`${IDEFilePath} ${bold(getColorForSeverity(diag, getStringForSeverity(diag)))}: ${diag.message}`
);
const previousLine = getLine(diag.range.start.line - 1, text);
if (previousLine) {
result.push(`${getPrintableLineNumber(realStartLine - 1)} ${gray(previousLine)}`);
}
const str = getLine(diag.range.start.line, text);
const lineNumStr = realStartLine.toString().padStart(2, "0");
const lineNumLen = lineNumStr.length;
result.push(`${getBackgroundForSeverity(diag, lineNumStr)} ${str}`);
const tildes = generateString("~", diag.range.end.character - diag.range.start.character);
const beforeChars = stringWidth(str.substring(0, diag.range.start.character));
const spaces = generateString(" ", beforeChars + lineNumLen - 1);
result.push(` ${spaces}${bold(getColorForSeverity(diag, tildes))}`);
const nextLine = getLine(diag.range.start.line + 1, text);
if (nextLine) {
result.push(`${getPrintableLineNumber(realStartLine + 1)} ${gray(nextLine)}`);
}
result.push("");
return result.join("\n");
}
function generateString(str, len) {
return Array.from({ length: len }, () => str).join("");
}
function getStringForSeverity(diag) {
switch (diag.severity) {
case DiagnosticSeverity.Error:
return "Error";
case DiagnosticSeverity.Warning:
return "Warning";
case DiagnosticSeverity.Hint:
return "Hint";
default:
return "Unknown";
}
}
function getColorForSeverity(diag, text) {
switch (diag.severity) {
case DiagnosticSeverity.Error:
return red(text);
case DiagnosticSeverity.Warning:
return yellow(text);
case DiagnosticSeverity.Hint:
return gray(text);
default:
return text;
}
}
function getBackgroundForSeverity(diag, text) {
switch (diag.severity) {
case DiagnosticSeverity.Error:
return bgRed(white(text));
case DiagnosticSeverity.Warning:
return bgYellow(white(text));
case DiagnosticSeverity.Hint:
return bgWhite(black(text));
default:
return text;
}
}
function getPrintableLineNumber(line) {
return bgWhite(black(line.toString().padStart(2, "0")));
}
function getLine(line, text) {
return text.substring(
offsetAt({ line, character: 0 }, text),
offsetAt({ line, character: Number.MAX_SAFE_INTEGER }, text)
).replace(/\t/g, " ").trimEnd();
}
export {
printDiagnostic
};

8
node_modules/astro/dist/cli/dev/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
import type yargs from 'yargs-parser';
import { type LogOptions } from '../../core/logger/core.js';
interface DevOptions {
flags: yargs.Arguments;
logging: LogOptions;
}
export declare function dev({ flags, logging }: DevOptions): Promise<import("../../core/dev/dev.js").DevServer | undefined>;
export {};

26
node_modules/astro/dist/cli/dev/index.js generated vendored Normal file
View file

@ -0,0 +1,26 @@
import fs from "node:fs";
import { resolveConfigPath, resolveFlags } from "../../core/config/index.js";
import devServer from "../../core/dev/index.js";
import { info } from "../../core/logger/core.js";
import { handleConfigError, loadSettings } from "../load-settings.js";
async function dev({ flags, logging }) {
const settings = await loadSettings({ cmd: "dev", flags, logging });
if (!settings)
return;
const root = flags.root;
const configFlag = resolveFlags(flags).config;
const configFlagPath = configFlag ? await resolveConfigPath({ cwd: root, flags, fs }) : void 0;
return await devServer(settings, {
configFlag,
configFlagPath,
flags,
logging,
handleConfigError(e) {
handleConfigError(e, { cmd: "dev", cwd: root, flags, logging });
info(logging, "astro", "Continuing with previous valid configuration\n");
}
});
}
export {
dev
};

6
node_modules/astro/dist/cli/docs/index.d.ts generated vendored Normal file
View 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
View 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
View 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
View 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
};

2
node_modules/astro/dist/cli/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
/** The primary CLI action */
export declare function cli(args: string[]): Promise<void>;

163
node_modules/astro/dist/cli/index.js generated vendored Normal file
View file

@ -0,0 +1,163 @@
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."],
["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."],
["telemetry", "Configure telemetry settings."]
],
"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",
"dev",
"build",
"preview",
"check",
"docs",
"info"
]);
if (supportedCommands.has(cmd)) {
return cmd;
}
return "help";
}
async function runCommand(cmd, flags) {
var _a;
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 = (_a = flags._[3]) == null ? void 0 : _a.toString();
await update(subcommand, { flags });
return;
}
}
const { enableVerboseLogging, nodeLogDestination } = await import("../core/logger/node.js");
const logging = {
dest: nodeLogDestination,
level: "info"
};
if (flags.verbose) {
logging.level = "debug";
enableVerboseLogging();
} else if (flags.silent) {
logging.level = "silent";
}
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = cmd === "dev" ? "development" : "production";
}
switch (cmd) {
case "add": {
const { add } = await import("./add/index.js");
const packages = flags._.slice(3);
await add(packages, { flags, logging });
return;
}
case "dev": {
const { dev } = await import("./dev/index.js");
const server = await dev({ flags, logging });
if (server) {
return await new Promise(() => {
});
}
return;
}
case "build": {
const { build } = await import("./build/index.js");
await build({ flags, logging });
return;
}
case "preview": {
const { preview } = await import("./preview/index.js");
const server = await preview({ flags, logging });
if (server) {
return await server.closed();
}
return;
}
case "check": {
const { check } = await import("./check/index.js");
const checkServer = await check({ flags, logging });
if (checkServer) {
if (checkServer.isWatchMode) {
await checkServer.watch();
return await new Promise(() => {
});
} else {
const checkResult = await checkServer.check();
return process.exit(checkResult);
}
}
return;
}
case "sync": {
const { sync } = await import("./sync/index.js");
const exitCode = await sync({ flags, logging });
return process.exit(exitCode);
}
}
throw new Error(`Error running ${cmd} -- no command found.`);
}
async function cli(args) {
const flags = yargs(args);
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
};

6
node_modules/astro/dist/cli/info/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import type yargs from 'yargs-parser';
interface InfoOptions {
flags: yargs.Arguments;
}
export declare function printInfo({ flags }: InfoOptions): Promise<void>;
export {};

45
node_modules/astro/dist/cli/info/index.js generated vendored Normal file
View file

@ -0,0 +1,45 @@
import * as colors from "kleur/colors";
import { arch, platform } from "node:os";
import whichPm from "which-pm";
import { openConfig } from "../../core/config/index.js";
import { ASTRO_VERSION } from "../../core/constants.js";
async function printInfo({ flags }) {
var _a;
const packageManager = await whichPm(process.cwd());
let adapter = "Couldn't determine.";
let integrations = [];
const MAX_PADDING = 25;
function printRow(label, value) {
const padding = MAX_PADDING - label.length;
console.log(`${colors.bold(label)}` + " ".repeat(padding) + `${colors.green(value)}`);
}
try {
const { userConfig } = await openConfig({
cwd: flags.root,
flags,
cmd: "info"
});
if ((_a = userConfig.adapter) == null ? void 0 : _a.name) {
adapter = userConfig.adapter.name;
}
if (userConfig.integrations) {
integrations = ((userConfig == null ? void 0 : userConfig.integrations) ?? []).filter(Boolean).flat().map((i) => i == null ? void 0 : i.name);
}
} catch (_e) {
}
console.log();
const packageManagerName = (packageManager == null ? void 0 : packageManager.name) ?? "Couldn't determine.";
printRow("Astro version", `v${ASTRO_VERSION}`);
printRow("Package manager", packageManagerName);
printRow("Platform", platform());
printRow("Architecture", arch());
printRow("Adapter", adapter);
let integrationsString = "None or couldn't determine.";
if (integrations.length > 0) {
integrationsString = integrations.join(", ");
}
printRow("Integrations", integrationsString);
}
export {
printInfo
};

15
node_modules/astro/dist/cli/load-settings.d.ts generated vendored Normal file
View file

@ -0,0 +1,15 @@
import type { Arguments as Flags } from 'yargs-parser';
import { type LogOptions } from '../core/logger/core.js';
interface LoadSettingsOptions {
cmd: string;
flags: Flags;
logging: LogOptions;
}
export declare function loadSettings({ cmd, flags, logging }: LoadSettingsOptions): Promise<import("../@types/astro.js").AstroSettings | undefined>;
export declare function handleConfigError(e: any, { cmd, cwd, flags, logging }: {
cmd: string;
cwd?: string;
flags?: Flags;
logging: LogOptions;
}): Promise<void>;
export {};

39
node_modules/astro/dist/cli/load-settings.js generated vendored Normal file
View file

@ -0,0 +1,39 @@
import * as colors from "kleur/colors";
import fs from "node:fs";
import { ZodError } from "zod";
import { createSettings, openConfig, resolveConfigPath } from "../core/config/index.js";
import { collectErrorMetadata } from "../core/errors/dev/index.js";
import { error } from "../core/logger/core.js";
import { formatConfigErrorMessage, formatErrorMessage } from "../core/messages.js";
import * as event from "../events/index.js";
import { eventConfigError, telemetry } from "../events/index.js";
async function loadSettings({ cmd, flags, logging }) {
const root = flags.root;
const { astroConfig: initialAstroConfig, userConfig: initialUserConfig } = await openConfig({
cwd: root,
flags,
cmd
}).catch(async (e) => {
await handleConfigError(e, { cmd, cwd: root, flags, logging });
return {};
});
if (!initialAstroConfig)
return;
telemetry.record(event.eventCliSession(cmd, initialUserConfig, flags));
return createSettings(initialAstroConfig, root);
}
async function handleConfigError(e, { cmd, cwd, flags, logging }) {
const path = await resolveConfigPath({ cwd, flags, fs });
error(logging, "astro", `Unable to load ${path ? colors.bold(path) : "your Astro config"}
`);
if (e instanceof ZodError) {
console.error(formatConfigErrorMessage(e) + "\n");
telemetry.record(eventConfigError({ cmd, err: e, isFatal: true }));
} else if (e instanceof Error) {
console.error(formatErrorMessage(collectErrorMetadata(e)) + "\n");
}
}
export {
handleConfigError,
loadSettings
};

8
node_modules/astro/dist/cli/preview/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
import type yargs from 'yargs-parser';
import type { LogOptions } from '../../core/logger/core.js';
interface PreviewOptions {
flags: yargs.Arguments;
logging: LogOptions;
}
export declare function preview({ flags, logging }: PreviewOptions): Promise<import("../../@types/astro.js").PreviewServer | undefined>;
export {};

11
node_modules/astro/dist/cli/preview/index.js generated vendored Normal file
View file

@ -0,0 +1,11 @@
import previewServer from "../../core/preview/index.js";
import { loadSettings } from "../load-settings.js";
async function preview({ flags, logging }) {
const settings = await loadSettings({ cmd: "preview", flags, logging });
if (!settings)
return;
return await previewServer(settings, { flags, logging });
}
export {
preview
};

8
node_modules/astro/dist/cli/sync/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
import type yargs from 'yargs-parser';
import type { LogOptions } from '../../core/logger/core.js';
interface SyncOptions {
flags: yargs.Arguments;
logging: LogOptions;
}
export declare function sync({ flags, logging }: SyncOptions): Promise<import("../../core/sync/index.js").ProcessExit | undefined>;
export {};

13
node_modules/astro/dist/cli/sync/index.js generated vendored Normal file
View file

@ -0,0 +1,13 @@
import fs from "node:fs";
import { syncCli } from "../../core/sync/index.js";
import { loadSettings } from "../load-settings.js";
async function sync({ flags, logging }) {
const settings = await loadSettings({ cmd: "sync", flags, logging });
if (!settings)
return;
const exitCode = await syncCli(settings, { logging, fs, flags });
return exitCode;
}
export {
sync
};

6
node_modules/astro/dist/cli/telemetry/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import type yargs from 'yargs-parser';
interface TelemetryOptions {
flags: yargs.Arguments;
}
export declare function update(subcommand: string, { flags }: TelemetryOptions): Promise<void>;
export {};

39
node_modules/astro/dist/cli/telemetry/index.js generated vendored Normal file
View file

@ -0,0 +1,39 @@
import * as msg from "../../core/messages.js";
import { telemetry } from "../../events/index.js";
async function update(subcommand, { flags }) {
const isValid = ["enable", "disable", "reset"].includes(subcommand);
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);
console.log(msg.telemetryEnabled());
return;
}
case "disable": {
telemetry.setEnabled(false);
console.log(msg.telemetryDisabled());
return;
}
case "reset": {
telemetry.clear();
console.log(msg.telemetryReset());
return;
}
}
}
export {
update
};

2
node_modules/astro/dist/cli/throw-and-exit.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
/** Display error and exit */
export declare function throwAndExit(cmd: string, err: unknown): Promise<void>;

21
node_modules/astro/dist/cli/throw-and-exit.js generated vendored Normal file
View file

@ -0,0 +1,21 @@
import { collectErrorMetadata } from "../core/errors/dev/index.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) {
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);
setTimeout(exitWithErrorMessage, 400);
await telemetryPromise.catch((err2) => debug("telemetry", `record() error: ${err2.message}`)).then(exitWithErrorMessage);
}
export {
throwAndExit
};