@promptctl/go-template-js 0.1.0 → 0.3.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.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { sha1 } from "@noble/hashes/legacy.js";
2
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
3
+ import { sha256, sha512 } from "@noble/hashes/sha2.js";
1
4
  //#region src/errors.ts
2
5
  var TemplateError = class extends Error {
3
6
  name = "TemplateError";
@@ -77,6 +80,26 @@ var MissingFieldError = class extends EvalError {
77
80
  this.path = path;
78
81
  }
79
82
  };
83
+ /**
84
+ * Thrown when a template calls `fail "message"`. Consumers can catch
85
+ * this specifically to distinguish intentional template failures from
86
+ * engine bugs. The message comes from the template author.
87
+ *
88
+ * [LAW:single-enforcer] One class, one place. The `fail` sprig function
89
+ * is the only producer; catch `FailError` to handle it distinctly from
90
+ * TypeMismatchError or other eval errors.
91
+ */
92
+ var FailError = class extends EvalError {
93
+ name = "FailError";
94
+ kind = "FailError";
95
+ constructor(message, pos = {
96
+ line: 0,
97
+ column: 0,
98
+ offset: 0
99
+ }, ctx = {}) {
100
+ super(message, pos, ctx);
101
+ }
102
+ };
80
103
  function buildSnippet(source, pos) {
81
104
  const lines = source.split("\n");
82
105
  const lineIdx = pos.line - 1;
@@ -165,6 +188,8 @@ const KEYWORDS = new Map([
165
188
  ["end", "End"],
166
189
  ["range", "Range"],
167
190
  ["with", "With"],
191
+ ["break", "Break"],
192
+ ["continue", "Continue"],
168
193
  ["define", "Define"],
169
194
  ["template", "Template"],
170
195
  ["block", "Block"],
@@ -172,19 +197,25 @@ const KEYWORDS = new Map([
172
197
  ["false", "Bool"],
173
198
  ["nil", "Nil"]
174
199
  ]);
175
- const LEFT_DELIM = "{{";
176
- const RIGHT_DELIM = "}}";
200
+ const DEFAULT_DELIMS = {
201
+ left: "{{",
202
+ right: "}}"
203
+ };
177
204
  const COMMENT_OPEN = "/*";
178
205
  const COMMENT_CLOSE = "*/";
179
206
  var Lexer = class {
180
207
  src;
208
+ leftDelim;
209
+ rightDelim;
181
210
  offset = 0;
182
211
  line = 1;
183
212
  column = 1;
184
213
  mode = "text";
185
214
  pending;
186
- constructor(src) {
215
+ constructor(src, delims = DEFAULT_DELIMS) {
187
216
  this.src = src;
217
+ this.leftDelim = delims.left;
218
+ this.rightDelim = delims.right;
188
219
  }
189
220
  /** Position of the next byte to consume. */
190
221
  pos() {
@@ -230,8 +261,8 @@ var Lexer = class {
230
261
  }
231
262
  const startPos = this.pos();
232
263
  let end = this.offset;
233
- while (end < this.src.length && !this.src.startsWith(LEFT_DELIM, end)) end += 1;
234
- const trimLeft = end < this.src.length && this.src[end + 2] === "-";
264
+ while (end < this.src.length && !this.src.startsWith(this.leftDelim, end)) end += 1;
265
+ const trimLeft = end < this.src.length && this.src[end + this.leftDelim.length] === "-";
235
266
  let textEnd = end;
236
267
  if (trimLeft) while (textEnd > this.offset && isSpace(this.src[textEnd - 1] ?? "")) textEnd -= 1;
237
268
  if (textEnd > this.offset) {
@@ -244,21 +275,21 @@ var Lexer = class {
244
275
  }
245
276
  emitLeftDelim(trimLeft) {
246
277
  const start = this.pos();
247
- this.advanceBy(2);
278
+ this.advanceBy(this.leftDelim.length);
248
279
  if (trimLeft) {
249
280
  this.advanceBy(1);
250
281
  while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
251
282
  }
252
283
  this.mode = "action";
253
284
  if (this.src.startsWith(COMMENT_OPEN, this.offset)) return this.readComment(start, trimLeft);
254
- return this.makeToken("LeftDelim", trimLeft ? "{{-" : "{{", start, trimLeft ? { trimLeft: true } : {});
285
+ return this.makeToken("LeftDelim", trimLeft ? `${this.leftDelim}-` : this.leftDelim, start, trimLeft ? { trimLeft: true } : {});
255
286
  }
256
287
  readComment(startDelim, trimLeft) {
257
288
  this.advanceBy(2);
258
289
  const bodyStart = this.offset;
259
290
  const closeIdx = this.src.indexOf(COMMENT_CLOSE, this.offset);
260
291
  if (closeIdx === -1) throw this.err("unclosed comment", startDelim, {
261
- expected: "*/}}",
292
+ expected: `*/${this.rightDelim}`,
262
293
  found: "end of input"
263
294
  });
264
295
  this.advanceTo(closeIdx);
@@ -270,11 +301,11 @@ var Lexer = class {
270
301
  trimRight = true;
271
302
  this.advanceBy(1);
272
303
  }
273
- if (!this.src.startsWith(RIGHT_DELIM, this.offset)) throw this.err("expected `}}` to close comment", this.pos(), {
274
- expected: "}}",
304
+ if (!this.src.startsWith(this.rightDelim, this.offset)) throw this.err(`expected \`${this.rightDelim}\` to close comment`, this.pos(), {
305
+ expected: this.rightDelim,
275
306
  found: this.src[this.offset] ?? "end of input"
276
307
  });
277
- this.advanceBy(2);
308
+ this.advanceBy(this.rightDelim.length);
278
309
  if (trimRight) while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
279
310
  this.mode = "text";
280
311
  return this.makeToken("Comment", body, startDelim, {
@@ -284,21 +315,21 @@ var Lexer = class {
284
315
  }
285
316
  readAction() {
286
317
  this.skipActionSpaces();
287
- if (this.src.startsWith(RIGHT_DELIM, this.offset)) {
318
+ if (this.src.startsWith(`-${this.rightDelim}`, this.offset)) {
288
319
  const start = this.pos();
289
- this.advanceBy(2);
320
+ this.advanceBy(1 + this.rightDelim.length);
290
321
  this.mode = "text";
291
- return this.makeToken("RightDelim", "}}", start);
322
+ while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
323
+ return this.makeToken("RightDelim", `-${this.rightDelim}`, start, { trimRight: true });
292
324
  }
293
- if (this.src.startsWith("-}}", this.offset)) {
325
+ if (this.src.startsWith(this.rightDelim, this.offset)) {
294
326
  const start = this.pos();
295
- this.advanceBy(3);
327
+ this.advanceBy(this.rightDelim.length);
296
328
  this.mode = "text";
297
- while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
298
- return this.makeToken("RightDelim", "-}}", start, { trimRight: true });
329
+ return this.makeToken("RightDelim", this.rightDelim, start);
299
330
  }
300
331
  if (this.offset >= this.src.length) throw this.err("unclosed action", this.pos(), {
301
- expected: "}}",
332
+ expected: this.rightDelim,
302
333
  found: "end of input"
303
334
  });
304
335
  const ch = this.src[this.offset];
@@ -527,17 +558,18 @@ function isIdentPart(c) {
527
558
  }
528
559
  //#endregion
529
560
  //#region src/parser/parser.ts
530
- function parse(source) {
531
- return new Parser(source).parseTemplate();
561
+ function parse(source, delims) {
562
+ return new Parser(source, delims).parseTemplate();
532
563
  }
533
564
  var Parser = class {
534
565
  lex;
535
566
  buf = [];
536
567
  defines = /* @__PURE__ */ new Map();
537
568
  source;
538
- constructor(source) {
569
+ rangeDepth = 0;
570
+ constructor(source, delims) {
539
571
  this.source = source;
540
- this.lex = new Lexer(source);
572
+ this.lex = delims ? new Lexer(source, delims) : new Lexer(source);
541
573
  }
542
574
  peek(n = 0) {
543
575
  while (this.buf.length <= n) this.buf.push(this.lex.next());
@@ -629,6 +661,12 @@ var Parser = class {
629
661
  case "With":
630
662
  this.next();
631
663
  return this.parseBranch("With", left.pos, trimLeft);
664
+ case "Break":
665
+ this.next();
666
+ return this.parseBreakOrContinue("Break", left.pos, trimLeft);
667
+ case "Continue":
668
+ this.next();
669
+ return this.parseBreakOrContinue("Continue", left.pos, trimLeft);
632
670
  case "Template":
633
671
  this.next();
634
672
  return this.parseTemplateInvocation(left.pos, trimLeft);
@@ -658,7 +696,9 @@ var Parser = class {
658
696
  parseBranch(kind, startPos, trimLeft) {
659
697
  const pipe = this.parsePipeline();
660
698
  this.expect("RightDelim", "`}}`");
699
+ if (kind === "Range") this.rangeDepth += 1;
661
700
  const list = this.parseList();
701
+ if (kind === "Range") this.rangeDepth -= 1;
662
702
  const elsePart = this.parseElsePart();
663
703
  const trim = {
664
704
  trimLeft,
@@ -692,6 +732,22 @@ var Parser = class {
692
732
  };
693
733
  }
694
734
  }
735
+ parseBreakOrContinue(kind, startPos, trimLeft) {
736
+ if (this.rangeDepth === 0) throw new ParseError(`{{${kind === "Break" ? "break" : "continue"}}} outside of {{range}}`, startPos, { source: this.source });
737
+ const trim = {
738
+ trimLeft,
739
+ trimRight: this.expect("RightDelim", "`}}`").trimRight === true
740
+ };
741
+ return kind === "Break" ? {
742
+ type: "Break",
743
+ pos: startPos,
744
+ trim
745
+ } : {
746
+ type: "Continue",
747
+ pos: startPos,
748
+ trim
749
+ };
750
+ }
695
751
  /**
696
752
  * Parse the `{{else}}` / `{{else if PIPE}}` segment, if any.
697
753
  *
@@ -758,7 +814,10 @@ var Parser = class {
758
814
  const name = this.parseQuotedName();
759
815
  const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline();
760
816
  this.expect("RightDelim", "`}}`");
817
+ const savedDepth = this.rangeDepth;
818
+ this.rangeDepth = 0;
761
819
  const list = this.parseList();
820
+ this.rangeDepth = savedDepth;
762
821
  const trim = {
763
822
  trimLeft,
764
823
  trimRight: this.consumeEnd()
@@ -782,7 +841,10 @@ var Parser = class {
782
841
  parseDefine(_startPos, _trimLeft) {
783
842
  const name = this.parseQuotedName();
784
843
  this.expect("RightDelim", "`}}`");
844
+ const savedDepth = this.rangeDepth;
845
+ this.rangeDepth = 0;
785
846
  const list = this.parseList();
847
+ this.rangeDepth = savedDepth;
786
848
  this.consumeEnd();
787
849
  if (this.defines.has(name)) throw new ParseError(`redefinition of template ${JSON.stringify(name)}`, list.pos, { source: this.source });
788
850
  this.defines.set(name, list);
@@ -1111,10 +1173,15 @@ function decodeRuneLiteral(raw, pos, source) {
1111
1173
  * - Methods/functions are returned as-is for the caller to invoke when
1112
1174
  * the AST shape demands a function call.
1113
1175
  *
1114
- * Missing-key handling matches Go's `missingkey=error` default: a
1115
- * genuinely absent field returns `MISSING`, which the caller surfaces as
1116
- * a `MissingFieldError`. The receiver-is-nullish case at the top of
1176
+ * Missing-key handling: a genuinely absent field returns the `MISSING`
1177
+ * sentinel, which the caller (`Engine.resolveFieldChain`) interprets per
1178
+ * the configured `missingKey` policy — `"default"`/`"zero"` produce
1179
+ * `undefined` (Go-default `<no value>` when emitted), `"error"` throws
1180
+ * `MissingFieldError`. The receiver-is-nullish case at the top of
1117
1181
  * `getField` is the trust-boundary exception documented inline below.
1182
+ *
1183
+ * [LAW:single-enforcer] This module returns the `MISSING` discriminator
1184
+ * unconditionally; the policy decision lives at exactly one site.
1118
1185
  */
1119
1186
  /** Sentinel returned by `getField` when a field is genuinely absent. */
1120
1187
  const MISSING = Symbol("go-template-js.MISSING");
@@ -1293,6 +1360,21 @@ function eagerBuiltins(toString) {
1293
1360
  fn: (fn, ...args) => fn(...args),
1294
1361
  argTypes: ["callable", "value"]
1295
1362
  },
1363
+ html: {
1364
+ fn: (...args) => htmlEscape(goPrint(args, toString)),
1365
+ argTypes: ["stringifiable"],
1366
+ returnType: "string"
1367
+ },
1368
+ js: {
1369
+ fn: (...args) => jsEscape(goPrint(args, toString)),
1370
+ argTypes: ["stringifiable"],
1371
+ returnType: "string"
1372
+ },
1373
+ urlquery: {
1374
+ fn: (...args) => urlQueryEscape(goPrint(args, toString)),
1375
+ argTypes: ["stringifiable"],
1376
+ returnType: "string"
1377
+ },
1296
1378
  not: {
1297
1379
  fn: (v) => !isTruthy(v),
1298
1380
  argTypes: ["truthy"]
@@ -1403,6 +1485,53 @@ function stringifyForPrint(value, toString) {
1403
1485
  if (typeof value === "string") return value;
1404
1486
  return toString(value);
1405
1487
  }
1488
+ const HTML_ESCAPE_TABLE = {
1489
+ "\0": "�",
1490
+ "\"": "&#34;",
1491
+ "'": "&#39;",
1492
+ "&": "&amp;",
1493
+ "<": "&lt;",
1494
+ ">": "&gt;"
1495
+ };
1496
+ function htmlEscape(s) {
1497
+ return s.replace(/[\0"'&<>]/g, (c) => HTML_ESCAPE_TABLE[c] ?? c);
1498
+ }
1499
+ const JS_FIXED_ESCAPES = {
1500
+ "\\": "\\\\",
1501
+ "'": "\\'",
1502
+ "\"": "\\\"",
1503
+ "<": "\\u003C",
1504
+ ">": "\\u003E",
1505
+ "&": "\\u0026",
1506
+ "=": "\\u003D"
1507
+ };
1508
+ const JS_NON_ASCII_PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;
1509
+ function jsEscape(s) {
1510
+ let out = "";
1511
+ for (const ch of s) {
1512
+ const fixed = JS_FIXED_ESCAPES[ch];
1513
+ if (fixed !== void 0) {
1514
+ out += fixed;
1515
+ continue;
1516
+ }
1517
+ const cp = ch.codePointAt(0);
1518
+ if (cp < 32 || cp >= 128 && !JS_NON_ASCII_PRINTABLE.test(ch)) {
1519
+ out += `\\u${cp.toString(16).toUpperCase().padStart(4, "0")}`;
1520
+ continue;
1521
+ }
1522
+ out += ch;
1523
+ }
1524
+ return out;
1525
+ }
1526
+ const URL_QUERY_ENCODER = new TextEncoder();
1527
+ function urlQueryEscape(s) {
1528
+ let out = "";
1529
+ const bytes = URL_QUERY_ENCODER.encode(s);
1530
+ for (const b of bytes) if (b >= 48 && b <= 57 || b >= 65 && b <= 90 || b >= 97 && b <= 122 || b === 45 || b === 46 || b === 95 || b === 126) out += String.fromCharCode(b);
1531
+ else if (b === 32) out += "+";
1532
+ else out += `%${b.toString(16).toUpperCase().padStart(2, "0")}`;
1533
+ return out;
1534
+ }
1406
1535
  function sprintf(format, args, toString) {
1407
1536
  let out = "";
1408
1537
  let argIdx = 0;
@@ -1480,33 +1609,6 @@ function formatV(value) {
1480
1609
  return String(value);
1481
1610
  }
1482
1611
  //#endregion
1483
- //#region src/evaluator/errors.ts
1484
- /**
1485
- * Re-exports from the unified error module, plus a small helper for
1486
- * constructing `TypeMismatchError` from inside sprig func bodies.
1487
- *
1488
- * Historical location — code that imported from this path keeps
1489
- * working. New code should import directly from `src/errors.ts`.
1490
- */
1491
- const NO_POS = {
1492
- line: 0,
1493
- column: 0,
1494
- offset: 0
1495
- };
1496
- /**
1497
- * Construct a TypeMismatchError from inside a registered func body,
1498
- * where the call-site `pos` is unavailable. The dispatch site
1499
- * (`evalCommand`) catches this and re-emits with the correct pos —
1500
- * see [LAW:single-enforcer] in evaluator.ts.
1501
- *
1502
- * Use when the gate cannot validate (nested elements, alternating
1503
- * variadic positions). For first-class arg validation, declare the
1504
- * type in `argTypes` so `enforceArgTypes` catches it at the boundary.
1505
- */
1506
- function bodyTypeMismatch(funcName, argIndex, expected, receivedSummary) {
1507
- return new TypeMismatchError(funcName, argIndex, expected, receivedSummary, NO_POS);
1508
- }
1509
- //#endregion
1510
1612
  //#region src/evaluator/scope.ts
1511
1613
  function rootScope(value) {
1512
1614
  return {
@@ -1564,6 +1666,38 @@ function declareVar(scope, name, value) {
1564
1666
  * no instance mutation, so the same Engine handles concurrent evaluate
1565
1667
  * calls (tested through the parse-once-eval-many invariant).
1566
1668
  */
1669
+ const VALID_MISSING_KEYS = new Set([
1670
+ "default",
1671
+ "zero",
1672
+ "error"
1673
+ ]);
1674
+ function validateMissingKey(value) {
1675
+ if (value === void 0) return "default";
1676
+ if (VALID_MISSING_KEYS.has(value)) return value;
1677
+ throw new Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${describeBoundaryValue(value)}`);
1678
+ }
1679
+ function describeBoundaryValue(value) {
1680
+ if (typeof value === "string") return JSON.stringify(value);
1681
+ if (value === null) return "null";
1682
+ if (value === void 0) return "undefined";
1683
+ if (typeof value === "bigint") return `${value}n`;
1684
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1685
+ if (typeof value === "symbol") return value.toString();
1686
+ if (typeof value === "function") return "[Function]";
1687
+ return `[${typeof value}]`;
1688
+ }
1689
+ function validateDelims(value) {
1690
+ if (value === void 0) return void 0;
1691
+ if (typeof value !== "object" || value === null) throw new Error(`EngineConfig.delims: expected { left, right } object, got ${describeBoundaryValue(value)}`);
1692
+ if (typeof value.left !== "string" || value.left.length === 0) throw new Error(`EngineConfig.delims.left: expected non-empty string, got ${describeBoundaryValue(value.left)}`);
1693
+ if (typeof value.right !== "string" || value.right.length === 0) throw new Error(`EngineConfig.delims.right: expected non-empty string, got ${describeBoundaryValue(value.right)}`);
1694
+ return {
1695
+ left: value.left,
1696
+ right: value.right
1697
+ };
1698
+ }
1699
+ const BREAK_SIGNAL = Object.freeze({ kind: "break" });
1700
+ const CONTINUE_SIGNAL = Object.freeze({ kind: "continue" });
1567
1701
  const NO_PIPE = { kind: "none" };
1568
1702
  /**
1569
1703
  * A parsed template bound to its parent engine.
@@ -1596,10 +1730,14 @@ var Engine = class {
1596
1730
  fromString;
1597
1731
  toString;
1598
1732
  funcs;
1733
+ missingKey;
1734
+ delims;
1599
1735
  constructor(config) {
1600
1736
  this.fromString = config.fromString;
1601
1737
  const userToString = Object.hasOwn(config, "toString") ? config.toString : void 0;
1602
1738
  this.toString = userToString ?? defaultToString;
1739
+ this.missingKey = validateMissingKey(config.missingKey);
1740
+ this.delims = validateDelims(config.delims);
1603
1741
  this.funcs = {
1604
1742
  ...defaultBuiltins(this.toString),
1605
1743
  ...config.funcs ?? {}
@@ -1613,7 +1751,7 @@ var Engine = class {
1613
1751
  * re-parsing.
1614
1752
  */
1615
1753
  parse(source) {
1616
- const parsed = parse(source);
1754
+ const parsed = parse(source, this.delims);
1617
1755
  return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope));
1618
1756
  }
1619
1757
  /**
@@ -1672,6 +1810,8 @@ var Engine = class {
1672
1810
  case "With":
1673
1811
  this.evalWith(node, scope, ctx);
1674
1812
  return;
1813
+ case "Break": throw BREAK_SIGNAL;
1814
+ case "Continue": throw CONTINUE_SIGNAL;
1675
1815
  case "Template":
1676
1816
  this.evalTemplateInvoke(node, scope, ctx);
1677
1817
  return;
@@ -1707,20 +1847,30 @@ var Engine = class {
1707
1847
  const value = this.evalPipeWithoutDecls(node.pipe, scope, ctx);
1708
1848
  const decls = node.pipe.decls;
1709
1849
  const entries = enumerateForRange(value);
1710
- if (entries.length === 0) {
1711
- if (node.elseList) this.evalList(node.elseList, scope, ctx);
1712
- return;
1713
- }
1714
- for (const [key, item] of entries) {
1715
- const child = pushScope(scope, item);
1716
- if (decls.length === 1) declareVar(child, decls[0]?.idents[0] ?? "$", item);
1717
- else if (decls.length >= 2) {
1718
- const k = decls[0]?.idents[0] ?? "$";
1719
- const v = decls[1]?.idents[0] ?? "$";
1720
- declareVar(child, k, key);
1721
- declareVar(child, v, item);
1850
+ try {
1851
+ if (entries.length === 0) {
1852
+ if (node.elseList) this.evalList(node.elseList, scope, ctx);
1853
+ return;
1722
1854
  }
1723
- this.evalList(node.list, child, ctx);
1855
+ for (const [key, item] of entries) {
1856
+ const child = pushScope(scope, item);
1857
+ if (decls.length === 1) declareVar(child, decls[0]?.idents[0] ?? "$", item);
1858
+ else if (decls.length >= 2) {
1859
+ const k = decls[0]?.idents[0] ?? "$";
1860
+ const v = decls[1]?.idents[0] ?? "$";
1861
+ declareVar(child, k, key);
1862
+ declareVar(child, v, item);
1863
+ }
1864
+ try {
1865
+ this.evalList(node.list, child, ctx);
1866
+ } catch (e) {
1867
+ if (e === CONTINUE_SIGNAL) continue;
1868
+ throw e;
1869
+ }
1870
+ }
1871
+ } catch (e) {
1872
+ if (e === BREAK_SIGNAL) return;
1873
+ throw e;
1724
1874
  }
1725
1875
  }
1726
1876
  evalTemplateInvoke(node, scope, ctx) {
@@ -1779,11 +1929,12 @@ var Engine = class {
1779
1929
  const v = piped.value;
1780
1930
  args.push(lazy ? () => v : v);
1781
1931
  }
1782
- enforceArgTypes(head.ident, fn.argTypes, args, cmd.pos, ctx.source, this.toString, fn.argTypePattern);
1932
+ enforceArgTypes(head.ident, fn.argTypes, args, cmd.pos, ctx.source, this.toString, fn.argTypePattern, this.fromString);
1783
1933
  try {
1784
1934
  return fn.fn(...args);
1785
1935
  } catch (e) {
1786
1936
  if (e instanceof TypeMismatchError) throw new TypeMismatchError(e.funcName, e.argIndex, e.expected, e.receivedSummary, cmd.pos, { source: ctx.source });
1937
+ if (e instanceof FailError) throw new FailError(e.message, cmd.pos, { source: ctx.source });
1787
1938
  throw e;
1788
1939
  }
1789
1940
  }
@@ -1802,7 +1953,7 @@ var Engine = class {
1802
1953
  source: ctx.source,
1803
1954
  available: Object.keys(this.funcs)
1804
1955
  });
1805
- enforceArgTypes(node.ident, fn.argTypes, [], node.pos, ctx.source, this.toString, fn.argTypePattern);
1956
+ enforceArgTypes(node.ident, fn.argTypes, [], node.pos, ctx.source, this.toString, fn.argTypePattern, this.fromString);
1806
1957
  return fn.fn();
1807
1958
  }
1808
1959
  case "Chain": return this.resolveFieldChain(this.evalPrimary(node.node, scope, ctx), node.fields, node.pos, ctx);
@@ -1812,8 +1963,8 @@ var Engine = class {
1812
1963
  }
1813
1964
  resolveFieldChain(receiver, idents, pos, ctx) {
1814
1965
  const result = walkFieldChain(receiver, idents);
1815
- if (result === MISSING) throw new MissingFieldError(idents, pos, { source: ctx.source });
1816
- return result;
1966
+ if (result !== MISSING) return result;
1967
+ if (this.missingKey === "error") throw new MissingFieldError(idents, pos, { source: ctx.source });
1817
1968
  }
1818
1969
  resolveVariable(idents, scope, pos, ctx) {
1819
1970
  const head = idents[0] ?? "$";
@@ -1867,7 +2018,7 @@ function formatScalarLikeGo(v) {
1867
2018
  function createEngine(config) {
1868
2019
  return new Engine(config);
1869
2020
  }
1870
- function enforceArgTypes(funcName, argTypes, values, pos, src, toString = defaultToString, pattern) {
2021
+ function enforceArgTypes(funcName, argTypes, values, pos, src, toString = defaultToString, pattern, fromString = defaultFromString) {
1871
2022
  const lookup = makeSlotLookup(argTypes, pattern);
1872
2023
  let firstOrdered = -1;
1873
2024
  let firstComparable = -1;
@@ -1875,6 +2026,9 @@ function enforceArgTypes(funcName, argTypes, values, pos, src, toString = defaul
1875
2026
  const declared = lookup(i);
1876
2027
  const value = values[i];
1877
2028
  if (!matchesArgType(declared, value, toString)) throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), describeValue(value), pos, { source: src });
2029
+ if (declared === "liftable" && typeof value === "string") values[i] = fromString(value);
2030
+ if (declared === "int") values[i] = Math.trunc(Number(value));
2031
+ else if (declared === "float") values[i] = Number(value);
1878
2032
  if (declared === "ordered") {
1879
2033
  if (firstOrdered === -1) firstOrdered = i;
1880
2034
  else if (!sameOrderedKind(values[firstOrdered], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("ordered")} of the same kind as ${describeValue(values[firstOrdered])}`, describeValue(value), pos, { source: src });
@@ -1901,6 +2055,8 @@ function matchesArgType(declared, value, toString) {
1901
2055
  case "value": return true;
1902
2056
  case "string": return typeof value === "string";
1903
2057
  case "number": return typeof value === "number" || typeof value === "bigint";
2058
+ case "int": return typeof value === "number" && Number.isFinite(value) || typeof value === "bigint" && Number.isSafeInteger(Number(value));
2059
+ case "float": return typeof value === "number" || typeof value === "bigint" && Number.isFinite(Number(value));
1904
2060
  case "bool": return typeof value === "boolean";
1905
2061
  case "ordered": return typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean";
1906
2062
  case "T": return value !== null && value !== void 0 && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint" && typeof value !== "symbol";
@@ -1920,9 +2076,13 @@ function matchesArgType(declared, value, toString) {
1920
2076
  } catch {
1921
2077
  return false;
1922
2078
  }
2079
+ case "liftable": return typeof value === "string" || value !== null && value !== void 0 && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint" && typeof value !== "symbol";
1923
2080
  case "serializable": return isJsonSerializable(value);
1924
2081
  }
1925
2082
  }
2083
+ function defaultFromString(s) {
2084
+ return s;
2085
+ }
1926
2086
  function defaultToString(value) {
1927
2087
  if (typeof value === "string") return value;
1928
2088
  if (value === null || value === void 0) return "<nil>";
@@ -1971,6 +2131,8 @@ function comparableKind(v) {
1971
2131
  }
1972
2132
  function humanArgType(t) {
1973
2133
  switch (t) {
2134
+ case "int": return "integer (finite number or safe-integer bigint)";
2135
+ case "float": return "float (number, including NaN/Infinity, or finite-convertible bigint)";
1974
2136
  case "T": return "T (consumer-defined fragment)";
1975
2137
  case "ordered": return "orderable primitive";
1976
2138
  case "list": return "list";
@@ -1978,6 +2140,7 @@ function humanArgType(t) {
1978
2140
  case "sized": return "sized value (string, list, map, set, or dict)";
1979
2141
  case "comparable": return "comparable value (orderable primitive, nil, list, dict, Map, or Set)";
1980
2142
  case "stringifiable": return "stringifiable value (string or convertible via the engine's toString)";
2143
+ case "liftable": return "liftable value (T or string, the latter lifted via the engine's fromString)";
1981
2144
  case "callable": return "callable (function value)";
1982
2145
  case "collection": return "collection (string, array, Map, or dict)";
1983
2146
  case "index-key": return "index key (number, bigint, or string)";
@@ -2275,189 +2438,1124 @@ function sprigConversions() {
2275
2438
  };
2276
2439
  }
2277
2440
  //#endregion
2278
- //#region src/sprig/defaults/empty.ts
2441
+ //#region src/sprig/datetime/_duration.ts
2279
2442
  /**
2280
- * `empty val` — true if `val` is "empty" per Go sprig's rules:
2281
- * nil, false, 0, 0.0, "", empty array/Map/object.
2443
+ * Go-style duration: parsing and formatting.
2282
2444
  *
2283
- * Note: `empty 0` is true (this surprises newcomers — Go sprig matches
2284
- * Go's reflect-IsZero semantics).
2285
- */
2286
- function empty(value) {
2287
- if (value === null || value === void 0) return true;
2288
- if (value === false) return true;
2289
- if (typeof value === "number") return value === 0 || Number.isNaN(value);
2290
- if (typeof value === "bigint") return value === 0n;
2291
- if (typeof value === "string") return value.length === 0;
2292
- if (Array.isArray(value)) return value.length === 0;
2293
- if (value instanceof Map) return value.size === 0;
2294
- if (value instanceof Set) return value.size === 0;
2295
- if (typeof value === "object") return Object.keys(value).length === 0;
2296
- return false;
2297
- }
2298
- //#endregion
2299
- //#region src/sprig/defaults/coalesce.ts
2300
- /**
2301
- * `coalesce a b c …` — returns the first non-empty argument, or
2302
- * undefined if none are non-empty.
2445
+ * Go's `time.ParseDuration` grammar:
2446
+ * duration = [-] component+
2447
+ * component = decimal unit
2448
+ * unit = ns | us | µs | ms | s | m | h
2449
+ *
2450
+ * Values are nanoseconds internally (same as Go's time.Duration).
2451
+ *
2452
+ * [LAW:one-source-of-truth] All duration string ↔ nanoseconds
2453
+ * conversions live here. No other file does this math.
2303
2454
  */
2304
- function coalesce(...values) {
2305
- for (const v of values) if (!empty(v)) return v;
2306
- }
2307
- //#endregion
2308
- //#region src/sprig/defaults/default.ts
2455
+ const NS_PER = {
2456
+ h: 36e11,
2457
+ m: 6e10,
2458
+ s: 1e9,
2459
+ ms: 1e6,
2460
+ us: 1e3,
2461
+ µs: 1e3,
2462
+ ns: 1
2463
+ };
2309
2464
  /**
2310
- * `default defaultVal val` — returns `val` if non-empty (per `empty`),
2311
- * else `defaultVal`.
2465
+ * Parse a Go duration string to nanoseconds (as a float for sub-ms
2466
+ * precision). Returns `NaN` on parse failure.
2312
2467
  *
2313
- * Argument order matches Go sprig: the *default* comes first, the
2314
- * value comes second. Pipelines feed the trailing arg, so
2315
- * `{{ .name | default "anonymous" }}` evaluates default("anonymous", .name).
2468
+ * Accepts: "0", "300ms", "1.5h", "2h45m", "-1h30m", "100µs".
2316
2469
  */
2317
- function defaultFn(defaultVal, value) {
2318
- return empty(value) ? defaultVal : value;
2470
+ function parseDurationNs(s) {
2471
+ if (s === "0") return 0;
2472
+ let negative = false;
2473
+ let rest = s;
2474
+ if (rest.startsWith("-")) {
2475
+ negative = true;
2476
+ rest = rest.slice(1);
2477
+ } else if (rest.startsWith("+")) rest = rest.slice(1);
2478
+ if (!rest) return NaN;
2479
+ let total = 0;
2480
+ const UNIT_RE = /^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;
2481
+ while (rest.length > 0) {
2482
+ const m = UNIT_RE.exec(rest);
2483
+ if (!m) return NaN;
2484
+ const value = parseFloat(m[1] ?? "0");
2485
+ const unit = m[2];
2486
+ total += value * NS_PER[unit];
2487
+ rest = rest.slice(m[0].length);
2488
+ }
2489
+ return negative ? -total : total;
2319
2490
  }
2320
- //#endregion
2321
- //#region src/sprig/defaults/fromJson.ts
2322
2491
  /**
2323
- * `fromJson s` — parses a JSON string into a value.
2492
+ * Format nanoseconds as Go's `time.Duration.String()`.
2324
2493
  *
2325
- * Returns the parsed value. Throws if the input is not valid JSON,
2326
- * matching Go sprig's behaviour (Go sprig propagates the parse error).
2494
+ * Go's algorithm mirrors time/time.go Duration.String():
2495
+ * - Values < 1µs: "Xns"
2496
+ * - Values < 1ms: "X.YYYµs" (trailing zeros trimmed)
2497
+ * - Values < 1s: "X.YYYms" (trailing zeros trimmed)
2498
+ * - Values >= 1s: "XhYmZ.WWWs" (hours/minutes shown when non-zero;
2499
+ * intermediate zero units always shown once hours or
2500
+ * minutes appear; e.g. "1h0m0s", "1m0s")
2327
2501
  */
2328
- function fromJson(input) {
2329
- return JSON.parse(input);
2502
+ function formatDurationNs(ns) {
2503
+ if (ns === 0) return "0s";
2504
+ let negative = false;
2505
+ let abs = ns;
2506
+ if (abs < 0) {
2507
+ negative = true;
2508
+ abs = -abs;
2509
+ }
2510
+ let out;
2511
+ if (abs < NS_PER.us) out = `${Math.floor(abs)}ns`;
2512
+ else if (abs < NS_PER.ms) out = fmtSubUnit(abs, NS_PER.us, 3, "µs");
2513
+ else if (abs < NS_PER.s) out = fmtSubUnit(abs, NS_PER.ms, 6, "ms");
2514
+ else out = fmtGeqSecond(abs);
2515
+ return negative ? `-${out}` : out;
2516
+ }
2517
+ /** Format sub-second values in a given unit (µs, ms). */
2518
+ function fmtSubUnit(abs, unit, fracDigits, suffix) {
2519
+ const whole = Math.floor(abs / unit);
2520
+ const frac = Math.round(abs % unit);
2521
+ if (frac === 0) return `${whole}${suffix}`;
2522
+ return `${whole}.${String(frac).padStart(fracDigits, "0").replace(/0+$/, "")}${suffix}`;
2523
+ }
2524
+ /** Format durations >= 1 second as Go does. */
2525
+ function fmtGeqSecond(abs) {
2526
+ const h = Math.floor(abs / NS_PER.h);
2527
+ abs -= h * NS_PER.h;
2528
+ const m = Math.floor(abs / NS_PER.m);
2529
+ abs -= m * NS_PER.m;
2530
+ const s = Math.floor(abs / NS_PER.s);
2531
+ const nsFrac = abs - s * NS_PER.s;
2532
+ const secStr = nsFrac === 0 ? `${s}s` : `${s}.${String(Math.round(nsFrac)).padStart(9, "0").replace(/0+$/, "")}s`;
2533
+ if (h > 0) return `${h}h${m}m${secStr}`;
2534
+ if (m > 0) return `${m}m${secStr}`;
2535
+ return secStr;
2536
+ }
2537
+ /** Convert integer seconds to nanoseconds. */
2538
+ function secondsToNs(s) {
2539
+ return s * NS_PER.s;
2330
2540
  }
2331
2541
  //#endregion
2332
- //#region src/sprig/defaults/ternary.ts
2542
+ //#region src/sprig/datetime/_resolve.ts
2333
2543
  /**
2334
- * `ternary trueVal falseVal cond` — returns `trueVal` if `cond` is
2335
- * truthy, else `falseVal`.
2544
+ * Normalise the heterogeneous `t` argument accepted by date functions.
2336
2545
  *
2337
- * Note: argument order matches Go sprig and surprises newcomers.
2338
- * Pipelines feed cond as the trailing arg, e.g.
2339
- * `{{ .ok | ternary "YES" "NO" }}` → ternary("YES", "NO", .ok)
2546
+ * Go sprig's `dateInZone` accepts: `time.Time`, `int64`, `int`, `int32`.
2547
+ * JS side: `Date`, `number` (Unix seconds), `bigint` (Unix seconds),
2548
+ * `string` (ISO / Go-layout string).
2549
+ *
2550
+ * When `t` is already a `Date`, it is returned unchanged.
2551
+ * When `t` is a number or bigint, it is treated as Unix seconds (matching
2552
+ * Go's `time.Unix(n, 0)` — NOT milliseconds).
2553
+ * When `t` is a string, it is parsed by `Date.parse` as a fallback.
2554
+ *
2555
+ * [LAW:single-enforcer] One place owns `t → Date` normalisation.
2556
+ * All date functions call this; none duplicate the logic.
2340
2557
  */
2341
- function ternary(trueVal, falseVal, cond) {
2342
- return isTruthy(cond) ? trueVal : falseVal;
2558
+ function resolveDate(t) {
2559
+ if (t instanceof Date) return t;
2560
+ if (typeof t === "bigint") return /* @__PURE__ */ new Date(Number(t) * 1e3);
2561
+ if (typeof t === "number") return /* @__PURE__ */ new Date(t * 1e3);
2562
+ if (typeof t === "string") {
2563
+ const parsed = new Date(t);
2564
+ if (!Number.isNaN(parsed.getTime())) return parsed;
2565
+ throw new Error(`sprig: cannot parse date value ${JSON.stringify(t)}`);
2566
+ }
2567
+ throw new Error(`sprig: unsupported date type: ${typeof t}`);
2343
2568
  }
2344
2569
  //#endregion
2345
- //#region src/sprig/defaults/toJson.ts
2570
+ //#region src/sprig/datetime/ago.ts
2346
2571
  /**
2347
- * `toJson val` — serializes a value to compact JSON.
2348
- *
2349
- * Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that
2350
- * `JSON.stringify(undefined)` is undefined; we coerce that to "null"
2351
- * for byte-equivalence with Go's encoding/json (which encodes
2352
- * untyped-nil as null).
2572
+ * `ago t` — Go-style duration since `t`.
2573
+ * Mirrors Go sprig: `time.Since(t).Round(time.Second).String()`.
2353
2574
  */
2354
- function toJson(value) {
2355
- return JSON.stringify(value) ?? "null";
2575
+ function ago(t, clock) {
2576
+ const ms = clock().getTime() - resolveDate(t).getTime();
2577
+ return formatDurationNs(Math.round(ms / 1e3) * 1e9);
2356
2578
  }
2357
2579
  //#endregion
2358
- //#region src/sprig/defaults/toPrettyJson.ts
2580
+ //#region src/sprig/datetime/_format.ts
2581
+ const MONTHS_LONG$1 = [
2582
+ "January",
2583
+ "February",
2584
+ "March",
2585
+ "April",
2586
+ "May",
2587
+ "June",
2588
+ "July",
2589
+ "August",
2590
+ "September",
2591
+ "October",
2592
+ "November",
2593
+ "December"
2594
+ ];
2595
+ const MONTHS_SHORT$1 = [
2596
+ "Jan",
2597
+ "Feb",
2598
+ "Mar",
2599
+ "Apr",
2600
+ "May",
2601
+ "Jun",
2602
+ "Jul",
2603
+ "Aug",
2604
+ "Sep",
2605
+ "Oct",
2606
+ "Nov",
2607
+ "Dec"
2608
+ ];
2609
+ const WEEKDAYS_LONG = [
2610
+ "Sunday",
2611
+ "Monday",
2612
+ "Tuesday",
2613
+ "Wednesday",
2614
+ "Thursday",
2615
+ "Friday",
2616
+ "Saturday"
2617
+ ];
2618
+ const WEEKDAYS_SHORT = [
2619
+ "Sun",
2620
+ "Mon",
2621
+ "Tue",
2622
+ "Wed",
2623
+ "Thu",
2624
+ "Fri",
2625
+ "Sat"
2626
+ ];
2627
+ function pad2(n) {
2628
+ return n < 10 ? `0${n}` : String(n);
2629
+ }
2630
+ function pad3(n) {
2631
+ return n < 10 ? `00${n}` : n < 100 ? `0${n}` : String(n);
2632
+ }
2633
+ function spacePad2(n) {
2634
+ return n < 10 ? ` ${n}` : String(n);
2635
+ }
2636
+ /** ±hhmm (no colon). E.g. "+0500", "-0500", "+0000". */
2637
+ function fmtOffset(offsetMinutes) {
2638
+ const sign = offsetMinutes >= 0 ? "+" : "-";
2639
+ const abs = Math.abs(offsetMinutes);
2640
+ return `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;
2641
+ }
2642
+ /** ±hh:mm (with colon). E.g. "+05:00", "-05:00", "+00:00". */
2643
+ function fmtOffsetColon(offsetMinutes) {
2644
+ const sign = offsetMinutes >= 0 ? "+" : "-";
2645
+ const abs = Math.abs(offsetMinutes);
2646
+ return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
2647
+ }
2648
+ /** ±hh only. */
2649
+ function fmtOffsetHour(offsetMinutes) {
2650
+ return `${offsetMinutes >= 0 ? "+" : "-"}${pad2(Math.floor(Math.abs(offsetMinutes) / 60))}`;
2651
+ }
2652
+ /** Z or ±hhmm. */
2653
+ function fmtOffsetZ(offsetMinutes) {
2654
+ return offsetMinutes === 0 ? "Z" : fmtOffset(offsetMinutes);
2655
+ }
2656
+ /** Z or ±hh:mm. */
2657
+ function fmtOffsetColonZ(offsetMinutes) {
2658
+ return offsetMinutes === 0 ? "Z" : fmtOffsetColon(offsetMinutes);
2659
+ }
2660
+ /** Z or ±hh. */
2661
+ function fmtOffsetHourZ(offsetMinutes) {
2662
+ return offsetMinutes === 0 ? "Z" : fmtOffsetHour(offsetMinutes);
2663
+ }
2664
+ function fmtFrac(ms, width, trimTrailing) {
2665
+ const nanosTotal = ms * 1e6;
2666
+ const s = String(nanosTotal).padStart(9, "0").slice(0, width);
2667
+ if (trimTrailing) return s.replace(/0+$/, "");
2668
+ return s;
2669
+ }
2670
+ const TOKENS$1 = [
2671
+ [".000000000", (z) => `.${fmtFrac(z.ms, 9, false)}`],
2672
+ [".999999999", (z) => {
2673
+ const s = fmtFrac(z.ms, 9, true);
2674
+ return s ? `.${s}` : "";
2675
+ }],
2676
+ [".000000", (z) => `.${fmtFrac(z.ms, 6, false)}`],
2677
+ [".999999", (z) => {
2678
+ const s = fmtFrac(z.ms, 6, true);
2679
+ return s ? `.${s}` : "";
2680
+ }],
2681
+ [".000", (z) => `.${pad3(z.ms)}`],
2682
+ [".999", (z) => {
2683
+ const s = pad3(z.ms).replace(/0+$/, "");
2684
+ return s ? `.${s}` : "";
2685
+ }],
2686
+ ["January", (z) => MONTHS_LONG$1[z.month - 1] ?? "January"],
2687
+ ["Monday", (z) => WEEKDAYS_LONG[z.weekday] ?? "Monday"],
2688
+ ["Z07:00", (z) => fmtOffsetColonZ(z.offsetMinutes)],
2689
+ ["-07:00", (z) => fmtOffsetColon(z.offsetMinutes)],
2690
+ ["Z0700", (z) => fmtOffsetZ(z.offsetMinutes)],
2691
+ ["-0700", (z) => fmtOffset(z.offsetMinutes)],
2692
+ ["2006", (z) => String(z.year)],
2693
+ ["Jan", (z) => MONTHS_SHORT$1[z.month - 1] ?? "Jan"],
2694
+ ["Mon", (z) => WEEKDAYS_SHORT[z.weekday] ?? "Mon"],
2695
+ ["MST", (z) => z.tzAbbr],
2696
+ ["-07", (z) => fmtOffsetHour(z.offsetMinutes)],
2697
+ ["Z07", (z) => fmtOffsetHourZ(z.offsetMinutes)],
2698
+ ["15", (z) => pad2(z.hour)],
2699
+ ["01", (z) => pad2(z.month)],
2700
+ ["02", (z) => pad2(z.day)],
2701
+ ["_2", (z) => spacePad2(z.day)],
2702
+ ["03", (z) => pad2(z.hour12)],
2703
+ ["04", (z) => pad2(z.minute)],
2704
+ ["05", (z) => pad2(z.second)],
2705
+ ["06", (z) => pad2(z.year % 100)],
2706
+ ["PM", (z) => z.hour >= 12 ? "PM" : "AM"],
2707
+ ["pm", (z) => z.hour >= 12 ? "pm" : "am"],
2708
+ ["1", (z) => String(z.month)],
2709
+ ["2", (z) => String(z.day)],
2710
+ ["3", (z) => String(z.hour12)],
2711
+ ["4", (z) => String(z.minute)],
2712
+ ["5", (z) => String(z.second)]
2713
+ ];
2359
2714
  /**
2360
- * `toPrettyJson val` — JSON with 2-space indentation, matching Go
2361
- * sprig's output exactly.
2715
+ * Format `zoneParts` according to Go's reference-time layout string.
2716
+ * Literal characters pass through unchanged.
2362
2717
  */
2363
- function toPrettyJson(value) {
2364
- return JSON.stringify(value, null, 2) ?? "null";
2718
+ function formatGoLayout(layout, z) {
2719
+ let result = "";
2720
+ let i = 0;
2721
+ while (i < layout.length) {
2722
+ let matched = false;
2723
+ for (const [token, replacer] of TOKENS$1) if (layout.startsWith(token, i)) {
2724
+ result += replacer(z);
2725
+ i += token.length;
2726
+ matched = true;
2727
+ break;
2728
+ }
2729
+ if (!matched) result += layout[i++];
2730
+ }
2731
+ return result;
2365
2732
  }
2366
2733
  //#endregion
2367
- //#region src/sprig/defaults/index.ts
2368
- function sprigDefaults() {
2734
+ //#region src/sprig/datetime/_zone.ts
2735
+ const INTL_OPTS = {
2736
+ year: "numeric",
2737
+ month: "2-digit",
2738
+ day: "2-digit",
2739
+ weekday: "long",
2740
+ hour: "2-digit",
2741
+ minute: "2-digit",
2742
+ second: "2-digit",
2743
+ hour12: false
2744
+ };
2745
+ function indexParts(parts) {
2746
+ const out = /* @__PURE__ */ new Map();
2747
+ for (const p of parts) out.set(p.type, p.value);
2748
+ return out;
2749
+ }
2750
+ const WEEKDAY_NAMES = [
2751
+ "Sunday",
2752
+ "Monday",
2753
+ "Tuesday",
2754
+ "Wednesday",
2755
+ "Thursday",
2756
+ "Friday",
2757
+ "Saturday"
2758
+ ];
2759
+ /** Extract date parts in the requested IANA timezone. Falls back to "UTC" on invalid zone, mirroring Go sprig. */
2760
+ function getZoneParts(date, tzInput) {
2761
+ let tz;
2762
+ try {
2763
+ new Intl.DateTimeFormat("en-US", { timeZone: tzInput });
2764
+ tz = tzInput;
2765
+ } catch {
2766
+ tz = "UTC";
2767
+ }
2768
+ const p = indexParts(new Intl.DateTimeFormat("en-US", {
2769
+ ...INTL_OPTS,
2770
+ timeZone: tz
2771
+ }).formatToParts(date));
2772
+ const hour = parseInt(p.get("hour") ?? "0", 10) % 24;
2773
+ const tzAbbr = indexParts(new Intl.DateTimeFormat("en-US", {
2774
+ timeZone: tz,
2775
+ timeZoneName: "short"
2776
+ }).formatToParts(date)).get("timeZoneName") ?? tz;
2777
+ const offsetMinutes = parseGMTOffset(indexParts(new Intl.DateTimeFormat("en-US", {
2778
+ timeZone: tz,
2779
+ timeZoneName: "shortOffset"
2780
+ }).formatToParts(date)).get("timeZoneName") ?? "GMT");
2781
+ const weekday = WEEKDAY_NAMES.indexOf(p.get("weekday") ?? "Sunday");
2369
2782
  return {
2370
- default: {
2371
- fn: (a, b) => defaultFn(a, b),
2372
- argTypes: ["value", "truthy"]
2373
- },
2374
- empty: {
2375
- fn: (v) => empty(v),
2376
- argTypes: ["truthy"]
2377
- },
2378
- coalesce: {
2379
- fn: (...vs) => coalesce(...vs),
2380
- argTypes: ["truthy"]
2381
- },
2382
- ternary: {
2383
- fn: (a, b, c) => ternary(a, b, c),
2384
- argTypes: [
2385
- "value",
2386
- "value",
2387
- "truthy"
2388
- ]
2389
- },
2390
- fromJson: {
2391
- fn: (s) => fromJson(s),
2392
- argTypes: ["string"]
2393
- },
2394
- toJson: {
2395
- fn: (v) => toJson(v),
2396
- argTypes: ["serializable"],
2397
- returnType: "string"
2398
- },
2399
- toPrettyJson: {
2400
- fn: (v) => toPrettyJson(v),
2401
- argTypes: ["serializable"],
2402
- returnType: "string"
2403
- }
2783
+ year: parseInt(p.get("year") ?? "2000", 10),
2784
+ month: parseInt(p.get("month") ?? "1", 10),
2785
+ day: parseInt(p.get("day") ?? "1", 10),
2786
+ weekday: weekday === -1 ? 0 : weekday,
2787
+ hour,
2788
+ hour12: hour % 12 || 12,
2789
+ minute: parseInt(p.get("minute") ?? "0", 10),
2790
+ second: parseInt(p.get("second") ?? "0", 10),
2791
+ ms: date.getUTCMilliseconds(),
2792
+ tzAbbr,
2793
+ offsetMinutes
2404
2794
  };
2405
2795
  }
2796
+ /** Parse "GMT", "GMT+5", "GMT+5:30", "GMT-4" → offset in minutes. */
2797
+ function parseGMTOffset(s) {
2798
+ if (s === "GMT" || s === "UTC") return 0;
2799
+ const m = s.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);
2800
+ if (!m) return 0;
2801
+ const sign = m[1] === "+" ? 1 : -1;
2802
+ const h = parseInt(m[2] ?? "0", 10);
2803
+ const min = parseInt(m[3] ?? "0", 10);
2804
+ return sign * (h * 60 + min);
2805
+ }
2806
+ /** Host timezone name (IANA string). */
2807
+ function localTz() {
2808
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
2809
+ }
2406
2810
  //#endregion
2407
- //#region src/sprig/dicts/dict.ts
2811
+ //#region src/sprig/datetime/date.ts
2408
2812
  /**
2409
- * `dict k1 v1 k2 v2 …` — builds a record from alternating key/value pairs.
2410
- *
2411
- * [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates
2412
- * the kv cycle via `argTypePattern: "alternating"` against
2413
- * `argTypes: ["string", "value"]`, so every key position is a string by
2414
- * the time the body runs. The body trusts the gate; no per-key probe.
2415
- *
2416
- * Odd-length call (`dict "a"`) leaves the last value `undefined` —
2417
- * matches Go sprig.
2813
+ * `date format t` — format `t` using Go's reference-time layout,
2814
+ * in the host timezone (mirrors Go's `date` which uses `time.Local`).
2418
2815
  */
2419
- function dict(...kvs) {
2420
- const out = {};
2421
- for (let i = 0; i < kvs.length; i += 2) out[kvs[i]] = kvs[i + 1];
2422
- return out;
2816
+ function date(format, t) {
2817
+ return formatGoLayout(format, getZoneParts(resolveDate(t), localTz()));
2423
2818
  }
2424
2819
  //#endregion
2425
- //#region src/sprig/dicts/get.ts
2820
+ //#region src/sprig/datetime/dateInZone.ts
2426
2821
  /**
2427
- * `get d key` — returns d[key] or undefined.
2428
- *
2429
- * [LAW:single-enforcer] The gate validates `d` is a plain object
2430
- * (`"dict"`); the body trusts the receiver type. The Map case lives in
2431
- * template-laws-3gt.7 (where the slot widens with an explicit Map-key
2432
- * carve-out per audit B5/B6) — until then, Maps are rejected at the
2433
- * gate.
2822
+ * `dateInZone format t zone` — format `t` using Go's reference-time
2823
+ * layout, displayed in the named IANA timezone.
2434
2824
  */
2435
- function get(d, key) {
2436
- return d[key];
2825
+ function dateInZone(format, t, zone) {
2826
+ return formatGoLayout(format, getZoneParts(resolveDate(t), zone));
2437
2827
  }
2438
2828
  //#endregion
2439
- //#region src/sprig/dicts/hasKey.ts
2829
+ //#region src/sprig/datetime/dateModify.ts
2440
2830
  /**
2441
- * `hasKey d key` — true when `key` is a own-property of `d`.
2442
- *
2443
- * Note: sprig's name is `hasKey` though docs sometimes say `haskey`.
2444
- * [LAW:single-enforcer] Receiver type validated at the gate.
2831
+ * `dateModify duration t` — add or subtract a Go duration from `t`.
2832
+ * `duration` is a Go duration string: "1h30m", "-24h", "300ms".
2445
2833
  */
2446
- function hasKey(d, key) {
2447
- return key in d;
2834
+ function dateModify(duration, t) {
2835
+ const d = resolveDate(t);
2836
+ const ns = parseDurationNs(duration);
2837
+ if (Number.isNaN(ns)) return d;
2838
+ return new Date(d.getTime() + ns / 1e6);
2448
2839
  }
2449
2840
  //#endregion
2450
- //#region src/sprig/dicts/keys.ts
2841
+ //#region src/sprig/datetime/duration.ts
2451
2842
  /**
2452
- * `keys d` — list of own enumerable string keys.
2843
+ * `duration sec` — seconds → Go-style duration string.
2844
+ * Mirrors Go sprig: accepts a string (parsed as decimal integer seconds)
2845
+ * or a number/bigint.
2453
2846
  *
2454
- * [LAW:single-enforcer] Receiver type validated at the gate (`"dict"`);
2455
- * the body trusts the parameter. Maps are rejected by the dict gate —
2456
- * closes audit finding B6 (no silent `String(key)` flattening of
2457
- * typed-T Map keys, because Maps never reach this body).
2847
+ * `duration("3600")` → `"1h0m0s"`, `duration("5")` → `"5s"`.
2848
+ *
2849
+ * Note: Go sprig only handles `string` and `int64` inputs; `int` (the type
2850
+ * of a Go template integer literal) falls to a default-zero branch. To
2851
+ * maintain portable templates, always pass seconds as a string.
2458
2852
  */
2459
- function keys(d) {
2460
- return Object.keys(d);
2853
+ function duration(sec) {
2854
+ if (typeof sec === "string") {
2855
+ const n = parseInt(sec, 10);
2856
+ return Number.isNaN(n) ? "0s" : formatDurationNs(secondsToNs(n));
2857
+ }
2858
+ if (typeof sec === "bigint") return formatDurationNs(secondsToNs(Number(sec)));
2859
+ if (typeof sec === "number") return formatDurationNs(secondsToNs(sec));
2860
+ return "0s";
2861
+ }
2862
+ //#endregion
2863
+ //#region src/sprig/datetime/durationRound.ts
2864
+ const YEAR = 36e11 * 24 * 365;
2865
+ const MONTH = 36e11 * 24 * 30;
2866
+ const DAY = 36e11 * 24;
2867
+ const HOUR = 36e11;
2868
+ const MINUTE = 6e10;
2869
+ const SECOND = 1e9;
2870
+ /**
2871
+ * `durationRound d` — parse a Go duration string and truncate to the
2872
+ * largest unit. Mirrors Go sprig's `durationRound` which uses integer
2873
+ * division (NOT rounding) and custom single-unit suffixes.
2874
+ *
2875
+ * Examples: "1h30m" → "1h", "90s" → "1m", "1h" → "60m" (strict >).
2876
+ */
2877
+ function durationRound(d) {
2878
+ const ns = parseDurationNs(String(d));
2879
+ if (Number.isNaN(ns)) return "0s";
2880
+ const u = Math.abs(ns);
2881
+ if (u > YEAR) return `${Math.floor(u / YEAR)}y`;
2882
+ if (u > MONTH) return `${Math.floor(u / MONTH)}mo`;
2883
+ if (u > DAY) return `${Math.floor(u / DAY)}d`;
2884
+ if (u > HOUR) return `${Math.floor(u / HOUR)}h`;
2885
+ if (u > MINUTE) return `${Math.floor(u / MINUTE)}m`;
2886
+ if (u > SECOND) return `${Math.floor(u / SECOND)}s`;
2887
+ return "0s";
2888
+ }
2889
+ //#endregion
2890
+ //#region src/sprig/datetime/htmlDate.ts
2891
+ /** `htmlDate t` — YYYY-MM-DD in the host timezone. */
2892
+ function htmlDate(t) {
2893
+ const z = getZoneParts(resolveDate(t), localTz());
2894
+ return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
2895
+ }
2896
+ //#endregion
2897
+ //#region src/sprig/datetime/htmlDateInZone.ts
2898
+ /** `htmlDateInZone t zone` — YYYY-MM-DD in the named timezone. */
2899
+ function htmlDateInZone(t, zone) {
2900
+ const z = getZoneParts(resolveDate(t), zone);
2901
+ return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
2902
+ }
2903
+ //#endregion
2904
+ //#region src/sprig/datetime/now.ts
2905
+ /** `now` — current instant. Routed through the clock seam. */
2906
+ function now(clock) {
2907
+ return clock();
2908
+ }
2909
+ //#endregion
2910
+ //#region src/sprig/datetime/_parse.ts
2911
+ /**
2912
+ * Parse a date string according to Go's reference-time layout.
2913
+ *
2914
+ * Mirrors `time.ParseInLocation` with UTC as the default location
2915
+ * (when the layout contains no timezone token, the result is UTC).
2916
+ *
2917
+ * Strategy: tokenise the layout the same way the formatter does —
2918
+ * greedy longest-match — but instead of replacing tokens with values,
2919
+ * consume the corresponding characters from the value string.
2920
+ */
2921
+ const MONTHS_LONG = [
2922
+ "January",
2923
+ "February",
2924
+ "March",
2925
+ "April",
2926
+ "May",
2927
+ "June",
2928
+ "July",
2929
+ "August",
2930
+ "September",
2931
+ "October",
2932
+ "November",
2933
+ "December"
2934
+ ];
2935
+ const MONTHS_SHORT = [
2936
+ "Jan",
2937
+ "Feb",
2938
+ "Mar",
2939
+ "Apr",
2940
+ "May",
2941
+ "Jun",
2942
+ "Jul",
2943
+ "Aug",
2944
+ "Sep",
2945
+ "Oct",
2946
+ "Nov",
2947
+ "Dec"
2948
+ ];
2949
+ function defaultState() {
2950
+ return {
2951
+ year: 2e3,
2952
+ month: 1,
2953
+ day: 1,
2954
+ hour: 0,
2955
+ minute: 0,
2956
+ second: 0,
2957
+ ms: 0,
2958
+ offsetMinutes: 0,
2959
+ isPM: false,
2960
+ hour12: false
2961
+ };
2962
+ }
2963
+ function consumeFixed(val, pos, n) {
2964
+ return [val.slice(pos, pos + n), pos + n];
2965
+ }
2966
+ function consumeDigits(val, pos, min, max) {
2967
+ let end = pos;
2968
+ while (end < val.length && end - pos < max && val.charCodeAt(end) >= 48 && val.charCodeAt(end) <= 57) end++;
2969
+ if (end - pos < min) throw new Error(`sprig toDate: expected ${min}-${max} digits at pos ${pos}`);
2970
+ return [parseInt(val.slice(pos, end), 10), end];
2971
+ }
2972
+ function consumeMonthLong(val, pos) {
2973
+ for (const [i, m] of MONTHS_LONG.entries()) if (val.startsWith(m, pos)) return [i + 1, pos + m.length];
2974
+ throw new Error(`sprig toDate: expected month name at pos ${pos}`);
2975
+ }
2976
+ function consumeMonthShort(val, pos) {
2977
+ for (const [i, m] of MONTHS_SHORT.entries()) if (val.startsWith(m, pos)) return [i + 1, pos + m.length];
2978
+ throw new Error(`sprig toDate: expected short month name at pos ${pos}`);
2979
+ }
2980
+ function consumeWeekdayLong(val, pos) {
2981
+ for (const d of [
2982
+ "Sunday",
2983
+ "Monday",
2984
+ "Tuesday",
2985
+ "Wednesday",
2986
+ "Thursday",
2987
+ "Friday",
2988
+ "Saturday"
2989
+ ]) if (val.startsWith(d, pos)) return pos + d.length;
2990
+ throw new Error(`sprig toDate: expected weekday name at pos ${pos}`);
2991
+ }
2992
+ function consumeWeekdayShort(val, pos) {
2993
+ for (const d of [
2994
+ "Sun",
2995
+ "Mon",
2996
+ "Tue",
2997
+ "Wed",
2998
+ "Thu",
2999
+ "Fri",
3000
+ "Sat"
3001
+ ]) if (val.startsWith(d, pos)) return pos + d.length;
3002
+ throw new Error(`sprig toDate: expected short weekday name at pos ${pos}`);
3003
+ }
3004
+ function consumeSpacePaddedDay(val, pos) {
3005
+ if (val[pos] === " ") {
3006
+ const [n, end] = consumeDigits(val, pos + 1, 1, 1);
3007
+ return [n, end];
3008
+ }
3009
+ return consumeDigits(val, pos, 1, 2);
3010
+ }
3011
+ /** Parse offset like "+0500", "-0500", "+05:00", "-05:00", "+05", "-05". Returns minutes. */
3012
+ function consumeOffset(val, pos, withColon) {
3013
+ const sign = val[pos] === "+" ? 1 : val[pos] === "-" ? -1 : 0;
3014
+ if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${pos}`);
3015
+ let p = pos + 1;
3016
+ const [h, p2] = consumeDigits(val, p, 2, 2);
3017
+ p = p2;
3018
+ let m = 0;
3019
+ if (withColon && val[p] === ":") {
3020
+ const [m2, p3] = consumeDigits(val, p + 1, 2, 2);
3021
+ m = m2;
3022
+ p = p3;
3023
+ } else if (!withColon) {
3024
+ const [m2, p3] = consumeDigits(val, p, 2, 2);
3025
+ m = m2;
3026
+ p = p3;
3027
+ }
3028
+ return [sign * (h * 60 + m), p];
3029
+ }
3030
+ /** Parse "Z" or an offset. withColon controls +05:00 vs +0500 form. Returns [offsetMinutes, newPos]. */
3031
+ function consumeZOrOffset(val, pos, withColon, hourOnly) {
3032
+ if (val[pos] === "Z") return [0, pos + 1];
3033
+ if (hourOnly) {
3034
+ const sign = val[pos] === "+" ? 1 : val[pos] === "-" ? -1 : 0;
3035
+ if (sign === 0) throw new Error(`sprig toDate: expected Z or +/- at pos ${pos}`);
3036
+ const [h, p2] = consumeDigits(val, pos + 1, 2, 2);
3037
+ return [sign * h * 60, p2];
3038
+ }
3039
+ return consumeOffset(val, pos, withColon);
3040
+ }
3041
+ /** Parse timezone abbreviation (e.g. "UTC", "EST"). Returns new pos. */
3042
+ function consumeTzAbbr(val, pos) {
3043
+ let end = pos;
3044
+ while (end < val.length && val.charCodeAt(end) >= 65 && val.charCodeAt(end) <= 90) end++;
3045
+ if (end === pos) throw new Error(`sprig toDate: expected timezone abbreviation at pos ${pos}`);
3046
+ return end;
3047
+ }
3048
+ /** Parse fractional seconds (like ".000", ".999", etc.) starting AFTER the dot. */
3049
+ function consumeFrac(val, pos, width) {
3050
+ const [raw, end] = consumeFixed(val, pos, width);
3051
+ const ns = parseInt(raw.padEnd(9, "0"), 10);
3052
+ return [Math.round(ns / 1e6), end];
3053
+ }
3054
+ function dispatchToken(token, val, vp, st) {
3055
+ const s = { ...st };
3056
+ switch (token) {
3057
+ case "January": {
3058
+ const [m, p2] = consumeMonthLong(val, vp);
3059
+ s.month = m;
3060
+ return [p2, s];
3061
+ }
3062
+ case "Monday": return [consumeWeekdayLong(val, vp), s];
3063
+ case "Jan": {
3064
+ const [m, p2] = consumeMonthShort(val, vp);
3065
+ s.month = m;
3066
+ return [p2, s];
3067
+ }
3068
+ case "Mon": return [consumeWeekdayShort(val, vp), s];
3069
+ case "2006": {
3070
+ const [y, p2] = consumeDigits(val, vp, 4, 4);
3071
+ s.year = y;
3072
+ return [p2, s];
3073
+ }
3074
+ case "06": {
3075
+ const [y, p2] = consumeDigits(val, vp, 2, 2);
3076
+ s.year = y < 70 ? 2e3 + y : 1900 + y;
3077
+ return [p2, s];
3078
+ }
3079
+ case "01": {
3080
+ const [m, p2] = consumeDigits(val, vp, 2, 2);
3081
+ s.month = m;
3082
+ return [p2, s];
3083
+ }
3084
+ case "1": {
3085
+ const [m, p2] = consumeDigits(val, vp, 1, 2);
3086
+ s.month = m;
3087
+ return [p2, s];
3088
+ }
3089
+ case "_2": {
3090
+ const [d, p2] = consumeSpacePaddedDay(val, vp);
3091
+ s.day = d;
3092
+ return [p2, s];
3093
+ }
3094
+ case "02": {
3095
+ const [d, p2] = consumeDigits(val, vp, 2, 2);
3096
+ s.day = d;
3097
+ return [p2, s];
3098
+ }
3099
+ case "2": {
3100
+ const [d, p2] = consumeDigits(val, vp, 1, 2);
3101
+ s.day = d;
3102
+ return [p2, s];
3103
+ }
3104
+ case "15": {
3105
+ const [h, p2] = consumeDigits(val, vp, 2, 2);
3106
+ s.hour = h;
3107
+ return [p2, s];
3108
+ }
3109
+ case "03": {
3110
+ const [h, p2] = consumeDigits(val, vp, 2, 2);
3111
+ s.hour = h;
3112
+ s.hour12 = true;
3113
+ return [p2, s];
3114
+ }
3115
+ case "3": {
3116
+ const [h, p2] = consumeDigits(val, vp, 1, 2);
3117
+ s.hour = h;
3118
+ s.hour12 = true;
3119
+ return [p2, s];
3120
+ }
3121
+ case "04": {
3122
+ const [m, p2] = consumeDigits(val, vp, 2, 2);
3123
+ s.minute = m;
3124
+ return [p2, s];
3125
+ }
3126
+ case "4": {
3127
+ const [m, p2] = consumeDigits(val, vp, 1, 2);
3128
+ s.minute = m;
3129
+ return [p2, s];
3130
+ }
3131
+ case "05": {
3132
+ const [sec, p2] = consumeDigits(val, vp, 2, 2);
3133
+ s.second = sec;
3134
+ return [p2, s];
3135
+ }
3136
+ case "5": {
3137
+ const [sec, p2] = consumeDigits(val, vp, 1, 2);
3138
+ s.second = sec;
3139
+ return [p2, s];
3140
+ }
3141
+ case "PM":
3142
+ case "pm": {
3143
+ const ampm = val.slice(vp, vp + 2).toLowerCase();
3144
+ if (ampm !== "am" && ampm !== "pm") throw new Error(`sprig toDate: expected AM/PM at pos ${vp}, got ${JSON.stringify(val.slice(vp, vp + 2))}`);
3145
+ s.isPM = ampm === "pm";
3146
+ s.hour12 = true;
3147
+ return [vp + 2, s];
3148
+ }
3149
+ case "MST": return [consumeTzAbbr(val, vp), s];
3150
+ case "-0700": {
3151
+ const [off, p2] = consumeOffset(val, vp, false);
3152
+ s.offsetMinutes = off;
3153
+ return [p2, s];
3154
+ }
3155
+ case "-07:00": {
3156
+ const [off, p2] = consumeOffset(val, vp, true);
3157
+ s.offsetMinutes = off;
3158
+ return [p2, s];
3159
+ }
3160
+ case "-07": {
3161
+ const sign = val[vp] === "+" ? 1 : val[vp] === "-" ? -1 : 0;
3162
+ if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${vp}`);
3163
+ const [h, p2] = consumeDigits(val, vp + 1, 2, 2);
3164
+ s.offsetMinutes = sign * h * 60;
3165
+ return [p2, s];
3166
+ }
3167
+ case "Z0700": {
3168
+ const [off, p2] = consumeZOrOffset(val, vp, false, false);
3169
+ s.offsetMinutes = off;
3170
+ return [p2, s];
3171
+ }
3172
+ case "Z07:00": {
3173
+ const [off, p2] = consumeZOrOffset(val, vp, true, false);
3174
+ s.offsetMinutes = off;
3175
+ return [p2, s];
3176
+ }
3177
+ case "Z07": {
3178
+ const [off, p2] = consumeZOrOffset(val, vp, false, true);
3179
+ s.offsetMinutes = off;
3180
+ return [p2, s];
3181
+ }
3182
+ case ".000000000": {
3183
+ if (val[vp] !== ".") throw new Error(`sprig toDate: expected . at pos ${vp}`);
3184
+ const [ms, p3] = consumeFrac(val, vp + 1, 9);
3185
+ s.ms = ms;
3186
+ return [p3, s];
3187
+ }
3188
+ case ".999999999": {
3189
+ if (val[vp] !== ".") return [vp, s];
3190
+ const end = vp + 1;
3191
+ let e2 = end;
3192
+ while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;
3193
+ const frac = val.slice(end, e2).padEnd(9, "0");
3194
+ s.ms = Math.round(parseInt(frac, 10) / 1e6);
3195
+ return [e2, s];
3196
+ }
3197
+ case ".000000": {
3198
+ if (val[vp] !== ".") throw new Error(`sprig toDate: expected . at pos ${vp}`);
3199
+ const [ms, p3] = consumeFrac(val, vp + 1, 6);
3200
+ s.ms = ms;
3201
+ return [p3, s];
3202
+ }
3203
+ case ".999999": {
3204
+ if (val[vp] !== ".") return [vp, s];
3205
+ const end = vp + 1;
3206
+ let e2 = end;
3207
+ while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;
3208
+ const frac = val.slice(end, e2).padEnd(9, "0");
3209
+ s.ms = Math.round(parseInt(frac, 10) / 1e6);
3210
+ return [e2, s];
3211
+ }
3212
+ case ".000": {
3213
+ if (val[vp] !== ".") throw new Error(`sprig toDate: expected . at pos ${vp}`);
3214
+ const [ms, p3] = consumeFrac(val, vp + 1, 3);
3215
+ s.ms = ms;
3216
+ return [p3, s];
3217
+ }
3218
+ case ".999": {
3219
+ if (val[vp] !== ".") return [vp, s];
3220
+ const end = vp + 1;
3221
+ let e2 = end;
3222
+ while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;
3223
+ const frac = val.slice(end, e2).padEnd(3, "0");
3224
+ s.ms = parseInt(frac, 10);
3225
+ return [e2, s];
3226
+ }
3227
+ }
3228
+ throw new Error(`sprig toDate: unhandled token ${token}`);
3229
+ }
3230
+ const TOKENS = [
3231
+ ".000000000",
3232
+ ".999999999",
3233
+ ".000000",
3234
+ ".999999",
3235
+ ".000",
3236
+ ".999",
3237
+ "January",
3238
+ "Monday",
3239
+ "Z07:00",
3240
+ "-07:00",
3241
+ "Z0700",
3242
+ "-0700",
3243
+ "2006",
3244
+ "Jan",
3245
+ "Mon",
3246
+ "MST",
3247
+ "-07",
3248
+ "Z07",
3249
+ "15",
3250
+ "01",
3251
+ "02",
3252
+ "_2",
3253
+ "03",
3254
+ "04",
3255
+ "05",
3256
+ "06",
3257
+ "PM",
3258
+ "pm",
3259
+ "1",
3260
+ "2",
3261
+ "3",
3262
+ "4",
3263
+ "5"
3264
+ ];
3265
+ /**
3266
+ * Parse `value` according to Go's reference-time `layout`.
3267
+ * Returns a UTC-based `Date` whose wall time corresponds to the parsed
3268
+ * components adjusted for the parsed timezone offset.
3269
+ */
3270
+ function parseGoLayout(layout, value) {
3271
+ let lp = 0;
3272
+ let vp = 0;
3273
+ let st = defaultState();
3274
+ while (lp < layout.length) {
3275
+ let matched = false;
3276
+ for (const token of TOKENS) if (layout.startsWith(token, lp)) {
3277
+ const [newVp, newSt] = dispatchToken(token, value, vp, st);
3278
+ vp = newVp;
3279
+ st = newSt;
3280
+ lp += token.length;
3281
+ matched = true;
3282
+ break;
3283
+ }
3284
+ if (!matched) {
3285
+ const lc = layout.charAt(lp);
3286
+ if (value[vp] !== lc) throw new Error(`sprig toDate: expected ${JSON.stringify(lc)} at pos ${vp}, got ${JSON.stringify(value[vp])}`);
3287
+ lp++;
3288
+ vp++;
3289
+ }
3290
+ }
3291
+ if (vp !== value.length) throw new Error(`sprig toDate: extra characters at pos ${vp}: ${JSON.stringify(value.slice(vp))}`);
3292
+ if (st.hour12) {
3293
+ const h12 = st.hour % 12;
3294
+ st.hour = st.isPM ? h12 + 12 : h12;
3295
+ }
3296
+ const utcMs = Date.UTC(st.year, st.month - 1, st.day, st.hour, st.minute, st.second, st.ms) - st.offsetMinutes * 60 * 1e3;
3297
+ return new Date(utcMs);
3298
+ }
3299
+ //#endregion
3300
+ //#region src/sprig/datetime/toDate.ts
3301
+ /**
3302
+ * `toDate format value` — parse `value` string using Go's reference-time
3303
+ * layout. Returns a `Date`. Mirrors Go sprig's `toDate`.
3304
+ */
3305
+ function toDate(format, value) {
3306
+ return parseGoLayout(format, value);
3307
+ }
3308
+ //#endregion
3309
+ //#region src/sprig/datetime/unixEpoch.ts
3310
+ /** `unixEpoch t` — seconds since Unix epoch as a decimal string. */
3311
+ function unixEpoch(t) {
3312
+ return String(Math.floor(resolveDate(t).getTime() / 1e3));
3313
+ }
3314
+ //#endregion
3315
+ //#region src/sprig/datetime/index.ts
3316
+ /**
3317
+ * Build the sprig date/time FuncMap.
3318
+ *
3319
+ * @param clock - Source of "current time". Defaults to `() => new Date()`.
3320
+ * Pass a frozen clock for deterministic test output (mirrors
3321
+ * `EngineConfig.clock`).
3322
+ */
3323
+ function sprigDatetime(clock = () => /* @__PURE__ */ new Date()) {
3324
+ return {
3325
+ now: {
3326
+ fn: () => now(clock),
3327
+ argTypes: []
3328
+ },
3329
+ date: {
3330
+ fn: (format, t) => date(format, t),
3331
+ argTypes: ["string", "value"]
3332
+ },
3333
+ dateInZone: {
3334
+ fn: (format, t, zone) => dateInZone(format, t, zone),
3335
+ argTypes: [
3336
+ "string",
3337
+ "value",
3338
+ "string"
3339
+ ]
3340
+ },
3341
+ dateModify: {
3342
+ fn: (dur, t) => dateModify(dur, t),
3343
+ argTypes: ["string", "value"]
3344
+ },
3345
+ htmlDate: {
3346
+ fn: (t) => htmlDate(t),
3347
+ argTypes: ["value"]
3348
+ },
3349
+ htmlDateInZone: {
3350
+ fn: (t, zone) => htmlDateInZone(t, zone),
3351
+ argTypes: ["value", "string"]
3352
+ },
3353
+ duration: {
3354
+ fn: (sec) => duration(sec),
3355
+ argTypes: ["value"]
3356
+ },
3357
+ durationRound: {
3358
+ fn: (d) => durationRound(d),
3359
+ argTypes: ["value"]
3360
+ },
3361
+ toDate: {
3362
+ fn: (format, s) => toDate(format, s),
3363
+ argTypes: ["string", "string"]
3364
+ },
3365
+ ago: {
3366
+ fn: (t) => ago(t, clock),
3367
+ argTypes: ["value"]
3368
+ },
3369
+ unixEpoch: {
3370
+ fn: (t) => unixEpoch(t),
3371
+ argTypes: ["value"]
3372
+ }
3373
+ };
3374
+ }
3375
+ //#endregion
3376
+ //#region src/sprig/defaults/empty.ts
3377
+ /**
3378
+ * `empty val` — true if `val` is "empty" per Go sprig's rules:
3379
+ * nil, false, 0, 0.0, "", empty array/Map/object.
3380
+ *
3381
+ * Note: `empty 0` is true (this surprises newcomers — Go sprig matches
3382
+ * Go's reflect-IsZero semantics).
3383
+ */
3384
+ function empty(value) {
3385
+ if (value === null || value === void 0) return true;
3386
+ if (value === false) return true;
3387
+ if (typeof value === "number") return value === 0 || Number.isNaN(value);
3388
+ if (typeof value === "bigint") return value === 0n;
3389
+ if (typeof value === "string") return value.length === 0;
3390
+ if (Array.isArray(value)) return value.length === 0;
3391
+ if (value instanceof Map) return value.size === 0;
3392
+ if (value instanceof Set) return value.size === 0;
3393
+ if (typeof value === "object") return Object.keys(value).length === 0;
3394
+ return false;
3395
+ }
3396
+ //#endregion
3397
+ //#region src/sprig/defaults/coalesce.ts
3398
+ /**
3399
+ * `coalesce a b c …` — returns the first non-empty argument, or
3400
+ * undefined if none are non-empty.
3401
+ */
3402
+ function coalesce(...values) {
3403
+ for (const v of values) if (!empty(v)) return v;
3404
+ }
3405
+ //#endregion
3406
+ //#region src/sprig/defaults/default.ts
3407
+ /**
3408
+ * `default defaultVal val` — returns `val` if non-empty (per `empty`),
3409
+ * else `defaultVal`.
3410
+ *
3411
+ * Argument order matches Go sprig: the *default* comes first, the
3412
+ * value comes second. Pipelines feed the trailing arg, so
3413
+ * `{{ .name | default "anonymous" }}` evaluates default("anonymous", .name).
3414
+ */
3415
+ function defaultFn(defaultVal, value) {
3416
+ return empty(value) ? defaultVal : value;
3417
+ }
3418
+ //#endregion
3419
+ //#region src/sprig/defaults/fromJson.ts
3420
+ /**
3421
+ * `fromJson s` — parses a JSON string into a value.
3422
+ *
3423
+ * Returns the parsed value. Throws if the input is not valid JSON,
3424
+ * matching Go sprig's behaviour (Go sprig propagates the parse error).
3425
+ */
3426
+ function fromJson(input) {
3427
+ return JSON.parse(input);
3428
+ }
3429
+ //#endregion
3430
+ //#region src/sprig/defaults/ternary.ts
3431
+ /**
3432
+ * `ternary trueVal falseVal cond` — returns `trueVal` if `cond` is
3433
+ * truthy, else `falseVal`.
3434
+ *
3435
+ * Note: argument order matches Go sprig and surprises newcomers.
3436
+ * Pipelines feed cond as the trailing arg, e.g.
3437
+ * `{{ .ok | ternary "YES" "NO" }}` → ternary("YES", "NO", .ok)
3438
+ */
3439
+ function ternary(trueVal, falseVal, cond) {
3440
+ return isTruthy(cond) ? trueVal : falseVal;
3441
+ }
3442
+ //#endregion
3443
+ //#region src/sprig/defaults/toJson.ts
3444
+ /**
3445
+ * `toJson val` — serializes a value to compact JSON.
3446
+ *
3447
+ * Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that
3448
+ * `JSON.stringify(undefined)` is undefined; we coerce that to "null"
3449
+ * for byte-equivalence with Go's encoding/json (which encodes
3450
+ * untyped-nil as null).
3451
+ */
3452
+ function toJson(value) {
3453
+ return JSON.stringify(value) ?? "null";
3454
+ }
3455
+ //#endregion
3456
+ //#region src/sprig/defaults/toPrettyJson.ts
3457
+ /**
3458
+ * `toPrettyJson val` — JSON with 2-space indentation, matching Go
3459
+ * sprig's output exactly.
3460
+ */
3461
+ function toPrettyJson(value) {
3462
+ return JSON.stringify(value, null, 2) ?? "null";
3463
+ }
3464
+ //#endregion
3465
+ //#region src/sprig/defaults/index.ts
3466
+ function sprigDefaults() {
3467
+ return {
3468
+ default: {
3469
+ fn: (a, b) => defaultFn(a, b),
3470
+ argTypes: ["value", "truthy"]
3471
+ },
3472
+ empty: {
3473
+ fn: (v) => empty(v),
3474
+ argTypes: ["truthy"]
3475
+ },
3476
+ coalesce: {
3477
+ fn: (...vs) => coalesce(...vs),
3478
+ argTypes: ["truthy"]
3479
+ },
3480
+ ternary: {
3481
+ fn: (a, b, c) => ternary(a, b, c),
3482
+ argTypes: [
3483
+ "value",
3484
+ "value",
3485
+ "truthy"
3486
+ ]
3487
+ },
3488
+ fromJson: {
3489
+ fn: (s) => fromJson(s),
3490
+ argTypes: ["string"]
3491
+ },
3492
+ toJson: {
3493
+ fn: (v) => toJson(v),
3494
+ argTypes: ["serializable"],
3495
+ returnType: "string"
3496
+ },
3497
+ toPrettyJson: {
3498
+ fn: (v) => toPrettyJson(v),
3499
+ argTypes: ["serializable"],
3500
+ returnType: "string"
3501
+ }
3502
+ };
3503
+ }
3504
+ //#endregion
3505
+ //#region src/sprig/dicts/dict.ts
3506
+ /**
3507
+ * `dict k1 v1 k2 v2 …` — builds a record from alternating key/value pairs.
3508
+ *
3509
+ * [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates
3510
+ * the kv cycle via `argTypePattern: "alternating"` against
3511
+ * `argTypes: ["string", "value"]`, so every key position is a string by
3512
+ * the time the body runs. The body trusts the gate; no per-key probe.
3513
+ *
3514
+ * Odd-length call (`dict "a"`) leaves the last value `undefined` —
3515
+ * matches Go sprig.
3516
+ */
3517
+ function dict(...kvs) {
3518
+ const out = {};
3519
+ for (let i = 0; i < kvs.length; i += 2) out[kvs[i]] = kvs[i + 1];
3520
+ return out;
3521
+ }
3522
+ //#endregion
3523
+ //#region src/sprig/dicts/get.ts
3524
+ /**
3525
+ * `get d key` — returns d[key] or undefined.
3526
+ *
3527
+ * [LAW:single-enforcer] The gate validates `d` is a plain object
3528
+ * (`"dict"`); the body trusts the receiver type. The Map case lives in
3529
+ * template-laws-3gt.7 (where the slot widens with an explicit Map-key
3530
+ * carve-out per audit B5/B6) — until then, Maps are rejected at the
3531
+ * gate.
3532
+ */
3533
+ function get(d, key) {
3534
+ return d[key];
3535
+ }
3536
+ //#endregion
3537
+ //#region src/sprig/dicts/hasKey.ts
3538
+ /**
3539
+ * `hasKey d key` — true when `key` is a own-property of `d`.
3540
+ *
3541
+ * Note: sprig's name is `hasKey` though docs sometimes say `haskey`.
3542
+ * [LAW:single-enforcer] Receiver type validated at the gate.
3543
+ */
3544
+ function hasKey(d, key) {
3545
+ return key in d;
3546
+ }
3547
+ //#endregion
3548
+ //#region src/sprig/dicts/keys.ts
3549
+ /**
3550
+ * `keys d` — list of own enumerable string keys.
3551
+ *
3552
+ * [LAW:single-enforcer] Receiver type validated at the gate (`"dict"`);
3553
+ * the body trusts the parameter. Maps are rejected by the dict gate —
3554
+ * closes audit finding B6 (no silent `String(key)` flattening of
3555
+ * typed-T Map keys, because Maps never reach this body).
3556
+ */
3557
+ function keys(d) {
3558
+ return Object.keys(d);
2461
3559
  }
2462
3560
  //#endregion
2463
3561
  //#region src/sprig/dicts/merge.ts
@@ -2591,41 +3689,258 @@ function sprigDicts() {
2591
3689
  fn: (d, k) => unset(d, k),
2592
3690
  argTypes: ["dict", "string"]
2593
3691
  },
2594
- keys: {
2595
- fn: (d) => keys(d),
2596
- argTypes: ["dict"]
3692
+ keys: {
3693
+ fn: (d) => keys(d),
3694
+ argTypes: ["dict"]
3695
+ },
3696
+ values: {
3697
+ fn: (d) => values(d),
3698
+ argTypes: ["dict"]
3699
+ },
3700
+ pluck: {
3701
+ fn: (k, ...d) => pluck(k, ...d),
3702
+ argTypes: ["string", "dict"]
3703
+ },
3704
+ pick: {
3705
+ fn: (d, ...k) => pick(d, ...k),
3706
+ argTypes: ["dict", "string"]
3707
+ },
3708
+ omit: {
3709
+ fn: (d, ...k) => omit(d, ...k),
3710
+ argTypes: ["dict", "string"]
3711
+ },
3712
+ hasKey: {
3713
+ fn: (d, k) => hasKey(d, k),
3714
+ argTypes: ["dict", "string"]
3715
+ },
3716
+ merge: {
3717
+ fn: (d, ...s) => merge(d, ...s),
3718
+ argTypes: ["dict"]
3719
+ },
3720
+ mergeOverwrite: {
3721
+ fn: (d, ...s) => mergeOverwrite(d, ...s),
3722
+ argTypes: ["dict"]
3723
+ }
3724
+ };
3725
+ }
3726
+ //#endregion
3727
+ //#region src/sprig/flow/fail.ts
3728
+ /**
3729
+ * `fail msg` — unconditionally abort template evaluation with `msg`.
3730
+ *
3731
+ * Mirrors Go sprig's `fail`, which returns `(string, error)` and causes
3732
+ * text/template to stop execution. Throws `FailError` so consumers can
3733
+ * catch it specifically and distinguish it from engine errors.
3734
+ *
3735
+ * [LAW:types-are-the-program] Return type `never` encodes the invariant
3736
+ * that this function never returns — the type system enforces what a
3737
+ * comment would only suggest.
3738
+ */
3739
+ function fail(msg) {
3740
+ throw new FailError(msg);
3741
+ }
3742
+ //#endregion
3743
+ //#region src/sprig/flow/index.ts
3744
+ function sprigFlow() {
3745
+ return { fail: {
3746
+ fn: (msg) => fail(msg),
3747
+ argTypes: ["string"]
3748
+ } };
3749
+ }
3750
+ //#endregion
3751
+ //#region src/sprig/hash/adler32sum.ts
3752
+ const _enc$2 = new TextEncoder();
3753
+ const MOD_ADLER = 65521;
3754
+ /**
3755
+ * `adler32sum s` — Adler-32 checksum of `s` as a decimal string.
3756
+ *
3757
+ * Matches Go's `hash/adler32.Checksum([]byte(s))` formatted with `%d`.
3758
+ * Uses unsigned 32-bit arithmetic via `>>> 0` to mirror Go's uint32 result.
3759
+ */
3760
+ function adler32sum(s) {
3761
+ const bytes = _enc$2.encode(s);
3762
+ let a = 1;
3763
+ let b = 0;
3764
+ for (const byte of bytes) {
3765
+ a = (a + byte) % MOD_ADLER;
3766
+ b = (b + a) % MOD_ADLER;
3767
+ }
3768
+ return String(b * 65536 + a >>> 0);
3769
+ }
3770
+ //#endregion
3771
+ //#region src/sprig/hash/_b32.ts
3772
+ /**
3773
+ * [LAW:one-source-of-truth] RFC 4648 base32 alphabet and decode table —
3774
+ * shared by b32enc and b32dec.
3775
+ */
3776
+ const ALPHA32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
3777
+ /** Reverse lookup: character → 5-bit value. */
3778
+ const DECODE32 = new Map(Array.from(ALPHA32).map((c, i) => [c, i]));
3779
+ //#endregion
3780
+ //#region src/sprig/hash/b32dec.ts
3781
+ const _dec$1 = new TextDecoder();
3782
+ /** `b32dec s` — RFC 4648 base32 decoded back to a UTF-8 string. */
3783
+ function b32dec(s) {
3784
+ const stripped = s.replace(/=+$/, "").toUpperCase();
3785
+ const bytes = [];
3786
+ let bits = 0;
3787
+ let value = 0;
3788
+ for (const c of stripped) {
3789
+ const v = DECODE32.get(c);
3790
+ if (v === void 0) throw new Error(`b32dec: invalid character '${c}'`);
3791
+ value = value << 5 | v;
3792
+ bits += 5;
3793
+ if (bits >= 8) {
3794
+ bits -= 8;
3795
+ bytes.push(value >> bits & 255);
3796
+ }
3797
+ }
3798
+ return _dec$1.decode(new Uint8Array(bytes));
3799
+ }
3800
+ //#endregion
3801
+ //#region src/sprig/hash/b32enc.ts
3802
+ const _enc$1 = new TextEncoder();
3803
+ /** `b32enc s` — UTF-8 bytes of `s` encoded as RFC 4648 base32. */
3804
+ function b32enc(s) {
3805
+ const bytes = _enc$1.encode(s);
3806
+ let result = "";
3807
+ let bits = 0;
3808
+ let value = 0;
3809
+ for (const byte of bytes) {
3810
+ value = value << 8 | byte;
3811
+ bits += 8;
3812
+ while (bits >= 5) {
3813
+ bits -= 5;
3814
+ result += ALPHA32[value >> bits & 31];
3815
+ }
3816
+ }
3817
+ if (bits > 0) result += ALPHA32[value << 5 - bits & 31];
3818
+ while (result.length % 8 !== 0) result += "=";
3819
+ return result;
3820
+ }
3821
+ //#endregion
3822
+ //#region src/sprig/hash/b64dec.ts
3823
+ const _dec = new TextDecoder();
3824
+ /** `b64dec s` — standard base64 decoded back to a UTF-8 string. */
3825
+ function b64dec(s) {
3826
+ const binary = atob(s);
3827
+ const bytes = new Uint8Array(binary.length);
3828
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
3829
+ return _dec.decode(bytes);
3830
+ }
3831
+ //#endregion
3832
+ //#region src/sprig/hash/b64enc.ts
3833
+ const _enc = new TextEncoder();
3834
+ /** `b64enc s` — UTF-8 bytes of `s` encoded as standard base64. */
3835
+ function b64enc(s) {
3836
+ const bytes = _enc.encode(s);
3837
+ const chars = [];
3838
+ for (const b of bytes) chars.push(String.fromCharCode(b));
3839
+ return btoa(chars.join(""));
3840
+ }
3841
+ //#endregion
3842
+ //#region src/sprig/hash/sha1sum.ts
3843
+ /** `sha1sum s` — hex-encoded SHA-1 digest of `s` (UTF-8). */
3844
+ function sha1sum(s) {
3845
+ return bytesToHex(sha1(utf8ToBytes(s)));
3846
+ }
3847
+ //#endregion
3848
+ //#region src/sprig/hash/sha256sum.ts
3849
+ /** `sha256sum s` — hex-encoded SHA-256 digest of `s` (UTF-8). */
3850
+ function sha256sum(s) {
3851
+ return bytesToHex(sha256(utf8ToBytes(s)));
3852
+ }
3853
+ //#endregion
3854
+ //#region src/sprig/hash/sha512sum.ts
3855
+ /** `sha512sum s` — hex-encoded SHA-512 digest of `s` (UTF-8). */
3856
+ function sha512sum(s) {
3857
+ return bytesToHex(sha512(utf8ToBytes(s)));
3858
+ }
3859
+ //#endregion
3860
+ //#region src/sprig/hash/uuidv4.ts
3861
+ /**
3862
+ * `uuidv4` — RFC 4122 v4 UUID via `globalThis.crypto.randomUUID()`.
3863
+ *
3864
+ * Available in Node >= 20.19 (package minimum), Bun, Deno, and all modern browsers.
3865
+ * Throws if the runtime lacks `crypto.randomUUID` — this should never
3866
+ * happen in the supported environment set.
3867
+ */
3868
+ function uuidv4() {
3869
+ if (typeof globalThis.crypto?.randomUUID !== "function") throw new Error("uuidv4: globalThis.crypto.randomUUID is not available");
3870
+ return globalThis.crypto.randomUUID();
3871
+ }
3872
+ //#endregion
3873
+ //#region src/sprig/hash/index.ts
3874
+ /** Build the sprig hash/encoding FuncMap. */
3875
+ function sprigHash() {
3876
+ return {
3877
+ b64enc: {
3878
+ fn: (s) => b64enc(s),
3879
+ argTypes: ["string"]
3880
+ },
3881
+ b64dec: {
3882
+ fn: (s) => b64dec(s),
3883
+ argTypes: ["string"]
2597
3884
  },
2598
- values: {
2599
- fn: (d) => values(d),
2600
- argTypes: ["dict"]
3885
+ b32enc: {
3886
+ fn: (s) => b32enc(s),
3887
+ argTypes: ["string"]
2601
3888
  },
2602
- pluck: {
2603
- fn: (k, ...d) => pluck(k, ...d),
2604
- argTypes: ["string", "dict"]
3889
+ b32dec: {
3890
+ fn: (s) => b32dec(s),
3891
+ argTypes: ["string"]
2605
3892
  },
2606
- pick: {
2607
- fn: (d, ...k) => pick(d, ...k),
2608
- argTypes: ["dict", "string"]
3893
+ sha1sum: {
3894
+ fn: (s) => sha1sum(s),
3895
+ argTypes: ["string"]
2609
3896
  },
2610
- omit: {
2611
- fn: (d, ...k) => omit(d, ...k),
2612
- argTypes: ["dict", "string"]
3897
+ sha256sum: {
3898
+ fn: (s) => sha256sum(s),
3899
+ argTypes: ["string"]
2613
3900
  },
2614
- hasKey: {
2615
- fn: (d, k) => hasKey(d, k),
2616
- argTypes: ["dict", "string"]
3901
+ sha512sum: {
3902
+ fn: (s) => sha512sum(s),
3903
+ argTypes: ["string"]
2617
3904
  },
2618
- merge: {
2619
- fn: (d, ...s) => merge(d, ...s),
2620
- argTypes: ["dict"]
3905
+ adler32sum: {
3906
+ fn: (s) => adler32sum(s),
3907
+ argTypes: ["string"]
2621
3908
  },
2622
- mergeOverwrite: {
2623
- fn: (d, ...s) => mergeOverwrite(d, ...s),
2624
- argTypes: ["dict"]
3909
+ uuidv4: {
3910
+ fn: () => uuidv4(),
3911
+ argTypes: []
2625
3912
  }
2626
3913
  };
2627
3914
  }
2628
3915
  //#endregion
3916
+ //#region src/sprig/lists/all.ts
3917
+ /**
3918
+ * `all v1 v2 …` — true iff `empty(x)` is false for every argument.
3919
+ * An empty argument list returns true (Go sprig: vacuous truth).
3920
+ *
3921
+ * [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper
3922
+ * the rest of the sprig surface (default, coalesce, empty) routes
3923
+ * through, so "is this empty?" has exactly one answer.
3924
+ */
3925
+ function all(...values) {
3926
+ for (const v of values) if (empty(v)) return false;
3927
+ return true;
3928
+ }
3929
+ //#endregion
3930
+ //#region src/sprig/lists/any.ts
3931
+ /**
3932
+ * `any v1 v2 …` — true iff `empty(x)` is false for at least one
3933
+ * argument. An empty argument list returns false.
3934
+ *
3935
+ * [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper
3936
+ * the rest of the sprig surface (default, coalesce, empty) routes
3937
+ * through, so "is this empty?" has exactly one answer.
3938
+ */
3939
+ function any(...values) {
3940
+ for (const v of values) if (!empty(v)) return true;
3941
+ return false;
3942
+ }
3943
+ //#endregion
2629
3944
  //#region src/sprig/lists/append.ts
2630
3945
  /** `append list item` — add item at the end. */
2631
3946
  function append(list, item) {
@@ -2655,6 +3970,82 @@ function concat(...lists) {
2655
3970
  return out;
2656
3971
  }
2657
3972
  //#endregion
3973
+ //#region src/evaluator/errors.ts
3974
+ /**
3975
+ * Re-exports from the unified error module, plus a small helper for
3976
+ * constructing `TypeMismatchError` from inside sprig func bodies.
3977
+ *
3978
+ * Historical location — code that imported from this path keeps
3979
+ * working. New code should import directly from `src/errors.ts`.
3980
+ */
3981
+ const NO_POS = {
3982
+ line: 0,
3983
+ column: 0,
3984
+ offset: 0
3985
+ };
3986
+ /**
3987
+ * Construct a TypeMismatchError from inside a registered func body,
3988
+ * where the call-site `pos` is unavailable. The dispatch site
3989
+ * (`evalCommand`) catches this and re-emits with the correct pos —
3990
+ * see [LAW:single-enforcer] in evaluator.ts.
3991
+ *
3992
+ * Use when the gate cannot validate (nested elements, alternating
3993
+ * variadic positions). For first-class arg validation, declare the
3994
+ * type in `argTypes` so `enforceArgTypes` catches it at the boundary.
3995
+ */
3996
+ function bodyTypeMismatch(funcName, argIndex, expected, receivedSummary) {
3997
+ return new TypeMismatchError(funcName, argIndex, expected, receivedSummary, NO_POS);
3998
+ }
3999
+ //#endregion
4000
+ //#region src/sprig/lists/dig.ts
4001
+ /**
4002
+ * `dig key1 key2 … default dict` — walks nested dict by string keys,
4003
+ * returning the deepest value found, or `default` when a key along
4004
+ * the path is missing.
4005
+ *
4006
+ * The argument shape is *positional from the end*:
4007
+ *
4008
+ * dig "a" "b" "c" <default> <dict>
4009
+ *
4010
+ * — last arg is the dict, the one before it is the default, every
4011
+ * preceding arg is a string key. This shape comes straight from Go
4012
+ * sprig and is unintuitive but documented.
4013
+ *
4014
+ * [LAW:single-enforcer] exception: `argTypes: ["value"]` (variadic
4015
+ * trailing slot) — the from-the-end positional shape cannot be
4016
+ * expressed by the gate's positional-from-the-start + trailing-repeat
4017
+ * model. We accept body-side validation here and use
4018
+ * `bodyTypeMismatch` so failures still surface as TypeMismatchError
4019
+ * with the correct call-site pos.
4020
+ */
4021
+ function dig(...args) {
4022
+ if (args.length < 3) throw bodyTypeMismatch("dig", 0, "at least 3 arguments (...keys, default, dict)", `${args.length} argument${args.length === 1 ? "" : "s"}`);
4023
+ const dict = args[args.length - 1];
4024
+ const def = args[args.length - 2];
4025
+ const keys = args.slice(0, -2);
4026
+ if (!isPlainDict(dict)) throw bodyTypeMismatch("dig", args.length - 1, "dict", describeKind(dict));
4027
+ for (let i = 0; i < keys.length; i++) if (typeof keys[i] !== "string") throw bodyTypeMismatch("dig", i, "string", describeKind(keys[i]));
4028
+ return digFromDict(dict, def, keys, args.length);
4029
+ }
4030
+ function digFromDict(d, def, ks, argCount) {
4031
+ const k = ks[0];
4032
+ if (!Object.hasOwn(d, k)) return def;
4033
+ const step = d[k];
4034
+ if (ks.length === 1) return step;
4035
+ if (!isPlainDict(step)) throw bodyTypeMismatch("dig", argCount - 1, "dict at intermediate key", describeKind(step));
4036
+ return digFromDict(step, def, ks.slice(1), argCount);
4037
+ }
4038
+ function isPlainDict(v) {
4039
+ return v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Map) && !(v instanceof Set);
4040
+ }
4041
+ function describeKind(v) {
4042
+ if (v === null) return "null";
4043
+ if (Array.isArray(v)) return "array";
4044
+ if (v instanceof Map) return "Map";
4045
+ if (v instanceof Set) return "Set";
4046
+ return typeof v;
4047
+ }
4048
+ //#endregion
2658
4049
  //#region src/sprig/lists/first.ts
2659
4050
  function first(list) {
2660
4051
  return list[0];
@@ -2726,6 +4117,26 @@ function slice(list, i, j) {
2726
4117
  return list.slice(start, end);
2727
4118
  }
2728
4119
  //#endregion
4120
+ //#region src/sprig/lists/sortAlpha.ts
4121
+ /**
4122
+ * `sortAlpha list` — stringify each element, sort lexicographically.
4123
+ * Returns `string[]`.
4124
+ *
4125
+ * Mirrors Go sprig's `sortAlpha`, which calls `strslice` (skips nil
4126
+ * entries, stringifies the rest via `strval`) then `sort.StringSlice`.
4127
+ * `String(v)` lines up with Go's `%v` for primitives; non-ASCII byte
4128
+ * ordering is identical to Go's `sort.StringSlice` for ASCII input
4129
+ * (the only kind the conformance fixtures exercise).
4130
+ */
4131
+ function sortAlpha(list) {
4132
+ const out = [];
4133
+ for (const v of list) {
4134
+ if (v === null || v === void 0) continue;
4135
+ out.push(String(v));
4136
+ }
4137
+ return out.sort();
4138
+ }
4139
+ //#endregion
2729
4140
  //#region src/sprig/lists/uniq.ts
2730
4141
  /** Unique values, preserving first-occurrence order. */
2731
4142
  function uniq(list) {
@@ -2810,6 +4221,33 @@ function sprigLists() {
2810
4221
  append: {
2811
4222
  fn: (l, i) => append(l, i),
2812
4223
  argTypes: ["list", "value"]
4224
+ },
4225
+ sortAlpha: {
4226
+ fn: (l) => sortAlpha(l),
4227
+ argTypes: ["list"],
4228
+ returnType: "list"
4229
+ },
4230
+ push: {
4231
+ fn: (l, i) => append(l, i),
4232
+ argTypes: ["list", "value"]
4233
+ },
4234
+ tuple: {
4235
+ fn: (...a) => list(...a),
4236
+ argTypes: ["value"]
4237
+ },
4238
+ dig: {
4239
+ fn: (...a) => dig(...a),
4240
+ argTypes: ["value"]
4241
+ },
4242
+ all: {
4243
+ fn: (...a) => all(...a),
4244
+ argTypes: ["truthy"],
4245
+ returnType: "bool"
4246
+ },
4247
+ any: {
4248
+ fn: (...a) => any(...a),
4249
+ argTypes: ["truthy"],
4250
+ returnType: "bool"
2813
4251
  }
2814
4252
  };
2815
4253
  }
@@ -2817,80 +4255,187 @@ function sprigLists() {
2817
4255
  //#region src/sprig/math/add.ts
2818
4256
  /** `add a b c …` — variadic integer sum. */
2819
4257
  function add(...args) {
2820
- return args.reduce((acc, v) => acc + Math.trunc(Number(v)), 0);
4258
+ return args.reduce((acc, v) => acc + v, 0);
4259
+ }
4260
+ //#endregion
4261
+ //#region src/sprig/math/add1.ts
4262
+ /** `add1 n` — integer increment. Mirrors Go sprig's `add1(i interface{}) int64`. */
4263
+ function add1(n) {
4264
+ return n + 1;
4265
+ }
4266
+ //#endregion
4267
+ //#region src/sprig/math/add1f.ts
4268
+ /** `add1f n` — float increment. Mirrors Go sprig's `add1f(i interface{}) float64`. */
4269
+ function add1f(n) {
4270
+ return n + 1;
2821
4271
  }
2822
4272
  //#endregion
2823
4273
  //#region src/sprig/math/addf.ts
2824
4274
  function addf(...args) {
2825
- return args.reduce((acc, v) => acc + Number(v), 0);
4275
+ return args.reduce((acc, v) => acc + v, 0);
2826
4276
  }
2827
4277
  //#endregion
2828
4278
  //#region src/sprig/math/ceil.ts
2829
4279
  function ceil(a) {
2830
- return Math.ceil(Number(a));
4280
+ return Math.ceil(a);
2831
4281
  }
2832
4282
  //#endregion
2833
4283
  //#region src/sprig/math/div.ts
2834
4284
  /** `div a b` — integer division (Go semantics: truncate toward zero). */
2835
4285
  function div(a, b) {
2836
- return Math.trunc(Math.trunc(Number(a)) / Math.trunc(Number(b)));
4286
+ return Math.trunc(a / b);
2837
4287
  }
2838
4288
  //#endregion
2839
4289
  //#region src/sprig/math/divf.ts
2840
4290
  function divf(a, b) {
2841
- return Number(a) / Number(b);
4291
+ return a / b;
2842
4292
  }
2843
4293
  //#endregion
2844
4294
  //#region src/sprig/math/floor.ts
2845
4295
  function floor(a) {
2846
- return Math.floor(Number(a));
4296
+ return Math.floor(a);
2847
4297
  }
2848
4298
  //#endregion
2849
4299
  //#region src/sprig/math/max.ts
2850
- /** `max a b c …` — variadic maximum. */
4300
+ /** `max a b c …` — variadic maximum (Go int64 semantics; args arrive truncated). */
2851
4301
  function max(...args) {
2852
- return args.map((v) => Number(v)).reduce((m, v) => v > m ? v : m, Number.NEGATIVE_INFINITY);
4302
+ return args.reduce((m, v) => v > m ? v : m, Number.NEGATIVE_INFINITY);
4303
+ }
4304
+ //#endregion
4305
+ //#region src/sprig/math/maxf.ts
4306
+ /**
4307
+ * `maxf a b c …` — variadic float-typed maximum. Mirrors Go sprig's
4308
+ * `maxf` (float64, no truncation). Distinct from `max` (int64-truncated).
4309
+ */
4310
+ function maxf(...args) {
4311
+ return args.reduce((m, v) => Math.max(m, v), -Infinity);
2853
4312
  }
2854
4313
  //#endregion
2855
4314
  //#region src/sprig/math/min.ts
2856
- /** `min a b c …` — variadic minimum. */
4315
+ /** `min a b c …` — variadic minimum (Go int64 semantics; args arrive truncated). */
2857
4316
  function min(...args) {
2858
- return args.map((v) => Number(v)).reduce((m, v) => v < m ? v : m, Number.POSITIVE_INFINITY);
4317
+ return args.reduce((m, v) => v < m ? v : m, Number.POSITIVE_INFINITY);
4318
+ }
4319
+ //#endregion
4320
+ //#region src/sprig/math/minf.ts
4321
+ /** `minf a b c …` — variadic float-typed minimum. Float counterpart of `min` (int64-truncated). */
4322
+ function minf(...args) {
4323
+ return args.reduce((m, v) => Math.min(m, v), Infinity);
2859
4324
  }
2860
4325
  //#endregion
2861
4326
  //#region src/sprig/math/mod.ts
2862
4327
  /** `mod a b` — modulo. JS `%` matches Go's: sign follows the dividend. */
2863
4328
  function mod(a, b) {
2864
- return Math.trunc(Number(a)) % Math.trunc(Number(b));
4329
+ return a % b;
2865
4330
  }
2866
4331
  //#endregion
2867
4332
  //#region src/sprig/math/mul.ts
2868
4333
  /** `mul a b c …` — variadic integer product. */
2869
4334
  function mul(...args) {
2870
- return args.reduce((acc, v) => acc * Math.trunc(Number(v)), 1);
4335
+ return args.reduce((acc, v) => acc * v, 1);
2871
4336
  }
2872
4337
  //#endregion
2873
4338
  //#region src/sprig/math/mulf.ts
2874
4339
  function mulf(...args) {
2875
- return args.reduce((acc, v) => acc * Number(v), 1);
4340
+ return args.reduce((acc, v) => acc * v, 1);
2876
4341
  }
2877
4342
  //#endregion
2878
4343
  //#region src/sprig/math/round.ts
2879
4344
  /** `round a [precision=0]` — round half-away-from-zero, matching Go sprig. */
2880
4345
  function round(a, precision = 0) {
2881
- const n = Number(a);
2882
- const factor = 10 ** Math.trunc(Number(precision));
2883
- return Math.sign(n) * Math.round(Math.abs(n) * factor) / factor;
4346
+ const factor = 10 ** precision;
4347
+ return Math.sign(a) * Math.round(Math.abs(a) * factor) / factor;
4348
+ }
4349
+ //#endregion
4350
+ //#region src/sprig/math/untilStep.ts
4351
+ /**
4352
+ * `untilStep start stop step` — Python-`range`-shaped integer slice.
4353
+ * Mirrors Go sprig's `untilStep(start, stop, step int) []int`. Step
4354
+ * direction must agree with the start→stop direction; mismatched signs
4355
+ * (e.g. `start < stop` with `step <= 0`) yield an empty slice rather
4356
+ * than looping forever.
4357
+ */
4358
+ function untilStep(start, stop, step) {
4359
+ const v = [];
4360
+ if (stop < start) {
4361
+ if (step >= 0) return v;
4362
+ for (let i = start; i > stop; i += step) v.push(i);
4363
+ return v;
4364
+ }
4365
+ if (step <= 0) return v;
4366
+ for (let i = start; i < stop; i += step) v.push(i);
4367
+ return v;
4368
+ }
4369
+ //#endregion
4370
+ //#region src/sprig/math/seq.ts
4371
+ /**
4372
+ * `seq …` — space-joined integer sequence. Mirrors Go sprig's `seq`,
4373
+ * which dispatches on arity and is **inclusive** of the end value:
4374
+ *
4375
+ * seq() → ""
4376
+ * seq(end) → 1..end (descending if end<1)
4377
+ * seq(start, end) → start..end (step ±1 by direction)
4378
+ * seq(start, step, end) → stepped, end inclusive when reached
4379
+ * 4+ args → ""
4380
+ *
4381
+ * Inclusivity is implemented the same way Go does it — by passing
4382
+ * `end + increment` (or `end + step` for the 2-arg case) into the
4383
+ * exclusive `untilStep`. The 3-arg form returns "" when the bounds
4384
+ * descend (`end < start`) but the caller passes a positive step —
4385
+ * matching Go's early-return at `if step > 0 { return "" }`.
4386
+ *
4387
+ * Output is the int slice joined with " ", so `{{ seq 5 }}` emits
4388
+ * `1 2 3 4 5`. Result type is `string`, **not** `number[]`.
4389
+ */
4390
+ function seq(...params) {
4391
+ let increment = 1;
4392
+ switch (params.length) {
4393
+ case 0: return "";
4394
+ case 1: {
4395
+ const start = 1;
4396
+ const end = params[0];
4397
+ if (end < start) increment = -1;
4398
+ return untilStep(start, end + increment, increment).join(" ");
4399
+ }
4400
+ case 2: {
4401
+ const start = params[0];
4402
+ const end = params[1];
4403
+ const step = end < start ? -1 : 1;
4404
+ return untilStep(start, end + step, step).join(" ");
4405
+ }
4406
+ case 3: {
4407
+ const start = params[0];
4408
+ const step = params[1];
4409
+ const end = params[2];
4410
+ if (end < start) {
4411
+ increment = -1;
4412
+ if (step > 0) return "";
4413
+ }
4414
+ return untilStep(start, end + increment, step).join(" ");
4415
+ }
4416
+ default: return "";
4417
+ }
2884
4418
  }
2885
4419
  //#endregion
2886
4420
  //#region src/sprig/math/sub.ts
2887
4421
  function sub(a, b) {
2888
- return Math.trunc(Number(a)) - Math.trunc(Number(b));
4422
+ return a - b;
2889
4423
  }
2890
4424
  //#endregion
2891
4425
  //#region src/sprig/math/subf.ts
2892
4426
  function subf(a, b) {
2893
- return Number(a) - Number(b);
4427
+ return a - b;
4428
+ }
4429
+ //#endregion
4430
+ //#region src/sprig/math/until.ts
4431
+ /**
4432
+ * `until count` — `[0, 1, …, count-1]` for positive counts, or
4433
+ * `[0, -1, …, count+1]` for negative counts. Mirrors Go sprig's
4434
+ * `until`, which derives step direction from the sign of `count`
4435
+ * and delegates to `untilStep`.
4436
+ */
4437
+ function until(count) {
4438
+ return untilStep(0, count, count < 0 ? -1 : 1);
2894
4439
  }
2895
4440
  //#endregion
2896
4441
  //#region src/sprig/math/index.ts
@@ -2898,59 +4443,220 @@ function sprigMath() {
2898
4443
  return {
2899
4444
  add: {
2900
4445
  fn: (...a) => add(...a),
2901
- argTypes: ["number"]
4446
+ argTypes: ["int"]
2902
4447
  },
2903
4448
  sub: {
2904
4449
  fn: (a, b) => sub(a, b),
2905
- argTypes: ["number", "number"]
4450
+ argTypes: ["int", "int"]
2906
4451
  },
2907
4452
  mul: {
2908
4453
  fn: (...a) => mul(...a),
2909
- argTypes: ["number"]
4454
+ argTypes: ["int"]
2910
4455
  },
2911
4456
  div: {
2912
4457
  fn: (a, b) => div(a, b),
2913
- argTypes: ["number", "number"]
4458
+ argTypes: ["int", "int"]
2914
4459
  },
2915
4460
  mod: {
2916
4461
  fn: (a, b) => mod(a, b),
2917
- argTypes: ["number", "number"]
4462
+ argTypes: ["int", "int"]
2918
4463
  },
2919
4464
  min: {
2920
4465
  fn: (...a) => min(...a),
2921
- argTypes: ["number"]
4466
+ argTypes: ["int"]
2922
4467
  },
2923
4468
  max: {
2924
4469
  fn: (...a) => max(...a),
2925
- argTypes: ["number"]
4470
+ argTypes: ["int"]
2926
4471
  },
2927
4472
  floor: {
2928
4473
  fn: (a) => floor(a),
2929
- argTypes: ["number"]
4474
+ argTypes: ["float"]
2930
4475
  },
2931
4476
  ceil: {
2932
4477
  fn: (a) => ceil(a),
2933
- argTypes: ["number"]
4478
+ argTypes: ["float"]
2934
4479
  },
2935
4480
  round: {
2936
4481
  fn: (a, p) => round(a, p),
2937
- argTypes: ["number", "number"]
4482
+ argTypes: ["float", "int"]
2938
4483
  },
2939
4484
  addf: {
2940
4485
  fn: (...a) => addf(...a),
2941
- argTypes: ["number"]
4486
+ argTypes: ["float"]
2942
4487
  },
2943
4488
  subf: {
2944
4489
  fn: (a, b) => subf(a, b),
2945
- argTypes: ["number", "number"]
4490
+ argTypes: ["float", "float"]
2946
4491
  },
2947
4492
  mulf: {
2948
4493
  fn: (...a) => mulf(...a),
2949
- argTypes: ["number"]
4494
+ argTypes: ["float"]
2950
4495
  },
2951
4496
  divf: {
2952
4497
  fn: (a, b) => divf(a, b),
4498
+ argTypes: ["float", "float"]
4499
+ },
4500
+ add1: {
4501
+ fn: (n) => add1(n),
4502
+ argTypes: ["int"]
4503
+ },
4504
+ add1f: {
4505
+ fn: (n) => add1f(n),
4506
+ argTypes: ["float"]
4507
+ },
4508
+ maxf: {
4509
+ fn: (...a) => maxf(...a),
4510
+ argTypes: ["float"]
4511
+ },
4512
+ minf: {
4513
+ fn: (...a) => minf(...a),
4514
+ argTypes: ["float"]
4515
+ },
4516
+ biggest: {
4517
+ fn: (...a) => max(...a),
4518
+ argTypes: ["int"]
4519
+ },
4520
+ seq: {
4521
+ fn: (...a) => seq(...a),
4522
+ argTypes: ["int"],
4523
+ returnType: "string"
4524
+ },
4525
+ until: {
4526
+ fn: (n) => until(n),
4527
+ argTypes: ["int"],
4528
+ returnType: "list"
4529
+ },
4530
+ untilStep: {
4531
+ fn: (a, b, c) => untilStep(a, b, c),
4532
+ argTypes: [
4533
+ "int",
4534
+ "int",
4535
+ "int"
4536
+ ],
4537
+ returnType: "list"
4538
+ }
4539
+ };
4540
+ }
4541
+ //#endregion
4542
+ //#region src/sprig/random/_prng.ts
4543
+ /**
4544
+ * Internal PRNG seam for sprig random functions.
4545
+ *
4546
+ * [LAW:single-enforcer] All randomness in this module routes through
4547
+ * the `random` parameter — never through `Math.random` directly. The
4548
+ * caller supplies the source; these helpers consume it.
4549
+ */
4550
+ var RandIntRangeError = class extends Error {
4551
+ constructor(min, max) {
4552
+ super(`randIntFromRange: max must be greater than min (max=${max}, min=${min})`);
4553
+ this.name = "RandIntRangeError";
4554
+ }
4555
+ };
4556
+ /** Clamp PRNG output to [0, 1) to defend against out-of-range injected sources. */
4557
+ function clampRandom(value) {
4558
+ if (!Number.isFinite(value)) return 0;
4559
+ return Math.max(0, Math.min(value, .9999999999999999));
4560
+ }
4561
+ const ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
4562
+ const ALPHANUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
4563
+ const NUMERIC = "0123456789";
4564
+ const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)).join("");
4565
+ function randString(n, charset, random) {
4566
+ const chars = [];
4567
+ for (let i = 0; i < n; i++) chars.push(charset.charAt(Math.floor(clampRandom(random()) * charset.length)));
4568
+ return chars.join("");
4569
+ }
4570
+ /** Inclusive `min`, exclusive `max` — mirrors Go `rand.Intn(max-min)+min`. */
4571
+ function randIntFromRange(min, max, random) {
4572
+ if (max <= min) throw new RandIntRangeError(min, max);
4573
+ return Math.floor(clampRandom(random()) * (max - min)) + min;
4574
+ }
4575
+ //#endregion
4576
+ //#region src/sprig/random/randAlpha.ts
4577
+ /** `randAlpha n` — `n` random letters [A-Za-z]. */
4578
+ function randAlpha(n, random) {
4579
+ return randString(Number(n), ALPHA, random);
4580
+ }
4581
+ //#endregion
4582
+ //#region src/sprig/random/randAlphaNum.ts
4583
+ /** `randAlphaNum n` — `n` random alphanumeric characters [A-Za-z0-9]. */
4584
+ function randAlphaNum(n, random) {
4585
+ return randString(Number(n), ALPHANUM, random);
4586
+ }
4587
+ //#endregion
4588
+ //#region src/sprig/random/randAscii.ts
4589
+ /** `randAscii n` — `n` random printable ASCII characters (0x20–0x7E). */
4590
+ function randAscii(n, random) {
4591
+ return randString(Number(n), ASCII, random);
4592
+ }
4593
+ //#endregion
4594
+ //#region src/sprig/random/randInt.ts
4595
+ /** `randInt min max` — random integer in [min, max). Mirrors Go sprig. */
4596
+ function randInt(min, max, random) {
4597
+ try {
4598
+ return randIntFromRange(Number(min), Number(max), random);
4599
+ } catch (e) {
4600
+ if (e instanceof RandIntRangeError) throw bodyTypeMismatch("randInt", 1, "max > min", `constraint violated (max=${Number(max)}, min=${Number(min)})`);
4601
+ throw e;
4602
+ }
4603
+ }
4604
+ //#endregion
4605
+ //#region src/sprig/random/randNumeric.ts
4606
+ /** `randNumeric n` — `n` random decimal digits [0-9]. */
4607
+ function randNumeric(n, random) {
4608
+ return randString(Number(n), NUMERIC, random);
4609
+ }
4610
+ //#endregion
4611
+ //#region src/sprig/random/shuffle.ts
4612
+ /**
4613
+ * `shuffle s` — returns a randomly permuted copy of `s`.
4614
+ *
4615
+ * Operates on Unicode code points (matching Go sprig's rune-level Fisher-Yates).
4616
+ */
4617
+ function shuffle(s, random) {
4618
+ const runes = [...s];
4619
+ for (let i = runes.length - 1; i > 0; i--) {
4620
+ const j = Math.floor(clampRandom(random()) * (i + 1));
4621
+ const tmp = runes[i];
4622
+ runes[i] = runes[j];
4623
+ runes[j] = tmp;
4624
+ }
4625
+ return runes.join("");
4626
+ }
4627
+ //#endregion
4628
+ //#region src/sprig/random/index.ts
4629
+ /**
4630
+ * Build the sprig random FuncMap.
4631
+ *
4632
+ * @param random - PRNG source. Defaults to `Math.random`. Pass a seeded
4633
+ * generator for reproducible templates (matches `EngineConfig.random`).
4634
+ */
4635
+ function sprigRandom(random = Math.random) {
4636
+ return {
4637
+ randInt: {
4638
+ fn: (min, max) => randInt(min, max, random),
2953
4639
  argTypes: ["number", "number"]
4640
+ },
4641
+ randAlpha: {
4642
+ fn: (n) => randAlpha(n, random),
4643
+ argTypes: ["number"]
4644
+ },
4645
+ randAlphaNum: {
4646
+ fn: (n) => randAlphaNum(n, random),
4647
+ argTypes: ["number"]
4648
+ },
4649
+ randNumeric: {
4650
+ fn: (n) => randNumeric(n, random),
4651
+ argTypes: ["number"]
4652
+ },
4653
+ randAscii: {
4654
+ fn: (n) => randAscii(n, random),
4655
+ argTypes: ["number"]
4656
+ },
4657
+ shuffle: {
4658
+ fn: (s) => shuffle(s, random),
4659
+ argTypes: ["string"]
2954
4660
  }
2955
4661
  };
2956
4662
  }
@@ -3059,6 +4765,199 @@ function sprigRegex() {
3059
4765
  };
3060
4766
  }
3061
4767
  //#endregion
4768
+ //#region src/sprig/semver/parse.ts
4769
+ /**
4770
+ * SemVer parsing and comparison utilities.
4771
+ *
4772
+ * Mirrors Masterminds/semver v3 semantics used by Go sprig:
4773
+ * - Optional v prefix; missing minor/patch default to 0
4774
+ * - Standard semver 2.0.0 ordering: major.minor.patch then pre-release
4775
+ * - Release (no pre-release) > pre-release of same version
4776
+ *
4777
+ * [LAW:one-source-of-truth] One parser, one comparator. Constraint
4778
+ * evaluation imports from here rather than re-implementing comparison.
4779
+ */
4780
+ const VERSION_RE = /^v?(\d+)(?:\.(\d+)(?:\.(\d+))?)?(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
4781
+ function parseSemVer(s) {
4782
+ const input = s.trim();
4783
+ const m = VERSION_RE.exec(input);
4784
+ if (!m) throw new Error(`invalid semver: ${JSON.stringify(s)}`);
4785
+ return {
4786
+ Major: parseInt(m[1] ?? "0", 10),
4787
+ Minor: m[2] !== void 0 ? parseInt(m[2], 10) : 0,
4788
+ Patch: m[3] !== void 0 ? parseInt(m[3], 10) : 0,
4789
+ Prerelease: m[4] ?? "",
4790
+ Metadata: m[5] ?? "",
4791
+ Original: input
4792
+ };
4793
+ }
4794
+ /** Returns negative if a < b, 0 if equal, positive if a > b. */
4795
+ function compareSemVer(a, b) {
4796
+ const d = a.Major - b.Major || a.Minor - b.Minor || a.Patch - b.Patch;
4797
+ if (d !== 0) return d;
4798
+ return comparePrerelease(a.Prerelease, b.Prerelease);
4799
+ }
4800
+ function comparePrerelease(a, b) {
4801
+ if (a === b) return 0;
4802
+ if (a === "") return 1;
4803
+ if (b === "") return -1;
4804
+ const aParts = a.split(".");
4805
+ const bParts = b.split(".");
4806
+ for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
4807
+ const ap = aParts[i];
4808
+ const bp = bParts[i];
4809
+ if (ap === void 0) return -1;
4810
+ if (bp === void 0) return 1;
4811
+ const an = /^\d+$/.test(ap) ? parseInt(ap, 10) : null;
4812
+ const bn = /^\d+$/.test(bp) ? parseInt(bp, 10) : null;
4813
+ if (an !== null && bn !== null) {
4814
+ if (an !== bn) return an - bn;
4815
+ } else if (an !== null) return -1;
4816
+ else if (bn !== null) return 1;
4817
+ else {
4818
+ if (ap < bp) return -1;
4819
+ if (ap > bp) return 1;
4820
+ }
4821
+ }
4822
+ return 0;
4823
+ }
4824
+ //#endregion
4825
+ //#region src/sprig/semver/semver.ts
4826
+ /**
4827
+ * `semver s` — parse a semver string into a struct with Major, Minor,
4828
+ * Patch, Prerelease, Metadata, Original fields.
4829
+ *
4830
+ * Mirrors Go sprig's `semver` which wraps Masterminds/semver v3's
4831
+ * `NewVersion`. Template field access (`.Major`, `.Prerelease`, etc.)
4832
+ * maps to the same-named keys on the returned object.
4833
+ *
4834
+ * Throws on invalid input — matches Go's behaviour where `semver` returns
4835
+ * (Version, error) and sprig panics on error.
4836
+ */
4837
+ function semver(s) {
4838
+ return parseSemVer(s);
4839
+ }
4840
+ //#endregion
4841
+ //#region src/sprig/semver/constraint.ts
4842
+ /**
4843
+ * Masterminds/semver v3-compatible constraint parsing and evaluation.
4844
+ *
4845
+ * Supports operators: =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), "" (=).
4846
+ * AND groups: comma- or whitespace-separated.
4847
+ * OR groups: || separated.
4848
+ *
4849
+ * [LAW:types-are-the-program] A constraint IS a predicate function —
4850
+ * parsing produces (v: SemVer) => boolean directly. No intermediate
4851
+ * structural representation is needed at the call site.
4852
+ */
4853
+ const TOKEN_RE = /(!=|>=|<=|>|<|~|\^|=)?\s*(v?\d[^\s,]*)/g;
4854
+ function parseConstraintExpr(s) {
4855
+ const orGroups = s.split(/\|\|/).map((p) => p.trim()).filter(Boolean);
4856
+ if (orGroups.length === 0) throw new Error(`empty constraint: ${JSON.stringify(s)}`);
4857
+ const preds = orGroups.map(parseAndGroup);
4858
+ return (v) => preds.some((p) => p(v));
4859
+ }
4860
+ function parseAndGroup(s) {
4861
+ const preds = [];
4862
+ let consumed = 0;
4863
+ for (const m of s.matchAll(TOKEN_RE)) {
4864
+ const gap = s.slice(consumed, m.index);
4865
+ if (gap.length > 0 && !/^[,\s]*$/.test(gap)) throw new Error(`unexpected characters in constraint: ${JSON.stringify(gap)}`);
4866
+ preds.push(buildSingle(m[1] ?? "", m[2] ?? ""));
4867
+ consumed = (m.index ?? 0) + m[0].length;
4868
+ }
4869
+ if (preds.length === 0) throw new Error(`no constraint tokens in: ${JSON.stringify(s)}`);
4870
+ const remaining = s.slice(consumed).trim();
4871
+ if (remaining.length > 0) throw new Error(`unexpected characters in constraint: ${JSON.stringify(remaining)}`);
4872
+ return (v) => preds.every((p) => p(v));
4873
+ }
4874
+ function countComponents(vstr) {
4875
+ const core = vstr.replace(/^v/, "").replace(/[-+].*$/, "");
4876
+ return Math.min(core.split(".").length, 3);
4877
+ }
4878
+ function makeSemVer(major, minor, patch, pre) {
4879
+ return {
4880
+ Major: major,
4881
+ Minor: minor,
4882
+ Patch: patch,
4883
+ Prerelease: pre,
4884
+ Metadata: "",
4885
+ Original: pre ? `${major}.${minor}.${patch}-${pre}` : `${major}.${minor}.${patch}`
4886
+ };
4887
+ }
4888
+ function preReleaseCheck(v, constraint) {
4889
+ if (v.Prerelease === "") return true;
4890
+ if (constraint.Prerelease !== "") return v.Major === constraint.Major && v.Minor === constraint.Minor && v.Patch === constraint.Patch;
4891
+ return false;
4892
+ }
4893
+ function buildSingle(op, vstr) {
4894
+ const cv = parseSemVer(vstr);
4895
+ const components = countComponents(vstr);
4896
+ const minorDirty = components < 2;
4897
+ const patchDirty = components < 3;
4898
+ switch (op) {
4899
+ case "":
4900
+ case "=": return (v) => compareSemVer(v, cv) === 0;
4901
+ case "!=": return (v) => compareSemVer(v, cv) !== 0;
4902
+ case ">": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) > 0;
4903
+ case ">=": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0;
4904
+ case "<": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) < 0;
4905
+ case "<=": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) <= 0;
4906
+ case "~": return buildTilde(cv, minorDirty);
4907
+ case "^": return buildCaret(cv, minorDirty, patchDirty);
4908
+ default: throw new Error(`unknown constraint operator: ${JSON.stringify(op)}`);
4909
+ }
4910
+ }
4911
+ function buildTilde(cv, minorDirty) {
4912
+ if (minorDirty) {
4913
+ const lower = makeSemVer(cv.Major, 0, 0, cv.Prerelease);
4914
+ const upper = makeSemVer(cv.Major + 1, 0, 0, "");
4915
+ return (v) => preReleaseCheck(v, lower) && compareSemVer(v, lower) >= 0 && compareSemVer(v, upper) < 0;
4916
+ }
4917
+ const upper = makeSemVer(cv.Major, cv.Minor + 1, 0, "");
4918
+ return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;
4919
+ }
4920
+ function buildCaret(cv, minorDirty, patchDirty) {
4921
+ let upper;
4922
+ if (minorDirty) upper = makeSemVer(cv.Major + 1, 0, 0, "");
4923
+ else if (cv.Major > 0) upper = makeSemVer(cv.Major + 1, 0, 0, "");
4924
+ else if (cv.Minor > 0) upper = makeSemVer(0, cv.Minor + 1, 0, "");
4925
+ else if (patchDirty) upper = makeSemVer(0, 1, 0, "");
4926
+ else upper = makeSemVer(0, 0, cv.Patch + 1, "");
4927
+ return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;
4928
+ }
4929
+ //#endregion
4930
+ //#region src/sprig/semver/semverCompare.ts
4931
+ /**
4932
+ * `semverCompare constraint version` — returns true iff `version`
4933
+ * satisfies `constraint`.
4934
+ *
4935
+ * Constraint syntax follows Masterminds/semver v3 (Go sprig's semver
4936
+ * library): =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), || for OR,
4937
+ * comma/space for AND.
4938
+ *
4939
+ * Note: Go sprig's argument order is (constraint, version) — the
4940
+ * constraint comes first.
4941
+ */
4942
+ function semverCompare(constraint, version) {
4943
+ return parseConstraintExpr(constraint)(parseSemVer(version));
4944
+ }
4945
+ //#endregion
4946
+ //#region src/sprig/semver/index.ts
4947
+ function sprigSemver() {
4948
+ return {
4949
+ semver: {
4950
+ fn: (s) => semver(s),
4951
+ argTypes: ["string"]
4952
+ },
4953
+ semverCompare: {
4954
+ fn: (constraint, version) => semverCompare(constraint, version),
4955
+ argTypes: ["string", "string"],
4956
+ returnType: "bool"
4957
+ }
4958
+ };
4959
+ }
4960
+ //#endregion
3062
4961
  //#region src/sprig/strings/abbrev.ts
3063
4962
  /**
3064
4963
  * `abbrev width s` — truncate `s` to `width` chars, replacing the tail
@@ -3999,6 +5898,6 @@ function sprigTypes() {
3999
5898
  };
4000
5899
  }
4001
5900
  //#endregion
4002
- export { Engine, EvalError, FuncNotFoundError, MissingFieldError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDefaults, sprigDicts, sprigLists, sprigMath, sprigRegex, sprigStrings, sprigTypes };
5901
+ export { Engine, EvalError, FailError, FuncNotFoundError, MissingFieldError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDatetime, sprigDefaults, sprigDicts, sprigFlow, sprigHash, sprigLists, sprigMath, sprigRandom, sprigRegex, sprigSemver, sprigStrings, sprigTypes };
4003
5902
 
4004
5903
  //# sourceMappingURL=index.js.map