@atomic-ehr/codegen 0.0.1-canary.20251006092200.fdb4a88 → 0.0.1-canary.20251007094146.5297616

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.
Files changed (90) hide show
  1. package/dist/cli/index.js +48 -124
  2. package/dist/index.d.ts +2121 -62
  3. package/dist/index.js +6076 -84
  4. package/dist/index.js.map +1 -0
  5. package/package.json +3 -7
  6. package/dist/api/builder.d.ts +0 -154
  7. package/dist/api/builder.js +0 -341
  8. package/dist/api/generators/base/BaseGenerator.d.ts +0 -186
  9. package/dist/api/generators/base/BaseGenerator.js +0 -565
  10. package/dist/api/generators/base/FileManager.d.ts +0 -88
  11. package/dist/api/generators/base/FileManager.js +0 -202
  12. package/dist/api/generators/base/PythonTypeMapper.d.ts +0 -16
  13. package/dist/api/generators/base/PythonTypeMapper.js +0 -71
  14. package/dist/api/generators/base/TemplateEngine.d.ts +0 -126
  15. package/dist/api/generators/base/TemplateEngine.js +0 -133
  16. package/dist/api/generators/base/TypeMapper.d.ts +0 -129
  17. package/dist/api/generators/base/TypeMapper.js +0 -153
  18. package/dist/api/generators/base/TypeScriptTypeMapper.d.ts +0 -51
  19. package/dist/api/generators/base/TypeScriptTypeMapper.js +0 -232
  20. package/dist/api/generators/base/builders/DirectoryBuilder.d.ts +0 -99
  21. package/dist/api/generators/base/builders/DirectoryBuilder.js +0 -215
  22. package/dist/api/generators/base/builders/FileBuilder.d.ts +0 -160
  23. package/dist/api/generators/base/builders/FileBuilder.js +0 -406
  24. package/dist/api/generators/base/builders/IndexBuilder.d.ts +0 -126
  25. package/dist/api/generators/base/builders/IndexBuilder.js +0 -290
  26. package/dist/api/generators/base/enhanced-errors.d.ts +0 -84
  27. package/dist/api/generators/base/enhanced-errors.js +0 -259
  28. package/dist/api/generators/base/error-handler.d.ts +0 -89
  29. package/dist/api/generators/base/error-handler.js +0 -243
  30. package/dist/api/generators/base/errors.d.ts +0 -251
  31. package/dist/api/generators/base/errors.js +0 -692
  32. package/dist/api/generators/base/index.d.ts +0 -99
  33. package/dist/api/generators/base/index.js +0 -160
  34. package/dist/api/generators/base/types.d.ts +0 -433
  35. package/dist/api/generators/base/types.js +0 -12
  36. package/dist/api/generators/types.d.ts +0 -53
  37. package/dist/api/generators/types.js +0 -4
  38. package/dist/api/generators/typescript.d.ts +0 -190
  39. package/dist/api/generators/typescript.js +0 -819
  40. package/dist/api/index.d.ts +0 -51
  41. package/dist/api/index.js +0 -50
  42. package/dist/cli/commands/generate/typescript.d.ts +0 -10
  43. package/dist/cli/commands/generate/typescript.js +0 -52
  44. package/dist/cli/commands/generate.d.ts +0 -15
  45. package/dist/cli/commands/generate.js +0 -159
  46. package/dist/cli/commands/index.d.ts +0 -29
  47. package/dist/cli/commands/index.js +0 -100
  48. package/dist/cli/commands/typeschema/generate.d.ts +0 -19
  49. package/dist/cli/commands/typeschema/generate.js +0 -124
  50. package/dist/cli/commands/typeschema.d.ts +0 -10
  51. package/dist/cli/commands/typeschema.js +0 -47
  52. package/dist/cli/index.d.ts +0 -9
  53. package/dist/cli/utils/log.d.ts +0 -10
  54. package/dist/cli/utils/log.js +0 -23
  55. package/dist/cli/utils/prompts.d.ts +0 -56
  56. package/dist/cli/utils/prompts.js +0 -202
  57. package/dist/cli/utils/spinner.d.ts +0 -110
  58. package/dist/cli/utils/spinner.js +0 -266
  59. package/dist/config.d.ts +0 -217
  60. package/dist/config.js +0 -591
  61. package/dist/logger.d.ts +0 -157
  62. package/dist/logger.js +0 -281
  63. package/dist/typeschema/cache.d.ts +0 -80
  64. package/dist/typeschema/cache.js +0 -239
  65. package/dist/typeschema/core/binding.d.ts +0 -11
  66. package/dist/typeschema/core/binding.js +0 -143
  67. package/dist/typeschema/core/field-builder.d.ts +0 -12
  68. package/dist/typeschema/core/field-builder.js +0 -123
  69. package/dist/typeschema/core/identifier.d.ts +0 -13
  70. package/dist/typeschema/core/identifier.js +0 -94
  71. package/dist/typeschema/core/nested-types.d.ts +0 -9
  72. package/dist/typeschema/core/nested-types.js +0 -93
  73. package/dist/typeschema/core/transformer.d.ts +0 -11
  74. package/dist/typeschema/core/transformer.js +0 -235
  75. package/dist/typeschema/generator.d.ts +0 -36
  76. package/dist/typeschema/generator.js +0 -243
  77. package/dist/typeschema/index.d.ts +0 -15
  78. package/dist/typeschema/index.js +0 -15
  79. package/dist/typeschema/parser.d.ts +0 -79
  80. package/dist/typeschema/parser.js +0 -274
  81. package/dist/typeschema/profile/processor.d.ts +0 -14
  82. package/dist/typeschema/profile/processor.js +0 -261
  83. package/dist/typeschema/register.d.ts +0 -21
  84. package/dist/typeschema/register.js +0 -117
  85. package/dist/typeschema/types.d.ts +0 -240
  86. package/dist/typeschema/types.js +0 -19
  87. package/dist/utils/codegen-logger.d.ts +0 -102
  88. package/dist/utils/codegen-logger.js +0 -196
  89. package/dist/utils.d.ts +0 -22
  90. package/dist/utils.js +0 -42
package/dist/index.d.ts CHANGED
@@ -1,82 +1,2141 @@
1
+ import { CanonicalManager } from '@atomic-ehr/fhir-canonical-manager';
2
+ import * as FS from '@atomic-ehr/fhirschema';
3
+ import { FHIRSchema, StructureDefinition } from '@atomic-ehr/fhirschema';
4
+
1
5
  /**
2
- * Main entry point for the @atomic-ehr/codegen library
6
+ * CodeGen Logger
3
7
  *
4
- * ## Overview
8
+ * Clean, colorful logging designed for code generation tools
9
+ */
10
+ interface LogOptions {
11
+ prefix?: string;
12
+ timestamp?: boolean;
13
+ verbose?: boolean;
14
+ }
15
+ /**
16
+ * Simple code generation logger with pretty colors and clean formatting
17
+ */
18
+ declare class CodegenLogger {
19
+ private options;
20
+ constructor(options?: LogOptions);
21
+ private formatMessage;
22
+ /**
23
+ * Success message with checkmark
24
+ */
25
+ success(message: string): void;
26
+ /**
27
+ * Error message with X mark
28
+ */
29
+ error(message: string, error?: Error): void;
30
+ /**
31
+ * Warning message with warning sign
32
+ */
33
+ warn(message: string): void;
34
+ /**
35
+ * Info message with info icon
36
+ */
37
+ info(message: string): void;
38
+ /**
39
+ * Debug message (only shows in verbose mode)
40
+ */
41
+ debug(message: string): void;
42
+ /**
43
+ * Step message with rocket
44
+ */
45
+ step(message: string): void;
46
+ /**
47
+ * Progress message with clock
48
+ */
49
+ progress(message: string): void;
50
+ /**
51
+ * Plain message (no icon, just colored text)
52
+ */
53
+ plain(message: string, color?: (str: string) => string): void;
54
+ /**
55
+ * Dimmed/gray text for less important info
56
+ */
57
+ dim(message: string): void;
58
+ /**
59
+ * Create a child logger with a prefix
60
+ */
61
+ child(prefix: string): CodegenLogger;
62
+ /**
63
+ * Update options
64
+ */
65
+ configure(options: Partial<LogOptions>): void;
66
+ }
67
+
68
+ type Name = string & {
69
+ readonly __brand: unique symbol;
70
+ };
71
+ type CanonicalUrl = string & {
72
+ readonly __brand: unique symbol;
73
+ };
74
+ interface PackageMeta {
75
+ name: string;
76
+ version: string;
77
+ }
78
+ type RichFHIRSchema = Omit<FS.FHIRSchema, "package_meta" | "base" | "name" | "url"> & {
79
+ package_meta: PackageMeta;
80
+ name: Name;
81
+ url: CanonicalUrl;
82
+ base: CanonicalUrl;
83
+ };
84
+ type IdentifierBase = {
85
+ name: Name;
86
+ url: CanonicalUrl;
87
+ package: string;
88
+ version: string;
89
+ };
90
+ type PrimitiveIdentifier = {
91
+ kind: "primitive-type";
92
+ } & IdentifierBase;
93
+ type ComplexTypeIdentifier = {
94
+ kind: "complex-type";
95
+ } & IdentifierBase;
96
+ type ResourceIdentifier = {
97
+ kind: "resource";
98
+ } & IdentifierBase;
99
+ type ValueSetIdentifier = {
100
+ kind: "value-set";
101
+ } & IdentifierBase;
102
+ type NestedIdentifier = {
103
+ kind: "nested";
104
+ } & IdentifierBase;
105
+ type BindingIdentifier = {
106
+ kind: "binding";
107
+ } & IdentifierBase;
108
+ type ProfileIdentifier = {
109
+ kind: "profile";
110
+ } & IdentifierBase;
111
+ type LogicalIdentifier = {
112
+ kind: "logical";
113
+ } & IdentifierBase;
114
+ type Identifier = PrimitiveIdentifier | ComplexTypeIdentifier | ResourceIdentifier | NestedIdentifier | BindingIdentifier | ValueSetIdentifier | ProfileIdentifier | LogicalIdentifier;
115
+ type TypeSchema = RegularTypeSchema | PrimitiveTypeSchema | ValueSetTypeSchema | BindingTypeSchema | ProfileTypeSchema;
116
+ interface PrimitiveTypeSchema {
117
+ identifier: PrimitiveIdentifier;
118
+ description?: string;
119
+ base: Identifier;
120
+ dependencies?: Identifier[];
121
+ }
122
+ interface NestedType {
123
+ identifier: NestedIdentifier;
124
+ base: Identifier;
125
+ fields: Record<string, Field>;
126
+ }
127
+ interface ProfileTypeSchema {
128
+ identifier: ProfileIdentifier;
129
+ base: Identifier;
130
+ description?: string;
131
+ fields?: Record<string, Field>;
132
+ constraints?: Record<string, ProfileConstraint>;
133
+ extensions?: ProfileExtension[];
134
+ validation?: ValidationRule[];
135
+ dependencies?: Identifier[];
136
+ metadata?: ProfileMetadata;
137
+ nested?: NestedType[];
138
+ }
139
+ interface ProfileConstraint {
140
+ min?: number;
141
+ max?: string;
142
+ mustSupport?: boolean;
143
+ fixedValue?: any;
144
+ patternValue?: any;
145
+ binding?: {
146
+ strength: "required" | "extensible" | "preferred" | "example";
147
+ valueSet: string;
148
+ };
149
+ types?: Array<{
150
+ code: string;
151
+ profile?: string[];
152
+ targetProfile?: string[];
153
+ }>;
154
+ slicing?: {
155
+ discriminator: any[];
156
+ rules: string;
157
+ ordered?: boolean;
158
+ };
159
+ }
160
+ interface ProfileExtension {
161
+ path: string;
162
+ profile: string | string[];
163
+ min?: number;
164
+ max?: string;
165
+ mustSupport?: boolean;
166
+ }
167
+ interface ValidationRule {
168
+ path: string;
169
+ key: string;
170
+ severity: "error" | "warning" | "information";
171
+ human: string;
172
+ expression?: string;
173
+ }
174
+ interface ProfileMetadata {
175
+ publisher?: string;
176
+ contact?: any[];
177
+ copyright?: string;
178
+ purpose?: string;
179
+ experimental?: boolean;
180
+ date?: string;
181
+ jurisdiction?: any[];
182
+ package?: string;
183
+ }
184
+ interface RegularTypeSchema {
185
+ identifier: Identifier;
186
+ base?: Identifier;
187
+ description?: string;
188
+ fields?: {
189
+ [k: string]: Field;
190
+ };
191
+ nested?: NestedType[];
192
+ dependencies?: Identifier[];
193
+ }
194
+ interface RegularField {
195
+ type: Identifier;
196
+ reference?: Identifier[];
197
+ required?: boolean;
198
+ excluded?: boolean;
199
+ array?: boolean;
200
+ binding?: BindingIdentifier;
201
+ enum?: string[];
202
+ min?: number;
203
+ max?: number;
204
+ }
205
+ interface ChoiceFieldDeclaration {
206
+ choices: string[];
207
+ required?: boolean;
208
+ excluded?: boolean;
209
+ array?: boolean;
210
+ min?: number;
211
+ max?: number;
212
+ }
213
+ interface ChoiceFieldInstance {
214
+ choiceOf: string;
215
+ type: Identifier;
216
+ required?: boolean;
217
+ excluded?: boolean;
218
+ array?: boolean;
219
+ reference?: Identifier[];
220
+ binding?: BindingIdentifier;
221
+ enum?: string[];
222
+ min?: number;
223
+ max?: number;
224
+ }
225
+ type Concept = {
226
+ code: string;
227
+ display?: string;
228
+ system?: string;
229
+ };
230
+ interface ValueSetTypeSchema {
231
+ identifier: ValueSetIdentifier;
232
+ description?: string;
233
+ concept?: Concept[];
234
+ compose?: ValueSetCompose;
235
+ }
236
+ interface BindingTypeSchema {
237
+ identifier: BindingIdentifier;
238
+ description?: string;
239
+ type?: Identifier;
240
+ strength?: string;
241
+ enum?: string[];
242
+ valueset?: ValueSetIdentifier;
243
+ dependencies?: Identifier[];
244
+ }
245
+ type Field = RegularField | ChoiceFieldDeclaration | ChoiceFieldInstance;
246
+ interface TypeschemaGeneratorOptions {
247
+ verbose?: boolean;
248
+ logger?: CodegenLogger;
249
+ treeshake?: string[];
250
+ manager?: ReturnType<typeof CanonicalManager> | null;
251
+ }
252
+ type TypeschemaParserOptions = {
253
+ format?: "auto" | "ndjson" | "json";
254
+ validate?: boolean;
255
+ strict?: boolean;
256
+ };
257
+ type ValueSet = {
258
+ resourceType: "ValueSet";
259
+ id: string;
260
+ name?: string;
261
+ url?: string;
262
+ description?: string;
263
+ compose?: ValueSetCompose;
264
+ expansion?: {
265
+ contains: Concept[];
266
+ };
267
+ experimental?: boolean;
268
+ immutable?: boolean;
269
+ extension?: any[];
270
+ status?: string;
271
+ identifier?: any[];
272
+ title?: string;
273
+ publisher?: string;
274
+ version?: string;
275
+ meta?: any;
276
+ date?: string;
277
+ contact?: any;
278
+ };
279
+ type ValueSetCompose = {
280
+ include: {
281
+ concept?: Concept[];
282
+ system?: string;
283
+ filter?: {}[];
284
+ }[];
285
+ };
286
+ type RichValueSet = Omit<ValueSet, "name" | "url"> & {
287
+ package_meta: PackageMeta;
288
+ name?: Name;
289
+ url?: CanonicalUrl;
290
+ };
291
+
292
+ type Register = {
293
+ appendFs(fs: FHIRSchema): void;
294
+ ensureCanonicalUrl(name: string | Name | CanonicalUrl): CanonicalUrl;
295
+ resolveSd(canonicalUrl: CanonicalUrl): StructureDefinition | undefined;
296
+ resolveFs(canonicalUrl: CanonicalUrl): RichFHIRSchema | undefined;
297
+ resolveFsGenealogy(canonicalUrl: CanonicalUrl): RichFHIRSchema[];
298
+ allSd(): StructureDefinition[];
299
+ allFs(): RichFHIRSchema[];
300
+ allVs(): RichValueSet[];
301
+ resolveVs(canonicalUrl: CanonicalUrl): RichValueSet | undefined;
302
+ complexTypeDict(): Record<string, RichFHIRSchema>;
303
+ resolveAny(canonicalUrl: CanonicalUrl): any | undefined;
304
+ } & ReturnType<typeof CanonicalManager>;
305
+
306
+ /**
307
+ * New Config Schema for High-Level API
5
308
  *
6
- * atomic-codegen is a comprehensive code generation toolkit for FHIR healthcare standards,
7
- * designed with TypeSchema as the intermediate format for maximum flexibility and type safety.
309
+ * Simple configuration system compatible ONLY with the new high-level APIBuilder.
310
+ * All legacy config functionality has been removed.
311
+ */
312
+ /**
313
+ * TypeScript generator configuration options
314
+ */
315
+ interface TypeScriptGeneratorConfig {
316
+ moduleFormat?: "esm" | "cjs";
317
+ generateIndex?: boolean;
318
+ includeDocuments?: boolean;
319
+ namingConvention?: "PascalCase" | "camelCase";
320
+ strictMode?: boolean;
321
+ includeProfiles?: boolean;
322
+ includeExtensions?: boolean;
323
+ includeCodeSystems?: boolean;
324
+ includeOperations?: boolean;
325
+ /** Generate individual TypeScript files for value sets (default: false) */
326
+ generateValueSets?: boolean;
327
+ /** Include helper validation functions in value set files (default: false) */
328
+ includeValueSetHelpers?: boolean;
329
+ /** Which binding strengths to generate value sets for (default: ['required']) */
330
+ valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
331
+ /** Directory name for value set files (relative to outputDir) (default: 'valuesets') */
332
+ valueSetDirectory?: string;
333
+ /** Value set generation mode (default: 'required-only') */
334
+ valueSetMode?: "all" | "required-only" | "custom";
335
+ fhirVersion?: "R4" | "R5";
336
+ resourceTypes?: string[];
337
+ maxDepth?: number;
338
+ profileOptions?: {
339
+ generateKind?: "interface" | "type" | "both";
340
+ includeConstraints?: boolean;
341
+ includeDocumentation?: boolean;
342
+ strictMode?: boolean;
343
+ subfolder?: string;
344
+ };
345
+ generateBuilders?: boolean;
346
+ builderOptions?: {
347
+ includeValidation?: boolean;
348
+ includeFactoryMethods?: boolean;
349
+ includeInterfaces?: boolean;
350
+ generateNestedBuilders?: boolean;
351
+ includeHelperMethods?: boolean;
352
+ supportPartialBuild?: boolean;
353
+ includeJSDoc?: boolean;
354
+ generateFactories?: boolean;
355
+ includeTypeGuards?: boolean;
356
+ handleChoiceTypes?: boolean;
357
+ generateArrayHelpers?: boolean;
358
+ };
359
+ validatorOptions?: {
360
+ includeCardinality?: boolean;
361
+ includeTypes?: boolean;
362
+ includeConstraints?: boolean;
363
+ includeInvariants?: boolean;
364
+ validateRequired?: boolean;
365
+ allowAdditional?: boolean;
366
+ strictValidation?: boolean;
367
+ collectMetrics?: boolean;
368
+ generateAssertions?: boolean;
369
+ generatePartialValidators?: boolean;
370
+ optimizePerformance?: boolean;
371
+ includeJSDoc?: boolean;
372
+ generateCompositeValidators?: boolean;
373
+ };
374
+ guardOptions?: {
375
+ includeRuntimeValidation?: boolean;
376
+ includeErrorMessages?: boolean;
377
+ treeShakeable?: boolean;
378
+ targetTSVersion?: "3.8" | "4.0" | "4.5" | "5.0";
379
+ strictGuards?: boolean;
380
+ includeNullChecks?: boolean;
381
+ verbose?: boolean;
382
+ };
383
+ }
384
+ /**
385
+ * TypeSchema Configuration
386
+ * Controls TypeSchema generation and caching behavior
387
+ */
388
+ interface TypeSchemaConfig {
389
+ /** Enable persistent caching of generated TypeSchemas */
390
+ enablePersistence?: boolean;
391
+ /** Directory to store cached TypeSchemas (relative to outputDir) */
392
+ cacheDir?: string;
393
+ /** Maximum age of cached schemas in milliseconds before regeneration */
394
+ maxAge?: number;
395
+ /** Whether to validate cached schemas before reuse */
396
+ validateCached?: boolean;
397
+ /** Force regeneration of schemas even if cached */
398
+ forceRegenerate?: boolean;
399
+ /** Share cache across multiple codegen runs */
400
+ shareCache?: boolean;
401
+ /** Cache key prefix for namespacing */
402
+ cacheKeyPrefix?: string;
403
+ /** Only generate TypeSchemas for specific ResourceTypes (treeshaking) */
404
+ treeshake?: string[];
405
+ /** Generate single TypeSchema file instead of multiple files */
406
+ singleFile?: boolean;
407
+ /** Profile packages configuration */
408
+ profiles?: {
409
+ /** Auto-detect profiles in packages */
410
+ autoDetect?: boolean;
411
+ };
412
+ }
413
+ /**
414
+ * Main configuration schema for the new high-level API
415
+ */
416
+ interface Config {
417
+ outputDir?: string;
418
+ verbose?: boolean;
419
+ overwrite?: boolean;
420
+ validate?: boolean;
421
+ cache?: boolean;
422
+ typescript?: TypeScriptGeneratorConfig;
423
+ typeSchema?: TypeSchemaConfig;
424
+ packages?: string[];
425
+ files?: string[];
426
+ $schema?: string;
427
+ }
428
+ /**
429
+ * Default configuration values
430
+ */
431
+ declare const DEFAULT_CONFIG: Required<Config>;
432
+ /**
433
+ * Configuration file names to search for
434
+ */
435
+ declare const CONFIG_FILE_NAMES: string[];
436
+ /**
437
+ * Validation error interface
438
+ */
439
+ interface ConfigValidationError {
440
+ path: string;
441
+ message: string;
442
+ value?: unknown;
443
+ }
444
+ /**
445
+ * Configuration validation result
446
+ */
447
+ interface ConfigValidationResult {
448
+ valid: boolean;
449
+ errors: ConfigValidationError[];
450
+ warnings: string[];
451
+ config?: Config;
452
+ }
453
+ /**
454
+ * Simple configuration validator
455
+ */
456
+ declare class ConfigValidator {
457
+ /**
458
+ * Validate a configuration object
459
+ */
460
+ validate(config: unknown): ConfigValidationResult;
461
+ private validateTypeScriptConfig;
462
+ private validateValidatorOptions;
463
+ private validateGuardOptions;
464
+ private validateProfileOptions;
465
+ private validateTypeSchemaConfig;
466
+ }
467
+ /**
468
+ * Configuration loader with autoloading capabilities
469
+ */
470
+ declare class ConfigLoader {
471
+ private validator;
472
+ /**
473
+ * Auto-load configuration from the current working directory
474
+ */
475
+ autoload(workingDir?: string): Promise<Config>;
476
+ /**
477
+ * Load configuration from a specific file
478
+ */
479
+ loadFromFile(filePath: string): Promise<Config>;
480
+ /**
481
+ * Find configuration file in the given directory
482
+ */
483
+ private findConfigFile;
484
+ /**
485
+ * Merge user config with defaults
486
+ */
487
+ private mergeWithDefaults;
488
+ }
489
+ /**
490
+ * Global config loader instance
491
+ */
492
+ declare const configLoader: ConfigLoader;
493
+ /**
494
+ * Convenience function to auto-load configuration
495
+ */
496
+ declare function loadConfig(workingDir?: string): Promise<Config>;
497
+ /**
498
+ * Type guard to check if an object is a valid Config
499
+ */
500
+ declare function isConfig(obj: unknown): obj is Config;
501
+ /**
502
+ * Define configuration with type safety and IntelliSense support.
503
+ * Similar to Vite's defineConfig function pattern.
8
504
  *
9
- * ## Key Features
505
+ * @example
506
+ * ```typescript
507
+ * import { defineConfig } from "@atomic-ehr/codegen";
10
508
  *
11
- * - **🔥 FHIR R4/R5 Support**: Complete FHIR resource and profile generation
12
- * - **🇺🇸 US Core Profiles**: Built-in support for US healthcare implementation guides
13
- * - **📋 TypeSchema Integration**: Uses TypeSchema as universal intermediate format
14
- * - **🎯 Type Safety**: Full TypeScript support with runtime validation
15
- * - **⚡ Performance**: Built with Bun for maximum speed
16
- * - **🏗️ Extensible**: Plugin architecture for custom generators
509
+ * export default defineConfig({
510
+ * outputDir: "./generated",
511
+ * packages: [
512
+ * "hl7.fhir.r4.core@4.0.1",
513
+ * "hl7.fhir.us.core@6.1.0"
514
+ * ],
515
+ * typescript: {
516
+ * generateIndex: true,
517
+ * strictMode: true
518
+ * }
519
+ * });
520
+ * ```
521
+ */
522
+ declare function defineConfig(config: Config): Config;
523
+
524
+ /**
525
+ * TypeSchema Cache System
17
526
  *
18
- * ## Quick Start
527
+ * Caching system for TypeSchema documents with both in-memory and persistent file-based storage.
528
+ */
529
+
530
+ /**
531
+ * TypeSchema Cache with optional persistent storage
532
+ */
533
+ declare class TypeSchemaCache {
534
+ private cache;
535
+ private config;
536
+ private cacheDir?;
537
+ constructor(config?: TypeSchemaConfig);
538
+ /**
539
+ * Store a schema in the cache
540
+ */
541
+ set(schema: TypeSchema): Promise<void>;
542
+ /**
543
+ * Retrieve a schema by identifier
544
+ */
545
+ get(identifier: Identifier): TypeSchema | null;
546
+ /**
547
+ * Retrieve a schema by URL
548
+ */
549
+ getByUrl(url: string): TypeSchema | null;
550
+ /**
551
+ * Check if a schema exists in cache
552
+ */
553
+ has(identifier: Identifier): boolean;
554
+ /**
555
+ * Check if a schema exists by URL
556
+ */
557
+ hasByUrl(url: string): boolean;
558
+ /**
559
+ * Delete a schema from cache
560
+ */
561
+ delete(identifier: Identifier): boolean;
562
+ /**
563
+ * Delete a schema by URL
564
+ */
565
+ deleteByUrl(url: string): boolean;
566
+ /**
567
+ * Get schemas by package
568
+ */
569
+ getByPackage(packageName: string): TypeSchema[];
570
+ /**
571
+ * Get schemas by kind
572
+ */
573
+ getByKind(kind: string): TypeSchema[];
574
+ /**
575
+ * Store multiple schemas
576
+ */
577
+ setMany(schemas: TypeSchema[]): void;
578
+ /**
579
+ * Clear all cached schemas
580
+ */
581
+ clear(): void;
582
+ /**
583
+ * Generate cache key for identifier
584
+ */
585
+ private generateKey;
586
+ /**
587
+ * Initialize cache directory if persistence is enabled
588
+ */
589
+ initialize(): Promise<void>;
590
+ /**
591
+ * Load all cached schemas from disk
592
+ */
593
+ private loadFromDisk;
594
+ /**
595
+ * Persist a schema to disk
596
+ */
597
+ private persistSchema;
598
+ /**
599
+ * Clear cache directory
600
+ */
601
+ clearDisk(): Promise<void>;
602
+ }
603
+
604
+ /**
605
+ * TypeSchema Generator
19
606
  *
20
- * ```typescript
21
- * import { APIBuilder } from '@atomic-ehr/codegen';
607
+ * Generates TypeSchema documents from FHIR packages using fhrischema.
608
+ * Provides high-level API for converting FHIR Structure Definitions to TypeSchema format.
609
+ */
610
+
611
+ /**
612
+ * TypeSchema Generator class
22
613
  *
23
- * // High-level API for common workflows
24
- * const api = new APIBuilder();
614
+ * Main class for generating TypeSchema documents from FHIR packages.
615
+ * Leverages fhrischema for FHIR parsing and canonical manager for dependency resolution.
616
+ */
617
+ declare class TypeSchemaGenerator {
618
+ private manager;
619
+ private options;
620
+ private cacheConfig?;
621
+ private cache?;
622
+ private logger;
623
+ constructor(options?: TypeschemaGeneratorOptions, cacheConfig?: TypeSchemaConfig);
624
+ private initializeCache;
625
+ registerFromPackageMetas(packageMetas: PackageMeta[]): Promise<Register>;
626
+ generateFhirSchemas(structureDefinitions: StructureDefinition[]): FHIRSchema[];
627
+ generateValueSetSchemas(valueSets: RichValueSet[]): Promise<TypeSchema[]>;
628
+ generateFromPackage(packageName: string, packageVersion?: string): Promise<TypeSchema[]>;
629
+ /**
630
+ * Apply treeshaking to StructureDefinitions before FHIR schema transformation
631
+ * This is more efficient and includes smart reference handling
632
+ */
633
+ private applyStructureDefinitionTreeshaking;
634
+ private extractStructureDefinitionDependenciesWithReferences;
635
+ private extractResourceNameFromUrl;
636
+ }
637
+
638
+ /**
639
+ * TypeSchema Parser
25
640
  *
26
- * // Generate FHIR types from packages
27
- * await api
28
- * .fromFHIRPackages(['hl7.fhir.r4.core@4.0.1', 'hl7.fhir.us.core@6.1.0'])
29
- * .typescript('./src/types/fhir')
30
- * .withValidation()
31
- * .generate();
32
- * ```
641
+ * Parser for reading and manipulating TypeSchema documents from various formats.
642
+ * Supports both NDJSON and JSON formats with automatic format detection.
643
+ */
644
+
645
+ /**
646
+ * TypeSchema Parser class
33
647
  *
34
- * ## Architecture
648
+ * Provides functionality to read, parse, and manipulate TypeSchema documents
649
+ * from files or strings in various formats.
650
+ */
651
+ declare class TypeSchemaParser {
652
+ private options;
653
+ constructor(options?: TypeschemaParserOptions);
654
+ /**
655
+ * Parse TypeSchema from file
656
+ */
657
+ parseFromFile(filePath: string): Promise<TypeSchema[]>;
658
+ /**
659
+ * Parse TypeSchema from string content
660
+ */
661
+ parseFromString(content: string, format?: "ndjson" | "json"): Promise<TypeSchema[]>;
662
+ /**
663
+ * Parse multiple TypeSchema files
664
+ */
665
+ parseFromFiles(filePaths: string[]): Promise<TypeSchema[]>;
666
+ /**
667
+ * Parse a single TypeSchema object
668
+ */
669
+ parseSchema(schemaData: any): TypeSchema;
670
+ /**
671
+ * Find schemas by identifier
672
+ */
673
+ findByIdentifier(schemas: TypeSchema[], identifier: Partial<Identifier>): TypeSchema[];
674
+ /**
675
+ * Find schema by URL
676
+ */
677
+ findByUrl(schemas: TypeSchema[], url: string): TypeSchema | undefined;
678
+ /**
679
+ * Find schemas by kind
680
+ */
681
+ findByKind(schemas: TypeSchema[], kind: Identifier["kind"]): TypeSchema[];
682
+ /**
683
+ * Find schemas by package
684
+ */
685
+ findByPackage(schemas: TypeSchema[], packageName: string): TypeSchema[];
686
+ /**
687
+ * Get all dependencies from a schema
688
+ */
689
+ /**
690
+ * Resolve schema dependencies
691
+ */
692
+ /**
693
+ * Detect format from content or filename
694
+ */
695
+ private detectFormat;
696
+ /**
697
+ * Parse NDJSON format
698
+ */
699
+ private parseNDJSON;
700
+ /**
701
+ * Parse JSON format
702
+ */
703
+ private parseJSON;
704
+ /**
705
+ * Validate schemas
706
+ */
707
+ private validateSchemas;
708
+ /**
709
+ * Validate identifier structure
710
+ */
711
+ private isValidIdentifier;
712
+ /**
713
+ * Check if identifier matches criteria
714
+ */
715
+ private matchesIdentifier;
716
+ }
717
+
718
+ interface WriterOptions {
719
+ outputDir: string;
720
+ tabSize: number;
721
+ withDebugComment?: boolean;
722
+ commentLinePrefix: string;
723
+ logger?: CodegenLogger;
724
+ }
725
+
726
+ /**
727
+ * High-Level API Builder
35
728
  *
36
- * The library follows a three-stage architecture:
729
+ * Provides a fluent, chainable API for common codegen use cases with pre-built generators.
730
+ * This builder pattern allows users to configure generation in a declarative way.
731
+ */
732
+
733
+ /**
734
+ * Configuration options for the API builder
735
+ */
736
+ interface APIBuilderOptions {
737
+ outputDir?: string;
738
+ verbose?: boolean;
739
+ overwrite?: boolean;
740
+ cache?: boolean;
741
+ typeSchemaConfig?: TypeSchemaConfig;
742
+ logger?: CodegenLogger;
743
+ manager?: ReturnType<typeof CanonicalManager> | null;
744
+ throwException?: boolean;
745
+ }
746
+ /**
747
+ * Progress callback for long-running operations
748
+ */
749
+ type ProgressCallback$1 = (phase: string, current: number, total: number, message?: string) => void;
750
+ /**
751
+ * Generation result information
752
+ */
753
+ interface GenerationResult {
754
+ success: boolean;
755
+ outputDir: string;
756
+ filesGenerated: string[];
757
+ errors: string[];
758
+ warnings: string[];
759
+ duration: number;
760
+ }
761
+ /**
762
+ * High-Level API Builder class
37
763
  *
38
- * 1. **Input**: FHIR packages, JSON Schema, or custom schemas
39
- * 2. **TypeSchema**: Universal intermediate representation
40
- * 3. **Output**: TypeScript, Python, Go, or custom target languages
764
+ * Provides a fluent interface for configuring and executing code generation
765
+ * from FHIR packages or TypeSchema documents.
766
+ */
767
+ declare class APIBuilder {
768
+ private schemas;
769
+ private options;
770
+ private generators;
771
+ private cache?;
772
+ private pendingOperations;
773
+ private typeSchemaGenerator?;
774
+ private logger;
775
+ private packages;
776
+ progressCallback: any;
777
+ private typeSchemaConfig?;
778
+ constructor(options?: APIBuilderOptions);
779
+ fromPackage(packageName: string, version?: string): APIBuilder;
780
+ /**
781
+ * Load TypeSchema from files
782
+ */
783
+ fromFiles(...filePaths: string[]): APIBuilder;
784
+ /**
785
+ * Load TypeSchema from TypeSchema objects
786
+ */
787
+ fromSchemas(schemas: TypeSchema[]): APIBuilder;
788
+ typescript(options?: {
789
+ moduleFormat?: "esm" | "cjs";
790
+ generateIndex?: boolean;
791
+ includeDocuments?: boolean;
792
+ namingConvention?: "PascalCase" | "camelCase";
793
+ includeExtensions?: boolean;
794
+ includeProfiles?: boolean;
795
+ generateValueSets?: boolean;
796
+ includeValueSetHelpers?: boolean;
797
+ valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
798
+ valueSetMode?: "all" | "required-only" | "custom";
799
+ valueSetDirectory?: string;
800
+ }): APIBuilder;
801
+ typescript2(opts: Partial<WriterOptions>): this;
802
+ /**
803
+ * Set a progress callback for monitoring generation
804
+ */
805
+ onProgress(callback: ProgressCallback$1): APIBuilder;
806
+ /**
807
+ * Set the output directory for all generators
808
+ */
809
+ outputTo(directory: string): APIBuilder;
810
+ verbose(enabled?: boolean): APIBuilder;
811
+ throwException(enabled?: boolean): APIBuilder;
812
+ generate(): Promise<GenerationResult>;
813
+ /**
814
+ * Generate and return the results without writing to files
815
+ */
816
+ build(): Promise<{
817
+ typescript?: {
818
+ content: string;
819
+ filename: string;
820
+ }[];
821
+ }>;
822
+ /**
823
+ * Clear all configuration and start fresh
824
+ */
825
+ reset(): APIBuilder;
826
+ /**
827
+ * Get loaded schemas (for inspection)
828
+ */
829
+ getSchemas(): TypeSchema[];
830
+ /**
831
+ * Get configured generators (for inspection)
832
+ */
833
+ getGenerators(): string[];
834
+ private loadFromFiles;
835
+ private executeGenerators;
836
+ }
837
+ /**
838
+ * Create a new API builder instance
839
+ */
840
+ declare function createAPI(options?: APIBuilderOptions): APIBuilder;
841
+ /**
842
+ * Create an API builder instance from a configuration object
843
+ */
844
+ declare function createAPIFromConfig(config: Config): APIBuilder;
845
+ /**
846
+ * Convenience function for quick TypeScript generation from a package
847
+ */
848
+ declare function generateTypesFromPackage(packageName: string, outputDir: string, options?: {
849
+ version?: string;
850
+ verbose?: boolean;
851
+ validate?: boolean;
852
+ }): Promise<GenerationResult>;
853
+ /**
854
+ * Convenience function for quick TypeScript generation from files
855
+ */
856
+ declare function generateTypesFromFiles(inputFiles: string[], outputDir: string, options?: {
857
+ verbose?: boolean;
858
+ validate?: boolean;
859
+ }): Promise<GenerationResult>;
860
+
861
+ /**
862
+ * Core types and interfaces for the base generator system
41
863
  *
42
- * ## Examples
864
+ * This module provides the foundational type definitions that all generators
865
+ * build upon, ensuring consistency and type safety across the system.
866
+ */
867
+
868
+ /**
869
+ * Base configuration options that all generators must support
870
+ * These options provide the minimum required configuration for any generator
871
+ */
872
+ interface BaseGeneratorOptions {
873
+ /** Output directory where generated files will be written */
874
+ outputDir: string;
875
+ /** Logger instance for tracking generation progress and errors */
876
+ logger?: CodegenLogger;
877
+ /** Whether to overwrite existing files (default: true) */
878
+ overwrite?: boolean;
879
+ /** Whether to validate schemas and generated content (default: true) */
880
+ validate?: boolean;
881
+ /** Enable detailed logging for debugging (default: false) */
882
+ verbose?: boolean;
883
+ /** Enable beginner-friendly error messages and guidance (default: false) */
884
+ beginnerMode?: boolean;
885
+ /** Format for error output: console, json, or structured (default: 'console') */
886
+ errorFormat?: "console" | "json" | "structured";
887
+ }
888
+ /**
889
+ * Language-specific type representation
890
+ * This interface standardizes how FHIR types are mapped to target languages
891
+ */
892
+ interface LanguageType {
893
+ /** The type string in the target language (e.g., "string", "number", "Patient") */
894
+ name: string;
895
+ /** Whether this is a primitive type that doesn't need imports */
896
+ isPrimitive: boolean;
897
+ /** Import path if this type needs to be imported from another module */
898
+ importPath?: string;
899
+ /** Generic parameters if this is a generic type (e.g., ["T", "K"] for Map<T,K>) */
900
+ generics?: string[];
901
+ /** Whether this type is nullable/optional in the target language */
902
+ nullable?: boolean;
903
+ /** Additional metadata specific to the target language */
904
+ metadata?: Record<string, unknown>;
905
+ }
906
+ /**
907
+ * Generated file metadata and content
908
+ * Represents a single generated file with all its associated information
909
+ */
910
+ interface GeneratedFile {
911
+ /** Full file system path where the file was/will be written */
912
+ path: string;
913
+ /** Filename only (without directory path) */
914
+ filename: string;
915
+ /** The generated content of the file */
916
+ content: string;
917
+ /** List of symbols exported from this file */
918
+ exports: string[];
919
+ /** File size in bytes */
920
+ size: number;
921
+ /** When this file was generated */
922
+ timestamp: Date;
923
+ /** Additional metadata about the generation process */
924
+ metadata?: {
925
+ /** Time taken to generate this file in milliseconds */
926
+ generationTime?: number;
927
+ /** Number of schemas processed for this file */
928
+ schemaCount?: number;
929
+ /** Template used to generate this file */
930
+ templateName?: string;
931
+ /** Any warnings generated during processing */
932
+ warnings?: string[];
933
+ };
934
+ }
935
+ /**
936
+ * Template context provided to template engines
937
+ * Contains all the data needed to render templates for code generation
938
+ */
939
+ interface TemplateContext {
940
+ /** The schema being processed */
941
+ schema: TypeSchema;
942
+ /** Type mapper for the target language */
943
+ typeMapper: TypeMapper;
944
+ /** Current file being generated */
945
+ filename: string;
946
+ /** Target language name (e.g., "TypeScript", "Python") */
947
+ language: string;
948
+ /** Generation timestamp in ISO format */
949
+ timestamp: string;
950
+ /** Import map for the current file */
951
+ imports?: Map<string, string>;
952
+ /** Export set for the current file */
953
+ exports?: Set<string>;
954
+ /** Additional context data that templates can use */
955
+ [key: string]: unknown;
956
+ }
957
+ /**
958
+ * File builder context passed to lifecycle hooks
959
+ * Provides access to file generation state during the build process
960
+ */
961
+ interface FileContext {
962
+ /** Name of the file being generated */
963
+ filename: string;
964
+ /** Current file content */
965
+ content: string;
966
+ /** Map of imports (symbol name -> import path) */
967
+ imports: Map<string, string>;
968
+ /** Set of exported symbols */
969
+ exports: Set<string>;
970
+ /** Additional metadata about the file */
971
+ metadata: Record<string, unknown>;
972
+ /** The schema that generated this file (if applicable) */
973
+ schema?: TypeSchema;
974
+ /** Template name used to generate this file (if applicable) */
975
+ templateName?: string;
976
+ }
977
+ /**
978
+ * Statistics about file operations
979
+ * Used for performance monitoring and optimization
980
+ */
981
+ interface FileStats {
982
+ /** File size in bytes */
983
+ size: number;
984
+ /** Time taken to generate content in milliseconds */
985
+ generationTime: number;
986
+ /** Time taken to write to disk in milliseconds */
987
+ writeTime: number;
988
+ /** Memory used during generation in bytes */
989
+ memoryUsed?: number;
990
+ /** Number of template renders performed */
991
+ templateRenders?: number;
992
+ }
993
+ /**
994
+ * Progress callback signature for monitoring generation
995
+ * Allows consumers to track progress of long-running operations
996
+ */
997
+ type ProgressCallback = (
998
+ /** Current phase of generation */
999
+ phase: "validation" | "generation" | "writing" | "complete",
1000
+ /** Current item number being processed */
1001
+ current: number,
1002
+ /** Total number of items to process */
1003
+ total: number,
1004
+ /** Optional message describing current operation */
1005
+ message?: string,
1006
+ /** Schema being processed (if applicable) */
1007
+ schema?: TypeSchema) => void;
1008
+ /**
1009
+ * Lifecycle hook signatures for file operations
1010
+ * These hooks allow customization of the file generation process
1011
+ */
1012
+ /** Hook called before saving a file - can modify content or abort save */
1013
+ type BeforeSaveHook = (context: FileContext) => void | Promise<void>;
1014
+ /** Hook called after successfully saving a file */
1015
+ type AfterSaveHook = (filePath: string, stats: FileStats) => void | Promise<void>;
1016
+ /** Hook called when an error occurs during file operations */
1017
+ type ErrorHook = (error: Error, context: FileContext) => void | Promise<void>;
1018
+ /**
1019
+ * File builder configuration options
1020
+ * Controls how files are generated and processed
1021
+ */
1022
+ interface FileBuilderOptions {
1023
+ /** Template name to use for content generation */
1024
+ template?: string;
1025
+ /** Strategy for resolving import paths */
1026
+ importStrategy?: "auto" | "manual" | "none";
1027
+ /** Level of content validation to perform */
1028
+ validation?: "strict" | "loose" | "none";
1029
+ /** Enable pretty printing of generated content */
1030
+ prettify?: boolean;
1031
+ /** Custom formatting options */
1032
+ formatting?: {
1033
+ /** Number of spaces for indentation (default: 2) */
1034
+ indentSize?: number;
1035
+ /** Use tabs instead of spaces (default: false) */
1036
+ useTabs?: boolean;
1037
+ /** Maximum line length before wrapping (default: 100) */
1038
+ maxLineLength?: number;
1039
+ };
1040
+ /** File encoding (default: 'utf-8') */
1041
+ encoding?: BufferEncoding;
1042
+ }
1043
+ /**
1044
+ * Abstract base class for type mapping between FHIR and target languages
1045
+ * Each language-specific generator must implement this interface
1046
+ */
1047
+ declare abstract class TypeMapper {
1048
+ /**
1049
+ * Map a FHIR primitive type to the target language
1050
+ * @param fhirType - FHIR primitive type name (e.g., "string", "integer")
1051
+ * @returns Language-specific type representation
1052
+ */
1053
+ abstract mapPrimitive(fhirType: string): LanguageType;
1054
+ /**
1055
+ * Map a FHIR reference to the target language
1056
+ * @param targets - Array of possible reference targets
1057
+ * @returns Language-specific reference type
1058
+ */
1059
+ abstract mapReference(targets: Identifier[]): LanguageType;
1060
+ /**
1061
+ * Map an array type in the target language
1062
+ * @param elementType - The element type name
1063
+ * @returns Language-specific array type
1064
+ */
1065
+ abstract mapArray(elementType: string): LanguageType;
1066
+ /**
1067
+ * Map optional/nullable types
1068
+ * @param type - The base type
1069
+ * @param required - Whether the field is required
1070
+ * @returns Language-specific optional type
1071
+ */
1072
+ abstract mapOptional(type: string, required: boolean): LanguageType;
1073
+ /**
1074
+ * Map enumerated values to the target language
1075
+ * @param values - Array of possible values
1076
+ * @param name - Optional name for the enum type
1077
+ * @returns Language-specific enum type
1078
+ */
1079
+ abstract mapEnum(values: string[], name?: string): LanguageType;
1080
+ /**
1081
+ * Format a FHIR type name according to target language conventions
1082
+ * @param name - FHIR type name
1083
+ * @returns Formatted type name
1084
+ */
1085
+ abstract formatTypeName(name: string): string;
1086
+ /**
1087
+ * Format a field name according to target language conventions
1088
+ * @param name - FHIR field name
1089
+ * @returns Formatted field name
1090
+ */
1091
+ abstract formatFieldName(name: string): string;
1092
+ /**
1093
+ * Format a filename according to target language conventions
1094
+ * @param name - Base filename
1095
+ * @returns Formatted filename (without extension)
1096
+ */
1097
+ abstract formatFileName(name: string): string;
1098
+ /**
1099
+ * Map a complete TypeSchema identifier to target language type
1100
+ * @param identifier - FHIR type identifier
1101
+ * @returns Language-specific type representation
1102
+ */
1103
+ abstract mapType(identifier: Identifier): LanguageType;
1104
+ /**
1105
+ * Get import statement format for the target language
1106
+ * @param symbols - Symbols to import
1107
+ * @param from - Module to import from
1108
+ * @returns Formatted import statement
1109
+ */
1110
+ formatImport?(symbols: string[], from: string): string;
1111
+ /**
1112
+ * Get export statement format for the target language
1113
+ * @param symbols - Symbols to export
1114
+ * @returns Formatted export statement
1115
+ */
1116
+ formatExport?(symbols: string[]): string;
1117
+ }
1118
+ /**
1119
+ * Template engine interface
1120
+ * Abstraction for different template engines (Handlebars, etc.)
1121
+ */
1122
+ interface TemplateEngine {
1123
+ /**
1124
+ * Render a template with the given context
1125
+ * @param templateName - Name of the template to render
1126
+ * @param context - Data to pass to the template
1127
+ * @returns Rendered content
1128
+ */
1129
+ render(templateName: string, context: Record<string, unknown>): string;
1130
+ /**
1131
+ * Register a template
1132
+ * @param name - Template name
1133
+ * @param template - Template content or compiled template
1134
+ */
1135
+ registerTemplate(name: string, template: string | ((...args: any[]) => any)): void;
1136
+ /**
1137
+ * Register a helper function
1138
+ * @param name - Helper name
1139
+ * @param helper - Helper function
1140
+ */
1141
+ registerHelper(name: string, helper: (...args: any[]) => any): void;
1142
+ /**
1143
+ * Check if a template exists
1144
+ * @param name - Template name
1145
+ * @returns True if template exists
1146
+ */
1147
+ hasTemplate(name: string): boolean;
1148
+ /**
1149
+ * Get list of available templates
1150
+ * @returns Array of template names
1151
+ */
1152
+ getAvailableTemplates(): string[];
1153
+ }
1154
+ /**
1155
+ * Generator capabilities interface
1156
+ * Describes what a generator can do - used for introspection
1157
+ */
1158
+ interface GeneratorCapabilities {
1159
+ /** Programming language this generator targets */
1160
+ language: string;
1161
+ /** File extensions this generator produces */
1162
+ fileExtensions: string[];
1163
+ /** Whether this generator supports templates */
1164
+ supportsTemplates: boolean;
1165
+ /** Whether this generator supports custom type mapping */
1166
+ supportsCustomTypeMapping: boolean;
1167
+ /** Whether this generator supports incremental generation */
1168
+ supportsIncrementalGeneration: boolean;
1169
+ /** Whether this generator supports validation */
1170
+ supportsValidation: boolean;
1171
+ /** Supported schema kinds */
1172
+ supportedSchemaKinds: Array<"resource" | "complex-type" | "profile" | "primitive-type" | "logical">;
1173
+ /** Version of the generator */
1174
+ version: string;
1175
+ /** Additional metadata about capabilities */
1176
+ metadata?: Record<string, unknown>;
1177
+ }
1178
+
1179
+ /**
1180
+ * Core file management system with batching and performance optimizations
43
1181
  *
44
- * ### FHIR Patient with US Core Extensions
1182
+ * This replaces scattered writeFile calls with a comprehensive file management
1183
+ * system that provides better error handling, performance, and maintainability.
1184
+ */
1185
+
1186
+ interface FileManagerOptions {
1187
+ outputDir: string;
1188
+ logger: CodegenLogger;
1189
+ overwrite?: boolean;
1190
+ batchSize?: number;
1191
+ }
1192
+ interface WriteFileResult {
1193
+ path: string;
1194
+ size: number;
1195
+ writeTime: number;
1196
+ }
1197
+ /**
1198
+ * High-performance file manager with batching and error recovery
45
1199
  *
46
- * ```typescript
47
- * import { USCorePatient, USCoreRaceExtension } from './types/fhir';
48
- *
49
- * const patient: USCorePatient = {
50
- * resourceType: 'Patient',
51
- * identifier: [{ value: 'MRN-123' }],
52
- * name: [{ family: 'Johnson', given: ['Maria'] }],
53
- * gender: 'female',
54
- * extension: [{
55
- * url: 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race',
56
- * extension: [{ url: 'text', valueString: 'Hispanic or Latino' }]
57
- * } as USCoreRaceExtension]
58
- * };
59
- * ```
1200
+ * Features:
1201
+ * - Automatic directory creation
1202
+ * - Batch operations for better performance
1203
+ * - Comprehensive error handling with recovery suggestions
1204
+ * - Import path resolution
1205
+ * - File existence checks
1206
+ */
1207
+ declare class FileManager {
1208
+ private readonly options;
1209
+ private readonly logger;
1210
+ constructor(options: FileManagerOptions);
1211
+ /**
1212
+ * Write a file with automatic directory creation
1213
+ * @param relativePath Path relative to output directory
1214
+ * @param content File content
1215
+ * @param options Write options
1216
+ */
1217
+ writeFile(relativePath: string, content: string, options?: {
1218
+ encoding?: BufferEncoding;
1219
+ overwrite?: boolean;
1220
+ }): Promise<WriteFileResult>;
1221
+ /**
1222
+ * Write multiple files in batch for better performance
1223
+ * @param files Map of relative path to content
1224
+ */
1225
+ writeBatch(files: Map<string, string>): Promise<WriteFileResult[]>;
1226
+ /**
1227
+ * Ensure directory exists, creating parent directories as needed
1228
+ * @param dirPath Full directory path
1229
+ */
1230
+ ensureDirectory(dirPath: string): Promise<void>;
1231
+ /**
1232
+ * Clean directory by removing all contents
1233
+ * @param relativePath Path relative to output directory
1234
+ */
1235
+ cleanDirectory(relativePath?: string): Promise<void>;
1236
+ /**
1237
+ * Get relative import path between two files
1238
+ * @param fromFile Source file path
1239
+ * @param toFile Target file path
1240
+ */
1241
+ getRelativeImportPath(fromFile: string, toFile: string): string;
1242
+ /**
1243
+ * Check if a file would be overwritten
1244
+ * @param relativePath Path relative to output directory
1245
+ */
1246
+ wouldOverwrite(relativePath: string): Promise<boolean>;
1247
+ /**
1248
+ * Get file statistics
1249
+ * @param relativePath Path relative to output directory
1250
+ */
1251
+ getFileStats(relativePath: string): Promise<FileStats | null>;
1252
+ /**
1253
+ * Get output directory
1254
+ */
1255
+ getOutputDirectory(): string;
1256
+ /**
1257
+ * Set batch size for operations
1258
+ * @param size Batch size
1259
+ */
1260
+ setBatchSize(size: number): void;
1261
+ /**
1262
+ * Get current batch size
1263
+ */
1264
+ getBatchSize(): number;
1265
+ }
1266
+
1267
+ /**
1268
+ * Index file builder for automated exports
60
1269
  *
61
- * ### Runtime Validation
1270
+ * Automatically generates index files that export all types and functions
1271
+ * from a directory, with support for grouping and namespaces.
1272
+ */
1273
+
1274
+ interface IndexBuilderConfig {
1275
+ directory: string;
1276
+ fileManager: FileManager;
1277
+ templateEngine?: TemplateEngine;
1278
+ logger: CodegenLogger;
1279
+ }
1280
+ /**
1281
+ * Builder for index files with intelligent export management
62
1282
  *
63
- * ```typescript
64
- * import { isUSCorePatient, validateFHIRResource } from './types/fhir/guards';
1283
+ * Features:
1284
+ * - Automatic export detection
1285
+ * - Namespace support
1286
+ * - Export grouping
1287
+ * - Custom headers
1288
+ * - Template support
1289
+ */
1290
+ declare class IndexBuilder {
1291
+ private readonly config;
1292
+ private readonly exports;
1293
+ private readonly namespaces;
1294
+ private readonly reExports;
1295
+ private header;
1296
+ private footer;
1297
+ private groupingFunction?;
1298
+ private sortFunction?;
1299
+ constructor(config: IndexBuilderConfig);
1300
+ /**
1301
+ * Add exports from a specific file
1302
+ * @param exportNames Export names
1303
+ * @param fromPath Path to file (without extension)
1304
+ */
1305
+ withExports(exportNames: string[], fromPath: string): IndexBuilder;
1306
+ /**
1307
+ * Add a single export
1308
+ * @param exportName Export name
1309
+ * @param fromPath Path to file
1310
+ */
1311
+ withExport(exportName: string, fromPath: string): IndexBuilder;
1312
+ /**
1313
+ * Add namespace exports
1314
+ * @param namespaces Map of namespace to path
1315
+ */
1316
+ withNamespaces(namespaces: Record<string, string>): IndexBuilder;
1317
+ /**
1318
+ * Add namespace export
1319
+ * @param namespace Namespace name
1320
+ * @param path Path to export as namespace
1321
+ */
1322
+ withNamespace(namespace: string, path: string): IndexBuilder;
1323
+ /**
1324
+ * Re-export all from paths
1325
+ * @param paths Paths to re-export all from
1326
+ */
1327
+ withReExports(paths: string[]): IndexBuilder;
1328
+ /**
1329
+ * Add re-export
1330
+ * @param path Path to re-export all from
1331
+ */
1332
+ withReExport(path: string): IndexBuilder;
1333
+ /**
1334
+ * Set header content
1335
+ * @param header Header content
1336
+ */
1337
+ withHeader(header: string): IndexBuilder;
1338
+ /**
1339
+ * Set footer content
1340
+ * @param footer Footer content
1341
+ */
1342
+ withFooter(footer: string): IndexBuilder;
1343
+ /**
1344
+ * Group exports by function
1345
+ * @param fn Function that returns group name for export
1346
+ */
1347
+ groupBy(fn: (exportName: string) => string): IndexBuilder;
1348
+ /**
1349
+ * Sort exports by function
1350
+ * @param fn Sort function for [exportName, fromPath] tuples
1351
+ */
1352
+ sortBy(fn: (a: [string, string], b: [string, string]) => number): IndexBuilder;
1353
+ /**
1354
+ * Auto-discover exports from directory
1355
+ * @param filePattern Pattern to match files (e.g., "*.ts")
1356
+ */
1357
+ autoDiscover(_filePattern?: string): Promise<IndexBuilder>;
1358
+ /**
1359
+ * Save the index file
1360
+ */
1361
+ save(): Promise<string>;
1362
+ /**
1363
+ * Build content without saving (for preview)
1364
+ */
1365
+ build(): string;
1366
+ /**
1367
+ * Generate the index file content
1368
+ */
1369
+ private generateContent;
1370
+ /**
1371
+ * Generate simple exports without grouping
1372
+ */
1373
+ private generateSimpleExports;
1374
+ /**
1375
+ * Generate grouped exports
1376
+ */
1377
+ private generateGroupedExports;
1378
+ /**
1379
+ * Get current exports (for testing/debugging)
1380
+ */
1381
+ getExports(): Map<string, string>;
1382
+ /**
1383
+ * Get current namespaces (for testing/debugging)
1384
+ */
1385
+ getNamespaces(): Map<string, string>;
1386
+ /**
1387
+ * Get current re-exports (for testing/debugging)
1388
+ */
1389
+ getReExports(): Map<string, string>;
1390
+ }
1391
+
1392
+ /**
1393
+ * Fluent file builder with lifecycle hooks and validation
65
1394
  *
66
- * if (isUSCorePatient(someData)) {
67
- * // TypeScript knows this is a USCorePatient
68
- * const validation = await validateFHIRResource(someData);
69
- * if (validation.valid) {
70
- * console.log('Valid US Core Patient!');
71
- * }
72
- * }
73
- * ```
1395
+ * This provides a clean, chainable API for building files with imports,
1396
+ * exports, content generation, and lifecycle hooks for customization.
1397
+ */
1398
+
1399
+ interface FileBuilderConfig {
1400
+ filename: string;
1401
+ fileManager: FileManager;
1402
+ templateEngine?: TemplateEngine;
1403
+ typeMapper: TypeMapper;
1404
+ logger: CodegenLogger;
1405
+ }
1406
+ /**
1407
+ * Fluent builder for creating files with lifecycle hooks
1408
+ *
1409
+ * Features:
1410
+ * - Fluent API for content building
1411
+ * - Template integration
1412
+ * - Import/export management
1413
+ * - Lifecycle hooks (before/after save, error handling)
1414
+ * - Content validation
1415
+ * - Automatic import path resolution
1416
+ */
1417
+ declare class FileBuilder {
1418
+ private readonly config;
1419
+ private content;
1420
+ private readonly imports;
1421
+ private readonly exports;
1422
+ private readonly metadata;
1423
+ private beforeSaveHooks;
1424
+ private afterSaveHooks;
1425
+ private errorHooks;
1426
+ private options;
1427
+ constructor(config: FileBuilderConfig);
1428
+ /**
1429
+ * Set content directly
1430
+ * @param content File content
1431
+ */
1432
+ withContent(content: string | (() => string)): FileBuilder;
1433
+ /**
1434
+ * Generate content from template
1435
+ * @param templateName Template to use
1436
+ * @param context Template context
1437
+ */
1438
+ withTemplate(templateName: string, context: Record<string, unknown>): FileBuilder;
1439
+ /**
1440
+ * Append content to existing content
1441
+ * @param content Content to append
1442
+ */
1443
+ appendContent(content: string): FileBuilder;
1444
+ /**
1445
+ * Prepend content to existing content
1446
+ * @param content Content to prepend
1447
+ */
1448
+ prependContent(content: string): FileBuilder;
1449
+ /**
1450
+ * Set all imports at once
1451
+ * @param imports Map of symbol name to import path
1452
+ */
1453
+ withImports(imports: Map<string, string>): FileBuilder;
1454
+ /**
1455
+ * Add a single import
1456
+ * @param symbol Symbol to import
1457
+ * @param from Import path
1458
+ */
1459
+ addImport(symbol: string, from: string): FileBuilder;
1460
+ /**
1461
+ * Add multiple imports from the same path
1462
+ * @param symbols Symbols to import
1463
+ * @param from Import path
1464
+ */
1465
+ addImports(symbols: string[], from: string): FileBuilder;
1466
+ /**
1467
+ * Set all exports at once
1468
+ * @param exports Array of export names
1469
+ */
1470
+ withExports(exports: string[]): FileBuilder;
1471
+ /**
1472
+ * Add a single export
1473
+ * @param name Export name
1474
+ */
1475
+ addExport(name: string): FileBuilder;
1476
+ /**
1477
+ * Add multiple exports
1478
+ * @param names Export names
1479
+ */
1480
+ addExports(names: string[]): FileBuilder;
1481
+ /**
1482
+ * Set metadata for the file
1483
+ * @param key Metadata key
1484
+ * @param value Metadata value
1485
+ */
1486
+ withMetadata(key: string, value: unknown): FileBuilder;
1487
+ /**
1488
+ * Set file builder options
1489
+ * @param options Options to set
1490
+ */
1491
+ withOptions(options: Partial<FileBuilderOptions>): FileBuilder;
1492
+ /**
1493
+ * Add hook to run before saving
1494
+ * @param hook Hook function
1495
+ */
1496
+ onBeforeSave(hook: BeforeSaveHook): FileBuilder;
1497
+ /**
1498
+ * Add hook to run after successful save
1499
+ * @param hook Hook function
1500
+ */
1501
+ onAfterSave(hook: AfterSaveHook): FileBuilder;
1502
+ /**
1503
+ * Add hook to run when error occurs
1504
+ * @param hook Hook function
1505
+ */
1506
+ onError(hook: ErrorHook): FileBuilder;
1507
+ /**
1508
+ * Build final content without saving
1509
+ * @returns File context with final content
1510
+ */
1511
+ build(): FileContext;
1512
+ /**
1513
+ * Save the file
1514
+ * @returns Promise resolving to file path
1515
+ */
1516
+ save(): Promise<string>;
1517
+ /**
1518
+ * Build final content with imports and exports
1519
+ */
1520
+ private buildFinalContent;
1521
+ /**
1522
+ * Generate import statements
1523
+ */
1524
+ private generateImportStatements;
1525
+ /**
1526
+ * Generate export statements
1527
+ */
1528
+ private generateExportStatements;
1529
+ /**
1530
+ * Prettify content (basic implementation)
1531
+ */
1532
+ private prettifyContent;
1533
+ /**
1534
+ * Validate generated content
1535
+ */
1536
+ private validateContent;
1537
+ /**
1538
+ * Get current content (for testing/debugging)
1539
+ */
1540
+ getContent(): string;
1541
+ /**
1542
+ * Get current imports (for testing/debugging)
1543
+ */
1544
+ getImports(): Map<string, string>;
1545
+ /**
1546
+ * Get current exports (for testing/debugging)
1547
+ */
1548
+ getExports(): Set<string>;
1549
+ }
1550
+
1551
+ /**
1552
+ * Directory builder for batch file operations
1553
+ *
1554
+ * Provides a fluent API for managing entire directories of files,
1555
+ * including subdirectories, index files, and batch operations.
1556
+ */
1557
+
1558
+ interface DirectoryBuilderConfig {
1559
+ path: string;
1560
+ fileManager: FileManager;
1561
+ logger: CodegenLogger;
1562
+ }
1563
+ /**
1564
+ * Fluent builder for directory operations
1565
+ *
1566
+ * Features:
1567
+ * - Subdirectory management
1568
+ * - Batch file operations
1569
+ * - Index file generation
1570
+ * - Directory cleaning
1571
+ * - File listing for preview
1572
+ */
1573
+ declare class DirectoryBuilder {
1574
+ private readonly config;
1575
+ private readonly files;
1576
+ private readonly subdirectories;
1577
+ private indexBuilder?;
1578
+ private shouldClean;
1579
+ constructor(config: DirectoryBuilderConfig);
1580
+ /**
1581
+ * Add a subdirectory
1582
+ * @param name Subdirectory name
1583
+ */
1584
+ withSubdirectory(name: string): DirectoryBuilder;
1585
+ /**
1586
+ * Add files to this directory
1587
+ * @param files Map of filename to FileBuilder
1588
+ */
1589
+ withFiles(files: Record<string, FileBuilder>): DirectoryBuilder;
1590
+ /**
1591
+ * Add a single file
1592
+ * @param filename File name
1593
+ * @param builder File builder
1594
+ */
1595
+ withFile(filename: string, builder: FileBuilder): DirectoryBuilder;
1596
+ /**
1597
+ * Set index builder for this directory
1598
+ * @param builder Index builder
1599
+ */
1600
+ withIndex(builder: IndexBuilder): DirectoryBuilder;
1601
+ /**
1602
+ * Clean directory before creating files
1603
+ */
1604
+ clean(): DirectoryBuilder;
1605
+ /**
1606
+ * Ensure directory exists
1607
+ */
1608
+ ensure(): Promise<DirectoryBuilder>;
1609
+ /**
1610
+ * Save all files in this directory
1611
+ */
1612
+ save(): Promise<string[]>;
1613
+ /**
1614
+ * Get all files that would be generated (for preview)
1615
+ */
1616
+ getFileList(): string[];
1617
+ /**
1618
+ * Get statistics about this directory
1619
+ */
1620
+ getStats(): {
1621
+ fileCount: number;
1622
+ subdirectoryCount: number;
1623
+ hasIndex: boolean;
1624
+ totalFiles: number;
1625
+ };
1626
+ /**
1627
+ * Check if directory would overwrite existing files
1628
+ */
1629
+ wouldOverwrite(): Promise<string[]>;
1630
+ /**
1631
+ * Get the path of this directory
1632
+ */
1633
+ getPath(): string;
1634
+ /**
1635
+ * Get all file builders (for testing/debugging)
1636
+ */
1637
+ getFiles(): Map<string, FileBuilder>;
1638
+ /**
1639
+ * Get all subdirectories (for testing/debugging)
1640
+ */
1641
+ getSubdirectories(): Map<string, DirectoryBuilder>;
1642
+ /**
1643
+ * Get index builder (for testing/debugging)
1644
+ */
1645
+ getIndexBuilder(): IndexBuilder | undefined;
1646
+ }
1647
+
1648
+ /**
1649
+ * Centralized error handling and reporting system
1650
+ *
1651
+ * This module provides a comprehensive error handling solution that:
1652
+ * - Handles both generator-specific and unknown errors gracefully
1653
+ * - Provides rich, context-aware error reporting
1654
+ * - Supports multiple output formats (console, JSON, structured)
1655
+ * - Includes batch error handling for multiple failures
1656
+ * - Offers smart error recovery suggestions
1657
+ */
1658
+
1659
+ interface ErrorHandlerOptions {
1660
+ logger: CodegenLogger;
1661
+ verbose?: boolean;
1662
+ beginnerMode?: boolean;
1663
+ outputFormat?: "console" | "json" | "structured";
1664
+ }
1665
+ /**
1666
+ * Centralized error handler with smart reporting
1667
+ */
1668
+ declare class ErrorHandler {
1669
+ private options;
1670
+ constructor(options: ErrorHandlerOptions);
1671
+ /**
1672
+ * Handle a single error with appropriate reporting
1673
+ */
1674
+ handleError(error: Error, context?: {
1675
+ schema?: TypeSchema;
1676
+ filename?: string;
1677
+ }): void;
1678
+ /**
1679
+ * Handle multiple errors in batch
1680
+ */
1681
+ handleBatchErrors(errors: Error[]): void;
1682
+ /**
1683
+ * Handle generator-specific errors with rich context
1684
+ */
1685
+ private handleGeneratorError;
1686
+ /**
1687
+ * Handle unknown errors gracefully
1688
+ */
1689
+ private handleUnknownError;
1690
+ /**
1691
+ * Report error to console with formatting
1692
+ */
1693
+ private reportErrorToConsole;
1694
+ /**
1695
+ * Report error as JSON for programmatic consumption
1696
+ */
1697
+ private reportErrorAsJson;
1698
+ /**
1699
+ * Report error in structured format
1700
+ */
1701
+ private reportErrorStructured;
1702
+ /**
1703
+ * Report multiple errors efficiently
1704
+ */
1705
+ private reportBatchErrors;
1706
+ /**
1707
+ * Get common suggestions across similar errors
1708
+ */
1709
+ private getCommonSuggestions;
1710
+ /**
1711
+ * Get recovery actions for an error
1712
+ */
1713
+ private getRecoveryActions;
1714
+ }
1715
+ /**
1716
+ * Error boundary for catching and handling all generator errors
1717
+ */
1718
+ declare class GeneratorErrorBoundary {
1719
+ private errorHandler;
1720
+ constructor(errorHandler: ErrorHandler);
1721
+ /**
1722
+ * Wrap an async operation with error boundary
1723
+ */
1724
+ withErrorBoundary<T>(operation: () => Promise<T>, context?: {
1725
+ schema?: TypeSchema;
1726
+ filename?: string;
1727
+ operationName?: string;
1728
+ }): Promise<T>;
1729
+ /**
1730
+ * Wrap a batch operation with error boundary
1731
+ */
1732
+ withBatchErrorBoundary<T>(operations: Array<() => Promise<T>>, _context?: {
1733
+ operationName?: string;
1734
+ }): Promise<T[]>;
1735
+ }
1736
+
1737
+ /**
1738
+ * Abstract base generator class with comprehensive functionality
1739
+ *
1740
+ * Provides common functionality for all generators including:
1741
+ * - Schema validation and processing
1742
+ * - File management with fluent API
1743
+ * - Template processing
1744
+ * - Error handling and recovery
1745
+ * - Progress monitoring
1746
+ * - Performance optimization
1747
+ */
1748
+ declare abstract class BaseGenerator<TOptions extends BaseGeneratorOptions = BaseGeneratorOptions, TResult extends GeneratedFile[] = GeneratedFile[]> {
1749
+ /** Validated and merged options */
1750
+ protected options: Required<TOptions>;
1751
+ /** Logger instance for this generator */
1752
+ protected readonly logger: CodegenLogger;
1753
+ /** File manager for all file operations */
1754
+ protected readonly fileManager: FileManager;
1755
+ /** Template engine for content generation (optional) */
1756
+ protected readonly templateEngine?: TemplateEngine;
1757
+ /** Language-specific type mapper */
1758
+ protected readonly typeMapper: TypeMapper;
1759
+ /** Enhanced error handler for comprehensive error reporting */
1760
+ protected readonly errorHandler: ErrorHandler;
1761
+ /** Error boundary for catching and handling all generator errors */
1762
+ protected readonly errorBoundary: GeneratorErrorBoundary;
1763
+ /** Progress callback if provided */
1764
+ private progressCallback?;
1765
+ /** Generated files tracking */
1766
+ private generatedFiles;
1767
+ /** Generation start time for performance metrics */
1768
+ private generationStartTime;
1769
+ /** Cache for expensive operations */
1770
+ private readonly cache;
1771
+ constructor(options: TOptions);
1772
+ /**
1773
+ * Get the name of the target language (e.g., "TypeScript", "Python", "Rust")
1774
+ */
1775
+ protected abstract getLanguageName(): string;
1776
+ /**
1777
+ * Get the file extension for the target language (e.g., ".ts", ".py", ".rs")
1778
+ */
1779
+ protected abstract getFileExtension(): string;
1780
+ /**
1781
+ * Create a language-specific type mapper
1782
+ */
1783
+ protected abstract createTypeMapper(): TypeMapper;
1784
+ /**
1785
+ * Generate content for a single schema
1786
+ * @param schema - The TypeSchema to generate code for
1787
+ * @param context - Additional context for generation
1788
+ */
1789
+ protected abstract generateSchemaContent(schema: TypeSchema, context: TemplateContext): Promise<string>;
1790
+ /**
1791
+ * Validate generated content before writing
1792
+ * @param content - The generated content
1793
+ * @param context - The generation context
1794
+ */
1795
+ protected abstract validateContent(content: string, context: TemplateContext): Promise<void>;
1796
+ /**
1797
+ * Filter and sort schemas with language-specific logic
1798
+ * @param schemas - Input schemas
1799
+ */
1800
+ protected abstract filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
1801
+ /**
1802
+ * Get generator capabilities - can be overridden for introspection
1803
+ */
1804
+ getCapabilities(): GeneratorCapabilities;
1805
+ /**
1806
+ * Create file manager instance - can be overridden for custom file handling
1807
+ */
1808
+ protected createFileManager(): FileManager;
1809
+ /**
1810
+ * Create template engine instance - can be overridden for custom templates
1811
+ * Returns undefined if template engine is not needed
1812
+ */
1813
+ protected createTemplateEngine(): TemplateEngine | undefined;
1814
+ /**
1815
+ * Generate code from TypeSchema documents
1816
+ * This is the main method that orchestrates the entire generation process
1817
+ * @param schemas - Array of TypeSchema documents
1818
+ */
1819
+ generate(schemas: TypeSchema[]): Promise<TResult>;
1820
+ /**
1821
+ * Generate and return content without writing files (useful for testing)
1822
+ * @param schemas - Array of TypeSchema documents
1823
+ */
1824
+ build(schemas: TypeSchema[]): Promise<TResult>;
1825
+ /**
1826
+ * Create a file builder for fluent file generation
1827
+ * @param filename - Name of the file to create
1828
+ */
1829
+ file(filename: string): FileBuilder;
1830
+ /**
1831
+ * Create a directory builder for batch operations
1832
+ * @param path - Directory path relative to output directory
1833
+ */
1834
+ directory(path: string): DirectoryBuilder;
1835
+ /**
1836
+ * Create an index file builder
1837
+ * @param directory - Directory to create index for
1838
+ */
1839
+ index(directory?: string): IndexBuilder;
1840
+ /**
1841
+ * Set progress callback for monitoring generation
1842
+ * @param callback - Progress callback function
1843
+ */
1844
+ onProgress(callback: ProgressCallback): this;
1845
+ /**
1846
+ * Validate generator configuration
1847
+ */
1848
+ private validateConfiguration;
1849
+ /**
1850
+ * Merge options with defaults
1851
+ */
1852
+ private mergeWithDefaults;
1853
+ /**
1854
+ * Validate schemas before processing
1855
+ */
1856
+ private validateSchemas;
1857
+ /**
1858
+ * Validate individual schema
1859
+ */
1860
+ protected validateSchema(schema: TypeSchema): Promise<void>;
1861
+ /**
1862
+ * Detect circular references in schema dependencies
1863
+ */
1864
+ private detectCircularReferences;
1865
+ /**
1866
+ * Generate files from processed schemas
1867
+ */
1868
+ private generateFiles;
1869
+ /**
1870
+ * Generate a single file from a schema
1871
+ */
1872
+ private generateFileForSchema;
1873
+ /**
1874
+ * Ensure filename has correct extension
1875
+ */
1876
+ private ensureFileExtension;
1877
+ /**
1878
+ * Extract exported symbols from generated content
1879
+ * Can be overridden by language-specific implementations
1880
+ */
1881
+ protected extractExports(content: string): string[];
1882
+ /**
1883
+ * Report progress to callback if provided
1884
+ */
1885
+ protected reportProgress(phase: "validation" | "generation" | "writing" | "complete", current: number, total: number, message?: string, schema?: TypeSchema): void;
1886
+ /**
1887
+ * Run post-generation hooks
1888
+ * Can be overridden to add custom post-processing
1889
+ */
1890
+ protected runPostGenerationHooks(): Promise<void>;
1891
+ /**
1892
+ * Get cached value or compute and cache it
1893
+ */
1894
+ protected getCachedOrCompute<T>(key: string, computeFn: () => T | Promise<T>): T | Promise<T>;
1895
+ /**
1896
+ * Clear internal cache
1897
+ */
1898
+ protected clearCache(): void;
1899
+ /**
1900
+ * Get generation statistics
1901
+ */
1902
+ getGenerationStats(): {
1903
+ filesGenerated: number;
1904
+ totalSize: number;
1905
+ averageFileSize: number;
1906
+ generationTime: number;
1907
+ averageTimePerFile: number;
1908
+ cacheHitRate: number;
1909
+ };
1910
+ }
1911
+
1912
+ /**
1913
+ * Abstract base class for language-specific type mapping
1914
+ *
1915
+ * This provides the interface that all language generators must implement
1916
+ * to convert FHIR TypeSchema types into their target language types.
1917
+ */
1918
+
1919
+ /**
1920
+ * Configuration for type mapping behavior
1921
+ */
1922
+ interface TypeMapperOptions {
1923
+ /** Whether to generate nullable types (e.g., T | null) */
1924
+ generateNullable?: boolean;
1925
+ /** Whether to use strict type checking */
1926
+ strictTypes?: boolean;
1927
+ /** Custom type mappings */
1928
+ customMappings?: Record<string, string>;
1929
+ /** Whether to generate array types or use generic collections */
1930
+ preferArraySyntax?: boolean;
1931
+ /** Naming convention strategy */
1932
+ namingConvention?: "camelCase" | "PascalCase" | "snake_case" | "kebab-case";
1933
+ }
1934
+
1935
+ /**
1936
+ * TypeScript-specific type mapper implementation
1937
+ */
1938
+
1939
+ /**
1940
+ * TypeScript-specific options
1941
+ */
1942
+ interface TypeScriptTypeMapperOptions extends TypeMapperOptions {
1943
+ /** Whether to use 'unknown' or 'any' for unmapped types */
1944
+ preferUnknown?: boolean;
1945
+ /** Whether to generate branded types for primitives */
1946
+ useBrandedTypes?: boolean;
1947
+ /** Whether to use 'undefined' or 'null' for optional types */
1948
+ preferUndefined?: boolean;
1949
+ /** Module format for imports */
1950
+ moduleFormat?: "esm" | "commonjs";
1951
+ }
1952
+
1953
+ /**
1954
+ * Modern TypeScript Generator built on BaseGenerator
1955
+ *
1956
+ * This is the new, clean implementation that replaces the monolithic typescript.ts generator.
1957
+ * Built using the BaseGenerator architecture with TypeMapper, TemplateEngine, and FileManager.
1958
+ */
1959
+
1960
+ /**
1961
+ * TypeScript-specific generator options
1962
+ */
1963
+ interface TypeScriptGeneratorOptions extends BaseGeneratorOptions {
1964
+ /** Module format for imports/exports */
1965
+ moduleFormat?: "esm" | "cjs";
1966
+ /** Whether to generate index files */
1967
+ generateIndex?: boolean;
1968
+ /** Include JSDoc documentation */
1969
+ includeDocuments?: boolean;
1970
+ /** Naming convention for types */
1971
+ namingConvention?: "PascalCase" | "camelCase";
1972
+ /** Include FHIR extensions */
1973
+ includeExtensions?: boolean;
1974
+ /** Include FHIR profiles */
1975
+ includeProfiles?: boolean;
1976
+ /** Generate value set files (default: false) */
1977
+ generateValueSets?: boolean;
1978
+ /** Include helper validation functions (default: false) */
1979
+ includeValueSetHelpers?: boolean;
1980
+ /**
1981
+ * Which binding strengths to generate value sets for
1982
+ * Only used when valueSetMode is 'custom'
1983
+ * @default ['required']
1984
+ */
1985
+ valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
1986
+ /**
1987
+ * Directory name for value set files (relative to outputDir)
1988
+ * @default 'valuesets'
1989
+ */
1990
+ valueSetDirectory?: string;
1991
+ /**
1992
+ * Value set generation mode
1993
+ * - 'all': Generate for all binding strengths with enums
1994
+ * - 'required-only': Generate only for required bindings (safe default)
1995
+ * - 'custom': Use valueSetStrengths array to control
1996
+ * @default 'required-only'
1997
+ */
1998
+ valueSetMode?: "all" | "required-only" | "custom";
1999
+ /** Type mapper options */
2000
+ typeMapperOptions?: TypeScriptTypeMapperOptions;
2001
+ }
2002
+ /**
2003
+ * Result of generating a single TypeScript file
2004
+ */
2005
+ interface GeneratedTypeScript {
2006
+ content: string;
2007
+ imports: Map<string, string>;
2008
+ exports: string[];
2009
+ filename: string;
2010
+ }
2011
+ /**
2012
+ * Modern TypeScript Generator
74
2013
  *
75
- * @packageDocumentation
76
- * @module @atomic-ehr/codegen
77
- * @version 0.0.1
78
- * @author Atomic EHR Team
79
- * @since 0.0.1
2014
+ * Generates clean, type-safe TypeScript interfaces from FHIR TypeSchema documents.
2015
+ * Uses the new BaseGenerator architecture for maintainability and extensibility.
80
2016
  */
81
- export * from "./api/index";
82
- export * from "./config";
2017
+ declare class TypeScriptGenerator extends BaseGenerator<TypeScriptGeneratorOptions, GeneratedFile[]> {
2018
+ private readonly resourceTypes;
2019
+ private collectedValueSets;
2020
+ private get tsOptions();
2021
+ protected getLanguageName(): string;
2022
+ protected getFileExtension(): string;
2023
+ protected createTypeMapper(): TypeMapper;
2024
+ protected generateSchemaContent(schema: TypeSchema, _context: TemplateContext): Promise<string>;
2025
+ protected filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
2026
+ protected validateContent(content: string, context: TemplateContext): Promise<void>;
2027
+ /**
2028
+ * Transform multiple schemas into TypeScript
2029
+ */
2030
+ transformSchemas(schemas: TypeSchema[]): Promise<GeneratedTypeScript[]>;
2031
+ /**
2032
+ * Transform a single schema into TypeScript
2033
+ */
2034
+ transformSchema(schema: TypeSchema): Promise<GeneratedTypeScript | undefined>;
2035
+ /**
2036
+ * Check if a binding schema should generate a value set file
2037
+ */
2038
+ private shouldGenerateValueSet;
2039
+ /**
2040
+ * Collect value sets from schemas that should generate value set files
2041
+ */
2042
+ private collectValueSets;
2043
+ /**
2044
+ * Check if a field binding should use a value set type
2045
+ */
2046
+ private shouldUseValueSetType;
2047
+ /**
2048
+ * Get the TypeScript type name for a binding
2049
+ */
2050
+ private getValueSetTypeName;
2051
+ /**
2052
+ * Check if a field has enum values that should be inlined
2053
+ */
2054
+ private shouldUseInlineEnum;
2055
+ /**
2056
+ * Generate inline enum type from field enum values
2057
+ */
2058
+ private generateInlineEnumType;
2059
+ private shouldSkipSchema;
2060
+ private getFilenameForSchema;
2061
+ private extractImportsFromContent;
2062
+ private extractExportsFromContent;
2063
+ /**
2064
+ * Generate special Reference interface with generics
2065
+ */
2066
+ private generateReferenceInterface;
2067
+ /**
2068
+ * Generate TypeScript interface directly without templates
2069
+ */
2070
+ private generateTypeScriptInterface;
2071
+ /**
2072
+ * Collect import dependencies from a field
2073
+ */
2074
+ private collectFieldImports;
2075
+ /**
2076
+ * Extract resource types from reference field constraints
2077
+ */
2078
+ private extractReferenceTypes;
2079
+ /**
2080
+ * Generate nested type interface
2081
+ */
2082
+ private generateNestedTypeInterface;
2083
+ /**
2084
+ * Capitalize first letter of string
2085
+ */
2086
+ private capitalizeFirst;
2087
+ /**
2088
+ * Generate field lines (handles polymorphic fields by expanding them)
2089
+ */
2090
+ private generateFieldLines;
2091
+ /**
2092
+ * Generate a single field line
2093
+ */
2094
+ private generateFieldLine;
2095
+ /**
2096
+ * Extract exported symbols from TypeScript content
2097
+ */
2098
+ protected extractExports(content: string): string[];
2099
+ /**
2100
+ * Set output directory for compatibility with API builder
2101
+ */
2102
+ setOutputDir(directory: string): void;
2103
+ /**
2104
+ * Update generator options for compatibility with API builder
2105
+ */
2106
+ setOptions(options: Partial<TypeScriptGeneratorOptions>): void;
2107
+ /**
2108
+ * Get current options for compatibility with API builder
2109
+ */
2110
+ getOptions(): TypeScriptGeneratorOptions;
2111
+ /**
2112
+ * Override generate to clean directory first
2113
+ */
2114
+ generate(schemas: TypeSchema[]): Promise<GeneratedFile[]>;
2115
+ /**
2116
+ * Run post-generation hooks - generate utility files
2117
+ */
2118
+ protected runPostGenerationHooks(): Promise<void>;
2119
+ /**
2120
+ * Generate utilities.ts file with ResourceType union
2121
+ */
2122
+ private generateUtilitiesFile;
2123
+ /**
2124
+ * Generate a complete value set TypeScript file
2125
+ */
2126
+ private generateValueSetFile;
2127
+ /**
2128
+ * Create valuesets directory and generate all value set files
2129
+ */
2130
+ private generateValueSetFiles;
2131
+ /**
2132
+ * Generate index.ts file that re-exports all value sets
2133
+ */
2134
+ private generateValueSetIndexFile;
2135
+ /**
2136
+ * Generate main types/index.ts file that exports all types and value sets
2137
+ */
2138
+ private generateMainIndexFile;
2139
+ }
2140
+
2141
+ export { APIBuilder, type APIBuilderOptions, CONFIG_FILE_NAMES, type Config, ConfigLoader, type ConfigValidationError, type ConfigValidationResult, ConfigValidator, DEFAULT_CONFIG, type GeneratedFile, type GenerationResult, type PackageMeta as PackageInfo, type ProgressCallback$1 as ProgressCallback, type TypeSchema, TypeSchemaCache, type TypeSchemaConfig, type Field as TypeSchemaField, TypeSchemaGenerator, type Identifier as TypeSchemaIdentifier, TypeSchemaParser, TypeScriptGenerator, type TypeScriptGeneratorConfig, type TypeScriptGeneratorOptions, configLoader, createAPI, createAPIFromConfig, defineConfig, generateTypesFromFiles, generateTypesFromPackage, isConfig, loadConfig };