wasm-ast-types 0.4.3 → 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -1 +1,130 @@
1
1
  # wasm-ast-types
2
+
3
+ ## working with ASTs
4
+
5
+ ### 1 edit the fixture
6
+
7
+ edit `./scripts/fixture.ts`, for example:
8
+
9
+ ```js
10
+ // ./scripts/fixture.ts
11
+ export interface InstantiateMsg {
12
+ admin?: string | null;
13
+ members: Member[];
14
+ }
15
+ ```
16
+
17
+ ### 2 run AST generator
18
+
19
+ ```
20
+ yarn test:ast
21
+ ```
22
+
23
+ ### 3 look at the JSON produced
24
+
25
+ ```
26
+ code ./scripts/test-output.json
27
+ ```
28
+
29
+ We use the npm module `ast-stringify` to strip out unneccesary props, and generate a JSON for reference.
30
+
31
+ You will see a `File` and `Program`... only concern yourself with the `body[]`:
32
+
33
+ ```json
34
+ {
35
+ "type": "File",
36
+ "errors": [],
37
+ "program": {
38
+ "type": "Program",
39
+ "sourceType": "module",
40
+ "interpreter": null,
41
+ "body": [
42
+ {
43
+ "type": "ExportNamedDeclaration",
44
+ "exportKind": "type",
45
+ "specifiers": [],
46
+ "source": null,
47
+ "declaration": {
48
+ "type": "TSInterfaceDeclaration",
49
+ "id": {
50
+ "type": "Identifier",
51
+ "name": "InstantiateMsg"
52
+ },
53
+ "body": {
54
+ "type": "TSInterfaceBody",
55
+ "body": [
56
+ {
57
+ "type": "TSPropertySignature",
58
+ "key": {
59
+ "type": "Identifier",
60
+ "name": "admin"
61
+ },
62
+ "computed": false,
63
+ "optional": true,
64
+ "typeAnnotation": {
65
+ "type": "TSTypeAnnotation",
66
+ "typeAnnotation": {
67
+ "type": "TSUnionType",
68
+ "types": [
69
+ {
70
+ "type": "TSStringKeyword"
71
+ },
72
+ {
73
+ "type": "TSNullKeyword"
74
+ }
75
+ ]
76
+ }
77
+ }
78
+ },
79
+ {
80
+ "type": "TSPropertySignature",
81
+ "key": {
82
+ "type": "Identifier",
83
+ "name": "members"
84
+ },
85
+ "computed": false,
86
+ "typeAnnotation": {
87
+ "type": "TSTypeAnnotation",
88
+ "typeAnnotation": {
89
+ "type": "TSArrayType",
90
+ "elementType": {
91
+ "type": "TSTypeReference",
92
+ "typeName": {
93
+ "type": "Identifier",
94
+ "name": "Member"
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
100
+ ]
101
+ }
102
+ }
103
+ }
104
+ ],
105
+ "directives": []
106
+ },
107
+ "comments": []
108
+ }
109
+ ```
110
+
111
+ ### 4 code with `@babel/types` using the JSON as a reference
112
+
113
+ NOTE: 4 continued ideally you should be writing a test with your generator!
114
+
115
+ ```js
116
+ import * as t from '@babel/types';
117
+
118
+ export const createNewGenerator = () => {
119
+ return t.exportNamedDeclaration(
120
+ t.tsInterfaceDeclaration(
121
+ t.identifier('InstantiateMsg'),
122
+ null,
123
+ [],
124
+ t.tsInterfaceBody([
125
+ // ... more code ...
126
+ ])
127
+ )
128
+ );
129
+ };
130
+ ```
@@ -7,7 +7,7 @@ var _typeof = require("@babel/runtime/helpers/typeof");
7
7
  Object.defineProperty(exports, "__esModule", {
8
8
  value: true
9
9
  });
10
- exports.createReactQueryHooks = exports.createReactQueryHookInterface = exports.createReactQueryHook = void 0;
10
+ exports.createReactQueryMutationHooks = exports.createReactQueryMutationHook = exports.createReactQueryMutationArgsInterface = exports.createReactQueryHooks = exports.createReactQueryHookInterface = exports.createReactQueryHook = void 0;
11
11
 
12
12
  var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
13
13
 
@@ -23,6 +23,8 @@ var _babel = require("./utils/babel");
23
23
 
24
24
  var _types2 = require("./utils/types");
25
25
 
26
+ var _wasm = require("./wasm");
27
+
26
28
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
27
29
 
28
30
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
@@ -33,7 +35,8 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
33
35
 
34
36
  var DEFAULT_OPTIONS = {
35
37
  optionalClient: false,
36
- v4: false
38
+ v4: false,
39
+ mutations: false
37
40
  };
38
41
 
39
42
  var createReactQueryHooks = function createReactQueryHooks(_ref) {
@@ -108,17 +111,151 @@ var createReactQueryHook = function createReactQueryHook(_ref2) {
108
111
 
109
112
  exports.createReactQueryHook = createReactQueryHook;
110
113
 
111
- var createReactQueryHookInterface = function createReactQueryHookInterface(_ref3) {
112
- var QueryClient = _ref3.QueryClient,
113
- hookParamsTypeName = _ref3.hookParamsTypeName,
114
- responseType = _ref3.responseType,
115
- jsonschema = _ref3.jsonschema,
116
- _ref3$options = _ref3.options,
117
- options = _ref3$options === void 0 ? {} : _ref3$options;
114
+ /**
115
+ * Example:
116
+ ```
117
+ export interface Cw4UpdateMembersMutation {
118
+ client: Cw4GroupClient
119
+ args: {
120
+ tokenId: string
121
+ remove: string[]
122
+ }
123
+ options?: Omit<
124
+ UseMutationOptions<ExecuteResult, Error, Pick<Cw4UpdateMembersMutation, 'args'>>,
125
+ 'mutationFn'
126
+ >
127
+ }
128
+ ```
129
+ */
130
+ var createReactQueryMutationArgsInterface = function createReactQueryMutationArgsInterface(_ref3) {
131
+ var _jsonschema$$ref;
132
+
133
+ var ExecuteClient = _ref3.ExecuteClient,
134
+ mutationHookParamsTypeName = _ref3.mutationHookParamsTypeName,
135
+ useMutationTypeParameter = _ref3.useMutationTypeParameter,
136
+ jsonschema = _ref3.jsonschema;
137
+ var typedUseMutationOptions = t.tsTypeReference(t.identifier('UseMutationOptions'), useMutationTypeParameter);
138
+ var body = [(0, _utils.tsPropertySignature)(t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(ExecuteClient))), false)];
139
+ var msgType = (0, _types2.getParamsTypeAnnotation)(jsonschema); // TODO: this should not have to be done manually.
140
+
141
+ if (!msgType && jsonschema !== null && jsonschema !== void 0 && (_jsonschema$$ref = jsonschema.$ref) !== null && _jsonschema$$ref !== void 0 && _jsonschema$$ref.startsWith('#/definitions/')) {
142
+ var refName = jsonschema === null || jsonschema === void 0 ? void 0 : jsonschema.$ref;
143
+
144
+ if (/_for_[A-Z]/.test(refName)) {
145
+ refName = refName.replace(/_for_/, 'For');
146
+ }
147
+
148
+ msgType = t.tsTypeAnnotation((0, _types2.getTypeFromRef)(refName));
149
+ }
150
+
151
+ if (msgType) {
152
+ body.push(t.tsPropertySignature(t.identifier('msg'), msgType));
153
+ } // fee: number | StdFee | "auto" = "auto", memo?: string, funds?: readonly Coin[]
154
+
155
+
156
+ var optionalArgs = t.tsPropertySignature(t.identifier('args'), t.tsTypeAnnotation(t.tsTypeLiteral(_wasm.FIXED_EXECUTE_PARAMS.map(function (param) {
157
+ return (0, _babel.propertySignature)(param.name, param.typeAnnotation, param.optional);
158
+ }))));
159
+ optionalArgs.optional = true;
160
+ body.push(optionalArgs);
161
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(mutationHookParamsTypeName), null, [], t.tsInterfaceBody(body)));
162
+ };
163
+
164
+ exports.createReactQueryMutationArgsInterface = createReactQueryMutationArgsInterface;
165
+
166
+ var createReactQueryMutationHooks = function createReactQueryMutationHooks(_ref4) {
167
+ var execMsg = _ref4.execMsg,
168
+ contractName = _ref4.contractName,
169
+ ExecuteClient = _ref4.ExecuteClient,
170
+ _ref4$options = _ref4.options,
171
+ options = _ref4$options === void 0 ? {} : _ref4$options;
172
+ // merge the user options with the defaults
173
+ return (0, _utils.getMessageProperties)(execMsg).reduce(function (m, schema) {
174
+ var _jsonschema$propertie2, _Object$keys;
175
+
176
+ // update_members
177
+ var execMethodUnderscoreName = Object.keys(schema.properties)[0]; // updateMembers
178
+
179
+ var execMethodName = (0, _case.camel)(execMethodUnderscoreName); // Cw20UpdateMembersMutation
180
+
181
+ var mutationHookParamsTypeName = "".concat((0, _case.pascal)(contractName)).concat((0, _case.pascal)(execMethodName), "Mutation"); // useCw20UpdateMembersMutation
182
+
183
+ var mutationHookName = "use".concat(mutationHookParamsTypeName);
184
+ var jsonschema = schema.properties[execMethodUnderscoreName];
185
+ var properties = (_jsonschema$propertie2 = jsonschema.properties) !== null && _jsonschema$propertie2 !== void 0 ? _jsonschema$propertie2 : {}; // TODO: there should be a better way to do this
186
+
187
+ var hasMsg = !!((_Object$keys = Object.keys(properties)) !== null && _Object$keys !== void 0 && _Object$keys.length || jsonschema !== null && jsonschema !== void 0 && jsonschema.$ref); // <ExecuteResult, Error, Cw4UpdateMembersMutation>
188
+
189
+ var useMutationTypeParameter = generateMutationTypeParameter(mutationHookParamsTypeName, hasMsg);
190
+ return [createReactQueryMutationArgsInterface({
191
+ mutationHookParamsTypeName: mutationHookParamsTypeName,
192
+ ExecuteClient: ExecuteClient,
193
+ jsonschema: jsonschema,
194
+ useMutationTypeParameter: useMutationTypeParameter
195
+ }), createReactQueryMutationHook({
196
+ execMethodName: execMethodName,
197
+ mutationHookName: mutationHookName,
198
+ mutationHookParamsTypeName: mutationHookParamsTypeName,
199
+ hasMsg: hasMsg,
200
+ useMutationTypeParameter: useMutationTypeParameter
201
+ })].concat((0, _toConsumableArray2["default"])(m));
202
+ }, []);
203
+ };
204
+ /**
205
+ * Generates the mutation type parameter. If args exist, we use a pick. If not, we just return the params type.
206
+ */
207
+
208
+
209
+ exports.createReactQueryMutationHooks = createReactQueryMutationHooks;
210
+
211
+ function generateMutationTypeParameter(mutationHookParamsTypeName, hasArgs) {
212
+ return t.tsTypeParameterInstantiation([// Data
213
+ t.tSTypeReference(t.identifier('ExecuteResult')), // Error
214
+ t.tsTypeReference(t.identifier('Error')), // Variables
215
+ t.tsTypeReference(t.identifier(mutationHookParamsTypeName))]);
216
+ }
217
+
218
+ /**
219
+ *
220
+ * Example:
221
+ ```
222
+ export const useCw4UpdateMembersMutation = ({ client, options }: Omit<Cw4UpdateMembersMutation, 'args'>) =>
223
+ useMutation<ExecuteResult, Error, Pick<Cw4UpdateMembersMutation, 'args'>>(
224
+ ({ args }) => client.updateMembers(args),
225
+ options
226
+ )
227
+ ```
228
+ */
229
+ var createReactQueryMutationHook = function createReactQueryMutationHook(_ref5) {
230
+ var mutationHookName = _ref5.mutationHookName,
231
+ mutationHookParamsTypeName = _ref5.mutationHookParamsTypeName,
232
+ execMethodName = _ref5.execMethodName,
233
+ useMutationTypeParameter = _ref5.useMutationTypeParameter,
234
+ hasMsg = _ref5.hasMsg;
235
+ var useMutationFunctionArgs = [(0, _babel.shorthandProperty)('client')];
236
+ if (hasMsg) useMutationFunctionArgs.push((0, _babel.shorthandProperty)('msg'));
237
+ useMutationFunctionArgs.push(t.objectProperty(t.identifier('args'), t.assignmentPattern(t.objectPattern(_wasm.FIXED_EXECUTE_PARAMS.map(function (param) {
238
+ return (0, _babel.shorthandProperty)(param.name);
239
+ })), t.objectExpression([]))));
240
+ return t.exportNamedDeclaration(t.functionDeclaration(t.identifier(mutationHookName), [(0, _utils.identifier)('options', t.tsTypeAnnotation((0, _babel.omitTypeReference)(t.tsTypeReference(t.identifier('UseMutationOptions'), useMutationTypeParameter), 'mutationFn')), true)], t.blockStatement([t.returnStatement((0, _utils.callExpression)(t.identifier('useMutation'), [t.arrowFunctionExpression([t.objectPattern(useMutationFunctionArgs)], t.callExpression(t.memberExpression(t.identifier('client'), t.identifier(execMethodName)), (hasMsg ? [t.identifier('msg')] : []).concat(_wasm.FIXED_EXECUTE_PARAMS.map(function (param) {
241
+ return t.identifier(param.name);
242
+ }))), false // not async
243
+ ), t.identifier('options')], useMutationTypeParameter))])));
244
+ };
245
+
246
+ exports.createReactQueryMutationHook = createReactQueryMutationHook;
247
+
248
+ var createReactQueryHookInterface = function createReactQueryHookInterface(_ref6) {
249
+ var QueryClient = _ref6.QueryClient,
250
+ hookParamsTypeName = _ref6.hookParamsTypeName,
251
+ responseType = _ref6.responseType,
252
+ jsonschema = _ref6.jsonschema,
253
+ _ref6$options = _ref6.options,
254
+ options = _ref6$options === void 0 ? {} : _ref6$options;
118
255
  // merge the user options with the defaults
119
256
  options = _objectSpread(_objectSpread({}, DEFAULT_OPTIONS), options);
120
257
  var typedUseQueryOptions = t.tsTypeReference(t.identifier('UseQueryOptions'), t.tsTypeParameterInstantiation([(0, _babel.typeRefOrOptionalUnion)(t.identifier(responseType), options.optionalClient), t.tsTypeReference(t.identifier('Error')), t.tsTypeReference(t.identifier(responseType)), t.tsArrayType(t.tsParenthesizedType(t.tsUnionType([t.tsStringKeyword(), t.tsUndefinedKeyword()])))]));
121
- var body = [(0, _utils.tsPropertySignature)(t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(QueryClient))), options.optionalClient), (0, _utils.tsPropertySignature)(t.identifier('options'), t.tsTypeAnnotation(options.v4 ? t.tSIntersectionType([t.tsTypeReference(t.identifier('Omit'), t.tsTypeParameterInstantiation([typedUseQueryOptions, t.tsLiteralType(t.stringLiteral("'queryKey' | 'queryFn' | 'initialData'"))])), t.tSTypeLiteral([t.tsPropertySignature(t.identifier('initialData?'), t.tsTypeAnnotation(t.tsUndefinedKeyword()))])]) : typedUseQueryOptions), true)];
258
+ var body = [(0, _utils.tsPropertySignature)(t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(QueryClient))), options.optionalClient), (0, _utils.tsPropertySignature)(t.identifier('options'), t.tsTypeAnnotation(options.v4 ? t.tSIntersectionType([(0, _babel.omitTypeReference)(typedUseQueryOptions, "'queryKey' | 'queryFn' | 'initialData'"), t.tSTypeLiteral([t.tsPropertySignature(t.identifier('initialData?'), t.tsTypeAnnotation(t.tsUndefinedKeyword()))])]) : typedUseQueryOptions), true)];
122
259
  var props = getProps(jsonschema, true);
123
260
 
124
261
  if (props.length) {
@@ -131,9 +268,9 @@ var createReactQueryHookInterface = function createReactQueryHookInterface(_ref3
131
268
  exports.createReactQueryHookInterface = createReactQueryHookInterface;
132
269
 
133
270
  var getProps = function getProps(jsonschema, camelize) {
134
- var _jsonschema$propertie2;
271
+ var _jsonschema$propertie3;
135
272
 
136
- var keys = Object.keys((_jsonschema$propertie2 = jsonschema.properties) !== null && _jsonschema$propertie2 !== void 0 ? _jsonschema$propertie2 : {});
273
+ var keys = Object.keys((_jsonschema$propertie3 = jsonschema.properties) !== null && _jsonschema$propertie3 !== void 0 ? _jsonschema$propertie3 : {});
137
274
  if (!keys.length) return [];
138
275
  return keys.map(function (prop) {
139
276
  var _getPropertyType = (0, _types2.getPropertyType)(jsonschema, prop),
@@ -10,6 +10,8 @@ var t = _interopRequireWildcard(require("@babel/types"));
10
10
 
11
11
  var _query_msg = _interopRequireDefault(require("./../../../__fixtures__/basic/query_msg.json"));
12
12
 
13
+ var _execute_msg_for__empty = _interopRequireDefault(require("./../../../__fixtures__/basic/execute_msg_for__empty.json"));
14
+
13
15
  var _reactQuery = require("./react-query");
14
16
 
15
17
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
@@ -69,4 +71,9 @@ it('createReactQueryHooks', function () {
69
71
  v4: true
70
72
  }
71
73
  })));
74
+ expectCode(t.program((0, _reactQuery.createReactQueryMutationHooks)({
75
+ execMsg: _execute_msg_for__empty["default"],
76
+ contractName: 'Sg721',
77
+ ExecuteClient: 'Sg721Client'
78
+ })));
72
79
  });
@@ -7,7 +7,7 @@ var _typeof = require("@babel/runtime/helpers/typeof");
7
7
  Object.defineProperty(exports, "__esModule", {
8
8
  value: true
9
9
  });
10
- exports.typedIdentifier = exports.typeRefOrOptionalUnion = exports.tsTypeOperator = exports.tsPropertySignature = exports.tsObjectPattern = exports.shorthandProperty = exports.recursiveNamespace = exports.propertySignature = exports.promiseTypeAnnotation = exports.optionalConditionalExpression = exports.memberExpressionOrIdentifierSnake = exports.memberExpressionOrIdentifier = exports.importStmt = exports.importAminoMsg = exports.identifier = exports.getMessageProperties = exports.getFieldDimensionality = exports.classProperty = exports.classDeclaration = exports.callExpression = exports.bindMethod = exports.arrowFunctionExpression = exports.arrayTypeNDimensions = exports.FieldTypeAsts = void 0;
10
+ exports.typedIdentifier = exports.typeRefOrOptionalUnion = exports.tsTypeOperator = exports.tsPropertySignature = exports.tsObjectPattern = exports.shorthandProperty = exports.recursiveNamespace = exports.propertySignature = exports.promiseTypeAnnotation = exports.pickTypeReference = exports.parameterizedTypeReference = exports.optionalConditionalExpression = exports.omitTypeReference = exports.memberExpressionOrIdentifierSnake = exports.memberExpressionOrIdentifier = exports.importStmt = exports.importAminoMsg = exports.identifier = exports.getMessageProperties = exports.getFieldDimensionality = exports.classProperty = exports.classDeclaration = exports.callExpression = exports.bindMethod = exports.arrowFunctionExpression = exports.arrayTypeNDimensions = exports.FieldTypeAsts = void 0;
11
11
 
12
12
  var _toArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toArray"));
13
13
 
@@ -21,6 +21,7 @@ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "functio
21
21
 
22
22
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
23
23
 
24
+ // t.TSPropertySignature - kind?
24
25
  var propertySignature = function propertySignature(name, typeAnnotation) {
25
26
  var optional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
26
27
  return {
@@ -279,4 +280,29 @@ var typeRefOrOptionalUnion = function typeRefOrOptionalUnion(identifier) {
279
280
  return optional ? t.tsUnionType([typeReference, t.tsUndefinedKeyword()]) : typeReference;
280
281
  };
281
282
 
282
- exports.typeRefOrOptionalUnion = typeRefOrOptionalUnion;
283
+ exports.typeRefOrOptionalUnion = typeRefOrOptionalUnion;
284
+
285
+ var parameterizedTypeReference = function parameterizedTypeReference(identifier, from, omit) {
286
+ return t.tsTypeReference(t.identifier(identifier), t.tsTypeParameterInstantiation([from, typeof omit === 'string' ? t.tsLiteralType(t.stringLiteral(omit)) : t.tsUnionType(omit.map(function (o) {
287
+ return t.tsLiteralType(t.stringLiteral(o));
288
+ }))]));
289
+ };
290
+ /**
291
+ * omitTypeReference(t.tsTypeReference(t.identifier('Cw4UpdateMembersMutation'),),'args').....
292
+ * Omit<Cw4UpdateMembersMutation, 'args'>
293
+ */
294
+
295
+
296
+ exports.parameterizedTypeReference = parameterizedTypeReference;
297
+
298
+ var omitTypeReference = function omitTypeReference(from, omit) {
299
+ return parameterizedTypeReference('Omit', from, omit);
300
+ };
301
+
302
+ exports.omitTypeReference = omitTypeReference;
303
+
304
+ var pickTypeReference = function pickTypeReference(from, pick) {
305
+ return parameterizedTypeReference('Pick', from, pick);
306
+ };
307
+
308
+ exports.pickTypeReference = pickTypeReference;
@@ -7,7 +7,9 @@ var _typeof = require("@babel/runtime/helpers/typeof");
7
7
  Object.defineProperty(exports, "__esModule", {
8
8
  value: true
9
9
  });
10
- exports.getType = exports.getPropertyType = exports.createTypedObjectParams = void 0;
10
+ exports.getParamsTypeAnnotation = exports.createTypedObjectParams = void 0;
11
+ exports.getPropertySignatureFromProp = getPropertySignatureFromProp;
12
+ exports.getTypeFromRef = exports.getType = exports.getPropertyType = void 0;
11
13
 
12
14
  var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
13
15
 
@@ -51,6 +53,8 @@ var getTypeFromRef = function getTypeFromRef($ref) {
51
53
  }
52
54
  };
53
55
 
56
+ exports.getTypeFromRef = getTypeFromRef;
57
+
54
58
  var getArrayTypeFromRef = function getArrayTypeFromRef($ref) {
55
59
  return t.tsArrayType(getTypeFromRef($ref));
56
60
  };
@@ -183,79 +187,95 @@ var getPropertyType = function getPropertyType(schema, prop) {
183
187
 
184
188
  exports.getPropertyType = getPropertyType;
185
189
 
186
- var createTypedObjectParams = function createTypedObjectParams(jsonschema) {
187
- var _jsonschema$propertie;
188
-
189
- var camelize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
190
- var keys = Object.keys((_jsonschema$propertie = jsonschema.properties) !== null && _jsonschema$propertie !== void 0 ? _jsonschema$propertie : {});
191
- if (!keys.length) return;
192
- var typedParams = keys.map(function (prop) {
193
- if (jsonschema.properties[prop].type === 'object') {
194
- if (jsonschema.properties[prop].title) {
195
- return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(jsonschema.properties[prop].title))));
196
- } else {
197
- throw new Error('createTypedObjectParams() contact maintainer');
198
- }
190
+ function getPropertySignatureFromProp(jsonschema, prop, camelize) {
191
+ if (jsonschema.properties[prop].type === 'object') {
192
+ if (jsonschema.properties[prop].title) {
193
+ return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(jsonschema.properties[prop].title))));
194
+ } else {
195
+ throw new Error('createTypedObjectParams() contact maintainer');
199
196
  }
197
+ }
200
198
 
201
- if (Array.isArray(jsonschema.properties[prop].allOf)) {
202
- var _jsonschema$required;
199
+ if (Array.isArray(jsonschema.properties[prop].allOf)) {
200
+ var _jsonschema$required;
203
201
 
204
- var isOptional = !((_jsonschema$required = jsonschema.required) !== null && _jsonschema$required !== void 0 && _jsonschema$required.includes(prop));
205
- var unionTypes = jsonschema.properties[prop].allOf.map(function (el) {
206
- if (el.title) return el.title;
207
- if (el.$ref) return getTypeStrFromRef(el.$ref);
208
- return el.type;
209
- });
210
- var uniqUnionTypes = (0, _toConsumableArray2["default"])(new Set(unionTypes));
202
+ var isOptional = !((_jsonschema$required = jsonschema.required) !== null && _jsonschema$required !== void 0 && _jsonschema$required.includes(prop));
203
+ var unionTypes = jsonschema.properties[prop].allOf.map(function (el) {
204
+ if (el.title) return el.title;
205
+ if (el.$ref) return getTypeStrFromRef(el.$ref);
206
+ return el.type;
207
+ });
208
+ var uniqUnionTypes = (0, _toConsumableArray2["default"])(new Set(unionTypes));
211
209
 
212
- if (uniqUnionTypes.length === 1) {
213
- return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(uniqUnionTypes[0]))), isOptional);
214
- } else {
215
- return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(uniqUnionTypes.map(function (typ) {
216
- return t.tsTypeReference(t.identifier(typ));
217
- }))), isOptional);
218
- }
219
- } else if (Array.isArray(jsonschema.properties[prop].oneOf)) {
220
- var _jsonschema$required2;
210
+ if (uniqUnionTypes.length === 1) {
211
+ return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(uniqUnionTypes[0]))), isOptional);
212
+ } else {
213
+ return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(uniqUnionTypes.map(function (typ) {
214
+ return t.tsTypeReference(t.identifier(typ));
215
+ }))), isOptional);
216
+ }
217
+ } else if (Array.isArray(jsonschema.properties[prop].oneOf)) {
218
+ var _jsonschema$required2;
221
219
 
222
- var _isOptional = !((_jsonschema$required2 = jsonschema.required) !== null && _jsonschema$required2 !== void 0 && _jsonschema$required2.includes(prop));
220
+ var _isOptional = !((_jsonschema$required2 = jsonschema.required) !== null && _jsonschema$required2 !== void 0 && _jsonschema$required2.includes(prop));
223
221
 
224
- var _unionTypes = jsonschema.properties[prop].oneOf.map(function (el) {
225
- if (el.title) return el.title;
226
- if (el.$ref) return getTypeStrFromRef(el.$ref);
227
- return el.type;
228
- });
222
+ var _unionTypes = jsonschema.properties[prop].oneOf.map(function (el) {
223
+ if (el.title) return el.title;
224
+ if (el.$ref) return getTypeStrFromRef(el.$ref);
225
+ return el.type;
226
+ });
229
227
 
230
- var _uniqUnionTypes = (0, _toConsumableArray2["default"])(new Set(_unionTypes));
228
+ var _uniqUnionTypes = (0, _toConsumableArray2["default"])(new Set(_unionTypes));
231
229
 
232
- if (_uniqUnionTypes.length === 1) {
233
- return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(_uniqUnionTypes[0]))), _isOptional);
234
- } else {
235
- return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(_uniqUnionTypes.map(function (typ) {
236
- return t.tsTypeReference(t.identifier(typ));
237
- }))), _isOptional);
238
- }
230
+ if (_uniqUnionTypes.length === 1) {
231
+ return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(_uniqUnionTypes[0]))), _isOptional);
232
+ } else {
233
+ return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(_uniqUnionTypes.map(function (typ) {
234
+ return t.tsTypeReference(t.identifier(typ));
235
+ }))), _isOptional);
239
236
  }
237
+ }
240
238
 
241
- try {
242
- getPropertyType(jsonschema, prop);
243
- } catch (e) {
244
- console.log(e);
245
- console.log(jsonschema, prop);
246
- }
239
+ try {
240
+ getPropertyType(jsonschema, prop);
241
+ } catch (e) {
242
+ console.log(e);
243
+ console.log(jsonschema, prop);
244
+ }
245
+
246
+ var _getPropertyType = getPropertyType(jsonschema, prop),
247
+ type = _getPropertyType.type,
248
+ optional = _getPropertyType.optional;
247
249
 
248
- var _getPropertyType = getPropertyType(jsonschema, prop),
249
- type = _getPropertyType.type,
250
- optional = _getPropertyType.optional;
250
+ return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(type), optional);
251
+ }
251
252
 
252
- return (0, _babel.propertySignature)(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(type), optional);
253
+ var getParamsTypeAnnotation = function getParamsTypeAnnotation(jsonschema) {
254
+ var _jsonschema$propertie;
255
+
256
+ var camelize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
257
+ var keys = Object.keys((_jsonschema$propertie = jsonschema.properties) !== null && _jsonschema$propertie !== void 0 ? _jsonschema$propertie : {});
258
+ if (!keys.length) return undefined;
259
+ var typedParams = keys.map(function (prop) {
260
+ return getPropertySignatureFromProp(jsonschema, prop, camelize);
253
261
  });
262
+ return t.tsTypeAnnotation(t.tsTypeLiteral((0, _toConsumableArray2["default"])(typedParams)));
263
+ };
264
+
265
+ exports.getParamsTypeAnnotation = getParamsTypeAnnotation;
266
+
267
+ var createTypedObjectParams = function createTypedObjectParams(jsonschema) {
268
+ var _jsonschema$propertie2;
269
+
270
+ var camelize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
271
+ var keys = Object.keys((_jsonschema$propertie2 = jsonschema.properties) !== null && _jsonschema$propertie2 !== void 0 ? _jsonschema$propertie2 : {});
272
+ if (!keys.length) return; // const typedParams = keys.map(prop => getPropertySignatureFromProp(jsonschema, prop, camelize));
273
+
254
274
  var params = keys.map(function (prop) {
255
275
  return t.objectProperty(camelize ? t.identifier((0, _case.camel)(prop)) : t.identifier(prop), camelize ? t.identifier((0, _case.camel)(prop)) : t.identifier(prop), false, true);
256
276
  });
257
277
  var obj = t.objectPattern((0, _toConsumableArray2["default"])(params));
258
- obj.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral((0, _toConsumableArray2["default"])(typedParams)));
278
+ obj.typeAnnotation = getParamsTypeAnnotation(jsonschema, camelize);
259
279
  return obj;
260
280
  };
261
281
 
package/main/wasm.js CHANGED
@@ -7,7 +7,7 @@ var _typeof = require("@babel/runtime/helpers/typeof");
7
7
  Object.defineProperty(exports, "__esModule", {
8
8
  value: true
9
9
  });
10
- exports.createWasmQueryMethod = exports.createWasmExecMethod = exports.createTypeOrInterface = exports.createTypeInterface = exports.createQueryInterface = exports.createQueryClass = exports.createPropertyFunctionWithObjectParamsForExec = exports.createPropertyFunctionWithObjectParams = exports.createExecuteInterface = exports.createExecuteClass = void 0;
10
+ exports.createWasmQueryMethod = exports.createWasmExecMethod = exports.createTypeOrInterface = exports.createTypeInterface = exports.createQueryInterface = exports.createQueryClass = exports.createPropertyFunctionWithObjectParamsForExec = exports.createPropertyFunctionWithObjectParams = exports.createExecuteInterface = exports.createExecuteClass = exports.FIXED_EXECUTE_PARAMS = exports.CONSTANT_EXEC_PARAMS = void 0;
11
11
 
12
12
  var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
13
13
 
@@ -60,6 +60,8 @@ var createQueryClass = function createQueryClass(className, implementsClassName,
60
60
  };
61
61
 
62
62
  exports.createQueryClass = createQueryClass;
63
+ var CONSTANT_EXEC_PARAMS = [t.assignmentPattern((0, _babel.identifier)('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), false), t.stringLiteral('auto')), (0, _babel.identifier)('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), (0, _babel.identifier)('funds', t.tsTypeAnnotation((0, _babel.tsTypeOperator)(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
64
+ exports.CONSTANT_EXEC_PARAMS = CONSTANT_EXEC_PARAMS;
63
65
 
64
66
  var createWasmExecMethod = function createWasmExecMethod(jsonschema) {
65
67
  var _jsonschema$propertie2;
@@ -71,9 +73,8 @@ var createWasmExecMethod = function createWasmExecMethod(jsonschema) {
71
73
  var args = Object.keys(properties).map(function (prop) {
72
74
  return t.objectProperty(t.identifier(prop), t.identifier((0, _case.camel)(prop)), false, prop === (0, _case.camel)(prop));
73
75
  });
74
- var constantParams = [t.assignmentPattern((0, _babel.identifier)('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), false), t.stringLiteral('auto')), (0, _babel.identifier)('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), (0, _babel.identifier)('funds', t.tsTypeAnnotation((0, _babel.tsTypeOperator)(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
75
76
  return t.classProperty(t.identifier(methodName), (0, _utils.arrowFunctionExpression)(obj ? [// props
76
- obj].concat(constantParams) : constantParams, t.blockStatement([t.returnStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('execute')), [t.memberExpression(t.thisExpression(), t.identifier('sender')), t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression((0, _toConsumableArray2["default"])(args)))]), t.identifier('fee'), t.identifier('memo'), t.identifier('funds')])))]), // return type
77
+ obj].concat(CONSTANT_EXEC_PARAMS) : CONSTANT_EXEC_PARAMS, t.blockStatement([t.returnStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('execute')), [t.memberExpression(t.thisExpression(), t.identifier('sender')), t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression((0, _toConsumableArray2["default"])(args)))]), t.identifier('fee'), t.identifier('memo'), t.identifier('funds')])))]), // return type
77
78
  t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ExecuteResult'))]))), true));
78
79
  };
79
80
 
@@ -132,14 +133,15 @@ var createPropertyFunctionWithObjectParams = function createPropertyFunctionWith
132
133
  };
133
134
 
134
135
  exports.createPropertyFunctionWithObjectParams = createPropertyFunctionWithObjectParams;
136
+ var FIXED_EXECUTE_PARAMS = [(0, _babel.identifier)('fee', t.tsTypeAnnotation(t.tsUnionType([t.tsNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), true), (0, _babel.identifier)('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), (0, _babel.identifier)('funds', t.tsTypeAnnotation((0, _babel.tsTypeOperator)(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
137
+ exports.FIXED_EXECUTE_PARAMS = FIXED_EXECUTE_PARAMS;
135
138
 
136
139
  var createPropertyFunctionWithObjectParamsForExec = function createPropertyFunctionWithObjectParamsForExec(methodName, responseType, jsonschema) {
137
140
  var obj = (0, _types2.createTypedObjectParams)(jsonschema);
138
- var fixedParams = [(0, _babel.identifier)('fee', t.tsTypeAnnotation(t.tsUnionType([t.tsNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), true), (0, _babel.identifier)('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), (0, _babel.identifier)('funds', t.tsTypeAnnotation((0, _babel.tsTypeOperator)(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
139
141
  var func = {
140
142
  type: 'TSFunctionType',
141
143
  typeAnnotation: (0, _utils.promiseTypeAnnotation)(responseType),
142
- parameters: obj ? [obj].concat(fixedParams) : fixedParams
144
+ parameters: obj ? [obj].concat(FIXED_EXECUTE_PARAMS) : FIXED_EXECUTE_PARAMS
143
145
  };
144
146
  return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
145
147
  };
@@ -6,12 +6,15 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
6
6
 
7
7
  import * as t from '@babel/types';
8
8
  import { camel, pascal } from 'case';
9
- import { tsPropertySignature, tsObjectPattern, callExpression, getMessageProperties } from './utils';
10
- import { typeRefOrOptionalUnion, propertySignature, optionalConditionalExpression } from './utils/babel';
11
- import { getPropertyType } from './utils/types';
9
+ import { callExpression, getMessageProperties, identifier, tsObjectPattern, tsPropertySignature } from './utils';
10
+ import { omitTypeReference, optionalConditionalExpression, propertySignature, shorthandProperty, typeRefOrOptionalUnion } from './utils/babel';
11
+ import { getParamsTypeAnnotation, getPropertyType, getTypeFromRef } from './utils/types';
12
+ import { FIXED_EXECUTE_PARAMS } from './wasm'; // TODO: this mutations boolean is not actually used here and only at a higher level
13
+
12
14
  const DEFAULT_OPTIONS = {
13
15
  optionalClient: false,
14
- v4: false
16
+ v4: false,
17
+ mutations: false
15
18
  };
16
19
  export const createReactQueryHooks = ({
17
20
  queryMsg,
@@ -77,6 +80,124 @@ export const createReactQueryHook = ({
77
80
  })], t.tsTypeAnnotation(t.tsTypeReference(t.identifier(hookParamsTypeName))))], t.blockStatement([t.returnStatement(callExpression(t.identifier('useQuery'), [t.arrayExpression(generateUseQueryQueryKey(hookKeyName, props, options.optionalClient)), t.arrowFunctionExpression([], optionalConditionalExpression(t.identifier('client'), t.callExpression(t.memberExpression(t.identifier('client'), t.identifier(methodName)), args), t.identifier('undefined'), options.optionalClient), false), options.optionalClient ? t.objectExpression([t.spreadElement(t.identifier('options')), t.objectProperty(t.identifier('enabled'), t.logicalExpression('&&', t.unaryExpression('!', t.unaryExpression('!', t.identifier('client'))), t.conditionalExpression( // explicitly check for undefined
78
81
  t.binaryExpression('!=', t.optionalMemberExpression(t.identifier('options'), t.identifier('enabled'), false, true), t.identifier('undefined')), t.memberExpression(t.identifier('options'), t.identifier('enabled')), t.booleanLiteral(true))))]) : t.identifier('options')], t.tsTypeParameterInstantiation([typeRefOrOptionalUnion(t.identifier(responseType), options.optionalClient), t.tsTypeReference(t.identifier('Error')), t.tsTypeReference(t.identifier(responseType)), t.tsArrayType(t.tsParenthesizedType(t.tsUnionType([t.tsStringKeyword(), t.tsUndefinedKeyword()])))])))])));
79
82
  };
83
+
84
+ /**
85
+ * Example:
86
+ ```
87
+ export interface Cw4UpdateMembersMutation {
88
+ client: Cw4GroupClient
89
+ args: {
90
+ tokenId: string
91
+ remove: string[]
92
+ }
93
+ options?: Omit<
94
+ UseMutationOptions<ExecuteResult, Error, Pick<Cw4UpdateMembersMutation, 'args'>>,
95
+ 'mutationFn'
96
+ >
97
+ }
98
+ ```
99
+ */
100
+ export const createReactQueryMutationArgsInterface = ({
101
+ ExecuteClient,
102
+ mutationHookParamsTypeName,
103
+ useMutationTypeParameter,
104
+ jsonschema
105
+ }) => {
106
+ const typedUseMutationOptions = t.tsTypeReference(t.identifier('UseMutationOptions'), useMutationTypeParameter);
107
+ const body = [tsPropertySignature(t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(ExecuteClient))), false)];
108
+ let msgType = getParamsTypeAnnotation(jsonschema); // TODO: this should not have to be done manually.
109
+
110
+ if (!msgType && jsonschema?.$ref?.startsWith('#/definitions/')) {
111
+ let refName = jsonschema?.$ref;
112
+
113
+ if (/_for_[A-Z]/.test(refName)) {
114
+ refName = refName.replace(/_for_/, 'For');
115
+ }
116
+
117
+ msgType = t.tsTypeAnnotation(getTypeFromRef(refName));
118
+ }
119
+
120
+ if (msgType) {
121
+ body.push(t.tsPropertySignature(t.identifier('msg'), msgType));
122
+ } // fee: number | StdFee | "auto" = "auto", memo?: string, funds?: readonly Coin[]
123
+
124
+
125
+ const optionalArgs = t.tsPropertySignature(t.identifier('args'), t.tsTypeAnnotation(t.tsTypeLiteral(FIXED_EXECUTE_PARAMS.map(param => propertySignature(param.name, param.typeAnnotation, param.optional)))));
126
+ optionalArgs.optional = true;
127
+ body.push(optionalArgs);
128
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(mutationHookParamsTypeName), null, [], t.tsInterfaceBody(body)));
129
+ };
130
+ export const createReactQueryMutationHooks = ({
131
+ execMsg,
132
+ contractName,
133
+ ExecuteClient,
134
+ options = {}
135
+ }) => {
136
+ // merge the user options with the defaults
137
+ return getMessageProperties(execMsg).reduce((m, schema) => {
138
+ // update_members
139
+ const execMethodUnderscoreName = Object.keys(schema.properties)[0]; // updateMembers
140
+
141
+ const execMethodName = camel(execMethodUnderscoreName); // Cw20UpdateMembersMutation
142
+
143
+ const mutationHookParamsTypeName = `${pascal(contractName)}${pascal(execMethodName)}Mutation`; // useCw20UpdateMembersMutation
144
+
145
+ const mutationHookName = `use${mutationHookParamsTypeName}`;
146
+ const jsonschema = schema.properties[execMethodUnderscoreName];
147
+ const properties = jsonschema.properties ?? {}; // TODO: there should be a better way to do this
148
+
149
+ const hasMsg = !!(Object.keys(properties)?.length || jsonschema?.$ref); // <ExecuteResult, Error, Cw4UpdateMembersMutation>
150
+
151
+ const useMutationTypeParameter = generateMutationTypeParameter(mutationHookParamsTypeName, hasMsg);
152
+ return [createReactQueryMutationArgsInterface({
153
+ mutationHookParamsTypeName,
154
+ ExecuteClient,
155
+ jsonschema,
156
+ useMutationTypeParameter
157
+ }), createReactQueryMutationHook({
158
+ execMethodName,
159
+ mutationHookName,
160
+ mutationHookParamsTypeName,
161
+ hasMsg,
162
+ useMutationTypeParameter
163
+ }), ...m];
164
+ }, []);
165
+ };
166
+ /**
167
+ * Generates the mutation type parameter. If args exist, we use a pick. If not, we just return the params type.
168
+ */
169
+
170
+ function generateMutationTypeParameter(mutationHookParamsTypeName, hasArgs) {
171
+ return t.tsTypeParameterInstantiation([// Data
172
+ t.tSTypeReference(t.identifier('ExecuteResult')), // Error
173
+ t.tsTypeReference(t.identifier('Error')), // Variables
174
+ t.tsTypeReference(t.identifier(mutationHookParamsTypeName))]);
175
+ }
176
+
177
+ /**
178
+ *
179
+ * Example:
180
+ ```
181
+ export const useCw4UpdateMembersMutation = ({ client, options }: Omit<Cw4UpdateMembersMutation, 'args'>) =>
182
+ useMutation<ExecuteResult, Error, Pick<Cw4UpdateMembersMutation, 'args'>>(
183
+ ({ args }) => client.updateMembers(args),
184
+ options
185
+ )
186
+ ```
187
+ */
188
+ export const createReactQueryMutationHook = ({
189
+ mutationHookName,
190
+ mutationHookParamsTypeName,
191
+ execMethodName,
192
+ useMutationTypeParameter,
193
+ hasMsg
194
+ }) => {
195
+ const useMutationFunctionArgs = [shorthandProperty('client')];
196
+ if (hasMsg) useMutationFunctionArgs.push(shorthandProperty('msg'));
197
+ useMutationFunctionArgs.push(t.objectProperty(t.identifier('args'), t.assignmentPattern(t.objectPattern(FIXED_EXECUTE_PARAMS.map(param => shorthandProperty(param.name))), t.objectExpression([]))));
198
+ return t.exportNamedDeclaration(t.functionDeclaration(t.identifier(mutationHookName), [identifier('options', t.tsTypeAnnotation(omitTypeReference(t.tsTypeReference(t.identifier('UseMutationOptions'), useMutationTypeParameter), 'mutationFn')), true)], t.blockStatement([t.returnStatement(callExpression(t.identifier('useMutation'), [t.arrowFunctionExpression([t.objectPattern(useMutationFunctionArgs)], t.callExpression(t.memberExpression(t.identifier('client'), t.identifier(execMethodName)), (hasMsg ? [t.identifier('msg')] : []).concat(FIXED_EXECUTE_PARAMS.map(param => t.identifier(param.name)))), false // not async
199
+ ), t.identifier('options')], useMutationTypeParameter))])));
200
+ };
80
201
  export const createReactQueryHookInterface = ({
81
202
  QueryClient,
82
203
  hookParamsTypeName,
@@ -87,7 +208,7 @@ export const createReactQueryHookInterface = ({
87
208
  // merge the user options with the defaults
88
209
  options = _objectSpread(_objectSpread({}, DEFAULT_OPTIONS), options);
89
210
  const typedUseQueryOptions = t.tsTypeReference(t.identifier('UseQueryOptions'), t.tsTypeParameterInstantiation([typeRefOrOptionalUnion(t.identifier(responseType), options.optionalClient), t.tsTypeReference(t.identifier('Error')), t.tsTypeReference(t.identifier(responseType)), t.tsArrayType(t.tsParenthesizedType(t.tsUnionType([t.tsStringKeyword(), t.tsUndefinedKeyword()])))]));
90
- const body = [tsPropertySignature(t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(QueryClient))), options.optionalClient), tsPropertySignature(t.identifier('options'), t.tsTypeAnnotation(options.v4 ? t.tSIntersectionType([t.tsTypeReference(t.identifier('Omit'), t.tsTypeParameterInstantiation([typedUseQueryOptions, t.tsLiteralType(t.stringLiteral("'queryKey' | 'queryFn' | 'initialData'"))])), t.tSTypeLiteral([t.tsPropertySignature(t.identifier('initialData?'), t.tsTypeAnnotation(t.tsUndefinedKeyword()))])]) : typedUseQueryOptions), true)];
211
+ const body = [tsPropertySignature(t.identifier('client'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(QueryClient))), options.optionalClient), tsPropertySignature(t.identifier('options'), t.tsTypeAnnotation(options.v4 ? t.tSIntersectionType([omitTypeReference(typedUseQueryOptions, "'queryKey' | 'queryFn' | 'initialData'"), t.tSTypeLiteral([t.tsPropertySignature(t.identifier('initialData?'), t.tsTypeAnnotation(t.tsUndefinedKeyword()))])]) : typedUseQueryOptions), true)];
91
212
  const props = getProps(jsonschema, true);
92
213
 
93
214
  if (props.length) {
@@ -1,7 +1,8 @@
1
1
  import generate from '@babel/generator';
2
2
  import * as t from '@babel/types';
3
3
  import query_msg from './../../../__fixtures__/basic/query_msg.json';
4
- import { createReactQueryHooks } from './react-query';
4
+ import execute_msg from './../../../__fixtures__/basic/execute_msg_for__empty.json';
5
+ import { createReactQueryHooks, createReactQueryMutationHooks } from './react-query';
5
6
 
6
7
  const expectCode = ast => {
7
8
  expect(generate(ast).code).toMatchSnapshot();
@@ -56,4 +57,9 @@ it('createReactQueryHooks', () => {
56
57
  v4: true
57
58
  }
58
59
  })));
60
+ expectCode(t.program(createReactQueryMutationHooks({
61
+ execMsg: execute_msg,
62
+ contractName: 'Sg721',
63
+ ExecuteClient: 'Sg721Client'
64
+ })));
59
65
  });
@@ -1,5 +1,6 @@
1
1
  import * as t from '@babel/types';
2
2
  import { snake } from "case";
3
+ // t.TSPropertySignature - kind?
3
4
  export const propertySignature = (name, typeAnnotation, optional = false) => {
4
5
  return {
5
6
  type: 'TSPropertySignature',
@@ -164,4 +165,18 @@ export const optionalConditionalExpression = (test, expression, alternate, optio
164
165
  export const typeRefOrOptionalUnion = (identifier, optional = false) => {
165
166
  const typeReference = t.tsTypeReference(identifier);
166
167
  return optional ? t.tsUnionType([typeReference, t.tsUndefinedKeyword()]) : typeReference;
168
+ };
169
+ export const parameterizedTypeReference = (identifier, from, omit) => {
170
+ return t.tsTypeReference(t.identifier(identifier), t.tsTypeParameterInstantiation([from, typeof omit === 'string' ? t.tsLiteralType(t.stringLiteral(omit)) : t.tsUnionType(omit.map(o => t.tsLiteralType(t.stringLiteral(o))))]));
171
+ };
172
+ /**
173
+ * omitTypeReference(t.tsTypeReference(t.identifier('Cw4UpdateMembersMutation'),),'args').....
174
+ * Omit<Cw4UpdateMembersMutation, 'args'>
175
+ */
176
+
177
+ export const omitTypeReference = (from, omit) => {
178
+ return parameterizedTypeReference('Omit', from, omit);
179
+ };
180
+ export const pickTypeReference = (from, pick) => {
181
+ return parameterizedTypeReference('Pick', from, pick);
167
182
  };
@@ -16,7 +16,7 @@ const getTypeStrFromRef = $ref => {
16
16
  }
17
17
  };
18
18
 
19
- const getTypeFromRef = $ref => {
19
+ export const getTypeFromRef = $ref => {
20
20
  switch ($ref) {
21
21
  case '#/definitions/Binary':
22
22
  return t.tsTypeReference(t.identifier('Binary'));
@@ -150,65 +150,72 @@ export const getPropertyType = (schema, prop) => {
150
150
  optional
151
151
  };
152
152
  };
153
- export const createTypedObjectParams = (jsonschema, camelize = true) => {
154
- const keys = Object.keys(jsonschema.properties ?? {});
155
- if (!keys.length) return;
156
- const typedParams = keys.map(prop => {
157
- if (jsonschema.properties[prop].type === 'object') {
158
- if (jsonschema.properties[prop].title) {
159
- return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(jsonschema.properties[prop].title))));
160
- } else {
161
- throw new Error('createTypedObjectParams() contact maintainer');
162
- }
153
+ export function getPropertySignatureFromProp(jsonschema, prop, camelize) {
154
+ if (jsonschema.properties[prop].type === 'object') {
155
+ if (jsonschema.properties[prop].title) {
156
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(jsonschema.properties[prop].title))));
157
+ } else {
158
+ throw new Error('createTypedObjectParams() contact maintainer');
163
159
  }
160
+ }
164
161
 
165
- if (Array.isArray(jsonschema.properties[prop].allOf)) {
166
- const isOptional = !jsonschema.required?.includes(prop);
167
- const unionTypes = jsonschema.properties[prop].allOf.map(el => {
168
- if (el.title) return el.title;
169
- if (el.$ref) return getTypeStrFromRef(el.$ref);
170
- return el.type;
171
- });
172
- const uniqUnionTypes = [...new Set(unionTypes)];
173
-
174
- if (uniqUnionTypes.length === 1) {
175
- return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(uniqUnionTypes[0]))), isOptional);
176
- } else {
177
- return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(uniqUnionTypes.map(typ => t.tsTypeReference(t.identifier(typ))))), isOptional);
178
- }
179
- } else if (Array.isArray(jsonschema.properties[prop].oneOf)) {
180
- const isOptional = !jsonschema.required?.includes(prop);
181
- const unionTypes = jsonschema.properties[prop].oneOf.map(el => {
182
- if (el.title) return el.title;
183
- if (el.$ref) return getTypeStrFromRef(el.$ref);
184
- return el.type;
185
- });
186
- const uniqUnionTypes = [...new Set(unionTypes)];
187
-
188
- if (uniqUnionTypes.length === 1) {
189
- return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(uniqUnionTypes[0]))), isOptional);
190
- } else {
191
- return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(uniqUnionTypes.map(typ => t.tsTypeReference(t.identifier(typ))))), isOptional);
192
- }
162
+ if (Array.isArray(jsonschema.properties[prop].allOf)) {
163
+ const isOptional = !jsonschema.required?.includes(prop);
164
+ const unionTypes = jsonschema.properties[prop].allOf.map(el => {
165
+ if (el.title) return el.title;
166
+ if (el.$ref) return getTypeStrFromRef(el.$ref);
167
+ return el.type;
168
+ });
169
+ const uniqUnionTypes = [...new Set(unionTypes)];
170
+
171
+ if (uniqUnionTypes.length === 1) {
172
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(uniqUnionTypes[0]))), isOptional);
173
+ } else {
174
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(uniqUnionTypes.map(typ => t.tsTypeReference(t.identifier(typ))))), isOptional);
193
175
  }
194
-
195
- try {
196
- getPropertyType(jsonschema, prop);
197
- } catch (e) {
198
- console.log(e);
199
- console.log(jsonschema, prop);
176
+ } else if (Array.isArray(jsonschema.properties[prop].oneOf)) {
177
+ const isOptional = !jsonschema.required?.includes(prop);
178
+ const unionTypes = jsonschema.properties[prop].oneOf.map(el => {
179
+ if (el.title) return el.title;
180
+ if (el.$ref) return getTypeStrFromRef(el.$ref);
181
+ return el.type;
182
+ });
183
+ const uniqUnionTypes = [...new Set(unionTypes)];
184
+
185
+ if (uniqUnionTypes.length === 1) {
186
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsTypeReference(t.identifier(uniqUnionTypes[0]))), isOptional);
187
+ } else {
188
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(t.tsUnionType(uniqUnionTypes.map(typ => t.tsTypeReference(t.identifier(typ))))), isOptional);
200
189
  }
190
+ }
191
+
192
+ try {
193
+ getPropertyType(jsonschema, prop);
194
+ } catch (e) {
195
+ console.log(e);
196
+ console.log(jsonschema, prop);
197
+ }
198
+
199
+ const {
200
+ type,
201
+ optional
202
+ } = getPropertyType(jsonschema, prop);
203
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(type), optional);
204
+ }
205
+ export const getParamsTypeAnnotation = (jsonschema, camelize = true) => {
206
+ const keys = Object.keys(jsonschema.properties ?? {});
207
+ if (!keys.length) return undefined;
208
+ const typedParams = keys.map(prop => getPropertySignatureFromProp(jsonschema, prop, camelize));
209
+ return t.tsTypeAnnotation(t.tsTypeLiteral([...typedParams]));
210
+ };
211
+ export const createTypedObjectParams = (jsonschema, camelize = true) => {
212
+ const keys = Object.keys(jsonschema.properties ?? {});
213
+ if (!keys.length) return; // const typedParams = keys.map(prop => getPropertySignatureFromProp(jsonschema, prop, camelize));
201
214
 
202
- const {
203
- type,
204
- optional
205
- } = getPropertyType(jsonschema, prop);
206
- return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(type), optional);
207
- });
208
215
  const params = keys.map(prop => {
209
216
  return t.objectProperty(camelize ? t.identifier(camel(prop)) : t.identifier(prop), camelize ? t.identifier(camel(prop)) : t.identifier(prop), false, true);
210
217
  });
211
218
  const obj = t.objectPattern([...params]);
212
- obj.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([...typedParams]));
219
+ obj.typeAnnotation = getParamsTypeAnnotation(jsonschema, camelize);
213
220
  return obj;
214
221
  };
package/module/wasm.js CHANGED
@@ -27,6 +27,7 @@ export const createQueryClass = (className, implementsClassName, queryMsg) => {
27
27
  t.classMethod('constructor', t.identifier('constructor'), [typedIdentifier('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('CosmWasmClient')))), typedIdentifier('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([// client/contract set
28
28
  t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('client'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress'))), ...bindings])), ...methods], [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))]));
29
29
  };
30
+ export const CONSTANT_EXEC_PARAMS = [t.assignmentPattern(identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), false), t.stringLiteral('auto')), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
30
31
  export const createWasmExecMethod = jsonschema => {
31
32
  const underscoreName = Object.keys(jsonschema.properties)[0];
32
33
  const methodName = camel(underscoreName);
@@ -35,9 +36,8 @@ export const createWasmExecMethod = jsonschema => {
35
36
  const args = Object.keys(properties).map(prop => {
36
37
  return t.objectProperty(t.identifier(prop), t.identifier(camel(prop)), false, prop === camel(prop));
37
38
  });
38
- const constantParams = [t.assignmentPattern(identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), false), t.stringLiteral('auto')), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
39
39
  return t.classProperty(t.identifier(methodName), arrowFunctionExpression(obj ? [// props
40
- obj, ...constantParams] : constantParams, t.blockStatement([t.returnStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('execute')), [t.memberExpression(t.thisExpression(), t.identifier('sender')), t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression([...args]))]), t.identifier('fee'), t.identifier('memo'), t.identifier('funds')])))]), // return type
40
+ obj, ...CONSTANT_EXEC_PARAMS] : CONSTANT_EXEC_PARAMS, t.blockStatement([t.returnStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('execute')), [t.memberExpression(t.thisExpression(), t.identifier('sender')), t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression([...args]))]), t.identifier('fee'), t.identifier('memo'), t.identifier('funds')])))]), // return type
41
41
  t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ExecuteResult'))]))), true));
42
42
  };
43
43
  export const createExecuteClass = (className, implementsClassName, extendsClassName, execMsg) => {
@@ -81,13 +81,13 @@ export const createPropertyFunctionWithObjectParams = (methodName, responseType,
81
81
  };
82
82
  return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
83
83
  };
84
+ export const FIXED_EXECUTE_PARAMS = [identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tsNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), true), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
84
85
  export const createPropertyFunctionWithObjectParamsForExec = (methodName, responseType, jsonschema) => {
85
86
  const obj = createTypedObjectParams(jsonschema);
86
- const fixedParams = [identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tsNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), true), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
87
87
  const func = {
88
88
  type: 'TSFunctionType',
89
89
  typeAnnotation: promiseTypeAnnotation(responseType),
90
- parameters: obj ? [obj, ...fixedParams] : fixedParams
90
+ parameters: obj ? [obj, ...FIXED_EXECUTE_PARAMS] : FIXED_EXECUTE_PARAMS
91
91
  };
92
92
  return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
93
93
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wasm-ast-types",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "CosmWasm TypeScript AST generation",
5
5
  "author": "Dan Lynch <pyramation@gmail.com>",
6
6
  "homepage": "https://github.com/pyramation/cosmwasm-typescript-gen/tree/master/packages/wasm-ast-types#readme",
@@ -84,5 +84,5 @@
84
84
  "ast-stringify": "0.1.0",
85
85
  "case": "1.6.3"
86
86
  },
87
- "gitHead": "c5fc4992d9da5f1c9da1f2c34469994dee7801df"
87
+ "gitHead": "871479982969e89f40b75ca5c85e8bed34a824da"
88
88
  }
@@ -1,5 +1,5 @@
1
1
  import * as t from '@babel/types';
2
- import { QueryMsg } from './types';
2
+ import { QueryMsg, ExecuteMsg } from './types';
3
3
 
4
4
  interface ReactQueryHooks {
5
5
  queryMsg: QueryMsg
@@ -19,6 +19,7 @@ interface ReactQueryHookQuery {
19
19
  export declare interface ReactQueryOptions {
20
20
  optionalClient?: boolean
21
21
  v4?: boolean
22
+ mutations?: boolean
22
23
  }
23
24
  export declare const createReactQueryHooks: ({ queryMsg, contractName, QueryClient, options }: ReactQueryHooks) => any;
24
25
  export declare const createReactQueryHook: ({ hookName, hookParamsTypeName, responseType, hookKeyName, methodName, jsonschema }: ReactQueryHookQuery) => t.ExportNamedDeclaration;
@@ -29,4 +30,41 @@ interface ReactQueryHookQueryInterface {
29
30
  jsonschema: any;
30
31
  }
31
32
  export declare const createReactQueryHookInterface: ({ QueryClient, hookParamsTypeName, responseType, jsonschema }: ReactQueryHookQueryInterface) => t.ExportNamedDeclaration;
33
+
34
+ interface ReactQueryMutationHooks {
35
+ execMsg: ExecuteMsg
36
+ contractName: string
37
+ ExecuteClient: string
38
+ options?: ReactQueryOptions
39
+ }
40
+ export declare const createReactQueryMutationHooks: ({ execMsg, contractName, ExecuteClient, options }: ReactQueryMutationHooks) => any
41
+
42
+ interface ReactQueryMutationHook {
43
+ mutationHookName: string;
44
+ mutationHookParamsTypeName: string;
45
+ execMethodName: string;
46
+ execArgs: t.ObjectProperty[]
47
+ options?: ReactQueryOptions
48
+ }
49
+
50
+ export declare const createReactQueryMutationHook: ({
51
+ mutationHookName,
52
+ mutationHookParamsTypeName,
53
+ execMethodName,
54
+ execArgs,
55
+ options,
56
+ }: ReactQueryMutationHook) => any
57
+
58
+ interface ReactQueryMutationHookInterface {
59
+ ExecuteClient: string
60
+ mutationHookParamsTypeName: string;
61
+ jsonschema: any
62
+ }
63
+
64
+ export declare const createReactQueryMutationArgsInterface: ({
65
+ ExecuteClient,
66
+ mutationHookParamsTypeName,
67
+ jsonschema
68
+ }: ReactQueryMutationHookInterface) => t.ExportNamedDeclaration;
69
+
32
70
  export { };