macroforge_ts_syn 0.1.83

TypeScript syntax types for compile-time macro code generation
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
//! # Macroforge Configuration Types
//!
//! Serializable configuration types shared between the host process and external macro
//! processes. These live in `macroforge_ts_syn` so they can be used in [`MacroContextIR`]
//! for cross-process transfer.
//!
//! The config parsing logic (reading `macroforge.config.ts` via SWC) remains in
//! `macroforge_ts::host::config`.

use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Serialize};

/// Information about an imported function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportInfo {
    /// The imported name (or "default" for default imports).
    pub name: String,
    /// The module specifier.
    pub source: String,
}

/// An alias for a foreign type that allows matching different name-package pairs.
///
/// This is useful when a type can be imported from different paths or with different names.
///
/// ## Example
///
/// ```javascript
/// foreignTypes: {
///   "DateTime.DateTime": {
///     from: ["effect"],
///     aliases: [
///       { name: "DateTime", from: "effect/DateTime" }
///     ],
///     serialize: (v) => DateTime.formatIso(v),
///     // ...
///   }
/// }
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ForeignTypeAlias {
    /// The type name to match (e.g., "DateTime" or "DateTime.DateTime").
    pub name: String,
    /// The import source to match (e.g., "effect/DateTime").
    pub from: String,
}

/// Configuration for a single foreign type.
///
/// Foreign types allow global registration of handlers for external types
/// (like Effect's `DateTime`) so they work like primitives without per-field annotations.
///
/// ## Key Format
///
/// The key in `foreignTypes` should be the fully qualified type name as used in code:
/// - Simple type name: `"DateTime"` - matches `DateTime` in code
/// - Fully qualified: `"DateTime.DateTime"` - matches `DateTime.DateTime` (namespace.type pattern)
///
/// ## Import Source Validation
///
/// Foreign types are only matched when the type is imported from a source listed in
/// `from` or one of the `aliases`. Types with the same name from different packages
/// are ignored (fall back to generic handling).
///
/// ## Example
///
/// ```javascript
/// foreignTypes: {
///   // For Effect's DateTime where you import { DateTime } and use DateTime.DateTime
///   "DateTime.DateTime": {
///     from: ["effect"],
///     aliases: [
///       { name: "DateTime", from: "effect/DateTime" },
///       { name: "MyDateTime", from: "my-effect-wrapper" }
///     ],
///     serialize: (v) => DateTime.formatIso(v),
///     deserialize: (raw) => DateTime.unsafeFromDate(new Date(raw)),
///     default: () => DateTime.unsafeNow()
///   }
/// }
/// ```
///
/// This configuration matches:
/// - `import { DateTime } from 'effect'` with type `DateTime.DateTime`
/// - `import { DateTime } from 'effect/DateTime'` with type `DateTime`
/// - `import { MyDateTime } from 'my-effect-wrapper'` with type `MyDateTime`
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ForeignTypeConfig {
    /// The full type key as specified in config (e.g., "DateTime" or "DateTime.DateTime").
    /// This is the key from the foreignTypes object.
    pub name: String,

    /// Optional namespace for the type (e.g., "DateTime" for DateTime.DateTime).
    /// If specified, the type is accessed as `namespace.typeName`.
    /// If not specified, defaults to the first segment of the name if it contains a dot.
    pub namespace: Option<String>,

    /// Import sources where this type can come from (e.g., ["effect", "effect/DateTime"]).
    /// Used to validate that the type is imported from the correct module.
    pub from: Vec<String>,

    /// Serialization function expression (e.g., "(v, ctx) => v.toJSON()").
    pub serialize_expr: Option<String>,

    /// Import info if serialize is a named function from another module.
    pub serialize_import: Option<ImportInfo>,

    /// Deserialization function expression.
    pub deserialize_expr: Option<String>,

    /// Import info if deserialize is a named function from another module.
    pub deserialize_import: Option<ImportInfo>,

    /// Default value function expression (e.g., "() => DateTime.now()").
    pub default_expr: Option<String>,

    /// Import info if default is a named function from another module.
    pub default_import: Option<ImportInfo>,

    /// Shape-check predicate expression for union variant matching.
    /// Used when this foreign type appears as a variant in a union type alias.
    /// The expression should be a function `(value: unknown) => boolean`.
    /// Example: `(v: unknown) => typeof v === "string"` for types deserialized from strings.
    pub has_shape_expr: Option<String>,

    /// Import info if hasShape is a named function from another module.
    pub has_shape_import: Option<ImportInfo>,

    /// Aliases for this foreign type, allowing different name-package pairs to use the same config.
    #[serde(default)]
    pub aliases: Vec<ForeignTypeAlias>,

    /// Namespaces referenced in expressions (serialize_expr, deserialize_expr, default_expr).
    ///
    /// This is auto-extracted during config parsing by analyzing the expression ASTs.
    /// For example, if `serialize: (v) => DateTime.formatIso(v)`, this would contain `["DateTime"]`.
    ///
    /// Used to determine which namespaces need to be imported for the generated code to work.
    #[serde(default)]
    pub expression_namespaces: Vec<String>,
}

impl ForeignTypeConfig {
    /// Returns the namespace for this type.
    /// If `namespace` is explicitly set, returns that.
    /// Otherwise, if the name contains a dot (e.g., "Deep.A.B.Type"), returns everything before the last dot.
    /// Otherwise, returns None.
    pub fn get_namespace(&self) -> Option<&str> {
        if let Some(ref ns) = self.namespace {
            return Some(ns);
        }
        // If name contains a dot, extract namespace (everything before the last dot)
        if let Some(dot_idx) = self.name.rfind('.') {
            return Some(&self.name[..dot_idx]);
        }
        None
    }

    /// Returns the simple type name (last segment after dots).
    /// For "DateTime.DateTime", returns "DateTime".
    /// For "DateTime", returns "DateTime".
    pub fn get_type_name(&self) -> &str {
        self.name.rsplit('.').next().unwrap_or(&self.name)
    }

    /// Returns the full qualified name to match against.
    /// If namespace is set: "namespace.typeName"
    /// Otherwise: the name as-is
    pub fn get_qualified_name(&self) -> String {
        if let Some(ns) = self.get_namespace() {
            let type_name = self.get_type_name();
            if ns != type_name {
                return format!("{}.{}", ns, type_name);
            }
        }
        self.name.clone()
    }
}

/// Build flags consumed by the `@cfg` attribute macro.
///
/// The predicate in `/** @cfg({ feature: 'ssr' }) */` evaluates against these
/// flags: keys with single-value configs (e.g. `target`) match exactly; keys
/// whose config value is an array (e.g. `features`) match when the annotation
/// value is a member; multiple keys in one annotation combine with implicit AND.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CfgFlags {
    /// Active feature flags. `@cfg({ feature: 'ssr' })` passes when `'ssr'` is in this list.
    #[serde(default)]
    pub features: Vec<String>,

    /// Build target (e.g. `"web"`, `"node"`, `"deno"`). `@cfg({ target: 'web' })` matches exactly.
    #[serde(default)]
    pub target: Option<String>,

    /// Whether this build treats `@cfg({ debugAssertions: true })` as truthy.
    #[serde(default)]
    pub debug_assertions: bool,

    /// Arbitrary string-keyed predicate values. Accepts any JSON scalar so
    /// annotations like `@cfg({ tenant: 'acme' })` or `@cfg({ version: 2 })`
    /// can match exactly.
    #[serde(default)]
    pub custom: HashMap<String, serde_json::Value>,
}

/// Behavior knobs for the `@deprecated` attribute macro.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeprecatedConfig {
    /// Inject a one-shot `console.warn(...)` into the deprecated declaration's
    /// body so runtime use is visible alongside tsc's static `@deprecated` tag.
    ///
    /// Parsed but currently not acted on: the attribute pass only rewrites
    /// the JSDoc; runtime warn injection is not yet implemented, so this
    /// flag has no effect today (despite defaulting to `true`).
    #[serde(default = "crate::config::default_true")]
    pub runtime_warn: bool,

    /// Treat any use of a `@deprecated` symbol as a macro-expansion error.
    /// Off by default; turn on when chasing deprecations out of a codebase.
    #[serde(default)]
    pub fail_on_use: bool,
}

impl Default for DeprecatedConfig {
    fn default() -> Self {
        Self {
            runtime_warn: true,
            fail_on_use: false,
        }
    }
}

/// Enforcement strategy for `@mustUse`. Only one mode today; keeping this as
/// an enum reserves room for a future `Wrap` variant without a breaking change.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MustUseMode {
    /// Emit a macroforge diagnostic at the discarded-call site. No runtime cost.
    #[default]
    Lint,
}

/// Behavior knobs for the `@mustUse` attribute macro.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MustUseConfig {
    #[serde(default)]
    pub mode: MustUseMode,
}

/// Sandbox configuration for `@buildtime` evaluation.
///
/// Mirrors the `buildtime` block of `macroforge.config.*`:
///
/// ```js
/// buildtime: {
///   timeout: 5000,                                  // ms
///   maxHeap: 256,                                   // MiB (advisory)
///   filesystem: { read: ["**"], write: [] },
///   env: ["HOME"],
///   network: false,
///   flags: { RELEASE: "1" }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildtimeConfig {
    /// Wall-clock evaluation budget in milliseconds.
    #[serde(default = "default_buildtime_timeout_ms")]
    pub timeout_ms: u64,

    /// JS heap ceiling in MiB. Advisory — the Boa backend exposes no
    /// memory-limit hook, so this is carried but not enforced.
    #[serde(default = "default_buildtime_max_heap_mb")]
    pub max_heap_mb: usize,

    /// Glob patterns readable via `buildtime.fs`. Defaults to everything.
    #[serde(default = "default_buildtime_fs_read")]
    pub fs_read: Vec<String>,

    /// Glob patterns writable via `buildtime.fs`. Empty by default; no
    /// write API is currently exposed to sandboxed code.
    #[serde(default)]
    pub fs_write: Vec<String>,

    /// Environment variable names exposed as `buildtime.env.NAME`.
    #[serde(default)]
    pub env_allow: Vec<String>,

    /// Whether sandboxed code may reach the network. No network API is
    /// currently exposed, so this is carried for forward compatibility.
    #[serde(default)]
    pub network: bool,

    /// Build flags exposed as `buildtime.flags.has(name)` / `.get(name)`.
    #[serde(default)]
    pub flags: BTreeMap<String, String>,
}

impl Default for BuildtimeConfig {
    fn default() -> Self {
        Self {
            timeout_ms: default_buildtime_timeout_ms(),
            max_heap_mb: default_buildtime_max_heap_mb(),
            fs_read: default_buildtime_fs_read(),
            fs_write: Vec::new(),
            env_allow: Vec::new(),
            network: false,
            flags: BTreeMap::new(),
        }
    }
}

/// Default `@buildtime` evaluation timeout (5s), in milliseconds.
pub fn default_buildtime_timeout_ms() -> u64 {
    5_000
}

/// Default `@buildtime` heap ceiling (256 MiB).
pub fn default_buildtime_max_heap_mb() -> usize {
    256
}

/// Default readable globs for `@buildtime` (`**`).
pub fn default_buildtime_fs_read() -> Vec<String> {
    vec!["**".to_string()]
}

/// Behavior knobs for the `@nonExhaustive` attribute macro.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NonExhaustiveConfig {
    /// Brand property name used in the intersection. Keep this stable across a
    /// project so downstream consumers can pattern-match on it.
    #[serde(default = "default_non_exhaustive_brand")]
    pub brand: String,
}

impl Default for NonExhaustiveConfig {
    fn default() -> Self {
        Self {
            brand: default_non_exhaustive_brand(),
        }
    }
}

fn default_non_exhaustive_brand() -> String {
    "__nonExhaustive".to_string()
}

pub(crate) fn default_true() -> bool {
    true
}

/// Configuration for the macro host system.
///
/// This struct represents the contents of a `macroforge.config.js` file.
/// It controls macro loading, execution, and foreign type handling.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MacroforgeConfig {
    /// Whether to preserve `@derive` decorators in the output code.
    ///
    /// When `false` (default), decorators are stripped after expansion.
    /// When `true`, decorators remain in the output (useful for debugging).
    #[serde(default)]
    pub keep_decorators: bool,

    /// Whether to generate a convenience const for non-class types.
    ///
    /// When `true` (default), generates an `export const TypeName = { ... } as const;`
    /// that groups all generated functions for a type into a single namespace-like object.
    #[serde(default = "default_generate_convenience_const")]
    pub generate_convenience_const: bool,

    /// Foreign type configurations.
    ///
    /// Maps type names to their handlers for serialization, deserialization, and defaults.
    #[serde(default)]
    pub foreign_types: Vec<ForeignTypeConfig>,

    /// Build flags consumed by `@cfg`. Missing key is equivalent to an empty block.
    #[serde(default)]
    pub cfg: CfgFlags,

    /// Knobs for `@deprecated`. Missing key uses per-field defaults.
    #[serde(default)]
    pub deprecated: DeprecatedConfig,

    /// Knobs for `@mustUse`. Missing key = lint-mode diagnostic.
    #[serde(default)]
    pub must_use: MustUseConfig,

    /// Knobs for `@nonExhaustive`. Missing key = default brand name.
    #[serde(default)]
    pub non_exhaustive: NonExhaustiveConfig,

    /// Sandbox settings for `@buildtime`. Missing key uses the defaults.
    #[serde(default)]
    pub buildtime: BuildtimeConfig,

    /// Import sources from the config file itself.
    ///
    /// Maps imported names (e.g., "DateTime", "Option") to their import info
    /// (module source). This is used to determine the correct import source
    /// when generating namespace imports for foreign type expressions.
    #[serde(default, skip_serializing)]
    pub config_imports: HashMap<String, ImportInfo>,
}

/// Returns the default for generate_convenience_const (true).
pub fn default_generate_convenience_const() -> bool {
    true
}

impl Default for MacroforgeConfig {
    fn default() -> Self {
        Self {
            keep_decorators: false,
            generate_convenience_const: true,
            foreign_types: Vec::new(),
            cfg: CfgFlags::default(),
            deprecated: DeprecatedConfig::default(),
            must_use: MustUseConfig::default(),
            non_exhaustive: NonExhaustiveConfig::default(),
            buildtime: BuildtimeConfig::default(),
            config_imports: HashMap::new(),
        }
    }
}