astro 1.1.6 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/@types/astro.d.ts +4 -2
  2. package/dist/cli/index.js +56 -23
  3. package/dist/core/add/index.js +72 -68
  4. package/dist/core/build/generate.js +3 -1
  5. package/dist/core/build/vite-plugin-analyzer.js +7 -1
  6. package/dist/{vite-plugin-astro → core/compile}/compile.d.ts +3 -8
  7. package/dist/{vite-plugin-astro → core/compile}/compile.js +23 -56
  8. package/dist/core/compile/index.d.ts +3 -0
  9. package/dist/core/compile/index.js +7 -0
  10. package/dist/core/compile/style.d.ts +5 -0
  11. package/dist/core/compile/style.js +31 -0
  12. package/dist/core/compile/types.d.ts +7 -0
  13. package/dist/core/compile/types.js +0 -0
  14. package/dist/core/config.d.ts +6 -2
  15. package/dist/core/config.js +58 -37
  16. package/dist/core/create-vite.js +1 -1
  17. package/dist/core/dev/index.d.ts +1 -0
  18. package/dist/core/dev/index.js +4 -2
  19. package/dist/core/endpoint/dev/index.d.ts +2 -0
  20. package/dist/core/endpoint/index.d.ts +2 -0
  21. package/dist/core/endpoint/index.js +2 -1
  22. package/dist/core/messages.d.ts +2 -1
  23. package/dist/core/messages.js +5 -4
  24. package/dist/core/util.d.ts +13 -0
  25. package/dist/core/util.js +10 -2
  26. package/dist/jsx/babel.js +2 -1
  27. package/dist/runtime/server/astro-global.js +1 -1
  28. package/dist/runtime/server/hydration.js +1 -1
  29. package/dist/runtime/server/render/component.js +2 -1
  30. package/dist/runtime/server/render/page.js +1 -1
  31. package/dist/runtime/server/serialize.d.ts +2 -1
  32. package/dist/runtime/server/serialize.js +37 -12
  33. package/dist/vite-plugin-astro/hmr.d.ts +1 -1
  34. package/dist/vite-plugin-astro/hmr.js +3 -1
  35. package/dist/vite-plugin-astro/index.js +18 -26
  36. package/dist/vite-plugin-astro-server/index.js +1 -0
  37. package/dist/vite-plugin-markdown-legacy/index.js +16 -10
  38. package/dist/vite-style-transform/index.d.ts +2 -0
  39. package/dist/vite-style-transform/index.js +5 -0
  40. package/dist/vite-style-transform/style-transform.d.ts +10 -0
  41. package/dist/vite-style-transform/style-transform.js +36 -0
  42. package/dist/{vite-plugin-astro/styles.d.ts → vite-style-transform/transform-with-vite.d.ts} +0 -0
  43. package/dist/{vite-plugin-astro/styles.js → vite-style-transform/transform-with-vite.js} +0 -0
  44. package/package.json +8 -7
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import type { MarkdownHeading, MarkdownMetadata, MarkdownRenderingResult, RehypePlugins, RemarkPlugins, RemarkRehype, ShikiConfig } from '@astrojs/markdown-remark';
3
4
  import type * as babel from '@babel/core';
4
5
  import type { AddressInfo } from 'net';
@@ -843,7 +844,7 @@ export interface MarkdownInstance<T extends Record<string, any>> {
843
844
  getHeaders(): void;
844
845
  default: AstroComponentFactory;
845
846
  }
846
- export interface MDXInstance<T> extends Omit<MarkdownInstance<T>, 'rawContent' | 'compiledContent'> {
847
+ export interface MDXInstance<T extends Record<string, any>> extends Omit<MarkdownInstance<T>, 'rawContent' | 'compiledContent'> {
847
848
  /** MDX does not support rawContent! If you need to read the Markdown contents to calculate values (ex. reading time), we suggest injecting frontmatter via remark plugins. Learn more on our docs: https://docs.astro.build/en/guides/integrations-guide/mdx/#inject-frontmatter-via-remark-or-rehype-plugins */
848
849
  rawContent: never;
849
850
  /** MDX does not support compiledContent! If you need to read the HTML contents to calculate values (ex. reading time), we suggest injecting frontmatter via rehype plugins. Learn more on our docs: https://docs.astro.build/en/guides/integrations-guide/mdx/#inject-frontmatter-via-remark-or-rehype-plugins */
@@ -860,7 +861,7 @@ export interface MarkdownLayoutProps<T extends Record<string, any>> {
860
861
  rawContent: MarkdownInstance<T>['rawContent'];
861
862
  compiledContent: MarkdownInstance<T>['compiledContent'];
862
863
  }
863
- export declare type MDXLayoutProps<T> = Omit<MarkdownLayoutProps<T>, 'rawContent' | 'compiledContent'>;
864
+ export declare type MDXLayoutProps<T extends Record<string, any>> = Omit<MarkdownLayoutProps<T>, 'rawContent' | 'compiledContent'>;
864
865
  export declare type GetHydrateCallback = () => Promise<() => void | Promise<void>>;
865
866
  /**
866
867
  * getStaticPaths() options
@@ -974,6 +975,7 @@ export interface APIContext {
974
975
  }
975
976
  export interface EndpointOutput {
976
977
  body: Body;
978
+ encoding?: BufferEncoding;
977
979
  }
978
980
  export declare type APIRoute = (context: APIContext) => EndpointOutput | Response | Promise<EndpointOutput | Response>;
979
981
  export interface EndpointHandler {
package/dist/cli/index.js CHANGED
@@ -1,14 +1,17 @@
1
1
  import * as colors from "kleur/colors";
2
+ import { pathToFileURL } from "url";
3
+ import { normalizePath } from "vite";
2
4
  import yargs from "yargs-parser";
3
5
  import { z } from "zod";
4
6
  import add from "../core/add/index.js";
5
7
  import build from "../core/build/index.js";
6
- import { openConfig } from "../core/config.js";
8
+ import { openConfig, resolveConfigPath, resolveFlags, resolveRoot } from "../core/config.js";
7
9
  import devServer from "../core/dev/index.js";
8
10
  import { collectErrorMetadata } from "../core/errors.js";
9
- import { debug, info, warn } from "../core/logger/core.js";
11
+ import { debug, error, info } from "../core/logger/core.js";
10
12
  import { enableVerboseLogging, nodeLogDestination } from "../core/logger/node.js";
11
13
  import { formatConfigErrorMessage, formatErrorMessage, printHelp } from "../core/messages.js";
14
+ import { appendForwardSlash } from "../core/path.js";
12
15
  import preview from "../core/preview/index.js";
13
16
  import { ASTRO_VERSION, createSafeError } from "../core/util.js";
14
17
  import * as event from "../events/index.js";
@@ -62,6 +65,18 @@ function resolveCommand(flags) {
62
65
  }
63
66
  return "help";
64
67
  }
68
+ async function handleConfigError(e, { cwd, flags, logging }) {
69
+ const path = await resolveConfigPath({ cwd, flags });
70
+ if (e instanceof Error) {
71
+ if (path) {
72
+ error(logging, "astro", `Unable to load ${colors.bold(path)}
73
+ `);
74
+ }
75
+ console.error(
76
+ formatErrorMessage(collectErrorMetadata(e, path ? pathToFileURL(path) : void 0)) + "\n"
77
+ );
78
+ }
79
+ }
65
80
  async function runCommand(cmd, flags) {
66
81
  var _a;
67
82
  const root = flags.root;
@@ -98,39 +113,57 @@ async function runCommand(cmd, flags) {
98
113
  return await telemetryHandler.update(subcommand, { flags, telemetry });
99
114
  }
100
115
  }
101
- let { astroConfig, userConfig, userConfigPath } = await openConfig({
116
+ let { astroConfig, userConfig } = await openConfig({
102
117
  cwd: root,
103
118
  flags,
104
119
  cmd,
105
120
  logging
121
+ }).catch(async (e) => {
122
+ await handleConfigError(e, { cwd: root, flags, logging });
123
+ return {};
106
124
  });
125
+ if (!astroConfig)
126
+ return;
107
127
  telemetry.record(event.eventCliSession(cmd, userConfig, flags));
108
128
  switch (cmd) {
109
129
  case "dev": {
110
- async function startDevServer() {
111
- const { watcher, stop } = await devServer(astroConfig, { logging, telemetry });
112
- watcher.on("change", logRestartServerOnConfigChange);
113
- watcher.on("unlink", logRestartServerOnConfigChange);
114
- function logRestartServerOnConfigChange(changedFile) {
115
- if (userConfigPath === changedFile) {
116
- warn(logging, "astro", "Astro config updated. Restart server to see changes!");
117
- }
118
- }
119
- watcher.on("add", async function restartServerOnNewConfigFile(addedFile) {
120
- if (!userConfigPath && addedFile.includes("astro.config")) {
121
- const addedConfig = await openConfig({ cwd: root, flags, cmd, logging });
122
- if (addedConfig.userConfigPath) {
123
- info(logging, "astro", "Astro config detected. Restarting server...");
124
- astroConfig = addedConfig.astroConfig;
125
- userConfig = addedConfig.userConfig;
126
- userConfigPath = addedConfig.userConfigPath;
130
+ async function startDevServer({ isRestart = false } = {}) {
131
+ const { watcher, stop } = await devServer(astroConfig, { logging, telemetry, isRestart });
132
+ let restartInFlight = false;
133
+ const configFlag = resolveFlags(flags).config;
134
+ const configFlagPath = configFlag ? await resolveConfigPath({ cwd: root, flags }) : void 0;
135
+ const resolvedRoot = appendForwardSlash(resolveRoot(root));
136
+ const handleServerRestart = (logMsg) => async function(changedFile) {
137
+ if (!restartInFlight && (configFlag ? configFlagPath && normalizePath(configFlagPath) === normalizePath(changedFile) : new RegExp(
138
+ `${normalizePath(resolvedRoot)}.*astro.config.((mjs)|(cjs)|(js)|(ts))$`
139
+ ).test(normalizePath(changedFile)))) {
140
+ restartInFlight = true;
141
+ console.clear();
142
+ try {
143
+ const newConfig = await openConfig({
144
+ cwd: root,
145
+ flags,
146
+ cmd,
147
+ logging,
148
+ isConfigReload: true
149
+ });
150
+ info(logging, "astro", logMsg + "\n");
151
+ astroConfig = newConfig.astroConfig;
152
+ await stop();
153
+ await startDevServer({ isRestart: true });
154
+ } catch (e) {
155
+ await handleConfigError(e, { cwd: root, flags, logging });
127
156
  await stop();
128
- await startDevServer();
157
+ info(logging, "astro", "Continuing with previous valid configuration\n");
158
+ await startDevServer({ isRestart: true });
129
159
  }
130
160
  }
131
- });
161
+ };
162
+ watcher.on("change", handleServerRestart("Configuration updated. Restarting..."));
163
+ watcher.on("unlink", handleServerRestart("Configuration removed. Restarting..."));
164
+ watcher.on("add", handleServerRestart("Configuration added. Restarting..."));
132
165
  }
133
- await startDevServer();
166
+ await startDevServer({ isRestart: false });
134
167
  return await new Promise(() => {
135
168
  });
136
169
  }
@@ -8,7 +8,7 @@ import path from "path";
8
8
  import preferredPM from "preferred-pm";
9
9
  import prompts from "prompts";
10
10
  import { fileURLToPath, pathToFileURL } from "url";
11
- import { resolveConfigURL } from "../config.js";
11
+ import { resolveConfigPath } from "../config.js";
12
12
  import { debug, info } from "../logger/core.js";
13
13
  import * as msg from "../messages.js";
14
14
  import { printHelp } from "../messages.js";
@@ -80,15 +80,73 @@ async function add(names, { cwd, flags, logging, telemetry }) {
80
80
  });
81
81
  return;
82
82
  }
83
- let configURL;
83
+ const integrationNames = names.map((name) => ALIASES.has(name) ? ALIASES.get(name) : name);
84
+ const integrations = await validateIntegrations(integrationNames);
85
+ let installResult = await tryToInstallIntegrations({ integrations, cwd, flags, logging });
84
86
  const root = pathToFileURL(cwd ? path.resolve(cwd) : process.cwd());
85
- configURL = await resolveConfigURL({ cwd, flags });
87
+ root.href = appendForwardSlash(root.href);
88
+ switch (installResult) {
89
+ case UpdateResult.updated: {
90
+ if (integrations.find((integration) => integration.id === "tailwind")) {
91
+ const possibleConfigFiles = [
92
+ "./tailwind.config.cjs",
93
+ "./tailwind.config.mjs",
94
+ "./tailwind.config.js"
95
+ ].map((p) => fileURLToPath(new URL(p, root)));
96
+ let alreadyConfigured = false;
97
+ for (const possibleConfigPath of possibleConfigFiles) {
98
+ if (existsSync(possibleConfigPath)) {
99
+ alreadyConfigured = true;
100
+ break;
101
+ }
102
+ }
103
+ if (!alreadyConfigured) {
104
+ info(
105
+ logging,
106
+ null,
107
+ `
108
+ ${magenta(
109
+ `Astro will generate a minimal ${bold("./tailwind.config.cjs")} file.`
110
+ )}
111
+ `
112
+ );
113
+ if (await askToContinue({ flags })) {
114
+ await fs.writeFile(
115
+ fileURLToPath(new URL("./tailwind.config.cjs", root)),
116
+ TAILWIND_CONFIG_STUB,
117
+ { encoding: "utf-8" }
118
+ );
119
+ debug("add", `Generated default ./tailwind.config.cjs file`);
120
+ }
121
+ } else {
122
+ debug("add", `Using existing Tailwind configuration`);
123
+ }
124
+ }
125
+ break;
126
+ }
127
+ case UpdateResult.cancelled: {
128
+ info(
129
+ logging,
130
+ null,
131
+ msg.cancelled(
132
+ `Dependencies ${bold("NOT")} installed.`,
133
+ `Be sure to install them manually before continuing!`
134
+ )
135
+ );
136
+ break;
137
+ }
138
+ case UpdateResult.failure: {
139
+ throw createPrettyError(new Error(`Unable to install dependencies`));
140
+ }
141
+ }
142
+ const rawConfigPath = await resolveConfigPath({ cwd, flags });
143
+ let configURL = rawConfigPath ? pathToFileURL(rawConfigPath) : void 0;
86
144
  applyPolyfill();
87
145
  if (configURL) {
88
146
  debug("add", `Found config at ${configURL}`);
89
147
  } else {
90
148
  info(logging, "add", `Unable to locate a config file, generating one for you.`);
91
- configURL = new URL("./astro.config.mjs", appendForwardSlash(root.href));
149
+ configURL = new URL("./astro.config.mjs", root);
92
150
  await fs.writeFile(fileURLToPath(configURL), ASTRO_CONFIG_STUB, { encoding: "utf-8" });
93
151
  }
94
152
  if (configURL == null ? void 0 : configURL.pathname.endsWith("package.json")) {
@@ -96,8 +154,6 @@ async function add(names, { cwd, flags, logging, telemetry }) {
96
154
  `Unable to use "astro add" with package.json configuration. Try migrating to \`astro.config.mjs\` and try again.`
97
155
  );
98
156
  }
99
- const integrationNames = names.map((name) => ALIASES.has(name) ? ALIASES.get(name) : name);
100
- const integrations = await validateIntegrations(integrationNames);
101
157
  let ast = null;
102
158
  try {
103
159
  ast = await parseAstroConfig(configURL);
@@ -139,7 +195,6 @@ async function add(names, { cwd, flags, logging, telemetry }) {
139
195
  throw createPrettyError(err);
140
196
  }
141
197
  let configResult;
142
- let installResult;
143
198
  if (ast) {
144
199
  try {
145
200
  configResult = await updateAstroConfig({
@@ -173,72 +228,18 @@ async function add(names, { cwd, flags, logging, telemetry }) {
173
228
  }
174
229
  }
175
230
  info(logging, null, msg.success(`Configuration up-to-date.`));
176
- break;
231
+ return;
177
232
  }
178
- }
179
- installResult = await tryToInstallIntegrations({ integrations, cwd, flags, logging });
180
- switch (installResult) {
181
- case UpdateResult.updated: {
182
- const len = integrations.length;
183
- if (integrations.find((integration) => integration.id === "tailwind")) {
184
- const possibleConfigFiles = [
185
- "./tailwind.config.cjs",
186
- "./tailwind.config.mjs",
187
- "./tailwind.config.js"
188
- ].map((p) => fileURLToPath(new URL(p, configURL)));
189
- let alreadyConfigured = false;
190
- for (const possibleConfigPath of possibleConfigFiles) {
191
- if (existsSync(possibleConfigPath)) {
192
- alreadyConfigured = true;
193
- break;
194
- }
195
- }
196
- if (!alreadyConfigured) {
197
- info(
198
- logging,
199
- null,
200
- `
201
- ${magenta(
202
- `Astro will generate a minimal ${bold("./tailwind.config.cjs")} file.`
203
- )}
204
- `
205
- );
206
- if (await askToContinue({ flags })) {
207
- await fs.writeFile(
208
- fileURLToPath(new URL("./tailwind.config.cjs", configURL)),
209
- TAILWIND_CONFIG_STUB,
210
- { encoding: "utf-8" }
211
- );
212
- debug("add", `Generated default ./tailwind.config.cjs file`);
213
- }
214
- } else {
215
- debug("add", `Using existing Tailwind configuration`);
216
- }
217
- }
233
+ default: {
218
234
  const list = integrations.map((integration) => ` - ${integration.packageName}`).join("\n");
219
235
  info(
220
236
  logging,
221
237
  null,
222
238
  msg.success(
223
- `Added the following integration${len === 1 ? "" : "s"} to your project:
239
+ `Added the following integration${integrations.length === 1 ? "" : "s"} to your project:
224
240
  ${list}`
225
241
  )
226
242
  );
227
- return;
228
- }
229
- case UpdateResult.cancelled: {
230
- info(
231
- logging,
232
- null,
233
- msg.cancelled(
234
- `Dependencies ${bold("NOT")} installed.`,
235
- `Be sure to install them manually before continuing!`
236
- )
237
- );
238
- return;
239
- }
240
- case UpdateResult.failure: {
241
- throw createPrettyError(new Error(`Unable to install dependencies`));
242
243
  }
243
244
  }
244
245
  }
@@ -459,11 +460,11 @@ async function getInstallIntegrationsCommand({
459
460
  ).sort();
460
461
  switch (pm.name) {
461
462
  case "npm":
462
- return { pm: "npm", command: "install", flags: ["--save-dev"], dependencies };
463
+ return { pm: "npm", command: "install", flags: [], dependencies };
463
464
  case "yarn":
464
- return { pm: "yarn", command: "add", flags: ["--dev"], dependencies };
465
+ return { pm: "yarn", command: "add", flags: [], dependencies };
465
466
  case "pnpm":
466
- return { pm: "pnpm", command: "install", flags: ["--save-dev"], dependencies };
467
+ return { pm: "pnpm", command: "install", flags: [], dependencies };
467
468
  default:
468
469
  return null;
469
470
  }
@@ -478,7 +479,10 @@ async function tryToInstallIntegrations({
478
479
  if (installCommand === null) {
479
480
  return 0 /* none */;
480
481
  } else {
481
- const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command} ${installCommand.flags.join(" ")} ${cyan(installCommand.dependencies.join(" "))}`;
482
+ const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
483
+ "",
484
+ ...installCommand.flags
485
+ ].join(" ")} ${cyan(installCommand.dependencies.join(" "))}`;
482
486
  const message = `
483
487
  ${boxen(coloredOutput, {
484
488
  margin: 0.5,
@@ -260,12 +260,14 @@ async function generatePath(pathname, opts, gopts) {
260
260
  streaming: true
261
261
  };
262
262
  let body;
263
+ let encoding;
263
264
  if (pageData.route.type === "endpoint") {
264
265
  const result = await callEndpoint(mod, options);
265
266
  if (result.type === "response") {
266
267
  throw new Error(`Returning a Response from an endpoint is not supported in SSG mode.`);
267
268
  }
268
269
  body = result.body;
270
+ encoding = result.encoding;
269
271
  } else {
270
272
  const response = await render(options);
271
273
  if (response.status !== 200 || !response.body) {
@@ -277,7 +279,7 @@ async function generatePath(pathname, opts, gopts) {
277
279
  const outFile = getOutFile(astroConfig, outFolder, pathname, pageData.route.type);
278
280
  pageData.route.distURL = outFile;
279
281
  await fs.promises.mkdir(outFolder, { recursive: true });
280
- await fs.promises.writeFile(outFile, body, "utf-8");
282
+ await fs.promises.writeFile(outFile, body, encoding ?? "utf-8");
281
283
  }
282
284
  export {
283
285
  chunkIsPage,
@@ -55,7 +55,7 @@ function vitePluginAnalyzer(internals) {
55
55
  }
56
56
  return {
57
57
  name: "@astro/rollup-plugin-astro-analyzer",
58
- generateBundle() {
58
+ async generateBundle() {
59
59
  var _a;
60
60
  const hoistScanner = hoistedScriptScanner();
61
61
  const ids = this.getModuleIds();
@@ -75,6 +75,12 @@ function vitePluginAnalyzer(internals) {
75
75
  const cid = c.resolvedPath ? decodeURI(c.resolvedPath) : c.specifier;
76
76
  internals.discoveredClientOnlyComponents.add(cid);
77
77
  clientOnlys.push(cid);
78
+ if (c.resolvedPath === c.specifier) {
79
+ const resolvedId = await this.resolve(c.specifier, id);
80
+ if (resolvedId) {
81
+ clientOnlys.push(resolvedId.id);
82
+ }
83
+ }
78
84
  }
79
85
  for (const [pageInfo] of getTopLevelPages(id, this)) {
80
86
  const pageData = getPageDataByViteID(internals, pageInfo.id);
@@ -1,8 +1,6 @@
1
1
  import type { TransformResult } from '@astrojs/compiler';
2
- import type { PluginContext } from 'rollup';
3
- import type { ViteDevServer } from 'vite';
4
- import type { AstroConfig } from '../@types/astro';
5
- import type { TransformStyleWithVite } from './styles';
2
+ import type { AstroConfig } from '../../@types/astro';
3
+ import type { TransformStyle } from './types';
6
4
  declare type CompileResult = TransformResult & {
7
5
  cssDeps: Set<string>;
8
6
  source: string;
@@ -12,10 +10,7 @@ export interface CompileProps {
12
10
  filename: string;
13
11
  moduleId: string;
14
12
  source: string;
15
- ssr: boolean;
16
- transformStyleWithVite: TransformStyleWithVite;
17
- viteDevServer?: ViteDevServer;
18
- pluginContext: PluginContext;
13
+ transformStyle: TransformStyle;
19
14
  }
20
15
  export declare function isCached(config: AstroConfig, filename: string): boolean;
21
16
  export declare function getCachedSource(config: AstroConfig, filename: string): string | null;
@@ -1,35 +1,19 @@
1
1
  import { transform } from "@astrojs/compiler";
2
- import { fileURLToPath } from "url";
3
- import { AstroErrorCodes } from "../core/errors.js";
4
- import { prependForwardSlash } from "../core/path.js";
5
- import { viteID } from "../core/util.js";
2
+ import { AstroErrorCodes } from "../errors.js";
3
+ import { prependForwardSlash } from "../path.js";
4
+ import { AggregateError, viteID } from "../util.js";
5
+ import { createStylePreprocessor } from "./style.js";
6
6
  const configCache = /* @__PURE__ */ new WeakMap();
7
- function getNormalizedID(filename) {
8
- try {
9
- const filenameURL = new URL(`file://${filename}`);
10
- return fileURLToPath(filenameURL);
11
- } catch (err) {
12
- return filename;
13
- }
14
- }
15
7
  async function compile({
16
8
  config,
17
9
  filename,
18
10
  moduleId,
19
11
  source,
20
- ssr,
21
- transformStyleWithVite,
22
- viteDevServer,
23
- pluginContext
12
+ transformStyle
24
13
  }) {
25
14
  var _a;
26
- const normalizedID = getNormalizedID(filename);
27
15
  let cssDeps = /* @__PURE__ */ new Set();
28
- let cssTransformError;
29
- if (!pluginContext.addWatchFile) {
30
- pluginContext.addWatchFile = () => {
31
- };
32
- }
16
+ let cssTransformErrors = [];
33
17
  const transformResult = await transform(source, {
34
18
  pathname: `/@fs${prependForwardSlash(moduleId)}`,
35
19
  projectRoot: config.root.toString(),
@@ -37,47 +21,30 @@ async function compile({
37
21
  sourcefile: filename,
38
22
  sourcemap: "both",
39
23
  internalURL: `/@fs${prependForwardSlash(
40
- viteID(new URL("../runtime/server/index.js", import.meta.url))
24
+ viteID(new URL("../../runtime/server/index.js", import.meta.url))
41
25
  )}`,
42
26
  experimentalStaticExtraction: true,
43
- preprocessStyle: async (value, attrs) => {
44
- const lang = `.${(attrs == null ? void 0 : attrs.lang) || "css"}`.toLowerCase();
45
- try {
46
- const result = await transformStyleWithVite.call(pluginContext, {
47
- id: normalizedID,
48
- source: value,
49
- lang,
50
- ssr,
51
- viteDevServer
52
- });
53
- if (!result)
54
- return null;
55
- for (const dep of result.deps) {
56
- cssDeps.add(dep);
57
- }
58
- let map;
59
- if (result.map) {
60
- if (typeof result.map === "string") {
61
- map = result.map;
62
- } else if (result.map.mappings) {
63
- map = result.map.toString();
64
- }
65
- }
66
- return { code: result.code, map };
67
- } catch (err) {
68
- cssTransformError = err;
69
- return null;
70
- }
71
- }
27
+ preprocessStyle: createStylePreprocessor(transformStyle, cssDeps, cssTransformErrors)
72
28
  }).catch((err) => {
73
29
  err.code = err.code || AstroErrorCodes.UnknownCompilerError;
74
30
  throw err;
75
31
  }).then((result) => {
76
- if (cssTransformError) {
77
- cssTransformError.code = cssTransformError.code || AstroErrorCodes.UnknownCompilerCSSError;
78
- throw cssTransformError;
32
+ switch (cssTransformErrors.length) {
33
+ case 0:
34
+ return result;
35
+ case 1: {
36
+ let error = cssTransformErrors[0];
37
+ if (!error.code) {
38
+ error.code = AstroErrorCodes.UnknownCompilerCSSError;
39
+ }
40
+ throw cssTransformErrors[0];
41
+ }
42
+ default: {
43
+ const aggregateError = new AggregateError(cssTransformErrors);
44
+ aggregateError.code = AstroErrorCodes.UnknownCompilerCSSError;
45
+ throw aggregateError;
46
+ }
79
47
  }
80
- return result;
81
48
  });
82
49
  const compileResult = Object.create(transformResult, {
83
50
  cssDeps: {
@@ -0,0 +1,3 @@
1
+ export type { CompileProps } from './compile';
2
+ export { cachedCompilation, getCachedSource, invalidateCompilation, isCached } from './compile.js';
3
+ export type { TransformStyle } from './types';
@@ -0,0 +1,7 @@
1
+ import { cachedCompilation, getCachedSource, invalidateCompilation, isCached } from "./compile.js";
2
+ export {
3
+ cachedCompilation,
4
+ getCachedSource,
5
+ invalidateCompilation,
6
+ isCached
7
+ };
@@ -0,0 +1,5 @@
1
+ import type { TransformOptions } from '@astrojs/compiler';
2
+ import type { TransformStyle } from './types';
3
+ declare type PreprocessStyle = TransformOptions['preprocessStyle'];
4
+ export declare function createStylePreprocessor(transformStyle: TransformStyle, cssDeps: Set<string>, errors: Error[]): PreprocessStyle;
5
+ export {};
@@ -0,0 +1,31 @@
1
+ function createStylePreprocessor(transformStyle, cssDeps, errors) {
2
+ const preprocessStyle = async (value, attrs) => {
3
+ const lang = `.${(attrs == null ? void 0 : attrs.lang) || "css"}`.toLowerCase();
4
+ try {
5
+ const result = await transformStyle(value, lang);
6
+ if (!result)
7
+ return null;
8
+ for (const dep of result.deps) {
9
+ cssDeps.add(dep);
10
+ }
11
+ let map;
12
+ if (result.map) {
13
+ if (typeof result.map === "string") {
14
+ map = result.map;
15
+ } else if (result.map.mappings) {
16
+ map = result.map.toString();
17
+ }
18
+ }
19
+ return { code: result.code, map };
20
+ } catch (err) {
21
+ errors.push(err);
22
+ return {
23
+ error: err + ""
24
+ };
25
+ }
26
+ };
27
+ return preprocessStyle;
28
+ }
29
+ export {
30
+ createStylePreprocessor
31
+ };
@@ -0,0 +1,7 @@
1
+ import type { SourceMap } from 'rollup';
2
+ export declare type TransformStyleResult = null | {
3
+ code: string;
4
+ map: SourceMap | null;
5
+ deps: Set<string>;
6
+ };
7
+ export declare type TransformStyle = (source: string, lang: string) => TransformStyleResult | Promise<TransformStyleResult>;
File without changes
@@ -235,22 +235,26 @@ export declare const AstroConfigSchema: z.ZodObject<{
235
235
  }>;
236
236
  /** Turn raw config values into normalized values */
237
237
  export declare function validateConfig(userConfig: any, root: string, cmd: string, logging: LogOptions): Promise<AstroConfig>;
238
+ /** Convert the generic "yargs" flag object into our own, custom TypeScript object. */
239
+ export declare function resolveFlags(flags: Partial<Flags>): CLIFlags;
240
+ export declare function resolveRoot(cwd?: string): string;
238
241
  interface LoadConfigOptions {
239
242
  cwd?: string;
240
243
  flags?: Flags;
241
244
  cmd: string;
242
245
  validate?: boolean;
243
246
  logging: LogOptions;
247
+ /** Invalidate when reloading a previously loaded config */
248
+ isConfigReload?: boolean;
244
249
  }
245
250
  /**
246
251
  * Resolve the file URL of the user's `astro.config.js|cjs|mjs|ts` file
247
252
  * Note: currently the same as loadConfig but only returns the `filePath`
248
253
  * instead of the resolved config
249
254
  */
250
- export declare function resolveConfigURL(configOptions: Pick<LoadConfigOptions, 'cwd' | 'flags'>): Promise<URL | undefined>;
255
+ export declare function resolveConfigPath(configOptions: Pick<LoadConfigOptions, 'cwd' | 'flags'>): Promise<string | undefined>;
251
256
  interface OpenConfigResult {
252
257
  userConfig: AstroUserConfig;
253
- userConfigPath: string | undefined;
254
258
  astroConfig: AstroConfig;
255
259
  flags: CLIFlags;
256
260
  root: string;