@peridotvault/peridotbase-sdk 0.0.0-stage → 0.2.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/dist/auth.d.ts +33 -0
- package/dist/auth.js +72 -0
- package/dist/client.d.ts +1149 -0
- package/dist/client.js +6030 -0
- package/dist/ddl.d.ts +31 -0
- package/dist/ddl.js +28 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.js +187 -0
- package/dist/expr.d.ts +127 -0
- package/dist/expr.js +1177 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +28 -0
- package/dist/org-multisig.d.ts +29 -0
- package/dist/org-multisig.js +90 -0
- package/dist/pda.d.ts +95 -0
- package/dist/pda.js +327 -0
- package/dist/sql.d.ts +244 -0
- package/dist/sql.js +1523 -0
- package/dist/tooling.d.ts +68 -0
- package/dist/tooling.js +432 -0
- package/dist/v3.d.ts +357 -0
- package/dist/v3.js +1649 -0
- package/dist/values.d.ts +229 -0
- package/dist/values.js +1362 -0
- package/dist/verify.d.ts +37 -0
- package/dist/verify.js +210 -0
- package/idl/peridotbase_core.json +17404 -0
- package/package.json +43 -4
- package/README.md +0 -3
package/dist/values.js
ADDED
|
@@ -0,0 +1,1362 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.MICROS_PER_DAY = exports.SECONDS_PER_DAY = exports.MICROS_PER_HOUR = exports.MICROS_PER_MINUTE = exports.MICROS_PER_SECOND = exports.RANGE_SCALE_MASK = exports.RANGE_SCALE_SHIFT = exports.RANGE_UPPER_INC = exports.RANGE_LOWER_INC = exports.POSTING_V3_DOMAIN = exports.INDEX_ID_V3_DOMAIN = exports.UNIQUE_V3_DOMAIN = exports.PK_V3_DOMAIN = exports.ROLE_TO_ANCHOR = exports.TABLE_GUARD = exports.CONSTRAINT_KIND_TO_ANCHOR = exports.ANCHOR_TO_COLUMN_TYPE = exports.COLUMN_TYPE_TO_ANCHOR = exports.MAX_TEXT_LEN = exports.MAX_INLINE_TEXT_LEN = void 0;
|
|
7
|
+
exports.isOverflowValue = isOverflowValue;
|
|
8
|
+
exports.encodeGuardBits = encodeGuardBits;
|
|
9
|
+
exports.decodeGuardBits = decodeGuardBits;
|
|
10
|
+
exports.toBigInt = toBigInt;
|
|
11
|
+
exports.uuidToBytes = uuidToBytes;
|
|
12
|
+
exports.bytesToUuid = bytesToUuid;
|
|
13
|
+
exports.dateTextToDays = dateTextToDays;
|
|
14
|
+
exports.daysToDateText = daysToDateText;
|
|
15
|
+
exports.timestampTextToSeconds = timestampTextToSeconds;
|
|
16
|
+
exports.secondsToTimestampText = secondsToTimestampText;
|
|
17
|
+
exports.coerceValue = coerceValue;
|
|
18
|
+
exports.readI128LE = readI128LE;
|
|
19
|
+
exports.encodeTypedValue = encodeTypedValue;
|
|
20
|
+
exports.typedValueSize = typedValueSize;
|
|
21
|
+
exports.compositeIndexKeyV3 = compositeIndexKeyV3;
|
|
22
|
+
exports.canonicalTypedKeyV3 = canonicalTypedKeyV3;
|
|
23
|
+
exports.primaryKeyCanonicalV3 = primaryKeyCanonicalV3;
|
|
24
|
+
exports.decodeCanonicalTypedKeyV3 = decodeCanonicalTypedKeyV3;
|
|
25
|
+
exports.decodeCoveringPayload = decodeCoveringPayload;
|
|
26
|
+
exports.pkDigestV3 = pkDigestV3;
|
|
27
|
+
exports.uniqueDigestV3 = uniqueDigestV3;
|
|
28
|
+
exports.postingDigestV3 = postingDigestV3;
|
|
29
|
+
exports.toAnchorValue = toAnchorValue;
|
|
30
|
+
exports.fromAnchorValue = fromAnchorValue;
|
|
31
|
+
exports.rangeScale = rangeScale;
|
|
32
|
+
exports.displayValue = displayValue;
|
|
33
|
+
exports.formatMoney = formatMoney;
|
|
34
|
+
exports.intervalTotalMicros = intervalTotalMicros;
|
|
35
|
+
exports.parseInterval = parseInterval;
|
|
36
|
+
exports.formatInterval = formatInterval;
|
|
37
|
+
exports.civilFromDays = civilFromDays;
|
|
38
|
+
exports.daysFromCivil = daysFromCivil;
|
|
39
|
+
exports.addMonthsToDays = addMonthsToDays;
|
|
40
|
+
exports.dateAddInterval = dateAddInterval;
|
|
41
|
+
exports.timestampAddInterval = timestampAddInterval;
|
|
42
|
+
const bn_js_1 = __importDefault(require("bn.js"));
|
|
43
|
+
const crypto_1 = require("crypto");
|
|
44
|
+
/** Maximum byte length of an inline TEXT value (mirrors `MAX_INLINE_TEXT_LEN`). */
|
|
45
|
+
exports.MAX_INLINE_TEXT_LEN = 512;
|
|
46
|
+
/** Maximum byte length of a logical TEXT value (mirrors `MAX_TEXT_LEN`). */
|
|
47
|
+
exports.MAX_TEXT_LEN = 4 * 1024;
|
|
48
|
+
function isOverflowValue(value) {
|
|
49
|
+
return (typeof value === "object" &&
|
|
50
|
+
value !== null &&
|
|
51
|
+
!(value instanceof Uint8Array) &&
|
|
52
|
+
"ref" in value);
|
|
53
|
+
}
|
|
54
|
+
exports.COLUMN_TYPE_TO_ANCHOR = {
|
|
55
|
+
bool: { bool: {} },
|
|
56
|
+
address: { address: {} },
|
|
57
|
+
inet: { inet: {} },
|
|
58
|
+
cidr: { cidr: {} },
|
|
59
|
+
macaddr: { macAddr: {} },
|
|
60
|
+
bit: { bit: {} },
|
|
61
|
+
varbit: { varBit: {} },
|
|
62
|
+
range: { range: {} },
|
|
63
|
+
numrange: { numRange: {} },
|
|
64
|
+
tsrange: { tsRange: {} },
|
|
65
|
+
daterange: { dateRange: {} },
|
|
66
|
+
time: { time: {} },
|
|
67
|
+
i64: { i64: {} },
|
|
68
|
+
decimal: { decimal: {} },
|
|
69
|
+
text: { text: {} },
|
|
70
|
+
uuid: { uuid: {} },
|
|
71
|
+
date: { date: {} },
|
|
72
|
+
timestamp: { timestamp: {} },
|
|
73
|
+
interval: { interval: {} },
|
|
74
|
+
};
|
|
75
|
+
exports.ANCHOR_TO_COLUMN_TYPE = {
|
|
76
|
+
bool: "bool",
|
|
77
|
+
i64: "i64",
|
|
78
|
+
decimal: "decimal",
|
|
79
|
+
text: "text",
|
|
80
|
+
uuid: "uuid",
|
|
81
|
+
date: "date",
|
|
82
|
+
timestamp: "timestamp",
|
|
83
|
+
interval: "interval",
|
|
84
|
+
address: "address",
|
|
85
|
+
inet: "inet",
|
|
86
|
+
cidr: "cidr",
|
|
87
|
+
macaddr: "macaddr",
|
|
88
|
+
macAddr: "macaddr",
|
|
89
|
+
bit: "bit",
|
|
90
|
+
varbit: "varbit",
|
|
91
|
+
varBit: "varbit",
|
|
92
|
+
range: "range",
|
|
93
|
+
numRange: "numrange",
|
|
94
|
+
tsRange: "tsrange",
|
|
95
|
+
dateRange: "daterange",
|
|
96
|
+
time: "time",
|
|
97
|
+
};
|
|
98
|
+
exports.CONSTRAINT_KIND_TO_ANCHOR = {
|
|
99
|
+
notNull: { notNull: {} },
|
|
100
|
+
primaryKey: { primaryKey: {} },
|
|
101
|
+
unique: { unique: {} },
|
|
102
|
+
check: { check: {} },
|
|
103
|
+
appendOnly: { appendOnly: {} },
|
|
104
|
+
denyDelete: { denyDelete: {} },
|
|
105
|
+
denyUpdate: { denyUpdate: {} },
|
|
106
|
+
immutable: { immutable: {} },
|
|
107
|
+
generatedStored: { generatedStored: {} },
|
|
108
|
+
generatedVirtual: { generatedVirtual: {} },
|
|
109
|
+
compositePrimaryKey: { compositePrimaryKey: {} },
|
|
110
|
+
compositeIndex: { compositeIndex: {} },
|
|
111
|
+
coveringIndex: { coveringIndex: {} },
|
|
112
|
+
};
|
|
113
|
+
/** Guard bits as enforced on-chain by `set_table_guard`. */
|
|
114
|
+
exports.TABLE_GUARD = {
|
|
115
|
+
appendOnly: 0x01,
|
|
116
|
+
denyDelete: 0x02,
|
|
117
|
+
denyUpdate: 0x04,
|
|
118
|
+
immutable: 0x08,
|
|
119
|
+
freezePolicies: 0x10,
|
|
120
|
+
};
|
|
121
|
+
/** Encodes a guard object into the on-chain bitmask. */
|
|
122
|
+
function encodeGuardBits(guards) {
|
|
123
|
+
if (!guards)
|
|
124
|
+
return 0;
|
|
125
|
+
let bits = 0;
|
|
126
|
+
for (const [kind, enabled] of Object.entries(guards)) {
|
|
127
|
+
if (enabled)
|
|
128
|
+
bits |= exports.TABLE_GUARD[kind] ?? 0;
|
|
129
|
+
}
|
|
130
|
+
return bits;
|
|
131
|
+
}
|
|
132
|
+
/** Decodes guard bits into a readable object. */
|
|
133
|
+
function decodeGuardBits(bits) {
|
|
134
|
+
return {
|
|
135
|
+
appendOnly: (bits & exports.TABLE_GUARD.appendOnly) !== 0,
|
|
136
|
+
denyDelete: (bits & exports.TABLE_GUARD.denyDelete) !== 0,
|
|
137
|
+
denyUpdate: (bits & exports.TABLE_GUARD.denyUpdate) !== 0,
|
|
138
|
+
immutable: (bits & exports.TABLE_GUARD.immutable) !== 0,
|
|
139
|
+
freezePolicies: (bits & exports.TABLE_GUARD.freezePolicies) !== 0,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
exports.ROLE_TO_ANCHOR = {
|
|
143
|
+
owner: { owner: {} },
|
|
144
|
+
admin: { admin: {} },
|
|
145
|
+
member: { member: {} },
|
|
146
|
+
none: { none: {} },
|
|
147
|
+
};
|
|
148
|
+
function toBigInt(value) {
|
|
149
|
+
if (typeof value === "bigint")
|
|
150
|
+
return value;
|
|
151
|
+
if (typeof value === "number") {
|
|
152
|
+
if (!Number.isInteger(value)) {
|
|
153
|
+
throw new Error(`expected an integer, got ${value}`);
|
|
154
|
+
}
|
|
155
|
+
return BigInt(value);
|
|
156
|
+
}
|
|
157
|
+
return BigInt(value);
|
|
158
|
+
}
|
|
159
|
+
/** Parses a canonical UUID string into its 16-byte representation. */
|
|
160
|
+
function uuidToBytes(value) {
|
|
161
|
+
const hex = value.replace(/-/g, "").toLowerCase();
|
|
162
|
+
if (!/^[0-9a-f]{32}$/.test(hex)) {
|
|
163
|
+
throw new Error(`invalid UUID: ${value}`);
|
|
164
|
+
}
|
|
165
|
+
const out = new Uint8Array(16);
|
|
166
|
+
for (let i = 0; i < 16; i += 1) {
|
|
167
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
/** Formats 16 raw bytes as a canonical UUID string. */
|
|
172
|
+
function bytesToUuid(bytes) {
|
|
173
|
+
const hex = Array.from(bytes)
|
|
174
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
175
|
+
.join("");
|
|
176
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Coerces a raw user value into the canonical representation for a column.
|
|
180
|
+
* This is the single place where SQL literal types become on-chain types.
|
|
181
|
+
*/
|
|
182
|
+
/** Milliseconds in one UTC day. */
|
|
183
|
+
const MS_PER_DAY = 86400000;
|
|
184
|
+
/**
|
|
185
|
+
* Parses a `YYYY-MM-DD` literal into days since 1970-01-01 UTC.
|
|
186
|
+
* Round-trips through UTC so an invalid calendar date is rejected rather than
|
|
187
|
+
* silently normalized.
|
|
188
|
+
*/
|
|
189
|
+
function dateTextToDays(value) {
|
|
190
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value.trim());
|
|
191
|
+
if (!match)
|
|
192
|
+
throw new Error(`invalid DATE literal: ${value} (expected YYYY-MM-DD)`);
|
|
193
|
+
const [, year, month, day] = match;
|
|
194
|
+
const ms = Date.UTC(Number(year), Number(month) - 1, Number(day));
|
|
195
|
+
if (!Number.isFinite(ms))
|
|
196
|
+
throw new Error(`invalid DATE literal: ${value}`);
|
|
197
|
+
const roundTrip = new Date(ms).toISOString().slice(0, 10);
|
|
198
|
+
if (roundTrip !== value.trim())
|
|
199
|
+
throw new Error(`invalid DATE literal: ${value}`);
|
|
200
|
+
return BigInt(Math.floor(ms / MS_PER_DAY));
|
|
201
|
+
}
|
|
202
|
+
/** Formats days since epoch as `YYYY-MM-DD`. */
|
|
203
|
+
function daysToDateText(days) {
|
|
204
|
+
return new Date(Number(days) * MS_PER_DAY).toISOString().slice(0, 10);
|
|
205
|
+
}
|
|
206
|
+
/** Parses an ISO-8601 timestamp (or date) into whole UTC seconds. */
|
|
207
|
+
function timestampTextToSeconds(value) {
|
|
208
|
+
const ms = Date.parse(value.trim());
|
|
209
|
+
if (!Number.isFinite(ms)) {
|
|
210
|
+
throw new Error(`invalid TIMESTAMP literal: ${value} (expected ISO-8601)`);
|
|
211
|
+
}
|
|
212
|
+
return BigInt(Math.floor(ms / 1000));
|
|
213
|
+
}
|
|
214
|
+
/** Formats whole UTC seconds as an ISO-8601 timestamp. */
|
|
215
|
+
function secondsToTimestampText(seconds) {
|
|
216
|
+
return new Date(Number(seconds) * 1000).toISOString().replace(".000Z", "Z");
|
|
217
|
+
}
|
|
218
|
+
function coerceI64Like(value, label) {
|
|
219
|
+
if (typeof value === "bigint")
|
|
220
|
+
return value;
|
|
221
|
+
if (typeof value === "number") {
|
|
222
|
+
if (!Number.isSafeInteger(value))
|
|
223
|
+
throw new Error(`unsafe ${label} value: ${value}`);
|
|
224
|
+
return BigInt(value);
|
|
225
|
+
}
|
|
226
|
+
if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
|
|
227
|
+
return BigInt(value.trim());
|
|
228
|
+
}
|
|
229
|
+
throw new Error(`cannot coerce ${String(value)} to ${label}`);
|
|
230
|
+
}
|
|
231
|
+
function parseIpv4(text) {
|
|
232
|
+
const parts = text.split(".");
|
|
233
|
+
if (parts.length !== 4)
|
|
234
|
+
throw new Error(`invalid IPv4: ${text}`);
|
|
235
|
+
const bytes = parts.map((part) => {
|
|
236
|
+
if (!/^\d+$/.test(part))
|
|
237
|
+
throw new Error(`invalid IPv4: ${text}`);
|
|
238
|
+
const value = Number(part);
|
|
239
|
+
if (value < 0 || value > 255)
|
|
240
|
+
throw new Error(`invalid IPv4: ${text}`);
|
|
241
|
+
return value;
|
|
242
|
+
});
|
|
243
|
+
return Uint8Array.from(bytes);
|
|
244
|
+
}
|
|
245
|
+
function ipv4ToMapped(bytes) {
|
|
246
|
+
const out = new Uint8Array(16);
|
|
247
|
+
out[10] = 0xff;
|
|
248
|
+
out[11] = 0xff;
|
|
249
|
+
out.set(bytes, 12);
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
/** Parses IPv4, IPv4-mapped and the common IPv6 forms (including `::`). */
|
|
253
|
+
function parseInet(text, prefix) {
|
|
254
|
+
const [address, embedded] = text.includes("/") ? text.split("/") : [text, undefined];
|
|
255
|
+
const prefixText = embedded ?? (prefix === undefined ? undefined : String(prefix));
|
|
256
|
+
if (address.includes(".") && !address.includes(":")) {
|
|
257
|
+
const v4 = parseIpv4(address);
|
|
258
|
+
const p = prefixText === undefined ? 32 : Number(prefixText);
|
|
259
|
+
if (!Number.isInteger(p) || p < 0 || p > 32)
|
|
260
|
+
throw new Error(`invalid CIDR prefix: ${text}`);
|
|
261
|
+
return { bytes: ipv4ToMapped(v4), prefix: 96 + p };
|
|
262
|
+
}
|
|
263
|
+
const groups = address.split("::");
|
|
264
|
+
if (groups.length > 2)
|
|
265
|
+
throw new Error(`invalid IPv6: ${text}`);
|
|
266
|
+
const left = groups[0] ? groups[0].split(":") : [];
|
|
267
|
+
const right = groups[1] ? groups[1].split(":") : [];
|
|
268
|
+
const fill = 8 - left.length - right.length;
|
|
269
|
+
if (fill < 0 || (groups.length === 1 && fill !== 0)) {
|
|
270
|
+
throw new Error(`invalid IPv6: ${text}`);
|
|
271
|
+
}
|
|
272
|
+
const all = [...left, ...new Array(groups.length === 2 ? fill : 0).fill("0"), ...right];
|
|
273
|
+
const bytes = new Uint8Array(16);
|
|
274
|
+
all.forEach((group, index) => {
|
|
275
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(group))
|
|
276
|
+
throw new Error(`invalid IPv6: ${text}`);
|
|
277
|
+
const value = parseInt(group, 16);
|
|
278
|
+
bytes[index * 2] = value >> 8;
|
|
279
|
+
bytes[index * 2 + 1] = value & 0xff;
|
|
280
|
+
});
|
|
281
|
+
const p = prefixText === undefined ? 128 : Number(prefixText);
|
|
282
|
+
if (!Number.isInteger(p) || p < 0 || p > 128)
|
|
283
|
+
throw new Error(`invalid CIDR prefix: ${text}`);
|
|
284
|
+
return { bytes, prefix: p };
|
|
285
|
+
}
|
|
286
|
+
function inetToText(bytes, prefix) {
|
|
287
|
+
const mapped = bytes.slice(0, 10).every((byte) => byte === 0) &&
|
|
288
|
+
bytes[10] === 0xff &&
|
|
289
|
+
bytes[11] === 0xff;
|
|
290
|
+
if (mapped) {
|
|
291
|
+
return `${bytes.slice(12).join(".")}/${prefix - 96}`;
|
|
292
|
+
}
|
|
293
|
+
const groups = [];
|
|
294
|
+
for (let index = 0; index < 16; index += 2) {
|
|
295
|
+
groups.push(((bytes[index] << 8) | bytes[index + 1]).toString(16));
|
|
296
|
+
}
|
|
297
|
+
return `${groups.join(":")}/${prefix}`;
|
|
298
|
+
}
|
|
299
|
+
function macToBytes(text) {
|
|
300
|
+
const parts = text.split(/[:-]/);
|
|
301
|
+
if (parts.length !== 6)
|
|
302
|
+
throw new Error(`invalid MACADDR: ${text}`);
|
|
303
|
+
const bytes = parts.map((part) => {
|
|
304
|
+
if (!/^[0-9a-fA-F]{2}$/.test(part))
|
|
305
|
+
throw new Error(`invalid MACADDR: ${text}`);
|
|
306
|
+
return parseInt(part, 16);
|
|
307
|
+
});
|
|
308
|
+
return Uint8Array.from(bytes);
|
|
309
|
+
}
|
|
310
|
+
function bitTextToBytes(text) {
|
|
311
|
+
if (!/^[01]+$/.test(text))
|
|
312
|
+
throw new Error(`invalid BIT string: ${text}`);
|
|
313
|
+
const bytes = new Uint8Array(Math.ceil(text.length / 8));
|
|
314
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
315
|
+
if (text[index] === "1")
|
|
316
|
+
bytes[Math.floor(index / 8)] |= 1 << (7 - (index % 8));
|
|
317
|
+
}
|
|
318
|
+
return { bytes, length: text.length };
|
|
319
|
+
}
|
|
320
|
+
function coerceValue(value, column) {
|
|
321
|
+
if (value === null || value === undefined)
|
|
322
|
+
return null;
|
|
323
|
+
switch (column.type) {
|
|
324
|
+
case "bool":
|
|
325
|
+
if (typeof value === "boolean")
|
|
326
|
+
return value;
|
|
327
|
+
if (typeof value === "string") {
|
|
328
|
+
if (value.toLowerCase() === "true")
|
|
329
|
+
return true;
|
|
330
|
+
if (value.toLowerCase() === "false")
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
if (typeof value === "number")
|
|
334
|
+
return value !== 0;
|
|
335
|
+
throw new Error(`cannot coerce ${String(value)} to BOOLEAN`);
|
|
336
|
+
case "i64":
|
|
337
|
+
return toBigInt(value);
|
|
338
|
+
case "decimal": {
|
|
339
|
+
const scale = column.scale ?? 0;
|
|
340
|
+
if (typeof value === "object" && value !== null && "decimal" in value) {
|
|
341
|
+
if (value.scale !== scale) {
|
|
342
|
+
throw new Error(`decimal scale mismatch: expected ${scale}`);
|
|
343
|
+
}
|
|
344
|
+
return value;
|
|
345
|
+
}
|
|
346
|
+
const raw = (typeof value === "number" ? value.toString() : String(value)).trim();
|
|
347
|
+
const factor = 10n ** BigInt(scale);
|
|
348
|
+
const negative = raw.startsWith("-");
|
|
349
|
+
const unsigned = negative ? raw.slice(1) : raw;
|
|
350
|
+
const dot = unsigned.indexOf(".");
|
|
351
|
+
const whole = dot === -1 ? unsigned : unsigned.slice(0, dot) || "0";
|
|
352
|
+
const fraction = dot === -1 ? "" : unsigned.slice(dot + 1);
|
|
353
|
+
const padded = fraction.padEnd(scale, "0");
|
|
354
|
+
// PostgreSQL rounds half away from zero when a value exceeds the scale.
|
|
355
|
+
let digits = BigInt(padded.slice(0, scale) || "0");
|
|
356
|
+
if (padded.length > scale && Number(padded[scale]) >= 5)
|
|
357
|
+
digits += 1n;
|
|
358
|
+
let scaled = BigInt(whole || "0") * factor + digits;
|
|
359
|
+
if (negative)
|
|
360
|
+
scaled = -scaled;
|
|
361
|
+
return { decimal: scaled, scale };
|
|
362
|
+
}
|
|
363
|
+
case "text":
|
|
364
|
+
if (typeof value !== "string") {
|
|
365
|
+
throw new Error(`cannot coerce ${String(value)} to TEXT`);
|
|
366
|
+
}
|
|
367
|
+
return value;
|
|
368
|
+
case "uuid":
|
|
369
|
+
if (value instanceof Uint8Array) {
|
|
370
|
+
if (value.length !== 16)
|
|
371
|
+
throw new Error("UUID must be 16 bytes");
|
|
372
|
+
return value;
|
|
373
|
+
}
|
|
374
|
+
if (typeof value === "string")
|
|
375
|
+
return uuidToBytes(value);
|
|
376
|
+
throw new Error(`cannot coerce ${String(value)} to UUID`);
|
|
377
|
+
case "date":
|
|
378
|
+
if (value instanceof Date) {
|
|
379
|
+
return BigInt(Math.floor(value.getTime() / MS_PER_DAY));
|
|
380
|
+
}
|
|
381
|
+
if (typeof value === "string")
|
|
382
|
+
return dateTextToDays(value);
|
|
383
|
+
return coerceI64Like(value, "DATE");
|
|
384
|
+
case "timestamp":
|
|
385
|
+
if (value instanceof Date)
|
|
386
|
+
return BigInt(Math.floor(value.getTime() / 1000));
|
|
387
|
+
if (typeof value === "string" && !/^-?\d+$/.test(value.trim())) {
|
|
388
|
+
return timestampTextToSeconds(value);
|
|
389
|
+
}
|
|
390
|
+
return coerceI64Like(value, "TIMESTAMP");
|
|
391
|
+
case "interval":
|
|
392
|
+
if (typeof value === "string")
|
|
393
|
+
return parseInterval(value);
|
|
394
|
+
if (typeof value === "object" && value !== null && "interval" in value) {
|
|
395
|
+
const parsed = value.interval;
|
|
396
|
+
return {
|
|
397
|
+
interval: {
|
|
398
|
+
months: Number(parsed.months),
|
|
399
|
+
days: Number(parsed.days),
|
|
400
|
+
micros: BigInt(parsed.micros),
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
interval: {
|
|
406
|
+
months: 0,
|
|
407
|
+
days: 0,
|
|
408
|
+
micros: coerceI64Like(value, "INTERVAL") * 1000000n,
|
|
409
|
+
},
|
|
410
|
+
};
|
|
411
|
+
case "inet":
|
|
412
|
+
case "cidr": {
|
|
413
|
+
if (typeof value === "string") {
|
|
414
|
+
const parsed = parseInet(value);
|
|
415
|
+
return { inet: parsed.bytes, prefix: parsed.prefix };
|
|
416
|
+
}
|
|
417
|
+
if (typeof value === "object" && value !== null && "inet" in value) {
|
|
418
|
+
const parsed = value;
|
|
419
|
+
return {
|
|
420
|
+
inet: Uint8Array.from(parsed.inet),
|
|
421
|
+
prefix: Number(parsed.prefix),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
throw new Error(`cannot coerce ${String(value)} to ${column.type.toUpperCase()}`);
|
|
425
|
+
}
|
|
426
|
+
case "macaddr":
|
|
427
|
+
if (typeof value === "string")
|
|
428
|
+
return { mac: macToBytes(value) };
|
|
429
|
+
if (value instanceof Uint8Array) {
|
|
430
|
+
if (value.length !== 6)
|
|
431
|
+
throw new Error("MACADDR must be 6 bytes");
|
|
432
|
+
return { mac: Uint8Array.from(value) };
|
|
433
|
+
}
|
|
434
|
+
if (typeof value === "object" && value !== null && "mac" in value) {
|
|
435
|
+
return { mac: Uint8Array.from(value.mac) };
|
|
436
|
+
}
|
|
437
|
+
throw new Error(`cannot coerce ${String(value)} to MACADDR`);
|
|
438
|
+
case "bit":
|
|
439
|
+
case "varbit":
|
|
440
|
+
if (typeof value === "string")
|
|
441
|
+
return { bit: bitTextToBytes(value).bytes, length: value.length };
|
|
442
|
+
if (typeof value === "object" && value !== null && "bit" in value) {
|
|
443
|
+
const parsed = value;
|
|
444
|
+
return { bit: Uint8Array.from(parsed.bit), length: Number(parsed.length) };
|
|
445
|
+
}
|
|
446
|
+
throw new Error(`cannot coerce ${String(value)} to ${column.type.toUpperCase()}`);
|
|
447
|
+
case "time": {
|
|
448
|
+
if (typeof value === "string") {
|
|
449
|
+
const match = /^(\d{2}):(\d{2}):(\d{2})$/.exec(value.trim());
|
|
450
|
+
if (!match)
|
|
451
|
+
throw new Error(`invalid TIME literal: ${value}`);
|
|
452
|
+
const hours = Number(match[1]);
|
|
453
|
+
const minutes = Number(match[2]);
|
|
454
|
+
const seconds = Number(match[3]);
|
|
455
|
+
if (hours > 23 || minutes > 59 || seconds > 59) {
|
|
456
|
+
throw new Error(`invalid TIME literal: ${value}`);
|
|
457
|
+
}
|
|
458
|
+
return BigInt(hours * 3600 + minutes * 60 + seconds);
|
|
459
|
+
}
|
|
460
|
+
return coerceI64Like(value, "TIME");
|
|
461
|
+
}
|
|
462
|
+
case "range":
|
|
463
|
+
case "numrange":
|
|
464
|
+
case "tsrange":
|
|
465
|
+
case "daterange":
|
|
466
|
+
return coerceRange(value, column);
|
|
467
|
+
case "address":
|
|
468
|
+
if (value instanceof Uint8Array) {
|
|
469
|
+
if (value.length !== 32)
|
|
470
|
+
throw new Error("ADDRESS must be 32 bytes");
|
|
471
|
+
return { address: Uint8Array.from(value) };
|
|
472
|
+
}
|
|
473
|
+
if (typeof value === "object" && value !== null && "address" in value) {
|
|
474
|
+
const bytes = Uint8Array.from(value.address);
|
|
475
|
+
if (bytes.length !== 32)
|
|
476
|
+
throw new Error("ADDRESS must be 32 bytes");
|
|
477
|
+
return { address: bytes };
|
|
478
|
+
}
|
|
479
|
+
if (typeof value === "string") {
|
|
480
|
+
const bytes = Buffer.from(value.replace(/^0x/, ""), "hex");
|
|
481
|
+
if (bytes.length !== 32)
|
|
482
|
+
throw new Error("ADDRESS string must be 32-byte hex");
|
|
483
|
+
return { address: Uint8Array.from(bytes) };
|
|
484
|
+
}
|
|
485
|
+
throw new Error(`cannot coerce ${String(value)} to ADDRESS`);
|
|
486
|
+
default:
|
|
487
|
+
throw new Error(`unknown column type: ${column.type}`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function writeI128LE(buffer, offset, value) {
|
|
491
|
+
let v = BigInt.asUintN(128, value);
|
|
492
|
+
for (let i = 0; i < 16; i += 1) {
|
|
493
|
+
buffer[offset + i] = Number(v & 0xffn);
|
|
494
|
+
v >>= 8n;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function readI128LE(buffer, offset) {
|
|
498
|
+
let v = 0n;
|
|
499
|
+
for (let i = 15; i >= 0; i -= 1) {
|
|
500
|
+
v = (v << 8n) | BigInt(buffer[offset + i]);
|
|
501
|
+
}
|
|
502
|
+
return BigInt.asIntN(128, v);
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Canonical Borsh encoding of a typed `Value`. This must byte-for-byte match
|
|
506
|
+
* the Rust `Value` enum because it is used for PK hashing and index keys.
|
|
507
|
+
*/
|
|
508
|
+
function encodeTypedValue(value) {
|
|
509
|
+
if (value === null || value === undefined) {
|
|
510
|
+
return Buffer.from([0]);
|
|
511
|
+
}
|
|
512
|
+
if (typeof value === "boolean") {
|
|
513
|
+
return Buffer.from([1, value ? 1 : 0]);
|
|
514
|
+
}
|
|
515
|
+
if (typeof value === "bigint" || typeof value === "number") {
|
|
516
|
+
const buffer = Buffer.alloc(9);
|
|
517
|
+
buffer[0] = 2;
|
|
518
|
+
buffer.writeBigInt64LE(BigInt(value.toString()), 1);
|
|
519
|
+
return buffer;
|
|
520
|
+
}
|
|
521
|
+
if (typeof value === "string") {
|
|
522
|
+
const data = Buffer.from(value, "utf8");
|
|
523
|
+
const buffer = Buffer.alloc(5 + data.length);
|
|
524
|
+
buffer[0] = 4;
|
|
525
|
+
buffer.writeUInt32LE(data.length, 1);
|
|
526
|
+
data.copy(buffer, 5);
|
|
527
|
+
return buffer;
|
|
528
|
+
}
|
|
529
|
+
if (value instanceof Uint8Array) {
|
|
530
|
+
const buffer = Buffer.alloc(17);
|
|
531
|
+
buffer[0] = 5;
|
|
532
|
+
Buffer.from(value).copy(buffer, 1);
|
|
533
|
+
return buffer;
|
|
534
|
+
}
|
|
535
|
+
if (typeof value === "object" && "decimal" in value) {
|
|
536
|
+
const buffer = Buffer.alloc(18);
|
|
537
|
+
buffer[0] = 3;
|
|
538
|
+
writeI128LE(buffer, 1, value.decimal);
|
|
539
|
+
buffer[17] = value.scale;
|
|
540
|
+
return buffer;
|
|
541
|
+
}
|
|
542
|
+
if (isOverflowValue(value)) {
|
|
543
|
+
const buffer = Buffer.alloc(39);
|
|
544
|
+
buffer[0] = 6;
|
|
545
|
+
Buffer.from(value.ref.key).copy(buffer, 1);
|
|
546
|
+
buffer.writeUInt16LE(value.ref.chunks, 33);
|
|
547
|
+
buffer.writeUInt32LE(value.ref.len, 35);
|
|
548
|
+
return buffer;
|
|
549
|
+
}
|
|
550
|
+
if (typeof value === "object" && value !== null && "address" in value) {
|
|
551
|
+
const buffer = Buffer.alloc(33);
|
|
552
|
+
buffer[0] = 7;
|
|
553
|
+
Buffer.from(value.address).copy(buffer, 1);
|
|
554
|
+
return buffer;
|
|
555
|
+
}
|
|
556
|
+
if (typeof value === "object" && value !== null && "inet" in value) {
|
|
557
|
+
const parsed = value;
|
|
558
|
+
const buffer = Buffer.alloc(18);
|
|
559
|
+
buffer[0] = 8;
|
|
560
|
+
Buffer.from(parsed.inet).copy(buffer, 1);
|
|
561
|
+
buffer[17] = parsed.prefix & 0xff;
|
|
562
|
+
return buffer;
|
|
563
|
+
}
|
|
564
|
+
if (typeof value === "object" && value !== null && "mac" in value) {
|
|
565
|
+
const buffer = Buffer.alloc(7);
|
|
566
|
+
buffer[0] = 9;
|
|
567
|
+
Buffer.from(value.mac).copy(buffer, 1);
|
|
568
|
+
return buffer;
|
|
569
|
+
}
|
|
570
|
+
if (typeof value === "object" && value !== null && "interval" in value) {
|
|
571
|
+
const parsed = value.interval;
|
|
572
|
+
const buffer = Buffer.alloc(17);
|
|
573
|
+
buffer[0] = 12;
|
|
574
|
+
buffer.writeInt32LE(parsed.months, 1);
|
|
575
|
+
buffer.writeInt32LE(parsed.days, 5);
|
|
576
|
+
buffer.writeBigInt64LE(parsed.micros, 9);
|
|
577
|
+
return buffer;
|
|
578
|
+
}
|
|
579
|
+
if (typeof value === "object" && value !== null && "range" in value) {
|
|
580
|
+
const parsed = value.range;
|
|
581
|
+
const buffer = Buffer.alloc(18);
|
|
582
|
+
buffer[0] = 11;
|
|
583
|
+
buffer.writeBigInt64LE(parsed.start, 1);
|
|
584
|
+
buffer.writeBigInt64LE(parsed.end, 9);
|
|
585
|
+
buffer[17] = parsed.flags;
|
|
586
|
+
return buffer;
|
|
587
|
+
}
|
|
588
|
+
if (typeof value === "object" && value !== null && "bit" in value) {
|
|
589
|
+
const parsed = value;
|
|
590
|
+
const buffer = Buffer.alloc(11 + parsed.bit.length);
|
|
591
|
+
buffer[0] = 10;
|
|
592
|
+
buffer.writeUInt32LE(parsed.bit.length, 1);
|
|
593
|
+
Buffer.from(parsed.bit).copy(buffer, 5);
|
|
594
|
+
buffer.writeUInt16LE(parsed.length, 5 + parsed.bit.length);
|
|
595
|
+
return buffer;
|
|
596
|
+
}
|
|
597
|
+
throw new Error(`cannot encode value: ${String(value)}`);
|
|
598
|
+
}
|
|
599
|
+
/** Borsh size of a canonical `Value`, in bytes. */
|
|
600
|
+
function typedValueSize(value) {
|
|
601
|
+
if (value === null || value === undefined)
|
|
602
|
+
return 1;
|
|
603
|
+
if (typeof value === "boolean")
|
|
604
|
+
return 2;
|
|
605
|
+
if (typeof value === "bigint" || typeof value === "number")
|
|
606
|
+
return 9;
|
|
607
|
+
if (typeof value === "string")
|
|
608
|
+
return 5 + Buffer.byteLength(value, "utf8");
|
|
609
|
+
if (value instanceof Uint8Array)
|
|
610
|
+
return 17;
|
|
611
|
+
if (typeof value === "object" && value !== null && "address" in value)
|
|
612
|
+
return 33;
|
|
613
|
+
if (typeof value === "object" && value !== null && "inet" in value)
|
|
614
|
+
return 18;
|
|
615
|
+
if (typeof value === "object" && value !== null && "mac" in value)
|
|
616
|
+
return 7;
|
|
617
|
+
if (typeof value === "object" && value !== null && "bit" in value) {
|
|
618
|
+
return 11 + value.bit.length;
|
|
619
|
+
}
|
|
620
|
+
if (typeof value === "object" && value !== null && "interval" in value)
|
|
621
|
+
return 17;
|
|
622
|
+
if (typeof value === "object" && value !== null && "range" in value)
|
|
623
|
+
return 18;
|
|
624
|
+
if (typeof value === "object" && "decimal" in value)
|
|
625
|
+
return 18;
|
|
626
|
+
if (isOverflowValue(value))
|
|
627
|
+
return 39;
|
|
628
|
+
throw new Error(`cannot size value: ${String(value)}`);
|
|
629
|
+
}
|
|
630
|
+
/** Domain separators for v3 digests (frozen PRD §3.2, §5). */ exports.PK_V3_DOMAIN = Buffer.from("peridotbase:pk:v3", "utf8");
|
|
631
|
+
exports.UNIQUE_V3_DOMAIN = Buffer.from("peridotbase:unique:v3", "utf8");
|
|
632
|
+
exports.INDEX_ID_V3_DOMAIN = Buffer.from("peridotbase:index-id:v3", "utf8");
|
|
633
|
+
exports.POSTING_V3_DOMAIN = Buffer.from("peridotbase:posting:v3", "utf8");
|
|
634
|
+
/**
|
|
635
|
+
* Composite index key: `0xFE | count | [u16 len | canonical part]...`.
|
|
636
|
+
* Mirrors Rust `v3_index_key_for_row`.
|
|
637
|
+
*/
|
|
638
|
+
function compositeIndexKeyV3(parts) {
|
|
639
|
+
const head = Buffer.from([0xfe, parts.length & 0xff]);
|
|
640
|
+
const body = parts.map((part) => {
|
|
641
|
+
const length = Buffer.alloc(2);
|
|
642
|
+
length.writeUInt16LE(part.length);
|
|
643
|
+
return Buffer.concat([length, Buffer.from(part)]);
|
|
644
|
+
});
|
|
645
|
+
return Buffer.concat([head, ...body]);
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Canonical v3 PK/index key with pinned tags (not enum order).
|
|
649
|
+
* NULL and Ref are rejected as PK keys. Mirrors Rust `canonical_typed_key_v3`.
|
|
650
|
+
*/
|
|
651
|
+
function canonicalTypedKeyV3(value) {
|
|
652
|
+
if (typeof value === "boolean")
|
|
653
|
+
return Buffer.from([0x01, value ? 1 : 0]);
|
|
654
|
+
if (typeof value === "bigint") {
|
|
655
|
+
const b = Buffer.alloc(9);
|
|
656
|
+
b[0] = 0x02;
|
|
657
|
+
b.writeBigInt64LE(value, 1);
|
|
658
|
+
return b;
|
|
659
|
+
}
|
|
660
|
+
if (typeof value === "number") {
|
|
661
|
+
if (!Number.isSafeInteger(value))
|
|
662
|
+
throw new Error(`unsafe i64: ${value}`);
|
|
663
|
+
const b = Buffer.alloc(9);
|
|
664
|
+
b[0] = 0x02;
|
|
665
|
+
b.writeBigInt64LE(BigInt(value), 1);
|
|
666
|
+
return b;
|
|
667
|
+
}
|
|
668
|
+
if (typeof value === "object" && value !== null && "decimal" in value) {
|
|
669
|
+
const d = value;
|
|
670
|
+
const b = Buffer.alloc(18);
|
|
671
|
+
b[0] = 0x03;
|
|
672
|
+
let v = BigInt.asUintN(128, d.decimal);
|
|
673
|
+
for (let i = 0; i < 16; i += 1) {
|
|
674
|
+
b[1 + i] = Number(v & 0xffn);
|
|
675
|
+
v >>= 8n;
|
|
676
|
+
}
|
|
677
|
+
b[17] = d.scale;
|
|
678
|
+
return b;
|
|
679
|
+
}
|
|
680
|
+
if (typeof value === "string") {
|
|
681
|
+
const data = Buffer.from(value, "utf8");
|
|
682
|
+
const b = Buffer.alloc(5 + data.length);
|
|
683
|
+
b[0] = 0x04;
|
|
684
|
+
b.writeUInt32LE(data.length, 1);
|
|
685
|
+
data.copy(b, 5);
|
|
686
|
+
return b;
|
|
687
|
+
}
|
|
688
|
+
if (value instanceof Uint8Array) {
|
|
689
|
+
if (value.length !== 16)
|
|
690
|
+
throw new Error("UUID must be 16 bytes");
|
|
691
|
+
const b = Buffer.alloc(17);
|
|
692
|
+
b[0] = 0x05;
|
|
693
|
+
Buffer.from(value).copy(b, 1);
|
|
694
|
+
return b;
|
|
695
|
+
}
|
|
696
|
+
if (typeof value === "object" && value !== null && "address" in value) {
|
|
697
|
+
const bytes = value.address;
|
|
698
|
+
if (bytes.length !== 32)
|
|
699
|
+
throw new Error("ADDRESS must be 32 bytes");
|
|
700
|
+
const b = Buffer.alloc(33);
|
|
701
|
+
b[0] = 0x06;
|
|
702
|
+
Buffer.from(bytes).copy(b, 1);
|
|
703
|
+
return b;
|
|
704
|
+
}
|
|
705
|
+
if (typeof value === "object" && value !== null && "inet" in value) {
|
|
706
|
+
const parsed = value;
|
|
707
|
+
const b = Buffer.alloc(18);
|
|
708
|
+
b[0] = 0x07;
|
|
709
|
+
Buffer.from(parsed.inet).copy(b, 1);
|
|
710
|
+
b[17] = parsed.prefix;
|
|
711
|
+
return b;
|
|
712
|
+
}
|
|
713
|
+
if (typeof value === "object" && value !== null && "mac" in value) {
|
|
714
|
+
const b = Buffer.alloc(7);
|
|
715
|
+
b[0] = 0x08;
|
|
716
|
+
Buffer.from(value.mac).copy(b, 1);
|
|
717
|
+
return b;
|
|
718
|
+
}
|
|
719
|
+
if (typeof value === "object" && value !== null && "range" in value) {
|
|
720
|
+
const parsed = value.range;
|
|
721
|
+
const b = Buffer.alloc(18);
|
|
722
|
+
b[0] = 0x0a;
|
|
723
|
+
b.writeBigInt64LE(parsed.start, 1);
|
|
724
|
+
b.writeBigInt64LE(parsed.end, 9);
|
|
725
|
+
b[17] = parsed.flags;
|
|
726
|
+
return b;
|
|
727
|
+
}
|
|
728
|
+
if (typeof value === "object" && value !== null && "bit" in value) {
|
|
729
|
+
const parsed = value;
|
|
730
|
+
const b = Buffer.alloc(11 + parsed.bit.length);
|
|
731
|
+
b[0] = 0x09;
|
|
732
|
+
b.writeUInt32LE(parsed.bit.length, 1);
|
|
733
|
+
Buffer.from(parsed.bit).copy(b, 5);
|
|
734
|
+
b.writeUInt16LE(parsed.length, 5 + parsed.bit.length);
|
|
735
|
+
return b;
|
|
736
|
+
}
|
|
737
|
+
throw new Error("NULL/Ref invalid as v3 PK key");
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Canonical v3 primary-key bytes for one or more columns. A single column keeps
|
|
741
|
+
* the legacy encoding; composite keys are tagged `0xFE` and length-prefixed.
|
|
742
|
+
*/
|
|
743
|
+
function primaryKeyCanonicalV3(values, columns) {
|
|
744
|
+
if (columns.length === 1)
|
|
745
|
+
return canonicalTypedKeyV3(values[columns[0]]);
|
|
746
|
+
const parts = [Buffer.from([0xfe, columns.length & 0xff])];
|
|
747
|
+
for (const column of columns) {
|
|
748
|
+
const bytes = canonicalTypedKeyV3(values[column]);
|
|
749
|
+
const len = Buffer.alloc(2);
|
|
750
|
+
len.writeUInt16LE(bytes.length);
|
|
751
|
+
parts.push(len, bytes);
|
|
752
|
+
}
|
|
753
|
+
return Buffer.concat(parts);
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Reverse of `canonicalTypedKeyV3` for covering-index payloads. The tag byte
|
|
757
|
+
* decides the type, so no column spec is needed; NULL is not encoded.
|
|
758
|
+
*/
|
|
759
|
+
function decodeCanonicalTypedKeyV3(bytes) {
|
|
760
|
+
const b = Buffer.from(bytes);
|
|
761
|
+
const tag = b[0];
|
|
762
|
+
switch (tag) {
|
|
763
|
+
case 0x01:
|
|
764
|
+
return b[1] !== 0;
|
|
765
|
+
case 0x02:
|
|
766
|
+
return b.readBigInt64LE(1);
|
|
767
|
+
case 0x03:
|
|
768
|
+
return { decimal: b.readBigInt64LE(1), scale: b[17] };
|
|
769
|
+
case 0x04: {
|
|
770
|
+
const length = b.readUInt32LE(1);
|
|
771
|
+
return b.subarray(5, 5 + length).toString("utf8");
|
|
772
|
+
}
|
|
773
|
+
case 0x05:
|
|
774
|
+
return Uint8Array.from(b.subarray(1, 17));
|
|
775
|
+
case 0x06:
|
|
776
|
+
return { address: Uint8Array.from(b.subarray(1, 33)) };
|
|
777
|
+
case 0x07:
|
|
778
|
+
return { inet: Uint8Array.from(b.subarray(1, 17)), prefix: b[17] };
|
|
779
|
+
case 0x08:
|
|
780
|
+
return { mac: Uint8Array.from(b.subarray(1, 7)) };
|
|
781
|
+
case 0x09: {
|
|
782
|
+
const length = b.readUInt32LE(1);
|
|
783
|
+
return {
|
|
784
|
+
bit: Uint8Array.from(b.subarray(5, 5 + length)),
|
|
785
|
+
length: b.readUInt16LE(5 + length),
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
case 0x0a:
|
|
789
|
+
return {
|
|
790
|
+
range: {
|
|
791
|
+
start: b.readBigInt64LE(1),
|
|
792
|
+
end: b.readBigInt64LE(9),
|
|
793
|
+
flags: b[17],
|
|
794
|
+
},
|
|
795
|
+
};
|
|
796
|
+
default:
|
|
797
|
+
throw new Error(`unknown canonical key tag: ${tag}`);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Decodes an INCLUDE payload written by the program: per column
|
|
802
|
+
* `present: u8` then `len: u16 LE` + canonical key when present.
|
|
803
|
+
*/
|
|
804
|
+
function decodeCoveringPayload(payload, columnCount) {
|
|
805
|
+
const b = Buffer.from(payload);
|
|
806
|
+
const out = [];
|
|
807
|
+
let offset = 0;
|
|
808
|
+
for (let index = 0; index < columnCount; index += 1) {
|
|
809
|
+
if (offset >= b.length)
|
|
810
|
+
throw new Error("truncated covering payload");
|
|
811
|
+
const present = b[offset];
|
|
812
|
+
offset += 1;
|
|
813
|
+
if (present === 0) {
|
|
814
|
+
out.push(null);
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
const length = b.readUInt16LE(offset);
|
|
818
|
+
offset += 2;
|
|
819
|
+
out.push(decodeCanonicalTypedKeyV3(b.subarray(offset, offset + length)));
|
|
820
|
+
offset += length;
|
|
821
|
+
}
|
|
822
|
+
return out;
|
|
823
|
+
}
|
|
824
|
+
/** D = SHA256("peridotbase:pk:v3" || K). */
|
|
825
|
+
function pkDigestV3(key) {
|
|
826
|
+
return (0, crypto_1.createHash)("sha256").update(exports.PK_V3_DOMAIN).update(key).digest();
|
|
827
|
+
}
|
|
828
|
+
/** U = SHA256("peridotbase:unique:v3" || canonicalIndexedKey). */
|
|
829
|
+
function uniqueDigestV3(key) {
|
|
830
|
+
return (0, crypto_1.createHash)("sha256").update(exports.UNIQUE_V3_DOMAIN).update(key).digest();
|
|
831
|
+
}
|
|
832
|
+
/** V = SHA256("peridotbase:posting:v3" || canonicalIndexedKey). */
|
|
833
|
+
function postingDigestV3(key) {
|
|
834
|
+
return (0, crypto_1.createHash)("sha256").update(exports.POSTING_V3_DOMAIN).update(key).digest();
|
|
835
|
+
}
|
|
836
|
+
/** Converts a canonical value into the Anchor enum object for instruction args. */
|
|
837
|
+
/**
|
|
838
|
+
* The Rust `Value` enum uses tuple variants (`Text(String)`), which the
|
|
839
|
+
* Anchor coder models as a single numerically-named field. Encoding therefore
|
|
840
|
+
* requires the variant payload to be a one-element array; passing the scalar
|
|
841
|
+
* directly is silently truncated to its first character.
|
|
842
|
+
*/
|
|
843
|
+
function toAnchorValue(value) {
|
|
844
|
+
if (value === null || value === undefined)
|
|
845
|
+
return { null: {} };
|
|
846
|
+
if (typeof value === "boolean")
|
|
847
|
+
return { bool: [value] };
|
|
848
|
+
if (typeof value === "bigint" || typeof value === "number") {
|
|
849
|
+
return { i64: [new bn_js_1.default(value.toString())] };
|
|
850
|
+
}
|
|
851
|
+
if (typeof value === "string")
|
|
852
|
+
return { text: [value] };
|
|
853
|
+
if (value instanceof Uint8Array)
|
|
854
|
+
return { uuid: [Array.from(value)] };
|
|
855
|
+
if (typeof value === "object" && value !== null && "address" in value) {
|
|
856
|
+
return { address: [Array.from(value.address)] };
|
|
857
|
+
}
|
|
858
|
+
if (typeof value === "object" && value !== null && "inet" in value) {
|
|
859
|
+
const parsed = value;
|
|
860
|
+
return { inet: [Array.from(parsed.inet), parsed.prefix] };
|
|
861
|
+
}
|
|
862
|
+
if (typeof value === "object" && value !== null && "mac" in value) {
|
|
863
|
+
return { macAddr: [Array.from(value.mac)] };
|
|
864
|
+
}
|
|
865
|
+
if (typeof value === "object" && value !== null && "bit" in value) {
|
|
866
|
+
const parsed = value;
|
|
867
|
+
return { bit: [Buffer.from(parsed.bit), parsed.length] };
|
|
868
|
+
}
|
|
869
|
+
if (typeof value === "object" && value !== null && "interval" in value) {
|
|
870
|
+
const parsed = value.interval;
|
|
871
|
+
return { interval: [parsed.months, parsed.days, new bn_js_1.default(parsed.micros.toString())] };
|
|
872
|
+
}
|
|
873
|
+
if (typeof value === "object" && value !== null && "range" in value) {
|
|
874
|
+
const parsed = value.range;
|
|
875
|
+
return { rangeI64: [new bn_js_1.default(parsed.start.toString()), new bn_js_1.default(parsed.end.toString()), parsed.flags] };
|
|
876
|
+
}
|
|
877
|
+
if (typeof value === "object" && "decimal" in value) {
|
|
878
|
+
const d = value;
|
|
879
|
+
return { decimal: [new bn_js_1.default(d.decimal.toString()), d.scale] };
|
|
880
|
+
}
|
|
881
|
+
if (isOverflowValue(value)) {
|
|
882
|
+
return {
|
|
883
|
+
ref: [
|
|
884
|
+
{
|
|
885
|
+
key: Array.from(value.ref.key),
|
|
886
|
+
chunks: value.ref.chunks,
|
|
887
|
+
len: value.ref.len,
|
|
888
|
+
},
|
|
889
|
+
],
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
throw new Error(`cannot convert value: ${String(value)}`);
|
|
893
|
+
}
|
|
894
|
+
/** Unwraps the coder's numerically-keyed tuple field (`{"0": v}` / `[v]`). */
|
|
895
|
+
function tupleField(payload) {
|
|
896
|
+
if (Array.isArray(payload))
|
|
897
|
+
return payload[0];
|
|
898
|
+
if (payload !== null && typeof payload === "object" && "0" in payload) {
|
|
899
|
+
return payload["0"];
|
|
900
|
+
}
|
|
901
|
+
return payload;
|
|
902
|
+
}
|
|
903
|
+
/** Converts an Anchor enum object back into a canonical value. */
|
|
904
|
+
function fromAnchorValue(value) {
|
|
905
|
+
if (value === null || value === undefined)
|
|
906
|
+
return null;
|
|
907
|
+
if ("null" in value)
|
|
908
|
+
return null;
|
|
909
|
+
if ("bool" in value)
|
|
910
|
+
return Boolean(tupleField(value.bool));
|
|
911
|
+
if ("i64" in value)
|
|
912
|
+
return BigInt(tupleField(value.i64).toString());
|
|
913
|
+
if ("decimal" in value) {
|
|
914
|
+
const payload = value.decimal;
|
|
915
|
+
const scaled = Array.isArray(payload) ? payload[0] : payload["0"];
|
|
916
|
+
const scale = Array.isArray(payload) ? payload[1] : payload["1"];
|
|
917
|
+
return {
|
|
918
|
+
decimal: BigInt(scaled.toString()),
|
|
919
|
+
scale: Number(scale),
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
if ("text" in value)
|
|
923
|
+
return String(tupleField(value.text));
|
|
924
|
+
if ("uuid" in value)
|
|
925
|
+
return Uint8Array.from(tupleField(value.uuid));
|
|
926
|
+
if ("address" in value) {
|
|
927
|
+
return { address: Uint8Array.from(tupleField(value.address)) };
|
|
928
|
+
}
|
|
929
|
+
if ("inet" in value) {
|
|
930
|
+
const payload = value.inet;
|
|
931
|
+
const bytes = Array.isArray(payload) ? payload[0] : payload["0"];
|
|
932
|
+
const prefix = Array.isArray(payload) ? payload[1] : payload["1"];
|
|
933
|
+
return { inet: Uint8Array.from(bytes), prefix: Number(prefix) };
|
|
934
|
+
}
|
|
935
|
+
if ("macAddr" in value || "macaddr" in value) {
|
|
936
|
+
const payload = value.macAddr ?? value.macaddr;
|
|
937
|
+
return { mac: Uint8Array.from(tupleField(payload)) };
|
|
938
|
+
}
|
|
939
|
+
if ("bit" in value) {
|
|
940
|
+
const payload = value.bit;
|
|
941
|
+
const bytes = Array.isArray(payload) ? payload[0] : payload["0"];
|
|
942
|
+
const length = Array.isArray(payload) ? payload[1] : payload["1"];
|
|
943
|
+
return { bit: Uint8Array.from(bytes), length: Number(length) };
|
|
944
|
+
}
|
|
945
|
+
if ("interval" in value) {
|
|
946
|
+
const payload = value.interval;
|
|
947
|
+
return {
|
|
948
|
+
interval: {
|
|
949
|
+
months: Number(payload[0] ?? payload["0"]),
|
|
950
|
+
days: Number(payload[1] ?? payload["1"]),
|
|
951
|
+
micros: BigInt((payload[2] ?? payload["2"]).toString()),
|
|
952
|
+
},
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
if ("rangeI64" in value || "rangei64" in value) {
|
|
956
|
+
const payload = value.rangeI64 ?? value.rangei64;
|
|
957
|
+
return {
|
|
958
|
+
range: {
|
|
959
|
+
start: BigInt(tupleField(payload[0] ?? payload["0"]).toString()),
|
|
960
|
+
end: BigInt(tupleField(payload[1] ?? payload["1"]).toString()),
|
|
961
|
+
flags: Number(payload[2] ?? payload["2"]),
|
|
962
|
+
},
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
if ("ref" in value) {
|
|
966
|
+
const payload = tupleField(value.ref);
|
|
967
|
+
return {
|
|
968
|
+
ref: {
|
|
969
|
+
key: Uint8Array.from(payload.key),
|
|
970
|
+
chunks: Number(payload.chunks),
|
|
971
|
+
len: Number(payload.len),
|
|
972
|
+
},
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
throw new Error(`cannot decode value: ${JSON.stringify(value)}`);
|
|
976
|
+
}
|
|
977
|
+
/** Range flag bits: 0-1 endpoint inclusivity, 2-5 decimal scale. */
|
|
978
|
+
exports.RANGE_LOWER_INC = 0x01;
|
|
979
|
+
exports.RANGE_UPPER_INC = 0x02;
|
|
980
|
+
exports.RANGE_SCALE_SHIFT = 2;
|
|
981
|
+
exports.RANGE_SCALE_MASK = 0x3f;
|
|
982
|
+
/** Decimal scale carried in the range flags (0 for non-numeric ranges). */
|
|
983
|
+
function rangeScale(flags) {
|
|
984
|
+
return (flags & exports.RANGE_SCALE_MASK) >> exports.RANGE_SCALE_SHIFT;
|
|
985
|
+
}
|
|
986
|
+
function rangeEndpoint(text, column) {
|
|
987
|
+
const trimmed = text.trim();
|
|
988
|
+
switch (column.type) {
|
|
989
|
+
case "numrange": {
|
|
990
|
+
const scale = column.scale ?? 0;
|
|
991
|
+
const fraction = trimmed.includes(".") ? trimmed.split(".")[1] : "";
|
|
992
|
+
if (fraction.length > scale) {
|
|
993
|
+
throw new Error(`NUMRANGE scale mismatch: at most ${scale} decimals, got ${fraction.length}`);
|
|
994
|
+
}
|
|
995
|
+
const decimal = coerceValue(trimmed, { type: "decimal", scale });
|
|
996
|
+
return decimal.decimal;
|
|
997
|
+
}
|
|
998
|
+
case "tsrange":
|
|
999
|
+
return /^-?\d+$/.test(trimmed) ? BigInt(trimmed) : timestampTextToSeconds(trimmed);
|
|
1000
|
+
case "daterange":
|
|
1001
|
+
return /^-?\d+$/.test(trimmed) ? BigInt(trimmed) : dateTextToDays(trimmed);
|
|
1002
|
+
default:
|
|
1003
|
+
if (!/^-?\d+$/.test(trimmed))
|
|
1004
|
+
throw new Error(`invalid RANGE bound: ${text}`);
|
|
1005
|
+
return BigInt(trimmed);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function coerceRange(value, column) {
|
|
1009
|
+
const scale = column.type === "numrange" ? (column.scale ?? 0) : 0;
|
|
1010
|
+
if (scale > 15)
|
|
1011
|
+
throw new Error("NUMRANGE scale must be at most 15");
|
|
1012
|
+
if (typeof value === "string") {
|
|
1013
|
+
const trimmed = value.trim();
|
|
1014
|
+
const lower = trimmed[0];
|
|
1015
|
+
const upper = trimmed[trimmed.length - 1];
|
|
1016
|
+
if ((lower !== "[" && lower !== "(") || (upper !== "]" && upper !== ")")) {
|
|
1017
|
+
throw new Error(`invalid RANGE literal: ${value}`);
|
|
1018
|
+
}
|
|
1019
|
+
const inner = trimmed.slice(1, -1);
|
|
1020
|
+
const comma = inner.indexOf(",");
|
|
1021
|
+
if (comma < 0)
|
|
1022
|
+
throw new Error(`invalid RANGE literal: ${value}`);
|
|
1023
|
+
const unquote = (part) => {
|
|
1024
|
+
const text = part.trim();
|
|
1025
|
+
return text.length >= 2 && text.startsWith('"') && text.endsWith('"')
|
|
1026
|
+
? text.slice(1, -1)
|
|
1027
|
+
: text;
|
|
1028
|
+
};
|
|
1029
|
+
const start = rangeEndpoint(unquote(inner.slice(0, comma)), column);
|
|
1030
|
+
const end = rangeEndpoint(unquote(inner.slice(comma + 1)), column);
|
|
1031
|
+
const flags = (lower === "[" ? exports.RANGE_LOWER_INC : 0) |
|
|
1032
|
+
(upper === "]" ? exports.RANGE_UPPER_INC : 0) |
|
|
1033
|
+
(scale << exports.RANGE_SCALE_SHIFT);
|
|
1034
|
+
return { range: { start, end, flags } };
|
|
1035
|
+
}
|
|
1036
|
+
if (typeof value === "object" && value !== null && "range" in value) {
|
|
1037
|
+
const parsed = value.range;
|
|
1038
|
+
const flags = Number(parsed.flags);
|
|
1039
|
+
if ((flags & ~exports.RANGE_SCALE_MASK) !== 0)
|
|
1040
|
+
throw new Error(`invalid RANGE flags: ${flags}`);
|
|
1041
|
+
if (rangeScale(flags) !== scale) {
|
|
1042
|
+
throw new Error(`range scale mismatch: expected ${scale}`);
|
|
1043
|
+
}
|
|
1044
|
+
return {
|
|
1045
|
+
range: {
|
|
1046
|
+
start: BigInt(parsed.start.toString()),
|
|
1047
|
+
end: BigInt(parsed.end.toString()),
|
|
1048
|
+
flags,
|
|
1049
|
+
},
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
throw new Error(`cannot coerce ${String(value)} to ${column.type.toUpperCase()}`);
|
|
1053
|
+
}
|
|
1054
|
+
/** Human-readable projection of a canonical value (UUIDs become strings). */
|
|
1055
|
+
function displayValue(value, column) {
|
|
1056
|
+
if (value === null || value === undefined)
|
|
1057
|
+
return null;
|
|
1058
|
+
if (column?.type === "uuid" && value instanceof Uint8Array) {
|
|
1059
|
+
return bytesToUuid(value);
|
|
1060
|
+
}
|
|
1061
|
+
if (column?.type === "date" && typeof value === "bigint") {
|
|
1062
|
+
return daysToDateText(value);
|
|
1063
|
+
}
|
|
1064
|
+
if (column?.type === "timestamp" && typeof value === "bigint") {
|
|
1065
|
+
return secondsToTimestampText(value);
|
|
1066
|
+
}
|
|
1067
|
+
if (value && typeof value === "object" && "interval" in value) {
|
|
1068
|
+
return formatInterval(value.interval);
|
|
1069
|
+
}
|
|
1070
|
+
if (column?.type === "interval" && typeof value === "bigint") {
|
|
1071
|
+
// Legacy second-only intervals (pre calendar model).
|
|
1072
|
+
return `${value.toString()}s`;
|
|
1073
|
+
}
|
|
1074
|
+
if (value && typeof value === "object" && "inet" in value) {
|
|
1075
|
+
const parsed = value;
|
|
1076
|
+
return inetToText(parsed.inet, parsed.prefix);
|
|
1077
|
+
}
|
|
1078
|
+
if (value && typeof value === "object" && "mac" in value) {
|
|
1079
|
+
return Array.from(value.mac)
|
|
1080
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
1081
|
+
.join(":");
|
|
1082
|
+
}
|
|
1083
|
+
if (column?.type === "time" && typeof value === "bigint") {
|
|
1084
|
+
const total = Number(value);
|
|
1085
|
+
const hours = Math.floor(total / 3600);
|
|
1086
|
+
const minutes = Math.floor((total % 3600) / 60);
|
|
1087
|
+
const seconds = total % 60;
|
|
1088
|
+
return [hours, minutes, seconds]
|
|
1089
|
+
.map((part) => String(part).padStart(2, "0"))
|
|
1090
|
+
.join(":");
|
|
1091
|
+
}
|
|
1092
|
+
if (value && typeof value === "object" && "range" in value) {
|
|
1093
|
+
const parsed = value.range;
|
|
1094
|
+
const format = (bound) => {
|
|
1095
|
+
if (column?.type === "numrange") {
|
|
1096
|
+
const scale = rangeScale(parsed.flags);
|
|
1097
|
+
const negative = bound < 0n;
|
|
1098
|
+
const digits = (negative ? -bound : bound).toString().padStart(scale + 1, "0");
|
|
1099
|
+
const whole = digits.slice(0, digits.length - scale) || "0";
|
|
1100
|
+
const fraction = scale === 0 ? "" : `.${digits.slice(digits.length - scale)}`;
|
|
1101
|
+
return `${negative ? "-" : ""}${whole}${fraction}`;
|
|
1102
|
+
}
|
|
1103
|
+
if (column?.type === "tsrange")
|
|
1104
|
+
return `"${secondsToTimestampText(bound)}"`;
|
|
1105
|
+
if (column?.type === "daterange")
|
|
1106
|
+
return `"${daysToDateText(bound)}"`;
|
|
1107
|
+
return bound.toString();
|
|
1108
|
+
};
|
|
1109
|
+
return `${parsed.flags & exports.RANGE_LOWER_INC ? "[" : "("}${format(parsed.start)},${format(parsed.end)}${parsed.flags & exports.RANGE_UPPER_INC ? "]" : ")"}`;
|
|
1110
|
+
}
|
|
1111
|
+
if (value && typeof value === "object" && "bit" in value) {
|
|
1112
|
+
const parsed = value;
|
|
1113
|
+
let out = "";
|
|
1114
|
+
for (let index = 0; index < parsed.length; index += 1) {
|
|
1115
|
+
out += (parsed.bit[Math.floor(index / 8)] & (1 << (7 - (index % 8)))) !== 0 ? "1" : "0";
|
|
1116
|
+
}
|
|
1117
|
+
return out;
|
|
1118
|
+
}
|
|
1119
|
+
if (value &&
|
|
1120
|
+
typeof value === "object" &&
|
|
1121
|
+
"decimal" in value &&
|
|
1122
|
+
!(value instanceof Uint8Array)) {
|
|
1123
|
+
const d = value;
|
|
1124
|
+
const negative = d.decimal < 0n;
|
|
1125
|
+
const digits = (negative ? -d.decimal : d.decimal).toString().padStart(d.scale + 1, "0");
|
|
1126
|
+
const whole = digits.slice(0, digits.length - d.scale) || "0";
|
|
1127
|
+
const frac = d.scale > 0 ? "." + digits.slice(digits.length - d.scale) : "";
|
|
1128
|
+
return `${negative ? "-" : ""}${whole}${frac}`;
|
|
1129
|
+
}
|
|
1130
|
+
if (typeof value === "bigint")
|
|
1131
|
+
return value.toString();
|
|
1132
|
+
if (typeof value === "object" && value !== null && "address" in value) {
|
|
1133
|
+
return Buffer.from(value.address).toString("hex");
|
|
1134
|
+
}
|
|
1135
|
+
return value;
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Locale-aware MONEY formatting without floating-point loss. Granularity comes
|
|
1139
|
+
* from the column's decimal scale; the currency is presentation metadata.
|
|
1140
|
+
*/
|
|
1141
|
+
function formatMoney(value, options = {}) {
|
|
1142
|
+
if (value === null || value === undefined)
|
|
1143
|
+
return null;
|
|
1144
|
+
const text = displayValue(value);
|
|
1145
|
+
const negative = text.startsWith("-");
|
|
1146
|
+
const unsigned = negative ? text.slice(1) : text;
|
|
1147
|
+
const [whole, fraction = ""] = unsigned.split(".");
|
|
1148
|
+
const locale = options.locale ?? "en-US";
|
|
1149
|
+
const grouped = new Intl.NumberFormat(locale, { useGrouping: true }).format(BigInt(whole || "0"));
|
|
1150
|
+
const decimalSeparator = new Intl.NumberFormat(locale, { useGrouping: true })
|
|
1151
|
+
.formatToParts(1.1)
|
|
1152
|
+
.find((part) => part.type === "decimal")?.value ?? ".";
|
|
1153
|
+
const amount = `${grouped}${fraction ? decimalSeparator + fraction : ""}`;
|
|
1154
|
+
let symbol = "";
|
|
1155
|
+
let symbolAfter = false;
|
|
1156
|
+
if (options.currency) {
|
|
1157
|
+
const parts = new Intl.NumberFormat(locale, {
|
|
1158
|
+
style: "currency",
|
|
1159
|
+
currency: options.currency,
|
|
1160
|
+
}).formatToParts(0);
|
|
1161
|
+
symbol =
|
|
1162
|
+
parts.find((part) => part.type === "currency")?.value ?? options.currency;
|
|
1163
|
+
symbolAfter =
|
|
1164
|
+
parts.findIndex((part) => part.type === "currency") >
|
|
1165
|
+
parts.findIndex((part) => part.type === "integer");
|
|
1166
|
+
const gap = parts.find((part) => part.type === "literal")?.value ?? "";
|
|
1167
|
+
symbol = symbolAfter ? gap + symbol : symbol + gap;
|
|
1168
|
+
}
|
|
1169
|
+
return `${negative ? "-" : ""}${symbolAfter ? "" : symbol}${amount}${symbolAfter ? symbol : ""}`;
|
|
1170
|
+
}
|
|
1171
|
+
// ---------------------------------------------------------------------------
|
|
1172
|
+
// Calendar intervals
|
|
1173
|
+
// ---------------------------------------------------------------------------
|
|
1174
|
+
exports.MICROS_PER_SECOND = 1000000n;
|
|
1175
|
+
exports.MICROS_PER_MINUTE = 60n * exports.MICROS_PER_SECOND;
|
|
1176
|
+
exports.MICROS_PER_HOUR = 60n * exports.MICROS_PER_MINUTE;
|
|
1177
|
+
exports.SECONDS_PER_DAY = 86400n;
|
|
1178
|
+
exports.MICROS_PER_DAY = exports.SECONDS_PER_DAY * exports.MICROS_PER_SECOND;
|
|
1179
|
+
/** PostgreSQL compares/normalises intervals with a 30-day month. */
|
|
1180
|
+
function intervalTotalMicros(interval) {
|
|
1181
|
+
return (BigInt(interval.months) * 30n * exports.MICROS_PER_DAY +
|
|
1182
|
+
BigInt(interval.days) * exports.MICROS_PER_DAY +
|
|
1183
|
+
interval.micros);
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Parses PostgreSQL interval text: `1 year 2 mons 3 days 04:05:06.789`, the
|
|
1187
|
+
* `Y-M-D` date form, and plain unit lists. A bare number is seconds, matching
|
|
1188
|
+
* `interval '5'`.
|
|
1189
|
+
*/
|
|
1190
|
+
function parseInterval(text) {
|
|
1191
|
+
const raw = text.trim().toLowerCase();
|
|
1192
|
+
if (!raw)
|
|
1193
|
+
throw new Error("empty INTERVAL literal");
|
|
1194
|
+
let months = 0;
|
|
1195
|
+
let days = 0;
|
|
1196
|
+
let micros = 0n;
|
|
1197
|
+
// PostgreSQL date form: "3-4" (years-months) and "3-4-5" (y-m-d).
|
|
1198
|
+
const dateForm = /^([+-]?\d+)-([+-]?\d+)(?:-([+-]?\d+))?$/.exec(raw);
|
|
1199
|
+
if (dateForm) {
|
|
1200
|
+
months = Number(dateForm[1]) * 12 + Number(dateForm[2]);
|
|
1201
|
+
days = dateForm[3] ? Number(dateForm[3]) : 0;
|
|
1202
|
+
return { interval: { months, days, micros } };
|
|
1203
|
+
}
|
|
1204
|
+
const timeMatch = /([+-]?\d+):(\d{1,2})(?::(\d{1,2})(?:\.(\d+))?)?/.exec(raw);
|
|
1205
|
+
if (timeMatch) {
|
|
1206
|
+
const sign = timeMatch[0].startsWith("-") ? -1n : 1n;
|
|
1207
|
+
const hours = BigInt(timeMatch[1].replace("-", "")) * exports.MICROS_PER_HOUR;
|
|
1208
|
+
const minutes = BigInt(timeMatch[2]) * exports.MICROS_PER_MINUTE;
|
|
1209
|
+
const seconds = BigInt(timeMatch[3] ?? "0") * exports.MICROS_PER_SECOND;
|
|
1210
|
+
const fraction = timeMatch[4] ? BigInt(timeMatch[4].padEnd(6, "0").slice(0, 6)) : 0n;
|
|
1211
|
+
micros += sign * (hours + minutes + seconds + fraction);
|
|
1212
|
+
}
|
|
1213
|
+
const units = {
|
|
1214
|
+
y: { months: 12 },
|
|
1215
|
+
yr: { months: 12 },
|
|
1216
|
+
yrs: { months: 12 },
|
|
1217
|
+
year: { months: 12 },
|
|
1218
|
+
years: { months: 12 },
|
|
1219
|
+
mon: { months: 1 },
|
|
1220
|
+
mons: { months: 1 },
|
|
1221
|
+
month: { months: 1 },
|
|
1222
|
+
months: { months: 1 },
|
|
1223
|
+
w: { days: 7 },
|
|
1224
|
+
wk: { days: 7 },
|
|
1225
|
+
wks: { days: 7 },
|
|
1226
|
+
week: { days: 7 },
|
|
1227
|
+
weeks: { days: 7 },
|
|
1228
|
+
d: { days: 1 },
|
|
1229
|
+
day: { days: 1 },
|
|
1230
|
+
days: { days: 1 },
|
|
1231
|
+
h: { micros: exports.MICROS_PER_HOUR },
|
|
1232
|
+
hr: { micros: exports.MICROS_PER_HOUR },
|
|
1233
|
+
hrs: { micros: exports.MICROS_PER_HOUR },
|
|
1234
|
+
hour: { micros: exports.MICROS_PER_HOUR },
|
|
1235
|
+
hours: { micros: exports.MICROS_PER_HOUR },
|
|
1236
|
+
m: { micros: exports.MICROS_PER_MINUTE },
|
|
1237
|
+
min: { micros: exports.MICROS_PER_MINUTE },
|
|
1238
|
+
mins: { micros: exports.MICROS_PER_MINUTE },
|
|
1239
|
+
minute: { micros: exports.MICROS_PER_MINUTE },
|
|
1240
|
+
minutes: { micros: exports.MICROS_PER_MINUTE },
|
|
1241
|
+
s: { micros: exports.MICROS_PER_SECOND },
|
|
1242
|
+
sec: { micros: exports.MICROS_PER_SECOND },
|
|
1243
|
+
secs: { micros: exports.MICROS_PER_SECOND },
|
|
1244
|
+
second: { micros: exports.MICROS_PER_SECOND },
|
|
1245
|
+
seconds: { micros: exports.MICROS_PER_SECOND },
|
|
1246
|
+
ms: { micros: 1000n },
|
|
1247
|
+
msec: { micros: 1000n },
|
|
1248
|
+
usec: { micros: 1n },
|
|
1249
|
+
us: { micros: 1n },
|
|
1250
|
+
};
|
|
1251
|
+
const pattern = /([+-]?\d+(?:\.\d+)?)\s*([a-z]+)/g;
|
|
1252
|
+
let matched = false;
|
|
1253
|
+
for (let match = pattern.exec(raw); match; match = pattern.exec(raw)) {
|
|
1254
|
+
const unit = units[match[2]];
|
|
1255
|
+
if (!unit)
|
|
1256
|
+
throw new Error(`unsupported INTERVAL unit: ${match[2]}`);
|
|
1257
|
+
matched = true;
|
|
1258
|
+
const amount = Number(match[1]);
|
|
1259
|
+
if (unit.months)
|
|
1260
|
+
months += Math.round(amount * unit.months);
|
|
1261
|
+
if (unit.days)
|
|
1262
|
+
days += Math.round(amount * unit.days);
|
|
1263
|
+
if (unit.micros)
|
|
1264
|
+
micros += BigInt(Math.round(amount * Number(unit.micros)));
|
|
1265
|
+
}
|
|
1266
|
+
if (matched || timeMatch)
|
|
1267
|
+
return { interval: { months, days, micros } };
|
|
1268
|
+
if (/^[+-]?\d+(?:\.\d+)?$/.test(raw)) {
|
|
1269
|
+
return { interval: { months: 0, days: 0, micros: BigInt(Math.round(Number(raw) * 1e6)) } };
|
|
1270
|
+
}
|
|
1271
|
+
throw new Error(`invalid INTERVAL literal: ${text}`);
|
|
1272
|
+
}
|
|
1273
|
+
/** Canonical PostgreSQL-style text for an interval. */
|
|
1274
|
+
function formatInterval(interval) {
|
|
1275
|
+
const parts = [];
|
|
1276
|
+
if (interval.months !== 0) {
|
|
1277
|
+
const years = Math.trunc(interval.months / 12);
|
|
1278
|
+
const mons = interval.months % 12;
|
|
1279
|
+
if (years !== 0)
|
|
1280
|
+
parts.push(`${years} year${Math.abs(years) === 1 ? "" : "s"}`);
|
|
1281
|
+
if (mons !== 0)
|
|
1282
|
+
parts.push(`${mons} mon${Math.abs(mons) === 1 ? "" : "s"}`);
|
|
1283
|
+
}
|
|
1284
|
+
if (interval.days !== 0) {
|
|
1285
|
+
parts.push(`${interval.days} day${Math.abs(interval.days) === 1 ? "" : "s"}`);
|
|
1286
|
+
}
|
|
1287
|
+
let micros = interval.micros;
|
|
1288
|
+
if (micros !== 0n || parts.length === 0) {
|
|
1289
|
+
const negative = micros < 0n;
|
|
1290
|
+
if (negative)
|
|
1291
|
+
micros = -micros;
|
|
1292
|
+
const hours = micros / exports.MICROS_PER_HOUR;
|
|
1293
|
+
const minutes = (micros % exports.MICROS_PER_HOUR) / exports.MICROS_PER_MINUTE;
|
|
1294
|
+
const seconds = (micros % exports.MICROS_PER_MINUTE) / exports.MICROS_PER_SECOND;
|
|
1295
|
+
const fraction = micros % exports.MICROS_PER_SECOND;
|
|
1296
|
+
const time = [hours, minutes, seconds]
|
|
1297
|
+
.map((part) => part.toString().padStart(2, "0"))
|
|
1298
|
+
.join(":");
|
|
1299
|
+
const frac = fraction === 0n ? "" : `.${fraction.toString().padStart(6, "0").replace(/0+$/, "")}`;
|
|
1300
|
+
parts.push(`${negative ? "-" : ""}${time}${frac}`);
|
|
1301
|
+
}
|
|
1302
|
+
return parts.join(" ");
|
|
1303
|
+
}
|
|
1304
|
+
/** Days in a proleptic Gregorian month (month is 1-12). */
|
|
1305
|
+
function daysInMonth(year, month) {
|
|
1306
|
+
if (month === 2) {
|
|
1307
|
+
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
1308
|
+
return leap ? 29 : 28;
|
|
1309
|
+
}
|
|
1310
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
1311
|
+
}
|
|
1312
|
+
/** Days since 1970-01-01 to a civil date (Howard Hinnant). */
|
|
1313
|
+
function civilFromDays(days) {
|
|
1314
|
+
const z = Number(days) + 719468;
|
|
1315
|
+
const era = Math.floor((z >= 0 ? z : z - 146096) / 146097);
|
|
1316
|
+
const doe = z - era * 146097;
|
|
1317
|
+
const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
|
|
1318
|
+
const y = yoe + era * 400;
|
|
1319
|
+
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
|
|
1320
|
+
const mp = Math.floor((5 * doy + 2) / 153);
|
|
1321
|
+
const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
|
|
1322
|
+
const month = mp < 10 ? mp + 3 : mp - 9;
|
|
1323
|
+
return { year: month <= 2 ? y + 1 : y, month, day };
|
|
1324
|
+
}
|
|
1325
|
+
/** Civil date to days since 1970-01-01 (Howard Hinnant). */
|
|
1326
|
+
function daysFromCivil(year, month, day) {
|
|
1327
|
+
const y = month <= 2 ? year - 1 : year;
|
|
1328
|
+
const era = Math.floor((y >= 0 ? y : y - 399) / 400);
|
|
1329
|
+
const yoe = y - era * 400;
|
|
1330
|
+
const m = month;
|
|
1331
|
+
const doy = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + day - 1;
|
|
1332
|
+
const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
|
|
1333
|
+
return BigInt(era * 146097 + doe - 719468);
|
|
1334
|
+
}
|
|
1335
|
+
/** Adds calendar months to a day count, clamping the day to the target month. */
|
|
1336
|
+
function addMonthsToDays(days, months) {
|
|
1337
|
+
if (months === 0)
|
|
1338
|
+
return days;
|
|
1339
|
+
const { year, month, day } = civilFromDays(days);
|
|
1340
|
+
const total = year * 12 + (month - 1) + months;
|
|
1341
|
+
const newYear = Math.floor(total / 12);
|
|
1342
|
+
const newMonth = ((total % 12) + 12) % 12 + 1;
|
|
1343
|
+
const newDay = Math.min(day, daysInMonth(newYear, newMonth));
|
|
1344
|
+
return daysFromCivil(newYear, newMonth, newDay);
|
|
1345
|
+
}
|
|
1346
|
+
/** `DATE + INTERVAL`; rejects a sub-day part because DATE is whole days. */
|
|
1347
|
+
function dateAddInterval(days, interval) {
|
|
1348
|
+
if (interval.micros !== 0n) {
|
|
1349
|
+
throw new Error("DATE arithmetic with a sub-day INTERVAL requires a TIMESTAMP column");
|
|
1350
|
+
}
|
|
1351
|
+
return addMonthsToDays(days, interval.months) + BigInt(interval.days);
|
|
1352
|
+
}
|
|
1353
|
+
/** `TIMESTAMP + INTERVAL`; the time of day is preserved and month-ends clamp. */
|
|
1354
|
+
function timestampAddInterval(seconds, interval) {
|
|
1355
|
+
if (interval.micros % exports.MICROS_PER_SECOND !== 0n) {
|
|
1356
|
+
throw new Error("TIMESTAMP arithmetic with sub-second INTERVAL precision");
|
|
1357
|
+
}
|
|
1358
|
+
const baseDays = seconds / exports.SECONDS_PER_DAY - (seconds % exports.SECONDS_PER_DAY < 0n ? 1n : 0n);
|
|
1359
|
+
const timeOfDay = seconds - baseDays * exports.SECONDS_PER_DAY;
|
|
1360
|
+
const newDays = addMonthsToDays(baseDays, interval.months) + BigInt(interval.days);
|
|
1361
|
+
return newDays * exports.SECONDS_PER_DAY + timeOfDay + interval.micros / exports.MICROS_PER_SECOND;
|
|
1362
|
+
}
|