babel-plugin-hylid-bridge 2.4.0 → 2.9.0

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/CHANGELOG.md CHANGED
@@ -3,6 +3,22 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [2.9.0](https://code.alipay.com/ant-ife/hylid-bridge/compare/v2.9.0-alpha.0...v2.9.0) (2022-11-09)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * 类型兼容
12
+
13
+
14
+ ## [2.9.0-alpha.0](https://code.alipay.com/ant-ife/hylid-bridge/compare/v2.8.0...v2.9.0-alpha.0) (2022-11-09)
15
+
16
+
17
+ ### Features
18
+
19
+ * 支持 my.call 调用
20
+
21
+
6
22
  ## [2.4.0](https://code.alipay.com/ant-ife/hylid-bridge/compare/v2.4.0-alpha.4...v2.4.0) (2022-08-18)
7
23
 
8
24
  **Note:** Version bump only for package babel-plugin-hylid-bridge
@@ -4,15 +4,11 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = getLibraryDir;
7
-
8
7
  var _utils = require("./utils");
9
-
10
8
  var libraryDir;
11
-
12
9
  function getLibraryDir() {
13
10
  if (!libraryDir) {
14
11
  var cwd = process.cwd();
15
-
16
12
  try {
17
13
  libraryDir = process.env.HYLID_BRIDGE_PACKAGE_DIR || require.resolve('hylid-bridge/package.json', {
18
14
  paths: [cwd]
@@ -22,6 +18,5 @@ function getLibraryDir() {
22
18
  (0, _utils.error)("Can not resolve the hylid-bridge package from the directory: ".concat(cwd, "."), e);
23
19
  }
24
20
  }
25
-
26
21
  return libraryDir;
27
22
  }
package/lib/index.d.ts CHANGED
@@ -3,5 +3,5 @@ import { PluginPass } from '@babel/core';
3
3
  interface IState extends PluginPass {
4
4
  usedJSAPIList: 'all' | string[];
5
5
  }
6
- declare const _default: (_: typeof babelCore, opts?: Record<string, any>) => babelCore.PluginObj<IState>;
6
+ declare const _default: (core: typeof babelCore, opts?: Record<string, any>) => babelCore.PluginObj<IState>;
7
7
  export default _default;
package/lib/index.js CHANGED
@@ -1,151 +1,153 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  var _typeof = require("@babel/runtime/helpers/typeof");
6
-
7
5
  Object.defineProperty(exports, "__esModule", {
8
6
  value: true
9
7
  });
10
8
  exports.default = void 0;
11
-
12
9
  var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
13
-
14
10
  var _path = _interopRequireDefault(require("path"));
15
-
16
11
  var _fsExtra = _interopRequireDefault(require("fs-extra"));
17
-
18
12
  var _lodash = _interopRequireDefault(require("lodash"));
19
-
20
13
  var babelTypes = _interopRequireWildcard(require("@babel/types"));
21
-
22
14
  var _getLibraryDir = _interopRequireDefault(require("./getLibraryDir"));
23
-
24
15
  var utils = _interopRequireWildcard(require("./utils"));
25
-
26
16
  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
-
28
17
  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; }
29
-
30
18
  /**
31
19
  * https://astexplorer.net/
32
20
  */
21
+
33
22
  var identifierPrefix = '__hylid_bridge__';
34
23
  var libraryName = 'hylid-bridge';
35
24
  var libraryDir = (0, _getLibraryDir.default)();
36
-
37
25
  function snakeCaseTarget(value) {
38
26
  if (value === 'H5') {
39
27
  return 'h5';
40
28
  }
41
-
42
29
  return _lodash.default.snakeCase(value);
43
30
  }
44
-
45
31
  function isTargetSupported(target) {
46
32
  var libraryDir = (0, _getLibraryDir.default)();
47
33
  return ['MpWeb', 'Mp', 'Web'].some(function (prefix) {
48
34
  if (target.startsWith(prefix)) {
49
35
  var targetClientDir = _path.default.resolve(libraryDir, 'lib/clients', snakeCaseTarget(prefix), snakeCaseTarget(target.replace(prefix, '')));
50
-
51
36
  return _fsExtra.default.existsSync(targetClientDir);
52
37
  }
53
-
54
38
  return false;
55
39
  });
56
40
  }
57
-
58
41
  function getTargets(customTargets) {
59
42
  var targets = customTargets || (process.env.HYLID_BRIDGE_TARGETS ? process.env.HYLID_BRIDGE_TARGETS.split(',') : []);
60
43
  return targets.filter(isTargetSupported);
61
44
  }
62
-
63
45
  function isApiExists(name, target) {
64
46
  var targetSplit = splitTarget(target);
65
-
66
47
  if (targetSplit.length !== 2) {
67
48
  throw new Error("Wrong target configuration: ".concat(target, "."));
68
49
  }
69
-
70
50
  return _fsExtra.default.existsSync(_path.default.resolve(libraryDir, "./lib/clients/".concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name, ".js")));
71
51
  }
72
-
73
52
  function getUserAppEnvPath(appEnvPath) {
74
53
  var realAppEnvPath = appEnvPath !== null && appEnvPath !== void 0 ? appEnvPath : _path.default.resolve(process.cwd(), './src/appEnv.ts');
75
-
76
54
  if (!_fsExtra.default.existsSync(realAppEnvPath)) {
77
55
  utils.log("Can not find the appEnv module at the path: ".concat(realAppEnvPath, "."));
78
56
  return;
79
57
  }
80
-
81
58
  return realAppEnvPath;
82
59
  }
83
-
84
60
  function splitTarget(target) {
85
61
  var prefixList = ['MpWeb', 'Mp', 'Web'];
86
-
87
62
  for (var i = 0, il = prefixList.length; i < il; i++) {
88
63
  var prefix = prefixList[i];
89
-
90
64
  if (target.startsWith(prefix)) {
91
65
  return [snakeCaseTarget(prefix), snakeCaseTarget(target.replace(prefix, ''))];
92
66
  }
93
67
  }
94
-
95
68
  throw new Error("Invalid bridge target: ".concat(target, "."));
96
69
  }
97
-
98
70
  var myLocalName = "".concat(identifierPrefix, "my__");
99
-
100
- var _default = function _default(_, opts) {
71
+ function getNames(node, scope, state, targets) {
72
+ var _state$filename;
73
+ if (node.object.type === 'Identifier' && node.property.type === 'Identifier' &&
74
+ // Remix 中会编译所有 node_modules 下的模块
75
+ !((_state$filename = state.filename) !== null && _state$filename !== void 0 && _state$filename.includes("".concat(_path.default.sep, "node_modules").concat(_path.default.sep, "hylid-bridge").concat(_path.default.sep))) && targets && targets.length && !scope.hasBinding('my')) {
76
+ return {
77
+ objectName: node.object.name,
78
+ propertyName: node.property.name
79
+ };
80
+ }
81
+ return {
82
+ objectName: undefined,
83
+ propertyName: undefined
84
+ };
85
+ }
86
+ function isJSAPIInTargets(jsapiName, targets, filename) {
87
+ return targets.every(function (target) {
88
+ var targetSplit = splitTarget(target);
89
+ if (!isApiExists(jsapiName, target)) {
90
+ utils.warn("Can not find the API `".concat(jsapiName, "` in `").concat(_path.default.resolve(libraryDir, './lib/clients/' + targetSplit[0] + '/' + targetSplit[1]), "`. Fallback to import all API codes of ").concat(target, ". Current file path: `").concat(filename, "`."));
91
+ return false;
92
+ }
93
+ return true;
94
+ });
95
+ }
96
+ var _default = function _default(core, opts) {
101
97
  var targets = getTargets(opts === null || opts === void 0 ? void 0 : opts.targets);
102
98
  var userAppEnvPath = getUserAppEnvPath(opts === null || opts === void 0 ? void 0 : opts.appEnvPath);
103
99
  return {
104
100
  name: 'babel-plugin-hylid-bridge',
105
101
  visitor: {
106
102
  MemberExpression: function MemberExpression(path, state) {
107
- var _this$filename,
108
- _this = this;
109
-
110
- var objectName = path.node.object.name;
111
- var propertyName = path.node.property.name;
112
-
113
- if ( // Remix 中会编译所有 node_modules 下的模块
114
- (_this$filename = this.filename) !== null && _this$filename !== void 0 && _this$filename.includes("".concat(_path.default.sep, "node_modules").concat(_path.default.sep, "hylid-bridge").concat(_path.default.sep)) || !targets || !targets.length || objectName !== 'my' || path.scope.hasBinding('my')) {
103
+ var _getNames = getNames(path.node, path.scope, state, targets),
104
+ objectName = _getNames.objectName,
105
+ propertyName = _getNames.propertyName;
106
+ if (!propertyName || propertyName === 'call' || objectName !== 'my') {
115
107
  return;
116
108
  }
117
-
118
- var newNode = babelTypes.cloneNode(path.node, true, true);
119
- newNode.object = babelTypes.identifier(myLocalName);
120
-
109
+ var newNode = core.types.cloneNode(path.node, true, true);
110
+ newNode.object = core.types.identifier(myLocalName);
121
111
  if (state.usedJSAPIList === 'all') {
122
112
  path.replaceWith(newNode);
123
113
  return;
124
114
  }
125
-
126
115
  if (path.node.computed) {
127
116
  state.usedJSAPIList = 'all';
128
- utils.warn("Detect visiting the property of `my` with computed mode: my[".concat(propertyName, "]. Fallback to import all API codes of ").concat(targets.join(','), ". Current file path: `").concat(this.file.opts.filename, "`."));
117
+ utils.warn("Detect visiting the property of `my` with computed mode: my[".concat(propertyName, "]. Fallback to import all API codes of ").concat(targets.join(','), ". Current file path: `").concat(state.filename, "`."));
129
118
  } else {
130
119
  state.usedJSAPIList = state.usedJSAPIList || [];
131
120
  var name = propertyName;
132
-
133
- if (targets.every(function (target) {
134
- var targetSplit = splitTarget(target);
135
-
136
- if (!isApiExists(name, target)) {
137
- utils.warn("Can not find the API `".concat(name, "` in `").concat(_path.default.resolve(libraryDir, './lib/clients/' + targetSplit[0] + '/' + targetSplit[1]), "`. Fallback to import all API codes of ").concat(target, ". Current file path: `").concat(_this.file.opts.filename, "`."));
138
- return false;
139
- }
140
-
141
- return true;
142
- })) {
121
+ if (isJSAPIInTargets(name, targets, state.filename)) {
143
122
  state.usedJSAPIList.push(name);
144
123
  } else {
145
124
  state.usedJSAPIList = 'all';
146
125
  }
147
126
  }
148
-
127
+ path.replaceWith(newNode);
128
+ },
129
+ CallExpression: function CallExpression(path, state) {
130
+ if (path.node.callee.type !== 'MemberExpression') {
131
+ return;
132
+ }
133
+ var _getNames2 = getNames(path.node.callee, path.scope, state, targets),
134
+ objectName = _getNames2.objectName,
135
+ propertyName = _getNames2.propertyName;
136
+ if (objectName !== 'my' || propertyName !== 'call' || !path.node.arguments[0] || path.node.arguments[0].type !== 'StringLiteral') {
137
+ return;
138
+ }
139
+ var newNode = core.types.callExpression(babelTypes.memberExpression(babelTypes.identifier(myLocalName), babelTypes.identifier(path.node.arguments[0].value)), path.node.arguments.slice(1));
140
+ if (state.usedJSAPIList === 'all') {
141
+ path.replaceWith(newNode);
142
+ return;
143
+ }
144
+ state.usedJSAPIList = state.usedJSAPIList || [];
145
+ var name = path.node.arguments[0].value;
146
+ if (isJSAPIInTargets(name, targets, state.filename)) {
147
+ state.usedJSAPIList.push(name);
148
+ } else {
149
+ state.usedJSAPIList = 'all';
150
+ }
149
151
  path.replaceWith(newNode);
150
152
  },
151
153
  Program: {
@@ -153,47 +155,37 @@ var _default = function _default(_, opts) {
153
155
  if (!state.usedJSAPIList) {
154
156
  return;
155
157
  }
156
-
157
158
  var usedJSAPIList = state.usedJSAPIList || [];
158
159
  var appEnvLocalName = "".concat(identifierPrefix, "appEnv__");
159
-
160
160
  if (path.scope.hasBinding(appEnvLocalName)) {
161
161
  return;
162
162
  }
163
-
164
163
  var innerAppEnvLocalName = "".concat(identifierPrefix, "innerAppEnv__");
165
164
  var userAppEnvLocalName = "".concat(identifierPrefix, "userAppEnv__");
166
165
  var nodes = [babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(innerAppEnvLocalName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/appEnv")))];
167
-
168
166
  if (userAppEnvPath) {
169
- var relativePath = _path.default.relative(_path.default.dirname(this.filename), userAppEnvPath.replace(/\.ts$/, ''));
170
-
167
+ var relativePath = _path.default.relative(_path.default.dirname(state.filename), userAppEnvPath.replace(/\.ts$/, ''));
171
168
  nodes.push(babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(userAppEnvLocalName))], babelTypes.stringLiteral(relativePath.startsWith('../') ? relativePath : "./".concat(relativePath))));
172
169
  } else {
173
170
  nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(userAppEnvLocalName), babelTypes.objectExpression([]))]));
174
171
  }
175
-
176
172
  var objectSpreadName = "".concat(identifierPrefix, "objectSpread__");
177
173
  nodes.push(babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(objectSpreadName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/objectSpread"))), babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(appEnvLocalName), babelTypes.callExpression(babelTypes.identifier(objectSpreadName), [babelTypes.identifier(innerAppEnvLocalName), babelTypes.identifier(userAppEnvLocalName)]))]));
178
-
179
174
  if (usedJSAPIList === 'all') {
180
175
  nodes.push.apply(nodes, (0, _toConsumableArray2.default)(targets.map(function (target) {
181
176
  var targetSplit = splitTarget(target);
182
177
  return babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))], babelTypes.stringLiteral("".concat(libraryName, "/lib/clients/").concat(targetSplit[0], "/").concat(targetSplit[1], "/index")));
183
178
  })));
184
-
185
179
  var buildElseIf = function buildElseIf(targetList) {
186
180
  if (!targetList.length) {
187
181
  return;
188
182
  }
189
-
190
183
  var target = targetList[0];
191
184
  var targetSplit = splitTarget(target);
192
185
  return babelTypes.ifStatement(babelTypes.identifier("".concat(appEnvLocalName, ".").concat(_lodash.default.camelCase("is_".concat(targetSplit[0], "_").concat(targetSplit[1])))), babelTypes.blockStatement([babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__"))))]), buildElseIf(targetList.slice(1)));
193
186
  };
194
-
195
- nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))])); // Do not generate the `if statement` when there is just one target.
196
-
187
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))]));
188
+ // Do not generate the `if statement` when there is just one target.
197
189
  if (targets.length === 1) {
198
190
  var targetSplit = splitTarget(targets[0]);
199
191
  nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))));
@@ -203,7 +195,6 @@ var _default = function _default(_, opts) {
203
195
  }
204
196
  } else if (usedJSAPIList.length) {
205
197
  var normalizedJSAPIList = _lodash.default.uniq(usedJSAPIList);
206
-
207
198
  normalizedJSAPIList.forEach(function (name) {
208
199
  targets.forEach(function (target) {
209
200
  var targetSplit = splitTarget(target);
@@ -212,12 +203,10 @@ var _default = function _default(_, opts) {
212
203
  nodes.push(n);
213
204
  });
214
205
  });
215
-
216
206
  var _buildElseIf = function _buildElseIf(targetList) {
217
207
  if (!targetList.length) {
218
208
  return;
219
209
  }
220
-
221
210
  var target = targetList[0];
222
211
  var targetSplit = splitTarget(target);
223
212
  var propertyList = normalizedJSAPIList.map(function (name) {
@@ -225,34 +214,28 @@ var _default = function _default(_, opts) {
225
214
  });
226
215
  return babelTypes.ifStatement(babelTypes.identifier("".concat(appEnvLocalName, ".").concat(_lodash.default.camelCase("is_".concat(targetSplit[0], "_").concat(targetSplit[1])))), babelTypes.blockStatement([babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.objectExpression(propertyList)))]), _buildElseIf(targetList.slice(1)));
227
216
  };
228
-
229
- nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))])); // Do not generate the `if statement` when there is just one target.
230
-
217
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))]));
218
+ // Do not generate the `if statement` when there is just one target.
231
219
  if (targets.length === 1) {
232
220
  var _targetSplit = splitTarget(targets[0]);
233
-
234
221
  var propertyList = normalizedJSAPIList.map(function (name) {
235
222
  return babelTypes.objectProperty(babelTypes.identifier(name), babelTypes.identifier("".concat(identifierPrefix).concat(_targetSplit[0], "_").concat(_targetSplit[1], "_").concat(name, "__")));
236
223
  });
237
224
  nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.objectExpression(propertyList))));
238
225
  } else {
239
226
  var _elseIfNode = _buildElseIf(targets);
240
-
241
227
  _elseIfNode && nodes.push(_elseIfNode);
242
228
  }
243
229
  }
244
-
245
230
  if (nodes.length) {
246
231
  path.unshiftContainer('body', nodes);
247
232
  }
248
-
249
233
  if (targets.length && (usedJSAPIList === 'all' || usedJSAPIList.length)) {
250
- utils.log("Successfully inject the Hylid-bridge into ".concat(this.filename, " to support the targets: ").concat(targets.join(','), "."));
234
+ utils.log("Successfully inject the Hylid-bridge into ".concat(state.filename, " to support the targets: ").concat(targets.join(','), "."));
251
235
  }
252
236
  }
253
237
  }
254
238
  }
255
239
  };
256
240
  };
257
-
258
241
  exports.default = _default;
package/lib/utils.js CHANGED
@@ -1,42 +1,31 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
7
  exports.error = error;
9
8
  exports.log = log;
10
9
  exports.warn = warn;
11
-
12
10
  var _chalk = _interopRequireDefault(require("chalk"));
13
-
14
11
  function log() {
15
12
  var _console;
16
-
17
13
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
18
14
  args[_key] = arguments[_key];
19
15
  }
20
-
21
16
  (_console = console).log.apply(_console, [_chalk.default.bold.green('[LOG]')].concat(args));
22
17
  }
23
-
24
18
  function error() {
25
19
  var _console2;
26
-
27
20
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
28
21
  args[_key2] = arguments[_key2];
29
22
  }
30
-
31
23
  (_console2 = console).error.apply(_console2, [_chalk.default.bold.red('[ERROR]')].concat(args));
32
24
  }
33
-
34
25
  function warn() {
35
26
  var _console3;
36
-
37
27
  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
38
28
  args[_key3] = arguments[_key3];
39
29
  }
40
-
41
30
  (_console3 = console).error.apply(_console3, [_chalk.default.bold.yellow('[WARN]')].concat(args));
42
31
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "babel-plugin-hylid-bridge",
3
- "version": "2.4.0",
3
+ "version": "2.9.0",
4
4
  "description": "babel-plugin-hylid-bridge",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {