@pezkuwi/types-codec 16.5.5

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 (197) hide show
  1. package/README.md +3 -0
  2. package/build/abstract/Array.d.ts +89 -0
  3. package/build/abstract/Base.d.ts +75 -0
  4. package/build/abstract/Int.d.ts +80 -0
  5. package/build/abstract/Object.d.ts +67 -0
  6. package/build/abstract/index.d.ts +3 -0
  7. package/build/base/Compact.d.ts +88 -0
  8. package/build/base/DoNotConstruct.d.ts +63 -0
  9. package/build/base/Enum.d.ts +118 -0
  10. package/build/base/Int.d.ts +16 -0
  11. package/build/base/Null.d.ts +56 -0
  12. package/build/base/Option.d.ts +94 -0
  13. package/build/base/Result.d.ts +38 -0
  14. package/build/base/Tuple.d.ts +42 -0
  15. package/build/base/UInt.d.ts +15 -0
  16. package/build/base/Vec.d.ts +28 -0
  17. package/build/base/VecAny.d.ts +15 -0
  18. package/build/base/VecFixed.d.ts +30 -0
  19. package/build/base/index.d.ts +12 -0
  20. package/build/bundle.d.ts +7 -0
  21. package/build/extended/BTreeMap.d.ts +5 -0
  22. package/build/extended/BTreeSet.d.ts +64 -0
  23. package/build/extended/BitVec.d.ts +37 -0
  24. package/build/extended/Bytes.d.ts +29 -0
  25. package/build/extended/HashMap.d.ts +5 -0
  26. package/build/extended/Linkage.d.ts +37 -0
  27. package/build/extended/Map.d.ts +59 -0
  28. package/build/extended/OptionBool.d.ts +36 -0
  29. package/build/extended/Range.d.ts +29 -0
  30. package/build/extended/RangeInclusive.d.ts +6 -0
  31. package/build/extended/Type.d.ts +16 -0
  32. package/build/extended/U8aFixed.d.ts +16 -0
  33. package/build/extended/WrapperKeepOpaque.d.ts +40 -0
  34. package/build/extended/WrapperOpaque.d.ts +10 -0
  35. package/build/extended/index.d.ts +14 -0
  36. package/build/index.d.ts +2 -0
  37. package/build/native/Bool.d.ts +71 -0
  38. package/build/native/Date.d.ts +84 -0
  39. package/build/native/Float.d.ts +68 -0
  40. package/build/native/Json.d.ts +69 -0
  41. package/build/native/Raw.d.ts +87 -0
  42. package/build/native/Set.d.ts +84 -0
  43. package/build/native/Struct.d.ts +106 -0
  44. package/build/native/Text.d.ts +77 -0
  45. package/build/native/index.d.ts +8 -0
  46. package/build/packageDetect.d.ts +1 -0
  47. package/build/packageInfo.d.ts +6 -0
  48. package/build/primitive/F32.d.ts +11 -0
  49. package/build/primitive/F64.d.ts +11 -0
  50. package/build/primitive/I128.d.ts +11 -0
  51. package/build/primitive/I16.d.ts +11 -0
  52. package/build/primitive/I256.d.ts +11 -0
  53. package/build/primitive/I32.d.ts +11 -0
  54. package/build/primitive/I64.d.ts +11 -0
  55. package/build/primitive/I8.d.ts +11 -0
  56. package/build/primitive/ISize.d.ts +12 -0
  57. package/build/primitive/U128.d.ts +11 -0
  58. package/build/primitive/U16.d.ts +11 -0
  59. package/build/primitive/U256.d.ts +11 -0
  60. package/build/primitive/U32.d.ts +11 -0
  61. package/build/primitive/U64.d.ts +11 -0
  62. package/build/primitive/U8.d.ts +11 -0
  63. package/build/primitive/USize.d.ts +12 -0
  64. package/build/primitive/index.d.ts +16 -0
  65. package/build/types/codec.d.ts +113 -0
  66. package/build/types/helpers.d.ts +27 -0
  67. package/build/types/index.d.ts +4 -0
  68. package/build/types/interfaces.d.ts +74 -0
  69. package/build/types/registry.d.ts +67 -0
  70. package/build/utils/compareArray.d.ts +1 -0
  71. package/build/utils/compareMap.d.ts +1 -0
  72. package/build/utils/compareSet.d.ts +1 -0
  73. package/build/utils/decodeU8a.d.ts +26 -0
  74. package/build/utils/index.d.ts +8 -0
  75. package/build/utils/sanitize.d.ts +15 -0
  76. package/build/utils/sortValues.d.ts +12 -0
  77. package/build/utils/toConstructors.d.ts +16 -0
  78. package/build/utils/typesToMap.d.ts +2 -0
  79. package/build/utils/util.d.ts +3 -0
  80. package/package.json +34 -0
  81. package/src/abstract/Array.ts +213 -0
  82. package/src/abstract/Base.ts +129 -0
  83. package/src/abstract/Int.ts +271 -0
  84. package/src/abstract/Object.ts +99 -0
  85. package/src/abstract/index.ts +6 -0
  86. package/src/base/Compact.spec.ts +99 -0
  87. package/src/base/Compact.ts +198 -0
  88. package/src/base/DoNotConstruct.spec.ts +23 -0
  89. package/src/base/DoNotConstruct.ts +118 -0
  90. package/src/base/Enum.spec.ts +487 -0
  91. package/src/base/Enum.ts +460 -0
  92. package/src/base/Int.spec.ts +225 -0
  93. package/src/base/Int.ts +34 -0
  94. package/src/base/Null.spec.ts +41 -0
  95. package/src/base/Null.ts +96 -0
  96. package/src/base/Option.spec.ts +216 -0
  97. package/src/base/Option.ts +275 -0
  98. package/src/base/Result.spec.ts +64 -0
  99. package/src/base/Result.ts +79 -0
  100. package/src/base/Tuple.spec.ts +161 -0
  101. package/src/base/Tuple.ts +149 -0
  102. package/src/base/UInt.spec.ts +192 -0
  103. package/src/base/UInt.ts +30 -0
  104. package/src/base/Vec.spec.ts +224 -0
  105. package/src/base/Vec.ts +133 -0
  106. package/src/base/VecAny.ts +23 -0
  107. package/src/base/VecFixed.spec.ts +78 -0
  108. package/src/base/VecFixed.ts +92 -0
  109. package/src/base/index.ts +15 -0
  110. package/src/bundle.ts +13 -0
  111. package/src/checkTypes.manual.ts +12 -0
  112. package/src/extended/BTreeMap.spec.ts +245 -0
  113. package/src/extended/BTreeMap.ts +16 -0
  114. package/src/extended/BTreeSet.spec.ts +260 -0
  115. package/src/extended/BTreeSet.ts +233 -0
  116. package/src/extended/BitVec.spec.ts +97 -0
  117. package/src/extended/BitVec.ts +137 -0
  118. package/src/extended/Bytes.spec.ts +75 -0
  119. package/src/extended/Bytes.ts +88 -0
  120. package/src/extended/HashMap.spec.ts +36 -0
  121. package/src/extended/HashMap.ts +16 -0
  122. package/src/extended/Linkage.spec.ts +43 -0
  123. package/src/extended/Linkage.ts +81 -0
  124. package/src/extended/Map.spec.ts +123 -0
  125. package/src/extended/Map.ts +255 -0
  126. package/src/extended/OptionBool.spec.ts +49 -0
  127. package/src/extended/OptionBool.ts +93 -0
  128. package/src/extended/Range.spec.ts +37 -0
  129. package/src/extended/Range.ts +56 -0
  130. package/src/extended/RangeInclusive.ts +20 -0
  131. package/src/extended/Type.spec.ts +118 -0
  132. package/src/extended/Type.ts +29 -0
  133. package/src/extended/U8aFixed.spec.ts +117 -0
  134. package/src/extended/U8aFixed.ts +57 -0
  135. package/src/extended/WrapperKeepOpaque.spec.ts +101 -0
  136. package/src/extended/WrapperKeepOpaque.ts +128 -0
  137. package/src/extended/WrapperOpaque.spec.ts +58 -0
  138. package/src/extended/WrapperOpaque.ts +27 -0
  139. package/src/extended/index.ts +17 -0
  140. package/src/index.ts +6 -0
  141. package/src/mod.ts +4 -0
  142. package/src/native/Bool.spec.ts +74 -0
  143. package/src/native/Bool.ts +137 -0
  144. package/src/native/Date.spec.ts +85 -0
  145. package/src/native/Date.ts +169 -0
  146. package/src/native/Float.spec.ts +51 -0
  147. package/src/native/Float.ts +136 -0
  148. package/src/native/Json.ts +147 -0
  149. package/src/native/Raw.spec.ts +113 -0
  150. package/src/native/Raw.ts +171 -0
  151. package/src/native/Set.spec.ts +116 -0
  152. package/src/native/Set.ts +269 -0
  153. package/src/native/Struct.data.ts +4 -0
  154. package/src/native/Struct.spec.ts +411 -0
  155. package/src/native/Struct.ts +338 -0
  156. package/src/native/Text.spec.ts +85 -0
  157. package/src/native/Text.ts +184 -0
  158. package/src/native/index.ts +11 -0
  159. package/src/packageDetect.ts +11 -0
  160. package/src/packageInfo.ts +6 -0
  161. package/src/primitive/F32.ts +14 -0
  162. package/src/primitive/F64.ts +14 -0
  163. package/src/primitive/I128.ts +14 -0
  164. package/src/primitive/I16.ts +14 -0
  165. package/src/primitive/I256.ts +14 -0
  166. package/src/primitive/I32.ts +14 -0
  167. package/src/primitive/I64.ts +14 -0
  168. package/src/primitive/I8.ts +14 -0
  169. package/src/primitive/ISize.ts +21 -0
  170. package/src/primitive/U128.ts +14 -0
  171. package/src/primitive/U16.ts +14 -0
  172. package/src/primitive/U256.ts +14 -0
  173. package/src/primitive/U32.ts +14 -0
  174. package/src/primitive/U64.ts +14 -0
  175. package/src/primitive/U8.ts +14 -0
  176. package/src/primitive/USize.ts +21 -0
  177. package/src/primitive/index.ts +19 -0
  178. package/src/test/performance.ts +61 -0
  179. package/src/types/codec.ts +140 -0
  180. package/src/types/helpers.ts +50 -0
  181. package/src/types/index.ts +7 -0
  182. package/src/types/interfaces.ts +98 -0
  183. package/src/types/registry.ts +86 -0
  184. package/src/utils/compareArray.ts +22 -0
  185. package/src/utils/compareMap.ts +40 -0
  186. package/src/utils/compareSet.ts +23 -0
  187. package/src/utils/decodeU8a.ts +123 -0
  188. package/src/utils/index.ts +11 -0
  189. package/src/utils/sanitize.spec.ts +89 -0
  190. package/src/utils/sanitize.ts +290 -0
  191. package/src/utils/sortValues.ts +103 -0
  192. package/src/utils/toConstructors.ts +46 -0
  193. package/src/utils/typesToMap.ts +14 -0
  194. package/src/utils/util.ts +8 -0
  195. package/tsconfig.build.json +16 -0
  196. package/tsconfig.build.tsbuildinfo +1 -0
  197. package/tsconfig.spec.json +21 -0
@@ -0,0 +1,338 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { HexString } from '@pezkuwi/util/types';
5
+ import type { AnyJson, BareOpts, Codec, CodecClass, DefinitionSetter, Inspect, IStruct, IU8a, Registry } from '../types/index.js';
6
+
7
+ import { isBoolean, isHex, isObject, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, u8aConcatStrict, u8aToHex, u8aToU8a } from '@pezkuwi/util';
8
+
9
+ import { compareMap, decodeU8aStruct, mapToTypeMap, typesToMap } from '../utils/index.js';
10
+
11
+ type TypesDef<T = Codec> = Record<string, string | CodecClass<T>>;
12
+
13
+ type Definition = [CodecClass[], string[]];
14
+
15
+ function noopSetDefinition (d: Definition): Definition {
16
+ return d;
17
+ }
18
+
19
+ /** @internal */
20
+ function decodeStructFromObject (registry: Registry, [Types, keys]: Definition, value: any, jsonMap: Map<string, string>): [Iterable<[string, Codec]>, number] {
21
+ let jsonObj: Record<string, unknown> | undefined;
22
+ const typeofArray = Array.isArray(value);
23
+ const typeofMap = value instanceof Map;
24
+ const count = keys.length;
25
+
26
+ if (!typeofArray && !typeofMap && !isObject(value)) {
27
+ throw new Error(`Struct: Cannot decode value ${stringify(value)} (typeof ${typeof value}), expected an input object, map or array`);
28
+ } else if (typeofArray && value.length !== count) {
29
+ throw new Error(`Struct: Unable to map ${stringify(value)} array to object with known keys ${keys.join(', ')}`);
30
+ }
31
+
32
+ const raw = new Array<[string, Codec]>(count);
33
+
34
+ for (let i = 0; i < count; i++) {
35
+ const key = keys[i];
36
+ const jsonKey = jsonMap.get(key) || key;
37
+ const Type = Types[i];
38
+ let assign: unknown;
39
+
40
+ try {
41
+ if (typeofArray) {
42
+ assign = value[i] as unknown;
43
+ } else if (typeofMap) {
44
+ assign = jsonKey && value.get(jsonKey);
45
+ } else {
46
+ assign = jsonKey && Object.prototype.hasOwnProperty.call(value, jsonKey) ? value[jsonKey] as unknown : undefined;
47
+
48
+ if (isUndefined(assign)) {
49
+ if (isUndefined(jsonObj)) {
50
+ const entries = Object.entries(value);
51
+
52
+ jsonObj = {};
53
+
54
+ for (let e = 0, ecount = entries.length; e < ecount; e++) {
55
+ if (Object.prototype.hasOwnProperty.call(value, entries[e][0])) {
56
+ jsonObj[stringCamelCase(entries[e][0])] = entries[e][1];
57
+ }
58
+ }
59
+ }
60
+
61
+ assign = jsonKey && Object.prototype.hasOwnProperty.call(jsonObj, jsonKey) ? jsonObj[jsonKey] : undefined;
62
+ }
63
+ }
64
+
65
+ raw[i] = [
66
+ key,
67
+ assign instanceof Type
68
+ ? assign
69
+ : new Type(registry, assign)
70
+ ];
71
+ } catch (error) {
72
+ let type = Type.name;
73
+
74
+ try {
75
+ type = new Type(registry).toRawType();
76
+ } catch {
77
+ // ignore
78
+ }
79
+
80
+ throw new Error(`Struct: failed on ${jsonKey}: ${type}:: ${(error as Error).message}`);
81
+ }
82
+ }
83
+
84
+ return [raw, 0];
85
+ }
86
+
87
+ /**
88
+ * @name Struct
89
+ * @description
90
+ * A Struct defines an Object with key-value pairs - where the values are Codec values. It removes
91
+ * a lot of repetition from the actual coding, define a structure type, pass it the key/Codec
92
+ * values in the constructor and it manages the decoding. It is important that the constructor
93
+ * values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical,
94
+ * it needs to decoded in the specific defined order.
95
+ * @noInheritDoc
96
+ */
97
+ export class Struct<
98
+ // The actual Class structure, i.e. key -> Class
99
+ S extends TypesDef = TypesDef,
100
+ // input values, mapped by key can be anything (construction)
101
+ V extends { [K in keyof S]: any } = { [K in keyof S]: any },
102
+ // type names, mapped by key, name of Class in S
103
+ E extends { [K in keyof S]: string } = { [K in keyof S]: string }> extends Map<keyof S, Codec> implements IStruct<keyof S> {
104
+ readonly registry: Registry;
105
+
106
+ public createdAtHash?: IU8a | undefined;
107
+ public initialU8aLength?: number;
108
+ public isStorageFallback?: boolean;
109
+
110
+ readonly #jsonMap: Map<keyof S, string>;
111
+ readonly #Types: Definition;
112
+
113
+ constructor (registry: Registry, Types: S, value?: V | Map<unknown, unknown> | unknown[] | HexString | null, jsonMap = new Map<string, string>(), { definition, setDefinition = noopSetDefinition }: DefinitionSetter<Definition> = {}) {
114
+ const typeMap = definition || setDefinition(mapToTypeMap(registry, Types));
115
+ const [decoded, decodedLength] = isU8a(value) || isHex(value)
116
+ ? decodeU8aStruct(registry, new Array<[string, Codec]>(typeMap[0].length), u8aToU8a(value), typeMap)
117
+ : value instanceof Struct
118
+ ? [value as Iterable<[string, Codec]>, 0]
119
+ : decodeStructFromObject(registry, typeMap, value || {}, jsonMap);
120
+
121
+ super(decoded);
122
+
123
+ this.initialU8aLength = decodedLength;
124
+ this.registry = registry;
125
+ this.#jsonMap = jsonMap;
126
+ this.#Types = typeMap;
127
+ }
128
+
129
+ public static with<S extends TypesDef> (Types: S, jsonMap?: Map<string, string>): CodecClass<Struct<S>> {
130
+ let definition: Definition | undefined;
131
+
132
+ // eslint-disable-next-line no-return-assign
133
+ const setDefinition = (d: Definition) =>
134
+ definition = d;
135
+
136
+ return class extends Struct<S> {
137
+ static {
138
+ const keys = Object.keys(Types);
139
+
140
+ objectProperties(this.prototype, keys, (k: string, _: number, self: Struct) =>
141
+ self.get(k)
142
+ );
143
+ }
144
+
145
+ constructor (registry: Registry, value?: unknown) {
146
+ super(registry, Types, value as HexString, jsonMap, { definition, setDefinition });
147
+ }
148
+ };
149
+ }
150
+
151
+ /**
152
+ * @description The available keys for this struct
153
+ */
154
+ public get defKeys (): string[] {
155
+ return this.#Types[1];
156
+ }
157
+
158
+ /**
159
+ * @description Checks if the value is an empty value '{}'
160
+ */
161
+ public get isEmpty (): boolean {
162
+ return [...this.keys()].length === 0;
163
+ }
164
+
165
+ /**
166
+ * @description The length of the value when encoded as a Uint8Array
167
+ */
168
+ public get encodedLength (): number {
169
+ let total = 0;
170
+
171
+ for (const v of this.values()) {
172
+ total += v.encodedLength;
173
+ }
174
+
175
+ return total;
176
+ }
177
+
178
+ /**
179
+ * @description returns a hash of the contents
180
+ */
181
+ public get hash (): IU8a {
182
+ return this.registry.hash(this.toU8a());
183
+ }
184
+
185
+ /**
186
+ * @description Returns the Type description of the structure
187
+ */
188
+ public get Type (): E {
189
+ const result: Record<string, string> = {};
190
+ const [Types, keys] = this.#Types;
191
+
192
+ for (let i = 0, count = keys.length; i < count; i++) {
193
+ result[keys[i]] = new Types[i](this.registry).toRawType();
194
+ }
195
+
196
+ return result as E;
197
+ }
198
+
199
+ /**
200
+ * @description Compares the value of the input to see if there is a match
201
+ */
202
+ public eq (other?: unknown): boolean {
203
+ return compareMap(this, other);
204
+ }
205
+
206
+ /**
207
+ * @description Returns a specific names entry in the structure
208
+ * @param key The name of the entry to retrieve
209
+ */
210
+ public override get (key: keyof S): Codec | undefined {
211
+ return super.get(key);
212
+ }
213
+
214
+ /**
215
+ * @description Returns the values of a member at a specific index (Rather use get(name) for performance)
216
+ */
217
+ public getAtIndex (index: number): Codec {
218
+ return this.toArray()[index];
219
+ }
220
+
221
+ /**
222
+ * @description Returns the a types value by name
223
+ */
224
+ public getT <T = Codec> (key: string): T {
225
+ return super.get(key) as unknown as T;
226
+ }
227
+
228
+ /**
229
+ * @description Returns a breakdown of the hex encoding for this Codec
230
+ */
231
+ public inspect (isBare?: BareOpts): Inspect {
232
+ const inner: Inspect[] = [];
233
+
234
+ for (const [k, v] of this.entries()) {
235
+ inner.push({
236
+ ...v.inspect(
237
+ !isBare || isBoolean(isBare)
238
+ ? isBare
239
+ : isBare[k]
240
+ ),
241
+ name: stringCamelCase(k as string)
242
+ });
243
+ }
244
+
245
+ return {
246
+ inner
247
+ };
248
+ }
249
+
250
+ /**
251
+ * @description Converts the Object to an standard JavaScript Array
252
+ */
253
+ public toArray (): Codec[] {
254
+ return [...this.values()];
255
+ }
256
+
257
+ /**
258
+ * @description Returns a hex string representation of the value
259
+ */
260
+ public toHex (): HexString {
261
+ return u8aToHex(this.toU8a());
262
+ }
263
+
264
+ /**
265
+ * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
266
+ */
267
+ public toHuman (isExtended?: boolean, disableAscii?: boolean): Record<string, AnyJson> {
268
+ const json: Record<string, AnyJson> = {};
269
+
270
+ for (const [k, v] of this.entries()) {
271
+ json[k as string] = v.toHuman(isExtended, disableAscii);
272
+ }
273
+
274
+ return json;
275
+ }
276
+
277
+ /**
278
+ * @description Converts the Object to JSON, typically used for RPC transfers
279
+ */
280
+ public toJSON (): Record<string, AnyJson> {
281
+ const json: Record<string, AnyJson> = {};
282
+
283
+ for (const [k, v] of this.entries()) {
284
+ // Here we pull out the entry against the JSON mapping (if supplied)
285
+ // since this representation goes over RPC and needs to be correct
286
+ json[(this.#jsonMap.get(k) || k) as string] = v.toJSON();
287
+ }
288
+
289
+ return json;
290
+ }
291
+
292
+ /**
293
+ * @description Converts the value in a best-fit primitive form
294
+ */
295
+ public toPrimitive (disableAscii?: boolean): Record<string, AnyJson> {
296
+ const json: Record<string, AnyJson> = {};
297
+
298
+ for (const [k, v] of this.entries()) {
299
+ json[k as string] = v.toPrimitive(disableAscii);
300
+ }
301
+
302
+ return json;
303
+ }
304
+
305
+ /**
306
+ * @description Returns the base runtime type name for this instance
307
+ */
308
+ public toRawType (): string {
309
+ return stringify(typesToMap(this.registry, this.#Types));
310
+ }
311
+
312
+ /**
313
+ * @description Returns the string representation of the value
314
+ */
315
+ public override toString (): string {
316
+ return stringify(this.toJSON());
317
+ }
318
+
319
+ /**
320
+ * @description Encodes the value as a Uint8Array as per the SCALE specifications
321
+ * @param isBare true when the value has none of the type-specific prefixes (internal)
322
+ */
323
+ public toU8a (isBare?: BareOpts): Uint8Array {
324
+ const encoded: Uint8Array[] = [];
325
+
326
+ for (const [k, v] of this.entries()) {
327
+ encoded.push(
328
+ v.toU8a(
329
+ !isBare || isBoolean(isBare)
330
+ ? isBare
331
+ : isBare[k]
332
+ )
333
+ );
334
+ }
335
+
336
+ return u8aConcatStrict(encoded);
337
+ }
338
+ }
@@ -0,0 +1,85 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
+
6
+ import type { CodecTo } from '@pezkuwi/types-codec/types';
7
+
8
+ import { TypeRegistry } from '@pezkuwi/types';
9
+ import { Bytes, Raw, Text } from '@pezkuwi/types-codec';
10
+ import { stringToU8a } from '@pezkuwi/util';
11
+
12
+ import { perf } from '../test/performance.js';
13
+
14
+ describe('Text', (): void => {
15
+ const registry = new TypeRegistry();
16
+
17
+ describe('decode', (): void => {
18
+ const testDecode = (type: string, input: null | string | Uint8Array | { toString: () => string }, expected: string, toFn: 'toString' | 'toHex' | 'toHuman' = 'toString'): void =>
19
+ it(`can decode from ${type}`, (): void => {
20
+ expect(new Text(registry, input)[toFn]()).toBe(expected);
21
+ });
22
+
23
+ testDecode('string', 'foo', 'foo');
24
+ testDecode('Text', new Text(registry, 'foo'), 'foo');
25
+ testDecode('Uint8Array', Uint8Array.from([12, 102, 111, 111]), 'foo');
26
+ testDecode('Raw', new Raw(registry, Uint8Array.from([102, 111, 111])), 'foo'); // no length
27
+ testDecode('Raw', new Raw(registry, Uint8Array.from([102, 111, 111])), 'foo', 'toHuman'); // no length
28
+ testDecode('Bytes', new Bytes(registry, Uint8Array.from([12, 102, 111, 111])), 'foo'); // length-aware encoding
29
+ testDecode('Bytes', new Bytes(registry, Uint8Array.from([12, 102, 111, 111])), 'foo', 'toHuman'); // length-aware encoding
30
+ testDecode('object with `toString()`', { toString (): string {
31
+ return 'foo';
32
+ } }, 'foo');
33
+ testDecode('hex input value', new Text(registry, '0x12345678'), '0x12345678', 'toHex');
34
+ testDecode('null', null, '');
35
+ });
36
+
37
+ describe('encode', (): void => {
38
+ const testEncode = (to: CodecTo, expected: string | Uint8Array): void =>
39
+ it(`can encode ${to}`, (): void => {
40
+ expect(new Text(registry, 'foo')[to]()).toEqual(expected);
41
+ });
42
+
43
+ testEncode('toHex', '0x666f6f');
44
+ testEncode('toString', 'foo');
45
+ testEncode('toU8a', Uint8Array.from([12, 102, 111, 111]));
46
+ });
47
+
48
+ describe('utils', (): void => {
49
+ it('compares actual string values', (): void => {
50
+ expect(new Text(registry, '123').eq('123')).toBe(true);
51
+ });
52
+
53
+ it('compares actual String values', (): void => {
54
+ expect(new Text(registry, 'XYX').eq(String('XYX'))).toBe(true);
55
+ });
56
+
57
+ it('compares actual non-string values (fails)', (): void => {
58
+ expect(new Text(registry, '123').eq(123)).toBe(false);
59
+ });
60
+
61
+ it('calulates the length & encoded length correctly for ASCII', (): void => {
62
+ const test = new Text(registry, 'abcde');
63
+
64
+ expect(test.encodedLength).toEqual(6);
65
+ expect(test).toHaveLength(5);
66
+ });
67
+
68
+ it('calulates the length & encoded length correctly for non-ASCII', (): void => {
69
+ const test = new Text(registry, '中文');
70
+
71
+ expect(test.encodedLength).toEqual(7);
72
+ expect(test).toHaveLength(2);
73
+ });
74
+
75
+ it('has a sane inspect', (): void => {
76
+ expect(
77
+ new Text(registry, 'abcde').inspect()
78
+ ).toEqual({
79
+ outer: [new Uint8Array([5 << 2]), stringToU8a('abcde')]
80
+ });
81
+ });
82
+ });
83
+
84
+ perf('Text', 100_000, [[new Uint8Array([6 << 2, 102, 111, 111, 102, 111, 111])]], (v: Uint8Array) => new Text(registry, v));
85
+ });
@@ -0,0 +1,184 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { HexString } from '@pezkuwi/util/types';
5
+ import type { AnyString, AnyU8a, Inspect, IText, IU8a, Registry } from '../types/index.js';
6
+
7
+ import { compactAddLength, compactFromU8aLim, compactToU8a, hexToU8a, isHex, isString, isU8a, stringToU8a, u8aToHex, u8aToString } from '@pezkuwi/util';
8
+
9
+ import { Raw } from './Raw.js';
10
+
11
+ const MAX_LENGTH = 128 * 1024;
12
+
13
+ /** @internal */
14
+ function decodeText (value?: null | AnyString | AnyU8a | { toString: () => string }): [string, number] {
15
+ if (isU8a(value)) {
16
+ if (!value.length) {
17
+ return ['', 0];
18
+ }
19
+
20
+ // for Raw, the internal buffer does not have an internal length
21
+ // (the same applies in e.g. Bytes, where length is added at encoding-time)
22
+ if (value instanceof Raw) {
23
+ return [u8aToString(value), 0];
24
+ }
25
+
26
+ const [offset, length] = compactFromU8aLim(value);
27
+ const total = offset + length;
28
+
29
+ if (length > MAX_LENGTH) {
30
+ throw new Error(`Text: length ${length.toString()} exceeds ${MAX_LENGTH}`);
31
+ } else if (total > value.length) {
32
+ throw new Error(`Text: required length less than remainder, expected at least ${total}, found ${value.length}`);
33
+ }
34
+
35
+ return [u8aToString(value.subarray(offset, total)), total];
36
+ } else if (isHex(value)) {
37
+ return [u8aToString(hexToU8a(value)), 0];
38
+ }
39
+
40
+ return [value ? value.toString() : '', 0];
41
+ }
42
+
43
+ /**
44
+ * @name Text
45
+ * @description
46
+ * This is a string wrapper, along with the length. It is used both for strings as well
47
+ * as items such as documentation. It simply extends the standard JS `String` built-in
48
+ * object, inheriting all methods exposed from `String`.
49
+ * @noInheritDoc
50
+ */
51
+ export class Text extends String implements IText {
52
+ readonly registry: Registry;
53
+
54
+ public createdAtHash?: IU8a;
55
+ public initialU8aLength?: number;
56
+ public isStorageFallback?: boolean;
57
+
58
+ #override: string | null = null;
59
+
60
+ constructor (registry: Registry, value?: null | AnyString | AnyU8a | { toString: () => string }) {
61
+ const [str, decodedLength] = decodeText(value);
62
+
63
+ super(str);
64
+
65
+ this.registry = registry;
66
+ this.initialU8aLength = decodedLength;
67
+ }
68
+
69
+ /**
70
+ * @description The length of the value when encoded as a Uint8Array
71
+ */
72
+ public get encodedLength (): number {
73
+ return this.toU8a().length;
74
+ }
75
+
76
+ /**
77
+ * @description returns a hash of the contents
78
+ */
79
+ public get hash (): IU8a {
80
+ return this.registry.hash(this.toU8a());
81
+ }
82
+
83
+ /**
84
+ * @description Checks if the value is an empty value
85
+ */
86
+ public get isEmpty (): boolean {
87
+ return this.length === 0;
88
+ }
89
+
90
+ /**
91
+ * @description The length of the value
92
+ */
93
+ public override get length (): number {
94
+ // only included here since we ignore inherited docs
95
+ return super.length;
96
+ }
97
+
98
+ /**
99
+ * @description Compares the value of the input to see if there is a match
100
+ */
101
+ public eq (other?: unknown): boolean {
102
+ return isString(other)
103
+ ? this.toString() === other.toString()
104
+ : false;
105
+ }
106
+
107
+ /**
108
+ * @description Returns a breakdown of the hex encoding for this Codec
109
+ */
110
+ public inspect (): Inspect {
111
+ const value = stringToU8a(super.toString());
112
+
113
+ return {
114
+ outer: value.length
115
+ ? [compactToU8a(value.length), value]
116
+ : [compactToU8a(value.length)]
117
+ };
118
+ }
119
+
120
+ /**
121
+ * @description Set an override value for this
122
+ */
123
+ public setOverride (override: string): void {
124
+ this.#override = override;
125
+ }
126
+
127
+ /**
128
+ * @description Returns a hex string representation of the value
129
+ */
130
+ public toHex (): HexString {
131
+ // like with Vec<u8>, when we are encoding to hex, we don't actually add
132
+ // the length prefix (it is already implied by the actual string length)
133
+ return u8aToHex(this.toU8a(true));
134
+ }
135
+
136
+ /**
137
+ * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
138
+ */
139
+ public toHuman (): string {
140
+ return this.toJSON();
141
+ }
142
+
143
+ /**
144
+ * @description Converts the Object to JSON, typically used for RPC transfers
145
+ */
146
+ public toJSON (): string {
147
+ return this.toString();
148
+ }
149
+
150
+ /**
151
+ * @description Converts the value in a best-fit primitive form
152
+ */
153
+ public toPrimitive (): string {
154
+ return this.toJSON();
155
+ }
156
+
157
+ /**
158
+ * @description Returns the base runtime type name for this instance
159
+ */
160
+ public toRawType (): string {
161
+ return 'Text';
162
+ }
163
+
164
+ /**
165
+ * @description Returns the string representation of the value
166
+ */
167
+ public override toString (): string {
168
+ return this.#override || super.toString();
169
+ }
170
+
171
+ /**
172
+ * @description Encodes the value as a Uint8Array as per the SCALE specifications
173
+ * @param isBare true when the value has none of the type-specific prefixes (internal)
174
+ */
175
+ public toU8a (isBare?: boolean): Uint8Array {
176
+ // NOTE Here we use the super toString (we are not taking overrides into account,
177
+ // rather encoding the original value the string was constructed with)
178
+ const encoded = stringToU8a(super.toString());
179
+
180
+ return isBare
181
+ ? encoded
182
+ : compactAddLength(encoded);
183
+ }
184
+ }
@@ -0,0 +1,11 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { bool as Bool, bool } from './Bool.js';
5
+ export { CodecDate, CodecDate as Date } from './Date.js';
6
+ export { Float } from './Float.js';
7
+ export { Json } from './Json.js';
8
+ export { Raw } from './Raw.js';
9
+ export { CodecSet, CodecSet as Set } from './Set.js';
10
+ export { Struct } from './Struct.js';
11
+ export { Text } from './Text.js';
@@ -0,0 +1,11 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Do not edit, auto-generated by @polkadot/dev
5
+ // (packageInfo imports will be kept as-is, user-editable)
6
+
7
+ import { detectPackage } from '@pezkuwi/util';
8
+
9
+ import { packageInfo } from './packageInfo.js';
10
+
11
+ detectPackage(packageInfo, null, []);
@@ -0,0 +1,6 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Do not edit, auto-generated by @polkadot/dev
5
+
6
+ export const packageInfo = { name: '@pezkuwi/types-codec', path: 'auto', type: 'auto', version: '16.5.5' };
@@ -0,0 +1,14 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Float } from '../native/Float.js';
5
+
6
+ /**
7
+ * @name f32
8
+ * @description
9
+ * A 32-bit float
10
+ */
11
+ export class f32 extends Float.with(32) {
12
+ // NOTE without this, we cannot properly determine extensions
13
+ readonly __FloatType = 'f32';
14
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Float } from '../native/Float.js';
5
+
6
+ /**
7
+ * @name f64
8
+ * @description
9
+ * A 64-bit float
10
+ */
11
+ export class f64 extends Float.with(64) {
12
+ // NOTE without this, we cannot properly determine extensions
13
+ readonly __FloatType = 'f64';
14
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Int } from '../base/Int.js';
5
+
6
+ /**
7
+ * @name i128
8
+ * @description
9
+ * A 128-bit signed integer
10
+ */
11
+ export class i128 extends Int.with(128) {
12
+ // NOTE without this, we cannot properly determine extensions
13
+ readonly __IntType = 'i128';
14
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright 2017-2025 @polkadot/types-codec authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Int } from '../base/Int.js';
5
+
6
+ /**
7
+ * @name i16
8
+ * @description
9
+ * A 16-bit signed integer
10
+ */
11
+ export class i16 extends Int.with(16) {
12
+ // NOTE without this, we cannot properly determine extensions
13
+ readonly __IntType = 'i16';
14
+ }