@blocklet/sdk 1.16.11-beta-0ae58a71 → 1.16.11-beta-f74663ac

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,14 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import { AxiosResponse, Method } from 'axios';
3
3
  import { IncomingMessage } from 'http';
4
- export type MountPoint = {
5
- did: string;
6
- name: string;
7
- title: string;
8
- port: number;
9
- webEndpoint: string;
10
- mountPoint: string;
11
- };
12
4
  declare const getChildWebEndpoint: (name: string) => string;
13
5
  declare const getParentWebEndpoint: () => string;
14
6
  declare const getComponentWebEndpoint: (keyword: string) => string;
@@ -8,17 +8,9 @@ const util_1 = require("@blocklet/meta/lib/util");
8
8
  const axios_1 = __importDefault(require("axios"));
9
9
  const get_1 = __importDefault(require("lodash/get"));
10
10
  const url_join_1 = __importDefault(require("url-join"));
11
+ const constant_1 = require("@blocklet/constant");
11
12
  const config_1 = require("../config");
12
13
  const verify_sign_1 = require("../util/verify-sign");
13
- const parseMountPoints = () => {
14
- const mountPoints = JSON.parse(process.env.BLOCKLET_MOUNT_POINTS) || [];
15
- mountPoints.forEach((x) => {
16
- if (x.port) {
17
- x.webEndpoint = `http://127.0.0.1:${x.port}`;
18
- }
19
- });
20
- return mountPoints;
21
- };
22
14
  const doCall = async ({ url, ...options }) => {
23
15
  try {
24
16
  const resp = await (0, axios_1.default)({
@@ -33,13 +25,16 @@ const doCall = async ({ url, ...options }) => {
33
25
  return resp;
34
26
  }
35
27
  catch (error) {
28
+ delete error.config;
29
+ delete error.request;
30
+ delete error.response;
36
31
  config_1.logger.error(`call ${url} api failed`, {
37
32
  url,
38
33
  responseStatus: (0, get_1.default)(error, 'response.status'),
39
34
  responseData: (0, get_1.default)(error, 'response.data'),
40
35
  error,
41
36
  });
42
- throw new Error(`call ${url} api failed`);
37
+ throw new Error(`call ${url} api failed: ${error.message}`);
43
38
  }
44
39
  };
45
40
  const parsePorts = () => JSON.parse(process.env.BLOCKLET_WEB_PORTS);
@@ -60,30 +55,42 @@ const getParentWebEndpoint = () => {
60
55
  return getWebEndpoint(parentName);
61
56
  };
62
57
  exports.getParentWebEndpoint = getParentWebEndpoint;
58
+ const getComponent = (name) => {
59
+ const item = config_1.components.find((x) => [x.title, x.name, x.did].includes(name));
60
+ return item;
61
+ };
63
62
  const getComponentWebEndpoint = (keyword) => {
64
- const mountPoints = parseMountPoints();
65
- const item = mountPoints.find((x) => [x.title, x.name, x.did].includes(keyword));
63
+ const item = getComponent(keyword);
66
64
  return item ? item.webEndpoint : '';
67
65
  };
68
66
  exports.getComponentWebEndpoint = getComponentWebEndpoint;
69
67
  const call = async ({ name, method = 'POST', path: _path, ...options }) => {
70
- let baseURL;
71
- if (name) {
72
- baseURL = getComponentWebEndpoint(name) || getChildWebEndpoint(name);
68
+ if (!name) {
69
+ throw new Error('component.call: name is required');
73
70
  }
74
- else {
75
- baseURL = getParentWebEndpoint();
71
+ const component = getComponent(name);
72
+ if (!component) {
73
+ throw new Error(`can not find component ${name}`);
76
74
  }
75
+ const baseURL = component.webEndpoint;
77
76
  if (!baseURL) {
78
77
  throw new Error(`can not find web endpoint for ${name}`);
79
78
  }
80
79
  const url = (0, url_join_1.default)(baseURL, _path);
81
- return doCall({ url, method, ...options });
80
+ try {
81
+ const resp = await doCall({ url, method, ...options });
82
+ return resp;
83
+ }
84
+ catch (error) {
85
+ if (component.status !== constant_1.BlockletStatus.running) {
86
+ throw new Error(`component ${name} is not running`);
87
+ }
88
+ throw error;
89
+ }
82
90
  };
83
91
  exports.call = call;
84
92
  const getComponentMountPoint = (keyword) => {
85
- const mountPoints = parseMountPoints();
86
- const item = mountPoints.find((x) => [x.title, x.name, x.did].includes(keyword));
93
+ const item = getComponent(keyword);
87
94
  return item ? item.mountPoint : '';
88
95
  };
89
96
  exports.getComponentMountPoint = getComponentMountPoint;
@@ -92,5 +99,5 @@ exports.default = {
92
99
  getComponentMountPoint,
93
100
  getComponentWebEndpoint,
94
101
  getChildWebEndpoint,
95
- getParentWebEndpoint,
102
+ getParentWebEndpoint, // deprecated
96
103
  };
package/lib/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export declare const logger: {
1
+ import { TComponentInternalInfo } from '@blocklet/meta/lib/util';
2
+ declare const logger: {
2
3
  info: {
3
4
  (...data: any[]): void;
4
5
  (message?: any, ...optionalParams: any[]): void;
@@ -13,6 +14,29 @@ export declare const logger: {
13
14
  (message?: any, ...optionalParams: any[]): void;
14
15
  };
15
16
  };
17
+ declare const env: Readonly<{
18
+ appId: string;
19
+ appPid: string;
20
+ appIds: string[];
21
+ appName: string;
22
+ appDescription: string;
23
+ appUrl: string;
24
+ isComponent: boolean;
25
+ dataDir: string;
26
+ cacheDir: string;
27
+ mode: string;
28
+ appStorageEndpoint: string;
29
+ serverVersion: string;
30
+ preferences: {
31
+ [key: string]: any;
32
+ };
33
+ }>;
34
+ type MountPoint = TComponentInternalInfo & {
35
+ webEndpoint: string;
36
+ };
37
+ type TComponents = Array<MountPoint>;
38
+ declare const components: TComponents;
39
+ export { logger, env, components, MountPoint };
16
40
  declare const _default: {
17
41
  logger: {
18
42
  info: {
@@ -29,5 +53,23 @@ declare const _default: {
29
53
  (message?: any, ...optionalParams: any[]): void;
30
54
  };
31
55
  };
56
+ env: Readonly<{
57
+ appId: string;
58
+ appPid: string;
59
+ appIds: string[];
60
+ appName: string;
61
+ appDescription: string;
62
+ appUrl: string;
63
+ isComponent: boolean;
64
+ dataDir: string;
65
+ cacheDir: string;
66
+ mode: string;
67
+ appStorageEndpoint: string;
68
+ serverVersion: string;
69
+ preferences: {
70
+ [key: string]: any;
71
+ };
72
+ }>;
73
+ components: TComponents;
32
74
  };
33
75
  export default _default;
package/lib/config.js CHANGED
@@ -1,8 +1,29 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.logger = void 0;
6
+ exports.components = exports.env = exports.logger = void 0;
4
7
  /* eslint-disable no-console */
5
- exports.logger = {
8
+ const events_1 = __importDefault(require("events"));
9
+ const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
10
+ const env_1 = __importDefault(require("@blocklet/env"));
11
+ const constant_1 = require("@blocklet/constant");
12
+ const notification_1 = __importDefault(require("./service/notification"));
13
+ const emitter = new events_1.default();
14
+ const Events = {
15
+ componentsUpdate: 'componentsUpdate',
16
+ envUpdate: 'envUpdate',
17
+ };
18
+ const AppConfigKeyMap = {
19
+ BLOCKLET_APP_NAME: 'appName',
20
+ BLOCKLET_APP_DESCRIPTION: 'appDescription',
21
+ BLOCKLET_APP_URL: 'appUrl',
22
+ BLOCKLET_APP_SPACE_ENDPOINT: 'appStorageEndpoint',
23
+ ABT_NODE_VERSION: 'serverVersion',
24
+ ABT_NODE: 'serverVersion', // for backup compatibility
25
+ };
26
+ const logger = {
6
27
  info: console.log,
7
28
  debug: (...args) => {
8
29
  if (process.env.NODE_ENV === 'development') {
@@ -12,6 +33,43 @@ exports.logger = {
12
33
  warn: console.warn,
13
34
  error: console.error,
14
35
  };
36
+ exports.logger = logger;
37
+ const env = (0, cloneDeep_1.default)(env_1.default);
38
+ exports.env = env;
39
+ const parseComponents = () => {
40
+ const mountPoints = JSON.parse(process.env.BLOCKLET_MOUNT_POINTS || '[]') || [];
41
+ mountPoints.forEach((x) => {
42
+ if (x.port) {
43
+ x.webEndpoint = `http://127.0.0.1:${x.port}`;
44
+ }
45
+ });
46
+ return mountPoints;
47
+ };
48
+ const components = parseComponents();
49
+ exports.components = components;
50
+ const inRuntimeEnv = !!process.env.BLOCKLET_APP_SK;
51
+ if (inRuntimeEnv) {
52
+ notification_1.default.on(constant_1.BlockletInternalEvents.componentsUpdated, (data) => {
53
+ components.splice(0, components.length);
54
+ components.push(...data.components.map((x) => {
55
+ if (x.port) {
56
+ x.webEndpoint = `http://127.0.0.1:${x.port}`;
57
+ }
58
+ return x;
59
+ }));
60
+ emitter.emit(Events.componentsUpdate, components);
61
+ });
62
+ notification_1.default.on(constant_1.BlockletInternalEvents.appConfigChanged, (data) => {
63
+ const configObj = (data.configs || []).reduce((o, { key, value }) => {
64
+ o[AppConfigKeyMap[key] || key] = value;
65
+ return o;
66
+ }, {});
67
+ Object.assign(env, configObj);
68
+ emitter.emit(Events.envUpdate, configObj);
69
+ });
70
+ }
15
71
  exports.default = {
16
- logger: exports.logger,
72
+ logger,
73
+ env,
74
+ components,
17
75
  };
@@ -8,6 +8,6 @@ declare class DataBase<T = AnyObject> extends BaseStore<T> {
8
8
  page?: number;
9
9
  size?: number;
10
10
  projection?: ProjectionQuery<T>;
11
- }): Promise<import("@nedb/core").Row<T>[]>;
11
+ }): PromiseLike<import("@nedb/core").Row<T>[]>;
12
12
  }
13
13
  export = DataBase;
@@ -34,7 +34,7 @@ class DataBase extends core_1.DataStore {
34
34
  const doc = await this.findOne(query);
35
35
  return !!doc;
36
36
  }
37
- async paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {}, }) {
37
+ paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {}, }) {
38
38
  return this.cursor(condition)
39
39
  .sort(sort)
40
40
  .skip(Math.max(page * size - size, 0))
package/lib/index.d.ts CHANGED
@@ -9,9 +9,9 @@ import createConnectHandlers from './connect/handler';
9
9
  import Database from './database/index';
10
10
  import middlewares from './middlewares/index';
11
11
  import getWallet from './wallet';
12
- import Component, { MountPoint } from './component/index';
12
+ import Component from './component/index';
13
13
  import Security from './security/index';
14
- import config from './config';
14
+ import config, { MountPoint } from './config';
15
15
  export { Auth as AuthService };
16
16
  export { Auth };
17
17
  export { Notification as NotificationService };
@@ -11,7 +11,7 @@ declare const _default: {
11
11
  role: string;
12
12
  fullName: string;
13
13
  };
14
- }, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => Promise<void>;
14
+ }, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => void;
15
15
  auth: ({ roles, permissions, getClient }?: {
16
16
  roles?: string[];
17
17
  permissions?: string[];
@@ -6,5 +6,5 @@ type User = {
6
6
  };
7
7
  declare const userMiddleware: () => (req: Request & {
8
8
  user?: User;
9
- }, res: Response, next: NextFunction) => Promise<void>;
9
+ }, res: Response, next: NextFunction) => void;
10
10
  export = userMiddleware;
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const userMiddleware = () => async (req, res, next) => {
2
+ const userMiddleware = () => (req, res, next) => {
3
3
  if (req.headers['x-user-did']) {
4
4
  req.user = {
5
5
  did: req.headers['x-user-did'],
@@ -32,6 +32,7 @@ const Jwt = __importStar(require("@arcblock/jwt"));
32
32
  const events_1 = __importDefault(require("events"));
33
33
  const ws_1 = require("@arcblock/ws");
34
34
  const channel_1 = require("@blocklet/meta/lib/channel");
35
+ const constant_1 = require("@blocklet/constant");
35
36
  const check_blocklet_env_1 = __importDefault(require("../util/check-blocklet-env"));
36
37
  const send_notification_1 = require("../util/send-notification");
37
38
  const constants_1 = require("../util/constants");
@@ -52,11 +53,13 @@ const getSender = () => {
52
53
  * }} options
53
54
  * @returns
54
55
  */
56
+ // eslint-disable-next-line require-await
55
57
  const doSendToUser = async (receiver, notification, options) => {
56
58
  (0, check_blocklet_env_1.default)();
57
59
  return (0, send_notification_1.sendToUser)(receiver, notification, getSender(), process.env.ABT_NODE_SERVICE_PORT, options);
58
60
  };
59
61
  exports.sendToUser = doSendToUser;
62
+ // eslint-disable-next-line require-await
60
63
  const doSendToRelay = async (topic, event, data) => {
61
64
  (0, check_blocklet_env_1.default)();
62
65
  return (0, send_notification_1.sendToRelay)(topic, event, data, getSender(), process.env.ABT_NODE_SERVICE_PORT);
@@ -73,6 +76,7 @@ exports.sendToRelay = doSendToRelay;
73
76
  * }} options
74
77
  * @returns
75
78
  */
79
+ // eslint-disable-next-line require-await
76
80
  const broadcast = async (notification, options = {}) => {
77
81
  (0, check_blocklet_env_1.default)();
78
82
  const sender = getSender();
@@ -116,6 +120,18 @@ const initClient = () => {
116
120
  console.error(msg);
117
121
  emitError({ message: msg });
118
122
  });
123
+ appPublicChannel
124
+ .join()
125
+ .receive('error', (err) => {
126
+ const msg = `join channel error: ${err.message}`;
127
+ console.error(msg);
128
+ emitter.emit('error', { message: msg });
129
+ })
130
+ .receive('timeout', () => {
131
+ const msg = 'join channel timeout';
132
+ console.error(msg);
133
+ emitter.emit('error', { message: msg });
134
+ });
119
135
  messageChannel.on('message', ({ status, response } = {}) => {
120
136
  if (status === 'ok') {
121
137
  messageEmitter.emit(response.type, response);
@@ -131,17 +147,27 @@ const initClient = () => {
131
147
  });
132
148
  }
133
149
  });
134
- appPublicChannel
135
- .join()
136
- .receive('error', (err) => {
137
- const msg = `join channel error: ${err.message}`;
138
- console.error(msg);
139
- emitter.emit('error', { message: msg });
140
- })
141
- .receive('timeout', () => {
142
- const msg = 'join channel timeout';
143
- console.error(msg);
144
- emitter.emit('error', { message: msg });
150
+ [constant_1.BlockletInternalEvents.componentsUpdated, constant_1.BlockletInternalEvents.appConfigChanged].forEach((event) => {
151
+ messageChannel.on(event, ({ status, response } = {}) => {
152
+ if (status === 'ok') {
153
+ const { data, sender } = response;
154
+ // verify sender is server
155
+ if (!Jwt.verify(sender.token, process.env.ABT_NODE_PK)) {
156
+ const message = `verify sender failed in internal events. event: ${event}, sender: ${JSON.stringify(sender)}`;
157
+ emitError({ message });
158
+ console.error(message);
159
+ return;
160
+ }
161
+ emitter.emit(event, data);
162
+ }
163
+ else {
164
+ emitError(response);
165
+ console.error({
166
+ status,
167
+ response,
168
+ });
169
+ }
170
+ });
145
171
  });
146
172
  appPublicChannel.on(notification_1.NOTIFICATION_TYPES.HI, ({ status, response } = {}) => {
147
173
  if (status === 'ok') {
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.emailConfigSchema = void 0;
7
+ /* eslint-disable import/prefer-default-export */
7
8
  const joi_1 = __importDefault(require("joi"));
8
9
  const emailConfigSchema = joi_1.default.object({
9
10
  from: joi_1.default.string().email().required(),
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.16.11-beta-0ae58a71",
6
+ "version": "1.16.11-beta-f74663ac",
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,15 +26,15 @@
26
26
  "author": "linchen1987 <linchen.1987@foxmail.com> (http://github.com/linchen1987)",
27
27
  "license": "Apache-2.0",
28
28
  "dependencies": {
29
- "@abtnode/client": "1.16.11-beta-0ae58a71",
30
- "@abtnode/constant": "1.16.11-beta-0ae58a71",
29
+ "@abtnode/client": "1.16.11-beta-f74663ac",
30
+ "@abtnode/constant": "1.16.11-beta-f74663ac",
31
31
  "@arcblock/did": "1.18.80",
32
32
  "@arcblock/did-auth": "1.18.80",
33
33
  "@arcblock/jwt": "1.18.80",
34
34
  "@arcblock/ws": "1.18.80",
35
- "@blocklet/constant": "1.16.11-beta-0ae58a71",
36
- "@blocklet/env": "1.16.11-beta-0ae58a71",
37
- "@blocklet/meta": "1.16.11-beta-0ae58a71",
35
+ "@blocklet/constant": "1.16.11-beta-f74663ac",
36
+ "@blocklet/env": "1.16.11-beta-f74663ac",
37
+ "@blocklet/meta": "1.16.11-beta-f74663ac",
38
38
  "@did-connect/authenticator": "^2.1.59",
39
39
  "@did-connect/handler": "^2.1.59",
40
40
  "@nedb/core": "^2.1.5",
@@ -55,7 +55,7 @@
55
55
  "@nedb/core": "^2.1.2"
56
56
  },
57
57
  "devDependencies": {
58
- "@arcblock/eslint-config-ts": "^0.2.3",
58
+ "@arcblock/eslint-config-ts": "^0.2.4",
59
59
  "@types/express": "^4.17.14",
60
60
  "@types/jest": "^29.2.0",
61
61
  "@types/json-stable-stringify": "^1.0.34",
@@ -73,5 +73,5 @@
73
73
  "ts-node": "^10.9.1",
74
74
  "typescript": "^5.0.4"
75
75
  },
76
- "gitHead": "5d044a08b4399eb855563e670af7cbd0d3851e94"
76
+ "gitHead": "c59bc852f73b9e216af9d806b9c9e24b2e37ae27"
77
77
  }