@cocojs/compiler 0.1.0-beta.202601082201 → 0.1.0-beta.202601082202

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.esm.js +513 -0
  2. package/package.json +2 -1
@@ -0,0 +1,513 @@
1
+ import * as ts from 'typescript';
2
+
3
+ function _arrayLikeToArray(r, a) {
4
+ (null == a || a > r.length) && (a = r.length);
5
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
6
+ return n;
7
+ }
8
+ function _arrayWithoutHoles(r) {
9
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
10
+ }
11
+ function _createForOfIteratorHelper(r, e) {
12
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
13
+ if (!t) {
14
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
15
+ t && (r = t);
16
+ var n = 0,
17
+ F = function () {};
18
+ return {
19
+ s: F,
20
+ n: function () {
21
+ return n >= r.length ? {
22
+ done: true
23
+ } : {
24
+ done: false,
25
+ value: r[n++]
26
+ };
27
+ },
28
+ e: function (r) {
29
+ throw r;
30
+ },
31
+ f: F
32
+ };
33
+ }
34
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
35
+ }
36
+ var o,
37
+ a = true,
38
+ u = false;
39
+ return {
40
+ s: function () {
41
+ t = t.call(r);
42
+ },
43
+ n: function () {
44
+ var r = t.next();
45
+ return a = r.done, r;
46
+ },
47
+ e: function (r) {
48
+ u = true, o = r;
49
+ },
50
+ f: function () {
51
+ try {
52
+ a || null == t.return || t.return();
53
+ } finally {
54
+ if (u) throw o;
55
+ }
56
+ }
57
+ };
58
+ }
59
+ function _defineProperty(e, r, t) {
60
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
61
+ value: t,
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true
65
+ }) : e[r] = t, e;
66
+ }
67
+ function _iterableToArray(r) {
68
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
69
+ }
70
+ function _nonIterableSpread() {
71
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
72
+ }
73
+ function ownKeys(e, r) {
74
+ var t = Object.keys(e);
75
+ if (Object.getOwnPropertySymbols) {
76
+ var o = Object.getOwnPropertySymbols(e);
77
+ r && (o = o.filter(function (r) {
78
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
79
+ })), t.push.apply(t, o);
80
+ }
81
+ return t;
82
+ }
83
+ function _objectSpread2(e) {
84
+ for (var r = 1; r < arguments.length; r++) {
85
+ var t = null != arguments[r] ? arguments[r] : {};
86
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
87
+ _defineProperty(e, r, t[r]);
88
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
89
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
90
+ });
91
+ }
92
+ return e;
93
+ }
94
+ function _toConsumableArray(r) {
95
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
96
+ }
97
+ function _toPrimitive(t, r) {
98
+ if ("object" != typeof t || !t) return t;
99
+ var e = t[Symbol.toPrimitive];
100
+ if (void 0 !== e) {
101
+ var i = e.call(t, r);
102
+ if ("object" != typeof i) return i;
103
+ throw new TypeError("@@toPrimitive must return a primitive value.");
104
+ }
105
+ return ("string" === r ? String : Number)(t);
106
+ }
107
+ function _toPropertyKey(t) {
108
+ var i = _toPrimitive(t, "string");
109
+ return "symbol" == typeof i ? i : i + "";
110
+ }
111
+ function _unsupportedIterableToArray(r, a) {
112
+ if (r) {
113
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
114
+ var t = {}.toString.call(r).slice(8, -1);
115
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
116
+ }
117
+ }
118
+
119
+ var wrapperClassName = ['String', 'Number', 'Boolean'];
120
+ var innerClassName = ['Object', 'Symbol', 'Array', 'Map', 'Set', 'Function'];
121
+ // {}
122
+ function isObjectType(type) {
123
+ return !!type && ts.isTypeLiteralNode(type);
124
+ }
125
+ // []
126
+ function isTupleArray(type) {
127
+ return !!type && ts.isTupleTypeNode(type);
128
+ }
129
+ // () => {}
130
+ function isFunctionType(type) {
131
+ return !!type && ts.isFunctionTypeNode(type);
132
+ }
133
+ function isDecoratorExp(decorator, decoratorName) {
134
+ var expr = decorator.expression;
135
+ return ts.isCallExpression(expr) && ts.isIdentifier(expr.expression) && expr.expression.text === decoratorName;
136
+ }
137
+ function hasClassKindDecorator(classDeclaration) {
138
+ var _classDeclaration$mod;
139
+ return !!((_classDeclaration$mod = classDeclaration.modifiers) !== null && _classDeclaration$mod !== void 0 && _classDeclaration$mod.find(function (modifier) {
140
+ return ts.isDecorator(modifier);
141
+ }));
142
+ }
143
+ function extractIdentifierFromType(type) {
144
+ if (ts.isTypeReferenceNode(type)) {
145
+ if (ts.isIdentifier(type.typeName)) {
146
+ if (wrapperClassName.includes(type.typeName.text) || innerClassName.includes(type.typeName.text)) {
147
+ return ts.factory.createIdentifier('undefined');
148
+ }
149
+ return ts.factory.createIdentifier(type.typeName.text);
150
+ }
151
+ } else if (type.kind === ts.SyntaxKind.StringKeyword || type.kind === ts.SyntaxKind.NumberKeyword || type.kind === ts.SyntaxKind.BooleanKeyword || type.kind === ts.SyntaxKind.ObjectKeyword || type && ts.isLiteralTypeNode(type) && type.literal.kind === ts.SyntaxKind.NullKeyword || type.kind === ts.SyntaxKind.UndefinedKeyword || type.kind === ts.SyntaxKind.SymbolKeyword) {
152
+ return ts.factory.createIdentifier('undefined');
153
+ } else if (isObjectType(type) || isTupleArray(type) || isFunctionType(type)) {
154
+ return ts.factory.createIdentifier('undefined');
155
+ }
156
+ return undefined;
157
+ }
158
+ function createNamedImport(className, importPath) {
159
+ return ts.factory.createImportDeclaration(undefined,
160
+ // modifiers
161
+ ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(className))])), ts.factory.createStringLiteral(importPath), undefined);
162
+ }
163
+ function createImport(className, importPath) {
164
+ return ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(undefined, ts.factory.createIdentifier(className), undefined), ts.factory.createStringLiteral(importPath), undefined);
165
+ }
166
+ function updateTypeImports(sourceFile) {
167
+ var identifyList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
168
+ if (!identifyList.length) {
169
+ return sourceFile;
170
+ }
171
+ var importNames = new Set();
172
+ identifyList.forEach(function (iden) {
173
+ return importNames.add(iden.text);
174
+ });
175
+ var newStatements = [];
176
+ var _iterator = _createForOfIteratorHelper(importNames),
177
+ _step;
178
+ try {
179
+ var _loop = function _loop() {
180
+ var name = _step.value;
181
+ var _iterator2 = _createForOfIteratorHelper(sourceFile.statements),
182
+ _step2;
183
+ try {
184
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
185
+ var stmt = _step2.value;
186
+ if (ts.isImportDeclaration(stmt)) {
187
+ var _stmt$importClause$na;
188
+ if (((_stmt$importClause$na = stmt.importClause.namedBindings) === null || _stmt$importClause$na === void 0 ? void 0 : _stmt$importClause$na.kind) === ts.SyntaxKind.NamedImports) {
189
+ var match = stmt.importClause.namedBindings.elements.find(function (e) {
190
+ return name === e.name.text;
191
+ });
192
+ if (match) {
193
+ var importPath = stmt.moduleSpecifier.text;
194
+ newStatements.push(createNamedImport(name, importPath));
195
+ break;
196
+ }
197
+ }
198
+ if (stmt.importClause.name && ts.isIdentifier(stmt.importClause.name)) {
199
+ if (stmt.importClause.name.text === name) {
200
+ var _importPath = stmt.moduleSpecifier.text;
201
+ newStatements.push(createImport(name, _importPath));
202
+ break;
203
+ }
204
+ }
205
+ }
206
+ }
207
+ } catch (err) {
208
+ _iterator2.e(err);
209
+ } finally {
210
+ _iterator2.f();
211
+ }
212
+ };
213
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
214
+ _loop();
215
+ }
216
+ } catch (err) {
217
+ _iterator.e(err);
218
+ } finally {
219
+ _iterator.f();
220
+ }
221
+ return ts.factory.updateSourceFile(sourceFile, [].concat(newStatements, _toConsumableArray(sourceFile.statements)));
222
+ }
223
+
224
+ function isConstructParamsDecorator(decorator) {
225
+ return isDecoratorExp(decorator, 'constructorParam');
226
+ }
227
+ function extractIdentifiersFromConstructor(ctor) {
228
+ var identifiers = [];
229
+ var _iterator = _createForOfIteratorHelper(ctor.parameters),
230
+ _step;
231
+ try {
232
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
233
+ var param = _step.value;
234
+ if (!param.type) {
235
+ return [];
236
+ }
237
+ var id = extractIdentifierFromType(param.type);
238
+ if (!id) {
239
+ return [];
240
+ }
241
+ identifiers.push(id);
242
+ }
243
+ } catch (err) {
244
+ _iterator.e(err);
245
+ } finally {
246
+ _iterator.f();
247
+ }
248
+ return identifiers;
249
+ }
250
+ function updateConstructorParamDecorator(classDeclaration) {
251
+ var modifiers = classDeclaration.modifiers;
252
+ if (!modifiers) {
253
+ return {
254
+ updated: false,
255
+ modifiers: classDeclaration.modifiers
256
+ };
257
+ }
258
+ var decorators = modifiers.filter(ts.isDecorator);
259
+ if (!decorators.length) {
260
+ return {
261
+ updated: false,
262
+ modifiers: classDeclaration.modifiers
263
+ };
264
+ }
265
+ var constructParams = decorators.find(isConstructParamsDecorator);
266
+ if (!constructParams) {
267
+ return {
268
+ updated: false,
269
+ modifiers: classDeclaration.modifiers
270
+ };
271
+ }
272
+ var call = constructParams.expression;
273
+ // 已有参数,不处理
274
+ if (call.arguments.length > 0) {
275
+ return {
276
+ updated: false,
277
+ modifiers: classDeclaration.modifiers
278
+ };
279
+ }
280
+ // 找 constructor
281
+ var ctor = classDeclaration.members.find(function (m) {
282
+ return ts.isConstructorDeclaration(m);
283
+ });
284
+ if (!ctor) {
285
+ return {
286
+ updated: false,
287
+ modifiers: classDeclaration.modifiers
288
+ };
289
+ }
290
+ var identifiers = extractIdentifiersFromConstructor(ctor);
291
+ if (!identifiers.length) {
292
+ return {
293
+ updated: false,
294
+ modifiers: classDeclaration.modifiers
295
+ };
296
+ }
297
+ // 构造数组:[Api, User]
298
+ var arrayLiteral = ts.factory.createArrayLiteralExpression(identifiers, false);
299
+ var newModifiers = modifiers.map(function (m) {
300
+ return ts.isDecorator(m) && m === constructParams ? ts.factory.createDecorator(ts.factory.updateCallExpression(call, call.expression, call.typeArguments, [arrayLiteral])) : m;
301
+ });
302
+ return {
303
+ updated: true,
304
+ modifiers: newModifiers,
305
+ constructorParamTypeList: identifiers
306
+ };
307
+ }
308
+
309
+ function isAutowiredDecorator(decorator) {
310
+ return isDecoratorExp(decorator, 'autowired');
311
+ }
312
+ function updateAutowiredDecorator(member, markUpdate) {
313
+ if (!ts.isPropertyDeclaration(member)) {
314
+ return member;
315
+ }
316
+ var modifiers = member.modifiers;
317
+ if (!modifiers) {
318
+ return member;
319
+ }
320
+ var decorators = modifiers.filter(ts.isDecorator);
321
+ if (!decorators.length) {
322
+ return member;
323
+ }
324
+ var autowired = decorators.find(isAutowiredDecorator);
325
+ if (!autowired) {
326
+ return member;
327
+ }
328
+ var call = autowired.expression;
329
+ // 已经有参数,不处理
330
+ if (call.arguments.length > 0) {
331
+ return member;
332
+ }
333
+ if (!member.type) {
334
+ return member;
335
+ }
336
+ var identifier = extractIdentifierFromType(member.type);
337
+ if (!identifier) {
338
+ return member;
339
+ }
340
+ markUpdate(identifier);
341
+ var newModifiers = modifiers.map(function (m) {
342
+ return ts.isDecorator(m) && m === autowired ? ts.factory.createDecorator(ts.factory.updateCallExpression(call, call.expression, call.typeArguments, [identifier])) : m;
343
+ });
344
+ return ts.factory.updatePropertyDeclaration(member, newModifiers, member.name, ts.factory.createToken(ts.SyntaxKind.ExclamationToken), member.type, member.initializer);
345
+ }
346
+
347
+ function isComponentDecorator(decorator) {
348
+ return isDecoratorExp(decorator, 'component');
349
+ }
350
+ function updateComponentDecorator(member, markUpdate) {
351
+ if (!ts.isMethodDeclaration(member)) {
352
+ return member;
353
+ }
354
+ var modifiers = member.modifiers;
355
+ if (!modifiers) {
356
+ return member;
357
+ }
358
+ var decorators = modifiers.filter(ts.isDecorator);
359
+ if (!decorators.length) {
360
+ return member;
361
+ }
362
+ var component = decorators.find(isComponentDecorator);
363
+ if (!component) {
364
+ return member;
365
+ }
366
+ var call = component.expression;
367
+ // 已有参数,不处理
368
+ if (call.arguments.length > 0) {
369
+ return member;
370
+ }
371
+ // 没有返回类型,无法补全
372
+ if (!member.type) {
373
+ return member;
374
+ }
375
+ var identifier = extractIdentifierFromType(member.type);
376
+ if (!identifier) {
377
+ return member;
378
+ }
379
+ markUpdate(identifier);
380
+ var newModifiers = modifiers.map(function (m) {
381
+ return ts.isDecorator(m) && m === component ? ts.factory.createDecorator(ts.factory.updateCallExpression(call, call.expression, call.typeArguments, [identifier])) : m;
382
+ });
383
+ return ts.factory.updateMethodDeclaration(member, newModifiers, member.asteriskToken, member.name, member.questionToken, member.typeParameters, member.parameters, member.type, member.body);
384
+ }
385
+
386
+ var innerIdName = '$$id';
387
+ function ifNeedAdd$$idProperty(classDecorator, prefix) {
388
+ var className = classDecorator.name.text;
389
+ var $$idProperties = classDecorator.members.filter(function (member) {
390
+ var _member$modifiers;
391
+ return ts.isPropertyDeclaration(member) && ((_member$modifiers = member.modifiers) === null || _member$modifiers === void 0 ? void 0 : _member$modifiers.some(function (modify) {
392
+ return modify.kind === ts.SyntaxKind.StaticKeyword;
393
+ })) && ts.isIdentifier(member.name) && member.name.text === '$$id';
394
+ });
395
+ if ($$idProperties.length === 0) {
396
+ return ts.factory.createPropertyDeclaration([ts.factory.createModifier(ts.SyntaxKind.StaticKeyword)], innerIdName, undefined, undefined, ts.factory.createStringLiteral("".concat(prefix).concat(className)));
397
+ } else if ($$idProperties.length === 1) {
398
+ var property = $$idProperties[0];
399
+ if (property.initializer && ts.isStringLiteral(property.initializer)) {
400
+ if (!property.initializer.text.trim()) {
401
+ throw new Error("\u60F3\u8981\u4E3A\u7C7B".concat(className, "\u81EA\u5B9A\u4E49\"").concat(innerIdName, "\"\uFF0C\u503C\u4E0D\u80FD\u662F\u7A7A\u5B57\u7B26\u4E32"));
402
+ } else {
403
+ return null;
404
+ }
405
+ } else {
406
+ throw new Error("\u60F3\u8981\u4E3A\u7C7B".concat(className, "\u81EA\u5B9A\u4E49\"").concat(innerIdName, "\"\uFF0C\u503C\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u5B57\u9762\u91CF"));
407
+ }
408
+ } else {
409
+ throw new Error("\u7C7B".concat(className, "\u5B58\u5728\u591A\u4E2A\"").concat(innerIdName, "\"\uFF0C\u6700\u591A\u53EA\u80FD\u6709\u4E00\u4E2A\uFF01"));
410
+ }
411
+ }
412
+
413
+ function updateMembers(classDeclaration) {
414
+ var updated = false;
415
+ var autowiredList = [];
416
+ var componentList = [];
417
+ var updateAutowired = function updateAutowired(identifier) {
418
+ autowiredList.push(identifier);
419
+ updated = true;
420
+ };
421
+ var updateComponent = function updateComponent(identifier) {
422
+ componentList.push(identifier);
423
+ updated = true;
424
+ };
425
+ var members = classDeclaration.members.map(function (member) {
426
+ if (ts.isPropertyDeclaration(member)) {
427
+ return updateAutowiredDecorator(member, updateAutowired);
428
+ } else if (ts.isMethodDeclaration(member)) {
429
+ return updateComponentDecorator(member, updateComponent);
430
+ } else {
431
+ return member;
432
+ }
433
+ });
434
+ return {
435
+ updated: updated,
436
+ members: updated ? members : classDeclaration.members,
437
+ autowiredList: autowiredList,
438
+ componentList: componentList
439
+ };
440
+ }
441
+ function transformerFactory() {
442
+ var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
443
+ return function (context) {
444
+ var constructorParamList = [];
445
+ var autowiredList = [];
446
+ var componentList = [];
447
+ var _visit = function visit(node) {
448
+ if (ts.isClassDeclaration(node)) {
449
+ if (hasClassKindDecorator(node)) {
450
+ var $$idProperty = ifNeedAdd$$idProperty(node, prefix);
451
+ var _updateMembers = updateMembers(node),
452
+ members = _updateMembers.members,
453
+ membersUpdated = _updateMembers.updated,
454
+ _autowiredList = _updateMembers.autowiredList,
455
+ _componentList = _updateMembers.componentList;
456
+ var _updateConstructorPar = updateConstructorParamDecorator(node),
457
+ modifiers = _updateConstructorPar.modifiers,
458
+ constructorParamsUpdated = _updateConstructorPar.updated,
459
+ _constructorParamTypeList = _updateConstructorPar.constructorParamTypeList;
460
+ if (!membersUpdated && !constructorParamsUpdated && !$$idProperty) {
461
+ return node;
462
+ } else {
463
+ if (_autowiredList) {
464
+ autowiredList = _autowiredList;
465
+ }
466
+ if (_componentList) {
467
+ componentList = _componentList;
468
+ }
469
+ if (constructorParamsUpdated) {
470
+ constructorParamList = _constructorParamTypeList;
471
+ }
472
+ return ts.factory.updateClassDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, $$idProperty ? [$$idProperty].concat(_toConsumableArray(members)) : members);
473
+ }
474
+ }
475
+ return node;
476
+ } else {
477
+ return ts.visitEachChild(node, _visit, context);
478
+ }
479
+ };
480
+ // @ts-ignore
481
+ return function (sourceFile) {
482
+ var updatedSourceFile = ts.visitNode(sourceFile, _visit);
483
+ if (!constructorParamList.length && !autowiredList.length && !componentList.length) {
484
+ return updatedSourceFile;
485
+ }
486
+ return updateTypeImports(updatedSourceFile, [].concat(_toConsumableArray(constructorParamList), _toConsumableArray(autowiredList), _toConsumableArray(componentList)));
487
+ };
488
+ };
489
+ }
490
+
491
+ var commonCompilerOptions = {
492
+ target: ts.ScriptTarget.ESNext,
493
+ module: ts.ModuleKind.ESNext,
494
+ emitDecoratorMetadata: false
495
+ };
496
+ function compileOneFile(code, fileName) {
497
+ var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
498
+ var result = ts.transpileModule(code, {
499
+ fileName: fileName,
500
+ compilerOptions: _objectSpread2(_objectSpread2({}, commonCompilerOptions), {}, {
501
+ sourceMap: true
502
+ }),
503
+ transformers: {
504
+ before: [transformerFactory(prefix)]
505
+ }
506
+ });
507
+ return {
508
+ code: result.outputText,
509
+ map: result.sourceMapText
510
+ };
511
+ }
512
+
513
+ export { commonCompilerOptions, compileOneFile, transformerFactory };
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@cocojs/compiler",
3
- "version": "0.1.0-beta.202601082201",
3
+ "version": "0.1.0-beta.202601082202",
4
4
  "description": "A Coco component transpiler built on the TypeScript compiler API.",
5
5
  "main": "dist/index.cjs.js",
6
+ "module": "dist/index.esm.js",
6
7
  "types": "dist/index.d.ts",
7
8
  "files": [
8
9
  "dist"