Formatting
This commit is contained in:
@@ -1,2 +1,4 @@
|
|||||||
/node_modules
|
/node_modules
|
||||||
/dist
|
/dist
|
||||||
|
/coverage
|
||||||
|
/docs
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Prettier configuration aligned with @xo-cash/eslint-config
|
||||||
|
export default {
|
||||||
|
// Matches @stylistic/max-len': [ 'warn', 150, ...]
|
||||||
|
printWidth: 150,
|
||||||
|
|
||||||
|
// Matches @stylistic/no-tabs': [ 'error' ]
|
||||||
|
useTabs: false,
|
||||||
|
|
||||||
|
// Matches @stylistic/indent': [ 'error', 4, ...]
|
||||||
|
tabWidth: 4,
|
||||||
|
|
||||||
|
// Matches @stylistic/array-bracket-spacing': [ 'error', 'always', ...]
|
||||||
|
bracketSpacing: true,
|
||||||
|
|
||||||
|
// Matches @stylistic/quotes: ['error', 'single', { avoidEscape: true }], from @chalp/eslint-airbnb/base/stylistic.js
|
||||||
|
singleQuote: true,
|
||||||
|
|
||||||
|
// Matches @stylistic/semi: ['error', 'always'], from @chalp/eslint-airbnb/base/stylistic.js
|
||||||
|
semi: true,
|
||||||
|
|
||||||
|
// Matches @stylistic/arrow-parens: ['error', 'always'], from @chalp/eslint-airbnb/base/stylistic.js
|
||||||
|
arrowParens: 'always',
|
||||||
|
};
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { subtle, getRandomValues } from "node:crypto";
|
import { subtle, getRandomValues } from 'node:crypto';
|
||||||
import { fromExtendedJson, toExtendedJson } from "@xo-cash/utils";
|
import { fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
||||||
import { sha256, binToBase64, binToHex } from "@bitauth/libauth";
|
import { sha256, binToBase64, binToHex } from '@bitauth/libauth';
|
||||||
|
|
||||||
import { BaseSyncClient, type Resource, type ResourcesRecord } from "../../source/shared/base-client.js";
|
import { BaseSyncClient, type Resource, type ResourcesRecord } from '../../source/shared/base-client.js';
|
||||||
|
|
||||||
type ResourceKey = {
|
type ResourceKey = {
|
||||||
resourceId: string;
|
resourceId: string;
|
||||||
@@ -32,7 +32,7 @@ export class EncryptedClientPerResource<T = unknown> extends BaseSyncClient<T> {
|
|||||||
this.emit('resource-instance-updated', {
|
this.emit('resource-instance-updated', {
|
||||||
...message,
|
...message,
|
||||||
resourceId: resourceKey.resourceId,
|
resourceId: resourceKey.resourceId,
|
||||||
value: await EncryptedClientPerResource.decrypt(resourceKey.keyMaterial, message.value) as T,
|
value: (await EncryptedClientPerResource.decrypt(resourceKey.keyMaterial, message.value)) as T,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.emit('error', error instanceof Error ? error : new Error(String(error)));
|
this.emit('error', error instanceof Error ? error : new Error(String(error)));
|
||||||
@@ -75,17 +75,21 @@ export class EncryptedClientPerResource<T = unknown> extends BaseSyncClient<T> {
|
|||||||
* @returns The resources record with decrypted values, keyed by original resource ID
|
* @returns The resources record with decrypted values, keyed by original resource ID
|
||||||
*/
|
*/
|
||||||
private async decryptResources(resources: ResourcesRecord<string>): Promise<ResourcesRecord<T>> {
|
private async decryptResources(resources: ResourcesRecord<string>): Promise<ResourcesRecord<T>> {
|
||||||
const entries = await Promise.all(Object.entries(resources).map(async ([ hashedResourceId, resource ]) => {
|
const entries = await Promise.all(
|
||||||
|
Object.entries(resources).map(async ([hashedResourceId, resource]) => {
|
||||||
const { resourceId, keyMaterial } = this.getResourceKey(hashedResourceId);
|
const { resourceId, keyMaterial } = this.getResourceKey(hashedResourceId);
|
||||||
|
|
||||||
const instances: Resource<T>[] = await Promise.all(resource.instances.map(async (instance) => ({
|
const instances: Resource<T>[] = await Promise.all(
|
||||||
|
resource.instances.map(async (instance) => ({
|
||||||
...instance,
|
...instance,
|
||||||
resourceId,
|
resourceId,
|
||||||
value: await EncryptedClientPerResource.decrypt(keyMaterial, instance.value) as T,
|
value: (await EncryptedClientPerResource.decrypt(keyMaterial, instance.value)) as T,
|
||||||
})));
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
return [ resourceId, { ...resource, instances } ] as const;
|
return [resourceId, { ...resource, instances }] as const;
|
||||||
}));
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
return Object.fromEntries(entries);
|
return Object.fromEntries(entries);
|
||||||
}
|
}
|
||||||
@@ -107,12 +111,14 @@ export class EncryptedClientPerResource<T = unknown> extends BaseSyncClient<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async writeMany(resources: Record<string, T>): Promise<ResourcesRecord<T>> {
|
public async writeMany(resources: Record<string, T>): Promise<ResourcesRecord<T>> {
|
||||||
const encryptedEntries = await Promise.all(Object.entries(resources).map(async ([ resourceId, value ]) => {
|
const encryptedEntries = await Promise.all(
|
||||||
|
Object.entries(resources).map(async ([resourceId, value]) => {
|
||||||
const hashedResourceId = this.hashResourceId(resourceId);
|
const hashedResourceId = this.hashResourceId(resourceId);
|
||||||
const { keyMaterial } = this.getResourceKey(hashedResourceId);
|
const { keyMaterial } = this.getResourceKey(hashedResourceId);
|
||||||
|
|
||||||
return [ hashedResourceId, await EncryptedClientPerResource.encrypt(keyMaterial, value) ] as const;
|
return [hashedResourceId, await EncryptedClientPerResource.encrypt(keyMaterial, value)] as const;
|
||||||
}));
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const response = await this.client.writeMany(Object.fromEntries(encryptedEntries));
|
const response = await this.client.writeMany(Object.fromEntries(encryptedEntries));
|
||||||
|
|
||||||
@@ -152,7 +158,7 @@ export class EncryptedClientPerResource<T = unknown> extends BaseSyncClient<T> {
|
|||||||
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, encodedValue);
|
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, encodedValue);
|
||||||
|
|
||||||
// Prepend the IV so it can be recovered when decrypting
|
// Prepend the IV so it can be recovered when decrypting
|
||||||
return binToBase64(Buffer.concat([ iv, new Uint8Array(encrypted) ]));
|
return binToBase64(Buffer.concat([iv, new Uint8Array(encrypted)]));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { subtle, getRandomValues } from "node:crypto";
|
import { subtle, getRandomValues } from 'node:crypto';
|
||||||
import { fromExtendedJson, toExtendedJson } from "@xo-cash/utils";
|
import { fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
||||||
import { sha256, binToBase64 } from "@bitauth/libauth";
|
import { sha256, binToBase64 } from '@bitauth/libauth';
|
||||||
|
|
||||||
import { BaseSyncClient, type ResourcesRecord } from "../../source/shared/base-client.js";
|
import { BaseSyncClient, type ResourcesRecord } from '../../source/shared/base-client.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encrypts every resource with a single shared key.
|
* Encrypts every resource with a single shared key.
|
||||||
@@ -10,7 +10,10 @@ import { BaseSyncClient, type ResourcesRecord } from "../../source/shared/base-c
|
|||||||
export class EncryptedClient<T = unknown> extends BaseSyncClient<T> {
|
export class EncryptedClient<T = unknown> extends BaseSyncClient<T> {
|
||||||
private readonly encryptionKey: Uint8Array;
|
private readonly encryptionKey: Uint8Array;
|
||||||
|
|
||||||
constructor(private readonly client: BaseSyncClient<string>, encryptionKey: Uint8Array | string) {
|
constructor(
|
||||||
|
private readonly client: BaseSyncClient<string>,
|
||||||
|
encryptionKey: Uint8Array | string,
|
||||||
|
) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
// Hash the encryption key into 32 bytes if it is a string
|
// Hash the encryption key into 32 bytes if it is a string
|
||||||
@@ -20,7 +23,7 @@ export class EncryptedClient<T = unknown> extends BaseSyncClient<T> {
|
|||||||
try {
|
try {
|
||||||
this.emit('resource-instance-updated', {
|
this.emit('resource-instance-updated', {
|
||||||
...message,
|
...message,
|
||||||
value: await EncryptedClient.decrypt(this.encryptionKey, message.value) as T,
|
value: (await EncryptedClient.decrypt(this.encryptionKey, message.value)) as T,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.emit('error', error instanceof Error ? error : new Error(String(error)));
|
this.emit('error', error instanceof Error ? error : new Error(String(error)));
|
||||||
@@ -34,14 +37,18 @@ export class EncryptedClient<T = unknown> extends BaseSyncClient<T> {
|
|||||||
* @returns The resources record with decrypted values
|
* @returns The resources record with decrypted values
|
||||||
*/
|
*/
|
||||||
private async decryptResources(resources: ResourcesRecord<string>): Promise<ResourcesRecord<T>> {
|
private async decryptResources(resources: ResourcesRecord<string>): Promise<ResourcesRecord<T>> {
|
||||||
const entries = await Promise.all(Object.entries(resources).map(async ([ resourceId, resource ]) => {
|
const entries = await Promise.all(
|
||||||
const instances = await Promise.all(resource.instances.map(async (instance) => ({
|
Object.entries(resources).map(async ([resourceId, resource]) => {
|
||||||
|
const instances = await Promise.all(
|
||||||
|
resource.instances.map(async (instance) => ({
|
||||||
...instance,
|
...instance,
|
||||||
value: await EncryptedClient.decrypt(this.encryptionKey, instance.value) as T,
|
value: (await EncryptedClient.decrypt(this.encryptionKey, instance.value)) as T,
|
||||||
})));
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
return [ resourceId, { ...resource, instances } ] as const;
|
return [resourceId, { ...resource, instances }] as const;
|
||||||
}));
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
return Object.fromEntries(entries);
|
return Object.fromEntries(entries);
|
||||||
}
|
}
|
||||||
@@ -61,9 +68,11 @@ export class EncryptedClient<T = unknown> extends BaseSyncClient<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async writeMany(resources: Record<string, T>): Promise<ResourcesRecord<T>> {
|
public async writeMany(resources: Record<string, T>): Promise<ResourcesRecord<T>> {
|
||||||
const encryptedEntries = await Promise.all(Object.entries(resources).map(async ([ resourceId, value ]) => {
|
const encryptedEntries = await Promise.all(
|
||||||
return [ resourceId, await EncryptedClient.encrypt(this.encryptionKey, value) ] as const;
|
Object.entries(resources).map(async ([resourceId, value]) => {
|
||||||
}));
|
return [resourceId, await EncryptedClient.encrypt(this.encryptionKey, value)] as const;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const response = await this.client.writeMany(Object.fromEntries(encryptedEntries));
|
const response = await this.client.writeMany(Object.fromEntries(encryptedEntries));
|
||||||
|
|
||||||
@@ -103,7 +112,7 @@ export class EncryptedClient<T = unknown> extends BaseSyncClient<T> {
|
|||||||
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, encodedValue);
|
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, encodedValue);
|
||||||
|
|
||||||
// Prepend the IV so it can be recovered when decrypting
|
// Prepend the IV so it can be recovered when decrypting
|
||||||
return binToBase64(Buffer.concat([ iv, new Uint8Array(encrypted) ]));
|
return binToBase64(Buffer.concat([iv, new Uint8Array(encrypted)]));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+8
-6
@@ -1,21 +1,23 @@
|
|||||||
import type { BaseSyncClient, ResourcesRecord } from "../source/shared/base-client.js";
|
import type { BaseSyncClient, ResourcesRecord } from '../source/shared/base-client.js';
|
||||||
|
|
||||||
export const writeMany = async (client: BaseSyncClient<{ message: string }>): Promise<ResourcesRecord<{ message: string }>> => {
|
export const writeMany = async (client: BaseSyncClient<{ message: string }>): Promise<ResourcesRecord<{ message: string }>> => {
|
||||||
// Create a group of resources with changes
|
// Create a group of resources with changes
|
||||||
const resources = Object.fromEntries(Array.from({ length: 10 }, (_, index) => [
|
const resources = Object.fromEntries(
|
||||||
|
Array.from({ length: 10 }, (_, index) => [
|
||||||
`resource-${index}`,
|
`resource-${index}`,
|
||||||
{
|
{
|
||||||
message: `Hello, world! this is the minimal sync client using ${client.constructor.name} ${index}`,
|
message: `Hello, world! this is the minimal sync client using ${client.constructor.name} ${index}`,
|
||||||
},
|
},
|
||||||
]));
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
// Write the resources to the server
|
// Write the resources to the server
|
||||||
const res = await client.writeMany(resources);
|
const res = await client.writeMany(resources);
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
}
|
};
|
||||||
|
|
||||||
export const readMany = async (client: BaseSyncClient<{ message: string }>,): Promise<ResourcesRecord<{ message: string }>> => {
|
export const readMany = async (client: BaseSyncClient<{ message: string }>): Promise<ResourcesRecord<{ message: string }>> => {
|
||||||
// Create a list of resource IDs
|
// Create a list of resource IDs
|
||||||
const resources = Array.from({ length: 10 }, (_, index) => `resource-${index}`);
|
const resources = Array.from({ length: 10 }, (_, index) => `resource-${index}`);
|
||||||
|
|
||||||
@@ -23,4 +25,4 @@ export const readMany = async (client: BaseSyncClient<{ message: string }>,): Pr
|
|||||||
const res = await client.readMany(resources);
|
const res = await client.readMany(resources);
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
}
|
};
|
||||||
|
|||||||
+14
-10
@@ -1,16 +1,16 @@
|
|||||||
import { PrivateKey } from "@xo-cash/primitives";
|
import { PrivateKey } from '@xo-cash/primitives';
|
||||||
|
|
||||||
// Core clients
|
// Core clients
|
||||||
import type { BaseSyncClient } from "../source/shared/base-client.js";
|
import type { BaseSyncClient } from '../source/shared/base-client.js';
|
||||||
import { SSEClient } from '../source/sse/client.js';
|
import { SSEClient } from '../source/sse/client.js';
|
||||||
import { WsClient } from "../source/ws/client.js";
|
import { WsClient } from '../source/ws/client.js';
|
||||||
|
|
||||||
// Experimental clients
|
// Experimental clients
|
||||||
import { EncryptedClientPerResource } from "./experimental/encrypted-client-per-resource.js";
|
import { EncryptedClientPerResource } from './experimental/encrypted-client-per-resource.js';
|
||||||
import { EncryptedClient } from "./experimental/encrypted-client.js";
|
import { EncryptedClient } from './experimental/encrypted-client.js';
|
||||||
|
|
||||||
// Shared functions
|
// Shared functions
|
||||||
import { writeMany, readMany } from "./shared.js";
|
import { writeMany, readMany } from './shared.js';
|
||||||
|
|
||||||
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
||||||
|
|
||||||
@@ -18,7 +18,9 @@ const clients = {
|
|||||||
sse: new SSEClient<{ message: string }>('https://dev.v2.sync.xo.harvmaster.com', privateKey),
|
sse: new SSEClient<{ message: string }>('https://dev.v2.sync.xo.harvmaster.com', privateKey),
|
||||||
ws: new WsClient<{ message: string }>('wss://dev.v2.sync.xo.harvmaster.com', privateKey),
|
ws: new WsClient<{ message: string }>('wss://dev.v2.sync.xo.harvmaster.com', privateKey),
|
||||||
encrypted: new EncryptedClient<{ message: string }>(new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey), 'secret'),
|
encrypted: new EncryptedClient<{ message: string }>(new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey), 'secret'),
|
||||||
encryptedPerResource: new EncryptedClientPerResource<{ message: string }>(new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey)),
|
encryptedPerResource: new EncryptedClientPerResource<{ message: string }>(
|
||||||
|
new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Test the suite for a given client
|
// Test the suite for a given client
|
||||||
@@ -34,7 +36,9 @@ const testSuite = async (client: BaseSyncClient<{ message: string }>) => {
|
|||||||
await client.subscribe('test');
|
await client.subscribe('test');
|
||||||
|
|
||||||
// Write a new value to the resource
|
// Write a new value to the resource
|
||||||
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using ' + client.constructor.name});
|
await client.write('test', {
|
||||||
|
message: 'Hello, world! this is the minimal sync client using ' + client.constructor.name,
|
||||||
|
});
|
||||||
|
|
||||||
// Read the current value of the resource
|
// Read the current value of the resource
|
||||||
const data = await client.read('test');
|
const data = await client.read('test');
|
||||||
@@ -52,7 +56,7 @@ const testSuite = async (client: BaseSyncClient<{ message: string }>) => {
|
|||||||
await client.disconnect();
|
await client.disconnect();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
// Get the clients to test
|
// Get the clients to test
|
||||||
const selectClients = (params: string[]): BaseSyncClient<{ message: string }>[] => {
|
const selectClients = (params: string[]): BaseSyncClient<{ message: string }>[] => {
|
||||||
@@ -68,7 +72,7 @@ const selectClients = (params: string[]): BaseSyncClient<{ message: string }>[]
|
|||||||
|
|
||||||
// Return the clients that are known to the clients object
|
// Return the clients that are known to the clients object
|
||||||
return names.map((n) => clients[n as keyof typeof clients]);
|
return names.map((n) => clients[n as keyof typeof clients]);
|
||||||
}
|
};
|
||||||
|
|
||||||
// Get the params
|
// Get the params
|
||||||
const params = process.argv.slice(2);
|
const params = process.argv.slice(2);
|
||||||
|
|||||||
+17
-13
@@ -1,28 +1,32 @@
|
|||||||
import { PrivateKey } from "@xo-cash/primitives";
|
import { PrivateKey } from '@xo-cash/primitives';
|
||||||
|
|
||||||
import type { BaseSyncClient } from "../source/shared/base-client.js";
|
import type { BaseSyncClient } from '../source/shared/base-client.js';
|
||||||
|
|
||||||
import { SSEClient } from "../source/sse/client.js";
|
import { SSEClient } from '../source/sse/client.js';
|
||||||
import { EncryptedClientPerResource } from "./experimental/encrypted-client-per-resource.js";
|
import { EncryptedClientPerResource } from './experimental/encrypted-client-per-resource.js';
|
||||||
|
|
||||||
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
||||||
|
|
||||||
// Define some formatting helpers
|
// Define some formatting helpers
|
||||||
const formatResourceId = (resourceId: string) => {
|
const formatResourceId = (resourceId: string) => {
|
||||||
return `\x1b[32m${resourceId}\x1b[0m`;
|
return `\x1b[32m${resourceId}\x1b[0m`;
|
||||||
}
|
};
|
||||||
|
|
||||||
const formatMessage = (message: string) => {
|
const formatMessage = (message: string) => {
|
||||||
return `\x1b[34m${message}\x1b[0m`;
|
return `\x1b[34m${message}\x1b[0m`;
|
||||||
}
|
};
|
||||||
|
|
||||||
const resetFormatting = () => {
|
const resetFormatting = () => {
|
||||||
return `\x1b[0m`;
|
return '\x1b[0m';
|
||||||
}
|
};
|
||||||
|
|
||||||
const startTUI = async (client: BaseSyncClient<string>) => {
|
const startTUI = async (client: BaseSyncClient<string>) => {
|
||||||
// Listen and log out the resource change
|
// Listen and log out the resource change
|
||||||
client.on('resource-instance-updated', (message) => {
|
client.on('resource-instance-updated', (message) => {
|
||||||
// Print the message with colours
|
// Print the message with colours
|
||||||
console.log(`${formatResourceId(message.resourceId)}:${formatResourceId(message.publicKey)} updated: ${formatMessage(message.value)}${resetFormatting()}`);
|
console.log(
|
||||||
|
`${formatResourceId(message.resourceId)}:${formatResourceId(message.publicKey)} updated: ${formatMessage(message.value)}${resetFormatting()}`,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Connect to the sync server and subscribe to the resource
|
// Connect to the sync server and subscribe to the resource
|
||||||
@@ -43,12 +47,12 @@ const startTUI = async (client: BaseSyncClient<string>) => {
|
|||||||
await client.write('encrypted-test', message);
|
await client.write('encrypted-test', message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const clients = {
|
const clients = {
|
||||||
'sse': new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey),
|
sse: new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey),
|
||||||
'encrypted': new EncryptedClientPerResource<string>(new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey)),
|
encrypted: new EncryptedClientPerResource<string>(new SSEClient<string>('https://dev.v2.sync.xo.harvmaster.com', privateKey)),
|
||||||
}
|
};
|
||||||
|
|
||||||
const params = process.argv.slice(2);
|
const params = process.argv.slice(2);
|
||||||
const client = params[0] === 'false' ? clients.sse : clients.encrypted;
|
const client = params[0] === 'false' ? clients.sse : clients.encrypted;
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import baseConfig from '@xo-cash/eslint-config';
|
||||||
|
|
||||||
|
export default [
|
||||||
|
{
|
||||||
|
ignores: [ 'coverage/**', 'docs/**', 'demo/**' ],
|
||||||
|
},
|
||||||
|
...baseConfig,
|
||||||
|
];
|
||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
export * from './shared/base-client.js';
|
export * from './shared/base-client.ts';
|
||||||
|
|
||||||
export * from './sse/client.js';
|
export * from './sse/client.ts';
|
||||||
export * from './ws/client.js';
|
export * from './ws/client.ts';
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { binToHex, flattenBinArray, secp256k1, sha256 } from "@bitauth/libauth";
|
import { binToHex, flattenBinArray, secp256k1, sha256 } from '@bitauth/libauth';
|
||||||
|
|
||||||
import { toExtendedJson, EventEmitter, fromExtendedJson } from "@xo-cash/utils";
|
import { toExtendedJson, EventEmitter, fromExtendedJson } from '@xo-cash/utils';
|
||||||
import type { WriteRequest } from "../types.js";
|
import type { WriteRequest } from '../types.ts';
|
||||||
import z from "zod";
|
import z from 'zod';
|
||||||
|
|
||||||
export type AuthenticatedRequestHeaders = {
|
export type AuthenticatedRequestHeaders = {
|
||||||
'X-Public-Key': string;
|
'X-Public-Key': string;
|
||||||
@@ -18,7 +18,7 @@ export type XOSyncClientEventMap<T = unknown> = {
|
|||||||
resourceId: string;
|
resourceId: string;
|
||||||
};
|
};
|
||||||
'subscriptions-updated': Set<string>;
|
'subscriptions-updated': Set<string>;
|
||||||
'error': Error;
|
error: Error;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Resource<PayloadType = unknown> = z.infer<typeof BaseSyncClient.resourceInstanceSchema> & {
|
export type Resource<PayloadType = unknown> = z.infer<typeof BaseSyncClient.resourceInstanceSchema> & {
|
||||||
@@ -28,7 +28,6 @@ export type Resource<PayloadType = unknown> = z.infer<typeof BaseSyncClient.reso
|
|||||||
export type ResourcesRecord<PayloadType = unknown> = Record<string, { instances: Resource<PayloadType>[] }>;
|
export type ResourcesRecord<PayloadType = unknown> = Record<string, { instances: Resource<PayloadType>[] }>;
|
||||||
|
|
||||||
export abstract class BaseSyncClient<T = unknown> extends EventEmitter<XOSyncClientEventMap<T>> {
|
export abstract class BaseSyncClient<T = unknown> extends EventEmitter<XOSyncClientEventMap<T>> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connects to the sync server
|
* Connects to the sync server
|
||||||
*/
|
*/
|
||||||
@@ -214,7 +213,7 @@ export abstract class BaseSyncClient<T = unknown> extends EventEmitter<XOSyncCli
|
|||||||
* @returns The Resource Object with the decoded value
|
* @returns The Resource Object with the decoded value
|
||||||
*/
|
*/
|
||||||
static decodeResourcesResponse<T = unknown>(response: z.infer<typeof BaseSyncClient.resourcesResponseSchema>): ResourcesRecord<T> {
|
static decodeResourcesResponse<T = unknown>(response: z.infer<typeof BaseSyncClient.resourcesResponseSchema>): ResourcesRecord<T> {
|
||||||
return Object.entries(response.resources).reduce<ResourcesRecord<T>>((acc, [resourceId, resource]) => {
|
return Object.entries(response.resources).reduce<ResourcesRecord<T>>((acc, [ resourceId, resource ]) => {
|
||||||
// Get the instances
|
// Get the instances
|
||||||
const instances = resource.instances;
|
const instances = resource.instances;
|
||||||
|
|
||||||
|
|||||||
+29
-20
@@ -1,7 +1,7 @@
|
|||||||
import { SSESession, toExtendedJson, fromExtendedJson } from '@xo-cash/utils';
|
import { SSESession, toExtendedJson, fromExtendedJson } from '@xo-cash/utils';
|
||||||
import { PrivateKey } from '@xo-cash/primitives'
|
import type { PrivateKey } from '@xo-cash/primitives';
|
||||||
|
|
||||||
import { BaseSyncClient, type ResourcesRecord } from '../shared/base-client.js';
|
import { BaseSyncClient, type ResourcesRecord } from '../shared/base-client.ts';
|
||||||
|
|
||||||
export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType> {
|
export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType> {
|
||||||
private readonly url: string;
|
private readonly url: string;
|
||||||
@@ -11,7 +11,7 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
private privateKey: PrivateKey;
|
private privateKey: PrivateKey;
|
||||||
private textEncoder = new TextEncoder();
|
private textEncoder = new TextEncoder();
|
||||||
|
|
||||||
private get subscriptionUrl() {
|
private get subscriptionUrl(): string {
|
||||||
return `${this.url}/data/subscribe`;
|
return `${this.url}/data/subscribe`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,16 +28,20 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
|
|
||||||
// Whenever we get a new subscription, we need to reconnect the session with the new subscriptions in the body
|
// Whenever we get a new subscription, we need to reconnect the session with the new subscriptions in the body
|
||||||
// We add a small debounce to this to prevent parallel subscriptions from causing multiple reconnects
|
// We add a small debounce to this to prevent parallel subscriptions from causing multiple reconnects
|
||||||
this.on('subscriptions-updated', () => {
|
this.on(
|
||||||
|
'subscriptions-updated',
|
||||||
|
() => {
|
||||||
// Nothing awaits this listener, so report failures as an error event instead of an unhandled rejection
|
// Nothing awaits this listener, so report failures as an error event instead of an unhandled rejection
|
||||||
this.reconnect().catch((error) => this.emit('error', error));
|
this.reconnect().catch((error) => this.emit('error', error));
|
||||||
}, 25);
|
},
|
||||||
|
25,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connects to the server
|
* Connects to the server
|
||||||
*/
|
*/
|
||||||
async connect() {
|
async connect(): Promise<void> {
|
||||||
// The server rejects a subscribe request with no resource IDs, so there is nothing to connect to yet.
|
// The server rejects a subscribe request with no resource IDs, so there is nothing to connect to yet.
|
||||||
// subscribe() connects once there is a subscription. read() and write() are plain fetches and don't need a session.
|
// subscribe() connects once there is a subscription. read() and write() are plain fetches and don't need a session.
|
||||||
if (this.subscriptions.size === 0) {
|
if (this.subscriptions.size === 0) {
|
||||||
@@ -52,14 +56,14 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
/**
|
/**
|
||||||
* Disconnects from the server
|
* Disconnects from the server
|
||||||
*/
|
*/
|
||||||
async disconnect() {
|
async disconnect(): Promise<void> {
|
||||||
await this.sseSession?.disconnect();
|
this.sseSession?.disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reconnects to the server
|
* Reconnects to the server
|
||||||
*/
|
*/
|
||||||
async reconnect() {
|
async reconnect(): Promise<void> {
|
||||||
// Close the current session. Its subscription list is fixed in the request body, so it can't be reused
|
// Close the current session. Its subscription list is fixed in the request body, so it can't be reused
|
||||||
this.sseSession?.close();
|
this.sseSession?.close();
|
||||||
this.sseSession = undefined;
|
this.sseSession = undefined;
|
||||||
@@ -72,13 +76,13 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
* Creates a new SSE session
|
* Creates a new SSE session
|
||||||
* @returns The SSE session
|
* @returns The SSE session
|
||||||
*/
|
*/
|
||||||
private createSession() {
|
private createSession(): SSESession {
|
||||||
// Build the request body
|
// Build the request body
|
||||||
const body = toExtendedJson({ resourceId: [ ...this.subscriptions ] });
|
const body = toExtendedJson({ resourceId: [ ...this.subscriptions ] });
|
||||||
|
|
||||||
// Create a new SSE session
|
// Create a new SSE session
|
||||||
const session = new SSESession(this.subscriptionUrl, {
|
const session = new SSESession(this.subscriptionUrl, {
|
||||||
onRequest: async (request) => {
|
onRequest: async (request): Promise<RequestInit> => {
|
||||||
// Get the path from the URL
|
// Get the path from the URL
|
||||||
const url = new URL(this.subscriptionUrl);
|
const url = new URL(this.subscriptionUrl);
|
||||||
const path = url.pathname;
|
const path = url.pathname;
|
||||||
@@ -93,7 +97,7 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
request.headers = {
|
request.headers = {
|
||||||
...request.headers,
|
...request.headers,
|
||||||
...authHeaders,
|
...authHeaders,
|
||||||
}
|
};
|
||||||
|
|
||||||
// Return the request with the authentication headers
|
// Return the request with the authentication headers
|
||||||
return request;
|
return request;
|
||||||
@@ -112,7 +116,7 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
session.on('disconnected', this.handleOnConnectionUpdated.bind(this, 'disconnected'));
|
session.on('disconnected', this.handleOnConnectionUpdated.bind(this, 'disconnected'));
|
||||||
|
|
||||||
// Create a listener to re-emit the messages
|
// Create a listener to re-emit the messages
|
||||||
session.on('message', (message) => {
|
session.on('message', (message): void => {
|
||||||
const parsedMessage = BaseSyncClient.resourceInstanceSchema.safeParse(fromExtendedJson(message.data));
|
const parsedMessage = BaseSyncClient.resourceInstanceSchema.safeParse(fromExtendedJson(message.data));
|
||||||
if (!parsedMessage.success) {
|
if (!parsedMessage.success) {
|
||||||
return;
|
return;
|
||||||
@@ -140,14 +144,17 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
*/
|
*/
|
||||||
async writeMany(resources: Record<string, PayloadType>): Promise<ResourcesRecord<PayloadType>> {
|
async writeMany(resources: Record<string, PayloadType>): Promise<ResourcesRecord<PayloadType>> {
|
||||||
// Sign the resource write requests
|
// Sign the resource write requests
|
||||||
const signedResources = Object.entries(resources).map(([resourceId, value]) => {
|
const signedResources = Object.entries(resources).map(([ resourceId, value ]) => {
|
||||||
const valueStr = toExtendedJson(value);
|
const valueStr = toExtendedJson(value);
|
||||||
const valueBytes = this.textEncoder.encode(valueStr);
|
const valueBytes = this.textEncoder.encode(valueStr);
|
||||||
|
|
||||||
return BaseSyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
|
return BaseSyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Send the resource write requests to the server
|
// Send the resource write requests to the server
|
||||||
const res = await this.sendRequest('/data/write', { resources: signedResources });
|
const res = await this.sendRequest('/data/write', {
|
||||||
|
resources: signedResources,
|
||||||
|
});
|
||||||
|
|
||||||
// If the response is not ok, throw an error
|
// If the response is not ok, throw an error
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -169,7 +176,9 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
*/
|
*/
|
||||||
async readMany(resourceIds: string[]): Promise<ResourcesRecord<PayloadType>> {
|
async readMany(resourceIds: string[]): Promise<ResourcesRecord<PayloadType>> {
|
||||||
// Send the resource read requests to the server
|
// Send the resource read requests to the server
|
||||||
const res = await this.sendRequest('/data/get', { resourceId: resourceIds });
|
const res = await this.sendRequest('/data/get', {
|
||||||
|
resourceId: resourceIds,
|
||||||
|
});
|
||||||
|
|
||||||
// If the response is not ok, throw an error
|
// If the response is not ok, throw an error
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -187,7 +196,7 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
* Destroy the current SSE Session, then re-create it with the additional resource ID in the subscription list
|
* Destroy the current SSE Session, then re-create it with the additional resource ID in the subscription list
|
||||||
* @param resourceId - The resource ID to add to the subscription list
|
* @param resourceId - The resource ID to add to the subscription list
|
||||||
*/
|
*/
|
||||||
async subscribe(resourceId: string) {
|
async subscribe(resourceId: string): Promise<void> {
|
||||||
this.subscriptions.add(resourceId);
|
this.subscriptions.add(resourceId);
|
||||||
|
|
||||||
this.emit('subscriptions-updated', this.subscriptions);
|
this.emit('subscriptions-updated', this.subscriptions);
|
||||||
@@ -197,13 +206,13 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
* Destroy the current SSE Session, then re-create it without the resource ID in the subscription list
|
* Destroy the current SSE Session, then re-create it without the resource ID in the subscription list
|
||||||
* @param resourceId - The resource ID to remove from the subscription list
|
* @param resourceId - The resource ID to remove from the subscription list
|
||||||
*/
|
*/
|
||||||
async unsubscribe(resourceId: string) {
|
async unsubscribe(resourceId: string): Promise<void> {
|
||||||
this.subscriptions.delete(resourceId);
|
this.subscriptions.delete(resourceId);
|
||||||
|
|
||||||
this.emit('subscriptions-updated', this.subscriptions);
|
this.emit('subscriptions-updated', this.subscriptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleOnConnectionUpdated(value: 'connected' | 'disconnected') {
|
async handleOnConnectionUpdated(value: 'connected' | 'disconnected'): Promise<void> {
|
||||||
this.emit('connection-updated', value);
|
this.emit('connection-updated', value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,7 +250,7 @@ export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType
|
|||||||
*/
|
*/
|
||||||
private async decodeResponse(response: Response): Promise<ResourcesRecord<PayloadType>> {
|
private async decodeResponse(response: Response): Promise<ResourcesRecord<PayloadType>> {
|
||||||
// Decode the response from Extended JSON
|
// Decode the response from Extended JSON
|
||||||
const text = fromExtendedJson(await response.text())
|
const text = fromExtendedJson(await response.text());
|
||||||
|
|
||||||
// Parse the response as a record of resources
|
// Parse the response as a record of resources
|
||||||
const resources = BaseSyncClient.resourcesResponseSchema.parse(text);
|
const resources = BaseSyncClient.resourcesResponseSchema.parse(text);
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
export * from './client.js';
|
export * from './client.ts';
|
||||||
|
|||||||
+41
-26
@@ -1,8 +1,8 @@
|
|||||||
import { ExponentialBackoff, fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
import { ExponentialBackoff, fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
||||||
import type { PrivateKey } from '@xo-cash/primitives';
|
import type { PrivateKey } from '@xo-cash/primitives';
|
||||||
|
|
||||||
import { WsMessageSchema, WsSuccessResponseSchema, WsErrorResponseSchema, type WsMessage } from './types.js';
|
import { WsMessageSchema, WsSuccessResponseSchema, WsErrorResponseSchema, type WsMessage } from './types.ts';
|
||||||
import { BaseSyncClient, type ResourcesRecord } from '../shared/base-client.js';
|
import { BaseSyncClient, type ResourcesRecord } from '../shared/base-client.ts';
|
||||||
|
|
||||||
/** A request sent over the sync server's WebSocket connection. */
|
/** A request sent over the sync server's WebSocket connection. */
|
||||||
type WsRequest = {
|
type WsRequest = {
|
||||||
@@ -18,6 +18,7 @@ type PendingRequest = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type WsClientOptions = {
|
export type WsClientOptions = {
|
||||||
|
|
||||||
/** Called for server-pushed events and uncorrelated server errors. */
|
/** Called for server-pushed events and uncorrelated server errors. */
|
||||||
onMessage: (message: WsMessage) => void;
|
onMessage: (message: WsMessage) => void;
|
||||||
|
|
||||||
@@ -56,19 +57,18 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
private webSocket: Promise<WebSocket> | undefined;
|
private webSocket: Promise<WebSocket> | undefined;
|
||||||
|
|
||||||
/** Retries a failed connection attempt forever (maxAttempts 0), waiting up to 30s between attempts. */
|
/** Retries a failed connection attempt forever (maxAttempts 0), waiting up to 30s between attempts. */
|
||||||
private readonly connectBackoff = new ExponentialBackoff({ maxAttempts: 0, maxDelay: 30_000 });
|
private readonly connectBackoff = new ExponentialBackoff({
|
||||||
|
maxAttempts: 0,
|
||||||
|
maxDelay: 30_000,
|
||||||
|
});
|
||||||
|
|
||||||
constructor(
|
constructor(url: string, privateKey: PrivateKey, options: Partial<WsClientOptions> = {}) {
|
||||||
url: string,
|
|
||||||
privateKey: PrivateKey,
|
|
||||||
options: Partial<WsClientOptions> = {},
|
|
||||||
) {
|
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this.url = url;
|
this.url = url;
|
||||||
this.privateKey = privateKey;
|
this.privateKey = privateKey;
|
||||||
this.messageListeners.add(options.onMessage ?? (() => {}));
|
this.messageListeners.add(options.onMessage ?? ((): void => {}));
|
||||||
this.errorListeners.add(options.onError ?? (() => {}));
|
this.errorListeners.add(options.onError ?? ((): void => {}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Connect, and keep reconnecting on drops until `disconnect()` is called. */
|
/** Connect, and keep reconnecting on drops until `disconnect()` is called. */
|
||||||
@@ -93,7 +93,10 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
|
|
||||||
// If the attempt is still retrying, it sees it is no longer current after its next handshake,
|
// If the attempt is still retrying, it sees it is no longer current after its next handshake,
|
||||||
// closes that socket and stops. Its rejection is handled here.
|
// closes that socket and stops. Its rejection is handled here.
|
||||||
attempt?.then((socket) => socket.close(), () => {});
|
attempt?.then(
|
||||||
|
(socket) => socket.close(),
|
||||||
|
() => {},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -112,7 +115,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
for (const resourceId of this.subscriptions) {
|
for (const resourceId of this.subscriptions) {
|
||||||
// A failure here means the attempt was stopped by disconnect() or the socket closed before the
|
// A failure here means the attempt was stopped by disconnect() or the socket closed before the
|
||||||
// frame was sent. A close starts a new attempt, which replays this again, so there is nothing to do.
|
// frame was sent. A close starts a new attempt, which replays this again, so there is nothing to do.
|
||||||
this.send('/data/subscribe', { resourceId: [resourceId] }).catch(() => {});
|
this.send('/data/subscribe', { resourceId: [ resourceId ] }).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.webSocket;
|
return this.webSocket;
|
||||||
@@ -125,7 +128,8 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
* It stops being current when `disconnect()` is called.
|
* It stops being current when `disconnect()` is called.
|
||||||
*/
|
*/
|
||||||
private openWebSocket(): Promise<WebSocket> {
|
private openWebSocket(): Promise<WebSocket> {
|
||||||
const attempt: Promise<WebSocket> = this.connectBackoff.run(async ({ stopRetries }) => {
|
const attempt: Promise<WebSocket> = this.connectBackoff.run(
|
||||||
|
async ({ stopRetries }) => {
|
||||||
// `attempt` is only read after this await: run() calls this function before `attempt` is assigned.
|
// `attempt` is only read after this await: run() calls this function before `attempt` is assigned.
|
||||||
const socket = await WsClient.waitForOpen(new WebSocket(WsClient.httpToWsUrl(this.url)));
|
const socket = await WsClient.waitForOpen(new WebSocket(WsClient.httpToWsUrl(this.url)));
|
||||||
|
|
||||||
@@ -136,30 +140,32 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
throw new Error('WebSocket client disconnected');
|
throw new Error('WebSocket client disconnected');
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.onmessage = (event) => this.handleMessage(String(event.data));
|
socket.onmessage = (event): void => this.handleMessage(String(event.data));
|
||||||
socket.onerror = () => this.emitError(new Error('WebSocket error'));
|
socket.onerror = (): void => this.emitError(new Error('WebSocket error'));
|
||||||
socket.onclose = () => {
|
socket.onclose = async (): Promise<void> => {
|
||||||
this.rejectPendingRequests(new Error('WebSocket connection closed'));
|
this.rejectPendingRequests(new Error('WebSocket connection closed'));
|
||||||
this.emit('connection-updated', 'disconnected');
|
this.emit('connection-updated', 'disconnected');
|
||||||
|
|
||||||
// Reconnect, unless disconnect() was called
|
// Reconnect, unless disconnect() was called
|
||||||
if (this.webSocket === attempt) {
|
if (this.webSocket === attempt) {
|
||||||
this.webSocket = undefined;
|
this.webSocket = undefined;
|
||||||
this.getWebSocket();
|
await this.getWebSocket();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
this.emit('connection-updated', 'connected');
|
this.emit('connection-updated', 'connected');
|
||||||
|
|
||||||
return socket;
|
return socket;
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
// Report failed handshakes, but not the error thrown above after disconnect()
|
// Report failed handshakes, but not the error thrown above after disconnect()
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
if (this.webSocket === attempt) {
|
if (this.webSocket === attempt) {
|
||||||
this.emitError(error);
|
this.emitError(error);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Nothing may be awaiting this attempt (e.g. a reconnect started by onclose), and it rejects if disconnect() stops it.
|
// Nothing may be awaiting this attempt (e.g. a reconnect started by onclose), and it rejects if disconnect() stops it.
|
||||||
// Mark the rejection as handled so it isn't reported as unhandled. Callers awaiting `attempt` still receive it.
|
// Mark the rejection as handled so it isn't reported as unhandled. Callers awaiting `attempt` still receive it.
|
||||||
@@ -170,7 +176,9 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
|
|
||||||
async readMany(resourceIds: string[]): Promise<ResourcesRecord<PayloadType>> {
|
async readMany(resourceIds: string[]): Promise<ResourcesRecord<PayloadType>> {
|
||||||
// Read the resources from the server
|
// Read the resources from the server
|
||||||
const response = await this.request('/data/get', { resourceId: resourceIds });
|
const response = await this.request('/data/get', {
|
||||||
|
resourceId: resourceIds,
|
||||||
|
});
|
||||||
|
|
||||||
// Parse the response as a record of resources
|
// Parse the response as a record of resources
|
||||||
const resources = BaseSyncClient.resourcesResponseSchema.parse(response);
|
const resources = BaseSyncClient.resourcesResponseSchema.parse(response);
|
||||||
@@ -183,14 +191,17 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
|
|
||||||
async writeMany(resourcesToWrite: Record<string, PayloadType>): Promise<ResourcesRecord<PayloadType>> {
|
async writeMany(resourcesToWrite: Record<string, PayloadType>): Promise<ResourcesRecord<PayloadType>> {
|
||||||
// Sign the resources
|
// Sign the resources
|
||||||
const signedResources = Object.entries(resourcesToWrite).map(([resourceId, value]) => {
|
const signedResources = Object.entries(resourcesToWrite).map(([ resourceId, value ]) => {
|
||||||
const valueStr = toExtendedJson(value);
|
const valueStr = toExtendedJson(value);
|
||||||
const valueBytes = this.textEncoder.encode(valueStr);
|
const valueBytes = this.textEncoder.encode(valueStr);
|
||||||
|
|
||||||
return BaseSyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
|
return BaseSyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Write the resources to the server
|
// Write the resources to the server
|
||||||
const response = await this.request('/data/write', { resources: signedResources });
|
const response = await this.request('/data/write', {
|
||||||
|
resources: signedResources,
|
||||||
|
});
|
||||||
|
|
||||||
// Parse the response as a record of resources
|
// Parse the response as a record of resources
|
||||||
const resources = BaseSyncClient.resourcesResponseSchema.parse(response);
|
const resources = BaseSyncClient.resourcesResponseSchema.parse(response);
|
||||||
@@ -211,7 +222,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
* @param resourceId - The resource ID to subscribe to
|
* @param resourceId - The resource ID to subscribe to
|
||||||
*/
|
*/
|
||||||
async subscribe(resourceId: string): Promise<void> {
|
async subscribe(resourceId: string): Promise<void> {
|
||||||
await this.send('/data/subscribe', { resourceId: [resourceId] });
|
await this.send('/data/subscribe', { resourceId: [ resourceId ] });
|
||||||
|
|
||||||
// Remembered only after sending: if send() started a new socket, getWebSocket() replays the
|
// Remembered only after sending: if send() started a new socket, getWebSocket() replays the
|
||||||
// existing subscriptions, and this one isn't among them yet. Sending it twice in the same
|
// existing subscriptions, and this one isn't among them yet. Sending it twice in the same
|
||||||
@@ -231,7 +242,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.request('/data/unsubscribe', { resourceId: [resourceId] });
|
await this.request('/data/unsubscribe', { resourceId: [ resourceId ] });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Send a request and wait for the response carrying the same ID. */
|
/** Send a request and wait for the response carrying the same ID. */
|
||||||
@@ -275,8 +286,8 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
*/
|
*/
|
||||||
private static waitForOpen(socket: WebSocket): Promise<WebSocket> {
|
private static waitForOpen(socket: WebSocket): Promise<WebSocket> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
socket.onopen = () => resolve(socket);
|
socket.onopen = (): void => resolve(socket);
|
||||||
socket.onerror = () => reject(new Error('WebSocket connection failed'));
|
socket.onerror = (): void => reject(new Error('WebSocket connection failed'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,6 +299,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
const { success, data: message } = WsMessageSchema.safeParse(fromExtendedJson(raw));
|
const { success, data: message } = WsMessageSchema.safeParse(fromExtendedJson(raw));
|
||||||
if (!success) {
|
if (!success) {
|
||||||
this.emitError(new Error('Invalid WebSocket message'));
|
this.emitError(new Error('Invalid WebSocket message'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,6 +317,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
const error = WsErrorResponseSchema.safeParse(message);
|
const error = WsErrorResponseSchema.safeParse(message);
|
||||||
if (error.success) {
|
if (error.success) {
|
||||||
this.emitError(new Error(`${error.data.error} (${error.data.statusCode})`));
|
this.emitError(new Error(`${error.data.error} (${error.data.statusCode})`));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -330,6 +343,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
if (message.type === 'error') {
|
if (message.type === 'error') {
|
||||||
const error = WsErrorResponseSchema.parse(message);
|
const error = WsErrorResponseSchema.parse(message);
|
||||||
pending.reject(new Error(`${error.error} (${error.statusCode})`));
|
pending.reject(new Error(`${error.error} (${error.statusCode})`));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,6 +354,7 @@ export class WsClient<PayloadType = unknown> extends BaseSyncClient<PayloadType>
|
|||||||
// If the response is not successful, reject the pending request
|
// If the response is not successful, reject the pending request
|
||||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||||
pending.reject(new Error(`Request failed (${response.statusCode})`));
|
pending.reject(new Error(`Request failed (${response.statusCode})`));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
export * from './client.js';
|
export * from './client.ts';
|
||||||
|
|||||||
+2
-2
@@ -19,7 +19,7 @@ export const WsErrorResponseSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type WsErrorResponse = z.infer<typeof WsErrorResponseSchema>;
|
export type WsErrorResponse = z.infer<typeof WsErrorResponseSchema>;
|
||||||
|
|
||||||
export const WsResponseSchema = z.discriminatedUnion('type', [WsSuccessResponseSchema, WsErrorResponseSchema]);
|
export const WsResponseSchema = z.discriminatedUnion('type', [ WsSuccessResponseSchema, WsErrorResponseSchema ]);
|
||||||
export type WsResponse = z.infer<typeof WsResponseSchema>;
|
export type WsResponse = z.infer<typeof WsResponseSchema>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,5 +36,5 @@ export const WsEventSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type WsEvent = z.infer<typeof WsEventSchema>;
|
export type WsEvent = z.infer<typeof WsEventSchema>;
|
||||||
|
|
||||||
export const WsMessageSchema = z.union([WsResponseSchema, WsEventSchema]);
|
export const WsMessageSchema = z.union([ WsResponseSchema, WsEventSchema ]);
|
||||||
export type WsMessage = z.infer<typeof WsMessageSchema>;
|
export type WsMessage = z.infer<typeof WsMessageSchema>;
|
||||||
|
|||||||
+7
-1
@@ -2,6 +2,7 @@
|
|||||||
// Visit https://aka.ms/tsconfig to read more about this file
|
// Visit https://aka.ms/tsconfig to read more about this file
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
// File Layout
|
// File Layout
|
||||||
|
"rootDir": "./source",
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
|
|
||||||
// Environment Settings
|
// Environment Settings
|
||||||
@@ -27,5 +28,10 @@
|
|||||||
"noUncheckedSideEffectImports": true,
|
"noUncheckedSideEffectImports": true,
|
||||||
"moduleDetection": "force",
|
"moduleDetection": "force",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
}
|
|
||||||
|
// GP
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"rewriteRelativeImportExtensions": true
|
||||||
|
},
|
||||||
|
"exclude": ["demo/**"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user