Skip to content

Commit

Permalink
Deno adapter (withastro#2934)
Browse files Browse the repository at this point in the history
* Bundle everything, commit 1

* Get everything working

* Remove dependency on readable-stream

* Adds a changeset

* Fix ts errors

* Use the node logger in tests

* Callback the logger when done writing

* Fix test helper to await the callback

* Use serialize-javascript again

* Remove dead code

* Rename hook

* Oops
  • Loading branch information
matthewp authored Mar 30, 2022
1 parent 5b4fc59 commit f976e1f
Show file tree
Hide file tree
Showing 39 changed files with 560 additions and 422 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"mime": "^3.0.0",
"ora": "^6.1.0",
"parse5": "^6.0.1",
"path-browserify": "^1.0.1",
"path-to-regexp": "^6.2.0",
"postcss": "^8.4.12",
"postcss-load-config": "^3.1.4",
Expand Down Expand Up @@ -148,6 +149,7 @@
"@types/mime": "^2.0.3",
"@types/mocha": "^9.1.0",
"@types/parse5": "^6.0.3",
"@types/path-browserify": "^1.0.0",
"@types/prettier": "^2.4.4",
"@types/resolve": "^1.20.1",
"@types/rimraf": "^3.0.2",
Expand Down
2 changes: 2 additions & 0 deletions src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type * as vite from 'vite';
import { z } from 'zod';
import type { AstroConfigSchema } from '../core/config';
import type { AstroComponentFactory, Metadata } from '../runtime/server';
import type { ViteConfigWithSSR } from '../core/create-vite';
export type { SSRManifest } from '../core/app/types';

export interface AstroBuiltinProps {
Expand Down Expand Up @@ -680,6 +681,7 @@ export interface AstroIntegration {
'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>;
'astro:server:done'?: () => void | Promise<void>;
'astro:build:start'?: (options: { buildConfig: BuildConfig }) => void | Promise<void>;
'astro:build:setup'?: (options: { vite: ViteConfigWithSSR, target: 'client' | 'server' }) => void;
'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; routes: RouteData[] }) => void | Promise<void>;
};
}
Expand Down
6 changes: 3 additions & 3 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/* eslint-disable no-console */

import type { AstroConfig } from '../@types/astro';
import { enableVerboseLogging, LogOptions } from '../core/logger.js';
import { LogOptions } from '../core/logger/core.js';

import * as colors from 'kleur/colors';
import yargs from 'yargs-parser';
import { z } from 'zod';
import { defaultLogDestination } from '../core/logger.js';
import { nodeLogDestination, enableVerboseLogging } from '../core/logger/node.js';
import build from '../core/build/index.js';
import add from '../core/add/index.js';
import devServer from '../core/dev/index.js';
Expand Down Expand Up @@ -87,7 +87,7 @@ export async function cli(args: string[]) {

// logLevel
let logging: LogOptions = {
dest: defaultLogDestination,
dest: nodeLogDestination,
level: 'info',
};
if (flags.verbose) {
Expand Down
2 changes: 1 addition & 1 deletion src/core/add/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import preferredPM from 'preferred-pm';
import ora from 'ora';
import { resolveConfigURL } from '../config.js';
import { apply as applyPolyfill } from '../polyfill.js';
import { error, info, debug, LogOptions } from '../logger.js';
import { error, info, debug, LogOptions } from '../logger/core.js';
import { printHelp } from '../messages.js';
import * as msg from '../messages.js';
import * as CONSTS from './consts.js';
Expand Down
12 changes: 8 additions & 4 deletions src/core/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { ComponentInstance, EndpointHandler, ManifestData, RouteData } from '../../@types/astro';
import type { SSRManifest as Manifest, RouteInfo } from './types';
import type { LogOptions } from '../logger/core.js';

import mime from 'mime';
import { defaultLogOptions } from '../logger.js';
import { consoleLogDestination } from '../logger/console.js';
export { deserializeManifest } from './common.js';
import { matchRoute } from '../routing/match.js';
import { render } from '../render/core.js';
Expand All @@ -18,15 +19,18 @@ export class App {
#routeDataToRouteInfo: Map<RouteData, RouteInfo>;
#routeCache: RouteCache;
#encoder = new TextEncoder();
#logging = defaultLogOptions;
#logging: LogOptions = {
dest: consoleLogDestination,
level: 'info'
};

constructor(manifest: Manifest) {
this.#manifest = manifest;
this.#manifestData = {
routes: manifest.routes.map((route) => route.routeData),
};
this.#routeDataToRouteInfo = new Map(manifest.routes.map((route) => [route.routeData, route]));
this.#routeCache = new RouteCache(defaultLogOptions);
this.#routeCache = new RouteCache(this.#logging);
}
match(request: Request): RouteData | undefined {
const url = new URL(request.url);
Expand Down Expand Up @@ -105,7 +109,7 @@ export class App {
const url = new URL(request.url);
const handler = mod as unknown as EndpointHandler;
const result = await callEndpoint(handler, {
logging: defaultLogOptions,
logging: this.#logging,
origin: url.origin,
pathname: url.pathname,
request,
Expand Down
2 changes: 1 addition & 1 deletion src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { OutputAsset, OutputChunk, RollupOutput } from 'rollup';
import { fileURLToPath } from 'url';
import type { AstroConfig, ComponentInstance, EndpointHandler, SSRLoadedRenderer } from '../../@types/astro';
import type { BuildInternals } from '../../core/build/internal.js';
import { debug, info } from '../../core/logger.js';
import { debug, info } from '../logger/core.js';
import { appendForwardSlash, prependForwardSlash } from '../../core/path.js';
import type { RenderOptions } from '../../core/render/core';
import { BEFORE_HYDRATION_SCRIPT_ID } from '../../vite-plugin-scripts/index.js';
Expand Down
7 changes: 4 additions & 3 deletions src/core/build/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import type { AstroConfig, BuildConfig, ManifestData } from '../../@types/astro';
import type { LogOptions } from '../logger';
import type { LogOptions } from '../logger/core';

import fs from 'fs';
import * as colors from 'kleur/colors';
import { apply as applyPolyfill } from '../polyfill.js';
import { performance } from 'perf_hooks';
import * as vite from 'vite';
import { createVite, ViteConfigWithSSR } from '../create-vite.js';
import { debug, defaultLogOptions, info, levels, timerMessage, warn, warnIfUsingExperimentalSSR } from '../logger.js';
import { debug, info, levels, timerMessage, warn, warnIfUsingExperimentalSSR } from '../logger/core.js';
import { nodeLogOptions } from '../logger/node.js';
import { createRouteManifest } from '../routing/index.js';
import { generateSitemap } from '../render/sitemap.js';
import { collectPagesData } from './page-data.js';
Expand All @@ -25,7 +26,7 @@ export interface BuildOptions {
}

/** `astro build` */
export default async function build(config: AstroConfig, options: BuildOptions = { logging: defaultLogOptions }): Promise<void> {
export default async function build(config: AstroConfig, options: BuildOptions = { logging: nodeLogOptions }): Promise<void> {
applyPolyfill();
const builder = new AstroBuilder(config, options);
await builder.run();
Expand Down
6 changes: 3 additions & 3 deletions src/core/build/page-data.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { AstroConfig, ComponentInstance, ManifestData, RouteData } from '../../@types/astro';
import type { AllPagesData } from './types';
import type { LogOptions } from '../logger';
import { info } from '../logger.js';
import type { LogOptions } from '../logger/core';
import { info } from '../logger/core.js';
import type { ViteDevServer } from 'vite';

import { fileURLToPath } from 'url';
import * as colors from 'kleur/colors';
import { debug } from '../logger.js';
import { debug } from '../logger/core.js';
import { preload as ssrPreload } from '../render/dev/index.js';
import { generateRssFunction } from '../render/rss.js';
import { callGetStaticPaths, RouteCache, RouteCacheEntry } from '../render/route-cache.js';
Expand Down
2 changes: 1 addition & 1 deletion src/core/build/scan-based-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ViteDevServer } from 'vite';
import type { RollupOutput, RollupWatcher } from 'rollup';
import type { AstroConfig, RouteType } from '../../@types/astro';
import type { AllPagesData, PageBuildData } from './types';
import type { LogOptions } from '../logger';
import type { LogOptions } from '../logger/core';
import type { ViteConfigWithSSR } from '../create-vite.js';

import { fileURLToPath } from 'url';
Expand Down
25 changes: 18 additions & 7 deletions src/core/build/static-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import npath from 'path';
import { fileURLToPath } from 'url';
import * as vite from 'vite';
import { createBuildInternals } from '../../core/build/internal.js';
import { info } from '../../core/logger.js';
import { info } from '../logger/core.js';
import { appendForwardSlash, prependForwardSlash } from '../../core/path.js';
import { emptyDir, removeDir } from '../../core/util.js';
import { rollupPluginAstroBuildCSS } from '../../vite-plugin-build-css/index.js';
Expand All @@ -20,6 +20,7 @@ import { vitePluginPages } from './vite-plugin-pages.js';
import { generatePages } from './generate.js';
import { trackPageData } from './internal.js';
import { isBuildingToSSR } from '../util.js';
import { runHookBuildSetup } from '../../integrations/index.js';
import { getTimeStat } from './util.js';

export async function staticBuild(opts: StaticBuildOptions) {
Expand Down Expand Up @@ -112,8 +113,8 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
const { astroConfig, viteConfig } = opts;
const ssr = astroConfig.buildOptions.experimentalSsr;
const out = ssr ? opts.buildConfig.server : astroConfig.dist;
// TODO: use vite.mergeConfig() here?
return await vite.build({

const viteBuildConfig = {
logLevel: 'error',
mode: 'production',
css: viteConfig.css,
Expand All @@ -122,7 +123,6 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
emptyOutDir: false,
manifest: false,
outDir: fileURLToPath(out),
ssr: true,
rollupOptions: {
input: [],
output: {
Expand All @@ -132,6 +132,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
assetFileNames: 'assets/asset.[hash][extname]',
},
},
ssr: true,
// must match an esbuild target
target: 'esnext',
// improve build performance
Expand All @@ -156,7 +157,13 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
server: viteConfig.server,
base: astroConfig.buildOptions.site ? new URL(astroConfig.buildOptions.site).pathname : '/',
ssr: viteConfig.ssr,
} as ViteConfigWithSSR);
resolve: viteConfig.resolve
} as ViteConfigWithSSR;

await runHookBuildSetup({ config: astroConfig, vite: viteBuildConfig, target: 'server' });

// TODO: use vite.mergeConfig() here?
return await vite.build(viteBuildConfig);
}

async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals, input: Set<string>) {
Expand All @@ -173,7 +180,7 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals,

const out = isBuildingToSSR(astroConfig) ? opts.buildConfig.client : astroConfig.dist;

const buildResult = await vite.build({
const viteBuildConfig = {
logLevel: 'info',
mode: 'production',
css: viteConfig.css,
Expand Down Expand Up @@ -207,7 +214,11 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals,
envPrefix: 'PUBLIC_',
server: viteConfig.server,
base: appendForwardSlash(astroConfig.buildOptions.site ? new URL(astroConfig.buildOptions.site).pathname : '/'),
});
} as ViteConfigWithSSR;

await runHookBuildSetup({ config: astroConfig, vite: viteBuildConfig, target: 'client' });

const buildResult = await vite.build(viteBuildConfig);
info(opts.logging, null, dim(`Completed in ${getTimeStat(timer, performance.now())}.\n`));
return buildResult;
}
Expand Down
9 changes: 8 additions & 1 deletion src/core/create-vite.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { AstroConfig } from '../@types/astro';
import type { LogOptions } from './logger';
import type { LogOptions } from './logger/core';

import { builtinModules } from 'module';
import { fileURLToPath } from 'url';
Expand Down Expand Up @@ -81,6 +81,13 @@ export async function createVite(commandConfig: ViteConfigWithSSR, { astroConfig
css: {
postcss: astroConfig.styleOptions.postcss || {},
},
resolve: {
alias: {
// This is needed for Deno compatibility, as the non-browser version
// of this module depends on Node `crypto`
'randombytes': 'randombytes/browser'
}
},
// Note: SSR API is in beta (https://vitejs.dev/guide/ssr.html)
ssr: {
external: [...ALWAYS_EXTERNAL],
Expand Down
5 changes: 3 additions & 2 deletions src/core/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import * as vite from 'vite';
import type { AstroConfig } from '../../@types/astro';
import { runHookConfigDone, runHookConfigSetup, runHookServerDone, runHookServerSetup, runHookServerStart } from '../../integrations/index.js';
import { createVite } from '../create-vite.js';
import { defaultLogOptions, info, LogOptions, warn, warnIfUsingExperimentalSSR } from '../logger.js';
import { info, LogOptions, warn, warnIfUsingExperimentalSSR } from '../logger/core.js';
import { nodeLogOptions } from '../logger/node.js';
import * as msg from '../messages.js';
import { apply as applyPolyfill } from '../polyfill.js';
import { getResolvedHostForVite } from '../util.js';
Expand All @@ -19,7 +20,7 @@ export interface DevServer {
}

/** `astro dev` */
export default async function dev(config: AstroConfig, options: DevOptions = { logging: defaultLogOptions }): Promise<DevServer> {
export default async function dev(config: AstroConfig, options: DevOptions = { logging: nodeLogOptions }): Promise<DevServer> {
const devStart = performance.now();
applyPolyfill();
config = await runHookConfigSetup({ config, command: 'dev' });
Expand Down
Loading

0 comments on commit f976e1f

Please sign in to comment.