vize_atelier_sfc 0.63.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
//! defineEmits macro handling.
//!
//! Handles the `defineEmits` Compiler Macro.
//!
//! Based on Vue.js official implementation:
//! https://github.com/vuejs/core/blob/main/packages/compiler-sfc/src/script/defineEmits.ts

use vize_carton::{FxHashSet, String, ToCompactString};

use oxc_ast::ast::{CallExpression, Expression, TSSignature, TSType, TSTypeLiteral};
use oxc_span::GetSpan;

use super::context::ScriptCompileContext;

pub const DEFINE_EMITS: &str = "defineEmits";

/// Result of processing defineEmits
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct DefineEmitsResult {
    /// Runtime declaration (the argument passed to defineEmits)
    pub runtime_decl: Option<String>,
    /// Type declaration (the type parameter)
    pub type_decl: Option<String>,
    /// The variable name this is assigned to (e.g., "emit")
    pub decl_id: Option<String>,
}

/// Process defineEmits call expression
///
/// Returns true if this was a defineEmits call, false otherwise.
/// Mutates ctx to store the emits information.
#[allow(dead_code)]
pub fn process_define_emits(
    ctx: &mut ScriptCompileContext,
    call: &CallExpression<'_>,
    source: &str,
    decl_id: Option<String>,
) -> bool {
    if !is_call_of(call, DEFINE_EMITS) {
        return false;
    }

    if ctx.has_define_emits_call {
        // In Vue, this would call ctx.error() - for now we just log
        eprintln!("duplicate {}() call", DEFINE_EMITS);
    }

    ctx.has_define_emits_call = true;

    // Store runtime declaration (first argument)
    let runtime_decl = if !call.arguments.is_empty() {
        let arg = &call.arguments[0];
        let start = arg.span().start as usize;
        let end = arg.span().end as usize;
        Some(String::from(source[start..end].trim()))
    } else {
        None
    };

    // Store type declaration (type parameter)
    let type_decl = call.type_arguments.as_ref().map(|params| {
        let start = params.span.start as usize;
        let end = params.span.end as usize;
        let type_str = &source[start..end];
        // Remove the < and > from type params
        if type_str.starts_with('<') && type_str.ends_with('>') {
            String::from(&type_str[1..type_str.len() - 1])
        } else {
            String::from(type_str)
        }
    });

    // Error if both type and runtime args are provided
    if runtime_decl.is_some() && type_decl.is_some() {
        eprintln!(
            "{}() cannot accept both type and non-type arguments at the same time. Use one or the other.",
            DEFINE_EMITS
        );
    }

    // Store emits info in macros
    ctx.emits_runtime_decl = runtime_decl;
    ctx.emits_type_decl = type_decl;
    ctx.emit_decl_id = decl_id;

    true
}

/// Generate runtime emits declaration
///
/// Returns the emits array/object as a string for use in the compiled output.
#[allow(dead_code)]
pub fn gen_runtime_emits(ctx: &ScriptCompileContext, model_names: &[String]) -> Option<String> {
    fn debug_string<T: std::fmt::Debug>(value: &T) -> String {
        let mut out = String::default();
        use std::fmt::Write as _;
        let _ = write!(&mut out, "{:?}", value);
        out
    }

    let mut emits_decl = String::default();

    if let Some(ref runtime_decl) = ctx.emits_runtime_decl {
        emits_decl = runtime_decl.trim().to_compact_string();
    } else if ctx.emits_type_decl.is_some() {
        let type_declared_emits = extract_runtime_emits(ctx);
        if !type_declared_emits.is_empty() {
            let emits: Vec<String> = type_declared_emits
                .into_iter()
                .map(|k| debug_string(&k)) // JSON.stringify equivalent
                .collect();
            let joined = emits.join(", ");
            let mut out = String::with_capacity(joined.len() + 2);
            out.push('[');
            out.push_str(&joined);
            out.push(']');
            emits_decl = out;
        }
    }

    // Merge with model emits if defineModel was called
    if !model_names.is_empty() {
        let model_emits: Vec<String> = model_names
            .iter()
            .map(|n| {
                let mut name = String::with_capacity(7 + n.len());
                name.push_str("update:");
                name.push_str(n);
                debug_string(&name)
            })
            .collect();
        let joined = model_emits.join(", ");
        let mut model_emits_decl = String::with_capacity(joined.len() + 2);
        model_emits_decl.push('[');
        model_emits_decl.push_str(&joined);
        model_emits_decl.push(']');

        if emits_decl.is_empty() {
            emits_decl = model_emits_decl;
        } else {
            // /*@__PURE__*/_mergeModels(emitsDecl, modelEmitsDecl)
            let mut merged = String::with_capacity(emits_decl.len() + model_emits_decl.len() + 26);
            merged.push_str("/*@__PURE__*/_mergeModels(");
            merged.push_str(&emits_decl);
            merged.push_str(", ");
            merged.push_str(&model_emits_decl);
            merged.push(')');
            emits_decl = merged;
        }
    }

    if emits_decl.is_empty() {
        None
    } else {
        Some(emits_decl)
    }
}

/// Extract runtime emits from type declaration
///
/// Parses the type declaration to extract event names.
#[allow(dead_code)]
pub fn extract_runtime_emits(ctx: &ScriptCompileContext) -> FxHashSet<String> {
    let mut emits = FxHashSet::default();

    let type_decl = match &ctx.emits_type_decl {
        Some(decl) => decl,
        None => return emits,
    };

    // Parse the type declaration to extract event names
    // This is a simplified implementation - the full implementation would need
    // to use OXC's type resolver to properly resolve union types, etc.

    // Handle TSFunctionType: (e: 'click') => void
    if type_decl.contains("=>") && !type_decl.contains('{') {
        if let Some(event_name) = extract_event_name_from_function_type(type_decl) {
            emits.insert(event_name);
        }
        return emits;
    }

    // Handle object/interface type: { (e: 'click'): void } or { click: [...] }
    extract_events_from_type_literal(type_decl, &mut emits);

    emits
}

/// Extract event name from a function type like (e: 'click') => void
fn extract_event_name_from_function_type(type_str: &str) -> Option<String> {
    // Look for pattern like (e: 'eventName') or (e: "eventName")
    let re = regex::Regex::new(r#"\(\s*\w+\s*:\s*['"]([^'"]+)['"]\s*[,)]"#).ok()?;
    re.captures(type_str)
        .and_then(|cap| cap.get(1).map(|m| m.as_str().to_compact_string()))
}

/// Extract events from a type literal (object type)
fn extract_events_from_type_literal(type_str: &str, emits: &mut FxHashSet<String>) {
    // Handle call signatures: { (e: 'click'): void; (e: 'update'): void }
    let call_sig_re =
        regex::Regex::new(r#"\(\s*\w+\s*:\s*['"]([^'"]+)['"]\s*(?:,\s*[^)]+)?\)\s*:"#).unwrap();
    for cap in call_sig_re.captures_iter(type_str) {
        if let Some(event_name) = cap.get(1) {
            emits.insert(event_name.as_str().to_compact_string());
        }
    }

    // Handle property syntax: { click: [...], update: [...] }
    // This is for the newer emit type syntax
    let prop_re = regex::Regex::new(r#"(?:^|[{;,])\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:"#).unwrap();
    for cap in prop_re.captures_iter(type_str) {
        if let Some(prop_name) = cap.get(1) {
            let name = prop_name.as_str();
            // Skip common type keywords
            if !matches!(name, "type" | "required" | "default" | "validator") {
                emits.insert(name.to_compact_string());
            }
        }
    }
}

/// Extract event names from AST (for OXC-based parsing)
#[allow(dead_code)]
pub fn extract_event_names_from_ts_type(
    ts_type: &TSType<'_>,
    emits: &mut FxHashSet<String>,
    #[allow(clippy::only_used_in_recursion)] source: &str,
) {
    match ts_type {
        TSType::TSFunctionType(func_type) => {
            // Extract from first parameter's type annotation
            if let Some(first_param) = func_type.params.items.first() {
                if let Some(type_ann) = &first_param.type_annotation {
                    extract_literal_values_from_ts_type(&type_ann.type_annotation, emits, source);
                }
            }
        }
        TSType::TSTypeLiteral(type_lit) => {
            extract_from_ts_type_literal(type_lit, emits, source);
        }
        TSType::TSUnionType(union) => {
            for member in union.types.iter() {
                extract_event_names_from_ts_type(member, emits, source);
            }
        }
        TSType::TSIntersectionType(intersection) => {
            for member in intersection.types.iter() {
                extract_event_names_from_ts_type(member, emits, source);
            }
        }
        TSType::TSParenthesizedType(paren) => {
            extract_event_names_from_ts_type(&paren.type_annotation, emits, source);
        }
        _ => {}
    }
}

/// Extract from TSTypeLiteral (object type with properties and call signatures)
fn extract_from_ts_type_literal(
    type_lit: &TSTypeLiteral<'_>,
    emits: &mut FxHashSet<String>,
    source: &str,
) {
    let mut has_property = false;
    let mut has_call_signature = false;

    // First pass: collect property names and check for call signatures
    for member in type_lit.members.iter() {
        match member {
            TSSignature::TSPropertySignature(prop) => {
                has_property = true;
                // Get the property key name
                if let Some(name) = get_property_key_name(&prop.key, source) {
                    emits.insert(name);
                }
            }
            TSSignature::TSCallSignatureDeclaration(_call) => {
                has_call_signature = true;
            }
            _ => {}
        }
    }

    // Error check: can't mix property syntax with call signatures
    if has_property && has_call_signature {
        eprintln!("defineEmits() type cannot mixed call signature and property syntax.");
    }

    // Second pass: extract from call signatures if no properties
    if has_call_signature && !has_property {
        for member in type_lit.members.iter() {
            if let TSSignature::TSCallSignatureDeclaration(call) = member {
                if let Some(first_param) = call.params.items.first() {
                    if let Some(type_ann) = &first_param.type_annotation {
                        extract_literal_values_from_ts_type(
                            &type_ann.type_annotation,
                            emits,
                            source,
                        );
                    }
                }
            }
        }
    }
}

/// Extract literal string values from a TSType (for event names)
fn extract_literal_values_from_ts_type(
    ts_type: &TSType<'_>,
    emits: &mut FxHashSet<String>,
    #[allow(clippy::only_used_in_recursion)] source: &str,
) {
    match ts_type {
        TSType::TSLiteralType(lit_type) => {
            match &lit_type.literal {
                oxc_ast::ast::TSLiteral::StringLiteral(s) => {
                    emits.insert(s.value.to_compact_string());
                }
                oxc_ast::ast::TSLiteral::NumericLiteral(n) => {
                    emits.insert(n.value.to_compact_string());
                }
                // Skip UnaryExpression and TemplateLiteral as per Vue's implementation
                _ => {}
            }
        }
        TSType::TSUnionType(union) => {
            for member in union.types.iter() {
                extract_literal_values_from_ts_type(member, emits, source);
            }
        }
        TSType::TSParenthesizedType(paren) => {
            extract_literal_values_from_ts_type(&paren.type_annotation, emits, source);
        }
        _ => {}
    }
}

/// Get property key name from a PropertyKey
fn get_property_key_name(key: &oxc_ast::ast::PropertyKey<'_>, _source: &str) -> Option<String> {
    match key {
        oxc_ast::ast::PropertyKey::StaticIdentifier(id) => Some(id.name.to_compact_string()),
        oxc_ast::ast::PropertyKey::StringLiteral(s) => Some(s.value.to_compact_string()),
        oxc_ast::ast::PropertyKey::NumericLiteral(n) => Some(n.value.to_compact_string()),
        _ => None,
    }
}

/// Check if call expression is of given name
fn is_call_of(call: &CallExpression<'_>, name: &str) -> bool {
    if let Expression::Identifier(id) = &call.callee {
        return id.name.as_str() == name;
    }
    false
}

#[cfg(test)]
mod tests {
    use vize_carton::{CompactString, FxHashSet, ToCompactString};

    use super::{
        extract_event_name_from_function_type, extract_events_from_type_literal, gen_runtime_emits,
        ScriptCompileContext,
    };

    fn snapshot_emits(emits: &FxHashSet<CompactString>) -> Vec<&str> {
        let mut emits: Vec<_> = emits.iter().map(|event| event.as_str()).collect();
        emits.sort_unstable();
        emits
    }

    #[test]
    fn test_extract_event_name_from_function_type() {
        let result = extract_event_name_from_function_type("(e: 'click') => void");
        assert_eq!(result, Some("click".to_compact_string()));

        let result = extract_event_name_from_function_type("(e: \"update\") => void");
        assert_eq!(result, Some("update".to_compact_string()));
    }

    #[test]
    fn test_extract_events_from_type_literal() {
        let mut emits = FxHashSet::default();
        extract_events_from_type_literal("{ (e: 'click'): void; (e: 'update'): void }", &mut emits);
        insta::assert_debug_snapshot!(snapshot_emits(&emits));
    }

    #[test]
    fn test_extract_events_call_signature_with_payload() {
        let mut emits = FxHashSet::default();
        extract_events_from_type_literal("{ (e: 'click', payload: MouseEvent): void }", &mut emits);
        insta::assert_debug_snapshot!(snapshot_emits(&emits));
    }

    #[test]
    fn test_gen_runtime_emits_empty() {
        let ctx = ScriptCompileContext::new("");
        let result = gen_runtime_emits(&ctx, &[]);
        assert!(result.is_none());
    }

    #[test]
    fn test_gen_runtime_emits_with_models() {
        let ctx = ScriptCompileContext::new("");
        let result = gen_runtime_emits(
            &ctx,
            &[
                "modelValue".to_compact_string(),
                "count".to_compact_string(),
            ],
        );
        assert!(result.is_some());
        let emits = result.unwrap();
        insta::assert_snapshot!(emits.as_str());
    }
}