#![allow(unused_must_use)] use super::*; use crate::transform::SegmentKind; use serde_json::to_string_pretty; use swc_atoms::Atom; macro_rules! snapshot_res { ($res: expr, $prefix: expr) => { match $res { Ok(v) => { let mut output: String = $prefix; for module in &v.modules { let is_entry = if module.is_entry { "(ENTRY POINT)" } else { "" }; output += format!( "\n============================= {} {}==\n\n{}\n\n{:?}", module.path, is_entry, module.code, module.map ) .as_str(); if let Some(segment) = &module.segment { let segment = to_string_pretty(&segment).unwrap(); output += &format!("\n/*\n{}\n*/", segment); } } output += format!( "\n== DIAGNOSTICS ==\n\n{}", to_string_pretty(&v.diagnostics).unwrap() ) .as_str(); insta::assert_snapshot!(output); } Err(err) => { insta::assert_snapshot!(err); } } }; } macro_rules! test_input { ($input: expr) => {{ let input = $input; let code = input.code.to_string(); let snapshot = input.snapshot; let res = test_input_fn(input); if snapshot { snapshot_res!(&res, format!("==INPUT==\n\n{}", code.to_string())); } res }}; } fn test_input_fn(input: TestInput) -> Result { let strip_exports: Option> = input .strip_exports .map(|v| v.into_iter().map(|s| Atom::from(s)).collect()); let reg_ctx_name: Option> = input .reg_ctx_name .map(|v| v.into_iter().map(|s| Atom::from(s)).collect()); let strip_ctx_name: Option> = input .strip_ctx_name .map(|v| v.into_iter().map(|s| Atom::from(s)).collect()); transform_modules(TransformModulesOptions { src_dir: input.src_dir, root_dir: input.root_dir, input: vec![TransformModuleInput { code: input.code.clone(), path: input.filename, dev_path: input.dev_path, }], source_maps: true, minify: input.minify, transpile_ts: input.transpile_ts, transpile_jsx: input.transpile_jsx, preserve_filenames: input.preserve_filenames, explicit_extensions: input.explicit_extensions, entry_strategy: input.entry_strategy, mode: input.mode, scope: input.scope, core_module: input.core_module, strip_exports, strip_ctx_name, reg_ctx_name, strip_event_handlers: input.strip_event_handlers, is_server: input.is_server, // filler to maintain line offsets }) } #[test] fn migrated_qrl_pure() { let code = include_str!("fixtures/migrated-qrl-pure.js").to_string(); for minify in [MinifyMode::None, MinifyMode::Simplify] { let output = test_input_fn(TestInput { code: code.clone(), filename: "node_modules/library/index.qwik.mjs".into(), entry_strategy: EntryStrategy::Smart, mode: EmitMode::Prod, minify, is_server: Some(false), ..TestInput::default() }) .unwrap(); let parent = output .modules .iter() .find(|module| module.segment.is_none()) .unwrap(); let calls: Vec<_> = parent .code .lines() .filter(|line| line.contains("qrl(")) .collect(); assert!(!calls.is_empty()); for call in calls { assert!(call.contains("/*#__PURE__*/"), "{call}"); } assert!(parent.code.contains("KEEP_SIDE_EFFECT")); let render = output .modules .iter() .find(|module| { module .segment .as_ref() .is_some_and(|segment| segment.display_name.ends_with("_App_component")) }) .unwrap(); assert!(render.code.contains("useRead")); assert!(render.code.contains("q_s_CCC333ccc33")); if matches!(minify, MinifyMode::Simplify) { snapshot_res!( Ok::<_, anyhow::Error>(output), format!("==INPUT==\n\n{}", code) ); } } } #[test] fn smart_visible_task_heavy_library() { test_input!(TestInput { code: include_str!("fixtures/smart-visible-task-heavy-library.tsx").to_string(), entry_strategy: EntryStrategy::Smart, transpile_ts: true, transpile_jsx: true, mode: EmitMode::Prod, ..TestInput::default() }); } #[test] fn smart_lifted_event_captures() { let code = include_str!("fixtures/smart-lifted-captures.tsx").to_string(); let result = test_input_fn(TestInput { code: code.clone(), entry_strategy: EntryStrategy::Smart, transpile_ts: true, transpile_jsx: true, mode: EmitMode::Prod, ..TestInput::default() }); let output = result.as_ref().unwrap(); let handlers: Vec<_> = output .modules .iter() .filter_map(|module| module.segment.as_ref()) .filter(|segment| segment.ctx_kind == SegmentKind::EventHandler) .collect(); assert_eq!(handlers.len(), 2); let lifted = handlers .iter() .find(|segment| { segment .param_names .as_ref() .is_some_and(|params| params.len() > 2) }) .unwrap(); assert!(!lifted.captures); assert!(lifted.entry.is_none()); assert_eq!( handlers .iter() .filter(|segment| segment.entry.is_none()) .count(), 2 ); let callback = output .modules .iter() .filter_map(|module| module.segment.as_ref()) .find(|segment| segment.ctx_name == "$") .unwrap(); let render = output .modules .iter() .filter_map(|module| module.segment.as_ref()) .find(|segment| segment.ctx_name == "component$") .unwrap(); assert!(render.entry.is_some()); assert_eq!(callback.entry, render.entry); let event = output .modules .iter() .filter_map(|module| module.segment.as_ref()) .find(|segment| segment.ctx_name == "event$") .unwrap(); assert!(event.entry.is_none()); snapshot_res!(&result, format!("==INPUT==\n\n{}", code)); } #[test] fn smart_event_qrl_alias_consumers() { for (event, render, separated) in [ ("alias", "", true), ("(alias)", "", true), ("[alias]", "", true), ("enabled ? alias : alias", "", true), ("() => alias()", "", true), ("alias", "alias();", false), ("alias", "unknown(alias);", false), ( "alias", "const View = alias; const rendered = ; consume(rendered);", false, ), ] { let output = test_input_fn(TestInput { code: format!( r#" import {{ $ as defer, component$, useSignal }} from '@qwik.dev/core'; export const App = component$(() => {{ const count = useSignal(0); const click = defer(() => count.value++); const alias = click; {render} return ))} ); }) "# .to_string(), transpile_ts: true, transpile_jsx: true, ..TestInput::default() }); } #[test] fn example_functional_component_capture_props() { test_input!(TestInput { code: r#" import { $, component$, useStore } from '@qwik.dev/core'; export const App = component$(({count, rest: [I2, {I3, v1: [I4], I5=v2, ...I6}, I7=v3, ...I8]}) => { const state = useStore({count: 0}); const {rest: [C2, {C3, v1: [C4], C5=v2, ...C6}, C7=v3, ...C8]} = foo(); return $(() => { return (
state.count += count + total }> {I2}{I3}{I4}{I5}{I6}{I7}{I8} {C2}{C3}{C4}{C5}{C6}{C7}{C8} {v1}{v2}{v3}
) }); }) "# .to_string(), transpile_ts: true, transpile_jsx: true, ..TestInput::default() }); } #[test] fn example_multi_capture() { test_input!(TestInput { code: r#" import { $, component$ } from '@qwik.dev/core'; export const Foo = component$(({foo}) => { const arg0 = 20; return $(() => { const fn = ({aaa}) => aaa; return (
{foo}{fn()}{arg0}
) }); }) export const Bar = component$(({bar}) => { return $(() => { return (
{bar}
) }); }) "# .to_string(), transpile_ts: true, ..TestInput::default() }); } #[test] fn example_dead_code() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; import { deps } from 'deps'; export const Foo = component$(({foo}) => { useMount$(() => { if (false) { deps(); } }); return (
); }) "# .to_string(), minify: MinifyMode::Simplify, ..TestInput::default() }); } #[test] fn example_with_tagname() { test_input!(TestInput { code: r#" import { $, component$ } from '@qwik.dev/core'; export const Foo = component$(() => { return $(() => { return (
) }); }, { tagName: "my-foo", }); "# .to_string(), ..TestInput::default() }); } #[test] fn example_with_style() { test_input!(TestInput { code: r#" import { $, component$, useStyles$ } from '@qwik.dev/core'; export const Foo = component$(() => { useStyles$('.class {}'); return (
); }, { tagName: "my-foo", }); "# .to_string(), ..TestInput::default() }); } #[test] fn example_props_optimization() { test_input!(TestInput { code: r#" import { $, component$, useTask$ } from '@qwik.dev/core'; import { CONST } from 'const'; const getValue = () => 0; export const Works = component$(({ count, some = 1+2, hello = CONST, stuff: hey, stuffDefault: hey2 = 123, ...rest}) => { console.log(hey, some); useTask$(({track}) => { track(() => count); console.log(count, rest, hey, some, hey2); }); return (
{count}
); }); export const NoWorks2 = component$(({count, stuff: {hey}}) => { console.log(hey); useTask$(({track}) => { track(() => count); console.log(count); }); return (
{count}
); }); export const DynamicDefaults = component$(({count, stuff = getValue(), other: value = getValue()}) => { console.log(stuff); useTask$(({track}) => { track(() => stuff); track(() => value); console.log(count, stuff, value); }); return (
{value}
); }); export const ReferencedDefault = component$(({first = getValue(second), second}) => (
{first}{second}
)); "# .to_string(), transpile_jsx: true, entry_strategy: EntryStrategy::Inline, transpile_ts: true, ..TestInput::default() }); } #[test] fn dynamic_props_defaults_do_not_subscribe_component() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; const getValue = () => 0; export const DynamicDefault = component$(({ value = getValue() }) => { console.log(value); return
{value}
; }); "# .to_string(), transpile_jsx: true, entry_strategy: EntryStrategy::Inline, transpile_ts: true, ..TestInput::default() }); } #[test] fn dynamic_props_defaults_in_separate_segments() { test_input!(TestInput { code: r#" import { $, component$, useSignal } from '@qwik.dev/core'; const defaults = { showDelay: 100, hideDelay: 200 }; export const Repro = component$(({ showDelay = defaults.showDelay, hideDelay = defaults.hideDelay }) => { const open = useSignal(false); const show$ = $(() => setTimeout(() => (open.value = true), showDelay)); const hide$ = $(() => setTimeout(() => (open.value = false), hideDelay)); return
; }); "# .to_string(), transpile_jsx: true, entry_strategy: EntryStrategy::Inline, transpile_ts: true, ..TestInput::default() }); } #[test] fn nested_segment_param_does_not_collide_with_captured_props() { test_input!(TestInput { code: r#" import { component$, useComputed$ } from '@qwik.dev/core'; export const Cmp = component$(({ isOpen, initialFee }) => { const networkFee = useComputed$(async ({ track }) => { const open = track(() => isOpen?.value ?? true); return open ? initialFee : 0; }); return
{networkFee.value}
; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn nested_segments_number_captured_raw_props() { test_input!(TestInput { code: r#" import { $, component$, useComputed$ } from '@qwik.dev/core'; export const Cmp = component$(({ isOpen, initialFee }) => { const networkFee = useComputed$(async ({ track }) => { const inner = $(() => track(() => isOpen.value) + initialFee); return inner; }); const other = useComputed$(({ track }) => { const deeper = useComputed$(({ track: t2 }) => t2(() => track(() => initialFee))); return deeper; }); return
{networkFee.value}{other.value}
; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn nested_segments_number_captured_raw_props_inline() { test_input!(TestInput { code: r#" import { $, component$, useComputed$ } from '@qwik.dev/core'; export const Cmp = component$(({ isOpen, initialFee }) => { const networkFee = useComputed$(async ({ track }) => { const inner = $(() => track(() => isOpen.value) + initialFee); return inner; }); const other = useComputed$(({ track }) => { const deeper = useComputed$(({ track: t2 }) => t2(() => track(() => initialFee))); return deeper; }); return
{networkFee.value}{other.value}
; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, entry_strategy: EntryStrategy::Inline, ..TestInput::default() }); } #[test] fn repeated_use_context_destructures_get_distinct_bindings() { test_input!(TestInput { code: r#" import { component$, useContext } from '@qwik.dev/core'; import { WalletsContextId, SessionContextId } from './ctx'; export const Cmp = component$(() => { const { wallets } = useContext(WalletsContextId); const { user } = useContext(SessionContextId); return
{wallets}{user}
; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn nested_destructure_rebinding_prop_name() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; export const Cmp = component$((props: { flag?: boolean; className?: string }) => { if (props.flag) { const { className, ...rest } = props; console.log(className, rest); } const { className, ...rest } = props; return
{JSON.stringify(rest)}
; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn destructured_props_as_jsx_tags() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; import { Fallback, fallback, getFallback } from './x'; export const Cmp = component$((props: { Model?: any; ui?: any; icons: any; 'my-icon': any }) => { const { Model = Fallback, ui = fallback, icons, 'my-icon': Icon } = props; return ( ); }); export const Cmp2 = component$(({ Model = getFallback() }: { Model?: any }) => { return ; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn destructured_props_as_jsx_tags_inline() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; import { Fallback, fallback, getFallback } from './x'; export const Cmp = component$((props: { Model?: any; ui?: any; icons: any; 'my-icon': any }) => { const { Model = Fallback, ui = fallback, icons, 'my-icon': Icon } = props; return ( ); }); export const Cmp2 = component$(({ Model = getFallback() }: { Model?: any }) => { return ; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, entry_strategy: EntryStrategy::Inline, ..TestInput::default() }); } #[test] fn captured_props_as_jsx_tags() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; import { Fallback, fallback, render } from './x'; export const Cmp = component$(({ Model = Fallback }: { Model?: any }) => { return
; }); export const Rows = component$(({ item, items }: any) => { return (
    {items.map((item: any, idx: number) => (
  • console.log(item)} onDblClick$={() => console.log(idx)} /> ))}
); }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn should_not_consolidate_locals_named_like_props() { test_input!(TestInput { code: r#" import { $, component$ } from '@qwik.dev/core'; import { render } from './x'; export const Nested = component$(({ Model }: { Model: any }) => { return ; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn destructured_prop_named_like_jsx_tag() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; export const Cmp = component$((props: { title: string; _Item: any }) => { const { title, _Item } = props; return <_Item>{title}; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn jsx_tag_names_are_not_segment_uses() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; import { icons } from './icons'; const div = Math.random(); const title = Math.random(); const Home = Math.random(); console.log(div, title, Home); export const Cmp = component$(() => { return
; }); "# .to_string(), transpile_jsx: true, transpile_ts: true, ..TestInput::default() }); } #[test] fn jsx_lowercase_tag_outside_segments() { test_input!(TestInput { code: r#" import { component$ } from '@qwik.dev/core'; const div = { size: 1 }; const span = { size: 2 }; console.log(span,
); const Label = () => label; export const Cmp = component$(() => { console.log(div); return