macroforge_ts 0.1.80

TypeScript macro expansion engine - write compile-time macros in Rust
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
use super::*;

// ==================== EARLY BAILOUT TESTS ====================

#[test]
fn test_early_bailout_no_derive_returns_unchanged() {
    // Code without @derive should be returned unchanged immediately

    let source = r#"
class User {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}
"#;

    let result = expand_test(source);

    assert!(
        !result.changed,
        "Code without @derive should be returned unchanged"
    );
    assert!(result.diagnostics.is_empty(), "No diagnostics expected");
}

#[test]
fn test_early_bailout_svelte_runes_unchanged() {
    // Svelte runes ($state, $derived) without @derive should be returned unchanged

    let source = r#"
let count = $state(0);
let double = $derived(count * 2);

function increment() {
    count++;
}
"#;

    let result = expand_test_file(source, "Counter.svelte.ts");

    // Svelte runes code should be returned exactly as-is
    assert!(
        !result.changed,
        "Svelte runes without @derive should be unchanged"
    );
    assert!(
        result.diagnostics.is_empty(),
        "No diagnostics for Svelte runes"
    );
}

#[test]
fn test_early_bailout_svelte_props_unchanged() {
    // Svelte $props() rune should be returned unchanged

    let source = r#"
interface Props {
    name: string;
    count?: number;
}

let { name, count = 0 }: Props = $props();
"#;

    let result = expand_test_file(source, "Component.svelte.ts");

    assert!(
        !result.changed,
        "Svelte $props() without @derive should be unchanged"
    );
    assert!(
        result.diagnostics.is_empty(),
        "No diagnostics for Svelte $props"
    );
}

#[test]
fn test_early_bailout_complex_svelte_component_unchanged() {
    // Complex Svelte component code without @derive should be returned unchanged

    let source = r#"
interface Props {
    items: string[];
    selected?: string;
}

let { items, selected = '' }: Props = $props();

let filteredItems = $derived(
    items.filter(item => item.includes(selected))
);

let count = $state(0);
let message = $derived.by(() => {
    if (count === 0) return 'No items';
    return `${count} items`;
});

function handleClick() {
    count++;
}

$effect(() => {
    console.log('Count changed:', count);
});
"#;

    let result = expand_test_file(source, "List.svelte.ts");

    assert!(
        !result.changed,
        "Complex Svelte code without @derive should be unchanged"
    );
    assert!(result.diagnostics.is_empty(), "No diagnostics expected");
}

#[test]
fn test_with_derive_processes_normally() {
    // Code WITH @derive should be processed normally

    let source = r#"
/** @derive(Debug) */
class User {
    name: string;
}
"#;

    let result = expand_test(source);

    // Should have processed the macro
    assert!(
        result.code.contains("toString"),
        "Debug macro should generate toString"
    );
    assert!(result.changed, "Code with @derive should be modified");
}

#[test]
fn test_derive_in_string_literal_still_skipped() {
    // @derive inside a string literal should still trigger processing
    // (we do a simple contains check, not parsing)

    let source = r#"
const msg = "Use @derive to add methods";
class User {
    name: string;
}
"#;

    let result = expand_test(source);

    // The contains("@derive") check will find the string literal
    // This is a conservative approach - we process the file but find no actual decorators
    // The result should have no errors and the code may have minor changes from parsing
    assert!(
        result
            .diagnostics
            .iter()
            .all(|d| d.level != DiagnosticLevel::Error),
        "No errors expected even with @derive in string literal"
    );
}

#[test]
fn test_early_bailout_empty_file() {
    // Empty file should be returned unchanged

    let source = "";
    let result = expand_test_file(source, "empty.ts");

    assert!(!result.changed, "Empty file should be returned unchanged");
    assert!(
        result.diagnostics.is_empty(),
        "No diagnostics for empty file"
    );
}

#[test]
fn test_early_bailout_only_comments() {
    // File with only comments should be returned unchanged

    let source = r#"
// This is a comment
/* Another comment */
/**
 * JSDoc comment without derive
 */
"#;

    let result = expand_test_file(source, "comments.ts");

    assert!(
        !result.changed,
        "Comments-only file should be returned unchanged"
    );
    assert!(
        result.diagnostics.is_empty(),
        "No diagnostics for comments-only file"
    );
}

#[test]
fn test_early_bailout_regular_typescript() {
    // Regular TypeScript without macros should be returned unchanged

    let source = r#"
interface User {
    id: string;
    name: string;
    email: string;
}

type Role = 'admin' | 'user' | 'guest';

enum Status {
    Active,
    Inactive,
    Pending
}

function createUser(name: string): User {
    return {
        id: crypto.randomUUID(),
        name,
        email: `${name}@example.com`
    };
}

const users: Map<string, User> = new Map();

export { User, Role, Status, createUser, users };
"#;

    let result = expand_test_file(source, "types.ts");

    assert!(
        !result.changed,
        "Regular TypeScript should be returned unchanged"
    );
    assert!(
        result.diagnostics.is_empty(),
        "No diagnostics for regular TypeScript"
    );
}

#[test]
fn test_no_false_positive_derive_in_prose_jsdoc() {
    // Regression test: `@derive` mentioned in prose doc comments (not as a directive)
    // should NOT trigger macro expansion. This file has zero actual macro annotations.
    let source = r#"
import type { Option } from "effect";
import { Exit } from "effect";
import type { Utc } from "effect/DateTime";

/** Deserialize result format from @derive(Deserialize) */
export type DeserializeResult<T> =
  | { success: true; value: T }
  | { success: false; errors: Array<{ field: string; message: string }> };

/** Converts a deserialize result to an Effect Exit */
export function toExit<T>(
  result: DeserializeResult<T>,
): Exit.Exit<T, Array<{ field: string; message: string }>> {
  if (result.success) {
    return Exit.succeed(result.value);
  } else {
    return Exit.fail(result.errors);
  }
}

/** Base interface for field controllers */
export interface FieldController<T> {
  readonly path: ReadonlyArray<string | number>;
  readonly name: string;
  readonly constraints: Record<string, unknown>;
  readonly label?: string;
  readonly description?: string;
  readonly placeholder?: string;
  readonly disabled?: boolean;
  readonly readonly?: boolean;
  get(): T;
  set(value: T): void;
  /** Transform input value before setting (applies configured format like uppercase, trim, etc.) */
  transform(value: T): T;
  getError(): Option.Option<Array<string>>;
  setError(value: Option.Option<Array<string>>): void;
  getTainted(): Option.Option<boolean>;
  setTainted(value: Option.Option<boolean>): void;
  validate(): Array<string>;
}

/** Number field controller with numeric constraints */
export interface NumberFieldController extends FieldController<number | null> {
  readonly min?: number;
  readonly max?: number;
  readonly step?: number;
}

/** Select field controller with options */
export interface SelectFieldController<T = string> extends FieldController<T> {
  readonly options: ReadonlyArray<{ label: string; value: T }>;
}

/** Toggle/boolean field controller */
export interface ToggleFieldController extends FieldController<boolean> {
  readonly styleClasses?: string;
}

/** Checkbox field controller */
export interface CheckboxFieldController extends FieldController<boolean> {
  readonly styleClasses?: string;
}

/** Switch field controller */
export type SwitchFieldController = FieldController<boolean>;

/** Text area field controller */
export type TextAreaFieldController = FieldController<string | null>;

/** Radio group option */
export interface RadioGroupOption {
  readonly label: string;
  readonly value: string;
  readonly icon?: unknown;
}

/** Radio group field controller */
export interface RadioGroupFieldController extends FieldController<string> {
  readonly options: ReadonlyArray<RadioGroupOption>;
  readonly orientation?: "horizontal" | "vertical";
}

/** Tags field controller (array of strings) */
export type TagsFieldController = FieldController<ReadonlyArray<string>>;

/** Combobox item type */
export interface ComboboxItem<T = unknown> {
  readonly label: string;
  readonly value: T;
}

/** Configuration for combobox fields that store graph edge objects */
export interface EdgeConfig {
  /** Field path within the edge object that references the entity (e.g. "in") */
  readonly entityField: string;
}

/** Combobox field controller */
export interface ComboboxFieldController<
  T = string,
> extends FieldController<T | null> {
  readonly items: ReadonlyArray<ComboboxItem<T>>;
  readonly allowCustom?: boolean;
  readonly roundedClass?: string;
  /** URLs to fetch items from (populated by @comboboxController({ fetchUrls: [...] })) */
  readonly fetchUrls?: ReadonlyArray<string>;
  /** Key path to extract the display label from fetched items (default: "name") */
  readonly itemLabelKeyName?: string;
  /** Key path to extract the value from fetched items (default: "id") */
  readonly itemValueKeyName?: string;
  /** Edge configuration for fields that store graph edges instead of direct entities */
  readonly edgeConfig?: EdgeConfig;
}

/** Combobox multiple field controller */
export interface ComboboxMultipleFieldController<
  T = string,
> extends FieldController<ReadonlyArray<T>> {
  readonly items: ReadonlyArray<ComboboxItem<T>>;
  readonly allowCustom?: boolean;
  readonly roundedClass?: string;
  /** URLs to fetch items from (populated by @comboboxController({ fetchUrls: [...] })) */
  readonly fetchUrls?: ReadonlyArray<string>;
  /** Key path to extract the display label from fetched items (default: "name") */
  readonly itemLabelKeyName?: string;
  /** Key path to extract the value from fetched items (default: "id") */
  readonly itemValueKeyName?: string;
  /** Edge configuration for fields that store graph edges instead of direct entities */
  readonly edgeConfig?: EdgeConfig;
}

/** Duration field controller - value is a [seconds, nanos] tuple */
export type DurationFieldController = FieldController<[number, number] | null>;

/** Date-time field controller */
export type DateTimeFieldController = FieldController<Utc | null>;

/** Date-only field controller (no time component) */
export type DateFieldController = FieldController<Utc | null>;

/** Multi-date picker field controller */
export type DatePickerMultipleFieldController = FieldController<Array<Utc> | null>;

/** Email field controller with subcontrollers */
export interface EmailFieldController extends FieldController<string | null> {
  /** Controller for the email string input */
  readonly emailController: FieldController<string | null>;
  /** Controller for the "can email" toggle */
  readonly canEmailController: FieldController<boolean>;
}

/** Phone field controller with subcontrollers */
export interface PhoneFieldController extends FieldController<unknown> {
  readonly phoneTypeController: ComboboxFieldController<string>;
  readonly numberController: FieldController<string | null>;
  readonly canCallController: ToggleFieldController;
  readonly canTextController: ToggleFieldController;
}

/** Enum/Variant field controller */
export interface EnumFieldController<
  TVariant extends string = string,
  TVariantControllers = { [K in TVariant]?: Record<string, FieldController<unknown>> },
> extends FieldController<{ type: TVariant; [key: string]: unknown } | null> {
  readonly variants: Record<
    TVariant,
    { label: string; fields?: Record<string, unknown> }
  >;
  readonly defaultVariant?: TVariant;
  /** Derived variant detected from the current value (tag field or shape matching). */
  readonly currentVariant: TVariant;
  readonly legend?: string;
  readonly selectLabel?: string;
  readonly variantControllers?: TVariantControllers;
}

/** Base interface for array field controllers */
export interface ArrayFieldController<T> extends FieldController<ReadonlyArray<T>> {
  at(index: number): FieldController<T>;
  push(value: T): void;
  remove(index: number): void;
  swap(a: number, b: number): void;
}

/** Item state for array fieldset items */
export interface ArrayFieldsetItem<T> {
  readonly _id: string;
  readonly isLeaving: boolean;
  readonly variant: "object" | "tuple";
  readonly val?: [PropertyKey, T];
}

/** Combobox hydration config for array fieldsets */
export interface ArrayFieldsetComboboxConfig<T = unknown> {
  readonly items: Array<{ label: string; value: T }>;
  readonly setItems?: (items: Array<{ label: string; value: T }>) => void;
  readonly itemLabelKeyName: string;
  readonly itemValueKeyName: string;
  readonly fetchConfigs: ReadonlyArray<{ url: string; schema?: unknown }>;
  readonly skipInitialFetch?: boolean;
}

/** Array fieldset controller with element controllers */
export interface ArrayFieldsetController<
  TItem,
  TElementControllers extends Record<string, FieldController<unknown>> = Record<
    string,
    FieldController<unknown>
  >,
> extends ArrayFieldController<TItem> {
  /** Template structure for new items */
  readonly itemStructure: TItem;
  /** Legend text for the fieldset */
  readonly legendText?: string;
  /** Radio group configuration for "main" item selection */
  readonly radioGroup?: {
    readonly mainFieldKey: string;
  };
  /** Whether to display items in card style */
  readonly card?: boolean;
  /** Whether items can be reordered via drag-and-drop */
  readonly reorderable?: boolean;
  /** Combobox fetch configurations for items */
  readonly comboboxFetchConfigs?: ReadonlyArray<ArrayFieldsetComboboxConfig>;
  /** Create element controllers for a specific item */
  elementControllers(context: {
    index: number;
    item: ArrayFieldsetItem<TItem>;
  }): TElementControllers;
}

/** Base Gigaform interface - generated forms extend this */
export interface BaseGigaform<TData> {
  data: TData;
  validate(): Exit.Exit<TData, Array<{ field: string; message: string }>>;
  asyncValidate(): Promise<
    Exit.Exit<TData, ReadonlyArray<{ field: string; message: string }>>
  >;
  reset(overrides: Partial<TData> | null): void;
}

/** Gigaform with variant support (for unions/enums) */
export interface VariantGigaform<
  TData,
  TVariant extends string,
> extends BaseGigaform<TData> {
  readonly currentVariant: TVariant;
  switchVariant(variant: TVariant): void;
}

/** Manual entry controllers for site address fields */
export interface SiteManualEntryControllers {
  readonly addressLine1: FieldController<string | null>;
  readonly addressLine2: FieldController<string | null>;
  readonly locality: FieldController<string | null>;
  readonly administrativeAreaLevel1: FieldController<string | null>;
  readonly postalCode: FieldController<string | null>;
  readonly country: FieldController<string | null>;
}

/** Filter configuration for duplicate site search */
export interface SiteDuplicateSearchFilters {
  readonly siteId?: string;
  readonly filters: ReadonlyArray<{
    field: string;
    op: string;
    value: unknown;
  }>;
}

/** Address lookup field controller for Google Places integration */
export interface AddressLookupFieldController<
  TSite = unknown,
> extends FieldController<TSite | null> {
  /** Label background class for floating label */
  readonly labelBgClass?: string;
}

/** Site fieldset controller with lookup and manual entry modes */
export interface SiteFieldsetController<
  TSite = unknown,
> extends FieldController<TSite | null> {
  /** Controller for Google Places address lookup */
  readonly lookupController: AddressLookupFieldController<TSite>;
  /** Controllers for manual address entry fields */
  readonly manualEntryControllers: SiteManualEntryControllers;
  /** Configuration for duplicate site search */
  readonly duplicateSearchFilters?: SiteDuplicateSearchFilters;
  /** Optional scrolling container getter for scroll position preservation */
  readonly scrollingContainer?: () => HTMLElement | null;
}

/** Wrapper for nullable nested struct field controllers */
export interface NullableControllers<_T> {
  isNull(): boolean;
  initialize(): void;
  clear(): void;
}
"#;

    // The quick-check used by expand_inner/expand_for_cache must reject this file
    // so it never reaches the expansion engine at all.
    assert!(
        !crate::expand_core::has_macro_annotations(source),
        "has_macro_annotations should return false for a file with @derive only in prose JSDoc"
    );

    {
        let result = expand_test(source);

        // File should NOT be changed — no actual macro annotations
        assert!(
            !result.changed,
            "File with @derive in prose JSDoc should NOT trigger expansion. Got changed=true with code:\n{}",
            result.code
        );

        // Should have zero error diagnostics
        let errors: Vec<_> = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .collect();
        assert!(
            errors.is_empty(),
            "Should have no errors for a file with no macros, got: {:?}",
            errors
        );
    }
}