|
1 | | -import { format } from "./formatting.ts"; |
2 | | -import { parseTemplateTokens, type Token } from "./parsing.ts"; |
| 1 | +/* |
| 2 | + * Parsing and formatting for templates for config values like 'Hello {{user#tag}}'. |
| 3 | + * |
| 4 | + * The message is split in to "tokens" and validated based on the passed schema. |
| 5 | + * This is a loose usage of the term, but in this case tokens consist of: |
| 6 | + * - Any literal text |
| 7 | + * - Parsed expressions inside {{}} |
| 8 | + * |
| 9 | + * These tokens are then rejoined in the formatting stage, based on the passed parameters. |
| 10 | + */ |
3 | 11 |
|
4 | | -export class Template<P extends Record<string, ParameterType>> { |
5 | | - private _tokens: Token[]; |
| 12 | +import { formatTokens } from "./formatting.ts"; |
| 13 | +import { parseTemplateTokens } from "./parsing.ts"; |
6 | 14 |
|
7 | | - public static parse<P extends Record<string, ParameterType>>(template: string, params: P): Template<P> | string { |
8 | | - const tokens = parseTemplateTokens(template, params); |
| 15 | +/** |
| 16 | + * @returns A function to call to format data with the template, |
| 17 | + * or an error denoting something that went wrong with parsing. |
| 18 | + */ |
| 19 | +export function parseTemplate<S extends TemplateSchema>(template: string, schema: S): ((params: ParameterRecord<S>) => string) | string { |
| 20 | + // just a typed wrapper |
| 21 | + const tokens = parseTemplateTokens(template, schema); |
9 | 22 |
|
10 | | - if (typeof tokens === "string") |
11 | | - return tokens; |
| 23 | + if (typeof tokens === "string") |
| 24 | + return tokens; |
12 | 25 |
|
13 | | - return new Template(tokens); |
14 | | - } |
15 | | - |
16 | | - private constructor(tokens: Token[]) { |
17 | | - this._tokens = tokens; |
18 | | - } |
19 | | - |
20 | | - public format(params: { readonly [K in keyof P]: ParameterValue<P[K]> }): string { |
21 | | - return format(params, this._tokens); |
22 | | - } |
| 26 | + return params => formatTokens(params, tokens); |
23 | 27 | } |
24 | 28 |
|
| 29 | +export type TemplateSchema = Record<string, ParameterType>; |
| 30 | +export type ParameterRecord<S extends Record<string, ParameterType> = any> = { readonly [K in keyof S]: ParameterValue<S[K]> }; |
| 31 | + |
25 | 32 | export const enum FormattingWrapper { |
26 | 33 | BlockQuote, |
27 | 34 | InlineCodeblock, |
@@ -65,8 +72,6 @@ export const enum TimestampPresentationType { |
65 | 72 |
|
66 | 73 | export type UserParameter = { id: string; tag: string; }; |
67 | 74 |
|
68 | | -export type AnyParameterValue = ParameterValue<any>; |
69 | | - |
70 | 75 | type ParameterValue<T extends ParameterType = any> = |
71 | 76 | T extends ParameterType.User ? UserParameter : |
72 | 77 | T extends ParameterType.RawString ? string : |
|
0 commit comments