@novasamatech/host-api 0.6.6-0 → 0.6.6

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/dist/logger.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import type { Logger } from './types.js';
2
- export declare function createDefaultLogger(): Logger;
2
+ export declare function createDefaultLogger(msgPrefix?: string): Logger;
package/dist/logger.js CHANGED
@@ -1,8 +1,10 @@
1
- export function createDefaultLogger() {
1
+ export function createDefaultLogger(msgPrefix) {
2
+ const prefix = msgPrefix ? `[${msgPrefix}]` : '';
2
3
  return {
3
- info: (...args) => console.info(...args),
4
- error: (...args) => console.error(...args),
5
- warn: (...args) => console.warn(...args),
6
- log: (...args) => console.log(...args),
4
+ info: (...args) => console.info(prefix, ...args),
5
+ error: (...args) => console.error(prefix, ...args),
6
+ warn: (...args) => console.warn(prefix, ...args),
7
+ log: (...args) => console.log(prefix, ...args),
8
+ withPrefix: (newPrefix) => createDefaultLogger(newPrefix),
7
9
  };
8
10
  }
@@ -1,5 +1,5 @@
1
1
  export declare const JsonRpcMessageSendV1_request: import("scale-ts").Codec<[`0x${string}`, string]>;
2
- export declare const JsonRpcMessageSendV1_response: import("scale-ts").Codec<import("scale-ts").ResultPayload<undefined, import("packages/scale/dist/err.js").CodecError<{
2
+ export declare const JsonRpcMessageSendV1_response: import("scale-ts").Codec<import("scale-ts").ResultPayload<undefined, import("packages/scale/src/err.js").CodecError<{
3
3
  reason: string;
4
4
  }, "GenericError">>>;
5
5
  export declare const JsonRpcMessageSubscribeV1_start: import("scale-ts").Codec<`0x${string}`>;
@@ -6,6 +6,6 @@ export declare const PushNotificationV1_request: import("scale-ts").Codec<{
6
6
  text: string;
7
7
  deeplink: string | undefined;
8
8
  }>;
9
- export declare const PushNotificationV1_response: import("scale-ts").Codec<import("scale-ts").ResultPayload<undefined, import("packages/scale/dist/err.js").CodecError<{
9
+ export declare const PushNotificationV1_response: import("scale-ts").Codec<import("scale-ts").ResultPayload<undefined, import("packages/scale/src/err.js").CodecError<{
10
10
  reason: string;
11
11
  }, "GenericError">>>;
@@ -1,6 +1,6 @@
1
1
  import type { Logger } from './types.js';
2
2
  export type Provider = {
3
- logger: Logger;
3
+ readonly logger: Logger;
4
4
  isCorrectEnvironment(): boolean;
5
5
  postMessage(message: Uint8Array): void;
6
6
  subscribe(callback: (message: Uint8Array) => void): () => void;
package/dist/transport.js CHANGED
@@ -1,10 +1,15 @@
1
- import { enumValue, isEnumVariant, resultErr, resultOk } from '@novasamatech/scale';
1
+ import { enumValue, isEnumVariant, resultErr, resultOk, toHex } from '@novasamatech/scale';
2
2
  import { createNanoEvents } from 'nanoevents';
3
3
  import { HANDSHAKE_INTERVAL, HANDSHAKE_TIMEOUT, JAM_CODEC_PROTOCOL_ID } from './constants.js';
4
4
  import { composeAction, createRequestId, delay, promiseWithResolvers } from './helpers.js';
5
- import { Message } from './protocol/messageCodec.js';
5
+ import { Message, MessagePayload } from './protocol/messageCodec.js';
6
6
  import { HandshakeErr } from './protocol/v1/handshake.js';
7
- const isConnected = (status) => status === 'connected';
7
+ function isConnected(status) {
8
+ return status === 'connected';
9
+ }
10
+ function getSubscriptionKey(method, payload) {
11
+ return `${method}_${toHex(MessagePayload.enc(payload))}`;
12
+ }
8
13
  export function createTransport(provider) {
9
14
  let codecVersion = JAM_CODEC_PROTOCOL_ID;
10
15
  const handshakeAbortController = new AbortController();
@@ -39,6 +44,8 @@ export function createTransport(provider) {
39
44
  throwIfIncorrectEnvironment();
40
45
  throwIfInvalidCodecVersion();
41
46
  }
47
+ // subscriptions management (multiplexing)
48
+ const activeSubscriptions = new Map();
42
49
  const transport = {
43
50
  provider,
44
51
  isCorrectEnvironment() {
@@ -137,39 +144,77 @@ export function createTransport(provider) {
137
144
  subscribe(method, payload, callback) {
138
145
  checks();
139
146
  const events = createNanoEvents();
140
- const requestId = createRequestId();
141
147
  const startAction = composeAction(method, 'start');
142
- const stopAction = composeAction(method, 'stop');
143
- const interruptAction = composeAction(method, 'interrupt');
144
- const receiveAction = composeAction(method, 'receive');
145
- const unsubscribeReceive = transport.listenMessages(receiveAction, (receivedId, data) => {
146
- if (receivedId === requestId) {
147
- callback(data.value);
148
- }
149
- });
150
- const unsubscribeInterrupt = transport.listenMessages(interruptAction, receivedId => {
151
- if (receivedId === requestId) {
152
- events.emit('interrupt');
153
- stopSubscription();
148
+ const startPayload = enumValue(startAction, payload);
149
+ const subscriptionKey = getSubscriptionKey(method, startPayload);
150
+ let subscription = activeSubscriptions.get(subscriptionKey);
151
+ function unsubscribeListener() {
152
+ const subscription = activeSubscriptions.get(subscriptionKey);
153
+ if (subscription) {
154
+ const newListeners = subscription.listeners.filter(listener => listener.call !== callback);
155
+ if (newListeners.length === 0) {
156
+ activeSubscriptions.delete(subscriptionKey);
157
+ subscription.kill();
158
+ }
159
+ else {
160
+ subscription.listeners = newListeners;
161
+ }
154
162
  }
155
- });
156
- const stopSubscription = () => {
157
- unsubscribeReceive();
158
- unsubscribeInterrupt();
159
- events.events = {};
163
+ }
164
+ const listener = {
165
+ call: callback,
166
+ unsubscribe: unsubscribeListener,
160
167
  };
161
- const startPayload = enumValue(startAction, payload);
162
- transport.postMessage(requestId, startPayload);
163
- return {
164
- unsubscribe() {
165
- stopSubscription();
166
- const stopPayload = enumValue(stopAction, undefined);
167
- transport.postMessage(requestId, stopPayload);
168
- },
168
+ const publicSubscription = {
169
+ unsubscribe: unsubscribeListener,
169
170
  onInterrupt(callback) {
170
171
  return events.on('interrupt', callback);
171
172
  },
172
173
  };
174
+ // wiring up a real subscription
175
+ if (!subscription) {
176
+ const requestId = createRequestId();
177
+ const stopAction = composeAction(method, 'stop');
178
+ const interruptAction = composeAction(method, 'interrupt');
179
+ const receiveAction = composeAction(method, 'receive');
180
+ const unsubscribeReceive = transport.listenMessages(receiveAction, (receivedId, data) => {
181
+ if (receivedId === requestId) {
182
+ const subscription = activeSubscriptions.get(subscriptionKey);
183
+ if (subscription) {
184
+ for (const listener of subscription.listeners) {
185
+ listener.call(data.value);
186
+ }
187
+ }
188
+ }
189
+ });
190
+ const unsubscribeInterrupt = transport.listenMessages(interruptAction, receivedId => {
191
+ if (receivedId === requestId) {
192
+ events.emit('interrupt');
193
+ stopSubscription();
194
+ }
195
+ });
196
+ const stopSubscription = () => {
197
+ unsubscribeReceive();
198
+ unsubscribeInterrupt();
199
+ events.events = {};
200
+ };
201
+ // creating subscription
202
+ subscription = {
203
+ requestId,
204
+ kill: () => {
205
+ stopSubscription();
206
+ const stopPayload = enumValue(stopAction, undefined);
207
+ transport.postMessage(requestId, stopPayload);
208
+ },
209
+ listeners: [listener],
210
+ };
211
+ activeSubscriptions.set(subscriptionKey, subscription);
212
+ transport.postMessage(requestId, startPayload);
213
+ }
214
+ else {
215
+ subscription.listeners.push(listener);
216
+ }
217
+ return publicSubscription;
173
218
  },
174
219
  handleSubscription(method, handler) {
175
220
  checks();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,58 @@
1
+ import { createNanoEvents } from 'nanoevents';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { createDefaultLogger } from './logger.js';
4
+ import { createTransport } from './transport.js';
5
+ function createProviders() {
6
+ const bus = createNanoEvents();
7
+ function createProvider(listenTo, postTo) {
8
+ return {
9
+ logger: createDefaultLogger(),
10
+ isCorrectEnvironment: () => true,
11
+ dispose: () => delete bus.events[listenTo],
12
+ subscribe: callback => bus.on(listenTo, callback),
13
+ postMessage: message => bus.emit(postTo, message),
14
+ };
15
+ }
16
+ return {
17
+ host: createProvider('toHost', 'toSdk'),
18
+ sdk: createProvider('toSdk', 'toHost'),
19
+ };
20
+ }
21
+ describe('transport', () => {
22
+ describe('subscription', () => {
23
+ it('should multiplex subscriptions', () => {
24
+ const providers = createProviders();
25
+ const events = createNanoEvents();
26
+ const host = createTransport(providers.host);
27
+ const sdk = createTransport(providers.sdk);
28
+ const hostUnsubscribe = vi.fn();
29
+ const containerHandler = vi.fn((_, send) => {
30
+ const unsub = events.on('push', () => {
31
+ send({ tag: 'v1', value: 'connected' });
32
+ });
33
+ return () => {
34
+ unsub();
35
+ hostUnsubscribe();
36
+ };
37
+ });
38
+ host.handleSubscription('host_account_connection_status_subscribe', containerHandler);
39
+ const s1Handler = vi.fn();
40
+ const s1 = sdk.subscribe('host_account_connection_status_subscribe', { tag: 'v1', value: undefined }, s1Handler);
41
+ const s2Handler = vi.fn();
42
+ const s2 = sdk.subscribe('host_account_connection_status_subscribe', { tag: 'v1', value: undefined }, s2Handler);
43
+ events.emit('push');
44
+ expect(s1Handler).toHaveBeenCalledTimes(1);
45
+ expect(s2Handler).toHaveBeenCalledTimes(1);
46
+ s1.unsubscribe();
47
+ expect(hostUnsubscribe).not.toBeCalled();
48
+ events.emit('push');
49
+ expect(s1Handler).toHaveBeenCalledTimes(1);
50
+ expect(s2Handler).toHaveBeenCalledTimes(2);
51
+ s2.unsubscribe();
52
+ expect(hostUnsubscribe).toHaveBeenCalledTimes(1);
53
+ events.emit('push');
54
+ expect(s1Handler).toHaveBeenCalledTimes(1);
55
+ expect(s2Handler).toHaveBeenCalledTimes(2);
56
+ });
57
+ });
58
+ });
package/dist/types.d.ts CHANGED
@@ -2,7 +2,9 @@ import type { HostApiProtocol } from './protocol/impl.js';
2
2
  import type { ComposeMessageAction, MessageAction, MessagePayloadSchema, PickMessagePayload, PickMessagePayloadValue } from './protocol/messageCodec.js';
3
3
  import type { Provider } from './provider.js';
4
4
  export type HostApiMethod = keyof HostApiProtocol;
5
- export type Logger = Record<'info' | 'warn' | 'error' | 'log', (...args: unknown[]) => void>;
5
+ export type Logger = Record<'info' | 'warn' | 'error' | 'log', (...args: unknown[]) => void> & {
6
+ withPrefix(prefix: string): Logger;
7
+ };
6
8
  export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected';
7
9
  export type RequestHandler<Method extends string> = (message: PickMessagePayloadValue<ComposeMessageAction<Method, 'request'>>) => PromiseLike<PickMessagePayloadValue<ComposeMessageAction<Method, 'response'>>>;
8
10
  export type SubscriptionHandler<Method extends string> = (params: PickMessagePayloadValue<ComposeMessageAction<Method, 'start'>>, send: (value: PickMessagePayloadValue<ComposeMessageAction<Method, 'receive'>>) => void, interrupt: () => void) => VoidFunction;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@novasamatech/host-api",
3
3
  "type": "module",
4
- "version": "0.6.6-0",
4
+ "version": "0.6.6",
5
5
  "description": "Host API: transport implementation for host - product integration.",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -12,6 +12,7 @@
12
12
  "exports": {
13
13
  "./package.json": "./package.json",
14
14
  ".": {
15
+ "#/source": "./src/index.ts",
15
16
  "types": "./dist/index.d.ts",
16
17
  "default": "./dist/index.js"
17
18
  }
@@ -21,10 +22,10 @@
21
22
  "README.md"
22
23
  ],
23
24
  "dependencies": {
24
- "@novasamatech/scale": "0.6.6-0",
25
+ "@novasamatech/scale": "0.6.6",
25
26
  "@polkadot-api/utils": "^0.2.0",
26
27
  "nanoevents": "9.1.0",
27
- "nanoid": "5.1.6",
28
+ "nanoid": "5.1.7",
28
29
  "neverthrow": "^8.2.0",
29
30
  "scale-ts": "1.6.1"
30
31
  },