Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/mp sys 小程序系统信息面板 #123

Merged
merged 9 commits into from
Jan 6, 2025
Merged
37 changes: 24 additions & 13 deletions packages/page-spy-alipay/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import PageSpy, {
setMPSDK,
utilAPI,
Client,
SocketStoreBase,
platformAPI,
} from '@huolala-tech/page-spy-mp-base';
import { SpyClient } from '@huolala-tech/page-spy-types';

Expand All @@ -13,23 +13,23 @@ declare const my: any;
setMPSDK(my);

// alipay toxic storage api...
utilAPI.getStorage = (key: string) => {
platformAPI.getStorageSync = (key: string) => {
const res = my.getStorageSync({ key });
if (res.success) {
return res.data;
}
return undefined;
};

utilAPI.setStorage = (key: string, value: any) => {
platformAPI.setStorageSync = (key: string, value: any) => {
return my.setStorageSync({ key, data: value });
};

utilAPI.removeStorage = (key) => {
platformAPI.removeStorageSync = (key) => {
return my.removeStorageSync({ key });
};

utilAPI.showActionSheet = (params) => {
platformAPI.showActionSheet = (params) => {
return my.showActionSheet({
...params,
items: params.itemList,
Expand All @@ -41,16 +41,27 @@ utilAPI.showActionSheet = (params) => {
});
};

// TODO 个人小程序不支持该 api.. 先不管
platformAPI.setClipboardData = (params) => {
return my.setClipboard({
text: params.data,
...params,
});
};

const info = my.getSystemInfoSync();

PageSpy.client = new Client({
sdk: 'mp-alipay',
osType: info.platform.toLowerCase() as SpyClient.OS,
browserType: 'mp-alipay',
osVersion: info.system,
browserVersion: info.version,
sdkVersion: PKG_VERSION,
});
PageSpy.client = new Client(
{
sdk: 'mp-alipay',
osType: info.platform.toLowerCase() as SpyClient.OS,
browserType: 'mp-alipay',
osVersion: info.system,
browserVersion: info.version,
sdkVersion: PKG_VERSION,
},
info,
);

SocketStoreBase.messageFilters.push((data) => {
return data.data;
Expand Down
2 changes: 2 additions & 0 deletions packages/page-spy-base/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export class Client {
sdk: 'unknown',
sdkVersion: '0.0.0',
},
// the raw info from getSystemInfoSync or similar api, will be sent by system plugin
public rawInfo?: Record<string, any>,
) {}

plugins: string[] = [];
Expand Down
26 changes: 13 additions & 13 deletions packages/page-spy-mp-base/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import type { SpyMP } from '@huolala-tech/page-spy-types';
import { getRandomId } from '@huolala-tech/page-spy-base/dist/utils';
import type { Client } from '@huolala-tech/page-spy-base/dist/client';

import { getMPSDK, joinQuery, promisifyMPApi } from '../utils';
import { joinQuery, promisifyMPApi } from '../utils';
import { Config } from '../config';
import { getMPSDK } from '../helpers/mp-api';

interface TResponse<T> {
code: string;
Expand Down Expand Up @@ -52,17 +53,16 @@ export default class Request {
name: encodeURIComponent(device),
});

return promisifyMPApi<{ data: TResponse<TCreateRoom> }>(getMPSDK().request)(
{
url: `${scheme[0]}${this.base}/api/v1/room/create?${query}`,
method: 'POST',
sslVerify: enableSSL !== false,
data: JSON.stringify({
useSecret,
secret,
}),
},
).then(
return promisifyMPApi(getMPSDK().request<TResponse<TCreateRoom>>)({
url: `${scheme[0]}${this.base}/api/v1/room/create?${query}`,
method: 'POST',
// uniapp building android native need this option.
sslVerify: enableSSL !== false,
data: JSON.stringify({
useSecret,
secret,
}),
}).then(
(res) => {
const { name, address } = res.data?.data || {};
const roomUrl = this.getRoomUrl(address);
Expand All @@ -74,7 +74,7 @@ export default class Request {
},
(err) => {
/* c8 ignore next */
throw Error(`Request create room failed: ${err.message}`);
throw Error(`Request create room failed: ${err.message || err}`);
},
);
}
Expand Down
50 changes: 50 additions & 0 deletions packages/page-spy-mp-base/src/helpers/mp-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Wrap the mp api to smooth the platform differences, for internal usage only.
// This api can be modified by mp sdk implementor.
// This api should be passed through PageSpy instance to avoid esm multi-pack.

import { MPSDK } from '../types';

let mpSDK: any;

// the origin mp sdk, used for hacking
let originMPSDK: any;

if (typeof Proxy !== 'undefined') {
mpSDK = new Proxy(
{},
{
get(target, p: string) {
if (platformAPI[p]) {
return platformAPI[p];
}
if (originMPSDK[p]) {
return originMPSDK[p];
} else {
console.error('The mp sdk does not support the api:', p);
}
},
},
);
}

// for API compatibility
// this api can be modified by mp sdk implementor, to smoothy the platform differences.
export const platformAPI: Record<string, any> = {};
export const getMPSDK = () => {
if (!mpSDK) {
throw Error('the mp sdk is not set');
}
return mpSDK as MPSDK;
};

export const getOriginMPSDK = () => originMPSDK as MPSDK;

export const setMPSDK = (SDK: MPSDK) => {
originMPSDK = SDK;
if (typeof Proxy === 'undefined') {
mpSDK = {
...SDK,
...platformAPI,
};
}
};
5 changes: 3 additions & 2 deletions packages/page-spy-mp-base/src/helpers/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import {
SocketWrapper,
} from '@huolala-tech/page-spy-base/dist/socket-base';
import { ROOM_SESSION_KEY } from '@huolala-tech/page-spy-base/dist/constants';
import { getMPSDK, utilAPI } from '../utils';
import {
MPSocket,
SocketOnCloseHandler,
SocketOnErrorHandler,
SocketOnMessageHandler,
SocketOnOpenHandler,
} from '../types';
import { getMPSDK } from './mp-api';

export class MPSocketWrapper extends SocketWrapper {
public socketInstance: MPSocket | null = null;
Expand Down Expand Up @@ -94,7 +94,8 @@ export class MPSocketStore extends SocketStoreBase {
// this is an abstract method of parent class, cannot be static
/* eslint-disable-next-line */
onOffline() {
utilAPI.removeStorage(ROOM_SESSION_KEY);
const mp = getMPSDK();
mp.removeStorageSync(ROOM_SESSION_KEY);
}
}

Expand Down
32 changes: 16 additions & 16 deletions packages/page-spy-mp-base/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import Request from './api';
// import './index.less';
// eslint-disable-next-line import/order
import { Config } from './config';
import { getMPSDK, utilAPI } from './utils';
import { getMPSDK } from './helpers/mp-api';

type UpdateConfig = {
title?: string;
Expand Down Expand Up @@ -120,7 +120,8 @@ class PageSpy {
updateConfiguration() {
const { messageCapacity, useSecret } = this.config.get();
if (useSecret === true) {
const cache = utilAPI.getStorage(ROOM_SESSION_KEY);
const mp = getMPSDK();
const cache = mp.getStorageSync(ROOM_SESSION_KEY);
const secret = cache?.secret || getAuthSecret();
this.config.set('secret', secret);
psLog.log(`Room Secret: ${secret}`);
Expand All @@ -135,7 +136,7 @@ class PageSpy {
async init() {
const mp = getMPSDK();
const config = this.config.get();
const roomCache = utilAPI.getStorage(ROOM_SESSION_KEY);
const roomCache = mp.getStorageSync(ROOM_SESSION_KEY);
if (!roomCache || typeof roomCache !== 'object') {
await this.createNewConnection();
} else {
Expand Down Expand Up @@ -207,7 +208,7 @@ class PageSpy {
useSecret,
secret,
};
utilAPI.setStorage(ROOM_SESSION_KEY, roomCache);
getMPSDK().setStorageSync(ROOM_SESSION_KEY, roomCache);
}

triggerPlugins<T extends PageSpyPluginLifecycle>(
Expand Down Expand Up @@ -270,17 +271,15 @@ class PageSpy {
{
text: 'PageSpy 房间号:' + this.address.slice(0, 4),
action() {
if (mp.setClipboardData) {
mp.setClipboardData({
data: that.getDebugLink(),
success() {
mp.showToast({
title: '复制成功',
icon: 'success',
});
},
});
}
mp.setClipboardData({
data: that.getDebugLink(),
success() {
mp.showToast({
title: '复制成功',
icon: 'success',
});
},
});
},
},
];
Expand Down Expand Up @@ -309,7 +308,7 @@ class PageSpy {
}
});

utilAPI.showActionSheet({
mp.showActionSheet({
itemColor: '#b67cff',
itemList: options.map((o) => o.text),
success(res) {
Expand Down Expand Up @@ -386,3 +385,4 @@ export { SocketStoreBase, Client, psLog };
export * from './types';
export * from './utils';
export * from './helpers/socket';
export * from './helpers/mp-api';
4 changes: 2 additions & 2 deletions packages/page-spy-mp-base/src/plugins/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
OnInitParams,
} from '@huolala-tech/page-spy-types/index';
import socketStore from '../helpers/socket';
import { getMPSDK } from '../utils';
import { getMPSDK, getOriginMPSDK } from '../helpers/mp-api';

// TODO this plugin should test on multiple platforms
export default class ErrorPlugin implements PageSpyPlugin {
Expand All @@ -33,7 +33,7 @@ export default class ErrorPlugin implements PageSpyPlugin {
}

public onReset() {
const mp = getMPSDK();
const mp = getOriginMPSDK();
if (mp.canIUse('offError')) {
mp.offError(this.errorHandler);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
ReqReadyState,
toLowerKeys,
} from '@huolala-tech/page-spy-base/dist/network/common';
import { getMPSDK } from '../../../utils';
import MPNetworkProxyBase from './base';
import { MPNetworkAPI } from '../../../types';
import { getOriginMPSDK } from '../../../helpers/mp-api';

export default class MPWeixinRequestProxy extends MPNetworkProxyBase {
public request: MPNetworkAPI['request'] | null = null;
Expand All @@ -22,7 +22,7 @@ export default class MPWeixinRequestProxy extends MPNetworkProxyBase {

public reset() {
if (this.request) {
const mp = getMPSDK();
const mp = getOriginMPSDK();
Object.defineProperty(mp, 'request', {
value: this.request,
configurable: true,
Expand All @@ -34,7 +34,7 @@ export default class MPWeixinRequestProxy extends MPNetworkProxyBase {

public initProxyHandler() {
const that = this;
const mp = getMPSDK();
const mp = getOriginMPSDK();
const originRequest = mp.request;

if (!originRequest) {
Expand Down
15 changes: 7 additions & 8 deletions packages/page-spy-mp-base/src/plugins/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import type {
OnInitParams,
} from '@huolala-tech/page-spy-types';
import socketStore from '../helpers/socket';
import { getMPSDK, utilAPI } from '../utils';
import type { MPStorageAPI, KVList } from '../types';
import { getMPSDK, getOriginMPSDK } from '../helpers/mp-api';

const descriptor = {
configurable: true,
Expand Down Expand Up @@ -58,7 +58,7 @@ export default class StoragePlugin implements PageSpyPlugin {
}

public onReset() {
const mp = getMPSDK();
const mp = getOriginMPSDK();
Object.entries(StoragePlugin.originFunctions).forEach(([key, fn]) => {
Object.defineProperty(mp, key, {
value: fn,
Expand All @@ -76,7 +76,7 @@ export default class StoragePlugin implements PageSpyPlugin {
const data = info.keys.map((key) => {
return {
name: key,
value: mpDataStringify(utilAPI.getStorage(key)),
value: mpDataStringify(mp.getStorageSync(key)),
};
});

Expand All @@ -103,7 +103,7 @@ export default class StoragePlugin implements PageSpyPlugin {
/* c8 ignore stop */

public initStorageProxy() {
const mp = getMPSDK();
const mp = getOriginMPSDK();
const proxyFunctions = [
'setStorage',
'setStorageSync',
Expand Down Expand Up @@ -180,13 +180,12 @@ export default class StoragePlugin implements PageSpyPlugin {
},

removeStorageSync: {
// in alipay, the param is an object actually, but it works.
// TODO: really?
value(keyOrObj: string) {
value(keyOrObj: string | { key: string }) {
try {
const res =
StoragePlugin.originFunctions!.removeStorageSync(keyOrObj);
that.sendRemoveItem(keyOrObj);
const key = typeof keyOrObj === 'string' ? keyOrObj : keyOrObj.key;
that.sendRemoveItem(key);
return res;
/* c8 ignore next 4 */
} catch (e) {
Expand Down
Loading
Loading