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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
* @description
* The default object-position value for responsive images. Can be overridden by the `position` prop on the image component.
* Requires a value for `layout` to be set.
*/
objectPosition?: string;
/**
* @docs
* @name image.breakpoints
* @type {number[]}
* @default `[640, 750, 82... | ```suggestion
* Whether to automatically add global styles for responsive images. We recommend enabling this option to ensure that images resize correctly.
* This option is only used when `layout` is set to `constrained`, `full-width`, or `fixed` using the configuration or the `layout` prop on the image compone... | /**
* @docs
* @name image.objectPosition
* @type {string}
* @default `"center"`
* @version 5.10.0
* @description
* The default object-position value for responsive images. Can be overridden by the `position` prop on the image component.
* Requires a value for `layout` to be set.
*
* See... | @@ -1328,58 +1328,62 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
/**
* @docs
- * @name image.experimentalLayout
+ * @name image.layout
* @type {ImageLayout}
* @default `undefined`
+ * @version 5.10.0
* @description
* The default layout type for responsive images. C... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.857 | suggestion | 483 | 51 | 51 | false | feat: unflag responsive images | 13,917 | withastro/astro | 47,179 | TypeScript | ascorbic | ascorbic |
* - Start with '**.' to allow all subdomains ('endsWith').
* - Start with '*.' to allow only one level of subdomain.
*
* `pathname`:
* - End with '/**' to allow all sub-routes ('startsWith').
* - End with '/*' to allow only one level of sub-route.
*/
remotePatterns?: Partial<RemotePatter... | ```suggestion
*
* See [the layout component property](https://docs.astro.build/en/reference/modules/astro-assets/#layout) for more details.
*/
```
@ascorbic We can match these up to whatever the stable docs end up being, but in my draft branch, all of these properties have a link to their corresponding ... | * You can use wildcards to define the permitted `hostname` and `pathname` values as described below. Otherwise, only the exact values provided will be configured:
* `hostname`:
* - Start with '**.' to allow all subdomains ('endsWith').
* - Start with '*.' to allow only one level of subdomain.
*
* ... | @@ -1328,58 +1328,62 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
/**
* @docs
- * @name image.experimentalLayout
+ * @name image.layout
* @type {ImageLayout}
* @default `undefined`
+ * @version 5.10.0
* @description
* The default layout type for responsive images. C... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.786 | suggestion | 750 | 51 | 51 | false | feat: unflag responsive images | 13,917 | withastro/astro | 47,179 | TypeScript | sarah11918 | ascorbic |
.map((script) => {
if (result.userAssetsBase) {
script.props.src =
(result.base === '/' ? '' : result.base) + result.userAssetsBase + script.props.src;
}
return renderElement('script', script, false);
});
const links = Array.from(result.links)
.filter(uniqueElements)
.map((link) => renderElem... | Is it possible this change means that meta tags are injected even if csp is disabled? | .map((script) => {
if (result.userAssetsBase) {
script.props.src =
(result.base === '/' ? '' : result.base) + result.userAssetsBase + script.props.src;
}
return renderElement('script', script, false);
});
const links = Array.from(result.links)
.filter(uniqueElements)
.map((link) => renderElem... | @@ -52,7 +52,7 @@ export function renderAllHeadContent(result: SSRResult) {
}
}
- if (result.shouldInjectCspMetaTags) {
+ if (result.cspDestination === 'meta') { | packages/astro/src/runtime/server/render/head.ts | 26 | TypeScript | 0.429 | question | 86 | 51 | 51 | false | refactor(csp): change CSP behaviour | 13,923 | withastro/astro | 47,179 | TypeScript | theosanderson | ematipico |
message: `Cannot use server-rendered pages without an adapter. Please install and configure the appropriate server adapter for your final deployment.`,
hint: 'See https://docs.astro.build/en/guides/on-demand-rendering/ for more information.',
} satisfies ErrorData;
/**
* @docs
* @see
* - [Server-side Rendering](h... | I think we could use another sentence here guiding the user re: what to DO in this situation? If they haven't configured experimental CSP, then why might the adapter be trying to use it and how can they stop the adapter from doing this?
(There's no other place than config that the user could be adding CSP content, ... | message: `Cannot use server-rendered pages without an adapter. Please install and configure the appropriate server adapter for your final deployment.`,
hint: 'See https://docs.astro.build/en/guides/on-demand-rendering/ for more information.',
} satisfies ErrorData;
/**
* @docs
* @see
* - [Server-side Rendering](h... | @@ -414,6 +414,18 @@ export const AdapterSupportOutputMismatch = {
`The \`${adapterName}\` adapter is configured to output a static website, but the project contains server-rendered pages. Please install and configure the appropriate server adapter for your final deployment.`,
} satisfies ErrorData;
+/**
+ * @doc... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 0.643 | suggestion | 517 | 51 | 51 | false | feat(csp): add static header adapter function | 13,926 | withastro/astro | 47,179 | TypeScript | sarah11918 | ematipico |
// * Avoid `queue.add()` in an async for loop. Notice the `await
// queue.onIdle();` after this loop. We do not want to create a scenario
// where tasks are added to the queue after the queue.onIdle() resolves.
// This can break tests and create annoying race conditions.
// * Exposing a concurrency... | I'm confused now. Are you already doing as I suggest? | // * Avoid `queue.add()` in an async for loop. Notice the `await
// queue.onIdle();` after this loop. We do not want to create a scenario
// where tasks are added to the queue after the queue.onIdle() resolves.
// This can break tests and create annoying race conditions.
// * Exposing a concurrency... | @@ -219,7 +221,11 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil
delete globalThis?.astroAsset?.addStaticImage;
}
- await runHookBuildGenerated({ settings: options.settings, logger });
+ await runHookBuildGenerated({
+ settings: options.settings,
+ logger,
+ _experimentalR... | packages/astro/src/core/build/generate.ts | 26 | TypeScript | 0.286 | question | 53 | 51 | 51 | false | feat(csp): add static header adapter function | 13,926 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
* 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 default warning/error message.
*
* This is useful when the warning/error might not be applicable in certain contex... | This comment needs updating to match the new meaning of the flag | * 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 default warning/error message.
*
* This is useful when the warning/error might not be applicable in certain contex... | @@ -89,6 +89,13 @@ export interface AstroAdapterFeatures {
* Determine the type of build output the adapter is intended for. Defaults to `server`;
*/
buildOutput?: 'static' | 'server';
+
+ /**
+ * If supported by the adapter and enabled, Astro won't provide CSP hashes for static pages anymore.
+ * Instead, th... | packages/astro/src/types/public/integrations.ts | 26 | TypeScript | 0.214 | suggestion | 64 | 51 | 51 | false | feat(csp): add static header adapter function | 13,926 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
`- ${alsoFound}`
);
},
} satisfies ErrorData;
/**
* @docs
* @see
* - [devalue library](https://github.com/rich-harris/devalue)
* @description
* `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets).
*/
expo... | ```suggestion
* The `file` loader can’t determine which parser to use. Please provide a custom parser (e.g. `csv-parse`) to create a collection from your file type.
``` | `- ${alsoFound}`
);
},
} satisfies ErrorData;
/**
* @docs
* @see
* - [devalue library](https://github.com/rich-harris/devalue)
* @description
* `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets).
*/
expo... | @@ -1855,7 +1855,7 @@ export const UnsupportedConfigTransformError = {
* @see
* - [Passing a `parser` to the `file` loader](https://docs.astro.build/en/guides/content-collections/#parser-function)
* @description
- * The `file` loader can’t determine which parser to use. Please provide a custom parser (e.g. `toml... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 0.929 | suggestion | 171 | 51 | 51 | false | feat: Add TOML support to the built-in content loaders | 13,941 | withastro/astro | 47,179 | TypeScript | sarah11918 | aditsachde |
*
* @default {true}
*/
imageCDN?: boolean;
/**
* If enabled, the adapter will save [static headers in the framework API file](https://docs.netlify.com/frameworks-api/#headers).
*
* Here the list of the headers that are added:
* - The CSP header of the static pages is added when CSP support is enabled.
... | It's confusing having `_experimentalStaticHeaders` and `experimentalStaticHeaders`, one of which is a flag and the other a map of the actual headers. | *
* @default {true}
*/
imageCDN?: boolean;
/**
* If enabled, the adapter will save [static headers in the framework API file](https://docs.netlify.com/frameworks-api/#headers).
*
* Here the list of the headers that are added:
* - The CSP header of the static pages is added when CSP support is enabled.
... | @@ -218,6 +259,7 @@ export default function netlifyIntegration(
let outDir: URL;
let rootDir: URL;
let astroMiddlewareEntryPoint: URL | undefined = undefined;
+ let _experimentalStaticHeaders: Map<IntegrationResolvedRoute, Headers> | undefined = undefined; | packages/integrations/netlify/src/index.ts | 26 | TypeScript | 0.5 | suggestion | 150 | 51 | 51 | false | feat(netlify): add experimental support for static headers | 13,952 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
session,
vite: {
server: {
watch: {
ignored: [fileURLToPath(new URL('./.netlify/**', rootDir))],
},
},
},
image: {
service: {
entrypoint: enableImageCDN ? '@astrojs/netlify/image-service.js' : undefined,
},
},
});
},
'astro:routes:r... | This is the one I was referring to | session,
vite: {
server: {
watch: {
ignored: [fileURLToPath(new URL('./.netlify/**', rootDir))],
},
},
},
image: {
service: {
entrypoint: enableImageCDN ? '@astrojs/netlify/image-service.js' : undefined,
},
},
});
},
'astro:routes:r... | @@ -619,7 +619,7 @@ export default function netlifyIntegration(
finalBuildOutput = buildOutput;
const edgeMiddleware = integrationConfig?.edgeMiddleware ?? false;
- const experimentalStaticHeaders = integrationConfig?.experimentalStaticHeaders ?? false;
+ const experimentalStaticHeaders = integrationC... | packages/integrations/netlify/src/index.ts | 26 | TypeScript | 0.071 | suggestion | 34 | 51 | 51 | false | feat(netlify): add experimental support for static headers | 13,952 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
function getPrivateEnv(
fullEnv: Record<string, string>,
astroConfig: AstroConfig,
coerceValues: boolean
): Record<string, string> {
const viteConfig = astroConfig.vite;
let envPrefixes: string[] = ['PUBLIC_'];
if (viteConfig.envPrefix) {
envPrefixes = Array.isArray(viteConfig.envPrefix)
? viteConfig.envPref... | FYI this code existed before `astro:env` so I'm afraid this change would be a breaking one. It would be great if you could test on an older version of Astro. To be sure, in `4.9`since `astro:env` was introduced in `4.10` | function getPrivateEnv(
fullEnv: Record<string, string>,
astroConfig: AstroConfig,
useRawValues: boolean,
): Record<string, string> {
const viteConfig = astroConfig.vite;
let envPrefixes: string[] = ['PUBLIC_'];
if (viteConfig.envPrefix) {
envPrefixes = Array.isArray(viteConfig.envPrefix)
? viteConfig.envPre... | @@ -30,7 +31,7 @@ function getPrivateEnv(
}
// Boolean values should be inlined to support `export const prerender`
// We already know that these are NOT sensitive values, so inlining is safe
- if (value === '0' || value === '1' || value === 'true' || value === 'false') {
+ if (coerceValues && (val... | packages/astro/src/env/env-loader.ts | 26 | TypeScript | 0.643 | suggestion | 220 | 49 | 51 | false | don't coerce environment variable values when populating import.meta.env | 13,971 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | adamhl8 |
fullEnv: Record<string, string>,
astroConfig: AstroConfig,
coerceValues: boolean,
): Record<string, string> {
const viteConfig = astroConfig.vite;
let envPrefixes: string[] = ['PUBLIC_'];
if (viteConfig.envPrefix) {
envPrefixes = Array.isArray(viteConfig.envPrefix)
? viteConfig.envPrefix
: [viteConfig.env... | I think it's important to note in docs/changeset that this only affects `import.meta.env` when the value is taken from `process.env` (ie. doesn't happen if you set a var in `.env`, but happens if you set it inline while running the command) | fullEnv: Record<string, string>,
astroConfig: AstroConfig,
useRawValues: boolean,
): Record<string, string> {
const viteConfig = astroConfig.vite;
let envPrefixes: string[] = ['PUBLIC_'];
if (viteConfig.envPrefix) {
envPrefixes = Array.isArray(viteConfig.envPrefix)
? viteConfig.envPrefix
: [viteConfig.env... | @@ -30,7 +31,10 @@ function getPrivateEnv(
}
// Boolean values should be inlined to support `export const prerender`
// We already know that these are NOT sensitive values, so inlining is safe
- if (value === '0' || value === '1' || value === 'true' || value === 'false') {
+ if (
+ coerceValues... | packages/astro/src/env/env-loader.ts | 26 | TypeScript | 0.643 | suggestion | 240 | 51 | 51 | false | don't coerce environment variable values when populating import.meta.env | 13,971 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | adamhl8 |
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.x
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.rawEnvValues
* @type {boolean}
* @default `false`
... | ```suggestion
* This flag aligns `import.meta.env`'s behavior in Astro with [Vite](https://vite.dev/guide/env-and-mode.html#env-variables).
*
* See the [experimental raw environment variables guide](/en/reference/experimental-flags/raw-env-values/) for more information.
``` |
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.x
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.rawEnvValues
* @type {boolean}
* @default `false`
... | @@ -2435,6 +2435,23 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
*
*/
liveContentCollections?: boolean;
+
+ /**
+ * @name experimental.rawEnvValues
+ * @type {boolean}
+ * @default `false`
+ * @version 5.12
+ * @description
+ *
+ * Disables coercion of `import.meta.env` ... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.786 | suggestion | 287 | 51 | 51 | false | don't coerce environment variable values when populating import.meta.env | 13,971 | withastro/astro | 47,179 | TypeScript | sarah11918 | adamhl8 |
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.x
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.rawEnvValues
* @type {boolean}
* @default `false`
* @vers... | ```suggestion
* See the [experimental raw environment variables guide](https://docs.astro.build/en/reference/experimental-flags/raw-env-values/) for more information.
``` | * @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.x
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.rawEnvValues
* @type {boolean}
* @default `false`
* @vers... | @@ -2435,6 +2435,25 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
*
*/
liveContentCollections?: boolean;
+
+ /**
+ * @name experimental.rawEnvValues
+ * @type {boolean}
+ * @default `false`
+ * @version 5.12
+ * @description
+ *
+ * Disables coercion of `import.meta.env` ... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.714 | suggestion | 175 | 51 | 51 | false | don't coerce environment variable values when populating import.meta.env | 13,971 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | adamhl8 |
shouldRestart = settings.preferences.ignoreNextPreferenceReload ? false : true;
settings.preferences.ignoreNextPreferenceReload = false;
}
}
if (!shouldRestart && settings.watchFiles.length > 0) {
// If the config file didn't change, check if any of the watched files changed.
shouldRestart = settings.wa... | ```suggestion
"Astro's Content Security Policy (CSP) does not work in development mode. To verify your CSP implementation, build the project and run the preview server.",
```
what about something like this? Probably simpler to just say "doesn't work."
| shouldRestart = settings.preferences.ignoreNextPreferenceReload ? false : true;
settings.preferences.ignoreNextPreferenceReload = false;
}
}
if (!shouldRestart && settings.watchFiles.length > 0) {
// If the config file didn't change, check if any of the watched files changed.
shouldRestart = settings.wa... | @@ -77,6 +77,12 @@ async function restartContainer(container: Container): Promise<Container | Error
try {
const { astroConfig } = await resolveConfig(container.inlineConfig, 'dev', container.fs);
+ if (astroConfig.experimental.csp) {
+ logger.info(
+ 'config',
+ "Be aware that due to the nature of the d... | packages/astro/src/core/dev/restart.ts | 26 | TypeScript | 0.929 | security | 258 | 51 | 51 | false | fix: add info message in dev | 13,987 | withastro/astro | 47,179 | TypeScript | sarah11918 | ematipico |
let latestModified: Date | undefined;
for (const entry of processedEntries) {
if (entry.cacheHint) {
if (entry.cacheHint.tags) {
entry.cacheHint.tags.forEach((tag) => entryTags.add(tag));
}
if (typeof entry.cacheHint.maxAge === 'number') {
if (minMaxAge === undefined || ent... | You might want to add a comment explaining why the use of `Set` instead of a simple array | let latestModified: Date | undefined;
for (const entry of processedEntries) {
if (entry.cacheHint) {
if (entry.cacheHint.tags) {
entry.cacheHint.tags.forEach((tag) => entryTags.add(tag));
}
if (typeof entry.cacheHint.maxAge === 'number') {
if (minMaxAge === undefined || ent... | @@ -529,33 +531,44 @@ export function createGetLiveCollection({
if (processedEntries.length > 0) {
const entryTags = new Set<string>();
let minMaxAge: number | undefined;
+ let latestModified: Date | undefined;
for (const entry of processedEntries) {
if (entry.cacheHint) {
if (entry... | packages/astro/src/content/runtime.ts | 26 | TypeScript | 0.429 | suggestion | 89 | 51 | 51 | false | feat: add lastModified field to live collection cache hints | 13,999 | withastro/astro | 47,179 | TypeScript | ematipico | ascorbic |
if (latestModified === undefined || entry.cacheHint.lastModified > latestModified) {
latestModified = entry.cacheHint.lastModified;
}
}
}
}
// Merge collection and entry cache hints
if (entryTags.size > 0 || minMaxAge !== undefined || latestModified || cacheHint) {
con... | Out of curiosity, do timezones have a role in this logic? | if (latestModified === undefined || entry.cacheHint.lastModified > latestModified) {
latestModified = entry.cacheHint.lastModified;
}
}
}
}
// Merge collection and entry cache hints
if (entryTags.size > 0 || minMaxAge !== undefined || latestModified || cacheHint) {
con... | @@ -529,33 +531,44 @@ export function createGetLiveCollection({
if (processedEntries.length > 0) {
const entryTags = new Set<string>();
let minMaxAge: number | undefined;
+ let latestModified: Date | undefined;
for (const entry of processedEntries) {
if (entry.cacheHint) {
if (entry... | packages/astro/src/content/runtime.ts | 26 | TypeScript | 0.214 | question | 58 | 51 | 51 | false | feat: add lastModified field to live collection cache hints | 13,999 | withastro/astro | 47,179 | TypeScript | ematipico | ascorbic |
describe('without streaming', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/headers/',
output: 'server',
adapter: nodejs({ mode: 'middleware', experimentalDisableStreaming: true }),
});
await fixture.build();
});
it('sends a single chunk', async () => {
con... | Can you also check that it sets content-length and doesn't set transfer-encoding to chunked? |
describe('without streaming', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/headers/',
output: 'server',
adapter: nodejs({ mode: 'middleware', experimentalDisableStreaming: true }),
});
await fixture.build();
});
// TODO: needs e2e tests to check real headers... | @@ -7,124 +7,169 @@ describe('Node Adapter Headers', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
- before(async () => {
- fixture = await loadFixture({
- root: './fixtures/headers/',
- output: 'server',
- adapter: nodejs({ mode: 'middleware' }),
+ describe('streaming', () => {
+ bef... | packages/integrations/node/test/headers.test.js | 26 | JavaScript | 0.214 | question | 92 | 46 | 48 | false | feat(node): experimentalDisableStreaming | 14,012 | withastro/astro | 47,179 | TypeScript | ascorbic | florian-lefebvre |
import type { RewritePayload } from '../../types/public/common.js';
import type { AstroConfig } from '../../types/public/config.js';
import type { RouteData } from '../../types/public/internal.js';
import { shouldAppendForwardSlash } from '../build/util.js';
import { originPathnameSymbol } from '../constants.js';
impor... | During build mode, in the server output, statically generated pages are prefixed with `client/` (or whatever is configured in `build.client`). This was the main culprit of i18n fallback rewrites not working in server mode — they simply didn't match in the `findRouteToRewrite` function.
My fix uses `buildClient` from... | import type { RewritePayload } from '../../types/public/common.js';
import type { AstroConfig } from '../../types/public/config.js';
import type { RouteData } from '../../types/public/internal.js';
import { shouldAppendForwardSlash } from '../build/util.js';
import { originPathnameSymbol } from '../constants.js';
impor... | @@ -22,7 +22,7 @@ type FindRouteToRewrite = {
trailingSlash: AstroConfig['trailingSlash'];
buildFormat: AstroConfig['build']['format'];
base: AstroConfig['base'];
- outDir: AstroConfig['outDir'] | string;
+ outDir: AstroConfig['outDir'] | AstroConfig['build']['client'] | string; | packages/astro/src/core/routing/rewrite.ts | 25 | TypeScript | 0.643 | suggestion | 536 | 50 | 50 | false | fix i18n fallback rewrites failing in server mode | 14,017 | withastro/astro | 47,179 | TypeScript | dmgawel | dmgawel |
if (config.type !== LIVE_CONTENT_TYPE) {
throw new AstroError({
...AstroErrorData.LiveContentConfigError,
message: AstroErrorData.LiveContentConfigError.message(
'Collections in a live config file must have a type of `live`.',
importerFilename,
),
});
}
if (!config.loader) {
throw new AstroE... | ```suggestion
'Live collection loaders must have `loadCollection()` and `loadEntry()` methods. Please check that you are not using a loader intended for build-time collections',
```
maybe something like this? Asking a question when it's not possible to react to the answer feels maybe less helpful than being expl... |
if (config.type !== LIVE_CONTENT_TYPE) {
throw new AstroError({
...AstroErrorData.LiveContentConfigError,
message: AstroErrorData.LiveContentConfigError.message(
'Collections in a live config file must have a type of `live`.',
importerFilename,
),
});
}
if (!config.loader) {
throw new AstroE... | @@ -141,6 +144,17 @@ export function defineLiveCollection<
),
});
}
+
+ if(!config.loader.loadCollection || !config.loader.loadEntry) {
+ throw new AstroError({
+ ...AstroErrorData.LiveContentConfigError,
+ message: AstroErrorData.LiveContentConfigError.message(
+ 'Live collection loaders must have `lo... | packages/astro/src/content/config.ts | 26 | TypeScript | 0.786 | question | 350 | 51 | 51 | false | Make "type" optional when defining live collections | 14,019 | withastro/astro | 47,179 | TypeScript | sarah11918 | ascorbic |
};
interface CollectionFilter {
addToAge?: number;
returnInvalid?: boolean;
}
type EntryFilter = {
id: keyof typeof entries;
addToAge?: number;
};
const entries = {
'123': { id: '123', data: { title: 'Page 123', age: 10 } },
'456': { id: '456', data: { title: 'Page 456', age: 20 } },
'789': { id: '789', data:... | ```suggestion
const loader: LiveLoader<Entry, EntryFilter, CollectionFilter, CustomError> = {
``` | };
interface CollectionFilter {
addToAge?: number;
returnInvalid?: boolean;
}
type EntryFilter = {
id: keyof typeof entries;
addToAge?: number;
};
const entries = {
'123': { id: '123', data: { title: 'Page 123', age: 10 } },
'456': { id: '456', data: { title: 'Page 456', age: 20 } },
'789': { id: '789', data:... | @@ -30,7 +30,7 @@ class CustomError extends Error {
}
}
-const loader: LiveLoader<Entry, EntryFilter, CollectionFilter, CustomError> = {
+export const loader: LiveLoader<Entry, EntryFilter, CollectionFilter, CustomError> = { | packages/astro/test/fixtures/live-loaders/src/live.config.ts | 26 | TypeScript | 0.714 | suggestion | 99 | 51 | 51 | false | Make "type" optional when defining live collections | 14,019 | withastro/astro | 47,179 | TypeScript | ascorbic | ascorbic |
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type * as vite from 'vite';
import { prependForwardSlash, slash } from '../../../core/path.js';
import type { ImageMetadata } from '../../types.js';
... | Let's not use `node:crypto`, but let's use the standard [`crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) standard type. We already have this module that exports some useful functions about encryptions:
https://github.com/withastro/astro/blob/main/packages/astro/src/core/encryption.ts
If there ... | import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type * as vite from 'vite';
import { generateContentHash } from '../../../core/encryption.js';
import { prependForwardSlash, slash } from '../../../core/path.js';
import type { ImageMetadata ... | @@ -9,6 +10,17 @@ import { imageMetadata } from '../metadata.js';
type FileEmitter = vite.Rollup.EmitFile;
type ImageMetadataWithContents = ImageMetadata & { contents?: Buffer };
+// Global cache for SVG content deduplication
+// Maps content hash -> { handle: string, filename: string }
+const svgContentCache = new... | packages/astro/src/assets/utils/node/emitAsset.ts | 21 | TypeScript | 0.786 | suggestion | 450 | 46 | 46 | false | fix(astro): fix svg content-based deduplication | 14,031 | withastro/astro | 47,179 | TypeScript | ematipico | jp-knj |
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type * as vite from 'vite';
import { prependForwardSlash, slash } from '../../../core/path.js';
import type { ImageMetadata } from '../../types.js';
... | Since this is a cache and we don't do any iteration, I think we can use a [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instead. However, a `WeakMap` needs an object as a key. So maybe we can create a new object e.g. `SvgCacheKey = { hash: string, fileData: Buffer... | import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type * as vite from 'vite';
import { generateContentHash } from '../../../core/encryption.js';
import { prependForwardSlash, slash } from '../../../core/path.js';
import type { ImageMetadata ... | @@ -9,6 +10,17 @@ import { imageMetadata } from '../metadata.js';
type FileEmitter = vite.Rollup.EmitFile;
type ImageMetadataWithContents = ImageMetadata & { contents?: Buffer };
+// Global cache for SVG content deduplication
+// Maps content hash -> { handle: string, filename: string }
+const svgContentCache = new... | packages/astro/src/assets/utils/node/emitAsset.ts | 15 | TypeScript | 0.643 | performance | 377 | 40 | 40 | false | fix(astro): fix svg content-based deduplication | 14,031 | withastro/astro | 47,179 | TypeScript | ematipico | jp-knj |
}
/**
* Generates an SHA-256 digest of the given string.
* @param {string} data The string to hash.
* @param {CspAlgorithm} algorithm The algorithm to use.
*/
export async function generateCspDigest(data: string, algorithm: CspAlgorithm): Promise<CspHash> {
const hashBuffer = await crypto.subtle.digest(algorithm,... | The function `generateCspDigest` at line 123 does the same thing you're doing here.
```suggestion
return encodeBase64(hashArray);
``` | import { decodeBase64, decodeHex, encodeBase64, encodeHexUpperCase } from '@oslojs/encoding';
import type { CspAlgorithm } from '../types/public/index.js';
import { ALGORITHMS, type CspHash } from './csp/config.js';
// Chose this algorithm for no particular reason, can change.
// This algo does check against text mani... | @@ -123,3 +123,17 @@ export async function generateCspDigest(data: string, algorithm: CspAlgorithm):
const hash = encodeBase64(new Uint8Array(hashBuffer));
return `${ALGORITHMS[algorithm]}${hash}`;
}
+
+/**
+ * Generate SHA-256 hash of buffer content for deduplication
+ * @param {ArrayBuffer} data The buffer data ... | packages/astro/src/core/encryption.ts | 26 | TypeScript | 0.714 | suggestion | 139 | 28 | 137 | false | fix(astro): fix svg content-based deduplication | 14,031 | withastro/astro | 47,179 | TypeScript | ematipico | jp-knj |
const decryptedBuffer = await crypto.subtle.decrypt(
{
name: ALGORITHM,
iv,
},
key,
dataArray,
);
const decryptedString = decoder.decode(decryptedBuffer);
return decryptedString;
}
/**
* Generates an SHA-256 digest of the given string.
* @param {string} data The string to hash.
* @param {CspAlgori... | ```suggestion
* Generate SHA-256 hash of a buffer.
```
The function doesn't have anything to do with "content duplication". | const decryptedBuffer = await crypto.subtle.decrypt(
{
name: ALGORITHM,
iv,
},
key,
dataArray,
);
const decryptedString = decoder.decode(decryptedBuffer);
return decryptedString;
}
/**
* Generates an SHA-256 digest of the given string.
* @param {string} data The string to hash.
* @param {CspAlgori... | @@ -123,3 +123,17 @@ export async function generateCspDigest(data: string, algorithm: CspAlgorithm):
const hash = encodeBase64(new Uint8Array(hashBuffer));
return `${ALGORITHMS[algorithm]}${hash}`;
}
+
+/**
+ * Generate SHA-256 hash of buffer content for deduplication | packages/astro/src/core/encryption.ts | 26 | TypeScript | 0.714 | suggestion | 130 | 38 | 35 | false | fix(astro): fix svg content-based deduplication | 14,031 | withastro/astro | 47,179 | TypeScript | ematipico | jp-knj |
const existing = svgContentCache.get(key);
if (existing) {
// Reuse existing handle for duplicate SVG content
emittedImage.src = `__ASTRO_ASSET_IMAGE__${existing.handle}__`;
} else {
// First time seeing this SVG content - emit it
const handle = fileEmitter!({
name: filename,
... | There's a bit of repeated code here. Before, it was a few lines, so it was easy to maintain. However, it's now quite long; we should move the code inside a function. | }
const fileMetadata = await imageMetadata(fileData, id);
const emittedImage: Omit<ImageMetadataWithContents, 'fsPath'> = {
src: '',
...fileMetadata,
};
// Private for now, we generally don't want users to rely on filesystem paths, but we need it so that we can maybe remove the original asset from the build... | @@ -62,14 +79,34 @@ export async function emitESMImage(
const filename = path.basename(pathname, path.extname(pathname) + `.${fileMetadata.format}`);
try {
- // fileEmitter throws in dev
- const handle = fileEmitter!({
- name: filename,
- source: await fs.readFile(url),
- type: 'asset',
- });
-
-... | packages/astro/src/assets/utils/node/emitAsset.ts | 26 | TypeScript | 0.429 | suggestion | 166 | 51 | 51 | false | fix(astro): fix svg content-based deduplication | 14,031 | withastro/astro | 47,179 | TypeScript | ematipico | jp-knj |
import path from 'node:path';
import type { CompilerOptions } from 'typescript';
import { normalizePath, type ResolvedConfig, type Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';
type Alias = {
find: RegExp;
replacement: string;
};
/** Returns a list of compiled aliases. ... | ```suggestion
const effectiveBaseUrl = baseUrl ?? (paths ? '.' : undefined);
``` | import path from 'node:path';
import type { CompilerOptions } from 'typescript';
import { normalizePath, type ResolvedConfig, type Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';
type Alias = {
find: RegExp;
replacement: string;
};
/** Returns a list of compiled aliases. ... | @@ -14,10 +14,13 @@ const getConfigAlias = (settings: AstroSettings): Alias[] | null => {
if (!tsConfig || !tsConfigPath || !tsConfig.compilerOptions) return null;
const { baseUrl, paths } = tsConfig.compilerOptions as CompilerOptions;
- if (!baseUrl) return null;
+
+ // If paths exist but baseUrl doesn't, defau... | packages/astro/src/vite-plugin-config-alias/index.ts | 19 | TypeScript | 0.714 | suggestion | 81 | 44 | 44 | false | fix(astro): drop baseUrl requirement for ts-paths | 14,064 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | jp-knj |
let _config: AstroConfig;
let finalBuildOutput: HookParameters<'astro:config:done'>['buildOutput'];
const cloudflareModulePlugin: PluginOption & CloudflareModulePluginExtra = cloudflareModuleLoader(
args?.cloudflareModules ?? true,
);
let _routes: IntegrationResolvedRoute[];
return {
name: '@astrojs/cloudf... | You mentioned wanting a way to add a default for the KV binding name. You could do it by hoisting `const bindingName = args?.sessionKVBindingName ?? 'SESSION';` up to the top level of `createIntegration` where you can use it in all of the hooks | let _config: AstroConfig;
let finalBuildOutput: HookParameters<'astro:config:done'>['buildOutput'];
const cloudflareModulePlugin: PluginOption & CloudflareModulePluginExtra = cloudflareModuleLoader(
args?.cloudflareModules ?? true,
);
let _routes: IntegrationResolvedRoute[];
const SESSION_KV_BINDING_NAME = a... | @@ -159,42 +159,29 @@ export default function createIntegration(args?: Options): AstroIntegration {
logger,
addWatchFile,
addMiddleware,
- createCodegenDir,
}) => {
let session = config.session;
const isBuild = command === 'build';
if (!session?.driver) {
- const sessionDir ... | packages/integrations/cloudflare/src/index.ts | 26 | TypeScript | 0.643 | suggestion | 244 | 51 | 51 | false | refactor astro sessions to use cf kv binding | 14,066 | withastro/astro | 47,179 | TypeScript | ascorbic | alexanderniebuhr |
const cloudflareModulePlugin: PluginOption & CloudflareModulePluginExtra = cloudflareModuleLoader(
args?.cloudflareModules ?? true,
);
let _routes: IntegrationResolvedRoute[];
const SESSION_KV_BINDING_NAME = args?.sessionKVBindingName ?? 'SESSION';
return {
name: '@astrojs/cloudflare',
hooks: {
'astro:... | ```suggestion
`Enabling sessions with Cloudflare KV with the "${SESSION_KV_BINDING_NAME}" KV binding.`,
```
I think that's redundant now. It only said "for production" before because it wasn't used in dev. | const cloudflareModulePlugin: PluginOption & CloudflareModulePluginExtra = cloudflareModuleLoader(
args?.cloudflareModules ?? true,
);
let _routes: IntegrationResolvedRoute[];
const SESSION_KV_BINDING_NAME = args?.sessionKVBindingName ?? 'SESSION';
return {
name: '@astrojs/cloudflare',
hooks: {
'astro:... | @@ -159,42 +161,27 @@ export default function createIntegration(args?: Options): AstroIntegration {
logger,
addWatchFile,
addMiddleware,
- createCodegenDir,
}) => {
let session = config.session;
const isBuild = command === 'build';
if (!session?.driver) {
- const sessionDir ... | packages/integrations/cloudflare/src/index.ts | 26 | TypeScript | 0.857 | suggestion | 214 | 51 | 51 | false | refactor astro sessions to use cf kv binding | 14,066 | withastro/astro | 47,179 | TypeScript | ascorbic | alexanderniebuhr |
import './astro-jsx';
import type { OmitIndexSignature, Simplify } from './dist/type-utils.js';
import type { AstroBuiltinAttributes } from './dist/types/public/elements.js';
import type { BundledLanguage, SpecialLanguage, LanguageRegistration } from 'shiki';
/** Any supported HTML or SVG element name, as defined by t... | I think we need to move this to a file in `src/types/public` instead, I need to investigate | import './astro-jsx';
import type { OmitIndexSignature, Simplify } from './dist/type-utils.js';
import type { AstroBuiltinAttributes } from './dist/types/public/elements.js';
/** Any supported HTML or SVG element name, as defined by the HTML specification */
export type HTMLTag = keyof astroHTML.JSX.DefinedIntrinsicEl... | @@ -1,6 +1,7 @@
import './astro-jsx';
import type { OmitIndexSignature, Simplify } from './dist/type-utils.js';
import type { AstroBuiltinAttributes } from './dist/types/public/elements.js';
+import type { BundledLanguage, SpecialLanguage, LanguageRegistration } from 'shiki'; | packages/astro/types.d.ts | 4 | TypeScript | 0.571 | refactor | 91 | 29 | 29 | false | fix: export lang types for use in custom component | 14,071 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | Grisoly |
outDir = new URL(config.outDir, rootDir);
let session = config.session;
if (!session?.driver) {
logger.info('Enabling sessions with Netlify Blobs');
session = {
...session,
driver: 'netlify-blobs',
options: {
name: 'astro-sessions',
consistency: 'strong',
... | Waiting on https://github.com/netlify/primitives/pull/348 |
outDir = new URL(config.outDir, rootDir);
let session = config.session;
if (!session?.driver) {
logger.info('Enabling sessions with Netlify Blobs');
session = {
...session,
driver: 'netlify-blobs',
options: {
name: 'astro-sessions',
consistency: 'strong',
... | @@ -564,6 +581,25 @@ export default function netlifyIntegration(
};
}
+ const features = integrationConfig?.devFeatures;
+
+ const vitePluginOptions: NetlifyPluginOptions = {
+ images: {
+ // We don't need to disable the feature, because if the user disables it
+ // we'll disable the wh... | packages/integrations/netlify/src/index.ts | 26 | TypeScript | 0.214 | suggestion | 57 | 51 | 51 | false | fix: regressions in Netlify adapter | 14,078 | withastro/astro | 47,179 | TypeScript | ascorbic | ascorbic |
import type { ImageMetadata } from './types.js';
export interface SvgComponentProps {
meta: ImageMetadata;
attributes: Record<string, string>;
children: string;
}
export function createSvgComponent({ meta, attributes, children }: SvgComponentProps) {
const Component = createComponent((_, props) => {
const norma... | Should it be `toString` instead? | import type { ImageMetadata } from './types.js';
export interface SvgComponentProps {
meta: ImageMetadata;
attributes: Record<string, string>;
children: string;
}
export function createSvgComponent({ meta, attributes, children }: SvgComponentProps) {
const Component = createComponent((_, props) => {
const norma... | @@ -29,6 +29,11 @@ export function createSvgComponent({ meta, attributes, children }: SvgComponentP
});
}
+ Object.defineProperty(Component, 'toJSON', { | packages/astro/src/assets/runtime.ts | 26 | TypeScript | 0.286 | question | 32 | 51 | 51 | false | fix: make SVG ImageMetadata serializable | 14,112 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | ascorbic |
geo: parseBase64JSON('x-nf-geo') ?? {
city: 'Mock City',
country: { code: 'mock', name: 'Mock Country' },
subdivision: { code: 'SD', name: 'Mock Subdivision' },
timezone: 'UTC',
longitude: 0,
latitude: 0,
},
ip:
typeof req.headers['x-nf-client-connection-ip'] === 'string'
? req... | Could you do `satisfies Context['flags']` to make sure the value is not wrong? | geo: parseBase64JSON('x-nf-geo') ?? {
city: 'Mock City',
country: { code: 'mock', name: 'Mock Country' },
subdivision: { code: 'SD', name: 'Mock Subdivision' },
timezone: 'UTC',
longitude: 0,
latitude: 0,
},
ip:
typeof req.headers['x-nf-client-connection-ip'] === 'string'
? req... | @@ -539,8 +539,10 @@ export default function netlifyIntegration(
get cookies(): never {
throw new Error('Please use Astro.cookies instead.');
},
- // @ts-expect-error This is not currently included in the public Netlify types
- flags: undefined,
+ flags: {
+ get: () => undefined,
+ evaluation... | packages/integrations/netlify/src/index.ts | 26 | TypeScript | 0.429 | bug | 78 | 51 | 51 | false | fix: adds mock feature flags to the Netlify dev context object | 14,120 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | ascorbic |
if (!existsSync(cacheDir)) {
await mkdir(cacheDir, { recursive: true });
}
let config = {
version: 1,
projectId: randomUUID(),
workspaceRoot: fileURLToPath(settings.config.root),
};
if (existsSync(configPath)) {
try {
config = JSON.parse(await readFile(con... | This code seems a bit funny? Why is there `config` with a `version` property different from the expected format returned in the response? Which then is never used again?
Can’t we `response.end(JSON.stringify(config))` instead of redefining the object?
And `existsSync()` followed by `readFile()` is usually conside... | if (!existsSync(cacheDir)) {
await mkdir(cacheDir, { recursive: true });
}
let config;
try {
config = JSON.parse(await readFile(configPath, 'utf-8'));
} catch {
config = {
version: '1.0',
projectId: randomUUID(),
workspaceRoot: fileURLToPath(settings.conf... | @@ -135,6 +139,50 @@ export default function createVitePluginAstroServer({
route: '',
handle: trailingSlashMiddleware(settings),
});
+
+ // Chrome DevTools workspace handler
+ // See https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md
... | packages/astro/src/vite-plugin-astro-server/plugin.ts | 26 | TypeScript | 1 | bug | 1,316 | 51 | 51 | false | feat: add automatic chrome workspace handling | 14,122 | withastro/astro | 47,179 | TypeScript | delucis | ascorbic |
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.rawEnvValues
* @type {boolean}
* @default `false`
* @version 5.12
* @description
*
* Disables coercion of `import.meta.env` values that are populated from `... | This content looks good, and I'd suggest should go in both the changeset and is pretty much all that's needed in a new docs PR at `reference/experimental-flags/chrome-dev-tools/` or something like that? | * @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.rawEnvValues
* @type {boolean}
* @default `false`
* @version 5.12
* @description
*
* Disables coercion of `import.meta.env` values that are populated from `... | @@ -2458,6 +2458,31 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* See the [experimental raw environment variables guide](https://docs.astro.build/en/reference/experimental-flags/raw-env-values/) for more information.
*/
rawEnvValues?: boolean;
+ /**
+ * @name experimental.chromeDev... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.643 | question | 202 | 51 | 51 | false | feat: add automatic chrome workspace handling | 14,122 | withastro/astro | 47,179 | TypeScript | sarah11918 | ascorbic |
* @type {boolean}
* @default `false`
* @version 5.12
* @description
*
* Disables coercion of `import.meta.env` values that are populated from `process.env`, allowing you to use the raw value.
*
* By default, Astro converts your environment variables used through `import.meta.env` in some cases, ... | ```suggestion
* When enabled, the dev server will automatically configure a [Chrome DevTools workspace](https://developer.chrome.com/docs/devtools/workspaces) for your project,
```
Let's inline this link to define what the workspaces are, and let the "see more info" be the link to our own experimental docs, where... | * @type {boolean}
* @default `false`
* @version 5.12
* @description
*
* Disables coercion of `import.meta.env` values that are populated from `process.env`, allowing you to use the raw value.
*
* By default, Astro converts your environment variables used through `import.meta.env` in some cases, ... | @@ -2458,6 +2458,31 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* See the [experimental raw environment variables guide](https://docs.astro.build/en/reference/experimental-flags/raw-env-values/) for more information.
*/
rawEnvValues?: boolean;
+ /**
+ * @name experimental.chromeDev... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.786 | suggestion | 377 | 51 | 51 | false | feat: add automatic chrome workspace handling | 14,122 | withastro/astro | 47,179 | TypeScript | sarah11918 | ascorbic |
* See the [experimental raw environment variables guide](https://docs.astro.build/en/reference/experimental-flags/raw-env-values/) for more information.
*/
rawEnvValues?: boolean;
/**
* @name experimental.chromeDevtoolsWorkspace
* @type {boolean}
* @default `false`
* @version 5.13
* @descriptio... | ```suggestion
* See the [experimental Chrome DevTools workspace feature documentation](https://docs.astro.build/en/reference/experimental-flags/chrome-devtools-workspace/) for more information.
``` | * See the [experimental raw environment variables guide](https://docs.astro.build/en/reference/experimental-flags/raw-env-values/) for more information.
*/
rawEnvValues?: boolean;
/**
* @name experimental.chromeDevtoolsWorkspace
* @type {boolean}
* @default `false`
* @version 5.13
* @descriptio... | @@ -2458,6 +2458,31 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* See the [experimental raw environment variables guide](https://docs.astro.build/en/reference/experimental-flags/raw-env-values/) for more information.
*/
rawEnvValues?: boolean;
+ /**
+ * @name experimental.chromeDev... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.786 | suggestion | 202 | 51 | 51 | false | feat: add automatic chrome workspace handling | 14,122 | withastro/astro | 47,179 | TypeScript | sarah11918 | ascorbic |
? viteConfig.envPrefix
: [viteConfig.envPrefix];
}
const privateEnv: Record<string, string> = {};
for (const key in fullEnv) {
// Ignore public env var
if (!isValidIdentifierRe.test(key) || envPrefixes.some((prefix) => key.startsWith(prefix))) {
continue;
}
// Only replace with process.env if not s... | This could be quite confusing if boolean values are the only ones that use build-time values while the others use runtime | }): Record<string, string> {
let envPrefixes: string[] = ['PUBLIC_'];
if (viteConfig.envPrefix) {
envPrefixes = Array.isArray(viteConfig.envPrefix)
? viteConfig.envPrefix
: [viteConfig.envPrefix];
}
const privateEnv: Record<string, string> = {};
for (const key in fullEnv) {
// Ignore public env var
if... | @@ -22,45 +25,51 @@ function getPrivateEnv(
const privateEnv: Record<string, string> = {};
for (const key in fullEnv) {
// Ignore public env var
- if (isValidIdentifierRe.test(key) && envPrefixes.every((prefix) => !key.startsWith(prefix))) {
- if (typeof process.env[key] !== 'undefined') {
- let value = pr... | packages/astro/src/env/env-loader.ts | 26 | TypeScript | 0.429 | suggestion | 121 | 51 | 51 | false | feat: experimental static import.meta.env | 14,173 | withastro/astro | 47,179 | TypeScript | ascorbic | florian-lefebvre |
* ```css
* body {background:red} body {background:#ff0}
* ```
*
*/
preserveScriptOrder?: boolean;
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveCont... | This should mention the difference with boolean values if that's what's happening | * ```css
* body {background:red} body {background:#ff0}
* ```
*
*/
preserveScriptOrder?: boolean;
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveCont... | @@ -2433,31 +2433,30 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
- * @version 5.x
+ * @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveContentCo... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.286 | suggestion | 81 | 51 | 51 | false | feat: experimental static import.meta.env | 14,173 | withastro/astro | 47,179 | TypeScript | ascorbic | florian-lefebvre |
import { fileURLToPath } from 'node:url';
import { loadEnv } from 'vite';
import type { AstroConfig } from '../types/public/index.js';
// Match valid JS variable names (identifiers), which accepts most alphanumeric characters,
// except that the first character cannot be a number.
const isValidIdentifierRe = /^[_$a-zA... | The logic of the function has changed. Could we add some JsDoc so we keep up with the business logic? | import { fileURLToPath } from 'node:url';
import { loadEnv } from 'vite';
import type { AstroConfig } from '../types/public/index.js';
// Match valid JS variable names (identifiers), which accepts most alphanumeric characters,
// except that the first character cannot be a number.
const isValidIdentifierRe = /^[_$a-zA... | @@ -6,12 +6,15 @@ import type { AstroConfig } from '../types/public/index.js';
// except that the first character cannot be a number.
const isValidIdentifierRe = /^[_$a-zA-Z][\w$]*$/;
-function getPrivateEnv(
- fullEnv: Record<string, string>,
- astroConfig: AstroConfig,
- useRawValues: boolean,
-): Record<string, ... | packages/astro/src/env/env-loader.ts | 13 | TypeScript | 0.429 | question | 102 | 38 | 38 | false | feat: experimental static import.meta.env | 14,173 | withastro/astro | 47,179 | TypeScript | ematipico | florian-lefebvre |
preserveScriptOrder?: boolean;
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.staticImportMetaEnv
* ... | ```suggestion
* Currently, non-public `import.meta.env` environment variables are replaced by a reference to `process.env`. Additionally, Astro may also convert the value type of your environment variables used through `import.meta.env`, which can prevent access to some values such as the strings `"true"` (which is... | preserveScriptOrder?: boolean;
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveContentCollections?: boolean;
/**
* @name experimental.staticImportMetaEnv
* ... | @@ -2433,31 +2433,32 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
- * @version 5.x
+ * @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveContentCo... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 1 | refactor | 834 | 51 | 51 | false | feat: experimental static import.meta.env | 14,173 | withastro/astro | 47,179 | TypeScript | sarah11918 | florian-lefebvre |
* ```css
* body {background:red} body {background:#ff0}
* ```
*
*/
preserveScriptOrder?: boolean;
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveCont... | Should this sentence be updated too? | * ```css
* body {background:red} body {background:#ff0}
* ```
*
*/
preserveScriptOrder?: boolean;
/**
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
* @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveCont... | @@ -2433,31 +2433,31 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* @name experimental.liveContentCollections
* @type {boolean}
* @default `false`
- * @version 5.x
+ * @version 5.10
* @description
* Enables the use of live content collections.
*
*/
liveContentCo... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.143 | question | 36 | 51 | 51 | false | feat: experimental static import.meta.env | 14,173 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
*
* - 'middleware' - Build to middleware, to be used within another Node.js server, such as Express.
* - 'standalone' - Build to a standalone server. The server starts up just by running the built script.
*/
mode: 'middleware' | 'standalone';
/**
* Disables HTML streaming. This is useful for example if ther... | ```suggestion
experimentalErrorPageHost?: string | URL;
```
Seeing the changeset, it makes sense to accept a `URL` too. What do you think? Also, it would be nice to show an example of what the option can accept. | *
* - 'middleware' - Build to middleware, to be used within another Node.js server, such as Express.
* - 'standalone' - Build to a standalone server. The server starts up just by running the built script.
*/
mode: 'middleware' | 'standalone';
/**
* Disables HTML streaming. This is useful for example if ther... | @@ -21,6 +21,16 @@ export interface UserOptions {
* - The CSP header of the static pages is added when CSP support is enabled.
*/
experimentalStaticHeaders?: boolean;
+
+ /**
+ * The host that should be used if the server needs to fetch the prerendered error page.
+ * If not provided, this will default to th... | packages/integrations/node/src/types.ts | 26 | TypeScript | 1 | suggestion | 217 | 47 | 46 | false | feat: add support for specifying a prerendered error page host | 14,188 | withastro/astro | 47,179 | TypeScript | ematipico | ascorbic |
import { AsyncLocalStorage } from 'node:async_hooks';
import { NodeApp } from 'astro/app/node';
import type { Options, RequestHandler } from './types.js';
/**
* Creates a Node.js http listener for on-demand rendered pages, compatible with http.createServer and Connect middleware.
* If the next callback is provided, ... | You should use `URL.canParse` beforehand. If the function returns `false`, we could throw an error or default to `undefined`. Probably an error makes sense. Perhaps we should validate outside of this closure. | import { AsyncLocalStorage } from 'node:async_hooks';
import { NodeApp } from 'astro/app/node';
import type { Options, RequestHandler } from './types.js';
/**
* Creates a Node.js http listener for on-demand rendered pages, compatible with http.createServer and Connect middleware.
* If the next callback is provided, ... | @@ -20,6 +20,16 @@ export function createAppHandler(app: NodeApp): RequestHandler {
console.error(reason);
});
+ const prerenderedErrorPageFetch = options.experimentalErrorPageHost
+ ? (url: string) => {
+ const errorPageUrl = new URL(url);
+ const originUrl = new URL(options.experimentalErrorPageHost!); | packages/integrations/node/src/serve-app.ts | 26 | TypeScript | 0.786 | suggestion | 209 | 51 | 51 | false | feat: add support for specifying a prerendered error page host | 14,188 | withastro/astro | 47,179 | TypeScript | ematipico | ascorbic |
},
supportedAstroFeatures: {
hybridOutput: 'stable',
staticOutput: 'stable',
serverOutput: 'stable',
sharpImageService: 'stable',
i18nDomains: 'experimental',
envGetSecret: 'stable',
},
};
}
export default function createIntegration(userOptions: UserOptions): AstroIntegration {
if (!userOptio... | @ematipico I've done the validation here so it happens early | },
supportedAstroFeatures: {
hybridOutput: 'stable',
staticOutput: 'stable',
serverOutput: 'stable',
sharpImageService: 'stable',
i18nDomains: 'experimental',
envGetSecret: 'stable',
},
};
}
const protocols = ['http:', 'https:'];
export default function createIntegration(userOptions: UserOpti... | @@ -39,6 +39,15 @@ export default function createIntegration(userOptions: UserOptions): AstroIntegr
throw new AstroError(`Setting the 'mode' option is required.`);
}
+ if (
+ userOptions.experimentalErrorPageHost &&
+ !URL.canParse(userOptions.experimentalErrorPageHost)
+ ) {
+ throw new AstroError(
+ `Inva... | packages/integrations/node/src/index.ts | 26 | TypeScript | 0.214 | suggestion | 60 | 51 | 51 | false | feat: add support for specifying a prerendered error page host | 14,188 | withastro/astro | 47,179 | TypeScript | ascorbic | ascorbic |
import { isRunnableDevEnvironment, type ViteDevServer } from 'vite';
import type { RemoteFontProviderModResolver } from '../definitions.js';
export function createBuildRemoteFontProviderModResolver(): RemoteFontProviderModResolver {
return {
resolve(id) {
return import(id);
},
};
}
export function createDevS... | How will this be handled in other dev enviornments? | import type { RunnableDevEnvironment } from 'vite';
import type { RemoteFontProviderModResolver } from '../definitions.js';
export function createBuildRemoteFontProviderModResolver(): RemoteFontProviderModResolver {
return {
resolve(id) {
return import(id);
},
};
}
export function createDevServerRemoteFontPr... | @@ -16,7 +16,11 @@ export function createDevServerRemoteFontProviderModResolver({
}): RemoteFontProviderModResolver {
return {
resolve(id) {
- return server.ssrLoadModule(id);
+ const ssrEnvironment = server.environments.ssr;
+ if (!isRunnableDevEnvironment(ssrEnvironment)) { | packages/astro/src/assets/fonts/implementations/remote-font-provider-mod-resolver.ts | 20 | TypeScript | 0.357 | question | 51 | 27 | 23 | false | refactor: use ssr environment to load modules | 14,191 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
ssrEnvironment.moduleGraph.invalidateModule(mod as unknown as vite.EnvironmentModuleNode);
},
fixStacktrace(err) {
return viteServer.ssrFixStacktrace(err);
},
clientReload() {
viteServer.hot.send({
type: 'full-reload',
path: '*',
});
},
webSocketSend(msg) {
return ssrEnvironment.hot.s... | Ah we missed each other. Same question: what happens in a non-runnable dev environment? | ssrEnvironment.moduleGraph.invalidateModule(mod as unknown as vite.EnvironmentModuleNode);
},
fixStacktrace(err) {
return viteServer.ssrFixStacktrace(err);
},
clientReload() {
viteServer.environments.client.hot.send({
type: 'full-reload',
path: '*',
});
},
webSocketSend(msg) {
return ... | @@ -102,11 +105,18 @@ export function createViteLoader(viteServer: vite.ViteDevServer): ModuleLoader {
});
},
webSocketSend(msg) {
- return viteServer.hot.send(msg);
+ return ssrEnvironment.hot.send(msg);
},
isHttps() {
- return !!viteServer.config.server.https;
+ return !!ssrEnvironment.config.... | packages/astro/src/core/module-loader/vite.ts | 26 | TypeScript | 0.214 | question | 87 | 28 | 28 | false | refactor: use ssr environment to load modules | 14,191 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
if (isWindows) {
let slashed = slash(path);
// Windows like C:/foo/bar
if (!slashed.startsWith('/')) {
slashed = '/' + slashed;
}
return new URL('file://' + slashed);
}
// Unix is easy
return new URL('file://' + path);
}
// this function parses the options from a `Record<string, string>`
// provided ... | Can't we use Zod for this? It has coercion and transformations. | import { LibsqlError } from '@libsql/client';
import { AstroError } from 'astro/errors';
import type { DBColumn } from '../core/types.js';
export function hasPrimaryKey(column: DBColumn) {
return 'primaryKey' in column.schema && !!column.schema.primaryKey;
}
const isWindows = process?.platform === 'win32';
export c... | @@ -34,3 +39,18 @@ export function pathToFileURL(path: string): URL {
// Unix is easy
return new URL('file://' + path);
}
+
+// this function parses the options from a `Record<string, string>`
+// provided from the object conversion of the searchParams and properly
+// verifies that the Config object is providing ... | packages/db/src/runtime/utils.ts | 26 | TypeScript | 0.286 | style | 63 | 28 | 41 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | Fryuni | Adammatthiesen |
return `
import { asDrizzleTable, normalizeDatabaseUrl } from ${RUNTIME_IMPORT};
${clientImport}
const dbUrl = normalizeDatabaseUrl(${JSON.stringify(ASTRO_DATABASE_FILE)}, ${JSON.stringify(dbUrl)});
export const db = createClient({ url: dbUrl });
export * from ${RUNTIME_VIRTUAL_IMPORT};
${getStringifiedTableExpor... | ```suggestion
// Request module to be loaded immediately in process
localExecution?: boolean;
``` | *
* @param localExecution - Whether the DB client is being used in a local execution context (e.g. CLI commands).
* @returns The module import string for the DB client.
*/
function getDBModule(localExecution: boolean) {
return localExecution
? `import { createClient } from '${DB_CLIENTS.node}';`
: `import { cr... | @@ -137,11 +152,13 @@ export function getRemoteVirtualModContents({
appToken,
isBuild,
output,
+ __execute = false, // Used for execute command
}: {
tables: DBTables;
appToken: string;
isBuild: boolean;
output: AstroConfig['output'];
+ __execute?: boolean; | packages/db/src/core/integration/vite-plugin-db.ts | 26 | TypeScript | 0.714 | suggestion | 100 | 51 | 51 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | Fryuni | Adammatthiesen |
import { DB_CLIENTS, VIRTUAL_CLIENT_MODULE_ID } from '../consts.js';
import type { VitePlugin } from '../utils.js';
type VitePluginDBClientParams = {
connectToRemote: boolean;
mode: 'node' | 'web';
};
function getRemoteClientModule(mode: 'node' | 'web') {
switch (mode) {
case 'web': {
return `export { createC... | ```suggestion
case 'web':
return `export { createClient } from '${DB_CLIENTS.web}';`;
``` | import { DB_CLIENTS, VIRTUAL_CLIENT_MODULE_ID } from '../consts.js';
import type { VitePlugin } from '../utils.js';
type VitePluginDBClientParams = {
connectToRemote: boolean;
mode: 'node' | 'web';
};
function getRemoteClientModule(mode: 'node' | 'web') {
switch (mode) {
case 'web':
return `export { createCli... | @@ -0,0 +1,52 @@
+import { DB_CLIENTS, VIRTUAL_CLIENT_MODULE_ID } from '../consts.js';
+import type { VitePlugin } from '../utils.js';
+
+type VitePluginDBClientParams = {
+ connectToRemote: boolean;
+ mode: 'node' | 'web';
+};
+
+function getRemoteClientModule(mode: 'node' | 'web') {
+ switch (mode) {
+ case 'web': {... | packages/db/src/core/integration/vite-plugin-db-client.ts | 13 | TypeScript | 0.571 | suggestion | 94 | 38 | 38 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | Fryuni | Adammatthiesen |
if (existsSync(seedFile)) {
params.seedHandler.inProgress = true;
await params.seedHandler.execute(seedFile);
}
}
if (params.seedHandler.inProgress) {
(params.logger ?? console).info('Seeded database.');
params.seedHandler.inProgress = false;
}
return getLocalVirtualModContents({
... | Can you add some JSDocs that explain the business logic of the function? The new `localExecution` adds some logic that isn't clear to me. For example, it doesn't explain why, when `localExecution` is `true`, we need the node client. It's an assumption that isn't explained. | });
}
await recreateTables(params);
const seedFiles = getResolvedSeedFiles(params);
for await (const seedFile of seedFiles) {
// Use `addWatchFile()` to invalidate the `astro:db` module
// when a seed file changes.
this.addWatchFile(fileURLToPath(seedFile));
if (existsSync(seedFile)) {
... | @@ -117,15 +117,31 @@ export function getConfigVirtualModContents() {
return `export * from ${RUNTIME_VIRTUAL_IMPORT}`;
}
-export function getLocalVirtualModContents({ tables, root }: { tables: DBTables; root: URL }) {
+export function getLocalVirtualModContents({
+ tables,
+ root,
+ localExecution = false,
+}: { | packages/db/src/core/integration/vite-plugin-db.ts | 26 | TypeScript | 0.571 | suggestion | 274 | 51 | 51 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | ematipico | Adammatthiesen |
${clientImport}
const dbUrl = normalizeDatabaseUrl(${JSON.stringify(ASTRO_DATABASE_FILE)}, ${JSON.stringify(dbUrl)});
export const db = createClient({ url: dbUrl });
export * from ${RUNTIME_VIRTUAL_IMPORT};
${getStringifiedTableExports(tables)}`;
}
export function getRemoteVirtualModContents({
tables,
appToken,
... | Hence my previous comment. Why do we need the node client? | function getDBModule(localExecution: boolean) {
return localExecution
? `import { createClient } from '${DB_CLIENTS.node}';`
: `import { createClient } from '${VIRTUAL_CLIENT_MODULE_ID}';`;
}
export function getLocalVirtualModContents({
tables,
root,
localExecution,
}: {
tables: DBTables;
root: URL;
/**
*... | @@ -117,15 +117,31 @@ export function getConfigVirtualModContents() {
return `export * from ${RUNTIME_VIRTUAL_IMPORT}`;
}
-export function getLocalVirtualModContents({ tables, root }: { tables: DBTables; root: URL }) {
+export function getLocalVirtualModContents({
+ tables,
+ root,
+ localExecution = false,
+}: {
... | packages/db/src/core/integration/vite-plugin-db.ts | 26 | TypeScript | 0.214 | question | 59 | 51 | 51 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | ematipico | Adammatthiesen |
return `
import { asDrizzleTable, normalizeDatabaseUrl } from ${RUNTIME_IMPORT};
${clientImport}
const dbUrl = normalizeDatabaseUrl(${JSON.stringify(ASTRO_DATABASE_FILE)}, ${JSON.stringify(dbUrl)});
export const db = createClient({ url: dbUrl });
export * from ${RUNTIME_VIRTUAL_IMPORT};
${getStringifiedTableExport... | If possible, I would avoid the `?` here. Why? Because it's an internal code, and by adding `?` we might miss code paths that might require `true` instead. This is usually a pattern I follow inside code that isn't exposed to the user: the compiler fails all the instances of the code, and forces me to update them all. Wo... | * @returns The module import string for the DB client.
*/
function getDBModule(localExecution: boolean) {
return localExecution
? `import { createClient } from '${DB_CLIENTS.node}';`
: `import { createClient } from '${VIRTUAL_CLIENT_MODULE_ID}';`;
}
export function getLocalVirtualModContents({
tables,
root,
... | @@ -137,11 +153,14 @@ export function getRemoteVirtualModContents({
appToken,
isBuild,
output,
+ localExecution = false, // Used for execute command
}: {
tables: DBTables;
appToken: string;
isBuild: boolean;
output: AstroConfig['output'];
+ // Request module to be loaded immediately in process
+ loc... | packages/db/src/core/integration/vite-plugin-db.ts | 26 | TypeScript | 0.643 | bug | 376 | 51 | 51 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | ematipico | Adammatthiesen |
// In production build, always read the runtime environment variable.
return `process.env.ASTRO_DB_APP_TOKEN`;
} else {
// Static mode or prerendering needs the local app token.
return `process.env.ASTRO_DB_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
}
} else {
return JSON.stringify(appToken);... | To me, using a node client for a remote feels like an error. However, I am sure you think it's not. Is it because the execution of commands can be done only locally? If so, then I have two suggestions:
- commands shouldn't call `getRemoteVirtualModContents`
- add some JsDoc to `getRemoteVirtualModContents` that expla... |
${clientImport}
const dbUrl = normalizeDatabaseUrl(${JSON.stringify(ASTRO_DATABASE_FILE)}, ${JSON.stringify(dbUrl)});
export const db = createClient({ url: dbUrl });
export * from ${RUNTIME_VIRTUAL_IMPORT};
${getStringifiedTableExports(tables)}`;
}
export function getRemoteVirtualModContents({
tables,
appToken,
... | @@ -170,10 +189,17 @@ export function getRemoteVirtualModContents({
}
}
+ // If this is for the execute command, we need to import the client directly instead of using the runtime only virtual module.
+ const clientImport = localExecution
+ ? `import { createClient } from '${DB_CLIENTS.node}';`
+ : `import { c... | packages/db/src/core/integration/vite-plugin-db.ts | 26 | TypeScript | 0.786 | suggestion | 379 | 51 | 51 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | ematipico | Adammatthiesen |
import type { Config as LibSQLConfig } from '@libsql/client';
import z from 'zod';
const rawLibSQLOptions = z.record(z.string());
const parseNumber = (value: string) => z.coerce.number().parse(value);
const parseBoolean = (value: string) => z.coerce.boolean().parse(value);
const booleanValues = ['true', 'false'];
/... | ```suggestion
// parse a value that should be a boolean, but could be a valueless variable:
``` | import type { Config as LibSQLConfig } from '@libsql/client';
import z from 'zod';
const rawLibSQLOptions = z.record(z.string());
const parseNumber = (value: string) => z.coerce.number().parse(value);
const parseBoolean = (value: string) => z.coerce.boolean().parse(value);
const booleanValues = ['true', 'false'];
/... | @@ -0,0 +1,57 @@
+import type { Config as LibSQLConfig } from '@libsql/client';
+import z from 'zod';
+
+const rawLibSQLOptions = z.record(z.string());
+
+const parseNumber = (value: string) => z.coerce.number().parse(value);
+const parseBoolean = (value: string) => z.coerce.boolean().parse(value);
+
+const booleanValu... | packages/db/src/core/db-client/utils.ts | 11 | TypeScript | 0.643 | suggestion | 97 | 36 | 36 | false | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | ematipico | Adammatthiesen |
* prefetchAll: true,
* defaultStrategy: 'viewport',
* },
* experimental: {
* clientPrerender: true,
* },
* }
* ```
*
* Continue to use the `data-astro-prefetch` attribute on any `<a />` link on your site to opt in to prefetching.
* Instead of appending a `<link>` tag to th... | ```suggestion
* When two routes generate the same prerendered URL, fail the build instead of skipping one.
```
It's no longer silent! | * prefetchAll: true,
* defaultStrategy: 'viewport',
* },
* experimental: {
* clientPrerender: true,
* },
* }
* ```
*
* Continue to use the `data-astro-prefetch` attribute on any `<a />` link on your site to opt in to prefetching.
* Instead of appending a `<link>` tag to th... | @@ -2083,6 +2083,18 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
*/
clientPrerender?: boolean;
+ /**
+ *
+ * @name experimental.failOnPrerenderConflict
+ * @type {boolean}
+ * @default `false`
+ * @version 5.x
+ * @description
+ * When two routes generate the same prerende... | packages/astro/src/types/public/config.ts | 26 | TypeScript | 0.786 | bug | 139 | 51 | 51 | false | Warn or fail on prerendered route collision | 14,206 | withastro/astro | 47,179 | TypeScript | ascorbic | Fryuni |
// Chrome DevTools workspace handler
// See https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md
viteServer.middlewares.use(async function chromeDevToolsHandler(request, response, next) {
if (request.url !== '/.well-known/appspecific/com.chr... | I think a warning would be enough, and we should override it in this case |
// Chrome DevTools workspace handler
// See https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md
viteServer.middlewares.use(async function chromeDevToolsHandler(request, response, next) {
if (request.url !== '/.well-known/appspecific/com.chr... | @@ -162,11 +163,14 @@ export default function createVitePluginAstroServer({
let config;
try {
config = JSON.parse(await readFile(configPath, 'utf-8'));
+ if (config.version !== pluginVersion) throw new Error('Found outdated config.'); | packages/astro/src/vite-plugin-astro-server/plugin.ts | 26 | TypeScript | 0.286 | suggestion | 73 | 51 | 51 | false | Fix automatic Chrome DevTools workspace feature | 14,225 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | delucis |
import { appendForwardSlash, joinPaths } from '@astrojs/internal-helpers/path';
import type { SSRManifest } from '../core/app/types.js';
import { shouldAppendForwardSlash } from '../core/build/util.js';
import { REROUTE_DIRECTIVE_HEADER } from '../core/constants.js';
import { i18nNoLocaleFoundInPath, MissingLocale } fr... | This function is only used here, so there's no need to have a function. We can add a `.map` after the `split` at line 20 and have the mapping logic there.
Also, since this happens for a specific case e.g. `fr-fr.html`, we could leave a comment that explains the `.html` check | import { appendForwardSlash, joinPaths } from '@astrojs/internal-helpers/path';
import type { SSRManifest } from '../core/app/types.js';
import { shouldAppendForwardSlash } from '../core/build/util.js';
import { REROUTE_DIRECTIVE_HEADER } from '../core/constants.js';
import { i18nNoLocaleFoundInPath, MissingLocale } fr... | @@ -19,12 +19,13 @@ export function requestHasLocale(locales: Locales) {
export function pathHasLocale(path: string, locales: Locales): boolean {
const segments = path.split('/');
for (const segment of segments) {
+ const normalizedSegment = normalizeThePath(segment); | packages/astro/src/i18n/index.ts | 22 | TypeScript | 0.643 | suggestion | 276 | 47 | 47 | false | Properly compute `currentLocale` when `path` segment contains `.html` | 14,229 | withastro/astro | 47,179 | TypeScript | ematipico | jonmichaeldarby |
},
'astro:config:done': ({ setAdapter, config, buildOutput, logger }) => {
if (buildOutput === 'static') {
logger.warn(
'[@astrojs/cloudflare] This adapter is intended to be used with server rendered pages, which this project does not contain any of. As such, this adapter is unnecessary.',
);
... | Could we use a Set instead? In theory the values should be distinct anyways 🤔 | },
'astro:config:done': ({ setAdapter, config, buildOutput, logger }) => {
if (buildOutput === 'static') {
logger.warn(
'[@astrojs/cloudflare] This adapter is intended to be used with server rendered pages, which this project does not contain any of. As such, this adapter is unnecessary.',
);
... | @@ -248,7 +248,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
name: '@astrojs/cloudflare',
serverEntrypoint: customWorkerEntryPoint ?? '@astrojs/cloudflare/entrypoints/server.js',
exports: args?.workerEntryPoint?.namedExports
- ? ['default', ...args.workerEntry... | packages/integrations/cloudflare/src/index.ts | 26 | TypeScript | 0.286 | suggestion | 78 | 51 | 51 | false | Filter duplicate exports from Cloudflare adapter's `namedExports` | 14,234 | withastro/astro | 47,179 | TypeScript | alexanderniebuhr | yanthomasdev |
if (!inBrowser) return;
// Init only once
if (inited) return;
inited = true;
debug?.(`[astro] Initializing prefetch script`);
// Fallback default values if not set by user config
prefetchAll ??= defaultOpts?.prefetchAll ?? false;
defaultStrategy ??= defaultOpts?.defaultStrategy ?? 'hover';
// In the future... | ```suggestion
document.addEventListener(
``` | if (!inBrowser) return;
// Init only once
if (inited) return;
inited = true;
debug?.(`[astro] Initializing prefetch script`);
// Fallback default values if not set by user config
prefetchAll ??= defaultOpts?.prefetchAll ?? false;
defaultStrategy ??= defaultOpts?.defaultStrategy ?? 'hover';
// In the future... | @@ -53,7 +53,8 @@ export function init(defaultOpts?: InitOptions) {
* Prefetch links with higher priority when the user taps on them
*/
function initTapStrategy() {
- for (const event of ['touchstart', 'mousedown']) {
+ const events = ['touchstart', 'mousedown'];
+ for (const event of events) {
document.body.ad... | packages/astro/src/prefetch/index.ts | 26 | TypeScript | 0.429 | suggestion | 48 | 51 | 51 | false | fix(prefetch): Fix "tap" prefetch strategy when view transitions are enabled | 14,235 | withastro/astro | 47,179 | TypeScript | martrapp | toxeeec |
buffer = await loadRemoteImage(sourceUrl);
} catch (err: unknown) {
console.error('Could not process image request:', err);
return undefined;
}
}
return buffer;
}
async function loadRemoteImage(src: URL) {
try {
const res = await fetch(src);
if (!res.ok) {
return undefined;
}
return Buffe... | Linter says this can be removed as it’s unused now:
```suggestion
``` | buffer = await loadRemoteImage(sourceUrl);
} catch (err: unknown) {
console.error('Could not process image request:', err);
return undefined;
}
}
return buffer;
}
async function loadRemoteImage(src: URL) {
try {
const res = await fetch(src);
if (!res.ok) {
return undefined;
}
return Buffe... | @@ -73,6 +74,8 @@ async function loadRemoteImage(src: URL) {
}
}
+const URL_PROTOCOL_REGEX = /^(?:(?:http|ftp|https|ws):?\/\/|\/\/)/;
+ | packages/astro/src/assets/endpoint/node.ts | 26 | TypeScript | 0.643 | suggestion | 73 | 51 | 51 | false | fix(assets): fix remote path detection | 14,241 | withastro/astro | 47,179 | TypeScript | delucis | ematipico |
handleContext.request,
);
// This is a case where the user tries to rewrite from a SSR route to a prerendered route (SSG).
// This case isn't valid because when building for SSR, the prerendered route disappears from the server output because it becomes an HTML file,
// so Astro can't re... | This assignment wasn't the cause of the bug, but when the bug was fixed, this broke sequences *without* rewrites. It's not needed, because the new request won't have any cookies to read as it has no headers. Instead we preserve the cookies from the original request. | );
// This is a case where the user tries to rewrite from a SSR route to a prerendered route (SSG).
// This case isn't valid because when building for SSR, the prerendered route disappears from the server output because it becomes an HTML file,
// so Astro can't retrieve it from the emitted man... | @@ -78,7 +77,6 @@ export function sequence(...handlers: MiddlewareHandler[]): MiddlewareHandler {
carriedPayload = payload;
handleContext.request = newRequest;
handleContext.url = new URL(newRequest.url);
- handleContext.cookies = new AstroCookies(newRequest); | packages/astro/src/core/middleware/sequence.ts | 26 | TypeScript | 0.643 | bug | 266 | 45 | 43 | false | fix: don't lose cookies in middleware sequences | 14,280 | withastro/astro | 47,179 | TypeScript | ascorbic | ascorbic |
import { sequence, defineMiddleware } from 'astro/middleware';
const middleware1 = defineMiddleware((_, next) => next('/'));
const middleware2 = defineMiddleware(async ({ request }, next) => {
console.log(await request.clone().text());
return next();
});
const middleware3 = defineMiddleware(async ({ request }, nex... | This is middleware 2. 1 doesn't set any cookies | import { sequence, defineMiddleware } from 'astro/middleware';
const middleware1 = defineMiddleware((_, next) => next('/'));
const middleware2 = defineMiddleware(async ({ request, cookies }, next) => {
cookies.set('cookie1', 'Cookie from middleware 1');
console.log(await request.clone().text());
return next();
});... | @@ -2,14 +2,16 @@ import { sequence, defineMiddleware } from 'astro/middleware';
const middleware1 = defineMiddleware((_, next) => next('/'));
-const middleware2 = defineMiddleware(async ({ request }, next) => {
+const middleware2 = defineMiddleware(async ({ request, cookies }, next) => {
+ cookies.set('cookie1', ... | packages/astro/test/fixtures/middleware-sequence-request-clone/src/middleware.js | 6 | JavaScript | 0.071 | suggestion | 47 | 15 | 18 | false | fix: don't lose cookies in middleware sequences | 14,280 | withastro/astro | 47,179 | TypeScript | Fryuni | ascorbic |
const pipelineMiddleware = await pipeline.getMiddleware();
const pipelineActions = actions ?? (await pipeline.getActions());
setOriginPathname(
request,
pathname,
pipeline.manifest.trailingSlash,
pipeline.manifest.buildFormat,
);
return new RenderContext(
pipeline,
locals,
sequence(...pip... | ```suggestion
shouldInjectCspMetaTags ?? !!pipeline.manifest.csp,
``` | const pipelineMiddleware = await pipeline.getMiddleware();
const pipelineActions = actions ?? (await pipeline.getActions());
setOriginPathname(
request,
pathname,
pipeline.manifest.trailingSlash,
pipeline.manifest.buildFormat,
);
return new RenderContext(
pipeline,
locals,
sequence(...pip... | @@ -114,6 +125,9 @@ export class RenderContext {
undefined,
props,
partial,
+ typeof shouldInjectCspMetaTags !== 'undefined'
+ ? shouldInjectCspMetaTags
+ : !!pipeline.manifest.csp, | packages/astro/src/core/render-context.ts | 26 | TypeScript | 0.786 | suggestion | 74 | 51 | 51 | false | fix(csp): CSP headers in development server | 14,283 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
width: targetWidth,
height: targetHeight,
loading: attributes.loading ?? 'lazy',
decoding: attributes.decoding ?? 'async',
};
},
getURL(options) {
// For SVG files, return the original source path
if (isESMImportedImage(options.src) && options.src.format === 'svg') {
return options.src.src;
}
... | Can we add a link to this list? I checked the entire file, I couldn't find a reference to that | width: targetWidth,
height: targetHeight,
loading: attributes.loading ?? 'lazy',
decoding: attributes.decoding ?? 'async',
};
},
getURL(options) {
// For SVG files, return the original source path
if (isESMImportedImage(options.src) && options.src.format === 'svg') {
return options.src.src;
}
... | @@ -62,6 +62,80 @@ const service: ExternalImageService = {
return '/_vercel/image?' + searchParams;
},
+ // Adapted from the base service's getSrcSet, but always returning widths that are valid for Vercel | packages/integrations/vercel/src/image/build-service.ts | 26 | TypeScript | 0.286 | question | 95 | 51 | 51 | false | fix(vercel): ensure srcset widths are always from configured list | 14,289 | withastro/astro | 47,179 | TypeScript | ematipico | ascorbic |
interface AstroPluginOptions {
settings: AstroSettings;
logger: Logger;
fs: typeof fs;
}
export default function createVitePluginAstroServer({
settings,
logger,
fs: fsMod,
}: AstroPluginOptions): vite.Plugin {
return {
name: 'astro:server',
async configureServer(viteServer) {
const loader = createViteLo... | Will the routes still get updated? | name: 'astro:server',
async configureServer(viteServer) {
const loader = createViteLoader(viteServer);
// NOTE: this is temporary, we will use the configuration and proper loading later
// @ts-expect-error
const url = pathToFileURL(import.meta.dirname + '/entrypoint.js');
const createExports = await ... | @@ -47,58 +36,24 @@ import { trailingSlashMiddleware } from './trailing-slash.js';
interface AstroPluginOptions {
settings: AstroSettings;
logger: Logger;
- fs: typeof fs;
}
export default function createVitePluginAstroServer({
settings,
logger,
- fs: fsMod,
}: AstroPluginOptions): vite.Plugin {
return ... | packages/astro/src/vite-plugin-astro-server/plugin.ts | 26 | TypeScript | 0.071 | question | 34 | 51 | 51 | false | refactor(dev): use entry point to bootstrap the app | 14,333 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
const astro = info.meta.astro as AstroPluginMetadata['astro'];
let hasAddedIsland = false;
for (const comp of astro.serverComponents) {
if (!settings.serverIslandNameMap.has(comp.resolvedPath)) {
if (!settings.adapter) {
throw new AstroError(AstroErrorData.NoAdapterInstalledServerIslands);
... | Why importing from from the ssr environment doesn't work here? |
const astro = info.meta.astro as AstroPluginMetadata['astro'];
let hasAddedIsland = false;
for (const comp of astro.serverComponents) {
if (!settings.serverIslandNameMap.has(comp.resolvedPath)) {
if (!settings.adapter) {
throw new AstroError(AstroErrorData.NoAdapterInstalledServerIslands);
... | @@ -66,9 +80,8 @@ export function vitePluginServerIslands({ settings }: AstroPluginOptions): ViteP
// Append the name map, for prod
settings.serverIslandNameMap.set(comp.resolvedPath, name);
-
settings.serverIslandMap.set(name, () => {
- return ssrEnvironment?.runner.import(comp.resolvedPath) a... | packages/astro/src/core/server-islands/vite-plugin-server-islands.ts | 26 | TypeScript | 0.214 | question | 62 | 51 | 51 | false | feat: add support for server islands in Environment API | 14,390 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | ascorbic |
ignoreWorkspaces: [
'examples/**',
'**/{test,e2e}/**/{fixtures,_temp-fixtures}/**',
'benchmark/**',
],
workspaces: {
'.': {
ignoreDependencies: [
'@astrojs/check', // Used by the build script but not as a standard module import
],
// In smoke tests, we checkout to the docs repo so those binaries... | Why is this ignore needed? If temporary, can you add a todo comment? | ignoreWorkspaces: [
'examples/**',
'**/{test,e2e}/**/{fixtures,_temp-fixtures}/**',
'benchmark/**',
],
workspaces: {
'.': {
ignoreDependencies: [
'@astrojs/check', // Used by the build script but not as a standard module import
],
// In smoke tests, we checkout to the docs repo so those binaries... | @@ -30,7 +30,7 @@ export default {
'e2e/**/*.test.js',
'test/units/teardown.js',
],
- ignore: ['**/e2e/**/{fixtures,_temp-fixtures}/**', 'performance/**/*'],
+ ignore: ['**/e2e/**/{fixtures,_temp-fixtures}/**', 'performance/**/*', 'src/vite-plugin-app/createExports.ts'], | knip.js | 26 | JavaScript | 0.214 | question | 68 | 51 | 51 | false | refactor: clean up dead code for env API | 14,395 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | ascorbic |
*
* <!-- GOOD: `src` is a URL. -->
* <Image src="https://example.com/my_image.png" alt="Cool image" />
*
* <!-- BAD: `src` is an image's `src` path instead of the full image object. -->
* <Image src={myImage.src} alt="Cool image" />
*
* <!-- BAD: `src` is a string filepath. -->
* <Image src="../my_image.png" a... | ```suggestion
* @deprecated This error was removed in Astro v6.0.0 along with the removal of `Astro.glob()`.
``` | *
* <!-- GOOD: `src` is a URL. -->
* <Image src="https://example.com/my_image.png" alt="Cool image" />
*
* <!-- BAD: `src` is an image's `src` path instead of the full image object. -->
* <Image src={myImage.src} alt="Cool image" />
*
* <!-- BAD: `src` is a string filepath. -->
* <Image src="../my_image.png" a... | @@ -951,6 +951,7 @@ export const LocalImageUsedWrongly = {
* - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob)
* @description
* `Astro.glob()` can only be used in `.astro` files. You can use [`import.meta.glob()`](https://vite.dev/guide/features.html#glob-import) instead to achieve th... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 0.929 | suggestion | 115 | 51 | 51 | false | feat!: remove Astro.glob | 14,421 | withastro/astro | 47,179 | TypeScript | sarah11918 | florian-lefebvre |
hint: 'If you want to use an image from your `src` folder, you need to either import it or if the image is coming from a content collection, use the [image() schema helper](https://docs.astro.build/en/guides/images/#images-in-content-collections). See https://docs.astro.build/en/guides/images/#src-required for more in... | ```suggestion
* @deprecated This error was removed in Astro v6.0.0 along with the removal of `Astro.glob()`.
``` | hint: 'If you want to use an image from your `src` folder, you need to either import it or if the image is coming from a content collection, use the [image() schema helper](https://docs.astro.build/en/guides/images/#images-in-content-collections). See https://docs.astro.build/en/guides/images/#src-required for more in... | @@ -966,6 +967,7 @@ export const AstroGlobUsedOutside = {
* - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob)
* @description
* `Astro.glob()` did not return any matching files. There might be a typo in the glob pattern.
+ * @deprecated Removed in Astro v6.0.0 as it is no longer releva... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 0.929 | suggestion | 115 | 51 | 51 | false | feat!: remove Astro.glob | 14,421 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
export const UnknownViteError = {
name: 'UnknownViteError',
title: 'Unknown Vite Error.',
} satisfies ErrorData;
/**
* @docs
* @see
* - [Type Imports](https://docs.astro.build/en/guides/typescript/#type-imports)
* @description
* Astro could not import the requested file. Oftentimes, this is caused by the import ... | ```suggestion
* @deprecated This error was removed in Astro v6.0.0 along with the removal of `Astro.glob()`.
``` | export const UnknownViteError = {
name: 'UnknownViteError',
title: 'Unknown Vite Error.',
} satisfies ErrorData;
/**
* @docs
* @see
* - [Type Imports](https://docs.astro.build/en/guides/typescript/#type-imports)
* @description
* Astro could not import the requested file. Oftentimes, this is caused by the import ... | @@ -1075,6 +1077,7 @@ export const FailedToLoadModuleSSR = {
* - [Glob Patterns](https://docs.astro.build/en/guides/imports/#glob-patterns)
* @description
* Astro encountered an invalid glob pattern. This is often caused by the glob pattern not being a valid file path.
+ * @deprecated Removed in Astro v6.0.0 as i... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 0.929 | suggestion | 115 | 51 | 51 | false | feat!: remove Astro.glob | 14,421 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
} satisfies ErrorData;
/**
* @docs
* @description
* The CSP feature isn't enabled
* @message
* The `experimental.csp` configuration isn't enabled.
*/
export const CspNotEnabled = {
name: 'CspNotEnabled',
title: "CSP feature isn't enabled",
message: "The `experimental.csp` configuration isn't enabled.",
} sati... | `message` is going to be rendered as a paragraph, so it needs a full stop at the end
```suggestion
* This property on the Astro global is not available in getStaticPaths().
*/
export const UnavailableAstroGlobalProperty = {
name: 'UnavailableAstroGlobalProperty',
title: 'Unavailable Astro global property in g... | } satisfies ErrorData;
/**
* @docs
* @description
* The CSP feature isn't enabled
* @message
* The `experimental.csp` configuration isn't enabled.
*/
export const CspNotEnabled = {
name: 'CspNotEnabled',
title: "CSP feature isn't enabled",
message: "The `experimental.csp` configuration isn't enabled.",
} sati... | @@ -1417,6 +1417,19 @@ export const CspNotEnabled = {
message: "The `experimental.csp` configuration isn't enabled.",
} satisfies ErrorData;
+/**
+ * @docs
+ * @description
+ * Unavailable Astro global property in getStaticPaths
+ * @message
+ * This property on the Astro global is not available in getStaticPaths
... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 0.786 | suggestion | 428 | 51 | 51 | false | feat: deprecate Astro in getStaticPaths | 14,432 | withastro/astro | 47,179 | TypeScript | yanthomasdev | florian-lefebvre |
} satisfies ErrorData;
/**
* @docs
* @description
* The CSP feature isn't enabled
* @message
* The `experimental.csp` configuration isn't enabled.
*/
export const CspNotEnabled = {
name: 'CspNotEnabled',
title: "CSP feature isn't enabled",
message: "The `experimental.csp` configuration isn't enabled.",
} sati... | ```suggestion
* Unavailable Astro global property in getStaticPaths
* @message
* The Astro global is not available in getStaticPaths().
*/
export const UnavailableAstroGlobalProperty = {
name: 'UnavailableAstroGlobalProperty',
title: 'Unavailable Astro global property in getStaticPaths()',
message: (name... | } satisfies ErrorData;
/**
* @docs
* @description
* The CSP feature isn't enabled
* @message
* The `experimental.csp` configuration isn't enabled.
*/
export const CspNotEnabled = {
name: 'CspNotEnabled',
title: "CSP feature isn't enabled",
message: "The `experimental.csp` configuration isn't enabled.",
} sati... | @@ -1417,6 +1417,19 @@ export const CspNotEnabled = {
message: "The `experimental.csp` configuration isn't enabled.",
} satisfies ErrorData;
+/**
+ * @docs
+ * @description
+ * Unavailable Astro global property in getStaticPaths
+ * @message
+ * This property on the Astro global is not available in getStaticPaths(... | packages/astro/src/core/errors/errors-data.ts | 26 | TypeScript | 1 | question | 1,205 | 51 | 51 | false | feat: deprecate Astro in getStaticPaths | 14,432 | withastro/astro | 47,179 | TypeScript | sarah11918 | florian-lefebvre |
let fixture;
before(async () => {
fixture = await loadFixture({
root,
site: 'https://mysite.dev/',
});
await fixture.editFile(
'/src/pages/food/[name].astro',
(prev) => prev.replace('getStaticPaths() {', 'getStaticPaths() {\nAstro.getActionResult;'),
false,
);
});
after(async () => {
fixt... | ```suggestion
assert.equal(err.title, 'Unavailable Astro global in getStaticPaths()');
``` | let fixture;
before(async () => {
fixture = await loadFixture({
root,
site: 'https://mysite.dev/',
});
await fixture.editFile(
'/src/pages/food/[name].astro',
(prev) => prev.replace('getStaticPaths() {', 'getStaticPaths() {\nAstro.getActionResult;'),
false,
);
});
after(async () => {
fixt... | @@ -135,4 +142,60 @@ describe('getStaticPaths - dev calls', () => {
const res = await fixture.fetch('/pizza/parmesan-and-olives');
assert.equal(res.status, 200);
});
+
+ it('warns if Astro.generator or Astro.site is accessed', async () => {
+ const originalWarn = console.warn;
+ /** @type {Array<string>} */
+... | packages/astro/test/astro-get-static-paths.test.js | 26 | JavaScript | 0.571 | suggestion | 95 | 30 | 30 | false | feat: deprecate Astro in getStaticPaths | 14,432 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
/// <reference types="vite/types/import-meta.d.ts" />
/// <reference path="./types/content.d.ts" />
/// <reference path="./types/actions.d.ts" />
/// <reference path="./types/env.d.ts" />
/// <reference path="./types/fonts.d.ts" />
interface ImportMetaEnv {
// TODO: remove in Astro 7
/**
* The prefix for Astro-gen... | ```suggestion
* @deprecated This will be removed in a future major version of Astro. Use `build.assetsPrefix` from `astro:config/server` instead.
``` | /// <reference types="vite/types/import-meta.d.ts" />
/// <reference path="./types/content.d.ts" />
/// <reference path="./types/actions.d.ts" />
/// <reference path="./types/env.d.ts" />
/// <reference path="./types/fonts.d.ts" />
interface ImportMetaEnv {
// TODO: remove in Astro 7
/**
* The prefix for Astro-gen... | @@ -5,8 +5,10 @@
/// <reference path="./types/fonts.d.ts" />
interface ImportMetaEnv {
+ // TODO: remove in Astro 7
/**
* The prefix for Astro-generated asset links if the build.assetsPrefix config option is set. This can be used to create asset links not handled by Astro.
+ * @deprectated It will be removed ... | packages/astro/client.d.ts | 11 | TypeScript | 0.786 | suggestion | 153 | 36 | 36 | false | feat: deprecate import.meta.env.ASSETS_PREFIX | 14,461 | withastro/astro | 47,179 | TypeScript | ascorbic | florian-lefebvre |
} catch (err) {
logger.error(`Error serializing pages\n${(err as any).toString()}`);
return;
}
}
const destDir = fileURLToPath(dir);
const lastmod = opts.lastmod?.toISOString();
const xslURL = opts.xslURL ? new URL(opts.xslURL, finalSiteUrl).href : undefined;
if (chu... | Why does this need the `Promise.resolve()`? | if (serializedUrls.length === 0) {
logger.warn('No pages found!');
return;
}
urlData = serializedUrls;
} catch (err) {
logger.error(`Error serializing pages\n${(err as any).toString()}`);
return;
}
}
const destDir = fileURLToPath(dir);
const... | @@ -174,9 +174,53 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
return;
}
}
+
const destDir = fileURLToPath(dir);
const lastmod = opts.lastmod?.toISOString();
const xslURL = opts.xslURL ? new URL(opts.xslURL, finalSiteUrl).href : undefined;
+
+ if (... | packages/integrations/sitemap/src/index.ts | 26 | TypeScript | 0.214 | question | 43 | 51 | 51 | false | Feature(sitemap): named files chunking strategy | 14,471 | withastro/astro | 47,179 | TypeScript | ascorbic | Slackluky |
fonts = result.fonts;
} else {
const result = await resolveFont(
family.name,
// We do not merge the defaults, we only provide defaults as a fallback
{
weights: family.weights ?? defaults.weights,
styles: family.styles ?? defaults.styles,
subsets: family.subsets ?? defaults.subsets,
... | Only problem I can foresee is it can be pretty ugly for providers that support a lot of fonts, like google. Ideas welcome! | fontTypeExtractor,
fontFileReader,
});
// URLs are already proxied at this point so no further processing is required
fonts = result.fonts;
} else {
const result = await resolveFont(
family.name,
// We do not merge the defaults, we only provide defaults as a fallback
{
weights: fa... | @@ -189,6 +189,13 @@ export async function orchestrate({
'assets',
`No data found for font family ${bold(family.name)}. Review your configuration`,
);
+ const availableFamilies = await listFonts([family.provider.name!]);
+ if (availableFamilies && !availableFamilies.includes(family.name)) {
+ ... | packages/astro/src/assets/fonts/orchestrate.ts | 26 | TypeScript | 0.357 | suggestion | 122 | 51 | 51 | false | feat(fonts): warn on unsupported family name | 14,475 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
systemFallbacksProvider: createSystemFallbacksProvider(),
fontMetricsResolver: fakeFontMetricsResolver,
fontTypeExtractor,
fontFileReader: createFontaceFontFileReader({ errorHandler }),
logger,
createUrlProxy: ({ local, cssVariable, ...params }) => {
const dataCollector = createDataCollector(param... | I think you need to set `FORCE_COLOR` to get this to match in CI | }),
},
}),
localProviderUrlResolver: createRequireLocalProviderUrlResolver({ root }),
storage,
cssRenderer: createMinifiableCssRenderer({ minify: true }),
systemFallbacksProvider: createSystemFallbacksProvider(),
fontMetricsResolver: fakeFontMetricsResolver,
fontTypeExtractor,
fontFileR... | @@ -259,4 +260,153 @@ describe('fonts orchestrate()', () => {
],
);
});
+
+ it('warns if remote provider does not return any font data', async () => {
+ const fakeUnifontProvider = defineFontProvider('test', () => {
+ return {
+ resolveFont: () => {
+ return undefined;
+ },
+ };
+ });
+ const ... | packages/astro/test/units/assets/fonts/orchestrate.test.js | 26 | JavaScript | 0.357 | suggestion | 64 | 51 | 51 | false | feat(fonts): warn on unsupported family name | 14,475 | withastro/astro | 47,179 | TypeScript | ascorbic | florian-lefebvre |
const message = (await getErrorOverlayContent(page)).message;
expect(message).toMatch('can only be used in');
});
test('can handle DomException errors', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/dom-exception'), { waitUntil: 'networkidle' });
const message = (await getErrorOverlayConten... | Is there way you could use `getOverlayContent(page)`? | const message = (await getErrorOverlayContent(page)).message;
expect(message).toMatch('can only be used in');
});
test('can handle DomException errors', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/dom-exception'), { waitUntil: 'networkidle' });
const message = (await getErrorOverlayConten... | @@ -142,4 +142,38 @@ test.describe('Error display', () => {
const codeFrameContent = await codeFrame.innerHTML();
expect(codeFrameContent).toContain('error-line');
});
+
+ test('copy stack trace to clipboard', async ({ page, astro, context }) => {
+ await context.grantPermissions(['clipboard-read', 'clipboard-... | packages/astro/e2e/errors.test.js | 26 | JavaScript | 0.429 | question | 53 | 51 | 49 | false | feat(astro): add copy button for stack trace in error overlay | 14,489 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | dev-shetty |
assert.equal(document.querySelector('h2').id, 'frontmattertitle');
assert.equal(h3Ids.includes('keyword-2'), true);
assert.equal(h3Ids.includes('tag-1'), true);
assert.equal(document.querySelector('h4').id, 'item-2');
assert.equal(document.querySelector('h5').id, 'nested-item-3');
assert.equal(document.quer... | We could also potentially remove this block now — it was only added to test separately from the default behaviour, but it’s now just duplicating the `MDX getHeadings` describe block above. | import * as assert from 'node:assert/strict';
import { before, describe, it } from 'node:test';
import { rehypeHeadingIds } from '@astrojs/markdown-remark';
import mdx from '@astrojs/mdx';
import { parseHTML } from 'linkedom';
import { visit } from 'unist-util-visit';
import { loadFixture } from '../../../astro/test/te... | @@ -202,15 +202,14 @@ describe('MDX headings with frontmatter', () => {
});
});
-describe('experimental.headingIdCompat', () => {
+describe('MDX IDs', () => { | packages/integrations/mdx/test/mdx-get-headings.test.js | 26 | JavaScript | 0.571 | refactor | 188 | 51 | 204 | false | feat!: stabilize experimental.headingIdCompat | 14,494 | withastro/astro | 47,179 | TypeScript | delucis | florian-lefebvre |
logger.debug(
'update',
`Re-calculating routes for ${path.slice(settings.config.srcDir.pathname.length)}`,
);
const file = pathToFileURL(normalizePath(path));
routeList = await createRoutesList(
{
settings,
fsMod,
},
logger,
// TODO: the caller should handle this
{ dev:... | What happens in other enviornments? | logger.debug(
'update',
`Re-calculating routes for ${path.slice(settings.config.srcDir.pathname.length)}`,
);
const file = pathToFileURL(normalizePath(path));
routeList = await createRoutesList(
{
settings,
fsMod,
},
logger,
// TODO: the caller should handle this
{ dev:... | @@ -70,21 +75,28 @@ export default async function astroPluginRoutes({
serializedRouteInfo = routeList.routes.map((r): SerializedRouteInfo => {
return {
- file: '',
+ file: fileURLToPath(file),
links: [],
scripts: [],
styles: [],
routeData: serializeRouteData(r, settings.config... | packages/astro/src/vite-plugin-routes/index.ts | 26 | TypeScript | 0.071 | question | 35 | 51 | 51 | false | chore: handle invalidation of manifest | 14,537 | withastro/astro | 47,179 | TypeScript | ascorbic | ematipico |
// IMPORTANT: do not publish this file! It's only intended for development within the monorepo
declare module 'virtual:astro:env/internal' {
export const schema: import('./src/env/schema.js').EnvSchema;
}
declare module 'virtual:astro:assets/fonts/internal' {
export const internalConsumableMap: import('./src/assets... | Do we have some guidelines on how to use this file? I know you mentioned in some other PR. If we add some guidelines, maybe we should also set on stone how to name our internal modules. At the moment, we don't have a naming convention | // IMPORTANT: do not publish this file!
// It provides typings for internal virtual modules.
// The naming convention is: virtual:astro:<feature>/<...custom>
declare module 'virtual:astro:env/internal' {
export const schema: import('./src/env/schema.js').EnvSchema;
}
declare module 'virtual:astro:assets/fonts/intern... | packages/astro/dev-only.d.ts | 1 | TypeScript | 0.5 | question | 234 | 18 | 21 | false | refactor(actions): plugin and virtual modules | 14,538 | withastro/astro | 47,179 | TypeScript | ematipico | florian-lefebvre | |
export const ACTIONS_TYPES_FILE = 'actions.d.ts';
export const VIRTUAL_MODULE_ID = 'astro:actions';
export const RUNTIME_VIRTUAL_MODULE_ID = 'virtual:astro:actions/runtime';
export const RESOLVED_RUNTIME_VIRTUAL_MODULE_ID = '\0' + RUNTIME_VIRTUAL_MODULE_ID;
export const ENTRYPOINT_VIRTUAL_MODULE_ID = 'virtual:astro:... | We should really start documenting these virtual modules, so at least when we import them, we have some JSDocs that informs how about their usage | export const ACTIONS_TYPES_FILE = 'actions.d.ts';
export const VIRTUAL_MODULE_ID = 'astro:actions';
/** Used to expose shared utilities, with server or client specific implementations */
export const RUNTIME_VIRTUAL_MODULE_ID = 'virtual:astro:actions/runtime';
export const RESOLVED_RUNTIME_VIRTUAL_MODULE_ID = '\0' + ... | @@ -1,9 +1,17 @@
-export const VIRTUAL_MODULE_ID = 'astro:actions';
-export const RESOLVED_VIRTUAL_MODULE_ID = '\0' + VIRTUAL_MODULE_ID;
export const ACTIONS_TYPES_FILE = 'actions.d.ts';
-export const ASTRO_ACTIONS_INTERNAL_MODULE_ID = 'astro-internal:actions';
-export const RESOLVED_ASTRO_ACTIONS_INTERNAL_MODULE_ID =... | packages/astro/src/actions/consts.ts | 13 | TypeScript | 0.429 | suggestion | 145 | 22 | 24 | false | refactor(actions): plugin and virtual modules | 14,538 | withastro/astro | 47,179 | TypeScript | ematipico | florian-lefebvre |
'Skew Protection',
() => {
let fixture;
before(async () => {
// Set DEPLOY_ID env var for the test
process.env.DEPLOY_ID = 'test-deploy-123';
fixture = await loadFixture({
root: new URL('./fixtures/skew-protection/', import.meta.url),
});
await fixture.build();
// Clean up
delete proce... | This test contains a note but doesn't actually test anything | 'Skew Protection',
() => {
let fixture;
before(async () => {
// Set DEPLOY_ID env var for the test
process.env.DEPLOY_ID = 'test-deploy-123';
fixture = await loadFixture({
root: new URL('./fixtures/skew-protection/', import.meta.url),
});
await fixture.build();
// Clean up
delete proce... | @@ -0,0 +1,85 @@
+import * as assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { before, describe, it } from 'node:test';
+import { loadFixture } from '../../../../astro/test/test-utils.js';
+
+describe(
+ 'Skew Protection',
+ () => {
+ let fixture;
+
+ before(async () => {
+ ... | packages/integrations/netlify/test/functions/skew-protection.test.js | 26 | JavaScript | 0.214 | suggestion | 60 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | matthewp | matthewp |
// Set DEPLOY_ID env var for the test
process.env.DEPLOY_ID = 'test-deploy-123';
fixture = await loadFixture({
root: new URL('./fixtures/skew-protection/', import.meta.url),
});
await fixture.build();
// Clean up
delete process.env.DEPLOY_ID;
});
it('Includes adapter headers in actions t... | this test hasn't been filled out. It's probably not possible to test this and we should likely just remove it. | // Set DEPLOY_ID env var for the test
process.env.DEPLOY_ID = 'test-deploy-123';
fixture = await loadFixture({
root: new URL('./fixtures/skew-protection/', import.meta.url),
});
await fixture.build();
// Clean up
delete process.env.DEPLOY_ID;
});
it('Server islands inline adapter headers... | @@ -0,0 +1,85 @@
+import * as assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { before, describe, it } from 'node:test';
+import { loadFixture } from '../../../../astro/test/test-utils.js';
+
+describe(
+ 'Skew Protection',
+ () => {
+ let fixture;
+
+ before(async () => {
+ ... | packages/integrations/netlify/test/functions/skew-protection.test.js | 26 | JavaScript | 0.429 | suggestion | 110 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | matthewp | matthewp |
/*
NOTE: Do not add any dependencies or imports in this file so that it can load quickly in dev.
*/
import { internalFetchHeaders } from 'astro:adapter-config/client';
const debug = import.meta.env.DEV ? console.debug : undefined;
const inBrowser = import.meta.env.SSR === false;
// Track prefetched URLs so we don't... | Should rephrase this to be more like "be careful about adding dependencies", as in this case it's necessary. | /*
NOTE: Be careful about adding dependencies or imports in this file so that it can load quickly in dev.
*/
import { internalFetchHeaders } from 'virtual:astro:adapter-config/client';
const debug = import.meta.env.DEV ? console.debug : undefined;
const inBrowser = import.meta.env.SSR === false;
// Track prefetched... | @@ -2,6 +2,8 @@
NOTE: Do not add any dependencies or imports in this file so that it can load quickly in dev. | packages/astro/src/prefetch/index.ts | 2 | TypeScript | 0.429 | suggestion | 108 | 27 | 27 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | matthewp | matthewp |
* `astro:build:generated` hook, so adapters can consume them and add them inside
* their hosting headers configuration file.
*
* NOTE: the semantics and list of headers might change until the feature
* is out of experimental
*/
experimentalStaticHeaders?: boolean;
}
export interface AstroAdapter {
name: ... | We are already inside a configuration, so calling this `Config` seems redundant.
Also, "runtime" and client-side code have different meanings to us, so I would look for a better name or a better description. | * `astro:build:generated` hook, so adapters can consume them and add them inside
* their hosting headers configuration file.
*
* NOTE: the semantics and list of headers might change until the feature
* is out of experimental
*/
experimentalStaticHeaders?: boolean;
}
export interface AstroAdapter {
name: ... | @@ -115,6 +115,16 @@ export interface AstroAdapter {
* If the adapter is not able to handle certain configurations, Astro will throw an error.
*/
supportedAstroFeatures: AstroAdapterFeatureMap;
+ /**
+ * Runtime configuration that will be available to Astro's client-side code.
+ */
+ runtimeConfig?: { | packages/astro/src/types/public/integrations.ts | 26 | TypeScript | 0.643 | suggestion | 208 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | ematipico | matthewp |
*
* NOTE: the semantics and list of headers might change until the feature
* is out of experimental
*/
experimentalStaticHeaders?: boolean;
}
export interface AstroAdapter {
name: string;
serverEntrypoint?: string | URL;
previewEntrypoint?: string | URL;
exports?: string[];
args?: any;
adapterFeatures?:... | We also have a fetch call for retrieving the 404 error in SSR. I believe this isn't internal.
I would put the supported features inside a list. They aren't a detail, but they define user and developer expectations | *
* NOTE: the semantics and list of headers might change until the feature
* is out of experimental
*/
experimentalStaticHeaders?: boolean;
}
export interface AstroAdapter {
name: string;
serverEntrypoint?: string | URL;
previewEntrypoint?: string | URL;
exports?: string[];
args?: any;
adapterFeatures?:... | @@ -115,6 +115,16 @@ export interface AstroAdapter {
* If the adapter is not able to handle certain configurations, Astro will throw an error.
*/
supportedAstroFeatures: AstroAdapterFeatureMap;
+ /**
+ * Runtime configuration that will be available to Astro's client-side code.
+ */
+ runtimeConfig?: {
+ /**
... | packages/astro/src/types/public/integrations.ts | 26 | TypeScript | 0.643 | suggestion | 215 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | ematipico | matthewp |
import type { Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';
const VIRTUAL_CLIENT_ID = 'astro:adapter-config/client';
const RESOLVED_VIRTUAL_CLIENT_ID = '\0' + VIRTUAL_CLIENT_ID;
export function vitePluginAdapterConfig(settings: AstroSettings): VitePlugin {
return {
nam... | The presence of `/client` implies a possible `/server`. However, it seems that's not the case, so maybe we should just remove it or call it `/runtime` | import type { Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';
const VIRTUAL_CLIENT_ID = 'virtual:astro:adapter-config/client';
const RESOLVED_VIRTUAL_CLIENT_ID = '\0' + VIRTUAL_CLIENT_ID;
export function vitePluginAdapterConfig(settings: AstroSettings): VitePlugin {
return... | @@ -0,0 +1,41 @@
+import type { Plugin as VitePlugin } from 'vite';
+import type { AstroSettings } from '../types/astro.js';
+
+const VIRTUAL_CLIENT_ID = 'astro:adapter-config/client'; | packages/astro/src/vite-plugin-adapter-config/index.ts | 4 | TypeScript | 0.571 | suggestion | 150 | 29 | 29 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | ematipico | matthewp |
// IMPORTANT: do not publish this file!
// It provides typings for internal virtual modules.
// The naming convention is: virtual:astro:<feature>/<...custom>
declare module 'virtual:astro:env/internal' {
export const schema: import('./src/env/schema.js').EnvSchema;
}
declare module 'virtual:astro:assets/fonts/intern... | Since it's an internal virtual module, can we stick to the convention? In this case
```suggestion
declare module 'virtual:astro:adapter-config/client' {
``` | // IMPORTANT: do not publish this file!
// It provides typings for internal virtual modules.
// The naming convention is: virtual:astro:<feature>/<...custom>
declare module 'virtual:astro:env/internal' {
export const schema: import('./src/env/schema.js').EnvSchema;
}
declare module 'virtual:astro:assets/fonts/intern... | @@ -11,6 +11,10 @@ declare module 'virtual:astro:assets/fonts/internal' {
export const consumableMap: import('./src/assets/fonts/types.js').ConsumableMap;
}
+declare module 'astro:adapter-config/client' { | packages/astro/dev-only.d.ts | 14 | TypeScript | 0.714 | suggestion | 159 | 25 | 25 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | matthewp |
finalBuildOutput = buildOutput;
const useEdgeMiddleware = integrationConfig?.edgeMiddleware ?? false;
const useStaticHeaders = integrationConfig?.experimentalStaticHeaders ?? false;
setAdapter({
name: '@astrojs/netlify',
serverEntrypoint: '@astrojs/netlify/ssr-function.js',
exports: ['... | Netlify should get `assetQueryParams` too (which would need adding to `skew-protection.json`) | const useEdgeMiddleware = integrationConfig?.edgeMiddleware ?? false;
const useStaticHeaders = integrationConfig?.experimentalStaticHeaders ?? false;
setAdapter({
name: '@astrojs/netlify',
serverEntrypoint: '@astrojs/netlify/ssr-function.js',
exports: ['default'],
adapterFeatures: {
... | @@ -662,6 +685,15 @@ export default function netlifyIntegration(
sharpImageService: 'stable',
envGetSecret: 'stable',
},
+ client: {
+ internalFetchHeaders: (): Record<string, string> => {
+ const deployId = process.env.DEPLOY_ID;
+ if (deployId) {
+ return { 'X-Netlify-D... | packages/integrations/netlify/src/index.ts | 26 | TypeScript | 0.429 | suggestion | 93 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | ascorbic | matthewp |
serverEntrypoint?: string | URL;
previewEntrypoint?: string | URL;
exports?: string[];
args?: any;
adapterFeatures?: AstroAdapterFeatures;
/**
* List of features supported by an adapter.
*
* If the adapter is not able to handle certain configurations, Astro will throw an error.
*/
supportedAstroFeatures:... | Wouldn't it be better if this was a Map, plain object, or even `URLSearchParams`? | serverEntrypoint?: string | URL;
previewEntrypoint?: string | URL;
exports?: string[];
args?: any;
adapterFeatures?: AstroAdapterFeatures;
/**
* List of features supported by an adapter.
*
* If the adapter is not able to handle certain configurations, Astro will throw an error.
*/
supportedAstroFeatures:... | @@ -115,6 +115,22 @@ export interface AstroAdapter {
* If the adapter is not able to handle certain configurations, Astro will throw an error.
*/
supportedAstroFeatures: AstroAdapterFeatureMap;
+ /**
+ * Configuration for Astro's client-side code.
+ */
+ client?: {
+ /**
+ * Headers to inject into Astro's ... | packages/astro/src/types/public/integrations.ts | 26 | TypeScript | 0.429 | question | 81 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | ascorbic | matthewp |
},
adapterFeatures: {
edgeMiddleware,
buildOutput,
experimentalStaticHeaders,
},
supportedAstroFeatures: {
hybridOutput: 'stable',
staticOutput: 'stable',
serverOutput: 'stable',
sharpImageService: 'stable',
i18nDomains: 'experimental',
envGetSecret: 'stable',
},
client: {
inte... | How come the query string logic checks for `skewProtection` boolean but the headers logic above doesn't?
Also, can we make the `skewProtection` boolean default to `process.env.VERCEL_SKEW_PROTECTION_ENABLED === '1'`?
See the docs https://vercel.com/docs/skew-protection#supported-frameworks | },
adapterFeatures: {
edgeMiddleware,
buildOutput,
experimentalStaticHeaders,
},
supportedAstroFeatures: {
hybridOutput: 'stable',
staticOutput: 'stable',
serverOutput: 'stable',
sharpImageService: 'stable',
i18nDomains: 'experimental',
envGetSecret: 'stable',
},
client: {
inte... | @@ -130,6 +130,21 @@ function getAdapter({
i18nDomains: 'experimental',
envGetSecret: 'stable',
},
+ client: {
+ internalFetchHeaders: skewProtection
+ ? (): Record<string, string> => {
+ const deploymentId = process.env.VERCEL_DEPLOYMENT_ID;
+ if (deploymentId) {
+ return { 'x-deployme... | packages/integrations/vercel/src/index.ts | 26 | TypeScript | 0.571 | question | 292 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | styfle | matthewp |
name: PACKAGE_NAME,
serverEntrypoint: `${PACKAGE_NAME}/entrypoint`,
exports: ['default'],
args: {
middlewareSecret,
skewProtection,
},
adapterFeatures: {
edgeMiddleware,
buildOutput,
experimentalStaticHeaders,
},
supportedAstroFeatures: {
hybridOutput: 'stable',
staticOutput: 'stabl... | ```suggestion
return { 'x-deployment-id': deploymentId };
```
See the docs here https://vercel.com/docs/skew-protection | name: PACKAGE_NAME,
serverEntrypoint: `${PACKAGE_NAME}/entrypoint`,
exports: ['default'],
args: {
middlewareSecret,
skewProtection,
},
adapterFeatures: {
edgeMiddleware,
buildOutput,
experimentalStaticHeaders,
},
supportedAstroFeatures: {
hybridOutput: 'stable',
staticOutput: 'stabl... | @@ -130,6 +130,20 @@ function getAdapter({
i18nDomains: 'experimental',
envGetSecret: 'stable',
},
+ client: {
+ internalFetchHeaders: skewProtection
+ ? (): Record<string, string> => {
+ const deploymentId = process.env.VERCEL_DEPLOYMENT_ID;
+ if (deploymentId) {
+ return { 'x-vercel-d... | packages/integrations/vercel/src/index.ts | 26 | TypeScript | 0.714 | suggestion | 127 | 51 | 51 | false | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | styfle | 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) => `\
{
"main"... | `_routes.json` is only for cloudflare pages | 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) => `\
{
"main"... | @@ -80,6 +80,16 @@ export default async function seed() {
// TODO
}
`,
+ CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
+{
+ "main": "dist/_worker.js/index.js",
+ "name": ${JSON.stringify(name)},
+ "assets": {
+ "binding": "ASSETS",
+ "directory": "./dist"
+ }
+}`,
+ CLOUDFLARE_ASSETSIGNORE: `_worker.js`, | packages/astro/src/cli/add/index.ts | 26 | TypeScript | 0.214 | suggestion | 43 | 51 | 51 | false | feat(cli): scaffold wrangler.jsonc in astro add | 14,564 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
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) => `\
{
"main"... | `compatibility_date` is required for publishing. What if we added
```suggestion
"compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0,10))},
"assets": {
``` | 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) => `\
{
"main"... | @@ -80,6 +80,16 @@ export default async function seed() {
// TODO
}
`,
+ CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
+{
+ "main": "dist/_worker.js/index.js",
+ "name": ${JSON.stringify(name)},
+ "assets": { | packages/astro/src/cli/add/index.ts | 26 | TypeScript | 0.714 | suggestion | 182 | 51 | 51 | false | feat(cli): scaffold wrangler.jsonc in astro add | 14,564 | withastro/astro | 47,179 | TypeScript | OliverSpeir | florian-lefebvre |
}\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: `\
import { db } from 'astro:db';
// https://astro.buil... | ```suggestion
"compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0,10))},
"compatibility_flags": [
"nodejs_compat",
"global_fetch_strictly_public"
],
```
from wrangler cli https://github.com/cloudflare/workers-sdk/blob/ca6c01017ccc39671e8724a6b9a5aa37a5e07e57/packages/create-cl... | }\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: `\
import { db } from 'astro:db';
// https://astro.buil... | @@ -80,6 +80,17 @@ export default async function seed() {
// TODO
}
`,
+ CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
+{
+ "main": "dist/_worker.js/index.js",
+ "name": ${JSON.stringify(name)},
+ "compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0,10))}, | packages/astro/src/cli/add/index.ts | 26 | TypeScript | 0.786 | suggestion | 383 | 51 | 51 | false | feat(cli): scaffold wrangler.jsonc in astro add | 14,564 | withastro/astro | 47,179 | TypeScript | OliverSpeir | florian-lefebvre |
`,
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) => `\
{
"ma... | ```suggestion
},
"observability": {
"enabled": true
}
```
from wrangler cli and our deploy guide
https://github.com/cloudflare/workers-sdk/blob/ca6c01017ccc39671e8724a6b9a5aa37a5e07e57/packages/create-cloudflare/templates/astro/workers/templates/ts/wrangler.jsonc#L13C1-L15C5 | `,
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) => `\
{
"ma... | @@ -80,6 +80,17 @@ export default async function seed() {
// TODO
}
`,
+ CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
+{
+ "main": "dist/_worker.js/index.js",
+ "name": ${JSON.stringify(name)},
+ "compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0,10))},
+ "assets": {
+ "binding": "ASSETS"... | packages/astro/src/cli/add/index.ts | 26 | TypeScript | 0.786 | suggestion | 293 | 51 | 51 | false | feat(cli): scaffold wrangler.jsonc in astro add | 14,564 | withastro/astro | 47,179 | TypeScript | OliverSpeir | florian-lefebvre |
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: `\
impo... | @OliverSpeir should we also include `$schema`? |
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: `\
impo... | @@ -80,6 +80,24 @@ export default async function seed() {
// TODO
}
`,
+ CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
+{ | packages/astro/src/cli/add/index.ts | 26 | TypeScript | 0.286 | question | 46 | 51 | 51 | false | feat(cli): scaffold wrangler.jsonc in astro add | 14,564 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | florian-lefebvre |
import type { ExternalImageService } from 'astro';
import { baseService } from 'astro/assets';
import { isESMImportedImage } from 'astro/assets/utils';
import { sharedValidateOptions } from './shared.js';
const service: ExternalImageService = {
...baseService,
validateOptions: (options, serviceOptions) =>
sharedVa... | surprised this non-null assertion doesn't trigger a linting thing | const sortedDensityValues = densityValues.sort((a, b) => a - b);
allWidths = calculatedWidths.map((width, index) => {
// Check if this width is already in the configured widths
if (configuredWidths.includes(width)) {
return {
width,
descriptor: `${sortedDensityValues[index]}x`,
};
... | @@ -114,13 +118,43 @@ const service: ExternalImageService = {
});
// Calculate the widths for each density, rounding to avoid floats.
- const densityWidths = densityValues
+ const calculatedWidths = densityValues
.sort((a, b) => a - b)
.map((density) => Math.round(targetWidth! * density));
- ... | packages/integrations/vercel/src/image/build-service.ts | 26 | TypeScript | 0.357 | style | 65 | 147 | 51 | false | fix(vercel): validate densities-based srcset widths against configured sizes | 14,570 | withastro/astro | 47,179 | TypeScript | Princesseuh | matthewp |
);
if (!resolvedModule) {
return RESOLVED_NOOP_ENTRYPOINT_VIRTUAL_MODULE_ID;
}
resolvedActionsId = resolvedModule.id;
return RESOLVED_ENTRYPOINT_VIRTUAL_MODULE_ID;
}
},
async configureServer(server) {
const filePresentOnStartup = await isActionsFilePresent(fs, settings.config.srcDir... | If we're exporting this file from a vite module, doesn't that mean that `virtual.js` doesn't need to be a runtime code? Or is there something else I missed? | `${decodeURI(new URL('actions', settings.config.srcDir).pathname)}`,
);
if (!resolvedModule) {
return RESOLVED_NOOP_ENTRYPOINT_VIRTUAL_MODULE_ID;
}
resolvedActionsId = resolvedModule.id;
return RESOLVED_ENTRYPOINT_VIRTUAL_MODULE_ID;
}
},
async configureServer(server) {
const fi... | @@ -99,6 +100,10 @@ export function vitePluginActions({
server.watcher.on('change', watcherCallback);
},
async load(id, opts) {
+ if (id === RESOLVED_VIRTUAL_MODULE_ID) {
+ return { code: `export * from 'astro/actions/runtime/virtual.js';` } | packages/astro/src/actions/vite-plugin-actions.ts | 26 | TypeScript | 0.5 | question | 157 | 50 | 51 | false | fix(actions): virtual module | 14,582 | withastro/astro | 47,179 | TypeScript | ematipico | florian-lefebvre |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.