@netkitty/codec 1.2.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/CHANGELOG.md +295 -0
  2. package/README.md +62 -10
  3. package/README.zh-CN.md +55 -9
  4. package/dist/Codec.d.ts +3 -2
  5. package/dist/Codec.js +109 -10
  6. package/dist/abstracts/BaseHeader.d.ts +54 -2
  7. package/dist/abstracts/BaseHeader.js +185 -43
  8. package/dist/errors/CodecSchemaValidateError.d.ts +34 -1
  9. package/dist/errors/CodecSchemaValidateError.js +26 -3
  10. package/dist/headers/ADSAMS.js +2 -0
  11. package/dist/headers/AH.js +4 -2
  12. package/dist/headers/AMQP.js +2 -1
  13. package/dist/headers/ARP.js +16 -10
  14. package/dist/headers/BACnetIP.js +1 -0
  15. package/dist/headers/BFD.d.ts +2 -1
  16. package/dist/headers/BFD.js +30 -4
  17. package/dist/headers/BGP.js +6 -1
  18. package/dist/headers/Babel.js +2 -1
  19. package/dist/headers/BitTorrent.d.ts +2 -0
  20. package/dist/headers/BitTorrent.js +4 -2
  21. package/dist/headers/C37118.d.ts +3 -2
  22. package/dist/headers/C37118.js +35 -15
  23. package/dist/headers/CAPWAP.js +1 -0
  24. package/dist/headers/CDP.d.ts +3 -3
  25. package/dist/headers/CDP.js +47 -11
  26. package/dist/headers/CMS.js +27 -12
  27. package/dist/headers/COTP.d.ts +2 -0
  28. package/dist/headers/COTP.js +8 -4
  29. package/dist/headers/CassandraCQL.js +1 -0
  30. package/dist/headers/CoAP.js +20 -2
  31. package/dist/headers/Codesys.js +1 -0
  32. package/dist/headers/Collectd.js +1 -1
  33. package/dist/headers/DCCP.d.ts +3 -2
  34. package/dist/headers/DCCP.js +61 -8
  35. package/dist/headers/DHCPFailover.js +1 -0
  36. package/dist/headers/DNP3.d.ts +5 -3
  37. package/dist/headers/DNP3.js +62 -7
  38. package/dist/headers/DNS.js +3 -3
  39. package/dist/headers/DTLS.js +1 -0
  40. package/dist/headers/Diameter.js +3 -2
  41. package/dist/headers/EAPOL.js +1 -1
  42. package/dist/headers/EIGRP.d.ts +3 -2
  43. package/dist/headers/EIGRP.js +32 -6
  44. package/dist/headers/ENIP.js +1 -0
  45. package/dist/headers/Elasticsearch.js +1 -0
  46. package/dist/headers/EtherCAT.js +1 -0
  47. package/dist/headers/EthernetII.js +7 -0
  48. package/dist/headers/FTP.js +6 -6
  49. package/dist/headers/Finger.js +3 -3
  50. package/dist/headers/FoundationFieldbusHSE.js +1 -0
  51. package/dist/headers/GELF.js +8 -1
  52. package/dist/headers/GENEVE.js +2 -1
  53. package/dist/headers/GLBP.js +1 -1
  54. package/dist/headers/GRE.js +1 -0
  55. package/dist/headers/GTPU.js +1 -0
  56. package/dist/headers/GTPv2C.js +2 -0
  57. package/dist/headers/GitProtocol.js +2 -2
  58. package/dist/headers/Goose.js +24 -12
  59. package/dist/headers/Gopher.js +6 -6
  60. package/dist/headers/HARTIP.js +1 -0
  61. package/dist/headers/HSR.js +3 -0
  62. package/dist/headers/HTTP.js +6 -6
  63. package/dist/headers/HTTP2.js +2 -0
  64. package/dist/headers/ICMP.js +3 -1
  65. package/dist/headers/ICMPv6.js +11 -16
  66. package/dist/headers/IEC104_I_Frame.js +215 -163
  67. package/dist/headers/IEC104_S_Frame.js +26 -3
  68. package/dist/headers/IEC104_U_Frame.js +33 -4
  69. package/dist/headers/IEC61850SampledValues.js +6 -5
  70. package/dist/headers/IGMP.d.ts +8 -7
  71. package/dist/headers/IGMP.js +58 -19
  72. package/dist/headers/IMAP.js +5 -5
  73. package/dist/headers/IPFIX.js +3 -2
  74. package/dist/headers/IPv4.js +41 -21
  75. package/dist/headers/IPv6.js +5 -1
  76. package/dist/headers/IPv6HopByHopOptions.js +15 -12
  77. package/dist/headers/IRC.js +4 -4
  78. package/dist/headers/ISAKMP.js +3 -1
  79. package/dist/headers/ISCSI.js +2 -0
  80. package/dist/headers/ISIS.js +2 -1
  81. package/dist/headers/ISOSession.d.ts +2 -0
  82. package/dist/headers/ISOSession.js +14 -10
  83. package/dist/headers/Ident.js +8 -8
  84. package/dist/headers/KNXnetIP.js +1 -0
  85. package/dist/headers/Kafka.js +1 -0
  86. package/dist/headers/Kerberos.js +2 -0
  87. package/dist/headers/L2TP.js +3 -2
  88. package/dist/headers/LACP.js +1 -1
  89. package/dist/headers/LDAP.js +3 -4
  90. package/dist/headers/LDP.js +1 -0
  91. package/dist/headers/LLC.d.ts +2 -0
  92. package/dist/headers/LLC.js +3 -0
  93. package/dist/headers/LPD.js +3 -3
  94. package/dist/headers/MGCP.js +7 -7
  95. package/dist/headers/MMS.d.ts +2 -0
  96. package/dist/headers/MMS.js +10 -6
  97. package/dist/headers/MQTT.js +1 -0
  98. package/dist/headers/MQTTSN.js +1 -0
  99. package/dist/headers/MarkerProtocol.js +1 -1
  100. package/dist/headers/Megaco.js +3 -3
  101. package/dist/headers/Memcached.js +3 -2
  102. package/dist/headers/ModbusTCP.js +1 -0
  103. package/dist/headers/ModbusUDP.js +1 -0
  104. package/dist/headers/MongoDB.js +1 -0
  105. package/dist/headers/MySQL.js +1 -0
  106. package/dist/headers/NATS.js +2 -2
  107. package/dist/headers/NBDS.js +1 -0
  108. package/dist/headers/NBSS.js +1 -0
  109. package/dist/headers/NFS.js +1 -0
  110. package/dist/headers/NHRP.d.ts +1 -1
  111. package/dist/headers/NHRP.js +30 -4
  112. package/dist/headers/NNTP.js +6 -6
  113. package/dist/headers/NetFlowV5.js +1 -0
  114. package/dist/headers/OLSR.js +2 -1
  115. package/dist/headers/OPCUA.js +1 -0
  116. package/dist/headers/OSPF.d.ts +3 -3
  117. package/dist/headers/OSPF.js +72 -7
  118. package/dist/headers/OpenFlow.js +1 -0
  119. package/dist/headers/OpenVPN.js +1 -0
  120. package/dist/headers/PCWorx.js +1 -0
  121. package/dist/headers/PIM.d.ts +3 -3
  122. package/dist/headers/PIM.js +55 -6
  123. package/dist/headers/POP3.js +5 -5
  124. package/dist/headers/PPPoEDiscovery.js +4 -1
  125. package/dist/headers/PPPoESession.js +1 -0
  126. package/dist/headers/PPTP.js +1 -0
  127. package/dist/headers/PTP.js +6 -1
  128. package/dist/headers/PostgreSQL.js +2 -0
  129. package/dist/headers/QUIC.js +2 -0
  130. package/dist/headers/RADIUS.js +1 -0
  131. package/dist/headers/RDP.d.ts +2 -0
  132. package/dist/headers/RDP.js +6 -1
  133. package/dist/headers/RFB.js +4 -4
  134. package/dist/headers/RGoose.js +8 -1
  135. package/dist/headers/RSVP.d.ts +3 -3
  136. package/dist/headers/RSVP.js +59 -44
  137. package/dist/headers/RTCP.js +2 -0
  138. package/dist/headers/RTP.js +2 -1
  139. package/dist/headers/RTPS.d.ts +2 -0
  140. package/dist/headers/RTPS.js +4 -1
  141. package/dist/headers/RTSP.js +7 -7
  142. package/dist/headers/RawData.js +1 -1
  143. package/dist/headers/Redis.js +4 -4
  144. package/dist/headers/Rlogin.js +5 -5
  145. package/dist/headers/Rsync.js +2 -2
  146. package/dist/headers/S7comm.d.ts +2 -0
  147. package/dist/headers/S7comm.js +5 -1
  148. package/dist/headers/SCTP.d.ts +2 -2
  149. package/dist/headers/SCTP.js +31 -7
  150. package/dist/headers/SFlow.js +2 -1
  151. package/dist/headers/SIP.js +6 -6
  152. package/dist/headers/SLMP.js +1 -0
  153. package/dist/headers/SLP.js +2 -0
  154. package/dist/headers/SLPv1.js +1 -0
  155. package/dist/headers/SMB1.js +1 -0
  156. package/dist/headers/SMB2.js +1 -0
  157. package/dist/headers/SMPP.js +1 -0
  158. package/dist/headers/SMTP.js +6 -6
  159. package/dist/headers/SNAP.js +18 -5
  160. package/dist/headers/SNMP.js +6 -6
  161. package/dist/headers/SOCKS4.js +11 -5
  162. package/dist/headers/SSDP.js +7 -7
  163. package/dist/headers/SSH.js +5 -4
  164. package/dist/headers/STOMP.js +5 -5
  165. package/dist/headers/STUN.js +3 -1
  166. package/dist/headers/SercosIII.d.ts +3 -2
  167. package/dist/headers/SercosIII.js +41 -5
  168. package/dist/headers/Skinny.js +1 -0
  169. package/dist/headers/StatsD.js +4 -4
  170. package/dist/headers/SunRPC.js +1 -0
  171. package/dist/headers/Syslog.js +2 -2
  172. package/dist/headers/TCP.js +31 -64
  173. package/dist/headers/TLS_Alert.js +42 -12
  174. package/dist/headers/TLS_ApplicationData.d.ts +3 -3
  175. package/dist/headers/TLS_ApplicationData.js +32 -8
  176. package/dist/headers/TLS_ChangeCipherSpec.d.ts +2 -2
  177. package/dist/headers/TLS_ChangeCipherSpec.js +33 -8
  178. package/dist/headers/TLS_Handshake.js +78 -30
  179. package/dist/headers/TLS_Heartbeat.d.ts +4 -3
  180. package/dist/headers/TLS_Heartbeat.js +50 -8
  181. package/dist/headers/TPKT.js +4 -2
  182. package/dist/headers/TacacsPlus.js +1 -0
  183. package/dist/headers/Telnet.js +2 -1
  184. package/dist/headers/Teredo.js +2 -2
  185. package/dist/headers/UDP.js +20 -56
  186. package/dist/headers/VLAN_802dot1Q.js +8 -0
  187. package/dist/headers/VRRP.d.ts +2 -1
  188. package/dist/headers/VRRP.js +45 -9
  189. package/dist/headers/WCCP.js +1 -0
  190. package/dist/headers/WHOIS.js +3 -3
  191. package/dist/headers/WSDiscovery.js +2 -2
  192. package/dist/headers/XMPP.js +3 -3
  193. package/dist/headers/Zabbix.js +1 -0
  194. package/dist/helper/Checksum.d.ts +15 -0
  195. package/dist/helper/Checksum.js +56 -0
  196. package/dist/helper/Crc.d.ts +18 -0
  197. package/dist/helper/Crc.js +58 -0
  198. package/dist/index.d.ts +3 -3
  199. package/dist/lib/SchemaValidator.d.ts +31 -0
  200. package/dist/lib/SchemaValidator.js +137 -0
  201. package/dist/schema/ProtocolFieldJSONSchema.d.ts +4 -1
  202. package/dist/schema/ProtocolJSONSchema.d.ts +1 -1
  203. package/dist/types/CodecErrorInfo.d.ts +11 -0
  204. package/dist/types/LayerGraph.d.ts +14 -1
  205. package/package.json +2 -2
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Crc32 = Crc32;
4
+ exports.Crc16Dnp = Crc16Dnp;
5
+ exports.Crc16CcittFalse = Crc16CcittFalse;
6
+ /**
7
+ * Lookup table of a reflected (LSB-first) CRC: entry n is the register after shifting byte n through
8
+ * the reversed polynomial eight times.
9
+ * @param reversedPolynomial
10
+ */
11
+ function ReflectedTable(reversedPolynomial) {
12
+ const table = new Uint32Array(256);
13
+ for (let n = 0; n < 256; n++) {
14
+ let register = n;
15
+ for (let bit = 0; bit < 8; bit++)
16
+ register = register & 1 ? (register >>> 1) ^ reversedPolynomial : register >>> 1;
17
+ table[n] = register >>> 0;
18
+ }
19
+ return table;
20
+ }
21
+ const CRC32_TABLE = ReflectedTable(0xEDB88320);
22
+ const CRC16_DNP_TABLE = ReflectedTable(0xA6BC);
23
+ /**
24
+ * CRC-32 as used by IEEE 802.3 / zlib (CRC-32/ISO-HDLC): polynomial 0x04C11DB7 processed reflected,
25
+ * initial value 0xFFFFFFFF, final XOR 0xFFFFFFFF. Check value: Crc32('123456789') = 0xCBF43926.
26
+ * @param buffer
27
+ */
28
+ function Crc32(buffer) {
29
+ let register = 0xFFFFFFFF;
30
+ for (let i = 0; i < buffer.length; i++)
31
+ register = CRC32_TABLE[(register ^ buffer[i]) & 0xFF] ^ (register >>> 8);
32
+ return (register ^ 0xFFFFFFFF) >>> 0;
33
+ }
34
+ /**
35
+ * CRC-16/DNP (IEEE 1815 data link layer): polynomial 0x3D65 processed reflected, initial value 0,
36
+ * final XOR 0xFFFF. DNP3 sends it low octet first. Check value: Crc16Dnp('123456789') = 0xEA82.
37
+ * @param buffer
38
+ */
39
+ function Crc16Dnp(buffer) {
40
+ let register = 0;
41
+ for (let i = 0; i < buffer.length; i++)
42
+ register = CRC16_DNP_TABLE[(register ^ buffer[i]) & 0xFF] ^ (register >>> 8);
43
+ return (register ^ 0xFFFF) & 0xFFFF;
44
+ }
45
+ /**
46
+ * CRC-16/CCITT-FALSE (the IEEE C37.118.2 CHK): polynomial 0x1021 processed MSB-first, initial value
47
+ * 0xFFFF, no final XOR. Check value: Crc16CcittFalse('123456789') = 0x29B1.
48
+ * @param buffer
49
+ */
50
+ function Crc16CcittFalse(buffer) {
51
+ let register = 0xFFFF;
52
+ for (let i = 0; i < buffer.length; i++) {
53
+ register ^= buffer[i] << 8;
54
+ for (let bit = 0; bit < 8; bit++)
55
+ register = register & 0x8000 ? ((register << 1) ^ 0x1021) & 0xFFFF : (register << 1) & 0xFFFF;
56
+ }
57
+ return register;
58
+ }
package/dist/index.d.ts CHANGED
@@ -20,8 +20,8 @@ export { type CodecSchema } from './types/CodecSchema';
20
20
  export { type HeaderTreeNode } from './types/HeaderTreeNode';
21
21
  export { type CodecModuleConstructor } from './types/CodecModuleConstructor';
22
22
  export { type CodecModule } from './types/CodecModule';
23
- export { type CodecErrorInfo } from './types/CodecErrorInfo';
24
- export { type NextLayer, type ConsistencyIssue } from './types/LayerGraph';
23
+ export { type CodecErrorInfo, type CodecErrorSeverity } from './types/CodecErrorInfo';
24
+ export { type NextLayer, type ConsistencyIssue, type HeuristicParent } from './types/LayerGraph';
25
25
  export { type DissectionField, type DissectionLayer } from './types/Dissection';
26
26
  /**
27
27
  * Schemas
@@ -53,4 +53,4 @@ export { Float32ToHex, Int16ToHex, Int32ToHex, Int64ToHex, Int8ToHex, UInt16ToHe
53
53
  /**
54
54
  * Error classes (all extend NetKittyError)
55
55
  */
56
- export { CodecSchemaValidateError } from './errors/CodecSchemaValidateError';
56
+ export { CodecSchemaValidateError, type CodecSchemaValidationIssue } from './errors/CodecSchemaValidateError';
@@ -0,0 +1,31 @@
1
+ import { ErrorObject, ValidateFunction } from 'ajv';
2
+ import { ProtocolJSONSchema } from '../schema/ProtocolJSONSchema';
3
+ import { CodecSchemaValidateError } from '../errors/CodecSchemaValidateError';
4
+ /**
5
+ * Derive the validation keywords a string field's `contentEncoding` implies, in place: an ipv4/ipv6/mac
6
+ * field gets `format: 'ipv4'|'ipv6'|'mac'`, a bigint field gets a numeric `pattern`. An explicit
7
+ * `format`/`pattern` on the field is left alone. Applied to every published schema (PROTOCOL_SCHEMA)
8
+ * and to every compiled validator, so the shape a UI sees and the shape encode enforces are the same,
9
+ * and every address field is constrained consistently without repeating the keyword per field.
10
+ */
11
+ export declare function DeriveContentConstraints<T>(node: T): T;
12
+ /**
13
+ * Compile the Ajv shape validator for a protocol schema. The schema's decode/encode closures are
14
+ * stripped first (the same JSON round-trip that produces PROTOCOL_SCHEMA), so only the declarative
15
+ * shell is compiled. One place for the Ajv options keeps every validator identical.
16
+ */
17
+ export declare function CompileSchemaValidator(schema: ProtocolJSONSchema): ValidateFunction;
18
+ /**
19
+ * The validator for a header class, compiled on first use and cached on that class. Compiling all
20
+ * ~190 schemas eagerly cost ~0.5 s at `new Codec()`; lazily, a codec only pays for the protocols it
21
+ * actually encodes.
22
+ */
23
+ export declare function SchemaValidatorOf(headerClass: object, schema: ProtocolJSONSchema): ValidateFunction;
24
+ /**
25
+ * Ajv instancePath (JSON Pointer, '/goosePdu/allData/0/dataType') → the dotted field path the codec
26
+ * uses everywhere else for errors ('goosePdu.allData[0].dataType'). A 'required' /
27
+ * 'additionalProperties' error points at the parent object, so the named property is appended.
28
+ */
29
+ export declare function AjvErrorFieldPath(error: ErrorObject): string;
30
+ /** Build the thrown error for a failed validation, carrying the layer, the field path and Ajv's errors. */
31
+ export declare function SchemaValidateErrorOf(layerId: string, ajvErrors: ErrorObject[] | null | undefined): CodecSchemaValidateError;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeriveContentConstraints = DeriveContentConstraints;
4
+ exports.CompileSchemaValidator = CompileSchemaValidator;
5
+ exports.SchemaValidatorOf = SchemaValidatorOf;
6
+ exports.AjvErrorFieldPath = AjvErrorFieldPath;
7
+ exports.SchemaValidateErrorOf = SchemaValidateErrorOf;
8
+ const ajv_1 = require("ajv");
9
+ const ip_address_1 = require("ip-address");
10
+ const CodecSchemaValidateError_1 = require("../errors/CodecSchemaValidateError");
11
+ const StringContentEncodingEnum_1 = require("./StringContentEncodingEnum");
12
+ /**
13
+ * Dotted-quad IPv4: four 0–255 decimal octets. Leading zeros ('010') are accepted because encode
14
+ * parses each octet as decimal (IPv4ToBuffer), so such input already encoded deterministically.
15
+ */
16
+ const IPV4_PATTERN = /^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/;
17
+ /** Colon-separated 6-octet MAC (what decode emits and encode parses). */
18
+ const MAC_PATTERN = /^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/;
19
+ /** A BigInt-convertible integer string: decimal (optionally negative) or 0x-hex. */
20
+ const BIGINT_PATTERN = '^(-?[0-9]+|0[xX][0-9a-fA-F]+)$';
21
+ /** Ajv `format` name each address content encoding validates against. */
22
+ const CONTENT_ENCODING_FORMATS = {
23
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.IPv4]: 'ipv4',
24
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.IPv6]: 'ipv6',
25
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.MAC]: 'mac'
26
+ };
27
+ /**
28
+ * Derive the validation keywords a string field's `contentEncoding` implies, in place: an ipv4/ipv6/mac
29
+ * field gets `format: 'ipv4'|'ipv6'|'mac'`, a bigint field gets a numeric `pattern`. An explicit
30
+ * `format`/`pattern` on the field is left alone. Applied to every published schema (PROTOCOL_SCHEMA)
31
+ * and to every compiled validator, so the shape a UI sees and the shape encode enforces are the same,
32
+ * and every address field is constrained consistently without repeating the keyword per field.
33
+ */
34
+ function DeriveContentConstraints(node) {
35
+ if (!node || typeof node !== 'object')
36
+ return node;
37
+ if (Array.isArray(node)) {
38
+ node.forEach((item) => DeriveContentConstraints(item));
39
+ return node;
40
+ }
41
+ const schemaNode = node;
42
+ const encoding = schemaNode.contentEncoding;
43
+ if (typeof encoding === 'string') {
44
+ if (CONTENT_ENCODING_FORMATS[encoding] && schemaNode.format === undefined)
45
+ schemaNode.format = CONTENT_ENCODING_FORMATS[encoding];
46
+ if (encoding === StringContentEncodingEnum_1.StringContentEncodingEnum.BIGINT && schemaNode.pattern === undefined)
47
+ schemaNode.pattern = BIGINT_PATTERN;
48
+ }
49
+ for (const key of ['properties', 'items', 'anyOf', 'oneOf', 'allOf', 'definitions', '$defs']) {
50
+ const child = schemaNode[key];
51
+ if (!child || typeof child !== 'object')
52
+ continue;
53
+ if (key === 'properties' || key === 'definitions' || key === '$defs')
54
+ Object.values(child).forEach((value) => DeriveContentConstraints(value));
55
+ else
56
+ DeriveContentConstraints(child);
57
+ }
58
+ return node;
59
+ }
60
+ //Own-property slot on each header class holding its compiled validator. Own (not inherited) so a
61
+ //custom codec extending a built-in compiles its own schema instead of reusing the base class's.
62
+ const VALIDATOR_KEY = '__validate';
63
+ /**
64
+ * Compile the Ajv shape validator for a protocol schema. The schema's decode/encode closures are
65
+ * stripped first (the same JSON round-trip that produces PROTOCOL_SCHEMA), so only the declarative
66
+ * shell is compiled. One place for the Ajv options keeps every validator identical.
67
+ */
68
+ function CompileSchemaValidator(schema) {
69
+ const ajv = new ajv_1.Ajv({
70
+ strict: false,
71
+ useDefaults: true,
72
+ coerceTypes: true
73
+ });
74
+ ajv.addFormat('ipv4', IPV4_PATTERN);
75
+ ajv.addFormat('ipv6', (value) => ip_address_1.Address6.isValid(value));
76
+ ajv.addFormat('mac', MAC_PATTERN);
77
+ return ajv.compile(DeriveContentConstraints(JSON.parse(JSON.stringify(schema))));
78
+ }
79
+ /**
80
+ * The validator for a header class, compiled on first use and cached on that class. Compiling all
81
+ * ~190 schemas eagerly cost ~0.5 s at `new Codec()`; lazily, a codec only pays for the protocols it
82
+ * actually encodes.
83
+ */
84
+ function SchemaValidatorOf(headerClass, schema) {
85
+ if (Object.hasOwn(headerClass, VALIDATOR_KEY))
86
+ return headerClass[VALIDATOR_KEY];
87
+ const validate = CompileSchemaValidator(schema);
88
+ Object.defineProperty(headerClass, VALIDATOR_KEY, { enumerable: false, configurable: false, writable: false, value: validate });
89
+ return validate;
90
+ }
91
+ /**
92
+ * Ajv instancePath (JSON Pointer, '/goosePdu/allData/0/dataType') → the dotted field path the codec
93
+ * uses everywhere else for errors ('goosePdu.allData[0].dataType'). A 'required' /
94
+ * 'additionalProperties' error points at the parent object, so the named property is appended.
95
+ */
96
+ function AjvErrorFieldPath(error) {
97
+ const segments = error.instancePath
98
+ .split('/')
99
+ .slice(1)
100
+ .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'));
101
+ const params = error.params;
102
+ if (error.keyword === 'required' && typeof params.missingProperty === 'string')
103
+ segments.push(params.missingProperty);
104
+ if (error.keyword === 'additionalProperties' && typeof params.additionalProperty === 'string')
105
+ segments.push(params.additionalProperty);
106
+ let path = '';
107
+ for (const segment of segments) {
108
+ if (/^\d+$/.test(segment))
109
+ path += `[${segment}]`;
110
+ else
111
+ path += path ? `.${segment}` : segment;
112
+ }
113
+ return path;
114
+ }
115
+ /** Build the thrown error for a failed validation, carrying the layer, the field path and Ajv's errors. */
116
+ function SchemaValidateErrorOf(layerId, ajvErrors) {
117
+ const errors = (ajvErrors ? ajvErrors : []).map((error) => ({
118
+ instancePath: error.instancePath,
119
+ schemaPath: error.schemaPath,
120
+ keyword: error.keyword,
121
+ params: error.params,
122
+ message: error.message ? error.message : '',
123
+ path: AjvErrorFieldPath(error)
124
+ }));
125
+ //Report the most specific failure. Inside an anyOf (option/item variants) Ajv lists every failed
126
+ //branch, and the first is usually just "must be equal to constant" on the variant discriminator
127
+ //of a branch that was never meant to match; the deepest instancePath is the real offending field.
128
+ //At equal depth a non-`const` failure wins over a sibling variant's discriminator mismatch. Ties
129
+ //otherwise keep Ajv's order, so a plain (non-anyOf) failure reports exactly Ajv's first error.
130
+ const score = (issue) => issue.instancePath.split('/').length * 2 + (issue.keyword === 'const' ? 0 : 1);
131
+ const primary = errors.reduce((best, issue) => (!best || score(issue) > score(best) ? issue : best), undefined);
132
+ return new CodecSchemaValidateError_1.CodecSchemaValidateError(primary && primary.message ? primary.message : 'Unknown Error', {
133
+ layerId: layerId,
134
+ path: primary ? primary.path : '',
135
+ errors: errors
136
+ });
137
+ }
@@ -5,6 +5,9 @@ export interface ProtocolFieldJSONSchema extends JSONSchema7 {
5
5
  decode?: () => void | Promise<void>;
6
6
  label?: string;
7
7
  hidden?: boolean;
8
+ readOnly?: boolean;
9
+ autoCalculated?: boolean;
10
+ byteAlignment?: number;
8
11
  $defs?: {
9
12
  [key: string]: ProtocolFieldJSONSchemaDefinition;
10
13
  } | undefined;
@@ -17,7 +20,7 @@ export interface ProtocolFieldJSONSchema extends JSONSchema7 {
17
20
  patternProperties?: {
18
21
  [key: string]: ProtocolFieldJSONSchemaDefinition;
19
22
  } | undefined;
20
- additionalProperties?: ProtocolFieldJSONSchemaDefinition | undefined;
23
+ additionalProperties?: ProtocolFieldJSONSchemaDefinition | boolean | undefined;
21
24
  dependencies?: {
22
25
  [key: string]: ProtocolFieldJSONSchemaDefinition | string[];
23
26
  } | undefined;
@@ -14,7 +14,7 @@ export interface ProtocolJSONSchema extends JSONSchema7 {
14
14
  patternProperties?: {
15
15
  [key: string]: ProtocolFieldJSONSchemaDefinition;
16
16
  } | undefined;
17
- additionalProperties?: ProtocolFieldJSONSchemaDefinition | undefined;
17
+ additionalProperties?: ProtocolFieldJSONSchemaDefinition | boolean | undefined;
18
18
  dependencies?: {
19
19
  [key: string]: ProtocolFieldJSONSchemaDefinition | string[];
20
20
  } | undefined;
@@ -1,5 +1,16 @@
1
+ /**
2
+ * How serious a recorded codec error is:
3
+ * - `error`: the field could not be decoded/encoded as given (malformed bytes on decode; an internal
4
+ * failure or an unencodable value on encode, so the emitted layer may be incomplete).
5
+ * - `warning`: encode wrote the layer but had to adjust or flag the input (value clamped to its
6
+ * range, a semantically odd value such as IPv4 version != 4, a checksum that could not be computed).
7
+ * - `info`: encode used a field's default because the input left it out ("Not Found").
8
+ */
9
+ export type CodecErrorSeverity = 'error' | 'warning' | 'info';
1
10
  export type CodecErrorInfo = {
2
11
  id: string;
3
12
  path: string;
4
13
  message: string;
14
+ /** Always set by the built-in codec; optional in the type so hand-built entries stay valid. */
15
+ severity?: CodecErrorSeverity;
5
16
  };
@@ -1,7 +1,20 @@
1
+ /**
2
+ * A parent a content-heuristic header can follow (BaseHeader.heuristicParents): the parent layer id,
3
+ * optionally with the parent field value the child needs (e.g. RDP needs COTP pduType 0xE0, a
4
+ * Connection Request) — reported by allowedNextLayers() as that child's discriminator.
5
+ */
6
+ export type HeuristicParent = string | {
7
+ parent: string;
8
+ discriminator: {
9
+ field: string;
10
+ value: string | number;
11
+ };
12
+ };
1
13
  /**
2
14
  * A layer that may follow a given parent layer in the editor's "add next layer" menu. `discriminator`
3
15
  * tells the caller which parent field to set (and to what) so decode would route to this layer;
4
- * it is null for RawData, which may always follow any layer.
16
+ * it is null when there is no parent field to set: RawData (which may follow any layer), and children
17
+ * recognized by their own content or by a value encode derives (LLC after eth, COTP after TPKT, …).
5
18
  */
6
19
  export type NextLayer = {
7
20
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netkitty/codec",
3
- "version": "1.2.1",
3
+ "version": "2.1.0",
4
4
  "description": "Schema-driven packet codec: encode/decode 180+ network and industrial (OT/ICS/SCADA) protocol headers — TCP/IP, TLS, HTTP/2, DNS, MQTT, plus Modbus, DNP3, IEC 61850 (GOOSE/SV/MMS), IEC 104, S7comm, OPC UA, PROFINET, EtherCAT, BACnet and more.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -138,5 +138,5 @@
138
138
  },
139
139
  "homepage": "https://github.com/myq1991/netkitty/tree/main/packages/codec#readme",
140
140
  "bugs": "https://github.com/myq1991/netkitty/issues",
141
- "gitHead": "519fdefcb5c76f69fade408cc36e0c2fa69ccad4"
141
+ "gitHead": "c392c19e0fbf6de6d2ce5213ea775c6033ff93cd"
142
142
  }