@chrischall/warapp-mcp 0.3.1 → 0.5.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.
@@ -0,0 +1,371 @@
1
+ // Deriving the reader dialect from the client bundle itself.
2
+ //
3
+ // Every war.app client build re-minifies the code, hotfix builds included (docs/CLIENT-RELEASES.md),
4
+ // so the names the bundle's readers call — the BinaryReader's methods (`a.Tg()`), the Serializer's
5
+ // helpers (`P.Ya(a)`), the Enumerable helpers, the nullable wrapper classes — change with every
6
+ // build while what they do does not. Rather than pin one build's names, this module finds them by
7
+ // structure:
8
+ //
9
+ // - the wrapper and helper CLASSES by their registered type names (`W["warlight.shared.Serializer"]=P`),
10
+ // which the minifier keeps;
11
+ // - the haxe.io.Input methods by what they do (readByte throws its own name; readInt32 reads four
12
+ // bytes and shifts by 24; readInt16 sign-extends at 32768; …);
13
+ // - the BinaryReader methods by the Input method they call (or the varint/raw/string shapes);
14
+ // - the static helpers by their canonical form: the function's tokens with every name renamed to
15
+ // its order of first appearance, except reader-method names (replaced by their role) and class
16
+ // vars (replaced by their registered type name). Two builds' helpers that do the same thing have
17
+ // the same canonical form, whatever the minifier called them.
18
+ //
19
+ // Nothing here runs bundle code: it reads source text. The result is only names → roles; the
20
+ // interpreter attaches its built-in natives to them and `verifyDialect` still probes the bundle's
21
+ // own definitions against those natives, so a wrong derivation is refused at load, never decoded
22
+ // through. A bundle this module cannot read in full gets `null`, and the interpreter falls back to
23
+ // its built-in (v6.07) names.
24
+ import { parseExpressionAt } from 'acorn';
25
+ /** Registered type names of the classes the dialect lives on. */
26
+ const INPUT_TYPE = 'haxe.io.Input';
27
+ const READER_TYPE = 'system.io.BinaryReader';
28
+ const SERIALIZER_TYPE = 'warlight.shared.Serializer';
29
+ const UTILITY_TYPE = 'warlight.shared.SharedUtility';
30
+ const PUMP_TYPE = 'warlight.shared.MessagePump';
31
+ const ENUMERABLE_TYPE = 'system.linq.Enumerable';
32
+ /** The wrapper classes `new X(v)` reads as `v` (v6.07: Z, Yb, uc, dc, oc, ec, fc). */
33
+ export const WRAPPER_TYPES = [
34
+ 'system.Nullable_Int',
35
+ 'system.Nullable',
36
+ 'system.Nullable_Float',
37
+ 'system.Nullable_Bool',
38
+ 'system.CsRef',
39
+ 'system.TimeSpan',
40
+ 'system.DateTime',
41
+ ];
42
+ /** The longest function source this module canonicalizes (the helpers are a few hundred characters). */
43
+ const MAX_FN_SOURCE = 4000;
44
+ /** The reader roles a derivation must find, or it is not used. */
45
+ const REQUIRED_READER_ROLES = ['bool', 'int32', 'u8', 'string', 'float64', 'float32', 'uint16', 'raw', 'varint'];
46
+ /** The Serializer roles a derivation must find (every one the v6.07 dialect had). */
47
+ const REQUIRED_STATIC_ROLES = [
48
+ 'int32',
49
+ 'string',
50
+ 'bool',
51
+ 'u8',
52
+ 'float32',
53
+ 'float64',
54
+ 'timespan',
55
+ 'date',
56
+ 'guid',
57
+ 'uint16',
58
+ 'bytes',
59
+ 'list',
60
+ 'dict',
61
+ ];
62
+ const KEYWORDS = new Set('var let const function return if else for while do break continue new null true false this typeof instanceof in of throw try catch finally switch case default void delete'.split(' '));
63
+ const TOKEN = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[A-Za-z_$][\w$]*|\d+(?:\.\d+)?(?:[eE][-+]?\d+)?|>>>=?|===|!==|<<=|>>=|[=!<>]=|&&|\|\||\+\+|--|<<|>>|[-+*/%&|^]=|\S/g;
64
+ /**
65
+ * A function's canonical form: its tokens, with keywords, literals and punctuation kept, a member
66
+ * name that is a known reader method replaced by `@<role>`, an identifier that is a registered class
67
+ * var replaced by `@T:<type name>`, and every other name by `#<n>`, its order of first appearance.
68
+ */
69
+ export function canonicalize(src, roleOf, typeOf) {
70
+ const names = new Map();
71
+ const out = [];
72
+ let prev = '';
73
+ for (const t of src.match(TOKEN) ?? []) {
74
+ const c = t[0];
75
+ const isName = /[A-Za-z_$]/.test(c);
76
+ if (!isName || KEYWORDS.has(t))
77
+ out.push(t);
78
+ else if (prev === '.' && roleOf(t) !== undefined)
79
+ out.push(`@${roleOf(t)}`);
80
+ else if (prev !== '.' && typeOf(t) !== undefined)
81
+ out.push(`@T:${typeOf(t)}`);
82
+ else {
83
+ let n = names.get(t);
84
+ if (n === undefined) {
85
+ n = `#${names.size}`;
86
+ names.set(t, n);
87
+ }
88
+ out.push(n);
89
+ }
90
+ prev = t;
91
+ }
92
+ return out.join(' ');
93
+ }
94
+ /**
95
+ * The Serializer helpers of client v6.07.0.1 in canonical form (generated from that bundle with this
96
+ * module's own reader roles), by role. 6.08.0.1 and 6.08.0.2 give the same forms.
97
+ */
98
+ export const SERIALIZER_TEMPLATES = {
99
+ 'function ( #0 ) { return #0 . @int32 ( ) }': 'int32',
100
+ 'function ( #0 ) { return #0 . @bool ( ) ? #0 . @string ( ) : null }': 'string',
101
+ 'function ( #0 ) { return #0 . @bool ( ) }': 'bool',
102
+ 'function ( #0 ) { return #0 . @u8 ( ) }': 'u8',
103
+ 'function ( #0 ) { return #0 . @float32 ( ) }': 'float32',
104
+ 'function ( #0 ) { return #0 . @float64 ( ) }': 'float64',
105
+ 'function ( #0 ) { return #0 . @uint16 ( ) }': 'uint16',
106
+ 'function ( #0 ) { #0 = #0 . @float64 ( ) ; return - 922336666814565 >= #0 ? @T:system.TimeSpan . #1 : 922336666814565 <= #0 ? @T:system.TimeSpan . #2 : new @T:system.TimeSpan ( #0 ) }': 'timespan',
107
+ 'function ( #0 ) { var #1 = #0 . @int32 ( ) ; return - 1 == #1 ? null : #0 . @raw ( #1 ) }': 'bytes',
108
+ 'function ( #0 , #1 ) { #0 = #0 . @int32 ( ) ; if ( - 1 == #0 ) return null ; for ( var #2 = [ ] , #3 = 0 ; #3 < #0 ; ) #2 . #4 ( #1 ( ) ) , ++ #3 ; return #2 }': 'list',
109
+ 'function ( #0 , #1 ) { #0 = #0 . @int32 ( ) ; if ( - 1 == #0 ) return null ; for ( var #2 = [ ] , #3 = 0 ; #3 < #0 ; ) #2 [ #3 ] = #1 ( ) , ++ #3 ; return #2 }': 'list',
110
+ 'function ( #0 , #1 , #2 ) { #0 = #0 . @int32 ( ) ; if ( - 1 == #0 ) return null ; for ( var #3 = new @T:system.collections.generic.Dictionary ( #0 ) , #4 = 0 ; #4 < #0 ; ) { var #5 = #1 ( ) ; @T:warlight.shared.Assert . #6 ( ! #3 . #7 ( #5 ) , "Dupe keys deserialized" ) ; #3 . #8 ( #5 , #2 ( ) ) ; ++ #4 } return #3 }': 'dict',
111
+ };
112
+ /** The date and guid helpers call a SharedUtility reader: matched by that helper's shape (see `utilityRole`). */
113
+ const UTILITY_CALL = 'function ( #0 ) { return @T:warlight.shared.SharedUtility . #1 ( #0 ) }';
114
+ /** v6.07's `P.uL`: a list into a client collection class (`new Je`), whose type name varies. */
115
+ const COLLECTION_LIST = /^function \( #0 , #1 \) \{ #0 = #0 \. @int32 \( \) ; if \( - 1 == #0 \) return null ; for \( var #2 = new (?:#\d+|@T:[\w.$]+) , #3 = 0 ; #3 < #0 ; \) #2 \. #\d+ \( #1 \( \) \) , \+\+ #3 ; return #2 \}$/;
116
+ /** SharedUtility's ParseLongSafe and TryGetValue-or-default (`O.fA`, `O.Fy`): identity in the built-in dialect. */
117
+ const UTILITY_IDENTITY_MARK = '"ParseLongSafe(null)"';
118
+ const UTILITY_TRY_GET = /^function \( #0 , #1 , #2 \) \{ var #3 = new @T:system\.CsRef \( null \) ; return #0 \. #4 \( #1 , #3 \) \? #3 \. #5 : #2 \}$/;
119
+ /** MessagePump's identity (`za.rc`). */
120
+ const IDENTITY = 'function ( #0 ) { return #0 }';
121
+ /** Enumerable's Select and ToArray (`E.Za`, `E.Sa`). */
122
+ const SELECT = 'function ( #0 , #1 ) { for ( var #2 = [ ] , #3 = 0 ; #3 < #0 . #4 ; ) { var #5 = #0 [ #3 ] ; ++ #3 ; #2 . #6 ( #1 ( #5 ) ) } return #2 }';
123
+ const TO_ARRAY = 'function ( #0 ) { for ( var #1 = [ ] , #2 = 0 ; #2 < #0 . #3 ; ) { var #4 = #0 [ #2 ] ; ++ #2 ; #1 . #5 ( #4 ) } return #1 }';
124
+ /** The source of the function expression starting at `at`, or undefined when it does not parse or is too long. */
125
+ function functionAt(src, at) {
126
+ try {
127
+ const end = Math.min(src.length, at + MAX_FN_SOURCE);
128
+ const node = parseExpressionAt(src.slice(0, end), at, { ecmaVersion: 'latest' });
129
+ if (node.type !== 'FunctionExpression')
130
+ return undefined;
131
+ return src.slice(at, node.end);
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ const esc = (s) => s.replace(/\$/g, '\\$');
138
+ /** `cls.name=function…` statics of a class: name → source (the first definition of each name). */
139
+ function staticsOf(src, cls) {
140
+ const out = new Map();
141
+ for (const m of src.matchAll(new RegExp(`(?<![\\w$.])${esc(cls)}\\.([\\w$]+)\\s*=\\s*(?=function\\b)`, 'g'))) {
142
+ if (out.has(m[1]))
143
+ continue;
144
+ const fn = functionAt(src, m.index + m[0].length);
145
+ if (fn)
146
+ out.set(m[1], fn);
147
+ }
148
+ return out;
149
+ }
150
+ /**
151
+ * The function-valued properties of `cls.prototype={…}` (or `cls.prototype=Fa(base.prototype,{…})`),
152
+ * name → source. Only the first prototype assignment of the class is read.
153
+ */
154
+ function prototypeOf(src, cls) {
155
+ const out = new Map();
156
+ const m = new RegExp(`(?<![\\w$.])${esc(cls)}\\.prototype\\s*=\\s*`).exec(src);
157
+ if (!m)
158
+ return out;
159
+ let at = m.index + m[0].length;
160
+ if (src[at] !== '{') {
161
+ // `Fa(base.prototype,{` — the object literal is the second argument.
162
+ const brace = src.indexOf('{', at);
163
+ if (brace < 0 || brace - at > 200)
164
+ return out;
165
+ at = brace;
166
+ }
167
+ let obj;
168
+ try {
169
+ obj = parseExpressionAt(src, at, { ecmaVersion: 'latest' });
170
+ }
171
+ catch {
172
+ return out;
173
+ }
174
+ if (obj.type !== 'ObjectExpression')
175
+ return out;
176
+ for (const p of obj.properties ?? []) {
177
+ if (p.type !== 'Property' || p.key.type !== 'Identifier' || !p.key.name)
178
+ continue;
179
+ if (p.value.type !== 'FunctionExpression' || p.value.end - p.value.start > MAX_FN_SOURCE)
180
+ continue;
181
+ out.set(p.key.name, src.slice(p.value.start, p.value.end));
182
+ }
183
+ return out;
184
+ }
185
+ /** Classify haxe.io.Input's methods by what they do. */
186
+ function inputRoles(methods) {
187
+ const roles = new Map();
188
+ let readByte;
189
+ for (const [name, fn] of methods) {
190
+ if (/methodName\s*:\s*"readByte"/.test(fn))
191
+ readByte = name;
192
+ }
193
+ if (!readByte)
194
+ return roles;
195
+ roles.set(readByte, 'readByte');
196
+ const calls = (fn, name) => fn.split(`this.${name}(`).length - 1;
197
+ let readInt32;
198
+ for (const [name, fn] of methods) {
199
+ if (name === readByte)
200
+ continue;
201
+ const bytes = calls(fn, readByte);
202
+ if (bytes === 4 && fn.includes('<<24')) {
203
+ readInt32 = name;
204
+ roles.set(name, 'readInt32');
205
+ }
206
+ else if (bytes === 2 && fn.includes('32768'))
207
+ roles.set(name, 'readInt16');
208
+ else if (bytes === 2)
209
+ roles.set(name, 'readUInt16');
210
+ }
211
+ if (readInt32) {
212
+ for (const [name, fn] of methods) {
213
+ if (roles.has(name))
214
+ continue;
215
+ const ints = calls(fn, readInt32);
216
+ if (ints === 2)
217
+ roles.set(name, 'readDouble');
218
+ else if (ints === 1)
219
+ roles.set(name, 'readFloat');
220
+ }
221
+ }
222
+ return roles;
223
+ }
224
+ const FROM_INPUT = {
225
+ readByte: 'u8',
226
+ readInt32: 'int32',
227
+ readInt16: 'int16',
228
+ readUInt16: 'uint16',
229
+ readFloat: 'float32',
230
+ readDouble: 'float64',
231
+ };
232
+ /** Classify the BinaryReader's methods by the Input method they call, or their own shape. */
233
+ function readerRoles(methods, input) {
234
+ const roles = new Map();
235
+ for (const [name, fn] of methods) {
236
+ if (fn.includes('"Bad format"') && /&127\)<</.test(fn))
237
+ roles.set(name, 'varint');
238
+ else if (/new [\w$]+\(new ArrayBuffer\(/.test(fn))
239
+ roles.set(name, 'raw');
240
+ else if (fn.includes('4294967296'))
241
+ continue; // the int64 read: no built-in
242
+ else {
243
+ const bool = /return\s*0\s*!=\s*this\.[\w$]+\.([\w$]+)\(\)/.exec(fn);
244
+ if (bool && input.get(bool[1]) === 'readByte') {
245
+ roles.set(name, 'bool');
246
+ continue;
247
+ }
248
+ const direct = /return\s+this\.[\w$]+\.([\w$]+)\(\)/.exec(fn);
249
+ const r = direct ? input.get(direct[1]) : undefined;
250
+ if (r)
251
+ roles.set(name, FROM_INPUT[r]);
252
+ }
253
+ }
254
+ // Self calls (`bc:function(){try{return this.JIb()}…}`) and the string read (varint then raw).
255
+ for (let pass = 0; pass < 3; pass++) {
256
+ for (const [name, fn] of methods) {
257
+ if (roles.has(name))
258
+ continue;
259
+ const own = [...fn.matchAll(/this\.([\w$]+)\(/g)].map((m) => m[1]).filter((n) => methods.has(n));
260
+ const ownRoles = own.map((n) => roles.get(n));
261
+ if (ownRoles.includes('varint') && ownRoles.includes('raw'))
262
+ roles.set(name, 'string');
263
+ else if (own.length === 1 && ownRoles[0] && /^function\(\)\{try\{return this\.[\w$]+\(\)\}/.test(fn))
264
+ roles.set(name, ownRoles[0]);
265
+ }
266
+ }
267
+ return roles;
268
+ }
269
+ /** The protocol version most of the bundle's readers default to (`null==d&&(d=243)`). */
270
+ export function bundleProtocol(src) {
271
+ const counts = new Map();
272
+ for (const m of src.matchAll(/null==([a-z])&&\(\1=(\d{3})\)/g)) {
273
+ const v = Number(m[2]);
274
+ counts.set(v, (counts.get(v) ?? 0) + 1);
275
+ }
276
+ let best;
277
+ let n = 0;
278
+ for (const [v, c] of counts) {
279
+ if (c > n) {
280
+ best = v;
281
+ n = c;
282
+ }
283
+ }
284
+ return n >= 3 ? best : undefined;
285
+ }
286
+ /**
287
+ * Derive the dialect from a bundle, or `null` when any required class or role cannot be found (the
288
+ * interpreter then uses its built-in names).
289
+ */
290
+ export function deriveDialect(bundle) {
291
+ const { src, typeNameOf, varOf } = bundle;
292
+ const inputVar = varOf.get(INPUT_TYPE);
293
+ const readerVar = varOf.get(READER_TYPE);
294
+ const serializer = varOf.get(SERIALIZER_TYPE);
295
+ if (!inputVar || !readerVar || !serializer)
296
+ return null;
297
+ const input = inputRoles(prototypeOf(src, inputVar));
298
+ const reader = readerRoles(prototypeOf(src, readerVar), input);
299
+ const readerMethods = {};
300
+ for (const [n, r] of reader)
301
+ readerMethods[n] = r;
302
+ const found = new Set(reader.values());
303
+ if (!REQUIRED_READER_ROLES.every((r) => found.has(r)))
304
+ return null;
305
+ const roleOf = (n) => reader.get(n);
306
+ const typeOf = (n) => typeNameOf.get(n);
307
+ const canon = (fn) => canonicalize(fn, roleOf, typeOf);
308
+ const statics = {};
309
+ const put = (cls, name, role) => {
310
+ (statics[cls] ??= {})[name] = role;
311
+ };
312
+ // The SharedUtility date and guid readers (P.Td → O.N3c, P.tL → O.Q3c): told apart by what they read.
313
+ const utility = varOf.get(UTILITY_TYPE);
314
+ const utilityStatics = utility ? staticsOf(src, utility) : new Map();
315
+ const utilityRole = (name) => {
316
+ const fn = utilityStatics.get(name);
317
+ if (!fn)
318
+ return undefined;
319
+ // A guid is 16 raw bytes; a date is one float64.
320
+ if (/@raw \( 16 \)/.test(canon(fn)) || /\(16\)/.test(fn))
321
+ return 'guid';
322
+ if (canon(fn).includes('@float64'))
323
+ return 'date';
324
+ return undefined;
325
+ };
326
+ for (const [name, fn] of staticsOf(src, serializer)) {
327
+ const c = canon(fn);
328
+ const role = SERIALIZER_TEMPLATES[c];
329
+ if (role)
330
+ put(serializer, name, role);
331
+ else if (COLLECTION_LIST.test(c))
332
+ put(serializer, name, 'list');
333
+ else if (c === UTILITY_CALL) {
334
+ const callee = /return [\w$]+\.([\w$]+)\(/.exec(fn)?.[1];
335
+ const r = callee ? utilityRole(callee) : undefined;
336
+ if (r)
337
+ put(serializer, name, r);
338
+ }
339
+ }
340
+ const roles = new Set(Object.values(statics[serializer] ?? {}));
341
+ if (!REQUIRED_STATIC_ROLES.every((r) => roles.has(r)))
342
+ return null;
343
+ if (utility) {
344
+ for (const [name, fn] of utilityStatics) {
345
+ if (fn.includes(UTILITY_IDENTITY_MARK) || UTILITY_TRY_GET.test(canon(fn)))
346
+ put(utility, name, 'identity');
347
+ }
348
+ }
349
+ const pump = varOf.get(PUMP_TYPE);
350
+ if (pump) {
351
+ for (const [name, fn] of staticsOf(src, pump))
352
+ if (canon(fn) === IDENTITY)
353
+ put(pump, name, 'identity');
354
+ }
355
+ const enumerable = varOf.get(ENUMERABLE_TYPE);
356
+ if (enumerable) {
357
+ for (const [name, fn] of staticsOf(src, enumerable)) {
358
+ if (name === 'Range')
359
+ put(enumerable, name, 'range');
360
+ else {
361
+ const c = canon(fn);
362
+ if (c === SELECT)
363
+ put(enumerable, name, 'select');
364
+ else if (c === TO_ARRAY)
365
+ put(enumerable, name, 'toArray');
366
+ }
367
+ }
368
+ }
369
+ const wrappers = WRAPPER_TYPES.map((t) => varOf.get(t)).filter((v) => v !== undefined);
370
+ return { readerMethods, statics, wrappers, serializer, protocol: bundleProtocol(src) };
371
+ }
@@ -77,6 +77,7 @@
77
77
  // and hoisted names it declares.
78
78
  import { parseExpressionAt, } from 'acorn';
79
79
  import { PROTOCOL_VERSION, ProtocolError, Reader } from './codec.js';
80
+ import { bundleProtocol, deriveDialect } from './dialect.js';
80
81
  /** A reader the interpreter cannot evaluate, or one that failed on the bytes. */
81
82
  export class InterpError extends Error {
82
83
  kind;
@@ -168,69 +169,119 @@ function list(r, item) {
168
169
  const f = callback(item);
169
170
  return asReader(r).list(() => f());
170
171
  }
171
- /** The names used by client v6.07 (protocol 242). */
172
- export const DEFAULT_DIALECT = {
172
+ /** The built-in natives for each reader-method role (`a.Tg()`). */
173
+ const READER_NATIVES = {
174
+ bool: (r) => r.bool(),
175
+ int32: (r) => r.int32(),
176
+ u8: (r) => r.u8(),
177
+ string: (r) => strBody(r),
178
+ // The client's 8-byte read is a float64 (its two int32 halves reassembled as a double), not an
179
+ // int64: kill rates, luck and TimeSpans (milliseconds) all arrive through it.
180
+ float64: (r) => r.float64(),
181
+ float32: (r) => r.float32(),
182
+ uint16: (r) => r.uint16(),
183
+ int16: (r) => r.int16(),
184
+ raw: (r, n) => {
185
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 0)
186
+ throw new InterpError('bad-value', `bad byte count ${String(n)}`);
187
+ return r.raw(n);
188
+ },
189
+ varint: (r) => r.varint(),
190
+ };
191
+ /** The built-in natives for each static-helper role (`P.Ya(a)`, `E.Za(xs, f)`, …). */
192
+ const STATIC_NATIVES = {
193
+ int32: (r) => asReader(r).int32(),
194
+ string: (r) => asReader(r).string(),
195
+ bool: (r) => asReader(r).bool(),
196
+ u8: (r) => asReader(r).u8(),
197
+ float32: (r) => asReader(r).float32(),
198
+ float64: (r) => asReader(r).float64(),
199
+ timespan: (r) => asReader(r).float64(),
200
+ date: (r) => asReader(r).date(),
201
+ guid: (r) => asReader(r).guid(),
202
+ uint16: (r) => asReader(r).uint16(),
203
+ bytes: (r) => readBytes(asReader(r)),
204
+ list,
205
+ dict: (r, k, v) => {
206
+ const fk = callback(k);
207
+ const fv = callback(v);
208
+ return asReader(r).list(() => [fk(), fv()]);
209
+ },
210
+ identity: (x) => x,
211
+ // Enumerable helpers (special-unit lists): Range → Select → ToArray.
212
+ range,
213
+ select: (xs, f) => {
214
+ const fn = callback(f);
215
+ return asArray(xs).map((x) => fn(x));
216
+ },
217
+ toArray: (xs) => [...asArray(xs)],
218
+ };
219
+ /** A derived (or built-in) dialect's names → roles, as the natives the interpreter calls. */
220
+ function dialectFrom(names) {
221
+ const readerMethods = {};
222
+ for (const [n, role] of Object.entries(names.readerMethods))
223
+ readerMethods[n] = READER_NATIVES[role];
224
+ const statics = {};
225
+ for (const [cls, fns] of Object.entries(names.statics)) {
226
+ statics[cls] = {};
227
+ for (const [n, role] of Object.entries(fns))
228
+ statics[cls][n] = STATIC_NATIVES[role];
229
+ }
230
+ return { readerMethods, statics, wrappers: [...names.wrappers] };
231
+ }
232
+ /**
233
+ * The names client v6.07.0.1 (protocol 242) used, by role: the fallback when a bundle's own names
234
+ * cannot be derived (`deriveDialect`), and the dialect of the test mini-bundles.
235
+ */
236
+ const V607_NAMES = {
173
237
  readerMethods: {
174
- Ua: (r) => r.bool(),
175
- Og: (r) => r.int32(),
176
- bc: (r) => r.u8(),
177
- FJ: (r) => strBody(r),
178
- // The client's 8-byte read is a float64 (its two int32 halves reassembled as a double), not an
179
- // int64: kill rates, luck and TimeSpans (milliseconds) all arrive through it.
180
- E3a: (r) => r.float64(),
181
- Om: (r) => r.float32(),
182
- NGb: (r) => r.uint16(),
183
- S3c: (r) => r.int16(),
184
- MGb: (r) => r.u8(),
185
- JS: (r, n) => {
186
- if (typeof n !== 'number' || !Number.isInteger(n) || n < 0)
187
- throw new InterpError('bad-value', `bad byte count ${String(n)}`);
188
- return r.raw(n);
189
- },
190
- I3c: (r) => r.varint(),
238
+ Ua: 'bool',
239
+ Og: 'int32',
240
+ bc: 'u8',
241
+ FJ: 'string',
242
+ E3a: 'float64',
243
+ Om: 'float32',
244
+ NGb: 'uint16',
245
+ S3c: 'int16',
246
+ MGb: 'u8',
247
+ JS: 'raw',
248
+ I3c: 'varint',
191
249
  },
192
250
  statics: {
193
251
  P: {
194
- Ya: (r) => asReader(r).int32(),
195
- wc: (r) => asReader(r).string(),
196
- Yc: (r) => asReader(r).bool(),
197
- uq: (r) => asReader(r).u8(),
198
- Ao: (r) => asReader(r).float32(),
199
- ak: (r) => asReader(r).float64(),
200
- uy: (r) => asReader(r).float64(),
201
- Td: (r) => asReader(r).date(),
202
- tL: (r) => asReader(r).guid(),
203
- Z5: (r) => asReader(r).uint16(),
204
- sL: (r) => readBytes(asReader(r)),
205
- Sd: list,
206
- ms: list,
207
- uL: list,
208
- ef: (r, k, v) => {
209
- const fk = callback(k);
210
- const fv = callback(v);
211
- return asReader(r).list(() => [fk(), fv()]);
212
- },
213
- },
214
- O: { fA: (x) => x, Fy: (x) => x, rc: (x) => x },
215
- za: { rc: (x) => x },
216
- // Enumerable helpers (special-unit lists): Range → Select → ToArray.
217
- E: {
218
- Range: range,
219
- Za: (xs, f) => {
220
- const fn = callback(f);
221
- return asArray(xs).map((x) => fn(x));
222
- },
223
- Sa: (xs) => [...asArray(xs)],
252
+ Ya: 'int32',
253
+ wc: 'string',
254
+ Yc: 'bool',
255
+ uq: 'u8',
256
+ Ao: 'float32',
257
+ ak: 'float64',
258
+ uy: 'timespan',
259
+ Td: 'date',
260
+ tL: 'guid',
261
+ Z5: 'uint16',
262
+ sL: 'bytes',
263
+ Sd: 'list',
264
+ ms: 'list',
265
+ uL: 'list',
266
+ ef: 'dict',
224
267
  },
268
+ O: { fA: 'identity', Fy: 'identity', rc: 'identity' },
269
+ za: { rc: 'identity' },
270
+ E: { Range: 'range', Za: 'select', Sa: 'toArray' },
225
271
  },
226
272
  wrappers: ['Z', 'Yb', 'uc', 'dc', 'oc', 'ec', 'fc'],
227
273
  };
228
- /** The class whose statics are the reader helpers (`P.Ya(a)`), checked by `verifyDialect`. */
274
+ /** The names used by client v6.07 (protocol 242): the fallback when a bundle's own names cannot be derived. */
275
+ export const DEFAULT_DIALECT = dialectFrom(V607_NAMES);
276
+ /** The Serializer roles every board count, flag and unit count is read through (see {@link REQUIRED_HELPERS}). */
277
+ const REQUIRED_ROLES = ['int32', 'bool', 'u8'];
278
+ /** The class whose statics are the reader helpers (`P.Ya(a)`) in the built-in dialect, checked by `verifyDialect`. */
229
279
  export const READER_HELPERS = 'P';
230
280
  /**
231
- * The helpers every board count, flag and unit count is read through (int32, bool, byte). A bundle
232
- * whose own definition of one of these cannot be verified is refused at load: an unverified one could
233
- * be a swapped same-width read, which decodes a wrong board without an error (#148).
281
+ * The helpers every board count, flag and unit count is read through (int32, bool, byte), in the
282
+ * built-in dialect. A bundle whose own definition of one of these cannot be verified is refused at
283
+ * load: an unverified one could be a swapped same-width read, which decodes a wrong board without an
284
+ * error (#148). A derived dialect names its own (`BundleInterpreter.requiredHelpers`), by role.
234
285
  */
235
286
  export const REQUIRED_HELPERS = ['Ya', 'Yc', 'uq'];
236
287
  /**
@@ -470,6 +521,14 @@ export class BundleInterpreter {
470
521
  opts;
471
522
  version;
472
523
  dialect;
524
+ /** The class whose statics are the reader helpers `verifyDialect` checks (the Serializer). */
525
+ helperClass;
526
+ /** The reader helpers that must verify for the bundle to load (int32, bool and byte, by role). */
527
+ requiredHelpers;
528
+ /** The dialect was derived from this bundle (false: the built-in v6.07 names). */
529
+ derived;
530
+ /** The protocol version the bundle's readers default to, when clear (`null==d&&(d=243)`). */
531
+ bundleProtocol;
473
532
  wrappers;
474
533
  /** Resolved functions by `Cls.fn` / `new Cls`: a hit, `null` (no constructor) or the cached failure. */
475
534
  fnCache = new Map();
@@ -500,12 +559,30 @@ export class BundleInterpreter {
500
559
  this.maxDepth = opts.maxDepth ?? DEFAULT_MAX_DEPTH;
501
560
  this.maxMillis = opts.maxMillis ?? DEFAULT_MAX_MILLIS;
502
561
  this.now = opts.now ?? (() => performance.now());
503
- const d = opts.dialect ?? {};
504
- this.dialect = {
505
- readerMethods: { ...DEFAULT_DIALECT.readerMethods, ...d.readerMethods },
506
- statics: { ...DEFAULT_DIALECT.statics, ...d.statics },
507
- wrappers: d.wrappers ?? DEFAULT_DIALECT.wrappers,
508
- };
562
+ // The bundle's own names, derived from its structure (every build renames them: #340); the
563
+ // built-in v6.07 names when they cannot be, or when the caller gives a dialect (the tests' mini-bundles).
564
+ const derived = opts.dialect ? null : deriveDialect(bundle);
565
+ if (derived) {
566
+ this.dialect = dialectFrom(derived);
567
+ this.helperClass = derived.serializer;
568
+ const helpers = derived.statics[derived.serializer] ?? {};
569
+ this.requiredHelpers = Object.keys(helpers)
570
+ .filter((n) => REQUIRED_ROLES.includes(helpers[n]))
571
+ .sort();
572
+ this.derived = true;
573
+ }
574
+ else {
575
+ const d = opts.dialect ?? {};
576
+ this.dialect = {
577
+ readerMethods: { ...DEFAULT_DIALECT.readerMethods, ...d.readerMethods },
578
+ statics: { ...DEFAULT_DIALECT.statics, ...d.statics },
579
+ wrappers: d.wrappers ?? DEFAULT_DIALECT.wrappers,
580
+ };
581
+ this.helperClass = READER_HELPERS;
582
+ this.requiredHelpers = REQUIRED_HELPERS;
583
+ this.derived = false;
584
+ }
585
+ this.bundleProtocol = derived ? derived.protocol : bundleProtocol(bundle.src);
509
586
  this.wrappers = new Set(this.dialect.wrappers);
510
587
  }
511
588
  /** The class var for a registered type name, or the argument itself if it is a var. */
@@ -573,18 +650,18 @@ export class BundleInterpreter {
573
650
  verifyDialect() {
574
651
  const out = { verified: [], unverified: [], mismatched: [] };
575
652
  const reasons = {};
576
- const natives = Object.hasOwn(this.dialect.statics, READER_HELPERS) ? this.dialect.statics[READER_HELPERS] : {};
653
+ const natives = Object.hasOwn(this.dialect.statics, this.helperClass) ? this.dialect.statics[this.helperClass] : {};
577
654
  // The bundle's definitions run like any interpreted code: contained, and under one step budget
578
655
  // shared by the whole check, so a hostile bundle cannot spend more than one read's worth here.
579
656
  // Past the budget, a probe is unevaluable (the helper unverified), never a mismatch.
580
657
  const budget = { spent: 0 };
581
- const forms = this.helperForms(READER_HELPERS, Object.keys(natives), budget);
658
+ const forms = this.helperForms(this.helperClass, Object.keys(natives), budget);
582
659
  // The required helpers are probed first: a runaway definition of another cannot spend the budget
583
660
  // they need. Object literals assigned to P are parsed under a bound of their own (see helperForms).
584
- const order = [...forms.keys()].sort((a, b) => Number(REQUIRED_HELPERS.includes(b)) - Number(REQUIRED_HELPERS.includes(a)) || (a < b ? -1 : 1));
661
+ const order = [...forms.keys()].sort((a, b) => Number(this.requiredHelpers.includes(b)) - Number(this.requiredHelpers.includes(a)) || (a < b ? -1 : 1));
585
662
  for (const name of order) {
586
663
  const native = natives[name];
587
- const key = `${READER_HELPERS}.${name}`;
664
+ const key = `${this.helperClass}.${name}`;
588
665
  let mismatch = false;
589
666
  let why;
590
667
  for (const form of forms.get(name)) {
@@ -627,14 +704,14 @@ export class BundleInterpreter {
627
704
  // and the built-in would decode every read through it unchecked. Absent from the check is not
628
705
  // verified (#148).
629
706
  const src = this.bundle.src;
630
- const esc = READER_HELPERS.replace(/\$/g, '\\$');
631
- for (const name of REQUIRED_HELPERS) {
707
+ const esc = this.helperClass.replace(/\$/g, '\\$');
708
+ for (const name of this.requiredHelpers) {
632
709
  if (forms.has(name) || !Object.hasOwn(natives, name))
633
710
  continue;
634
711
  const ref = new RegExp(`(?<![\\w$.])${esc}\\s*(?:\\.\\s*${name}(?![\\w$])|\\[\\s*(["'\`])${name}\\1\\s*\\])`);
635
712
  if (!ref.test(src))
636
713
  continue;
637
- const key = `${READER_HELPERS}.${name}`;
714
+ const key = `${this.helperClass}.${name}`;
638
715
  out.unverified.push(key);
639
716
  reasons[key] = 'the bundle reads through it, but no definition was found in a form this check can follow';
640
717
  }