feat: use typescript-eslint@v6's reworked configs (#7425)
This commit is contained in:
parent
fc6826ff76
commit
2fea174303
154 changed files with 321 additions and 462 deletions
|
@ -1,4 +1,5 @@
|
|||
**/*.d.ts
|
||||
packages/**/*.min.js
|
||||
packages/**/dist/**/*
|
||||
packages/**/fixtures/**/*
|
||||
packages/webapi/**/*
|
||||
|
|
|
@ -1,23 +1,53 @@
|
|||
module.exports = {
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended-type-checked',
|
||||
'plugin:@typescript-eslint/stylistic-type-checked',
|
||||
'prettier',
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
extends: ['plugin:@typescript-eslint/recommended', 'prettier'],
|
||||
parserOptions: {
|
||||
project: ['./packages/*/tsconfig.json', './tsconfig.eslint.json'],
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
plugins: ['@typescript-eslint', 'prettier', 'no-only-tests'],
|
||||
rules: {
|
||||
'@typescript-eslint/ban-ts-comment': 'off',
|
||||
'@typescript-eslint/camelcase': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-empty-function': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-non-null-assertion': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
'@typescript-eslint/no-use-before-define': 'off',
|
||||
'@typescript-eslint/no-var-requires': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'no-console': 'warn',
|
||||
'prefer-const': 'off',
|
||||
'no-shadow': 'off',
|
||||
'@typescript-eslint/no-shadow': ['error'],
|
||||
// These off/configured-differently-by-default rules fit well for us
|
||||
'@typescript-eslint/array-type': ['error', { default: 'array-simple' }],
|
||||
'@typescript-eslint/no-unused-vars': ['error', { ignoreRestSiblings: true }],
|
||||
'no-only-tests/no-only-tests': 'error',
|
||||
'@typescript-eslint/no-shadow': ['error'],
|
||||
'no-console': 'warn',
|
||||
|
||||
// Todo: do we want these?
|
||||
'@typescript-eslint/array-type': 'off',
|
||||
'@typescript-eslint/ban-ts-comment': 'off',
|
||||
'@typescript-eslint/class-literal-property-style': 'off',
|
||||
'@typescript-eslint/consistent-indexed-object-style': 'off',
|
||||
'@typescript-eslint/consistent-type-definitions': 'off',
|
||||
'@typescript-eslint/dot-notation': 'off',
|
||||
'@typescript-eslint/no-base-to-string': 'off',
|
||||
'@typescript-eslint/no-confusing-void-expression': 'off',
|
||||
'@typescript-eslint/no-empty-function': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'off',
|
||||
'@typescript-eslint/no-misused-promises': 'off',
|
||||
'@typescript-eslint/no-redundant-type-constituents': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||
'@typescript-eslint/no-unsafe-call': 'off',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||
'@typescript-eslint/no-unsafe-return': 'off',
|
||||
'@typescript-eslint/prefer-nullish-coalescing': 'off',
|
||||
'@typescript-eslint/prefer-string-starts-ends-with': 'off',
|
||||
'@typescript-eslint/require-await': 'off',
|
||||
'@typescript-eslint/restrict-plus-operands': 'off',
|
||||
'@typescript-eslint/restrict-template-expressions': 'off',
|
||||
'@typescript-eslint/sort-type-constituents': 'off',
|
||||
'@typescript-eslint/unbound-method': 'off',
|
||||
|
||||
// These rules enabled by the preset configs don't work well for us
|
||||
'@typescript-eslint/await-thenable': 'off',
|
||||
'prefer-const': 'off',
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
|
@ -41,6 +71,7 @@ module.exports = {
|
|||
{
|
||||
files: ['benchmark/**/*.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
'no-console': 'off',
|
||||
},
|
||||
},
|
||||
|
|
5
.github/workflows/ci.yml
vendored
5
.github/workflows/ci.yml
vendored
|
@ -32,7 +32,7 @@ env:
|
|||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
timeout-minutes: 3
|
||||
timeout-minutes: 5
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
|
@ -50,6 +50,9 @@ jobs:
|
|||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build (ignoring failures)
|
||||
run: pnpm run build || true
|
||||
|
||||
# Lint autofix cannot run on forks, so just skip those! See https://github.com/wearerequired/lint-action/issues/13
|
||||
- name: Lint (External)
|
||||
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.owner.login != github.repository_owner }}
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
"test:e2e": "cd packages/astro && pnpm playwright install && pnpm run test:e2e",
|
||||
"test:e2e:match": "cd packages/astro && pnpm playwright install && pnpm run test:e2e:match",
|
||||
"benchmark": "astro-benchmark",
|
||||
"lint": "eslint --cache .",
|
||||
"lint": "eslint . --report-unused-disable-directives",
|
||||
"version": "changeset version && node ./scripts/deps/update-example-versions.js && pnpm install --no-frozen-lockfile && pnpm run format",
|
||||
"preinstall": "npx only-allow pnpm"
|
||||
},
|
||||
|
@ -78,8 +78,8 @@
|
|||
"@changesets/changelog-github": "^0.4.8",
|
||||
"@changesets/cli": "^2.26.1",
|
||||
"@types/node": "^18.16.18",
|
||||
"@typescript-eslint/eslint-plugin": "^5.60.0",
|
||||
"@typescript-eslint/parser": "^5.60.0",
|
||||
"@typescript-eslint/eslint-plugin": "6.0.0-alpha.158",
|
||||
"@typescript-eslint/parser": "6.0.0-alpha.158",
|
||||
"esbuild": "^0.17.19",
|
||||
"eslint": "^8.43.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
#!/usr/bin/env node
|
||||
/* eslint-disable no-console */
|
||||
'use strict';
|
||||
|
||||
// ISOMORPHIC FILE: NO TOP-LEVEL IMPORT/REQUIRE() ALLOWED
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { expect } from '@playwright/test';
|
||||
import { getColor, isWindows, testFactory } from './test-utils.js';
|
||||
import { isWindows, testFactory } from './test-utils.js';
|
||||
|
||||
const test = testFactory({
|
||||
root: './fixtures/css/',
|
||||
|
|
|
@ -19,8 +19,6 @@ test.describe('Hydration race', () => {
|
|||
test('Islands inside of slots hydrate', async ({ page, astro }) => {
|
||||
await page.goto(astro.resolveUrl('/slot'));
|
||||
|
||||
const html = await page.content();
|
||||
|
||||
const one = page.locator('#one');
|
||||
await expect(one, 'updated text').toHaveText('Hello One in the client');
|
||||
|
||||
|
|
|
@ -18,8 +18,7 @@ for (let i = 0; i < testFiles.length; i++) {
|
|||
}
|
||||
|
||||
export function loadFixture(inlineConfig) {
|
||||
if (!inlineConfig || !inlineConfig.root)
|
||||
throw new Error("Must provide { root: './fixtures/...' }");
|
||||
if (!inlineConfig?.root) throw new Error("Must provide { root: './fixtures/...' }");
|
||||
|
||||
// resolve the relative root (i.e. "./fixtures/tailwindcss") to a full filepath
|
||||
// without this, the main `loadFixture` helper will resolve relative to `packages/astro/test`
|
||||
|
|
|
@ -35,7 +35,7 @@ export const get: APIRoute = async ({ request }) => {
|
|||
const url = new URL(request.url);
|
||||
const transform = await imageService.parseURL(url, imageServiceConfig);
|
||||
|
||||
if (!transform || !transform.src) {
|
||||
if (!transform?.src) {
|
||||
throw new Error('Incorrect transform returned by `parseURL`');
|
||||
}
|
||||
|
||||
|
|
|
@ -36,7 +36,7 @@ const service: LocalImageService = {
|
|||
async transform(inputBuffer, transformOptions) {
|
||||
const transform: BaseServiceTransform = transformOptions as BaseServiceTransform;
|
||||
|
||||
let format = transform.format!;
|
||||
let format = transform.format;
|
||||
|
||||
const operations: Operation[] = [];
|
||||
|
||||
|
|
|
@ -291,7 +291,6 @@ export const codecs = {
|
|||
avif: {
|
||||
name: 'AVIF',
|
||||
extension: 'avif',
|
||||
// eslint-disable-next-line no-control-regex
|
||||
detectors: [/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/],
|
||||
dec: () =>
|
||||
instantiateEmscriptenWasm(avifDec as DecodeModuleFactory, avifDecWasm),
|
||||
|
@ -322,7 +321,6 @@ export const codecs = {
|
|||
oxipng: {
|
||||
name: 'OxiPNG',
|
||||
extension: 'png',
|
||||
// eslint-disable-next-line no-control-regex
|
||||
detectors: [/^\x89PNG\x0D\x0A\x1A\x0A/],
|
||||
dec: async () => {
|
||||
await pngEncDecInit()
|
||||
|
|
|
@ -29,14 +29,14 @@ export async function processBuffer(
|
|||
|
||||
switch (encoding) {
|
||||
case 'avif':
|
||||
return await impl.encodeAvif(imageData, { quality }) as Uint8Array;
|
||||
return await impl.encodeAvif(imageData, { quality });
|
||||
case 'jpeg':
|
||||
case 'jpg':
|
||||
return await impl.encodeJpeg(imageData, { quality }) as Uint8Array;
|
||||
return await impl.encodeJpeg(imageData, { quality });
|
||||
case 'png':
|
||||
return await impl.encodePng(imageData) as Uint8Array;
|
||||
return await impl.encodePng(imageData);
|
||||
case 'webp':
|
||||
return await impl.encodeWebp(imageData, { quality }) as Uint8Array;
|
||||
return await impl.encodeWebp(imageData, { quality });
|
||||
default:
|
||||
throw Error(`Unsupported encoding format`)
|
||||
}
|
||||
|
|
|
@ -49,7 +49,6 @@ export const JP2: IImage = {
|
|||
switch (nextBoxType) {
|
||||
case BoxTypes.rreq:
|
||||
// WHAT ARE THESE 4 BYTES?????
|
||||
// eslint-disable-next-line no-case-declarations
|
||||
const MAGIC = 4
|
||||
offset = offset + 4 + MAGIC + calculateRREQLength(buffer.slice(offset + 4))
|
||||
return parseIHDR(buffer.slice(offset + 8, offset + 24))
|
||||
|
|
|
@ -19,7 +19,7 @@ const handlers: { [type: string]: Handler} = {
|
|||
let dimensions: string[] = []
|
||||
|
||||
while (lines.length > 0) {
|
||||
const line = lines.shift() as string
|
||||
const line = lines.shift()!
|
||||
if (line[0] === '#') {
|
||||
continue
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ const handlers: { [type: string]: Handler} = {
|
|||
pam: (lines) => {
|
||||
const size: { [key: string]: number } = {}
|
||||
while (lines.length > 0) {
|
||||
const line = lines.shift() as string
|
||||
const line = lines.shift()!
|
||||
if (line.length > 16 || line.charCodeAt(0) > 128) {
|
||||
continue
|
||||
}
|
||||
|
|
|
@ -41,8 +41,8 @@ function parseLength(len: string) {
|
|||
function parseViewbox(viewbox: string): IAttributes {
|
||||
const bounds = viewbox.split(' ')
|
||||
return {
|
||||
height: parseLength(bounds[3]) as number,
|
||||
width: parseLength(bounds[2]) as number
|
||||
height: parseLength(bounds[3])!,
|
||||
width: parseLength(bounds[2])!
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -51,21 +51,21 @@ function parseAttributes(root: string): IAttributes {
|
|||
const height = root.match(extractorRegExps.height)
|
||||
const viewbox = root.match(extractorRegExps.viewbox)
|
||||
return {
|
||||
height: height && parseLength(height[2]) as number,
|
||||
viewbox: viewbox && parseViewbox(viewbox[2]) as IAttributes,
|
||||
width: width && parseLength(width[2]) as number,
|
||||
height: height && parseLength(height[2])!,
|
||||
viewbox: viewbox && parseViewbox(viewbox[2])!,
|
||||
width: width && parseLength(width[2])!,
|
||||
}
|
||||
}
|
||||
|
||||
function calculateByDimensions(attrs: IAttributes): ISize {
|
||||
return {
|
||||
height: attrs.height as number,
|
||||
width: attrs.width as number,
|
||||
height: attrs.height!,
|
||||
width: attrs.width!,
|
||||
}
|
||||
}
|
||||
|
||||
function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ISize {
|
||||
const ratio = (viewbox.width as number) / (viewbox.height as number)
|
||||
const ratio = (viewbox.width!) / (viewbox.height!)
|
||||
if (attrs.width) {
|
||||
return {
|
||||
height: Math.floor(attrs.width / ratio),
|
||||
|
@ -79,8 +79,8 @@ function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ISize {
|
|||
}
|
||||
}
|
||||
return {
|
||||
height: viewbox.height as number,
|
||||
width: viewbox.width as number,
|
||||
height: viewbox.height!,
|
||||
width: viewbox.width!,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -44,7 +44,7 @@ function extractTags(buffer: Buffer, isBigEndian: boolean) {
|
|||
const tags: {[key: number]: number} = {}
|
||||
|
||||
let temp: Buffer | undefined = buffer
|
||||
while (temp && temp.length) {
|
||||
while (temp?.length) {
|
||||
const code = readUInt(temp, 16, 0, isBigEndian)
|
||||
const type = readUInt(temp, 16, 2, isBigEndian)
|
||||
const length = readUInt(temp, 32, 4, isBigEndian)
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
/* eslint-disable no-console */
|
||||
import {
|
||||
AstroCheck,
|
||||
DiagnosticSeverity,
|
||||
|
|
|
@ -14,7 +14,7 @@ export const errorMap: ZodErrorMap = (baseError, ctx) => {
|
|||
// raise a single error when `key` does not match:
|
||||
// > Did not match union.
|
||||
// > key: Expected `'tutorial' | 'blog'`, received 'foo'
|
||||
let typeOrLiteralErrByPath: Map<string, TypeOrLiteralErrByPathEntry> = new Map();
|
||||
let typeOrLiteralErrByPath = new Map<string, TypeOrLiteralErrByPathEntry>();
|
||||
for (const unionError of baseError.unionErrors.map((e) => e.errors).flat()) {
|
||||
if (unionError.code === 'invalid_type' || unionError.code === 'invalid_literal') {
|
||||
const flattenedErrorPath = flattenErrorPath(unionError.path);
|
||||
|
|
|
@ -177,7 +177,7 @@ export function getDataEntryExts(settings: Pick<AstroSettings, 'dataEntryTypes'>
|
|||
export function getEntryConfigByExtMap<TEntryType extends ContentEntryType | DataEntryType>(
|
||||
entryTypes: TEntryType[]
|
||||
): Map<string, TEntryType> {
|
||||
const map: Map<string, TEntryType> = new Map();
|
||||
const map = new Map<string, TEntryType>();
|
||||
for (const entryType of entryTypes) {
|
||||
for (const ext of entryType.extensions) {
|
||||
map.set(ext, entryType);
|
||||
|
@ -310,7 +310,7 @@ function getYAMLErrorLine(rawData: string | undefined, objectKey: string) {
|
|||
return numNewlinesBeforeKey;
|
||||
}
|
||||
|
||||
export function parseFrontmatter(fileContents: string, filePath: string) {
|
||||
export function parseFrontmatter(fileContents: string) {
|
||||
try {
|
||||
// `matter` is empty string on cache results
|
||||
// clear cache to prevent this
|
||||
|
|
|
@ -203,7 +203,7 @@ export class App {
|
|||
): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
const pathname = prependForwardSlash(this.removeBase(url.pathname));
|
||||
const info = this.#routeDataToRouteInfo.get(routeData!)!;
|
||||
const info = this.#routeDataToRouteInfo.get(routeData)!;
|
||||
const isCompressHTML = this.#manifest.compressHTML ?? false;
|
||||
// may be used in the future for handling rel=modulepreload, rel=icon, rel=manifest etc.
|
||||
const links = new Set<never>();
|
||||
|
|
|
@ -34,7 +34,7 @@ class NodeIncomingMessage extends IncomingMessage {
|
|||
/**
|
||||
* The read-only body property of the Request interface contains a ReadableStream with the body contents that have been added to the request.
|
||||
*/
|
||||
body?: any | undefined;
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
export class NodeApp extends App {
|
||||
|
|
|
@ -121,7 +121,7 @@ export function chunkIsPage(
|
|||
if (output.type !== 'chunk') {
|
||||
return false;
|
||||
}
|
||||
const chunk = output as OutputChunk;
|
||||
const chunk = output;
|
||||
if (chunk.facadeModuleId) {
|
||||
const facadeToEntryId = prependForwardSlash(
|
||||
rootRelativeFacadeId(chunk.facadeModuleId, settings)
|
||||
|
@ -470,15 +470,7 @@ async function generatePath(
|
|||
onRequest?: MiddlewareHandler<unknown>
|
||||
) {
|
||||
const { settings, logging, origin, routeCache } = opts;
|
||||
const {
|
||||
mod,
|
||||
internals,
|
||||
linkIds,
|
||||
scripts: hoistedScripts,
|
||||
styles: _styles,
|
||||
pageData,
|
||||
renderers,
|
||||
} = gopts;
|
||||
const { mod, internals, scripts: hoistedScripts, styles: _styles, pageData, renderers } = gopts;
|
||||
|
||||
// This adds the page name to the array so it can be shown as part of stats.
|
||||
if (pageData.route.type === 'page') {
|
||||
|
|
|
@ -18,11 +18,11 @@ export function registerAllPlugins({ internals, options, register }: AstroBuildP
|
|||
register(pluginAliasResolve(internals));
|
||||
register(pluginAnalyzer(internals));
|
||||
register(pluginInternals(internals));
|
||||
register(pluginRenderers(options, internals));
|
||||
register(pluginMiddleware(options, internals));
|
||||
register(pluginRenderers(options));
|
||||
register(pluginMiddleware(options));
|
||||
register(pluginPages(options, internals));
|
||||
register(pluginCSS(options, internals));
|
||||
register(astroHeadBuildPlugin(options, internals));
|
||||
register(astroHeadBuildPlugin(internals));
|
||||
register(pluginPrerender(options, internals));
|
||||
register(astroConfigBuildPlugin(options, internals));
|
||||
register(pluginHoistedScripts(options, internals));
|
||||
|
|
|
@ -126,7 +126,7 @@ export function vitePluginAnalyzer(internals: BuildInternals): VitePlugin {
|
|||
|
||||
for (const id of ids) {
|
||||
const info = this.getModuleInfo(id);
|
||||
if (!info || !info.meta?.astro) continue;
|
||||
if (!info?.meta?.astro) continue;
|
||||
|
||||
const astro = info.meta.astro as AstroPluginMetadata['astro'];
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ export const astroEntryPrefix = '\0astro-entry:';
|
|||
* entries to re-export only the names the user is using.
|
||||
*/
|
||||
export function vitePluginComponentEntry(internals: BuildInternals): VitePlugin {
|
||||
const componentToExportNames: Map<string, string[]> = new Map();
|
||||
const componentToExportNames = new Map<string, string[]>();
|
||||
|
||||
mergeComponentExportNames(internals.discoveredHydratedComponents);
|
||||
mergeComponentExportNames(internals.discoveredClientOnlyComponents);
|
||||
|
|
|
@ -107,7 +107,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
|
|||
},
|
||||
|
||||
async generateBundle(_outputOptions, bundle) {
|
||||
for (const [_, chunk] of Object.entries(bundle)) {
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type !== 'chunk') continue;
|
||||
if ('viteMetadata' in chunk === false) continue;
|
||||
const meta = chunk.viteMetadata as ViteMetadata;
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import { MIDDLEWARE_PATH_SEGMENT_NAME } from '../../constants.js';
|
||||
import { addRollupInput } from '../add-rollup-input.js';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
|
||||
|
@ -9,10 +8,7 @@ export const MIDDLEWARE_MODULE_ID = '@astro-middleware';
|
|||
|
||||
const EMPTY_MIDDLEWARE = '\0empty-middleware';
|
||||
|
||||
export function vitePluginMiddleware(
|
||||
opts: StaticBuildOptions,
|
||||
_internals: BuildInternals
|
||||
): VitePlugin {
|
||||
export function vitePluginMiddleware(opts: StaticBuildOptions): VitePlugin {
|
||||
return {
|
||||
name: '@astro/plugin-middleware',
|
||||
|
||||
|
@ -44,16 +40,13 @@ export function vitePluginMiddleware(
|
|||
};
|
||||
}
|
||||
|
||||
export function pluginMiddleware(
|
||||
opts: StaticBuildOptions,
|
||||
internals: BuildInternals
|
||||
): AstroBuildPlugin {
|
||||
export function pluginMiddleware(opts: StaticBuildOptions): AstroBuildPlugin {
|
||||
return {
|
||||
build: 'ssr',
|
||||
hooks: {
|
||||
'build:before': () => {
|
||||
return {
|
||||
vitePlugin: vitePluginMiddleware(opts, internals),
|
||||
vitePlugin: vitePluginMiddleware(opts),
|
||||
};
|
||||
},
|
||||
},
|
||||
|
|
|
@ -39,7 +39,7 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V
|
|||
|
||||
options(options) {
|
||||
if (opts.settings.config.output === 'static') {
|
||||
const inputs: Set<string> = new Set();
|
||||
const inputs = new Set<string>();
|
||||
|
||||
for (const [path, pageData] of Object.entries(opts.allPages)) {
|
||||
if (routeIsRedirect(pageData.route)) {
|
||||
|
|
|
@ -1,17 +1,12 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import { addRollupInput } from '../add-rollup-input.js';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
|
||||
export const RENDERERS_MODULE_ID = '@astro-renderers';
|
||||
export const RESOLVED_RENDERERS_MODULE_ID = `\0${RENDERERS_MODULE_ID}`;
|
||||
|
||||
let inputs: Set<string> = new Set();
|
||||
export function vitePluginRenderers(
|
||||
opts: StaticBuildOptions,
|
||||
_internals: BuildInternals
|
||||
): VitePlugin {
|
||||
export function vitePluginRenderers(opts: StaticBuildOptions): VitePlugin {
|
||||
return {
|
||||
name: '@astro/plugin-renderers',
|
||||
|
||||
|
@ -49,16 +44,13 @@ export function vitePluginRenderers(
|
|||
};
|
||||
}
|
||||
|
||||
export function pluginRenderers(
|
||||
opts: StaticBuildOptions,
|
||||
internals: BuildInternals
|
||||
): AstroBuildPlugin {
|
||||
export function pluginRenderers(opts: StaticBuildOptions): AstroBuildPlugin {
|
||||
return {
|
||||
build: 'ssr',
|
||||
hooks: {
|
||||
'build:before': () => {
|
||||
return {
|
||||
vitePlugin: vitePluginRenderers(opts, internals),
|
||||
vitePlugin: vitePluginRenderers(opts),
|
||||
};
|
||||
},
|
||||
},
|
||||
|
|
|
@ -42,10 +42,7 @@ function vitePluginSSR(
|
|||
},
|
||||
async load(id) {
|
||||
if (id === RESOLVED_SSR_VIRTUAL_MODULE_ID) {
|
||||
const {
|
||||
settings: { config },
|
||||
allPages,
|
||||
} = options;
|
||||
const { allPages } = options;
|
||||
const imports: string[] = [];
|
||||
const contents: string[] = [];
|
||||
const exports: string[] = [];
|
||||
|
@ -82,7 +79,7 @@ function vitePluginSSR(
|
|||
},
|
||||
async generateBundle(_opts, bundle) {
|
||||
// Add assets from this SSR chunk as well.
|
||||
for (const [_chunkName, chunk] of Object.entries(bundle)) {
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === 'asset') {
|
||||
internals.staticFiles.add(chunk.fileName);
|
||||
}
|
||||
|
@ -162,7 +159,7 @@ function vitePluginSSRSplit(
|
|||
enforce: 'post',
|
||||
options(opts) {
|
||||
if (options.settings.config.build.split) {
|
||||
const inputs: Set<string> = new Set();
|
||||
const inputs = new Set<string>();
|
||||
|
||||
for (const path of Object.keys(options.allPages)) {
|
||||
inputs.add(getVirtualModulePageNameFromPath(SPLIT_MODULE_ID, path));
|
||||
|
@ -178,10 +175,6 @@ function vitePluginSSRSplit(
|
|||
},
|
||||
async load(id) {
|
||||
if (id.startsWith(RESOLVED_SPLIT_MODULE_ID)) {
|
||||
const {
|
||||
settings: { config },
|
||||
allPages,
|
||||
} = options;
|
||||
const imports: string[] = [];
|
||||
const contents: string[] = [];
|
||||
const exports: string[] = [];
|
||||
|
@ -204,7 +197,7 @@ function vitePluginSSRSplit(
|
|||
},
|
||||
async generateBundle(_opts, bundle) {
|
||||
// Add assets from this SSR chunk as well.
|
||||
for (const [_chunkName, chunk] of Object.entries(bundle)) {
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === 'asset') {
|
||||
internals.staticFiles.add(chunk.fileName);
|
||||
}
|
||||
|
@ -268,7 +261,7 @@ export function pluginSSRSplit(
|
|||
logging: options.logging,
|
||||
entryPoints: internals.entryPoints,
|
||||
});
|
||||
for (const [moduleName, chunk] of internals.ssrSplitEntryChunks) {
|
||||
for (const [, chunk] of internals.ssrSplitEntryChunks) {
|
||||
const code = injectManifest(manifest, chunk);
|
||||
mutate(chunk, 'server', code);
|
||||
}
|
||||
|
@ -413,8 +406,8 @@ function buildManifest(
|
|||
if (!route.prerender) continue;
|
||||
if (!route.pathname) continue;
|
||||
|
||||
const outFolder = getOutFolder(opts.settings.config, route.pathname!, route.type);
|
||||
const outFile = getOutFile(opts.settings.config, outFolder, route.pathname!, route.type);
|
||||
const outFolder = getOutFolder(opts.settings.config, route.pathname, route.type);
|
||||
const outFile = getOutFile(opts.settings.config, outFolder, route.pathname, route.type);
|
||||
const file = outFile.toString().replace(opts.settings.config.build.client.toString(), '');
|
||||
routes.push({
|
||||
file,
|
||||
|
|
|
@ -78,6 +78,8 @@ export async function compile({
|
|||
}
|
||||
|
||||
function handleCompileResultErrors(result: TransformResult, cssTransformErrors: AstroError[]) {
|
||||
// TODO: Export the DiagnosticSeverity enum from @astrojs/compiler?
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
|
||||
const compilerError = result.diagnostics.find((diag) => diag.severity === 1);
|
||||
|
||||
if (compilerError) {
|
||||
|
@ -96,7 +98,6 @@ function handleCompileResultErrors(result: TransformResult, cssTransformErrors:
|
|||
case 0:
|
||||
break;
|
||||
case 1: {
|
||||
const error = cssTransformErrors[0];
|
||||
throw cssTransformErrors[0];
|
||||
}
|
||||
default: {
|
||||
|
|
|
@ -8,7 +8,7 @@ import { BUNDLED_THEMES } from 'shiki';
|
|||
import { z } from 'zod';
|
||||
import { appendForwardSlash, prependForwardSlash, trimSlashes } from '../path.js';
|
||||
|
||||
const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = {
|
||||
const ASTRO_CONFIG_DEFAULTS = {
|
||||
root: '.',
|
||||
srcDir: './src',
|
||||
publicDir: './public',
|
||||
|
@ -30,7 +30,6 @@ const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = {
|
|||
server: {
|
||||
host: false,
|
||||
port: 3000,
|
||||
streaming: true,
|
||||
open: false,
|
||||
},
|
||||
integrations: [],
|
||||
|
@ -45,7 +44,7 @@ const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = {
|
|||
assets: false,
|
||||
redirects: false,
|
||||
},
|
||||
};
|
||||
} satisfies AstroUserConfig & { server: { open: boolean } };
|
||||
|
||||
export const AstroConfigSchema = z.object({
|
||||
root: z
|
||||
|
@ -172,8 +171,8 @@ export const AstroConfigSchema = z.object({
|
|||
theme: z
|
||||
.enum(BUNDLED_THEMES as [Theme, ...Theme[]])
|
||||
.or(z.custom<IThemeRegistration>())
|
||||
.default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.theme),
|
||||
wrap: z.boolean().or(z.null()).default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.wrap),
|
||||
.default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.theme!),
|
||||
wrap: z.boolean().or(z.null()).default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.wrap!),
|
||||
})
|
||||
.default({}),
|
||||
remarkPlugins: z
|
||||
|
|
|
@ -18,7 +18,7 @@ interface OngoingStat {
|
|||
*/
|
||||
export class AstroTimer {
|
||||
private enabled: boolean;
|
||||
private ongoingTimers: Map<string, OngoingStat> = new Map();
|
||||
private ongoingTimers = new Map<string, OngoingStat>();
|
||||
private stats: Record<string, Stat> = {};
|
||||
|
||||
constructor() {
|
||||
|
|
|
@ -99,7 +99,7 @@ class AstroCookies implements AstroCookiesInterface {
|
|||
*/
|
||||
get(key: string): AstroCookie {
|
||||
// Check for outgoing Set-Cookie values first
|
||||
if (this.#outgoing !== null && this.#outgoing.has(key)) {
|
||||
if (this.#outgoing?.has(key)) {
|
||||
let [serializedValue, , isSetValue] = this.#outgoing.get(key)!;
|
||||
if (isSetValue) {
|
||||
return new AstroCookie(serializedValue);
|
||||
|
@ -120,7 +120,7 @@ class AstroCookies implements AstroCookiesInterface {
|
|||
* @returns
|
||||
*/
|
||||
has(key: string): boolean {
|
||||
if (this.#outgoing !== null && this.#outgoing.has(key)) {
|
||||
if (this.#outgoing?.has(key)) {
|
||||
let [, , isSetValue] = this.#outgoing.get(key)!;
|
||||
return isSetValue;
|
||||
}
|
||||
|
|
|
@ -121,10 +121,10 @@ export async function createVite(
|
|||
markdownVitePlugin({ settings, logging }),
|
||||
htmlVitePlugin(),
|
||||
jsxVitePlugin({ settings, logging }),
|
||||
astroPostprocessVitePlugin({ settings }),
|
||||
astroPostprocessVitePlugin(),
|
||||
mode === 'dev' && astroIntegrationsContainerPlugin({ settings, logging }),
|
||||
astroScriptsPageSSRPlugin({ settings }),
|
||||
astroHeadPlugin({ settings }),
|
||||
astroHeadPlugin(),
|
||||
astroScannerPlugin({ settings }),
|
||||
astroInjectEnvTsPlugin({ settings, logging, fs }),
|
||||
astroContentVirtualModPlugin({ settings }),
|
||||
|
@ -315,12 +315,3 @@ function isCommonNotAstro(dep: string): boolean {
|
|||
)
|
||||
);
|
||||
}
|
||||
|
||||
interface PkgJSON {
|
||||
name: string;
|
||||
dependencies?: Record<string, string>;
|
||||
devDependencies?: Record<string, string>;
|
||||
peerDependencies?: Record<string, string>;
|
||||
keywords?: string[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
|
|
@ -125,7 +125,7 @@ interface Restart {
|
|||
|
||||
export async function createContainerWithAutomaticRestart({
|
||||
flags,
|
||||
handleConfigError = (_e: Error) => {},
|
||||
handleConfigError = () => {},
|
||||
beforeRestart,
|
||||
params,
|
||||
}: CreateContainerWithAutomaticRestart): Promise<Restart> {
|
||||
|
@ -143,7 +143,6 @@ export async function createContainerWithAutomaticRestart({
|
|||
};
|
||||
|
||||
async function handleServerRestart(logMsg: string) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-shadow
|
||||
const container = restart.container;
|
||||
const { container: newContainer, error } = await restartContainer({
|
||||
beforeRestart,
|
||||
|
|
|
@ -20,11 +20,9 @@ type EsbuildMessage = ESBuildTransformResult['warnings'][number];
|
|||
*/
|
||||
export function collectErrorMetadata(e: any, rootFolder?: URL | undefined): ErrorWithMetadata {
|
||||
const err =
|
||||
AggregateError.is(e) || Array.isArray((e as any).errors)
|
||||
? (e.errors as SSRError[])
|
||||
: [e as SSRError];
|
||||
AggregateError.is(e) || Array.isArray(e.errors) ? (e.errors as SSRError[]) : [e as SSRError];
|
||||
|
||||
err.forEach((error, idx) => {
|
||||
err.forEach((error) => {
|
||||
if (e.stack) {
|
||||
const stackInfo = collectInfoFromStacktrace(e);
|
||||
error.stack = stackInfo.stack;
|
||||
|
@ -73,7 +71,7 @@ export function collectErrorMetadata(e: any, rootFolder?: URL | undefined): Erro
|
|||
|
||||
// If we received an array of errors and it's not from us, it's most likely from ESBuild, try to extract info for Vite to display
|
||||
// NOTE: We still need to be defensive here, because it might not necessarily be from ESBuild, it's just fairly likely.
|
||||
if (!AggregateError.is(e) && Array.isArray((e as any).errors)) {
|
||||
if (!AggregateError.is(e) && Array.isArray(e.errors)) {
|
||||
(e.errors as EsbuildMessage[]).forEach((buildError, i) => {
|
||||
const { location, pluginName, text } = buildError;
|
||||
|
||||
|
@ -226,7 +224,7 @@ export function renderErrorMarkdown(markdown: string, target: 'html' | 'cli') {
|
|||
} else {
|
||||
return markdown
|
||||
.replace(linkRegex, (fullMatch, m1, m2) => `${bold(m1)} ${underline(m2)}`)
|
||||
.replace(urlRegex, (fullMatch, m1) => ` ${underline(fullMatch.trim())} `)
|
||||
.replace(urlRegex, (fullMatch) => ` ${underline(fullMatch.trim())} `)
|
||||
.replace(boldRegex, (fullMatch, m1) => `${bold(m1)}`);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -81,7 +81,7 @@ export class AstroError extends Error {
|
|||
this.frame = codeFrame(source, location);
|
||||
}
|
||||
|
||||
static is(err: Error | unknown): err is AstroError {
|
||||
static is(err: unknown): err is AstroError {
|
||||
return (err as AstroError).type === 'AstroError';
|
||||
}
|
||||
}
|
||||
|
@ -95,7 +95,7 @@ export class CompilerError extends AstroError {
|
|||
this.name = 'CompilerError';
|
||||
}
|
||||
|
||||
static is(err: Error | unknown): err is CompilerError {
|
||||
static is(err: unknown): err is CompilerError {
|
||||
return (err as CompilerError).type === 'CompilerError';
|
||||
}
|
||||
}
|
||||
|
@ -103,7 +103,7 @@ export class CompilerError extends AstroError {
|
|||
export class CSSError extends AstroError {
|
||||
type: ErrorTypes = 'CSSError';
|
||||
|
||||
static is(err: Error | unknown): err is CSSError {
|
||||
static is(err: unknown): err is CSSError {
|
||||
return (err as CSSError).type === 'CSSError';
|
||||
}
|
||||
}
|
||||
|
@ -111,7 +111,7 @@ export class CSSError extends AstroError {
|
|||
export class MarkdownError extends AstroError {
|
||||
type: ErrorTypes = 'MarkdownError';
|
||||
|
||||
static is(err: Error | unknown): err is MarkdownError {
|
||||
static is(err: unknown): err is MarkdownError {
|
||||
return (err as MarkdownError).type === 'MarkdownError';
|
||||
}
|
||||
}
|
||||
|
@ -119,7 +119,7 @@ export class MarkdownError extends AstroError {
|
|||
export class InternalError extends AstroError {
|
||||
type: ErrorTypes = 'InternalError';
|
||||
|
||||
static is(err: Error | unknown): err is InternalError {
|
||||
static is(err: unknown): err is InternalError {
|
||||
return (err as InternalError).type === 'InternalError';
|
||||
}
|
||||
}
|
||||
|
@ -136,7 +136,7 @@ export class AggregateError extends AstroError {
|
|||
this.errors = props.errors;
|
||||
}
|
||||
|
||||
static is(err: Error | unknown): err is AggregateError {
|
||||
static is(err: unknown): err is AggregateError {
|
||||
return (err as AggregateError).type === 'AggregateError';
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
import type { AstroConfig } from '../../@types/astro';
|
||||
import type { AstroErrorPayload } from './dev/vite';
|
||||
|
||||
const style = /* css */ `
|
||||
|
@ -665,7 +664,7 @@ class ErrorOverlay extends HTMLElement {
|
|||
const errorLine = this.root.querySelector<HTMLSpanElement>('.error-line');
|
||||
|
||||
if (errorLine) {
|
||||
if (errorLine.parentElement && errorLine.parentElement.parentElement) {
|
||||
if (errorLine.parentElement?.parentElement) {
|
||||
errorLine.parentElement.parentElement.scrollTop =
|
||||
errorLine.offsetTop - errorLine.parentElement.parentElement.offsetTop - 8;
|
||||
}
|
||||
|
@ -745,6 +744,6 @@ function getOverlayCode() {
|
|||
`;
|
||||
}
|
||||
|
||||
export function patchOverlay(code: string, config: AstroConfig) {
|
||||
export function patchOverlay(code: string) {
|
||||
return code.replace('class ErrorOverlay', getOverlayCode() + '\nclass ViteErrorOverlay');
|
||||
}
|
||||
|
|
|
@ -89,7 +89,7 @@ export function formatYAMLException(e: YAMLException): ViteErrorPayload['err'] {
|
|||
|
||||
/** Coalesce any throw variable to an Error instance. */
|
||||
export function createSafeError(err: any): Error {
|
||||
if (err instanceof Error || (err && err.name && err.message)) {
|
||||
if (err instanceof Error || (err?.name && err.message)) {
|
||||
return err;
|
||||
} else {
|
||||
const error = new Error(JSON.stringify(err));
|
||||
|
|
|
@ -49,11 +49,6 @@ export async function callMiddleware<R>(
|
|||
apiContext: APIContext,
|
||||
responseFunction: () => Promise<R>
|
||||
): Promise<Response | R> {
|
||||
let resolveResolve: any;
|
||||
new Promise((resolve) => {
|
||||
resolveResolve = resolve;
|
||||
});
|
||||
|
||||
let nextCalled = false;
|
||||
let responseFunctionPromise: Promise<R> | undefined = undefined;
|
||||
const next: MiddlewareNext<R> = async () => {
|
||||
|
|
|
@ -174,7 +174,7 @@ export async function renderPage(options: SSROptions): Promise<Response> {
|
|||
adapterName: options.env.adapterName,
|
||||
});
|
||||
if (options.middleware) {
|
||||
if (options.middleware && options.middleware.onRequest) {
|
||||
if (options.middleware?.onRequest) {
|
||||
const onRequest = options.middleware.onRequest as MiddlewareResponseHandler;
|
||||
const response = await callMiddleware<Response>(env.logging, onRequest, apiContext, () => {
|
||||
return coreRenderPage({
|
||||
|
|
|
@ -33,8 +33,8 @@ interface Item {
|
|||
|
||||
function countOccurrences(needle: string, haystack: string) {
|
||||
let count = 0;
|
||||
for (let i = 0; i < haystack.length; i += 1) {
|
||||
if (haystack[i] === needle) count += 1;
|
||||
for (const hay of haystack) {
|
||||
if (hay === needle) count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
@ -61,10 +61,6 @@ function getParts(part: string, file: string) {
|
|||
return result;
|
||||
}
|
||||
|
||||
function areSamePart(a: RoutePart, b: RoutePart) {
|
||||
return a.content === b.content && a.dynamic === b.dynamic && a.spread === b.spread;
|
||||
}
|
||||
|
||||
function getPattern(
|
||||
segments: RoutePart[][],
|
||||
base: string,
|
||||
|
@ -208,25 +204,6 @@ function injectedRouteToItem(
|
|||
};
|
||||
}
|
||||
|
||||
// Seeings if the two routes are siblings of each other, with `b` being the route
|
||||
// in focus. If it is in the same parent folder as `a`, they are siblings.
|
||||
function areSiblings(a: RouteData, b: RouteData) {
|
||||
if (a.segments.length < b.segments.length) return false;
|
||||
for (let i = 0; i < b.segments.length - 1; i++) {
|
||||
let segment = b.segments[i];
|
||||
if (segment.length === a.segments[i].length) {
|
||||
for (let j = 0; j < segment.length; j++) {
|
||||
if (!areSamePart(segment[j], a.segments[i][j])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface CreateRouteManifestParams {
|
||||
/** Astro Settings object */
|
||||
settings: AstroSettings;
|
||||
|
@ -243,16 +220,16 @@ export function createRouteManifest(
|
|||
): ManifestData {
|
||||
const components: string[] = [];
|
||||
const routes: RouteData[] = [];
|
||||
const validPageExtensions: Set<string> = new Set([
|
||||
const validPageExtensions = new Set<string>([
|
||||
'.astro',
|
||||
...SUPPORTED_MARKDOWN_FILE_EXTENSIONS,
|
||||
...settings.pageExtensions,
|
||||
]);
|
||||
const validEndpointExtensions: Set<string> = new Set(['.js', '.ts']);
|
||||
const validEndpointExtensions = new Set<string>(['.js', '.ts']);
|
||||
const localFs = fsMod ?? nodeFs;
|
||||
const prerender = getPrerenderDefault(settings.config);
|
||||
|
||||
const foundInvalidFileExtensions: Set<string> = new Set();
|
||||
const foundInvalidFileExtensions = new Set<string>();
|
||||
|
||||
function walk(
|
||||
fs: typeof nodeFs,
|
||||
|
|
|
@ -29,7 +29,7 @@ interface ConfigErrorEventPayload extends ErrorEventPayload {
|
|||
const ANONYMIZE_MESSAGE_REGEX = /^(\w| )+/;
|
||||
function anonymizeErrorMessage(msg: string): string | undefined {
|
||||
const matchedMessage = msg.match(ANONYMIZE_MESSAGE_REGEX);
|
||||
if (!matchedMessage || !matchedMessage[0]) {
|
||||
if (!matchedMessage?.[0]) {
|
||||
return undefined;
|
||||
}
|
||||
return matchedMessage[0].trim().substring(0, 20);
|
||||
|
@ -72,6 +72,8 @@ export function eventError({
|
|||
cliCommand: cmd,
|
||||
isFatal: isFatal,
|
||||
anonymousMessageHint:
|
||||
// https://github.com/typescript-eslint/typescript-eslint/issues/4820
|
||||
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- errorData may be false
|
||||
errorData && errorData.message
|
||||
? getSafeErrorMessage(errorData.message)
|
||||
: anonymizeErrorMessage(err.message),
|
||||
|
|
|
@ -21,8 +21,7 @@ const visibleDirective: ClientDirective = (load, _options, el) => {
|
|||
}
|
||||
});
|
||||
|
||||
for (let i = 0; i < el.children.length; i++) {
|
||||
const child = el.children[i];
|
||||
for (const child of el.children) {
|
||||
io.observe(child);
|
||||
}
|
||||
};
|
||||
|
|
|
@ -4,7 +4,7 @@ import { AstroError, AstroErrorData } from '../../core/errors/index.js';
|
|||
|
||||
/** Create the Astro.glob() runtime function. */
|
||||
function createAstroGlobFn() {
|
||||
const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => {
|
||||
const globHandler = (importMetaGlobResult: Record<string, any>) => {
|
||||
if (typeof importMetaGlobResult === 'string') {
|
||||
throw new AstroError({
|
||||
...AstroErrorData.AstroGlobUsedOutside,
|
||||
|
|
|
@ -118,13 +118,13 @@ declare const Astro: {
|
|||
const templates = this.querySelectorAll('template[data-astro-template]');
|
||||
for (const template of templates) {
|
||||
const closest = template.closest(this.tagName);
|
||||
if (!closest || !closest.isSameNode(this)) continue;
|
||||
if (!closest?.isSameNode(this)) continue;
|
||||
slots[template.getAttribute('data-astro-template') || 'default'] = template.innerHTML;
|
||||
template.remove();
|
||||
}
|
||||
for (const slot of slotted) {
|
||||
const closest = slot.closest(this.tagName);
|
||||
if (!closest || !closest.isSameNode(this)) continue;
|
||||
if (!closest?.isSameNode(this)) continue;
|
||||
slots[slot.getAttribute('name') || 'default'] = slot.innerHTML;
|
||||
}
|
||||
const props = this.hasAttribute('props')
|
||||
|
|
|
@ -19,7 +19,7 @@ function getHandlerFromModule(mod: EndpointHandler, method: string) {
|
|||
|
||||
/** Renders an endpoint request to completion, returning the body. */
|
||||
export async function renderEndpoint(mod: EndpointHandler, context: APIContext, ssr: boolean) {
|
||||
const { request, params, locals } = context;
|
||||
const { request, params } = context;
|
||||
const chosenMethod = request.method?.toLowerCase();
|
||||
const handler = getHandlerFromModule(mod, chosenMethod);
|
||||
if (!ssr && ssr === false && chosenMethod && chosenMethod !== 'get') {
|
||||
|
|
|
@ -85,10 +85,7 @@ Did you forget to import the component or is it possible there is a typo?`);
|
|||
let props: Record<string, any> = {};
|
||||
let slots: Record<string, any> = {};
|
||||
for (const [key, value] of Object.entries(vnode.props ?? {})) {
|
||||
if (
|
||||
key === 'children' ||
|
||||
(value && typeof value === 'object' && (value as any)['$$slot'])
|
||||
) {
|
||||
if (key === 'children' || (value && typeof value === 'object' && value['$$slot'])) {
|
||||
slots[key === 'children' ? 'default' : key] = () => renderJSX(result, value);
|
||||
} else {
|
||||
props[key] = value;
|
||||
|
@ -117,7 +114,7 @@ Did you forget to import the component or is it possible there is a typo?`);
|
|||
try {
|
||||
const output = await vnode.type(vnode.props ?? {});
|
||||
let renderResult: any;
|
||||
if (output && output[AstroJSX]) {
|
||||
if (output?.[AstroJSX]) {
|
||||
renderResult = await renderJSXVNode(result, output, skip);
|
||||
return renderResult;
|
||||
} else if (!output) {
|
||||
|
@ -251,11 +248,9 @@ function useConsoleFilter() {
|
|||
consoleFilterRefs++;
|
||||
|
||||
if (!originalConsoleError) {
|
||||
// eslint-disable-next-line no-console
|
||||
originalConsoleError = console.error;
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error = filteredConsoleError;
|
||||
} catch (error) {
|
||||
// If we're unable to hook `console.error`, just accept it
|
||||
|
|
|
@ -25,7 +25,7 @@ export function renderAllHeadContent(result: SSRResult) {
|
|||
result.styles.clear();
|
||||
const scripts = Array.from(result.scripts)
|
||||
.filter(uniqueElements)
|
||||
.map((script, i) => {
|
||||
.map((script) => {
|
||||
return renderElement('script', script, false);
|
||||
});
|
||||
const links = Array.from(result.links)
|
||||
|
|
|
@ -51,7 +51,7 @@ export async function renderSlotToString(
|
|||
let instructions: null | RenderInstruction[] = null;
|
||||
let iterator = renderSlot(result, slotted, fallback);
|
||||
for await (const chunk of iterator) {
|
||||
if (typeof (chunk as any).type === 'string') {
|
||||
if (typeof chunk.type === 'string') {
|
||||
if (instructions === null) {
|
||||
instructions = [];
|
||||
}
|
||||
|
|
|
@ -2,17 +2,12 @@ import { parse } from 'acorn';
|
|||
import { walk } from 'estree-walker';
|
||||
import MagicString from 'magic-string';
|
||||
import type { Plugin } from 'vite';
|
||||
import type { AstroSettings } from '../@types/astro';
|
||||
import { isMarkdownFile } from '../core/util.js';
|
||||
|
||||
// Check for `Astro.glob()`. Be very forgiving of whitespace. False positives are okay.
|
||||
const ASTRO_GLOB_REGEX = /Astro2?\s*\.\s*glob\s*\(/;
|
||||
|
||||
interface AstroPluginOptions {
|
||||
settings: AstroSettings;
|
||||
}
|
||||
|
||||
export default function astro(_opts: AstroPluginOptions): Plugin {
|
||||
export default function astro(): Plugin {
|
||||
return {
|
||||
name: 'astro:postprocess',
|
||||
async transform(code, id) {
|
||||
|
|
|
@ -31,7 +31,7 @@ export default function createVitePluginAstroServer({
|
|||
const serverController = createController({ loader });
|
||||
|
||||
/** rebuild the route cache + manifest, as needed. */
|
||||
function rebuildManifest(needsManifestRebuild: boolean, _file: string) {
|
||||
function rebuildManifest(needsManifestRebuild: boolean) {
|
||||
env.routeCache.clearAll();
|
||||
if (needsManifestRebuild) {
|
||||
manifest = createRouteManifest({ settings }, logging);
|
||||
|
@ -66,7 +66,7 @@ export default function createVitePluginAstroServer({
|
|||
if (!id.includes('vite/dist/client/client.mjs')) return;
|
||||
|
||||
// Replace the Vite overlay with ours
|
||||
return patchOverlay(code, settings.config);
|
||||
return patchOverlay(code);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
@ -84,7 +84,7 @@ export async function handleRequest(
|
|||
|
||||
// This could be a runtime error from Vite's SSR module, so try to fix it here
|
||||
try {
|
||||
env.loader.fixStacktrace(err as Error);
|
||||
env.loader.fixStacktrace(err);
|
||||
} catch {}
|
||||
|
||||
// This is our last line of defense regarding errors where we still might have some information about the request
|
||||
|
|
|
@ -137,7 +137,7 @@ export async function handleRoute(
|
|||
|
||||
const { config } = settings;
|
||||
const filePath: URL | undefined = matchedRoute.filePath;
|
||||
const { route, preloadedComponent, mod } = matchedRoute;
|
||||
const { route, preloadedComponent } = matchedRoute;
|
||||
const buildingToSSR = isServerLikeOutput(config);
|
||||
|
||||
// Headers are only available when using SSR.
|
||||
|
|
|
@ -93,8 +93,6 @@ async function enhanceCompileError({
|
|||
err,
|
||||
id,
|
||||
source,
|
||||
config,
|
||||
logging,
|
||||
}: EnhanceCompilerErrorOptions): Promise<void> {
|
||||
const lineText = (err as any).loc?.lineText;
|
||||
// Verify frontmatter: a common reason that this plugin fails is that
|
||||
|
@ -122,7 +120,7 @@ async function enhanceCompileError({
|
|||
} catch (frontmatterErr: any) {
|
||||
// Improve the error by replacing the phrase "unexpected end of file"
|
||||
// with "unexpected end of frontmatter" in the esbuild error message.
|
||||
if (frontmatterErr && frontmatterErr.message) {
|
||||
if (frontmatterErr?.message) {
|
||||
frontmatterErr.message = frontmatterErr.message.replace(
|
||||
'end of file',
|
||||
'end of frontmatter'
|
||||
|
|
|
@ -15,7 +15,7 @@ import { isAstroScript } from './query.js';
|
|||
const PKG_PREFIX = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const E2E_PREFIX = fileURLToPath(new URL('../../e2e', import.meta.url));
|
||||
const isPkgFile = (id: string | null) => {
|
||||
return id && id.startsWith(PKG_PREFIX) && !id.startsWith(E2E_PREFIX);
|
||||
return id?.startsWith(PKG_PREFIX) && !id.startsWith(E2E_PREFIX);
|
||||
};
|
||||
|
||||
export interface HandleHotUpdateOptions {
|
||||
|
|
|
@ -88,7 +88,7 @@ export default function astro({ settings, logging }: AstroPluginOptions): vite.P
|
|||
}
|
||||
|
||||
if (hoistedScript.type === 'external') {
|
||||
const src = hoistedScript.src!;
|
||||
const src = hoistedScript.src;
|
||||
if (src.startsWith('/') && !isBrowserPath(src)) {
|
||||
const publicDir = config.publicDir.pathname.replace(/\/$/, '').split('/').pop() + '/';
|
||||
throw new Error(
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
import type { ModuleInfo } from 'rollup';
|
||||
import type * as vite from 'vite';
|
||||
import type { AstroSettings, SSRComponentMetadata, SSRResult } from '../@types/astro';
|
||||
import type { SSRComponentMetadata, SSRResult } from '../@types/astro';
|
||||
import type { AstroBuildPlugin } from '../core/build/plugin.js';
|
||||
import type { StaticBuildOptions } from '../core/build/types';
|
||||
import type { PluginMetadata } from '../vite-plugin-astro/types';
|
||||
|
||||
import { getTopLevelPages, walkParentInfos } from '../core/build/graph.js';
|
||||
|
@ -12,11 +11,7 @@ import { getAstroMetadata } from '../vite-plugin-astro/index.js';
|
|||
// Detect this in comments, both in .astro components and in js/ts files.
|
||||
const injectExp = /(^\/\/|\/\/!)\s*astro-head-inject/;
|
||||
|
||||
export default function configHeadVitePlugin({
|
||||
settings,
|
||||
}: {
|
||||
settings: AstroSettings;
|
||||
}): vite.Plugin {
|
||||
export default function configHeadVitePlugin(): vite.Plugin {
|
||||
let server: vite.ViteDevServer;
|
||||
|
||||
function propagateMetadata<
|
||||
|
@ -70,10 +65,7 @@ export default function configHeadVitePlugin({
|
|||
};
|
||||
}
|
||||
|
||||
export function astroHeadBuildPlugin(
|
||||
options: StaticBuildOptions,
|
||||
internals: BuildInternals
|
||||
): AstroBuildPlugin {
|
||||
export function astroHeadBuildPlugin(internals: BuildInternals): AstroBuildPlugin {
|
||||
return {
|
||||
build: 'ssr',
|
||||
hooks: {
|
||||
|
|
|
@ -6,8 +6,8 @@ import { visit } from 'unist-util-visit';
|
|||
import { escape, needsEscape, replaceAttribute } from './utils.js';
|
||||
|
||||
const rehypeEscape: Plugin<[{ s: MagicString }], Root> = ({ s }) => {
|
||||
return (tree, file) => {
|
||||
visit(tree, (node: Root | RootContent, index, parent) => {
|
||||
return (tree) => {
|
||||
visit(tree, (node: Root | RootContent) => {
|
||||
if (node.type === 'text' || node.type === 'comment') {
|
||||
if (needsEscape(node.value)) {
|
||||
s.overwrite(node.position!.start.offset!, node.position!.end.offset!, escape(node.value));
|
||||
|
|
|
@ -7,7 +7,7 @@ import { escape } from './utils.js';
|
|||
|
||||
const rehypeSlots: Plugin<[{ s: MagicString }], Root> = ({ s }) => {
|
||||
return (tree, file) => {
|
||||
visit(tree, (node: Root | RootContent, index, parent) => {
|
||||
visit(tree, (node: Root | RootContent) => {
|
||||
if (node.type === 'element' && node.tagName === 'slot') {
|
||||
if (typeof node.properties?.['is:inline'] !== 'undefined') return;
|
||||
const name = node.properties?.['name'] ?? 'default';
|
||||
|
|
|
@ -51,7 +51,7 @@ function detectImportSourceFromComments(code: string): string | undefined {
|
|||
// if no imports were found, look for @jsxImportSource comment
|
||||
const multiline = code.match(/\/\*\*?[\S\s]*\*\//gm) || [];
|
||||
for (const comment of multiline) {
|
||||
const [_, lib] = comment.slice(0, -2).match(/@jsxImportSource\s*(\S+)/) || [];
|
||||
const [, lib] = comment.slice(0, -2).match(/@jsxImportSource\s*(\S+)/) || [];
|
||||
if (lib) {
|
||||
return lib.trim();
|
||||
}
|
||||
|
|
|
@ -11,7 +11,6 @@ import * as t from '@babel/types';
|
|||
*/
|
||||
export default async function tagExportsWithRenderer({
|
||||
rendererName,
|
||||
root,
|
||||
}: {
|
||||
rendererName: string;
|
||||
root: URL;
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
import { fileURLToPath } from 'node:url';
|
||||
import type { ContentEntryType } from '../@types/astro.js';
|
||||
import { parseFrontmatter } from '../content/utils.js';
|
||||
|
||||
export const markdownContentEntryType: ContentEntryType = {
|
||||
extensions: ['.md'],
|
||||
async getEntryInfo({ fileUrl, contents }: { fileUrl: URL; contents: string }) {
|
||||
const parsed = parseFrontmatter(contents, fileURLToPath(fileUrl));
|
||||
async getEntryInfo({ contents }: { contents: string }) {
|
||||
const parsed = parseFrontmatter(contents);
|
||||
return {
|
||||
data: parsed.data,
|
||||
body: parsed.content,
|
||||
|
|
|
@ -41,7 +41,7 @@ export async function scan(code: string, id: string, isHybridOutput = false): Pr
|
|||
didInit = true;
|
||||
}
|
||||
|
||||
const [_, exports] = eslexer.parse(code, id);
|
||||
const [, exports] = eslexer.parse(code, id);
|
||||
let pageOptions: PageOptions = {};
|
||||
for (const _export of exports) {
|
||||
const { n: name, le: endOfLocalName } = _export;
|
||||
|
|
|
@ -48,7 +48,7 @@ export default function astroScriptsPlugin({ settings }: { settings: AstroSettin
|
|||
}
|
||||
return null;
|
||||
},
|
||||
buildStart(options) {
|
||||
buildStart() {
|
||||
const hasHydrationScripts = settings.scripts.some((s) => s.stage === 'before-hydration');
|
||||
if (hasHydrationScripts && env?.command === 'build' && !env?.ssrBuild) {
|
||||
this.emitFile({
|
||||
|
|
|
@ -7,7 +7,7 @@ export function vitePluginSSRManifest(): VitePlugin {
|
|||
return {
|
||||
name: '@astrojs/vite-plugin-astro-ssr-manifest',
|
||||
enforce: 'post',
|
||||
resolveId(id, parent) {
|
||||
resolveId(id) {
|
||||
if (id === manifestVirtualModuleId) {
|
||||
return resolvedManifestVirtualModuleId;
|
||||
}
|
||||
|
|
|
@ -20,7 +20,6 @@ describe('Dynamic components', () => {
|
|||
});
|
||||
|
||||
it('Loads pages using client:media hydrator', async () => {
|
||||
const root = new URL('http://example.com/media/index.html');
|
||||
const html = await fixture.readFile('/media/index.html');
|
||||
const $ = cheerio.load(html);
|
||||
|
||||
|
|
|
@ -41,7 +41,7 @@ describe('Pagination', () => {
|
|||
{ color: 'blue', p: '2' },
|
||||
];
|
||||
await Promise.all(
|
||||
params.map(async ({ color, p }, idx) => {
|
||||
params.map(async ({ color, p }) => {
|
||||
const html = await fixture.readFile(`/posts/${color}/${p}/index.html`);
|
||||
const $ = cheerio.load(html);
|
||||
expect($('#page-param').text()).to.equal(p);
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { expect } from 'chai';
|
||||
import { load as cheerioLoad } from 'cheerio';
|
||||
import { loadFixture } from './test-utils.js';
|
||||
|
||||
// Asset bundling
|
||||
|
|
|
@ -21,7 +21,7 @@ describe('Component Libraries', () => {
|
|||
await fixture.build();
|
||||
});
|
||||
|
||||
function createFindEvidence(expected, prefix) {
|
||||
function createFindEvidence(expected) {
|
||||
return async function findEvidence(pathname) {
|
||||
const html = await fixture.readFile(pathname);
|
||||
const $ = cheerioLoad(html);
|
||||
|
@ -102,7 +102,7 @@ describe('Component Libraries', () => {
|
|||
await devServer.stop();
|
||||
});
|
||||
|
||||
function createFindEvidence(expected, prefix) {
|
||||
function createFindEvidence(expected) {
|
||||
return async function findEvidence(pathname) {
|
||||
const html = await fixture.fetch(pathname).then((res) => res.text());
|
||||
const $ = cheerioLoad(html);
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { expect } from 'chai';
|
||||
import { load as cheerioLoad } from 'cheerio';
|
||||
import { loadFixture } from './test-utils.js';
|
||||
import testAdapter from './test-adapter.js';
|
||||
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { expect } from 'chai';
|
||||
import * as cheerio from 'cheerio';
|
||||
import { loadFixture, silentLogging } from './test-utils.js';
|
||||
|
||||
describe('Errors in JavaScript', () => {
|
||||
|
|
|
@ -4,8 +4,6 @@ import eol from 'eol';
|
|||
import { loadFixture } from './test-utils.js';
|
||||
|
||||
describe('PostCSS', function () {
|
||||
const PREFIXED_CSS = `{-webkit-appearance:none;appearance:none`;
|
||||
|
||||
let fixture;
|
||||
let bundledCSS;
|
||||
before(async () => {
|
||||
|
|
|
@ -5,8 +5,6 @@ import { loadFixture } from './test-utils.js';
|
|||
describe('Public dev with base', () => {
|
||||
/** @type {import('./test-utils').Fixture} */
|
||||
let fixture;
|
||||
/** @type {import('./test-utils').DevServer} */
|
||||
let devServer;
|
||||
let $;
|
||||
|
||||
before(async () => {
|
||||
|
@ -15,7 +13,7 @@ describe('Public dev with base', () => {
|
|||
site: 'http://example.com/',
|
||||
base: '/blog',
|
||||
});
|
||||
devServer = await fixture.startDevServer();
|
||||
await fixture.startDevServer();
|
||||
});
|
||||
|
||||
it('200 when loading /@vite/client', async () => {
|
||||
|
|
|
@ -1,11 +1,6 @@
|
|||
import { expect } from 'chai';
|
||||
import * as cheerio from 'cheerio';
|
||||
import { loadFixture } from './test-utils.js';
|
||||
|
||||
function addLeadingSlash(path) {
|
||||
return path.startsWith('/') ? path : '/' + path;
|
||||
}
|
||||
|
||||
describe("Static build - format: 'file'", () => {
|
||||
let fixture;
|
||||
|
||||
|
|
|
@ -88,7 +88,7 @@ describe('Static build', () => {
|
|||
}
|
||||
});
|
||||
|
||||
function createFindEvidence(expected, prefix) {
|
||||
function createFindEvidence(expected) {
|
||||
return async function findEvidence(pathname) {
|
||||
const html = await fixture.readFile(pathname);
|
||||
const $ = cheerioLoad(html);
|
||||
|
|
|
@ -101,8 +101,7 @@ export const silentLogging = {
|
|||
* .clean() - Async. Removes the project’s dist folder.
|
||||
*/
|
||||
export async function loadFixture(inlineConfig) {
|
||||
if (!inlineConfig || !inlineConfig.root)
|
||||
throw new Error("Must provide { root: './fixtures/...' }");
|
||||
if (!inlineConfig?.root) throw new Error("Must provide { root: './fixtures/...' }");
|
||||
|
||||
// load config
|
||||
let cwd = inlineConfig.root;
|
||||
|
@ -235,7 +234,7 @@ export async function loadFixture(inlineConfig) {
|
|||
},
|
||||
loadTestAdapterApp: async (streaming) => {
|
||||
const url = new URL(`./server/entry.mjs?id=${fixtureId}`, config.outDir);
|
||||
const { createApp, manifest, middleware } = await import(url);
|
||||
const { createApp, manifest } = await import(url);
|
||||
const app = createApp(streaming);
|
||||
app.manifest = manifest;
|
||||
return app;
|
||||
|
|
|
@ -9,7 +9,7 @@ describe('astro/src/core/compile', () => {
|
|||
it('throws an aggregate error with the errors', async () => {
|
||||
let error;
|
||||
try {
|
||||
let r = await cachedCompilation({
|
||||
await cachedCompilation({
|
||||
astroConfig: {
|
||||
root: pathToFileURL('/'),
|
||||
},
|
||||
|
|
|
@ -1,6 +1,4 @@
|
|||
import { expect } from 'chai';
|
||||
import * as cheerio from 'cheerio';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { runInContainer } from '../../../dist/core/dev/index.js';
|
||||
import { openConfig, createSettings } from '../../../dist/core/config/index.js';
|
||||
|
|
|
@ -48,7 +48,7 @@ describe('dev container', () => {
|
|||
url: '/',
|
||||
});
|
||||
container.handle(req, res);
|
||||
const html = await done;
|
||||
await done;
|
||||
expect(res.statusCode).to.equal(
|
||||
200,
|
||||
"We get a 200 because the error occurs in the template, but we didn't crash!"
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { expect } from 'chai';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { getStylesForURL } from '../../../dist/core/render/dev/css.js';
|
||||
import { viteID } from '../../../dist/core/util.js';
|
||||
|
|
|
@ -72,7 +72,7 @@ describe('core/render', () => {
|
|||
`;
|
||||
});
|
||||
|
||||
const Page = createComponent((result, _props) => {
|
||||
const Page = createComponent((result) => {
|
||||
return render`${renderComponent(
|
||||
result,
|
||||
'PageLayout',
|
||||
|
@ -158,7 +158,7 @@ describe('core/render', () => {
|
|||
`;
|
||||
});
|
||||
|
||||
const Page = createComponent((result, _props) => {
|
||||
const Page = createComponent((result) => {
|
||||
return render`${renderComponent(
|
||||
result,
|
||||
'PageLayout',
|
||||
|
@ -221,7 +221,7 @@ describe('core/render', () => {
|
|||
`;
|
||||
});
|
||||
|
||||
const Page = createComponent((result, _props) => {
|
||||
const Page = createComponent((result) => {
|
||||
return render`${renderComponent(
|
||||
result,
|
||||
'PageLayout',
|
||||
|
|
|
@ -119,7 +119,7 @@ describe('core/render', () => {
|
|||
throw new Error('uh oh');
|
||||
});
|
||||
|
||||
const Page = createComponent((result, _props) => {
|
||||
const Page = createComponent((result) => {
|
||||
return render`<div>${renderComponent(result, 'Component', Component, {})}</div>`;
|
||||
});
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ import { Volume } from 'memfs';
|
|||
import httpMocks from 'node-mocks-http';
|
||||
import realFS from 'node:fs';
|
||||
import npath from 'path';
|
||||
import { fileURLToPath, pathToFileURL } from 'url';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { unixify } from './correct-path.js';
|
||||
|
||||
class VirtualVolume extends Volume {
|
||||
|
|
|
@ -49,7 +49,7 @@ describe('astro scan', () => {
|
|||
|
||||
it('throws on let boolean literal', async () => {
|
||||
try {
|
||||
const result = await scan(`export let prerender = true;`, '/src/components/index.astro');
|
||||
await scan(`export let prerender = true;`, '/src/components/index.astro');
|
||||
expect(false).to.be.true;
|
||||
} catch (e) {
|
||||
expect(e.message).to.contain(
|
||||
|
@ -60,7 +60,7 @@ describe('astro scan', () => {
|
|||
|
||||
it('throws on var boolean literal', async () => {
|
||||
try {
|
||||
const result = await scan(`export var prerender = true;`, '/src/components/index.astro');
|
||||
await scan(`export var prerender = true;`, '/src/components/index.astro');
|
||||
expect(false).to.be.true;
|
||||
} catch (e) {
|
||||
expect(e.message).to.contain(
|
||||
|
@ -71,7 +71,7 @@ describe('astro scan', () => {
|
|||
|
||||
it('throws on unknown values I', async () => {
|
||||
try {
|
||||
const result = await scan(`export const prerender = !!value;`, '/src/components/index.astro');
|
||||
await scan(`export const prerender = !!value;`, '/src/components/index.astro');
|
||||
expect(false).to.be.true;
|
||||
} catch (e) {
|
||||
expect(e.message).to.contain(
|
||||
|
@ -82,7 +82,7 @@ describe('astro scan', () => {
|
|||
|
||||
it('throws on unknown values II', async () => {
|
||||
try {
|
||||
const result = await scan(`export const prerender = value;`, '/src/components/index.astro');
|
||||
await scan(`export const prerender = value;`, '/src/components/index.astro');
|
||||
expect(false).to.be.true;
|
||||
} catch (e) {
|
||||
expect(e.message).to.contain(
|
||||
|
@ -93,7 +93,7 @@ describe('astro scan', () => {
|
|||
|
||||
it('throws on unknown values III', async () => {
|
||||
try {
|
||||
const result = await scan(
|
||||
await scan(
|
||||
`export let prerender = undefined; prerender = true;`,
|
||||
'/src/components/index.astro'
|
||||
);
|
||||
|
@ -107,10 +107,7 @@ describe('astro scan', () => {
|
|||
|
||||
it('throws on unknown values IV', async () => {
|
||||
try {
|
||||
const result = await scan(
|
||||
`let prerender = true; export { prerender }`,
|
||||
'/src/components/index.astro'
|
||||
);
|
||||
await scan(`let prerender = true; export { prerender }`, '/src/components/index.astro');
|
||||
expect(false).to.be.true;
|
||||
} catch (e) {
|
||||
expect(e.message).to.contain(
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { expect } from 'chai';
|
||||
import * as cheerio from 'cheerio';
|
||||
import { loadFixture } from './test-utils.js';
|
||||
|
||||
describe('Vue with multi-renderer', () => {
|
||||
|
|
|
@ -52,7 +52,7 @@ export async function getContext(argv: string[]): Promise<Context> {
|
|||
|
||||
const pkgManager = detectPackageManager()?.name ?? 'npm';
|
||||
const [username, version] = await Promise.all([getName(), getVersion()]);
|
||||
let cwd = flags['_'][0] as string;
|
||||
let cwd = flags['_'][0];
|
||||
let {
|
||||
'--help': help = false,
|
||||
'--template': template,
|
||||
|
|
|
@ -31,7 +31,6 @@ export async function git(ctx: Pick<Context, 'cwd' | 'git' | 'yes' | 'prompt' |
|
|||
end: 'Git initialized',
|
||||
while: () =>
|
||||
init({ cwd: ctx.cwd }).catch((e) => {
|
||||
// eslint-disable-next-line no-console
|
||||
error('error', e);
|
||||
process.exit(1);
|
||||
}),
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
/* eslint no-console: 'off' */
|
||||
import type { Context } from './context';
|
||||
|
||||
import { color } from '@astrojs/cli-kit';
|
||||
|
@ -34,7 +33,6 @@ export async function template(ctx: Pick<Context, 'template' | 'prompt' | 'dryRu
|
|||
end: 'Template copied',
|
||||
while: () =>
|
||||
copyTemplate(ctx.template!, ctx as Context).catch((e) => {
|
||||
// eslint-disable-next-line no-console
|
||||
if (e instanceof Error) {
|
||||
error('error', e.message);
|
||||
process.exit(1);
|
||||
|
|
|
@ -63,7 +63,6 @@ export async function typescript(
|
|||
end: 'TypeScript customized',
|
||||
while: () =>
|
||||
setupTypeScript(ts!, { cwd: ctx.cwd }).catch((e) => {
|
||||
// eslint-disable-next-line no-console
|
||||
error('error', e);
|
||||
process.exit(1);
|
||||
}),
|
||||
|
|
|
@ -64,11 +64,11 @@ export const welcome = [
|
|||
|
||||
export const getName = () =>
|
||||
new Promise<string>((resolve) => {
|
||||
exec('git config user.name', { encoding: 'utf-8' }, (_1, gitName, _2) => {
|
||||
exec('git config user.name', { encoding: 'utf-8' }, (_1, gitName) => {
|
||||
if (gitName.trim()) {
|
||||
return resolve(gitName.split(' ')[0].trim());
|
||||
}
|
||||
exec('whoami', { encoding: 'utf-8' }, (_3, whoami, _4) => {
|
||||
exec('whoami', { encoding: 'utf-8' }, (_3, whoami) => {
|
||||
if (whoami.trim()) {
|
||||
return resolve(whoami.split(' ')[0].trim());
|
||||
}
|
||||
|
|
|
@ -93,7 +93,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
|
|||
vite.ssr.target = 'webworker';
|
||||
}
|
||||
},
|
||||
'astro:build:ssr': ({ manifest, entryPoints }) => {
|
||||
'astro:build:ssr': ({ entryPoints }) => {
|
||||
_entryPoints = entryPoints;
|
||||
},
|
||||
'astro:build:done': async ({ pages, routes, dir }) => {
|
||||
|
@ -138,7 +138,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
|
|||
const fileName = entryPointsRouteData[index].component
|
||||
.replace('src/pages/', '')
|
||||
.replace('.astro', '.js')
|
||||
.replace(/(\[\.\.\.)(\w+)(\])/g, (_match, _p1, p2, _p3) => {
|
||||
.replace(/(\[\.\.\.)(\w+)(\])/g, (_match, _p1, p2) => {
|
||||
return `[[${p2}]]`;
|
||||
});
|
||||
|
||||
|
|
|
@ -37,7 +37,6 @@ export function runCLI(basePath, { silent, port = 8787 }) {
|
|||
(async function () {
|
||||
for (const msg of p.stderr) {
|
||||
if (!silent) {
|
||||
// eslint-disable-next-line
|
||||
console.error(msg);
|
||||
}
|
||||
}
|
||||
|
@ -45,7 +44,6 @@ export function runCLI(basePath, { silent, port = 8787 }) {
|
|||
|
||||
for await (const msg of p.stdout) {
|
||||
if (!silent) {
|
||||
// eslint-disable-next-line
|
||||
console.log(msg);
|
||||
}
|
||||
if (msg.includes(`Listening on`)) {
|
||||
|
|
|
@ -95,7 +95,7 @@ export function getAdapter(args?: Options): AstroAdapter {
|
|||
const denoImportsShimPlugin = {
|
||||
name: '@astrojs/deno:shim',
|
||||
setup(build: esbuild.PluginBuild) {
|
||||
build.onLoad({ filter: /__deno_imports\.js$/ }, async (args) => {
|
||||
build.onLoad({ filter: /__deno_imports\.js$/ }, async () => {
|
||||
return {
|
||||
contents: DENO_IMPORTS,
|
||||
loader: 'js',
|
||||
|
|
|
@ -93,7 +93,6 @@ export function start(manifest: SSRManifest, options: Options) {
|
|||
});
|
||||
|
||||
_startPromise = Promise.resolve(_server.listenAndServe());
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`Server running on port ${port}`);
|
||||
}
|
||||
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
/* Deno types consider DOM elements nullable */
|
||||
/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */
|
||||
import { DOMParser } from 'https://deno.land/x/deno_dom@v0.1.35-alpha/deno-dom-wasm.ts';
|
||||
import { assert, assertEquals } from 'https://deno.land/std@0.158.0/testing/asserts.ts';
|
||||
import { runBuildAndStartApp, defaultTestPermissions } from './helpers.ts';
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
/* Deno types consider DOM elements nullable */
|
||||
/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */
|
||||
import { DOMParser } from 'https://deno.land/x/deno_dom@v0.1.35-alpha/deno-dom-wasm.ts';
|
||||
import { assert, assertEquals } from 'https://deno.land/std@0.158.0/testing/asserts.ts';
|
||||
import { runBuildAndStartAppFromSubprocess } from './helpers.ts';
|
||||
|
|
|
@ -162,7 +162,6 @@ export async function ssgBuild({
|
|||
}
|
||||
|
||||
if (!inputBuffer) {
|
||||
// eslint-disable-next-line no-console
|
||||
warn({ level: logLevel, message: `"${src}" image could not be fetched` });
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
/// <reference types="astro/astro-jsx" />
|
||||
import type {
|
||||
ColorDefinition,
|
||||
ImageService,
|
||||
OutputFormat,
|
||||
TransformOptions,
|
||||
} from '../loaders/index.js';
|
||||
import type { ImageService, OutputFormat, TransformOptions } from '../loaders/index.js';
|
||||
import { isSSRService, parseAspectRatio } from '../loaders/index.js';
|
||||
import { isRemoteImage } from '../utils/paths.js';
|
||||
import type { ImageMetadata } from '../vite-plugin-astro-image.js';
|
||||
|
@ -91,7 +86,7 @@ async function resolveTransform(input: GetImageTransform): Promise<TransformOpti
|
|||
height,
|
||||
aspectRatio,
|
||||
format: format as OutputFormat,
|
||||
background: background as ColorDefinition | undefined,
|
||||
background,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue