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
/** * Deletes a session value. */ delete(key: string) { this.#data?.delete(key); if (this.#partial) { this.#toDelete.add(key); } this.#dirty = true; } /** * Sets a session value. The session is created if it does not exist. */ set<T = any>(key: string, value: T, { ttl }: { ttl?: number } = {}...
The comment should be updated to reflect the new logic
/** * Deletes a session value. */ delete(key: string) { this.#data?.delete(key); if (this.#partial) { this.#toDelete.add(key); } this.#dirty = true; } /** * Sets a session value. The session is created if it does not exist. */ set<T = any>(key: string, value: T, { ttl }: { ttl?: number } = {}...
@@ -138,9 +152,10 @@ export class AstroSession<TDriver extends SessionDriverName = any> { message: 'The session key was not provided.', }); } + let cloned: T; try { // Attempt to serialize the value so we can throw an error early if needed
packages/astro/src/core/session.ts
26
TypeScript
0.286
suggestion
54
51
51
false
fix: clone session data on .set()
12,883
withastro/astro
47,179
TypeScript
ematipico
kaytwo
import assert from 'node:assert/strict'; import { before, describe, it } from 'node:test'; import * as devalue from 'devalue'; import testAdapter from './test-adapter.js'; import { loadFixture } from './test-utils.js'; import fs from 'node:fs'; describe('Astro.session', () => { /** @type {import('./test-utils').Fixtu...
We should probably be creating this in production too in that case. It could go here: https://github.com/kaytwo/astro/blob/6e7afe876fa8ee07457dd60e145de70aa3f9f5c3/packages/astro/src/core/session.ts#L396
import assert from 'node:assert/strict'; import { before, describe, it } from 'node:test'; import * as devalue from 'devalue'; import testAdapter from './test-adapter.js'; import { loadFixture } from './test-utils.js'; describe('Astro.session', () => { /** @type {import('./test-utils').Fixture} */ let fixture; bef...
@@ -1,13 +1,17 @@ import assert from 'node:assert/strict'; import { before, describe, it } from 'node:test'; +import * as devalue from 'devalue'; import testAdapter from './test-adapter.js'; import { loadFixture } from './test-utils.js'; +import fs from 'node:fs'; describe('Astro.session', () => { /** @type {i...
packages/astro/test/sessions.test.js
14
JavaScript
0.5
suggestion
207
39
39
false
fix: clone session data on .set()
12,883
withastro/astro
47,179
TypeScript
ascorbic
kaytwo
); } throw err; } if (!driver) { throw new AstroError({ ...SessionStorageInitError, message: SessionStorageInitError.message( 'The module did not export a driver.', this.#config.driver, ), }); } try { this.#storage = createStorage({ driver: driver(this.#config.opti...
OK, I think I understand this now. So is the problem that if you try to read a session when the directory hasn't been created then it has an error? I'm not happy with this workaround because we're otherwise not using the storage unless the user actually reads or writes a session. This is soemthign that should be fixed ...
); } throw err; } if (!driver) { throw new AstroError({ ...SessionStorageInitError, message: SessionStorageInitError.message( 'The module did not export a driver.', this.#config.driver, ), }); } try { this.#storage = createStorage({ driver: driver(this.#config.opti...
@@ -455,6 +449,13 @@ export class AstroSession<TDriver extends SessionDriverName = any> { this.#storage = createStorage({ driver: driver(this.#config.options), }); + if (this.#config.driver === 'fs-lite') { + // seems to be a race condition in unstorage when the session directory doesn't exist + //...
packages/astro/src/core/session.ts
26
TypeScript
0.643
suggestion
612
51
45
false
fix: clone session data on .set()
12,883
withastro/astro
47,179
TypeScript
ascorbic
kaytwo
| Promise<Array<TData>> | Record<string, Omit<TData, 'id'> & { id?: string }> | Promise<Record<string, Omit<TData, 'id'> & { id?: string }>>); }; type DataCollectionConfig<S extends BaseSchema> = { type: 'data'; schema?: S | ((context: SchemaContext) => S); }; type ContentCollectionConfig<S ext...
I've changed the jsdocs for these because most people will run `astro dev` rather than `astro sync`
| Promise<Array<TData>> | Record<string, Omit<TData, 'id'> & { id?: string }> | Promise<Record<string, Omit<TData, 'id'> & { id?: string }>>); }; type DataCollectionConfig<S extends BaseSchema> = { type: 'data'; schema?: S | ((context: SchemaContext) => S); }; type ContentCollectionConfig<S ext...
@@ -89,27 +89,29 @@ declare module 'astro:content' { input: CollectionConfig<S>, ): CollectionConfig<S>; - /** Run `astro sync` to generate high fidelity types */ + /** Run `astro dev` or `astro sync` to generate high fidelity types */
packages/astro/types/content.d.ts
26
TypeScript
0.429
suggestion
99
50
51
false
fix: add render() to stub content type defs
12,884
withastro/astro
47,179
TypeScript
ascorbic
ascorbic
}), ); } return config; } export default function (options?: Options): AstroIntegration { return { name: '@astrojs/vue', hooks: { 'astro:config:setup': async ({ addRenderer, updateConfig, command }) => { addRenderer(getRenderer()); if (options?.jsx) { addRenderer(getJsxRenderer()); } ...
```suggestion if (!options?.jsx) return; const knownJsxRenderers = ['@astrojs/react', '@astrojs/preact', '@astrojs/solid-js']; const enabledKnownJsxRenderers = config.integrations.filter((renderer) => knownJsxRenderers.includes(renderer.name)); // This error can only be thrown from here since Vu...
}), ); } return config; } export default function (options?: Options): AstroIntegration { return { name: '@astrojs/vue', hooks: { 'astro:config:setup': async ({ addRenderer, updateConfig, command }) => { addRenderer(getRenderer()); if (options?.jsx) { addRenderer(getJsxRenderer()); } ...
@@ -156,6 +156,15 @@ export default function (options?: Options): AstroIntegration { } updateConfig({ vite: await getViteConfiguration(command, options) }); }, + 'astro:config:done': ({ logger, config }) => { + const knownJsxRenderers = ['@astrojs/react', '@astrojs/preact', '@astrojs/solid-js']; + ...
packages/integrations/vue/src/index.ts
26
TypeScript
1
suggestion
757
31
33
false
Add warnings if multiple JSX renderers are used
12,887
withastro/astro
47,179
TypeScript
florian-lefebvre
louisescher
* See the [Content collections documentation](https://docs.astro.build/en/guides/content-collections/) for more information. */ export const InvalidContentEntryDataError = { name: 'InvalidContentEntryDataError', title: 'Content entry data does not match schema.', message(collection: string, entryId: string, error:...
```suggestion * A content loader returned an invalid `id`. ``` Like the title of your PR, if the reason this entry is invalid is only and exactly because of the ID, would it be more helpful to specify this here?
* Make sure that all required fields are present, and that all fields are of the correct type. * You can check against the collection schema in your `src/content.config.*` file. * See the [Content collections documentation](https://docs.astro.build/en/guides/content-collections/) for more information. */ export con...
@@ -1563,6 +1563,34 @@ export const InvalidContentEntryDataError = { 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 content loader for the collection **blog*...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.857
question
215
51
51
false
Improve errors for invalid IDs in content collections
12,892
withastro/astro
47,179
TypeScript
sarah11918
louisescher
title: 'Content entry data does not match schema.', message(collection: string, entryId: string, error: ZodError) { return [ `**${String(collection)} → ${String(entryId)}** data does not match collection schema.`, ...error.errors.map((zodError) => zodError.message), ].join('\n'); }, hint: 'See https://doc...
```suggestion export const ContentLoaderReturnsInvalidId = { ``` Just an e.g. based on my earlier question. There are probably lots of ways an entry can be invalid, so does it make sense to entirely base this on invalid ID
export const InvalidContentEntryDataError = { name: 'InvalidContentEntryDataError', title: 'Content entry data does not match schema.', message(collection: string, entryId: string, error: ZodError) { return [ `**${String(collection)} → ${String(entryId)}** data does not match collection schema.`, ...error.er...
@@ -1563,6 +1563,34 @@ export const InvalidContentEntryDataError = { 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 content loader for the collection **blog*...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.786
suggestion
225
51
51
false
Improve errors for invalid IDs in content collections
12,892
withastro/astro
47,179
TypeScript
sarah11918
louisescher
scripts: { stage: InjectedScriptStage; content: string; }[]; /** * Map of directive name (e.g. `load`) to the directive script code */ clientDirectives: Map<string, string>; devToolbarApps: (DevToolbarAppEntry | string)[]; middlewares: { pre: string[]; post: string[] }; tsConfig: TSConfig | undefined; t...
```suggestion // This makes content optional. Internal only so it's not optional on InjectedType ```
scripts: { stage: InjectedScriptStage; content: string; }[]; /** * Map of directive name (e.g. `load`) to the directive script code */ clientDirectives: Map<string, string>; devToolbarApps: (DevToolbarAppEntry | string)[]; middlewares: { pre: string[]; post: string[] }; tsConfig: TSConfig | undefined; t...
@@ -64,7 +64,8 @@ export interface AstroSettings { latestAstroVersion: string | undefined; serverIslandMap: NonNullable<SSRManifest['serverIslandMap']>; serverIslandNameMap: NonNullable<SSRManifest['serverIslandNameMap']>; - injectedTypes: Array<InjectedType>; + // This makes content optional. Internal only so it...
packages/astro/src/types/astro.ts
26
TypeScript
0.857
suggestion
103
51
51
false
fix: do not generate a stub for content types
12,909
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); const _EnvFieldMetadata = z.u...
```suggestion message: `**Invalid combination** of "access" and "context" options:\n Review the configuration of \`env.schema.${ctx.path.at(-1)}\`.\n Learn more at https://docs.astro.build/en/guides/environment-variables/#variable-types`, ``` Some questions! - Do error messages usually have some bolded word...
context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); const _EnvFieldMetadata = z.u...
@@ -75,11 +75,28 @@ const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); -const EnvFieldMetadata = z.union([ +const _EnvFieldMetadata = z.union([ PublicClientEnvFieldMetadata, PublicServerEnvFieldMetadata, SecretServerEnvFieldMetadata, ]); +const Env...
packages/astro/src/env/schema.ts
26
TypeScript
1
security
742
51
51
false
feat: improve astro:env config error
12,912
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
}), ]); export type EnvFieldType = z.infer<typeof EnvFieldType>; const PublicClientEnvFieldMetadata = z.object({ context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldM...
~~Can you explain to me where we check the **values** of `access` and `context`? I can't see it in the code, it's probably somewhere~~ I checked the source code, I am up to speed. To be honest, I would move the refine inside `PublicClientEnvFieldMetadata`, etc. instead, because it allow us to actually provide a good...
}), ]); export type EnvFieldType = z.infer<typeof EnvFieldType>; const PublicClientEnvFieldMetadata = z.object({ context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldM...
@@ -75,11 +75,28 @@ const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); -const EnvFieldMetadata = z.union([ +const _EnvFieldMetadata = z.union([ PublicClientEnvFieldMetadata, PublicServerEnvFieldMetadata, SecretServerEnvFieldMetadata, ]); +const Env...
packages/astro/src/env/schema.ts
26
TypeScript
0.786
suggestion
336
51
51
false
feat: improve astro:env config error
12,912
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); const _EnvFieldMetadata = z.u...
```suggestion message: `**Invalid combination** of "access" and "context" options:\n Secret client variables are not supported, review the configuration of \`env.schema.${ctx.path.at(-1)}\`.\n Learn more at https://docs.astro.build/en/guides/environment-variables/#variable-types`, ```
context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); const _EnvFieldMetadata = z.u...
@@ -75,11 +75,28 @@ const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); -const EnvFieldMetadata = z.union([ +const _EnvFieldMetadata = z.union([ PublicClientEnvFieldMetadata, PublicServerEnvFieldMetadata, SecretServerEnvFieldMetadata, ]); +const Env...
packages/astro/src/env/schema.ts
26
TypeScript
0.929
security
293
51
51
false
feat: improve astro:env config error
12,912
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); const _EnvFieldMetadata = z.u...
```suggestion message: `**Invalid combination** of "access" and "context" options:\n Secret client variables are not supported. Please review the configuration of \`env.schema.${ctx.path.at(-1)}\`.\n Learn more at https://docs.astro.build/en/guides/environment-variables/#variable-types`, ``` Technically should...
context: z.literal('client'), access: z.literal('public'), }); const PublicServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('public'), }); const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); const _EnvFieldMetadata = z.u...
@@ -75,11 +75,28 @@ const SecretServerEnvFieldMetadata = z.object({ context: z.literal('server'), access: z.literal('secret'), }); -const EnvFieldMetadata = z.union([ +const _EnvFieldMetadata = z.union([ PublicClientEnvFieldMetadata, PublicServerEnvFieldMetadata, SecretServerEnvFieldMetadata, ]); +const Env...
packages/astro/src/env/schema.ts
26
TypeScript
1
security
375
51
51
false
feat: improve astro:env config error
12,912
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
export type TreeNode = | { type: 'text'; content: string | HTMLString; } | { type: 'component'; component: AstroInstance['default']; collectedLinks?: string[]; collectedStyles?: string[]; collectedScripts?: string[]; props: Record<string, any>; children: TreeNode[]; } | { type: '...
It might look like I'm doing a lot of change here, but I'm only extracting the factory function here out so I can call itself for arrays. Disabling whitespace in diff should make it easier to review.
export type TreeNode = // Markdoc `if` tag often returns an array of nodes in the AST, which gets translated // here as an array of `TreeNode`s, which we'll render all without a wrapper. | TreeNode[] | { type: 'text'; content: string | HTMLString; } | { type: 'component'; component: AstroInstance['...
@@ -35,75 +38,86 @@ export type TreeNode = children: TreeNode[]; }; -export const ComponentNode = createComponent({ - factory(result: any, { treeNode }: { treeNode: TreeNode }) { - if (treeNode.type === 'text') return render`${treeNode.content}`; -
packages/integrations/markdoc/components/TreeNode.ts
26
TypeScript
0.429
refactor
199
51
51
false
Fix markdoc render code block in if tag
12,930
withastro/astro
47,179
TypeScript
bluwy
bluwy
import type { IncomingHttpHeaders } from 'node:http'; import { AstroError, AstroErrorData } from './errors/index.js'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; type RequestBody = | ArrayBuffer | Blob | ReadableStream | URLSearchParams | ...
This is type provided by `Request.body`
import type { IncomingHttpHeaders } from 'node:http'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; type RequestBody = | ArrayBuffer | Blob | ReadableStream | URLSearchParams | FormData | ReadableStream<Uint8Array>; export interface Create...
@@ -1,15 +1,22 @@ import type { IncomingHttpHeaders } from 'node:http'; +import { AstroError, AstroErrorData } from './errors/index.js'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; -type RequestBody = ArrayBuffer | Blob | ReadableStream | U...
packages/astro/src/core/request.ts
11
TypeScript
0.357
suggestion
39
36
36
false
fix(routing): don't trigger get of headers
12,937
withastro/astro
47,179
TypeScript
ematipico
ematipico
import type { IncomingHttpHeaders } from 'node:http'; import { AstroError, AstroErrorData } from './errors/index.js'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; type RequestBody = | ArrayBuffer | Blob | ReadableStream | URLSearchParams | ...
I added `null` because `Request.body` is `ReadableStream<Uint8Array> | null`
import type { IncomingHttpHeaders } from 'node:http'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; type RequestBody = | ArrayBuffer | Blob | ReadableStream | URLSearchParams | FormData | ReadableStream<Uint8Array>; export interface Create...
@@ -1,15 +1,22 @@ import type { IncomingHttpHeaders } from 'node:http'; +import { AstroError, AstroErrorData } from './errors/index.js'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; -type RequestBody = ArrayBuffer | Blob | ReadableStream | U...
packages/astro/src/core/request.ts
18
TypeScript
0.571
suggestion
76
43
43
false
fix(routing): don't trigger get of headers
12,937
withastro/astro
47,179
TypeScript
ematipico
ematipico
Object.defineProperty(request, 'headers', { ...headersDesc, get() { logger.warn( null, `\`Astro.request.headers\` was used when rendering the route \`${routePattern}'\`. \`Astro.request.headers\` is not available on prerendered pages. If you need access to request headers, make sure that the page...
Where is this version of the function used?
import type { IncomingHttpHeaders } from 'node:http'; import type { Logger } from './logger/core.js'; type HeaderType = Headers | Record<string, any> | IncomingHttpHeaders; type RequestBody = | ArrayBuffer | Blob | ReadableStream | URLSearchParams | FormData | ReadableStream<Uint8Array>; export interface Create...
@@ -92,3 +103,32 @@ export function createRequest({ return request; } + +/** + * Utility function that creates a new `Request` with a new URL from an old `Request`. + * + * @param newUrl The new `URL` + * @param oldRequest The old `Request` + */ +export function copyRequest(newUrl: URL, oldRequest: Request, isPrer...
packages/astro/src/core/request.ts
26
TypeScript
0.143
question
43
48
105
false
fix(routing): don't trigger get of headers
12,937
withastro/astro
47,179
TypeScript
ascorbic
ematipico
export async function syncInternal({ mode, logger, fs = fsMod, settings, skip, force, manifest, }: SyncOptions): Promise<void> { const isDev = mode === 'development'; if (force) { await clearContentLayerCache({ settings, logger, fs, isDev }); } const timerStart = performance.now(); if (!skip?.content) {...
`existSync` is now marked unused
* @experimental The JavaScript API is experimental */ export async function syncInternal({ mode, logger, fs = fsMod, settings, skip, force, manifest, command, }: SyncOptions): Promise<void> { const isDev = command === 'dev'; if (force) { await clearContentLayerCache({ settings, logger, fs, isDev }); } ...
@@ -127,15 +130,14 @@ export async function syncInternal({ settings.timer.start('Sync content layer'); let store: MutableDataStore | undefined; try { - const dataStoreFile = getDataStoreFile(settings); - if (existsSync(dataStoreFile)) { - store = await MutableDataStore.fromFile(dataStoreFile); - } + ...
packages/astro/src/core/sync/index.ts
26
TypeScript
0.286
suggestion
32
51
51
false
fix: explicitly set dev mode for data store
12,947
withastro/astro
47,179
TypeScript
ematipico
ascorbic
isDev: boolean; }) { const dataStore = getDataStoreFile(settings, isDev); if (fs.existsSync(dataStore)) { logger.debug('content', 'clearing data store'); await fs.promises.rm(dataStore, { force: true }); logger.warn('content', 'data store cleared (force)'); } } /** * Generates TypeScript types for all Astro...
Double checking if this is correct. In Astro, you can also technically do `astro build --devOutput` to get the development build. Do we want `isDev` `true` in that case? The `mode` here is typed as `string` because end-users can name it anything in practice. e.g. `astro build --mode staging` or `astro build --mode s...
logger: Logger; fs?: typeof fsMod; isDev: boolean; }) { const dataStore = getDataStoreFile(settings, isDev); if (fs.existsSync(dataStore)) { logger.debug('content', 'clearing data store'); await fs.promises.rm(dataStore, { force: true }); logger.warn('content', 'data store cleared (force)'); } } /** * Gen...
@@ -116,8 +118,9 @@ export async function syncInternal({ force, manifest, }: SyncOptions): Promise<void> { + const isDev = mode === 'development';
packages/astro/src/core/sync/index.ts
26
TypeScript
0.786
suggestion
426
51
51
false
fix: explicitly set dev mode for data store
12,947
withastro/astro
47,179
TypeScript
bluwy
ascorbic
const viteConfig: ViteUserConfig = { optimizeDeps: { include: ['@astrojs/preact/client.js', 'preact', 'preact/jsx-runtime'], exclude: ['@astrojs/preact/server.js'], }, }; if (compat) { viteConfig.optimizeDeps!.include!.push( 'preact/compat', 'preact/test-utils', ...
Just released as 2.10.1, thanks for letting us know this was an issue!
const viteConfig: ViteUserConfig = { optimizeDeps: { include: ['@astrojs/preact/client.js', 'preact', 'preact/jsx-runtime'], exclude: ['@astrojs/preact/server.js'], }, }; if (compat) { viteConfig.optimizeDeps!.include!.push( 'preact/compat', 'preact/test-utils', ...
@@ -60,7 +60,21 @@ export default function ({ include, exclude, compat, devtools }: Options = {}): }; } - viteConfig.plugins = [preactPlugin]; + viteConfig.plugins = [ + preactPlugin, + // TODO: remove once https://github.com/preactjs/preset-vite/pull/156 is released
packages/integrations/preact/src/index.ts
26
TypeScript
0.214
suggestion
70
51
50
false
chore(preact): upgrade @preact/preset-vite
12,950
withastro/astro
47,179
TypeScript
rschristian
Marabyte
const status = redirectRoute && typeof redirect === 'object' ? redirect.status : method === 'GET' ? 301 : 308; const headers = { location: encodeURI(redirectRouteGenerate(renderContext)) }; if (redirect && redirectIsExternal(redirect)) { if (typeof redirect === 'string') { return Response.redirect(redirect, s...
Should this todo be addressed now?
const status = redirectRoute && typeof redirect === 'object' ? redirect.status : method === 'GET' ? 301 : 308; const headers = { location: encodeURI(redirectRouteGenerate(renderContext)) }; if (redirect && redirectIsExternal(redirect)) { if (typeof redirect === 'string') { return Response.redirect(redirect, s...
@@ -21,13 +39,17 @@ function redirectRouteGenerate(renderContext: RenderContext): string { if (typeof redirectRoute !== 'undefined') { return redirectRoute?.generate(params) || redirectRoute?.pathname || '/'; } else if (typeof redirect === 'string') { - // TODO: this logic is duplicated between here and manifes...
packages/astro/src/core/redirects/render.ts
26
TypeScript
0.143
question
34
39
38
false
feat(routing): external redirects
12,979
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
* } * }) * ``` * * * For statically-generated sites with no adapter installed, this will produce a client redirect using a [`<meta http-equiv="refresh">` tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#http-equiv) and does not support status codes. * * When using SSR or with a stat...
Note: See my suggestions in the Docs PR. I think this could nicely be incorporated into the existing description instead of a standalone section!
* '/about': 'https://example.com/about', * '/news': { * status: 302, * destination: 'https://example.com/news' * } * } * }) * ``` * * * For statically-generated sites with no adapter installed, this will produce a client redirect using a [`<meta http-equiv="refresh">` tag](h...
@@ -287,14 +287,28 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * You can customize the [redirection status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages) using an object in the redirect config: * * ```js - * { + * export default defineConfig({ ...
packages/astro/src/types/public/config.ts
26
TypeScript
0.429
suggestion
145
51
51
false
feat(routing): external redirects
12,979
withastro/astro
47,179
TypeScript
sarah11918
ematipico
* destination: 'https://example.com/news' * } * } * }) * ``` * * * For statically-generated sites with no adapter installed, this will produce a client redirect using a [`<meta http-equiv="refresh">` tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#http-equiv) and does not s...
```suggestion * }) * ``` */ ``` This might fix it?
* destination: 'https://example.com/news' * } * } * }) * ``` * * * For statically-generated sites with no adapter installed, this will produce a client redirect using a [`<meta http-equiv="refresh">` tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#http-equiv) and does not s...
@@ -287,16 +292,15 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * You can customize the [redirection status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages) using an object in the redirect config: * * ```js - * { + * export default defineConfig({ ...
packages/astro/src/types/public/config.ts
26
TypeScript
0.571
question
61
51
51
false
feat(routing): external redirects
12,979
withastro/astro
47,179
TypeScript
sarah11918
ematipico
message: (globStr: string) => `\`Astro.glob(${globStr})\` did not return any matching files.`, hint: 'Check the pattern for typos.', } satisfies ErrorData; /** * @docs * @see * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) * @description * A redirect must be given a location w...
```suggestion * An external redirect must start with http or https, and must be a valid URL. */ export const UnsupportedExternalRedirect = { name: 'UnsupportedExternalRedirect', title: 'Unsupported or malformed URL.', message: 'An external redirect must start with http or https, and must be a valid URL.', `...
message: (globStr: string) => `\`Astro.glob(${globStr})\` did not return any matching files.`, hint: 'Check the pattern for typos.', } satisfies ErrorData; /** * @docs * @see * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) * @description * A redirect must be given a location w...
@@ -995,6 +995,20 @@ export const RedirectWithNoLocation = { name: 'RedirectWithNoLocation', title: 'A redirect must be given a location with the `Location` header.', } satisfies ErrorData; + +/** + * @docs + * @see + * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) + * @descript...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.786
suggestion
357
51
51
false
feat(routing): external redirects
12,979
withastro/astro
47,179
TypeScript
sarah11918
ematipico
fallbackRoutes: [], }; const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } } } } } } } if (dev) { // In SSR, a 404 route is injected in the App directly for some special handling, // it must not appear in the manifest ensu...
This is not injected in dev anymore if there's no adapter, is that expected?
fallbackRoutes: [], }; const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } } } } } } } if (dev) { // In SSR, a 404 route is injected in the App directly for some special handling, // it must not appear in the manifest ensu...
@@ -718,12 +718,13 @@ export async function createRouteManifest( } if (dev || settings.buildOutput === 'server') { injectImageEndpoint(settings, { routes }, dev ? 'dev' : 'build'); - // Ideally we would only inject the server islands route if server islands are used in the project. - // Unfortunately, there is...
packages/astro/src/core/routing/manifest/create.ts
26
TypeScript
0.357
question
76
51
51
false
Fix server islands for prerender-only sites
12,982
withastro/astro
47,179
TypeScript
florian-lefebvre
bluwy
test('Scripts are only executed once', async ({ page, astro }) => { // Go to page 1 await page.goto(astro.resolveUrl('/one')); let p = page.locator('#one'); await expect(p, 'should have content').toHaveText('Page 1'); // go to page 2 await page.click('#click-two'); const article = page.locator('#twoarti...
Navigation across pages 3 and 5 will do a full page load as those don't use the client router.
test('Scripts are only executed once', async ({ page, astro }) => { // Go to page 1 await page.goto(astro.resolveUrl('/one')); let p = page.locator('#one'); await expect(p, 'should have content').toHaveText('Page 1'); // go to page 2 await page.click('#click-two'); const article = page.locator('#twoarti...
@@ -647,14 +647,35 @@ test.describe('View Transitions', () => { test('Scripts are only executed once', async ({ page, astro }) => { // Go to page 1 await page.goto(astro.resolveUrl('/one')); - const p = page.locator('#one'); + let p = page.locator('#one'); await expect(p, 'should have content').toHaveText(...
packages/astro/e2e/view-transitions.test.js
26
JavaScript
0.286
suggestion
94
51
51
false
Prevent rerunning scripts already ran in router
12,985
withastro/astro
47,179
TypeScript
martrapp
matthewp
// can't fetch, let someone else deal with it. return null; } } export function getFallback(): Fallback { const el = document.querySelector('[name="astro-view-transitions-fallback"]'); if (el) { return el.getAttribute('content') as Fallback; } return 'animate'; } const scriptsAlreadyRan = new Set<string>()...
maybe move checking the type attribute two lines up as we do not need to remember e.g. speculation rules, import maps, or partytown scripts
} catch { // can't fetch, let someone else deal with it. return null; } } export function getFallback(): Fallback { const el = document.querySelector('[name="astro-view-transitions-fallback"]'); if (el) { return el.getAttribute('content') as Fallback; } return 'animate'; } function runScripts() { let wai...
@@ -132,10 +132,17 @@ export function getFallback(): Fallback { return 'animate'; } +const scriptsAlreadyRan = new Set<string>(); +const detectScriptExecuted = (script: HTMLScriptElement) => { + const key = script.src ? new URL(script.src, location.href).href : script.textContent!; + if (scriptsAlreadyRan.has(key)...
packages/astro/src/transitions/router.ts
26
TypeScript
0.571
suggestion
140
51
51
false
Prevent rerunning scripts already ran in router
12,985
withastro/astro
47,179
TypeScript
martrapp
matthewp
const PERSIST_ATTR = 'data-astro-transition-persist'; const scriptsAlreadyRan = new Set<string>(); export function detectScriptExecuted(script: HTMLScriptElement) { const key = script.src ? new URL(script.src, location.href).href : script.textContent!; if (scriptsAlreadyRan.has(key)) return true; scriptsAlreadyRan...
Seems this is the real cause of what let the tests fail last time. We should definitively visit all scripts, and not break after the first known one ;-)
const PERSIST_ATTR = 'data-astro-transition-persist'; const scriptsAlreadyRan = new Set<string>(); export function detectScriptExecuted(script: HTMLScriptElement) { const key = script.src ? new URL(script.src, location.href).href : script.textContent!; if (scriptsAlreadyRan.has(key)) return true; scriptsAlreadyRan...
@@ -6,25 +6,29 @@ export type SavedFocus = { const PERSIST_ATTR = 'data-astro-transition-persist'; +const scriptsAlreadyRan = new Set<string>(); +export function detectScriptExecuted(script: HTMLScriptElement) { + const key = script.src ? new URL(script.src, location.href).href : script.textContent!; + if (scripts...
packages/astro/src/transitions/swap-functions.ts
26
TypeScript
0.429
bug
153
51
51
false
Prevent rerunning scripts already ran in router
12,985
withastro/astro
47,179
TypeScript
martrapp
matthewp
return { html, redirected: res.redirected ? res.url : undefined, mediaType, }; } catch { // can't fetch, let someone else deal with it. return null; } } export function getFallback(): Fallback { const el = document.querySelector('[name="astro-view-transitions-fallback"]'); if (el) { return el.ge...
Not quite sure about your last commit but to me it looks as if it would simply prevent all reruns including those with data-astro-rerun
return { html, redirected: res.redirected ? res.url : undefined, mediaType, }; } catch { // can't fetch, let someone else deal with it. return null; } } export function getFallback(): Fallback { const el = document.querySelector('[name="astro-view-transitions-fallback"]'); if (el) { return el.ge...
@@ -138,6 +139,7 @@ function runScripts() { if (script.dataset.astroExec === '') continue; const type = script.getAttribute('type'); if (type && type !== 'module' && type !== 'text/javascript') continue; + if (detectScriptExecuted(script)) continue;
packages/astro/src/transitions/router.ts
26
TypeScript
0.357
suggestion
137
51
51
false
Prevent rerunning scripts already ran in router
12,985
withastro/astro
47,179
TypeScript
martrapp
matthewp
} } catch (e: any) { this.#logger.error( 'router', `Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.`, ); this.#logger.error('router', `Error: ${e}`); } } } return pathname; } #r...
This function should be moved inside `internal-helpers` (the `MANY_SLASHES` constant, too) since it's been used in multiple places
} catch (e: any) { this.#logger.error( 'router', `Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.`, ); this.#logger.error('router', `Error: ${e}`); } } } return pathname; } #redirect...
@@ -250,12 +253,53 @@ export class App { return pathname; } + #redirectTrailingSlash(pathname: string): string | undefined { + const { trailingSlash } = this.#manifest; + + // Ignore root and internal paths + if (pathname === '/' || pathname.startsWith('/_')) { + return; + } + + // Redirect multiple trail...
packages/astro/src/core/app/index.ts
26
TypeScript
0.571
refactor
131
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
ematipico
ascorbic
} export function isRemotePath(src: string) { return /^(?:http|ftp|https|ws):?\/\//.test(src) || src.startsWith('data:'); } export function slash(path: string) { return path.replace(/\\/g, '/'); } export function fileExtension(path: string) { const ext = path.split('.').pop(); return ext !== path ? `.${ext}` : '...
```suggestion const WITH_FILE_EXT = /\/[^/]+\.\w+$/; export function hasFileExtension(path: string) { return WITH_FILE_EXT.test(path); ```
export function removeFileExtension(path: string) { let idx = path.lastIndexOf('.'); return idx === -1 ? path : path.slice(0, idx); } export function removeQueryString(path: string) { const index = path.lastIndexOf('?'); return index > 0 ? path.substring(0, index) : path; } export function isRemotePath(src: stri...
@@ -104,3 +104,9 @@ export function removeBase(path: string, base: string) { } return path; } + +const withFileExt = /\/[^/]+\.\w+$/; + +export function hasFileExtension(path: string) { + return withFileExt.test(path);
packages/internal-helpers/src/path.ts
26
TypeScript
0.714
suggestion
145
28
37
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
ematipico
ascorbic
#redirectTrailingSlash(pathname: string): string | undefined { const { trailingSlash } = this.#manifest; // Ignore root and internal paths if (pathname === '/' || pathname.startsWith('/_')) { return; } // Redirect multiple trailing slashes to collapsed path if (MANY_SLASHES.test(pathname)) { const ...
We already have a bunch of methods to handle trailing slashes, let's use them instead of re-inventing the wheel: - `prependForwardSlash` - `removeTrailingForwardSlash`
const { trailingSlash } = this.#manifest; // Ignore root and internal paths if (pathname === '/' || pathname.startsWith('/_')) { return pathname; } // Redirect multiple trailing slashes to collapsed path const path = collapseDuplicateTrailingSlashes(pathname, trailingSlash !== 'never'); if (path !== ...
@@ -250,12 +253,53 @@ export class App { return pathname; } + #redirectTrailingSlash(pathname: string): string | undefined { + const { trailingSlash } = this.#manifest; + + // Ignore root and internal paths + if (pathname === '/' || pathname.startsWith('/_')) { + return; + } + + // Redirect multiple trail...
packages/astro/src/core/app/index.ts
26
TypeScript
0.714
suggestion
170
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
ematipico
ascorbic
return path ? path : '/'; } if (trailingSlash === 'ignore') { return; } // Add a trailing slash if it's not a file const hasTrailingSlash = pathname.endsWith('/'); if (trailingSlash === 'always' && !hasTrailingSlash && !hasFileExtension(pathname)) { return `${pathname}/`; } if (trailingSlash ...
The changeset doesn't mention anything regarding the status code (`301` and `308`). I think we should document it.
} if (trailingSlash === 'ignore') { return pathname; } if (trailingSlash === 'always' && !hasFileExtension(pathname)) { return appendForwardSlash(pathname); } if (trailingSlash === 'never') { return removeTrailingForwardSlash(pathname); } return pathname; } async render(request: Request, ...
@@ -250,12 +253,53 @@ export class App { return pathname; } + #redirectTrailingSlash(pathname: string): string | undefined { + const { trailingSlash } = this.#manifest; + + // Ignore root and internal paths + if (pathname === '/' || pathname.startsWith('/_')) { + return; + } + + // Redirect multiple trail...
packages/astro/src/core/app/index.ts
26
TypeScript
0.571
suggestion
114
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
ematipico
ascorbic
return; } // Add a trailing slash if it's not a file const hasTrailingSlash = pathname.endsWith('/'); if (trailingSlash === 'always' && !hasTrailingSlash && !hasFileExtension(pathname)) { return `${pathname}/`; } if (trailingSlash === 'never' && hasTrailingSlash) { return pathname.slice(0, -1); ...
Shouldn't we pass the hash, too?
} if (trailingSlash === 'always' && !hasFileExtension(pathname)) { return appendForwardSlash(pathname); } if (trailingSlash === 'never') { return removeTrailingForwardSlash(pathname); } return pathname; } async render(request: Request, renderOptions?: RenderOptions): Promise<Response> { let rou...
@@ -250,12 +253,53 @@ export class App { return pathname; } + #redirectTrailingSlash(pathname: string): string | undefined { + const { trailingSlash } = this.#manifest; + + // Ignore root and internal paths + if (pathname === '/' || pathname.startsWith('/_')) { + return; + } + + // Redirect multiple trail...
packages/astro/src/core/app/index.ts
26
TypeScript
0.143
question
33
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
ematipico
ascorbic
import path from 'node:path'; import { appendForwardSlash, collapseDuplicateTrailingSlashes, } from '@astrojs/internal-helpers/path'; import { bold } from 'kleur/colors'; import type { Logger } from '../core/logger/core.js'; import notFoundTemplate, { subpathNotUsedTemplate } from '../template/4xx.js'; import { write...
I think I'd move this to a its own middleware since it's no longer about the dev base handling, but not a big blocker for the PR.
import path from 'node:path'; import { bold } from 'kleur/colors'; import type { Logger } from '../core/logger/core.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../template/4xx.js'; import { writeHtmlResponse } from './response.js'; import { appendForwardSlash } from '@astrojs/internal-helpers/path'; ...
@@ -23,8 +24,8 @@ export function baseMiddleware( return function devBaseMiddleware(req, res, next) { const url = req.url!; - if (manySlashes.test(url)) { - const destination = url.replace(manySlashes, '/'); + const destination = collapseDuplicateTrailingSlashes(url, true); + if (url && destination !== url)...
packages/astro/src/vite-plugin-astro-server/base.ts
26
TypeScript
0.429
refactor
129
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
bluwy
ascorbic
</html>`; } export function subpathNotUsedTemplate(base: string, pathname: string) { return template({ pathname, statusCode: 404, title: 'Not found', tabTitle: '404: Not Found', body: `<p>In your <code>site</code> you have your base path set to <a href="${base}">${base}</a>. Do you want to go there instead?...
Not opposed to also a link to Discord for help, but perhaps a docs link to config reference for `trailingSlash` is more directly helpful?
</html>`; } export function subpathNotUsedTemplate(base: string, pathname: string) { return template({ pathname, statusCode: 404, title: 'Not found', tabTitle: '404: Not Found', body: `<p>In your <code>site</code> you have your base path set to <a href="${base}">${base}</a>. Do you want to go there instead?...
@@ -129,6 +130,21 @@ export function subpathNotUsedTemplate(base: string, pathname: string) { }); } +export function trailingSlashMismatchTemplate(pathname: string, trailingSlash: 'always' | 'never' | 'ignore') { + const corrected = + trailingSlash === 'always' + ? appendForwardSlash(pathname) + : removeTrail...
packages/astro/src/template/4xx.ts
26
TypeScript
0.5
question
137
38
38
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
sarah11918
ascorbic
* } * ``` * * In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs/`: * * ```js * { * base: '/docs', * trailingSlash: "always" * } * ``` */ base?: string; /** * @docs * @name trailingSlash * @type {('always' | 'never' | ...
```suggestion * - `'ignore'` - Match URLs regardless of whether a trailing "/" exists. Requests for "/about" and "/about/" will both match the same route. * - `'always'` - Only match URLs that include a trailing slash (e.g: "/about/"). In production, requests for on-demand rendered URLs without a trailing sla...
* } * ``` * * In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs/`: * * ```js * { * base: '/docs', * trailingSlash: "always" * } * ``` */ base?: string; /** * @docs * @name trailingSlash * @type {('always' | 'never' | ...
@@ -236,14 +236,13 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * @see build.format * @description * - * Set the route matching behavior of the dev server. Choose from the following options: - * - `'always'` - Only match URLs that include a trailing slash (ex: "/foo/") - * - `'nev...
packages/astro/src/types/public/config.ts
26
TypeScript
0.857
suggestion
2,053
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
sarah11918
ascorbic
* * In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs/`: * * ```js * { * base: '/docs', * trailingSlash: "always" * } * ``` */ base?: string; /** * @docs * @name trailingSlash * @type {('always' | 'never' | 'ignore')} *...
```suggestion * Trailing slashes on prerendered pages are handled by the hosting platform, and may not respect your chosen configuration. ```
* * In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs/`: * * ```js * { * base: '/docs', * trailingSlash: "always" * } * ``` */ base?: string; /** * @docs * @name trailingSlash * @type {('always' | 'never' | 'ignore')} *...
@@ -236,14 +236,13 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * @see build.format * @description * - * Set the route matching behavior of the dev server. Choose from the following options: - * - `'always'` - Only match URLs that include a trailing slash (ex: "/foo/") - * - `'nev...
packages/astro/src/types/public/config.ts
26
TypeScript
0.857
suggestion
147
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
sarah11918
ascorbic
* * ```js * { * base: '/docs', * trailingSlash: "always" * } * ``` */ base?: string; /** * @docs * @name trailingSlash * @type {('always' | 'never' | 'ignore')} * @default `'ignore'` * @see build.format * @description * * Set the route matching behavior for trailing slashes in the...
```suggestion * When redirects occur in production for GET requests, the redirect will be a 301 (permanent) redirect. For all other request methods, it will be a 308 (permanent, and preserve the request method) redirect. * * Trailing slashes on prerendered pages are handled by the hosting platform, and may no...
* * ```js * { * base: '/docs', * trailingSlash: "always" * } * ``` */ base?: string; /** * @docs * @name trailingSlash * @type {('always' | 'never' | 'ignore')} * @default `'ignore'` * @see build.format * @description * * Set the route matching behavior for trailing slashes in the...
@@ -236,14 +236,13 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * @see build.format * @description * - * Set the route matching behavior of the dev server. Choose from the following options: - * - `'always'` - Only match URLs that include a trailing slash (ex: "/foo/") - * - `'nev...
packages/astro/src/types/public/config.ts
26
TypeScript
0.929
question
394
51
51
false
feat: redirect trailing slashes on on-demand rendered pages
12,994
withastro/astro
47,179
TypeScript
sarah11918
ascorbic
export const ActionCalledFromServerError = { name: 'ActionCalledFromServerError', title: 'Action unexpected called from the server.', message: 'Action called from a server page or endpoint without using `Astro.callAction()`. This wrapper must be used to call actions from server code.', hint: 'See the `Astro.callA...
There's an error for this already called `ServerOnlyModule`
export const ActionCalledFromServerError = { name: 'ActionCalledFromServerError', title: 'Action unexpected called from the server.', message: 'Action called from a server page or endpoint without using `Astro.callAction()`. This wrapper must be used to call actions from server code.', hint: 'See the `Astro.callA...
@@ -1782,6 +1782,30 @@ export const ActionCalledFromServerError = { hint: 'See the `Astro.callAction()` reference for usage examples: https://docs.astro.build/en/reference/api-reference/#callaction', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot the module without enabling the experimental feat...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.5
suggestion
59
48
36
false
chore: first implementation for serialized config
13,000
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import type { Plugin } from 'vite'; import { CantUseManifestModule, ForbiddenManifestModule } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConf...
I think we could go with a simpler approach ```suggestion const VIRTUAL_SERVER_ID = 'astro:manifest/server' const RESOLVED_VIRTUAL_SERVER_ID = '\0' + VIRTUAL_SERVER_ID const VIRTUAL_CLIENT_ID = 'astro:manifest/client' const RESOLVED_VIRTUAL_CLIENT_ID = '\0' + VIRTUAL_CLIENT_ID ```
import type { Plugin } from 'vite'; import { CantUseManifestModule } from '../core/errors/errors-data.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConfig, Clie...
@@ -0,0 +1,111 @@ +import type { Plugin } from 'vite'; +import { CantUseManifestModule, ForbiddenManifestModule } from '../core/errors/errors-data.js'; +import { AstroError } from '../core/errors/index.js'; +import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +...
packages/astro/src/manifest/virtual-module.ts
21
TypeScript
0.857
suggestion
287
46
46
false
chore: first implementation for serialized config
13,000
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
const VIRTUAL_MODULES_IDS_SET = new Set(Object.values(VIRTUAL_MODULES_IDS)); function resolveVirtualModuleId<T extends string>(id: T): `\0${T}` { return `\0${id}`; } export default function virtualModulePlugin({ settings, logger, }: { settings: AstroSettings; logger: Logger }): Plugin { return { enforce: 'pre'...
What would be the use case for this?
export default function virtualModulePlugin({ settings, logger: _logger, }: { settings: AstroSettings; logger: Logger }): Plugin { return { enforce: 'pre', name: 'astro-manifest-plugin', resolveId(id) { // Resolve the virtual module if (VIRTUAL_SERVER_ID === id) { return RESOLVED_VIRTUAL_SERVER_ID; ...
@@ -0,0 +1,111 @@ +import type { Plugin } from 'vite'; +import { CantUseManifestModule, ForbiddenManifestModule } from '../core/errors/errors-data.js'; +import { AstroError } from '../core/errors/index.js'; +import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +...
packages/astro/src/manifest/virtual-module.ts
26
TypeScript
0.143
question
36
51
51
false
chore: first implementation for serialized config
13,000
withastro/astro
47,179
TypeScript
ascorbic
ematipico
import type { Plugin } from 'vite'; import { CantUseManifestModule, ForbiddenManifestModule } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConf...
can you fix these lint errors?
import type { Plugin } from 'vite'; import { CantUseManifestModule } from '../core/errors/errors-data.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConfig, Clie...
@@ -0,0 +1,111 @@ +import type { Plugin } from 'vite'; +import { CantUseManifestModule, ForbiddenManifestModule } from '../core/errors/errors-data.js'; +import { AstroError } from '../core/errors/index.js'; +import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +...
packages/astro/src/manifest/virtual-module.ts
20
TypeScript
0.214
question
30
45
45
false
chore: first implementation for serialized config
13,000
withastro/astro
47,179
TypeScript
matthewp
ematipico
import type { AstroConfig } from './config.js'; export type SerializedClientBuild = Pick<AstroConfig['build'], 'format' | 'redirects'>; export type SerializedServerBuild = Pick<AstroConfig['build'], 'client' | 'server'>; export type ClientConfigSerialized = Pick< AstroConfig, 'base' | 'i18n' | 'trailingSlash' | 'c...
Glad that these are using `Pick`. We should only be adding things to this module that we explicitly decide to add, rather than defaulting to exposing everything. If that was your thought too, mind making a comment here saying as such, so that we don't mistakenly change that in the future?
/** * **IMPORTANT**: use the `Pick` interface to select only the properties that we want to expose * to the users. Using blanket types could expose properties that we don't want. So if we decide to expose * properties, we need to be good at justifying them. For example: why you need this config? can't you use an int...
@@ -0,0 +1,19 @@ +import type { AstroConfig } from './config.js'; + +export type SerializedClientBuild = Pick<AstroConfig['build'], 'format' | 'redirects'>;
packages/astro/src/types/public/manifest.ts
10
TypeScript
0.643
question
289
20
27
false
chore: first implementation for serialized config
13,000
withastro/astro
47,179
TypeScript
matthewp
ematipico
import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConfig } from '../types/public/config.js'; import type { RouteData } from '../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSION...
Does `?raw` have to be at the end of the query? What if it's in the middle?
import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConfig } from '../types/public/config.js'; import type { RouteData } from '../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSION...
@@ -18,6 +18,9 @@ export function isURL(value: unknown): value is URL { } /** Check if a file is a markdown file based on its extension */ export function isMarkdownFile(fileId: string, option?: { suffix?: string }): boolean { + if (fileId.endsWith('?raw')) { + return false; + }
packages/astro/src/core/util.ts
23
TypeScript
0.357
question
76
48
48
false
fix: allow imports of Markdown files as raw text
13,026
withastro/astro
47,179
TypeScript
ematipico
ascorbic
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 (newChildren != null) { newProps.children = React.createElement(StaticHtml, { hydrate: need...
Should this be an else if? ```suggestion else if ('renderToReadableStream' in ReactDOM) { ```
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 (newChildren != null) { newProps.children = React.createElement(StaticHtml, { hydrate: need...
@@ -101,6 +101,9 @@ async function renderToStaticMarkup(Component, props, { default: children, ...sl formState, }; let html; + if (opts.experimentalDisableStreaming) { + html = ReactDOM.renderToString(vnode); + } if ('renderToReadableStream' in ReactDOM) {
packages/integrations/react/server.js
26
JavaScript
0.643
suggestion
97
51
51
false
Adds experimental support for disabling streaming
13,036
withastro/astro
47,179
TypeScript
florian-lefebvre
artmsilva
import react, { type Options as ViteReactPluginOptions } from '@vitejs/plugin-react'; import type { AstroIntegration, ContainerRenderer } from 'astro'; import type * as vite from 'vite'; import { type ReactVersionConfig, type SupportedReactVersion, getReactMajorVersion, isUnsupportedVersion, versionsConfig, } from...
```suggestion * Disable streaming in React components ```
import react, { type Options as ViteReactPluginOptions } from '@vitejs/plugin-react'; import type { AstroIntegration, ContainerRenderer } from 'astro'; import type * as vite from 'vite'; import { type ReactVersionConfig, type SupportedReactVersion, getReactMajorVersion, isUnsupportedVersion, versionsConfig, } from...
@@ -14,6 +14,10 @@ export type ReactIntegrationOptions = Pick< 'include' | 'exclude' | 'babel' > & { experimentalReactChildren?: boolean; + /** + * Disable streaming support for React components in order to support libraries that are not compatible with streaming like Stitches.js
packages/integrations/react/src/index.ts
18
TypeScript
0.571
suggestion
61
43
43
false
Adds experimental support for disabling streaming
13,036
withastro/astro
47,179
TypeScript
ascorbic
artmsilva
export type ReactIntegrationOptions = Pick< ViteReactPluginOptions, 'include' | 'exclude' | 'babel' > & { experimentalReactChildren?: boolean; /** * Disable streaming support for React components in order to support libraries that are not compatible with streaming like Stitches.js */ experimentalDisableStream...
Now we're adding more options it's probably best to make this an options object
export type ReactIntegrationOptions = Pick< ViteReactPluginOptions, 'include' | 'exclude' | 'babel' > & { experimentalReactChildren?: boolean; /** * Disable streaming in React components */ experimentalDisableStreaming?: boolean; }; const FAST_REFRESH_PREAMBLE = react.preambleCode; function getRenderer(reac...
@@ -26,7 +30,10 @@ function getRenderer(reactConfig: ReactVersionConfig) { }; } -function optionsPlugin(experimentalReactChildren: boolean): vite.Plugin { +function optionsPlugin( + experimentalReactChildren: boolean, + experimentalDisableStreaming: boolean +): vite.Plugin {
packages/integrations/react/src/index.ts
26
TypeScript
0.214
suggestion
79
51
51
false
Adds experimental support for disabling streaming
13,036
withastro/astro
47,179
TypeScript
ascorbic
artmsilva
} } // support `className` for better JSX compat if (key === 'className') { return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`); } // Prevents URLs in attributes from being escaped in static builds if (typeof value === 'string' && value.includes('&') && isHttpUrl(value)) { return m...
I think https://github.com/withastro/astro/blob/main/packages/astro/src/runtime/server/render/util.ts#L10-L11 should be updated instead? Or maybe that's not enough
return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`); } } // support `className` for better JSX compat if (key === 'className') { return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`); } // Prevents URLs in attributes from being escaped in stati...
@@ -114,6 +114,11 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the return markHTMLString(` ${key}`); } + // Popover seems to be boolean, but it can actually have the value "auto" or "manual" + if (key === 'popover' && typeof value === 'boolean') {
packages/astro/src/runtime/server/render/util.ts
26
TypeScript
0.429
suggestion
163
51
51
false
Fixes attribute rendering for `popover`
13,037
withastro/astro
47,179
TypeScript
florian-lefebvre
nanarino
if (typeof value === 'object') { return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`); } } // support `className` for better JSX compat if (key === 'className') { return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`); } // Prevents URLs in att...
```suggestion // We cannot add it to htmlBooleanAttributes because it can be: boolean | "auto" | "manual" ```
if (typeof value === 'object') { return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`); } } // support `className` for better JSX compat if (key === 'className') { return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`); } // Prevents URLs in att...
@@ -115,6 +115,11 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the return markHTMLString(` ${key}`); } + // Popover seems to be boolean, but it can actually have the value "auto" or "manual"
packages/astro/src/runtime/server/render/util.ts
26
TypeScript
0.786
suggestion
112
51
51
false
Fixes attribute rendering for `popover`
13,037
withastro/astro
47,179
TypeScript
florian-lefebvre
nanarino
const { tsConfig, tsConfigPath } = settings; if (!tsConfig || !tsConfigPath || !tsConfig.compilerOptions) return null; const { baseUrl, paths } = tsConfig.compilerOptions as CompilerOptions; if (!baseUrl) return null; // resolve the base url from the configuration file directory const resolvedBaseUrl = path.res...
This is the fix. The index needs resetting between paths, because it's per-regex
const { tsConfig, tsConfigPath } = settings; if (!tsConfig || !tsConfigPath || !tsConfig.compilerOptions) return null; const { baseUrl, paths } = tsConfig.compilerOptions as CompilerOptions; if (!baseUrl) return null; // resolve the base url from the configuration file directory const resolvedBaseUrl = path.res...
@@ -33,10 +33,9 @@ const getConfigAlias = (settings: AstroSettings): Alias[] | null => { .join('')}$`, ); - /** Internal index used to calculate the matching id in a replacement. */ - let matchId = 0; - for (const value of values) { + /** Internal index used to calculate the matching id in a repl...
packages/astro/src/vite-plugin-config-alias/index.ts
26
TypeScript
0.286
suggestion
80
51
51
false
fix: correctly handle multiple wildcard path aliases
13,059
withastro/astro
47,179
TypeScript
ascorbic
ascorbic
); }, } satisfies ErrorData; /** * @docs * @see * - [devalue library](https://github.com/rich-harris/devalue) * @description * `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets). */ export const Unsupported...
```suggestion export const CantUseAstroConfigModuleError = { name: 'CantUseAstroConfigModuleError', ``` To match all the other errors
* @description * Content collection entries must have unique slugs. Duplicates are often caused by the `slug` frontmatter property. */ export const DuplicateContentEntrySlugError = { name: 'DuplicateContentEntrySlugError', title: 'Duplicate content entry slug.', message(collection: string, slug: string, preExisti...
@@ -1758,6 +1758,19 @@ export const UnsupportedConfigTransformError = { hint: 'See the devalue library for all supported types: https://github.com/rich-harris/devalue', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot use the module `astro:config` without enabling the experimental feature. + */ +e...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.929
suggestion
138
51
51
false
fix: docs and types
13,087
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
`**${collection}** contains multiple entries with the same slug: \`${slug}\`. ` + `Slugs must be unique.\n\n` + `Entries: \n` + `- ${preExisting}\n` + `- ${alsoFound}` ); }, } satisfies ErrorData; /** * @docs * @see * - [devalue library](https://github.com/rich-harris/devalue) * @description * `...
This now shows up in the Content Collections Errors section 😅
hint: 'Ensure your data entry is an object with valid JSON (for `.json` entries) or YAML (for `.yaml` entries).', } satisfies ErrorData; /** * @docs * @message `COLLECTION_NAME` contains multiple entries with the same slug: `SLUG`. Slugs must be unique. * @description * Content collection entries must have unique ...
@@ -1758,6 +1758,19 @@ export const UnsupportedConfigTransformError = { hint: 'See the devalue library for all supported types: https://github.com/rich-harris/devalue', } satisfies ErrorData; +/** + * @docs
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.357
suggestion
62
51
51
false
fix: docs and types
13,087
withastro/astro
47,179
TypeScript
sarah11918
ematipico
import { loadFixture } from './test-utils.js'; describe('astro:config/client', () => { /** @type {import('./test-utils').Fixture} */ let fixture; let devServer; describe('when the experimental flag is not enabled', async () => { before(async () => { fixture = await loadFixture({ root: './fixtures/astro-m...
```suggestion assert.match(html, /CantUseAstroConfigModuleError/); ```
import { loadFixture } from './test-utils.js'; describe('astro:config/client', () => { /** @type {import('./test-utils').Fixture} */ let fixture; let devServer; describe('when the experimental flag is not enabled', async () => { before(async () => { fixture = await loadFixture({ root: './fixtures/astro-m...
@@ -29,7 +29,7 @@ describe('astro:manifest/client', () => { it('should throw an error when importing the module', async () => { const response = await fixture.fetch('/'); const html = await response.text(); - assert.match(html, /CantUseManifestModule/); + assert.match(html, /CantUseAstroConfigModule/);
packages/astro/test/serializeManifest.test.js
26
JavaScript
0.786
suggestion
75
51
51
false
fix: docs and types
13,087
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
it('should return an error when using inside a client script', async () => { const error = await fixture.build().catch((err) => err); assert.equal(error instanceof AstroError, true); assert.equal(error.name, ServerOnlyModule.name); }); }); describe('when the experimental flag is not enabled in dev', asy...
```suggestion assert.match(html, /CantUseAstroConfigModuleError/); ```
it('should return an error when using inside a client script', async () => { const error = await fixture.build().catch((err) => err); assert.equal(error instanceof AstroError, true); assert.equal(error.name, ServerOnlyModule.name); }); }); describe('when the experimental flag is not enabled in dev', asy...
@@ -150,7 +150,7 @@ describe('astro:manifest/server', () => { it('should throw an error when importing the module', async () => { const response = await fixture.fetch('/server'); const html = await response.text(); - assert.match(html, /CantUseManifestModule/); + assert.match(html, /CantUseAstroConfigMod...
packages/astro/test/serializeManifest.test.js
26
JavaScript
0.786
suggestion
75
51
51
false
fix: docs and types
13,087
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
assert.deepEqual(await response.json(), { something: 'true', }); request = new Request('http://example.com/api/', { headers: { origin: 'http://loreum.com', 'content-type': 'application/x-www-form-urlencoded' }, method: 'GET', }); response = await app.render(request); assert.equal(response.status, ...
Since this is quite a delicate feature that involves security, would you mind adding a test for each verb method that was added to `SAFE_METHODS`? I would like to cover all cases if possible
assert.deepEqual(await response.json(), { something: 'true', }); request = new Request('http://example.com/api/', { headers: { origin: 'http://loreum.com', 'content-type': 'application/x-www-form-urlencoded' }, method: 'GET', }); response = await app.render(request); assert.equal(response.status, ...
@@ -176,6 +176,34 @@ describe('CSRF origin check', () => { }); }); + it("return a 200 when the origin doesn't match but calling HEAD", async () => {
packages/astro/test/csrf-protection.test.js
26
JavaScript
0.643
security
191
51
51
false
fix: respond with 200 to HEAD requests for non-prerendered pages as well
13,101
withastro/astro
47,179
TypeScript
ematipico
corneliusroemer
method: 'GET', }); response = await app.render(request); assert.equal(response.status, 200); assert.deepEqual(await response.json(), { something: 'true', }); request = new Request('http://example.com/api/', { headers: { origin: 'http://loreum.com', 'content-type': 'text/plain' }, method: 'GET',...
The test is failing because you're hitting an endpoint, which exposes only the `GET` method. You should: - create an astro component and hit that route - expand the `api.ts` file and add the rest of the verbs to test
method: 'GET', }); response = await app.render(request); assert.equal(response.status, 200); assert.deepEqual(await response.json(), { something: 'true', }); request = new Request('http://example.com/api/', { headers: { origin: 'http://loreum.com', 'content-type': 'text/plain' }, method: 'GET',...
@@ -176,6 +176,34 @@ describe('CSRF origin check', () => { }); }); + it("return a 200 when the origin doesn't match but calling HEAD", async () => { + let request; + let response; + request = new Request('http://example.com/api/', { + headers: { origin: 'http://loreum.com', 'content-type': 'multipart/form-d...
packages/astro/test/csrf-protection.test.js
26
JavaScript
0.643
bug
222
51
51
false
fix: respond with 200 to HEAD requests for non-prerendered pages as well
13,101
withastro/astro
47,179
TypeScript
ematipico
corneliusroemer
*/ const FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain', ]; const SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS', 'TRACE']; /** * Returns a middleware function in charge to check the `origin` header. * * @private */ export function createOriginCheckMiddleware(): Midd...
a nuance, imho `isSameOrigin` would fit better, as seen also in `isPrerendered`, `hasContentType` etc.
*/ const FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain', ]; // Note: TRACE is unsupported by undici/Node.js const SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']; /** * Returns a middleware function in charge to check the `origin` header. * * @private */ export funct...
@@ -25,15 +27,11 @@ export function createOriginCheckMiddleware(): MiddlewareHandler { if (isPrerendered) { return next(); } - if (request.method === 'GET') { + // Safe methods don't require origin check + if (SAFE_METHODS.includes(request.method)) { return next(); } - const sameOrigin = - (reque...
packages/astro/src/core/app/middlewares.ts
26
TypeScript
0.714
suggestion
102
51
51
false
fix: respond with 200 to HEAD requests for non-prerendered pages as well
13,101
withastro/astro
47,179
TypeScript
jurajkapsz
corneliusroemer
'astro:config:setup': ({ config: _config, command, injectScript }) => { const lib = `${appendForwardSlash(_config.base)}~partytown/`; const recreateIFrameScript = `;(e=>{e.addEventListener("astro:before-swap",e=>{let r=document.body.querySelector("iframe[src*='${lib}']");if(r)e.newDocument.body.append(r)})})...
```suggestion await copyLibFiles(fileURLToPath(new URL(options?.config?.lib?.replace(/^\/?/, '') ?? '~partytown', dir)), { ```
'astro:config:setup': ({ config: _config, command, injectScript }) => { const lib = `${appendForwardSlash(_config.base)}~partytown/`; const recreateIFrameScript = `;(e=>{e.addEventListener("astro:before-swap",e=>{let r=document.body.querySelector("iframe[src*='${lib}']");if(r)e.newDocument.body.append(r)})})...
@@ -48,7 +48,8 @@ export default function createPlugin(options?: PartytownOptions): AstroIntegrati ); }, 'astro:build:done': async ({ dir }) => { - await copyLibFiles(fileURLToPath(new URL('~partytown', dir)), { + let libValue = options?.config?.lib?.replace(/^\/?/, ''); + await copyLibFiles(fileU...
packages/integrations/partytown/src/index.ts
26
TypeScript
0.786
suggestion
132
41
43
false
feat(partytown): allow overriding `copyLibFiles.dest` in `astro:build:done` hook with the `lib` option
13,109
withastro/astro
47,179
TypeScript
florian-lefebvre
arnottferels
} else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; if (base !== '/' && newUrl.pathname.startsWith(base)) { pathname = shouldAppendForwardSlash(trailingSlash, buildFormat) ? appendForward...
Nit: since we already do the decoding at line 58, let's do it once: ```js let decodedPathname = decodeURI(pathname) ``` And let's use this variable at line 58 and line 68
} else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; if (base !== '/' && newUrl.pathname.startsWith(base)) { pathname = shouldAppendForwardSlash(trailingSlash, buildFormat) ? appendForward...
@@ -65,7 +65,7 @@ export function findRouteToRewrite({ return { routeData: foundRoute, newUrl, - pathname, + pathname: decodeURI(pathname),
packages/astro/src/core/routing/rewrite.ts
26
TypeScript
0.786
suggestion
179
51
51
false
fix: correctly handle pathname for dynamic routing in rewrite
13,113
withastro/astro
47,179
TypeScript
ematipico
unprintable123
// Pipe this to the same handling as `UpdateResult.updated` for now. case UpdateResult.failure: case UpdateResult.updated: case undefined: { const list = integrations .map((integration) => ` - ${integration.integrationName}`) .join('\n'); logger.info( 'SKIP_FORMAT', msg.success( `Add...
```suggestion logger.warn('SKIP_FORMAT', msg.actionRequired('You must import your Tailwind stylesheet, e.g.:\n')); ``` I like how short yours is, but is it *always*, *literally*, *exactly* accurate? Is it always "copy this exact code in this exact spot?" Non-blocking, but just a note that you ARE going to ge...
// Pipe this to the same handling as `UpdateResult.updated` for now. case UpdateResult.failure: case UpdateResult.updated: case undefined: { const list = integrations .map((integration) => ` - ${integration.integrationName}`) .join('\n'); logger.info( 'SKIP_FORMAT', msg.success( `Add...
@@ -361,7 +361,19 @@ export async function add(names: string[], { flags }: AddOptions) { } to your project:\n${list}`, ), ); - logger.info('SKIP_FORMAT', msg.success("Import './src/styles/global.css' in a layout")); + if (integrations.find((integration) => integration.integrationName === 'tailwind'))...
packages/astro/src/cli/add/index.ts
26
TypeScript
0.786
suggestion
419
51
51
false
Tailwind v4 onboarding enhancements
13,119
withastro/astro
47,179
TypeScript
sarah11918
Hacksore
* Checks if the given request corresponds to a 404 or 500 route based on the specified base path. * * @param {Request} request - The HTTP request object to be checked. * @param {string} [base=''] - The base path to trim from the request's URL before checking the route. Default is an empty string. * @return {boolea...
```suggestion return route.type === 'redirect' && route.redirect && redirectIsExternal(route.redirect); ```
import type { RoutesList } from '../../types/astro.js'; import type { RouteData } from '../../types/public/internal.js'; import { redirectIsExternal } from '../redirects/render.js'; import { SERVER_ISLAND_BASE_PREFIX, SERVER_ISLAND_COMPONENT } from '../server-islands/endpoint.js'; /** Find matching route from pathname...
@@ -76,3 +77,18 @@ export function requestIs404Or500(request: Request, base = '') { return isRoute404(pathname) || isRoute500(pathname); } + +/** + * Determines whether a given route is an external redirect. + * + * @param {RouteData} route - The route object to check. + * @return {boolean} Returns true if the rou...
packages/astro/src/core/routing/match.ts
26
TypeScript
0.857
suggestion
110
28
90
false
fix(routing): skip middleware for external redirects
13,133
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
regexStr += '(:[0-9]+)?'; } if (pathname) { if (pathname.endsWith('/**')) { // Match any path. regexStr += `(\\${pathname.replace('/**', '')}.*)`; } if (pathname.endsWith('/*')) { // Match one level of path regexStr += `(\\${pathname.replace('/*', '')}\/[^/?#]+)\/?`; } else { // Exact match ...
```suggestion } catch { ``` I think that works
regexStr += '(:[0-9]+)?'; } if (pathname) { if (pathname.endsWith('/**')) { // Match any path. regexStr += `(\\${pathname.replace('/**', '')}.*)`; } if (pathname.endsWith('/*')) { // Match one level of path regexStr += `(\\${pathname.replace('/*', '')}\/[^/?#]+)\/?`; } else { // Exact match ...
@@ -91,7 +91,7 @@ export function remotePatternToRegex( } try { new RegExp(regexStr); - } catch (e) { + } catch (_e) {
packages/integrations/netlify/src/index.ts
26
TypeScript
0.571
suggestion
50
51
51
false
chore: fix linting issues, integration tests
13,187
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import { fileURLToPath } from 'node:url'; import type { CreatePreviewServer } from 'astro'; import { AstroError } from 'astro/errors'; import { logListeningOn } from './log-listening-on.js'; import type { createExports } from './server.js'; import { createServer } from './standalone.js'; type ServerModule = ReturnType...
Is this unused? If so, maybe we can remove it
import { fileURLToPath } from 'node:url'; import type { CreatePreviewServer } from 'astro'; import { AstroError } from 'astro/errors'; import { logListeningOn } from './log-listening-on.js'; import type { createExports } from './server.js'; import { createServer } from './standalone.js'; type ServerModule = ReturnType...
@@ -10,14 +10,13 @@ type MaybeServerModule = Partial<ServerModule>; const createPreviewServer: CreatePreviewServer = async (preview) => { let ssrHandler: ServerModule['handler']; - let options: ServerModule['options']; + let _options: ServerModule['options'];
packages/integrations/node/src/preview.ts
13
TypeScript
0.143
question
45
38
38
false
chore: fix linting issues, integration tests
13,187
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
const headers = config.build.assetsPrefix ? undefined : [ { for: `${config.base}${config.base.endsWith('/') ? '' : '/'}${config.build.assets}/*`, values: { 'Cache-Control': 'public, max-age=31536000, immutable', }, }, ]; // See https://docs.netlify.com/image-cdn/create-integratio...
I would suggest a different use case. "notice missing files" isn't a good one imho, we should provide a better example, maybe a real one. Maybe "missing files" is what we're looking, but we should reword it
const headers = config.build.assetsPrefix ? undefined : [ { for: `${config.base}${config.base.endsWith('/') ? '' : '/'}${config.build.assets}/*`, values: { 'Cache-Control': 'public, max-age=31536000, immutable', }, }, ]; // See https://docs.netlify.com/image-cdn/create-integratio...
@@ -139,6 +140,12 @@ async function writeNetlifyFrameworkConfig(config: AstroConfig, logger: AstroInt } export interface NetlifyIntegrationConfig { + /** Force files to be bundled with your function. This is helpful when you notice missing files. */
packages/integrations/netlify/src/index.ts
26
TypeScript
0.5
suggestion
206
51
51
false
Update netlify adapter to integrate includeFiles and excludeFiles options
13,194
withastro/astro
47,179
TypeScript
ematipico
dfdez
} const fallback = finalBuildOutput === 'static' ? '/.netlify/static' : '/.netlify/functions/ssr'; const redirects = createRedirectsFromAstroRoutes({ config: _config, dir, routeToDynamicTargetMap: new Map(staticRedirects.map((route) => [route, fallback])), buildOutput, assets, }); if (!redire...
Since you passed `absolute: true`, there's no need to use `_config.root`. Plus, you could have used `rootDir` instead. https://www.npmjs.com/package/fast-glob#output-control
routes: IntegrationResolvedRoute[], dir: URL, buildOutput: HookParameters<'astro:config:done'>['buildOutput'], assets: HookParameters<'astro:build:done'>['assets'], ) { // all other routes are handled by SSR const staticRedirects = routes.filter( (route) => route.type === 'redirect' && (route.redirect |...
@@ -246,6 +255,18 @@ export default function netlifyIntegration( } } + async function getFilesByGlob( + include: Array<string> = [], + exclude: Array<string> = [], + ): Promise<Array<URL>> { + const files = await glob(include, { + cwd: fileURLToPath(rootDir), + absolute: true, + ignore: exclude, + }); ...
packages/integrations/netlify/src/index.ts
26
TypeScript
0.571
suggestion
177
51
51
false
Update netlify adapter to integrate includeFiles and excludeFiles options
13,194
withastro/astro
47,179
TypeScript
ematipico
dfdez
if (finalBuildOutput === 'server') { // Merge any includes from `vite.assetsInclude if (_config.vite.assetsInclude) { const mergeGlobbedIncludes = (globPattern: unknown) => { if (typeof globPattern === 'string') { const entries = glob.sync(globPattern).map((p) => pathToFileURL(p)); extraFil...
Two questions: - Why aren't these assets resolved from the same `cwd` of line 263? - Why don't we ignore `exclude`?
absolute: true, ignore: exclude, }); return files.map((file) => pathToFileURL(file)); } async function writeSSRFunction({ notFoundContent, logger, root, }: { notFoundContent?: string; logger: AstroIntegrationLogger; root: URL; }) { const entry = new URL('./entry.mjs', ssrBuildDir()); con...
@@ -257,12 +278,38 @@ export default function netlifyIntegration( }) { const entry = new URL('./entry.mjs', ssrBuildDir()); + const _includeFiles = integrationConfig?.includeFiles || []; + const _excludeFiles = integrationConfig?.excludeFiles || []; + + if (finalBuildOutput === 'server') { + // Merge any in...
packages/integrations/netlify/src/index.ts
26
TypeScript
0.5
question
120
51
51
false
Update netlify adapter to integrate includeFiles and excludeFiles options
13,194
withastro/astro
47,179
TypeScript
ematipico
dfdez
export interface NetlifyIntegrationConfig { /** Force files to be bundled with your function. This is helpful when you notice missing files. */ includeFiles?: string[]; /** Exclude any files from the bundling process that would otherwise be included. */ excludeFiles?: string[]; /** * If enabled, On-Demand-Rend...
There's an important piece of information that is missing from the inline JS docs. The code resolves the files from the `rootDir`. This information must be shared with the docs. This information is also missing from the docs PR (I checked). What does that mean? If a user adds an absolute path, this might fail. We s...
export interface NetlifyIntegrationConfig { /** * Force files to be bundled with your SSR function. * This is useful for including any type of file that is not directly detected by the bundler, * like configuration files or assets that are dynamically imported at runtime. * * Note: File paths are resolved re...
@@ -139,6 +140,12 @@ async function writeNetlifyFrameworkConfig(config: AstroConfig, logger: AstroInt } export interface NetlifyIntegrationConfig { + /** Force files to be bundled with your function. This is helpful when you notice missing files. */ + includeFiles?: string[]; + + /** Exclude any files from the bund...
packages/integrations/netlify/src/index.ts
26
TypeScript
0.643
bug
351
51
51
false
Update netlify adapter to integrate includeFiles and excludeFiles options
13,194
withastro/astro
47,179
TypeScript
ematipico
dfdez
for: `${config.base}${config.base.endsWith('/') ? '' : '/'}${config.build.assets}/*`, values: { 'Cache-Control': 'public, max-age=31536000, immutable', }, }, ]; // See https://docs.netlify.com/image-cdn/create-integration/ const deployConfigDir = new URL('.netlify/v1/', config.root); awa...
```suggestion * Note: File paths are resolved relative to your project's `root`. Absolute paths may not work as expected. ```
for: `${config.base}${config.base.endsWith('/') ? '' : '/'}${config.build.assets}/*`, values: { 'Cache-Control': 'public, max-age=31536000, immutable', }, }, ]; // See https://docs.netlify.com/image-cdn/create-integration/ const deployConfigDir = new URL('.netlify/v1/', config.root); awa...
@@ -139,6 +140,32 @@ async function writeNetlifyFrameworkConfig(config: AstroConfig, logger: AstroInt } export interface NetlifyIntegrationConfig { + /** + * Force files to be bundled with your SSR function. + * This is useful for including any type of file that is not directly detected by the bundler, + * like ...
packages/integrations/netlify/src/index.ts
26
TypeScript
0.714
suggestion
129
51
51
false
Update netlify adapter to integrate includeFiles and excludeFiles options
13,194
withastro/astro
47,179
TypeScript
ematipico
dfdez
} const fallback = finalBuildOutput === 'static' ? '/.netlify/static' : '/.netlify/functions/ssr'; const redirects = createRedirectsFromAstroRoutes({ config: _config, dir, routeToDynamicTargetMap: new Map(staticRedirects.map((route) => [route, fallback])), buildOutput, assets, }); if (!redire...
```suggestion return files.map((file) => pathToFileURL(file)); ``` `pathToFileURL` already return a URL object
} const fallback = finalBuildOutput === 'static' ? '/.netlify/static' : '/.netlify/functions/ssr'; const redirects = createRedirectsFromAstroRoutes({ config: _config, dir, routeToDynamicTargetMap: new Map(staticRedirects.map((route) => [route, fallback])), buildOutput, assets, }); if (!redire...
@@ -246,6 +275,18 @@ export default function netlifyIntegration( } } + async function getFilesByGlob( + include: Array<string> = [], + exclude: Array<string> = [], + ): Promise<Array<URL>> { + const files = await glob(include, { + cwd: fileURLToPath(rootDir), + absolute: true, + ignore: exclude, + }); ...
packages/integrations/netlify/src/index.ts
26
TypeScript
0.714
suggestion
115
51
51
false
Update netlify adapter to integrate includeFiles and excludeFiles options
13,194
withastro/astro
47,179
TypeScript
ascorbic
dfdez
*/ export function isRoute404or500(route: RouteData): boolean { return isRoute404(route.route) || isRoute500(route.route); } /** * Determines if a given route is associated with the server island component. * * @param {RouteData} route - The route data object to evaluate. * @return {boolean} Returns true if the ...
```suggestion base === '/' ? url.pathname.slice(base.length) : url.pathname.slice(base.length + 1); ```
*/ export function isRoute404or500(route: RouteData): boolean { return isRoute404(route.route) || isRoute500(route.route); } /** * Determines if a given route is associated with the server island component. * * @param {RouteData} route - The route data object to evaluate. * @return {boolean} Returns true if the ...
@@ -59,7 +59,8 @@ export function isRouteServerIsland(route: RouteData): boolean { */ export function isRequestServerIsland(request: Request, base = ''): boolean { const url = new URL(request.url); - const pathname = url.pathname.slice(base.length); + const pathname = + base == '/' ? url.pathname.slice(base.lengt...
packages/astro/src/core/routing/match.ts
26
TypeScript
0.714
suggestion
107
51
51
false
fix(i18n): bypass server island with base
13,205
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
*/ export function isRoute404or500(route: RouteData): boolean { return isRoute404(route.route) || isRoute500(route.route); } /** * Determines if a given route is associated with the server island component. * * @param {RouteData} route - The route data object to evaluate. * @return {boolean} Returns true if the ...
Does this take into account base with trailing/leading slashes? eg. will it work if base if `/custom`, `custom/` and `/custom/`?
*/ export function isRoute404or500(route: RouteData): boolean { return isRoute404(route.route) || isRoute500(route.route); } /** * Determines if a given route is associated with the server island component. * * @param {RouteData} route - The route data object to evaluate. * @return {boolean} Returns true if the ...
@@ -59,7 +59,8 @@ export function isRouteServerIsland(route: RouteData): boolean { */ export function isRequestServerIsland(request: Request, base = ''): boolean { const url = new URL(request.url); - const pathname = url.pathname.slice(base.length); + const pathname = + base == '/' ? url.pathname.slice(base.lengt...
packages/astro/src/core/routing/match.ts
26
TypeScript
0.5
question
128
51
51
false
fix(i18n): bypass server island with base
13,205
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import { z } from 'zod'; export const resolveFontOptionsSchema = z.object({ weights: z.array(z.string()).nonempty(), styles: z.array(z.enum(['normal', 'italic', 'oblique'])).nonempty(), subsets: z.array(z.string()).nonempty(), fallbacks: z.array(z.string()).nonempty().optional(), });
Does zod catch duplicates? e.g. `styles: ['normal', 'normal', 'normal']`
import { z } from 'zod'; function dedupe<T>(arr: Array<T>): Array<T> { return [...new Set(arr)]; } export const resolveFontOptionsSchema = z.object({ weights: z .array(z.string()) .nonempty() .transform((arr) => dedupe(arr)), styles: z .array(z.enum(['normal', 'italic', 'oblique'])) .nonempty() .transf...
@@ -0,0 +1,8 @@ +import { z } from 'zod'; + +export const resolveFontOptionsSchema = z.object({ + weights: z.array(z.string()).nonempty(), + styles: z.array(z.enum(['normal', 'italic', 'oblique'])).nonempty(),
packages/astro/src/assets/fonts/config.ts
5
TypeScript
0.357
refactor
72
9
26
false
feat(fonts): local provider
13,209
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
if (payload instanceof URL) { newUrl = payload; } else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); if (b...
use `prependForwardSlash`, available from the same package that provides `appendForwardSlash`
let newUrl: URL | undefined = undefined; if (payload instanceof URL) { newUrl = payload; } else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; const shouldAppendSlash = shouldAppendForward...
@@ -45,15 +45,31 @@ export function findRouteToRewrite({ } else { newUrl = new URL(payload, new URL(request.url).origin); } + let pathname = newUrl.pathname; + + const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); + if (base !== '/' && newUrl.pathname.startsWith(base)) { - pathna...
packages/astro/src/core/routing/rewrite.ts
26
TypeScript
0.429
suggestion
94
51
51
false
FIX: Ensures that rewrite url contains base path
13,233
withastro/astro
47,179
TypeScript
ematipico
joshmkennedy
newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); if (base !== '/' && newUrl.pathname.startsWith(base)) { pathname = shouldAppendSlash ? append...
I am not really sure what we're going here, can you explain please?
} else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); if (base !== '/' && newUrl.pathname.startsWith(base)) { ...
@@ -45,15 +45,31 @@ export function findRouteToRewrite({ } else { newUrl = new URL(payload, new URL(request.url).origin); } + let pathname = newUrl.pathname; + + const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); + if (base !== '/' && newUrl.pathname.startsWith(base)) { - pathna...
packages/astro/src/core/routing/rewrite.ts
26
TypeScript
0.214
question
67
51
51
false
FIX: Ensures that rewrite url contains base path
13,233
withastro/astro
47,179
TypeScript
ematipico
joshmkennedy
if (payload instanceof URL) { newUrl = payload; } else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); if (b...
I believe all of this can be fixed by using `joinPaths`, available from `from '../path.js'`
let newUrl: URL | undefined = undefined; if (payload instanceof URL) { newUrl = payload; } else if (payload instanceof Request) { newUrl = new URL(payload.url); } else { newUrl = new URL(payload, new URL(request.url).origin); } let pathname = newUrl.pathname; const shouldAppendSlash = shouldAppendForward...
@@ -45,15 +45,31 @@ export function findRouteToRewrite({ } else { newUrl = new URL(payload, new URL(request.url).origin); } + let pathname = newUrl.pathname; + + const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); + if (base !== '/' && newUrl.pathname.startsWith(base)) { - pathna...
packages/astro/src/core/routing/rewrite.ts
26
TypeScript
0.357
suggestion
91
51
51
false
FIX: Ensures that rewrite url contains base path
13,233
withastro/astro
47,179
TypeScript
ematipico
joshmkennedy
message: 'Action called from a server page or endpoint without using `Astro.callAction()`. This wrapper must be used to call actions from server code.', hint: 'See the `Astro.callAction()` reference for usage examples: https://docs.astro.build/en/reference/api-reference/#callaction', } satisfies ErrorData; // Gene...
```suggestion hint: Ensure your adapter supports `buildOutput: "server"`: https://docs.astro.build/en/reference/adapter-reference/#building-an-adapter', ``` Maybe this?
message: 'Action called from a server page or endpoint without using `Astro.callAction()`. This wrapper must be used to call actions from server code.', hint: 'See the `Astro.callAction()` reference for usage examples: https://docs.astro.build/en/reference/api-reference/#callaction', } satisfies ErrorData; // Gene...
@@ -1815,16 +1815,15 @@ export const UnknownError = { name: 'UnknownError', title: 'Unknown Error.' } sa /** * @docs * @see - * - [On-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/) + * - [Server output adapter feature](https://docs.astro.build/en/reference/adapter-reference/#building-an...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.714
question
172
51
51
false
chore: reword error message
13,240
withastro/astro
47,179
TypeScript
sarah11918
ematipico
* @description * Action called from a server page or endpoint without using `Astro.callAction()`. */ export const ActionCalledFromServerError = { name: 'ActionCalledFromServerError', title: 'Action unexpected called from the server.', message: 'Action called from a server page or endpoint without using `Astro.c...
```suggestion * Your adapter must support server output to use sessions. ```
* @description * Action called from a server page or endpoint without using `Astro.callAction()`. */ export const ActionCalledFromServerError = { name: 'ActionCalledFromServerError', title: 'Action unexpected called from the server.', message: 'Action called from a server page or endpoint without using `Astro.c...
@@ -1815,16 +1815,15 @@ export const UnknownError = { name: 'UnknownError', title: 'Unknown Error.' } sa /** * @docs * @see - * - [On-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/) + * - [Server output adapter feature](https://docs.astro.build/en/reference/adapter-reference/#building-an...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.643
suggestion
79
51
51
false
chore: reword error message
13,240
withastro/astro
47,179
TypeScript
sarah11918
ematipico
import { actions, isInputError } from 'astro:actions'; import { useState } from 'react'; import {createLoggerFromFlags} from "../../../../../src/cli/flags.ts"; export function PostComment({ postId, serverBodyError, }: { postId: string; serverBodyError?: string; }) { const [comments, setComments] = useState<{ auth...
Just noting that if this is required, it's a user-side bug. Understand if this is just a debug in-progress
import { actions, isInputError } from 'astro:actions'; import { useState } from 'react'; import {createLoggerFromFlags} from "../../../../../src/cli/flags.ts"; export function PostComment({ postId, serverBodyError, }: { postId: string; serverBodyError?: string; }) { const [comments, setComments] = useState<{ auth...
@@ -17,7 +18,7 @@ export function PostComment({ <form method="POST" data-testid="client" - action={actions.blog.comment} + action={actions.blog.comment.toString()}
packages/astro/e2e/fixtures/actions-blog/src/components/PostComment.tsx
21
TypeScript
0.571
bug
106
46
46
false
refactor(core): move actions inside core
13,262
withastro/astro
47,179
TypeScript
bholmesdev
ematipico
this.request = payload; } else { this.request = copyRequest( newUrl, this.request, // need to send the flag of the previous routeData routeData.prerender, this.pipeline.logger, this.routeData.route, ); } this.isRewriting = true; this.url = new URL(this....
Nice, this looks like the fix we needed. And I'll add some context from @JacobNWolf 's issue to make sure we test it: Actions were being bundled into edge middleware, when they should only be bundled into your server runtime. It looks like this moves the _functionality_ into the server runtime, but I wanna make sure...
} this.routeData = routeData; componentInstance = newComponent; if (payload instanceof Request) { this.request = payload; } else { this.request = copyRequest( newUrl, this.request, // need to send the flag of the previous routeData routeData.prerender, this.p...
@@ -192,6 +194,15 @@ export class RenderContext { } let response: Response; + if (!ctx.isPrerendered) {
packages/astro/src/core/render-context.ts
26
TypeScript
0.5
suggestion
435
51
51
false
refactor(core): move actions inside core
13,262
withastro/astro
47,179
TypeScript
bholmesdev
ematipico
import type { ModuleLoader } from '../core/module-loader/index.js'; import { ASTRO_ACTIONS_INTERNAL_MODULE_ID } from './consts.js'; import type { SSRActions } from '../core/app/types.js'; /** * It accepts a module loader and the astro settings, and it attempts to load the middlewares defined in the configuration. * ...
should this be addressed in this PR?
import type {ModuleLoader} from "../core/module-loader/index.js"; import {ASTRO_ACTIONS_INTERNAL_MODULE_ID} from "./consts.js"; import type {SSRActions} from "../core/app/types.js"; import {ActionsCantBeLoaded} from "../core/errors/errors-data.js"; import {AstroError} from "../core/errors/index.js"; /** * It accepts ...
@@ -0,0 +1,18 @@ +import type { ModuleLoader } from '../core/module-loader/index.js'; +import { ASTRO_ACTIONS_INTERNAL_MODULE_ID } from './consts.js'; +import type { SSRActions } from '../core/app/types.js'; + +/** + * It accepts a module loader and the astro settings, and it attempts to load the middlewares defined in...
packages/astro/src/actions/loadActions.ts
14
TypeScript
0.143
question
36
19
21
false
refactor(core): move actions inside core
13,262
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
import type { Plugin } from 'vite'; import type { AstroSettings } from '../../types/astro.js'; import { resolveProviders, type ResolveMod } from './providers/utils.js'; import * as unifont from 'unifont'; import type { FontFamily, FontProvider, FontType } from './types.js'; import xxhash from 'xxhash-wasm'; import { ex...
Have a look to this file, there are some linting diagnostics that should be addressed
import type { Plugin } from 'vite'; import type { AstroSettings } from '../../types/astro.js'; import { resolveProviders, type ResolveMod } from './providers/utils.js'; import * as unifont from 'unifont'; import type { FontFamily, FontProvider, FontType } from './types.js'; import xxhash from 'xxhash-wasm'; import { ex...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
1
TypeScript
0.286
suggestion
86
26
26
false
feat(fonts): improve cache
13,273
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
export function isFontType(str: string): str is FontType { return (FONT_TYPES as Readonly<Array<string>>).includes(str); } export function createCache(storage: Storage) { return async function cache( key: string, cb: () => Promise<Buffer>, ): Promise<{ cached: boolean; data: Buffer }> { const existing = awai...
Maybe an example can help this. I read it, and I'm not sure what's an URL that we can control. Also, you mention the URL but the return type is a string. Which one is correct? If it's really an URL, shouldn't we use the `URL` type? Can we also document what the collect function is supposed to do?
export function isFontType(str: string): str is FontType { return (FONT_TYPES as Readonly<Array<string>>).includes(str); } export function createCache(storage: Storage) { return async function cache( key: string, cb: () => Promise<Buffer>, ): Promise<{ cached: boolean; data: Buffer }> { const existing = awai...
@@ -72,4 +72,31 @@ export function createCache(storage: Storage) { }; } -export type CacheHandler = ReturnType<typeof createCache>; \ No newline at end of file +export type CacheHandler = ReturnType<typeof createCache>; + +/** + * The fonts data we receive contains urls or file paths we do no control. + * However,...
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.786
question
299
49
51
false
refactor(fonts): url proxy
13,274
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
} const hash = req.url.slice(1); const url = hashToUrlMap?.get(hash); if (!url) { return next(); } logManager.add(hash); // Cache should be defined at this point since initialize it called before registering // the middleware. hashToUrlMap is defined at the same time so if it's not ...
Do you think this information should be part of the roadmap, and eventually documented? I believe users might expect fonts to be browser-cached, or they would expect production to behave like dev.
const logManager = createLogManager(logger); // Base is taken into account by default. The prefix contains a traling slash, // so it matches correctly any hash, eg. /_astro/fonts/abc.woff => abc.woff server.middlewares.use(URL_PREFIX, async (req, res, next) => { if (!req.url) { return next(); }...
@@ -272,16 +278,14 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { const { cached, data } = await cache!(hash, () => fetchFont(url)); logManager.remove(hash, cached); - // TODO: add cache control back - // TODO: set content type and cache control manually - // const ke...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.429
performance
197
51
51
false
feat(fonts): dev headers
13,275
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
for (const src of family.src) { for (const weight of src.weights ?? DEFAULTS.weights) { for (const style of src.styles ?? DEFAULTS.styles) { // TODO: handle fallbacks? // TODO: handle subset fonts.push({ weight, style, src: src.paths.map((path) => ({ url: proxyURL(fileURLToPath(n...
If this function can be null, then have the `constructor` accept the `update` callback. Doing `const a = new AClass(); a.update() = something` isn't a good pattern, because it relies on the caller to **mutate** internal functions of the class. Same for `getPaths`.
for (const src of family.src) { for (const weight of src.weights ?? DEFAULTS.weights) { for (const style of src.styles ?? DEFAULTS.styles) { // TODO: handle fallbacks? // TODO: handle subset fonts.push({ weight, style, src: src.paths.map((path) => ({ url: proxyURL(fileURLToPath(n...
@@ -14,43 +14,58 @@ type InitializedProvider = NonNullable<Awaited<ReturnType<unifont.Provider>>>; type ResolveFontResult = NonNullable<Awaited<ReturnType<InitializedProvider['resolveFont']>>>; -interface Options { +interface ResolveOptions { root: URL; + proxyURL: (value: string) => string; } -interface Reso...
packages/astro/src/assets/fonts/providers/local.ts
26
TypeScript
0.786
suggestion
269
46
51
false
feat(fonts): better local provider
13,276
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
await storage.setItemRaw(key, data); return { cached: false, data }; }; } export type CacheHandler = ReturnType<typeof createCache>; export interface ProxyURLOptions { hashString: (value: string) => string; collect: (data: { hash: string; type: FontType; value: string; }) => string; } /** * The fonts ...
nit: Options are usually optional, which isn't the case. Also, please start documenting stuff because it's getting very difficult to understand the flow of the code. For example: - the documentation of this method should be updated because `hashString` and `collect` aren't passed directly anymore, but they are part...
await storage.setItemRaw(key, data); return { cached: false, data }; }; } export type CacheHandler = ReturnType<typeof createCache>; export interface ProxyURLOptions { /** * The original URL */ value: string; /** * Specifies how the hash is computed. Can be based on the value, * a specific string for ...
@@ -83,24 +92,10 @@ export type CacheHandler = ReturnType<typeof createCache>; * - `collect` will save the association of the original url and the new hash for later use * - the returned url will be `/_astro/fonts/<hash>.woff2` */ -export function createURLProxy({ - hashString, - collect, -}: { - hashString: (val...
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.643
suggestion
403
33
45
false
feat(fonts): better local provider
13,276
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
for (const src of family.src) { for (const weight of src.weights ?? DEFAULTS.weights) { for (const style of src.styles ?? DEFAULTS.styles) { // TODO: handle fallbacks? // TODO: handle subset fonts.push({ weight, style, src: src.paths.map((path) => ({ url: proxyURL(fileURLToPath(ne...
Please document the methods and the class. It will help other developers to maintain new code.
for (const src of family.src) { for (const weight of src.weights ?? DEFAULTS.weights) { for (const style of src.styles ?? DEFAULTS.styles) { // TODO: handle fallbacks? // TODO: handle subset fonts.push({ weight, style, src: src.paths.map((path) => ({ url: proxyURL(fileURLToPath(ne...
@@ -14,43 +14,58 @@ type InitializedProvider = NonNullable<Awaited<ReturnType<unifont.Provider>>>; type ResolveFontResult = NonNullable<Awaited<ReturnType<InitializedProvider['resolveFont']>>>; -interface Options { +interface ResolveOptions { root: URL; + proxyURL: (value: string) => string; } -interface Reso...
packages/astro/src/assets/fonts/providers/local.ts
26
TypeScript
0.214
suggestion
95
45
51
false
feat(fonts): better local provider
13,276
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
async buildStart() { if (isBuild) { await initialize({ resolveMod: (id) => import(id), base: new URL(CACHE_DIR, settings.config.cacheDir), }); } }, async configureServer(server) { const localFontsWatcher = new LocalFontsWatcher(); localFontsWatcher.update = () => { logger.info('a...
Shouldn't we purge fonts when they are deleted too?
logger.info('assets', 'Fonts initialized'); } return { name: 'astro:fonts', config(_, { command }) { isBuild = command === 'build'; }, async buildStart() { if (isBuild) { await initialize({ resolveMod: (id) => import(id), base: new URL(CACHE_DIR, settings.config.cacheDir), }); } ...
@@ -250,14 +261,28 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { if (isBuild) { await initialize({ resolveMod: (id) => import(id), + base: new URL(CACHE_DIR, settings.config.cacheDir), }); } }, async configureServer(server) { + const localFontsWatcher ...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.286
question
52
51
51
false
feat(fonts): better local provider
13,276
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
isBuild = command === 'build'; }, async buildStart() { if (isBuild) { await initialize({ resolveMod: (id) => import(id), base: new URL(CACHE_DIR, settings.config.cacheDir), }); } }, async configureServer(server) { const localFontsWatcher = new LocalFontsWatcher(); localFontsWatc...
I am not sure I understand this part of the code. Here's some questions: - does `hashToUrlMap` change during the life cycle of the dev server? - why do we filter them? shouldn't they be already correct?
resolvedMap.set(family.name, { preloadData: [...preloadData], css }); } logger.info('assets', 'Fonts initialized'); } return { name: 'astro:fonts', config(_, { command }) { isBuild = command === 'build'; }, async buildStart() { if (isBuild) { await initialize({ resolveMod: (id) => impor...
@@ -250,14 +261,28 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { if (isBuild) { await initialize({ resolveMod: (id) => import(id), + base: new URL(CACHE_DIR, settings.config.cacheDir), }); } }, async configureServer(server) { + const localFontsWatcher ...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.643
question
207
51
51
false
feat(fonts): better local provider
13,276
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
await storage.setItemRaw(key, data); return { cached: false, data }; }; } export type CacheHandler = ReturnType<typeof createCache>; export interface ProxyURLOptions { hashString: (value: string) => string; collect: (data: { hash: string; type: FontType; value: string; }) => string; } /** * The fonts ...
Also, why do we pass a string and an object? Wouldn't be easier to just pass everything inside the object? Sorry, they might be silly questions, but it seems that the complexity of the code increasing without reasons
await storage.setItemRaw(key, data); return { cached: false, data }; }; } export type CacheHandler = ReturnType<typeof createCache>; export interface ProxyURLOptions { /** * The original URL */ value: string; /** * Specifies how the hash is computed. Can be based on the value, * a specific string for ...
@@ -83,24 +92,10 @@ export type CacheHandler = ReturnType<typeof createCache>; * - `collect` will save the association of the original url and the new hash for later use * - the returned url will be `/_astro/fonts/<hash>.woff2` */ -export function createURLProxy({ - hashString, - collect, -}: { - hashString: (val...
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.429
performance
217
33
45
false
feat(fonts): better local provider
13,276
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
* Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. */ headers?: OutgoingHttpHeaders; /** * @name server.open * @type {string | boolean} * @default `false` * @version 4.1.0 * @description * Controls whether the dev server should open in your browser window on startup. ...
Wouldn't the default be [an empty array](https://github.com/withastro/astro/blob/84d8fcf5df348bf988fdc6da09de141f88568534/packages/astro/src/core/config/schema.ts#L80) instead? ```suggestion * @default `[]` ```
* @description * * A list of hostnames that Astro is allowed to respond to. When the value is set to `true`, any * hostname is allowed. * * ```js * { * server: { * allowedHosts: ['staging.example.com', 'qa.example.com'] * } * } * ``` */ allowedHosts?: string[] | true; /** * @name ...
@@ -95,6 +95,26 @@ export type ServerConfig = { * ``` */ open?: string | boolean; + + /** + * @name server.allowedHosts + * @type {string[] | true} + * @default `false`
packages/astro/src/types/public/config.ts
26
TypeScript
0.857
suggestion
215
51
51
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
ArmandPhilippot
ematipico
* { * server: { open: "/about" } * } * ``` */ open?: string | boolean; /** * @name server.allowedHosts * @type {string[] | true} * @default `false` * @version 5.4.0 * @description * * A list of hostnames that Astro is allowed to respond to. When the value is set to `true`, any * hostnam...
Shouldn't we use `true` here instead of `boolean`? Since the type is `z.literal(true)`, when using `false`, Typescript will throw an error, right? ```suggestion allowedHosts?: string[] | true; ``` Also, it seems we use `false` instead of `boolean` for `markdown.syntaxHighlight` which uses `z.literal(false)`. So it...
/** * @name server.headers * @typeraw {OutgoingHttpHeaders} * @default `{}` * @version 1.7.0 * @description * Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. */ headers?: OutgoingHttpHeaders; /** * @name server.open * @type {string | boolean} * @default `false` ...
@@ -95,6 +95,26 @@ export type ServerConfig = { * ``` */ open?: string | boolean; + + /** + * @name server.allowedHosts + * @type {string[] | true} + * @default `false` + * @version 5.4.0 + * @description + * + * A list of hostnames that Astro is allowed to respond to. When the value is set to `true`, a...
packages/astro/src/types/public/config.ts
26
TypeScript
1
suggestion
341
51
51
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
ArmandPhilippot
ematipico
import { cyan } from 'kleur/colors'; import devServer from '../../core/dev/index.js'; import { printHelp } from '../../core/messages.js'; import { type Flags, flagsToAstroInlineConfig } from '../flags.js'; interface DevOptions { flags: Flags; } export async function dev({ flags }: DevOptions) { if (flags.help || fl...
Should we precise that `true` is also a valid value? I know, it might be difficult to keep it brief if we add this information... Maybe something like: ```suggestion ['--allowed-hosts', 'Specify a comma-separated list of allowed hosts or allow any hostname.'], ```
import { cyan } from 'kleur/colors'; import devServer from '../../core/dev/index.js'; import { printHelp } from '../../core/messages.js'; import { type Flags, flagsToAstroInlineConfig } from '../flags.js'; interface DevOptions { flags: Flags; } export async function dev({ flags }: DevOptions) { if (flags.help || fl...
@@ -20,6 +20,7 @@ export async function dev({ flags }: DevOptions) { ['--host <custom-address>', `Expose on a network IP address at <custom-address>`], ['--open', 'Automatically open the app in the browser on server start'], ['--force', 'Clear the content layer cache, forcing a full rebuild.'], + ...
packages/astro/src/cli/dev/index.ts
23
TypeScript
0.857
question
272
38
38
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
ArmandPhilippot
ematipico
import { cyan } from 'kleur/colors'; import { printHelp } from '../../core/messages.js'; import previewServer from '../../core/preview/index.js'; import { type Flags, flagsToAstroInlineConfig } from '../flags.js'; interface PreviewOptions { flags: Flags; } export async function preview({ flags }: PreviewOptions) { ...
Same as above for the `dev` command: ```suggestion ['--allowed-hosts', 'Specify a comma-separated list of allowed hosts or allow any hostname.'], ```
import { cyan } from 'kleur/colors'; import { printHelp } from '../../core/messages.js'; import previewServer from '../../core/preview/index.js'; import { type Flags, flagsToAstroInlineConfig } from '../flags.js'; interface PreviewOptions { flags: Flags; } export async function preview({ flags }: PreviewOptions) { ...
@@ -18,6 +18,7 @@ export async function preview({ flags }: PreviewOptions) { ['--host', `Listen on all addresses, including LAN and public addresses.`], ['--host <custom-address>', `Expose on a network IP address at <custom-address>`], ['--open', 'Automatically open the app in the browser on server st...
packages/astro/src/cli/preview/index.ts
21
TypeScript
0.714
suggestion
157
36
36
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
ArmandPhilippot
ematipico
* @description * Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. */ headers?: OutgoingHttpHeaders; /** * @name server.open * @type {string | boolean} * @default `false` * @version 4.1.0 * @description * Controls whether the dev server should open in your browser wind...
Is true a type? I think the type is `boolean`.
* @version 5.4.0 * @description * * A list of hostnames that Astro is allowed to respond to. When the value is set to `true`, any * hostname is allowed. * * ```js * { * server: { * allowedHosts: ['staging.example.com', 'qa.example.com'] * } * } * ``` */ allowedHosts?: string[] | tru...
@@ -95,6 +95,26 @@ export type ServerConfig = { * ``` */ open?: string | boolean; + + /** + * @name server.allowedHosts + * @type {string[] | true}
packages/astro/src/types/public/config.ts
26
TypeScript
0.357
suggestion
46
51
51
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
Eveeifyeve
ematipico
/** * @name server.open * @type {string | boolean} * @default `false` * @version 4.1.0 * @description * Controls whether the dev server should open in your browser window on startup. * * Pass a full URL string (e.g. "http://example.com") or a pathname (e.g. "/about") to specify the URL to open. * *...
Description looks great! I noticed that Vite's documentation includes multiple warnings (which hosts can I trust? using `true` is dangerous and we suggest you don't do it...) Do we feel the need for any of that here? Otherwise assuming it renders fine in preview, looks good to me!
* * ```js * { * server: { * allowedHosts: ['staging.example.com', 'qa.example.com'] * } * } * ``` */ allowedHosts?: string[] | true; /** * @name server.headers * @typeraw {OutgoingHttpHeaders} * @default `{}` * @version 1.7.0 * @description * Set custom HTTP response headers to ...
@@ -95,6 +95,26 @@ export type ServerConfig = { * ``` */ open?: string | boolean; + + /** + * @name server.allowedHosts + * @type {string[] | true} + * @default `[]` + * @version 5.4.0 + * @description + * + * A list of hostnames that Astro is allowed to respond to. When the value is set to `true`, any
packages/astro/src/types/public/config.ts
26
TypeScript
0.571
suggestion
287
51
51
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
sarah11918
ematipico
* @default `{}` * @version 1.7.0 * @description * Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. */ headers?: OutgoingHttpHeaders; /** * @name server.open * @type {string | boolean} * @default `false` * @version 4.1.0 * @description * Controls whether the dev se...
The entry itself looks good, but we don't *have* to just add it at the end of existing ones. Since there are already entries for (in this order): - `server.host` - `server.port` - `server.open` Where does this make the most *sense* for placement? Should it maybe come after `server.host`? (It definitely feels...
* @type {string[] | true} * @default `[]` * @version 5.4.0 * @description * * A list of hostnames that Astro is allowed to respond to. When the value is set to `true`, any * hostname is allowed. * * ```js * { * server: { * allowedHosts: ['staging.example.com', 'qa.example.com'] * } *...
@@ -95,6 +95,26 @@ export type ServerConfig = { * ``` */ open?: string | boolean; + + /**
packages/astro/src/types/public/config.ts
26
TypeScript
0.643
suggestion
376
51
51
false
feat: add new `allowedHosts` option
13,278
withastro/astro
47,179
TypeScript
sarah11918
ematipico
import { removePosition } from 'unist-util-remove-position'; import { visitParents } from 'unist-util-visit-parents'; type Highlighter = ( code: string, language: string, options?: { meta?: string }, ) => Promise<Root | string>; const languagePattern = /\blanguage-(\S+)\b/; // Don’t highlight math code blocks by d...
Why do we pass a third argument as an object instead of a plain `excludeLanguages`? What does the new argument represent? Options or something?
import { removePosition } from 'unist-util-remove-position'; import { visitParents } from 'unist-util-visit-parents'; type Highlighter = ( code: string, language: string, options?: { meta?: string }, ) => Promise<Root | string>; const languagePattern = /\blanguage-(\S+)\b/; // Don’t highlight math code blocks by d...
@@ -21,7 +23,11 @@ const languagePattern = /\blanguage-(\S+)\b/; * A function which receives the code and language, and returns the HTML of a syntax * highlighted `<pre>` element. */ -export async function highlightCodeBlocks(tree: Root, highlighter: Highlighter) { +export async function highlightCodeBlocks( ...
packages/markdown/remark/src/highlight.ts
26
TypeScript
0.571
question
144
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
ematipico
chrisirhc
} // Where the `<code>` is the only child. if (parent.children.length !== 1) { return; } // And the `<code>` has a class name that starts with `language-`. let languageMatch: RegExpMatchArray | null | undefined; let { className } = node.properties; if (typeof className === 'string') { languageMa...
The code will hit a false positive if a user provides a value such as `excludeLanguages: ['']`. Can we make the check a bit stronger?
} // Where the `<code>` is the only child. if (parent.children.length !== 1) { return; } // And the `<code>` has a class name that starts with `language-`. let languageMatch: RegExpMatchArray | null | undefined; let { className } = node.properties; if (typeof className === 'string') { languageMa...
@@ -61,8 +67,7 @@ export async function highlightCodeBlocks(tree: Root, highlighter: Highlighter) } } - // Don’t mighlight math code blocks. - if (languageMatch?.[1] === 'math') { + if (excludeLanguages.includes(languageMatch?.[1] ?? '')) {
packages/markdown/remark/src/highlight.ts
26
TypeScript
0.571
question
134
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
ematipico
chrisirhc
export type RemarkPlugin<PluginParameters extends any[] = any[]> = unified.Plugin< PluginParameters, mdast.Root >; export type RemarkPlugins = (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[]; export type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugin< PluginParameters, hast...
I am a bit concerned about the placement of this new option. Shiki doesn't have a `excludeLangs` option, and `shikiConfig` is an object that **must match** the shiki config options. Wouldn't adding the option to `markdown` make more sense? Of course, we would need to change the logic of the `prism` syntax highlighte...
} } export type RemarkPlugin<PluginParameters extends any[] = any[]> = unified.Plugin< PluginParameters, mdast.Root >; export type RemarkPlugins = (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[]; export type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugin< PluginParameters, ...
@@ -37,7 +37,9 @@ export type ThemePresets = BuiltinTheme | 'css-variables'; export interface ShikiConfig extends Pick<CreateShikiHighlighterOptions, 'langs' | 'theme' | 'themes' | 'langAlias'>, - Pick<ShikiHighlighterHighlightOptions, 'defaultColor' | 'wrap' | 'transformers'> {} + Pick<ShikiHighlighterHighlight...
packages/markdown/remark/src/types.ts
26
TypeScript
0.643
suggestion
328
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
ematipico
chrisirhc
image: sanitizeConfigInfo( userConfig.image, Object.keys(AstroConfigSchema.shape.image._def.innerType.shape), ), markdown: sanitizeConfigInfo( userConfig.markdown, Object.keys(AstroConfigSchema.shape.markdown._def.innerType.shape), ), experimental: sanitizeConfigInfo( userConfig.experimental, ...
This only measures for the syntax highlight type. Is that ok?
image: sanitizeConfigInfo( userConfig.image, Object.keys(AstroConfigSchema.shape.image._def.innerType.shape), ), markdown: sanitizeConfigInfo( userConfig.markdown, Object.keys(AstroConfigSchema.shape.markdown._def.innerType.shape), ), experimental: sanitizeConfigInfo( userConfig.experimental, ...
@@ -107,7 +107,11 @@ function createAnonymousConfigInfo(userConfig: AstroUserConfig) { }; // Measure string literal/enum configuration values configInfo.build.format = measureStringLiteral(userConfig.build?.format); - configInfo.markdown.syntaxHighlight = measureStringLiteral(userConfig.markdown?.syntaxHighlight)...
packages/astro/src/events/session.ts
26
TypeScript
0.357
question
61
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
chrisirhc
chrisirhc