@promptctl/go-template-js 0.10.0 → 0.13.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 +110 -4
- package/dist/index.d.ts +126 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +762 -324
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -78,6 +78,9 @@ var ArgCountError = class extends EvalError {
|
|
|
78
78
|
this.got = got;
|
|
79
79
|
}
|
|
80
80
|
};
|
|
81
|
+
function isStackOverflow(e) {
|
|
82
|
+
return (e instanceof RangeError || e instanceof Error && e.name === "InternalError") && (e.message.includes("call stack") || e.message.includes("too much recursion"));
|
|
83
|
+
}
|
|
81
84
|
var TypeMismatchError = class extends EvalError {
|
|
82
85
|
name = "TypeMismatchError";
|
|
83
86
|
kind = "TypeMismatchError";
|
|
@@ -87,7 +90,7 @@ var TypeMismatchError = class extends EvalError {
|
|
|
87
90
|
expected;
|
|
88
91
|
receivedSummary;
|
|
89
92
|
constructor(funcName, argIndex, expected, receivedSummary, pos, ctx = {}) {
|
|
90
|
-
super(`function ${JSON.stringify(funcName)} arg ${argIndex}: expected ${expected}, but a ${receivedSummary} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`, pos, ctx);
|
|
93
|
+
super(`function ${JSON.stringify(funcName)} arg ${argIndex}: expected ${expected}, but a value of type ${receivedSummary} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`, pos, ctx);
|
|
91
94
|
this.funcName = funcName;
|
|
92
95
|
this.argIndex = argIndex;
|
|
93
96
|
this.expected = expected;
|
|
@@ -599,7 +602,7 @@ function isIdentPart(c) {
|
|
|
599
602
|
/**
|
|
600
603
|
* The named sub-templates a template can invoke: the ones its own source
|
|
601
604
|
* declared plus, transitively, the ones it inherited at parse. Opaque: only
|
|
602
|
-
* `has` and the `EMPTY` identity are public, so a consumer can neither build
|
|
605
|
+
* `has`, `names` and the `EMPTY` identity are public, so a consumer can neither build
|
|
603
606
|
* one by hand (the parser is the single enforcer of the redefinition invariant
|
|
604
607
|
* below) nor reach the AST inside — the entry lookup is `lookupDefine`, a
|
|
605
608
|
* module export index.ts never re-exports.
|
|
@@ -635,10 +638,26 @@ var Defines = class Defines {
|
|
|
635
638
|
has(name) {
|
|
636
639
|
return readDefine(this, name) !== void 0;
|
|
637
640
|
}
|
|
641
|
+
/**
|
|
642
|
+
* Every name this set can render, own and inherited, sorted — what a
|
|
643
|
+
* consumer reads after `evaluateDefine` reports a name as not defined.
|
|
644
|
+
* The parser forbids redeclaring an inherited name, so the chain repeats
|
|
645
|
+
* none; the Set keeps the listing duplicate-free without leaning on that.
|
|
646
|
+
*/
|
|
647
|
+
names() {
|
|
648
|
+
const names = /* @__PURE__ */ new Set();
|
|
649
|
+
for (let d = this; d; d = d.#parent) for (const name of d.#own.keys()) names.add(name);
|
|
650
|
+
return [...names].sort();
|
|
651
|
+
}
|
|
638
652
|
};
|
|
639
653
|
function parse(source, delims, inherit = Defines.EMPTY) {
|
|
640
654
|
return new Parser(source, delims, inherit).parseTemplate();
|
|
641
655
|
}
|
|
656
|
+
const PIPELINE_CONTEXT = {
|
|
657
|
+
If: "if",
|
|
658
|
+
Range: "range",
|
|
659
|
+
With: "with"
|
|
660
|
+
};
|
|
642
661
|
var Parser = class {
|
|
643
662
|
lex;
|
|
644
663
|
buf = [];
|
|
@@ -760,7 +779,7 @@ var Parser = class {
|
|
|
760
779
|
return null;
|
|
761
780
|
case "RightDelim": throw this.errAt(head, "empty action", { expected: "pipeline" });
|
|
762
781
|
default: {
|
|
763
|
-
const pipe = this.parsePipeline();
|
|
782
|
+
const pipe = this.parsePipeline("command");
|
|
764
783
|
const right = this.expect("RightDelim", "`}}`");
|
|
765
784
|
return {
|
|
766
785
|
type: "Action",
|
|
@@ -775,7 +794,7 @@ var Parser = class {
|
|
|
775
794
|
}
|
|
776
795
|
}
|
|
777
796
|
parseBranch(kind, startPos, trimLeft) {
|
|
778
|
-
const pipe = this.parsePipeline();
|
|
797
|
+
const pipe = this.parsePipeline(PIPELINE_CONTEXT[kind]);
|
|
779
798
|
this.expect("RightDelim", "`}}`");
|
|
780
799
|
if (kind === "Range") this.rangeDepth += 1;
|
|
781
800
|
const list = this.parseList();
|
|
@@ -873,7 +892,7 @@ var Parser = class {
|
|
|
873
892
|
}
|
|
874
893
|
parseTemplateInvocation(startPos, trimLeft) {
|
|
875
894
|
const name = this.parseQuotedName();
|
|
876
|
-
const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline();
|
|
895
|
+
const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline("template clause");
|
|
877
896
|
const trim = {
|
|
878
897
|
trimLeft,
|
|
879
898
|
trimRight: this.expect("RightDelim", "`}}`").trimRight === true
|
|
@@ -893,7 +912,7 @@ var Parser = class {
|
|
|
893
912
|
}
|
|
894
913
|
parseBlock(startPos, trimLeft) {
|
|
895
914
|
const name = this.parseQuotedName();
|
|
896
|
-
const pipe = this.
|
|
915
|
+
const pipe = this.parsePipeline("block clause");
|
|
897
916
|
this.expect("RightDelim", "`}}`");
|
|
898
917
|
const savedDepth = this.rangeDepth;
|
|
899
918
|
this.rangeDepth = 0;
|
|
@@ -907,19 +926,13 @@ var Parser = class {
|
|
|
907
926
|
list,
|
|
908
927
|
source: this.source
|
|
909
928
|
});
|
|
910
|
-
return
|
|
929
|
+
return {
|
|
911
930
|
type: "Block",
|
|
912
931
|
pos: startPos,
|
|
913
932
|
name,
|
|
914
933
|
pipe,
|
|
915
934
|
list,
|
|
916
935
|
trim
|
|
917
|
-
} : {
|
|
918
|
-
type: "Block",
|
|
919
|
-
pos: startPos,
|
|
920
|
-
name,
|
|
921
|
-
list,
|
|
922
|
-
trim
|
|
923
936
|
};
|
|
924
937
|
}
|
|
925
938
|
parseDefine(_startPos, _trimLeft) {
|
|
@@ -944,9 +957,11 @@ var Parser = class {
|
|
|
944
957
|
});
|
|
945
958
|
return decodeStringLiteral(t.value, t.pos, this.source);
|
|
946
959
|
}
|
|
947
|
-
parsePipeline() {
|
|
960
|
+
parsePipeline(context) {
|
|
948
961
|
const startPos = this.peek().pos;
|
|
949
|
-
const decls = this.tryParseDecls();
|
|
962
|
+
const decls = this.tryParseDecls(context);
|
|
963
|
+
const end = this.peek();
|
|
964
|
+
if (end.type === "RightDelim" || end.type === "RightParen") throw this.errAt(end, `missing value for ${context}`, { expected: "command" });
|
|
950
965
|
const cmds = [this.parseCommand()];
|
|
951
966
|
while (this.peek().type === "Pipe") {
|
|
952
967
|
this.next();
|
|
@@ -965,18 +980,19 @@ var Parser = class {
|
|
|
965
980
|
cmds
|
|
966
981
|
};
|
|
967
982
|
}
|
|
968
|
-
tryParseDecls() {
|
|
969
|
-
if (this.peek()
|
|
983
|
+
tryParseDecls(context) {
|
|
984
|
+
if (!isDeclTarget(this.peek())) return void 0;
|
|
970
985
|
let n = 1;
|
|
971
986
|
while (this.peek(n).type === "Comma") {
|
|
972
|
-
if (this.peek(n + 1)
|
|
987
|
+
if (!isDeclTarget(this.peek(n + 1))) return void 0;
|
|
973
988
|
n += 2;
|
|
974
989
|
}
|
|
975
990
|
const opType = this.peek(n).type;
|
|
976
991
|
if (opType !== "Declare" && opType !== "Assign") return void 0;
|
|
977
992
|
const vars = [varFromToken(this.next())];
|
|
978
993
|
while (this.peek().type === "Comma") {
|
|
979
|
-
this.next();
|
|
994
|
+
const comma = this.next();
|
|
995
|
+
if (vars.length === (context === "range" ? 2 : 1)) throw this.errAt(comma, `too many declarations in ${context}`);
|
|
980
996
|
vars.push(varFromToken(this.expect("Variable", "$variable")));
|
|
981
997
|
}
|
|
982
998
|
return {
|
|
@@ -1037,7 +1053,7 @@ var Parser = class {
|
|
|
1037
1053
|
}
|
|
1038
1054
|
}
|
|
1039
1055
|
parseChainOrPipe(startPos) {
|
|
1040
|
-
const inner = this.parsePipeline();
|
|
1056
|
+
const inner = this.parsePipeline("parenthesized pipeline");
|
|
1041
1057
|
const rparen = this.expect("RightParen", "`)`");
|
|
1042
1058
|
const fields = [];
|
|
1043
1059
|
const expectedNextOffset = rparen.pos.offset + 1;
|
|
@@ -1087,6 +1103,9 @@ function canStartPrimary(t) {
|
|
|
1087
1103
|
default: return false;
|
|
1088
1104
|
}
|
|
1089
1105
|
}
|
|
1106
|
+
function isDeclTarget(t) {
|
|
1107
|
+
return t.type === "Variable" && !t.value.includes(".");
|
|
1108
|
+
}
|
|
1090
1109
|
function varFromToken(t) {
|
|
1091
1110
|
return {
|
|
1092
1111
|
type: "Variable",
|
|
@@ -1303,7 +1322,7 @@ function children(node) {
|
|
|
1303
1322
|
node.elseList
|
|
1304
1323
|
] : [node.pipe, node.list];
|
|
1305
1324
|
case "Template": return node.pipe ? [node.pipe] : [];
|
|
1306
|
-
case "Block": return
|
|
1325
|
+
case "Block": return [node.pipe, node.list];
|
|
1307
1326
|
default: return assertNever(node);
|
|
1308
1327
|
}
|
|
1309
1328
|
}
|
|
@@ -1404,6 +1423,50 @@ function isLazy(fn) {
|
|
|
1404
1423
|
return LAZY_FUNCS.has(fn);
|
|
1405
1424
|
}
|
|
1406
1425
|
//#endregion
|
|
1426
|
+
//#region src/evaluator/include.ts
|
|
1427
|
+
const render = () => {
|
|
1428
|
+
throw new Error("include was called outside the evaluator's dispatch");
|
|
1429
|
+
};
|
|
1430
|
+
/** Helm's `include(name string, data interface{}) (string, error)`. */
|
|
1431
|
+
const include = {
|
|
1432
|
+
fn: render,
|
|
1433
|
+
argTypes: ["string", "value"],
|
|
1434
|
+
arity: { kind: "exact" },
|
|
1435
|
+
returnType: "string"
|
|
1436
|
+
};
|
|
1437
|
+
const renderFragments = () => {
|
|
1438
|
+
throw new Error("includeFragments was called outside the evaluator's dispatch");
|
|
1439
|
+
};
|
|
1440
|
+
/** Capture a define for replay as its original output fragments. */
|
|
1441
|
+
const includeFragments = {
|
|
1442
|
+
...include,
|
|
1443
|
+
fn: renderFragments,
|
|
1444
|
+
returnType: "value"
|
|
1445
|
+
};
|
|
1446
|
+
function includeKind(fn) {
|
|
1447
|
+
if (fn.fn === render) return "text";
|
|
1448
|
+
if (fn.fn === renderFragments) return "fragments";
|
|
1449
|
+
}
|
|
1450
|
+
const captureText = Symbol.for("@promptctl/go-template-js/captureText");
|
|
1451
|
+
function isCapturedText(value) {
|
|
1452
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1453
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1454
|
+
return prototype !== null && Object.hasOwn(prototype, captureText);
|
|
1455
|
+
}
|
|
1456
|
+
/** A capture's visible label is its Stringer view and determines its truth. */
|
|
1457
|
+
var CapturedText = class {
|
|
1458
|
+
#text;
|
|
1459
|
+
constructor(text) {
|
|
1460
|
+
this.#text = text;
|
|
1461
|
+
}
|
|
1462
|
+
get [captureText]() {
|
|
1463
|
+
return this.#text;
|
|
1464
|
+
}
|
|
1465
|
+
toString() {
|
|
1466
|
+
return this[captureText];
|
|
1467
|
+
}
|
|
1468
|
+
};
|
|
1469
|
+
//#endregion
|
|
1407
1470
|
//#region src/evaluator/truthy.ts
|
|
1408
1471
|
/**
|
|
1409
1472
|
* Go-template truthiness, used by `if`, `with`, and `range`-empty.
|
|
@@ -1419,6 +1482,7 @@ function isTruthy(value) {
|
|
|
1419
1482
|
if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
|
|
1420
1483
|
if (typeof value === "bigint") return value !== 0n;
|
|
1421
1484
|
if (typeof value === "string") return value.length > 0;
|
|
1485
|
+
if (isCapturedText(value)) return value.toString().length > 0;
|
|
1422
1486
|
if (Array.isArray(value)) return value.length > 0;
|
|
1423
1487
|
if (value instanceof Map) return value.size > 0;
|
|
1424
1488
|
if (value instanceof Set) return value.size > 0;
|
|
@@ -1494,13 +1558,13 @@ function eagerBuiltins(toString, isT) {
|
|
|
1494
1558
|
arity: { kind: "variadic" }
|
|
1495
1559
|
},
|
|
1496
1560
|
print: {
|
|
1497
|
-
fn: (...args) => goPrint(args, toString),
|
|
1561
|
+
fn: (...args) => goPrint(args, toString, isT),
|
|
1498
1562
|
argTypes: ["stringifiable"],
|
|
1499
1563
|
arity: { kind: "variadic" },
|
|
1500
1564
|
returnType: "string"
|
|
1501
1565
|
},
|
|
1502
1566
|
println: {
|
|
1503
|
-
fn: (...args) => `${
|
|
1567
|
+
fn: (...args) => `${goPrintln(args, toString, isT)}\n`,
|
|
1504
1568
|
argTypes: ["stringifiable"],
|
|
1505
1569
|
arity: { kind: "variadic" },
|
|
1506
1570
|
returnType: "string"
|
|
@@ -1525,22 +1589,23 @@ function eagerBuiltins(toString, isT) {
|
|
|
1525
1589
|
call: {
|
|
1526
1590
|
fn: (fn, ...args) => fn(...args),
|
|
1527
1591
|
argTypes: ["callable", "value"],
|
|
1528
|
-
arity: { kind: "variadic" }
|
|
1592
|
+
arity: { kind: "variadic" },
|
|
1593
|
+
writes: true
|
|
1529
1594
|
},
|
|
1530
1595
|
html: {
|
|
1531
|
-
fn: (...args) => htmlEscape(goPrint(args, toString)),
|
|
1596
|
+
fn: (...args) => htmlEscape(goPrint(args, toString, isT)),
|
|
1532
1597
|
argTypes: ["stringifiable"],
|
|
1533
1598
|
arity: { kind: "variadic" },
|
|
1534
1599
|
returnType: "string"
|
|
1535
1600
|
},
|
|
1536
1601
|
js: {
|
|
1537
|
-
fn: (...args) => jsEscape(goPrint(args, toString)),
|
|
1602
|
+
fn: (...args) => jsEscape(goPrint(args, toString, isT)),
|
|
1538
1603
|
argTypes: ["stringifiable"],
|
|
1539
1604
|
arity: { kind: "variadic" },
|
|
1540
1605
|
returnType: "string"
|
|
1541
1606
|
},
|
|
1542
1607
|
urlquery: {
|
|
1543
|
-
fn: (...args) => urlQueryEscape(goPrint(args, toString)),
|
|
1608
|
+
fn: (...args) => urlQueryEscape(goPrint(args, toString, isT)),
|
|
1544
1609
|
argTypes: ["stringifiable"],
|
|
1545
1610
|
arity: { kind: "variadic" },
|
|
1546
1611
|
returnType: "string"
|
|
@@ -1662,22 +1727,20 @@ function goPrintfType(v) {
|
|
|
1662
1727
|
if (v instanceof Map || typeof v === "object") return "map[string]interface {}";
|
|
1663
1728
|
return typeof v;
|
|
1664
1729
|
}
|
|
1665
|
-
function goPrint(args, toString) {
|
|
1730
|
+
function goPrint(args, toString, isT) {
|
|
1666
1731
|
let out = "";
|
|
1667
1732
|
let prevIsString = false;
|
|
1668
1733
|
for (let i = 0; i < args.length; i++) {
|
|
1669
1734
|
const arg = args[i];
|
|
1670
1735
|
const isString = typeof arg === "string";
|
|
1671
1736
|
if (i > 0 && !prevIsString && !isString) out += " ";
|
|
1672
|
-
out +=
|
|
1737
|
+
out += formatV(arg, toString, isT);
|
|
1673
1738
|
prevIsString = isString;
|
|
1674
1739
|
}
|
|
1675
1740
|
return out;
|
|
1676
1741
|
}
|
|
1677
|
-
function
|
|
1678
|
-
|
|
1679
|
-
if (typeof value === "string") return value;
|
|
1680
|
-
return toString(value);
|
|
1742
|
+
function goPrintln(args, toString, isT) {
|
|
1743
|
+
return args.map((arg) => formatV(arg, toString, isT)).join(" ");
|
|
1681
1744
|
}
|
|
1682
1745
|
const HTML_ESCAPE_TABLE = {
|
|
1683
1746
|
"\0": "�",
|
|
@@ -1751,26 +1814,34 @@ function sprintf(format, args, toString, isT) {
|
|
|
1751
1814
|
}
|
|
1752
1815
|
const verb = format[j];
|
|
1753
1816
|
const spec = format.slice(i + 1, j);
|
|
1817
|
+
const missing = argIdx >= args.length;
|
|
1754
1818
|
const arg = args[argIdx++];
|
|
1755
|
-
out += formatVerb(verb ?? "", spec, arg, toString, isT);
|
|
1819
|
+
out += missing ? `%!${verb ?? ""}(MISSING)` : formatVerb(verb ?? "", spec, arg, toString, isT);
|
|
1756
1820
|
i = j + 1;
|
|
1757
1821
|
}
|
|
1758
1822
|
return out;
|
|
1759
1823
|
}
|
|
1760
1824
|
function formatVerb(verb, spec, arg, toString, isT) {
|
|
1825
|
+
if (arg instanceof Uint8Array && (verb === "s" || verb === "q")) return formatLeafVerb(verb, spec, new TextDecoder().decode(arg), toString, isT);
|
|
1826
|
+
if (arg instanceof Uint8Array && verb === "x") return applyWidth(spec, Array.from(arg, (b) => b.toString(16).padStart(2, "0")).join(""));
|
|
1827
|
+
return formatWalk(arg, (leaf) => formatLeafVerb(verb, spec, leaf, toString, isT), toString, isT);
|
|
1828
|
+
}
|
|
1829
|
+
function formatLeafVerb(verb, spec, arg, toString, isT) {
|
|
1761
1830
|
switch (verb) {
|
|
1762
|
-
case "s": return
|
|
1831
|
+
case "s": return applyWidth(spec, formatLeafV(arg, toString, isT));
|
|
1763
1832
|
case "d":
|
|
1764
|
-
if (typeof arg !== "number" && typeof arg !== "bigint") return
|
|
1833
|
+
if (typeof arg !== "number" && typeof arg !== "bigint") return badVerb(verb, arg, toString, isT);
|
|
1765
1834
|
return applyWidth(spec, String(typeof arg === "bigint" ? arg : Math.trunc(arg)));
|
|
1766
|
-
case "v": return applyWidth(spec,
|
|
1767
|
-
case "q": return applyWidth(spec, JSON.stringify(
|
|
1835
|
+
case "v": return applyWidth(spec, formatLeafV(arg, toString, isT));
|
|
1836
|
+
case "q": return applyWidth(spec, JSON.stringify(formatLeafV(arg, toString, isT)));
|
|
1768
1837
|
case "f": {
|
|
1769
|
-
if (typeof arg !== "number" && typeof arg !== "bigint") return
|
|
1838
|
+
if (typeof arg !== "number" && typeof arg !== "bigint") return badVerb(verb, arg, toString, isT);
|
|
1770
1839
|
const precision = spec.includes(".") ? Number(spec.split(".")[1]) : 6;
|
|
1771
1840
|
return applyWidth(spec, Number(arg).toFixed(precision));
|
|
1772
1841
|
}
|
|
1773
|
-
case "t":
|
|
1842
|
+
case "t":
|
|
1843
|
+
if (typeof arg !== "boolean") return badVerb(verb, arg, toString, isT);
|
|
1844
|
+
return applyWidth(spec, String(arg));
|
|
1774
1845
|
case "x":
|
|
1775
1846
|
if (typeof arg === "string") {
|
|
1776
1847
|
const bytes = new TextEncoder().encode(arg);
|
|
@@ -1778,12 +1849,16 @@ function formatVerb(verb, spec, arg, toString, isT) {
|
|
|
1778
1849
|
for (const b of bytes) hex += b.toString(16).padStart(2, "0");
|
|
1779
1850
|
return applyWidth(spec, hex);
|
|
1780
1851
|
}
|
|
1781
|
-
if (typeof arg !== "number" && typeof arg !== "bigint") return
|
|
1852
|
+
if (typeof arg !== "number" && typeof arg !== "bigint") return badVerb(verb, arg, toString, isT);
|
|
1782
1853
|
if (typeof arg === "bigint") return applyWidth(spec, arg.toString(16));
|
|
1783
1854
|
return applyWidth(spec, Math.trunc(arg).toString(16));
|
|
1784
|
-
default: return
|
|
1855
|
+
default: return badVerb(verb, arg, toString, isT);
|
|
1785
1856
|
}
|
|
1786
1857
|
}
|
|
1858
|
+
function badVerb(verb, arg, toString, isT) {
|
|
1859
|
+
if (arg === null || arg === void 0) return `%!${verb}(<nil>)`;
|
|
1860
|
+
return `%!${verb}(${goPrintfType(arg)}=${formatLeafV(arg, toString, isT)})`;
|
|
1861
|
+
}
|
|
1787
1862
|
function applyWidth(spec, body) {
|
|
1788
1863
|
const flag = spec.match(/^([+\-# 0]*)/)?.[1] ?? "";
|
|
1789
1864
|
const widthMatch = spec.slice(flag.length).match(/^(\d+)/);
|
|
@@ -1794,70 +1869,232 @@ function applyWidth(spec, body) {
|
|
|
1794
1869
|
return flag.includes("-") ? body + pad : pad + body;
|
|
1795
1870
|
}
|
|
1796
1871
|
function formatV(value, toString, isT) {
|
|
1872
|
+
try {
|
|
1873
|
+
return formatWalk(value, (leaf) => formatLeafV(leaf, toString, isT), toString, isT);
|
|
1874
|
+
} catch (err) {
|
|
1875
|
+
if (err instanceof UnprintableError) throw new UnprintableError(err.leaf, err.cause, value);
|
|
1876
|
+
throw err;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
function formatWalk(value, leaf, toString, isT) {
|
|
1880
|
+
if (isT(value)) return leaf(value);
|
|
1881
|
+
const walk = (v) => formatWalk(v, leaf, toString, isT);
|
|
1882
|
+
if (Array.isArray(value)) return `[${value.map(walk).join(" ")}]`;
|
|
1883
|
+
if (ArrayBuffer.isView(value) && !(value instanceof DataView)) return `[${Array.from(value, walk).join(" ")}]`;
|
|
1884
|
+
if (value instanceof Map) return formatEntries([...value.entries()], walk, toString, isT);
|
|
1885
|
+
if (isPlainObject(value)) return formatEntries(Object.entries(value), walk, toString, isT);
|
|
1886
|
+
if (isStruct(value)) return `{${Object.values(value).map(walk).join(" ")}}`;
|
|
1887
|
+
return leaf(value);
|
|
1888
|
+
}
|
|
1889
|
+
function isStruct(value) {
|
|
1890
|
+
return typeof value === "object" && value !== null && !(value instanceof Set) && !hasOwnString(value);
|
|
1891
|
+
}
|
|
1892
|
+
function formatLeafV(value, toString, isT) {
|
|
1797
1893
|
if (value === null || value === void 0) return "<nil>";
|
|
1798
1894
|
if (typeof value === "string") return value;
|
|
1799
|
-
if (isT(value)) return
|
|
1800
|
-
if (
|
|
1801
|
-
if (value
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1895
|
+
if (isT(value)) return flattenT(value, toString);
|
|
1896
|
+
if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
|
|
1897
|
+
if (typeof value === "object" && hasOwnString(value)) return stringerText(value);
|
|
1898
|
+
throw new UnprintableError(value);
|
|
1899
|
+
}
|
|
1900
|
+
function flattenT(value, toString) {
|
|
1901
|
+
try {
|
|
1902
|
+
return toString(value);
|
|
1903
|
+
} catch (err) {
|
|
1904
|
+
if (isStackOverflow(err)) throw err;
|
|
1905
|
+
throw new UnprintableError(value, err);
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
function stringerText(value) {
|
|
1909
|
+
try {
|
|
1910
|
+
return String(value);
|
|
1911
|
+
} catch (err) {
|
|
1912
|
+
if (isStackOverflow(err)) throw err;
|
|
1913
|
+
throw new UnprintableError(value, err);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
function hasOwnString(value) {
|
|
1917
|
+
let root = value;
|
|
1918
|
+
for (let p = Object.getPrototypeOf(root); p !== null; p = Object.getPrototypeOf(p)) root = p;
|
|
1919
|
+
const own = value.toString;
|
|
1920
|
+
return typeof own === "function" && own !== root.toString;
|
|
1921
|
+
}
|
|
1922
|
+
/** A value Go's `%v` has no text form for: a Set, a function, a symbol, or
|
|
1923
|
+
* a T the engine's `toString` cannot flatten. The action and the call that
|
|
1924
|
+
* met it report it at their position. */
|
|
1925
|
+
var UnprintableError = class extends Error {
|
|
1926
|
+
name = "UnprintableError";
|
|
1927
|
+
/** What cannot print, named from the printed value: the leaf alone, or
|
|
1928
|
+
* the value holding it. */
|
|
1929
|
+
summary;
|
|
1930
|
+
constructor(leaf, cause, root = leaf) {
|
|
1931
|
+
const summary = root === leaf ? typeNameOf(leaf) : `${typeNameOf(root)} holding ${typeNameOf(leaf)}`;
|
|
1932
|
+
const why = cause instanceof TypeMismatchError ? `expected ${cause.expected}` : "it has no text form";
|
|
1933
|
+
super(`cannot print a value of type ${summary}: ${why}`, { cause });
|
|
1934
|
+
this.leaf = leaf;
|
|
1935
|
+
this.summary = summary;
|
|
1936
|
+
}
|
|
1937
|
+
};
|
|
1938
|
+
function typeNameOf(value) {
|
|
1939
|
+
if (value === null) return "null";
|
|
1940
|
+
if (Array.isArray(value)) return "array";
|
|
1941
|
+
if (typeof value !== "object") return typeof value;
|
|
1942
|
+
if (isPlainObject(value)) return "object";
|
|
1943
|
+
for (let p = Object.getPrototypeOf(value); p !== null; p = Object.getPrototypeOf(p)) {
|
|
1944
|
+
const name = p.constructor?.name;
|
|
1945
|
+
if (typeof name === "string" && name !== "") return name === "Object" ? "object" : name;
|
|
1946
|
+
}
|
|
1947
|
+
return "object";
|
|
1948
|
+
}
|
|
1949
|
+
function formatEntries(entries, walk, toString, isT) {
|
|
1807
1950
|
const isNumeric = (k) => typeof k === "number" || typeof k === "bigint";
|
|
1808
|
-
const byKey = (
|
|
1809
|
-
if (isNumeric(a) && isNumeric(b)) return a < b ? -1 : a > b ? 1 : 0;
|
|
1810
|
-
if (isNumeric(a) !== isNumeric(b)) return isNumeric(a) ? -1 : 1;
|
|
1811
|
-
|
|
1812
|
-
return as < bs ? -1 : as > bs ? 1 : 0;
|
|
1951
|
+
const byKey = (a, b) => {
|
|
1952
|
+
if (isNumeric(a.k) && isNumeric(b.k)) return a.k < b.k ? -1 : a.k > b.k ? 1 : 0;
|
|
1953
|
+
if (isNumeric(a.k) !== isNumeric(b.k)) return isNumeric(a.k) ? -1 : 1;
|
|
1954
|
+
return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
|
|
1813
1955
|
};
|
|
1814
|
-
return `map[${
|
|
1956
|
+
return `map[${entries.map(([k, v]) => ({
|
|
1957
|
+
k,
|
|
1958
|
+
v,
|
|
1959
|
+
text: formatV(k, toString, isT)
|
|
1960
|
+
})).sort(byKey).map(({ k, v }) => `${walk(k)}:${walk(v)}`).join(" ")}]`;
|
|
1815
1961
|
}
|
|
1816
1962
|
function isPlainObject(value) {
|
|
1817
1963
|
if (value === null || typeof value !== "object") return false;
|
|
1818
1964
|
if (Array.isArray(value)) return false;
|
|
1819
1965
|
if (value instanceof Map || value instanceof Set) return false;
|
|
1820
1966
|
const proto = Object.getPrototypeOf(value);
|
|
1821
|
-
return proto === null || proto ===
|
|
1967
|
+
return proto === null || Object.getPrototypeOf(proto) === null;
|
|
1968
|
+
}
|
|
1969
|
+
//#endregion
|
|
1970
|
+
//#region src/evaluator/marks.ts
|
|
1971
|
+
const NO_MARKS = /* @__PURE__ */ new Set();
|
|
1972
|
+
let createMarked;
|
|
1973
|
+
let openMarked;
|
|
1974
|
+
let readCarrier;
|
|
1975
|
+
/**
|
|
1976
|
+
* A func's return value together with the marks of the call that
|
|
1977
|
+
* produced it. Opaque: build one with {@link marked}; only the engine
|
|
1978
|
+
* reads it.
|
|
1979
|
+
*/
|
|
1980
|
+
var Marked = class Marked {
|
|
1981
|
+
#value;
|
|
1982
|
+
#marks;
|
|
1983
|
+
constructor(value, marks) {
|
|
1984
|
+
this.#value = value;
|
|
1985
|
+
this.#marks = marks;
|
|
1986
|
+
}
|
|
1987
|
+
static {
|
|
1988
|
+
createMarked = (value, marks) => value instanceof Marked ? new Marked(value.#value, [...value.#marks, ...marks]) : new Marked(value, marks);
|
|
1989
|
+
openMarked = (result) => result instanceof Marked ? {
|
|
1990
|
+
value: result.#value,
|
|
1991
|
+
marks: result.#marks
|
|
1992
|
+
} : {
|
|
1993
|
+
value: result,
|
|
1994
|
+
marks: []
|
|
1995
|
+
};
|
|
1996
|
+
readCarrier = (result, into) => {
|
|
1997
|
+
if (!(result instanceof Marked)) return result;
|
|
1998
|
+
for (const mark of result.#marks) into.add(mark);
|
|
1999
|
+
return result.#value;
|
|
2000
|
+
};
|
|
2001
|
+
}
|
|
2002
|
+
};
|
|
2003
|
+
/**
|
|
2004
|
+
* Return this from a registered func to mark the call: every emission
|
|
2005
|
+
* and control decision that depends on the call's result reports
|
|
2006
|
+
* `marks`. The template sees `value`, exactly as if it had been returned
|
|
2007
|
+
* directly.
|
|
2008
|
+
*/
|
|
2009
|
+
function marked(value, ...marks) {
|
|
2010
|
+
return createMarked(value, marks);
|
|
2011
|
+
}
|
|
2012
|
+
/**
|
|
2013
|
+
* A func's return read apart: its value and the marks it carries (none
|
|
2014
|
+
* for a plain value). For JS code that builds on a marking func outside a
|
|
2015
|
+
* template — `const { value, marks } = unmarked(tween.fn(...))`, then
|
|
2016
|
+
* `return marked(Math.min(1, value as number), ...marks)`.
|
|
2017
|
+
*/
|
|
2018
|
+
function unmarked(result) {
|
|
2019
|
+
return openMarked(result);
|
|
2020
|
+
}
|
|
2021
|
+
/** `a ∪ b`, sharing an operand when the other is empty. */
|
|
2022
|
+
function unionMarks(a, b) {
|
|
2023
|
+
if (b.size === 0) return a;
|
|
2024
|
+
if (a.size === 0) return b;
|
|
2025
|
+
return new Set([...a, ...b]);
|
|
1822
2026
|
}
|
|
1823
2027
|
//#endregion
|
|
1824
2028
|
//#region src/evaluator/scope.ts
|
|
1825
|
-
|
|
2029
|
+
/**
|
|
2030
|
+
* Lexical scope chain for the evaluator.
|
|
2031
|
+
*
|
|
2032
|
+
* [LAW:dataflow-not-control-flow] A `Scope` is a `dot`, a parent
|
|
2033
|
+
* pointer and the variables declared in it. Entering a construct or an
|
|
2034
|
+
* iteration *constructs* a frame and leaving it drops the frame, so
|
|
2035
|
+
* nothing is ever undone: iterations of `{{range}}` cannot see each
|
|
2036
|
+
* other's `:=` declarations — the data shape itself prevents the bug.
|
|
2037
|
+
*
|
|
2038
|
+
* Only a frame's variables change. A lookup walks the parent chain.
|
|
2039
|
+
* Assignment via `=` searches the chain and overwrites the binding in
|
|
2040
|
+
* the frame that declared it; declaration via `:=` always creates the
|
|
2041
|
+
* binding in the current leaf frame.
|
|
2042
|
+
*
|
|
2043
|
+
* `$` is an ordinary variable declared in a chain's root frame, as in
|
|
2044
|
+
* Go, where it is `vars[0]`: so `$ = v` assigns it, and a `template` /
|
|
2045
|
+
* `block` invocation starts a fresh chain whose only variable is `$`.
|
|
2046
|
+
*/
|
|
2047
|
+
/** The frame a template body starts in: `.` and `$` are both `dot`. */
|
|
2048
|
+
function rootScope(dot) {
|
|
1826
2049
|
return {
|
|
1827
|
-
dot
|
|
1828
|
-
root: value,
|
|
2050
|
+
dot,
|
|
1829
2051
|
parent: void 0,
|
|
1830
|
-
vars:
|
|
2052
|
+
vars: new Map([["$", dot]])
|
|
1831
2053
|
};
|
|
1832
2054
|
}
|
|
1833
2055
|
function pushScope(parent, dot) {
|
|
1834
2056
|
return {
|
|
1835
2057
|
dot,
|
|
1836
|
-
root: parent.root,
|
|
1837
2058
|
parent,
|
|
1838
2059
|
vars: /* @__PURE__ */ new Map()
|
|
1839
2060
|
};
|
|
1840
2061
|
}
|
|
2062
|
+
function findFrame(scope, name) {
|
|
2063
|
+
let cur = scope;
|
|
2064
|
+
while (cur !== void 0 && !cur.vars.has(name)) cur = cur.parent;
|
|
2065
|
+
return cur;
|
|
2066
|
+
}
|
|
1841
2067
|
/**
|
|
1842
2068
|
* Look up a `$var` binding, walking the parent chain.
|
|
1843
|
-
* Returns
|
|
1844
|
-
*
|
|
1845
|
-
* "not declared" from "declared but undefined".
|
|
2069
|
+
* Returns the binding on hit and `undefined` on miss — a `Binding` is a
|
|
2070
|
+
* record, so a variable declared as `undefined` is still a hit.
|
|
1846
2071
|
*/
|
|
1847
2072
|
function lookupVar(scope, name) {
|
|
1848
|
-
|
|
1849
|
-
while (cur !== void 0) {
|
|
1850
|
-
if (cur.vars.has(name)) return {
|
|
1851
|
-
found: true,
|
|
1852
|
-
value: cur.vars.get(name)
|
|
1853
|
-
};
|
|
1854
|
-
cur = cur.parent;
|
|
1855
|
-
}
|
|
1856
|
-
return { found: false };
|
|
2073
|
+
return findFrame(scope, name)?.vars.get(name);
|
|
1857
2074
|
}
|
|
1858
2075
|
/** Declare a new variable in the leaf scope (for `:=`). */
|
|
1859
|
-
function declareVar(scope, name,
|
|
1860
|
-
scope.vars.set(name,
|
|
2076
|
+
function declareVar(scope, name, binding) {
|
|
2077
|
+
scope.vars.set(name, binding);
|
|
2078
|
+
}
|
|
2079
|
+
/**
|
|
2080
|
+
* Overwrite the nearest frame's binding of `name` (for `=`), as Go's
|
|
2081
|
+
* text/template exec.go walks its variable stack. Returns whether any
|
|
2082
|
+
* frame declared it; the caller owns the "undefined variable" error,
|
|
2083
|
+
* which needs a position this module does not have.
|
|
2084
|
+
*/
|
|
2085
|
+
function assignVar(scope, name, binding) {
|
|
2086
|
+
const frame = findFrame(scope, name);
|
|
2087
|
+
frame?.vars.set(name, binding);
|
|
2088
|
+
return frame !== void 0;
|
|
2089
|
+
}
|
|
2090
|
+
/** Add `marks` to what `name`'s binding depends on, if any frame declared it. */
|
|
2091
|
+
function markVar(scope, name, marks) {
|
|
2092
|
+
const binding = lookupVar(scope, name);
|
|
2093
|
+
if (binding === void 0) return;
|
|
2094
|
+
assignVar(scope, name, {
|
|
2095
|
+
value: binding.value,
|
|
2096
|
+
marks: unionMarks(binding.marks, marks)
|
|
2097
|
+
});
|
|
1861
2098
|
}
|
|
1862
2099
|
//#endregion
|
|
1863
2100
|
//#region src/evaluator/evaluator.ts
|
|
@@ -1966,6 +2203,7 @@ function validateArgSpecs(funcs) {
|
|
|
1966
2203
|
const BREAK_SIGNAL = Object.freeze({ kind: "break" });
|
|
1967
2204
|
const CONTINUE_SIGNAL = Object.freeze({ kind: "continue" });
|
|
1968
2205
|
const NO_PIPE = { kind: "none" };
|
|
2206
|
+
const notDefined = (name) => `template ${JSON.stringify(name)} is not defined`;
|
|
1969
2207
|
/**
|
|
1970
2208
|
* A parsed template bound to its parent engine.
|
|
1971
2209
|
*
|
|
@@ -1982,18 +2220,20 @@ let internalCreateTemplate;
|
|
|
1982
2220
|
var Template = class Template {
|
|
1983
2221
|
source;
|
|
1984
2222
|
_evaluate;
|
|
2223
|
+
_evaluateDefine;
|
|
1985
2224
|
_defines;
|
|
1986
2225
|
_referencedFunctions;
|
|
1987
2226
|
_referencedCalls;
|
|
1988
|
-
constructor(source, evaluate, defines, referencedFunctions, referencedCalls) {
|
|
2227
|
+
constructor(source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls) {
|
|
1989
2228
|
this.source = source;
|
|
1990
2229
|
this._evaluate = evaluate;
|
|
2230
|
+
this._evaluateDefine = evaluateDefine;
|
|
1991
2231
|
this._defines = defines;
|
|
1992
2232
|
this._referencedFunctions = referencedFunctions;
|
|
1993
2233
|
this._referencedCalls = referencedCalls;
|
|
1994
2234
|
}
|
|
1995
2235
|
static {
|
|
1996
|
-
internalCreateTemplate = (source, evaluate, defines, referencedFunctions, referencedCalls) => new Template(source, evaluate, defines, referencedFunctions, referencedCalls);
|
|
2236
|
+
internalCreateTemplate = (source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls) => new Template(source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls);
|
|
1997
2237
|
}
|
|
1998
2238
|
/**
|
|
1999
2239
|
* The named sub-templates this template can invoke — its own `{{define}}`s
|
|
@@ -2011,6 +2251,15 @@ var Template = class Template {
|
|
|
2011
2251
|
return this._evaluate(scope);
|
|
2012
2252
|
}
|
|
2013
2253
|
/**
|
|
2254
|
+
* Render one named sub-template — any `{{ define }}` in {@link defines}, its
|
|
2255
|
+
* own or inherited — with `scope` as its dot and `$`, as Go's
|
|
2256
|
+
* `ExecuteTemplate` does. The output is the same `T[]` a whole-template
|
|
2257
|
+
* {@link evaluate} produces, through the same `emitted` / `decided` hooks.
|
|
2258
|
+
*/
|
|
2259
|
+
evaluateDefine(name, scope) {
|
|
2260
|
+
return this._evaluateDefine(name, scope);
|
|
2261
|
+
}
|
|
2262
|
+
/**
|
|
2014
2263
|
* The FuncMap function names this template references — every identifier that
|
|
2015
2264
|
* names a function in this parse: the template body and its own `{{ define }}`
|
|
2016
2265
|
* blocks. A set inherited at parse (see {@link Template.defines}) is described
|
|
@@ -2123,16 +2372,22 @@ var Engine = class {
|
|
|
2123
2372
|
fromString;
|
|
2124
2373
|
toString;
|
|
2125
2374
|
isT;
|
|
2375
|
+
captures = /* @__PURE__ */ new WeakMap();
|
|
2126
2376
|
funcs;
|
|
2127
2377
|
missingKey;
|
|
2128
2378
|
delims;
|
|
2379
|
+
emitted;
|
|
2380
|
+
decided;
|
|
2129
2381
|
constructor(config) {
|
|
2130
2382
|
this.fromString = config.fromString;
|
|
2131
2383
|
const userToString = Object.hasOwn(config, "toString") ? config.toString : void 0;
|
|
2132
2384
|
this.toString = userToString ?? defaultToString;
|
|
2133
|
-
this.isT = config.isT ?? DEFAULT_IS_T;
|
|
2134
2385
|
this.missingKey = validateMissingKey(config.missingKey);
|
|
2135
2386
|
this.delims = validateDelims(config.delims);
|
|
2387
|
+
const isT = config.isT ?? DEFAULT_IS_T;
|
|
2388
|
+
this.isT = (value) => !isCapturedText(value) && isT(value);
|
|
2389
|
+
this.emitted = config.emitted ?? ((value) => value);
|
|
2390
|
+
this.decided = config.decided ?? (() => {});
|
|
2136
2391
|
this.funcs = validateArgSpecs({
|
|
2137
2392
|
...defaultBuiltins(this.toString, this.isT),
|
|
2138
2393
|
...config.funcs ?? {}
|
|
@@ -2147,7 +2402,14 @@ var Engine = class {
|
|
|
2147
2402
|
*/
|
|
2148
2403
|
parse(source, inherit) {
|
|
2149
2404
|
const parsed = parse(source, this.delims, inherit);
|
|
2150
|
-
return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope
|
|
2405
|
+
return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope, (root, ctx) => this.evalList(parsed.root, root, ctx)), (name, scope) => {
|
|
2406
|
+
const entry = lookupDefine(parsed.defines, name);
|
|
2407
|
+
if (!entry) throw new Error(notDefined(name));
|
|
2408
|
+
return this.evalParsed(parsed, scope, (root, ctx) => this.renderDefine(name, entry, root.dot, entry.list.pos, {
|
|
2409
|
+
...ctx,
|
|
2410
|
+
source: entry.source
|
|
2411
|
+
}));
|
|
2412
|
+
}, parsed.defines, collectReferencedFunctions(parsed), collectReferencedCalls(parsed));
|
|
2151
2413
|
}
|
|
2152
2414
|
/**
|
|
2153
2415
|
* Convenience sugar for `parse(src).evaluate.bind(template)`.
|
|
@@ -2168,15 +2430,19 @@ var Engine = class {
|
|
|
2168
2430
|
evaluate(template, scope) {
|
|
2169
2431
|
return template.evaluate(scope);
|
|
2170
2432
|
}
|
|
2171
|
-
evalParsed(parsed, scope) {
|
|
2433
|
+
evalParsed(parsed, scope, body) {
|
|
2172
2434
|
const out = [];
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2435
|
+
body(rootScope({
|
|
2436
|
+
value: scope,
|
|
2437
|
+
marks: NO_MARKS
|
|
2438
|
+
}), {
|
|
2439
|
+
emit: (value, marks) => out.push(this.emitted(value, marks)),
|
|
2440
|
+
decided: this.decided,
|
|
2176
2441
|
defines: parsed.defines,
|
|
2177
|
-
source: parsed.source
|
|
2178
|
-
|
|
2179
|
-
|
|
2442
|
+
source: parsed.source,
|
|
2443
|
+
marks: NO_MARKS,
|
|
2444
|
+
depth: 0
|
|
2445
|
+
});
|
|
2180
2446
|
return out;
|
|
2181
2447
|
}
|
|
2182
2448
|
evalList(node, scope, ctx) {
|
|
@@ -2185,14 +2451,15 @@ var Engine = class {
|
|
|
2185
2451
|
evalNode(node, scope, ctx) {
|
|
2186
2452
|
switch (node.type) {
|
|
2187
2453
|
case "Text":
|
|
2188
|
-
ctx.
|
|
2454
|
+
ctx.emit(this.fromString(node.text), ctx.marks);
|
|
2189
2455
|
return;
|
|
2190
2456
|
case "Comment": return;
|
|
2191
|
-
case "Action":
|
|
2192
|
-
|
|
2193
|
-
|
|
2457
|
+
case "Action":
|
|
2458
|
+
this.read(ctx, (reads) => {
|
|
2459
|
+
const value = this.evalPipe(node.pipe, scope, ctx, reads);
|
|
2460
|
+
if (node.pipe.decls.length === 0) this.emitValue(value, node.pos, ctx, unionMarks(reads, ctx.marks));
|
|
2461
|
+
});
|
|
2194
2462
|
return;
|
|
2195
|
-
}
|
|
2196
2463
|
case "List":
|
|
2197
2464
|
this.evalList(node, scope, ctx);
|
|
2198
2465
|
return;
|
|
@@ -2228,36 +2495,47 @@ var Engine = class {
|
|
|
2228
2495
|
}
|
|
2229
2496
|
}
|
|
2230
2497
|
evalIf(node, scope, ctx) {
|
|
2231
|
-
|
|
2232
|
-
|
|
2498
|
+
const frame = constructFrame(scope);
|
|
2499
|
+
const { value: cond, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));
|
|
2500
|
+
const arm = this.decide(reads, ctx, frame, node);
|
|
2501
|
+
if (isTruthy(cond)) this.evalList(node.list, frame, arm);
|
|
2502
|
+
else if (node.elseList) this.evalList(node.elseList, frame, arm);
|
|
2233
2503
|
}
|
|
2234
2504
|
evalWith(node, scope, ctx) {
|
|
2235
|
-
const
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2505
|
+
const frame = constructFrame(scope);
|
|
2506
|
+
const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));
|
|
2507
|
+
const arm = this.decide(reads, ctx, frame, node);
|
|
2508
|
+
if (isTruthy(value)) this.evalList(node.list, pushScope(frame, {
|
|
2509
|
+
value,
|
|
2510
|
+
marks: arm.marks
|
|
2511
|
+
}), arm);
|
|
2512
|
+
else if (node.elseList) this.evalList(node.elseList, frame, arm);
|
|
2240
2513
|
}
|
|
2241
2514
|
evalRange(node, scope, ctx) {
|
|
2242
|
-
const
|
|
2243
|
-
const
|
|
2515
|
+
const rangeScope = constructFrame(scope);
|
|
2516
|
+
const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, rangeScope, ctx, r));
|
|
2517
|
+
const arm = this.decide(reads, ctx, rangeScope, node);
|
|
2518
|
+
const { decls, isAssign } = node.pipe;
|
|
2244
2519
|
const entries = enumerateForRange(value);
|
|
2245
2520
|
try {
|
|
2246
2521
|
if (entries.length === 0) {
|
|
2247
|
-
if (node.elseList) this.evalList(node.elseList,
|
|
2522
|
+
if (node.elseList) this.evalList(node.elseList, rangeScope, arm);
|
|
2248
2523
|
return;
|
|
2249
2524
|
}
|
|
2250
2525
|
for (const [key, item] of entries) {
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2526
|
+
decls.forEach((decl, i) => {
|
|
2527
|
+
const binding = {
|
|
2528
|
+
value: i === decls.length - 1 ? item : key,
|
|
2529
|
+
marks: arm.marks
|
|
2530
|
+
};
|
|
2531
|
+
this.bind(rangeScope, decl, isAssign, binding, ctx);
|
|
2532
|
+
});
|
|
2533
|
+
const child = pushScope(rangeScope, {
|
|
2534
|
+
value: item,
|
|
2535
|
+
marks: arm.marks
|
|
2536
|
+
});
|
|
2259
2537
|
try {
|
|
2260
|
-
this.evalList(node.list, child,
|
|
2538
|
+
this.evalList(node.list, child, arm);
|
|
2261
2539
|
} catch (e) {
|
|
2262
2540
|
if (e === CONTINUE_SIGNAL) continue;
|
|
2263
2541
|
throw e;
|
|
@@ -2269,59 +2547,149 @@ var Engine = class {
|
|
|
2269
2547
|
}
|
|
2270
2548
|
}
|
|
2271
2549
|
evalTemplateInvoke(node, scope, ctx) {
|
|
2272
|
-
const entry =
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2550
|
+
const entry = this.definedEntry(node.name, node.pos, ctx);
|
|
2551
|
+
const dot = this.invocationDot(node.pipe, scope, ctx);
|
|
2552
|
+
this.renderDefine(node.name, entry, dot, node.pos, ctx);
|
|
2553
|
+
}
|
|
2554
|
+
definedEntry(name, pos, ctx) {
|
|
2555
|
+
const entry = lookupDefine(ctx.defines, name);
|
|
2556
|
+
if (!entry) throw new EvalError(notDefined(name), pos, { source: ctx.source });
|
|
2557
|
+
return entry;
|
|
2558
|
+
}
|
|
2559
|
+
renderDefine(name, body, dot, pos, ctx) {
|
|
2560
|
+
try {
|
|
2561
|
+
this.evalList(body.list, rootScope(dot), {
|
|
2562
|
+
...ctx,
|
|
2563
|
+
source: body.source,
|
|
2564
|
+
depth: ctx.depth + 1
|
|
2565
|
+
});
|
|
2566
|
+
} catch (e) {
|
|
2567
|
+
if (!isStackOverflow(e)) throw e;
|
|
2568
|
+
throw new EvalError(`template ${JSON.stringify(name)}: nesting depth ${ctx.depth + 1} exceeds the host's stack`, pos, {
|
|
2569
|
+
source: ctx.source,
|
|
2570
|
+
cause: e
|
|
2571
|
+
});
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
include(kind, registered, name, data, pos, ctx, reads) {
|
|
2575
|
+
const entry = this.definedEntry(name, pos, ctx);
|
|
2576
|
+
const parts = [];
|
|
2577
|
+
const fragments = kind === "fragments" ? [] : void 0;
|
|
2578
|
+
const emit = (value, marks) => {
|
|
2579
|
+
parts.push(this.toString(value));
|
|
2580
|
+
fragments?.push(value);
|
|
2581
|
+
for (const mark of marks) reads.add(mark);
|
|
2582
|
+
};
|
|
2583
|
+
const decided = (marks) => {
|
|
2584
|
+
ctx.decided(marks);
|
|
2585
|
+
for (const mark of marks) reads.add(mark);
|
|
2586
|
+
};
|
|
2587
|
+
const dot = {
|
|
2588
|
+
value: data,
|
|
2589
|
+
marks: new Set([...reads, ...ctx.marks])
|
|
2590
|
+
};
|
|
2591
|
+
try {
|
|
2592
|
+
this.renderDefine(name, entry, dot, pos, {
|
|
2593
|
+
...ctx,
|
|
2594
|
+
emit,
|
|
2595
|
+
decided
|
|
2596
|
+
});
|
|
2597
|
+
} catch (e) {
|
|
2598
|
+
if (!(e instanceof TemplateError)) throw e;
|
|
2599
|
+
const root = innermost(e);
|
|
2600
|
+
throw new (root instanceof FailError ? FailError : EvalError)(`error calling ${registered} ${JSON.stringify(name)}: ${root.message}`, pos, {
|
|
2601
|
+
source: ctx.source,
|
|
2602
|
+
cause: e
|
|
2603
|
+
});
|
|
2604
|
+
}
|
|
2605
|
+
const text = parts.join("");
|
|
2606
|
+
if (!fragments) return text;
|
|
2607
|
+
const capture = new CapturedText(text);
|
|
2608
|
+
this.captures.set(capture, fragments);
|
|
2609
|
+
return capture;
|
|
2280
2610
|
}
|
|
2281
2611
|
evalBlock(node, scope, ctx) {
|
|
2282
|
-
const
|
|
2612
|
+
const dot = this.invocationDot(node.pipe, scope, ctx);
|
|
2283
2613
|
const entry = lookupDefine(ctx.defines, node.name) ?? {
|
|
2284
2614
|
list: node.list,
|
|
2285
2615
|
source: ctx.source
|
|
2286
2616
|
};
|
|
2287
|
-
this.
|
|
2288
|
-
out: ctx.out,
|
|
2289
|
-
defines: ctx.defines,
|
|
2290
|
-
source: entry.source
|
|
2291
|
-
});
|
|
2617
|
+
this.renderDefine(node.name, entry, dot, node.pos, ctx);
|
|
2292
2618
|
}
|
|
2293
|
-
|
|
2294
|
-
|
|
2619
|
+
decide(reads, ctx, frame, arms) {
|
|
2620
|
+
const marks = unionMarks(ctx.marks, reads);
|
|
2621
|
+
ctx.decided(marks);
|
|
2622
|
+
for (const name of this.assignedIn(arms)) markVar(frame, name, marks);
|
|
2623
|
+
return {
|
|
2624
|
+
...ctx,
|
|
2625
|
+
marks
|
|
2626
|
+
};
|
|
2295
2627
|
}
|
|
2296
|
-
|
|
2628
|
+
assigned = /* @__PURE__ */ new WeakMap();
|
|
2629
|
+
assignedIn(arms) {
|
|
2630
|
+
const cached = this.assigned.get(arms.list);
|
|
2631
|
+
if (cached !== void 0) return cached;
|
|
2632
|
+
const names = /* @__PURE__ */ new Set();
|
|
2633
|
+
const collect = (n) => {
|
|
2634
|
+
if (n.type === "Pipe" && n.isAssign) for (const d of n.decls) names.add(d.idents[0] ?? "$");
|
|
2635
|
+
};
|
|
2636
|
+
for (const list of [arms.list, arms.elseList]) if (list) walk(list, collect);
|
|
2637
|
+
const found = [...names];
|
|
2638
|
+
this.assigned.set(arms.list, found);
|
|
2639
|
+
return found;
|
|
2640
|
+
}
|
|
2641
|
+
invocationDot(pipe, scope, ctx) {
|
|
2642
|
+
const { value, reads } = this.read(ctx, (r) => pipe ? this.evalPipe(pipe, scope, ctx, r) : null);
|
|
2643
|
+
return {
|
|
2644
|
+
value,
|
|
2645
|
+
marks: unionMarks(reads, ctx.marks)
|
|
2646
|
+
};
|
|
2647
|
+
}
|
|
2648
|
+
read(ctx, evaluate) {
|
|
2649
|
+
const reads = /* @__PURE__ */ new Set();
|
|
2650
|
+
try {
|
|
2651
|
+
return {
|
|
2652
|
+
value: evaluate(reads),
|
|
2653
|
+
reads
|
|
2654
|
+
};
|
|
2655
|
+
} catch (e) {
|
|
2656
|
+
ctx.decided(unionMarks(reads, ctx.marks));
|
|
2657
|
+
throw e;
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
evalPipe(pipe, scope, ctx, reads) {
|
|
2297
2661
|
if (pipe.cmds.length === 0) throw new EvalError("empty pipeline", pipe.pos, { source: ctx.source });
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
value = this.evalCommand(
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2662
|
+
const inputs = /* @__PURE__ */ new Set();
|
|
2663
|
+
let value;
|
|
2664
|
+
try {
|
|
2665
|
+
value = this.evalCommand(pipe.cmds[0], scope, ctx, NO_PIPE, inputs);
|
|
2666
|
+
for (let i = 1; i < pipe.cmds.length; i++) {
|
|
2667
|
+
const next = pipe.cmds[i];
|
|
2668
|
+
value = this.evalCommand(next, scope, ctx, {
|
|
2669
|
+
kind: "value",
|
|
2670
|
+
value
|
|
2671
|
+
}, inputs);
|
|
2672
|
+
}
|
|
2673
|
+
} finally {
|
|
2674
|
+
for (const mark of inputs) reads.add(mark);
|
|
2305
2675
|
}
|
|
2306
|
-
|
|
2676
|
+
for (const decl of pipe.decls) this.bind(scope, decl, pipe.isAssign, {
|
|
2677
|
+
value,
|
|
2678
|
+
marks: unionMarks(inputs, ctx.marks)
|
|
2679
|
+
}, ctx);
|
|
2307
2680
|
return value;
|
|
2308
2681
|
}
|
|
2309
|
-
|
|
2310
|
-
const
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
decls: [],
|
|
2314
|
-
isAssign: false,
|
|
2315
|
-
cmds: pipe.cmds
|
|
2316
|
-
};
|
|
2317
|
-
return this.evalPipe(stripped, scope, ctx);
|
|
2682
|
+
bind(scope, decl, isAssign, binding, ctx) {
|
|
2683
|
+
const name = decl.idents[0] ?? "$";
|
|
2684
|
+
if (!isAssign) declareVar(scope, name, binding);
|
|
2685
|
+
else if (!assignVar(scope, name, binding)) throw undefinedVariable(name, decl.pos, ctx);
|
|
2318
2686
|
}
|
|
2319
|
-
evalCommand(cmd, scope, ctx, piped) {
|
|
2687
|
+
evalCommand(cmd, scope, ctx, piped, reads) {
|
|
2320
2688
|
if (cmd.args.length === 0) throw new EvalError("empty command", cmd.pos, { source: ctx.source });
|
|
2321
2689
|
const head = cmd.args[0];
|
|
2322
2690
|
if (head.type !== "Identifier") {
|
|
2323
2691
|
if (cmd.args.length > 1) throw new EvalError(`cannot apply arguments to a ${head.type} primary; only functions take arguments`, cmd.pos, { source: ctx.source });
|
|
2324
|
-
return this.evalPrimary(head, scope, ctx);
|
|
2692
|
+
return this.evalPrimary(head, scope, ctx, reads);
|
|
2325
2693
|
}
|
|
2326
2694
|
const fn = this.funcs[head.ident];
|
|
2327
2695
|
if (!fn) throw new FuncNotFoundError(head.ident, head.pos, {
|
|
@@ -2330,46 +2698,67 @@ var Engine = class {
|
|
|
2330
2698
|
});
|
|
2331
2699
|
const argNodes = cmd.args.slice(1);
|
|
2332
2700
|
const lazy = isLazy(fn);
|
|
2333
|
-
const args = argNodes.map((n) => lazy ? () => this.evalPrimary(n, scope, ctx) : this.evalPrimary(n, scope, ctx));
|
|
2701
|
+
const args = argNodes.map((n) => lazy ? () => this.evalPrimary(n, scope, ctx, reads) : this.evalPrimary(n, scope, ctx, reads));
|
|
2334
2702
|
if (piped.kind === "value") {
|
|
2335
2703
|
const v = piped.value;
|
|
2336
2704
|
args.push(lazy ? () => v : v);
|
|
2337
2705
|
}
|
|
2338
|
-
return this.invoke(head.ident, fn, args, cmd.pos, ctx);
|
|
2706
|
+
return this.invoke(head.ident, fn, args, cmd.pos, ctx, reads);
|
|
2339
2707
|
}
|
|
2340
|
-
invoke(name, fn, args, pos, ctx) {
|
|
2341
|
-
enforceArgTypes(name, fn, args, pos, ctx.source, this.toString, this.fromString, this.isT);
|
|
2708
|
+
invoke(name, fn, args, pos, ctx, reads) {
|
|
2342
2709
|
try {
|
|
2343
|
-
|
|
2710
|
+
enforceArgTypes(name, fn, args, pos, ctx.source, this.toString, this.fromString, this.isT);
|
|
2344
2711
|
} catch (e) {
|
|
2712
|
+
if (e instanceof TemplateError) throw e;
|
|
2713
|
+
throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {
|
|
2714
|
+
source: ctx.source,
|
|
2715
|
+
cause: e
|
|
2716
|
+
});
|
|
2717
|
+
}
|
|
2718
|
+
let result;
|
|
2719
|
+
try {
|
|
2720
|
+
const kind = includeKind(fn);
|
|
2721
|
+
result = readCarrier(kind !== void 0 ? this.include(kind, name, args[0], args[1], pos, ctx, reads) : fn.fn(...args), reads);
|
|
2722
|
+
} catch (thrown) {
|
|
2723
|
+
const e = readCarrier(thrown, reads);
|
|
2345
2724
|
if (e instanceof TypeMismatchError) throw new TypeMismatchError(e.funcName, e.argIndex, e.expected, e.receivedSummary, pos, { source: ctx.source });
|
|
2346
|
-
if (e instanceof FailError) throw new FailError(e.message, pos, {
|
|
2725
|
+
if (e instanceof FailError) throw new FailError(e.message, pos, {
|
|
2726
|
+
source: ctx.source,
|
|
2727
|
+
cause: e.cause
|
|
2728
|
+
});
|
|
2347
2729
|
if (e instanceof TemplateError) throw e;
|
|
2348
2730
|
throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {
|
|
2349
2731
|
source: ctx.source,
|
|
2350
2732
|
cause: e
|
|
2351
2733
|
});
|
|
2352
2734
|
}
|
|
2735
|
+
if (fn.writes === true) ctx.decided(new Set([...reads, ...ctx.marks]));
|
|
2736
|
+
return result;
|
|
2353
2737
|
}
|
|
2354
|
-
evalPrimary(node, scope, ctx) {
|
|
2738
|
+
evalPrimary(node, scope, ctx, reads) {
|
|
2739
|
+
const value = this.evalOperand(node, scope, ctx, reads);
|
|
2740
|
+
if (value instanceof Marked) throw new EvalError("a marked() value reached the template from inside a func's return; return marked(...) itself, not a structure containing one", node.pos, { source: ctx.source });
|
|
2741
|
+
return value;
|
|
2742
|
+
}
|
|
2743
|
+
evalOperand(node, scope, ctx, reads) {
|
|
2355
2744
|
switch (node.type) {
|
|
2356
|
-
case "Dot": return scope
|
|
2745
|
+
case "Dot": return this.readDot(scope, reads);
|
|
2357
2746
|
case "Nil": return null;
|
|
2358
2747
|
case "Bool": return node.value;
|
|
2359
2748
|
case "Number": return numberValue(node);
|
|
2360
2749
|
case "String": return node.value;
|
|
2361
|
-
case "Field": return this.resolveFieldChain(scope
|
|
2362
|
-
case "Variable": return this.resolveVariable(node.idents, scope, node.pos, ctx);
|
|
2750
|
+
case "Field": return this.resolveFieldChain(this.readDot(scope, reads), node.idents, node.pos, ctx);
|
|
2751
|
+
case "Variable": return this.resolveVariable(node.idents, scope, node.pos, ctx, reads);
|
|
2363
2752
|
case "Identifier": {
|
|
2364
2753
|
const fn = this.funcs[node.ident];
|
|
2365
2754
|
if (!fn) throw new FuncNotFoundError(node.ident, node.pos, {
|
|
2366
2755
|
source: ctx.source,
|
|
2367
2756
|
available: Object.keys(this.funcs)
|
|
2368
2757
|
});
|
|
2369
|
-
return this.invoke(node.ident, fn, [], node.pos, ctx);
|
|
2758
|
+
return this.invoke(node.ident, fn, [], node.pos, ctx, reads);
|
|
2370
2759
|
}
|
|
2371
|
-
case "Chain": return this.resolveFieldChain(this.evalPrimary(node.node, scope, ctx), node.fields, node.pos, ctx);
|
|
2372
|
-
case "Pipe": return this.evalPipe(node, scope, ctx);
|
|
2760
|
+
case "Chain": return this.resolveFieldChain(this.evalPrimary(node.node, scope, ctx, reads), node.fields, node.pos, ctx);
|
|
2761
|
+
case "Pipe": return this.evalPipe(node, scope, ctx, reads);
|
|
2373
2762
|
default: throw new EvalError(`cannot evaluate ${node.type} as a value`, node.pos, { source: ctx.source });
|
|
2374
2763
|
}
|
|
2375
2764
|
}
|
|
@@ -2378,38 +2767,43 @@ var Engine = class {
|
|
|
2378
2767
|
if (result !== MISSING) return result;
|
|
2379
2768
|
if (this.missingKey === "error") throw new MissingFieldError(idents, pos, { source: ctx.source });
|
|
2380
2769
|
}
|
|
2381
|
-
resolveVariable(idents, scope, pos, ctx) {
|
|
2770
|
+
resolveVariable(idents, scope, pos, ctx, reads) {
|
|
2382
2771
|
const head = idents[0] ?? "$";
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
}
|
|
2387
|
-
const lookup = lookupVar(scope, head);
|
|
2388
|
-
if (!lookup.found) throw new EvalError(`undefined variable ${head}`, pos, { source: ctx.source });
|
|
2772
|
+
const binding = lookupVar(scope, head);
|
|
2773
|
+
if (binding === void 0) throw undefinedVariable(head, pos, ctx);
|
|
2774
|
+
for (const mark of binding.marks) reads.add(mark);
|
|
2389
2775
|
const tail = idents.slice(1);
|
|
2390
|
-
return tail.length === 0 ?
|
|
2776
|
+
return tail.length === 0 ? binding.value : this.resolveFieldChain(binding.value, tail, pos, ctx);
|
|
2391
2777
|
}
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
if (
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
2402
|
-
ctx.out.push(this.fromString(String(value)));
|
|
2778
|
+
readDot(scope, reads) {
|
|
2779
|
+
for (const mark of scope.dot.marks) reads.add(mark);
|
|
2780
|
+
return scope.dot.value;
|
|
2781
|
+
}
|
|
2782
|
+
emitValue(value, pos, ctx, marks) {
|
|
2783
|
+
if (isCapturedText(value)) {
|
|
2784
|
+
const fragments = this.captures.get(value);
|
|
2785
|
+
if (!fragments) throw new EvalError("cannot emit fragments captured by a different engine", pos, { source: ctx.source });
|
|
2786
|
+
for (const fragment of fragments) ctx.emit(fragment, marks);
|
|
2403
2787
|
return;
|
|
2404
2788
|
}
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2789
|
+
ctx.emit(this.lift(value, pos, ctx.source), marks);
|
|
2790
|
+
}
|
|
2791
|
+
lift(value, pos, source) {
|
|
2792
|
+
if (value === null || value === void 0) return this.fromString("<no value>");
|
|
2793
|
+
if (typeof value === "string") return this.fromString(value);
|
|
2794
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return this.fromString(String(value));
|
|
2795
|
+
if (this.isT(value)) return value;
|
|
2796
|
+
try {
|
|
2797
|
+
return this.fromString(formatV(value, this.toString, this.isT));
|
|
2798
|
+
} catch (err) {
|
|
2799
|
+
throw new EvalError(err instanceof UnprintableError ? err.message : `cannot print: ${errorText(err)}`, pos, {
|
|
2800
|
+
source,
|
|
2801
|
+
cause: err
|
|
2802
|
+
});
|
|
2408
2803
|
}
|
|
2409
|
-
ctx.out.push(this.fromString(formatV(value, this.toString, this.isT)));
|
|
2410
2804
|
}
|
|
2411
2805
|
};
|
|
2412
|
-
const DEFAULT_IS_T = (v) => typeof v === "
|
|
2806
|
+
const DEFAULT_IS_T = (v) => typeof v === "string";
|
|
2413
2807
|
function createEngine(config) {
|
|
2414
2808
|
return new Engine(config);
|
|
2415
2809
|
}
|
|
@@ -2423,20 +2817,21 @@ function enforceArgTypes(funcName, spec, values, pos, src, toString = defaultToS
|
|
|
2423
2817
|
for (let i = 0; i < values.length; i++) {
|
|
2424
2818
|
const declared = lookup(i);
|
|
2425
2819
|
const value = values[i];
|
|
2426
|
-
|
|
2820
|
+
const refusal = refusalOf(declared, value, toString, isT);
|
|
2821
|
+
if (refusal !== void 0) {
|
|
2427
2822
|
if ((declared === "int" || declared === "truncating-int") && (typeof value === "number" || typeof value === "bigint")) throw new NotIntegerError(funcName, i + 1, value, pos, { source: src });
|
|
2428
|
-
throw new TypeMismatchError(funcName, i + 1, humanArgType(declared),
|
|
2823
|
+
throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), refusal, pos, { source: src });
|
|
2429
2824
|
}
|
|
2430
2825
|
if (declared === "liftable" && typeof value === "string") values[i] = fromString(value);
|
|
2431
2826
|
if (declared === "truncating-int") values[i] = Math.trunc(Number(value));
|
|
2432
2827
|
else if (declared === "int" || declared === "float") values[i] = Number(value);
|
|
2433
2828
|
if (declared === "ordered") {
|
|
2434
2829
|
if (firstOrdered === -1) firstOrdered = i;
|
|
2435
|
-
else if (!sameOrderedKind(values[firstOrdered], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("ordered")} of the same kind as ${
|
|
2830
|
+
else if (!sameOrderedKind(values[firstOrdered], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("ordered")} of the same kind as ${typeNameOf(values[firstOrdered])}`, typeNameOf(value), pos, { source: src });
|
|
2436
2831
|
}
|
|
2437
2832
|
if (declared === "comparable") {
|
|
2438
2833
|
if (firstComparable === -1) firstComparable = i;
|
|
2439
|
-
else if (!sameComparableKind(values[firstComparable], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("comparable")} of the same kind as ${
|
|
2834
|
+
else if (!sameComparableKind(values[firstComparable], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("comparable")} of the same kind as ${typeNameOf(values[firstComparable])}`, typeNameOf(value), pos, { source: src });
|
|
2440
2835
|
}
|
|
2441
2836
|
}
|
|
2442
2837
|
}
|
|
@@ -2464,7 +2859,7 @@ function makeSlotLookup(argTypes, arity) {
|
|
|
2464
2859
|
case "alternating": return (i) => argTypes[i % len];
|
|
2465
2860
|
}
|
|
2466
2861
|
}
|
|
2467
|
-
function matchesArgType(declared, value,
|
|
2862
|
+
function matchesArgType(declared, value, isT) {
|
|
2468
2863
|
switch (declared) {
|
|
2469
2864
|
case "truthy":
|
|
2470
2865
|
case "reflective":
|
|
@@ -2484,14 +2879,6 @@ function matchesArgType(declared, value, toString, isT) {
|
|
|
2484
2879
|
case "collection": return typeof value === "string" || Array.isArray(value) || value instanceof Map || isPlainObject(value);
|
|
2485
2880
|
case "index-key": return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
|
|
2486
2881
|
case "sliceable": return typeof value === "string" || Array.isArray(value);
|
|
2487
|
-
case "stringifiable":
|
|
2488
|
-
if (typeof value === "string") return true;
|
|
2489
|
-
try {
|
|
2490
|
-
toString(value);
|
|
2491
|
-
return true;
|
|
2492
|
-
} catch {
|
|
2493
|
-
return false;
|
|
2494
|
-
}
|
|
2495
2882
|
case "liftable": return typeof value === "string" || isT(value);
|
|
2496
2883
|
case "serializable": return isJsonSerializable(value);
|
|
2497
2884
|
default: throw new Error(`invalid ArgType: ${String(declared)}`);
|
|
@@ -2504,7 +2891,7 @@ function defaultToString(value) {
|
|
|
2504
2891
|
if (typeof value === "string") return value;
|
|
2505
2892
|
if (value === null || value === void 0) return "<nil>";
|
|
2506
2893
|
if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
|
|
2507
|
-
throw new TypeMismatchError("<engine.toString>", 1, "string (or a consumer-supplied toString that flattens T)",
|
|
2894
|
+
throw new TypeMismatchError("<engine.toString>", 1, "string (or a consumer-supplied toString that flattens T)", typeNameOf(value), {
|
|
2508
2895
|
line: 0,
|
|
2509
2896
|
column: 0,
|
|
2510
2897
|
offset: 0
|
|
@@ -2544,13 +2931,13 @@ function humanArgType(t) {
|
|
|
2544
2931
|
case "int": return "integer (safe-integer number or bigint)";
|
|
2545
2932
|
case "truncating-int": return "integer (finite number, truncated toward zero, or safe-integer bigint)";
|
|
2546
2933
|
case "float": return "float (number, including NaN/Infinity, or finite-convertible bigint)";
|
|
2547
|
-
case "T": return "T (
|
|
2934
|
+
case "T": return "T (a value the engine's isT accepts)";
|
|
2548
2935
|
case "ordered": return "orderable primitive";
|
|
2549
2936
|
case "list": return "list";
|
|
2550
2937
|
case "dict": return "dict (plain object)";
|
|
2551
2938
|
case "sized": return "sized value (string, list, map, set, or dict)";
|
|
2552
2939
|
case "comparable": return "comparable value (orderable primitive, nil, list, dict, Map, or Set)";
|
|
2553
|
-
case "stringifiable": return "stringifiable value (string
|
|
2940
|
+
case "stringifiable": return "stringifiable value (string, nil, scalar, a T the engine's toString flattens, an object with its own toString, a class instance, or a list/map of those; not a Set, function or symbol)";
|
|
2554
2941
|
case "liftable": return "liftable value (T or string, the latter lifted via the engine's fromString)";
|
|
2555
2942
|
case "callable": return "callable (function value)";
|
|
2556
2943
|
case "collection": return "collection (string, array, Map, or dict)";
|
|
@@ -2565,15 +2952,30 @@ function humanArgType(t) {
|
|
|
2565
2952
|
default: throw new Error(`invalid ArgType: ${String(t)}`);
|
|
2566
2953
|
}
|
|
2567
2954
|
}
|
|
2955
|
+
function constructFrame(scope) {
|
|
2956
|
+
return pushScope(scope, scope.dot);
|
|
2957
|
+
}
|
|
2958
|
+
function undefinedVariable(name, pos, ctx) {
|
|
2959
|
+
return new EvalError(`undefined variable: ${name}`, pos, { source: ctx.source });
|
|
2960
|
+
}
|
|
2961
|
+
function innermost(e) {
|
|
2962
|
+
return e.cause instanceof TemplateError ? innermost(e.cause) : e;
|
|
2963
|
+
}
|
|
2568
2964
|
function errorText(e) {
|
|
2569
2965
|
return e instanceof Error ? e.message : String(e);
|
|
2570
2966
|
}
|
|
2571
|
-
function
|
|
2572
|
-
if (
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2967
|
+
function refusalOf(declared, value, toString, isT) {
|
|
2968
|
+
if (declared === "stringifiable") return printRefusal(value, toString, isT)?.summary;
|
|
2969
|
+
return matchesArgType(declared, value, isT) ? void 0 : typeNameOf(value);
|
|
2970
|
+
}
|
|
2971
|
+
function printRefusal(value, toString, isT) {
|
|
2972
|
+
try {
|
|
2973
|
+
formatV(value, toString, isT);
|
|
2974
|
+
return;
|
|
2975
|
+
} catch (err) {
|
|
2976
|
+
if (err instanceof UnprintableError) return err;
|
|
2977
|
+
throw err;
|
|
2978
|
+
}
|
|
2577
2979
|
}
|
|
2578
2980
|
/**
|
|
2579
2981
|
* Produce [key, value] entries for a `range` operand.
|
|
@@ -3035,33 +3437,41 @@ function pad3(n) {
|
|
|
3035
3437
|
function spacePad2(n) {
|
|
3036
3438
|
return n < 10 ? ` ${n}` : String(n);
|
|
3037
3439
|
}
|
|
3440
|
+
function offsetParts(offsetSeconds) {
|
|
3441
|
+
const minutes = Math.trunc(offsetSeconds / 60);
|
|
3442
|
+
const abs = Math.abs(minutes);
|
|
3443
|
+
return {
|
|
3444
|
+
sign: minutes < 0 ? "-" : "+",
|
|
3445
|
+
hh: pad2(Math.floor(abs / 60)),
|
|
3446
|
+
mm: pad2(abs % 60)
|
|
3447
|
+
};
|
|
3448
|
+
}
|
|
3038
3449
|
/** ±hhmm (no colon). E.g. "+0500", "-0500", "+0000". */
|
|
3039
|
-
function fmtOffset(
|
|
3040
|
-
const sign
|
|
3041
|
-
|
|
3042
|
-
return `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;
|
|
3450
|
+
function fmtOffset(offsetSeconds) {
|
|
3451
|
+
const { sign, hh, mm } = offsetParts(offsetSeconds);
|
|
3452
|
+
return `${sign}${hh}${mm}`;
|
|
3043
3453
|
}
|
|
3044
3454
|
/** ±hh:mm (with colon). E.g. "+05:00", "-05:00", "+00:00". */
|
|
3045
|
-
function fmtOffsetColon(
|
|
3046
|
-
const sign
|
|
3047
|
-
|
|
3048
|
-
return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
|
|
3455
|
+
function fmtOffsetColon(offsetSeconds) {
|
|
3456
|
+
const { sign, hh, mm } = offsetParts(offsetSeconds);
|
|
3457
|
+
return `${sign}${hh}:${mm}`;
|
|
3049
3458
|
}
|
|
3050
3459
|
/** ±hh only. */
|
|
3051
|
-
function fmtOffsetHour(
|
|
3052
|
-
|
|
3460
|
+
function fmtOffsetHour(offsetSeconds) {
|
|
3461
|
+
const { sign, hh } = offsetParts(offsetSeconds);
|
|
3462
|
+
return `${sign}${hh}`;
|
|
3053
3463
|
}
|
|
3054
3464
|
/** Z or ±hhmm. */
|
|
3055
|
-
function fmtOffsetZ(
|
|
3056
|
-
return
|
|
3465
|
+
function fmtOffsetZ(offsetSeconds) {
|
|
3466
|
+
return offsetSeconds === 0 ? "Z" : fmtOffset(offsetSeconds);
|
|
3057
3467
|
}
|
|
3058
3468
|
/** Z or ±hh:mm. */
|
|
3059
|
-
function fmtOffsetColonZ(
|
|
3060
|
-
return
|
|
3469
|
+
function fmtOffsetColonZ(offsetSeconds) {
|
|
3470
|
+
return offsetSeconds === 0 ? "Z" : fmtOffsetColon(offsetSeconds);
|
|
3061
3471
|
}
|
|
3062
3472
|
/** Z or ±hh. */
|
|
3063
|
-
function fmtOffsetHourZ(
|
|
3064
|
-
return
|
|
3473
|
+
function fmtOffsetHourZ(offsetSeconds) {
|
|
3474
|
+
return offsetSeconds === 0 ? "Z" : fmtOffsetHour(offsetSeconds);
|
|
3065
3475
|
}
|
|
3066
3476
|
function fmtFrac(ms, width, trimTrailing) {
|
|
3067
3477
|
const nanosTotal = ms * 1e6;
|
|
@@ -3087,16 +3497,16 @@ const TOKENS$1 = [
|
|
|
3087
3497
|
}],
|
|
3088
3498
|
["January", (z) => MONTHS_LONG$1[z.month - 1] ?? "January"],
|
|
3089
3499
|
["Monday", (z) => WEEKDAYS_LONG[z.weekday] ?? "Monday"],
|
|
3090
|
-
["Z07:00", (z) => fmtOffsetColonZ(z.
|
|
3091
|
-
["-07:00", (z) => fmtOffsetColon(z.
|
|
3092
|
-
["Z0700", (z) => fmtOffsetZ(z.
|
|
3093
|
-
["-0700", (z) => fmtOffset(z.
|
|
3094
|
-
["2006", (z) => String(z.year)],
|
|
3500
|
+
["Z07:00", (z) => fmtOffsetColonZ(z.offsetSeconds)],
|
|
3501
|
+
["-07:00", (z) => fmtOffsetColon(z.offsetSeconds)],
|
|
3502
|
+
["Z0700", (z) => fmtOffsetZ(z.offsetSeconds)],
|
|
3503
|
+
["-0700", (z) => fmtOffset(z.offsetSeconds)],
|
|
3504
|
+
["2006", (z) => `${z.year < 0 ? "-" : ""}${String(Math.abs(z.year)).padStart(4, "0")}`],
|
|
3095
3505
|
["Jan", (z) => MONTHS_SHORT$1[z.month - 1] ?? "Jan"],
|
|
3096
3506
|
["Mon", (z) => WEEKDAYS_SHORT[z.weekday] ?? "Mon"],
|
|
3097
3507
|
["MST", (z) => z.tzAbbr],
|
|
3098
|
-
["-07", (z) => fmtOffsetHour(z.
|
|
3099
|
-
["Z07", (z) => fmtOffsetHourZ(z.
|
|
3508
|
+
["-07", (z) => fmtOffsetHour(z.offsetSeconds)],
|
|
3509
|
+
["Z07", (z) => fmtOffsetHourZ(z.offsetSeconds)],
|
|
3100
3510
|
["15", (z) => pad2(z.hour)],
|
|
3101
3511
|
["01", (z) => pad2(z.month)],
|
|
3102
3512
|
["02", (z) => pad2(z.day)],
|
|
@@ -3104,7 +3514,7 @@ const TOKENS$1 = [
|
|
|
3104
3514
|
["03", (z) => pad2(z.hour12)],
|
|
3105
3515
|
["04", (z) => pad2(z.minute)],
|
|
3106
3516
|
["05", (z) => pad2(z.second)],
|
|
3107
|
-
["06", (z) => pad2(z.year % 100)],
|
|
3517
|
+
["06", (z) => pad2(Math.abs(z.year) % 100)],
|
|
3108
3518
|
["PM", (z) => z.hour >= 12 ? "PM" : "AM"],
|
|
3109
3519
|
["pm", (z) => z.hour >= 12 ? "pm" : "am"],
|
|
3110
3520
|
["1", (z) => String(z.month)],
|
|
@@ -3135,6 +3545,7 @@ function formatGoLayout(layout, z) {
|
|
|
3135
3545
|
//#endregion
|
|
3136
3546
|
//#region src/sprig/datetime/_zone.ts
|
|
3137
3547
|
const INTL_OPTS = {
|
|
3548
|
+
era: "short",
|
|
3138
3549
|
year: "numeric",
|
|
3139
3550
|
month: "2-digit",
|
|
3140
3551
|
day: "2-digit",
|
|
@@ -3142,13 +3553,9 @@ const INTL_OPTS = {
|
|
|
3142
3553
|
hour: "2-digit",
|
|
3143
3554
|
minute: "2-digit",
|
|
3144
3555
|
second: "2-digit",
|
|
3145
|
-
hour12: false
|
|
3556
|
+
hour12: false,
|
|
3557
|
+
timeZoneName: "short"
|
|
3146
3558
|
};
|
|
3147
|
-
function indexParts(parts) {
|
|
3148
|
-
const out = /* @__PURE__ */ new Map();
|
|
3149
|
-
for (const p of parts) out.set(p.type, p.value);
|
|
3150
|
-
return out;
|
|
3151
|
-
}
|
|
3152
3559
|
const WEEKDAY_NAMES = [
|
|
3153
3560
|
"Sunday",
|
|
3154
3561
|
"Monday",
|
|
@@ -3158,56 +3565,87 @@ const WEEKDAY_NAMES = [
|
|
|
3158
3565
|
"Friday",
|
|
3159
3566
|
"Saturday"
|
|
3160
3567
|
];
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3568
|
+
function readParts(fmt, date) {
|
|
3569
|
+
const parts = /* @__PURE__ */ new Map();
|
|
3570
|
+
for (const p of fmt.formatToParts(date)) parts.set(p.type, p.value);
|
|
3571
|
+
return (type) => {
|
|
3572
|
+
const value = parts.get(type);
|
|
3573
|
+
if (value === void 0) throw new Error(`Intl.DateTimeFormat omitted the ${type} part`);
|
|
3574
|
+
return value;
|
|
3575
|
+
};
|
|
3576
|
+
}
|
|
3577
|
+
function buildFormatter(timeZone) {
|
|
3578
|
+
return new Intl.DateTimeFormat("en-US", {
|
|
3579
|
+
...INTL_OPTS,
|
|
3580
|
+
timeZone
|
|
3581
|
+
});
|
|
3582
|
+
}
|
|
3583
|
+
const OFFSET_ZONE = /^[+-]/;
|
|
3584
|
+
const formattersByZone = /* @__PURE__ */ new Map();
|
|
3585
|
+
function zoneFormatter(name) {
|
|
3586
|
+
const key = name.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
3587
|
+
const cached = formattersByZone.get(key);
|
|
3588
|
+
if (cached !== void 0) return cached;
|
|
3589
|
+
const loaded = OFFSET_ZONE.test(name) ? void 0 : buildOrUnknown(name);
|
|
3590
|
+
if (loaded === void 0) return zoneFormatter("UTC");
|
|
3591
|
+
formattersByZone.set(key, loaded);
|
|
3592
|
+
return loaded;
|
|
3593
|
+
}
|
|
3594
|
+
function buildOrUnknown(name) {
|
|
3595
|
+
if (name === "UTC") return buildFormatter(name);
|
|
3164
3596
|
try {
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3597
|
+
return buildFormatter(name);
|
|
3598
|
+
} catch (e) {
|
|
3599
|
+
if (e instanceof RangeError) return void 0;
|
|
3600
|
+
throw e;
|
|
3169
3601
|
}
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
const
|
|
3175
|
-
const
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
const
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
const
|
|
3602
|
+
}
|
|
3603
|
+
/** Extract date parts in the requested IANA timezone. Falls back to "UTC" on invalid zone, mirroring Go sprig. */
|
|
3604
|
+
function getZoneParts(date, zone) {
|
|
3605
|
+
const part = readParts(zoneFormatter(zone), date);
|
|
3606
|
+
const eraYear = parseInt(part("year"), 10);
|
|
3607
|
+
const year = part("era") === "BC" ? 1 - eraYear : eraYear;
|
|
3608
|
+
const month = parseInt(part("month"), 10);
|
|
3609
|
+
const day = parseInt(part("day"), 10);
|
|
3610
|
+
const hour = parseInt(part("hour"), 10) % 24;
|
|
3611
|
+
const minute = parseInt(part("minute"), 10);
|
|
3612
|
+
const second = parseInt(part("second"), 10);
|
|
3613
|
+
const ms = date.getUTCMilliseconds();
|
|
3614
|
+
const offsetSeconds = (daysFromCivil(year, month, day) * 864e5 + ((hour * 60 + minute) * 60 + second) * 1e3 + ms - date.getTime()) / 1e3;
|
|
3615
|
+
const weekdayName = part("weekday");
|
|
3616
|
+
const weekday = WEEKDAY_NAMES.indexOf(weekdayName);
|
|
3617
|
+
if (weekday === -1) throw new Error(`Intl.DateTimeFormat gave an unknown weekday ${weekdayName}`);
|
|
3184
3618
|
return {
|
|
3185
|
-
year
|
|
3186
|
-
month
|
|
3187
|
-
day
|
|
3188
|
-
weekday
|
|
3619
|
+
year,
|
|
3620
|
+
month,
|
|
3621
|
+
day,
|
|
3622
|
+
weekday,
|
|
3189
3623
|
hour,
|
|
3190
3624
|
hour12: hour % 12 || 12,
|
|
3191
|
-
minute
|
|
3192
|
-
second
|
|
3193
|
-
ms
|
|
3194
|
-
tzAbbr,
|
|
3195
|
-
|
|
3625
|
+
minute,
|
|
3626
|
+
second,
|
|
3627
|
+
ms,
|
|
3628
|
+
tzAbbr: part("timeZoneName"),
|
|
3629
|
+
offsetSeconds
|
|
3196
3630
|
};
|
|
3197
3631
|
}
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
const
|
|
3202
|
-
|
|
3203
|
-
const
|
|
3204
|
-
|
|
3205
|
-
const min = parseInt(m[3] ?? "0", 10);
|
|
3206
|
-
return sign * (h * 60 + min);
|
|
3632
|
+
function daysFromCivil(year, month, day) {
|
|
3633
|
+
const y = month <= 2 ? year - 1 : year;
|
|
3634
|
+
const era = Math.floor(y / 400);
|
|
3635
|
+
const yearOfEra = y - era * 400;
|
|
3636
|
+
const dayOfYear = Math.floor((153 * ((month + 9) % 12) + 2) / 5) + day - 1;
|
|
3637
|
+
const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
|
|
3638
|
+
return era * 146097 + dayOfEra - 719468;
|
|
3207
3639
|
}
|
|
3640
|
+
let hostZone;
|
|
3208
3641
|
/** Host timezone name (IANA string). */
|
|
3209
3642
|
function localTz() {
|
|
3210
|
-
|
|
3643
|
+
const key = `${globalThis.process?.env.TZ}|${(/* @__PURE__ */ new Date()).getTimezoneOffset()}`;
|
|
3644
|
+
if (hostZone?.key !== key) hostZone = {
|
|
3645
|
+
key,
|
|
3646
|
+
zone: Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
3647
|
+
};
|
|
3648
|
+
return hostZone.zone;
|
|
3211
3649
|
}
|
|
3212
3650
|
//#endregion
|
|
3213
3651
|
//#region src/sprig/datetime/date.ts
|
|
@@ -3292,15 +3730,13 @@ function durationRound(d) {
|
|
|
3292
3730
|
//#region src/sprig/datetime/htmlDate.ts
|
|
3293
3731
|
/** `htmlDate t` — YYYY-MM-DD in the host timezone. */
|
|
3294
3732
|
function htmlDate(t) {
|
|
3295
|
-
|
|
3296
|
-
return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
|
|
3733
|
+
return formatGoLayout("2006-01-02", getZoneParts(resolveDate(t), localTz()));
|
|
3297
3734
|
}
|
|
3298
3735
|
//#endregion
|
|
3299
3736
|
//#region src/sprig/datetime/htmlDateInZone.ts
|
|
3300
3737
|
/** `htmlDateInZone t zone` — YYYY-MM-DD in the named timezone. */
|
|
3301
3738
|
function htmlDateInZone(t, zone) {
|
|
3302
|
-
|
|
3303
|
-
return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
|
|
3739
|
+
return formatGoLayout("2006-01-02", getZoneParts(resolveDate(t), zone));
|
|
3304
3740
|
}
|
|
3305
3741
|
//#endregion
|
|
3306
3742
|
//#region src/sprig/datetime/now.ts
|
|
@@ -3795,16 +4231,7 @@ function sprigDatetime(clock = () => /* @__PURE__ */ new Date()) {
|
|
|
3795
4231
|
* Go's reflect-IsZero semantics).
|
|
3796
4232
|
*/
|
|
3797
4233
|
function empty(value) {
|
|
3798
|
-
|
|
3799
|
-
if (value === false) return true;
|
|
3800
|
-
if (typeof value === "number") return value === 0 || Number.isNaN(value);
|
|
3801
|
-
if (typeof value === "bigint") return value === 0n;
|
|
3802
|
-
if (typeof value === "string") return value.length === 0;
|
|
3803
|
-
if (Array.isArray(value)) return value.length === 0;
|
|
3804
|
-
if (value instanceof Map) return value.size === 0;
|
|
3805
|
-
if (value instanceof Set) return value.size === 0;
|
|
3806
|
-
if (typeof value === "object") return Object.keys(value).length === 0;
|
|
3807
|
-
return false;
|
|
4234
|
+
return !isTruthy(value);
|
|
3808
4235
|
}
|
|
3809
4236
|
//#endregion
|
|
3810
4237
|
//#region src/sprig/defaults/coalesce.ts
|
|
@@ -4123,12 +4550,14 @@ function sprigDicts() {
|
|
|
4123
4550
|
"string",
|
|
4124
4551
|
"value"
|
|
4125
4552
|
],
|
|
4126
|
-
arity: { kind: "exact" }
|
|
4553
|
+
arity: { kind: "exact" },
|
|
4554
|
+
writes: true
|
|
4127
4555
|
},
|
|
4128
4556
|
unset: {
|
|
4129
4557
|
fn: (d, k) => unset(d, k),
|
|
4130
4558
|
argTypes: ["dict", "string"],
|
|
4131
|
-
arity: { kind: "exact" }
|
|
4559
|
+
arity: { kind: "exact" },
|
|
4560
|
+
writes: true
|
|
4132
4561
|
},
|
|
4133
4562
|
keys: {
|
|
4134
4563
|
fn: (d) => keys(d),
|
|
@@ -4482,8 +4911,8 @@ function dig(...args) {
|
|
|
4482
4911
|
const dict = args[args.length - 1];
|
|
4483
4912
|
const def = args[args.length - 2];
|
|
4484
4913
|
const keys = args.slice(0, -2);
|
|
4485
|
-
if (!isPlainDict(dict)) throw bodyTypeMismatch("dig", args.length - 1, "dict",
|
|
4486
|
-
for (let i = 0; i < keys.length; i++) if (typeof keys[i] !== "string") throw bodyTypeMismatch("dig", i, "string",
|
|
4914
|
+
if (!isPlainDict(dict)) throw bodyTypeMismatch("dig", args.length - 1, "dict", typeNameOf(dict));
|
|
4915
|
+
for (let i = 0; i < keys.length; i++) if (typeof keys[i] !== "string") throw bodyTypeMismatch("dig", i, "string", typeNameOf(keys[i]));
|
|
4487
4916
|
return digFromDict(dict, def, keys, args.length);
|
|
4488
4917
|
}
|
|
4489
4918
|
function digFromDict(d, def, ks, argCount) {
|
|
@@ -4491,19 +4920,12 @@ function digFromDict(d, def, ks, argCount) {
|
|
|
4491
4920
|
if (!Object.hasOwn(d, k)) return def;
|
|
4492
4921
|
const step = d[k];
|
|
4493
4922
|
if (ks.length === 1) return step;
|
|
4494
|
-
if (!isPlainDict(step)) throw bodyTypeMismatch("dig", argCount - 1, "dict at intermediate key",
|
|
4923
|
+
if (!isPlainDict(step)) throw bodyTypeMismatch("dig", argCount - 1, "dict at intermediate key", typeNameOf(step));
|
|
4495
4924
|
return digFromDict(step, def, ks.slice(1), argCount);
|
|
4496
4925
|
}
|
|
4497
4926
|
function isPlainDict(v) {
|
|
4498
4927
|
return v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Map) && !(v instanceof Set);
|
|
4499
4928
|
}
|
|
4500
|
-
function describeKind(v) {
|
|
4501
|
-
if (v === null) return "null";
|
|
4502
|
-
if (Array.isArray(v)) return "array";
|
|
4503
|
-
if (v instanceof Map) return "Map";
|
|
4504
|
-
if (v instanceof Set) return "Set";
|
|
4505
|
-
return typeof v;
|
|
4506
|
-
}
|
|
4507
4929
|
//#endregion
|
|
4508
4930
|
//#region src/sprig/lists/first.ts
|
|
4509
4931
|
function first(list) {
|
|
@@ -5518,38 +5940,60 @@ function sprigSemver() {
|
|
|
5518
5940
|
};
|
|
5519
5941
|
}
|
|
5520
5942
|
//#endregion
|
|
5943
|
+
//#region src/sprig/strings/abbreviateFull.ts
|
|
5944
|
+
/**
|
|
5945
|
+
* goutils.AbbreviateFull (Masterminds/goutils@v1.1.1 stringutils.go), the
|
|
5946
|
+
* function behind both sprig `abbrev` and `abbrevboth`: keep at most
|
|
5947
|
+
* `maxWidth` characters of `cps`, starting near `offset`, marking each cut
|
|
5948
|
+
* end with `...`.
|
|
5949
|
+
*
|
|
5950
|
+
* [LAW:one-source-of-truth] Ported whole, step for step in Go's order, so
|
|
5951
|
+
* both sprig wrappers share Go's one control flow instead of each
|
|
5952
|
+
* reconstructing the branch it noticed. Indexed by code point where Go
|
|
5953
|
+
* indexes by byte — see `runes.js`.
|
|
5954
|
+
*
|
|
5955
|
+
* Go returns an error at its two minimum-width checks; both sprig wrappers
|
|
5956
|
+
* guard against reaching them, so here they throw rather than model sprig's
|
|
5957
|
+
* swallowed error.
|
|
5958
|
+
*/
|
|
5959
|
+
function abbreviateFull(cps, offset, maxWidth) {
|
|
5960
|
+
if (cps.length === 0) return "";
|
|
5961
|
+
if (maxWidth < 4) throw new Error("stringutils illegal argument: Minimum abbreviation width is 4");
|
|
5962
|
+
if (cps.length <= maxWidth) return cps.join("");
|
|
5963
|
+
const start = Math.min(offset, cps.length - (maxWidth - 3));
|
|
5964
|
+
if (start <= 4) return `${cps.slice(0, maxWidth - 3).join("")}...`;
|
|
5965
|
+
if (maxWidth < 7) throw new Error("stringutils illegal argument: Minimum abbreviation width with offset is 7");
|
|
5966
|
+
if (start + maxWidth - 3 < cps.length) return `...${abbreviateFull(cps.slice(start), 0, maxWidth - 3)}`;
|
|
5967
|
+
return `...${cps.slice(cps.length - (maxWidth - 3)).join("")}`;
|
|
5968
|
+
}
|
|
5969
|
+
//#endregion
|
|
5521
5970
|
//#region src/sprig/strings/abbrev.ts
|
|
5522
5971
|
/**
|
|
5523
5972
|
* `abbrev width s` — truncate `s` to `width` chars, replacing the tail
|
|
5524
|
-
* with `...` when truncation occurs
|
|
5525
|
-
*
|
|
5526
|
-
*
|
|
5973
|
+
* with `...` when truncation occurs: sprig's guard around
|
|
5974
|
+
* goutils.Abbreviate, which is AbbreviateFull at offset 0. Widths below 4
|
|
5975
|
+
* cannot fit the ellipsis and return `s` unchanged.
|
|
5527
5976
|
*
|
|
5528
5977
|
* `width` counts code points, so the cut never splits an astral
|
|
5529
5978
|
* character — see `runes.js` for why that differs from Go's bytes.
|
|
5530
5979
|
*/
|
|
5531
5980
|
function abbrev(width, s) {
|
|
5532
|
-
const cps = runes(s);
|
|
5533
|
-
if (cps.length <= width) return s;
|
|
5534
5981
|
if (width < 4) return s;
|
|
5535
|
-
return
|
|
5982
|
+
return abbreviateFull(runes(s), 0, width);
|
|
5536
5983
|
}
|
|
5537
5984
|
//#endregion
|
|
5538
5985
|
//#region src/sprig/strings/abbrevboth.ts
|
|
5539
5986
|
/**
|
|
5540
|
-
* `abbrevboth left right s` —
|
|
5541
|
-
*
|
|
5542
|
-
* left
|
|
5543
|
-
* a slice taken between them.
|
|
5987
|
+
* `abbrevboth left right s` — sprig's guard around goutils.AbbreviateFull
|
|
5988
|
+
* with `left` as the offset and `right` as the maximum width: a window of
|
|
5989
|
+
* `s` near `left`, with `...` at each end that was cut.
|
|
5544
5990
|
*
|
|
5545
5991
|
* Offsets count code points, so the window never splits an astral
|
|
5546
5992
|
* character — see `runes.js` for why that differs from Go's bytes.
|
|
5547
5993
|
*/
|
|
5548
5994
|
function abbrevboth(left, right, s) {
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
if (left < 0 || left > cps.length - right + 1) return s;
|
|
5552
|
-
return `...${cps.slice(left, left + right - 6).join("")}...`;
|
|
5995
|
+
if (right < 4 || left > 0 && right < 7) return s;
|
|
5996
|
+
return abbreviateFull(runes(s), left, right);
|
|
5553
5997
|
}
|
|
5554
5998
|
//#endregion
|
|
5555
5999
|
//#region src/sprig/strings/caseUtils.ts
|
|
@@ -5905,17 +6349,11 @@ function initials(s) {
|
|
|
5905
6349
|
function join(sep, list) {
|
|
5906
6350
|
const parts = [];
|
|
5907
6351
|
for (const v of list) {
|
|
5908
|
-
if (v !== null && v !== void 0 && typeof v === "object") throw bodyTypeMismatch("join", 2, "list of strings/primitives", `list element of type ${
|
|
6352
|
+
if (v !== null && v !== void 0 && typeof v === "object") throw bodyTypeMismatch("join", 2, "list of strings/primitives", `list element of type ${typeNameOf(v)}`);
|
|
5909
6353
|
parts.push(String(v));
|
|
5910
6354
|
}
|
|
5911
6355
|
return parts.join(sep);
|
|
5912
6356
|
}
|
|
5913
|
-
function describe(v) {
|
|
5914
|
-
if (Array.isArray(v)) return "array";
|
|
5915
|
-
if (v instanceof Map) return "Map";
|
|
5916
|
-
if (v instanceof Set) return "Set";
|
|
5917
|
-
return "object";
|
|
5918
|
-
}
|
|
5919
6357
|
//#endregion
|
|
5920
6358
|
//#region src/sprig/strings/kebabcase.ts
|
|
5921
6359
|
/**
|
|
@@ -6535,6 +6973,6 @@ function sprigTypes() {
|
|
|
6535
6973
|
};
|
|
6536
6974
|
}
|
|
6537
6975
|
//#endregion
|
|
6538
|
-
export { ArgCountError, Defines, Engine, EvalError, FailError, FuncNotFoundError, MissingFieldError, NotIntegerError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDatetime, sprigDefaults, sprigDicts, sprigFlow, sprigHash, sprigLists, sprigMath, sprigRandom, sprigRegex, sprigSemver, sprigStrings, sprigTypes, staticDictEntries };
|
|
6976
|
+
export { ArgCountError, Defines, Engine, EvalError, FailError, FuncNotFoundError, MissingFieldError, NotIntegerError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, include, includeFragments, marked, sprigConversions, sprigDatetime, sprigDefaults, sprigDicts, sprigFlow, sprigHash, sprigLists, sprigMath, sprigRandom, sprigRegex, sprigSemver, sprigStrings, sprigTypes, staticDictEntries, unmarked };
|
|
6539
6977
|
|
|
6540
6978
|
//# sourceMappingURL=index.js.map
|