@blocklet/sdk 1.8.33 → 1.8.35

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.
Files changed (53) hide show
  1. package/lib/component/index.d.ts +35 -0
  2. package/lib/component/index.js +83 -80
  3. package/lib/config.d.ts +33 -0
  4. package/lib/config.js +10 -7
  5. package/lib/connect/authenticator.d.ts +5 -0
  6. package/lib/connect/authenticator.js +14 -15
  7. package/lib/connect/handler.d.ts +2 -0
  8. package/lib/connect/handler.js +91 -65
  9. package/lib/connect/shared.d.ts +13 -0
  10. package/lib/connect/shared.js +26 -31
  11. package/lib/database/index.d.ts +13 -0
  12. package/lib/database/index.js +52 -39
  13. package/lib/env.d.ts +12 -0
  14. package/lib/env.js +12 -9
  15. package/lib/error-handler.d.ts +0 -0
  16. package/lib/error-handler.js +5 -5
  17. package/lib/index.d.ts +51 -0
  18. package/lib/index.js +51 -40
  19. package/lib/middlewares/auth.d.ts +3 -0
  20. package/lib/middlewares/auth.js +52 -49
  21. package/lib/middlewares/component.d.ts +7 -0
  22. package/lib/middlewares/component.js +28 -24
  23. package/lib/middlewares/index.d.ts +20 -0
  24. package/lib/middlewares/index.js +16 -8
  25. package/lib/middlewares/user.d.ts +10 -0
  26. package/lib/middlewares/user.js +20 -10
  27. package/lib/security/index.d.ts +9 -0
  28. package/lib/security/index.js +22 -21
  29. package/lib/service/auth.d.ts +9 -0
  30. package/lib/service/auth.js +132 -165
  31. package/lib/service/notification.d.ts +44 -0
  32. package/lib/service/notification.js +149 -129
  33. package/lib/types/notification.d.ts +71 -0
  34. package/lib/types/notification.js +3 -0
  35. package/lib/util/check-blocklet-env.d.ts +2 -0
  36. package/lib/util/check-blocklet-env.js +20 -19
  37. package/lib/util/constants.d.ts +5 -0
  38. package/lib/util/constants.js +6 -2
  39. package/lib/util/send-notification.d.ts +25 -0
  40. package/lib/util/send-notification.js +118 -115
  41. package/lib/validators/index.d.ts +12 -0
  42. package/lib/validators/index.js +13 -7
  43. package/lib/validators/notification.d.ts +59 -0
  44. package/lib/validators/notification.js +127 -97
  45. package/lib/version.d.ts +6 -0
  46. package/lib/version.js +6 -0
  47. package/lib/wallet-authenticator.d.ts +5 -0
  48. package/lib/wallet-authenticator.js +13 -16
  49. package/lib/wallet-handler.d.ts +17 -0
  50. package/lib/wallet-handler.js +121 -88
  51. package/lib/wallet.d.ts +3 -0
  52. package/lib/wallet.js +9 -10
  53. package/package.json +40 -18
@@ -0,0 +1,35 @@
1
+ import { AxiosResponse } from 'axios';
2
+ export declare type MountPoint = {
3
+ did: string;
4
+ name: string;
5
+ title: string;
6
+ port: number;
7
+ webEndpoint: string;
8
+ mountPoint: string;
9
+ };
10
+ declare const getChildWebEndpoint: (name: string) => string;
11
+ declare const getParentWebEndpoint: () => string;
12
+ declare const call: ({ name, path: _path, data }: {
13
+ name?: string;
14
+ path: string;
15
+ data: any;
16
+ }) => Promise<AxiosResponse<any, any>>;
17
+ declare const getComponentMountPoint: (keyword: string) => string;
18
+ declare const getComponentWebEndpoint: (keyword: string) => string;
19
+ export { call };
20
+ export { getComponentMountPoint };
21
+ export { getComponentWebEndpoint };
22
+ export { getChildWebEndpoint };
23
+ export { getParentWebEndpoint };
24
+ declare const _default: {
25
+ call: ({ name, path: _path, data }: {
26
+ name?: string;
27
+ path: string;
28
+ data: any;
29
+ }) => Promise<AxiosResponse<any, any>>;
30
+ getComponentMountPoint: (keyword: string) => string;
31
+ getComponentWebEndpoint: (keyword: string) => string;
32
+ getChildWebEndpoint: (name: string) => string;
33
+ getParentWebEndpoint: () => string;
34
+ };
35
+ export default _default;
@@ -1,92 +1,95 @@
1
- const axios = require('axios').default;
2
- const get = require('lodash/get');
3
- const joinURL = require('url-join');
4
- const stableStringify = require('json-stable-stringify');
5
- const { getParentComponentName } = require('@blocklet/meta/lib/util');
6
-
7
- const getWallet = require('../wallet');
8
- const config = require('../config');
9
-
10
- const parseMountPoints = () => {
11
- const mountPoints = JSON.parse(process.env.BLOCKLET_MOUNT_POINTS) || [];
12
-
13
- mountPoints.forEach((x) => {
14
- if (x.port) {
15
- x.webEndpoint = `http://127.0.0.1:${x.port}`;
16
- }
17
- });
18
-
19
- return mountPoints;
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
+ });
20
10
  };
21
-
22
- const parsePorts = () => JSON.parse(process.env.BLOCKLET_WEB_PORTS);
23
-
24
- const call = async ({ name, path: _path, data }) => {
25
- const baseURL = name ? getChildWebEndpoint(name) : getParentWebEndpoint();
26
-
27
- const url = joinURL(baseURL, _path);
28
-
29
- return doCall({ url, data });
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
30
13
  };
31
-
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getParentWebEndpoint = exports.getChildWebEndpoint = exports.getComponentWebEndpoint = exports.getComponentMountPoint = exports.call = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const get_1 = __importDefault(require("lodash/get"));
18
+ const url_join_1 = __importDefault(require("url-join"));
19
+ const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
20
+ const util_1 = require("@blocklet/meta/lib/util");
21
+ const wallet_1 = __importDefault(require("../wallet"));
22
+ const config_1 = require("../config");
23
+ const sign = (data) => {
24
+ const wallet = (0, wallet_1.default)();
25
+ const signData = typeof data === 'undefined' ? {} : data;
26
+ return { 'x-component-sig': wallet.sign((0, json_stable_stringify_1.default)(signData)) };
27
+ };
28
+ const doCall = ({ url, data }) => __awaiter(void 0, void 0, void 0, function* () {
29
+ try {
30
+ const resp = yield axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
31
+ config_1.logger.info(`call ${url} api success`);
32
+ return resp;
33
+ }
34
+ catch (error) {
35
+ config_1.logger.error(`call ${url} api failed`, {
36
+ url,
37
+ responseStatus: (0, get_1.default)(error, 'response.status'),
38
+ responseData: (0, get_1.default)(error, 'response.data'),
39
+ error,
40
+ });
41
+ throw new Error(`call ${url} api failed`);
42
+ }
43
+ });
44
+ const parsePorts = () => JSON.parse(process.env.BLOCKLET_WEB_PORTS);
32
45
  const getWebEndpoint = (name) => {
33
- const ports = parsePorts();
34
- if (ports[name]) {
35
- return `http://127.0.0.1:${ports[name]}`;
36
- }
37
- return '';
46
+ const ports = parsePorts();
47
+ if (ports[name]) {
48
+ return `http://127.0.0.1:${ports[name]}`;
49
+ }
50
+ return '';
38
51
  };
39
-
40
52
  const getChildWebEndpoint = (name) => {
41
- const fullName = `${process.env.BLOCKLET_REAL_NAME}/${name}`;
42
- return getWebEndpoint(fullName);
53
+ const fullName = `${process.env.BLOCKLET_REAL_NAME}/${name}`;
54
+ return getWebEndpoint(fullName);
43
55
  };
44
-
56
+ exports.getChildWebEndpoint = getChildWebEndpoint;
45
57
  const getParentWebEndpoint = () => {
46
- const parentName = getParentComponentName(process.env.BLOCKLET_REAL_NAME);
47
- return getWebEndpoint(parentName);
58
+ const parentName = (0, util_1.getParentComponentName)(process.env.BLOCKLET_REAL_NAME);
59
+ return getWebEndpoint(parentName);
48
60
  };
49
-
50
- const getComponentMountPoint = (s) => {
51
- const mountPoints = parseMountPoints();
52
- const item = mountPoints.find((x) => [x.title, x.name, x.did].includes(s));
53
- return item ? item.mountPoint : '';
54
- };
55
-
56
- const getComponentWebEndpoint = (s) => {
57
- const mountPoints = parseMountPoints();
58
- const item = mountPoints.find((x) => [x.title, x.name, x.did].includes(s));
59
- return item ? item.webEndpoint : '';
61
+ exports.getParentWebEndpoint = getParentWebEndpoint;
62
+ const parseMountPoints = () => {
63
+ const mountPoints = JSON.parse(process.env.BLOCKLET_MOUNT_POINTS) || [];
64
+ mountPoints.forEach((x) => {
65
+ if (x.port) {
66
+ x.webEndpoint = `http://127.0.0.1:${x.port}`;
67
+ }
68
+ });
69
+ return mountPoints;
60
70
  };
61
-
62
- const sign = (data) => {
63
- const wallet = getWallet();
64
- const signData = typeof data === 'undefined' ? {} : data;
65
-
66
- return { 'x-component-sig': wallet.sign(stableStringify(signData)) };
71
+ const call = ({ name, path: _path, data }) => __awaiter(void 0, void 0, void 0, function* () {
72
+ const baseURL = name ? getChildWebEndpoint(name) : getParentWebEndpoint();
73
+ const url = (0, url_join_1.default)(baseURL, _path);
74
+ return doCall({ url, data });
75
+ });
76
+ exports.call = call;
77
+ const getComponentMountPoint = (keyword) => {
78
+ const mountPoints = parseMountPoints();
79
+ const item = mountPoints.find((x) => [x.title, x.name, x.did].includes(keyword));
80
+ return item ? item.mountPoint : '';
67
81
  };
68
-
69
- const doCall = async ({ url, data }) => {
70
- try {
71
- const resp = await axios.post(url, data, { headers: sign(data), timeout: 60000 });
72
- config.logger.info(`call ${url} api success`);
73
- return resp;
74
- } catch (error) {
75
- config.logger.error(`call ${url} api failed`, {
76
- url,
77
- responseStatus: get(error, 'response.status'),
78
- responseData: get(error, 'response.data'),
79
- error,
80
- });
81
-
82
- throw new Error(`call ${url} api failed`);
83
- }
82
+ exports.getComponentMountPoint = getComponentMountPoint;
83
+ const getComponentWebEndpoint = (keyword) => {
84
+ const mountPoints = parseMountPoints();
85
+ const item = mountPoints.find((x) => [x.title, x.name, x.did].includes(keyword));
86
+ return item ? item.webEndpoint : '';
84
87
  };
85
-
86
- module.exports = {
87
- call,
88
- getComponentMountPoint,
89
- getComponentWebEndpoint,
90
- getChildWebEndpoint,
91
- getParentWebEndpoint,
88
+ exports.getComponentWebEndpoint = getComponentWebEndpoint;
89
+ exports.default = {
90
+ call,
91
+ getComponentMountPoint,
92
+ getComponentWebEndpoint,
93
+ getChildWebEndpoint,
94
+ getParentWebEndpoint,
92
95
  };
@@ -0,0 +1,33 @@
1
+ export declare const logger: {
2
+ info: {
3
+ (...data: any[]): void;
4
+ (message?: any, ...optionalParams: any[]): void;
5
+ };
6
+ debug: (...args: any[]) => void;
7
+ warn: {
8
+ (...data: any[]): void;
9
+ (message?: any, ...optionalParams: any[]): void;
10
+ };
11
+ error: {
12
+ (...data: any[]): void;
13
+ (message?: any, ...optionalParams: any[]): void;
14
+ };
15
+ };
16
+ declare const _default: {
17
+ logger: {
18
+ info: {
19
+ (...data: any[]): void;
20
+ (message?: any, ...optionalParams: any[]): void;
21
+ };
22
+ debug: (...args: any[]) => void;
23
+ warn: {
24
+ (...data: any[]): void;
25
+ (message?: any, ...optionalParams: any[]): void;
26
+ };
27
+ error: {
28
+ (...data: any[]): void;
29
+ (message?: any, ...optionalParams: any[]): void;
30
+ };
31
+ };
32
+ };
33
+ export default _default;
package/lib/config.js CHANGED
@@ -1,14 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logger = void 0;
1
4
  /* eslint-disable no-console */
2
-
3
- module.exports = {
4
- logger: {
5
+ exports.logger = {
5
6
  info: console.log,
6
7
  debug: (...args) => {
7
- if (process.env.NODE_ENV === 'development') {
8
- console.debug(...args);
9
- }
8
+ if (process.env.NODE_ENV === 'development') {
9
+ console.debug(...args);
10
+ }
10
11
  },
11
12
  warn: console.warn,
12
13
  error: console.error,
13
- },
14
+ };
15
+ exports.default = {
16
+ logger: exports.logger,
14
17
  };
@@ -0,0 +1,5 @@
1
+ import { Authenticator } from '@did-connect/authenticator';
2
+ declare class BlockletAuthenticator extends Authenticator {
3
+ constructor(options?: {});
4
+ }
5
+ export = BlockletAuthenticator;
@@ -1,16 +1,15 @@
1
- const { Authenticator } = require('@did-connect/authenticator');
2
-
3
- const getWallet = require('../wallet');
4
- const checkBlockletEnv = require('../util/check-blocklet-env');
5
- const getShared = require('./shared');
6
-
7
- module.exports = class BlockletAuthenticator extends Authenticator {
8
- constructor(options = {}) {
9
- checkBlockletEnv();
10
-
11
- super({
12
- wallet: getWallet(),
13
- ...getShared(options),
14
- });
15
- }
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
4
  };
5
+ const authenticator_1 = require("@did-connect/authenticator");
6
+ const wallet_1 = __importDefault(require("../wallet"));
7
+ const check_blocklet_env_1 = __importDefault(require("../util/check-blocklet-env"));
8
+ const shared_1 = __importDefault(require("./shared"));
9
+ class BlockletAuthenticator extends authenticator_1.Authenticator {
10
+ constructor(options = {}) {
11
+ (0, check_blocklet_env_1.default)();
12
+ super(Object.assign({ wallet: (0, wallet_1.default)() }, (0, shared_1.default)(options)));
13
+ }
14
+ }
15
+ module.exports = BlockletAuthenticator;
@@ -0,0 +1,2 @@
1
+ declare const createConnectHandlers: ({ authenticator, storage, logger, socketPathname, sendNotificationFn, }: $TSFixMe) => import("@did-connect/handler").THandlers;
2
+ export = createConnectHandlers;
@@ -1,73 +1,99 @@
1
- const get = require('lodash/get');
2
- const { createHandlers } = require('@did-connect/handler');
3
- const Notification = require('../service/notification');
4
-
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
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 __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ const get_1 = __importDefault(require("lodash/get"));
38
+ const handler_1 = require("@did-connect/handler");
39
+ const notification_1 = __importStar(require("../service/notification"));
5
40
  const noop = () => ({});
6
-
7
41
  // whether app web page is in mobile DID wallet
8
42
  const inMobileWallet = (didwallet) => {
9
- return didwallet && ['ios', 'android'].includes(didwallet.os);
43
+ return didwallet && ['ios', 'android'].includes(didwallet.os);
10
44
  };
11
-
12
45
  const consoleLogger = { info: noop, error: console.error, warn: console.warn, debug: noop };
13
46
  const getConnectedDid = (session) => {
14
- if (session.autoConnect === false) {
15
- return '';
16
- }
17
-
18
- if (inMobileWallet(session.didwallet)) {
19
- return '';
20
- }
21
-
22
- return get(session, 'previousConnected.userDid', '');
23
- };
24
-
25
- module.exports = ({ authenticator, storage, logger = consoleLogger, socketPathname, sendNotificationFn }) => {
26
- const handlers = createHandlers({
27
- storage,
28
- authenticator,
29
- logger,
30
- socketPathname,
31
- });
32
-
33
- const originCreateHandler = handlers.handleSessionCreate;
34
- handlers.handleSessionCreate = async (context) => {
35
- const session = await originCreateHandler(context);
36
- const connectedDid = getConnectedDid(session);
37
-
38
- // send notification to wallet to trigger wallet to auto connect
39
- if (connectedDid) {
40
- // wallet use check url to check status of the session
41
- let checkUrl = '';
42
- try {
43
- checkUrl = new URL(session.authUrl);
44
- checkUrl.pathname = checkUrl.pathname.replace(/\/auth/, '/session');
45
- } catch (e) {
46
- checkUrl = '';
47
- console.error(e);
48
- }
49
-
50
- const deepLink = new URL('https://abtwallet.io/i/');
51
- deepLink.searchParams.set('action', 'requestAuth');
52
- deepLink.searchParams.set('url', encodeURIComponent(session.authUrl));
53
- const message = {
54
- type: 'connect',
55
- url: deepLink.href,
56
- };
57
-
58
- if (checkUrl) {
59
- message.checkUrl = checkUrl.href;
60
- }
61
-
62
- // sendNotificationFn maybe custom function so we need params
63
- const sendFn = sendNotificationFn || Notification.sendToUser.bind(Notification);
64
- sendFn(connectedDid, message, { ...context, session }).catch((err) => {
65
- console.error(err);
66
- });
47
+ if (session.autoConnect === false) {
48
+ return '';
49
+ }
50
+ if (inMobileWallet(session.didwallet)) {
51
+ return '';
67
52
  }
68
-
69
- return session;
70
- };
71
-
72
- return handlers;
53
+ return (0, get_1.default)(session, 'previousConnected.userDid', '');
54
+ };
55
+ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger, socketPathname, sendNotificationFn, }) => {
56
+ const handlers = (0, handler_1.createHandlers)({
57
+ storage,
58
+ authenticator,
59
+ logger,
60
+ socketPathname,
61
+ });
62
+ const originCreateHandler = handlers.handleSessionCreate;
63
+ handlers.handleSessionCreate = (context) => __awaiter(void 0, void 0, void 0, function* () {
64
+ const session = yield originCreateHandler(context);
65
+ const connectedDid = getConnectedDid(session);
66
+ // send notification to wallet to trigger wallet to auto connect
67
+ if (connectedDid) {
68
+ // wallet use check url to check status of the session
69
+ let checkUrl = '';
70
+ try {
71
+ // @ts-expect-error TS(2322) FIXME: Type 'URL' is not assignable to type 'string'.
72
+ checkUrl = new URL(session.authUrl);
73
+ checkUrl.pathname = checkUrl.pathname.replace(/\/auth/, '/session');
74
+ }
75
+ catch (e) {
76
+ checkUrl = '';
77
+ console.error(e);
78
+ }
79
+ const deepLink = new URL('https://abtwallet.io/i/');
80
+ deepLink.searchParams.set('action', 'requestAuth');
81
+ deepLink.searchParams.set('url', encodeURIComponent(session.authUrl));
82
+ const message = {
83
+ type: 'connect',
84
+ url: deepLink.href,
85
+ };
86
+ if (checkUrl) {
87
+ message.checkUrl = checkUrl.href;
88
+ }
89
+ // sendNotificationFn maybe custom function so we need params
90
+ const sendFn = sendNotificationFn || notification_1.sendToUser.bind(notification_1.default);
91
+ sendFn(connectedDid, message, Object.assign(Object.assign({}, context), { session })).catch((err) => {
92
+ console.error(err);
93
+ });
94
+ }
95
+ return session;
96
+ });
97
+ return handlers;
73
98
  };
99
+ module.exports = createConnectHandlers;
@@ -0,0 +1,13 @@
1
+ declare const connectShared: (options?: {}) => {
2
+ appInfo: (...args: any[]) => Promise<{
3
+ name: string | undefined;
4
+ description: string | undefined;
5
+ link: string;
6
+ icon: string;
7
+ updateSubEndpoint: true;
8
+ subscriptionEndpoint: string;
9
+ nodeDid: string | undefined;
10
+ }>;
11
+ chainInfo: () => Record<string, string>;
12
+ };
13
+ export = connectShared;
@@ -1,33 +1,28 @@
1
- const joinUrl = require('url-join');
2
- const { getConnectAppUrl, getChainInfo } = require('@blocklet/meta/lib/util');
3
- const { SERVICE_PREFIX } = require('../util/constants');
4
-
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ const url_join_1 = __importDefault(require("url-join"));
15
+ const util_1 = require("@blocklet/meta/lib/util");
16
+ const constants_1 = require("../util/constants");
5
17
  // wraps value in closure or returns closure
6
18
  const closure = (value) => (typeof value === 'function' ? value : () => value);
7
-
8
- module.exports = (options = {}) => ({
9
- chainInfo: () => getChainInfo(process.env),
10
-
11
- ...options,
12
-
13
- appInfo: async (...args) => {
14
- const info = await closure(options.appInfo)(...args);
15
-
16
- const { request, baseUrl } = args[0];
17
- const groupPathPrefix = request.headers['x-group-path-prefix'] || '/';
18
- const appLogo = process.env.BLOCKLET_APP_LOGO || '';
19
- const appLogoSquare = process.env.BLOCKLET_APP_LOGO_SQUARE || '';
20
- const appLogoStore = joinUrl(baseUrl, SERVICE_PREFIX, '/blocklet/logo');
21
-
22
- return {
23
- name: process.env.BLOCKLET_APP_NAME,
24
- description: process.env.BLOCKLET_APP_DESCRIPTION,
25
- ...(info || {}),
26
- link: getConnectAppUrl(args[0]),
27
- icon: appLogoSquare || appLogo || appLogoStore,
28
- updateSubEndpoint: true,
29
- subscriptionEndpoint: joinUrl(groupPathPrefix, SERVICE_PREFIX, 'websocket'),
30
- nodeDid: process.env.ABT_NODE_DID,
31
- };
32
- },
33
- });
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);
21
+ const { request, baseUrl } = args[0];
22
+ const groupPathPrefix = request.headers['x-group-path-prefix'] || '/';
23
+ const appLogo = process.env.BLOCKLET_APP_LOGO || '';
24
+ const appLogoSquare = process.env.BLOCKLET_APP_LOGO_SQUARE || '';
25
+ const appLogoStore = (0, url_join_1.default)(baseUrl, constants_1.SERVICE_PREFIX, '/blocklet/logo');
26
+ 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: appLogoSquare || appLogo || appLogoStore, updateSubEndpoint: true, subscriptionEndpoint: (0, url_join_1.default)(groupPathPrefix, constants_1.SERVICE_PREFIX, 'websocket'), nodeDid: process.env.ABT_NODE_DID });
27
+ }) }));
28
+ module.exports = connectShared;
@@ -0,0 +1,13 @@
1
+ import { DataStore as BaseStore, DataStoreOptions } from '@nedb/core';
2
+ declare class DataBase extends BaseStore {
3
+ constructor(name: string, options?: DataStoreOptions);
4
+ exists(...args: any[]): Promise<boolean>;
5
+ paginate({ condition, sort, page, size, projection }: {
6
+ condition?: {};
7
+ sort?: {};
8
+ page?: number;
9
+ size?: number;
10
+ projection?: {};
11
+ }): Promise<import("@nedb/core").Row<import("@nedb/core").AnyObject>[]>;
12
+ }
13
+ export = DataBase;
@@ -1,41 +1,54 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const { DataStore: BaseStore } = require('@nedb/core');
4
-
5
- if (!process.env.BLOCKLET_DATA_DIR) {
6
- throw new Error('Blocklet SDK must be used in blocklet runtime');
7
- }
8
-
9
- const DB_DIR = path.join(process.env.BLOCKLET_DATA_DIR, 'db');
10
- fs.ensureDirSync(DB_DIR);
11
-
12
- module.exports = class DataStore extends BaseStore {
13
- constructor(name, options = {}) {
14
- const filename = options.filename || path.join(DB_DIR, `${name}.db`);
15
- super({
16
- filename,
17
- autoload: true,
18
- timestampData: true,
19
- onload: (err) => {
20
- if (err) {
21
- console.error(`failed to load disk database ${filename}`, err);
22
- }
23
- },
24
- ...options,
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());
25
9
  });
26
- }
27
-
28
- async exists(...args) {
29
- const doc = await this.findOne(...args);
30
- return !!doc;
31
- }
32
-
33
- async paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {} }) {
34
- return this.cursor(condition)
35
- .sort(sort)
36
- .skip(Math.max(page * size - size, 0))
37
- .limit(Math.max(size, 1))
38
- .projection(projection)
39
- .exec();
40
- }
41
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ const fs_extra_1 = __importDefault(require("fs-extra"));
15
+ const path_1 = __importDefault(require("path"));
16
+ const core_1 = require("@nedb/core");
17
+ // FIXME: 实例创建时才去校验 process.env.BLOCKLET_DATA_DIR
18
+ // if (!process.env.BLOCKLET_DATA_DIR) {
19
+ // throw new Error('Blocklet SDK must be used in blocklet runtime');
20
+ // }
21
+ // const DB_DIR = path.join(process.env.BLOCKLET_DATA_DIR, 'db');
22
+ // fs.ensureDirSync(DB_DIR);
23
+ class DataBase extends core_1.DataStore {
24
+ constructor(name, options = {}) {
25
+ if (!process.env.BLOCKLET_DATA_DIR) {
26
+ throw new Error('Blocklet SDK must be used in blocklet runtime');
27
+ }
28
+ const DB_DIR = path_1.default.join(process.env.BLOCKLET_DATA_DIR, 'db');
29
+ fs_extra_1.default.ensureDirSync(DB_DIR);
30
+ const filename = options.filename || path_1.default.join(DB_DIR, `${name}.db`);
31
+ super(Object.assign({ filename, autoload: true, timestampData: true, onload: (err) => {
32
+ if (err) {
33
+ console.error(`failed to load disk database ${filename}`, err);
34
+ }
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;
41
+ });
42
+ }
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
+ });
52
+ }
53
+ }
54
+ module.exports = DataBase;