@homedev/objector 1.3.7 → 1.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,81 @@
1
+ /**
2
+ * Parses and queries command-line arguments.
3
+ *
4
+ * Accepts argv-like arrays and parses only the provided tokens.
5
+ *
6
+ * @public
7
+ */
8
+ export declare class CommandLineArgs {
9
+ #private;
10
+ /**
11
+ * Creates a parser for the provided command-line tokens.
12
+ *
13
+ * @param args - Argument tokens to parse.
14
+ * @param definitions - Known argument definitions used by usage output.
15
+ */
16
+ constructor(args: string[], definitions?: CommandLineArgumentDefinition[]);
17
+ /**
18
+ * Returns normalized parsed argument tokens.
19
+ */
20
+ get args(): string[];
21
+ /**
22
+ * Returns non-option positional values.
23
+ */
24
+ get positionals(): string[];
25
+ /**
26
+ * Returns true if a flag was provided.
27
+ *
28
+ * @param flag - Option name with or without `-`/`--` prefix.
29
+ */
30
+ has(flag: string): boolean;
31
+ /**
32
+ * Returns values for a flag.
33
+ *
34
+ * @param flag - Option name with or without `-`/`--` prefix.
35
+ */
36
+ getArgs(flag: string): string[];
37
+ /**
38
+ * Returns true for boolean flags, first value for valued flags, or undefined.
39
+ *
40
+ * @param flag - Option name with or without `-`/`--` prefix.
41
+ */
42
+ get(flag: string): string | true | undefined;
43
+ /**
44
+ * Returns all options as a plain object.
45
+ */
46
+ toObject(): Record<string, string[] | true>;
47
+ /**
48
+ * Builds usage output from provided argument definitions.
49
+ *
50
+ * @param command - Command name shown in usage output.
51
+ */
52
+ usage(command?: string): string;
53
+ }
54
+
55
+ /**
56
+ * Defines an argument for usage output.
57
+ *
58
+ * @public
59
+ */
60
+ export declare interface CommandLineArgumentDefinition {
61
+ name: string;
62
+ alias?: string;
63
+ description?: string;
64
+ takesValue?: boolean;
65
+ multiple?: boolean;
66
+ valueName?: string;
67
+ }
68
+
69
+ /**
70
+ * Parsed representation of a single CLI option.
71
+ *
72
+ * @public
73
+ */
74
+ export declare interface CommandLineOption {
75
+ values: string[];
76
+ sawEqualsStyle: boolean;
77
+ }
78
+
1
79
  /**
2
80
  * @public
3
81
  */
@@ -20,6 +98,13 @@ declare interface EncoderOptions {
20
98
 
21
99
  declare type EncoderOptions_2 = ObjectorDecoratorOptions;
22
100
 
101
+ /**
102
+ * Checks whether a file is readable.
103
+ *
104
+ * @param fileName - File path to check.
105
+ * @returns True when the file can be accessed for reading.
106
+ * @public
107
+ */
23
108
  export declare const exists: (fileName: string) => Promise<boolean>;
24
109
 
25
110
  export declare interface FieldContext {
@@ -131,12 +216,32 @@ export declare type FieldProcessorTypedFunc = FieldProcessorFunc | (FieldProcess
131
216
 
132
217
  declare type FieldProcessorTypedFunc_2 = FieldProcessorFunc_2 | (FieldProcessorOptions_2 & { fn: FieldProcessorFunc_2 })
133
218
 
134
- declare interface FilePatternOptions {
219
+ /**
220
+ * @public
221
+ */
222
+ export declare interface FilePatternOptions {
135
223
  cwd: string;
136
224
  filter?: (fileName: string, index: number, array: string[]) => boolean;
137
225
  map: (fileName: string, index: number, array: string[]) => Promise<any>;
138
226
  }
139
227
 
228
+ /**
229
+ * Resolves the working directory used by file utilities.
230
+ *
231
+ * @param cwd - Optional absolute or relative directory override.
232
+ * @returns Absolute working directory path.
233
+ * @public
234
+ */
235
+ export declare const getCwd: (cwd?: string) => string;
236
+
237
+ /**
238
+ * Maps files matching a glob pattern (or a single path) with async projection.
239
+ *
240
+ * @param pattern - Glob pattern(s) or direct file path.
241
+ * @param options - Mapping options including cwd, optional filter, and map function.
242
+ * @returns Mapped result for a direct path, or mapped array for glob patterns.
243
+ * @public
244
+ */
140
245
  export declare const globMap: <T>(pattern: string | string[], options: FilePatternOptions) => Promise<T[] | T>;
141
246
 
142
247
  /**
@@ -174,9 +279,10 @@ export declare interface LoadContext {
174
279
 
175
280
  /**
176
281
  * @public
177
- * @param fileName
178
- * @param options
179
- * @returns
282
+ * @param fileName - Name or path of the file to load.
283
+ * @param options - Loading options including parser selection and lookup directories.
284
+ * @returns Parsed file content and path metadata.
285
+ * @throws - When no parser is resolved or locating/reading/parsing fails.
180
286
  */
181
287
  export declare const loadFormat: <T = any>(fileName: string, options?: LoadOptions) => Promise<LoadResult<T>>;
182
288
 
@@ -206,27 +312,87 @@ export declare interface LoadOptions {
206
312
  format?: string;
207
313
  }
208
314
 
315
+ /**
316
+ * Result of loading and parsing a file.
317
+ *
318
+ * @typeParam T - Parsed content type.
319
+ * @public
320
+ */
209
321
  export declare interface LoadResult<T> {
210
322
  fullPath: string;
211
323
  folderPath: string;
212
324
  content: T;
213
325
  }
214
326
 
327
+ /**
328
+ * Resolves a file path by searching the provided directories.
329
+ *
330
+ * @param fileName - File name or path to locate.
331
+ * @param dirs - Optional directories to search when fileName is relative.
332
+ * @returns Absolute path to the first matching file.
333
+ * @throws - When no matching file is found.
334
+ * @public
335
+ */
215
336
  export declare const locate: (fileName: string, dirs?: string[]) => Promise<string>;
216
337
 
338
+ /**
339
+ * @public
340
+ */
217
341
  export declare type LogFunction = (className: string, ...args: any[]) => void;
218
342
 
343
+ /**
344
+ * @public
345
+ */
219
346
  export declare class Logger {
220
347
  options: LoggerOptions;
348
+ /**
349
+ * Creates a logger with optional configuration overrides.
350
+ *
351
+ * @param options - Partial logger options to merge with defaults.
352
+ */
221
353
  constructor(options?: Partial<LoggerOptions>);
354
+ /**
355
+ * Writes a log entry when the message level passes the configured filter.
356
+ *
357
+ * @param className - Log level name.
358
+ * @param args - Log payload values.
359
+ */
222
360
  write(className: string, ...args: any[]): void;
361
+ /**
362
+ * Writes an INFO level log entry.
363
+ *
364
+ * @param args - Log payload values.
365
+ */
223
366
  info(...args: any[]): void;
367
+ /**
368
+ * Writes an ERROR level log entry.
369
+ *
370
+ * @param args - Log payload values.
371
+ */
224
372
  error(...args: any[]): void;
373
+ /**
374
+ * Writes a WARN level log entry.
375
+ *
376
+ * @param args - Log payload values.
377
+ */
225
378
  warn(...args: any[]): void;
379
+ /**
380
+ * Writes a DEBUG level log entry.
381
+ *
382
+ * @param args - Log payload values.
383
+ */
226
384
  debug(...args: any[]): void;
385
+ /**
386
+ * Writes a VERBOSE level log entry.
387
+ *
388
+ * @param args - Log payload values.
389
+ */
227
390
  verbose(...args: any[]): void;
228
391
  }
229
392
 
393
+ /**
394
+ * @public
395
+ */
230
396
  export declare interface LoggerOptions {
231
397
  level: string;
232
398
  showClass: boolean;
@@ -252,32 +418,74 @@ export declare const makeFieldProcessorMap: <T = unknown>(source: Record<keyof T
252
418
  keys?: (keyof T)[];
253
419
  }) => FieldProcessorMap;
254
420
 
421
+ /**
422
+ * Fluent markdown content builder.
423
+ *
424
+ * @public
425
+ */
255
426
  export declare class Markdown extends StringBuilder {
256
427
  #private;
428
+ /**
429
+ * Writes a markdown heading and trailing blank line.
430
+ *
431
+ * @param text - Heading text.
432
+ * @param level - Heading level from 1 to 6.
433
+ */
257
434
  header(text: string, level?: number): this;
435
+ /**
436
+ * Starts a fenced code block and optionally writes code and closes it.
437
+ *
438
+ * @param code - Optional code content.
439
+ * @param language - Optional code language id.
440
+ */
258
441
  codeBlock(code?: string, language?: string): this;
442
+ /** Closes the current fenced code block. */
259
443
  endCodeBlock(): this;
260
- link(text: string, url: string): this;
444
+ /** Writes an inline markdown link. */
445
+ link(text: string, url: string, title?: string): this;
446
+ /** Writes a markdown table from headers and rows. */
261
447
  table(headers: string[], rows: string[][]): this;
448
+ /** Writes one or more quoted lines. */
262
449
  blockquote(text: string): this;
450
+ /** Writes bold text. */
263
451
  bold(text: string): this;
452
+ /** Writes italic text. */
264
453
  italic(text: string): this;
454
+ /** Writes a bullet item line. */
265
455
  item(text: string): this;
456
+ /** Writes bullet items from an array or key-value map. */
266
457
  items(items: string[] | Record<string, any>): this;
458
+ /** Writes an ordered list starting from the provided number. */
267
459
  orderedList(items: string[], start?: number): this;
460
+ /** Writes inline code text. */
268
461
  code(text: string): this;
462
+ /** Writes a horizontal rule. */
269
463
  horizontalRule(): this;
464
+ /** Writes an image markdown line. */
270
465
  image(alt: string, url: string): this;
466
+ /** Writes strikethrough text. */
271
467
  strikethrough(text: string): this;
468
+ /** Writes highlighted text using == syntax. */
272
469
  highlight(text: string): this;
470
+ /** Writes subscript text using ~ syntax. */
273
471
  subscript(text: string): this;
472
+ /** Writes superscript text using ^ syntax. */
274
473
  superscript(text: string): this;
474
+ /** Writes a markdown task list. */
275
475
  taskList(items: {
276
476
  text: string;
277
477
  checked: boolean;
278
478
  }[]): this;
479
+ /**
480
+ * Starts a section heading and increments internal nesting level.
481
+ *
482
+ * @param text - Section title.
483
+ * @param level - Optional explicit heading level baseline.
484
+ */
279
485
  section(text: string, level?: number): this;
486
+ /** Decrements section nesting level by one. */
280
487
  endSection(): this;
488
+ /** Sets the internal section nesting level directly. */
281
489
  setSectionLevel(level: number): this;
282
490
  }
283
491
 
@@ -373,7 +581,7 @@ export declare class Objector {
373
581
  keys(keys: FieldProcessorMap_2): this;
374
582
  sources(sources: FieldProcessorMap_2): this;
375
583
  sections(sections: Record<string, FieldProcessorSectionFunc_2>): this;
376
- variables(vars: Record<string, unknown>): this;
584
+ variables(vars: Record<string, any>): this;
377
585
  functions(funcs: Record<string, AsyncFunction>): this;
378
586
  getFunctions(): Record<string, AsyncFunction>;
379
587
  getOutputs(): Output[];
@@ -425,6 +633,9 @@ export declare type ObjectorPluginConstructor = new (o: Objector, ...args: any[]
425
633
 
426
634
  declare type ObjectorPluginFunction = (o: Objector) => void;
427
635
 
636
+ /**
637
+ * @public
638
+ */
428
639
  export declare interface Output {
429
640
  name: string;
430
641
  type?: 'json' | 'yaml' | 'text';
@@ -491,24 +702,74 @@ declare type SharedFunctionOptions = ObjectorDecoratorOptions;
491
702
 
492
703
  declare type SourceFunc = (...args: any[]) => any;
493
704
 
705
+ /**
706
+ * @public
707
+ */
494
708
  export declare class StringBuilder {
495
709
  #private;
496
710
  options: StringBuilderOptions;
711
+ /**
712
+ * Creates a new StringBuilder instance.
713
+ *
714
+ * @param initial - Optional initial content.
715
+ * @param options - Builder formatting options.
716
+ */
497
717
  constructor(initial?: string | string[] | StringBuilder, options?: StringBuilderOptions);
718
+ /**
719
+ * Replaces current formatting options.
720
+ *
721
+ * @param options - New builder options.
722
+ * @returns Current builder instance.
723
+ */
498
724
  setOptions(options: StringBuilderOptions): this;
725
+ /** Clears all buffered blocks. */
499
726
  clear(): this;
727
+ /** Returns true when no content is buffered. */
500
728
  isEmpty(): boolean;
729
+ /** Returns concatenated content. */
501
730
  toString(): string;
731
+ /** Increases indentation level by one. */
502
732
  indent(): this;
733
+ /** Decreases indentation level by one when possible. */
503
734
  dedent(): this;
735
+ /** Returns current indentation level. */
504
736
  getCurrentIndent(): number;
737
+ /** Returns current content split by newline. */
505
738
  getLines(): string[];
739
+ /**
740
+ * Formats a line according to indentation and line options.
741
+ *
742
+ * @param line - Input line to format.
743
+ * @returns Formatted line including line separator.
744
+ */
506
745
  formatLine(line?: string): string;
746
+ /**
747
+ * Appends one or more values to the buffer.
748
+ *
749
+ * @param args - Values to append.
750
+ * @returns Current builder instance.
751
+ */
507
752
  write(...args: any[]): this;
753
+ /**
754
+ * Writes one or more formatted lines.
755
+ *
756
+ * @param args - Values to write as lines.
757
+ * @returns Current builder instance.
758
+ */
508
759
  writeLine(...args: any[]): this;
760
+ /**
761
+ * Maps input items to writes using a callback.
762
+ *
763
+ * @param items - Source items.
764
+ * @param fn - Mapping callback.
765
+ * @returns Current builder instance.
766
+ */
509
767
  writeMap<T>(items: T[], fn: (item: T, index: number, builder: this) => string | this): this;
510
768
  }
511
769
 
770
+ /**
771
+ * @public
772
+ */
512
773
  export declare interface StringBuilderOptions {
513
774
  indentChar?: string;
514
775
  indentSize?: number;
@@ -522,6 +783,16 @@ export declare const variable: (options?: VariableOptions) => (_: any, ctx: Clas
522
783
 
523
784
  declare type VariableOptions = ObjectorDecoratorOptions;
524
785
 
786
+ /**
787
+ * Encodes and writes content to a file path using the selected format encoder.
788
+ *
789
+ * @param filePath - Destination file path.
790
+ * @param content - Data to encode and write.
791
+ * @param options - Encoder selection options.
792
+ * @returns Promise resolved when writing completes.
793
+ * @throws - When no encoder can be resolved.
794
+ * @public
795
+ */
525
796
  export declare const writeFormat: (filePath: string, content: any, options?: WriteFormatOptions) => Promise<void>;
526
797
 
527
798
  /**
@@ -540,8 +811,20 @@ export declare interface WriteFormatOptions {
540
811
  encoders?: Record<string, WriteFormatEncoder>;
541
812
  }
542
813
 
814
+ /**
815
+ * Writes a single output entry to disk.
816
+ *
817
+ * @param o - Output entry to write.
818
+ * @param options - Writing behavior configuration.
819
+ * @returns Promise resolved when output is processed.
820
+ * @throws - When class requirements fail or file operations fail.
821
+ * @public
822
+ */
543
823
  export declare const writeOutput: (o: Output, options?: WriteOutputOption) => Promise<void>;
544
824
 
825
+ /**
826
+ * @public
827
+ */
545
828
  export declare interface WriteOutputOption {
546
829
  targetDirectory?: string;
547
830
  writing?: (output: Output) => boolean | undefined | void;
@@ -549,8 +832,19 @@ export declare interface WriteOutputOption {
549
832
  classRequired?: boolean;
550
833
  }
551
834
 
835
+ /**
836
+ * Writes multiple outputs to disk.
837
+ *
838
+ * @param outputs - Output definitions to write.
839
+ * @param options - Writing behavior configuration.
840
+ * @returns Promise resolved when all outputs are processed.
841
+ * @public
842
+ */
552
843
  export declare const writeOutputs: (outputs: Output[], options?: WriteOutputsOption) => Promise<void>;
553
844
 
845
+ /**
846
+ * @public
847
+ */
554
848
  export declare interface WriteOutputsOption extends WriteOutputOption {
555
849
  removeFirst?: boolean;
556
850
  }
@@ -579,28 +873,6 @@ declare global {
579
873
  }
580
874
  }
581
875
 
582
- declare global {
583
- interface Array<T> {
584
- mapAsync<U>(callback: (value: T, index: number, array: T[]) => Promise<U>): Promise<U[]>;
585
- forEachAsync(callback: (value: T, index: number, array: T[]) => Promise<void>): Promise<void>;
586
- sortBy<K extends keyof T>(selector: (item: T) => T[K], ascending?: boolean): T[];
587
- unique(): T[];
588
- uniqueBy<K extends keyof T>(selector: (item: T) => T[K]): T[];
589
- groupBy<K extends keyof T>(selector: (item: T) => T[K]): Record<T[K] & (string | number | symbol), T[]>;
590
- toObject<K extends keyof T, V>(keySelector: (item: T) => T[K], valueSelector?: (item: T) => V): Record<T[K] & (string | number | symbol), V>;
591
- toObjectWithKey<K extends keyof T>(key: K): Record<string, T>;
592
- nonNullMap<U>(callback: (value: T, index: number, array: T[]) => U | null | undefined): U[];
593
- nonNullMapAsync<U>(callback: (value: T, index: number, array: T[]) => Promise<U | null | undefined>): Promise<U[]>;
594
- findOrFail(predicate: (value: T, index: number, array: T[]) => boolean, message?: string, thisArg?: any): T;
595
- selectFor<K>(predicate: (value: T, index: number, array: T[]) => boolean, selector: (value: T) => K, message?: string, thisArg?: any): K;
596
- createInstances<TTarget>(targetConstructor: new (...args: any[]) => TTarget, ...args: any[]): TTarget[];
597
- mergeAll(options?: MergeOptions): any;
598
- }
599
- interface ArrayConstructor {
600
- flat<T>(v: T | T[] | T[][]): T[];
601
- }
602
- }
603
-
604
876
  declare global {
605
877
  interface String {
606
878
  capitalize(): string;
@@ -628,3 +900,25 @@ declare global {
628
900
  }
629
901
  }
630
902
 
903
+ declare global {
904
+ interface Array<T> {
905
+ mapAsync<U>(callback: (value: T, index: number, array: T[]) => Promise<U>): Promise<U[]>;
906
+ forEachAsync(callback: (value: T, index: number, array: T[]) => Promise<void>): Promise<void>;
907
+ sortBy<K extends keyof T>(selector: (item: T) => T[K], ascending?: boolean): T[];
908
+ unique(): T[];
909
+ uniqueBy<K extends keyof T>(selector: (item: T) => T[K]): T[];
910
+ groupBy<K extends keyof T>(selector: (item: T) => T[K]): Record<T[K] & (string | number | symbol), T[]>;
911
+ toObject<K extends keyof T, V>(keySelector: (item: T) => T[K], valueSelector?: (item: T) => V): Record<T[K] & (string | number | symbol), V>;
912
+ toObjectWithKey<K extends keyof T>(key: K): Record<string, T>;
913
+ nonNullMap<U>(callback: (value: T, index: number, array: T[]) => U | null | undefined): U[];
914
+ nonNullMapAsync<U>(callback: (value: T, index: number, array: T[]) => Promise<U | null | undefined>): Promise<U[]>;
915
+ findOrFail(predicate: (value: T, index: number, array: T[]) => boolean, message?: string, thisArg?: any): T;
916
+ selectFor<K>(predicate: (value: T, index: number, array: T[]) => boolean, selector: (value: T) => K, message?: string, thisArg?: any): K;
917
+ createInstances<TTarget>(targetConstructor: new (...args: any[]) => TTarget, ...args: any[]): TTarget[];
918
+ mergeAll(options?: MergeOptions): any;
919
+ }
920
+ interface ArrayConstructor {
921
+ flat<T>(v: T | T[] | T[][]): T[];
922
+ }
923
+ }
924
+
package/dist/index.js CHANGED
@@ -1,28 +1,30 @@
1
- var zt=Object.create;var kr=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var $r=(r,e)=>{return Object.defineProperty(r,"name",{value:e,enumerable:!1,configurable:!0}),r};var Cr=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Y=(r)=>{throw TypeError(r)},Ht=(r,e,t)=>(e in r)?kr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var mr=(r,e,t)=>e.has(r)||Y("Cannot "+t),Gt=(r,e)=>Object(e)!==e?Y('Cannot use the "in" operator on this value'):r.has(e),Pr=(r,e,t)=>(mr(r,e,"read from private field"),t?t.call(r):e.get(r));var Dr=(r,e,t,n)=>(mr(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),Zt=(r,e,t)=>(mr(r,e,"access private method"),t),Lr=(r)=>[,,,zt(r?.[Cr("metadata")]??null)],Rr=["class","method","getter","setter","accessor","field","value","get","set"],N=(r)=>r!==void 0&&typeof r!=="function"?Y("Function expected"):r,Qt=(r,e,t,n,i)=>({kind:Rr[r],name:e,metadata:n,addInitializer:(s)=>t._?Y("Already initialized"):i.push(N(s||null))}),gr=(r,e)=>Ht(e,Cr("metadata"),r[3]),Ir=(r,e,t,n)=>{for(var i=0,s=r[e>>1],f=s&&s.length;i<f;i++)e&1?s[i].call(t):n=s[i].call(t,n);return n},u=(r,e,t,n,i,s)=>{var f,a,p,y,d,m=e&7,O=!!(e&8),b=!!(e&16),P=m>3?r.length+1:m?O?1:2:0,w=Rr[m+5],j=m>3&&(r[P-1]=[]),D=r[P]||(r[P]=[]),A=m&&(!b&&!O&&(i=i.prototype),m<5&&(m>3||!b)&&qt(m<4?i:{get[t](){return Pr(this,s)},set[t](E){Dr(this,s,E)}},t));m?b&&m<4&&$r(s,(m>2?"set ":m>1?"get ":"")+t):$r(i,t);for(var F=n.length-1;F>=0;F--){if(y=Qt(m,t,p={},r[3],D),m){if(y.static=O,y.private=b,d=y.access={has:b?(E)=>Gt(i,E):(E)=>(t in E)},m^3)d.get=b?(E)=>(m^1?Pr:Zt)(E,i,m^4?s:A.get):(E)=>E[t];if(m>2)d.set=b?(E,M)=>Dr(E,i,M,m^4?s:A.set):(E,M)=>E[t]=M}if(a=(0,n[F])(m?m<4?b?s:A[w]:m>4?void 0:{get:A.get,set:A.set}:i,y),p._=1,m^4||a===void 0)N(a)&&(m>4?j.unshift(a):m?b?s=a:A[w]=a:i=a);else if(typeof a!=="object"||a===null)Y("Object expected");else N(f=a.get)&&(A.get=f),N(f=a.set)&&(A.set=f),N(f=a.init)&&j.unshift(f)}return m||gr(r,i),A&&kr(i,t,A),b?m^4?s:A:i};import Br from"fs/promises";import yr from"path";import Xt from"fs/promises";import Tt from"path";import xt from"fs/promises";import vt from"fs/promises";import Kr from"fs/promises";import Ur from"path";import en from"fs/promises";import hr from"path";import _r from"path";var br=async(r)=>{try{return await Br.access(r,Br.constants.R_OK),!0}catch{return!1}},tr=async(r,e)=>{let t=!yr.isAbsolute(r)&&e?["",...e]:[""];for(let n of t){let i=yr.join(n,r);if(await br(i))return yr.resolve(i)}throw Error(`File not found: "${r}"`)},Wr=async(r,e)=>{let t=await tr(r,e?.dirs),n=await Xt.readFile(t,"utf-8"),i=Tt.dirname(t),s={text:{fn:(a)=>a,matching:["\\.txt$","\\.text$"]},json:{fn:JSON.parse,matching:["\\.json$"]},...e?.parsers},f=e?.format?s[e.format]:Object.values(s).find((a)=>a.matching?.some((p)=>new RegExp(p).test(r)));if(!f)throw Error(`Unsupported format for file "${r}" and no matching parser found`);return{content:await f.fn(n),fullPath:t,folderPath:i}},Vt=async(r,e,t)=>{let n={text:{fn:(s)=>s,matching:["\\.txt$","\\.text$"]},json:{fn:JSON.stringify,matching:["\\.json$"]},...t?.encoders},i=t?.format?n[t.format]:Object.values(n).find((s)=>s.matching?.some((f)=>new RegExp(f).test(r)));if(!i)throw Error(`Unsupported format for file "${r}" and no matching encoder found`);await xt.writeFile(r,await i.fn(e))},Jr=async(r,e)=>{if(typeof r==="string"&&!r.includes("*"))return await e.map(r,0,[]);let t=await Array.fromAsync(vt.glob(r,{cwd:e.cwd})),n=e.filter?t.filter(e.filter):t;return await Promise.all(n.map(e.map))},Nr=async(r,e)=>{if(e?.targetDirectory&&e?.removeFirst)try{await Kr.rm(e?.targetDirectory,{recursive:!0,force:!0})}catch(t){throw Error(`Failed to clean the output directory: ${t.message}`)}for(let t of r)await rn(t,e)},rn=async(r,e)=>{let t=Ur.join(e?.targetDirectory??".",r.name),n=Ur.dirname(t);if(e?.classes){if(r.class!==void 0&&!e.classes.includes(r.class))return;if(e.classRequired&&r.class===void 0)throw Error(`Output "${r.name}" is missing class field`)}if(e?.writing?.(r)===!1)return;try{await Kr.mkdir(n,{recursive:!0})}catch(i){throw Error(`Failed to create target directory "${n}" for output "${t}": ${i.message}`)}try{await Vt(t,r.value,{format:r.type??"text"})}catch(i){throw Error(`Failed to write output "${t}": ${i.message}`)}},dr=(r)=>r?_r.isAbsolute(r)?r:_r.join(process.cwd(),r):process.cwd(),tn=async(r,e)=>{let t=[];for(let n of r)try{let i=!hr.isAbsolute(n)?hr.join(dr(e?.cwd),n):n;if(e?.filter?.(i)===!1)continue;let s=await import(i);if(e?.resolveDefault==="only"&&!s.default)throw Error(`Module ${n} does not have a default export`);let f=e?.resolveDefault?s.default??s:s,a=e?.map?await e.map(f,n):f;if(a!==void 0)t.push(a)}catch(i){if(e?.fail?.(n,i)===!1)continue;throw Error(`Failed to import module ${n}: ${i.message??i}`)}return t},Rn=async(r,e)=>{let t=[];for(let n of r){let i=(await Array.fromAsync(en.glob(n,{cwd:dr(e?.cwd)}))).map((s)=>hr.join(dr(e?.cwd),s));t.push(...await tn(i,e))}return t};class z{o;context;constructor(r){this.o=r}}var c=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.sources({[i]:(s)=>n.apply({...this,context:s},s.args)})})},Bn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.sections({[i]:(s)=>{return n.call({...this,context:s},s.section)}})})},Un=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.keys({[i]:(s)=>n.call({...this,context:s},s.value)})})},_n=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.variables({[i]:n})})},Wn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.functions({[i]:n})})},Jn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.encoders({[i]:{fn:n}})})},Kn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.decoders({[i]:{fn:n}})})};import{createHash as W}from"crypto";import I from"path";var Yr=(r)=>({output:(e)=>{delete e.parent[e.key];for(let t of Array.isArray(e.value)?e.value:[e.value])if(typeof t==="string")r.output({name:t,value:e.parent});else r.output({...t,value:t.value??e.parent});return g.SkipSiblings()}});import nn from"path";var zr=(r)=>({load:async(e)=>{let t=e.options.globalContext;for(let{file:n}of Array.isArray(e.value)?e.value:[e.value]){if(!n)throw Error("File reference required");await r.load(n,t.file&&nn.dirname(t.file))}return g.DeleteItem()}});class wr{cache=new Map;maxSize;constructor(r=100){this.maxSize=r}get(r){return this.cache.get(r)}set(r,e){this.evictIfNeeded(),this.cache.set(r,e)}has(r){return this.cache.has(r)}clear(){this.cache.clear()}setMaxSize(r){this.maxSize=r}size(){return this.cache.size}evictIfNeeded(){if(this.cache.size>=this.maxSize){let r=null,e=1/0;for(let[t,n]of this.cache.entries())if(n.timestamp<e)e=n.timestamp,r=t;if(r)this.cache.delete(r)}}}var nr=(r)=>{let e=defined(r.value,"Model value cannot be null or undefined");if(typeof e==="string")return r.parent;let t=e.model;if(!t)return r.parent;if(typeof t==="string")return Object.select(r.root,t);return t};var ir=(r)=>{let e=defined(r.value,"Source value cannot be null or undefined");if(typeof e==="string")return Object.select(r.root,e);if(Array.isArray(e))return e;let t=e;if(typeof t.from==="string")return Object.select(r.root,t.from);return t.from};Array.prototype.findOrFail=function(r,e,t){let n=this.find(r,t);if(n===void 0)throw Error(e??"Element not found");return n};Array.flat=function(r){if(Array.isArray(r))return r.flat(2);else return[r]};Array.prototype.forEachAsync=async function(r){for(let e=0;e<this.length;e++)await r(this[e],e,this)};Array.prototype.groupBy=function(r){return this.reduce((e,t)=>{let n=r(t);if(!e[n])e[n]=[];return e[n].push(t),e},{})};Array.prototype.createInstances=function(r,...e){return this.map((t,n)=>new r(...e,t,n))};Array.prototype.mapAsync=async function(r){return Promise.all(this.map(r))};Array.prototype.nonNullMap=function(r){let e=[];for(let t=0;t<this.length;t++){let n=r(this[t],t,this);if(n!=null)e.push(n)}return e};Array.prototype.nonNullMapAsync=async function(r){let e=[];for(let t=0;t<this.length;t++){let n=await r(this[t],t,this);if(n!=null)e.push(n)}return e};Array.prototype.mergeAll=function(r){let e={};for(let t of this.toReversed())Object.merge(t,e,r);return e};Array.prototype.toObject=function(r,e){return Object.fromEntries(this.map((t)=>{let n=r(t),i=e?e(t):t;return[n,i]}))};Array.prototype.toObjectWithKey=function(r){return Object.fromEntries(this.map((e)=>[String(e[r]),e]))};Array.prototype.selectFor=function(r,e,t,n){let i=this.find(r,n);if(i===void 0)throw Error(t??"Element not found");return e(i)};Array.prototype.sortBy=function(r,e=!0){return this.slice().sort((t,n)=>{let i=r(t),s=r(n);if(i<s)return e?-1:1;if(i>s)return e?1:-1;return 0})};Array.prototype.unique=function(){return Array.from(new Set(this))};Array.prototype.uniqueBy=function(r){let e=new Set;return this.filter((t)=>{let n=r(t);if(e.has(n))return!1;else return e.add(n),!0})};var L;((r)=>{r[r.Explore=0]="Explore",r[r.SkipSiblings=1]="SkipSiblings",r[r.NoExplore=2]="NoExplore",r[r.ReplaceParent=3]="ReplaceParent",r[r.DeleteParent=4]="DeleteParent",r[r.MergeParent=5]="MergeParent",r[r.ReplaceItem=6]="ReplaceItem",r[r.DeleteItem=7]="DeleteItem"})(L||={});class g{action;by;skipSiblings;reexplore;constructor(r,e,t,n){this.action=r,this.by=e,this.skipSiblings=t,this.reexplore=n}static _explore=new g(0);static _noExplore=new g(2);static _skipSiblings=new g(1);static _deleteParent=new g(4);static ReplaceParent(r,e){return new g(3,r,void 0,e)}static SkipSiblings(){return g._skipSiblings}static Explore(){return g._explore}static NoExplore(){return g._noExplore}static DeleteParent(){return g._deleteParent}static MergeParent(r){return new g(5,r)}static ReplaceItem(r,e){return new g(6,r,e)}static DeleteItem(r){return new g(7,void 0,r)}}Object.navigate=async(r,e)=>{let t=new WeakSet,n=[],i=[],s=async(a,p,y)=>{let d=a===null,m=d?g.Explore():await e({key:a,value:p,path:n,parent:y,parents:i});if(p&&typeof p==="object"&&m.action===0){if(t.has(p))return m;if(t.add(p),!d)n.push(a),i.push(y);let O=p;while(await f(O,a,y))O=y[a];if(!d)i.pop(),n.pop()}return m},f=async(a,p,y)=>{let d=Object.keys(a),m=d.length;for(let O=0;O<m;O++){let b=d[O],P=a[b],w=await s(b,P,a),j=w.action;if(j===0||j===2)continue;if(j===6){if(a[b]=w.by,w.skipSiblings)return;continue}if(j===7){if(delete a[b],w.skipSiblings)return;continue}if(j===1)return;if(j===3){if(p===null)throw Error("Cannot replace root object");if(y[p]=w.by,w.reexplore)return!0;return}if(j===4){if(p===null)throw Error("Cannot delete root object");delete y[p];return}if(j===5)delete a[b],Object.assign(a,w.by)}};await s(null,r,null)};Object.find=async function(r,e){let t=[];return await Object.navigate(r,(n)=>{if(e([...n.path,n.key].join("."),n.value))t.push(n.value);return g.Explore()}),t};Object.merge=(r,e,t)=>{for(let n of Object.keys(e)){if(r[n]===void 0)continue;let i=e[n],s=r[n];if(typeof s!==typeof i||Array.isArray(s)!==Array.isArray(i)){let a=t?.mismatch?.(n,s,i,r,e);if(a!==void 0){e[n]=a;continue}throw Error(`Type mismatch: ${n}`)}let f=t?.mode?.(n,s,i,r,e)??e[".merge"]??"merge";switch(f){case"source":e[n]=s;continue;case"target":continue;case"skip":delete e[n],delete r[n];continue;case"merge":break;default:throw Error(`Unknown merge mode: ${f}`)}if(typeof s==="object")if(Array.isArray(s))i.push(...s);else{if(t?.navigate?.(n,s,i,r,e)===!1)continue;Object.merge(s,i,t)}else{if(s===i)continue;let a=t?.conflict?.(n,s,i,r,e);e[n]=a===void 0?i:a}}for(let n of Object.keys(r))if(e[n]===void 0)e[n]=r[n]};var on=/^\[([^=\]]*)([=]*)([^\]]*)\]$/,sn=/^([^[\]]*)\[([^\]]*)]$/,Or=(r,e,t,n)=>{if(r.startsWith("{")&&r.endsWith("}")){let i=r.substring(1,r.length-1);return Object.select(e,i,t)?.toString()}return n?r:void 0},an=(r,e,t,n)=>{let i=Or(e,t,n);if(i)return Object.select(r,i,n);let s=on.exec(e);if(s){let[,a,p,y]=s,d=Or(a.trim(),t,n,!0),m=Or(y.trim(),t,n,!0);if(Array.isArray(r)&&(p==="="||p==="==")&&d)return r.find((O)=>O?.[d]==m)}let f=sn.exec(e);if(f){let[,a,p]=f;return r?.[a]?.[p]}return r?.[e]};Object.select=(r,e,t)=>{let n=void 0,i=void 0,s=e??"",f=(m)=>{if(!m)return[m,!1];return m.endsWith("?")?[m.substring(0,m.length-1),!0]:[m,!1]},a=(m,O)=>{let[b,P]=f(O.pop());if(!b){if(t?.set!==void 0&&i!==void 0&&n!==void 0)n[i]=t.set;return m}let w=an(m,b,r,t);if(w===void 0){if(P||t?.optional||t?.defaultValue!==void 0)return;throw Error(`Unknown path element: "${b}" in "${s}"`)}return n=m,i=b,a(w,O)},p=s.splitNested(t?.separator??".","{","}"),y=void 0;if(p.length>0&&p[p.length-1].startsWith("?="))y=p.pop()?.substring(2);p.reverse();let d=a(r,p);if(d===void 0)return y??t?.defaultValue;return d};Object.deepClone=function(r){if(typeof structuredClone<"u")try{return structuredClone(r)}catch{}return JSON.parse(JSON.stringify(r))};Object.toList=function(r,e){return Object.entries(r).map(([t,n])=>({[e]:t,...n}))};Object.mapEntries=function(r,e){let t=Object.entries(r).map(([n,i])=>e(n,i));return Object.fromEntries(t)};global.AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;global.defined=(r,e="Value is undefined")=>{if(r===void 0||r===null)throw Error(e);return r};String.prototype.tokenize=function(r,e=/\${([^}]+)}/g){return this.replace(e,(t,n)=>{let i=r[n];if(i===null||i===void 0)return"";if(typeof i==="string")return i;if(typeof i==="number"||typeof i==="boolean")return String(i);return String(i)})};String.prototype.toPascal=function(){return this.replace(/((?:[_ ]+)\w|^\w)/g,(r,e)=>e.toUpperCase()).replace(/[^a-zA-Z0-9 ]/g,"").replace(/[_ ]/g,"")};String.prototype.capitalize=function(){return this.replace(/((?:[ ]+)\w|^\w)/g,(r,e)=>e.toUpperCase())};String.prototype.toCamel=function(){return this.toPascal().replace(/((?:[ ]+\w)|^\w)/g,(r,e)=>e.toLowerCase())};String.prototype.toSnake=function(){return this.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/\s+/g,"_")};String.prototype.toKebab=function(){return this.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/\s+/g,"-")};String.prototype.changeCase=function(r){switch(r){case"upper":return this.toUpperCase();case"lower":return this.toLowerCase();case"pascal":return this.toPascal();case"camel":return this.toCamel();case"snake":return this.toSnake();case"kebab":return this.toKebab();default:throw Error(`Unsupported case type: ${r}`)}};String.prototype.splitWithQuotes=function(r=","){let e=[],t=this.length,n=r.length,i=0,s=(f)=>{if(f+n>t)return!1;for(let a=0;a<n;a++)if(this[f+a]!==r[a])return!1;return!0};while(i<t){while(i<t&&this[i]===" ")i++;if(i>=t)break;let f="",a=this[i]==='"'||this[i]==="'";if(a){let p=this[i++];while(i<t&&this[i]!==p)f+=this[i++];if(i<t)i++}else{while(i<t&&!s(i)){let p=this[i];if(p==='"'||p==="'"){f+=p,i++;while(i<t&&this[i]!==p)f+=this[i++];if(i<t)f+=this[i++]}else f+=this[i++]}f=f.trim()}if(f)e.push({value:f,quoted:a});if(s(i))i+=n}return e};String.prototype.splitNested=function(r,e,t){let n=0,i="",s=[];for(let f of this){if(i+=f,f===e)n++;if(f===t)n--;if(n===0&&f===r)s.push(i.slice(0,-1)),i=""}if(i)s.push(i);return s};String.prototype.toStringBuilder=function(){return new q(this.split(`
1
+ var Ht=Object.create;var Dr=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Mr=(r,e)=>{return Object.defineProperty(r,"name",{value:e,enumerable:!1,configurable:!0}),r};var Cr=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),z=(r)=>{throw TypeError(r)},Jt=(r,e,t)=>(e in r)?Dr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var pr=(r,e,t)=>e.has(r)||z("Cannot "+t),Zt=(r,e)=>Object(e)!==e?z('Cannot use the "in" operator on this value'):r.has(e),$r=(r,e,t)=>(pr(r,e,"read from private field"),t?t.call(r):e.get(r));var Pr=(r,e,t,n)=>(pr(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),Qt=(r,e,t)=>(pr(r,e,"access private method"),t),kr=(r)=>[,,,Ht(r?.[Cr("metadata")]??null)],Lr=["class","method","getter","setter","accessor","field","value","get","set"],Y=(r)=>r!==void 0&&typeof r!=="function"?z("Function expected"):r,xt=(r,e,t,n,i)=>({kind:Lr[r],name:e,metadata:n,addInitializer:(s)=>t._?z("Already initialized"):i.push(Y(s||null))}),gr=(r,e)=>Jt(e,Cr("metadata"),r[3]),Rr=(r,e,t,n)=>{for(var i=0,s=r[e>>1],u=s&&s.length;i<u;i++)e&1?s[i].call(t):n=s[i].call(t,n);return n},f=(r,e,t,n,i,s)=>{var u,a,l,y,d,p=e&7,O=!!(e&8),b=!!(e&16),P=p>3?r.length+1:p?O?1:2:0,w=Lr[p+5],j=p>3&&(r[P-1]=[]),D=r[P]||(r[P]=[]),A=p&&(!b&&!O&&(i=i.prototype),p<5&&(p>3||!b)&&Gt(p<4?i:{get[t](){return $r(this,s)},set[t](F){Pr(this,s,F)}},t));p?b&&p<4&&Mr(s,(p>2?"set ":p>1?"get ":"")+t):Mr(i,t);for(var E=n.length-1;E>=0;E--){if(y=xt(p,t,l={},r[3],D),p){if(y.static=O,y.private=b,d=y.access={has:b?(F)=>Zt(i,F):(F)=>(t in F)},p^3)d.get=b?(F)=>(p^1?$r:Qt)(F,i,p^4?s:A.get):(F)=>F[t];if(p>2)d.set=b?(F,M)=>Pr(F,i,M,p^4?s:A.set):(F,M)=>F[t]=M}if(a=(0,n[E])(p?p<4?b?s:A[w]:p>4?void 0:{get:A.get,set:A.set}:i,y),l._=1,p^4||a===void 0)Y(a)&&(p>4?j.unshift(a):p?b?s=a:A[w]=a:i=a);else if(typeof a!=="object"||a===null)z("Object expected");else Y(u=a.get)&&(A.get=u),Y(u=a.set)&&(A.set=u),Y(u=a.init)&&j.unshift(u)}return p||gr(r,i),A&&Dr(i,t,A),b?p^4?s:A:i};import Ir from"fs/promises";import hr from"path";import en from"fs/promises";import tn from"path";import on from"fs/promises";import un from"fs/promises";import qr from"fs/promises";import Br from"path";import cn from"fs/promises";import dr from"path";import _r from"path";Array.prototype.findOrFail=function(r,e,t){let n=this.find(r,t);if(n===void 0)throw Error(e??"Element not found");return n};Array.flat=function(r){if(Array.isArray(r))return r.flat(2);else return[r]};Array.prototype.forEachAsync=async function(r){for(let e=0;e<this.length;e++)await r(this[e],e,this)};Array.prototype.groupBy=function(r){return this.reduce((e,t)=>{let n=r(t);if(!e[n])e[n]=[];return e[n].push(t),e},{})};Array.prototype.createInstances=function(r,...e){return this.map((t,n)=>new r(...e,t,n))};Array.prototype.mapAsync=async function(r){return Promise.all(this.map(r))};Array.prototype.nonNullMap=function(r){let e=[];for(let t=0;t<this.length;t++){let n=r(this[t],t,this);if(n!=null)e.push(n)}return e};Array.prototype.nonNullMapAsync=async function(r){let e=[];for(let t=0;t<this.length;t++){let n=await r(this[t],t,this);if(n!=null)e.push(n)}return e};Array.prototype.mergeAll=function(r){let e={};for(let t of this.slice().reverse())Object.merge(t,e,r);return e};Array.prototype.toObject=function(r,e){return Object.fromEntries(this.map((t)=>{let n=r(t),i=e?e(t):t;return[n,i]}))};Array.prototype.toObjectWithKey=function(r){return Object.fromEntries(this.map((e)=>[String(e[r]),e]))};Array.prototype.selectFor=function(r,e,t,n){let i=this.find(r,n);if(i===void 0)throw Error(t??"Element not found");return e(i)};Array.prototype.sortBy=function(r,e=!0){return this.slice().sort((t,n)=>{let i=r(t),s=r(n);if(i<s)return e?-1:1;if(i>s)return e?1:-1;return 0})};Array.prototype.unique=function(){return Array.from(new Set(this))};Array.prototype.uniqueBy=function(r){let e=new Set;return this.filter((t)=>{let n=r(t);if(e.has(n))return!1;else return e.add(n),!0})};var L;((r)=>{r[r.Explore=0]="Explore",r[r.SkipSiblings=1]="SkipSiblings",r[r.NoExplore=2]="NoExplore",r[r.ReplaceParent=3]="ReplaceParent",r[r.DeleteParent=4]="DeleteParent",r[r.MergeParent=5]="MergeParent",r[r.ReplaceItem=6]="ReplaceItem",r[r.DeleteItem=7]="DeleteItem"})(L||={});class g{action;by;skipSiblings;reexplore;constructor(r,e,t,n){this.action=r,this.by=e,this.skipSiblings=t,this.reexplore=n}static _explore=new g(0);static _noExplore=new g(2);static _skipSiblings=new g(1);static _deleteParent=new g(4);static ReplaceParent(r,e){return new g(3,r,void 0,e)}static SkipSiblings(){return g._skipSiblings}static Explore(){return g._explore}static NoExplore(){return g._noExplore}static DeleteParent(){return g._deleteParent}static MergeParent(r){return new g(5,r)}static ReplaceItem(r,e){return new g(6,r,e)}static DeleteItem(r){return new g(7,void 0,r)}}Object.navigate=async(r,e)=>{let t=new WeakSet,n=[],i=[],s=async(a,l,y)=>{let d=a===null,p=d?g.Explore():await e({key:a,value:l,path:n,parent:y,parents:i});if(l&&typeof l==="object"&&p.action===0){if(t.has(l))return p;if(t.add(l),!d)n.push(a),i.push(y);let O=l;while(await u(O,a,y))O=y[a];if(!d)i.pop(),n.pop()}return p},u=async(a,l,y)=>{let d=Object.keys(a),p=d.length;for(let O=0;O<p;O++){let b=d[O],P=a[b],w=await s(b,P,a),j=w.action;if(j===0||j===2)continue;if(j===6){if(a[b]=w.by,w.skipSiblings)return;continue}if(j===7){if(delete a[b],w.skipSiblings)return;continue}if(j===1)return;if(j===3){if(l===null)throw Error("Cannot replace root object");if(y[l]=w.by,w.reexplore)return!0;return}if(j===4){if(l===null)throw Error("Cannot delete root object");delete y[l];return}if(j===5)delete a[b],Object.assign(a,w.by)}};await s(null,r,null)};Object.find=async function(r,e){let t=[];return await Object.navigate(r,(n)=>{if(e([...n.path,n.key].join("."),n.value))t.push(n.value);return g.Explore()}),t};Object.merge=(r,e,t)=>{for(let n of Object.keys(e)){if(r[n]===void 0)continue;let i=e[n],s=r[n];if(typeof s!==typeof i||Array.isArray(s)!==Array.isArray(i)){let a=t?.mismatch?.(n,s,i,r,e);if(a!==void 0){e[n]=a;continue}throw Error(`Type mismatch: ${n}`)}let u=t?.mode?.(n,s,i,r,e)??e[".merge"]??"merge";switch(u){case"source":e[n]=s;continue;case"target":continue;case"skip":delete e[n],delete r[n];continue;case"merge":break;default:throw Error(`Unknown merge mode: ${u}`)}if(typeof s==="object")if(Array.isArray(s))i.push(...s);else{if(t?.navigate?.(n,s,i,r,e)===!1)continue;Object.merge(s,i,t)}else{if(s===i)continue;let a=t?.conflict?.(n,s,i,r,e);e[n]=a===void 0?i:a}}for(let n of Object.keys(r))if(e[n]===void 0)e[n]=r[n]};var Xt=/^\[([^=\]]*)([=]*)([^\]]*)\]$/,Ut=/^([^[\]]*)\[([^\]]*)]$/,yr=(r,e,t,n)=>{if(r.startsWith("{")&&r.endsWith("}")){let i=r.substring(1,r.length-1);return Object.select(e,i,t)?.toString()}return n?r:void 0},Tt=(r,e,t,n)=>{let i=yr(e,t,n);if(i)return Object.select(r,i,n);let s=Xt.exec(e);if(s){let[,a,l,y]=s,d=yr(a.trim(),t,n,!0),p=yr(y.trim(),t,n,!0);if(Array.isArray(r)&&(l==="="||l==="==")&&d)return r.find((O)=>O?.[d]==p)}let u=Ut.exec(e);if(u){let[,a,l]=u;return r?.[a]?.[l]}return r?.[e]};Object.select=(r,e,t)=>{let n=void 0,i=void 0,s=e??"",u=(p)=>{if(!p)return[p,!1];return p.endsWith("?")?[p.substring(0,p.length-1),!0]:[p,!1]},a=(p,O)=>{let[b,P]=u(O.pop());if(!b){if(t?.set!==void 0&&i!==void 0&&n!==void 0)n[i]=t.set;return p}let w=Tt(p,b,r,t);if(w===void 0){if(P||t?.optional||t?.defaultValue!==void 0)return;throw Error(`Unknown path element: "${b}" in "${s}"`)}return n=p,i=b,a(w,O)},l=s.splitNested(t?.separator??".","{","}"),y=void 0;if(l.length>0&&l[l.length-1].startsWith("?="))y=l.pop()?.substring(2);l.reverse();let d=a(r,l);if(d===void 0)return y??t?.defaultValue;return d};Object.deepClone=function(r){if(typeof structuredClone<"u")try{return structuredClone(r)}catch{}return JSON.parse(JSON.stringify(r))};Object.toList=function(r,e){return Object.entries(r).map(([t,n])=>({[e]:t,...n}))};Object.mapEntries=function(r,e){let t=Object.entries(r).map(([n,i])=>e(n,i));return Object.fromEntries(t)};global.AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;global.defined=(r,e="Value is undefined")=>{if(r===void 0||r===null)throw Error(e);return r};String.prototype.tokenize=function(r,e=/\${([^}]+)}/g){return this.replace(e,(t,n)=>{let i=r[n];if(i===null||i===void 0)return"";if(typeof i==="string")return i;if(typeof i==="number"||typeof i==="boolean")return String(i);return String(i)})};String.prototype.toPascal=function(){return this.replace(/((?:[_ ]+)\w|^\w)/g,(r,e)=>e.toUpperCase()).replace(/[^a-zA-Z0-9 ]/g,"").replace(/[_ ]/g,"")};String.prototype.capitalize=function(){return this.replace(/((?:[ ]+)\w|^\w)/g,(r,e)=>e.toUpperCase())};String.prototype.toCamel=function(){return this.toPascal().replace(/((?:[ ]+\w)|^\w)/g,(r,e)=>e.toLowerCase())};String.prototype.toSnake=function(){return this.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/\s+/g,"_")};String.prototype.toKebab=function(){return this.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/\s+/g,"-")};String.prototype.changeCase=function(r){switch(r){case"upper":return this.toUpperCase();case"lower":return this.toLowerCase();case"pascal":return this.toPascal();case"camel":return this.toCamel();case"snake":return this.toSnake();case"kebab":return this.toKebab();default:throw Error(`Unsupported case type: ${r}`)}};String.prototype.splitWithQuotes=function(r=","){let e=[],t=this.length,n=r.length,i=0,s=(u)=>{if(u+n>t)return!1;for(let a=0;a<n;a++)if(this[u+a]!==r[a])return!1;return!0};while(i<t){while(i<t&&this[i]===" ")i++;if(i>=t)break;let u="",a=this[i]==='"'||this[i]==="'";if(a){let l=this[i++];while(i<t&&this[i]!==l)u+=this[i++];if(i<t)i++}else{while(i<t&&!s(i)){let l=this[i];if(l==='"'||l==="'"){u+=l,i++;while(i<t&&this[i]!==l)u+=this[i++];if(i<t)u+=this[i++]}else u+=this[i++]}u=u.trim()}if(u)e.push({value:u,quoted:a});if(s(i))i+=n}return e};String.prototype.splitNested=function(r,e,t){let n=0,i="",s=[];for(let u of this){if(i+=u,u===e)n++;if(u===t)n--;if(n===0&&u===r)s.push(i.slice(0,-1)),i=""}if(i)s.push(i);return s};String.prototype.toStringBuilder=function(){return new H(this.split(`
2
2
  `))};String.prototype.padBlock=function(r,e=`
3
3
  `,t=" "){let n=t.repeat(r);return this.split(e).map((i)=>n+i).join(e)};String.prototype.stripIndent=function(){let r=this.split(/\r?\n/),e=r.filter((n)=>n.trim().length>0).map((n)=>/^[ \t]*/.exec(n)?.[0].length??0),t=e.length>0?Math.min(...e):0;if(t===0)return this;return r.map((n)=>n.slice(t)).join(`
4
- `)};String.prototype.toHtmlLink=function(r){return`<a href="${r??this.toString()}">${this.toString()}</a>`};String.prototype.toRgb=function(){let r=this.toString().replace("#","");if(r.length!==6)throw Error("Invalid hex color");let e=parseInt(r.substring(0,2),16),t=parseInt(r.substring(2,4),16),n=parseInt(r.substring(4,6),16);return`rgb(${e.toString()}, ${t.toString()}, ${n.toString()})`};String.prototype.toArgb=function(){let r=this.toString().replace("#","");if(r.length!==8)throw Error("Invalid hex color");let e=parseInt(r.substring(0,2),16),t=parseInt(r.substring(2,4),16),n=parseInt(r.substring(4,6),16),i=parseInt(r.substring(6,8),16);return`argb(${e.toString()}, ${t.toString()}, ${n.toString()}, ${i.toString()})`};String.prototype.single=function(r){return this.replaceAll(new RegExp(`(${r})+`,"g"),"$1")};String.prototype.remove=function(r){return this.replaceAll(new RegExp(r,"g"),"")};String.prototype.toAlphanum=function(){return this.replace(/[^a-z0-9]/gi,"")};String.prototype.toAlpha=function(){return this.replace(/[^a-z]/gi,"")};class fn{options;constructor(r){this.options={level:"INFO",showClass:!1,levels:["DEBUG","VERBOSE","INFO","WARN","ERROR"],timeStamp:!1,timeOptions:{second:"2-digit",minute:"2-digit",hour:"2-digit",day:"2-digit",month:"2-digit",year:"2-digit"},logFunction:(e,...t)=>{switch(e){case"ERROR":console.error(...t);break;case"WARN":console.warn(...t);break;case"DEBUG":console.debug(...t);break;case"VERBOSE":console.log(...t);break;default:console.log(...t)}},...r}}write(r,...e){if(this.options.level){let i=this.options.levels.indexOf(this.options.level)??-1,s=this.options.levels.indexOf(r);if(s===-1)throw Error(`Unknown log level: ${r}`);if(s<i)return}let t=[],n=[];if(this.options.timeStamp)n.push(new Date().toLocaleString(this.options.timeLocale,this.options.timeOptions));if(this.options.showClass)n.push(r);if(n.length>0)t.push(`[${n.join(" ")}]`);t.push(...e),this.options.logFunction(r,...t)}info(...r){this.write("INFO",...r)}error(...r){this.write("ERROR",...r)}warn(...r){this.write("WARN",...r)}debug(...r){this.write("DEBUG",...r)}verbose(...r){this.write("VERBOSE",...r)}}class q{#r=[];#e=0;options;constructor(r,e){if(r instanceof q)this.options={...r.options,...e},this.#r.push(...r.#r);else if(this.options=e??{},r)if(Array.isArray(r))this.#r.push(...r);else this.#r.push(r)}setOptions(r){return this.options=r,this}clear(){return this.#r.length=0,this}isEmpty(){return this.#r.length===0}toString(){return this.#r.join("")}indent(){return this.#e+=1,this}dedent(){if(this.#e>0)this.#e-=1;return this}getCurrentIndent(){return this.#e}getLines(){return this.toString().split(`
4
+ `)};String.prototype.toHtmlLink=function(r){return`<a href="${r??this.toString()}">${this.toString()}</a>`};String.prototype.toRgb=function(){let r=this.toString().replace("#","");if(r.length!==6)throw Error("Invalid hex color");let e=parseInt(r.substring(0,2),16),t=parseInt(r.substring(2,4),16),n=parseInt(r.substring(4,6),16);return`rgb(${e.toString()}, ${t.toString()}, ${n.toString()})`};String.prototype.toArgb=function(){let r=this.toString().replace("#","");if(r.length!==8)throw Error("Invalid hex color");let e=parseInt(r.substring(0,2),16),t=parseInt(r.substring(2,4),16),n=parseInt(r.substring(4,6),16),i=parseInt(r.substring(6,8),16);return`argb(${e.toString()}, ${t.toString()}, ${n.toString()}, ${i.toString()})`};String.prototype.single=function(r){return this.replaceAll(new RegExp(`(${r})+`,"g"),"$1")};String.prototype.remove=function(r){return this.replaceAll(new RegExp(r,"g"),"")};String.prototype.toAlphanum=function(){return this.replace(/[^a-z0-9]/gi,"")};String.prototype.toAlpha=function(){return this.replace(/[^a-z]/gi,"")};class Vt{options;constructor(r){this.options={level:"INFO",showClass:!1,levels:["DEBUG","VERBOSE","INFO","WARN","ERROR"],timeStamp:!1,timeOptions:{second:"2-digit",minute:"2-digit",hour:"2-digit",day:"2-digit",month:"2-digit",year:"2-digit"},logFunction:(e,...t)=>{switch(e){case"ERROR":console.error(...t);break;case"WARN":console.warn(...t);break;case"DEBUG":console.debug(...t);break;case"VERBOSE":console.log(...t);break;default:console.log(...t)}},...r}}write(r,...e){if(this.options.level){let i=this.options.levels.indexOf(this.options.level),s=this.options.levels.indexOf(r);if(i===-1)throw Error(`Unknown configured log level: ${this.options.level}`);if(s===-1)throw Error(`Unknown log level: ${r}`);if(s<i)return}let t=[],n=[];if(this.options.timeStamp)n.push(new Date().toLocaleString(this.options.timeLocale,this.options.timeOptions));if(this.options.showClass)n.push(r);if(n.length>0)t.push(`[${n.join(" ")}]`);t.push(...e),this.options.logFunction(r,...t)}info(...r){this.write("INFO",...r)}error(...r){this.write("ERROR",...r)}warn(...r){this.write("WARN",...r)}debug(...r){this.write("DEBUG",...r)}verbose(...r){this.write("VERBOSE",...r)}}class H{#r=[];#e=0;options;constructor(r,e){if(r instanceof H)this.options={...r.options,...e},this.#r.push(...r.#r);else if(this.options=e??{},r)if(Array.isArray(r))this.#r.push(...r);else this.#r.push(r)}setOptions(r){return this.options=r,this}clear(){return this.#r.length=0,this}isEmpty(){return this.#r.length===0}toString(){return this.#r.join("")}indent(){return this.#e+=1,this}dedent(){if(this.#e>0)this.#e-=1;return this}getCurrentIndent(){return this.#e}getLines(){return this.toString().split(`
5
5
  `)}formatLine(r){r??=`
6
6
  `;let e=(this.options.indentChar??" ").repeat(this.#e*(this.options.indentSize??2));if(this.options.trim)r=r.trim();return e+(this.options.linePrefix??"")+r+(this.options.lineSuffix??"")+(this.options.lineSeparator??`
7
- `)}write(...r){return this.#r.push(...r.flatMap((e)=>{if(e!==void 0){if(typeof e==="string")return e;if(Array.isArray(e))return e.flat();if(e instanceof q)return e.toString();if(typeof e==="function")return e(this);return String(e)}}).filter((e)=>e!==void 0)),this}writeLine(...r){return this.write(r.length>0?r.map((e)=>this.formatLine(e)):`
8
- `)}writeMap(r,e){return r.forEach((t,n)=>e(t,n,this)),this}}class un extends q{header(r,e=1){return this.writeLine(`${"#".repeat(e)} ${r}`,"")}codeBlock(r,e){if(e??="",this.writeLine("```"+e),r!==void 0)this.writeLine(r).endCodeBlock();return this}endCodeBlock(){return this.writeLine("```")}link(r,e){return this.write(`[${r}](${e})`)}table(r,e){let t=r.map((s,f)=>{let a=s.length;return e.forEach((p)=>{if(p[f])a=Math.max(a,p[f].length)}),a}),n=r.map((s,f)=>s.padEnd(t[f]));this.writeLine("| "+n.join(" | ")+" |");let i=t.map((s)=>"-".repeat(s));return this.writeLine("| "+i.join(" | ")+" |"),e.forEach((s)=>{let f=s.map((a,p)=>a.padEnd(t[p]));this.writeLine("| "+f.join(" | ")+" |")}),this}blockquote(r){return r.split(`
9
- `).forEach((e)=>this.writeLine("> "+e)),this}bold(r){return this.write(`**${r}**`)}italic(r){return this.write(`*${r}*`)}item(r){return this.writeLine(`- ${r}`)}items(r){if(Array.isArray(r))r.forEach((e)=>this.item(e));else Object.entries(r).forEach(([e,t])=>t!==void 0&&this.item(`${e}: ${t!==void 0?String(t):""}`));return this}orderedList(r,e=1){return r.forEach((t,n)=>this.writeLine(`${(n+e).toString()}. ${t}`)),this}code(r){return this.write(`\`${r}\``)}horizontalRule(){return this.writeLine("---")}image(r,e){return this.writeLine(`![${r}](${e})`)}strikethrough(r){return this.write(`~~${r}~~`)}highlight(r){return this.write(`==${r}==`)}subscript(r){return this.write(`~${r}~`)}superscript(r){return this.write(`^${r}^`)}taskList(r){return r.forEach((e)=>this.writeLine(`- [${e.checked?"x":" "}] ${e.text}`)),this}#r=0;section(r,e){if(e!==void 0)this.#r=e;else this.#r++;return this.header(r,this.#r)}endSection(){if(this.#r>0)this.#r--;return this}setSectionLevel(r){return this.#r=r,this}}var qr=(r,e)=>{if(typeof r.value==="string"){if(r.quoted)return r.value;if(r.value.startsWith("[")&&r.value.endsWith("]")){let t=r.value.slice(1,-1);if(t.trim()==="")return[];return t.split(";").map((n)=>{let i=n.trim();if(!isNaN(+i))return+i;return i})}if(r.value.startsWith("{")&&r.value.endsWith("}")){if(r.value.slice(1,-1).trim()==="")return{}}if(r.value==="null")return null;if(r.value==="undefined")return;if(r.value.startsWith("@"))return r.value.slice(1);if(!isNaN(+r.value))return+r.value}return e(r.value)},or=(r,e,t,n,i,s)=>{let f=n?.(r)??r,a=i(f);if(a[0])return a[1];if(!e){let p=Object.select(t,r),y=i(p);if(y[0])return y[1]}throw Error(s)},sr=(r,e,t,n,i)=>{let s=typeof r.types==="function"?r.types(n,e.value,i):r.types?.[n];if(!s||s==="ref")return qr(e,(a)=>Object.select(t,a));let f=qr(e,()=>e.value);if(Array.isArray(s)){if(!s.includes(f))throw Error(`Argument ${n.toString()} must be one of [${s.join(", ")}]: ${f}`);return f}if(typeof s==="string"){if(s.endsWith("?")){let a=s.slice(0,-1);if(e.value==="null")return g.ReplaceItem(null);if(e.value==="undefined")return g.ReplaceItem(void 0);if(e.value==="")return"";s=a}switch(s){case"any":return f;case"array":return or(f,e.quoted,t,null,(a)=>[Array.isArray(a),a],`Argument ${n.toString()} must be an array: ${f}`);case"object":return or(f,e.quoted,t,null,(a)=>[typeof a==="object"&&a!==null,a],`Argument ${n.toString()} must be an object: ${f}`);case"number":return or(f,e.quoted,t,(a)=>Number(a),(a)=>[!isNaN(a),a],`Argument ${n.toString()} must be a number: ${f}`);case"boolean":return or(f,e.quoted,t,null,(a)=>{if([!0,"true","1",1,"yes","on"].includes(a))return[!0,!0];if([!1,"false","0",0,"no","off"].includes(a))return[!0,!1];if([null,"null","undefined",void 0,""].includes(a))return[!0,!1];if(Array.isArray(a))return[!0,a.length>0];return[!1,!1]},`Argument ${n.toString()} must be a boolean: ${f}`);case"string":return f.toString();default:throw Error(`Unknown type for argument ${n.toString()}: ${s}`)}}return s(f,t,n,e.quoted)};var ar=(r,e)=>{let t=r?.[e];if(t===void 0)throw Error(`Unhandled field processor type: ${e}`);return typeof t==="function"?{options:{},fn:t}:{options:t,fn:t.fn}},Hr=(r)=>!r.quoted&&r.value.startsWith("."),cn=(r)=>{let e={};for(let t of r){if(!Hr(t))continue;let n=t.value.indexOf("="),i=n>-1?t.value.slice(1,n):t.value.slice(1),s=n>-1?t.value.slice(n+1):"";if(s.length>=2){let f=s[0],a=s[s.length-1];if(f==='"'&&a==='"'||f==="'"&&a==="'")s=s.slice(1,-1)}if(!e[i])e[i]=[];e[i].push(s)}return e},Gr=(r,e,t)=>{let n=(r??"").splitWithQuotes(),i=cn(n),s=n.filter((a)=>!Hr(a)),f=e.options.processArgs===!1?[]:s.map((a,p)=>sr(e.options,a,t,p,s));return{rawArgs:s,parsedArgs:f,tags:i}};var ln=(r)=>{return r!==null&&typeof r==="object"&&"action"in r},Zr=(r,e)=>e.keys!==void 0&&r.key.startsWith(".")&&e.keys[r.key.substring(1)]!==void 0,Qr=async(r,e,t,n)=>{let{key:i,parent:s}=r,f=ar(n.keys,i.substring(1));if(f.options.processArgs!==!1&&(typeof f.options.types==="function"||f.options.types?.[0]!==void 0))r.value=sr(f.options,{value:r.value,quoted:!1},t,0,[]);if(typeof r.value!=="string")await $(r.value,{...n,root:{...t,parent:r.parent,parents:r.parents},filters:[...n.filters??[],...f.options.filters??[]]});let a=await f.fn({path:e,root:t,parent:s,key:i,options:n,value:r.value,args:[],rawArgs:[],tags:{}});return ln(a)?a:g.ReplaceParent(a)};var Xr=async(r,e,t,n)=>{if(!e?.onSection&&!e?.onSectionConfig&&!e?.sections)return[r,!1];let i=/<@\s*section(?:\s*:\s*([\w-]+))?\s*@>([\s\S]*?)<@\s*\/\s*section\s*@>/g,s,f=r,a=0,p=!1,y={content:f,root:n,path:t,options:e,section:{}};while((s=i.exec(r))!==null){p=!0;let[d,m,O]=s,b=s.index,P=b+d.length,w=r[P]===`
10
- `;if(w)P++;let j=b+a,D=P+a,A={},F=O,E=/(^|\r?\n)[ \t]*---[ \t]*(\r?\n|$)/m.exec(O);if(E){let J=O.slice(0,E.index),lr=E.index+E[0].length;F=O.slice(lr);let rr=J.stripIndent().trim();if(rr.length>0)try{A=e?.configParser?.(rr)??{}}catch(pr){throw Error(`Failed to parse YAML config for section: ${pr.message}`)}}else if(/^\r?\n/.test(F))F=F.replace(/^\r?\n/,"");F=F.stripIndent().replace(/(?:\r?\n[ \t]*)+$/,"").replace(/[ \t]+$/,"");let M={config:m?{...A,type:m}:A,content:F};if(y.content=f,y.section=M,Object.keys(M.config).length>0){if(await e.onSectionConfig?.(y)!==!1)await $(M.config,{...e,root:n})}let T=y.section.config.type?e.sections?.[y.section.config.type]:void 0,B;if(T)B=await T(y);else if(e.onSection)B=await e.onSection(y);if(M.trim)M.content=M.content.trim();if(M.indent)M.content=M.content.split(`
11
- `).map((J)=>" ".repeat(M.indent)+J).join(`
12
- `);let C="";if(B===!0||M.show)C=M.content;else if(typeof B==="string")C=B;if(w&&C!==""&&!C.endsWith(`
13
- `))C+=`
14
- `;let x=f.lastIndexOf(`
15
- `,j-1),V=x===-1?0:x+1,v=f.slice(V,j).trim().length===0?V:j;f=f.slice(0,v)+C+f.slice(D),a+=C.length-(D-v),y.content=f}return[f,p]};var Ar=(r)=>{let e=[],t=0;while(t<r.length)if(r[t]==="$"&&r[t+1]==="("&&(t===0||r[t-1]!=="\\")){let n=t;t+=2;let i=1;for(;t<r.length;t++)if(r[t]==="(")i++;else if(r[t]===")"){if(i--,i===0){e.push([n,t]);break}}if(i!==0)throw Error(`Unmatched opening $( at position ${n.toString()}`);t++}else t++;return e};var Tr=(r)=>({value:r}),pn=(r)=>{return r!==null&&typeof r==="object"},xr=async(r,e,t)=>{for(let n=e.length-1;n>=0;n--){let[i,s]=e[n],f=r.slice(i+2,s),a=await xr(f,Ar(f),t);if(typeof a==="object")return a;let p=await t(a,r);if(pn(p))return p.value;r=r.slice(0,i)+p+r.slice(s+1)}return r},Vr=async(r,e)=>xr(r,Ar(r),e);var mn=(r)=>{return r!==null&&typeof r==="object"&&"action"in r},gn=/([\w\d.-_/]+):(.+)/,yn=async(r,e,t,n)=>{let i=await(async()=>{let s=gn.exec(r);if(!s)return await Object.select(e,r);let[f,a,p]=s,y=ar(n.sources,a),d=Gr(p,y,e);return await y.fn({args:d.parsedArgs,rawArgs:d.rawArgs,tags:d.tags,key:a,options:n,root:e,path:t,value:null})})();if(i===null||i===void 0)return"";if(typeof i==="object")return Tr(i);return i},jr=async(r,e,t,n)=>{let i=await Vr(e,(s)=>yn(s,t,r,n));if(mn(i))return i;if(i===e)return g.Explore();if(typeof i==="string"){let s=await jr(r,i,t,n);if(s.action!==L.Explore)return s}return g.ReplaceItem(i)};var $=async(r,e)=>{return e??={},await Object.navigate(r,async(t)=>{let n=[...t.path,t.key].join(".");if(e?.filters?.length&&e.filters.some((a)=>a.test(n)))return g.NoExplore();let i=t.path.length===0,s=t.parents.length>0?t.parents.toReversed():[];if(i){if(s.length>0)throw Error("Root object should not have a parent");s=e?.root?.parents?[e.root.parent,...e.root.parents.toReversed()]:[]}let f={...r,...e.root,this:t.parent,parent:s.length>0?s[0]:null,parents:s};try{if(t.key.startsWith("$"))return g.NoExplore();let a=g.Explore();if(typeof t.value==="string"){let p=t.value,y=!1;while(!0){let[d,m]=await Xr(p,e,n,f);if(y=y||m,a=await jr(n,d,f,e),a.action===L.ReplaceItem&&typeof a.by==="string"){p=a.by;continue}if(a.action===L.Explore&&m&&d!==p)a=g.ReplaceItem(d);break}if(a.action===L.Explore&&p!==t.value)a=g.ReplaceItem(p);switch(a.action){case L.Explore:break;case L.ReplaceItem:t.value=a.by;break;default:return a}}if(Zr(t,e))a=await Qr(t,n,f,e);return a}catch(a){throw Error(`${a.message}
16
- (${n})`)}}),r};var vr=(r,e)=>e?{fn:(t)=>r(...t.args),types:e}:(t)=>r(...t.args),Pi=(r,e)=>Object.fromEntries(r.map((t)=>[t.name,vr(t,e?.types?.[t.name])])),H=(r,e)=>Object.fromEntries((e?.keys??Object.keys(r)).map((t)=>[t,vr(r[t],e?.types?.[t])]));var fr=async(r,e)=>{let t=r.value;if(t.selector===void 0)return e;if(typeof t.selector!=="string"){let n=JSON.parse(JSON.stringify(t.selector));return await $(n,{...r.options,root:{...r.root,result:e}}),n}return await Object.select({...r.root,result:e},t.selector)};import U from"path";class _{constructor(){}static normalize(r){return U.normalize(U.resolve(r))}static resolveInContext(r,e){let t=e??process.cwd(),n=U.isAbsolute(r)?r:U.join(t,r);return this.normalize(n)}static isDirectoryPattern(r){return r.endsWith("/")}static isGlobPattern(r){return r.includes("*")}static toAbsolute(r,e){if(U.isAbsolute(r))return r;return U.join(e??process.cwd(),r)}}var R={and:(...r)=>r.every((e)=>!!e),or:(...r)=>r.some((e)=>!!e),xor:(...r)=>r.filter((e)=>!!e).length===1,true:(...r)=>r.every((e)=>!!e),false:(...r)=>r.every((e)=>!e),eq:(...r)=>r.every((e)=>e===r[0]),ne:(...r)=>r.some((e)=>e!==r[0]),lt:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]<e),le:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]<=e),gt:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]>e),ge:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]>=e),in:(r,e)=>{if(Array.isArray(e))return e.includes(r);if(typeof r==="string")return r.includes(e);if(Array.isArray(r))return r.includes(e);return!1},notin:(r,e)=>!R.in(r,e),contains:(r,e)=>r.includes(e),notcontains:(r,e)=>!r.includes(e),containsi:(r,e)=>r.toLowerCase().includes(e.toLowerCase()),notcontainsi:(r,e)=>!r.toLowerCase().includes(e.toLowerCase()),null:(...r)=>r.every((e)=>e===null||e===void 0),notnull:(...r)=>r.every((e)=>e!==null&&e!==void 0),empty:(...r)=>r.every((e)=>e===""),notempty:(...r)=>r.every((e)=>e!==""),nullorempty:(...r)=>r.every((e)=>e===null||e===void 0||e===""),notnullorempty:(...r)=>r.every((e)=>e!==null&&e!==void 0&&e!=="")},ur={and:()=>"boolean",or:()=>"boolean",xor:()=>"boolean",true:()=>"boolean",false:()=>"boolean",lt:()=>"number",le:()=>"number",gt:()=>"number",ge:()=>"number"};var re=()=>({each:{filters:[/select|model/],fn:async(r)=>{let e=r.value;delete r.parent[r.key];let t=await ir(r),n=await nr(r);if(!Array.isArray(t))throw Error('Key "each" requires a source list');if(n===void 0)throw Error('Key "each" must define a model');if(e.extend?.model)n=[e.model,...Array.isArray(e.extend.model)?e.extend.model:[e.extend.model]].mergeAll();let i=[];for(let s=0;s<t.length;s++){let f=Object.deepClone(n);if(await $(f,{...r.options,root:{...r.root,index:s,item:t[s],instance:f}}),e.extend?.result){let a=e.extend.result;f=[f,...Array.isArray(a)?a:[a]].mergeAll()}i.push(await fr(r,f))}return i}}});var ee=()=>({map:{filters:[/select|model/],fn:async(r)=>{delete r.parent[r.key];let e=await ir(r),t=await nr(r);if(!Array.isArray(e))throw Error('Key "map" requires a source list');if(t===void 0)throw Error('Key "map" must define a model');let n=[];return await e.forEachAsync(async(i,s)=>{let f=Object.deepClone(t);await $(f,{...r.options,root:{...r.root,index:s,item:i,instance:f}}),n.push(await fr(r,f))}),n}}});var te=()=>({concat:async(r)=>{let e=[];for(let t of Array.isArray(r.value)?r.value:[r.value])e.push(...await Object.select(r.root,t));return e.filter((t)=>t!==void 0)}});var ne=()=>({extends:async(r)=>{let e=async(t,n)=>{for(let i of Array.isArray(n)?n:[n]){let s=await Object.select(r.root,i),f=Object.deepClone(s);if(f[r.key])await e(f,f[r.key]);await $(f,{...r.options}),Object.merge(f,t),delete t[r.key]}};return await e(r.parent,r.value),g.Explore()},group:(r)=>{let e=r.root.parent,t=r.value,{items:n,...i}=t;return t.items.forEach((s)=>e.push({...i,...s})),g.DeleteParent()}});var ie=(r)=>({skip:{types:{0:"boolean"},fn:(e)=>e.value?g.DeleteParent():g.DeleteItem()},metadata:({path:e,value:t})=>{return r.metadata(e,t),g.DeleteItem()},if:{types:{0:"boolean"},fn:async(e)=>{let t=e.parent[".then"],n=e.parent[".else"];if(t!==void 0)delete e.parent[".then"];if(n!==void 0)delete e.parent[".else"];let i=e.value?t:n;if(i===void 0)return g.DeleteItem();if(typeof i==="string")return(await $({value:i},{...e.options,root:{...e.root}})).value;return g.ReplaceParent(i,!0)}},switch:(e)=>{let t=e.value;if(!t.cases)throw Error("Missing cases for switch");if(t.cases[t.from]!==void 0)return g.ReplaceParent(t.cases[t.from],!0);if(t.default!==void 0)return g.ReplaceParent(t.default,!0);return g.DeleteParent()}});var oe=()=>({from:async({root:r,parent:e,value:t})=>{let n=await Object.select(r,t);if(n===null||n===void 0)throw Error(`Unable to resolve reference: ${t}`);if(e.content){if(Array.isArray(e.content)&&Array.isArray(n))return[...n,...e.content];return Object.merge(n,e.content),e.content}return n}});import se from"node:vm";var ae=(r)=>({modules:async(e)=>{for(let[t,n]of Object.entries(e.value)){let i=se.createContext({console,objector:r,document:e.root}),s=new se.SourceTextModule(n,{identifier:t,context:i});await s.link((f)=>{throw Error(`Module ${f} is not allowed`)}),await s.evaluate(),r.sources(Object.fromEntries(Object.entries(s.namespace).map(([f,a])=>[`${t}.${f}`,(p)=>a(p,...p.args)])))}return g.DeleteItem()}});var fe=()=>({try:{fn:(r)=>{let e=r.parent[".catch"];if(e!==void 0)delete r.parent[".catch"];try{return r.value}catch(t){if(e!==void 0)return e;return g.DeleteItem()}}}});var ue=()=>({let:{fn:(r)=>{let e=r.value;return Object.assign(r.root,e),g.DeleteItem()}}});var ce=()=>({tap:{fn:(r)=>{return console.log(`[tap] ${r.path}:`,r.value),r.value}}});var hn=(r,e)=>{let t=e.section.config.using,n=r.getFunctions();if(!t)return n;let i={};return t.forEach((s)=>{if(s in n){i[s]=n[s];return}if(s in e.root){i[s]=e.root[s];return}throw Error(`Function or variable "${s}" not found for script section`)}),i},Sr=(r,e,t,n,i=[])=>{let s=hn(r,t),f=["section","context","config","system",...Object.keys(s),...i],a=[e,t.root,t.section.config,r,...Object.values(s)];return[new AsyncFunction(...f,n).bind(t),a]},dn=(r,e)=>{let t={write:(...n)=>{return e.push(...n),t},writeLine:(...n)=>{return e.push(...n.map((i)=>i+`
7
+ `)}write(...r){return this.#r.push(...r.flatMap((e)=>{if(e!==void 0){if(typeof e==="string")return e;if(Array.isArray(e))return e.flat();if(e instanceof H)return e.toString();if(typeof e==="function")return e(this);return String(e)}}).filter((e)=>e!==void 0)),this}writeLine(...r){return this.write(r.length>0?r.map((e)=>this.formatLine(e)):`
8
+ `)}writeMap(r,e){return r.forEach((t,n)=>e(t,n,this)),this}}class vt extends H{#r=0;#e="```";#t(r){return Math.min(6,Math.max(1,Math.floor(r)))}#n(r){if(r===void 0)return"```";let e=0;for(let t of r.matchAll(/`+/g))e=Math.max(e,t[0].length);return"`".repeat(Math.max(3,e+1))}header(r,e=1){let t=this.#t(e);return this.writeLine(`${"#".repeat(t)} ${r}`,"")}codeBlock(r,e){let t=this.#n(r);if(this.#e=t,e??="",this.writeLine(t+e),r!==void 0)this.writeLine(r).endCodeBlock();return this}endCodeBlock(){let r=this.#e;return this.#e="```",this.writeLine(r)}link(r,e,t){if(t)return this.write(`[${r}](${e} "${t}")`);return this.write(`[${r}](${e})`)}table(r,e){if(r.length===0)throw Error("Table requires at least one header");let t=r.map((s,u)=>{let a=s.length;return e.forEach((l)=>{if(l[u])a=Math.max(a,l[u].length)}),a}),n=r.map((s,u)=>s.padEnd(t[u]));this.writeLine("| "+n.join(" | ")+" |");let i=t.map((s)=>"-".repeat(s));return this.writeLine("| "+i.join(" | ")+" |"),e.forEach((s)=>{let u=r.map((a,l)=>(s[l]??"").padEnd(t[l]));this.writeLine("| "+u.join(" | ")+" |")}),this}blockquote(r){return r.split(`
9
+ `).forEach((e)=>this.writeLine("> "+e)),this}bold(r){return this.write(`**${r}**`)}italic(r){return this.write(`*${r}*`)}item(r){return this.writeLine(`- ${r}`)}items(r){if(Array.isArray(r))r.forEach((e)=>this.item(e));else Object.entries(r).forEach(([e,t])=>t!==void 0&&this.item(`${e}: ${t!==void 0?String(t):""}`));return this}orderedList(r,e=1){return r.forEach((t,n)=>this.writeLine(`${(n+e).toString()}. ${t}`)),this}code(r){return this.write(`\`${r}\``)}horizontalRule(){return this.writeLine("---")}image(r,e){return this.writeLine(`![${r}](${e})`)}strikethrough(r){return this.write(`~~${r}~~`)}highlight(r){return this.write(`==${r}==`)}subscript(r){return this.write(`~${r}~`)}superscript(r){return this.write(`^${r}^`)}taskList(r){return r.forEach((e)=>this.writeLine(`- [${e.checked?"x":" "}] ${e.text}`)),this}section(r,e){if(e!==void 0)this.#r=this.#t(e);else this.#r=Math.min(6,this.#r+1);return this.header(r,this.#r)}endSection(){if(this.#r>0)this.#r--;return this}setSectionLevel(r){return this.#r=Math.min(6,Math.max(0,Math.floor(r))),this}}class rn{#r;#e;#t=new Map;#n=[];constructor(r,e=[]){this.#r=[...r],this.#e=[...e],this.#s()}get args(){return[...this.#r]}get positionals(){return[...this.#n]}has(r){return this.#t.has(this.#i(r))}getArgs(r){return[...this.#t.get(this.#i(r))?.values??[]]}get(r){let e=this.#t.get(this.#i(r))?.values;if(!e)return;if(e.length===0)return!0;return e[0]}toObject(){let r={};for(let[e,t]of this.#t.entries())r[e]=t.values.length>0?[...t.values]:!0;return r}usage(r="command"){let e=[`Usage: ${r} [options]`];if(this.#n.length>0)e[0]+=" [values]";if(this.#e.length===0)return e.join(`
10
+ `);e.push("","Options:");for(let t of this.#e){let n=`--${t.name}`,i=t.alias?`-${t.alias}`:void 0,s=t.valueName??"value",u=t.takesValue?t.multiple?` <${s}...>`:` <${s}>`:"",a=i?`${i}, ${n}`:n,l=t.description?` ${t.description}`:"";e.push(` ${a}${u}${l}`)}return e.join(`
11
+ `)}#s(){for(let r=0;r<this.#r.length;r++){let e=this.#r[r];if(!e.startsWith("-")||e==="-"){this.#n.push(e);continue}if(e.startsWith("--")&&e.includes("=")){let i=e.indexOf("="),s=this.#i(e.slice(0,i)),u=e.slice(i+1);this.#o(s,u.length>0?[u]:[""],!0);continue}let t=this.#i(e),n=[];while(r+1<this.#r.length){let i=this.#r[r+1];if(i.startsWith("-")&&i!=="-")break;n.push(i),r++}this.#o(t,n,!1)}}#o(r,e,t){let n=this.#t.get(r);if(!n){this.#t.set(r,{values:[...e],sawEqualsStyle:t});return}n.values.push(...e),n.sawEqualsStyle=n.sawEqualsStyle||t}#i(r){return r.replace(/^-+/,"").trim()}}var br=async(r)=>{try{return await Ir.access(r,Ir.constants.R_OK),!0}catch{return!1}},nr=async(r,e)=>{let t=!hr.isAbsolute(r)&&e?["",...e]:[""];for(let n of t){let i=hr.join(n,r);if(await br(i))return hr.resolve(i)}throw Error(`File not found: "${r}"`)},nn=(r,e)=>e?.some((t)=>new RegExp(t).test(r))===!0,Kr=async(r,e)=>{let t=await nr(r,e?.dirs),n=await en.readFile(t,"utf-8"),i=tn.dirname(t),s={text:{fn:(a)=>a,matching:["\\.txt$","\\.text$"]},json:{fn:JSON.parse,matching:["\\.json$"]},...e?.parsers},u=e?.format?s[e.format]:Object.values(s).find((a)=>nn(r,a.matching));if(!u)throw Error(`Unsupported format for file "${r}" and no matching parser found`);return{content:await u.fn(n),fullPath:t,folderPath:i}},sn=(r,e)=>e?.some((t)=>new RegExp(t).test(r))===!0,an=async(r,e,t)=>{let n={text:{fn:(s)=>s,matching:["\\.txt$","\\.text$"]},json:{fn:JSON.stringify,matching:["\\.json$"]},...t?.encoders},i=t?.format?n[t.format]:Object.values(n).find((s)=>sn(r,s.matching));if(!i)throw Error(`Unsupported format for file "${r}" and no matching encoder found`);await on.writeFile(r,await i.fn(e))},Wr=async(r,e)=>{if(typeof r==="string"&&!r.includes("*"))return await e.map(r,0,[]);let t=await Array.fromAsync(un.glob(r,{cwd:e.cwd})),n=e.filter?t.filter(e.filter):t;return await Promise.all(n.map(e.map))},Nr=async(r,e)=>{if(e?.targetDirectory&&e?.removeFirst)try{await qr.rm(e?.targetDirectory,{recursive:!0,force:!0})}catch(t){throw Error(`Failed to clean the output directory: ${t.message}`,{cause:t})}for(let t of r)await fn(t,e)},fn=async(r,e)=>{let t=Br.join(e?.targetDirectory??".",r.name),n=Br.dirname(t);if(e?.classes){if(r.class!==void 0&&!e.classes.includes(r.class))return;if(e.classRequired&&r.class===void 0)throw Error(`Output "${r.name}" is missing class field`)}if(e?.writing?.(r)===!1)return;try{await qr.mkdir(n,{recursive:!0})}catch(i){throw Error(`Failed to create target directory "${n}" for output "${t}": ${i.message}`,{cause:i})}try{await an(t,r.value,{format:r.type??"text"})}catch(i){throw Error(`Failed to write output "${t}": ${i.message}`,{cause:i})}},Yr=(r)=>r?_r.isAbsolute(r)?r:_r.join(process.cwd(),r):process.cwd(),ln=async(r,e)=>{let t=[];for(let n of r)try{let i=!dr.isAbsolute(n)?dr.join(Yr(e?.cwd),n):n;if(e?.filter?.(i)===!1)continue;let s=await import(i);if(e?.resolveDefault==="only"&&!s.default)throw Error(`Module ${n} does not have a default export`);let u=e?.resolveDefault?s.default??s:s,a=e?.map?await e.map(u,n):u;if(a!==void 0)t.push(a)}catch(i){if(e?.fail?.(n,i)===!1)continue;throw Error(`Failed to import module ${n}: ${i.message??i}`,{cause:i})}return t},_n=async(r,e)=>{let t=[],n=Yr(e?.cwd);for(let i of r){let s=(await Array.fromAsync(cn.glob(i,{cwd:n}))).map((u)=>dr.join(n,u));t.push(...await ln(s,e))}return t};class G{o;context;constructor(r){this.o=r}}var c=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.sources({[i]:(s)=>n.apply({...this,context:s},s.args)})})},Wn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.sections({[i]:(s)=>{return n.call({...this,context:s},s.section)}})})},qn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.keys({[i]:(s)=>n.call({...this,context:s},s.value)})})},Nn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.variables({[i]:n})})},Yn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.functions({[i]:n})})},zn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.encoders({[i]:{fn:n}})})},Hn=(r)=>(e,t)=>{t.addInitializer(function(){let n=this[t.name],i=r?.name??t.name;this.o.decoders({[i]:{fn:n}})})};import{createHash as W}from"crypto";import I from"path";var zr=(r)=>({output:(e)=>{delete e.parent[e.key];for(let t of Array.isArray(e.value)?e.value:[e.value])if(typeof t==="string")r.output({name:t,value:e.parent});else r.output({...t,value:t.value??e.parent});return g.SkipSiblings()}});import mn from"path";var Hr=(r)=>({load:async(e)=>{let t=e.options.globalContext;for(let{file:n}of Array.isArray(e.value)?e.value:[e.value]){if(!n)throw Error("File reference required");await r.load(n,t.file&&mn.dirname(t.file))}return g.DeleteItem()}});class wr{cache=new Map;maxSize;constructor(r=100){this.maxSize=r}get(r){return this.cache.get(r)}set(r,e){this.evictIfNeeded(),this.cache.set(r,e)}has(r){return this.cache.has(r)}clear(){this.cache.clear()}setMaxSize(r){this.maxSize=r}size(){return this.cache.size}evictIfNeeded(){if(this.cache.size>=this.maxSize){let r=null,e=1/0;for(let[t,n]of this.cache.entries())if(n.timestamp<e)e=n.timestamp,r=t;if(r)this.cache.delete(r)}}}var ir=(r)=>{let e=defined(r.value,"Model value cannot be null or undefined");if(typeof e==="string")return r.parent;let t=e.model;if(!t)return r.parent;if(typeof t==="string")return Object.select(r.root,t);return t};var or=(r)=>{let e=defined(r.value,"Source value cannot be null or undefined");if(typeof e==="string")return Object.select(r.root,e);if(Array.isArray(e))return e;let t=e;if(typeof t.from==="string")return Object.select(r.root,t.from);return t.from};var Gr=(r,e)=>{if(typeof r.value==="string"){if(r.quoted)return r.value;if(r.value.startsWith("[")&&r.value.endsWith("]")){let t=r.value.slice(1,-1);if(t.trim()==="")return[];return t.split(";").map((n)=>{let i=n.trim();if(!isNaN(+i))return+i;return i})}if(r.value.startsWith("{")&&r.value.endsWith("}")){if(r.value.slice(1,-1).trim()==="")return{}}if(r.value==="null")return null;if(r.value==="undefined")return;if(r.value.startsWith("@"))return r.value.slice(1);if(!isNaN(+r.value))return+r.value}return e(r.value)},sr=(r,e,t,n,i,s)=>{let u=n?.(r)??r,a=i(u);if(a[0])return a[1];if(!e){let l=Object.select(t,r),y=i(l);if(y[0])return y[1]}throw Error(s)},ar=(r,e,t,n,i)=>{let s=typeof r.types==="function"?r.types(n,e.value,i):r.types?.[n];if(!s||s==="ref")return Gr(e,(a)=>Object.select(t,a));let u=Gr(e,()=>e.value);if(Array.isArray(s)){if(!s.includes(u))throw Error(`Argument ${n.toString()} must be one of [${s.join(", ")}]: ${u}`);return u}if(typeof s==="string"){if(s.endsWith("?")){let a=s.slice(0,-1);if(e.value==="null")return g.ReplaceItem(null);if(e.value==="undefined")return g.ReplaceItem(void 0);if(e.value==="")return"";s=a}switch(s){case"any":return u;case"array":return sr(u,e.quoted,t,null,(a)=>[Array.isArray(a),a],`Argument ${n.toString()} must be an array: ${u}`);case"object":return sr(u,e.quoted,t,null,(a)=>[typeof a==="object"&&a!==null,a],`Argument ${n.toString()} must be an object: ${u}`);case"number":return sr(u,e.quoted,t,(a)=>Number(a),(a)=>[!isNaN(a),a],`Argument ${n.toString()} must be a number: ${u}`);case"boolean":return sr(u,e.quoted,t,null,(a)=>{if([!0,"true","1",1,"yes","on"].includes(a))return[!0,!0];if([!1,"false","0",0,"no","off"].includes(a))return[!0,!1];if([null,"null","undefined",void 0,""].includes(a))return[!0,!1];if(Array.isArray(a))return[!0,a.length>0];return[!1,!1]},`Argument ${n.toString()} must be a boolean: ${u}`);case"string":return u.toString();default:throw Error(`Unknown type for argument ${n.toString()}: ${s}`)}}return s(u,t,n,e.quoted)};var ur=(r,e)=>{let t=r?.[e];if(t===void 0)throw Error(`Unhandled field processor type: ${e}`);return typeof t==="function"?{options:{},fn:t}:{options:t,fn:t.fn}},Jr=(r)=>!r.quoted&&r.value.startsWith("."),pn=(r)=>{let e={};for(let t of r){if(!Jr(t))continue;let n=t.value.indexOf("="),i=n>-1?t.value.slice(1,n):t.value.slice(1),s=n>-1?t.value.slice(n+1):"";if(s.length>=2){let u=s[0],a=s[s.length-1];if(u==='"'&&a==='"'||u==="'"&&a==="'")s=s.slice(1,-1)}if(!e[i])e[i]=[];e[i].push(s)}return e},Zr=(r,e,t)=>{let n=(r??"").splitWithQuotes(),i=pn(n),s=n.filter((a)=>!Jr(a)),u=e.options.processArgs===!1?[]:s.map((a,l)=>ar(e.options,a,t,l,s));return{rawArgs:s,parsedArgs:u,tags:i}};var gn=(r)=>{return r!==null&&typeof r==="object"&&"action"in r},Qr=(r,e)=>e.keys!==void 0&&r.key.startsWith(".")&&e.keys[r.key.substring(1)]!==void 0,xr=async(r,e,t,n)=>{let{key:i,parent:s}=r,u=ur(n.keys,i.substring(1));if(u.options.processArgs!==!1&&(typeof u.options.types==="function"||u.options.types?.[0]!==void 0))r.value=ar(u.options,{value:r.value,quoted:!1},t,0,[]);if(typeof r.value!=="string")await $(r.value,{...n,root:{...t,parent:r.parent,parents:r.parents},filters:[...n.filters??[],...u.options.filters??[]]});let a=await u.fn({path:e,root:t,parent:s,key:i,options:n,value:r.value,args:[],rawArgs:[],tags:{}});return gn(a)?a:g.ReplaceParent(a)};var Xr=async(r,e,t,n)=>{if(!e?.onSection&&!e?.onSectionConfig&&!e?.sections)return[r,!1];let i=/<@\s*section(?:\s*:\s*([\w-]+))?\s*@>([\s\S]*?)<@\s*\/\s*section\s*@>/g,s,u=r,a=0,l=!1,y={content:u,root:n,path:t,options:e,section:{}};while((s=i.exec(r))!==null){l=!0;let[d,p,O]=s,b=s.index,P=b+d.length,w=r[P]===`
12
+ `;if(w)P++;let j=b+a,D=P+a,A={},E=O,F=/(^|\r?\n)[ \t]*---[ \t]*(\r?\n|$)/m.exec(O);if(F){let q=O.slice(0,F.index),mr=F.index+F[0].length;E=O.slice(mr);let rr=q.stripIndent().trim();if(rr.length>0)try{A=e?.configParser?.(rr)??{}}catch(er){throw Error(`Failed to parse YAML config for section: ${er.message}`,{cause:er})}}else if(/^\r?\n/.test(E))E=E.replace(/^\r?\n/,"");E=E.stripIndent().replace(/(?:\r?\n[ \t]*)+$/,"").replace(/[ \t]+$/,"");let M={config:p?{...A,type:p}:A,content:E};if(y.content=u,y.section=M,Object.keys(M.config).length>0){if(await e.onSectionConfig?.(y)!==!1)await $(M.config,{...e,root:n})}let U=y.section.config.type?e.sections?.[y.section.config.type]:void 0,B;if(U)B=await U(y);else if(e.onSection)B=await e.onSection(y);if(M.trim)M.content=M.content.trim();if(M.indent)M.content=M.content.split(`
13
+ `).map((q)=>" ".repeat(M.indent)+q).join(`
14
+ `);let k="";if(B===!0||M.show)k=M.content;else if(typeof B==="string")k=B;if(w&&k!==""&&!k.endsWith(`
15
+ `))k+=`
16
+ `;let T=u.lastIndexOf(`
17
+ `,j-1),V=T===-1?0:T+1,v=u.slice(V,j).trim().length===0?V:j;u=u.slice(0,v)+k+u.slice(D),a+=k.length-(D-v),y.content=u}return[u,l]};var Or=(r)=>{let e=[],t=0;while(t<r.length)if(r[t]==="$"&&r[t+1]==="("&&(t===0||r[t-1]!=="\\")){let n=t;t+=2;let i=1;for(;t<r.length;t++)if(r[t]==="(")i++;else if(r[t]===")"){if(i--,i===0){e.push([n,t]);break}}if(i!==0)throw Error(`Unmatched opening $( at position ${n.toString()}`);t++}else t++;return e};var Ur=(r)=>({value:r}),yn=(r)=>{return r!==null&&typeof r==="object"},Tr=async(r,e,t)=>{for(let n=e.length-1;n>=0;n--){let[i,s]=e[n],u=r.slice(i+2,s),a=await Tr(u,Or(u),t);if(typeof a==="object")return a;let l=await t(a,r);if(yn(l))return l.value;r=r.slice(0,i)+l+r.slice(s+1)}return r},Vr=async(r,e)=>Tr(r,Or(r),e);var hn=(r)=>{return r!==null&&typeof r==="object"&&"action"in r},dn=/([\w\d.-_/]+):(.+)/,bn=async(r,e,t,n)=>{let i=await(async()=>{let s=dn.exec(r);if(!s)return await Object.select(e,r);let[u,a,l]=s,y=ur(n.sources,a),d=Zr(l,y,e);return await y.fn({args:d.parsedArgs,rawArgs:d.rawArgs,tags:d.tags,key:a,options:n,root:e,path:t,value:null})})();if(i===null||i===void 0)return"";if(typeof i==="object")return Ur(i);return i},Ar=async(r,e,t,n)=>{let i=await Vr(e,(s)=>bn(s,t,r,n));if(hn(i))return i;if(i===e)return g.Explore();if(typeof i==="string"){let s=await Ar(r,i,t,n);if(s.action!==L.Explore)return s}return g.ReplaceItem(i)};var $=async(r,e)=>{return e??={},await Object.navigate(r,async(t)=>{let n=[...t.path,t.key].join(".");if(e?.filters?.length&&e.filters.some((a)=>a.test(n)))return g.NoExplore();let i=t.path.length===0,s=t.parents.length>0?t.parents.toReversed():[];if(i){if(s.length>0)throw Error("Root object should not have a parent");s=e?.root?.parents?[e.root.parent,...e.root.parents.toReversed()]:[]}let u={...r,...e.root,this:t.parent,parent:s.length>0?s[0]:null,parents:s};try{if(t.key.startsWith("$"))return g.NoExplore();let a=g.Explore();if(typeof t.value==="string"){let l=t.value,y=!1;while(!0){let[d,p]=await Xr(l,e,n,u);if(y=y||p,a=await Ar(n,d,u,e),a.action===L.ReplaceItem&&typeof a.by==="string"){l=a.by;continue}if(a.action===L.Explore&&p&&d!==l)a=g.ReplaceItem(d);break}if(a.action===L.Explore&&l!==t.value)a=g.ReplaceItem(l);switch(a.action){case L.Explore:break;case L.ReplaceItem:t.value=a.by;break;default:return a}}if(Qr(t,e))a=await xr(t,n,u,e);return a}catch(a){throw Error(`${a.message}
18
+ (${n})`,{cause:a})}}),r};var vr=(r,e)=>e?{fn:(t)=>r(...t.args),types:e}:(t)=>r(...t.args),Ci=(r,e)=>Object.fromEntries(r.map((t)=>[t.name,vr(t,e?.types?.[t.name])])),J=(r,e)=>Object.fromEntries((e?.keys??Object.keys(r)).map((t)=>[t,vr(r[t],e?.types?.[t])]));var fr=async(r,e)=>{let t=r.value;if(t.selector===void 0)return e;if(typeof t.selector!=="string"){let n=JSON.parse(JSON.stringify(t.selector));return await $(n,{...r.options,root:{...r.root,result:e}}),n}return await Object.select({...r.root,result:e},t.selector)};import _ from"path";class K{constructor(){}static normalize(r){return _.normalize(_.resolve(r))}static resolveInContext(r,e){let t=e??process.cwd(),n=_.isAbsolute(r)?r:_.join(t,r);return this.normalize(n)}static isDirectoryPattern(r){return r.endsWith("/")}static isGlobPattern(r){return r.includes("*")}static toAbsolute(r,e){if(_.isAbsolute(r))return r;return _.join(e??process.cwd(),r)}}var R={and:(...r)=>r.every((e)=>!!e),or:(...r)=>r.some((e)=>!!e),xor:(...r)=>r.filter((e)=>!!e).length===1,true:(...r)=>r.every((e)=>!!e),false:(...r)=>r.every((e)=>!e),eq:(...r)=>r.every((e)=>e===r[0]),ne:(...r)=>r.some((e)=>e!==r[0]),lt:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]<e),le:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]<=e),gt:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]>e),ge:(...r)=>typeof r[0]==="number"&&r.slice(1).every((e)=>typeof e==="number"&&r[0]>=e),in:(r,e)=>{if(Array.isArray(e))return e.includes(r);if(typeof r==="string")return r.includes(e);if(Array.isArray(r))return r.includes(e);return!1},notin:(r,e)=>!R.in(r,e),contains:(r,e)=>r.includes(e),notcontains:(r,e)=>!r.includes(e),containsi:(r,e)=>r.toLowerCase().includes(e.toLowerCase()),notcontainsi:(r,e)=>!r.toLowerCase().includes(e.toLowerCase()),null:(...r)=>r.every((e)=>e===null||e===void 0),notnull:(...r)=>r.every((e)=>e!==null&&e!==void 0),empty:(...r)=>r.every((e)=>e===""),notempty:(...r)=>r.every((e)=>e!==""),nullorempty:(...r)=>r.every((e)=>e===null||e===void 0||e===""),notnullorempty:(...r)=>r.every((e)=>e!==null&&e!==void 0&&e!=="")},cr={and:()=>"boolean",or:()=>"boolean",xor:()=>"boolean",true:()=>"boolean",false:()=>"boolean",lt:()=>"number",le:()=>"number",gt:()=>"number",ge:()=>"number"};var re=()=>({each:{filters:[/select|model/],fn:async(r)=>{let e=r.value;delete r.parent[r.key];let t=await or(r),n=await ir(r);if(!Array.isArray(t))throw Error('Key "each" requires a source list');if(n===void 0)throw Error('Key "each" must define a model');if(e.extend?.model)n=[e.model,...Array.isArray(e.extend.model)?e.extend.model:[e.extend.model]].mergeAll();let i=[];for(let s=0;s<t.length;s++){let u=Object.deepClone(n);if(await $(u,{...r.options,root:{...r.root,index:s,item:t[s],instance:u}}),e.extend?.result){let a=e.extend.result;u=[u,...Array.isArray(a)?a:[a]].mergeAll()}i.push(await fr(r,u))}return i}}});var ee=()=>({map:{filters:[/select|model/],fn:async(r)=>{delete r.parent[r.key];let e=await or(r),t=await ir(r);if(!Array.isArray(e))throw Error('Key "map" requires a source list');if(t===void 0)throw Error('Key "map" must define a model');let n=[];return await e.forEachAsync(async(i,s)=>{let u=Object.deepClone(t);await $(u,{...r.options,root:{...r.root,index:s,item:i,instance:u}}),n.push(await fr(r,u))}),n}}});var te=()=>({concat:async(r)=>{let e=[];for(let t of Array.isArray(r.value)?r.value:[r.value])e.push(...await Object.select(r.root,t));return e.filter((t)=>t!==void 0)}});var ne=()=>({extends:async(r)=>{let e=async(t,n)=>{for(let i of Array.isArray(n)?n:[n]){let s=await Object.select(r.root,i),u=Object.deepClone(s);if(u[r.key])await e(u,u[r.key]);await $(u,{...r.options}),Object.merge(u,t),delete t[r.key]}};return await e(r.parent,r.value),g.Explore()},group:(r)=>{let e=r.root.parent,t=r.value,{items:n,...i}=t;return t.items.forEach((s)=>e.push({...i,...s})),g.DeleteParent()}});var ie=(r)=>({skip:{types:{0:"boolean"},fn:(e)=>e.value?g.DeleteParent():g.DeleteItem()},metadata:({path:e,value:t})=>{return r.metadata(e,t),g.DeleteItem()},if:{types:{0:"boolean"},fn:async(e)=>{let t=e.parent[".then"],n=e.parent[".else"];if(t!==void 0)delete e.parent[".then"];if(n!==void 0)delete e.parent[".else"];let i=e.value?t:n;if(i===void 0)return g.DeleteItem();if(typeof i==="string")return(await $({value:i},{...e.options,root:{...e.root}})).value;return g.ReplaceParent(i,!0)}},switch:(e)=>{let t=e.value;if(!t.cases)throw Error("Missing cases for switch");if(t.cases[t.from]!==void 0)return g.ReplaceParent(t.cases[t.from],!0);if(t.default!==void 0)return g.ReplaceParent(t.default,!0);return g.DeleteParent()}});var oe=()=>({from:async({root:r,parent:e,value:t})=>{let n=await Object.select(r,t);if(n===null||n===void 0)throw Error(`Unable to resolve reference: ${t}`);if(e.content){if(Array.isArray(e.content)&&Array.isArray(n))return[...n,...e.content];return Object.merge(n,e.content),e.content}return n}});import se from"node:vm";var ae=(r)=>({modules:async(e)=>{for(let[t,n]of Object.entries(e.value)){let i=se.createContext({console,objector:r,document:e.root}),s=new se.SourceTextModule(n,{identifier:t,context:i});await s.link((u)=>{throw Error(`Module ${u} is not allowed`)}),await s.evaluate(),r.sources(Object.fromEntries(Object.entries(s.namespace).map(([u,a])=>[`${t}.${u}`,(l)=>a(l,...l.args)])))}return g.DeleteItem()}});var ue=()=>({try:{fn:(r)=>{let e=r.parent[".catch"];if(e!==void 0)delete r.parent[".catch"];try{return r.value}catch(t){if(e!==void 0)return e;return g.DeleteItem()}}}});var fe=()=>({let:{fn:(r)=>{let e=r.value;return Object.assign(r.root,e),g.DeleteItem()}}});var ce=()=>({tap:{fn:(r)=>{return console.log(`[tap] ${r.path}:`,r.value),r.value}}});var wn=(r,e)=>{let t=e.section.config.using,n=r.getFunctions();if(!t)return n;let i={};return t.forEach((s)=>{if(s in n){i[s]=n[s];return}if(s in e.root){i[s]=e.root[s];return}throw Error(`Function or variable "${s}" not found for script section`)}),i},jr=(r,e,t,n,i=[])=>{let s=wn(r,t),u=["section","context","config","system",...Object.keys(s),...i],a=[e,t.root,t.section.config,r,...Object.values(s)];return[new AsyncFunction(...u,n).bind(t),a]},On=(r,e)=>{let t={write:(...n)=>{return e.push(...n),t},writeLine:(...n)=>{return e.push(...n.map((i)=>i+`
17
19
  `)),t},clear:()=>{return e.splice(0,e.length),t},prepend:(...n)=>{return e.unshift(...n),t},prependLine:(...n)=>{return e.unshift(...n.map((i)=>i+`
18
- `)),t},setOptions:(n)=>{return Object.assign(r.section,n),t},use:(n)=>{return n(t),t},getLines:()=>e};return t},bn=async(r,e,t)=>{let n=t.section.config.condition;if(n!==void 0){let[i,s]=Sr(r,e,t,`return (${n})`);if(!await i(...s))return!1}return!0},le=(r)=>async(e)=>{let t=[],n=dn(e,t);if(!await bn(r,n,e))return!1;let[i,s]=Sr(r,n,e,e.section.content,["item"]),f=e.section.config.each;if(f){let[a,p]=Sr(r,n,e,`return (${f})`),y=Array.isArray(f)?f:await a(...p);if(!Array.isArray(y))throw Error('The "each" property of a script section must return an array');for(let d of y){let m=await i(...s,d);if(typeof m<"u")t.push(m)}}else{let a=await i(...s);if(typeof a<"u")return a}if(t.length===0)return!1;return t.join("")};var pe=(r)=>({script:le(r)});import me from"fs/promises";import G from"path";var ge=(r)=>({include:async(e)=>{let{file:t}=e.options.globalContext;return await Jr(e.args[0],{cwd:G.dirname(t),filter:(n)=>G.basename(t)!==n,map:async(n)=>r.load(n,G.dirname(t),e.root)})},exists:async({args:[e]})=>await br(e),file:async(e)=>await me.readFile(await tr(e.args[0],r.getIncludeDirectories())).then((t)=>t.toString()),scan:async(e)=>{let t=[],i=(()=>{let a=e.args[2]??["**/node_modules/**"],p=typeof a==="string"?a.split(",").map((y)=>y.trim()):a;if(!Array.isArray(p))throw Error("Scan exclusion must be a list");return p})(),{file:s}=e.options.globalContext,f=e.args[1]?await tr(e.args[1],r.getIncludeDirectories()):G.dirname(s);for await(let a of me.glob(e.args[0],{cwd:f,exclude:(p)=>i.some((y)=>G.matchesGlob(p,y))}))t.push(a);return t}});var ye=(r)=>({substring:{types:{0:"ref",1:"number",2:"number"},fn:(e)=>e.args[0].substring(e.args[1],e.args[2])},repeat:{types:{0:"ref",1:"number"},fn:({args:[e,t]})=>e.repeat(t)},pad:{types:{0:"ref",1:"number",2:"string"},fn:({args:[e,t],tags:n})=>{let i=n.join?.[0]??`
19
- `,s=n.padChar?.[0]??" ";return e.padBlock(t??2,i,s)}},formatAs:{fn:({args:[e,t],tags:n})=>{let i=r.getEncoder(t);if(!i)throw Error("Unsupported format: "+String(t));let s=[];if(i.options?.includeTags)s=[n];return i.fn(e,...s)}}});var cr=(r,e=0,t)=>{let n=" ".repeat(e),i=" ".repeat(e+1);if(r===null||r===void 0)return"null";else if(typeof r==="boolean")return String(r);else if(typeof r==="number")return String(r);else if(typeof r==="string")return`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`;else if(Array.isArray(r)){if(r.length===0)return"[]";return`[
20
- ${r.map((f)=>`${i}${cr(f,e+1)},`).join(`
20
+ `)),t},setOptions:(n)=>{return Object.assign(r.section,n),t},use:(n)=>{return n(t),t},getLines:()=>e};return t},An=async(r,e,t)=>{let n=t.section.config.condition;if(n!==void 0){let[i,s]=jr(r,e,t,`return (${n})`);if(!await i(...s))return!1}return!0},le=(r)=>async(e)=>{let t=[],n=On(e,t);if(!await An(r,n,e))return!1;let[i,s]=jr(r,n,e,e.section.content,["item"]),u=e.section.config.each;if(u){let[a,l]=jr(r,n,e,`return (${u})`),y=Array.isArray(u)?u:await a(...l);if(!Array.isArray(y))throw Error('The "each" property of a script section must return an array');for(let d of y){let p=await i(...s,d);if(typeof p<"u")t.push(p)}}else{let a=await i(...s);if(typeof a<"u")return a}if(t.length===0)return!1;return t.join("")};var me=(r)=>({script:le(r)});import pe from"fs/promises";import Z from"path";var ge=(r)=>({include:async(e)=>{let{file:t}=e.options.globalContext;return await Wr(e.args[0],{cwd:Z.dirname(t),filter:(n)=>Z.basename(t)!==n,map:async(n)=>r.load(n,Z.dirname(t),e.root)})},exists:async({args:[e]})=>await br(e),file:async(e)=>await pe.readFile(await nr(e.args[0],r.getIncludeDirectories())).then((t)=>t.toString()),scan:async(e)=>{let t=[],i=(()=>{let a=e.args[2]??["**/node_modules/**"],l=typeof a==="string"?a.split(",").map((y)=>y.trim()):a;if(!Array.isArray(l))throw Error("Scan exclusion must be a list");return l})(),{file:s}=e.options.globalContext,u=e.args[1]?await nr(e.args[1],r.getIncludeDirectories()):Z.dirname(s);for await(let a of pe.glob(e.args[0],{cwd:u,exclude:(l)=>i.some((y)=>Z.matchesGlob(l,y))}))t.push(a);return t}});var ye=(r)=>({substring:{types:{0:"ref",1:"number",2:"number"},fn:(e)=>e.args[0].substring(e.args[1],e.args[2])},repeat:{types:{0:"ref",1:"number"},fn:({args:[e,t]})=>e.repeat(t)},pad:{types:{0:"ref",1:"number",2:"string"},fn:({args:[e,t],tags:n})=>{let i=n.join?.[0]??`
21
+ `,s=n.padChar?.[0]??" ";return e.padBlock(t??2,i,s)}},formatAs:{fn:({args:[e,t],tags:n})=>{let i=r.getEncoder(t);if(!i)throw Error("Unsupported format: "+String(t));let s=[];if(i.options?.includeTags)s=[n];return i.fn(e,...s)}}});var lr=(r,e=0,t)=>{let n=" ".repeat(e),i=" ".repeat(e+1);if(r===null||r===void 0)return"null";else if(typeof r==="boolean")return String(r);else if(typeof r==="number")return String(r);else if(typeof r==="string")return`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`;else if(Array.isArray(r)){if(r.length===0)return"[]";return`[
22
+ ${r.map((u)=>`${i}${lr(u,e+1)},`).join(`
21
23
  `)}
22
- ${n}]`}else if(typeof r==="object"){let s=Object.entries(r).sort((a,p)=>t?.sortKeys?a[0].localeCompare(p[0]):0);if(s.length===0)return"{}";return`{
23
- ${s.map(([a,p])=>`${i}${a} = ${cr(p,e+1,t)}`).join(`
24
+ ${n}]`}else if(typeof r==="object"){let s=Object.entries(r).sort((a,l)=>t?.sortKeys?a[0].localeCompare(l[0]):0);if(s.length===0)return"{}";return`{
25
+ ${s.map(([a,l])=>`${i}${a} = ${lr(l,e+1,t)}`).join(`
24
26
  `)}
25
- ${n}}`}else return String(r)},Z=(r)=>{if(!r)return r;return r.replaceAll("\\n",`
26
- `).replaceAll("\\$","$").replaceAll("\\t","\t")};var he=()=>({...H({merge:(...r)=>r.flatMap((e)=>e)}),join:({args:[r],root:e,tags:t})=>{let n=defined(r,"Join source cannot be null or undefined"),i=t.key?.[0],s=t.separator?.[0]??t.sep?.[0],f=t.finalize?.length>0,a=Z(s);if(typeof n==="string"){if(f&&n.length&&a)return n+a;return n}if(!Array.isArray(n))throw Error("Object is not a list");let p=((i?.length)?n.map((O)=>Object.select({...e,...O},i)):n).join(a),y=t.pad?.[0]??"0",d=t.padChar?.[0]??" ",m=f&&p.length&&a?p+a:p;return y?m.padBlock(parseInt(y),`
27
- `,d):m},range:({args:[r,e,t]})=>{let n=parseInt(r),i=parseInt(e),s=parseInt(t)||1;if(isNaN(n))throw Error("Invalid range: start value '"+String(r)+"' is not a number");if(isNaN(i))throw Error("Invalid range: end value '"+String(e)+"' is not a number");if(s===0)throw Error("Invalid range: step cannot be zero");if((i-n)/s<0)throw Error("Invalid range: step "+String(s)+" has wrong direction for range "+String(n)+" to "+String(i));return Array.from({length:Math.floor((i-n)/s)+1},(f,a)=>n+a*s)},filter:{types:(r,e,t)=>{switch(r){case 0:return"array";case 1:return Object.keys(R)}return ur[t[1].value]?.(r-2,e,t.slice(2))},fn:({args:[r,e,t],root:n,tags:i})=>{if(r===null||r===void 0)throw Error("Filter source cannot be null or undefined");if(!Array.isArray(r))throw Error("Filter source must be an array");let s=i.key?.[0],f=R[e];if(s){let p=Array(r.length);for(let d=0;d<r.length;d++)try{p[d]=Object.select({...n,...r[d]},s)}catch{p[d]=Symbol("invalid")}let y=[];for(let d=0;d<r.length;d++){let m=p[d];if(typeof m!=="symbol"&&t===void 0?f(m):f(m,t))y.push(r[d])}return y}let a=[];for(let p of r)if(t===void 0?f(p):f(p,t))a.push(p);return a}}});var de=()=>({each:{processArgs:!1,fn:async({rawArgs:[r,e,...t],root:n,options:i,tags:s})=>{let f=async(w)=>w.quoted?Z(w.value):await Object.select(n,w.value),a=await Object.select(n,r.value),p=await f(e),y=s.key?.[0],d=Array.isArray(a)?a:Object.toList(a,"name"),m=[],O=await t.mapAsync(async(w)=>await f(w)),b={...n,item:void 0,index:0,params:O,instance:void 0,parent:n.this,tags:s},P={...i,root:b};if(await d.forEachAsync(async(w,j)=>{let D=Object.deepClone(p),A={instance:D},F=typeof p==="string"?A:D;if(b.item=w,b.index=j,b.instance=D,s?.root?.[0])Object.assign(b,await Object.select(b,s.root[0]));if(await $(F,P),y!==void 0)m.push(await Object.select(A.instance,y));else m.push(A.instance)}),s.join?.length){if(m.length===0)return"";let w=Z(s.join[0]),j=s.pad?.[0]??"0",D=s.padChar?.[0]??" ",A=s.finalize?.length&&w?w:"",F=`${m.join(w)}${A}`;return j?F.padBlock(parseInt(j),`
28
- `,D):F}return m}}});var Q=async(r,e,t)=>r.rawArgs[e].quoted?r.rawArgs[e].value:await Object.select(r.root,r.rawArgs[e].value,{defaultValue:t}),be=()=>({switch:{processArgs:!1,fn:async(r)=>{let e=await Q(r,0,!1),t=await Q(r,1);if(t[e]===void 0){if(r.rawArgs.length>2)return Q(r,2);throw Error(`Unhandled switch case: ${e}`)}return t[e]}}});var we=()=>({if:{types:{0:"boolean"},fn:(r)=>r.args[0]?r.args[1]:r.args[2]},check:{types:{0:Object.keys(R)},fn:(r)=>R[r.args[0]](...r.args.slice(1))},...H(R,{types:ur})});var Oe=(r)=>({default:{processArgs:!1,fn:async(e)=>{for(let t=0;t<e.rawArgs.length;t++)if(e.rawArgs[t]?.value!==void 0){let i=await Q(e,t,null);if(i!==null)return i}if(e.tags.nullable?.length)return g.DeleteItem();if(e.tags.fail?.length)throw Error(`No valid value found for default (${e.rawArgs.map((t)=>t.value).join(", ")})`);return""}},section:{types:["string","boolean"],fn:(e)=>{let t=e.args[0];if(!(e.args[1]??!0))return null;let i=r.getSection(t);if(!i)throw Error(`Section not found: ${t}`);return i.content}}});var Ae=()=>({convert:({args:[r,e,t]})=>{switch(e){case"string":return String(r);case"number":{let n=Number(r);if(!isNaN(n))return g.ReplaceItem(n);break}case"boolean":if(r==="true"||r===!0||r===1||r==="1"||r==="yes"||r==="on")return g.ReplaceItem(!0);else if(r==="false"||r===!1||r===0||r==="0"||r==="no"||r==="off")return g.ReplaceItem(!1);break;default:throw Error(`Unsupported type for convert: ${e}`)}if(t!==void 0)return g.ReplaceItem(t);throw Error(`Failed to convert value to ${e}`)},isType:({args:[r,e]})=>{let n=(()=>{switch(e){case"string":return typeof r==="string";case"number":return typeof r==="number";case"boolean":return typeof r==="boolean";case"object":return r!==null&&typeof r==="object"&&!Array.isArray(r);case"array":return Array.isArray(r);case"null":return r===null;case"undefined":return r===void 0;case"function":return typeof r==="function";default:throw Error(`Unknown type for isType: ${e}`)}})();return g.ReplaceItem(n)},typeOf:({args:[r]})=>{if(r===null)return"null";else if(Array.isArray(r))return"array";else return typeof r}});var je=(r)=>{var e,t,n,i,s,f,a,p,y,d,m,O,b,P,w,j,D,A,F,E,M,T,B,C,x,V,Mr,v,J,lr,rr,pr,Se,Ee,Fe,Me,$e,Pe,De,ke,Ce,Le,Re,Ie,Be,Ue,_e,We,Je,Ke,Ne,Ye,ze,qe,He,Ge,Ze,Qe,Xe,Te,xe,Ve,ve,rt,et,tt,nt,it,ot,st,at,ft,ut,ct,lt,pt,mt,gt,yt,ht,dt,bt,wt,Ot,At,jt,St,Et,Ft,Mt,$t,Pt,Dt,kt,Ct,Lt,Rt,It,Bt,Ut,_t,Wt,Jt,Kt,i,s,f,a,p,y,d,m,O,b,P,w,j,D,A,F,E,M,T,B,C,x,V,Mr,v,J,lr,rr,pr,Se,Ee,Fe,Me,$e,Pe,De,ke,Ce,Le,Re,Ie,Be,Ue,_e,We,Je,Ke,Ne,Ye,ze,qe,He,Ge,Ze,Qe,Xe,Te,xe,Ve,ve,rt,et,tt,nt,it,ot,st,at,ft,ut,ct,lt,pt,mt,gt,yt,ht,dt,bt,wt,Ot,At,jt,St,Et,Ft,Mt,$t,Pt,Dt,kt,Ct,Lt,Rt,It,Bt,Ut,_t,Wt,Jt,Kt;return r.use((n=z,i=[c()],s=[c()],f=[c()],a=[c()],p=[c()],y=[c()],d=[c()],m=[c()],O=[c()],b=[c()],P=[c()],w=[c()],j=[c()],D=[c()],A=[c()],F=[c()],E=[c()],M=[c()],T=[c()],B=[c()],C=[c()],x=[c()],V=[c()],Mr=[c()],v=[c()],J=[c()],lr=[c()],rr=[c()],pr=[c()],Se=[c()],Ee=[c()],Fe=[c()],Me=[c()],$e=[c()],Pe=[c()],De=[c()],ke=[c()],Ce=[c()],Le=[c()],Re=[c()],Ie=[c()],Be=[c()],Ue=[c()],_e=[c()],We=[c()],Je=[c()],Ke=[c()],Ne=[c()],Ye=[c()],ze=[c()],qe=[c()],He=[c()],Ge=[c()],Ze=[c()],Qe=[c()],Xe=[c()],Te=[c()],xe=[c()],Ve=[c()],ve=[c()],rt=[c()],et=[c()],tt=[c()],nt=[c()],it=[c()],ot=[c()],st=[c()],at=[c()],ft=[c()],ut=[c()],ct=[c()],lt=[c()],pt=[c()],mt=[c()],gt=[c()],yt=[c()],ht=[c()],dt=[c()],bt=[c()],wt=[c()],Ot=[c()],At=[c()],jt=[c()],St=[c()],Et=[c()],Ft=[c()],Mt=[c()],$t=[c()],Pt=[c()],Dt=[c()],kt=[c()],Ct=[c()],Lt=[c()],Rt=[c()],It=[c()],Bt=[c()],Ut=[c()],_t=[c()],Wt=[c()],Jt=[c()],Kt=[c()],t=Lr(n),e=class extends n{constructor(){super(...arguments);Ir(t,5,this)}env(o){return process.env[o]}uuid(){return crypto.randomUUID()}pascal(o){return o.toPascal()}camel(o){return o.toCamel()}capital(o){return o.capitalize()}snake(o,l="lower"){return o.changeCase(l).toSnake()}kebab(o,l="lower"){return o.changeCase(l).toKebab()}len(o){return o.length}reverse(o){return o.split("").reverse().join("")}concat(...o){return o.join("")}trim(o){return o.trim()}ltrim(o){return o.trimStart()}rtrim(o){return o.trimEnd()}lower(o){return o.toLowerCase()}upper(o){return o.toUpperCase()}encode(o,l){return Buffer.from(o).toString(l??"base64")}decode(o,l){return Buffer.from(o,l??"base64").toString()}list(o,l="name"){return Object.toList(o,l)}object(o,l="name"){return o.toObject((h)=>h[l],(h)=>{let{[l]:S,...k}=h;return k})}pathJoin(...o){return I.join(...o)}resolve(...o){return I.resolve(...o)}dirname(o){return I.dirname(o)}basename(o,l){return I.basename(o,l)}normalize(o){return I.normalize(o)}extname(o){return I.extname(o)}relative(o,l){return I.relative(o,l)}isAbsolute(o){return I.isAbsolute(o)}segments(o){return o.split("/").filter(Boolean)}log(...o){console.log(...o)}md5(o){return W("md5").update(o).digest("hex")}sha1(o){return W("sha1").update(o).digest("hex")}sha256(o){return W("sha256").update(o).digest("hex")}sha512(o){return W("sha512").update(o).digest("hex")}hash(o,l="sha256"){return W(l).update(o).digest("hex")}hmac(o,l,h="sha256"){return W(h).update(o).digest("hex")}base64Encode(o){return Buffer.from(o).toString("base64")}base64Decode(o){return Buffer.from(o,"base64").toString("utf-8")}hexEncode(o){return Buffer.from(o).toString("hex")}hexDecode(o){return Buffer.from(o,"hex").toString("utf-8")}add(...o){return o.reduce((l,h)=>l+h,0)}subtract(o,l){return o-l}multiply(...o){return o.reduce((l,h)=>l*h,1)}divide(o,l){if(l===0)throw Error("Division by zero");return o/l}modulo(o,l){return o%l}power(o,l){return Math.pow(o,l)}sqrt(o){return Math.sqrt(o)}abs(o){return Math.abs(o)}floor(o){return Math.floor(o)}ceil(o){return Math.ceil(o)}round(o,l){let h=Math.pow(10,l??0);return Math.round(o*h)/h}min(...o){return Math.min(...o)}max(...o){return Math.max(...o)}clamp(o,l,h){return Math.max(l,Math.min(h,o))}random(o,l){let h=o??0,S=l??1;return Math.random()*(S-h)+h}timestamp(o){return new Date(o).getTime()}iso(o){return new Date(o).toISOString()}utc(o){return new Date(o).toUTCString()}formatDate(o,l){let h=new Date(o),S=h.getFullYear(),k=String(h.getMonth()+1).padStart(2,"0"),er=String(h.getDate()).padStart(2,"0"),K=String(h.getHours()).padStart(2,"0"),Nt=String(h.getMinutes()).padStart(2,"0"),Yt=String(h.getSeconds()).padStart(2,"0");return l.replace("YYYY",String(S)).replace("MM",k).replace("DD",er).replace("HH",K).replace("mm",Nt).replace("ss",Yt)}parseDate(o){return new Date(o).getTime()}year(o){return new Date(o).getFullYear()}month(o){return new Date(o).getMonth()+1}day(o){return new Date(o).getDate()}dayOfWeek(o){return new Date(o).getDay()}hours(o){return new Date(o).getHours()}minutes(o){return new Date(o).getMinutes()}seconds(o){return new Date(o).getSeconds()}regexTest(o,l,h){return new RegExp(o,h).test(l)}regexMatch(o,l,h){return new RegExp(o,h).exec(l)}regexMatchAll(o,l,h){return Array.from(l.matchAll(new RegExp(o,h)))}regexReplace(o,l,h,S){return h.replace(new RegExp(o,S),l)}regexReplaceAll(o,l,h,S){return h.replace(new RegExp(o,S??"g"),l)}regexSplit(o,l,h){return l.split(new RegExp(o,h))}regexExec(o,l,h){return new RegExp(o,h).exec(l)}regexSearch(o,l,h){return l.search(new RegExp(o,h))}unique(o,l){if(!Array.isArray(o))return o;let h=new Set;return o.filter((S)=>{let k=l?S[l]:S;if(h.has(k))return!1;return h.add(k),!0})}groupBy(o,l){if(!Array.isArray(o))return o;let h={};return o.forEach((S)=>{let k=String(S[l]);if(!h[k])h[k]=[];h[k].push(S)}),h}chunk(o,l=1){if(!Array.isArray(o))return[];let h=[];for(let S=0;S<o.length;S+=l)h.push(o.slice(S,S+l));return h}flatten(o,l=1){if(!Array.isArray(o))return[o];let h=[],S=(k,er)=>{for(let K of k)if(Array.isArray(K)&&er>0)S(K,er-1);else h.push(K)};return S(o,l),h}compact(o){if(!Array.isArray(o))return o;return o.filter((l)=>l!==null&&l!==void 0)}head(o,l){if(!Array.isArray(o))return o;return l?o.slice(0,l):o[0]}tail(o,l){if(!Array.isArray(o))return o;return l?o.slice(-l):o[o.length-1]}isEmail(o){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o)}isUrl(o){try{return new URL(o),!0}catch{return!1}}isJson(o){try{return JSON.parse(o),!0}catch{return!1}}isUuid(o){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o)}minLength(o,l){return o?.length>=l}maxLength(o,l){return o?.length<=l}lengthEquals(o,l){return o?.length===l}isNumber(o){return typeof o==="number"&&!isNaN(o)}isString(o){return typeof o==="string"}isBoolean(o){return typeof o==="boolean"}isArray(o){return Array.isArray(o)}isObject(o){return o!==null&&typeof o==="object"&&!Array.isArray(o)}isEmpty(o){if(o===null||o===void 0)return!0;if(typeof o==="string"||Array.isArray(o))return o.length===0;if(typeof o==="object")return Object.keys(o).length===0;return!1}isTruthy(o){return!!o}isFalsy(o){return!o}inRange(o,l,h){return o>=l&&o<=h}matchesPattern(o,l){return new RegExp(l).test(o)}includes(o,l){if(typeof o==="string")return o.includes(String(l));return Array.isArray(o)&&o.includes(l)}startsWith(o,l){return o.startsWith(l)}endsWith(o,l){return o.endsWith(l)}},u(t,1,"env",i,e),u(t,1,"uuid",s,e),u(t,1,"pascal",f,e),u(t,1,"camel",a,e),u(t,1,"capital",p,e),u(t,1,"snake",y,e),u(t,1,"kebab",d,e),u(t,1,"len",m,e),u(t,1,"reverse",O,e),u(t,1,"concat",b,e),u(t,1,"trim",P,e),u(t,1,"ltrim",w,e),u(t,1,"rtrim",j,e),u(t,1,"lower",D,e),u(t,1,"upper",A,e),u(t,1,"encode",F,e),u(t,1,"decode",E,e),u(t,1,"list",M,e),u(t,1,"object",T,e),u(t,1,"pathJoin",B,e),u(t,1,"resolve",C,e),u(t,1,"dirname",x,e),u(t,1,"basename",V,e),u(t,1,"normalize",Mr,e),u(t,1,"extname",v,e),u(t,1,"relative",J,e),u(t,1,"isAbsolute",lr,e),u(t,1,"segments",rr,e),u(t,1,"log",pr,e),u(t,1,"md5",Se,e),u(t,1,"sha1",Ee,e),u(t,1,"sha256",Fe,e),u(t,1,"sha512",Me,e),u(t,1,"hash",$e,e),u(t,1,"hmac",Pe,e),u(t,1,"base64Encode",De,e),u(t,1,"base64Decode",ke,e),u(t,1,"hexEncode",Ce,e),u(t,1,"hexDecode",Le,e),u(t,1,"add",Re,e),u(t,1,"subtract",Ie,e),u(t,1,"multiply",Be,e),u(t,1,"divide",Ue,e),u(t,1,"modulo",_e,e),u(t,1,"power",We,e),u(t,1,"sqrt",Je,e),u(t,1,"abs",Ke,e),u(t,1,"floor",Ne,e),u(t,1,"ceil",Ye,e),u(t,1,"round",ze,e),u(t,1,"min",qe,e),u(t,1,"max",He,e),u(t,1,"clamp",Ge,e),u(t,1,"random",Ze,e),u(t,1,"timestamp",Qe,e),u(t,1,"iso",Xe,e),u(t,1,"utc",Te,e),u(t,1,"formatDate",xe,e),u(t,1,"parseDate",Ve,e),u(t,1,"year",ve,e),u(t,1,"month",rt,e),u(t,1,"day",et,e),u(t,1,"dayOfWeek",tt,e),u(t,1,"hours",nt,e),u(t,1,"minutes",it,e),u(t,1,"seconds",ot,e),u(t,1,"regexTest",st,e),u(t,1,"regexMatch",at,e),u(t,1,"regexMatchAll",ft,e),u(t,1,"regexReplace",ut,e),u(t,1,"regexReplaceAll",ct,e),u(t,1,"regexSplit",lt,e),u(t,1,"regexExec",pt,e),u(t,1,"regexSearch",mt,e),u(t,1,"unique",gt,e),u(t,1,"groupBy",yt,e),u(t,1,"chunk",ht,e),u(t,1,"flatten",dt,e),u(t,1,"compact",bt,e),u(t,1,"head",wt,e),u(t,1,"tail",Ot,e),u(t,1,"isEmail",At,e),u(t,1,"isUrl",jt,e),u(t,1,"isJson",St,e),u(t,1,"isUuid",Et,e),u(t,1,"minLength",Ft,e),u(t,1,"maxLength",Mt,e),u(t,1,"lengthEquals",$t,e),u(t,1,"isNumber",Pt,e),u(t,1,"isString",Dt,e),u(t,1,"isBoolean",kt,e),u(t,1,"isArray",Ct,e),u(t,1,"isObject",Lt,e),u(t,1,"isEmpty",Rt,e),u(t,1,"isTruthy",It,e),u(t,1,"isFalsy",Bt,e),u(t,1,"inRange",Ut,e),u(t,1,"matchesPattern",_t,e),u(t,1,"includes",Wt,e),u(t,1,"startsWith",Jt,e),u(t,1,"endsWith",Kt,e),gr(t,e),e)).keys({...Yr(r),...zr(r),...re(),...ee(),...oe(),...te(),...ne(),...ie(r),...ae(r),...fe(),...ue(),...ce()}).sources({...ge(r),...ye(r),...Ae(),...he(),...de(),...be(),...we(),...Oe(r)}).sections(pe(r)).fieldOptions({configParser:Bun.YAML.parse,onSection:(o)=>{if(o.section.config.name)r.section(o.section)}}).decoders({yaml:{matching:["\\.yml$","\\.yaml$"],fn:Bun.YAML.parse}}).encoders({json:{fn:(o)=>JSON.stringify(o,null,2)},yaml:{fn:(o)=>Bun.YAML.stringify(o,null,2)},terraform:{options:{includeTags:!0},fn:(o,l)=>cr(o,0,{sortKeys:!!(l?.sort?.length??l?.sortKeys?.length)})}})};import wn from"fs/promises";import X from"path";class Er{includeDirectories=[];baseIncludeDirectories=[];includes=[];addDirectories(...r){this.includeDirectories.push(...r),this.baseIncludeDirectories.push(...r)}getDirectories(){return this.includeDirectories}reset(){this.includeDirectories=[...this.baseIncludeDirectories]}restore(r){this.includeDirectories=[...r]}snapshot(){return[...this.includeDirectories]}addFiles(...r){this.includes.push(...r)}getPendingAndClear(){let r=[...this.includes];return this.includes.length=0,r}async processPatterns(r,e,t){let n=[];for(let i of r)if(_.isGlobPattern(i)){let s=(await Array.fromAsync(wn.glob(i,{cwd:e}))).map((f)=>X.join(e,f));n.push(...s.filter((f)=>!t.included.includes(f)))}else if(_.isDirectoryPattern(i)){let s=X.isAbsolute(i)?i:X.join(e,i);if(!this.includeDirectories.includes(s))this.includeDirectories.push(s)}else n.push(i);return n.unique()}buildSearchDirs(r){let e=r?[r]:[];return e.push(...this.includeDirectories.map((t)=>X.isAbsolute(t)?t:X.join(r??process.cwd(),t))),e}}class Fr{includeManager;loadFn;constructor(r,e){this.includeManager=r;this.loadFn=e}async processIncludes(r,e,t){let n=[];if(r.content.includes)n.push(...r.content.includes),delete r.content.includes;n.push(...this.includeManager.getPendingAndClear());let i=await this.includeManager.processPatterns(n,r.folderPath,t);for(let s of i)Object.merge(await this.loadFn(s,r.folderPath,{parent:r.content,...e},!0,t),r.content)}}class On{includeManager=new Er;includeProcessor;cacheManager=new wr(100);outputs=[];vars={};funcs={};fields={sources:{},keys:{},sections:{}};objectMetadata={};currentContext=null;storedSections={};dataEncoders={};dataDecoders={};constructor(){this.includeProcessor=new Fr(this.includeManager,this.load.bind(this)),this.use(je)}use(r){if(r.prototype instanceof z)new r(this);else r(this);return this}includeDirectory(...r){return this.includeManager.addDirectories(...r),this}getIncludeDirectories(){return this.includeManager.getDirectories()}include(...r){return this.includeManager.addFiles(...r),this}keys(r){return Object.assign(this.fields.keys,{...this.fields.keys,...r}),this}sources(r){return Object.assign(this.fields.sources,{...this.fields.sources,...r}),this}sections(r){return Object.assign(this.fields.sections,{...this.fields.sections,...r}),this}variables(r){return Object.assign(this.vars,{...this.vars,...r}),this}functions(r){return Object.assign(this.funcs,{...this.funcs,...r}),this}getFunctions(){return this.funcs}getOutputs(){return this.outputs}output(r){return this.outputs.push(r),this}metadata(r,e){return this.objectMetadata[r]=e,this}getMetadata(r){return this.objectMetadata[r]}getAllMetadata(){return this.objectMetadata}setCacheMaxSize(r){return this.cacheManager.setMaxSize(r),this}clearCache(){return this.cacheManager.clear(),this}getCurrentContext(){return this.currentContext}fieldOptions(r){return Object.assign(this.fields,{...this.fields,...r}),this}section(r){return this.storedSections[r.config.name]=r,this}getSection(r){return this.storedSections[r]}encoders(r){return Object.assign(this.dataEncoders,{...this.dataEncoders,...r}),this}decoders(r){return Object.assign(this.dataDecoders,{...this.dataDecoders,...r}),this}getEncoder(r){return this.dataEncoders[r]}getDecoder(r){return this.dataDecoders[r]}filter(r){return this.fields.filters??=[],this.fields.filters.push(r),this}async loadObject(r,e,t){return $(r,{...this.fields,globalContext:{file:t?.fullPath??"@internal"},root:{...e,...this.fields.root,...this.vars,functions:this.funcs,context:this.currentContext,sections:this.storedSections,$document:{root:{content:r},fileName:t?.fileName??"@internal",folder:t?.folderPath??"@internal",fullPath:t?.fullPath??"@internal"}}})}async load(r,e,t,n,i){let s=this.includeManager.snapshot();try{this.includeManager.reset();let f=this.includeManager.buildSearchDirs(e);if(i)this.currentContext=i;this.currentContext??={included:[],document:null};let a=typeof r==="string"?await Wr(r,{dirs:f,parsers:this.dataDecoders,format:"yaml"}):{content:r,fullPath:"@internal",folderPath:"@internal"};if(typeof r==="string"){let y=_.normalize(a.fullPath);if(this.currentContext.included.push(y),!a.content)return null;let d=this.cacheManager.get(y),m;if(d)m=d.raw;else m=a.content,this.cacheManager.set(y,{raw:m,timestamp:Date.now()});let O=Object.deepClone(m);a.content=O}await this.includeProcessor.processIncludes(a,t,this.currentContext);let p;if(n!==!0)p=await this.loadObject(a.content,t,{fileName:a.fullPath,folderPath:a.folderPath,fullPath:a.fullPath});else p=a.content;return this.currentContext.document=p,p}catch(f){throw this.includeManager.restore(s),f}finally{this.includeManager.restore(s)}}async writeAll(r){await Nr(this.getOutputs(),r)}}export{Nr as writeOutputs,rn as writeOutput,Vt as writeFormat,_n as variable,Wn as sharedFunction,Bn as section,$ as processFields,H as makeFieldProcessorMap,Pi as makeFieldProcessorList,vr as makeFieldProcessor,c as macro,tr as locate,Wr as loadFormat,Un as key,tn as importList,Rn as importGlob,Jr as globMap,ar as getProcessor,Gr as getArgs,br as exists,Jn as encoder,Kn as decoder,R as conditionPredicates,q as StringBuilder,z as ObjectorPlugin,On as Objector,g as NavigateResult,L as NavigateAction,un as Markdown,fn as Logger};
27
+ ${n}}`}else return String(r)},Q=(r)=>{if(!r)return r;return r.replaceAll("\\n",`
28
+ `).replaceAll("\\$","$").replaceAll("\\t","\t")};var he=()=>({...J({merge:(...r)=>r.flatMap((e)=>e)}),join:({args:[r],root:e,tags:t})=>{let n=defined(r,"Join source cannot be null or undefined"),i=t.key?.[0],s=t.separator?.[0]??t.sep?.[0],u=t.finalize?.length>0,a=Q(s);if(typeof n==="string"){if(u&&n.length&&a)return n+a;return n}if(!Array.isArray(n))throw Error("Object is not a list");let l=((i?.length)?n.map((O)=>Object.select({...e,...O},i)):n).join(a),y=t.pad?.[0]??"0",d=t.padChar?.[0]??" ",p=u&&l.length&&a?l+a:l;return y?p.padBlock(parseInt(y),`
29
+ `,d):p},range:({args:[r,e,t]})=>{let n=parseInt(r),i=parseInt(e),s=parseInt(t)||1;if(isNaN(n))throw Error("Invalid range: start value '"+String(r)+"' is not a number");if(isNaN(i))throw Error("Invalid range: end value '"+String(e)+"' is not a number");if(s===0)throw Error("Invalid range: step cannot be zero");if((i-n)/s<0)throw Error("Invalid range: step "+String(s)+" has wrong direction for range "+String(n)+" to "+String(i));return Array.from({length:Math.floor((i-n)/s)+1},(u,a)=>n+a*s)},filter:{types:(r,e,t)=>{switch(r){case 0:return"array";case 1:return Object.keys(R)}return cr[t[1].value]?.(r-2,e,t.slice(2))},fn:({args:[r,e,t],root:n,tags:i})=>{if(r===null||r===void 0)throw Error("Filter source cannot be null or undefined");if(!Array.isArray(r))throw Error("Filter source must be an array");let s=i.key?.[0],u=R[e];if(s){let l=Array(r.length);for(let d=0;d<r.length;d++)try{l[d]=Object.select({...n,...r[d]},s)}catch{l[d]=Symbol("invalid")}let y=[];for(let d=0;d<r.length;d++){let p=l[d];if(typeof p!=="symbol"&&t===void 0?u(p):u(p,t))y.push(r[d])}return y}let a=[];for(let l of r)if(t===void 0?u(l):u(l,t))a.push(l);return a}}});var de=()=>({each:{processArgs:!1,fn:async({rawArgs:[r,e,...t],root:n,options:i,tags:s})=>{let u=async(w)=>w.quoted?Q(w.value):await Object.select(n,w.value),a=await Object.select(n,r.value),l=await u(e),y=s.key?.[0],d=Array.isArray(a)?a:Object.toList(a,"name"),p=[],O=await t.mapAsync(async(w)=>await u(w)),b={...n,item:void 0,index:0,params:O,instance:void 0,parent:n.this,tags:s},P={...i,root:b};if(await d.forEachAsync(async(w,j)=>{let D=Object.deepClone(l),A={instance:D},E=typeof l==="string"?A:D;if(b.item=w,b.index=j,b.instance=D,s?.root?.[0])Object.assign(b,await Object.select(b,s.root[0]));if(await $(E,P),y!==void 0)p.push(await Object.select(A.instance,y));else p.push(A.instance)}),s.join?.length){if(p.length===0)return"";let w=Q(s.join[0]),j=s.pad?.[0]??"0",D=s.padChar?.[0]??" ",A=s.finalize?.length&&w?w:"",E=`${p.join(w)}${A}`;return j?E.padBlock(parseInt(j),`
30
+ `,D):E}return p}}});var x=async(r,e,t)=>r.rawArgs[e].quoted?r.rawArgs[e].value:await Object.select(r.root,r.rawArgs[e].value,{defaultValue:t}),be=()=>({switch:{processArgs:!1,fn:async(r)=>{let e=await x(r,0,!1),t=await x(r,1);if(t[e]===void 0){if(r.rawArgs.length>2)return x(r,2);throw Error(`Unhandled switch case: ${e}`)}return t[e]}}});var we=()=>({if:{types:{0:"boolean"},fn:(r)=>r.args[0]?r.args[1]:r.args[2]},check:{types:{0:Object.keys(R)},fn:(r)=>R[r.args[0]](...r.args.slice(1))},...J(R,{types:cr})});var Oe=(r)=>({default:{processArgs:!1,fn:async(e)=>{for(let t=0;t<e.rawArgs.length;t++)if(e.rawArgs[t]?.value!==void 0){let i=await x(e,t,null);if(i!==null)return i}if(e.tags.nullable?.length)return g.DeleteItem();if(e.tags.fail?.length)throw Error(`No valid value found for default (${e.rawArgs.map((t)=>t.value).join(", ")})`);return""}},section:{types:["string","boolean"],fn:(e)=>{let t=e.args[0];if(!(e.args[1]??!0))return null;let i=r.getSection(t);if(!i)throw Error(`Section not found: ${t}`);return i.content}}});var Ae=()=>({convert:({args:[r,e,t]})=>{switch(e){case"string":return String(r);case"number":{let n=Number(r);if(!isNaN(n))return g.ReplaceItem(n);break}case"boolean":if(r==="true"||r===!0||r===1||r==="1"||r==="yes"||r==="on")return g.ReplaceItem(!0);else if(r==="false"||r===!1||r===0||r==="0"||r==="no"||r==="off")return g.ReplaceItem(!1);break;default:throw Error(`Unsupported type for convert: ${e}`)}if(t!==void 0)return g.ReplaceItem(t);throw Error(`Failed to convert value to ${e}`)},isType:({args:[r,e]})=>{let n=(()=>{switch(e){case"string":return typeof r==="string";case"number":return typeof r==="number";case"boolean":return typeof r==="boolean";case"object":return r!==null&&typeof r==="object"&&!Array.isArray(r);case"array":return Array.isArray(r);case"null":return r===null;case"undefined":return r===void 0;case"function":return typeof r==="function";default:throw Error(`Unknown type for isType: ${e}`)}})();return g.ReplaceItem(n)},typeOf:({args:[r]})=>{if(r===null)return"null";else if(Array.isArray(r))return"array";else return typeof r}});var je=(r)=>{var e,t,n,i,s,u,a,l,y,d,p,O,b,P,w,j,D,A,E,F,M,U,B,k,T,V,Er,v,q,mr,rr,er,Se,Fe,Ee,Me,$e,Pe,De,Ce,ke,Le,Re,Ie,Be,_e,Ke,We,qe,Ne,Ye,ze,He,Ge,Je,Ze,Qe,xe,Xe,Ue,Te,Ve,ve,rt,et,tt,nt,it,ot,st,at,ut,ft,ct,lt,mt,pt,gt,yt,ht,dt,bt,wt,Ot,At,jt,St,Ft,Et,Mt,$t,Pt,Dt,Ct,kt,Lt,Rt,It,Bt,_t,Kt,Wt,qt,Nt,i,s,u,a,l,y,d,p,O,b,P,w,j,D,A,E,F,M,U,B,k,T,V,Er,v,q,mr,rr,er,Se,Fe,Ee,Me,$e,Pe,De,Ce,ke,Le,Re,Ie,Be,_e,Ke,We,qe,Ne,Ye,ze,He,Ge,Je,Ze,Qe,xe,Xe,Ue,Te,Ve,ve,rt,et,tt,nt,it,ot,st,at,ut,ft,ct,lt,mt,pt,gt,yt,ht,dt,bt,wt,Ot,At,jt,St,Ft,Et,Mt,$t,Pt,Dt,Ct,kt,Lt,Rt,It,Bt,_t,Kt,Wt,qt,Nt;return r.use((n=G,i=[c()],s=[c()],u=[c()],a=[c()],l=[c()],y=[c()],d=[c()],p=[c()],O=[c()],b=[c()],P=[c()],w=[c()],j=[c()],D=[c()],A=[c()],E=[c()],F=[c()],M=[c()],U=[c()],B=[c()],k=[c()],T=[c()],V=[c()],Er=[c()],v=[c()],q=[c()],mr=[c()],rr=[c()],er=[c()],Se=[c()],Fe=[c()],Ee=[c()],Me=[c()],$e=[c()],Pe=[c()],De=[c()],Ce=[c()],ke=[c()],Le=[c()],Re=[c()],Ie=[c()],Be=[c()],_e=[c()],Ke=[c()],We=[c()],qe=[c()],Ne=[c()],Ye=[c()],ze=[c()],He=[c()],Ge=[c()],Je=[c()],Ze=[c()],Qe=[c()],xe=[c()],Xe=[c()],Ue=[c()],Te=[c()],Ve=[c()],ve=[c()],rt=[c()],et=[c()],tt=[c()],nt=[c()],it=[c()],ot=[c()],st=[c()],at=[c()],ut=[c()],ft=[c()],ct=[c()],lt=[c()],mt=[c()],pt=[c()],gt=[c()],yt=[c()],ht=[c()],dt=[c()],bt=[c()],wt=[c()],Ot=[c()],At=[c()],jt=[c()],St=[c()],Ft=[c()],Et=[c()],Mt=[c()],$t=[c()],Pt=[c()],Dt=[c()],Ct=[c()],kt=[c()],Lt=[c()],Rt=[c()],It=[c()],Bt=[c()],_t=[c()],Kt=[c()],Wt=[c()],qt=[c()],Nt=[c()],t=kr(n),e=class extends n{constructor(){super(...arguments);Rr(t,5,this)}env(o){return process.env[o]}uuid(){return crypto.randomUUID()}pascal(o){return o.toPascal()}camel(o){return o.toCamel()}capital(o){return o.capitalize()}snake(o,m="lower"){return o.changeCase(m).toSnake()}kebab(o,m="lower"){return o.changeCase(m).toKebab()}len(o){return o.length}reverse(o){return o.split("").reverse().join("")}concat(...o){return o.join("")}trim(o){return o.trim()}ltrim(o){return o.trimStart()}rtrim(o){return o.trimEnd()}lower(o){return o.toLowerCase()}upper(o){return o.toUpperCase()}encode(o,m){return Buffer.from(o).toString(m??"base64")}decode(o,m){return Buffer.from(o,m??"base64").toString()}list(o,m="name"){return Object.toList(o,m)}object(o,m="name"){return o.toObject((h)=>h[m],(h)=>{let{[m]:S,...C}=h;return C})}pathJoin(...o){return I.join(...o)}resolve(...o){return I.resolve(...o)}dirname(o){return I.dirname(o)}basename(o,m){return I.basename(o,m)}normalize(o){return I.normalize(o)}extname(o){return I.extname(o)}relative(o,m){return I.relative(o,m)}isAbsolute(o){return I.isAbsolute(o)}segments(o){return o.split("/").filter(Boolean)}log(...o){console.log(...o)}md5(o){return W("md5").update(o).digest("hex")}sha1(o){return W("sha1").update(o).digest("hex")}sha256(o){return W("sha256").update(o).digest("hex")}sha512(o){return W("sha512").update(o).digest("hex")}hash(o,m="sha256"){return W(m).update(o).digest("hex")}hmac(o,m,h="sha256"){return W(h).update(o).digest("hex")}base64Encode(o){return Buffer.from(o).toString("base64")}base64Decode(o){return Buffer.from(o,"base64").toString("utf-8")}hexEncode(o){return Buffer.from(o).toString("hex")}hexDecode(o){return Buffer.from(o,"hex").toString("utf-8")}add(...o){return o.reduce((m,h)=>m+h,0)}subtract(o,m){return o-m}multiply(...o){return o.reduce((m,h)=>m*h,1)}divide(o,m){if(m===0)throw Error("Division by zero");return o/m}modulo(o,m){return o%m}power(o,m){return Math.pow(o,m)}sqrt(o){return Math.sqrt(o)}abs(o){return Math.abs(o)}floor(o){return Math.floor(o)}ceil(o){return Math.ceil(o)}round(o,m){let h=Math.pow(10,m??0);return Math.round(o*h)/h}min(...o){return Math.min(...o)}max(...o){return Math.max(...o)}clamp(o,m,h){return Math.max(m,Math.min(h,o))}random(o,m){let h=o??0,S=m??1;return Math.random()*(S-h)+h}timestamp(o){return new Date(o).getTime()}iso(o){return new Date(o).toISOString()}utc(o){return new Date(o).toUTCString()}formatDate(o,m){let h=new Date(o),S=h.getFullYear(),C=String(h.getMonth()+1).padStart(2,"0"),tr=String(h.getDate()).padStart(2,"0"),N=String(h.getHours()).padStart(2,"0"),Yt=String(h.getMinutes()).padStart(2,"0"),zt=String(h.getSeconds()).padStart(2,"0");return m.replace("YYYY",String(S)).replace("MM",C).replace("DD",tr).replace("HH",N).replace("mm",Yt).replace("ss",zt)}parseDate(o){return new Date(o).getTime()}year(o){return new Date(o).getFullYear()}month(o){return new Date(o).getMonth()+1}day(o){return new Date(o).getDate()}dayOfWeek(o){return new Date(o).getDay()}hours(o){return new Date(o).getHours()}minutes(o){return new Date(o).getMinutes()}seconds(o){return new Date(o).getSeconds()}regexTest(o,m,h){return new RegExp(o,h).test(m)}regexMatch(o,m,h){return new RegExp(o,h).exec(m)}regexMatchAll(o,m,h){return Array.from(m.matchAll(new RegExp(o,h)))}regexReplace(o,m,h,S){return h.replace(new RegExp(o,S),m)}regexReplaceAll(o,m,h,S){return h.replace(new RegExp(o,S??"g"),m)}regexSplit(o,m,h){return m.split(new RegExp(o,h))}regexExec(o,m,h){return new RegExp(o,h).exec(m)}regexSearch(o,m,h){return m.search(new RegExp(o,h))}unique(o,m){if(!Array.isArray(o))return o;let h=new Set;return o.filter((S)=>{let C=m?S[m]:S;if(h.has(C))return!1;return h.add(C),!0})}groupBy(o,m){if(!Array.isArray(o))return o;let h={};return o.forEach((S)=>{let C=String(S[m]);if(!h[C])h[C]=[];h[C].push(S)}),h}chunk(o,m=1){if(!Array.isArray(o))return[];let h=[];for(let S=0;S<o.length;S+=m)h.push(o.slice(S,S+m));return h}flatten(o,m=1){if(!Array.isArray(o))return[o];let h=[],S=(C,tr)=>{for(let N of C)if(Array.isArray(N)&&tr>0)S(N,tr-1);else h.push(N)};return S(o,m),h}compact(o){if(!Array.isArray(o))return o;return o.filter((m)=>m!==null&&m!==void 0)}head(o,m){if(!Array.isArray(o))return o;return m?o.slice(0,m):o[0]}tail(o,m){if(!Array.isArray(o))return o;return m?o.slice(-m):o[o.length-1]}isEmail(o){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o)}isUrl(o){try{return new URL(o),!0}catch{return!1}}isJson(o){try{return JSON.parse(o),!0}catch{return!1}}isUuid(o){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o)}minLength(o,m){return o?.length>=m}maxLength(o,m){return o?.length<=m}lengthEquals(o,m){return o?.length===m}isNumber(o){return typeof o==="number"&&!isNaN(o)}isString(o){return typeof o==="string"}isBoolean(o){return typeof o==="boolean"}isArray(o){return Array.isArray(o)}isObject(o){return o!==null&&typeof o==="object"&&!Array.isArray(o)}isEmpty(o){if(o===null||o===void 0)return!0;if(typeof o==="string"||Array.isArray(o))return o.length===0;if(typeof o==="object")return Object.keys(o).length===0;return!1}isTruthy(o){return!!o}isFalsy(o){return!o}inRange(o,m,h){return o>=m&&o<=h}matchesPattern(o,m){return new RegExp(m).test(o)}includes(o,m){if(typeof o==="string")return o.includes(String(m));return Array.isArray(o)&&o.includes(m)}startsWith(o,m){return o.startsWith(m)}endsWith(o,m){return o.endsWith(m)}},f(t,1,"env",i,e),f(t,1,"uuid",s,e),f(t,1,"pascal",u,e),f(t,1,"camel",a,e),f(t,1,"capital",l,e),f(t,1,"snake",y,e),f(t,1,"kebab",d,e),f(t,1,"len",p,e),f(t,1,"reverse",O,e),f(t,1,"concat",b,e),f(t,1,"trim",P,e),f(t,1,"ltrim",w,e),f(t,1,"rtrim",j,e),f(t,1,"lower",D,e),f(t,1,"upper",A,e),f(t,1,"encode",E,e),f(t,1,"decode",F,e),f(t,1,"list",M,e),f(t,1,"object",U,e),f(t,1,"pathJoin",B,e),f(t,1,"resolve",k,e),f(t,1,"dirname",T,e),f(t,1,"basename",V,e),f(t,1,"normalize",Er,e),f(t,1,"extname",v,e),f(t,1,"relative",q,e),f(t,1,"isAbsolute",mr,e),f(t,1,"segments",rr,e),f(t,1,"log",er,e),f(t,1,"md5",Se,e),f(t,1,"sha1",Fe,e),f(t,1,"sha256",Ee,e),f(t,1,"sha512",Me,e),f(t,1,"hash",$e,e),f(t,1,"hmac",Pe,e),f(t,1,"base64Encode",De,e),f(t,1,"base64Decode",Ce,e),f(t,1,"hexEncode",ke,e),f(t,1,"hexDecode",Le,e),f(t,1,"add",Re,e),f(t,1,"subtract",Ie,e),f(t,1,"multiply",Be,e),f(t,1,"divide",_e,e),f(t,1,"modulo",Ke,e),f(t,1,"power",We,e),f(t,1,"sqrt",qe,e),f(t,1,"abs",Ne,e),f(t,1,"floor",Ye,e),f(t,1,"ceil",ze,e),f(t,1,"round",He,e),f(t,1,"min",Ge,e),f(t,1,"max",Je,e),f(t,1,"clamp",Ze,e),f(t,1,"random",Qe,e),f(t,1,"timestamp",xe,e),f(t,1,"iso",Xe,e),f(t,1,"utc",Ue,e),f(t,1,"formatDate",Te,e),f(t,1,"parseDate",Ve,e),f(t,1,"year",ve,e),f(t,1,"month",rt,e),f(t,1,"day",et,e),f(t,1,"dayOfWeek",tt,e),f(t,1,"hours",nt,e),f(t,1,"minutes",it,e),f(t,1,"seconds",ot,e),f(t,1,"regexTest",st,e),f(t,1,"regexMatch",at,e),f(t,1,"regexMatchAll",ut,e),f(t,1,"regexReplace",ft,e),f(t,1,"regexReplaceAll",ct,e),f(t,1,"regexSplit",lt,e),f(t,1,"regexExec",mt,e),f(t,1,"regexSearch",pt,e),f(t,1,"unique",gt,e),f(t,1,"groupBy",yt,e),f(t,1,"chunk",ht,e),f(t,1,"flatten",dt,e),f(t,1,"compact",bt,e),f(t,1,"head",wt,e),f(t,1,"tail",Ot,e),f(t,1,"isEmail",At,e),f(t,1,"isUrl",jt,e),f(t,1,"isJson",St,e),f(t,1,"isUuid",Ft,e),f(t,1,"minLength",Et,e),f(t,1,"maxLength",Mt,e),f(t,1,"lengthEquals",$t,e),f(t,1,"isNumber",Pt,e),f(t,1,"isString",Dt,e),f(t,1,"isBoolean",Ct,e),f(t,1,"isArray",kt,e),f(t,1,"isObject",Lt,e),f(t,1,"isEmpty",Rt,e),f(t,1,"isTruthy",It,e),f(t,1,"isFalsy",Bt,e),f(t,1,"inRange",_t,e),f(t,1,"matchesPattern",Kt,e),f(t,1,"includes",Wt,e),f(t,1,"startsWith",qt,e),f(t,1,"endsWith",Nt,e),gr(t,e),e)).keys({...zr(r),...Hr(r),...re(),...ee(),...oe(),...te(),...ne(),...ie(r),...ae(r),...ue(),...fe(),...ce()}).sources({...ge(r),...ye(r),...Ae(),...he(),...de(),...be(),...we(),...Oe(r)}).sections(me(r)).fieldOptions({configParser:Bun.YAML.parse,onSection:(o)=>{if(o.section.config.name)r.section(o.section)}}).decoders({yaml:{matching:["\\.yml$","\\.yaml$"],fn:Bun.YAML.parse}}).encoders({json:{fn:(o)=>JSON.stringify(o,null,2)},yaml:{fn:(o)=>Bun.YAML.stringify(o,null,2)},terraform:{options:{includeTags:!0},fn:(o,m)=>lr(o,0,{sortKeys:!!(m?.sort?.length??m?.sortKeys?.length)})}})};import jn from"fs/promises";import X from"path";class Sr{includeDirectories=[];baseIncludeDirectories=[];includes=[];addDirectories(...r){this.includeDirectories.push(...r),this.baseIncludeDirectories.push(...r)}getDirectories(){return this.includeDirectories}reset(){this.includeDirectories=[...this.baseIncludeDirectories]}restore(r){this.includeDirectories=[...r]}snapshot(){return[...this.includeDirectories]}addFiles(...r){this.includes.push(...r)}getPendingAndClear(){let r=[...this.includes];return this.includes.length=0,r}async processPatterns(r,e,t){let n=[];for(let i of r)if(K.isGlobPattern(i)){let s=(await Array.fromAsync(jn.glob(i,{cwd:e}))).map((u)=>X.join(e,u));n.push(...s.filter((u)=>!t.included.includes(u)))}else if(K.isDirectoryPattern(i)){let s=X.isAbsolute(i)?i:X.join(e,i);if(!this.includeDirectories.includes(s))this.includeDirectories.push(s)}else n.push(i);return n.unique()}buildSearchDirs(r){let e=r?[r]:[];return e.push(...this.includeDirectories.map((t)=>X.isAbsolute(t)?t:X.join(r??process.cwd(),t))),e}}class Fr{includeManager;loadFn;constructor(r,e){this.includeManager=r;this.loadFn=e}async processIncludes(r,e,t){let n=[];if(r.content.includes)n.push(...r.content.includes),delete r.content.includes;n.push(...this.includeManager.getPendingAndClear());let i=await this.includeManager.processPatterns(n,r.folderPath,t);for(let s of i)Object.merge(await this.loadFn(s,r.folderPath,{parent:r.content,...e},!0,t),r.content)}}class Sn{includeManager=new Sr;includeProcessor;cacheManager=new wr(100);outputs=[];vars={};funcs={};fields={sources:{},keys:{},sections:{}};objectMetadata={};currentContext=null;storedSections={};dataEncoders={};dataDecoders={};constructor(){this.includeProcessor=new Fr(this.includeManager,this.load.bind(this)),this.use(je)}use(r){if(r.prototype instanceof G)new r(this);else r(this);return this}includeDirectory(...r){return this.includeManager.addDirectories(...r),this}getIncludeDirectories(){return this.includeManager.getDirectories()}include(...r){return this.includeManager.addFiles(...r),this}keys(r){return Object.assign(this.fields.keys,{...this.fields.keys,...r}),this}sources(r){return Object.assign(this.fields.sources,{...this.fields.sources,...r}),this}sections(r){return Object.assign(this.fields.sections,{...this.fields.sections,...r}),this}variables(r){return Object.assign(this.vars,{...this.vars,...r}),this}functions(r){return Object.assign(this.funcs,{...this.funcs,...r}),this}getFunctions(){return this.funcs}getOutputs(){return this.outputs}output(r){return this.outputs.push(r),this}metadata(r,e){return this.objectMetadata[r]=e,this}getMetadata(r){return this.objectMetadata[r]}getAllMetadata(){return this.objectMetadata}setCacheMaxSize(r){return this.cacheManager.setMaxSize(r),this}clearCache(){return this.cacheManager.clear(),this}getCurrentContext(){return this.currentContext}fieldOptions(r){return Object.assign(this.fields,{...this.fields,...r}),this}section(r){return this.storedSections[r.config.name]=r,this}getSection(r){return this.storedSections[r]}encoders(r){return Object.assign(this.dataEncoders,{...this.dataEncoders,...r}),this}decoders(r){return Object.assign(this.dataDecoders,{...this.dataDecoders,...r}),this}getEncoder(r){return this.dataEncoders[r]}getDecoder(r){return this.dataDecoders[r]}filter(r){return this.fields.filters??=[],this.fields.filters.push(r),this}async loadObject(r,e,t){return $(r,{...this.fields,globalContext:{file:t?.fullPath??"@internal"},root:{...e,...this.fields.root,...this.vars,functions:this.funcs,context:this.currentContext,sections:this.storedSections,$document:{root:{content:r},fileName:t?.fileName??"@internal",folder:t?.folderPath??"@internal",fullPath:t?.fullPath??"@internal"}}})}async load(r,e,t,n,i){let s=this.includeManager.snapshot();try{this.includeManager.reset();let u=this.includeManager.buildSearchDirs(e);if(i)this.currentContext=i;this.currentContext??={included:[],document:null};let a=typeof r==="string"?await Kr(r,{dirs:u,parsers:this.dataDecoders,format:"yaml"}):{content:r,fullPath:"",folderPath:""};if(typeof r==="string"){let y=K.normalize(a.fullPath);if(this.currentContext.included.push(y),!a.content)return null;let d=this.cacheManager.get(y),p;if(d)p=d.raw;else p=a.content,this.cacheManager.set(y,{raw:p,timestamp:Date.now()});let O=Object.deepClone(p);a.content=O}await this.includeProcessor.processIncludes(a,t,this.currentContext);let l;if(n!==!0)l=await this.loadObject(a.content,t,{fileName:a.fullPath,folderPath:a.folderPath,fullPath:a.fullPath});else l=a.content;return this.currentContext.document=l,l}catch(u){throw this.includeManager.restore(s),u}finally{this.includeManager.restore(s)}}async writeAll(r){await Nr(this.getOutputs(),r)}}export{Nr as writeOutputs,fn as writeOutput,an as writeFormat,Nn as variable,Yn as sharedFunction,Wn as section,$ as processFields,J as makeFieldProcessorMap,Ci as makeFieldProcessorList,vr as makeFieldProcessor,c as macro,nr as locate,Kr as loadFormat,qn as key,ln as importList,_n as importGlob,Wr as globMap,ur as getProcessor,Yr as getCwd,Zr as getArgs,br as exists,zn as encoder,Hn as decoder,R as conditionPredicates,H as StringBuilder,G as ObjectorPlugin,Sn as Objector,g as NavigateResult,L as NavigateAction,vt as Markdown,Vt as Logger,rn as CommandLineArgs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@homedev/objector",
3
- "version": "1.3.7",
3
+ "version": "1.3.9",
4
4
  "description": "object extensions for YAML/JSON",
5
5
  "author": "julzor",
6
6
  "license": "ISC",