@onekeyfe/hd-transport-http 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @onekeyfe/hd-transport-http
2
+
3
+ 使用 http 协议与固件通信
@@ -0,0 +1,2 @@
1
+ export declare const DEFAULT_URL = "http://localhost:21320";
2
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,2BAA2B,CAAC"}
package/dist/http.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare type HttpRequestOptions = {
2
+ body?: Array<any> | Record<string, unknown> | string;
3
+ url: string;
4
+ method: 'POST' | 'GET';
5
+ };
6
+ export declare function request(options: HttpRequestOptions): Promise<any>;
7
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAEA,oBAAY,kBAAkB,GAAG;IAC/B,IAAI,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;IACrD,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC;CACxB,CAAC;AAwBF,wBAAsB,OAAO,CAAC,OAAO,EAAE,kBAAkB,gBAsBxD"}
@@ -0,0 +1,30 @@
1
+ import * as _onekeyfe_hd_transport from '@onekeyfe/hd-transport';
2
+ import _onekeyfe_hd_transport__default, { OneKeyDeviceInfoWithSession, AcquireInput } from '@onekeyfe/hd-transport';
3
+
4
+ declare type IncompleteRequestOptions = {
5
+ body?: Array<any> | Record<string, unknown> | string;
6
+ url: string;
7
+ };
8
+ declare class HttpTransport {
9
+ _messages: ReturnType<typeof _onekeyfe_hd_transport__default.parseConfigure> | undefined;
10
+ configured: boolean;
11
+ stopped: boolean;
12
+ url: string;
13
+ constructor(url?: string);
14
+ _post(options: IncompleteRequestOptions): Promise<any>;
15
+ init(): Promise<string>;
16
+ _silentInit(): Promise<string>;
17
+ configure(signedData: any): void;
18
+ listen(old?: Array<OneKeyDeviceInfoWithSession>): Promise<OneKeyDeviceInfoWithSession[]>;
19
+ enumerate(): Promise<OneKeyDeviceInfoWithSession[]>;
20
+ _acquireMixed(input: AcquireInput): Promise<any>;
21
+ acquire(input: AcquireInput): Promise<string>;
22
+ release(session: string, onclose: boolean): Promise<void>;
23
+ call(session: string, name: string, data: Record<string, unknown>): Promise<_onekeyfe_hd_transport.MessageFromOneKey>;
24
+ post(session: string, name: string, data: Record<string, unknown>): Promise<void>;
25
+ read(session: string): Promise<_onekeyfe_hd_transport.MessageFromOneKey>;
26
+ requestDevice(): Promise<never>;
27
+ stop(): void;
28
+ }
29
+
30
+ export { HttpTransport as default };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,wBAAwB,CAAC;AAC/C,OAAO,KAAK,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAMxF,aAAK,wBAAwB,GAAG;IAC9B,IAAI,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;IACrD,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC,SAAS,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAEnE,UAAU,UAAS;IAEnB,OAAO,UAAS;IAEhB,GAAG,EAAE,MAAM,CAAC;gBAEA,GAAG,CAAC,EAAE,MAAM;IAIxB,KAAK,CAAC,OAAO,EAAE,wBAAwB;IAYjC,IAAI;IAKJ,WAAW;IASjB,SAAS,CAAC,UAAU,EAAE,GAAG;IAMnB,MAAM,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,2BAA2B,CAAC;IAY/C,SAAS;IAMf,aAAa,CAAC,KAAK,EAAE,YAAY;IAO3B,OAAO,CAAC,KAAK,EAAE,YAAY;IAK3B,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO;IAUzC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IA4BjE,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAYjE,IAAI,CAAC,OAAO,EAAE,MAAM;IAe1B,aAAa;IAKb,IAAI;CAGL"}
package/dist/index.js ADDED
@@ -0,0 +1,216 @@
1
+ 'use strict';
2
+
3
+ var transport = require('@onekeyfe/hd-transport');
4
+ var axios = require('axios');
5
+
6
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
+
8
+ var transport__default = /*#__PURE__*/_interopDefaultLegacy(transport);
9
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
10
+
11
+ /******************************************************************************
12
+ Copyright (c) Microsoft Corporation.
13
+
14
+ Permission to use, copy, modify, and/or distribute this software for any
15
+ purpose with or without fee is hereby granted.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
+ PERFORMANCE OF THIS SOFTWARE.
24
+ ***************************************************************************** */
25
+
26
+ function __awaiter(thisArg, _arguments, P, generator) {
27
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
+ return new (P || (P = Promise))(function (resolve, reject) {
29
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
33
+ });
34
+ }
35
+
36
+ function contentType(body) {
37
+ if (typeof body === 'string') {
38
+ return 'text/plain';
39
+ }
40
+ return 'application/json';
41
+ }
42
+ function wrapBody(body) {
43
+ if (typeof body === 'string') {
44
+ return body;
45
+ }
46
+ return JSON.stringify(body);
47
+ }
48
+ function parseResult(text) {
49
+ try {
50
+ return JSON.parse(text);
51
+ }
52
+ catch (e) {
53
+ return text;
54
+ }
55
+ }
56
+ function request(options) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ const fetchOptions = {
59
+ url: options.url,
60
+ method: options.method,
61
+ data: wrapBody(options.body),
62
+ withCredentials: false,
63
+ headers: {
64
+ 'Content-Type': contentType(options.body == null ? '' : options.body),
65
+ },
66
+ };
67
+ const res = yield axios__default["default"].request(fetchOptions);
68
+ if (+res.status === 200) {
69
+ return parseResult(res.data);
70
+ }
71
+ const resJson = parseResult(res.data);
72
+ if (typeof resJson === 'object' && resJson != null && resJson.error != null) {
73
+ throw new Error(resJson.error);
74
+ }
75
+ else {
76
+ throw new Error(res.data);
77
+ }
78
+ });
79
+ }
80
+
81
+ const DEFAULT_URL = 'http://localhost:21320';
82
+
83
+ const { check, buildOne, receiveOne, parseConfigure } = transport__default["default"];
84
+ class HttpTransport {
85
+ constructor(url) {
86
+ this.configured = false;
87
+ this.stopped = false;
88
+ this.url = url == null ? DEFAULT_URL : url;
89
+ }
90
+ _post(options) {
91
+ if (this.stopped) {
92
+ return Promise.reject('Transport stopped.');
93
+ }
94
+ return request(Object.assign(Object.assign({}, options), { method: 'POST', url: this.url + options.url }));
95
+ }
96
+ init() {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ const bridgeVersion = yield this._silentInit();
99
+ return bridgeVersion;
100
+ });
101
+ }
102
+ _silentInit() {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ const infoS = yield request({
105
+ url: this.url,
106
+ method: 'POST',
107
+ });
108
+ const info = check.info(infoS);
109
+ return info.version;
110
+ });
111
+ }
112
+ configure(signedData) {
113
+ const messages = parseConfigure(signedData);
114
+ this.configured = true;
115
+ this._messages = messages;
116
+ }
117
+ listen(old) {
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ if (old === null) {
120
+ throw new Error('Http-Transport does not support listen without previous.');
121
+ }
122
+ const devicesS = yield this._post({
123
+ url: '/listen',
124
+ body: old,
125
+ });
126
+ const devices = check.devices(devicesS);
127
+ return devices;
128
+ });
129
+ }
130
+ enumerate() {
131
+ return __awaiter(this, void 0, void 0, function* () {
132
+ const devicesS = yield this._post({ url: '/enumerate' });
133
+ const devices = check.devices(devicesS);
134
+ return devices;
135
+ });
136
+ }
137
+ _acquireMixed(input) {
138
+ const previousStr = input.previous == null ? 'null' : input.previous;
139
+ const url = `/acquire/${input.path}/${previousStr}`;
140
+ return this._post({ url });
141
+ }
142
+ acquire(input) {
143
+ return __awaiter(this, void 0, void 0, function* () {
144
+ const acquireS = yield this._acquireMixed(input);
145
+ return check.acquire(acquireS);
146
+ });
147
+ }
148
+ release(session, onclose) {
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ const res = this._post({
151
+ url: `/release/${session}`,
152
+ });
153
+ if (onclose) {
154
+ return;
155
+ }
156
+ yield res;
157
+ });
158
+ }
159
+ call(session, name, data) {
160
+ return __awaiter(this, void 0, void 0, function* () {
161
+ if (this._messages == null) {
162
+ throw new Error('Transport not configured.');
163
+ }
164
+ const messages = this._messages;
165
+ console.log('transport-http', 'call-', 'messages: ', messages, ' name: ', name, ' data: ', data);
166
+ const o = buildOne(messages, name, data);
167
+ const outData = o.toString('hex');
168
+ const resData = yield this._post({
169
+ url: `/call/${session}`,
170
+ body: outData,
171
+ });
172
+ if (typeof resData !== 'string') {
173
+ throw new Error('Returning data is not string.');
174
+ }
175
+ const jsonData = receiveOne(messages, resData);
176
+ return check.call(jsonData);
177
+ });
178
+ }
179
+ post(session, name, data) {
180
+ return __awaiter(this, void 0, void 0, function* () {
181
+ if (this._messages == null) {
182
+ throw new Error('Transport not configured.');
183
+ }
184
+ const messages = this._messages;
185
+ const outData = buildOne(messages, name, data).toString('hex');
186
+ yield this._post({
187
+ url: `/post/${session}`,
188
+ body: outData,
189
+ });
190
+ });
191
+ }
192
+ read(session) {
193
+ return __awaiter(this, void 0, void 0, function* () {
194
+ if (this._messages == null) {
195
+ throw new Error('Transport not configured.');
196
+ }
197
+ const messages = this._messages;
198
+ const resData = yield this._post({
199
+ url: `/read/${session}`,
200
+ });
201
+ if (typeof resData !== 'string') {
202
+ throw new Error('Returning data is not string.');
203
+ }
204
+ const jsonData = receiveOne(messages, resData);
205
+ return check.call(jsonData);
206
+ });
207
+ }
208
+ requestDevice() {
209
+ return Promise.reject();
210
+ }
211
+ stop() {
212
+ this.stopped = true;
213
+ }
214
+ }
215
+
216
+ module.exports = HttpTransport;
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@onekeyfe/hd-transport-http",
3
+ "version": "0.0.1",
4
+ "description": "hardware http transport",
5
+ "author": "OneKey",
6
+ "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
7
+ "license": "ISC",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/OneKeyHQ/hardware-js-sdk.git"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "scripts": {
18
+ "test": "echo \"Error: run tests from root\" && exit 1",
19
+ "build": "rimraf dist && rollup -c ../../build/rollup.config.js",
20
+ "lint": "eslint .",
21
+ "lint:fix": "eslint . --fix"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/OneKeyHQ/hardware-js-sdk/issues"
25
+ },
26
+ "dependencies": {
27
+ "@onekeyfe/hd-transport": "^0.0.1",
28
+ "axios": "^0.27.2"
29
+ },
30
+ "gitHead": "20ce0ad2bd0388f9286be7b08cb76d94946a48c1"
31
+ }
@@ -0,0 +1 @@
1
+ export const DEFAULT_URL = 'http://localhost:21320';
package/src/http.ts ADDED
@@ -0,0 +1,53 @@
1
+ import axios, { AxiosRequestConfig } from 'axios';
2
+
3
+ export type HttpRequestOptions = {
4
+ body?: Array<any> | Record<string, unknown> | string;
5
+ url: string;
6
+ method: 'POST' | 'GET';
7
+ };
8
+
9
+ function contentType(body: any) {
10
+ if (typeof body === 'string') {
11
+ return 'text/plain';
12
+ }
13
+ return 'application/json';
14
+ }
15
+
16
+ function wrapBody(body: any) {
17
+ if (typeof body === 'string') {
18
+ return body;
19
+ }
20
+ return JSON.stringify(body);
21
+ }
22
+
23
+ function parseResult(text: string) {
24
+ try {
25
+ return JSON.parse(text);
26
+ } catch (e) {
27
+ return text;
28
+ }
29
+ }
30
+
31
+ export async function request(options: HttpRequestOptions) {
32
+ const fetchOptions: AxiosRequestConfig = {
33
+ url: options.url,
34
+ method: options.method,
35
+ data: wrapBody(options.body),
36
+ withCredentials: false,
37
+ headers: {
38
+ 'Content-Type': contentType(options.body == null ? '' : options.body),
39
+ },
40
+ };
41
+
42
+ const res = await axios.request(fetchOptions);
43
+
44
+ if (+res.status === 200) {
45
+ return parseResult(res.data);
46
+ }
47
+ const resJson = parseResult(res.data);
48
+ if (typeof resJson === 'object' && resJson != null && resJson.error != null) {
49
+ throw new Error(resJson.error);
50
+ } else {
51
+ throw new Error(res.data);
52
+ }
53
+ }
package/src/index.ts ADDED
@@ -0,0 +1,161 @@
1
+ import transport from '@onekeyfe/hd-transport';
2
+ import type { AcquireInput, OneKeyDeviceInfoWithSession } from '@onekeyfe/hd-transport';
3
+ import { request as http } from './http';
4
+ import { DEFAULT_URL } from './constants';
5
+
6
+ const { check, buildOne, receiveOne, parseConfigure } = transport;
7
+
8
+ type IncompleteRequestOptions = {
9
+ body?: Array<any> | Record<string, unknown> | string;
10
+ url: string;
11
+ };
12
+
13
+ export default class HttpTransport {
14
+ _messages: ReturnType<typeof transport.parseConfigure> | undefined;
15
+
16
+ configured = false;
17
+
18
+ stopped = false;
19
+
20
+ url: string;
21
+
22
+ constructor(url?: string) {
23
+ this.url = url == null ? DEFAULT_URL : url;
24
+ }
25
+
26
+ _post(options: IncompleteRequestOptions) {
27
+ if (this.stopped) {
28
+ // eslint-disable-next-line prefer-promise-reject-errors
29
+ return Promise.reject('Transport stopped.');
30
+ }
31
+ return http({
32
+ ...options,
33
+ method: 'POST',
34
+ url: this.url + options.url,
35
+ });
36
+ }
37
+
38
+ async init() {
39
+ const bridgeVersion = await this._silentInit();
40
+ return bridgeVersion;
41
+ }
42
+
43
+ async _silentInit() {
44
+ const infoS = await http({
45
+ url: this.url,
46
+ method: 'POST',
47
+ });
48
+ const info = check.info(infoS);
49
+ return info.version;
50
+ }
51
+
52
+ configure(signedData: any) {
53
+ const messages = parseConfigure(signedData);
54
+ this.configured = true;
55
+ this._messages = messages;
56
+ }
57
+
58
+ async listen(old?: Array<OneKeyDeviceInfoWithSession>) {
59
+ if (old === null) {
60
+ throw new Error('Http-Transport does not support listen without previous.');
61
+ }
62
+ const devicesS = await this._post({
63
+ url: '/listen',
64
+ body: old,
65
+ });
66
+ const devices = check.devices(devicesS);
67
+ return devices;
68
+ }
69
+
70
+ async enumerate() {
71
+ const devicesS = await this._post({ url: '/enumerate' });
72
+ const devices = check.devices(devicesS);
73
+ return devices;
74
+ }
75
+
76
+ _acquireMixed(input: AcquireInput) {
77
+ const previousStr = input.previous == null ? 'null' : input.previous;
78
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
79
+ const url = `/acquire/${input.path}/${previousStr}`;
80
+ return this._post({ url });
81
+ }
82
+
83
+ async acquire(input: AcquireInput) {
84
+ const acquireS = await this._acquireMixed(input);
85
+ return check.acquire(acquireS);
86
+ }
87
+
88
+ async release(session: string, onclose: boolean) {
89
+ const res = this._post({
90
+ url: `/release/${session}`,
91
+ });
92
+ if (onclose) {
93
+ return;
94
+ }
95
+ await res;
96
+ }
97
+
98
+ async call(session: string, name: string, data: Record<string, unknown>) {
99
+ if (this._messages == null) {
100
+ throw new Error('Transport not configured.');
101
+ }
102
+ const messages = this._messages;
103
+ console.log(
104
+ 'transport-http',
105
+ 'call-',
106
+ 'messages: ',
107
+ messages,
108
+ ' name: ',
109
+ name,
110
+ ' data: ',
111
+ data
112
+ );
113
+ const o = buildOne(messages, name, data);
114
+ const outData = o.toString('hex');
115
+ const resData = await this._post({
116
+ url: `/call/${session}`,
117
+ body: outData,
118
+ });
119
+ if (typeof resData !== 'string') {
120
+ throw new Error('Returning data is not string.');
121
+ }
122
+ const jsonData = receiveOne(messages, resData);
123
+ return check.call(jsonData);
124
+ }
125
+
126
+ async post(session: string, name: string, data: Record<string, unknown>) {
127
+ if (this._messages == null) {
128
+ throw new Error('Transport not configured.');
129
+ }
130
+ const messages = this._messages;
131
+ const outData = buildOne(messages, name, data).toString('hex');
132
+ await this._post({
133
+ url: `/post/${session}`,
134
+ body: outData,
135
+ });
136
+ }
137
+
138
+ async read(session: string) {
139
+ if (this._messages == null) {
140
+ throw new Error('Transport not configured.');
141
+ }
142
+ const messages = this._messages;
143
+ const resData = await this._post({
144
+ url: `/read/${session}`,
145
+ });
146
+ if (typeof resData !== 'string') {
147
+ throw new Error('Returning data is not string.');
148
+ }
149
+ const jsonData = receiveOne(messages, resData);
150
+ return check.call(jsonData);
151
+ }
152
+
153
+ requestDevice() {
154
+ // eslint-disable-next-line prefer-promise-reject-errors
155
+ return Promise.reject();
156
+ }
157
+
158
+ stop() {
159
+ this.stopped = true;
160
+ }
161
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "../../tsconfig.lib.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ },
6
+ "include": ["./src"]
7
+ }