before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
* env: { * schema: { * // ... * }, * validateSecrets: true * } * }) * ``` */ validateSecrets?: boolean; }; /** * * @kind heading * @name Legacy Flags * @description * To help some users migrate between versions of Astro, we occasionally introduce `legacy` ...
```suggestion * Enable backwards compatibility for v4 content collections. * * When enabled, restores the following v4 behaviors: ```
}; /** * * @kind heading * @name Legacy Flags * @description * To help some users migrate between versions of Astro, we occasionally introduce `legacy` flags. * These flags allow you to opt in to some deprecated or otherwise outdated behavior of Astro * in the latest version, so that you can continue t...
@@ -2371,7 +2371,25 @@ export interface AstroUserConfig< * These flags allow you to opt in to some deprecated or otherwise outdated behavior of Astro * in the latest version, so that you can continue to upgrade and take advantage of new Astro releases. */ - legacy?: Record<string, never>; // Currently no legac...
packages/astro/src/types/public/config.ts
26
TypeScript
0.714
suggestion
146
51
51
false
feat: add legacy.collectionsBackwardsCompat flag for v6 content colle…
14,927
withastro/astro
47,179
TypeScript
ascorbic
matthewp
>(config: CollectionConfig<S, TLoader>): CollectionConfig<S, TLoader> { const importerFilename = getImporterFilename(); if (importerFilename?.includes('live.config')) { throw new AstroError({ ...AstroErrorData.LiveContentConfigError, message: AstroErrorData.LiveContentConfigError.message( 'Collections in...
```suggestion `Live content collections must be defined in "src/live.config.ts" file. Check the loaders used in "${importerFilename ?? 'your content config file'}" to ensure you are not using a live loader to define a build-time content collection.`, ``` This message sounds a bit confusing, but I think the probl...
>(config: CollectionConfig<S, TLoader>): CollectionConfig<S, TLoader> { const importerFilename = getImporterFilename(); if (importerFilename?.includes('live.config')) { throw new AstroError({ ...AstroErrorData.LiveContentConfigError, message: AstroErrorData.LiveContentConfigError.message( 'Collections in...
@@ -176,30 +192,23 @@ export function defineCollection< }); } - if (!('loader' in config)) { - throw new AstroError({ - ...AstroErrorData.ContentCollectionMissingLoader, - message: AstroErrorData.ContentCollectionMissingLoader.message(importerFilename), - }); - } - - if (config.type && config.type !== CONT...
packages/astro/src/content/config.ts
26
TypeScript
0.857
suggestion
810
34
34
false
feat: add legacy.collectionsBackwardsCompat flag for v6 content colle…
14,927
withastro/astro
47,179
TypeScript
sarah11918
matthewp
}); } return config; } export function defineCollection< S extends BaseSchema, TLoader extends LoaderConstraint<{ id: string }> = LoaderConstraint<{ id: string }>, >(config: CollectionConfig<S, TLoader>): CollectionConfig<S, TLoader> { const importerFilename = getImporterFilename(); if (importerFilename?.inc...
```suggestion `A content collection is defined with legacy features (e.g. missing a \`loader\` or has a \`type\`). Check your collection definitions in ${importerFilename ?? 'your content config file'} to ensure that all collections are defined using the current properties.`, ``` Similarly, this sounds like a le...
}); } return config; } export function defineCollection< S extends BaseSchema, TLoader extends LoaderConstraint<{ id: string }> = LoaderConstraint<{ id: string }>, >(config: CollectionConfig<S, TLoader>): CollectionConfig<S, TLoader> { const importerFilename = getImporterFilename(); if (importerFilename?.inc...
@@ -176,30 +192,23 @@ export function defineCollection< }); } - if (!('loader' in config)) { - throw new AstroError({ - ...AstroErrorData.ContentCollectionMissingLoader, - message: AstroErrorData.ContentCollectionMissingLoader.message(importerFilename), - }); - } - - if (config.type && config.type !== CONT...
packages/astro/src/content/config.ts
26
TypeScript
1
question
431
43
43
false
feat: add legacy.collectionsBackwardsCompat flag for v6 content colle…
14,927
withastro/astro
47,179
TypeScript
sarah11918
matthewp
import type { CspDirective } from './config.js'; import type { SSRManifestCSP } from '../app/types.js'; /** * `existingDirective` is something like `img-src 'self'`. Same as `newDirective. * * Returns `undefined` if no directive has been deduped * @param existingDirective * @param newDirective */ export function...
```suggestion * `existingDirective` is something like `img-src 'self'`. Same as `newDirective`. ```
import type { CspDirective } from './config.js'; import type { SSRManifestCSP } from '../app/types.js'; /** * `existingDirective` is something like `img-src 'self'`. Same as `newDirective`. * * Returns `undefined` if no directive has been deduped * @param existingDirective * @param newDirective */ export functio...
@@ -0,0 +1,46 @@ +import type { CspDirective } from './config.js'; +import type { SSRManifestCSP } from '../app/types.js'; + +/** + * `existingDirective` is something like `img-src 'self'`. Same as `newDirective.
packages/astro/src/core/csp/runtime.ts
5
TypeScript
0.714
suggestion
100
30
30
false
fix(csp): deduplicate CSP resources
14,940
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import type { CspDirective } from './config.js'; import type { SSRManifestCSP } from '../app/types.js'; /** * `existingDirective` is something like `img-src 'self'`. Same as `newDirective. * * Returns `undefined` if no directive has been deduped * @param existingDirective * @param newDirective */ export function...
I think the splitting may not be robust enough here. See https://github.com/withastro/astro/blob/33333e8ca1d77141312ebc6b1ffa387713cc3994/packages/astro/src/core/csp/common.ts#L77-L83
import type { CspDirective } from './config.js'; import type { SSRManifestCSP } from '../app/types.js'; /** * `existingDirective` is something like `img-src 'self'`. Same as `newDirective`. * * Returns `undefined` if no directive has been deduped * @param existingDirective * @param newDirective */ export functio...
@@ -0,0 +1,46 @@ +import type { CspDirective } from './config.js'; +import type { SSRManifestCSP } from '../app/types.js'; + +/** + * `existingDirective` is something like `img-src 'self'`. Same as `newDirective. + * + * Returns `undefined` if no directive has been deduped + * @param existingDirective + * @param newDir...
packages/astro/src/core/csp/runtime.ts
15
TypeScript
0.357
suggestion
183
40
40
false
fix(csp): deduplicate CSP resources
14,940
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
.default(ASTRO_CONFIG_DEFAULTS.srcDir) .transform((val) => new URL(val)), publicDir: z .string() .optional() .default(ASTRO_CONFIG_DEFAULTS.publicDir) .transform((val) => new URL(val)), outDir: z .string() .optional() .default(ASTRO_CONFIG_DEFAULTS.outDir) .transform((val) => new URL(val)), cache...
Problem is it shows in types, which is not good IMO. I think instead we could have this union but type cast it to include static and server only
.default(ASTRO_CONFIG_DEFAULTS.srcDir) .transform((val) => new URL(val)), publicDir: z .string() .optional() .default(ASTRO_CONFIG_DEFAULTS.publicDir) .transform((val) => new URL(val)), outDir: z .string() .optional() .default(ASTRO_CONFIG_DEFAULTS.outDir) .transform((val) => new URL(val)), cache...
@@ -149,9 +149,14 @@ export const AstroConfigSchema = z.object({ .optional() .default(ASTRO_CONFIG_DEFAULTS.trailingSlash), output: z - .union([z.literal('static'), z.literal('server')]) + // Keep 'hybrid' here so we can give a helpful error message. + .union([z.literal('static'), z.literal('server'), z.lite...
packages/astro/src/core/config/schemas/base.ts
26
TypeScript
0.571
suggestion
144
51
51
false
feat: print a more helpful error message for `output: hybrid`
14,958
withastro/astro
47,179
TypeScript
florian-lefebvre
ascorbic
ACTIONS_RESOLVED_ENTRYPOINT_VIRTUAL_MODULE_ID, OPTIONS_VIRTUAL_MODULE_ID, RESOLVED_NOOP_ENTRYPOINT_VIRTUAL_MODULE_ID, RESOLVED_OPTIONS_VIRTUAL_MODULE_ID, RESOLVED_RUNTIME_VIRTUAL_MODULE_ID, RESOLVED_VIRTUAL_MODULE_ID, RUNTIME_VIRTUAL_MODULE_ID, VIRTUAL_MODULE_ID, } from './consts.js'; import { isActionsFilePres...
in my opinion this should be named `ssr` not `server` to match the Vite-defined name. Soft opinion, open to discussion.
ACTIONS_RESOLVED_ENTRYPOINT_VIRTUAL_MODULE_ID, OPTIONS_VIRTUAL_MODULE_ID, RESOLVED_NOOP_ENTRYPOINT_VIRTUAL_MODULE_ID, RESOLVED_OPTIONS_VIRTUAL_MODULE_ID, RESOLVED_RUNTIME_VIRTUAL_MODULE_ID, RESOLVED_VIRTUAL_MODULE_ID, RUNTIME_VIRTUAL_MODULE_ID, VIRTUAL_MODULE_ID, } from './consts.js'; import { isActionsFilePres...
@@ -31,7 +32,7 @@ export function vitePluginActionsBuild( name: '@astro/plugin-actions-build', applyToEnvironment(environment) { - return environment.name === 'ssr'; + return environment.name === ASTRO_VITE_ENVIRONMENT_NAMES.server;
packages/astro/src/actions/vite-plugin-actions.ts
26
TypeScript
0.571
suggestion
119
51
51
false
refactor: stabilise environment names
14,961
withastro/astro
47,179
TypeScript
matthewp
ematipico
return { code: `export const css = new Set()`, }; } if (id.startsWith(RESOLVED_MODULE_DEV_CSS_PREFIX)) { const componentPath = getComponentFromVirtualModuleCssName( RESOLVED_MODULE_DEV_CSS_PREFIX, id, ); // Collect CSS by walking the dependency tree from the component...
There's a lot of unrelated changes in this PR. Is your editor formatting? Isn't the code already formatted by CI?
} if (id.startsWith(RESOLVED_MODULE_DEV_CSS_PREFIX)) { const componentPath = getComponentFromVirtualModuleCssName( RESOLVED_MODULE_DEV_CSS_PREFIX, id, ); // Collect CSS by walking the dependency tree from the component const cssWithOrder = new Map<string, ImportedDevStyle>(); // Th...
@@ -82,110 +83,119 @@ export function astroDevCssPlugin({ routesList, command }: AstroVitePluginOption // Cache CSS content by module ID to avoid re-reading const cssContentCache = new Map<string, string>(); - return [{ - name: MODULE_DEV_CSS, + return [ + { + name: MODULE_DEV_CSS, - async configureServer(...
packages/astro/src/vite-plugin-css/index.ts
26
TypeScript
0.429
question
113
51
51
false
refactor: stabilise environment names
14,961
withastro/astro
47,179
TypeScript
matthewp
ematipico
if (!mod) { return { code: 'export const css = new Set()', }; } // Walk through the graph depth-first for (const collected of collectCSSWithOrder(componentPageId, mod!)) { // Use the CSS file ID as the key to deduplicate while keeping best ordering if (!cssWithOrder....
Hard to tell from the diff but this looks like an actual code change? Is this correct?
code: 'export const css = new Set()' }; } // Walk through the graph depth-first for (const collected of collectCSSWithOrder(componentPageId, mod!)) { // Use the CSS file ID as the key to deduplicate while keeping best ordering if (!cssWithOrder.has(collected.idKey)) { // Look up ...
@@ -82,110 +83,119 @@ export function astroDevCssPlugin({ routesList, command }: AstroVitePluginOption // Cache CSS content by module ID to avoid re-reading const cssContentCache = new Map<string, string>(); - return [{ - name: MODULE_DEV_CSS, + return [ + { + name: MODULE_DEV_CSS, - async configureServer(...
packages/astro/src/vite-plugin-css/index.ts
26
TypeScript
0.286
question
86
51
51
false
refactor: stabilise environment names
14,961
withastro/astro
47,179
TypeScript
matthewp
ematipico
// possible extensions for markdown files export const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [ '.markdown', '.mdown', '.mkdn', '.mkd', '.mdwn', '.md', ] as const; // The folder name where to find the middleware export const MIDDLEWARE_PATH_SEGMENT_NAME = 'middleware'; // The environments used inside Astro expor...
We can do this in another PR, but wanted to note that I'm not sure we actually use this environment for anything. The comment says it's used for cloudflare, but how exactly is it used?
// possible extensions for markdown files export const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [ '.markdown', '.mdown', '.mkdn', '.mkd', '.mdwn', '.md', ] as const; // The folder name where to find the middleware export const MIDDLEWARE_PATH_SEGMENT_NAME = 'middleware'; // The environments used inside Astro expor...
@@ -107,9 +107,16 @@ export const MIDDLEWARE_PATH_SEGMENT_NAME = 'middleware'; // The environments used inside Astro export const ASTRO_VITE_ENVIRONMENT_NAMES = { + // It maps to the classic `ssr` Vite environment server: 'ssr', + // It maps to the classic `client` Vite environment client: 'client', + // Enviro...
packages/astro/src/core/constants.ts
26
TypeScript
0.429
question
185
32
35
false
refactor: stabilise environment names
14,961
withastro/astro
47,179
TypeScript
matthewp
ematipico
import type * as vite from 'vite'; export const NOOP_MODULE_ID = 'virtual:astro:noop'; const RESOLVED_NOOP_MODULE_ID = '\0' + NOOP_MODULE_ID; // An empty module that does nothing. This can be used as a placeholder // when you just need a module to be in the graph. // We use this for the client build when there are no...
If this is confusing just read the code below this, the chunk gets deleted at the end.
import type * as vite from 'vite'; export const NOOP_MODULE_ID = 'virtual:astro:noop'; const RESOLVED_NOOP_MODULE_ID = '\0' + NOOP_MODULE_ID; // An empty module that does nothing. This can be used as a placeholder // when you just need a module to be in the graph. // We use this for the client build when there are no...
@@ -17,7 +17,7 @@ export function pluginNoop(): vite.Plugin { }, load(id) { if(id === RESOLVED_NOOP_MODULE_ID) { - return ''; + return 'export const noop = {};';
packages/astro/src/core/build/plugins/plugin-noop.ts
20
TypeScript
0.214
suggestion
86
34
34
false
fix: suppress empty chunk warning for noop entrypoint
14,976
withastro/astro
47,179
TypeScript
matthewp
matthewp
import { existsSync } from 'node:fs'; import type { PluginConfig } from '@cloudflare/vite-plugin'; /** * Checks whether a wrangler file exists at the given path * @param root */ export function hasWranglerConfig(root: URL) { return ( existsSync(new URL('wrangler.jsonc', root)) || existsSync(new URL('wrangler.t...
I think we should leave this todo
import { existsSync } from 'node:fs'; import type { PluginConfig } from '@cloudflare/vite-plugin'; /** * Checks whether a wrangler file exists at the given path * @param root */ export function hasWranglerConfig(root: URL) { return ( existsSync(new URL('wrangler.jsonc', root)) || existsSync(new URL('wrangler.t...
@@ -13,13 +14,12 @@ export function hasWranglerConfig(root: URL) { } /** - * Creates a minimal wrangler.json file + * Returns the default wrangler configuration used by Astro Cloudflare configuration. */ -export function wranglerTemplate(): string { - const wrangler = { - // TODO: better way to handle name, mayb...
packages/integrations/cloudflare/src/wrangler.ts
20
TypeScript
0.143
suggestion
33
39
40
false
feat(cloudflare): inline config injection
14,984
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import { existsSync } from 'node:fs'; import type { PluginConfig } from '@cloudflare/vite-plugin'; /** * Checks whether a wrangler file exists at the given path * @param root */ export function hasWranglerConfig(root: URL) { return ( existsSync(new URL('wrangler.jsonc', root)) || existsSync(new URL('wrangler.t...
```suggestion compatibility_date: new Date().toISOString().slice(0, 10), ```
import { existsSync } from 'node:fs'; import type { PluginConfig } from '@cloudflare/vite-plugin'; /** * Checks whether a wrangler file exists at the given path * @param root */ export function hasWranglerConfig(root: URL) { return ( existsSync(new URL('wrangler.jsonc', root)) || existsSync(new URL('wrangler.t...
@@ -13,13 +14,12 @@ export function hasWranglerConfig(root: URL) { } /** - * Creates a minimal wrangler.json file + * Returns the default wrangler configuration used by Astro Cloudflare configuration. */ -export function wranglerTemplate(): string { - const wrangler = { - // TODO: better way to handle name, mayb...
packages/integrations/cloudflare/src/wrangler.ts
22
TypeScript
0.571
suggestion
78
39
40
false
feat(cloudflare): inline config injection
14,984
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import { existsSync } from 'node:fs'; import type { PluginConfig } from '@cloudflare/vite-plugin'; /** * Checks whether a wrangler file exists at the given path * @param root */ export function hasWranglerConfig(root: URL) { return ( existsSync(new URL('wrangler.jsonc', root)) || existsSync(new URL('wrangler.t...
What's the reason for this? I assume `compatibility_date` means that we want compatibility as of a specific date. So any time we update the plugin we could bump this. But just always setting it to the current date would mean that if they make a breaking API change we are saying that we support that, even though we don'...
import { existsSync } from 'node:fs'; import type { PluginConfig } from '@cloudflare/vite-plugin'; /** * Checks whether a wrangler file exists at the given path * @param root */ export function hasWranglerConfig(root: URL) { return ( existsSync(new URL('wrangler.jsonc', root)) || existsSync(new URL('wrangler.t...
@@ -13,13 +14,12 @@ export function hasWranglerConfig(root: URL) { } /** - * Creates a minimal wrangler.json file + * Returns the default wrangler configuration used by Astro Cloudflare configuration. */ -export function wranglerTemplate(): string { - const wrangler = { - // TODO: better way to handle name, mayb...
packages/integrations/cloudflare/src/wrangler.ts
22
TypeScript
0.643
bug
392
39
40
false
feat(cloudflare): inline config injection
14,984
withastro/astro
47,179
TypeScript
matthewp
ematipico
}, resolveId(source, importer) { if (importer) { // Do propagation any time a new module is imported. This is because // A module with propagation might be loaded before one of its parent pages // is loaded, in which case that parent page won't have the in-tree and containsHead // values. Walking...
The `transform` is still needed, unless I misunderstood the TODO. Without it, some tests fail
}, resolveId(source, importer) { if (importer) { // Do propagation any time a new module is imported. This is because // A module with propagation might be loaded before one of its parent pages // is loaded, in which case that parent page won't have the in-tree and containsHead // values. Walking...
@@ -74,7 +74,6 @@ export default function configHeadVitePlugin(): vite.Plugin { } }, transform(source, id) { - // TODO This could probably be removed now that this is handled in resolveId
packages/astro/src/vite-plugin-head/index.ts
26
TypeScript
0.357
bug
93
51
51
false
chore: address some TODO
14,986
withastro/astro
47,179
TypeScript
ematipico
ematipico
* "img-src 'self' https://images.cdn.example.com" * ] * } * } * }); * ``` * After the build, the `<meta>` element will add your directives into the `content` value alongside Astro's default directives: * * ```html * <meta * http-equ...
Looking at the failing tests, I think this is because the [library used in docgen](https://github.com/jsdoc2md/jsdoc-api) to validate the JSDoc doesn't handle Typescript optional properties. This wasn't failing before because `docgen` wasn't run. We could replace `?:` with `:`: ```suggestion * @type {{ has...
* csp: { * directives: [ * "default-src 'self'", * "img-src 'self' https://images.cdn.example.com" * ] * } * } * }); * ``` * After the build, the `<meta>` element will add your directives into the `content` value alongside...
@@ -785,6 +787,7 @@ export interface AstroUserConfig< directives?: CspDirective[]; /** + * @docs * @name security.csp.styleDirective * @type {{ hashes?: CspHash[], resources?: string[] }}
packages/astro/src/types/public/config.ts
26
TypeScript
1
bug
534
51
51
false
Update v6 config reference JSDoc for CSP entries
15,011
withastro/astro
47,179
TypeScript
ArmandPhilippot
sarah11918
* } * }); * ``` * * After the build, the `<meta>` element will instead apply your sources to the `style-src` directives: * * ```html * <head> * <meta * http-equiv="content-security-policy" * content=" * style-src 'self'...
Same here: ```suggestion * @type {{ hashes: CspHash[], resources: string[], strictDynamic: boolean }} ```
* ] * } * } * } * }); * ``` * * After the build, the `<meta>` element will instead apply your sources to the `style-src` directives: * * ```html * <head> * <meta * http-equiv="content-security-policy" ...
@@ -880,6 +885,7 @@ export interface AstroUserConfig< }; /** + * @docs * @name security.csp.scriptDirective * @type {{ hashes?: CspHash[], resources?: string[], strictDynamic?: boolean }}
packages/astro/src/types/public/config.ts
26
TypeScript
0.857
suggestion
112
51
51
false
Update v6 config reference JSDoc for CSP entries
15,011
withastro/astro
47,179
TypeScript
ArmandPhilippot
sarah11918
* Individual drivers may also support a `ttl` option that will automatically delete sessions after the specified time. See your chosen driver's documentation for more information. * ::: */ /** * @docs * @kind heading * @name Dev Toolbar Options */ devToolbar?: { /** * @docs * @name devToolbar.e...
```suggestion * @name devToolbar.placement * @version 5.17.0 ```
* * Individual drivers may also support a `ttl` option that will automatically delete sessions after the specified time. See your chosen driver's documentation for more information. * ::: */ /** * @docs * @kind heading * @name Dev Toolbar Options */ devToolbar?: { /** * @docs * @name devToolb...
@@ -1170,6 +1170,18 @@ export interface AstroUserConfig< * This option is scoped to the entire project, to only disable the toolbar for yourself, run `npm run astro preferences disable devToolbar`. To disable the toolbar for all your Astro projects, run `npm run astro preferences disable devToolbar --global`. *...
packages/astro/src/types/public/config.ts
26
TypeScript
0.571
suggestion
73
51
51
false
Add `devToolbar.placement` configuration option
15,015
withastro/astro
47,179
TypeScript
sarah11918
tony
* @docs * @kind heading * @name Dev Toolbar Options */ devToolbar?: { /** * @docs * @name devToolbar.enabled * @type {boolean} * @default `true` * @description * Whether to enable the Astro Dev Toolbar. This toolbar allows you to inspect your page islands, see helpful audits on performance ...
```suggestion * The placement of the toolbar can still be changed via the toolbar settings UI. Once changed, the user's preference is saved in `localStorage` and overrides this configuration value. ```
/** * @docs * @kind heading * @name Dev Toolbar Options */ devToolbar?: { /** * @docs * @name devToolbar.enabled * @type {boolean} * @default `true` * @description * Whether to enable the Astro Dev Toolbar. This toolbar allows you to inspect your page islands, see helpful audits on perform...
@@ -1170,6 +1170,18 @@ export interface AstroUserConfig< * This option is scoped to the entire project, to only disable the toolbar for yourself, run `npm run astro preferences disable devToolbar`. To disable the toolbar for all your Astro projects, run `npm run astro preferences disable devToolbar --global`. *...
packages/astro/src/types/public/config.ts
26
TypeScript
0.857
suggestion
206
51
51
false
Add `devToolbar.placement` configuration option
15,015
withastro/astro
47,179
TypeScript
sarah11918
tony
); } if (!render) { render = await entryType.getRenderFunction(config); // Cache the render function for this content type, so it can re-use parsers and other expensive setup renderFunctionByContentType.set(entryType, render); } let rendered: RenderedContent | undefined = un...
what is `rendered` here and why would its existence affect where the body is retained or no? Shouldn't `retainBody` be the sole decider here?
); } if (!render) { render = await entryType.getRenderFunction(config); // Cache the render function for this content type, so it can re-use parsers and other expensive setup renderFunctionByContentType.set(entryType, render); } let rendered: RenderedContent | undefined = un...
@@ -201,7 +207,7 @@ export function glob(globOptions: GlobOptions): Loader { store.set({ id, data: parsedData, - body, + body: globOptions.retainBody === false && rendered ? undefined : body,
packages/astro/src/content/loaders/glob.ts
26
TypeScript
0.571
question
141
51
51
false
feat: add `retainBody` option to the `glob()` loader
15,022
withastro/astro
47,179
TypeScript
matthewp
ascorbic
if (isServerEnvironment && _options.optimizeDeps?.noDiscovery === false) { return { optimizeDeps: { include: [ 'astro', 'astro/runtime/**', 'astro > html-escaper', 'astro > mrmime', 'astro > zod/v4', ...
Does this support regexes? If so we could exclude all imports that start with `virtual:`
configEnvironment(environmentName, _options) { const isServerEnvironment = ['ssr', 'prerender'].includes(environmentName); if (isServerEnvironment && _options.optimizeDeps?.noDiscovery === false) { return { optimizeDeps: { include: [ 'astro', ...
@@ -245,14 +245,27 @@ export default function createIntegration(args?: Options): AstroIntegration { 'astro > es-module-lexer', 'astro > unstorage', 'astro > neotraverse/modern', + 'astro/app', + 'astro/compiler-runtime', ], excl...
packages/integrations/cloudflare/src/index.ts
26
TypeScript
0.429
question
88
51
51
false
Add more optimizeDeps for Cloudflare prebundling
15,026
withastro/astro
47,179
TypeScript
florian-lefebvre
matthewp
debugInfo: await this.getDebugInfo(), }; // Additional data for the dev overlay const children = `window.__astro_dev_toolbar__ = ${JSON.stringify(additionalMetadata)}`; scripts.add({ props: {}, children }); } } // TODO: We should allow adding generic HTML elements to the head, not ...
Why this change? I don't think we want to do this. This makes it so that every route's CSS is calculated vs. just the route that's being requested.
const children = `window.__astro_dev_toolbar__ = ${JSON.stringify(additionalMetadata)}`; scripts.add({ props: {}, children }); } } // TODO: We should allow adding generic HTML elements to the head, not just scripts for (const script of settings.scripts) { if (script.stage === 'head-inline') ...
@@ -126,7 +130,19 @@ export class AstroServerPipeline extends Pipeline { } } - const { css } = await loader.import(getDevCSSModuleName(routeData.component)); + const { devCSSMap } = await import('virtual:astro:dev-css-all');
packages/astro/src/vite-plugin-app/pipeline.ts
26
TypeScript
0.429
question
147
51
51
false
fix(cloudflare): experimental chromeDevtoolsWorkspace
15,030
withastro/astro
47,179
TypeScript
matthewp
ematipico
export default { preprocess: vitePreprocess(), }\n`, LIT_NPMRC: `\ # Lit libraries are required to be hoisted due to dependency issues. public-hoist-pattern[]=*lit* `, DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ impor...
I think here it makes sense to keep the dynamic generation: > When you start your project, you should always set compatibility_date to the current date. https://developers.cloudflare.com/workers/configuration/compatibility-dates/
export default { preprocess: vitePreprocess(), }\n`, LIT_NPMRC: `\ # Lit libraries are required to be hoisted due to dependency issues. public-hoist-pattern[]=*lit* `, DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ impor...
@@ -83,20 +83,16 @@ export default async function seed() { `, CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\ { - "main": "dist/_worker.js/index.js", + "compatibility_date": "2025-05-21",
packages/astro/src/cli/add/index.ts
26
TypeScript
0.5
suggestion
235
51
51
false
Update wrangler config template in astro add
15,047
withastro/astro
47,179
TypeScript
florian-lefebvre
matthewp
export default { preprocess: vitePreprocess(), }\n`, LIT_NPMRC: `\ # Lit libraries are required to be hoisted due to dependency issues. public-hoist-pattern[]=*lit* `, DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ impor...
We could export a util from `@cloudflare/vite-plugin` to get the latest `compatibility_date` supported by the installed version. You could then use that to provide the value here. Would that be helpful? In the meantime, it would be good to use a more recent compatibility date.
export default { preprocess: vitePreprocess(), }\n`, LIT_NPMRC: `\ # Lit libraries are required to be hoisted due to dependency issues. public-hoist-pattern[]=*lit* `, DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ impor...
@@ -83,20 +83,16 @@ export default async function seed() { `, CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\ { - "main": "dist/_worker.js/index.js", + "compatibility_date": "2025-05-21",
packages/astro/src/cli/add/index.ts
26
TypeScript
0.643
suggestion
280
51
51
false
Update wrangler config template in astro add
15,047
withastro/astro
47,179
TypeScript
jamesopstad
matthewp
DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ import { db } from 'astro:db'; // https://astro.build/db/seed export default async function seed() { // TODO } `, CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\ { "compa...
Is this `assets` config necessary? `assets.directory` is set by the Cloudflare plugin at build time so doesn't do anything here. `assets.binding` is only necessary if the user is using the binding (unless Astro uses it internally?).
DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ import { db } from 'astro:db'; // https://astro.build/db/seed export default async function seed() { // TODO } `, CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\ { "compa...
@@ -83,20 +83,16 @@ export default async function seed() { `, CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\ { - "main": "dist/_worker.js/index.js", + "compatibility_date": "2025-05-21", "name": ${JSON.stringify(name)}, - "compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0, 10))}, - "compa...
packages/astro/src/cli/add/index.ts
26
TypeScript
0.643
question
232
51
51
false
Update wrangler config template in astro add
15,047
withastro/astro
47,179
TypeScript
jamesopstad
matthewp
public-hoist-pattern[]=*lit* `, DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ import { db } from 'astro:db'; // https://astro.build/db/seed export default async function seed() { // TODO } `, CLOUDFLARE_WRANGLER_CONFIG...
Are you setting `global_fetch_strictly_public` internally in the programmatic config? It's the right default for Astro because the Worker is the origin.
public-hoist-pattern[]=*lit* `, DB_CONFIG: `\ import { defineDb } from 'astro:db'; // https://astro.build/db/config export default defineDb({ tables: {} }); `, DB_SEED: `\ import { db } from 'astro:db'; // https://astro.build/db/seed export default async function seed() { // TODO } `, CLOUDFLARE_WRANGLER_CONFIG...
@@ -83,20 +83,16 @@ export default async function seed() { `, CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\ { - "main": "dist/_worker.js/index.js", + "compatibility_date": "2025-05-21", "name": ${JSON.stringify(name)}, - "compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0, 10))}, - "compa...
packages/astro/src/cli/add/index.ts
26
TypeScript
0.571
suggestion
152
51
51
false
Update wrangler config template in astro add
15,047
withastro/astro
47,179
TypeScript
jamesopstad
matthewp
languagePlugins, services, tsconfigPath, includeProjectReference, ({ project }) => { const { languageServiceHost } = project.typescript!; const astroInstall = getAstroInstall([this.workspacePath]); addAstroTypes( typeof astroInstall === 'string' ? undefined : astroInstall, ...
```suggestion // Required to avoid tinyglobby running eternally expandDirectories: false, ``` Update the comment as you see fit, but just an explanation of the option would be great!
languagePlugins, services, tsconfigPath, includeProjectReference, ({ project }) => { const { languageServiceHost } = project.typescript!; const astroInstall = getAstroInstall([this.workspacePath]); addAstroTypes( typeof astroInstall === 'string' ? undefined : astroInstall, ...
@@ -166,10 +166,11 @@ export class AstroCheck { languagePlugins, services, () => { - return fg.sync('**/*.astro', { + return globSync('**/*.astro', { cwd: this.workspacePath, ignore: ['node_modules'], absolute: true, + expandDirectories: false,
packages/language-tools/language-server/src/check.ts
26
TypeScript
0.786
suggestion
198
51
51
false
chore: Replace fast-glob with tinyglobby in language server
15,057
withastro/astro
47,179
TypeScript
Princesseuh
fabon-f
import { env as globalEnv } from 'cloudflare:workers'; import { sessionKVBindingName } from 'virtual:astro-cloudflare:config'; import type { Response as CfResponse, ExecutionContext, ExportedHandlerFetchHandler, } from '@cloudflare/workers-types'; import { createApp } from 'astro/app/entrypoint'; import { setGetEnv ...
I'd remove `runtime` from the types entirely, so users don't get autocomplete
import { env as globalEnv } from 'cloudflare:workers'; import { sessionKVBindingName } from 'virtual:astro-cloudflare:config'; import type { Response as CfResponse, ExecutionContext, ExportedHandlerFetchHandler, } from '@cloudflare/workers-types'; import { createApp } from 'astro/app/entrypoint'; import { setGetEnv ...
@@ -18,6 +18,12 @@ setGetEnv(createGetEnv(globalEnv as Env)); export interface Runtime { cfContext: ExecutionContext; + runtime: { + get env(): never; + get cf(): never; + get caches(): never; + get ctx(): never; + };
packages/integrations/cloudflare/src/utils/handler.ts
26
TypeScript
0.571
suggestion
77
51
51
false
Add deprecation getters for Astro.locals.runtime
15,075
withastro/astro
47,179
TypeScript
ascorbic
matthewp
if (env[sessionKVBindingName]) { const sessionConfigOptions = app.manifest.sessionConfig?.options ?? {}; Object.assign(sessionConfigOptions, { binding: env[sessionKVBindingName], }); } // static assets fallback, in case default _routes.json is not used if (app.manifest.assets.has(pathname)) { return env...
How about using `Object.defineProperty` with `enumerable: false` to define `runtime`, so it doesn't show up on the objects
// static assets fallback, in case default _routes.json is not used if (app.manifest.assets.has(pathname)) { return env.ASSETS.fetch(request.url.replace(/\.html$/, '')); } const routeData = app.match(request as Request & Parameters<ExportedHandlerFetchHandler>[0]); if (!routeData) { // https://developers.clo...
@@ -58,6 +64,28 @@ export async function handle( const locals: Runtime = { cfContext: context, + runtime: {
packages/integrations/cloudflare/src/utils/handler.ts
26
TypeScript
0.5
suggestion
122
51
51
false
Add deprecation getters for Astro.locals.runtime
15,075
withastro/astro
47,179
TypeScript
ascorbic
matthewp
await page.click('#link3'); await page.waitForURL('**/partial-swap?v=3'); expect(consoleErrors.join(', '), 'There should only be two executions').toEqual( 'head script, body script', ); }); test('page-load event waits for inlined module scripts', async ({ page, astro }) => { let lines = []; page.on('c...
Would it make sense to do `test.skip` on line 1724 with a comment instead? Since it will never run and stay as documentation basically
await page.click('#link3'); await page.waitForURL('**/partial-swap?v=3'); expect(consoleErrors.join(', '), 'There should only be two executions').toEqual( 'head script, body script', ); }); test('page-load event waits for inlined module scripts', async ({ page, astro }) => { let lines = []; page.on('c...
@@ -1722,7 +1722,7 @@ test.describe('View Transitions', () => { }); test('fallback triggers animation if not skipped', async ({ page, astro, browserName }) => { - test.skip(browserName !== 'firefox', 'Only makes sense for browser that uses fallback'); + test.skip(browserName !== 'some-browser-that-does-not-supp...
packages/astro/e2e/view-transitions.test.js
26
JavaScript
0.571
question
134
51
51
false
view transitions: fix Firefox e2e tests for playwright 1.57
15,113
withastro/astro
47,179
TypeScript
florian-lefebvre
martrapp
await next.promise; } // Only create a new promise if rendering is still ongoing. Otherwise // there will be a dangling promises that breaks tests (probably not an actual app) if (!renderingComplete) { next = promiseWithResolvers(); } // If an error occurs during rendering, throw the error a...
I guess this is the bulk of the improvement right? If so a comment here explaining why this seemingly more complicated code is actually good/necessary would help prevent accidental regressions from those who think they are simplifying code. Thanks!
await next.promise; } // Only create a new promise if rendering is still ongoing. Otherwise // there will be a dangling promises that breaks tests (probably not an actual app) if (!renderingComplete) { next = promiseWithResolvers(); } // If an error occurs during rendering, throw the error a...
@@ -259,16 +265,35 @@ export async function renderToAsyncIterable( // Get the total length of all arrays. let length = 0; + let stringToEncode = ''; for (let i = 0, len = buffer.length; i < len; i++) { - length += buffer[i].length; + const bufferEntry = buffer[i]; + + if (typeof bufferEntry ===...
packages/astro/src/runtime/server/render/astro/render.ts
26
TypeScript
0.5
refactor
248
51
51
false
perf(astro): group chunks on emit
15,123
withastro/astro
47,179
TypeScript
matthewp
43081j
} // If an error occurs during rendering, throw the error as we cannot proceed. if (error) { throw error; } // Get the total length of all arrays. let length = 0; for (let i = 0, len = buffer.length; i < len; i++) { length += buffer[i].length; } // Create a new array with total len...
Rather than checking if next is string, why don't we just store a separate array for string values and just check that in general? This would simplify this implementation and we don't have to store string | buffer in this array.
} // Only create a new promise if rendering is still ongoing. Otherwise // there will be a dangling promises that breaks tests (probably not an actual app) if (!renderingComplete) { next = promiseWithResolvers(); } // If an error occurs during rendering, throw the error as we cannot proceed. ...
@@ -257,18 +263,47 @@ export async function renderToAsyncIterable( throw error; } - // Get the total length of all arrays. + // This calculates the length of the final merged array. + // While doing so, it also replaces consecutive strings with their + // concatenated Uint8Array equivalent. + // Th...
packages/astro/src/runtime/server/render/astro/render.ts
26
TypeScript
0.5
refactor
228
51
51
false
perf(astro): group chunks on emit
15,123
withastro/astro
47,179
TypeScript
anonrig
43081j
value: mergedArray, }; return returnValue; }, async return() { // If the client disconnects, // we signal to the rest of the internals to ignore the results of existing renders and avoid kicking off more of them. result.cancelled = true; return { done: true, value: undefined }; }, }; con...
We can also construct this offset in the previous for loop, can't we ?
length += encoded.length; stringToEncode = ''; buffer[i] = encoded; } else { buffer[i] = ''; } } else { length += bufferEntry.length; } } // Create a new array with total length and merge all source arrays. let mergedArray = new Uint8Array(length); let offset ...
@@ -257,18 +263,47 @@ export async function renderToAsyncIterable( throw error; } - // Get the total length of all arrays. + // This calculates the length of the final merged array. + // While doing so, it also replaces consecutive strings with their + // concatenated Uint8Array equivalent. + // Th...
packages/astro/src/runtime/server/render/astro/render.ts
26
TypeScript
0.214
question
70
51
51
false
perf(astro): group chunks on emit
15,123
withastro/astro
47,179
TypeScript
anonrig
43081j
import type { SSRResult } from '../../../types/public/internal.js'; import type { HTMLBytes, HTMLString } from '../escape.js'; import { markHTMLString } from '../escape.js'; import { determineIfNeedsHydrationScript, determinesIfNeedsDirectiveScript, getPrescripts, } from '../scripts.js'; import { renderAllHeadConten...
stringifyChunk already returns string, toString() seems redundant
} else { return stringifyChunk(result, chunk); } } export function chunkToByteArray( result: SSRResult, chunk: Exclude<RenderDestinationChunk, Response>, ): Uint8Array { if (ArrayBuffer.isView(chunk)) { return chunk as Uint8Array; } else { // `stringifyChunk` might return a HTMLString, call `.toString()` t...
@@ -145,6 +145,17 @@ export function chunkToByteArray( } } +export function chunkToByteArrayOrString( + result: SSRResult, + chunk: Exclude<RenderDestinationChunk, Response>, +): Uint8Array | string { + if (ArrayBuffer.isView(chunk)) { + return chunk as Uint8Array; + } else { + return stringifyChunk(result, chun...
packages/astro/src/runtime/server/render/common.ts
26
TypeScript
0.214
suggestion
65
151
33
false
perf(astro): group chunks on emit
15,123
withastro/astro
47,179
TypeScript
anonrig
43081j
import colors from 'piccolore'; import type * as vite from 'vite'; import type { Logger } from '../core/logger/core.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../template/4xx.js'; import type { AstroSettings } from '../types/astro.js'; import { writeHtmlResponse } from './response.js'; export funct...
Instead of a try/catch, could it be possible to have the previous code but with `config.base || '/'`
import colors from 'piccolore'; import type * as vite from 'vite'; import type { Logger } from '../core/logger/core.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../template/4xx.js'; import type { AstroSettings } from '../types/astro.js'; import { writeHtmlResponse } from './response.js'; export funct...
@@ -13,10 +13,20 @@ export function baseMiddleware( logger: Logger, ): vite.Connect.NextHandleFunction { const { config } = settings; - const site = config.site ? new URL(config.base, config.site) : undefined; - const devRootURL = new URL(config.base, 'http://localhost'); - const devRoot = site ? site.pathname : d...
packages/astro/src/vite-plugin-astro-server/base.ts
26
TypeScript
0.571
suggestion
100
51
51
false
fix(dev): preserve query params when base path is stripped
15,124
withastro/astro
47,179
TypeScript
florian-lefebvre
eureka928
import * as fs from 'node:fs'; import path from 'node:path'; import { appendForwardSlash } from '@astrojs/internal-helpers/path'; import colors from 'piccolore'; import type * as vite from 'vite'; import type { Logger } from '../core/logger/core.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../template...
```suggestion // The base may be an empty string by now, causing the URL creation to fail. We provide a default instead const base = config.base || '/'; ```
import * as fs from 'node:fs'; import path from 'node:path'; import { appendForwardSlash } from '@astrojs/internal-helpers/path'; import colors from 'piccolore'; import type * as vite from 'vite'; import type { Logger } from '../core/logger/core.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../template...
@@ -13,8 +13,9 @@ export function baseMiddleware( logger: Logger, ): vite.Connect.NextHandleFunction { const { config } = settings; - const site = config.site ? new URL(config.base, config.site) : undefined; - const devRootURL = new URL(config.base, 'http://localhost'); + const base = config.base || '/';
packages/astro/src/vite-plugin-astro-server/base.ts
17
TypeScript
0.786
bug
161
42
42
false
fix(dev): preserve query params when base path is stripped
15,124
withastro/astro
47,179
TypeScript
florian-lefebvre
eureka928
/** * Astro global available in all contexts in .astro files * * [Astro reference](https://docs.astro.build/en/reference/api-reference/) */ export interface AstroGlobal< Props extends Record<string, any> = Record<string, any>, Self = AstroComponentFactory, Params extends Record<string, string | undefined> = Reco...
These 2 properties are removed on main, I must have messed up the last `main > next` merge
/** * Astro global available in all contexts in .astro files * * [Astro reference](https://docs.astro.build/en/reference/api-reference/) */ export interface AstroGlobal< Props extends Record<string, any> = Record<string, any>, Self = AstroComponentFactory, Params extends Record<string, string | undefined> = Reco...
@@ -15,23 +15,7 @@ export interface AstroGlobal< Props extends Record<string, any> = Record<string, any>, Self = AstroComponentFactory, Params extends Record<string, string | undefined> = Record<string, string | undefined>, -> extends AstroSharedContext<Props, Params> { - /** - * Returns a [URL](https://develope...
packages/astro/src/types/public/context.ts
26
TypeScript
0.429
suggestion
90
51
51
false
chore: remove useless type
15,129
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
const slotString = Symbol.for('astro:slot-string'); export class SlotString extends HTMLString { public instructions: null | RenderInstruction[]; public [slotString]: boolean; constructor(content: string, instructions: null | RenderInstruction[]) { super(content); this.instructions = instructions; this[slotS...
An empty array is truthy (`!![] => true`), which would create a new array without any real need. ```suggestion if (source.instructions?.length) { ```
const slotString = Symbol.for('astro:slot-string'); export class SlotString extends HTMLString { public instructions: null | RenderInstruction[]; public [slotString]: boolean; constructor(content: string, instructions: null | RenderInstruction[]) { super(content); this.instructions = instructions; this[slotS...
@@ -27,6 +27,21 @@ export function isSlotString(str: string): str is any { return !!(str as any)[slotString]; } +/** + * Collects instructions from a SlotString into the target array. + * Returns the (possibly newly created) instructions array. + */ +export function mergeSlotInstructions( + target: RenderInstructi...
packages/astro/src/runtime/server/render/slot.ts
26
TypeScript
0.714
suggestion
152
51
51
false
Fix hydration for framework components in MDX slots
15,150
withastro/astro
47,179
TypeScript
Fryuni
matthewp
export interface LocalImageService<T extends Record<string, any> = Record<string, any>> extends SharedServiceProps<T> { /** * Parse the requested parameters passed in the URL from `getURL` back into an object to be used later by `transform`. * * In most cases, this will get query parameters using, for example,...
I see that this bit of documentation was outdated. I'm going at update it with all the properties that should have been reflected here as well.
export interface LocalImageService<T extends Record<string, any> = Record<string, any>> extends SharedServiceProps<T> { /** * Parse the requested parameters passed in the URL from `getURL` back into an object to be used later by `transform`. * * In most cases, this will get query parameters using, for example, ...
@@ -111,7 +112,7 @@ export interface LocalImageService<T extends Record<string, any> = Record<string /** * A list of properties that should be used to generate the hash for the image. * - * Generally, this should be all the properties that can change the result of the image. By default, this is `src`, `width`,...
packages/astro/src/assets/services/service.ts
26
TypeScript
0.429
suggestion
143
51
51
false
adds ImageTransform.background
15,153
withastro/astro
47,179
TypeScript
jcayzac
jcayzac
const sharpService: LocalImageService<SharpImageServiceConfig> = { validateOptions: baseService.validateOptions, getURL: baseService.getURL, parseURL: baseService.parseURL, getHTMLAttributes: baseService.getHTMLAttributes, getSrcSet: baseService.getSrcSet, async transform(inputBuffer, transformOptions, config) { ...
This property is also relevant for when you crop an image isn't it? I assume it should be passed there as well
const sharpService: LocalImageService<SharpImageServiceConfig> = { validateOptions: baseService.validateOptions, getURL: baseService.getURL, parseURL: baseService.parseURL, getHTMLAttributes: baseService.getHTMLAttributes, getSrcSet: baseService.getSrcSet, async transform(inputBuffer, transformOptions, config) { ...
@@ -71,6 +71,11 @@ const sharpService: LocalImageService<SharpImageServiceConfig> = { // always call rotate to adjust for EXIF data orientation result.rotate(); + // if background is set, flatten the image with the specified background + if (transform.background) { + result.flatten({ background: transform.b...
packages/astro/src/assets/services/sharp.ts
26
TypeScript
0.429
suggestion
110
51
51
false
adds ImageTransform.background
15,153
withastro/astro
47,179
TypeScript
Princesseuh
jcayzac
const MODULE_DEV_CSS_ALL = 'virtual:astro:dev-css-all'; const RESOLVED_MODULE_DEV_CSS_ALL = '\0' + MODULE_DEV_CSS_ALL; const ASTRO_CSS_EXTENSION_POST_PATTERN = '@_@'; /** * Extract the original component path from a masked virtual module name. * Inverse function of getVirtualModulePageName(). */ function getCompone...
I think a more valuable comment is describing **why** we need to stop the propagation
interface AstroVitePluginOptions { routesList: RoutesList; command: 'dev' | 'build'; } /** * Extract the original component path from a masked virtual module name. * Inverse function of getVirtualModulePageName(). */ function getComponentFromVirtualModuleCssName(virtualModulePrefix: string, id: string): string { ...
@@ -44,6 +44,11 @@ function* collectCSSWithOrder( ): Generator<ImportedDevStyle & { id: string; idKey: string }, void, unknown> { seen.add(id); + // Stop traversing if we reach a propagation stopping point.
packages/astro/src/vite-plugin-css/index.ts
26
TypeScript
0.214
suggestion
86
51
51
false
Fix CSS collection in dev mode with content collections
15,167
withastro/astro
47,179
TypeScript
ematipico
HiDeoo
const RESOLVED_MODULE_DEV_CSS_ALL = '\0' + MODULE_DEV_CSS_ALL; const ASTRO_CSS_EXTENSION_POST_PATTERN = '@_@'; /** * Extract the original component path from a masked virtual module name. * Inverse function of getVirtualModulePageName(). */ function getComponentFromVirtualModuleCssName(virtualModulePrefix: string, ...
I think there's a constant for the query param name
routesList: RoutesList; command: 'dev' | 'build'; } /** * Extract the original component path from a masked virtual module name. * Inverse function of getVirtualModulePageName(). */ function getComponentFromVirtualModuleCssName(virtualModulePrefix: string, id: string): string { return id .slice(virtualModulePr...
@@ -44,6 +44,11 @@ function* collectCSSWithOrder( ): Generator<ImportedDevStyle & { id: string; idKey: string }, void, unknown> { seen.add(id); + // Stop traversing if we reach a propagation stopping point. + if (id.includes('?astroPropagatedAssets')) {
packages/astro/src/vite-plugin-css/index.ts
26
TypeScript
0.214
suggestion
51
51
51
false
Fix CSS collection in dev mode with content collections
15,167
withastro/astro
47,179
TypeScript
florian-lefebvre
HiDeoo
*/ service?: ImageServiceConfig; /** * @docs * @name image.service.config.limitInputPixels * @kind h4 * @type {number | boolean} * @default `true` * @version 4.1.0 * @description * * Whether or not to limit the size of images that the Sharp image service will process. * * Set `fa...
```suggestion * The default [kernel used for resizing images](https://sharp.pixelplumbing.com/api-resize/#resize) in the Sharp image service. ``` Feels like we should give people some guidance on where to find the options available to them!
*/ service?: ImageServiceConfig; /** * @docs * @name image.service.config.limitInputPixels * @kind h4 * @type {number | boolean} * @default `true` * @version 4.1.0 * @description * * Whether or not to limit the size of images that the Sharp image service will process. * * Set `fa...
@@ -1313,6 +1313,20 @@ export interface AstroUserConfig< * Set `false` to bypass the default image size limit for the Sharp image service and process large images. */ + /** + * @docs + * @name image.service.config.kernel + * @kind h4 + * @type {string | undefined} + * @default `undefined` + * @ve...
packages/astro/src/types/public/config.ts
26
TypeScript
0.857
suggestion
246
51
51
false
feat(sharp): add kernel option to image service config
15,171
withastro/astro
47,179
TypeScript
sarah11918
mark-ignacio
/** * @docs * @name image.service.config.limitInputPixels * @kind h4 * @type {number | boolean} * @default `true` * @version 4.1.0 * @description * * Whether or not to limit the size of images that the Sharp image service will process. * * Set `false` to bypass the default image size ...
```suggestion * By default this is `undefined`, which maps to Sharp's default kernel of `lanczos3`. ``` Sharp uses inline code syntax for their kernels, so I'm guessing we should?
/** * @docs * @name image.service.config.limitInputPixels * @kind h4 * @type {number | boolean} * @default `true` * @version 4.1.0 * @description * * Whether or not to limit the size of images that the Sharp image service will process. * * Set `false` to bypass the default image size ...
@@ -1313,6 +1313,20 @@ export interface AstroUserConfig< * Set `false` to bypass the default image size limit for the Sharp image service and process large images. */ + /** + * @docs + * @name image.service.config.kernel + * @kind h4 + * @type {string | undefined} + * @default `undefined` + * @ve...
packages/astro/src/types/public/config.ts
26
TypeScript
0.929
question
185
51
51
false
feat(sharp): add kernel option to image service config
15,171
withastro/astro
47,179
TypeScript
sarah11918
mark-ignacio
function googleicons(config?: GoogleiconsOptions): FontProvider { const provider = providers.googleicons(config); let initializedProvider: InitializedProvider | undefined; return { name: provider._name, config, async init(context) { initializedProvider = await provider(context); }, async resolveFont({ f...
```suggestion * - [Google](https://fonts.google.com/) * - [Google Icons](https://fonts.google.com/icons) ``` Shouldn't we actually keep both in this comment?
function googleicons(config?: GoogleiconsOptions): FontProvider { const provider = providers.googleicons(config); let initializedProvider: InitializedProvider | undefined; return { name: provider._name, config, async init(context) { initializedProvider = await provider(context); }, async resolveFont({ f...
@@ -98,18 +99,38 @@ function google(config?: GoogleOptions): FontProvider { }; } +/** [Google Icons](https://fonts.google.com/icons) */ +function googleicons(config?: GoogleiconsOptions): FontProvider { + const provider = providers.googleicons(config); + let initializedProvider: InitializedProvider | undefined; + ...
packages/astro/src/assets/fonts/providers/index.ts
26
TypeScript
0.786
question
165
35
36
false
feat(fonts): export googleicons provider
15,174
withastro/astro
47,179
TypeScript
HiDeoo
florian-lefebvre
resolveId(id) { if (id === VIRTUAL_MODULE_ID) { return RESOLVED_VIRTUAL_MODULE_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_MODULE_ID) { return { code: ` export const internalConsumableMap = new Map(${JSON.stringify(Array.from(internalConsumableMap?.entries() ?? []))}); export...
Could we just merge both conditions?
resolveId(id) { if (id === VIRTUAL_MODULE_ID) { return RESOLVED_VIRTUAL_MODULE_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_MODULE_ID) { return { code: ` export const internalConsumableMap = new Map(${JSON.stringify(Array.from(internalConsumableMap?.entries() ?? []))}); export...
@@ -308,38 +308,44 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { } }, async buildEnd() { - if (sync || settings.config.experimental.fonts!.length === 0) { - cleanup(); - return; - } + if (sync || settings.config.experimental.fonts!.length === 0) { + cleanup(); + ...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.143
question
36
51
51
false
fix: prevent font copying when stopping dev server with q+enter
15,178
withastro/astro
47,179
TypeScript
florian-lefebvre
kedarvartak
); } }); server.middlewares.use(assetsDir, async (req, res, next) => { if (!req.url) { return next(); } const hash = req.url.slice(1); const associatedData = fontFileDataMap?.get(hash); if (!associatedData) { return next(); } // We don't want the request to be cache...
I think buffer has a `byteLength` prop which is the correct value for Content-Length.
); } }); server.middlewares.use(assetsDir, async (req, res, next) => { if (!req.url) { return next(); } const hash = req.url.slice(1); const associatedData = fontFileDataMap?.get(hash); if (!associatedData) { return next(); } // We don't want the request to be cache...
@@ -278,12 +292,12 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { // Storage should be defined at this point since initialize it called before registering // the middleware. hashToUrlMap is defined at the same time so if it's not set by now, // no url will be matched and...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.357
suggestion
85
51
51
false
feat(fonts): getFontBuffer()
15,182
withastro/astro
47,179
TypeScript
matthewp
florian-lefebvre
*/ driver: TDriver; /** * Options for the unstorage driver * @deprecated Use `import { sessionDrivers } from 'astro/config'` instead. This will be removed in Astro 7 */ options?: NoInfer<BuiltinDriverOptions[TDriver]>; } interface CustomConfig extends BaseSessionConfig { /** * Entrypoint for a custom ses...
Is it possible to keep the unstorage config as the default somehow? IIRC from my tests it was the only way to keep autocomplete for now. Maybe try to update `UnstorageConfig` driver property to be optional
/** * Entrypoint for an unstorage session driver * @deprecated Use `import { sessionDrivers } from 'astro/config'` instead. This will be removed in Astro 7 */ driver?: TDriver; /** * Options for the unstorage driver * @deprecated Use `import { sessionDrivers } from 'astro/config'` instead. This will be rem...
@@ -74,10 +74,10 @@ interface CustomConfig extends BaseSessionConfig { options?: Record<string, unknown>; } -export type SessionConfig<TDriver extends SessionDriverName | SessionDriverConfig> = [ +export type SessionConfig<TDriver extends SessionDriverName | SessionDriverConfig | undefined> = [ TDriver, ] exten...
packages/astro/src/core/session/types.ts
26
TypeScript
0.571
suggestion
205
32
35
false
Make session.driver optional in config schema
15,208
withastro/astro
47,179
TypeScript
florian-lefebvre
matthewp
}, async handler(id) { if (id === RESOLVED_MODULE_DEV_CSS) { return { code: `export const css = new Set()`, }; } if (id.startsWith(RESOLVED_MODULE_DEV_CSS_PREFIX)) { const componentPath = getComponentFromVirtualModuleCssName( RESOLVED_MODULE_DEV_CSS_PREFIX, ...
So this will never run on CF. Isn't it an issue?
load: { filter: { id: new RegExp(`^(${RESOLVED_MODULE_DEV_CSS}|${RESOLVED_MODULE_DEV_CSS_PREFIX}.*)$`), }, async handler(id) { if (id === RESOLVED_MODULE_DEV_CSS) { return { code: `export const css = new Set()`, }; } if (id.startsWith(RESOLVED_MODULE_DEV_CSS_PREFIX...
@@ -130,8 +134,10 @@ export function astroDevCssPlugin({ routesList, command }: AstroVitePluginOption const componentPageId = getVirtualModulePageNameForComponent(componentPath); // Ensure the page module is loaded. This will populate the graph and allow us to walk through. - await environment?.run...
packages/astro/src/vite-plugin-css/index.ts
26
TypeScript
0.071
question
48
51
51
false
fix(core): reload CSS
15,259
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
return [prefix, sanitizedName, suffix].join(''); } // Injected routes include "pages/[name].[ext]" already. Clean those up! if (name.startsWith('pages/')) { const sanitizedName = name.split('.')[0]; return [prefix, sanitizedName, suffix].join(''); } const encoded = enc...
```suggestion // decides to rename their virtual module, `build.serverEntry` will stop working. ```
emptyOutDir: false, copyPublicDir: false, manifest: false, rollupOptions: { ...viteConfig.build?.rollupOptions, // Setting as `exports-only` allows us to safely delete inputs that are only used during prerendering preserveEntrySignatures: 'exports-only', ...(useLegacyDynamic ? { input: 'virt...
@@ -240,7 +240,15 @@ async function buildEnvironments(opts: StaticBuildOptions, internals: BuildInter chunkInfo.facadeModuleId, routes, ); - } else if (chunkInfo.facadeModuleId === RESOLVED_SSR_VIRTUAL_MODULE_ID) { + } else if ( + chunkInfo.facadeModuleId === RESOLVED_SSR_VIRTU...
packages/astro/src/core/build/static-build.ts
26
TypeScript
0.786
suggestion
108
51
51
false
fix(build): server entry regression
15,269
withastro/astro
47,179
TypeScript
matthewp
ematipico
} // Injected routes include "pages/[name].[ext]" already. Clean those up! if (name.startsWith('pages/')) { const sanitizedName = name.split('.')[0]; return [prefix, sanitizedName, suffix].join(''); } const encoded = encodeName(name); return [prefix, encoded, suffix].jo...
Here's something to try that I think might get around the hard-coding here: 1. Add a configResolved() hook and check `rollupOptions.input`. Save that value somewhere in the scope. 2. Inside here I think you can check `chunkInfo.modules` which is an array of module names, if that contains the rollupOptions.input the...
copyPublicDir: false, manifest: false, rollupOptions: { ...viteConfig.build?.rollupOptions, // Setting as `exports-only` allows us to safely delete inputs that are only used during prerendering preserveEntrySignatures: 'exports-only', ...(useLegacyDynamic ? { input: 'virtual:astro:legacy-ssr-en...
@@ -240,7 +240,15 @@ async function buildEnvironments(opts: StaticBuildOptions, internals: BuildInter chunkInfo.facadeModuleId, routes, ); - } else if (chunkInfo.facadeModuleId === RESOLVED_SSR_VIRTUAL_MODULE_ID) { + } else if ( + chunkInfo.facadeModuleId === RESOLVED_SSR_VIRTU...
packages/astro/src/core/build/static-build.ts
26
TypeScript
0.571
suggestion
362
51
51
false
fix(build): server entry regression
15,269
withastro/astro
47,179
TypeScript
matthewp
ematipico
const cssVariablesTheme = () => _cssVariablesTheme ?? (_cssVariablesTheme = createCssVariablesTheme({ variablePrefix: '--astro-code-', })); // Caches Promise<ShikiHighlighter> for reuse when the same theme and langs are provided const cachedHighlighters = new Map(); export async function createShikiHighlighter({...
TIL you could do this to guarantee a deterministic key order!
let _cssVariablesTheme: ReturnType<typeof createCssVariablesTheme>; const cssVariablesTheme = () => _cssVariablesTheme ?? (_cssVariablesTheme = createCssVariablesTheme({ variablePrefix: '--astro-code-', })); // Caches Promise<ShikiHighlighter> for reuse when the same theme and langs are provided const cachedHigh...
@@ -77,11 +80,21 @@ export async function createShikiHighlighter({ }: CreateShikiHighlighterOptions = {}): Promise<ShikiHighlighter> { theme = theme === 'css-variables' ? cssVariablesTheme() : theme; - const highlighter = await createHighlighter({ + const highlighterOptions = { langs: ['plaintext', ...langs], ...
packages/markdown/remark/src/shiki.ts
26
TypeScript
0.286
suggestion
61
51
51
false
perf(markdown): properly cache shiki instances
15,277
withastro/astro
47,179
TypeScript
delucis
ematipico
throw formattedError; } export function pagesGlobToRssItems(items: GlobResult): Promise<ValidatedRSSFeedItem[]> { return Promise.all( Object.entries(items).map(async ([filePath, getInfo]) => { const { url, frontmatter } = await (getInfo as () => Promise<any>)(); if (url === undefined || url === null) { t...
Why is the `any` typecast needed here?
throw formattedError; } export function pagesGlobToRssItems(items: GlobResult): Promise<ValidatedRSSFeedItem[]> { return Promise.all( Object.entries(items).map(async ([filePath, getInfo]) => { const { url, frontmatter } = await getInfo(); if (url === undefined || url === null) { throw new Error( `[R...
@@ -130,26 +130,26 @@ async function validateRssOptions(rssOptions: RSSOptions) { export function pagesGlobToRssItems(items: GlobResult): Promise<ValidatedRSSFeedItem[]> { return Promise.all( Object.entries(items).map(async ([filePath, getInfo]) => { - const { url, frontmatter } = await getInfo(); + const { u...
packages/astro-rss/src/index.ts
26
TypeScript
0.357
question
38
51
51
false
Astro 6 astrojs/rss fix for Zod 4
15,283
withastro/astro
47,179
TypeScript
florian-lefebvre
eldair
[ `[RSS] Invalid or missing options:`, ...parsedResult.error.issues.map((zodError) => { const path = zodError.path.join('.'); const message = `${zodError.message} (${path})`; const code = zodError.code; if (path === 'items' && code === 'invalid_union') { return [ message, `The ...
```suggestion const { url, frontmatter } = await getInfo(); ```
[ `[RSS] Invalid or missing options:`, ...parsedResult.error.issues.map((zodError) => { const path = zodError.path.join('.'); const message = `${zodError.message} (${path})`; const code = zodError.code; if (path === 'items' && code === 'invalid_union') { return [ message, `The ...
@@ -130,26 +130,26 @@ async function validateRssOptions(rssOptions: RSSOptions) { export function pagesGlobToRssItems(items: GlobResult): Promise<ValidatedRSSFeedItem[]> { return Promise.all( Object.entries(items).map(async ([filePath, getInfo]) => { - const { url, frontmatter } = await getInfo(); + const { u...
packages/astro-rss/src/index.ts
26
TypeScript
0.571
suggestion
68
51
51
false
Astro 6 astrojs/rss fix for Zod 4
15,283
withastro/astro
47,179
TypeScript
florian-lefebvre
eldair
import fs from 'node:fs'; import os from 'node:os'; import PLimit from 'p-limit'; import PQueue from 'p-queue'; import colors from 'piccolore'; import { generateImagesForPath, getStaticImageList, prepareAssetsGenerationEnv, } from '../../assets/build/generate.js'; import { collapseDuplicateTrailingSlashes, isRelat...
I'm not sure if this should be a warning or an error, but happy either way personally.
if (route.component.includes('node_modules/')) { // For routes from node_modules (usually injected by integrations), // prettify it by only grabbing the part after the last `node_modules/` return /.*node_modules\/(.+)/.exec(route.component)?.[1] ?? route.component; } return route.component; } /** * Check if ...
@@ -634,3 +640,29 @@ function getPrettyRouteName(route: RouteData): string { } return route.component; } + +/** + * Check if a file exists in the public directory that would conflict with the output file. + * Public files take priority over generated routes. Returns true if there's a conflict. + */ +function check...
packages/astro/src/core/build/generate.ts
26
TypeScript
0.429
suggestion
86
637
34
false
Fix public files taking priority over API routes in build
15,331
withastro/astro
47,179
TypeScript
Princesseuh
matthewp
refreshContextData, }: { collectionName: string; loaderName: string; parseData: LoaderContext['parseData']; refreshContextData?: Record<string, unknown>; }): Promise<LoaderContext> { return { collection: collectionName, store: this.#store.scopedStore(collectionName), meta: this.#store.metaStore(c...
nit: create a type for the new options, to avoid maintaining the same type in two different places
refreshContextData, }: { collectionName: string; loaderName: string; parseData: LoaderContext['parseData']; refreshContextData?: Record<string, unknown>; }): Promise<LoaderContext> { return { collection: collectionName, store: this.#store.scopedStore(collectionName), meta: this.#store.metaStore(c...
@@ -140,9 +144,13 @@ class ContentLayer { }; } - async #processMarkdown(content: string): Promise<RenderedContent> { + async #processMarkdown(content: string, options?: { fileURL?: URL }): Promise<RenderedContent> {
packages/astro/src/content/content-layer.ts
26
TypeScript
0.429
nitpick
100
51
51
false
feat: add frontmatter parsing and fileURL option to renderMarkdown
15,332
withastro/astro
47,179
TypeScript
ematipico
matthewp
export const getName = () => new Promise<string>((resolve) => { exec('git config user.name', { encoding: 'utf-8' }, (_1, gitName) => { if (gitName.trim()) { return resolve(gitName.split(' ')[0].trim()); } exec('whoami', { encoding: 'utf-8' }, (_3, whoami) => { if (whoami.trim()) { return resolv...
nit ```suggestion signal: AbortSignal.timeout(10_000), ```
export const getName = () => new Promise<string>((resolve) => { exec('git config user.name', { encoding: 'utf-8' }, (_1, gitName) => { if (gitName.trim()) { return resolve(gitName.split(' ')[0].trim()); } exec('whoami', { encoding: 'utf-8' }, (_3, whoami) => { if (whoami.trim()) { return resolv...
@@ -61,9 +61,16 @@ export const getVersion = ( let registry = await getRegistry(packageManager); const { version } = await fetch(`${registry}/${packageName}/${packageTag}`, { redirect: 'follow', + signal: AbortSignal.timeout(10000),
packages/create-astro/src/messages.ts
26
TypeScript
0.571
suggestion
61
51
51
false
fix(create-astro): add timeout to npm registry fetch to prevent hanging
15,344
withastro/astro
47,179
TypeScript
vicb
matthewp
exec('whoami', { encoding: 'utf-8' }, (_3, whoami) => { if (whoami.trim()) { return resolve(whoami.split(' ')[0].trim()); } return resolve('astronaut'); }); }); }); export const getVersion = ( packageManager: string, packageName: string, packageTag = 'latest', fallback = '', ) => new Pro...
Instead of writing fallback version it'd write the version, bit similar to how context is good in errors ```suggestion `Unable to fetch latest ${packageName} version from the npm registry. Using ${fallback} instead.`, ``` (note though that fallback can be empty, not sure what that would do in the logic, though!)
exec('whoami', { encoding: 'utf-8' }, (_3, whoami) => { if (whoami.trim()) { return resolve(whoami.split(' ')[0].trim()); } return resolve('astronaut'); }); }); }); export const getVersion = ( packageManager: string, packageName: string, packageTag = 'latest', fallback = '', ) => new Pro...
@@ -61,9 +61,16 @@ export const getVersion = ( let registry = await getRegistry(packageManager); const { version } = await fetch(`${registry}/${packageName}/${packageTag}`, { redirect: 'follow', + signal: AbortSignal.timeout(10_000), }) .then((res) => res.json()) - .catch(() => ({ version: fallback...
packages/create-astro/src/messages.ts
26
TypeScript
1
suggestion
319
51
51
false
fix(create-astro): add timeout to npm registry fetch to prevent hanging
15,344
withastro/astro
47,179
TypeScript
Princesseuh
matthewp
} }, 'astro:config:done': ({ logger, config }) => { const knownJsxRenderers = ['@astrojs/react', '@astrojs/preact', '@astrojs/solid-js']; const enabledKnownJsxRenderers = config.integrations.filter((renderer) => knownJsxRenderers.includes(renderer.name), ); if (enabledKnownJsxRenderers.l...
I don't understand why we didn't add the new code **here**, which is the plugin in charge for configuring the environment.
if (command === 'dev' && devtools) { injectScript('page', 'import "preact/debug";'); } }, 'astro:config:done': ({ logger, config }) => { const knownJsxRenderers = ['@astrojs/react', '@astrojs/preact', '@astrojs/solid-js']; const enabledKnownJsxRenderers = config.integrations.filter((renderer)...
@@ -68,9 +72,7 @@ function configEnvironmentPlugin(compat: boolean | undefined): Plugin { name: '@astrojs/preact:environment', configEnvironment(environmentName, options) { const environmentOptions: EnvironmentOptions = { - optimizeDeps: { - exclude: ['@astrojs/preact/server.js'], - }, + optimize...
packages/integrations/preact/src/index.ts
26
TypeScript
0.357
suggestion
123
51
51
false
fix(preact): include server.js in SSR optimizeDeps for Cloudflare
15,383
withastro/astro
47,179
TypeScript
ematipico
matthewp
export const getContainerRenderer = (): AstroRenderer => getRenderer(false); export interface Options extends Pick<VitePreactPluginOptions, 'include' | 'exclude'> { compat?: boolean; devtools?: boolean; } export default function ({ include, exclude, compat, devtools }: Options = {}): AstroIntegration { return { ...
```suggestion // Ideally would be environment config, but // putting it there does not result in it being optimized include: ['@astrojs/preact/server.js'], ```
export const getContainerRenderer = (): AstroRenderer => getRenderer(false); export interface Options extends Pick<VitePreactPluginOptions, 'include' | 'exclude'> { compat?: boolean; devtools?: boolean; } export default function ({ include, exclude, compat, devtools }: Options = {}): AstroIntegration { return { ...
@@ -34,7 +34,11 @@ export default function ({ include, exclude, compat, devtools }: Options = {}): }, }); - const viteConfig: ViteUserConfig = {}; + const viteConfig: ViteUserConfig = { + optimizeDeps: { + include: ['@astrojs/preact/server.js'],
packages/integrations/preact/src/index.ts
26
TypeScript
0.714
performance
177
51
51
false
fix(preact): include server.js in SSR optimizeDeps for Cloudflare
15,383
withastro/astro
47,179
TypeScript
matthewp
matthewp
if (existsSync(pkgURL)) { packageJson = { type: 'exists', data: await fs.readFile(fileURLToPath(pkgURL)).then((res) => JSON.parse(res.toString())), }; return packageJson.data; } packageJson = { type: 'does-not-exist' }; return null; } switch (installResult) { case UpdateResult.updated: { ...
There is the `getPackage()` utility that could be useful I think
if (existsSync(pkgURL)) { packageJson = { type: 'exists', data: await fs.readFile(fileURLToPath(pkgURL)).then((res) => JSON.parse(res.toString())), }; return packageJson.data; } packageJson = { type: 'does-not-exist' }; return null; } switch (installResult) { case UpdateResult.updated: { ...
@@ -217,10 +218,15 @@ export async function add(names: string[], { flags }: AddOptions) { if (await askToContinue({ flags, logger })) { const data = await getPackageJson(); + const require = createRequire(root); + const { getLocalWorkerdCompatibilityDate } = await import(require.resolve('@astro...
packages/astro/src/cli/add/index.ts
26
TypeScript
0.429
refactor
64
51
51
false
in `astro add cloudflare` use cloudflare/vite-plugin's function to get latest compatibility date for wrangler.jsonc scaffolding
15,386
withastro/astro
47,179
TypeScript
florian-lefebvre
OliverSpeir
// In smoke tests, we checkout to the docs repo so those binaries are not present in this project // vsce and ovsx are only used in CI for publishing, and due to how we have to publish the VS Code extension have // to be installed in the vscode package, but knip is expecting them to be in the root node_modules...
unfortunate to turn off this whole file, if someone knows a better way
// In smoke tests, we checkout to the docs repo so those binaries are not present in this project // vsce and ovsx are only used in CI for publishing, and due to how we have to publish the VS Code extension have // to be installed in the vscode package, but knip is expecting them to be in the root node_modules...
@@ -40,6 +40,8 @@ export default { 'performance/**/*', // This export is resolved dynamically in packages/astro/src/vite-plugin-app/index.ts 'src/vite-plugin-app/createExports.ts', + // This file resolves @astrojs/cloudflare/info from the user's project at runtime + 'src/cli/add/index.ts',
knip.js
26
JavaScript
0.286
suggestion
70
51
51
false
in `astro add cloudflare` use cloudflare/vite-plugin's function to get latest compatibility date for wrangler.jsonc scaffolding
15,386
withastro/astro
47,179
TypeScript
OliverSpeir
OliverSpeir
hybridOutput: 'stable', staticOutput: 'unsupported', i18nDomains: 'experimental', sharpImageService: { support: 'limited', message: 'Cloudflare does not support sharp at runtime. However, you can configure `imageService: "compile"` to optimize images with sharp on prerender...
@matthewp I'd like to understand why not specifying a `serverEntrypoint` is fine
serverOutput: 'stable', hybridOutput: 'stable', staticOutput: 'unsupported', i18nDomains: 'experimental', sharpImageService: { support: 'limited', message: 'Cloudflare does not support sharp at runtime. However, you can configure `imageService: "compile"` to optimize ...
@@ -266,20 +243,8 @@ export default function createIntegration(args?: Options): AstroIntegration { content: '/// <reference types="@astrojs/cloudflare/types.d.ts" />', }); - let customWorkerEntryPoint: URL | undefined; - if (args?.workerEntryPoint && typeof args.workerEntryPoint.path === 'string') { ...
packages/integrations/cloudflare/src/index.ts
26
TypeScript
0.357
suggestion
80
51
51
false
chore(cloudflare): remove workerEntryPoint option
15,400
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
filter: { id: new RegExp(`^(${VIRTUAL_SERVICE_ID}|${VIRTUAL_MODULE_ID})$`), }, async handler(id) { if (id === VIRTUAL_SERVICE_ID) { if (isAstroServerEnvironment(this.environment)) { return await this.resolve(settings.config.image.service.entrypoint); } return await this.re...
```suggestion import { getConfiguredImageService as _getConfiguredImageService } from "astro/assets"; export { isLocalService } from "astro/assets"; import { getImage as getImageInternal } from "astro/assets"; ${settings.config.image.responsiveStyles ? `import "${VIRTUAL_IMAGE_STYLES_ID}";` : ''...
filter: { id: new RegExp(`^(${VIRTUAL_SERVICE_ID}|${VIRTUAL_MODULE_ID})$`), }, async handler(id) { if (id === VIRTUAL_SERVICE_ID) { if (isAstroServerEnvironment(this.environment)) { return await this.resolve(settings.config.image.service.entrypoint); } return await this.re...
@@ -155,61 +157,61 @@ export default function assets({ fs, settings, sync, logger }: Options): vite.Pl handler() { return { code: ` - import { getConfiguredImageService as _getConfiguredImageService } from "astro/assets"; - export { isLocalService } from "astro/assets"; - import { ge...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.786
suggestion
325
51
51
false
feat(csp): support responsive images
15,407
withastro/astro
47,179
TypeScript
ascorbic
ematipico
* Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset URLs (images, stylesheets, scripts, etc.). * Useful for adapters that need to track deployment versions or other me...
can you break these into separate interfaces/types for readability?
* Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset URLs (images, stylesheets, scripts, etc.). * Useful for adapters that need to track deployment versions or other me...
@@ -143,7 +133,29 @@ export interface AstroAdapter { * Configuration for Astro's client-side code. */ client?: AstroAdapterClientConfig; -} +} & ( + | {
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.357
question
67
51
51
false
feat: better adapter type
15,412
withastro/astro
47,179
TypeScript
matthewp
florian-lefebvre
import type { Context } from '@netlify/functions'; import { setGetEnv } from 'astro/env/setup'; import { middlewareSecret, cacheOnDemandPages, packageVersion } from 'virtual:astro-netlify:config'; import { createApp } from 'astro/app/entrypoint'; setGetEnv((key) => process.env[key]); const app = createApp(import.meta...
I don't know if we can trust `request.url` here, if the `Host` header is not sanitized (not sure if Netlify does this or not) then an attacker could do bad things. I think we should avoid `fetch`. I can't tell how the old code worked.
import type { Context } from '@netlify/functions'; import { setGetEnv } from 'astro/env/setup'; import { middlewareSecret, cacheOnDemandPages, packageVersion } from 'virtual:astro-netlify:config'; import { createApp } from 'astro/app/entrypoint'; setGetEnv((key) => process.env[key]); const app = createApp(); export ...
@@ -1,76 +1,76 @@ import type { Context } from '@netlify/functions'; -import type { SSRManifest } from 'astro'; -import { App } from 'astro/app'; import { setGetEnv } from 'astro/env/setup'; +import { middlewareSecret, cacheOnDemandPages, packageVersion } from 'virtual:astro-netlify:config'; +import { createApp } fro...
packages/integrations/netlify/src/ssr-function.ts
15
TypeScript
0.643
security
234
40
40
false
feat: convert netlify and vercel adapters to new API
15,413
withastro/astro
47,179
TypeScript
matthewp
florian-lefebvre
export async function dependencies( ctx: Pick< Context, 'install' | 'yes' | 'prompt' | 'packageManager' | 'cwd' | 'dryRun' | 'tasks' | 'add' >, ) { let deps = ctx.install ?? ctx.yes; if (deps === undefined) { ({ deps } = await ctx.prompt({ name: 'deps', type: 'confirm', label: title('deps'), messa...
We don't want to break 3rd party integrations being added this way. I think what we want to do is run the string through some sort of bash sanitizer.
export async function dependencies( ctx: Pick< Context, 'install' | 'yes' | 'prompt' | 'packageManager' | 'cwd' | 'dryRun' | 'tasks' | 'add' >, ) { let deps = ctx.install ?? ctx.yes; if (deps === undefined) { ({ deps } = await ctx.prompt({ name: 'deps', type: 'confirm', label: title('deps'), mess...
@@ -23,8 +23,18 @@ export async function dependencies( })); ctx.install = deps; } + ctx.add = ctx.add?.reduce<KnownLibs[]>( + (acc, item) => acc.concat(item.split(',') as KnownLibs[]), + [], + ); - ctx.add = ctx.add?.reduce<string[]>((acc, item) => acc.concat(item.split(',')), []); + if (ctx.add) { + for (...
packages/create-astro/src/actions/dependencies.ts
26
TypeScript
0.357
security
149
51
51
false
fix(create-astro): make --add stricter
15,419
withastro/astro
47,179
TypeScript
matthewp
ematipico
interface ExecaOptions { cwd?: string | URL; stdio?: StdioOptions; timeout?: number; } interface Output { stdout: string; stderr: string; exitCode: number; } const text = (stream: NodeJS.ReadableStream | Readable | null) => stream ? textFromStream(stream).then((t) => t.trimEnd()) : ''; export async function sh...
Hmm, I'd check if there isn't a Windows nonsense that could happen here. I feel like I remember some Node update requiring shell true in some contexts on Windows.
interface ExecaOptions { cwd?: string | URL; stdio?: StdioOptions; timeout?: number; } interface Output { stdout: string; stderr: string; exitCode: number; } const text = (stream: NodeJS.ReadableStream | Readable | null) => stream ? textFromStream(stream).then((t) => t.trimEnd()) : ''; export async function sh...
@@ -27,9 +27,9 @@ export async function shell( let stdout = ''; let stderr = ''; try { - child = spawn(`${command} ${flags.join(' ')}`, { + child = spawn(command, flags, { cwd: opts.cwd, - shell: true, + shell: false,
packages/create-astro/src/shell.ts
26
TypeScript
0.429
suggestion
162
45
45
false
fix(create-astro): make --add stricter
15,419
withastro/astro
47,179
TypeScript
Princesseuh
ematipico
variables: { ...configA.variables, ...configB.variables, }, partials: { ...configA.partials, ...configB.partials, }, validation: { ...configA.validation, ...configB.validation, }, }; } /** * Sync custom attributes between tags and nodes that share the same name. * In Markdoc, `table` e...
Can you just omit the type here since it will be the type of the value you're assigning
variables: { ...configA.variables, ...configB.variables, }, partials: { ...configA.partials, ...configB.partials, }, validation: { ...configA.validation, ...configB.validation, }, }; } /** * Sync custom attributes between tags and nodes that share the same name. * In Markdoc, `table` e...
@@ -98,6 +100,45 @@ export function mergeConfig( }; } +/** + * Sync custom attributes between tags and nodes that share the same name. + * In Markdoc, `table` exists as both a tag (`{% table %}`) and a node (the inner + * table structure). Attributes on the tag propagate to the child node in the AST, + * so both s...
packages/integrations/markdoc/src/runtime.ts
26
TypeScript
0.357
suggestion
88
51
51
false
fix(markdoc): resolve custom attributes on built-in table tag
15,457
withastro/astro
47,179
TypeScript
matthewp
AhmadYasser1
*/ staticHeaders?: boolean; } /** * @internal * Configuration for Astro's client-side code from adapters. * This is used internally to inject adapter-specific behavior into client code. */ export interface AstroAdapterClientConfig { /** * Headers to inject into Astro's internal fetch calls (Actions, View Tra...
```suggestion * - `'auto'`: The adapter defines its own entrypoint and provides either serverEntrypoint or rollupOptions.input ```
*/ staticHeaders?: boolean; } /** * @internal * Configuration for Astro's client-side code from adapters. * This is used internally to inject adapter-specific behavior into client code. */ export interface AstroAdapterClientConfig { /** * Headers to inject into Astro's internal fetch calls (Actions, View Tra...
@@ -122,11 +122,12 @@ export interface AstroAdapterClientConfig { interface AdapterLegacyDynamicProperties { /** * Determines how the adapter's entrypoint is handled during the build. - * - `'self'`: The adapter defines its own entrypoint and sets rollupOptions.input - * - `'legacy-dynamic'`: Uses the virtual m...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.714
suggestion
134
51
51
false
feat: improve naming of new adapter api
15,461
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset URLs (images, stylesheets, scripts, etc.). * Useful for adapters that need to track deployment versions or other metadata. */ assetQueryParams?: URLSearchParams; } interface AdapterLeg...
```suggestion * - `'auto'`: The adapter defines its own entrypoint and provides either serverEntrypoint or rollupOptions.input ```
internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset URLs (images, stylesheets, scripts, etc.). * Useful for adapters that need to track deployment versions or other metadata. */ assetQueryParams?: URLSearchParams; } interface AdapterExp...
@@ -135,11 +136,11 @@ interface AdapterLegacyDynamicProperties { interface AdapterSelfProperties { /** * Determines how the adapter's entrypoint is handled during the build. - * - `'self'`: The adapter defines its own entrypoint and sets rollupOptions.input - * - `'legacy-dynamic'`: Uses the virtual module entr...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.714
suggestion
134
51
51
false
feat: improve naming of new adapter api
15,461
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
/** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch). * Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset U...
If `exports` and `args` are only used with `explicit`, should they also be deprecated? If someone runs a linter with a `no-deprecated` rule, maybe this could help them spot quickly what need to change here (in addition to the docs)?
/** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch). * Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset U...
@@ -119,27 +119,28 @@ export interface AstroAdapterClientConfig { assetQueryParams?: URLSearchParams; } -interface AdapterLegacyDynamicProperties { +interface AdapterExplicitProperties { /** * Determines how the adapter's entrypoint is handled during the build. - * - `'self'`: The adapter defines its own ent...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.643
question
233
51
51
false
feat: improve naming of new adapter api
15,461
withastro/astro
47,179
TypeScript
ArmandPhilippot
florian-lefebvre
/** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch). * Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset U...
```suggestion /** @deprecated This will be removed in a future major version, alongside `entrypointResolution: 'explicit'` */ exports?: string[]; /** @deprecated This will be removed in a future major version, alongside `entrypointResolution: 'explicit'` */ args?: any; ```
/** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch). * Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset U...
@@ -119,27 +119,28 @@ export interface AstroAdapterClientConfig { assetQueryParams?: URLSearchParams; } -interface AdapterLegacyDynamicProperties { +interface AdapterExplicitProperties { /** * Determines how the adapter's entrypoint is handled during the build. - * - `'self'`: The adapter defines its own ent...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.857
suggestion
273
51
51
false
feat: improve naming of new adapter api
15,461
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
/** * @internal * Configuration for Astro's client-side code from adapters. * This is used internally to inject adapter-specific behavior into client code. */ export interface AstroAdapterClientConfig { /** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetc...
```suggestion * @deprecated This will be removed in a future major version and `'auto'` will become the default ```
/** * @internal * Configuration for Astro's client-side code from adapters. * This is used internally to inject adapter-specific behavior into client code. */ export interface AstroAdapterClientConfig { /** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetc...
@@ -119,27 +119,28 @@ export interface AstroAdapterClientConfig { assetQueryParams?: URLSearchParams; } -interface AdapterLegacyDynamicProperties { +interface AdapterExplicitProperties { /** * Determines how the adapter's entrypoint is handled during the build. - * - `'self'`: The adapter defines its own ent...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.786
suggestion
117
51
51
false
feat: improve naming of new adapter api
15,461
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
/** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch). * Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset U...
```suggestion /** @deprecated This will be removed in a future major version, alongside `entrypointResolution: 'explicit'` */ exports?: string[]; /** @deprecated This will be removed in a future major version, alongside `entrypointResolution: 'explicit'` */ args?: any; ```
/** * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch). * Can be an object of headers or a function that returns headers. */ internalFetchHeaders?: Record<string, string> | (() => Record<string, string>); /** * Query parameters to append to all asset U...
@@ -119,27 +119,30 @@ export interface AstroAdapterClientConfig { assetQueryParams?: URLSearchParams; } -interface AdapterLegacyDynamicProperties { +interface AdapterExplicitProperties { /** * Determines how the adapter's entrypoint is handled during the build. - * - `'self'`: The adapter defines its own ent...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.857
suggestion
277
51
51
false
feat: improve naming of new adapter api
15,461
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
*/ abstract tryRewrite(rewritePayload: RewritePayload, request: Request): Promise<TryRewriteResult>; /** * Tells the pipeline how to retrieve a component give a `RouteData` * @param routeData */ abstract getComponentByRoute(routeData: RouteData): Promise<ComponentInstance>; /** * The current name of the...
Going by the old explanation in the comment, I think we can refactor this to always return NOOP when `middlewareMode` is `edge`, but let me know if this is incorrect.
} abstract headElements(routeData: RouteData): Promise<HeadElements> | HeadElements; abstract componentMetadata(routeData: RouteData): Promise<SSRResult['componentMetadata']> | void; /** * It attempts to retrieve the `RouteData` that matches the input `url`, and the component that belongs to the `RouteData`. ...
@@ -116,9 +116,15 @@ export abstract class Pipeline { if (this.resolvedMiddleware) { return this.resolvedMiddleware; } - // The middleware can be undefined when using edge middleware. - // This is set to undefined by the plugin-ssr.ts - else if (this.middleware) { + + const middlewareMode = this.manifest....
packages/astro/src/core/base-pipeline.ts
26
TypeScript
0.571
bug
166
51
51
false
feat: refactor `edgemiddleware` into `middlewareMode` adapter feature
15,495
withastro/astro
47,179
TypeScript
leekeh
leekeh
import type { IncomingMessage, ServerResponse } from 'node:http'; import type { MiddlewareMode, SSRManifest } from 'astro'; export interface UserOptions { /** * Specifies the mode that the adapter builds to. * * - 'middleware' - Build to middleware, to be used within another Node.js server, such as Express. *...
The node adapter doesn't expose any middleware options, plus exposing a variant that is just `classic` doesn't serve any utility. We should just remove it
import type { IncomingMessage, ServerResponse } from 'node:http'; export interface UserOptions { /** * Specifies the mode that the adapter builds to. * * - 'middleware' - Build to middleware, to be used within another Node.js server, such as Express. * - 'standalone' - Build to a standalone server. The server...
@@ -9,6 +9,10 @@ export interface UserOptions { * - 'standalone' - Build to a standalone server. The server starts up just by running the built script. */ mode: 'middleware' | 'standalone'; + /** + * Controls when and how middleware executes. + */ + middlewareMode?: Exclude<MiddlewareMode, 'edge'>;
packages/integrations/node/src/types.ts
15
TypeScript
0.571
refactor
154
40
40
false
feat: refactor `edgemiddleware` into `middlewareMode` adapter feature
15,495
withastro/astro
47,179
TypeScript
ematipico
leekeh
import { appendFile, rm, stat } from 'node:fs/promises'; import { createInterface } from 'node:readline/promises'; import { removeLeadingForwardSlash } from '@astrojs/internal-helpers/path'; import { createRedirectsFromAstroRoutes, printAsRedirects } from '@astrojs/underscore-redirects'; import { cloudflare as cfVitePl...
It doesn't make sense to expose an option if the variant is only one.
import { appendFile, rm, stat } from 'node:fs/promises'; import { createInterface } from 'node:readline/promises'; import { removeLeadingForwardSlash } from '@astrojs/internal-helpers/path'; import { createRedirectsFromAstroRoutes, printAsRedirects } from '@astrojs/underscore-redirects'; import { cloudflare as cfVitePl...
@@ -21,6 +21,11 @@ import { createCloudflarePrerenderer } from './prerenderer.js'; export type { Runtime } from './utils/handler.js'; export type Options = { + /** + * Controls when and how middleware executes. + */ + middlewareMode?: Exclude<MiddlewareMode, 'edge'>;
packages/integrations/cloudflare/src/index.ts
26
TypeScript
0.214
suggestion
70
51
51
false
feat: refactor `edgemiddleware` into `middlewareMode` adapter feature
15,495
withastro/astro
47,179
TypeScript
ematipico
leekeh
export type AdapterSupportWithMessage = { support: Exclude<AdapterSupportsKind, 'stable'>; message: string; /** * Determines if a feature support warning/error in the adapter should be suppressed: * - `"default"`: Suppresses the default warning/error message. * - `"all"`: Suppresses both the custom and the def...
The wording here is a bit confusing: maybe you can rephrase? > your adapter might expect … but uses an adapter Should these both be “adapter”?
export type AdapterSupportWithMessage = { support: Exclude<AdapterSupportsKind, 'stable'>; message: string; /** * Determines if a feature support warning/error in the adapter should be suppressed: * - `"default"`: Suppresses the default warning/error message. * - `"all"`: Suppresses both the custom and the def...
@@ -82,21 +82,23 @@ export type AdapterSupport = AdapterSupportsKind | AdapterSupportWithMessage; export interface AstroAdapterFeatures { /** - * Creates an edge function that will communicate with the Astro middleware + * Defines whether any on-demand rendering middleware code will be bundled when built. When e...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.429
question
144
51
51
false
feat: improve AstroAdapter jsdocs
15,550
withastro/astro
47,179
TypeScript
delucis
florian-lefebvre
* or the default message might cause confusion and conflict with a custom one. */ suppress?: 'all' | 'default'; }; export type AdapterSupport = AdapterSupportsKind | AdapterSupportWithMessage; export interface AstroAdapterFeatures { /** * Defines whether any on-demand rendering middleware code will be bundled...
Small suggestion here: ```suggestion * Whether or not the adapter provides experimental support for setting response headers for static pages. When this * feature is enabled, Astro will return a map of the `Headers` emitted by the static pages. This map is available * as `routeToHeaders` in the `astro:build:gene...
* or the default message might cause confusion and conflict with a custom one. */ suppress?: 'all' | 'default'; }; export type AdapterSupport = AdapterSupportsKind | AdapterSupportWithMessage; export interface AstroAdapterFeatures { /** * Defines whether any on-demand rendering middleware code will be bundled...
@@ -82,21 +82,23 @@ export type AdapterSupport = AdapterSupportsKind | AdapterSupportWithMessage; export interface AstroAdapterFeatures { /** - * Creates an edge function that will communicate with the Astro middleware + * Defines whether any on-demand rendering middleware code will be bundled when built. When e...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.857
bug
549
51
51
false
feat: improve AstroAdapter jsdocs
15,550
withastro/astro
47,179
TypeScript
delucis
florian-lefebvre
export const viteFSConfig = ${JSON.stringify(resolvedConfig.server.fs ?? {})}; export const safeModulePaths = new Set(${JSON.stringify( // @ts-expect-error safeModulePaths is internal to Vite Array.from(resolvedConfig.safeModulePaths ?? []), )}); const assetQueryParams = ${ ...
Sorry to interrupt, but is this change intended?
export const viteFSConfig = ${JSON.stringify(resolvedConfig.server.fs ?? {})}; export const safeModulePaths = new Set(${JSON.stringify( // @ts-expect-error safeModulePaths is internal to Vite Array.from(resolvedConfig.safeModulePaths ?? []), )}); const assetQueryParams = ${ ...
@@ -190,11 +190,10 @@ export default function assets({ fs, settings, sync, logger }: Options): vite.Pl enumerable: false, configurable: true, }); -export const inferRemoteSize = async (url) => { - const service = await _getConfiguredImageService() - - return service....
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.143
question
48
51
51
false
Respect remote image allowlists
15,586
withastro/astro
47,179
TypeScript
rururux
matthewp
import type * as fsMod from 'node:fs'; import { extname } from 'node:path'; import MagicString from 'magic-string'; import type * as vite from 'vite'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { appendForwardSlash, joinPaths, pr...
Nit: I think we can put the `CONTENT_IMAGE_FLAG` import here to keep the imports organized ```suggestion import type * as vite from 'vite'; import { CONTENT_IMAGE_FLAG } from '../content/consts.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; ```
import type * as fsMod from 'node:fs'; import { extname } from 'node:path'; import MagicString from 'magic-string'; import picomatch from 'picomatch'; import type * as vite from 'vite'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { ...
packages/astro/src/assets/vite-plugin-assets.ts
6
TypeScript
0.929
suggestion
273
31
31
false
fix(assets): prevent circular dependency deadlock with SVG in content collections
15,603
withastro/astro
47,179
TypeScript
astrochemx
0xRozier
resolveId: { filter: { id: new RegExp(`(?:\\?|&)(?:${CONTENT_IMAGE_FLAG}|${CONTENT_RENDER_FLAG})(?:&|=|$)`), }, async handler(id, importer, opts) { if (hasContentFlag(id, CONTENT_IMAGE_FLAG)) { const [base, query] = id.split('?'); const params = new URLSearchParams(query); const import...
Small optimisation: assign id to resolved, so we don't need to return a new array via spread ```js resolved.id = `${resolved.id}?${CONTENT_IMAGE_FLAG}`; return resolved; ```
resolveId: { filter: { id: new RegExp(`(?:\\?|&)(?:${CONTENT_IMAGE_FLAG}|${CONTENT_RENDER_FLAG})(?:&|=|$)`), }, async handler(id, importer, opts) { if (hasContentFlag(id, CONTENT_IMAGE_FLAG)) { const [base, query] = id.split('?'); const params = new URLSearchParams(query); const import...
@@ -53,7 +53,11 @@ export function astroContentAssetPropagationPlugin({ message: AstroErrorData.ImageNotFound.message(base), }); } - return resolved; + // Preserve the content image flag in the resolved ID so that downstream plugins + // (e.g. astro:assets:esm) can detect content collec...
packages/astro/src/content/vite-plugin-content-assets.ts
26
TypeScript
0.714
suggestion
175
51
51
false
fix(assets): prevent circular dependency deadlock with SVG in content collections
15,603
withastro/astro
47,179
TypeScript
ematipico
0xRozier
const componentPath = this.getComponentPath(); const componentExport = this.getComponentExport(); let componentId = this.result.serverIslandNameMap.get(componentPath); if (!componentId) { throw new Error(`Could not find server component name ${componentPath}`); } // Remove internal props for (const k...
can you use ar regular top-level type import here?
const componentPath = this.getComponentPath(); const componentExport = this.getComponentExport(); let componentId = this.result.serverIslandNameMap.get(componentPath); if (!componentId) { throw new Error(`Could not find server component name ${componentPath}`); } // Remove internal props for (const k...
@@ -158,7 +158,20 @@ export class ServerIslandComponent { for (const name in this.slots) { if (name !== 'fallback') { const content = await renderSlotToString(this.result, this.slots[name]); - renderedSlots[name] = content.toString(); + let slotHtml = content.toString(); + // Append script instruct...
packages/astro/src/runtime/server/render/server-islands.ts
26
TypeScript
0.429
question
50
51
51
false
fix: include slot scripts in server island response
15,633
withastro/astro
47,179
TypeScript
matthewp
jwoyo
/** * When `imageService` is set to `cloudflare-binding`, the Cloudflare Images binding will be used * to transform images. The binding will be automatically configured for you. * * By default, the binding is named `IMAGES`, but you can override this by providing a different name here. * If you define the bi...
Are there any docs for this? I found various references to it on GitHub but no documentation. I noticed `std-env` [also check `process.env.SHELL`](https://github.com/unjs/std-env/pull/63/changes#diff-2b7ff992842c6f8113f826af7e81b310a87148e85eef65304868dfc91dad5febR119) but no idea what matters where.
/** * When `imageService` is set to `cloudflare-binding`, the Cloudflare Images binding will be used * to transform images. The binding will be automatically configured for you. * * By default, the binding is named `IMAGES`, but you can override this by providing a different name here. * If you define the bi...
@@ -60,6 +60,10 @@ export default function createIntegration(args?: Options): AstroIntegration { name: '@astrojs/cloudflare', hooks: { 'astro:config:setup': ({ command, config, updateConfig, logger, addWatchFile }) => { + if (!!process.versions.webcontainer) {
packages/integrations/cloudflare/src/index.ts
26
TypeScript
0.643
suggestion
302
51
51
false
feat(cloudflare): throw on stackblitz
15,636
withastro/astro
47,179
TypeScript
delucis
florian-lefebvre
let _cssVariablesTheme: ReturnType<typeof createCssVariablesTheme>; const cssVariablesTheme = () => _cssVariablesTheme ?? (_cssVariablesTheme = createCssVariablesTheme({ variablePrefix: '--astro-code-', })); // Caches Promise<ShikiHighlighterInternal> for reuse when the same `themes` and `langAlias`. const cache...
This is wasteful because we're polluting the key with empty objects. I suggest looking for a different approach e.g. ```js const keyCache = []; if (options?.theme) { keyCache.push(options.theme) } ... const key = keyCache.length > 0 ? JSON.stringify() : ""; ```
let _cssVariablesTheme: ReturnType<typeof createCssVariablesTheme>; const cssVariablesTheme = () => _cssVariablesTheme ?? (_cssVariablesTheme = createCssVariablesTheme({ variablePrefix: '--astro-code-', })); // Caches Promise<ShikiHighlighterInternal> for reuse when the same `themes` and `langAlias`. const cache...
@@ -73,41 +81,77 @@ const cssVariablesTheme = () => variablePrefix: '--astro-code-', })); -// Caches Promise<ShikiHighlighter> for reuse when the same theme and langs are provided -const cachedHighlighters = new Map(); +// Caches Promise<ShikiHighlighterInternal> for reuse when the same `themes` and `langAlias`....
packages/markdown/remark/src/shiki.ts
26
TypeScript
0.857
performance
264
51
51
false
fix(markdown-remark): reuse shiki highlighter instance
15,651
withastro/astro
47,179
TypeScript
ematipico
ocavue
} await highlighter.loadLanguage(lang); } return highlighter; } let shikiEngine: RegexEngine | undefined = undefined; async function createShikiHighlighterInternal({ langs = [], theme = 'github-dark', themes = {}, langAlias = {}, }: CreateShikiHighlighterOptions = {}): Promise<ShikiHighlighterInternal> { t...
Can you please add a test that verifies the correctness of the code? Specifically, we want to test that given we create an highlighter with certain options and languages, the second time we request the same highlighter, it doesn't load again the languages
if (langAlias) { keyCache.push(Object.entries(langAlias).sort()); } return keyCache.length > 0 ? JSON.stringify(keyCache) : ''; } /** * Ensures that the languages are loaded into the highlighter. This is * especially important when the languages are objects representing custom * user-defined languages. */ asy...
@@ -73,41 +81,77 @@ const cssVariablesTheme = () => variablePrefix: '--astro-code-', })); -// Caches Promise<ShikiHighlighter> for reuse when the same theme and langs are provided -const cachedHighlighters = new Map(); +// Caches Promise<ShikiHighlighterInternal> for reuse when the same `themes` and `langAlias`....
packages/markdown/remark/src/shiki.ts
26
TypeScript
0.429
suggestion
256
51
51
false
fix(markdown-remark): reuse shiki highlighter instance
15,651
withastro/astro
47,179
TypeScript
ematipico
ocavue
* allowedDomains: [ * { * hostname: '**.example.com', * protocol: 'https' * }, * { * hostname: 'staging.myapp.com', * protocol: 'https', * port: '443' * } * ] * } * } * ``` * * When not configured, ...
Docs wise, LGTM! But we need to update [the version](https://github.com/withastro/astro/blob/efae11cef1ebe1f2f54ceb55db0d1ff1938351c6/packages/astro/src/types/public/config.ts#L643C15-L643C21): ```suggestion * @version 5.18.0 ```
* allowedDomains: [ * { * hostname: '**.example.com', * protocol: 'https' * }, * { * hostname: 'staging.myapp.com', * protocol: 'https', * port: '443' * } * ] * } * } * ``` * * When not configured, ...
@@ -645,6 +645,31 @@ export interface AstroUserConfig< */ allowedDomains?: Partial<RemotePattern>[]; + /** + * @docs + * @name security.actionBodySizeLimit + * @kind h4 + * @type {number} + * @default `1048576` (1 MB) + * @version 5.x.0
packages/astro/src/types/public/config.ts
26
TypeScript
0.929
suggestion
232
51
51
false
Make the limit of the body of a POST configurable (port from 5-legacy)
15,657
withastro/astro
47,179
TypeScript
ArmandPhilippot
qzio
* Each pattern can specify `protocol`, `hostname`, and `port`. All three are validated if provided. * The patterns support wildcards for flexible hostname matching: * * - `*.example.com` - matches exactly one subdomain level (e.g., `sub.example.com` but not `deep.sub.example.com`) * - `**.example.com` - ...
A non-blocking nit: If this should only be used with some edge cases (re: the caution in the code snippet), it might be a good idea to emphasize this in the sentence: ```suggestion * In some specific contexts (e.g., applications behind trusted reverse proxies with dynamic domains), you may need to allow all domains....
* Each pattern can specify `protocol`, `hostname`, and `port`. All three are validated if provided. * The patterns support wildcards for flexible hostname matching: * * - `*.example.com` - matches exactly one subdomain level (e.g., `sub.example.com` but not `deep.sub.example.com`) * - `**.example.com` - ...
@@ -641,6 +644,17 @@ export interface AstroUserConfig< * } * ``` * + * To allow all domains (useful for applications behind trusted reverse proxies with dynamic domains), use an empty object:
packages/astro/src/types/public/config.ts
26
TypeScript
1
bug
357
51
51
false
Document empty {} for allowing any domain
15,663
withastro/astro
47,179
TypeScript
ArmandPhilippot
matthewp
* * ```js * { * security: { * // Example: Allow any subdomain of example.com on https * allowedDomains: [ * { * hostname: '**.example.com', * protocol: 'https' * }, * { * hostname: 'staging.myapp.com', * protocol: 'https'...
Maybe "only when necessary" is a little less vague than "with caution"? (but I'm really nitpicking...) ```suggestion * // Allow any domain - use this only when necessary ```
* * ```js * { * security: { * // Example: Allow any subdomain of example.com on https * allowedDomains: [ * { * hostname: '**.example.com', * protocol: 'https' * }, * { * hostname: 'staging.myapp.com', * protocol: 'https'...
@@ -641,6 +644,17 @@ export interface AstroUserConfig< * } * ``` * + * To allow all domains (useful for applications behind trusted reverse proxies with dynamic domains), use an empty object: + * + * ```js + * { + * security: { + * // Allow any domain - use with caution
packages/astro/src/types/public/config.ts
26
TypeScript
0.786
suggestion
180
51
51
false
Document empty {} for allowing any domain
15,663
withastro/astro
47,179
TypeScript
ArmandPhilippot
matthewp
/* eslint-disable regexp/control-character-escape */ /* eslint-disable no-control-regex */ /* eslint-disable regexp/no-optional-assertion */ /* eslint-disable regexp/no-useless-escape */ /* eslint-disable regexp/no-obscure-range */ // ESM vendored version of cssesc: https://github.com/mathiasbynens/cssesc/blob/cb894eb4...
```suggestion // ESM vendored version of cssesc: https://github.com/mathiasbynens/cssesc/blob/cb894eb42f27c8d3cd793f16afe35b3ab38000a1/cssesc.js // See https://github.com/withastro/astro/pull/15669 ```
/* eslint-disable regexp/control-character-escape */ /* eslint-disable no-control-regex */ /* eslint-disable regexp/no-optional-assertion */ /* eslint-disable regexp/no-useless-escape */ /* eslint-disable regexp/no-obscure-range */ // ESM vendored version of cssesc: https://github.com/mathiasbynens/cssesc/blob/cb894eb4...
@@ -0,0 +1,102 @@ +/* eslint-disable regexp/control-character-escape */ +/* eslint-disable no-control-regex */ +/* eslint-disable regexp/no-optional-assertion */ +/* eslint-disable regexp/no-useless-escape */ +/* eslint-disable regexp/no-obscure-range */ +// ESM vendored version of cssesc: https://github.com/mathiasbyn...
packages/astro/src/transitions/cssesc.ts
6
TypeScript
0.786
suggestion
204
31
31
false
feat: vendor cssesc
15,669
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
platform: 'node', target: 'node14.16.1', sourcemap: 'inline', sourcesContent: false, }; export default async function build(...args) { const config = Object.assign({}, defaultConfig); const isDev = args.slice(-1)[0] === 'IS_DEV'; const patterns = args .filter((f) => !!f) // remove empty args .map...
No issues found.
platform: 'node', target: 'node14.16.1', sourcemap: 'inline', sourcesContent: false, }; export default async function build(...args) { const config = Object.assign({}, defaultConfig); const isDev = args.slice(-1)[0] === 'IS_DEV'; const patterns = args .filter((f) => !!f) // remove empty args .map...
@@ -7,11 +7,10 @@ import glob from 'tiny-glob'; /** @type {import('esbuild').BuildOptions} */ const defaultConfig = { - bundle: true, minify: false, format: 'esm', platform: 'node', - target: 'node14', + target: 'node14.16.1', sourcemap: 'inline', sourcesContent: false, }; @@ -26,16 +25,15 @@ exp...
scripts/cmd/build.js
0
JavaScript
1
none
16
51
51
true
Update build script to avoid bundling
304
withastro/astro
47,179
TypeScript
natemoo-re
import type { LogOptions } from '../logger'; import type { AstroConfig, RuntimeMode } from './astro'; export interface CompileOptions { logging: LogOptions; resolvePackageUrl: (p: string) => Promise<string>; astroConfig: AstroConfig; hmrPort?: number; mode: RuntimeMode; }
No issues found.
import type { LogOptions } from '../logger'; import type { AstroConfig, RuntimeMode } from './astro'; export interface CompileOptions { logging: LogOptions; resolvePackageUrl: (p: string) => Promise<string>; astroConfig: AstroConfig; hmrPort?: number; mode: RuntimeMode; }
@@ -7,5 +7,4 @@ export interface CompileOptions { astroConfig: AstroConfig; hmrPort?: number; mode: RuntimeMode; - tailwindConfig?: string; }
packages/astro/src/@types/compiler.ts
0
TypeScript
1
none
16
11
11
true
Pass configured Tailwind config file to the `tailwindcss` plugin
352
withastro/astro
47,179
TypeScript
bradlc
import { logger as snowpackLogger } from 'snowpack'; import { defaultLogLevel } from './logger.js'; const neverWarn = new RegExp( '(' + /(run "snowpack init" to create a project config file.)|/.source + /(Unscannable package import found.)|/.source + /(Cannot call a namespace \('loadLanguages'\))|/.sourc...
No issues found.
import { logger as snowpackLogger } from 'snowpack'; import { defaultLogLevel } from './logger.js'; const neverWarn = new RegExp( '(' + /(run "snowpack init" to create a project config file.)|/.source + /(Unscannable package import found.)|/.source + /(Cannot call a namespace \('loadLanguages'\))|/.sourc...
@@ -1,8 +1,6 @@ import { logger as snowpackLogger } from 'snowpack'; import { defaultLogLevel } from './logger.js'; -const onceMessages = ['Ready!', 'watching for file changes'].map((str) => new RegExp(`\\[snowpack\\](.*?)${str}`)); - const neverWarn = new RegExp( '(' + /(run "snowpack init" to create a pr...
packages/astro/src/snowpack-logger.ts
0
TypeScript
1
none
16
28
28
true
Remove second snowpack instance
368
withastro/astro
47,179
TypeScript
matthewp
// For everything else, parse & scope const c = className.replace(/^\.?/, '.'); // make sure class always has leading '.' const selectors: Selector[] = []; let ss = selector; // final output // Pass 1: parse selector string; extract top-level selectors { let start = 0; let lastValue = ''; let ...
No issues found.
// For everything else, parse & scope const c = className.replace(/^\.?/, '.'); // make sure class always has leading '.' const selectors: Selector[] = []; let ss = selector; // final output // Pass 1: parse selector string; extract top-level selectors { let start = 0; let lastValue = ''; let ...
@@ -82,7 +82,7 @@ export function scopeRule(selector: string, className: string) { // scope everything else let newSelector = value; - const pseudoIndex = newSelector.indexOf(':'); + const pseudoIndex = newSelector.search(/(?<!\\):/); if (pseudoIndex > 0) { // if there’s a pseudoclass (:fo...
packages/astro/src/compiler/transform/postcss-scoped-styles/index.ts
0
TypeScript
1
none
16
51
51
true
Fix scoped CSS selector when class contains a colon
383
withastro/astro
47,179
TypeScript
bradlc
DType.before(async () => { try { const astroConfig = await loadConfig(fileURLToPath(new URL('./fixtures/astro-doctype', import.meta.url))); const logging = { level: 'error', dest: process.stderr, }; runtime = await createRuntime(astroConfig, { logging }); } catch (err) { console.e...
No issues found.
DType.before(async () => { try { const astroConfig = await loadConfig(fileURLToPath(new URL('./fixtures/astro-doctype', import.meta.url))); const logging = { level: 'error', dest: process.stderr, }; runtime = await createRuntime(astroConfig, { logging }); } catch (err) { console.e...
@@ -56,4 +56,13 @@ DType.skip('Preserves user provided doctype', async () => { assert.ok(html.startsWith('<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'), 'Doctype included was preserved'); }); +DType('User provided doctype is case insensitive', async () =>...
packages/astro/test/astro-doctype.test.js
0
JavaScript
1
none
16
51
51
true
Make doctype be case insensitive
419
withastro/astro
47,179
TypeScript
matthewp
const outURL = srcURL.replace(/\$([^.]+)\.astro$/, '$1'); const builtURLs = new Set<string>(); // !important: internal cache that prevents building the same URLs /** Recursively build collection URLs */ async function loadCollection(url: string): Promise<LoadResult | undefined> { if (builtURLs.has(url)) r...
No issues found.
const outURL = srcURL.replace(/\$([^.]+)\.astro$/, '$1'); const builtURLs = new Set<string>(); // !important: internal cache that prevents building the same URLs /** Recursively build collection URLs */ async function loadCollection(url: string): Promise<LoadResult | undefined> { if (builtURLs.has(url)) r...
@@ -91,18 +91,13 @@ export async function buildCollectionPage({ astroConfig, filepath, runtime, site export async function buildStaticPage({ astroConfig, buildState, filepath, runtime }: PageBuildOptions): Promise<void> { const { pages: pagesRoot } = astroConfig; const url = filepath.pathname.replace(pagesRoot.p...
packages/astro/src/build/page.ts
0
TypeScript
1
none
16
51
51
true
Improve asset resolution in Astro
437
withastro/astro
47,179
TypeScript
drwpow
import { suite } from 'uvu'; import * as assert from 'uvu/assert'; import { doc } from './test-utils.js'; import { setupBuild } from './helpers.js'; const Resolution = suite('Astro Resolution'); setupBuild(Resolution, './fixtures/astro-resolve'); Resolution('Assets', async (context) => { await context.build(); ...
No issues found.
import { suite } from 'uvu'; import * as assert from 'uvu/assert'; import { doc } from './test-utils.js'; import { setupBuild } from './helpers.js'; const Resolution = suite('Astro Resolution'); setupBuild(Resolution, './fixtures/astro-resolve'); Resolution('Assets', async (context) => { await context.build(); ...
@@ -1,5 +1,6 @@ import { suite } from 'uvu'; import * as assert from 'uvu/assert'; +import { doc } from './test-utils.js'; import { setupBuild } from './helpers.js'; const Resolution = suite('Astro Resolution'); @@ -9,11 +10,30 @@ setupBuild(Resolution, './fixtures/astro-resolve'); Resolution('Assets', async (co...
packages/astro/test/astro-resolve.test.js
0
JavaScript
1
none
16
40
40
true
Fix script resolution
438
withastro/astro
47,179
TypeScript
drwpow
'noscript', 'base' ]); export class EndOfHead { private head: TemplateNode | null = null; private firstNonHead: TemplateNode | null = null; private parent: TemplateNode | null = null; private stack: TemplateNode[] = []; public append: (...node: TemplateNode[]) => void = () => void 0; get found(): b...
No issues found.
'noscript', 'base' ]); export class EndOfHead { private head: TemplateNode | null = null; private firstNonHead: TemplateNode | null = null; private parent: TemplateNode | null = null; private stack: TemplateNode[] = []; public append: (...node: TemplateNode[]) => void = () => void 0; get found(): b...
@@ -0,0 +1,69 @@ +import type { TemplateNode } from '@astrojs/parser'; + +const validHeadElements = new Set([ + '!doctype', + 'title', + 'meta', + 'link', + 'style', + 'script', + 'noscript', + 'base' +]); + +export class EndOfHead { + private head: TemplateNode | null = null; + private firstNonHead: Template...
packages/astro/src/compiler/transform/util/end-of-head.ts
0
TypeScript
1
none
16
51
51
true
Allow the head element to be optional
447
withastro/astro
47,179
TypeScript
matthewp
Basics('Can load page', async ({ runtime }) => { const result = await runtime.load('/'); if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('h1').text(), 'Hello world!'); }); Basics('Sets the HMR port when dynamic components used', async ({ runtime }) => { const...
No issues found.
Basics('Can load page', async ({ runtime }) => { const result = await runtime.load('/'); if (result.error) throw new Error(result.error); const $ = doc(result.contents); assert.equal($('h1').text(), 'Hello world!'); }); Basics('Sets the HMR port when dynamic components used', async ({ runtime }) => { const...
@@ -64,4 +64,14 @@ Basics('Build does not include HMR client', async ({ build, readFile }) => { assert.equal(hmrPortScript.length, 0, 'No script setting the websocket port'); }); +Basics('Allows forward-slashes in mustache tags (#407)', async ({ runtime }) => { + const result = await runtime.load('/forward-slash...
packages/astro/test/astro-basic.test.js
0
JavaScript
1
none
16
51
51
true
Fix parser error on forward slash
469
withastro/astro
47,179
TypeScript
drwpow