@pezkuwi/types-create 16.5.17 → 16.5.19

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 (168) hide show
  1. package/build/LICENSE +201 -0
  2. package/build/README.md +3 -0
  3. package/build/bundle.js +3 -0
  4. package/build/cjs/bundle.d.ts +3 -0
  5. package/build/cjs/bundle.js +9 -0
  6. package/build/cjs/create/class.js +165 -0
  7. package/build/cjs/create/index.js +5 -0
  8. package/build/cjs/create/type.js +66 -0
  9. package/build/cjs/exports.js +5 -0
  10. package/build/cjs/index.js +5 -0
  11. package/build/cjs/packageInfo.js +4 -0
  12. package/build/cjs/types/augmentRegistry.js +3 -0
  13. package/build/cjs/types/index.js +6 -0
  14. package/build/cjs/types/lookup.js +2 -0
  15. package/build/cjs/types/types.js +29 -0
  16. package/build/cjs/util/encodeTypes.js +128 -0
  17. package/build/cjs/util/getTypeDef.js +195 -0
  18. package/build/cjs/util/index.js +7 -0
  19. package/build/cjs/util/typeSplit.js +60 -0
  20. package/build/cjs/util/xcm.js +9 -0
  21. package/build/create/class.d.ts +5 -0
  22. package/build/create/class.js +160 -0
  23. package/build/create/index.d.ts +2 -0
  24. package/build/create/index.js +2 -0
  25. package/build/create/type.d.ts +3 -0
  26. package/build/create/type.js +63 -0
  27. package/build/exports.d.ts +2 -0
  28. package/build/exports.js +2 -0
  29. package/build/index.d.ts +2 -0
  30. package/build/index.js +2 -0
  31. package/build/package.json +291 -0
  32. package/build/packageDetect.d.ts +1 -0
  33. package/build/packageDetect.js +4 -0
  34. package/build/packageInfo.d.ts +6 -0
  35. package/build/packageInfo.js +1 -0
  36. package/build/types/augmentRegistry.d.ts +11 -0
  37. package/build/types/augmentRegistry.js +1 -0
  38. package/build/types/index.d.ts +4 -0
  39. package/build/types/index.js +3 -0
  40. package/build/types/lookup.d.ts +14 -0
  41. package/build/types/lookup.js +1 -0
  42. package/build/types/types.d.ts +43 -0
  43. package/build/types/types.js +26 -0
  44. package/build/util/encodeTypes.d.ts +11 -0
  45. package/build/util/encodeTypes.js +123 -0
  46. package/build/util/getTypeDef.d.ts +8 -0
  47. package/build/util/getTypeDef.js +192 -0
  48. package/build/util/index.d.ts +4 -0
  49. package/build/util/index.js +4 -0
  50. package/build/util/typeSplit.d.ts +1 -0
  51. package/build/util/typeSplit.js +57 -0
  52. package/build/util/xcm.d.ts +2 -0
  53. package/build/util/xcm.js +5 -0
  54. package/build-deno/README.md +3 -0
  55. package/build-deno/bundle.ts +5 -0
  56. package/build-deno/create/class.ts +252 -0
  57. package/build-deno/create/index.ts +3 -0
  58. package/build-deno/create/type.ts +85 -0
  59. package/build-deno/exports.ts +3 -0
  60. package/build-deno/index.ts +4 -0
  61. package/build-deno/mod.ts +2 -0
  62. package/build-deno/packageDetect.ts +8 -0
  63. package/build-deno/packageInfo.ts +3 -0
  64. package/build-deno/types/augmentRegistry.ts +15 -0
  65. package/build-deno/types/index.ts +7 -0
  66. package/build-deno/types/lookup.ts +16 -0
  67. package/build-deno/types/types.ts +45 -0
  68. package/build-deno/util/encodeTypes.ts +201 -0
  69. package/build-deno/util/getTypeDef.ts +267 -0
  70. package/build-deno/util/index.ts +5 -0
  71. package/build-deno/util/typeSplit.ts +53 -0
  72. package/build-deno/util/xcm.ts +10 -0
  73. package/build-tsc-cjs/packageDetect.js +6 -0
  74. package/{cjs → build-tsc-cjs}/packageInfo.js +1 -1
  75. package/{packageInfo.js → build-tsc-esm/packageInfo.js} +1 -1
  76. package/package.json +11 -11
  77. package/src/bundle.ts +9 -0
  78. package/src/create/class.ts +257 -0
  79. package/src/create/index.ts +5 -0
  80. package/src/create/type.ts +94 -0
  81. package/src/exports.ts +6 -0
  82. package/src/index.ts +6 -0
  83. package/src/mod.ts +4 -0
  84. package/src/packageDetect.ts +12 -0
  85. package/src/packageInfo.ts +6 -0
  86. package/src/types/augmentRegistry.ts +19 -0
  87. package/src/types/index.ts +11 -0
  88. package/src/types/lookup.ts +21 -0
  89. package/src/types/types.ts +47 -0
  90. package/src/util/encodeTypes.spec.ts +217 -0
  91. package/src/util/encodeTypes.ts +205 -0
  92. package/src/util/getTypeDef.spec.ts +704 -0
  93. package/src/util/getTypeDef.ts +279 -0
  94. package/src/util/index.ts +7 -0
  95. package/src/util/typeSplit.spec.ts +50 -0
  96. package/src/util/typeSplit.ts +56 -0
  97. package/src/util/xcm.ts +12 -0
  98. package/tsconfig.build.json +15 -0
  99. package/tsconfig.build.tsbuildinfo +1 -0
  100. package/tsconfig.spec.json +17 -0
  101. package/tsconfig.spec.tsbuildinfo +1 -0
  102. /package/{cjs → build}/bundle.d.ts +0 -0
  103. /package/{create → build/cjs/create}/class.d.ts +0 -0
  104. /package/{create → build/cjs/create}/index.d.ts +0 -0
  105. /package/{create → build/cjs/create}/type.d.ts +0 -0
  106. /package/{exports.d.ts → build/cjs/exports.d.ts} +0 -0
  107. /package/{index.d.ts → build/cjs/index.d.ts} +0 -0
  108. /package/{cjs → build/cjs}/package.json +0 -0
  109. /package/{packageDetect.d.ts → build/cjs/packageDetect.d.ts} +0 -0
  110. /package/{cjs → build/cjs}/packageDetect.js +0 -0
  111. /package/{packageInfo.d.ts → build/cjs/packageInfo.d.ts} +0 -0
  112. /package/{types → build/cjs/types}/augmentRegistry.d.ts +0 -0
  113. /package/{types → build/cjs/types}/index.d.ts +0 -0
  114. /package/{types → build/cjs/types}/lookup.d.ts +0 -0
  115. /package/{types → build/cjs/types}/types.d.ts +0 -0
  116. /package/{util → build/cjs/util}/encodeTypes.d.ts +0 -0
  117. /package/{util → build/cjs/util}/getTypeDef.d.ts +0 -0
  118. /package/{util → build/cjs/util}/index.d.ts +0 -0
  119. /package/{util → build/cjs/util}/typeSplit.d.ts +0 -0
  120. /package/{util → build/cjs/util}/xcm.d.ts +0 -0
  121. /package/{bundle.d.ts → build-tsc/bundle.d.ts} +0 -0
  122. /package/{cjs → build-tsc}/create/class.d.ts +0 -0
  123. /package/{cjs → build-tsc}/create/index.d.ts +0 -0
  124. /package/{cjs → build-tsc}/create/type.d.ts +0 -0
  125. /package/{cjs → build-tsc}/exports.d.ts +0 -0
  126. /package/{cjs → build-tsc}/index.d.ts +0 -0
  127. /package/{cjs → build-tsc}/packageDetect.d.ts +0 -0
  128. /package/{cjs → build-tsc}/packageInfo.d.ts +0 -0
  129. /package/{cjs → build-tsc}/types/augmentRegistry.d.ts +0 -0
  130. /package/{cjs → build-tsc}/types/index.d.ts +0 -0
  131. /package/{cjs → build-tsc}/types/lookup.d.ts +0 -0
  132. /package/{cjs → build-tsc}/types/types.d.ts +0 -0
  133. /package/{cjs → build-tsc}/util/encodeTypes.d.ts +0 -0
  134. /package/{cjs → build-tsc}/util/getTypeDef.d.ts +0 -0
  135. /package/{cjs → build-tsc}/util/index.d.ts +0 -0
  136. /package/{cjs → build-tsc}/util/typeSplit.d.ts +0 -0
  137. /package/{cjs → build-tsc}/util/xcm.d.ts +0 -0
  138. /package/{cjs → build-tsc-cjs}/bundle.js +0 -0
  139. /package/{cjs → build-tsc-cjs}/create/class.js +0 -0
  140. /package/{cjs → build-tsc-cjs}/create/index.js +0 -0
  141. /package/{cjs → build-tsc-cjs}/create/type.js +0 -0
  142. /package/{cjs → build-tsc-cjs}/exports.js +0 -0
  143. /package/{cjs → build-tsc-cjs}/index.js +0 -0
  144. /package/{cjs → build-tsc-cjs}/types/augmentRegistry.js +0 -0
  145. /package/{cjs → build-tsc-cjs}/types/index.js +0 -0
  146. /package/{cjs → build-tsc-cjs}/types/lookup.js +0 -0
  147. /package/{cjs → build-tsc-cjs}/types/types.js +0 -0
  148. /package/{cjs → build-tsc-cjs}/util/encodeTypes.js +0 -0
  149. /package/{cjs → build-tsc-cjs}/util/getTypeDef.js +0 -0
  150. /package/{cjs → build-tsc-cjs}/util/index.js +0 -0
  151. /package/{cjs → build-tsc-cjs}/util/typeSplit.js +0 -0
  152. /package/{cjs → build-tsc-cjs}/util/xcm.js +0 -0
  153. /package/{bundle.js → build-tsc-esm/bundle.js} +0 -0
  154. /package/{create → build-tsc-esm/create}/class.js +0 -0
  155. /package/{create → build-tsc-esm/create}/index.js +0 -0
  156. /package/{create → build-tsc-esm/create}/type.js +0 -0
  157. /package/{exports.js → build-tsc-esm/exports.js} +0 -0
  158. /package/{index.js → build-tsc-esm/index.js} +0 -0
  159. /package/{packageDetect.js → build-tsc-esm/packageDetect.js} +0 -0
  160. /package/{types → build-tsc-esm/types}/augmentRegistry.js +0 -0
  161. /package/{types → build-tsc-esm/types}/index.js +0 -0
  162. /package/{types → build-tsc-esm/types}/lookup.js +0 -0
  163. /package/{types → build-tsc-esm/types}/types.js +0 -0
  164. /package/{util → build-tsc-esm/util}/encodeTypes.js +0 -0
  165. /package/{util → build-tsc-esm/util}/getTypeDef.js +0 -0
  166. /package/{util → build-tsc-esm/util}/index.js +0 -0
  167. /package/{util → build-tsc-esm/util}/typeSplit.js +0 -0
  168. /package/{util → build-tsc-esm/util}/xcm.js +0 -0
@@ -0,0 +1,192 @@
1
+ import { sanitize } from '@pezkuwi/types-codec';
2
+ import { isNumber, isString, objectSpread, stringify } from '@pezkuwi/util';
3
+ import { TypeDefInfo } from '../types/index.js';
4
+ import { typeSplit } from './typeSplit.js';
5
+ const KNOWN_INTERNALS = ['_alias', '_fallback'];
6
+ function getTypeString(typeOrObj) {
7
+ return isString(typeOrObj)
8
+ ? typeOrObj.toString()
9
+ : stringify(typeOrObj);
10
+ }
11
+ function isRustEnum(details) {
12
+ const values = Object.values(details);
13
+ if (values.some((v) => isNumber(v))) {
14
+ if (!values.every((v) => isNumber(v) && v >= 0 && v <= 255)) {
15
+ throw new Error('Invalid number-indexed enum definition');
16
+ }
17
+ return false;
18
+ }
19
+ return true;
20
+ }
21
+ function _decodeEnum(value, details, count, fallbackType) {
22
+ value.info = TypeDefInfo.Enum;
23
+ value.fallbackType = fallbackType;
24
+ // not as pretty, but remain compatible with oo7 for both struct and Array types
25
+ if (Array.isArray(details)) {
26
+ value.sub = details.map((name, index) => ({
27
+ index,
28
+ info: TypeDefInfo.Plain,
29
+ name,
30
+ type: 'Null'
31
+ }));
32
+ }
33
+ else if (isRustEnum(details)) {
34
+ value.sub = Object.entries(details).map(([name, typeOrObj], index) => objectSpread({}, getTypeDef(getTypeString(typeOrObj || 'Null'), { name }, count), { index }));
35
+ }
36
+ else {
37
+ value.sub = Object.entries(details).map(([name, index]) => ({
38
+ index,
39
+ info: TypeDefInfo.Plain,
40
+ name,
41
+ type: 'Null'
42
+ }));
43
+ }
44
+ return value;
45
+ }
46
+ function _decodeSet(value, details, fallbackType) {
47
+ value.info = TypeDefInfo.Set;
48
+ value.fallbackType = fallbackType;
49
+ value.length = details._bitLength;
50
+ value.sub = Object
51
+ .entries(details)
52
+ .filter(([name]) => !name.startsWith('_'))
53
+ .map(([name, index]) => ({
54
+ index,
55
+ info: TypeDefInfo.Plain,
56
+ name,
57
+ type: 'Null'
58
+ }));
59
+ return value;
60
+ }
61
+ function _decodeStruct(value, type, _, count) {
62
+ const parsed = JSON.parse(type);
63
+ const keys = Object.keys(parsed);
64
+ if (parsed._enum) {
65
+ return _decodeEnum(value, parsed._enum, count, parsed._fallback);
66
+ }
67
+ else if (parsed._set) {
68
+ return _decodeSet(value, parsed._set, parsed._fallback);
69
+ }
70
+ value.alias = parsed._alias
71
+ ? new Map(Object.entries(parsed._alias))
72
+ : undefined;
73
+ value.fallbackType = parsed._fallback;
74
+ value.sub = keys
75
+ .filter((name) => !KNOWN_INTERNALS.includes(name))
76
+ .map((name) => getTypeDef(getTypeString(parsed[name]), { name }, count));
77
+ return value;
78
+ }
79
+ function _decodeFixedVec(value, type, _, count) {
80
+ const max = type.length - 1;
81
+ let index = -1;
82
+ let inner = 0;
83
+ for (let i = 1; (i < max) && (index === -1); i++) {
84
+ switch (type[i]) {
85
+ case ';': {
86
+ if (inner === 0) {
87
+ index = i;
88
+ }
89
+ break;
90
+ }
91
+ case '[':
92
+ case '(':
93
+ case '<':
94
+ inner++;
95
+ break;
96
+ case ']':
97
+ case ')':
98
+ case '>':
99
+ inner--;
100
+ break;
101
+ }
102
+ }
103
+ if (index === -1) {
104
+ throw new Error(`${type}: Unable to extract location of ';'`);
105
+ }
106
+ const vecType = type.substring(1, index);
107
+ const [strLength, displayName] = type.substring(index + 1, max).split(';');
108
+ const length = parseInt(strLength.trim(), 10);
109
+ if (length > 2048) {
110
+ throw new Error(`${type}: Only support for [Type; <length>], where length <= 2048`);
111
+ }
112
+ value.displayName = displayName;
113
+ value.length = length;
114
+ value.sub = getTypeDef(vecType, {}, count);
115
+ return value;
116
+ }
117
+ function _decodeTuple(value, _, subType, count) {
118
+ value.sub = subType.length === 0
119
+ ? []
120
+ : typeSplit(subType).map((inner) => getTypeDef(inner, {}, count));
121
+ return value;
122
+ }
123
+ function _decodeAnyInt(value, type, _, clazz) {
124
+ const [strLength, displayName] = type.substring(clazz.length + 1, type.length - 1).split(',');
125
+ const length = parseInt(strLength.trim(), 10);
126
+ if ((length > 8192) || (length % 8)) {
127
+ throw new Error(`${type}: Only support for ${clazz}<bitLength>, where length <= 8192 and a power of 8, found ${length}`);
128
+ }
129
+ value.displayName = displayName;
130
+ value.length = length;
131
+ return value;
132
+ }
133
+ function _decodeInt(value, type, subType) {
134
+ return _decodeAnyInt(value, type, subType, 'Int');
135
+ }
136
+ function _decodeUInt(value, type, subType) {
137
+ return _decodeAnyInt(value, type, subType, 'UInt');
138
+ }
139
+ function _decodeDoNotConstruct(value, type, _) {
140
+ const NAME_LENGTH = 'DoNotConstruct'.length;
141
+ value.displayName = type.substring(NAME_LENGTH + 1, type.length - 1);
142
+ return value;
143
+ }
144
+ function hasWrapper(type, [start, end]) {
145
+ return (type.startsWith(start)) && (type.slice(-1 * end.length) === end);
146
+ }
147
+ const nestedExtraction = [
148
+ ['[', ']', TypeDefInfo.VecFixed, _decodeFixedVec],
149
+ ['{', '}', TypeDefInfo.Struct, _decodeStruct],
150
+ ['(', ')', TypeDefInfo.Tuple, _decodeTuple],
151
+ // the inner for these are the same as tuple, multiple values
152
+ ['BTreeMap<', '>', TypeDefInfo.BTreeMap, _decodeTuple],
153
+ ['HashMap<', '>', TypeDefInfo.HashMap, _decodeTuple],
154
+ ['Int<', '>', TypeDefInfo.Int, _decodeInt],
155
+ ['Result<', '>', TypeDefInfo.Result, _decodeTuple],
156
+ ['UInt<', '>', TypeDefInfo.UInt, _decodeUInt],
157
+ ['DoNotConstruct<', '>', TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct]
158
+ ];
159
+ const wrappedExtraction = [
160
+ ['BTreeSet<', '>', TypeDefInfo.BTreeSet],
161
+ ['Compact<', '>', TypeDefInfo.Compact],
162
+ ['Linkage<', '>', TypeDefInfo.Linkage],
163
+ ['Opaque<', '>', TypeDefInfo.WrapperOpaque],
164
+ ['Option<', '>', TypeDefInfo.Option],
165
+ ['Range<', '>', TypeDefInfo.Range],
166
+ ['RangeInclusive<', '>', TypeDefInfo.RangeInclusive],
167
+ ['Vec<', '>', TypeDefInfo.Vec],
168
+ ['WrapperKeepOpaque<', '>', TypeDefInfo.WrapperKeepOpaque],
169
+ ['WrapperOpaque<', '>', TypeDefInfo.WrapperOpaque]
170
+ ];
171
+ function extractSubType(type, [start, end]) {
172
+ return type.substring(start.length, type.length - end.length);
173
+ }
174
+ export function getTypeDef(_type, { displayName, name } = {}, count = 0) {
175
+ // create the type via Type, allowing types to be sanitized
176
+ const type = sanitize(_type);
177
+ const value = { displayName, info: TypeDefInfo.Plain, name, type };
178
+ if (++count > 64) {
179
+ throw new Error('getTypeDef: Maximum nested limit reached');
180
+ }
181
+ const nested = nestedExtraction.find((nested) => hasWrapper(type, nested));
182
+ if (nested) {
183
+ value.info = nested[2];
184
+ return nested[3](value, type, extractSubType(type, nested), count);
185
+ }
186
+ const wrapped = wrappedExtraction.find((wrapped) => hasWrapper(type, wrapped));
187
+ if (wrapped) {
188
+ value.info = wrapped[2];
189
+ value.sub = getTypeDef(extractSubType(type, wrapped), {}, count);
190
+ }
191
+ return value;
192
+ }
@@ -0,0 +1,4 @@
1
+ export * from './encodeTypes.js';
2
+ export * from './getTypeDef.js';
3
+ export * from './typeSplit.js';
4
+ export * from './xcm.js';
@@ -0,0 +1,4 @@
1
+ export * from './encodeTypes.js';
2
+ export * from './getTypeDef.js';
3
+ export * from './typeSplit.js';
4
+ export * from './xcm.js';
@@ -0,0 +1 @@
1
+ export declare function typeSplit(type: string): string[];
@@ -0,0 +1,57 @@
1
+ export function typeSplit(type) {
2
+ const result = [];
3
+ // these are the depths of the various tokens: <, [, {, (
4
+ let c = 0;
5
+ let f = 0;
6
+ let s = 0;
7
+ let t = 0;
8
+ // current start position
9
+ let start = 0;
10
+ for (let i = 0, count = type.length; i < count; i++) {
11
+ switch (type[i]) {
12
+ // if we are not nested, add the type
13
+ case ',': {
14
+ if (!(c || f || s || t)) {
15
+ result.push(type.substring(start, i).trim());
16
+ start = i + 1;
17
+ }
18
+ break;
19
+ }
20
+ // adjust compact/vec (and friends) depth
21
+ case '<':
22
+ c++;
23
+ break;
24
+ case '>':
25
+ c--;
26
+ break;
27
+ // adjust fixed vec depths
28
+ case '[':
29
+ f++;
30
+ break;
31
+ case ']':
32
+ f--;
33
+ break;
34
+ // adjust struct depth
35
+ case '{':
36
+ s++;
37
+ break;
38
+ case '}':
39
+ s--;
40
+ break;
41
+ // adjust tuple depth
42
+ case '(':
43
+ t++;
44
+ break;
45
+ case ')':
46
+ t--;
47
+ break;
48
+ }
49
+ }
50
+ // ensure we have all the terminators taken care of
51
+ if (c || f || s || t) {
52
+ throw new Error(`Invalid definition (missing terminators) found in ${type}`);
53
+ }
54
+ // the final leg of the journey
55
+ result.push(type.substring(start, type.length).trim());
56
+ return result;
57
+ }
@@ -0,0 +1,2 @@
1
+ export declare const XCM_MAPPINGS: string[];
2
+ export declare function mapXcmTypes(version: 'V0' | 'V1' | 'V2' | 'V3' | 'V4' | 'V5'): Record<string, string>;
@@ -0,0 +1,5 @@
1
+ import { objectSpread } from '@pezkuwi/util';
2
+ export const XCM_MAPPINGS = ['AssetInstance', 'Fungibility', 'Junction', 'Junctions', 'MultiAsset', 'MultiAssetFilter', 'MultiLocation', 'Response', 'WildFungibility', 'WildMultiAsset', 'Xcm', 'XcmError'];
3
+ export function mapXcmTypes(version) {
4
+ return XCM_MAPPINGS.reduce((all, key) => objectSpread(all, { [key]: `${key}${version}` }), {});
5
+ }
@@ -0,0 +1,3 @@
1
+ # @pezkuwi/types-create
2
+
3
+ Base type-creation functionality.
@@ -0,0 +1,5 @@
1
+
2
+ export { packageInfo } from './packageInfo.ts';
3
+ export { TypeDefInfo } from './types/index.ts';
4
+
5
+ export * from './exports.ts';
@@ -0,0 +1,252 @@
1
+
2
+ import type { Codec, CodecClass, LookupString, Registry, U8aBitLength, UIntBitLength } from 'https://deno.land/x/pezkuwi/types-codec/types/index.ts';
3
+ import type { TypeDef } from '../types/index.ts';
4
+
5
+ import { BTreeMap, BTreeSet, Bytes, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Null, Option, Range, RangeInclusive, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed, WrapperKeepOpaque, WrapperOpaque } from 'https://deno.land/x/pezkuwi/types-codec/mod.ts';
6
+ import { isNumber, stringify } from 'https://deno.land/x/pezkuwi/util/mod.ts';
7
+
8
+ import { TypeDefInfo } from '../types/index.ts';
9
+ import { getTypeDef } from '../util/getTypeDef.ts';
10
+
11
+ function getTypeDefType ({ lookupName, type }: TypeDef): string {
12
+ return lookupName || type;
13
+ }
14
+
15
+ function getSubDefArray (value: TypeDef): TypeDef[] {
16
+ if (!Array.isArray(value.sub)) {
17
+ throw new Error(`Expected subtype as TypeDef[] in ${stringify(value)}`);
18
+ }
19
+
20
+ return value.sub;
21
+ }
22
+
23
+ function getSubDef (value: TypeDef): TypeDef {
24
+ if (!value.sub || Array.isArray(value.sub)) {
25
+ throw new Error(`Expected subtype as TypeDef in ${stringify(value)}`);
26
+ }
27
+
28
+ return value.sub;
29
+ }
30
+
31
+ function getSubType (value: TypeDef): string {
32
+ return getTypeDefType(getSubDef(value));
33
+ }
34
+
35
+ function getTypeClassMap (value: TypeDef): Record<string, string> {
36
+ const subs = getSubDefArray(value);
37
+ const map: Record<string, string> = {};
38
+
39
+ for (let i = 0, count = subs.length; i < count; i++) {
40
+ const sub = subs[i];
41
+
42
+ if (!sub.name) {
43
+ throw new Error(`No name found in definition ${stringify(sub)}`);
44
+ }
45
+
46
+ map[sub.name] = getTypeDefType(sub);
47
+ }
48
+
49
+ return map;
50
+ }
51
+
52
+ function getTypeClassArray (value: TypeDef): string[] {
53
+ return getSubDefArray(value).map(getTypeDefType);
54
+ }
55
+
56
+ function createInt (Clazz: typeof Int | typeof UInt, { displayName, length }: TypeDef): CodecClass<Codec> {
57
+ if (!isNumber(length)) {
58
+ throw new Error(`Expected bitLength information for ${displayName || Clazz.constructor.name}<bitLength>`);
59
+ }
60
+
61
+ return Clazz.with(length as UIntBitLength, displayName);
62
+ }
63
+
64
+ function createHashMap (Clazz: typeof BTreeMap | typeof HashMap, value: TypeDef): CodecClass<Codec> {
65
+ const [keyType, valueType] = getTypeClassArray(value);
66
+
67
+ return Clazz.with(keyType, valueType);
68
+ }
69
+
70
+ function createWithSub (Clazz: { with: (t: string) => CodecClass<Codec> }, value: TypeDef): CodecClass<Codec> {
71
+ return Clazz.with(getSubType(value));
72
+ }
73
+
74
+ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => CodecClass<Codec>> = {
75
+ [TypeDefInfo.BTreeMap]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
76
+ createHashMap(BTreeMap, value),
77
+
78
+ [TypeDefInfo.BTreeSet]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
79
+ createWithSub(BTreeSet, value),
80
+
81
+ [TypeDefInfo.Compact]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
82
+ createWithSub(Compact, value),
83
+
84
+ [TypeDefInfo.DoNotConstruct]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
85
+ DoNotConstruct.with(value.displayName || value.type),
86
+
87
+ [TypeDefInfo.Enum]: (_registry: Registry, value: TypeDef): CodecClass<Codec> => {
88
+ const subs = getSubDefArray(value);
89
+
90
+ return Enum.with(
91
+ subs.every(({ type }) => type === 'Null')
92
+ ? subs.reduce<Record<string, number>>((out, { index, name }, count) => {
93
+ if (!name) {
94
+ throw new Error('No name found in sub definition');
95
+ }
96
+
97
+ out[name] = index || count;
98
+
99
+ return out;
100
+ }, {})
101
+ : getTypeClassMap(value)
102
+ );
103
+ },
104
+
105
+ [TypeDefInfo.HashMap]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
106
+ createHashMap(HashMap, value),
107
+
108
+ [TypeDefInfo.Int]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
109
+ createInt(Int, value),
110
+
111
+ // We have circular deps between Linkage & Struct
112
+ [TypeDefInfo.Linkage]: (_registry: Registry, value: TypeDef): CodecClass<Codec> => {
113
+ const type = `Option<${getSubType(value)}>`;
114
+ // eslint-disable-next-line sort-keys
115
+ const Clazz = Struct.with({ previous: type, next: type } as any);
116
+
117
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
118
+ Clazz.prototype.toRawType = function (): string {
119
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call
120
+ return `Linkage<${this.next.toRawType(true)}>`;
121
+ };
122
+
123
+ return Clazz;
124
+ },
125
+
126
+ [TypeDefInfo.Null]: (_registry: Registry, _value: TypeDef): CodecClass<Codec> =>
127
+ Null,
128
+
129
+ [TypeDefInfo.Option]: (_registry: Registry, value: TypeDef): CodecClass<Codec> => {
130
+ if (!value.sub || Array.isArray(value.sub)) {
131
+ throw new Error('Expected type information for Option');
132
+ }
133
+
134
+ // NOTE This is opt-in (unhandled), not by default
135
+ // if (value.sub.type === 'bool') {
136
+ // return OptionBool;
137
+ // }
138
+
139
+ return createWithSub(Option, value);
140
+ },
141
+
142
+ [TypeDefInfo.Plain]: (registry: Registry, value: TypeDef): CodecClass<Codec> =>
143
+ registry.getOrUnknown(value.type),
144
+
145
+ [TypeDefInfo.Range]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
146
+ createWithSub(Range, value),
147
+
148
+ [TypeDefInfo.RangeInclusive]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
149
+ createWithSub(RangeInclusive, value),
150
+
151
+ [TypeDefInfo.Result]: (_registry: Registry, value: TypeDef): CodecClass<Codec> => {
152
+ const [Ok, Err] = getTypeClassArray(value);
153
+
154
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
155
+ return Result.with({ Err, Ok });
156
+ },
157
+
158
+ [TypeDefInfo.Set]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
159
+ CodecSet.with(
160
+ getSubDefArray(value).reduce<Record<string, number>>((result, { index, name }) => {
161
+ if (!name || !isNumber(index)) {
162
+ throw new Error('No name found in sub definition');
163
+ }
164
+
165
+ result[name] = index;
166
+
167
+ return result;
168
+ }, {}),
169
+ value.length
170
+ ),
171
+
172
+ [TypeDefInfo.Si]: (registry: Registry, value: TypeDef): CodecClass<Codec> =>
173
+ getTypeClass(registry, registry.lookup.getTypeDef(value.type as LookupString)),
174
+
175
+ [TypeDefInfo.Struct]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
176
+ Struct.with(getTypeClassMap(value), value.alias),
177
+
178
+ [TypeDefInfo.Tuple]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
179
+ Tuple.with(getTypeClassArray(value)),
180
+
181
+ [TypeDefInfo.UInt]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
182
+ createInt(UInt, value),
183
+
184
+ [TypeDefInfo.Vec]: (_registry: Registry, { sub }: TypeDef): CodecClass<Codec> => {
185
+ if (!sub || Array.isArray(sub)) {
186
+ throw new Error('Expected type information for vector');
187
+ }
188
+
189
+ return (
190
+ sub.type === 'u8'
191
+ ? Bytes
192
+ : Vec.with(getTypeDefType(sub))
193
+ );
194
+ },
195
+
196
+ [TypeDefInfo.VecFixed]: (_registry: Registry, { displayName, length, sub }: TypeDef): CodecClass<Codec> => {
197
+ if (!isNumber(length) || !sub || Array.isArray(sub)) {
198
+ throw new Error('Expected length & type information for fixed vector');
199
+ }
200
+
201
+ return (
202
+ sub.type === 'u8'
203
+ ? U8aFixed.with((length * 8) as U8aBitLength, displayName)
204
+ : VecFixed.with(getTypeDefType(sub), length)
205
+ );
206
+ },
207
+
208
+ [TypeDefInfo.WrapperKeepOpaque]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
209
+ createWithSub(WrapperKeepOpaque, value),
210
+
211
+ [TypeDefInfo.WrapperOpaque]: (_registry: Registry, value: TypeDef): CodecClass<Codec> =>
212
+ createWithSub(WrapperOpaque, value)
213
+ };
214
+
215
+ export function constructTypeClass<T extends Codec = Codec> (registry: Registry, typeDef: TypeDef): CodecClass<T> {
216
+ try {
217
+ const Type = infoMapping[typeDef.info](registry, typeDef);
218
+
219
+ if (!Type) {
220
+ throw new Error('No class created');
221
+ }
222
+
223
+ // don't clobber any existing
224
+ if (!Type.__fallbackType && typeDef.fallbackType) {
225
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
226
+ // @ts-ignore ...this is the only place we we actually assign this...
227
+ Type.__fallbackType = typeDef.fallbackType;
228
+ }
229
+
230
+ return Type as CodecClass<T>;
231
+ } catch (error) {
232
+ throw new Error(`Unable to construct class from ${stringify(typeDef)}: ${(error as Error).message}`);
233
+ }
234
+ }
235
+
236
+ export function getTypeClass<T extends Codec = Codec> (registry: Registry, typeDef: TypeDef): CodecClass<T> {
237
+ return registry.getUnsafe(typeDef.type, false, typeDef) as unknown as CodecClass<T>;
238
+ }
239
+
240
+ export function createClassUnsafe<T extends Codec = Codec, K extends string = string> (registry: Registry, type: K): CodecClass<T> {
241
+ return (
242
+ // just retrieve via name, no creation via typeDef
243
+ registry.getUnsafe(type) ||
244
+ // we don't have an existing type, create the class via typeDef
245
+ getTypeClass(
246
+ registry,
247
+ registry.isLookupType(type)
248
+ ? registry.lookup.getTypeDef(type)
249
+ : getTypeDef(type)
250
+ )
251
+ );
252
+ }
@@ -0,0 +1,3 @@
1
+
2
+ export * from './class.ts';
3
+ export * from './type.ts';
@@ -0,0 +1,85 @@
1
+
2
+ import type { Bytes } from 'https://deno.land/x/pezkuwi/types-codec/mod.ts';
3
+ import type { Codec, CodecClass, IU8a, Registry } from 'https://deno.land/x/pezkuwi/types-codec/types/index.ts';
4
+ import type { CreateOptions } from '../types/index.ts';
5
+
6
+ import { Option } from 'https://deno.land/x/pezkuwi/types-codec/mod.ts';
7
+ import { isHex, isU8a, u8aEq, u8aToHex, u8aToU8a } from 'https://deno.land/x/pezkuwi/util/mod.ts';
8
+
9
+ import { createClassUnsafe } from './class.ts';
10
+
11
+ function checkInstance (created: Codec, matcher: Uint8Array): void {
12
+ const u8a = created.toU8a();
13
+ const rawType = created.toRawType();
14
+ const isOk = (
15
+ // full match, all ok
16
+ u8aEq(u8a, matcher) ||
17
+ (
18
+ // on a length-prefixed type, just check the actual length
19
+ ['Bytes', 'Text', 'Type'].includes(rawType) &&
20
+ matcher.length === (created as unknown as Bytes).length
21
+ ) ||
22
+ (
23
+ // when the created is empty and matcher is also empty, let it slide...
24
+ created.isEmpty &&
25
+ matcher.every((v) => !v)
26
+ )
27
+ );
28
+
29
+ if (!isOk) {
30
+ throw new Error(`${rawType}:: Decoded input doesn't match input, received ${u8aToHex(matcher, 512)} (${matcher.length} bytes), created ${u8aToHex(u8a, 512)} (${u8a.length} bytes)`);
31
+ }
32
+ }
33
+
34
+ function checkPedantic (created: Codec, [value]: unknown[]): void {
35
+ if (isU8a(value)) {
36
+ checkInstance(created, value);
37
+ } else if (isHex(value)) {
38
+ checkInstance(created, u8aToU8a(value));
39
+ }
40
+ }
41
+
42
+ function initType<T extends Codec> (registry: Registry, Type: CodecClass, params: unknown[] = [], { blockHash, isFallback, isOptional, isPedantic }: CreateOptions = {}): T {
43
+ const created = new (
44
+ isOptional
45
+ ? Option.with(Type)
46
+ : Type
47
+ )(registry, ...params);
48
+
49
+ isPedantic && checkPedantic(created, params);
50
+
51
+ if (blockHash) {
52
+ created.createdAtHash = createTypeUnsafe<IU8a>(registry, 'BlockHash', [blockHash]);
53
+ }
54
+
55
+ if (isFallback) {
56
+ created.isStorageFallback = true;
57
+ }
58
+
59
+ return created as T;
60
+ }
61
+
62
+ export function createTypeUnsafe<T extends Codec = Codec, K extends string = string> (registry: Registry, type: K, params: unknown[] = [], options: CreateOptions = {}): T {
63
+ let Clazz: CodecClass | null = null;
64
+ let firstError: Error | null = null;
65
+
66
+ try {
67
+ Clazz = createClassUnsafe(registry, type);
68
+
69
+ return initType(registry, Clazz, params, options);
70
+ } catch (error) {
71
+ firstError = new Error(`createType(${type}):: ${(error as Error).message}`);
72
+ }
73
+
74
+ if (Clazz?.__fallbackType) {
75
+ try {
76
+ Clazz = createClassUnsafe(registry, Clazz.__fallbackType as unknown as K);
77
+
78
+ return initType(registry, Clazz, params, options);
79
+ } catch {
80
+ // swallow, we will throw the first error again
81
+ }
82
+ }
83
+
84
+ throw firstError;
85
+ }
@@ -0,0 +1,3 @@
1
+
2
+ export * from './create/index.ts';
3
+ export * from './util/index.ts';
@@ -0,0 +1,4 @@
1
+
2
+ import './packageDetect.ts';
3
+
4
+ export * from './bundle.ts';
@@ -0,0 +1,2 @@
1
+
2
+ export * from './index.ts';
@@ -0,0 +1,8 @@
1
+
2
+
3
+ import { packageInfo as codecInfo } from 'https://deno.land/x/pezkuwi/types-codec/packageInfo.ts';
4
+ import { detectPackage } from 'https://deno.land/x/pezkuwi/util/mod.ts';
5
+
6
+ import { packageInfo } from './packageInfo.ts';
7
+
8
+ detectPackage(packageInfo, null, [codecInfo]);
@@ -0,0 +1,3 @@
1
+
2
+
3
+ export const packageInfo = { name: '@pezkuwi/types-create', path: new URL(import.meta.url).pathname, type: 'deno', version: '16.5.18' };
@@ -0,0 +1,15 @@
1
+
2
+ import 'https://deno.land/x/pezkuwi/types-codec/types/registry.ts';
3
+
4
+ import type { Codec, CodecClass, ICompact, INumber, LookupString } from 'https://deno.land/x/pezkuwi/types-codec/types/index.ts';
5
+ import type { ILookup, TypeDef } from 'https://deno.land/x/pezkuwi/types-create/types/index.ts';
6
+
7
+ declare module 'https://deno.land/x/pezkuwi/types-codec/types/registry.ts' {
8
+ interface Registry {
9
+ readonly lookup: ILookup;
10
+
11
+ createLookupType (lookupId: ICompact<INumber> | number): LookupString;
12
+ getUnsafe <T extends Codec = Codec, K extends string = string> (name: K, withUnknown?: boolean, knownTypeDef?: TypeDef): CodecClass<T> | undefined;
13
+ setLookup (lookup: ILookup): void;
14
+ }
15
+ }
@@ -0,0 +1,7 @@
1
+
2
+ import './augmentRegistry.ts';
3
+
4
+ export type { CodecCreateOptions as CreateOptions } from 'https://deno.land/x/pezkuwi/types-codec/types/index.ts';
5
+
6
+ export * from './lookup.ts';
7
+ export * from './types.ts';