libshv-js 3.16.1 → 3.17.0

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/src/json.ts DELETED
@@ -1,136 +0,0 @@
1
- import {UnpackContext} from './cpcontext';
2
- import {CponReader, stringifyDate} from './cpon';
3
- import {Decimal, Double, isIMap, isShvMap, makeIMap, makeMap, makeMetaMap, RpcValueWithMetaData, UInt, type RpcValue} from './rpcvalue';
4
-
5
- const decodeMap = (x: object) => makeMap(Object.fromEntries(Object.entries(x).map(([key, value]) => [key, decodeValueJson(value)])));
6
-
7
- const decodeValueJson = (x: unknown): RpcValue => {
8
- switch (true) {
9
- case Array.isArray(x): {
10
- const list = x as unknown[];
11
- const handleType = (typeName: unknown, typeValue: unknown) => {
12
- switch (true) {
13
- case typeName === 'Blob': {
14
- if (typeof typeValue !== 'string' || typeValue.length % 2 !== 0) {
15
- throw new TypeError(`Invalid JSON-encoded Blob: '${JSON.stringify(typeValue)}'`);
16
- }
17
-
18
- const buffer = new ArrayBuffer(typeValue.length / 2);
19
- const array = new Uint8Array(buffer);
20
-
21
- // I can assume even length because of the previous check.
22
- for (let i = 0; i < typeValue.length / 2; i++) {
23
- array[i] = Number.parseInt(typeValue.slice(i * 2, (i * 2) + 2), 16);
24
- }
25
-
26
- return buffer;
27
- }
28
-
29
- case typeName === 'IMap':
30
- if (typeof typeValue !== 'object' || typeValue === null) {
31
- throw new TypeError(`Invalid JSON-encoded IMap: '${JSON.stringify(typeValue)}'`);
32
- }
33
-
34
- if (Object.keys(typeValue).some(key => !/^-?\d+$/.test(key))) {
35
- throw new TypeError(`Invalid JSON-encoded IMap (non-Int key): '${JSON.stringify(typeValue)}'`);
36
- }
37
-
38
- return makeIMap(decodeMap(typeValue));
39
- case typeName === 'DateTime':
40
- if (typeof typeValue !== 'string') {
41
- throw new TypeError(`Invalid JSON-encoded DateTime: '${JSON.stringify(typeValue)}'`);
42
- }
43
-
44
- // Kinda lame that I'm encoding the datetime string, but this is the easiest way right now.
45
- return new CponReader(new UnpackContext(new TextEncoder().encode(typeValue).buffer)).readDateTimeInner();
46
- default:
47
- throw new TypeError(`Invalid JSON-encoded type name: '${JSON.stringify(typeName)}'`);
48
- }
49
- };
50
-
51
- switch (true) {
52
- case list.length === 3 && list[0] === JSON_TAG_TYPE:
53
- return handleType(list[1], list[2]);
54
- case list.length === 3 && list[0] === JSON_TAG_META:
55
- case list.length === 5 && list[0] === JSON_TAG_META && list[2] === JSON_TAG_TYPE: {
56
- if (typeof list[1] !== 'object' || list[1] === null) {
57
- throw new TypeError(`Invalid JSON-encoded MetaData: '${JSON.stringify(list[1])}'`);
58
- }
59
-
60
- const value = (() => {
61
- if (list.length === 3) {
62
- const decoded = decodeValueJson(list[2]);
63
- if (decoded instanceof RpcValueWithMetaData) {
64
- throw new TypeError('Logic error: got RpcValueWithMetaData as the value in JSON-encoded RpcValueWithMetaData, please report this bug to the maintainer.');
65
- }
66
-
67
- return decoded;
68
- }
69
-
70
- return handleType(list[3], list[4]);
71
- })();
72
-
73
- return new RpcValueWithMetaData(makeMetaMap(decodeMap(list[1])), value);
74
- }
75
-
76
- default:
77
- return list.map(value => decodeValueJson(value));
78
- }
79
- }
80
-
81
- case x === null:
82
- return undefined;
83
- case typeof x === 'object':
84
- return decodeMap(x);
85
- case typeof x === 'number':
86
- case typeof x === 'boolean':
87
- case typeof x === 'string':
88
- return x;
89
- default:
90
- throw new Error(`Unknown JSON-encoded value: ${JSON.stringify(x)}`);
91
- }
92
- };
93
-
94
- export const fromJson = (str: string): RpcValue | Error => decodeValueJson(JSON.parse(str));
95
-
96
- const JSON_TAG_META = '!shvMeta';
97
- const JSON_TAG_TYPE = '!shvType';
98
-
99
- const encodeValueJson = (x: RpcValue): unknown => {
100
- switch (true) {
101
- case x instanceof RpcValueWithMetaData: {
102
- const res = [JSON_TAG_META, encodeValueJson(makeMap(x.meta))] as const;
103
- const encoded = encodeValueJson(x.value);
104
- if (Array.isArray(encoded) && encoded[0] === JSON_TAG_TYPE) {
105
- return [...res, ...encoded as unknown[]];
106
- }
107
-
108
- return [...res, encoded];
109
- }
110
-
111
- case Array.isArray(x):
112
- return x.map(value => encodeValueJson(value));
113
- case isShvMap(x): {
114
- const map = x as Record<string, RpcValue>;
115
- return Object.fromEntries(Object.entries(map).map(([key, value]) => [key, encodeValueJson(value)] as const));
116
- }
117
-
118
- case isIMap(x):
119
- return [JSON_TAG_TYPE, 'IMap', encodeValueJson(makeMap(x))];
120
- case x instanceof ArrayBuffer:
121
- return [JSON_TAG_TYPE, 'Blob', new Uint8Array(x).reduce((acc, v) => acc + v.toString(16).padStart(2, '0'), '')];
122
- case x instanceof Date:
123
- return [JSON_TAG_TYPE, 'DateTime', stringifyDate(x)];
124
- case x === undefined:
125
- // eslint-disable-next-line unicorn/no-null
126
- return null;
127
- case x instanceof Decimal:
128
- case x instanceof UInt:
129
- case x instanceof Double:
130
- throw new TypeError('Decimal/Double/UInt not supported in JSON');
131
- default:
132
- return x;
133
- }
134
- };
135
-
136
- export const toJson = (value: RpcValue): string | Error => JSON.stringify(encodeValueJson(value));
package/src/rpcmessage.ts DELETED
@@ -1,91 +0,0 @@
1
- import * as z from './zod';
2
-
3
- export const RPC_MESSAGE_REQUEST_ID = 8;
4
- export const RPC_MESSAGE_SHV_PATH = 9;
5
- export const RPC_MESSAGE_METHOD = 10;
6
- export const RPC_MESSAGE_CALLER_IDS = 11;
7
- export const RPC_MESSAGE_ACCESS_LEVEL = 17;
8
-
9
- export const RPC_MESSAGE_PARAMS = 1;
10
- export const RPC_MESSAGE_RESULT = 2;
11
- export const RPC_MESSAGE_ERROR = 3;
12
- export const RPC_MESSAGE_DELAY = 4;
13
- export const RPC_MESSAGE_ABORT = 5;
14
-
15
- export const ERROR_CODE = 1;
16
- export const ERROR_MESSAGE = 2;
17
- export const ERROR_DATA = 3;
18
-
19
- enum ErrorCode {
20
- InvalidRequest = 1,
21
- MethodNotFound = 2,
22
- InvalidParams = 3,
23
- InternalError = 4,
24
- ParseError = 5,
25
- MethodCallTimeout = 6,
26
- MethodCallCancelled = 7,
27
- MethodCallException = 8,
28
- Unknown = 9,
29
- LoginRequired = 10,
30
- UserIDRequired = 11,
31
- NotImplemented = 12,
32
- }
33
-
34
- const ErrorMapZod = z.imap({
35
- [ERROR_CODE]: z.number(),
36
- [ERROR_MESSAGE]: z.string().optional(),
37
- [ERROR_DATA]: z.rpcvalue().optional(),
38
- });
39
-
40
- export type ErrorMap = z.infer<typeof ErrorMapZod>;
41
-
42
- const RpcRequestMetaZod = z.metamap({
43
- [RPC_MESSAGE_CALLER_IDS]: z.int().or(z.array(z.int())).optional(),
44
- [RPC_MESSAGE_REQUEST_ID]: z.number(),
45
- [RPC_MESSAGE_METHOD]: z.string(),
46
- [RPC_MESSAGE_SHV_PATH]: z.string(),
47
- [RPC_MESSAGE_ACCESS_LEVEL]: z.int().gte(0).lte(63).optional(),
48
- });
49
-
50
- const RpcRequestValueZod = z.imap({
51
- [RPC_MESSAGE_PARAMS]: z.rpcvalue().optional(),
52
- }).or(z.imap({
53
- [RPC_MESSAGE_ABORT]: z.boolean(),
54
- }));
55
-
56
- const RpcResponseMetaZod = z.metamap({
57
- [RPC_MESSAGE_CALLER_IDS]: z.int().or(z.array(z.int())).optional(),
58
- [RPC_MESSAGE_REQUEST_ID]: z.number(),
59
- });
60
-
61
- const RpcResponseValueZod = z.imap({
62
- [RPC_MESSAGE_RESULT]: z.rpcvalue(),
63
- }).or(z.imap({
64
- [RPC_MESSAGE_ERROR]: ErrorMapZod,
65
- })).or(z.imap({
66
- [RPC_MESSAGE_DELAY]: z.double(),
67
- }));
68
-
69
- const RpcSignalMetaZod = z.metamap({
70
- [RPC_MESSAGE_SHV_PATH]: z.string(),
71
- [RPC_MESSAGE_METHOD]: z.string(),
72
- });
73
- const RpcSignalValueZod = z.imap({
74
- [RPC_MESSAGE_PARAMS]: z.rpcvalue().optional(),
75
- });
76
-
77
- const RpcRequestZod = z.withMeta(RpcRequestMetaZod, RpcRequestValueZod);
78
- const RpcResponseZod = z.withMeta(RpcResponseMetaZod, RpcResponseValueZod);
79
- const RpcSignalZod = z.withMeta(RpcSignalMetaZod, RpcSignalValueZod);
80
- const RpcMessageZod = z.union([RpcRequestZod, RpcResponseZod, RpcSignalZod]);
81
- export type RpcRequest = z.infer<typeof RpcRequestZod>;
82
- export type RpcResponse = z.infer<typeof RpcResponseZod>;
83
- export type RpcResponseValue = z.infer<typeof RpcResponseValueZod>;
84
- export type RpcSignal = z.infer<typeof RpcSignalZod>;
85
- export type RpcMessage = z.infer<typeof RpcMessageZod>;
86
-
87
- export const isSignal = (message: RpcMessage): message is RpcSignal => !(RPC_MESSAGE_REQUEST_ID in message.meta) && RPC_MESSAGE_METHOD in message.meta;
88
- export const isRequest = (message: RpcMessage): message is RpcRequest => RPC_MESSAGE_REQUEST_ID in message.meta && RPC_MESSAGE_METHOD in message.meta;
89
- export const isResponse = (message: RpcMessage): message is RpcResponse => RPC_MESSAGE_REQUEST_ID in message.meta && !(RPC_MESSAGE_METHOD in message.meta);
90
-
91
- export {RpcMessageZod, ErrorCode};
package/src/rpcvalue.ts DELETED
@@ -1,147 +0,0 @@
1
- class UInt<T extends number = number> {
2
- readonly value: T;
3
-
4
- constructor(u: T | UInt<T>) {
5
- if (u instanceof UInt) {
6
- this.value = u.value;
7
- return;
8
- }
9
-
10
- if (u < 0 || !Number.isInteger(u)) {
11
- throw new Error(`Invalid value '${u}' for UInt must a positive integral number`);
12
- }
13
-
14
- this.value = u;
15
- }
16
-
17
- [Symbol.toPrimitive]() {
18
- return this.value;
19
- }
20
-
21
- toString() {
22
- return `${this.value.toString()}`;
23
- }
24
- }
25
-
26
- class Double {
27
- readonly value: number;
28
-
29
- constructor(u: number) {
30
- this.value = u;
31
- }
32
- }
33
-
34
- class Decimal {
35
- mantisa: number;
36
- exponent: number;
37
-
38
- constructor(mantisa: number, exponent: number) {
39
- if (!Number.isInteger(exponent)) {
40
- throw new TypeError(`Decimal: exponent must be integral (${exponent})`);
41
- }
42
-
43
- this.mantisa = mantisa;
44
- this.exponent = exponent;
45
- }
46
- }
47
-
48
- export type Null = undefined;
49
- export type Bool = boolean;
50
- export type Blob = ArrayBuffer;
51
- export type ShvString = string;
52
- export type DateTime = Date & {utc_offset?: number};
53
- const withOffset = (date: Date, utcOffset?: number) => {
54
- const clonedDate: DateTime = new Date(date);
55
- clonedDate.utc_offset = utcOffset;
56
- return clonedDate;
57
- };
58
-
59
- export type List = RpcValue[];
60
-
61
- const shvMapType = Symbol('shvMapType');
62
-
63
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I can't get rid of this yet
64
- type IMap<T extends Record<number, RpcValue> = Record<number, any>> = {
65
- [Key in keyof T]: T[Key];
66
- } & {
67
- [shvMapType]: 'imap';
68
- };
69
-
70
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I can't get rid of this yet
71
- type ShvMap<T extends Record<string, RpcValue> = Record<string, any>> = {
72
- [Key in keyof T]: T[Key];
73
- } & {
74
- [shvMapType]: 'map';
75
- };
76
-
77
- export type Int = number;
78
-
79
- export type RpcValueType =
80
- Null |
81
- Bool |
82
- Int |
83
- UInt |
84
- Double |
85
- Decimal |
86
- Blob |
87
- ShvString |
88
- DateTime |
89
- List |
90
- ShvMap |
91
- IMap;
92
-
93
- type MetaMap<T extends Record<string | number, RpcValue> = Record<string | number, RpcValue>> = {
94
- [Key in keyof T]: T[Key];
95
- } & {
96
- [shvMapType]: 'metamap';
97
- };
98
-
99
- const isShvMap = (x: unknown): x is ShvMap => typeof x === 'object' && (x as ShvMap)[shvMapType] === 'map';
100
-
101
- const isIMap = (x: unknown): x is IMap => typeof x === 'object' && (x as IMap)[shvMapType] === 'imap';
102
-
103
- const isMetaMap = (x: unknown): x is IMap => typeof x === 'object' && (x as MetaMap)[shvMapType] === 'metamap';
104
-
105
- export const typeName = (x: unknown): string => {
106
- switch (true) {
107
- case x === undefined: return 'Null';
108
- case typeof x === 'boolean': return 'Bool';
109
- case typeof x === 'string': return 'String';
110
- case x instanceof ArrayBuffer: return 'Blob';
111
- case x instanceof UInt: return 'UInt';
112
- case typeof x === 'number': return 'Int';
113
- case x instanceof Double: return 'Double';
114
- case x instanceof Decimal: return 'Decimal';
115
- case Array.isArray(x): return 'List';
116
- case x instanceof Date: return 'Date';
117
- case isShvMap(x): return 'ShvMap';
118
- case isIMap(x): return 'IMap';
119
- case isMetaMap(x): return 'MetaMap';
120
- default: return '<unknown type>';
121
- }
122
- };
123
-
124
- const makeMetaMap = <T extends Record<string | number, RpcValue> = Record<string | number, RpcValue>, U extends Record<number, RpcValue> = Omit<T, typeof shvMapType>>(x: U = {} as U): MetaMap<U> => ({
125
- ...x,
126
- [shvMapType]: 'metamap',
127
- });
128
-
129
- const makeIMap = <T extends Record<number, RpcValue> = Record<number, RpcValue>, U extends Record<number, RpcValue> = Omit<T, typeof shvMapType>>(x: U = {} as U): IMap<U> => ({
130
- ...x,
131
- [shvMapType]: 'imap',
132
- });
133
-
134
- const makeMap = <T extends Record<string, RpcValue> = Record<string, RpcValue>, U extends Record<string, RpcValue> = Omit<T, typeof shvMapType>>(x: U = {} as U): ShvMap<U> => ({
135
- ...x,
136
- [shvMapType]: 'map',
137
- });
138
-
139
- class RpcValueWithMetaData<MetaSchema extends MetaMap = MetaMap, ValueSchema extends RpcValueType = RpcValueType> {
140
- constructor(public meta: MetaSchema, public value: ValueSchema) {
141
- /* nothing */
142
- }
143
- }
144
-
145
- export type RpcValue = RpcValueType | RpcValueWithMetaData;
146
-
147
- export {shvMapType, Decimal, Double, type IMap, type MetaMap, RpcValueWithMetaData, type ShvMap, UInt, withOffset, makeMap, makeIMap, makeMetaMap, isIMap, isMetaMap, isShvMap};