vize_atelier_sfc 0.71.0

Atelier SFC - The Single File Component workshop for Vize
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! SFC compilation implementation.
//!
//! This is the main entry point for compiling Vue Single File Components.
//! Following the Vue.js core structure, template/script/style compilation
//! is delegated to specialized modules.

mod bindings;
mod helpers;
mod normal_script;
mod styles;
#[cfg(test)]
mod tests;

use crate::compile_script::{compile_script_setup_inline_with_context, TemplateParts};
use crate::compile_template::{
    compile_template_block, compile_template_block_vapor, extract_template_parts,
    extract_template_parts_full, TemplateBlockCompileContext,
};
use crate::rewrite_default::rewrite_default;
use crate::script::ScriptCompileContext;
use crate::types::{BindingType, SfcCompileOptions, SfcCompileResult, SfcDescriptor, SfcError};

use self::bindings::{croquis_to_legacy_bindings, register_normal_script_bindings};
use self::helpers::{
    demote_v_model_reactive_const_bindings, extract_component_name, generate_scope_id,
};
use self::normal_script::extract_normal_script_content;
use self::styles::compile_styles;

// Re-export ScriptCompileResult for public API
pub use crate::compile_script::ScriptCompileResult;
use vize_carton::{profile, String, ToCompactString};

fn create_vapor_ssr_fallback_warning(descriptor: &SfcDescriptor) -> SfcError {
    SfcError {
        message: "SFC Vapor SSR is not supported yet; falling back to standard SSR output."
            .to_compact_string(),
        code: Some("VAPOR_SSR_FALLBACK".to_compact_string()),
        loc: descriptor
            .template
            .as_ref()
            .map(|template| template.loc.clone()),
    }
}

fn create_v_model_reactive_const_warning(
    script_setup: &crate::types::SfcScriptBlock<'_>,
    binding_name: &str,
) -> SfcError {
    let mut message = String::from("`v-model` cannot update the const reactive binding `");
    message.push_str(binding_name);
    message.push_str("`. The compiler transformed it to `let` so the update can work.");

    SfcError {
        message,
        code: Some("V_MODEL_CONST_REACTIVE_DEMOTED".to_compact_string()),
        loc: Some(script_setup.loc.clone()),
    }
}

fn is_ts_lang(lang: Option<&str>) -> bool {
    matches!(lang, Some("ts" | "tsx"))
}

/// Compile an SFC descriptor into JavaScript and CSS
pub fn compile_sfc(
    descriptor: &SfcDescriptor,
    options: SfcCompileOptions,
) -> Result<SfcCompileResult, SfcError> {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    let mut code = String::default();
    let mut css = None;

    let filename = options.script.id.as_deref().unwrap_or("anonymous.vue");

    let has_styles = !descriptor.styles.is_empty();
    let has_scoped = descriptor.styles.iter().any(|s| s.scoped);
    // Use externally-provided scope ID if available, otherwise generate from filename.
    // The external scope ID ensures consistency with JS-side SHA-256 generation.
    // Template/script-only SFCs do not need the hash.
    let needs_scope_id =
        has_styles || !descriptor.css_vars.is_empty() || options.scope_id.is_some();
    let scope_id = if needs_scope_id {
        options
            .scope_id
            .clone()
            .unwrap_or_else(|| generate_scope_id(filename))
    } else {
        String::default()
    };

    let vapor_requested = options.vapor
        || descriptor
            .script_setup
            .as_ref()
            .map(|s| s.attrs.contains_key("vapor"))
            .unwrap_or(false)
        || descriptor
            .script
            .as_ref()
            .map(|s| s.attrs.contains_key("vapor"))
            .unwrap_or(false);

    // Vapor components currently render on the client. For SSR we fall back to
    // the standard VDOM compiler and let the client hydrate with Vapor output.
    if descriptor.template.is_some() && options.template.ssr && vapor_requested {
        warnings.push(create_vapor_ssr_fallback_warning(descriptor));
    }
    let is_vapor = !options.template.ssr && vapor_requested;

    // is_ts controls output format:
    // - true: output TypeScript (add `: any` annotations, defineComponent wrapper)
    // - false: output JavaScript (strip TypeScript syntax from TS sources)
    // Source language detection is tracked separately in the script/setup branches below.
    let is_ts = options.script.is_ts || options.template.is_ts;
    let template_is_ts = options.template.is_ts
        || descriptor
            .script_setup
            .as_ref()
            .is_some_and(|s| is_ts_lang(s.lang.as_deref()))
        || descriptor
            .script
            .as_ref()
            .is_some_and(|s| is_ts_lang(s.lang.as_deref()));

    // Extract component name from filename
    let component_name = extract_component_name(filename);

    // Determine output mode based on script type
    let has_script_setup = descriptor.script_setup.is_some();
    let has_script = descriptor.script.is_some();
    let has_template = descriptor.template.is_some();

    // Case 1: Template only - just output render function
    if !has_script && !has_script_setup && has_template {
        let template = descriptor.template.as_ref().unwrap();
        let template_result = if is_vapor {
            profile!(
                "atelier.sfc.template.vapor",
                compile_template_block_vapor(
                    template,
                    &scope_id,
                    has_scoped,
                    None,
                    options.template.custom_renderer,
                )
            )
        } else {
            // Enable hoisting for template-only SFCs (hoisted consts go at module level)
            let mut template_opts = options.template.clone();
            let mut dom_opts = template_opts.compiler_options.take().unwrap_or_default();
            dom_opts.hoist_static = true;
            template_opts.compiler_options = Some(dom_opts);
            // Don't pass scope IDs to template compiler - scoped CSS is handled by
            // runtime __scopeId and CSS transformation, not by adding attributes
            // to template elements during compilation.
            profile!(
                "atelier.sfc.template.compile",
                compile_template_block(
                    template,
                    &template_opts,
                    TemplateBlockCompileContext {
                        scope_id: &scope_id,
                        apply_scope_id: options.template.ssr && has_scoped,
                        is_ts: template_is_ts,
                        component_name: Some(&component_name),
                        bindings: None,
                        croquis: None,
                    },
                )
            )
        };

        match template_result {
            Ok(template_code) => {
                code = template_code;
                if is_vapor {
                    code.push_str("const _sfc_main = { __vapor: true }\n");
                    code.push_str("_sfc_main.render = render\n");
                    code.push_str("export default _sfc_main\n");
                } else if options.template.ssr {
                    code.push_str("const _sfc_main = {}\n");
                    code.push_str("_sfc_main.ssrRender = ssrRender\n");
                    code.push_str("export default _sfc_main\n");
                }
            }
            Err(e) => errors.push(e),
        }

        // Compile styles
        let all_css = profile!(
            "atelier.sfc.styles",
            compile_styles(&descriptor.styles, &scope_id, &options.style, &mut warnings)
        );
        if !all_css.is_empty() {
            css = Some(all_css);
        }

        return Ok(SfcCompileResult {
            code,
            css,
            map: None,
            errors,
            warnings,
            bindings: None,
        });
    }

    // Case 2: Script (non-setup) + Template - rewrite default and compile template
    if has_script && !has_script_setup {
        let script = descriptor.script.as_ref().unwrap();

        // Check if source script is TypeScript
        let source_is_ts = script
            .lang
            .as_ref()
            .is_some_and(|l| l == "ts" || l == "tsx");

        // Rewrite `export default` to `const _sfc_main = ...`
        // Parse as TypeScript if source is TypeScript
        let (rewritten_script, _has_default) = profile!(
            "atelier.sfc.normal_script.rewrite_default",
            rewrite_default(&script.content, "_sfc_main", source_is_ts)
        );

        // Transpile TypeScript to JavaScript if needed
        let final_script = if source_is_ts && !is_ts {
            profile!(
                "atelier.sfc.normal_script.ts_to_js",
                crate::compile_script::typescript::transform_typescript_to_js(&rewritten_script)
            )
        } else {
            rewritten_script
        };

        // Compile template if present
        if has_template {
            let template = descriptor.template.as_ref().unwrap();
            let template_result = if is_vapor {
                profile!(
                    "atelier.sfc.template.vapor",
                    compile_template_block_vapor(
                        template,
                        &scope_id,
                        has_scoped,
                        None,
                        options.template.custom_renderer,
                    )
                )
            } else {
                let mut template_opts = options.template.clone();
                let mut dom_opts = template_opts.compiler_options.take().unwrap_or_default();
                dom_opts.hoist_static = true;
                template_opts.compiler_options = Some(dom_opts);

                // Don't pass scope IDs to template compiler - scoped CSS is handled by
                // runtime __scopeId and CSS transformation.
                profile!(
                    "atelier.sfc.template.compile",
                    compile_template_block(
                        template,
                        &template_opts,
                        TemplateBlockCompileContext {
                            scope_id: &scope_id,
                            apply_scope_id: options.template.ssr && has_scoped,
                            is_ts: template_is_ts,
                            component_name: Some(&component_name),
                            bindings: None,
                            croquis: None,
                        },
                    )
                )
            };

            match template_result {
                Ok(template_code) => {
                    // Build output matching Vue's compiler-sfc:
                    // 1. Full template output (imports + hoisted + export function render(...))
                    // 2. Rewritten script
                    // 3. _sfc_main.render = render / _sfc_main.ssrRender = ssrRender
                    // 4. export default _sfc_main
                    code.push_str(&template_code);
                    code.push_str(&final_script);
                    code.push('\n');

                    // Export the component with render attached
                    if is_vapor {
                        code.push_str("_sfc_main.__vapor = true\n");
                    }
                    if options.template.ssr {
                        code.push_str("_sfc_main.ssrRender = ssrRender\n");
                    } else {
                        code.push_str("_sfc_main.render = render\n");
                    }
                    code.push_str("export default _sfc_main\n");
                }
                Err(e) => {
                    errors.push(e);
                    // Fall back to just the script
                    code = script.content.to_compact_string();
                    code.push('\n');
                }
            }
        } else {
            // No template - just output rewritten script and export
            code.push_str(&final_script);
            if is_vapor {
                code.push_str("\n_sfc_main.__vapor = true");
            }
            code.push_str("\nexport default _sfc_main\n");
        }

        // Compile styles
        let all_css = profile!(
            "atelier.sfc.styles",
            compile_styles(&descriptor.styles, &scope_id, &options.style, &mut warnings)
        );
        if !all_css.is_empty() {
            css = Some(all_css);
        }

        return Ok(SfcCompileResult {
            code,
            css,
            map: None,
            errors,
            warnings,
            bindings: None,
        });
    }

    // Case 3: Script setup with inline template
    // If we reach here without script_setup, it means the SFC has no content
    let script_setup = match descriptor.script_setup.as_ref() {
        Some(s) => s,
        None => {
            return Err(SfcError {
                message:
                    "At least one <template> or <script> is required in a single file component."
                        .to_compact_string(),
                code: None,
                loc: None,
            });
        }
    };

    // Extract normal script content if present (for type definitions, imports, etc.)
    // When both <script> and <script setup> exist, normal script content should be preserved
    // (except for export default which is handled by script setup)
    let normal_script_content = if has_script {
        let script = descriptor.script.as_ref().unwrap();
        // Check if source is TypeScript
        let source_is_ts = script
            .lang
            .as_ref()
            .is_some_and(|l| l == "ts" || l == "tsx");
        Some(profile!(
            "atelier.sfc.normal_script.extract",
            extract_normal_script_content(&script.content, source_is_ts, is_ts)
        ))
    } else {
        None
    };

    // 1. Croquis parser: rich analysis with ReactivityTracker
    let mut croquis = profile!(
        "atelier.sfc.script_setup.croquis",
        crate::script::analyze_script_setup_to_summary(&script_setup.content)
    );
    let mut script_bindings = croquis_to_legacy_bindings(&croquis.bindings);
    let mut script_setup_content = script_setup.content.to_compact_string();

    // 2. ScriptCompileContext: needed for macro span info and TypeScript type resolution
    //    (Croquis doesn't resolve type references like `defineProps<Props>()`)
    let mut ctx = profile!(
        "atelier.sfc.script_context.new",
        ScriptCompileContext::new(&script_setup.content)
    );

    // Merge type definitions from normal <script> block so that
    // defineProps<TypeRef>() can resolve types defined there.
    if has_script {
        let script = descriptor.script.as_ref().unwrap();
        profile!(
            "atelier.sfc.script_context.collect_normal_types",
            ctx.collect_types_from(&script.content)
        );
    }
    profile!(
        "atelier.sfc.script_context.collect_setup_import_types",
        ctx.collect_imported_types_from_path(&script_setup.content, filename)
    );
    if has_script {
        let script = descriptor.script.as_ref().unwrap();
        profile!(
            "atelier.sfc.script_context.collect_normal_import_types",
            ctx.collect_imported_types_from_path(&script.content, filename)
        );
    }
    profile!("atelier.sfc.script_context.analyze", ctx.analyze());

    // 3. Merge Props bindings from ScriptCompileContext (type resolution fallback)
    //    Croquis can't resolve interface references, so we take Props from the legacy analyzer
    for (name, bt) in &ctx.bindings.bindings {
        if matches!(bt, BindingType::Props | BindingType::PropsAliased) {
            script_bindings.bindings.entry(name.clone()).or_insert(*bt);
        }
    }

    // Register $emit or __emit binding when defineEmits is used, so the template
    // compiler knows not to prefix it with _ctx.
    if let Some(ref emits_macro) = ctx.macros.define_emits {
        if let Some(ref binding_name) = emits_macro.binding_name {
            // e.g., const emit = defineEmits([...]) -> emit is setup const
            script_bindings
                .bindings
                .entry(binding_name.clone())
                .or_insert(BindingType::SetupConst);
        } else {
            // defineEmits([...]) without assignment -> $emit is exposed in setup args
            script_bindings
                .bindings
                .entry("$emit".to_compact_string())
                .or_insert(BindingType::SetupConst);
        }
    }

    // Register bindings from normal <script> block.
    // When both <script> and <script setup> exist, all imports and exported
    // variables from the normal script are accessible in the template.
    // This enables proper component resolution (e.g., `import { Form as PForm }`)
    // and identifier prefix resolution (avoiding incorrect `_ctx.` prefix).
    if has_script {
        let script = descriptor.script.as_ref().unwrap();
        profile!(
            "atelier.sfc.normal_script.register_bindings",
            register_normal_script_bindings(&script.content, &mut script_bindings)
        );
    }

    if let Some(template) = &descriptor.template {
        let demoted_ids = profile!(
            "atelier.sfc.script_setup.demote_v_model_reactive_consts",
            demote_v_model_reactive_const_bindings(
                &template.content,
                script_setup.lang.as_deref(),
                &mut script_setup_content,
                &mut ctx,
                &mut script_bindings,
                &mut croquis,
            )
        );

        for binding_name in demoted_ids {
            warnings.push(create_v_model_reactive_const_warning(
                script_setup,
                &binding_name,
            ));
        }
    }

    // Compile template with bindings (if present) to get the render function
    let template_result = if let Some(template) = &descriptor.template {
        if is_vapor {
            Some(profile!(
                "atelier.sfc.template.vapor",
                compile_template_block_vapor(
                    template,
                    &scope_id,
                    has_scoped,
                    Some(&script_bindings),
                    options.template.custom_renderer,
                )
            ))
        } else {
            // Don't pass scope IDs to template compiler - scoped CSS is handled by
            // runtime __scopeId and CSS transformation.
            Some(profile!(
                "atelier.sfc.template.compile",
                compile_template_block(
                    template,
                    &options.template,
                    TemplateBlockCompileContext {
                        scope_id: &scope_id,
                        apply_scope_id: options.template.ssr && has_scoped,
                        is_ts: template_is_ts,
                        component_name: Some(&component_name),
                        bindings: Some(&script_bindings),
                        croquis: Some(croquis),
                    },
                )
            ))
        }
    } else {
        None
    };

    // Extract template parts for inline mode (imports, hoisted, preamble, render_body)
    let (
        template_imports,
        template_hoisted,
        template_render_fn,
        template_render_fn_name,
        template_preamble,
        render_body,
    ) = match &template_result {
        Some(Ok(template_code)) => {
            if is_vapor || options.template.ssr {
                let (imports, hoisted, render_fn, render_fn_name) = profile!(
                    "atelier.sfc.template.extract_parts_full",
                    extract_template_parts_full(template_code)
                );
                (
                    imports,
                    hoisted,
                    render_fn,
                    render_fn_name,
                    String::default(),
                    String::default(),
                )
            } else {
                let (imports, hoisted, preamble, body, render_fn_name) = profile!(
                    "atelier.sfc.template.extract_parts",
                    extract_template_parts(template_code)
                );
                (
                    imports,
                    hoisted,
                    String::default(),
                    render_fn_name,
                    preamble,
                    body,
                )
            }
        }
        Some(Err(e)) => {
            errors.push(e.clone());
            (
                String::default(),
                String::default(),
                String::default(),
                "",
                String::default(),
                String::default(),
            )
        }
        None => (
            String::default(),
            String::default(),
            String::default(),
            "",
            String::default(),
            String::default(),
        ),
    };

    // Compile script setup using inline mode to match Vue's @vue/compiler-sfc output format:
    // 1. Template imports (from "vue")
    // 2. User imports
    // 3. Hoisted literal consts (module-level)
    // 4. export default { __name, props?, emits?, setup(__props) { ... return (_ctx, _cache) => { ... } } }
    // Detect if the source script setup uses TypeScript
    let source_is_ts = script_setup
        .lang
        .as_ref()
        .is_some_and(|l| l == "ts" || l == "tsx");

    let script_result = profile!(
        "atelier.sfc.script_setup.inline_compile",
        compile_script_setup_inline_with_context(
            ctx,
            &script_setup_content,
            &component_name,
            is_ts,
            source_is_ts,
            is_vapor,
            TemplateParts {
                imports: &template_imports,
                hoisted: &template_hoisted,
                render_fn: &template_render_fn,
                render_fn_name: template_render_fn_name,
                preamble: &template_preamble,
                render_body: &render_body,
                render_is_block: is_vapor,
            },
            normal_script_content.as_deref(),
            &descriptor.css_vars,
            &scope_id,
        )
    )?;

    // The inline mode compile_script_setup_inline generates a complete output
    // including imports, hoisted vars, and `export default { ... }` with inline render
    code.push_str(&script_result.code);

    // Compile styles
    let all_css = profile!(
        "atelier.sfc.styles",
        compile_styles(&descriptor.styles, &scope_id, &options.style, &mut warnings)
    );
    if !all_css.is_empty() {
        css = Some(all_css);
    }

    Ok(SfcCompileResult {
        code,
        css,
        map: None,
        errors,
        warnings,
        bindings: script_result.bindings,
    })
}