@promptctl/go-template-js 0.1.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -9
- package/dist/index.d.ts +149 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2223 -324
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
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
|
|
176
|
-
|
|
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(
|
|
234
|
-
const trimLeft = end < this.src.length && this.src[end +
|
|
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(
|
|
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 ?
|
|
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(
|
|
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(
|
|
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(
|
|
318
|
+
if (this.src.startsWith(`-${this.rightDelim}`, this.offset)) {
|
|
288
319
|
const start = this.pos();
|
|
289
|
-
this.advanceBy(
|
|
320
|
+
this.advanceBy(1 + this.rightDelim.length);
|
|
290
321
|
this.mode = "text";
|
|
291
|
-
|
|
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(
|
|
325
|
+
if (this.src.startsWith(this.rightDelim, this.offset)) {
|
|
294
326
|
const start = this.pos();
|
|
295
|
-
this.advanceBy(
|
|
327
|
+
this.advanceBy(this.rightDelim.length);
|
|
296
328
|
this.mode = "text";
|
|
297
|
-
|
|
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
|
-
|
|
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
|
|
1115
|
-
*
|
|
1116
|
-
*
|
|
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");
|
|
@@ -1268,11 +1335,11 @@ function eagerBuiltins(toString) {
|
|
|
1268
1335
|
},
|
|
1269
1336
|
slice: {
|
|
1270
1337
|
fn: (collection, ...indices) => {
|
|
1271
|
-
const i = indices.length >= 1 ?
|
|
1272
|
-
const j = indices.length >= 2 ?
|
|
1338
|
+
const i = indices.length >= 1 ? indices[0] : 0;
|
|
1339
|
+
const j = indices.length >= 2 ? indices[1] : void 0;
|
|
1273
1340
|
return typeof collection === "string" ? collection.slice(i, j) : collection.slice(i, j);
|
|
1274
1341
|
},
|
|
1275
|
-
argTypes: ["sliceable", "
|
|
1342
|
+
argTypes: ["sliceable", "int"]
|
|
1276
1343
|
},
|
|
1277
1344
|
print: {
|
|
1278
1345
|
fn: (...args) => goPrint(args, toString),
|
|
@@ -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
|
+
"\"": """,
|
|
1491
|
+
"'": "'",
|
|
1492
|
+
"&": "&",
|
|
1493
|
+
"<": "<",
|
|
1494
|
+
">": ">"
|
|
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
|
-
|
|
1711
|
-
if (
|
|
1712
|
-
|
|
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
|
-
|
|
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) {
|
|
@@ -1784,6 +1934,7 @@ var Engine = class {
|
|
|
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
|
}
|
|
@@ -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
|
|
1816
|
-
|
|
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] ?? "$";
|
|
@@ -1876,6 +2027,8 @@ function enforceArgTypes(funcName, argTypes, values, pos, src, toString = defaul
|
|
|
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 });
|
|
1878
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);
|
|
1879
2032
|
if (declared === "ordered") {
|
|
1880
2033
|
if (firstOrdered === -1) firstOrdered = i;
|
|
1881
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,7 +2054,8 @@ function matchesArgType(declared, value, toString) {
|
|
|
1901
2054
|
case "reflective":
|
|
1902
2055
|
case "value": return true;
|
|
1903
2056
|
case "string": return typeof value === "string";
|
|
1904
|
-
case "
|
|
2057
|
+
case "int": return typeof value === "number" && Number.isFinite(value) || typeof value === "bigint" && Number.isSafeInteger(Number(value));
|
|
2058
|
+
case "float": return typeof value === "number" || typeof value === "bigint" && Number.isFinite(Number(value));
|
|
1905
2059
|
case "bool": return typeof value === "boolean";
|
|
1906
2060
|
case "ordered": return typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean";
|
|
1907
2061
|
case "T": return value !== null && value !== void 0 && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint" && typeof value !== "symbol";
|
|
@@ -1923,6 +2077,7 @@ function matchesArgType(declared, value, toString) {
|
|
|
1923
2077
|
}
|
|
1924
2078
|
case "liftable": return typeof value === "string" || value !== null && value !== void 0 && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint" && typeof value !== "symbol";
|
|
1925
2079
|
case "serializable": return isJsonSerializable(value);
|
|
2080
|
+
default: throw new Error(`invalid ArgType: ${String(declared)}`);
|
|
1926
2081
|
}
|
|
1927
2082
|
}
|
|
1928
2083
|
function defaultFromString(s) {
|
|
@@ -1976,6 +2131,8 @@ function comparableKind(v) {
|
|
|
1976
2131
|
}
|
|
1977
2132
|
function humanArgType(t) {
|
|
1978
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)";
|
|
1979
2136
|
case "T": return "T (consumer-defined fragment)";
|
|
1980
2137
|
case "ordered": return "orderable primitive";
|
|
1981
2138
|
case "list": return "list";
|
|
@@ -1993,8 +2150,8 @@ function humanArgType(t) {
|
|
|
1993
2150
|
case "reflective":
|
|
1994
2151
|
case "value":
|
|
1995
2152
|
case "string":
|
|
1996
|
-
case "number":
|
|
1997
2153
|
case "bool": return t;
|
|
2154
|
+
default: throw new Error(`invalid ArgType: ${String(t)}`);
|
|
1998
2155
|
}
|
|
1999
2156
|
}
|
|
2000
2157
|
function describeValue(value) {
|
|
@@ -2059,7 +2216,7 @@ function numberValue(n) {
|
|
|
2059
2216
|
function atoi(s) {
|
|
2060
2217
|
if (!/^[+-]?\d+$/.test(s)) return 0;
|
|
2061
2218
|
const n = Number.parseInt(s, 10);
|
|
2062
|
-
return Number.
|
|
2219
|
+
return Number.isSafeInteger(n) ? n : 0;
|
|
2063
2220
|
}
|
|
2064
2221
|
//#endregion
|
|
2065
2222
|
//#region src/sprig/conversions/float64.ts
|
|
@@ -2144,13 +2301,19 @@ function parseBase0(s) {
|
|
|
2144
2301
|
* parseable → 0.
|
|
2145
2302
|
*/
|
|
2146
2303
|
function int(v) {
|
|
2147
|
-
if (typeof v === "number")
|
|
2148
|
-
|
|
2304
|
+
if (typeof v === "number") {
|
|
2305
|
+
const n = Math.trunc(v);
|
|
2306
|
+
return Number.isSafeInteger(n) ? n : 0;
|
|
2307
|
+
}
|
|
2308
|
+
if (typeof v === "bigint") {
|
|
2309
|
+
const n = Number(v);
|
|
2310
|
+
return Number.isSafeInteger(n) ? n : 0;
|
|
2311
|
+
}
|
|
2149
2312
|
if (typeof v === "string") {
|
|
2150
2313
|
const parsed = parseBase0(v);
|
|
2151
2314
|
if (parsed === null) return 0;
|
|
2152
|
-
const n = Number.parseInt(parsed.digits, parsed.base);
|
|
2153
|
-
return Number.
|
|
2315
|
+
const n = parsed.sign * Number.parseInt(parsed.digits, parsed.base);
|
|
2316
|
+
return Number.isSafeInteger(n) ? n : 0;
|
|
2154
2317
|
}
|
|
2155
2318
|
if (typeof v === "boolean") return v ? 1 : 0;
|
|
2156
2319
|
return 0;
|
|
@@ -2162,7 +2325,15 @@ function int(v) {
|
|
|
2162
2325
|
* full Go-`int64` precision survives the round-trip (a JS `number`
|
|
2163
2326
|
* loses precision past 2^53).
|
|
2164
2327
|
*
|
|
2165
|
-
*
|
|
2328
|
+
* Shares `parseBase0`'s base-detect + sign rules with `int`, so the
|
|
2329
|
+
* input shape (what string forms are recognized) is the same. The
|
|
2330
|
+
* **carrier** differs — `int` returns a JS `number` and applies a
|
|
2331
|
+
* `Number.isSafeInteger` clamp on output so the returned value
|
|
2332
|
+
* round-trips without precision loss; `int64`'s `bigint` carrier
|
|
2333
|
+
* holds the full int64 range, so no clamp is needed and string
|
|
2334
|
+
* forms like `"9007199254740993"` (past 2^53) survive unchanged.
|
|
2335
|
+
* The divergence is intentional: the carrier *forces* the precision
|
|
2336
|
+
* policy at this boundary, not the other way around.
|
|
2166
2337
|
*/
|
|
2167
2338
|
function int64(v) {
|
|
2168
2339
|
if (typeof v === "bigint") return v;
|
|
@@ -2196,8 +2367,8 @@ function toDecimal(s) {
|
|
|
2196
2367
|
if (!/^[+-]?[0-7]+$/.test(s)) return 0;
|
|
2197
2368
|
const sign = s[0] === "-" ? -1 : 1;
|
|
2198
2369
|
const body = s[0] === "+" || s[0] === "-" ? s.slice(1) : s;
|
|
2199
|
-
const n = Number.parseInt(body, 8);
|
|
2200
|
-
return Number.
|
|
2370
|
+
const n = sign * Number.parseInt(body, 8);
|
|
2371
|
+
return Number.isSafeInteger(n) ? n : 0;
|
|
2201
2372
|
}
|
|
2202
2373
|
//#endregion
|
|
2203
2374
|
//#region src/sprig/conversions/toRawJson.ts
|
|
@@ -2243,12 +2414,12 @@ function sprigConversions() {
|
|
|
2243
2414
|
atoi: {
|
|
2244
2415
|
fn: (s) => atoi(s),
|
|
2245
2416
|
argTypes: ["string"],
|
|
2246
|
-
returnType: "
|
|
2417
|
+
returnType: "int"
|
|
2247
2418
|
},
|
|
2248
2419
|
int: {
|
|
2249
2420
|
fn: (v) => int(v),
|
|
2250
2421
|
argTypes: ["value"],
|
|
2251
|
-
returnType: "
|
|
2422
|
+
returnType: "int"
|
|
2252
2423
|
},
|
|
2253
2424
|
int64: {
|
|
2254
2425
|
fn: (v) => int64(v),
|
|
@@ -2257,7 +2428,7 @@ function sprigConversions() {
|
|
|
2257
2428
|
float64: {
|
|
2258
2429
|
fn: (v) => float64(v),
|
|
2259
2430
|
argTypes: ["value"],
|
|
2260
|
-
returnType: "
|
|
2431
|
+
returnType: "float"
|
|
2261
2432
|
},
|
|
2262
2433
|
toString: {
|
|
2263
2434
|
fn: (v) => toString(v),
|
|
@@ -2271,7 +2442,7 @@ function sprigConversions() {
|
|
|
2271
2442
|
toDecimal: {
|
|
2272
2443
|
fn: (s) => toDecimal(s),
|
|
2273
2444
|
argTypes: ["string"],
|
|
2274
|
-
returnType: "
|
|
2445
|
+
returnType: "int"
|
|
2275
2446
|
},
|
|
2276
2447
|
toRawJson: {
|
|
2277
2448
|
fn: (v) => toRawJson(v),
|
|
@@ -2281,176 +2452,1111 @@ function sprigConversions() {
|
|
|
2281
2452
|
};
|
|
2282
2453
|
}
|
|
2283
2454
|
//#endregion
|
|
2284
|
-
//#region src/sprig/
|
|
2455
|
+
//#region src/sprig/datetime/_duration.ts
|
|
2285
2456
|
/**
|
|
2286
|
-
*
|
|
2287
|
-
* nil, false, 0, 0.0, "", empty array/Map/object.
|
|
2457
|
+
* Go-style duration: parsing and formatting.
|
|
2288
2458
|
*
|
|
2289
|
-
*
|
|
2290
|
-
*
|
|
2459
|
+
* Go's `time.ParseDuration` grammar:
|
|
2460
|
+
* duration = [-] component+
|
|
2461
|
+
* component = decimal unit
|
|
2462
|
+
* unit = ns | us | µs | ms | s | m | h
|
|
2463
|
+
*
|
|
2464
|
+
* Values are nanoseconds internally (same as Go's time.Duration).
|
|
2465
|
+
*
|
|
2466
|
+
* [LAW:one-source-of-truth] All duration string ↔ nanoseconds
|
|
2467
|
+
* conversions live here. No other file does this math.
|
|
2291
2468
|
*/
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
if (typeof value === "object") return Object.keys(value).length === 0;
|
|
2302
|
-
return false;
|
|
2303
|
-
}
|
|
2304
|
-
//#endregion
|
|
2305
|
-
//#region src/sprig/defaults/coalesce.ts
|
|
2469
|
+
const NS_PER = {
|
|
2470
|
+
h: 36e11,
|
|
2471
|
+
m: 6e10,
|
|
2472
|
+
s: 1e9,
|
|
2473
|
+
ms: 1e6,
|
|
2474
|
+
us: 1e3,
|
|
2475
|
+
µs: 1e3,
|
|
2476
|
+
ns: 1
|
|
2477
|
+
};
|
|
2306
2478
|
/**
|
|
2307
|
-
*
|
|
2308
|
-
*
|
|
2479
|
+
* Parse a Go duration string to nanoseconds (as a float for sub-ms
|
|
2480
|
+
* precision). Returns `NaN` on parse failure.
|
|
2481
|
+
*
|
|
2482
|
+
* Accepts: "0", "300ms", "1.5h", "2h45m", "-1h30m", "100µs".
|
|
2309
2483
|
*/
|
|
2310
|
-
function
|
|
2311
|
-
|
|
2484
|
+
function parseDurationNs(s) {
|
|
2485
|
+
if (s === "0") return 0;
|
|
2486
|
+
let negative = false;
|
|
2487
|
+
let rest = s;
|
|
2488
|
+
if (rest.startsWith("-")) {
|
|
2489
|
+
negative = true;
|
|
2490
|
+
rest = rest.slice(1);
|
|
2491
|
+
} else if (rest.startsWith("+")) rest = rest.slice(1);
|
|
2492
|
+
if (!rest) return NaN;
|
|
2493
|
+
let total = 0;
|
|
2494
|
+
const UNIT_RE = /^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;
|
|
2495
|
+
while (rest.length > 0) {
|
|
2496
|
+
const m = UNIT_RE.exec(rest);
|
|
2497
|
+
if (!m) return NaN;
|
|
2498
|
+
const value = parseFloat(m[1] ?? "0");
|
|
2499
|
+
const unit = m[2];
|
|
2500
|
+
total += value * NS_PER[unit];
|
|
2501
|
+
rest = rest.slice(m[0].length);
|
|
2502
|
+
}
|
|
2503
|
+
return negative ? -total : total;
|
|
2312
2504
|
}
|
|
2313
|
-
//#endregion
|
|
2314
|
-
//#region src/sprig/defaults/default.ts
|
|
2315
2505
|
/**
|
|
2316
|
-
*
|
|
2317
|
-
* else `defaultVal`.
|
|
2506
|
+
* Format nanoseconds as Go's `time.Duration.String()`.
|
|
2318
2507
|
*
|
|
2319
|
-
*
|
|
2320
|
-
*
|
|
2321
|
-
*
|
|
2508
|
+
* Go's algorithm mirrors time/time.go Duration.String():
|
|
2509
|
+
* - Values < 1µs: "Xns"
|
|
2510
|
+
* - Values < 1ms: "X.YYYµs" (trailing zeros trimmed)
|
|
2511
|
+
* - Values < 1s: "X.YYYms" (trailing zeros trimmed)
|
|
2512
|
+
* - Values >= 1s: "XhYmZ.WWWs" (hours/minutes shown when non-zero;
|
|
2513
|
+
* intermediate zero units always shown once hours or
|
|
2514
|
+
* minutes appear; e.g. "1h0m0s", "1m0s")
|
|
2322
2515
|
*/
|
|
2323
|
-
function
|
|
2324
|
-
|
|
2516
|
+
function formatDurationNs(ns) {
|
|
2517
|
+
if (ns === 0) return "0s";
|
|
2518
|
+
let negative = false;
|
|
2519
|
+
let abs = ns;
|
|
2520
|
+
if (abs < 0) {
|
|
2521
|
+
negative = true;
|
|
2522
|
+
abs = -abs;
|
|
2523
|
+
}
|
|
2524
|
+
let out;
|
|
2525
|
+
if (abs < NS_PER.us) out = `${Math.floor(abs)}ns`;
|
|
2526
|
+
else if (abs < NS_PER.ms) out = fmtSubUnit(abs, NS_PER.us, 3, "µs");
|
|
2527
|
+
else if (abs < NS_PER.s) out = fmtSubUnit(abs, NS_PER.ms, 6, "ms");
|
|
2528
|
+
else out = fmtGeqSecond(abs);
|
|
2529
|
+
return negative ? `-${out}` : out;
|
|
2530
|
+
}
|
|
2531
|
+
/** Format sub-second values in a given unit (µs, ms). */
|
|
2532
|
+
function fmtSubUnit(abs, unit, fracDigits, suffix) {
|
|
2533
|
+
const whole = Math.floor(abs / unit);
|
|
2534
|
+
const frac = Math.round(abs % unit);
|
|
2535
|
+
if (frac === 0) return `${whole}${suffix}`;
|
|
2536
|
+
return `${whole}.${String(frac).padStart(fracDigits, "0").replace(/0+$/, "")}${suffix}`;
|
|
2537
|
+
}
|
|
2538
|
+
/** Format durations >= 1 second as Go does. */
|
|
2539
|
+
function fmtGeqSecond(abs) {
|
|
2540
|
+
const h = Math.floor(abs / NS_PER.h);
|
|
2541
|
+
abs -= h * NS_PER.h;
|
|
2542
|
+
const m = Math.floor(abs / NS_PER.m);
|
|
2543
|
+
abs -= m * NS_PER.m;
|
|
2544
|
+
const s = Math.floor(abs / NS_PER.s);
|
|
2545
|
+
const nsFrac = abs - s * NS_PER.s;
|
|
2546
|
+
const secStr = nsFrac === 0 ? `${s}s` : `${s}.${String(Math.round(nsFrac)).padStart(9, "0").replace(/0+$/, "")}s`;
|
|
2547
|
+
if (h > 0) return `${h}h${m}m${secStr}`;
|
|
2548
|
+
if (m > 0) return `${m}m${secStr}`;
|
|
2549
|
+
return secStr;
|
|
2550
|
+
}
|
|
2551
|
+
/** Convert integer seconds to nanoseconds. */
|
|
2552
|
+
function secondsToNs(s) {
|
|
2553
|
+
return s * NS_PER.s;
|
|
2325
2554
|
}
|
|
2326
2555
|
//#endregion
|
|
2327
|
-
//#region src/sprig/
|
|
2556
|
+
//#region src/sprig/datetime/_resolve.ts
|
|
2328
2557
|
/**
|
|
2329
|
-
*
|
|
2558
|
+
* Normalise the heterogeneous `t` argument accepted by date functions.
|
|
2330
2559
|
*
|
|
2331
|
-
*
|
|
2332
|
-
*
|
|
2560
|
+
* Go sprig's `dateInZone` accepts: `time.Time`, `int64`, `int`, `int32`.
|
|
2561
|
+
* JS side: `Date`, `number` (Unix seconds), `bigint` (Unix seconds),
|
|
2562
|
+
* `string` (ISO / Go-layout string).
|
|
2563
|
+
*
|
|
2564
|
+
* When `t` is already a `Date`, it is returned unchanged.
|
|
2565
|
+
* When `t` is a number or bigint, it is treated as Unix seconds (matching
|
|
2566
|
+
* Go's `time.Unix(n, 0)` — NOT milliseconds).
|
|
2567
|
+
* When `t` is a string, it is parsed by `Date.parse` as a fallback.
|
|
2568
|
+
*
|
|
2569
|
+
* [LAW:single-enforcer] One place owns `t → Date` normalisation.
|
|
2570
|
+
* All date functions call this; none duplicate the logic.
|
|
2333
2571
|
*/
|
|
2334
|
-
function
|
|
2335
|
-
|
|
2572
|
+
function resolveDate(t) {
|
|
2573
|
+
if (t instanceof Date) return t;
|
|
2574
|
+
if (typeof t === "bigint") return /* @__PURE__ */ new Date(Number(t) * 1e3);
|
|
2575
|
+
if (typeof t === "number") return /* @__PURE__ */ new Date(t * 1e3);
|
|
2576
|
+
if (typeof t === "string") {
|
|
2577
|
+
const parsed = new Date(t);
|
|
2578
|
+
if (!Number.isNaN(parsed.getTime())) return parsed;
|
|
2579
|
+
throw new Error(`sprig: cannot parse date value ${JSON.stringify(t)}`);
|
|
2580
|
+
}
|
|
2581
|
+
throw new Error(`sprig: unsupported date type: ${typeof t}`);
|
|
2336
2582
|
}
|
|
2337
2583
|
//#endregion
|
|
2338
|
-
//#region src/sprig/
|
|
2584
|
+
//#region src/sprig/datetime/ago.ts
|
|
2339
2585
|
/**
|
|
2340
|
-
* `
|
|
2341
|
-
*
|
|
2342
|
-
*
|
|
2343
|
-
* Note: argument order matches Go sprig and surprises newcomers.
|
|
2344
|
-
* Pipelines feed cond as the trailing arg, e.g.
|
|
2345
|
-
* `{{ .ok | ternary "YES" "NO" }}` → ternary("YES", "NO", .ok)
|
|
2586
|
+
* `ago t` — Go-style duration since `t`.
|
|
2587
|
+
* Mirrors Go sprig: `time.Since(t).Round(time.Second).String()`.
|
|
2346
2588
|
*/
|
|
2347
|
-
function
|
|
2348
|
-
|
|
2589
|
+
function ago(t, clock) {
|
|
2590
|
+
const ms = clock().getTime() - resolveDate(t).getTime();
|
|
2591
|
+
return formatDurationNs(Math.round(ms / 1e3) * 1e9);
|
|
2349
2592
|
}
|
|
2350
2593
|
//#endregion
|
|
2351
|
-
//#region src/sprig/
|
|
2594
|
+
//#region src/sprig/datetime/_format.ts
|
|
2595
|
+
const MONTHS_LONG$1 = [
|
|
2596
|
+
"January",
|
|
2597
|
+
"February",
|
|
2598
|
+
"March",
|
|
2599
|
+
"April",
|
|
2600
|
+
"May",
|
|
2601
|
+
"June",
|
|
2602
|
+
"July",
|
|
2603
|
+
"August",
|
|
2604
|
+
"September",
|
|
2605
|
+
"October",
|
|
2606
|
+
"November",
|
|
2607
|
+
"December"
|
|
2608
|
+
];
|
|
2609
|
+
const MONTHS_SHORT$1 = [
|
|
2610
|
+
"Jan",
|
|
2611
|
+
"Feb",
|
|
2612
|
+
"Mar",
|
|
2613
|
+
"Apr",
|
|
2614
|
+
"May",
|
|
2615
|
+
"Jun",
|
|
2616
|
+
"Jul",
|
|
2617
|
+
"Aug",
|
|
2618
|
+
"Sep",
|
|
2619
|
+
"Oct",
|
|
2620
|
+
"Nov",
|
|
2621
|
+
"Dec"
|
|
2622
|
+
];
|
|
2623
|
+
const WEEKDAYS_LONG = [
|
|
2624
|
+
"Sunday",
|
|
2625
|
+
"Monday",
|
|
2626
|
+
"Tuesday",
|
|
2627
|
+
"Wednesday",
|
|
2628
|
+
"Thursday",
|
|
2629
|
+
"Friday",
|
|
2630
|
+
"Saturday"
|
|
2631
|
+
];
|
|
2632
|
+
const WEEKDAYS_SHORT = [
|
|
2633
|
+
"Sun",
|
|
2634
|
+
"Mon",
|
|
2635
|
+
"Tue",
|
|
2636
|
+
"Wed",
|
|
2637
|
+
"Thu",
|
|
2638
|
+
"Fri",
|
|
2639
|
+
"Sat"
|
|
2640
|
+
];
|
|
2641
|
+
function pad2(n) {
|
|
2642
|
+
return n < 10 ? `0${n}` : String(n);
|
|
2643
|
+
}
|
|
2644
|
+
function pad3(n) {
|
|
2645
|
+
return n < 10 ? `00${n}` : n < 100 ? `0${n}` : String(n);
|
|
2646
|
+
}
|
|
2647
|
+
function spacePad2(n) {
|
|
2648
|
+
return n < 10 ? ` ${n}` : String(n);
|
|
2649
|
+
}
|
|
2650
|
+
/** ±hhmm (no colon). E.g. "+0500", "-0500", "+0000". */
|
|
2651
|
+
function fmtOffset(offsetMinutes) {
|
|
2652
|
+
const sign = offsetMinutes >= 0 ? "+" : "-";
|
|
2653
|
+
const abs = Math.abs(offsetMinutes);
|
|
2654
|
+
return `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;
|
|
2655
|
+
}
|
|
2656
|
+
/** ±hh:mm (with colon). E.g. "+05:00", "-05:00", "+00:00". */
|
|
2657
|
+
function fmtOffsetColon(offsetMinutes) {
|
|
2658
|
+
const sign = offsetMinutes >= 0 ? "+" : "-";
|
|
2659
|
+
const abs = Math.abs(offsetMinutes);
|
|
2660
|
+
return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
|
|
2661
|
+
}
|
|
2662
|
+
/** ±hh only. */
|
|
2663
|
+
function fmtOffsetHour(offsetMinutes) {
|
|
2664
|
+
return `${offsetMinutes >= 0 ? "+" : "-"}${pad2(Math.floor(Math.abs(offsetMinutes) / 60))}`;
|
|
2665
|
+
}
|
|
2666
|
+
/** Z or ±hhmm. */
|
|
2667
|
+
function fmtOffsetZ(offsetMinutes) {
|
|
2668
|
+
return offsetMinutes === 0 ? "Z" : fmtOffset(offsetMinutes);
|
|
2669
|
+
}
|
|
2670
|
+
/** Z or ±hh:mm. */
|
|
2671
|
+
function fmtOffsetColonZ(offsetMinutes) {
|
|
2672
|
+
return offsetMinutes === 0 ? "Z" : fmtOffsetColon(offsetMinutes);
|
|
2673
|
+
}
|
|
2674
|
+
/** Z or ±hh. */
|
|
2675
|
+
function fmtOffsetHourZ(offsetMinutes) {
|
|
2676
|
+
return offsetMinutes === 0 ? "Z" : fmtOffsetHour(offsetMinutes);
|
|
2677
|
+
}
|
|
2678
|
+
function fmtFrac(ms, width, trimTrailing) {
|
|
2679
|
+
const nanosTotal = ms * 1e6;
|
|
2680
|
+
const s = String(nanosTotal).padStart(9, "0").slice(0, width);
|
|
2681
|
+
if (trimTrailing) return s.replace(/0+$/, "");
|
|
2682
|
+
return s;
|
|
2683
|
+
}
|
|
2684
|
+
const TOKENS$1 = [
|
|
2685
|
+
[".000000000", (z) => `.${fmtFrac(z.ms, 9, false)}`],
|
|
2686
|
+
[".999999999", (z) => {
|
|
2687
|
+
const s = fmtFrac(z.ms, 9, true);
|
|
2688
|
+
return s ? `.${s}` : "";
|
|
2689
|
+
}],
|
|
2690
|
+
[".000000", (z) => `.${fmtFrac(z.ms, 6, false)}`],
|
|
2691
|
+
[".999999", (z) => {
|
|
2692
|
+
const s = fmtFrac(z.ms, 6, true);
|
|
2693
|
+
return s ? `.${s}` : "";
|
|
2694
|
+
}],
|
|
2695
|
+
[".000", (z) => `.${pad3(z.ms)}`],
|
|
2696
|
+
[".999", (z) => {
|
|
2697
|
+
const s = pad3(z.ms).replace(/0+$/, "");
|
|
2698
|
+
return s ? `.${s}` : "";
|
|
2699
|
+
}],
|
|
2700
|
+
["January", (z) => MONTHS_LONG$1[z.month - 1] ?? "January"],
|
|
2701
|
+
["Monday", (z) => WEEKDAYS_LONG[z.weekday] ?? "Monday"],
|
|
2702
|
+
["Z07:00", (z) => fmtOffsetColonZ(z.offsetMinutes)],
|
|
2703
|
+
["-07:00", (z) => fmtOffsetColon(z.offsetMinutes)],
|
|
2704
|
+
["Z0700", (z) => fmtOffsetZ(z.offsetMinutes)],
|
|
2705
|
+
["-0700", (z) => fmtOffset(z.offsetMinutes)],
|
|
2706
|
+
["2006", (z) => String(z.year)],
|
|
2707
|
+
["Jan", (z) => MONTHS_SHORT$1[z.month - 1] ?? "Jan"],
|
|
2708
|
+
["Mon", (z) => WEEKDAYS_SHORT[z.weekday] ?? "Mon"],
|
|
2709
|
+
["MST", (z) => z.tzAbbr],
|
|
2710
|
+
["-07", (z) => fmtOffsetHour(z.offsetMinutes)],
|
|
2711
|
+
["Z07", (z) => fmtOffsetHourZ(z.offsetMinutes)],
|
|
2712
|
+
["15", (z) => pad2(z.hour)],
|
|
2713
|
+
["01", (z) => pad2(z.month)],
|
|
2714
|
+
["02", (z) => pad2(z.day)],
|
|
2715
|
+
["_2", (z) => spacePad2(z.day)],
|
|
2716
|
+
["03", (z) => pad2(z.hour12)],
|
|
2717
|
+
["04", (z) => pad2(z.minute)],
|
|
2718
|
+
["05", (z) => pad2(z.second)],
|
|
2719
|
+
["06", (z) => pad2(z.year % 100)],
|
|
2720
|
+
["PM", (z) => z.hour >= 12 ? "PM" : "AM"],
|
|
2721
|
+
["pm", (z) => z.hour >= 12 ? "pm" : "am"],
|
|
2722
|
+
["1", (z) => String(z.month)],
|
|
2723
|
+
["2", (z) => String(z.day)],
|
|
2724
|
+
["3", (z) => String(z.hour12)],
|
|
2725
|
+
["4", (z) => String(z.minute)],
|
|
2726
|
+
["5", (z) => String(z.second)]
|
|
2727
|
+
];
|
|
2352
2728
|
/**
|
|
2353
|
-
*
|
|
2354
|
-
*
|
|
2355
|
-
* Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that
|
|
2356
|
-
* `JSON.stringify(undefined)` is undefined; we coerce that to "null"
|
|
2357
|
-
* for byte-equivalence with Go's encoding/json (which encodes
|
|
2358
|
-
* untyped-nil as null).
|
|
2729
|
+
* Format `zoneParts` according to Go's reference-time layout string.
|
|
2730
|
+
* Literal characters pass through unchanged.
|
|
2359
2731
|
*/
|
|
2360
|
-
function
|
|
2361
|
-
|
|
2732
|
+
function formatGoLayout(layout, z) {
|
|
2733
|
+
let result = "";
|
|
2734
|
+
let i = 0;
|
|
2735
|
+
while (i < layout.length) {
|
|
2736
|
+
let matched = false;
|
|
2737
|
+
for (const [token, replacer] of TOKENS$1) if (layout.startsWith(token, i)) {
|
|
2738
|
+
result += replacer(z);
|
|
2739
|
+
i += token.length;
|
|
2740
|
+
matched = true;
|
|
2741
|
+
break;
|
|
2742
|
+
}
|
|
2743
|
+
if (!matched) result += layout[i++];
|
|
2744
|
+
}
|
|
2745
|
+
return result;
|
|
2362
2746
|
}
|
|
2363
2747
|
//#endregion
|
|
2364
|
-
//#region src/sprig/
|
|
2748
|
+
//#region src/sprig/datetime/_zone.ts
|
|
2749
|
+
const INTL_OPTS = {
|
|
2750
|
+
year: "numeric",
|
|
2751
|
+
month: "2-digit",
|
|
2752
|
+
day: "2-digit",
|
|
2753
|
+
weekday: "long",
|
|
2754
|
+
hour: "2-digit",
|
|
2755
|
+
minute: "2-digit",
|
|
2756
|
+
second: "2-digit",
|
|
2757
|
+
hour12: false
|
|
2758
|
+
};
|
|
2759
|
+
function indexParts(parts) {
|
|
2760
|
+
const out = /* @__PURE__ */ new Map();
|
|
2761
|
+
for (const p of parts) out.set(p.type, p.value);
|
|
2762
|
+
return out;
|
|
2763
|
+
}
|
|
2764
|
+
const WEEKDAY_NAMES = [
|
|
2765
|
+
"Sunday",
|
|
2766
|
+
"Monday",
|
|
2767
|
+
"Tuesday",
|
|
2768
|
+
"Wednesday",
|
|
2769
|
+
"Thursday",
|
|
2770
|
+
"Friday",
|
|
2771
|
+
"Saturday"
|
|
2772
|
+
];
|
|
2773
|
+
/** Extract date parts in the requested IANA timezone. Falls back to "UTC" on invalid zone, mirroring Go sprig. */
|
|
2774
|
+
function getZoneParts(date, tzInput) {
|
|
2775
|
+
let tz;
|
|
2776
|
+
try {
|
|
2777
|
+
new Intl.DateTimeFormat("en-US", { timeZone: tzInput });
|
|
2778
|
+
tz = tzInput;
|
|
2779
|
+
} catch {
|
|
2780
|
+
tz = "UTC";
|
|
2781
|
+
}
|
|
2782
|
+
const p = indexParts(new Intl.DateTimeFormat("en-US", {
|
|
2783
|
+
...INTL_OPTS,
|
|
2784
|
+
timeZone: tz
|
|
2785
|
+
}).formatToParts(date));
|
|
2786
|
+
const hour = parseInt(p.get("hour") ?? "0", 10) % 24;
|
|
2787
|
+
const tzAbbr = indexParts(new Intl.DateTimeFormat("en-US", {
|
|
2788
|
+
timeZone: tz,
|
|
2789
|
+
timeZoneName: "short"
|
|
2790
|
+
}).formatToParts(date)).get("timeZoneName") ?? tz;
|
|
2791
|
+
const offsetMinutes = parseGMTOffset(indexParts(new Intl.DateTimeFormat("en-US", {
|
|
2792
|
+
timeZone: tz,
|
|
2793
|
+
timeZoneName: "shortOffset"
|
|
2794
|
+
}).formatToParts(date)).get("timeZoneName") ?? "GMT");
|
|
2795
|
+
const weekday = WEEKDAY_NAMES.indexOf(p.get("weekday") ?? "Sunday");
|
|
2796
|
+
return {
|
|
2797
|
+
year: parseInt(p.get("year") ?? "2000", 10),
|
|
2798
|
+
month: parseInt(p.get("month") ?? "1", 10),
|
|
2799
|
+
day: parseInt(p.get("day") ?? "1", 10),
|
|
2800
|
+
weekday: weekday === -1 ? 0 : weekday,
|
|
2801
|
+
hour,
|
|
2802
|
+
hour12: hour % 12 || 12,
|
|
2803
|
+
minute: parseInt(p.get("minute") ?? "0", 10),
|
|
2804
|
+
second: parseInt(p.get("second") ?? "0", 10),
|
|
2805
|
+
ms: date.getUTCMilliseconds(),
|
|
2806
|
+
tzAbbr,
|
|
2807
|
+
offsetMinutes
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
/** Parse "GMT", "GMT+5", "GMT+5:30", "GMT-4" → offset in minutes. */
|
|
2811
|
+
function parseGMTOffset(s) {
|
|
2812
|
+
if (s === "GMT" || s === "UTC") return 0;
|
|
2813
|
+
const m = s.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);
|
|
2814
|
+
if (!m) return 0;
|
|
2815
|
+
const sign = m[1] === "+" ? 1 : -1;
|
|
2816
|
+
const h = parseInt(m[2] ?? "0", 10);
|
|
2817
|
+
const min = parseInt(m[3] ?? "0", 10);
|
|
2818
|
+
return sign * (h * 60 + min);
|
|
2819
|
+
}
|
|
2820
|
+
/** Host timezone name (IANA string). */
|
|
2821
|
+
function localTz() {
|
|
2822
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
2823
|
+
}
|
|
2824
|
+
//#endregion
|
|
2825
|
+
//#region src/sprig/datetime/date.ts
|
|
2365
2826
|
/**
|
|
2366
|
-
* `
|
|
2367
|
-
*
|
|
2827
|
+
* `date format t` — format `t` using Go's reference-time layout,
|
|
2828
|
+
* in the host timezone (mirrors Go's `date` which uses `time.Local`).
|
|
2368
2829
|
*/
|
|
2369
|
-
function
|
|
2370
|
-
return
|
|
2830
|
+
function date(format, t) {
|
|
2831
|
+
return formatGoLayout(format, getZoneParts(resolveDate(t), localTz()));
|
|
2371
2832
|
}
|
|
2372
2833
|
//#endregion
|
|
2373
|
-
//#region src/sprig/
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
empty: {
|
|
2381
|
-
fn: (v) => empty(v),
|
|
2382
|
-
argTypes: ["truthy"]
|
|
2383
|
-
},
|
|
2384
|
-
coalesce: {
|
|
2385
|
-
fn: (...vs) => coalesce(...vs),
|
|
2386
|
-
argTypes: ["truthy"]
|
|
2387
|
-
},
|
|
2388
|
-
ternary: {
|
|
2389
|
-
fn: (a, b, c) => ternary(a, b, c),
|
|
2390
|
-
argTypes: [
|
|
2391
|
-
"value",
|
|
2392
|
-
"value",
|
|
2393
|
-
"truthy"
|
|
2394
|
-
]
|
|
2395
|
-
},
|
|
2396
|
-
fromJson: {
|
|
2397
|
-
fn: (s) => fromJson(s),
|
|
2398
|
-
argTypes: ["string"]
|
|
2399
|
-
},
|
|
2400
|
-
toJson: {
|
|
2401
|
-
fn: (v) => toJson(v),
|
|
2402
|
-
argTypes: ["serializable"],
|
|
2403
|
-
returnType: "string"
|
|
2404
|
-
},
|
|
2405
|
-
toPrettyJson: {
|
|
2406
|
-
fn: (v) => toPrettyJson(v),
|
|
2407
|
-
argTypes: ["serializable"],
|
|
2408
|
-
returnType: "string"
|
|
2409
|
-
}
|
|
2410
|
-
};
|
|
2834
|
+
//#region src/sprig/datetime/dateInZone.ts
|
|
2835
|
+
/**
|
|
2836
|
+
* `dateInZone format t zone` — format `t` using Go's reference-time
|
|
2837
|
+
* layout, displayed in the named IANA timezone.
|
|
2838
|
+
*/
|
|
2839
|
+
function dateInZone(format, t, zone) {
|
|
2840
|
+
return formatGoLayout(format, getZoneParts(resolveDate(t), zone));
|
|
2411
2841
|
}
|
|
2412
2842
|
//#endregion
|
|
2413
|
-
//#region src/sprig/
|
|
2843
|
+
//#region src/sprig/datetime/dateModify.ts
|
|
2414
2844
|
/**
|
|
2415
|
-
* `
|
|
2416
|
-
*
|
|
2417
|
-
* [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates
|
|
2418
|
-
* the kv cycle via `argTypePattern: "alternating"` against
|
|
2419
|
-
* `argTypes: ["string", "value"]`, so every key position is a string by
|
|
2420
|
-
* the time the body runs. The body trusts the gate; no per-key probe.
|
|
2421
|
-
*
|
|
2422
|
-
* Odd-length call (`dict "a"`) leaves the last value `undefined` —
|
|
2423
|
-
* matches Go sprig.
|
|
2845
|
+
* `dateModify duration t` — add or subtract a Go duration from `t`.
|
|
2846
|
+
* `duration` is a Go duration string: "1h30m", "-24h", "300ms".
|
|
2424
2847
|
*/
|
|
2425
|
-
function
|
|
2426
|
-
const
|
|
2427
|
-
|
|
2428
|
-
return
|
|
2848
|
+
function dateModify(duration, t) {
|
|
2849
|
+
const d = resolveDate(t);
|
|
2850
|
+
const ns = parseDurationNs(duration);
|
|
2851
|
+
if (Number.isNaN(ns)) return d;
|
|
2852
|
+
return new Date(d.getTime() + ns / 1e6);
|
|
2429
2853
|
}
|
|
2430
2854
|
//#endregion
|
|
2431
|
-
//#region src/sprig/
|
|
2855
|
+
//#region src/sprig/datetime/duration.ts
|
|
2432
2856
|
/**
|
|
2433
|
-
* `
|
|
2857
|
+
* `duration sec` — seconds → Go-style duration string.
|
|
2858
|
+
* Mirrors Go sprig: accepts a string (parsed as decimal integer seconds)
|
|
2859
|
+
* or a number/bigint.
|
|
2434
2860
|
*
|
|
2435
|
-
*
|
|
2436
|
-
*
|
|
2437
|
-
*
|
|
2438
|
-
*
|
|
2439
|
-
*
|
|
2861
|
+
* `duration("3600")` → `"1h0m0s"`, `duration("5")` → `"5s"`.
|
|
2862
|
+
*
|
|
2863
|
+
* Note: Go sprig only handles `string` and `int64` inputs; `int` (the type
|
|
2864
|
+
* of a Go template integer literal) falls to a default-zero branch. To
|
|
2865
|
+
* maintain portable templates, always pass seconds as a string.
|
|
2440
2866
|
*/
|
|
2441
|
-
function
|
|
2442
|
-
|
|
2867
|
+
function duration(sec) {
|
|
2868
|
+
if (typeof sec === "string") {
|
|
2869
|
+
const n = parseInt(sec, 10);
|
|
2870
|
+
return Number.isNaN(n) ? "0s" : formatDurationNs(secondsToNs(n));
|
|
2871
|
+
}
|
|
2872
|
+
if (typeof sec === "bigint") return formatDurationNs(secondsToNs(Number(sec)));
|
|
2873
|
+
if (typeof sec === "number") return formatDurationNs(secondsToNs(sec));
|
|
2874
|
+
return "0s";
|
|
2443
2875
|
}
|
|
2444
2876
|
//#endregion
|
|
2445
|
-
//#region src/sprig/
|
|
2877
|
+
//#region src/sprig/datetime/durationRound.ts
|
|
2878
|
+
const YEAR = 36e11 * 24 * 365;
|
|
2879
|
+
const MONTH = 36e11 * 24 * 30;
|
|
2880
|
+
const DAY = 36e11 * 24;
|
|
2881
|
+
const HOUR = 36e11;
|
|
2882
|
+
const MINUTE = 6e10;
|
|
2883
|
+
const SECOND = 1e9;
|
|
2446
2884
|
/**
|
|
2447
|
-
* `
|
|
2885
|
+
* `durationRound d` — parse a Go duration string and truncate to the
|
|
2886
|
+
* largest unit. Mirrors Go sprig's `durationRound` which uses integer
|
|
2887
|
+
* division (NOT rounding) and custom single-unit suffixes.
|
|
2448
2888
|
*
|
|
2449
|
-
*
|
|
2450
|
-
* [LAW:single-enforcer] Receiver type validated at the gate.
|
|
2889
|
+
* Examples: "1h30m" → "1h", "90s" → "1m", "1h" → "60m" (strict >).
|
|
2451
2890
|
*/
|
|
2452
|
-
function
|
|
2453
|
-
|
|
2891
|
+
function durationRound(d) {
|
|
2892
|
+
const ns = parseDurationNs(String(d));
|
|
2893
|
+
if (Number.isNaN(ns)) return "0s";
|
|
2894
|
+
const u = Math.abs(ns);
|
|
2895
|
+
if (u > YEAR) return `${Math.floor(u / YEAR)}y`;
|
|
2896
|
+
if (u > MONTH) return `${Math.floor(u / MONTH)}mo`;
|
|
2897
|
+
if (u > DAY) return `${Math.floor(u / DAY)}d`;
|
|
2898
|
+
if (u > HOUR) return `${Math.floor(u / HOUR)}h`;
|
|
2899
|
+
if (u > MINUTE) return `${Math.floor(u / MINUTE)}m`;
|
|
2900
|
+
if (u > SECOND) return `${Math.floor(u / SECOND)}s`;
|
|
2901
|
+
return "0s";
|
|
2902
|
+
}
|
|
2903
|
+
//#endregion
|
|
2904
|
+
//#region src/sprig/datetime/htmlDate.ts
|
|
2905
|
+
/** `htmlDate t` — YYYY-MM-DD in the host timezone. */
|
|
2906
|
+
function htmlDate(t) {
|
|
2907
|
+
const z = getZoneParts(resolveDate(t), localTz());
|
|
2908
|
+
return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
|
|
2909
|
+
}
|
|
2910
|
+
//#endregion
|
|
2911
|
+
//#region src/sprig/datetime/htmlDateInZone.ts
|
|
2912
|
+
/** `htmlDateInZone t zone` — YYYY-MM-DD in the named timezone. */
|
|
2913
|
+
function htmlDateInZone(t, zone) {
|
|
2914
|
+
const z = getZoneParts(resolveDate(t), zone);
|
|
2915
|
+
return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
|
|
2916
|
+
}
|
|
2917
|
+
//#endregion
|
|
2918
|
+
//#region src/sprig/datetime/now.ts
|
|
2919
|
+
/** `now` — current instant. Routed through the clock seam. */
|
|
2920
|
+
function now(clock) {
|
|
2921
|
+
return clock();
|
|
2922
|
+
}
|
|
2923
|
+
//#endregion
|
|
2924
|
+
//#region src/sprig/datetime/_parse.ts
|
|
2925
|
+
/**
|
|
2926
|
+
* Parse a date string according to Go's reference-time layout.
|
|
2927
|
+
*
|
|
2928
|
+
* Mirrors `time.ParseInLocation` with UTC as the default location
|
|
2929
|
+
* (when the layout contains no timezone token, the result is UTC).
|
|
2930
|
+
*
|
|
2931
|
+
* Strategy: tokenise the layout the same way the formatter does —
|
|
2932
|
+
* greedy longest-match — but instead of replacing tokens with values,
|
|
2933
|
+
* consume the corresponding characters from the value string.
|
|
2934
|
+
*/
|
|
2935
|
+
const MONTHS_LONG = [
|
|
2936
|
+
"January",
|
|
2937
|
+
"February",
|
|
2938
|
+
"March",
|
|
2939
|
+
"April",
|
|
2940
|
+
"May",
|
|
2941
|
+
"June",
|
|
2942
|
+
"July",
|
|
2943
|
+
"August",
|
|
2944
|
+
"September",
|
|
2945
|
+
"October",
|
|
2946
|
+
"November",
|
|
2947
|
+
"December"
|
|
2948
|
+
];
|
|
2949
|
+
const MONTHS_SHORT = [
|
|
2950
|
+
"Jan",
|
|
2951
|
+
"Feb",
|
|
2952
|
+
"Mar",
|
|
2953
|
+
"Apr",
|
|
2954
|
+
"May",
|
|
2955
|
+
"Jun",
|
|
2956
|
+
"Jul",
|
|
2957
|
+
"Aug",
|
|
2958
|
+
"Sep",
|
|
2959
|
+
"Oct",
|
|
2960
|
+
"Nov",
|
|
2961
|
+
"Dec"
|
|
2962
|
+
];
|
|
2963
|
+
function defaultState() {
|
|
2964
|
+
return {
|
|
2965
|
+
year: 2e3,
|
|
2966
|
+
month: 1,
|
|
2967
|
+
day: 1,
|
|
2968
|
+
hour: 0,
|
|
2969
|
+
minute: 0,
|
|
2970
|
+
second: 0,
|
|
2971
|
+
ms: 0,
|
|
2972
|
+
offsetMinutes: 0,
|
|
2973
|
+
isPM: false,
|
|
2974
|
+
hour12: false
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
function consumeFixed(val, pos, n) {
|
|
2978
|
+
return [val.slice(pos, pos + n), pos + n];
|
|
2979
|
+
}
|
|
2980
|
+
function consumeDigits(val, pos, min, max) {
|
|
2981
|
+
let end = pos;
|
|
2982
|
+
while (end < val.length && end - pos < max && val.charCodeAt(end) >= 48 && val.charCodeAt(end) <= 57) end++;
|
|
2983
|
+
if (end - pos < min) throw new Error(`sprig toDate: expected ${min}-${max} digits at pos ${pos}`);
|
|
2984
|
+
return [parseInt(val.slice(pos, end), 10), end];
|
|
2985
|
+
}
|
|
2986
|
+
function consumeMonthLong(val, pos) {
|
|
2987
|
+
for (const [i, m] of MONTHS_LONG.entries()) if (val.startsWith(m, pos)) return [i + 1, pos + m.length];
|
|
2988
|
+
throw new Error(`sprig toDate: expected month name at pos ${pos}`);
|
|
2989
|
+
}
|
|
2990
|
+
function consumeMonthShort(val, pos) {
|
|
2991
|
+
for (const [i, m] of MONTHS_SHORT.entries()) if (val.startsWith(m, pos)) return [i + 1, pos + m.length];
|
|
2992
|
+
throw new Error(`sprig toDate: expected short month name at pos ${pos}`);
|
|
2993
|
+
}
|
|
2994
|
+
function consumeWeekdayLong(val, pos) {
|
|
2995
|
+
for (const d of [
|
|
2996
|
+
"Sunday",
|
|
2997
|
+
"Monday",
|
|
2998
|
+
"Tuesday",
|
|
2999
|
+
"Wednesday",
|
|
3000
|
+
"Thursday",
|
|
3001
|
+
"Friday",
|
|
3002
|
+
"Saturday"
|
|
3003
|
+
]) if (val.startsWith(d, pos)) return pos + d.length;
|
|
3004
|
+
throw new Error(`sprig toDate: expected weekday name at pos ${pos}`);
|
|
3005
|
+
}
|
|
3006
|
+
function consumeWeekdayShort(val, pos) {
|
|
3007
|
+
for (const d of [
|
|
3008
|
+
"Sun",
|
|
3009
|
+
"Mon",
|
|
3010
|
+
"Tue",
|
|
3011
|
+
"Wed",
|
|
3012
|
+
"Thu",
|
|
3013
|
+
"Fri",
|
|
3014
|
+
"Sat"
|
|
3015
|
+
]) if (val.startsWith(d, pos)) return pos + d.length;
|
|
3016
|
+
throw new Error(`sprig toDate: expected short weekday name at pos ${pos}`);
|
|
3017
|
+
}
|
|
3018
|
+
function consumeSpacePaddedDay(val, pos) {
|
|
3019
|
+
if (val[pos] === " ") {
|
|
3020
|
+
const [n, end] = consumeDigits(val, pos + 1, 1, 1);
|
|
3021
|
+
return [n, end];
|
|
3022
|
+
}
|
|
3023
|
+
return consumeDigits(val, pos, 1, 2);
|
|
3024
|
+
}
|
|
3025
|
+
/** Parse offset like "+0500", "-0500", "+05:00", "-05:00", "+05", "-05". Returns minutes. */
|
|
3026
|
+
function consumeOffset(val, pos, withColon) {
|
|
3027
|
+
const sign = val[pos] === "+" ? 1 : val[pos] === "-" ? -1 : 0;
|
|
3028
|
+
if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${pos}`);
|
|
3029
|
+
let p = pos + 1;
|
|
3030
|
+
const [h, p2] = consumeDigits(val, p, 2, 2);
|
|
3031
|
+
p = p2;
|
|
3032
|
+
let m = 0;
|
|
3033
|
+
if (withColon && val[p] === ":") {
|
|
3034
|
+
const [m2, p3] = consumeDigits(val, p + 1, 2, 2);
|
|
3035
|
+
m = m2;
|
|
3036
|
+
p = p3;
|
|
3037
|
+
} else if (!withColon) {
|
|
3038
|
+
const [m2, p3] = consumeDigits(val, p, 2, 2);
|
|
3039
|
+
m = m2;
|
|
3040
|
+
p = p3;
|
|
3041
|
+
}
|
|
3042
|
+
return [sign * (h * 60 + m), p];
|
|
3043
|
+
}
|
|
3044
|
+
/** Parse "Z" or an offset. withColon controls +05:00 vs +0500 form. Returns [offsetMinutes, newPos]. */
|
|
3045
|
+
function consumeZOrOffset(val, pos, withColon, hourOnly) {
|
|
3046
|
+
if (val[pos] === "Z") return [0, pos + 1];
|
|
3047
|
+
if (hourOnly) {
|
|
3048
|
+
const sign = val[pos] === "+" ? 1 : val[pos] === "-" ? -1 : 0;
|
|
3049
|
+
if (sign === 0) throw new Error(`sprig toDate: expected Z or +/- at pos ${pos}`);
|
|
3050
|
+
const [h, p2] = consumeDigits(val, pos + 1, 2, 2);
|
|
3051
|
+
return [sign * h * 60, p2];
|
|
3052
|
+
}
|
|
3053
|
+
return consumeOffset(val, pos, withColon);
|
|
3054
|
+
}
|
|
3055
|
+
/** Parse timezone abbreviation (e.g. "UTC", "EST"). Returns new pos. */
|
|
3056
|
+
function consumeTzAbbr(val, pos) {
|
|
3057
|
+
let end = pos;
|
|
3058
|
+
while (end < val.length && val.charCodeAt(end) >= 65 && val.charCodeAt(end) <= 90) end++;
|
|
3059
|
+
if (end === pos) throw new Error(`sprig toDate: expected timezone abbreviation at pos ${pos}`);
|
|
3060
|
+
return end;
|
|
3061
|
+
}
|
|
3062
|
+
/** Parse fractional seconds (like ".000", ".999", etc.) starting AFTER the dot. */
|
|
3063
|
+
function consumeFrac(val, pos, width) {
|
|
3064
|
+
const [raw, end] = consumeFixed(val, pos, width);
|
|
3065
|
+
const ns = parseInt(raw.padEnd(9, "0"), 10);
|
|
3066
|
+
return [Math.round(ns / 1e6), end];
|
|
3067
|
+
}
|
|
3068
|
+
function dispatchToken(token, val, vp, st) {
|
|
3069
|
+
const s = { ...st };
|
|
3070
|
+
switch (token) {
|
|
3071
|
+
case "January": {
|
|
3072
|
+
const [m, p2] = consumeMonthLong(val, vp);
|
|
3073
|
+
s.month = m;
|
|
3074
|
+
return [p2, s];
|
|
3075
|
+
}
|
|
3076
|
+
case "Monday": return [consumeWeekdayLong(val, vp), s];
|
|
3077
|
+
case "Jan": {
|
|
3078
|
+
const [m, p2] = consumeMonthShort(val, vp);
|
|
3079
|
+
s.month = m;
|
|
3080
|
+
return [p2, s];
|
|
3081
|
+
}
|
|
3082
|
+
case "Mon": return [consumeWeekdayShort(val, vp), s];
|
|
3083
|
+
case "2006": {
|
|
3084
|
+
const [y, p2] = consumeDigits(val, vp, 4, 4);
|
|
3085
|
+
s.year = y;
|
|
3086
|
+
return [p2, s];
|
|
3087
|
+
}
|
|
3088
|
+
case "06": {
|
|
3089
|
+
const [y, p2] = consumeDigits(val, vp, 2, 2);
|
|
3090
|
+
s.year = y < 70 ? 2e3 + y : 1900 + y;
|
|
3091
|
+
return [p2, s];
|
|
3092
|
+
}
|
|
3093
|
+
case "01": {
|
|
3094
|
+
const [m, p2] = consumeDigits(val, vp, 2, 2);
|
|
3095
|
+
s.month = m;
|
|
3096
|
+
return [p2, s];
|
|
3097
|
+
}
|
|
3098
|
+
case "1": {
|
|
3099
|
+
const [m, p2] = consumeDigits(val, vp, 1, 2);
|
|
3100
|
+
s.month = m;
|
|
3101
|
+
return [p2, s];
|
|
3102
|
+
}
|
|
3103
|
+
case "_2": {
|
|
3104
|
+
const [d, p2] = consumeSpacePaddedDay(val, vp);
|
|
3105
|
+
s.day = d;
|
|
3106
|
+
return [p2, s];
|
|
3107
|
+
}
|
|
3108
|
+
case "02": {
|
|
3109
|
+
const [d, p2] = consumeDigits(val, vp, 2, 2);
|
|
3110
|
+
s.day = d;
|
|
3111
|
+
return [p2, s];
|
|
3112
|
+
}
|
|
3113
|
+
case "2": {
|
|
3114
|
+
const [d, p2] = consumeDigits(val, vp, 1, 2);
|
|
3115
|
+
s.day = d;
|
|
3116
|
+
return [p2, s];
|
|
3117
|
+
}
|
|
3118
|
+
case "15": {
|
|
3119
|
+
const [h, p2] = consumeDigits(val, vp, 2, 2);
|
|
3120
|
+
s.hour = h;
|
|
3121
|
+
return [p2, s];
|
|
3122
|
+
}
|
|
3123
|
+
case "03": {
|
|
3124
|
+
const [h, p2] = consumeDigits(val, vp, 2, 2);
|
|
3125
|
+
s.hour = h;
|
|
3126
|
+
s.hour12 = true;
|
|
3127
|
+
return [p2, s];
|
|
3128
|
+
}
|
|
3129
|
+
case "3": {
|
|
3130
|
+
const [h, p2] = consumeDigits(val, vp, 1, 2);
|
|
3131
|
+
s.hour = h;
|
|
3132
|
+
s.hour12 = true;
|
|
3133
|
+
return [p2, s];
|
|
3134
|
+
}
|
|
3135
|
+
case "04": {
|
|
3136
|
+
const [m, p2] = consumeDigits(val, vp, 2, 2);
|
|
3137
|
+
s.minute = m;
|
|
3138
|
+
return [p2, s];
|
|
3139
|
+
}
|
|
3140
|
+
case "4": {
|
|
3141
|
+
const [m, p2] = consumeDigits(val, vp, 1, 2);
|
|
3142
|
+
s.minute = m;
|
|
3143
|
+
return [p2, s];
|
|
3144
|
+
}
|
|
3145
|
+
case "05": {
|
|
3146
|
+
const [sec, p2] = consumeDigits(val, vp, 2, 2);
|
|
3147
|
+
s.second = sec;
|
|
3148
|
+
return [p2, s];
|
|
3149
|
+
}
|
|
3150
|
+
case "5": {
|
|
3151
|
+
const [sec, p2] = consumeDigits(val, vp, 1, 2);
|
|
3152
|
+
s.second = sec;
|
|
3153
|
+
return [p2, s];
|
|
3154
|
+
}
|
|
3155
|
+
case "PM":
|
|
3156
|
+
case "pm": {
|
|
3157
|
+
const ampm = val.slice(vp, vp + 2).toLowerCase();
|
|
3158
|
+
if (ampm !== "am" && ampm !== "pm") throw new Error(`sprig toDate: expected AM/PM at pos ${vp}, got ${JSON.stringify(val.slice(vp, vp + 2))}`);
|
|
3159
|
+
s.isPM = ampm === "pm";
|
|
3160
|
+
s.hour12 = true;
|
|
3161
|
+
return [vp + 2, s];
|
|
3162
|
+
}
|
|
3163
|
+
case "MST": return [consumeTzAbbr(val, vp), s];
|
|
3164
|
+
case "-0700": {
|
|
3165
|
+
const [off, p2] = consumeOffset(val, vp, false);
|
|
3166
|
+
s.offsetMinutes = off;
|
|
3167
|
+
return [p2, s];
|
|
3168
|
+
}
|
|
3169
|
+
case "-07:00": {
|
|
3170
|
+
const [off, p2] = consumeOffset(val, vp, true);
|
|
3171
|
+
s.offsetMinutes = off;
|
|
3172
|
+
return [p2, s];
|
|
3173
|
+
}
|
|
3174
|
+
case "-07": {
|
|
3175
|
+
const sign = val[vp] === "+" ? 1 : val[vp] === "-" ? -1 : 0;
|
|
3176
|
+
if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${vp}`);
|
|
3177
|
+
const [h, p2] = consumeDigits(val, vp + 1, 2, 2);
|
|
3178
|
+
s.offsetMinutes = sign * h * 60;
|
|
3179
|
+
return [p2, s];
|
|
3180
|
+
}
|
|
3181
|
+
case "Z0700": {
|
|
3182
|
+
const [off, p2] = consumeZOrOffset(val, vp, false, false);
|
|
3183
|
+
s.offsetMinutes = off;
|
|
3184
|
+
return [p2, s];
|
|
3185
|
+
}
|
|
3186
|
+
case "Z07:00": {
|
|
3187
|
+
const [off, p2] = consumeZOrOffset(val, vp, true, false);
|
|
3188
|
+
s.offsetMinutes = off;
|
|
3189
|
+
return [p2, s];
|
|
3190
|
+
}
|
|
3191
|
+
case "Z07": {
|
|
3192
|
+
const [off, p2] = consumeZOrOffset(val, vp, false, true);
|
|
3193
|
+
s.offsetMinutes = off;
|
|
3194
|
+
return [p2, s];
|
|
3195
|
+
}
|
|
3196
|
+
case ".000000000": {
|
|
3197
|
+
if (val[vp] !== ".") throw new Error(`sprig toDate: expected . at pos ${vp}`);
|
|
3198
|
+
const [ms, p3] = consumeFrac(val, vp + 1, 9);
|
|
3199
|
+
s.ms = ms;
|
|
3200
|
+
return [p3, s];
|
|
3201
|
+
}
|
|
3202
|
+
case ".999999999": {
|
|
3203
|
+
if (val[vp] !== ".") return [vp, s];
|
|
3204
|
+
const end = vp + 1;
|
|
3205
|
+
let e2 = end;
|
|
3206
|
+
while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;
|
|
3207
|
+
const frac = val.slice(end, e2).padEnd(9, "0");
|
|
3208
|
+
s.ms = Math.round(parseInt(frac, 10) / 1e6);
|
|
3209
|
+
return [e2, s];
|
|
3210
|
+
}
|
|
3211
|
+
case ".000000": {
|
|
3212
|
+
if (val[vp] !== ".") throw new Error(`sprig toDate: expected . at pos ${vp}`);
|
|
3213
|
+
const [ms, p3] = consumeFrac(val, vp + 1, 6);
|
|
3214
|
+
s.ms = ms;
|
|
3215
|
+
return [p3, s];
|
|
3216
|
+
}
|
|
3217
|
+
case ".999999": {
|
|
3218
|
+
if (val[vp] !== ".") return [vp, s];
|
|
3219
|
+
const end = vp + 1;
|
|
3220
|
+
let e2 = end;
|
|
3221
|
+
while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;
|
|
3222
|
+
const frac = val.slice(end, e2).padEnd(9, "0");
|
|
3223
|
+
s.ms = Math.round(parseInt(frac, 10) / 1e6);
|
|
3224
|
+
return [e2, s];
|
|
3225
|
+
}
|
|
3226
|
+
case ".000": {
|
|
3227
|
+
if (val[vp] !== ".") throw new Error(`sprig toDate: expected . at pos ${vp}`);
|
|
3228
|
+
const [ms, p3] = consumeFrac(val, vp + 1, 3);
|
|
3229
|
+
s.ms = ms;
|
|
3230
|
+
return [p3, s];
|
|
3231
|
+
}
|
|
3232
|
+
case ".999": {
|
|
3233
|
+
if (val[vp] !== ".") return [vp, s];
|
|
3234
|
+
const end = vp + 1;
|
|
3235
|
+
let e2 = end;
|
|
3236
|
+
while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;
|
|
3237
|
+
const frac = val.slice(end, e2).padEnd(3, "0");
|
|
3238
|
+
s.ms = parseInt(frac, 10);
|
|
3239
|
+
return [e2, s];
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
throw new Error(`sprig toDate: unhandled token ${token}`);
|
|
3243
|
+
}
|
|
3244
|
+
const TOKENS = [
|
|
3245
|
+
".000000000",
|
|
3246
|
+
".999999999",
|
|
3247
|
+
".000000",
|
|
3248
|
+
".999999",
|
|
3249
|
+
".000",
|
|
3250
|
+
".999",
|
|
3251
|
+
"January",
|
|
3252
|
+
"Monday",
|
|
3253
|
+
"Z07:00",
|
|
3254
|
+
"-07:00",
|
|
3255
|
+
"Z0700",
|
|
3256
|
+
"-0700",
|
|
3257
|
+
"2006",
|
|
3258
|
+
"Jan",
|
|
3259
|
+
"Mon",
|
|
3260
|
+
"MST",
|
|
3261
|
+
"-07",
|
|
3262
|
+
"Z07",
|
|
3263
|
+
"15",
|
|
3264
|
+
"01",
|
|
3265
|
+
"02",
|
|
3266
|
+
"_2",
|
|
3267
|
+
"03",
|
|
3268
|
+
"04",
|
|
3269
|
+
"05",
|
|
3270
|
+
"06",
|
|
3271
|
+
"PM",
|
|
3272
|
+
"pm",
|
|
3273
|
+
"1",
|
|
3274
|
+
"2",
|
|
3275
|
+
"3",
|
|
3276
|
+
"4",
|
|
3277
|
+
"5"
|
|
3278
|
+
];
|
|
3279
|
+
/**
|
|
3280
|
+
* Parse `value` according to Go's reference-time `layout`.
|
|
3281
|
+
* Returns a UTC-based `Date` whose wall time corresponds to the parsed
|
|
3282
|
+
* components adjusted for the parsed timezone offset.
|
|
3283
|
+
*/
|
|
3284
|
+
function parseGoLayout(layout, value) {
|
|
3285
|
+
let lp = 0;
|
|
3286
|
+
let vp = 0;
|
|
3287
|
+
let st = defaultState();
|
|
3288
|
+
while (lp < layout.length) {
|
|
3289
|
+
let matched = false;
|
|
3290
|
+
for (const token of TOKENS) if (layout.startsWith(token, lp)) {
|
|
3291
|
+
const [newVp, newSt] = dispatchToken(token, value, vp, st);
|
|
3292
|
+
vp = newVp;
|
|
3293
|
+
st = newSt;
|
|
3294
|
+
lp += token.length;
|
|
3295
|
+
matched = true;
|
|
3296
|
+
break;
|
|
3297
|
+
}
|
|
3298
|
+
if (!matched) {
|
|
3299
|
+
const lc = layout.charAt(lp);
|
|
3300
|
+
if (value[vp] !== lc) throw new Error(`sprig toDate: expected ${JSON.stringify(lc)} at pos ${vp}, got ${JSON.stringify(value[vp])}`);
|
|
3301
|
+
lp++;
|
|
3302
|
+
vp++;
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
if (vp !== value.length) throw new Error(`sprig toDate: extra characters at pos ${vp}: ${JSON.stringify(value.slice(vp))}`);
|
|
3306
|
+
if (st.hour12) {
|
|
3307
|
+
const h12 = st.hour % 12;
|
|
3308
|
+
st.hour = st.isPM ? h12 + 12 : h12;
|
|
3309
|
+
}
|
|
3310
|
+
const utcMs = Date.UTC(st.year, st.month - 1, st.day, st.hour, st.minute, st.second, st.ms) - st.offsetMinutes * 60 * 1e3;
|
|
3311
|
+
return new Date(utcMs);
|
|
3312
|
+
}
|
|
3313
|
+
//#endregion
|
|
3314
|
+
//#region src/sprig/datetime/toDate.ts
|
|
3315
|
+
/**
|
|
3316
|
+
* `toDate format value` — parse `value` string using Go's reference-time
|
|
3317
|
+
* layout. Returns a `Date`. Mirrors Go sprig's `toDate`.
|
|
3318
|
+
*/
|
|
3319
|
+
function toDate(format, value) {
|
|
3320
|
+
return parseGoLayout(format, value);
|
|
3321
|
+
}
|
|
3322
|
+
//#endregion
|
|
3323
|
+
//#region src/sprig/datetime/unixEpoch.ts
|
|
3324
|
+
/** `unixEpoch t` — seconds since Unix epoch as a decimal string. */
|
|
3325
|
+
function unixEpoch(t) {
|
|
3326
|
+
return String(Math.floor(resolveDate(t).getTime() / 1e3));
|
|
3327
|
+
}
|
|
3328
|
+
//#endregion
|
|
3329
|
+
//#region src/sprig/datetime/index.ts
|
|
3330
|
+
/**
|
|
3331
|
+
* Build the sprig date/time FuncMap.
|
|
3332
|
+
*
|
|
3333
|
+
* @param clock - Source of "current time". Defaults to `() => new Date()`.
|
|
3334
|
+
* Pass a frozen clock for deterministic test output (mirrors
|
|
3335
|
+
* `EngineConfig.clock`).
|
|
3336
|
+
*/
|
|
3337
|
+
function sprigDatetime(clock = () => /* @__PURE__ */ new Date()) {
|
|
3338
|
+
return {
|
|
3339
|
+
now: {
|
|
3340
|
+
fn: () => now(clock),
|
|
3341
|
+
argTypes: []
|
|
3342
|
+
},
|
|
3343
|
+
date: {
|
|
3344
|
+
fn: (format, t) => date(format, t),
|
|
3345
|
+
argTypes: ["string", "value"]
|
|
3346
|
+
},
|
|
3347
|
+
dateInZone: {
|
|
3348
|
+
fn: (format, t, zone) => dateInZone(format, t, zone),
|
|
3349
|
+
argTypes: [
|
|
3350
|
+
"string",
|
|
3351
|
+
"value",
|
|
3352
|
+
"string"
|
|
3353
|
+
]
|
|
3354
|
+
},
|
|
3355
|
+
dateModify: {
|
|
3356
|
+
fn: (dur, t) => dateModify(dur, t),
|
|
3357
|
+
argTypes: ["string", "value"]
|
|
3358
|
+
},
|
|
3359
|
+
htmlDate: {
|
|
3360
|
+
fn: (t) => htmlDate(t),
|
|
3361
|
+
argTypes: ["value"]
|
|
3362
|
+
},
|
|
3363
|
+
htmlDateInZone: {
|
|
3364
|
+
fn: (t, zone) => htmlDateInZone(t, zone),
|
|
3365
|
+
argTypes: ["value", "string"]
|
|
3366
|
+
},
|
|
3367
|
+
duration: {
|
|
3368
|
+
fn: (sec) => duration(sec),
|
|
3369
|
+
argTypes: ["value"]
|
|
3370
|
+
},
|
|
3371
|
+
durationRound: {
|
|
3372
|
+
fn: (d) => durationRound(d),
|
|
3373
|
+
argTypes: ["value"]
|
|
3374
|
+
},
|
|
3375
|
+
toDate: {
|
|
3376
|
+
fn: (format, s) => toDate(format, s),
|
|
3377
|
+
argTypes: ["string", "string"]
|
|
3378
|
+
},
|
|
3379
|
+
ago: {
|
|
3380
|
+
fn: (t) => ago(t, clock),
|
|
3381
|
+
argTypes: ["value"]
|
|
3382
|
+
},
|
|
3383
|
+
unixEpoch: {
|
|
3384
|
+
fn: (t) => unixEpoch(t),
|
|
3385
|
+
argTypes: ["value"]
|
|
3386
|
+
}
|
|
3387
|
+
};
|
|
3388
|
+
}
|
|
3389
|
+
//#endregion
|
|
3390
|
+
//#region src/sprig/defaults/empty.ts
|
|
3391
|
+
/**
|
|
3392
|
+
* `empty val` — true if `val` is "empty" per Go sprig's rules:
|
|
3393
|
+
* nil, false, 0, 0.0, "", empty array/Map/object.
|
|
3394
|
+
*
|
|
3395
|
+
* Note: `empty 0` is true (this surprises newcomers — Go sprig matches
|
|
3396
|
+
* Go's reflect-IsZero semantics).
|
|
3397
|
+
*/
|
|
3398
|
+
function empty(value) {
|
|
3399
|
+
if (value === null || value === void 0) return true;
|
|
3400
|
+
if (value === false) return true;
|
|
3401
|
+
if (typeof value === "number") return value === 0 || Number.isNaN(value);
|
|
3402
|
+
if (typeof value === "bigint") return value === 0n;
|
|
3403
|
+
if (typeof value === "string") return value.length === 0;
|
|
3404
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
3405
|
+
if (value instanceof Map) return value.size === 0;
|
|
3406
|
+
if (value instanceof Set) return value.size === 0;
|
|
3407
|
+
if (typeof value === "object") return Object.keys(value).length === 0;
|
|
3408
|
+
return false;
|
|
3409
|
+
}
|
|
3410
|
+
//#endregion
|
|
3411
|
+
//#region src/sprig/defaults/coalesce.ts
|
|
3412
|
+
/**
|
|
3413
|
+
* `coalesce a b c …` — returns the first non-empty argument, or
|
|
3414
|
+
* undefined if none are non-empty.
|
|
3415
|
+
*/
|
|
3416
|
+
function coalesce(...values) {
|
|
3417
|
+
for (const v of values) if (!empty(v)) return v;
|
|
3418
|
+
}
|
|
3419
|
+
//#endregion
|
|
3420
|
+
//#region src/sprig/defaults/default.ts
|
|
3421
|
+
/**
|
|
3422
|
+
* `default defaultVal val` — returns `val` if non-empty (per `empty`),
|
|
3423
|
+
* else `defaultVal`.
|
|
3424
|
+
*
|
|
3425
|
+
* Argument order matches Go sprig: the *default* comes first, the
|
|
3426
|
+
* value comes second. Pipelines feed the trailing arg, so
|
|
3427
|
+
* `{{ .name | default "anonymous" }}` evaluates default("anonymous", .name).
|
|
3428
|
+
*/
|
|
3429
|
+
function defaultFn(defaultVal, value) {
|
|
3430
|
+
return empty(value) ? defaultVal : value;
|
|
3431
|
+
}
|
|
3432
|
+
//#endregion
|
|
3433
|
+
//#region src/sprig/defaults/fromJson.ts
|
|
3434
|
+
/**
|
|
3435
|
+
* `fromJson s` — parses a JSON string into a value.
|
|
3436
|
+
*
|
|
3437
|
+
* Returns the parsed value. Throws if the input is not valid JSON,
|
|
3438
|
+
* matching Go sprig's behaviour (Go sprig propagates the parse error).
|
|
3439
|
+
*/
|
|
3440
|
+
function fromJson(input) {
|
|
3441
|
+
return JSON.parse(input);
|
|
3442
|
+
}
|
|
3443
|
+
//#endregion
|
|
3444
|
+
//#region src/sprig/defaults/ternary.ts
|
|
3445
|
+
/**
|
|
3446
|
+
* `ternary trueVal falseVal cond` — returns `trueVal` if `cond` is
|
|
3447
|
+
* truthy, else `falseVal`.
|
|
3448
|
+
*
|
|
3449
|
+
* Note: argument order matches Go sprig and surprises newcomers.
|
|
3450
|
+
* Pipelines feed cond as the trailing arg, e.g.
|
|
3451
|
+
* `{{ .ok | ternary "YES" "NO" }}` → ternary("YES", "NO", .ok)
|
|
3452
|
+
*/
|
|
3453
|
+
function ternary(trueVal, falseVal, cond) {
|
|
3454
|
+
return isTruthy(cond) ? trueVal : falseVal;
|
|
3455
|
+
}
|
|
3456
|
+
//#endregion
|
|
3457
|
+
//#region src/sprig/defaults/toJson.ts
|
|
3458
|
+
/**
|
|
3459
|
+
* `toJson val` — serializes a value to compact JSON.
|
|
3460
|
+
*
|
|
3461
|
+
* Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that
|
|
3462
|
+
* `JSON.stringify(undefined)` is undefined; we coerce that to "null"
|
|
3463
|
+
* for byte-equivalence with Go's encoding/json (which encodes
|
|
3464
|
+
* untyped-nil as null).
|
|
3465
|
+
*/
|
|
3466
|
+
function toJson(value) {
|
|
3467
|
+
return JSON.stringify(value) ?? "null";
|
|
3468
|
+
}
|
|
3469
|
+
//#endregion
|
|
3470
|
+
//#region src/sprig/defaults/toPrettyJson.ts
|
|
3471
|
+
/**
|
|
3472
|
+
* `toPrettyJson val` — JSON with 2-space indentation, matching Go
|
|
3473
|
+
* sprig's output exactly.
|
|
3474
|
+
*/
|
|
3475
|
+
function toPrettyJson(value) {
|
|
3476
|
+
return JSON.stringify(value, null, 2) ?? "null";
|
|
3477
|
+
}
|
|
3478
|
+
//#endregion
|
|
3479
|
+
//#region src/sprig/defaults/index.ts
|
|
3480
|
+
function sprigDefaults() {
|
|
3481
|
+
return {
|
|
3482
|
+
default: {
|
|
3483
|
+
fn: (a, b) => defaultFn(a, b),
|
|
3484
|
+
argTypes: ["value", "truthy"]
|
|
3485
|
+
},
|
|
3486
|
+
empty: {
|
|
3487
|
+
fn: (v) => empty(v),
|
|
3488
|
+
argTypes: ["truthy"]
|
|
3489
|
+
},
|
|
3490
|
+
coalesce: {
|
|
3491
|
+
fn: (...vs) => coalesce(...vs),
|
|
3492
|
+
argTypes: ["truthy"]
|
|
3493
|
+
},
|
|
3494
|
+
ternary: {
|
|
3495
|
+
fn: (a, b, c) => ternary(a, b, c),
|
|
3496
|
+
argTypes: [
|
|
3497
|
+
"value",
|
|
3498
|
+
"value",
|
|
3499
|
+
"truthy"
|
|
3500
|
+
]
|
|
3501
|
+
},
|
|
3502
|
+
fromJson: {
|
|
3503
|
+
fn: (s) => fromJson(s),
|
|
3504
|
+
argTypes: ["string"]
|
|
3505
|
+
},
|
|
3506
|
+
toJson: {
|
|
3507
|
+
fn: (v) => toJson(v),
|
|
3508
|
+
argTypes: ["serializable"],
|
|
3509
|
+
returnType: "string"
|
|
3510
|
+
},
|
|
3511
|
+
toPrettyJson: {
|
|
3512
|
+
fn: (v) => toPrettyJson(v),
|
|
3513
|
+
argTypes: ["serializable"],
|
|
3514
|
+
returnType: "string"
|
|
3515
|
+
}
|
|
3516
|
+
};
|
|
3517
|
+
}
|
|
3518
|
+
//#endregion
|
|
3519
|
+
//#region src/sprig/dicts/dict.ts
|
|
3520
|
+
/**
|
|
3521
|
+
* `dict k1 v1 k2 v2 …` — builds a record from alternating key/value pairs.
|
|
3522
|
+
*
|
|
3523
|
+
* [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates
|
|
3524
|
+
* the kv cycle via `argTypePattern: "alternating"` against
|
|
3525
|
+
* `argTypes: ["string", "value"]`, so every key position is a string by
|
|
3526
|
+
* the time the body runs. The body trusts the gate; no per-key probe.
|
|
3527
|
+
*
|
|
3528
|
+
* Odd-length call (`dict "a"`) leaves the last value `undefined` —
|
|
3529
|
+
* matches Go sprig.
|
|
3530
|
+
*/
|
|
3531
|
+
function dict(...kvs) {
|
|
3532
|
+
const out = {};
|
|
3533
|
+
for (let i = 0; i < kvs.length; i += 2) out[kvs[i]] = kvs[i + 1];
|
|
3534
|
+
return out;
|
|
3535
|
+
}
|
|
3536
|
+
//#endregion
|
|
3537
|
+
//#region src/sprig/dicts/get.ts
|
|
3538
|
+
/**
|
|
3539
|
+
* `get d key` — returns d[key] or undefined.
|
|
3540
|
+
*
|
|
3541
|
+
* [LAW:single-enforcer] The gate validates `d` is a plain object
|
|
3542
|
+
* (`"dict"`); the body trusts the receiver type. The Map case lives in
|
|
3543
|
+
* template-laws-3gt.7 (where the slot widens with an explicit Map-key
|
|
3544
|
+
* carve-out per audit B5/B6) — until then, Maps are rejected at the
|
|
3545
|
+
* gate.
|
|
3546
|
+
*/
|
|
3547
|
+
function get(d, key) {
|
|
3548
|
+
return d[key];
|
|
3549
|
+
}
|
|
3550
|
+
//#endregion
|
|
3551
|
+
//#region src/sprig/dicts/hasKey.ts
|
|
3552
|
+
/**
|
|
3553
|
+
* `hasKey d key` — true when `key` is a own-property of `d`.
|
|
3554
|
+
*
|
|
3555
|
+
* Note: sprig's name is `hasKey` though docs sometimes say `haskey`.
|
|
3556
|
+
* [LAW:single-enforcer] Receiver type validated at the gate.
|
|
3557
|
+
*/
|
|
3558
|
+
function hasKey(d, key) {
|
|
3559
|
+
return key in d;
|
|
2454
3560
|
}
|
|
2455
3561
|
//#endregion
|
|
2456
3562
|
//#region src/sprig/dicts/keys.ts
|
|
@@ -2597,41 +3703,258 @@ function sprigDicts() {
|
|
|
2597
3703
|
fn: (d, k) => unset(d, k),
|
|
2598
3704
|
argTypes: ["dict", "string"]
|
|
2599
3705
|
},
|
|
2600
|
-
keys: {
|
|
2601
|
-
fn: (d) => keys(d),
|
|
2602
|
-
argTypes: ["dict"]
|
|
3706
|
+
keys: {
|
|
3707
|
+
fn: (d) => keys(d),
|
|
3708
|
+
argTypes: ["dict"]
|
|
3709
|
+
},
|
|
3710
|
+
values: {
|
|
3711
|
+
fn: (d) => values(d),
|
|
3712
|
+
argTypes: ["dict"]
|
|
3713
|
+
},
|
|
3714
|
+
pluck: {
|
|
3715
|
+
fn: (k, ...d) => pluck(k, ...d),
|
|
3716
|
+
argTypes: ["string", "dict"]
|
|
3717
|
+
},
|
|
3718
|
+
pick: {
|
|
3719
|
+
fn: (d, ...k) => pick(d, ...k),
|
|
3720
|
+
argTypes: ["dict", "string"]
|
|
3721
|
+
},
|
|
3722
|
+
omit: {
|
|
3723
|
+
fn: (d, ...k) => omit(d, ...k),
|
|
3724
|
+
argTypes: ["dict", "string"]
|
|
3725
|
+
},
|
|
3726
|
+
hasKey: {
|
|
3727
|
+
fn: (d, k) => hasKey(d, k),
|
|
3728
|
+
argTypes: ["dict", "string"]
|
|
3729
|
+
},
|
|
3730
|
+
merge: {
|
|
3731
|
+
fn: (d, ...s) => merge(d, ...s),
|
|
3732
|
+
argTypes: ["dict"]
|
|
3733
|
+
},
|
|
3734
|
+
mergeOverwrite: {
|
|
3735
|
+
fn: (d, ...s) => mergeOverwrite(d, ...s),
|
|
3736
|
+
argTypes: ["dict"]
|
|
3737
|
+
}
|
|
3738
|
+
};
|
|
3739
|
+
}
|
|
3740
|
+
//#endregion
|
|
3741
|
+
//#region src/sprig/flow/fail.ts
|
|
3742
|
+
/**
|
|
3743
|
+
* `fail msg` — unconditionally abort template evaluation with `msg`.
|
|
3744
|
+
*
|
|
3745
|
+
* Mirrors Go sprig's `fail`, which returns `(string, error)` and causes
|
|
3746
|
+
* text/template to stop execution. Throws `FailError` so consumers can
|
|
3747
|
+
* catch it specifically and distinguish it from engine errors.
|
|
3748
|
+
*
|
|
3749
|
+
* [LAW:types-are-the-program] Return type `never` encodes the invariant
|
|
3750
|
+
* that this function never returns — the type system enforces what a
|
|
3751
|
+
* comment would only suggest.
|
|
3752
|
+
*/
|
|
3753
|
+
function fail(msg) {
|
|
3754
|
+
throw new FailError(msg);
|
|
3755
|
+
}
|
|
3756
|
+
//#endregion
|
|
3757
|
+
//#region src/sprig/flow/index.ts
|
|
3758
|
+
function sprigFlow() {
|
|
3759
|
+
return { fail: {
|
|
3760
|
+
fn: (msg) => fail(msg),
|
|
3761
|
+
argTypes: ["string"]
|
|
3762
|
+
} };
|
|
3763
|
+
}
|
|
3764
|
+
//#endregion
|
|
3765
|
+
//#region src/sprig/hash/adler32sum.ts
|
|
3766
|
+
const _enc$2 = new TextEncoder();
|
|
3767
|
+
const MOD_ADLER = 65521;
|
|
3768
|
+
/**
|
|
3769
|
+
* `adler32sum s` — Adler-32 checksum of `s` as a decimal string.
|
|
3770
|
+
*
|
|
3771
|
+
* Matches Go's `hash/adler32.Checksum([]byte(s))` formatted with `%d`.
|
|
3772
|
+
* Uses unsigned 32-bit arithmetic via `>>> 0` to mirror Go's uint32 result.
|
|
3773
|
+
*/
|
|
3774
|
+
function adler32sum(s) {
|
|
3775
|
+
const bytes = _enc$2.encode(s);
|
|
3776
|
+
let a = 1;
|
|
3777
|
+
let b = 0;
|
|
3778
|
+
for (const byte of bytes) {
|
|
3779
|
+
a = (a + byte) % MOD_ADLER;
|
|
3780
|
+
b = (b + a) % MOD_ADLER;
|
|
3781
|
+
}
|
|
3782
|
+
return String(b * 65536 + a >>> 0);
|
|
3783
|
+
}
|
|
3784
|
+
//#endregion
|
|
3785
|
+
//#region src/sprig/hash/_b32.ts
|
|
3786
|
+
/**
|
|
3787
|
+
* [LAW:one-source-of-truth] RFC 4648 base32 alphabet and decode table —
|
|
3788
|
+
* shared by b32enc and b32dec.
|
|
3789
|
+
*/
|
|
3790
|
+
const ALPHA32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
3791
|
+
/** Reverse lookup: character → 5-bit value. */
|
|
3792
|
+
const DECODE32 = new Map(Array.from(ALPHA32).map((c, i) => [c, i]));
|
|
3793
|
+
//#endregion
|
|
3794
|
+
//#region src/sprig/hash/b32dec.ts
|
|
3795
|
+
const _dec$1 = new TextDecoder();
|
|
3796
|
+
/** `b32dec s` — RFC 4648 base32 decoded back to a UTF-8 string. */
|
|
3797
|
+
function b32dec(s) {
|
|
3798
|
+
const stripped = s.replace(/=+$/, "").toUpperCase();
|
|
3799
|
+
const bytes = [];
|
|
3800
|
+
let bits = 0;
|
|
3801
|
+
let value = 0;
|
|
3802
|
+
for (const c of stripped) {
|
|
3803
|
+
const v = DECODE32.get(c);
|
|
3804
|
+
if (v === void 0) throw new Error(`b32dec: invalid character '${c}'`);
|
|
3805
|
+
value = value << 5 | v;
|
|
3806
|
+
bits += 5;
|
|
3807
|
+
if (bits >= 8) {
|
|
3808
|
+
bits -= 8;
|
|
3809
|
+
bytes.push(value >> bits & 255);
|
|
3810
|
+
}
|
|
3811
|
+
}
|
|
3812
|
+
return _dec$1.decode(new Uint8Array(bytes));
|
|
3813
|
+
}
|
|
3814
|
+
//#endregion
|
|
3815
|
+
//#region src/sprig/hash/b32enc.ts
|
|
3816
|
+
const _enc$1 = new TextEncoder();
|
|
3817
|
+
/** `b32enc s` — UTF-8 bytes of `s` encoded as RFC 4648 base32. */
|
|
3818
|
+
function b32enc(s) {
|
|
3819
|
+
const bytes = _enc$1.encode(s);
|
|
3820
|
+
let result = "";
|
|
3821
|
+
let bits = 0;
|
|
3822
|
+
let value = 0;
|
|
3823
|
+
for (const byte of bytes) {
|
|
3824
|
+
value = value << 8 | byte;
|
|
3825
|
+
bits += 8;
|
|
3826
|
+
while (bits >= 5) {
|
|
3827
|
+
bits -= 5;
|
|
3828
|
+
result += ALPHA32[value >> bits & 31];
|
|
3829
|
+
}
|
|
3830
|
+
}
|
|
3831
|
+
if (bits > 0) result += ALPHA32[value << 5 - bits & 31];
|
|
3832
|
+
while (result.length % 8 !== 0) result += "=";
|
|
3833
|
+
return result;
|
|
3834
|
+
}
|
|
3835
|
+
//#endregion
|
|
3836
|
+
//#region src/sprig/hash/b64dec.ts
|
|
3837
|
+
const _dec = new TextDecoder();
|
|
3838
|
+
/** `b64dec s` — standard base64 decoded back to a UTF-8 string. */
|
|
3839
|
+
function b64dec(s) {
|
|
3840
|
+
const binary = atob(s);
|
|
3841
|
+
const bytes = new Uint8Array(binary.length);
|
|
3842
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
3843
|
+
return _dec.decode(bytes);
|
|
3844
|
+
}
|
|
3845
|
+
//#endregion
|
|
3846
|
+
//#region src/sprig/hash/b64enc.ts
|
|
3847
|
+
const _enc = new TextEncoder();
|
|
3848
|
+
/** `b64enc s` — UTF-8 bytes of `s` encoded as standard base64. */
|
|
3849
|
+
function b64enc(s) {
|
|
3850
|
+
const bytes = _enc.encode(s);
|
|
3851
|
+
const chars = [];
|
|
3852
|
+
for (const b of bytes) chars.push(String.fromCharCode(b));
|
|
3853
|
+
return btoa(chars.join(""));
|
|
3854
|
+
}
|
|
3855
|
+
//#endregion
|
|
3856
|
+
//#region src/sprig/hash/sha1sum.ts
|
|
3857
|
+
/** `sha1sum s` — hex-encoded SHA-1 digest of `s` (UTF-8). */
|
|
3858
|
+
function sha1sum(s) {
|
|
3859
|
+
return bytesToHex(sha1(utf8ToBytes(s)));
|
|
3860
|
+
}
|
|
3861
|
+
//#endregion
|
|
3862
|
+
//#region src/sprig/hash/sha256sum.ts
|
|
3863
|
+
/** `sha256sum s` — hex-encoded SHA-256 digest of `s` (UTF-8). */
|
|
3864
|
+
function sha256sum(s) {
|
|
3865
|
+
return bytesToHex(sha256(utf8ToBytes(s)));
|
|
3866
|
+
}
|
|
3867
|
+
//#endregion
|
|
3868
|
+
//#region src/sprig/hash/sha512sum.ts
|
|
3869
|
+
/** `sha512sum s` — hex-encoded SHA-512 digest of `s` (UTF-8). */
|
|
3870
|
+
function sha512sum(s) {
|
|
3871
|
+
return bytesToHex(sha512(utf8ToBytes(s)));
|
|
3872
|
+
}
|
|
3873
|
+
//#endregion
|
|
3874
|
+
//#region src/sprig/hash/uuidv4.ts
|
|
3875
|
+
/**
|
|
3876
|
+
* `uuidv4` — RFC 4122 v4 UUID via `globalThis.crypto.randomUUID()`.
|
|
3877
|
+
*
|
|
3878
|
+
* Available in Node >= 20.19 (package minimum), Bun, Deno, and all modern browsers.
|
|
3879
|
+
* Throws if the runtime lacks `crypto.randomUUID` — this should never
|
|
3880
|
+
* happen in the supported environment set.
|
|
3881
|
+
*/
|
|
3882
|
+
function uuidv4() {
|
|
3883
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") throw new Error("uuidv4: globalThis.crypto.randomUUID is not available");
|
|
3884
|
+
return globalThis.crypto.randomUUID();
|
|
3885
|
+
}
|
|
3886
|
+
//#endregion
|
|
3887
|
+
//#region src/sprig/hash/index.ts
|
|
3888
|
+
/** Build the sprig hash/encoding FuncMap. */
|
|
3889
|
+
function sprigHash() {
|
|
3890
|
+
return {
|
|
3891
|
+
b64enc: {
|
|
3892
|
+
fn: (s) => b64enc(s),
|
|
3893
|
+
argTypes: ["string"]
|
|
3894
|
+
},
|
|
3895
|
+
b64dec: {
|
|
3896
|
+
fn: (s) => b64dec(s),
|
|
3897
|
+
argTypes: ["string"]
|
|
2603
3898
|
},
|
|
2604
|
-
|
|
2605
|
-
fn: (
|
|
2606
|
-
argTypes: ["
|
|
3899
|
+
b32enc: {
|
|
3900
|
+
fn: (s) => b32enc(s),
|
|
3901
|
+
argTypes: ["string"]
|
|
2607
3902
|
},
|
|
2608
|
-
|
|
2609
|
-
fn: (
|
|
2610
|
-
argTypes: ["string"
|
|
3903
|
+
b32dec: {
|
|
3904
|
+
fn: (s) => b32dec(s),
|
|
3905
|
+
argTypes: ["string"]
|
|
2611
3906
|
},
|
|
2612
|
-
|
|
2613
|
-
fn: (
|
|
2614
|
-
argTypes: ["
|
|
3907
|
+
sha1sum: {
|
|
3908
|
+
fn: (s) => sha1sum(s),
|
|
3909
|
+
argTypes: ["string"]
|
|
2615
3910
|
},
|
|
2616
|
-
|
|
2617
|
-
fn: (
|
|
2618
|
-
argTypes: ["
|
|
3911
|
+
sha256sum: {
|
|
3912
|
+
fn: (s) => sha256sum(s),
|
|
3913
|
+
argTypes: ["string"]
|
|
2619
3914
|
},
|
|
2620
|
-
|
|
2621
|
-
fn: (
|
|
2622
|
-
argTypes: ["
|
|
3915
|
+
sha512sum: {
|
|
3916
|
+
fn: (s) => sha512sum(s),
|
|
3917
|
+
argTypes: ["string"]
|
|
2623
3918
|
},
|
|
2624
|
-
|
|
2625
|
-
fn: (
|
|
2626
|
-
argTypes: ["
|
|
3919
|
+
adler32sum: {
|
|
3920
|
+
fn: (s) => adler32sum(s),
|
|
3921
|
+
argTypes: ["string"]
|
|
2627
3922
|
},
|
|
2628
|
-
|
|
2629
|
-
fn: (
|
|
2630
|
-
argTypes: [
|
|
3923
|
+
uuidv4: {
|
|
3924
|
+
fn: () => uuidv4(),
|
|
3925
|
+
argTypes: []
|
|
2631
3926
|
}
|
|
2632
3927
|
};
|
|
2633
3928
|
}
|
|
2634
3929
|
//#endregion
|
|
3930
|
+
//#region src/sprig/lists/all.ts
|
|
3931
|
+
/**
|
|
3932
|
+
* `all v1 v2 …` — true iff `empty(x)` is false for every argument.
|
|
3933
|
+
* An empty argument list returns true (Go sprig: vacuous truth).
|
|
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 all(...values) {
|
|
3940
|
+
for (const v of values) if (empty(v)) return false;
|
|
3941
|
+
return true;
|
|
3942
|
+
}
|
|
3943
|
+
//#endregion
|
|
3944
|
+
//#region src/sprig/lists/any.ts
|
|
3945
|
+
/**
|
|
3946
|
+
* `any v1 v2 …` — true iff `empty(x)` is false for at least one
|
|
3947
|
+
* argument. An empty argument list returns false.
|
|
3948
|
+
*
|
|
3949
|
+
* [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper
|
|
3950
|
+
* the rest of the sprig surface (default, coalesce, empty) routes
|
|
3951
|
+
* through, so "is this empty?" has exactly one answer.
|
|
3952
|
+
*/
|
|
3953
|
+
function any(...values) {
|
|
3954
|
+
for (const v of values) if (!empty(v)) return true;
|
|
3955
|
+
return false;
|
|
3956
|
+
}
|
|
3957
|
+
//#endregion
|
|
2635
3958
|
//#region src/sprig/lists/append.ts
|
|
2636
3959
|
/** `append list item` — add item at the end. */
|
|
2637
3960
|
function append(list, item) {
|
|
@@ -2641,7 +3964,7 @@ function append(list, item) {
|
|
|
2641
3964
|
//#region src/sprig/lists/chunk.ts
|
|
2642
3965
|
/** `chunk size list` — split list into sub-lists of `size`. */
|
|
2643
3966
|
function chunk(size, list) {
|
|
2644
|
-
const n = Math.max(1,
|
|
3967
|
+
const n = Math.max(1, size);
|
|
2645
3968
|
const out = [];
|
|
2646
3969
|
for (let i = 0; i < list.length; i += n) out.push(list.slice(i, i + n));
|
|
2647
3970
|
return out;
|
|
@@ -2661,6 +3984,82 @@ function concat(...lists) {
|
|
|
2661
3984
|
return out;
|
|
2662
3985
|
}
|
|
2663
3986
|
//#endregion
|
|
3987
|
+
//#region src/evaluator/errors.ts
|
|
3988
|
+
/**
|
|
3989
|
+
* Re-exports from the unified error module, plus a small helper for
|
|
3990
|
+
* constructing `TypeMismatchError` from inside sprig func bodies.
|
|
3991
|
+
*
|
|
3992
|
+
* Historical location — code that imported from this path keeps
|
|
3993
|
+
* working. New code should import directly from `src/errors.ts`.
|
|
3994
|
+
*/
|
|
3995
|
+
const NO_POS = {
|
|
3996
|
+
line: 0,
|
|
3997
|
+
column: 0,
|
|
3998
|
+
offset: 0
|
|
3999
|
+
};
|
|
4000
|
+
/**
|
|
4001
|
+
* Construct a TypeMismatchError from inside a registered func body,
|
|
4002
|
+
* where the call-site `pos` is unavailable. The dispatch site
|
|
4003
|
+
* (`evalCommand`) catches this and re-emits with the correct pos —
|
|
4004
|
+
* see [LAW:single-enforcer] in evaluator.ts.
|
|
4005
|
+
*
|
|
4006
|
+
* Use when the gate cannot validate (nested elements, alternating
|
|
4007
|
+
* variadic positions). For first-class arg validation, declare the
|
|
4008
|
+
* type in `argTypes` so `enforceArgTypes` catches it at the boundary.
|
|
4009
|
+
*/
|
|
4010
|
+
function bodyTypeMismatch(funcName, argIndex, expected, receivedSummary) {
|
|
4011
|
+
return new TypeMismatchError(funcName, argIndex, expected, receivedSummary, NO_POS);
|
|
4012
|
+
}
|
|
4013
|
+
//#endregion
|
|
4014
|
+
//#region src/sprig/lists/dig.ts
|
|
4015
|
+
/**
|
|
4016
|
+
* `dig key1 key2 … default dict` — walks nested dict by string keys,
|
|
4017
|
+
* returning the deepest value found, or `default` when a key along
|
|
4018
|
+
* the path is missing.
|
|
4019
|
+
*
|
|
4020
|
+
* The argument shape is *positional from the end*:
|
|
4021
|
+
*
|
|
4022
|
+
* dig "a" "b" "c" <default> <dict>
|
|
4023
|
+
*
|
|
4024
|
+
* — last arg is the dict, the one before it is the default, every
|
|
4025
|
+
* preceding arg is a string key. This shape comes straight from Go
|
|
4026
|
+
* sprig and is unintuitive but documented.
|
|
4027
|
+
*
|
|
4028
|
+
* [LAW:single-enforcer] exception: `argTypes: ["value"]` (variadic
|
|
4029
|
+
* trailing slot) — the from-the-end positional shape cannot be
|
|
4030
|
+
* expressed by the gate's positional-from-the-start + trailing-repeat
|
|
4031
|
+
* model. We accept body-side validation here and use
|
|
4032
|
+
* `bodyTypeMismatch` so failures still surface as TypeMismatchError
|
|
4033
|
+
* with the correct call-site pos.
|
|
4034
|
+
*/
|
|
4035
|
+
function dig(...args) {
|
|
4036
|
+
if (args.length < 3) throw bodyTypeMismatch("dig", 0, "at least 3 arguments (...keys, default, dict)", `${args.length} argument${args.length === 1 ? "" : "s"}`);
|
|
4037
|
+
const dict = args[args.length - 1];
|
|
4038
|
+
const def = args[args.length - 2];
|
|
4039
|
+
const keys = args.slice(0, -2);
|
|
4040
|
+
if (!isPlainDict(dict)) throw bodyTypeMismatch("dig", args.length - 1, "dict", describeKind(dict));
|
|
4041
|
+
for (let i = 0; i < keys.length; i++) if (typeof keys[i] !== "string") throw bodyTypeMismatch("dig", i, "string", describeKind(keys[i]));
|
|
4042
|
+
return digFromDict(dict, def, keys, args.length);
|
|
4043
|
+
}
|
|
4044
|
+
function digFromDict(d, def, ks, argCount) {
|
|
4045
|
+
const k = ks[0];
|
|
4046
|
+
if (!Object.hasOwn(d, k)) return def;
|
|
4047
|
+
const step = d[k];
|
|
4048
|
+
if (ks.length === 1) return step;
|
|
4049
|
+
if (!isPlainDict(step)) throw bodyTypeMismatch("dig", argCount - 1, "dict at intermediate key", describeKind(step));
|
|
4050
|
+
return digFromDict(step, def, ks.slice(1), argCount);
|
|
4051
|
+
}
|
|
4052
|
+
function isPlainDict(v) {
|
|
4053
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Map) && !(v instanceof Set);
|
|
4054
|
+
}
|
|
4055
|
+
function describeKind(v) {
|
|
4056
|
+
if (v === null) return "null";
|
|
4057
|
+
if (Array.isArray(v)) return "array";
|
|
4058
|
+
if (v instanceof Map) return "Map";
|
|
4059
|
+
if (v instanceof Set) return "Set";
|
|
4060
|
+
return typeof v;
|
|
4061
|
+
}
|
|
4062
|
+
//#endregion
|
|
2664
4063
|
//#region src/sprig/lists/first.ts
|
|
2665
4064
|
function first(list) {
|
|
2666
4065
|
return list[0];
|
|
@@ -2727,11 +4126,31 @@ function reverse(list) {
|
|
|
2727
4126
|
//#region src/sprig/lists/slice.ts
|
|
2728
4127
|
/** `slice list [i [j]]` — Array.prototype.slice. */
|
|
2729
4128
|
function slice(list, i, j) {
|
|
2730
|
-
const start = i === void 0 ? 0 :
|
|
2731
|
-
const end = j === void 0 ? list.length :
|
|
4129
|
+
const start = i === void 0 ? 0 : i;
|
|
4130
|
+
const end = j === void 0 ? list.length : j;
|
|
2732
4131
|
return list.slice(start, end);
|
|
2733
4132
|
}
|
|
2734
4133
|
//#endregion
|
|
4134
|
+
//#region src/sprig/lists/sortAlpha.ts
|
|
4135
|
+
/**
|
|
4136
|
+
* `sortAlpha list` — stringify each element, sort lexicographically.
|
|
4137
|
+
* Returns `string[]`.
|
|
4138
|
+
*
|
|
4139
|
+
* Mirrors Go sprig's `sortAlpha`, which calls `strslice` (skips nil
|
|
4140
|
+
* entries, stringifies the rest via `strval`) then `sort.StringSlice`.
|
|
4141
|
+
* `String(v)` lines up with Go's `%v` for primitives; non-ASCII byte
|
|
4142
|
+
* ordering is identical to Go's `sort.StringSlice` for ASCII input
|
|
4143
|
+
* (the only kind the conformance fixtures exercise).
|
|
4144
|
+
*/
|
|
4145
|
+
function sortAlpha(list) {
|
|
4146
|
+
const out = [];
|
|
4147
|
+
for (const v of list) {
|
|
4148
|
+
if (v === null || v === void 0) continue;
|
|
4149
|
+
out.push(String(v));
|
|
4150
|
+
}
|
|
4151
|
+
return out.sort();
|
|
4152
|
+
}
|
|
4153
|
+
//#endregion
|
|
2735
4154
|
//#region src/sprig/lists/uniq.ts
|
|
2736
4155
|
/** Unique values, preserving first-occurrence order. */
|
|
2737
4156
|
function uniq(list) {
|
|
@@ -2797,8 +4216,8 @@ function sprigLists() {
|
|
|
2797
4216
|
fn: (l, i, j) => slice(l, i, j),
|
|
2798
4217
|
argTypes: [
|
|
2799
4218
|
"list",
|
|
2800
|
-
"
|
|
2801
|
-
"
|
|
4219
|
+
"int",
|
|
4220
|
+
"int"
|
|
2802
4221
|
]
|
|
2803
4222
|
},
|
|
2804
4223
|
concat: {
|
|
@@ -2807,7 +4226,7 @@ function sprigLists() {
|
|
|
2807
4226
|
},
|
|
2808
4227
|
chunk: {
|
|
2809
4228
|
fn: (s, l) => chunk(s, l),
|
|
2810
|
-
argTypes: ["
|
|
4229
|
+
argTypes: ["int", "list"]
|
|
2811
4230
|
},
|
|
2812
4231
|
prepend: {
|
|
2813
4232
|
fn: (l, i) => prepend(l, i),
|
|
@@ -2816,6 +4235,33 @@ function sprigLists() {
|
|
|
2816
4235
|
append: {
|
|
2817
4236
|
fn: (l, i) => append(l, i),
|
|
2818
4237
|
argTypes: ["list", "value"]
|
|
4238
|
+
},
|
|
4239
|
+
sortAlpha: {
|
|
4240
|
+
fn: (l) => sortAlpha(l),
|
|
4241
|
+
argTypes: ["list"],
|
|
4242
|
+
returnType: "list"
|
|
4243
|
+
},
|
|
4244
|
+
push: {
|
|
4245
|
+
fn: (l, i) => append(l, i),
|
|
4246
|
+
argTypes: ["list", "value"]
|
|
4247
|
+
},
|
|
4248
|
+
tuple: {
|
|
4249
|
+
fn: (...a) => list(...a),
|
|
4250
|
+
argTypes: ["value"]
|
|
4251
|
+
},
|
|
4252
|
+
dig: {
|
|
4253
|
+
fn: (...a) => dig(...a),
|
|
4254
|
+
argTypes: ["value"]
|
|
4255
|
+
},
|
|
4256
|
+
all: {
|
|
4257
|
+
fn: (...a) => all(...a),
|
|
4258
|
+
argTypes: ["truthy"],
|
|
4259
|
+
returnType: "bool"
|
|
4260
|
+
},
|
|
4261
|
+
any: {
|
|
4262
|
+
fn: (...a) => any(...a),
|
|
4263
|
+
argTypes: ["truthy"],
|
|
4264
|
+
returnType: "bool"
|
|
2819
4265
|
}
|
|
2820
4266
|
};
|
|
2821
4267
|
}
|
|
@@ -2823,80 +4269,187 @@ function sprigLists() {
|
|
|
2823
4269
|
//#region src/sprig/math/add.ts
|
|
2824
4270
|
/** `add a b c …` — variadic integer sum. */
|
|
2825
4271
|
function add(...args) {
|
|
2826
|
-
return args.reduce((acc, v) => acc +
|
|
4272
|
+
return args.reduce((acc, v) => acc + v, 0);
|
|
4273
|
+
}
|
|
4274
|
+
//#endregion
|
|
4275
|
+
//#region src/sprig/math/add1.ts
|
|
4276
|
+
/** `add1 n` — integer increment. Mirrors Go sprig's `add1(i interface{}) int64`. */
|
|
4277
|
+
function add1(n) {
|
|
4278
|
+
return n + 1;
|
|
4279
|
+
}
|
|
4280
|
+
//#endregion
|
|
4281
|
+
//#region src/sprig/math/add1f.ts
|
|
4282
|
+
/** `add1f n` — float increment. Mirrors Go sprig's `add1f(i interface{}) float64`. */
|
|
4283
|
+
function add1f(n) {
|
|
4284
|
+
return n + 1;
|
|
2827
4285
|
}
|
|
2828
4286
|
//#endregion
|
|
2829
4287
|
//#region src/sprig/math/addf.ts
|
|
2830
4288
|
function addf(...args) {
|
|
2831
|
-
return args.reduce((acc, v) => acc +
|
|
4289
|
+
return args.reduce((acc, v) => acc + v, 0);
|
|
2832
4290
|
}
|
|
2833
4291
|
//#endregion
|
|
2834
4292
|
//#region src/sprig/math/ceil.ts
|
|
2835
4293
|
function ceil(a) {
|
|
2836
|
-
return Math.ceil(
|
|
4294
|
+
return Math.ceil(a);
|
|
2837
4295
|
}
|
|
2838
4296
|
//#endregion
|
|
2839
4297
|
//#region src/sprig/math/div.ts
|
|
2840
4298
|
/** `div a b` — integer division (Go semantics: truncate toward zero). */
|
|
2841
4299
|
function div(a, b) {
|
|
2842
|
-
return Math.trunc(
|
|
4300
|
+
return Math.trunc(a / b);
|
|
2843
4301
|
}
|
|
2844
4302
|
//#endregion
|
|
2845
4303
|
//#region src/sprig/math/divf.ts
|
|
2846
4304
|
function divf(a, b) {
|
|
2847
|
-
return
|
|
4305
|
+
return a / b;
|
|
2848
4306
|
}
|
|
2849
4307
|
//#endregion
|
|
2850
4308
|
//#region src/sprig/math/floor.ts
|
|
2851
4309
|
function floor(a) {
|
|
2852
|
-
return Math.floor(
|
|
4310
|
+
return Math.floor(a);
|
|
2853
4311
|
}
|
|
2854
4312
|
//#endregion
|
|
2855
4313
|
//#region src/sprig/math/max.ts
|
|
2856
|
-
/** `max a b c …` — variadic maximum. */
|
|
4314
|
+
/** `max a b c …` — variadic maximum (Go int64 semantics; args arrive truncated). */
|
|
2857
4315
|
function max(...args) {
|
|
2858
|
-
return args.
|
|
4316
|
+
return args.reduce((m, v) => v > m ? v : m, Number.NEGATIVE_INFINITY);
|
|
4317
|
+
}
|
|
4318
|
+
//#endregion
|
|
4319
|
+
//#region src/sprig/math/maxf.ts
|
|
4320
|
+
/**
|
|
4321
|
+
* `maxf a b c …` — variadic float-typed maximum. Mirrors Go sprig's
|
|
4322
|
+
* `maxf` (float64, no truncation). Distinct from `max` (int64-truncated).
|
|
4323
|
+
*/
|
|
4324
|
+
function maxf(...args) {
|
|
4325
|
+
return args.reduce((m, v) => Math.max(m, v), -Infinity);
|
|
2859
4326
|
}
|
|
2860
4327
|
//#endregion
|
|
2861
4328
|
//#region src/sprig/math/min.ts
|
|
2862
|
-
/** `min a b c …` — variadic minimum. */
|
|
4329
|
+
/** `min a b c …` — variadic minimum (Go int64 semantics; args arrive truncated). */
|
|
2863
4330
|
function min(...args) {
|
|
2864
|
-
return args.
|
|
4331
|
+
return args.reduce((m, v) => v < m ? v : m, Number.POSITIVE_INFINITY);
|
|
4332
|
+
}
|
|
4333
|
+
//#endregion
|
|
4334
|
+
//#region src/sprig/math/minf.ts
|
|
4335
|
+
/** `minf a b c …` — variadic float-typed minimum. Float counterpart of `min` (int64-truncated). */
|
|
4336
|
+
function minf(...args) {
|
|
4337
|
+
return args.reduce((m, v) => Math.min(m, v), Infinity);
|
|
2865
4338
|
}
|
|
2866
4339
|
//#endregion
|
|
2867
4340
|
//#region src/sprig/math/mod.ts
|
|
2868
4341
|
/** `mod a b` — modulo. JS `%` matches Go's: sign follows the dividend. */
|
|
2869
4342
|
function mod(a, b) {
|
|
2870
|
-
return
|
|
4343
|
+
return a % b;
|
|
2871
4344
|
}
|
|
2872
4345
|
//#endregion
|
|
2873
4346
|
//#region src/sprig/math/mul.ts
|
|
2874
4347
|
/** `mul a b c …` — variadic integer product. */
|
|
2875
4348
|
function mul(...args) {
|
|
2876
|
-
return args.reduce((acc, v) => acc *
|
|
4349
|
+
return args.reduce((acc, v) => acc * v, 1);
|
|
2877
4350
|
}
|
|
2878
4351
|
//#endregion
|
|
2879
4352
|
//#region src/sprig/math/mulf.ts
|
|
2880
4353
|
function mulf(...args) {
|
|
2881
|
-
return args.reduce((acc, v) => acc *
|
|
4354
|
+
return args.reduce((acc, v) => acc * v, 1);
|
|
2882
4355
|
}
|
|
2883
4356
|
//#endregion
|
|
2884
4357
|
//#region src/sprig/math/round.ts
|
|
2885
4358
|
/** `round a [precision=0]` — round half-away-from-zero, matching Go sprig. */
|
|
2886
4359
|
function round(a, precision = 0) {
|
|
2887
|
-
const
|
|
2888
|
-
|
|
2889
|
-
|
|
4360
|
+
const factor = 10 ** precision;
|
|
4361
|
+
return Math.sign(a) * Math.round(Math.abs(a) * factor) / factor;
|
|
4362
|
+
}
|
|
4363
|
+
//#endregion
|
|
4364
|
+
//#region src/sprig/math/untilStep.ts
|
|
4365
|
+
/**
|
|
4366
|
+
* `untilStep start stop step` — Python-`range`-shaped integer slice.
|
|
4367
|
+
* Mirrors Go sprig's `untilStep(start, stop, step int) []int`. Step
|
|
4368
|
+
* direction must agree with the start→stop direction; mismatched signs
|
|
4369
|
+
* (e.g. `start < stop` with `step <= 0`) yield an empty slice rather
|
|
4370
|
+
* than looping forever.
|
|
4371
|
+
*/
|
|
4372
|
+
function untilStep(start, stop, step) {
|
|
4373
|
+
const v = [];
|
|
4374
|
+
if (stop < start) {
|
|
4375
|
+
if (step >= 0) return v;
|
|
4376
|
+
for (let i = start; i > stop; i += step) v.push(i);
|
|
4377
|
+
return v;
|
|
4378
|
+
}
|
|
4379
|
+
if (step <= 0) return v;
|
|
4380
|
+
for (let i = start; i < stop; i += step) v.push(i);
|
|
4381
|
+
return v;
|
|
4382
|
+
}
|
|
4383
|
+
//#endregion
|
|
4384
|
+
//#region src/sprig/math/seq.ts
|
|
4385
|
+
/**
|
|
4386
|
+
* `seq …` — space-joined integer sequence. Mirrors Go sprig's `seq`,
|
|
4387
|
+
* which dispatches on arity and is **inclusive** of the end value:
|
|
4388
|
+
*
|
|
4389
|
+
* seq() → ""
|
|
4390
|
+
* seq(end) → 1..end (descending if end<1)
|
|
4391
|
+
* seq(start, end) → start..end (step ±1 by direction)
|
|
4392
|
+
* seq(start, step, end) → stepped, end inclusive when reached
|
|
4393
|
+
* 4+ args → ""
|
|
4394
|
+
*
|
|
4395
|
+
* Inclusivity is implemented the same way Go does it — by passing
|
|
4396
|
+
* `end + increment` (or `end + step` for the 2-arg case) into the
|
|
4397
|
+
* exclusive `untilStep`. The 3-arg form returns "" when the bounds
|
|
4398
|
+
* descend (`end < start`) but the caller passes a positive step —
|
|
4399
|
+
* matching Go's early-return at `if step > 0 { return "" }`.
|
|
4400
|
+
*
|
|
4401
|
+
* Output is the int slice joined with " ", so `{{ seq 5 }}` emits
|
|
4402
|
+
* `1 2 3 4 5`. Result type is `string`, **not** `number[]`.
|
|
4403
|
+
*/
|
|
4404
|
+
function seq(...params) {
|
|
4405
|
+
let increment = 1;
|
|
4406
|
+
switch (params.length) {
|
|
4407
|
+
case 0: return "";
|
|
4408
|
+
case 1: {
|
|
4409
|
+
const start = 1;
|
|
4410
|
+
const end = params[0];
|
|
4411
|
+
if (end < start) increment = -1;
|
|
4412
|
+
return untilStep(start, end + increment, increment).join(" ");
|
|
4413
|
+
}
|
|
4414
|
+
case 2: {
|
|
4415
|
+
const start = params[0];
|
|
4416
|
+
const end = params[1];
|
|
4417
|
+
const step = end < start ? -1 : 1;
|
|
4418
|
+
return untilStep(start, end + step, step).join(" ");
|
|
4419
|
+
}
|
|
4420
|
+
case 3: {
|
|
4421
|
+
const start = params[0];
|
|
4422
|
+
const step = params[1];
|
|
4423
|
+
const end = params[2];
|
|
4424
|
+
if (end < start) {
|
|
4425
|
+
increment = -1;
|
|
4426
|
+
if (step > 0) return "";
|
|
4427
|
+
}
|
|
4428
|
+
return untilStep(start, end + increment, step).join(" ");
|
|
4429
|
+
}
|
|
4430
|
+
default: return "";
|
|
4431
|
+
}
|
|
2890
4432
|
}
|
|
2891
4433
|
//#endregion
|
|
2892
4434
|
//#region src/sprig/math/sub.ts
|
|
2893
4435
|
function sub(a, b) {
|
|
2894
|
-
return
|
|
4436
|
+
return a - b;
|
|
2895
4437
|
}
|
|
2896
4438
|
//#endregion
|
|
2897
4439
|
//#region src/sprig/math/subf.ts
|
|
2898
4440
|
function subf(a, b) {
|
|
2899
|
-
return
|
|
4441
|
+
return a - b;
|
|
4442
|
+
}
|
|
4443
|
+
//#endregion
|
|
4444
|
+
//#region src/sprig/math/until.ts
|
|
4445
|
+
/**
|
|
4446
|
+
* `until count` — `[0, 1, …, count-1]` for positive counts, or
|
|
4447
|
+
* `[0, -1, …, count+1]` for negative counts. Mirrors Go sprig's
|
|
4448
|
+
* `until`, which derives step direction from the sign of `count`
|
|
4449
|
+
* and delegates to `untilStep`.
|
|
4450
|
+
*/
|
|
4451
|
+
function until(count) {
|
|
4452
|
+
return untilStep(0, count, count < 0 ? -1 : 1);
|
|
2900
4453
|
}
|
|
2901
4454
|
//#endregion
|
|
2902
4455
|
//#region src/sprig/math/index.ts
|
|
@@ -2904,59 +4457,220 @@ function sprigMath() {
|
|
|
2904
4457
|
return {
|
|
2905
4458
|
add: {
|
|
2906
4459
|
fn: (...a) => add(...a),
|
|
2907
|
-
argTypes: ["
|
|
4460
|
+
argTypes: ["int"]
|
|
2908
4461
|
},
|
|
2909
4462
|
sub: {
|
|
2910
4463
|
fn: (a, b) => sub(a, b),
|
|
2911
|
-
argTypes: ["
|
|
4464
|
+
argTypes: ["int", "int"]
|
|
2912
4465
|
},
|
|
2913
4466
|
mul: {
|
|
2914
4467
|
fn: (...a) => mul(...a),
|
|
2915
|
-
argTypes: ["
|
|
4468
|
+
argTypes: ["int"]
|
|
2916
4469
|
},
|
|
2917
4470
|
div: {
|
|
2918
4471
|
fn: (a, b) => div(a, b),
|
|
2919
|
-
argTypes: ["
|
|
4472
|
+
argTypes: ["int", "int"]
|
|
2920
4473
|
},
|
|
2921
4474
|
mod: {
|
|
2922
4475
|
fn: (a, b) => mod(a, b),
|
|
2923
|
-
argTypes: ["
|
|
4476
|
+
argTypes: ["int", "int"]
|
|
2924
4477
|
},
|
|
2925
4478
|
min: {
|
|
2926
4479
|
fn: (...a) => min(...a),
|
|
2927
|
-
argTypes: ["
|
|
4480
|
+
argTypes: ["int"]
|
|
2928
4481
|
},
|
|
2929
4482
|
max: {
|
|
2930
4483
|
fn: (...a) => max(...a),
|
|
2931
|
-
argTypes: ["
|
|
4484
|
+
argTypes: ["int"]
|
|
2932
4485
|
},
|
|
2933
4486
|
floor: {
|
|
2934
4487
|
fn: (a) => floor(a),
|
|
2935
|
-
argTypes: ["
|
|
4488
|
+
argTypes: ["float"]
|
|
2936
4489
|
},
|
|
2937
4490
|
ceil: {
|
|
2938
4491
|
fn: (a) => ceil(a),
|
|
2939
|
-
argTypes: ["
|
|
4492
|
+
argTypes: ["float"]
|
|
2940
4493
|
},
|
|
2941
4494
|
round: {
|
|
2942
4495
|
fn: (a, p) => round(a, p),
|
|
2943
|
-
argTypes: ["
|
|
4496
|
+
argTypes: ["float", "int"]
|
|
2944
4497
|
},
|
|
2945
4498
|
addf: {
|
|
2946
4499
|
fn: (...a) => addf(...a),
|
|
2947
|
-
argTypes: ["
|
|
4500
|
+
argTypes: ["float"]
|
|
2948
4501
|
},
|
|
2949
4502
|
subf: {
|
|
2950
4503
|
fn: (a, b) => subf(a, b),
|
|
2951
|
-
argTypes: ["
|
|
4504
|
+
argTypes: ["float", "float"]
|
|
2952
4505
|
},
|
|
2953
4506
|
mulf: {
|
|
2954
4507
|
fn: (...a) => mulf(...a),
|
|
2955
|
-
argTypes: ["
|
|
4508
|
+
argTypes: ["float"]
|
|
2956
4509
|
},
|
|
2957
4510
|
divf: {
|
|
2958
4511
|
fn: (a, b) => divf(a, b),
|
|
2959
|
-
argTypes: ["
|
|
4512
|
+
argTypes: ["float", "float"]
|
|
4513
|
+
},
|
|
4514
|
+
add1: {
|
|
4515
|
+
fn: (n) => add1(n),
|
|
4516
|
+
argTypes: ["int"]
|
|
4517
|
+
},
|
|
4518
|
+
add1f: {
|
|
4519
|
+
fn: (n) => add1f(n),
|
|
4520
|
+
argTypes: ["float"]
|
|
4521
|
+
},
|
|
4522
|
+
maxf: {
|
|
4523
|
+
fn: (...a) => maxf(...a),
|
|
4524
|
+
argTypes: ["float"]
|
|
4525
|
+
},
|
|
4526
|
+
minf: {
|
|
4527
|
+
fn: (...a) => minf(...a),
|
|
4528
|
+
argTypes: ["float"]
|
|
4529
|
+
},
|
|
4530
|
+
biggest: {
|
|
4531
|
+
fn: (...a) => max(...a),
|
|
4532
|
+
argTypes: ["int"]
|
|
4533
|
+
},
|
|
4534
|
+
seq: {
|
|
4535
|
+
fn: (...a) => seq(...a),
|
|
4536
|
+
argTypes: ["int"],
|
|
4537
|
+
returnType: "string"
|
|
4538
|
+
},
|
|
4539
|
+
until: {
|
|
4540
|
+
fn: (n) => until(n),
|
|
4541
|
+
argTypes: ["int"],
|
|
4542
|
+
returnType: "list"
|
|
4543
|
+
},
|
|
4544
|
+
untilStep: {
|
|
4545
|
+
fn: (a, b, c) => untilStep(a, b, c),
|
|
4546
|
+
argTypes: [
|
|
4547
|
+
"int",
|
|
4548
|
+
"int",
|
|
4549
|
+
"int"
|
|
4550
|
+
],
|
|
4551
|
+
returnType: "list"
|
|
4552
|
+
}
|
|
4553
|
+
};
|
|
4554
|
+
}
|
|
4555
|
+
//#endregion
|
|
4556
|
+
//#region src/sprig/random/_prng.ts
|
|
4557
|
+
/**
|
|
4558
|
+
* Internal PRNG seam for sprig random functions.
|
|
4559
|
+
*
|
|
4560
|
+
* [LAW:single-enforcer] All randomness in this module routes through
|
|
4561
|
+
* the `random` parameter — never through `Math.random` directly. The
|
|
4562
|
+
* caller supplies the source; these helpers consume it.
|
|
4563
|
+
*/
|
|
4564
|
+
var RandIntRangeError = class extends Error {
|
|
4565
|
+
constructor(min, max) {
|
|
4566
|
+
super(`randIntFromRange: max must be greater than min (max=${max}, min=${min})`);
|
|
4567
|
+
this.name = "RandIntRangeError";
|
|
4568
|
+
}
|
|
4569
|
+
};
|
|
4570
|
+
/** Clamp PRNG output to [0, 1) to defend against out-of-range injected sources. */
|
|
4571
|
+
function clampRandom(value) {
|
|
4572
|
+
if (!Number.isFinite(value)) return 0;
|
|
4573
|
+
return Math.max(0, Math.min(value, .9999999999999999));
|
|
4574
|
+
}
|
|
4575
|
+
const ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
4576
|
+
const ALPHANUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
4577
|
+
const NUMERIC = "0123456789";
|
|
4578
|
+
const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)).join("");
|
|
4579
|
+
function randString(n, charset, random) {
|
|
4580
|
+
const chars = [];
|
|
4581
|
+
for (let i = 0; i < n; i++) chars.push(charset.charAt(Math.floor(clampRandom(random()) * charset.length)));
|
|
4582
|
+
return chars.join("");
|
|
4583
|
+
}
|
|
4584
|
+
/** Inclusive `min`, exclusive `max` — mirrors Go `rand.Intn(max-min)+min`. */
|
|
4585
|
+
function randIntFromRange(min, max, random) {
|
|
4586
|
+
if (max <= min) throw new RandIntRangeError(min, max);
|
|
4587
|
+
return Math.floor(clampRandom(random()) * (max - min)) + min;
|
|
4588
|
+
}
|
|
4589
|
+
//#endregion
|
|
4590
|
+
//#region src/sprig/random/randAlpha.ts
|
|
4591
|
+
/** `randAlpha n` — `n` random letters [A-Za-z]. */
|
|
4592
|
+
function randAlpha(n, random) {
|
|
4593
|
+
return randString(n, ALPHA, random);
|
|
4594
|
+
}
|
|
4595
|
+
//#endregion
|
|
4596
|
+
//#region src/sprig/random/randAlphaNum.ts
|
|
4597
|
+
/** `randAlphaNum n` — `n` random alphanumeric characters [A-Za-z0-9]. */
|
|
4598
|
+
function randAlphaNum(n, random) {
|
|
4599
|
+
return randString(n, ALPHANUM, random);
|
|
4600
|
+
}
|
|
4601
|
+
//#endregion
|
|
4602
|
+
//#region src/sprig/random/randAscii.ts
|
|
4603
|
+
/** `randAscii n` — `n` random printable ASCII characters (0x20–0x7E). */
|
|
4604
|
+
function randAscii(n, random) {
|
|
4605
|
+
return randString(n, ASCII, random);
|
|
4606
|
+
}
|
|
4607
|
+
//#endregion
|
|
4608
|
+
//#region src/sprig/random/randInt.ts
|
|
4609
|
+
/** `randInt min max` — random integer in [min, max). Mirrors Go sprig. */
|
|
4610
|
+
function randInt(min, max, random) {
|
|
4611
|
+
try {
|
|
4612
|
+
return randIntFromRange(min, max, random);
|
|
4613
|
+
} catch (e) {
|
|
4614
|
+
if (e instanceof RandIntRangeError) throw bodyTypeMismatch("randInt", 2, "max > min", `constraint violated (max=${max}, min=${min})`);
|
|
4615
|
+
throw e;
|
|
4616
|
+
}
|
|
4617
|
+
}
|
|
4618
|
+
//#endregion
|
|
4619
|
+
//#region src/sprig/random/randNumeric.ts
|
|
4620
|
+
/** `randNumeric n` — `n` random decimal digits [0-9]. */
|
|
4621
|
+
function randNumeric(n, random) {
|
|
4622
|
+
return randString(n, NUMERIC, random);
|
|
4623
|
+
}
|
|
4624
|
+
//#endregion
|
|
4625
|
+
//#region src/sprig/random/shuffle.ts
|
|
4626
|
+
/**
|
|
4627
|
+
* `shuffle s` — returns a randomly permuted copy of `s`.
|
|
4628
|
+
*
|
|
4629
|
+
* Operates on Unicode code points (matching Go sprig's rune-level Fisher-Yates).
|
|
4630
|
+
*/
|
|
4631
|
+
function shuffle(s, random) {
|
|
4632
|
+
const runes = [...s];
|
|
4633
|
+
for (let i = runes.length - 1; i > 0; i--) {
|
|
4634
|
+
const j = Math.floor(clampRandom(random()) * (i + 1));
|
|
4635
|
+
const tmp = runes[i];
|
|
4636
|
+
runes[i] = runes[j];
|
|
4637
|
+
runes[j] = tmp;
|
|
4638
|
+
}
|
|
4639
|
+
return runes.join("");
|
|
4640
|
+
}
|
|
4641
|
+
//#endregion
|
|
4642
|
+
//#region src/sprig/random/index.ts
|
|
4643
|
+
/**
|
|
4644
|
+
* Build the sprig random FuncMap.
|
|
4645
|
+
*
|
|
4646
|
+
* @param random - PRNG source. Defaults to `Math.random`. Pass a seeded
|
|
4647
|
+
* generator for reproducible templates (matches `EngineConfig.random`).
|
|
4648
|
+
*/
|
|
4649
|
+
function sprigRandom(random = Math.random) {
|
|
4650
|
+
return {
|
|
4651
|
+
randInt: {
|
|
4652
|
+
fn: (min, max) => randInt(min, max, random),
|
|
4653
|
+
argTypes: ["int", "int"]
|
|
4654
|
+
},
|
|
4655
|
+
randAlpha: {
|
|
4656
|
+
fn: (n) => randAlpha(n, random),
|
|
4657
|
+
argTypes: ["int"]
|
|
4658
|
+
},
|
|
4659
|
+
randAlphaNum: {
|
|
4660
|
+
fn: (n) => randAlphaNum(n, random),
|
|
4661
|
+
argTypes: ["int"]
|
|
4662
|
+
},
|
|
4663
|
+
randNumeric: {
|
|
4664
|
+
fn: (n) => randNumeric(n, random),
|
|
4665
|
+
argTypes: ["int"]
|
|
4666
|
+
},
|
|
4667
|
+
randAscii: {
|
|
4668
|
+
fn: (n) => randAscii(n, random),
|
|
4669
|
+
argTypes: ["int"]
|
|
4670
|
+
},
|
|
4671
|
+
shuffle: {
|
|
4672
|
+
fn: (s) => shuffle(s, random),
|
|
4673
|
+
argTypes: ["string"]
|
|
2960
4674
|
}
|
|
2961
4675
|
};
|
|
2962
4676
|
}
|
|
@@ -2975,11 +4689,10 @@ function regexFind(pattern, s) {
|
|
|
2975
4689
|
*/
|
|
2976
4690
|
function regexFindAll(pattern, s, n = -1) {
|
|
2977
4691
|
const re = new RegExp(pattern, "g");
|
|
2978
|
-
const limit = Number(n);
|
|
2979
4692
|
const out = [];
|
|
2980
4693
|
for (const m of s.matchAll(re)) {
|
|
4694
|
+
if (n >= 0 && out.length >= n) break;
|
|
2981
4695
|
out.push(m[0]);
|
|
2982
|
-
if (limit >= 0 && out.length >= limit) break;
|
|
2983
4696
|
}
|
|
2984
4697
|
return out;
|
|
2985
4698
|
}
|
|
@@ -3014,9 +4727,8 @@ function regexReplaceAllLiteral(pattern, s, repl) {
|
|
|
3014
4727
|
/** `regexSplit pattern s n` — split by regex, optional max count. */
|
|
3015
4728
|
function regexSplit(pattern, s, n = -1) {
|
|
3016
4729
|
const re = new RegExp(pattern);
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
return s.split(re).slice(0, limit);
|
|
4730
|
+
if (n < 0) return s.split(re);
|
|
4731
|
+
return s.split(re).slice(0, n);
|
|
3020
4732
|
}
|
|
3021
4733
|
//#endregion
|
|
3022
4734
|
//#region src/sprig/regex/index.ts
|
|
@@ -3035,7 +4747,7 @@ function sprigRegex() {
|
|
|
3035
4747
|
argTypes: [
|
|
3036
4748
|
"string",
|
|
3037
4749
|
"string",
|
|
3038
|
-
"
|
|
4750
|
+
"int"
|
|
3039
4751
|
]
|
|
3040
4752
|
},
|
|
3041
4753
|
regexReplaceAll: {
|
|
@@ -3059,12 +4771,205 @@ function sprigRegex() {
|
|
|
3059
4771
|
argTypes: [
|
|
3060
4772
|
"string",
|
|
3061
4773
|
"string",
|
|
3062
|
-
"
|
|
4774
|
+
"int"
|
|
3063
4775
|
]
|
|
3064
4776
|
}
|
|
3065
4777
|
};
|
|
3066
4778
|
}
|
|
3067
4779
|
//#endregion
|
|
4780
|
+
//#region src/sprig/semver/parse.ts
|
|
4781
|
+
/**
|
|
4782
|
+
* SemVer parsing and comparison utilities.
|
|
4783
|
+
*
|
|
4784
|
+
* Mirrors Masterminds/semver v3 semantics used by Go sprig:
|
|
4785
|
+
* - Optional v prefix; missing minor/patch default to 0
|
|
4786
|
+
* - Standard semver 2.0.0 ordering: major.minor.patch then pre-release
|
|
4787
|
+
* - Release (no pre-release) > pre-release of same version
|
|
4788
|
+
*
|
|
4789
|
+
* [LAW:one-source-of-truth] One parser, one comparator. Constraint
|
|
4790
|
+
* evaluation imports from here rather than re-implementing comparison.
|
|
4791
|
+
*/
|
|
4792
|
+
const VERSION_RE = /^v?(\d+)(?:\.(\d+)(?:\.(\d+))?)?(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
|
|
4793
|
+
function parseSemVer(s) {
|
|
4794
|
+
const input = s.trim();
|
|
4795
|
+
const m = VERSION_RE.exec(input);
|
|
4796
|
+
if (!m) throw new Error(`invalid semver: ${JSON.stringify(s)}`);
|
|
4797
|
+
return {
|
|
4798
|
+
Major: parseInt(m[1] ?? "0", 10),
|
|
4799
|
+
Minor: m[2] !== void 0 ? parseInt(m[2], 10) : 0,
|
|
4800
|
+
Patch: m[3] !== void 0 ? parseInt(m[3], 10) : 0,
|
|
4801
|
+
Prerelease: m[4] ?? "",
|
|
4802
|
+
Metadata: m[5] ?? "",
|
|
4803
|
+
Original: input
|
|
4804
|
+
};
|
|
4805
|
+
}
|
|
4806
|
+
/** Returns negative if a < b, 0 if equal, positive if a > b. */
|
|
4807
|
+
function compareSemVer(a, b) {
|
|
4808
|
+
const d = a.Major - b.Major || a.Minor - b.Minor || a.Patch - b.Patch;
|
|
4809
|
+
if (d !== 0) return d;
|
|
4810
|
+
return comparePrerelease(a.Prerelease, b.Prerelease);
|
|
4811
|
+
}
|
|
4812
|
+
function comparePrerelease(a, b) {
|
|
4813
|
+
if (a === b) return 0;
|
|
4814
|
+
if (a === "") return 1;
|
|
4815
|
+
if (b === "") return -1;
|
|
4816
|
+
const aParts = a.split(".");
|
|
4817
|
+
const bParts = b.split(".");
|
|
4818
|
+
for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
|
|
4819
|
+
const ap = aParts[i];
|
|
4820
|
+
const bp = bParts[i];
|
|
4821
|
+
if (ap === void 0) return -1;
|
|
4822
|
+
if (bp === void 0) return 1;
|
|
4823
|
+
const an = /^\d+$/.test(ap) ? parseInt(ap, 10) : null;
|
|
4824
|
+
const bn = /^\d+$/.test(bp) ? parseInt(bp, 10) : null;
|
|
4825
|
+
if (an !== null && bn !== null) {
|
|
4826
|
+
if (an !== bn) return an - bn;
|
|
4827
|
+
} else if (an !== null) return -1;
|
|
4828
|
+
else if (bn !== null) return 1;
|
|
4829
|
+
else {
|
|
4830
|
+
if (ap < bp) return -1;
|
|
4831
|
+
if (ap > bp) return 1;
|
|
4832
|
+
}
|
|
4833
|
+
}
|
|
4834
|
+
return 0;
|
|
4835
|
+
}
|
|
4836
|
+
//#endregion
|
|
4837
|
+
//#region src/sprig/semver/semver.ts
|
|
4838
|
+
/**
|
|
4839
|
+
* `semver s` — parse a semver string into a struct with Major, Minor,
|
|
4840
|
+
* Patch, Prerelease, Metadata, Original fields.
|
|
4841
|
+
*
|
|
4842
|
+
* Mirrors Go sprig's `semver` which wraps Masterminds/semver v3's
|
|
4843
|
+
* `NewVersion`. Template field access (`.Major`, `.Prerelease`, etc.)
|
|
4844
|
+
* maps to the same-named keys on the returned object.
|
|
4845
|
+
*
|
|
4846
|
+
* Throws on invalid input — matches Go's behaviour where `semver` returns
|
|
4847
|
+
* (Version, error) and sprig panics on error.
|
|
4848
|
+
*/
|
|
4849
|
+
function semver(s) {
|
|
4850
|
+
return parseSemVer(s);
|
|
4851
|
+
}
|
|
4852
|
+
//#endregion
|
|
4853
|
+
//#region src/sprig/semver/constraint.ts
|
|
4854
|
+
/**
|
|
4855
|
+
* Masterminds/semver v3-compatible constraint parsing and evaluation.
|
|
4856
|
+
*
|
|
4857
|
+
* Supports operators: =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), "" (=).
|
|
4858
|
+
* AND groups: comma- or whitespace-separated.
|
|
4859
|
+
* OR groups: || separated.
|
|
4860
|
+
*
|
|
4861
|
+
* [LAW:types-are-the-program] A constraint IS a predicate function —
|
|
4862
|
+
* parsing produces (v: SemVer) => boolean directly. No intermediate
|
|
4863
|
+
* structural representation is needed at the call site.
|
|
4864
|
+
*/
|
|
4865
|
+
const TOKEN_RE = /(!=|>=|<=|>|<|~|\^|=)?\s*(v?\d[^\s,]*)/g;
|
|
4866
|
+
function parseConstraintExpr(s) {
|
|
4867
|
+
const orGroups = s.split(/\|\|/).map((p) => p.trim()).filter(Boolean);
|
|
4868
|
+
if (orGroups.length === 0) throw new Error(`empty constraint: ${JSON.stringify(s)}`);
|
|
4869
|
+
const preds = orGroups.map(parseAndGroup);
|
|
4870
|
+
return (v) => preds.some((p) => p(v));
|
|
4871
|
+
}
|
|
4872
|
+
function parseAndGroup(s) {
|
|
4873
|
+
const preds = [];
|
|
4874
|
+
let consumed = 0;
|
|
4875
|
+
for (const m of s.matchAll(TOKEN_RE)) {
|
|
4876
|
+
const gap = s.slice(consumed, m.index);
|
|
4877
|
+
if (gap.length > 0 && !/^[,\s]*$/.test(gap)) throw new Error(`unexpected characters in constraint: ${JSON.stringify(gap)}`);
|
|
4878
|
+
preds.push(buildSingle(m[1] ?? "", m[2] ?? ""));
|
|
4879
|
+
consumed = (m.index ?? 0) + m[0].length;
|
|
4880
|
+
}
|
|
4881
|
+
if (preds.length === 0) throw new Error(`no constraint tokens in: ${JSON.stringify(s)}`);
|
|
4882
|
+
const remaining = s.slice(consumed).trim();
|
|
4883
|
+
if (remaining.length > 0) throw new Error(`unexpected characters in constraint: ${JSON.stringify(remaining)}`);
|
|
4884
|
+
return (v) => preds.every((p) => p(v));
|
|
4885
|
+
}
|
|
4886
|
+
function countComponents(vstr) {
|
|
4887
|
+
const core = vstr.replace(/^v/, "").replace(/[-+].*$/, "");
|
|
4888
|
+
return Math.min(core.split(".").length, 3);
|
|
4889
|
+
}
|
|
4890
|
+
function makeSemVer(major, minor, patch, pre) {
|
|
4891
|
+
return {
|
|
4892
|
+
Major: major,
|
|
4893
|
+
Minor: minor,
|
|
4894
|
+
Patch: patch,
|
|
4895
|
+
Prerelease: pre,
|
|
4896
|
+
Metadata: "",
|
|
4897
|
+
Original: pre ? `${major}.${minor}.${patch}-${pre}` : `${major}.${minor}.${patch}`
|
|
4898
|
+
};
|
|
4899
|
+
}
|
|
4900
|
+
function preReleaseCheck(v, constraint) {
|
|
4901
|
+
if (v.Prerelease === "") return true;
|
|
4902
|
+
if (constraint.Prerelease !== "") return v.Major === constraint.Major && v.Minor === constraint.Minor && v.Patch === constraint.Patch;
|
|
4903
|
+
return false;
|
|
4904
|
+
}
|
|
4905
|
+
function buildSingle(op, vstr) {
|
|
4906
|
+
const cv = parseSemVer(vstr);
|
|
4907
|
+
const components = countComponents(vstr);
|
|
4908
|
+
const minorDirty = components < 2;
|
|
4909
|
+
const patchDirty = components < 3;
|
|
4910
|
+
switch (op) {
|
|
4911
|
+
case "":
|
|
4912
|
+
case "=": return (v) => compareSemVer(v, cv) === 0;
|
|
4913
|
+
case "!=": return (v) => compareSemVer(v, cv) !== 0;
|
|
4914
|
+
case ">": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) > 0;
|
|
4915
|
+
case ">=": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0;
|
|
4916
|
+
case "<": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) < 0;
|
|
4917
|
+
case "<=": return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) <= 0;
|
|
4918
|
+
case "~": return buildTilde(cv, minorDirty);
|
|
4919
|
+
case "^": return buildCaret(cv, minorDirty, patchDirty);
|
|
4920
|
+
default: throw new Error(`unknown constraint operator: ${JSON.stringify(op)}`);
|
|
4921
|
+
}
|
|
4922
|
+
}
|
|
4923
|
+
function buildTilde(cv, minorDirty) {
|
|
4924
|
+
if (minorDirty) {
|
|
4925
|
+
const lower = makeSemVer(cv.Major, 0, 0, cv.Prerelease);
|
|
4926
|
+
const upper = makeSemVer(cv.Major + 1, 0, 0, "");
|
|
4927
|
+
return (v) => preReleaseCheck(v, lower) && compareSemVer(v, lower) >= 0 && compareSemVer(v, upper) < 0;
|
|
4928
|
+
}
|
|
4929
|
+
const upper = makeSemVer(cv.Major, cv.Minor + 1, 0, "");
|
|
4930
|
+
return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;
|
|
4931
|
+
}
|
|
4932
|
+
function buildCaret(cv, minorDirty, patchDirty) {
|
|
4933
|
+
let upper;
|
|
4934
|
+
if (minorDirty) upper = makeSemVer(cv.Major + 1, 0, 0, "");
|
|
4935
|
+
else if (cv.Major > 0) upper = makeSemVer(cv.Major + 1, 0, 0, "");
|
|
4936
|
+
else if (cv.Minor > 0) upper = makeSemVer(0, cv.Minor + 1, 0, "");
|
|
4937
|
+
else if (patchDirty) upper = makeSemVer(0, 1, 0, "");
|
|
4938
|
+
else upper = makeSemVer(0, 0, cv.Patch + 1, "");
|
|
4939
|
+
return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;
|
|
4940
|
+
}
|
|
4941
|
+
//#endregion
|
|
4942
|
+
//#region src/sprig/semver/semverCompare.ts
|
|
4943
|
+
/**
|
|
4944
|
+
* `semverCompare constraint version` — returns true iff `version`
|
|
4945
|
+
* satisfies `constraint`.
|
|
4946
|
+
*
|
|
4947
|
+
* Constraint syntax follows Masterminds/semver v3 (Go sprig's semver
|
|
4948
|
+
* library): =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), || for OR,
|
|
4949
|
+
* comma/space for AND.
|
|
4950
|
+
*
|
|
4951
|
+
* Note: Go sprig's argument order is (constraint, version) — the
|
|
4952
|
+
* constraint comes first.
|
|
4953
|
+
*/
|
|
4954
|
+
function semverCompare(constraint, version) {
|
|
4955
|
+
return parseConstraintExpr(constraint)(parseSemVer(version));
|
|
4956
|
+
}
|
|
4957
|
+
//#endregion
|
|
4958
|
+
//#region src/sprig/semver/index.ts
|
|
4959
|
+
function sprigSemver() {
|
|
4960
|
+
return {
|
|
4961
|
+
semver: {
|
|
4962
|
+
fn: (s) => semver(s),
|
|
4963
|
+
argTypes: ["string"]
|
|
4964
|
+
},
|
|
4965
|
+
semverCompare: {
|
|
4966
|
+
fn: (constraint, version) => semverCompare(constraint, version),
|
|
4967
|
+
argTypes: ["string", "string"],
|
|
4968
|
+
returnType: "bool"
|
|
4969
|
+
}
|
|
4970
|
+
};
|
|
4971
|
+
}
|
|
4972
|
+
//#endregion
|
|
3068
4973
|
//#region src/sprig/strings/abbrev.ts
|
|
3069
4974
|
/**
|
|
3070
4975
|
* `abbrev width s` — truncate `s` to `width` chars, replacing the tail
|
|
@@ -3073,10 +4978,9 @@ function sprigRegex() {
|
|
|
3073
4978
|
* behavior).
|
|
3074
4979
|
*/
|
|
3075
4980
|
function abbrev(width, s) {
|
|
3076
|
-
|
|
3077
|
-
if (
|
|
3078
|
-
|
|
3079
|
-
return `${s.slice(0, w - 3)}...`;
|
|
4981
|
+
if (s.length <= width) return s;
|
|
4982
|
+
if (width < 4) return s;
|
|
4983
|
+
return `${s.slice(0, width - 3)}...`;
|
|
3080
4984
|
}
|
|
3081
4985
|
//#endregion
|
|
3082
4986
|
//#region src/sprig/strings/abbrevboth.ts
|
|
@@ -3087,11 +4991,9 @@ function abbrev(width, s) {
|
|
|
3087
4991
|
* a slice taken between them.
|
|
3088
4992
|
*/
|
|
3089
4993
|
function abbrevboth(left, right, s) {
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
if (l < 0 || l > s.length - r + 1) return s;
|
|
3094
|
-
return `...${s.slice(l, l + r - 6)}...`;
|
|
4994
|
+
if (right < 7 || s.length < right) return s;
|
|
4995
|
+
if (left < 0 || left > s.length - right + 1) return s;
|
|
4996
|
+
return `...${s.slice(left, left + right - 6)}...`;
|
|
3095
4997
|
}
|
|
3096
4998
|
//#endregion
|
|
3097
4999
|
//#region src/sprig/strings/caseUtils.ts
|
|
@@ -3413,7 +5315,7 @@ function hasSuffix(suffix, s) {
|
|
|
3413
5315
|
//#region src/sprig/strings/indent.ts
|
|
3414
5316
|
/** `indent n s` — prefix every line of `s` with `n` spaces. */
|
|
3415
5317
|
function indent(n, s) {
|
|
3416
|
-
const pad = " ".repeat(Math.max(0,
|
|
5318
|
+
const pad = " ".repeat(Math.max(0, n));
|
|
3417
5319
|
return s.split("\n").map((line) => pad + line).join("\n");
|
|
3418
5320
|
}
|
|
3419
5321
|
//#endregion
|
|
@@ -3489,7 +5391,7 @@ function nospace(s) {
|
|
|
3489
5391
|
* Mirrors Go sprig's `plural(one, many string, count int) string`.
|
|
3490
5392
|
*/
|
|
3491
5393
|
function plural(one, many, n) {
|
|
3492
|
-
return n === 1
|
|
5394
|
+
return n === 1 ? one : many;
|
|
3493
5395
|
}
|
|
3494
5396
|
//#endregion
|
|
3495
5397
|
//#region src/sprig/strings/quote.ts
|
|
@@ -3513,8 +5415,7 @@ function regexQuoteMeta(s) {
|
|
|
3513
5415
|
//#endregion
|
|
3514
5416
|
//#region src/sprig/strings/repeat.ts
|
|
3515
5417
|
function repeat(n, s) {
|
|
3516
|
-
|
|
3517
|
-
return s.repeat(count);
|
|
5418
|
+
return s.repeat(Math.max(0, n));
|
|
3518
5419
|
}
|
|
3519
5420
|
//#endregion
|
|
3520
5421
|
//#region src/sprig/strings/replace.ts
|
|
@@ -3574,7 +5475,7 @@ function splitList(sep, s) {
|
|
|
3574
5475
|
* explicitly to recover the Go behavior.
|
|
3575
5476
|
*/
|
|
3576
5477
|
function splitn(sep, n, s) {
|
|
3577
|
-
const parts = goSplitN(s, sep,
|
|
5478
|
+
const parts = goSplitN(s, sep, n);
|
|
3578
5479
|
const res = {};
|
|
3579
5480
|
for (let i = 0; i < parts.length; i++) res[`_${i}`] = parts[i] ?? "";
|
|
3580
5481
|
return res;
|
|
@@ -3597,13 +5498,13 @@ function squote(...args) {
|
|
|
3597
5498
|
//#region src/sprig/strings/substr.ts
|
|
3598
5499
|
/**
|
|
3599
5500
|
* `substr i j s` — substring [i, j) with out-of-range clamping.
|
|
3600
|
-
* Matches Go sprig's behavior of clamping rather than throwing
|
|
5501
|
+
* Matches Go sprig's behavior of clamping rather than throwing:
|
|
5502
|
+
* negative `end` (and any `end > s.length`) clamps to `s.length`;
|
|
5503
|
+
* `start` clamps to `[0, end]`.
|
|
3601
5504
|
*/
|
|
3602
5505
|
function substr(start, end, s) {
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
if (j > s.length) j = s.length;
|
|
3606
|
-
if (i > j) i = j;
|
|
5506
|
+
const j = end < 0 || end > s.length ? s.length : end;
|
|
5507
|
+
const i = Math.min(Math.max(0, start), j);
|
|
3607
5508
|
return s.slice(i, j);
|
|
3608
5509
|
}
|
|
3609
5510
|
//#endregion
|
|
@@ -3674,13 +5575,11 @@ function trimSuffix(suffix, s) {
|
|
|
3674
5575
|
* Strings shorter than |n| are returned unchanged. Matches Go sprig.
|
|
3675
5576
|
*/
|
|
3676
5577
|
function trunc(n, s) {
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
if (len < 0) {
|
|
3680
|
-
const k = -len;
|
|
5578
|
+
if (n < 0) {
|
|
5579
|
+
const k = -n;
|
|
3681
5580
|
return k >= s.length ? s : s.slice(s.length - k);
|
|
3682
5581
|
}
|
|
3683
|
-
return
|
|
5582
|
+
return n >= s.length ? s : s.slice(0, n);
|
|
3684
5583
|
}
|
|
3685
5584
|
//#endregion
|
|
3686
5585
|
//#region src/sprig/strings/untitle.ts
|
|
@@ -3700,10 +5599,10 @@ function upper(s) {
|
|
|
3700
5599
|
* Lines longer than width that contain no spaces are emitted as-is.
|
|
3701
5600
|
*/
|
|
3702
5601
|
function wrap(width, s) {
|
|
3703
|
-
return wrapWithSeparator(
|
|
5602
|
+
return wrapWithSeparator(width, "\n", s);
|
|
3704
5603
|
}
|
|
3705
5604
|
function wrapWithSeparator(width, sep, s) {
|
|
3706
|
-
if (
|
|
5605
|
+
if (width <= 0) return s;
|
|
3707
5606
|
const out = [];
|
|
3708
5607
|
for (const para of s.split("\n")) {
|
|
3709
5608
|
let line = "";
|
|
@@ -3724,7 +5623,7 @@ function wrapWithSeparator(width, sep, s) {
|
|
|
3724
5623
|
//#region src/sprig/strings/wrapWith.ts
|
|
3725
5624
|
/** `wrapWith width sep s` — wrap to width using `sep` instead of \n. */
|
|
3726
5625
|
function wrapWith(width, sep, s) {
|
|
3727
|
-
return wrapWithSeparator(
|
|
5626
|
+
return wrapWithSeparator(width, sep, s);
|
|
3728
5627
|
}
|
|
3729
5628
|
//#endregion
|
|
3730
5629
|
//#region src/sprig/strings/index.ts
|
|
@@ -3732,13 +5631,13 @@ function sprigStrings() {
|
|
|
3732
5631
|
return {
|
|
3733
5632
|
abbrev: {
|
|
3734
5633
|
fn: (w, s) => abbrev(w, s),
|
|
3735
|
-
argTypes: ["
|
|
5634
|
+
argTypes: ["int", "string"]
|
|
3736
5635
|
},
|
|
3737
5636
|
abbrevboth: {
|
|
3738
5637
|
fn: (l, r, s) => abbrevboth(l, r, s),
|
|
3739
5638
|
argTypes: [
|
|
3740
|
-
"
|
|
3741
|
-
"
|
|
5639
|
+
"int",
|
|
5640
|
+
"int",
|
|
3742
5641
|
"string"
|
|
3743
5642
|
]
|
|
3744
5643
|
},
|
|
@@ -3765,7 +5664,7 @@ function sprigStrings() {
|
|
|
3765
5664
|
},
|
|
3766
5665
|
indent: {
|
|
3767
5666
|
fn: (n, s) => indent(n, s),
|
|
3768
|
-
argTypes: ["
|
|
5667
|
+
argTypes: ["int", "string"]
|
|
3769
5668
|
},
|
|
3770
5669
|
initials: {
|
|
3771
5670
|
fn: (s) => initials(s),
|
|
@@ -3786,7 +5685,7 @@ function sprigStrings() {
|
|
|
3786
5685
|
},
|
|
3787
5686
|
nindent: {
|
|
3788
5687
|
fn: (n, s) => nindent(n, s),
|
|
3789
|
-
argTypes: ["
|
|
5688
|
+
argTypes: ["int", "string"]
|
|
3790
5689
|
},
|
|
3791
5690
|
nospace: {
|
|
3792
5691
|
fn: (s) => nospace(s),
|
|
@@ -3798,7 +5697,7 @@ function sprigStrings() {
|
|
|
3798
5697
|
argTypes: [
|
|
3799
5698
|
"string",
|
|
3800
5699
|
"string",
|
|
3801
|
-
"
|
|
5700
|
+
"int"
|
|
3802
5701
|
],
|
|
3803
5702
|
returnType: "string"
|
|
3804
5703
|
},
|
|
@@ -3813,7 +5712,7 @@ function sprigStrings() {
|
|
|
3813
5712
|
},
|
|
3814
5713
|
repeat: {
|
|
3815
5714
|
fn: (n, s) => repeat(n, s),
|
|
3816
|
-
argTypes: ["
|
|
5715
|
+
argTypes: ["int", "string"]
|
|
3817
5716
|
},
|
|
3818
5717
|
replace: {
|
|
3819
5718
|
fn: (o, n, s) => replace(o, n, s),
|
|
@@ -3840,7 +5739,7 @@ function sprigStrings() {
|
|
|
3840
5739
|
fn: (sep, n, s) => splitn(sep, n, s),
|
|
3841
5740
|
argTypes: [
|
|
3842
5741
|
"string",
|
|
3843
|
-
"
|
|
5742
|
+
"int",
|
|
3844
5743
|
"string"
|
|
3845
5744
|
],
|
|
3846
5745
|
returnType: "dict"
|
|
@@ -3852,8 +5751,8 @@ function sprigStrings() {
|
|
|
3852
5751
|
substr: {
|
|
3853
5752
|
fn: (i, j, s) => substr(i, j, s),
|
|
3854
5753
|
argTypes: [
|
|
3855
|
-
"
|
|
3856
|
-
"
|
|
5754
|
+
"int",
|
|
5755
|
+
"int",
|
|
3857
5756
|
"string"
|
|
3858
5757
|
]
|
|
3859
5758
|
},
|
|
@@ -3884,7 +5783,7 @@ function sprigStrings() {
|
|
|
3884
5783
|
},
|
|
3885
5784
|
trunc: {
|
|
3886
5785
|
fn: (n, s) => trunc(n, s),
|
|
3887
|
-
argTypes: ["
|
|
5786
|
+
argTypes: ["int", "string"]
|
|
3888
5787
|
},
|
|
3889
5788
|
untitle: {
|
|
3890
5789
|
fn: (s) => untitle(s),
|
|
@@ -3896,12 +5795,12 @@ function sprigStrings() {
|
|
|
3896
5795
|
},
|
|
3897
5796
|
wrap: {
|
|
3898
5797
|
fn: (w, s) => wrap(w, s),
|
|
3899
|
-
argTypes: ["
|
|
5798
|
+
argTypes: ["int", "string"]
|
|
3900
5799
|
},
|
|
3901
5800
|
wrapWith: {
|
|
3902
5801
|
fn: (w, sep, s) => wrapWith(w, sep, s),
|
|
3903
5802
|
argTypes: [
|
|
3904
|
-
"
|
|
5803
|
+
"int",
|
|
3905
5804
|
"string",
|
|
3906
5805
|
"string"
|
|
3907
5806
|
]
|
|
@@ -4005,6 +5904,6 @@ function sprigTypes() {
|
|
|
4005
5904
|
};
|
|
4006
5905
|
}
|
|
4007
5906
|
//#endregion
|
|
4008
|
-
export { Engine, EvalError, FuncNotFoundError, MissingFieldError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDefaults, sprigDicts, sprigLists, sprigMath, sprigRegex, sprigStrings, sprigTypes };
|
|
5907
|
+
export { Engine, EvalError, FailError, FuncNotFoundError, MissingFieldError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDatetime, sprigDefaults, sprigDicts, sprigFlow, sprigHash, sprigLists, sprigMath, sprigRandom, sprigRegex, sprigSemver, sprigStrings, sprigTypes };
|
|
4009
5908
|
|
|
4010
5909
|
//# sourceMappingURL=index.js.map
|