astro 1.6.3 → 1.6.5

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.
@@ -1289,6 +1289,7 @@ export interface PreviewServerParams {
1289
1289
  serverEntrypoint: URL;
1290
1290
  host: string | undefined;
1291
1291
  port: number;
1292
+ base: string;
1292
1293
  }
1293
1294
  export declare type CreatePreviewServer = (params: PreviewServerParams) => PreviewServer | Promise<PreviewServer>;
1294
1295
  export interface PreviewModule {
package/dist/cli/index.js CHANGED
@@ -2,8 +2,6 @@ import * as colors from "kleur/colors";
2
2
  import { pathToFileURL } from "url";
3
3
  import yargs from "yargs-parser";
4
4
  import { z } from "zod";
5
- import add from "../core/add/index.js";
6
- import build from "../core/build/index.js";
7
5
  import {
8
6
  createSettings,
9
7
  openConfig,
@@ -11,18 +9,15 @@ import {
11
9
  resolveFlags
12
10
  } from "../core/config/index.js";
13
11
  import { ASTRO_VERSION } from "../core/constants.js";
14
- import devServer from "../core/dev/index.js";
15
12
  import { collectErrorMetadata } from "../core/errors/dev/index.js";
16
13
  import { createSafeError } from "../core/errors/index.js";
17
14
  import { debug, error, info } from "../core/logger/core.js";
18
15
  import { enableVerboseLogging, nodeLogDestination } from "../core/logger/node.js";
19
16
  import { formatConfigErrorMessage, formatErrorMessage, printHelp } from "../core/messages.js";
20
- import preview from "../core/preview/index.js";
21
17
  import * as event from "../events/index.js";
22
18
  import { eventConfigError, eventError, telemetry } from "../events/index.js";
23
19
  import { check } from "./check/index.js";
24
20
  import { openInBrowser } from "./open.js";
25
- import * as telemetryHandler from "./telemetry.js";
26
21
  function printAstroHelp() {
27
22
  printHelp({
28
23
  commandName: "astro",
@@ -106,6 +101,7 @@ async function runCommand(cmd, flags) {
106
101
  }
107
102
  switch (cmd) {
108
103
  case "add": {
104
+ const { default: add } = await import("../core/add/index.js");
109
105
  telemetry.record(event.eventCliSession(cmd));
110
106
  const packages = flags._.slice(3);
111
107
  return await add(packages, { cwd: root, flags, logging, telemetry });
@@ -115,6 +111,7 @@ async function runCommand(cmd, flags) {
115
111
  return await openInBrowser("https://docs.astro.build/");
116
112
  }
117
113
  case "telemetry": {
114
+ const telemetryHandler = await import("./telemetry.js");
118
115
  const subcommand = (_a = flags._[3]) == null ? void 0 : _a.toString();
119
116
  return await telemetryHandler.update(subcommand, { flags, telemetry });
120
117
  }
@@ -134,6 +131,7 @@ async function runCommand(cmd, flags) {
134
131
  let settings = createSettings(initialAstroConfig, root);
135
132
  switch (cmd) {
136
133
  case "dev": {
134
+ const { default: devServer } = await import("../core/dev/index.js");
137
135
  const configFlag = resolveFlags(flags).config;
138
136
  const configFlagPath = configFlag ? await resolveConfigPath({ cwd: root, flags }) : void 0;
139
137
  await devServer(settings, {
@@ -150,6 +148,7 @@ async function runCommand(cmd, flags) {
150
148
  });
151
149
  }
152
150
  case "build": {
151
+ const { default: build } = await import("../core/build/index.js");
153
152
  return await build(settings, { ...flags, logging, telemetry });
154
153
  }
155
154
  case "check": {
@@ -157,6 +156,7 @@ async function runCommand(cmd, flags) {
157
156
  return process.exit(ret);
158
157
  }
159
158
  case "preview": {
159
+ const { default: preview } = await import("../core/preview/index.js");
160
160
  const server = await preview(settings, { logging, telemetry });
161
161
  return await server.closed();
162
162
  }
@@ -9,4 +9,6 @@ export declare const visit: {
9
9
  };
10
10
  export { t };
11
11
  export declare function generate(ast: t.File): Promise<string>;
12
- export declare const parse: (code: string) => parser.ParseResult<t.File>;
12
+ export declare const parse: (code: string) => t.File & {
13
+ errors: parser.ParseError[];
14
+ };
@@ -9,6 +9,7 @@ export interface MatchOptions {
9
9
  export declare class App {
10
10
  #private;
11
11
  constructor(manifest: Manifest, streaming?: boolean);
12
+ removeBase(pathname: string): string;
12
13
  match(request: Request, { matchNotFound }?: MatchOptions): RouteData | undefined;
13
14
  render(request: Request, routeData?: RouteData): Promise<Response>;
14
15
  setCookieHeaders(response: Response): Generator<string, void, unknown>;
@@ -20,13 +20,13 @@ var __privateMethod = (obj, member, method) => {
20
20
  __accessCheck(obj, member, "access private method");
21
21
  return method;
22
22
  };
23
- var _env, _manifest, _manifestData, _routeDataToRouteInfo, _encoder, _logging, _renderPage, renderPage_fn, _callEndpoint, callEndpoint_fn;
23
+ var _env, _manifest, _manifestData, _routeDataToRouteInfo, _encoder, _logging, _base, _baseWithoutTrailingSlash, _renderPage, renderPage_fn, _callEndpoint, callEndpoint_fn;
24
24
  import mime from "mime";
25
25
  import { attachToResponse, getSetCookiesFromResponse } from "../cookies/index.js";
26
26
  import { call as callEndpoint } from "../endpoint/index.js";
27
27
  import { consoleLogDestination } from "../logger/console.js";
28
28
  import { error } from "../logger/core.js";
29
- import { joinPaths, prependForwardSlash } from "../path.js";
29
+ import { joinPaths, prependForwardSlash, removeTrailingForwardSlash } from "../path.js";
30
30
  import {
31
31
  createEnvironment,
32
32
  createRenderContext,
@@ -54,6 +54,8 @@ class App {
54
54
  dest: consoleLogDestination,
55
55
  level: "info"
56
56
  });
57
+ __privateAdd(this, _base, void 0);
58
+ __privateAdd(this, _baseWithoutTrailingSlash, void 0);
57
59
  __privateSet(this, _manifest, manifest);
58
60
  __privateSet(this, _manifestData, {
59
61
  routes: manifest.routes.map((route) => route.routeData)
@@ -85,13 +87,22 @@ class App {
85
87
  ssr: true,
86
88
  streaming
87
89
  }));
90
+ __privateSet(this, _base, __privateGet(this, _manifest).base || "/");
91
+ __privateSet(this, _baseWithoutTrailingSlash, removeTrailingForwardSlash(__privateGet(this, _base)));
92
+ }
93
+ removeBase(pathname) {
94
+ if (pathname.startsWith(__privateGet(this, _base))) {
95
+ return pathname.slice(__privateGet(this, _baseWithoutTrailingSlash).length + 1);
96
+ }
97
+ return pathname;
88
98
  }
89
99
  match(request, { matchNotFound = false } = {}) {
90
100
  const url = new URL(request.url);
91
101
  if (__privateGet(this, _manifest).assets.has(url.pathname)) {
92
102
  return void 0;
93
103
  }
94
- let routeData = matchRoute(url.pathname, __privateGet(this, _manifestData));
104
+ let pathname = "/" + this.removeBase(url.pathname);
105
+ let routeData = matchRoute(pathname, __privateGet(this, _manifestData));
95
106
  if (routeData) {
96
107
  return routeData;
97
108
  } else if (matchNotFound) {
@@ -149,11 +160,12 @@ _manifestData = new WeakMap();
149
160
  _routeDataToRouteInfo = new WeakMap();
150
161
  _encoder = new WeakMap();
151
162
  _logging = new WeakMap();
163
+ _base = new WeakMap();
164
+ _baseWithoutTrailingSlash = new WeakMap();
152
165
  _renderPage = new WeakSet();
153
166
  renderPage_fn = async function(request, routeData, mod, status = 200) {
154
167
  const url = new URL(request.url);
155
168
  const manifest = __privateGet(this, _manifest);
156
- const renderers = manifest.renderers;
157
169
  const info = __privateGet(this, _routeDataToRouteInfo).get(routeData);
158
170
  const links = createLinkStylesheetElementSet(info.links, manifest.site);
159
171
  let scripts = /* @__PURE__ */ new Set();
@@ -4,6 +4,7 @@ import { fileURLToPath } from "url";
4
4
  import { runHookBuildSsr } from "../../integrations/index.js";
5
5
  import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from "../../vite-plugin-scripts/index.js";
6
6
  import { pagesVirtualModuleId } from "../app/index.js";
7
+ import { removeLeadingForwardSlash, removeTrailingForwardSlash } from "../path.js";
7
8
  import { serializeRouteData } from "../routing/index.js";
8
9
  import { addRollupInput } from "./add-rollup-input.js";
9
10
  import { eachPageData, sortedCSS } from "./internal.js";
@@ -112,9 +113,11 @@ function buildManifest(opts, internals, staticFiles) {
112
113
  if (settings.scripts.some((script) => script.stage === "page")) {
113
114
  scripts.push({ type: "external", value: entryModules[PAGE_SCRIPT_ID] });
114
115
  }
116
+ const bareBase = removeTrailingForwardSlash(removeLeadingForwardSlash(settings.config.base));
117
+ const links = sortedCSS(pageData).map((pth) => bareBase ? bareBase + "/" + pth : pth);
115
118
  routes.push({
116
119
  file: "",
117
- links: sortedCSS(pageData),
120
+ links,
118
121
  scripts: [
119
122
  ...scripts,
120
123
  ...settings.scripts.filter((script) => script.stage === "head-inline").map(({ stage, content }) => ({ stage, children: content }))
@@ -137,7 +140,7 @@ function buildManifest(opts, internals, staticFiles) {
137
140
  pageMap: null,
138
141
  renderers: [],
139
142
  entryModules,
140
- assets: staticFiles.map((s) => "/" + s)
143
+ assets: staticFiles.map((s) => settings.config.base + s)
141
144
  };
142
145
  return ssrManifest;
143
146
  }
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "1.6.3";
1
+ const ASTRO_VERSION = "1.6.5";
2
2
  const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
3
3
  ".markdown",
4
4
  ".mdown",
@@ -62,6 +62,7 @@ async function createVite(commandConfig, { settings, logging, mode, fs = nodeFs
62
62
  },
63
63
  plugins: [
64
64
  configAliasVitePlugin({ settings }),
65
+ astroLoadFallbackPlugin({ fs, settings }),
65
66
  astroVitePlugin({ settings, logging }),
66
67
  astroScriptsPlugin({ settings }),
67
68
  mode !== "build" && vitePluginAstroServer({ settings, logging, fs }),
@@ -71,8 +72,7 @@ async function createVite(commandConfig, { settings, logging, mode, fs = nodeFs
71
72
  jsxVitePlugin({ settings, logging }),
72
73
  astroPostprocessVitePlugin({ settings }),
73
74
  astroIntegrationsContainerPlugin({ settings, logging }),
74
- astroScriptsPageSSRPlugin({ settings }),
75
- astroLoadFallbackPlugin({ fs })
75
+ astroScriptsPageSSRPlugin({ settings })
76
76
  ],
77
77
  publicDir: fileURLToPath(settings.config.publicDir),
78
78
  root: fileURLToPath(settings.config.root),
@@ -30,7 +30,7 @@ async function dev(settings, options) {
30
30
  isRestart: options.isRestart
31
31
  })
32
32
  );
33
- const currentVersion = "1.6.3";
33
+ const currentVersion = "1.6.5";
34
34
  if (currentVersion.includes("-")) {
35
35
  warn(options.logging, null, msg.prerelease({ currentVersion }));
36
36
  }
@@ -1,3 +1,3 @@
1
- export { createContainer, runInContainer, startContainer } from './container.js';
1
+ export { createContainer, isStarted, runInContainer, startContainer } from './container.js';
2
2
  export { default } from './dev.js';
3
3
  export { createContainerWithAutomaticRestart } from './restart.js';
@@ -1,10 +1,11 @@
1
- import { createContainer, runInContainer, startContainer } from "./container.js";
1
+ import { createContainer, isStarted, runInContainer, startContainer } from "./container.js";
2
2
  import { default as default2 } from "./dev.js";
3
3
  import { createContainerWithAutomaticRestart } from "./restart.js";
4
4
  export {
5
5
  createContainer,
6
6
  createContainerWithAutomaticRestart,
7
7
  default2 as default,
8
+ isStarted,
8
9
  runInContainer,
9
10
  startContainer
10
11
  };
@@ -3,9 +3,8 @@ import { createSettings, openConfig } from "../config/index.js";
3
3
  import { createSafeError } from "../errors/index.js";
4
4
  import { info } from "../logger/core.js";
5
5
  import { createContainer, isStarted, startContainer } from "./container.js";
6
- async function createRestartedContainer(container, settings) {
6
+ async function createRestartedContainer(container, settings, needsStart) {
7
7
  const { logging, fs, resolvedRoot, configFlag, configFlagPath } = container;
8
- const needsStart = isStarted(container);
9
8
  const newContainer = await createContainer({
10
9
  isRestart: true,
11
10
  logging,
@@ -52,6 +51,7 @@ async function restartContainer({
52
51
  if (beforeRestart) {
53
52
  beforeRestart();
54
53
  }
54
+ const needsStart = isStarted(container);
55
55
  try {
56
56
  const newConfig = await openConfig({
57
57
  cwd: resolvedRoot,
@@ -66,7 +66,7 @@ async function restartContainer({
66
66
  const settings = createSettings(astroConfig, resolvedRoot);
67
67
  await close();
68
68
  return {
69
- container: await createRestartedContainer(container, settings),
69
+ container: await createRestartedContainer(container, settings, needsStart),
70
70
  error: null
71
71
  };
72
72
  } catch (_err) {
@@ -75,7 +75,7 @@ async function restartContainer({
75
75
  await close();
76
76
  info(logging, "astro", "Continuing with previous valid configuration\n");
77
77
  return {
78
- container: await createRestartedContainer(container, existingSettings),
78
+ container: await createRestartedContainer(container, existingSettings, needsStart),
79
79
  error
80
80
  };
81
81
  }
@@ -47,7 +47,7 @@ function serverStart({
47
47
  site,
48
48
  isRestart = false
49
49
  }) {
50
- const version = "1.6.3";
50
+ const version = "1.6.5";
51
51
  const rootPath = site ? site.pathname : "/";
52
52
  const localPrefix = `${dim("\u2503")} Local `;
53
53
  const networkPrefix = `${dim("\u2503")} Network `;
@@ -255,7 +255,7 @@ function printHelp({
255
255
  message.push(
256
256
  linebreak(),
257
257
  ` ${bgGreen(black(` ${commandName} `))} ${green(
258
- `v${"1.6.3"}`
258
+ `v${"1.6.5"}`
259
259
  )} ${headline}`
260
260
  );
261
261
  }
@@ -34,7 +34,8 @@ async function preview(_settings, { logging }) {
34
34
  client: settings.config.build.client,
35
35
  serverEntrypoint: new URL(settings.config.build.serverEntry, settings.config.build.server),
36
36
  host,
37
- port
37
+ port,
38
+ base: settings.config.base
38
39
  });
39
40
  return server;
40
41
  }
@@ -18,7 +18,7 @@ var __privateSet = (obj, member, value, setter) => {
18
18
  };
19
19
  var _cache, _result, _slots, _loggingOpts;
20
20
  import { bold } from "kleur/colors";
21
- import { renderSlot } from "../../runtime/server/index.js";
21
+ import { renderSlot, stringifyChunk } from "../../runtime/server/index.js";
22
22
  import { renderJSX } from "../../runtime/server/jsx.js";
23
23
  import { AstroCookies } from "../cookies/index.js";
24
24
  import { warn } from "../logger/core.js";
@@ -102,12 +102,11 @@ Please update the name of this slot.`
102
102
  }
103
103
  }
104
104
  }
105
- const content = await renderSlot(__privateGet(this, _result), __privateGet(this, _slots)[name]).then(
106
- (res) => res != null ? String(res) : res
107
- );
105
+ const content = await renderSlot(__privateGet(this, _result), __privateGet(this, _slots)[name]);
106
+ const outHTML = stringifyChunk(__privateGet(this, _result), content);
108
107
  if (cacheable)
109
- __privateGet(this, _cache).set(name, content);
110
- return content;
108
+ __privateGet(this, _cache).set(name, outHTML);
109
+ return outHTML;
111
110
  }
112
111
  }
113
112
  _cache = new WeakMap();
@@ -1,11 +1,12 @@
1
1
  import type { SSRResult } from '../../../@types/astro';
2
2
  import type { RenderInstruction } from './types.js';
3
3
  import { HTMLBytes } from '../escape.js';
4
+ import { type SlotString } from './slot.js';
4
5
  export declare const Fragment: unique symbol;
5
6
  export declare const Renderer: unique symbol;
6
7
  export declare const encoder: TextEncoder;
7
8
  export declare const decoder: TextDecoder;
8
- export declare function stringifyChunk(result: SSRResult, chunk: string | RenderInstruction): any;
9
+ export declare function stringifyChunk(result: SSRResult, chunk: string | SlotString | RenderInstruction): any;
9
10
  export declare class HTMLParts {
10
11
  parts: string;
11
12
  constructor();
@@ -4,6 +4,7 @@ import {
4
4
  determinesIfNeedsDirectiveScript,
5
5
  getPrescripts
6
6
  } from "../scripts.js";
7
+ import { isSlotString } from "./slot.js";
7
8
  const Fragment = Symbol.for("astro:fragment");
8
9
  const Renderer = Symbol.for("astro:renderer");
9
10
  const encoder = new TextEncoder();
@@ -23,6 +24,17 @@ function stringifyChunk(result, chunk) {
23
24
  }
24
25
  }
25
26
  default: {
27
+ if (isSlotString(chunk)) {
28
+ let out = "";
29
+ const c = chunk;
30
+ if (c.instructions) {
31
+ for (const instr of c.instructions) {
32
+ out += stringifyChunk(result, instr);
33
+ }
34
+ }
35
+ out += chunk.toString();
36
+ return out;
37
+ }
26
38
  return chunk.toString();
27
39
  }
28
40
  }
@@ -1,10 +1,13 @@
1
1
  import type { SSRResult } from '../../../@types/astro.js';
2
2
  import type { RenderInstruction } from './types.js';
3
3
  import { HTMLString } from '../escape.js';
4
+ declare const slotString: unique symbol;
4
5
  export declare class SlotString extends HTMLString {
5
6
  instructions: null | RenderInstruction[];
7
+ [slotString]: boolean;
6
8
  constructor(content: string, instructions: null | RenderInstruction[]);
7
9
  }
10
+ export declare function isSlotString(str: string): str is any;
8
11
  export declare function renderSlot(_result: any, slotted: string, fallback?: any): Promise<string>;
9
12
  interface RenderSlotsResult {
10
13
  slotInstructions: null | RenderInstruction[];
@@ -1,11 +1,17 @@
1
1
  import { HTMLString, markHTMLString } from "../escape.js";
2
2
  import { renderChild } from "./any.js";
3
+ const slotString = Symbol.for("astro:slot-string");
3
4
  class SlotString extends HTMLString {
4
5
  constructor(content, instructions) {
5
6
  super(content);
6
7
  this.instructions = instructions;
8
+ this[slotString] = true;
7
9
  }
8
10
  }
11
+ slotString;
12
+ function isSlotString(str) {
13
+ return !!str[slotString];
14
+ }
9
15
  async function renderSlot(_result, slotted, fallback) {
10
16
  if (slotted) {
11
17
  let iterator = renderChild(slotted);
@@ -47,6 +53,7 @@ async function renderSlots(result, slots = {}) {
47
53
  }
48
54
  export {
49
55
  SlotString,
56
+ isSlotString,
50
57
  renderSlot,
51
58
  renderSlots
52
59
  };
@@ -10,7 +10,7 @@ const isPkgFile = (id) => {
10
10
  };
11
11
  async function handleHotUpdate(ctx, { config, logging, compile }) {
12
12
  let isStyleOnlyChange = false;
13
- if (ctx.file.endsWith(".astro")) {
13
+ if (ctx.file.endsWith(".astro") && isCached(config, ctx.file)) {
14
14
  const oldResult = await compile();
15
15
  invalidateCompilation(config, ctx.file);
16
16
  const newResult = await compile();
@@ -26,7 +26,7 @@ function astro({ settings, logging }) {
26
26
  }
27
27
  let resolvedConfig;
28
28
  const srcRootWeb = config.srcDir.pathname.slice(config.root.pathname.length - 1);
29
- const isBrowserPath = (path) => path.startsWith(srcRootWeb);
29
+ const isBrowserPath = (path) => path.startsWith(srcRootWeb) && srcRootWeb !== "/";
30
30
  const isFullFilePath = (path) => path.startsWith(prependForwardSlash(slash(fileURLToPath(config.root))));
31
31
  function resolveRelativeFromAstroParent(id, parsedFrom) {
32
32
  const filename = normalizeFilename(parsedFrom.filename);
@@ -11,27 +11,24 @@ function getPrivateEnv(viteConfig, astroConfig) {
11
11
  viteConfig.envDir ?? fileURLToPath(astroConfig.root),
12
12
  ""
13
13
  );
14
- const privateKeys = Object.keys(fullEnv).filter((key) => {
15
- for (const envPrefix of envPrefixes) {
16
- if (key.startsWith(envPrefix))
17
- return false;
14
+ const privateEnv = {};
15
+ for (const key in fullEnv) {
16
+ if (envPrefixes.every((prefix) => !key.startsWith(prefix))) {
17
+ if (typeof process.env[key] !== "undefined") {
18
+ privateEnv[key] = `process.env.${key}`;
19
+ } else {
20
+ privateEnv[key] = JSON.stringify(fullEnv[key]);
21
+ }
18
22
  }
19
- return true;
20
- });
21
- if (privateKeys.length === 0) {
22
- return null;
23
23
  }
24
- return Object.fromEntries(
25
- privateKeys.map((key) => {
26
- if (typeof process.env[key] !== "undefined")
27
- return [key, `process.env.${key}`];
28
- return [key, JSON.stringify(fullEnv[key])];
29
- })
30
- );
24
+ privateEnv.SITE = astroConfig.site ? `'${astroConfig.site}'` : "undefined";
25
+ privateEnv.SSR = JSON.stringify(true);
26
+ privateEnv.BASE_URL = astroConfig.base ? `'${astroConfig.base}'` : "undefined";
27
+ return privateEnv;
31
28
  }
32
29
  function getReferencedPrivateKeys(source, privateEnv) {
33
30
  const references = /* @__PURE__ */ new Set();
34
- for (const key of Object.keys(privateEnv)) {
31
+ for (const key in privateEnv) {
35
32
  if (source.includes(key)) {
36
33
  references.add(key);
37
34
  }
@@ -40,73 +37,52 @@ function getReferencedPrivateKeys(source, privateEnv) {
40
37
  }
41
38
  function envVitePlugin({ settings }) {
42
39
  let privateEnv;
43
- let config;
44
- let replacements;
45
- let pattern;
40
+ let viteConfig;
46
41
  const { config: astroConfig } = settings;
47
42
  return {
48
43
  name: "astro:vite-plugin-env",
49
44
  enforce: "pre",
50
45
  configResolved(resolvedConfig) {
51
- config = resolvedConfig;
46
+ viteConfig = resolvedConfig;
52
47
  },
53
48
  async transform(source, id, options) {
54
- const ssr = (options == null ? void 0 : options.ssr) === true;
55
- if (!ssr) {
49
+ if (!(options == null ? void 0 : options.ssr) || !source.includes("import.meta.env")) {
56
50
  return;
57
51
  }
58
- if (!source.includes("import.meta") || !/\benv\b/.test(source)) {
59
- return;
60
- }
61
- if (typeof privateEnv === "undefined") {
62
- privateEnv = getPrivateEnv(config, astroConfig);
63
- if (privateEnv) {
64
- privateEnv.SITE = astroConfig.site ? `'${astroConfig.site}'` : "undefined";
65
- privateEnv.SSR = JSON.stringify(true);
66
- privateEnv.BASE_URL = astroConfig.base ? `'${astroConfig.base}'` : void 0;
67
- const entries = Object.entries(privateEnv).map(([key, value]) => [
68
- `import.meta.env.${key}`,
69
- value
70
- ]);
71
- replacements = Object.fromEntries(entries);
72
- replacements = Object.assign(replacements, {
73
- "import.meta.env.SITE": astroConfig.site ? `'${astroConfig.site}'` : "undefined",
74
- "import.meta.env.SSR": JSON.stringify(true),
75
- "import.meta.env.BASE_URL": astroConfig.base ? `'${astroConfig.base}'` : void 0,
76
- "import.meta.env": `({})`
77
- });
78
- pattern = new RegExp(
79
- "(?<!(?<!\\.\\.)\\.)\\b(" + Object.keys(replacements).map((str) => {
80
- return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
81
- }).join("|") + ")\\b(?!\\s*?=[^=])",
82
- "g"
83
- );
84
- }
85
- }
86
- if (!privateEnv || !pattern)
87
- return;
88
- const references = getReferencedPrivateKeys(source, privateEnv);
89
- if (references.size === 0)
90
- return;
91
- const s = new MagicString(source);
52
+ let s;
53
+ const pattern = new RegExp(
54
+ `(?<!(?<!\\.\\.)\\.)\\b(import\\.meta\\.env\\.(.+?)|import\\.meta\\.env)\\b(?!\\s*?=[^=])`,
55
+ "g"
56
+ );
57
+ let references;
92
58
  let match;
93
59
  while (match = pattern.exec(source)) {
94
- const start = match.index;
95
- const end = start + match[0].length;
96
- let replacement = "" + replacements[match[1]];
60
+ let replacement;
97
61
  if (match[0] === "import.meta.env") {
62
+ privateEnv ?? (privateEnv = getPrivateEnv(viteConfig, astroConfig));
63
+ references ?? (references = getReferencedPrivateKeys(source, privateEnv));
98
64
  replacement = `(Object.assign(import.meta.env,{`;
99
65
  for (const key of references.values()) {
100
66
  replacement += `${key}:${privateEnv[key]},`;
101
67
  }
102
68
  replacement += "}))";
69
+ } else if (match[2]) {
70
+ privateEnv ?? (privateEnv = getPrivateEnv(viteConfig, astroConfig));
71
+ replacement = privateEnv[match[2]];
103
72
  }
104
- s.overwrite(start, end, replacement);
73
+ if (replacement) {
74
+ const start = match.index;
75
+ const end = start + match[0].length;
76
+ s ?? (s = new MagicString(source));
77
+ s.overwrite(start, end, replacement);
78
+ }
79
+ }
80
+ if (s) {
81
+ return {
82
+ code: s.toString(),
83
+ map: s.generateMap()
84
+ };
105
85
  }
106
- return {
107
- code: s.toString(),
108
- map: s.generateMap()
109
- };
110
86
  }
111
87
  };
112
88
  }
@@ -1,9 +1,11 @@
1
1
  /// <reference types="node" />
2
2
  import nodeFs from 'fs';
3
3
  import type * as vite from 'vite';
4
+ import type { AstroSettings } from '../@types/astro';
4
5
  declare type NodeFileSystemModule = typeof nodeFs;
5
6
  export interface LoadFallbackPluginParams {
6
7
  fs?: NodeFileSystemModule;
8
+ settings: AstroSettings;
7
9
  }
8
- export default function loadFallbackPlugin({ fs }: LoadFallbackPluginParams): vite.Plugin | false;
10
+ export default function loadFallbackPlugin({ fs, settings, }: LoadFallbackPluginParams): vite.Plugin[] | false;
9
11
  export {};
@@ -1,22 +1,55 @@
1
1
  import nodeFs from "fs";
2
- function loadFallbackPlugin({ fs }) {
2
+ import npath from "path";
3
+ function loadFallbackPlugin({
4
+ fs,
5
+ settings
6
+ }) {
3
7
  if (!fs || fs === nodeFs) {
4
8
  return false;
5
9
  }
6
- return {
7
- name: "astro:load-fallback",
8
- enforce: "post",
9
- async load(id) {
10
+ const tryLoadModule = async (id) => {
11
+ try {
12
+ return await fs.promises.readFile(cleanUrl(id), "utf-8");
13
+ } catch (e) {
10
14
  try {
11
- return await fs.promises.readFile(cleanUrl(id), "utf-8");
12
- } catch (e) {
15
+ return await fs.promises.readFile(id, "utf-8");
16
+ } catch (e2) {
13
17
  try {
14
- return await fs.promises.readFile(id, "utf-8");
15
- } catch (e2) {
18
+ const fullpath = new URL("." + id, settings.config.root);
19
+ return await fs.promises.readFile(fullpath, "utf-8");
20
+ } catch (e3) {
16
21
  }
17
22
  }
18
23
  }
19
24
  };
25
+ return [
26
+ {
27
+ name: "astro:load-fallback",
28
+ enforce: "post",
29
+ resolveId(id, parent) {
30
+ if (id.startsWith(".") && parent && fs.existsSync(parent)) {
31
+ return npath.posix.join(npath.posix.dirname(parent), id);
32
+ }
33
+ },
34
+ async load(id) {
35
+ const source = await tryLoadModule(id);
36
+ return source;
37
+ }
38
+ },
39
+ {
40
+ name: "astro:load-fallback-hmr",
41
+ enforce: "pre",
42
+ handleHotUpdate(context) {
43
+ const read = context.read;
44
+ context.read = async () => {
45
+ const source = await tryLoadModule(context.file);
46
+ if (source)
47
+ return source;
48
+ return read.call(context);
49
+ };
50
+ }
51
+ }
52
+ ];
20
53
  }
21
54
  const queryRE = /\?.*$/s;
22
55
  const hashRE = /#.*$/s;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro",
3
- "version": "1.6.3",
3
+ "version": "1.6.5",
4
4
  "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.",
5
5
  "type": "module",
6
6
  "author": "withastro",