@hylid/call 3.2.0-alpha.0 → 3.2.0-alpha.2

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.
@@ -44,10 +44,9 @@ var MESSAGE_HANDLER = [];
44
44
  export function mpWebOnMessage(cb) {
45
45
  MESSAGE_HANDLER.push(cb);
46
46
  return function () {
47
- var index = MESSAGE_HANDLER.indexOf(cb);
48
- if (index > -1) {
49
- MESSAGE_HANDLER.splice(index, 1);
50
- }
47
+ MESSAGE_HANDLER = MESSAGE_HANDLER.filter(function (o) {
48
+ return o !== cb;
49
+ });
51
50
  };
52
51
  }
53
52
  export function mpWebPostMessage(message) {
@@ -1,5 +1,11 @@
1
- import { PickMPArgs, PickMpReturns, MPApi } from '@hylid/types';
2
- import { MpWebJsApiConfig } from './types';
3
- declare type Callback<T> = (result?: T) => void;
4
- export declare const mpWebCall: <T extends keyof MPApi>(api: ({} & string) | T, options?: PickMPArgs<T> | Callback<ReturnType<MPApi[T]>> | undefined, config?: MpWebJsApiConfig) => void;
5
- export {};
1
+ import { MPApi } from '@hylid/types';
2
+ import { MpWebJsApiConfig, MpWebJsApiOptions } from './types';
3
+ import { mpWebOnMessage, mpWebPostMessage } from './mpWebBridge';
4
+ export declare function mpWebCall<T extends keyof MPApi>(api: T | ({} & string), options?: MpWebJsApiOptions<T>, config?: MpWebJsApiConfig): void;
5
+ export declare namespace mpWebCall {
6
+ var onMessage: typeof mpWebOnMessage;
7
+ var postMessage: typeof mpWebPostMessage;
8
+ var broadcastGlobalData: (key: string, result: any) => void;
9
+ var onReceiveGlobalData: (key: string, callback: (data: any, error: any, form: string) => void) => () => void;
10
+ var onPageEvent: (event: ({} & string) | "onShow" | "onHide" | "onTitleClick" | "onOptionMenuClick" | "onTabItemTap", callback: (data: any, err?: any) => void) => () => void;
11
+ }
package/lib/mpWebCall.js CHANGED
@@ -1,118 +1,111 @@
1
- var loadAppxBridge = function loadAppxBridge(cb) {
1
+ import { mpWebOnMessage, mpWebPostMessage } from "./mpWebBridge";
2
+ // 关联 postMessage 和 onMessage,根据 serialId 执行回调
3
+ var callMap = {};
4
+ // 注册 jsapi 的 message 处理器
5
+ mpWebOnMessage(function (msg) {
2
6
  var _a;
3
- try {
4
- // umd 包用的 IFF 模式,会立即向 window.my 上注入 jsapi,所以不能使用 window.my 判断是否已经加载了 appx 脚本
5
- // umd 版本和 modules 版本不能混用
6
- if ((_a = window.my) === null || _a === void 0 ? void 0 : _a.__hy_mounted__) {
7
- cb && cb("ready" /* BridgeReady.READY */);
8
- return;
9
- }
10
- var hyMy_1 = window.my || {};
11
- var script_1 = document.createElement('script');
12
- script_1.src = 'https://appx/web-view.min.js';
13
- script_1.onload = function onload() {
14
- var readyState = script_1['readyState'];
15
- if (typeof readyState === 'undefined' || /^(loaded|complete)$/.test(readyState)) {
16
- script_1.onload = null;
17
- Object.assign(window.my, hyMy_1, {
18
- __hy_mounted__: true
19
- });
20
- cb && cb("loaded" /* BridgeReady.LOADED */);
21
- }
22
- };
23
- var head = document.getElementsByTagName('head')[0] || document.body;
24
- head.appendChild(script_1);
25
- } catch (e) {
26
- cb && cb(null);
7
+ var message = msg;
8
+ var serialId = message.serialId;
9
+ // 不是 jsapi 的调用的消息
10
+ if (message.type !== 'apiCall') return;
11
+ if (!serialId) return;
12
+ if (!callMap[serialId]) return;
13
+ var callback = callMap[serialId];
14
+ var data = message.result;
15
+ var type = (_a = message.config) === null || _a === void 0 ? void 0 : _a.type; // JsApi 的类型
16
+ if (type === 'callback') {
17
+ var _b = data || {},
18
+ _data_1 = _b._data_,
19
+ _type_1 = _b._type_;
20
+ if (_type_1 === 'success') return callback(_data_1);
21
+ return callback(undefined, _data_1);
27
22
  }
28
- };
29
- var callbackFn = function callbackFn(res, callback) {
30
- var _a = callback || {},
31
- success = _a.success,
32
- fail = _a.fail,
33
- complete = _a.complete;
34
- var _b = res || {},
35
- _data_ = _b._data_,
36
- _type_ = _b._type_;
23
+ var _c = callback || {},
24
+ success = _c.success,
25
+ fail = _c.fail,
26
+ complete = _c.complete;
27
+ var _d = data || {},
28
+ _data_ = _d._data_,
29
+ _type_ = _d._type_;
37
30
  // 新版本协议
38
31
  if (_type_) {
39
32
  if (_type_ === 'success') success === null || success === void 0 ? void 0 : success(_data_);
40
33
  if (_type_ === 'fail') fail === null || fail === void 0 ? void 0 : fail(_data_);
41
- return complete === null || complete === void 0 ? void 0 : complete(_data_);
42
- }
43
- // 下面兼容老版本(老版本消息识别不明确,导致 H5 中走 success/fail 逻辑可能岔了)
44
- // @ts-ignore
45
- if (res === null || res === void 0 ? void 0 : res.error) {
46
- fail === null || fail === void 0 ? void 0 : fail(res);
34
+ complete === null || complete === void 0 ? void 0 : complete(_data_);
47
35
  } else {
48
- success === null || success === void 0 ? void 0 : success(res);
49
- }
50
- complete === null || complete === void 0 ? void 0 : complete(res);
51
- };
52
- export var mpWebCall = function () {
53
- var callMap = {};
54
- var WAITING_QUEUE = [];
55
- var isListening = false;
56
- function onMessage() {
57
- var messageHandler = window.my.onMessage;
58
- window.my.onMessage = function (message) {
59
- var _a;
60
- var serialId = message.serialId;
61
- var data = message.result;
62
- var type = (_a = message.config) === null || _a === void 0 ? void 0 : _a.type; // JsApi 的类型
63
- if (serialId) {
64
- var callback = callMap[serialId];
65
- if (!callback) return;
66
- if (type === 'callback') {
67
- callback(data);
68
- } else {
69
- callbackFn(data, callback);
70
- delete callMap[serialId];
71
- }
72
- } else if (messageHandler) {
73
- messageHandler(message);
74
- }
75
- };
76
- }
77
- function fireMessage(_a) {
78
- var api = _a.api,
79
- options = _a.options,
80
- config = _a.config;
81
- var random = Math.floor(Math.random() * 1000000);
82
- var serialId = api + '_' + random;
83
- if (options) {
84
- callMap[serialId] = options;
36
+ // 下面兼容老版本(老版本消息识别不明确,导致 H5 中走 success/fail 逻辑可能岔了)
37
+ // @ts-ignore
38
+ if (data === null || data === void 0 ? void 0 : data.error) {
39
+ fail === null || fail === void 0 ? void 0 : fail(data);
40
+ } else {
41
+ success === null || success === void 0 ? void 0 : success(data);
85
42
  }
86
- var params = {
87
- source: 'hylid',
88
- type: 'apiCall',
89
- api: api,
90
- serialId: serialId,
91
- options: options,
92
- config: config
93
- };
94
- window.my.postMessage(params);
43
+ complete === null || complete === void 0 ? void 0 : complete(data);
44
+ }
45
+ delete callMap[serialId];
46
+ });
47
+ export function mpWebCall(api, options, config) {
48
+ var random = Math.floor(Math.random() * 1000000);
49
+ var serialId = api + '_' + random;
50
+ // 只调用,没有参数,不需要接收 jsapi 执行结果
51
+ if (options) {
52
+ callMap[serialId] = options;
95
53
  }
96
- return function call(api, options, config) {
97
- loadAppxBridge(function (bridgeReady) {
98
- var params = {
99
- api: api,
100
- options: options,
101
- config: config
102
- };
103
- if (bridgeReady) {
104
- if (!isListening) {
105
- onMessage();
106
- isListening = true;
107
- }
108
- if (WAITING_QUEUE.length) {
109
- WAITING_QUEUE.forEach(fireMessage);
110
- WAITING_QUEUE = [];
111
- }
112
- fireMessage(params);
113
- } else {
114
- WAITING_QUEUE.push(params);
115
- }
116
- });
54
+ var message = {
55
+ source: 'hylid',
56
+ type: 'apiCall',
57
+ api: api,
58
+ serialId: serialId,
59
+ options: options,
60
+ config: config
61
+ };
62
+ mpWebPostMessage(message);
63
+ }
64
+ function broadcastGlobalData(key, result) {
65
+ var message = {
66
+ source: 'hylid',
67
+ type: 'broadcast',
68
+ from: window.location.href,
69
+ key: key,
70
+ result: result
117
71
  };
118
- }();
72
+ mpWebPostMessage(message);
73
+ }
74
+ function onReceiveGlobalData(key, callback) {
75
+ return mpWebOnMessage(function (msg) {
76
+ var message = msg;
77
+ if (message.source !== 'hylid') return;
78
+ if (message.type !== 'broadcast') return;
79
+ // 不是接收的目标消息
80
+ if (message.key !== key) return;
81
+ var _a = message.result || {},
82
+ _data_ = _a._data_,
83
+ _type_ = _a._type_;
84
+ if (_type_ === 'success') return callback(_data_, undefined, message.from);
85
+ return callback(undefined, _data_, message.from);
86
+ });
87
+ }
88
+ function onPageEvent(event, callback) {
89
+ // 告诉小程序侧,监听 event 事件
90
+ mpWebPostMessage({
91
+ source: 'hylid',
92
+ type: 'pageEvent',
93
+ event: event
94
+ });
95
+ return mpWebOnMessage(function (msg) {
96
+ var message = msg;
97
+ if (message.source !== 'hylid') return;
98
+ if (message.type !== 'pageEvent') return;
99
+ if (message.event !== event) return;
100
+ var _a = message.result || {},
101
+ _data_ = _a._data_,
102
+ _type_ = _a._type_;
103
+ if (_type_ === 'success') return callback(_data_);
104
+ return callback(undefined, _data_);
105
+ });
106
+ }
107
+ mpWebCall.onMessage = mpWebOnMessage;
108
+ mpWebCall.postMessage = mpWebPostMessage;
109
+ mpWebCall.broadcastGlobalData = broadcastGlobalData;
110
+ mpWebCall.onReceiveGlobalData = onReceiveGlobalData;
111
+ mpWebCall.onPageEvent = onPageEvent;
package/lib/notFound.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createError } from "./utils";
1
2
  export var notFound = function notFound(name, opt, config) {
2
3
  var _a;
3
4
  if (config === void 0) {
@@ -5,10 +6,7 @@ export var notFound = function notFound(name, opt, config) {
5
6
  }
6
7
  var _b = config.type,
7
8
  type = _b === void 0 ? 'async' : _b;
8
- var response = {
9
- error: -1,
10
- errorMessage: "".concat(name, " is not found")
11
- };
9
+ var response = createError('NOTFOUND', name);
12
10
  if (type === 'sync') return response;
13
11
  if (type === 'callback') {
14
12
  opt === null || opt === void 0 ? void 0 : opt(response);
package/lib/types.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { JsApiType, MPApi } from '@hylid/types';
1
+ import { JsApiType, MPApi, PickMPArgs, PickMpReturns } from '@hylid/types';
2
2
  export declare type JsApi = keyof MPApi;
3
3
  export interface MpWebJsApiConfig {
4
4
  type?: JsApiType;
5
5
  }
6
6
  export declare type Config = MpWebJsApiConfig;
7
- export interface MpWebMessageResult {
7
+ export interface MpWebMessageResult<T = any> {
8
8
  _type_: 'success' | 'fail';
9
- _data_: any;
9
+ _data_: T;
10
10
  }
11
- export interface MpWebMessage {
11
+ export interface MpWebJsApiMessage {
12
12
  source: 'hylid';
13
13
  type: 'apiCall';
14
14
  api: string;
@@ -17,4 +17,35 @@ export interface MpWebMessage {
17
17
  config?: MpWebJsApiConfig;
18
18
  result?: MpWebMessageResult;
19
19
  }
20
- export declare type JsApiInfo = Pick<MpWebMessage, 'api' | 'options' | 'config'>;
20
+ export interface MpWebBroadcastMessage {
21
+ source: 'hylid';
22
+ type: 'broadcast';
23
+ from: string;
24
+ key: string;
25
+ result?: MpWebMessageResult;
26
+ }
27
+ export interface MpWebPageEventMessage {
28
+ source: 'hylid';
29
+ type: 'pageEvent';
30
+ event: 'onShow' | 'onHide' | 'onTitleClick' | 'onOptionMenuClick' | 'onTabItemTap' | ({} & string);
31
+ result?: MpWebMessageResult;
32
+ }
33
+ export declare type Message = MpWebJsApiMessage | MpWebBroadcastMessage | MpWebPageEventMessage;
34
+ export declare type MessageHandler = (message: Message) => void;
35
+ declare type Callback<T> = (result?: T) => void;
36
+ export declare type MpWebJsApiOptions<T extends keyof MPApi> = PickMPArgs<T> | Callback<PickMpReturns<T>>;
37
+ export interface WebviewBridgeConfig {
38
+ /** 允许调用 jsApi 的白名单 */
39
+ whitelist?: string[];
40
+ /** 禁止调用 jsApi 的黑名单 */
41
+ blacklist?: string[];
42
+ /** 自定义 jsApi [ 优先级比较高,可以覆盖原生的 jsApi ] */
43
+ customApi?: CustomApi;
44
+ }
45
+ export interface CustomApi {
46
+ [key: string]: (params: {
47
+ success(v: any): void;
48
+ fail(v: any): void;
49
+ }) => void;
50
+ }
51
+ export {};
package/lib/utils.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { MpWebMessageResult } from './types';
2
+ declare const ERROR: {
3
+ NOTFOUND: {
4
+ code: number;
5
+ message: (name: string) => string;
6
+ };
7
+ NOTALLOWED: {
8
+ code: number;
9
+ message: (name: string) => string;
10
+ };
11
+ INVALID: {
12
+ code: number;
13
+ message: (name: string) => string;
14
+ };
15
+ NOTBIND: {
16
+ code: number;
17
+ message: (name: string) => string;
18
+ };
19
+ };
20
+ export declare const createError: (type: keyof typeof ERROR, name: string) => {
21
+ errorCode: number;
22
+ errorMessage: string;
23
+ };
24
+ export declare function createMessage(message: any, type?: 'success' | 'fail'): MpWebMessageResult;
25
+ export {};
package/lib/utils.js ADDED
@@ -0,0 +1,44 @@
1
+ var ERROR = {
2
+ NOTFOUND: {
3
+ code: -1,
4
+ message: function message(name) {
5
+ return "".concat(name, " is not found");
6
+ }
7
+ },
8
+ NOTALLOWED: {
9
+ code: -2,
10
+ message: function message(name) {
11
+ return "".concat(name, " is not allowed");
12
+ }
13
+ },
14
+ INVALID: {
15
+ code: -3,
16
+ message: function message(name) {
17
+ return "".concat(name, " is invalid");
18
+ }
19
+ },
20
+ NOTBIND: {
21
+ code: -4,
22
+ message: function message(name) {
23
+ return "".concat(name, " exec fail, webviewBridge not bind context");
24
+ }
25
+ }
26
+ };
27
+ export var createError = function createError(type, name) {
28
+ var _a = ERROR[type],
29
+ code = _a.code,
30
+ message = _a.message;
31
+ return {
32
+ errorCode: code,
33
+ errorMessage: message(name)
34
+ };
35
+ };
36
+ export function createMessage(message, type) {
37
+ if (type === void 0) {
38
+ type = 'success';
39
+ }
40
+ return {
41
+ _type_: type,
42
+ _data_: message
43
+ };
44
+ }
@@ -0,0 +1,26 @@
1
+ import { Message, WebviewBridgeConfig } from '../types';
2
+ interface WebViewContext {
3
+ postMessage(message: Message): void;
4
+ }
5
+ export declare class WebViewBridge {
6
+ private webview;
7
+ private config;
8
+ private context;
9
+ private MESSAGE_HANDLER;
10
+ /**
11
+ *
12
+ * @param webviewId webview 组件的 id,可传字符串,或者 my.createWebViewContext 创建出的实例
13
+ * @param config Config 配置
14
+ * @param context 页面上下文,传 this 即可。传入后,H5 侧可以使用广播、可以监听页面事件
15
+ */
16
+ constructor(webviewId: string | WebViewContext, config?: WebviewBridgeConfig, context?: any);
17
+ listen: (data: {
18
+ detail: Message;
19
+ }) => void;
20
+ private jsApiHandler;
21
+ private broadcastHandler;
22
+ private pageEventHandler;
23
+ private bindCtxEvent;
24
+ private sendMessage;
25
+ }
26
+ export {};
@@ -0,0 +1,124 @@
1
+ var __assign = this && this.__assign || function () {
2
+ __assign = Object.assign || function (t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
6
+ }
7
+ return t;
8
+ };
9
+ return __assign.apply(this, arguments);
10
+ };
11
+ import { callbackApi, getApiResult, isAllowed } from "./utils";
12
+ import { createMessage, createError } from "../utils";
13
+ var broadcastTargets = [];
14
+ var WebViewBridge = /** @class */function () {
15
+ /**
16
+ *
17
+ * @param webviewId webview 组件的 id,可传字符串,或者 my.createWebViewContext 创建出的实例
18
+ * @param config Config 配置
19
+ * @param context 页面上下文,传 this 即可。传入后,H5 侧可以使用广播、可以监听页面事件
20
+ */
21
+ function WebViewBridge(webviewId, config, context) {
22
+ if (config === void 0) {
23
+ config = {};
24
+ }
25
+ var _this = this;
26
+ this.config = {};
27
+ this.MESSAGE_HANDLER = [];
28
+ this.listen = function (data) {
29
+ if (data.detail.source !== 'hylid') return;
30
+ _this.MESSAGE_HANDLER.forEach(function (fn) {
31
+ return fn(data.detail);
32
+ });
33
+ };
34
+ this.jsApiHandler = function (data) {
35
+ if (data.type !== 'apiCall') return;
36
+ var config = data.config,
37
+ api = data.api;
38
+ var type = (config || {}).type;
39
+ // 权限管控不允许调用 JSAPI
40
+ if (!isAllowed(_this.config, api)) {
41
+ return _this.sendMessage(data, createMessage(createError('NOTALLOWED', api), 'fail'));
42
+ }
43
+ if (type === 'callback') {
44
+ callbackApi(api, data, function (result) {
45
+ return _this.sendMessage(data, result);
46
+ });
47
+ } else {
48
+ getApiResult(_this.config.customApi, data).then(function (result) {
49
+ _this.sendMessage(data, result);
50
+ });
51
+ }
52
+ };
53
+ this.broadcastHandler = function (data) {
54
+ if (data.type !== 'broadcast') return;
55
+ if (!_this.context) {
56
+ _this.sendMessage(data, createMessage(createError('NOTBIND', 'broadcast'), 'fail'));
57
+ return;
58
+ }
59
+ broadcastTargets.forEach(function (target) {
60
+ if (target === _this) return;
61
+ _this.sendMessage(data, createMessage(data.result), target);
62
+ });
63
+ };
64
+ this.pageEventHandler = function (data) {
65
+ var _a;
66
+ if (data.type !== 'pageEvent') return;
67
+ var event = data.event;
68
+ if (!event) {
69
+ _this.sendMessage(data, createMessage(createError('NOTFOUND', event), 'fail'));
70
+ return;
71
+ }
72
+ if (!_this.context) {
73
+ _this.sendMessage(data, createMessage(createError('NOTBIND', event), 'fail'));
74
+ return;
75
+ }
76
+ // 已经监听过了
77
+ if ((_a = _this.context[event]) === null || _a === void 0 ? void 0 : _a._hy_listener_) return;
78
+ _this.bindCtxEvent(event, function (payload) {
79
+ return _this.sendMessage(data, createMessage(payload));
80
+ });
81
+ _this.context[event]._hy_listener_ = true;
82
+ };
83
+ if (typeof webviewId === 'string') {
84
+ this.webview = my.createWebViewContext(webviewId);
85
+ } else {
86
+ this.webview = webviewId;
87
+ }
88
+ this.config = config;
89
+ this.context = context;
90
+ this.MESSAGE_HANDLER.push(this.jsApiHandler);
91
+ this.MESSAGE_HANDLER.push(this.broadcastHandler);
92
+ this.MESSAGE_HANDLER.push(this.pageEventHandler);
93
+ if (context) {
94
+ broadcastTargets.push(this);
95
+ this.bindCtxEvent('onUnload', function () {
96
+ broadcastTargets = broadcastTargets.filter(function (target) {
97
+ return target !== _this;
98
+ });
99
+ });
100
+ } else {
101
+ console.info("[hylid-call]: context \u5728\u5C0F\u7A0B\u5E8F\u4FA7\u672A\u4F20\u5165\uFF0Cbroadcast \u529F\u80FD\u3001\u9875\u9762\u76D1\u542C\u5C06\u65E0\u6CD5\u4F7F\u7528");
102
+ }
103
+ }
104
+ WebViewBridge.prototype.bindCtxEvent = function (event, callback) {
105
+ if (!this.context) {
106
+ return callback(createMessage(createError('NOTBIND', event), 'fail'));
107
+ }
108
+ var userEvent = this.context[event];
109
+ this.context[event] = function (opts) {
110
+ if (userEvent) userEvent.bind(this.context)(opts);
111
+ callback(createMessage(opts));
112
+ };
113
+ };
114
+ WebViewBridge.prototype.sendMessage = function (origin, result, context) {
115
+ if (context === void 0) {
116
+ context = this;
117
+ }
118
+ context.webview.postMessage(__assign(__assign({}, origin), {
119
+ result: result
120
+ }));
121
+ };
122
+ return WebViewBridge;
123
+ }();
124
+ export { WebViewBridge };
@@ -0,0 +1,3 @@
1
+ export declare function canIUse(payload: {
2
+ jsapi: string;
3
+ }): boolean;
@@ -0,0 +1,4 @@
1
+ export function canIUse(payload) {
2
+ var jsapi = payload.jsapi;
3
+ return my.canIUse(jsapi);
4
+ }
@@ -0,0 +1 @@
1
+ export declare function _getCurrentPages(): any[];
@@ -0,0 +1,6 @@
1
+ export function _getCurrentPages() {
2
+ if (typeof getCurrentPages === 'undefined') {
3
+ return [];
4
+ }
5
+ return getCurrentPages();
6
+ }
@@ -0,0 +1,18 @@
1
+ import { _getCurrentPages as getCurrentPages } from './getCurrentPages';
2
+ import { getMemory, removeMemory, setMemory } from './memory';
3
+ import { canIUse } from './canIUse';
4
+ declare const jsapis: {
5
+ getMemory: typeof getMemory;
6
+ setMemory: typeof setMemory;
7
+ removeMemory: typeof removeMemory;
8
+ getCurrentPages: typeof getCurrentPages;
9
+ canIUse: typeof canIUse;
10
+ };
11
+ interface InternalOptions {
12
+ name: keyof typeof jsapis;
13
+ payload: any;
14
+ success(res: any): void;
15
+ fail(e: any): void;
16
+ }
17
+ export declare function __hy_internal__(options: InternalOptions): Promise<void>;
18
+ export {};
@@ -0,0 +1,156 @@
1
+ var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) {
3
+ return value instanceof P ? value : new P(function (resolve) {
4
+ resolve(value);
5
+ });
6
+ }
7
+ return new (P || (P = Promise))(function (resolve, reject) {
8
+ function fulfilled(value) {
9
+ try {
10
+ step(generator.next(value));
11
+ } catch (e) {
12
+ reject(e);
13
+ }
14
+ }
15
+ function rejected(value) {
16
+ try {
17
+ step(generator["throw"](value));
18
+ } catch (e) {
19
+ reject(e);
20
+ }
21
+ }
22
+ function step(result) {
23
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
24
+ }
25
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
26
+ });
27
+ };
28
+ var __generator = this && this.__generator || function (thisArg, body) {
29
+ var _ = {
30
+ label: 0,
31
+ sent: function sent() {
32
+ if (t[0] & 1) throw t[1];
33
+ return t[1];
34
+ },
35
+ trys: [],
36
+ ops: []
37
+ },
38
+ f,
39
+ y,
40
+ t,
41
+ g;
42
+ return g = {
43
+ next: verb(0),
44
+ "throw": verb(1),
45
+ "return": verb(2)
46
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
47
+ return this;
48
+ }), g;
49
+ function verb(n) {
50
+ return function (v) {
51
+ return step([n, v]);
52
+ };
53
+ }
54
+ function step(op) {
55
+ if (f) throw new TypeError("Generator is already executing.");
56
+ while (_) try {
57
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
58
+ if (y = 0, t) op = [op[0] & 2, t.value];
59
+ switch (op[0]) {
60
+ case 0:
61
+ case 1:
62
+ t = op;
63
+ break;
64
+ case 4:
65
+ _.label++;
66
+ return {
67
+ value: op[1],
68
+ done: false
69
+ };
70
+ case 5:
71
+ _.label++;
72
+ y = op[1];
73
+ op = [0];
74
+ continue;
75
+ case 7:
76
+ op = _.ops.pop();
77
+ _.trys.pop();
78
+ continue;
79
+ default:
80
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
81
+ _ = 0;
82
+ continue;
83
+ }
84
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
85
+ _.label = op[1];
86
+ break;
87
+ }
88
+ if (op[0] === 6 && _.label < t[1]) {
89
+ _.label = t[1];
90
+ t = op;
91
+ break;
92
+ }
93
+ if (t && _.label < t[2]) {
94
+ _.label = t[2];
95
+ _.ops.push(op);
96
+ break;
97
+ }
98
+ if (t[2]) _.ops.pop();
99
+ _.trys.pop();
100
+ continue;
101
+ }
102
+ op = body.call(thisArg, _);
103
+ } catch (e) {
104
+ op = [6, e];
105
+ y = 0;
106
+ } finally {
107
+ f = t = 0;
108
+ }
109
+ if (op[0] & 5) throw op[1];
110
+ return {
111
+ value: op[0] ? op[1] : void 0,
112
+ done: true
113
+ };
114
+ }
115
+ };
116
+ import { _getCurrentPages as getCurrentPages } from "./getCurrentPages";
117
+ import { getMemory, removeMemory, setMemory } from "./memory";
118
+ import { canIUse } from "./canIUse";
119
+ import { createError } from "../../utils";
120
+ var jsapis = {
121
+ getMemory: getMemory,
122
+ setMemory: setMemory,
123
+ removeMemory: removeMemory,
124
+ getCurrentPages: getCurrentPages,
125
+ canIUse: canIUse
126
+ };
127
+ export function __hy_internal__(options) {
128
+ return __awaiter(this, void 0, void 0, function () {
129
+ var _a, success, fail, name, payload, jsapi, res, e_1;
130
+ return __generator(this, function (_b) {
131
+ switch (_b.label) {
132
+ case 0:
133
+ _a = options || {}, success = _a.success, fail = _a.fail, name = _a.name, payload = _a.payload;
134
+ jsapi = jsapis[name];
135
+ if (!jsapi) {
136
+ fail(createError('NOTFOUND', name));
137
+ return [2 /*return*/];
138
+ }
139
+ _b.label = 1;
140
+ case 1:
141
+ _b.trys.push([1, 3,, 4]);
142
+ return [4 /*yield*/, jsapi(payload)];
143
+ case 2:
144
+ res = _b.sent();
145
+ success(res);
146
+ return [3 /*break*/, 4];
147
+ case 3:
148
+ e_1 = _b.sent();
149
+ fail(e_1);
150
+ return [3 /*break*/, 4];
151
+ case 4:
152
+ return [2 /*return*/];
153
+ }
154
+ });
155
+ });
156
+ }
@@ -0,0 +1,10 @@
1
+ export declare function getMemory(payload: {
2
+ key: string;
3
+ }): any;
4
+ export declare function setMemory(payload: {
5
+ key: string;
6
+ value: any;
7
+ }): void;
8
+ export declare function removeMemory(payload: {
9
+ key: string;
10
+ }): void;
@@ -0,0 +1,12 @@
1
+ var data = {};
2
+ export function getMemory(payload) {
3
+ return data[payload.key];
4
+ }
5
+ export function setMemory(payload) {
6
+ data[payload.key] = {
7
+ data: payload.value
8
+ };
9
+ }
10
+ export function removeMemory(payload) {
11
+ delete data[payload.key];
12
+ }
@@ -0,0 +1,4 @@
1
+ import { MpWebJsApiMessage, CustomApi, MpWebMessageResult, WebviewBridgeConfig } from '../types';
2
+ export declare function callbackApi(apiName: string, jsapi: any, cb: (msg: MpWebMessageResult) => void): void;
3
+ export declare const getApiResult: (customApi: CustomApi | undefined, data: MpWebJsApiMessage) => Promise<MpWebMessageResult>;
4
+ export declare function isAllowed(config: WebviewBridgeConfig, api: string): boolean;
@@ -0,0 +1,201 @@
1
+ var __assign = this && this.__assign || function () {
2
+ __assign = Object.assign || function (t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
6
+ }
7
+ return t;
8
+ };
9
+ return __assign.apply(this, arguments);
10
+ };
11
+ var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) {
13
+ return value instanceof P ? value : new P(function (resolve) {
14
+ resolve(value);
15
+ });
16
+ }
17
+ return new (P || (P = Promise))(function (resolve, reject) {
18
+ function fulfilled(value) {
19
+ try {
20
+ step(generator.next(value));
21
+ } catch (e) {
22
+ reject(e);
23
+ }
24
+ }
25
+ function rejected(value) {
26
+ try {
27
+ step(generator["throw"](value));
28
+ } catch (e) {
29
+ reject(e);
30
+ }
31
+ }
32
+ function step(result) {
33
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
34
+ }
35
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
36
+ });
37
+ };
38
+ var __generator = this && this.__generator || function (thisArg, body) {
39
+ var _ = {
40
+ label: 0,
41
+ sent: function sent() {
42
+ if (t[0] & 1) throw t[1];
43
+ return t[1];
44
+ },
45
+ trys: [],
46
+ ops: []
47
+ },
48
+ f,
49
+ y,
50
+ t,
51
+ g;
52
+ return g = {
53
+ next: verb(0),
54
+ "throw": verb(1),
55
+ "return": verb(2)
56
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
57
+ return this;
58
+ }), g;
59
+ function verb(n) {
60
+ return function (v) {
61
+ return step([n, v]);
62
+ };
63
+ }
64
+ function step(op) {
65
+ if (f) throw new TypeError("Generator is already executing.");
66
+ while (_) try {
67
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
68
+ if (y = 0, t) op = [op[0] & 2, t.value];
69
+ switch (op[0]) {
70
+ case 0:
71
+ case 1:
72
+ t = op;
73
+ break;
74
+ case 4:
75
+ _.label++;
76
+ return {
77
+ value: op[1],
78
+ done: false
79
+ };
80
+ case 5:
81
+ _.label++;
82
+ y = op[1];
83
+ op = [0];
84
+ continue;
85
+ case 7:
86
+ op = _.ops.pop();
87
+ _.trys.pop();
88
+ continue;
89
+ default:
90
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
91
+ _ = 0;
92
+ continue;
93
+ }
94
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
95
+ _.label = op[1];
96
+ break;
97
+ }
98
+ if (op[0] === 6 && _.label < t[1]) {
99
+ _.label = t[1];
100
+ t = op;
101
+ break;
102
+ }
103
+ if (t && _.label < t[2]) {
104
+ _.label = t[2];
105
+ _.ops.push(op);
106
+ break;
107
+ }
108
+ if (t[2]) _.ops.pop();
109
+ _.trys.pop();
110
+ continue;
111
+ }
112
+ op = body.call(thisArg, _);
113
+ } catch (e) {
114
+ op = [6, e];
115
+ y = 0;
116
+ } finally {
117
+ f = t = 0;
118
+ }
119
+ if (op[0] & 5) throw op[1];
120
+ return {
121
+ value: op[0] ? op[1] : void 0,
122
+ done: true
123
+ };
124
+ }
125
+ };
126
+ import { createMessage, createError } from "../utils";
127
+ import { __hy_internal__ } from "./internal";
128
+ function getSyncApi(apiName, jsapi, options) {
129
+ // 同步场景无该 API
130
+ if (!jsapi) {
131
+ return createMessage(createError('NOTFOUND', apiName), 'fail');
132
+ }
133
+ // 传进来的 API 不是函数
134
+ if (typeof jsapi !== 'function') {
135
+ return createMessage(createError('INVALID', apiName), 'fail');
136
+ }
137
+ return createMessage(jsapi(options));
138
+ }
139
+ function getAsyncApi(apiName, jsapi, _options) {
140
+ return new Promise(function (resolve) {
141
+ var options = __assign(__assign({}, _options), {
142
+ success: function success(res) {
143
+ resolve(createMessage(res));
144
+ },
145
+ fail: function fail(res) {
146
+ resolve(createMessage(res, 'fail'));
147
+ }
148
+ });
149
+ // @ts-ignore
150
+ if (!jsapi) return my.call(api, options);
151
+ if (typeof jsapi !== 'function') {
152
+ return options.fail(createError('INVALID', apiName));
153
+ }
154
+ jsapi(options);
155
+ });
156
+ }
157
+ export function callbackApi(apiName, jsapi, cb) {
158
+ // 无该 API
159
+ if (!jsapi) {
160
+ return cb(createMessage(createError('NOTFOUND', apiName), 'fail'));
161
+ }
162
+ // 传进来的 API 不是函数
163
+ if (typeof jsapi !== 'function') {
164
+ return cb(createMessage(createError('INVALID', apiName), 'fail'));
165
+ }
166
+ jsapi(function (result) {
167
+ return cb(createMessage(result));
168
+ });
169
+ }
170
+ export var getApiResult = function getApiResult(customApi, data) {
171
+ if (customApi === void 0) {
172
+ customApi = {};
173
+ }
174
+ return __awaiter(void 0, void 0, void 0, function () {
175
+ var api, options, config, _a, type, jsapi;
176
+ return __generator(this, function (_b) {
177
+ api = data.api, options = data.options, config = data.config;
178
+ _a = (config || {}).type, type = _a === void 0 ? 'async' : _a;
179
+ jsapi = customApi[api] || {
180
+ __hy_internal__: __hy_internal__
181
+ }[api] || my[api];
182
+ if (type === 'sync') {
183
+ return [2 /*return*/, getSyncApi(api, jsapi, options)];
184
+ }
185
+ if (type === 'async') {
186
+ return [2 /*return*/, getAsyncApi(api, jsapi, options)];
187
+ }
188
+ // 不识别的类型
189
+ return [2 /*return*/, createMessage(createError('INVALID', api), 'fail')];
190
+ });
191
+ });
192
+ };
193
+ export function isAllowed(config, api) {
194
+ var _a = config || {},
195
+ whitelist = _a.whitelist,
196
+ blacklist = _a.blacklist;
197
+ // 黑白名单校验
198
+ if (whitelist && !whitelist.includes(api)) return false;
199
+ if (blacklist && blacklist.includes(api)) return false;
200
+ return true;
201
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@hylid/call",
3
- "version": "3.2.0-alpha.0",
3
+ "version": "3.2.0-alpha.2",
4
4
  "main": "lib/index.js",
5
5
  "files": [
6
6
  "lib"
7
7
  ],
8
8
  "dependencies": {
9
- "@hylid/env": "^3.2.0-alpha.0",
10
- "@hylid/types": "^3.2.0-alpha.0"
9
+ "@hylid/env": "^3.2.0-alpha.2",
10
+ "@hylid/types": "^3.2.0-alpha.2"
11
11
  },
12
12
  "publishConfig": {
13
13
  "access": "public"
@@ -1,24 +0,0 @@
1
- /// <reference types="miniprogram" />
2
- import { MpWebMessage } from './types';
3
- interface Config {
4
- whitelist?: string[];
5
- blacklist?: string[];
6
- customApi?: CustomApi;
7
- }
8
- interface CustomApi {
9
- [key: string]: (params: {
10
- success(v: any): void;
11
- fail(v: any): void;
12
- }) => void;
13
- }
14
- export declare class WebViewBridge {
15
- webview: WebViewContext;
16
- config: Config;
17
- constructor(ctx: WebViewContext, config?: Config);
18
- listen: (data: {
19
- detail: MpWebMessage;
20
- }) => Promise<true | undefined>;
21
- isAllowed(api: string): boolean;
22
- handleApi: (data: MpWebMessage) => Promise<unknown>;
23
- }
24
- export {};
@@ -1,229 +0,0 @@
1
- var __assign = this && this.__assign || function () {
2
- __assign = Object.assign || function (t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
6
- }
7
- return t;
8
- };
9
- return __assign.apply(this, arguments);
10
- };
11
- var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
12
- function adopt(value) {
13
- return value instanceof P ? value : new P(function (resolve) {
14
- resolve(value);
15
- });
16
- }
17
- return new (P || (P = Promise))(function (resolve, reject) {
18
- function fulfilled(value) {
19
- try {
20
- step(generator.next(value));
21
- } catch (e) {
22
- reject(e);
23
- }
24
- }
25
- function rejected(value) {
26
- try {
27
- step(generator["throw"](value));
28
- } catch (e) {
29
- reject(e);
30
- }
31
- }
32
- function step(result) {
33
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
34
- }
35
- step((generator = generator.apply(thisArg, _arguments || [])).next());
36
- });
37
- };
38
- var __generator = this && this.__generator || function (thisArg, body) {
39
- var _ = {
40
- label: 0,
41
- sent: function sent() {
42
- if (t[0] & 1) throw t[1];
43
- return t[1];
44
- },
45
- trys: [],
46
- ops: []
47
- },
48
- f,
49
- y,
50
- t,
51
- g;
52
- return g = {
53
- next: verb(0),
54
- "throw": verb(1),
55
- "return": verb(2)
56
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
57
- return this;
58
- }), g;
59
- function verb(n) {
60
- return function (v) {
61
- return step([n, v]);
62
- };
63
- }
64
- function step(op) {
65
- if (f) throw new TypeError("Generator is already executing.");
66
- while (_) try {
67
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
68
- if (y = 0, t) op = [op[0] & 2, t.value];
69
- switch (op[0]) {
70
- case 0:
71
- case 1:
72
- t = op;
73
- break;
74
- case 4:
75
- _.label++;
76
- return {
77
- value: op[1],
78
- done: false
79
- };
80
- case 5:
81
- _.label++;
82
- y = op[1];
83
- op = [0];
84
- continue;
85
- case 7:
86
- op = _.ops.pop();
87
- _.trys.pop();
88
- continue;
89
- default:
90
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
91
- _ = 0;
92
- continue;
93
- }
94
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
95
- _.label = op[1];
96
- break;
97
- }
98
- if (op[0] === 6 && _.label < t[1]) {
99
- _.label = t[1];
100
- t = op;
101
- break;
102
- }
103
- if (t && _.label < t[2]) {
104
- _.label = t[2];
105
- _.ops.push(op);
106
- break;
107
- }
108
- if (t[2]) _.ops.pop();
109
- _.trys.pop();
110
- continue;
111
- }
112
- op = body.call(thisArg, _);
113
- } catch (e) {
114
- op = [6, e];
115
- y = 0;
116
- } finally {
117
- f = t = 0;
118
- }
119
- if (op[0] & 5) throw op[1];
120
- return {
121
- value: op[0] ? op[1] : void 0,
122
- done: true
123
- };
124
- }
125
- };
126
- var WebViewBridge = /** @class */function () {
127
- function WebViewBridge(ctx, config) {
128
- if (config === void 0) {
129
- config = {};
130
- }
131
- var _this = this;
132
- this.config = {};
133
- this.listen = function (data) {
134
- return __awaiter(_this, void 0, void 0, function () {
135
- var command, config, api, type, notAllowedMessage;
136
- var _this = this;
137
- return __generator(this, function (_a) {
138
- command = data.detail;
139
- if (command.source === 'hylid') {
140
- config = command.config, api = command.api;
141
- type = (config || {}).type;
142
- // 权限管控不允许调用 JSAPI
143
- if (!this.isAllowed(api)) {
144
- notAllowedMessage = __assign(__assign({}, command), {
145
- result: {
146
- _type_: 'fail',
147
- _data_: {
148
- errorCode: -2,
149
- errorMessage: 'api is not allowed'
150
- }
151
- }
152
- });
153
- this.webview.postMessage(notAllowedMessage);
154
- return [2 /*return*/];
155
- }
156
- if (type === 'callback') {
157
- // @ts-ignore
158
- my[api](function (result) {
159
- _this.webview.postMessage(__assign(__assign({}, command), {
160
- result: result
161
- }));
162
- });
163
- } else {
164
- this.handleApi(command).then(function (result) {
165
- _this.webview.postMessage(__assign(__assign({}, command), {
166
- result: result
167
- }));
168
- });
169
- }
170
- // 表示被 hylid-bridge 消费了
171
- return [2 /*return*/, true];
172
- }
173
- return [2 /*return*/];
174
- });
175
- });
176
- };
177
- this.handleApi = function (data) {
178
- var api = data.api,
179
- _options = data.options,
180
- config = data.config;
181
- var _a = (config || {}).type,
182
- type = _a === void 0 ? 'async' : _a;
183
- return new Promise(function (resolve) {
184
- var _a;
185
- var options = __assign(__assign({}, _options), {
186
- success: function success(res) {
187
- resolve({
188
- _type_: 'success',
189
- _data_: res
190
- });
191
- },
192
- fail: function fail(res) {
193
- resolve({
194
- _type_: 'fail',
195
- _data_: res
196
- });
197
- }
198
- });
199
- // @ts-ignore
200
- var mpApi = ((_a = _this.config.customApi) === null || _a === void 0 ? void 0 : _a[api]) || my[api];
201
- if (type === 'sync') {
202
- var data_1 = mpApi(_options);
203
- resolve({
204
- _type_: 'success',
205
- _data_: data_1
206
- });
207
- }
208
- if (type === 'async') {
209
- if (!mpApi) {
210
- // @ts-ignore
211
- my.call(api, options);
212
- } else {
213
- mpApi(options);
214
- }
215
- }
216
- });
217
- };
218
- this.webview = ctx;
219
- this.config = config;
220
- }
221
- WebViewBridge.prototype.isAllowed = function (api) {
222
- // 黑白名单校验
223
- if (this.config.whitelist && !this.config.whitelist.includes(api)) return false;
224
- if (this.config.blacklist && this.config.blacklist.includes(api)) return false;
225
- return true;
226
- };
227
- return WebViewBridge;
228
- }();
229
- export { WebViewBridge };