@blocklet/sdk 1.8.66-beta-7f4224af → 1.8.66-beta.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.
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -25,9 +16,9 @@ const sign = (data) => {
25
16
  const signData = typeof data === 'undefined' ? {} : data;
26
17
  return { 'x-component-sig': wallet.sign((0, json_stable_stringify_1.default)(signData)) };
27
18
  };
28
- const doCall = ({ url, data }) => __awaiter(void 0, void 0, void 0, function* () {
19
+ const doCall = async ({ url, data }) => {
29
20
  try {
30
- const resp = yield axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
21
+ const resp = await axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
31
22
  config_1.logger.info(`call ${url} api success`);
32
23
  return resp;
33
24
  }
@@ -40,7 +31,7 @@ const doCall = ({ url, data }) => __awaiter(void 0, void 0, void 0, function* ()
40
31
  });
41
32
  throw new Error(`call ${url} api failed`);
42
33
  }
43
- });
34
+ };
44
35
  const parsePorts = () => JSON.parse(process.env.BLOCKLET_WEB_PORTS);
45
36
  const getWebEndpoint = (name) => {
46
37
  const ports = parsePorts();
@@ -68,11 +59,11 @@ const parseMountPoints = () => {
68
59
  });
69
60
  return mountPoints;
70
61
  };
71
- const call = ({ name, path: _path, data }) => __awaiter(void 0, void 0, void 0, function* () {
62
+ const call = async ({ name, path: _path, data }) => {
72
63
  const baseURL = name ? getChildWebEndpoint(name) : getParentWebEndpoint();
73
64
  const url = (0, url_join_1.default)(baseURL, _path);
74
65
  return doCall({ url, data });
75
- });
66
+ };
76
67
  exports.call = call;
77
68
  const getComponentMountPoint = (keyword) => {
78
69
  const mountPoints = parseMountPoints();
@@ -9,7 +9,10 @@ const shared_1 = __importDefault(require("./shared"));
9
9
  class BlockletAuthenticator extends authenticator_1.Authenticator {
10
10
  constructor(options = {}) {
11
11
  (0, check_blocklet_env_1.default)();
12
- super(Object.assign({ wallet: (0, wallet_1.default)() }, (0, shared_1.default)(options)));
12
+ super({
13
+ wallet: (0, wallet_1.default)(),
14
+ ...(0, shared_1.default)(options),
15
+ });
13
16
  }
14
17
  }
15
18
  module.exports = BlockletAuthenticator;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -60,8 +51,8 @@ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger,
60
51
  socketPathname,
61
52
  });
62
53
  const originCreateHandler = handlers.handleSessionCreate;
63
- handlers.handleSessionCreate = (context) => __awaiter(void 0, void 0, void 0, function* () {
64
- const session = yield originCreateHandler(context);
54
+ handlers.handleSessionCreate = async (context) => {
55
+ const session = await originCreateHandler(context);
65
56
  const connectedDid = getConnectedDid(session);
66
57
  // send notification to wallet to trigger wallet to auto connect
67
58
  if (connectedDid) {
@@ -88,12 +79,12 @@ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger,
88
79
  }
89
80
  // sendNotificationFn maybe custom function so we need params
90
81
  const sendFn = sendNotificationFn || notification_1.sendToUser.bind(notification_1.default);
91
- sendFn(connectedDid, message, Object.assign(Object.assign({}, context), { session })).catch((err) => {
82
+ sendFn(connectedDid, message, { ...context, session }).catch((err) => {
92
83
  console.error(err);
93
84
  });
94
85
  }
95
86
  return session;
96
- });
87
+ };
97
88
  return handlers;
98
89
  };
99
90
  module.exports = createConnectHandlers;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -16,10 +7,23 @@ const util_1 = require("@blocklet/meta/lib/util");
16
7
  const constants_1 = require("../util/constants");
17
8
  // wraps value in closure or returns closure
18
9
  const closure = (value) => (typeof value === 'function' ? value : () => value);
19
- const connectShared = (options = {}) => (Object.assign(Object.assign({ chainInfo: () => (0, util_1.getChainInfo)(process.env) }, options), { appInfo: (...args) => __awaiter(void 0, void 0, void 0, function* () {
20
- const info = yield closure(options.appInfo)(...args);
10
+ const connectShared = (options = {}) => ({
11
+ chainInfo: () => (0, util_1.getChainInfo)(process.env),
12
+ ...options,
13
+ appInfo: async (...args) => {
14
+ const info = await closure(options.appInfo)(...args);
21
15
  const { request, baseUrl } = args[0];
22
16
  const groupPathPrefix = request.headers['x-group-path-prefix'] || '/';
23
- return Object.assign(Object.assign({ name: process.env.BLOCKLET_APP_NAME, description: process.env.BLOCKLET_APP_DESCRIPTION }, (info || {})), { link: (0, util_1.getConnectAppUrl)(args[0]), icon: (0, url_join_1.default)(baseUrl, constants_1.SERVICE_PREFIX, `/blocklet/logo?v=${process.env.BLOCKLET_APP_VERSION || ''}`), updateSubEndpoint: true, subscriptionEndpoint: (0, url_join_1.default)(groupPathPrefix, constants_1.SERVICE_PREFIX, 'websocket'), nodeDid: process.env.ABT_NODE_DID });
24
- }) }));
17
+ return {
18
+ name: process.env.BLOCKLET_APP_NAME,
19
+ description: process.env.BLOCKLET_APP_DESCRIPTION,
20
+ ...(info || {}),
21
+ link: (0, util_1.getConnectAppUrl)(args[0]),
22
+ icon: (0, url_join_1.default)(baseUrl, constants_1.SERVICE_PREFIX, `/blocklet/logo?v=${process.env.BLOCKLET_APP_VERSION || ''}`),
23
+ updateSubEndpoint: true,
24
+ subscriptionEndpoint: (0, url_join_1.default)(groupPathPrefix, constants_1.SERVICE_PREFIX, 'websocket'),
25
+ nodeDid: process.env.ABT_NODE_DID,
26
+ };
27
+ },
28
+ });
25
29
  module.exports = connectShared;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -28,27 +19,29 @@ class DataBase extends core_1.DataStore {
28
19
  const DB_DIR = path_1.default.join(process.env.BLOCKLET_DATA_DIR, 'db');
29
20
  fs_extra_1.default.ensureDirSync(DB_DIR);
30
21
  const filename = options.filename || path_1.default.join(DB_DIR, `${name}.db`);
31
- super(Object.assign({ filename, autoload: true, timestampData: true, onload: (err) => {
22
+ super({
23
+ filename,
24
+ autoload: true,
25
+ timestampData: true,
26
+ onload: (err) => {
32
27
  if (err) {
33
28
  console.error(`failed to load disk database ${filename}`, err);
34
29
  }
35
- } }, options));
36
- }
37
- exists(...args) {
38
- return __awaiter(this, void 0, void 0, function* () {
39
- const doc = yield this.findOne(...args);
40
- return !!doc;
30
+ },
31
+ ...options,
41
32
  });
42
33
  }
43
- paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {} }) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- return this.cursor(condition)
46
- .sort(sort)
47
- .skip(Math.max(page * size - size, 0))
48
- .limit(Math.max(size, 1))
49
- .projection(projection)
50
- .exec();
51
- });
34
+ async exists(...args) {
35
+ const doc = await this.findOne(...args);
36
+ return !!doc;
37
+ }
38
+ async paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {} }) {
39
+ return this.cursor(condition)
40
+ .sort(sort)
41
+ .skip(Math.max(page * size - size, 0))
42
+ .limit(Math.max(size, 1))
43
+ .projection(projection)
44
+ .exec();
52
45
  }
53
46
  }
54
47
  module.exports = DataBase;
@@ -0,0 +1,9 @@
1
+ import type { Request, Response } from 'express';
2
+ import { generateBlockletEmbed } from './utils';
3
+ declare const expressEmbed: (req: Request, res: Response) => Promise<void>;
4
+ declare const _default: {
5
+ expressEmbed: (req: Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>) => Promise<void>;
6
+ generateBlockletEmbed: typeof generateBlockletEmbed;
7
+ };
8
+ export default _default;
9
+ export { expressEmbed, generateBlockletEmbed };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateBlockletEmbed = exports.expressEmbed = void 0;
4
+ const utils_1 = require("./utils");
5
+ Object.defineProperty(exports, "generateBlockletEmbed", { enumerable: true, get: function () { return utils_1.generateBlockletEmbed; } });
6
+ const expressEmbed = async (req, res) => {
7
+ const { query = {} } = req;
8
+ const { url = '' } = query;
9
+ const data = await (0, utils_1.getBlockletEmbedFromUrl)(url);
10
+ res.json(data);
11
+ };
12
+ exports.expressEmbed = expressEmbed;
13
+ exports.default = { expressEmbed, generateBlockletEmbed: utils_1.generateBlockletEmbed };
@@ -0,0 +1,26 @@
1
+ type InstanceType = 'client' | 'server';
2
+ type MessageType = string;
3
+ interface Callback {
4
+ (...args: any[]): void;
5
+ }
6
+ declare class Message {
7
+ id: string;
8
+ type: InstanceType;
9
+ private bc;
10
+ private eventMap;
11
+ init: (cb: Callback) => void;
12
+ onInit: (getData: () => any) => void;
13
+ close: () => void;
14
+ constructor(id: string, type?: InstanceType);
15
+ on(type: MessageType, cb: Callback): void;
16
+ off(type: MessageType, cb: Callback): void;
17
+ once(type: MessageType, cb: Callback): void;
18
+ send(type: MessageType, payload: any): void;
19
+ }
20
+ declare function useMessage(id?: string, type?: InstanceType): any;
21
+ declare const _default: {
22
+ useMessage: typeof useMessage;
23
+ Message: typeof Message;
24
+ };
25
+ export default _default;
26
+ export { useMessage, Message };
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Message = exports.useMessage = void 0;
4
+ const INIT = '__init';
5
+ const ON_INIT = '__on-init';
6
+ function checkKey(typeKey) {
7
+ return !typeKey.startsWith(INIT);
8
+ }
9
+ function ensureType(type) {
10
+ if (!checkKey(type)) {
11
+ throw new Error(`Type can't starts with ${INIT}`);
12
+ }
13
+ }
14
+ function notExist() {
15
+ console.error('function not exist');
16
+ }
17
+ class Message {
18
+ constructor(id, type = 'client') {
19
+ this.id = id;
20
+ this.type = type;
21
+ const bc = new BroadcastChannel(this.id);
22
+ this.bc = bc;
23
+ this.eventMap = new Map();
24
+ const onMessage = (event) => {
25
+ const { data } = event;
26
+ const { type: messageType, payload, id: dataId } = data;
27
+ if (dataId === this.id) {
28
+ const cbList = this.eventMap.get(messageType) || [];
29
+ cbList.forEach((cbItem) => {
30
+ cbItem(payload);
31
+ });
32
+ }
33
+ };
34
+ window.addEventListener('message', onMessage, false);
35
+ this.close = () => {
36
+ window.removeEventListener('message', onMessage, false);
37
+ // v1 message
38
+ this.bc.close();
39
+ };
40
+ // v1 message
41
+ bc.onmessage = ({ data }) => {
42
+ const { type: messageType, payload } = data;
43
+ const cbList = this.eventMap.get(messageType) || [];
44
+ cbList.forEach((cbItem) => {
45
+ cbItem(payload);
46
+ });
47
+ };
48
+ this.init = notExist;
49
+ this.onInit = notExist;
50
+ if (type === 'server') {
51
+ this.onInit = (getData = () => null) => {
52
+ this.eventMap.set(INIT, [
53
+ (listenKey) => {
54
+ const initData = getData();
55
+ this.send(listenKey, initData);
56
+ },
57
+ ]);
58
+ };
59
+ }
60
+ if (type === 'client') {
61
+ this.init = (cb) => {
62
+ const uniqueId = String(+new Date());
63
+ const listenKey = `${ON_INIT}_${uniqueId}`;
64
+ this.once(listenKey, cb);
65
+ this.send(INIT, listenKey);
66
+ };
67
+ }
68
+ }
69
+ on(type, cb) {
70
+ ensureType(type);
71
+ const cbList = this.eventMap.get(type) || [];
72
+ cbList.push(cb);
73
+ this.eventMap.set(type, cbList);
74
+ }
75
+ off(type, cb) {
76
+ ensureType(type);
77
+ const cbList = this.eventMap.get(type) || [];
78
+ if (cb) {
79
+ const index = cbList.indexOf(cb);
80
+ if (index !== -1) {
81
+ cbList.splice(index, 1);
82
+ }
83
+ }
84
+ else {
85
+ cbList.length = 0;
86
+ }
87
+ this.eventMap.set(type, cbList);
88
+ }
89
+ once(type, cb) {
90
+ ensureType(type);
91
+ const callback = (...args) => {
92
+ cb(...args);
93
+ this.off(type, callback);
94
+ };
95
+ this.on(type, callback);
96
+ }
97
+ send(type, payload) {
98
+ const data = {
99
+ id: this.id,
100
+ type,
101
+ payload,
102
+ };
103
+ if (this.type === 'server') {
104
+ const iframeList = [...document.querySelectorAll(`iframe[data-id="${this.id}"]`)];
105
+ iframeList.forEach((iframeItem) => {
106
+ iframeItem.contentWindow.postMessage(data, '*');
107
+ });
108
+ }
109
+ else {
110
+ window.parent.postMessage(data, '*');
111
+ }
112
+ // v1 message
113
+ this.bc.postMessage(data);
114
+ }
115
+ }
116
+ exports.Message = Message;
117
+ const messageCache = new Map();
118
+ function useMessage(id, type = 'client') {
119
+ // eslint-disable-next-line @typescript-eslint/naming-convention
120
+ const _id = id || window.frameElement?.dataset.id || window.name;
121
+ if (messageCache.has(_id)) {
122
+ return messageCache.get(_id);
123
+ }
124
+ const isInIframe = window !== window.parent;
125
+ const message = (type === 'server' || isInIframe) && _id ? new Message(_id, type) : null;
126
+ const data = { message };
127
+ messageCache.set(_id, data);
128
+ return data;
129
+ }
130
+ exports.useMessage = useMessage;
131
+ exports.default = {
132
+ useMessage,
133
+ Message,
134
+ };
@@ -0,0 +1,7 @@
1
+ export declare function getBlockletEmbedFromUrl(url: string): Promise<object | null>;
2
+ export declare function generateBlockletEmbed(): {
3
+ name: string;
4
+ url: string;
5
+ origin: string;
6
+ embed: any[];
7
+ };
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateBlockletEmbed = exports.getBlockletEmbedFromUrl = void 0;
7
+ const path_1 = require("path");
8
+ const jsdom_1 = __importDefault(require("jsdom"));
9
+ const lodash_1 = require("lodash");
10
+ const ufo_1 = require("ufo");
11
+ const axios_1 = __importDefault(require("axios"));
12
+ const { JSDOM } = jsdom_1.default;
13
+ const api = axios_1.default.create();
14
+ /**
15
+ * 判断 document 是否为开发环境
16
+ * @param document html document 对象(jsdom)
17
+ * @returns boolean
18
+ */
19
+ function checkDev(document) {
20
+ const scirptList = document.querySelectorAll('script[type="module"]');
21
+ return !![...scirptList].find((scriptItem) => scriptItem.textContent?.includes('window.__vite_plugin_react_preamble_installed__ = true'));
22
+ }
23
+ async function getEmbedUrlFromUrl(url) {
24
+ try {
25
+ const { data: htmlContent } = await api.get(url, {
26
+ headers: {
27
+ accept: 'text/html,application/xhtml+xml,application/xml',
28
+ },
29
+ });
30
+ const { document } = new JSDOM(htmlContent).window;
31
+ let prefix = '/';
32
+ let metaUrl = url;
33
+ const link = document.querySelector('link[rel="blocklet-open-embed"]');
34
+ const blockletScript = document.querySelector('script[src="__blocklet__.js"]');
35
+ if (link) {
36
+ metaUrl = link.getAttribute('href') || url;
37
+ }
38
+ const isDev = checkDev(document);
39
+ if (blockletScript) {
40
+ const scriptUrl = new URL('__blocklet__.js?type=json', (0, ufo_1.withTrailingSlash)(url));
41
+ const { data: blockletMeta } = await api.get(scriptUrl.href);
42
+ prefix = blockletMeta.prefix;
43
+ }
44
+ return isDev ? (0, ufo_1.joinURL)(prefix, metaUrl.replace(prefix, '')) : (0, ufo_1.joinURL)(prefix, metaUrl);
45
+ }
46
+ catch {
47
+ return url;
48
+ }
49
+ }
50
+ async function getBlockletEmbedFromUrl(url) {
51
+ const metaUrl = await getEmbedUrlFromUrl(url);
52
+ if (metaUrl) {
53
+ let finalUrl = '';
54
+ if (metaUrl.startsWith('http://') || metaUrl.startsWith('https://')) {
55
+ finalUrl = metaUrl;
56
+ }
57
+ else {
58
+ finalUrl = `${new URL(url).origin}${(0, path_1.join)('/', metaUrl)}`;
59
+ }
60
+ const { data: metaData } = await api.get(finalUrl);
61
+ if ((0, lodash_1.isObject)(metaData)) {
62
+ return metaData;
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+ exports.getBlockletEmbedFromUrl = getBlockletEmbedFromUrl;
68
+ function safeJsonParse(input, defaultValue) {
69
+ try {
70
+ return JSON.parse(input);
71
+ }
72
+ catch {
73
+ return defaultValue;
74
+ }
75
+ }
76
+ function generateBlockletEmbed() {
77
+ const BLOCKLET_MOUNT_POINTS = safeJsonParse(process.env.BLOCKLET_MOUNT_POINTS, []);
78
+ const { BLOCKLET_APP_NAME, BLOCKLET_APP_URL, BLOCKLET_REAL_NAME } = process.env;
79
+ let name = BLOCKLET_APP_NAME;
80
+ const blockletNames = BLOCKLET_REAL_NAME.split('/');
81
+ let url = '/';
82
+ const componentBlocklet = BLOCKLET_MOUNT_POINTS.find((blockletItem) => blockletItem.name === blockletNames[blockletNames.length - 1]);
83
+ if (componentBlocklet) {
84
+ // 先假设只有一层 component blocklet
85
+ url = componentBlocklet.mountPoint;
86
+ name = componentBlocklet.title;
87
+ }
88
+ return {
89
+ name,
90
+ url,
91
+ origin: BLOCKLET_APP_URL,
92
+ embed: [],
93
+ };
94
+ }
95
+ exports.generateBlockletEmbed = generateBlockletEmbed;
@@ -1,3 +1,8 @@
1
1
  import { NextFunction, Request, Response } from 'express';
2
- declare const AuthMiddleware: ({ roles, permissions, _AuthClient }?: $TSFixMe) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
2
+ type MiddlewareParams = {
3
+ roles?: string[];
4
+ permissions?: string[];
5
+ getClient?: Function;
6
+ };
7
+ declare const AuthMiddleware: ({ roles, permissions, getClient }?: MiddlewareParams) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
3
8
  export = AuthMiddleware;
@@ -1,41 +1,38 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
14
5
  const lru_cache_1 = __importDefault(require("lru-cache"));
15
6
  const auth_1 = __importDefault(require("../service/auth"));
16
- const cachedPermissions = new lru_cache_1.default({
17
- max: 10,
18
- maxAge: 60 * 1000, // cache for 2min
19
- });
20
- const getPermissionsByRole = (client, role) => __awaiter(void 0, void 0, void 0, function* () {
21
- const cached = cachedPermissions.get(role);
7
+ const cache = new lru_cache_1.default({ max: 10, maxAge: 60 * 1000 });
8
+ const clients = {};
9
+ const getServiceClient = () => {
10
+ const appId = process.env.BLOCKLET_APP_ID;
11
+ if (!clients[appId]) {
12
+ clients[appId] = new auth_1.default();
13
+ }
14
+ return clients[appId];
15
+ };
16
+ const getPermissionsByRole = async (getClient, role) => {
17
+ if (!role) {
18
+ return [];
19
+ }
20
+ const cached = cache.get(role);
22
21
  if (cached) {
23
22
  return cached;
24
23
  }
25
- const res = yield client.getPermissionsByRole(role);
26
- cachedPermissions.set(role, res);
24
+ const res = await getClient().getPermissionsByRole(role);
25
+ cache.set(role, res);
27
26
  return res;
28
- });
29
- // FIXME: 名字待确认, 全局的名称 Auth 已经被用了
30
- const AuthMiddleware = ({ roles, permissions, _AuthClient = auth_1.default } = {}) => {
27
+ };
28
+ const AuthMiddleware = ({ roles, permissions, getClient = getServiceClient } = {}) => {
31
29
  if (roles && !Array.isArray(roles)) {
32
30
  throw new Error('roles must be array');
33
31
  }
34
32
  if (permissions && !Array.isArray(permissions)) {
35
33
  throw new Error('permissions must be array');
36
34
  }
37
- const client = new _AuthClient();
38
- return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
35
+ return async (req, res, next) => {
39
36
  if (!req.headers['x-user-did']) {
40
37
  res.status(401).json({ code: 'forbidden', error: 'not authorized' });
41
38
  return;
@@ -45,13 +42,13 @@ const AuthMiddleware = ({ roles, permissions, _AuthClient = auth_1.default } = {
45
42
  return;
46
43
  }
47
44
  if (permissions) {
48
- const { permissions: list } = yield getPermissionsByRole(client, req.headers['x-user-role']);
45
+ const { permissions: list } = await getPermissionsByRole(getClient, req.headers['x-user-role']);
49
46
  if (!permissions.some((x) => (list || []).some((y) => y.name === x))) {
50
47
  res.status(403).json({ code: 'forbidden', error: 'no permission' });
51
48
  return;
52
49
  }
53
50
  }
54
51
  next();
55
- });
52
+ };
56
53
  };
57
54
  module.exports = AuthMiddleware;
@@ -12,7 +12,11 @@ declare const _default: {
12
12
  fullName: string;
13
13
  };
14
14
  }, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => Promise<void>;
15
- auth: ({ roles, permissions, _AuthClient }?: any) => (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => Promise<void>;
15
+ auth: ({ roles, permissions, getClient }?: {
16
+ roles?: string[];
17
+ permissions?: string[];
18
+ getClient?: Function;
19
+ }) => (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => Promise<void>;
16
20
  component: {
17
21
  verifySig: (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => void | import("express").Response<any, Record<string, any>>;
18
22
  };
@@ -1,14 +1,5 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- const userMiddleware = () => (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
2
+ const userMiddleware = () => async (req, res, next) => {
12
3
  if (req.headers['x-user-did']) {
13
4
  req.user = {
14
5
  did: req.headers['x-user-did'],
@@ -17,5 +8,5 @@ const userMiddleware = () => (req, res, next) => __awaiter(void 0, void 0, void
17
8
  };
18
9
  }
19
10
  next();
20
- });
11
+ };
21
12
  module.exports = userMiddleware;
@@ -22,7 +22,7 @@ interface AuthService {
22
22
  grantPermissionForRole(role: string, permission: string): Promise<Client.GeneralResponse>;
23
23
  revokePermissionFromRole(role: string, permission: string): Promise<Client.GeneralResponse>;
24
24
  updatePermissionsForRole(role: string, permissions: string): Promise<Client.ResponseRole>;
25
- hasPermission(role: string, permission: string): Promise<ABTNodeClient.BooleanResponse>;
25
+ hasPermission(role: string, permission: string): Promise<Client.BooleanResponse>;
26
26
  getPermissions(): Promise<Client.ResponsePermissions>;
27
27
  createPermission(args: OmitTeamDid<Client.RequestCreatePermissionInput>): Promise<Client.ResponsePermission>;
28
28
  updatePermission(args: OmitTeamDid<Client.PermissionInput>): Promise<Client.ResponsePermission>;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -28,7 +19,7 @@ const type = process.env.BLOCKLET_WALLET_TYPE !== 'eth'
28
19
  ? (0, wallet_1.WalletType)({ role: mcrypto_1.types.RoleType.ROLE_APPLICATION, pk: mcrypto_1.types.KeyType.ED25519, hash: mcrypto_1.types.HashType.SHA3 })
29
20
  : 'eth';
30
21
  const fixAvatar = (user) => {
31
- const avatar = user === null || user === void 0 ? void 0 : user.avatar;
22
+ const avatar = user?.avatar;
32
23
  if (avatar && avatar.startsWith(USER_AVATAR_URL_PREFIX)) {
33
24
  user.avatar = (0, url_join_1.default)(WELLKNOWN_SERVICE_PATH_PREFIX, USER_AVATAR_PATH_PREFIX, avatar.replace(USER_AVATAR_URL_PREFIX, ''));
34
25
  }
@@ -97,30 +88,30 @@ class AuthService {
97
88
  // 'configTrustedPassports',
98
89
  ];
99
90
  const teamDid = process.env.BLOCKLET_DID;
100
- const apiFallback = (fn) => (params = {}, ...args) => fn(Object.assign({ input: Object.assign(Object.assign({}, params), { teamDid }) }, args));
91
+ const apiFallback = (fn) => (params = {}, ...args) => fn({ input: { ...params, teamDid }, ...args });
101
92
  // const apiConvertDid = (fn: Function) => (did: string) => fn({ input: { user: { did }, teamDid } });
102
93
  const apiFnMap = {
103
- getUser: (fn) => (did) => __awaiter(this, void 0, void 0, function* () {
104
- const res = yield fn({ input: { user: { did }, teamDid } });
94
+ getUser: (fn) => async (did) => {
95
+ const res = await fn({ input: { user: { did }, teamDid } });
105
96
  fixAvatar(res.user);
106
97
  return res;
107
- }),
108
- getUsers: (fn) => (args) => __awaiter(this, void 0, void 0, function* () {
109
- const res = yield fn({ input: Object.assign({ teamDid }, args) });
98
+ },
99
+ getUsers: (fn) => async (args) => {
100
+ const res = await fn({ input: { teamDid, ...args } });
110
101
  (res.users || []).forEach(fixAvatar);
111
102
  return res;
112
- }),
103
+ },
113
104
  // removeUser: apiConvertDid,
114
105
  // updateUserRole: (fn: Function) => (did: string, role: string) => fn({ input: { user: { did, role }, teamDid } }),
115
106
  updateUserApproval: (fn) => (did, approved) => fn({ input: { user: { did, approved }, teamDid } }),
116
107
  getPermissionsByRole: (fn) => (name) => fn({ input: { role: { name }, teamDid } }),
117
- createRole: (fn) => ({ name, title, description }) => fn({ input: Object.assign(Object.assign({}, (0, pickBy_1.default)({ name, title, description }, isNotNullOrUndefined)), { teamDid }) }),
108
+ createRole: (fn) => ({ name, title, description }) => fn({ input: { ...(0, pickBy_1.default)({ name, title, description }, isNotNullOrUndefined), teamDid } }),
118
109
  updateRole: (fn) => (name, { title, description }) => fn({ input: { role: (0, pickBy_1.default)({ name, title, description }, isNotNullOrUndefined), teamDid } }),
119
110
  deleteRole: (fn) => (name) => fn({ input: { name, teamDid } }),
120
111
  grantPermissionForRole: (fn) => (roleName, permissionName) => fn({ input: { teamDid, roleName, grantName: permissionName } }),
121
112
  revokePermissionFromRole: (fn) => (roleName, permissionName) => fn({ input: { teamDid, roleName, grantName: permissionName } }),
122
113
  updatePermissionsForRole: (fn) => (roleName, permissionNames) => fn({ input: { teamDid, roleName, grantNames: permissionNames } }),
123
- createPermission: (fn) => ({ name, description }) => fn({ input: Object.assign(Object.assign({}, (0, pickBy_1.default)({ name, description }, isNotNullOrUndefined)), { teamDid }) }),
114
+ createPermission: (fn) => ({ name, description }) => fn({ input: { ...(0, pickBy_1.default)({ name, description }, isNotNullOrUndefined), teamDid } }),
124
115
  updatePermission: (fn) => (name, { description }) => fn({ input: { permission: (0, pickBy_1.default)({ name, description }, isNotNullOrUndefined), teamDid } }),
125
116
  deletePermission: (fn) => (name) => fn({ input: { name, teamDid } }),
126
117
  hasPermission: (fn) => (role, permission) => fn({ input: { teamDid, role, permission } }),
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -58,15 +49,15 @@ const getSender = () => ({
58
49
  * }} options
59
50
  * @returns
60
51
  */
61
- const doSendToUser = (receiver, notification, options) => __awaiter(void 0, void 0, void 0, function* () {
52
+ const doSendToUser = async (receiver, notification, options) => {
62
53
  (0, check_blocklet_env_1.default)();
63
54
  return (0, send_notification_1.sendToUser)(receiver, notification, getSender(), process.env.ABT_NODE_SERVICE_PORT, options);
64
- });
55
+ };
65
56
  exports.sendToUser = doSendToUser;
66
- const doSendToRelay = (topic, event, data) => __awaiter(void 0, void 0, void 0, function* () {
57
+ const doSendToRelay = async (topic, event, data) => {
67
58
  (0, check_blocklet_env_1.default)();
68
59
  return (0, send_notification_1.sendToRelay)(topic, event, data, getSender(), process.env.ABT_NODE_SERVICE_PORT);
69
- });
60
+ };
70
61
  exports.sendToRelay = doSendToRelay;
71
62
  /**
72
63
  *
@@ -79,13 +70,13 @@ exports.sendToRelay = doSendToRelay;
79
70
  * }} options
80
71
  * @returns
81
72
  */
82
- const broadcast = (notification, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
73
+ const broadcast = async (notification, options = {}) => {
83
74
  (0, check_blocklet_env_1.default)();
84
75
  const sender = getSender();
85
76
  const { channel = (0, channel_1.getAppPublicChannel)(sender.appDid) } = options;
86
77
  const { event = 'message' } = options;
87
78
  return (0, send_notification_1.sendToAppChannel)(channel, event, notification, sender, process.env.ABT_NODE_SERVICE_PORT, options);
88
- });
79
+ };
89
80
  exports.broadcast = broadcast;
90
81
  const emitter = new events_1.default();
91
82
  const messageEmitter = new events_1.default();
package/lib/util/env.js CHANGED
@@ -10,7 +10,7 @@ function parseEnv(env = process.env) {
10
10
  try {
11
11
  acc[key] = JSON.parse(env[x]);
12
12
  }
13
- catch (_a) {
13
+ catch {
14
14
  acc[key] = env[x];
15
15
  }
16
16
  return acc;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -60,15 +51,15 @@ const getRequestHeaders = () => ({ 'User-Agent': `BlockletSDK/${VERSION}` });
60
51
  * @param {Object} options
61
52
  * @returns
62
53
  */
63
- const sendToUser = (receiver, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
64
- yield (0, index_1.validateReceiver)(receiver);
54
+ const sendToUser = async (receiver, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => {
55
+ await (0, index_1.validateReceiver)(receiver);
65
56
  const opt = (0, pick_1.default)(options, ['keepForOfflineUser']);
66
- yield (0, index_1.validateOption)(opt);
57
+ await (0, index_1.validateOption)(opt);
67
58
  if (SERVER_MODE !== NODE_MODES.DEBUG) {
68
- yield (0, index_1.validateNotification)(notification);
59
+ await (0, index_1.validateNotification)(notification);
69
60
  }
70
61
  try {
71
- const { data: res } = yield axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-user`, {
62
+ const { data: res } = await axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-user`, {
72
63
  apiVersion: VERSION,
73
64
  data: {
74
65
  sender: { appDid, token: JWT.sign(appDid, appSk) },
@@ -86,16 +77,16 @@ const sendToUser = (receiver, notification, { appDid, appSk }, port = process.en
86
77
  console.error(err.response ? err.response.data : err);
87
78
  throw new Error(err.response ? err.response.data : err.message);
88
79
  }
89
- });
80
+ };
90
81
  exports.sendToUser = sendToUser;
91
- const sendToAppChannel = (channel, event, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
82
+ const sendToAppChannel = async (channel, event, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => {
92
83
  if (!channel) {
93
84
  throw new Error('channel is required');
94
85
  }
95
86
  if (!event) {
96
87
  throw new Error('event is required');
97
88
  }
98
- yield (0, index_1.validateChannelEvent)(event);
89
+ await (0, index_1.validateChannelEvent)(event);
99
90
  const opt = (0, pick_1.default)(options, ['socketId', 'userDid']);
100
91
  if (opt.userDid) {
101
92
  // @ts-expect-error TS(2551) FIXME: Property 'socketDid' does not exist on type 'Pick<... Remove this comment to see the full error message
@@ -103,10 +94,10 @@ const sendToAppChannel = (channel, event, notification, { appDid, appSk }, port
103
94
  delete opt.userDid;
104
95
  }
105
96
  if (SERVER_MODE !== NODE_MODES.DEBUG) {
106
- yield (0, index_1.validateNotification)(notification);
97
+ await (0, index_1.validateNotification)(notification);
107
98
  }
108
99
  try {
109
- const { data: res } = yield axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-app-channel`, {
100
+ const { data: res } = await axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-app-channel`, {
110
101
  apiVersion: VERSION,
111
102
  data: {
112
103
  sender: { appDid, token: JWT.sign(appDid, appSk) },
@@ -125,9 +116,9 @@ const sendToAppChannel = (channel, event, notification, { appDid, appSk }, port
125
116
  console.error(err.response ? err.response.data : err);
126
117
  throw new Error(err.response ? err.response.data : err.message);
127
118
  }
128
- });
119
+ };
129
120
  exports.sendToAppChannel = sendToAppChannel;
130
- const sendToRelay = (topic, event, data, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT) => __awaiter(void 0, void 0, void 0, function* () {
121
+ const sendToRelay = async (topic, event, data, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT) => {
131
122
  if (!topic) {
132
123
  throw new Error('topic is required');
133
124
  }
@@ -138,7 +129,7 @@ const sendToRelay = (topic, event, data, { appDid, appSk }, port = process.env.A
138
129
  throw new Error('data is required');
139
130
  }
140
131
  try {
141
- const { data: res } = yield axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/relay/api/send-to-relay-channel`, {
132
+ const { data: res } = await axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/relay/api/send-to-relay-channel`, {
142
133
  apiVersion: VERSION,
143
134
  data: {
144
135
  sender: { appDid, token: JWT.sign(appDid, appSk) },
@@ -156,7 +147,7 @@ const sendToRelay = (topic, event, data, { appDid, appSk }, port = process.env.A
156
147
  console.error(err.response ? err.response.data : err);
157
148
  throw new Error(err.response ? err.response.data : err.message);
158
149
  }
159
- });
150
+ };
160
151
  exports.sendToRelay = sendToRelay;
161
152
  exports.default = {
162
153
  sendToUser,
package/lib/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- declare const version = "1.8.66";
1
+ declare const version = "1.8.67";
2
2
  export { version };
3
3
  declare const _default: {
4
4
  version: string;
package/lib/version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
- const version = '1.8.66';
4
+ const version = '1.8.67';
5
5
  exports.version = version;
6
6
  exports.default = { version };
@@ -9,7 +9,10 @@ const shared_1 = __importDefault(require("./connect/shared"));
9
9
  class WalletAuthenticator extends did_auth_1.WalletAuthenticator {
10
10
  constructor(options = {}) {
11
11
  (0, check_blocklet_env_1.default)();
12
- super(Object.assign({ wallet: (0, wallet_1.default)().toJSON() }, (0, shared_1.default)(options)));
12
+ super({
13
+ wallet: (0, wallet_1.default)().toJSON(),
14
+ ...(0, shared_1.default)(options),
15
+ });
13
16
  }
14
17
  }
15
18
  module.exports = WalletAuthenticator;
@@ -22,26 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __rest = (this && this.__rest) || function (s, e) {
35
- var t = {};
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
- t[p] = s[p];
38
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
- t[p[i]] = s[p[i]];
42
- }
43
- return t;
44
- };
45
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
46
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
47
27
  };
@@ -61,11 +41,16 @@ class WalletHandlers extends did_auth_1.WalletHandlers {
61
41
  * @param {function} [params.sendNotificationFn] use in a non-blocklet environment
62
42
  * @param {function} [params.sendToRelayFn]
63
43
  */
64
- constructor(_a) {
65
- var { autoConnect = true, connectedDidOnly = false, sendNotificationFn = null, sendToRelayFn = null, options = {} } = _a, opts = __rest(_a, ["autoConnect", "connectedDidOnly", "sendNotificationFn", "sendToRelayFn", "options"]);
66
- super(Object.assign({ options: Object.assign(Object.assign({}, options), {
67
- sessionDidKey: autoConnect && connectedDidOnly ? CONNECTED_DID_KEY : options === null || options === void 0 ? void 0 : options.sessionDidKey,
68
- }) }, opts));
44
+ constructor({ autoConnect = true, connectedDidOnly = false, sendNotificationFn = null, sendToRelayFn = null, options = {}, ...opts }) {
45
+ super({
46
+ options: {
47
+ ...options,
48
+ ...{
49
+ sessionDidKey: autoConnect && connectedDidOnly ? CONNECTED_DID_KEY : options?.sessionDidKey,
50
+ },
51
+ },
52
+ ...opts,
53
+ });
69
54
  this.getConnectedDid = ({ req, didwallet, extraParams }) => {
70
55
  if (extraParams && extraParams.autoConnect === 'false') {
71
56
  return null;
@@ -83,14 +68,13 @@ class WalletHandlers extends did_auth_1.WalletHandlers {
83
68
  this.sendToRelayFn = sendToRelayFn || notification_1.sendToRelay.bind(notification_1.default);
84
69
  // @ts-ignore
85
70
  this.on('updated', (session) => {
86
- this.sendToRelayFn({ topic: session.token, event: 'updated', data: session }).catch(console.error);
71
+ this.sendToRelayFn(session.token, 'updated', session).catch(console.error);
87
72
  });
88
73
  }
89
- attach(_a) {
90
- var { onStart = noop } = _a, opts = __rest(_a, ["onStart"]);
91
- const realOnStart = (params) => __awaiter(this, void 0, void 0, function* () {
74
+ attach({ onStart = noop, ...opts }) {
75
+ const realOnStart = async (params) => {
92
76
  // @ts-expect-error TS(2554) FIXME: Expected 0 arguments, but got 1.
93
- const extra = (yield onStart(params)) || {};
77
+ const extra = (await onStart(params)) || {};
94
78
  const connectedDid = this.getConnectedDid(params);
95
79
  // fill extra
96
80
  extra.connectedDid = connectedDid || '';
@@ -123,9 +107,12 @@ class WalletHandlers extends did_auth_1.WalletHandlers {
123
107
  });
124
108
  }
125
109
  return extra;
126
- });
110
+ };
127
111
  // @ts-expect-error TS(2345) FIXME: Argument of type '{ onStart: (params: any) => Prom... Remove this comment to see the full error message
128
- super.attach(Object.assign({ onStart: realOnStart }, opts));
112
+ super.attach({
113
+ onStart: realOnStart,
114
+ ...opts,
115
+ });
129
116
  }
130
117
  }
131
118
  module.exports = WalletHandlers;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.8.66-beta-7f4224af",
6
+ "version": "1.8.66-beta.1",
7
7
  "description": "graphql client to read/write data on abt node",
8
8
  "main": "lib/index.js",
9
9
  "typings": "lib/index.d.ts",
@@ -26,25 +26,27 @@
26
26
  "author": "linchen1987 <linchen.1987@foxmail.com> (http://github.com/linchen1987)",
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "@abtnode/client": "1.8.66-beta-7f4224af",
30
- "@abtnode/constant": "1.8.66-beta-7f4224af",
31
- "@abtnode/util": "1.8.66-beta-7f4224af",
32
- "@arcblock/did-auth": "1.18.47",
33
- "@arcblock/jwt": "1.18.47",
34
- "@arcblock/ws": "1.18.47",
35
- "@blocklet/constant": "1.8.66-beta-7f4224af",
36
- "@blocklet/meta": "1.8.66-beta-7f4224af",
37
- "@did-connect/authenticator": "^2.1.35",
38
- "@did-connect/handler": "^2.1.35",
29
+ "@abtnode/client": "1.8.66",
30
+ "@abtnode/constant": "1.8.66",
31
+ "@abtnode/util": "^1.8.66",
32
+ "@arcblock/did-auth": "1.18.56",
33
+ "@arcblock/jwt": "1.18.56",
34
+ "@arcblock/ws": "1.18.56",
35
+ "@blocklet/constant": "1.8.66",
36
+ "@blocklet/meta": "1.8.66",
37
+ "@did-connect/authenticator": "^2.1.40",
38
+ "@did-connect/handler": "^2.1.40",
39
39
  "@nedb/core": "^2.1.5",
40
- "@ocap/mcrypto": "1.18.47",
41
- "@ocap/wallet": "1.18.47",
40
+ "@ocap/mcrypto": "1.18.56",
41
+ "@ocap/wallet": "1.18.56",
42
42
  "axios": "^0.27.2",
43
43
  "fs-extra": "^10.1.0",
44
44
  "joi": "17.7.0",
45
+ "jsdom": "^21.1.0",
45
46
  "json-stable-stringify": "^1.0.1",
46
47
  "lodash": "^4.17.21",
47
48
  "lru-cache": "^6.0.0",
49
+ "ufo": "^1.1.1",
48
50
  "url-join": "^4.0.1"
49
51
  },
50
52
  "resolutions": {
@@ -62,12 +64,11 @@
62
64
  "detect-port": "^1.5.1",
63
65
  "eslint": "^8.25.0",
64
66
  "jest": "^29.2.0",
65
- "joi-to-typescript": "^4.0.6",
67
+ "joi-to-typescript": "^4.0.7",
66
68
  "json-stable-stringify": "^1.0.1",
67
69
  "prettier": "^2.7.1",
68
70
  "ts-jest": "^29.0.3",
69
71
  "ts-node": "^10.9.1",
70
72
  "typescript": "^4.8.4"
71
- },
72
- "gitHead": "72d418f63ecb76b1d5d62edbcc5f336cb62bf308"
73
+ }
73
74
  }