expo-modules-test-core 56.0.0 → 56.0.1
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.
- package/LICENSE +21 -0
- package/android/build.gradle +2 -2
- package/build/index.js +18 -16
- package/build/index.js.map +1 -1
- package/package.json +11 -7
- package/src/index.ts +18 -16
- package/build/getStructure.d.ts +0 -3
- package/build/getStructure.d.ts.map +0 -1
- package/build/getStructure.js +0 -244
- package/build/getStructure.js.map +0 -1
- package/build/mockgen.d.ts +0 -4
- package/build/mockgen.d.ts.map +0 -1
- package/build/mockgen.js +0 -391
- package/build/mockgen.js.map +0 -1
- package/build/types.d.ts +0 -55
- package/build/types.d.ts.map +0 -1
- package/build/types.js +0 -3
- package/build/types.js.map +0 -1
- package/src/getStructure.ts +0 -299
- package/src/mockgen.ts +0 -525
- package/src/types.ts +0 -65
package/build/mockgen.js
DELETED
|
@@ -1,391 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
'use strict';
|
|
3
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
4
|
-
if (k2 === undefined) k2 = k;
|
|
5
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
6
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
7
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
8
|
-
}
|
|
9
|
-
Object.defineProperty(o, k2, desc);
|
|
10
|
-
}) : (function(o, m, k, k2) {
|
|
11
|
-
if (k2 === undefined) k2 = k;
|
|
12
|
-
o[k2] = m[k];
|
|
13
|
-
}));
|
|
14
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
15
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
16
|
-
}) : function(o, v) {
|
|
17
|
-
o["default"] = v;
|
|
18
|
-
});
|
|
19
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
20
|
-
var ownKeys = function(o) {
|
|
21
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
22
|
-
var ar = [];
|
|
23
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
24
|
-
return ar;
|
|
25
|
-
};
|
|
26
|
-
return ownKeys(o);
|
|
27
|
-
};
|
|
28
|
-
return function (mod) {
|
|
29
|
-
if (mod && mod.__esModule) return mod;
|
|
30
|
-
var result = {};
|
|
31
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
32
|
-
__setModuleDefault(result, mod);
|
|
33
|
-
return result;
|
|
34
|
-
};
|
|
35
|
-
})();
|
|
36
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
37
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
38
|
-
};
|
|
39
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
40
|
-
exports.generateMocks = generateMocks;
|
|
41
|
-
const fs_1 = __importDefault(require("fs"));
|
|
42
|
-
const path_1 = __importDefault(require("path"));
|
|
43
|
-
const prettier = __importStar(require("prettier"));
|
|
44
|
-
const typescript_1 = __importDefault(require("typescript"));
|
|
45
|
-
const directoryPath = process.cwd();
|
|
46
|
-
/*
|
|
47
|
-
We receive types from SourceKitten and `getStructure` like so (examples):
|
|
48
|
-
[AcceptedTypes]?, UIColor?, [String: Any]
|
|
49
|
-
|
|
50
|
-
We need to parse them first to TS nodes in `mapSwiftTypeToTsType` with the following helper functions.
|
|
51
|
-
*/
|
|
52
|
-
function isSwiftArray(type) {
|
|
53
|
-
// This can also be an object, but we check that first, so if it's not an object and is wrapped with [] it's an array.
|
|
54
|
-
return type.startsWith('[') && type.endsWith(']');
|
|
55
|
-
}
|
|
56
|
-
function maybeUnwrapSwiftArray(type) {
|
|
57
|
-
const isArray = isSwiftArray(type);
|
|
58
|
-
if (!isArray) {
|
|
59
|
-
return type;
|
|
60
|
-
}
|
|
61
|
-
const innerType = type.substring(1, type.length - 1);
|
|
62
|
-
return innerType;
|
|
63
|
-
}
|
|
64
|
-
function isSwiftOptional(type) {
|
|
65
|
-
return type.endsWith('?');
|
|
66
|
-
}
|
|
67
|
-
function maybeUnwrapSwiftOptional(type) {
|
|
68
|
-
const isOptional = isSwiftOptional(type);
|
|
69
|
-
if (!isOptional) {
|
|
70
|
-
return type;
|
|
71
|
-
}
|
|
72
|
-
const innerType = type.substring(0, type.length - 1);
|
|
73
|
-
return innerType;
|
|
74
|
-
}
|
|
75
|
-
function isSwiftDictionary(type) {
|
|
76
|
-
return (type.startsWith('[') &&
|
|
77
|
-
type.endsWith(']') &&
|
|
78
|
-
findRootColonInDictionary(type.substring(1, type.length - 1)) >= 0);
|
|
79
|
-
}
|
|
80
|
-
function isEither(type) {
|
|
81
|
-
return type.startsWith('Either<');
|
|
82
|
-
}
|
|
83
|
-
// "Either<TypeOne, TypeTwo>" -> ["TypeOne", "TypeTwo"]
|
|
84
|
-
function maybeUnwrapEither(type) {
|
|
85
|
-
if (!isEither(type)) {
|
|
86
|
-
return [type];
|
|
87
|
-
}
|
|
88
|
-
const innerType = type.substring(7, type.length - 1);
|
|
89
|
-
return innerType.split(',').map((t) => t.trim());
|
|
90
|
-
}
|
|
91
|
-
/*
|
|
92
|
-
The Swift object type can have nested objects as the type of it's values (or maybe even keys).
|
|
93
|
-
[String: [String: Any]]
|
|
94
|
-
|
|
95
|
-
We can't use regex to find the root colon, so this is the safest way – by counting brackets.
|
|
96
|
-
*/
|
|
97
|
-
function findRootColonInDictionary(type) {
|
|
98
|
-
let colonIndex = -1;
|
|
99
|
-
let openBracketsCount = 0;
|
|
100
|
-
for (let i = 0; i < type.length; i++) {
|
|
101
|
-
if (type[i] === '[') {
|
|
102
|
-
openBracketsCount++;
|
|
103
|
-
}
|
|
104
|
-
else if (type[i] === ']') {
|
|
105
|
-
openBracketsCount--;
|
|
106
|
-
}
|
|
107
|
-
else if (type[i] === ':' && openBracketsCount === 0) {
|
|
108
|
-
colonIndex = i;
|
|
109
|
-
break;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return colonIndex;
|
|
113
|
-
}
|
|
114
|
-
function unwrapSwiftDictionary(type) {
|
|
115
|
-
const innerType = type.substring(1, type.length - 1);
|
|
116
|
-
const colonPosition = findRootColonInDictionary(innerType);
|
|
117
|
-
return {
|
|
118
|
-
key: innerType.slice(0, colonPosition).trim(),
|
|
119
|
-
value: innerType.slice(colonPosition + 1).trim(),
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
/*
|
|
123
|
-
Main function that converts a string representation of a Swift type to a TypeScript compiler API node AST.
|
|
124
|
-
We can pass those types straight to a TypeScript printer (a function that converts AST to text).
|
|
125
|
-
*/
|
|
126
|
-
function mapSwiftTypeToTsType(type) {
|
|
127
|
-
if (!type) {
|
|
128
|
-
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.VoidKeyword);
|
|
129
|
-
}
|
|
130
|
-
if (isSwiftOptional(type)) {
|
|
131
|
-
return typescript_1.default.factory.createUnionTypeNode([
|
|
132
|
-
mapSwiftTypeToTsType(maybeUnwrapSwiftOptional(type)),
|
|
133
|
-
typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.UndefinedKeyword),
|
|
134
|
-
]);
|
|
135
|
-
}
|
|
136
|
-
if (isSwiftDictionary(type)) {
|
|
137
|
-
const { key, value } = unwrapSwiftDictionary(type);
|
|
138
|
-
const keyType = mapSwiftTypeToTsType(key);
|
|
139
|
-
const valueType = mapSwiftTypeToTsType(value);
|
|
140
|
-
const indexSignature = typescript_1.default.factory.createIndexSignature(undefined, [typescript_1.default.factory.createParameterDeclaration(undefined, undefined, 'key', undefined, keyType)], valueType);
|
|
141
|
-
const typeLiteralNode = typescript_1.default.factory.createTypeLiteralNode([indexSignature]);
|
|
142
|
-
return typeLiteralNode;
|
|
143
|
-
}
|
|
144
|
-
if (isSwiftArray(type)) {
|
|
145
|
-
return typescript_1.default.factory.createArrayTypeNode(mapSwiftTypeToTsType(maybeUnwrapSwiftArray(type)));
|
|
146
|
-
}
|
|
147
|
-
// Custom handling for the Either convertible
|
|
148
|
-
if (isEither(type)) {
|
|
149
|
-
return typescript_1.default.factory.createUnionTypeNode(maybeUnwrapEither(type).map((t) => mapSwiftTypeToTsType(t)));
|
|
150
|
-
}
|
|
151
|
-
switch (type) {
|
|
152
|
-
// Our custom representation for types that we have no type hints for. Not necessairly Swift any.
|
|
153
|
-
case 'unknown':
|
|
154
|
-
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword);
|
|
155
|
-
case 'String':
|
|
156
|
-
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.StringKeyword);
|
|
157
|
-
case 'Bool':
|
|
158
|
-
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.BooleanKeyword);
|
|
159
|
-
case 'Int':
|
|
160
|
-
case 'Float':
|
|
161
|
-
case 'Double':
|
|
162
|
-
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.NumberKeyword);
|
|
163
|
-
case 'Any': // Swift Any type
|
|
164
|
-
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword);
|
|
165
|
-
default: // Custom Swift type (record) – for now mapped to a custom TS type exported at the top of the file by `getMockedTypes`.
|
|
166
|
-
return typescript_1.default.factory.createTypeReferenceNode(type);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
// Mocks require sample return values, so we generate them based on TS AST.
|
|
170
|
-
function getMockLiterals(tsReturnType) {
|
|
171
|
-
if (!tsReturnType) {
|
|
172
|
-
return undefined;
|
|
173
|
-
}
|
|
174
|
-
switch (tsReturnType.kind) {
|
|
175
|
-
case typescript_1.default.SyntaxKind.AnyKeyword:
|
|
176
|
-
case typescript_1.default.SyntaxKind.VoidKeyword:
|
|
177
|
-
return undefined;
|
|
178
|
-
case typescript_1.default.SyntaxKind.UnionType:
|
|
179
|
-
// we take the first element of our union for the mock – we know the cast is correct since we create the type ourselves
|
|
180
|
-
// the second is `undefined` for optionals.
|
|
181
|
-
return getMockLiterals(tsReturnType.types[0]);
|
|
182
|
-
case typescript_1.default.SyntaxKind.StringKeyword:
|
|
183
|
-
return typescript_1.default.factory.createStringLiteral('');
|
|
184
|
-
case typescript_1.default.SyntaxKind.BooleanKeyword:
|
|
185
|
-
return typescript_1.default.factory.createFalse();
|
|
186
|
-
case typescript_1.default.SyntaxKind.NumberKeyword:
|
|
187
|
-
return typescript_1.default.factory.createNumericLiteral('0');
|
|
188
|
-
case typescript_1.default.SyntaxKind.ArrayType:
|
|
189
|
-
return typescript_1.default.factory.createArrayLiteralExpression();
|
|
190
|
-
case typescript_1.default.SyntaxKind.TypeLiteral:
|
|
191
|
-
// handles a dictionary, could be improved by creating an object fitting the schema instead of an empty one
|
|
192
|
-
return typescript_1.default.factory.createObjectLiteralExpression([], false);
|
|
193
|
-
}
|
|
194
|
-
return undefined;
|
|
195
|
-
}
|
|
196
|
-
function wrapWithAsync(tsType) {
|
|
197
|
-
return typescript_1.default.factory.createTypeReferenceNode('Promise', [tsType]);
|
|
198
|
-
}
|
|
199
|
-
function maybeWrapWithReturnStatement(tsType) {
|
|
200
|
-
if (tsType.kind === typescript_1.default.SyntaxKind.AnyKeyword || tsType.kind === typescript_1.default.SyntaxKind.VoidKeyword) {
|
|
201
|
-
return [];
|
|
202
|
-
}
|
|
203
|
-
if (tsType.kind === typescript_1.default.SyntaxKind.TypeReference) {
|
|
204
|
-
// A fallback – we print a comment that these mocks are not fitting the custom type. Could be improved by expanding a set of default mocks.
|
|
205
|
-
return [
|
|
206
|
-
typescript_1.default.addSyntheticTrailingComment(typescript_1.default.factory.createReturnStatement(typescript_1.default.factory.createNull()), typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` TODO: Replace with mock for value of type ${tsType?.typeName?.escapedText ?? ''}.`),
|
|
207
|
-
];
|
|
208
|
-
}
|
|
209
|
-
return [typescript_1.default.factory.createReturnStatement(getMockLiterals(tsType))];
|
|
210
|
-
}
|
|
211
|
-
/*
|
|
212
|
-
We iterate over a list of functions and we create TS AST for each of them.
|
|
213
|
-
*/
|
|
214
|
-
function getMockedFunctions(functions, { async = false, classMethod = false } = {}) {
|
|
215
|
-
return functions.map((fnStructure) => {
|
|
216
|
-
const name = typescript_1.default.factory.createIdentifier(fnStructure.name);
|
|
217
|
-
const returnType = mapSwiftTypeToTsType(fnStructure.types?.returnType);
|
|
218
|
-
const parameters = fnStructure?.types?.parameters.map((p) => typescript_1.default.factory.createParameterDeclaration(undefined, undefined, p.name ?? '_', undefined, mapSwiftTypeToTsType(p.typename), undefined)) ?? [];
|
|
219
|
-
const returnBlock = typescript_1.default.factory.createBlock(maybeWrapWithReturnStatement(returnType), true);
|
|
220
|
-
if (classMethod) {
|
|
221
|
-
return typescript_1.default.factory.createMethodDeclaration([async ? typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.AsyncKeyword) : undefined].flatMap((f) => f ? [f] : []), undefined, name, undefined, undefined, parameters, async ? wrapWithAsync(returnType) : returnType, returnBlock);
|
|
222
|
-
}
|
|
223
|
-
const func = typescript_1.default.factory.createFunctionDeclaration([
|
|
224
|
-
typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.ExportKeyword),
|
|
225
|
-
async ? typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.AsyncKeyword) : undefined,
|
|
226
|
-
].flatMap((f) => (f ? [f] : [])), undefined, name, undefined, parameters, async ? wrapWithAsync(returnType) : returnType, returnBlock);
|
|
227
|
-
return func;
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
/*
|
|
231
|
-
We iterate over a list of constants and create TS AST for each of them.
|
|
232
|
-
Constants are exported as `export const NAME = value;`
|
|
233
|
-
*/
|
|
234
|
-
function getMockedConstants(constants) {
|
|
235
|
-
return constants.map((constant) => {
|
|
236
|
-
const name = typescript_1.default.factory.createIdentifier(constant.name);
|
|
237
|
-
const returnType = mapSwiftTypeToTsType(constant.types?.returnType ?? 'unknown');
|
|
238
|
-
const initializer = getMockLiterals(returnType) ?? typescript_1.default.factory.createNumericLiteral('0');
|
|
239
|
-
return typescript_1.default.factory.createVariableStatement([typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.ExportKeyword)], typescript_1.default.factory.createVariableDeclarationList([typescript_1.default.factory.createVariableDeclaration(name, undefined, undefined, initializer)], typescript_1.default.NodeFlags.Const));
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Collect all type references used in any of the AST types to generate type aliases
|
|
244
|
-
* e.g. type `[URL: string]?` will generate `type URL = any;`
|
|
245
|
-
*/
|
|
246
|
-
function getAllTypeReferences(node, accumulator) {
|
|
247
|
-
if (typescript_1.default.isTypeReferenceNode(node)) {
|
|
248
|
-
accumulator.push(node.typeName?.escapedText);
|
|
249
|
-
}
|
|
250
|
-
node.forEachChild((n) => getAllTypeReferences(n, accumulator));
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Iterates over types to collect the aliases.
|
|
254
|
-
*/
|
|
255
|
-
function getTypesToMock(module) {
|
|
256
|
-
const foundTypes = [];
|
|
257
|
-
Object.values(module)
|
|
258
|
-
.flatMap((t) => (Array.isArray(t) ? t.map((t2) => t2?.types) : []))
|
|
259
|
-
.forEach((types) => {
|
|
260
|
-
types?.parameters.forEach(({ typename }) => {
|
|
261
|
-
getAllTypeReferences(mapSwiftTypeToTsType(typename), foundTypes);
|
|
262
|
-
});
|
|
263
|
-
types?.returnType &&
|
|
264
|
-
getAllTypeReferences(mapSwiftTypeToTsType(types?.returnType), foundTypes);
|
|
265
|
-
});
|
|
266
|
-
return new Set(foundTypes);
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Gets a mock for a custom type.
|
|
270
|
-
*/
|
|
271
|
-
function getMockedTypes(types) {
|
|
272
|
-
return Array.from(types).map((type) => {
|
|
273
|
-
const name = typescript_1.default.factory.createIdentifier(type);
|
|
274
|
-
const typeAlias = typescript_1.default.factory.createTypeAliasDeclaration([typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.ExportKeyword)], name, undefined, typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword));
|
|
275
|
-
return typeAlias;
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
const prefix = `Automatically generated by expo-modules-test-core.
|
|
279
|
-
|
|
280
|
-
This autogenerated file provides a mock for native Expo module,
|
|
281
|
-
and works out of the box with the expo jest preset.
|
|
282
|
-
`;
|
|
283
|
-
function getPrefix() {
|
|
284
|
-
return [typescript_1.default.factory.createJSDocComment(prefix)];
|
|
285
|
-
}
|
|
286
|
-
function generatePropTypesForDefinition(definition) {
|
|
287
|
-
return typescript_1.default.factory.createTypeAliasDeclaration([typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.ExportKeyword)], 'ViewProps', undefined, typescript_1.default.factory.createTypeLiteralNode([
|
|
288
|
-
...definition.props.map((p) => {
|
|
289
|
-
const propType = mapSwiftTypeToTsType(p.types.parameters[0]?.typename ?? '');
|
|
290
|
-
return typescript_1.default.factory.createPropertySignature(undefined, p.name, undefined, propType);
|
|
291
|
-
}),
|
|
292
|
-
...definition.events.map((e) => {
|
|
293
|
-
const eventType = typescript_1.default.factory.createFunctionTypeNode(undefined, [
|
|
294
|
-
typescript_1.default.factory.createParameterDeclaration(undefined, undefined, 'event', undefined, typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword)),
|
|
295
|
-
], typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.VoidKeyword));
|
|
296
|
-
return typescript_1.default.factory.createPropertySignature(undefined, e.name, undefined, eventType);
|
|
297
|
-
}),
|
|
298
|
-
]));
|
|
299
|
-
}
|
|
300
|
-
/*
|
|
301
|
-
Generate a mock for view props and functions.
|
|
302
|
-
*/
|
|
303
|
-
function getMockedViews(viewDefinitions) {
|
|
304
|
-
return viewDefinitions.flatMap((definition) => {
|
|
305
|
-
if (!definition) {
|
|
306
|
-
return [];
|
|
307
|
-
}
|
|
308
|
-
const propsType = generatePropTypesForDefinition(definition);
|
|
309
|
-
const props = typescript_1.default.factory.createParameterDeclaration(undefined, undefined, 'props', undefined, typescript_1.default.factory.createTypeReferenceNode('ViewProps', undefined), undefined);
|
|
310
|
-
const viewFunction = typescript_1.default.factory.createFunctionDeclaration([typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.ExportKeyword)], undefined,
|
|
311
|
-
// TODO: Handle this better once requireNativeViewManager accepts view name or a different solution for multiple views is built.
|
|
312
|
-
viewDefinitions.length === 1 ? 'View' : definition.name, undefined, [props], undefined, typescript_1.default.factory.createBlock([]));
|
|
313
|
-
return [propsType, viewFunction];
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
function getMockedClass(def) {
|
|
317
|
-
const classDecl = typescript_1.default.factory.createClassDeclaration([typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.ExportKeyword)], typescript_1.default.factory.createIdentifier(def.name), undefined, undefined, [
|
|
318
|
-
...getMockedFunctions(def.functions, { classMethod: true }),
|
|
319
|
-
...getMockedFunctions(def.asyncFunctions, { async: true, classMethod: true }),
|
|
320
|
-
]);
|
|
321
|
-
return classDecl;
|
|
322
|
-
}
|
|
323
|
-
function getMockedClasses(def) {
|
|
324
|
-
return def.map((d) => getMockedClass(d));
|
|
325
|
-
}
|
|
326
|
-
const newlineIdentifier = typescript_1.default.factory.createIdentifier('\n\n');
|
|
327
|
-
function separateWithNewlines(arr) {
|
|
328
|
-
return [arr, newlineIdentifier];
|
|
329
|
-
}
|
|
330
|
-
function omitFromSet(set, toOmit) {
|
|
331
|
-
const newSet = new Set(set);
|
|
332
|
-
toOmit.forEach((item) => {
|
|
333
|
-
if (item) {
|
|
334
|
-
newSet.delete(item);
|
|
335
|
-
}
|
|
336
|
-
});
|
|
337
|
-
return newSet;
|
|
338
|
-
}
|
|
339
|
-
function getMockForModule(module, includeTypes) {
|
|
340
|
-
return []
|
|
341
|
-
.concat(getPrefix(), newlineIdentifier, includeTypes
|
|
342
|
-
? getMockedTypes(omitFromSet(new Set([
|
|
343
|
-
...getTypesToMock(module),
|
|
344
|
-
...new Set(...module.views.map((v) => getTypesToMock(v))),
|
|
345
|
-
...new Set(...module.classes.map((c) => getTypesToMock(c))),
|
|
346
|
-
]),
|
|
347
|
-
// Ignore all types that are actually native classes
|
|
348
|
-
[
|
|
349
|
-
module.name,
|
|
350
|
-
...module.views.map((c) => c.name),
|
|
351
|
-
...module.classes.map((c) => c.name),
|
|
352
|
-
]))
|
|
353
|
-
: [], newlineIdentifier, getMockedConstants(module.constants), newlineIdentifier, getMockedFunctions(module.functions), getMockedFunctions(module.asyncFunctions, { async: true }), newlineIdentifier, getMockedViews(module.views), getMockedClasses(module.classes))
|
|
354
|
-
.flatMap(separateWithNewlines);
|
|
355
|
-
}
|
|
356
|
-
async function prettifyCode(text, parser = 'babel') {
|
|
357
|
-
return await prettier.format(text, {
|
|
358
|
-
parser,
|
|
359
|
-
tabWidth: 2,
|
|
360
|
-
printWidth: 100,
|
|
361
|
-
trailingComma: 'none',
|
|
362
|
-
singleQuote: true,
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
async function generateMocks(modules, outputLanguage = 'javascript') {
|
|
366
|
-
const printer = typescript_1.default.createPrinter({ newLine: typescript_1.default.NewLineKind.LineFeed });
|
|
367
|
-
for (const m of modules) {
|
|
368
|
-
const filename = m.name + (outputLanguage === 'javascript' ? '.js' : '.ts');
|
|
369
|
-
const resultFile = typescript_1.default.createSourceFile(filename, '', typescript_1.default.ScriptTarget.Latest, false, typescript_1.default.ScriptKind.TSX);
|
|
370
|
-
fs_1.default.mkdirSync(path_1.default.join(directoryPath, 'mocks'), { recursive: true });
|
|
371
|
-
const filePath = path_1.default.join(directoryPath, 'mocks', filename);
|
|
372
|
-
// get ts nodearray from getMockForModule(m) array
|
|
373
|
-
const mock = typescript_1.default.factory.createNodeArray(getMockForModule(m, outputLanguage === 'typescript'));
|
|
374
|
-
const printedTs = printer.printList(typescript_1.default.ListFormat.MultiLine + typescript_1.default.ListFormat.PreserveLines, mock, resultFile);
|
|
375
|
-
if (outputLanguage === 'javascript') {
|
|
376
|
-
const compiledJs = typescript_1.default.transpileModule(printedTs, {
|
|
377
|
-
compilerOptions: {
|
|
378
|
-
module: typescript_1.default.ModuleKind.ESNext,
|
|
379
|
-
target: typescript_1.default.ScriptTarget.ESNext,
|
|
380
|
-
},
|
|
381
|
-
}).outputText;
|
|
382
|
-
const prettifiedJs = await prettifyCode(compiledJs);
|
|
383
|
-
fs_1.default.writeFileSync(filePath, prettifiedJs);
|
|
384
|
-
}
|
|
385
|
-
else {
|
|
386
|
-
const prettifiedTs = await prettifyCode(printedTs, 'typescript');
|
|
387
|
-
fs_1.default.writeFileSync(filePath, prettifiedTs);
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
//# sourceMappingURL=mockgen.js.map
|
package/build/mockgen.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mockgen.js","sourceRoot":"","sources":["../src/mockgen.ts"],"names":[],"mappings":";AACA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoeb,sCAuCC;AAzgBD,4CAAoB;AACpB,gDAAwB;AACxB,mDAAqC;AACrC,4DAA4B;AAU5B,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAEpC;;;;;EAKE;AAEF,SAAS,YAAY,CAAC,IAAY;IAChC,sHAAsH;IACtH,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACpD,CAAC;AACD,SAAS,qBAAqB,CAAC,IAAY;IACzC,MAAM,OAAO,GAAG,YAAY,CAAC,IAAI,CAA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U,CAAC,GAAG,CAClB,CAAC;QACF,YAAE,CAAC,SAAS,CAAC,cAAI,CAAC,IAAI,CAAC,aAAa,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,aAAa,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC7D,kDAAkD;QAClD,MAAM,IAAI,GAAG,oBAAE,CAAC,OAAO,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC,EAAE,cAAc,KAAK,YAAY,CAAC,CAAC,CAAC;QAC9F,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CACjC,oBAAE,CAAC,UAAU,CAAC,SAAS,GAAG,oBAAE,CAAC,UAAU,CAAC,aAAa,EACrD,IAAI,EACJ,UAAU,CACX,CAAC;QAEF,IAAI,cAAc,KAAK,YAAY,EAAE,CAAC;YACpC,MAAM,UAAU,GAAG,oBAAE,CAAC,eAAe,CAAC,SAAS,EAAE;gBAC/C,eAAe,EAAE;oBACf,MAAM,EAAE,oBAAE,CAAC,UAAU,CAAC,MAAM;oBAC5B,MAAM,EAAE,oBAAE,CAAC,YAAY,CAAC,MAAM;iBAC/B;aACF,CAAC,CAAC,UAAU,CAAC;YACd,MAAM,YAAY,GAAG,MAAM,YAAY,CAAC,UAAU,CAAC,CAAC;YACpD,YAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;QAC3C,CAAC;aAAM,CAAC;YACN,MAAM,YAAY,GAAG,MAAM,YAAY,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;YACjE,YAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["#!/usr/bin/env node\n'use strict';\n\nimport fs from 'fs';\nimport path from 'path';\nimport * as prettier from 'prettier';\nimport ts from 'typescript';\n\nimport {\n Closure,\n ClosureTypes,\n Constant,\n OutputModuleDefinition,\n OutputNestedClassDefinition,\n} from './types';\n\nconst directoryPath = process.cwd();\n\n/*\nWe receive types from SourceKitten and `getStructure` like so (examples):\n[AcceptedTypes]?, UIColor?, [String: Any]\n\nWe need to parse them first to TS nodes in `mapSwiftTypeToTsType` with the following helper functions.\n*/\n\nfunction isSwiftArray(type: string) {\n // This can also be an object, but we check that first, so if it's not an object and is wrapped with [] it's an array.\n return type.startsWith('[') && type.endsWith(']');\n}\nfunction maybeUnwrapSwiftArray(type: string) {\n const isArray = isSwiftArray(type);\n if (!isArray) {\n return type;\n }\n const innerType = type.substring(1, type.length - 1);\n return innerType;\n}\n\nfunction isSwiftOptional(type: string) {\n return type.endsWith('?');\n}\nfunction maybeUnwrapSwiftOptional(type: string) {\n const isOptional = isSwiftOptional(type);\n if (!isOptional) {\n return type;\n }\n const innerType = type.substring(0, type.length - 1);\n return innerType;\n}\n\nfunction isSwiftDictionary(type: string) {\n return (\n type.startsWith('[') &&\n type.endsWith(']') &&\n findRootColonInDictionary(type.substring(1, type.length - 1)) >= 0\n );\n}\n\nfunction isEither(type: string) {\n return type.startsWith('Either<');\n}\n// \"Either<TypeOne, TypeTwo>\" -> [\"TypeOne\", \"TypeTwo\"]\nfunction maybeUnwrapEither(type: string): string[] {\n if (!isEither(type)) {\n return [type];\n }\n const innerType = type.substring(7, type.length - 1);\n return innerType.split(',').map((t) => t.trim());\n}\n\n/*\nThe Swift object type can have nested objects as the type of it's values (or maybe even keys).\n[String: [String: Any]]\n\nWe can't use regex to find the root colon, so this is the safest way – by counting brackets.\n*/\nfunction findRootColonInDictionary(type: string) {\n let colonIndex = -1;\n let openBracketsCount = 0;\n for (let i = 0; i < type.length; i++) {\n if (type[i] === '[') {\n openBracketsCount++;\n } else if (type[i] === ']') {\n openBracketsCount--;\n } else if (type[i] === ':' && openBracketsCount === 0) {\n colonIndex = i;\n break;\n }\n }\n return colonIndex;\n}\nfunction unwrapSwiftDictionary(type: string) {\n const innerType = type.substring(1, type.length - 1);\n const colonPosition = findRootColonInDictionary(innerType);\n return {\n key: innerType.slice(0, colonPosition).trim(),\n value: innerType.slice(colonPosition + 1).trim(),\n };\n}\n\ntype TSNode =\n | ts.UnionTypeNode\n | ts.KeywordTypeNode\n | ts.TypeReferenceNode\n | ts.ArrayTypeNode\n | ts.OptionalTypeNode\n | ts.TypeLiteralNode;\n\n/*\nMain function that converts a string representation of a Swift type to a TypeScript compiler API node AST.\nWe can pass those types straight to a TypeScript printer (a function that converts AST to text).\n*/\nfunction mapSwiftTypeToTsType(type: string): TSNode {\n if (!type) {\n return ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword);\n }\n if (isSwiftOptional(type)) {\n return ts.factory.createUnionTypeNode([\n mapSwiftTypeToTsType(maybeUnwrapSwiftOptional(type)),\n ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),\n ]);\n }\n if (isSwiftDictionary(type)) {\n const { key, value } = unwrapSwiftDictionary(type);\n const keyType = mapSwiftTypeToTsType(key);\n const valueType = mapSwiftTypeToTsType(value);\n\n const indexSignature = ts.factory.createIndexSignature(\n undefined,\n [ts.factory.createParameterDeclaration(undefined, undefined, 'key', undefined, keyType)],\n valueType\n );\n\n const typeLiteralNode = ts.factory.createTypeLiteralNode([indexSignature]);\n return typeLiteralNode;\n }\n if (isSwiftArray(type)) {\n return ts.factory.createArrayTypeNode(mapSwiftTypeToTsType(maybeUnwrapSwiftArray(type)));\n }\n // Custom handling for the Either convertible\n if (isEither(type)) {\n return ts.factory.createUnionTypeNode(\n maybeUnwrapEither(type).map((t) => mapSwiftTypeToTsType(t))\n );\n }\n\n switch (type) {\n // Our custom representation for types that we have no type hints for. Not necessairly Swift any.\n case 'unknown':\n return ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);\n case 'String':\n return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);\n case 'Bool':\n return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);\n case 'Int':\n case 'Float':\n case 'Double':\n return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);\n case 'Any': // Swift Any type\n return ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);\n default: // Custom Swift type (record) – for now mapped to a custom TS type exported at the top of the file by `getMockedTypes`.\n return ts.factory.createTypeReferenceNode(type);\n }\n}\n\n// Mocks require sample return values, so we generate them based on TS AST.\nfunction getMockLiterals(tsReturnType: TSNode) {\n if (!tsReturnType) {\n return undefined;\n }\n switch (tsReturnType.kind) {\n case ts.SyntaxKind.AnyKeyword:\n case ts.SyntaxKind.VoidKeyword:\n return undefined;\n case ts.SyntaxKind.UnionType:\n // we take the first element of our union for the mock – we know the cast is correct since we create the type ourselves\n // the second is `undefined` for optionals.\n return getMockLiterals(tsReturnType.types[0] as TSNode);\n case ts.SyntaxKind.StringKeyword:\n return ts.factory.createStringLiteral('');\n case ts.SyntaxKind.BooleanKeyword:\n return ts.factory.createFalse();\n case ts.SyntaxKind.NumberKeyword:\n return ts.factory.createNumericLiteral('0');\n case ts.SyntaxKind.ArrayType:\n return ts.factory.createArrayLiteralExpression();\n case ts.SyntaxKind.TypeLiteral:\n // handles a dictionary, could be improved by creating an object fitting the schema instead of an empty one\n return ts.factory.createObjectLiteralExpression([], false);\n }\n return undefined;\n}\n\nfunction wrapWithAsync(tsType: ts.TypeNode) {\n return ts.factory.createTypeReferenceNode('Promise', [tsType]);\n}\n\nfunction maybeWrapWithReturnStatement(tsType: TSNode) {\n if (tsType.kind === ts.SyntaxKind.AnyKeyword || tsType.kind === ts.SyntaxKind.VoidKeyword) {\n return [];\n }\n if (tsType.kind === ts.SyntaxKind.TypeReference) {\n // A fallback – we print a comment that these mocks are not fitting the custom type. Could be improved by expanding a set of default mocks.\n return [\n ts.addSyntheticTrailingComment(\n ts.factory.createReturnStatement(ts.factory.createNull()),\n ts.SyntaxKind.SingleLineCommentTrivia,\n ` TODO: Replace with mock for value of type ${\n ((tsType as any)?.typeName as any)?.escapedText ?? ''\n }.`\n ),\n ];\n }\n return [ts.factory.createReturnStatement(getMockLiterals(tsType))];\n}\n\n/*\nWe iterate over a list of functions and we create TS AST for each of them.\n*/\nfunction getMockedFunctions(functions: Closure[], { async = false, classMethod = false } = {}) {\n return functions.map((fnStructure) => {\n const name = ts.factory.createIdentifier(fnStructure.name);\n const returnType = mapSwiftTypeToTsType(fnStructure.types?.returnType);\n const parameters =\n fnStructure?.types?.parameters.map((p) =>\n ts.factory.createParameterDeclaration(\n undefined,\n undefined,\n p.name ?? '_',\n undefined,\n mapSwiftTypeToTsType(p.typename),\n undefined\n )\n ) ?? [];\n const returnBlock = ts.factory.createBlock(maybeWrapWithReturnStatement(returnType), true);\n\n if (classMethod) {\n return ts.factory.createMethodDeclaration(\n [async ? ts.factory.createToken(ts.SyntaxKind.AsyncKeyword) : undefined].flatMap((f) =>\n f ? [f] : []\n ),\n undefined,\n name,\n undefined,\n undefined,\n parameters,\n async ? wrapWithAsync(returnType) : returnType,\n returnBlock\n );\n }\n const func = ts.factory.createFunctionDeclaration(\n [\n ts.factory.createToken(ts.SyntaxKind.ExportKeyword),\n async ? ts.factory.createToken(ts.SyntaxKind.AsyncKeyword) : undefined,\n ].flatMap((f) => (f ? [f] : [])),\n undefined,\n name,\n undefined,\n parameters,\n async ? wrapWithAsync(returnType) : returnType,\n returnBlock\n );\n return func;\n });\n}\n\n/*\nWe iterate over a list of constants and create TS AST for each of them.\nConstants are exported as `export const NAME = value;`\n*/\nfunction getMockedConstants(constants: Constant[]) {\n return constants.map((constant) => {\n const name = ts.factory.createIdentifier(constant.name);\n const returnType = mapSwiftTypeToTsType(constant.types?.returnType ?? 'unknown');\n const initializer = getMockLiterals(returnType) ?? ts.factory.createNumericLiteral('0');\n\n return ts.factory.createVariableStatement(\n [ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],\n ts.factory.createVariableDeclarationList(\n [ts.factory.createVariableDeclaration(name, undefined, undefined, initializer)],\n ts.NodeFlags.Const\n )\n );\n });\n}\n\n/**\n * Collect all type references used in any of the AST types to generate type aliases\n * e.g. type `[URL: string]?` will generate `type URL = any;`\n */\nfunction getAllTypeReferences(node: ts.Node, accumulator: string[]) {\n if (ts.isTypeReferenceNode(node)) {\n accumulator.push((node.typeName as any)?.escapedText);\n }\n node.forEachChild((n) => getAllTypeReferences(n, accumulator));\n}\n\n/**\n * Iterates over types to collect the aliases.\n */\nfunction getTypesToMock(module: OutputModuleDefinition | OutputNestedClassDefinition) {\n const foundTypes: string[] = [];\n\n Object.values(module)\n .flatMap((t) => (Array.isArray(t) ? t.map((t2) => (t2 as Closure)?.types) : []))\n .forEach((types: ClosureTypes | null) => {\n types?.parameters.forEach(({ typename }) => {\n getAllTypeReferences(mapSwiftTypeToTsType(typename), foundTypes);\n });\n types?.returnType &&\n getAllTypeReferences(mapSwiftTypeToTsType(types?.returnType), foundTypes);\n });\n return new Set(foundTypes);\n}\n\n/**\n * Gets a mock for a custom type.\n */\nfunction getMockedTypes(types: Set<string>) {\n return Array.from(types).map((type) => {\n const name = ts.factory.createIdentifier(type);\n const typeAlias = ts.factory.createTypeAliasDeclaration(\n [ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],\n name,\n undefined,\n ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)\n );\n return typeAlias;\n });\n}\n\nconst prefix = `Automatically generated by expo-modules-test-core.\n\nThis autogenerated file provides a mock for native Expo module,\nand works out of the box with the expo jest preset.\n`;\nfunction getPrefix() {\n return [ts.factory.createJSDocComment(prefix)];\n}\n\nfunction generatePropTypesForDefinition(definition: OutputNestedClassDefinition) {\n return ts.factory.createTypeAliasDeclaration(\n [ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],\n 'ViewProps',\n undefined,\n ts.factory.createTypeLiteralNode([\n ...definition.props.map((p) => {\n const propType = mapSwiftTypeToTsType(p.types.parameters[0]?.typename ?? '');\n return ts.factory.createPropertySignature(undefined, p.name, undefined, propType);\n }),\n ...definition.events.map((e) => {\n const eventType = ts.factory.createFunctionTypeNode(\n undefined,\n [\n ts.factory.createParameterDeclaration(\n undefined,\n undefined,\n 'event',\n undefined,\n ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)\n ),\n ],\n ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)\n );\n return ts.factory.createPropertySignature(undefined, e.name, undefined, eventType);\n }),\n ])\n );\n}\n/*\nGenerate a mock for view props and functions.\n*/\nfunction getMockedViews(viewDefinitions: OutputNestedClassDefinition[]) {\n return viewDefinitions.flatMap((definition) => {\n if (!definition) {\n return [];\n }\n const propsType = generatePropTypesForDefinition(definition);\n const props = ts.factory.createParameterDeclaration(\n undefined,\n undefined,\n 'props',\n undefined,\n ts.factory.createTypeReferenceNode('ViewProps', undefined),\n undefined\n );\n const viewFunction = ts.factory.createFunctionDeclaration(\n [ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],\n undefined,\n // TODO: Handle this better once requireNativeViewManager accepts view name or a different solution for multiple views is built.\n viewDefinitions.length === 1 ? 'View' : definition.name,\n undefined,\n [props],\n undefined,\n ts.factory.createBlock([])\n );\n return [propsType, viewFunction];\n });\n}\n\nfunction getMockedClass(def: OutputNestedClassDefinition) {\n const classDecl = ts.factory.createClassDeclaration(\n [ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],\n ts.factory.createIdentifier(def.name),\n undefined,\n undefined,\n [\n ...getMockedFunctions(def.functions, { classMethod: true }),\n ...getMockedFunctions(def.asyncFunctions, { async: true, classMethod: true }),\n ] as ts.MethodDeclaration[]\n );\n return classDecl;\n}\n\nfunction getMockedClasses(def: OutputNestedClassDefinition[]) {\n return def.map((d) => getMockedClass(d));\n}\n\nconst newlineIdentifier = ts.factory.createIdentifier('\\n\\n') as any;\nfunction separateWithNewlines<T>(arr: T) {\n return [arr, newlineIdentifier];\n}\n\nfunction omitFromSet(set: Set<string>, toOmit: (string | undefined)[]) {\n const newSet = new Set(set);\n toOmit.forEach((item) => {\n if (item) {\n newSet.delete(item);\n }\n });\n return newSet;\n}\n\nfunction getMockForModule(module: OutputModuleDefinition, includeTypes: boolean) {\n return (\n [] as (\n | ts.TypeAliasDeclaration\n | ts.FunctionDeclaration\n | ts.JSDoc\n | ts.ClassDeclaration\n | ts.VariableStatement\n )[]\n )\n .concat(\n getPrefix(),\n newlineIdentifier,\n includeTypes\n ? getMockedTypes(\n omitFromSet(\n new Set([\n ...getTypesToMock(module),\n ...new Set(...module.views.map((v) => getTypesToMock(v))),\n ...new Set(...module.classes.map((c) => getTypesToMock(c))),\n ]),\n // Ignore all types that are actually native classes\n [\n module.name,\n ...module.views.map((c) => c.name),\n ...module.classes.map((c) => c.name),\n ]\n )\n )\n : [],\n newlineIdentifier,\n getMockedConstants(module.constants),\n newlineIdentifier,\n getMockedFunctions(module.functions) as ts.FunctionDeclaration[],\n getMockedFunctions(module.asyncFunctions, { async: true }) as ts.FunctionDeclaration[],\n newlineIdentifier,\n getMockedViews(module.views),\n getMockedClasses(module.classes)\n )\n .flatMap(separateWithNewlines);\n}\n\nasync function prettifyCode(text: string, parser: 'babel' | 'typescript' = 'babel') {\n return await prettier.format(text, {\n parser,\n tabWidth: 2,\n printWidth: 100,\n trailingComma: 'none',\n singleQuote: true,\n });\n}\n\nexport async function generateMocks(\n modules: OutputModuleDefinition[],\n outputLanguage: 'javascript' | 'typescript' = 'javascript'\n) {\n const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });\n\n for (const m of modules) {\n const filename = m.name + (outputLanguage === 'javascript' ? '.js' : '.ts');\n const resultFile = ts.createSourceFile(\n filename,\n '',\n ts.ScriptTarget.Latest,\n false,\n ts.ScriptKind.TSX\n );\n fs.mkdirSync(path.join(directoryPath, 'mocks'), { recursive: true });\n const filePath = path.join(directoryPath, 'mocks', filename);\n // get ts nodearray from getMockForModule(m) array\n const mock = ts.factory.createNodeArray(getMockForModule(m, outputLanguage === 'typescript'));\n const printedTs = printer.printList(\n ts.ListFormat.MultiLine + ts.ListFormat.PreserveLines,\n mock,\n resultFile\n );\n\n if (outputLanguage === 'javascript') {\n const compiledJs = ts.transpileModule(printedTs, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ESNext,\n },\n }).outputText;\n const prettifiedJs = await prettifyCode(compiledJs);\n fs.writeFileSync(filePath, prettifiedJs);\n } else {\n const prettifiedTs = await prettifyCode(printedTs, 'typescript');\n fs.writeFileSync(filePath, prettifiedTs);\n }\n }\n}\n"]}
|
package/build/types.d.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
export type FileType = {
|
|
2
|
-
path: string;
|
|
3
|
-
content: string;
|
|
4
|
-
};
|
|
5
|
-
export type Structure = {
|
|
6
|
-
'key.substructure': Structure[];
|
|
7
|
-
'key.typename': string;
|
|
8
|
-
'key.name': string;
|
|
9
|
-
'key.kind': string;
|
|
10
|
-
'key.offset': number;
|
|
11
|
-
'key.length': number;
|
|
12
|
-
};
|
|
13
|
-
export type CursorInfoOutput = {
|
|
14
|
-
'key.fully_annotated_decl': string;
|
|
15
|
-
'key.annotated_decl': string;
|
|
16
|
-
};
|
|
17
|
-
export type FullyAnnotatedDecl = {
|
|
18
|
-
'decl.function.free': {
|
|
19
|
-
'decl.var.parameter': {
|
|
20
|
-
'decl.var.parameter.argument_label': string;
|
|
21
|
-
'decl.var.parameter.type': string;
|
|
22
|
-
}[];
|
|
23
|
-
'decl.function.returntype': string;
|
|
24
|
-
};
|
|
25
|
-
};
|
|
26
|
-
export type ClosureTypes = {
|
|
27
|
-
parameters: {
|
|
28
|
-
name: any;
|
|
29
|
-
typename: any;
|
|
30
|
-
}[];
|
|
31
|
-
returnType: any;
|
|
32
|
-
};
|
|
33
|
-
export type Closure = {
|
|
34
|
-
name: string;
|
|
35
|
-
types: ClosureTypes | null;
|
|
36
|
-
};
|
|
37
|
-
export type Prop = {
|
|
38
|
-
name: string;
|
|
39
|
-
types: Omit<ClosureTypes, 'returnType'>;
|
|
40
|
-
};
|
|
41
|
-
export type Constant = {
|
|
42
|
-
name: string;
|
|
43
|
-
types: ClosureTypes | null;
|
|
44
|
-
};
|
|
45
|
-
export type OutputModuleDefinition = {
|
|
46
|
-
name: string;
|
|
47
|
-
views: OutputNestedClassDefinition[];
|
|
48
|
-
classes: OutputNestedClassDefinition[];
|
|
49
|
-
events: {
|
|
50
|
-
name: string;
|
|
51
|
-
}[];
|
|
52
|
-
constants: Constant[];
|
|
53
|
-
} & Record<'asyncFunctions' | 'functions' | 'properties', Closure[]> & Record<'props', Prop[]>;
|
|
54
|
-
export type OutputNestedClassDefinition = Omit<OutputModuleDefinition, 'views' | 'classes'>;
|
|
55
|
-
//# sourceMappingURL=types.d.ts.map
|
package/build/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,kBAAkB,EAAE,SAAS,EAAE,CAAC;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,0BAA0B,EAAE,MAAM,CAAC;IACnC,oBAAoB,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,oBAAoB,EAAE;QACpB,oBAAoB,EAAE;YACpB,mCAAmC,EAAE,MAAM,CAAC;YAC5C,yBAAyB,EAAE,MAAM,CAAC;SACnC,EAAE,CAAC;QACJ,0BAA0B,EAAE,MAAM,CAAC;KACpC,CAAC;CACH,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,UAAU,EAAE;QACV,IAAI,EAAE,GAAG,CAAC;QACV,QAAQ,EAAE,GAAG,CAAC;KACf,EAAE,CAAC;IACJ,UAAU,EAAE,GAAG,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,IAAI,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;CACzC,CAAC;AAEF,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,2BAA2B,EAAE,CAAC;IACrC,OAAO,EAAE,2BAA2B,EAAE,CAAC;IACvC,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;KACd,EAAE,CAAC;IACJ,SAAS,EAAE,QAAQ,EAAE,CAAC;CACvB,GAAG,MAAM,CAAC,gBAAgB,GAAG,WAAW,GAAG,YAAY,EAAE,OAAO,EAAE,CAAC,GAClE,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AAG1B,MAAM,MAAM,2BAA2B,GAAG,IAAI,CAAC,sBAAsB,EAAE,OAAO,GAAG,SAAS,CAAC,CAAC"}
|
package/build/types.js
DELETED
package/build/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["export type FileType = {\n path: string;\n content: string;\n};\n\nexport type Structure = {\n 'key.substructure': Structure[];\n 'key.typename': string;\n 'key.name': string;\n 'key.kind': string;\n 'key.offset': number;\n 'key.length': number;\n};\n\nexport type CursorInfoOutput = {\n 'key.fully_annotated_decl': string;\n 'key.annotated_decl': string;\n};\n\nexport type FullyAnnotatedDecl = {\n 'decl.function.free': {\n 'decl.var.parameter': {\n 'decl.var.parameter.argument_label': string;\n 'decl.var.parameter.type': string;\n }[];\n 'decl.function.returntype': string;\n };\n};\n\nexport type ClosureTypes = {\n parameters: {\n name: any;\n typename: any;\n }[];\n returnType: any;\n};\n\nexport type Closure = {\n name: string;\n types: ClosureTypes | null;\n};\n\nexport type Prop = {\n name: string;\n types: Omit<ClosureTypes, 'returnType'>;\n};\n\nexport type Constant = {\n name: string;\n types: ClosureTypes | null;\n};\n\nexport type OutputModuleDefinition = {\n name: string;\n views: OutputNestedClassDefinition[];\n classes: OutputNestedClassDefinition[];\n events: {\n name: string;\n }[];\n constants: Constant[];\n} & Record<'asyncFunctions' | 'functions' | 'properties', Closure[]> &\n Record<'props', Prop[]>;\n\n// views and classes are a very similar structure, same as module but without more nesting levels\nexport type OutputNestedClassDefinition = Omit<OutputModuleDefinition, 'views' | 'classes'>;\n"]}
|