Skip to content

Commit

Permalink
fix: relative sourcemaps for Vite 4.2 (#3422)
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat authored Mar 18, 2023
1 parent 3db12cc commit 8cd71f8
Show file tree
Hide file tree
Showing 102 changed files with 766 additions and 569 deletions.
443 changes: 261 additions & 182 deletions Cargo.lock

Large diffs are not rendered by default.

20 changes: 5 additions & 15 deletions packages/qwik-city/buildtime/vite/dev-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,14 @@ export function ssrDevMiddleware(ctx: BuildContext, server: ViteDevServer) {
const routeModulePaths = new WeakMap<RouteModule, string>();
try {
const { _deserializeData, _serializeData, _verifySerializable } =
await server.ssrLoadModule('@qwik-serializer', {
fixStacktrace: false,
});
await server.ssrLoadModule('@qwik-serializer');
const qwikSerializer = { _deserializeData, _serializeData, _verifySerializable };

// use vite to dynamically load each layout/page module in this route's hierarchy

const serverPlugins: RouteModule[] = [];
for (const file of ctx.serverPlugins) {
const layoutModule = await server.ssrLoadModule(file.filePath, {
fixStacktrace: false,
});
const layoutModule = await server.ssrLoadModule(file.filePath);
serverPlugins.push(layoutModule);
routeModulePaths.set(layoutModule, file.filePath);
}
Expand All @@ -105,15 +101,11 @@ export function ssrDevMiddleware(ctx: BuildContext, server: ViteDevServer) {

// found a matching route
for (const layout of route.layouts) {
const layoutModule = await server.ssrLoadModule(layout.filePath, {
fixStacktrace: false,
});
const layoutModule = await server.ssrLoadModule(layout.filePath);
routeModules.push(layoutModule);
routeModulePaths.set(layoutModule, layout.filePath);
}
const endpointModule = await server.ssrLoadModule(route.filePath, {
fixStacktrace: false,
});
const endpointModule = await server.ssrLoadModule(route.filePath);
routeModules.push(endpointModule);
routeModulePaths.set(endpointModule, route.filePath);
}
Expand Down Expand Up @@ -151,9 +143,7 @@ export function ssrDevMiddleware(ctx: BuildContext, server: ViteDevServer) {
let menu: ContentMenu | undefined = undefined;
const menus = ctx.menus.map((buildMenu) => {
const menuLoader: MenuModuleLoader = async () => {
const m = await server.ssrLoadModule(buildMenu.filePath, {
fixStacktrace: false,
});
const m = await server.ssrLoadModule(buildMenu.filePath);
const menuModule: MenuModule = {
default: m.default,
};
Expand Down
30 changes: 16 additions & 14 deletions packages/qwik-city/middleware/request-handler/user-response.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { QwikSerializer, ServerRequestEvent } from './types';
import type { RequestEvent, RequestHandler } from '@builder.io/qwik-city';
import { createRequestEvent, type RequestEventInternal } from './request-event';
import { createRequestEvent, getRequestMode, type RequestEventInternal } from './request-event';
import { ErrorResponse, getErrorHtml, minimalHtmlResponse } from './error-handler';
import { AbortMessage, RedirectMessage } from './redirect-handler';
import type { LoadedRoute } from '../../runtime/src/types';
Expand Down Expand Up @@ -53,20 +53,22 @@ async function runNext(requestEv: RequestEventInternal, resolve: (value: any) =>
requestEv.html(e.status, html);
}
} else if (!(e instanceof AbortMessage)) {
try {
if (!requestEv.headersSent) {
requestEv.headers.set('content-type', 'text/html; charset=utf-8');
requestEv.cacheControl({ noCache: true });
requestEv.status(500);
if (getRequestMode(requestEv) !== 'dev') {
try {
if (!requestEv.headersSent) {
requestEv.headers.set('content-type', 'text/html; charset=utf-8');
requestEv.cacheControl({ noCache: true });
requestEv.status(500);
}
const stream = requestEv.getWritableStream();
if (!stream.locked) {
const writer = stream.getWriter();
await writer.write(encoder.encode(minimalHtmlResponse(500, 'Internal Server Error')));
await writer.close();
}
} catch {
console.error('Unable to render error page');
}
const stream = requestEv.getWritableStream();
if (!stream.locked) {
const writer = stream.getWriter();
await writer.write(encoder.encode(minimalHtmlResponse(500, 'Internal Server Error')));
await writer.close();
}
} catch {
console.error('Unable to render error page');
}
return e;
}
Expand Down
1 change: 1 addition & 0 deletions packages/qwik/src/optimizer/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ fn optimize(
entry_strategy: optimizer_input.strategy,
explicit_extensions: optimizer_input.explicit_extensions,
core_module: optimizer_input.core_module,
root_dir: None,

mode: optimizer_input.mode,
scope: optimizer_input.scope,
Expand Down
22 changes: 11 additions & 11 deletions packages/qwik/src/optimizer/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,24 @@ categories = ["development-tools", "development-tools::cargo-plugins"]
crate-type = ["rlib"]

[dependencies]
swc_ecmascript = { version = "0.205.77", features = ["codegen", "utils", "visit", "parser", "transforms", "typescript", "react", "optimization"] }
swc_common = { version = "0.29.14", features = ["sourcemap"] }
swc_atoms = "0.4.24"
serde = "1.0.147"
serde_bytes = "0.11.7"
serde_json = "1.0.87"
swc_ecmascript = { version = "0.222.8", features = ["codegen", "utils", "visit", "parser", "transforms", "typescript", "react", "optimization"] }
swc_common = { version = "0.29.37", features = ["sourcemap"] }
swc_atoms = "0.4.39"
serde = "1.0.157"
serde_bytes = "0.11.9"
serde_json = "1.0.94"
simple-error = "0.2.3"
base64 = "0.13.1"
base64 = "0.21.0"
pathdiff = "0.2.1"
relative-path = "1.7.2"
relative-path = "1.8.0"
lazy_static = "1.4.0"
anyhow = "1.0.66"
anyhow = "1.0.70"
derivative = "2.2.0"
rayon = "1.5.3"
rayon = "1.7.0"
path-slash="0.2.1"

[dev-dependencies]
insta = "1.21.0"
insta = "1.28.0"

[features]
fs=[]
Expand Down
18 changes: 10 additions & 8 deletions packages/qwik/src/optimizer/core/src/code_move.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ pub fn generate_entries(
mut output: TransformOutput,
core_module: &JsWord,
explicit_extensions: bool,
root_dir: Option<&Path>,
) -> Result<TransformOutput, anyhow::Error> {
let source_map = Lrc::new(SourceMap::default());
let mut entries_map: BTreeMap<&str, Vec<&HookAnalysis>> = BTreeMap::new();
Expand All @@ -249,8 +250,9 @@ pub fn generate_entries(

for (entry, hooks) in &entries_map {
let module = new_entry_module(hooks, core_module, explicit_extensions);
let (code, map) = emit_source_code(Lrc::clone(&source_map), None, &module, false)
.context("Emitting source code")?;
let (code, map) =
emit_source_code(Lrc::clone(&source_map), None, &module, root_dir, false)
.context("Emitting source code")?;
new_modules.push(TransformModule {
path: [entry, ".js"].concat(),
code,
Expand Down Expand Up @@ -335,29 +337,29 @@ fn transform_arrow_fn(
scoped_idents: &[Id],
) -> ast::ArrowExpr {
match arrow.body {
ast::BlockStmtOrExpr::BlockStmt(mut block) => {
box ast::BlockStmtOrExpr::BlockStmt(mut block) => {
let mut stmts = Vec::with_capacity(1 + block.stmts.len());
stmts.push(create_use_lexical_scope(use_lexical_scope, scoped_idents));
stmts.append(&mut block.stmts);
ast::ArrowExpr {
body: ast::BlockStmtOrExpr::BlockStmt(ast::BlockStmt {
body: Box::new(ast::BlockStmtOrExpr::BlockStmt(ast::BlockStmt {
span: DUMMY_SP,
stmts,
}),
})),
..arrow
}
}
ast::BlockStmtOrExpr::Expr(expr) => {
box ast::BlockStmtOrExpr::Expr(expr) => {
let mut stmts = Vec::with_capacity(2);
if !scoped_idents.is_empty() {
stmts.push(create_use_lexical_scope(use_lexical_scope, scoped_idents));
}
stmts.push(create_return_stmt(expr));
ast::ArrowExpr {
body: ast::BlockStmtOrExpr::BlockStmt(ast::BlockStmt {
body: Box::new(ast::BlockStmtOrExpr::BlockStmt(ast::BlockStmt {
span: DUMMY_SP,
stmts,
}),
})),
..arrow
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/qwik/src/optimizer/core/src/filter_exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ fn empty_module_item(ident: ast::Ident) -> ast::ModuleItem {
return_type: None,
span: DUMMY_SP,
type_params: None,
body: ast::BlockStmtOrExpr::BlockStmt(ast::BlockStmt {
body: Box::new(ast::BlockStmtOrExpr::BlockStmt(ast::BlockStmt {
span: DUMMY_SP,
stmts: vec![ast::Stmt::Throw(ast::ThrowStmt {
span: DUMMY_SP,
Expand All @@ -74,7 +74,7 @@ fn empty_module_item(ident: ast::Ident) -> ast::ModuleItem {
raw: None,
}))),
})],
}),
})),
}))),
}],
})),
Expand Down
2 changes: 1 addition & 1 deletion packages/qwik/src/optimizer/core/src/inlined_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub fn convert_inlined_fn(

// Wrap around arrow functions
let expr = ast::Expr::Arrow(ast::ArrowExpr {
body: ast::BlockStmtOrExpr::Expr(Box::new(expr)),
body: Box::new(ast::BlockStmtOrExpr::Expr(Box::new(expr))),
is_async: false,
is_generator: false,
params,
Expand Down
26 changes: 21 additions & 5 deletions packages/qwik/src/optimizer/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,10 @@ use words::BUILDER_IO_QWIK;
#[cfg(feature = "fs")]
use std::fs;

#[cfg(feature = "fs")]
use std::path::Path;

use anyhow::Error;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::str;
use swc_atoms::JsWord;

Expand All @@ -56,6 +54,7 @@ pub use crate::parse::{ErrorBuffer, HookAnalysis, MinifyMode, TransformModule, T
#[serde(rename_all = "camelCase")]
pub struct TransformFsOptions {
pub src_dir: String,
pub root_dir: Option<String>,
pub vendor_roots: Vec<String>,
pub glob: Option<String>,
pub minify: MinifyMode,
Expand Down Expand Up @@ -88,6 +87,7 @@ pub struct TransformModuleInput {
#[serde(rename_all = "camelCase")]
pub struct TransformModulesOptions {
pub src_dir: String,
pub root_dir: Option<String>,
pub input: Vec<TransformModuleInput>,
pub source_maps: bool,
pub minify: MinifyMode,
Expand All @@ -114,6 +114,8 @@ pub fn transform_fs(config: TransformFsOptions) -> Result<TransformOutput, Error
.core_module
.map_or(BUILDER_IO_QWIK.clone(), |s| s.into());
let src_dir = Path::new(&config.src_dir);
let root_dir = config.root_dir.as_ref().map(Path::new);

let mut paths = vec![];
let entry_policy = &*parse_entry_strategy(&config.entry_strategy, config.manual_chunks);
crate::package_json::find_modules(src_dir, config.vendor_roots, &mut paths)?;
Expand All @@ -131,6 +133,7 @@ pub fn transform_fs(config: TransformFsOptions) -> Result<TransformOutput, Error
let relative_path = pathdiff::diff_paths(path, &config.src_dir).unwrap();
transform_code(TransformCodeOptions {
src_dir,
root_dir,
relative_path: relative_path.to_str().unwrap(),
minify: config.minify,
code: &code,
Expand All @@ -154,7 +157,12 @@ pub fn transform_fs(config: TransformFsOptions) -> Result<TransformOutput, Error
.reduce(|| Ok(TransformOutput::new()), |x, y| Ok(x?.append(&mut y?)))?;

final_output.modules.sort_unstable_by_key(|key| key.order);
final_output = generate_entries(final_output, &core_module, config.explicit_extensions)?;
final_output = generate_entries(
final_output,
&core_module,
config.explicit_extensions,
root_dir,
)?;
Ok(final_output)
}

Expand All @@ -163,6 +171,8 @@ pub fn transform_modules(config: TransformModulesOptions) -> Result<TransformOut
.core_module
.map_or(BUILDER_IO_QWIK.clone(), |s| s.into());
let src_dir = std::path::Path::new(&config.src_dir);
let root_dir = config.root_dir.as_ref().map(Path::new);

let entry_policy = &*parse_entry_strategy(&config.entry_strategy, config.manual_chunks);
#[cfg(feature = "parallel")]
let iterator = config.input.par_iter();
Expand All @@ -172,6 +182,7 @@ pub fn transform_modules(config: TransformModulesOptions) -> Result<TransformOut
let iterator = iterator.map(|path| -> Result<TransformOutput, Error> {
transform_code(TransformCodeOptions {
src_dir,
root_dir,
relative_path: &path.path,
code: &path.code,
minify: config.minify,
Expand Down Expand Up @@ -203,7 +214,12 @@ pub fn transform_modules(config: TransformModulesOptions) -> Result<TransformOut

let mut final_output = final_output?;
final_output.modules.sort_unstable_by_key(|key| key.order);
final_output = generate_entries(final_output, &core_module, config.explicit_extensions)?;
final_output = generate_entries(
final_output,
&core_module,
config.explicit_extensions,
root_dir,
)?;

Ok(final_output)
}
Loading

0 comments on commit 8cd71f8

Please sign in to comment.