macroforge 0.1.78 → 0.1.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts DELETED
@@ -1,1341 +0,0 @@
1
- /* auto-generated by NAPI-RS */
2
- /* eslint-disable */
3
- /**
4
- * Wrapper around `NativePositionMapper` for NAPI compatibility.
5
- *
6
- * This provides the same functionality as `NativePositionMapper` but with a
7
- * different JavaScript class name. Used internally by [`NativePlugin::get_mapper`].
8
- */
9
- export declare class NativeMapper {
10
- /**
11
- * Creates a new mapper wrapping the given source mapping.
12
- *
13
- * # Arguments
14
- *
15
- * * `mapping` - The source mapping result from macro expansion
16
- */
17
- constructor(mapping: SourceMappingResult)
18
- /** Checks if this mapper has no mapping data. */
19
- isEmpty(): boolean
20
- /**
21
- * Converts a position in the original source to expanded source.
22
- * See [`NativePositionMapper::original_to_expanded`] for details.
23
- */
24
- originalToExpanded(pos: number): number
25
- /**
26
- * Converts a position in the expanded source back to original.
27
- * See [`NativePositionMapper::expanded_to_original`] for details.
28
- */
29
- expandedToOriginal(pos: number): number | null
30
- /**
31
- * Returns the name of the macro that generated code at the given position.
32
- * See [`NativePositionMapper::generated_by`] for details.
33
- */
34
- generatedBy(pos: number): string | null
35
- /**
36
- * Maps a span from expanded source to original source.
37
- * See [`NativePositionMapper::map_span_to_original`] for details.
38
- */
39
- mapSpanToOriginal(start: number, length: number): SpanResult | null
40
- /**
41
- * Maps a span from original source to expanded source.
42
- * See [`NativePositionMapper::map_span_to_expanded`] for details.
43
- */
44
- mapSpanToExpanded(start: number, length: number): SpanResult
45
- /**
46
- * Checks if a position is inside macro-generated code.
47
- * See [`NativePositionMapper::is_in_generated`] for details.
48
- */
49
- isInGenerated(pos: number): boolean
50
- }
51
-
52
- /**
53
- * The main plugin class for macro expansion with caching support.
54
- *
55
- * `NativePlugin` is designed to be instantiated once and reused across multiple
56
- * file processing operations. It maintains a cache of expansion results keyed
57
- * by filepath and version, enabling efficient incremental processing.
58
- *
59
- * # Thread Safety
60
- *
61
- * The plugin is thread-safe through the use of `Mutex` for internal state.
62
- * However, macro expansion itself runs in a separate thread with a 32MB stack
63
- * to prevent stack overflow during deep AST recursion.
64
- *
65
- * # Example
66
- *
67
- * ```javascript
68
- * // Create a single plugin instance (typically at startup)
69
- * const plugin = new NativePlugin();
70
- *
71
- * // Process files with caching
72
- * const result1 = plugin.process_file("src/foo.ts", code1, { version: "1" });
73
- * const result2 = plugin.process_file("src/foo.ts", code2, { version: "1" }); // Cache hit!
74
- * const result3 = plugin.process_file("src/foo.ts", code3, { version: "2" }); // Cache miss
75
- *
76
- * // Get a mapper for position translation
77
- * const mapper = plugin.get_mapper("src/foo.ts");
78
- * ```
79
- */
80
- export declare class NativePlugin {
81
- /**
82
- * Creates a new `NativePlugin` instance.
83
- *
84
- * Initializes the plugin with an empty cache and sets up a default log file
85
- * at `/tmp/macroforge-plugin.log` for debugging purposes.
86
- *
87
- * # Returns
88
- *
89
- * A new `NativePlugin` ready for processing files.
90
- *
91
- * # Side Effects
92
- *
93
- * Creates or clears the log file at `/tmp/macroforge-plugin.log`.
94
- */
95
- constructor()
96
- /**
97
- * Writes a message to the plugin's log file.
98
- *
99
- * Useful for debugging macro expansion issues in production environments.
100
- *
101
- * # Arguments
102
- *
103
- * * `message` - The message to log
104
- *
105
- * # Note
106
- *
107
- * Messages are appended to the log file. If the log file hasn't been
108
- * configured or cannot be written to, the message is silently dropped.
109
- */
110
- log(message: string): void
111
- /**
112
- * Sets the path for the plugin's log file.
113
- *
114
- * # Arguments
115
- *
116
- * * `path` - The file path to use for logging
117
- *
118
- * # Note
119
- *
120
- * This does not create the file; it will be created when the first
121
- * message is logged.
122
- */
123
- setLogFile(path: string): void
124
- /**
125
- * Processes a TypeScript file through the macro expansion system.
126
- *
127
- * This is the main entry point for file processing. It handles caching,
128
- * thread isolation (to prevent stack overflow), and error recovery.
129
- *
130
- * # Arguments
131
- *
132
- * * `_env` - NAPI environment (unused but required by NAPI)
133
- * * `filepath` - Path to the file (used for TSX detection and caching)
134
- * * `code` - The TypeScript source code to process
135
- * * `options` - Optional configuration for expansion and caching
136
- *
137
- * # Returns
138
- *
139
- * An [`ExpandResult`] containing the expanded code, diagnostics, and source mapping.
140
- *
141
- * # Errors
142
- *
143
- * Returns an error if:
144
- * - Thread spawning fails
145
- * - The worker thread panics (often due to stack overflow)
146
- * - Macro expansion fails internally
147
- *
148
- * # Performance
149
- *
150
- * - Uses a 32MB thread stack to prevent stack overflow during deep AST recursion
151
- * - Caches results by filepath and version for efficient incremental processing
152
- * - Early bailout for files without `@derive` decorators
153
- *
154
- * # Thread Safety
155
- *
156
- * Macro expansion runs in a separate thread because:
157
- * 1. SWC AST operations can be deeply recursive, exceeding default stack limits
158
- * 2. Node.js thread stack is typically only 2MB
159
- * 3. Panics in the worker thread are caught and reported gracefully
160
- */
161
- processFile(filepath: string, code: string, options?: ProcessFileOptions | undefined | null): ExpandResult
162
- /**
163
- * Retrieves a position mapper for a previously processed file.
164
- *
165
- * The mapper enables translation between original and expanded source positions,
166
- * which is essential for IDE features like error reporting and navigation.
167
- *
168
- * # Arguments
169
- *
170
- * * `filepath` - Path to the file (must have been previously processed)
171
- *
172
- * # Returns
173
- *
174
- * `Some(NativeMapper)` if the file has been processed and has source mapping data,
175
- * `None` if the file hasn't been processed or has no mapping (no macros expanded).
176
- */
177
- getMapper(filepath: string): NativeMapper | null
178
- /**
179
- * Maps diagnostics from expanded source positions back to original source positions.
180
- *
181
- * This is used by IDE integrations to show errors at the correct locations
182
- * in the user's original code, rather than in the macro-expanded output.
183
- *
184
- * # Arguments
185
- *
186
- * * `filepath` - Path to the file the diagnostics are for
187
- * * `diags` - Diagnostics with positions in the expanded source
188
- *
189
- * # Returns
190
- *
191
- * Diagnostics with positions mapped back to the original source.
192
- * If no mapper is available for the file, returns diagnostics unchanged.
193
- */
194
- mapDiagnostics(filepath: string, diags: Array<JsDiagnostic>): Array<JsDiagnostic>
195
- }
196
-
197
- /**
198
- * Bidirectional position mapper for translating between original and expanded source positions.
199
- *
200
- * This mapper enables IDE features like error reporting, go-to-definition, and hover
201
- * to work correctly with macro-expanded code by translating positions between the
202
- * original source (what the user wrote) and the expanded source (what the compiler sees).
203
- *
204
- * # Performance
205
- *
206
- * Position lookups use binary search for O(log n) complexity, where n is the number
207
- * of mapping segments. This is critical for responsive IDE interactions.
208
- *
209
- * # Example
210
- *
211
- * ```javascript
212
- * const mapper = new PositionMapper(sourceMapping);
213
- *
214
- * // Convert original position to expanded
215
- * const expandedPos = mapper.original_to_expanded(42);
216
- *
217
- * // Convert expanded position back to original (if not in generated code)
218
- * const originalPos = mapper.expanded_to_original(100);
219
- *
220
- * // Check if a position is in macro-generated code
221
- * if (mapper.is_in_generated(pos)) {
222
- * const macro = mapper.generated_by(pos); // e.g., "Debug"
223
- * }
224
- * ```
225
- */
226
- export declare class PositionMapper {
227
- /**
228
- * Creates a new position mapper from source mapping data.
229
- *
230
- * # Arguments
231
- *
232
- * * `mapping` - The source mapping result from macro expansion
233
- *
234
- * # Returns
235
- *
236
- * A new `NativePositionMapper` ready for position translation.
237
- */
238
- constructor(mapping: SourceMappingResult)
239
- /**
240
- * Checks if this mapper has no mapping data.
241
- *
242
- * An empty mapper indicates no transformations occurred, so position
243
- * translation is an identity operation.
244
- *
245
- * # Returns
246
- *
247
- * `true` if there are no segments and no generated regions.
248
- */
249
- isEmpty(): boolean
250
- /**
251
- * Converts a position in the original source to the corresponding position in expanded source.
252
- *
253
- * Uses binary search for O(log n) lookup performance.
254
- *
255
- * # Arguments
256
- *
257
- * * `pos` - Byte offset in the original source
258
- *
259
- * # Returns
260
- *
261
- * The corresponding byte offset in the expanded source. If the position falls
262
- * in a gap between segments, returns the position unchanged. If after the last
263
- * segment, extrapolates based on the delta.
264
- *
265
- * # Algorithm
266
- *
267
- * 1. Binary search to find the segment containing or after `pos`
268
- * 2. If inside a segment, compute offset within segment and translate
269
- * 3. If after all segments, extrapolate from the last segment
270
- * 4. Otherwise, return position unchanged (gap or before first segment)
271
- */
272
- originalToExpanded(pos: number): number
273
- /**
274
- * Converts a position in the expanded source back to the original source position.
275
- *
276
- * Returns `None` if the position is inside macro-generated code that has no
277
- * corresponding location in the original source.
278
- *
279
- * # Arguments
280
- *
281
- * * `pos` - Byte offset in the expanded source
282
- *
283
- * # Returns
284
- *
285
- * `Some(original_pos)` if the position maps to original code,
286
- * `None` if the position is in macro-generated code.
287
- */
288
- expandedToOriginal(pos: number): number | null
289
- /**
290
- * Returns the name of the macro that generated code at the given position.
291
- *
292
- * # Arguments
293
- *
294
- * * `pos` - Byte offset in the expanded source
295
- *
296
- * # Returns
297
- *
298
- * `Some(macro_name)` if the position is inside generated code (e.g., "Debug"),
299
- * `None` if the position is in original (non-generated) code.
300
- */
301
- generatedBy(pos: number): string | null
302
- /**
303
- * Maps a span (start + length) from expanded source to original source.
304
- *
305
- * # Arguments
306
- *
307
- * * `start` - Start byte offset in expanded source
308
- * * `length` - Length of the span in bytes
309
- *
310
- * # Returns
311
- *
312
- * `Some(SpanResult)` with the mapped span in original source,
313
- * `None` if either endpoint is in generated code.
314
- */
315
- mapSpanToOriginal(start: number, length: number): SpanResult | null
316
- /**
317
- * Maps a span (start + length) from original source to expanded source.
318
- *
319
- * This always succeeds since every original position has an expanded equivalent.
320
- *
321
- * # Arguments
322
- *
323
- * * `start` - Start byte offset in original source
324
- * * `length` - Length of the span in bytes
325
- *
326
- * # Returns
327
- *
328
- * A `SpanResult` with the mapped span in expanded source.
329
- */
330
- mapSpanToExpanded(start: number, length: number): SpanResult
331
- /**
332
- * Checks if a position is inside macro-generated code.
333
- *
334
- * # Arguments
335
- *
336
- * * `pos` - Byte offset in the expanded source
337
- *
338
- * # Returns
339
- *
340
- * `true` if the position is inside a generated region, `false` otherwise.
341
- */
342
- isInGenerated(pos: number): boolean
343
- }
344
- export type NativePositionMapper = PositionMapper
345
-
346
- /**
347
- * Returns debug information about all registered macro descriptors (debug API).
348
- *
349
- * This provides low-level access to the inventory-based macro registration
350
- * system for debugging purposes.
351
- *
352
- * # Returns
353
- *
354
- * A vector of strings describing each registered macro descriptor.
355
- */
356
- export declare function __macroforgeDebugDescriptors(): Array<string>
357
-
358
- /**
359
- * Returns all registered macro module names (debug API).
360
- *
361
- * Modules group related macros together (e.g., "builtin", "serde").
362
- *
363
- * # Returns
364
- *
365
- * A vector of module names.
366
- */
367
- export declare function __macroforgeDebugGetModules(): Array<string>
368
-
369
- /**
370
- * Looks up a macro by module and name (debug API).
371
- *
372
- * Useful for testing macro registration and debugging lookup issues.
373
- *
374
- * # Arguments
375
- *
376
- * * `module` - The module name (e.g., "builtin")
377
- * * `name` - The macro name (e.g., "Debug")
378
- *
379
- * # Returns
380
- *
381
- * A string describing whether the macro was found or not.
382
- */
383
- export declare function __macroforgeDebugLookup(module: string, name: string): string
384
-
385
- /**
386
- * Returns the names of all registered macros.
387
- *
388
- * # Returns
389
- *
390
- * A vector of macro names (e.g., `["Debug", "Clone", "Serialize"]`).
391
- */
392
- export declare function __macroforgeGetMacroNames(): Array<string>
393
-
394
- /**
395
- * Returns the complete manifest of all registered macros and decorators.
396
- *
397
- * This is a debug/introspection API that allows tooling to discover
398
- * what macros are available at runtime.
399
- *
400
- * # Returns
401
- *
402
- * A [`MacroManifest`] containing all registered macros and decorators.
403
- *
404
- * # Example (JavaScript)
405
- *
406
- * ```javascript
407
- * const manifest = __macroforgeGetManifest();
408
- * console.log("Available macros:", manifest.macros.map(m => m.name));
409
- * // ["Debug", "Clone", "PartialEq", "Hash", "Serialize", "Deserialize", ...]
410
- * ```
411
- */
412
- export declare function __macroforgeGetManifest(): MacroManifest
413
-
414
- /**
415
- * Checks if any macros are registered in this package.
416
- *
417
- * Useful for build tools to determine if macro expansion is needed.
418
- *
419
- * # Returns
420
- *
421
- * `true` if at least one macro is registered, `false` otherwise.
422
- */
423
- export declare function __macroforgeIsMacroPackage(): boolean
424
-
425
- /**
426
- * r" Run this macro with the given context.
427
- * r"
428
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
429
- * r" It deserializes the macro context from JSON, executes the macro transformation,
430
- * r" and serializes the result back to JSON for the TypeScript plugin.
431
- * r"
432
- * r" # Arguments
433
- * r"
434
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
435
- * r" - `target_source`: The TypeScript source code to transform
436
- * r" - `file_name`: The source file path for error reporting
437
- * r" - Additional context metadata
438
- * r"
439
- * r" # Returns
440
- * r"
441
- * r" A JSON string containing the [`MacroResult`] with the transformed code
442
- * r" or any diagnostic errors.
443
- * r"
444
- * r" # Errors
445
- * r"
446
- * r" Returns a NAPI error if:
447
- * r" - The input JSON cannot be parsed
448
- * r" - The `TsStream` cannot be created from the context
449
- * r" - The result cannot be serialized to JSON
450
- */
451
- export declare function __macroforgeRunClone(contextJson: string): string
452
-
453
- /**
454
- * r" Run this macro with the given context.
455
- * r"
456
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
457
- * r" It deserializes the macro context from JSON, executes the macro transformation,
458
- * r" and serializes the result back to JSON for the TypeScript plugin.
459
- * r"
460
- * r" # Arguments
461
- * r"
462
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
463
- * r" - `target_source`: The TypeScript source code to transform
464
- * r" - `file_name`: The source file path for error reporting
465
- * r" - Additional context metadata
466
- * r"
467
- * r" # Returns
468
- * r"
469
- * r" A JSON string containing the [`MacroResult`] with the transformed code
470
- * r" or any diagnostic errors.
471
- * r"
472
- * r" # Errors
473
- * r"
474
- * r" Returns a NAPI error if:
475
- * r" - The input JSON cannot be parsed
476
- * r" - The `TsStream` cannot be created from the context
477
- * r" - The result cannot be serialized to JSON
478
- */
479
- export declare function __macroforgeRunDebug(contextJson: string): string
480
-
481
- /**
482
- * r" Run this macro with the given context.
483
- * r"
484
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
485
- * r" It deserializes the macro context from JSON, executes the macro transformation,
486
- * r" and serializes the result back to JSON for the TypeScript plugin.
487
- * r"
488
- * r" # Arguments
489
- * r"
490
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
491
- * r" - `target_source`: The TypeScript source code to transform
492
- * r" - `file_name`: The source file path for error reporting
493
- * r" - Additional context metadata
494
- * r"
495
- * r" # Returns
496
- * r"
497
- * r" A JSON string containing the [`MacroResult`] with the transformed code
498
- * r" or any diagnostic errors.
499
- * r"
500
- * r" # Errors
501
- * r"
502
- * r" Returns a NAPI error if:
503
- * r" - The input JSON cannot be parsed
504
- * r" - The `TsStream` cannot be created from the context
505
- * r" - The result cannot be serialized to JSON
506
- */
507
- export declare function __macroforgeRunDefault(contextJson: string): string
508
-
509
- /**
510
- * r" Run this macro with the given context.
511
- * r"
512
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
513
- * r" It deserializes the macro context from JSON, executes the macro transformation,
514
- * r" and serializes the result back to JSON for the TypeScript plugin.
515
- * r"
516
- * r" # Arguments
517
- * r"
518
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
519
- * r" - `target_source`: The TypeScript source code to transform
520
- * r" - `file_name`: The source file path for error reporting
521
- * r" - Additional context metadata
522
- * r"
523
- * r" # Returns
524
- * r"
525
- * r" A JSON string containing the [`MacroResult`] with the transformed code
526
- * r" or any diagnostic errors.
527
- * r"
528
- * r" # Errors
529
- * r"
530
- * r" Returns a NAPI error if:
531
- * r" - The input JSON cannot be parsed
532
- * r" - The `TsStream` cannot be created from the context
533
- * r" - The result cannot be serialized to JSON
534
- */
535
- export declare function __macroforgeRunDeserialize(contextJson: string): string
536
-
537
- /**
538
- * r" Run this macro with the given context.
539
- * r"
540
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
541
- * r" It deserializes the macro context from JSON, executes the macro transformation,
542
- * r" and serializes the result back to JSON for the TypeScript plugin.
543
- * r"
544
- * r" # Arguments
545
- * r"
546
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
547
- * r" - `target_source`: The TypeScript source code to transform
548
- * r" - `file_name`: The source file path for error reporting
549
- * r" - Additional context metadata
550
- * r"
551
- * r" # Returns
552
- * r"
553
- * r" A JSON string containing the [`MacroResult`] with the transformed code
554
- * r" or any diagnostic errors.
555
- * r"
556
- * r" # Errors
557
- * r"
558
- * r" Returns a NAPI error if:
559
- * r" - The input JSON cannot be parsed
560
- * r" - The `TsStream` cannot be created from the context
561
- * r" - The result cannot be serialized to JSON
562
- */
563
- export declare function __macroforgeRunHash(contextJson: string): string
564
-
565
- /**
566
- * r" Run this macro with the given context.
567
- * r"
568
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
569
- * r" It deserializes the macro context from JSON, executes the macro transformation,
570
- * r" and serializes the result back to JSON for the TypeScript plugin.
571
- * r"
572
- * r" # Arguments
573
- * r"
574
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
575
- * r" - `target_source`: The TypeScript source code to transform
576
- * r" - `file_name`: The source file path for error reporting
577
- * r" - Additional context metadata
578
- * r"
579
- * r" # Returns
580
- * r"
581
- * r" A JSON string containing the [`MacroResult`] with the transformed code
582
- * r" or any diagnostic errors.
583
- * r"
584
- * r" # Errors
585
- * r"
586
- * r" Returns a NAPI error if:
587
- * r" - The input JSON cannot be parsed
588
- * r" - The `TsStream` cannot be created from the context
589
- * r" - The result cannot be serialized to JSON
590
- */
591
- export declare function __macroforgeRunOrd(contextJson: string): string
592
-
593
- /**
594
- * r" Run this macro with the given context.
595
- * r"
596
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
597
- * r" It deserializes the macro context from JSON, executes the macro transformation,
598
- * r" and serializes the result back to JSON for the TypeScript plugin.
599
- * r"
600
- * r" # Arguments
601
- * r"
602
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
603
- * r" - `target_source`: The TypeScript source code to transform
604
- * r" - `file_name`: The source file path for error reporting
605
- * r" - Additional context metadata
606
- * r"
607
- * r" # Returns
608
- * r"
609
- * r" A JSON string containing the [`MacroResult`] with the transformed code
610
- * r" or any diagnostic errors.
611
- * r"
612
- * r" # Errors
613
- * r"
614
- * r" Returns a NAPI error if:
615
- * r" - The input JSON cannot be parsed
616
- * r" - The `TsStream` cannot be created from the context
617
- * r" - The result cannot be serialized to JSON
618
- */
619
- export declare function __macroforgeRunPartialEq(contextJson: string): string
620
-
621
- /**
622
- * r" Run this macro with the given context.
623
- * r"
624
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
625
- * r" It deserializes the macro context from JSON, executes the macro transformation,
626
- * r" and serializes the result back to JSON for the TypeScript plugin.
627
- * r"
628
- * r" # Arguments
629
- * r"
630
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
631
- * r" - `target_source`: The TypeScript source code to transform
632
- * r" - `file_name`: The source file path for error reporting
633
- * r" - Additional context metadata
634
- * r"
635
- * r" # Returns
636
- * r"
637
- * r" A JSON string containing the [`MacroResult`] with the transformed code
638
- * r" or any diagnostic errors.
639
- * r"
640
- * r" # Errors
641
- * r"
642
- * r" Returns a NAPI error if:
643
- * r" - The input JSON cannot be parsed
644
- * r" - The `TsStream` cannot be created from the context
645
- * r" - The result cannot be serialized to JSON
646
- */
647
- export declare function __macroforgeRunPartialOrd(contextJson: string): string
648
-
649
- /**
650
- * r" Run this macro with the given context.
651
- * r"
652
- * r" This function is automatically generated and exposed to JavaScript via NAPI.
653
- * r" It deserializes the macro context from JSON, executes the macro transformation,
654
- * r" and serializes the result back to JSON for the TypeScript plugin.
655
- * r"
656
- * r" # Arguments
657
- * r"
658
- * r" * `context_json` - A JSON string containing the [`MacroContextIR`] with:
659
- * r" - `target_source`: The TypeScript source code to transform
660
- * r" - `file_name`: The source file path for error reporting
661
- * r" - Additional context metadata
662
- * r"
663
- * r" # Returns
664
- * r"
665
- * r" A JSON string containing the [`MacroResult`] with the transformed code
666
- * r" or any diagnostic errors.
667
- * r"
668
- * r" # Errors
669
- * r"
670
- * r" Returns a NAPI error if:
671
- * r" - The input JSON cannot be parsed
672
- * r" - The `TsStream` cannot be created from the context
673
- * r" - The result cannot be serialized to JSON
674
- */
675
- export declare function __macroforgeRunSerialize(contextJson: string): string
676
-
677
- /**
678
- * Checks if the given TypeScript code has valid syntax.
679
- *
680
- * This function attempts to parse the code using SWC's TypeScript parser
681
- * without performing any macro expansion.
682
- *
683
- * # Arguments
684
- *
685
- * * `code` - The TypeScript source code to check
686
- * * `filepath` - The file path (used to determine if it's TSX based on extension)
687
- *
688
- * # Returns
689
- *
690
- * A [`SyntaxCheckResult`] indicating success or containing the parse error.
691
- *
692
- * # Example
693
- *
694
- * ```javascript
695
- * const result = check_syntax("const x: number = 42;", "test.ts");
696
- * if (!result.ok) {
697
- * console.error("Syntax error:", result.error);
698
- * }
699
- * ```
700
- */
701
- export declare function checkSyntax(code: string, filepath: string): SyntaxCheckResult
702
-
703
- /**
704
- * Clears the configuration cache.
705
- *
706
- * This is useful for testing to ensure each test starts with a clean state.
707
- * In production, clearing the cache will force configs to be re-parsed on next access.
708
- *
709
- * # Example
710
- *
711
- * ```javascript
712
- * const { clearConfigCache, loadConfig } = require('macroforge-ts');
713
- *
714
- * // Clear cache before each test
715
- * clearConfigCache();
716
- *
717
- * // Now load a fresh config
718
- * const result = loadConfig(configContent, configPath);
719
- * ```
720
- */
721
- export declare function clearConfigCache(): void
722
-
723
- /**
724
- * Entry for a registered decorator in the manifest.
725
- *
726
- * Used by [`MacroManifest`] to describe field-level decorators
727
- * that can be used with macros.
728
- */
729
- export interface DecoratorManifestEntry {
730
- /** The module this decorator belongs to (e.g., "serde"). */
731
- module: string
732
- /** The exported name of the decorator (e.g., "skip", "rename"). */
733
- export: string
734
- /** The decorator kind: "class", "property", "method", "accessor", "parameter". */
735
- kind: string
736
- /** Documentation string for the decorator. */
737
- docs: string
738
- }
739
-
740
- /**
741
- * The `@Derive` decorator function exported to JavaScript/TypeScript.
742
- *
743
- * This is a no-op function that exists purely for TypeScript type checking.
744
- * The actual decorator processing happens during macro expansion, where
745
- * `@derive(...)` decorators are recognized and transformed.
746
- *
747
- * # TypeScript Usage
748
- *
749
- * ```typescript
750
- * import { Derive } from "macroforge-ts";
751
- *
752
- * @Derive(Debug, Clone, Serialize)
753
- * class User {
754
- * name: string;
755
- * email: string;
756
- * }
757
- * ```
758
- */
759
- export declare function Derive(...features: any[]): ClassDecorator
760
-
761
- /**
762
- * Options for macro expansion.
763
- *
764
- * Used by [`expand_sync`] to configure expansion behavior.
765
- */
766
- export interface ExpandOptions {
767
- /**
768
- * If `true`, preserves `@derive` decorators in the output.
769
- * If `false` (default), decorators are stripped after expansion.
770
- */
771
- keepDecorators?: boolean
772
- /**
773
- * Additional decorator module names from external macros.
774
- *
775
- * These are used during decorator stripping to identify Macroforge-specific
776
- * decorators that should be removed from the output. Built-in decorator modules
777
- * (like "serde", "debug") are automatically included.
778
- *
779
- * External macro packages should export their decorator module names, which
780
- * plugins can collect and pass here.
781
- *
782
- * # Example
783
- *
784
- * ```javascript
785
- * expandSync(code, filepath, {
786
- * keepDecorators: false,
787
- * externalDecoratorModules: ["myMacro", "customValidator"]
788
- * });
789
- * ```
790
- */
791
- externalDecoratorModules?: Array<string>
792
- /**
793
- * Path to a previously loaded config file.
794
- *
795
- * When provided, the expansion will use the cached configuration
796
- * (including foreign types) from this path. The config must have been
797
- * previously loaded via [`load_config`].
798
- *
799
- * # Example
800
- *
801
- * ```javascript
802
- * // First, load the config
803
- * const configResult = loadConfig(configContent, configPath);
804
- *
805
- * // Then use it during expansion
806
- * expandSync(code, filepath, { configPath });
807
- * ```
808
- */
809
- configPath?: string
810
- /**
811
- * Pre-built type registry JSON from [`scan_project_sync`].
812
- *
813
- * When provided, macros receive project-wide type awareness through
814
- * the `type_registry` and `resolved_fields` fields on `MacroContextIR`.
815
- *
816
- * # Example
817
- *
818
- * ```javascript
819
- * const scan = scanProjectSync(projectRoot);
820
- * expandSync(code, filepath, { typeRegistryJson: scan.registryJson });
821
- * ```
822
- */
823
- typeRegistryJson?: string
824
- }
825
-
826
- /**
827
- * Result of expanding macros in TypeScript source code.
828
- *
829
- * This is the primary return type for macro expansion operations,
830
- * containing the expanded code, diagnostics, and source mapping.
831
- *
832
- * # Example
833
- *
834
- * ```rust
835
- * use macroforge_ts::{ExpandResult, MacroDiagnostic};
836
- *
837
- * // Create an ExpandResult programmatically
838
- * let result = ExpandResult {
839
- * code: "class User {}".to_string(),
840
- * types: None,
841
- * metadata: None,
842
- * diagnostics: vec![],
843
- * source_mapping: None,
844
- * };
845
- *
846
- * // Check for errors
847
- * if result.diagnostics.iter().any(|d| d.level == "error") {
848
- * // Handle errors
849
- * }
850
- * ```
851
- */
852
- export interface ExpandResult {
853
- /** The expanded TypeScript code with all macros processed. */
854
- code: string
855
- /** Optional TypeScript type declarations for generated methods. */
856
- types?: string
857
- /** Optional JSON metadata about processed classes. */
858
- metadata?: string
859
- /** Diagnostics (errors, warnings, info) from the expansion process. */
860
- diagnostics: Array<MacroDiagnostic>
861
- /** Source mapping for position translation between original and expanded code. */
862
- sourceMapping?: SourceMappingResult
863
- }
864
-
865
- /**
866
- * Synchronously expands macros in TypeScript code.
867
- *
868
- * This is the standalone macro expansion function that doesn't use caching.
869
- * For cached expansion, use [`NativePlugin::process_file`] instead.
870
- *
871
- * # Arguments
872
- *
873
- * * `_env` - NAPI environment (unused but required by NAPI)
874
- * * `code` - The TypeScript source code to expand
875
- * * `filepath` - The file path (used for TSX detection)
876
- * * `options` - Optional configuration (e.g., `keep_decorators`)
877
- *
878
- * # Returns
879
- *
880
- * An [`ExpandResult`] containing the expanded code, diagnostics, and source mapping.
881
- *
882
- * # Errors
883
- *
884
- * Returns an error if:
885
- * - Thread spawning fails
886
- * - The worker thread panics
887
- * - Macro host initialization fails
888
- *
889
- * # Performance
890
- *
891
- * - Uses a 32MB thread stack to prevent stack overflow
892
- * - Performs early bailout for files without `@derive` decorators
893
- *
894
- * # Example
895
- *
896
- * ```javascript
897
- * const result = expand_sync(env, code, "user.ts", { keep_decorators: false });
898
- * console.log(result.code); // Expanded TypeScript code
899
- * console.log(result.diagnostics); // Any warnings or errors
900
- * ```
901
- */
902
- export declare function expandSync(code: string, filepath: string, options?: ExpandOptions | undefined | null): ExpandResult
903
-
904
- /**
905
- * A region in the expanded source that was generated by a macro.
906
- *
907
- * These regions identify code that has no corresponding location in the
908
- * original source because it was synthesized by a macro.
909
- *
910
- * # Example
911
- *
912
- * For a `@derive(Debug)` macro that generates a `toString()` method,
913
- * a `GeneratedRegionResult` would mark the entire method body as generated
914
- * with `source_macro = "Debug"`.
915
- */
916
- export interface GeneratedRegionResult {
917
- /** Byte offset where the generated region starts in the expanded source. */
918
- start: number
919
- /** Byte offset where the generated region ends in the expanded source. */
920
- end: number
921
- /** Name of the macro that generated this region (e.g., "Debug", "Clone"). */
922
- sourceMacro: string
923
- }
924
-
925
- /**
926
- * Information about an imported identifier from a TypeScript module.
927
- *
928
- * Used to track where decorators and macro-related imports come from.
929
- */
930
- export interface ImportSourceResult {
931
- /** Local identifier name in the import statement (e.g., `Derive` in `import { Derive }`). */
932
- local: string
933
- /** Module specifier this identifier was imported from (e.g., `"macroforge-ts"`). */
934
- module: string
935
- }
936
-
937
- /**
938
- * A diagnostic from the TypeScript/JavaScript compiler or IDE.
939
- *
940
- * This structure mirrors TypeScript's diagnostic format for interoperability
941
- * with language servers and IDEs.
942
- */
943
- export interface JsDiagnostic {
944
- /** Byte offset where the diagnostic starts. `None` for global diagnostics. */
945
- start?: number
946
- /** Length of the diagnostic span in bytes. */
947
- length?: number
948
- /** Human-readable diagnostic message. */
949
- message?: string
950
- /** TypeScript diagnostic code (e.g., 2304 for "Cannot find name"). */
951
- code?: number
952
- /** Diagnostic category: "error", "warning", "suggestion", "message". */
953
- category?: string
954
- }
955
-
956
- /**
957
- * Load and parse a macroforge configuration file.
958
- *
959
- * Parses a `macroforge.config.js/ts` file and caches the result for use
960
- * during macro expansion. The configuration includes both simple settings
961
- * (like `keepDecorators`) and foreign type handlers.
962
- *
963
- * # Arguments
964
- *
965
- * * `content` - The raw content of the configuration file
966
- * * `filepath` - Path to the configuration file (used to determine syntax and as cache key)
967
- *
968
- * # Returns
969
- *
970
- * A [`LoadConfigResult`] containing the parsed configuration summary.
971
- *
972
- * # Example
973
- *
974
- * ```javascript
975
- * import { loadConfig, expandSync } from 'macroforge';
976
- * import fs from 'fs';
977
- *
978
- * const configPath = 'macroforge.config.js';
979
- * const configContent = fs.readFileSync(configPath, 'utf-8');
980
- *
981
- * // Load and cache the configuration
982
- * const result = loadConfig(configContent, configPath);
983
- * console.log(`Loaded config with ${result.foreignTypeCount} foreign types`);
984
- *
985
- * // The config is now cached and will be used by expandSync
986
- * const expanded = expandSync(code, filepath, { configPath });
987
- * ```
988
- */
989
- export declare function loadConfig(content: string, filepath: string): LoadConfigResult
990
-
991
- /**
992
- * Result of loading a macroforge configuration file.
993
- *
994
- * Returned by [`load_config`] after parsing a `macroforge.config.js/ts` file.
995
- */
996
- export interface LoadConfigResult {
997
- /** Whether to preserve `@derive` decorators in the output code. */
998
- keepDecorators: boolean
999
- /** Whether to generate a convenience const for non-class types. */
1000
- generateConvenienceConst: boolean
1001
- /** Whether the config has any foreign type handlers defined. */
1002
- hasForeignTypes: boolean
1003
- /** Number of foreign types configured. */
1004
- foreignTypeCount: number
1005
- }
1006
-
1007
- /**
1008
- * A diagnostic message produced during macro expansion.
1009
- *
1010
- * Diagnostics can represent errors, warnings, or informational messages
1011
- * that occurred during the macro expansion process.
1012
- *
1013
- * # Fields
1014
- *
1015
- * * `level` - Severity level: "error", "warning", or "info"
1016
- * * `message` - Human-readable description of the issue
1017
- * * `start` - Optional byte offset where the issue starts in the source
1018
- * * `end` - Optional byte offset where the issue ends in the source
1019
- *
1020
- * # Example
1021
- *
1022
- * ```rust
1023
- * use macroforge_ts::MacroDiagnostic;
1024
- *
1025
- * let _diag = MacroDiagnostic {
1026
- * level: "error".to_string(),
1027
- * message: "Unknown macro 'Foo'".to_string(),
1028
- * start: Some(42),
1029
- * end: Some(45),
1030
- * };
1031
- * ```
1032
- */
1033
- export interface MacroDiagnostic {
1034
- /**
1035
- * Severity level of the diagnostic.
1036
- * One of: "error", "warning", "info".
1037
- */
1038
- level: string
1039
- /** Human-readable message describing the diagnostic. */
1040
- message: string
1041
- /**
1042
- * Byte offset in the original source where the issue starts.
1043
- * `None` if the diagnostic is not associated with a specific location.
1044
- */
1045
- start?: number
1046
- /**
1047
- * Byte offset in the original source where the issue ends.
1048
- * `None` if the diagnostic is not associated with a specific location.
1049
- */
1050
- end?: number
1051
- }
1052
-
1053
- /**
1054
- * Complete manifest of all available macros and decorators.
1055
- *
1056
- * This is returned by [`get_macro_manifest`] and is useful for:
1057
- * - IDE autocompletion
1058
- * - Documentation generation
1059
- * - Tooling integration
1060
- */
1061
- export interface MacroManifest {
1062
- /** ABI version for compatibility checking. */
1063
- version: number
1064
- /** All registered macros (derive, attribute, function). */
1065
- macros: Array<MacroManifestEntry>
1066
- /** All registered field/class decorators. */
1067
- decorators: Array<DecoratorManifestEntry>
1068
- }
1069
-
1070
- /**
1071
- * Entry for a registered macro in the manifest.
1072
- *
1073
- * Used by [`MacroManifest`] to describe available macros to tooling
1074
- * such as IDE extensions and documentation generators.
1075
- */
1076
- export interface MacroManifestEntry {
1077
- /** The macro name (e.g., "Debug", "Clone", "Serialize"). */
1078
- name: string
1079
- /** The macro kind: "derive", "attribute", or "function". */
1080
- kind: string
1081
- /** Human-readable description of what the macro does. */
1082
- description: string
1083
- /** The package that provides this macro (e.g., "macroforge-ts"). */
1084
- package: string
1085
- }
1086
-
1087
- /**
1088
- * A segment mapping a range in the original source to a range in the expanded source.
1089
- *
1090
- * These segments form the core of the bidirectional source mapping system,
1091
- * enabling IDE features like "go to definition" and error reporting to work
1092
- * correctly with macro-expanded code.
1093
- *
1094
- * # Invariants
1095
- *
1096
- * - `original_start < original_end`
1097
- * - `expanded_start < expanded_end`
1098
- * - Segments are non-overlapping and sorted by position
1099
- */
1100
- export interface MappingSegmentResult {
1101
- /** Byte offset where this segment starts in the original source. */
1102
- originalStart: number
1103
- /** Byte offset where this segment ends in the original source. */
1104
- originalEnd: number
1105
- /** Byte offset where this segment starts in the expanded source. */
1106
- expandedStart: number
1107
- /** Byte offset where this segment ends in the expanded source. */
1108
- expandedEnd: number
1109
- }
1110
-
1111
- /**
1112
- * Parses import statements from TypeScript code and returns their sources.
1113
- *
1114
- * This function extracts information about all import statements in the code,
1115
- * mapping each imported identifier to its source module. Useful for analyzing
1116
- * dependencies and understanding where decorators come from.
1117
- *
1118
- * # Arguments
1119
- *
1120
- * * `code` - The TypeScript source code to parse
1121
- * * `filepath` - The file path (used for TSX detection)
1122
- *
1123
- * # Returns
1124
- *
1125
- * A vector of [`ImportSourceResult`] entries, one for each imported identifier.
1126
- *
1127
- * # Errors
1128
- *
1129
- * Returns an error if the code cannot be parsed.
1130
- *
1131
- * # Example
1132
- *
1133
- * ```javascript
1134
- * // For code: import { Derive, Clone } from "macroforge-ts";
1135
- * const imports = parse_import_sources(code, "test.ts");
1136
- * // Returns: [
1137
- * // { local: "Derive", module: "macroforge-ts" },
1138
- * // { local: "Clone", module: "macroforge-ts" }
1139
- * // ]
1140
- * ```
1141
- */
1142
- export declare function parseImportSources(code: string, filepath: string): Array<ImportSourceResult>
1143
-
1144
- /**
1145
- * Options for processing a file through the macro system.
1146
- *
1147
- * Used by [`NativePlugin::process_file`] to configure expansion behavior
1148
- * and caching.
1149
- */
1150
- export interface ProcessFileOptions {
1151
- /**
1152
- * If `true`, preserves `@derive` decorators in the output.
1153
- * If `false` (default), decorators are stripped after expansion.
1154
- */
1155
- keepDecorators?: boolean
1156
- /**
1157
- * Version string for cache invalidation.
1158
- * When provided, cached results are only reused if versions match.
1159
- */
1160
- version?: string
1161
- /**
1162
- * Additional decorator module names from external macros.
1163
- * See [`ExpandOptions::external_decorator_modules`] for details.
1164
- */
1165
- externalDecoratorModules?: Array<string>
1166
- /**
1167
- * Path to a previously loaded config file (for foreign types lookup).
1168
- * See [`ExpandOptions::config_path`] for details.
1169
- */
1170
- configPath?: string
1171
- /**
1172
- * Pre-built type registry JSON from [`scan_project_sync`].
1173
- * See [`ExpandOptions::type_registry_json`] for details.
1174
- */
1175
- typeRegistryJson?: string
1176
- }
1177
-
1178
- /** Options for scanning a TypeScript project for type information. */
1179
- export interface ScanOptions {
1180
- /** File extensions to scan (default: `[".ts", ".tsx"]`). */
1181
- extensions?: Array<string>
1182
- /** Whether to only collect exported types (default: `false`). */
1183
- exportedOnly?: boolean
1184
- }
1185
-
1186
- /**
1187
- * Scan a TypeScript project and build a type registry.
1188
- *
1189
- * This should be called once at build start (e.g., in Vite's `buildStart` hook)
1190
- * and the resulting `registry_json` should be passed to [`expand_sync`] via
1191
- * `ExpandOptions.type_registry_json`.
1192
- *
1193
- * # Arguments
1194
- *
1195
- * * `root_dir` - The project root directory to scan
1196
- * * `options` - Optional scan configuration
1197
- *
1198
- * # Returns
1199
- *
1200
- * A [`ScanResult`] with the serialized registry and scan statistics.
1201
- *
1202
- * # Example
1203
- *
1204
- * ```javascript
1205
- * const scan = scanProjectSync(projectRoot);
1206
- * console.log(`Found ${scan.typesFound} types in ${scan.filesScanned} files`);
1207
- *
1208
- * // Pass to expand_sync for each file
1209
- * const result = expandSync(code, filepath, {
1210
- * typeRegistryJson: scan.registryJson,
1211
- * });
1212
- * ```
1213
- */
1214
- export declare function scanProjectSync(rootDir: string, options?: ScanOptions | undefined | null): ScanResult
1215
-
1216
- /** Result of scanning a project for type information. */
1217
- export interface ScanResult {
1218
- /**
1219
- * JSON-serialized [`TypeRegistry`].
1220
- * Pass this to `expand_sync` via `ExpandOptions.type_registry_json`.
1221
- */
1222
- registryJson: string
1223
- /** Number of files scanned. */
1224
- filesScanned: number
1225
- /** Number of types found. */
1226
- typesFound: number
1227
- /** Diagnostics from scanning (e.g., files that failed to parse). */
1228
- diagnostics: Array<MacroDiagnostic>
1229
- }
1230
-
1231
- /**
1232
- * Complete source mapping information for a macro expansion.
1233
- *
1234
- * Contains both preserved segments (original code that wasn't modified)
1235
- * and generated regions (new code synthesized by macros).
1236
- *
1237
- * # Usage
1238
- *
1239
- * This mapping enables:
1240
- * - Converting positions from original source to expanded source and vice versa
1241
- * - Identifying which macro generated a given piece of code
1242
- * - Mapping IDE diagnostics from expanded code back to original source
1243
- */
1244
- export interface SourceMappingResult {
1245
- /**
1246
- * Segments mapping preserved regions between original and expanded source.
1247
- * Sorted by position for efficient binary search lookups.
1248
- */
1249
- segments: Array<MappingSegmentResult>
1250
- /**
1251
- * Regions in the expanded source that were generated by macros.
1252
- * Used to identify synthetic code with no original source location.
1253
- */
1254
- generatedRegions: Array<GeneratedRegionResult>
1255
- }
1256
-
1257
- /**
1258
- * A span (range) in source code, represented as start position and length.
1259
- *
1260
- * Used for mapping diagnostics and other positional information.
1261
- */
1262
- export interface SpanResult {
1263
- /** Byte offset where the span starts. */
1264
- start: number
1265
- /** Length of the span in bytes. */
1266
- length: number
1267
- }
1268
-
1269
- /**
1270
- * Result of checking TypeScript syntax validity.
1271
- *
1272
- * Returned by [`check_syntax`] to indicate whether code parses successfully.
1273
- */
1274
- export interface SyntaxCheckResult {
1275
- /** `true` if the code parsed without errors, `false` otherwise. */
1276
- ok: boolean
1277
- /** Error message if parsing failed, `None` if successful. */
1278
- error?: string
1279
- }
1280
-
1281
- /**
1282
- * Result of transforming TypeScript code through the macro system.
1283
- *
1284
- * This struct is returned by [`transform_sync`] and contains the transformed code
1285
- * along with optional source maps, type declarations, and metadata about processed classes.
1286
- *
1287
- * # Fields
1288
- *
1289
- * * `code` - The transformed TypeScript/JavaScript code with macros expanded
1290
- * * `map` - Optional source map for debugging (currently not implemented)
1291
- * * `types` - Optional TypeScript type declarations for generated methods
1292
- * * `metadata` - Optional JSON metadata about processed classes
1293
- */
1294
- export interface TransformResult {
1295
- /** The transformed TypeScript/JavaScript code with all macros expanded. */
1296
- code: string
1297
- /**
1298
- * Source map for mapping transformed positions back to original.
1299
- * Currently always `None` - source mapping is handled separately via `SourceMappingResult`.
1300
- */
1301
- map?: string
1302
- /**
1303
- * TypeScript type declarations (`.d.ts` content) for generated methods.
1304
- * Used by IDEs to provide type information for macro-generated code.
1305
- */
1306
- types?: string
1307
- /**
1308
- * JSON-serialized metadata about processed classes.
1309
- * Contains information about which classes were processed and what was generated.
1310
- */
1311
- metadata?: string
1312
- }
1313
-
1314
- /**
1315
- * Synchronously transforms TypeScript code through the macro expansion system.
1316
- *
1317
- * This is similar to [`expand_sync`] but returns a [`TransformResult`] which
1318
- * includes source map information (when available).
1319
- *
1320
- * # Arguments
1321
- *
1322
- * * `_env` - NAPI environment (unused but required by NAPI)
1323
- * * `code` - The TypeScript source code to transform
1324
- * * `filepath` - The file path (used for TSX detection)
1325
- *
1326
- * # Returns
1327
- *
1328
- * A [`TransformResult`] containing the transformed code and metadata.
1329
- *
1330
- * # Errors
1331
- *
1332
- * Returns an error if:
1333
- * - Thread spawning fails
1334
- * - The worker thread panics
1335
- * - Macro expansion fails
1336
- *
1337
- * # Thread Safety
1338
- *
1339
- * Uses a 32MB thread stack to prevent stack overflow during deep AST recursion.
1340
- */
1341
- export declare function transformSync(code: string, filepath: string): TransformResult