astro 1.0.1 → 1.0.4

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/core/add/index.js +21 -5
  2. package/dist/core/app/index.js +3 -0
  3. package/dist/core/app/node.js +11 -5
  4. package/dist/core/build/generate.js +2 -2
  5. package/dist/core/build/index.js +16 -35
  6. package/dist/core/dev/index.js +1 -1
  7. package/dist/core/errors.js +1 -1
  8. package/dist/core/messages.js +2 -2
  9. package/dist/core/render/dev/index.js +3 -4
  10. package/dist/core/render/dev/vite.js +4 -3
  11. package/dist/core/render/result.js +2 -1
  12. package/dist/core/routing/manifest/generator.js +4 -1
  13. package/dist/core/util.js +17 -3
  14. package/dist/jsx/babel.js +69 -1
  15. package/dist/runtime/server/astro-global.js +1 -1
  16. package/dist/runtime/server/astro-island.js +9 -1
  17. package/dist/runtime/server/astro-island.prebuilt.js +1 -1
  18. package/dist/runtime/server/hydration.js +8 -3
  19. package/dist/runtime/server/render/any.js +1 -2
  20. package/dist/runtime/server/render/component.js +4 -3
  21. package/dist/runtime/server/render/page.js +13 -2
  22. package/dist/types/@types/astro.d.ts +35 -1
  23. package/dist/types/core/app/node.d.ts +4 -3
  24. package/dist/types/core/build/page-data.d.ts +0 -6
  25. package/dist/types/core/errors.d.ts +5 -2
  26. package/dist/types/core/util.d.ts +8 -3
  27. package/dist/types/runtime/server/astro-island.prebuilt.d.ts +1 -1
  28. package/dist/types/runtime/server/hydration.d.ts +3 -10
  29. package/dist/types/runtime/server/index.d.ts +1 -1
  30. package/dist/types/runtime/server/render/any.d.ts +2 -1
  31. package/dist/types/runtime/server/render/astro.d.ts +3 -4
  32. package/dist/types/runtime/server/render/common.d.ts +2 -3
  33. package/dist/types/runtime/server/render/component.d.ts +2 -3
  34. package/dist/types/runtime/server/render/index.d.ts +0 -1
  35. package/dist/types/vite-plugin-astro/query.d.ts +1 -0
  36. package/dist/vite-plugin-astro/hmr.js +12 -4
  37. package/dist/vite-plugin-astro/index.js +5 -1
  38. package/dist/vite-plugin-astro/query.js +5 -0
  39. package/dist/vite-plugin-jsx/index.js +4 -1
  40. package/dist/vite-plugin-markdown/index.js +3 -3
  41. package/env.d.ts +17 -2
  42. package/package.json +3 -3
  43. package/dist/runtime/server/render/types.js +0 -0
  44. package/dist/types/runtime/server/render/types.d.ts +0 -7
@@ -255,10 +255,8 @@ async function parseAstroConfig(configURL) {
255
255
  return result;
256
256
  }
257
257
  const toIdent = (name) => {
258
- if (name.includes("-")) {
259
- return name.split("-")[0];
260
- }
261
- return name;
258
+ const ident = name.trim().replace(/[-_\.]?astro(?:js)?[-_\.]?/g, "").replace(/\.js/, "").replace(/(?:[\.\-\_\/]+)([a-zA-Z])/g, (_, w) => w.toUpperCase()).replace(/^[^a-zA-Z$_]+/, "");
259
+ return `${ident[0].toLowerCase()}${ident.slice(1)}`;
262
260
  };
263
261
  function createPrettyError(err) {
264
262
  err.message = `Astro could not update your astro.config.js file safely.
@@ -328,6 +326,24 @@ async function setAdapter(ast, adapter, exportName) {
328
326
  const configObject = path2.node.declaration.arguments[0];
329
327
  if (!t.isObjectExpression(configObject))
330
328
  return;
329
+ let outputProp = configObject.properties.find((prop) => {
330
+ if (prop.type !== "ObjectProperty")
331
+ return false;
332
+ if (prop.key.type === "Identifier") {
333
+ if (prop.key.name === "output")
334
+ return true;
335
+ }
336
+ if (prop.key.type === "StringLiteral") {
337
+ if (prop.key.value === "output")
338
+ return true;
339
+ }
340
+ return false;
341
+ });
342
+ if (!outputProp) {
343
+ configObject.properties.push(
344
+ t.objectProperty(t.identifier("output"), t.stringLiteral("server"))
345
+ );
346
+ }
331
347
  let adapterProp = configObject.properties.find((prop) => {
332
348
  if (prop.type !== "ObjectProperty")
333
349
  return false;
@@ -610,7 +626,7 @@ function parseIntegrationName(spec) {
610
626
  return { scope, name, tag };
611
627
  }
612
628
  async function askToContinue({ flags }) {
613
- if (flags.yes)
629
+ if (flags.yes || flags.y)
614
630
  return true;
615
631
  const response = await prompts({
616
632
  type: "confirm",
@@ -87,6 +87,9 @@ class App {
87
87
  });
88
88
  }
89
89
  }
90
+ if (routeData.route === "/404") {
91
+ defaultStatus = 404;
92
+ }
90
93
  let mod = __privateGet(this, _manifest).pageMap.get(routeData.component);
91
94
  if (routeData.type === "page") {
92
95
  let response = await __privateMethod(this, _renderPage, renderPage_fn).call(this, request, routeData, mod, defaultStatus);
@@ -19,10 +19,10 @@ function createRequestFromNodeRequest(req, body) {
19
19
  return request;
20
20
  }
21
21
  class NodeApp extends App {
22
- match(req) {
23
- return super.match(req instanceof Request ? req : createRequestFromNodeRequest(req));
22
+ match(req, opts = {}) {
23
+ return super.match(req instanceof Request ? req : createRequestFromNodeRequest(req), opts);
24
24
  }
25
- render(req) {
25
+ render(req, routeData) {
26
26
  if ("on" in req) {
27
27
  let body = Buffer.from([]);
28
28
  let reqBodyComplete = new Promise((resolve, reject) => {
@@ -37,10 +37,16 @@ class NodeApp extends App {
37
37
  });
38
38
  });
39
39
  return reqBodyComplete.then(() => {
40
- return super.render(req instanceof Request ? req : createRequestFromNodeRequest(req, body));
40
+ return super.render(
41
+ req instanceof Request ? req : createRequestFromNodeRequest(req, body),
42
+ routeData
43
+ );
41
44
  });
42
45
  }
43
- return super.render(req instanceof Request ? req : createRequestFromNodeRequest(req));
46
+ return super.render(
47
+ req instanceof Request ? req : createRequestFromNodeRequest(req),
48
+ routeData
49
+ );
44
50
  }
45
51
  }
46
52
  async function loadManifest(rootFolder) {
@@ -108,7 +108,7 @@ async function generatePage(opts, internals, pageData, ssrEntry, builtPaths) {
108
108
  const timeEnd = performance.now();
109
109
  const timeChange = getTimeStat(timeStart, timeEnd);
110
110
  const timeIncrease = `(+${timeChange})`;
111
- const filePath = getOutputFilename(opts.astroConfig, path);
111
+ const filePath = getOutputFilename(opts.astroConfig, path, pageData.route.type);
112
112
  const lineIcon = i === paths.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
113
113
  info(opts.logging, null, ` ${cyan(lineIcon)} ${dim(filePath)} ${dim(timeIncrease)}`);
114
114
  }
@@ -157,7 +157,7 @@ async function getPathsForRoute(pageData, mod, opts, builtPaths) {
157
157
  return paths;
158
158
  }
159
159
  function addPageName(pathname, opts) {
160
- opts.pageNames.push(pathname.replace(/\/?$/, "/").replace(/^\//, ""));
160
+ opts.pageNames.push(pathname.replace(/^\//, ""));
161
161
  }
162
162
  async function generatePath(pathname, opts, gopts) {
163
163
  var _a;
@@ -1,7 +1,6 @@
1
1
  import fs from "fs";
2
2
  import * as colors from "kleur/colors";
3
3
  import { performance } from "perf_hooks";
4
- import * as vite from "vite";
5
4
  import {
6
5
  runHookBuildDone,
7
6
  runHookBuildStart,
@@ -14,7 +13,6 @@ import { debug, info, levels, timerMessage } from "../logger/core.js";
14
13
  import { apply as applyPolyfill } from "../polyfill.js";
15
14
  import { RouteCache } from "../render/route-cache.js";
16
15
  import { createRouteManifest } from "../routing/index.js";
17
- import { createSafeError } from "../util.js";
18
16
  import { collectPagesData } from "./page-data.js";
19
17
  import { staticBuild } from "./static-build.js";
20
18
  import { getTimeStat } from "./util.js";
@@ -40,7 +38,6 @@ class AstroBuilder {
40
38
  debug("build", "Initial setup...");
41
39
  const { logging } = this;
42
40
  this.timer.init = performance.now();
43
- this.timer.viteStart = performance.now();
44
41
  this.config = await runHookConfigSetup({ config: this.config, command: "build" });
45
42
  this.manifest = createRouteManifest({ config: this.config }, this.logging);
46
43
  const viteConfig = await createVite(
@@ -55,15 +52,9 @@ class AstroBuilder {
55
52
  { astroConfig: this.config, logging, mode: "build" }
56
53
  );
57
54
  await runHookConfigDone({ config: this.config });
58
- const viteServer = await vite.createServer(viteConfig);
59
- debug("build", timerMessage("Vite started", this.timer.viteStart));
60
- return { viteConfig, viteServer };
55
+ return { viteConfig };
61
56
  }
62
- async build({
63
- viteConfig,
64
- viteServer
65
- }) {
66
- const { origin } = this;
57
+ async build({ viteConfig }) {
67
58
  const buildConfig = {
68
59
  client: new URL("./client/", this.config.outDir),
69
60
  server: new URL("./server/", this.config.outDir),
@@ -79,11 +70,7 @@ class AstroBuilder {
79
70
  const { assets, allPages } = await collectPagesData({
80
71
  astroConfig: this.config,
81
72
  logging: this.logging,
82
- manifest: this.manifest,
83
- origin,
84
- routeCache: this.routeCache,
85
- viteServer,
86
- ssr: this.config.output === "server"
73
+ manifest: this.manifest
87
74
  });
88
75
  debug("build", timerMessage("All pages loaded", this.timer.loadStart));
89
76
  const pageNames = [];
@@ -93,23 +80,18 @@ class AstroBuilder {
93
80
  "build",
94
81
  colors.dim(`Completed in ${getTimeStat(this.timer.init, performance.now())}.`)
95
82
  );
96
- try {
97
- await staticBuild({
98
- allPages,
99
- astroConfig: this.config,
100
- logging: this.logging,
101
- manifest: this.manifest,
102
- mode: this.mode,
103
- origin: this.origin,
104
- pageNames,
105
- routeCache: this.routeCache,
106
- viteConfig,
107
- buildConfig
108
- });
109
- } catch (err) {
110
- await viteServer.close();
111
- throw err;
112
- }
83
+ await staticBuild({
84
+ allPages,
85
+ astroConfig: this.config,
86
+ logging: this.logging,
87
+ manifest: this.manifest,
88
+ mode: this.mode,
89
+ origin: this.origin,
90
+ pageNames,
91
+ routeCache: this.routeCache,
92
+ viteConfig,
93
+ buildConfig
94
+ });
113
95
  this.timer.assetsStart = performance.now();
114
96
  Object.keys(assets).map((k) => {
115
97
  if (!assets[k])
@@ -120,7 +102,6 @@ class AstroBuilder {
120
102
  delete assets[k];
121
103
  });
122
104
  debug("build", timerMessage("Additional assets copied", this.timer.assetsStart));
123
- await viteServer.close();
124
105
  await runHookBuildDone({
125
106
  config: this.config,
126
107
  buildConfig,
@@ -141,7 +122,7 @@ class AstroBuilder {
141
122
  try {
142
123
  await this.build(setupData);
143
124
  } catch (_err) {
144
- throw fixViteErrorMessage(createSafeError(_err), setupData.viteServer);
125
+ throw fixViteErrorMessage(_err);
145
126
  }
146
127
  }
147
128
  async printStats({
@@ -46,7 +46,7 @@ async function dev(config, options) {
46
46
  https: !!((_a = viteConfig.server) == null ? void 0 : _a.https)
47
47
  })
48
48
  );
49
- const currentVersion = "1.0.1";
49
+ const currentVersion = "1.0.4";
50
50
  if (currentVersion.includes("-")) {
51
51
  warn(options.logging, null, msg.prerelease({ currentVersion }));
52
52
  }
@@ -17,7 +17,7 @@ function cleanErrorStack(stack) {
17
17
  function fixViteErrorMessage(_err, server, filePath) {
18
18
  var _a, _b;
19
19
  const err = createSafeError(_err);
20
- server.ssrFixStacktrace(err);
20
+ server == null ? void 0 : server.ssrFixStacktrace(err);
21
21
  if (err.message === "import.meta.glob() can only accept string literals.") {
22
22
  err.message = "Astro.glob() and import.meta.glob() can only accept string literals.";
23
23
  }
@@ -47,7 +47,7 @@ function devStart({
47
47
  https,
48
48
  site
49
49
  }) {
50
- const version = "1.0.1";
50
+ const version = "1.0.4";
51
51
  const rootPath = site ? site.pathname : "/";
52
52
  const localPrefix = `${dim("\u2503")} Local `;
53
53
  const networkPrefix = `${dim("\u2503")} Network `;
@@ -226,7 +226,7 @@ function printHelp({
226
226
  message.push(
227
227
  linebreak(),
228
228
  ` ${bgGreen(black(` ${commandName} `))} ${green(
229
- `v${"1.0.1"}`
229
+ `v${"1.0.4"}`
230
230
  )} ${headline}`
231
231
  );
232
232
  }
@@ -1,7 +1,6 @@
1
1
  import { fileURLToPath } from "url";
2
- import { prependForwardSlash } from "../../../core/path.js";
3
2
  import { PAGE_SCRIPT_ID } from "../../../vite-plugin-scripts/index.js";
4
- import { isPage } from "../../util.js";
3
+ import { isPage, resolveIdToUrl } from "../../util.js";
5
4
  import { render as coreRender } from "../core.js";
6
5
  import { collectMdMetadata } from "../util.js";
7
6
  import { getStylesForURL } from "./css.js";
@@ -54,7 +53,7 @@ async function render(renderers, mod, ssrOpts) {
54
53
  scripts.add({
55
54
  props: {
56
55
  type: "module",
57
- src: "/@id/astro/runtime/client/hmr.js"
56
+ src: await resolveIdToUrl(viteServer, "astro/runtime/client/hmr.js")
58
57
  },
59
58
  children: ""
60
59
  });
@@ -115,7 +114,7 @@ async function render(renderers, mod, ssrOpts) {
115
114
  if (s.startsWith("/@fs")) {
116
115
  return resolveClientDevPath(s);
117
116
  }
118
- return "/@id" + prependForwardSlash(s);
117
+ return await resolveIdToUrl(viteServer, s);
119
118
  },
120
119
  renderers,
121
120
  request,
@@ -2,6 +2,7 @@ import npath from "path";
2
2
  import { unwrapId } from "../../util.js";
3
3
  import { STYLE_EXTENSIONS } from "../util.js";
4
4
  const fileExtensionsToSSR = /* @__PURE__ */ new Set([".astro", ".md"]);
5
+ const STRIP_QUERY_PARAMS_REGEX = /\?.*$/;
5
6
  async function* crawlGraph(viteServer, _id, isFile, scanned = /* @__PURE__ */ new Set()) {
6
7
  const id = unwrapId(_id);
7
8
  const importedModules = /* @__PURE__ */ new Set();
@@ -15,11 +16,11 @@ async function* crawlGraph(viteServer, _id, isFile, scanned = /* @__PURE__ */ ne
15
16
  const entryIsStyle = STYLE_EXTENSIONS.has(npath.extname(id));
16
17
  for (const importedModule of entry.importedModules) {
17
18
  if (importedModule.id) {
18
- const { pathname } = new URL(`file://${importedModule.id}`);
19
- if (entryIsStyle && !STYLE_EXTENSIONS.has(npath.extname(pathname))) {
19
+ const importedModulePathname = importedModule.id.replace(STRIP_QUERY_PARAMS_REGEX, "");
20
+ if (entryIsStyle && !STYLE_EXTENSIONS.has(npath.extname(importedModulePathname))) {
20
21
  continue;
21
22
  }
22
- if (fileExtensionsToSSR.has(npath.extname(pathname))) {
23
+ if (fileExtensionsToSSR.has(npath.extname(importedModulePathname))) {
23
24
  const mod = viteServer.moduleGraph.getModuleById(importedModule.id);
24
25
  if (!(mod == null ? void 0 : mod.ssrModule)) {
25
26
  await viteServer.ssrLoadModule(importedModule.id);
@@ -223,7 +223,8 @@ const canonicalURL = new URL(Astro.url.pathname, Astro.site);
223
223
  renderers,
224
224
  pathname,
225
225
  hasHydrationScript: false,
226
- hasDirectives: /* @__PURE__ */ new Set()
226
+ hasDirectives: /* @__PURE__ */ new Set(),
227
+ pendingInstructions: /* @__PURE__ */ new Set()
227
228
  },
228
229
  response
229
230
  };
@@ -6,7 +6,10 @@ function getRouteGenerator(segments, addTrailingSlash) {
6
6
  return part.dynamic ? `:${part.content}` : part.content.normalize().replace(/\?/g, "%3F").replace(/#/g, "%23").replace(/%5B/g, "[").replace(/%5D/g, "]").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7
7
  }).join("");
8
8
  }).join("");
9
- const trailing = addTrailingSlash !== "never" && segments.length ? "/" : "";
9
+ let trailing = "";
10
+ if (addTrailingSlash === "always" && segments.length) {
11
+ trailing = "/";
12
+ }
10
13
  const toPath = compile(template + trailing);
11
14
  return toPath;
12
15
  }
package/dist/core/util.js CHANGED
@@ -4,8 +4,8 @@ import path from "path";
4
4
  import resolve from "resolve";
5
5
  import slash from "slash";
6
6
  import { fileURLToPath, pathToFileURL } from "url";
7
- import { removeTrailingForwardSlash } from "./path.js";
8
- const ASTRO_VERSION = "1.0.1";
7
+ import { prependForwardSlash, removeTrailingForwardSlash } from "./path.js";
8
+ const ASTRO_VERSION = "1.0.4";
9
9
  function isObject(value) {
10
10
  return typeof value === "object" && value != null;
11
11
  }
@@ -18,7 +18,10 @@ function padMultilineString(source, n = 2) {
18
18
  `);
19
19
  }
20
20
  const STATUS_CODE_REGEXP = /^\/?[0-9]{3}$/;
21
- function getOutputFilename(astroConfig, name) {
21
+ function getOutputFilename(astroConfig, name, type) {
22
+ if (type === "endpoint") {
23
+ return name;
24
+ }
22
25
  if (name === "/" || name === "") {
23
26
  return path.posix.join(name, "index.html");
24
27
  }
@@ -157,6 +160,16 @@ function getLocalAddress(serverAddress, host) {
157
160
  return serverAddress;
158
161
  }
159
162
  }
163
+ async function resolveIdToUrl(viteServer, id) {
164
+ const result = await viteServer.pluginContainer.resolveId(id);
165
+ if (!result) {
166
+ return VALID_ID_PREFIX + id;
167
+ }
168
+ if (path.isAbsolute(result.id)) {
169
+ return "/@fs" + prependForwardSlash(result.id);
170
+ }
171
+ return VALID_ID_PREFIX + result.id;
172
+ }
160
173
  export {
161
174
  ASTRO_VERSION,
162
175
  VALID_ID_PREFIX,
@@ -175,6 +188,7 @@ export {
175
188
  relativeToSrcDir,
176
189
  removeDir,
177
190
  resolveDependency,
191
+ resolveIdToUrl,
178
192
  resolvePages,
179
193
  unwrapId,
180
194
  viteID
package/dist/jsx/babel.js CHANGED
@@ -52,7 +52,7 @@ function addClientMetadata(node, meta) {
52
52
  }
53
53
  if (!existingAttributes.find((attr) => attr === "client:component-export")) {
54
54
  if (meta.name === "*") {
55
- meta.name = getTagName(node).split(".").at(1);
55
+ meta.name = getTagName(node).split(".").slice(1).join(".");
56
56
  }
57
57
  const componentExport = t.jsxAttribute(
58
58
  t.jsxNamespacedName(t.jsxIdentifier("client"), t.jsxIdentifier("component-export")),
@@ -157,6 +157,74 @@ function astroJSX() {
157
157
  }
158
158
  state.set("imports", imports);
159
159
  },
160
+ JSXMemberExpression(path, state) {
161
+ var _a;
162
+ const node = path.node;
163
+ if (((_a = state.filename) == null ? void 0 : _a.endsWith(".mdx")) && t.isJSXIdentifier(node.object) && node.object.name === "_components") {
164
+ return;
165
+ }
166
+ const parent = path.findParent((n) => t.isJSXElement(n));
167
+ const parentNode = parent.node;
168
+ const tagName = getTagName(parentNode);
169
+ if (!isComponent(tagName))
170
+ return;
171
+ if (!hasClientDirective(parentNode))
172
+ return;
173
+ const isClientOnly = isClientOnlyComponent(parentNode);
174
+ if (tagName === ClientOnlyPlaceholder)
175
+ return;
176
+ const imports = state.get("imports") ?? /* @__PURE__ */ new Map();
177
+ const namespace = tagName.split(".");
178
+ for (const [source, specs] of imports) {
179
+ for (const { imported, local } of specs) {
180
+ const reference = path.referencesImport(source, imported);
181
+ if (reference) {
182
+ path.setData("import", { name: imported, path: source });
183
+ break;
184
+ }
185
+ if (namespace.at(0) === local) {
186
+ path.setData("import", { name: imported, path: source });
187
+ break;
188
+ }
189
+ }
190
+ }
191
+ const meta = path.getData("import");
192
+ if (meta) {
193
+ let resolvedPath;
194
+ if (meta.path.startsWith(".")) {
195
+ const fileURL = pathToFileURL(state.filename);
196
+ resolvedPath = `/@fs${new URL(meta.path, fileURL).pathname}`;
197
+ if (resolvedPath.endsWith(".jsx")) {
198
+ resolvedPath = resolvedPath.slice(0, -4);
199
+ }
200
+ } else {
201
+ resolvedPath = meta.path;
202
+ }
203
+ if (isClientOnly) {
204
+ state.file.metadata.astro.clientOnlyComponents.push({
205
+ exportName: meta.name,
206
+ specifier: tagName,
207
+ resolvedPath
208
+ });
209
+ meta.resolvedPath = resolvedPath;
210
+ addClientOnlyMetadata(parentNode, meta);
211
+ } else {
212
+ state.file.metadata.astro.hydratedComponents.push({
213
+ exportName: "*",
214
+ specifier: tagName,
215
+ resolvedPath
216
+ });
217
+ meta.resolvedPath = resolvedPath;
218
+ addClientMetadata(parentNode, meta);
219
+ }
220
+ } else {
221
+ throw new Error(
222
+ `Unable to match <${getTagName(
223
+ parentNode
224
+ )}> with client:* directive to an import statement!`
225
+ );
226
+ }
227
+ },
160
228
  JSXIdentifier(path, state) {
161
229
  const isAttr = path.findParent((n) => t.isJSXAttribute(n));
162
230
  if (isAttr)
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "1.0.1";
1
+ const ASTRO_VERSION = "1.0.4";
2
2
  function createDeprecatedFetchContentFn() {
3
3
  return () => {
4
4
  throw new Error("Deprecated: Astro.fetchContent() has been replaced with Astro.glob().");
@@ -72,7 +72,15 @@ var _a;
72
72
  rendererUrl ? import(rendererUrl) : () => () => {
73
73
  }
74
74
  ]);
75
- this.Component = componentModule[this.getAttribute("component-export") || "default"];
75
+ const componentExport = this.getAttribute("component-export") || "default";
76
+ if (!componentExport.includes(".")) {
77
+ this.Component = componentModule[componentExport];
78
+ } else {
79
+ this.Component = componentModule;
80
+ for (const part of componentExport.split(".")) {
81
+ this.Component = this.Component[part];
82
+ }
83
+ }
76
84
  this.hydrator = hydrator;
77
85
  return this.hydrate;
78
86
  },
@@ -1,4 +1,4 @@
1
- var astro_island_prebuilt_default = `var a;{const l={0:t=>t,1:t=>JSON.parse(t,n),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,n)),5:t=>new Set(JSON.parse(t,n)),6:t=>BigInt(t),7:t=>new URL(t)},n=(t,r)=>{if(t===""||!Array.isArray(r))return r;const[e,i]=r;return e in l?l[e](i):void 0};customElements.get("astro-island")||customElements.define("astro-island",(a=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=()=>{if(!this.hydrator||this.parentElement?.closest("astro-island[ssr]"))return;const r=this.querySelectorAll("astro-slot"),e={},i=this.querySelectorAll("template[data-astro-template]");for(const s of i)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute("data-astro-template")||"default"]=s.innerHTML,s.remove());for(const s of r)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute("name")||"default"]=s.innerHTML);const o=this.hasAttribute("props")?JSON.parse(this.getAttribute("props"),n):{};this.hydrator(this)(this.Component,o,e,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),window.removeEventListener("astro:hydrate",this.hydrate),window.dispatchEvent(new CustomEvent("astro:hydrate"))}}connectedCallback(){!this.hasAttribute("await-children")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((r,e)=>{e.disconnect(),this.childrenConnectedCallback()}).observe(this,{childList:!0})}async childrenConnectedCallback(){window.addEventListener("astro:hydrate",this.hydrate),await import(this.getAttribute("before-hydration-url"));const r=JSON.parse(this.getAttribute("opts"));Astro[this.getAttribute("client")](async()=>{const e=this.getAttribute("renderer-url"),[i,{default:o}]=await Promise.all([import(this.getAttribute("component-url")),e?import(e):()=>()=>{}]);return this.Component=i[this.getAttribute("component-export")||"default"],this.hydrator=o,this.hydrate},r,this)}attributeChangedCallback(){this.hydrator&&this.hydrate()}},a.observedAttributes=["props"],a))}`;
1
+ var astro_island_prebuilt_default = `var a;{const l={0:t=>t,1:t=>JSON.parse(t,n),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,n)),5:t=>new Set(JSON.parse(t,n)),6:t=>BigInt(t),7:t=>new URL(t)},n=(t,r)=>{if(t===""||!Array.isArray(r))return r;const[s,i]=r;return s in l?l[s](i):void 0};customElements.get("astro-island")||customElements.define("astro-island",(a=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=()=>{if(!this.hydrator||this.parentElement?.closest("astro-island[ssr]"))return;const r=this.querySelectorAll("astro-slot"),s={},i=this.querySelectorAll("template[data-astro-template]");for(const e of i)!e.closest(this.tagName)?.isSameNode(this)||(s[e.getAttribute("data-astro-template")||"default"]=e.innerHTML,e.remove());for(const e of r)!e.closest(this.tagName)?.isSameNode(this)||(s[e.getAttribute("name")||"default"]=e.innerHTML);const o=this.hasAttribute("props")?JSON.parse(this.getAttribute("props"),n):{};this.hydrator(this)(this.Component,o,s,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),window.removeEventListener("astro:hydrate",this.hydrate),window.dispatchEvent(new CustomEvent("astro:hydrate"))}}connectedCallback(){!this.hasAttribute("await-children")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((r,s)=>{s.disconnect(),this.childrenConnectedCallback()}).observe(this,{childList:!0})}async childrenConnectedCallback(){window.addEventListener("astro:hydrate",this.hydrate),await import(this.getAttribute("before-hydration-url"));const r=JSON.parse(this.getAttribute("opts"));Astro[this.getAttribute("client")](async()=>{const s=this.getAttribute("renderer-url"),[i,{default:o}]=await Promise.all([import(this.getAttribute("component-url")),s?import(s):()=>()=>{}]),e=this.getAttribute("component-export")||"default";if(!e.includes("."))this.Component=i[e];else{this.Component=i;for(const c of e.split("."))this.Component=this.Component[c]}return this.hydrator=o,this.hydrate},r,this)}attributeChangedCallback(){this.hydrator&&this.hydrate()}},a.observedAttributes=["props"],a))}`;
2
2
  export {
3
3
  astro_island_prebuilt_default as default
4
4
  };
@@ -67,11 +67,11 @@ function extractDirectives(inputProps) {
67
67
  return extracted;
68
68
  }
69
69
  async function generateHydrateScript(scriptOptions, metadata) {
70
- const { renderer, result, astroId, props } = scriptOptions;
70
+ const { renderer, result, astroId, props, attrs } = scriptOptions;
71
71
  const { hydrate, componentUrl, componentExport } = metadata;
72
- if (!componentExport) {
72
+ if (!componentExport.value) {
73
73
  throw new Error(
74
- `Unable to resolve a componentExport for "${metadata.displayName}"! Please open an issue.`
74
+ `Unable to resolve a valid export for "${metadata.displayName}"! Please open an issue at https://astro.build/issues!`
75
75
  );
76
76
  }
77
77
  const island = {
@@ -80,6 +80,11 @@ async function generateHydrateScript(scriptOptions, metadata) {
80
80
  uid: astroId
81
81
  }
82
82
  };
83
+ if (attrs) {
84
+ for (const [key, value] of Object.entries(attrs)) {
85
+ island.props[key] = value;
86
+ }
87
+ }
83
88
  island.props["component-url"] = await result.resolve(componentUrl);
84
89
  if (renderer.clientEntrypoint) {
85
90
  island.props["component-export"] = componentExport.value;
@@ -1,6 +1,5 @@
1
1
  import { escapeHTML, HTMLString, markHTMLString } from "../escape.js";
2
2
  import { AstroComponent, renderAstroComponent } from "./astro.js";
3
- import { stringifyChunk } from "./common.js";
4
3
  async function* renderChild(child) {
5
4
  child = await child;
6
5
  if (child instanceof HTMLString) {
@@ -28,7 +27,7 @@ async function renderSlot(result, slotted, fallback) {
28
27
  let content = "";
29
28
  for await (const chunk of iterator) {
30
29
  if (chunk.type === "directive") {
31
- content += stringifyChunk(result, chunk);
30
+ result._metadata.pendingInstructions.add(chunk);
32
31
  } else {
33
32
  content += chunk;
34
33
  }
@@ -77,6 +77,7 @@ Did you forget to import the component or is it possible there is a typo?`
77
77
  const metadata = { displayName };
78
78
  const { hydration, isPage, props } = extractDirectives(_props);
79
79
  let html = "";
80
+ let attrs = void 0;
80
81
  if (hydration) {
81
82
  metadata.hydrate = hydration.directive;
82
83
  metadata.hydrateArgs = hydration.value;
@@ -164,7 +165,7 @@ but ${plural ? "none were" : "it was not"} able to server-side render ${metadata
164
165
  Did you mean to enable ${formatList(probableRendererNames.map((r) => "`" + r + "`"))}?`);
165
166
  } else if (matchingRenderers.length === 1) {
166
167
  renderer = matchingRenderers[0];
167
- ({ html } = await renderer.ssr.renderToStaticMarkup.call(
168
+ ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
168
169
  { result },
169
170
  Component,
170
171
  props,
@@ -189,7 +190,7 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
189
190
  if (metadata.hydrate === "only") {
190
191
  html = await renderSlot(result, slots == null ? void 0 : slots.fallback);
191
192
  } else {
192
- ({ html } = await renderer.ssr.renderToStaticMarkup.call(
193
+ ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
193
194
  { result },
194
195
  Component,
195
196
  props,
@@ -229,7 +230,7 @@ ${serializeProps(
229
230
  )}`
230
231
  );
231
232
  const island = await generateHydrateScript(
232
- { renderer, result, astroId, props },
233
+ { renderer, result, astroId, props, attrs },
233
234
  metadata
234
235
  );
235
236
  let unrenderedSlots = [];
@@ -36,13 +36,24 @@ async function renderPage(result, componentFactory, props, children, streaming)
36
36
  let init = result.response;
37
37
  let headers = new Headers(init.headers);
38
38
  let body;
39
+ async function* eachChunk() {
40
+ for await (const chunk of iterable) {
41
+ if (result._metadata.pendingInstructions.size) {
42
+ for (const instr of result._metadata.pendingInstructions) {
43
+ result._metadata.pendingInstructions.delete(instr);
44
+ yield instr;
45
+ }
46
+ }
47
+ yield chunk;
48
+ }
49
+ }
39
50
  if (streaming) {
40
51
  body = new ReadableStream({
41
52
  start(controller) {
42
53
  async function read() {
43
54
  let i = 0;
44
55
  try {
45
- for await (const chunk of iterable) {
56
+ for await (const chunk of eachChunk()) {
46
57
  let html = stringifyChunk(result, chunk);
47
58
  if (i === 0) {
48
59
  if (!/<!doctype html/i.test(html)) {
@@ -63,7 +74,7 @@ async function renderPage(result, componentFactory, props, children, streaming)
63
74
  } else {
64
75
  body = "";
65
76
  let i = 0;
66
- for await (const chunk of iterable) {
77
+ for await (const chunk of eachChunk()) {
67
78
  let html = stringifyChunk(result, chunk);
68
79
  if (i === 0) {
69
80
  if (!/<!doctype html/i.test(html)) {
@@ -216,7 +216,7 @@ export interface AstroGlobalPartial {
216
216
  */
217
217
  glob(globStr: `${any}.astro`): Promise<AstroInstance[]>;
218
218
  glob<T extends Record<string, any>>(globStr: `${any}.md`): Promise<MarkdownInstance<T>[]>;
219
- glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MarkdownInstance<T>[]>;
219
+ glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MDXInstance<T>[]>;
220
220
  glob<T extends Record<string, any>>(globStr: string): Promise<T[]>;
221
221
  /**
222
222
  * Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option
@@ -782,6 +782,25 @@ export interface MarkdownInstance<T extends Record<string, any>> {
782
782
  default: AstroComponentFactory;
783
783
  }>;
784
784
  }
785
+ export interface MDXInstance<T> extends Omit<MarkdownInstance<T>, 'rawContent' | 'compiledContent' | 'Content' | 'default'> {
786
+ /** 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 */
787
+ rawContent: never;
788
+ /** 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 */
789
+ compiledContent: never;
790
+ default: AstroComponentFactory;
791
+ Content: AstroComponentFactory;
792
+ }
793
+ export interface MarkdownLayoutProps<T extends Record<string, any>> {
794
+ frontmatter: {
795
+ file: MarkdownInstance<T>['file'];
796
+ url: MarkdownInstance<T>['url'];
797
+ } & T;
798
+ headings: MarkdownHeading[];
799
+ rawContent: MarkdownInstance<T>['rawContent'];
800
+ compiledContent: MarkdownInstance<T>['compiledContent'];
801
+ }
802
+ export interface MDXLayoutProps<T> extends Omit<MarkdownLayoutProps<T>, 'rawContent' | 'compiledContent'> {
803
+ }
785
804
  export declare type GetHydrateCallback = () => Promise<() => void | Promise<void>>;
786
805
  /**
787
806
  * getStaticPaths() options
@@ -917,6 +936,7 @@ export interface SSRLoadedRenderer extends AstroRenderer {
917
936
  check: AsyncRendererComponentFn<boolean>;
918
937
  renderToStaticMarkup: AsyncRendererComponentFn<{
919
938
  html: string;
939
+ attrs?: Record<string, string>;
920
940
  }>;
921
941
  };
922
942
  }
@@ -996,11 +1016,25 @@ export interface SSRElement {
996
1016
  props: Record<string, any>;
997
1017
  children: string;
998
1018
  }
1019
+ export interface HydrationMetadata {
1020
+ directive: string;
1021
+ value: string;
1022
+ componentUrl: string;
1023
+ componentExport: {
1024
+ value: string;
1025
+ };
1026
+ }
1027
+ export interface SSRRenderInstruction {
1028
+ type: 'directive';
1029
+ result: SSRResult;
1030
+ hydration: HydrationMetadata;
1031
+ }
999
1032
  export interface SSRMetadata {
1000
1033
  renderers: SSRLoadedRenderer[];
1001
1034
  pathname: string;
1002
1035
  hasHydrationScript: boolean;
1003
1036
  hasDirectives: Set<string>;
1037
+ pendingInstructions: Set<SSRRenderInstruction>;
1004
1038
  }
1005
1039
  export interface SSRResult {
1006
1040
  styles: Set<SSRElement>;
@@ -1,10 +1,11 @@
1
1
  /// <reference types="node" />
2
+ import type { RouteData } from '../../@types/astro';
2
3
  import type { SSRManifest } from './types';
3
4
  import { IncomingMessage } from 'http';
4
- import { App } from './index.js';
5
+ import { App, MatchOptions } from './index.js';
5
6
  export declare class NodeApp extends App {
6
- match(req: IncomingMessage | Request): import("../../@types/astro").RouteData | undefined;
7
- render(req: IncomingMessage | Request): Promise<Response>;
7
+ match(req: IncomingMessage | Request, opts?: MatchOptions): RouteData | undefined;
8
+ render(req: IncomingMessage | Request, routeData?: RouteData): Promise<Response>;
8
9
  }
9
10
  export declare function loadManifest(rootFolder: URL): Promise<SSRManifest>;
10
11
  export declare function loadApp(rootFolder: URL): Promise<NodeApp>;
@@ -1,16 +1,10 @@
1
- import type { ViteDevServer } from 'vite';
2
1
  import type { AstroConfig, ManifestData } from '../../@types/astro';
3
2
  import type { LogOptions } from '../logger/core';
4
3
  import type { AllPagesData } from './types';
5
- import { RouteCache } from '../render/route-cache.js';
6
4
  export interface CollectPagesDataOptions {
7
5
  astroConfig: AstroConfig;
8
6
  logging: LogOptions;
9
7
  manifest: ManifestData;
10
- origin: string;
11
- routeCache: RouteCache;
12
- viteServer: ViteDevServer;
13
- ssr: boolean;
14
8
  }
15
9
  export interface CollectPagesDataResult {
16
10
  assets: Record<string, string>;
@@ -22,8 +22,11 @@ export interface ErrorWithMetadata {
22
22
  };
23
23
  }
24
24
  export declare function cleanErrorStack(stack: string): string;
25
- /** Update the error message to correct any vite-isms that we don't want to expose to the user. */
26
- export declare function fixViteErrorMessage(_err: unknown, server: ViteDevServer, filePath?: URL): Error;
25
+ /**
26
+ * Update the error message to correct any vite-isms that we don't want to expose to the user.
27
+ * The `server` is required if the error may come from `server.ssrLoadModule()`.
28
+ */
29
+ export declare function fixViteErrorMessage(_err: unknown, server?: ViteDevServer, filePath?: URL): Error;
27
30
  export declare function createCustomViteLogger(logLevel: LogLevel): Logger;
28
31
  /**
29
32
  * Takes any error-like object and returns a standardized Error + metadata object.
@@ -1,5 +1,5 @@
1
- import type { ErrorPayload } from 'vite';
2
- import type { AstroConfig } from '../@types/astro';
1
+ import type { ErrorPayload, ViteDevServer } from 'vite';
2
+ import type { AstroConfig, RouteType } from '../@types/astro';
3
3
  export declare const ASTRO_VERSION: string;
4
4
  /** Returns true if argument is an object of any prototype/class (but not null). */
5
5
  export declare function isObject(value: unknown): value is Record<string, any>;
@@ -11,7 +11,7 @@ export declare function padMultilineString(source: string, n?: number): string;
11
11
  * Handles both "/foo" and "foo" `name` formats.
12
12
  * Handles `/404` and `/` correctly.
13
13
  */
14
- export declare function getOutputFilename(astroConfig: AstroConfig, name: string): string;
14
+ export declare function getOutputFilename(astroConfig: AstroConfig, name: string, type: RouteType): string;
15
15
  /** is a specifier an npm package? */
16
16
  export declare function parseNpmName(spec: string): {
17
17
  scope?: string;
@@ -41,3 +41,8 @@ export declare function isModeServerWithNoAdapter(config: AstroConfig): boolean;
41
41
  export declare function relativeToSrcDir(config: AstroConfig, idOrUrl: URL | string): string;
42
42
  export declare function emoji(char: string, fallback: string): string;
43
43
  export declare function getLocalAddress(serverAddress: string, host: string | boolean): string;
44
+ /**
45
+ * Simulate Vite's resolve and import analysis so we can import the id as an URL
46
+ * through a script tag or a dynamic import as-is.
47
+ */
48
+ export declare function resolveIdToUrl(viteServer: ViteDevServer, id: string): Promise<string>;
@@ -3,5 +3,5 @@
3
3
  * Do not edit this directly, but instead edit that file and rerun the prebuild
4
4
  * to generate this file.
5
5
  */
6
- declare const _default: "var a;{const l={0:t=>t,1:t=>JSON.parse(t,n),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,n)),5:t=>new Set(JSON.parse(t,n)),6:t=>BigInt(t),7:t=>new URL(t)},n=(t,r)=>{if(t===\"\"||!Array.isArray(r))return r;const[e,i]=r;return e in l?l[e](i):void 0};customElements.get(\"astro-island\")||customElements.define(\"astro-island\",(a=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=()=>{if(!this.hydrator||this.parentElement?.closest(\"astro-island[ssr]\"))return;const r=this.querySelectorAll(\"astro-slot\"),e={},i=this.querySelectorAll(\"template[data-astro-template]\");for(const s of i)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute(\"data-astro-template\")||\"default\"]=s.innerHTML,s.remove());for(const s of r)!s.closest(this.tagName)?.isSameNode(this)||(e[s.getAttribute(\"name\")||\"default\"]=s.innerHTML);const o=this.hasAttribute(\"props\")?JSON.parse(this.getAttribute(\"props\"),n):{};this.hydrator(this)(this.Component,o,e,{client:this.getAttribute(\"client\")}),this.removeAttribute(\"ssr\"),window.removeEventListener(\"astro:hydrate\",this.hydrate),window.dispatchEvent(new CustomEvent(\"astro:hydrate\"))}}connectedCallback(){!this.hasAttribute(\"await-children\")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((r,e)=>{e.disconnect(),this.childrenConnectedCallback()}).observe(this,{childList:!0})}async childrenConnectedCallback(){window.addEventListener(\"astro:hydrate\",this.hydrate),await import(this.getAttribute(\"before-hydration-url\"));const r=JSON.parse(this.getAttribute(\"opts\"));Astro[this.getAttribute(\"client\")](async()=>{const e=this.getAttribute(\"renderer-url\"),[i,{default:o}]=await Promise.all([import(this.getAttribute(\"component-url\")),e?import(e):()=>()=>{}]);return this.Component=i[this.getAttribute(\"component-export\")||\"default\"],this.hydrator=o,this.hydrate},r,this)}attributeChangedCallback(){this.hydrator&&this.hydrate()}},a.observedAttributes=[\"props\"],a))}";
6
+ declare const _default: "var a;{const l={0:t=>t,1:t=>JSON.parse(t,n),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,n)),5:t=>new Set(JSON.parse(t,n)),6:t=>BigInt(t),7:t=>new URL(t)},n=(t,r)=>{if(t===\"\"||!Array.isArray(r))return r;const[s,i]=r;return s in l?l[s](i):void 0};customElements.get(\"astro-island\")||customElements.define(\"astro-island\",(a=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=()=>{if(!this.hydrator||this.parentElement?.closest(\"astro-island[ssr]\"))return;const r=this.querySelectorAll(\"astro-slot\"),s={},i=this.querySelectorAll(\"template[data-astro-template]\");for(const e of i)!e.closest(this.tagName)?.isSameNode(this)||(s[e.getAttribute(\"data-astro-template\")||\"default\"]=e.innerHTML,e.remove());for(const e of r)!e.closest(this.tagName)?.isSameNode(this)||(s[e.getAttribute(\"name\")||\"default\"]=e.innerHTML);const o=this.hasAttribute(\"props\")?JSON.parse(this.getAttribute(\"props\"),n):{};this.hydrator(this)(this.Component,o,s,{client:this.getAttribute(\"client\")}),this.removeAttribute(\"ssr\"),window.removeEventListener(\"astro:hydrate\",this.hydrate),window.dispatchEvent(new CustomEvent(\"astro:hydrate\"))}}connectedCallback(){!this.hasAttribute(\"await-children\")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((r,s)=>{s.disconnect(),this.childrenConnectedCallback()}).observe(this,{childList:!0})}async childrenConnectedCallback(){window.addEventListener(\"astro:hydrate\",this.hydrate),await import(this.getAttribute(\"before-hydration-url\"));const r=JSON.parse(this.getAttribute(\"opts\"));Astro[this.getAttribute(\"client\")](async()=>{const s=this.getAttribute(\"renderer-url\"),[i,{default:o}]=await Promise.all([import(this.getAttribute(\"component-url\")),s?import(s):()=>()=>{}]),e=this.getAttribute(\"component-export\")||\"default\";if(!e.includes(\".\"))this.Component=i[e];else{this.Component=i;for(const c of e.split(\".\"))this.Component=this.Component[c]}return this.hydrator=o,this.hydrate},r,this)}attributeChangedCallback(){this.hydrator&&this.hydrate()}},a.observedAttributes=[\"props\"],a))}";
7
7
  export default _default;
@@ -1,13 +1,6 @@
1
- import type { AstroComponentMetadata, SSRElement, SSRLoadedRenderer, SSRResult } from '../../@types/astro';
1
+ import type { AstroComponentMetadata, HydrationMetadata, SSRElement, SSRLoadedRenderer, SSRResult } from '../../@types/astro';
2
2
  export declare const HydrationDirectiveProps: Set<string>;
3
- export interface HydrationMetadata {
4
- directive: string;
5
- value: string;
6
- componentUrl: string;
7
- componentExport: {
8
- value: string;
9
- };
10
- }
3
+ export { HydrationMetadata };
11
4
  interface ExtractedProps {
12
5
  isPage: boolean;
13
6
  hydration: HydrationMetadata | null;
@@ -19,7 +12,7 @@ interface HydrateScriptOptions {
19
12
  result: SSRResult;
20
13
  astroId: string;
21
14
  props: Record<string | number, any>;
15
+ attrs: Record<string, string> | undefined;
22
16
  }
23
17
  /** For hydrated components, generate a <script type="module"> to load the component */
24
18
  export declare function generateHydrateScript(scriptOptions: HydrateScriptOptions, metadata: Required<AstroComponentMetadata>): Promise<SSRElement>;
25
- export {};
@@ -4,7 +4,7 @@ export { escapeHTML, HTMLString, markHTMLString, markHTMLString as unescapeHTML,
4
4
  export type { Metadata } from './metadata';
5
5
  export { createMetadata } from './metadata.js';
6
6
  export { addAttribute, defineScriptVars, Fragment, maybeRenderHead, renderAstroComponent, renderComponent, Renderer as Renderer, renderHead, renderHTMLElement, renderPage, renderSlot, renderTemplate as render, renderTemplate, renderToString, stringifyChunk, voidElementNames, } from './render/index.js';
7
- export type { AstroComponentFactory, RenderInstruction } from './render/index.js';
7
+ export type { AstroComponentFactory } from './render/index.js';
8
8
  import type { AstroComponentFactory } from './render/index.js';
9
9
  export declare function createComponent(cb: AstroComponentFactory): AstroComponentFactory;
10
10
  export declare function mergeSlots(...slotted: unknown[]): Record<string, () => any>;
@@ -1,2 +1,3 @@
1
+ import { SSRResult } from '../../../@types/astro';
1
2
  export declare function renderChild(child: any): AsyncIterable<any>;
2
- export declare function renderSlot(result: any, slotted: string, fallback?: any): Promise<string>;
3
+ export declare function renderSlot(result: SSRResult, slotted: string, fallback?: any): Promise<string>;
@@ -1,6 +1,5 @@
1
- import type { SSRResult } from '../../../@types/astro';
1
+ import type { SSRRenderInstruction, SSRResult } from '../../../@types/astro';
2
2
  import type { AstroComponentFactory } from './index';
3
- import type { RenderInstruction } from './types';
4
3
  export declare class AstroComponent {
5
4
  private htmlParts;
6
5
  private expressions;
@@ -9,7 +8,7 @@ export declare class AstroComponent {
9
8
  [Symbol.asyncIterator](): AsyncGenerator<any, void, undefined>;
10
9
  }
11
10
  export declare function isAstroComponent(obj: any): obj is AstroComponent;
12
- export declare function renderAstroComponent(component: InstanceType<typeof AstroComponent>): AsyncIterable<string | RenderInstruction>;
11
+ export declare function renderAstroComponent(component: InstanceType<typeof AstroComponent>): AsyncIterable<string | SSRRenderInstruction>;
13
12
  export declare function renderToString(result: SSRResult, componentFactory: AstroComponentFactory, props: any, children: any): Promise<string>;
14
- export declare function renderToIterable(result: SSRResult, componentFactory: AstroComponentFactory, displayName: string, props: any, children: any): Promise<AsyncIterable<string | RenderInstruction>>;
13
+ export declare function renderToIterable(result: SSRResult, componentFactory: AstroComponentFactory, displayName: string, props: any, children: any): Promise<AsyncIterable<string | SSRRenderInstruction>>;
15
14
  export declare function renderTemplate(htmlParts: TemplateStringsArray, ...expressions: any[]): Promise<AstroComponent>;
@@ -1,5 +1,4 @@
1
- import type { SSRResult } from '../../../@types/astro';
2
- import type { RenderInstruction } from './types.js';
1
+ import type { SSRRenderInstruction, SSRResult } from '../../../@types/astro';
3
2
  export declare const Fragment: unique symbol;
4
3
  export declare const Renderer: unique symbol;
5
- export declare function stringifyChunk(result: SSRResult, chunk: string | RenderInstruction): any;
4
+ export declare function stringifyChunk(result: SSRResult, chunk: string | SSRRenderInstruction): any;
@@ -1,3 +1,2 @@
1
- import type { SSRResult } from '../../../@types/astro';
2
- import type { RenderInstruction } from './types.js';
3
- export declare function renderComponent(result: SSRResult, displayName: string, Component: unknown, _props: Record<string | number, any>, slots?: any): Promise<string | AsyncIterable<string | RenderInstruction>>;
1
+ import type { SSRRenderInstruction, SSRResult } from '../../../@types/astro';
2
+ export declare function renderComponent(result: SSRResult, displayName: string, Component: unknown, _props: Record<string | number, any>, slots?: any): Promise<string | AsyncIterable<string | SSRRenderInstruction>>;
@@ -6,7 +6,6 @@ export { renderComponent } from './component.js';
6
6
  export { renderHTMLElement } from './dom.js';
7
7
  export { maybeRenderHead, renderHead } from './head.js';
8
8
  export { renderPage } from './page.js';
9
- export type { RenderInstruction } from './types';
10
9
  export { addAttribute, defineScriptVars, voidElementNames } from './util.js';
11
10
  export interface AstroComponentFactory {
12
11
  (result: any, props: any, slots: any): ReturnType<typeof renderTemplate> | Response;
@@ -11,3 +11,4 @@ export interface ParsedRequestResult {
11
11
  query: AstroQuery;
12
12
  }
13
13
  export declare function parseAstroRequest(id: string): ParsedRequestResult;
14
+ export declare function isAstroScript(id: string): boolean;
@@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url";
2
2
  import { info } from "../core/logger/core.js";
3
3
  import * as msg from "../core/messages.js";
4
4
  import { invalidateCompilation, isCached } from "./compile.js";
5
+ import { isAstroScript } from "./query.js";
5
6
  async function trackCSSDependencies(opts) {
6
7
  const { viteDevServer, filename, deps, id } = opts;
7
8
  if (viteDevServer) {
@@ -29,7 +30,6 @@ const isPkgFile = (id) => {
29
30
  return (id == null ? void 0 : id.startsWith(fileURLToPath(PKG_PREFIX))) || (id == null ? void 0 : id.startsWith(PKG_PREFIX.pathname));
30
31
  };
31
32
  async function handleHotUpdate(ctx, { config, logging, compile }) {
32
- var _a;
33
33
  let isStyleOnlyChange = false;
34
34
  if (ctx.file.endsWith(".astro")) {
35
35
  const oldResult = await compile();
@@ -81,17 +81,25 @@ async function handleHotUpdate(ctx, { config, logging, compile }) {
81
81
  if (isStyleOnlyChange) {
82
82
  info(logging, "astro", msg.hmr({ file, style: true }));
83
83
  return mods.filter((mod) => {
84
- var _a2;
85
- return mod.id !== ctx.file && !((_a2 = mod.id) == null ? void 0 : _a2.endsWith(".ts"));
84
+ var _a;
85
+ return mod.id !== ctx.file && !((_a = mod.id) == null ? void 0 : _a.endsWith(".ts"));
86
86
  });
87
87
  }
88
88
  for (const mod of mods) {
89
89
  for (const imp of mod.importedModules) {
90
- if ((_a = imp.id) == null ? void 0 : _a.includes("?astro&type=script")) {
90
+ if (imp.id && isAstroScript(imp.id)) {
91
91
  mods.push(imp);
92
92
  }
93
93
  }
94
94
  }
95
+ for (const mod of filtered) {
96
+ if (mod.id && isAstroScript(mod.id) && mod.file) {
97
+ const astroMod = ctx.server.moduleGraph.getModuleById(mod.file);
98
+ if (astroMod) {
99
+ mods.unshift(astroMod);
100
+ }
101
+ }
102
+ }
95
103
  const isSelfAccepting = mods.every((m) => m.isSelfAccepting || m.url.endsWith(".svelte"));
96
104
  if (isSelfAccepting) {
97
105
  info(logging, "astro", msg.hmr({ file }));
@@ -294,7 +294,11 @@ ${source}
294
294
  pluginContext: this
295
295
  };
296
296
  const compile = () => cachedCompilation(compileProps);
297
- return handleHotUpdate.call(this, context, { config, logging, compile });
297
+ return handleHotUpdate.call(this, context, {
298
+ config,
299
+ logging,
300
+ compile
301
+ });
298
302
  }
299
303
  };
300
304
  }
@@ -18,6 +18,11 @@ function parseAstroRequest(id) {
18
18
  query
19
19
  };
20
20
  }
21
+ function isAstroScript(id) {
22
+ const parsed = parseAstroRequest(id);
23
+ return parsed.query.type === "script";
24
+ }
21
25
  export {
26
+ isAstroScript,
22
27
  parseAstroRequest
23
28
  };
@@ -35,7 +35,10 @@ async function transformJSX({
35
35
  }) {
36
36
  const { jsxTransformOptions } = renderer;
37
37
  const options = await jsxTransformOptions({ mode, ssr });
38
- const plugins = [...options.plugins || [], tagExportsPlugin({ rendererName: renderer.name })];
38
+ const plugins = [...options.plugins || []];
39
+ if (ssr) {
40
+ plugins.push(tagExportsPlugin({ rendererName: renderer.name }));
41
+ }
39
42
  const result = await babel.transformAsync(code, {
40
43
  presets: options.presets,
41
44
  plugins,
@@ -31,9 +31,7 @@ function markdown({ config, logging }) {
31
31
  const { frontmatter: injectedFrontmatter } = safelyGetAstroData(renderResult.vfile.data);
32
32
  const frontmatter = {
33
33
  ...injectedFrontmatter,
34
- ...raw.data,
35
- url: fileUrl,
36
- file: fileId
34
+ ...raw.data
37
35
  };
38
36
  const { layout } = frontmatter;
39
37
  if (frontmatter.setup) {
@@ -67,6 +65,8 @@ function markdown({ config, logging }) {
67
65
  };
68
66
  export async function Content() {
69
67
  const { layout, ...content } = frontmatter;
68
+ content.file = file;
69
+ content.url = url;
70
70
  content.astro = {};
71
71
  Object.defineProperty(content.astro, 'headings', {
72
72
  get() {
package/env.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference path="./client.d.ts" />
2
2
 
3
- type Astro = import('astro').AstroGlobal;
3
+ type Astro = import('./dist/types/@types/astro').AstroGlobal;
4
4
 
5
5
  // We duplicate the description here because editors won't show the JSDoc comment from the imported type (but will for its properties, ex: Astro.request will show the AstroGlobal.request description)
6
6
  /**
@@ -13,7 +13,7 @@ declare const Astro: Readonly<Astro>;
13
13
  declare const Fragment: any;
14
14
 
15
15
  declare module '*.md' {
16
- type MD = import('astro').MarkdownInstance<Record<string, any>>;
16
+ type MD = import('./dist/types/@types/astro').MarkdownInstance<Record<string, any>>;
17
17
 
18
18
  export const frontmatter: MD['frontmatter'];
19
19
  export const file: MD['file'];
@@ -29,6 +29,21 @@ declare module '*.md' {
29
29
  export default load;
30
30
  }
31
31
 
32
+ declare module '*.mdx' {
33
+ type MDX = import('astro').MDXInstance<Record<string, any>>;
34
+
35
+ export const frontmatter: MDX['frontmatter'];
36
+ export const file: MDX['file'];
37
+ export const url: MDX['url'];
38
+ export const getHeadings: MDX['getHeadings'];
39
+ export const Content: MDX['Content'];
40
+ export const rawContent: MDX['rawContent'];
41
+ export const compiledContent: MDX['compiledContent'];
42
+
43
+ const load: MDX['default'];
44
+ export default load;
45
+ }
46
+
32
47
  declare module '*.html' {
33
48
  const Component: { render(opts: { slots: Record<string, string> }): string };
34
49
  export default Component;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro",
3
- "version": "1.0.1",
3
+ "version": "1.0.4",
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",
@@ -74,7 +74,7 @@
74
74
  "vendor"
75
75
  ],
76
76
  "dependencies": {
77
- "@astrojs/compiler": "^0.23.1",
77
+ "@astrojs/compiler": "^0.23.3",
78
78
  "@astrojs/language-server": "^0.20.0",
79
79
  "@astrojs/markdown-remark": "^1.0.0",
80
80
  "@astrojs/telemetry": "^1.0.0",
@@ -126,7 +126,7 @@
126
126
  "tsconfig-resolver": "^3.0.1",
127
127
  "unist-util-visit": "^4.1.0",
128
128
  "vfile": "^5.3.2",
129
- "vite": "3.0.4",
129
+ "vite": "3.0.5",
130
130
  "yargs-parser": "^21.0.1",
131
131
  "zod": "^3.17.3"
132
132
  },
File without changes
@@ -1,7 +0,0 @@
1
- import type { SSRResult } from '../../../@types/astro';
2
- import type { HydrationMetadata } from '../hydration.js';
3
- export interface RenderInstruction {
4
- type: 'directive';
5
- result: SSRResult;
6
- hydration: HydrationMetadata;
7
- }