@blocklet/sdk 1.8.67-beta-65933c91 → 1.8.67

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,4 +1,13 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
@@ -16,9 +25,9 @@ const sign = (data) => {
16
25
  const signData = typeof data === 'undefined' ? {} : data;
17
26
  return { 'x-component-sig': wallet.sign((0, json_stable_stringify_1.default)(signData)) };
18
27
  };
19
- const doCall = async ({ url, data }) => {
28
+ const doCall = ({ url, data }) => __awaiter(void 0, void 0, void 0, function* () {
20
29
  try {
21
- const resp = await axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
30
+ const resp = yield axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
22
31
  config_1.logger.info(`call ${url} api success`);
23
32
  return resp;
24
33
  }
@@ -31,7 +40,7 @@ const doCall = async ({ url, data }) => {
31
40
  });
32
41
  throw new Error(`call ${url} api failed`);
33
42
  }
34
- };
43
+ });
35
44
  const parsePorts = () => JSON.parse(process.env.BLOCKLET_WEB_PORTS);
36
45
  const getWebEndpoint = (name) => {
37
46
  const ports = parsePorts();
@@ -59,11 +68,11 @@ const parseMountPoints = () => {
59
68
  });
60
69
  return mountPoints;
61
70
  };
62
- const call = async ({ name, path: _path, data }) => {
71
+ const call = ({ name, path: _path, data }) => __awaiter(void 0, void 0, void 0, function* () {
63
72
  const baseURL = name ? getChildWebEndpoint(name) : getParentWebEndpoint();
64
73
  const url = (0, url_join_1.default)(baseURL, _path);
65
74
  return doCall({ url, data });
66
- };
75
+ });
67
76
  exports.call = call;
68
77
  const getComponentMountPoint = (keyword) => {
69
78
  const mountPoints = parseMountPoints();
@@ -9,10 +9,7 @@ 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({
13
- wallet: (0, wallet_1.default)(),
14
- ...(0, shared_1.default)(options),
15
- });
12
+ super(Object.assign({ wallet: (0, wallet_1.default)() }, (0, shared_1.default)(options)));
16
13
  }
17
14
  }
18
15
  module.exports = BlockletAuthenticator;
@@ -22,6 +22,15 @@ 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
+ };
25
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
36
  };
@@ -51,8 +60,8 @@ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger,
51
60
  socketPathname,
52
61
  });
53
62
  const originCreateHandler = handlers.handleSessionCreate;
54
- handlers.handleSessionCreate = async (context) => {
55
- const session = await originCreateHandler(context);
63
+ handlers.handleSessionCreate = (context) => __awaiter(void 0, void 0, void 0, function* () {
64
+ const session = yield originCreateHandler(context);
56
65
  const connectedDid = getConnectedDid(session);
57
66
  // send notification to wallet to trigger wallet to auto connect
58
67
  if (connectedDid) {
@@ -79,12 +88,12 @@ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger,
79
88
  }
80
89
  // sendNotificationFn maybe custom function so we need params
81
90
  const sendFn = sendNotificationFn || notification_1.sendToUser.bind(notification_1.default);
82
- sendFn(connectedDid, message, { ...context, session }).catch((err) => {
91
+ sendFn(connectedDid, message, Object.assign(Object.assign({}, context), { session })).catch((err) => {
83
92
  console.error(err);
84
93
  });
85
94
  }
86
95
  return session;
87
- };
96
+ });
88
97
  return handlers;
89
98
  };
90
99
  module.exports = createConnectHandlers;
@@ -1,4 +1,13 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
@@ -7,23 +16,10 @@ const util_1 = require("@blocklet/meta/lib/util");
7
16
  const constants_1 = require("../util/constants");
8
17
  // wraps value in closure or returns closure
9
18
  const closure = (value) => (typeof value === 'function' ? value : () => value);
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);
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);
15
21
  const { request, baseUrl } = args[0];
16
22
  const groupPathPrefix = request.headers['x-group-path-prefix'] || '/';
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
- });
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
+ }) }));
29
25
  module.exports = connectShared;
@@ -1,4 +1,13 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
@@ -19,29 +28,27 @@ class DataBase extends core_1.DataStore {
19
28
  const DB_DIR = path_1.default.join(process.env.BLOCKLET_DATA_DIR, 'db');
20
29
  fs_extra_1.default.ensureDirSync(DB_DIR);
21
30
  const filename = options.filename || path_1.default.join(DB_DIR, `${name}.db`);
22
- super({
23
- filename,
24
- autoload: true,
25
- timestampData: true,
26
- onload: (err) => {
31
+ super(Object.assign({ filename, autoload: true, timestampData: true, onload: (err) => {
27
32
  if (err) {
28
33
  console.error(`failed to load disk database ${filename}`, err);
29
34
  }
30
- },
31
- ...options,
32
- });
35
+ } }, options));
33
36
  }
34
- async exists(...args) {
35
- const doc = await this.findOne(...args);
36
- return !!doc;
37
+ exists(...args) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ const doc = yield this.findOne(...args);
40
+ return !!doc;
41
+ });
37
42
  }
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();
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
+ });
45
52
  }
46
53
  }
47
54
  module.exports = DataBase;
@@ -1,8 +1,3 @@
1
1
  import { NextFunction, Request, Response } from 'express';
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>;
2
+ declare const AuthMiddleware: ({ roles, permissions, _AuthClient }?: $TSFixMe) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
8
3
  export = AuthMiddleware;
@@ -1,38 +1,41 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
5
14
  const lru_cache_1 = __importDefault(require("lru-cache"));
6
15
  const auth_1 = __importDefault(require("../service/auth"));
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);
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);
21
22
  if (cached) {
22
23
  return cached;
23
24
  }
24
- const res = await getClient().getPermissionsByRole(role);
25
- cache.set(role, res);
25
+ const res = yield client.getPermissionsByRole(role);
26
+ cachedPermissions.set(role, res);
26
27
  return res;
27
- };
28
- const AuthMiddleware = ({ roles, permissions, getClient = getServiceClient } = {}) => {
28
+ });
29
+ // FIXME: 名字待确认, 全局的名称 Auth 已经被用了
30
+ const AuthMiddleware = ({ roles, permissions, _AuthClient = auth_1.default } = {}) => {
29
31
  if (roles && !Array.isArray(roles)) {
30
32
  throw new Error('roles must be array');
31
33
  }
32
34
  if (permissions && !Array.isArray(permissions)) {
33
35
  throw new Error('permissions must be array');
34
36
  }
35
- return async (req, res, next) => {
37
+ const client = new _AuthClient();
38
+ return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
36
39
  if (!req.headers['x-user-did']) {
37
40
  res.status(401).json({ code: 'forbidden', error: 'not authorized' });
38
41
  return;
@@ -42,13 +45,13 @@ const AuthMiddleware = ({ roles, permissions, getClient = getServiceClient } = {
42
45
  return;
43
46
  }
44
47
  if (permissions) {
45
- const { permissions: list } = await getPermissionsByRole(getClient, req.headers['x-user-role']);
48
+ const { permissions: list } = yield getPermissionsByRole(client, req.headers['x-user-role']);
46
49
  if (!permissions.some((x) => (list || []).some((y) => y.name === x))) {
47
50
  res.status(403).json({ code: 'forbidden', error: 'no permission' });
48
51
  return;
49
52
  }
50
53
  }
51
54
  next();
52
- };
55
+ });
53
56
  };
54
57
  module.exports = AuthMiddleware;
@@ -12,11 +12,7 @@ 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, 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>;
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>;
20
16
  component: {
21
17
  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>>;
22
18
  };
@@ -1,5 +1,14 @@
1
1
  "use strict";
2
- const userMiddleware = () => async (req, res, next) => {
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* () {
3
12
  if (req.headers['x-user-did']) {
4
13
  req.user = {
5
14
  did: req.headers['x-user-did'],
@@ -8,5 +17,5 @@ const userMiddleware = () => async (req, res, next) => {
8
17
  };
9
18
  }
10
19
  next();
11
- };
20
+ });
12
21
  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<Client.BooleanResponse>;
25
+ hasPermission(role: string, permission: string): Promise<ABTNodeClient.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,4 +1,13 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
@@ -19,7 +28,7 @@ const type = process.env.BLOCKLET_WALLET_TYPE !== 'eth'
19
28
  ? (0, wallet_1.WalletType)({ role: mcrypto_1.types.RoleType.ROLE_APPLICATION, pk: mcrypto_1.types.KeyType.ED25519, hash: mcrypto_1.types.HashType.SHA3 })
20
29
  : 'eth';
21
30
  const fixAvatar = (user) => {
22
- const avatar = user?.avatar;
31
+ const avatar = user === null || user === void 0 ? void 0 : user.avatar;
23
32
  if (avatar && avatar.startsWith(USER_AVATAR_URL_PREFIX)) {
24
33
  user.avatar = (0, url_join_1.default)(WELLKNOWN_SERVICE_PATH_PREFIX, USER_AVATAR_PATH_PREFIX, avatar.replace(USER_AVATAR_URL_PREFIX, ''));
25
34
  }
@@ -88,30 +97,30 @@ class AuthService {
88
97
  // 'configTrustedPassports',
89
98
  ];
90
99
  const teamDid = process.env.BLOCKLET_DID;
91
- const apiFallback = (fn) => (params = {}, ...args) => fn({ input: { ...params, teamDid }, ...args });
100
+ const apiFallback = (fn) => (params = {}, ...args) => fn(Object.assign({ input: Object.assign(Object.assign({}, params), { teamDid }) }, args));
92
101
  // const apiConvertDid = (fn: Function) => (did: string) => fn({ input: { user: { did }, teamDid } });
93
102
  const apiFnMap = {
94
- getUser: (fn) => async (did) => {
95
- const res = await fn({ input: { user: { did }, teamDid } });
103
+ getUser: (fn) => (did) => __awaiter(this, void 0, void 0, function* () {
104
+ const res = yield fn({ input: { user: { did }, teamDid } });
96
105
  fixAvatar(res.user);
97
106
  return res;
98
- },
99
- getUsers: (fn) => async (args) => {
100
- const res = await fn({ input: { teamDid, ...args } });
107
+ }),
108
+ getUsers: (fn) => (args) => __awaiter(this, void 0, void 0, function* () {
109
+ const res = yield fn({ input: Object.assign({ teamDid }, args) });
101
110
  (res.users || []).forEach(fixAvatar);
102
111
  return res;
103
- },
112
+ }),
104
113
  // removeUser: apiConvertDid,
105
114
  // updateUserRole: (fn: Function) => (did: string, role: string) => fn({ input: { user: { did, role }, teamDid } }),
106
115
  updateUserApproval: (fn) => (did, approved) => fn({ input: { user: { did, approved }, teamDid } }),
107
116
  getPermissionsByRole: (fn) => (name) => fn({ input: { role: { name }, teamDid } }),
108
- createRole: (fn) => ({ name, title, description }) => fn({ input: { ...(0, pickBy_1.default)({ name, title, description }, isNotNullOrUndefined), teamDid } }),
117
+ createRole: (fn) => ({ name, title, description }) => fn({ input: Object.assign(Object.assign({}, (0, pickBy_1.default)({ name, title, description }, isNotNullOrUndefined)), { teamDid }) }),
109
118
  updateRole: (fn) => (name, { title, description }) => fn({ input: { role: (0, pickBy_1.default)({ name, title, description }, isNotNullOrUndefined), teamDid } }),
110
119
  deleteRole: (fn) => (name) => fn({ input: { name, teamDid } }),
111
120
  grantPermissionForRole: (fn) => (roleName, permissionName) => fn({ input: { teamDid, roleName, grantName: permissionName } }),
112
121
  revokePermissionFromRole: (fn) => (roleName, permissionName) => fn({ input: { teamDid, roleName, grantName: permissionName } }),
113
122
  updatePermissionsForRole: (fn) => (roleName, permissionNames) => fn({ input: { teamDid, roleName, grantNames: permissionNames } }),
114
- createPermission: (fn) => ({ name, description }) => fn({ input: { ...(0, pickBy_1.default)({ name, description }, isNotNullOrUndefined), teamDid } }),
123
+ createPermission: (fn) => ({ name, description }) => fn({ input: Object.assign(Object.assign({}, (0, pickBy_1.default)({ name, description }, isNotNullOrUndefined)), { teamDid }) }),
115
124
  updatePermission: (fn) => (name, { description }) => fn({ input: { permission: (0, pickBy_1.default)({ name, description }, isNotNullOrUndefined), teamDid } }),
116
125
  deletePermission: (fn) => (name) => fn({ input: { name, teamDid } }),
117
126
  hasPermission: (fn) => (role, permission) => fn({ input: { teamDid, role, permission } }),
@@ -11,7 +11,6 @@ type $TSFixMe = any;
11
11
  * @returns
12
12
  */
13
13
  declare const doSendToUser: (receiver: string | string[], notification: TNotificationInput, options?: TSendOptions) => Promise<any>;
14
- declare const doSendToRelay: (topic: string, event: string, data: any) => Promise<any>;
15
14
  /**
16
15
  *
17
16
  * @param {Notification} notification
@@ -31,11 +30,9 @@ export declare const _message: {
31
30
  off: any;
32
31
  };
33
32
  export { doSendToUser as sendToUser };
34
- export { doSendToRelay as sendToRelay };
35
33
  export { broadcast };
36
34
  declare const _default: {
37
35
  sendToUser: (receiver: string | string[], notification: TNotificationInput, options?: TSendOptions) => Promise<any>;
38
- sendToRelay: (topic: string, event: string, data: any) => Promise<any>;
39
36
  broadcast: (notification: TNotificationInput, options?: TSendOptions) => Promise<any>;
40
37
  on: (event: string, cb?: any) => EventEmitter;
41
38
  off: any;
@@ -22,11 +22,20 @@ 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
+ };
25
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
36
  };
28
37
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.broadcast = exports.sendToRelay = exports.sendToUser = exports._message = exports.off = exports.on = void 0;
38
+ exports.broadcast = exports.sendToUser = exports._message = exports.off = exports.on = void 0;
30
39
  /* eslint-disable @typescript-eslint/naming-convention */
31
40
  const Jwt = __importStar(require("@arcblock/jwt"));
32
41
  const events_1 = __importDefault(require("events"));
@@ -49,16 +58,11 @@ const getSender = () => ({
49
58
  * }} options
50
59
  * @returns
51
60
  */
52
- const doSendToUser = async (receiver, notification, options) => {
61
+ const doSendToUser = (receiver, notification, options) => __awaiter(void 0, void 0, void 0, function* () {
53
62
  (0, check_blocklet_env_1.default)();
54
63
  return (0, send_notification_1.sendToUser)(receiver, notification, getSender(), process.env.ABT_NODE_SERVICE_PORT, options);
55
- };
64
+ });
56
65
  exports.sendToUser = doSendToUser;
57
- const doSendToRelay = async (topic, event, data) => {
58
- (0, check_blocklet_env_1.default)();
59
- return (0, send_notification_1.sendToRelay)(topic, event, data, getSender(), process.env.ABT_NODE_SERVICE_PORT);
60
- };
61
- exports.sendToRelay = doSendToRelay;
62
66
  /**
63
67
  *
64
68
  * @param {Notification} notification
@@ -70,13 +74,13 @@ exports.sendToRelay = doSendToRelay;
70
74
  * }} options
71
75
  * @returns
72
76
  */
73
- const broadcast = async (notification, options = {}) => {
77
+ const broadcast = (notification, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
74
78
  (0, check_blocklet_env_1.default)();
75
79
  const sender = getSender();
76
80
  const { channel = (0, channel_1.getAppPublicChannel)(sender.appDid) } = options;
77
81
  const { event = 'message' } = options;
78
82
  return (0, send_notification_1.sendToAppChannel)(channel, event, notification, sender, process.env.ABT_NODE_SERVICE_PORT, options);
79
- };
83
+ });
80
84
  exports.broadcast = broadcast;
81
85
  const emitter = new events_1.default();
82
86
  const messageEmitter = new events_1.default();
@@ -174,7 +178,6 @@ exports._message = {
174
178
  };
175
179
  exports.default = {
176
180
  sendToUser: doSendToUser,
177
- sendToRelay: doSendToRelay,
178
181
  broadcast,
179
182
  on: exports.on,
180
183
  off: exports.off,
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 {
13
+ catch (_a) {
14
14
  acc[key] = env[x];
15
15
  }
16
16
  return acc;
@@ -16,11 +16,10 @@ export type TNotificationSender = {
16
16
  */
17
17
  declare const sendToUser: (receiver: string | string[], notification: TNotificationInput, { appDid, appSk }: TNotificationSender, port?: string, options?: {}) => Promise<any>;
18
18
  declare const sendToAppChannel: (channel: string, event: string, notification: TNotificationInput, { appDid, appSk }: TNotificationSender, port?: string, options?: TSendOptions) => Promise<any>;
19
- declare const sendToRelay: (topic: string, event: string, data: any, { appDid, appSk }: TNotificationSender, port?: string) => Promise<any>;
20
- export { sendToUser, sendToAppChannel, sendToRelay };
19
+ export { sendToUser };
20
+ export { sendToAppChannel };
21
21
  declare const _default: {
22
22
  sendToUser: (receiver: string | string[], notification: TNotificationInput, { appDid, appSk }: TNotificationSender, port?: string, options?: {}) => Promise<any>;
23
23
  sendToAppChannel: (channel: string, event: string, notification: TNotificationInput, { appDid, appSk }: TNotificationSender, port?: string, options?: TSendOptions) => Promise<any>;
24
- sendToRelay: (topic: string, event: string, data: any, { appDid, appSk }: TNotificationSender, port?: string) => Promise<any>;
25
24
  };
26
25
  export default _default;
@@ -22,16 +22,24 @@ 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
+ };
25
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
36
  };
28
37
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.sendToRelay = exports.sendToAppChannel = exports.sendToUser = void 0;
38
+ exports.sendToAppChannel = exports.sendToUser = void 0;
30
39
  const axios_1 = __importDefault(require("axios"));
31
40
  const pick_1 = __importDefault(require("lodash/pick"));
32
41
  const JWT = __importStar(require("@arcblock/jwt"));
33
42
  const constant_1 = __importDefault(require("@abtnode/constant"));
34
- const channel_1 = require("@blocklet/meta/lib/channel");
35
43
  const index_1 = require("../validators/index");
36
44
  const constants_1 = require("./constants");
37
45
  const version_1 = require("../version");
@@ -51,15 +59,15 @@ const getRequestHeaders = () => ({ 'User-Agent': `BlockletSDK/${VERSION}` });
51
59
  * @param {Object} options
52
60
  * @returns
53
61
  */
54
- const sendToUser = async (receiver, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => {
55
- await (0, index_1.validateReceiver)(receiver);
62
+ const sendToUser = (receiver, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
63
+ yield (0, index_1.validateReceiver)(receiver);
56
64
  const opt = (0, pick_1.default)(options, ['keepForOfflineUser']);
57
- await (0, index_1.validateOption)(opt);
65
+ yield (0, index_1.validateOption)(opt);
58
66
  if (SERVER_MODE !== NODE_MODES.DEBUG) {
59
- await (0, index_1.validateNotification)(notification);
67
+ yield (0, index_1.validateNotification)(notification);
60
68
  }
61
69
  try {
62
- const { data: res } = await axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-user`, {
70
+ const { data: res } = yield axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-user`, {
63
71
  apiVersion: VERSION,
64
72
  data: {
65
73
  sender: { appDid, token: JWT.sign(appDid, appSk) },
@@ -77,16 +85,16 @@ const sendToUser = async (receiver, notification, { appDid, appSk }, port = proc
77
85
  console.error(err.response ? err.response.data : err);
78
86
  throw new Error(err.response ? err.response.data : err.message);
79
87
  }
80
- };
88
+ });
81
89
  exports.sendToUser = sendToUser;
82
- const sendToAppChannel = async (channel, event, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => {
90
+ const sendToAppChannel = (channel, event, notification, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
83
91
  if (!channel) {
84
92
  throw new Error('channel is required');
85
93
  }
86
94
  if (!event) {
87
95
  throw new Error('event is required');
88
96
  }
89
- await (0, index_1.validateChannelEvent)(event);
97
+ yield (0, index_1.validateChannelEvent)(event);
90
98
  const opt = (0, pick_1.default)(options, ['socketId', 'userDid']);
91
99
  if (opt.userDid) {
92
100
  // @ts-expect-error TS(2551) FIXME: Property 'socketDid' does not exist on type 'Pick<... Remove this comment to see the full error message
@@ -94,10 +102,10 @@ const sendToAppChannel = async (channel, event, notification, { appDid, appSk },
94
102
  delete opt.userDid;
95
103
  }
96
104
  if (SERVER_MODE !== NODE_MODES.DEBUG) {
97
- await (0, index_1.validateNotification)(notification);
105
+ yield (0, index_1.validateNotification)(notification);
98
106
  }
99
107
  try {
100
- const { data: res } = await axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-app-channel`, {
108
+ const { data: res } = yield axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/api/send-to-app-channel`, {
101
109
  apiVersion: VERSION,
102
110
  data: {
103
111
  sender: { appDid, token: JWT.sign(appDid, appSk) },
@@ -116,41 +124,9 @@ const sendToAppChannel = async (channel, event, notification, { appDid, appSk },
116
124
  console.error(err.response ? err.response.data : err);
117
125
  throw new Error(err.response ? err.response.data : err.message);
118
126
  }
119
- };
127
+ });
120
128
  exports.sendToAppChannel = sendToAppChannel;
121
- const sendToRelay = async (topic, event, data, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT) => {
122
- if (!topic) {
123
- throw new Error('topic is required');
124
- }
125
- if (!event) {
126
- throw new Error('event is required');
127
- }
128
- if (!data) {
129
- throw new Error('data is required');
130
- }
131
- try {
132
- const { data: res } = await axios.post(`http://127.0.0.1:${port}${constants_1.SERVICE_PREFIX}/relay/api/send-to-relay-channel`, {
133
- apiVersion: VERSION,
134
- data: {
135
- sender: { appDid, token: JWT.sign(appDid, appSk) },
136
- channel: (0, channel_1.getRelayChannel)(appDid, topic),
137
- event,
138
- data,
139
- },
140
- }, {
141
- timeout: 60 * 1000,
142
- headers: getRequestHeaders(),
143
- });
144
- return res;
145
- }
146
- catch (err) {
147
- console.error(err.response ? err.response.data : err);
148
- throw new Error(err.response ? err.response.data : err.message);
149
- }
150
- };
151
- exports.sendToRelay = sendToRelay;
152
129
  exports.default = {
153
130
  sendToUser,
154
131
  sendToAppChannel,
155
- sendToRelay,
156
132
  };
@@ -9,10 +9,7 @@ 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({
13
- wallet: (0, wallet_1.default)().toJSON(),
14
- ...(0, shared_1.default)(options),
15
- });
12
+ super(Object.assign({ wallet: (0, wallet_1.default)().toJSON() }, (0, shared_1.default)(options)));
16
13
  }
17
14
  }
18
15
  module.exports = WalletAuthenticator;
@@ -1,15 +1,13 @@
1
1
  import { WalletHandlers as Handler } from '@arcblock/did-auth';
2
2
  declare class WalletHandlers extends Handler {
3
3
  enableConnect: boolean;
4
- sendNotificationFn: Function;
5
- sendToRelayFn: Function;
4
+ sendNotificationFn: $TSFixMe;
6
5
  /**
7
- * @param {boolean} params.autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
8
- * @param {boolean} params.connectedDidOnly only current login did or connected did can connect
9
- * @param {function} [params.sendNotificationFn] use in a non-blocklet environment
10
- * @param {function} [params.sendToRelayFn]
6
+ * @param {boolean} autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
7
+ * @param {boolean} connectedDidOnly only current login did or connected did can connect
8
+ * @param {function} sendNotificationFn use in a non-blocklet environment
11
9
  */
12
- constructor({ autoConnect, connectedDidOnly, sendNotificationFn, sendToRelayFn, options, ...opts }: any);
10
+ constructor({ autoConnect, connectedDidOnly, sendNotificationFn, options, ...opts }: $TSFixMe);
13
11
  getConnectedDid: ({ req, didwallet, extraParams }: $TSFixMe) => any;
14
12
  attach({ onStart, ...opts }: {
15
13
  [x: string]: any;
@@ -22,6 +22,26 @@ 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
+ };
25
45
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
46
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
47
  };
@@ -36,21 +56,19 @@ const inMobileWallet = (didwallet) => {
36
56
  };
37
57
  class WalletHandlers extends did_auth_1.WalletHandlers {
38
58
  /**
39
- * @param {boolean} params.autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
40
- * @param {boolean} params.connectedDidOnly only current login did or connected did can connect
41
- * @param {function} [params.sendNotificationFn] use in a non-blocklet environment
42
- * @param {function} [params.sendToRelayFn]
59
+ * @param {boolean} autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
60
+ * @param {boolean} connectedDidOnly only current login did or connected did can connect
61
+ * @param {function} sendNotificationFn use in a non-blocklet environment
43
62
  */
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
- });
63
+ constructor(_a) {
64
+ var { autoConnect = true, connectedDidOnly = false, sendNotificationFn, options = {} } = _a, opts = __rest(_a, ["autoConnect", "connectedDidOnly", "sendNotificationFn", "options"]);
65
+ // FIXME: wait check
66
+ // if (autoConnect && connectedDidOnly) {
67
+ // options.sessionDidKey = CONNECTED_DID_KEY;
68
+ // }
69
+ super(Object.assign({ options: Object.assign(Object.assign({}, options), {
70
+ sessionDidKey: autoConnect && connectedDidOnly ? CONNECTED_DID_KEY : options === null || options === void 0 ? void 0 : options.sessionDidKey,
71
+ }) }, opts));
54
72
  this.getConnectedDid = ({ req, didwallet, extraParams }) => {
55
73
  if (extraParams && extraParams.autoConnect === 'false') {
56
74
  return null;
@@ -65,16 +83,12 @@ class WalletHandlers extends did_auth_1.WalletHandlers {
65
83
  };
66
84
  this.enableConnect = !!autoConnect;
67
85
  this.sendNotificationFn = sendNotificationFn || notification_1.sendToUser.bind(notification_1.default);
68
- this.sendToRelayFn = sendToRelayFn || notification_1.sendToRelay.bind(notification_1.default);
69
- // @ts-ignore
70
- this.on('updated', (session) => {
71
- this.sendToRelayFn(session.token, 'updated', session).catch(console.error);
72
- });
73
86
  }
74
- attach({ onStart = noop, ...opts }) {
75
- const realOnStart = async (params) => {
87
+ attach(_a) {
88
+ var { onStart = noop } = _a, opts = __rest(_a, ["onStart"]);
89
+ const realOnStart = (params) => __awaiter(this, void 0, void 0, function* () {
76
90
  // @ts-expect-error TS(2554) FIXME: Expected 0 arguments, but got 1.
77
- const extra = (await onStart(params)) || {};
91
+ const extra = (yield onStart(params)) || {};
78
92
  const connectedDid = this.getConnectedDid(params);
79
93
  // fill extra
80
94
  extra.connectedDid = connectedDid || '';
@@ -82,8 +96,9 @@ class WalletHandlers extends did_auth_1.WalletHandlers {
82
96
  // send notification to wallet to trigger wallet to auto connect
83
97
  if (connectedDid) {
84
98
  // wallet use check url to check status of the session
85
- let checkUrl;
99
+ let checkUrl = '';
86
100
  try {
101
+ // @ts-expect-error TS(2322) FIXME: Type 'URL' is not assignable to type 'string'.
87
102
  checkUrl = new URL(decodeURIComponent(new URL(params.deepLink).searchParams.get('url')));
88
103
  checkUrl.pathname = checkUrl.pathname.replace(/auth$/, 'status');
89
104
  }
@@ -107,12 +122,9 @@ class WalletHandlers extends did_auth_1.WalletHandlers {
107
122
  });
108
123
  }
109
124
  return extra;
110
- };
111
- // @ts-expect-error TS(2345) FIXME: Argument of type '{ onStart: (params: any) => Prom... Remove this comment to see the full error message
112
- super.attach({
113
- onStart: realOnStart,
114
- ...opts,
115
125
  });
126
+ // @ts-expect-error TS(2345) FIXME: Argument of type '{ onStart: (params: any) => Prom... Remove this comment to see the full error message
127
+ super.attach(Object.assign({ onStart: realOnStart }, opts));
116
128
  }
117
129
  }
118
130
  module.exports = WalletHandlers;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.8.67-beta-65933c91",
6
+ "version": "1.8.67",
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,27 +26,24 @@
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",
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",
29
+ "@abtnode/client": "1.8.67",
30
+ "@abtnode/constant": "1.8.67",
31
+ "@arcblock/did-auth": "1.18.42",
32
+ "@arcblock/jwt": "1.18.42",
33
+ "@arcblock/ws": "1.18.42",
34
+ "@blocklet/constant": "1.8.67",
35
+ "@blocklet/meta": "1.8.67",
36
+ "@did-connect/authenticator": "^2.1.34",
37
+ "@did-connect/handler": "^2.1.34",
39
38
  "@nedb/core": "^2.1.5",
40
- "@ocap/mcrypto": "1.18.56",
41
- "@ocap/wallet": "1.18.56",
39
+ "@ocap/mcrypto": "1.18.42",
40
+ "@ocap/wallet": "1.18.42",
42
41
  "axios": "^0.27.2",
43
42
  "fs-extra": "^10.1.0",
44
43
  "joi": "17.7.0",
45
- "jsdom": "^21.1.0",
46
44
  "json-stable-stringify": "^1.0.1",
47
45
  "lodash": "^4.17.21",
48
46
  "lru-cache": "^6.0.0",
49
- "ufo": "^1.1.1",
50
47
  "url-join": "^4.0.1"
51
48
  },
52
49
  "resolutions": {
@@ -64,11 +61,12 @@
64
61
  "detect-port": "^1.5.1",
65
62
  "eslint": "^8.25.0",
66
63
  "jest": "^29.2.0",
67
- "joi-to-typescript": "^4.0.7",
64
+ "joi-to-typescript": "^4.0.6",
68
65
  "json-stable-stringify": "^1.0.1",
69
66
  "prettier": "^2.7.1",
70
67
  "ts-jest": "^29.0.3",
71
68
  "ts-node": "^10.9.1",
72
69
  "typescript": "^4.8.4"
73
- }
70
+ },
71
+ "gitHead": "543dbadffd29dc4f096261e136a2a306885d6508"
74
72
  }
@@ -1,9 +0,0 @@
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 };
@@ -1,13 +0,0 @@
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 };
@@ -1,26 +0,0 @@
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 };
@@ -1,134 +0,0 @@
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
- };
@@ -1,7 +0,0 @@
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
- };
@@ -1,95 +0,0 @@
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;