gofront 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +45 -49
  2. package/package.json +12 -8
  3. package/src/backend/js/expressions.js +1627 -148
  4. package/src/backend/js/fmt-runtime.js +573 -0
  5. package/src/backend/js/index.js +508 -102
  6. package/src/backend/js/runtime.js +1997 -106
  7. package/src/backend/js/statements.js +931 -87
  8. package/src/backend/js/stdlib/bits.js +87 -14
  9. package/src/backend/js/stdlib/builder.js +41 -6
  10. package/src/backend/js/stdlib/bytes.js +253 -7
  11. package/src/backend/js/stdlib/errors.js +7 -1
  12. package/src/backend/js/stdlib/fmt.js +349 -10
  13. package/src/backend/js/stdlib/index.js +19 -2
  14. package/src/backend/js/stdlib/json.js +1167 -0
  15. package/src/backend/js/stdlib/maps.js +0 -8
  16. package/src/backend/js/stdlib/math.js +17 -1
  17. package/src/backend/js/stdlib/simd.js +34 -0
  18. package/src/backend/js/stdlib/slices.js +36 -6
  19. package/src/backend/js/stdlib/strconv.js +10 -5
  20. package/src/backend/js/stdlib/strings.js +83 -4
  21. package/src/backend/js/stdlib/testing.js +7 -0
  22. package/src/backend/js/stdlib/time.js +79 -55
  23. package/src/backend/js/stdlib/unicode.js +1 -1
  24. package/src/backend/js/stdlib/utf8.js +1 -1
  25. package/src/backend/js/templ.js +38 -76
  26. package/src/backend/js/type-info.js +272 -0
  27. package/src/backend/shared/fmt-types.js +188 -0
  28. package/src/backend/wasm/boundary.js +446 -72
  29. package/src/backend/wasm/emit-builtins.js +320 -13
  30. package/src/backend/wasm/emit-exprs.js +1404 -199
  31. package/src/backend/wasm/emit-maps.js +61 -13
  32. package/src/backend/wasm/emit-stmts.js +1359 -164
  33. package/src/backend/wasm/emit.js +518 -74
  34. package/src/backend/wasm/encode.js +128 -13
  35. package/src/backend/wasm/globals.js +452 -0
  36. package/src/backend/wasm/index.js +194 -2489
  37. package/src/backend/wasm/method-expr.js +381 -0
  38. package/src/backend/wasm/module-emitter.js +2240 -0
  39. package/src/backend/wasm/monomorph.js +62 -4
  40. package/src/backend/wasm/optimize.js +4 -2
  41. package/src/backend/wasm/prescan.js +397 -0
  42. package/src/backend/wasm/stdlib/bytes.js +1804 -127
  43. package/src/backend/wasm/stdlib/core.js +1574 -199
  44. package/src/backend/wasm/stdlib/index.js +3 -5
  45. package/src/backend/wasm/stdlib/io.js +1567 -150
  46. package/src/backend/wasm/stdlib/packages.js +2 -0
  47. package/src/backend/wasm/stdlib/simd.js +499 -0
  48. package/src/backend/wasm/stdlib/time.js +1041 -12
  49. package/src/backend/wasm/types.js +221 -15
  50. package/src/backend/wasm/variadic.js +93 -0
  51. package/src/backend/wasm/wat.js +84 -20
  52. package/src/{cli-core.js → cli/cli-core.js} +236 -10
  53. package/src/{test-runner.js → cli/test-runner.js} +332 -39
  54. package/src/{vendor.js → cli/vendor.js} +89 -15
  55. package/src/compiler.js +107 -269
  56. package/src/dts-parser.js +71 -14
  57. package/src/index.js +15 -169
  58. package/src/{lexer.js → lexer/lexer.js} +102 -55
  59. package/src/{tokens.js → lexer/tokens.js} +1 -0
  60. package/src/link/sourcemap.js +97 -0
  61. package/src/link/stdlib.js +515 -0
  62. package/src/link/wasm.js +294 -0
  63. package/src/lower/bounds.js +394 -0
  64. package/src/lower/boxing.js +1 -6
  65. package/src/lower/captures.js +176 -32
  66. package/src/lower/embedding.js +2 -1
  67. package/src/lower/index.js +26 -18
  68. package/src/lower/json-codecs.js +1398 -0
  69. package/src/lower/ownership.js +22 -1
  70. package/src/lower/range.js +86 -1
  71. package/src/lower/reachability.js +132 -0
  72. package/src/parser/declarations.js +58 -13
  73. package/src/parser/expressions.js +29 -7
  74. package/src/parser/index.js +2 -1
  75. package/src/parser/statements.js +37 -22
  76. package/src/parser/struct-tag.js +144 -0
  77. package/src/{templ-parser.js → parser/templ.js} +138 -15
  78. package/src/parser/types.js +130 -13
  79. package/src/resolver.js +22 -1
  80. package/src/typechecker/assignability.js +215 -11
  81. package/src/typechecker/const-fold.js +356 -0
  82. package/src/typechecker/constants.js +256 -0
  83. package/src/typechecker/expressions.js +960 -99
  84. package/src/typechecker/index.js +491 -72
  85. package/src/typechecker/init-order.js +330 -0
  86. package/src/typechecker/resolve.js +596 -52
  87. package/src/typechecker/statements.js +157 -17
  88. package/src/typechecker/stdlib/core.js +333 -55
  89. package/src/typechecker/stdlib/excluded.js +898 -0
  90. package/src/typechecker/stdlib/extended.js +359 -26
  91. package/src/typechecker/{stdlib.js → stdlib/index.js} +6 -4
  92. package/src/typechecker/stdlib/simd.js +123 -0
  93. package/src/typechecker/termination.js +1 -1
  94. package/src/typechecker/types.js +165 -26
  95. package/stdlib/bytes/iter.go +192 -0
  96. package/stdlib/bytes/search.go +240 -0
  97. package/stdlib/bytes/split.go +218 -0
  98. package/stdlib/cmp/cmp.go +65 -0
  99. package/stdlib/encoding/json/errors.go +31 -0
  100. package/stdlib/encoding/json/indent.go +71 -0
  101. package/stdlib/encoding/json/number.go +12 -0
  102. package/stdlib/encoding/json/stream.go +173 -0
  103. package/stdlib/errors/overlay.go +12 -0
  104. package/stdlib/hash/hash.go +53 -0
  105. package/stdlib/internal/jsonrt/dec.go +738 -0
  106. package/stdlib/internal/jsonrt/enc.go +366 -0
  107. package/stdlib/internal/jsonrt/indent.go +135 -0
  108. package/stdlib/internal/jsonrt/number.go +27 -0
  109. package/stdlib/internal/jsonrt/reader.go +73 -0
  110. package/stdlib/internal/jsonrt/scanner.go +649 -0
  111. package/stdlib/io/io.go +346 -0
  112. package/stdlib/iter/iter.go +18 -0
  113. package/stdlib/maps/iter.go +65 -0
  114. package/stdlib/math/extra.go +270 -0
  115. package/stdlib/slices/extra.go +73 -0
  116. package/stdlib/slices/iter.go +113 -0
  117. package/stdlib/sort/sort.go +561 -0
  118. package/stdlib/strconv/quote.go +341 -0
  119. package/stdlib/strings/extra.go +35 -0
  120. package/stdlib/strings/iter.go +122 -0
  121. package/stdlib/sync/extra.go +105 -0
  122. package/stdlib/unicode/unicode.go +112 -0
  123. package/stdlib/unicode/utf8/bytes.go +239 -0
  124. package/src/backend/wasm/const-fold.js +0 -205
  125. package/src/backend/wasm/emit-stdlib.js +0 -13
  126. /package/src/{asset-manager.js → cli/asset-manager.js} +0 -0
  127. /package/src/{colors.js → cli/colors.js} +0 -0
  128. /package/src/{dev-server.js → cli/dev-server.js} +0 -0
  129. /package/src/{minifier.js → cli/minifier.js} +0 -0
  130. /package/src/{project-config.js → cli/project-config.js} +0 -0
  131. /package/src/{pwa.js → cli/pwa.js} +0 -0
  132. /package/src/{templ-lexer.js → lexer/templ-lexer.js} +0 -0
@@ -1,3 +1,5 @@
1
+ import { HELPER_FMT_LOOP, HELPER_FMT_UTIL } from "./fmt-runtime.js";
2
+
1
3
  // Runtime helpers emitted by the code generator when the corresponding feature is used.
2
4
  // Each export is a single JS statement (var __x = __x || function(...){...};) so that
3
5
  // multiple compiled files bundled together can safely repeat the declaration.
@@ -7,13 +9,222 @@ export const HELPER_LEN = `var __len = __len || function(a) {
7
9
  return a?.length ?? 0;
8
10
  };`;
9
11
 
12
+ // Slice views (Go's `b[lo:hi:max]` shares the backing store). A view of a
13
+ // plain array is a Proxy over an empty `__SV` array that holds the backing
14
+ // array `b`, offset `o`, length `n` and capacity `c`: Array.isArray, length,
15
+ // indexing, iteration and the Array.prototype methods work through the traps,
16
+ // so the rest of the runtime and JS callers see an ordinary array (`__SV`
17
+ // makes Array.prototype methods return plain arrays and Node print the
18
+ // elements). A view covering its whole backing array is that array. A
19
+ // typed-array view is a `subarray`; a capacity beyond its length is kept in a
20
+ // WeakMap shared by every compiled module. `__slice` also accepts strings
21
+ // (generic code). `__reslice` is `x = x[lo:hi]`: within `len(x)` a plain
22
+ // array is copied instead (a Proxy is much slower to index, and the old
23
+ // value of `x` is usually dead), see docs/go-compatibility.md.
24
+ // The copy keeps the capacity of the old value: its `__rcap` symbol property
25
+ // (shared by every compiled module) is `{b, o, c, s, so, own}` (backing array,
26
+ // offset, capacity, snapshot of the copy, its offset in `s`, and false while
27
+ // `s` is shared with another copy). An index
28
+ // write `x[i] = v` to a chain that the package self-reslices is followed by
29
+ // `__rcs(x, i)`, which writes the element through to `b` (and `s`), so it is
30
+ // ordered with writes through other slices of `b`. A slice or `append`
31
+ // beyond the copy's length writes the remaining elements that differ from the
32
+ // snapshot (written through other references to the copy) back into `b`
33
+ // first and continues with a view over `b`. `__mkslice` is `make([]T, n, cap)`.
34
+ // `__sv` is its own helper ("sv") so range loops can unwrap a view without
35
+ // pulling in the rest.
36
+ export const HELPER_SV = `var __sv = __sv || Symbol.for("gofront.sliceView");`;
37
+
38
+ export const HELPER_SLICE = `var __tcap = __tcap || (globalThis[Symbol.for("gofront.typedCap")] ??= new WeakMap());
39
+ var __SV = __SV || class extends Array {
40
+ static get [Symbol.species]() { return Array; }
41
+ [Symbol.for("nodejs.util.inspect.custom")]() { return Array.from(this); }
42
+ };
43
+ var __rcap = __rcap || Symbol.for("gofront.resliceCap");
44
+ var __svh = __svh || {
45
+ get(t, k) {
46
+ if (typeof k === "string") {
47
+ const ch = k.charCodeAt(0);
48
+ if (ch >= 48 && ch <= 57) { const i = +k; return i < t.n ? t.b[t.o + i] : undefined; }
49
+ if (k === "length") return t.n;
50
+ } else if (k === __sv) return t;
51
+ return t[k];
52
+ },
53
+ set(t, k, v) {
54
+ if (typeof k === "string") {
55
+ const ch = k.charCodeAt(0);
56
+ if (ch >= 48 && ch <= 57) { const i = +k; if (i < t.n) t.b[t.o + i] = v; return true; }
57
+ if (k === "length") return true;
58
+ }
59
+ t[k] = v;
60
+ return true;
61
+ },
62
+ has(t, k) {
63
+ if (typeof k === "string") {
64
+ const ch = k.charCodeAt(0);
65
+ if (ch >= 48 && ch <= 57) return +k < t.n;
66
+ }
67
+ return k in t;
68
+ },
69
+ defineProperty(t, k, d) {
70
+ if (typeof k === "string") {
71
+ const ch = k.charCodeAt(0);
72
+ if (ch >= 48 && ch <= 57) {
73
+ const i = +k;
74
+ if (i >= t.n || d.get || d.set || d.configurable === false) return false;
75
+ if ("value" in d) t.b[t.o + i] = d.value;
76
+ return true;
77
+ }
78
+ }
79
+ return Reflect.defineProperty(t, k, d);
80
+ },
81
+ preventExtensions() { return false; },
82
+ deleteProperty(t, k) {
83
+ if (typeof k === "string" && k.charCodeAt(0) >= 48 && k.charCodeAt(0) <= 57) return true;
84
+ return delete t[k];
85
+ },
86
+ ownKeys(t) {
87
+ const ks = [];
88
+ for (let i = 0; i < t.n; i++) ks.push(String(i));
89
+ ks.push("length");
90
+ return ks;
91
+ },
92
+ getOwnPropertyDescriptor(t, k) {
93
+ if (typeof k === "string") {
94
+ const ch = k.charCodeAt(0);
95
+ if (ch >= 48 && ch <= 57) {
96
+ const i = +k;
97
+ return i < t.n ? { value: t.b[t.o + i], writable: true, enumerable: true, configurable: true } : undefined;
98
+ }
99
+ if (k === "length") return { value: t.n, writable: true, enumerable: false, configurable: false };
100
+ }
101
+ return Reflect.getOwnPropertyDescriptor(t, k);
102
+ },
103
+ };
104
+ var __mkview = __mkview || function(b, o, n, c, f) {
105
+ if (o === 0 && n === b.length && c === n && !f) return b;
106
+ if (c === 0) return [];
107
+ const t = new __SV();
108
+ t.b = b; t.o = o; t.n = n; t.c = c;
109
+ return new Proxy(t, __svh);
110
+ };
111
+ var __cap = __cap || function(a) {
112
+ if (a == null) return 0;
113
+ const s = a[__sv];
114
+ if (s !== undefined) return s.c;
115
+ if (ArrayBuffer.isView(a)) return __tcap.get(a) ?? a.length;
116
+ return a[__rcap]?.c ?? a.length;
117
+ };
118
+ // A snapshot shared by a copy of a copy (e.own false) is cloned before it is
119
+ // updated, so the update does not reach the other copy's snapshot (whose
120
+ // write-back would then revert the element).
121
+ var __rcown = __rcown || function(e, a) {
122
+ if (e.own === false) { e.s = e.s.slice(e.so, e.so + a.length); e.so = 0; e.own = true; }
123
+ return e.s;
124
+ };
125
+ // Write back only the elements of a __reslice copy that changed since it was
126
+ // made (e.s from e.so is its snapshot, kept up to date by __rcs), so writes
127
+ // made meanwhile through other slices of the backing array are kept.
128
+ var __rcput = __rcput || function(e, a, from, to) {
129
+ for (let i = from; i < to; i++) {
130
+ const v = a[i];
131
+ if (!Object.is(v, e.s[e.so + i])) { e.b[e.o + i] = v; __rcown(e, a)[e.so + i] = v; }
132
+ }
133
+ };
134
+ // After an index write to a possible __reslice copy: write element i through.
135
+ var __rcs = __rcs || function(a, i) {
136
+ const e = a?.[__rcap];
137
+ if (e !== undefined && i >= 0 && i < e.c && i < a.length) { const v = a[i]; e.b[e.o + i] = v; __rcown(e, a)[e.so + i] = v; }
138
+ };
139
+ var __rcdef = __rcdef || function(r, e) {
140
+ Object.defineProperty(r, __rcap, { value: e, writable: true });
141
+ };
142
+ var __rcflush = __rcflush || function(a) {
143
+ const e = a[__rcap];
144
+ if (e !== undefined) __rcput(e, a, 0, a.length);
145
+ return e;
146
+ };
147
+ var __slice = __slice || function(a, lo, hi, max) {
148
+ if (typeof a === "string") return a.slice(lo, hi);
149
+ const s = a == null ? undefined : a[__sv];
150
+ const n = s !== undefined ? s.n : a == null ? 0 : a.length;
151
+ const c = s !== undefined ? s.c : __cap(a);
152
+ const mx = max;
153
+ if (hi === undefined) hi = n;
154
+ if (max === undefined) max = c;
155
+ if (!(lo >= 0 && lo <= hi && hi <= max && max <= c)) throw new Error("runtime error: slice bounds out of range");
156
+ if (a == null) return a;
157
+ if (s !== undefined) return __mkview(s.b, s.o + lo, hi - lo, max - lo);
158
+ if (c > n && Array.isArray(a)) {
159
+ // a is a __reslice copy (only those have cap > len): reach past its
160
+ // length or capacity through the backing array, else stay on the copy
161
+ // (an explicit max needs a view: the copy itself keeps the old cap).
162
+ if (hi <= n && (mx === undefined || mx <= n)) return __mkview(a, lo, hi - lo, Math.min(max, n) - lo, mx !== undefined);
163
+ else { const e = __rcflush(a); return __mkview(e.b, e.o + lo, hi - lo, max - lo); }
164
+ }
165
+ if (ArrayBuffer.isView(a)) {
166
+ const r = hi <= n ? a.subarray(lo, hi) : new a.constructor(a.buffer, a.byteOffset + lo * a.BYTES_PER_ELEMENT, hi - lo);
167
+ if (max - lo > hi - lo) __tcap.set(r, max - lo);
168
+ return r;
169
+ }
170
+ return __mkview(a, lo, hi - lo, max - lo);
171
+ };
172
+ var __reslice = __reslice || function(a, lo, hi) {
173
+ if (Array.isArray(a) && a[__sv] === undefined) {
174
+ const n = a.length;
175
+ if (hi === undefined) hi = n;
176
+ if (lo >= 0 && lo <= hi && hi <= n) {
177
+ if (lo === 0 && hi === n) return a;
178
+ const e = a[__rcap];
179
+ const r = a.slice(lo, hi);
180
+ if (e === undefined) {
181
+ __rcdef(r, { b: a, o: lo, c: n - lo, s: a.slice(lo, hi), so: 0 });
182
+ return r;
183
+ }
184
+ // A copy of a copy: write back the changed elements it drops and share
185
+ // the snapshot (copied on write, __rcown), so a pop costs no more than
186
+ // the copy itself.
187
+ if (lo > 0) __rcput(e, a, 0, lo);
188
+ __rcput(e, a, hi, n);
189
+ e.own = false;
190
+ __rcdef(r, { b: e.b, o: e.o + lo, c: e.c - lo, s: e.s, so: e.so + lo, own: false });
191
+ return r;
192
+ }
193
+ }
194
+ return __slice(a, lo, hi);
195
+ };
196
+ var __mkslice = __mkslice || function(n, b) {
197
+ if (!(n >= 0 && n <= b.length)) throw new Error("runtime error: makeslice: cap out of range");
198
+ return __slice(b, 0, n);
199
+ };`;
200
+
10
201
  export const HELPER_APPEND = `var __append = __append || function(a, ...b) {
11
202
  if (a && ArrayBuffer.isView(a)) {
203
+ const c = __tcap.get(a);
204
+ if (c !== undefined && a.length + b.length <= c) {
205
+ const r = new a.constructor(a.buffer, a.byteOffset, a.length + b.length);
206
+ r.set(b, a.length);
207
+ if (c > r.length) __tcap.set(r, c);
208
+ return r;
209
+ }
12
210
  const res = new a.constructor(a.length + b.length);
13
211
  res.set(a);
14
212
  res.set(b, a.length);
15
213
  return res;
16
214
  }
215
+ const s = a ? a[__sv] : undefined;
216
+ if (s !== undefined && s.n + b.length <= s.c) {
217
+ for (let i = 0; i < b.length; i++) s.b[s.o + s.n + i] = b[i];
218
+ return __mkview(s.b, s.o, s.n + b.length, s.c);
219
+ }
220
+ if (s === undefined && a) {
221
+ const e = a[__rcap];
222
+ if (e !== undefined && a.length + b.length <= e.c) {
223
+ __rcflush(a);
224
+ for (let i = 0; i < b.length; i++) e.b[e.o + a.length + i] = b[i];
225
+ return __mkview(e.b, e.o, a.length + b.length, e.c);
226
+ }
227
+ }
17
228
  return a ? [...a, ...b] : b;
18
229
  };`;
19
230
 
@@ -41,6 +252,41 @@ export const HELPER_SCLONE = `var __sclone = __sclone || function(x) {
41
252
  return Object.assign(Object.create(Object.getPrototypeOf(x)), x);
42
253
  };`;
43
254
 
255
+ // Variadic prologue. `f(xs...)` to a Go-compiled variadic function passes
256
+ // `{ __sp: xs }`, so the parameter is the caller's slice itself (or nil).
257
+ export const HELPER_VA = `var __va = __va || function(a, nilEmpty) {
258
+ const f = a.length === 1 ? a[0] : undefined;
259
+ if (a.length === 0 && nilEmpty) return null;
260
+ return f !== null && typeof f === "object" && f.__sp !== undefined ? f.__sp : a;
261
+ };`;
262
+
263
+ // Copy of a value whose type is a type parameter. `z` is the argument's
264
+ // zero-value factory: an object zero means a struct or array (copied by
265
+ // value); anything else (scalars, pointers, interfaces) is returned as is.
266
+ export const HELPER_VCLONE = `var __vclone = __vclone || function __vclone(z, x) {
267
+ if (x === null || typeof x !== "object") return x;
268
+ const zero = z?.();
269
+ if (zero === null || zero === undefined || typeof zero !== "object") return x;
270
+ const cp = (v) => {
271
+ if (v === null || typeof v !== "object") return v;
272
+ if (Array.isArray(v)) return v.map(cp);
273
+ if (typeof v.__clone === "function") return v.__clone();
274
+ return Object.assign(Object.create(Object.getPrototypeOf(v)), v);
275
+ };
276
+ return cp(x);
277
+ };`;
278
+
279
+ // == on type-parameter operands: structs and arrays compare by value, other
280
+ // type arguments with ===. Decided at run time from the zero-value factory.
281
+ export const HELPER_GEQ = `var __geq = __geq || function(z, a, b) {
282
+ if (a === b) return true;
283
+ if (z?.k === "iface") return __ifeq(a, b);
284
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
285
+ const zero = z?.();
286
+ if (zero === null || zero === undefined || typeof zero !== "object") return false;
287
+ return __equal(a, b);
288
+ };`;
289
+
44
290
  // Interface boxing: tag struct values (__v) vs struct pointers (__p) so type
45
291
  // switches can tell T from *T; tags are non-enumerable so __equal/JSON ignore them.
46
292
  export const HELPER_IFACE_BOX = `var __ifv = __ifv || function(x, ptrFields) {
@@ -62,17 +308,61 @@ export const HELPER_IFACE_BOX = `var __ifv = __ifv || function(x, ptrFields) {
62
308
  }
63
309
  for (const k of Object.keys(c)) {
64
310
  if (c[k] !== null && typeof c[k] === "object" && !Array.isArray(c[k]) && !ArrayBuffer.isView(c[k])) {
65
- if (!c[k].__v && !c[k].__p && (!Array.isArray(ptrFields) || !ptrFields.includes(k))) {
311
+ if (!c[k].__v && !c[k].__p && Object.isExtensible(c[k]) && (!Array.isArray(ptrFields) || !ptrFields.includes(k))) {
66
312
  Object.defineProperty(c[k], "__v", { value: true, configurable: true });
67
313
  }
68
314
  }
69
315
  }
70
316
  return c;
71
317
  };
318
+ var __buffer_proto = __buffer_proto || {
319
+ Write(d) {
320
+ this._lastOp = 0;
321
+ for (let i = 0; i < d.length; i++) this._buf.push(d[i]);
322
+ return [d.length, null];
323
+ },
324
+ WriteString(s) {
325
+ this._lastOp = 0;
326
+ const bytes = new TextEncoder().encode(s);
327
+ for (let i = 0; i < bytes.length; i++) this._buf.push(bytes[i]);
328
+ return [bytes.length, null];
329
+ },
330
+ Read(p) {
331
+ if (!this._buf || this._buf.length === 0) return [0, typeof __io_eof !== "undefined" ? __io_eof : "EOF"];
332
+ const n = Math.min(p.length, this._buf.length);
333
+ for (let i = 0; i < n; i++) p[i] = this._buf.shift();
334
+ if (n > 0) { this._lastOp = 1; this._lastByte = p[n - 1]; } else { this._lastOp = 0; }
335
+ return [n, null];
336
+ },
337
+ String() {
338
+ return new TextDecoder().decode(new Uint8Array(this._buf));
339
+ },
340
+ Reset() {
341
+ this._buf = [];
342
+ }
343
+ };
344
+ var __builder_proto = __builder_proto || {
345
+ Write(d) {
346
+ this._buf += new TextDecoder().decode(new Uint8Array(d));
347
+ return [d.length, null];
348
+ },
349
+ WriteString(s) {
350
+ this._buf += s;
351
+ return [new TextEncoder().encode(s).length, null];
352
+ },
353
+ String() {
354
+ return this._buf;
355
+ },
356
+ Reset() {
357
+ this._buf = "";
358
+ }
359
+ };
72
360
  var __ifp = __ifp || function(x, ptrFields, seen) {
73
361
  if (x === null || typeof x !== "object") return x;
362
+ if (Array.isArray(x._buf) && typeof x.Write !== "function") Object.assign(x, __buffer_proto);
363
+ else if (typeof x._buf === "string" && typeof x.WriteString !== "function") Object.assign(x, __builder_proto);
74
364
  if (x.__p !== true && Object.isExtensible(x))
75
- Object.defineProperty(x, "__p", { value: true, configurable: true });
365
+ Object.defineProperty(x, "__p", { value: true, configurable: true, writable: true });
76
366
  if (Array.isArray(ptrFields)) {
77
367
  seen = seen || new Set();
78
368
  if (seen.has(x)) return x;
@@ -124,16 +414,180 @@ var __ifps = __ifps || function(x) {
124
414
  return x;
125
415
  };`;
126
416
 
417
+ // fmt metadata: the Stringer/error element types of a slice, array or map
418
+ // converted to an interface (the elements are raw numbers/strings at run
419
+ // time), as a non-enumerable __fd descriptor that __sprintf reads.
420
+ export const HELPER_IFD = `var __ifd = __ifd || function(x, d) {
421
+ if (x !== null && typeof x === "object" && Object.isExtensible(x))
422
+ Object.defineProperty(x, "__fd", { value: d, configurable: true });
423
+ return x;
424
+ };`;
425
+
127
426
  // Nil-interface method call guard (strict mode only): matches Go's panic
128
427
  // message instead of a JS TypeError.
428
+ // Strict-mode 64-bit shifts (`both` packages): Go's wrap-around on `<<`, the
429
+ // sign fill on `>>`, and the negative-count panic.
430
+ export const HELPER_SHIFT = `var __shl64 = __shl64 || function(x, n, u) {
431
+ if (n < 0) throw new Error("runtime error: negative shift amount");
432
+ if (n >= 64) return 0;
433
+ const r = x * 2 ** n;
434
+ if (Number.isSafeInteger(r)) return r;
435
+ const b = BigInt(x) << BigInt(n);
436
+ return Number(u ? BigInt.asUintN(64, b) : BigInt.asIntN(64, b));
437
+ };
438
+ var __shr64 = __shr64 || function(x, n, u) {
439
+ if (n < 0) throw new Error("runtime error: negative shift amount");
440
+ if (n >= 64) return u || x >= 0 ? 0 : -1;
441
+ return Math.floor(x / 2 ** n);
442
+ };`;
443
+
129
444
  export const HELPER_NIL_CALL = `var __nilcall = __nilcall || function(x) {
130
445
  if (x == null) throw new Error("runtime error: invalid memory address or nil pointer dereference");
131
446
  return x;
132
447
  };`;
133
448
 
134
- export const HELPER_EQUAL = `var __equal = __equal || function __equal(a, b) {
449
+ // Strict-mode index checks (`both` packages): Go's out-of-range panic for
450
+ // slices, arrays and strings. `__at` reads an element; `__ix` returns the
451
+ // checked index for writes, compound assignments and string reads. A nil
452
+ // slice (`null`) has length 0.
453
+ export const HELPER_BOUNDS = `var __ixerr = __ixerr || function(i, n) {
454
+ throw new Error(i < 0 ? "runtime error: index out of range [" + i + "]" : "runtime error: index out of range [" + i + "] with length " + n);
455
+ };
456
+ var __at = __at || function(a, i) {
457
+ if (a != null && i >= 0 && i < a.length) return a[i];
458
+ return __ixerr(i, a == null ? 0 : a.length);
459
+ };
460
+ var __ix = __ix || function(a, i) {
461
+ if (a != null && i >= 0 && i < a.length) return i;
462
+ return __ixerr(i, a == null ? 0 : a.length);
463
+ };
464
+ var __lv;`;
465
+
466
+ // Generic zero values (generics are erased in JS): a generic function takes
467
+ // one zero-value factory per type parameter as leading arguments, and an
468
+ // instance of a generic struct keeps its factories under the `__tz` symbol
469
+ // (a symbol, so field iteration, equality and JSON never see it). Shared
470
+ // factories for the common zero values avoid a closure per call.
471
+ export const HELPER_GENERICS = `var __tz = __tz || Symbol.for("gofront.typeArgs");
472
+ var __zn = __zn || (() => null);
473
+ var __z0 = __z0 || (() => 0);
474
+ var __zs = __zs || (() => "");
475
+ var __zf = __zf || (() => false);
476
+ var __ti = __ti || function(f, k, id, is, u, b, fb) {
477
+ const g = () => f();
478
+ g.k = k; g.id = id; g.is = is; g.u = u; g.b = b; g.fb = fb;
479
+ return g;
480
+ };
481
+ var __tid = __tid || function(...ids) {
482
+ return ids.every((i) => i !== undefined) ? ids.join(",") : undefined;
483
+ };
484
+ var __tconv = __tconv || function(f, v) {
485
+ v = typeof v === "bigint" ? Number(v) : v;
486
+ switch (f?.k) {
487
+ case "int": case "int64": case "uint": case "uint64": case "uintptr": return Math.trunc(Number(v));
488
+ case "int8": return (Number(v) << 24) >> 24;
489
+ case "int16": return (Number(v) << 16) >> 16;
490
+ case "int32": case "rune": return Number(v) | 0;
491
+ case "uint8": case "byte": return Number(v) & 0xFF;
492
+ case "uint16": return Number(v) & 0xFFFF;
493
+ case "uint32": return Number(v) >>> 0;
494
+ case "float32": return Math.fround(Number(v));
495
+ case "float64": return Number(v);
496
+ default: return v;
497
+ }
498
+ };`;
499
+
500
+ // Strict-mode nil maps: the zero value of a map type is one frozen empty
501
+ // object, so reads, `len` and `range` behave as on an empty map, and every
502
+ // write goes through `__mw`, which panics with Go's message.
503
+ export const HELPER_NIL_MAP = `var __nilmap = __nilmap || Object.freeze(Object.defineProperties({}, { __map: { value: true }, __nilm: { value: true } }));
504
+ var __mw = __mw || function(m) {
505
+ if (m == null || m === __nilmap) throw new Error("assignment to entry in nil map");
506
+ return m;
507
+ };
508
+ var __isnm = __isnm || function(m) {
509
+ return m == null || m.__nilm === true || (m.__nm === true && Object.keys(m).length === 0);
510
+ };`;
511
+
512
+ // js-package nil maps: the zero value is a fresh `{}` carrying a hidden tag;
513
+ // `m == nil` holds while it stays empty (writes are allowed, as in plain JS).
514
+ export const HELPER_NM = `var __nm = __nm || function() { return Object.defineProperty({}, "__nm", { value: true }); };
515
+ var __isnm = __isnm || function(m) {
516
+ return m == null || m.__nilm === true || (m.__nm === true && Object.keys(m).length === 0);
517
+ };`;
518
+
519
+ // Struct map keys: a JS object key is a string, so a struct key is coerced
520
+ // through `toString` to an injective encoding, and the key value is kept in
521
+ // a table so ranging and fmt can recover it.
522
+ export const HELPER_STRUCT_KEY = `var __kt = __kt || new Map();
523
+ var __sk = __sk || function(o) {
524
+ const s = "\\u0001" + JSON.stringify(o, (k, v) => typeof v === "bigint" ? v.toString() + "n" : v);
525
+ if (!__kt.has(s)) __kt.set(s, typeof o.__clone === "function" ? o.__clone() : o);
526
+ return s;
527
+ };
528
+ var __ik = __ik || function(k) {
529
+ const t = typeof k;
530
+ if (t === "number" || t === "boolean" || t === "bigint") return "\\u0001" + t + ":" + String(k);
531
+ if (k !== null && t === "object" && typeof k.__gfUnbox === "function" && !k.constructor.name.endsWith("$Ptr")) {
532
+ const v = k.__gfUnbox(), vt = typeof v;
533
+ if (vt === "string" || vt === "number" || vt === "boolean" || vt === "bigint") {
534
+ const s = "\\u0001" + k.constructor.name + ":" + vt + ":" + String(v);
535
+ if (!__kt.has(s)) __kt.set(s, k);
536
+ return s;
537
+ }
538
+ }
539
+ return k;
540
+ };
541
+ // A key typed by a type parameter whose factory is \`f\`: interface type
542
+ // arguments key by dynamic type; \`box\` (an \`any\`-keyed map) boxes a named
543
+ // basic value first, other keys are left as they are.
544
+ var __ikt = __ikt || function(f, k, box) {
545
+ if (f?.k === "iface") return __ik(k);
546
+ return box ? __ik(f?.b ? f.b(k) : k) : k;
547
+ };
548
+ var __kd = __kd || function(s, copy) {
549
+ if (typeof s !== "string" || s.charCodeAt(0) !== 1) return s;
550
+ const k = __kt.get(s);
551
+ if (k === undefined) {
552
+ if (s.startsWith("\\u0001number:")) return Number(s.slice(8));
553
+ if (s.startsWith("\\u0001boolean:")) return s.slice(9) === "true";
554
+ if (s.startsWith("\\u0001bigint:")) return BigInt(s.slice(8));
555
+ return s;
556
+ }
557
+ return copy && typeof k.__clone === "function" ? k.__clone() : k;
558
+ };
559
+ var __kcmp = __kcmp || function(a, b) {
560
+ if (a !== null && b !== null && typeof a === "object" && typeof b === "object") {
561
+ for (const f of Object.keys(a)) {
562
+ const c = __kcmp(a[f], b[f]);
563
+ if (c !== 0) return c;
564
+ }
565
+ return 0;
566
+ }
567
+ return a < b ? -1 : a > b ? 1 : 0;
568
+ };`;
569
+
570
+ // Interface equality: named non-struct values are boxed in interfaces, so two
571
+ // boxes are equal when they share a type and hold the same value (as in Go).
572
+ export const HELPER_IFEQ = `var __ifeq = __ifeq || function(a, b) {
135
573
  if (a === b) return true;
574
+ if (a === null || a === undefined || b === null || b === undefined) return a == null && b == null;
575
+ if (typeof a === "object" && typeof b === "object" && a.constructor === b.constructor && typeof a.__gfUnbox === "function") {
576
+ return a.__gfUnbox() === b.__gfUnbox();
577
+ }
578
+ // Struct values boxed by __ifv compare field by field.
579
+ if (typeof a === "object" && typeof b === "object" && a.__v === true && b.__v === true && a.constructor === b.constructor) {
580
+ return __equal(a, b);
581
+ }
582
+ return false;
583
+ };`;
584
+
585
+ export const HELPER_EQUAL = `var __equal = __equal || function __equal(a, b) {
586
+ if (a === b && !Array.isArray(a)) return true;
136
587
  if (a === null || b === null) return false;
588
+ if (a.__target !== undefined && b.__target !== undefined) {
589
+ return a.__target === b.__target && a.__index === b.__index;
590
+ }
137
591
  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
138
592
  if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
139
593
  if (a.byteLength !== b.byteLength || a.length !== b.length) return false;
@@ -163,8 +617,17 @@ export const HELPER_CDIV = `var __cdiv = __cdiv || function(a, b) {
163
617
  return { re: (a.re * b.re + a.im * b.im) / d, im: (a.im * b.re - a.re * b.im) / d };
164
618
  };`;
165
619
 
166
- // Panic/defer runtime. \`stack\` holds the in-flight panic of every frame
167
- // currently running its defers; \`armed\` is set right before a deferred
620
+ export const HELPER_PTREQ = `var __ptreq = __ptreq || function __ptreq(a, b) {
621
+ if (a === b) return true;
622
+ if (!a || !b) return false;
623
+ if (a.__target !== undefined && b.__target !== undefined) {
624
+ return a.__target === b.__target && a.__index === b.__index;
625
+ }
626
+ return false;
627
+ };`;
628
+
629
+ // Panic/defer runtime. `stack` holds the in-flight panic of every frame
630
+ // currently running its defers; `armed` is set right before a deferred
168
631
  // function is invoked and consumed by that function's prologue, so recover()
169
632
  // only takes effect when called directly by the deferred function (Go spec).
170
633
  export const HELPER_PANIC = `var __gopanic = __gopanic || { stack: [], armed: false };
@@ -192,7 +655,10 @@ var __recover = __recover || function(ok) {
192
655
  return top.err?.message ?? String(top.err);
193
656
  };`;
194
657
 
195
- export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
658
+ export const HELPER_SPRINTF =
659
+ HELPER_FMT_UTIL +
660
+ `
661
+ var __sprintf = __sprintf || function(f, ...a) {
196
662
  let i = 0;
197
663
  const ptrMap = new WeakMap();
198
664
  const ptrSet = new WeakSet();
@@ -208,25 +674,94 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
208
674
  const markPtr = (o) => {
209
675
  if (o !== null && typeof o === "object") ptrSet.add(o);
210
676
  };
211
- const isPointer = (o) => {
212
- return o !== null && typeof o === "object" && (o.__p === true || ptrSet.has(o));
677
+ // el: o is a value element of a slice, array or map or a struct value field
678
+ // (per the static descriptor), so the __p tag left by an earlier &x does not
679
+ // make it a pointer; only the container's own pointer marking does.
680
+ const isPointer = (o, el) => {
681
+ return o !== null && typeof o === "object" && ((o.__p === true && !el) || ptrSet.has(o));
213
682
  };
214
- const formatV = (val, isPlus, isTopLevel) => {
683
+ const isExported = (k) => /^\\p{Lu}/u.test(k);
684
+ // %#v never calls String (nor, in Go, Error); the Error dispatch stays as it
685
+ // was before Stringer support.
686
+ let sharp = false;
687
+ // The method fmt calls on val: Error before String, and a pointer-receiver
688
+ // method (listed in the class's __pr) only for a pointer, as Go's method sets.
689
+ // __pe maps Error/String to the embedded interface field that provides it.
690
+ const stringMethod = (val, el) => {
691
+ for (const name of sharp ? ["Error"] : ["Error", "String"]) {
692
+ if (typeof val[name] === "function") {
693
+ if (val[name].length !== 0) continue;
694
+ if (!sharp && val.__pr !== undefined && val.__pr.includes(name) && !isPointer(val, el)) continue;
695
+ return name;
696
+ }
697
+ const pe = sharp ? undefined : val.__pe?.[name];
698
+ if (pe !== undefined && typeof val[pe]?.[name] === "function") return name;
699
+ }
700
+ return "";
701
+ };
702
+ // A nil *T boxed in an interface (a named non-struct type) has no value to call
703
+ // a value-receiver method on: fmt prints <nil>, as Go does after recovering.
704
+ const callMethod = (val, name) => {
705
+ if (typeof val[name] !== "function") return val[val.__pe[name]][name]();
706
+ if (typeof val.__gfUnbox !== "function" || val.__gfUnbox() !== null) return val[name]();
707
+ try { return val[name](); } catch (e) { return "<nil>"; }
708
+ };
709
+ // Errors from errors.New/Errorf and the stdlib are plain runtime objects, not
710
+ // instances of a user class; they print their message wherever they are.
711
+ const isRuntimeError = (val) => {
712
+ const proto = Object.getPrototypeOf(val);
713
+ return (proto === null || Object.getPrototypeOf(proto) === null) && typeof val.Error === "function" && val.Error.length === 0;
714
+ };
715
+ // ro: val was reached through an unexported field, where Go cannot call
716
+ // methods on user types. fd: descriptor of val's type when it is not carried
717
+ // by val itself (raw named values and the elements of slices and maps).
718
+ // el: val is a value element or value field, see isPointer.
719
+ // A value can have two descriptors: the Stringer one (see _fmtDesc) and the
720
+ // static type (fmt-types.js, set by __ft). fd is either one, or { $both, t, s }
721
+ // holding both, so typed formatting and Stringer dispatch compose.
722
+ const both = __fmtu.both;
723
+ const formatV = (val, isPlus, isTopLevel, ro, fd, el) => {
724
+ if (typeof __FT !== "undefined" && val instanceof __FT) {
725
+ if (val.t?.n === "time.Duration") {
726
+ return typeof __durationString === "function" ? __durationString(val.v) : String(val.v);
727
+ }
728
+ return formatV(val.v, isPlus, isTopLevel, ro, both(val.t, val.v?.__fd), el);
729
+ }
730
+ const [td, sdesc] = __fmtu.split(fd);
731
+ if (td?.n === "time.Duration") {
732
+ return typeof __durationString === "function" ? __durationString(val) : String(val);
733
+ }
734
+ if (sdesc?.b && !ro && !(val instanceof sdesc.b)) val = new sdesc.b(val);
735
+ if (sdesc?.m === 1 && (val === null || val === undefined)) return "map[]";
736
+ if (sdesc?.np !== undefined && (val === null || val === undefined)) val = sdesc.np;
215
737
  if (val === null || val === undefined) return "<nil>";
216
738
  if (typeof val === "boolean") return String(val);
217
- if (typeof val === "number" || typeof val === "bigint") return String(val);
739
+ if (typeof val === "number" && td) {
740
+ const fb = __fmtu.baseOf(td);
741
+ if (fb?.k === "b" && __fmtu.isFloatN(fb.n)) return __fmtu.fmtFloat(val, "g", {}, 0, false, -1, false, fb.n === "float32");
742
+ }
743
+ if (typeof val === "number" && Math.abs(val) >= 9007199254740992 && Math.abs(val) < 18446744073709551616 && Number.isInteger(val)) return BigInt(val).toString();
744
+ if (typeof val === "number" || typeof val === "bigint") return Object.is(val, -0) ? "-0" : String(val);
218
745
  if (typeof val === "string") return val;
219
746
  if (typeof val === "object") {
220
747
  if (val._d instanceof Date) {
221
748
  return typeof __timeFmt === "function" ? __timeFmt(val, "2006-01-02 15:04:05.999999999 -0700 MST") : String(val._d);
222
749
  }
223
750
  if ("re" in val && "im" in val) {
224
- const sign = val.im >= 0 ? "+" : "";
225
- return "(" + val.re + sign + val.im + "i)";
226
- }
227
- if (typeof val.Error === "function") {
228
- return String(val.Error());
751
+ const isNeg = val.im < 0 || Object.is(val.im, -0);
752
+ const sign = isNeg ? "" : "+";
753
+ const imStr = Object.is(val.im, -0) ? "-0" : String(val.im);
754
+ const reStr = Object.is(val.re, -0) ? "-0" : String(val.re);
755
+ return "(" + reStr + sign + imStr + "i)";
229
756
  }
757
+ const sm = ro ? (isRuntimeError(val) ? "Error" : "") : stringMethod(val, el);
758
+ if (sm) return String(callMethod(val, sm));
759
+ if (typeof val.__gfUnbox === "function") return formatV(val.__gfUnbox(), isPlus, isTopLevel, ro);
760
+ // fd is either a Stringer descriptor (see _fmtDesc) or, for operands that
761
+ // carry their static type, a type descriptor (fmt-types.js); sd is the
762
+ // latter with pointers and named types resolved.
763
+ const sd = td ? __fmtu.baseOf(td.k === "ptr" ? td.e : td) : null;
764
+ const cd = sdesc ?? val.__fd;
230
765
  if (Array.isArray(val) || ArrayBuffer.isView(val)) {
231
766
  const isElemPtr = val.__ptr_slice === true;
232
767
  const pf = val.__ptr_fields;
@@ -248,16 +783,33 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
248
783
  }
249
784
  }
250
785
  }
251
- parts.push(formatV(item, isPlus, false));
786
+ parts.push(formatV(item, isPlus, false, ro, both(sd?.e, cd?.e), cd?.e?.sv === 1));
252
787
  }
253
788
  return "[" + parts.join(" ") + "]";
254
789
  }
255
- if (val instanceof Map || val.__map === true) {
790
+ if (val instanceof Map || val.__map === true || sdesc?.m === 1) {
256
791
  const isElemPtr = val.__ptr_map === true;
257
792
  const parts = [];
258
793
  if (val instanceof Map) {
259
- const entries = Array.from(val.entries()).sort(([k1], [k2]) => {
794
+ // Keys of a type with String()/Error() sort by their raw value, as in Go.
795
+ const raw = (k) => (k !== null && typeof k === "object" && typeof k.__gfUnbox === "function" ? k.__gfUnbox() : k);
796
+ const entries = Array.from(val.entries()).sort(([a], [b]) => {
797
+ const k1 = raw(a), k2 = raw(b);
260
798
  if (typeof k1 === "number" && typeof k2 === "number") return k1 - k2;
799
+ // Struct and array keys compare field by field, as in Go.
800
+ if (k1 !== null && k2 !== null && typeof k1 === "object" && typeof k2 === "object" && !k1.__p && !k2.__p) {
801
+ const cmp = (x, y) => {
802
+ if (x !== null && y !== null && typeof x === "object" && typeof y === "object") {
803
+ for (const f of Object.keys(x)) {
804
+ const c = cmp(x[f], y[f]);
805
+ if (c !== 0) return c;
806
+ }
807
+ return 0;
808
+ }
809
+ return x < y ? -1 : x > y ? 1 : 0;
810
+ };
811
+ return cmp(k1, k2);
812
+ }
261
813
  const na = Number(k1), nb = Number(k2);
262
814
  if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;
263
815
  return String(k1).localeCompare(String(k2));
@@ -266,12 +818,26 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
266
818
  if (isElemPtr && v !== null && typeof v === "object") {
267
819
  markPtr(v);
268
820
  }
269
- parts.push(formatV(k, isPlus, false) + ":" + formatV(v, isPlus, false));
821
+ parts.push(formatV(k, isPlus, false, ro, both(sd?.key, cd?.k), cd?.k?.sv === 1) + ":" + formatV(v, isPlus, false, ro, both(sd?.val, cd?.v), cd?.v?.sv === 1));
270
822
  }
271
823
  } else {
272
824
  const keys = Object.keys(val).sort((a, b) => {
825
+ // Struct keys (encoded, see __sk) sort field by field, as in Go.
826
+ if (a.charCodeAt(0) === 1 && b.charCodeAt(0) === 1 && typeof __kd === "function")
827
+ return __kcmp(__kd(a), __kd(b));
273
828
  const na = Number(a), nb = Number(b);
274
829
  if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;
830
+ if (a[0] === "{" && b[0] === "{") {
831
+ // Struct keys (their %v text) sort field by field, as in Go.
832
+ const ta = a.slice(1, -1).split(/[ {}]+/), tb = b.slice(1, -1).split(/[ {}]+/);
833
+ for (let i = 0; i < ta.length && i < tb.length; i++) {
834
+ if (ta[i] === tb[i]) continue;
835
+ const x = Number(ta[i]), y = Number(tb[i]);
836
+ if (ta[i] !== "" && tb[i] !== "" && !Number.isNaN(x) && !Number.isNaN(y)) return x - y;
837
+ return ta[i].localeCompare(tb[i]);
838
+ }
839
+ return ta.length - tb.length;
840
+ }
275
841
  return a.localeCompare(b);
276
842
  });
277
843
  for (const k of keys) {
@@ -279,7 +845,8 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
279
845
  if (isElemPtr && v !== null && typeof v === "object") {
280
846
  markPtr(v);
281
847
  }
282
- parts.push(formatV(k, isPlus, false) + ":" + formatV(v, isPlus, false));
848
+ const kv = k.charCodeAt(0) === 1 && typeof __kd === "function" ? __kd(k) : ((sd && __fmtu.isNumKey(sd.key)) || cd?.k?.n) ? Number(k) : k;
849
+ parts.push(formatV(kv, isPlus, false, ro, both(sd?.key, cd?.k), cd?.k?.sv === 1) + ":" + formatV(v, isPlus, false, ro, both(sd?.val, cd?.v), cd?.v?.sv === 1));
283
850
  }
284
851
  }
285
852
  return "map[" + parts.join(" ") + "]";
@@ -287,7 +854,7 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
287
854
  if ("value" in val && (val.__box === true || (!val.__struct && !("__v" in val) && Object.keys(val).length === 1 && (val.constructor === Object || !val.constructor || val.constructor?.name === "Object")))) {
288
855
  return getPtr(val);
289
856
  }
290
- const isPtr = isPointer(val);
857
+ const isPtr = isPointer(val, el);
291
858
  if (isPtr) {
292
859
  if (!isTopLevel) {
293
860
  return getPtr(val);
@@ -295,77 +862,33 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
295
862
  getPtr(val);
296
863
  }
297
864
  const prefix = isPtr ? "&{" : "{";
298
- const keys = Object.keys(val);
865
+ const keys = __fmtu.keys(val);
299
866
  const parts = [];
867
+ const ff = typeof val.__ff === "function" ? val.__ff() : (sdesc?.ff ?? null);
300
868
  for (const k of keys) {
301
- const fv = formatV(val[k], isPlus, false);
869
+ const fk = both(sd?.f?.find((x) => x[0] === k)?.[1], ff?.[k]);
870
+ const fv = formatV(val[k], isPlus, false, ro || !isExported(k), fk, ff?.[k]?.sv === 1);
302
871
  parts.push(isPlus ? k + ":" + fv : fv);
303
872
  }
304
873
  return prefix + parts.join(" ") + "}";
305
874
  }
875
+ // A func value prints as an address; the targets share one fixed text.
876
+ if (typeof val === "function") return "0x1";
306
877
  return String(val);
307
878
  };
308
- return f.replace(/%([#+\\- 0]*)([0-9]*)\\.?([0-9]*)[sdvftxXqobeEgGwc%]/g, (m) => {
309
- if (m === "%%") return "%";
310
- const verb = m.slice(-1);
311
- const v = a[i++];
312
- const [, flags, width, prec] = m.match(/^%([#+\\- 0]*)([0-9]*)\\.?([0-9]*)/) || [];
313
- const zero = flags?.includes("0") && !flags?.includes("-");
314
- const pad = (s, w, z) => {
315
- w = parseInt(w) || 0;
316
- if (!w) return s;
317
- const p = (z ? "0" : " ").repeat(Math.max(0, w - s.length));
318
- return flags.includes("-") ? s + p : p + s;
319
- };
320
- switch (verb) {
321
- case "s": return pad(String(v == null ? "<nil>" : v), width, false);
322
- case "c": return pad(String.fromCodePoint(Number(v)), width, false);
323
- case "d": return pad(String(typeof v === "bigint" ? v : Math.trunc(Number(v))), width, zero);
324
- case "v": {
325
- const isPlus = flags?.includes("+") ?? false;
326
- return pad(formatV(v, isPlus, true), width, false);
327
- }
328
- case "f": { const n = Number(v), p = prec !== "" ? parseInt(prec) : 6; return pad(n.toFixed(p), width, zero); }
329
- case "t": return pad(String(!!v), width, false);
330
- case "x": {
331
- let hex;
332
- if (Array.isArray(v) || ArrayBuffer.isView(v)) {
333
- hex = Array.from(v).map((b) => (Number(b) & 0xff).toString(16).padStart(2, "0")).join("");
334
- } else if (typeof v === "string") {
335
- hex = Array.from(new TextEncoder().encode(v)).map((b) => b.toString(16).padStart(2, "0")).join("");
336
- } else if (typeof v === "bigint") {
337
- hex = BigInt.asUintN(64, v).toString(16);
338
- } else if (Math.abs(Number(v)) > 0xffffffff) {
339
- hex = (Math.trunc(Number(v) / 0x100000000) >>> 0).toString(16) + (Number(v) >>> 0).toString(16).padStart(8, "0");
340
- } else {
341
- hex = (Number(v) >>> 0).toString(16);
342
- }
343
- return pad(hex, width, zero);
344
- }
345
- case "X": {
346
- let hex;
347
- if (Array.isArray(v) || ArrayBuffer.isView(v)) {
348
- hex = Array.from(v).map((b) => (Number(b) & 0xff).toString(16).padStart(2, "0").toUpperCase()).join("");
349
- } else if (typeof v === "string") {
350
- hex = Array.from(new TextEncoder().encode(v)).map((b) => b.toString(16).padStart(2, "0").toUpperCase()).join("");
351
- } else if (typeof v === "bigint") {
352
- hex = BigInt.asUintN(64, v).toString(16).toUpperCase();
353
- } else if (Math.abs(Number(v)) > 0xffffffff) {
354
- hex = (Math.trunc(Number(v) / 0x100000000) >>> 0).toString(16).toUpperCase() + (Number(v) >>> 0).toString(16).padStart(8, "0").toUpperCase();
355
- } else {
356
- hex = (Number(v) >>> 0).toString(16).toUpperCase();
357
- }
358
- return pad(hex, width, zero);
359
- }
360
- case "o": return pad((typeof v === "bigint" ? BigInt.asUintN(64, v).toString(8) : (Number(v) >>> 0).toString(8)), width, zero);
361
- case "b": return pad((typeof v === "bigint" ? BigInt.asUintN(64, v).toString(2) : (Number(v) >>> 0).toString(2)), width, zero);
362
- case "q": return pad('"' + String(v == null ? "" : v).replace(/\\\\/g, "\\\\\\\\").replace(/"/g, '\\\\"') + '"', width, false);
363
- case "e": case "E": { const n = Number(v), p = prec !== "" ? parseInt(prec) : 6; return pad(n.toExponential(p), width, zero); }
364
- case "g": case "G": { const n = Number(v); return pad(prec !== "" ? n.toPrecision(parseInt(prec)) : String(n), width, zero); }
365
- case "w": return pad(String(v == null ? "<nil>" : typeof v === "object" && v.Error ? v.Error() : v), width, false);
366
- default: return m;
367
- }
368
- });
879
+ ` +
880
+ HELPER_FMT_LOOP;
881
+
882
+ // fmt.Sprint/Print/Append: a space goes between two operands when neither is a
883
+ // string; `ln` (Sprintln, Println, Appendln) separates always and ends with a newline.
884
+ export const HELPER_SPRINT = `var __sprint = __sprint || function(ln, ...a) {
885
+ const isStr = (x) => typeof x === "string" || (x !== null && typeof x === "object" && typeof x.__gfUnbox === "function" && typeof x.__gfUnbox() === "string");
886
+ let f = "";
887
+ for (let i = 0; i < a.length; i++) {
888
+ if (i > 0 && (ln || (!isStr(a[i - 1]) && !isStr(a[i])))) f += " ";
889
+ f += "%v";
890
+ }
891
+ return __sprintf(ln ? f + "\\n" : f, ...a);
369
892
  };`;
370
893
 
371
894
  export const HELPER_ERROR = `var __error = __error || function(msg, cause) {
@@ -379,9 +902,44 @@ export const HELPER_PATH_ERROR = `var __path_err_bad_pattern = __path_err_bad_pa
379
902
 
380
903
  export const HELPER_IO_EOF = `var __io_eof = __io_eof || __error("EOF");`;
381
904
 
905
+ export const HELPER_OS = `var __os_buf = "";
906
+ var __os_write = __os_write || function(s, isErr) {
907
+ if (typeof process !== "undefined" && process?.stdout?.write) {
908
+ process.stdout.write(s);
909
+ return [s.length, null];
910
+ }
911
+ __os_buf += s;
912
+ const nl = __os_buf.lastIndexOf(String.fromCharCode(10));
913
+ if (nl >= 0) {
914
+ const fn = (isErr && typeof console.error === "function") ? console.error : console.log;
915
+ fn(__os_buf.slice(0, nl));
916
+ __os_buf = __os_buf.slice(nl + 1);
917
+ }
918
+ return [s.length, null];
919
+ };
920
+ var __os_file = __os_file || class {
921
+ constructor(fd) { this.fd = fd; }
922
+ WriteString(s) { return __os_write(s, this.fd === 2); }
923
+ Write(b) {
924
+ const s = typeof b === "string" ? b : new TextDecoder().decode(b);
925
+ __os_write(s, this.fd === 2);
926
+ const n = typeof b === "string" ? s.length : (b?.byteLength ?? b?.length ?? s.length);
927
+ return [n, null];
928
+ }
929
+ Read(b) { return [0, typeof __io_eof !== "undefined" ? __io_eof : __error("EOF")]; }
930
+ Close() { return null; }
931
+ };
932
+ var __os_stdout = __os_stdout || new __os_file(1);
933
+ var __os_stderr = __os_stderr || new __os_file(2);
934
+ var __os_stdin = __os_stdin || new __os_file(0);
935
+ `;
936
+
382
937
  export const HELPER_ERROR_IS = `var __errorIs = __errorIs || function __errorIs(err, target) {
383
938
  if (err === null || err === undefined) return false;
384
939
  if (err === target) return true;
940
+ if (typeof err === "object" && typeof target === "object" && target !== null &&
941
+ typeof err.__gfUnbox === "function" && err.constructor === target.constructor &&
942
+ err.__gfUnbox() === target.__gfUnbox()) return true;
385
943
  if (typeof err === "object" && typeof target === "object" &&
386
944
  err._msg !== undefined && target._msg !== undefined &&
387
945
  err._msg === target._msg) return true;
@@ -407,7 +965,7 @@ export const HELPER_ERROR_IS = `var __errorIs = __errorIs || function __errorIs(
407
965
  return false;
408
966
  };`;
409
967
 
410
- export const HELPER_ERROR_AS = `var __errorAs = __errorAs || function(err, target, matcher) {
968
+ export const HELPER_ERROR_AS = `var __errorAs = __errorAs || function(err, target, matcher, extract) {
411
969
  if (err === null || err === undefined || target === null || typeof target !== "object") return false;
412
970
  let cur = err;
413
971
  while (cur !== null && cur !== undefined) {
@@ -415,7 +973,7 @@ export const HELPER_ERROR_AS = `var __errorAs = __errorAs || function(err, targe
415
973
  if (typeof cur.As === "function" && cur.As(target)) return true;
416
974
  if (matcher ? matcher(unboxed) : (unboxed !== err && typeof unboxed === "object" && !("_msg" in unboxed && "_cause" in unboxed))) {
417
975
  if ("value" in target) {
418
- target.value = unboxed;
976
+ target.value = extract ? extract(unboxed) : unboxed;
419
977
  } else {
420
978
  Object.assign(target, unboxed);
421
979
  }
@@ -423,17 +981,17 @@ export const HELPER_ERROR_AS = `var __errorAs = __errorAs || function(err, targe
423
981
  }
424
982
  if (Array.isArray(cur._errs)) {
425
983
  for (const sub of cur._errs) {
426
- if (__errorAs(sub, target, matcher)) return true;
984
+ if (__errorAs(sub, target, matcher, extract)) return true;
427
985
  }
428
986
  }
429
987
  if (typeof cur.Unwrap === "function") {
430
988
  const unwrapped = cur.Unwrap();
431
989
  if (Array.isArray(unwrapped)) {
432
990
  for (const sub of unwrapped) {
433
- if (__errorAs(sub, target, matcher)) return true;
991
+ if (__errorAs(sub, target, matcher, extract)) return true;
434
992
  }
435
993
  } else if (unwrapped !== null && unwrapped !== undefined) {
436
- if (__errorAs(unwrapped, target, matcher)) return true;
994
+ if (__errorAs(unwrapped, target, matcher, extract)) return true;
437
995
  }
438
996
  }
439
997
  cur = cur?._cause ?? null;
@@ -455,6 +1013,7 @@ export const HELPER_ERROR_JOIN = `var __errorJoin = __errorJoin || function(...e
455
1013
  const joined = __error(msg);
456
1014
  joined._errs = filtered;
457
1015
  joined.Unwrap = function() { return filtered; };
1016
+ joined.Unwrap.__multi = true;
458
1017
  return joined;
459
1018
  };`;
460
1019
 
@@ -652,28 +1211,78 @@ var __pathMatch = __pathMatch || function(pat, name) {
652
1211
  }
653
1212
  };`;
654
1213
 
655
- export const HELPER_TIME_FMT = `var __timeFmt = __timeFmt || function(d, layout) {
1214
+ export const HELPER_TIME_FMT = `var __timeLocalDt = __timeLocalDt || function(t) {
1215
+ const dt = t instanceof Date ? t : (t?._d ?? t);
1216
+ if (typeof t?._offset === "number") {
1217
+ return new Date(dt.getTime() + t._offset * 1000);
1218
+ }
1219
+ return null;
1220
+ };
1221
+ var __timeYear = __timeYear || function(t) {
1222
+ var ld = __timeLocalDt(t);
1223
+ return ld ? ld.getUTCFullYear() : (t instanceof Date ? t : t._d).getFullYear();
1224
+ };
1225
+ var __timeMonth = __timeMonth || function(t) {
1226
+ var ld = __timeLocalDt(t);
1227
+ return (ld ? ld.getUTCMonth() : (t instanceof Date ? t : t._d).getMonth()) + 1;
1228
+ };
1229
+ var __timeDay = __timeDay || function(t) {
1230
+ var ld = __timeLocalDt(t);
1231
+ return ld ? ld.getUTCDate() : (t instanceof Date ? t : t._d).getDate();
1232
+ };
1233
+ var __timeHour = __timeHour || function(t) {
1234
+ var ld = __timeLocalDt(t);
1235
+ return ld ? ld.getUTCHours() : (t instanceof Date ? t : t._d).getHours();
1236
+ };
1237
+ var __timeMinute = __timeMinute || function(t) {
1238
+ var ld = __timeLocalDt(t);
1239
+ return ld ? ld.getUTCMinutes() : (t instanceof Date ? t : t._d).getMinutes();
1240
+ };
1241
+ var __timeSecond = __timeSecond || function(t) {
1242
+ var ld = __timeLocalDt(t);
1243
+ return ld ? ld.getUTCSeconds() : (t instanceof Date ? t : t._d).getSeconds();
1244
+ };
1245
+ var __timeWeekday = __timeWeekday || function(t) {
1246
+ var ld = __timeLocalDt(t);
1247
+ return ld ? ld.getUTCDay() : (t instanceof Date ? t : t._d).getDay();
1248
+ };
1249
+ var __timeDate = __timeDate || function(t) {
1250
+ var ld = __timeLocalDt(t);
1251
+ var dt = t instanceof Date ? t : t._d;
1252
+ return ld ? [ld.getUTCFullYear(), ld.getUTCMonth() + 1, ld.getUTCDate()] : [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
1253
+ };
1254
+ var __timeClock = __timeClock || function(t) {
1255
+ var ld = __timeLocalDt(t);
1256
+ var dt = t instanceof Date ? t : t._d;
1257
+ return ld ? [ld.getUTCHours(), ld.getUTCMinutes(), ld.getUTCSeconds()] : [dt.getHours(), dt.getMinutes(), dt.getSeconds()];
1258
+ };
1259
+ var __timeFmt = __timeFmt || function(d, layout) {
656
1260
  const dt = d instanceof Date ? d : (d?._d ?? d);
657
- const isUtc = d?._offset === 0;
1261
+ const hasOff = typeof d?._offset === "number" || typeof d?._loc?._offset === "number";
1262
+ const offSec = typeof d?._offset === "number" ? d._offset : (d?._loc?._offset ?? 0);
1263
+ const localDt = hasOff ? new Date(dt.getTime() + offSec * 1000) : null;
658
1264
  const pad = (n, w = 2) => String(n).padStart(w, "0");
659
1265
  const DAYS = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
660
1266
  const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
661
- const getFullYear = () => isUtc ? dt.getUTCFullYear() : dt.getFullYear();
662
- const getMonth = () => isUtc ? dt.getUTCMonth() : dt.getMonth();
663
- const getDate = () => isUtc ? dt.getUTCDate() : dt.getDate();
664
- const getDay = () => isUtc ? dt.getUTCDay() : dt.getDay();
665
- const getHours = () => isUtc ? dt.getUTCHours() : dt.getHours();
666
- const getMinutes = () => isUtc ? dt.getUTCMinutes() : dt.getMinutes();
667
- const getSeconds = () => isUtc ? dt.getUTCSeconds() : dt.getSeconds();
668
- const getMilliseconds = () => isUtc ? dt.getUTCMilliseconds() : dt.getMilliseconds();
669
- const getTimezoneOffset = () => isUtc ? 0 : dt.getTimezoneOffset();
1267
+ const getFullYear = () => localDt ? localDt.getUTCFullYear() : dt.getFullYear();
1268
+ const getMonth = () => localDt ? localDt.getUTCMonth() : dt.getMonth();
1269
+ const getDate = () => localDt ? localDt.getUTCDate() : dt.getDate();
1270
+ const getDay = () => localDt ? localDt.getUTCDay() : dt.getDay();
1271
+ const getHours = () => localDt ? localDt.getUTCHours() : dt.getHours();
1272
+ const getMinutes = () => localDt ? localDt.getUTCMinutes() : dt.getMinutes();
1273
+ const getSeconds = () => localDt ? localDt.getUTCSeconds() : dt.getSeconds();
1274
+ const getMilliseconds = () => localDt ? localDt.getUTCMilliseconds() : dt.getMilliseconds();
1275
+ const getTimezoneOffset = () => hasOff ? Math.round(-offSec / 60) : dt.getTimezoneOffset();
670
1276
  return layout.replace(/2006|06|Monday|Mon|January|Jan|01|02|15|PM|pm|03|04|05|Z07:00|-07:00|-0700|MST|\\.(?:0+|9+)|1|2|3|4|5/g, t => {
671
1277
  if (t.startsWith(".")) {
672
1278
  const isZeroPad = t.includes("0");
673
1279
  const maxLen = t.length - 1;
674
1280
  const ms = getMilliseconds();
675
1281
  let frac = pad(ms, 3);
676
- if (maxLen > 3) frac = frac.padEnd(maxLen, "0");
1282
+ if (d?._ns) {
1283
+ frac += String(d._ns).padStart(6, "0");
1284
+ }
1285
+ if (maxLen > frac.length) frac = frac.padEnd(maxLen, "0");
677
1286
  else frac = frac.slice(0, maxLen);
678
1287
  if (!isZeroPad) {
679
1288
  frac = frac.replace(/0+$/, "");
@@ -714,17 +1323,199 @@ export const HELPER_TIME_FMT = `var __timeFmt = __timeFmt || function(d, layout)
714
1323
  const o = -getTimezoneOffset();
715
1324
  return (o >= 0 ? "+" : "-") + pad(Math.floor(Math.abs(o) / 60)) + pad(Math.abs(o) % 60);
716
1325
  }
717
- case "MST": return isUtc ? "UTC" : "LOCAL";
1326
+ case "MST": return d?._loc ? d._loc._name : (hasOff && offSec === 0 ? "UTC" : "LOCAL");
718
1327
  default: return t;
719
1328
  }
720
1329
  });
1330
+ };
1331
+ var __timeTruncate = __timeTruncate || function(t, d) {
1332
+ d = BigInt(d);
1333
+ if (d <= 0n) return t;
1334
+ var nano = BigInt(t._d.getTime()) * 1000000n + BigInt(t._ns || 0);
1335
+ var dt = nano + 62135596800000000000n;
1336
+ var r = dt % d;
1337
+ if (r < 0n) r += d;
1338
+ var newNano = nano - r;
1339
+ var newMs = Number(newNano / 1000000n);
1340
+ var remNs = Number(newNano % 1000000n);
1341
+ if (remNs < 0) { newMs--; remNs += 1000000; }
1342
+ return { _d: new Date(newMs), _offset: t._offset, _loc: t._loc, _ns: remNs };
1343
+ };
1344
+ var __timeRound = __timeRound || function(t, d) {
1345
+ d = BigInt(d);
1346
+ if (d <= 0n) return t;
1347
+ var nano = BigInt(t._d.getTime()) * 1000000n + BigInt(t._ns || 0);
1348
+ var dt = nano + 62135596800000000000n;
1349
+ var r = dt % d;
1350
+ if (r < 0n) r += d;
1351
+ var newNano = (r + r < d) ? (nano - r) : (nano + d - r);
1352
+ var newMs = Number(newNano / 1000000n);
1353
+ var remNs = Number(newNano % 1000000n);
1354
+ if (remNs < 0) { newMs--; remNs += 1000000; }
1355
+ return { _d: new Date(newMs), _offset: t._offset, _loc: t._loc, _ns: remNs };
1356
+ };
1357
+ var __timeAddDate = __timeAddDate || function(t, years, months, days) {
1358
+ var d = t._d;
1359
+ if (typeof t._offset === "number") {
1360
+ var offSec = t._offset;
1361
+ var localD = new Date(d.getTime() + offSec * 1000);
1362
+ var newLocalD = new Date(Date.UTC(
1363
+ localD.getUTCFullYear() + Number(years),
1364
+ localD.getUTCMonth() + Number(months),
1365
+ localD.getUTCDate() + Number(days),
1366
+ localD.getUTCHours(),
1367
+ localD.getUTCMinutes(),
1368
+ localD.getUTCSeconds(),
1369
+ localD.getUTCMilliseconds()
1370
+ ));
1371
+ var newDate = new Date(newLocalD.getTime() - offSec * 1000);
1372
+ return { _d: newDate, _offset: t._offset, _loc: t._loc, _ns: t._ns };
1373
+ }
1374
+ var newDate = new Date(
1375
+ d.getFullYear() + Number(years),
1376
+ d.getMonth() + Number(months),
1377
+ d.getDate() + Number(days),
1378
+ d.getHours(),
1379
+ d.getMinutes(),
1380
+ d.getSeconds(),
1381
+ d.getMilliseconds()
1382
+ );
1383
+ return { _d: newDate, _offset: t._offset, _loc: t._loc, _ns: t._ns };
1384
+ };
1385
+ var __timeYearDay = __timeYearDay || function(t) {
1386
+ var d = t._d;
1387
+ if (typeof t._offset === "number") {
1388
+ var localD = new Date(d.getTime() + t._offset * 1000);
1389
+ var start = new Date(Date.UTC(localD.getUTCFullYear(), 0, 0));
1390
+ return Math.floor((localD.getTime() - start.getTime()) / 86400000);
1391
+ }
1392
+ var start = new Date(d.getFullYear(), 0, 0);
1393
+ return Math.floor((d.getTime() - start.getTime()) / 86400000);
1394
+ };
1395
+ var __timeISOWeek = __timeISOWeek || function(t) {
1396
+ if (typeof t._offset === "number") {
1397
+ var d = new Date(t._d.getTime() + t._offset * 1000);
1398
+ var day = (d.getUTCDay() + 6) % 7;
1399
+ d.setUTCDate(d.getUTCDate() - day + 3);
1400
+ var year = d.getUTCFullYear();
1401
+ var firstThu = new Date(Date.UTC(year, 0, 4));
1402
+ var firstDay = (firstThu.getUTCDay() + 6) % 7;
1403
+ firstThu.setUTCDate(firstThu.getUTCDate() - firstDay + 3);
1404
+ var week = 1 + Math.round((d.getTime() - firstThu.getTime()) / 604800000);
1405
+ return [year, week];
1406
+ }
1407
+ var d = new Date(t._d.getTime());
1408
+ var day = (d.getDay() + 6) % 7;
1409
+ d.setDate(d.getDate() - day + 3);
1410
+ var year = d.getFullYear();
1411
+ var firstThu = new Date(year, 0, 4);
1412
+ var firstDay = (firstThu.getDay() + 6) % 7;
1413
+ firstThu.setDate(firstThu.getDate() - firstDay + 3);
1414
+ var week = 1 + Math.round((d.getTime() - firstThu.getTime()) / 604800000);
1415
+ return [year, week];
1416
+ };
1417
+ var __timeMarshalJSON = __timeMarshalJSON || function(t) {
1418
+ var y = (typeof t._offset === "number") ? new Date(t._d.getTime() + t._offset * 1000).getUTCFullYear() : t._d.getFullYear();
1419
+ if (y < 0 || y > 9999) {
1420
+ return [new Uint8Array(0), typeof __error === "function" ? __error("Time.MarshalJSON: year outside of range [0,9999]") : new Error("Time.MarshalJSON: year outside of range [0,9999]")];
1421
+ }
1422
+ var s = '"' + __timeFmt(t, "2006-01-02T15:04:05.999999999Z07:00") + '"';
1423
+ return [new TextEncoder().encode(s), null];
1424
+ };
1425
+ var __timeMarshalText = __timeMarshalText || function(t) {
1426
+ var y = (typeof t._offset === "number") ? new Date(t._d.getTime() + t._offset * 1000).getUTCFullYear() : t._d.getFullYear();
1427
+ if (y < 0 || y > 9999) {
1428
+ return [new Uint8Array(0), typeof __error === "function" ? __error("Time.MarshalText: year outside of range [0,9999]") : new Error("Time.MarshalText: year outside of range [0,9999]")];
1429
+ }
1430
+ var s = __timeFmt(t, "2006-01-02T15:04:05.999999999Z07:00");
1431
+ return [new TextEncoder().encode(s), null];
1432
+ };
1433
+ var __timeUnmarshalJSON = __timeUnmarshalJSON || function(t, data) {
1434
+ var s = typeof data === "string" ? data : new TextDecoder().decode(data);
1435
+ s = s.trim();
1436
+ if (s === "null") return null;
1437
+ if (!s.startsWith('"') || !s.endsWith('"') || s.length < 2) {
1438
+ return typeof __error === "function" ? __error("Time.UnmarshalJSON: input is not a JSON string") : new Error("Time.UnmarshalJSON: input is not a JSON string");
1439
+ }
1440
+ var inner = s.slice(1, -1);
1441
+ var parsed = __timeParse("2006-01-02T15:04:05.999999999Z07:00", inner);
1442
+ if (parsed[1]) parsed = __timeParse("2006-01-02T15:04:05Z07:00", inner);
1443
+ if (parsed[1]) return parsed[1];
1444
+ t._d = parsed[0]._d;
1445
+ t._offset = parsed[0]._offset;
1446
+ t._loc = parsed[0]._loc;
1447
+ t._ns = parsed[0]._ns;
1448
+ return null;
1449
+ };
1450
+ var __timeUnmarshalText = __timeUnmarshalText || function(t, data) {
1451
+ var s = typeof data === "string" ? data : new TextDecoder().decode(data);
1452
+ s = s.trim();
1453
+ var parsed = __timeParse("2006-01-02T15:04:05.999999999Z07:00", s);
1454
+ if (parsed[1]) parsed = __timeParse("2006-01-02T15:04:05Z07:00", s);
1455
+ if (parsed[1]) return parsed[1];
1456
+ t._d = parsed[0]._d;
1457
+ t._offset = parsed[0]._offset;
1458
+ t._loc = parsed[0]._loc;
1459
+ t._ns = parsed[0]._ns;
1460
+ return null;
1461
+ };
1462
+ var __timeAfterFunc = __timeAfterFunc || function(d, f) {
1463
+ var timer = {
1464
+ _id: null,
1465
+ _active: true,
1466
+ _f: f,
1467
+ Stop: function() {
1468
+ var act = this._active;
1469
+ if (act) {
1470
+ clearTimeout(this._id);
1471
+ this._active = false;
1472
+ }
1473
+ return act;
1474
+ },
1475
+ Reset: function(newD) {
1476
+ var act = this._active;
1477
+ if (act) clearTimeout(this._id);
1478
+ var self = this;
1479
+ this._active = true;
1480
+ this._id = setTimeout(function() {
1481
+ self._active = false;
1482
+ self._f();
1483
+ }, Math.round(Number(newD) / 1000000));
1484
+ return act;
1485
+ }
1486
+ };
1487
+ timer._id = setTimeout(function() {
1488
+ timer._active = false;
1489
+ timer._f();
1490
+ }, Math.round(Number(d) / 1000000));
1491
+ return timer;
721
1492
  };`;
722
1493
 
723
1494
  export const HELPER_TIME_PARSE = `var __timeParse = __timeParse || function(layout, value) {
724
1495
  try {
725
- const d = new Date(value);
1496
+ const val = String(value);
1497
+ const d = new Date(val);
726
1498
  if (isNaN(d.getTime())) throw 0;
727
- return [{ _d: d }, null];
1499
+ let offset = undefined;
1500
+ let loc = null;
1501
+ let ns = 0;
1502
+ const m = /\\.(\\d{1,9})/.exec(val);
1503
+ if (m) {
1504
+ const fracStr = m[1].padEnd(9, "0");
1505
+ ns = Number(fracStr.slice(3));
1506
+ }
1507
+ if (val.endsWith("Z") || val.endsWith("z")) {
1508
+ offset = 0;
1509
+ } else {
1510
+ const tzMatch = /([+-])(\\d{2}):?(\\d{2})$/.exec(val);
1511
+ if (tzMatch) {
1512
+ const sign = tzMatch[1] === "+" ? 1 : -1;
1513
+ const offSec = sign * (Number(tzMatch[2]) * 3600 + Number(tzMatch[3]) * 60);
1514
+ offset = offSec;
1515
+ loc = { _name: tzMatch[0], _offset: offSec, String() { return this._name; } };
1516
+ }
1517
+ }
1518
+ return [{ _d: d, _offset: offset, _loc: loc, _ns: ns }, null];
728
1519
  } catch {
729
1520
  return [{ _d: new Date(0) }, { Error() { return "parsing time: cannot parse"; }, toString() { return "parsing time: cannot parse"; }, _msg: "parsing time: cannot parse", _cause: null }];
730
1521
  }
@@ -743,6 +1534,7 @@ var __GoFront_T = __GoFront_T || class {
743
1534
  this.failed = false;
744
1535
  this.skipped = false;
745
1536
  this._logs = [];
1537
+ this._cleanups = [];
746
1538
  this._start = typeof performance !== "undefined" ? performance.now() : Date.now();
747
1539
  }
748
1540
  Name() { return this._name; }
@@ -795,15 +1587,71 @@ var __GoFront_T = __GoFront_T || class {
795
1587
  throw new __GoFront_SkipNow();
796
1588
  }
797
1589
  Skipped() { return this.skipped; }
1590
+ SkipNow() {
1591
+ this.skipped = true;
1592
+ throw new __GoFront_SkipNow();
1593
+ }
798
1594
  Helper() {}
1595
+ Parallel() {}
1596
+ Attr(k, v) {}
1597
+ Output() {
1598
+ return {
1599
+ Write(p) {
1600
+ process.stdout.write(typeof p === "string" ? p : Buffer.from(p));
1601
+ return [p.length, null];
1602
+ }
1603
+ };
1604
+ }
1605
+ Deadline() {
1606
+ return [null, false];
1607
+ }
1608
+ Context() {
1609
+ if (!this._ctx) {
1610
+ let canceled = false;
1611
+ this._ctx = {
1612
+ Deadline() { return [null, false]; },
1613
+ Done() { return null; },
1614
+ Err() { return canceled ? new Error("context canceled") : null; },
1615
+ Value(k) { return null; },
1616
+ };
1617
+ this.Cleanup(() => { canceled = true; });
1618
+ }
1619
+ return this._ctx;
1620
+ }
1621
+ Setenv(key, val) {
1622
+ const prev = process.env[key];
1623
+ const hasPrev = Object.prototype.hasOwnProperty.call(process.env, key);
1624
+ process.env[key] = String(val);
1625
+ this.Cleanup(() => {
1626
+ if (hasPrev) process.env[key] = prev;
1627
+ else delete process.env[key];
1628
+ });
1629
+ }
1630
+ Cleanup(fn) {
1631
+ this._cleanups.push(fn);
1632
+ }
1633
+ _runCleanups() {
1634
+ while (this._cleanups.length > 0) {
1635
+ const fn = this._cleanups.pop();
1636
+ try {
1637
+ fn();
1638
+ } catch (e) {
1639
+ this.Fail();
1640
+ this.Log("panic in cleanup: " + (e?.message ?? String(e)));
1641
+ }
1642
+ }
1643
+ }
799
1644
  Run(name, fn) {
800
1645
  const subName = this._name ? \`\${this._name}/\${name}\` : name;
801
- const subT = new __GoFront_T(subName, this);
1646
+ const subT = new this.constructor(subName, this);
802
1647
  if (typeof globalThis.__onSubtestStart === "function") globalThis.__onSubtestStart(subName);
1648
+ let isAsync = false;
803
1649
  try {
804
1650
  const res = fn(subT);
805
1651
  if (res && typeof res.then === "function") {
1652
+ isAsync = true;
806
1653
  return res.then(() => {
1654
+ subT._runCleanups();
807
1655
  if (typeof globalThis.__onSubtestEnd === "function") globalThis.__onSubtestEnd(subT);
808
1656
  return !subT.failed;
809
1657
  }).catch(e => {
@@ -815,6 +1663,7 @@ var __GoFront_T = __GoFront_T || class {
815
1663
  subT.Fail();
816
1664
  subT.Log("panic: " + (e?.message ?? String(e)));
817
1665
  }
1666
+ subT._runCleanups();
818
1667
  if (typeof globalThis.__onSubtestEnd === "function") globalThis.__onSubtestEnd(subT);
819
1668
  return false;
820
1669
  });
@@ -828,12 +1677,157 @@ var __GoFront_T = __GoFront_T || class {
828
1677
  subT.Fail();
829
1678
  subT.Log("panic: " + (e?.message ?? String(e)));
830
1679
  }
1680
+ } finally {
1681
+ if (!isAsync) {
1682
+ subT._runCleanups();
1683
+ }
831
1684
  }
832
1685
  if (typeof globalThis.__onSubtestEnd === "function") globalThis.__onSubtestEnd(subT);
833
1686
  return !subT.failed;
834
1687
  }
835
1688
  };
836
- var __testing_T = __GoFront_T;`;
1689
+ var __testing_T = __GoFront_T;
1690
+ var __GoFront_B = __GoFront_B || class extends __GoFront_T {
1691
+ constructor(name = "", parent = null) {
1692
+ super(name, parent);
1693
+ this.N = 1;
1694
+ this._bytes = 0n;
1695
+ this._reportAllocs = false;
1696
+ this._timerStart = typeof performance !== "undefined" ? performance.now() : Date.now();
1697
+ this._elapsedMs = 0;
1698
+ this._timerRunning = true;
1699
+ this._loopStarted = false;
1700
+ }
1701
+ ResetTimer() {
1702
+ this._timerStart = typeof performance !== "undefined" ? performance.now() : Date.now();
1703
+ this._elapsedMs = 0;
1704
+ }
1705
+ StartTimer() {
1706
+ if (!this._timerRunning) {
1707
+ this._timerStart = typeof performance !== "undefined" ? performance.now() : Date.now();
1708
+ this._timerRunning = true;
1709
+ }
1710
+ }
1711
+ StopTimer() {
1712
+ if (this._timerRunning) {
1713
+ const now = typeof performance !== "undefined" ? performance.now() : Date.now();
1714
+ this._elapsedMs += now - this._timerStart;
1715
+ this._timerRunning = false;
1716
+ }
1717
+ }
1718
+ ReportAllocs() {
1719
+ this._reportAllocs = true;
1720
+ }
1721
+ ReportMetric(n, unit) {}
1722
+ SetBytes(n) {
1723
+ this._bytes = BigInt(n);
1724
+ }
1725
+ Elapsed() {
1726
+ const ms = this._timerRunning
1727
+ ? this._elapsedMs + ((typeof performance !== "undefined" ? performance.now() : Date.now()) - this._timerStart)
1728
+ : this._elapsedMs;
1729
+ return BigInt(Math.round(ms * 1e6));
1730
+ }
1731
+ Loop() {
1732
+ if (!this._loopStarted) {
1733
+ this._loopStarted = true;
1734
+ this.ResetTimer();
1735
+ this._loopTargetNs = this._benchDurationNs || 1e9;
1736
+ this._loopIters = 0;
1737
+ this._nextCheck = 1;
1738
+ }
1739
+ if (this.failed || this.skipped) return false;
1740
+ this._loopIters++;
1741
+ this.N = this._loopIters;
1742
+ if (this._loopIters >= this._nextCheck) {
1743
+ const now = typeof performance !== "undefined" ? performance.now() : Date.now();
1744
+ const elapsedNs = (now - this._timerStart) * 1e6;
1745
+ if (elapsedNs >= this._loopTargetNs || this._loopIters >= 1e9) {
1746
+ this.StopTimer();
1747
+ return false;
1748
+ }
1749
+ const nsPerOp = Math.max(1, elapsedNs / this._loopIters);
1750
+ const remainingNs = this._loopTargetNs - elapsedNs;
1751
+ const addIters = Math.max(1, Math.min(100000, Math.floor(remainingNs / (nsPerOp * 2))));
1752
+ this._nextCheck = this._loopIters + addIters;
1753
+ }
1754
+ return true;
1755
+ }
1756
+ };
1757
+ var __testing_B = __GoFront_B;
1758
+ var __GoFront_M = __GoFront_M || class {
1759
+ constructor(runFn) {
1760
+ this._run = runFn;
1761
+ this._ran = false;
1762
+ this._exitCode = 0;
1763
+ }
1764
+ Run() {
1765
+ this._ran = true;
1766
+ const res = this._run();
1767
+ if (res && typeof res.then === "function") {
1768
+ this._promise = res.then(code => { this._exitCode = code; return code; });
1769
+ return 0;
1770
+ }
1771
+ this._exitCode = res ?? 0;
1772
+ return this._exitCode;
1773
+ }
1774
+ };
1775
+ var __testing_M = __GoFront_M;
1776
+ var __GoFront_BenchmarkResult = __GoFront_BenchmarkResult || class {
1777
+ constructor(b = null) {
1778
+ this.N = b?.N ?? 0;
1779
+ this.T = b ? b.Elapsed() : 0n;
1780
+ this.Bytes = b?._bytes ?? 0n;
1781
+ this.MemAllocs = 0n;
1782
+ this.MemBytes = 0n;
1783
+ this.Extra = new Map();
1784
+ }
1785
+ AllocedBytesPerOp() { return this.N > 0 ? this.MemBytes / BigInt(this.N) : 0n; }
1786
+ AllocsPerOp() { return this.N > 0 ? this.MemAllocs / BigInt(this.N) : 0n; }
1787
+ MemString() { return \`\${this.AllocedBytesPerOp()} B/op\\t\${this.AllocsPerOp()} allocs/op\`; }
1788
+ NsPerOp() { return this.N > 0 ? this.T / BigInt(this.N) : 0n; }
1789
+ String() {
1790
+ const ns = this.NsPerOp();
1791
+ let s = \`\${this.N}\\t\${ns} ns/op\`;
1792
+ if (this.Bytes > 0n && this.T > 0n) {
1793
+ const mbPerSec = (Number(this.Bytes * BigInt(this.N)) / (Number(this.T) / 1e9) / (1024 * 1024)).toFixed(2);
1794
+ s += \`\\t\${mbPerSec} MB/s\`;
1795
+ }
1796
+ return s;
1797
+ }
1798
+ };
1799
+ var __testing_BenchmarkResult = __GoFront_BenchmarkResult;
1800
+ var __testing_Benchmark = __testing_Benchmark || function(fn) {
1801
+ let b = new __GoFront_B("Benchmark");
1802
+ b._benchDurationNs = 1e9;
1803
+ b.N = 1;
1804
+ b.ResetTimer();
1805
+ fn(b);
1806
+ if (!b._loopStarted) {
1807
+ b.StopTimer();
1808
+ b._runCleanups();
1809
+ let n = 1;
1810
+ while (!b.failed && !b.skipped) {
1811
+ const elapsedNs = Number(b.Elapsed());
1812
+ if (elapsedNs >= 1e9 || n >= 1e9) break;
1813
+ let nextN;
1814
+ if (elapsedNs === 0) nextN = n * 100;
1815
+ else nextN = Math.max(n + 1, Math.min(1e9, Math.floor(n * (1e9 / elapsedNs) * 1.2)));
1816
+ if (nextN <= n) break;
1817
+ n = nextN;
1818
+ b = new __GoFront_B("Benchmark");
1819
+ b._benchDurationNs = 1e9;
1820
+ b.N = n;
1821
+ b.ResetTimer();
1822
+ fn(b);
1823
+ b.StopTimer();
1824
+ b._runCleanups();
1825
+ }
1826
+ } else {
1827
+ b._runCleanups();
1828
+ }
1829
+ return new __GoFront_BenchmarkResult(b);
1830
+ };`;
837
1831
 
838
1832
  export const HELPER_INJECT_STYLES = `var __injectStyles = __injectStyles || function(css) {
839
1833
  if (typeof document === "undefined" || !document || !document.head || !css) return;
@@ -893,6 +1887,73 @@ export const HELPER_DURATION = `var __durationString = __durationString || funct
893
1887
  }
894
1888
  }
895
1889
  return neg ? "-" + s : s;
1890
+ };
1891
+ var __durationRound = __durationRound || function(d, m) {
1892
+ d = BigInt(d);
1893
+ m = BigInt(m);
1894
+ if (m <= 0n) return Number(d);
1895
+ var r = d % m;
1896
+ if (d < 0n) {
1897
+ r = -r;
1898
+ if (r + r < m) return Number(d + r);
1899
+ return Number(d - m + r);
1900
+ }
1901
+ if (r + r < m) return Number(d - r);
1902
+ return Number(d + m - r);
1903
+ };
1904
+ var __monthString = __monthString || function(m) {
1905
+ var names = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
1906
+ var n = Number(m);
1907
+ if (n >= 1 && n <= 12) return names[n];
1908
+ return "%!Month(" + n + ")";
1909
+ };
1910
+ var __weekdayString = __weekdayString || function(w) {
1911
+ var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
1912
+ var n = Number(w);
1913
+ if (n >= 0 && n <= 6) return names[n];
1914
+ return "%!Weekday(" + n + ")";
1915
+ };
1916
+ var __timeParseDuration = __timeParseDuration || function(s) {
1917
+ var orig = String(s);
1918
+ if (orig === "0") return [0, null];
1919
+ var str = orig.trim();
1920
+ var neg = false;
1921
+ if (str.startsWith("-")) { neg = true; str = str.slice(1); }
1922
+ else if (str.startsWith("+")) { str = str.slice(1); }
1923
+ if (str === "0") return [0, null];
1924
+ if (str === "") return [0, typeof __error === "function" ? __error('time: invalid duration ""') : new Error('time: invalid duration ""')];
1925
+
1926
+ var totalNs = 0n;
1927
+ var re = /^(\\d*(?:\\.\\d+)?)(ns|us|µs|\\u00b5s|\\u03bcs|ms|s|m|h)/;
1928
+ while (str.length > 0) {
1929
+ var m = re.exec(str);
1930
+ if (!m || m[1] === "" || m[1] === ".") {
1931
+ return [0, typeof __error === "function" ? __error('time: invalid duration "' + orig + '"') : new Error('time: invalid duration "' + orig + '"')];
1932
+ }
1933
+ var numStr = m[1];
1934
+ var unitStr = m[2];
1935
+ var unitMult = 1n;
1936
+ if (unitStr === "ns") unitMult = 1n;
1937
+ else if (unitStr === "us" || unitStr === "µs" || unitStr === "\\u00b5s" || unitStr === "\\u03bcs") unitMult = 1000n;
1938
+ else if (unitStr === "ms") unitMult = 1000000n;
1939
+ else if (unitStr === "s") unitMult = 1000000000n;
1940
+ else if (unitStr === "m") unitMult = 60000000000n;
1941
+ else if (unitStr === "h") unitMult = 3600000000000n;
1942
+
1943
+ if (numStr.includes(".")) {
1944
+ var parts = numStr.split(".");
1945
+ var whole = parts[0] ? BigInt(parts[0]) : 0n;
1946
+ var frac = parts[1];
1947
+ var fracScale = Math.pow(10, frac.length);
1948
+ var fracVal = BigInt(Math.round((Number(frac) / fracScale) * Number(unitMult)));
1949
+ totalNs += whole * unitMult + fracVal;
1950
+ } else {
1951
+ totalNs += BigInt(numStr) * unitMult;
1952
+ }
1953
+ str = str.slice(m[0].length);
1954
+ }
1955
+ if (neg) totalNs = -totalNs;
1956
+ return [Number(totalNs), null];
896
1957
  };`;
897
1958
 
898
1959
  export const HELPER_SYNC = `var __sync_mutex = __sync_mutex || function() {
@@ -1325,3 +2386,833 @@ var __base64_std = __base64_std || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcd
1325
2386
  var __base64_url = __base64_url || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", "=");
1326
2387
  var __base64_raw_std = __base64_raw_std || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "");
1327
2388
  var __base64_raw_url = __base64_raw_url || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", "");`;
2389
+
2390
+ export const HELPER_JSON = `var __json_esc = __json_esc || function(s) {
2391
+ if (typeof s !== "string") s = String(s);
2392
+ var out = JSON.stringify(s);
2393
+ var escHtml = typeof OptEscapeHTML$$internal$jsonrt === "undefined" || OptEscapeHTML$$internal$jsonrt;
2394
+ if (escHtml) {
2395
+ out = out
2396
+ .replace(/[<>&]/g, function(c) {
2397
+ return c === "<" ? "\\\\u003c" : (c === ">" ? "\\\\u003e" : "\\\\u0026");
2398
+ })
2399
+ .replace(/\\u2028/g, "\\\\u2028")
2400
+ .replace(/\\u2029/g, "\\\\u2029");
2401
+ }
2402
+ return out;
2403
+ };
2404
+ var __json_check_unknown = __json_check_unknown || function(parsed, knownKeys) {
2405
+ var disallow = typeof OptDisallowUnknownFields$$internal$jsonrt !== "undefined" && OptDisallowUnknownFields$$internal$jsonrt;
2406
+ if (!disallow || !parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
2407
+ var lowerSet = new Set(knownKeys.map(function(k) { return k.toLowerCase(); }));
2408
+ for (var k in parsed) {
2409
+ if (Object.prototype.hasOwnProperty.call(parsed, k) && !k.startsWith("__")) {
2410
+ if (!lowerSet.has(k.toLowerCase())) {
2411
+ var msg = "json: unknown field " + JSON.stringify(k);
2412
+ return typeof __error === "function" ? __error(msg) : new Error(msg);
2413
+ }
2414
+ }
2415
+ }
2416
+ return null;
2417
+ };
2418
+ var __json_err = __json_err || function(msg, valKind, targetType) {
2419
+ var fullMsg = "json: " + msg;
2420
+ var valDesc = valKind || "";
2421
+ var typeDesc = targetType || "";
2422
+ if (!valDesc && msg.startsWith("cannot unmarshal ")) {
2423
+ var parts = msg.slice(17).split(" into ");
2424
+ valDesc = parts[0];
2425
+ var rest = parts[1] || "";
2426
+ var idx = rest.indexOf(" of type ");
2427
+ if (idx >= 0) typeDesc = rest.slice(idx + 9);
2428
+ else if (rest.startsWith("Go value of type ")) typeDesc = rest.slice(17);
2429
+ }
2430
+ var structName = __json_structs.length > 0 ? __json_structs[__json_structs.length - 1] : "";
2431
+ var fieldPath = __json_path.join(".");
2432
+ var offset = typeof __json_current_offset === "number" ? __json_current_offset : 0;
2433
+ var e;
2434
+ if (typeof UnmarshalTypeError$$internal$jsonrt === "function") {
2435
+ e = new UnmarshalTypeError$$internal$jsonrt(valDesc, typeDesc, BigInt(offset), structName, fieldPath);
2436
+ if (e.__p !== true && Object.isExtensible(e)) Object.defineProperty(e, "__p", { value: true, configurable: true, writable: true });
2437
+ } else {
2438
+ e = typeof __error === "function" ? __error(fullMsg) : new Error(fullMsg);
2439
+ e.Value = valDesc;
2440
+ e.Type = typeDesc;
2441
+ e.Offset = BigInt(offset);
2442
+ e.Struct = structName;
2443
+ e.Field = fieldPath;
2444
+ if (e.__p !== true && Object.isExtensible(e)) Object.defineProperty(e, "__p", { value: true, configurable: true, writable: true });
2445
+ }
2446
+ e.Error = function() { return fullMsg; };
2447
+ e._msg = fullMsg;
2448
+ e.__struct = "UnmarshalTypeError$$internal$jsonrt";
2449
+ return e;
2450
+ };
2451
+ // Decode error context, as in Go: innermost struct being decoded plus the path
2452
+ // of JSON field names from the root. Reset by every __json_unmarshal call.
2453
+ var __json_structs = __json_structs || [];
2454
+ var __json_path = __json_path || [];
2455
+ var __json_current_offset = __json_current_offset || 0;
2456
+ var __json_ctx = __json_ctx || function(typeName) {
2457
+ if (__json_path.length > 0 && __json_structs.length > 0) {
2458
+ return "Go struct field " + __json_structs[__json_structs.length - 1] + "." + __json_path.join(".") + " of type " + typeName;
2459
+ }
2460
+ return "Go value of type " + typeName;
2461
+ };
2462
+ // The JSON source text of a number, for "cannot unmarshal number <literal>" messages.
2463
+ var __json_lit = __json_lit || function(v, raw) {
2464
+ if (raw !== undefined && raw !== null) return String(raw).trim();
2465
+ return typeof v === "string" ? v.replace(/__bigint$/, "") : String(v);
2466
+ };
2467
+ var __json_is_valid_number = __json_is_valid_number || function(s) {
2468
+ return typeof s === "string" && /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(s);
2469
+ };
2470
+ var __json_enc_number = __json_enc_number || function(v) {
2471
+ var s = typeof v === "string" ? v : (v != null ? String(v) : "");
2472
+ if (s === "") return "0";
2473
+ if (!__json_is_valid_number(s)) {
2474
+ throw new Error("json: invalid number literal " + JSON.stringify(s));
2475
+ }
2476
+ return s;
2477
+ };
2478
+ var __json_number_decode = __json_number_decode || function(v, ctxType, raw) {
2479
+ if (typeof v === "number" || (typeof v === "string" && v.endsWith("__bigint"))) {
2480
+ return __json_lit(v, raw);
2481
+ }
2482
+ if (typeof v === "string") {
2483
+ if (!__json_is_valid_number(v)) {
2484
+ return __json_err("invalid number literal, trying to unmarshal " + JSON.stringify(v) + " into Number");
2485
+ }
2486
+ return v;
2487
+ }
2488
+ return __json_err("cannot unmarshal " + __json_type(v) + " into " + __json_ctx(ctxType));
2489
+ };
2490
+ var __json_dec_number = __json_dec_number || function(parsed, target, box, rawData, rawStr) {
2491
+ if (parsed === null) return null;
2492
+ var nv = __json_number_decode(parsed, "json.Number", rawStr);
2493
+ if (nv && nv._msg) return nv;
2494
+ if (box) box.value = nv;
2495
+ return null;
2496
+ };
2497
+ var __json_float_decode = __json_float_decode || function(v, bits, ctxType, raw) {
2498
+ var n = __json_number_value(v);
2499
+ if (typeof n !== "number") return __json_err("cannot unmarshal " + __json_type(v) + " into " + __json_ctx(ctxType));
2500
+ var f = bits === 32 ? Math.fround(n) : n;
2501
+ if (!isFinite(f)) return __json_err("cannot unmarshal number " + __json_lit(v, raw) + " into " + __json_ctx(ctxType));
2502
+ return f;
2503
+ };
2504
+ // []byte accepts a base64 string or (like Go) an array of uint8 values.
2505
+ var __json_bytes_decode = __json_bytes_decode || function(v) {
2506
+ if (Array.isArray(v)) {
2507
+ var u8 = new Uint8Array(v.length);
2508
+ for (var i = 0; i < v.length; i++) {
2509
+ var b = __json_int_decode(v[i], "uint8", "uint8", __json_raw_child(v, i));
2510
+ if (b && b._msg) return b;
2511
+ u8[i] = b;
2512
+ }
2513
+ return u8;
2514
+ }
2515
+ if (typeof v !== "string") return __json_err("cannot unmarshal " + __json_type(v) + " into " + __json_ctx("[]uint8"));
2516
+ return __json_b64_dec(v);
2517
+ };
2518
+ var __json_esc_noh = __json_esc_noh || function(s) {
2519
+ return JSON.stringify(String(s)).replace(/\\u2028/g, "\\\\u2028").replace(/\\u2029/g, "\\\\u2029");
2520
+ };
2521
+ var __json_syntax_msg = __json_syntax_msg || function(s) {
2522
+ if (typeof CheckValid$$internal$jsonrt === "function") {
2523
+ var se = CheckValid$$internal$jsonrt(new TextEncoder().encode(String(s)));
2524
+ if (se && typeof se.Error === "function") return se.Error();
2525
+ }
2526
+ var t = String(s).trim();
2527
+ if (t === "") return "unexpected end of JSON input";
2528
+ var m;
2529
+ try { JSON.parse(t); } catch (e) { m = String(e && e.message); }
2530
+ if (m && /end of JSON input|Unterminated/.test(m)) return "unexpected end of JSON input";
2531
+ var pos = m && /after JSON at position (\\d+)/.exec(m);
2532
+ if (pos) return "invalid character '" + t[Number(pos[1])] + "' after top-level value";
2533
+ if ("{[\\"-0123456789tfn".indexOf(t[0]) < 0) return "invalid character '" + t[0] + "' looking for beginning of value";
2534
+ return "invalid character in JSON value";
2535
+ };
2536
+ // Validates and compacts JSON text, escaping <, >, & and U+2028/U+2029 inside strings.
2537
+ var __json_compact = __json_compact || function(s) {
2538
+ try { JSON.parse(s); } catch (e) { return null; }
2539
+ var out = "", inStr = false, esc = false;
2540
+ var escHtml = typeof OptEscapeHTML$$internal$jsonrt === "undefined" || OptEscapeHTML$$internal$jsonrt;
2541
+ for (var i = 0; i < s.length; i++) {
2542
+ var c = s[i];
2543
+ if (inStr) {
2544
+ if (esc) { esc = false; out += c; continue; }
2545
+ if (c === "\\\\") { esc = true; out += c; continue; }
2546
+ if (c === '"') inStr = false;
2547
+ if (!escHtml) out += c;
2548
+ else if (c === "<") out += "\\\\u003c";
2549
+ else if (c === ">") out += "\\\\u003e";
2550
+ else if (c === "&") out += "\\\\u0026";
2551
+ else if (c === "\\u2028") out += "\\\\u2028";
2552
+ else if (c === "\\u2029") out += "\\\\u2029";
2553
+ else out += c;
2554
+ continue;
2555
+ }
2556
+ if (c === '"') { inStr = true; out += c; continue; }
2557
+ if (c === " " || c === "\\t" || c === "\\n" || c === "\\r") continue;
2558
+ out += c;
2559
+ }
2560
+ return out;
2561
+ };
2562
+ var __json_unsupported_value = __json_unsupported_value || function(str) {
2563
+ str = str === "Infinity" ? "+Inf" : (str === "-Infinity" ? "-Inf" : str);
2564
+ if (typeof UnsupportedValueError$$internal$jsonrt === "function") {
2565
+ var e = new UnsupportedValueError$$internal$jsonrt(null, str);
2566
+ e.Str = str;
2567
+ if (e.__p !== true && Object.isExtensible(e)) Object.defineProperty(e, "__p", { value: true, configurable: true, writable: true });
2568
+ e.__struct = "UnsupportedValueError$$internal$jsonrt";
2569
+ return e;
2570
+ }
2571
+ var e = new Error("json: unsupported value: " + str);
2572
+ e.Str = str;
2573
+ e.__struct = "UnsupportedValueError$$internal$jsonrt";
2574
+ return e;
2575
+ };
2576
+ var __json_marshaler_out = __json_marshaler_out || function(res, typeName) {
2577
+ var err = res && res[1];
2578
+ if (err) {
2579
+ var merr;
2580
+ if (typeof MarshalerError$$internal$jsonrt === "function") {
2581
+ merr = new MarshalerError$$internal$jsonrt(typeName, err, "MarshalJSON");
2582
+ if (merr.__p !== true && Object.isExtensible(merr)) Object.defineProperty(merr, "__p", { value: true, configurable: true, writable: true });
2583
+ merr.__struct = "MarshalerError$$internal$jsonrt";
2584
+ } else {
2585
+ merr = new Error("json: error calling MarshalJSON for type " + typeName + ": " + (typeof err.Error === "function" ? err.Error() : String(err)));
2586
+ }
2587
+ throw merr;
2588
+ }
2589
+ var b = res ? res[0] : null;
2590
+ var s = b === null || b === undefined ? "" : (typeof b === "string" ? b : new TextDecoder().decode(b));
2591
+ var c = __json_compact(s);
2592
+ if (c === null) throw new Error("json: error calling MarshalJSON for type " + typeName + ": " + __json_syntax_msg(s));
2593
+ return c;
2594
+ };
2595
+ // Keeps user errors returned by UnmarshalJSON intact while fitting the decoders'
2596
+ // "_msg"-tagged error protocol; __json_unmarshal unwraps __userErr.
2597
+ var __json_user_err = __json_user_err || function(e) {
2598
+ if (e && e._msg !== undefined) return e;
2599
+ return { _msg: e && typeof e.Error === "function" ? e.Error() : String(e), __userErr: e };
2600
+ };
2601
+ // Decodes the JSON string payload of a ,string field. Returns { v } or an error.
2602
+ var __json_unquote = __json_unquote || function(val, kind, typeStr) {
2603
+ if (val === null) return { v: null, lit: "null" };
2604
+ if (typeof val !== "string" || val.endsWith("__bigint")) {
2605
+ return __json_err("invalid use of ,string struct tag, trying to unmarshal unquoted value into " + typeStr);
2606
+ }
2607
+ var invalid = function() {
2608
+ return __json_err("invalid use of ,string struct tag, trying to unmarshal " + JSON.stringify(val) + " into " + typeStr);
2609
+ };
2610
+ var inner;
2611
+ try { inner = JSON.parse(__json_preserve_int64(val)); } catch (e) {
2612
+ if (kind !== "string" && kind !== "bool" && /^-?[0-9]/.test(val)) return __json_err("cannot unmarshal number " + val + " into " + __json_ctx(typeStr));
2613
+ return invalid();
2614
+ }
2615
+ if (inner === null) return { v: null, lit: val };
2616
+ if (kind === "string") return typeof inner === "string" ? { v: inner, lit: val } : invalid();
2617
+ if (kind === "bool") return typeof inner === "number" ? invalid() : { v: inner, lit: val };
2618
+ return typeof inner === "boolean" ? invalid() : { v: inner, lit: val };
2619
+ };
2620
+ var __json_type = __json_type || function(v) {
2621
+ if (v === null) return "null";
2622
+ if (Array.isArray(v)) return "array";
2623
+ var t = typeof v;
2624
+ if (t === "number" || t === "bigint") return "number";
2625
+ if (t === "string") return "string";
2626
+ if (t === "boolean") return "bool";
2627
+ if (t === "object") return "object";
2628
+ return t;
2629
+ };
2630
+ var __json_raw_index = __json_raw_index || new WeakMap();
2631
+ var __json_parse_raw_node = __json_parse_raw_node || function(s) {
2632
+ var i = 0;
2633
+ function ws() { while (i < s.length && /[\\t\\n\\r ]/.test(s[i])) i++; }
2634
+ function stringEnd() {
2635
+ i++;
2636
+ while (i < s.length) {
2637
+ if (s[i] === "\\\\") i += 2;
2638
+ else if (s[i++] === '"') break;
2639
+ }
2640
+ }
2641
+ function value() {
2642
+ ws();
2643
+ var start = i;
2644
+ var node = { children: null };
2645
+ if (s[i] === "{") {
2646
+ i++;
2647
+ node.children = new Map();
2648
+ ws();
2649
+ while (s[i] !== "}") {
2650
+ var keyStart = i;
2651
+ stringEnd();
2652
+ var key = JSON.parse(s.slice(keyStart, i));
2653
+ ws();
2654
+ i++;
2655
+ var child = value();
2656
+ node.children.set(key, child);
2657
+ ws();
2658
+ if (s[i] === ",") { i++; ws(); }
2659
+ else break;
2660
+ }
2661
+ i++;
2662
+ } else if (s[i] === "[") {
2663
+ i++;
2664
+ node.children = new Map();
2665
+ ws();
2666
+ var index = 0;
2667
+ while (s[i] !== "]") {
2668
+ node.children.set(String(index++), value());
2669
+ ws();
2670
+ if (s[i] === ",") { i++; ws(); }
2671
+ else break;
2672
+ }
2673
+ i++;
2674
+ } else if (s[i] === '"') {
2675
+ stringEnd();
2676
+ } else {
2677
+ while (i < s.length && !/[\\t\\n\\r ,}\\]]/.test(s[i])) i++;
2678
+ }
2679
+ node.raw = s.slice(start, i);
2680
+ node.start = start;
2681
+ node.end = i;
2682
+ return node;
2683
+ }
2684
+ return value();
2685
+ };
2686
+ var __json_bind_raw = __json_bind_raw || function(value, node) {
2687
+ if (value === null || typeof value !== "object" || !node?.children) return;
2688
+ __json_raw_index.set(value, node.children);
2689
+ for (const [key, child] of node.children) __json_bind_raw(value[key], child);
2690
+ };
2691
+ var __json_raw_child = __json_raw_child || function(parent, key) {
2692
+ return __json_raw_index.get(parent)?.get(String(key))?.raw;
2693
+ };
2694
+ var __json_raw_end = __json_raw_end || function(parent, key) {
2695
+ return __json_raw_index.get(parent)?.get(String(key))?.end;
2696
+ };
2697
+ var __json_raw_bytes = __json_raw_bytes || function(raw) {
2698
+ return new TextEncoder().encode(raw ?? "null");
2699
+ };
2700
+ var __json_match_field = __json_match_field || function(obj, tagName, fieldName) {
2701
+ if (Object.prototype.hasOwnProperty.call(obj, tagName)) return tagName;
2702
+ if (Object.prototype.hasOwnProperty.call(obj, fieldName)) return fieldName;
2703
+ var tagFold = tagName.toLowerCase();
2704
+ var fieldFold = fieldName.toLowerCase();
2705
+ for (const key of Object.keys(obj)) {
2706
+ var keyFold = key.toLowerCase();
2707
+ if (keyFold === tagFold || keyFold === fieldFold) return key;
2708
+ }
2709
+ return null;
2710
+ };
2711
+ var __json_float64 = __json_float64 || function(v) {
2712
+ if (!isFinite(v)) throw __json_unsupported_value(String(v));
2713
+ return Object.is(v, -0) ? "-0" : String(v);
2714
+ };
2715
+ var __json_float32 = __json_float32 || function(v) {
2716
+ var f = Math.fround(v);
2717
+ if (!isFinite(f)) throw __json_unsupported_value(String(f));
2718
+ if (Object.is(f, -0)) return "-0";
2719
+ var candidate;
2720
+ for (var precision = 1; precision <= 9; precision++) {
2721
+ candidate = f.toPrecision(precision);
2722
+ if (Math.fround(Number(candidate)) === f) break;
2723
+ }
2724
+ var n = Number(candidate);
2725
+ var expText = n.toExponential();
2726
+ var match = /e([+-]?)(\\d+)$/.exec(expText);
2727
+ var exponent = Number(match[2]) * (match[1] === "-" ? -1 : 1);
2728
+ if (exponent < -6 || exponent >= 21) {
2729
+ var mantissa = expText.slice(0, expText.indexOf("e"));
2730
+ var sign = exponent >= 0 ? "+" : "-";
2731
+ return mantissa + "e" + sign + String(Math.abs(exponent));
2732
+ }
2733
+ return n.toString();
2734
+ };
2735
+ var __json_number_value = __json_number_value || function(v) {
2736
+ return typeof v === "string" && v.endsWith("__bigint") ? Number(v.slice(0, -8)) : v;
2737
+ };
2738
+ var __json_int_decode = __json_int_decode || function(v, typeName, ctxType, raw) {
2739
+ var type = typeof v === "string" && v.endsWith("__bigint") ? "number" : __json_type(v);
2740
+ var fail = function() {
2741
+ return __json_err("cannot unmarshal " + (type === "number" ? "number " + __json_lit(v, raw) : type) + " into " + __json_ctx(ctxType));
2742
+ };
2743
+ if (type !== "number") return fail();
2744
+ // Go parses integers with strconv.ParseInt: "1.0" and "1e2" are not integers.
2745
+ if (raw !== undefined && raw !== null && !/^-?(0|[1-9][0-9]*)$/.test(String(raw).trim())) return fail();
2746
+ var integer;
2747
+ var signed = typeName === "int" || typeName.startsWith("int");
2748
+ if (typeName === "int64" || typeName === "uint64") {
2749
+ if (typeof v === "string" && v.endsWith("__bigint")) {
2750
+ try { integer = BigInt(v.slice(0, -8)); } catch (_) {}
2751
+ } else if (typeof v === "number" && Number.isSafeInteger(v)) {
2752
+ integer = BigInt(v);
2753
+ }
2754
+ if (integer !== undefined) {
2755
+ var min64 = typeName === "int64" ? -(1n << 63n) : 0n;
2756
+ var max64 = typeName === "int64" ? (1n << 63n) - 1n : (1n << 64n) - 1n;
2757
+ if (integer >= min64 && integer <= max64) return typeof v === "number" ? v : integer;
2758
+ }
2759
+ return fail();
2760
+ }
2761
+ if (typeof v === "number" && Number.isSafeInteger(v)) {
2762
+ if (typeName === "int") return v;
2763
+ var bits = typeName === "uint" ? 53 : Number(typeName.replace(/^(u?int|byte|rune)/, ""));
2764
+ if (!bits) bits = typeName === "byte" ? 8 : typeName === "rune" ? 32 : 53;
2765
+ var min = signed ? -(2 ** (bits - 1)) : 0;
2766
+ var max = signed ? (2 ** (bits - 1)) - 1 : (2 ** bits) - 1;
2767
+ if (v >= min && v <= max) return v;
2768
+ }
2769
+ return fail();
2770
+ };
2771
+ var __json_b64 = __json_b64 || function(u8) {
2772
+ if (u8 === null || u8 === undefined) return "null";
2773
+ if (typeof __base64_std !== "undefined") return '"' + __base64_std.EncodeToString(u8) + '"';
2774
+ var bstr = "";
2775
+ for (var i = 0; i < u8.length; i++) bstr += String.fromCharCode(u8[i]);
2776
+ return '"' + (typeof btoa !== "undefined" ? btoa(bstr) : Buffer.from(u8).toString("base64")) + '"';
2777
+ };
2778
+ var __json_b64_dec = __json_b64_dec || function(str) {
2779
+ if (typeof __base64_std !== "undefined") {
2780
+ var res = __base64_std.DecodeString(str);
2781
+ if (!res[1]) return res[0];
2782
+ }
2783
+ var bin = typeof atob !== "undefined" ? atob(str) : Buffer.from(str, "base64").toString("binary");
2784
+ var u8 = new Uint8Array(bin.length);
2785
+ for (var i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
2786
+ return u8;
2787
+ };
2788
+ var __json_is_zero = __json_is_zero || function(val, isStruct, isMap) {
2789
+ if (isStruct) return false;
2790
+ if (isMap) return __json_nilmap(val) || (val instanceof Map ? val.size === 0 : Object.keys(val).length === 0);
2791
+ if (val === null || val === undefined || val === false || val === 0 || val === "") return true;
2792
+ if (typeof val === "bigint") return val === 0n;
2793
+ if (Array.isArray(val) || (ArrayBuffer.isView(val) && !val.__raw)) return val.length === 0;
2794
+ if (val instanceof Map) return val.size === 0;
2795
+ if (val && val.__map) return Object.keys(val).filter(function(k) { return !k.startsWith("__"); }).length === 0;
2796
+ return false;
2797
+ };
2798
+ var __json_preserve_int64 = __json_preserve_int64 || function(str) {
2799
+ return str.replace(/"(?:\\\\.|[^"\\\\])*"|(?<=[,:\\[{\\s]|^)(-?\\d{16,})(?=[,\\]}\\s]|$)/g, function(m, num) {
2800
+ if (num) {
2801
+ try {
2802
+ var b = BigInt(num);
2803
+ if (b > 9007199254740991n || b < -9007199254740991n) return '"' + num + '__bigint"';
2804
+ } catch (e) {}
2805
+ }
2806
+ return m;
2807
+ });
2808
+ };
2809
+ // Go maps: a nil map is the __nm()/__nilmap marker, an empty one a plain object.
2810
+ var __json_nilmap = __json_nilmap || function(m) {
2811
+ return m === null || m === undefined || m.__nilm === true || m.__nm === true;
2812
+ };
2813
+ // Decoded maps carry a hidden marker so fmt and json treat them as maps.
2814
+ var __json_newmap = __json_newmap || function() {
2815
+ return Object.defineProperty(Object.create(null), "__map", { value: true, configurable: true });
2816
+ };
2817
+ // json.RawMessage is compacted (and validated) like any Marshaler output; nil is null.
2818
+ var __json_enc_raw = __json_enc_raw || function(v) {
2819
+ if (v === null || v === undefined) return "null";
2820
+ return __json_marshaler_out([v, null], "json.RawMessage");
2821
+ };
2822
+ var __json_enc_any = __json_enc_any || function(v) {
2823
+ if (v === null || v === undefined) return "null";
2824
+ var t = typeof v;
2825
+ if (t === "boolean") return v ? "true" : "false";
2826
+ if (t === "number") {
2827
+ if (!isFinite(v)) throw __json_unsupported_value(String(v));
2828
+ return Object.is(v, -0) ? "-0" : String(v);
2829
+ }
2830
+ if (t === "bigint") return v.toString();
2831
+ if (t === "string") return __json_esc(v);
2832
+ if (Object.prototype.toString.call(v) === "[object Uint8Array]") {
2833
+ if (v.__raw) return __json_enc_raw(v);
2834
+ return __json_b64(v);
2835
+ }
2836
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(v)) {
2837
+ var titems = [];
2838
+ for (var ti = 0; ti < v.length; ti++) titems.push(v instanceof Float32Array ? __json_float32(v[ti]) : (typeof v[ti] === "bigint" ? v[ti].toString() : String(v[ti])));
2839
+ return "[" + titems.join(",") + "]";
2840
+ }
2841
+ if (Array.isArray(v)) {
2842
+ var items = [];
2843
+ for (var i = 0; i < v.length; i++) items.push(__json_enc_any(v[i]));
2844
+ return "[" + items.join(",") + "]";
2845
+ }
2846
+ if (v instanceof Map) {
2847
+ var mkeys = Array.from(v.keys()).map(String).sort();
2848
+ var mentries = [];
2849
+ for (var mi = 0; mi < mkeys.length; mi++) {
2850
+ mentries.push(__json_esc(mkeys[mi]) + ":" + __json_enc_any(v.get(mkeys[mi])));
2851
+ }
2852
+ return "{" + mentries.join(",") + "}";
2853
+ }
2854
+ if (typeof v.__json_enc === "function") return v.__json_enc();
2855
+ if (typeof v.MarshalJSON === "function" && !(v.__v === true && v.MarshalJSON.__ptrRecv)) {
2856
+ return __json_marshaler_out(v.MarshalJSON(), v.constructor && v.constructor.name ? v.constructor.name : "value");
2857
+ }
2858
+ // Boxed named values (from an interface) encode as their value; *T boxes as the pointee.
2859
+ if (typeof v.__gfUnbox === "function") {
2860
+ var inner = v.__gfUnbox();
2861
+ if (Object.prototype.hasOwnProperty.call(v, "_p")) inner = inner == null ? null : inner.value;
2862
+ return __json_enc_any(inner);
2863
+ }
2864
+ if (typeof v === "object") {
2865
+ if (__json_nilmap(v)) return "null";
2866
+ var okeys = Object.keys(v).filter(function(k) { return !k.startsWith("__") || k === "__proto__"; });
2867
+ if (!v.__map && v.constructor && v.constructor !== Object && v.constructor.name !== "Object") {
2868
+ okeys = okeys.filter(function(k) { return !(k.length > 0 && k[0] >= "a" && k[0] <= "z"); });
2869
+ }
2870
+ okeys.sort();
2871
+ var oentries = [];
2872
+ for (var oi = 0; oi < okeys.length; oi++) {
2873
+ oentries.push(__json_esc(okeys[oi]) + ":" + __json_enc_any(v[okeys[oi]]));
2874
+ }
2875
+ return "{" + oentries.join(",") + "}";
2876
+ }
2877
+ return "null";
2878
+ };
2879
+ var __json_dec_any = __json_dec_any || function(parsed) {
2880
+ if (parsed === null) return null;
2881
+ var useNum = typeof OptUseNumber$$internal$jsonrt !== "undefined" && OptUseNumber$$internal$jsonrt;
2882
+ if (typeof parsed === "string") {
2883
+ if (parsed.endsWith("__bigint")) {
2884
+ var rawBig = parsed.slice(0, -8);
2885
+ if (useNum) return typeof Number$$internal$jsonrt === "function" ? new Number$$internal$jsonrt(rawBig) : rawBig;
2886
+ return Number(rawBig);
2887
+ }
2888
+ return parsed;
2889
+ }
2890
+ if (typeof parsed === "number") {
2891
+ if (useNum) {
2892
+ var rawNum = String(parsed);
2893
+ return typeof Number$$internal$jsonrt === "function" ? new Number$$internal$jsonrt(rawNum) : rawNum;
2894
+ }
2895
+ return parsed;
2896
+ }
2897
+ if (typeof parsed === "boolean") return parsed;
2898
+ if (Array.isArray(parsed)) {
2899
+ var outSlice = [];
2900
+ for (var i = 0; i < parsed.length; i++) outSlice.push(__json_dec_any(parsed[i]));
2901
+ return outSlice;
2902
+ }
2903
+ if (typeof parsed === "object") {
2904
+ var outMap = __json_newmap();
2905
+ for (var k in parsed) {
2906
+ if (Object.prototype.hasOwnProperty.call(parsed, k)) {
2907
+ outMap[k] = __json_dec_any(parsed[k]);
2908
+ }
2909
+ }
2910
+ return outMap;
2911
+ }
2912
+ return parsed;
2913
+ };
2914
+ var __json_dec_any_target = __json_dec_any_target || function(parsed, target, box) {
2915
+ var out = __json_dec_any(parsed);
2916
+ if (box) box.value = out;
2917
+ else if (target && typeof target === "object") {
2918
+ for (const k of Object.keys(out)) Object.defineProperty(target, k, { value: out[k], writable: true, enumerable: true, configurable: true });
2919
+ }
2920
+ return null;
2921
+ };
2922
+ var __json_enc_slice = __json_enc_slice || function(slice, elemEnc) {
2923
+ if (slice === null || slice === undefined) return "null";
2924
+ var items = [];
2925
+ for (var i = 0; i < slice.length; i++) items.push(elemEnc(slice[i]));
2926
+ return "[" + items.join(",") + "]";
2927
+ };
2928
+ var __json_enc_map = __json_enc_map || function(m, valEnc) {
2929
+ if (__json_nilmap(m)) return "null";
2930
+ if (m instanceof Map) {
2931
+ var mkeys = Array.from(m.keys()).map(String).sort();
2932
+ var mentries = [];
2933
+ for (var i = 0; i < mkeys.length; i++) {
2934
+ mentries.push(__json_esc(mkeys[i]) + ":" + valEnc(m.get(mkeys[i])));
2935
+ }
2936
+ return "{" + mentries.join(",") + "}";
2937
+ }
2938
+ var keys = Object.keys(m).filter(function(k) { return !k.startsWith("__") || k === "__proto__"; }).sort();
2939
+ var entries = [];
2940
+ for (var j = 0; j < keys.length; j++) {
2941
+ entries.push(__json_esc(keys[j]) + ":" + valEnc(m[keys[j]]));
2942
+ }
2943
+ return "{" + entries.join(",") + "}";
2944
+ };
2945
+ var __json_marshal = __json_marshal || function(enc, val) {
2946
+ try {
2947
+ var str = enc(val);
2948
+ return [new TextEncoder().encode(str), null];
2949
+ } catch (e) {
2950
+ if (e && typeof e.Error === "function") return [new Uint8Array(0), e];
2951
+ return [new Uint8Array(0), typeof __error === "function" ? __error(e.message || String(e)) : e];
2952
+ }
2953
+ };
2954
+ var __json_indent = __json_indent || function(jsonStr, prefix, indent) {
2955
+ var out = "";
2956
+ var depth = 0;
2957
+ var inString = false;
2958
+ var escaped = false;
2959
+ for (var i = 0; i < jsonStr.length; i++) {
2960
+ var c = jsonStr[i];
2961
+ if (inString) {
2962
+ out += c;
2963
+ if (escaped) escaped = false;
2964
+ else if (c === "\\\\") escaped = true;
2965
+ else if (c === '"') inString = false;
2966
+ continue;
2967
+ }
2968
+ if (c === '"') { inString = true; out += c; continue; }
2969
+ if (c === "{" || c === "[") {
2970
+ out += c;
2971
+ depth++;
2972
+ var next = jsonStr[i + 1];
2973
+ if ((c === "{" && next === "}") || (c === "[" && next === "]")) {
2974
+ out += next;
2975
+ i++;
2976
+ depth--;
2977
+ continue;
2978
+ }
2979
+ out += "\\n" + prefix + indent.repeat(depth);
2980
+ } else if (c === "}" || c === "]") {
2981
+ depth--;
2982
+ out += "\\n" + prefix + indent.repeat(depth) + c;
2983
+ } else if (c === ",") {
2984
+ out += ",\\n" + prefix + indent.repeat(depth);
2985
+ } else if (c === ":") {
2986
+ out += ": ";
2987
+ } else if (c !== " " && c !== "\\t" && c !== "\\n" && c !== "\\r") {
2988
+ out += c;
2989
+ }
2990
+ }
2991
+ return out;
2992
+ };
2993
+ var __json_marshal_indent = __json_marshal_indent || function(enc, val, prefix, indent) {
2994
+ var res = __json_marshal(enc, val);
2995
+ if (res[1]) return res;
2996
+ var rawStr = new TextDecoder().decode(res[0]);
2997
+ var formatted = __json_indent(rawStr, prefix, indent);
2998
+ return [new TextEncoder().encode(formatted), null];
2999
+ };
3000
+ var __json_valid = __json_valid || function(data) {
3001
+ try {
3002
+ var s = typeof data === "string" ? data : new TextDecoder().decode(((typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(data)) || data instanceof Uint8Array) ? data : new Uint8Array(data));
3003
+ JSON.parse(s);
3004
+ return true;
3005
+ } catch (e) {
3006
+ return false;
3007
+ }
3008
+ };
3009
+ // The static type of the target decides the argument errors, as in Go:
3010
+ // targetKind is "ptr" (a pointer), "val" (neither pointer nor interface) or
3011
+ // empty (an interface, judged by the dynamic value).
3012
+ var __json_invalid_target = __json_invalid_target || function(name, isPtr) {
3013
+ if (typeof InvalidUnmarshalError$$internal$jsonrt === "function") {
3014
+ var e = new InvalidUnmarshalError$$internal$jsonrt(name, isPtr);
3015
+ if (e.__p !== true && Object.isExtensible(e)) Object.defineProperty(e, "__p", { value: true, configurable: true, writable: true });
3016
+ e.__struct = "InvalidUnmarshalError$$internal$jsonrt";
3017
+ return e;
3018
+ }
3019
+ var msg = name === "" ? "json: Unmarshal(nil)" : (isPtr ? "json: Unmarshal(nil " + name + ")" : "json: Unmarshal(non-pointer " + name + ")");
3020
+ return typeof __error === "function" ? __error(msg) : new Error(msg);
3021
+ };
3022
+ var __json_unmarshal = __json_unmarshal || function(dec, data, target, targetTypeName, targetKind) {
3023
+ __json_structs.length = 0;
3024
+ __json_path.length = 0;
3025
+ __json_current_offset = 0;
3026
+ var u8data = ((typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(data)) || data instanceof Uint8Array) ? data : new Uint8Array(data);
3027
+ if (typeof CheckValid$$internal$jsonrt === "function") {
3028
+ var syntaxErr = CheckValid$$internal$jsonrt(u8data);
3029
+ if (syntaxErr) {
3030
+ if (typeof syntaxErr === "object" && syntaxErr !== null) {
3031
+ if (syntaxErr.__p !== true && Object.isExtensible(syntaxErr)) {
3032
+ Object.defineProperty(syntaxErr, "__p", { value: true, configurable: true, writable: true });
3033
+ }
3034
+ syntaxErr.__struct = "SyntaxError$$internal$jsonrt";
3035
+ }
3036
+ return syntaxErr;
3037
+ }
3038
+ }
3039
+ if (targetKind === "val") return __json_invalid_target(targetTypeName, false);
3040
+ if (target === null || target === undefined) {
3041
+ return targetKind === "ptr" ? __json_invalid_target(targetTypeName, true) : __json_invalid_target("", false);
3042
+ }
3043
+ if (typeof target !== "object" || target.__v === true) {
3044
+ var tname = targetTypeName || (target && target.constructor && target.constructor.name && target.constructor.name !== "Object" ? target.constructor.name : typeof target);
3045
+ return __json_invalid_target(tname, false);
3046
+ }
3047
+ var str;
3048
+ try {
3049
+ str = typeof data === "string" ? data : new TextDecoder().decode(u8data);
3050
+ } catch (e) {
3051
+ return typeof __error === "function" ? __error("invalid UTF-8 data") : e;
3052
+ }
3053
+ var safeStr = __json_preserve_int64(str);
3054
+ var parsed;
3055
+ try {
3056
+ parsed = JSON.parse(safeStr);
3057
+ } catch (e) {
3058
+ return typeof __error === "function" ? __error(e.message) : e;
3059
+ }
3060
+ var rootRaw = __json_parse_raw_node(str);
3061
+ __json_bind_raw(parsed, rootRaw);
3062
+ __json_current_offset = str.length;
3063
+ var isBox = target && typeof target === "object" && (Object.prototype.hasOwnProperty.call(target, "value") || typeof target.__gfUnbox === "function");
3064
+ var dest = isBox ? target.value : target;
3065
+ var err = dec(parsed, dest, isBox ? target : null, data, rootRaw.raw);
3066
+ if (err) return err.__userErr || err;
3067
+ return null;
3068
+ };
3069
+ var __json_encoder_encode = __json_encoder_encode || function(enc, codec, v) {
3070
+ var e = enc?.value ?? enc;
3071
+ if (e.err != null) return e.err;
3072
+ OptEscapeHTML$$internal$jsonrt = e.escapeHTML;
3073
+ var jsonStr;
3074
+ try {
3075
+ jsonStr = codec(v);
3076
+ } catch (err) {
3077
+ if (err && typeof err.Error === "function") return err;
3078
+ return typeof __error === "function" ? __error(err.message || String(err)) : err;
3079
+ } finally {
3080
+ OptEscapeHTML$$internal$jsonrt = true;
3081
+ }
3082
+ if (e.indent !== "" || e.prefix !== "") {
3083
+ var indented = __json_indent(jsonStr, e.prefix, e.indent);
3084
+ if (indented != null) jsonStr = indented;
3085
+ }
3086
+ var bytes = new TextEncoder().encode(jsonStr + "\\n");
3087
+ var res = e.w.Write(bytes);
3088
+ var err = Array.isArray(res) ? res[1] : null;
3089
+ if (err != null) {
3090
+ e.err = err;
3091
+ return err;
3092
+ }
3093
+ return null;
3094
+ };
3095
+ var __json_decoder_decode = __json_decoder_decode || function(dec, decFn, target, targetTypeName, targetKind) {
3096
+ var d = dec?.value ?? dec;
3097
+ var res = ScanNext$$internal$jsonrt(d.r);
3098
+ var data = res[0], skipped = res[1], err = res[2];
3099
+ d.offset += skipped;
3100
+ if (err != null) return err;
3101
+ d.offset += data.length;
3102
+ OptUseNumber$$internal$jsonrt = d.useNumber;
3103
+ OptDisallowUnknownFields$$internal$jsonrt = d.disallowUnknownFields;
3104
+ var uerr;
3105
+ try {
3106
+ uerr = __json_unmarshal(decFn, data, target, targetTypeName, targetKind);
3107
+ } finally {
3108
+ OptUseNumber$$internal$jsonrt = false;
3109
+ OptDisallowUnknownFields$$internal$jsonrt = false;
3110
+ }
3111
+ return uerr;
3112
+ };`;
3113
+
3114
+ export const HELPER_SIMD = `var __simd_f32x4 = __simd_f32x4 || function(a, b, c, d) {
3115
+ return Object.freeze([Math.fround(Number(a ?? 0)), Math.fround(Number(b ?? 0)), Math.fround(Number(c ?? 0)), Math.fround(Number(d ?? 0))]);
3116
+ };
3117
+ var __simd_splat = __simd_splat || function(v) {
3118
+ var s = Math.fround(Number(v ?? 0));
3119
+ return Object.freeze([s, s, s, s]);
3120
+ };
3121
+ var __simd_add = __simd_add || function(a, b) {
3122
+ return Object.freeze([Math.fround(a[0] + b[0]), Math.fround(a[1] + b[1]), Math.fround(a[2] + b[2]), Math.fround(a[3] + b[3])]);
3123
+ };
3124
+ var __simd_sub = __simd_sub || function(a, b) {
3125
+ return Object.freeze([Math.fround(a[0] - b[0]), Math.fround(a[1] - b[1]), Math.fround(a[2] - b[2]), Math.fround(a[3] - b[3])]);
3126
+ };
3127
+ var __simd_mul = __simd_mul || function(a, b) {
3128
+ return Object.freeze([Math.fround(a[0] * b[0]), Math.fround(a[1] * b[1]), Math.fround(a[2] * b[2]), Math.fround(a[3] * b[3])]);
3129
+ };
3130
+ var __simd_div = __simd_div || function(a, b) {
3131
+ return Object.freeze([Math.fround(a[0] / b[0]), Math.fround(a[1] / b[1]), Math.fround(a[2] / b[2]), Math.fround(a[3] / b[3])]);
3132
+ };
3133
+ var __simd_min = __simd_min || function(a, b) {
3134
+ return Object.freeze([Math.fround(Math.min(a[0], b[0])), Math.fround(Math.min(a[1], b[1])), Math.fround(Math.min(a[2], b[2])), Math.fround(Math.min(a[3], b[3]))]);
3135
+ };
3136
+ var __simd_max = __simd_max || function(a, b) {
3137
+ return Object.freeze([Math.fround(Math.max(a[0], b[0])), Math.fround(Math.max(a[1], b[1])), Math.fround(Math.max(a[2], b[2])), Math.fround(Math.max(a[3], b[3]))]);
3138
+ };
3139
+ var __simd_dot3 = __simd_dot3 || function(a, b) {
3140
+ return Math.fround(Math.fround(Math.fround(a[0] * b[0]) + Math.fround(a[1] * b[1])) + Math.fround(a[2] * b[2]));
3141
+ };
3142
+ var __simd_dot4 = __simd_dot4 || function(a, b) {
3143
+ return Math.fround(Math.fround(Math.fround(Math.fround(a[0] * b[0]) + Math.fround(a[1] * b[1])) + Math.fround(a[2] * b[2])) + Math.fround(a[3] * b[3]));
3144
+ };
3145
+ var __simd_with_lane = __simd_with_lane || function(a, i, v) {
3146
+ var r = [a[0], a[1], a[2], a[3]];
3147
+ r[i] = Math.fround(v);
3148
+ return Object.freeze(r);
3149
+ };
3150
+ var __simd_map = __simd_map || function(a, f) {
3151
+ return Object.freeze([Math.fround(f(a[0])), Math.fround(f(a[1])), Math.fround(f(a[2])), Math.fround(f(a[3]))]);
3152
+ };
3153
+ var __simd_neg = __simd_neg || function(a) { return __simd_map(a, function(x) { return -x; }); };
3154
+ var __simd_abs = __simd_abs || function(a) { return __simd_map(a, Math.abs); };
3155
+ var __simd_sqrt = __simd_sqrt || function(a) { return __simd_map(a, Math.sqrt); };
3156
+ var __simd_floor = __simd_floor || function(a) { return __simd_map(a, Math.floor); };
3157
+ var __simd_ceil = __simd_ceil || function(a) { return __simd_map(a, Math.ceil); };
3158
+ var __simd_trunc = __simd_trunc || function(a) { return __simd_map(a, Math.trunc); };
3159
+ var __simd_nearest = __simd_nearest || function(a) {
3160
+ return __simd_map(a, function(x) {
3161
+ if (!isFinite(x)) return x;
3162
+ var f = Math.floor(x), d = x - f, r;
3163
+ if (d < 0.5) r = f; else if (d > 0.5) r = f + 1; else r = (f % 2 === 0) ? f : f + 1;
3164
+ return (r === 0 && (x < 0 || Object.is(x, -0))) ? -0 : r;
3165
+ });
3166
+ };
3167
+ var __simd_muladd = __simd_muladd || function(a, b, c) {
3168
+ return Object.freeze([Math.fround(Math.fround(a[0] * b[0]) + c[0]), Math.fround(Math.fround(a[1] * b[1]) + c[1]), Math.fround(Math.fround(a[2] * b[2]) + c[2]), Math.fround(Math.fround(a[3] * b[3]) + c[3])]);
3169
+ };
3170
+ var __simd_sum = __simd_sum || function(a) {
3171
+ return Math.fround(Math.fround(Math.fround(a[0] + a[1]) + a[2]) + a[3]);
3172
+ };
3173
+ var __simd_cmp = __simd_cmp || function(a, b, f) {
3174
+ return Object.freeze([f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])]);
3175
+ };
3176
+ var __simd_eq = __simd_eq || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x === y; }); };
3177
+ var __simd_ne = __simd_ne || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x !== y; }); };
3178
+ var __simd_lt = __simd_lt || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x < y; }); };
3179
+ var __simd_le = __simd_le || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x <= y; }); };
3180
+ var __simd_gt = __simd_gt || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x > y; }); };
3181
+ var __simd_ge = __simd_ge || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x >= y; }); };
3182
+ var __simd_equal = __simd_equal || function(a, b) {
3183
+ return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
3184
+ };
3185
+ var __simd_mask_and = __simd_mask_and || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x && y; }); };
3186
+ var __simd_mask_or = __simd_mask_or || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x || y; }); };
3187
+ var __simd_mask_xor = __simd_mask_xor || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x !== y; }); };
3188
+ var __simd_mask_andnot = __simd_mask_andnot || function(a, b) { return __simd_cmp(a, b, function(x, y) { return x && !y; }); };
3189
+ var __simd_mask_not = __simd_mask_not || function(a) { return Object.freeze([!a[0], !a[1], !a[2], !a[3]]); };
3190
+ var __simd_mask_any = __simd_mask_any || function(a) { return a[0] || a[1] || a[2] || a[3]; };
3191
+ var __simd_mask_all = __simd_mask_all || function(a) { return a[0] && a[1] && a[2] && a[3]; };
3192
+ var __simd_mask_bits = __simd_mask_bits || function(a) { return (a[0] ? 1 : 0) | (a[1] ? 2 : 0) | (a[2] ? 4 : 0) | (a[3] ? 8 : 0); };
3193
+ var __simd_select = __simd_select || function(m, a, b) {
3194
+ return Object.freeze([m[0] ? a[0] : b[0], m[1] ? a[1] : b[1], m[2] ? a[2] : b[2], m[3] ? a[3] : b[3]]);
3195
+ };
3196
+ var __simd_shuffle = __simd_shuffle || function(a, b, i0, i1, i2, i3) {
3197
+ var c = [a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]];
3198
+ return Object.freeze([c[i0], c[i1], c[i2], c[i3]]);
3199
+ };
3200
+ var __simd_swizzle = __simd_swizzle || function(a, i0, i1, i2, i3) {
3201
+ return Object.freeze([a[i0], a[i1], a[i2], a[i3]]);
3202
+ };
3203
+ var __simd_load = __simd_load || function(buf, i) {
3204
+ if (i < 0 || i + 4 > buf.length) throw new Error("panic: runtime error: index out of range");
3205
+ return Object.freeze([Math.fround(buf[i]), Math.fround(buf[i + 1]), Math.fround(buf[i + 2]), Math.fround(buf[i + 3])]);
3206
+ };
3207
+ var __simd_store = __simd_store || function(buf, i, v) {
3208
+ if (i < 0 || i + 4 > buf.length) throw new Error("panic: runtime error: index out of range");
3209
+ buf[i] = v[0]; buf[i + 1] = v[1]; buf[i + 2] = v[2]; buf[i + 3] = v[3];
3210
+ };
3211
+ var __simd_load_slice = __simd_load_slice || function(xs, i) {
3212
+ if (xs == null || i < 0 || i + 4 > xs.length) throw new Error("panic: runtime error: index out of range");
3213
+ return Object.freeze([xs[i], xs[i + 1], xs[i + 2], xs[i + 3]]);
3214
+ };
3215
+ var __simd_store_slice = __simd_store_slice || function(xs, i, v) {
3216
+ if (xs == null || i < 0 || i + 4 > xs.length) throw new Error("panic: runtime error: index out of range");
3217
+ xs[i] = v[0]; xs[i + 1] = v[1]; xs[i + 2] = v[2]; xs[i + 3] = v[3];
3218
+ };`;