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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
export async function generateFallbacksCSS({
family,
fallbacks: _fallbacks,
font: fontData,
metrics,
}: {
family: Pick<ResolvedFontFamily, 'name' | 'nameWithHash'>;
/** The family fallbacks */
fallbacks: Array<string>;
font: GetMetricsForFamilyFont;
metrics: {
getMetricsForFamily: GetMetricsForFamily;
gene... | No issues found. | export async function generateFallbacksCSS({
family,
fallbacks: _fallbacks,
font: fontData,
metrics,
}: {
family: Pick<ResolvedFontFamily, 'name' | 'nameWithHash'>;
/** The family fallbacks */
fallbacks: Array<string>;
font: GetMetricsForFamilyFont;
metrics: {
getMetricsForFamily: GetMetricsForFamily;
gene... | @@ -1,25 +1,17 @@
import type * as unifont from 'unifont';
import type {
- BuiltInProvider,
FontFamily,
- FontProvider,
FontType,
LocalFontFamily,
ResolvedFontFamily,
ResolvedLocalFontFamily,
} from './types.js';
import { extname } from 'node:path';
-import {
- DEFAULT_FALLBACKS,
- FONT_TYPES,
- GOOGLE_PR... | packages/astro/src/assets/fonts/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): remove default provider | 13,572 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
import type { HydrationMetadata } from '../hydration.js';
const RenderInstructionSymbol = Symbol.for('astro:render');
export type RenderDirectiveInstruction = {
type: 'directive';
hydration: HydrationMetadata;
};
export type RenderHeadInstruction = {
type: 'head';
};
/**
* Render a renderer-specific hydration s... | No issues found. | import type { HydrationMetadata } from '../hydration.js';
const RenderInstructionSymbol = Symbol.for('astro:render');
export type RenderDirectiveInstruction = {
type: 'directive';
hydration: HydrationMetadata;
};
export type RenderHeadInstruction = {
type: 'head';
};
/**
* Render a renderer-specific hydration s... | @@ -25,24 +25,19 @@ export type MaybeRenderHeadInstruction = {
type: 'maybe-head';
};
+export type ServerIslandRuntimeInstruction = {
+ type: 'server-island-runtime';
+};
+
export type RenderInstruction =
| RenderDirectiveInstruction
| RenderHeadInstruction
| MaybeRenderHeadInstruction
- | RendererHydration... | packages/astro/src/runtime/server/render/instruction.ts | 0 | TypeScript | 1 | none | 16 | 48 | 48 | true | fix: extract shared logic for server island loading into a function and only include it once | 13,576 | withastro/astro | 47,179 | TypeScript | ascorbic | |
* prefetchAll: true
* }
* ```
*
* When set to `true`, you can disable prefetching individually by setting `data-astro-prefetch="false"` on any individual links.
*
* ```html
* <a href="/about" data-astro-prefetch="false">About</a>
*```
*/
prefetchAll?: boolean;
... | No issues found. | * prefetchAll: true
* }
* ```
*
* When set to `true`, you can disable prefetching individually by setting `data-astro-prefetch="false"` on any individual links.
*
* ```html
* <a href="/about" data-astro-prefetch="false">About</a>
*```
*/
prefetchAll?: boolean;
... | @@ -2176,42 +2176,6 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
responsiveImages?: boolean;
- /**
- *
- * @name experimental.svg
- * @type {boolean}
- * @default `undefined`
- * @version 5.x
- * @description
- *
- * This feature allows you to import SVG files directly int... | packages/astro/src/types/public/config.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: unflag svg component feature | 13,578 | withastro/astro | 47,179 | TypeScript | stramel | |
// This file is code-generated, please don't change it manually
export default [
"GI/D8grziRZwfj/Mqmn+dcgU/i8sylHSR/IfobqcUT4=",
"HDWxd14AUw8OvjrhhRRyyZFHCGnzxXGDrg59Qi8ayhc=",
"XN6a2Vn8uvpBr/WhdYPdK0jVeCzlcOD2XYaP10veV4Y=",
"ZR0ZAU8UNTzLmo/ApeWH0y1mVLT+XtFkvZ5nw32W8jI=",
"cSNmhdbFlyTDRozeu9HPjo+B2S4QAeMp0RO41PqgA... | No issues found. | // This file is code-generated, please don't change it manually
export default [
"GI/D8grziRZwfj/Mqmn+dcgU/i8sylHSR/IfobqcUT4=",
"HDWxd14AUw8OvjrhhRRyyZFHCGnzxXGDrg59Qi8ayhc=",
"XN6a2Vn8uvpBr/WhdYPdK0jVeCzlcOD2XYaP10veV4Y=",
"ZR0ZAU8UNTzLmo/ApeWH0y1mVLT+XtFkvZ5nw32W8jI=",
"cSNmhdbFlyTDRozeu9HPjo+B2S4QAeMp0RO41PqgA... | @@ -0,0 +1,10 @@
+// This file is code-generated, please don't change it manually
+export default [
+ "GI/D8grziRZwfj/Mqmn+dcgU/i8sylHSR/IfobqcUT4=",
+ "HDWxd14AUw8OvjrhhRRyyZFHCGnzxXGDrg59Qi8ayhc=",
+ "XN6a2Vn8uvpBr/WhdYPdK0jVeCzlcOD2XYaP10veV4Y=",
+ "ZR0ZAU8UNTzLmo/ApeWH0y1mVLT+XtFkvZ5nw32W8jI=",
+ "cSNmhdbFlyTDRozeu... | packages/astro/src/core/csp-hashes.js | 0 | JavaScript | 1 | none | 16 | 10 | 10 | true | chore: build hashes of scripts | 13,590 | withastro/astro | 47,179 | TypeScript | ematipico | |
entrypoint: 'astro/assets/fonts/providers/adobe',
config,
});
}
/** [Bunny](https://fonts.bunny.net/) */
function bunny() {
return defineAstroFontProvider({
entrypoint: 'astro/assets/fonts/providers/bunny',
});
}
/** [Fontshare](https://www.fontshare.com/) */
function fontshare() {
return defineAstroFontPro... | No issues found. | entrypoint: 'astro/assets/fonts/providers/adobe',
config,
});
}
/** [Bunny](https://fonts.bunny.net/) */
function bunny() {
return defineAstroFontProvider({
entrypoint: 'astro/assets/fonts/providers/bunny',
});
}
/** [Fontshare](https://www.fontshare.com/) */
function fontshare() {
return defineAstroFontPro... | @@ -1,25 +1,29 @@
import type { providers } from 'unifont';
-import type { FontProvider } from '../types.js';
+import type { AstroFontProvider } from '../types.js';
+/** [Adobe](https://fonts.adobe.com/) */
function adobe(config: Parameters<typeof providers.adobe>[0]) {
return defineAstroFontProvider({
entrypo... | packages/astro/src/assets/fonts/providers/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): jsdocs | 13,600 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
}
// check if the link starts with http or https; if not, throw an error
if (URL.canParse(destination) && !/^https?:\/\//.test(destination)) {
throw new AstroError(UnsupportedExternalRedirect);
}
routes.push({
type: 'redirect',
// For backwards compatibility, a redirect is never considered an index... | No issues found. | }
// check if the link starts with http or https; if not, throw an error
if (URL.canParse(destination) && !/^https?:\/\//.test(destination)) {
throw new AstroError(UnsupportedExternalRedirect);
}
routes.push({
type: 'redirect',
// For backwards compatibility, a redirect is never considered an index... | @@ -357,12 +357,9 @@ function createRedirectRoutes(
destination = to.destination;
}
- // URLs that don't start with leading slash should be considered external
- if (!destination.startsWith('/')) {
- // check if the link starts with http or https; if not, log a warning
- if (!/^https?:\/\//.test(destinat... | packages/astro/src/core/routing/manifest/create.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix relative redirects regression. Closes #13607 | 13,616 | withastro/astro | 47,179 | TypeScript | lfilho | |
// Extracted from https://raw.githubusercontent.com/seek-oss/capsize/refs/heads/master/packages/metrics/src/entireMetricsCollection.json
export const SYSTEM_METRICS = {
'Times New Roman': {
ascent: 1825,
descent: -443,
lineGap: 87,
unitsPerEm: 2048,
xWidthAvg: 832,
},
Arial: {
ascent: 1854,
descent: -... | No issues found. |
// Extracted from https://raw.githubusercontent.com/seek-oss/capsize/refs/heads/master/packages/metrics/src/entireMetricsCollection.json
export const SYSTEM_METRICS = {
'Times New Roman': {
ascent: 1825,
descent: -443,
lineGap: 87,
unitsPerEm: 2048,
xWidthAvg: 832,
},
Arial: {
ascent: 1854,
descent: -... | @@ -1,3 +1,4 @@
+import type { FontFaceMetrics } from './metrics.js';
import type { ResolvedRemoteFontFamily } from './types.js';
export const LOCAL_PROVIDER_NAME = 'local';
@@ -20,8 +21,61 @@ export const CACHE_DIR = './fonts/';
export const FONT_TYPES = ['woff2', 'woff', 'otf', 'ttf', 'eot'] as const;
+// Ex... | packages/astro/src/assets/fonts/constants.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): fallback improvements | 13,632 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
});
});
describe('resolveFontFamily()', () => {
const root = new URL(import.meta.url);
it('handles the local provider correctly', async () => {
assert.deepStrictEqual(
await resolveFontFamily({
family: {
name: 'Custom',
cssVariable: '--custom',
provider: 'local',
variants: ... | No issues found. | });
});
describe('resolveFontFamily()', () => {
const root = new URL(import.meta.url);
it('handles the local provider correctly', async () => {
assert.deepStrictEqual(
await resolveFontFamily({
family: {
name: 'Custom',
cssVariable: '--custom',
provider: 'local',
variants: ... | @@ -1,5 +1,5 @@
-import assert from 'node:assert/strict';
// @ts-check
+import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import { fontProviders } from '../../../../dist/assets/fonts/providers/index.js';
@@ -121,14 +121,21 @@ describe('fonts... | packages/astro/test/units/assets/fonts/utils.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): generate fallbacks for all faces | 13,635 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
generateFontFace: (_metrics, fallback) => `[${fallback.font},${fallback.name}]`,
},
}),
{
css: '',
fallbacks: ['sans-serif', 'foo'],
},
);
});
});
describe('resolveFontFamily()', () => {
const root = new URL(import.meta.url);
it('handles the local provider correctly', async... | No issues found. | generateFontFace: (_metrics, fallback) => `[${fallback.font},${fallback.name}]`,
},
}),
{
css: '',
fallbacks: ['sans-serif', 'foo'],
},
);
});
});
describe('resolveFontFamily()', () => {
const root = new URL(import.meta.url);
it('handles the local provider correctly', async... | @@ -411,7 +411,7 @@ describe('fonts utils', () => {
assert.equal(result.providers.length, length);
},
/**
- * @param {Array<string | undefined>} names
+ * @param {Array<string>} names
*/
assertProvidersNames: (names) => {
assert.deepStrictEqual(
@@ -479,7 +479,7 @@ describe('fon... | packages/astro/test/units/assets/fonts/utils.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(fonts): providers deduplication logic | 13,639 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
family: {
name: 'Test',
nameWithHash: 'Test-xxx',
cssVariable: '--test',
provider: 'local',
variants: [
{
weight: '400',
style: 'normal',
src: [{ url: '/test.woff2' }, { url: '/ignored.woff' }],
},
{
weight: '500',
style: 'normal',
... | No issues found. | family: {
name: 'Test',
nameWithHash: 'Test-xxx',
cssVariable: '--test',
provider: 'local',
variants: [
{
weight: '400',
style: 'normal',
src: [{ url: '/test.woff2' }, { url: '/ignored.woff' }],
},
{
weight: '500',
style: 'normal',
... | @@ -10,6 +10,7 @@ import * as googleEntrypoint from '../../../../dist/assets/fonts/providers/entry
import { resolveLocalFont } from '../../../../dist/assets/fonts/providers/local.js';
import { fontProviders } from '../../../../dist/config/entrypoint.js';
import { createSpyUrlProxy, simpleErrorHandler } from './utils... | packages/astro/test/units/assets/fonts/providers.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): local provider infer | 13,640 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
);
});
});
describe('resolveFontFamily()', () => {
const root = new URL(import.meta.url);
it('handles the local provider correctly', async () => {
assert.deepStrictEqual(
await resolveFontFamily({
family: {
name: 'Custom',
cssVariable: '--custom',
provider: 'local',
vari... | No issues found. | );
});
});
describe('resolveFontFamily()', () => {
const root = new URL(import.meta.url);
it('handles the local provider correctly', async () => {
assert.deepStrictEqual(
await resolveFontFamily({
family: {
name: 'Custom',
cssVariable: '--custom',
provider: 'local',
vari... | @@ -550,6 +550,18 @@ describe('fonts utils', () => {
false,
);
});
+ it('wraps format in quotes', () => {
+ assert.equal(
+ renderFontSrc([{ url: 'test', format: 'woff2' }]).includes('format("woff2")'),
+ true,
+ );
+ });
+ it('does not wrap tech in quotes', () => {
+ assert.equal(
+ rende... | packages/astro/test/units/assets/fonts/utils.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(font): type to format mapping | 13,643 | withastro/astro | 47,179 | TypeScript | tanishqmanuja | |
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... | No issues found. | 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... | @@ -30,3 +30,5 @@ export type Polymorphic<P extends { as: HTMLTag }> = PolymorphicAttributes<
>;
export type ComponentProps<T extends (args: any) => any> = Simplify<Parameters<T>[0]>;
+
+export type SvgComponent = (props: astroHTML.JSX.SVGAttributes) => any; | packages/astro/types.d.ts | 0 | TypeScript | 1 | none | 16 | 35 | 35 | true | feat(types): add SvgComponent type and update SVG module declaration | 13,651 | withastro/astro | 47,179 | TypeScript | ADTC | |
const newProps = {
...props,
...slots,
};
const newChildren = children ?? props.children;
if (children && opts.experimentalReactChildren) {
attrs['data-react-children'] = true;
const convert = await import('./vnode-children.js').then((mod) => mod.default);
newProps.children = convert(children);
} else if... | No issues found. | const newProps = {
...props,
...slots,
};
const newChildren = children ?? props.children;
if (children && opts.experimentalReactChildren) {
attrs['data-react-children'] = true;
const convert = await import('./vnode-children.js').then((mod) => mod.default);
newProps.children = convert(children);
} else if... | @@ -1,14 +1,21 @@
import opts from 'astro:react:opts';
+import type { AstroComponentMetadata } from 'astro';
import React from 'react';
import ReactDOM from 'react-dom/server';
import { incrementId } from './context.js';
import StaticHtml from './static-html.js';
+import type { RendererContext } from './types.js';... | packages/integrations/react/src/server.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: convert integrations to TS | 13,663 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
import { before, describe, it } from 'node:test';
import { loadFixture } from './test-utils.js';
import testAdapter from './test-adapter.js';
import assert from 'node:assert/strict';
import * as cheerio from 'cheerio';
describe('CSP', () => {
let app;
/**
* @type {import('../dist/core/build/types.js').SSGManifest}... | No issues found. | import { before, describe, it } from 'node:test';
import { loadFixture } from './test-utils.js';
import testAdapter from './test-adapter.js';
import assert from 'node:assert/strict';
import * as cheerio from 'cheerio';
describe('CSP', () => {
let app;
/**
* @type {import('../dist/core/build/types.js').SSGManifest}... | @@ -0,0 +1,42 @@
+import { before, describe, it } from 'node:test';
+import { loadFixture } from './test-utils.js';
+import testAdapter from './test-adapter.js';
+import assert from 'node:assert/strict';
+import * as cheerio from 'cheerio';
+
+describe('CSP', () => {
+ let app;
+ /**
+ * @type {import('../dist/core/bu... | packages/astro/test/csp.test.js | 0 | JavaScript | 1 | none | 16 | 43 | 43 | true | feat(csp): create hashes of tracked scripts and hashes | 13,675 | withastro/astro | 47,179 | TypeScript | ematipico | |
* It works by trying to get metrics (using capsize) of the provided font family.
* If some can be computed, they will be applied to the eligible fallbacks to match
* the original font shape as close as possible.
*/
export async function generateFallbacksCSS({
family,
fallbacks: _fallbacks,
font: fontData,
metri... | No issues found. | * It works by trying to get metrics (using capsize) of the provided font family.
* If some can be computed, they will be applied to the eligible fallbacks to match
* the original font shape as close as possible.
*/
export async function generateFallbacksCSS({
family,
fallbacks: _fallbacks,
font: fontData,
metri... | @@ -1,6 +1,6 @@
import { createRequire } from 'node:module';
import { extname } from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
+import { pathToFileURL } from 'node:url';
import type * as unifont from 'unifont';
import type { Storage } from 'unstorage';
import { AstroError, AstroErrorDa... | packages/astro/src/assets/fonts/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): warn if local font is in public dir | 13,678 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
// If `validateOptions` returned a different width than the one of the image, use it for attributes
if (inputtedWidth) {
props.width = inputtedWidth;
}
let targetWidth = props.width;
let targetHeight = props.height;
if (isESMImportedImage(props.src)) {
const aspectRatio = props.src.width / props.src... | No issues found. |
// If `validateOptions` returned a different width than the one of the image, use it for attributes
if (inputtedWidth) {
props.width = inputtedWidth;
}
let targetWidth = props.width;
let targetHeight = props.height;
if (isESMImportedImage(props.src)) {
const aspectRatio = props.src.width / props.src... | @@ -1,6 +1,7 @@
import type { ExternalImageService } from 'astro';
import { baseService } from 'astro/assets';
-import { isESMImportedImage, sharedValidateOptions } from './shared.js';
+import { sharedValidateOptions } from './shared.js';
+import { isESMImportedImage } from 'astro/assets/utils';
const service: Ext... | packages/integrations/vercel/src/image/build-service.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(vercel): handle SVG images correctly in build image service | 13,679 | withastro/astro | 47,179 | TypeScript | moonclavedev | |
// check if the link starts with http or https; if not, throw an error
if (URL.canParse(destination) && !/^https?:\/\//.test(destination)) {
throw new AstroError({
...UnsupportedExternalRedirect,
message: UnsupportedExternalRedirect.message(from, destination),
});
}
routes.push({
type: 'redire... | No issues found. | // check if the link starts with http or https; if not, throw an error
if (URL.canParse(destination) && !/^https?:\/\//.test(destination)) {
throw new AstroError({
...UnsupportedExternalRedirect,
message: UnsupportedExternalRedirect.message(from, destination),
});
}
routes.push({
type: 'redire... | @@ -359,7 +359,10 @@ function createRedirectRoutes(
// check if the link starts with http or https; if not, throw an error
if (URL.canParse(destination) && !/^https?:\/\//.test(destination)) {
- throw new AstroError(UnsupportedExternalRedirect);
+ throw new AstroError({
+ ...UnsupportedExternalRedirect,
... | packages/astro/src/core/routing/manifest/create.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: improve external redirects message | 13,680 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
import assert from 'node:assert/strict';
import { before, describe, it } from 'node:test';
import { sitemap } from './fixtures/static/deps.mjs';
import { loadFixture, readXML } from './test-utils.js';
describe('Sitemap with custom pages', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
/** ... | No issues found. | import assert from 'node:assert/strict';
import { before, describe, it } from 'node:test';
import { sitemap } from './fixtures/static/deps.mjs';
import { loadFixture, readXML } from './test-utils.js';
describe('Sitemap with custom pages', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
/** ... | @@ -0,0 +1,29 @@
+import assert from 'node:assert/strict';
+import { before, describe, it } from 'node:test';
+import { sitemap } from './fixtures/static/deps.mjs';
+import { loadFixture, readXML } from './test-utils.js';
+
+describe('Sitemap with custom pages', () => {
+ /** @type {import('./test-utils.js').Fixture} ... | packages/integrations/sitemap/test/custom-pages.test.js | 0 | JavaScript | 1 | none | 16 | 30 | 30 | true | feat(@astro/sitemap): custom sitemaps | 13,682 | withastro/astro | 47,179 | TypeScript | gouravkhunger | |
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: '`getEntry()` requires an entry identifier as the second argument.',
});
lookupId = lookup;
} else {
collection = collectionOrLookupObject.collection;
// Identifier could be `slug` for content entries, or `id` ... | No issues found. | throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: '`getEntry()` requires an entry identifier as the second argument.',
});
lookupId = lookup;
} else {
collection = collectionOrLookupObject.collection;
// Identifier could be `slug` for content entries, or `id` ... | @@ -19,14 +19,19 @@ import {
render as serverRender,
unescapeHTML,
} from '../runtime/server/index.js';
-import { CONTENT_LAYER_TYPE, IMAGE_IMPORT_PREFIX } from './consts.js';
+import { CONTENT_LAYER_TYPE, IMAGE_IMPORT_PREFIX, LIVE_CONTENT_TYPE } from './consts.js';
import { type DataEntry, globalDataStore } from... | packages/astro/src/content/runtime.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: initial live loader implementation | 13,688 | withastro/astro | 47,179 | TypeScript | ascorbic | |
root: './fixtures/i18n-routing-fallback-rewrite/',
base: '/base',
});
await fixture.build();
});
it('should rewrite dynamic fallback route with base', async () => {
let html = await fixture.readFile('/es/slug-1/index.html');
assert.equal(html.includes('slug-1'), true);
});
it('should rewrit... | No issues found. | root: './fixtures/i18n-routing-fallback-rewrite/',
base: '/base',
});
await fixture.build();
});
it('should rewrite dynamic fallback route with base', async () => {
let html = await fixture.readFile('/es/slug-1/index.html');
assert.equal(html.includes('slug-1'), true);
});
it('should rewrit... | @@ -1072,6 +1072,85 @@ describe('[SSG] i18n routing', () => {
});
});
+ describe('i18n routing with fallback rewrite from dynamic route', () => {
+ /** @type {import('./test-utils').Fixture} */
+ let fixture;
+
+ before(async () => {
+ fixture = await loadFixture({
+ root: './fixtures/i18n-routing-fallba... | packages/astro/test/i18n-routing.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix: fallback and rewrite dynamic route pattern matching | 13,697 | withastro/astro | 47,179 | TypeScript | benosmac | |
families: resolvedFamilies,
hasher,
});
resolvedFamilies = extractedUnifontProvidersResult.families;
const unifontProviders = extractedUnifontProvidersResult.providers;
const { resolveFont } = await unifont.createUnifont(unifontProviders, {
storage,
});
/**
* Holds associations of hash and original font... | No issues found. | families: resolvedFamilies,
hasher,
});
resolvedFamilies = extractedUnifontProvidersResult.families;
const unifontProviders = extractedUnifontProvidersResult.providers;
const { resolveFont } = await unifont.createUnifont(unifontProviders, {
storage,
});
/**
* Holds associations of hash and original font... | @@ -25,6 +25,8 @@ import type {
PreloadData,
} from './types.js';
import { pickFontFaceProperty, unifontFontFaceDataToProperties } from './utils.js';
+import { bold } from 'kleur/colors';
+import type { Logger } from '../../core/logger/core.js';
/**
* Manages how fonts are resolved:
@@ -54,6 +56,7 @@ export as... | packages/astro/src/assets/fonts/orchestrate.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): warn when no data | 13,756 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
} else if (ext === 'yml' || ext === 'yaml') {
parse = (text) =>
yaml.load(text, {
filename: fileName,
});
}
if (options?.parser) parse = options.parser;
if (parse === null) {
throw new AstroError({
...FileParserNotFound,
message: FileParserNotFound.message(fileName),
});
}
async function s... | No issues found. | } else if (ext === 'yml' || ext === 'yaml') {
parse = (text) =>
yaml.load(text, {
filename: fileName,
});
}
if (options?.parser) parse = options.parser;
if (parse === null) {
throw new AstroError({
...FileParserNotFound,
message: FileParserNotFound.message(fileName),
});
}
async function s... | @@ -4,6 +4,7 @@ import yaml from 'js-yaml';
import { AstroError } from '../../core/errors/index.js';
import { posixRelative } from '../utils.js';
import type { Loader, LoaderContext } from './types.js';
+import { FileGlobNotSupported, FileParserNotFound } from '../../core/errors/errors-data.js';
interface FileOpt... | packages/astro/src/content/loaders/file.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(astro): put them to follow a pattern for errors | 13,761 | withastro/astro | 47,179 | TypeScript | jp-knj | |
*/
export const UnsupportedExternalRedirect = {
name: 'UnsupportedExternalRedirect',
title: 'Unsupported or malformed URL.',
message: (from: string, to: string) =>
`The destination URL in the external redirect from "${from}" to "${to}" is unsupported.`,
hint: 'An external redirect must start with http or https, ... | No issues found. | */
export const UnsupportedExternalRedirect = {
name: 'UnsupportedExternalRedirect',
title: 'Unsupported or malformed URL.',
message: (from: string, to: string) =>
`The destination URL in the external redirect from "${from}" to "${to}" is unsupported.`,
hint: 'An external redirect must start with http or https, ... | @@ -1672,6 +1672,25 @@ export const ContentEntryDataError = {
hint: 'See https://docs.astro.build/en/guides/content-collections/ for more information on content schemas.',
} satisfies ErrorData;
+/**
+ * @docs
+ * @message
+ * **Example error message:**<br/>
+ * The schema cannot be a function for live collections... | packages/astro/src/core/errors/errors-data.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: add schema parsing to live collections | 13,763 | withastro/astro | 47,179 | TypeScript | ascorbic | |
x: 'foo',
},
},
},
{
name: 'Bar',
nameWithHash: 'Bar-xxx',
cssVariable: '--custom',
provider: {
provider: createProvider('test'),
config: {
x: 'bar',
},
},
},
]);
fixture.assertProvidersLength(2);
fixture.assertProvidersNames([
... | No issues found. | x: 'foo',
},
},
},
{
name: 'Bar',
nameWithHash: 'Bar-xxx',
cssVariable: '--custom',
provider: {
provider: createProvider('test'),
config: {
x: 'bar',
},
},
},
]);
fixture.assertProvidersLength(2);
fixture.assertProvidersNames([
... | @@ -450,6 +450,54 @@ describe('fonts logic', () => {
},
]);
});
+
+ it('turns relative protocols into https', () => {
+ const { collected, urlProxy } = createSpyUrlProxy();
+ const fonts = normalizeRemoteFontFaces({
+ urlProxy,
+ fonts: [
+ {
+ weight: '400',
+ style: 'normal',
+ ... | packages/astro/test/units/assets/fonts/logic.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(fonts): relative protocol urls | 13,765 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
collection: string;
data: Record<string, any>;
};
type EntryLookupObject = { collection: string; id: string } | { collection: string; slug: string };
function emulateLegacyEntry({ legacyId, ...entry }: DataEntry & { collection: string }) {
// Define this first so it's in scope for the render function
const legacy... | No issues found. | collection: string;
data: Record<string, any>;
};
type EntryLookupObject = { collection: string; id: string } | { collection: string; slug: string };
function emulateLegacyEntry({ legacyId, ...entry }: DataEntry & { collection: string }) {
// Define this first so it's in scope for the render function
const legacy... | @@ -121,6 +121,11 @@ export function createCollectionToGlobResultMap({
return collectionToGlobResultMap;
}
+const cacheHintSchema = z.object({
+ tags: z.array(z.string()).optional(),
+ maxAge: z.number().optional(),
+});
+
async function parseLiveEntry(
entry: LiveDataEntry,
schema: z.ZodType,
@@ -137,6 +142,... | packages/astro/src/content/runtime.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: add cache hint support to live loaders | 13,767 | withastro/astro | 47,179 | TypeScript | ascorbic | |
describe('db client config', () => {
test('parse config options from URL (docs example url)', () => {
const remoteURLToParse = new URL('file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io');
const options = Object.fromEntries(remoteURLToParse... | No issues found. |
describe('db client config', () => {
test('parse config options from URL (docs example url)', () => {
const remoteURLToParse = new URL('file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io');
const options = Object.fromEntries(remoteURLToParse... | @@ -0,0 +1,56 @@
+import assert from 'node:assert';
+import test, { describe } from 'node:test';
+import { parseOpts } from '../../dist/runtime/db-client.js';
+
+describe('db client config', () => {
+ test('parse config options from URL (docs example url)', () => {
+ const remoteURLToParse = new URL('file://l... | packages/db/test/unit/db-client.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix(db): update db-client connection options parsing | 13,772 | withastro/astro | 47,179 | TypeScript | Adammatthiesen | |
assert.equal(href?.startsWith('/_astro/fonts/'), true);
});
});
it('Has correct headers in dev', async () => {
const { fixture, run } = await createDevFixture({
experimental: {
fonts: [
{
name: 'Roboto',
cssVariable: '--font-roboto',
provider: fontProviders.fontsource(... | No issues found. | assert.equal(href?.startsWith('/_astro/fonts/'), true);
});
});
it('Has correct headers in dev', async () => {
const { fixture, run } = await createDevFixture({
experimental: {
fonts: [
{
name: 'Roboto',
cssVariable: '--font-roboto',
provider: fontProviders.fontsource(... | @@ -1,76 +1,101 @@
// @ts-check
import assert from 'node:assert/strict';
-import { after, before, describe, it } from 'node:test';
+import { describe, it } from 'node:test';
import { fontProviders } from 'astro/config';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';
+import { re... | packages/astro/test/fonts.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(fonts): take build config into account | 13,784 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
if (manifest) {
const request = new Request('http://example.com/index.html');
const response = await app.render(request);
const $ = cheerio.load(await response.text());
const meta = $('meta[http-equiv="Content-Security-Policy"]');
for (const hash of manifest.csp.clientStyleHashes) {
assert.match(
... | No issues found. | if (manifest) {
const request = new Request('http://example.com/index.html');
const response = await app.render(request);
const $ = cheerio.load(await response.text());
const meta = $('meta[http-equiv="Content-Security-Policy"]');
for (const hash of manifest.csp.clientStyleHashes) {
assert.match(
... | @@ -32,15 +32,74 @@ describe('CSP', () => {
const $ = cheerio.load(await response.text());
const meta = $('meta[http-equiv="Content-Security-Policy"]');
- for (const hash of manifest.clientStyleHashes) {
+ for (const hash of manifest.csp.clientStyleHashes) {
assert.match(
meta.attr('content'),
... | packages/astro/test/csp.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(csp): customise algorithm | 13,803 | withastro/astro | 47,179 | TypeScript | ematipico | |
configError.errors[0].message,
"The locale `lorem` key in the `i18n.domains` record doesn't exist in the `i18n.locales` array.",
);
});
it('errors if a domains value is not an URL', async () => {
const configError = await validateConfig({
output: 'server',
site: 'https://www.example.com',
... | No issues found. | configError.errors[0].message,
"The locale `lorem` key in the `i18n.domains` record doesn't exist in the `i18n.locales` array.",
);
});
it('errors if a domains value is not an URL', async () => {
const configError = await validateConfig({
output: 'server',
site: 'https://www.example.com',
... | @@ -479,4 +479,40 @@ describe('Config Validation', () => {
);
});
});
+
+ describe('csp', () => {
+ it('should throw an error if incorrect scriptHashes are passed', async () => {
+ let configError = await validateConfig({
+ experimental: {
+ csp: {
+ scriptHashes: ['fancy-1234567890'],
+ },
... | packages/astro/test/units/config/config-validate.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | chore: build hashes of scripts (#13590) | 13,805 | withastro/astro | 47,179 | TypeScript | ematipico | |
[...consumableMap.entries()],
[
[
'--test',
[
{
weight: '400',
style: 'normal',
src: [
{
url: joinPaths('/test', fileURLToPath(new URL('my-font.woff2.woff2', root))),
format: 'woff2',
tech: undefined,
},
{
url: jo... | No issues found. | [...consumableMap.entries()],
[
[
'--test',
[
{
weight: '400',
style: 'normal',
src: [
{
url: joinPaths('/test', fileURLToPath(new URL('my-font.woff2.woff2', root))),
format: 'woff2',
tech: undefined,
},
{
url: jo... | @@ -33,7 +33,7 @@ describe('fonts orchestrate()', () => {
const errorHandler = simpleErrorHandler;
const fontTypeExtractor = createFontTypeExtractor({ errorHandler });
const hasher = fakeHasher;
- const { fontFileDataMap, consumableMap } = await orchestrate({
+ const { fontFileDataMap, internalConsumableMap,... | packages/astro/test/units/assets/fonts/orchestrate.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): getFontData | 13,811 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
const meta = $('meta[http-equiv="Content-Security-Policy"]');
assert.ok(meta.attr('content').toString().includes('sha512-'));
});
it('should generate the hash with the sha384 algorithm', async () => {
fixture = await loadFixture({
root: './fixtures/csp/',
adapter: testAdapter({
setManifest(_manifest)... | No issues found. | const meta = $('meta[http-equiv="Content-Security-Policy"]');
assert.ok(meta.attr('content').toString().includes('sha512-'));
});
it('should generate the hash with the sha384 algorithm', async () => {
fixture = await loadFixture({
root: './fixtures/csp/',
adapter: testAdapter({
setManifest(_manifest)... | @@ -30,47 +30,65 @@ describe('CSP', () => {
const $ = cheerio.load(await response.text());
const meta = $('meta[http-equiv="Content-Security-Policy"]');
- for (const hash of manifest.csp.clientStyleHashes) {
- assert.match(
- meta.attr('content'),
- new RegExp(`'${hash}'`),
- `Should have a C... | packages/astro/test/csp.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(csp): resources for script and styles directives | 13,812 | withastro/astro | 47,179 | TypeScript | ematipico | |
export { defineDbIntegration } from './core/utils.js';
import { tableSchema } from './core/schemas.js';
import type { ColumnsConfig, TableConfig } from './core/types.js';
import { type Table, asDrizzleTable as internal_asDrizzleTable } from './runtime/index.js';
export function asDrizzleTable<
TableName extends strin... | No issues found. | export { defineDbIntegration } from './core/utils.js';
import { tableSchema } from './core/schemas.js';
import type { ColumnsConfig, TableConfig } from './core/types.js';
import { type Table, asDrizzleTable as internal_asDrizzleTable } from './runtime/index.js';
export function asDrizzleTable<
TableName extends strin... | @@ -7,7 +7,7 @@ export function asDrizzleTable<
TableName extends string = string,
TColumns extends ColumnsConfig = ColumnsConfig,
>(name: TableName, tableConfig: TableConfig<TColumns>) {
- return internal_asDrizzleTable(name, tableSchema.parse(tableConfig)) as Table<
+ return internal_asDrizzleTable(name, tableSc... | packages/db/src/utils.ts | 0 | TypeScript | 1 | none | 16 | 15 | 15 | true | Upgraded drizzle-orm to v.0.42.0 | 13,815 | withastro/astro | 47,179 | TypeScript | jonaspm | |
const meta = $('meta[http-equiv="Content-Security-Policy"]');
assert.ok(meta.attr('content').toString().includes('sha384-'));
});
it('should render hashes provided by the user', async () => {
fixture = await loadFixture({
root: './fixtures/csp/',
adapter: testAdapter({
setManifest(_manifest) {
... | No issues found. |
const meta = $('meta[http-equiv="Content-Security-Policy"]');
assert.ok(meta.attr('content').toString().includes('sha384-'));
});
it('should render hashes provided by the user', async () => {
fixture = await loadFixture({
root: './fixtures/csp/',
adapter: testAdapter({
setManifest(_manifest) {
... | @@ -159,12 +159,7 @@ describe('CSP', () => {
}),
experimental: {
csp: {
- directives: [
- {
- type: 'img-src',
- value: "'self' 'https://example.com'",
- },
- ],
+ directives: ["img-src 'self' 'https://example.com'"],
},
},
});
@@ -221,4 +216,58 @@ describe('CS... | packages/astro/test/csp.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(csp): runtime APIs | 13,824 | withastro/astro | 47,179 | TypeScript | ematipico | |
style: 'normal',
subset: undefined,
type: 'woff2',
url: 'foo',
weight: undefined,
},
{
style: 'italic',
subset: 'latin',
type: 'otf',
url: 'bar',
weight: undefined,
},
],
[
{
style: 'normal',
},
],
... | No issues found. | style: 'normal',
subset: undefined,
type: 'woff2',
url: 'foo',
weight: undefined,
},
{
style: 'italic',
subset: 'latin',
type: 'otf',
url: 'bar',
weight: undefined,
},
],
[
{
style: 'normal',
},
],
... | @@ -0,0 +1,161 @@
+// @ts-check
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { filterPreloads } from '../../../../dist/assets/fonts/runtime.js';
+
+describe('fonts runtime', () => {
+ describe('filterPreloads()', () => {
+ it('returns null if it should not preload', () =... | packages/astro/test/units/assets/fonts/runtime.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): granular preload | 13,826 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
var __ASTRO_SESSION_BINDING_NAME: string;
// Just used to pass the KV binding to unstorage.
// eslint-disable-next-line no-var
var __env__: Partial<Env>;
}
export async function handle(
manifest: SSRManifest,
app: App,
request: Parameters<ExportedHandlerFetchHandler>[0],
env: Env,
context: ExecutionContext,
... | No issues found. | var __ASTRO_SESSION_BINDING_NAME: string;
// Just used to pass the KV binding to unstorage.
// eslint-disable-next-line no-var
var __env__: Partial<Env>;
}
export async function handle(
manifest: SSRManifest,
app: App,
request: Parameters<ExportedHandlerFetchHandler>[0],
env: Env,
context: ExecutionContext,
... | @@ -0,0 +1,114 @@
+// @ts-expect-error - It is safe to expect the error here.
+import { env as globalEnv } from 'cloudflare:workers';
+import type { App } from 'astro/app';
+import type { SSRManifest } from 'astro';
+import type {
+ CacheStorage as CloudflareCacheStorage,
+ ExecutionContext,
+ ExportedHandlerFetchHandl... | packages/integrations/cloudflare/src/utils/handler.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(cloudflare): add support for user defined entryfile | 13,837 | withastro/astro | 47,179 | TypeScript | alexanderniebuhr | |
adapterName,
logger,
'i18nDomains',
() => {
return settings.config?.output === 'server' && !settings.config?.site;
},
);
}
validationResult.envGetSecret = validateSupportKind(
envGetSecret,
adapterName,
logger,
'astro:env getSecret',
() => Object.keys(settings.config?.env?.schema ?? {}... | No issues found. | adapterName,
logger,
'i18nDomains',
() => {
return settings.config?.output === 'server' && !settings.config?.site;
},
);
}
validationResult.envGetSecret = validateSupportKind(
envGetSecret,
adapterName,
logger,
'astro:env getSecret',
() => Object.keys(settings.config?.env?.schema ?? {}... | @@ -108,6 +108,10 @@ function getSupportMessage(supportKind: AdapterSupport): string | undefined {
return typeof supportKind === 'object' ? supportKind.message : undefined;
}
+function getSupportMessageSuppression(supportKind: AdapterSupport): 'all' | 'default' | undefined {
+ return typeof supportKind === 'object... | packages/astro/src/integrations/features-validation.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add option to suppress adapter feature support log | 13,842 | withastro/astro | 47,179 | TypeScript | yanthomasdev | |
schema: z.object({
breed: z.string(),
id: z.string(),
size: z.string(),
origin: z.string(),
lifespan: z.string(),
temperament: z.array(z.string()),
}),
});
const fish = defineCollection({
loader: file('src/data/fish.yaml'),
schema: z.object({
name: z.string(),
breed: z.string(),
age: z.number(),
... | No issues found. | schema: z.object({
breed: z.string(),
id: z.string(),
size: z.string(),
origin: z.string(),
lifespan: z.string(),
temperament: z.array(z.string()),
}),
});
const fish = defineCollection({
loader: file('src/data/fish.yaml'),
schema: z.object({
name: z.string(),
breed: z.string(),
age: z.number(),
... | @@ -173,10 +173,18 @@ const images = defineCollection({
}),
});
+const markdownContent = `
+# heading 1
+hello
+## heading 2
+
+
+`
+
const increment = defineCollection({
loader: {
name: 'increment-loader',
- load: async ({ store, refreshContext... | packages/astro/test/fixtures/content-layer/src/content.config.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: adds support for rendering markdown in loaders | 13,850 | withastro/astro | 47,179 | TypeScript | ascorbic | |
* service: passthroughImageService(),
* },
* });
* ```
*/
export const MissingSharp = {
name: 'MissingSharp',
title: 'Could not find Sharp.',
message:
'Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service.',
hint: "See Sharp's installation in... | No issues found. | * service: passthroughImageService(),
* },
* });
* ```
*/
export const MissingSharp = {
name: 'MissingSharp',
title: 'Could not find Sharp.',
message:
'Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service.',
hint: "See Sharp's installation in... | @@ -1700,7 +1700,7 @@ export const ContentEntryDataError = {
* The loader for a live content collection returned an invalid cache hint.
* Make sure that `cacheHint` is an object with the correct properties, or is undefined.
* @see
- * - [Experimental live content](https://astro.build/en/reference/experimental-fla... | packages/astro/src/core/errors/errors-data.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | chore: rename feature to live content collections | 13,861 | withastro/astro | 47,179 | TypeScript | ascorbic | |
await fixture.build();
assert.ok('Should build');
});
});
describe('Middleware API in PROD mode, SSR', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let middlewarePath;
/** @type {import('../src/core/app/index').App} */
let app;
before(async () => {
fixture = await loadFixture({
r... | No issues found. | await fixture.build();
assert.ok('Should build');
});
});
describe('Middleware API in PROD mode, SSR', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let middlewarePath;
/** @type {import('../src/core/app/index').App} */
let app;
before(async () => {
fixture = await loadFixture({
r... | @@ -388,3 +388,29 @@ describe('Middleware with tailwind', () => {
assert.equal(bundledCSS.includes('--tw'), true);
});
});
+
+describe('Middleware should support clone request', () => {
+ /** @type {import('./test-utils').Fixture} */
+ let fixture;
+ let devServer;
+
+ before(async () => {
+ fixture = await load... | packages/astro/test/middleware.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix: request should be properly cloned first then copy to modified in middleware | 13,877 | withastro/astro | 47,179 | TypeScript | yuhang-dong | |
assert.equal($svg.children()[0].name, 'svg');
$svg = $svg.children('svg');
assert.equal($svg.length, 1);
assert.equal(!!$svg.attr('xmlns'), false);
assert.equal(!!$svg.attr('xmlns:xlink'), false);
assert.equal(!!$svg.attr('version'), false);
});
it('should have no empty attributes'... | No issues found. | assert.equal($svg.children()[0].name, 'svg');
$svg = $svg.children('svg');
assert.equal($svg.length, 1);
assert.equal(!!$svg.attr('xmlns'), false);
assert.equal(!!$svg.attr('xmlns:xlink'), false);
assert.equal(!!$svg.attr('version'), false);
});
it('should have no empty attributes'... | @@ -150,4 +150,50 @@ describe('astro:assets - SVG Components', () => {
});
});
});
+
+ describe('SVGO optimization', () => {
+ /** @type {import('./test-utils').Fixture} */
+ let optimizedFixture;
+ /** @type {import('./test-utils').DevServer} */
+ let optimizedDevServer;
+
+ before(async () => {
+ opti... | packages/astro/test/core-image-svg.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: add SVGO optimization support for SVG assets | 13,880 | withastro/astro | 47,179 | TypeScript | azat-io | |
for (const key in overrides) {
const value = overrides[key];
if (value == null) {
continue;
}
const existing = merged[key];
if (existing == null) {
merged[key] = value;
continue;
}
// fields that require special handling:
if (key === 'vite' && rootPath === '') {
merged[key] = mergeViteCo... | No issues found. | for (const key in overrides) {
const value = overrides[key];
if (value == null) {
continue;
}
const existing = merged[key];
if (existing == null) {
merged[key] = value;
continue;
}
// fields that require special handling:
if (key === 'vite' && rootPath === '') {
merged[key] = mergeViteCo... | @@ -15,7 +15,7 @@ function mergeConfigRecursively(
continue;
}
- let existing = merged[key];
+ const existing = merged[key];
if (existing == null) {
merged[key] = value;
@@ -45,14 +45,6 @@ function mergeConfigRecursively(
continue;
}
- if (key === 'data' && rootPath === 'db') {
- // db.d... | packages/astro/src/core/config/merge.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | chore: clean db specific code | 13,893 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
{
inlineConfig: {
root: fixture.path,
logLevel: 'silent',
integrations: [],
},
},
async (container) => {
const { req, res, done, text } = createRequestAndResponse({
method: 'GET',
url: '/',
});
container.handle(req, res);
await done;
const html = await text... | No issues found. | {
inlineConfig: {
root: fixture.path,
logLevel: 'silent',
integrations: [],
},
},
async (container) => {
const { req, res, done, text } = createRequestAndResponse({
method: 'GET',
url: '/',
});
container.handle(req, res);
await done;
const html = await text... | @@ -147,4 +147,56 @@ describe('core/render components', () => {
},
);
});
+
+ it('should render custom element attributes as strings instead of boolean attributes', async () => {
+ const fixture = await createFixture({
+ '/src/pages/index.astro': `
+ ---
+ const selectedColor = "blue";
+ const auto... | packages/astro/test/units/render/components.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | added support to ignore custom elements which have htmlBooleanAt… | 13,909 | withastro/astro | 47,179 | TypeScript | isVivek99 | |
originalFormat = result.format;
delete resolvedOptions.inferSize; // Delete so it doesn't end up in the attributes
}
const originalFilePath = isESMImportedImage(resolvedOptions.src)
? resolvedOptions.src.fsPath
: undefined; // Only set for ESM imports, where we do have a file path
// Clone the `src` object... | No issues found. | originalFormat = result.format;
delete resolvedOptions.inferSize; // Delete so it doesn't end up in the attributes
}
const originalFilePath = isESMImportedImage(resolvedOptions.src)
? resolvedOptions.src.fsPath
: undefined; // Only set for ESM imports, where we do have a file path
// Clone the `src` object... | @@ -39,13 +39,9 @@ export async function getConfiguredImageService(): Promise<ImageService> {
return globalThis.astroAsset.imageService;
}
-type ImageConfig = AstroConfig['image'] & {
- experimentalResponsiveImages: boolean;
-};
-
export async function getImage(
options: UnresolvedImageTransform,
- imageConfig:... | packages/astro/src/assets/internal.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: unflag responsive images | 13,917 | withastro/astro | 47,179 | TypeScript | ascorbic | |
},
load(id) {
if (id === "@my-ssr") {
return {
code: `
import { App } from 'astro/app';
import fs from 'fs';
${
env
? `
await import('astro/env/setup')
.then(mod => mod.setGetEnv((key) => {
... | No issues found. | },
load(id) {
if (id === "@my-ssr") {
return {
code: `
import { App } from 'astro/app';
import fs from 'fs';
${
env
? `
await import('astro/env/setup')
.then(mod => mod.setGetEnv((key) => {
... | @@ -1,4 +1,4 @@
-import { viteID } from '../dist/core/util.js';
+import { viteID } from "../dist/core/util.js";
/**
* @typedef {import('../src/types/public/integrations.js').AstroAdapter} AstroAdapter
@@ -30,23 +30,25 @@ export default function ({
env,
} = {}) {
return {
- name: 'my-ssr-adapter',
+ name: "m... | packages/astro/test/test-adapter.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | refactor(csp): change CSP behaviour | 13,923 | withastro/astro | 47,179 | TypeScript | ematipico | |
assert.ok(meta.attr('content').toString().includes('sha384-hash2'));
assert.ok(meta.attr('content').toString().includes('sha384-hash4'));
assert.ok(meta.attr('content').toString().includes('sha512-hash1'));
assert.ok(meta.attr('content').toString().includes('sha512-hash3'));
});
it('should contain the additi... | No issues found. | assert.ok(meta.attr('content').toString().includes('sha384-hash2'));
assert.ok(meta.attr('content').toString().includes('sha384-hash4'));
assert.ok(meta.attr('content').toString().includes('sha512-hash1'));
assert.ok(meta.attr('content').toString().includes('sha512-hash3'));
});
it('should contain the additi... | @@ -52,7 +52,8 @@ describe('CSP', () => {
if (manifest) {
const request = new Request('http://example.com/index.html');
const response = await app.render(request);
- const $ = cheerio.load(await response.text());
+ const html = await response.text();
+ const $ = cheerio.load(html);
const meta = $... | packages/astro/test/csp.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(csp): add static header adapter function | 13,926 | withastro/astro | 47,179 | TypeScript | ematipico | |
throw new AstroError({
...AstroErrorData.DataCollectionEntryParseError,
message: AstroErrorData.DataCollectionEntryParseError.message(
pathRelToContentDir,
'data is not an object.',
),
location: { file: fileUrl.pathname },
});
}
return { data };
},
... | No issues found. | throw new AstroError({
...AstroErrorData.DataCollectionEntryParseError,
message: AstroErrorData.DataCollectionEntryParseError.message(
pathRelToContentDir,
'data is not an object.',
),
location: { file: fileUrl.pathname },
});
}
return { data };
},
... | @@ -1,6 +1,7 @@
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import yaml from 'js-yaml';
+import toml from 'smol-toml';
import { getContentPaths } from '../../content/index.js';
import createPreferences from '../../preferences/index.js';
import type { AstroSettings } from... | packages/astro/src/core/config/settings.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: Add TOML support to the built-in content loaders | 13,941 | withastro/astro | 47,179 | TypeScript | aditsachde | |
});
} else {
redirects.add({
dynamic: false,
input: `${base}${route.pathname}`,
target: dynamicTarget,
status: 200,
weight: 2,
});
if (route.pattern === '/404') {
redirects.add({
dynamic: true,
input: '/*',
target: dynamicTarget,
status: 404,
... | No issues found. | });
} else {
redirects.add({
dynamic: false,
input: `${base}${route.pathname}`,
target: dynamicTarget,
status: 200,
weight: 2,
});
if (route.pattern === '/404') {
redirects.add({
dynamic: true,
input: '/*',
target: dynamicTarget,
status: 404,
... | @@ -5,7 +5,7 @@ import type {
IntegrationResolvedRoute,
ValidRedirectStatus,
} from 'astro';
-import { Redirects } from './redirects.js';
+import { type HostRouteDefinition, HostRoutes } from './host-route.js';
const pathJoin = posix.join;
@@ -36,17 +36,17 @@ export function createRedirectsFromAstroRoutes({
... | packages/underscore-redirects/src/astro.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(netlify): add experimental support for static headers | 13,952 | withastro/astro | 47,179 | TypeScript | ematipico | |
astroVirtualManifestPlugin({ manifest }),
configAliasVitePlugin({ settings }),
astroLoadFallbackPlugin({ fs, root: settings.config.root }),
astroVitePlugin({ settings, logger }),
astroScriptsPlugin({ settings }),
// The server plugin is for dev only and having it run during the build causes
// the ... | No issues found. | astroVirtualManifestPlugin({ manifest }),
configAliasVitePlugin({ settings }),
astroLoadFallbackPlugin({ fs, root: settings.config.root }),
astroVitePlugin({ settings, logger }),
astroScriptsPlugin({ settings }),
// The server plugin is for dev only and having it run during the build causes
// the ... | @@ -125,7 +125,14 @@ export async function createVite(
});
const srcDirPattern = convertPathToPattern(fileURLToPath(settings.config.srcDir));
- const envLoader = createEnvLoader(mode, settings.config);
+ // TODO: use a single non coerced env loader in Astro 7
+ // Coercion is managed by astro:env directly
+ const... | packages/astro/src/core/create-vite.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | don't coerce environment variable values when populating import.meta.env | 13,971 | withastro/astro | 47,179 | TypeScript | adamhl8 | |
],
cacheHint: {
tags: ['page'],
maxAge: 60,
lastModified: '2025-01-02T00:00:00.000Z',
},
});
});
it('can load live data with dynamic filtering', async () => {
const res = await fixture.fetch('/api/?addToAge=5');
assert.equal(res.status, 200);
const data = await res.json();
... | No issues found. | ],
cacheHint: {
tags: ['page'],
maxAge: 60,
lastModified: '2025-01-02T00:00:00.000Z',
},
});
});
it('can load live data with dynamic filtering', async () => {
const res = await fixture.fetch('/api/?addToAge=5');
assert.equal(res.status, 200);
const data = await res.json();
... | @@ -47,11 +47,13 @@ describe('Live content collections', () => {
cacheHint: {
tags: [`page:123`],
maxAge: 60,
+ lastModified: '2025-01-01T00:00:00.000Z',
},
},
cacheHint: {
tags: [`page:123`],
maxAge: 60,
+ lastModified: '2025-01-01T00:00:00.000Z',
},
})... | packages/astro/test/live-loaders.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: add lastModified field to live collection cache hints | 13,999 | withastro/astro | 47,179 | TypeScript | ascorbic | |
import { STATIC_HEADERS_FILE } from './shared.js';
import startServer, { createStandaloneHandler } from './standalone.js';
import type { Options } from './types.js';
setGetEnv((key) => process.env[key]);
export function createExports(manifest: SSRManifest, options: Options) {
const app = new NodeApp(manifest, !optio... | No issues found. | import { STATIC_HEADERS_FILE } from './shared.js';
import startServer, { createStandaloneHandler } from './standalone.js';
import type { Options } from './types.js';
setGetEnv((key) => process.env[key]);
export function createExports(manifest: SSRManifest, options: Options) {
const app = new NodeApp(manifest, !optio... | @@ -13,7 +13,7 @@ import type { Options } from './types.js';
setGetEnv((key) => process.env[key]);
export function createExports(manifest: SSRManifest, options: Options) {
- const app = new NodeApp(manifest);
+ const app = new NodeApp(manifest, !options.experimentalDisableStreaming);
let headersMap: NodeAppHeader... | packages/integrations/node/src/server.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(node): experimentalDisableStreaming | 14,012 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
});
});
describe('i18n routing with fallback and trailing slash', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/i18n-routing-fallback/',
trailingSlash: 'always',
build: {
format: 'directory',
},... | No issues found. | });
});
describe('i18n routing with fallback and trailing slash', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/i18n-routing-fallback/',
trailingSlash: 'always',
build: {
format: 'directory',
},... | @@ -2261,6 +2261,40 @@ describe('Fallback rewrite SSR', () => {
});
});
+describe('Fallback rewrite hybrid', () => {
+ /** @type {import('./test-utils').Fixture} */
+ let fixture;
+ let app;
+
+ before(async () => {
+ fixture = await loadFixture({
+ root: './fixtures/i18n-routing-fallback-rewrite-hybrid/',
+ ... | packages/astro/test/i18n-routing.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix i18n fallback rewrites failing in server mode | 14,017 | withastro/astro | 47,179 | TypeScript | dmgawel | |
}
export function getEntryType(
entryPath: string,
paths: Pick<ContentPaths, 'config' | 'contentDir' | 'root'>,
contentFileExts: string[],
dataFileExts: string[],
): 'content' | 'data' | 'config' | 'ignored' {
const { ext } = path.parse(entryPath);
const fileUrl = pathToFileURL(entryPath);
const dotAstroDir = ... | No issues found. | }
export function getEntryType(
entryPath: string,
paths: Pick<ContentPaths, 'config' | 'contentDir' | 'root'>,
contentFileExts: string[],
dataFileExts: string[],
): 'content' | 'data' | 'config' | 'ignored' {
const { ext } = path.parse(entryPath);
const fileUrl = pathToFileURL(entryPath);
const dotAstroDir = ... | @@ -106,7 +106,7 @@ const collectionConfigParser = z.union([
_legacy: z.boolean().optional(),
}),
z.object({
- type: z.literal(LIVE_CONTENT_TYPE),
+ type: z.literal(LIVE_CONTENT_TYPE).optional().default(LIVE_CONTENT_TYPE),
schema: z.any().optional(),
loader: z.function(),
}), | packages/astro/src/content/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Make "type" optional when defining live collections | 14,019 | withastro/astro | 47,179 | TypeScript | ascorbic | |
let svgFiles = [];
try {
const files = await readdir(assetsDir);
svgFiles = files.filter(file => file.endsWith('.svg'));
} catch (_e) {
// Assets directory might not exist if no SVGs are emitted
}
// Should only have 2 unique SVG files (duplicate1/duplicate2 share content, unique is sepa... | No issues found. |
let svgFiles = [];
try {
const files = await readdir(assetsDir);
svgFiles = files.filter(file => file.endsWith('.svg'));
} catch (_e) {
// Assets directory might not exist if no SVGs are emitted
}
// Should only have 2 unique SVG files (duplicate1/duplicate2 share content, unique is sepa... | @@ -0,0 +1,95 @@
+import assert from 'node:assert/strict';
+import { readdir, } from 'node:fs/promises';
+import { after, before, describe, it } from 'node:test';
+import * as cheerio from 'cheerio';
+import { loadFixture } from './test-utils.js';
+
+describe('SVG Deduplication', () => {
+ /** @type {import('./test-uti... | packages/astro/test/svg-deduplication.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(astro): fix svg content-based deduplication | 14,031 | withastro/astro | 47,179 | TypeScript | jp-knj | |
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';
describe('Aliases with tsconfig.json without baseUrl', () => {
let fixture;
before(async () => {
fixture = await loadFixture({
roo... | No issues found. | import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';
describe('Aliases with tsconfig.json without baseUrl', () => {
let fixture;
before(async () => {
fixture = await loadFixture({
roo... | @@ -0,0 +1,48 @@
+import assert from 'node:assert/strict';
+import { after, before, describe, it } from 'node:test';
+import * as cheerio from 'cheerio';
+import { loadFixture } from './test-utils.js';
+
+describe('Aliases with tsconfig.json without baseUrl', () => {
+ let fixture;
+
+ before(async () => {
+ fixture =... | packages/astro/test/alias-tsconfig-no-baseurl.test.js | 0 | JavaScript | 1 | none | 16 | 48 | 48 | true | fix(astro): drop baseUrl requirement for ts-paths | 14,064 | withastro/astro | 47,179 | TypeScript | jp-knj | |
current: string;
/** url of the previous page (if there is one) */
prev: string | undefined;
/** url of the next page (if there is one) */
next: string | undefined;
/** url of the first page (if the current page is not the first page) */
first: string | undefined;
/** url of the last page (if the curren... | No issues found. | current: string;
/** url of the previous page (if there is one) */
prev: string | undefined;
/** url of the next page (if there is one) */
next: string | undefined;
/** url of the first page (if the current page is not the first page) */
first: string | undefined;
/** url of the last page (if the curren... | @@ -1,3 +1,4 @@
+import type { BundledLanguage, LanguageRegistration, SpecialLanguage } from 'shiki';
import type { OmitIndexSignature, Simplify } from '../../type-utils.js';
import type { APIContext } from './context.js';
@@ -180,3 +181,5 @@ export type InferGetStaticPropsType<T> = T extends (
export type Param... | packages/astro/src/types/public/common.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: export lang types for use in custom component | 14,071 | withastro/astro | 47,179 | TypeScript | Grisoly | |
adapter: netlifyAdapter(),
});
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
afterEach(async () => {
fixture.resetAllFiles();
});
it('loads Astro routes', async () => {
const rootResponse = await fixture.fetch('/');
const $root = che... | No issues found. | adapter: netlifyAdapter(),
});
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
afterEach(async () => {
fixture.resetAllFiles();
});
it('loads Astro routes', async () => {
const rootResponse = await fixture.fetch('/');
const $root = che... | @@ -36,7 +36,9 @@ describe('Netlify primitives', () => {
const imgResponse = await fixture.fetch('/astronaut');
const $img = cheerio.load(await imgResponse.text());
- assert($img('img').attr('src').startsWith('/_image?href='));
+ assert.equal($img('h1').text(), 'Hello, Astronaut');
+
+ // assert($img('i... | packages/integrations/netlify/test/development/primitives.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix: regressions in Netlify adapter | 14,078 | withastro/astro | 47,179 | TypeScript | ascorbic | |
describe('props', () => {
describe('strip', () => {
let $;
let html;
before(async () => {
let res = await fixture.fetch('/strip');
html = await res.text();
$ = cheerio.load(html, { xml: true });
});
it('removes unnecessary attributes', () => {
let $svg = $('#base svg');
... | No issues found. |
describe('props', () => {
describe('strip', () => {
let $;
let html;
before(async () => {
let res = await fixture.fetch('/strip');
html = await res.text();
$ = cheerio.load(html, { xml: true });
});
it('removes unnecessary attributes', () => {
let $svg = $('#base svg');
... | @@ -138,5 +138,16 @@ describe('astro:assets - SVG Components', () => {
assert.equal($svg.attr('aria-description'), 'Some description');
});
});
+
+ describe('metadata', () => {
+ it('returns a serializable metadata object', async () => {
+ let res = await fixture.fetch('/serialize.json');
+ let jso... | packages/astro/test/core-image-svg.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix: make SVG ImageMetadata serializable | 14,112 | withastro/astro | 47,179 | TypeScript | ascorbic | |
let fixture;
let devServer;
before(async () => {
fixture = await loadFixture({
root: './fixtures/astro-dev-headers/',
experimental: {
chromeDevtoolsWorkspace: true,
},
});
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
it('se... | No issues found. | let fixture;
let devServer;
before(async () => {
fixture = await loadFixture({
root: './fixtures/astro-dev-headers/',
experimental: {
chromeDevtoolsWorkspace: true,
},
});
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
it('se... | @@ -0,0 +1,61 @@
+import assert from 'node:assert/strict';
+import { after, before, describe, it } from 'node:test';
+import { loadFixture } from './test-utils.js';
+
+describe('Chrome DevTools workspace', () => {
+ describe('with experimental flag enabled', () => {
+ let fixture;
+ let devServer;
+
+ before(async (... | packages/astro/test/chrome-devtools-workspace.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: add automatic chrome workspace handling | 14,122 | withastro/astro | 47,179 | TypeScript | ascorbic | |
assert.equal(true, true);
}
});
});
describe('SSR reroute', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let app;
before(async () => {
fixture = await loadFixture({
root: './fixtures/reroute/',
output: 'server',
adapter: testAdapter(),
});
await fixture.build();
app = ... | No issues found. | assert.equal(true, true);
}
});
});
describe('SSR reroute', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let app;
before(async () => {
fixture = await loadFixture({
root: './fixtures/reroute/',
output: 'server',
adapter: testAdapter(),
});
await fixture.build();
app = ... | @@ -730,7 +730,7 @@ describe('Runtime error in SSR, custom 500', () => {
});
});
-describe('Issue 13633', async () => {
+describe('Rewrite issue 13633', async () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let devServer;
@@ -754,3 +754,33 @@ describe('Issue 13633', async () => {
assert... | packages/astro/test/rewrite.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(routing): update `routePattern` when using sequence | 14,132 | withastro/astro | 47,179 | TypeScript | ematipico | |
// Look in all of the .js files to see if the public env is inlined.
// Testing this way prevents hardcoding expected js files.
// If we find it in any of them that's good enough to know its working.
await Promise.all(
dirs.map(async (path) => {
if (path.endsWith('.js')) {
let js = await fixt... | No issues found. | // Look in all of the .js files to see if the public env is inlined.
// Testing this way prevents hardcoding expected js files.
// If we find it in any of them that's good enough to know its working.
await Promise.all(
dirs.map(async (path) => {
if (path.endsWith('.js')) {
let js = await fixt... | @@ -1,23 +1,22 @@
+// @ts-check
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import * as cheerio from 'cheerio';
+import testAdapter from './test-adapter.js';
import { loadFixture } from './test-utils.js';
-describe('Environment Variables', () => {
- /** @type ... | packages/astro/test/astro-envs.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: experimental static import.meta.env | 14,173 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
res.end('Not found');
}
});
await new Promise((resolve) => {
errorPageServer.listen(3030, resolve);
});
fixture = await loadFixture({
root: './fixtures/prerender-error-page/',
adapter: nodejs({ mode: 'standalone', experimentalErrorPageHost: 'http://localhost:3030' }),
});
await fixture.bui... | No issues found. | res.end('Not found');
}
});
await new Promise((resolve) => {
errorPageServer.listen(3030, resolve);
});
fixture = await loadFixture({
root: './fixtures/prerender-error-page/',
adapter: nodejs({ mode: 'standalone', experimentalErrorPageHost: 'http://localhost:3030' }),
});
await fixture.bui... | @@ -0,0 +1,107 @@
+import * as assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { after, before, describe, it } from 'node:test';
+import nodejs from '../dist/index.js';
+import { loadFixture } from './test-utils.js';
+
+describe('Prerendered error page host', () => {
+ /** @type {im... | packages/integrations/node/test/error-page-host.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: add support for specifying a prerendered error page host | 14,188 | withastro/astro | 47,179 | TypeScript | ascorbic | |
};
}) => void;
};
export type ModuleLoaderEventEmitter = TypedEventEmitter<LoaderEvents>;
export interface ModuleLoader {
import: (src: string) => Promise<Record<string, any>>;
resolveId: (specifier: string, parentId: string | undefined) => Promise<string | undefined>;
getModuleById: (id: string) => Environment... | No issues found. | };
}) => void;
};
export type ModuleLoaderEventEmitter = TypedEventEmitter<LoaderEvents>;
export interface ModuleLoader {
import: (src: string) => Promise<Record<string, any>>;
resolveId: (specifier: string, parentId: string | undefined) => Promise<string | undefined>;
getModuleById: (id: string) => Environment... | @@ -1,5 +1,6 @@
import { EventEmitter } from 'node:events';
import type * as fs from 'node:fs';
+import type { EnvironmentModuleNode } from 'vite';
import type { TypedEventEmitter } from '../../types/typed-emitter.js';
// This is a generic interface for a module loader. In the astro cli this is
@@ -23,12 +24,18 @... | packages/astro/src/core/module-loader/runner.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor: use ssr environment to load modules | 14,191 | withastro/astro | 47,179 | TypeScript | ematipico | |
import { createClient as createLibsqlClient } from '@libsql/client';
import { drizzle as drizzleLibsql } from 'drizzle-orm/libsql';
import { parseLibSQLConfig } from './utils.js';
type RemoteDbClientOptions = {
token: string;
url: string;
};
export function createClient(opts: RemoteDbClientOptions) {
const { token... | No issues found. | import { createClient as createLibsqlClient } from '@libsql/client';
import { drizzle as drizzleLibsql } from 'drizzle-orm/libsql';
import { parseLibSQLConfig } from './utils.js';
type RemoteDbClientOptions = {
token: string;
url: string;
};
export function createClient(opts: RemoteDbClientOptions) {
const { token... | @@ -0,0 +1,43 @@
+import { createClient as createLibsqlClient } from '@libsql/client';
+import { drizzle as drizzleLibsql } from 'drizzle-orm/libsql';
+import { parseLibSQLConfig } from './utils.js';
+
+type RemoteDbClientOptions = {
+ token: string;
+ url: string;
+};
+
+export function createClient(opts: RemoteDbClie... | packages/db/src/core/db-client/libsql-node.ts | 0 | TypeScript | 1 | none | 16 | 44 | 44 | true | feat(db): add support for non-node libsql client | 14,204 | withastro/astro | 47,179 | TypeScript | Adammatthiesen | |
}).catch((err) => {
logger.error('build', `Failed to call getStaticPaths for ${route.component}`);
throw err;
});
const label = staticPaths.length === 1 ? 'page' : 'pages';
logger.debug(
'build',
`├── ${bold(green('√'))} ${route.component} → ${magenta(`[${staticPaths.length} ${label}]`)}`,
);
... | No issues found. | }).catch((err) => {
logger.error('build', `Failed to call getStaticPaths for ${route.component}`);
throw err;
});
const label = staticPaths.length === 1 ? 'page' : 'pages';
logger.debug(
'build',
`├── ${bold(green('√'))} ${route.component} → ${magenta(`[${staticPaths.length} ${label}]`)}`,
);
... | @@ -386,8 +386,9 @@ async function getPathsForRoute(
}
})
.filter((staticPath) => {
+ const normalized = removeTrailingForwardSlash(staticPath);
// The path hasn't been built yet, include it
- if (!builtPaths.has(removeTrailingForwardSlash(staticPath))) {
+ if (!builtPaths.has(normalized)) {
... | packages/astro/src/core/build/generate.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Warn or fail on prerendered route collision | 14,206 | withastro/astro | 47,179 | TypeScript | Fryuni | |
let fixture;
let devServer;
before(async () => {
fixture = await loadFixture({
root: './fixtures/astro-dev-headers/',
experimental: {
chromeDevtoolsWorkspace: true,
},
});
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
it('se... | No issues found. | let fixture;
let devServer;
before(async () => {
fixture = await loadFixture({
root: './fixtures/astro-dev-headers/',
experimental: {
chromeDevtoolsWorkspace: true,
},
});
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.stop();
});
it('se... | @@ -27,11 +27,11 @@ describe('Chrome DevTools workspace', () => {
assert.equal(result.headers.get('content-type'), 'application/json');
const data = await result.json();
- assert.equal(data.version, '1.0');
- assert.equal(typeof data.projectId, 'string');
- assert.equal(data.projectId.length, 36); // UU... | packages/astro/test/chrome-devtools-workspace.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix automatic Chrome DevTools workspace feature | 14,225 | withastro/astro | 47,179 | TypeScript | delucis | |
fixture = await loadFixture({
root: './fixtures/i18n-routing/',
});
await fixture.build();
});
it('renders the page', async () => {
const html = await fixture.readFile('/endurance/index.html');
assert.equal(html.includes('Endurance'), true);
});
});
describe('current locale', () => {
desc... | No issues found. | fixture = await loadFixture({
root: './fixtures/i18n-routing/',
});
await fixture.build();
});
it('renders the page', async () => {
const html = await fixture.readFile('/endurance/index.html');
assert.equal(html.includes('Endurance'), true);
});
});
describe('current locale', () => {
desc... | @@ -1268,6 +1268,93 @@ describe('[SSG] i18n routing', () => {
});
});
+ describe('when `build.format` is `file`, locales array contains objects, and locale indexes use getStaticPaths', () => {
+ /** @type {import('./test-utils').Fixture} */
+ let fixture;
+
+ before(async () => {
+ fixture = await lo... | packages/astro/test/i18n-routing.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Properly compute `currentLocale` when `path` segment contains `.html` | 14,229 | withastro/astro | 47,179 | TypeScript | jonmichaeldarby | |
import * as assert from 'node:assert/strict';
import { existsSync } from 'node:fs';
import { describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import { astroCli } from './_test-utils.js';
const root = new URL('./fixtures/custom-entryfile/', import.meta.url);
describe('Custom entry file', () =... | No issues found. | import * as assert from 'node:assert/strict';
import { existsSync } from 'node:fs';
import { describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import { astroCli } from './_test-utils.js';
const root = new URL('./fixtures/custom-entryfile/', import.meta.url);
describe('Custom entry file', () =... | @@ -0,0 +1,16 @@
+import * as assert from 'node:assert/strict';
+import { existsSync } from 'node:fs';
+import { describe, it } from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { astroCli } from './_test-utils.js';
+
+const root = new URL('./fixtures/custom-entryfile/', import.meta.url);
+
+describe... | packages/integrations/cloudflare/test/custom-entryfile.test.js | 0 | JavaScript | 1 | none | 16 | 17 | 17 | true | Filter duplicate exports from Cloudflare adapter's `namedExports` | 14,234 | withastro/astro | 47,179 | TypeScript | yanthomasdev | |
test('data-astro-prefetch="viewport" should prefetch on viewport', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/'));
await expectUrlNotPrefetched('/prefetch-viewport', page);
// Scroll down to show the element
await Promise.all([
page.waitForEvent('request'), // wait prefetch request
... | No issues found. |
test('data-astro-prefetch="viewport" should prefetch on viewport', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/'));
await expectUrlNotPrefetched('/prefetch-viewport', page);
// Scroll down to show the element
await Promise.all([
page.waitForEvent('request'), // wait prefetch request
... | @@ -56,6 +56,24 @@ async function expectUrlNotPrefetched(url, page) {
expect(reqUrls).not.toContainEqual(url);
}
+/**
+ * @param {import('@playwright/test').Page} page
+ * @param {string} selector
+ */
+async function mouseDown(page, selector) {
+ const box = await page.locator(selector).boundingBox();
+ await pag... | packages/astro/e2e/prefetch.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(prefetch): Fix "tap" prefetch strategy when view transitions are enabled | 14,235 | withastro/astro | 47,179 | TypeScript | toxeeec | |
it('custom endpoint works', async () => {
const response = await customEndpointFixture.fetch('/');
const html = await response.text();
const $ = cheerio.load(html);
const src = $('#local img').attr('src');
let res = await customEndpointFixture.fetch(src);
assert.equal(res.status, 200);
... | No issues found. |
it('custom endpoint works', async () => {
const response = await customEndpointFixture.fetch('/');
const html = await response.text();
const $ = cheerio.load(html);
const src = $('#local img').attr('src');
let res = await customEndpointFixture.fetch(src);
assert.equal(res.status, 200);
... | @@ -839,6 +839,34 @@ describe('astro:image', () => {
});
});
+ it('returns 403 when loading a relative pattern iamge', async () => {
+ const fixtureWithBase = await loadFixture({
+ root: './fixtures/core-image-ssr/',
+ output: 'server',
+ adapter: testAdapter(),
+ });
+ // packages/astro/test/fixtures/c... | packages/astro/test/core-image.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(assets): fix remote path detection | 14,241 | withastro/astro | 47,179 | TypeScript | ematipico | |
});
},
},
},
],
});
rootPathContainer = await createContainer({
settings: rootPathSettings,
logger: defaultLogger,
});
});
after(async () => {
await container.close();
await baseContainer.close();
await rootPathContainer.close();
});
// Tests for trailingSlash: 'always'
... | No issues found. | });
},
},
},
],
});
rootPathContainer = await createContainer({
settings: rootPathSettings,
logger: defaultLogger,
});
});
after(async () => {
await container.close();
await baseContainer.close();
await rootPathContainer.close();
});
// Tests for trailingSlash: 'always'
... | @@ -10,14 +10,17 @@ import {
} from '../test-utils.js';
const fileSystem = {
- '/src/pages/api.ts': `export const GET = () => Response.json({ success: true })`,
- '/src/pages/dot.json.ts': `export const GET = () => Response.json({ success: true })`,
+ '/src/pages/api.ts': `export const GET = () => new Response(JSON... | packages/astro/test/units/routing/trailing-slash.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(astro): Astro.url.pathname respects trailingSlash: 'never' with base path | 14,260 | withastro/astro | 47,179 | TypeScript | jp-knj | |
readFile,
fetch,
});
await fontFetcher.fetch({ hash: 'abc', url: 'def', init: null });
await fontFetcher.fetch({ hash: 'foo', url: 'bar', init: null });
await fontFetcher.fetch({ hash: 'abc', url: 'def', init: null });
assert.deepStrictEqual([...store.keys()], ['abc', 'foo']);
assert.deepStr... | No issues found. | readFile,
fetch,
});
await fontFetcher.fetch({ hash: 'abc', url: 'def', init: null });
await fontFetcher.fetch({ hash: 'foo', url: 'bar', init: null });
await fontFetcher.fetch({ hash: 'abc', url: 'def', init: null });
assert.deepStrictEqual([...store.keys()], ['abc', 'foo']);
assert.deepStr... | @@ -13,11 +13,15 @@ import { createAstroErrorHandler } from '../../../../dist/assets/fonts/implement
import { createCachedFontFetcher } from '../../../../dist/assets/fonts/implementations/font-fetcher.js';
import { createCapsizeFontMetricsResolver } from '../../../../dist/assets/fonts/implementations/font-metrics-res... | packages/astro/test/units/assets/fonts/implementations.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): better dev hashes | 14,279 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
adapter: testAdapter({}),
});
await fixture.build();
app = await fixture.loadTestAdapterApp();
});
it('should render locals data', async () => {
const request = new Request('http://example.com/');
const response = await app.render(request);
const html = await response.text();
const $ = cheerio.load(... | No issues found. | adapter: testAdapter({}),
});
await fixture.build();
app = await fixture.loadTestAdapterApp();
});
it('should render locals data', async () => {
const request = new Request('http://example.com/');
const response = await app.render(request);
const html = await response.text();
const $ = cheerio.load(... | @@ -413,4 +413,35 @@ describe('Middleware should support clone request', () => {
const html = await res.text();
assert.equal(html.includes('Hello Sequence and Request Clone'), true);
});
+
+ it('should preserve cookies set in sequence', async () => {
+ const res = await fixture.fetch('/');
+ assert.ok(res.hea... | packages/astro/test/middleware.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix: don't lose cookies in middleware sequences | 14,280 | withastro/astro | 47,179 | TypeScript | ascorbic | |
const { preloadedComponent } = matchedRoute;
route = matchedRoute.route;
// Allows adapters to pass in locals in dev mode.
request = createRequest({
url,
headers: incomingRequest.headers,
method: incomingRequest.method,
body,
logger,
isPrerendered: route.prerender,
routePattern: route.component,
})... | No issues found. |
const { preloadedComponent } = matchedRoute;
route = matchedRoute.route;
// Allows adapters to pass in locals in dev mode.
request = createRequest({
url,
headers: incomingRequest.headers,
method: incomingRequest.method,
body,
logger,
isPrerendered: route.prerender,
routePattern: route.component,
})... | @@ -196,6 +196,7 @@ export async function handleRoute({
routeData: route,
clientAddress: incomingRequest.socket.remoteAddress,
actions,
+ shouldInjectCspMetaTags: false,
});
let response;
@@ -221,6 +222,7 @@ export async function handleRoute({
routeData: route,
clientAddress: incomingRequest.s... | packages/astro/src/vite-plugin-astro-server/route.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(csp): CSP headers in development server | 14,283 | withastro/astro | 47,179 | TypeScript | ematipico | |
});
it('generates valid image sizes when requested width is larger than source image', async () => {
const html = await fixture.readFile('../.vercel/output/static/index.html');
const $ = cheerio.load(html);
const img = $('#small-source img');
const widths = img
.attr('srcset')
.split(', ')
.map((ent... | No issues found. | });
it('generates valid image sizes when requested width is larger than source image', async () => {
const html = await fixture.readFile('../.vercel/output/static/index.html');
const $ = cheerio.load(html);
const img = $('#small-source img');
const widths = img
.attr('srcset')
.split(', ')
.map((ent... | @@ -28,6 +28,22 @@ describe('Image', () => {
assert.equal(img.attr('width'), '225');
});
+ it('generates valid image sizes when requested width is larger than source image', async () => {
+ const html = await fixture.readFile('../.vercel/output/static/index.html');
+ const $ = cheerio.load(html);
+ const img ... | packages/integrations/vercel/test/image.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(vercel): ensure srcset widths are always from configured list | 14,289 | withastro/astro | 47,179 | TypeScript | ascorbic | |
if (id === SERIALIZED_MANIFEST_ID) {
return SERIALIZED_MANIFEST_RESOLVED_ID;
}
},
async load(id) {
if (id === SERIALIZED_MANIFEST_RESOLVED_ID) {
const code = `
import { deserializeManifest as _deserializeManifest } from 'astro/app';
export const manifest = _deserializeManifest((${JSON.st... | No issues found. | if (id === SERIALIZED_MANIFEST_ID) {
return SERIALIZED_MANIFEST_RESOLVED_ID;
}
},
async load(id) {
if (id === SERIALIZED_MANIFEST_RESOLVED_ID) {
const code = `
import { deserializeManifest as _deserializeManifest } from 'astro/app';
export const manifest = _deserializeManifest((${JSON.st... | @@ -1,6 +1,19 @@
import type { Plugin } from 'vite';
+import { toFallbackType } from '../core/app/common.js';
+import { toRoutingStrategy } from '../core/app/index.js';
+import type { SerializedSSRManifest, SSRManifestCSP, SSRManifestI18n } from '../core/app/types.js';
+import {
+ getAlgorithm,
+ getDirectives,
+ getS... | packages/astro/src/manifest/serialized.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(dev): use entry point to bootstrap the app | 14,333 | withastro/astro | 47,179 | TypeScript | ematipico | |
serverEntry: 'index.js',
redirects: false,
},
session,
vite: {
plugins: [
command === 'build' ? undefined : cfVitePlugin({ viteEnvironment: { name: 'ssr' } }),
// https://developers.cloudflare.com/pages/functions/module-support/
// Allows imports of '.wasm', '.bin',... | No issues found. | serverEntry: 'index.js',
redirects: false,
},
session,
vite: {
plugins: [
command === 'build' ? undefined : cfVitePlugin({ viteEnvironment: { name: 'ssr' } }),
// https://developers.cloudflare.com/pages/functions/module-support/
// Allows imports of '.wasm', '.bin',... | @@ -101,6 +101,23 @@ export type Options = {
*/
sessionKVBindingName?: string;
+ /**
+ * When configured as `cloudflare-binding`, the Cloudflare Images binding will be used to transform images:
+ * - https://developers.cloudflare.com/images/transform-images/bindings/
+ *
+ * By default, this will use the "IM... | packages/integrations/cloudflare/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add support for Cloudflare images binding in environment API | 14,358 | withastro/astro | 47,179 | TypeScript | ascorbic | |
};
const pipeline = new DevPipeline(
logger,
manifest,
'production',
manifest.renderers,
resolve,
true,
streaming,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
);
return pipeline;
}
headElements(routeData: RouteData): Pic... | No issues found. | };
const pipeline = new DevPipeline(
logger,
manifest,
'production',
manifest.renderers,
resolve,
true,
streaming,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
);
return pipeline;
}
headElements(routeData: RouteData): Pic... | @@ -6,10 +6,7 @@ import type {
SSRResult,
} from '../../../types/public/index.js';
import { Pipeline, type TryRewriteResult } from '../../base-pipeline.js';
-import {
- createModuleScriptElement,
- createStylesheetElementSet,
-} from '../../render/ssr-element.js';
+import { createModuleScriptElement, createStyleshe... | packages/astro/src/core/app/dev/pipeline.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: add support for server islands in Environment API | 14,390 | withastro/astro | 47,179 | TypeScript | ascorbic | |
// ESBuild can give us a slightly better error message than the one in the error, so let's use it
if (text) {
try {
err[i].message = text;
} catch {}
}
if (location) {
err[i].loc = { file: location.file, line: location.line, column: location.column };
err[i].id = err[0].id || location?... | No issues found. | // ESBuild can give us a slightly better error message than the one in the error, so let's use it
if (text) {
try {
err[i].message = text;
} catch {}
}
if (location) {
err[i].loc = { file: location.file, line: location.line, column: location.column };
err[i].id = err[0].id || location?... | @@ -2,14 +2,11 @@ import * as fs from 'node:fs';
import { isAbsolute, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { stripVTControlCharacters } from 'node:util';
-import { escape } from 'html-escaper';
-import { bold, underline } from 'kleur/colors';
import type { ESBuildTransformResult... | packages/astro/src/core/errors/dev/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor: clean up dead code for env API | 14,395 | withastro/astro | 47,179 | TypeScript | ascorbic | |
if (typeof locale === 'string') {
return locale;
} else {
return locale.path;
}
});
if (!locales.includes(defaultLocale)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `The default locale \`${defaultLocale}\` is not present in the \`i18n.locales\` array.`,
path: ['i18n', 'lo... | No issues found. | if (typeof locale === 'string') {
return locale;
} else {
return locale.path;
}
});
if (!locales.includes(defaultLocale)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `The default locale \`${defaultLocale}\` is not present in the \`i18n.locales\` array.`,
path: ['i18n', 'lo... | @@ -42,21 +42,19 @@ export const AstroConfigRefinedSchema = z.custom<AstroConfig>().superRefine((con
}
}
- // TODO: Astro 6.0
- // Uncomment this validation check, and change the default value of redirectToDefaultLocale to false
- // if (
- // config.i18n &&
- // typeof config.i18n.routing !== 'string' &&
- //... | packages/astro/src/core/config/schemas/refined.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(astro)!: update `i18n.redirectToDefaultLocale` default | 14,406 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
import { ASTRO_VERSION } from '../../core/constants.js';
import type { AstroGlobalPartial } from '../../types/public/context.js';
// This is used to create the top-level Astro global; the one that you can use
// inside of getStaticPaths. See the `astroGlobalArgs` option for parameter type.
export function createAstro(... | No issues found. | import { ASTRO_VERSION } from '../../core/constants.js';
import type { AstroGlobalPartial } from '../../types/public/context.js';
// This is used to create the top-level Astro global; the one that you can use
// inside of getStaticPaths. See the `astroGlobalArgs` option for parameter type.
export function createAstro(... | @@ -1,41 +1,11 @@
import { ASTRO_VERSION } from '../../core/constants.js';
-import { AstroError, AstroErrorData } from '../../core/errors/index.js';
import type { AstroGlobalPartial } from '../../types/public/context.js';
-/** Create the Astro.glob() runtime function. */
-function createAstroGlobFn() {
- const glob... | packages/astro/src/runtime/server/astro-global.ts | 0 | TypeScript | 1 | none | 16 | 12 | 12 | true | feat!: remove Astro.glob | 14,421 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
// This is created inside of the runtime so we don't have access to the Astro logger.
console.warn(
`Astro.generator inside getStaticPaths is deprecated and will be removed in a future major version of Astro.`,
);
return ASTRO_GENERATOR;
},
get callAction(): any {
throw createError('callAction');... | No issues found. | // This is created inside of the runtime so we don't have access to the Astro logger.
console.warn(
`Astro.generator inside getStaticPaths is deprecated and will be removed in a future major version of Astro.`,
);
return ASTRO_GENERATOR;
},
get callAction(): any {
throw createError('callAction');... | @@ -1,11 +1,99 @@
-import { ASTRO_VERSION } from '../../core/constants.js';
-import type { AstroGlobalPartial } from '../../types/public/context.js';
+import { ASTRO_GENERATOR } from '../../core/constants.js';
+import { AstroError, AstroErrorData } from '../../core/errors/index.js';
+import type { AstroGlobal } from '.... | packages/astro/src/runtime/server/astro-global.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: deprecate Astro in getStaticPaths | 14,432 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
// Ignore root and internal paths
if (pathname === '/' || isInternalPath(pathname)) {
return pathname;
}
// Redirect multiple trailing slashes to collapsed path
const path = collapseDuplicateTrailingSlashes(pathname, trailingSlash !== 'never');
if (path !== pathname) {
return path;
}
if (traili... | No issues found. |
// Ignore root and internal paths
if (pathname === '/' || isInternalPath(pathname)) {
return pathname;
}
// Redirect multiple trailing slashes to collapsed path
const path = collapseDuplicateTrailingSlashes(pathname, trailingSlash !== 'never');
if (path !== pathname) {
return path;
}
if (traili... | @@ -320,14 +320,18 @@ export class App {
return pathname;
}
- async render(request: Request, renderOptions?: RenderOptions): Promise<Response> {
- let routeData: RouteData | undefined;
- let locals: object | undefined;
- let clientAddress: string | undefined;
- let addCookieHeader: boolean | undefined;
+ asy... | packages/astro/src/core/app/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: clean deprecated APIs | 14,462 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
customSitemaps = [],
publicBasePath = './',
xslURL: xslUrl,
lastmod,
namespaces = { news: true, xhtml: true, image: true, video: true },
}: WriteSitemapChunkConfig,
astroConfig: AstroConfig,
) {
await mkdir(destinationDir, { recursive: true });
// Normalize publicBasePath
let normalizedPublicBasePath =... | No issues found. | customSitemaps = [],
publicBasePath = './',
xslURL: xslUrl,
lastmod,
namespaces = { news: true, xhtml: true, image: true, video: true },
}: WriteSitemapChunkConfig,
astroConfig: AstroConfig,
) {
await mkdir(destinationDir, { recursive: true });
// Normalize publicBasePath
let normalizedPublicBasePath =... | @@ -0,0 +1,128 @@
+import { createWriteStream, type WriteStream } from 'node:fs';
+import { mkdir } from 'node:fs/promises';
+import { normalize, resolve } from 'node:path';
+import { pipeline, Readable } from 'node:stream';
+import { promisify } from 'node:util';
+import type { AstroConfig } from 'astro';
+import { Si... | packages/integrations/sitemap/src/write-sitemap-chunk.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Feature(sitemap): named files chunking strategy | 14,471 | withastro/astro | 47,179 | TypeScript | Slackluky | |
for (; j < vsize - 1; j++) {
let mv = 0;
let pv = -1;
const start = j * 32;
const vlen = Math.min(32, m) + start;
for (let k = start; k < vlen; k++) {
peq[b.charCodeAt(k)] |= 1 << k;
}
for (let i = 0; i < n; i++) {
const eq = peq[a.charCodeAt(i)];
const pb = (phc[(i / 32) | 0] >>> i) & 1;
con... | No issues found. | for (; j < vsize - 1; j++) {
let mv = 0;
let pv = -1;
const start = j * 32;
const vlen = Math.min(32, m) + start;
for (let k = start; k < vlen; k++) {
peq[b.charCodeAt(k)] |= 1 << k;
}
for (let i = 0; i < n; i++) {
const eq = peq[a.charCodeAt(i)];
const pb = (phc[(i / 32) | 0] >>> i) & 1;
con... | @@ -0,0 +1,152 @@
+import type { StringMatcher } from '../definitions.js';
+
+// Source: https://github.com/ka-weihe/fastest-levenshtein/blob/master/mod.ts
+// License: https://github.com/ka-weihe/fastest-levenshtein/blob/master/LICENSE.md
+const peq = new Uint32Array(0x10000);
+const myers_32 = (a: string, b: string):... | packages/astro/src/assets/fonts/implementations/levenshtein-string-matcher.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(fonts): warn on unsupported family name | 14,475 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
import type * as vite from 'vite';
import { AstroError } from '../core/errors/errors.js';
import { AstroErrorData } from '../core/errors/index.js';
import type { AstroSettings } from '../types/astro.js';
const virtualModuleId = 'astro:i18n';
type AstroInternationalization = {
settings: AstroSettings;
};
export defa... | No issues found. | import type * as vite from 'vite';
import { AstroError } from '../core/errors/errors.js';
import { AstroErrorData } from '../core/errors/index.js';
import type { AstroSettings } from '../types/astro.js';
const virtualModuleId = 'astro:i18n';
type AstroInternationalization = {
settings: AstroSettings;
};
export defa... | @@ -2,49 +2,20 @@ import type * as vite from 'vite';
import { AstroError } from '../core/errors/errors.js';
import { AstroErrorData } from '../core/errors/index.js';
import type { AstroSettings } from '../types/astro.js';
-import type { AstroConfig } from '../types/public/config.js';
const virtualModuleId = 'astr... | packages/astro/src/i18n/vite-plugin-i18n.ts | 0 | TypeScript | 1 | none | 16 | 27 | 27 | true | feat: support i18n | 14,486 | withastro/astro | 47,179 | TypeScript | ematipico | |
white-space: nowrap;
}
.link {
min-width: fit-content;
padding-right: 8px;
padding-top: 8px;
}
.link button {
background: none;
border: none;
font-size: inherit;
font-family: inherit;
}
.link a, .link button {
color: var(--accent);
text-decoration: none;
display: flex;
gap: 8px;
}
.link a:hover, ... | No issues found. | white-space: nowrap;
}
.link {
min-width: fit-content;
padding-right: 8px;
padding-top: 8px;
}
.link button {
background: none;
border: none;
font-size: inherit;
font-family: inherit;
}
.link a, .link button {
color: var(--accent);
text-decoration: none;
display: flex;
gap: 8px;
}
.link a:hover, ... | @@ -29,6 +29,7 @@ const style = /* css */ `
--background: #ffffff;
--error-text: #ba1212;
--error-text-hover: #a10000;
+ --success-text: #10b981;
--title-text: #090b11;
--box-background: #f3f4f7;
--box-background-hover: #dadbde;
@@ -39,7 +40,7 @@ const style = /* css */ `
--accent-hover: #792bc0;
... | packages/astro/src/core/errors/overlay.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(astro): add copy button for stack trace in error overlay | 14,489 | withastro/astro | 47,179 | TypeScript | dev-shetty | |
describe('Markdoc - Headings with custom Astro renderer', () => {
let fixture;
before(async () => {
fixture = await getFixture('headings-custom');
});
describe('dev', () => {
let devServer;
before(async () => {
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.s... | No issues found. | describe('Markdoc - Headings with custom Astro renderer', () => {
let fixture;
before(async () => {
fixture = await getFixture('headings-custom');
});
describe('dev', () => {
let devServer;
before(async () => {
devServer = await fixture.startDevServer();
});
after(async () => {
await devServer.s... | @@ -9,38 +9,6 @@ async function getFixture(name) {
});
}
-describe('experimental.headingIdCompat', () => {
- let fixture;
-
- before(async () => {
- fixture = await loadFixture({
- root: new URL(`./fixtures/headings/`, import.meta.url),
- experimental: { headingIdCompat: true },
- });
- });
-
- describe('dev... | packages/integrations/markdoc/test/headings.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat!: stabilize experimental.headingIdCompat | 14,494 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
chunk.type !== 'asset' &&
chunk.facadeModuleId === RESOLVED_ENTRYPOINT_VIRTUAL_MODULE_ID
) {
const outputDirectory = getServerOutputDirectory(opts.settings);
internals.astroActionsEntryPoint = new URL(chunkName, outputDirectory);
}
}
},
};
}
export function vitePluginActions({
fs,
s... | No issues found. | chunk.type !== 'asset' &&
chunk.facadeModuleId === RESOLVED_ENTRYPOINT_VIRTUAL_MODULE_ID
) {
const outputDirectory = getServerOutputDirectory(opts.settings);
internals.astroActionsEntryPoint = new URL(chunkName, outputDirectory);
}
}
},
};
}
export function vitePluginActions({
fs,
s... | @@ -7,50 +7,17 @@ import { shouldAppendForwardSlash } from '../core/build/util.js';
import { getServerOutputDirectory } from '../prerender/utils.js';
import type { AstroSettings } from '../types/astro.js';
import {
- ASTRO_ACTIONS_INTERNAL_MODULE_ID,
- NOOP_ACTIONS,
- RESOLVED_ASTRO_ACTIONS_INTERNAL_MODULE_ID,
- RES... | packages/astro/src/actions/vite-plugin-actions.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(actions): plugin and virtual modules | 14,538 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
if (queryParams) {
url += '?' + queryParams.toString();
}
return url;
}
function createStylesheetElement(
stylesheet: StylesheetAsset,
base?: string,
assetsPrefix?: AssetsPrefix,
queryParams?: URLSearchParams,
): SSRElement {
if (stylesheet.type === 'inline') {
return {
props: {},
children: styleshee... | No issues found. | if (queryParams) {
url += '?' + queryParams.toString();
}
return url;
}
function createStylesheetElement(
stylesheet: StylesheetAsset,
base?: string,
assetsPrefix?: AssetsPrefix,
queryParams?: URLSearchParams,
): SSRElement {
if (stylesheet.type === 'inline') {
return {
props: {},
children: styleshee... | @@ -3,21 +3,32 @@ import { fileExtension, joinPaths, prependForwardSlash, slash } from '../../core
import type { SSRElement } from '../../types/public/internal.js';
import type { AssetsPrefix, StylesheetAsset } from '../app/types.js';
-export function createAssetLink(href: string, base?: string, assetsPrefix?: Asse... | packages/astro/src/core/render/ssr-element.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Allow adapters to customize headers for fetch requests | 14,543 | withastro/astro | 47,179 | TypeScript | matthewp | |
const img = $('#densities-test img');
const srcset = img.attr('srcset');
// Extract widths from srcset (format: "url 1x", "url 1.5x", etc)
const descriptors = srcset
.split(', ')
.map((entry) => entry.split(' ')[1]);
// Extract the widths from the URLs (they should be valid configured sizes)
const u... | No issues found. | const img = $('#densities-test img');
const srcset = img.attr('srcset');
// Extract widths from srcset (format: "url 1x", "url 1.5x", etc)
const descriptors = srcset
.split(', ')
.map((entry) => entry.split(' ')[1]);
// Extract the widths from the URLs (they should be valid configured sizes)
const u... | @@ -44,6 +44,49 @@ describe('Image', () => {
assert.equal(img.attr('width'), '225', 'uses requested width in img attribute');
});
+ it('generates valid densities-based srcset using only configured sizes', async () => {
+ const html = await fixture.readFile('../.vercel/output/static/index.html');
+ const $ = ch... | packages/integrations/vercel/test/image.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(vercel): validate densities-based srcset widths against configured sizes | 14,570 | withastro/astro | 47,179 | TypeScript | matthewp | |
// Note: `orThrow` does not have progressive enhancement info.
// If you want to throw exceptions,
// you must handle those exceptions with client JS.
async orThrow(this: APIContext | undefined, param: any) {
const { data, error } = await handleAction(param, path, this);
if (error) throw erro... | No issues found. | // Note: `orThrow` does not have progressive enhancement info.
// If you want to throw exceptions,
// you must handle those exceptions with client JS.
async orThrow(this: APIContext | undefined, param: any) {
const { data, error } = await handleAction(param, path, this);
if (error) throw erro... | @@ -1,14 +1,14 @@
import { shouldAppendTrailingSlash } from 'virtual:astro:actions/options';
-import type { ActionClient, SafeResult } from '../actions/runtime/server.js';
+import type { APIContext } from '../../types/public/context.js';
+import type { ActionClient, SafeResult } from './server.js';
import {
ACTION_... | packages/astro/src/actions/runtime/virtual.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(actions): virtual module | 14,582 | withastro/astro | 47,179 | TypeScript | florian-lefebvre | |
it('resolves 404 on pattern match without static path - rest params', async () => {
const res = await fixture.fetch('/pizza/pizza-hut');
assert.equal(res.status, 404);
});
});
describe('route params type validation', () => {
it('resolves 200 on matching static path - string params', async () => {
// r... | No issues found. | it('resolves 404 on pattern match without static path - rest params', async () => {
const res = await fixture.fetch('/pizza/pizza-hut');
assert.equal(res.status, 404);
});
});
describe('route params type validation', () => {
it('resolves 200 on matching static path - string params', async () => {
// r... | @@ -6,6 +6,16 @@ import { loadFixture } from './test-utils.js';
const root = new URL('./fixtures/astro-get-static-paths/', import.meta.url);
+function resetFlags() {
+ // reset the flag used by [...calledTwiceTest].astro between each test
+ // @ts-expect-error not typed
+ globalThis.isCalledOnce = false;
+
+ // re... | packages/astro/test/astro-get-static-paths.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix!: disallow number in getStaticPaths params | 14,586 | withastro/astro | 47,179 | TypeScript | ocavue | |
console.log('Database schema is up to date.');
} else {
console.log(`Database schema is out of date.`);
}
if (isForceReset) {
const begin = await clack.confirm({
message: `Reset your database? All of your data will be erased and your schema created from scratch.`,
initialValue: false,
withGuide: fals... | No issues found. | console.log('Database schema is up to date.');
} else {
console.log(`Database schema is out of date.`);
}
if (isForceReset) {
const begin = await clack.confirm({
message: `Reset your database? All of your data will be erased and your schema created from scratch.`,
initialValue: false,
withGuide: fals... | @@ -1,6 +1,6 @@
+import * as clack from '@clack/prompts';
import type { AstroConfig } from 'astro';
import { sql } from 'drizzle-orm';
-import prompts from 'prompts';
import type { Arguments } from 'yargs-parser';
import { MIGRATION_VERSION } from '../../../consts.js';
import { createClient } from '../../../db-cli... | packages/db/src/core/cli/commands/push/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | perf: switch to clack for CLI prompts | 14,589 | withastro/astro | 47,179 | TypeScript | 43081j | |
declare module 'astro:content' {
interface Render {
'.mdx': Promise<{
Content: import('astro').MDXContent;
headings: import('astro').MarkdownHeading[];
remarkPluginFrontmatter: Record<string, any>;
components: import('astro').MDXInstance<{}>['components'];
}>;
}
}
| No issues found. | declare module 'astro:content' {
interface Render {
'.mdx': Promise<{
Content: import('astro').MDXContent;
headings: import('astro').MarkdownHeading[];
remarkPluginFrontmatter: Record<string, any>;
components: import('astro').MDXInstance<{}>['components'];
}>;
}
}
| @@ -1,7 +1,7 @@
declare module 'astro:content' {
interface Render {
'.mdx': Promise<{
- Content: import('astro').MarkdownInstance<{}>['Content'];
+ Content: import('astro').MDXContent;
headings: import('astro').MarkdownHeading[];
remarkPluginFrontmatter: Record<string, any>;
components: import('as... | packages/integrations/mdx/template/content-module-types.d.ts | 0 | TypeScript | 1 | none | 16 | 11 | 11 | true | feat(mdx): add TypeScript types for Content components prop | 14,591 | withastro/astro | 47,179 | TypeScript | matthewp | |
export function telemetryReset() {
return [green('▶ Anonymous telemetry preferences reset.'), ``].join('\n');
}
export function fsStrictWarning() {
const title = yellow('▶ ' + `${bold('vite.server.fs.strict')} has been disabled!`);
const subtitle = ` Files on your machine are likely accessible on your network.`;
... | No issues found. |
export function telemetryReset() {
return [green('▶ Anonymous telemetry preferences reset.'), ``].join('\n');
}
export function fsStrictWarning() {
const title = yellow('▶ ' + `${bold('vite.server.fs.strict')} has been disabled!`);
const subtitle = ` Files on your machine are likely accessible on your network.`;
... | @@ -1,8 +1,21 @@
+import { detect, resolveCommand } from 'package-manager-detector';
+import colors from 'picocolors';
+import type { ResolvedServerUrls } from 'vite';
+import type { ZodError } from 'zod';
+import { getDocsForError, renderErrorMarkdown } from './errors/dev/utils.js';
import {
- bgCyan,
+ AstroError,
+... | packages/astro/src/core/messages.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Replace `kleur` with `picocolors` | 14,598 | withastro/astro | 47,179 | TypeScript | delucis | |
import { defineMiddleware } from 'astro:middleware'
export const onRequest = defineMiddleware(async (ctx, next) => {
const url = new URL(ctx.request.url);
if (url.pathname.includes("/mid/to-redirect")) {
return ctx.redirect("/mid/from-redirect");
}
if (url.pathname.includes("/mid/to-rewrite")) {
return ctx.r... | No issues found. | import { defineMiddleware } from 'astro:middleware'
export const onRequest = defineMiddleware(async (ctx, next) => {
const url = new URL(ctx.request.url);
if (url.pathname.includes("/mid/to-redirect")) {
return ctx.redirect("/mid/from-redirect");
}
if (url.pathname.includes("/mid/to-rewrite")) {
return ctx.r... | @@ -0,0 +1,19 @@
+import { defineMiddleware } from 'astro:middleware'
+
+export const onRequest = defineMiddleware(async (ctx, next) => {
+ const url = new URL(ctx.request.url);
+
+ if (url.pathname.includes("/mid/to-redirect")) {
+ return ctx.redirect("/mid/from-redirect");
+ }
+ if (url.pathname.includes("/mid/to-r... | packages/integrations/cloudflare/test/fixtures/vite-plugin/src/middleware.ts | 0 | TypeScript | 1 | none | 16 | 20 | 20 | true | refactor: support middleware in entrypoint | 14,616 | withastro/astro | 47,179 | TypeScript | ematipico | |
// Skip if already has base path (makes function idempotent)
const alreadyHasBase = url.startsWith(normalizedBase + '/');
if (isRootRelative && !isExternal && !alreadyHasBase) {
return `url(${quote}${normalizedBase}${url}${quote})`;
}
return match;
});
}
export function createStylePreprocessor({
filen... | No issues found. | // Skip if already has base path (makes function idempotent)
const alreadyHasBase = url.startsWith(normalizedBase + '/');
if (isRootRelative && !isExternal && !alreadyHasBase) {
return `url(${quote}${normalizedBase}${url}${quote})`;
}
return match;
});
}
export function createStylePreprocessor({
filen... | @@ -1,20 +1,91 @@
import fs from 'node:fs';
import type { TransformOptions } from '@astrojs/compiler';
import { preprocessCSS, type ResolvedConfig } from 'vite';
+import type { AstroConfig } from '../../types/public/config.js';
import { AstroErrorData, CSSError, positionAt } from '../errors/index.js';
import { nor... | packages/astro/src/core/compile/style.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(css): rewrite absolute URLs with base path in dev mode | 14,622 | withastro/astro | 47,179 | TypeScript | aprici7y | |
});
});
describe('dev', () => {
/** @type {import('./test-utils.js').DevServer} */
let devServer;
before(async () => {
devServer = await fixture.startDevServer();
});
after(() => devServer.stop());
it('SVG metadata imported in React island is small', async () => {
const html = await fixture.fe... | No issues found. | });
});
describe('dev', () => {
/** @type {import('./test-utils.js').DevServer} */
let devServer;
before(async () => {
devServer = await fixture.startDevServer();
});
after(() => devServer.stop());
it('SVG metadata imported in React island is small', async () => {
const html = await fixture.fe... | @@ -0,0 +1,73 @@
+import assert from 'node:assert/strict';
+import { after, before, describe, it } from 'node:test';
+import * as cheerio from 'cheerio';
+import { loadFixture } from './test-utils.js';
+
+describe('astro:assets - SVG Components in Astro Islands', async () => {
+ /** @type {import('./test-utils.js').Fix... | packages/astro/test/core-image-svg-in-island.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Only attach SVG component in SSR | 14,623 | withastro/astro | 47,179 | TypeScript | delucis | |
},
}),
});
await fixture.build();
});
it('appends assetQueryParams to stylesheet URLs in SSR', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/');
const response = await app.render(request);
assert.equal(response.status, 200);
const h... | No issues found. | },
}),
});
await fixture.build();
});
it('appends assetQueryParams to stylesheet URLs in SSR', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/');
const response = await app.render(request);
assert.equal(response.status, 200);
const h... | @@ -0,0 +1,88 @@
+import assert from 'node:assert/strict';
+import { before, describe, it } from 'node:test';
+import * as cheerio from 'cheerio';
+import testAdapter from './test-adapter.js';
+import { loadFixture } from './test-utils.js';
+
+describe('Asset Query Parameters (Adapter Client Config)', () => {
+ /** @ty... | packages/astro/test/asset-query-params.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add support for skew protect for images and fonts | 14,627 | withastro/astro | 47,179 | TypeScript | matthewp | |
/**
* It injects the manifest in the given output rollup chunk. It returns the new emitted code
*/
function injectManifest(manifest: SerializedSSRManifest, chunk: Readonly<OutputChunk>) {
const code = chunk.code;
return code.replace(replaceExp, () => {
return JSON.stringify(manifest);
});
}
async function buil... | No issues found. | /**
* It injects the manifest in the given output rollup chunk. It returns the new emitted code
*/
function injectManifest(manifest: SerializedSSRManifest, chunk: Readonly<OutputChunk>) {
const code = chunk.code;
return code.replace(replaceExp, () => {
return JSON.stringify(manifest);
});
}
async function buil... | @@ -1,7 +1,6 @@
import { fileURLToPath } from 'node:url';
import type { OutputChunk } from 'rollup';
import { glob } from 'tinyglobby';
-import { type BuiltinDriverName, builtinDrivers } from 'unstorage';
import type { Plugin as VitePlugin } from 'vite';
import { getAssetsPrefix } from '../../../assets/utils/getAs... | packages/astro/src/core/build/plugins/plugin-manifest.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | refactor(sessions): import driver via vite plugin | 14,632 | withastro/astro | 47,179 | TypeScript | ematipico |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.