bitgpu 0.19.1 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region node_modules/@huggingface/tokenizers/dist/tokenizers.mjs
1
+ // node_modules/@huggingface/tokenizers/dist/tokenizers.mjs
2
2
  var DictionarySplitter = class {
3
3
  /**
4
4
  * @param dictionary The dictionary of words to use for splitting.
@@ -70,64 +70,40 @@ var AddedToken = class {
70
70
  }
71
71
  };
72
72
  var AddedToken_default = AddedToken;
73
- var BYTES_TO_UNICODE = (() => {
74
- const bs = [
75
- ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
76
- ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
77
- ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0))
78
- ];
79
- const cs = bs.slice();
80
- let n = 0;
81
- for (let b = 0; b < 256; ++b) if (!bs.includes(b)) {
82
- bs.push(b);
83
- cs.push(256 + n);
84
- n += 1;
85
- }
86
- const ccs = cs.map((n2) => String.fromCharCode(n2));
87
- return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
88
- })();
89
- var reverse_dictionary = (data) => Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
90
- var UNICODE_TO_BYTES = reverse_dictionary(BYTES_TO_UNICODE);
91
- var BLOOM_SPLIT_CHARS = ".,!?…。,、।۔،";
92
- var PROBLEMATIC_REGEX_MAP = /* @__PURE__ */ new Map([
93
- ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],
94
- ["(?i:[sdmt]|ll|ve|re)", "(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],
95
- ["[^\\r\\n\\p{L}\\p{N}]?+", "[^\\r\\n\\p{L}\\p{N}]?"],
96
- ["[^\\s\\p{L}\\p{N}]++", "[^\\s\\p{L}\\p{N}]+"],
97
- ["(?>\\p{Nd}{510})", "(?:\\p{Nd}{510})"],
98
- ["\\p{Nd}{3}+", "(?:\\p{Nd}{3})+"],
99
- ["\\G", ""],
100
- [` ?[^(\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\s${BLOOM_SPLIT_CHARS}]+`]
101
- ]);
102
- var PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";
103
- var clean_up_tokenization = (text) => text.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n't/g, "n't").replace(/ 'm/g, "'m").replace(/ 's/g, "'s").replace(/ 've/g, "'ve").replace(/ 're/g, "'re");
104
- var create_pattern = (pattern, invert = true) => {
105
- if (pattern.Regex !== void 0) {
106
- let regex = pattern.Regex.replace(/\\([#&~])/g, "$1");
107
- regex = regex.replace(/\\A/g, "^").replace(/\\z/g, "$").replace(/\\Z/g, "(?=\\r?\\n?$)");
108
- for (const [key, value] of PROBLEMATIC_REGEX_MAP) regex = regex.replaceAll(key, value);
109
- try {
110
- return new RegExp(regex, "gu");
111
- } catch (error) {
112
- if (!(error instanceof SyntaxError) || !error.message.toLowerCase().includes("invalid property name")) throw error;
113
- let changed = false;
114
- const fixed = regex.replace(/(\\[pP])\{([^}=]+)\}/g, (_, p, n) => {
73
+ var compile_unicode_regexp = (source, flags) => {
74
+ try {
75
+ return new RegExp(source, flags);
76
+ } catch (error) {
77
+ if (!(error instanceof SyntaxError)) throw error;
78
+ const property_names = /* @__PURE__ */ new Map();
79
+ const rewritten = source.replace(/(\\[pP])\{([^}=]+)\}/g, (text, p, n, offset) => {
80
+ let preceding_backslashes = 0;
81
+ for (let i = offset - 1; i >= 0 && source[i] === "\\"; --i) ++preceding_backslashes;
82
+ if (preceding_backslashes % 2 === 1) return text;
83
+ let property_name = property_names.get(n);
84
+ if (property_name === void 0) {
115
85
  try {
116
86
  new RegExp(`\\p{${n}}`, "u");
117
- return `${p}{${n}}`;
87
+ property_name = n;
118
88
  } catch {
119
- changed = true;
120
- return `${p}{Script=${n}}`;
89
+ property_name = `Script=${n}`;
121
90
  }
122
- });
123
- if (!changed) throw error;
124
- try {
125
- return new RegExp(fixed, "gu");
126
- } catch (e) {
127
- throw error;
91
+ property_names.set(n, property_name);
128
92
  }
93
+ return `${p}{${property_name}}`;
94
+ });
95
+ if (rewritten === source) throw error;
96
+ try {
97
+ return new RegExp(rewritten, flags);
98
+ } catch {
99
+ throw error;
129
100
  }
130
- } else if (pattern.String !== void 0) {
101
+ }
102
+ };
103
+ var clean_up_tokenization = (text) => text.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n't/g, "n't").replace(/ 'm/g, "'m").replace(/ 's/g, "'s").replace(/ 've/g, "'ve").replace(/ 're/g, "'re");
104
+ var create_pattern = (pattern, invert = true) => {
105
+ if (pattern.Regex !== void 0) return compile_unicode_regexp(rewrite_oniguruma_to_js(normalize_bloom_split_char_class(pattern.Regex)), "gu");
106
+ else if (pattern.String !== void 0) {
131
107
  const escaped = escape_reg_exp(pattern.String);
132
108
  return new RegExp(invert ? escaped : `(${escaped})`, "gu");
133
109
  } else {
@@ -135,6 +111,406 @@ var create_pattern = (pattern, invert = true) => {
135
111
  return null;
136
112
  }
137
113
  };
114
+ var UNICODE_WORD_CHARS_IN_CLASS = "\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}";
115
+ var UNICODE_WORD_CHARS = `${UNICODE_WORD_CHARS_IN_CLASS}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`;
116
+ var UNICODE_WORD_CLASS = `[${UNICODE_WORD_CHARS}]`;
117
+ var UNICODE_NON_WORD_CLASS = `[^${UNICODE_WORD_CHARS}]`;
118
+ var UNICODE_WORD_BOUNDARY = `(?:(?<!${UNICODE_WORD_CLASS})(?=${UNICODE_WORD_CLASS})|(?<=${UNICODE_WORD_CLASS})(?!${UNICODE_WORD_CLASS}))`;
119
+ var UNICODE_NON_WORD_BOUNDARY = `(?:(?<!${UNICODE_WORD_CLASS})(?!${UNICODE_WORD_CLASS})|(?<=${UNICODE_WORD_CLASS})(?=${UNICODE_WORD_CLASS}))`;
120
+ var LINE_START_ANCHOR = "(?:(?<![\\s\\S])|(?<=\\n))";
121
+ var LINE_END_ANCHOR = "(?:(?=\\n)|(?![\\s\\S]))";
122
+ var HEX_DIGIT_CHARS = "0-9A-Fa-f";
123
+ var ESCAPE_REWRITES = /* @__PURE__ */ new Map([
124
+ ["A", "(?<![\\s\\S])"],
125
+ ["z", "(?![\\s\\S])"],
126
+ ["Z", "(?=\\n?(?![\\s\\S]))"],
127
+ ["h", `[${HEX_DIGIT_CHARS}]`],
128
+ ["H", `[^${HEX_DIGIT_CHARS}]`],
129
+ ["w", UNICODE_WORD_CLASS],
130
+ ["W", UNICODE_NON_WORD_CLASS],
131
+ ["d", "\\p{Nd}"],
132
+ ["D", "\\P{Nd}"],
133
+ ["s", "\\p{White_Space}"],
134
+ ["S", "\\P{White_Space}"],
135
+ ["b", UNICODE_WORD_BOUNDARY],
136
+ ["B", UNICODE_NON_WORD_BOUNDARY],
137
+ ["a", "\\x07"],
138
+ ["e", "\\x1B"]
139
+ ]);
140
+ var CLASS_ESCAPE_REWRITES = /* @__PURE__ */ new Map([
141
+ ["h", HEX_DIGIT_CHARS],
142
+ ["w", UNICODE_WORD_CHARS_IN_CLASS],
143
+ ["d", "\\p{Nd}"],
144
+ ["D", "\\P{Nd}"],
145
+ ["s", "\\p{White_Space}"],
146
+ ["S", "\\P{White_Space}"],
147
+ ["a", "\\x07"],
148
+ ["e", "\\x1B"]
149
+ ]);
150
+ var CLASS_COMPLEMENT_ALTERNATIVES = /* @__PURE__ */ new Map([["W", `[^${UNICODE_WORD_CHARS_IN_CLASS}]`], ["H", `[^${HEX_DIGIT_CHARS}]`]]);
151
+ var RAW_WHITESPACE_ESCAPES = /* @__PURE__ */ new Map([
152
+ ["\n", "\\n"],
153
+ ["\r", "\\r"],
154
+ [" ", "\\t"],
155
+ ["\f", "\\f"],
156
+ ["\v", "\\v"]
157
+ ]);
158
+ var POSIX_CLASS_FRAGMENTS = /* @__PURE__ */ new Map([
159
+ ["alpha", "\\p{Alphabetic}"],
160
+ ["alnum", "\\p{Alphabetic}\\p{Nd}"],
161
+ ["digit", "\\p{Nd}"],
162
+ ["lower", "\\p{Lowercase}"],
163
+ ["upper", "\\p{Uppercase}"],
164
+ ["space", "\\p{White_Space}"],
165
+ ["blank", "\\t\\p{Zs}"],
166
+ ["punct", "\\p{P}\\p{S}"],
167
+ ["cntrl", "\\p{Cc}"],
168
+ ["word", UNICODE_WORD_CHARS_IN_CLASS],
169
+ ["xdigit", HEX_DIGIT_CHARS]
170
+ ]);
171
+ var JS_SYNTAX_CHARS = "^$\\.*+?()[]{}|/";
172
+ var GROUP_PREFIX_RE = /^\(\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/;
173
+ var BRACED_ESCAPE_RE = /^\\([pPxu])\{([^}]*)\}/;
174
+ var QUANTIFIER_BRACE_RE = /^\{(\d+(?:,\d*)?|,\d+)\}/;
175
+ var POSIX_BRACKET_RE = /^\[:(\^?)(\p{Alphabetic}+):\]/u;
176
+ var EMPTY_NEGATED_POSIX_BRACKET_RE = /^\[:\^:\]/;
177
+ var UNSUPPORTED_POSIX_BRACKET_RE = /^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/;
178
+ var FIXED_WIDTH_ESCAPE_RE = /^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/;
179
+ var is_ascii_letter = (char) => char >= "A" && char <= "Z" || char >= "a" && char <= "z";
180
+ var character_at = (text, index) => String.fromCodePoint(text.codePointAt(index));
181
+ var get_ascii_folded_hex_atom = (hex) => {
182
+ if (!/^[0-9A-Fa-f]{1,8}$/.test(hex)) return null;
183
+ const code_point = Number.parseInt(hex, 16);
184
+ if (code_point > 127) return null;
185
+ const letter = String.fromCharCode(code_point);
186
+ return is_ascii_letter(letter) ? `[${letter.toLowerCase()}${letter.toUpperCase()}]` : null;
187
+ };
188
+ var normalize_bloom_split_char_class = (regex) => regex.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g, "[^()|\\s$1]");
189
+ var ANY_CODE_POINT = "[\\s\\S]";
190
+ var MAX_CHARACTER_CLASS_NESTING_DEPTH = 256;
191
+ var create_character_class_operand = () => ({
192
+ fragment: "",
193
+ alternatives: [],
194
+ tail: null,
195
+ contains_complex_set: false
196
+ });
197
+ var throw_character_class_range_error = (index) => {
198
+ throw new SyntaxError(`Unsupported range with a set-valued character-class operand at index ${index}`);
199
+ };
200
+ var add_character_class_atom = (operand, atom, index, contains_complex_set = true) => {
201
+ if (operand.tail === "range") throw_character_class_range_error(index);
202
+ operand.alternatives.push(atom);
203
+ operand.tail = "set";
204
+ operand.contains_complex_set = operand.contains_complex_set || contains_complex_set;
205
+ };
206
+ var append_character_class_fragment = (operand, fragment, set_valued = false, index = -1) => {
207
+ if (set_valued && operand.tail === "range") throw_character_class_range_error(index);
208
+ if (operand.tail === "range") {
209
+ operand.fragment += fragment;
210
+ operand.tail = "complete_range";
211
+ return;
212
+ }
213
+ operand.fragment += fragment;
214
+ operand.tail = set_valued ? "set" : "scalar";
215
+ operand.contains_complex_set = operand.contains_complex_set || set_valued;
216
+ };
217
+ var rewrite_character_class_escape = (regex, index, operand) => {
218
+ const braced = BRACED_ESCAPE_RE.exec(regex.slice(index));
219
+ if (braced) {
220
+ const [text, kind, body] = braced;
221
+ if (kind === "P" && body === "Word") add_character_class_atom(operand, `[^${UNICODE_WORD_CHARS_IN_CLASS}]`, index);
222
+ else append_character_class_fragment(operand, kind === "x" ? `\\u{${body}}` : kind === "p" && body === "Word" ? UNICODE_WORD_CHARS_IN_CLASS : text, kind === "p" || kind === "P", index);
223
+ return index + text.length;
224
+ }
225
+ const fixed_width = FIXED_WIDTH_ESCAPE_RE.exec(regex.slice(index));
226
+ if (fixed_width) {
227
+ append_character_class_fragment(operand, fixed_width[0]);
228
+ return index + fixed_width[0].length;
229
+ }
230
+ if (index + 1 >= regex.length) throw new SyntaxError(`Unterminated escape in character class at index ${index}`);
231
+ const next = character_at(regex, index + 1);
232
+ const next_end = index + 1 + next.length;
233
+ const raw_whitespace = RAW_WHITESPACE_ESCAPES.get(next);
234
+ if (raw_whitespace !== void 0) {
235
+ append_character_class_fragment(operand, raw_whitespace);
236
+ return next_end;
237
+ }
238
+ const complement = CLASS_COMPLEMENT_ALTERNATIVES.get(next);
239
+ if (complement !== void 0) {
240
+ add_character_class_atom(operand, complement, index);
241
+ return next_end;
242
+ }
243
+ const rewrite = CLASS_ESCAPE_REWRITES.get(next);
244
+ let replacement;
245
+ let set_valued = false;
246
+ if (rewrite !== void 0) {
247
+ replacement = rewrite;
248
+ set_valued = next !== "a" && next !== "e";
249
+ } else if (/[A-Za-z0-9]/.test(next)) replacement = `\\${next}`;
250
+ else if (JS_SYNTAX_CHARS.includes(next) || next === "-") replacement = `\\${next}`;
251
+ else replacement = next;
252
+ append_character_class_fragment(operand, replacement, set_valued, index);
253
+ return next_end;
254
+ };
255
+ var compile_character_set_union = (pieces) => {
256
+ if (pieces.length === 1) return pieces[0];
257
+ return `(?:(?=(?:${pieces.join("|")}))${ANY_CODE_POINT})`;
258
+ };
259
+ var compile_character_class_operand = (operand) => {
260
+ return compile_character_set_union(operand.fragment.length === 0 ? operand.alternatives : [`[${operand.fragment}]`, ...operand.alternatives]);
261
+ };
262
+ var get_ascii_fold_additions = (positive_atom) => {
263
+ const membership = compile_unicode_regexp(`^(?:${positive_atom})$`, "u");
264
+ let additions = "";
265
+ for (let offset = 0; offset < 26; ++offset) {
266
+ const upper = String.fromCharCode(65 + offset);
267
+ const lower = String.fromCharCode(97 + offset);
268
+ const has_upper = membership.test(upper);
269
+ if (has_upper !== membership.test(lower)) additions += has_upper ? lower : upper;
270
+ }
271
+ return additions;
272
+ };
273
+ var parse_character_class = (regex, start, ascii_fold, apply_ascii_fold = true, nesting_depth = 1) => {
274
+ if (nesting_depth > MAX_CHARACTER_CLASS_NESTING_DEPTH) throw new SyntaxError(`Maximum character-class nesting depth of ${MAX_CHARACTER_CLASS_NESTING_DEPTH} exceeded at index ${start}`);
275
+ let i = start + 1;
276
+ const negated = regex[i] === "^";
277
+ if (negated) ++i;
278
+ const first_content_index = i;
279
+ const operands = [create_character_class_operand()];
280
+ let operand = operands[0];
281
+ let contains_nested_negated_complex_set = false;
282
+ while (i < regex.length) {
283
+ const char = character_at(regex, i);
284
+ if (char === "\\") {
285
+ i = rewrite_character_class_escape(regex, i, operand);
286
+ continue;
287
+ }
288
+ if (char === "]") {
289
+ if (i === first_content_index) {
290
+ append_character_class_fragment(operand, "\\]");
291
+ ++i;
292
+ continue;
293
+ }
294
+ if (operand.tail === null) {
295
+ if (operands.length > 1) throw new SyntaxError(`Malformed character-class intersection with an empty operand at index ${i}`);
296
+ throw new SyntaxError(`Empty character class at index ${start}`);
297
+ }
298
+ const contains_complex_set = operands.some((candidate) => candidate.contains_complex_set);
299
+ if (negated && operands.length > 1 && contains_nested_negated_complex_set) throw new SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${start}`);
300
+ const first_atom = compile_character_class_operand(operands[0]);
301
+ let positive_atom = first_atom;
302
+ if (operands.length > 1) {
303
+ let lookaheads = "";
304
+ for (let j = 1; j < operands.length; ++j) lookaheads += `(?=${compile_character_class_operand(operands[j])})`;
305
+ positive_atom = `(?:${lookaheads}${first_atom})`;
306
+ }
307
+ const is_direct_class = operands.length === 1 && operand.alternatives.length === 0;
308
+ let direct_fragment = operand.fragment;
309
+ if (ascii_fold && apply_ascii_fold) {
310
+ const additions = get_ascii_fold_additions(positive_atom);
311
+ if (additions.length > 0) {
312
+ if (is_direct_class) {
313
+ direct_fragment += additions;
314
+ positive_atom = `[${direct_fragment}]`;
315
+ } else positive_atom = compile_character_set_union([positive_atom, `[${additions}]`]);
316
+ }
317
+ }
318
+ return {
319
+ atom: negated ? is_direct_class ? `[^${direct_fragment}]` : `(?:(?!${positive_atom})${ANY_CODE_POINT})` : positive_atom,
320
+ end: i + 1,
321
+ negated,
322
+ contains_complex_set,
323
+ contains_nested_negated_complex_set
324
+ };
325
+ }
326
+ if (regex.startsWith("&&", i)) {
327
+ if (operand.tail === null) throw new SyntaxError(`Malformed character-class intersection with an empty operand at index ${i}`);
328
+ operand = create_character_class_operand();
329
+ operands.push(operand);
330
+ i += 2;
331
+ continue;
332
+ }
333
+ if (char === "[") {
334
+ const suffix = regex.slice(i);
335
+ if (EMPTY_NEGATED_POSIX_BRACKET_RE.test(suffix)) throw new SyntaxError(`Malformed empty negated POSIX character class at index ${i}`);
336
+ const posix = POSIX_BRACKET_RE.exec(suffix);
337
+ if (posix) {
338
+ const [, posix_negated, name] = posix;
339
+ const fragment = POSIX_CLASS_FRAGMENTS.get(name);
340
+ if (fragment === void 0) throw new SyntaxError(`Unsupported POSIX character class "${name}" at index ${i}`);
341
+ if (ascii_fold && posix_negated && (name === "lower" || name === "upper")) throw new SyntaxError(`Unsupported negated POSIX ${name} class inside an inline case-insensitive group`);
342
+ if (posix_negated) add_character_class_atom(operand, `[^${fragment}]`, i);
343
+ else append_character_class_fragment(operand, fragment, true, i);
344
+ i += posix[0].length;
345
+ continue;
346
+ }
347
+ if (UNSUPPORTED_POSIX_BRACKET_RE.test(suffix)) throw new SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${i}`);
348
+ const nested = parse_character_class(regex, i, ascii_fold, false, nesting_depth + 1);
349
+ add_character_class_atom(operand, nested.atom, i, nested.contains_complex_set);
350
+ contains_nested_negated_complex_set ||= nested.contains_nested_negated_complex_set || nested.negated && nested.contains_complex_set;
351
+ i = nested.end;
352
+ continue;
353
+ }
354
+ if (char === "-") {
355
+ const is_terminal_literal = regex[i + 1] === "]" || regex.startsWith("&&", i + 1);
356
+ if (operand.tail === "set" && !is_terminal_literal) throw_character_class_range_error(i);
357
+ if (operand.tail === null || operand.tail === "range" || operand.tail === "complete_range" || is_terminal_literal) append_character_class_fragment(operand, "\\-");
358
+ else {
359
+ operand.fragment += "-";
360
+ operand.tail = "range";
361
+ }
362
+ ++i;
363
+ continue;
364
+ }
365
+ append_character_class_fragment(operand, char === "^" && operand.fragment.length === 0 ? "\\^" : char);
366
+ i += char.length;
367
+ }
368
+ throw new SyntaxError(`${operands.length > 1 ? "Unterminated character-class intersection" : "Unterminated character class"} at index ${start}`);
369
+ };
370
+ var rewrite_oniguruma_to_js = (regex) => {
371
+ let out = "";
372
+ let atom_start = -1;
373
+ let last_was_quantifier = false;
374
+ let ascii_fold = false;
375
+ const group_states = [];
376
+ const emit_atom = (text) => {
377
+ atom_start = out.length;
378
+ out += text;
379
+ last_was_quantifier = false;
380
+ };
381
+ for (let i = 0; i < regex.length;) {
382
+ const char = character_at(regex, i);
383
+ if (char === "\\") {
384
+ const braced = BRACED_ESCAPE_RE.exec(regex.slice(i));
385
+ if (braced) {
386
+ const [text, kind, body] = braced;
387
+ let replacement2 = text;
388
+ if (kind === "x") {
389
+ const code_point_escape = `\\u{${body}}`;
390
+ replacement2 = ascii_fold ? get_ascii_folded_hex_atom(body) ?? code_point_escape : code_point_escape;
391
+ } else if (body === "Word") replacement2 = kind === "p" ? UNICODE_WORD_CLASS : UNICODE_NON_WORD_CLASS;
392
+ emit_atom(replacement2);
393
+ i += text.length;
394
+ continue;
395
+ }
396
+ const fixed_width = FIXED_WIDTH_ESCAPE_RE.exec(regex.slice(i));
397
+ if (fixed_width) {
398
+ const text = fixed_width[0];
399
+ emit_atom(ascii_fold && text[1] !== "c" ? get_ascii_folded_hex_atom(text.slice(2)) ?? text : text);
400
+ i += text.length;
401
+ continue;
402
+ }
403
+ if (i + 1 >= regex.length) {
404
+ out += char;
405
+ break;
406
+ }
407
+ const next = character_at(regex, i + 1);
408
+ i += 1 + next.length;
409
+ if (next === "G") continue;
410
+ const raw_whitespace = RAW_WHITESPACE_ESCAPES.get(next);
411
+ if (raw_whitespace !== void 0) {
412
+ emit_atom(raw_whitespace);
413
+ continue;
414
+ }
415
+ const rewrite = ESCAPE_REWRITES.get(next);
416
+ let replacement;
417
+ if (rewrite !== void 0) replacement = rewrite;
418
+ else if (/[A-Za-z0-9]/.test(next)) replacement = `\\${next}`;
419
+ else if (JS_SYNTAX_CHARS.includes(next)) replacement = `\\${next}`;
420
+ else replacement = next;
421
+ emit_atom(replacement);
422
+ continue;
423
+ }
424
+ switch (char) {
425
+ case "[": {
426
+ const parsed = parse_character_class(regex, i, ascii_fold);
427
+ emit_atom(parsed.atom);
428
+ i = parsed.end;
429
+ continue;
430
+ }
431
+ case "]":
432
+ emit_atom("\\]");
433
+ ++i;
434
+ continue;
435
+ case ".":
436
+ emit_atom("[^\\n]");
437
+ ++i;
438
+ continue;
439
+ case "^":
440
+ emit_atom(LINE_START_ANCHOR);
441
+ ++i;
442
+ continue;
443
+ case "$":
444
+ emit_atom(LINE_END_ANCHOR);
445
+ ++i;
446
+ continue;
447
+ case "(": {
448
+ const inline_case_insensitive = regex.startsWith("(?i:", i);
449
+ const source_prefix = inline_case_insensitive ? "(?i:" : GROUP_PREFIX_RE.exec(regex.slice(i))?.[0] ?? "(";
450
+ const output_prefix = inline_case_insensitive ? "(?:" : source_prefix === "(?>" ? "(?:" : source_prefix;
451
+ group_states.push([out.length, ascii_fold]);
452
+ if (inline_case_insensitive) ascii_fold = true;
453
+ out += output_prefix;
454
+ last_was_quantifier = false;
455
+ i += source_prefix.length;
456
+ continue;
457
+ }
458
+ case ")":
459
+ out += char;
460
+ [atom_start, ascii_fold] = group_states.pop() ?? [-1, false];
461
+ last_was_quantifier = false;
462
+ ++i;
463
+ continue;
464
+ case "|":
465
+ out += char;
466
+ atom_start = -1;
467
+ last_was_quantifier = false;
468
+ ++i;
469
+ continue;
470
+ case "{": {
471
+ const quant = QUANTIFIER_BRACE_RE.exec(regex.slice(i));
472
+ if (!quant || atom_start < 0) {
473
+ emit_atom("\\{");
474
+ ++i;
475
+ continue;
476
+ }
477
+ const body = quant[1].startsWith(",") ? `0${quant[1]}` : quant[1];
478
+ i += quant[0].length;
479
+ const following = regex[i];
480
+ if (following === "+" || following === "*") {
481
+ out = `${out.slice(0, atom_start)}(?:${out.slice(atom_start)}{${body}})${following}`;
482
+ ++i;
483
+ } else out += `{${body}}`;
484
+ last_was_quantifier = true;
485
+ continue;
486
+ }
487
+ case "}":
488
+ emit_atom("\\}");
489
+ ++i;
490
+ continue;
491
+ case "+":
492
+ if (last_was_quantifier) {
493
+ ++i;
494
+ continue;
495
+ }
496
+ out += char;
497
+ last_was_quantifier = true;
498
+ ++i;
499
+ continue;
500
+ case "*":
501
+ case "?":
502
+ out += char;
503
+ last_was_quantifier = true;
504
+ ++i;
505
+ continue;
506
+ default:
507
+ emit_atom(ascii_fold && is_ascii_letter(char) ? `[${char.toLowerCase()}${char.toUpperCase()}]` : char);
508
+ i += char.length;
509
+ continue;
510
+ }
511
+ }
512
+ return out;
513
+ };
138
514
  var escape_reg_exp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
139
515
  var fuse_unk = (arr, tokens_to_ids, unk_token_id) => {
140
516
  const fused = [];
@@ -324,14 +700,20 @@ var Sequence = class extends Normalizer_default {
324
700
  };
325
701
  var Sequence_default = Sequence;
326
702
  var Replace = class extends Normalizer_default {
703
+ /**
704
+ * @param config The configuration object for the normalizer.
705
+ */
706
+ constructor(config) {
707
+ super(config);
708
+ this.pattern = create_pattern(this.config.pattern ?? {});
709
+ }
327
710
  /**
328
711
  * Normalize the input text by replacing the pattern with the content.
329
712
  * @param text The input text to be normalized.
330
713
  * @returns The normalized text after replacing the pattern with the content.
331
714
  */
332
715
  normalize(text) {
333
- const pattern = create_pattern(this.config.pattern ?? {});
334
- return pattern === null ? text : text.replaceAll(pattern, this.config.content ?? "");
716
+ return this.pattern === null ? text : text.replaceAll(this.pattern, this.config.content ?? "");
335
717
  }
336
718
  };
337
719
  var Replace_default = Replace;
@@ -473,6 +855,25 @@ var PreTokenizer = class extends Callable_default {
473
855
  }
474
856
  };
475
857
  var PreTokenizer_default = PreTokenizer;
858
+ var BYTES_TO_UNICODE = (() => {
859
+ const bs = [
860
+ ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
861
+ ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
862
+ ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0))
863
+ ];
864
+ const cs = bs.slice();
865
+ let n = 0;
866
+ for (let b = 0; b < 256; ++b) if (!bs.includes(b)) {
867
+ bs.push(b);
868
+ cs.push(256 + n);
869
+ n += 1;
870
+ }
871
+ const ccs = cs.map((n2) => String.fromCharCode(n2));
872
+ return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
873
+ })();
874
+ var reverse_dictionary = (data) => Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
875
+ var UNICODE_TO_BYTES = reverse_dictionary(BYTES_TO_UNICODE);
876
+ var PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";
476
877
  var ByteLevel = class extends PreTokenizer_default {
477
878
  /**
478
879
  * Creates a new instance of the `ByteLevelPreTokenizer` class.
@@ -553,7 +954,7 @@ var Split = class extends PreTokenizer_default {
553
954
  */
554
955
  pre_tokenize_text(text) {
555
956
  if (this.pattern === null) return [];
556
- if (this.config.invert) return text.match(this.pattern) || [];
957
+ if (this.config.invert) return (text.match(this.pattern) || []).filter((x) => x);
557
958
  else if (this.config.behavior?.toLowerCase() === "removed") return text.split(this.pattern).filter((x) => x);
558
959
  else return regex_split(text, this.pattern);
559
960
  }
@@ -842,15 +1243,17 @@ var CharTrie = class {
842
1243
  node.is_leaf = true;
843
1244
  }
844
1245
  /**
845
- * Searches the trie for all strings with a common prefix of `text`.
846
- * @param text The common prefix to search for.
847
- * @yields Each string in the trie that has `text` as a prefix.
1246
+ * Searches the trie for stored strings that match `chars` starting at `start`.
1247
+ * @param chars The input characters to search.
1248
+ * @param start The index to start searching from.
1249
+ * @yields Each stored string that is a prefix of `chars` starting at `start`.
848
1250
  */
849
- *common_prefix_search(text) {
1251
+ *common_prefix_search(chars, start = 0) {
850
1252
  let node = this.root;
851
1253
  if (node === void 0) return;
852
1254
  let prefix = "";
853
- for (const ch of text) {
1255
+ for (let i = start; i < chars.length; ++i) {
1256
+ const ch = chars[i];
854
1257
  prefix += ch;
855
1258
  node = node.children.get(ch);
856
1259
  if (node === void 0) return;
@@ -920,8 +1323,7 @@ var TokenLattice = class {
920
1323
  * @param token_id The token ID of the token.
921
1324
  */
922
1325
  insert(pos, length, score, token_id) {
923
- const node_id = this.nodes.length;
924
- const node = new TokenLatticeNode(token_id, node_id, pos, length, score);
1326
+ const node = new TokenLatticeNode(token_id, this.nodes.length, pos, length, score);
925
1327
  this.begin_nodes[pos].push(node);
926
1328
  this.end_nodes[pos + length].push(node);
927
1329
  this.nodes.push(node);
@@ -1034,11 +1436,8 @@ var Unigram = class extends TokenizerModel_default {
1034
1436
  let begin_pos = 0;
1035
1437
  while (begin_pos < chars.length) {
1036
1438
  let has_single_node = false;
1037
- const tokens = [];
1038
- const sliced = chars.slice(begin_pos).join("");
1039
- const prefixed_tokens = this.trie.common_prefix_search(sliced);
1439
+ const prefixed_tokens = this.trie.common_prefix_search(chars, begin_pos);
1040
1440
  for (const token of prefixed_tokens) {
1041
- tokens.push(token);
1042
1441
  const token_id = this.tokens_to_ids.get(token);
1043
1442
  const token_score = this.scores[token_id];
1044
1443
  const n = len(token);
@@ -1081,7 +1480,7 @@ var PriorityQueue = class {
1081
1480
  * @param comparator Comparator function to determine priority. Defaults to a MaxHeap.
1082
1481
  * @param max_size Maximum size of the queue. Defaults to Infinity.
1083
1482
  */
1084
- constructor(comparator = (a, b) => a > b, max_size = Infinity) {
1483
+ constructor(comparator = (a, b) => a > b, max_size = 1e400) {
1085
1484
  this._heap = [];
1086
1485
  this._comparator = comparator;
1087
1486
  this._max_size = max_size;
@@ -1449,16 +1848,19 @@ function create_tokenizer_model(model_config, config) {
1449
1848
  case "Unigram": return new Unigram_default(model_config, config.eos_token);
1450
1849
  case "BPE": return new BPE_default(model_config);
1451
1850
  default:
1452
- if (model_config.vocab) if (Array.isArray(model_config.vocab)) return new Unigram_default(model_config, config.eos_token);
1453
- else if (Object.hasOwn(model_config, "continuing_subword_prefix") && Object.hasOwn(model_config, "unk_token")) if (Object.hasOwn(model_config, "merges")) return new BPE_default(model_config);
1454
- else return new WordPiece_default(model_config);
1455
- else return new Legacy_default(model_config, {
1456
- target_lang: config.target_lang,
1457
- bos_token: config.bos_token,
1458
- eos_token: config.eos_token,
1459
- pad_token: config.pad_token,
1460
- unk_token: config.unk_token
1461
- });
1851
+ if (model_config.vocab) {
1852
+ if (Array.isArray(model_config.vocab)) return new Unigram_default(model_config, config.eos_token);
1853
+ else if (Object.hasOwn(model_config, "continuing_subword_prefix") && Object.hasOwn(model_config, "unk_token")) {
1854
+ if (Object.hasOwn(model_config, "merges")) return new BPE_default(model_config);
1855
+ else return new WordPiece_default(model_config);
1856
+ } else return new Legacy_default(model_config, {
1857
+ target_lang: config.target_lang,
1858
+ bos_token: config.bos_token,
1859
+ eos_token: config.eos_token,
1860
+ pad_token: config.pad_token,
1861
+ unk_token: config.unk_token
1862
+ });
1863
+ }
1462
1864
  throw new Error(`Unknown TokenizerModel type: ${model_config?.type}`);
1463
1865
  }
1464
1866
  }
@@ -1801,9 +2203,16 @@ var Sequence4 = class extends Decoder_default {
1801
2203
  };
1802
2204
  var Sequence_default4 = Sequence4;
1803
2205
  var Replace3 = class extends Decoder_default {
2206
+ /**
2207
+ * @param config The configuration object for the decoder.
2208
+ */
2209
+ constructor(config) {
2210
+ super(config);
2211
+ this.pattern = create_pattern(this.config.pattern);
2212
+ }
1804
2213
  decode_chain(tokens) {
1805
- const pattern = create_pattern(this.config.pattern);
1806
2214
  const content = this.config.content ?? "";
2215
+ const pattern = this.pattern;
1807
2216
  return pattern === null ? tokens : tokens.map((token) => token.replaceAll(pattern, content));
1808
2217
  }
1809
2218
  };
@@ -2061,8 +2470,7 @@ var Tokenizer = class {
2061
2470
  }
2062
2471
  };
2063
2472
  var Tokenizer_default = Tokenizer;
2064
- //#endregion
2065
- //#region node_modules/@huggingface/jinja/dist/index.js
2473
+ // node_modules/@huggingface/jinja/dist/index.js
2066
2474
  var __defProp = Object.defineProperty;
2067
2475
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
2068
2476
  enumerable: true,
@@ -2097,6 +2505,7 @@ var TOKEN_TYPES = Object.freeze({
2097
2505
  CallOperator: "CallOperator",
2098
2506
  AdditiveBinaryOperator: "AdditiveBinaryOperator",
2099
2507
  MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator",
2508
+ ExponentiationBinaryOperator: "ExponentiationBinaryOperator",
2100
2509
  ComparisonBinaryOperator: "ComparisonBinaryOperator",
2101
2510
  UnaryOperator: "UnaryOperator",
2102
2511
  Comment: "Comment"
@@ -2112,14 +2521,15 @@ var Token = class {
2112
2521
  this.type = type;
2113
2522
  }
2114
2523
  };
2115
- function isWord(char) {
2116
- return /\w/.test(char);
2524
+ function isWord(code) {
2525
+ return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
2117
2526
  }
2118
- function isInteger(char) {
2119
- return /[0-9]/.test(char);
2527
+ function isInteger(code) {
2528
+ return code >= 48 && code <= 57;
2120
2529
  }
2121
- function isWhitespace(char) {
2122
- return /\s/.test(char);
2530
+ function isWhitespace(code) {
2531
+ if (code <= 32) return code === 32 || code >= 9 && code <= 13;
2532
+ return code > 127 && (code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288 || code === 65279);
2123
2533
  }
2124
2534
  var ORDERED_MAPPING_TABLE = [
2125
2535
  ["{%", TOKEN_TYPES.OpenStatement],
@@ -2145,11 +2555,15 @@ var ORDERED_MAPPING_TABLE = [
2145
2555
  ["+", TOKEN_TYPES.AdditiveBinaryOperator],
2146
2556
  ["-", TOKEN_TYPES.AdditiveBinaryOperator],
2147
2557
  ["~", TOKEN_TYPES.AdditiveBinaryOperator],
2558
+ ["**", TOKEN_TYPES.ExponentiationBinaryOperator],
2148
2559
  ["*", TOKEN_TYPES.MultiplicativeBinaryOperator],
2560
+ ["//", TOKEN_TYPES.MultiplicativeBinaryOperator],
2149
2561
  ["/", TOKEN_TYPES.MultiplicativeBinaryOperator],
2150
2562
  ["%", TOKEN_TYPES.MultiplicativeBinaryOperator],
2151
2563
  ["=", TOKEN_TYPES.Equals]
2152
2564
  ];
2565
+ var RULES_BY_FIRST_CHAR_CODE = [];
2566
+ for (const rule of ORDERED_MAPPING_TABLE) (RULES_BY_FIRST_CHAR_CODE[rule[0].charCodeAt(0)] ??= []).push(rule);
2153
2567
  var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([
2154
2568
  ["n", "\n"],
2155
2569
  ["t", " "],
@@ -2165,29 +2579,55 @@ function preprocess(template, options = {}) {
2165
2579
  if (template.endsWith("\n")) template = template.slice(0, -1);
2166
2580
  if (options.lstrip_blocks) template = template.replace(/^[ \t]*({[#%-])/gm, "$1");
2167
2581
  if (options.trim_blocks) template = template.replace(/([#%-]})\n/g, "$1");
2168
- return template.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs, (_, before, lstrip, rstrip, after) => (lstrip ? "" : before) + (rstrip ? "" : after));
2582
+ let result = "";
2583
+ let lastIndex = 0;
2584
+ for (const match of template.matchAll(/{%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs)) {
2585
+ const [fullMatch, lstrip, rstrip, after] = match;
2586
+ let endIndex = match.index;
2587
+ while (lstrip && endIndex > lastIndex && isWhitespace(template.charCodeAt(endIndex - 1))) --endIndex;
2588
+ result += template.slice(lastIndex, endIndex) + (rstrip ? "" : after);
2589
+ lastIndex = match.index + fullMatch.length;
2590
+ }
2591
+ return result + template.slice(lastIndex);
2169
2592
  }
2170
2593
  function tokenize(source, options = {}) {
2171
2594
  const tokens = [];
2172
2595
  const src = preprocess(source, options);
2596
+ const length = src.length;
2173
2597
  let cursorPosition = 0;
2174
2598
  let curlyBracketDepth = 0;
2599
+ const names = /* @__PURE__ */ new Map();
2175
2600
  const consumeWhile = (predicate) => {
2601
+ const start = cursorPosition;
2602
+ while (predicate(src.charCodeAt(cursorPosition))) if (++cursorPosition >= length) throw new SyntaxError("Unexpected end of input");
2603
+ return src.slice(start, cursorPosition);
2604
+ };
2605
+ const consumeString = (quote) => {
2176
2606
  let str = "";
2177
- while (predicate(src[cursorPosition])) {
2178
- if (src[cursorPosition] === "\\") {
2179
- ++cursorPosition;
2180
- if (cursorPosition >= src.length) throw new SyntaxError("Unexpected end of input");
2181
- const escaped = src[cursorPosition++];
2607
+ let start = cursorPosition;
2608
+ while (true) {
2609
+ if (cursorPosition >= length) throw new SyntaxError("Unexpected end of input");
2610
+ const char = src[cursorPosition];
2611
+ if (char === quote) break;
2612
+ ++cursorPosition;
2613
+ if (char !== "\\") continue;
2614
+ str += src.slice(start, cursorPosition - 1);
2615
+ if (cursorPosition >= length) throw new SyntaxError("Unexpected end of input");
2616
+ const escaped = src[cursorPosition++];
2617
+ if (escaped === "x" || escaped === "u") {
2618
+ const hexLength = escaped === "x" ? 2 : 4;
2619
+ const hex = src.slice(cursorPosition, cursorPosition + hexLength);
2620
+ if (hex.length !== hexLength || /[^0-9a-f]/i.test(hex)) throw new SyntaxError(`Invalid hexadecimal escape sequence: \\${escaped}${hex}`);
2621
+ str += String.fromCharCode(parseInt(hex, 16));
2622
+ cursorPosition += hexLength;
2623
+ } else {
2182
2624
  const unescaped = ESCAPE_CHARACTERS.get(escaped);
2183
2625
  if (unescaped === void 0) throw new SyntaxError(`Unexpected escaped character: ${escaped}`);
2184
2626
  str += unescaped;
2185
- continue;
2186
2627
  }
2187
- str += src[cursorPosition++];
2188
- if (cursorPosition >= src.length) throw new SyntaxError("Unexpected end of input");
2628
+ start = cursorPosition;
2189
2629
  }
2190
- return str;
2630
+ return str + src.slice(start, cursorPosition);
2191
2631
  };
2192
2632
  const stripTrailingWhitespace = () => {
2193
2633
  const lastToken = tokens.at(-1);
@@ -2197,66 +2637,81 @@ function tokenize(source, options = {}) {
2197
2637
  }
2198
2638
  };
2199
2639
  const skipLeadingWhitespace = () => {
2200
- while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) ++cursorPosition;
2640
+ while (cursorPosition < length && isWhitespace(src.charCodeAt(cursorPosition))) ++cursorPosition;
2201
2641
  };
2202
- main: while (cursorPosition < src.length) {
2642
+ main: while (cursorPosition < length) {
2203
2643
  const lastTokenType = tokens.at(-1)?.type;
2204
2644
  if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) {
2205
- let text = "";
2206
- while (cursorPosition < src.length && !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{" || src[cursorPosition + 1] === "#"))) text += src[cursorPosition++];
2207
- if (text.length > 0) {
2208
- tokens.push(new Token(text, TOKEN_TYPES.Text));
2645
+ let end = cursorPosition;
2646
+ while (true) {
2647
+ end = src.indexOf("{", end);
2648
+ if (end === -1) {
2649
+ end = length;
2650
+ break;
2651
+ }
2652
+ const next = src[end + 1];
2653
+ if (next === "%" || next === "{" || next === "#") break;
2654
+ ++end;
2655
+ }
2656
+ if (end > cursorPosition) {
2657
+ tokens.push(new Token(src.slice(cursorPosition, end), TOKEN_TYPES.Text));
2658
+ cursorPosition = end;
2209
2659
  continue;
2210
2660
  }
2211
2661
  }
2212
- if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") {
2213
- cursorPosition += 2;
2214
- const stripBefore = src[cursorPosition] === "-";
2215
- if (stripBefore) ++cursorPosition;
2216
- let comment = "";
2217
- while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") {
2218
- if (cursorPosition + 2 >= src.length) throw new SyntaxError("Missing end of comment tag");
2219
- comment += src[cursorPosition++];
2662
+ if (src[cursorPosition] === "{") {
2663
+ const nextChar = src[cursorPosition + 1];
2664
+ if (nextChar === "#") {
2665
+ cursorPosition += 2;
2666
+ const stripBefore = src[cursorPosition] === "-";
2667
+ if (stripBefore) ++cursorPosition;
2668
+ const end = src.indexOf("#}", cursorPosition);
2669
+ if (end === -1) throw new SyntaxError("Missing end of comment tag");
2670
+ let comment = src.slice(cursorPosition, end);
2671
+ const stripAfter = comment.endsWith("-");
2672
+ if (stripAfter) comment = comment.slice(0, -1);
2673
+ if (stripBefore) stripTrailingWhitespace();
2674
+ tokens.push(new Token(comment, TOKEN_TYPES.Comment));
2675
+ cursorPosition = end + 2;
2676
+ if (stripAfter) skipLeadingWhitespace();
2677
+ continue;
2678
+ }
2679
+ if (src[cursorPosition + 2] === "-") {
2680
+ if (nextChar === "%") {
2681
+ stripTrailingWhitespace();
2682
+ tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement));
2683
+ cursorPosition += 3;
2684
+ continue;
2685
+ }
2686
+ if (nextChar === "{") {
2687
+ stripTrailingWhitespace();
2688
+ tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression));
2689
+ curlyBracketDepth = 0;
2690
+ cursorPosition += 3;
2691
+ continue;
2692
+ }
2220
2693
  }
2221
- const stripAfter = comment.endsWith("-");
2222
- if (stripAfter) comment = comment.slice(0, -1);
2223
- if (stripBefore) stripTrailingWhitespace();
2224
- tokens.push(new Token(comment, TOKEN_TYPES.Comment));
2225
- cursorPosition += 2;
2226
- if (stripAfter) skipLeadingWhitespace();
2227
- continue;
2228
- }
2229
- if (src.slice(cursorPosition, cursorPosition + 3) === "{%-") {
2230
- stripTrailingWhitespace();
2231
- tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement));
2232
- cursorPosition += 3;
2233
- continue;
2234
- }
2235
- if (src.slice(cursorPosition, cursorPosition + 3) === "{{-") {
2236
- stripTrailingWhitespace();
2237
- tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression));
2238
- curlyBracketDepth = 0;
2239
- cursorPosition += 3;
2240
- continue;
2241
2694
  }
2242
2695
  consumeWhile(isWhitespace);
2243
- if (src.slice(cursorPosition, cursorPosition + 3) === "-%}") {
2244
- tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement));
2245
- cursorPosition += 3;
2246
- skipLeadingWhitespace();
2247
- continue;
2248
- }
2249
- if (src.slice(cursorPosition, cursorPosition + 3) === "-}}") {
2250
- tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression));
2251
- cursorPosition += 3;
2252
- skipLeadingWhitespace();
2253
- continue;
2254
- }
2255
2696
  const char = src[cursorPosition];
2697
+ if (char === "-" && src[cursorPosition + 2] === "}") {
2698
+ const nextChar = src[cursorPosition + 1];
2699
+ if (nextChar === "%") {
2700
+ tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement));
2701
+ cursorPosition += 3;
2702
+ skipLeadingWhitespace();
2703
+ continue;
2704
+ }
2705
+ if (nextChar === "}") {
2706
+ tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression));
2707
+ cursorPosition += 3;
2708
+ skipLeadingWhitespace();
2709
+ continue;
2710
+ }
2711
+ }
2256
2712
  if (char === "-" || char === "+") {
2257
- const lastTokenType2 = tokens.at(-1)?.type;
2258
- if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) throw new SyntaxError(`Unexpected character: ${char}`);
2259
- switch (lastTokenType2) {
2713
+ if (lastTokenType === TOKEN_TYPES.Text || lastTokenType === void 0) throw new SyntaxError(`Unexpected character: ${char}`);
2714
+ switch (lastTokenType) {
2260
2715
  case TOKEN_TYPES.Identifier:
2261
2716
  case TOKEN_TYPES.NumericLiteral:
2262
2717
  case TOKEN_TYPES.StringLiteral:
@@ -2264,15 +2719,22 @@ function tokenize(source, options = {}) {
2264
2719
  case TOKEN_TYPES.CloseSquareBracket: break;
2265
2720
  default: {
2266
2721
  ++cursorPosition;
2267
- const num = consumeWhile(isInteger);
2722
+ let num = consumeWhile(isInteger);
2723
+ if (num.length > 0 && src[cursorPosition] === "." && isInteger(src.charCodeAt(cursorPosition + 1))) {
2724
+ ++cursorPosition;
2725
+ const frac = consumeWhile(isInteger);
2726
+ num = `${num}.${frac}`;
2727
+ }
2268
2728
  tokens.push(new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator));
2269
2729
  continue;
2270
2730
  }
2271
2731
  }
2272
2732
  }
2273
- for (const [seq, type] of ORDERED_MAPPING_TABLE) {
2733
+ const code = src.charCodeAt(cursorPosition);
2734
+ const rules = RULES_BY_FIRST_CHAR_CODE[code];
2735
+ if (rules !== void 0) for (const [seq, type] of rules) {
2274
2736
  if (seq === "}}" && curlyBracketDepth > 0) continue;
2275
- if (src.slice(cursorPosition, cursorPosition + seq.length) === seq) {
2737
+ if (src.startsWith(seq, cursorPosition)) {
2276
2738
  tokens.push(new Token(seq, type));
2277
2739
  if (type === TOKEN_TYPES.OpenExpression) curlyBracketDepth = 0;
2278
2740
  else if (type === TOKEN_TYPES.OpenCurlyBracket) ++curlyBracketDepth;
@@ -2283,14 +2745,14 @@ function tokenize(source, options = {}) {
2283
2745
  }
2284
2746
  if (char === "'" || char === "\"") {
2285
2747
  ++cursorPosition;
2286
- const str = consumeWhile((c) => c !== char);
2748
+ const str = consumeString(char);
2287
2749
  tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));
2288
2750
  ++cursorPosition;
2289
2751
  continue;
2290
2752
  }
2291
- if (isInteger(char)) {
2753
+ if (isInteger(code)) {
2292
2754
  let num = consumeWhile(isInteger);
2293
- if (tokens.at(-1)?.type !== TOKEN_TYPES.Dot && src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) {
2755
+ if (lastTokenType !== TOKEN_TYPES.Dot && src[cursorPosition] === "." && isInteger(src.charCodeAt(cursorPosition + 1))) {
2294
2756
  ++cursorPosition;
2295
2757
  const frac = consumeWhile(isInteger);
2296
2758
  num = `${num}.${frac}`;
@@ -2298,8 +2760,11 @@ function tokenize(source, options = {}) {
2298
2760
  tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));
2299
2761
  continue;
2300
2762
  }
2301
- if (isWord(char)) {
2302
- const word = consumeWhile(isWord);
2763
+ if (isWord(code)) {
2764
+ let word = consumeWhile(isWord);
2765
+ const name = names.get(word);
2766
+ if (name === void 0) names.set(word, word);
2767
+ else word = name;
2303
2768
  tokens.push(new Token(word, TOKEN_TYPES.Identifier));
2304
2769
  continue;
2305
2770
  }
@@ -2496,6 +2961,13 @@ var SpreadExpression = class extends Expression {
2496
2961
  }
2497
2962
  type = "SpreadExpression";
2498
2963
  };
2964
+ var KeywordSpreadExpression = class extends Expression {
2965
+ constructor(argument) {
2966
+ super();
2967
+ this.argument = argument;
2968
+ }
2969
+ type = "KeywordSpreadExpression";
2970
+ };
2499
2971
  var CallStatement = class extends Statement {
2500
2972
  constructor(call, callerArgs, body) {
2501
2973
  super();
@@ -2581,10 +3053,10 @@ function parse(tokens) {
2581
3053
  case "call": {
2582
3054
  ++current;
2583
3055
  let callerArgs = null;
2584
- if (is(TOKEN_TYPES.OpenParen)) callerArgs = parseArgs();
3056
+ if (is(TOKEN_TYPES.OpenParen)) callerArgs = parseArgs("parameters");
2585
3057
  const callee = parsePrimaryExpression();
2586
3058
  if (callee.type !== "Identifier") throw new SyntaxError(`Expected identifier following call statement`);
2587
- const callArgs = parseArgs();
3059
+ const callArgs = parseArgs("call");
2588
3060
  expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
2589
3061
  const body = [];
2590
3062
  while (!isStatement("endcall")) body.push(parseAny());
@@ -2665,7 +3137,7 @@ function parse(tokens) {
2665
3137
  function parseMacroStatement() {
2666
3138
  const name = parsePrimaryExpression();
2667
3139
  if (name.type !== "Identifier") throw new SyntaxError(`Expected identifier following macro statement`);
2668
- const args = parseArgs();
3140
+ const args = parseArgs("parameters");
2669
3141
  expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
2670
3142
  const body = [];
2671
3143
  while (!isStatement("endmacro")) body.push(parseAny());
@@ -2775,32 +3247,56 @@ function parse(tokens) {
2775
3247
  return member;
2776
3248
  }
2777
3249
  function parseCallExpression(callee) {
2778
- let expression = new CallExpression(callee, parseArgs());
3250
+ let expression = new CallExpression(callee, parseArgs("call"));
2779
3251
  expression = parseMemberExpression(expression);
2780
3252
  if (is(TOKEN_TYPES.OpenParen)) expression = parseCallExpression(expression);
2781
3253
  return expression;
2782
3254
  }
2783
- function parseArgs() {
3255
+ function parseArgs(mode) {
2784
3256
  expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list");
2785
- const args = parseArgumentsList();
3257
+ const args = parseArgumentsList(mode);
2786
3258
  expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list");
2787
3259
  return args;
2788
3260
  }
2789
- function parseArgumentsList() {
3261
+ function parseArgumentsList(mode) {
2790
3262
  const args = [];
3263
+ const parameterNames = /* @__PURE__ */ new Set();
3264
+ let sawKeywordOrDefault = false;
3265
+ let sawSpreadArgument = false;
2791
3266
  while (!is(TOKEN_TYPES.CloseParen)) {
3267
+ const isKeywordSpread = is(TOKEN_TYPES.ExponentiationBinaryOperator);
3268
+ const isPositionalSpread = is(TOKEN_TYPES.MultiplicativeBinaryOperator) && tokens[current].value === "*";
3269
+ if (mode === "parameters" && (isKeywordSpread || isPositionalSpread)) throw new SyntaxError("Argument unpacking is not allowed in parameter declarations");
3270
+ if (isKeywordSpread) {
3271
+ ++current;
3272
+ args.push(new KeywordSpreadExpression(parseExpression()));
3273
+ if (is(TOKEN_TYPES.Comma)) ++current;
3274
+ if (!is(TOKEN_TYPES.CloseParen)) throw new SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");
3275
+ break;
3276
+ }
2792
3277
  let argument;
2793
- if (tokens[current].type === TOKEN_TYPES.MultiplicativeBinaryOperator && tokens[current].value === "*") {
3278
+ if (isPositionalSpread) {
3279
+ if (sawSpreadArgument) throw new SyntaxError("Only one `*` argument unpacking is allowed");
3280
+ sawSpreadArgument = true;
2794
3281
  ++current;
2795
3282
  argument = new SpreadExpression(parseExpression());
2796
3283
  } else {
2797
3284
  argument = parseExpression();
2798
3285
  if (is(TOKEN_TYPES.Equals)) {
2799
3286
  ++current;
2800
- if (!(argument instanceof Identifier)) throw new SyntaxError(`Expected identifier for keyword argument`);
3287
+ if (!(argument instanceof Identifier)) throw new SyntaxError(mode === "parameters" ? "Expected identifier for parameter declaration" : "Expected identifier for keyword argument");
2801
3288
  const value = parseExpression();
2802
3289
  argument = new KeywordArgumentExpression(argument, value);
2803
3290
  }
3291
+ if (mode === "parameters") {
3292
+ if (!(argument instanceof Identifier || argument instanceof KeywordArgumentExpression)) throw new SyntaxError("Expected identifier for parameter declaration");
3293
+ const parameterName = argument instanceof Identifier ? argument.value : argument.key.value;
3294
+ if (parameterNames.has(parameterName)) throw new SyntaxError(`Duplicate parameter name: ${parameterName}`);
3295
+ parameterNames.add(parameterName);
3296
+ }
3297
+ if (argument instanceof KeywordArgumentExpression) sawKeywordOrDefault = true;
3298
+ else if (sawKeywordOrDefault) throw new SyntaxError(mode === "call" ? "Positional arguments must come before keyword arguments" : "Non-default argument follows default argument");
3299
+ else if (sawSpreadArgument) throw new SyntaxError("Positional arguments must not follow `*` argument unpacking");
2804
3300
  }
2805
3301
  args.push(argument);
2806
3302
  if (is(TOKEN_TYPES.Comma)) ++current;
@@ -2846,8 +3342,17 @@ function parse(tokens) {
2846
3342
  return object;
2847
3343
  }
2848
3344
  function parseMultiplicativeExpression() {
2849
- let left = parseTestExpression();
3345
+ let left = parsePowerExpression();
2850
3346
  while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {
3347
+ const operator = tokens[current++];
3348
+ const right = parsePowerExpression();
3349
+ left = new BinaryExpression(operator, left, right);
3350
+ }
3351
+ return left;
3352
+ }
3353
+ function parsePowerExpression() {
3354
+ let left = parseTestExpression();
3355
+ while (is(TOKEN_TYPES.ExponentiationBinaryOperator)) {
2851
3356
  const operator = tokens[current++];
2852
3357
  const right = parseTestExpression();
2853
3358
  left = new BinaryExpression(operator, left, right);
@@ -2867,7 +3372,7 @@ function parse(tokens) {
2867
3372
  return operand;
2868
3373
  }
2869
3374
  function parseFilterExpression() {
2870
- let operand = parseCallMemberExpression();
3375
+ let operand = parseUnarySignExpression();
2871
3376
  while (is(TOKEN_TYPES.Pipe)) {
2872
3377
  ++current;
2873
3378
  let filter = parsePrimaryExpression();
@@ -2877,6 +3382,11 @@ function parse(tokens) {
2877
3382
  }
2878
3383
  return operand;
2879
3384
  }
3385
+ function parseUnarySignExpression() {
3386
+ const token = tokens[current];
3387
+ if (token && (token.type === TOKEN_TYPES.UnaryOperator || token.type === TOKEN_TYPES.AdditiveBinaryOperator) && (token.value === "-" || token.value === "+")) return new UnaryExpression(tokens[current++], parseUnarySignExpression());
3388
+ return parseCallMemberExpression();
3389
+ }
2880
3390
  function parsePrimaryExpression() {
2881
3391
  const token = tokens[current++];
2882
3392
  switch (token.type) {
@@ -2975,7 +3485,7 @@ function escapeRegExp(s) {
2975
3485
  }
2976
3486
  function replace(str, oldvalue, newvalue, count) {
2977
3487
  if (count === 0) return str;
2978
- let remaining = count == null || count < 0 ? Infinity : count;
3488
+ let remaining = count == null || count < 0 ? 1e400 : count;
2979
3489
  const pattern = oldvalue.length === 0 ? /* @__PURE__ */ new RegExp("(?=)", "gu") : new RegExp(escapeRegExp(oldvalue), "gu");
2980
3490
  return str.replaceAll(pattern, (match) => {
2981
3491
  if (remaining > 0) {
@@ -2989,8 +3499,6 @@ var BreakControl = class extends Error {};
2989
3499
  var ContinueControl = class extends Error {};
2990
3500
  var EMPTY_BUILTINS = /* @__PURE__ */ new Map();
2991
3501
  var RuntimeValue = class {
2992
- type = "RuntimeValue";
2993
- value;
2994
3502
  /**
2995
3503
  * A collection of built-in functions for this type.
2996
3504
  */
@@ -3001,6 +3509,7 @@ var RuntimeValue = class {
3001
3509
  * Creates a new RuntimeValue.
3002
3510
  */
3003
3511
  constructor(value = void 0) {
3512
+ this.type = "RuntimeValue";
3004
3513
  this.value = value;
3005
3514
  }
3006
3515
  /**
@@ -3016,17 +3525,27 @@ var RuntimeValue = class {
3016
3525
  }
3017
3526
  };
3018
3527
  var IntegerValue = class extends RuntimeValue {
3019
- type = "IntegerValue";
3528
+ constructor(value) {
3529
+ super(value);
3530
+ this.type = "IntegerValue";
3531
+ }
3020
3532
  };
3021
3533
  var FloatValue = class extends RuntimeValue {
3022
- type = "FloatValue";
3534
+ constructor(value) {
3535
+ super(value);
3536
+ this.type = "FloatValue";
3537
+ }
3023
3538
  toString() {
3539
+ if (Object.is(this.value, -0)) return "-0.0";
3024
3540
  return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString();
3025
3541
  }
3026
3542
  };
3027
3543
  var StringValue = class extends RuntimeValue {
3028
- type = "StringValue";
3029
3544
  _builtins;
3545
+ constructor(value) {
3546
+ super(value);
3547
+ this.type = "StringValue";
3548
+ }
3030
3549
  get builtins() {
3031
3550
  return this._builtins ??= /* @__PURE__ */ new Map([
3032
3551
  ["upper", new FunctionValue(() => {
@@ -3086,7 +3605,7 @@ var StringValue = class extends RuntimeValue {
3086
3605
  if (sep instanceof NullValue) {
3087
3606
  const text = this.value.trimStart();
3088
3607
  for (const { 0: match, index } of text.matchAll(/\S+/g)) {
3089
- if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) {
3608
+ if (maxsplit.value >= 0 && result.length >= maxsplit.value && index !== void 0) {
3090
3609
  result.push(match + text.slice(index + match.length));
3091
3610
  break;
3092
3611
  }
@@ -3095,7 +3614,7 @@ var StringValue = class extends RuntimeValue {
3095
3614
  } else {
3096
3615
  if (sep.value === "") throw new Error("empty separator");
3097
3616
  result = this.value.split(sep.value);
3098
- if (maxsplit.value !== -1 && result.length > maxsplit.value) result.push(result.splice(maxsplit.value).join(sep.value));
3617
+ if (maxsplit.value >= 0 && result.length > maxsplit.value) result.push(result.splice(maxsplit.value).join(sep.value));
3099
3618
  }
3100
3619
  return new ArrayValue(result.map((part) => new StringValue(part)));
3101
3620
  })],
@@ -3105,9 +3624,10 @@ var StringValue = class extends RuntimeValue {
3105
3624
  const newValue = args[1];
3106
3625
  if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) throw new Error("replace() arguments must be strings");
3107
3626
  let count;
3108
- if (args.length > 2) if (args[2].type === "KeywordArgumentsValue") count = args[2].value.get("count") ?? new NullValue();
3109
- else count = args[2];
3110
- else count = new NullValue();
3627
+ if (args.length > 2) {
3628
+ if (args[2].type === "KeywordArgumentsValue") count = args[2].value.get("count") ?? new NullValue();
3629
+ else count = args[2];
3630
+ } else count = new NullValue();
3111
3631
  if (!(count instanceof IntegerValue || count instanceof NullValue)) throw new Error("replace() count argument must be a number or null");
3112
3632
  return new StringValue(replace(this.value, oldValue.value, newValue.value, count.value));
3113
3633
  })]
@@ -3115,7 +3635,10 @@ var StringValue = class extends RuntimeValue {
3115
3635
  }
3116
3636
  };
3117
3637
  var BooleanValue = class extends RuntimeValue {
3118
- type = "BooleanValue";
3638
+ constructor(value) {
3639
+ super(value);
3640
+ this.type = "BooleanValue";
3641
+ }
3119
3642
  };
3120
3643
  var NON_ASCII_CHARS = /[\x7f-\uffff]/g;
3121
3644
  function makeAsciiSafe(str) {
@@ -3145,13 +3668,14 @@ function toJSON(input, options = {}, depth = 0, convertUndefinedToNull = true) {
3145
3668
  return result;
3146
3669
  }
3147
3670
  case "ArrayValue":
3671
+ case "NamespaceValue":
3148
3672
  case "ObjectValue": {
3149
3673
  const indentValue = indent ? " ".repeat(indent) : "";
3150
3674
  const basePadding = "\n" + indentValue.repeat(depth);
3151
3675
  const childrenPadding = basePadding + indentValue;
3152
3676
  if (input.type === "ArrayValue") {
3153
3677
  const core = input.value.map((x) => toJSON(x, options, depth + 1, convertUndefinedToNull));
3154
- return indent ? `[${childrenPadding}${core.join(`${itemSeparator}${childrenPadding}`)}${basePadding}]` : `[${core.join(itemSeparator)}]`;
3678
+ return indent && core.length > 0 ? `[${childrenPadding}${core.join(`${itemSeparator}${childrenPadding}`)}${basePadding}]` : `[${core.join(itemSeparator)}]`;
3155
3679
  } else {
3156
3680
  let entries = Array.from(input.value.entries());
3157
3681
  if (sortKeys) entries = entries.sort(([a], [b]) => a.localeCompare(b));
@@ -3161,15 +3685,18 @@ function toJSON(input, options = {}, depth = 0, convertUndefinedToNull = true) {
3161
3685
  const v = `${keyStr}${keySeparator}${toJSON(value, options, depth + 1, convertUndefinedToNull)}`;
3162
3686
  return indent ? `${childrenPadding}${v}` : v;
3163
3687
  });
3164
- return indent ? `{${core.join(itemSeparator)}${basePadding}}` : `{${core.join(itemSeparator)}}`;
3688
+ return indent && core.length > 0 ? `{${core.join(itemSeparator)}${basePadding}}` : `{${core.join(itemSeparator)}}`;
3165
3689
  }
3166
3690
  }
3167
3691
  default: throw new Error(`Cannot convert to JSON: ${input.type}`);
3168
3692
  }
3169
3693
  }
3170
3694
  var ObjectValue = class extends RuntimeValue {
3171
- type = "ObjectValue";
3172
3695
  _builtins;
3696
+ constructor(value) {
3697
+ super(value);
3698
+ this.type = "ObjectValue";
3699
+ }
3173
3700
  /**
3174
3701
  * NOTE: necessary to override since all JavaScript arrays are considered truthy,
3175
3702
  * while only non-empty Python arrays are consider truthy.
@@ -3208,9 +3735,7 @@ var ObjectValue = class extends RuntimeValue {
3208
3735
  if (!(reverse instanceof BooleanValue)) throw new Error("reverse must be a boolean");
3209
3736
  return new ArrayValue(Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])).sort((a, b) => {
3210
3737
  const index = by.value === "key" ? 0 : 1;
3211
- const aVal = a.value[index];
3212
- const bVal = b.value[index];
3213
- const result = compareRuntimeValues(aVal, bVal, caseSensitive.value);
3738
+ const result = compareRuntimeValues(a.value[index], b.value[index], caseSensitive.value);
3214
3739
  return reverse.value ? -result : result;
3215
3740
  }));
3216
3741
  })]
@@ -3229,12 +3754,60 @@ var ObjectValue = class extends RuntimeValue {
3229
3754
  return toJSON(this, {}, 0, false);
3230
3755
  }
3231
3756
  };
3757
+ var LoopValue = class extends ObjectValue {
3758
+ constructor(iteration, length, previtem, nextitem) {
3759
+ super();
3760
+ this.iteration = iteration;
3761
+ this.length = length;
3762
+ this.previtem = previtem;
3763
+ this.nextitem = nextitem;
3764
+ }
3765
+ createEntries() {
3766
+ const i = this.iteration;
3767
+ const length = this.length;
3768
+ return /* @__PURE__ */ new Map([
3769
+ ["index", new IntegerValue(i + 1)],
3770
+ ["index0", new IntegerValue(i)],
3771
+ ["revindex", new IntegerValue(length - i)],
3772
+ ["revindex0", new IntegerValue(length - i - 1)],
3773
+ ["first", new BooleanValue(i === 0)],
3774
+ ["last", new BooleanValue(i === length - 1)],
3775
+ ["length", new IntegerValue(length)],
3776
+ ["previtem", this.previtem ?? new UndefinedValue()],
3777
+ ["nextitem", this.nextitem ?? new UndefinedValue()]
3778
+ ]);
3779
+ }
3780
+ };
3781
+ Object.defineProperty(LoopValue.prototype, "value", {
3782
+ get() {
3783
+ return this.entries ??= this.createEntries();
3784
+ },
3785
+ set(entries) {
3786
+ this.entries = entries;
3787
+ },
3788
+ configurable: true
3789
+ });
3232
3790
  var KeywordArgumentsValue = class extends ObjectValue {
3233
- type = "KeywordArgumentsValue";
3791
+ constructor(value) {
3792
+ super(value);
3793
+ this.type = "KeywordArgumentsValue";
3794
+ }
3795
+ };
3796
+ var NamespaceValue = class extends RuntimeValue {
3797
+ constructor(value) {
3798
+ super(value);
3799
+ this.type = "NamespaceValue";
3800
+ }
3801
+ toString() {
3802
+ return toJSON(this, {}, 0, false);
3803
+ }
3234
3804
  };
3235
3805
  var ArrayValue = class extends RuntimeValue {
3236
- type = "ArrayValue";
3237
3806
  _builtins;
3807
+ constructor(value) {
3808
+ super(value);
3809
+ this.type = "ArrayValue";
3810
+ }
3238
3811
  get builtins() {
3239
3812
  return this._builtins ??= /* @__PURE__ */ new Map([["length", new IntegerValue(this.value.length)]]);
3240
3813
  }
@@ -3254,17 +3827,57 @@ var ArrayValue = class extends RuntimeValue {
3254
3827
  }
3255
3828
  };
3256
3829
  var TupleValue = class extends ArrayValue {
3257
- type = "TupleValue";
3830
+ constructor(value) {
3831
+ super(value);
3832
+ this.type = "TupleValue";
3833
+ }
3258
3834
  };
3259
3835
  var FunctionValue = class extends RuntimeValue {
3260
- type = "FunctionValue";
3836
+ constructor(value) {
3837
+ super(value);
3838
+ this.type = "FunctionValue";
3839
+ }
3261
3840
  };
3262
3841
  var NullValue = class extends RuntimeValue {
3263
- type = "NullValue";
3842
+ constructor(value) {
3843
+ super(value);
3844
+ this.type = "NullValue";
3845
+ }
3264
3846
  };
3265
3847
  var UndefinedValue = class extends RuntimeValue {
3266
- type = "UndefinedValue";
3848
+ constructor(value) {
3849
+ super(value);
3850
+ this.type = "UndefinedValue";
3851
+ }
3267
3852
  };
3853
+ function normalizeNamespaceEntry(pair) {
3854
+ let values;
3855
+ if (pair instanceof ArrayValue) values = pair.value;
3856
+ else if (pair instanceof StringValue) values = Array.from(pair.value, (char) => new StringValue(char));
3857
+ if (!values || values.length !== 2) throw new Error("namespace expected an object or an iterable of [key, value] pairs");
3858
+ const [key, value] = values;
3859
+ if (!(key instanceof StringValue)) throw new Error("namespace keys must be strings");
3860
+ return [key, value];
3861
+ }
3862
+ function namespaceBuiltin(args) {
3863
+ const positional = args.slice();
3864
+ let kwargs;
3865
+ if (positional.at(-1) instanceof KeywordArgumentsValue) kwargs = positional.pop();
3866
+ if (positional.length > 1) throw new Error(`namespace expected at most 1 argument, got ${positional.length}`);
3867
+ const entries = /* @__PURE__ */ new Map();
3868
+ if (positional.length === 1) {
3869
+ const source = positional[0];
3870
+ if (source instanceof ObjectValue) for (const [key, value] of source.value) entries.set(key, value);
3871
+ else if (source instanceof ArrayValue) for (const pair of source.value) {
3872
+ const [key, value] = normalizeNamespaceEntry(pair);
3873
+ entries.set(key.value, value);
3874
+ }
3875
+ else throw new Error(`'${source.type}' object is not iterable`);
3876
+ }
3877
+ if (kwargs) for (const [key, value] of kwargs.value) entries.set(key, value);
3878
+ return new NamespaceValue(entries);
3879
+ }
3880
+ var CALL_BLOCK_SCOPE = Symbol("callBlockScope");
3268
3881
  var _Environment = class {
3269
3882
  constructor(parent) {
3270
3883
  this.parent = parent;
@@ -3272,11 +3885,7 @@ var _Environment = class {
3272
3885
  /**
3273
3886
  * The variables declared in this environment.
3274
3887
  */
3275
- variables = /* @__PURE__ */ new Map([["namespace", new FunctionValue((args) => {
3276
- if (args.length === 0) return new ObjectValue(/* @__PURE__ */ new Map());
3277
- if (args.length !== 1 || !(args[0] instanceof ObjectValue)) throw new Error("`namespace` expects either zero arguments or a single object argument");
3278
- return args[0];
3279
- })]]);
3888
+ variables = (/* @__PURE__ */ new Map()).set("namespace", new FunctionValue(namespaceBuiltin));
3280
3889
  tests = _Environment.TESTS;
3281
3890
  /**
3282
3891
  * Set the value of a variable in the current environment.
@@ -3300,16 +3909,15 @@ var _Environment = class {
3300
3909
  /**
3301
3910
  * Resolve the environment in which the variable is declared.
3302
3911
  * @param {string} name The name of the variable.
3303
- * @returns {Environment} The environment in which the variable is declared.
3912
+ * @returns {Environment | undefined} The environment containing the variable, if declared.
3304
3913
  */
3305
3914
  resolve(name) {
3306
3915
  if (this.variables.has(name)) return this;
3307
3916
  if (this.parent) return this.parent.resolve(name);
3308
- throw new Error(`Unknown variable: ${name}`);
3309
3917
  }
3310
3918
  lookupVariable(name) {
3311
3919
  try {
3312
- return this.resolve(name).variables.get(name) ?? new UndefinedValue();
3920
+ return this.resolve(name)?.variables.get(name) ?? new UndefinedValue();
3313
3921
  } catch {
3314
3922
  return new UndefinedValue();
3315
3923
  }
@@ -3366,10 +3974,19 @@ function setupGlobals(env) {
3366
3974
  env.set("False", false);
3367
3975
  env.set("None", null);
3368
3976
  }
3977
+ function isAttributeContainer(value) {
3978
+ return value instanceof ObjectValue || value instanceof NamespaceValue;
3979
+ }
3980
+ function isNumericLikeValue(value) {
3981
+ return value instanceof IntegerValue || value instanceof FloatValue || value instanceof BooleanValue;
3982
+ }
3983
+ function getNumericValue(value) {
3984
+ return value instanceof BooleanValue ? Number(value.value) : value.value;
3985
+ }
3369
3986
  function getAttributeValue(item, attributePath) {
3370
3987
  const parts = attributePath.split(".");
3371
3988
  let value = item;
3372
- for (const part of parts) if (value instanceof ObjectValue) value = value.value.get(part) ?? new UndefinedValue();
3989
+ for (const part of parts) if (isAttributeContainer(value)) value = value.value.get(part) ?? new UndefinedValue();
3373
3990
  else if (value instanceof ArrayValue) {
3374
3991
  const index = parseInt(part, 10);
3375
3992
  if (!isNaN(index) && index >= 0 && index < value.value.length) value = value.value[index];
@@ -3382,12 +3999,7 @@ function compareRuntimeValues(a, b, caseSensitive = false) {
3382
3999
  if (a instanceof NullValue || b instanceof NullValue) throw new Error(`Cannot compare ${a.type} with ${b.type}`);
3383
4000
  if (a instanceof UndefinedValue && b instanceof UndefinedValue) return 0;
3384
4001
  if (a instanceof UndefinedValue || b instanceof UndefinedValue) throw new Error(`Cannot compare ${a.type} with ${b.type}`);
3385
- const isNumericLike = (v) => v instanceof IntegerValue || v instanceof FloatValue || v instanceof BooleanValue;
3386
- const getNumericValue = (v) => {
3387
- if (v instanceof BooleanValue) return v.value ? 1 : 0;
3388
- return v.value;
3389
- };
3390
- if (isNumericLike(a) && isNumericLike(b)) {
4002
+ if (isNumericLikeValue(a) && isNumericLikeValue(b)) {
3391
4003
  const aNum = getNumericValue(a);
3392
4004
  const bNum = getNumericValue(b);
3393
4005
  return aNum < bNum ? -1 : aNum > bNum ? 1 : 0;
@@ -3406,6 +4018,142 @@ function compareRuntimeValues(a, b, caseSensitive = false) {
3406
4018
  default: throw new Error(`Cannot compare type: ${a.type}`);
3407
4019
  }
3408
4020
  }
4021
+ function getParameterDescriptor(argument) {
4022
+ if (argument.type === "Identifier") return { name: argument.value };
4023
+ const keywordArgument = argument;
4024
+ return {
4025
+ name: keywordArgument.key.value,
4026
+ defaultValue: keywordArgument.value
4027
+ };
4028
+ }
4029
+ function isSpecialMacroArgument(name) {
4030
+ return name === "caller" || name === "kwargs" || name === "varargs";
4031
+ }
4032
+ function findAccessedSpecialMacroArguments(parameters, body) {
4033
+ const declared = /* @__PURE__ */ new Set();
4034
+ const accessed = /* @__PURE__ */ new Set();
4035
+ const declareName = (name) => {
4036
+ if (isSpecialMacroArgument(name)) declared.add(name);
4037
+ };
4038
+ const declareTarget = (target) => {
4039
+ if (target.type === "Identifier") declareName(target.value);
4040
+ else if (target.type === "TupleLiteral") for (const item of target.value) declareTarget(item);
4041
+ };
4042
+ const declareArgument = (argument) => {
4043
+ declareName(getParameterDescriptor(argument).name);
4044
+ };
4045
+ const visitArgumentDefaults = (args) => {
4046
+ for (const argument of args) {
4047
+ const parameter = getParameterDescriptor(argument);
4048
+ if (parameter.defaultValue) visit(parameter.defaultValue);
4049
+ }
4050
+ };
4051
+ const visitFilter = (filter) => {
4052
+ if (filter.type === "CallExpression") visit(filter.args);
4053
+ };
4054
+ const visit = (node) => {
4055
+ if (Array.isArray(node)) {
4056
+ for (const item of node) visit(item);
4057
+ return;
4058
+ }
4059
+ if (node instanceof Map) {
4060
+ for (const [key, value] of node) {
4061
+ visit(key);
4062
+ visit(value);
4063
+ }
4064
+ return;
4065
+ }
4066
+ if (!(node instanceof Statement)) return;
4067
+ switch (node.type) {
4068
+ case "For": {
4069
+ const statement = node;
4070
+ declareTarget(statement.loopvar);
4071
+ if (statement.iterable.type === "SelectExpression") {
4072
+ const iterable = statement.iterable;
4073
+ visit(iterable.lhs);
4074
+ visit(statement.body);
4075
+ visit(statement.defaultBlock);
4076
+ visit(iterable.test);
4077
+ return;
4078
+ }
4079
+ visit(statement.iterable);
4080
+ visit(statement.body);
4081
+ visit(statement.defaultBlock);
4082
+ return;
4083
+ }
4084
+ case "Set": {
4085
+ const statement = node;
4086
+ declareTarget(statement.assignee);
4087
+ visit(statement.value);
4088
+ visit(statement.body);
4089
+ return;
4090
+ }
4091
+ case "Macro": {
4092
+ const statement = node;
4093
+ for (const argument of statement.args) declareArgument(argument);
4094
+ visitArgumentDefaults(statement.args);
4095
+ visit(statement.body);
4096
+ return;
4097
+ }
4098
+ case "CallStatement": {
4099
+ const statement = node;
4100
+ visit(statement.call);
4101
+ for (const argument of statement.callerArgs ?? []) declareArgument(argument);
4102
+ visitArgumentDefaults(statement.callerArgs ?? []);
4103
+ visit(statement.body);
4104
+ return;
4105
+ }
4106
+ case "FilterStatement": {
4107
+ const statement = node;
4108
+ visit(statement.body);
4109
+ visitFilter(statement.filter);
4110
+ return;
4111
+ }
4112
+ case "Identifier": {
4113
+ const name = node.value;
4114
+ if (isSpecialMacroArgument(name) && !declared.has(name)) accessed.add(name);
4115
+ return;
4116
+ }
4117
+ case "MemberExpression": {
4118
+ const expression = node;
4119
+ visit(expression.object);
4120
+ if (expression.computed) visit(expression.property);
4121
+ return;
4122
+ }
4123
+ case "FilterExpression": {
4124
+ const expression = node;
4125
+ visit(expression.operand);
4126
+ visitFilter(expression.filter);
4127
+ return;
4128
+ }
4129
+ case "TestExpression":
4130
+ visit(node.operand);
4131
+ return;
4132
+ case "SelectExpression": {
4133
+ const expression = node;
4134
+ visit(expression.test);
4135
+ visit(expression.lhs);
4136
+ return;
4137
+ }
4138
+ case "KeywordArgumentExpression":
4139
+ visit(node.value);
4140
+ return;
4141
+ default: for (const child of Object.values(node)) visit(child);
4142
+ }
4143
+ };
4144
+ for (const parameter of parameters) declareArgument(parameter);
4145
+ visit(body);
4146
+ return accessed;
4147
+ }
4148
+ var ACCESSED_SPECIAL_ARGUMENTS = /* @__PURE__ */ new WeakMap();
4149
+ function getAccessedSpecialMacroArguments(node) {
4150
+ let accessed = ACCESSED_SPECIAL_ARGUMENTS.get(node);
4151
+ if (accessed === void 0) {
4152
+ accessed = findAccessedSpecialMacroArguments(node.type === "Macro" ? node.args : node.callerArgs ?? [], node.body);
4153
+ ACCESSED_SPECIAL_ARGUMENTS.set(node, accessed);
4154
+ }
4155
+ return accessed;
4156
+ }
3409
4157
  var Interpreter = class {
3410
4158
  global;
3411
4159
  constructor(env) {
@@ -3421,31 +4169,31 @@ var Interpreter = class {
3421
4169
  * Evaluates expressions following the binary operation type.
3422
4170
  */
3423
4171
  evaluateBinaryExpression(node, environment) {
4172
+ const operator = node.operator.value;
3424
4173
  const left = this.evaluate(node.left, environment);
3425
- switch (node.operator.value) {
4174
+ switch (operator) {
3426
4175
  case "and": return left.__bool__().value ? this.evaluate(node.right, environment) : left;
3427
4176
  case "or": return left.__bool__().value ? left : this.evaluate(node.right, environment);
3428
4177
  }
3429
4178
  const right = this.evaluate(node.right, environment);
3430
- switch (node.operator.value) {
4179
+ switch (operator) {
3431
4180
  case "==": return new BooleanValue(left.value == right.value);
3432
4181
  case "!=": return new BooleanValue(left.value != right.value);
3433
4182
  }
3434
- if (left instanceof UndefinedValue || right instanceof UndefinedValue) {
3435
- if (right instanceof UndefinedValue && ["in", "not in"].includes(node.operator.value)) return new BooleanValue(node.operator.value === "not in");
3436
- throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`);
3437
- } else if (left instanceof NullValue || right instanceof NullValue) throw new Error("Cannot perform operation on null values");
3438
- else if (node.operator.value === "~") return new StringValue(left.value.toString() + right.value.toString());
3439
- else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) {
4183
+ if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue) && operator !== "~" && operator !== "**") {
3440
4184
  const a = left.value, b = right.value;
3441
- switch (node.operator.value) {
4185
+ switch (operator) {
3442
4186
  case "+":
3443
4187
  case "-":
3444
4188
  case "*": {
3445
- const res = node.operator.value === "+" ? a + b : node.operator.value === "-" ? a - b : a * b;
4189
+ const res = operator === "+" ? a + b : operator === "-" ? a - b : a * b;
3446
4190
  return left instanceof FloatValue || right instanceof FloatValue ? new FloatValue(res) : new IntegerValue(res);
3447
4191
  }
3448
4192
  case "/": return new FloatValue(a / b);
4193
+ case "//": {
4194
+ const res = Math.floor(a / b);
4195
+ return left instanceof FloatValue || right instanceof FloatValue ? new FloatValue(res) : new IntegerValue(res);
4196
+ }
3449
4197
  case "%": {
3450
4198
  const rem = a % b;
3451
4199
  return left instanceof FloatValue || right instanceof FloatValue ? new FloatValue(rem) : new IntegerValue(rem);
@@ -3455,43 +4203,80 @@ var Interpreter = class {
3455
4203
  case ">=": return new BooleanValue(a >= b);
3456
4204
  case "<=": return new BooleanValue(a <= b);
3457
4205
  }
3458
- } else if (left instanceof ArrayValue && right instanceof ArrayValue) switch (node.operator.value) {
4206
+ } else if (left instanceof UndefinedValue || right instanceof UndefinedValue) {
4207
+ if (right instanceof UndefinedValue && ["in", "not in"].includes(operator)) return new BooleanValue(operator === "not in");
4208
+ if (operator === "~" && !(left instanceof NullValue || right instanceof NullValue)) return new StringValue((left instanceof UndefinedValue ? "" : left.value.toString()) + (right instanceof UndefinedValue ? "" : right.value.toString()));
4209
+ throw new Error(`Cannot perform operation ${operator} on undefined values`);
4210
+ } else if (left instanceof NullValue || right instanceof NullValue) throw new Error("Cannot perform operation on null values");
4211
+ else if (operator === "~") return new StringValue(left.value.toString() + right.value.toString());
4212
+ else if (operator === "**" && isNumericLikeValue(left) && isNumericLikeValue(right)) {
4213
+ const a = getNumericValue(left);
4214
+ const b = getNumericValue(right);
4215
+ if (a === 0 && b < 0) throw new Error("0.0 cannot be raised to a negative power");
4216
+ const result = a ** b;
4217
+ if (!Number.isFinite(result)) throw new Error("Exponentiation result is not a finite real number");
4218
+ return left instanceof FloatValue || right instanceof FloatValue || b < 0 ? new FloatValue(result) : new IntegerValue(result);
4219
+ } else if (left instanceof ArrayValue && right instanceof ArrayValue) switch (operator) {
3459
4220
  case "+": return new ArrayValue(left.value.concat(right.value));
3460
4221
  }
3461
4222
  else if (right instanceof ArrayValue) {
3462
4223
  const member = right.value.find((x) => x.value === left.value) !== void 0;
3463
- switch (node.operator.value) {
4224
+ switch (operator) {
3464
4225
  case "in": return new BooleanValue(member);
3465
4226
  case "not in": return new BooleanValue(!member);
3466
4227
  }
3467
4228
  }
3468
- if (left instanceof StringValue || right instanceof StringValue) switch (node.operator.value) {
4229
+ if (left instanceof StringValue || right instanceof StringValue) switch (operator) {
3469
4230
  case "+": return new StringValue(left.value.toString() + right.value.toString());
3470
4231
  }
3471
- if (left instanceof StringValue && right instanceof StringValue) switch (node.operator.value) {
4232
+ if (left instanceof StringValue && right instanceof StringValue) switch (operator) {
3472
4233
  case "in": return new BooleanValue(right.value.includes(left.value));
3473
4234
  case "not in": return new BooleanValue(!right.value.includes(left.value));
3474
4235
  }
3475
- if (left instanceof StringValue && right instanceof ObjectValue) switch (node.operator.value) {
4236
+ if (left instanceof StringValue && right instanceof ObjectValue) switch (operator) {
3476
4237
  case "in": return new BooleanValue(right.value.has(left.value));
3477
4238
  case "not in": return new BooleanValue(!right.value.has(left.value));
3478
4239
  }
3479
- throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`);
4240
+ throw new SyntaxError(`Unknown operator "${operator}" between ${left.type} and ${right.type}`);
4241
+ }
4242
+ /**
4243
+ * Evaluates the arguments of a call in the calling convention of FunctionValue: the positional arguments,
4244
+ * followed by a single KeywordArgumentsValue with all keyword arguments (if there are any).
4245
+ */
4246
+ evaluateCallArguments(args, environment) {
4247
+ for (const argument of args) {
4248
+ const type = argument.type;
4249
+ if (type === "KeywordArgumentExpression" || type === "SpreadExpression" || type === "KeywordSpreadExpression") {
4250
+ const [positionalArguments2, keywordArguments] = this.evaluateArguments(args, environment);
4251
+ if (keywordArguments.size > 0) positionalArguments2.push(new KeywordArgumentsValue(keywordArguments));
4252
+ return positionalArguments2;
4253
+ }
4254
+ }
4255
+ const positionalArguments = new Array(args.length);
4256
+ for (let i = 0; i < args.length; ++i) positionalArguments[i] = this.evaluate(args[i], environment);
4257
+ return positionalArguments;
3480
4258
  }
3481
4259
  evaluateArguments(args, environment) {
3482
4260
  const positionalArguments = [];
3483
4261
  const keywordArguments = /* @__PURE__ */ new Map();
4262
+ const addKeywordArgument = (key, value) => {
4263
+ if (keywordArguments.has(key)) throw new Error(`Got multiple values for keyword argument '${key}'`);
4264
+ keywordArguments.set(key, value);
4265
+ };
3484
4266
  for (const argument of args) if (argument.type === "SpreadExpression") {
3485
4267
  const spreadNode = argument;
3486
4268
  const val = this.evaluate(spreadNode.argument, environment);
3487
4269
  if (!(val instanceof ArrayValue)) throw new Error(`Cannot unpack non-iterable type: ${val.type}`);
3488
4270
  for (const item of val.value) positionalArguments.push(item);
3489
- } else if (argument.type === "KeywordArgumentExpression") {
4271
+ } else if (argument.type !== "KeywordArgumentExpression" && argument.type !== "KeywordSpreadExpression") positionalArguments.push(this.evaluate(argument, environment));
4272
+ for (const argument of args) if (argument.type === "KeywordArgumentExpression") {
3490
4273
  const kwarg = argument;
3491
- keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));
3492
- } else {
3493
- if (keywordArguments.size > 0) throw new Error("Positional arguments must come before keyword arguments");
3494
- positionalArguments.push(this.evaluate(argument, environment));
4274
+ addKeywordArgument(kwarg.key.value, this.evaluate(kwarg.value, environment));
4275
+ } else if (argument.type === "KeywordSpreadExpression") {
4276
+ const spreadNode = argument;
4277
+ const val = this.evaluate(spreadNode.argument, environment);
4278
+ if (!(val instanceof ObjectValue)) throw new Error(`Argument after ** must be a mapping, not ${val.type}`);
4279
+ for (const [key, value] of val.value) addKeywordArgument(key, value);
3495
4280
  }
3496
4281
  return [positionalArguments, keywordArguments];
3497
4282
  }
@@ -3547,7 +4332,7 @@ var Interpreter = class {
3547
4332
  }
3548
4333
  else if (operand instanceof IntegerValue || operand instanceof FloatValue) switch (filter.value) {
3549
4334
  case "abs": return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value));
3550
- case "int": return new IntegerValue(Math.floor(operand.value));
4335
+ case "int": return new IntegerValue(Math.trunc(operand.value) + 0);
3551
4336
  case "float": return new FloatValue(operand.value);
3552
4337
  case "string": return new StringValue(operand.toString());
3553
4338
  default: throw new Error(`Unknown NumericValue filter: ${filter.value}`);
@@ -3613,7 +4398,7 @@ var Interpreter = class {
3613
4398
  if (operand instanceof StringValue) {
3614
4399
  const val = filterName === "int" ? parseInt(operand.value, 10) : parseFloat(operand.value);
3615
4400
  return isNaN(val) ? defaultValue : filterName === "int" ? new IntegerValue(val) : new FloatValue(val);
3616
- } else if (operand instanceof IntegerValue || operand instanceof FloatValue) return operand;
4401
+ } else if (operand instanceof IntegerValue || operand instanceof FloatValue) return filterName === "int" ? new IntegerValue(Math.trunc(operand.value) + 0) : new FloatValue(operand.value);
3617
4402
  else if (operand instanceof BooleanValue) return filterName === "int" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0);
3618
4403
  else throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
3619
4404
  } else if (filterName === "default") {
@@ -3646,7 +4431,7 @@ var Interpreter = class {
3646
4431
  case "selectattr":
3647
4432
  case "rejectattr": {
3648
4433
  const select = filterName === "selectattr";
3649
- if (operand.value.some((x) => !(x instanceof ObjectValue))) throw new Error(`\`${filterName}\` can only be applied to array of objects`);
4434
+ if (operand.value.some((item) => !isAttributeContainer(item))) throw new Error(`\`${filterName}\` can only be applied to array of objects`);
3650
4435
  if (filter.args.some((x) => x.type !== "StringLiteral")) throw new Error(`arguments of \`${filterName}\` must be strings`);
3651
4436
  const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));
3652
4437
  let testFunction;
@@ -3668,7 +4453,7 @@ var Interpreter = class {
3668
4453
  if (!(attr instanceof StringValue)) throw new Error("attribute must be a string");
3669
4454
  const defaultValue = kwargs.get("default");
3670
4455
  return new ArrayValue(operand.value.map((item) => {
3671
- if (!(item instanceof ObjectValue)) throw new Error("items in map must be an object");
4456
+ if (!isAttributeContainer(item)) throw new Error("items in map must be an object");
3672
4457
  const value = getAttributeValue(item, attr.value);
3673
4458
  return value instanceof UndefinedValue ? defaultValue ?? new UndefinedValue() : value;
3674
4459
  }));
@@ -3681,11 +4466,11 @@ var Interpreter = class {
3681
4466
  case "indent": {
3682
4467
  const [args, kwargs] = this.evaluateArguments(filter.args, environment);
3683
4468
  const width = args.at(0) ?? kwargs.get("width") ?? new IntegerValue(4);
3684
- if (!(width instanceof IntegerValue)) throw new Error("width must be a number");
4469
+ if (!(width instanceof IntegerValue || width instanceof StringValue)) throw new Error("width must be an integer or a string");
3685
4470
  const first = args.at(1) ?? kwargs.get("first") ?? new BooleanValue(false);
3686
4471
  const blank = args.at(2) ?? kwargs.get("blank") ?? new BooleanValue(false);
3687
4472
  const lines = operand.value.split("\n");
3688
- const indent = " ".repeat(width.value);
4473
+ const indent = width instanceof StringValue ? width.value : " ".repeat(Math.max(0, width.value));
3689
4474
  return new StringValue(lines.map((x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x).join("\n"));
3690
4475
  }
3691
4476
  case "replace": {
@@ -3698,11 +4483,7 @@ var Interpreter = class {
3698
4483
  throw new Error(`Unknown StringValue filter: ${filterName}`);
3699
4484
  } else if (operand instanceof ObjectValue) {
3700
4485
  const builtin = operand.builtins.get(filterName);
3701
- if (builtin && builtin instanceof FunctionValue) {
3702
- const [args, kwargs] = this.evaluateArguments(filter.args, environment);
3703
- if (kwargs.size > 0) args.push(new KeywordArgumentsValue(kwargs));
3704
- return builtin.value(args, environment);
3705
- }
4486
+ if (builtin && builtin instanceof FunctionValue) return builtin.value(this.evaluateCallArguments(filter.args, environment), environment);
3706
4487
  throw new Error(`Unknown ObjectValue filter: ${filterName}`);
3707
4488
  } else throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
3708
4489
  }
@@ -3738,7 +4519,16 @@ var Interpreter = class {
3738
4519
  evaluateUnaryExpression(node, environment) {
3739
4520
  const argument = this.evaluate(node.argument, environment);
3740
4521
  switch (node.operator.value) {
3741
- case "not": return new BooleanValue(!argument.value);
4522
+ case "not": return new BooleanValue(!argument.__bool__().value);
4523
+ case "+":
4524
+ case "-": {
4525
+ const sign = node.operator.value === "-" ? -1 : 1;
4526
+ if (argument instanceof IntegerValue || argument instanceof FloatValue || argument instanceof BooleanValue) {
4527
+ const result = sign * (argument instanceof BooleanValue ? argument.value ? 1 : 0 : argument.value);
4528
+ return argument instanceof FloatValue ? new FloatValue(result) : new IntegerValue(result);
4529
+ }
4530
+ throw new SyntaxError(`Unknown operator "${node.operator.value}" for ${argument.type}`);
4531
+ }
3742
4532
  default: throw new SyntaxError(`Unknown operator: ${node.operator.value}`);
3743
4533
  }
3744
4534
  }
@@ -3749,19 +4539,42 @@ var Interpreter = class {
3749
4539
  return this.evaluateBlock(program.body, environment);
3750
4540
  }
3751
4541
  evaluateBlock(statements, environment) {
4542
+ return new StringValue(this.renderBlock(statements, environment));
4543
+ }
4544
+ /**
4545
+ * Jinja templates always evaluate to a String, so we accumulate the result of each statement into a final string.
4546
+ */
4547
+ renderBlock(statements, environment) {
3752
4548
  let result = "";
3753
- for (const statement of statements) {
3754
- const lastEvaluated = this.evaluate(statement, environment);
3755
- if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") result += lastEvaluated.toString();
4549
+ for (let i = 0; i < statements.length; ++i) {
4550
+ const statement = statements[i];
4551
+ switch (statement.type) {
4552
+ case "StringLiteral":
4553
+ result += statement.value;
4554
+ break;
4555
+ case "If":
4556
+ result += this.renderIf(statement, environment);
4557
+ break;
4558
+ case "For":
4559
+ result += this.renderFor(statement, environment);
4560
+ break;
4561
+ case "Set":
4562
+ this.executeSet(statement, environment);
4563
+ break;
4564
+ case "Comment": break;
4565
+ default: {
4566
+ const evaluated = this.evaluate(statement, environment);
4567
+ if (evaluated.type !== "NullValue" && evaluated.type !== "UndefinedValue") result += evaluated.toString();
4568
+ }
4569
+ }
3756
4570
  }
3757
- return new StringValue(result);
4571
+ return result;
3758
4572
  }
3759
4573
  evaluateIdentifier(node, environment) {
3760
4574
  return environment.lookupVariable(node.value);
3761
4575
  }
3762
4576
  evaluateCallExpression(expr, environment) {
3763
- const [args, kwargs] = this.evaluateArguments(expr.args, environment);
3764
- if (kwargs.size > 0) args.push(new KeywordArgumentsValue(kwargs));
4577
+ const args = this.evaluateCallArguments(expr.args, environment);
3765
4578
  const fn = this.evaluate(expr.callee, environment);
3766
4579
  if (fn.type !== "FunctionValue") throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
3767
4580
  return fn.value(args, environment);
@@ -3780,26 +4593,30 @@ var Interpreter = class {
3780
4593
  evaluateMemberExpression(expr, environment) {
3781
4594
  const object = this.evaluate(expr.object, environment);
3782
4595
  let property;
3783
- if (expr.computed) if (expr.property.type === "SliceExpression") return this.evaluateSliceExpression(object, expr.property, environment);
3784
- else property = this.evaluate(expr.property, environment);
3785
- else if (expr.property.type === "IntegerLiteral") property = new IntegerValue(expr.property.value);
4596
+ if (expr.computed) {
4597
+ if (expr.property.type === "SliceExpression") return this.evaluateSliceExpression(object, expr.property, environment);
4598
+ else property = this.evaluate(expr.property, environment);
4599
+ } else if (expr.property.type === "IntegerLiteral") property = new IntegerValue(expr.property.value);
3786
4600
  else property = new StringValue(expr.property.value);
3787
4601
  let value;
3788
- if (object instanceof ObjectValue) {
4602
+ if (isAttributeContainer(object)) {
3789
4603
  if (!(property instanceof StringValue)) throw new Error(`Cannot access property with non-string: got ${property.type}`);
3790
- value = object.value.get(property.value) ?? object.builtins.get(property.value);
3791
- } else if (object instanceof ArrayValue || object instanceof StringValue) if (property instanceof IntegerValue) {
3792
- value = object.value.at(property.value);
3793
- if (object instanceof StringValue) value = new StringValue(object.value.at(property.value));
3794
- } else if (property instanceof StringValue) value = object.builtins.get(property.value);
3795
- else throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);
3796
- else {
4604
+ value = object.value.get(property.value) ?? (object instanceof ObjectValue ? object.builtins.get(property.value) : void 0);
4605
+ } else if (object instanceof ArrayValue || object instanceof StringValue) {
4606
+ if (property instanceof IntegerValue) {
4607
+ if (object instanceof StringValue) {
4608
+ const character = object.value.at(property.value);
4609
+ value = character === void 0 ? void 0 : new StringValue(character);
4610
+ } else value = object.value.at(property.value);
4611
+ } else if (property instanceof StringValue) value = object.builtins.get(property.value);
4612
+ else throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);
4613
+ } else {
3797
4614
  if (!(property instanceof StringValue)) throw new Error(`Cannot access property with non-string: got ${property.type}`);
3798
4615
  value = object.builtins.get(property.value);
3799
4616
  }
3800
4617
  return value instanceof RuntimeValue ? value : new UndefinedValue();
3801
4618
  }
3802
- evaluateSet(node, environment) {
4619
+ executeSet(node, environment) {
3803
4620
  const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment);
3804
4621
  if (node.assignee.type === "Identifier") {
3805
4622
  const variableName = node.assignee.value;
@@ -3817,17 +4634,30 @@ var Interpreter = class {
3817
4634
  } else if (node.assignee.type === "MemberExpression") {
3818
4635
  const member = node.assignee;
3819
4636
  const object = this.evaluate(member.object, environment);
3820
- if (!(object instanceof ObjectValue)) throw new Error("Cannot assign to member of non-object");
4637
+ if (!(object instanceof NamespaceValue)) throw new Error("cannot assign attribute on non-namespace object");
3821
4638
  if (member.property.type !== "Identifier") throw new Error("Cannot assign to member with non-identifier property");
3822
4639
  object.value.set(member.property.value, rhs);
3823
4640
  } else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);
3824
- return new NullValue();
3825
4641
  }
3826
- evaluateIf(node, environment) {
4642
+ renderIf(node, environment) {
3827
4643
  const test = this.evaluate(node.test, environment);
3828
- return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);
4644
+ return this.renderBlock(test.__bool__().value ? node.body : node.alternate, environment);
4645
+ }
4646
+ /**
4647
+ * Assign the current item of a for loop to its loop variable(s).
4648
+ */
4649
+ bindLoopVariable(loopvar, current, scope) {
4650
+ if (loopvar.type === "Identifier") scope.setVariable(loopvar.value, current);
4651
+ else {
4652
+ const targets = loopvar.value;
4653
+ const values = current.value;
4654
+ for (let j = 0; j < targets.length; ++j) {
4655
+ if (targets[j].type !== "Identifier") throw new Error(`Cannot unpack non-identifier type: ${targets[j].type}`);
4656
+ scope.setVariable(targets[j].value, values[j]);
4657
+ }
4658
+ }
3829
4659
  }
3830
- evaluateFor(node, environment) {
4660
+ renderFor(node, environment) {
3831
4661
  const scope = new Environment(environment);
3832
4662
  let test, iterable;
3833
4663
  if (node.iterable.type === "SelectExpression") {
@@ -3837,51 +4667,35 @@ var Interpreter = class {
3837
4667
  } else iterable = this.evaluate(node.iterable, scope);
3838
4668
  if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`);
3839
4669
  if (iterable instanceof ObjectValue) iterable = iterable.keys();
3840
- const items = [];
3841
- const scopeUpdateFunctions = [];
3842
- for (let i = 0; i < iterable.value.length; ++i) {
3843
- const loopScope = new Environment(scope);
3844
- const current = iterable.value[i];
3845
- let scopeUpdateFunction;
3846
- if (node.loopvar.type === "Identifier") scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);
3847
- else if (node.loopvar.type === "TupleLiteral") {
3848
- const loopvar = node.loopvar;
3849
- if (current.type !== "ArrayValue") throw new Error(`Cannot unpack non-iterable type: ${current.type}`);
3850
- const c = current;
3851
- if (loopvar.value.length !== c.value.length) throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`);
3852
- scopeUpdateFunction = (scope2) => {
3853
- for (let j = 0; j < loopvar.value.length; ++j) {
3854
- if (loopvar.value[j].type !== "Identifier") throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);
3855
- scope2.setVariable(loopvar.value[j].value, c.value[j]);
3856
- }
3857
- };
3858
- } else throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);
3859
- if (test) {
3860
- scopeUpdateFunction(loopScope);
3861
- if (!this.evaluate(test, loopScope).__bool__().value) continue;
4670
+ const loopvar = node.loopvar;
4671
+ const candidates = iterable.value;
4672
+ let items;
4673
+ if (loopvar.type === "Identifier" && !test) items = candidates.slice();
4674
+ else {
4675
+ items = [];
4676
+ for (let i = 0; i < candidates.length; ++i) {
4677
+ const current = candidates[i];
4678
+ if (loopvar.type === "TupleLiteral") {
4679
+ if (current.type !== "ArrayValue") throw new Error(`Cannot unpack non-iterable type: ${current.type}`);
4680
+ const expected = loopvar.value.length;
4681
+ const actual = current.value.length;
4682
+ if (expected !== actual) throw new Error(`Too ${expected > actual ? "few" : "many"} items to unpack`);
4683
+ } else if (loopvar.type !== "Identifier") throw new Error(`Invalid loop variable(s): ${loopvar.type}`);
4684
+ if (test) {
4685
+ const loopScope = new Environment(scope);
4686
+ this.bindLoopVariable(loopvar, current, loopScope);
4687
+ if (!this.evaluate(test, loopScope).__bool__().value) continue;
4688
+ }
4689
+ items.push(current);
3862
4690
  }
3863
- items.push(current);
3864
- scopeUpdateFunctions.push(scopeUpdateFunction);
3865
4691
  }
3866
4692
  let result = "";
3867
4693
  let noIteration = true;
3868
4694
  for (let i = 0; i < items.length; ++i) {
3869
- const loop = /* @__PURE__ */ new Map([
3870
- ["index", new IntegerValue(i + 1)],
3871
- ["index0", new IntegerValue(i)],
3872
- ["revindex", new IntegerValue(items.length - i)],
3873
- ["revindex0", new IntegerValue(items.length - i - 1)],
3874
- ["first", new BooleanValue(i === 0)],
3875
- ["last", new BooleanValue(i === items.length - 1)],
3876
- ["length", new IntegerValue(items.length)],
3877
- ["previtem", i > 0 ? items[i - 1] : new UndefinedValue()],
3878
- ["nextitem", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]
3879
- ]);
3880
- scope.setVariable("loop", new ObjectValue(loop));
3881
- scopeUpdateFunctions[i](scope);
4695
+ scope.setVariable("loop", new LoopValue(i, items.length, i > 0 ? items[i - 1] : void 0, i < items.length - 1 ? items[i + 1] : void 0));
4696
+ this.bindLoopVariable(loopvar, items[i], scope);
3882
4697
  try {
3883
- const evaluated = this.evaluateBlock(node.body, scope);
3884
- result += evaluated.value;
4698
+ result += this.renderBlock(node.body, scope);
3885
4699
  } catch (err) {
3886
4700
  if (err instanceof ContinueControl) continue;
3887
4701
  if (err instanceof BreakControl) break;
@@ -3889,46 +4703,58 @@ var Interpreter = class {
3889
4703
  }
3890
4704
  noIteration = false;
3891
4705
  }
3892
- if (noIteration) {
3893
- const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);
3894
- result += defaultEvaluated.value;
4706
+ if (noIteration) result += this.renderBlock(node.defaultBlock, scope);
4707
+ return result;
4708
+ }
4709
+ /**
4710
+ * Bind every parameter name and special argument before evaluating defaults,
4711
+ * preventing unbound parameters from resolving in an outer scope.
4712
+ */
4713
+ bindMacroArguments(displayName, parameters, specialArguments, args, scope) {
4714
+ const positionalArguments = args.slice();
4715
+ let keywordArguments = /* @__PURE__ */ new Map();
4716
+ if (positionalArguments.at(-1) instanceof KeywordArgumentsValue) keywordArguments = new Map(positionalArguments.pop().value);
4717
+ const pendingDefaults = [];
4718
+ for (let i = 0; i < parameters.length; ++i) {
4719
+ const { name, defaultValue } = getParameterDescriptor(parameters[i]);
4720
+ let value = positionalArguments[i];
4721
+ if (value === void 0 && keywordArguments.has(name)) {
4722
+ value = keywordArguments.get(name);
4723
+ keywordArguments.delete(name);
4724
+ }
4725
+ if (value === void 0 && defaultValue !== void 0) pendingDefaults.push([name, defaultValue]);
4726
+ scope.setVariable(name, value ?? new UndefinedValue());
3895
4727
  }
3896
- return new StringValue(result);
4728
+ if (specialArguments.has("kwargs")) scope.setVariable("kwargs", new ObjectValue(keywordArguments));
4729
+ else if (keywordArguments.size > 0) throw new Error(`macro ${displayName} takes no keyword argument '${keywordArguments.keys().next().value}'`);
4730
+ if (specialArguments.has("varargs")) scope.setVariable("varargs", new ArrayValue(positionalArguments.slice(parameters.length)));
4731
+ else if (positionalArguments.length > parameters.length) throw new Error(`macro ${displayName} takes not more than ${parameters.length} argument(s)`);
4732
+ for (const [name, defaultValue] of pendingDefaults) scope.setVariable(name, this.evaluate(defaultValue, scope));
3897
4733
  }
3898
4734
  /**
3899
4735
  * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.
3900
4736
  */
3901
4737
  evaluateMacro(node, environment) {
3902
- environment.setVariable(node.name.value, new FunctionValue((args, scope) => {
3903
- const macroScope = new Environment(scope);
3904
- args = args.slice();
3905
- let kwargs;
3906
- if (args.at(-1)?.type === "KeywordArgumentsValue") kwargs = args.pop();
3907
- for (let i = 0; i < node.args.length; ++i) {
3908
- const nodeArg = node.args[i];
3909
- const passedArg = args[i];
3910
- if (nodeArg.type === "Identifier") {
3911
- const identifier = nodeArg;
3912
- if (!passedArg) throw new Error(`Missing positional argument: ${identifier.value}`);
3913
- macroScope.setVariable(identifier.value, passedArg);
3914
- } else if (nodeArg.type === "KeywordArgumentExpression") {
3915
- const kwarg = nodeArg;
3916
- const value = passedArg ?? kwargs?.value.get(kwarg.key.value) ?? this.evaluate(kwarg.value, macroScope);
3917
- macroScope.setVariable(kwarg.key.value, value);
3918
- } else throw new Error(`Unknown argument type: ${nodeArg.type}`);
4738
+ const specialArguments = getAccessedSpecialMacroArguments(node);
4739
+ environment.setVariable(node.name.value, new FunctionValue((args, callSite) => {
4740
+ let parent = environment;
4741
+ if (specialArguments.has("caller")) {
4742
+ const caller = callSite[CALL_BLOCK_SCOPE] ? callSite.variables.get("caller") : void 0;
4743
+ parent = new Environment(environment);
4744
+ parent.setVariable("caller", caller ?? new UndefinedValue());
3919
4745
  }
4746
+ const macroScope = new Environment(parent);
4747
+ this.bindMacroArguments(`'${node.name.value}'`, node.args, specialArguments, args, macroScope);
3920
4748
  return this.evaluateBlock(node.body, macroScope);
3921
4749
  }));
3922
4750
  return new NullValue();
3923
4751
  }
3924
4752
  evaluateCallStatement(node, environment) {
3925
- const callerFn = new FunctionValue((callerArgs, callerEnv) => {
3926
- const callBlockEnv = new Environment(callerEnv);
3927
- if (node.callerArgs) for (let i = 0; i < node.callerArgs.length; ++i) {
3928
- const param = node.callerArgs[i];
3929
- if (param.type !== "Identifier") throw new Error(`Caller parameter must be an identifier, got ${param.type}`);
3930
- callBlockEnv.setVariable(param.value, callerArgs[i] ?? new UndefinedValue());
3931
- }
4753
+ const parameters = node.callerArgs ?? [];
4754
+ const specialArguments = getAccessedSpecialMacroArguments(node);
4755
+ const callerFn = new FunctionValue((callerArguments) => {
4756
+ const callBlockEnv = new Environment(environment);
4757
+ this.bindMacroArguments("None", parameters, specialArguments, callerArguments, callBlockEnv);
3932
4758
  return this.evaluateBlock(node.body, callBlockEnv);
3933
4759
  });
3934
4760
  const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment);
@@ -3936,6 +4762,7 @@ var Interpreter = class {
3936
4762
  const fn = this.evaluate(node.call.callee, environment);
3937
4763
  if (fn.type !== "FunctionValue") throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
3938
4764
  const newEnv = new Environment(environment);
4765
+ newEnv[CALL_BLOCK_SCOPE] = true;
3939
4766
  newEnv.setVariable("caller", callerFn);
3940
4767
  return fn.value(macroArgs, newEnv);
3941
4768
  }
@@ -3946,17 +4773,17 @@ var Interpreter = class {
3946
4773
  evaluate(statement, environment) {
3947
4774
  if (!statement) return new UndefinedValue();
3948
4775
  switch (statement.type) {
3949
- case "Program": return this.evalProgram(statement, environment);
3950
- case "Set": return this.evaluateSet(statement, environment);
3951
- case "If": return this.evaluateIf(statement, environment);
3952
- case "For": return this.evaluateFor(statement, environment);
3953
- case "Macro": return this.evaluateMacro(statement, environment);
3954
- case "CallStatement": return this.evaluateCallStatement(statement, environment);
3955
- case "Break": throw new BreakControl();
3956
- case "Continue": throw new ContinueControl();
4776
+ case "Identifier": return this.evaluateIdentifier(statement, environment);
3957
4777
  case "IntegerLiteral": return new IntegerValue(statement.value);
3958
- case "FloatLiteral": return new FloatValue(statement.value);
4778
+ case "BinaryExpression": return this.evaluateBinaryExpression(statement, environment);
3959
4779
  case "StringLiteral": return new StringValue(statement.value);
4780
+ case "MemberExpression": return this.evaluateMemberExpression(statement, environment);
4781
+ case "CallExpression": return this.evaluateCallExpression(statement, environment);
4782
+ case "FilterExpression": return this.evaluateFilterExpression(statement, environment);
4783
+ case "TestExpression": return this.evaluateTestExpression(statement, environment);
4784
+ case "Ternary": return this.evaluateTernaryExpression(statement, environment);
4785
+ case "UnaryExpression": return this.evaluateUnaryExpression(statement, environment);
4786
+ case "FloatLiteral": return new FloatValue(statement.value);
3960
4787
  case "ArrayLiteral": return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));
3961
4788
  case "TupleLiteral": return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));
3962
4789
  case "ObjectLiteral": {
@@ -3968,17 +4795,19 @@ var Interpreter = class {
3968
4795
  }
3969
4796
  return new ObjectValue(mapping);
3970
4797
  }
3971
- case "Identifier": return this.evaluateIdentifier(statement, environment);
3972
- case "CallExpression": return this.evaluateCallExpression(statement, environment);
3973
- case "MemberExpression": return this.evaluateMemberExpression(statement, environment);
3974
- case "UnaryExpression": return this.evaluateUnaryExpression(statement, environment);
3975
- case "BinaryExpression": return this.evaluateBinaryExpression(statement, environment);
3976
- case "FilterExpression": return this.evaluateFilterExpression(statement, environment);
3977
- case "FilterStatement": return this.evaluateFilterStatement(statement, environment);
3978
- case "TestExpression": return this.evaluateTestExpression(statement, environment);
3979
4798
  case "SelectExpression": return this.evaluateSelectExpression(statement, environment);
3980
- case "Ternary": return this.evaluateTernaryExpression(statement, environment);
4799
+ case "If": return new StringValue(this.renderIf(statement, environment));
4800
+ case "Set":
4801
+ this.executeSet(statement, environment);
4802
+ return new NullValue();
4803
+ case "For": return new StringValue(this.renderFor(statement, environment));
4804
+ case "Macro": return this.evaluateMacro(statement, environment);
4805
+ case "CallStatement": return this.evaluateCallStatement(statement, environment);
4806
+ case "FilterStatement": return this.evaluateFilterStatement(statement, environment);
3981
4807
  case "Comment": return new NullValue();
4808
+ case "Break": throw new BreakControl();
4809
+ case "Continue": throw new ContinueControl();
4810
+ case "Program": return this.evalProgram(statement, environment);
3982
4811
  default: throw new SyntaxError(`Unknown node type: ${statement.type}`);
3983
4812
  }
3984
4813
  }
@@ -4001,17 +4830,47 @@ function convertToRuntimeValues(input) {
4001
4830
  var NEWLINE = "\n";
4002
4831
  var OPEN_STATEMENT = "{%- ";
4003
4832
  var CLOSE_STATEMENT = " -%}";
4833
+ var PRECEDENCE = Object.freeze({
4834
+ CONDITIONAL: 0,
4835
+ LOGICAL_OR: 1,
4836
+ LOGICAL_AND: 2,
4837
+ LOGICAL_NOT: 3,
4838
+ COMPARISON: 4,
4839
+ ADDITIVE: 5,
4840
+ MULTIPLICATIVE: 6,
4841
+ EXPONENTIATION: 7,
4842
+ TEST: 8,
4843
+ FILTER: 9,
4844
+ UNARY_SIGN: 10,
4845
+ ATOM: 11
4846
+ });
4004
4847
  function getBinaryOperatorPrecedence(expr) {
4005
4848
  switch (expr.operator.type) {
4006
- case "MultiplicativeBinaryOperator": return 4;
4007
- case "AdditiveBinaryOperator": return 3;
4008
- case "ComparisonBinaryOperator": return 2;
4849
+ case "ExponentiationBinaryOperator": return PRECEDENCE.EXPONENTIATION;
4850
+ case "MultiplicativeBinaryOperator": return PRECEDENCE.MULTIPLICATIVE;
4851
+ case "AdditiveBinaryOperator": return PRECEDENCE.ADDITIVE;
4852
+ case "ComparisonBinaryOperator": return PRECEDENCE.COMPARISON;
4009
4853
  case "Identifier":
4010
- if (expr.operator.value === "and") return 1;
4011
- if (expr.operator.value === "in" || expr.operator.value === "not in") return 2;
4012
- return 0;
4854
+ if (expr.operator.value === "and") return PRECEDENCE.LOGICAL_AND;
4855
+ if (expr.operator.value === "in" || expr.operator.value === "not in") return PRECEDENCE.COMPARISON;
4856
+ return PRECEDENCE.LOGICAL_OR;
4857
+ }
4858
+ return PRECEDENCE.LOGICAL_OR;
4859
+ }
4860
+ function getPrecedence(node) {
4861
+ switch (node.type) {
4862
+ case "SelectExpression":
4863
+ case "Ternary": return PRECEDENCE.CONDITIONAL;
4864
+ case "BinaryExpression": return getBinaryOperatorPrecedence(node);
4865
+ case "UnaryExpression": return node.operator.value === "not" ? PRECEDENCE.LOGICAL_NOT : PRECEDENCE.UNARY_SIGN;
4866
+ case "TestExpression": return PRECEDENCE.TEST;
4867
+ case "FilterExpression": return PRECEDENCE.FILTER;
4868
+ default: return PRECEDENCE.ATOM;
4013
4869
  }
4014
- return 0;
4870
+ }
4871
+ function formatOperand(node, minPrecedence) {
4872
+ const expr = formatExpression(node);
4873
+ return getPrecedence(node) < minPrecedence ? `(${expr})` : expr;
4015
4874
  }
4016
4875
  function format(program, indent = " ") {
4017
4876
  const indentStr = typeof indent === "number" ? " ".repeat(indent) : indent;
@@ -4023,6 +4882,9 @@ function createStatement(...text) {
4023
4882
  function formatStatements(stmts, depth, indentStr) {
4024
4883
  return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE);
4025
4884
  }
4885
+ function formatExpressionList(expressions) {
4886
+ return expressions.map((expression) => formatExpression(expression)).join(", ");
4887
+ }
4026
4888
  function formatStatement(node, depth, indentStr) {
4027
4889
  const pad = indentStr.repeat(depth);
4028
4890
  switch (node.type) {
@@ -4079,12 +4941,12 @@ function formatSet(node, depth, indentStr) {
4079
4941
  }
4080
4942
  function formatMacro(node, depth, indentStr) {
4081
4943
  const pad = indentStr.repeat(depth);
4082
- const args = node.args.map(formatExpression).join(", ");
4944
+ const args = formatExpressionList(node.args);
4083
4945
  return pad + createStatement("macro", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endmacro");
4084
4946
  }
4085
4947
  function formatCallStatement(node, depth, indentStr) {
4086
4948
  const pad = indentStr.repeat(depth);
4087
- const params = node.callerArgs && node.callerArgs.length > 0 ? `(${node.callerArgs.map(formatExpression).join(", ")})` : "";
4949
+ const params = node.callerArgs && node.callerArgs.length > 0 ? `(${formatExpressionList(node.callerArgs)})` : "";
4088
4950
  const callExpr = formatExpression(node.call);
4089
4951
  let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE;
4090
4952
  out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;
@@ -4098,67 +4960,61 @@ function formatFilterStatement(node, depth, indentStr) {
4098
4960
  out += pad + createStatement("endfilter");
4099
4961
  return out;
4100
4962
  }
4101
- function formatExpression(node, parentPrec = -1) {
4963
+ function formatExpression(node) {
4102
4964
  switch (node.type) {
4103
4965
  case "SpreadExpression": return `*${formatExpression(node.argument)}`;
4966
+ case "KeywordSpreadExpression": return `**${formatExpression(node.argument)}`;
4104
4967
  case "Identifier": return node.value;
4105
4968
  case "IntegerLiteral": return `${node.value}`;
4106
- case "FloatLiteral": return `${node.value}`;
4969
+ case "FloatLiteral": {
4970
+ const value = node.value;
4971
+ if (Object.is(value, -0)) return "-0.0";
4972
+ return value % 1 === 0 ? value.toFixed(1) : value.toString();
4973
+ }
4107
4974
  case "StringLiteral": return JSON.stringify(node.value);
4108
4975
  case "BinaryExpression": {
4109
4976
  const n = node;
4110
4977
  const thisPrecedence = getBinaryOperatorPrecedence(n);
4111
- const left = formatExpression(n.left, thisPrecedence);
4112
- const right = formatExpression(n.right, thisPrecedence + 1);
4113
- const expr = `${left} ${n.operator.value} ${right}`;
4114
- return thisPrecedence < parentPrec ? `(${expr})` : expr;
4978
+ const left = formatOperand(n.left, thisPrecedence);
4979
+ const right = formatOperand(n.right, thisPrecedence + 1);
4980
+ return `${left} ${n.operator.value} ${right}`;
4115
4981
  }
4116
4982
  case "UnaryExpression": {
4117
4983
  const n = node;
4118
- return n.operator.value + (n.operator.value === "not" ? " " : "") + formatExpression(n.argument, Infinity);
4984
+ const operandPrecedence = n.argument.type === "UnaryExpression" ? getPrecedence(n) : PRECEDENCE.ATOM;
4985
+ return n.operator.value + (n.operator.value === "not" ? " " : "") + formatOperand(n.argument, operandPrecedence);
4119
4986
  }
4120
4987
  case "CallExpression": {
4121
4988
  const n = node;
4122
- const args = n.args.map(formatExpression).join(", ");
4989
+ const args = formatExpressionList(n.args);
4123
4990
  return `${formatExpression(n.callee)}(${args})`;
4124
4991
  }
4125
4992
  case "MemberExpression": {
4126
4993
  const n = node;
4127
- let obj = formatExpression(n.object);
4128
- if (![
4129
- "Identifier",
4130
- "MemberExpression",
4131
- "CallExpression",
4132
- "StringLiteral",
4133
- "IntegerLiteral",
4134
- "FloatLiteral",
4135
- "ArrayLiteral",
4136
- "TupleLiteral",
4137
- "ObjectLiteral"
4138
- ].includes(n.object.type)) obj = `(${obj})`;
4994
+ const obj = formatOperand(n.object, PRECEDENCE.ATOM);
4139
4995
  let prop = formatExpression(n.property);
4140
4996
  if (!n.computed && n.property.type !== "Identifier" && n.property.type !== "IntegerLiteral") prop = `(${prop})`;
4141
4997
  return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`;
4142
4998
  }
4143
4999
  case "FilterExpression": {
4144
5000
  const n = node;
4145
- const operand = formatExpression(n.operand, Infinity);
5001
+ const operand = formatOperand(n.operand, PRECEDENCE.FILTER);
4146
5002
  if (n.filter.type === "CallExpression") return `${operand} | ${formatExpression(n.filter)}`;
4147
5003
  return `${operand} | ${n.filter.value}`;
4148
5004
  }
4149
5005
  case "SelectExpression": {
4150
5006
  const n = node;
4151
- return `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;
5007
+ return `${formatOperand(n.lhs, PRECEDENCE.LOGICAL_OR)} if ${formatOperand(n.test, PRECEDENCE.LOGICAL_OR)}`;
4152
5008
  }
4153
5009
  case "TestExpression": {
4154
5010
  const n = node;
4155
- return `${formatExpression(n.operand)} is${n.negate ? " not" : ""} ${n.test.value}`;
5011
+ return `${formatOperand(n.operand, PRECEDENCE.TEST)} is${n.negate ? " not" : ""} ${n.test.value}`;
4156
5012
  }
4157
5013
  case "ArrayLiteral":
4158
5014
  case "TupleLiteral": {
4159
- const elems = node.value.map(formatExpression);
5015
+ const elems = formatExpressionList(node.value);
4160
5016
  const brackets = node.type === "ArrayLiteral" ? "[]" : "()";
4161
- return `${brackets[0]}${elems.join(", ")}${brackets[1]}`;
5017
+ return `${brackets[0]}${elems}${brackets[1]}`;
4162
5018
  }
4163
5019
  case "ObjectLiteral": return `{${Array.from(node.value.entries()).map(([k, v]) => `${formatExpression(k)}: ${formatExpression(v)}`).join(", ")}}`;
4164
5020
  case "SliceExpression": {
@@ -4171,8 +5027,7 @@ function formatExpression(node, parentPrec = -1) {
4171
5027
  }
4172
5028
  case "Ternary": {
4173
5029
  const n = node;
4174
- const expr = `${formatExpression(n.trueExpr)} if ${formatExpression(n.condition, 0)} else ${formatExpression(n.falseExpr)}`;
4175
- return parentPrec > -1 ? `(${expr})` : expr;
5030
+ return `${formatOperand(n.trueExpr, PRECEDENCE.LOGICAL_OR)} if ${formatOperand(n.condition, PRECEDENCE.LOGICAL_OR)} else ${formatOperand(n.falseExpr, PRECEDENCE.CONDITIONAL)}`;
4176
5031
  }
4177
5032
  default: throw new Error(`Unknown expression type: ${node.type}`);
4178
5033
  }
@@ -4199,8 +5054,7 @@ var Template = class {
4199
5054
  return format(this.parsed, options?.indent || " ");
4200
5055
  }
4201
5056
  };
4202
- //#endregion
4203
- //#region src/chat/tokenizer.ts
5057
+ // src/chat/tokenizer.ts
4204
5058
  /*!
4205
5059
  * bitgpu/chat bundles @huggingface/tokenizers and @huggingface/jinja (Apache-2.0,
4206
5060
  * (c) Hugging Face) at build time so the published package stays dependency-free.
@@ -4297,8 +5151,7 @@ var ChatTokenizer = class {
4297
5151
  };
4298
5152
  }
4299
5153
  };
4300
- //#endregion
4301
- //#region src/chat/think.ts
5154
+ // src/chat/think.ts
4302
5155
  /** Longest suffix of `s` that is a proper prefix of `tag` (what must be held back). */
4303
5156
  function holdback$1(s, tag) {
4304
5157
  const max = Math.min(s.length, tag.length - 1);
@@ -4458,8 +5311,7 @@ var ThinkBudget = class {
4458
5311
  return this.spent >= this.budget || this.earlyFired ? this.closeId : null;
4459
5312
  }
4460
5313
  };
4461
- //#endregion
4462
- //#region src/chat/json.ts
5314
+ // src/chat/json.ts
4463
5315
  const SUPPORTED = /* @__PURE__ */ new Set([
4464
5316
  "type",
4465
5317
  "properties",
@@ -4586,7 +5438,7 @@ var JsonMachine = class JsonMachine {
4586
5438
  strLenOn = false;
4587
5439
  strCount = 0;
4588
5440
  strMin = 0;
4589
- strMax = Infinity;
5441
+ strMax = 1e400;
4590
5442
  numMin = null;
4591
5443
  numMax = null;
4592
5444
  numBuf = "";
@@ -4701,7 +5553,7 @@ var JsonMachine = class JsonMachine {
4701
5553
  this.strLenOn = sc?.minLength !== void 0 || sc?.maxLength !== void 0;
4702
5554
  this.strCount = 0;
4703
5555
  this.strMin = sc?.minLength ?? 0;
4704
- this.strMax = sc?.maxLength ?? Infinity;
5556
+ this.strMax = sc?.maxLength ?? 1e400;
4705
5557
  this.phase = 7;
4706
5558
  } else if (b === 45 || isDigit(b)) {
4707
5559
  if (t !== void 0 && t !== "number" && t !== "integer") return false;
@@ -4781,8 +5633,8 @@ var JsonMachine = class JsonMachine {
4781
5633
  * model in an unfinishable number. */
4782
5634
  intFeasible() {
4783
5635
  if (this.numMin === null && this.numMax === null) return true;
4784
- const lo = this.numMin ?? -Infinity;
4785
- const hi = this.numMax ?? Infinity;
5636
+ const lo = this.numMin ?? -1e400;
5637
+ const hi = this.numMax ?? 1e400;
4786
5638
  const neg = this.numBuf[0] === "-";
4787
5639
  const ds = neg ? this.numBuf.slice(1) : this.numBuf;
4788
5640
  if (ds === "") return lo <= 0;
@@ -4857,21 +5709,22 @@ var JsonMachine = class JsonMachine {
4857
5709
  if (b === 58) {
4858
5710
  const c = this.top();
4859
5711
  const key = c.seen[c.seen.length - 1];
4860
- if (c.branches) if (key === c.discKey) {
4861
- this.pending = { enum: c.branches.map((br) => br.properties[c.discRaw].enum?.[0]) };
4862
- c.discPending = true;
4863
- } else {
4864
- let prop = null;
4865
- for (const br of c.branches) {
4866
- const hit = Object.entries(br.properties ?? {}).find(([k]) => JsonMachine.bytesOf(k) === key);
4867
- if (hit) {
4868
- prop = hit[1];
4869
- break;
5712
+ if (c.branches) {
5713
+ if (key === c.discKey) {
5714
+ this.pending = { enum: c.branches.map((br) => br.properties[c.discRaw].enum?.[0]) };
5715
+ c.discPending = true;
5716
+ } else {
5717
+ let prop = null;
5718
+ for (const br of c.branches) {
5719
+ const hit = Object.entries(br.properties ?? {}).find(([k]) => JsonMachine.bytesOf(k) === key);
5720
+ if (hit) {
5721
+ prop = hit[1];
5722
+ break;
5723
+ }
4870
5724
  }
5725
+ this.pending = prop;
4871
5726
  }
4872
- this.pending = prop;
4873
- }
4874
- else {
5727
+ } else {
4875
5728
  const prop = c.node?.properties ? Object.entries(c.node.properties).find(([k]) => JsonMachine.bytesOf(k) === key) : void 0;
4876
5729
  this.pending = prop ? prop[1] : null;
4877
5730
  }
@@ -5008,9 +5861,7 @@ var JsonMachine = class JsonMachine {
5008
5861
  if (!isDigit(b)) return false;
5009
5862
  this.numSub = 7;
5010
5863
  return true;
5011
- case 7:
5012
- if (isDigit(b)) return true;
5013
- break;
5864
+ case 7: if (isDigit(b)) return true;
5014
5865
  }
5015
5866
  if (b === 46 && !this.numInt && (this.numSub === 1 || this.numSub === 2)) {
5016
5867
  this.numSub = 3;
@@ -5116,8 +5967,7 @@ function makeJsonFilter(table, eosTokenId, schema = null) {
5116
5967
  }
5117
5968
  };
5118
5969
  }
5119
- //#endregion
5120
- //#region src/chat/tools.ts
5970
+ // src/chat/tools.ts
5121
5971
  const BAD_NAME = /["\\\u0000-\u001f]/;
5122
5972
  /** Validate a tools list + choice; throws on anything the enforcer cannot guarantee. */
5123
5973
  function validateTools(tools, choice) {
@@ -5707,8 +6557,7 @@ function parseToolCallXml(raw, tools) {
5707
6557
  raw
5708
6558
  };
5709
6559
  }
5710
- //#endregion
5711
- //#region src/chat/index.ts
6560
+ // src/chat/index.ts
5712
6561
  function deriveChatWrap(tk) {
5713
6562
  if (!tk.hasChatTemplate) return null;
5714
6563
  try {
@@ -5960,11 +6809,13 @@ async function createChat(engine, options) {
5960
6809
  if (stops?.matched) stopCtl?.abort();
5961
6810
  };
5962
6811
  const emit = (chunk) => {
5963
- if (chunk.text) if (toolSplit) {
5964
- const r = toolSplit.push(chunk.text);
5965
- for (const b of r.blocks) pushBlock(b);
5966
- emitVisible(r.text);
5967
- } else emitVisible(chunk.text);
6812
+ if (chunk.text) {
6813
+ if (toolSplit) {
6814
+ const r = toolSplit.push(chunk.text);
6815
+ for (const b of r.blocks) pushBlock(b);
6816
+ emitVisible(r.text);
6817
+ } else emitVisible(chunk.text);
6818
+ }
5968
6819
  if (chunk.think) {
5969
6820
  thinkText += chunk.think;
5970
6821
  o.onThink?.(chunk.think);
@@ -5980,7 +6831,7 @@ async function createChat(engine, options) {
5980
6831
  minTokens: 64,
5981
6832
  ...o.thinkEarlyStop === true ? {} : o.thinkEarlyStop
5982
6833
  } : null;
5983
- const tb = think && (o.thinkBudget != null || tes) && tk.tokenToId("</think>") != null ? new ThinkBudget(tk.tokenToId("<think>"), tk.tokenToId("</think>"), Math.max(0, o.thinkBudget ?? Infinity), thinkPreopened, tes) : null;
6834
+ const tb = think && (o.thinkBudget != null || tes) && tk.tokenToId("</think>") != null ? new ThinkBudget(tk.tokenToId("<think>"), tk.tokenToId("</think>"), Math.max(0, o.thinkBudget ?? 1e400), thinkPreopened, tes) : null;
5984
6835
  let result;
5985
6836
  try {
5986
6837
  result = await engine.generate(inputTokenIds, {
@@ -6172,7 +7023,6 @@ async function createChat(engine, options) {
6172
7023
  tokenizer: tk
6173
7024
  };
6174
7025
  }
6175
- //#endregion
6176
7026
  export { ChatTokenizer, JsonMachine, StopScanner, ThinkBudget, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
6177
7027
 
6178
7028
  //# sourceMappingURL=chat.js.map