@promptctl/go-template-js 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brandon Fryslie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,230 @@
1
+ # go-template-js
2
+
3
+ Go template syntax + Sprig subset, generic over output type, in TypeScript.
4
+
5
+ - **Same syntax as Go's `text/template`** — templates that parse there parse here.
6
+ - **Generic over the output type** — render to strings, structured fragments, or anything else.
7
+ - **No silent flattening** — typed values never become strings without an explicit conversion.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add go-template-js
13
+ ```
14
+
15
+ ## Quickstart (string output)
16
+
17
+ ```ts
18
+ import { createEngine } from "go-template-js";
19
+
20
+ const engine = createEngine<string>({ fromString: (s) => s });
21
+ const tpl = engine.parse("Hello, {{ .name }}!");
22
+ console.log(tpl.evaluate({ name: "world" }).join("")); // "Hello, world!"
23
+ ```
24
+
25
+ `fromString` is the engine's bridge from text literals to its output type `T`. With `T = string` it's the identity function — that recovers Go template's default behaviour.
26
+
27
+ `engine.compile(src)` is the parse-and-evaluate sugar:
28
+
29
+ ```ts
30
+ const greet = engine.compile("hi {{ .name }}");
31
+ greet({ name: "ada" }).join(""); // "hi ada"
32
+ ```
33
+
34
+ ## Generic-T tutorial
35
+
36
+ The engine is parameterised over its output fragment type `T`. Consumers pick a fragment shape (e.g. styled text, AST nodes, layout primitives) and the engine emits a `T[]` that integrates into their downstream pipeline:
37
+
38
+ ```ts
39
+ import { createEngine, type TemplateFunc } from "go-template-js";
40
+
41
+ interface Frag { color: string; text: string }
42
+
43
+ const engine = createEngine<Frag>({
44
+ fromString: (s) => ({ color: "default", text: s }),
45
+ funcs: {
46
+ red: {
47
+ fn: (s: unknown) => ({ color: "red", text: String(s) }),
48
+ argTypes: ["string"],
49
+ returnType: "T",
50
+ },
51
+ },
52
+ });
53
+
54
+ const tpl = engine.parse('{{ .label }}: {{ red .value }}');
55
+ tpl.evaluate({ label: "warn", value: "ALERT" });
56
+ // → [
57
+ // { color: "default", text: "warn" },
58
+ // { color: "default", text: ": " },
59
+ // { color: "red", text: "ALERT" },
60
+ // ]
61
+ ```
62
+
63
+ Functions have optional `argTypes`. The engine uses them to enforce one architectural commitment: **a non-string `T` value will never silently flatten into a `string` parameter**. If you try to pipe a styled fragment into a function declared with `argTypes: ["string"]`, you get a `TypeMismatchError` naming the function, the argument index, and a suggestion to call your `unstyled` (or equivalent) flatten helper.
64
+
65
+ ### Stringification: the `toString` mirror of `fromString`
66
+
67
+ If your `T` is not `string`, the engine needs a way to flatten typed-T values back to plain text when they reach a `"stringifiable"` slot (`print`, `println`, `printf "%s"` and `"%q"`). Supply it via `toString`:
68
+
69
+ ```ts
70
+ const engine = createEngine<Frag>({
71
+ fromString: (s) => ({ color: "default", text: s }),
72
+ toString: (frag) => frag.text,
73
+ });
74
+ ```
75
+
76
+ Without it, typed-T values reaching a `"stringifiable"` slot throw `TypeMismatchError` directing you to configure `toString`. The default `toString` passes strings through unchanged and flattens numeric/boolean/nil primitives, so `T = string` engines work out of the box.
77
+
78
+ ### `ArgType` reference
79
+
80
+ Every entry in `argTypes` is one of:
81
+
82
+ | Kind | Accepts at runtime | Used by (examples) |
83
+ | --- | --- | --- |
84
+ | `"string"` | JS `string` | `upper`, `lower`, `trim`, `printf` format string |
85
+ | `"number"` | `typeof === "number"` or `bigint` (interchangeable) | `add`, `sub`, `mul`, `mod` |
86
+ | `"bool"` | `typeof === "boolean"` | (rare; most boolean slots use `"truthy"`) |
87
+ | `"T"` | Any non-primitive (consumer-defined fragment) | consumer-defined typed funcs returning `T` |
88
+ | `"ordered"` | `string`, `number`, `bigint`, or `boolean` | `lt`, `le`, `gt`, `ge` — additionally requires both slots share a kind |
89
+ | `"comparable"` | `"ordered"` ∪ nil ∪ arrays / Maps / Sets / plain objects (deep-equal) | `eq`, `ne` |
90
+ | `"list"` | `Array.isArray` | `first`, `last`, `rest`, `uniq`, `concat`, `chunk` |
91
+ | `"dict"` | plain object only (not `Map`, not class instance) | `get`, `keys`, `values`, `pluck`, `merge` |
92
+ | `"sized"` | `string` ∪ array ∪ `Map` ∪ `Set` ∪ plain object | `len` |
93
+ | `"stringifiable"` | `string`, or any value the engine's `toString` can flatten | `print`, `println`, `printf "%s"`, `printf "%q"` |
94
+ | `"callable"` | `typeof === "function"` | `call` (first slot) |
95
+ | `"collection"` | `string` ∪ array ∪ `Map` ∪ plain object | `index` (receiver slot) |
96
+ | `"index-key"` | `string`, `number`, or `bigint` | `index` (key slots) |
97
+ | `"sliceable"` | `string` or array | `slice` (receiver slot) |
98
+ | `"truthy"` | anything (truthiness context) | `not`, `and`, `or`, `default`, `empty`, `coalesce`, `ternary` |
99
+ | `"reflective"` | anything (type-inspection context) | `kindOf`, `typeOf`, `kindIs`, `typeIs`, `typeIsLike` |
100
+ | `"serializable"` | anything `JSON.stringify`-encodable (rejects functions, symbols, `bigint`) | `toJson`, `toPrettyJson` |
101
+ | `"value"` | anything (genuinely heterogeneous, by intent) | `list` constructor, `deepEqual`, `deepCopy`, `prepend` / `append` items |
102
+
103
+ The legacy `"any"` kind was removed in epic `template-laws-3gt`. Slots that genuinely accept anything now declare their *intent* (`"truthy"` / `"reflective"` / `"value"` / `"serializable"`); slots that did not are pinned to their precise kind so the gate enforces the constraint instead of leaking it into func bodies.
104
+
105
+ #### Variadic patterns
106
+
107
+ For variadic funcs, declare the trailing slot's type once — every excess argument is validated against it.
108
+
109
+ For funcs whose variadic tail *cycles* (e.g. `dict "k1" v1 "k2" v2 …`), set `argTypePattern: "alternating"` on the registration. The slot for arg index `i` becomes `argTypes[i % argTypes.length]`, so `dict` declares `argTypes: ["string", "value"]` and the gate enforces "string at even index, anything at odd index" without per-key revalidation in the body.
110
+
111
+ ## Syntax reference
112
+
113
+ Template syntax is Go template syntax. Read the canonical spec:
114
+ https://pkg.go.dev/text/template
115
+
116
+ Supported:
117
+
118
+ - All actions: `{{ pipeline }}`, `{{- ... -}}` trim markers, `{{/* comments */}}`.
119
+ - All control flow: `if/else if/else/end`, `range/else/end` (with index/value forms `range $i, $v := …`), `with/else/end`.
120
+ - All sub-template forms: `define`, `template`, `block`.
121
+ - Variable assignment: `$x := pipe` and `$x = pipe`.
122
+ - All literals: strings (interpreted + raw backtick), runes, integers (decimal/hex/octal/binary), floats (with exponents and hex-float `p` exponents), booleans, `nil`.
123
+ - Field access on JS objects (own + prototype properties), `Map` (via `.get`), arrays (numeric `index` builtin).
124
+ - Pipelines with last-arg piping: `x | f a b` ≡ `f a b x`.
125
+
126
+ ### Built-in functions
127
+
128
+ All of Go template's runtime built-ins:
129
+
130
+ `and` `or` `not` · `eq` `ne` `lt` `le` `gt` `ge` · `len` `index` `slice` · `print` `println` `printf` · `call`
131
+
132
+ `and`/`or` short-circuit (the engine passes thunks for those). `printf` supports `%s`, `%d`, `%v`, `%q`, `%f` (precision-aware), `%t`, `%x`, plus width and `-` left-align flags.
133
+
134
+ ### Sprig subset
135
+
136
+ Imported from `go-template-js` as category-scoped `FuncMap` factories:
137
+
138
+ | Category | Helper | Functions |
139
+ | --- | --- | --- |
140
+ | Defaults | `sprigDefaults()` | default, empty, coalesce, ternary, fromJson, toJson, toPrettyJson |
141
+ | Strings | `sprigStrings()` | trim, trimAll, trimPrefix, trimSuffix, upper, lower, title, untitle, repeat, substr, trunc, contains, hasPrefix, hasSuffix, replace, split, splitList, splitn, join, quote, squote, cat, indent, nindent, wrap, wrapWith, abbrev, abbrevboth, initials, nospace, snakecase, camelcase, kebabcase, swapcase, plural, regexQuoteMeta |
142
+ | Math | `sprigMath()` | add, sub, mul, div, mod, min, max, floor, ceil, round, addf, subf, mulf, divf |
143
+ | Lists | `sprigLists()` | list, first, last, rest, initial, len, reverse, uniq, without, has, compact, slice, concat, chunk, prepend, append |
144
+ | Dicts | `sprigDicts()` | dict, get, set, unset, keys, values, pluck, pick, omit, hasKey, merge, mergeOverwrite |
145
+ | Regex | `sprigRegex()` | regexMatch, regexFind, regexFindAll, regexReplaceAll, regexReplaceAllLiteral, regexSplit |
146
+ | Types | `sprigTypes()` | kindOf, kindIs, typeOf, typeIs, typeIsLike, deepEqual, deepCopy |
147
+ | Conversions | `sprigConversions()` | atoi, int, int64, float64, toString, toStrings, toDecimal, toRawJson |
148
+
149
+ ## Composing funcs from multiple sources
150
+
151
+ The `funcs` registry merges from any number of sources, with later entries overriding earlier on name collision:
152
+
153
+ ```ts
154
+ const engine = createEngine<string>({
155
+ fromString: (s) => s,
156
+ funcs: {
157
+ ...sprigDefaults(),
158
+ ...sprigStrings(),
159
+ ...projectFuncs, // your own, can override sprig if needed
160
+ },
161
+ });
162
+ ```
163
+
164
+ Go template's runtime built-ins (the names listed under "Built-in functions" above) are always merged in by `createEngine` itself; you do not register them. A consumer-supplied entry with the same name overrides the built-in.
165
+
166
+ ## Divergences from Go
167
+
168
+ The engine matches Go's `text/template` semantics aggressively. The remaining divergences are host-imposed — JavaScript cannot represent the relevant Go type, or the standard libraries differ:
169
+
170
+ - **Numeric typing.** Go has `int`, `float64`, and friends as distinct runtime types; JavaScript has one `number`. The numeric-verb type label reflects JS's view: integer JS numbers report as `int`, fractional as `float64`, `bigint` as `int64`. Non-numeric values into `%d`/`%f`/`%x` produce a Go-style `%!<verb>(<type>=<value>)` diagnostic — e.g. `printf "%d" "foo"` → `%!d(string=foo)`.
171
+ - **Regex semantics.** `sprigRegex()` uses ECMAScript regex, not Go's RE2. Lookbehind syntax, Unicode property escapes, and certain catastrophic-backtracking patterns differ.
172
+ - **String length.** Go strings are UTF-8 byte sequences; `len("é")` is `2` in Go. JS strings are UTF-16 code units; `len("é")` is `1` here. Choose grapheme libraries on the JS side if you need byte/grapheme counts.
173
+ - **Field access.** Walks JS objects, Maps, and arrays using JS property semantics, not Go reflection. Named-field access on an array is a `MissingFieldError` (no `length` / `[N]` magic — use the `index` and `len` built-ins).
174
+ - **Type mismatches at function boundaries are runtime errors, not compile errors.** By design: the engine does not know your `T` shape statically, so it surfaces the architectural commitment when the bad flow happens. See `TypeMismatchError`.
175
+ - **printf verbs** beyond `%s %d %v %q %f %t %x` are rendered as `%!<verb>(<type>=<value>)`. If you need more, register your own formatter via the `funcs` registry.
176
+
177
+ Notable parity statements (places where users sometimes expect divergence and there isn't one):
178
+
179
+ - A nil/undefined pipeline emits the literal `<no value>` string, matching Go's `text/template`.
180
+ - Range over a Map / plain object iterates in **sorted-by-key order** in both engines (Go's `internal/fmtsort`; ours mirrors it).
181
+ - Sprig `set` and `unset` mutate the receiver and return it — same as Go sprig.
182
+ - `{{ "key" | get .dict }}` composes correctly: last-arg piping puts the key in the trailing slot, which is `get(d, key)`'s second parameter. The form `{{ .dict | get "key" }}` does *not* work in either engine — the dict ends up in the key slot.
183
+ - `eq` / `ne` compare arrays, Maps, Sets, and plain objects by **structural deep-equal**, matching Go's `text/template` semantics. Reference-identity comparison is not a divergence — it was a bug fixed in epic `template-laws-3gt`.
184
+ - Sprig dict ops (`get`, `keys`, `values`, `pluck`, `hasKey`, …) accept **plain objects only**, not `Map`. Pass `Object.fromEntries(map)` if you have a `Map` to feed in. Maps remain valid for field-access (`.get(key)`) and for `range`.
185
+ - `empty` on a non-empty object returns **false**, even when every value is the zero value of its type (e.g. `{tag: "", text: ""}`). Matches Go sprig: `text/template.isTrue` treats structs as always truthy, and sprig's `empty` follows by returning `false` for any non-empty map or struct. `reflect.IsZero` is *not* what Go sprig consults here. The conformance fixture `sprig-empty-object-parity` pins this behavior byte-for-byte.
186
+
187
+ ## Errors
188
+
189
+ All errors extend `TemplateError`:
190
+
191
+ ```
192
+ TemplateError
193
+ ├── ParseError
194
+ └── EvalError
195
+ ├── FuncNotFoundError (with did-you-mean suggestions)
196
+ ├── TypeMismatchError (no-silent-flatten violation)
197
+ └── MissingFieldError (named field path failure)
198
+ ```
199
+
200
+ Every error carries `pos`, `source`, and a `kind` discriminator. `.toString()` produces a multi-line message with a 3-line source snippet and a caret pointing at the failing column.
201
+
202
+ ## Versioning policy
203
+
204
+ - Semver.
205
+ - **Syntax stability is a hard guarantee** — Go template syntax is the source of truth; deviations are bugs.
206
+ - **Output type guarantee** — `engine.evaluate(scope)` returning `T[]` for the engine's `T` parameter is part of the contract.
207
+ - **Sprig surface may grow but never shrinks** — once a sprig function is registered in a release, subsequent releases keep it.
208
+ - **Built-in semantics may be tightened** — the no-silent-flatten guard may catch additional edge cases over time. Tests against an Engine with strict argTypes are the safe bet.
209
+
210
+ ### Stable public API surface
211
+
212
+ The package exports exactly the following from `"go-template-js"` — anything else is internal and may change at any time:
213
+
214
+ - Engine: `createEngine`, `Engine`, `Template`, `EngineConfig`, `FuncMap`, `TemplateFunc`, `ArgType`.
215
+ - Errors: `TemplateError`, `ParseError`, `EvalError`, `FuncNotFoundError`, `TypeMismatchError`, `MissingFieldError`, `ErrorKind`.
216
+ - Sprig categories: `sprigDefaults`, `sprigStrings`, `sprigMath`, `sprigLists`, `sprigDicts`, `sprigRegex`, `sprigTypes`, `sprigConversions`.
217
+
218
+ Reaching into `dist/` subpaths or `src/` deep imports is unsupported.
219
+
220
+ ## Development
221
+
222
+ ```bash
223
+ pnpm install
224
+ pnpm build # tsdown → dist/
225
+ pnpm test # vitest
226
+ pnpm lint # biome check
227
+ pnpm typecheck # tsc --noEmit
228
+ ```
229
+
230
+ The roadmap and active work live in the project's `lit` issue tracker (run `lit ready` to see the queue).
@@ -0,0 +1,285 @@
1
+ //#region src/parser/pos.d.ts
2
+ /**
3
+ * Source position for AST nodes.
4
+ *
5
+ * `line` and `column` are 1-indexed for human-readable error reporting.
6
+ * `offset` is a 0-indexed byte offset into the source string for snippet
7
+ * extraction and machine-precise spans.
8
+ *
9
+ * [LAW:one-source-of-truth] All AST nodes carry the same Pos shape — there
10
+ * is exactly one canonical position type, never per-node ad-hoc shapes.
11
+ */
12
+ interface Pos {
13
+ readonly line: number;
14
+ readonly column: number;
15
+ readonly offset: number;
16
+ }
17
+ //#endregion
18
+ //#region src/errors.d.ts
19
+ type ErrorKind = "ParseError" | "EvalError" | "FuncNotFoundError" | "TypeMismatchError" | "MissingFieldError";
20
+ interface TemplateErrorContext {
21
+ readonly source?: string | undefined;
22
+ }
23
+ declare class TemplateError extends Error {
24
+ readonly name: string;
25
+ readonly kind: ErrorKind;
26
+ readonly pos: Pos;
27
+ readonly source: string | undefined;
28
+ constructor(message: string, pos: Pos, ctx?: TemplateErrorContext);
29
+ /** 3-line excerpt of the source around the error with caret. */
30
+ get sourceSnippet(): string;
31
+ toString(): string;
32
+ }
33
+ interface ParseErrorContext extends TemplateErrorContext {
34
+ readonly expected?: string;
35
+ readonly found?: string;
36
+ }
37
+ declare class ParseError extends TemplateError {
38
+ readonly name = "ParseError";
39
+ readonly kind: ErrorKind;
40
+ readonly expected: string | undefined;
41
+ readonly found: string | undefined;
42
+ constructor(message: string, pos: Pos, ctx?: ParseErrorContext);
43
+ }
44
+ declare class EvalError extends TemplateError {
45
+ readonly name: string;
46
+ readonly kind: ErrorKind;
47
+ }
48
+ /**
49
+ * Thrown when a template references a function the engine's FuncMap
50
+ * has no entry for. Includes a list of nearest-matching registered
51
+ * names by edit distance — most useful when the failure is a typo.
52
+ */
53
+ declare class FuncNotFoundError extends EvalError {
54
+ readonly name = "FuncNotFoundError";
55
+ readonly kind: ErrorKind;
56
+ readonly funcName: string;
57
+ readonly suggestions: readonly string[];
58
+ constructor(funcName: string, pos: Pos, ctx?: TemplateErrorContext & {
59
+ available?: readonly string[];
60
+ });
61
+ }
62
+ declare class TypeMismatchError extends EvalError {
63
+ readonly name = "TypeMismatchError";
64
+ readonly kind: ErrorKind;
65
+ readonly funcName: string;
66
+ /** 1-based argument index for human-readable messages. */
67
+ readonly argIndex: number;
68
+ readonly expected: string;
69
+ readonly receivedSummary: string;
70
+ constructor(funcName: string, argIndex: number, expected: string, receivedSummary: string, pos: Pos, ctx?: TemplateErrorContext);
71
+ }
72
+ declare class MissingFieldError extends EvalError {
73
+ readonly name = "MissingFieldError";
74
+ readonly kind: ErrorKind;
75
+ readonly path: readonly string[];
76
+ constructor(path: readonly string[], pos: Pos, ctx?: TemplateErrorContext);
77
+ }
78
+ //#endregion
79
+ //#region src/evaluator/evaluator.d.ts
80
+ /**
81
+ * Declared parameter type for a registered template function. Used by
82
+ * the no-silent-flatten guard to detect unsafe T-into-string flows.
83
+ *
84
+ * - "string" — must be a JS string. Non-string values raise
85
+ * TypeMismatchError. This is the **architectural commitment**: T
86
+ * never silently flattens into a string parameter.
87
+ * - "number" — must be `typeof "number"` or `bigint`.
88
+ * - "bool" — must be `typeof "boolean"`.
89
+ * - "T" — opaque caller-defined T; treated as "anything that is
90
+ * not a string". The guard does no further checking.
91
+ * - "ordered" — orderable primitive (string, number, bigint, boolean).
92
+ * When two or more "ordered" slots appear in the same call, all of
93
+ * them must share a kind, with `number` and `bigint` bridged. Used
94
+ * by `lt`/`le`/`gt`/`ge` to match Go's `text/template` rule that
95
+ * ordering operands have the same type.
96
+ *
97
+ * Precise kinds (added template-laws-3gt.1, consumed in .2–.7):
98
+ * - "list" — array. Excludes string (Go-parity: string is not a list).
99
+ * - "dict" — plain object (not Map; Maps are handled separately).
100
+ * - "sized" — has a meaningful `len`: string | array | Map | Set | object.
101
+ * - "comparable" — accepted by `eq`/`ne`: any JSON-shaped value
102
+ * (ordered primitive, nil, array, plain object, Map, or Set).
103
+ * Functions and symbols are excluded. When two or more "comparable"
104
+ * slots appear in the same call, all of them must share a kind, with
105
+ * `number`↔`bigint` bridged and `nil` acting as a wildcard. Object
106
+ * equality routes through `deepEqual` in `eq`/`ne` bodies.
107
+ * - "stringifiable" — string directly OR a value the engine's
108
+ * `toString` can flatten. The matcher *probes* the conversion;
109
+ * downstream func bodies call `engine.toString` to actually flatten.
110
+ * - "callable" — `typeof v === "function"`.
111
+ * - "collection" — string | array | Map | plain object. The receiver
112
+ * shape `index` accepts. Sets and primitives are rejected. Nil is
113
+ * rejected by the gate; the body trusts a non-nil collection.
114
+ * (Added template-laws-3gt.7 alongside the index migration.)
115
+ * - "index-key" — string | number | bigint. The key shape `index`
116
+ * accepts. The body decides which collection kind a given key fits
117
+ * (arrays want integer; objects want string).
118
+ * - "sliceable" — string | array. Receiver shape for `slice`. Folded
119
+ * into template-laws-3gt.8 alongside the intent-named migration so
120
+ * .9 could delete `"any"` from the union.
121
+ *
122
+ * Intent-named kinds (added template-laws-3gt.1, consumed in .8) —
123
+ * the labels carry intent for readers; runtime behavior is documented
124
+ * pass-through except where noted:
125
+ * - "truthy" — anything (truthiness context).
126
+ * - "reflective" — anything (type-inspection context).
127
+ * - "value" — anything (genuinely heterogeneous: constructors,
128
+ * structural ops). Documents intent.
129
+ * - "serializable" — anything JSON-encodable. Runtime-validated:
130
+ * functions, symbols, and circular refs fail the gate.
131
+ *
132
+ * [LAW:make-it-impossible] `"any"` is intentionally absent from this
133
+ * union. Every slot must engage with the type system. If a slot is
134
+ * genuinely heterogeneous, use the kind that documents the reason
135
+ * (`"truthy"`, `"reflective"`, `"serializable"`, `"value"`,
136
+ * `"callable"`). The history for this decision lives in epic
137
+ * template-laws-3gt.
138
+ */
139
+ type ArgType = "string" | "number" | "bool" | "T" | "ordered" | "list" | "dict" | "sized" | "comparable" | "stringifiable" | "callable" | "collection" | "index-key" | "sliceable" | "truthy" | "reflective" | "value" | "serializable";
140
+ interface TemplateFunc {
141
+ /**
142
+ * The function body. Parameter types are *contravariant-bottom*
143
+ * (`never[]`) so any concrete signature is assignable here — write
144
+ * `fn: (s: string, n: number) => …` if that's what the func wants,
145
+ * and rely on `argTypes` + `enforceArgTypes` to validate at runtime.
146
+ *
147
+ * [LAW:single-enforcer] Param-type validation lives at the dispatch
148
+ * site (`enforceArgTypes`). The compile-time signature does not
149
+ * duplicate that gate — it stays out of the way so consumer
150
+ * implementations can declare the precise types they expect.
151
+ */
152
+ readonly fn: (...args: never[]) => unknown;
153
+ /**
154
+ * Declared positional parameter types. Required.
155
+ *
156
+ * For variadic funcs, declare the type of the trailing parameter
157
+ * once — the no-silent-flatten guard validates every excess argument
158
+ * against `argTypes[argTypes.length - 1]`. This matches Go's
159
+ * `text/template` validation against repeated parameter types when
160
+ * `Variadic`.
161
+ *
162
+ * The pipe-fed last argument is appended to the positional list
163
+ * before validation, so it is checked against the trailing slot.
164
+ */
165
+ readonly argTypes: readonly ArgType[];
166
+ readonly returnType?: ArgType;
167
+ /**
168
+ * Variadic-position lookup pattern.
169
+ *
170
+ * Default (omitted): the trailing slot repeats. `["string", "value"]`
171
+ * means "first arg string, every arg after is value (heterogeneous)".
172
+ *
173
+ * `"alternating"`: `argTypes` describes a *cycle*. The slot for arg
174
+ * index `i` is `argTypes[i % argTypes.length]`. Used by `dict`'s
175
+ * `string, value, string, value, …` kv pairing — without this the
176
+ * gate cannot distinguish even-index keys (must be string) from
177
+ * odd-index values (anything), and the body would re-validate per
178
+ * key, splitting `[LAW:single-enforcer]` across two layers.
179
+ *
180
+ * Added by template-laws-3gt.3.
181
+ */
182
+ readonly argTypePattern?: "alternating";
183
+ }
184
+ type FuncMap = Record<string, TemplateFunc>;
185
+ interface EngineConfig<T> {
186
+ /** Convert a text literal (or string-returning function result) into T. */
187
+ readonly fromString: (s: string) => T;
188
+ /**
189
+ * Flatten a T (or other engine-managed value) into a string.
190
+ *
191
+ * [LAW:single-enforcer] Dual of `fromString`: one place owns the
192
+ * string→T direction, this owns the T→string direction. Built-ins
193
+ * registered against the `"stringifiable"` ArgType call this when
194
+ * they need to format a non-string value (the matcher probes via
195
+ * `toString` to validate; the body re-uses it to flatten).
196
+ *
197
+ * Default behaviour: passes through any value that is already a
198
+ * `typeof "string"` and throws `TypeMismatchError` for everything
199
+ * else. That makes the `T = string` case (consumer set
200
+ * `fromString: (s) => s`) work out of the box, while a non-string T
201
+ * configured without a `toString` errors loudly the first time a
202
+ * `"stringifiable"` slot encounters a T value — never silently.
203
+ */
204
+ readonly toString?: (value: T) => string;
205
+ /** Optional registry of named functions usable in pipelines. */
206
+ readonly funcs?: FuncMap;
207
+ }
208
+ declare class Template<T> {
209
+ readonly source: string;
210
+ private readonly _evaluate;
211
+ private constructor();
212
+ evaluate(scope: unknown): T[];
213
+ }
214
+ declare class Engine<T> {
215
+ private readonly fromString;
216
+ private readonly toString;
217
+ private readonly funcs;
218
+ constructor(config: EngineConfig<T>);
219
+ /**
220
+ * Parse a template source into a reusable Template handle.
221
+ *
222
+ * The returned Template is immutable; calling `evaluate(scope)` on
223
+ * it any number of times with different scopes is safe and avoids
224
+ * re-parsing.
225
+ */
226
+ parse(source: string): Template<T>;
227
+ /**
228
+ * Convenience sugar for `parse(src).evaluate.bind(template)`.
229
+ *
230
+ * Returns a closure that takes a scope and produces T[]. Useful when
231
+ * the template is parsed once at module load and called many times.
232
+ */
233
+ compile(source: string): (scope: unknown) => T[];
234
+ /**
235
+ * Evaluate a parsed template against a scope value, producing T[].
236
+ *
237
+ * Accepts only Templates produced by `engine.parse(src)` so the
238
+ * public type surface stays clear of internal AST shapes.
239
+ */
240
+ evaluate(template: Template<T>, scope: unknown): T[];
241
+ private evalParsed;
242
+ private evalList;
243
+ private evalNode;
244
+ private evalIf;
245
+ private evalWith;
246
+ private evalRange;
247
+ private evalTemplateInvoke;
248
+ private evalBlock;
249
+ private evalAction;
250
+ private evalPipe;
251
+ private evalPipeWithoutDecls;
252
+ private evalCommand;
253
+ private evalPrimary;
254
+ private resolveFieldChain;
255
+ private resolveVariable;
256
+ private emitFromValue;
257
+ }
258
+ declare function createEngine<T>(config: EngineConfig<T>): Engine<T>;
259
+ //#endregion
260
+ //#region src/sprig/conversions/index.d.ts
261
+ declare function sprigConversions(): FuncMap;
262
+ //#endregion
263
+ //#region src/sprig/defaults/index.d.ts
264
+ declare function sprigDefaults(): FuncMap;
265
+ //#endregion
266
+ //#region src/sprig/dicts/index.d.ts
267
+ declare function sprigDicts(): FuncMap;
268
+ //#endregion
269
+ //#region src/sprig/lists/index.d.ts
270
+ declare function sprigLists(): FuncMap;
271
+ //#endregion
272
+ //#region src/sprig/math/index.d.ts
273
+ declare function sprigMath(): FuncMap;
274
+ //#endregion
275
+ //#region src/sprig/regex/index.d.ts
276
+ declare function sprigRegex(): FuncMap;
277
+ //#endregion
278
+ //#region src/sprig/strings/index.d.ts
279
+ declare function sprigStrings(): FuncMap;
280
+ //#endregion
281
+ //#region src/sprig/types/index.d.ts
282
+ declare function sprigTypes(): FuncMap;
283
+ //#endregion
284
+ export { type ArgType, Engine, type EngineConfig, type ErrorKind, EvalError, type FuncMap, FuncNotFoundError, MissingFieldError, ParseError, Template, TemplateError, type TemplateFunc, TypeMismatchError, createEngine, sprigConversions, sprigDefaults, sprigDicts, sprigLists, sprigMath, sprigRegex, sprigStrings, sprigTypes };
285
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/parser/pos.ts","../src/errors.ts","../src/evaluator/evaluator.ts","../src/sprig/conversions/index.ts","../src/sprig/defaults/index.ts","../src/sprig/dicts/index.ts","../src/sprig/lists/index.ts","../src/sprig/math/index.ts","../src/sprig/regex/index.ts","../src/sprig/strings/index.ts","../src/sprig/types/index.ts"],"mappings":";;AAUA;;;;;;;;;UAAiB,GAAA;EAAA,SACN,IAAA;EAAA,SACA,MAAA;EAAA,SACA,MAAA;AAAA;;;KCSC,SAAA;AAAA,UAOK,oBAAA;EAAA,SACN,MAAA;AAAA;AAAA,cAOE,aAAA,SAAsB,KAAA;EAAA,SACf,IAAA;EAAA,SACT,IAAA,EAAM,SAAA;EAAA,SACN,GAAA,EAAK,GAAA;EAAA,SACL,MAAA;cAEG,OAAA,UAAiB,GAAA,EAAK,GAAA,EAAK,GAAA,GAAK,oBAAA;EANX;EAAA,IAa7B,aAAA,CAAA;EAIK,QAAA,CAAA;AAAA;AAAA,UAWM,iBAAA,SAA0B,oBAAA;EAAA,SAChC,QAAA;EAAA,SACA,KAAA;AAAA;AAAA,cAGE,UAAA,SAAmB,aAAA;EAAA,SACZ,IAAA;EAAA,SACA,IAAA,EAAM,SAAA;EAAA,SACf,QAAA;EAAA,SACA,KAAA;cAEG,OAAA,UAAiB,GAAA,EAAK,GAAA,EAAK,GAAA,GAAK,iBAAA;AAAA;AAAA,cAWjC,SAAA,SAAkB,aAAA;EAAA,SACX,IAAA;EAAA,SACA,IAAA,EAAM,SAAA;AAAA;;AAxB1B;;;;cAgCa,iBAAA,SAA0B,SAAA;EAAA,SACnB,IAAA;EAAA,SACA,IAAA,EAAM,SAAA;EAAA,SACf,QAAA;EAAA,SACA,WAAA;cAGP,QAAA,UACA,GAAA,EAAK,GAAA,EACL,GAAA,GAAK,oBAAA;IAAyB,SAAA;EAAA;AAAA;AAAA,cAUrB,iBAAA,SAA0B,SAAA;EAAA,SACnB,IAAA;EAAA,SACA,IAAA,EAAM,SAAA;EAAA,SACf,QAAA;EAjDkC;EAAA,SAmDlC,QAAA;EAAA,SACA,QAAA;EAAA,SACA,eAAA;cAGP,QAAA,UACA,QAAA,UACA,QA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