@arpabet/vrpc 0.2.1 → 0.4.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/README.md CHANGED
@@ -21,7 +21,7 @@ client.addFunction("notify", (args) => null); // server calls YOU
21
21
  | Option | Default | Meaning |
22
22
  |---|---|---|
23
23
  | `url` | — | `ws://` / `wss://` endpoint |
24
- | `codec` | `"msgpack"` | `"msgpack"` works with every server; `"json"` needs a JSON-codec server (negotiated via the `vrpc.json` subprotocol) |
24
+ | `codec` | `"msgpack"` | `"msgpack"` or `"json"`. The client offers the codec's WebSocket subprotocol (`vrpc.msgpack`, `vrpc.json`), as the Go client does, and the server must echo it: any value-rpc server from v1.5.3 on. A codec object with empty `subprotocols` offers nothing |
25
25
  | `auth` | — | credential (or async factory) for the handshake `auth` field |
26
26
  | `timeoutMs` | `5000` | default unary timeout, sent as the request SLA |
27
27
  | `connectTimeoutMs` | `10000` | dial + handshake bound |
@@ -50,14 +50,22 @@ with `valuerpc.CodeOf`.
50
50
 
51
51
  ## Value model
52
52
 
53
- `null | boolean | number | bigint | string | Uint8Array | Value[] | {…} |
54
- VrpcDouble | VrpcDecimal | VrpcExt`
53
+ `null | boolean | number | bigint | string | Uint8Array | Date | Value[] | {…} |
54
+ VrpcDouble | VrpcBigInt | VrpcDecimal | VrpcTimestamp | VrpcExt`
55
55
 
56
56
  - Integer `number`s encode as value LONG; beyond ±2^53 pass a `bigint`
57
- (exact int64 over msgpack). `double(x)` forces a DOUBLE encoding.
57
+ (exact int64 over msgpack, BigInt beyond that). `double(x)` forces a DOUBLE
58
+ encoding and `bigInt(x)` a BIGINT one.
58
59
  - `Uint8Array` is value RAW bytes.
59
60
  - Maps are plain objects; keys encode sorted (canonical frames).
60
61
  - `VrpcDecimal` (`decimal("1.045")`) and `VrpcExt` round-trip over msgpack.
62
+ - A `Date` encodes as value's TIMESTAMP (msgpack's timestamp extension, the
63
+ instant a Go `time.Time` field holds). Timestamps decode to `VrpcTimestamp`
64
+ (`timestamp(seconds, nanos)`), which keeps nanoseconds; `toDate()` converts
65
+ when milliseconds are enough.
66
+
67
+ The msgpack bytes are value's canonical form: the conformance vectors of
68
+ `go.arpabet.com/value` (`test/canonical.json`) run against this codec.
61
69
 
62
70
  ## Streams & flow control
63
71
 
package/dist/index.d.ts CHANGED
@@ -7,15 +7,16 @@
7
7
  * | BOOL | boolean |
8
8
  * | NUMBER/LONG | number (safe integers) or bigint |
9
9
  * | NUMBER/DOUBLE | number (or VrpcDouble to force) |
10
- * | NUMBER/BIGINT | bigint beyond int64 |
10
+ * | NUMBER/BIGINT | bigint beyond int64 (or VrpcBigInt) |
11
11
  * | NUMBER/DECIMAL | VrpcDecimal |
12
12
  * | STRING/UTF8 | string |
13
13
  * | STRING/RAW | Uint8Array |
14
+ * | TIMESTAMP | VrpcTimestamp (Date encodes as one) |
14
15
  * | LIST | Array |
15
16
  * | MAP | plain object (string keys) |
16
17
  * | UNKNOWN (ext) | VrpcExt |
17
18
  */
18
- type Value = null | boolean | number | bigint | string | Uint8Array | VrpcDouble | VrpcDecimal | VrpcExt | Value[] | {
19
+ type Value = null | boolean | number | bigint | string | Uint8Array | Date | VrpcDouble | VrpcBigInt | VrpcDecimal | VrpcTimestamp | VrpcExt | Value[] | {
19
20
  [key: string]: Value;
20
21
  };
21
22
  /** A string-keyed map value (the envelope shape). */
@@ -35,11 +36,29 @@ declare class VrpcDouble {
35
36
  }
36
37
  /** Convenience constructor for {@link VrpcDouble}. */
37
38
  declare function double(value: number): VrpcDouble;
39
+ /**
40
+ * Forces an integer to encode as value's NUMBER/BIGINT kind (ext type 1) even
41
+ * when it fits int64. A bare `bigint` within int64 encodes as LONG, which is
42
+ * what a peer usually wants; use `bigInt(5n)` when the peer's handler verifies
43
+ * a BIGINT argument or when the bytes must match a value built with
44
+ * `value.BigInt` in Go. Decoding never produces it: a BIGINT comes back as a
45
+ * `bigint`.
46
+ */
47
+ declare class VrpcBigInt {
48
+ readonly value: bigint;
49
+ constructor(value: bigint);
50
+ valueOf(): bigint;
51
+ toString(): string;
52
+ }
53
+ /** Convenience constructor for {@link VrpcBigInt}. */
54
+ declare function bigInt(value: bigint | number | string): VrpcBigInt;
38
55
  /**
39
56
  * An arbitrary-precision decimal: `coefficient * 10^exponent`, mirroring the
40
- * shopspring/decimal representation used by value's NUMBER/DECIMAL kind.
41
- * Round-trips through the msgpack codec (ext tag 2). The JSON codec cannot
42
- * represent it (matching the Go-side asymmetry) and rejects it on encode.
57
+ * shopspring/decimal representation used by value's NUMBER/DECIMAL kind. On
58
+ * the wire (ext type 2) it is a 4-byte scale, the negated exponent, followed
59
+ * by the two's-complement coefficient. Round-trips through the msgpack codec.
60
+ * The JSON codec cannot represent it (matching the Go-side asymmetry) and
61
+ * rejects it on encode.
43
62
  */
44
63
  declare class VrpcDecimal {
45
64
  readonly coefficient: bigint;
@@ -53,6 +72,40 @@ declare class VrpcDecimal {
53
72
  }
54
73
  /** Convenience constructor for {@link VrpcDecimal} from a decimal string. */
55
74
  declare function decimal(s: string): VrpcDecimal;
75
+ /**
76
+ * An instant with nanosecond precision: value's TIMESTAMP kind, MessagePack's
77
+ * timestamp extension (type -1). `seconds` counts from the Unix epoch and
78
+ * `nanos` lies within that second, 0 ≤ nanos < 1e9. It has no zone.
79
+ *
80
+ * A `Date` encodes as a timestamp too (whole milliseconds). The decoder always
81
+ * yields a VrpcTimestamp, which keeps every nanosecond; `toDate()` converts
82
+ * when millisecond precision is enough, and `exactAsDate()` tells whether
83
+ * that conversion loses anything.
84
+ */
85
+ declare class VrpcTimestamp {
86
+ readonly seconds: bigint;
87
+ readonly nanos: number;
88
+ constructor(seconds: bigint, nanos: number);
89
+ /** The instant a Date denotes, at millisecond precision. */
90
+ static fromDate(d: Date): VrpcTimestamp;
91
+ /**
92
+ * Parses RFC 3339 text such as "2026-10-30T07:28:39.075Z" or
93
+ * "2026-10-30T09:28:39+02:00", with up to nine fraction digits.
94
+ */
95
+ static fromString(s: string): VrpcTimestamp;
96
+ /** True when a Date holds this instant exactly: whole milliseconds within Date's range. */
97
+ exactAsDate(): boolean;
98
+ /** The instant as a Date, truncated to whole milliseconds. */
99
+ toDate(): Date;
100
+ /**
101
+ * RFC 3339 in UTC with the fraction trimmed of trailing zeros, the text Go's
102
+ * value renders: "2026-10-30T07:28:39.075Z", "2026-10-30T07:28:39Z".
103
+ */
104
+ toString(): string;
105
+ equals(other: VrpcTimestamp): boolean;
106
+ }
107
+ /** Convenience constructor for {@link VrpcTimestamp}. */
108
+ declare function timestamp(seconds: bigint | number, nanos?: number): VrpcTimestamp;
56
109
  /**
57
110
  * An opaque msgpack extension value (value kind UNKNOWN): the ext tag plus its
58
111
  * payload bytes. Preserved through both codecs so unrecognized extensions
@@ -68,25 +121,54 @@ declare class VrpcExt {
68
121
 
69
122
  /**
70
123
  * MessagePack codec producing the canonical byte form of go.arpabet.com/value
71
- * (see its CANONICAL.md): minimal integer family, doubles always float64,
72
- * str/bin distinct, map keys sorted by UTF-8 byte order, BIGINT as ext tag 1
73
- * (big.Int gob framing), DECIMAL as ext tag 2 (shopspring framing). Equal
74
- * values therefore produce byte-identical frames on both sides of the wire.
124
+ * (see its CANONICAL.md and testdata/canonical.json): minimal integer family,
125
+ * doubles always float64, str/bin distinct, map keys sorted by UTF-8 byte
126
+ * order, BIGINT as ext type 1 (minimal two's complement), DECIMAL as ext type
127
+ * 2 (4-byte scale plus two's-complement unscaled integer), TIMESTAMP as
128
+ * MessagePack's ext type -1 in its smallest form. Equal values therefore
129
+ * produce byte-identical frames on both sides of the wire.
75
130
  */
76
131
 
132
+ declare const BIGINT_EXT_TAG = 1;
133
+ declare const DECIMAL_EXT_TAG = 2;
134
+ /** MessagePack's timestamp extension, type -1, as the byte on the wire. */
135
+ declare const TIMESTAMP_EXT_TAG = 255;
77
136
  /** Decode limits mirroring value's limits.go defaults. */
78
137
  interface DecodeLimits {
79
138
  maxDepth: number;
80
139
  maxCollectionLen: number;
81
140
  maxByteLen: number;
141
+ /** Largest absolute decimal scale accepted; value's MaxDecimalExponent. 0 disables the check. */
142
+ maxDecimalExponent?: number;
82
143
  }
83
144
  declare const DEFAULT_LIMITS: DecodeLimits;
145
+ /**
146
+ * The minimal two's-complement big-endian encoding of an integer: at least one
147
+ * byte, the sign in the top bit (java.math.BigInteger.toByteArray()). 0 is 00,
148
+ * 127 is 7f, 128 is 0080, -1 is ff, -128 is 80, -129 is ff7f.
149
+ */
150
+ declare function twosComplementEncode(v: bigint): Uint8Array;
151
+ /** Decodes a two's-complement big-endian integer of any length of at least one byte. */
152
+ declare function twosComplementDecode(data: Uint8Array): bigint;
153
+ /**
154
+ * The payload of a MessagePack timestamp in its smallest form: 32-bit when the
155
+ * seconds fit an unsigned 32-bit integer and there are no nanoseconds, 64-bit
156
+ * (30 bits of nanoseconds above 34 bits of seconds) up to 2^34 seconds, 96-bit
157
+ * (32-bit nanoseconds then 64-bit signed seconds) otherwise.
158
+ */
159
+ declare function timestampPayload(seconds: bigint, nanos: number): Uint8Array;
84
160
  /** Encodes a single value in value's canonical MessagePack form. */
85
161
  declare function msgpackEncode(v: Value): Uint8Array;
86
162
  /** Decodes one value; throws on malformed, truncated, or oversized input. */
87
163
  declare function msgpackDecode(data: Uint8Array, limits?: DecodeLimits): Value;
88
164
 
89
165
  type CodecName = "msgpack" | "json";
166
+ /**
167
+ * The WebSocket subprotocol tokens of the wire codecs, valuerpc's
168
+ * SubprotocolMsgpack and SubprotocolJson.
169
+ */
170
+ declare const SUBPROTOCOL_MSGPACK = "vrpc.msgpack";
171
+ declare const SUBPROTOCOL_JSON = "vrpc.json";
90
172
  /**
91
173
  * The wire codec seam (WEB.md §3.3): one envelope per WebSocket frame,
92
174
  * msgpack in binary frames, JSON in text frames.
@@ -94,11 +176,13 @@ type CodecName = "msgpack" | "json";
94
176
  interface WireCodec {
95
177
  readonly name: CodecName;
96
178
  /**
97
- * Subprotocol offered on dial. msgpack offers none: "no subprotocol" IS the
98
- * msgpack negotiation, and it keeps compatibility with servers that predate
99
- * codec negotiation. JSON offers "vrpc.json" and requires the server to echo
100
- * it (a server that does not support JSON fails the connect with a clear
101
- * error instead of choking on text frames).
179
+ * Subprotocols offered on dial, of which the server must echo one: the
180
+ * token of the codec, "vrpc.msgpack" or "vrpc.json", as the Go client
181
+ * offers the token of its codec. A server that predates codec negotiation
182
+ * (value-rpc before v1.5.3) echoes none, and the connect fails with a clear
183
+ * error instead of exchanging frames in a codec the two sides did not agree
184
+ * on. A codec with an empty list offers nothing and takes what the server
185
+ * serves a client that offers nothing, which is msgpack.
102
186
  */
103
187
  readonly subprotocols: string[];
104
188
  readonly textFrames: boolean;
@@ -255,9 +339,12 @@ interface ClientOptions {
255
339
  /** WebSocket endpoint, e.g. "wss://example.com/rpc". */
256
340
  url: string;
257
341
  /**
258
- * Wire codec. "msgpack" (default) speaks to every value-rpc server —
259
- * binary frames, no subprotocol. "json" offers the "vrpc.json" subprotocol
260
- * and requires a server with JSON codec support (WEB.md phase 1).
342
+ * Wire codec. "msgpack" (default) is binary frames, "json" text frames. The
343
+ * client offers the codec's WebSocket subprotocol, "vrpc.msgpack" or
344
+ * "vrpc.json", as the Go client does, and requires the server to echo it:
345
+ * any value-rpc server from v1.5.3 on does for msgpack, and for JSON unless
346
+ * it was restricted to msgpack. Pass a codec object whose `subprotocols` is
347
+ * empty to offer nothing, which an older server needs.
261
348
  */
262
349
  codec?: CodecName | WireCodec;
263
350
  /**
@@ -461,6 +548,9 @@ declare function createClient(options: ClientOptions): VrpcClient;
461
548
  * - bigint -> encoded as a number when within ±2^53, else rejected
462
549
  * (the wire cannot carry it exactly; use msgpack)
463
550
  * - VrpcDecimal -> rejected on encode (does not round-trip through JSON)
551
+ * - Date, VrpcTimestamp -> RFC 3339 text in UTC ("2026-10-30T07:28:39.075Z"),
552
+ * the rendering of value's TIMESTAMP; it reads back as a
553
+ * string, because a string is never re-typed by content
464
554
  *
465
555
  * Known hazard inherited from the convention: a *string* that genuinely starts
466
556
  * with "base64," or "data:application/x-msgpack-ext;" is indistinguishable
@@ -574,4 +664,4 @@ interface TypedClient<A extends ApiShape> {
574
664
  /** Wraps a client with a compile-time-typed API surface (zero runtime cost). */
575
665
  declare function typedClient<A extends ApiShape>(client: VrpcClient): TypedClient<A>;
576
666
 
577
- export { type ApiShape, type CallOptions, type ChatHandler, type ClientEvents, type ClientOptions, Code, type CodecName, DEFAULT_LIMITS, type DecodeLimits, type DialOptions, type Dialect, type Dialer, type HandlerContext, HashChain, type IncomingStreamHandler, MessageType, type Metadata, type OutgoingStreamHandler, Protocol, type ReconnectOptions, type Status, type Transport, type TypedChat, type TypedClient, type TypedStream, type UnaryHandler, type Value, type ValueMap, type VrpcChat, VrpcClient, VrpcDecimal, VrpcDouble, VrpcError, VrpcExt, type VrpcStream, type WireCodec, codeName, codeOf, codecByName, createClient, decimal, double, jsonCodec, jsonDecode, jsonEncode, msgpackCodec, msgpackDecode, msgpackEncode, newDialect, typedClient, webSocketDialer };
667
+ export { type ApiShape, BIGINT_EXT_TAG, type CallOptions, type ChatHandler, type ClientEvents, type ClientOptions, Code, type CodecName, DECIMAL_EXT_TAG, DEFAULT_LIMITS, type DecodeLimits, type DialOptions, type Dialect, type Dialer, type HandlerContext, HashChain, type IncomingStreamHandler, MessageType, type Metadata, type OutgoingStreamHandler, Protocol, type ReconnectOptions, SUBPROTOCOL_JSON, SUBPROTOCOL_MSGPACK, type Status, TIMESTAMP_EXT_TAG, type Transport, type TypedChat, type TypedClient, type TypedStream, type UnaryHandler, type Value, type ValueMap, VrpcBigInt, type VrpcChat, VrpcClient, VrpcDecimal, VrpcDouble, VrpcError, VrpcExt, type VrpcStream, VrpcTimestamp, type WireCodec, bigInt, codeName, codeOf, codecByName, createClient, decimal, double, jsonCodec, jsonDecode, jsonEncode, msgpackCodec, msgpackDecode, msgpackEncode, newDialect, timestamp, timestampPayload, twosComplementDecode, twosComplementEncode, typedClient, webSocketDialer };
package/dist/index.js CHANGED
@@ -16,6 +16,21 @@ var VrpcDouble = class {
16
16
  function double(value) {
17
17
  return new VrpcDouble(value);
18
18
  }
19
+ var VrpcBigInt = class {
20
+ constructor(value) {
21
+ this.value = value;
22
+ }
23
+ value;
24
+ valueOf() {
25
+ return this.value;
26
+ }
27
+ toString() {
28
+ return this.value.toString();
29
+ }
30
+ };
31
+ function bigInt(value) {
32
+ return new VrpcBigInt(BigInt(value));
33
+ }
19
34
  var VrpcDecimal = class _VrpcDecimal {
20
35
  constructor(coefficient, exponent) {
21
36
  this.coefficient = coefficient;
@@ -64,6 +79,82 @@ var VrpcDecimal = class _VrpcDecimal {
64
79
  function decimal(s) {
65
80
  return VrpcDecimal.fromString(s);
66
81
  }
82
+ var NANOS_PER_SECOND = 1e9;
83
+ var NANOS_PER_MILLI = 1e6;
84
+ var MAX_DATE_SECONDS = 8640000000000n;
85
+ var VrpcTimestamp = class _VrpcTimestamp {
86
+ constructor(seconds, nanos) {
87
+ this.seconds = seconds;
88
+ this.nanos = nanos;
89
+ if (!Number.isInteger(nanos) || nanos < 0 || nanos >= NANOS_PER_SECOND) {
90
+ throw new RangeError(`vrpc: timestamp nanoseconds out of range: ${nanos}`);
91
+ }
92
+ if (seconds < INT64_MIN || seconds > INT64_MAX) {
93
+ throw new RangeError(`vrpc: timestamp seconds out of int64 range: ${seconds}`);
94
+ }
95
+ }
96
+ seconds;
97
+ nanos;
98
+ /** The instant a Date denotes, at millisecond precision. */
99
+ static fromDate(d) {
100
+ const ms = d.getTime();
101
+ if (!Number.isFinite(ms)) throw new RangeError("vrpc: invalid Date");
102
+ const sec = Math.floor(ms / 1e3);
103
+ return new _VrpcTimestamp(BigInt(sec), (ms - sec * 1e3) * NANOS_PER_MILLI);
104
+ }
105
+ /**
106
+ * Parses RFC 3339 text such as "2026-10-30T07:28:39.075Z" or
107
+ * "2026-10-30T09:28:39+02:00", with up to nine fraction digits.
108
+ */
109
+ static fromString(s) {
110
+ const m = /^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?([Zz]|[+-]\d{2}:\d{2})$/.exec(
111
+ s.trim()
112
+ );
113
+ if (!m) throw new SyntaxError(`vrpc: invalid RFC 3339 timestamp: ${JSON.stringify(s)}`);
114
+ const [, y, mo, d, h, mi, sec, frac = "", zone] = m;
115
+ const dt = /* @__PURE__ */ new Date(0);
116
+ dt.setUTCFullYear(Number(y), Number(mo) - 1, Number(d));
117
+ dt.setUTCHours(Number(h), Number(mi), Number(sec), 0);
118
+ const same = dt.getUTCFullYear() === Number(y) && dt.getUTCMonth() === Number(mo) - 1 && dt.getUTCDate() === Number(d) && dt.getUTCHours() === Number(h) && dt.getUTCMinutes() === Number(mi) && dt.getUTCSeconds() === Number(sec);
119
+ if (!same) throw new SyntaxError(`vrpc: invalid RFC 3339 timestamp: ${JSON.stringify(s)}`);
120
+ let seconds = BigInt(dt.getTime() / 1e3);
121
+ if (zone !== "Z" && zone !== "z") {
122
+ const sign = zone[0] === "-" ? -1n : 1n;
123
+ seconds -= sign * (BigInt(zone.slice(1, 3)) * 3600n + BigInt(zone.slice(4, 6)) * 60n);
124
+ }
125
+ return new _VrpcTimestamp(seconds, Number((frac + "000000000").slice(0, 9)));
126
+ }
127
+ /** True when a Date holds this instant exactly: whole milliseconds within Date's range. */
128
+ exactAsDate() {
129
+ return this.nanos % NANOS_PER_MILLI === 0 && this.seconds >= -MAX_DATE_SECONDS && this.seconds <= MAX_DATE_SECONDS;
130
+ }
131
+ /** The instant as a Date, truncated to whole milliseconds. */
132
+ toDate() {
133
+ if (this.seconds < -MAX_DATE_SECONDS || this.seconds > MAX_DATE_SECONDS) {
134
+ throw new RangeError(`vrpc: timestamp ${this.toString()} is outside the range of Date`);
135
+ }
136
+ return new Date(Number(this.seconds) * 1e3 + Math.floor(this.nanos / NANOS_PER_MILLI));
137
+ }
138
+ /**
139
+ * RFC 3339 in UTC with the fraction trimmed of trailing zeros, the text Go's
140
+ * value renders: "2026-10-30T07:28:39.075Z", "2026-10-30T07:28:39Z".
141
+ */
142
+ toString() {
143
+ if (this.seconds < -MAX_DATE_SECONDS || this.seconds > MAX_DATE_SECONDS) {
144
+ return `${this.seconds}s${this.nanos}ns`;
145
+ }
146
+ const iso = new Date(Number(this.seconds) * 1e3).toISOString();
147
+ let out = iso.slice(0, -5);
148
+ if (this.nanos !== 0) out += "." + String(this.nanos).padStart(9, "0").replace(/0+$/, "");
149
+ return out + "Z";
150
+ }
151
+ equals(other) {
152
+ return this.seconds === other.seconds && this.nanos === other.nanos;
153
+ }
154
+ };
155
+ function timestamp(seconds, nanos = 0) {
156
+ return new VrpcTimestamp(BigInt(seconds), nanos);
157
+ }
67
158
  var VrpcExt = class {
68
159
  constructor(tag, data) {
69
160
  this.tag = tag;
@@ -158,10 +249,12 @@ function bytesToHex(data) {
158
249
  // src/msgpack.ts
159
250
  var BIGINT_EXT_TAG = 1;
160
251
  var DECIMAL_EXT_TAG = 2;
252
+ var TIMESTAMP_EXT_TAG = 255;
161
253
  var DEFAULT_LIMITS = {
162
254
  maxDepth: 1e3,
163
255
  maxCollectionLen: 16777216,
164
- maxByteLen: 1073741824
256
+ maxByteLen: 1073741824,
257
+ maxDecimalExponent: 1048576
165
258
  };
166
259
  var Writer = class {
167
260
  buf = new Uint8Array(256);
@@ -311,39 +404,60 @@ function packExt(w, tag, data) {
311
404
  w.byte(tag);
312
405
  w.bytes(data);
313
406
  }
314
- function bigIntGobEncode(v) {
315
- const neg = v < 0n;
316
- let abs = neg ? -v : v;
317
- const mag = [];
318
- while (abs > 0n) {
319
- mag.unshift(Number(abs & 0xffn));
320
- abs >>= 8n;
321
- }
322
- const out = new Uint8Array(1 + mag.length);
323
- out[0] = 1 << 1 | (neg ? 1 : 0);
324
- out.set(mag, 1);
325
- return out;
407
+ function twosComplementEncode(v) {
408
+ const abs = v < 0n ? -v : v;
409
+ const bitLength = abs === 0n ? 0 : abs.toString(2).length;
410
+ const n = Math.floor((bitLength + 8) / 8);
411
+ let t = v < 0n ? v + (1n << BigInt(8 * n)) : v;
412
+ const out = new Uint8Array(n);
413
+ for (let i = n - 1; i >= 0; i--) {
414
+ out[i] = Number(t & 0xffn);
415
+ t >>= 8n;
416
+ }
417
+ let start = 0;
418
+ while (start < n - 1 && out[start] === 255 && (out[start + 1] & 128) !== 0) start++;
419
+ return start === 0 ? out : out.slice(start);
326
420
  }
327
- function bigIntGobDecode(data) {
328
- if (data.length === 0) throw new SyntaxError("vrpc: empty bigint payload");
329
- const first = data[0];
330
- if (first >> 1 !== 1) throw new SyntaxError(`vrpc: unsupported bigint gob version ${first >> 1}`);
331
- const neg = (first & 1) === 1;
421
+ function twosComplementDecode(data) {
422
+ if (data.length === 0) throw new SyntaxError("vrpc: empty big integer payload");
332
423
  let v = 0n;
333
- for (let i = 1; i < data.length; i++) v = v << 8n | BigInt(data[i]);
334
- return neg ? -v : v;
424
+ for (const b of data) v = v << 8n | BigInt(b);
425
+ if ((data[0] & 128) !== 0) v -= 1n << BigInt(8 * data.length);
426
+ return v;
335
427
  }
336
428
  function packBigInt(w, v) {
337
- packExt(w, BIGINT_EXT_TAG, bigIntGobEncode(v));
429
+ packExt(w, BIGINT_EXT_TAG, twosComplementEncode(v));
338
430
  }
339
431
  function packDecimal(w, v) {
340
- const coef = bigIntGobEncode(v.coefficient);
341
- const payload = new Uint8Array(4 + coef.length);
342
- const dv = new DataView(payload.buffer);
343
- dv.setInt32(0, v.exponent);
344
- payload.set(coef, 4);
432
+ const scale = Math.min(-v.exponent, 2147483647);
433
+ const unscaled = twosComplementEncode(v.coefficient);
434
+ const payload = new Uint8Array(4 + unscaled.length);
435
+ new DataView(payload.buffer).setInt32(0, scale);
436
+ payload.set(unscaled, 4);
345
437
  packExt(w, DECIMAL_EXT_TAG, payload);
346
438
  }
439
+ var SECONDS_34 = 1n << 34n;
440
+ var MAX_SECONDS_32 = 0xffffffffn;
441
+ function timestampPayload(seconds, nanos) {
442
+ if (nanos === 0 && seconds >= 0n && seconds <= MAX_SECONDS_32) {
443
+ const out2 = new Uint8Array(4);
444
+ new DataView(out2.buffer).setUint32(0, Number(seconds));
445
+ return out2;
446
+ }
447
+ if (seconds >= 0n && seconds < SECONDS_34) {
448
+ const out2 = new Uint8Array(8);
449
+ new DataView(out2.buffer).setBigUint64(0, BigInt(nanos) << 34n | seconds);
450
+ return out2;
451
+ }
452
+ const out = new Uint8Array(12);
453
+ const dv = new DataView(out.buffer);
454
+ dv.setUint32(0, nanos);
455
+ dv.setBigInt64(4, seconds);
456
+ return out;
457
+ }
458
+ function packTimestamp(w, t) {
459
+ packExt(w, TIMESTAMP_EXT_TAG, timestampPayload(t.seconds, t.nanos));
460
+ }
347
461
  function packValue(w, v) {
348
462
  if (v === null || v === void 0) {
349
463
  w.byte(192);
@@ -377,8 +491,14 @@ function packValue(w, v) {
377
491
  packBin(w, v);
378
492
  } else if (v instanceof VrpcDouble) {
379
493
  packDouble(w, v.value);
494
+ } else if (v instanceof VrpcBigInt) {
495
+ packBigInt(w, v.value);
380
496
  } else if (v instanceof VrpcDecimal) {
381
497
  packDecimal(w, v);
498
+ } else if (v instanceof Date) {
499
+ packTimestamp(w, VrpcTimestamp.fromDate(v));
500
+ } else if (v instanceof VrpcTimestamp) {
501
+ packTimestamp(w, v);
382
502
  } else if (v instanceof VrpcExt) {
383
503
  packExt(w, v.tag, v.data);
384
504
  } else if (Array.isArray(v)) {
@@ -485,16 +605,45 @@ var Reader = class {
485
605
  function normalizeInt(v) {
486
606
  return v >= -9007199254740991n && v <= 9007199254740991n ? Number(v) : v;
487
607
  }
488
- function decodeExt(tag, data) {
489
- if (tag === BIGINT_EXT_TAG) return bigIntGobDecode(data);
608
+ function decodeExt(tag, data, limits) {
609
+ if (tag === BIGINT_EXT_TAG) return twosComplementDecode(data);
490
610
  if (tag === DECIMAL_EXT_TAG) {
491
611
  if (data.length < 5) throw new SyntaxError("vrpc: truncated decimal payload");
492
- const dv = new DataView(data.buffer, data.byteOffset, data.byteLength);
493
- const exponent = dv.getInt32(0);
494
- return new VrpcDecimal(bigIntGobDecode(data.subarray(4)), exponent);
612
+ const scale = new DataView(data.buffer, data.byteOffset, data.byteLength).getInt32(0);
613
+ const limit = limits.maxDecimalExponent ?? 0;
614
+ if (limit > 0 && Math.abs(scale) > limit) {
615
+ throw new RangeError(`vrpc: decimal scale ${scale} exceeds limit ${limit}`);
616
+ }
617
+ return new VrpcDecimal(twosComplementDecode(data.subarray(4)), 0 - scale);
495
618
  }
619
+ if (tag === TIMESTAMP_EXT_TAG) return decodeTimestamp(data);
496
620
  return new VrpcExt(tag, data);
497
621
  }
622
+ function decodeTimestamp(data) {
623
+ const dv = new DataView(data.buffer, data.byteOffset, data.byteLength);
624
+ let seconds;
625
+ let nanos;
626
+ switch (data.length) {
627
+ case 4:
628
+ seconds = BigInt(dv.getUint32(0));
629
+ nanos = 0;
630
+ break;
631
+ case 8: {
632
+ const v = dv.getBigUint64(0);
633
+ nanos = Number(v >> 34n);
634
+ seconds = v & SECONDS_34 - 1n;
635
+ break;
636
+ }
637
+ case 12:
638
+ nanos = dv.getUint32(0);
639
+ seconds = dv.getBigInt64(4);
640
+ break;
641
+ default:
642
+ throw new SyntaxError(`vrpc: timestamp payload of ${data.length} bytes, want 4, 8 or 12`);
643
+ }
644
+ if (nanos >= 1e9) throw new SyntaxError(`vrpc: timestamp nanoseconds ${nanos} out of range`);
645
+ return new VrpcTimestamp(seconds, nanos);
646
+ }
498
647
  function readValue(r, depth) {
499
648
  if (depth > r.limits.maxDepth) throw new RangeError("vrpc: msgpack nesting too deep");
500
649
  const b = r.byte();
@@ -518,15 +667,15 @@ function readValue(r, depth) {
518
667
  return r.take(r.u32());
519
668
  case 199: {
520
669
  const n = r.u8();
521
- return decodeExt(r.byte(), r.take(n));
670
+ return decodeExt(r.byte(), r.take(n), r.limits);
522
671
  }
523
672
  case 200: {
524
673
  const n = r.u16();
525
- return decodeExt(r.byte(), r.take(n));
674
+ return decodeExt(r.byte(), r.take(n), r.limits);
526
675
  }
527
676
  case 201: {
528
677
  const n = r.u32();
529
- return decodeExt(r.byte(), r.take(n));
678
+ return decodeExt(r.byte(), r.take(n), r.limits);
530
679
  }
531
680
  case 202:
532
681
  return r.f32();
@@ -549,15 +698,15 @@ function readValue(r, depth) {
549
698
  case 211:
550
699
  return normalizeInt(r.i64());
551
700
  case 212:
552
- return decodeExt(r.byte(), r.take(1));
701
+ return decodeExt(r.byte(), r.take(1), r.limits);
553
702
  case 213:
554
- return decodeExt(r.byte(), r.take(2));
703
+ return decodeExt(r.byte(), r.take(2), r.limits);
555
704
  case 214:
556
- return decodeExt(r.byte(), r.take(4));
705
+ return decodeExt(r.byte(), r.take(4), r.limits);
557
706
  case 215:
558
- return decodeExt(r.byte(), r.take(8));
707
+ return decodeExt(r.byte(), r.take(8), r.limits);
559
708
  case 216:
560
- return decodeExt(r.byte(), r.take(16));
709
+ return decodeExt(r.byte(), r.take(16), r.limits);
561
710
  case 217:
562
711
  return utf8Decode(r.take(r.u8()));
563
712
  case 218:
@@ -638,6 +787,8 @@ function writeValue(out, v, depth) {
638
787
  out.push(JSON.stringify(BASE64_PREFIX + base64RawStdEncode(v)));
639
788
  } else if (v instanceof VrpcDouble) {
640
789
  writeNumber(out, v.value, true);
790
+ } else if (v instanceof VrpcBigInt) {
791
+ writeValue(out, v.value, depth);
641
792
  } else if (v instanceof VrpcExt) {
642
793
  const payload = new Uint8Array(1 + v.data.length);
643
794
  payload[0] = v.tag;
@@ -647,6 +798,10 @@ function writeValue(out, v, depth) {
647
798
  throw new TypeError(
648
799
  "vrpc: VrpcDecimal does not round-trip through the JSON codec; use msgpack or model it as a string"
649
800
  );
801
+ } else if (v instanceof Date) {
802
+ out.push(JSON.stringify(VrpcTimestamp.fromDate(v).toString()));
803
+ } else if (v instanceof VrpcTimestamp) {
804
+ out.push(JSON.stringify(v.toString()));
650
805
  } else if (Array.isArray(v)) {
651
806
  out.push("[");
652
807
  for (let i = 0; i < v.length; i++) {
@@ -732,6 +887,8 @@ function jsonDecode(text, limits = DEFAULT_LIMITS) {
732
887
  }
733
888
 
734
889
  // src/codec.ts
890
+ var SUBPROTOCOL_MSGPACK = "vrpc.msgpack";
891
+ var SUBPROTOCOL_JSON = "vrpc.json";
735
892
  function assertMap(v, codec) {
736
893
  if (v === null || typeof v !== "object" || Array.isArray(v) || v instanceof Uint8Array) {
737
894
  throw new SyntaxError(`vrpc: expected a ${codec} map envelope`);
@@ -741,7 +898,7 @@ function assertMap(v, codec) {
741
898
  function msgpackCodec(limits = DEFAULT_LIMITS) {
742
899
  return {
743
900
  name: "msgpack",
744
- subprotocols: [],
901
+ subprotocols: [SUBPROTOCOL_MSGPACK],
745
902
  textFrames: false,
746
903
  encode: (msg) => msgpackEncode(msg),
747
904
  decode: (data) => {
@@ -757,7 +914,7 @@ function msgpackCodec(limits = DEFAULT_LIMITS) {
757
914
  function jsonCodec(limits = DEFAULT_LIMITS) {
758
915
  return {
759
916
  name: "json",
760
- subprotocols: ["vrpc.json"],
917
+ subprotocols: [SUBPROTOCOL_JSON],
761
918
  textFrames: true,
762
919
  encode: (msg) => jsonEncode(msg),
763
920
  decode: (data) => {
@@ -1076,7 +1233,7 @@ var webSocketDialer = (opts) => {
1076
1233
  7 /* Unavailable */,
1077
1234
  `server did not accept subprotocol ${opts.subprotocols.join("/")} (got ${JSON.stringify(
1078
1235
  ws.protocol
1079
- )}); it likely predates JSON codec support \u2014 use codec: "msgpack"`
1236
+ )}); it predates codec negotiation (value-rpc before v1.5.3) or does not enable this codec`
1080
1237
  )
1081
1238
  );
1082
1239
  return;
@@ -2271,16 +2428,24 @@ function typedClient(client) {
2271
2428
  };
2272
2429
  }
2273
2430
  export {
2431
+ BIGINT_EXT_TAG,
2274
2432
  Code,
2433
+ DECIMAL_EXT_TAG,
2275
2434
  DEFAULT_LIMITS,
2276
2435
  HashChain,
2277
2436
  MessageType,
2278
2437
  Protocol,
2438
+ SUBPROTOCOL_JSON,
2439
+ SUBPROTOCOL_MSGPACK,
2440
+ TIMESTAMP_EXT_TAG,
2441
+ VrpcBigInt,
2279
2442
  VrpcClient,
2280
2443
  VrpcDecimal,
2281
2444
  VrpcDouble,
2282
2445
  VrpcError,
2283
2446
  VrpcExt,
2447
+ VrpcTimestamp,
2448
+ bigInt,
2284
2449
  codeName,
2285
2450
  codeOf,
2286
2451
  codecByName,
@@ -2294,6 +2459,10 @@ export {
2294
2459
  msgpackDecode,
2295
2460
  msgpackEncode,
2296
2461
  newDialect,
2462
+ timestamp,
2463
+ timestampPayload,
2464
+ twosComplementDecode,
2465
+ twosComplementEncode,
2297
2466
  typedClient,
2298
2467
  webSocketDialer
2299
2468
  };