@keplr-wallet/router 0.12.0-alpha.0 → 0.12.0-alpha.3

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/LICENSE CHANGED
@@ -1,4 +1,6 @@
1
- License: Apache2.0
1
+ License: Apache2.0 (Extension) / All rights reserved (Mobile)
2
+
3
+ ## Keplr Extension License:
2
4
 
3
5
  Apache License
4
6
  Version 2.0, January 2004
@@ -200,4 +202,8 @@ License: Apache2.0
200
202
  distributed under the License is distributed on an "AS IS" BASIS,
201
203
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
204
  See the License for the specific language governing permissions and
203
- limitations under the License.
205
+ limitations under the License.
206
+
207
+ ## Keplr Mobile License
208
+
209
+ Copyright (c) 2021 Chainapsis Inc. All rights reserved.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/encoding/index.ts"],"names":[],"mappings":";;;AAEA,MAAa,eAAe;IAA5B;QACU,sBAAiB,GAGrB,IAAI,GAAG,EAAE,CAAC;IA0BhB,CAAC;IAxBC,eAAe,CACb,MAAqE;QAErE,IAAI,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE;YAC7C,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;SAC7D;QAED,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC;IAED,YAAY,CAAC,OAAoC;QAC/C,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;YACjB,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;SAC9B;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,IAAI,KAAK,CAAC,yBAAyB,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;SAC1D;QACD,OAAO,MAAM,CAAC,cAAc,CAC1B,OAAO,CAAC,GAAG,EACX,MAAM,CAAC,SAAS,CACG,CAAC;IACxB,CAAC;CACF;AA9BD,0CA8BC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/encoding/index.ts"],"names":[],"mappings":";;;AAEA,MAAa,eAAe;IAA5B;QACU,sBAAiB,GACvB,IAAI,GAAG,EAAE,CAAC;IA0Bd,CAAC;IAxBC,eAAe,CACb,MAAqE;QAErE,IAAI,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE;YAC7C,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;SAC7D;QAED,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC;IAED,YAAY,CAAC,OAAoC;QAC/C,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;YACjB,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;SAC9B;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,IAAI,KAAK,CAAC,yBAAyB,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;SAC1D;QACD,OAAO,MAAM,CAAC,cAAc,CAC1B,OAAO,CAAC,GAAG,EACX,MAAM,CAAC,SAAS,CACG,CAAC;IACxB,CAAC;CACF;AA5BD,0CA4BC"}
@@ -1,4 +1,4 @@
1
1
  import { Message } from "./message";
2
2
  import { Env } from "./types";
3
- export declare type Handler = (env: Env, msg: Message<unknown>) => any;
4
- export declare type InternalHandler<M extends Message<unknown>> = (env: Env, msg: M) => (M extends Message<infer R> ? R : never) | Promise<M extends Message<infer R> ? R : never>;
3
+ export type Handler = (env: Env, msg: Message<unknown>) => any;
4
+ export type InternalHandler<M extends Message<unknown>> = (env: Env, msg: M) => (M extends Message<infer R> ? R : never) | Promise<M extends Message<infer R> ? R : never>;
package/build/index.d.ts CHANGED
@@ -6,4 +6,4 @@ export * from "./error";
6
6
  export * from "./message";
7
7
  export * from "./constant";
8
8
  export * from "./encoding";
9
- export * from "./json-uint8-array";
9
+ export * from "./simple";
package/build/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[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);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -18,5 +22,5 @@ __exportStar(require("./error"), exports);
18
22
  __exportStar(require("./message"), exports);
19
23
  __exportStar(require("./constant"), exports);
20
24
  __exportStar(require("./encoding"), exports);
21
- __exportStar(require("./json-uint8-array"), exports);
25
+ __exportStar(require("./simple"), exports);
22
26
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAAyB;AACzB,4CAA0B;AAC1B,+CAA6B;AAC7B,0CAAwB;AACxB,0CAAwB;AACxB,4CAA0B;AAC1B,6CAA2B;AAC3B,6CAA2B;AAC3B,qDAAmC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,4CAA0B;AAC1B,+CAA6B;AAC7B,0CAAwB;AACxB,0CAAwB;AACxB,4CAA0B;AAC1B,6CAA2B;AAC3B,6CAA2B;AAC3B,2CAAyB"}
@@ -8,7 +8,10 @@ export declare abstract class Router {
8
8
  protected registeredHandler: Map<string, Handler>;
9
9
  protected guards: Guard[];
10
10
  protected port: string;
11
+ protected _isInitialized: boolean;
12
+ protected _initWaiter: Promise<void> | undefined;
11
13
  constructor(envProducer: EnvProducer);
14
+ get isInitialized(): boolean;
12
15
  registerMessage(msgCls: {
13
16
  new (...args: any): Message<unknown>;
14
17
  } & {
@@ -16,7 +19,9 @@ export declare abstract class Router {
16
19
  }): void;
17
20
  addHandler(route: string, handler: Handler): void;
18
21
  addGuard(guard: Guard): void;
19
- abstract listen(port: string): void;
20
- abstract unlisten(): void;
22
+ protected abstract attachHandler(): void;
23
+ protected abstract detachHandler(): void;
24
+ listen(port: string, initFn?: () => Promise<void>): Promise<void>;
25
+ unlisten(): void;
21
26
  protected handleMessage(message: any, sender: MessageSender): Promise<unknown>;
22
27
  }
@@ -11,7 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.Router = void 0;
13
13
  const encoding_1 = require("../encoding");
14
- const json_uint8_array_1 = require("../json-uint8-array");
14
+ const common_1 = require("@keplr-wallet/common");
15
15
  class Router {
16
16
  constructor(envProducer) {
17
17
  this.envProducer = envProducer;
@@ -19,6 +19,10 @@ class Router {
19
19
  this.registeredHandler = new Map();
20
20
  this.guards = [];
21
21
  this.port = "";
22
+ this._isInitialized = false;
23
+ }
24
+ get isInitialized() {
25
+ return this._isInitialized;
22
26
  }
23
27
  registerMessage(msgCls) {
24
28
  this.msgRegistry.registerMessage(msgCls);
@@ -32,10 +36,33 @@ class Router {
32
36
  addGuard(guard) {
33
37
  this.guards.push(guard);
34
38
  }
39
+ listen(port, initFn) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ this.port = port;
42
+ this.attachHandler();
43
+ if (initFn) {
44
+ let initWaiter;
45
+ this._initWaiter = new Promise((resolve) => {
46
+ initWaiter = resolve;
47
+ });
48
+ yield initFn();
49
+ initWaiter();
50
+ }
51
+ this._isInitialized = true;
52
+ return;
53
+ });
54
+ }
55
+ unlisten() {
56
+ this.port = "";
57
+ this.detachHandler();
58
+ }
35
59
  handleMessage(message, sender) {
36
60
  var _a;
37
61
  return __awaiter(this, void 0, void 0, function* () {
38
- const msg = this.msgRegistry.parseMessage(json_uint8_array_1.JSONUint8Array.unwrap(message));
62
+ if (!this.isInitialized) {
63
+ yield this._initWaiter;
64
+ }
65
+ const msg = this.msgRegistry.parseMessage(common_1.JSONUint8Array.unwrap(message));
39
66
  const env = this.envProducer(sender, (_a = msg.routerMeta) !== null && _a !== void 0 ? _a : {});
40
67
  for (const guard of this.guards) {
41
68
  yield guard(env, msg, sender);
@@ -50,7 +77,7 @@ class Router {
50
77
  if (!handler) {
51
78
  throw new Error("Can't get handler");
52
79
  }
53
- return json_uint8_array_1.JSONUint8Array.wrap(yield handler(env, msg));
80
+ return common_1.JSONUint8Array.wrap(yield handler(env, msg));
54
81
  });
55
82
  }
56
83
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/router/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,0CAA8C;AAC9C,0DAAqD;AAErD,MAAsB,MAAM;IAQ1B,YAA+B,WAAwB;QAAxB,gBAAW,GAAX,WAAW,CAAa;QAP7C,gBAAW,GAAoB,IAAI,0BAAe,EAAE,CAAC;QACrD,sBAAiB,GAAyB,IAAI,GAAG,EAAE,CAAC;QAEpD,WAAM,GAAY,EAAE,CAAC;QAErB,SAAI,GAAG,EAAE,CAAC;IAEsC,CAAC;IAEpD,eAAe,CACpB,MAAqE;QAErE,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAC3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symbolRoute: unique symbol;
4
+ declare const symbolType: unique symbol;
5
+ export declare class SimpleMessage<R = any> extends Message<R> {
6
+ protected [symbolRoute]: string;
7
+ protected [symbolType]: string;
8
+ [key: string]: any;
9
+ constructor(route: string, type: string, data: Record<string, any>);
10
+ route(): string;
11
+ type(): string;
12
+ validateBasic(): void;
13
+ approveExternal(): boolean;
14
+ }
15
+ /**
16
+ * Send message without typing and message instance.
17
+ * Usage of this function is not recommended.
18
+ * However, if you know about this function well,
19
+ * and you want to avoid the usage of troublesome typing and class definition,
20
+ * You can try using this function.
21
+ * @param requester
22
+ * @param port
23
+ * @param route
24
+ * @param type
25
+ * @param data
26
+ */
27
+ export declare function sendSimpleMessage<R = any>(requester: MessageRequester, port: string, route: string, type: string, data: Record<string, any>): Promise<R>;
28
+ export {};
@@ -0,0 +1,59 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.sendSimpleMessage = exports.SimpleMessage = void 0;
13
+ const message_1 = require("./message");
14
+ const symbolRoute = Symbol();
15
+ const symbolType = Symbol();
16
+ class SimpleMessage extends message_1.Message {
17
+ constructor(route, type, data) {
18
+ super();
19
+ this[symbolRoute] = route;
20
+ this[symbolType] = type;
21
+ for (const key of Object.keys(data)) {
22
+ this[key] = data[key];
23
+ }
24
+ }
25
+ route() {
26
+ return this[symbolRoute];
27
+ }
28
+ type() {
29
+ return this[symbolType];
30
+ }
31
+ // validateBasic should be handled in background.
32
+ validateBasic() {
33
+ // noop
34
+ }
35
+ // approveExternal should be handled in background.
36
+ approveExternal() {
37
+ return true;
38
+ }
39
+ }
40
+ exports.SimpleMessage = SimpleMessage;
41
+ /**
42
+ * Send message without typing and message instance.
43
+ * Usage of this function is not recommended.
44
+ * However, if you know about this function well,
45
+ * and you want to avoid the usage of troublesome typing and class definition,
46
+ * You can try using this function.
47
+ * @param requester
48
+ * @param port
49
+ * @param route
50
+ * @param type
51
+ * @param data
52
+ */
53
+ function sendSimpleMessage(requester, port, route, type, data) {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ return yield requester.sendMessage(port, new SimpleMessage(route, type, data));
56
+ });
57
+ }
58
+ exports.sendSimpleMessage = sendSimpleMessage;
59
+ //# sourceMappingURL=simple.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simple.js","sourceRoot":"","sources":["../src/simple.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uCAAoC;AAGpC,MAAM,WAAW,GAAkB,MAAM,EAAE,CAAC;AAC5C,MAAM,UAAU,GAAkB,MAAM,EAAE,CAAC;AAE3C,MAAa,aAAuB,SAAQ,iBAAU;IAMpD,YAAY,KAAa,EAAE,IAAY,EAAE,IAAyB;QAChE,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC;QAC1B,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;QAExB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;YACnC,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;SACvB;IACH,CAAC;IAED,KAAK;QACH,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC;IAC3B,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC;IAC1B,CAAC;IAED,iDAAiD;IACjD,aAAa;QACX,OAAO;IACT,CAAC;IAED,mDAAmD;IAC1C,eAAe;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlCD,sCAkCC;AAED;;;;;;;;;;;GAWG;AACH,SAAsB,iBAAiB,CACrC,SAA2B,EAC3B,IAAY,EACZ,KAAa,EACb,IAAY,EACZ,IAAyB;;QAEzB,OAAO,MAAM,SAAS,CAAC,WAAW,CAChC,IAAI,EACJ,IAAI,aAAa,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CACrC,CAAC;IACJ,CAAC;CAAA;AAXD,8CAWC"}
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const simple_1 = require("./simple");
4
+ const common_1 = require("@keplr-wallet/common");
5
+ describe("Test simple message", () => {
6
+ it("test simple message", () => {
7
+ const simpleMessage = new simple_1.SimpleMessage("route-test", "type-test", {
8
+ test: 1,
9
+ test2: "test",
10
+ });
11
+ expect(simpleMessage.route()).toBe("route-test");
12
+ expect(simpleMessage.type()).toBe("type-test");
13
+ expect(simpleMessage.approveExternal()).toBe(true);
14
+ expect(() => {
15
+ simpleMessage.validateBasic();
16
+ }).not.toThrow();
17
+ });
18
+ it("encoded simple message should have only datas", () => {
19
+ const simpleMessage = new simple_1.SimpleMessage("route-test", "type-test", {
20
+ test: 1,
21
+ test2: "test",
22
+ });
23
+ const encoded = common_1.JSONUint8Array.stringify(simpleMessage);
24
+ const decoded = common_1.JSONUint8Array.parse(encoded);
25
+ expect(decoded["route"]).toBe(undefined);
26
+ expect(decoded["type"]).toBe(undefined);
27
+ expect(decoded["test"]).toBe(1);
28
+ expect(decoded["test2"]).toBe("test");
29
+ expect(Object.keys(decoded).length).toBe(2);
30
+ });
31
+ });
32
+ //# sourceMappingURL=simple.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simple.spec.js","sourceRoot":"","sources":["../src/simple.spec.ts"],"names":[],"mappings":";;AAAA,qCAAyC;AACzC,iDAAsD;AAEtD,QAAQ,CAAC,qBAAq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AAC,CAAC;QACtC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
package/build/types.d.ts CHANGED
@@ -1,17 +1,18 @@
1
1
  /// <reference types="firefox-webext-browser" />
2
2
  import { Message } from "./message";
3
- export declare type MessageSender = Pick<browser.runtime.MessageSender, "id" | "url" | "tab">;
4
- export declare type FnRequestInteractionOptions = {
3
+ export type MessageSender = Pick<browser.runtime.MessageSender, "id" | "url" | "tab">;
4
+ export type FnRequestInteractionOptions = {
5
+ unstableOnClose?: () => void;
5
6
  forceOpenWindow?: boolean;
6
7
  channel?: string;
7
8
  };
8
- export declare type FnRequestInteraction = <M extends Message<unknown>>(url: string, msg: M, options?: FnRequestInteractionOptions) => Promise<M extends Message<infer R> ? R : never>;
9
+ export type FnRequestInteraction = <M extends Message<unknown>>(url: string, msg: M, options?: FnRequestInteractionOptions) => Promise<M extends Message<infer R> ? R : never>;
9
10
  export interface Env {
10
11
  readonly isInternalMsg: boolean;
11
12
  readonly requestInteraction: FnRequestInteraction;
12
13
  }
13
- export declare type EnvProducer = (sender: MessageSender, routerMeta: Record<string, any>) => Env;
14
+ export type EnvProducer = (sender: MessageSender, routerMeta: Record<string, any>) => Env;
14
15
  export interface MessageRequester {
15
16
  sendMessage<M extends Message<unknown>>(port: string, msg: M): Promise<M extends Message<infer R> ? R : never>;
16
17
  }
17
- export declare type Guard = (env: Omit<Env, "requestInteraction">, msg: Message<unknown>, sender: MessageSender) => Promise<void>;
18
+ export type Guard = (env: Omit<Env, "requestInteraction">, msg: Message<unknown>, sender: MessageSender) => Promise<void>;
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@keplr-wallet/router",
3
- "version": "0.12.0-alpha.0",
3
+ "version": "0.12.0-alpha.3",
4
4
  "main": "build/index.js",
5
5
  "author": "chainapsis",
6
6
  "license": "Apache-2.0",
7
- "private": false,
8
7
  "publishConfig": {
9
8
  "access": "public"
10
9
  },
10
+ "dependencies": {
11
+ "@keplr-wallet/common": "0.12.0-alpha.3"
12
+ },
11
13
  "scripts": {
12
14
  "clean": "rm -rf node_modules; rm -rf build",
13
15
  "build": "tsc",
@@ -16,5 +18,5 @@
16
18
  "lint-test": "eslint \"src/**/*\" && prettier --check \"src/**/*\"",
17
19
  "lint-fix": "eslint --fix \"src/**/*\" && prettier --write \"src/**/*\""
18
20
  },
19
- "gitHead": "34327309b724b59f8e41d044db6e57a332614fae"
21
+ "gitHead": "1ee89644b711dd1dbbebc8eb86ed29d407088834"
20
22
  }
@@ -1,10 +1,8 @@
1
1
  import { Message } from "../message";
2
2
 
3
3
  export class MessageRegistry {
4
- private registeredMsgType: Map<
5
- string,
6
- { new (): Message<unknown> }
7
- > = new Map();
4
+ private registeredMsgType: Map<string, { new (): Message<unknown> }> =
5
+ new Map();
8
6
 
9
7
  registerMessage(
10
8
  msgCls: { new (...args: any): Message<unknown> } & { type(): string }
package/src/index.ts CHANGED
@@ -6,4 +6,4 @@ export * from "./error";
6
6
  export * from "./message";
7
7
  export * from "./constant";
8
8
  export * from "./encoding";
9
- export * from "./json-uint8-array";
9
+ export * from "./simple";
@@ -2,7 +2,7 @@ import { Message } from "../message";
2
2
  import { Handler } from "../handler";
3
3
  import { EnvProducer, Guard, MessageSender } from "../types";
4
4
  import { MessageRegistry } from "../encoding";
5
- import { JSONUint8Array } from "../json-uint8-array";
5
+ import { JSONUint8Array } from "@keplr-wallet/common";
6
6
 
7
7
  export abstract class Router {
8
8
  protected msgRegistry: MessageRegistry = new MessageRegistry();
@@ -12,8 +12,15 @@ export abstract class Router {
12
12
 
13
13
  protected port = "";
14
14
 
15
+ protected _isInitialized: boolean = false;
16
+ protected _initWaiter: Promise<void> | undefined;
17
+
15
18
  constructor(protected readonly envProducer: EnvProducer) {}
16
19
 
20
+ get isInitialized(): boolean {
21
+ return this._isInitialized;
22
+ }
23
+
17
24
  public registerMessage(
18
25
  msgCls: { new (...args: any): Message<unknown> } & { type(): string }
19
26
  ): void {
@@ -32,14 +39,42 @@ export abstract class Router {
32
39
  this.guards.push(guard);
33
40
  }
34
41
 
35
- public abstract listen(port: string): void;
42
+ protected abstract attachHandler(): void;
36
43
 
37
- public abstract unlisten(): void;
44
+ protected abstract detachHandler(): void;
45
+
46
+ public async listen(
47
+ port: string,
48
+ initFn?: () => Promise<void>
49
+ ): Promise<void> {
50
+ this.port = port;
51
+ this.attachHandler();
52
+
53
+ if (initFn) {
54
+ let initWaiter: (() => void) | undefined;
55
+ this._initWaiter = new Promise<void>((resolve) => {
56
+ initWaiter = resolve;
57
+ });
58
+ await initFn();
59
+ initWaiter!();
60
+ }
61
+ this._isInitialized = true;
62
+ return;
63
+ }
64
+
65
+ public unlisten(): void {
66
+ this.port = "";
67
+ this.detachHandler();
68
+ }
38
69
 
39
70
  protected async handleMessage(
40
71
  message: any,
41
72
  sender: MessageSender
42
73
  ): Promise<unknown> {
74
+ if (!this.isInitialized) {
75
+ await this._initWaiter;
76
+ }
77
+
43
78
  const msg = this.msgRegistry.parseMessage(JSONUint8Array.unwrap(message));
44
79
  const env = this.envProducer(sender, msg.routerMeta ?? {});
45
80
 
@@ -0,0 +1,34 @@
1
+ import { SimpleMessage } from "./simple";
2
+ import { JSONUint8Array } from "@keplr-wallet/common";
3
+
4
+ describe("Test simple message", () => {
5
+ it("test simple message", () => {
6
+ const simpleMessage = new SimpleMessage("route-test", "type-test", {
7
+ test: 1,
8
+ test2: "test",
9
+ });
10
+
11
+ expect(simpleMessage.route()).toBe("route-test");
12
+ expect(simpleMessage.type()).toBe("type-test");
13
+ expect(simpleMessage.approveExternal()).toBe(true);
14
+ expect(() => {
15
+ simpleMessage.validateBasic();
16
+ }).not.toThrow();
17
+ });
18
+
19
+ it("encoded simple message should have only datas", () => {
20
+ const simpleMessage = new SimpleMessage("route-test", "type-test", {
21
+ test: 1,
22
+ test2: "test",
23
+ });
24
+
25
+ const encoded = JSONUint8Array.stringify(simpleMessage);
26
+ const decoded = JSONUint8Array.parse(encoded);
27
+
28
+ expect(decoded["route"]).toBe(undefined);
29
+ expect(decoded["type"]).toBe(undefined);
30
+ expect(decoded["test"]).toBe(1);
31
+ expect(decoded["test2"]).toBe("test");
32
+ expect(Object.keys(decoded).length).toBe(2);
33
+ });
34
+ });
package/src/simple.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { Message } from "./message";
2
+ import { MessageRequester } from "./types";
3
+
4
+ const symbolRoute: unique symbol = Symbol();
5
+ const symbolType: unique symbol = Symbol();
6
+
7
+ export class SimpleMessage<R = any> extends Message<R> {
8
+ protected [symbolRoute]: string;
9
+ protected [symbolType]: string;
10
+
11
+ [key: string]: any;
12
+
13
+ constructor(route: string, type: string, data: Record<string, any>) {
14
+ super();
15
+
16
+ this[symbolRoute] = route;
17
+ this[symbolType] = type;
18
+
19
+ for (const key of Object.keys(data)) {
20
+ this[key] = data[key];
21
+ }
22
+ }
23
+
24
+ route(): string {
25
+ return this[symbolRoute];
26
+ }
27
+
28
+ type(): string {
29
+ return this[symbolType];
30
+ }
31
+
32
+ // validateBasic should be handled in background.
33
+ validateBasic(): void {
34
+ // noop
35
+ }
36
+
37
+ // approveExternal should be handled in background.
38
+ override approveExternal(): boolean {
39
+ return true;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Send message without typing and message instance.
45
+ * Usage of this function is not recommended.
46
+ * However, if you know about this function well,
47
+ * and you want to avoid the usage of troublesome typing and class definition,
48
+ * You can try using this function.
49
+ * @param requester
50
+ * @param port
51
+ * @param route
52
+ * @param type
53
+ * @param data
54
+ */
55
+ export async function sendSimpleMessage<R = any>(
56
+ requester: MessageRequester,
57
+ port: string,
58
+ route: string,
59
+ type: string,
60
+ data: Record<string, any>
61
+ ): Promise<R> {
62
+ return await requester.sendMessage(
63
+ port,
64
+ new SimpleMessage(route, type, data)
65
+ );
66
+ }
package/src/types.ts CHANGED
@@ -6,6 +6,12 @@ export type MessageSender = Pick<
6
6
  >;
7
7
 
8
8
  export type FnRequestInteractionOptions = {
9
+ // If possible, the callback below is called when the popup is closed.
10
+ // In the case of the logic inside the extension, it is difficult to measure when the callback below should be invoked.
11
+ // Therefore, logic should not completely depend on the callback below.
12
+ // In the case of a detached popup, it is not guaranteed that any logic will be executed when it is closed.
13
+ // To solve this problem, the callback below is used.
14
+ unstableOnClose?: () => void;
9
15
  forceOpenWindow?: boolean;
10
16
  channel?: string;
11
17
  };
@@ -1,2 +0,0 @@
1
- export declare function toHex(data: Uint8Array): string;
2
- export declare function fromHex(hexstring: string): Uint8Array;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- /*
3
- Belows are from @cosmjs/encoding library.
4
- To reduce the bundle size of provider, put them directly here.
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.fromHex = exports.toHex = void 0;
8
- function toHex(data) {
9
- let out = "";
10
- for (const byte of data) {
11
- out += ("0" + byte.toString(16)).slice(-2);
12
- }
13
- return out;
14
- }
15
- exports.toHex = toHex;
16
- function fromHex(hexstring) {
17
- if (hexstring.length % 2 !== 0) {
18
- throw new Error("hex string length must be a multiple of 2");
19
- }
20
- const listOfInts = [];
21
- for (let i = 0; i < hexstring.length; i += 2) {
22
- const hexByteAsString = hexstring.substr(i, 2);
23
- if (!hexByteAsString.match(/[0-9a-f]{2}/i)) {
24
- throw new Error("hex string contains invalid characters");
25
- }
26
- listOfInts.push(parseInt(hexByteAsString, 16));
27
- }
28
- return new Uint8Array(listOfInts);
29
- }
30
- exports.fromHex = fromHex;
31
- //# sourceMappingURL=hex.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hex.js","sourceRoot":"","sources":["../../src/json-uint8-array/hex.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,SAAgB,KAAK,CAAC,IAAgB;IACpC,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE;QACvB,GAAG,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KAC5C;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAND,sBAMC;AAED,SAAgB,OAAO,CAAC,SAAiB;IACvC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE;QAC9B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,MAAM,UAAU,GAAa,EAAE,CAAC;IAChC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QAC5C,MAAM,eAAe,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/C,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE;YAC1C,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;SAC3D;QACD,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,CAAC;KAChD;IACD,OAAO,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;AACpC,CAAC;AAdD,0BAcC"}
@@ -1,6 +0,0 @@
1
- export declare class JSONUint8Array {
2
- static parse(text: string): any;
3
- static stringify(obj: unknown): string;
4
- static wrap(obj: any): any;
5
- static unwrap(obj: any): any;
6
- }
@@ -1,44 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JSONUint8Array = void 0;
4
- // The JSON encoder that supports the `Uint8Array`.
5
- const hex_1 = require("./hex");
6
- class JSONUint8Array {
7
- static parse(text) {
8
- return JSON.parse(text, (_, value) => {
9
- if (value &&
10
- typeof value === "string" &&
11
- value.startsWith("__uint8array__")) {
12
- return hex_1.fromHex(value.replace("__uint8array__", ""));
13
- }
14
- return value;
15
- });
16
- }
17
- static stringify(obj) {
18
- return JSON.stringify(obj, (_, value) => {
19
- if (value &&
20
- (value instanceof Uint8Array ||
21
- (typeof value === "object" &&
22
- "type" in value &&
23
- "data" in value &&
24
- value.type === "Buffer" &&
25
- Array.isArray(value.data)))) {
26
- const array = value instanceof Uint8Array ? value : new Uint8Array(value.data);
27
- return `__uint8array__${hex_1.toHex(array)}`;
28
- }
29
- return value;
30
- });
31
- }
32
- static wrap(obj) {
33
- if (obj === undefined)
34
- return undefined;
35
- return JSON.parse(JSONUint8Array.stringify(obj));
36
- }
37
- static unwrap(obj) {
38
- if (obj === undefined)
39
- return undefined;
40
- return JSONUint8Array.parse(JSON.stringify(obj));
41
- }
42
- }
43
- exports.JSONUint8Array = JSONUint8Array;
44
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/json-uint8-array/index.ts"],"names":[],"mappings":";;;AAAA,mDAAmD;AACnD,+BAAuC;AAEvC,MAAa,cAAc;IACzB,MAAM,CAAC,KAAK,CAAC,IAAY;QACvB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE;YACnC,IACE,KAAK;gBACL,OAAO,KAAK,KAAK,QAAQ;gBACzB,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAClC;gBACA,OAAO,aAAO,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC,CAAC;aACrD;YAED,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,SAAS,CAAC,GAAY;QAC3B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE;YACtC,IACE,KAAK;gBACL,CAAC,KAAK,YAAY,UAAU;oBAC1B,CAAC,OAAO,KAAK,KAAK,QAAQ;wBACxB,MAAM,IAAI,KAAK;wBACf,MAAM,IAAI,KAAK;wBACf,KAAK,CAAC,IAAI,KAAK,QAAQ;wBACvB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAC/B;gBACA,MAAM,KAAK,GACT,KAAK,YAAY,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBAEnE,OAAO,iBAAiB,WAAK,CAAC,KAAK,CAAC,EAAE,CAAC;aACxC;YAED,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,IAAI,CAAC,GAAQ;QAClB,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO,SAAS,CAAC;QAExC,OAAO,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;IACnD,CAAC;IAED,MAAM,CAAC,MAAM,CAAC,GAAQ;QACpB,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO,SAAS,CAAC;QAExC,OAAO,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;IACnD,CAAC;CACF;AA/CD,wCA+CC"}
@@ -1,100 +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
- const assert_1 = __importDefault(require("assert"));
7
- const index_1 = require("./index");
8
- describe("Test json with Uint8Array", () => {
9
- it("should stringify properly with uint8array", () => {
10
- const test = {
11
- a: 1,
12
- b: "test",
13
- c: new Uint8Array([1, 2, 3]),
14
- d: Buffer.from([1, 2, 3]),
15
- e: undefined,
16
- f: null,
17
- };
18
- const text = index_1.JSONUint8Array.stringify(test);
19
- assert_1.default.strictEqual(text, '{"a":1,"b":"test","c":"__uint8array__010203","d":"__uint8array__010203","f":null}');
20
- });
21
- it("should parse properly with the prefixed string with __uint8array__", () => {
22
- const text = '{"a":1,"b":"test","c":"__uint8array__010203","d":"__uint8array__010203","f":null}';
23
- const obj = index_1.JSONUint8Array.parse(text);
24
- assert_1.default.deepStrictEqual(obj, {
25
- a: 1,
26
- b: "test",
27
- c: new Uint8Array([1, 2, 3]),
28
- d: new Uint8Array([1, 2, 3]),
29
- f: null,
30
- });
31
- });
32
- it("should stringify properly with uint8array for nested obj", () => {
33
- const test = {
34
- a: 1,
35
- b: "test",
36
- c: new Uint8Array([1, 2, 3]),
37
- d: {
38
- a: new Uint8Array([1, 2, 3]),
39
- b: Buffer.from([1, 2, 3]),
40
- c: [new Uint8Array([1, 2, 3]), Buffer.from([1, 2, 3])],
41
- d: [new Uint8Array([1, 2, 3]), null, undefined],
42
- },
43
- };
44
- const text = index_1.JSONUint8Array.stringify(test);
45
- assert_1.default.strictEqual(text, '{"a":1,"b":"test","c":"__uint8array__010203","d":{"a":"__uint8array__010203","b":"__uint8array__010203","c":["__uint8array__010203","__uint8array__010203"],"d":["__uint8array__010203",null,null]}}');
46
- });
47
- it("should parse properly with uint8array for nested text", () => {
48
- const text = '{"a":1,"b":"test","c":"__uint8array__010203","d":{"a":"__uint8array__010203","b":"__uint8array__010203","c":["__uint8array__010203","__uint8array__010203"],"d":["__uint8array__010203",null,null]}}';
49
- const obj = index_1.JSONUint8Array.parse(text);
50
- assert_1.default.deepStrictEqual(obj, {
51
- a: 1,
52
- b: "test",
53
- c: new Uint8Array([1, 2, 3]),
54
- d: {
55
- a: new Uint8Array([1, 2, 3]),
56
- b: new Uint8Array([1, 2, 3]),
57
- c: [new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])],
58
- d: [new Uint8Array([1, 2, 3]), null, null],
59
- },
60
- });
61
- });
62
- it("should wrap/unwrap properly with uint8array for nested obj", () => {
63
- const test = {
64
- a: 1,
65
- b: "test",
66
- c: new Uint8Array([1, 2, 3]),
67
- d: {
68
- a: new Uint8Array([1, 2, 3]),
69
- b: Buffer.from([1, 2, 3]),
70
- c: [new Uint8Array([1, 2, 3]), Buffer.from([1, 2, 3])],
71
- d: [new Uint8Array([1, 2, 3]), null, undefined],
72
- },
73
- };
74
- const wraped = index_1.JSONUint8Array.wrap(test);
75
- assert_1.default.deepStrictEqual(wraped, {
76
- a: 1,
77
- b: "test",
78
- c: "__uint8array__010203",
79
- d: {
80
- a: "__uint8array__010203",
81
- b: "__uint8array__010203",
82
- c: ["__uint8array__010203", "__uint8array__010203"],
83
- d: ["__uint8array__010203", null, null],
84
- },
85
- });
86
- const unwraped = index_1.JSONUint8Array.unwrap(wraped);
87
- assert_1.default.deepStrictEqual(unwraped, {
88
- a: 1,
89
- b: "test",
90
- c: new Uint8Array([1, 2, 3]),
91
- d: {
92
- a: new Uint8Array([1, 2, 3]),
93
- b: new Uint8Array([1, 2, 3]),
94
- c: [new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])],
95
- d: [new Uint8Array([1, 2, 3]), null, null],
96
- },
97
- });
98
- });
99
- });
100
- //# sourceMappingURL=json.spec.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"json.spec.js","sourceRoot":"","sources":["../../src/json-uint8-array/json.spec.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,mCAAyC;AAEzC,QAAQ,CAAC,2BAA2B,EAAE,GAAG,EAAE;IACzC,EAAE,CAAC,2CAA2C,EAAE,GAAG,EAAE;QACnD,MAAM,IAAI,GAAG;YACX,CAAC,EAAE,CAAC;YACJ,CAAC,EAAE,MAAM;YACT,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC5B,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YACzB,CAAC,EAAE,SAAS;YACZ,CAAC,EAAE,IAAI;SACR,CAAC;QAEF,MAAM,IAAI,GAAG,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C,EAAE;gBACD,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBAC5B,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBAC5B,CAAC,EAAE,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;gBACzD,CAAC,EAAE,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;aAC3C;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -1,28 +0,0 @@
1
- /*
2
- Belows are from @cosmjs/encoding library.
3
- To reduce the bundle size of provider, put them directly here.
4
- */
5
-
6
- export function toHex(data: Uint8Array): string {
7
- let out = "";
8
- for (const byte of data) {
9
- out += ("0" + byte.toString(16)).slice(-2);
10
- }
11
- return out;
12
- }
13
-
14
- export function fromHex(hexstring: string): Uint8Array {
15
- if (hexstring.length % 2 !== 0) {
16
- throw new Error("hex string length must be a multiple of 2");
17
- }
18
-
19
- const listOfInts: number[] = [];
20
- for (let i = 0; i < hexstring.length; i += 2) {
21
- const hexByteAsString = hexstring.substr(i, 2);
22
- if (!hexByteAsString.match(/[0-9a-f]{2}/i)) {
23
- throw new Error("hex string contains invalid characters");
24
- }
25
- listOfInts.push(parseInt(hexByteAsString, 16));
26
- }
27
- return new Uint8Array(listOfInts);
28
- }
@@ -1,51 +0,0 @@
1
- // The JSON encoder that supports the `Uint8Array`.
2
- import { fromHex, toHex } from "./hex";
3
-
4
- export class JSONUint8Array {
5
- static parse(text: string) {
6
- return JSON.parse(text, (_, value) => {
7
- if (
8
- value &&
9
- typeof value === "string" &&
10
- value.startsWith("__uint8array__")
11
- ) {
12
- return fromHex(value.replace("__uint8array__", ""));
13
- }
14
-
15
- return value;
16
- });
17
- }
18
-
19
- static stringify(obj: unknown): string {
20
- return JSON.stringify(obj, (_, value) => {
21
- if (
22
- value &&
23
- (value instanceof Uint8Array ||
24
- (typeof value === "object" &&
25
- "type" in value &&
26
- "data" in value &&
27
- value.type === "Buffer" &&
28
- Array.isArray(value.data)))
29
- ) {
30
- const array =
31
- value instanceof Uint8Array ? value : new Uint8Array(value.data);
32
-
33
- return `__uint8array__${toHex(array)}`;
34
- }
35
-
36
- return value;
37
- });
38
- }
39
-
40
- static wrap(obj: any): any {
41
- if (obj === undefined) return undefined;
42
-
43
- return JSON.parse(JSONUint8Array.stringify(obj));
44
- }
45
-
46
- static unwrap(obj: any): any {
47
- if (obj === undefined) return undefined;
48
-
49
- return JSONUint8Array.parse(JSON.stringify(obj));
50
- }
51
- }
@@ -1,116 +0,0 @@
1
- import assert from "assert";
2
-
3
- import { JSONUint8Array } from "./index";
4
-
5
- describe("Test json with Uint8Array", () => {
6
- it("should stringify properly with uint8array", () => {
7
- const test = {
8
- a: 1,
9
- b: "test",
10
- c: new Uint8Array([1, 2, 3]),
11
- d: Buffer.from([1, 2, 3]),
12
- e: undefined,
13
- f: null,
14
- };
15
-
16
- const text = JSONUint8Array.stringify(test);
17
-
18
- assert.strictEqual(
19
- text,
20
- '{"a":1,"b":"test","c":"__uint8array__010203","d":"__uint8array__010203","f":null}'
21
- );
22
- });
23
-
24
- it("should parse properly with the prefixed string with __uint8array__", () => {
25
- const text =
26
- '{"a":1,"b":"test","c":"__uint8array__010203","d":"__uint8array__010203","f":null}';
27
-
28
- const obj = JSONUint8Array.parse(text);
29
- assert.deepStrictEqual(obj, {
30
- a: 1,
31
- b: "test",
32
- c: new Uint8Array([1, 2, 3]),
33
- d: new Uint8Array([1, 2, 3]),
34
- f: null,
35
- });
36
- });
37
-
38
- it("should stringify properly with uint8array for nested obj", () => {
39
- const test = {
40
- a: 1,
41
- b: "test",
42
- c: new Uint8Array([1, 2, 3]),
43
- d: {
44
- a: new Uint8Array([1, 2, 3]),
45
- b: Buffer.from([1, 2, 3]),
46
- c: [new Uint8Array([1, 2, 3]), Buffer.from([1, 2, 3])],
47
- d: [new Uint8Array([1, 2, 3]), null, undefined],
48
- },
49
- };
50
-
51
- const text = JSONUint8Array.stringify(test);
52
-
53
- assert.strictEqual(
54
- text,
55
- '{"a":1,"b":"test","c":"__uint8array__010203","d":{"a":"__uint8array__010203","b":"__uint8array__010203","c":["__uint8array__010203","__uint8array__010203"],"d":["__uint8array__010203",null,null]}}'
56
- );
57
- });
58
-
59
- it("should parse properly with uint8array for nested text", () => {
60
- const text =
61
- '{"a":1,"b":"test","c":"__uint8array__010203","d":{"a":"__uint8array__010203","b":"__uint8array__010203","c":["__uint8array__010203","__uint8array__010203"],"d":["__uint8array__010203",null,null]}}';
62
-
63
- const obj = JSONUint8Array.parse(text);
64
- assert.deepStrictEqual(obj, {
65
- a: 1,
66
- b: "test",
67
- c: new Uint8Array([1, 2, 3]),
68
- d: {
69
- a: new Uint8Array([1, 2, 3]),
70
- b: new Uint8Array([1, 2, 3]),
71
- c: [new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])],
72
- d: [new Uint8Array([1, 2, 3]), null, null],
73
- },
74
- });
75
- });
76
-
77
- it("should wrap/unwrap properly with uint8array for nested obj", () => {
78
- const test = {
79
- a: 1,
80
- b: "test",
81
- c: new Uint8Array([1, 2, 3]),
82
- d: {
83
- a: new Uint8Array([1, 2, 3]),
84
- b: Buffer.from([1, 2, 3]),
85
- c: [new Uint8Array([1, 2, 3]), Buffer.from([1, 2, 3])],
86
- d: [new Uint8Array([1, 2, 3]), null, undefined],
87
- },
88
- };
89
-
90
- const wraped = JSONUint8Array.wrap(test);
91
- assert.deepStrictEqual(wraped, {
92
- a: 1,
93
- b: "test",
94
- c: "__uint8array__010203",
95
- d: {
96
- a: "__uint8array__010203",
97
- b: "__uint8array__010203",
98
- c: ["__uint8array__010203", "__uint8array__010203"],
99
- d: ["__uint8array__010203", null, null],
100
- },
101
- });
102
-
103
- const unwraped = JSONUint8Array.unwrap(wraped);
104
- assert.deepStrictEqual(unwraped, {
105
- a: 1,
106
- b: "test",
107
- c: new Uint8Array([1, 2, 3]),
108
- d: {
109
- a: new Uint8Array([1, 2, 3]),
110
- b: new Uint8Array([1, 2, 3]),
111
- c: [new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])],
112
- d: [new Uint8Array([1, 2, 3]), null, null],
113
- },
114
- });
115
- });
116
- });