@promptctl/go-template-js 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +230 -0
- package/dist/index.d.ts +285 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4004 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4004 @@
|
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
var TemplateError = class extends Error {
|
|
3
|
+
name = "TemplateError";
|
|
4
|
+
kind = "EvalError";
|
|
5
|
+
pos;
|
|
6
|
+
source;
|
|
7
|
+
constructor(message, pos, ctx = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.pos = pos;
|
|
10
|
+
this.source = ctx.source;
|
|
11
|
+
}
|
|
12
|
+
/** 3-line excerpt of the source around the error with caret. */
|
|
13
|
+
get sourceSnippet() {
|
|
14
|
+
return this.source ? buildSnippet(this.source, this.pos) : "";
|
|
15
|
+
}
|
|
16
|
+
toString() {
|
|
17
|
+
const head = `${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`;
|
|
18
|
+
const snippet = this.sourceSnippet;
|
|
19
|
+
return snippet ? `${head}\n\n${snippet}` : head;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var ParseError = class extends TemplateError {
|
|
23
|
+
name = "ParseError";
|
|
24
|
+
kind = "ParseError";
|
|
25
|
+
expected;
|
|
26
|
+
found;
|
|
27
|
+
constructor(message, pos, ctx = {}) {
|
|
28
|
+
super(message, pos, ctx);
|
|
29
|
+
this.expected = ctx.expected;
|
|
30
|
+
this.found = ctx.found;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var EvalError = class extends TemplateError {
|
|
34
|
+
name = "EvalError";
|
|
35
|
+
kind = "EvalError";
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Thrown when a template references a function the engine's FuncMap
|
|
39
|
+
* has no entry for. Includes a list of nearest-matching registered
|
|
40
|
+
* names by edit distance — most useful when the failure is a typo.
|
|
41
|
+
*/
|
|
42
|
+
var FuncNotFoundError = class extends EvalError {
|
|
43
|
+
name = "FuncNotFoundError";
|
|
44
|
+
kind = "FuncNotFoundError";
|
|
45
|
+
funcName;
|
|
46
|
+
suggestions;
|
|
47
|
+
constructor(funcName, pos, ctx = {}) {
|
|
48
|
+
const suggestions = nearestMatches(funcName, ctx.available ?? []);
|
|
49
|
+
const tail = suggestions.length === 0 ? "" : ` (did you mean: ${suggestions.join(", ")}?)`;
|
|
50
|
+
super(`function ${JSON.stringify(funcName)} is not registered${tail}`, pos, ctx);
|
|
51
|
+
this.funcName = funcName;
|
|
52
|
+
this.suggestions = suggestions;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var TypeMismatchError = class extends EvalError {
|
|
56
|
+
name = "TypeMismatchError";
|
|
57
|
+
kind = "TypeMismatchError";
|
|
58
|
+
funcName;
|
|
59
|
+
/** 1-based argument index for human-readable messages. */
|
|
60
|
+
argIndex;
|
|
61
|
+
expected;
|
|
62
|
+
receivedSummary;
|
|
63
|
+
constructor(funcName, argIndex, expected, receivedSummary, pos, ctx = {}) {
|
|
64
|
+
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);
|
|
65
|
+
this.funcName = funcName;
|
|
66
|
+
this.argIndex = argIndex;
|
|
67
|
+
this.expected = expected;
|
|
68
|
+
this.receivedSummary = receivedSummary;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var MissingFieldError = class extends EvalError {
|
|
72
|
+
name = "MissingFieldError";
|
|
73
|
+
kind = "MissingFieldError";
|
|
74
|
+
path;
|
|
75
|
+
constructor(path, pos, ctx = {}) {
|
|
76
|
+
super(`field "${path.join(".")}" not found on receiver`, pos, ctx);
|
|
77
|
+
this.path = path;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
function buildSnippet(source, pos) {
|
|
81
|
+
const lines = source.split("\n");
|
|
82
|
+
const lineIdx = pos.line - 1;
|
|
83
|
+
const display = [];
|
|
84
|
+
if (lineIdx - 1 >= 0 && lineIdx - 1 < lines.length) display.push({
|
|
85
|
+
num: lineIdx,
|
|
86
|
+
text: lines[lineIdx - 1] ?? ""
|
|
87
|
+
});
|
|
88
|
+
if (lineIdx >= 0 && lineIdx < lines.length) display.push({
|
|
89
|
+
num: lineIdx + 1,
|
|
90
|
+
text: lines[lineIdx] ?? ""
|
|
91
|
+
});
|
|
92
|
+
if (lineIdx + 1 < lines.length) display.push({
|
|
93
|
+
num: lineIdx + 2,
|
|
94
|
+
text: lines[lineIdx + 1] ?? ""
|
|
95
|
+
});
|
|
96
|
+
if (display.length === 0) return "";
|
|
97
|
+
const numWidth = String(display[display.length - 1]?.num ?? 1).length;
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const d of display) {
|
|
100
|
+
out.push(` ${String(d.num).padStart(numWidth, " ")} | ${d.text}`);
|
|
101
|
+
if (d.num === pos.line) {
|
|
102
|
+
const gutter = ` ${" ".repeat(numWidth)} | `;
|
|
103
|
+
const caretPad = " ".repeat(Math.max(0, pos.column - 1));
|
|
104
|
+
out.push(`${gutter}${caretPad}^`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out.join("\n");
|
|
108
|
+
}
|
|
109
|
+
function nearestMatches(target, candidates) {
|
|
110
|
+
if (candidates.length === 0) return [];
|
|
111
|
+
const ranked = candidates.map((c) => ({
|
|
112
|
+
name: c,
|
|
113
|
+
dist: editDistance(target, c)
|
|
114
|
+
})).sort((a, b) => a.dist - b.dist);
|
|
115
|
+
const cutoff = Math.max(2, Math.floor(target.length / 2));
|
|
116
|
+
return ranked.filter((r) => r.dist <= cutoff).slice(0, 3).map((r) => r.name);
|
|
117
|
+
}
|
|
118
|
+
function editDistance(a, b) {
|
|
119
|
+
if (a === b) return 0;
|
|
120
|
+
const m = a.length;
|
|
121
|
+
const n = b.length;
|
|
122
|
+
if (m === 0) return n;
|
|
123
|
+
if (n === 0) return m;
|
|
124
|
+
const prev = new Array(n + 1);
|
|
125
|
+
const cur = new Array(n + 1);
|
|
126
|
+
for (let j = 0; j <= n; j++) prev[j] = j;
|
|
127
|
+
for (let i = 1; i <= m; i++) {
|
|
128
|
+
cur[0] = i;
|
|
129
|
+
for (let j = 1; j <= n; j++) {
|
|
130
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
131
|
+
cur[j] = Math.min((cur[j - 1] ?? 0) + 1, (prev[j] ?? 0) + 1, (prev[j - 1] ?? 0) + cost);
|
|
132
|
+
}
|
|
133
|
+
for (let j = 0; j <= n; j++) prev[j] = cur[j] ?? 0;
|
|
134
|
+
}
|
|
135
|
+
return prev[n] ?? 0;
|
|
136
|
+
}
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/parser/ast.ts
|
|
139
|
+
function assertNever(value) {
|
|
140
|
+
throw new Error(`unhandled node kind: ${JSON.stringify(value)}`);
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/parser/lexer.ts
|
|
144
|
+
/**
|
|
145
|
+
* Lexer for Go-template syntax.
|
|
146
|
+
*
|
|
147
|
+
* Mirrors the tokens that text/template/parse/lex.go produces. The lexer
|
|
148
|
+
* is a pull-style state machine — call `next()` to consume the next
|
|
149
|
+
* token, `peek()` to look without consuming. EOF is emitted explicitly
|
|
150
|
+
* as a terminal token.
|
|
151
|
+
*
|
|
152
|
+
* [LAW:dataflow-not-control-flow] The state of the lexer is captured in
|
|
153
|
+
* a single `mode` discriminator (`text` | `action` | `done`), and the
|
|
154
|
+
* `next()` method dispatches on that mode in one switch. Variability
|
|
155
|
+
* lives in the data (current offset, current mode), not in scattered
|
|
156
|
+
* conditional code paths around side effects.
|
|
157
|
+
*
|
|
158
|
+
* [LAW:single-enforcer] All position tracking happens through `advance`.
|
|
159
|
+
* Callers never adjust `offset`, `line`, or `column` directly — that
|
|
160
|
+
* would let line/column drift from offset.
|
|
161
|
+
*/
|
|
162
|
+
const KEYWORDS = new Map([
|
|
163
|
+
["if", "If"],
|
|
164
|
+
["else", "Else"],
|
|
165
|
+
["end", "End"],
|
|
166
|
+
["range", "Range"],
|
|
167
|
+
["with", "With"],
|
|
168
|
+
["define", "Define"],
|
|
169
|
+
["template", "Template"],
|
|
170
|
+
["block", "Block"],
|
|
171
|
+
["true", "Bool"],
|
|
172
|
+
["false", "Bool"],
|
|
173
|
+
["nil", "Nil"]
|
|
174
|
+
]);
|
|
175
|
+
const LEFT_DELIM = "{{";
|
|
176
|
+
const RIGHT_DELIM = "}}";
|
|
177
|
+
const COMMENT_OPEN = "/*";
|
|
178
|
+
const COMMENT_CLOSE = "*/";
|
|
179
|
+
var Lexer = class {
|
|
180
|
+
src;
|
|
181
|
+
offset = 0;
|
|
182
|
+
line = 1;
|
|
183
|
+
column = 1;
|
|
184
|
+
mode = "text";
|
|
185
|
+
pending;
|
|
186
|
+
constructor(src) {
|
|
187
|
+
this.src = src;
|
|
188
|
+
}
|
|
189
|
+
/** Position of the next byte to consume. */
|
|
190
|
+
pos() {
|
|
191
|
+
return {
|
|
192
|
+
line: this.line,
|
|
193
|
+
column: this.column,
|
|
194
|
+
offset: this.offset
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Build a ParseError that always carries the source for snippet
|
|
199
|
+
* extraction. Lexer call sites use this exclusively.
|
|
200
|
+
*/
|
|
201
|
+
err(message, pos, extra = {}) {
|
|
202
|
+
return new ParseError(message, pos, {
|
|
203
|
+
...extra,
|
|
204
|
+
source: this.src
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
next() {
|
|
208
|
+
if (this.pending) {
|
|
209
|
+
const t = this.pending;
|
|
210
|
+
this.pending = void 0;
|
|
211
|
+
return t;
|
|
212
|
+
}
|
|
213
|
+
return this.read();
|
|
214
|
+
}
|
|
215
|
+
peek() {
|
|
216
|
+
if (!this.pending) this.pending = this.read();
|
|
217
|
+
return this.pending;
|
|
218
|
+
}
|
|
219
|
+
read() {
|
|
220
|
+
switch (this.mode) {
|
|
221
|
+
case "text": return this.readText();
|
|
222
|
+
case "action": return this.readAction();
|
|
223
|
+
case "done": return this.makeToken("EOF", "", this.pos());
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
readText() {
|
|
227
|
+
if (this.offset >= this.src.length) {
|
|
228
|
+
this.mode = "done";
|
|
229
|
+
return this.makeToken("EOF", "", this.pos());
|
|
230
|
+
}
|
|
231
|
+
const startPos = this.pos();
|
|
232
|
+
let end = this.offset;
|
|
233
|
+
while (end < this.src.length && !this.src.startsWith(LEFT_DELIM, end)) end += 1;
|
|
234
|
+
const trimLeft = end < this.src.length && this.src[end + 2] === "-";
|
|
235
|
+
let textEnd = end;
|
|
236
|
+
if (trimLeft) while (textEnd > this.offset && isSpace(this.src[textEnd - 1] ?? "")) textEnd -= 1;
|
|
237
|
+
if (textEnd > this.offset) {
|
|
238
|
+
const value = this.src.slice(this.offset, textEnd);
|
|
239
|
+
this.advanceTo(textEnd);
|
|
240
|
+
return this.makeToken("Text", value, startPos);
|
|
241
|
+
}
|
|
242
|
+
this.advanceTo(end);
|
|
243
|
+
return this.emitLeftDelim(trimLeft);
|
|
244
|
+
}
|
|
245
|
+
emitLeftDelim(trimLeft) {
|
|
246
|
+
const start = this.pos();
|
|
247
|
+
this.advanceBy(2);
|
|
248
|
+
if (trimLeft) {
|
|
249
|
+
this.advanceBy(1);
|
|
250
|
+
while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
251
|
+
}
|
|
252
|
+
this.mode = "action";
|
|
253
|
+
if (this.src.startsWith(COMMENT_OPEN, this.offset)) return this.readComment(start, trimLeft);
|
|
254
|
+
return this.makeToken("LeftDelim", trimLeft ? "{{-" : "{{", start, trimLeft ? { trimLeft: true } : {});
|
|
255
|
+
}
|
|
256
|
+
readComment(startDelim, trimLeft) {
|
|
257
|
+
this.advanceBy(2);
|
|
258
|
+
const bodyStart = this.offset;
|
|
259
|
+
const closeIdx = this.src.indexOf(COMMENT_CLOSE, this.offset);
|
|
260
|
+
if (closeIdx === -1) throw this.err("unclosed comment", startDelim, {
|
|
261
|
+
expected: "*/}}",
|
|
262
|
+
found: "end of input"
|
|
263
|
+
});
|
|
264
|
+
this.advanceTo(closeIdx);
|
|
265
|
+
const body = this.src.slice(bodyStart, closeIdx).trim();
|
|
266
|
+
this.advanceBy(2);
|
|
267
|
+
while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
268
|
+
let trimRight = false;
|
|
269
|
+
if (this.src[this.offset] === "-") {
|
|
270
|
+
trimRight = true;
|
|
271
|
+
this.advanceBy(1);
|
|
272
|
+
}
|
|
273
|
+
if (!this.src.startsWith(RIGHT_DELIM, this.offset)) throw this.err("expected `}}` to close comment", this.pos(), {
|
|
274
|
+
expected: "}}",
|
|
275
|
+
found: this.src[this.offset] ?? "end of input"
|
|
276
|
+
});
|
|
277
|
+
this.advanceBy(2);
|
|
278
|
+
if (trimRight) while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
279
|
+
this.mode = "text";
|
|
280
|
+
return this.makeToken("Comment", body, startDelim, {
|
|
281
|
+
...trimLeft ? { trimLeft: true } : {},
|
|
282
|
+
...trimRight ? { trimRight: true } : {}
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
readAction() {
|
|
286
|
+
this.skipActionSpaces();
|
|
287
|
+
if (this.src.startsWith(RIGHT_DELIM, this.offset)) {
|
|
288
|
+
const start = this.pos();
|
|
289
|
+
this.advanceBy(2);
|
|
290
|
+
this.mode = "text";
|
|
291
|
+
return this.makeToken("RightDelim", "}}", start);
|
|
292
|
+
}
|
|
293
|
+
if (this.src.startsWith("-}}", this.offset)) {
|
|
294
|
+
const start = this.pos();
|
|
295
|
+
this.advanceBy(3);
|
|
296
|
+
this.mode = "text";
|
|
297
|
+
while (isSpace(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
298
|
+
return this.makeToken("RightDelim", "-}}", start, { trimRight: true });
|
|
299
|
+
}
|
|
300
|
+
if (this.offset >= this.src.length) throw this.err("unclosed action", this.pos(), {
|
|
301
|
+
expected: "}}",
|
|
302
|
+
found: "end of input"
|
|
303
|
+
});
|
|
304
|
+
const ch = this.src[this.offset];
|
|
305
|
+
const start = this.pos();
|
|
306
|
+
switch (ch) {
|
|
307
|
+
case "(":
|
|
308
|
+
this.advanceBy(1);
|
|
309
|
+
return this.makeToken("LeftParen", "(", start);
|
|
310
|
+
case ")":
|
|
311
|
+
this.advanceBy(1);
|
|
312
|
+
return this.makeToken("RightParen", ")", start);
|
|
313
|
+
case "|":
|
|
314
|
+
this.advanceBy(1);
|
|
315
|
+
return this.makeToken("Pipe", "|", start);
|
|
316
|
+
case ",":
|
|
317
|
+
this.advanceBy(1);
|
|
318
|
+
return this.makeToken("Comma", ",", start);
|
|
319
|
+
case ":":
|
|
320
|
+
if (this.src[this.offset + 1] === "=") {
|
|
321
|
+
this.advanceBy(2);
|
|
322
|
+
return this.makeToken("Declare", ":=", start);
|
|
323
|
+
}
|
|
324
|
+
throw this.err("expected `:=`", start, {
|
|
325
|
+
expected: ":=",
|
|
326
|
+
found: ":"
|
|
327
|
+
});
|
|
328
|
+
case "=":
|
|
329
|
+
this.advanceBy(1);
|
|
330
|
+
return this.makeToken("Assign", "=", start);
|
|
331
|
+
case "\"": return this.readQuotedString(start);
|
|
332
|
+
case "`": return this.readRawString(start);
|
|
333
|
+
case "'": return this.readChar(start);
|
|
334
|
+
}
|
|
335
|
+
if (ch === "$") return this.readVariable(start);
|
|
336
|
+
if (ch !== void 0 && (isDigit(ch) || isSign(ch) && isDigit(this.src[this.offset + 1] ?? "") || ch === "." && isDigit(this.src[this.offset + 1] ?? ""))) return this.readNumber(start);
|
|
337
|
+
if (ch === ".") return this.readDotOrField(start);
|
|
338
|
+
if (ch !== void 0 && isIdentStart(ch)) return this.readIdentifier(start);
|
|
339
|
+
throw this.err(`unexpected character ${JSON.stringify(ch)}`, start, { found: ch ?? "end of input" });
|
|
340
|
+
}
|
|
341
|
+
readQuotedString(start) {
|
|
342
|
+
const startOffset = this.offset;
|
|
343
|
+
this.advanceBy(1);
|
|
344
|
+
while (this.offset < this.src.length) {
|
|
345
|
+
const c = this.src[this.offset];
|
|
346
|
+
if (c === "\\") {
|
|
347
|
+
this.advanceBy(1);
|
|
348
|
+
if (this.offset < this.src.length) this.advanceBy(1);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (c === "\n") throw this.err("newline in interpreted string", start, { found: "\\n" });
|
|
352
|
+
if (c === "\"") {
|
|
353
|
+
this.advanceBy(1);
|
|
354
|
+
return this.makeToken("String", this.src.slice(startOffset, this.offset), start);
|
|
355
|
+
}
|
|
356
|
+
this.advanceBy(1);
|
|
357
|
+
}
|
|
358
|
+
throw this.err("unterminated string literal", start, {
|
|
359
|
+
expected: "\"",
|
|
360
|
+
found: "end of input"
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
readRawString(start) {
|
|
364
|
+
const startOffset = this.offset;
|
|
365
|
+
this.advanceBy(1);
|
|
366
|
+
while (this.offset < this.src.length) {
|
|
367
|
+
if (this.src[this.offset] === "`") {
|
|
368
|
+
this.advanceBy(1);
|
|
369
|
+
return this.makeToken("String", this.src.slice(startOffset, this.offset), start);
|
|
370
|
+
}
|
|
371
|
+
this.advanceBy(1);
|
|
372
|
+
}
|
|
373
|
+
throw this.err("unterminated raw string literal", start, {
|
|
374
|
+
expected: "`",
|
|
375
|
+
found: "end of input"
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
readChar(start) {
|
|
379
|
+
const startOffset = this.offset;
|
|
380
|
+
this.advanceBy(1);
|
|
381
|
+
while (this.offset < this.src.length) {
|
|
382
|
+
const c = this.src[this.offset];
|
|
383
|
+
if (c === "\\") {
|
|
384
|
+
this.advanceBy(1);
|
|
385
|
+
if (this.offset < this.src.length) this.advanceBy(1);
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (c === "\n") throw this.err("newline in rune literal", start, { found: "\\n" });
|
|
389
|
+
if (c === "'") {
|
|
390
|
+
this.advanceBy(1);
|
|
391
|
+
return this.makeToken("Char", this.src.slice(startOffset, this.offset), start);
|
|
392
|
+
}
|
|
393
|
+
this.advanceBy(1);
|
|
394
|
+
}
|
|
395
|
+
throw this.err("unterminated rune literal", start, {
|
|
396
|
+
expected: "'",
|
|
397
|
+
found: "end of input"
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
readNumber(start) {
|
|
401
|
+
const startOffset = this.offset;
|
|
402
|
+
if (isSign(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
403
|
+
if (this.src[this.offset] === "0" && this.offset + 1 < this.src.length) {
|
|
404
|
+
const next = this.src[this.offset + 1];
|
|
405
|
+
if (next === "x" || next === "X") {
|
|
406
|
+
this.advanceBy(2);
|
|
407
|
+
while (isHex(this.src[this.offset] ?? "") || this.src[this.offset] === "_") this.advanceBy(1);
|
|
408
|
+
if (this.src[this.offset] === "." || this.src[this.offset] === "p" || this.src[this.offset] === "P") while (this.isHexFloatTail(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
409
|
+
return this.finishNumber(startOffset, start);
|
|
410
|
+
}
|
|
411
|
+
if (next === "o" || next === "O") {
|
|
412
|
+
this.advanceBy(2);
|
|
413
|
+
while (isOctal(this.src[this.offset] ?? "") || this.src[this.offset] === "_") this.advanceBy(1);
|
|
414
|
+
return this.finishNumber(startOffset, start);
|
|
415
|
+
}
|
|
416
|
+
if (next === "b" || next === "B") {
|
|
417
|
+
this.advanceBy(2);
|
|
418
|
+
while (isBinary(this.src[this.offset] ?? "") || this.src[this.offset] === "_") this.advanceBy(1);
|
|
419
|
+
return this.finishNumber(startOffset, start);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
while (isDigit(this.src[this.offset] ?? "") || this.src[this.offset] === "_") this.advanceBy(1);
|
|
423
|
+
if (this.src[this.offset] === ".") {
|
|
424
|
+
this.advanceBy(1);
|
|
425
|
+
while (isDigit(this.src[this.offset] ?? "") || this.src[this.offset] === "_") this.advanceBy(1);
|
|
426
|
+
}
|
|
427
|
+
if (this.src[this.offset] === "e" || this.src[this.offset] === "E") {
|
|
428
|
+
this.advanceBy(1);
|
|
429
|
+
if (isSign(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
430
|
+
while (isDigit(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
431
|
+
}
|
|
432
|
+
if (this.src[this.offset] === "i") this.advanceBy(1);
|
|
433
|
+
return this.finishNumber(startOffset, start);
|
|
434
|
+
}
|
|
435
|
+
isHexFloatTail(c) {
|
|
436
|
+
return isHex(c) || c === "." || c === "p" || c === "P" || c === "+" || c === "-" || c === "_";
|
|
437
|
+
}
|
|
438
|
+
finishNumber(startOffset, start) {
|
|
439
|
+
if (this.offset === startOffset) throw this.err("expected number", start, { expected: "digit" });
|
|
440
|
+
return this.makeToken("Number", this.src.slice(startOffset, this.offset), start);
|
|
441
|
+
}
|
|
442
|
+
readVariable(start) {
|
|
443
|
+
const startOffset = this.offset;
|
|
444
|
+
this.advanceBy(1);
|
|
445
|
+
while (isIdentPart(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
446
|
+
while (this.src[this.offset] === "." && isIdentStart(this.src[this.offset + 1] ?? "")) {
|
|
447
|
+
this.advanceBy(1);
|
|
448
|
+
while (isIdentPart(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
449
|
+
}
|
|
450
|
+
return this.makeToken("Variable", this.src.slice(startOffset, this.offset), start);
|
|
451
|
+
}
|
|
452
|
+
readDotOrField(start) {
|
|
453
|
+
const startOffset = this.offset;
|
|
454
|
+
this.advanceBy(1);
|
|
455
|
+
if (!isIdentStart(this.src[this.offset] ?? "")) return this.makeToken("Dot", ".", start);
|
|
456
|
+
while (isIdentPart(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
457
|
+
while (this.src[this.offset] === "." && isIdentStart(this.src[this.offset + 1] ?? "")) {
|
|
458
|
+
this.advanceBy(1);
|
|
459
|
+
while (isIdentPart(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
460
|
+
}
|
|
461
|
+
return this.makeToken("Field", this.src.slice(startOffset, this.offset), start);
|
|
462
|
+
}
|
|
463
|
+
readIdentifier(start) {
|
|
464
|
+
const startOffset = this.offset;
|
|
465
|
+
while (isIdentPart(this.src[this.offset] ?? "")) this.advanceBy(1);
|
|
466
|
+
const text = this.src.slice(startOffset, this.offset);
|
|
467
|
+
const kw = KEYWORDS.get(text);
|
|
468
|
+
if (kw) return this.makeToken(kw, text, start);
|
|
469
|
+
return this.makeToken("Identifier", text, start);
|
|
470
|
+
}
|
|
471
|
+
skipActionSpaces() {
|
|
472
|
+
while (this.offset < this.src.length) {
|
|
473
|
+
const c = this.src[this.offset];
|
|
474
|
+
if (c === " " || c === " " || c === "\r" || c === "\n") this.advanceBy(1);
|
|
475
|
+
else return;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
advanceBy(n) {
|
|
479
|
+
for (let i = 0; i < n; i++) {
|
|
480
|
+
const c = this.src[this.offset];
|
|
481
|
+
this.offset += 1;
|
|
482
|
+
if (c === "\n") {
|
|
483
|
+
this.line += 1;
|
|
484
|
+
this.column = 1;
|
|
485
|
+
} else this.column += 1;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
advanceTo(target) {
|
|
489
|
+
while (this.offset < target) this.advanceBy(1);
|
|
490
|
+
}
|
|
491
|
+
makeToken(type, value, pos, extra = {}) {
|
|
492
|
+
return Object.freeze({
|
|
493
|
+
type,
|
|
494
|
+
value,
|
|
495
|
+
pos,
|
|
496
|
+
...extra.trimLeft !== void 0 ? { trimLeft: extra.trimLeft } : {},
|
|
497
|
+
...extra.trimRight !== void 0 ? { trimRight: extra.trimRight } : {}
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
function isSpace(c) {
|
|
502
|
+
return c === " " || c === " " || c === "\r" || c === "\n";
|
|
503
|
+
}
|
|
504
|
+
function isSign(c) {
|
|
505
|
+
return c === "+" || c === "-";
|
|
506
|
+
}
|
|
507
|
+
function isDigit(c) {
|
|
508
|
+
return c >= "0" && c <= "9";
|
|
509
|
+
}
|
|
510
|
+
function isHex(c) {
|
|
511
|
+
return isDigit(c) || c >= "a" && c <= "f" || c >= "A" && c <= "F";
|
|
512
|
+
}
|
|
513
|
+
function isOctal(c) {
|
|
514
|
+
return c >= "0" && c <= "7";
|
|
515
|
+
}
|
|
516
|
+
function isBinary(c) {
|
|
517
|
+
return c === "0" || c === "1";
|
|
518
|
+
}
|
|
519
|
+
function isLetter(c) {
|
|
520
|
+
return c >= "a" && c <= "z" || c >= "A" && c <= "Z";
|
|
521
|
+
}
|
|
522
|
+
function isIdentStart(c) {
|
|
523
|
+
return isLetter(c) || c === "_";
|
|
524
|
+
}
|
|
525
|
+
function isIdentPart(c) {
|
|
526
|
+
return isIdentStart(c) || isDigit(c);
|
|
527
|
+
}
|
|
528
|
+
//#endregion
|
|
529
|
+
//#region src/parser/parser.ts
|
|
530
|
+
function parse(source) {
|
|
531
|
+
return new Parser(source).parseTemplate();
|
|
532
|
+
}
|
|
533
|
+
var Parser = class {
|
|
534
|
+
lex;
|
|
535
|
+
buf = [];
|
|
536
|
+
defines = /* @__PURE__ */ new Map();
|
|
537
|
+
source;
|
|
538
|
+
constructor(source) {
|
|
539
|
+
this.source = source;
|
|
540
|
+
this.lex = new Lexer(source);
|
|
541
|
+
}
|
|
542
|
+
peek(n = 0) {
|
|
543
|
+
while (this.buf.length <= n) this.buf.push(this.lex.next());
|
|
544
|
+
return this.buf[n];
|
|
545
|
+
}
|
|
546
|
+
next() {
|
|
547
|
+
if (this.buf.length > 0) return this.buf.shift();
|
|
548
|
+
return this.lex.next();
|
|
549
|
+
}
|
|
550
|
+
expect(type, what) {
|
|
551
|
+
const t = this.next();
|
|
552
|
+
if (t.type !== type) throw this.errAt(t, `expected ${what}`, {
|
|
553
|
+
expected: what,
|
|
554
|
+
found: tokenLabel(t)
|
|
555
|
+
});
|
|
556
|
+
return t;
|
|
557
|
+
}
|
|
558
|
+
errAt(t, message, extra = {}) {
|
|
559
|
+
return new ParseError(message, t.pos, {
|
|
560
|
+
...extra,
|
|
561
|
+
source: this.source
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
parseTemplate() {
|
|
565
|
+
const root = this.parseList();
|
|
566
|
+
if (this.peek().type !== "EOF") {
|
|
567
|
+
const left = this.peek();
|
|
568
|
+
const inside = this.peek(1);
|
|
569
|
+
if (left.type === "LeftDelim" && (inside.type === "Else" || inside.type === "End")) {
|
|
570
|
+
const keyword = inside.type === "Else" ? "else" : "end";
|
|
571
|
+
throw this.errAt(left, `unexpected \`{{${keyword}}}\` outside of \`if\`, \`range\`, \`with\`, or \`block\``, { found: `{{${keyword}}}` });
|
|
572
|
+
}
|
|
573
|
+
throw this.errAt(left, `unexpected ${tokenLabel(left)}`, { found: tokenLabel(left) });
|
|
574
|
+
}
|
|
575
|
+
return {
|
|
576
|
+
root,
|
|
577
|
+
defines: this.defines,
|
|
578
|
+
source: this.source
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
parseList() {
|
|
582
|
+
const startPos = this.peek().pos;
|
|
583
|
+
const nodes = [];
|
|
584
|
+
while (true) {
|
|
585
|
+
const t = this.peek();
|
|
586
|
+
if (t.type === "EOF") break;
|
|
587
|
+
if (t.type === "Text") {
|
|
588
|
+
this.next();
|
|
589
|
+
nodes.push({
|
|
590
|
+
type: "Text",
|
|
591
|
+
pos: t.pos,
|
|
592
|
+
text: t.value
|
|
593
|
+
});
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
if (t.type === "Comment") {
|
|
597
|
+
this.next();
|
|
598
|
+
const trim = trimFromToken(t);
|
|
599
|
+
nodes.push({
|
|
600
|
+
type: "Comment",
|
|
601
|
+
pos: t.pos,
|
|
602
|
+
text: t.value,
|
|
603
|
+
trim
|
|
604
|
+
});
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
if (t.type === "LeftDelim") {
|
|
608
|
+
const inside = this.peek(1).type;
|
|
609
|
+
if (inside === "Else" || inside === "End") return finishList(startPos, nodes);
|
|
610
|
+
const action = this.parseAction();
|
|
611
|
+
if (action !== null) nodes.push(action);
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
throw this.errAt(t, `unexpected ${tokenLabel(t)} at top level`, { found: tokenLabel(t) });
|
|
615
|
+
}
|
|
616
|
+
return finishList(startPos, nodes);
|
|
617
|
+
}
|
|
618
|
+
parseAction() {
|
|
619
|
+
const left = this.expect("LeftDelim", "`{{`");
|
|
620
|
+
const trimLeft = left.trimLeft === true;
|
|
621
|
+
const head = this.peek();
|
|
622
|
+
switch (head.type) {
|
|
623
|
+
case "If":
|
|
624
|
+
this.next();
|
|
625
|
+
return this.parseBranch("If", left.pos, trimLeft);
|
|
626
|
+
case "Range":
|
|
627
|
+
this.next();
|
|
628
|
+
return this.parseBranch("Range", left.pos, trimLeft);
|
|
629
|
+
case "With":
|
|
630
|
+
this.next();
|
|
631
|
+
return this.parseBranch("With", left.pos, trimLeft);
|
|
632
|
+
case "Template":
|
|
633
|
+
this.next();
|
|
634
|
+
return this.parseTemplateInvocation(left.pos, trimLeft);
|
|
635
|
+
case "Block":
|
|
636
|
+
this.next();
|
|
637
|
+
return this.parseBlock(left.pos, trimLeft);
|
|
638
|
+
case "Define":
|
|
639
|
+
this.next();
|
|
640
|
+
this.parseDefine(left.pos, trimLeft);
|
|
641
|
+
return null;
|
|
642
|
+
case "RightDelim": throw this.errAt(head, "empty action", { expected: "pipeline" });
|
|
643
|
+
default: {
|
|
644
|
+
const pipe = this.parsePipeline();
|
|
645
|
+
const right = this.expect("RightDelim", "`}}`");
|
|
646
|
+
return {
|
|
647
|
+
type: "Action",
|
|
648
|
+
pos: left.pos,
|
|
649
|
+
pipe,
|
|
650
|
+
trim: {
|
|
651
|
+
trimLeft,
|
|
652
|
+
trimRight: right.trimRight === true
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
parseBranch(kind, startPos, trimLeft) {
|
|
659
|
+
const pipe = this.parsePipeline();
|
|
660
|
+
this.expect("RightDelim", "`}}`");
|
|
661
|
+
const list = this.parseList();
|
|
662
|
+
const elsePart = this.parseElsePart();
|
|
663
|
+
const trim = {
|
|
664
|
+
trimLeft,
|
|
665
|
+
trimRight: elsePart.endConsumed ? elsePart.endRight : this.consumeEnd()
|
|
666
|
+
};
|
|
667
|
+
const base = elsePart.list ? {
|
|
668
|
+
pipe,
|
|
669
|
+
list,
|
|
670
|
+
elseList: elsePart.list,
|
|
671
|
+
trim
|
|
672
|
+
} : {
|
|
673
|
+
pipe,
|
|
674
|
+
list,
|
|
675
|
+
trim
|
|
676
|
+
};
|
|
677
|
+
switch (kind) {
|
|
678
|
+
case "If": return {
|
|
679
|
+
type: "If",
|
|
680
|
+
pos: startPos,
|
|
681
|
+
...base
|
|
682
|
+
};
|
|
683
|
+
case "Range": return {
|
|
684
|
+
type: "Range",
|
|
685
|
+
pos: startPos,
|
|
686
|
+
...base
|
|
687
|
+
};
|
|
688
|
+
case "With": return {
|
|
689
|
+
type: "With",
|
|
690
|
+
pos: startPos,
|
|
691
|
+
...base
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Parse the `{{else}}` / `{{else if PIPE}}` segment, if any.
|
|
697
|
+
*
|
|
698
|
+
* `else if` is desugared into a nested IfNode wrapped in the elseList.
|
|
699
|
+
* The recursive parseBranch consumes the chain's single closing
|
|
700
|
+
* `{{end}}`, so the outer caller must NOT consume another — hence the
|
|
701
|
+
* `endConsumed` flag we propagate back.
|
|
702
|
+
*/
|
|
703
|
+
parseElsePart() {
|
|
704
|
+
if (this.peek().type !== "LeftDelim" || this.peek(1).type !== "Else") return {
|
|
705
|
+
list: void 0,
|
|
706
|
+
endRight: false,
|
|
707
|
+
endConsumed: false
|
|
708
|
+
};
|
|
709
|
+
const left = this.next();
|
|
710
|
+
this.next();
|
|
711
|
+
if (this.peek().type === "If") {
|
|
712
|
+
this.next();
|
|
713
|
+
const innerIf = this.parseBranch("If", left.pos, left.trimLeft === true);
|
|
714
|
+
return {
|
|
715
|
+
list: {
|
|
716
|
+
type: "List",
|
|
717
|
+
pos: left.pos,
|
|
718
|
+
nodes: [innerIf]
|
|
719
|
+
},
|
|
720
|
+
endRight: innerIf.trim.trimRight,
|
|
721
|
+
endConsumed: true
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
this.expect("RightDelim", "`}}`");
|
|
725
|
+
return {
|
|
726
|
+
list: this.parseList(),
|
|
727
|
+
endRight: false,
|
|
728
|
+
endConsumed: false
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
/** Consume the closing `{{end}}` and return whether it was a `-}}`. */
|
|
732
|
+
consumeEnd() {
|
|
733
|
+
this.expect("LeftDelim", "`{{end}}`");
|
|
734
|
+
this.expect("End", "`end`");
|
|
735
|
+
return this.expect("RightDelim", "`}}`").trimRight === true;
|
|
736
|
+
}
|
|
737
|
+
parseTemplateInvocation(startPos, trimLeft) {
|
|
738
|
+
const name = this.parseQuotedName();
|
|
739
|
+
const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline();
|
|
740
|
+
const trim = {
|
|
741
|
+
trimLeft,
|
|
742
|
+
trimRight: this.expect("RightDelim", "`}}`").trimRight === true
|
|
743
|
+
};
|
|
744
|
+
return pipe ? {
|
|
745
|
+
type: "Template",
|
|
746
|
+
pos: startPos,
|
|
747
|
+
name,
|
|
748
|
+
pipe,
|
|
749
|
+
trim
|
|
750
|
+
} : {
|
|
751
|
+
type: "Template",
|
|
752
|
+
pos: startPos,
|
|
753
|
+
name,
|
|
754
|
+
trim
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
parseBlock(startPos, trimLeft) {
|
|
758
|
+
const name = this.parseQuotedName();
|
|
759
|
+
const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline();
|
|
760
|
+
this.expect("RightDelim", "`}}`");
|
|
761
|
+
const list = this.parseList();
|
|
762
|
+
const trim = {
|
|
763
|
+
trimLeft,
|
|
764
|
+
trimRight: this.consumeEnd()
|
|
765
|
+
};
|
|
766
|
+
if (!this.defines.has(name)) this.defines.set(name, list);
|
|
767
|
+
return pipe ? {
|
|
768
|
+
type: "Block",
|
|
769
|
+
pos: startPos,
|
|
770
|
+
name,
|
|
771
|
+
pipe,
|
|
772
|
+
list,
|
|
773
|
+
trim
|
|
774
|
+
} : {
|
|
775
|
+
type: "Block",
|
|
776
|
+
pos: startPos,
|
|
777
|
+
name,
|
|
778
|
+
list,
|
|
779
|
+
trim
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
parseDefine(_startPos, _trimLeft) {
|
|
783
|
+
const name = this.parseQuotedName();
|
|
784
|
+
this.expect("RightDelim", "`}}`");
|
|
785
|
+
const list = this.parseList();
|
|
786
|
+
this.consumeEnd();
|
|
787
|
+
if (this.defines.has(name)) throw new ParseError(`redefinition of template ${JSON.stringify(name)}`, list.pos, { source: this.source });
|
|
788
|
+
this.defines.set(name, list);
|
|
789
|
+
}
|
|
790
|
+
parseQuotedName() {
|
|
791
|
+
const t = this.next();
|
|
792
|
+
if (t.type !== "String") throw this.errAt(t, "expected template name (quoted string)", {
|
|
793
|
+
expected: "string",
|
|
794
|
+
found: tokenLabel(t)
|
|
795
|
+
});
|
|
796
|
+
return decodeStringLiteral(t.value, t.pos, this.source);
|
|
797
|
+
}
|
|
798
|
+
parsePipeline() {
|
|
799
|
+
const startPos = this.peek().pos;
|
|
800
|
+
const decls = this.tryParseDecls();
|
|
801
|
+
const cmds = [this.parseCommand()];
|
|
802
|
+
while (this.peek().type === "Pipe") {
|
|
803
|
+
this.next();
|
|
804
|
+
const next = this.peek();
|
|
805
|
+
if (!canStartPrimary(next.type)) throw this.errAt(next, "missing command after `|`", {
|
|
806
|
+
expected: "command",
|
|
807
|
+
found: tokenLabel(next)
|
|
808
|
+
});
|
|
809
|
+
cmds.push(this.parseCommand());
|
|
810
|
+
}
|
|
811
|
+
return {
|
|
812
|
+
type: "Pipe",
|
|
813
|
+
pos: startPos,
|
|
814
|
+
decls: decls?.vars ?? [],
|
|
815
|
+
isAssign: decls?.isAssign ?? false,
|
|
816
|
+
cmds
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
tryParseDecls() {
|
|
820
|
+
if (this.peek().type !== "Variable") return void 0;
|
|
821
|
+
let n = 1;
|
|
822
|
+
while (this.peek(n).type === "Comma") {
|
|
823
|
+
if (this.peek(n + 1).type !== "Variable") return void 0;
|
|
824
|
+
n += 2;
|
|
825
|
+
}
|
|
826
|
+
const opType = this.peek(n).type;
|
|
827
|
+
if (opType !== "Declare" && opType !== "Assign") return void 0;
|
|
828
|
+
const vars = [varFromToken(this.next())];
|
|
829
|
+
while (this.peek().type === "Comma") {
|
|
830
|
+
this.next();
|
|
831
|
+
vars.push(varFromToken(this.expect("Variable", "$variable")));
|
|
832
|
+
}
|
|
833
|
+
return {
|
|
834
|
+
vars,
|
|
835
|
+
isAssign: this.next().type === "Assign"
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
parseCommand() {
|
|
839
|
+
const startPos = this.peek().pos;
|
|
840
|
+
const args = [this.parsePrimary()];
|
|
841
|
+
while (canStartPrimary(this.peek().type)) args.push(this.parsePrimary());
|
|
842
|
+
return {
|
|
843
|
+
type: "Command",
|
|
844
|
+
pos: startPos,
|
|
845
|
+
args
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
parsePrimary() {
|
|
849
|
+
const t = this.next();
|
|
850
|
+
switch (t.type) {
|
|
851
|
+
case "Dot": return {
|
|
852
|
+
type: "Dot",
|
|
853
|
+
pos: t.pos
|
|
854
|
+
};
|
|
855
|
+
case "Field": return {
|
|
856
|
+
type: "Field",
|
|
857
|
+
pos: t.pos,
|
|
858
|
+
idents: t.value.slice(1).split(".")
|
|
859
|
+
};
|
|
860
|
+
case "Variable": return varFromToken(t);
|
|
861
|
+
case "Identifier": return {
|
|
862
|
+
type: "Identifier",
|
|
863
|
+
pos: t.pos,
|
|
864
|
+
ident: t.value
|
|
865
|
+
};
|
|
866
|
+
case "String": return {
|
|
867
|
+
type: "String",
|
|
868
|
+
pos: t.pos,
|
|
869
|
+
raw: t.value,
|
|
870
|
+
value: decodeStringLiteral(t.value, t.pos, this.source)
|
|
871
|
+
};
|
|
872
|
+
case "Number": return numberFromToken(t);
|
|
873
|
+
case "Char": return runeNumberFromToken(t, this.source);
|
|
874
|
+
case "Bool": return {
|
|
875
|
+
type: "Bool",
|
|
876
|
+
pos: t.pos,
|
|
877
|
+
value: t.value === "true"
|
|
878
|
+
};
|
|
879
|
+
case "Nil": return {
|
|
880
|
+
type: "Nil",
|
|
881
|
+
pos: t.pos
|
|
882
|
+
};
|
|
883
|
+
case "LeftParen": return this.parseChainOrPipe(t.pos);
|
|
884
|
+
default: throw this.errAt(t, `expected command argument, found ${tokenLabel(t)}`, {
|
|
885
|
+
expected: "command argument",
|
|
886
|
+
found: tokenLabel(t)
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
parseChainOrPipe(startPos) {
|
|
891
|
+
const inner = this.parsePipeline();
|
|
892
|
+
const rparen = this.expect("RightParen", "`)`");
|
|
893
|
+
const fields = [];
|
|
894
|
+
const expectedNextOffset = rparen.pos.offset + 1;
|
|
895
|
+
const t = this.peek();
|
|
896
|
+
if (t.type === "Field" && t.pos.offset === expectedNextOffset) {
|
|
897
|
+
this.next();
|
|
898
|
+
fields.push(...t.value.slice(1).split("."));
|
|
899
|
+
}
|
|
900
|
+
if (fields.length === 0) return inner;
|
|
901
|
+
return {
|
|
902
|
+
type: "Chain",
|
|
903
|
+
pos: startPos,
|
|
904
|
+
node: inner,
|
|
905
|
+
fields
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
function finishList(pos, nodes) {
|
|
910
|
+
return {
|
|
911
|
+
type: "List",
|
|
912
|
+
pos,
|
|
913
|
+
nodes
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
function trimFromToken(t) {
|
|
917
|
+
return {
|
|
918
|
+
trimLeft: t.trimLeft === true,
|
|
919
|
+
trimRight: t.trimRight === true
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
function tokenLabel(t) {
|
|
923
|
+
if (t.type === "EOF") return "end of input";
|
|
924
|
+
return t.value || t.type;
|
|
925
|
+
}
|
|
926
|
+
function canStartPrimary(t) {
|
|
927
|
+
switch (t) {
|
|
928
|
+
case "Dot":
|
|
929
|
+
case "Field":
|
|
930
|
+
case "Variable":
|
|
931
|
+
case "Identifier":
|
|
932
|
+
case "String":
|
|
933
|
+
case "Number":
|
|
934
|
+
case "Char":
|
|
935
|
+
case "Bool":
|
|
936
|
+
case "Nil":
|
|
937
|
+
case "LeftParen": return true;
|
|
938
|
+
default: return false;
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function varFromToken(t) {
|
|
942
|
+
return {
|
|
943
|
+
type: "Variable",
|
|
944
|
+
pos: t.pos,
|
|
945
|
+
idents: splitVariableIdents(t.value)
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
function splitVariableIdents(value) {
|
|
949
|
+
const dotIdx = value.indexOf(".");
|
|
950
|
+
if (dotIdx === -1) return [value];
|
|
951
|
+
return [value.slice(0, dotIdx), ...value.slice(dotIdx + 1).split(".")];
|
|
952
|
+
}
|
|
953
|
+
function numberFromToken(t) {
|
|
954
|
+
const text = t.value;
|
|
955
|
+
const cleaned = text.replace(/_/g, "");
|
|
956
|
+
const isComplex = cleaned.toLowerCase().endsWith("i");
|
|
957
|
+
const body = isComplex ? cleaned.slice(0, -1) : cleaned;
|
|
958
|
+
const isFloat = !isComplex && (body.includes(".") || !body.startsWith("0x") && !body.startsWith("0X") && /[eE]/.test(body) || (body.startsWith("0x") || body.startsWith("0X")) && /[pP]/.test(body));
|
|
959
|
+
const isInt = !isComplex && !isFloat;
|
|
960
|
+
const base = {
|
|
961
|
+
type: "Number",
|
|
962
|
+
pos: t.pos,
|
|
963
|
+
text,
|
|
964
|
+
isInt,
|
|
965
|
+
isUint: false,
|
|
966
|
+
isFloat,
|
|
967
|
+
isComplex
|
|
968
|
+
};
|
|
969
|
+
if (isInt) {
|
|
970
|
+
const intValue = parseIntegerLiteral(body);
|
|
971
|
+
return {
|
|
972
|
+
...base,
|
|
973
|
+
intValue
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
if (isFloat) {
|
|
977
|
+
const floatValue = parseFloatLiteral(body);
|
|
978
|
+
return {
|
|
979
|
+
...base,
|
|
980
|
+
floatValue
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
const im = parseFloatLiteral(body);
|
|
984
|
+
return {
|
|
985
|
+
...base,
|
|
986
|
+
complexValue: [0, im]
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
function runeNumberFromToken(t, source) {
|
|
990
|
+
const inner = decodeRuneLiteral(t.value, t.pos, source);
|
|
991
|
+
return {
|
|
992
|
+
type: "Number",
|
|
993
|
+
pos: t.pos,
|
|
994
|
+
text: t.value,
|
|
995
|
+
isInt: true,
|
|
996
|
+
isUint: false,
|
|
997
|
+
isFloat: false,
|
|
998
|
+
isComplex: false,
|
|
999
|
+
intValue: BigInt(inner)
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
function parseIntegerLiteral(text) {
|
|
1003
|
+
let sign = 1n;
|
|
1004
|
+
let body = text;
|
|
1005
|
+
if (body.startsWith("+")) body = body.slice(1);
|
|
1006
|
+
else if (body.startsWith("-")) {
|
|
1007
|
+
sign = -1n;
|
|
1008
|
+
body = body.slice(1);
|
|
1009
|
+
}
|
|
1010
|
+
return sign * BigInt(body);
|
|
1011
|
+
}
|
|
1012
|
+
function parseFloatLiteral(text) {
|
|
1013
|
+
return Number(text);
|
|
1014
|
+
}
|
|
1015
|
+
function decodeStringLiteral(raw, pos, source) {
|
|
1016
|
+
if (raw.startsWith("`")) return raw.slice(1, -1);
|
|
1017
|
+
let out = "";
|
|
1018
|
+
for (let i = 1; i < raw.length - 1; i++) {
|
|
1019
|
+
const c = raw[i];
|
|
1020
|
+
if (c !== "\\") {
|
|
1021
|
+
out += c;
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
const next = raw[++i];
|
|
1025
|
+
switch (next) {
|
|
1026
|
+
case "n":
|
|
1027
|
+
out += "\n";
|
|
1028
|
+
break;
|
|
1029
|
+
case "t":
|
|
1030
|
+
out += " ";
|
|
1031
|
+
break;
|
|
1032
|
+
case "r":
|
|
1033
|
+
out += "\r";
|
|
1034
|
+
break;
|
|
1035
|
+
case "\\":
|
|
1036
|
+
out += "\\";
|
|
1037
|
+
break;
|
|
1038
|
+
case "\"":
|
|
1039
|
+
out += "\"";
|
|
1040
|
+
break;
|
|
1041
|
+
case "'":
|
|
1042
|
+
out += "'";
|
|
1043
|
+
break;
|
|
1044
|
+
case "a":
|
|
1045
|
+
out += "\x07";
|
|
1046
|
+
break;
|
|
1047
|
+
case "b":
|
|
1048
|
+
out += "\b";
|
|
1049
|
+
break;
|
|
1050
|
+
case "f":
|
|
1051
|
+
out += "\f";
|
|
1052
|
+
break;
|
|
1053
|
+
case "v":
|
|
1054
|
+
out += "\v";
|
|
1055
|
+
break;
|
|
1056
|
+
case "0":
|
|
1057
|
+
case "1":
|
|
1058
|
+
case "2":
|
|
1059
|
+
case "3":
|
|
1060
|
+
case "4":
|
|
1061
|
+
case "5":
|
|
1062
|
+
case "6":
|
|
1063
|
+
case "7": {
|
|
1064
|
+
const digits = next + (raw[i + 1] ?? "") + (raw[i + 2] ?? "");
|
|
1065
|
+
i += 2;
|
|
1066
|
+
out += String.fromCodePoint(Number.parseInt(digits, 8));
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
case "x": {
|
|
1070
|
+
const digits = (raw[i + 1] ?? "") + (raw[i + 2] ?? "");
|
|
1071
|
+
i += 2;
|
|
1072
|
+
out += String.fromCodePoint(Number.parseInt(digits, 16));
|
|
1073
|
+
break;
|
|
1074
|
+
}
|
|
1075
|
+
case "u": {
|
|
1076
|
+
const digits = raw.slice(i + 1, i + 5);
|
|
1077
|
+
i += 4;
|
|
1078
|
+
out += String.fromCodePoint(Number.parseInt(digits, 16));
|
|
1079
|
+
break;
|
|
1080
|
+
}
|
|
1081
|
+
case "U": {
|
|
1082
|
+
const digits = raw.slice(i + 1, i + 9);
|
|
1083
|
+
i += 8;
|
|
1084
|
+
out += String.fromCodePoint(Number.parseInt(digits, 16));
|
|
1085
|
+
break;
|
|
1086
|
+
}
|
|
1087
|
+
default: throw new ParseError(`bad escape sequence \\${next}`, pos, {
|
|
1088
|
+
expected: "valid escape sequence",
|
|
1089
|
+
found: `\\${next}`,
|
|
1090
|
+
source
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return out;
|
|
1095
|
+
}
|
|
1096
|
+
function decodeRuneLiteral(raw, pos, source) {
|
|
1097
|
+
const decoded = decodeStringLiteral(`"${raw.slice(1, -1).replace(/"/g, "\\\"")}"`, pos, source);
|
|
1098
|
+
if (decoded.length === 0) throw new ParseError("empty rune literal", pos, { source });
|
|
1099
|
+
return decoded.codePointAt(0) ?? 0;
|
|
1100
|
+
}
|
|
1101
|
+
//#endregion
|
|
1102
|
+
//#region src/evaluator/access.ts
|
|
1103
|
+
/**
|
|
1104
|
+
* Field / index access for evaluator primaries.
|
|
1105
|
+
*
|
|
1106
|
+
* Mirrors Go's `text/template` semantics where applicable:
|
|
1107
|
+
* - Plain JS objects: own + prototype-chain properties.
|
|
1108
|
+
* - Maps: `.get(key)`.
|
|
1109
|
+
* - Arrays: numeric `[i]` (string-indexed access not supported — that's
|
|
1110
|
+
* Go's behavior for slices/arrays).
|
|
1111
|
+
* - Methods/functions are returned as-is for the caller to invoke when
|
|
1112
|
+
* the AST shape demands a function call.
|
|
1113
|
+
*
|
|
1114
|
+
* Missing-key handling matches Go's `missingkey=error` default: a
|
|
1115
|
+
* genuinely absent field returns `MISSING`, which the caller surfaces as
|
|
1116
|
+
* a `MissingFieldError`. The receiver-is-nullish case at the top of
|
|
1117
|
+
* `getField` is the trust-boundary exception documented inline below.
|
|
1118
|
+
*/
|
|
1119
|
+
/** Sentinel returned by `getField` when a field is genuinely absent. */
|
|
1120
|
+
const MISSING = Symbol("go-template-js.MISSING");
|
|
1121
|
+
function getField(value, name) {
|
|
1122
|
+
if (value === null || value === void 0) return MISSING;
|
|
1123
|
+
if (value instanceof Map) return value.has(name) ? value.get(name) : MISSING;
|
|
1124
|
+
if (Array.isArray(value)) return MISSING;
|
|
1125
|
+
if (typeof value === "object") {
|
|
1126
|
+
const obj = value;
|
|
1127
|
+
if (name in obj) return obj[name];
|
|
1128
|
+
return MISSING;
|
|
1129
|
+
}
|
|
1130
|
+
return MISSING;
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Walk a chain of field names left-to-right. Returns `MISSING` as soon
|
|
1134
|
+
* as any link is missing. The caller decides how to surface the error
|
|
1135
|
+
* (typically via EvalError pointing at the AST node's position).
|
|
1136
|
+
*/
|
|
1137
|
+
function walkFieldChain(value, idents) {
|
|
1138
|
+
let cur = value;
|
|
1139
|
+
for (const id of idents) {
|
|
1140
|
+
if (cur === MISSING) return MISSING;
|
|
1141
|
+
cur = getField(cur, id);
|
|
1142
|
+
}
|
|
1143
|
+
return cur;
|
|
1144
|
+
}
|
|
1145
|
+
//#endregion
|
|
1146
|
+
//#region src/sprig/types/deepEqual.ts
|
|
1147
|
+
/**
|
|
1148
|
+
* `deepEqual a b` — recursive structural equality.
|
|
1149
|
+
*
|
|
1150
|
+
* Mirrors Go sprig's intent. Implementation handles primitives,
|
|
1151
|
+
* arrays, plain objects, Maps, and Sets. NaN is treated as equal to
|
|
1152
|
+
* itself (matches `Object.is`).
|
|
1153
|
+
*/
|
|
1154
|
+
function deepEqual(a, b) {
|
|
1155
|
+
if (Object.is(a, b)) return true;
|
|
1156
|
+
if (a === null || b === null || a === void 0 || b === void 0) return false;
|
|
1157
|
+
if (typeof a !== typeof b) return false;
|
|
1158
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
1159
|
+
if (a.length !== b.length) return false;
|
|
1160
|
+
return a.every((v, i) => deepEqual(v, b[i]));
|
|
1161
|
+
}
|
|
1162
|
+
if (a instanceof Map && b instanceof Map) {
|
|
1163
|
+
if (a.size !== b.size) return false;
|
|
1164
|
+
for (const [k, v] of a) if (!b.has(k) || !deepEqual(v, b.get(k))) return false;
|
|
1165
|
+
return true;
|
|
1166
|
+
}
|
|
1167
|
+
if (a instanceof Set && b instanceof Set) {
|
|
1168
|
+
if (a.size !== b.size) return false;
|
|
1169
|
+
for (const v of a) if (!b.has(v)) return false;
|
|
1170
|
+
return true;
|
|
1171
|
+
}
|
|
1172
|
+
if (typeof a === "object" && typeof b === "object") {
|
|
1173
|
+
const ak = Object.keys(a);
|
|
1174
|
+
const bk = Object.keys(b);
|
|
1175
|
+
if (ak.length !== bk.length) return false;
|
|
1176
|
+
return ak.every((k) => deepEqual(a[k], b[k]));
|
|
1177
|
+
}
|
|
1178
|
+
return false;
|
|
1179
|
+
}
|
|
1180
|
+
//#endregion
|
|
1181
|
+
//#region src/evaluator/lazy.ts
|
|
1182
|
+
const LAZY_FUNCS = /* @__PURE__ */ new WeakSet();
|
|
1183
|
+
/** Mark a func as wanting thunks. Internal — only `defaultBuiltins` calls this. */
|
|
1184
|
+
function markLazy(fn) {
|
|
1185
|
+
LAZY_FUNCS.add(fn);
|
|
1186
|
+
return fn;
|
|
1187
|
+
}
|
|
1188
|
+
/** True iff the func was registered via `markLazy`. */
|
|
1189
|
+
function isLazy(fn) {
|
|
1190
|
+
return LAZY_FUNCS.has(fn);
|
|
1191
|
+
}
|
|
1192
|
+
//#endregion
|
|
1193
|
+
//#region src/evaluator/truthy.ts
|
|
1194
|
+
/**
|
|
1195
|
+
* Go-template truthiness, used by `if`, `with`, and `range`-empty.
|
|
1196
|
+
*
|
|
1197
|
+
* Per https://pkg.go.dev/text/template#hdr-Actions, "the empty values
|
|
1198
|
+
* are false, 0, any nil pointer or interface value, and any array,
|
|
1199
|
+
* slice, map, or string of length zero." Strings of length zero are
|
|
1200
|
+
* also empty.
|
|
1201
|
+
*/
|
|
1202
|
+
function isTruthy(value) {
|
|
1203
|
+
if (value === null || value === void 0) return false;
|
|
1204
|
+
if (value === false) return false;
|
|
1205
|
+
if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
|
|
1206
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
1207
|
+
if (typeof value === "string") return value.length > 0;
|
|
1208
|
+
if (Array.isArray(value)) return value.length > 0;
|
|
1209
|
+
if (value instanceof Map) return value.size > 0;
|
|
1210
|
+
if (value instanceof Set) return value.size > 0;
|
|
1211
|
+
if (typeof value === "object") return Object.keys(value).length > 0;
|
|
1212
|
+
return Boolean(value);
|
|
1213
|
+
}
|
|
1214
|
+
//#endregion
|
|
1215
|
+
//#region src/evaluator/builtins.ts
|
|
1216
|
+
/**
|
|
1217
|
+
* Go template's built-in functions.
|
|
1218
|
+
*
|
|
1219
|
+
* https://pkg.go.dev/text/template#hdr-Functions
|
|
1220
|
+
*
|
|
1221
|
+
* Categories:
|
|
1222
|
+
* - Eager (most): args evaluated normally, value-in / value-out.
|
|
1223
|
+
* - Lazy (and/or): take thunks instead of values so evaluation can
|
|
1224
|
+
* short-circuit. Registered via `markLazy` — see lazy.ts.
|
|
1225
|
+
*
|
|
1226
|
+
* [LAW:single-enforcer] Built-ins live in *one* exported FuncMap.
|
|
1227
|
+
* Consumers merge with their own funcs; user-supplied entries with
|
|
1228
|
+
* matching names override the built-in (intentional — gives
|
|
1229
|
+
* consumers an escape hatch).
|
|
1230
|
+
*/
|
|
1231
|
+
function eagerBuiltins(toString) {
|
|
1232
|
+
return {
|
|
1233
|
+
eq: {
|
|
1234
|
+
fn: (a, ...rest) => rest.some((r) => goEqPair(a, r)),
|
|
1235
|
+
argTypes: ["comparable"]
|
|
1236
|
+
},
|
|
1237
|
+
ne: {
|
|
1238
|
+
fn: (a, b) => !goEqPair(a, b),
|
|
1239
|
+
argTypes: ["comparable", "comparable"]
|
|
1240
|
+
},
|
|
1241
|
+
lt: {
|
|
1242
|
+
fn: (a, b) => compare(a, b) < 0,
|
|
1243
|
+
argTypes: ["ordered", "ordered"]
|
|
1244
|
+
},
|
|
1245
|
+
le: {
|
|
1246
|
+
fn: (a, b) => compare(a, b) <= 0,
|
|
1247
|
+
argTypes: ["ordered", "ordered"]
|
|
1248
|
+
},
|
|
1249
|
+
gt: {
|
|
1250
|
+
fn: (a, b) => compare(a, b) > 0,
|
|
1251
|
+
argTypes: ["ordered", "ordered"]
|
|
1252
|
+
},
|
|
1253
|
+
ge: {
|
|
1254
|
+
fn: (a, b) => compare(a, b) >= 0,
|
|
1255
|
+
argTypes: ["ordered", "ordered"]
|
|
1256
|
+
},
|
|
1257
|
+
len: {
|
|
1258
|
+
fn: (v) => goLen(v),
|
|
1259
|
+
argTypes: ["sized"]
|
|
1260
|
+
},
|
|
1261
|
+
index: {
|
|
1262
|
+
fn: (collection, ...keys) => {
|
|
1263
|
+
let cur = collection;
|
|
1264
|
+
for (const k of keys) cur = goIndex(cur, k);
|
|
1265
|
+
return cur;
|
|
1266
|
+
},
|
|
1267
|
+
argTypes: ["collection", "index-key"]
|
|
1268
|
+
},
|
|
1269
|
+
slice: {
|
|
1270
|
+
fn: (collection, ...indices) => {
|
|
1271
|
+
const i = indices.length >= 1 ? Number(indices[0]) : 0;
|
|
1272
|
+
const j = indices.length >= 2 ? Number(indices[1]) : void 0;
|
|
1273
|
+
return typeof collection === "string" ? collection.slice(i, j) : collection.slice(i, j);
|
|
1274
|
+
},
|
|
1275
|
+
argTypes: ["sliceable", "number"]
|
|
1276
|
+
},
|
|
1277
|
+
print: {
|
|
1278
|
+
fn: (...args) => goPrint(args, toString),
|
|
1279
|
+
argTypes: ["stringifiable"],
|
|
1280
|
+
returnType: "string"
|
|
1281
|
+
},
|
|
1282
|
+
println: {
|
|
1283
|
+
fn: (...args) => `${goPrint(args, toString)}\n`,
|
|
1284
|
+
argTypes: ["stringifiable"],
|
|
1285
|
+
returnType: "string"
|
|
1286
|
+
},
|
|
1287
|
+
printf: {
|
|
1288
|
+
fn: (format, ...args) => sprintf(format, args, toString),
|
|
1289
|
+
argTypes: ["string", "stringifiable"],
|
|
1290
|
+
returnType: "string"
|
|
1291
|
+
},
|
|
1292
|
+
call: {
|
|
1293
|
+
fn: (fn, ...args) => fn(...args),
|
|
1294
|
+
argTypes: ["callable", "value"]
|
|
1295
|
+
},
|
|
1296
|
+
not: {
|
|
1297
|
+
fn: (v) => !isTruthy(v),
|
|
1298
|
+
argTypes: ["truthy"]
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
function lazyBuiltins() {
|
|
1303
|
+
return {
|
|
1304
|
+
and: markLazy({
|
|
1305
|
+
argTypes: ["truthy"],
|
|
1306
|
+
fn: (...thunks) => {
|
|
1307
|
+
let last = true;
|
|
1308
|
+
for (const t of thunks) {
|
|
1309
|
+
last = t();
|
|
1310
|
+
if (!isTruthy(last)) return last;
|
|
1311
|
+
}
|
|
1312
|
+
return last;
|
|
1313
|
+
}
|
|
1314
|
+
}),
|
|
1315
|
+
or: markLazy({
|
|
1316
|
+
argTypes: ["truthy"],
|
|
1317
|
+
fn: (...thunks) => {
|
|
1318
|
+
let last = false;
|
|
1319
|
+
for (const t of thunks) {
|
|
1320
|
+
last = t();
|
|
1321
|
+
if (isTruthy(last)) return last;
|
|
1322
|
+
}
|
|
1323
|
+
return last;
|
|
1324
|
+
}
|
|
1325
|
+
})
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
function defaultBuiltins(toString) {
|
|
1329
|
+
return {
|
|
1330
|
+
...eagerBuiltins(toString),
|
|
1331
|
+
...lazyBuiltins()
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
function goEqPair(a, b) {
|
|
1335
|
+
if (typeof a === "number" && typeof b === "bigint") return BigInt(a) === b;
|
|
1336
|
+
if (typeof a === "bigint" && typeof b === "number") return a === BigInt(b);
|
|
1337
|
+
return deepEqual(a, b);
|
|
1338
|
+
}
|
|
1339
|
+
function compare(a, b) {
|
|
1340
|
+
if (typeof a === "bigint" && typeof b === "bigint") return a === b ? 0 : a < b ? -1 : 1;
|
|
1341
|
+
if (typeof a === "bigint" || typeof b === "bigint") {
|
|
1342
|
+
const an = typeof a === "bigint" ? a : BigInt(Math.trunc(Number(a)));
|
|
1343
|
+
const bn = typeof b === "bigint" ? b : BigInt(Math.trunc(Number(b)));
|
|
1344
|
+
return an === bn ? 0 : an < bn ? -1 : 1;
|
|
1345
|
+
}
|
|
1346
|
+
const x = a;
|
|
1347
|
+
const y = b;
|
|
1348
|
+
return x === y ? 0 : x < y ? -1 : 1;
|
|
1349
|
+
}
|
|
1350
|
+
function goLen(value) {
|
|
1351
|
+
if (typeof value === "string") return value.length;
|
|
1352
|
+
if (Array.isArray(value)) return value.length;
|
|
1353
|
+
if (value instanceof Map) return value.size;
|
|
1354
|
+
if (value instanceof Set) return value.size;
|
|
1355
|
+
return Object.keys(value).length;
|
|
1356
|
+
}
|
|
1357
|
+
function goIndex(collection, key) {
|
|
1358
|
+
if (Array.isArray(collection)) {
|
|
1359
|
+
const i = Number(key);
|
|
1360
|
+
if (!Number.isInteger(i)) throw new Error(`index: array index must be integer, got ${describeType(key)}`);
|
|
1361
|
+
if (i < 0 || i >= collection.length) throw new Error(`index: out of range [${i}] with length ${collection.length}`);
|
|
1362
|
+
return collection[i];
|
|
1363
|
+
}
|
|
1364
|
+
if (collection instanceof Map) return collection.get(key);
|
|
1365
|
+
if (typeof collection === "string") return collection[Number(key)];
|
|
1366
|
+
if (collection !== null && typeof collection === "object") {
|
|
1367
|
+
if (typeof key !== "string") throw new Error(`index: object index must be string, got ${describeType(key)}`);
|
|
1368
|
+
return collection[key];
|
|
1369
|
+
}
|
|
1370
|
+
throw new Error(`index: cannot index ${describeType(collection)}`);
|
|
1371
|
+
}
|
|
1372
|
+
function describeType(v) {
|
|
1373
|
+
if (v === null) return "null";
|
|
1374
|
+
if (v === void 0) return "undefined";
|
|
1375
|
+
if (Array.isArray(v)) return "array";
|
|
1376
|
+
if (v instanceof Map) return "Map";
|
|
1377
|
+
return typeof v;
|
|
1378
|
+
}
|
|
1379
|
+
function goPrintfType(v) {
|
|
1380
|
+
if (v === null || v === void 0) return "<nil>";
|
|
1381
|
+
if (typeof v === "string") return "string";
|
|
1382
|
+
if (typeof v === "boolean") return "bool";
|
|
1383
|
+
if (typeof v === "bigint") return "int64";
|
|
1384
|
+
if (typeof v === "number") return Number.isInteger(v) ? "int" : "float64";
|
|
1385
|
+
if (Array.isArray(v)) return "[]interface {}";
|
|
1386
|
+
if (v instanceof Map || typeof v === "object") return "map[string]interface {}";
|
|
1387
|
+
return typeof v;
|
|
1388
|
+
}
|
|
1389
|
+
function goPrint(args, toString) {
|
|
1390
|
+
let out = "";
|
|
1391
|
+
let prevIsString = false;
|
|
1392
|
+
for (let i = 0; i < args.length; i++) {
|
|
1393
|
+
const arg = args[i];
|
|
1394
|
+
const isString = typeof arg === "string";
|
|
1395
|
+
if (i > 0 && !prevIsString && !isString) out += " ";
|
|
1396
|
+
out += stringifyForPrint(arg, toString);
|
|
1397
|
+
prevIsString = isString;
|
|
1398
|
+
}
|
|
1399
|
+
return out;
|
|
1400
|
+
}
|
|
1401
|
+
function stringifyForPrint(value, toString) {
|
|
1402
|
+
if (value === null || value === void 0) return "<nil>";
|
|
1403
|
+
if (typeof value === "string") return value;
|
|
1404
|
+
return toString(value);
|
|
1405
|
+
}
|
|
1406
|
+
function sprintf(format, args, toString) {
|
|
1407
|
+
let out = "";
|
|
1408
|
+
let argIdx = 0;
|
|
1409
|
+
let i = 0;
|
|
1410
|
+
while (i < format.length) {
|
|
1411
|
+
const ch = format[i];
|
|
1412
|
+
if (ch !== "%") {
|
|
1413
|
+
out += ch;
|
|
1414
|
+
i += 1;
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
if (format[i + 1] === "%") {
|
|
1418
|
+
out += "%";
|
|
1419
|
+
i += 2;
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
let j = i + 1;
|
|
1423
|
+
while (j < format.length && "+-# 0".includes(format[j] ?? "")) j += 1;
|
|
1424
|
+
while (j < format.length && format[j] !== void 0 && /[0-9]/.test(format[j])) j += 1;
|
|
1425
|
+
if (format[j] === ".") {
|
|
1426
|
+
j += 1;
|
|
1427
|
+
while (j < format.length && format[j] !== void 0 && /[0-9]/.test(format[j])) j += 1;
|
|
1428
|
+
}
|
|
1429
|
+
const verb = format[j];
|
|
1430
|
+
const spec = format.slice(i + 1, j);
|
|
1431
|
+
const arg = args[argIdx++];
|
|
1432
|
+
out += formatVerb(verb ?? "", spec, arg, toString);
|
|
1433
|
+
i = j + 1;
|
|
1434
|
+
}
|
|
1435
|
+
return out;
|
|
1436
|
+
}
|
|
1437
|
+
function formatVerb(verb, spec, arg, toString) {
|
|
1438
|
+
switch (verb) {
|
|
1439
|
+
case "s": return typeof arg === "string" ? applyWidth(spec, arg) : applyWidth(spec, stringifyForPrint(arg, toString));
|
|
1440
|
+
case "d":
|
|
1441
|
+
if (typeof arg !== "number" && typeof arg !== "bigint") return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
|
|
1442
|
+
return applyWidth(spec, String(typeof arg === "bigint" ? arg : Math.trunc(arg)));
|
|
1443
|
+
case "v": return applyWidth(spec, formatV(arg));
|
|
1444
|
+
case "q": return applyWidth(spec, JSON.stringify(stringifyForPrint(arg, toString)));
|
|
1445
|
+
case "f": {
|
|
1446
|
+
if (typeof arg !== "number" && typeof arg !== "bigint") return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
|
|
1447
|
+
const precision = spec.includes(".") ? Number(spec.split(".")[1]) : 6;
|
|
1448
|
+
return applyWidth(spec, Number(arg).toFixed(precision));
|
|
1449
|
+
}
|
|
1450
|
+
case "t": return applyWidth(spec, isTruthy(arg) ? "true" : "false");
|
|
1451
|
+
case "x":
|
|
1452
|
+
if (typeof arg === "string") {
|
|
1453
|
+
const bytes = new TextEncoder().encode(arg);
|
|
1454
|
+
let hex = "";
|
|
1455
|
+
for (const b of bytes) hex += b.toString(16).padStart(2, "0");
|
|
1456
|
+
return applyWidth(spec, hex);
|
|
1457
|
+
}
|
|
1458
|
+
if (typeof arg !== "number" && typeof arg !== "bigint") return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
|
|
1459
|
+
if (typeof arg === "bigint") return applyWidth(spec, arg.toString(16));
|
|
1460
|
+
return applyWidth(spec, Math.trunc(arg).toString(16));
|
|
1461
|
+
default: return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
function applyWidth(spec, body) {
|
|
1465
|
+
const flag = spec.match(/^([+\-# 0]*)/)?.[1] ?? "";
|
|
1466
|
+
const widthMatch = spec.slice(flag.length).match(/^(\d+)/);
|
|
1467
|
+
if (!widthMatch) return body;
|
|
1468
|
+
const width = Number(widthMatch[1]);
|
|
1469
|
+
if (body.length >= width) return body;
|
|
1470
|
+
const pad = " ".repeat(width - body.length);
|
|
1471
|
+
return flag.includes("-") ? body + pad : pad + body;
|
|
1472
|
+
}
|
|
1473
|
+
function formatV(value) {
|
|
1474
|
+
if (value === null || value === void 0) return "<nil>";
|
|
1475
|
+
if (typeof value === "string") return value;
|
|
1476
|
+
if (typeof value === "bigint") return value.toString();
|
|
1477
|
+
if (Array.isArray(value)) return `[${value.map(formatV).join(" ")}]`;
|
|
1478
|
+
if (value instanceof Map) return `map[${[...value.entries()].map(([k, v]) => `${formatV(k)}:${formatV(v)}`).join(" ")}]`;
|
|
1479
|
+
if (typeof value === "object") return `{${Object.values(value).map(formatV).join(" ")}}`;
|
|
1480
|
+
return String(value);
|
|
1481
|
+
}
|
|
1482
|
+
//#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
|
+
//#region src/evaluator/scope.ts
|
|
1511
|
+
function rootScope(value) {
|
|
1512
|
+
return {
|
|
1513
|
+
dot: value,
|
|
1514
|
+
root: value,
|
|
1515
|
+
parent: void 0,
|
|
1516
|
+
vars: /* @__PURE__ */ new Map()
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
function pushScope(parent, dot) {
|
|
1520
|
+
return {
|
|
1521
|
+
dot,
|
|
1522
|
+
root: parent.root,
|
|
1523
|
+
parent,
|
|
1524
|
+
vars: /* @__PURE__ */ new Map()
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Look up a `$var` binding, walking the parent chain.
|
|
1529
|
+
* Returns `{ found: true, value }` on hit and `{ found: false }` on miss
|
|
1530
|
+
* — explicit shape rather than `undefined` so callers can disambiguate
|
|
1531
|
+
* "not declared" from "declared but undefined".
|
|
1532
|
+
*/
|
|
1533
|
+
function lookupVar(scope, name) {
|
|
1534
|
+
let cur = scope;
|
|
1535
|
+
while (cur !== void 0) {
|
|
1536
|
+
if (cur.vars.has(name)) return {
|
|
1537
|
+
found: true,
|
|
1538
|
+
value: cur.vars.get(name)
|
|
1539
|
+
};
|
|
1540
|
+
cur = cur.parent;
|
|
1541
|
+
}
|
|
1542
|
+
return { found: false };
|
|
1543
|
+
}
|
|
1544
|
+
/** Declare a new variable in the leaf scope (for `:=`). */
|
|
1545
|
+
function declareVar(scope, name, value) {
|
|
1546
|
+
scope.vars.set(name, value);
|
|
1547
|
+
}
|
|
1548
|
+
//#endregion
|
|
1549
|
+
//#region src/evaluator/evaluator.ts
|
|
1550
|
+
/**
|
|
1551
|
+
* Engine<T> — generic-over-T template evaluator.
|
|
1552
|
+
*
|
|
1553
|
+
* [LAW:dataflow-not-control-flow] Evaluation is one switch on the AST
|
|
1554
|
+
* node's type. Every node kind has exactly one production rule; the
|
|
1555
|
+
* shape of work is fixed by the data, not by scattered branching.
|
|
1556
|
+
*
|
|
1557
|
+
* [LAW:single-enforcer] All `string → T` conversion goes through
|
|
1558
|
+
* `fromString`. There is exactly one place text becomes T. Function
|
|
1559
|
+
* returns of `string` are routed through the same converter on their
|
|
1560
|
+
* way to the output stream — the asymmetry between "string in / T out"
|
|
1561
|
+
* is encoded as a single function call, not duplicated at every site.
|
|
1562
|
+
*
|
|
1563
|
+
* State is threaded as a single `EvalContext` per `evaluate()` call —
|
|
1564
|
+
* no instance mutation, so the same Engine handles concurrent evaluate
|
|
1565
|
+
* calls (tested through the parse-once-eval-many invariant).
|
|
1566
|
+
*/
|
|
1567
|
+
const NO_PIPE = { kind: "none" };
|
|
1568
|
+
/**
|
|
1569
|
+
* A parsed template bound to its parent engine.
|
|
1570
|
+
*
|
|
1571
|
+
* Template instances are immutable — `evaluate(scope)` may be called
|
|
1572
|
+
* any number of times with different scopes, matching the
|
|
1573
|
+
* "parse-once-eval-many" invariant from the epic spec. The `source`
|
|
1574
|
+
* property exposes the original template text for debugging /
|
|
1575
|
+
* diagnostics.
|
|
1576
|
+
*
|
|
1577
|
+
* Construct via `engine.parse(src)`. The constructor is private so
|
|
1578
|
+
* the public type surface need not reference internal AST shapes.
|
|
1579
|
+
*/
|
|
1580
|
+
let internalCreateTemplate;
|
|
1581
|
+
var Template = class Template {
|
|
1582
|
+
source;
|
|
1583
|
+
_evaluate;
|
|
1584
|
+
constructor(source, evaluate) {
|
|
1585
|
+
this.source = source;
|
|
1586
|
+
this._evaluate = evaluate;
|
|
1587
|
+
}
|
|
1588
|
+
static {
|
|
1589
|
+
internalCreateTemplate = (source, evaluate) => new Template(source, evaluate);
|
|
1590
|
+
}
|
|
1591
|
+
evaluate(scope) {
|
|
1592
|
+
return this._evaluate(scope);
|
|
1593
|
+
}
|
|
1594
|
+
};
|
|
1595
|
+
var Engine = class {
|
|
1596
|
+
fromString;
|
|
1597
|
+
toString;
|
|
1598
|
+
funcs;
|
|
1599
|
+
constructor(config) {
|
|
1600
|
+
this.fromString = config.fromString;
|
|
1601
|
+
const userToString = Object.hasOwn(config, "toString") ? config.toString : void 0;
|
|
1602
|
+
this.toString = userToString ?? defaultToString;
|
|
1603
|
+
this.funcs = {
|
|
1604
|
+
...defaultBuiltins(this.toString),
|
|
1605
|
+
...config.funcs ?? {}
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Parse a template source into a reusable Template handle.
|
|
1610
|
+
*
|
|
1611
|
+
* The returned Template is immutable; calling `evaluate(scope)` on
|
|
1612
|
+
* it any number of times with different scopes is safe and avoids
|
|
1613
|
+
* re-parsing.
|
|
1614
|
+
*/
|
|
1615
|
+
parse(source) {
|
|
1616
|
+
const parsed = parse(source);
|
|
1617
|
+
return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope));
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* Convenience sugar for `parse(src).evaluate.bind(template)`.
|
|
1621
|
+
*
|
|
1622
|
+
* Returns a closure that takes a scope and produces T[]. Useful when
|
|
1623
|
+
* the template is parsed once at module load and called many times.
|
|
1624
|
+
*/
|
|
1625
|
+
compile(source) {
|
|
1626
|
+
const template = this.parse(source);
|
|
1627
|
+
return (scope) => template.evaluate(scope);
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Evaluate a parsed template against a scope value, producing T[].
|
|
1631
|
+
*
|
|
1632
|
+
* Accepts only Templates produced by `engine.parse(src)` so the
|
|
1633
|
+
* public type surface stays clear of internal AST shapes.
|
|
1634
|
+
*/
|
|
1635
|
+
evaluate(template, scope) {
|
|
1636
|
+
return template.evaluate(scope);
|
|
1637
|
+
}
|
|
1638
|
+
evalParsed(parsed, scope) {
|
|
1639
|
+
const out = [];
|
|
1640
|
+
const root = rootScope(scope);
|
|
1641
|
+
const ctx = {
|
|
1642
|
+
out,
|
|
1643
|
+
defines: parsed.defines,
|
|
1644
|
+
source: parsed.source
|
|
1645
|
+
};
|
|
1646
|
+
this.evalList(parsed.root, root, ctx);
|
|
1647
|
+
return out;
|
|
1648
|
+
}
|
|
1649
|
+
evalList(node, scope, ctx) {
|
|
1650
|
+
for (const child of node.nodes) this.evalNode(child, scope, ctx);
|
|
1651
|
+
}
|
|
1652
|
+
evalNode(node, scope, ctx) {
|
|
1653
|
+
switch (node.type) {
|
|
1654
|
+
case "Text":
|
|
1655
|
+
ctx.out.push(this.fromString(node.text));
|
|
1656
|
+
return;
|
|
1657
|
+
case "Comment": return;
|
|
1658
|
+
case "Action": {
|
|
1659
|
+
const value = this.evalAction(node, scope, ctx);
|
|
1660
|
+
if (node.pipe.decls.length === 0) this.emitFromValue(value, ctx);
|
|
1661
|
+
return;
|
|
1662
|
+
}
|
|
1663
|
+
case "List":
|
|
1664
|
+
this.evalList(node, scope, ctx);
|
|
1665
|
+
return;
|
|
1666
|
+
case "If":
|
|
1667
|
+
this.evalIf(node, scope, ctx);
|
|
1668
|
+
return;
|
|
1669
|
+
case "Range":
|
|
1670
|
+
this.evalRange(node, scope, ctx);
|
|
1671
|
+
return;
|
|
1672
|
+
case "With":
|
|
1673
|
+
this.evalWith(node, scope, ctx);
|
|
1674
|
+
return;
|
|
1675
|
+
case "Template":
|
|
1676
|
+
this.evalTemplateInvoke(node, scope, ctx);
|
|
1677
|
+
return;
|
|
1678
|
+
case "Block":
|
|
1679
|
+
this.evalBlock(node, scope, ctx);
|
|
1680
|
+
return;
|
|
1681
|
+
case "Pipe":
|
|
1682
|
+
case "Command":
|
|
1683
|
+
case "Identifier":
|
|
1684
|
+
case "Field":
|
|
1685
|
+
case "Variable":
|
|
1686
|
+
case "Chain":
|
|
1687
|
+
case "Dot":
|
|
1688
|
+
case "Nil":
|
|
1689
|
+
case "Bool":
|
|
1690
|
+
case "Number":
|
|
1691
|
+
case "String": throw new EvalError(`unexpected ${node.type} at statement position`, node.pos, { source: ctx.source });
|
|
1692
|
+
default: assertNever(node);
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
evalIf(node, scope, ctx) {
|
|
1696
|
+
if (isTruthy(this.evalPipe(node.pipe, scope, ctx))) this.evalList(node.list, scope, ctx);
|
|
1697
|
+
else if (node.elseList) this.evalList(node.elseList, scope, ctx);
|
|
1698
|
+
}
|
|
1699
|
+
evalWith(node, scope, ctx) {
|
|
1700
|
+
const value = this.evalPipe(node.pipe, scope, ctx);
|
|
1701
|
+
if (isTruthy(value)) {
|
|
1702
|
+
const child = pushScope(scope, value);
|
|
1703
|
+
this.evalList(node.list, child, ctx);
|
|
1704
|
+
} else if (node.elseList) this.evalList(node.elseList, scope, ctx);
|
|
1705
|
+
}
|
|
1706
|
+
evalRange(node, scope, ctx) {
|
|
1707
|
+
const value = this.evalPipeWithoutDecls(node.pipe, scope, ctx);
|
|
1708
|
+
const decls = node.pipe.decls;
|
|
1709
|
+
const entries = enumerateForRange(value);
|
|
1710
|
+
if (entries.length === 0) {
|
|
1711
|
+
if (node.elseList) this.evalList(node.elseList, scope, ctx);
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
for (const [key, item] of entries) {
|
|
1715
|
+
const child = pushScope(scope, item);
|
|
1716
|
+
if (decls.length === 1) declareVar(child, decls[0]?.idents[0] ?? "$", item);
|
|
1717
|
+
else if (decls.length >= 2) {
|
|
1718
|
+
const k = decls[0]?.idents[0] ?? "$";
|
|
1719
|
+
const v = decls[1]?.idents[0] ?? "$";
|
|
1720
|
+
declareVar(child, k, key);
|
|
1721
|
+
declareVar(child, v, item);
|
|
1722
|
+
}
|
|
1723
|
+
this.evalList(node.list, child, ctx);
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
evalTemplateInvoke(node, scope, ctx) {
|
|
1727
|
+
const tpl = ctx.defines.get(node.name);
|
|
1728
|
+
if (!tpl) throw new EvalError(`template ${JSON.stringify(node.name)} is not defined`, node.pos, { source: ctx.source });
|
|
1729
|
+
const child = pushScope(scope, node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot);
|
|
1730
|
+
this.evalList(tpl, child, ctx);
|
|
1731
|
+
}
|
|
1732
|
+
evalBlock(node, scope, ctx) {
|
|
1733
|
+
const child = pushScope(scope, node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot);
|
|
1734
|
+
const tpl = ctx.defines.get(node.name) ?? node.list;
|
|
1735
|
+
this.evalList(tpl, child, ctx);
|
|
1736
|
+
}
|
|
1737
|
+
evalAction(node, scope, ctx) {
|
|
1738
|
+
return this.evalPipe(node.pipe, scope, ctx);
|
|
1739
|
+
}
|
|
1740
|
+
evalPipe(pipe, scope, ctx) {
|
|
1741
|
+
if (pipe.cmds.length === 0) throw new EvalError("empty pipeline", pipe.pos, { source: ctx.source });
|
|
1742
|
+
let value = this.evalCommand(pipe.cmds[0], scope, ctx, NO_PIPE);
|
|
1743
|
+
for (let i = 1; i < pipe.cmds.length; i++) {
|
|
1744
|
+
const next = pipe.cmds[i];
|
|
1745
|
+
value = this.evalCommand(next, scope, ctx, {
|
|
1746
|
+
kind: "value",
|
|
1747
|
+
value
|
|
1748
|
+
});
|
|
1749
|
+
}
|
|
1750
|
+
if (pipe.decls.length > 0) for (const decl of pipe.decls) declareVar(scope, decl.idents[0] ?? "$", value);
|
|
1751
|
+
return value;
|
|
1752
|
+
}
|
|
1753
|
+
evalPipeWithoutDecls(pipe, scope, ctx) {
|
|
1754
|
+
const stripped = {
|
|
1755
|
+
type: "Pipe",
|
|
1756
|
+
pos: pipe.pos,
|
|
1757
|
+
decls: [],
|
|
1758
|
+
isAssign: false,
|
|
1759
|
+
cmds: pipe.cmds
|
|
1760
|
+
};
|
|
1761
|
+
return this.evalPipe(stripped, scope, ctx);
|
|
1762
|
+
}
|
|
1763
|
+
evalCommand(cmd, scope, ctx, piped) {
|
|
1764
|
+
if (cmd.args.length === 0) throw new EvalError("empty command", cmd.pos, { source: ctx.source });
|
|
1765
|
+
const head = cmd.args[0];
|
|
1766
|
+
if (head.type !== "Identifier") {
|
|
1767
|
+
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 });
|
|
1768
|
+
return this.evalPrimary(head, scope, ctx);
|
|
1769
|
+
}
|
|
1770
|
+
const fn = this.funcs[head.ident];
|
|
1771
|
+
if (!fn) throw new FuncNotFoundError(head.ident, head.pos, {
|
|
1772
|
+
source: ctx.source,
|
|
1773
|
+
available: Object.keys(this.funcs)
|
|
1774
|
+
});
|
|
1775
|
+
const argNodes = cmd.args.slice(1);
|
|
1776
|
+
const lazy = isLazy(fn);
|
|
1777
|
+
const args = argNodes.map((n) => lazy ? () => this.evalPrimary(n, scope, ctx) : this.evalPrimary(n, scope, ctx));
|
|
1778
|
+
if (piped.kind === "value") {
|
|
1779
|
+
const v = piped.value;
|
|
1780
|
+
args.push(lazy ? () => v : v);
|
|
1781
|
+
}
|
|
1782
|
+
enforceArgTypes(head.ident, fn.argTypes, args, cmd.pos, ctx.source, this.toString, fn.argTypePattern);
|
|
1783
|
+
try {
|
|
1784
|
+
return fn.fn(...args);
|
|
1785
|
+
} catch (e) {
|
|
1786
|
+
if (e instanceof TypeMismatchError) throw new TypeMismatchError(e.funcName, e.argIndex, e.expected, e.receivedSummary, cmd.pos, { source: ctx.source });
|
|
1787
|
+
throw e;
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
evalPrimary(node, scope, ctx) {
|
|
1791
|
+
switch (node.type) {
|
|
1792
|
+
case "Dot": return scope.dot;
|
|
1793
|
+
case "Nil": return null;
|
|
1794
|
+
case "Bool": return node.value;
|
|
1795
|
+
case "Number": return numberValue(node);
|
|
1796
|
+
case "String": return node.value;
|
|
1797
|
+
case "Field": return this.resolveFieldChain(scope.dot, node.idents, node.pos, ctx);
|
|
1798
|
+
case "Variable": return this.resolveVariable(node.idents, scope, node.pos, ctx);
|
|
1799
|
+
case "Identifier": {
|
|
1800
|
+
const fn = this.funcs[node.ident];
|
|
1801
|
+
if (!fn) throw new FuncNotFoundError(node.ident, node.pos, {
|
|
1802
|
+
source: ctx.source,
|
|
1803
|
+
available: Object.keys(this.funcs)
|
|
1804
|
+
});
|
|
1805
|
+
enforceArgTypes(node.ident, fn.argTypes, [], node.pos, ctx.source, this.toString, fn.argTypePattern);
|
|
1806
|
+
return fn.fn();
|
|
1807
|
+
}
|
|
1808
|
+
case "Chain": return this.resolveFieldChain(this.evalPrimary(node.node, scope, ctx), node.fields, node.pos, ctx);
|
|
1809
|
+
case "Pipe": return this.evalPipe(node, scope, ctx);
|
|
1810
|
+
default: throw new EvalError(`cannot evaluate ${node.type} as a value`, node.pos, { source: ctx.source });
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
resolveFieldChain(receiver, idents, pos, ctx) {
|
|
1814
|
+
const result = walkFieldChain(receiver, idents);
|
|
1815
|
+
if (result === MISSING) throw new MissingFieldError(idents, pos, { source: ctx.source });
|
|
1816
|
+
return result;
|
|
1817
|
+
}
|
|
1818
|
+
resolveVariable(idents, scope, pos, ctx) {
|
|
1819
|
+
const head = idents[0] ?? "$";
|
|
1820
|
+
if (head === "$") {
|
|
1821
|
+
const tail = idents.slice(1);
|
|
1822
|
+
return tail.length === 0 ? scope.root : this.resolveFieldChain(scope.root, tail, pos, ctx);
|
|
1823
|
+
}
|
|
1824
|
+
const lookup = lookupVar(scope, head);
|
|
1825
|
+
if (!lookup.found) throw new EvalError(`undefined variable ${head}`, pos, { source: ctx.source });
|
|
1826
|
+
const tail = idents.slice(1);
|
|
1827
|
+
return tail.length === 0 ? lookup.value : this.resolveFieldChain(lookup.value, tail, pos, ctx);
|
|
1828
|
+
}
|
|
1829
|
+
emitFromValue(value, ctx) {
|
|
1830
|
+
if (value === null || value === void 0) {
|
|
1831
|
+
ctx.out.push(this.fromString("<no value>"));
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
if (typeof value === "string") {
|
|
1835
|
+
ctx.out.push(this.fromString(value));
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
1839
|
+
ctx.out.push(this.fromString(String(value)));
|
|
1840
|
+
return;
|
|
1841
|
+
}
|
|
1842
|
+
if (Array.isArray(value)) {
|
|
1843
|
+
ctx.out.push(this.fromString(formatArrayLikeGo(value)));
|
|
1844
|
+
return;
|
|
1845
|
+
}
|
|
1846
|
+
if (value instanceof Map) {
|
|
1847
|
+
ctx.out.push(this.fromString(formatMapLikeGo(value)));
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
ctx.out.push(value);
|
|
1851
|
+
}
|
|
1852
|
+
};
|
|
1853
|
+
function formatArrayLikeGo(arr) {
|
|
1854
|
+
return `[${arr.map(formatScalarLikeGo).join(" ")}]`;
|
|
1855
|
+
}
|
|
1856
|
+
function formatMapLikeGo(m) {
|
|
1857
|
+
const parts = [];
|
|
1858
|
+
for (const [k, v] of m) parts.push(`${formatScalarLikeGo(k)}:${formatScalarLikeGo(v)}`);
|
|
1859
|
+
return `map[${parts.join(" ")}]`;
|
|
1860
|
+
}
|
|
1861
|
+
function formatScalarLikeGo(v) {
|
|
1862
|
+
if (v === null || v === void 0) return "<nil>";
|
|
1863
|
+
if (Array.isArray(v)) return formatArrayLikeGo(v);
|
|
1864
|
+
if (v instanceof Map) return formatMapLikeGo(v);
|
|
1865
|
+
return String(v);
|
|
1866
|
+
}
|
|
1867
|
+
function createEngine(config) {
|
|
1868
|
+
return new Engine(config);
|
|
1869
|
+
}
|
|
1870
|
+
function enforceArgTypes(funcName, argTypes, values, pos, src, toString = defaultToString, pattern) {
|
|
1871
|
+
const lookup = makeSlotLookup(argTypes, pattern);
|
|
1872
|
+
let firstOrdered = -1;
|
|
1873
|
+
let firstComparable = -1;
|
|
1874
|
+
for (let i = 0; i < values.length; i++) {
|
|
1875
|
+
const declared = lookup(i);
|
|
1876
|
+
const value = values[i];
|
|
1877
|
+
if (!matchesArgType(declared, value, toString)) throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), describeValue(value), pos, { source: src });
|
|
1878
|
+
if (declared === "ordered") {
|
|
1879
|
+
if (firstOrdered === -1) firstOrdered = i;
|
|
1880
|
+
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 });
|
|
1881
|
+
}
|
|
1882
|
+
if (declared === "comparable") {
|
|
1883
|
+
if (firstComparable === -1) firstComparable = i;
|
|
1884
|
+
else if (!sameComparableKind(values[firstComparable], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("comparable")} of the same kind as ${describeValue(values[firstComparable])}`, describeValue(value), pos, { source: src });
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
function makeSlotLookup(argTypes, pattern) {
|
|
1889
|
+
if (argTypes.length === 0) return () => "value";
|
|
1890
|
+
if (pattern === "alternating") {
|
|
1891
|
+
const len = argTypes.length;
|
|
1892
|
+
return (i) => argTypes[i % len];
|
|
1893
|
+
}
|
|
1894
|
+
const trailing = argTypes[argTypes.length - 1];
|
|
1895
|
+
return (i) => i < argTypes.length ? argTypes[i] : trailing;
|
|
1896
|
+
}
|
|
1897
|
+
function matchesArgType(declared, value, toString) {
|
|
1898
|
+
switch (declared) {
|
|
1899
|
+
case "truthy":
|
|
1900
|
+
case "reflective":
|
|
1901
|
+
case "value": return true;
|
|
1902
|
+
case "string": return typeof value === "string";
|
|
1903
|
+
case "number": return typeof value === "number" || typeof value === "bigint";
|
|
1904
|
+
case "bool": return typeof value === "boolean";
|
|
1905
|
+
case "ordered": return typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean";
|
|
1906
|
+
case "T": return value !== null && value !== void 0 && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint" && typeof value !== "symbol";
|
|
1907
|
+
case "list": return Array.isArray(value);
|
|
1908
|
+
case "dict": return isPlainObject(value);
|
|
1909
|
+
case "sized": return typeof value === "string" || Array.isArray(value) || value instanceof Map || value instanceof Set || isPlainObject(value);
|
|
1910
|
+
case "comparable": return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean" || Array.isArray(value) || value instanceof Map || value instanceof Set || isPlainObject(value);
|
|
1911
|
+
case "callable": return typeof value === "function";
|
|
1912
|
+
case "collection": return typeof value === "string" || Array.isArray(value) || value instanceof Map || isPlainObject(value);
|
|
1913
|
+
case "index-key": return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
|
|
1914
|
+
case "sliceable": return typeof value === "string" || Array.isArray(value);
|
|
1915
|
+
case "stringifiable":
|
|
1916
|
+
if (typeof value === "string") return true;
|
|
1917
|
+
try {
|
|
1918
|
+
toString(value);
|
|
1919
|
+
return true;
|
|
1920
|
+
} catch {
|
|
1921
|
+
return false;
|
|
1922
|
+
}
|
|
1923
|
+
case "serializable": return isJsonSerializable(value);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
function defaultToString(value) {
|
|
1927
|
+
if (typeof value === "string") return value;
|
|
1928
|
+
if (value === null || value === void 0) return "<nil>";
|
|
1929
|
+
if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
|
|
1930
|
+
throw new TypeMismatchError("<engine.toString>", 1, "string (or a consumer-supplied toString that flattens T)", describeValue(value), {
|
|
1931
|
+
line: 0,
|
|
1932
|
+
column: 0,
|
|
1933
|
+
offset: 0
|
|
1934
|
+
});
|
|
1935
|
+
}
|
|
1936
|
+
function isPlainObject(value) {
|
|
1937
|
+
if (value === null || typeof value !== "object") return false;
|
|
1938
|
+
if (Array.isArray(value)) return false;
|
|
1939
|
+
if (value instanceof Map || value instanceof Set) return false;
|
|
1940
|
+
const proto = Object.getPrototypeOf(value);
|
|
1941
|
+
return proto === null || proto === Object.prototype;
|
|
1942
|
+
}
|
|
1943
|
+
function isJsonSerializable(value) {
|
|
1944
|
+
try {
|
|
1945
|
+
return JSON.stringify(value) !== void 0;
|
|
1946
|
+
} catch {
|
|
1947
|
+
return false;
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
function sameOrderedKind(a, b) {
|
|
1951
|
+
if (typeof a === typeof b) return true;
|
|
1952
|
+
if (typeof a === "number" && typeof b === "bigint") return true;
|
|
1953
|
+
if (typeof a === "bigint" && typeof b === "number") return true;
|
|
1954
|
+
return false;
|
|
1955
|
+
}
|
|
1956
|
+
function sameComparableKind(a, b) {
|
|
1957
|
+
const ka = comparableKind(a);
|
|
1958
|
+
const kb = comparableKind(b);
|
|
1959
|
+
if (ka === "nil" || kb === "nil") return true;
|
|
1960
|
+
return ka === kb;
|
|
1961
|
+
}
|
|
1962
|
+
function comparableKind(v) {
|
|
1963
|
+
if (v === null || v === void 0) return "nil";
|
|
1964
|
+
if (typeof v === "string") return "string";
|
|
1965
|
+
if (typeof v === "number" || typeof v === "bigint") return "number";
|
|
1966
|
+
if (typeof v === "boolean") return "boolean";
|
|
1967
|
+
if (Array.isArray(v)) return "array";
|
|
1968
|
+
if (v instanceof Map) return "map";
|
|
1969
|
+
if (v instanceof Set) return "set";
|
|
1970
|
+
return "object";
|
|
1971
|
+
}
|
|
1972
|
+
function humanArgType(t) {
|
|
1973
|
+
switch (t) {
|
|
1974
|
+
case "T": return "T (consumer-defined fragment)";
|
|
1975
|
+
case "ordered": return "orderable primitive";
|
|
1976
|
+
case "list": return "list";
|
|
1977
|
+
case "dict": return "dict (plain object)";
|
|
1978
|
+
case "sized": return "sized value (string, list, map, set, or dict)";
|
|
1979
|
+
case "comparable": return "comparable value (orderable primitive, nil, list, dict, Map, or Set)";
|
|
1980
|
+
case "stringifiable": return "stringifiable value (string or convertible via the engine's toString)";
|
|
1981
|
+
case "callable": return "callable (function value)";
|
|
1982
|
+
case "collection": return "collection (string, array, Map, or dict)";
|
|
1983
|
+
case "index-key": return "index key (number, bigint, or string)";
|
|
1984
|
+
case "sliceable": return "sliceable value (string or array)";
|
|
1985
|
+
case "serializable": return "JSON-serializable value";
|
|
1986
|
+
case "truthy":
|
|
1987
|
+
case "reflective":
|
|
1988
|
+
case "value":
|
|
1989
|
+
case "string":
|
|
1990
|
+
case "number":
|
|
1991
|
+
case "bool": return t;
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
function describeValue(value) {
|
|
1995
|
+
if (value === null) return "null";
|
|
1996
|
+
if (value === void 0) return "undefined";
|
|
1997
|
+
if (Array.isArray(value)) return "array";
|
|
1998
|
+
if (value instanceof Map) return "Map";
|
|
1999
|
+
return typeof value;
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Produce [key, value] entries for a `range` operand.
|
|
2003
|
+
*
|
|
2004
|
+
* - Arrays / typed arrays / strings: numeric index → element
|
|
2005
|
+
* - Maps and plain objects: entries sorted by key. Matches Go's
|
|
2006
|
+
* `text/template`, which sorts map keys via `internal/fmtsort`
|
|
2007
|
+
* before iterating — same input always produces the same byte
|
|
2008
|
+
* output. Strings sort lexically; numbers numerically.
|
|
2009
|
+
* - Sets: index → element (Go ranges over channels but we map to Set
|
|
2010
|
+
* for symmetry with arrays/iteration)
|
|
2011
|
+
* - null/undefined: empty
|
|
2012
|
+
*/
|
|
2013
|
+
function enumerateForRange(value) {
|
|
2014
|
+
if (value === null || value === void 0) return [];
|
|
2015
|
+
if (Array.isArray(value)) return value.map((v, i) => [i, v]);
|
|
2016
|
+
if (typeof value === "string") return [...value].map((c, i) => [i, c]);
|
|
2017
|
+
if (value instanceof Map) return sortMapEntries([...value.entries()]);
|
|
2018
|
+
if (value instanceof Set) return [...value.values()].map((v, i) => [i, v]);
|
|
2019
|
+
if (typeof value === "object") return sortMapEntries(Object.entries(value));
|
|
2020
|
+
return [];
|
|
2021
|
+
}
|
|
2022
|
+
function sortMapEntries(entries) {
|
|
2023
|
+
return [...entries].sort((a, b) => compareMapKeys(a[0], b[0]));
|
|
2024
|
+
}
|
|
2025
|
+
function compareMapKeys(a, b) {
|
|
2026
|
+
if ((typeof a === "number" || typeof a === "bigint") && (typeof b === "number" || typeof b === "bigint")) {
|
|
2027
|
+
const ax = typeof a === "bigint" ? Number(a) : a;
|
|
2028
|
+
const bx = typeof b === "bigint" ? Number(b) : b;
|
|
2029
|
+
return ax === bx ? 0 : ax < bx ? -1 : 1;
|
|
2030
|
+
}
|
|
2031
|
+
const as = String(a);
|
|
2032
|
+
const bs = String(b);
|
|
2033
|
+
return as === bs ? 0 : as < bs ? -1 : 1;
|
|
2034
|
+
}
|
|
2035
|
+
function numberValue(n) {
|
|
2036
|
+
if (n.intValue !== void 0) {
|
|
2037
|
+
const bi = n.intValue;
|
|
2038
|
+
if (bi >= BigInt(Number.MIN_SAFE_INTEGER) && bi <= BigInt(Number.MAX_SAFE_INTEGER)) return Number(bi);
|
|
2039
|
+
return bi;
|
|
2040
|
+
}
|
|
2041
|
+
if (n.floatValue !== void 0) return n.floatValue;
|
|
2042
|
+
if (n.complexValue !== void 0) return n.complexValue;
|
|
2043
|
+
throw new Error("internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated");
|
|
2044
|
+
}
|
|
2045
|
+
//#endregion
|
|
2046
|
+
//#region src/sprig/conversions/atoi.ts
|
|
2047
|
+
/**
|
|
2048
|
+
* `atoi s` — parse a base-10 integer string. Returns 0 for any
|
|
2049
|
+
* non-parseable input, matching Go sprig (`strconv.Atoi(s)` with the
|
|
2050
|
+
* error discarded). Hex/octal prefixes are *not* accepted — that's
|
|
2051
|
+
* what `toDecimal` is for.
|
|
2052
|
+
*/
|
|
2053
|
+
function atoi(s) {
|
|
2054
|
+
if (!/^[+-]?\d+$/.test(s)) return 0;
|
|
2055
|
+
const n = Number.parseInt(s, 10);
|
|
2056
|
+
return Number.isNaN(n) ? 0 : n;
|
|
2057
|
+
}
|
|
2058
|
+
//#endregion
|
|
2059
|
+
//#region src/sprig/conversions/float64.ts
|
|
2060
|
+
/**
|
|
2061
|
+
* `float64 v` — coerce to a JS number. Strings parse via
|
|
2062
|
+
* `Number.parseFloat` (Go: `strconv.ParseFloat(s, 64)`); non-numeric
|
|
2063
|
+
* input collapses to 0.
|
|
2064
|
+
*/
|
|
2065
|
+
function float64(v) {
|
|
2066
|
+
if (typeof v === "number") return v;
|
|
2067
|
+
if (typeof v === "bigint") return Number(v);
|
|
2068
|
+
if (typeof v === "string") {
|
|
2069
|
+
const n = Number.parseFloat(v);
|
|
2070
|
+
return Number.isNaN(n) ? 0 : n;
|
|
2071
|
+
}
|
|
2072
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
2073
|
+
return 0;
|
|
2074
|
+
}
|
|
2075
|
+
//#endregion
|
|
2076
|
+
//#region src/sprig/conversions/parseBase0.ts
|
|
2077
|
+
/**
|
|
2078
|
+
* Internal helper — Go's `strconv.ParseInt(s, 0, 64)` auto-detect rule.
|
|
2079
|
+
*
|
|
2080
|
+
* `0x`/`0X` → hex, `0b`/`0B` → binary, `0o`/`0O` → octal,
|
|
2081
|
+
* leading `0` → octal, otherwise decimal.
|
|
2082
|
+
*
|
|
2083
|
+
* Returns the parsed integer string-keyed (so callers can decide
|
|
2084
|
+
* `Number` vs `BigInt`), or `null` for unparseable input. Empty
|
|
2085
|
+
* string and lone `+`/`-` are unparseable.
|
|
2086
|
+
*/
|
|
2087
|
+
function parseBase0(s) {
|
|
2088
|
+
if (s === "") return null;
|
|
2089
|
+
let sign = 1;
|
|
2090
|
+
let body = s;
|
|
2091
|
+
if (body[0] === "+") body = body.slice(1);
|
|
2092
|
+
else if (body[0] === "-") {
|
|
2093
|
+
sign = -1;
|
|
2094
|
+
body = body.slice(1);
|
|
2095
|
+
}
|
|
2096
|
+
if (body === "") return null;
|
|
2097
|
+
if (/^0x[0-9a-fA-F]+$/i.test(body)) return {
|
|
2098
|
+
sign,
|
|
2099
|
+
digits: body.slice(2),
|
|
2100
|
+
base: 16
|
|
2101
|
+
};
|
|
2102
|
+
if (/^0b[01]+$/i.test(body)) return {
|
|
2103
|
+
sign,
|
|
2104
|
+
digits: body.slice(2),
|
|
2105
|
+
base: 2
|
|
2106
|
+
};
|
|
2107
|
+
if (/^0o[0-7]+$/i.test(body)) return {
|
|
2108
|
+
sign,
|
|
2109
|
+
digits: body.slice(2),
|
|
2110
|
+
base: 8
|
|
2111
|
+
};
|
|
2112
|
+
if (body === "0") return {
|
|
2113
|
+
sign,
|
|
2114
|
+
digits: "0",
|
|
2115
|
+
base: 10
|
|
2116
|
+
};
|
|
2117
|
+
if (body[0] === "0") {
|
|
2118
|
+
if (!/^0[0-7]+$/.test(body)) return null;
|
|
2119
|
+
return {
|
|
2120
|
+
sign,
|
|
2121
|
+
digits: body.slice(1),
|
|
2122
|
+
base: 8
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
if (!/^[0-9]+$/.test(body)) return null;
|
|
2126
|
+
return {
|
|
2127
|
+
sign,
|
|
2128
|
+
digits: body,
|
|
2129
|
+
base: 10
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
//#endregion
|
|
2133
|
+
//#region src/sprig/conversions/int.ts
|
|
2134
|
+
/**
|
|
2135
|
+
* `int v` — coerce to integer, truncating toward zero. Strings parse
|
|
2136
|
+
* with Go's `strconv.ParseInt(s, 0, 64)` rule (base auto-detect: hex
|
|
2137
|
+
* `0x`, octal `0`/`0o`, binary `0b`, decimal default). Anything not
|
|
2138
|
+
* parseable → 0.
|
|
2139
|
+
*/
|
|
2140
|
+
function int(v) {
|
|
2141
|
+
if (typeof v === "number") return Math.trunc(v);
|
|
2142
|
+
if (typeof v === "bigint") return Number(v);
|
|
2143
|
+
if (typeof v === "string") {
|
|
2144
|
+
const parsed = parseBase0(v);
|
|
2145
|
+
if (parsed === null) return 0;
|
|
2146
|
+
const n = Number.parseInt(parsed.digits, parsed.base);
|
|
2147
|
+
return Number.isNaN(n) ? 0 : parsed.sign * n;
|
|
2148
|
+
}
|
|
2149
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
2150
|
+
return 0;
|
|
2151
|
+
}
|
|
2152
|
+
//#endregion
|
|
2153
|
+
//#region src/sprig/conversions/int64.ts
|
|
2154
|
+
/**
|
|
2155
|
+
* `int64 v` — coerce to a 64-bit integer. Returns `bigint` so the
|
|
2156
|
+
* full Go-`int64` precision survives the round-trip (a JS `number`
|
|
2157
|
+
* loses precision past 2^53).
|
|
2158
|
+
*
|
|
2159
|
+
* Same coercion rules as `int`; differs only in the carrier type.
|
|
2160
|
+
*/
|
|
2161
|
+
function int64(v) {
|
|
2162
|
+
if (typeof v === "bigint") return v;
|
|
2163
|
+
if (typeof v === "number") return BigInt(Math.trunc(v));
|
|
2164
|
+
if (typeof v === "string") {
|
|
2165
|
+
const parsed = parseBase0(v);
|
|
2166
|
+
if (parsed === null) return 0n;
|
|
2167
|
+
const prefix = parsed.base === 16 ? "0x" : parsed.base === 2 ? "0b" : parsed.base === 8 ? "0o" : "";
|
|
2168
|
+
const n = BigInt(prefix + parsed.digits);
|
|
2169
|
+
return parsed.sign === -1 ? -n : n;
|
|
2170
|
+
}
|
|
2171
|
+
if (typeof v === "boolean") return v ? 1n : 0n;
|
|
2172
|
+
return 0n;
|
|
2173
|
+
}
|
|
2174
|
+
//#endregion
|
|
2175
|
+
//#region src/sprig/conversions/toDecimal.ts
|
|
2176
|
+
/**
|
|
2177
|
+
* `toDecimal s` — parse `s` as base-8 (octal) and return the decimal
|
|
2178
|
+
* value. Despite the name, sprig hard-codes base 8 — see Masterminds
|
|
2179
|
+
* `toDecimal`: `strconv.ParseInt(fmt.Sprintf("%v", v), 8, 64)`.
|
|
2180
|
+
*
|
|
2181
|
+
* Prefixes are *not* accepted (only base-8 explicit means no `0o`/`0x`
|
|
2182
|
+
* detection). Non-octal digits or non-string-parseable input → 0.
|
|
2183
|
+
*
|
|
2184
|
+
* Examples:
|
|
2185
|
+
* toDecimal "0755" → 493 (the "convert octal-string to decimal" use case)
|
|
2186
|
+
* toDecimal "08" → 0 (8 is not an octal digit; Go errors)
|
|
2187
|
+
* toDecimal "0xff" → 0 (no prefix detection at base 8)
|
|
2188
|
+
*/
|
|
2189
|
+
function toDecimal(s) {
|
|
2190
|
+
if (!/^[+-]?[0-7]+$/.test(s)) return 0;
|
|
2191
|
+
const sign = s[0] === "-" ? -1 : 1;
|
|
2192
|
+
const body = s[0] === "+" || s[0] === "-" ? s.slice(1) : s;
|
|
2193
|
+
const n = Number.parseInt(body, 8);
|
|
2194
|
+
return Number.isNaN(n) ? 0 : sign * n;
|
|
2195
|
+
}
|
|
2196
|
+
//#endregion
|
|
2197
|
+
//#region src/sprig/conversions/toRawJson.ts
|
|
2198
|
+
/**
|
|
2199
|
+
* `toRawJson v` — JSON-encode without HTML escaping. Go uses a json
|
|
2200
|
+
* encoder with `SetEscapeHTML(false)`; JS `JSON.stringify` does not
|
|
2201
|
+
* HTML-escape by default, so the function is a direct mapping.
|
|
2202
|
+
*
|
|
2203
|
+
* The undefined→"null" coercion matches Go's `encoding/json` (which
|
|
2204
|
+
* encodes untyped-nil as `null`); JS would otherwise return
|
|
2205
|
+
* `undefined` and break callers expecting a string.
|
|
2206
|
+
*/
|
|
2207
|
+
function toRawJson(value) {
|
|
2208
|
+
return JSON.stringify(value) ?? "null";
|
|
2209
|
+
}
|
|
2210
|
+
//#endregion
|
|
2211
|
+
//#region src/sprig/conversions/toString.ts
|
|
2212
|
+
/**
|
|
2213
|
+
* `toString v` — Go sprig's `strval`. Strings pass through; everything
|
|
2214
|
+
* else routes through Go's `%v` formatter (`fmt.Sprintf("%v", v)`).
|
|
2215
|
+
*
|
|
2216
|
+
* [LAW:one-source-of-truth] Shares `formatV` with printf's `%v` verb —
|
|
2217
|
+
* one place owns "what does Go's %v look like".
|
|
2218
|
+
*/
|
|
2219
|
+
function toString(v) {
|
|
2220
|
+
return typeof v === "string" ? v : formatV(v);
|
|
2221
|
+
}
|
|
2222
|
+
//#endregion
|
|
2223
|
+
//#region src/sprig/conversions/toStrings.ts
|
|
2224
|
+
/**
|
|
2225
|
+
* `toStrings list` — map each element through `toString`.
|
|
2226
|
+
*
|
|
2227
|
+
* The `"list"` gate validates array-ness once; this body trusts it
|
|
2228
|
+
* and only routes the per-element conversion.
|
|
2229
|
+
*/
|
|
2230
|
+
function toStrings(list) {
|
|
2231
|
+
return list.map(toString);
|
|
2232
|
+
}
|
|
2233
|
+
//#endregion
|
|
2234
|
+
//#region src/sprig/conversions/index.ts
|
|
2235
|
+
function sprigConversions() {
|
|
2236
|
+
return {
|
|
2237
|
+
atoi: {
|
|
2238
|
+
fn: (s) => atoi(s),
|
|
2239
|
+
argTypes: ["string"],
|
|
2240
|
+
returnType: "number"
|
|
2241
|
+
},
|
|
2242
|
+
int: {
|
|
2243
|
+
fn: (v) => int(v),
|
|
2244
|
+
argTypes: ["value"],
|
|
2245
|
+
returnType: "number"
|
|
2246
|
+
},
|
|
2247
|
+
int64: {
|
|
2248
|
+
fn: (v) => int64(v),
|
|
2249
|
+
argTypes: ["value"]
|
|
2250
|
+
},
|
|
2251
|
+
float64: {
|
|
2252
|
+
fn: (v) => float64(v),
|
|
2253
|
+
argTypes: ["value"],
|
|
2254
|
+
returnType: "number"
|
|
2255
|
+
},
|
|
2256
|
+
toString: {
|
|
2257
|
+
fn: (v) => toString(v),
|
|
2258
|
+
argTypes: ["value"],
|
|
2259
|
+
returnType: "string"
|
|
2260
|
+
},
|
|
2261
|
+
toStrings: {
|
|
2262
|
+
fn: (l) => toStrings(l),
|
|
2263
|
+
argTypes: ["list"]
|
|
2264
|
+
},
|
|
2265
|
+
toDecimal: {
|
|
2266
|
+
fn: (s) => toDecimal(s),
|
|
2267
|
+
argTypes: ["string"],
|
|
2268
|
+
returnType: "number"
|
|
2269
|
+
},
|
|
2270
|
+
toRawJson: {
|
|
2271
|
+
fn: (v) => toRawJson(v),
|
|
2272
|
+
argTypes: ["serializable"],
|
|
2273
|
+
returnType: "string"
|
|
2274
|
+
}
|
|
2275
|
+
};
|
|
2276
|
+
}
|
|
2277
|
+
//#endregion
|
|
2278
|
+
//#region src/sprig/defaults/empty.ts
|
|
2279
|
+
/**
|
|
2280
|
+
* `empty val` — true if `val` is "empty" per Go sprig's rules:
|
|
2281
|
+
* nil, false, 0, 0.0, "", empty array/Map/object.
|
|
2282
|
+
*
|
|
2283
|
+
* Note: `empty 0` is true (this surprises newcomers — Go sprig matches
|
|
2284
|
+
* Go's reflect-IsZero semantics).
|
|
2285
|
+
*/
|
|
2286
|
+
function empty(value) {
|
|
2287
|
+
if (value === null || value === void 0) return true;
|
|
2288
|
+
if (value === false) return true;
|
|
2289
|
+
if (typeof value === "number") return value === 0 || Number.isNaN(value);
|
|
2290
|
+
if (typeof value === "bigint") return value === 0n;
|
|
2291
|
+
if (typeof value === "string") return value.length === 0;
|
|
2292
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
2293
|
+
if (value instanceof Map) return value.size === 0;
|
|
2294
|
+
if (value instanceof Set) return value.size === 0;
|
|
2295
|
+
if (typeof value === "object") return Object.keys(value).length === 0;
|
|
2296
|
+
return false;
|
|
2297
|
+
}
|
|
2298
|
+
//#endregion
|
|
2299
|
+
//#region src/sprig/defaults/coalesce.ts
|
|
2300
|
+
/**
|
|
2301
|
+
* `coalesce a b c …` — returns the first non-empty argument, or
|
|
2302
|
+
* undefined if none are non-empty.
|
|
2303
|
+
*/
|
|
2304
|
+
function coalesce(...values) {
|
|
2305
|
+
for (const v of values) if (!empty(v)) return v;
|
|
2306
|
+
}
|
|
2307
|
+
//#endregion
|
|
2308
|
+
//#region src/sprig/defaults/default.ts
|
|
2309
|
+
/**
|
|
2310
|
+
* `default defaultVal val` — returns `val` if non-empty (per `empty`),
|
|
2311
|
+
* else `defaultVal`.
|
|
2312
|
+
*
|
|
2313
|
+
* Argument order matches Go sprig: the *default* comes first, the
|
|
2314
|
+
* value comes second. Pipelines feed the trailing arg, so
|
|
2315
|
+
* `{{ .name | default "anonymous" }}` evaluates default("anonymous", .name).
|
|
2316
|
+
*/
|
|
2317
|
+
function defaultFn(defaultVal, value) {
|
|
2318
|
+
return empty(value) ? defaultVal : value;
|
|
2319
|
+
}
|
|
2320
|
+
//#endregion
|
|
2321
|
+
//#region src/sprig/defaults/fromJson.ts
|
|
2322
|
+
/**
|
|
2323
|
+
* `fromJson s` — parses a JSON string into a value.
|
|
2324
|
+
*
|
|
2325
|
+
* Returns the parsed value. Throws if the input is not valid JSON,
|
|
2326
|
+
* matching Go sprig's behaviour (Go sprig propagates the parse error).
|
|
2327
|
+
*/
|
|
2328
|
+
function fromJson(input) {
|
|
2329
|
+
return JSON.parse(input);
|
|
2330
|
+
}
|
|
2331
|
+
//#endregion
|
|
2332
|
+
//#region src/sprig/defaults/ternary.ts
|
|
2333
|
+
/**
|
|
2334
|
+
* `ternary trueVal falseVal cond` — returns `trueVal` if `cond` is
|
|
2335
|
+
* truthy, else `falseVal`.
|
|
2336
|
+
*
|
|
2337
|
+
* Note: argument order matches Go sprig and surprises newcomers.
|
|
2338
|
+
* Pipelines feed cond as the trailing arg, e.g.
|
|
2339
|
+
* `{{ .ok | ternary "YES" "NO" }}` → ternary("YES", "NO", .ok)
|
|
2340
|
+
*/
|
|
2341
|
+
function ternary(trueVal, falseVal, cond) {
|
|
2342
|
+
return isTruthy(cond) ? trueVal : falseVal;
|
|
2343
|
+
}
|
|
2344
|
+
//#endregion
|
|
2345
|
+
//#region src/sprig/defaults/toJson.ts
|
|
2346
|
+
/**
|
|
2347
|
+
* `toJson val` — serializes a value to compact JSON.
|
|
2348
|
+
*
|
|
2349
|
+
* Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that
|
|
2350
|
+
* `JSON.stringify(undefined)` is undefined; we coerce that to "null"
|
|
2351
|
+
* for byte-equivalence with Go's encoding/json (which encodes
|
|
2352
|
+
* untyped-nil as null).
|
|
2353
|
+
*/
|
|
2354
|
+
function toJson(value) {
|
|
2355
|
+
return JSON.stringify(value) ?? "null";
|
|
2356
|
+
}
|
|
2357
|
+
//#endregion
|
|
2358
|
+
//#region src/sprig/defaults/toPrettyJson.ts
|
|
2359
|
+
/**
|
|
2360
|
+
* `toPrettyJson val` — JSON with 2-space indentation, matching Go
|
|
2361
|
+
* sprig's output exactly.
|
|
2362
|
+
*/
|
|
2363
|
+
function toPrettyJson(value) {
|
|
2364
|
+
return JSON.stringify(value, null, 2) ?? "null";
|
|
2365
|
+
}
|
|
2366
|
+
//#endregion
|
|
2367
|
+
//#region src/sprig/defaults/index.ts
|
|
2368
|
+
function sprigDefaults() {
|
|
2369
|
+
return {
|
|
2370
|
+
default: {
|
|
2371
|
+
fn: (a, b) => defaultFn(a, b),
|
|
2372
|
+
argTypes: ["value", "truthy"]
|
|
2373
|
+
},
|
|
2374
|
+
empty: {
|
|
2375
|
+
fn: (v) => empty(v),
|
|
2376
|
+
argTypes: ["truthy"]
|
|
2377
|
+
},
|
|
2378
|
+
coalesce: {
|
|
2379
|
+
fn: (...vs) => coalesce(...vs),
|
|
2380
|
+
argTypes: ["truthy"]
|
|
2381
|
+
},
|
|
2382
|
+
ternary: {
|
|
2383
|
+
fn: (a, b, c) => ternary(a, b, c),
|
|
2384
|
+
argTypes: [
|
|
2385
|
+
"value",
|
|
2386
|
+
"value",
|
|
2387
|
+
"truthy"
|
|
2388
|
+
]
|
|
2389
|
+
},
|
|
2390
|
+
fromJson: {
|
|
2391
|
+
fn: (s) => fromJson(s),
|
|
2392
|
+
argTypes: ["string"]
|
|
2393
|
+
},
|
|
2394
|
+
toJson: {
|
|
2395
|
+
fn: (v) => toJson(v),
|
|
2396
|
+
argTypes: ["serializable"],
|
|
2397
|
+
returnType: "string"
|
|
2398
|
+
},
|
|
2399
|
+
toPrettyJson: {
|
|
2400
|
+
fn: (v) => toPrettyJson(v),
|
|
2401
|
+
argTypes: ["serializable"],
|
|
2402
|
+
returnType: "string"
|
|
2403
|
+
}
|
|
2404
|
+
};
|
|
2405
|
+
}
|
|
2406
|
+
//#endregion
|
|
2407
|
+
//#region src/sprig/dicts/dict.ts
|
|
2408
|
+
/**
|
|
2409
|
+
* `dict k1 v1 k2 v2 …` — builds a record from alternating key/value pairs.
|
|
2410
|
+
*
|
|
2411
|
+
* [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates
|
|
2412
|
+
* the kv cycle via `argTypePattern: "alternating"` against
|
|
2413
|
+
* `argTypes: ["string", "value"]`, so every key position is a string by
|
|
2414
|
+
* the time the body runs. The body trusts the gate; no per-key probe.
|
|
2415
|
+
*
|
|
2416
|
+
* Odd-length call (`dict "a"`) leaves the last value `undefined` —
|
|
2417
|
+
* matches Go sprig.
|
|
2418
|
+
*/
|
|
2419
|
+
function dict(...kvs) {
|
|
2420
|
+
const out = {};
|
|
2421
|
+
for (let i = 0; i < kvs.length; i += 2) out[kvs[i]] = kvs[i + 1];
|
|
2422
|
+
return out;
|
|
2423
|
+
}
|
|
2424
|
+
//#endregion
|
|
2425
|
+
//#region src/sprig/dicts/get.ts
|
|
2426
|
+
/**
|
|
2427
|
+
* `get d key` — returns d[key] or undefined.
|
|
2428
|
+
*
|
|
2429
|
+
* [LAW:single-enforcer] The gate validates `d` is a plain object
|
|
2430
|
+
* (`"dict"`); the body trusts the receiver type. The Map case lives in
|
|
2431
|
+
* template-laws-3gt.7 (where the slot widens with an explicit Map-key
|
|
2432
|
+
* carve-out per audit B5/B6) — until then, Maps are rejected at the
|
|
2433
|
+
* gate.
|
|
2434
|
+
*/
|
|
2435
|
+
function get(d, key) {
|
|
2436
|
+
return d[key];
|
|
2437
|
+
}
|
|
2438
|
+
//#endregion
|
|
2439
|
+
//#region src/sprig/dicts/hasKey.ts
|
|
2440
|
+
/**
|
|
2441
|
+
* `hasKey d key` — true when `key` is a own-property of `d`.
|
|
2442
|
+
*
|
|
2443
|
+
* Note: sprig's name is `hasKey` though docs sometimes say `haskey`.
|
|
2444
|
+
* [LAW:single-enforcer] Receiver type validated at the gate.
|
|
2445
|
+
*/
|
|
2446
|
+
function hasKey(d, key) {
|
|
2447
|
+
return key in d;
|
|
2448
|
+
}
|
|
2449
|
+
//#endregion
|
|
2450
|
+
//#region src/sprig/dicts/keys.ts
|
|
2451
|
+
/**
|
|
2452
|
+
* `keys d` — list of own enumerable string keys.
|
|
2453
|
+
*
|
|
2454
|
+
* [LAW:single-enforcer] Receiver type validated at the gate (`"dict"`);
|
|
2455
|
+
* the body trusts the parameter. Maps are rejected by the dict gate —
|
|
2456
|
+
* closes audit finding B6 (no silent `String(key)` flattening of
|
|
2457
|
+
* typed-T Map keys, because Maps never reach this body).
|
|
2458
|
+
*/
|
|
2459
|
+
function keys(d) {
|
|
2460
|
+
return Object.keys(d);
|
|
2461
|
+
}
|
|
2462
|
+
//#endregion
|
|
2463
|
+
//#region src/sprig/dicts/merge.ts
|
|
2464
|
+
/**
|
|
2465
|
+
* `merge dst src1 src2 …` — copies missing keys from sources into dst,
|
|
2466
|
+
* leaving dst's existing keys untouched. Returns a new dict.
|
|
2467
|
+
*
|
|
2468
|
+
* [LAW:single-enforcer] Every dict slot is gated as `"dict"` (variadic
|
|
2469
|
+
* trailing-repeat), so dst and every source are plain objects by the
|
|
2470
|
+
* time the body runs.
|
|
2471
|
+
*/
|
|
2472
|
+
function merge(dst, ...sources) {
|
|
2473
|
+
const out = { ...dst };
|
|
2474
|
+
for (const s of sources) for (const [k, v] of Object.entries(s)) if (!(k in out)) out[k] = v;
|
|
2475
|
+
return out;
|
|
2476
|
+
}
|
|
2477
|
+
//#endregion
|
|
2478
|
+
//#region src/sprig/dicts/mergeOverwrite.ts
|
|
2479
|
+
/**
|
|
2480
|
+
* `mergeOverwrite dst src1 src2 …` — like `merge` but later sources
|
|
2481
|
+
* overwrite earlier values.
|
|
2482
|
+
*
|
|
2483
|
+
* [LAW:single-enforcer] Every dict slot is gated as `"dict"`.
|
|
2484
|
+
*/
|
|
2485
|
+
function mergeOverwrite(dst, ...sources) {
|
|
2486
|
+
const out = { ...dst };
|
|
2487
|
+
for (const s of sources) Object.assign(out, s);
|
|
2488
|
+
return out;
|
|
2489
|
+
}
|
|
2490
|
+
//#endregion
|
|
2491
|
+
//#region src/sprig/dicts/omit.ts
|
|
2492
|
+
/**
|
|
2493
|
+
* `omit d k1 k2 …` — sub-dict with the listed keys removed.
|
|
2494
|
+
*
|
|
2495
|
+
* [LAW:single-enforcer] Receiver type validated at the gate.
|
|
2496
|
+
*/
|
|
2497
|
+
function omit(d, ...drop) {
|
|
2498
|
+
const set = new Set(drop);
|
|
2499
|
+
const out = {};
|
|
2500
|
+
for (const [k, v] of Object.entries(d)) if (!set.has(k)) out[k] = v;
|
|
2501
|
+
return out;
|
|
2502
|
+
}
|
|
2503
|
+
//#endregion
|
|
2504
|
+
//#region src/sprig/dicts/pick.ts
|
|
2505
|
+
/**
|
|
2506
|
+
* `pick d k1 k2 …` — sub-dict with only the listed keys.
|
|
2507
|
+
*
|
|
2508
|
+
* [LAW:single-enforcer] Receiver type validated at the gate.
|
|
2509
|
+
*/
|
|
2510
|
+
function pick(d, ...wanted) {
|
|
2511
|
+
const out = {};
|
|
2512
|
+
for (const key of wanted) if (key in d) out[key] = d[key];
|
|
2513
|
+
return out;
|
|
2514
|
+
}
|
|
2515
|
+
//#endregion
|
|
2516
|
+
//#region src/sprig/dicts/pluck.ts
|
|
2517
|
+
/**
|
|
2518
|
+
* `pluck key d1 d2 …` — collect d[key] from each dict that has it.
|
|
2519
|
+
*
|
|
2520
|
+
* [LAW:single-enforcer] Every dict slot is gated as `"dict"`; the body
|
|
2521
|
+
* trusts each receiver and skips entries that lack the key.
|
|
2522
|
+
*/
|
|
2523
|
+
function pluck(key, ...dicts) {
|
|
2524
|
+
const out = [];
|
|
2525
|
+
for (const d of dicts) if (key in d) out.push(d[key]);
|
|
2526
|
+
return out;
|
|
2527
|
+
}
|
|
2528
|
+
//#endregion
|
|
2529
|
+
//#region src/sprig/dicts/set.ts
|
|
2530
|
+
/**
|
|
2531
|
+
* `set d key value` — mutates the receiver to bind `key=value` and
|
|
2532
|
+
* returns it. Matches Go sprig: the receiver and the returned value
|
|
2533
|
+
* are the same dict.
|
|
2534
|
+
*
|
|
2535
|
+
* [LAW:single-enforcer] Non-dict receivers are rejected at the gate
|
|
2536
|
+
* (`argTypes: ["dict", "string", "value"]`); the body trusts the
|
|
2537
|
+
* receiver type. The previous body-level `bodyTypeMismatch` (working-
|
|
2538
|
+
* tree fix in template-laws-703.10) became dead code once the slot
|
|
2539
|
+
* declared `"dict"` and was deleted in template-laws-3gt.3.
|
|
2540
|
+
*/
|
|
2541
|
+
function set(d, key, value) {
|
|
2542
|
+
d[key] = value;
|
|
2543
|
+
return d;
|
|
2544
|
+
}
|
|
2545
|
+
//#endregion
|
|
2546
|
+
//#region src/sprig/dicts/unset.ts
|
|
2547
|
+
/**
|
|
2548
|
+
* `unset d key` — mutates the receiver to drop `key` and returns it.
|
|
2549
|
+
* Matches Go sprig: the receiver and the returned value are the same
|
|
2550
|
+
* dict.
|
|
2551
|
+
*
|
|
2552
|
+
* [LAW:single-enforcer] Non-dict receivers are rejected at the gate;
|
|
2553
|
+
* see `set.ts` for the rationale.
|
|
2554
|
+
*/
|
|
2555
|
+
function unset(d, key) {
|
|
2556
|
+
delete d[key];
|
|
2557
|
+
return d;
|
|
2558
|
+
}
|
|
2559
|
+
//#endregion
|
|
2560
|
+
//#region src/sprig/dicts/values.ts
|
|
2561
|
+
/**
|
|
2562
|
+
* `values d` — list of own enumerable values.
|
|
2563
|
+
*
|
|
2564
|
+
* [LAW:single-enforcer] Receiver type validated at the gate.
|
|
2565
|
+
*/
|
|
2566
|
+
function values(d) {
|
|
2567
|
+
return Object.values(d);
|
|
2568
|
+
}
|
|
2569
|
+
//#endregion
|
|
2570
|
+
//#region src/sprig/dicts/index.ts
|
|
2571
|
+
function sprigDicts() {
|
|
2572
|
+
return {
|
|
2573
|
+
dict: {
|
|
2574
|
+
fn: (...kv) => dict(...kv),
|
|
2575
|
+
argTypes: ["string", "value"],
|
|
2576
|
+
argTypePattern: "alternating"
|
|
2577
|
+
},
|
|
2578
|
+
get: {
|
|
2579
|
+
fn: (d, k) => get(d, k),
|
|
2580
|
+
argTypes: ["dict", "string"]
|
|
2581
|
+
},
|
|
2582
|
+
set: {
|
|
2583
|
+
fn: (d, k, v) => set(d, k, v),
|
|
2584
|
+
argTypes: [
|
|
2585
|
+
"dict",
|
|
2586
|
+
"string",
|
|
2587
|
+
"value"
|
|
2588
|
+
]
|
|
2589
|
+
},
|
|
2590
|
+
unset: {
|
|
2591
|
+
fn: (d, k) => unset(d, k),
|
|
2592
|
+
argTypes: ["dict", "string"]
|
|
2593
|
+
},
|
|
2594
|
+
keys: {
|
|
2595
|
+
fn: (d) => keys(d),
|
|
2596
|
+
argTypes: ["dict"]
|
|
2597
|
+
},
|
|
2598
|
+
values: {
|
|
2599
|
+
fn: (d) => values(d),
|
|
2600
|
+
argTypes: ["dict"]
|
|
2601
|
+
},
|
|
2602
|
+
pluck: {
|
|
2603
|
+
fn: (k, ...d) => pluck(k, ...d),
|
|
2604
|
+
argTypes: ["string", "dict"]
|
|
2605
|
+
},
|
|
2606
|
+
pick: {
|
|
2607
|
+
fn: (d, ...k) => pick(d, ...k),
|
|
2608
|
+
argTypes: ["dict", "string"]
|
|
2609
|
+
},
|
|
2610
|
+
omit: {
|
|
2611
|
+
fn: (d, ...k) => omit(d, ...k),
|
|
2612
|
+
argTypes: ["dict", "string"]
|
|
2613
|
+
},
|
|
2614
|
+
hasKey: {
|
|
2615
|
+
fn: (d, k) => hasKey(d, k),
|
|
2616
|
+
argTypes: ["dict", "string"]
|
|
2617
|
+
},
|
|
2618
|
+
merge: {
|
|
2619
|
+
fn: (d, ...s) => merge(d, ...s),
|
|
2620
|
+
argTypes: ["dict"]
|
|
2621
|
+
},
|
|
2622
|
+
mergeOverwrite: {
|
|
2623
|
+
fn: (d, ...s) => mergeOverwrite(d, ...s),
|
|
2624
|
+
argTypes: ["dict"]
|
|
2625
|
+
}
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
//#endregion
|
|
2629
|
+
//#region src/sprig/lists/append.ts
|
|
2630
|
+
/** `append list item` — add item at the end. */
|
|
2631
|
+
function append(list, item) {
|
|
2632
|
+
return [...list, item];
|
|
2633
|
+
}
|
|
2634
|
+
//#endregion
|
|
2635
|
+
//#region src/sprig/lists/chunk.ts
|
|
2636
|
+
/** `chunk size list` — split list into sub-lists of `size`. */
|
|
2637
|
+
function chunk(size, list) {
|
|
2638
|
+
const n = Math.max(1, Math.trunc(Number(size)));
|
|
2639
|
+
const out = [];
|
|
2640
|
+
for (let i = 0; i < list.length; i += n) out.push(list.slice(i, i + n));
|
|
2641
|
+
return out;
|
|
2642
|
+
}
|
|
2643
|
+
//#endregion
|
|
2644
|
+
//#region src/sprig/lists/compact.ts
|
|
2645
|
+
/** `compact list` — drop empty values per sprig's `empty` rules. */
|
|
2646
|
+
function compact(list) {
|
|
2647
|
+
return list.filter((v) => !empty(v));
|
|
2648
|
+
}
|
|
2649
|
+
//#endregion
|
|
2650
|
+
//#region src/sprig/lists/concat.ts
|
|
2651
|
+
/** `concat a b c …` — flat-concat lists. */
|
|
2652
|
+
function concat(...lists) {
|
|
2653
|
+
const out = [];
|
|
2654
|
+
for (const l of lists) out.push(...l);
|
|
2655
|
+
return out;
|
|
2656
|
+
}
|
|
2657
|
+
//#endregion
|
|
2658
|
+
//#region src/sprig/lists/first.ts
|
|
2659
|
+
function first(list) {
|
|
2660
|
+
return list[0];
|
|
2661
|
+
}
|
|
2662
|
+
//#endregion
|
|
2663
|
+
//#region src/sprig/lists/has.ts
|
|
2664
|
+
/** `has item list` — true iff `item` ∈ `list`. Note arg order matches Go sprig. */
|
|
2665
|
+
function has(item, list) {
|
|
2666
|
+
return list.some((e) => deepEqual(e, item));
|
|
2667
|
+
}
|
|
2668
|
+
//#endregion
|
|
2669
|
+
//#region src/sprig/lists/initial.ts
|
|
2670
|
+
/** All elements except the last. */
|
|
2671
|
+
function initial(list) {
|
|
2672
|
+
return list.slice(0, -1);
|
|
2673
|
+
}
|
|
2674
|
+
//#endregion
|
|
2675
|
+
//#region src/sprig/lists/last.ts
|
|
2676
|
+
function last(list) {
|
|
2677
|
+
return list[list.length - 1];
|
|
2678
|
+
}
|
|
2679
|
+
//#endregion
|
|
2680
|
+
//#region src/sprig/lists/len.ts
|
|
2681
|
+
/**
|
|
2682
|
+
* Sprig `len` — same shape as the evaluator's built-in `len`. Re-exposed
|
|
2683
|
+
* here so the sprig category is self-contained per the epic's required
|
|
2684
|
+
* layout.
|
|
2685
|
+
*
|
|
2686
|
+
* [LAW:single-enforcer] Sized-kind validation lives at the gate via
|
|
2687
|
+
* argTypes: ["sized"]. The body picks the per-kind readout; nil and
|
|
2688
|
+
* non-sized values are rejected once by `enforceArgTypes`, never here.
|
|
2689
|
+
*/
|
|
2690
|
+
function len(value) {
|
|
2691
|
+
if (Array.isArray(value)) return value.length;
|
|
2692
|
+
if (typeof value === "string") return value.length;
|
|
2693
|
+
if (value instanceof Map) return value.size;
|
|
2694
|
+
if (value instanceof Set) return value.size;
|
|
2695
|
+
return Object.keys(value).length;
|
|
2696
|
+
}
|
|
2697
|
+
//#endregion
|
|
2698
|
+
//#region src/sprig/lists/list.ts
|
|
2699
|
+
/** `list a b c …` — constructs a list from the given items. */
|
|
2700
|
+
function list(...items) {
|
|
2701
|
+
return items;
|
|
2702
|
+
}
|
|
2703
|
+
//#endregion
|
|
2704
|
+
//#region src/sprig/lists/prepend.ts
|
|
2705
|
+
/** `prepend list item` — add item at the front. */
|
|
2706
|
+
function prepend(list, item) {
|
|
2707
|
+
return [item, ...list];
|
|
2708
|
+
}
|
|
2709
|
+
//#endregion
|
|
2710
|
+
//#region src/sprig/lists/rest.ts
|
|
2711
|
+
/** All elements except the first. */
|
|
2712
|
+
function rest(list) {
|
|
2713
|
+
return list.slice(1);
|
|
2714
|
+
}
|
|
2715
|
+
//#endregion
|
|
2716
|
+
//#region src/sprig/lists/reverse.ts
|
|
2717
|
+
function reverse(list) {
|
|
2718
|
+
return [...list].reverse();
|
|
2719
|
+
}
|
|
2720
|
+
//#endregion
|
|
2721
|
+
//#region src/sprig/lists/slice.ts
|
|
2722
|
+
/** `slice list [i [j]]` — Array.prototype.slice. */
|
|
2723
|
+
function slice(list, i, j) {
|
|
2724
|
+
const start = i === void 0 ? 0 : Number(i);
|
|
2725
|
+
const end = j === void 0 ? list.length : Number(j);
|
|
2726
|
+
return list.slice(start, end);
|
|
2727
|
+
}
|
|
2728
|
+
//#endregion
|
|
2729
|
+
//#region src/sprig/lists/uniq.ts
|
|
2730
|
+
/** Unique values, preserving first-occurrence order. */
|
|
2731
|
+
function uniq(list) {
|
|
2732
|
+
const out = [];
|
|
2733
|
+
for (const v of list) if (!out.some((e) => deepEqual(e, v))) out.push(v);
|
|
2734
|
+
return out;
|
|
2735
|
+
}
|
|
2736
|
+
//#endregion
|
|
2737
|
+
//#region src/sprig/lists/without.ts
|
|
2738
|
+
/** `without list a b c …` — drop any of a/b/c… from list. */
|
|
2739
|
+
function without(list, ...exclude) {
|
|
2740
|
+
return list.filter((v) => !exclude.some((e) => deepEqual(e, v)));
|
|
2741
|
+
}
|
|
2742
|
+
//#endregion
|
|
2743
|
+
//#region src/sprig/lists/index.ts
|
|
2744
|
+
function sprigLists() {
|
|
2745
|
+
return {
|
|
2746
|
+
list: {
|
|
2747
|
+
fn: (...a) => list(...a),
|
|
2748
|
+
argTypes: ["value"]
|
|
2749
|
+
},
|
|
2750
|
+
first: {
|
|
2751
|
+
fn: (l) => first(l),
|
|
2752
|
+
argTypes: ["list"]
|
|
2753
|
+
},
|
|
2754
|
+
last: {
|
|
2755
|
+
fn: (l) => last(l),
|
|
2756
|
+
argTypes: ["list"]
|
|
2757
|
+
},
|
|
2758
|
+
rest: {
|
|
2759
|
+
fn: (l) => rest(l),
|
|
2760
|
+
argTypes: ["list"]
|
|
2761
|
+
},
|
|
2762
|
+
initial: {
|
|
2763
|
+
fn: (l) => initial(l),
|
|
2764
|
+
argTypes: ["list"]
|
|
2765
|
+
},
|
|
2766
|
+
len: {
|
|
2767
|
+
fn: (l) => len(l),
|
|
2768
|
+
argTypes: ["sized"]
|
|
2769
|
+
},
|
|
2770
|
+
reverse: {
|
|
2771
|
+
fn: (l) => reverse(l),
|
|
2772
|
+
argTypes: ["list"]
|
|
2773
|
+
},
|
|
2774
|
+
uniq: {
|
|
2775
|
+
fn: (l) => uniq(l),
|
|
2776
|
+
argTypes: ["list"]
|
|
2777
|
+
},
|
|
2778
|
+
without: {
|
|
2779
|
+
fn: (l, ...e) => without(l, ...e),
|
|
2780
|
+
argTypes: ["list", "value"]
|
|
2781
|
+
},
|
|
2782
|
+
has: {
|
|
2783
|
+
fn: (i, l) => has(i, l),
|
|
2784
|
+
argTypes: ["value", "list"]
|
|
2785
|
+
},
|
|
2786
|
+
compact: {
|
|
2787
|
+
fn: (l) => compact(l),
|
|
2788
|
+
argTypes: ["list"]
|
|
2789
|
+
},
|
|
2790
|
+
slice: {
|
|
2791
|
+
fn: (l, i, j) => slice(l, i, j),
|
|
2792
|
+
argTypes: [
|
|
2793
|
+
"list",
|
|
2794
|
+
"number",
|
|
2795
|
+
"number"
|
|
2796
|
+
]
|
|
2797
|
+
},
|
|
2798
|
+
concat: {
|
|
2799
|
+
fn: (...l) => concat(...l),
|
|
2800
|
+
argTypes: ["list"]
|
|
2801
|
+
},
|
|
2802
|
+
chunk: {
|
|
2803
|
+
fn: (s, l) => chunk(s, l),
|
|
2804
|
+
argTypes: ["number", "list"]
|
|
2805
|
+
},
|
|
2806
|
+
prepend: {
|
|
2807
|
+
fn: (l, i) => prepend(l, i),
|
|
2808
|
+
argTypes: ["list", "value"]
|
|
2809
|
+
},
|
|
2810
|
+
append: {
|
|
2811
|
+
fn: (l, i) => append(l, i),
|
|
2812
|
+
argTypes: ["list", "value"]
|
|
2813
|
+
}
|
|
2814
|
+
};
|
|
2815
|
+
}
|
|
2816
|
+
//#endregion
|
|
2817
|
+
//#region src/sprig/math/add.ts
|
|
2818
|
+
/** `add a b c …` — variadic integer sum. */
|
|
2819
|
+
function add(...args) {
|
|
2820
|
+
return args.reduce((acc, v) => acc + Math.trunc(Number(v)), 0);
|
|
2821
|
+
}
|
|
2822
|
+
//#endregion
|
|
2823
|
+
//#region src/sprig/math/addf.ts
|
|
2824
|
+
function addf(...args) {
|
|
2825
|
+
return args.reduce((acc, v) => acc + Number(v), 0);
|
|
2826
|
+
}
|
|
2827
|
+
//#endregion
|
|
2828
|
+
//#region src/sprig/math/ceil.ts
|
|
2829
|
+
function ceil(a) {
|
|
2830
|
+
return Math.ceil(Number(a));
|
|
2831
|
+
}
|
|
2832
|
+
//#endregion
|
|
2833
|
+
//#region src/sprig/math/div.ts
|
|
2834
|
+
/** `div a b` — integer division (Go semantics: truncate toward zero). */
|
|
2835
|
+
function div(a, b) {
|
|
2836
|
+
return Math.trunc(Math.trunc(Number(a)) / Math.trunc(Number(b)));
|
|
2837
|
+
}
|
|
2838
|
+
//#endregion
|
|
2839
|
+
//#region src/sprig/math/divf.ts
|
|
2840
|
+
function divf(a, b) {
|
|
2841
|
+
return Number(a) / Number(b);
|
|
2842
|
+
}
|
|
2843
|
+
//#endregion
|
|
2844
|
+
//#region src/sprig/math/floor.ts
|
|
2845
|
+
function floor(a) {
|
|
2846
|
+
return Math.floor(Number(a));
|
|
2847
|
+
}
|
|
2848
|
+
//#endregion
|
|
2849
|
+
//#region src/sprig/math/max.ts
|
|
2850
|
+
/** `max a b c …` — variadic maximum. */
|
|
2851
|
+
function max(...args) {
|
|
2852
|
+
return args.map((v) => Number(v)).reduce((m, v) => v > m ? v : m, Number.NEGATIVE_INFINITY);
|
|
2853
|
+
}
|
|
2854
|
+
//#endregion
|
|
2855
|
+
//#region src/sprig/math/min.ts
|
|
2856
|
+
/** `min a b c …` — variadic minimum. */
|
|
2857
|
+
function min(...args) {
|
|
2858
|
+
return args.map((v) => Number(v)).reduce((m, v) => v < m ? v : m, Number.POSITIVE_INFINITY);
|
|
2859
|
+
}
|
|
2860
|
+
//#endregion
|
|
2861
|
+
//#region src/sprig/math/mod.ts
|
|
2862
|
+
/** `mod a b` — modulo. JS `%` matches Go's: sign follows the dividend. */
|
|
2863
|
+
function mod(a, b) {
|
|
2864
|
+
return Math.trunc(Number(a)) % Math.trunc(Number(b));
|
|
2865
|
+
}
|
|
2866
|
+
//#endregion
|
|
2867
|
+
//#region src/sprig/math/mul.ts
|
|
2868
|
+
/** `mul a b c …` — variadic integer product. */
|
|
2869
|
+
function mul(...args) {
|
|
2870
|
+
return args.reduce((acc, v) => acc * Math.trunc(Number(v)), 1);
|
|
2871
|
+
}
|
|
2872
|
+
//#endregion
|
|
2873
|
+
//#region src/sprig/math/mulf.ts
|
|
2874
|
+
function mulf(...args) {
|
|
2875
|
+
return args.reduce((acc, v) => acc * Number(v), 1);
|
|
2876
|
+
}
|
|
2877
|
+
//#endregion
|
|
2878
|
+
//#region src/sprig/math/round.ts
|
|
2879
|
+
/** `round a [precision=0]` — round half-away-from-zero, matching Go sprig. */
|
|
2880
|
+
function round(a, precision = 0) {
|
|
2881
|
+
const n = Number(a);
|
|
2882
|
+
const factor = 10 ** Math.trunc(Number(precision));
|
|
2883
|
+
return Math.sign(n) * Math.round(Math.abs(n) * factor) / factor;
|
|
2884
|
+
}
|
|
2885
|
+
//#endregion
|
|
2886
|
+
//#region src/sprig/math/sub.ts
|
|
2887
|
+
function sub(a, b) {
|
|
2888
|
+
return Math.trunc(Number(a)) - Math.trunc(Number(b));
|
|
2889
|
+
}
|
|
2890
|
+
//#endregion
|
|
2891
|
+
//#region src/sprig/math/subf.ts
|
|
2892
|
+
function subf(a, b) {
|
|
2893
|
+
return Number(a) - Number(b);
|
|
2894
|
+
}
|
|
2895
|
+
//#endregion
|
|
2896
|
+
//#region src/sprig/math/index.ts
|
|
2897
|
+
function sprigMath() {
|
|
2898
|
+
return {
|
|
2899
|
+
add: {
|
|
2900
|
+
fn: (...a) => add(...a),
|
|
2901
|
+
argTypes: ["number"]
|
|
2902
|
+
},
|
|
2903
|
+
sub: {
|
|
2904
|
+
fn: (a, b) => sub(a, b),
|
|
2905
|
+
argTypes: ["number", "number"]
|
|
2906
|
+
},
|
|
2907
|
+
mul: {
|
|
2908
|
+
fn: (...a) => mul(...a),
|
|
2909
|
+
argTypes: ["number"]
|
|
2910
|
+
},
|
|
2911
|
+
div: {
|
|
2912
|
+
fn: (a, b) => div(a, b),
|
|
2913
|
+
argTypes: ["number", "number"]
|
|
2914
|
+
},
|
|
2915
|
+
mod: {
|
|
2916
|
+
fn: (a, b) => mod(a, b),
|
|
2917
|
+
argTypes: ["number", "number"]
|
|
2918
|
+
},
|
|
2919
|
+
min: {
|
|
2920
|
+
fn: (...a) => min(...a),
|
|
2921
|
+
argTypes: ["number"]
|
|
2922
|
+
},
|
|
2923
|
+
max: {
|
|
2924
|
+
fn: (...a) => max(...a),
|
|
2925
|
+
argTypes: ["number"]
|
|
2926
|
+
},
|
|
2927
|
+
floor: {
|
|
2928
|
+
fn: (a) => floor(a),
|
|
2929
|
+
argTypes: ["number"]
|
|
2930
|
+
},
|
|
2931
|
+
ceil: {
|
|
2932
|
+
fn: (a) => ceil(a),
|
|
2933
|
+
argTypes: ["number"]
|
|
2934
|
+
},
|
|
2935
|
+
round: {
|
|
2936
|
+
fn: (a, p) => round(a, p),
|
|
2937
|
+
argTypes: ["number", "number"]
|
|
2938
|
+
},
|
|
2939
|
+
addf: {
|
|
2940
|
+
fn: (...a) => addf(...a),
|
|
2941
|
+
argTypes: ["number"]
|
|
2942
|
+
},
|
|
2943
|
+
subf: {
|
|
2944
|
+
fn: (a, b) => subf(a, b),
|
|
2945
|
+
argTypes: ["number", "number"]
|
|
2946
|
+
},
|
|
2947
|
+
mulf: {
|
|
2948
|
+
fn: (...a) => mulf(...a),
|
|
2949
|
+
argTypes: ["number"]
|
|
2950
|
+
},
|
|
2951
|
+
divf: {
|
|
2952
|
+
fn: (a, b) => divf(a, b),
|
|
2953
|
+
argTypes: ["number", "number"]
|
|
2954
|
+
}
|
|
2955
|
+
};
|
|
2956
|
+
}
|
|
2957
|
+
//#endregion
|
|
2958
|
+
//#region src/sprig/regex/regexFind.ts
|
|
2959
|
+
/** `regexFind pattern s` — first match, or "" when no match. */
|
|
2960
|
+
function regexFind(pattern, s) {
|
|
2961
|
+
const m = new RegExp(pattern).exec(s);
|
|
2962
|
+
return m ? m[0] : "";
|
|
2963
|
+
}
|
|
2964
|
+
//#endregion
|
|
2965
|
+
//#region src/sprig/regex/regexFindAll.ts
|
|
2966
|
+
/**
|
|
2967
|
+
* `regexFindAll pattern s n` — first `n` matches (or all if n<0).
|
|
2968
|
+
* Mirrors Go sprig's signature: pattern, s, then optional n.
|
|
2969
|
+
*/
|
|
2970
|
+
function regexFindAll(pattern, s, n = -1) {
|
|
2971
|
+
const re = new RegExp(pattern, "g");
|
|
2972
|
+
const limit = Number(n);
|
|
2973
|
+
const out = [];
|
|
2974
|
+
for (const m of s.matchAll(re)) {
|
|
2975
|
+
out.push(m[0]);
|
|
2976
|
+
if (limit >= 0 && out.length >= limit) break;
|
|
2977
|
+
}
|
|
2978
|
+
return out;
|
|
2979
|
+
}
|
|
2980
|
+
//#endregion
|
|
2981
|
+
//#region src/sprig/regex/regexMatch.ts
|
|
2982
|
+
/** `regexMatch pattern s` — true iff JS regex matches anywhere in s. */
|
|
2983
|
+
function regexMatch(pattern, s) {
|
|
2984
|
+
return new RegExp(pattern).test(s);
|
|
2985
|
+
}
|
|
2986
|
+
//#endregion
|
|
2987
|
+
//#region src/sprig/regex/regexReplaceAll.ts
|
|
2988
|
+
/**
|
|
2989
|
+
* `regexReplaceAll pattern s repl` — replace ALL pattern matches with
|
|
2990
|
+
* the replacement string. Replacement supports JS's $1/$2/$<name>
|
|
2991
|
+
* backreference syntax.
|
|
2992
|
+
*/
|
|
2993
|
+
function regexReplaceAll(pattern, s, repl) {
|
|
2994
|
+
return s.replace(new RegExp(pattern, "g"), repl);
|
|
2995
|
+
}
|
|
2996
|
+
//#endregion
|
|
2997
|
+
//#region src/sprig/regex/regexReplaceAllLiteral.ts
|
|
2998
|
+
/**
|
|
2999
|
+
* `regexReplaceAllLiteral` — like regexReplaceAll but the replacement
|
|
3000
|
+
* string is treated literally ($1/$2 are not expanded).
|
|
3001
|
+
*/
|
|
3002
|
+
function regexReplaceAllLiteral(pattern, s, repl) {
|
|
3003
|
+
const literal = repl.replace(/\$/g, "$$$$");
|
|
3004
|
+
return s.replace(new RegExp(pattern, "g"), literal);
|
|
3005
|
+
}
|
|
3006
|
+
//#endregion
|
|
3007
|
+
//#region src/sprig/regex/regexSplit.ts
|
|
3008
|
+
/** `regexSplit pattern s n` — split by regex, optional max count. */
|
|
3009
|
+
function regexSplit(pattern, s, n = -1) {
|
|
3010
|
+
const re = new RegExp(pattern);
|
|
3011
|
+
const limit = Number(n);
|
|
3012
|
+
if (limit < 0) return s.split(re);
|
|
3013
|
+
return s.split(re).slice(0, limit);
|
|
3014
|
+
}
|
|
3015
|
+
//#endregion
|
|
3016
|
+
//#region src/sprig/regex/index.ts
|
|
3017
|
+
function sprigRegex() {
|
|
3018
|
+
return {
|
|
3019
|
+
regexMatch: {
|
|
3020
|
+
fn: (p, s) => regexMatch(p, s),
|
|
3021
|
+
argTypes: ["string", "string"]
|
|
3022
|
+
},
|
|
3023
|
+
regexFind: {
|
|
3024
|
+
fn: (p, s) => regexFind(p, s),
|
|
3025
|
+
argTypes: ["string", "string"]
|
|
3026
|
+
},
|
|
3027
|
+
regexFindAll: {
|
|
3028
|
+
fn: (p, s, n) => regexFindAll(p, s, n),
|
|
3029
|
+
argTypes: [
|
|
3030
|
+
"string",
|
|
3031
|
+
"string",
|
|
3032
|
+
"number"
|
|
3033
|
+
]
|
|
3034
|
+
},
|
|
3035
|
+
regexReplaceAll: {
|
|
3036
|
+
fn: (p, s, r) => regexReplaceAll(p, s, r),
|
|
3037
|
+
argTypes: [
|
|
3038
|
+
"string",
|
|
3039
|
+
"string",
|
|
3040
|
+
"string"
|
|
3041
|
+
]
|
|
3042
|
+
},
|
|
3043
|
+
regexReplaceAllLiteral: {
|
|
3044
|
+
fn: (p, s, r) => regexReplaceAllLiteral(p, s, r),
|
|
3045
|
+
argTypes: [
|
|
3046
|
+
"string",
|
|
3047
|
+
"string",
|
|
3048
|
+
"string"
|
|
3049
|
+
]
|
|
3050
|
+
},
|
|
3051
|
+
regexSplit: {
|
|
3052
|
+
fn: (p, s, n) => regexSplit(p, s, n),
|
|
3053
|
+
argTypes: [
|
|
3054
|
+
"string",
|
|
3055
|
+
"string",
|
|
3056
|
+
"number"
|
|
3057
|
+
]
|
|
3058
|
+
}
|
|
3059
|
+
};
|
|
3060
|
+
}
|
|
3061
|
+
//#endregion
|
|
3062
|
+
//#region src/sprig/strings/abbrev.ts
|
|
3063
|
+
/**
|
|
3064
|
+
* `abbrev width s` — truncate `s` to `width` chars, replacing the tail
|
|
3065
|
+
* with `...` when truncation occurs. Width must be at least 4 to fit
|
|
3066
|
+
* the ellipsis; smaller widths return `s` unchanged (Go sprig
|
|
3067
|
+
* behavior).
|
|
3068
|
+
*/
|
|
3069
|
+
function abbrev(width, s) {
|
|
3070
|
+
const w = Number(width);
|
|
3071
|
+
if (s.length <= w) return s;
|
|
3072
|
+
if (w < 4) return s;
|
|
3073
|
+
return `${s.slice(0, w - 3)}...`;
|
|
3074
|
+
}
|
|
3075
|
+
//#endregion
|
|
3076
|
+
//#region src/sprig/strings/abbrevboth.ts
|
|
3077
|
+
/**
|
|
3078
|
+
* `abbrevboth left right s` — abbreviate from both ends, leaving `...`
|
|
3079
|
+
* around the visible window. Mirrors Go sprig's abbrevboth semantics:
|
|
3080
|
+
* left/right specify offsets (0-indexed); the result has `...` around
|
|
3081
|
+
* a slice taken between them.
|
|
3082
|
+
*/
|
|
3083
|
+
function abbrevboth(left, right, s) {
|
|
3084
|
+
const l = Number(left);
|
|
3085
|
+
const r = Number(right);
|
|
3086
|
+
if (r < 7 || s.length < r) return s;
|
|
3087
|
+
if (l < 0 || l > s.length - r + 1) return s;
|
|
3088
|
+
return `...${s.slice(l, l + r - 6)}...`;
|
|
3089
|
+
}
|
|
3090
|
+
//#endregion
|
|
3091
|
+
//#region src/sprig/strings/caseUtils.ts
|
|
3092
|
+
/**
|
|
3093
|
+
* Word-classifying state machine ported from huandu/xstrings v1.3.3
|
|
3094
|
+
* (https://github.com/huandu/xstrings/blob/v1.3.3/convert.go), which
|
|
3095
|
+
* Go sprig delegates to for `snakecase`, `camelcase`, and `kebabcase`.
|
|
3096
|
+
*
|
|
3097
|
+
* [LAW:one-source-of-truth] Three sprig funcs target the same
|
|
3098
|
+
* algorithm with two different connector chars (`_`, `-`) plus a
|
|
3099
|
+
* separate camel walk. The state machine lives once in this module;
|
|
3100
|
+
* the per-func files are thin specializations.
|
|
3101
|
+
*
|
|
3102
|
+
* ## Port notes
|
|
3103
|
+
*
|
|
3104
|
+
* Go iterates UTF-8 bytes via `utf8.DecodeRuneInString`. JS strings
|
|
3105
|
+
* are UTF-16; iterating with `for…of` (or `Array.from(s)`) yields
|
|
3106
|
+
* code points the same way Go yields runes, so the rune-level logic
|
|
3107
|
+
* carries over. We intentionally do NOT attempt to mirror xstrings'
|
|
3108
|
+
* `isAlphabet` CJK-exclusion table — for ASCII/Latin templates, which
|
|
3109
|
+
* are what real users feed sprig, the simpler `isLetter` test
|
|
3110
|
+
* matches Go's output. The fixture suite pins the cases consumers
|
|
3111
|
+
* actually exercise.
|
|
3112
|
+
*
|
|
3113
|
+
* `unicode.ToTitle` from Go has no JS equivalent for ASCII letters
|
|
3114
|
+
* (Title and Upper coincide for code points without a separate Title
|
|
3115
|
+
* mapping), so we use `String.toUpperCase()` everywhere xstrings would
|
|
3116
|
+
* have used either.
|
|
3117
|
+
*/
|
|
3118
|
+
const WordType = {
|
|
3119
|
+
Invalid: 0,
|
|
3120
|
+
Number: 1,
|
|
3121
|
+
UpperCase: 2,
|
|
3122
|
+
Alphabet: 3,
|
|
3123
|
+
Connector: 4,
|
|
3124
|
+
Punct: 5,
|
|
3125
|
+
Other: 6
|
|
3126
|
+
};
|
|
3127
|
+
const isConnectorRe = /^[-_\s]$/;
|
|
3128
|
+
const isPunctRe = /^\p{P}$/u;
|
|
3129
|
+
const isLetterRe = /^\p{L}$/u;
|
|
3130
|
+
const isUpperRe = /^\p{Lu}$/u;
|
|
3131
|
+
const isNumberRe = /^\p{N}$/u;
|
|
3132
|
+
function isConnector(ch) {
|
|
3133
|
+
return ch !== void 0 && isConnectorRe.test(ch);
|
|
3134
|
+
}
|
|
3135
|
+
function isAlphabet(ch) {
|
|
3136
|
+
return ch !== void 0 && isLetterRe.test(ch);
|
|
3137
|
+
}
|
|
3138
|
+
function isUpper$1(ch) {
|
|
3139
|
+
return ch !== void 0 && isUpperRe.test(ch);
|
|
3140
|
+
}
|
|
3141
|
+
function isNumber(ch) {
|
|
3142
|
+
return ch !== void 0 && isNumberRe.test(ch);
|
|
3143
|
+
}
|
|
3144
|
+
function isPunct(ch) {
|
|
3145
|
+
return ch !== void 0 && isPunctRe.test(ch);
|
|
3146
|
+
}
|
|
3147
|
+
/**
|
|
3148
|
+
* Pull the next word off `cps` starting at `i`. Returns the word's
|
|
3149
|
+
* type + text and the index of the first code point after the word.
|
|
3150
|
+
*
|
|
3151
|
+
* Mirrors xstrings.nextWord: classifies the first rune, then extends
|
|
3152
|
+
* the word as long as the next rune fits the same class — with a
|
|
3153
|
+
* special "HTTPStatus" carve-out where an upper-run followed by a
|
|
3154
|
+
* lower letter releases the last upper into the next word.
|
|
3155
|
+
*/
|
|
3156
|
+
function nextWord(cps, start) {
|
|
3157
|
+
if (start >= cps.length) return {
|
|
3158
|
+
word: {
|
|
3159
|
+
wt: WordType.Invalid,
|
|
3160
|
+
text: ""
|
|
3161
|
+
},
|
|
3162
|
+
next: start
|
|
3163
|
+
};
|
|
3164
|
+
const r = cps[start];
|
|
3165
|
+
let i = start + 1;
|
|
3166
|
+
if (isConnector(r)) {
|
|
3167
|
+
while (i < cps.length && isConnector(cps[i])) i++;
|
|
3168
|
+
return {
|
|
3169
|
+
word: {
|
|
3170
|
+
wt: WordType.Connector,
|
|
3171
|
+
text: cps.slice(start, i).join("")
|
|
3172
|
+
},
|
|
3173
|
+
next: i
|
|
3174
|
+
};
|
|
3175
|
+
}
|
|
3176
|
+
if (isPunct(r)) {
|
|
3177
|
+
while (i < cps.length && isPunct(cps[i])) i++;
|
|
3178
|
+
return {
|
|
3179
|
+
word: {
|
|
3180
|
+
wt: WordType.Punct,
|
|
3181
|
+
text: cps.slice(start, i).join("")
|
|
3182
|
+
},
|
|
3183
|
+
next: i
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
if (isUpper$1(r)) {
|
|
3187
|
+
if (i >= cps.length) return {
|
|
3188
|
+
word: {
|
|
3189
|
+
wt: WordType.UpperCase,
|
|
3190
|
+
text: r
|
|
3191
|
+
},
|
|
3192
|
+
next: i
|
|
3193
|
+
};
|
|
3194
|
+
if (isUpper$1(cps[i])) {
|
|
3195
|
+
let endOfRun = i;
|
|
3196
|
+
while (endOfRun < cps.length && isUpper$1(cps[endOfRun])) endOfRun++;
|
|
3197
|
+
if (endOfRun < cps.length && isAlphabet(cps[endOfRun])) return {
|
|
3198
|
+
word: {
|
|
3199
|
+
wt: WordType.UpperCase,
|
|
3200
|
+
text: cps.slice(start, endOfRun - 1).join("")
|
|
3201
|
+
},
|
|
3202
|
+
next: endOfRun - 1
|
|
3203
|
+
};
|
|
3204
|
+
return {
|
|
3205
|
+
word: {
|
|
3206
|
+
wt: WordType.UpperCase,
|
|
3207
|
+
text: cps.slice(start, endOfRun).join("")
|
|
3208
|
+
},
|
|
3209
|
+
next: endOfRun
|
|
3210
|
+
};
|
|
3211
|
+
}
|
|
3212
|
+
if (isAlphabet(cps[i])) {
|
|
3213
|
+
let end = i + 1;
|
|
3214
|
+
while (end < cps.length && isAlphabet(cps[end]) && !isUpper$1(cps[end])) end++;
|
|
3215
|
+
return {
|
|
3216
|
+
word: {
|
|
3217
|
+
wt: WordType.UpperCase,
|
|
3218
|
+
text: cps.slice(start, end).join("")
|
|
3219
|
+
},
|
|
3220
|
+
next: end
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
return {
|
|
3224
|
+
word: {
|
|
3225
|
+
wt: WordType.UpperCase,
|
|
3226
|
+
text: r
|
|
3227
|
+
},
|
|
3228
|
+
next: i
|
|
3229
|
+
};
|
|
3230
|
+
}
|
|
3231
|
+
if (isAlphabet(r)) {
|
|
3232
|
+
while (i < cps.length && isAlphabet(cps[i]) && !isUpper$1(cps[i])) i++;
|
|
3233
|
+
return {
|
|
3234
|
+
word: {
|
|
3235
|
+
wt: WordType.Alphabet,
|
|
3236
|
+
text: cps.slice(start, i).join("")
|
|
3237
|
+
},
|
|
3238
|
+
next: i
|
|
3239
|
+
};
|
|
3240
|
+
}
|
|
3241
|
+
if (isNumber(r)) {
|
|
3242
|
+
while (i < cps.length && isNumber(cps[i])) i++;
|
|
3243
|
+
return {
|
|
3244
|
+
word: {
|
|
3245
|
+
wt: WordType.Number,
|
|
3246
|
+
text: cps.slice(start, i).join("")
|
|
3247
|
+
},
|
|
3248
|
+
next: i
|
|
3249
|
+
};
|
|
3250
|
+
}
|
|
3251
|
+
while (i < cps.length && !isConnector(cps[i]) && !isAlphabet(cps[i]) && !isNumber(cps[i]) && !isPunct(cps[i])) i++;
|
|
3252
|
+
return {
|
|
3253
|
+
word: {
|
|
3254
|
+
wt: WordType.Other,
|
|
3255
|
+
text: cps.slice(start, i).join("")
|
|
3256
|
+
},
|
|
3257
|
+
next: i
|
|
3258
|
+
};
|
|
3259
|
+
}
|
|
3260
|
+
/**
|
|
3261
|
+
* Lowercase a word's text into the output buffer. Connector words
|
|
3262
|
+
* have their internal connector chars rewritten to the target
|
|
3263
|
+
* connector; all other words are lowered character-by-character.
|
|
3264
|
+
*/
|
|
3265
|
+
function pushLowered(buf, word, connector) {
|
|
3266
|
+
if (word.wt !== WordType.UpperCase && word.wt !== WordType.Connector) {
|
|
3267
|
+
buf.push(word.text);
|
|
3268
|
+
return;
|
|
3269
|
+
}
|
|
3270
|
+
for (const ch of word.text) if (isConnector(ch)) buf.push(connector);
|
|
3271
|
+
else if (isUpper$1(ch)) buf.push(ch.toLowerCase());
|
|
3272
|
+
else buf.push(ch);
|
|
3273
|
+
}
|
|
3274
|
+
/**
|
|
3275
|
+
* Port of xstrings.camelCaseToLowerCase. Walks word-by-word and
|
|
3276
|
+
* inserts `connector` at the right transitions to produce snake/kebab
|
|
3277
|
+
* output.
|
|
3278
|
+
*/
|
|
3279
|
+
function camelCaseToLowerCase(s, connector) {
|
|
3280
|
+
if (s.length === 0) return "";
|
|
3281
|
+
const cps = Array.from(s);
|
|
3282
|
+
const buf = [];
|
|
3283
|
+
let { word, next: i } = nextWord(cps, 0);
|
|
3284
|
+
while (i < cps.length) {
|
|
3285
|
+
if (word.wt !== WordType.Connector) pushLowered(buf, word, connector);
|
|
3286
|
+
const prev = word;
|
|
3287
|
+
const last = word;
|
|
3288
|
+
({word, next: i} = nextWord(cps, i));
|
|
3289
|
+
if (prev.wt === WordType.Number) {
|
|
3290
|
+
while (word.wt === WordType.Alphabet || word.wt === WordType.Number) {
|
|
3291
|
+
pushLowered(buf, word, connector);
|
|
3292
|
+
({word, next: i} = nextWord(cps, i));
|
|
3293
|
+
}
|
|
3294
|
+
if (word.wt !== WordType.Invalid && word.wt !== WordType.Punct && word.wt !== WordType.Connector) buf.push(connector);
|
|
3295
|
+
continue;
|
|
3296
|
+
}
|
|
3297
|
+
if (prev.wt === WordType.Connector) {
|
|
3298
|
+
pushLowered(buf, last, connector);
|
|
3299
|
+
continue;
|
|
3300
|
+
}
|
|
3301
|
+
if (prev.wt === WordType.Punct) continue;
|
|
3302
|
+
if (word.wt !== WordType.Number) {
|
|
3303
|
+
if (word.wt !== WordType.Connector && word.wt !== WordType.Punct) buf.push(connector);
|
|
3304
|
+
continue;
|
|
3305
|
+
}
|
|
3306
|
+
if (i >= cps.length) continue;
|
|
3307
|
+
const numberWord = word;
|
|
3308
|
+
({word, next: i} = nextWord(cps, i));
|
|
3309
|
+
if (word.wt !== WordType.Alphabet) {
|
|
3310
|
+
pushLowered(buf, numberWord, connector);
|
|
3311
|
+
if (word.wt !== WordType.Connector && word.wt !== WordType.Punct) buf.push(connector);
|
|
3312
|
+
continue;
|
|
3313
|
+
}
|
|
3314
|
+
buf.push(connector);
|
|
3315
|
+
pushLowered(buf, numberWord, connector);
|
|
3316
|
+
while (word.wt === WordType.Alphabet || word.wt === WordType.Number) {
|
|
3317
|
+
pushLowered(buf, word, connector);
|
|
3318
|
+
({word, next: i} = nextWord(cps, i));
|
|
3319
|
+
}
|
|
3320
|
+
if (word.wt !== WordType.Invalid && word.wt !== WordType.Connector && word.wt !== WordType.Punct) buf.push(connector);
|
|
3321
|
+
}
|
|
3322
|
+
pushLowered(buf, word, connector);
|
|
3323
|
+
return buf.join("").toLowerCase();
|
|
3324
|
+
}
|
|
3325
|
+
/**
|
|
3326
|
+
* Port of xstrings.ToCamelCase. Two-phase walk:
|
|
3327
|
+
* - Phase 1 preserves leading connectors verbatim, capitalizes the
|
|
3328
|
+
* first non-connector rune.
|
|
3329
|
+
* - Phase 2 walks `(prev, curr)` rune pairs, collapsing connector→
|
|
3330
|
+
* non-connector to a single uppered rune, preserving runs of
|
|
3331
|
+
* adjacent connectors, and lowercasing other runes.
|
|
3332
|
+
*/
|
|
3333
|
+
function camelCase(s) {
|
|
3334
|
+
if (s.length === 0) return "";
|
|
3335
|
+
const cps = Array.from(s);
|
|
3336
|
+
const buf = [];
|
|
3337
|
+
let i = 0;
|
|
3338
|
+
let r0 = "";
|
|
3339
|
+
while (i < cps.length) {
|
|
3340
|
+
r0 = cps[i];
|
|
3341
|
+
i++;
|
|
3342
|
+
if (!isConnector(r0)) {
|
|
3343
|
+
r0 = r0.toUpperCase();
|
|
3344
|
+
break;
|
|
3345
|
+
}
|
|
3346
|
+
buf.push(r0);
|
|
3347
|
+
}
|
|
3348
|
+
if (i >= cps.length) {
|
|
3349
|
+
if (cps.length > 0) buf.push(r0);
|
|
3350
|
+
return buf.join("");
|
|
3351
|
+
}
|
|
3352
|
+
while (i < cps.length) {
|
|
3353
|
+
const r1 = r0;
|
|
3354
|
+
r0 = cps[i];
|
|
3355
|
+
i++;
|
|
3356
|
+
if (isConnector(r0) && isConnector(r1)) {
|
|
3357
|
+
buf.push(r1);
|
|
3358
|
+
continue;
|
|
3359
|
+
}
|
|
3360
|
+
if (isConnector(r1)) r0 = r0.toUpperCase();
|
|
3361
|
+
else {
|
|
3362
|
+
r0 = r0.toLowerCase();
|
|
3363
|
+
buf.push(r1);
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
buf.push(r0);
|
|
3367
|
+
return buf.join("");
|
|
3368
|
+
}
|
|
3369
|
+
//#endregion
|
|
3370
|
+
//#region src/sprig/strings/camelcase.ts
|
|
3371
|
+
/**
|
|
3372
|
+
* `camelcase s` — port of `xstrings.ToCamelCase`. Note: despite the
|
|
3373
|
+
* name, Go sprig's `camelcase` is **PascalCase** — the first letter
|
|
3374
|
+
* is uppercased, not lowercased. This is a documented Go-sprig
|
|
3375
|
+
* quirk and we preserve it byte-for-byte.
|
|
3376
|
+
*
|
|
3377
|
+
* Examples (matching the xstrings docstring):
|
|
3378
|
+
* "some_words" -> "SomeWords"
|
|
3379
|
+
* "http_server" -> "HttpServer"
|
|
3380
|
+
* "_complex__case_" -> "_Complex_Case_"
|
|
3381
|
+
*/
|
|
3382
|
+
function camelcase(s) {
|
|
3383
|
+
return camelCase(s);
|
|
3384
|
+
}
|
|
3385
|
+
//#endregion
|
|
3386
|
+
//#region src/sprig/strings/cat.ts
|
|
3387
|
+
/** `cat a b c` — concatenates with spaces, like Go sprig. */
|
|
3388
|
+
function cat(...args) {
|
|
3389
|
+
return args.join(" ");
|
|
3390
|
+
}
|
|
3391
|
+
//#endregion
|
|
3392
|
+
//#region src/sprig/strings/contains.ts
|
|
3393
|
+
function contains(substr, s) {
|
|
3394
|
+
return s.includes(substr);
|
|
3395
|
+
}
|
|
3396
|
+
//#endregion
|
|
3397
|
+
//#region src/sprig/strings/hasPrefix.ts
|
|
3398
|
+
function hasPrefix(prefix, s) {
|
|
3399
|
+
return s.startsWith(prefix);
|
|
3400
|
+
}
|
|
3401
|
+
//#endregion
|
|
3402
|
+
//#region src/sprig/strings/hasSuffix.ts
|
|
3403
|
+
function hasSuffix(suffix, s) {
|
|
3404
|
+
return s.endsWith(suffix);
|
|
3405
|
+
}
|
|
3406
|
+
//#endregion
|
|
3407
|
+
//#region src/sprig/strings/indent.ts
|
|
3408
|
+
/** `indent n s` — prefix every line of `s` with `n` spaces. */
|
|
3409
|
+
function indent(n, s) {
|
|
3410
|
+
const pad = " ".repeat(Math.max(0, Number(n)));
|
|
3411
|
+
return s.split("\n").map((line) => pad + line).join("\n");
|
|
3412
|
+
}
|
|
3413
|
+
//#endregion
|
|
3414
|
+
//#region src/sprig/strings/initials.ts
|
|
3415
|
+
/** `initials s` — first letter of each whitespace-separated word, uppercased. */
|
|
3416
|
+
function initials(s) {
|
|
3417
|
+
return s.split(/\s+/).filter((w) => w.length > 0).map((w) => (w[0] ?? "").toUpperCase()).join("");
|
|
3418
|
+
}
|
|
3419
|
+
//#endregion
|
|
3420
|
+
//#region src/sprig/strings/join.ts
|
|
3421
|
+
/**
|
|
3422
|
+
* `join sep list` — joins a list with the separator.
|
|
3423
|
+
*
|
|
3424
|
+
* [LAW:single-enforcer] The list-shape gate is `argTypes: ["string",
|
|
3425
|
+
* "list"]` — non-arrays raise TypeMismatchError before this body runs.
|
|
3426
|
+
* The body validates each *element* because the no-silent-flatten
|
|
3427
|
+
* commitment ("typed values never become strings without an explicit
|
|
3428
|
+
* conversion") applies inside lists too: primitives stringify
|
|
3429
|
+
* naturally; non-primitive (typed-T) elements throw, and `evalCommand`
|
|
3430
|
+
* re-emits with the call-site pos.
|
|
3431
|
+
*/
|
|
3432
|
+
function join(sep, list) {
|
|
3433
|
+
const parts = [];
|
|
3434
|
+
for (const v of list) {
|
|
3435
|
+
if (v !== null && v !== void 0 && typeof v === "object") throw bodyTypeMismatch("join", 2, "list of strings/primitives", `list element of type ${describe(v)}`);
|
|
3436
|
+
parts.push(String(v));
|
|
3437
|
+
}
|
|
3438
|
+
return parts.join(sep);
|
|
3439
|
+
}
|
|
3440
|
+
function describe(v) {
|
|
3441
|
+
if (Array.isArray(v)) return "array";
|
|
3442
|
+
if (v instanceof Map) return "Map";
|
|
3443
|
+
if (v instanceof Set) return "Set";
|
|
3444
|
+
return "object";
|
|
3445
|
+
}
|
|
3446
|
+
//#endregion
|
|
3447
|
+
//#region src/sprig/strings/kebabcase.ts
|
|
3448
|
+
/**
|
|
3449
|
+
* `kebabcase s` — port of `xstrings.ToKebabCase`. Identical to
|
|
3450
|
+
* `snakecase` except the connector is `-`.
|
|
3451
|
+
*/
|
|
3452
|
+
function kebabcase(s) {
|
|
3453
|
+
return camelCaseToLowerCase(s, "-");
|
|
3454
|
+
}
|
|
3455
|
+
//#endregion
|
|
3456
|
+
//#region src/sprig/strings/lower.ts
|
|
3457
|
+
function lower(s) {
|
|
3458
|
+
return s.toLowerCase();
|
|
3459
|
+
}
|
|
3460
|
+
//#endregion
|
|
3461
|
+
//#region src/sprig/strings/nindent.ts
|
|
3462
|
+
/** `nindent n s` — `indent` with a leading newline. */
|
|
3463
|
+
function nindent(n, s) {
|
|
3464
|
+
return `\n${indent(n, s)}`;
|
|
3465
|
+
}
|
|
3466
|
+
//#endregion
|
|
3467
|
+
//#region src/sprig/strings/nospace.ts
|
|
3468
|
+
/**
|
|
3469
|
+
* `nospace s` — strip whitespace from `s`. Mirrors Go sprig's
|
|
3470
|
+
* `goutils.DeleteWhiteSpace`, which iterates bytes and drops anything
|
|
3471
|
+
* `unicode.IsSpace` returns true for. ECMAScript `\s` covers the same
|
|
3472
|
+
* ASCII whitespace set (space, tab, CR, LF, VT, FF) — the goutils
|
|
3473
|
+
* implementation is byte-indexed so multi-byte Unicode whitespace
|
|
3474
|
+
* already escapes its filter, leaving ASCII as the de-facto contract.
|
|
3475
|
+
*/
|
|
3476
|
+
function nospace(s) {
|
|
3477
|
+
return s.replace(/\s+/g, "");
|
|
3478
|
+
}
|
|
3479
|
+
//#endregion
|
|
3480
|
+
//#region src/sprig/strings/plural.ts
|
|
3481
|
+
/**
|
|
3482
|
+
* `plural one many n` — return `one` if `n == 1`, else `many`.
|
|
3483
|
+
* Mirrors Go sprig's `plural(one, many string, count int) string`.
|
|
3484
|
+
*/
|
|
3485
|
+
function plural(one, many, n) {
|
|
3486
|
+
return n === 1 || n === 1n ? one : many;
|
|
3487
|
+
}
|
|
3488
|
+
//#endregion
|
|
3489
|
+
//#region src/sprig/strings/quote.ts
|
|
3490
|
+
/** `quote a b c` — wraps each arg in double quotes, joined by spaces. */
|
|
3491
|
+
function quote(...args) {
|
|
3492
|
+
return args.map((a) => `"${a}"`).join(" ");
|
|
3493
|
+
}
|
|
3494
|
+
//#endregion
|
|
3495
|
+
//#region src/sprig/strings/regexQuoteMeta.ts
|
|
3496
|
+
/**
|
|
3497
|
+
* `regexQuoteMeta s` — escape regex metacharacters in `s` so it can be
|
|
3498
|
+
* embedded literally in a regex. Mirrors Go's `regexp.QuoteMeta`,
|
|
3499
|
+
* which backslash-escapes the set `\.+*?()|[]{}^$`.
|
|
3500
|
+
*
|
|
3501
|
+
* ECMAScript regex shares the same metacharacter set, so the escape
|
|
3502
|
+
* list is identical.
|
|
3503
|
+
*/
|
|
3504
|
+
function regexQuoteMeta(s) {
|
|
3505
|
+
return s.replace(/[\\.+*?()|[\]{}^$]/g, "\\$&");
|
|
3506
|
+
}
|
|
3507
|
+
//#endregion
|
|
3508
|
+
//#region src/sprig/strings/repeat.ts
|
|
3509
|
+
function repeat(n, s) {
|
|
3510
|
+
const count = Math.max(0, Number(n));
|
|
3511
|
+
return s.repeat(count);
|
|
3512
|
+
}
|
|
3513
|
+
//#endregion
|
|
3514
|
+
//#region src/sprig/strings/replace.ts
|
|
3515
|
+
/** Replaces ALL occurrences of `old` with `nw` in `s` (Go's strings.Replace n=-1). */
|
|
3516
|
+
function replace(old, nw, s) {
|
|
3517
|
+
return s.split(old).join(nw);
|
|
3518
|
+
}
|
|
3519
|
+
//#endregion
|
|
3520
|
+
//#region src/sprig/strings/snakecase.ts
|
|
3521
|
+
/**
|
|
3522
|
+
* `snakecase s` — port of `xstrings.ToSnakeCase`. Inserts `_` between
|
|
3523
|
+
* camelCase/PascalCase word boundaries and rewrites any space, dash,
|
|
3524
|
+
* or underscore run into a single `_`. Runs of upper-case letters
|
|
3525
|
+
* release their last character into the next word, so `HTTPServer`
|
|
3526
|
+
* becomes `http_server`, not `https_erver`.
|
|
3527
|
+
*/
|
|
3528
|
+
function snakecase(s) {
|
|
3529
|
+
return camelCaseToLowerCase(s, "_");
|
|
3530
|
+
}
|
|
3531
|
+
//#endregion
|
|
3532
|
+
//#region src/sprig/strings/split.ts
|
|
3533
|
+
/**
|
|
3534
|
+
* `split sep s` — Go sprig oddity: returns a DICT keyed by `_<index>`,
|
|
3535
|
+
* not a list. Use `splitList` for the list form.
|
|
3536
|
+
* split "/" "a/b/c" → { _0: "a", _1: "b", _2: "c" }
|
|
3537
|
+
*/
|
|
3538
|
+
function split(sep, s) {
|
|
3539
|
+
const parts = s.split(sep);
|
|
3540
|
+
const out = {};
|
|
3541
|
+
for (let i = 0; i < parts.length; i++) out[`_${i}`] = parts[i];
|
|
3542
|
+
return out;
|
|
3543
|
+
}
|
|
3544
|
+
//#endregion
|
|
3545
|
+
//#region src/sprig/strings/splitList.ts
|
|
3546
|
+
function splitList(sep, s) {
|
|
3547
|
+
return s.split(sep);
|
|
3548
|
+
}
|
|
3549
|
+
//#endregion
|
|
3550
|
+
//#region src/sprig/strings/splitn.ts
|
|
3551
|
+
/**
|
|
3552
|
+
* `splitn sep n s` — split `s` on `sep` into at most `n` parts and
|
|
3553
|
+
* return a `{_0, _1, …}` map. Mirrors Go sprig:
|
|
3554
|
+
*
|
|
3555
|
+
* parts := strings.SplitN(orig, sep, n)
|
|
3556
|
+
* for i, v := range parts {
|
|
3557
|
+
* res["_" + strconv.Itoa(i)] = v
|
|
3558
|
+
* }
|
|
3559
|
+
*
|
|
3560
|
+
* The `{_0, _1}` shape (rather than a list) is idiosyncratic to Go
|
|
3561
|
+
* sprig. Preserve it byte-for-byte — consumers index into the result
|
|
3562
|
+
* by name, e.g. `(splitn ":" 2 "a:b:c")._1` → `"b:c"`.
|
|
3563
|
+
*
|
|
3564
|
+
* `strings.SplitN` semantics that JS `String.split(sep, n)` does *not*
|
|
3565
|
+
* match: when there are more parts than `n`, the last slot holds the
|
|
3566
|
+
* **unsplit remainder**, not a truncated prefix. JS `split` would
|
|
3567
|
+
* drop "b:c" entirely; Go keeps it. The body re-joins the tail
|
|
3568
|
+
* explicitly to recover the Go behavior.
|
|
3569
|
+
*/
|
|
3570
|
+
function splitn(sep, n, s) {
|
|
3571
|
+
const parts = goSplitN(s, sep, typeof n === "bigint" ? Number(n) : n);
|
|
3572
|
+
const res = {};
|
|
3573
|
+
for (let i = 0; i < parts.length; i++) res[`_${i}`] = parts[i] ?? "";
|
|
3574
|
+
return res;
|
|
3575
|
+
}
|
|
3576
|
+
function goSplitN(s, sep, n) {
|
|
3577
|
+
if (n === 0) return [];
|
|
3578
|
+
const all = sep === "" ? Array.from(s) : s.split(sep);
|
|
3579
|
+
if (n < 0 || all.length <= n) return all;
|
|
3580
|
+
const head = all.slice(0, n - 1);
|
|
3581
|
+
const tail = all.slice(n - 1).join(sep);
|
|
3582
|
+
return [...head, tail];
|
|
3583
|
+
}
|
|
3584
|
+
//#endregion
|
|
3585
|
+
//#region src/sprig/strings/squote.ts
|
|
3586
|
+
/** `squote a b c` — like `quote` but single quotes. */
|
|
3587
|
+
function squote(...args) {
|
|
3588
|
+
return args.map((a) => `'${a}'`).join(" ");
|
|
3589
|
+
}
|
|
3590
|
+
//#endregion
|
|
3591
|
+
//#region src/sprig/strings/substr.ts
|
|
3592
|
+
/**
|
|
3593
|
+
* `substr i j s` — substring [i, j) with out-of-range clamping.
|
|
3594
|
+
* Matches Go sprig's behavior of clamping rather than throwing.
|
|
3595
|
+
*/
|
|
3596
|
+
function substr(start, end, s) {
|
|
3597
|
+
let i = Math.max(0, Number(start));
|
|
3598
|
+
let j = end === void 0 || end === null ? s.length : Number(end);
|
|
3599
|
+
if (j > s.length) j = s.length;
|
|
3600
|
+
if (i > j) i = j;
|
|
3601
|
+
return s.slice(i, j);
|
|
3602
|
+
}
|
|
3603
|
+
//#endregion
|
|
3604
|
+
//#region src/sprig/strings/swapcase.ts
|
|
3605
|
+
/**
|
|
3606
|
+
* `swapcase s` — flip case per code point. Mirrors Go sprig's
|
|
3607
|
+
* `goutils.SwapCase` for ASCII and Latin-1 inputs.
|
|
3608
|
+
*
|
|
3609
|
+
* Go's `goutils.SwapCase` carries a "preceded by whitespace" flag and
|
|
3610
|
+
* uses `unicode.ToTitle` instead of `ToUpper` for the first lowercase
|
|
3611
|
+
* letter of each word. For ASCII letters Title and Upper coincide, so
|
|
3612
|
+
* the flag has no observable effect on output and is omitted here —
|
|
3613
|
+
* keeping it would be load-bearing complexity that the type system
|
|
3614
|
+
* cannot constrain. Non-ASCII ligatures (e.g. German `ß` whose JS
|
|
3615
|
+
* `toUpperCase` returns `SS` while Go's `ToTitle` returns `ẞ`) diverge,
|
|
3616
|
+
* matching the README's existing Go/Unicode divergence statements.
|
|
3617
|
+
*/
|
|
3618
|
+
function swapcase(s) {
|
|
3619
|
+
let out = "";
|
|
3620
|
+
for (const ch of s) if (isUpper(ch)) out += ch.toLowerCase();
|
|
3621
|
+
else if (isLower(ch)) out += ch.toUpperCase();
|
|
3622
|
+
else out += ch;
|
|
3623
|
+
return out;
|
|
3624
|
+
}
|
|
3625
|
+
function isUpper(ch) {
|
|
3626
|
+
return ch !== ch.toLowerCase() && ch === ch.toUpperCase();
|
|
3627
|
+
}
|
|
3628
|
+
function isLower(ch) {
|
|
3629
|
+
return ch !== ch.toUpperCase() && ch === ch.toLowerCase();
|
|
3630
|
+
}
|
|
3631
|
+
//#endregion
|
|
3632
|
+
//#region src/sprig/strings/title.ts
|
|
3633
|
+
/** Capitalize the first letter of each whitespace-separated word. */
|
|
3634
|
+
function title(s) {
|
|
3635
|
+
return s.replace(/\b([a-zA-Z])/g, (m) => m.toUpperCase());
|
|
3636
|
+
}
|
|
3637
|
+
//#endregion
|
|
3638
|
+
//#region src/sprig/strings/trim.ts
|
|
3639
|
+
function trim(s) {
|
|
3640
|
+
return s.trim();
|
|
3641
|
+
}
|
|
3642
|
+
//#endregion
|
|
3643
|
+
//#region src/sprig/strings/trimAll.ts
|
|
3644
|
+
/** `trimAll cutset s` — strip leading + trailing chars in `cutset`. */
|
|
3645
|
+
function trimAll(cutset, s) {
|
|
3646
|
+
if (cutset.length === 0) return s;
|
|
3647
|
+
const set = new Set([...cutset]);
|
|
3648
|
+
let start = 0;
|
|
3649
|
+
while (start < s.length && set.has(s[start])) start += 1;
|
|
3650
|
+
let end = s.length;
|
|
3651
|
+
while (end > start && set.has(s[end - 1])) end -= 1;
|
|
3652
|
+
return s.slice(start, end);
|
|
3653
|
+
}
|
|
3654
|
+
//#endregion
|
|
3655
|
+
//#region src/sprig/strings/trimPrefix.ts
|
|
3656
|
+
function trimPrefix(prefix, s) {
|
|
3657
|
+
return s.startsWith(prefix) ? s.slice(prefix.length) : s;
|
|
3658
|
+
}
|
|
3659
|
+
//#endregion
|
|
3660
|
+
//#region src/sprig/strings/trimSuffix.ts
|
|
3661
|
+
function trimSuffix(suffix, s) {
|
|
3662
|
+
return s.endsWith(suffix) ? s.slice(0, s.length - suffix.length) : s;
|
|
3663
|
+
}
|
|
3664
|
+
//#endregion
|
|
3665
|
+
//#region src/sprig/strings/trunc.ts
|
|
3666
|
+
/**
|
|
3667
|
+
* `trunc n s` — first `n` chars when n>=0; last |n| chars when n<0.
|
|
3668
|
+
* Strings shorter than |n| are returned unchanged. Matches Go sprig.
|
|
3669
|
+
*/
|
|
3670
|
+
function trunc(n, s) {
|
|
3671
|
+
const len = Number(n);
|
|
3672
|
+
if (Number.isNaN(len)) return s;
|
|
3673
|
+
if (len < 0) {
|
|
3674
|
+
const k = -len;
|
|
3675
|
+
return k >= s.length ? s : s.slice(s.length - k);
|
|
3676
|
+
}
|
|
3677
|
+
return len >= s.length ? s : s.slice(0, len);
|
|
3678
|
+
}
|
|
3679
|
+
//#endregion
|
|
3680
|
+
//#region src/sprig/strings/untitle.ts
|
|
3681
|
+
/** Lowercase the first letter of each whitespace-separated word. */
|
|
3682
|
+
function untitle(s) {
|
|
3683
|
+
return s.replace(/\b([A-Z])/g, (m) => m.toLowerCase());
|
|
3684
|
+
}
|
|
3685
|
+
//#endregion
|
|
3686
|
+
//#region src/sprig/strings/upper.ts
|
|
3687
|
+
function upper(s) {
|
|
3688
|
+
return s.toUpperCase();
|
|
3689
|
+
}
|
|
3690
|
+
//#endregion
|
|
3691
|
+
//#region src/sprig/strings/wrap.ts
|
|
3692
|
+
/**
|
|
3693
|
+
* `wrap width s` — soft-wrap `s` to `width` columns at word boundaries.
|
|
3694
|
+
* Lines longer than width that contain no spaces are emitted as-is.
|
|
3695
|
+
*/
|
|
3696
|
+
function wrap(width, s) {
|
|
3697
|
+
return wrapWithSeparator(Number(width), "\n", s);
|
|
3698
|
+
}
|
|
3699
|
+
function wrapWithSeparator(width, sep, s) {
|
|
3700
|
+
if (!Number.isFinite(width) || width <= 0) return s;
|
|
3701
|
+
const out = [];
|
|
3702
|
+
for (const para of s.split("\n")) {
|
|
3703
|
+
let line = "";
|
|
3704
|
+
for (const word of para.split(/\s+/)) {
|
|
3705
|
+
if (word.length === 0) continue;
|
|
3706
|
+
if (line.length === 0) line = word;
|
|
3707
|
+
else if (line.length + 1 + word.length <= width) line += ` ${word}`;
|
|
3708
|
+
else {
|
|
3709
|
+
out.push(line);
|
|
3710
|
+
line = word;
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
if (line.length > 0) out.push(line);
|
|
3714
|
+
}
|
|
3715
|
+
return out.join(sep);
|
|
3716
|
+
}
|
|
3717
|
+
//#endregion
|
|
3718
|
+
//#region src/sprig/strings/wrapWith.ts
|
|
3719
|
+
/** `wrapWith width sep s` — wrap to width using `sep` instead of \n. */
|
|
3720
|
+
function wrapWith(width, sep, s) {
|
|
3721
|
+
return wrapWithSeparator(Number(width), sep, s);
|
|
3722
|
+
}
|
|
3723
|
+
//#endregion
|
|
3724
|
+
//#region src/sprig/strings/index.ts
|
|
3725
|
+
function sprigStrings() {
|
|
3726
|
+
return {
|
|
3727
|
+
abbrev: {
|
|
3728
|
+
fn: (w, s) => abbrev(w, s),
|
|
3729
|
+
argTypes: ["number", "string"]
|
|
3730
|
+
},
|
|
3731
|
+
abbrevboth: {
|
|
3732
|
+
fn: (l, r, s) => abbrevboth(l, r, s),
|
|
3733
|
+
argTypes: [
|
|
3734
|
+
"number",
|
|
3735
|
+
"number",
|
|
3736
|
+
"string"
|
|
3737
|
+
]
|
|
3738
|
+
},
|
|
3739
|
+
camelcase: {
|
|
3740
|
+
fn: (s) => camelcase(s),
|
|
3741
|
+
argTypes: ["string"],
|
|
3742
|
+
returnType: "string"
|
|
3743
|
+
},
|
|
3744
|
+
cat: {
|
|
3745
|
+
fn: (...a) => cat(...a),
|
|
3746
|
+
argTypes: ["string"]
|
|
3747
|
+
},
|
|
3748
|
+
contains: {
|
|
3749
|
+
fn: (sub, s) => contains(sub, s),
|
|
3750
|
+
argTypes: ["string", "string"]
|
|
3751
|
+
},
|
|
3752
|
+
hasPrefix: {
|
|
3753
|
+
fn: (p, s) => hasPrefix(p, s),
|
|
3754
|
+
argTypes: ["string", "string"]
|
|
3755
|
+
},
|
|
3756
|
+
hasSuffix: {
|
|
3757
|
+
fn: (sf, s) => hasSuffix(sf, s),
|
|
3758
|
+
argTypes: ["string", "string"]
|
|
3759
|
+
},
|
|
3760
|
+
indent: {
|
|
3761
|
+
fn: (n, s) => indent(n, s),
|
|
3762
|
+
argTypes: ["number", "string"]
|
|
3763
|
+
},
|
|
3764
|
+
initials: {
|
|
3765
|
+
fn: (s) => initials(s),
|
|
3766
|
+
argTypes: ["string"]
|
|
3767
|
+
},
|
|
3768
|
+
join: {
|
|
3769
|
+
fn: (sep, list) => join(sep, list),
|
|
3770
|
+
argTypes: ["string", "list"]
|
|
3771
|
+
},
|
|
3772
|
+
kebabcase: {
|
|
3773
|
+
fn: (s) => kebabcase(s),
|
|
3774
|
+
argTypes: ["string"],
|
|
3775
|
+
returnType: "string"
|
|
3776
|
+
},
|
|
3777
|
+
lower: {
|
|
3778
|
+
fn: (s) => lower(s),
|
|
3779
|
+
argTypes: ["string"]
|
|
3780
|
+
},
|
|
3781
|
+
nindent: {
|
|
3782
|
+
fn: (n, s) => nindent(n, s),
|
|
3783
|
+
argTypes: ["number", "string"]
|
|
3784
|
+
},
|
|
3785
|
+
nospace: {
|
|
3786
|
+
fn: (s) => nospace(s),
|
|
3787
|
+
argTypes: ["string"],
|
|
3788
|
+
returnType: "string"
|
|
3789
|
+
},
|
|
3790
|
+
plural: {
|
|
3791
|
+
fn: (one, many, n) => plural(one, many, n),
|
|
3792
|
+
argTypes: [
|
|
3793
|
+
"string",
|
|
3794
|
+
"string",
|
|
3795
|
+
"number"
|
|
3796
|
+
],
|
|
3797
|
+
returnType: "string"
|
|
3798
|
+
},
|
|
3799
|
+
quote: {
|
|
3800
|
+
fn: (...a) => quote(...a),
|
|
3801
|
+
argTypes: ["string"]
|
|
3802
|
+
},
|
|
3803
|
+
regexQuoteMeta: {
|
|
3804
|
+
fn: (s) => regexQuoteMeta(s),
|
|
3805
|
+
argTypes: ["string"],
|
|
3806
|
+
returnType: "string"
|
|
3807
|
+
},
|
|
3808
|
+
repeat: {
|
|
3809
|
+
fn: (n, s) => repeat(n, s),
|
|
3810
|
+
argTypes: ["number", "string"]
|
|
3811
|
+
},
|
|
3812
|
+
replace: {
|
|
3813
|
+
fn: (o, n, s) => replace(o, n, s),
|
|
3814
|
+
argTypes: [
|
|
3815
|
+
"string",
|
|
3816
|
+
"string",
|
|
3817
|
+
"string"
|
|
3818
|
+
]
|
|
3819
|
+
},
|
|
3820
|
+
snakecase: {
|
|
3821
|
+
fn: (s) => snakecase(s),
|
|
3822
|
+
argTypes: ["string"],
|
|
3823
|
+
returnType: "string"
|
|
3824
|
+
},
|
|
3825
|
+
split: {
|
|
3826
|
+
fn: (sep, s) => split(sep, s),
|
|
3827
|
+
argTypes: ["string", "string"]
|
|
3828
|
+
},
|
|
3829
|
+
splitList: {
|
|
3830
|
+
fn: (sep, s) => splitList(sep, s),
|
|
3831
|
+
argTypes: ["string", "string"]
|
|
3832
|
+
},
|
|
3833
|
+
splitn: {
|
|
3834
|
+
fn: (sep, n, s) => splitn(sep, n, s),
|
|
3835
|
+
argTypes: [
|
|
3836
|
+
"string",
|
|
3837
|
+
"number",
|
|
3838
|
+
"string"
|
|
3839
|
+
],
|
|
3840
|
+
returnType: "dict"
|
|
3841
|
+
},
|
|
3842
|
+
squote: {
|
|
3843
|
+
fn: (...a) => squote(...a),
|
|
3844
|
+
argTypes: ["string"]
|
|
3845
|
+
},
|
|
3846
|
+
substr: {
|
|
3847
|
+
fn: (i, j, s) => substr(i, j, s),
|
|
3848
|
+
argTypes: [
|
|
3849
|
+
"number",
|
|
3850
|
+
"number",
|
|
3851
|
+
"string"
|
|
3852
|
+
]
|
|
3853
|
+
},
|
|
3854
|
+
swapcase: {
|
|
3855
|
+
fn: (s) => swapcase(s),
|
|
3856
|
+
argTypes: ["string"],
|
|
3857
|
+
returnType: "string"
|
|
3858
|
+
},
|
|
3859
|
+
title: {
|
|
3860
|
+
fn: (s) => title(s),
|
|
3861
|
+
argTypes: ["string"]
|
|
3862
|
+
},
|
|
3863
|
+
trim: {
|
|
3864
|
+
fn: (s) => trim(s),
|
|
3865
|
+
argTypes: ["string"]
|
|
3866
|
+
},
|
|
3867
|
+
trimAll: {
|
|
3868
|
+
fn: (cs, s) => trimAll(cs, s),
|
|
3869
|
+
argTypes: ["string", "string"]
|
|
3870
|
+
},
|
|
3871
|
+
trimPrefix: {
|
|
3872
|
+
fn: (p, s) => trimPrefix(p, s),
|
|
3873
|
+
argTypes: ["string", "string"]
|
|
3874
|
+
},
|
|
3875
|
+
trimSuffix: {
|
|
3876
|
+
fn: (sf, s) => trimSuffix(sf, s),
|
|
3877
|
+
argTypes: ["string", "string"]
|
|
3878
|
+
},
|
|
3879
|
+
trunc: {
|
|
3880
|
+
fn: (n, s) => trunc(n, s),
|
|
3881
|
+
argTypes: ["number", "string"]
|
|
3882
|
+
},
|
|
3883
|
+
untitle: {
|
|
3884
|
+
fn: (s) => untitle(s),
|
|
3885
|
+
argTypes: ["string"]
|
|
3886
|
+
},
|
|
3887
|
+
upper: {
|
|
3888
|
+
fn: (s) => upper(s),
|
|
3889
|
+
argTypes: ["string"]
|
|
3890
|
+
},
|
|
3891
|
+
wrap: {
|
|
3892
|
+
fn: (w, s) => wrap(w, s),
|
|
3893
|
+
argTypes: ["number", "string"]
|
|
3894
|
+
},
|
|
3895
|
+
wrapWith: {
|
|
3896
|
+
fn: (w, sep, s) => wrapWith(w, sep, s),
|
|
3897
|
+
argTypes: [
|
|
3898
|
+
"number",
|
|
3899
|
+
"string",
|
|
3900
|
+
"string"
|
|
3901
|
+
]
|
|
3902
|
+
}
|
|
3903
|
+
};
|
|
3904
|
+
}
|
|
3905
|
+
//#endregion
|
|
3906
|
+
//#region src/sprig/types/deepCopy.ts
|
|
3907
|
+
/**
|
|
3908
|
+
* `deepCopy v` — recursive structural clone.
|
|
3909
|
+
*
|
|
3910
|
+
* Uses `structuredClone` when available; falls back to a JSON
|
|
3911
|
+
* round-trip for older targets. The fallback drops functions and
|
|
3912
|
+
* symbols — same caveat as JSON.stringify.
|
|
3913
|
+
*/
|
|
3914
|
+
function deepCopy(value) {
|
|
3915
|
+
if (typeof globalThis.structuredClone === "function") return globalThis.structuredClone(value);
|
|
3916
|
+
return JSON.parse(JSON.stringify(value));
|
|
3917
|
+
}
|
|
3918
|
+
//#endregion
|
|
3919
|
+
//#region src/sprig/types/kindOf.ts
|
|
3920
|
+
/**
|
|
3921
|
+
* `kindOf v` — JS-flavoured equivalent of Go's `reflect.Kind`.
|
|
3922
|
+
*
|
|
3923
|
+
* Go: int / float64 / string / bool / slice / map / struct / ptr / …
|
|
3924
|
+
* JS: number / string / boolean / array / map / object / null / undefined / function / bigint / symbol
|
|
3925
|
+
*
|
|
3926
|
+
* We return the JS-native kind. Consumers porting templates from Go
|
|
3927
|
+
* sprig should test against the JS-native names.
|
|
3928
|
+
*/
|
|
3929
|
+
function kindOf(value) {
|
|
3930
|
+
if (value === null) return "null";
|
|
3931
|
+
if (Array.isArray(value)) return "array";
|
|
3932
|
+
if (value instanceof Map) return "map";
|
|
3933
|
+
if (value instanceof Set) return "set";
|
|
3934
|
+
return typeof value;
|
|
3935
|
+
}
|
|
3936
|
+
//#endregion
|
|
3937
|
+
//#region src/sprig/types/kindIs.ts
|
|
3938
|
+
function kindIs(kind, value) {
|
|
3939
|
+
return kindOf(value) === kind;
|
|
3940
|
+
}
|
|
3941
|
+
//#endregion
|
|
3942
|
+
//#region src/sprig/types/typeOf.ts
|
|
3943
|
+
/**
|
|
3944
|
+
* `typeOf v` — for JS, essentially the same as kindOf, with the
|
|
3945
|
+
* caveat that "object" is the catch-all for plain dicts and class
|
|
3946
|
+
* instances. Go's reflect.Type would distinguish struct names; we
|
|
3947
|
+
* don't have that info at runtime.
|
|
3948
|
+
*/
|
|
3949
|
+
function typeOf(value) {
|
|
3950
|
+
return kindOf(value);
|
|
3951
|
+
}
|
|
3952
|
+
//#endregion
|
|
3953
|
+
//#region src/sprig/types/typeIs.ts
|
|
3954
|
+
function typeIs(type, value) {
|
|
3955
|
+
return typeOf(value) === type;
|
|
3956
|
+
}
|
|
3957
|
+
//#endregion
|
|
3958
|
+
//#region src/sprig/types/typeIsLike.ts
|
|
3959
|
+
/**
|
|
3960
|
+
* `typeIsLike type v` — Go sprig's "like" matches both value and
|
|
3961
|
+
* pointer-to-value. JS doesn't have pointers so this collapses to
|
|
3962
|
+
* `typeIs`.
|
|
3963
|
+
*/
|
|
3964
|
+
function typeIsLike(type, value) {
|
|
3965
|
+
return typeIs(type, value);
|
|
3966
|
+
}
|
|
3967
|
+
//#endregion
|
|
3968
|
+
//#region src/sprig/types/index.ts
|
|
3969
|
+
function sprigTypes() {
|
|
3970
|
+
return {
|
|
3971
|
+
kindOf: {
|
|
3972
|
+
fn: (v) => kindOf(v),
|
|
3973
|
+
argTypes: ["reflective"]
|
|
3974
|
+
},
|
|
3975
|
+
kindIs: {
|
|
3976
|
+
fn: (k, v) => kindIs(k, v),
|
|
3977
|
+
argTypes: ["string", "reflective"]
|
|
3978
|
+
},
|
|
3979
|
+
typeOf: {
|
|
3980
|
+
fn: (v) => typeOf(v),
|
|
3981
|
+
argTypes: ["reflective"]
|
|
3982
|
+
},
|
|
3983
|
+
typeIs: {
|
|
3984
|
+
fn: (t, v) => typeIs(t, v),
|
|
3985
|
+
argTypes: ["string", "reflective"]
|
|
3986
|
+
},
|
|
3987
|
+
typeIsLike: {
|
|
3988
|
+
fn: (t, v) => typeIsLike(t, v),
|
|
3989
|
+
argTypes: ["string", "reflective"]
|
|
3990
|
+
},
|
|
3991
|
+
deepEqual: {
|
|
3992
|
+
fn: (a, b) => deepEqual(a, b),
|
|
3993
|
+
argTypes: ["value", "value"]
|
|
3994
|
+
},
|
|
3995
|
+
deepCopy: {
|
|
3996
|
+
fn: (v) => deepCopy(v),
|
|
3997
|
+
argTypes: ["value"]
|
|
3998
|
+
}
|
|
3999
|
+
};
|
|
4000
|
+
}
|
|
4001
|
+
//#endregion
|
|
4002
|
+
export { Engine, EvalError, FuncNotFoundError, MissingFieldError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDefaults, sprigDicts, sprigLists, sprigMath, sprigRegex, sprigStrings, sprigTypes };
|
|
4003
|
+
|
|
4004
|
+
//# sourceMappingURL=index.js.map
|