Repository navigation
Expand file tree
/
Copy pathprotocolEngine.js
More file actions
2825 lines (2824 loc) · 216 KB
/
Copy pathprotocolEngine.js
File metadata and controls
2825 lines (2824 loc) · 216 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Generic binary protocols, shared by classic scripts and CommonJS.
*
* compile(JSON schema) validates and returns { schema, id, messages, diagnostics }.
* Schema: {id,endian,framing:{header,footer,fixedLength,length:{offset,type,
* adjustment,unit},maxLength},headerFields,command:{offset,type},payloadOffset,
* payloadEnd,checksums,structures,messages}. Negative byte positions count from
* frame end; all end positions are exclusive. Length field * unit + adjustment
* gives the whole frame length; unit defaults to 1 and must divide encoded wire
* length exactly. Checksum ranges exclude their own storage explicitly.
* Fields: {id,name,type,endian,offset,count,length,encoding,enum,baseType,ref,
* fields,bits,condition,default}. Offsets are relative to their containing struct.
* Structures are arrays of fields. count turns any field into an array. bits are
* named slices {name,offset,length,type:'bool'|'int'|'uint',enum}. Dynamic count,
* offset, length and condition expressions accept numbers, field paths,
* FRAME_LENGTH/PAYLOAD_LENGTH/REMAINING, arithmetic, comparisons, bit operators and
* MIN/MAX/ABS/LEN; LEN uses encoded field byte spans, never element/string counts.
* No JavaScript is evaluated. Dispatch is {field,offset,name,messages}
* and recursively selects a child message by its command (or commandRange).
* reserved fields behave as bytes with zero padding by default; they retain
* their Uint8Array and byte span and never expose a numeric value.
* Version 2 adds fixed {bytes,framingRole:'sync'|'end'}, bounded struct {length},
* choice {selector,branches:[{equals|range|mask|expression|default,fields}]},
* repeat {count|until:'end',fields,length?}, and configurable tlv
* {headerFields,lengthField,lengthIncludesHeader,lengthUnit,lengthAdjustment,
* selector,branches,count|until:'end',invalidItem:'stop'|'skip'} nodes. A TLV
* length bounds its entire container; the header's lengthField bounds each V.
* Unknown TLV V is retained in rawPayload. invalidItem defaults to stop; skip
* requires a validated item end. Segment leftover is preserve (default), exact,
* or padding with paddingByte. Bounded repeat container tails live in the
* parent's _segmentTails[nodeName], keeping item arrays JSON serializable.
* Offsets use offsetBase:'segment' (default) or
* 'frame'; PARENT/CURRENT paths and PARENT_REMAINING expose explicit scopes.
* Fixed framing bindings are derived into compiled.framing, never persisted
* into canonical schema.framing. label is display text; id remains identity.
* Version 3 uses messages:[oneWholeFrame] and framing:{maxLength} only. Every
* field declares byteLength; 0 requires lengthSource:{fieldId,unit,adjustment},
* lengthFrom (safe expression, REMAINING, or contents for containers), or
* boundary:{startFieldId?,endFieldId} referring to adjacent fixed fields.
* Root byteLength/lengthSource/lengthFrom bounds the frame; fixed framing roles derive
* synchronization/end delimiters. type:checksum stores its own 1/2/4 bytes and
* checksum:{type,...,start,end} accepts field-ID edges or position expressions.
* Stable legacy message aliases keep existing send/mapping identities during
* migration; the canonical new structure has no parallel legacy rule sources.
*
* decode(bytes,compiled) returns typed fields, flat path->value values, an ARRAY
* flatFields of {fieldId,path,value,numeric,byteOffset,endByte,bitOffset?,bitLength?},
* spans, warnings, known, messageId/name, command, header, rawPayload. uint64/int64
* are always BigInt. numeric is null when precision cannot safely be retained.
* Unrecognized tail bytes live in fields._unknownTail; unknown messages preserve
* fields.rawPayload. Warning entries are {code,message,...}. Bad framing or
* checksums throw ProtocolError. Valid but short known layouts produce warnings.
* Any incomplete/ambiguous/boundary failure sets valid:false and suppresses all
* flatFields.numeric outputs. analyze(schema) returns nonthrowing diagnostics;
* selectBranch(sourceOrCompiledNode,context) shares exact condition semantics.
* decode's optional third argument {maxFields} sets a hard output field budget.
* encode(compiled,messageId,fields,{sequence,layout,header}) returns Uint8Array.
* Conflicted messages require layout:'detail' (or a declared layout name).
* StreamParser uses DataParser callback signatures and reports each received byte
* exactly once as a valid frame or discarded/error byte. Source offsets and
* timestamps follow each frame's first byte, including across appendData blocks.
* StreamParser options/properties: deferDecode finds validated boundaries and
* emits a {deferred:true,...} placeholder after framing and static fixed checks.
* Dynamic layout validity is resolved in the worker; invalid layouts retain
* their frame bytes. maxDecodedFields bounds live decoded output.
* createFactorySource() exposes trusted engine code for embedding in a classic
* Blob worker; user schemas remain data passed through compile's safe parser.
*/
(function createProtocolEngine(root, codecOverride, reservedOverride, symbolsOverride) {
'use strict';
const LEN_CONTEXT = Symbol('protocol-wire-length');
const RULE_LENGTHS = Symbol('constraint-wire-lengths');
const LENGTH_BOUNDARY = Symbol('expression-length-boundary');
const LENGTH_CURSOR = Symbol('expression-length-cursor');
const textCodec = codecOverride || (typeof module !== 'undefined' && module.exports
? require('./textCodec') : root.SerialPlotter?.TextCodec);
const reservedNames = reservedOverride || (typeof module !== 'undefined' && module.exports
? require('./reservedNames').ReservedNames : root.SerialPlotter.ReservedNames);
const protocolSymbols = symbolsOverride || (typeof module !== 'undefined' && module.exports
? require('./protocolSymbols').ProtocolSymbols : root.SerialPlotter.ProtocolSymbols);
const LIMITS = Object.freeze({ frame: 1024 * 1024, fields: 8192, array: 4096,
depth: 16, expression: 256, messages: 2048 });
const FORBIDDEN = new Set(['__proto__', 'prototype', 'constructor']);
const legacyEncodingMaps = new Map();
const compiledProtocols = new WeakSet();
const TYPES = Object.freeze({ uint8: [1, 'getUint8', 'setUint8'], int8: [1, 'getInt8', 'setInt8'],
uint16: [2, 'getUint16', 'setUint16'], int16: [2, 'getInt16', 'setInt16'],
uint32: [4, 'getUint32', 'setUint32'], int32: [4, 'getInt32', 'setInt32'],
uint64: [8, 'getBigUint64', 'setBigUint64'], int64: [8, 'getBigInt64', 'setBigInt64'],
float32: [4, 'getFloat32', 'setFloat32'], float64: [8, 'getFloat64', 'setFloat64'],
bool: [1, 'getUint8', 'setUint8'] });
class ProtocolError extends Error {
constructor(code, message, details = {}) { super(message); this.name = 'ProtocolError';
this.code = code; Object.assign(this, details); }
}
function fail(code, message, details = {}) { throw new ProtocolError(code, message, details); }
function bytesOf(bytes) {
if (bytes instanceof Uint8Array) return bytes;
if (ArrayBuffer.isView(bytes)) return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (bytes instanceof ArrayBuffer) return new Uint8Array(bytes);
return Uint8Array.from(bytes || []);
}
function encodeBytes(value, path) {
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return bytesOf(value);
if (!Array.isArray(value) || value.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255))
fail('value', `Invalid byte sequence: ${path}`);
return Uint8Array.from(value);
}
function safeName(name) {
return typeof name === 'string' && /^[A-Za-z_$][\w$]*$/.test(name) && !FORBIDDEN.has(name);
}
function lookup(object, path) {
if (Object.hasOwn(object, path)) return object[path];
const parts = path.replace(/\[(\d+)\]/g, '.$1').split('.');
let current = object;
for (const part of parts) {
if (FORBIDDEN.has(part) || current === null || current === undefined ||
!Object.hasOwn(Object(current), part)) return undefined;
current = current[part];
}
return current;
}
const PRECEDENCE = { '||': 1, '&&': 2, '|': 3, '^': 4, '&': 5,
'==': 6, '!=': 6, '===': 6, '!==': 6, '<': 7, '>': 7, '<=': 7, '>=': 7,
'<<': 8, '>>': 8, '>>>': 8, '+': 9, '-': 9, '*': 10, '/': 10, '%': 10 };
function expression(source) {
if (source === undefined || typeof source === 'number' || typeof source === 'boolean') {
if (typeof source === 'number' && !Number.isFinite(source)) fail('schema', 'Invalid expression number');
return { literal: source };
}
if (typeof source !== 'string' || source.length > LIMITS.expression)
fail('schema', 'Expression exceeds safe length limit');
const tokens = [], pattern = /\s*(0x[\da-f]+|(?:\d+(?:\.\d*)?|\.\d+)|[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[\d+\])*|>>>|===|!==|<<|>>|<=|>=|==|!=|&&|\|\||[()+\-*/%<>&^|!~,])/igy;
let position = 0;
while (position < source.trimEnd().length) {
pattern.lastIndex = position;
const match = pattern.exec(source);
if (!match) fail('schema', `Unsafe expression: ${source}`);
const token = match[1];
if (token.split(/[.\[\]]/).some(part => FORBIDDEN.has(part)))
fail('schema', `Unsafe expression identifier: ${token}`);
tokens.push(token); position = pattern.lastIndex;
if (tokens.length > 128) fail('schema', 'Expression token limit exceeded');
}
let index = 0, depth = 0;
function parse(minimum = 0) {
if (++depth > 32) fail('schema', 'Expression nesting limit exceeded');
const token = tokens[index++]; let node;
if (token === '(') { node = parse(); if (tokens[index++] !== ')') fail('schema', 'Unclosed expression'); }
else if (['+', '-', '!', '~'].includes(token)) node = { op: token, unary: parse(11) };
else if (/^(?:\d|\.)/.test(token || '')) node = { literal: !token.includes('.') && !Number.isSafeInteger(Number(token)) ? BigInt(token) : Number(token) };
else if (/^[A-Za-z_$]/.test(token || '')) {
if (tokens[index] === '(') {
if (!reservedNames.protocolFunctions.includes(token)) fail('schema', `Unsafe expression function: ${token}`);
index++; const args = [];
if (tokens[index] !== ')') { args.push(parse()); while (tokens[index] === ',') { index++; args.push(parse()); } }
if (tokens[index++] !== ')' || args.length < 1 || args.length > 8 || token === 'ABS' && args.length !== 1)
fail('schema', 'Invalid expression function arguments');
if (token === 'LEN' && (args.length !== 1 || !args[0].variable || reservedNames.protocolVariables.includes(args[0].variable)))
fail('expression', 'LEN 需要一个字段或数据段路径,例如 LEN(payload)');
node = { fn: token, args };
} else node = { variable: token };
} else fail('schema', `Invalid expression: ${source}`);
while (Object.hasOwn(PRECEDENCE, tokens[index]) && PRECEDENCE[tokens[index]] >= minimum) {
const op = tokens[index++]; node = { op, left: node, right: parse(PRECEDENCE[op] + 1) };
}
depth--; return node;
}
const tree = parse();
if (index !== tokens.length) fail('schema', `Invalid expression: ${source}`);
return tree;
}
function evaluate(tree, context) {
if (Object.hasOwn(tree, 'literal')) return tree.literal;
if (tree.lengthChoice) {
const branch = chooseBranch(tree.lengthChoice, context);
if (!branch) fail('length-reference', 'LEN 的数据段没有匹配的条件分支');
return evaluate(branch.lengthTree, context);
}
if (tree.variable) {
if (tree.variable === 'TRUE') return true;
if (tree.variable === 'FALSE') return false;
const value = lookup(context, tree.variable);
if (value === undefined) fail('expression', `Unknown expression identifier: ${tree.variable}`);
if (!['bigint', 'number', 'boolean'].includes(typeof value)) fail('expression', 'Expression requires a scalar');
return value;
}
if (tree.fn === 'LEN') {
if (!context[LEN_CONTEXT]) fail('length-reference', 'LEN 需要协议字段的实际编码字节范围,不能按数组元素数或字符数推测');
return context[LEN_CONTEXT](tree.args[0].variable);
}
if (tree.fn) { const args = tree.args.map(arg => evaluate(arg, context));
if (tree.fn === 'ABS') return args[0] < 0 ? -args[0] : args[0];
return args.reduce((a, b) => tree.fn === 'MIN' ? (a < b ? a : b) : (a > b ? a : b)); }
if (tree.unary) {
const value = evaluate(tree.unary, context);
return tree.op === '-' ? -value : tree.op === '+' ? value : tree.op === '!' ? !value : ~value;
}
let a = evaluate(tree.left, context);
if (tree.op === '&&' && !a || tree.op === '||' && a) return a;
let b = evaluate(tree.right, context);
if (['/', '%'].includes(tree.op) && (b === 0 || b === 0n)) fail('expression', 'Division by zero');
if (typeof a === 'bigint' || typeof b === 'bigint') {
if (typeof a !== 'bigint' && Number.isSafeInteger(a)) a = BigInt(a);
if (typeof b !== 'bigint' && Number.isSafeInteger(b)) b = BigInt(b);
if (typeof a !== typeof b && !['<','>','<=','>=','==','!=','===','!==','&&','||'].includes(tree.op))
fail('expression', 'Cannot mix an exact integer with a fractional value');
if (tree.op === '>>>') fail('expression', 'Unsigned shift is undefined for exact integers');
if (['/','%'].includes(tree.op) && b === 0n) fail('expression', 'Division by zero');
}
switch (tree.op) {
case '+': return a + b; case '-': return a - b; case '*': return a * b;
case '/': return a / b; case '%': return a % b; case '<<': return a << b;
case '>>': return a >> b; case '>>>': return a >>> b; case '&': return a & b;
case '|': return a | b; case '^': return a ^ b; case '==': case '===': return a === b;
case '!=': case '!==': return a !== b; case '<': return a < b; case '>': return a > b;
case '<=': return a <= b; case '>=': return a >= b; case '&&': return a && b; case '||': return a || b;
default: fail('expression', 'Unsupported expression operator');
}
}
function bounded(value, maximum, label, minimum = 0) {
if (typeof value === 'bigint' && value >= BigInt(minimum) && value <= BigInt(maximum)) value = Number(value);
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
fail('bounds', `${label} is outside the allowed range ${minimum}–${maximum}`);
return value;
}
function lengthScope(lengths, prefix, parent, fields) {
const names = new Set(fields.map(field => field.name));
return path => {
if (path.startsWith('PARENT.')) {
if (parent) return parent(path.slice(7));
} else {
const current = path.startsWith('CURRENT.'), name = current ? path.slice(8) : path;
const key = prefix ? prefix + '.' + name : name;
if (lengths.has(key)) return lengths.get(key);
if (!current && !names.has(name.split(/[.[]/)[0]) && parent) return parent(name);
}
fail('length-reference', `LEN(${path}) 的字段尚未读取、未启用或没有确定的字节范围`);
};
}
function little(field, compiled) {
const order = field.endian ?? compiled.schema.endian ?? 'little';
return order === 'little' || order === 'le';
}
function baseType(field) { return field.type === 'checksum' ? 'uint' + field.byteLength * 8 : field.type === 'enum' ? field.baseType || 'uint8' : field.type; }
function scalarWidth(field) { return field.type === 'bitfield' ? field.byteLength : TYPES[baseType(field)]?.[0]; }
function elementRepeatToEnd(field) { return field.until === 'end' && !['repeat','tlv'].includes(field.type); }
function repeatedItemLength(field, context, index, start, end, maxLength, fallback) {
return field.expressions.length ? bounded(evaluate(field.expressions.length,{...context,INDEX:index,REMAINING:end-start}),maxLength,'Field length') : fallback;
}
function numeric(value) {
if (typeof value === 'boolean') return Number(value);
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
if (typeof value === 'bigint') { const num = Number(value); return Number.isSafeInteger(num) ? num : null; }
return null;
}
function cloneJSON(source) {
let json;
try { json = JSON.stringify(source); } catch { fail('schema', 'Protocol schema must be JSON serializable'); }
if (!json || json.length > 2 * LIMITS.frame) fail('schema', 'Protocol schema exceeds size limit');
return JSON.parse(json);
}
function compile(input) {
if (input && typeof input === 'object' && compiledProtocols.has(input)) return input;
const { schema, renames: symbolRenames } = migrateSymbols(input?._compiledProtocol === true && input.schema ? input.schema : input);
if (typeof schema.id !== 'string' || !schema.id.trim()) fail('schema', 'Protocol requires a stable id');
if (!Array.isArray(schema.messages) || !schema.messages.length) fail('schema', 'Protocol requires messages');
const compiled = { _compiledProtocol: true, schema, id: schema.id, messages: [], diagnostics: [], unified: schema.schemaVersion >= 3,
usesLengthFunction: /\bLEN\s*\(/.test(JSON.stringify(schema)),
messageById: new Map(), layoutWrites: [], symbolRenames, maxLength: schema.framing?.maxLength ?? LIMITS.frame, fieldCount: 0 };
bounded(compiled.maxLength, LIMITS.frame, 'Frame length limit', 1);
const framing = schema.framing ||= {};
compiled.framing = { ...framing };
for (const key of ['header', 'footer']) {
if (framing[key] !== undefined && (!Array.isArray(framing[key]) || framing[key].length > 64 ||
framing[key].some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)))
fail('schema', `Invalid framing ${key}`);
}
if (framing.fixedLength) bounded(framing.fixedLength, compiled.maxLength, 'Fixed frame length', 1);
function validateScalar(field, label) {
if (!TYPES[field.type] || !/^uint(?:8|16|32)$/.test(field.type)) fail('schema', `Invalid ${label} type`);
bounded(field.offset, compiled.maxLength, `${label} offset`);
}
if (framing.length) { validateScalar(framing.length, 'Length field');
bounded(framing.length.unit ?? 1, LIMITS.frame, 'Length unit', 1);
if (!Number.isSafeInteger(framing.length.adjustment ?? 0)) fail('schema', 'Invalid length adjustment'); }
if (schema.command) validateScalar(schema.command, 'Command field');
bounded(schema.payloadOffset ?? 0, compiled.maxLength, 'Payload offset');
if (schema.payloadEnd !== undefined && (!Number.isSafeInteger(schema.payloadEnd) ||
Math.abs(schema.payloadEnd) > compiled.maxLength)) fail('schema', 'Invalid payload end');
if (schema.endian && !['little', 'big', 'le', 'be'].includes(schema.endian)) fail('schema', 'Invalid protocol endian');
// Save generated identities in canonical JSON so later label/name edits
// retain mappings. Reusable structure leaves gain an instance prefix.
const identities = new Set();
function identity(value, fallback) {
const id = value || fallback;
if (typeof id !== 'string' || !id || id.length > 512 || identities.has(id))
fail('schema', `Invalid or duplicate stable id: ${id}`);
identities.add(id); return id;
}
function stampFields(fields, scope, depth = 0, metadata = false) {
if (!Array.isArray(fields) || depth > LIMITS.depth) fail('schema', 'Invalid fields or structure nesting limit');
for (const source of fields) {
if (!source || typeof source !== 'object') fail('schema', 'Invalid field definition');
source.id = identity(source.id, `${scope}.${source.name}`);
const conflict = reservedNames.error(source.name, 'field');
if (conflict && !(metadata && source.name === 'rawPayload' && source.type === 'bytes')) fail('reserved-name', conflict, { nodeId: source.id });
if (source.bits) {
if (!Array.isArray(source.bits)) fail('schema', 'Invalid bit fields');
for (const bit of source.bits) {
bit.id = identity(bit.id, `${source.id}.${bit.name}`);
const conflict = reservedNames.error(bit.name, 'field');
if (conflict) fail('reserved-name', conflict, { nodeId: bit.id });
}
}
if (source.fields) stampFields(source.fields, source.id, depth + 1);
if (source.headerFields) stampFields(source.headerFields, `${source.id}.header`, depth + 1);
if (source.branches) {
if (!Array.isArray(source.branches)) fail('schema', 'Invalid branches', { nodeId: source.id });
source.branches.forEach((branch, i) => { branch.id = identity(branch.id, `${source.id}.branch${i}`);
stampFields(branch.fields || [], branch.id, depth + 1, !!branch.legacyUnknown); });
}
}
}
function stampMessages(messages, scope, depth = 0) {
if (!Array.isArray(messages) || depth > LIMITS.depth) fail('schema', 'Invalid nested messages');
for (const message of messages) {
message.id = identity(message.id, `${scope}.${message.command}`);
stampFields(message.fields || [], message.id);
if (message.dispatch) stampMessages(message.dispatch.messages, message.id, depth + 1);
}
}
stampFields(schema.headerFields || [], `${schema.id}.header`);
for (const [name, fields] of Object.entries(schema.structures || {})) {
if (!safeName(name)) fail('schema', 'Invalid structure name');
stampFields(fields, `${schema.id}.structures.${name}`);
}
stampMessages(schema.messages, schema.id);
function fieldsOf(fields, scope, stack = [], instancePrefix = '', inheritedEndian = schema.endian, metadata = false, instanceReferences = new Map()) {
if (!Array.isArray(fields)) fail('schema', `Fields must be an array: ${scope}`);
if (stack.length > LIMITS.depth) fail('schema', 'Structure nesting limit exceeded');
const names = new Set();
return fields.map(source => {
if (++compiled.fieldCount > LIMITS.fields) fail('schema', 'Field count limit exceeded');
if (!safeName(source.name) || names.has(source.name)) fail('schema', `Invalid or duplicate field name: ${source.name}`);
const conflict = reservedNames.error(source.name, 'field');
if (conflict && !(metadata && source.name === 'rawPayload' && source.type === 'bytes')) fail('reserved-name', conflict, { nodeId: source.id });
names.add(source.name);
try {
const field = { ...source, endian: source.endian ?? inheritedEndian, id: `${instancePrefix}${source.id}`, expressions: {} };
if (source.lengthSource) field.lengthSource = { ...source.lengthSource,
fieldId: instanceReferences.get(source.lengthSource.fieldId) ?? source.lengthSource.fieldId };
if (!TYPES[baseType(field)] && !['bytes', 'reserved', 'string', 'struct', 'choice', 'repeat', 'tlv', 'fixed', 'bitfield'].includes(field.type))
fail('schema', `Unsupported field type: ${field.type}`);
if (field.type === 'bitfield') bounded(field.byteLength, compiled.maxLength, 'Bit group byte length', 1);
if (field.valueSource !== undefined && (field.valueSource !== 'SEQ' || !/^uint(?:8|16|32)$/.test(baseType(field)) || field.count !== undefined || field.until !== undefined))
fail('schema', 'Sequence valueSource requires SEQ and an unsigned scalar', { nodeId: field.id });
if (field.endian && !['little', 'big', 'le', 'be'].includes(field.endian)) fail('schema', 'Invalid field endian');
for (const prop of ['offset', 'count', 'length', 'condition']) if (field[prop] !== undefined)
field.expressions[prop] = expression(field[prop]);
if (typeof field.count === 'number') bounded(field.count, LIMITS.array, 'Array count');
for (const prop of ['offset', 'length']) if (typeof field[prop] === 'number') bounded(field[prop], compiled.maxLength, `Field ${prop}`);
if (field.ref) {
if (stack.includes(field.ref)) fail('schema', `Cyclic structure reference: ${field.ref}`);
if (!Object.hasOwn(schema.structures || {}, field.ref)) fail('schema', `Unknown structure: ${field.ref}`);
const references = new Map(instanceReferences), prefix = `${field.id}/`;
const register = fields => {
for (const item of fields || []) {
references.set(item.id, prefix + item.id);
register(item.fields); register(item.headerFields);
for (const branch of item.branches || []) register(branch.fields);
}
};
register(schema.structures[field.ref]);
field.fields = fieldsOf(schema.structures[field.ref], field.id, [...stack, field.ref], prefix, field.endian, false, references);
} else if (['struct', 'repeat'].includes(field.type)) field.fields = fieldsOf(field.fields || [], field.id, [...stack, field.id], instancePrefix, field.endian, false, instanceReferences);
if (field.leftover && !['preserve','exact','padding'].includes(field.leftover)) fail('schema', 'Invalid leftover policy', { nodeId: field.id });
if (field.paddingByte !== undefined) bounded(field.paddingByte, 255, 'Padding byte');
if (field.invalidItem && !['stop','skip'].includes(field.invalidItem)) fail('schema', 'Invalid TLV item failure policy', { nodeId: field.id });
if (field.offsetBase && !['segment', 'frame'].includes(field.offsetBase)) fail('schema', 'Invalid offset base', { nodeId: field.id });
if (field.type === 'fixed') {
field.bytes = Array.from(encodeBytes(field.bytes, field.name));
if (!field.bytes.length) fail('schema', 'Fixed bytes must not be empty', { nodeId: field.id });
}
if (field.expectedBytes) field.expectedBytes = Array.from(encodeBytes(field.expectedBytes, field.name));
if (field.displayBase !== undefined && !['dec','hex'].includes(field.displayBase))
fail('schema', 'Number base must be dec or hex', { nodeId: field.id });
if (field.displayBase === undefined && (['fixed','bytes','reserved'].includes(field.type) || field.expectedBytes)) field.displayBase = 'hex';
if (field.selector !== undefined) field.selectorExpression = expression(field.selector);
if (['choice', 'tlv'].includes(field.type)) {
field.branches = (field.branches || []).map(branch => ({ ...branch,
fields: fieldsOf(branch.fields || [], branch.id, [...stack, field.id], instancePrefix, field.endian, !!branch.legacyUnknown, instanceReferences),
expressionTree: branch.expression === undefined ? null : expression(branch.expression) }));
validateBranches(field, compiled);
}
if (field.type === 'tlv') {
field.headerFields = fieldsOf(field.headerFields || [], `${field.id}.header`, [...stack, field.id], instancePrefix, field.endian, false, instanceReferences);
if (!safeName(field.lengthField) || !field.headerFields.some(item => item.name === field.lengthField && /^uint(8|16|32)$/.test(baseType(item))))
fail('schema', 'TLV lengthField must reference an unsigned header scalar', { nodeId: field.id });
bounded(field.lengthUnit ?? 1, LIMITS.frame, 'TLV length unit', 1);
if (!Number.isSafeInteger(field.lengthAdjustment ?? 0)) fail('schema', 'Invalid TLV adjustment', { nodeId: field.id });
}
if (['repeat', 'tlv'].includes(field.type)) {
if (field.until !== undefined && field.until !== 'end' || field.count !== undefined && field.until !== undefined)
fail('schema', 'Repeat requires either count or until:end', { nodeId: field.id });
if (field.count === undefined && field.until !== 'end') fail('schema', 'Repeat requires a count or until:end', { nodeId: field.id });
if (minimumSize(field.type === 'tlv' ? field.headerFields : field.fields) === 0)
fail('progress', 'Repeated item must make positive byte progress', { nodeId: field.id });
}
if(field.until!==undefined&&!['repeat','tlv'].includes(field.type)){
if(field.until!=='end'||field.count!==undefined)
fail('schema','Repeat requires either count or until:end',{nodeId:field.id});
if (field.framingRole) fail('boundary','帧头或帧尾字段必须是单个固定字段,不能重复至段末',{nodeId:field.id});
if (field.type === 'checksum') fail('boundary','校验值字段需要单项覆盖范围;请放入结构体后重复该结构体',{nodeId:field.id});
if (field.inline || field.legacyOverlay) fail('boundary','内联或覆盖字段不能重复至段末,请先改为独立数据段',{nodeId:field.id});
}
if (field.type === 'string' && textCodec) textCodec.normalizeTextEncoding(field.encoding || 'utf-8');
if (field.bits) {
if (!Array.isArray(field.bits) || field.type !== 'bitfield' && !/^u?int(?:8|16|32|64)$/.test(baseType(field))) fail('schema', 'Bit slices require an integer field');
const bits = new Set(), ranges = [], totalBits = scalarWidth(field) * 8;
field.bits = field.bits.map(bit => {
if (!safeName(bit.name) || bits.has(bit.name)) fail('schema', 'Invalid or duplicate bit field name');
const conflict = reservedNames.error(bit.name, 'field');
if (conflict) fail('reserved-name', conflict, { nodeId: bit.id });
bits.add(bit.name); bounded(bit.offset, totalBits - 1, 'Bit offset');
bounded(bit.length, totalBits - bit.offset, 'Bit length', 1);
if (bit.type !== undefined && !['uint', 'int', 'bool', 'reserved'].includes(bit.type)) fail('schema', 'Invalid bit value type');
if (field.type === 'bitfield') {
if (bit.type === 'bool' && bit.length !== 1) fail('schema', 'Boolean bit slices require exactly one bit');
if (ranges.some(range => bit.offset < range.end && bit.offset + bit.length > range.start))
fail('overlap', 'Bit slices overlap', { nodeId: bit.id });
ranges.push({ start: bit.offset, end: bit.offset + bit.length });
}
return { ...bit, id: `${instancePrefix}${bit.id}` };
});
}
return field;
} catch (error) { if (error instanceof ProtocolError) error.nodeId ??= source.id; throw error; }
});
}
function messagesOf(messages, scope, depth = 0) {
if (depth > LIMITS.depth || !Array.isArray(messages)) fail('schema', 'Invalid message dispatch');
const commands = new Set();
return messages.map(source => {
if (compiled.messages.length >= LIMITS.messages) fail('schema', 'Message count limit exceeded');
const id = source.id || `${scope}.${source.command}`;
if (typeof id !== 'string' || compiled.messageById.has(id)) fail('schema', `Invalid or duplicate message id: ${id}`);
if (source.command !== undefined && (!Number.isSafeInteger(source.command) || source.command < 0)) fail('schema', 'Invalid message command');
const key = `${source.command}:${source.length ?? '*'}`;
if (source.command !== undefined && commands.has(key)) fail('schema', `Ambiguous message command: ${source.command}`);
commands.add(key);
const message = { ...source, id, name: source.name || id, fields: fieldsOf(source.fields || [], id) };
if (source.length !== undefined) bounded(source.length, compiled.maxLength, 'Message length');
if (source.maxLength !== undefined) bounded(source.maxLength, compiled.maxLength, 'Message payload limit');
compiled.messages.push(message); compiled.messageById.set(id, message);
if (source.dispatch) {
const dispatch = source.dispatch;
if (!safeName(dispatch.name || 'content') || typeof dispatch.field !== 'string') fail('schema', 'Invalid nested dispatch');
const conflict = reservedNames.error(dispatch.name || 'content', 'field');
if (conflict) fail('reserved-name', conflict, { nodeId: message.id });
message.dispatch = { ...dispatch, offsetExpression: expression(dispatch.offset ?? 0),
messages: messagesOf(dispatch.messages, id, depth + 1) };
for (const child of message.dispatch.messages) child.parent = message;
}
return message;
});
}
compiled.rootMessages = messagesOf(schema.messages, schema.id);
compiled.headerFields = fieldsOf(schema.headerFields || [], `${schema.id}.header`);
if (compiled.unified) prepareUnifiedFields(compiled);
validateLengthRoles(compiled);
compiled.checksums = (schema.checksums || []).map((source, index) => {
const config = { ...source, type: source.type || 'crc',
width: source.width ?? (Number(String(source.type).replace('crc', '')) || 8),
id: source.id || `checksum${index}` };
validateChecksumResult(config);
if (!['crc', 'crc8', 'crc16', 'crc32', 'sum', 'xor'].includes(config.type)) fail('schema', 'Unsupported checksum');
if (!['8', '16', '32'].includes(String(config.width))) fail('schema', 'Checksum width must be 8, 16 or 32');
if (config.type.startsWith('crc') && config.polynomial === undefined) fail('schema', 'CRC requires a polynomial');
for (const prop of ['polynomial', 'init', 'xorOut']) if (config[prop] !== undefined &&
(!Number.isSafeInteger(config[prop]) || config[prop] < 0 || config[prop] >= 2 ** config.width))
fail('schema', `Invalid checksum ${prop}`);
for (const prop of ['start', 'end', 'offset']) config[`${prop}Expression`] = expression(config[prop] ?? (prop === 'start' ? 0 : -config.width / 8));
return config;
});
{
const builtins = new Set(reservedNames.protocolVariables);
validateFields(compiled.headerFields, builtins, compiled, 0);
const validateMessages = (messages, inherited) => {
for (const message of messages) {
validateFields(message.fields, inherited, compiled, schema.payloadOffset || 0);
if (message.dispatch) validateMessages(message.dispatch.messages, new Set([...inherited, ...message.fields.map(field => field.name)]));
}
};
validateMessages(compiled.rootMessages, new Set([...builtins, ...compiled.headerFields.map(f => f.name)]));
}
if (compiled.unified) bindUnifiedFraming(compiled);
else { bindFraming(compiled); validateAutoWriters(compiled); }
if (!compiled.unified && !compiled.framing.fixedLength && !compiled.framing.length && !compiled.framing.footer?.length) fail('schema', 'Framing requires fixedLength, length, or footer');
compileRules(compiled);
compileLengthRelations(compiled);
validateElementRepetitions(compiled);
if (compiled.unified) checkStructuralBoundaries(compiled);
const prepareScan = fields => { for (const field of fields) {
field.scanWidth = scalarWidth(field);
if (field.endBytes) field.endTable = delimiterTable(field.endBytes);
const trees = [...Object.values(field.expressions), field.selectorExpression,
...Object.entries(field.checksumConfig ?? {}).filter(([key]) => key.endsWith('Expression')).map(([, value]) => value),
...(field.branches ?? []).map(branch => branch.expressionTree)];
if (!field.expressionBoundaryScope && trees.some(tree => variables(tree).some(name => /\b(?:FRAME_LENGTH|PAYLOAD_LENGTH|REMAINING|PARENT_REMAINING)\b/.test(name)))) compiled.streamFrameContext = true;
if (field.fields) prepareScan(field.fields);
if (field.headerFields) prepareScan(field.headerFields);
for (const branch of field.branches ?? []) prepareScan(branch.fields);
} };
for (const message of compiled.rootMessages) prepareScan(message.fields);
compiled.footerTable = delimiterTable(compiled.framing.footer ?? []);
compiled.streamPreChecks = [...compiled.checksums, ...(compiled.preChecksums ?? [])].filter(config =>
[config.start, config.end, config.offset].every(value => Number.isInteger(value) && value >= 0));
compiledProtocols.add(compiled); return compiled;
}
// Validation constraints do not define byte boundaries unless an explicit
// length-value fallback is enabled. Wire spans provide LEN/checksum ranges.
function compileRules(compiled) {
const sources = compiled.schema.rules ?? [];
if (!Array.isArray(sources) || sources.length > 512) fail('rules', '规则数量不能超过 512');
if (sources.length && !compiled.unified) fail('rules', '规则约束需要整帧字段结构');
const ids = new Set(), entries = compiled.fieldEntries ?? new Map();
const paths = new Map();
const collectPaths = (fields, prefix = '') => { for (const field of fields) {
const path = prefix + field.name; paths.set(path, field);
for (const bit of field.bits ?? []) if (bit.type !== 'reserved') paths.set(path + '.' + bit.name, { ...bit, type: bit.type ?? 'uint', id: field.id });
const childPrefix = field.inline ? prefix : path + '.';
if (field.fields) collectPaths(field.fields, childPrefix);
if (field.headerFields) collectPaths(field.headerFields, childPrefix);
for (const branch of field.branches ?? []) collectPaths(branch.fields, childPrefix);
} };
if (sources.length) collectPaths(compiled.rootMessages[0].fields);
const checkTree = tree => {
const inspect = (node, lengthArgument = false) => {
if (!node) return;
const name = node.variable;
if (name) {
if (['TRUE', 'FALSE', 'FRAME_LENGTH', 'PAYLOAD_LENGTH', 'SEQ', 'REMAINING'].includes(name)) return;
const path = name.replace(/^CURRENT\./, '').replace(/\[\d+\]/g, '');
if (!paths.has(path)) fail('rule-reference', `规则引用不存在的字段:${name}`);
const field = paths.get(path);
if (!lengthArgument && !/^(?:u?int\d*|float\d+|bool|enum|bitfield|checksum)$/.test(field.type))
fail('rule-reference', `规则数值表达式需要标量;数据段长度请使用 LEN(${name})`);
}
for (const child of [node.left, node.right, node.unary, ...(node.args ?? [])]) inspect(child, node.fn === 'LEN');
};
inspect(tree);
};
const compileRule = source => {
const rule = { stage: 'validation', strength: 'weak', send: 'verify', enabled: true, ...source };
if (typeof rule.id !== 'string' || !rule.id || ids.has(rule.id) || entries.has(rule.id) || rule.id === compiled.id || compiled.messageById.has(rule.id)) fail('rules', '规则 ID 缺失或重复');
if (typeof rule.enabled !== 'boolean') fail('rules', '规则启用状态必须是布尔值');
ids.add(rule.id);
if (!['parsing', 'validation', 'both'].includes(rule.stage)) fail('rules', '规则参与阶段无效');
if (!['strong', 'weak'].includes(rule.strength) || !['verify', 'fill'].includes(rule.send)) fail('rules', '规则强度或发送行为无效');
if (!['assert', 'length', 'checksum'].includes(rule.type)) fail('rules', '规则类型无效');
if (rule.enabled === false) return rule;
const tree = (text, label) => { if (text === undefined || text === '') fail('rules', `${label}不能为空`);
const result = expression(text); checkTree(result); return result; };
if (rule.condition !== undefined && rule.condition !== '') rule.conditionTree = tree(rule.condition, '规则启用条件');
if (rule.type !== 'checksum') rule.tree = tree(rule.expression, '验证表达式');
if (rule.targetFieldId) {
rule.target = entries.get(rule.targetFieldId)?.field;
if (!rule.target || !/^u?int(?:8|16|32|64)$/.test(baseType(rule.target)) || rule.target.count !== undefined || rule.target.until !== undefined)
fail('rule-reference', '回填/校验值字段必须是单个整数字段');
}
if (rule.boundaryFallback !== undefined) {
if (typeof rule.boundaryFallback !== 'boolean' || rule.type !== 'length' || !rule.target)
fail('rules', '长度值表达式需要整数字段及明确的用途');
rule.valueTree = tree(rule.value, '本字段的值表达式');
const path = entries.get(rule.targetFieldId).path;
rule.tree = expression(`${path} == (${rule.value})`);
}
if (rule.type === 'checksum') {
if (!rule.target || !/^uint(?:8|16|32)$/.test(baseType(rule.target))) fail('rules', '校验值字段必须为 1、2 或 4 字节无符号整数');
rule.config = { type: 'sum', ...rule.checksum, width: scalarWidth(rule.target) * 8 };
validateChecksumResult(rule.config,{nodeId:rule.id});
if (!['crc', 'crc8', 'crc16', 'crc32', 'sum', 'xor'].includes(rule.config.type)) fail('rules', '校验算法无效');
if (/^crc\d+$/.test(rule.config.type) && Number(rule.config.type.slice(3)) !== rule.config.width) fail('rules', 'CRC 位数必须与校验值字段宽度一致');
if (rule.config.type.startsWith('crc') && !Number.isSafeInteger(rule.config.polynomial)) fail('rules', 'CRC 需要多项式');
for (const key of ['polynomial', 'init', 'xorOut']) if (rule.config[key] !== undefined &&
(!Number.isSafeInteger(rule.config[key]) || rule.config[key] < 0 || rule.config[key] >= 2 ** rule.config.width)) fail('rules', `校验参数 ${key} 超出存储范围`);
for (const key of ['start', 'end']) {
const value = rule.config[key] ?? (key === 'start' ? 0 : { fieldId: rule.targetFieldId, edge: 'start' });
rule.config[key] = value;
if (value && typeof value === 'object') {
if (!entries.has(value.fieldId) || !['start', 'end'].includes(value.edge)) fail('rule-reference', '校验范围字段引用无效');
} else rule.config[key + 'Tree'] = tree(value, '校验范围');
}
}
if (rule.send === 'fill') {
if (!rule.target) fail('rules', '自动回填需要指定字段');
if (rule.target.type === 'checksum' || rule.target.autoLengthTargets?.length || rule.target.autoFrameLength || rule.target.valueSource)
fail('rule-writer', '回填字段已由现有解析/校验规则自动写入');
if (rule.target.expectedBytes || [...entries.values()].some(({ field }) =>
[...Object.values(field.expressions), field.selectorExpression, ...(field.branches ?? []).map(branch => branch.expressionTree)]
.some(tree => ruleValueVariables(tree).some(name => name.split('.').at(-1) === rule.target.name))))
fail('rule-writer', '回填字段参与解析路径或字节边界,请保留解析长度绑定或显式输入其值');
if (rule.type !== 'checksum') rule.valueTree = tree(rule.value, '回填表达式');
}
rule.references = [...new Set([rule.tree, rule.valueTree, rule.conditionTree,
rule.config?.startTree, rule.config?.endTree].flatMap(item => variables(item)))];
return rule;
};
compiled.rules = sources.map(source => {
try { return compileRule(source); }
catch (error) { if (error instanceof ProtocolError) error.nodeId ??= source?.id; throw error; }
});
const writers = new Map();
for (const rule of compiled.rules) if (rule.enabled !== false && rule.send === 'fill') {
if (writers.has(rule.targetFieldId)) fail('rule-writer', '多个规则回填同一字段');
writers.set(rule.targetFieldId, rule);
}
// Value dependencies are ordered before consumers. Checksum byte coverage
// dependencies are added against actual spans when sending variable frames.
const ordered = [], visiting = new Set(), visited = new Set();
const visit = rule => {
if (visiting.has(rule)) fail('rule-cycle', '自动回填存在循环依赖');
if (visited.has(rule)) return;
visiting.add(rule);
for (const name of ruleValueVariables(rule.valueTree)) {
const field = paths.get(name.replace(/^CURRENT\./, '').replace(/\[\d+\]/g, ''));
const owner = writers.get(field?.id); if (owner) visit(owner);
}
visiting.delete(rule); visited.add(rule); ordered.push(rule);
};
for (const rule of writers.values()) visit(rule);
compiled.ruleWriters = ordered;
const staticSpans = compiled.ruleStaticSpans ?? [];
const staticContext = Object.create(null);
if (compiled.framing.fixedLength) staticContext.FRAME_LENGTH = staticContext.PAYLOAD_LENGTH = compiled.framing.fixedLength;
const ranges = new Map(), staticWriters = ordered.filter(rule => staticSpans.some(span => span.fieldId === rule.targetFieldId));
for (const rule of compiled.rules) if (rule.enabled !== false && rule.type === 'checksum') {
try {
const range = ruleChecksumRange(rule, staticSpans, { length: compiled.framing.fixedLength ?? compiled.maxLength }, staticContext);
if (rule.send === 'fill' && range.start < range.target.endByte && range.end > range.target.byteOffset)
fail('rule-writer', '校验回填范围包含自身存储');
ranges.set(rule, range);
} catch (error) {
if (!['expression', 'rule-unavailable', 'length-reference'].includes(error.code)) throw error;
compiled.diagnostics.push({ severity: 'warning', code: 'rule-dynamic-range', nodeId: rule.id,
message: '动态校验覆盖范围与回填依赖将在样例编码时检查' });
}
}
const marked = new Set(), visitingChecks = new Set();
const orderCheck = rule => {
if (visitingChecks.has(rule)) fail('rule-cycle', '校验自动回填存在循环依赖');
if (marked.has(rule)) return;
visitingChecks.add(rule);
const range = ranges.get(rule);
for (const other of staticWriters) if (other !== rule) {
const span = staticSpans.find(span => span.fieldId === other.targetFieldId);
if (range && span.byteOffset < range.end && span.endByte > range.start ||
ruleValueVariables(rule.valueTree).some(name => ruleReadsStorage(name, span.path))) orderCheck(other);
}
visitingChecks.delete(rule); marked.add(rule);
};
for (const rule of staticWriters) orderCheck(rule);
}
function ruleValueVariables(tree) {
if (!tree || tree.fn === 'LEN') return [];
if (tree.variable) return [tree.variable];
return [tree.left, tree.right, tree.unary, ...(tree.args ?? [])].flatMap(ruleValueVariables);
}
function ruleReadsStorage(name, path) {
name = name.replace(/^CURRENT\./, '');
return name === path || name.startsWith(path + '.');
}
function ruleContext(bytes, spans, compiled, complete = true, cache = null) {
const values = cache?.values ?? Object.create(null), lengths = spans[RULE_LENGTHS] ?? cache?.lengths ?? new Map();
const put = (path, value) => { values[path] = value; values['CURRENT.' + path] = value; };
for (let spanIndex = cache?.spanCount ?? 0; spanIndex < spans.length; spanIndex++) {
const span = spans[spanIndex];
lengths.set(span.path, span.endByte - span.byteOffset);
const width = scalarWidth(span.field), repeated = span.field.count !== undefined || elementRepeatToEnd(span.field);
if (width) for (let index = 0; index < (repeated ? (span.endByte - span.byteOffset) / width : 1); index++) {
const path = span.path + (repeated ? `[${index}]` : '');
const value = scalarRead(bytes, span.field, span.byteOffset + index * width, compiled);
put(path, value); lengths.set(path, width);
for (const bit of span.field.bits ?? []) if (bit.type !== 'reserved') {
let sliced = BigInt(value) >> BigInt(bit.offset) & (1n << BigInt(bit.length)) - 1n;
if (bit.type === 'int' && sliced & 1n << BigInt(bit.length - 1)) sliced -= 1n << BigInt(bit.length);
put(path + '.' + bit.name, bit.type === 'bool' ? sliced !== 0n : bit.length <= 53 ? Number(sliced) : sliced);
lengths.set(path + '.' + bit.name, Math.ceil((bit.offset % 8 + bit.length) / 8));
}
if (span.field.valueSource === 'SEQ') values.SEQ = value;
}
}
if (complete) { values.FRAME_LENGTH = values.PAYLOAD_LENGTH = bytes.length; values.REMAINING = 0; values.SEQ ??= 0; }
values[LEN_CONTEXT] = path => {
const value = lengths.get(path.replace(/^CURRENT\./, ''));
if (value === undefined) fail('rule-unavailable', `LEN(${path}) 对应字段尚未读取或未启用`);
return value;
};
if (cache) Object.assign(cache, { values, lengths, spanCount: spans.length });
return values;
}
function ruleChecksumRange(rule, spans, bytes, context, instance = null) {
const target = spans.filter(span => span.fieldId === rule.targetFieldId);
if (!target.length) fail('rule-unavailable', '校验值字段尚未读取或未启用');
const selected = instance ?? (target.length === 1 ? target[0] : null);
if (!selected) fail('rule-reference', '校验值字段有多个实例');
const scope = selected.path.slice(0, -selected.field.name.length);
const resolve = key => {
const ref = rule.config[key];
if (ref && typeof ref === 'object') {
const matches = spans.filter(span => span.fieldId === ref.fieldId);
if (!matches.length) fail('rule-unavailable', '校验范围尚未读取或未启用');
const local = matches.filter(span => span.path.startsWith(scope));
const match = local.length === 1 ? local[0] : matches.length === 1 ? matches[0] : null;
if (!match) fail('rule-reference', '校验范围存在多个实例且无法确定所属段');
return ref.edge === 'end' ? match.endByte : match.byteOffset;
}
return position(rule.config[key + 'Tree'], context, bytes.length);
};
const start = resolve('start'), end = resolve('end');
if (start < 0 || start > end || end > bytes.length) fail('rule-range', '校验覆盖范围超出已读取字节');
return { start, end, target: selected };
}
function evaluateRules(bytes, compiled, spans, stage, { partial = false, done = new Set(), contextCache = null } = {}) {
const results = [], context = ruleContext(bytes, spans, compiled, !partial, contextCache);
for (const rule of compiled.rules ?? []) {
if (done.has(rule.id) || rule.stage !== stage && rule.stage !== 'both') continue;
const result = { ruleId: rule.id, name: rule.name || rule.id, stage, strength: rule.strength, status: 'not-run' };
if (rule.enabled === false) { result.message = '规则已禁用'; results.push(result); continue; }
try {
if (rule.conditionTree && !evaluate(rule.conditionTree, context)) { result.message = '启用条件不满足'; results.push(result); done.add(rule.id); continue; }
let passed;
if (rule.type === 'checksum') {
const instances = spans.filter(span => span.fieldId === rule.targetFieldId);
if (!instances.length) fail('rule-unavailable', '校验值字段尚未读取或未启用');
for (const instance of instances) {
const key = rule.id + ':' + instance.path;
if (partial && done.has(key)) continue;
const range = ruleChecksumRange(rule, spans, bytes, context, instance);
const actual = scalarRead(bytes, rule.target, range.target.byteOffset, compiled);
const expected = checksum(bytes.subarray(range.start, range.end), rule.config), ok = actual === expected;
results.push({ ...result, actual, expected, path: instance.path, status: ok ? 'passed' : 'failed',
message: ok ? '通过' : `规则“${result.name}”验证失败:${instance.path}` });
done.add(key);
}
// Repeated fields can produce more instances on the next block.
continue;
} else {
passed = Boolean(evaluate(rule.tree, context));
if (rule.tree.left && rule.tree.right) {
result.actual = evaluate(rule.tree.left, context); result.expected = evaluate(rule.tree.right, context);
}
}
result.status = passed ? 'passed' : 'failed';
result.message = passed ? '通过' : `规则“${result.name}”验证失败`;
done.add(rule.id);
} catch (error) {
if (!(error instanceof ProtocolError)) throw error;
if (partial && ['rule-unavailable', 'expression'].includes(error.code)) continue;
result.status = 'not-run'; result.message = error.message;
result.unavailable = true;
}
results.push(result);
}
return results;
}
function applyRuleResults(record, results) {
record.ruleResults = results;
for (const result of results) if (result.status === 'failed' || result.unavailable) {
if (result.strength === 'strong') record.valid = false;
record.warnings.push({ code: 'rule', severity: result.strength === 'strong' ? 'error' : 'warning',
ruleId: result.ruleId, stage: result.stage, message: result.message, actual: result.actual, expected: result.expected });
}
}
function fillRuleWrites(bytes, compiled, spans) {
const layout = scanUnifiedFrame(bytes, compiled, bytes.length);
const nodes = compiled.ruleWriters.flatMap(rule => {
const matches = spans.filter(span => span.fieldId === rule.targetFieldId);
if (!matches.length) {
if (rule.conditionTree && !evaluate(rule.conditionTree, ruleContext(bytes, spans, compiled))) return [];
fail('rule-reference', '回填字段缺失或未启用');
}
return matches.map(target => ({ rule, target }));
});
for (const check of fieldChecksumRanges(compiled, layout.spans, bytes.length))
nodes.push({ check, target: { field: check.field, fieldId: check.fieldId, path: check.path,
byteOffset: check.offset, endByte: check.offset + check.config.width / 8 } });
for (let i = 0; i < nodes.length; i++) for (let j = 0; j < i; j++)
if (nodes[i].target.byteOffset < nodes[j].target.endByte && nodes[i].target.endByte > nodes[j].target.byteOffset)
fail('rule-writer', '自动回填存储区域重叠');
const pending = new Set(nodes), completed = new Set();
while (pending.size) {
let progressed = false;
for (const node of pending) {
const { rule, target } = node, context = ruleContext(bytes, spans, compiled);
const valueDependencies = [rule?.valueTree, rule?.conditionTree, rule?.config?.startTree, rule?.config?.endTree].flatMap(ruleValueVariables);
if (node.check) {
const scope = target.path.split('.').slice(0, -1);
for (let name of [node.check.config.startExpression, node.check.config.endExpression].flatMap(ruleValueVariables)) {
const parts = [...scope];
while (name.startsWith('PARENT.')) { parts.pop(); name = name.slice(7); }
const explicit = name.startsWith('CURRENT.'); name = name.replace(/^CURRENT\./, '');
// Legacy local contexts inherit enclosing values unless CURRENT is explicit.
do { valueDependencies.push([...parts, name].join('.')); } while (!explicit && parts.length && parts.pop() !== undefined);
}
}
if (nodes.some(other => other !== node && !completed.has(other) && valueDependencies.some(name =>
ruleReadsStorage(name, other.target.path)))) continue;
if (rule?.conditionTree && !evaluate(rule.conditionTree, context)) {
completed.add(node); pending.delete(node); progressed = true; continue;
}
const range = node.check ? fieldChecksumRanges(compiled, scanUnifiedFrame(bytes, compiled, bytes.length).spans, bytes.length)
.find(check => check.fieldId === target.fieldId && check.path === target.path)
: (rule.type === 'checksum' ? ruleChecksumRange(rule, spans, bytes, context, target) : null);
if (range && range.start < target.endByte && range.end > target.byteOffset) fail('rule-writer', '校验回填范围包含自身存储');
if (range && nodes.some(other => other !== node && !completed.has(other) &&
other.target.byteOffset < range.end && other.target.endByte > range.start)) continue;
const value = range ? checksum(bytes.subarray(range.start, range.end), node.check?.config ?? rule.config) : evaluate(rule.valueTree, context);
scalarWrite(bytes, target.field, target.byteOffset, value, compiled);
completed.add(node); pending.delete(node); progressed = true;
}
if (!progressed) fail('rule-cycle', '自动回填存在循环依赖');
}
}
function migrateSymbols(input) {
const schema = cloneJSON(input);
try { return protocolSymbols.migrate(schema); }
catch (error) { fail('symbol-migration', error.message); }
}
function validLengthSource(field) {
return /^uint(?:8|16|32)$/.test(baseType(field)) && field.count === undefined && field.until === undefined && !field.expectedBytes;
}
function validateLengthRoles(compiled) {
const fields = [], referenced = new Set();
function collect(list) {
for (const field of list || []) {
fields.push(field);
if (field.lengthSource) referenced.add(field.lengthSource.fieldId);
collect(field.fields); collect(field.headerFields);
for (const branch of field.branches || []) collect(branch.fields);
}
}
collect(compiled.headerFields);
for (const message of compiled.messages) {
if (message.lengthSource) referenced.add(message.lengthSource.fieldId);
if (compiled.unified && message.lengthFrom !== undefined) {
const names = new Set(variables(expression(message.lengthFrom)).map(name => name.replace(/^CURRENT\./, '')));
for (const [id, entry] of compiled.fieldEntries) if (names.has(entry.path)) referenced.add(id);
}
collect(message.fields);
}
for (const field of fields) if (field.role === 'length' && (!validLengthSource(field) || !referenced.has(field.id)))
fail('length-role', 'Length role requires unsigned scalar storage and at least one lengthSource consumer', { nodeId: field.id });
}
function prepareUnifiedFields(compiled) {
const schema = compiled.schema;
if (compiled.rootMessages.length !== 1 || schema.command || schema.headerFields?.length || schema.checksums?.length ||
Object.keys(schema.framing || {}).some(key => key !== 'maxLength')) fail('schema', 'Unified fields require one whole-frame structure and field-based rules');
const entries = new Map(); compiled.fieldEntries = entries; compiled.fieldChecksums = [];
function collect(fields, prefix = '', owner = null) {
fields.forEach((field, index) => {
const path = prefix ? `${prefix}.${field.name}` : field.name;
entries.set(field.id, { field, path, fields, index, owner });
if (field.fields) collect(field.fields, field.inline ? prefix : path, field);
if (field.headerFields) collect(field.headerFields, path, field);
for (const branch of field.branches || []) collect(branch.fields, field.inline ? prefix : path, field);
});
}
collect(compiled.rootMessages[0].fields);
const relationCandidates = new Set();
const collectRelation = node => {
if (node.fn === 'LEN') relationCandidates.add(node.args[0].variable.replace(/^CURRENT\./, ''));
for (const child of [node.left,node.right,node.unary,...(node.args ?? [])]) if (child) collectRelation(child);
};
for (const rule of schema.rules ?? []) if (rule.enabled !== false && rule.boundaryFallback === true && rule.value)
collectRelation(expression(rule.value));
const root = compiled.rootMessages[0];
if (root.byteLength === undefined) root.byteLength = 0;
bounded(root.byteLength, compiled.maxLength, 'Whole frame byte length');
if (root.byteLength > 0 && root.lengthSource && root.legacyProtocol !== true) fail('length', 'Fixed whole-frame byte length conflicts with lengthSource binding', { nodeId: root.id });
if (root.lengthFrom !== undefined && (root.byteLength > 0 || root.lengthSource))
fail('length', 'Whole-frame length expression conflicts with fixed length or lengthSource binding', { nodeId: root.id });
// A literal zero explicitly requests content-defined framing; empty input is an invalid expression.
if (root.lengthFrom === 0 || typeof root.lengthFrom === 'string' && root.lengthFrom.trim() === '0') delete root.lengthFrom;
for (const entry of entries.values()) {
const { field, fields, index } = entry;
field.lengthRelationCandidate = relationCandidates.has(entry.path);
const width = scalarWidth(field);
if (field.byteLength === undefined) field.byteLength = width ?? (field.type === 'fixed' ? field.bytes.length : typeof field.length === 'number' ? field.length : 0);
bounded(field.byteLength, compiled.maxLength, 'Field byte length');
if (field.byteLength > 0 && field.lengthSource) fail('length', 'Fixed field byte length conflicts with lengthSource binding', { nodeId: field.id });
if (width !== undefined && field.byteLength !== width || field.type === 'fixed' && field.byteLength !== field.bytes.length)
fail('width', 'Byte length does not match field type or fixed bytes', { nodeId: field.id });
if (field.byteLength > 0 && !width && field.type !== 'fixed') field.length = field.byteLength;
else if (field.byteLength === 0) {
if (width || field.type === 'fixed') fail('width', 'Scalar and fixed fields require a positive byte length', { nodeId: field.id });
if (field.lengthSource) {
const source = entries.get(field.lengthSource.fieldId);
if (!source || !validLengthSource(source.field)) fail('reference', 'Length source must reference an unsigned scalar field', { nodeId: field.id });
const unit = bounded(field.lengthSource.unit ?? 1, compiled.maxLength, 'Length source unit', 1), adjustment = field.lengthSource.adjustment ?? 0;
if (!Number.isSafeInteger(adjustment)) fail('length', 'Invalid length source adjustment', { nodeId: field.id });
const owners = owner => { const chain = []; for (let node = owner; node; node = entries.get(node.id)?.owner) chain.unshift(node); return chain; };
const from = owners(entry.owner), to = owners(source.owner);
let common = 0; while (common < from.length && common < to.length && from[common] === to[common]) common++;
const localPath = 'PARENT.'.repeat(from.length - common) +
[...to.slice(common).filter(owner => !owner.inline).map(owner => owner.name), source.field.name].join('.');
field.length = `(${localPath}) * ${unit} + (${adjustment})`;
field.autoLengthSource = source.field; field.autoLengthUnit = unit; field.autoLengthAdjustment = adjustment;
source.field.autoLengthTargets ??= []; source.field.autoLengthTargets.push(field.id);
} else if (field.lengthFrom === 'contents' && ['struct','choice','repeat','tlv'].includes(field.type)) delete field.length;
else if (field.lengthFrom !== undefined && String(field.lengthFrom).trim()) field.length = field.lengthFrom;
else if (field.boundary) {
const start = entries.get(field.boundary.startFieldId), end = entries.get(field.boundary.endFieldId);
if (field.boundary.startFieldId && (!start || start.field.type !== 'fixed' || start.fields !== fields || start.index !== index - 1) ||
!end || end.field.type !== 'fixed' || end.fields !== fields || end.index !== index + 1)
fail('boundary', 'Variable boundary must reference adjacent independent fixed byte fields', { nodeId: field.id });
field.endBytes = end.field.bytes;
} else if (field.lengthRelationCandidate) field.length = 'REMAINING';
else fail('length', '0 byte variable fields require a length source or fixed boundary;结构体、分支或定次重复可选择“按内部字段确定”,原始字节须提供独立边界', { nodeId: field.id });
}
if (field.length !== undefined) field.expressions.length = expression(field.length);
else delete field.expressions.length;
if (field.type === 'checksum') {
const config = { type: 'sum', ...field.checksum, width: field.byteLength * 8, id: field.id, endian: field.endian };
validateChecksumResult(config,{nodeId:field.id});
if (![8,16,32].includes(config.width) || !['crc','crc8','crc16','crc32','sum','xor'].includes(config.type) || /^crc\d+$/.test(config.type) && Number(config.type.slice(3)) !== config.width) fail('checksum', 'Invalid checksum type or byte width', { nodeId: field.id });
if (config.type.startsWith('crc') && !Number.isSafeInteger(config.polynomial)) fail('checksum', 'CRC requires a polynomial', { nodeId: field.id });
for (const key of ['polynomial','init','xorOut']) if (config[key] !== undefined && (!Number.isSafeInteger(config[key]) || config[key] < 0 || config[key] >= 2 ** config.width)) fail('checksum', 'Invalid checksum ' + key, { nodeId: field.id });
for (const key of ['start','end']) {
const reference = config[key];
if (reference && typeof reference === 'object') {
if (!entries.has(reference.fieldId) || !['start','end'].includes(reference.edge ?? 'start')) fail('reference', 'Unknown checksum boundary field', { nodeId: field.id });
if (reference.fieldId === field.id && (key === 'start' || reference.edge === 'end')) fail('checksum', 'Checksum range includes its own storage', { nodeId: field.id });
} else if (reference !== undefined) config[key + 'Expression'] = expression(reference);
}
field.checksumConfig = config; compiled.fieldChecksums.push(field);
}
}
compiled.frameAliases = new Map();
const selectorPath = field => {
if (field.selectorFieldId) return entries.get(field.selectorFieldId)?.path;
if (typeof field.selector !== 'string' || !/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(field.selector)) return null;
const direct = [...entries.values()].find(entry => entry.path === field.selector);
return direct?.path ?? field.selector;
};
function aliases(fields, selectors = []) {
for (const field of fields) {
for (const branch of field.branches || []) {
const chain = branch.legacyMessage ? [...selectors, { path: selectorPath(field) ?? branch.selectorPath, value: branch.equals ?? branch.legacyMessage.command, choiceId: field.id, branchId: branch.id }] : selectors;
if (branch.legacyMessage) branch.legacyMessage.id = branch.id;
if (branch.legacyMessage) {
const alias = { ...branch.legacyMessage, id: branch.id, fields: branch.fields, frameAlias: true, selectors: chain, valuePath: branch.valuePath ?? '', branchId: branch.id };
if (selectors.length) alias.parent = compiled.frameAliases.get(selectors.at(-1).branchId);
if (compiled.messageById.has(alias.id)) fail('schema', 'Duplicate legacy message identity');
compiled.messages.push(alias); compiled.messageById.set(alias.id, alias); compiled.frameAliases.set(alias.id, alias);
}
aliases(branch.fields, chain);
}
if (field.fields) aliases(field.fields, selectors);
}
}
aliases(root.fields);
}
function bindUnifiedFraming(compiled) {
const root = compiled.rootMessages[0], framing = compiled.framing;
if (root.byteLength) framing.fixedLength = root.byteLength;
let cursor = 0;
for (const field of root.fields) {
if (field.offset !== undefined) cursor = typeof field.offset === 'number' ? field.offset : null;
if (field.framingRole === 'sync') {
if (field.type !== 'fixed' || cursor === null || field.condition !== undefined) fail('schema', 'Synchronization requires unconditional fixed bytes at a known position', { nodeId: field.id });
compiled.sync = { offset: cursor, bytes: field.bytes };
if (!cursor) framing.header = field.bytes;
}
if (field.framingRole === 'end') {
if (field.type !== 'fixed' || field !== root.fields.at(-1) || field.condition !== undefined) fail('boundary', 'End delimiter must be the final independent fixed field', { nodeId: field.id });
framing.footer = field.bytes; compiled.fieldFooter = true;
}
const width = scalarWidth(field) ?? (field.type === 'fixed' ? field.bytes.length : typeof field.length === 'number' ? field.length : null);
cursor = cursor === null || width === null || field.condition !== undefined || elementRepeatToEnd(field) || field.count !== undefined && typeof field.count !== 'number' ? null : cursor + width * (typeof field.count === 'number' ? field.count : 1);
}
if (root.lengthFrom === undefined && !framing.fixedLength && cursor !== null && cursor > 0) framing.fixedLength = cursor;
const staticFields = new Map();
function locate(fields, base = 0, restricted = false) {
let at = base;
for (const field of fields) {
const before = at;
if (field.offset !== undefined) at = typeof field.offset === 'number' && base !== null ? (field.offsetBase === 'frame' ? 0 : base) + field.offset : null;
const optional = restricted || field.condition !== undefined || field.count !== undefined || elementRepeatToEnd(field);
if (at !== null && !optional) staticFields.set(field.id, { field, offset: at });
if (field.fields) locate(field.fields, at, optional);
const pattern = field.type === 'fixed' ? field.bytes : field.expectedBytes;
if (field.framingRole === 'sync' && at !== null && pattern?.length && !optional) {
if (compiled.sync && (compiled.sync.offset !== at || String(compiled.sync.bytes) !== String(pattern))) fail('ambiguity', 'Conflicting synchronization fields', { nodeId: field.id });
compiled.sync = { offset: at, bytes: pattern }; if (!at) framing.header = pattern;
}
const width = scalarWidth(field) ?? (field.type === 'fixed' ? field.bytes.length : typeof field.length === 'number' ? field.length : null);
at = field.legacyOverlay ? before : at === null || width === null || field.condition !== undefined || elementRepeatToEnd(field) || field.count !== undefined && typeof field.count !== 'number' ? null : at + width * (typeof field.count === 'number' ? field.count : 1);
}