@promptctl/go-template-js 0.9.0 → 0.12.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/README.md +131 -10
- package/dist/index.d.ts +284 -44
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1306 -519
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ Go template syntax + Sprig subset, generic over output type, in TypeScript.
|
|
|
24
24
|
- [Syntax and built-ins](#syntax-and-built-ins)
|
|
25
25
|
- [Sprig subset](#sprig-subset)
|
|
26
26
|
- [Composing funcs from multiple sources](#composing-funcs-from-multiple-sources)
|
|
27
|
+
- [Rendering a define as a value: `include`](#rendering-a-define-as-a-value-include)
|
|
27
28
|
- [Divergences from Go](#divergences-from-go)
|
|
28
29
|
- [Errors](#errors)
|
|
29
30
|
- [Versioning policy](#versioning-policy)
|
|
@@ -40,6 +41,20 @@ pnpm add @promptctl/go-template-js
|
|
|
40
41
|
|
|
41
42
|
Requires Node **≥ 20.19.0** (per `engines.node`). The package is ESM-only.
|
|
42
43
|
|
|
44
|
+
### If the `@promptctl` scope is unreachable
|
|
45
|
+
|
|
46
|
+
Some internal npm proxies don't serve the `@promptctl` scope, and an ordinary install can't resolve the package. Every GitHub release from v0.9.0 on carries the packed tarball as an asset, byte-identical to the one npm serves for that version — depend on it directly:
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
{
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@promptctl/go-template-js": "https://github.com/promptctl/go-template-js/releases/download/vX.Y.Z/promptctl-go-template-js-X.Y.Z.tgz"
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Substitute a released version for `X.Y.Z` in both places; the [releases page](https://github.com/promptctl/go-template-js/releases) lists them, each with its asset. `@promptctl/rich-js` needs the same treatment if you depend on it — it sits in the same scope, so it won't resolve either: point it at its own release asset, and redirect the transitive `@promptctl/go-template-js` it pulls in to the URL above. The redirect field is `pnpm.overrides` for pnpm, `overrides` for npm, `resolutions` for yarn; pnpm ignores a top-level `overrides` without warning. Don't substitute `github:promptctl/go-template-js#semver:^X.Y.Z` — a git dependency installs the source tree, which carries no `dist/`, so the install exits 0 and the package fails later at import.
|
|
57
|
+
|
|
43
58
|
## Quick start
|
|
44
59
|
|
|
45
60
|
```ts
|
|
@@ -70,10 +85,12 @@ interface Frag { color: string; text: string }
|
|
|
70
85
|
|
|
71
86
|
const engine = createEngine<Frag>({
|
|
72
87
|
fromString: (s) => ({ color: "default", text: s }),
|
|
88
|
+
isT: (v): v is Frag => typeof v === "object" && v !== null && "color" in v,
|
|
73
89
|
funcs: {
|
|
74
90
|
red: {
|
|
75
91
|
fn: (s: unknown) => ({ color: "red", text: String(s) }),
|
|
76
92
|
argTypes: ["string"],
|
|
93
|
+
arity: { kind: "exact" },
|
|
77
94
|
returnType: "T",
|
|
78
95
|
},
|
|
79
96
|
},
|
|
@@ -88,7 +105,9 @@ tpl.evaluate({ label: "warn", value: "ALERT" });
|
|
|
88
105
|
// ]
|
|
89
106
|
```
|
|
90
107
|
|
|
91
|
-
|
|
108
|
+
`isT` tells the engine which values are fragments: an action that yields a T emits it as itself, and an action that yields anything else emits it as Go's `%v` prints it (`map[k:v]`, `[a b]`). It defaults to "is a string", so an engine whose `T` is not a string must declare it, and the `EngineConfig` type requires it.
|
|
109
|
+
|
|
110
|
+
Functions declare `argTypes` and `arity`, both required. The engine uses `argTypes` 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.
|
|
92
111
|
|
|
93
112
|
### Lifting and stringification: the boundary bridges
|
|
94
113
|
|
|
@@ -97,11 +116,12 @@ Functions have optional `argTypes`. The engine uses them to enforce one architec
|
|
|
97
116
|
| Direction | Bridge | ArgType | Where it runs |
|
|
98
117
|
| --- | --- | --- | --- |
|
|
99
118
|
| `string` → `T` | `fromString` (required) | `"liftable"` | a string at a `"liftable"` slot is replaced with `fromString(s)` before the body sees it |
|
|
100
|
-
| `T` → `string` | `toString` (optional) | `"stringifiable"` | a
|
|
119
|
+
| `T` → `string` | `toString` (optional) | `"stringifiable"` | a T at a `"stringifiable"` slot, at any depth, is flattened via `toString` (e.g. `print`, `printf "%s"`); any other value prints as Go's `%v` |
|
|
101
120
|
|
|
102
121
|
```ts
|
|
103
122
|
const engine = createEngine<Frag>({
|
|
104
123
|
fromString: (s) => ({ color: "default", text: s }),
|
|
124
|
+
isT: (v): v is Frag => typeof v === "object" && v !== null && "color" in v,
|
|
105
125
|
toString: (frag) => frag.text,
|
|
106
126
|
});
|
|
107
127
|
```
|
|
@@ -110,6 +130,34 @@ const engine = createEngine<Frag>({
|
|
|
110
130
|
|
|
111
131
|
Use `"liftable"` for any consumer-defined function whose slot should accept either a `T` value or a string literal. The body, by contract, only ever receives `T` — the gate owns the lift, so the body has no string-vs-`T` discrimination to do.
|
|
112
132
|
|
|
133
|
+
### Provenance: `marked`, `emitted` and `decided`
|
|
134
|
+
|
|
135
|
+
Some funcs return values that change on their own, such as an animation's `tween` or a clock. The host then needs to know which output depends on them. A number or a string cannot carry that fact, so the engine carries it beside the value. A func marks its call by returning `marked(value, ...tokens)`. The template sees `value` exactly as if it had been returned directly, and the arity is unchanged. Two optional `EngineConfig` hooks then report each token wherever the output depends on it:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
import { createEngine, marked } from "@promptctl/go-template-js";
|
|
139
|
+
|
|
140
|
+
const engine = createEngine<Frag>({
|
|
141
|
+
fromString: (s) => ({ color: "default", text: s }),
|
|
142
|
+
isT: (v): v is Frag => typeof v === "object" && v !== null && "color" in v,
|
|
143
|
+
funcs: {
|
|
144
|
+
pulse: {
|
|
145
|
+
fn: () => marked(frame.t < 0.5 ? "red" : "blue", { changesAt: 0.5 }),
|
|
146
|
+
argTypes: [],
|
|
147
|
+
arity: { kind: "exact" },
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
// Every emitted T, with the marks it depends on; the return is what is output.
|
|
151
|
+
emitted: (frag, marks) => (marks.size === 0 ? frag : { ...frag, holds: [...marks] }),
|
|
152
|
+
// Every if/with/range pipe, with the marks it read, whichever arm runs.
|
|
153
|
+
decided: (marks) => marks.forEach((m) => host.redrawAt(m)),
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
A mark follows the value into every scope it is bound into: a variable, the dot that `with` and `range` push, the dot a `template` or `block` invocation pushes, and the dot `include` hands its body. Every mark the body reads reaches the result of the `include` call. It then reaches every action that reads any of these. `eq`, `printf`, `default`, sprig maths and every other func pass it through simply by being called on the value. A func that stores anything it was handed, whether in place in an argument (sprig `set` and `unset`) or in a closure or module variable that a later call returns, says so with `writes: true` on its registration. So does a func that runs code it was handed, since that code may store. Where such a write lands is beyond what the engine can follow: an object read later, a fragment already emitted, or your data for the next evaluation. So each call of such a func reports the marks of all its inputs (target and key included, since a marked value can choose where the write goes) through `decided` as it runs. The builtin `call` declares it too, because the function it runs comes from your data and has no registration to say whether it writes. An `if`/`with`/`range` pipe's marks also go to `decided`, including when the arm taken is empty. They also reach every emission inside the arm, and every variable an arm could assign with `=`, whichever arm runs, because that variable's value afterwards depends on the decision. Every report to `decided` also carries the marks of the arms it sits in. The rule is that a mark may be reported early but never late. Tracking is per action, so an emission can carry a mark it did not strictly need. A mark bound somewhere nobody reads, as in `{{ $t := pulse }}still`, is reported nowhere.
|
|
158
|
+
|
|
159
|
+
The engine sees only what flows through arguments and returns, so a store the func does not declare is reported late. Code in your data that runs on a read must not write state the output later reads: getters, Proxy traps, `toJSON` and `toString`. As in Go, a read is a read. Among the builtins, only `call` runs data code as a call; a registered func that does so declares `writes`, as above. An action or control pipe that throws, whether in its pipe, in `fromString`, or in `emitted`, reports what it had read through `decided` before the error propagates, because the error may clear when a mark changes. `marked(...)` must be the func's return value itself. One nested inside a returned object or list is not read where it is returned: there it is opaque, an object with no fields that prints and compares the same at every frame, so the output never varies with it. A func that later returns it on its own, as `index` or `get` does, reads it with its marks, so its value never reaches the output without them. A template operand that is one (`(box).c`) raises an error naming the likely mistake. To build on a marking func from JS, `unmarked(result)` gives back `{ value, marks }` to compute with. Re-mark what you derive from it with `marked(f(value), ...marks)`; a result that drops them reports late. A func whose failure depends on a value that changes throws `marked(error, ...tokens)`, and the throw reports those tokens through `decided`. With neither hook configured, output is unchanged, and so are `referencedCalls()` and the other static facts.
|
|
160
|
+
|
|
113
161
|
## `ArgType` reference
|
|
114
162
|
|
|
115
163
|
Every entry in `argTypes` is one of:
|
|
@@ -117,16 +165,17 @@ Every entry in `argTypes` is one of:
|
|
|
117
165
|
| Kind | Accepts at runtime | Used by (examples) |
|
|
118
166
|
| --- | --- | --- |
|
|
119
167
|
| `"string"` | JS `string` | `upper`, `lower`, `trim`, `printf` format string |
|
|
120
|
-
| `"int"` |
|
|
168
|
+
| `"int"` | safe-integer `number` or safe-integer-range `bigint` — a Go `int` parameter, so a fractional is refused as Go refuses `repeat 2.7 "x"`; gate normalizes to `number` | built-in `slice` indices, `repeat`, `substr`, `trunc`, `until`, `seq`, `chunk`, `splitn`, `round`'s precision |
|
|
169
|
+
| `"truncating-int"` | finite `number` or safe-integer-range `bigint` — the numeric half of sprig's `cast.ToInt64` read of an `interface{}` parameter (the cast's string/bool/nil conversions are refused); gate truncates toward zero (`max 1.5 2.5` → `2`, as in Go) | `add`, `add1`, `sub`, `mul`, `div`, `mod`, `max`, `min`, sprig's list `slice` |
|
|
121
170
|
| `"float"` | any `number` (including `NaN`/`±Infinity` — legitimate IEEE-754 floats) or `bigint` whose `Number()` is finite; gate normalizes to `number` via `Number(v)` | `addf`, `subf`, `mulf`, `divf`, `maxf`, `minf` |
|
|
122
171
|
| `"bool"` | `typeof === "boolean"` | (rare; most boolean slots use `"truthy"`) |
|
|
123
|
-
| `"T"` |
|
|
172
|
+
| `"T"` | A value the engine's `isT` accepts (default: a string) | consumer-defined typed funcs returning `T` |
|
|
124
173
|
| `"ordered"` | `string`, `number`, `bigint`, or `boolean` | `lt`, `le`, `gt`, `ge` — additionally requires both slots share a kind |
|
|
125
174
|
| `"comparable"` | `"ordered"` ∪ nil ∪ arrays / Maps / Sets / plain objects (deep-equal) | `eq`, `ne` |
|
|
126
175
|
| `"list"` | `Array.isArray` | `first`, `last`, `rest`, `uniq`, `concat`, `chunk` |
|
|
127
176
|
| `"dict"` | plain object only (not `Map`, not class instance) | `get`, `keys`, `values`, `pluck`, `merge` |
|
|
128
177
|
| `"sized"` | `string` ∪ array ∪ `Map` ∪ `Set` ∪ plain object | `len` |
|
|
129
|
-
| `"stringifiable"` | `string`,
|
|
178
|
+
| `"stringifiable"` | a value Go's `%v` can print: `string`, nil, a scalar, a T the engine's `toString` flattens, an object with its own `toString`, a class instance (printed as a Go struct, `{alice 30}`), or a list/map of those (a `Set`, a function or a symbol is refused) | `print`, `println`, `printf`, `html`, `js`, `urlquery` |
|
|
130
179
|
| `"liftable"` | `T`, or `string` (lifted to `T` via the engine's `fromString` before the body runs) | consumer-defined funcs that accept either a `T` fragment or a bare text literal at a slot |
|
|
131
180
|
| `"callable"` | `typeof === "function"` | `call` (first slot) |
|
|
132
181
|
| `"collection"` | `string` ∪ array ∪ `Map` ∪ plain object | `index` (receiver slot) |
|
|
@@ -139,11 +188,27 @@ Every entry in `argTypes` is one of:
|
|
|
139
188
|
|
|
140
189
|
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.
|
|
141
190
|
|
|
142
|
-
|
|
191
|
+
A slot naming a kind that is not in this table — a stale `["number" as ArgType]`, or any registration from a JS caller with no compile-time guard — is rejected by `createEngine`, naming the func and the slot. That check is at construct time rather than at the gate on purpose: the kind a slot declares is a fact about the declaration, so it is knowable before a template is ever parsed, and reporting it there means a consumer sees it against the line that wrote it instead of mid-render.
|
|
192
|
+
|
|
193
|
+
### Arity
|
|
194
|
+
|
|
195
|
+
Every registration declares an `arity`, which says how many arguments the func takes and how `argTypes` covers them:
|
|
196
|
+
|
|
197
|
+
| `arity` | Meaning |
|
|
198
|
+
| --- | --- |
|
|
199
|
+
| `{ kind: "exact" }` | Exactly `argTypes.length` arguments; each slot is declared once. |
|
|
200
|
+
| `{ kind: "variadic" }` | At least `argTypes.length - 1` arguments. One slot per Go parameter, the repeating one last, so every excess argument is validated against it. |
|
|
201
|
+
| `{ kind: "alternating", minimum: n }` | At least `n` arguments, with `argTypes` read as a *cycle*: the slot for argument `i` is `argTypes[i % argTypes.length]`. |
|
|
202
|
+
|
|
203
|
+
The gate enforces those counts before the func body runs, and rejects a call it does not accept with an `ArgCountError` carrying the position and a source caret. The message mirrors Go's: `wrong number of args for upper: want 1 got 2` for a fixed-arity signature, `want at least 1 got 0` for a variadic one. The counts themselves are pinned against Go's real signatures by `go-arity.test.ts`, so the gate rejects exactly what Go rejects — note that `add` is `func(i ...interface{})` in sprig, so `{{ add 1 }}` and even `{{ add }}` are legal calls there and here.
|
|
143
204
|
|
|
144
|
-
|
|
205
|
+
A func body therefore never sees a wrong argument count, and never needs to check for one.
|
|
145
206
|
|
|
146
|
-
|
|
207
|
+
Neither `"exact"` nor `"variadic"` carries a count — it *is* `argTypes.length` and `argTypes.length - 1` respectively, and a second copy could only disagree. `minimum` survives on `"alternating"` alone, where `argTypes` is a cycle length rather than a parameter count: `merge` declares `["dict", "dict"]` and requires one, while `dict` declares a two-slot cycle and requires nothing.
|
|
208
|
+
|
|
209
|
+
Alternation is what lets `dict "k1" v1 "k2" v2 …` be checked at the gate: `dict` declares `argTypes: ["string", "value"]` with `{ kind: "alternating", minimum: 0 }`, and the gate enforces "string at even index, anything at odd index" without per-key revalidation in the body.
|
|
210
|
+
|
|
211
|
+
A declared minimum mirrors Go's *arity gate*, which is not always the same as the function body's own requirement. Go's `eq` is `eq(arg1, arg2 ...)`, so its gate wants at least one argument; the familiar "missing argument for comparison" comes from Go's `eq` body and is a different error.
|
|
147
212
|
|
|
148
213
|
## Syntax and built-ins
|
|
149
214
|
|
|
@@ -212,13 +277,63 @@ const engine = createEngine<string>({
|
|
|
212
277
|
|
|
213
278
|
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.
|
|
214
279
|
|
|
280
|
+
## Rendering a define as a value: `include`
|
|
281
|
+
|
|
282
|
+
`{{ template "name" . }}` writes a define's output straight into the result, where nothing can touch it. `include` is Helm's answer: it renders the define and returns the text as a string, so the output can be piped, tested, defaulted or stored like any other value.
|
|
283
|
+
|
|
284
|
+
```gotemplate
|
|
285
|
+
{{ define "user" }}{{ .first }} {{ .last }}{{ end }}
|
|
286
|
+
{{ define "badge" }}{{ if .admin }}admin{{ end }}{{ end }}
|
|
287
|
+
{{ define "list" }}{{ range . }}- {{ . }}
|
|
288
|
+
{{ end }}{{ end }}
|
|
289
|
+
|
|
290
|
+
{{ include "user" .owner | upper }}
|
|
291
|
+
{{ include "list" .items | indent 4 }}
|
|
292
|
+
{{ if include "badge" .owner }}<span>{{ include "badge" .owner }}</span>{{ end }}
|
|
293
|
+
{{ include "badge" .owner | default "guest" }}
|
|
294
|
+
{{ $name := include "user" .owner }}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
Go's `text/template` has no `include`, so it is not a built-in. Register it like a sprig category, under whatever name you like:
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import { createEngine, include, sprigDefaults, sprigStrings } from "@promptctl/go-template-js";
|
|
301
|
+
|
|
302
|
+
const engine = createEngine<string>({
|
|
303
|
+
fromString: (s) => s,
|
|
304
|
+
funcs: { ...sprigStrings(), ...sprigDefaults(), include }, // or { partial: include }
|
|
305
|
+
});
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
It behaves as Helm's `include` does, and the conformance corpus checks it against that implementation in Go (`conformance/fixtures/include-helm-uses`). The one exception is recursion depth: Helm stops a define recursing past 1000 levels, and here the JS host's stack runs out first (see [Divergences from Go](#divergences-from-go)).
|
|
309
|
+
|
|
310
|
+
- The body sees its data argument as both `.` and `$`, never the caller's variables, the same as with `{{ template }}`. With no data to pass, pass `.` or `nil` explicitly.
|
|
311
|
+
- It renders any define it can see, inherited ones included (`engine.parse(src, helpers.defines())`).
|
|
312
|
+
- An undefined name fails at the call with `template "name" is not defined`. An error inside the body fails at the call as `error calling include "name": <what went wrong>`. Its `cause` is the body's own error, with its class and its position in the source that declared the define. A `fail` in the body stays a `FailError`.
|
|
313
|
+
- With a non-string `T`, the body's fragments are flattened through the engine's `toString` and the result is one string. An engine with a non-string `T` and no `toString` fails loudly the first time `include` runs.
|
|
314
|
+
- Provenance carries through: every mark the body read, including those of a decision whose arm emitted nothing, and every mark on the data argument, reach the emission that uses the result.
|
|
315
|
+
|
|
316
|
+
### Rendering a define by name
|
|
317
|
+
|
|
318
|
+
`template.evaluateDefine(name, scope)` renders one define from a parsed template, as Go's `ExecuteTemplate` does. `scope` is the define's `.` and `$`. Inherited defines can be rendered too. The result is the same `T[]` that `evaluate` returns, and it goes through the same `emitted` and `decided` hooks:
|
|
319
|
+
|
|
320
|
+
```ts
|
|
321
|
+
const tpl = engine.parse('{{ define "card" }}[{{ .title }}]{{ end }}');
|
|
322
|
+
tpl.evaluateDefine("card", { title: "hi" }).join(""); // "[hi]"
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
An undefined name is the host's mistake, not the template's: it throws a plain `Error` (not a `TemplateError`) reading `template "name" is not defined`, where Go returns `no template "name" associated with template "..."`. `template.defines().names()` lists, sorted, every name the template can render, inherited ones included. Errors inside the define, a stack overflow included, point into the source that declared it.
|
|
326
|
+
|
|
215
327
|
## Divergences from Go
|
|
216
328
|
|
|
217
329
|
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:
|
|
218
330
|
|
|
219
331
|
- **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)`.
|
|
332
|
+
- **Recursion depth.** Go stops a recursive define at 100000 nested levels. Here the JS host's stack runs out first, a few hundred levels down on Node, depending on the body. The overflow surfaces as one `EvalError` naming the define, `template "name": nesting depth N exceeds the host's stack`, not as a raw stack error.
|
|
220
333
|
- **Regex semantics.** `sprigRegex()` uses ECMAScript regex, not Go's RE2. Lookbehind syntax, Unicode property escapes, and certain catastrophic-backtracking patterns differ.
|
|
221
334
|
- **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.
|
|
335
|
+
- **String slicing.** `trunc`, `substr`, `abbrev`, and `abbrevboth` count code points where Go counts bytes, so the same `n` keeps a different amount of text in each engine: `substr 0 2 "éx"` → `é` in Go, `éx` here. The divergence starts at any two-byte character, not only astral ones, and Go's answer is frequently not valid UTF-8 at all: `trunc 1 "éx"` → the single byte `0xC3` in Go, `é` here; `trunc 1 "𐍈x"` → the single byte `0xF0` in Go, `𐍈` here. Each of those Go results is the first fragment of the character's UTF-8 encoding, and is not a well-formed string on its own. Counting code points is deliberate: it keeps them from splitting a character and returning a lone surrogate.
|
|
336
|
+
- **Width counting.** `wrap` and `wrapWith` measure width in UTF-16 code units where Go measures bytes: `wrap 5 "éé éé"` → `éé\néé` in Go, unwrapped `éé éé` here. `printf`'s width flags diverge on a different axis — Go pads to a rune count and this engine to a UTF-16 unit count, so the two agree on BMP text and differ only on astral: `printf "%-5s|" "𐍈𐍈"` → `𐍈𐍈 |` in Go, `𐍈𐍈 |` here. Neither is converted to code points: they never cut inside a character, so they cannot emit a lone surrogate, and counting runes in `wrap` would move it further from Go's bytes rather than closer.
|
|
222
337
|
- **Field access.** Walks JS objects, Maps, and arrays using JS property semantics, not Go reflection. Named-field access on an array is a missing field — silently `<no value>` under the default `missingKey: "default"` policy, or a `MissingFieldError` under `missingKey: "error"`. There is no `length` / `[N]` magic; use the `index` and `len` built-ins.
|
|
223
338
|
- **`missingkey=zero`.** Accepted as a config value (`missingKey: "zero"`) for API parity with Go's `Option("missingkey=zero")`, but JavaScript erases value-types at runtime — there is no `reflect.New(elemType).Elem()` analogue, so `"zero"` produces the same observable behavior as `"default"` (silent `<no value>`). To force a typed-zero substitute at the use site, use sprig: `{{ .missing | default "" }}`.
|
|
224
339
|
- **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`.
|
|
@@ -236,6 +351,7 @@ Places where users sometimes expect divergence and there isn't one:
|
|
|
236
351
|
- `{{ "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.
|
|
237
352
|
- `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`.
|
|
238
353
|
- 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`.
|
|
354
|
+
- **Splitting by character** matches Go. `split ""`, `splitList ""`, and `trimAll`'s cutset all work in whole characters on both sides, astral input included — pinned by the conformance fixtures `sprig-split-astral-empty-sep`, `sprig-splitlist-astral-empty-sep`, and `sprig-trimall-astral-cutset`. It is the slicing and width-counting functions, noted above, that do diverge.
|
|
239
355
|
- `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.
|
|
240
356
|
|
|
241
357
|
## Errors
|
|
@@ -247,6 +363,7 @@ TemplateError
|
|
|
247
363
|
├── ParseError
|
|
248
364
|
└── EvalError
|
|
249
365
|
├── FuncNotFoundError (with did-you-mean suggestions)
|
|
366
|
+
├── ArgCountError (wrong number of args, Go's own message)
|
|
250
367
|
├── TypeMismatchError (no-silent-flatten violation)
|
|
251
368
|
└── MissingFieldError (named field path failure)
|
|
252
369
|
```
|
|
@@ -265,14 +382,18 @@ Every error carries `pos`, `source`, and a `kind` discriminator. `.toString()` p
|
|
|
265
382
|
|
|
266
383
|
The package exports exactly the following from `"@promptctl/go-template-js"` — anything else is internal and may change at any time:
|
|
267
384
|
|
|
268
|
-
- Engine: `createEngine`, `Engine`, `Template`, `EngineConfig`, `FuncMap`, `TemplateFunc`, `ArgType`, `MissingKeyOption`, `Delims`.
|
|
269
|
-
-
|
|
385
|
+
- Engine: `createEngine`, `Engine`, `Template`, `EngineConfig`, `FuncMap`, `TemplateFunc`, `ArgType`, `Arity`, `MissingKeyOption`, `Delims`.
|
|
386
|
+
- Provenance: `marked`, `unmarked`, `Marked`.
|
|
387
|
+
- Sub-templates: `include`.
|
|
388
|
+
- Errors: `TemplateError`, `ParseError`, `EvalError`, `FuncNotFoundError`, `ArgCountError`, `ArgCount`, `TypeMismatchError`, `MissingFieldError`, `FailError`, `ErrorKind`.
|
|
270
389
|
- Sprig categories: `sprigDefaults`, `sprigStrings`, `sprigMath`, `sprigLists`, `sprigDicts`, `sprigRegex`, `sprigTypes`, `sprigConversions`, `sprigSemver`, `sprigFlow`, `sprigRandom`, `sprigHash`, `sprigDatetime`.
|
|
271
390
|
|
|
272
391
|
Reaching into `dist/` subpaths or `src/` deep imports is unsupported.
|
|
273
392
|
|
|
274
393
|
## Development
|
|
275
394
|
|
|
395
|
+
The toolchain needs Node 22.12+ (vitest 5's range), above the package's 20.19 runtime floor.
|
|
396
|
+
|
|
276
397
|
```bash
|
|
277
398
|
pnpm install
|
|
278
399
|
pnpm build # tsdown → dist/
|