janja 2.4.3 → 3.0.0

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,29 @@
1
+ declare class LRUCache<T> {
2
+ private cache;
3
+ private maxSize;
4
+ private ttl;
5
+ private stats;
6
+ constructor(options?: CacheOptions);
7
+ get(key: string): T | null;
8
+ /**
9
+ * Look at an entry without counting it as a hit or changing its position.
10
+ */
11
+ peek(key: string): T | null;
12
+ set(key: string, value: T): void;
13
+ has(key: string): boolean;
14
+ delete(key: string): boolean;
15
+ clear(): void;
16
+ invalidate(predicate?: (key: string) => boolean): void;
17
+ getStats(): {
18
+ size: number;
19
+ hitRate: number;
20
+ hits: number;
21
+ misses: number;
22
+ evictions: number;
23
+ };
24
+ resetStats(): void;
25
+ }
26
+
1
27
  interface Mapping {
2
28
  source: Loc;
3
29
  target: Loc;
@@ -42,12 +68,23 @@ declare class SourceMap {
42
68
  }
43
69
 
44
70
  declare class OutScript extends SourceMap {
45
- code: string;
71
+ private codeParts;
72
+ private codeLength;
73
+ get code(): string;
74
+ set code(value: string);
46
75
  get script(): Script;
47
- start(): void;
76
+ checkpoint(): unknown;
77
+ rollback(checkpoint: unknown): void;
78
+ start(root?: boolean): void;
48
79
  end(): void;
49
80
  pushRaw(loc: Loc | null, ...lines: string[]): void;
50
81
  pushStr(loc: Loc | null, s: string): Pos | void;
82
+ /**
83
+ * In stream mode, hand the output collected so far to the writer once
84
+ * there is enough of it. Only valid where `s` is the template's own output,
85
+ * i.e. not inside captures, macros, blocks or partials.
86
+ */
87
+ pushFlush(): void;
51
88
  pushVar(loc: Loc | null, v: string): void;
52
89
  }
53
90
 
@@ -55,6 +92,8 @@ declare class Context extends OutScript {
55
92
  context: string;
56
93
  private stack;
57
94
  private index;
95
+ checkpoint(): unknown;
96
+ rollback(checkpoint: unknown): void;
58
97
  in(): string;
59
98
  out(): void;
60
99
  }
@@ -100,6 +139,8 @@ interface SyntaxNode {
100
139
  type: string;
101
140
  loc: Loc;
102
141
  body?: SyntaxNode[];
142
+ val?: Exp | string;
143
+ strip?: Strip;
103
144
  traverse: (cb: (node: SyntaxNode) => void) => void;
104
145
  }
105
146
  declare class Traversal implements SyntaxNode {
@@ -124,16 +165,39 @@ declare class BlockNode extends Traversal {
124
165
  constructor(val: IdExp, body: SyntaxNode[], loc: Loc, strip: Strip);
125
166
  }
126
167
 
168
+ interface CompiledTemplate {
169
+ code: string;
170
+ mappings: Mapping[];
171
+ script?: Script;
172
+ sources: Map<string, string>;
173
+ fingerprint: string;
174
+ }
175
+ declare function templateCacheKey(template: string, stream?: boolean): string;
176
+ declare function optionsFingerprint(options: Required<CompilerOptions>): string;
127
177
  declare class Compiler extends Context {
128
178
  options: Required<CompilerOptions>;
179
+ private revalidate;
180
+ private stream;
129
181
  template: string;
130
182
  state: Record<string, any>;
131
183
  private isRoot;
132
184
  private rootNode;
133
185
  private partials;
134
186
  private blocks;
135
- constructor(options?: CompilerOptions);
136
- compile(template: string, root?: boolean, partials?: Map<string, string>, blocks?: Map<string, BlockNode[]>): Promise<this>;
187
+ private sources;
188
+ private cache?;
189
+ private compiled?;
190
+ /**
191
+ * Whether the code being generated may write output to the stream. True
192
+ * only in stream mode, for the template's own top-level output.
193
+ */
194
+ flushable: boolean;
195
+ constructor(options: Required<CompilerOptions>, cache?: LRUCache<CompiledTemplate>, revalidate?: boolean, stream?: boolean);
196
+ compile(template: string, root?: boolean, partials?: Map<string, string>, blocks?: Map<string, BlockNode[]>, sources?: Map<string, string>): Promise<this>;
197
+ get script(): Script;
198
+ private generateCacheKey;
199
+ private fingerprint;
200
+ private isFresh;
137
201
  private parseTemplates;
138
202
  private collectPartialsAndBlocks;
139
203
  private compileNode;
@@ -148,9 +212,10 @@ declare class Tokenizer implements Pos {
148
212
  protected index: number;
149
213
  protected tokens: Token[];
150
214
  private tokenPatterns;
215
+ private markerIndices;
151
216
  line: number;
152
217
  column: number;
153
- constructor(options?: ParserOptions);
218
+ constructor(options: Required<ParserOptions>);
154
219
  tokenize(template: string): Token[];
155
220
  private consumeSpecialTokens;
156
221
  private consumeTextToken;
@@ -161,8 +226,8 @@ declare class Tokenizer implements Pos {
161
226
  declare class Parser extends Tokenizer {
162
227
  private expParser;
163
228
  protected cursor: number;
164
- parse(template: string): Promise<RootNode>;
165
- parseUntil(names?: string[]): Promise<SyntaxNode[]>;
229
+ parse(template: string): RootNode;
230
+ parseUntil(names?: string[]): SyntaxNode[];
166
231
  parseExp<T extends Exp = Exp>({ val, loc }: DirectiveExpression): T | undefined;
167
232
  peek(): Token | null;
168
233
  private advance;
@@ -170,6 +235,24 @@ declare class Parser extends Tokenizer {
170
235
  emitExpErr({ name, loc }: DirectiveToken, required?: boolean): void;
171
236
  }
172
237
 
238
+ interface SecurityOptions {
239
+ sandbox?: boolean;
240
+ allowedGlobals?: string[];
241
+ deepEscape?: boolean;
242
+ cspNonce?: string;
243
+ cspHeaders?: Record<string, string>;
244
+ }
245
+ interface SecurityAuditResult {
246
+ issues: SecurityIssue[];
247
+ severity: 'low' | 'medium' | 'high' | 'critical';
248
+ }
249
+ interface SecurityIssue {
250
+ type: string;
251
+ message: string;
252
+ location?: string;
253
+ severity: 'low' | 'medium' | 'high' | 'critical';
254
+ }
255
+
173
256
  type MaybePromise<T> = T | Promise<T>;
174
257
  type ObjectType<T = any> = Record<string, T>;
175
258
  type Primitive = string | number | boolean | null | undefined;
@@ -218,18 +301,28 @@ interface DirectiveExpression {
218
301
  loc: Loc;
219
302
  }
220
303
  type Token = CommentToken | DirectiveToken | OutputToken | TextToken;
221
- type Filters = Record<string, (value: any, ...args: any[]) => any>;
222
- type Script = (globals: ObjectType, escape: (v: any) => any, filters: Filters) => Promise<string>;
304
+ /**
305
+ * A filter receives the piped value followed by the arguments written in the
306
+ * template. `this` is the context the expression is evaluated in. It may
307
+ * return a promise.
308
+ */
309
+ type Filter<Value = any, Args extends any[] = any[], Result = unknown> = (this: ObjectType, value: Value, ...args: Args) => Result;
310
+ type Filters = Record<string, Filter>;
311
+ type Script = (globals: ObjectType, escape: (v: any) => any, filters: Filters,
312
+ /** Receives chunks of output when the template was compiled for streaming */
313
+ write?: (chunk: string) => void | Promise<void>) => Promise<string>;
223
314
  interface Plugin {
224
315
  filters?: Filters;
225
316
  parsers?: ParserMap;
226
317
  compilers?: CompilerMap;
318
+ formatters?: FormatterMap;
227
319
  }
228
- type ParserFn<T extends Token = any, U extends SyntaxNode = any> = (token: T, parser: Parser) => AsyncGenerator<U | 'NEXT' | void>;
320
+ type ParserFn<T extends Token = any, U extends SyntaxNode = any> = (token: T, parser: Parser) => Generator<U | 'NEXT' | void>;
229
321
  type ParserMap = Record<string, string | ParserFn>;
230
322
  type CompilerFn<T extends SyntaxNode = any> = (node: T, compiler: Compiler) => MaybePromise<void>;
231
323
  type CompilerMap = Record<string, string | CompilerFn>;
232
-
324
+ type FormatterFn<T extends SyntaxNode = any> = (node: T) => string;
325
+ type FormatterMap = Record<string, string | FormatterFn>;
233
326
  interface BaseOptions {
234
327
  debug?: (error: Error) => any;
235
328
  filters?: Filters;
@@ -250,34 +343,295 @@ interface CompilerOptions extends ParserOptions {
250
343
  stripComments?: boolean;
251
344
  loader?: (path: string) => Promise<string>;
252
345
  }
346
+ interface FormatterOptions extends ParserOptions {
347
+ trimWhitespace?: boolean;
348
+ stripComments?: boolean;
349
+ }
350
+ interface CacheOptions {
351
+ enabled?: boolean;
352
+ maxSize?: number;
353
+ ttl?: number;
354
+ /**
355
+ * Re-read included templates through the loader on every cache hit and
356
+ * recompile when one of them changed. Disable when templates are immutable
357
+ * at runtime to skip those loader calls.
358
+ * @default true
359
+ */
360
+ revalidate?: boolean;
361
+ }
253
362
  interface RendererOptions extends CompilerOptions {
254
363
  globals?: ObjectType;
255
364
  autoEscape?: boolean;
365
+ cache?: CacheOptions;
366
+ security?: SecurityOptions;
367
+ }
368
+ /**
369
+ * Define filters with their value and argument types checked, e.g.
370
+ * `defineFilters({ shout: (value: string, times = 1) => ... })`.
371
+ */
372
+ declare function defineFilters<T extends Filters>(filters: T): T;
373
+ /**
374
+ * Define a plugin (filters, parsers and compilers) with its shape checked.
375
+ */
376
+ declare function definePlugin<T extends Plugin>(plugin: T): T;
377
+
378
+ declare class Safe extends String {
379
+ constructor(value: unknown);
380
+ }
381
+
382
+ declare function escape(v: unknown): string;
383
+
384
+ declare function abs(this: ObjectType, value?: number): number;
385
+ declare function add(this: ObjectType, value?: number, addend?: number): number;
386
+ declare function capitalize(this: ObjectType, value?: string): string;
387
+ declare function ceil(this: ObjectType, value?: number): number;
388
+ declare function compact(this: ObjectType, value?: unknown[]): {}[];
389
+ declare function div(this: ObjectType, value?: number, divisor?: number): number;
390
+ declare function entries(this: ObjectType, value?: ObjectType): [string, any][];
391
+ declare function even(this: ObjectType, value?: number | string): boolean;
392
+ declare function fallback(this: ObjectType, value: any, defaultValue: any, anyFalsy?: boolean): any;
393
+ declare function first(this: ObjectType, value?: string | any[]): any;
394
+ declare function get(this: ObjectType, value: ObjectType, ...path: string[]): ObjectType;
395
+ declare function groupby(this: ObjectType, value: ObjectType[] | undefined, key: string): Record<string, ObjectType[]>;
396
+ declare function join(this: ObjectType, value?: string | string[], separator?: string): string;
397
+ declare function json(this: ObjectType, value?: unknown, indent?: number): Safe;
398
+ declare function keys(this: ObjectType, value?: ObjectType): string[];
399
+ declare function last(this: ObjectType, value?: string | unknown[]): unknown;
400
+ declare function length(this: ObjectType, value?: string): number;
401
+ declare function lower(this: ObjectType, value?: string): string;
402
+ declare function map(this: ObjectType, value: ObjectType[] | undefined, key: string, defaultValue?: unknown): any[];
403
+ declare function max(this: ObjectType, value?: number, ...rest: number[]): number;
404
+ declare function min(this: ObjectType, value?: number, ...rest: number[]): number;
405
+ declare function mul(this: ObjectType, value?: number, multiplier?: number): number;
406
+ declare function odd(this: ObjectType, value?: number | string): boolean;
407
+ declare function omit(this: ObjectType, value?: ObjectType, ...omitKeys: string[]): {};
408
+ declare function pick(this: ObjectType, value?: ObjectType, ...pickKeys: string[]): {};
409
+ declare function repeat(this: ObjectType, value?: string, count?: number): string;
410
+ declare function replace(this: ObjectType, value: string | undefined, search: string, replacement: string): string;
411
+ declare function reverse(this: ObjectType, value?: string | unknown[]): string | unknown[];
412
+ declare function safe(this: ObjectType, value?: string): Safe;
413
+ declare function slice(this: ObjectType, value?: string, start?: number, end?: number): string;
414
+ declare function sort(this: ObjectType, value?: string | unknown[]): string | unknown[];
415
+ declare function split(this: ObjectType, value?: string, separator?: string): string[];
416
+ declare function sub(this: ObjectType, value?: number, subtrahend?: number): number;
417
+ declare function sum(this: ObjectType, value?: number[]): number;
418
+ declare function trim(this: ObjectType, value?: string): string;
419
+ declare function truncate(this: ObjectType, value?: string, maxLength?: number, truncateStr?: string): string;
420
+ declare function unique(this: ObjectType, value?: string | unknown[]): string | unknown[];
421
+ declare function upper(this: ObjectType, value?: string): string;
422
+ declare function urldecode(this: ObjectType, value?: string): string;
423
+ declare function urlencode(this: ObjectType, value?: string): string;
424
+ declare function values(this: ObjectType, value?: ObjectType): any[];
425
+ declare function date(this: ObjectType, value: Date | string, format?: string): string;
426
+ declare function timeAgo(this: ObjectType, value: Date | string): string;
427
+ declare function round(this: ObjectType, value: number, decimals?: number): number;
428
+ declare function fixed(this: ObjectType, value: number, decimals?: number): string;
429
+ declare function percent(this: ObjectType, value: number, decimals?: number): string;
430
+ declare function currency(this: ObjectType, value: number, currencyCode?: string, locale?: string): string;
431
+ declare function wordCount(this: ObjectType, value: string): number;
432
+ declare function stripTags(this: ObjectType, value: string): string;
433
+ declare function slugify(this: ObjectType, value: string): string;
434
+ declare function shuffle(this: ObjectType, value: unknown[]): unknown[];
435
+ declare function chunk(this: ObjectType, value: unknown[], size: number): unknown[][];
436
+ declare function pluck(this: ObjectType, value: ObjectType[], key: string): any[];
437
+ declare function defaults(this: ObjectType, value: ObjectType, defaultValues: ObjectType): {
438
+ [x: string]: any;
439
+ };
440
+ declare function invert(this: ObjectType, value: ObjectType): {};
441
+ declare function merge(this: ObjectType, value: ObjectType, ...objects: ObjectType[]): any;
442
+ declare function fetchUrl(this: ObjectType, url: string, options?: RequestInit): Promise<string>;
443
+ declare function delay(this: ObjectType, value: unknown, ms: number): Promise<unknown>;
444
+
445
+ declare const filters_abs: typeof abs;
446
+ declare const filters_add: typeof add;
447
+ declare const filters_capitalize: typeof capitalize;
448
+ declare const filters_ceil: typeof ceil;
449
+ declare const filters_chunk: typeof chunk;
450
+ declare const filters_compact: typeof compact;
451
+ declare const filters_currency: typeof currency;
452
+ declare const filters_date: typeof date;
453
+ declare const filters_defaults: typeof defaults;
454
+ declare const filters_delay: typeof delay;
455
+ declare const filters_div: typeof div;
456
+ declare const filters_entries: typeof entries;
457
+ declare const filters_escape: typeof escape;
458
+ declare const filters_even: typeof even;
459
+ declare const filters_fallback: typeof fallback;
460
+ declare const filters_fetchUrl: typeof fetchUrl;
461
+ declare const filters_first: typeof first;
462
+ declare const filters_fixed: typeof fixed;
463
+ declare const filters_get: typeof get;
464
+ declare const filters_groupby: typeof groupby;
465
+ declare const filters_invert: typeof invert;
466
+ declare const filters_join: typeof join;
467
+ declare const filters_json: typeof json;
468
+ declare const filters_keys: typeof keys;
469
+ declare const filters_last: typeof last;
470
+ declare const filters_length: typeof length;
471
+ declare const filters_lower: typeof lower;
472
+ declare const filters_map: typeof map;
473
+ declare const filters_max: typeof max;
474
+ declare const filters_merge: typeof merge;
475
+ declare const filters_min: typeof min;
476
+ declare const filters_mul: typeof mul;
477
+ declare const filters_odd: typeof odd;
478
+ declare const filters_omit: typeof omit;
479
+ declare const filters_percent: typeof percent;
480
+ declare const filters_pick: typeof pick;
481
+ declare const filters_pluck: typeof pluck;
482
+ declare const filters_repeat: typeof repeat;
483
+ declare const filters_replace: typeof replace;
484
+ declare const filters_reverse: typeof reverse;
485
+ declare const filters_round: typeof round;
486
+ declare const filters_safe: typeof safe;
487
+ declare const filters_shuffle: typeof shuffle;
488
+ declare const filters_slice: typeof slice;
489
+ declare const filters_slugify: typeof slugify;
490
+ declare const filters_sort: typeof sort;
491
+ declare const filters_split: typeof split;
492
+ declare const filters_stripTags: typeof stripTags;
493
+ declare const filters_sub: typeof sub;
494
+ declare const filters_sum: typeof sum;
495
+ declare const filters_timeAgo: typeof timeAgo;
496
+ declare const filters_trim: typeof trim;
497
+ declare const filters_truncate: typeof truncate;
498
+ declare const filters_unique: typeof unique;
499
+ declare const filters_upper: typeof upper;
500
+ declare const filters_urldecode: typeof urldecode;
501
+ declare const filters_urlencode: typeof urlencode;
502
+ declare const filters_values: typeof values;
503
+ declare const filters_wordCount: typeof wordCount;
504
+ declare namespace filters {
505
+ export {
506
+ filters_abs as abs,
507
+ filters_add as add,
508
+ filters_capitalize as capitalize,
509
+ filters_ceil as ceil,
510
+ filters_chunk as chunk,
511
+ filters_compact as compact,
512
+ filters_currency as currency,
513
+ filters_date as date,
514
+ filters_defaults as defaults,
515
+ filters_delay as delay,
516
+ filters_div as div,
517
+ filters_entries as entries,
518
+ filters_escape as escape,
519
+ filters_even as even,
520
+ filters_fallback as fallback,
521
+ filters_fetchUrl as fetchUrl,
522
+ filters_first as first,
523
+ filters_fixed as fixed,
524
+ filters_get as get,
525
+ filters_groupby as groupby,
526
+ filters_invert as invert,
527
+ filters_join as join,
528
+ filters_json as json,
529
+ filters_keys as keys,
530
+ filters_last as last,
531
+ filters_length as length,
532
+ filters_lower as lower,
533
+ filters_map as map,
534
+ filters_max as max,
535
+ filters_merge as merge,
536
+ filters_min as min,
537
+ filters_mul as mul,
538
+ filters_odd as odd,
539
+ filters_omit as omit,
540
+ filters_percent as percent,
541
+ filters_pick as pick,
542
+ filters_pluck as pluck,
543
+ filters_repeat as repeat,
544
+ filters_replace as replace,
545
+ filters_reverse as reverse,
546
+ filters_round as round,
547
+ filters_safe as safe,
548
+ filters_shuffle as shuffle,
549
+ filters_slice as slice,
550
+ filters_slugify as slugify,
551
+ filters_sort as sort,
552
+ filters_split as split,
553
+ filters_stripTags as stripTags,
554
+ filters_sub as sub,
555
+ filters_sum as sum,
556
+ filters_timeAgo as timeAgo,
557
+ filters_trim as trim,
558
+ filters_truncate as truncate,
559
+ filters_unique as unique,
560
+ filters_upper as upper,
561
+ filters_urldecode as urldecode,
562
+ filters_urlencode as urlencode,
563
+ filters_values as values,
564
+ filters_wordCount as wordCount,
565
+ };
566
+ }
567
+
568
+ interface ErrorSuggestion {
569
+ message: string;
570
+ fix?: string;
571
+ example?: string;
256
572
  }
257
573
 
258
574
  declare class CompileError extends SyntaxError {
259
575
  protected src: string;
260
576
  protected loc?: Loc | undefined;
261
- constructor(message: string, src: string, loc?: Loc | undefined);
577
+ protected context?: string | undefined;
578
+ constructor(message: string, src: string, loc?: Loc | undefined, context?: string | undefined);
262
579
  get details(): string;
580
+ get suggestions(): ErrorSuggestion[];
263
581
  }
264
582
 
583
+ declare const baseOptions: Required<BaseOptions>;
584
+ declare const parserOptions: Required<ParserOptions>;
585
+ declare const compilerOptions: Required<CompilerOptions>;
586
+ declare const renderOptions: Required<RendererOptions>;
587
+ declare const mergeOptions: <T extends Required<BaseOptions>, U extends RendererOptions>(defaultOptions: T, ...optionsArray: U[]) => Required<U>;
588
+
265
589
  declare class RenderError extends CompileError {
266
590
  protected src: string;
267
591
  protected getLoc: () => Loc;
268
- constructor(message: string, src: string, getLoc: () => Loc);
592
+ constructor(message: string, src: string, getLoc: () => Loc, context?: string);
269
593
  get details(): string;
270
594
  }
271
595
 
272
596
  declare class Renderer {
273
597
  protected options: Required<RendererOptions>;
598
+ private cache?;
599
+ private sandbox?;
600
+ private filters;
601
+ private escape;
274
602
  constructor(options?: RendererOptions);
275
603
  render(template: string, globals: ObjectType): Promise<string>;
604
+ /**
605
+ * Bind a template to the type of data it expects:
606
+ * `const page = renderer.template<{ title: string }>(source)`.
607
+ */
608
+ template<Data extends ObjectType = ObjectType>(template: string): (data: Data) => Promise<string>;
609
+ /**
610
+ * Render a template that was compiled ahead of time by `precompileTemplate`.
611
+ */
612
+ renderCompiled(script: Script, globals?: ObjectType): Promise<string>;
613
+ /**
614
+ * Render a template as a stream of chunks, so the first bytes can be sent
615
+ * before the whole page is rendered. Output is written between top-level
616
+ * parts of the template and between the iterations of top-level loops.
617
+ */
618
+ renderStream(template: string, globals?: ObjectType): ReadableStream<string>;
619
+ private createCompiler;
620
+ private wrapError;
621
+ private run;
276
622
  renderFile(filepath: string, globals: ObjectType): Promise<string>;
277
- }
278
-
279
- declare class Safe extends String {
280
- constructor(value: unknown);
623
+ clearCache(): void;
624
+ invalidateCache(predicate?: (key: string) => boolean): void;
625
+ getCacheStats(): {
626
+ size: number;
627
+ hitRate: number;
628
+ hits: number;
629
+ misses: number;
630
+ evictions: number;
631
+ } | null;
632
+ resetCacheStats(): void;
633
+ auditTemplate(template: string): SecurityAuditResult;
634
+ getCSPHeaders(): Record<string, string>;
281
635
  }
282
636
 
283
637
  declare class ExpCompiler {
@@ -298,7 +652,10 @@ declare class ExpCompiler {
298
652
 
299
653
  declare class ExpError extends SyntaxError {
300
654
  loc: Loc;
301
- constructor(message: string, loc: Loc);
655
+ private context?;
656
+ constructor(message: string, loc: Loc, context?: string | undefined);
657
+ get suggestions(): ErrorSuggestion[];
658
+ get details(): string;
302
659
  }
303
660
 
304
661
  interface ExpToken<T = ExpTokenType> {
@@ -308,6 +665,7 @@ interface ExpToken<T = ExpTokenType> {
308
665
  raw?: string;
309
666
  }
310
667
  declare const expTokenTypes: Record<string, ExpTokenType>;
668
+ declare function isForbiddenIdentifier(name: unknown): boolean;
311
669
  declare class ExpTokenizer implements Pos {
312
670
  val: string;
313
671
  tokens: ExpToken[];
@@ -315,6 +673,7 @@ declare class ExpTokenizer implements Pos {
315
673
  line: number;
316
674
  column: number;
317
675
  tokenize(val: string, loc: Loc): ExpToken<ExpTokenType>[];
676
+ private afterOperand;
318
677
  private readString;
319
678
  private readNumber;
320
679
  private readIdentifier;
@@ -340,8 +699,327 @@ declare class ExpParser implements Pos {
340
699
  private consume;
341
700
  }
342
701
 
702
+ /**
703
+ * A source map as defined by the Source Map Revision 3 specification.
704
+ */
705
+ interface SourceMapV3 {
706
+ version: 3;
707
+ file?: string;
708
+ sources: string[];
709
+ sourcesContent: string[];
710
+ names: string[];
711
+ mappings: string;
712
+ }
713
+ interface SourceMapOptions {
714
+ /** Name of the generated file */
715
+ file?: string;
716
+ /** Name of the template the code was compiled from */
717
+ source: string;
718
+ /** The template itself, embedded so tools need not find it on disk */
719
+ sourceContent: string;
720
+ /** Zero-based line of the generated file that holds the compiled code */
721
+ line: number;
722
+ }
723
+ /**
724
+ * Turn the compiler's mappings (template location -> offset in the compiled
725
+ * code, which is a single line) into a standard source map.
726
+ */
727
+ declare function generateSourceMap(mappings: Mapping[], { file, source, sourceContent, line }: SourceMapOptions): SourceMapV3;
728
+
729
+ interface PrecompileOptions extends CompilerOptions {
730
+ /**
731
+ * Also export a ready-to-call `render(globals, options)` function. The
732
+ * generated module then imports the runtime from `janja`.
733
+ */
734
+ includeRuntime?: boolean;
735
+ /** Also return a source map (`precompile` only) */
736
+ sourceMap?: boolean;
737
+ /** Name of the template, recorded in the source map */
738
+ filename?: string;
739
+ /** Also return TypeScript declarations for the module (`precompile` only) */
740
+ dts?: boolean;
741
+ }
742
+ interface PrecompileResult {
743
+ /** Source of an ES module exporting the compiled template as `script` */
744
+ code: string;
745
+ /** Present when the `sourceMap` option is set */
746
+ map?: SourceMapV3;
747
+ /** Present when the `dts` option is set */
748
+ dts?: string;
749
+ }
750
+ /**
751
+ * Compile a template into the source of an ES module, optionally with a
752
+ * source map pointing back into the template.
753
+ *
754
+ * The module's `script` export is the compiled template; pass it to
755
+ * `renderCompiled` to render it without compiling anything at runtime.
756
+ */
757
+ declare function precompile(template: string, { includeRuntime, sourceMap, filename, dts, ...options }?: PrecompileOptions): Promise<PrecompileResult>;
758
+ /**
759
+ * Compile a template into the source of an ES module. See `precompile`.
760
+ */
761
+ declare function precompileTemplate(template: string, options?: PrecompileOptions): Promise<string>;
762
+
763
+ interface TranslationDict {
764
+ [key: string]: string | TranslationDict;
765
+ }
766
+ interface I18nOptions {
767
+ defaultLocale?: string;
768
+ locale?: string;
769
+ translations?: Record<string, TranslationDict>;
770
+ pluralRules?: PluralRules;
771
+ }
772
+ interface PluralRules {
773
+ [locale: string]: (n: number) => 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';
774
+ }
775
+ declare class I18n {
776
+ private defaultLocale;
777
+ private currentLocale;
778
+ private translations;
779
+ private pluralRules;
780
+ constructor(options?: I18nOptions);
781
+ setLocale(locale: string): void;
782
+ getLocale(): string;
783
+ addTranslations(locale: string, translations: TranslationDict): void;
784
+ translate(key: string, params?: ObjectType): string;
785
+ t(key: string, params?: ObjectType): string;
786
+ pluralize(key: string, count: number, params?: ObjectType): string;
787
+ formatDate(date: Date | string, options?: Intl.DateTimeFormatOptions): string;
788
+ formatNumber(number: number, options?: Intl.NumberFormatOptions): string;
789
+ formatCurrency(number: number, currency: string, options?: Intl.NumberFormatOptions): string;
790
+ private getTranslation;
791
+ private interpolate;
792
+ private getPluralForm;
793
+ private getDefaultPluralRules;
794
+ private mergeDeep;
795
+ private isObject;
796
+ }
797
+ declare const i18n: I18n;
798
+
799
+ interface CompositionOptions {
800
+ data?: ObjectType;
801
+ options?: RendererOptions;
802
+ }
803
+ /**
804
+ * Compose multiple templates together, passing the output of one as input to the next.
805
+ */
806
+ declare function composeTemplates(templates: string[], options?: CompositionOptions): Promise<string>;
807
+ /**
808
+ * Compose templates with partial data, allowing each template to access specific data.
809
+ */
810
+ declare function composeTemplatesWithData(templates: Array<{
811
+ template: string;
812
+ data?: ObjectType;
813
+ }>, options?: CompositionOptions): Promise<string>;
814
+ /**
815
+ * Create a template composition pipeline.
816
+ */
817
+ declare class TemplatePipeline {
818
+ private templates;
819
+ private data;
820
+ private options?;
821
+ constructor(options?: RendererOptions);
822
+ addTemplate(template: string): TemplatePipeline;
823
+ setData(data: ObjectType): TemplatePipeline;
824
+ setOptions(options: RendererOptions): TemplatePipeline;
825
+ execute(): Promise<string>;
826
+ }
827
+ /**
828
+ * Compose templates in a layout pattern (header, content, footer).
829
+ */
830
+ declare function composeLayout(layout: string, content: string, options?: CompositionOptions): Promise<string>;
831
+ /**
832
+ * Compose templates with slots for flexible content placement.
833
+ */
834
+ declare function composeWithSlots(template: string, slots: Record<string, string>, options?: CompositionOptions): Promise<string>;
835
+
836
+ interface WhitespaceOptions {
837
+ trim?: boolean;
838
+ stripComments?: boolean;
839
+ collapseWhitespace?: boolean;
840
+ preserveNewlines?: boolean;
841
+ }
842
+ declare const defaultWhitespaceOptions: Required<WhitespaceOptions>;
843
+ declare function mergeWhitespaceOptions(options?: WhitespaceOptions): Required<WhitespaceOptions>;
844
+ declare function applyWhitespaceControl(content: string, options: Required<WhitespaceOptions>): string;
845
+ declare function getWhitespaceCompilerOptions(options: WhitespaceOptions): Partial<CompilerOptions>;
846
+ declare function getWhitespaceRendererOptions(options: WhitespaceOptions): Partial<RendererOptions>;
847
+
848
+ interface MixinDefinition {
849
+ name: string;
850
+ template: string;
851
+ data?: ObjectType;
852
+ }
853
+ interface MixinOptions {
854
+ data?: ObjectType;
855
+ options?: RendererOptions;
856
+ }
857
+ declare class MixinRegistry {
858
+ private mixins;
859
+ register(mixin: MixinDefinition): void;
860
+ registerMultiple(mixins: MixinDefinition[]): void;
861
+ get(name: string): MixinDefinition | undefined;
862
+ has(name: string): boolean;
863
+ delete(name: string): boolean;
864
+ clear(): void;
865
+ list(): string[];
866
+ }
867
+ declare const globalMixinRegistry: MixinRegistry;
868
+ declare function applyMixin(name: string, options?: MixinOptions, registry?: MixinRegistry): Promise<string>;
869
+ declare function applyMixins(names: string[], options?: MixinOptions, registry?: MixinRegistry): Promise<string[]>;
870
+ declare function extendTemplateWithMixin(baseTemplate: string, mixinName: string, options?: MixinOptions, registry?: MixinRegistry): Promise<string>;
871
+ declare function createMixin(name: string, template: string, data?: ObjectType): MixinDefinition;
872
+
873
+ interface ValidationError {
874
+ type: 'error' | 'warning';
875
+ message: string;
876
+ line?: number;
877
+ column?: number;
878
+ suggestion?: string;
879
+ }
880
+ interface ValidationResult {
881
+ valid: boolean;
882
+ errors: ValidationError[];
883
+ warnings: ValidationError[];
884
+ }
885
+ /**
886
+ * Validates templates by running them through the real parser, so it reports
887
+ * exactly the syntax errors that rendering would.
888
+ */
889
+ declare class TemplateValidator {
890
+ private options;
891
+ constructor(options?: CompilerOptions);
892
+ validate(template: string): Promise<ValidationResult>;
893
+ private checkFilters;
894
+ }
895
+ declare function validateTemplate(template: string, options?: CompilerOptions): Promise<ValidationResult>;
896
+
897
+ interface TemplateAnalysis {
898
+ /** Names the template reads from the data it is rendered with */
899
+ variables: string[];
900
+ /** Filters the template applies */
901
+ filters: string[];
902
+ /** Templates it includes, directly or through other includes */
903
+ includes: string[];
904
+ /** Blocks it defines */
905
+ blocks: string[];
906
+ /** Macros it defines */
907
+ macros: string[];
908
+ }
909
+ /**
910
+ * Statically determine what a template needs: the data it reads, the filters
911
+ * it applies and the templates it includes. Included templates are followed
912
+ * through the `loader` option.
913
+ */
914
+ declare function analyzeTemplate(template: string, options?: CompilerOptions): Promise<TemplateAnalysis>;
915
+ /**
916
+ * TypeScript declarations for a module produced by `precompile`: the data
917
+ * the template reads becomes the `TemplateData` interface.
918
+ */
919
+ declare function generateDeclarations({ variables }: Pick<TemplateAnalysis, 'variables'>, { includeRuntime }?: {
920
+ includeRuntime?: boolean | undefined;
921
+ }): string;
922
+
923
+ type FormatOptions = Pick<ParserOptions, 'commentOpen' | 'commentClose' | 'directiveOpen' | 'directiveClose' | 'outputOpen' | 'outputClose'>;
924
+ /**
925
+ * Normalise the tags of a template:
926
+ *
927
+ * {{=name|upper}} -> {{= name | upper }}
928
+ * {{if a eq 1}} -> {{ if a eq 1 }}
929
+ * {{#note#}} -> {{# note #}}
930
+ *
931
+ * Only what is inside tags changes. Text between tags, where whitespace may
932
+ * matter, is kept byte for byte, as are whitespace-control markers. A tag is
933
+ * left exactly as written whenever its expression does not parse or
934
+ * reformatting would not provably keep its meaning. Formatting twice gives
935
+ * the same result as formatting once.
936
+ *
937
+ * Throws a `CompileError` for templates with an unclosed tag.
938
+ */
939
+ declare function formatTemplate(template: string, options?: FormatOptions): string;
940
+
941
+ interface FileLoaderOptions {
942
+ /**
943
+ * Extensions tried, in order, when a path has none.
944
+ * @default ['.janja', '.html']
945
+ */
946
+ extensions?: string[];
947
+ }
948
+ /**
949
+ * A `loader` that reads templates from a directory (Node.js only).
950
+ *
951
+ * Paths are resolved against `root`, with or without an extension, and may
952
+ * not lead outside of it, so that a template cannot include arbitrary files.
953
+ */
954
+ declare function createFileLoader(root: string, { extensions }?: FileLoaderOptions): (name: string) => Promise<string>;
955
+
956
+ interface ErrorRecoveryOptions {
957
+ /**
958
+ * Whether to continue rendering when an error occurs
959
+ */
960
+ continueOnError?: boolean;
961
+ /**
962
+ * Fallback value to use when a variable is undefined
963
+ */
964
+ undefinedFallback?: any;
965
+ /**
966
+ * Whether to ignore missing filters
967
+ */
968
+ ignoreMissingFilters?: boolean;
969
+ /**
970
+ * Custom error handler for rendering errors
971
+ */
972
+ onError?: (error: Error, context: ErrorContext) => any;
973
+ }
974
+ interface ErrorContext {
975
+ template: string;
976
+ data: ObjectType;
977
+ expression?: string;
978
+ filter?: string;
979
+ }
980
+ declare class ErrorRecovery {
981
+ private options;
982
+ constructor(options?: ErrorRecoveryOptions);
983
+ /**
984
+ * Safely evaluate an expression with error recovery
985
+ */
986
+ safeEvaluate(expression: string, data: ObjectType, context?: Partial<ErrorContext>): any;
987
+ /**
988
+ * Safely apply a filter with error recovery
989
+ */
990
+ safeApplyFilter(value: any, filterName: string, filterFn: ((value: any, ...args: any[]) => any) | undefined, args?: any[], context?: Partial<ErrorContext>): any;
991
+ /**
992
+ * Wrap a rendering function with error recovery
993
+ */
994
+ wrapRender<T extends (...args: any[]) => any>(fn: T, context?: Partial<ErrorContext>): T;
995
+ /**
996
+ * Simple expression evaluation (placeholder for actual expression evaluator)
997
+ */
998
+ private evaluateExpression;
999
+ /**
1000
+ * Create a safe data accessor that handles undefined paths
1001
+ */
1002
+ createSafeAccessor(data: ObjectType): (path: string) => any;
1003
+ }
1004
+ /**
1005
+ * Default error handler that logs to console
1006
+ */
1007
+ declare function defaultErrorHandler(error: Error, context: ErrorContext): void;
1008
+ /**
1009
+ * Create error recovery options with defaults
1010
+ */
1011
+ declare function createErrorRecovery(options?: ErrorRecoveryOptions): ErrorRecovery;
1012
+
343
1013
  declare function render(template: string, data: ObjectType, options?: RendererOptions): Promise<string>;
344
1014
  declare function renderFile(filepath: string, data: ObjectType, options?: RendererOptions): Promise<string>;
1015
+ /**
1016
+ * Render a template that was compiled ahead of time by `precompileTemplate`.
1017
+ */
1018
+ declare function renderCompiled(script: Script, data?: ObjectType, options?: RendererOptions): Promise<string>;
1019
+ /**
1020
+ * Render a template as a stream of chunks. See `Renderer.renderStream`.
1021
+ */
1022
+ declare function renderStream(template: string, data?: ObjectType, options?: RendererOptions): ReadableStream<string>;
345
1023
 
346
- export { CompileError, Compiler, ExpCompiler, ExpError, ExpParser, ExpTokenizer, Parser, RenderError, Renderer, RootNode, Safe, TokenType, Tokenizer, Traversal, expTokenTypes, render, renderFile };
347
- export type { BinaryExp, BinaryExpTokenType, BinaryExpType, Checker, CommentToken, CompilerFn, CompilerMap, DirectiveExpression, DirectiveToken, Exp, ExpBase, ExpToken, ExpTokenType, ExpType, Filters, IdExp, IfExp, LitExp, Loc, MaybePromise, NotExp, ObjectType, OutputToken, ParserFn, ParserMap, Plugin, Pos, Primitive, Script, SeqExp, Strip, SyntaxNode, TernaryExpTokenType, TernaryExpType, TextToken, Token, TokenBase, UnaryExpTokenType, UnaryExpType };
1024
+ export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
1025
+ export type { BaseOptions, BinaryExp, BinaryExpTokenType, BinaryExpType, CacheOptions, Checker, CommentToken, CompiledTemplate, CompilerFn, CompilerMap, CompilerOptions, CompositionOptions, DirectiveExpression, DirectiveToken, ErrorContext, ErrorRecoveryOptions, Exp, ExpBase, ExpToken, ExpTokenType, ExpType, FileLoaderOptions, Filter, Filters, FormatOptions, FormatterFn, FormatterMap, FormatterOptions, I18nOptions, IdExp, IfExp, LitExp, Loc, MaybePromise, MixinDefinition, MixinOptions, NotExp, ObjectType, OutputToken, ParserFn, ParserMap, ParserOptions, Plugin, PluralRules, Pos, PrecompileOptions, PrecompileResult, Primitive, RendererOptions, Script, SeqExp, SourceMapOptions, SourceMapV3, Strip, SyntaxNode, TemplateAnalysis, TernaryExpTokenType, TernaryExpType, TextToken, Token, TokenBase, TranslationDict, UnaryExpTokenType, UnaryExpType, ValidationError, ValidationResult, WhitespaceOptions };