@eidos.space/eidos-file 0.1.0 → 2.0.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/DEVELOPER_PLATFORM.md +55 -53
- package/FIELD-CONVERSION.md +75 -0
- package/README.md +89 -106
- package/dist/adapter-contract-BRKKEulb.d.mts +1110 -0
- package/dist/adapter-contract-BRKKEulb.d.mts.map +1 -0
- package/dist/better-sqlite3.d.mts +64 -3
- package/dist/better-sqlite3.d.mts.map +1 -1
- package/dist/better-sqlite3.mjs +395 -14
- package/dist/better-sqlite3.mjs.map +1 -1
- package/dist/browser.d.mts +4 -3
- package/dist/browser.d.mts.map +1 -1
- package/dist/browser.mjs +30 -11
- package/dist/browser.mjs.map +1 -1
- package/dist/csv-BQPkzC5Y.mjs +386 -0
- package/dist/csv-BQPkzC5Y.mjs.map +1 -0
- package/dist/csv.d.mts +4 -2
- package/dist/csv.d.mts.map +1 -1
- package/dist/csv.mjs +1 -248
- package/dist/index.d.mts +327 -18
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3555 -4
- package/dist/index.mjs.map +1 -0
- package/dist/node-sqlite.d.mts +98 -0
- package/dist/node-sqlite.d.mts.map +1 -0
- package/dist/node-sqlite.mjs +684 -0
- package/dist/node-sqlite.mjs.map +1 -0
- package/dist/runtime-9_adwQ0y.mjs +5637 -0
- package/dist/runtime-9_adwQ0y.mjs.map +1 -0
- package/dist/runtime-C9IcEeTi.d.mts +728 -0
- package/dist/runtime-C9IcEeTi.d.mts.map +1 -0
- package/dist/select-options-CfNwfc_a.mjs +561 -0
- package/dist/select-options-CfNwfc_a.mjs.map +1 -0
- package/dist/sqlite-wasm-BM6hsxH8.mjs +2007 -0
- package/dist/sqlite-wasm-BM6hsxH8.mjs.map +1 -0
- package/dist/temporal-fyRCzJjy.d.mts +517 -0
- package/dist/temporal-fyRCzJjy.d.mts.map +1 -0
- package/package.json +11 -4
- package/dist/csv.mjs.map +0 -1
- package/dist/host-CqP1MeMK.d.mts +0 -213
- package/dist/host-CqP1MeMK.d.mts.map +0 -1
- package/dist/host-D5kZAhga.mjs +0 -478
- package/dist/host-D5kZAhga.mjs.map +0 -1
- package/dist/relation-values-B0JhHBjZ.mjs +0 -232
- package/dist/relation-values-B0JhHBjZ.mjs.map +0 -1
- package/dist/runtime-C3bstvB8.d.mts +0 -465
- package/dist/runtime-C3bstvB8.d.mts.map +0 -1
- package/dist/runtime-CWC5y95G.mjs +0 -2907
- package/dist/runtime-CWC5y95G.mjs.map +0 -1
|
@@ -0,0 +1,2007 @@
|
|
|
1
|
+
import { k as canonicalizeEidosFileJson } from "./select-options-CfNwfc_a.mjs";
|
|
2
|
+
import { G as EIDOS_FILE_FORMAT, H as EIDOS_FILE_EXTENSION, X as EIDOS_FILE_MIME_TYPE, ct as EidosAdapterError, dt as assertUnicodeString, ft as exactConnectionBindingCount, g as parseNonNegativeInt64, lt as assertExactConnectionBindings, m as MemoryByteSource, ut as assertInt64Decimal } from "./runtime-9_adwQ0y.mjs";
|
|
3
|
+
//#region src/adapter-transport.ts
|
|
4
|
+
const EIDOS_ADAPTER_TRANSPORT_LIMITS = Object.freeze({
|
|
5
|
+
maxOutstandingRequests: 32,
|
|
6
|
+
maxQueuedBytes: 16 * 1024 * 1024,
|
|
7
|
+
maxRequestBytes: 8 * 1024 * 1024,
|
|
8
|
+
maxResponseBytes: 16 * 1024 * 1024,
|
|
9
|
+
defaultTimeoutMs: 3e4,
|
|
10
|
+
maxTimeoutMs: 3e5,
|
|
11
|
+
commitAckTimeoutMs: 5e3
|
|
12
|
+
});
|
|
13
|
+
const RUNTIME_OPERATIONS = new Set([
|
|
14
|
+
"negotiate",
|
|
15
|
+
"getSnapshot",
|
|
16
|
+
"getSchemaPage",
|
|
17
|
+
"queryRows",
|
|
18
|
+
"getRowsById",
|
|
19
|
+
"aggregate",
|
|
20
|
+
"groupRows",
|
|
21
|
+
"queryGroupRows",
|
|
22
|
+
"previewFormula",
|
|
23
|
+
"mutateRows",
|
|
24
|
+
"revertMutation",
|
|
25
|
+
"mutateView",
|
|
26
|
+
"preflightSchema",
|
|
27
|
+
"getSchemaPlanDependencies",
|
|
28
|
+
"mutateSchema",
|
|
29
|
+
"validate",
|
|
30
|
+
"exportCsv",
|
|
31
|
+
"importCsv"
|
|
32
|
+
]);
|
|
33
|
+
const PREPARED_OPERATIONS = new Set([
|
|
34
|
+
"mutateRows",
|
|
35
|
+
"revertMutation",
|
|
36
|
+
"mutateView",
|
|
37
|
+
"mutateSchema",
|
|
38
|
+
"importCsv"
|
|
39
|
+
]);
|
|
40
|
+
function validateAdapterCarrier(carrier) {
|
|
41
|
+
if (!isRecord(carrier) || !("envelope" in carrier) || !("buffers" in carrier)) throw adapterFailure("protocol-error", "Carrier must contain envelope and buffers", true);
|
|
42
|
+
if (!Array.isArray(carrier.buffers) || !carrier.buffers.every((item) => item instanceof ArrayBuffer)) throw adapterFailure("protocol-error", "Carrier buffers must be ArrayBuffer values", true);
|
|
43
|
+
const buffers = carrier.buffers;
|
|
44
|
+
validateAdapterEnvelope(carrier.envelope);
|
|
45
|
+
const descriptors = "attachments" in carrier.envelope ? carrier.envelope.attachments ?? [] : [];
|
|
46
|
+
if (descriptors.length !== carrier.buffers.length) throw adapterFailure("protocol-error", "Attachment descriptor count mismatch", true);
|
|
47
|
+
const ids = /* @__PURE__ */ new Set();
|
|
48
|
+
const slots = /* @__PURE__ */ new Set();
|
|
49
|
+
descriptors.forEach((descriptor, index) => {
|
|
50
|
+
if (!isRecord(descriptor) || !opaque(descriptor.id) || !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(String(descriptor.slot)) || !safeNonNegativeInteger(descriptor.byteLength) || ids.has(String(descriptor.id)) || slots.has(String(descriptor.slot)) || buffers[index].byteLength !== descriptor.byteLength) throw adapterFailure("protocol-error", "Invalid attachment descriptor", true);
|
|
51
|
+
ids.add(String(descriptor.id));
|
|
52
|
+
slots.add(String(descriptor.slot));
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function validateAdapterEnvelope(envelope) {
|
|
56
|
+
if (!isRecord(envelope) || envelope.protocol !== "eidos-adapter" || typeof envelope.kind !== "string") throw adapterFailure("protocol-error", "Invalid Adapter envelope", true);
|
|
57
|
+
assertJsonValue(envelope);
|
|
58
|
+
if (envelope.kind === "hello") {
|
|
59
|
+
exactKeys(envelope, [
|
|
60
|
+
"kind",
|
|
61
|
+
"protocol",
|
|
62
|
+
"versions"
|
|
63
|
+
]);
|
|
64
|
+
if (!Array.isArray(envelope.versions) || envelope.versions.length < 1 || !envelope.versions.every((item) => typeof item === "string")) throw adapterFailure("protocol-error", "Invalid Adapter hello", true);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (envelope.kind === "hello-error") {
|
|
68
|
+
exactKeys(envelope, [
|
|
69
|
+
"kind",
|
|
70
|
+
"protocol",
|
|
71
|
+
"error"
|
|
72
|
+
]);
|
|
73
|
+
validateAdapterError(envelope.error);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (envelope.version !== "1.0" || !opaque(envelope.epoch) || !opaque(envelope.sessionID)) throw adapterFailure("protocol-error", "Invalid Adapter session binding", true);
|
|
77
|
+
switch (envelope.kind) {
|
|
78
|
+
case "hello-result":
|
|
79
|
+
exactKeys(envelope, [
|
|
80
|
+
"kind",
|
|
81
|
+
"protocol",
|
|
82
|
+
"version",
|
|
83
|
+
"epoch",
|
|
84
|
+
"sessionID",
|
|
85
|
+
"limits",
|
|
86
|
+
"cancelMode"
|
|
87
|
+
]);
|
|
88
|
+
validateTransportLimits(envelope.limits);
|
|
89
|
+
if (envelope.cancelMode !== "interrupt" && envelope.cancelMode !== "terminate") throw adapterFailure("protocol-error", "Invalid cancel mode", true);
|
|
90
|
+
return;
|
|
91
|
+
case "request":
|
|
92
|
+
exactKeys(envelope, [
|
|
93
|
+
"kind",
|
|
94
|
+
"protocol",
|
|
95
|
+
"version",
|
|
96
|
+
"epoch",
|
|
97
|
+
"sessionID",
|
|
98
|
+
"requestID",
|
|
99
|
+
"sequence",
|
|
100
|
+
"timeoutMs",
|
|
101
|
+
"operation",
|
|
102
|
+
"payload",
|
|
103
|
+
"attachments"
|
|
104
|
+
], true);
|
|
105
|
+
requestCorrelation(envelope);
|
|
106
|
+
if (!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(String(envelope.operation))) throw adapterFailure("protocol-error", "Invalid Runtime operation", true);
|
|
107
|
+
validateAttachments(envelope.attachments);
|
|
108
|
+
return;
|
|
109
|
+
case "response":
|
|
110
|
+
requestCorrelation(envelope);
|
|
111
|
+
if (typeof envelope.ok !== "boolean") throw adapterFailure("protocol-error", "Invalid response status", true);
|
|
112
|
+
if (envelope.ok) validateAttachments(envelope.attachments);
|
|
113
|
+
else validateWireError(envelope.error);
|
|
114
|
+
return;
|
|
115
|
+
case "commit-prepared":
|
|
116
|
+
requestCorrelation(envelope);
|
|
117
|
+
validateCommitReceipt(envelope.receipt);
|
|
118
|
+
return;
|
|
119
|
+
case "commit-ack":
|
|
120
|
+
requestCorrelation(envelope);
|
|
121
|
+
if (!opaque(envelope.receiptID) || !sha256(envelope.requestDigest)) throw adapterFailure("protocol-error", "Invalid commit acknowledgement", true);
|
|
122
|
+
return;
|
|
123
|
+
case "cancel":
|
|
124
|
+
requestId(envelope.requestID);
|
|
125
|
+
return;
|
|
126
|
+
case "close":
|
|
127
|
+
requestId(envelope.requestID);
|
|
128
|
+
if (envelope.timeoutMs !== void 0) positiveSafeInteger(envelope.timeoutMs, "timeoutMs");
|
|
129
|
+
return;
|
|
130
|
+
case "close-result":
|
|
131
|
+
requestId(envelope.requestID);
|
|
132
|
+
return;
|
|
133
|
+
default: throw adapterFailure("protocol-error", "Unknown Adapter envelope kind", true);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
var AdapterTransportServer = class {
|
|
137
|
+
commitBarrier;
|
|
138
|
+
runtime = null;
|
|
139
|
+
limits;
|
|
140
|
+
sequence = 0;
|
|
141
|
+
queue = Promise.resolve();
|
|
142
|
+
active = null;
|
|
143
|
+
pendingAck = null;
|
|
144
|
+
helloComplete = false;
|
|
145
|
+
closing = false;
|
|
146
|
+
closed = false;
|
|
147
|
+
queuedBytes = 0;
|
|
148
|
+
outstandingRequests = 0;
|
|
149
|
+
constructor(send, options) {
|
|
150
|
+
this.send = send;
|
|
151
|
+
this.options = options;
|
|
152
|
+
opaqueOrThrow(options.epoch, "epoch");
|
|
153
|
+
opaqueOrThrow(options.sessionID, "sessionID");
|
|
154
|
+
opaqueOrThrow(options.workingID, "workingID");
|
|
155
|
+
this.limits = { ...options.limits ?? EIDOS_ADAPTER_TRANSPORT_LIMITS };
|
|
156
|
+
validateTransportLimits(this.limits);
|
|
157
|
+
this.commitBarrier = { prepare: (preparation, context) => this.prepareCommit(preparation, context) };
|
|
158
|
+
}
|
|
159
|
+
attachRuntime(runtime) {
|
|
160
|
+
if (this.runtime) throw new Error("Runtime is already attached");
|
|
161
|
+
this.runtime = runtime;
|
|
162
|
+
}
|
|
163
|
+
receive(carrier) {
|
|
164
|
+
try {
|
|
165
|
+
validateAdapterCarrier(carrier);
|
|
166
|
+
const envelope = carrier.envelope;
|
|
167
|
+
if (envelope.kind === "hello") {
|
|
168
|
+
this.receiveHello(envelope);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if ("epoch" in envelope && (envelope.epoch !== this.options.epoch || envelope.sessionID !== this.options.sessionID)) return;
|
|
172
|
+
if (!this.helloComplete || this.closed) return;
|
|
173
|
+
if (envelope.kind === "cancel") {
|
|
174
|
+
this.runtime?.cancel({ requestId: envelope.requestID });
|
|
175
|
+
if (this.pendingAck?.receipt.requestID === envelope.requestID && !this.pendingAck.accepted) this.pendingAck.reject(adapterFailure("cancelled", "Request was cancelled", false, true));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (envelope.kind === "commit-ack") {
|
|
179
|
+
this.receiveCommitAck(envelope);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (envelope.kind === "close") {
|
|
183
|
+
this.receiveClose(envelope);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (envelope.kind !== "request") {
|
|
187
|
+
this.fatal("Unexpected client envelope");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
this.receiveRequest(envelope, carrier.buffers);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const failure = adapterError(error);
|
|
193
|
+
if (failure.fatal) this.fatal(failure.message);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
receiveHello(envelope) {
|
|
197
|
+
if (this.helloComplete || this.closed || !envelope.versions.includes("1.0")) {
|
|
198
|
+
this.post({
|
|
199
|
+
kind: "hello-error",
|
|
200
|
+
protocol: "eidos-adapter",
|
|
201
|
+
error: adapterFailure("unsupported-capability", "Eidos Adapter 1.0 is required", false)
|
|
202
|
+
});
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
this.helloComplete = true;
|
|
206
|
+
this.post({
|
|
207
|
+
kind: "hello-result",
|
|
208
|
+
protocol: "eidos-adapter",
|
|
209
|
+
version: "1.0",
|
|
210
|
+
epoch: this.options.epoch,
|
|
211
|
+
sessionID: this.options.sessionID,
|
|
212
|
+
limits: { ...this.limits },
|
|
213
|
+
cancelMode: this.options.cancelMode
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
receiveRequest(envelope, buffers) {
|
|
217
|
+
if (this.closing || !this.runtime) {
|
|
218
|
+
this.failure(envelope, adapterFailure("transport-closed", "Transport is closing", false));
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (envelope.sequence !== this.sequence + 1) {
|
|
222
|
+
this.fatal("Request sequence is not contiguous");
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (!RUNTIME_OPERATIONS.has(envelope.operation)) {
|
|
226
|
+
this.failure(envelope, adapterFailure("protocol-error", "Unknown Runtime operation", false));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const size = carrierBytes({
|
|
230
|
+
envelope,
|
|
231
|
+
buffers
|
|
232
|
+
});
|
|
233
|
+
if (size > this.limits.maxRequestBytes) {
|
|
234
|
+
this.failure(envelope, adapterFailure("resource-limit", "Request exceeds maxRequestBytes", false));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (this.queuedBytes + size > this.limits.maxQueuedBytes) {
|
|
238
|
+
this.failure(envelope, adapterFailure("backpressure", "Transport queue is full", false, true));
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (this.outstandingRequests >= this.limits.maxOutstandingRequests) {
|
|
242
|
+
this.failure(envelope, adapterFailure("backpressure", "Too many outstanding requests", false, true));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
this.sequence = envelope.sequence;
|
|
246
|
+
this.queuedBytes += size;
|
|
247
|
+
this.outstandingRequests += 1;
|
|
248
|
+
const task = async () => {
|
|
249
|
+
this.queuedBytes -= size;
|
|
250
|
+
try {
|
|
251
|
+
await this.executeRequest(envelope, buffers);
|
|
252
|
+
} finally {
|
|
253
|
+
this.outstandingRequests -= 1;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
this.queue = this.queue.then(task, task);
|
|
257
|
+
}
|
|
258
|
+
async executeRequest(envelope, buffers) {
|
|
259
|
+
if (!this.runtime || this.closed) return;
|
|
260
|
+
try {
|
|
261
|
+
const payload = requestPayload(envelope, buffers);
|
|
262
|
+
this.active = {
|
|
263
|
+
envelope,
|
|
264
|
+
buffers,
|
|
265
|
+
requestDigest: await digestRequest(envelope, buffers, this.options.workingID)
|
|
266
|
+
};
|
|
267
|
+
const method = this.runtime[envelope.operation];
|
|
268
|
+
if (typeof method !== "function") throw runtimeFailure("unsupported", "Runtime operation is unavailable");
|
|
269
|
+
const timeoutMs = Math.min(envelope.timeoutMs ?? this.limits.defaultTimeoutMs, this.limits.maxTimeoutMs);
|
|
270
|
+
const result = await method.call(this.runtime, payload, {
|
|
271
|
+
requestId: envelope.requestID,
|
|
272
|
+
deadlineMilliseconds: timeoutMs
|
|
273
|
+
});
|
|
274
|
+
const response = responsePayload(envelope.operation, result);
|
|
275
|
+
const responseCarrier = {
|
|
276
|
+
envelope: {
|
|
277
|
+
kind: "response",
|
|
278
|
+
protocol: "eidos-adapter",
|
|
279
|
+
version: "1.0",
|
|
280
|
+
epoch: this.options.epoch,
|
|
281
|
+
sessionID: this.options.sessionID,
|
|
282
|
+
requestID: envelope.requestID,
|
|
283
|
+
sequence: envelope.sequence,
|
|
284
|
+
ok: true,
|
|
285
|
+
result: response.result,
|
|
286
|
+
...response.attachments.length > 0 ? { attachments: response.attachments.map((entry) => entry.descriptor) } : {}
|
|
287
|
+
},
|
|
288
|
+
buffers: response.attachments.map((entry) => entry.buffer)
|
|
289
|
+
};
|
|
290
|
+
if (carrierBytes(responseCarrier) > this.limits.maxResponseBytes) throw runtimeFailure("resource-limit", "Response exceeds maxResponseBytes");
|
|
291
|
+
this.send(responseCarrier, responseCarrier.buffers);
|
|
292
|
+
if (this.pendingAck?.accepted) this.options.settlePreparedReceipt?.(this.pendingAck.receipt, true);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
const runtime = runtimeErrorFromUnknown(error);
|
|
295
|
+
this.post({
|
|
296
|
+
kind: "response",
|
|
297
|
+
protocol: "eidos-adapter",
|
|
298
|
+
version: "1.0",
|
|
299
|
+
epoch: this.options.epoch,
|
|
300
|
+
sessionID: this.options.sessionID,
|
|
301
|
+
requestID: envelope.requestID,
|
|
302
|
+
sequence: envelope.sequence,
|
|
303
|
+
ok: false,
|
|
304
|
+
error: {
|
|
305
|
+
source: "runtime",
|
|
306
|
+
error: runtime
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
if (this.pendingAck && !this.pendingAck.accepted) this.options.settlePreparedReceipt?.(this.pendingAck.receipt, false);
|
|
310
|
+
} finally {
|
|
311
|
+
this.active = null;
|
|
312
|
+
if (this.pendingAck) clearTimeout(this.pendingAck.timer);
|
|
313
|
+
this.pendingAck = null;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async prepareCommit(preparation, _context) {
|
|
317
|
+
const active = this.active;
|
|
318
|
+
if (!active || !PREPARED_OPERATIONS.has(active.envelope.operation) || this.pendingAck) throw adapterFailure("protocol-error", "Commit barrier is outside a prepared mutation", true);
|
|
319
|
+
const receipt = {
|
|
320
|
+
protocol: "eidos-commit-receipt",
|
|
321
|
+
version: "1.0",
|
|
322
|
+
receiptID: this.options.allocateReceiptID(),
|
|
323
|
+
epoch: this.options.epoch,
|
|
324
|
+
sessionID: this.options.sessionID,
|
|
325
|
+
workingID: this.options.workingID,
|
|
326
|
+
requestID: active.envelope.requestID,
|
|
327
|
+
sequence: active.envelope.sequence,
|
|
328
|
+
operation: active.envelope.operation,
|
|
329
|
+
fileID: preparation.fileID,
|
|
330
|
+
baseRevision: preparation.baseRevision,
|
|
331
|
+
commitRevision: preparation.commitRevision,
|
|
332
|
+
requestDigest: active.requestDigest,
|
|
333
|
+
reconciliation: preparation.reconciliation
|
|
334
|
+
};
|
|
335
|
+
validateCommitReceipt(receipt);
|
|
336
|
+
validateReceiptSemantics(receipt, active.envelope.operation);
|
|
337
|
+
const prepared = {
|
|
338
|
+
kind: "commit-prepared",
|
|
339
|
+
protocol: "eidos-adapter",
|
|
340
|
+
version: "1.0",
|
|
341
|
+
epoch: this.options.epoch,
|
|
342
|
+
sessionID: this.options.sessionID,
|
|
343
|
+
requestID: active.envelope.requestID,
|
|
344
|
+
sequence: active.envelope.sequence,
|
|
345
|
+
receipt
|
|
346
|
+
};
|
|
347
|
+
if (carrierBytes({
|
|
348
|
+
envelope: prepared,
|
|
349
|
+
buffers: []
|
|
350
|
+
}) > this.limits.maxResponseBytes) throw adapterFailure("resource-limit", "Prepared receipt exceeds maxResponseBytes", false);
|
|
351
|
+
this.options.retainPreparedReceipt?.(receipt);
|
|
352
|
+
await new Promise((resolve, reject) => {
|
|
353
|
+
this.pendingAck = {
|
|
354
|
+
receipt,
|
|
355
|
+
resolve,
|
|
356
|
+
reject,
|
|
357
|
+
timer: setTimeout(() => {
|
|
358
|
+
reject(adapterFailure("deadline-exceeded", "Commit acknowledgement timed out", false, true));
|
|
359
|
+
}, this.limits.commitAckTimeoutMs),
|
|
360
|
+
accepted: false
|
|
361
|
+
};
|
|
362
|
+
this.post(prepared);
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
receiveCommitAck(envelope) {
|
|
366
|
+
const pending = this.pendingAck;
|
|
367
|
+
if (!pending) {
|
|
368
|
+
this.fatal("Commit acknowledgement has no preparation");
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const receipt = pending.receipt;
|
|
372
|
+
if (envelope.requestID !== receipt.requestID || envelope.sequence !== receipt.sequence || envelope.receiptID !== receipt.receiptID || envelope.requestDigest !== receipt.requestDigest) {
|
|
373
|
+
pending.reject(adapterFailure("protocol-error", "Commit acknowledgement mismatch", true));
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (pending.accepted) return;
|
|
377
|
+
pending.accepted = true;
|
|
378
|
+
clearTimeout(pending.timer);
|
|
379
|
+
pending.resolve();
|
|
380
|
+
}
|
|
381
|
+
receiveClose(envelope) {
|
|
382
|
+
if (this.closing) return;
|
|
383
|
+
this.closing = true;
|
|
384
|
+
const task = async () => {
|
|
385
|
+
try {
|
|
386
|
+
await this.runtime?.close({
|
|
387
|
+
requestId: envelope.requestID,
|
|
388
|
+
...envelope.timeoutMs === void 0 ? {} : { deadlineMilliseconds: envelope.timeoutMs }
|
|
389
|
+
});
|
|
390
|
+
} finally {
|
|
391
|
+
this.options.closeConnection();
|
|
392
|
+
this.closed = true;
|
|
393
|
+
this.post({
|
|
394
|
+
kind: "close-result",
|
|
395
|
+
protocol: "eidos-adapter",
|
|
396
|
+
version: "1.0",
|
|
397
|
+
epoch: this.options.epoch,
|
|
398
|
+
sessionID: this.options.sessionID,
|
|
399
|
+
requestID: envelope.requestID
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
this.queue = this.queue.then(task, task);
|
|
404
|
+
}
|
|
405
|
+
failure(request, error) {
|
|
406
|
+
this.post({
|
|
407
|
+
kind: "response",
|
|
408
|
+
protocol: "eidos-adapter",
|
|
409
|
+
version: "1.0",
|
|
410
|
+
epoch: this.options.epoch,
|
|
411
|
+
sessionID: this.options.sessionID,
|
|
412
|
+
requestID: request.requestID,
|
|
413
|
+
sequence: request.sequence,
|
|
414
|
+
ok: false,
|
|
415
|
+
error: {
|
|
416
|
+
source: "adapter",
|
|
417
|
+
error
|
|
418
|
+
}
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
fatal(message) {
|
|
422
|
+
this.closed = true;
|
|
423
|
+
this.closing = true;
|
|
424
|
+
this.pendingAck?.reject(adapterFailure("transport-fatal", message, true));
|
|
425
|
+
try {
|
|
426
|
+
this.options.closeConnection();
|
|
427
|
+
} catch {}
|
|
428
|
+
}
|
|
429
|
+
post(envelope) {
|
|
430
|
+
this.send({
|
|
431
|
+
envelope,
|
|
432
|
+
buffers: []
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
var AdapterTransportRuntimeClient = class {
|
|
437
|
+
limits = null;
|
|
438
|
+
epoch = "";
|
|
439
|
+
sessionID = "";
|
|
440
|
+
sequence = 0;
|
|
441
|
+
wireID = 0;
|
|
442
|
+
queuedBytes = 0;
|
|
443
|
+
pending = /* @__PURE__ */ new Map();
|
|
444
|
+
applicationToWire = /* @__PURE__ */ new Map();
|
|
445
|
+
unsubscribe;
|
|
446
|
+
helloResolve = null;
|
|
447
|
+
helloReject = null;
|
|
448
|
+
state = "opening";
|
|
449
|
+
constructor(channel, options) {
|
|
450
|
+
this.channel = channel;
|
|
451
|
+
this.options = options;
|
|
452
|
+
opaqueOrThrow(options.workingID, "workingID");
|
|
453
|
+
this.unsubscribe = channel.subscribe((carrier) => void this.receive(carrier), () => this.channelClosed());
|
|
454
|
+
}
|
|
455
|
+
async connect() {
|
|
456
|
+
if (this.state !== "opening") return this;
|
|
457
|
+
const ready = new Promise((resolve, reject) => {
|
|
458
|
+
this.helloResolve = resolve;
|
|
459
|
+
this.helloReject = reject;
|
|
460
|
+
});
|
|
461
|
+
this.channel.post({
|
|
462
|
+
envelope: {
|
|
463
|
+
kind: "hello",
|
|
464
|
+
protocol: "eidos-adapter",
|
|
465
|
+
versions: ["1.0"]
|
|
466
|
+
},
|
|
467
|
+
buffers: []
|
|
468
|
+
});
|
|
469
|
+
await ready;
|
|
470
|
+
return this;
|
|
471
|
+
}
|
|
472
|
+
async negotiate(request, context) {
|
|
473
|
+
const result = await this.call("negotiate", request, context);
|
|
474
|
+
this.installOptionalMethods(result.capabilities);
|
|
475
|
+
return result;
|
|
476
|
+
}
|
|
477
|
+
getSnapshot(request, context) {
|
|
478
|
+
return this.call("getSnapshot", request, context);
|
|
479
|
+
}
|
|
480
|
+
getSchemaPage(request, context) {
|
|
481
|
+
return this.call("getSchemaPage", request, context);
|
|
482
|
+
}
|
|
483
|
+
queryRows(request, context) {
|
|
484
|
+
return this.call("queryRows", request, context);
|
|
485
|
+
}
|
|
486
|
+
getRowsById(request, context) {
|
|
487
|
+
return this.call("getRowsById", request, context);
|
|
488
|
+
}
|
|
489
|
+
aggregate(request, context) {
|
|
490
|
+
return this.call("aggregate", request, context);
|
|
491
|
+
}
|
|
492
|
+
groupRows(request, context) {
|
|
493
|
+
return this.call("groupRows", request, context);
|
|
494
|
+
}
|
|
495
|
+
queryGroupRows(request, context) {
|
|
496
|
+
return this.call("queryGroupRows", request, context);
|
|
497
|
+
}
|
|
498
|
+
previewFormula(request, context) {
|
|
499
|
+
return this.call("previewFormula", request, context);
|
|
500
|
+
}
|
|
501
|
+
mutateRows(request, context) {
|
|
502
|
+
return this.call("mutateRows", request, context);
|
|
503
|
+
}
|
|
504
|
+
mutateView(request, context) {
|
|
505
|
+
return this.call("mutateView", request, context);
|
|
506
|
+
}
|
|
507
|
+
preflightSchema(request, context) {
|
|
508
|
+
return this.call("preflightSchema", request, context);
|
|
509
|
+
}
|
|
510
|
+
getSchemaPlanDependencies(request, context) {
|
|
511
|
+
return this.call("getSchemaPlanDependencies", request, context);
|
|
512
|
+
}
|
|
513
|
+
mutateSchema(request, context) {
|
|
514
|
+
return this.call("mutateSchema", request, context);
|
|
515
|
+
}
|
|
516
|
+
validate(request, context) {
|
|
517
|
+
return this.call("validate", request, context);
|
|
518
|
+
}
|
|
519
|
+
async cancel(request) {
|
|
520
|
+
const wireID = this.applicationToWire.get(request.requestId);
|
|
521
|
+
if (!wireID || !this.limits || this.state !== "open") return;
|
|
522
|
+
const pending = this.pending.get(wireID);
|
|
523
|
+
if (!pending || pending.ackAttempted) return;
|
|
524
|
+
this.channel.post({
|
|
525
|
+
envelope: {
|
|
526
|
+
kind: "cancel",
|
|
527
|
+
protocol: "eidos-adapter",
|
|
528
|
+
version: "1.0",
|
|
529
|
+
epoch: this.epoch,
|
|
530
|
+
sessionID: this.sessionID,
|
|
531
|
+
requestID: wireID
|
|
532
|
+
},
|
|
533
|
+
buffers: []
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
async close(context) {
|
|
537
|
+
if (this.state === "closed") return;
|
|
538
|
+
assertRequestContext(context);
|
|
539
|
+
if (!this.limits || this.state === "opening") {
|
|
540
|
+
this.finishClose();
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
const wireID = this.nextWireID();
|
|
544
|
+
await new Promise((resolve, reject) => {
|
|
545
|
+
const timeout = Math.min(context.deadlineMilliseconds ?? this.limits.defaultTimeoutMs, this.limits.maxTimeoutMs);
|
|
546
|
+
const timer = setTimeout(() => reject(runtimeFailure("deadline-exceeded", "Transport close timed out", true)), timeout);
|
|
547
|
+
const listener = (carrier) => {
|
|
548
|
+
if (carrier.envelope.kind === "close-result" && carrier.envelope.requestID === wireID) {
|
|
549
|
+
clearTimeout(timer);
|
|
550
|
+
remove();
|
|
551
|
+
resolve();
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
const remove = this.channel.subscribe(listener);
|
|
555
|
+
this.channel.post({
|
|
556
|
+
envelope: {
|
|
557
|
+
kind: "close",
|
|
558
|
+
protocol: "eidos-adapter",
|
|
559
|
+
version: "1.0",
|
|
560
|
+
epoch: this.epoch,
|
|
561
|
+
sessionID: this.sessionID,
|
|
562
|
+
requestID: wireID,
|
|
563
|
+
timeoutMs: timeout
|
|
564
|
+
},
|
|
565
|
+
buffers: []
|
|
566
|
+
});
|
|
567
|
+
}).finally(() => this.finishClose());
|
|
568
|
+
}
|
|
569
|
+
call(operation, logicalRequest, context) {
|
|
570
|
+
try {
|
|
571
|
+
assertRequestContext(context);
|
|
572
|
+
if (!this.limits || this.state !== "open") throw runtimeFailure(this.state === "fatal" ? "fatal" : "closed", "Transport is not open");
|
|
573
|
+
if (this.applicationToWire.has(context.requestId)) throw runtimeFailure("invalid-request", "requestId is already unresolved");
|
|
574
|
+
if (this.pending.size >= this.limits.maxOutstandingRequests) throw runtimeFailure("resource-limit", "Transport request limit reached", true);
|
|
575
|
+
const attachment = operation === "importCsv" ? extractCsvRequest(logicalRequest) : {
|
|
576
|
+
payload: logicalRequest,
|
|
577
|
+
attachments: []
|
|
578
|
+
};
|
|
579
|
+
const wireID = this.nextWireID();
|
|
580
|
+
const sequence = ++this.sequence;
|
|
581
|
+
const timeoutMs = Math.min(context.deadlineMilliseconds ?? this.limits.defaultTimeoutMs, this.limits.maxTimeoutMs);
|
|
582
|
+
const envelope = {
|
|
583
|
+
kind: "request",
|
|
584
|
+
protocol: "eidos-adapter",
|
|
585
|
+
version: "1.0",
|
|
586
|
+
epoch: this.epoch,
|
|
587
|
+
sessionID: this.sessionID,
|
|
588
|
+
requestID: wireID,
|
|
589
|
+
sequence,
|
|
590
|
+
timeoutMs,
|
|
591
|
+
operation,
|
|
592
|
+
payload: attachment.payload,
|
|
593
|
+
...attachment.attachments.length > 0 ? { attachments: attachment.attachments.map((entry) => entry.descriptor) } : {}
|
|
594
|
+
};
|
|
595
|
+
const carrier = {
|
|
596
|
+
envelope,
|
|
597
|
+
buffers: attachment.attachments.map((entry) => entry.buffer)
|
|
598
|
+
};
|
|
599
|
+
const bytes = carrierBytes(carrier);
|
|
600
|
+
if (bytes > this.limits.maxRequestBytes || this.queuedBytes + bytes > this.limits.maxQueuedBytes) throw runtimeFailure("resource-limit", "Transport request exceeds negotiated limits");
|
|
601
|
+
return new Promise((resolve, reject) => {
|
|
602
|
+
const requestDigest = digestRequest(envelope, carrier.buffers, this.options.workingID);
|
|
603
|
+
const timer = setTimeout(() => {
|
|
604
|
+
const pending = this.pending.get(wireID);
|
|
605
|
+
if (!pending) return;
|
|
606
|
+
if (pending.ackAttempted) this.fatalPending(runtimeFailure("unknown-commit", "Commit outcome requires reconciliation", false, { reconciliationRequired: true }));
|
|
607
|
+
else this.cancel({ requestId: context.requestId });
|
|
608
|
+
}, timeoutMs);
|
|
609
|
+
const unsubscribe = context.signal?.onAbort(() => {
|
|
610
|
+
this.cancel({ requestId: context.requestId });
|
|
611
|
+
}) ?? (() => void 0);
|
|
612
|
+
this.pending.set(wireID, {
|
|
613
|
+
operation,
|
|
614
|
+
applicationRequestID: context.requestId,
|
|
615
|
+
sequence,
|
|
616
|
+
bytes,
|
|
617
|
+
resolve,
|
|
618
|
+
reject,
|
|
619
|
+
unsubscribe,
|
|
620
|
+
timer,
|
|
621
|
+
requestDigest,
|
|
622
|
+
ackAttempted: false
|
|
623
|
+
});
|
|
624
|
+
this.applicationToWire.set(context.requestId, wireID);
|
|
625
|
+
this.queuedBytes += bytes;
|
|
626
|
+
this.channel.post(carrier, carrier.buffers);
|
|
627
|
+
});
|
|
628
|
+
} catch (error) {
|
|
629
|
+
return Promise.reject(runtimeErrorFromUnknown(error));
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
installOptionalMethods(capabilities) {
|
|
633
|
+
if (capabilities.mutationUndo) this.revertMutation = (request, context) => this.call("revertMutation", request, context);
|
|
634
|
+
else delete this.revertMutation;
|
|
635
|
+
if (capabilities.csvExport) this.exportCsv = (request, context) => this.call("exportCsv", request, context);
|
|
636
|
+
else delete this.exportCsv;
|
|
637
|
+
if (capabilities.csvImport) this.importCsv = (request, context) => this.call("importCsv", request, context);
|
|
638
|
+
else delete this.importCsv;
|
|
639
|
+
}
|
|
640
|
+
async receive(carrier) {
|
|
641
|
+
try {
|
|
642
|
+
validateAdapterCarrier(carrier);
|
|
643
|
+
const envelope = carrier.envelope;
|
|
644
|
+
if (envelope.kind === "hello-result" && this.state === "opening") {
|
|
645
|
+
this.epoch = envelope.epoch;
|
|
646
|
+
this.sessionID = envelope.sessionID;
|
|
647
|
+
this.limits = { ...envelope.limits };
|
|
648
|
+
this.state = "open";
|
|
649
|
+
this.helloResolve?.();
|
|
650
|
+
this.helloResolve = null;
|
|
651
|
+
this.helloReject = null;
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
if (envelope.kind === "hello-error" && this.state === "opening") {
|
|
655
|
+
const error = mapAdapterError(envelope.error);
|
|
656
|
+
this.helloReject?.(error);
|
|
657
|
+
this.state = "fatal";
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (!("epoch" in envelope) || envelope.epoch !== this.epoch || envelope.sessionID !== this.sessionID) return;
|
|
661
|
+
if (envelope.kind === "commit-prepared") {
|
|
662
|
+
await this.receivePrepared(envelope);
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (envelope.kind !== "response") return;
|
|
666
|
+
const pending = this.pending.get(envelope.requestID);
|
|
667
|
+
if (!pending || pending.sequence !== envelope.sequence) return;
|
|
668
|
+
if (envelope.ok) {
|
|
669
|
+
const result = resultPayload(pending.operation, envelope.result, carrier.buffers);
|
|
670
|
+
this.settle(envelope.requestID, () => pending.resolve(result));
|
|
671
|
+
} else {
|
|
672
|
+
const error = envelope.error.source === "runtime" ? envelope.error.error : mapAdapterError(envelope.error.error);
|
|
673
|
+
this.settle(envelope.requestID, () => pending.reject(error));
|
|
674
|
+
}
|
|
675
|
+
} catch (error) {
|
|
676
|
+
this.fatalPending(runtimeErrorFromUnknown(error));
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
async receivePrepared(envelope) {
|
|
680
|
+
const pending = this.pending.get(envelope.requestID);
|
|
681
|
+
if (!pending || pending.sequence !== envelope.sequence || pending.ackAttempted) throw runtimeFailure("fatal", "Unexpected commit preparation");
|
|
682
|
+
validateReceiptSemantics(envelope.receipt, pending.operation);
|
|
683
|
+
if (envelope.receipt.epoch !== this.epoch || envelope.receipt.sessionID !== this.sessionID || envelope.receipt.workingID !== this.options.workingID || envelope.receipt.requestDigest !== await pending.requestDigest) throw runtimeFailure("fatal", "Commit receipt session mismatch");
|
|
684
|
+
pending.receipt = envelope.receipt;
|
|
685
|
+
this.options.retainPreparedReceipt(envelope.receipt);
|
|
686
|
+
pending.ackAttempted = true;
|
|
687
|
+
this.channel.post({
|
|
688
|
+
envelope: {
|
|
689
|
+
kind: "commit-ack",
|
|
690
|
+
protocol: "eidos-adapter",
|
|
691
|
+
version: "1.0",
|
|
692
|
+
epoch: this.epoch,
|
|
693
|
+
sessionID: this.sessionID,
|
|
694
|
+
requestID: envelope.requestID,
|
|
695
|
+
sequence: envelope.sequence,
|
|
696
|
+
receiptID: envelope.receipt.receiptID,
|
|
697
|
+
requestDigest: envelope.receipt.requestDigest
|
|
698
|
+
},
|
|
699
|
+
buffers: []
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
settle(wireID, settle) {
|
|
703
|
+
const pending = this.pending.get(wireID);
|
|
704
|
+
if (!pending) return;
|
|
705
|
+
clearTimeout(pending.timer);
|
|
706
|
+
pending.unsubscribe();
|
|
707
|
+
this.pending.delete(wireID);
|
|
708
|
+
this.applicationToWire.delete(pending.applicationRequestID);
|
|
709
|
+
this.queuedBytes -= pending.bytes;
|
|
710
|
+
if (pending.receipt) this.options.settlePreparedReceipt(pending.receipt);
|
|
711
|
+
settle();
|
|
712
|
+
}
|
|
713
|
+
channelClosed() {
|
|
714
|
+
const unknown = Array.from(this.pending.values()).some((item) => item.ackAttempted);
|
|
715
|
+
this.fatalPending(unknown ? runtimeFailure("unknown-commit", "Commit outcome requires reconciliation", false, { reconciliationRequired: true }) : runtimeFailure("fatal", "Transport channel closed"));
|
|
716
|
+
}
|
|
717
|
+
fatalPending(error) {
|
|
718
|
+
this.state = "fatal";
|
|
719
|
+
for (const [wireID, pending] of this.pending) this.settle(wireID, () => pending.reject(pending.ackAttempted ? runtimeFailure("unknown-commit", "Commit outcome requires reconciliation", false, { reconciliationRequired: true }) : error));
|
|
720
|
+
}
|
|
721
|
+
finishClose() {
|
|
722
|
+
if (this.state === "closed") return;
|
|
723
|
+
this.state = "closed";
|
|
724
|
+
this.unsubscribe();
|
|
725
|
+
this.channel.close?.();
|
|
726
|
+
}
|
|
727
|
+
nextWireID() {
|
|
728
|
+
this.wireID += 1;
|
|
729
|
+
return `request-${this.wireID}`;
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
function requestPayload(envelope, buffers) {
|
|
733
|
+
const attachments = envelope.attachments ?? [];
|
|
734
|
+
if (envelope.operation === "importCsv") {
|
|
735
|
+
if (attachments.length !== 1 || attachments[0].slot !== "csv") throw adapterFailure("protocol-error", "importCsv requires exactly one csv attachment", true);
|
|
736
|
+
if (!isRecord(envelope.payload) || "csv" in envelope.payload) throw adapterFailure("protocol-error", "importCsv payload must omit csv", true);
|
|
737
|
+
return {
|
|
738
|
+
...envelope.payload,
|
|
739
|
+
csv: new Uint8Array(buffers[0].slice(0))
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
if (attachments.length !== 0) throw adapterFailure("protocol-error", "Runtime operation does not accept attachments", true);
|
|
743
|
+
return envelope.payload;
|
|
744
|
+
}
|
|
745
|
+
function responsePayload(operation, result) {
|
|
746
|
+
if (operation === "exportCsv") {
|
|
747
|
+
if (!isRecord(result) || !(result.csv instanceof Uint8Array)) throw adapterFailure("protocol-error", "exportCsv result is missing owned csv bytes", true);
|
|
748
|
+
const buffer = ownedArrayBuffer(result.csv);
|
|
749
|
+
const { csv: _csv, ...payload } = result;
|
|
750
|
+
return {
|
|
751
|
+
result: payload,
|
|
752
|
+
attachments: [{
|
|
753
|
+
descriptor: {
|
|
754
|
+
id: "csv",
|
|
755
|
+
slot: "csv",
|
|
756
|
+
byteLength: buffer.byteLength
|
|
757
|
+
},
|
|
758
|
+
buffer
|
|
759
|
+
}]
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
assertJsonValue(result);
|
|
763
|
+
return {
|
|
764
|
+
result,
|
|
765
|
+
attachments: []
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
function resultPayload(operation, result, buffers) {
|
|
769
|
+
if (operation !== "exportCsv") {
|
|
770
|
+
if (buffers.length !== 0) throw adapterFailure("protocol-error", "Unexpected response attachment", true);
|
|
771
|
+
return result;
|
|
772
|
+
}
|
|
773
|
+
if (!isRecord(result) || buffers.length !== 1) throw adapterFailure("protocol-error", "Invalid exportCsv response attachments", true);
|
|
774
|
+
return {
|
|
775
|
+
...result,
|
|
776
|
+
csv: new Uint8Array(buffers[0].slice(0))
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
function extractCsvRequest(request) {
|
|
780
|
+
const buffer = ownedArrayBuffer(request.csv);
|
|
781
|
+
const { csv: _csv, ...payload } = request;
|
|
782
|
+
return {
|
|
783
|
+
payload,
|
|
784
|
+
attachments: [{
|
|
785
|
+
descriptor: {
|
|
786
|
+
id: "csv",
|
|
787
|
+
slot: "csv",
|
|
788
|
+
byteLength: buffer.byteLength
|
|
789
|
+
},
|
|
790
|
+
buffer
|
|
791
|
+
}]
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
async function digestRequest(envelope, buffers, workingID) {
|
|
795
|
+
const attachments = await Promise.all((envelope.attachments ?? []).map(async (descriptor, index) => ({
|
|
796
|
+
...descriptor,
|
|
797
|
+
sha256: await sha256Bytes(new Uint8Array(buffers[index]))
|
|
798
|
+
})));
|
|
799
|
+
return sha256Bytes(new TextEncoder().encode(canonicalizeEidosFileJson({
|
|
800
|
+
protocol: "eidos-adapter",
|
|
801
|
+
version: "1.0",
|
|
802
|
+
epoch: envelope.epoch,
|
|
803
|
+
sessionID: envelope.sessionID,
|
|
804
|
+
workingID,
|
|
805
|
+
requestID: envelope.requestID,
|
|
806
|
+
sequence: envelope.sequence,
|
|
807
|
+
timeoutMs: envelope.timeoutMs ?? null,
|
|
808
|
+
operation: envelope.operation,
|
|
809
|
+
payload: envelope.payload,
|
|
810
|
+
attachments
|
|
811
|
+
})));
|
|
812
|
+
}
|
|
813
|
+
async function sha256Bytes(bytes) {
|
|
814
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
815
|
+
return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join("");
|
|
816
|
+
}
|
|
817
|
+
function validateReceiptSemantics(receipt, operation) {
|
|
818
|
+
if (receipt.operation !== operation || receipt.reconciliation.operation !== operation || receipt.fileID !== receipt.reconciliation.result.fileId || receipt.commitRevision !== receipt.reconciliation.result.revision || BigInt(receipt.commitRevision) !== BigInt(receipt.baseRevision) + 1n) throw adapterFailure("protocol-error", "Commit receipt semantic mismatch", true);
|
|
819
|
+
}
|
|
820
|
+
function validateCommitReceipt(receipt) {
|
|
821
|
+
if (!isRecord(receipt) || receipt.protocol !== "eidos-commit-receipt" || receipt.version !== "1.0" || !opaque(receipt.receiptID) || !opaque(receipt.epoch) || !opaque(receipt.sessionID) || !opaque(receipt.workingID) || !requestIdValue(receipt.requestID) || !positiveSafeIntegerValue(receipt.sequence) || typeof receipt.operation !== "string" || typeof receipt.fileID !== "string" || !nonNegativeInt64(receipt.baseRevision) || !nonNegativeInt64(receipt.commitRevision) || !sha256(receipt.requestDigest) || !isRecord(receipt.reconciliation)) throw adapterFailure("protocol-error", "Invalid commit receipt", true);
|
|
822
|
+
}
|
|
823
|
+
function carrierBytes(carrier) {
|
|
824
|
+
return new TextEncoder().encode(canonicalizeEidosFileJson(carrier.envelope)).byteLength + carrier.buffers.reduce((total, buffer) => total + buffer.byteLength, 0);
|
|
825
|
+
}
|
|
826
|
+
function validateTransportLimits(value) {
|
|
827
|
+
if (!isRecord(value)) throw adapterFailure("protocol-error", "Invalid Transport limits", true);
|
|
828
|
+
for (const key of [
|
|
829
|
+
"maxOutstandingRequests",
|
|
830
|
+
"maxQueuedBytes",
|
|
831
|
+
"maxRequestBytes",
|
|
832
|
+
"maxResponseBytes",
|
|
833
|
+
"defaultTimeoutMs",
|
|
834
|
+
"maxTimeoutMs",
|
|
835
|
+
"commitAckTimeoutMs"
|
|
836
|
+
]) positiveSafeInteger(value[key], key);
|
|
837
|
+
if (Number(value.maxOutstandingRequests) > 65536 || Number(value.maxQueuedBytes) < 1048576 || Number(value.maxRequestBytes) < 65536 || Number(value.maxResponseBytes) < 65536 || Number(value.defaultTimeoutMs) < 3e4 || Number(value.maxTimeoutMs) < Number(value.defaultTimeoutMs) || Number(value.commitAckTimeoutMs) < 100 || Number(value.commitAckTimeoutMs) > 6e4) throw adapterFailure("protocol-error", "Transport limits are outside Adapter 1.0 bounds", true);
|
|
838
|
+
}
|
|
839
|
+
function validateAttachments(value) {
|
|
840
|
+
if (value === void 0) return;
|
|
841
|
+
if (!Array.isArray(value) || value.length > 1024) throw adapterFailure("protocol-error", "Invalid attachment list", true);
|
|
842
|
+
}
|
|
843
|
+
function validateWireError(value) {
|
|
844
|
+
if (!isRecord(value) || value.source !== "adapter" && value.source !== "runtime") throw adapterFailure("protocol-error", "Invalid wire error", true);
|
|
845
|
+
if (value.source === "adapter") validateAdapterError(value.error);
|
|
846
|
+
else validateRuntimeError(value.error);
|
|
847
|
+
}
|
|
848
|
+
function validateAdapterError(value) {
|
|
849
|
+
if (!isRecord(value) || typeof value.code !== "string" || typeof value.message !== "string" || typeof value.retryable !== "boolean" || typeof value.fatal !== "boolean") throw adapterFailure("protocol-error", "Invalid Adapter error", true);
|
|
850
|
+
}
|
|
851
|
+
function validateRuntimeError(value) {
|
|
852
|
+
if (!isRecord(value) || typeof value.code !== "string" || typeof value.message !== "string" || typeof value.retryable !== "boolean") throw adapterFailure("protocol-error", "Invalid Runtime error", true);
|
|
853
|
+
}
|
|
854
|
+
function requestCorrelation(value) {
|
|
855
|
+
requestId(value.requestID);
|
|
856
|
+
positiveSafeInteger(value.sequence, "sequence");
|
|
857
|
+
if (value.timeoutMs !== void 0) positiveSafeInteger(value.timeoutMs, "timeoutMs");
|
|
858
|
+
}
|
|
859
|
+
function requestId(value) {
|
|
860
|
+
if (!requestIdValue(value)) throw adapterFailure("protocol-error", "Invalid request ID", true);
|
|
861
|
+
}
|
|
862
|
+
function requestIdValue(value) {
|
|
863
|
+
return typeof value === "string" && value.length > 0 && !value.includes("\0") && new TextEncoder().encode(value).byteLength <= 128 && !hasUnpairedSurrogate(value);
|
|
864
|
+
}
|
|
865
|
+
function opaque(value) {
|
|
866
|
+
return typeof value === "string" && value.length >= 1 && value.length <= 128 && !hasUnpairedSurrogate(value);
|
|
867
|
+
}
|
|
868
|
+
function opaqueOrThrow(value, label) {
|
|
869
|
+
if (!opaque(value)) throw new RangeError(`${label} must be an Adapter opaque token`);
|
|
870
|
+
}
|
|
871
|
+
function nonNegativeInt64(value) {
|
|
872
|
+
if (typeof value !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(value)) return false;
|
|
873
|
+
try {
|
|
874
|
+
return BigInt(value) <= 9223372036854775807n;
|
|
875
|
+
} catch {
|
|
876
|
+
return false;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
function sha256(value) {
|
|
880
|
+
return typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
|
|
881
|
+
}
|
|
882
|
+
function positiveSafeInteger(value, label) {
|
|
883
|
+
if (!positiveSafeIntegerValue(value)) throw adapterFailure("protocol-error", `${label} must be a positive safe integer`, true);
|
|
884
|
+
}
|
|
885
|
+
function positiveSafeIntegerValue(value) {
|
|
886
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
|
|
887
|
+
}
|
|
888
|
+
function safeNonNegativeInteger(value) {
|
|
889
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
890
|
+
}
|
|
891
|
+
function isRecord(value) {
|
|
892
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
893
|
+
}
|
|
894
|
+
function exactKeys(value, allowed, optional = false) {
|
|
895
|
+
const accepted = new Set(allowed);
|
|
896
|
+
if (Object.keys(value).some((key) => !accepted.has(key))) throw adapterFailure("protocol-error", "Envelope has unknown members", true);
|
|
897
|
+
if (!optional && allowed.some((key) => !(key in value))) throw adapterFailure("protocol-error", "Envelope is missing required members", true);
|
|
898
|
+
}
|
|
899
|
+
function assertJsonValue(value, seen = /* @__PURE__ */ new Set()) {
|
|
900
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
|
901
|
+
if (typeof value === "string" && hasUnpairedSurrogate(value)) throw adapterFailure("protocol-error", "JSON string contains an unpaired surrogate", true);
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
905
|
+
if (typeof value !== "object" || value === null || seen.has(value)) throw adapterFailure("protocol-error", "Envelope contains a non-JSON value", true);
|
|
906
|
+
seen.add(value);
|
|
907
|
+
if (Array.isArray(value)) value.forEach((entry) => assertJsonValue(entry, seen));
|
|
908
|
+
else for (const [key, entry] of Object.entries(value)) {
|
|
909
|
+
if (hasUnpairedSurrogate(key)) throw adapterFailure("protocol-error", "JSON key contains an unpaired surrogate", true);
|
|
910
|
+
assertJsonValue(entry, seen);
|
|
911
|
+
}
|
|
912
|
+
seen.delete(value);
|
|
913
|
+
}
|
|
914
|
+
function hasUnpairedSurrogate(value) {
|
|
915
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
916
|
+
const code = value.charCodeAt(index);
|
|
917
|
+
if (code >= 55296 && code <= 56319) {
|
|
918
|
+
if (index + 1 >= value.length) return true;
|
|
919
|
+
const next = value.charCodeAt(index + 1);
|
|
920
|
+
if (next < 56320 || next > 57343) return true;
|
|
921
|
+
index += 1;
|
|
922
|
+
} else if (code >= 56320 && code <= 57343) return true;
|
|
923
|
+
}
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
function adapterFailure(code, message, fatal, retryable = false) {
|
|
927
|
+
return {
|
|
928
|
+
code,
|
|
929
|
+
message,
|
|
930
|
+
retryable,
|
|
931
|
+
fatal
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
function adapterError(value) {
|
|
935
|
+
if (isRecord(value) && typeof value.code === "string" && typeof value.message === "string" && typeof value.fatal === "boolean") return value;
|
|
936
|
+
return adapterFailure("transport-fatal", value instanceof Error ? value.message : "Adapter Transport failed", true);
|
|
937
|
+
}
|
|
938
|
+
function runtimeFailure(code, message, retryable = false, details) {
|
|
939
|
+
return {
|
|
940
|
+
code,
|
|
941
|
+
message,
|
|
942
|
+
retryable,
|
|
943
|
+
...details ? { details } : {}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function runtimeErrorFromUnknown(value) {
|
|
947
|
+
if (isRecord(value) && typeof value.code === "string" && typeof value.message === "string" && typeof value.retryable === "boolean" && !("fatal" in value)) return value;
|
|
948
|
+
if (isRecord(value) && typeof value.code === "string" && "fatal" in value) return mapAdapterError(value);
|
|
949
|
+
return runtimeFailure("fatal", value instanceof Error ? value.message : "Runtime operation failed");
|
|
950
|
+
}
|
|
951
|
+
function mapAdapterError(error) {
|
|
952
|
+
if (error.code === "commit-outcome-unknown") return runtimeFailure("unknown-commit", error.message, false, { reconciliationRequired: true });
|
|
953
|
+
return runtimeFailure(error.fatal ? "fatal" : error.code === "busy" ? "busy" : error.code === "cancelled" ? "cancelled" : error.code === "deadline-exceeded" ? "deadline-exceeded" : error.code === "resource-limit" || error.code === "backpressure" ? "resource-limit" : error.code === "corrupt" || error.code === "not-a-database" ? "corrupt-file" : error.code === "adapter-closed" || error.code === "transport-closed" ? "closed" : "adapter-error", error.message, error.retryable, {
|
|
954
|
+
adapterCode: error.code,
|
|
955
|
+
fatal: error.fatal
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
function assertRequestContext(context) {
|
|
959
|
+
requestId(context.requestId);
|
|
960
|
+
if (context.deadlineMilliseconds !== void 0) positiveSafeInteger(context.deadlineMilliseconds, "deadlineMilliseconds");
|
|
961
|
+
if (context.signal?.aborted) throw runtimeFailure("cancelled", "Request was cancelled", true);
|
|
962
|
+
}
|
|
963
|
+
function ownedArrayBuffer(bytes) {
|
|
964
|
+
return bytes.slice().buffer;
|
|
965
|
+
}
|
|
966
|
+
/** Host byte limits are decimal strings and must never be compared as Number. */
|
|
967
|
+
function transportFitsHostLimit(bytes, limit) {
|
|
968
|
+
return Number.isSafeInteger(bytes) && bytes >= 0 && BigInt(bytes) <= BigInt(limit);
|
|
969
|
+
}
|
|
970
|
+
//#endregion
|
|
971
|
+
//#region src/data-source.ts
|
|
972
|
+
function eidosFileSnapshot(runtime, path) {
|
|
973
|
+
return {
|
|
974
|
+
path,
|
|
975
|
+
metadata: runtime.info(),
|
|
976
|
+
tables: runtime.listTables().map((table) => ({
|
|
977
|
+
table,
|
|
978
|
+
fields: runtime.listFields(table.id),
|
|
979
|
+
views: runtime.listViews(table.id),
|
|
980
|
+
rowCount: runtime.countRows(table.id)
|
|
981
|
+
}))
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
/** Adapts the synchronous core runtime to the public async view contract. */
|
|
985
|
+
var EidosFileRuntimeDataSource = class {
|
|
986
|
+
constructor(runtime, path) {
|
|
987
|
+
this.runtime = runtime;
|
|
988
|
+
this.path = path;
|
|
989
|
+
}
|
|
990
|
+
async getSnapshot() {
|
|
991
|
+
return eidosFileSnapshot(this.runtime, this.path);
|
|
992
|
+
}
|
|
993
|
+
async getPage(tableId, offset, limit, query, totalHint, cursor, projection) {
|
|
994
|
+
return this.runtime.getRowPage(tableId, offset, limit, query, totalHint, cursor, projection);
|
|
995
|
+
}
|
|
996
|
+
async getRow(tableId, rowId) {
|
|
997
|
+
return this.runtime.getRow(tableId, rowId);
|
|
998
|
+
}
|
|
999
|
+
async getGroupCounts(tableId, fieldId, query) {
|
|
1000
|
+
return this.runtime.countRowsByField(tableId, fieldId, query);
|
|
1001
|
+
}
|
|
1002
|
+
async calculateColumnStats(tableId, configs, query) {
|
|
1003
|
+
return this.runtime.calculateColumnStats(tableId, configs, query);
|
|
1004
|
+
}
|
|
1005
|
+
async previewFormula(tableId, input) {
|
|
1006
|
+
return this.runtime.previewFormula(tableId, input);
|
|
1007
|
+
}
|
|
1008
|
+
async insertRow(tableId, fields) {
|
|
1009
|
+
const mutation = this.runtime.mutateRows({
|
|
1010
|
+
tableId,
|
|
1011
|
+
insert: [{ fields }]
|
|
1012
|
+
});
|
|
1013
|
+
return this.mutationResult(tableId, this.runtime.getRow(tableId, mutation.rows[0].id));
|
|
1014
|
+
}
|
|
1015
|
+
async updateRow(tableId, rowId, fields) {
|
|
1016
|
+
return this.mutationResult(tableId, (() => {
|
|
1017
|
+
this.runtime.mutateRows({
|
|
1018
|
+
tableId,
|
|
1019
|
+
update: [{
|
|
1020
|
+
id: rowId,
|
|
1021
|
+
fields
|
|
1022
|
+
}]
|
|
1023
|
+
});
|
|
1024
|
+
return this.runtime.getRow(tableId, rowId);
|
|
1025
|
+
})());
|
|
1026
|
+
}
|
|
1027
|
+
async deleteRowRanges(tableId, ranges, query) {
|
|
1028
|
+
const deletedCount = this.runtime.deleteRowRanges(tableId, ranges, query);
|
|
1029
|
+
return this.deleteResult(tableId, deletedCount);
|
|
1030
|
+
}
|
|
1031
|
+
async deleteRows(tableId, rowIds) {
|
|
1032
|
+
return this.deleteResult(tableId, this.runtime.deleteRows(tableId, rowIds).length);
|
|
1033
|
+
}
|
|
1034
|
+
async updateField(tableId, fieldId, changes) {
|
|
1035
|
+
this.runtime.updateField(tableId, fieldId, changes);
|
|
1036
|
+
return this.getSnapshot();
|
|
1037
|
+
}
|
|
1038
|
+
async addField(tableId, field, placement) {
|
|
1039
|
+
this.runtime.addField(tableId, field, placement);
|
|
1040
|
+
return this.getSnapshot();
|
|
1041
|
+
}
|
|
1042
|
+
async deleteField(tableId, fieldId) {
|
|
1043
|
+
this.runtime.deleteField(tableId, fieldId);
|
|
1044
|
+
return this.getSnapshot();
|
|
1045
|
+
}
|
|
1046
|
+
async createTable(input) {
|
|
1047
|
+
this.runtime.createTable(input);
|
|
1048
|
+
return this.getSnapshot();
|
|
1049
|
+
}
|
|
1050
|
+
async updateTable(tableId, changes) {
|
|
1051
|
+
this.runtime.updateTable(tableId, changes);
|
|
1052
|
+
return this.getSnapshot();
|
|
1053
|
+
}
|
|
1054
|
+
async deleteTable(tableId) {
|
|
1055
|
+
this.runtime.deleteTable(tableId);
|
|
1056
|
+
return this.getSnapshot();
|
|
1057
|
+
}
|
|
1058
|
+
async createView(tableId, input) {
|
|
1059
|
+
this.runtime.createView(tableId, input);
|
|
1060
|
+
return this.getSnapshot();
|
|
1061
|
+
}
|
|
1062
|
+
async duplicateView(viewId, name) {
|
|
1063
|
+
this.runtime.duplicateView(viewId, name);
|
|
1064
|
+
return this.getSnapshot();
|
|
1065
|
+
}
|
|
1066
|
+
async deleteView(viewId) {
|
|
1067
|
+
this.runtime.deleteView(viewId);
|
|
1068
|
+
return this.getSnapshot();
|
|
1069
|
+
}
|
|
1070
|
+
async reorderViews(tableId, viewIds) {
|
|
1071
|
+
this.runtime.reorderViews(tableId, viewIds);
|
|
1072
|
+
return this.getSnapshot();
|
|
1073
|
+
}
|
|
1074
|
+
async updateView(viewId, changes) {
|
|
1075
|
+
this.runtime.updateView(viewId, changes);
|
|
1076
|
+
return this.getSnapshot();
|
|
1077
|
+
}
|
|
1078
|
+
mutationResult(tableId, row) {
|
|
1079
|
+
return {
|
|
1080
|
+
tableId,
|
|
1081
|
+
row,
|
|
1082
|
+
rowCount: this.runtime.countRows(tableId),
|
|
1083
|
+
revision: this.runtime.info().revision
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
deleteResult(tableId, deletedCount) {
|
|
1087
|
+
return {
|
|
1088
|
+
tableId,
|
|
1089
|
+
deletedCount,
|
|
1090
|
+
rowCount: this.runtime.countRows(tableId),
|
|
1091
|
+
revision: this.runtime.info().revision
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
};
|
|
1095
|
+
//#endregion
|
|
1096
|
+
//#region src/host.ts
|
|
1097
|
+
var EidosFileHostError = class extends Error {
|
|
1098
|
+
constructor(code, message, conflict, cause) {
|
|
1099
|
+
super(message);
|
|
1100
|
+
this.code = code;
|
|
1101
|
+
this.conflict = conflict;
|
|
1102
|
+
this.cause = cause;
|
|
1103
|
+
this.name = "EidosFileHostError";
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
const initialState = {
|
|
1107
|
+
phase: "idle",
|
|
1108
|
+
descriptor: null,
|
|
1109
|
+
permission: "unavailable",
|
|
1110
|
+
capabilities: null,
|
|
1111
|
+
source: null,
|
|
1112
|
+
snapshot: null,
|
|
1113
|
+
dirty: false,
|
|
1114
|
+
error: null,
|
|
1115
|
+
conflict: null,
|
|
1116
|
+
recoveryAvailable: false
|
|
1117
|
+
};
|
|
1118
|
+
var EidosFileSession = class {
|
|
1119
|
+
state = initialState;
|
|
1120
|
+
handle = null;
|
|
1121
|
+
document = null;
|
|
1122
|
+
closePromise = null;
|
|
1123
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1124
|
+
constructor(runtime, recovery) {
|
|
1125
|
+
this.runtime = runtime;
|
|
1126
|
+
this.recovery = recovery;
|
|
1127
|
+
}
|
|
1128
|
+
getState = () => this.state;
|
|
1129
|
+
subscribe = (listener) => {
|
|
1130
|
+
this.listeners.add(listener);
|
|
1131
|
+
return () => this.listeners.delete(listener);
|
|
1132
|
+
};
|
|
1133
|
+
async open(handle, options) {
|
|
1134
|
+
this.assertOpen();
|
|
1135
|
+
const previousState = this.state;
|
|
1136
|
+
const previousDocument = this.document;
|
|
1137
|
+
const previousHandle = this.handle;
|
|
1138
|
+
this.setState({
|
|
1139
|
+
...initialState,
|
|
1140
|
+
phase: "opening",
|
|
1141
|
+
capabilities: handle.capabilities
|
|
1142
|
+
});
|
|
1143
|
+
let document = null;
|
|
1144
|
+
try {
|
|
1145
|
+
const read = await handle.read(options);
|
|
1146
|
+
document = await this.runtime.open(read, options);
|
|
1147
|
+
const snapshot = await document.source.getSnapshot();
|
|
1148
|
+
const permission = await handle.permission();
|
|
1149
|
+
const recoveryAvailable = Boolean(this.recovery && await this.recovery.load(read.descriptor.id));
|
|
1150
|
+
this.document = document;
|
|
1151
|
+
this.handle = handle;
|
|
1152
|
+
document = null;
|
|
1153
|
+
this.setState({
|
|
1154
|
+
phase: "ready",
|
|
1155
|
+
descriptor: {
|
|
1156
|
+
...read.descriptor,
|
|
1157
|
+
metadata: snapshot.metadata
|
|
1158
|
+
},
|
|
1159
|
+
permission,
|
|
1160
|
+
capabilities: handle.capabilities,
|
|
1161
|
+
source: this.document.source,
|
|
1162
|
+
snapshot,
|
|
1163
|
+
dirty: false,
|
|
1164
|
+
error: null,
|
|
1165
|
+
conflict: null,
|
|
1166
|
+
recoveryAvailable
|
|
1167
|
+
});
|
|
1168
|
+
await settleResources(previousDocument, previousHandle === handle ? null : previousHandle);
|
|
1169
|
+
return snapshot;
|
|
1170
|
+
} catch (cause) {
|
|
1171
|
+
await settleResources(document, previousHandle === handle ? null : handle);
|
|
1172
|
+
const error = hostError("read-failed", "Unable to open Eidos File", cause);
|
|
1173
|
+
this.setState(previousDocument && previousState.source ? {
|
|
1174
|
+
...previousState,
|
|
1175
|
+
phase: "error",
|
|
1176
|
+
error,
|
|
1177
|
+
conflict: null
|
|
1178
|
+
} : {
|
|
1179
|
+
...initialState,
|
|
1180
|
+
phase: "error",
|
|
1181
|
+
error
|
|
1182
|
+
});
|
|
1183
|
+
throw error;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
async refresh() {
|
|
1187
|
+
const snapshot = await this.requireDocument().source.getSnapshot();
|
|
1188
|
+
this.setState({
|
|
1189
|
+
...this.state,
|
|
1190
|
+
snapshot
|
|
1191
|
+
});
|
|
1192
|
+
return snapshot;
|
|
1193
|
+
}
|
|
1194
|
+
markDirty(snapshot) {
|
|
1195
|
+
this.requireDocument();
|
|
1196
|
+
this.setState({
|
|
1197
|
+
...this.state,
|
|
1198
|
+
phase: "dirty",
|
|
1199
|
+
dirty: true,
|
|
1200
|
+
snapshot: snapshot ?? this.state.snapshot,
|
|
1201
|
+
error: null,
|
|
1202
|
+
conflict: null
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
async checkpoint() {
|
|
1206
|
+
const document = this.requireDocument();
|
|
1207
|
+
if (!this.recovery || !this.state.descriptor || !this.state.dirty) return null;
|
|
1208
|
+
const bytes = await document.exportBytes();
|
|
1209
|
+
const recovery = {
|
|
1210
|
+
id: this.state.descriptor.id,
|
|
1211
|
+
descriptor: this.state.descriptor,
|
|
1212
|
+
bytes,
|
|
1213
|
+
updatedAt: Date.now()
|
|
1214
|
+
};
|
|
1215
|
+
await this.recovery.save(recovery);
|
|
1216
|
+
this.setState({
|
|
1217
|
+
...this.state,
|
|
1218
|
+
recoveryAvailable: true
|
|
1219
|
+
});
|
|
1220
|
+
return recovery;
|
|
1221
|
+
}
|
|
1222
|
+
async save(options = {}) {
|
|
1223
|
+
const document = this.requireDocument();
|
|
1224
|
+
if (!this.handle?.write || !this.state.capabilities?.write) throw new EidosFileHostError("permission-denied", "This host cannot write to the open Eidos File. Use Save As instead.");
|
|
1225
|
+
const permission = await this.requestWritePermission();
|
|
1226
|
+
if (permission !== "granted") throw new EidosFileHostError("permission-denied", "Write permission was not granted for this Eidos File.");
|
|
1227
|
+
const expectedRevision = this.state.descriptor?.revision;
|
|
1228
|
+
this.setState({
|
|
1229
|
+
...this.state,
|
|
1230
|
+
phase: "saving",
|
|
1231
|
+
error: null,
|
|
1232
|
+
conflict: null
|
|
1233
|
+
});
|
|
1234
|
+
try {
|
|
1235
|
+
const bytes = await document.exportBytes({ signal: options.signal });
|
|
1236
|
+
const descriptor = await this.handle.write(bytes, {
|
|
1237
|
+
...options,
|
|
1238
|
+
expectedRevision
|
|
1239
|
+
});
|
|
1240
|
+
const snapshot = await document.source.getSnapshot();
|
|
1241
|
+
await this.recovery?.delete(descriptor.id);
|
|
1242
|
+
this.setState({
|
|
1243
|
+
...this.state,
|
|
1244
|
+
phase: "ready",
|
|
1245
|
+
descriptor: {
|
|
1246
|
+
...descriptor,
|
|
1247
|
+
metadata: snapshot.metadata
|
|
1248
|
+
},
|
|
1249
|
+
permission,
|
|
1250
|
+
snapshot,
|
|
1251
|
+
dirty: false,
|
|
1252
|
+
error: null,
|
|
1253
|
+
conflict: null,
|
|
1254
|
+
recoveryAvailable: false
|
|
1255
|
+
});
|
|
1256
|
+
return descriptor;
|
|
1257
|
+
} catch (cause) {
|
|
1258
|
+
if (cause instanceof EidosFileHostError && cause.code === "conflict") {
|
|
1259
|
+
this.setState({
|
|
1260
|
+
...this.state,
|
|
1261
|
+
phase: "conflict",
|
|
1262
|
+
dirty: true,
|
|
1263
|
+
error: cause,
|
|
1264
|
+
conflict: cause.conflict ?? null
|
|
1265
|
+
});
|
|
1266
|
+
throw cause;
|
|
1267
|
+
}
|
|
1268
|
+
const error = hostError("write-failed", "Unable to save Eidos File", cause);
|
|
1269
|
+
this.setState({
|
|
1270
|
+
...this.state,
|
|
1271
|
+
phase: "error",
|
|
1272
|
+
dirty: true,
|
|
1273
|
+
error
|
|
1274
|
+
});
|
|
1275
|
+
throw error;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
async saveAs(handle) {
|
|
1279
|
+
const document = this.requireDocument();
|
|
1280
|
+
if (!handle.write) throw new EidosFileHostError("permission-denied", "The selected destination is not writable.");
|
|
1281
|
+
const permission = await requestHandleWritePermission(handle);
|
|
1282
|
+
if (permission !== "granted") throw new EidosFileHostError("permission-denied", "Write permission was not granted for the selected destination.");
|
|
1283
|
+
const bytes = await document.exportBytes();
|
|
1284
|
+
const descriptor = await handle.write(bytes, { force: true });
|
|
1285
|
+
const previousHandle = this.handle;
|
|
1286
|
+
const previousDescriptorId = this.state.descriptor?.id;
|
|
1287
|
+
this.handle = handle;
|
|
1288
|
+
const snapshot = await document.source.getSnapshot();
|
|
1289
|
+
this.setState({
|
|
1290
|
+
...this.state,
|
|
1291
|
+
phase: "ready",
|
|
1292
|
+
descriptor: {
|
|
1293
|
+
...descriptor,
|
|
1294
|
+
metadata: snapshot.metadata
|
|
1295
|
+
},
|
|
1296
|
+
permission,
|
|
1297
|
+
capabilities: handle.capabilities,
|
|
1298
|
+
snapshot,
|
|
1299
|
+
dirty: false,
|
|
1300
|
+
error: null,
|
|
1301
|
+
conflict: null,
|
|
1302
|
+
recoveryAvailable: false
|
|
1303
|
+
});
|
|
1304
|
+
await Promise.allSettled([...previousHandle && previousHandle !== handle ? [Promise.resolve().then(() => previousHandle.close?.())] : [], ...this.recovery ? [this.recovery.delete(previousDescriptorId ?? descriptor.id)] : []]);
|
|
1305
|
+
return descriptor;
|
|
1306
|
+
}
|
|
1307
|
+
async reload(options) {
|
|
1308
|
+
const previousDocument = this.requireDocument();
|
|
1309
|
+
if (!this.handle) throw new EidosFileHostError("closed", "No file is open");
|
|
1310
|
+
const handle = this.handle;
|
|
1311
|
+
let replacement = null;
|
|
1312
|
+
try {
|
|
1313
|
+
const read = await handle.read(options);
|
|
1314
|
+
replacement = await this.runtime.open(read, options);
|
|
1315
|
+
const snapshot = await replacement.source.getSnapshot();
|
|
1316
|
+
this.document = replacement;
|
|
1317
|
+
replacement = null;
|
|
1318
|
+
this.setState({
|
|
1319
|
+
...this.state,
|
|
1320
|
+
phase: "ready",
|
|
1321
|
+
descriptor: {
|
|
1322
|
+
...read.descriptor,
|
|
1323
|
+
metadata: snapshot.metadata
|
|
1324
|
+
},
|
|
1325
|
+
source: this.document.source,
|
|
1326
|
+
snapshot,
|
|
1327
|
+
dirty: false,
|
|
1328
|
+
error: null,
|
|
1329
|
+
conflict: null,
|
|
1330
|
+
recoveryAvailable: false
|
|
1331
|
+
});
|
|
1332
|
+
await Promise.allSettled([Promise.resolve().then(() => previousDocument.close()), ...this.recovery ? [this.recovery.delete(read.descriptor.id)] : []]);
|
|
1333
|
+
return snapshot;
|
|
1334
|
+
} catch (cause) {
|
|
1335
|
+
await settleResources(replacement);
|
|
1336
|
+
const error = hostError("read-failed", "Unable to reload Eidos File", cause);
|
|
1337
|
+
this.setState({
|
|
1338
|
+
...this.state,
|
|
1339
|
+
phase: "error",
|
|
1340
|
+
error,
|
|
1341
|
+
conflict: null
|
|
1342
|
+
});
|
|
1343
|
+
throw error;
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
async restore(recovery) {
|
|
1347
|
+
this.assertOpen();
|
|
1348
|
+
const previousDocument = this.document;
|
|
1349
|
+
let document = null;
|
|
1350
|
+
try {
|
|
1351
|
+
document = await this.runtime.open({
|
|
1352
|
+
descriptor: recovery.descriptor,
|
|
1353
|
+
bytes: copyArrayBuffer(recovery.bytes)
|
|
1354
|
+
});
|
|
1355
|
+
const snapshot = await document.source.getSnapshot();
|
|
1356
|
+
this.document = document;
|
|
1357
|
+
document = null;
|
|
1358
|
+
this.setState({
|
|
1359
|
+
...this.state,
|
|
1360
|
+
phase: "dirty",
|
|
1361
|
+
descriptor: {
|
|
1362
|
+
...recovery.descriptor,
|
|
1363
|
+
metadata: snapshot.metadata
|
|
1364
|
+
},
|
|
1365
|
+
source: this.document.source,
|
|
1366
|
+
snapshot,
|
|
1367
|
+
dirty: true,
|
|
1368
|
+
error: null,
|
|
1369
|
+
conflict: null,
|
|
1370
|
+
recoveryAvailable: true
|
|
1371
|
+
});
|
|
1372
|
+
await settleResources(previousDocument);
|
|
1373
|
+
return snapshot;
|
|
1374
|
+
} catch (cause) {
|
|
1375
|
+
await settleResources(document);
|
|
1376
|
+
const error = hostError("read-failed", "Unable to restore Eidos File recovery data", cause);
|
|
1377
|
+
this.setState({
|
|
1378
|
+
...this.state,
|
|
1379
|
+
phase: "error",
|
|
1380
|
+
error,
|
|
1381
|
+
conflict: null
|
|
1382
|
+
});
|
|
1383
|
+
throw error;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
async close() {
|
|
1387
|
+
if (this.state.phase === "closed") return;
|
|
1388
|
+
if (this.closePromise) return this.closePromise;
|
|
1389
|
+
this.closePromise = this.closeResources();
|
|
1390
|
+
return this.closePromise;
|
|
1391
|
+
}
|
|
1392
|
+
async closeResources() {
|
|
1393
|
+
const document = this.document;
|
|
1394
|
+
const handle = this.handle;
|
|
1395
|
+
this.document = null;
|
|
1396
|
+
this.handle = null;
|
|
1397
|
+
const results = await settleResources(document, handle);
|
|
1398
|
+
this.setState({
|
|
1399
|
+
...initialState,
|
|
1400
|
+
phase: "closed"
|
|
1401
|
+
});
|
|
1402
|
+
this.listeners.clear();
|
|
1403
|
+
const failure = results.find((result) => result.status === "rejected");
|
|
1404
|
+
if (failure) throw failure.reason;
|
|
1405
|
+
}
|
|
1406
|
+
async requestWritePermission() {
|
|
1407
|
+
if (!this.handle) return "unavailable";
|
|
1408
|
+
const requested = await requestHandleWritePermission(this.handle);
|
|
1409
|
+
this.setState({
|
|
1410
|
+
...this.state,
|
|
1411
|
+
permission: requested
|
|
1412
|
+
});
|
|
1413
|
+
return requested;
|
|
1414
|
+
}
|
|
1415
|
+
assertOpen() {
|
|
1416
|
+
if (this.state.phase === "closed") throw new EidosFileHostError("closed", "The Eidos File session is closed");
|
|
1417
|
+
}
|
|
1418
|
+
requireDocument() {
|
|
1419
|
+
this.assertOpen();
|
|
1420
|
+
if (!this.document || !this.state.source) throw new EidosFileHostError("closed", "No Eidos File is open");
|
|
1421
|
+
return this.document;
|
|
1422
|
+
}
|
|
1423
|
+
setState(state) {
|
|
1424
|
+
this.state = state;
|
|
1425
|
+
for (const listener of this.listeners) listener();
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
const eidosFileTypeHandler = {
|
|
1429
|
+
id: EIDOS_FILE_FORMAT,
|
|
1430
|
+
label: "Eidos File",
|
|
1431
|
+
extensions: [EIDOS_FILE_EXTENSION],
|
|
1432
|
+
mimeTypes: [EIDOS_FILE_MIME_TYPE],
|
|
1433
|
+
accepts: ({ name, mimeType }) => mimeType === "application/vnd.eidos+sqlite3" || name.toLowerCase().endsWith(".eidos")
|
|
1434
|
+
};
|
|
1435
|
+
var EidosFileHandlerRegistry = class {
|
|
1436
|
+
handlers = /* @__PURE__ */ new Map();
|
|
1437
|
+
constructor(handlers = [eidosFileTypeHandler]) {
|
|
1438
|
+
for (const handler of handlers) this.register(handler);
|
|
1439
|
+
}
|
|
1440
|
+
register(handler) {
|
|
1441
|
+
if (this.handlers.has(handler.id)) throw new Error(`Duplicate Eidos File handler: ${handler.id}`);
|
|
1442
|
+
this.handlers.set(handler.id, handler);
|
|
1443
|
+
return () => this.handlers.delete(handler.id);
|
|
1444
|
+
}
|
|
1445
|
+
match(descriptor) {
|
|
1446
|
+
return [...this.handlers.values()].find((handler) => handler.accepts(descriptor)) ?? null;
|
|
1447
|
+
}
|
|
1448
|
+
list() {
|
|
1449
|
+
return [...this.handlers.values()];
|
|
1450
|
+
}
|
|
1451
|
+
};
|
|
1452
|
+
function hostError(code, message, cause) {
|
|
1453
|
+
return cause instanceof EidosFileHostError ? cause : new EidosFileHostError(code, message, void 0, cause);
|
|
1454
|
+
}
|
|
1455
|
+
function copyArrayBuffer(bytes) {
|
|
1456
|
+
const copy = new Uint8Array(bytes.byteLength);
|
|
1457
|
+
copy.set(bytes);
|
|
1458
|
+
return copy.buffer;
|
|
1459
|
+
}
|
|
1460
|
+
async function requestHandleWritePermission(handle) {
|
|
1461
|
+
const current = await handle.permission();
|
|
1462
|
+
if (current === "granted" || !handle.requestPermission) return current;
|
|
1463
|
+
return handle.requestPermission();
|
|
1464
|
+
}
|
|
1465
|
+
function settleResources(document, handle) {
|
|
1466
|
+
return Promise.allSettled([...document ? [Promise.resolve().then(async () => document.close())] : [], ...handle?.close ? [Promise.resolve().then(async () => handle.close?.())] : []]);
|
|
1467
|
+
}
|
|
1468
|
+
//#endregion
|
|
1469
|
+
//#region src/sqlite-wasm.ts
|
|
1470
|
+
const DEFAULT_BUSY_TIMEOUT_MS = 5e3;
|
|
1471
|
+
const DEFAULT_MAX_RESULT_ROWS = 1e5;
|
|
1472
|
+
const DEFAULT_MAX_RESULT_BYTES = 16 * 1024 * 1024;
|
|
1473
|
+
const UTF8 = new TextEncoder();
|
|
1474
|
+
const UTF8_FATAL = new TextDecoder("utf-8", { fatal: true });
|
|
1475
|
+
/**
|
|
1476
|
+
* EA-Connection-1.0 binding for the official SQLite WASM build.
|
|
1477
|
+
*
|
|
1478
|
+
* This class is intended to live beside Runtime in a Dedicated Worker. The
|
|
1479
|
+
* Window side must expose RuntimeClient over the Adapter transport profile,
|
|
1480
|
+
* never this object or its underlying database.
|
|
1481
|
+
*/
|
|
1482
|
+
var SQLiteWasmConnectionPort = class {
|
|
1483
|
+
connectionCapabilities;
|
|
1484
|
+
maxResultRows;
|
|
1485
|
+
maxResultBytes;
|
|
1486
|
+
transactionModes = [];
|
|
1487
|
+
snapshots = /* @__PURE__ */ new Set();
|
|
1488
|
+
scalarPointers = /* @__PURE__ */ new Set();
|
|
1489
|
+
localCommit = 0;
|
|
1490
|
+
savepointSequence = 0;
|
|
1491
|
+
mainReadEstablished = false;
|
|
1492
|
+
closed = false;
|
|
1493
|
+
constructor(database, sqlite3, options = {}) {
|
|
1494
|
+
this.database = database;
|
|
1495
|
+
this.sqlite3 = sqlite3;
|
|
1496
|
+
const busyTimeoutMs = positiveLimit(options.busyTimeoutMs, DEFAULT_BUSY_TIMEOUT_MS, "busyTimeoutMs");
|
|
1497
|
+
this.maxResultRows = positiveLimit(options.maxResultRows, DEFAULT_MAX_RESULT_ROWS, "maxResultRows");
|
|
1498
|
+
this.maxResultBytes = positiveLimit(options.maxResultBytes, DEFAULT_MAX_RESULT_BYTES, "maxResultBytes");
|
|
1499
|
+
this.database.exec(`PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = ${busyTimeoutMs};`);
|
|
1500
|
+
const sqliteVersion = this.runMandatoryProbes();
|
|
1501
|
+
const capi = this.sqlite3.capi;
|
|
1502
|
+
const pointer = this.database.pointer;
|
|
1503
|
+
if (!pointer) throw new EidosAdapterError("adapter-closed", "Connection is closed");
|
|
1504
|
+
this.connectionCapabilities = {
|
|
1505
|
+
adapterVersion: "1.0",
|
|
1506
|
+
sqliteVersion,
|
|
1507
|
+
json1: true,
|
|
1508
|
+
returning: true,
|
|
1509
|
+
strict: true,
|
|
1510
|
+
int64: true,
|
|
1511
|
+
scalarFunctions: true,
|
|
1512
|
+
directOnlyFunctions: true,
|
|
1513
|
+
interrupt: true,
|
|
1514
|
+
snapshot: true,
|
|
1515
|
+
defensiveMode: false,
|
|
1516
|
+
busyTimeoutMs,
|
|
1517
|
+
maxVariables: capi.sqlite3_limit(pointer, capi.SQLITE_LIMIT_VARIABLE_NUMBER, -1),
|
|
1518
|
+
maxSqlBytes: capi.sqlite3_limit(pointer, capi.SQLITE_LIMIT_SQL_LENGTH, -1),
|
|
1519
|
+
maxValueBytes: capi.sqlite3_limit(pointer, capi.SQLITE_LIMIT_LENGTH, -1),
|
|
1520
|
+
maxResultRows: this.maxResultRows,
|
|
1521
|
+
maxResultBytes: this.maxResultBytes
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
capabilities() {
|
|
1525
|
+
this.assertOpen();
|
|
1526
|
+
return { ...this.connectionCapabilities };
|
|
1527
|
+
}
|
|
1528
|
+
execSchema(sql) {
|
|
1529
|
+
this.assertOpen();
|
|
1530
|
+
if (/(?:^|;)\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/i.test(sql)) throw new EidosAdapterError("invalid-argument", "Transaction-control SQL is owned by ConnectionPort.transaction");
|
|
1531
|
+
if (this.transactionModes.at(-1) === "read") throw new EidosAdapterError("read-only", "Schema statements are forbidden in a read transaction");
|
|
1532
|
+
try {
|
|
1533
|
+
this.database.exec(sql);
|
|
1534
|
+
} catch (error) {
|
|
1535
|
+
throw this.mapError(error);
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
query(sql, bindings = []) {
|
|
1539
|
+
this.assertOpen();
|
|
1540
|
+
assertExactConnectionBindings(sql, bindings);
|
|
1541
|
+
let statement;
|
|
1542
|
+
try {
|
|
1543
|
+
statement = this.database.prepare(sql);
|
|
1544
|
+
this.assertReader(statement, "query");
|
|
1545
|
+
this.bind(statement, bindings);
|
|
1546
|
+
const columns = statement.getColumnNames().map((name) => ({ name: assertUnicodeString(name, "column name") }));
|
|
1547
|
+
const rows = [];
|
|
1548
|
+
let resultBytes = measureColumns(columns);
|
|
1549
|
+
while (statement.step()) {
|
|
1550
|
+
if (rows.length >= this.maxResultRows) throw new EidosAdapterError("resource-limit", "Query result exceeds maxResultRows");
|
|
1551
|
+
const row = this.readRow(statement);
|
|
1552
|
+
resultBytes += measureRow(row);
|
|
1553
|
+
if (resultBytes > this.maxResultBytes) throw new EidosAdapterError("resource-limit", "Query result exceeds maxResultBytes");
|
|
1554
|
+
rows.push(row);
|
|
1555
|
+
}
|
|
1556
|
+
this.noteRead(sql);
|
|
1557
|
+
return {
|
|
1558
|
+
columns,
|
|
1559
|
+
rows
|
|
1560
|
+
};
|
|
1561
|
+
} catch (error) {
|
|
1562
|
+
throw this.mapError(error);
|
|
1563
|
+
} finally {
|
|
1564
|
+
statement?.finalize();
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
get(sql, bindings = []) {
|
|
1568
|
+
this.assertOpen();
|
|
1569
|
+
assertExactConnectionBindings(sql, bindings);
|
|
1570
|
+
let statement;
|
|
1571
|
+
try {
|
|
1572
|
+
statement = this.database.prepare(sql);
|
|
1573
|
+
this.assertReader(statement, "get");
|
|
1574
|
+
this.bind(statement, bindings);
|
|
1575
|
+
const columns = statement.getColumnNames().map((name) => ({ name: assertUnicodeString(name, "column name") }));
|
|
1576
|
+
const row = statement.step() ? this.readRow(statement) : null;
|
|
1577
|
+
if (measureColumns(columns) + (row ? measureRow(row) : 0) > this.maxResultBytes) throw new EidosAdapterError("resource-limit", "Query result exceeds maxResultBytes");
|
|
1578
|
+
this.noteRead(sql);
|
|
1579
|
+
return {
|
|
1580
|
+
columns,
|
|
1581
|
+
row
|
|
1582
|
+
};
|
|
1583
|
+
} catch (error) {
|
|
1584
|
+
throw this.mapError(error);
|
|
1585
|
+
} finally {
|
|
1586
|
+
statement?.finalize();
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
run(sql, bindings = []) {
|
|
1590
|
+
this.assertOpen();
|
|
1591
|
+
assertExactConnectionBindings(sql, bindings);
|
|
1592
|
+
let statement;
|
|
1593
|
+
try {
|
|
1594
|
+
statement = this.database.prepare(sql);
|
|
1595
|
+
this.assertWriter(statement, "run");
|
|
1596
|
+
this.bind(statement, bindings);
|
|
1597
|
+
statement.step();
|
|
1598
|
+
return this.runResult();
|
|
1599
|
+
} catch (error) {
|
|
1600
|
+
throw this.mapError(error);
|
|
1601
|
+
} finally {
|
|
1602
|
+
statement?.finalize();
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
runMany(sql, bindingSets) {
|
|
1606
|
+
this.assertOpen();
|
|
1607
|
+
const expectedBindings = exactConnectionBindingCount(sql);
|
|
1608
|
+
for (const bindings of bindingSets) if (bindings.length !== expectedBindings) throw new EidosAdapterError("invalid-argument", `Statement requires ${expectedBindings} bindings, received ${bindings.length}`);
|
|
1609
|
+
let statement;
|
|
1610
|
+
try {
|
|
1611
|
+
statement = this.database.prepare(sql);
|
|
1612
|
+
this.assertWriter(statement, "runMany");
|
|
1613
|
+
const results = [];
|
|
1614
|
+
for (const bindings of bindingSets) {
|
|
1615
|
+
this.bind(statement, bindings);
|
|
1616
|
+
statement.step();
|
|
1617
|
+
results.push(this.runResult());
|
|
1618
|
+
statement.reset(true);
|
|
1619
|
+
}
|
|
1620
|
+
return results;
|
|
1621
|
+
} catch (error) {
|
|
1622
|
+
throw this.mapError(error);
|
|
1623
|
+
} finally {
|
|
1624
|
+
statement?.finalize();
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
registerScalar(definition, operation) {
|
|
1628
|
+
this.assertOpen();
|
|
1629
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(definition.name) || !Number.isInteger(definition.arity) || definition.arity < 0 || definition.arity > 127 || definition.deterministic !== true || definition.directOnly !== true) throw new EidosAdapterError("invalid-argument", "Invalid ScalarDefinition");
|
|
1630
|
+
const capi = this.sqlite3.capi;
|
|
1631
|
+
const wasm = this.sqlite3.wasm;
|
|
1632
|
+
const pointer = wasm.installFunction((contextPointer, argumentCount, argumentsPointer) => {
|
|
1633
|
+
try {
|
|
1634
|
+
const values = [];
|
|
1635
|
+
for (let index = 0; index < argumentCount; index += 1) {
|
|
1636
|
+
const valuePointer = wasm.peekPtr(argumentsPointer + index * wasm.ptrSizeof);
|
|
1637
|
+
values.push(this.readValue(valuePointer, "value"));
|
|
1638
|
+
}
|
|
1639
|
+
this.writeScalarResult(contextPointer, operation(...values));
|
|
1640
|
+
} catch (error) {
|
|
1641
|
+
capi.sqlite3_result_error(contextPointer, error instanceof Error ? error.message : "Scalar function failed", -1);
|
|
1642
|
+
}
|
|
1643
|
+
}, "viii");
|
|
1644
|
+
try {
|
|
1645
|
+
const databasePointer = this.database.pointer;
|
|
1646
|
+
if (!databasePointer) throw new EidosAdapterError("adapter-closed", "Connection is closed");
|
|
1647
|
+
this.database.checkRc(capi.sqlite3_create_function_v2(databasePointer, definition.name, definition.arity, capi.SQLITE_UTF8 | capi.SQLITE_DETERMINISTIC | capi.SQLITE_DIRECTONLY, 0, pointer, 0, 0, 0));
|
|
1648
|
+
this.scalarPointers.add(pointer);
|
|
1649
|
+
} catch (error) {
|
|
1650
|
+
wasm.uninstallFunction(pointer);
|
|
1651
|
+
throw this.mapError(error);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
transaction(mode, operation) {
|
|
1655
|
+
this.assertOpen();
|
|
1656
|
+
if (mode !== "read" && mode !== "write") throw new EidosAdapterError("invalid-argument", "Invalid transaction mode");
|
|
1657
|
+
const parent = this.transactionModes.at(-1);
|
|
1658
|
+
if (parent === "read" && mode === "write") throw new EidosAdapterError("read-only", "Cannot escalate a read transaction");
|
|
1659
|
+
const outer = this.transactionModes.length === 0;
|
|
1660
|
+
const effectiveMode = parent ?? mode;
|
|
1661
|
+
const savepoint = "eidos_adapter_" + ++this.savepointSequence;
|
|
1662
|
+
let started = false;
|
|
1663
|
+
const noCallbackFailure = Symbol("no-callback-failure");
|
|
1664
|
+
let callbackFailure = noCallbackFailure;
|
|
1665
|
+
try {
|
|
1666
|
+
this.database.exec(outer ? effectiveMode === "write" ? "BEGIN IMMEDIATE" : "BEGIN DEFERRED" : "SAVEPOINT " + savepoint);
|
|
1667
|
+
started = true;
|
|
1668
|
+
this.transactionModes.push(effectiveMode);
|
|
1669
|
+
if (outer) this.mainReadEstablished = false;
|
|
1670
|
+
let result;
|
|
1671
|
+
try {
|
|
1672
|
+
result = operation();
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
callbackFailure = error;
|
|
1675
|
+
throw error;
|
|
1676
|
+
}
|
|
1677
|
+
if (result instanceof Promise) return result.then((value) => {
|
|
1678
|
+
try {
|
|
1679
|
+
this.database.exec(outer ? "COMMIT" : "RELEASE " + savepoint);
|
|
1680
|
+
if (outer && effectiveMode === "write") this.localCommit += 1;
|
|
1681
|
+
return value;
|
|
1682
|
+
} catch (error) {
|
|
1683
|
+
this.rollbackTransaction(outer, savepoint);
|
|
1684
|
+
throw this.mapError(error);
|
|
1685
|
+
} finally {
|
|
1686
|
+
this.transactionModes.pop();
|
|
1687
|
+
if (outer) this.mainReadEstablished = false;
|
|
1688
|
+
}
|
|
1689
|
+
}, (error) => {
|
|
1690
|
+
try {
|
|
1691
|
+
this.rollbackTransaction(outer, savepoint);
|
|
1692
|
+
throw error;
|
|
1693
|
+
} finally {
|
|
1694
|
+
this.transactionModes.pop();
|
|
1695
|
+
if (outer) this.mainReadEstablished = false;
|
|
1696
|
+
}
|
|
1697
|
+
});
|
|
1698
|
+
this.database.exec(outer ? "COMMIT" : "RELEASE " + savepoint);
|
|
1699
|
+
if (outer && effectiveMode === "write") this.localCommit += 1;
|
|
1700
|
+
this.transactionModes.pop();
|
|
1701
|
+
if (outer) this.mainReadEstablished = false;
|
|
1702
|
+
return result;
|
|
1703
|
+
} catch (error) {
|
|
1704
|
+
try {
|
|
1705
|
+
if (started) this.rollbackTransaction(outer, savepoint);
|
|
1706
|
+
throw callbackFailure === error && callbackFailure !== noCallbackFailure ? error : this.mapError(error);
|
|
1707
|
+
} finally {
|
|
1708
|
+
if (started) this.transactionModes.pop();
|
|
1709
|
+
if (outer) this.mainReadEstablished = false;
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
dataVersion() {
|
|
1714
|
+
this.assertOpen();
|
|
1715
|
+
const value = this.query("PRAGMA data_version").rows[0]?.[0];
|
|
1716
|
+
if (!value || value.tag !== "integer") throw new EidosAdapterError("protocol-error", "PRAGMA data_version did not return INTEGER", false, true);
|
|
1717
|
+
return `${this.localCommit}:${value.value}`;
|
|
1718
|
+
}
|
|
1719
|
+
interrupt() {
|
|
1720
|
+
this.assertOpen();
|
|
1721
|
+
const pointer = this.database.pointer;
|
|
1722
|
+
if (!pointer) throw new EidosAdapterError("adapter-closed", "Connection is closed");
|
|
1723
|
+
this.sqlite3.capi.sqlite3_interrupt(pointer);
|
|
1724
|
+
}
|
|
1725
|
+
async snapshot(context) {
|
|
1726
|
+
this.assertOpen();
|
|
1727
|
+
if (this.transactionModes.length !== 1 || this.transactionModes[0] !== "read" || !this.mainReadEstablished) throw new EidosAdapterError("invalid-argument", "snapshot requires an established outer read transaction");
|
|
1728
|
+
const startedAt = Date.now();
|
|
1729
|
+
if (context.deadlineMilliseconds !== void 0 && (!Number.isSafeInteger(context.deadlineMilliseconds) || context.deadlineMilliseconds < 1)) throw new EidosAdapterError("invalid-argument", "deadlineMilliseconds must be a positive safe integer");
|
|
1730
|
+
this.assertSnapshotContext(context, startedAt);
|
|
1731
|
+
const maxBytes = parseNonNegativeInt64(context.maxBytes, "maxBytes");
|
|
1732
|
+
const estimate = this.database.selectValue("SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()");
|
|
1733
|
+
if ((typeof estimate === "bigint" ? estimate : BigInt(Number(estimate ?? 0))) > maxBytes) throw new EidosAdapterError("resource-limit", "Database snapshot exceeds maxBytes");
|
|
1734
|
+
let bytes;
|
|
1735
|
+
try {
|
|
1736
|
+
bytes = this.sqlite3.capi.sqlite3_js_db_export(this.database, "main").slice();
|
|
1737
|
+
} catch (error) {
|
|
1738
|
+
throw this.mapError(error);
|
|
1739
|
+
}
|
|
1740
|
+
this.assertSnapshotContext(context, startedAt);
|
|
1741
|
+
if (BigInt(bytes.byteLength) > maxBytes) throw new EidosAdapterError("resource-limit", "Database snapshot exceeds maxBytes");
|
|
1742
|
+
const source = new MemoryByteSource(bytes);
|
|
1743
|
+
this.snapshots.add(source);
|
|
1744
|
+
let released = false;
|
|
1745
|
+
return {
|
|
1746
|
+
bytes: source,
|
|
1747
|
+
release: async () => {
|
|
1748
|
+
if (released) return;
|
|
1749
|
+
released = true;
|
|
1750
|
+
source.release();
|
|
1751
|
+
this.snapshots.delete(source);
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
}
|
|
1755
|
+
close() {
|
|
1756
|
+
if (this.closed) return;
|
|
1757
|
+
this.closed = true;
|
|
1758
|
+
for (const snapshot of this.snapshots) snapshot.release();
|
|
1759
|
+
this.snapshots.clear();
|
|
1760
|
+
this.database.close();
|
|
1761
|
+
for (const pointer of this.scalarPointers) try {
|
|
1762
|
+
this.sqlite3.wasm.uninstallFunction(pointer);
|
|
1763
|
+
} catch {}
|
|
1764
|
+
this.scalarPointers.clear();
|
|
1765
|
+
}
|
|
1766
|
+
bind(statement, bindings) {
|
|
1767
|
+
if (statement.parameterCount !== bindings.length) throw new EidosAdapterError("invalid-argument", `Statement requires ${statement.parameterCount} bindings, received ${bindings.length}`);
|
|
1768
|
+
const capi = this.sqlite3.capi;
|
|
1769
|
+
for (let index = 0; index < bindings.length; index += 1) {
|
|
1770
|
+
const value = bindings[index];
|
|
1771
|
+
const bindingIndex = index + 1;
|
|
1772
|
+
switch (value.tag) {
|
|
1773
|
+
case "null":
|
|
1774
|
+
statement.bind(bindingIndex, null);
|
|
1775
|
+
break;
|
|
1776
|
+
case "integer":
|
|
1777
|
+
statement.bind(bindingIndex, assertInt64Decimal(value.value));
|
|
1778
|
+
break;
|
|
1779
|
+
case "real":
|
|
1780
|
+
if (!Number.isFinite(value.value)) throw new EidosAdapterError("invalid-sql-value", "REAL must be finite binary64");
|
|
1781
|
+
this.database.checkRc(capi.sqlite3_bind_double(statement.pointer, bindingIndex, Object.is(value.value, -0) ? 0 : value.value));
|
|
1782
|
+
break;
|
|
1783
|
+
case "text":
|
|
1784
|
+
statement.bind(bindingIndex, assertUnicodeString(value.value));
|
|
1785
|
+
break;
|
|
1786
|
+
case "blob":
|
|
1787
|
+
statement.bindAsBlob(bindingIndex, value.value.slice());
|
|
1788
|
+
break;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
readRow(statement) {
|
|
1793
|
+
const row = [];
|
|
1794
|
+
for (let index = 0; index < statement.columnCount; index += 1) row.push(this.readValue(statement.pointer, "column", index));
|
|
1795
|
+
return row;
|
|
1796
|
+
}
|
|
1797
|
+
readValue(pointer, source, columnIndex = 0) {
|
|
1798
|
+
const capi = this.sqlite3.capi;
|
|
1799
|
+
const type = source === "column" ? capi.sqlite3_column_type(pointer, columnIndex) : capi.sqlite3_value_type(pointer);
|
|
1800
|
+
const bytes = () => {
|
|
1801
|
+
const length = source === "column" ? capi.sqlite3_column_bytes(pointer, columnIndex) : capi.sqlite3_value_bytes(pointer);
|
|
1802
|
+
const dataPointer = source === "column" ? capi.sqlite3_column_blob(pointer, columnIndex) : capi.sqlite3_value_blob(pointer);
|
|
1803
|
+
return length === 0 ? new Uint8Array() : this.sqlite3.wasm.heap8u().slice(dataPointer, dataPointer + length);
|
|
1804
|
+
};
|
|
1805
|
+
switch (type) {
|
|
1806
|
+
case capi.SQLITE_NULL: return { tag: "null" };
|
|
1807
|
+
case capi.SQLITE_INTEGER: return {
|
|
1808
|
+
tag: "integer",
|
|
1809
|
+
value: String(source === "column" ? capi.sqlite3_column_int64(pointer, columnIndex) : capi.sqlite3_value_int64(pointer))
|
|
1810
|
+
};
|
|
1811
|
+
case capi.SQLITE_FLOAT: {
|
|
1812
|
+
const value = source === "column" ? capi.sqlite3_column_double(pointer, columnIndex) : capi.sqlite3_value_double(pointer);
|
|
1813
|
+
if (!Number.isFinite(value)) throw new EidosAdapterError("invalid-sql-value", "SQLite returned a non-finite REAL", false, true);
|
|
1814
|
+
return {
|
|
1815
|
+
tag: "real",
|
|
1816
|
+
value: Object.is(value, -0) ? 0 : value
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
case capi.SQLITE_TEXT: try {
|
|
1820
|
+
return {
|
|
1821
|
+
tag: "text",
|
|
1822
|
+
value: UTF8_FATAL.decode(bytes())
|
|
1823
|
+
};
|
|
1824
|
+
} catch {
|
|
1825
|
+
throw new EidosAdapterError("invalid-sql-value", "SQLite returned invalid UTF-8 TEXT", false, true);
|
|
1826
|
+
}
|
|
1827
|
+
case capi.SQLITE_BLOB: return {
|
|
1828
|
+
tag: "blob",
|
|
1829
|
+
value: bytes()
|
|
1830
|
+
};
|
|
1831
|
+
default: throw new EidosAdapterError("protocol-error", "SQLite returned an unknown storage class", false, true);
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
writeScalarResult(contextPointer, value) {
|
|
1835
|
+
const capi = this.sqlite3.capi;
|
|
1836
|
+
const wasm = this.sqlite3.wasm;
|
|
1837
|
+
switch (value.tag) {
|
|
1838
|
+
case "null":
|
|
1839
|
+
capi.sqlite3_result_null(contextPointer);
|
|
1840
|
+
break;
|
|
1841
|
+
case "integer":
|
|
1842
|
+
capi.sqlite3_result_int64(contextPointer, assertInt64Decimal(value.value));
|
|
1843
|
+
break;
|
|
1844
|
+
case "real":
|
|
1845
|
+
if (!Number.isFinite(value.value)) throw new EidosAdapterError("invalid-sql-value", "REAL must be finite binary64");
|
|
1846
|
+
capi.sqlite3_result_double(contextPointer, Object.is(value.value, -0) ? 0 : value.value);
|
|
1847
|
+
break;
|
|
1848
|
+
case "text":
|
|
1849
|
+
capi.sqlite3_result_text(contextPointer, assertUnicodeString(value.value), -1, capi.SQLITE_TRANSIENT);
|
|
1850
|
+
break;
|
|
1851
|
+
case "blob": {
|
|
1852
|
+
const bytes = value.value.slice();
|
|
1853
|
+
const pointer = wasm.alloc(Math.max(1, bytes.byteLength));
|
|
1854
|
+
try {
|
|
1855
|
+
if (bytes.byteLength > 0) wasm.heap8u().set(bytes, pointer);
|
|
1856
|
+
capi.sqlite3_result_blob(contextPointer, pointer, bytes.byteLength, capi.SQLITE_TRANSIENT);
|
|
1857
|
+
} finally {
|
|
1858
|
+
wasm.dealloc(pointer);
|
|
1859
|
+
}
|
|
1860
|
+
break;
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
assertReader(statement, operation) {
|
|
1865
|
+
if (statement.columnCount === 0) throw new EidosAdapterError("invalid-argument", operation + " requires one row-producing statement");
|
|
1866
|
+
this.assertStatementAllowed(statement);
|
|
1867
|
+
}
|
|
1868
|
+
assertWriter(statement, operation) {
|
|
1869
|
+
if (statement.columnCount !== 0) throw new EidosAdapterError("invalid-argument", operation + " requires one no-result statement");
|
|
1870
|
+
this.assertStatementAllowed(statement);
|
|
1871
|
+
}
|
|
1872
|
+
assertStatementAllowed(statement) {
|
|
1873
|
+
if (this.transactionModes.at(-1) === "read" && this.sqlite3.capi.sqlite3_stmt_readonly(statement.pointer) === 0) throw new EidosAdapterError("read-only", "Mutating statement is forbidden in a read transaction");
|
|
1874
|
+
}
|
|
1875
|
+
runResult() {
|
|
1876
|
+
const pointer = this.database.pointer;
|
|
1877
|
+
if (!pointer) throw new EidosAdapterError("adapter-closed", "Connection is closed");
|
|
1878
|
+
return {
|
|
1879
|
+
changes: String(this.sqlite3.capi.sqlite3_changes64(pointer)),
|
|
1880
|
+
lastInsertRowid: String(this.sqlite3.capi.sqlite3_last_insert_rowid(pointer))
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
rollbackTransaction(outer, savepoint) {
|
|
1884
|
+
try {
|
|
1885
|
+
this.database.exec(outer ? "ROLLBACK" : "ROLLBACK TO " + savepoint + "; RELEASE " + savepoint);
|
|
1886
|
+
} catch {
|
|
1887
|
+
this.closed = true;
|
|
1888
|
+
throw new EidosAdapterError("transport-fatal", "Transaction rollback could not be proven", false, true);
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
noteRead(sql) {
|
|
1892
|
+
if (this.transactionModes.length === 1 && this.transactionModes[0] === "read" && !/^\s*PRAGMA\b/i.test(sql) && !/\btemp(?:\.|\s)/i.test(sql)) this.mainReadEstablished = true;
|
|
1893
|
+
}
|
|
1894
|
+
assertSnapshotContext(context, startedAt) {
|
|
1895
|
+
if (context.cancellation.cancelled()) throw new EidosAdapterError("cancelled", "Snapshot was cancelled");
|
|
1896
|
+
if (context.deadlineMilliseconds !== void 0 && Date.now() - startedAt >= context.deadlineMilliseconds) throw new EidosAdapterError("deadline-exceeded", "Snapshot deadline was exceeded");
|
|
1897
|
+
}
|
|
1898
|
+
runMandatoryProbes() {
|
|
1899
|
+
try {
|
|
1900
|
+
const version = this.database.selectArray("SELECT sqlite_version(), sqlite_source_id()");
|
|
1901
|
+
if (typeof version?.[0] !== "string" || compareSqliteVersion(version[0], "3.45.0") < 0 || typeof version[1] !== "string" || version[1].length === 0) throw new EidosAdapterError("unsupported-capability", "SQLite 3.45.0 or later with source ID is required");
|
|
1902
|
+
const json = this.database.selectArray("SELECT json_valid('[]'), json_array_length('[1,2]')");
|
|
1903
|
+
const foreignKeys = this.database.selectValue("PRAGMA foreign_keys");
|
|
1904
|
+
const trustedSchema = this.database.selectValue("PRAGMA trusted_schema");
|
|
1905
|
+
const boundaryStatement = this.database.prepare("SELECT CAST('-9223372036854775808' AS INTEGER), CAST('9223372036854775807' AS INTEGER), X'000102FF'");
|
|
1906
|
+
try {
|
|
1907
|
+
if (!boundaryStatement.step()) throw new EidosAdapterError("unsupported-capability", "SQLite mandatory value probe returned no row");
|
|
1908
|
+
const values = this.readRow(boundaryStatement);
|
|
1909
|
+
if (values[0]?.tag !== "integer" || values[0].value !== "-9223372036854775808" || values[1]?.tag !== "integer" || values[1].value !== "9223372036854775807" || values[2]?.tag !== "blob" || hex(values[2].value) !== "000102ff") throw new EidosAdapterError("unsupported-capability", "SQLite mandatory value probe failed");
|
|
1910
|
+
} finally {
|
|
1911
|
+
boundaryStatement.finalize();
|
|
1912
|
+
}
|
|
1913
|
+
if (Number(json?.[0]) !== 1 || Number(json?.[1]) !== 2 || Number(foreignKeys) !== 1 || Number(trustedSchema) !== 0) throw new EidosAdapterError("unsupported-capability", "SQLite mandatory JSON/PRAGMA probes failed");
|
|
1914
|
+
this.database.exec("BEGIN");
|
|
1915
|
+
try {
|
|
1916
|
+
this.database.exec("CREATE TEMP TABLE eidos_adapter_probe(id INTEGER PRIMARY KEY, value TEXT NOT NULL) STRICT");
|
|
1917
|
+
const returned = this.database.selectArray("INSERT INTO eidos_adapter_probe(value) VALUES ('ok') RETURNING id, value");
|
|
1918
|
+
if (Number(returned?.[0]) !== 1 || returned?.[1] !== "ok") throw new EidosAdapterError("unsupported-capability", "SQLite STRICT/RETURNING probe failed");
|
|
1919
|
+
this.database.exec("DROP TABLE eidos_adapter_probe");
|
|
1920
|
+
this.database.exec("ROLLBACK");
|
|
1921
|
+
} catch (error) {
|
|
1922
|
+
this.database.exec("ROLLBACK");
|
|
1923
|
+
throw error;
|
|
1924
|
+
}
|
|
1925
|
+
this.registerScalar({
|
|
1926
|
+
name: "eidos_adapter_probe_scalar",
|
|
1927
|
+
arity: 1,
|
|
1928
|
+
deterministic: true,
|
|
1929
|
+
directOnly: true
|
|
1930
|
+
}, (value) => value);
|
|
1931
|
+
const storage = this.query("SELECT typeof(eidos_adapter_probe_scalar(NULL)), typeof(eidos_adapter_probe_scalar(1)), typeof(eidos_adapter_probe_scalar(1.0)), typeof(eidos_adapter_probe_scalar('x')), typeof(eidos_adapter_probe_scalar(X'0001')), hex(eidos_adapter_probe_scalar(X'0001'))").rows[0];
|
|
1932
|
+
const expected = [
|
|
1933
|
+
"null",
|
|
1934
|
+
"integer",
|
|
1935
|
+
"real",
|
|
1936
|
+
"text",
|
|
1937
|
+
"blob",
|
|
1938
|
+
"0001"
|
|
1939
|
+
];
|
|
1940
|
+
if (!storage || storage.length !== expected.length || storage.some((value, index) => value.tag !== "text" || value.value !== expected[index])) throw new EidosAdapterError("unsupported-capability", "Scalar function storage-class probe failed");
|
|
1941
|
+
return version[0];
|
|
1942
|
+
} catch (error) {
|
|
1943
|
+
const mapped = this.mapError(error);
|
|
1944
|
+
if (mapped instanceof EidosAdapterError) throw mapped;
|
|
1945
|
+
throw new EidosAdapterError("unsupported-capability", "SQLite mandatory probes failed");
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
assertOpen() {
|
|
1949
|
+
if (this.closed || !this.database.pointer) throw new EidosAdapterError("adapter-closed", "Connection is closed");
|
|
1950
|
+
}
|
|
1951
|
+
mapError(error) {
|
|
1952
|
+
if (error instanceof EidosAdapterError) return error;
|
|
1953
|
+
const pointer = this.database.pointer;
|
|
1954
|
+
const extended = pointer ? this.sqlite3.capi.sqlite3_extended_errcode(pointer) : void 0;
|
|
1955
|
+
const primary = extended === void 0 ? void 0 : extended & 255;
|
|
1956
|
+
const message = error instanceof Error ? error.message : "SQLite WASM failure";
|
|
1957
|
+
switch (primary) {
|
|
1958
|
+
case 5: return new EidosAdapterError("busy", "SQLite is busy", true, false, 5, extended);
|
|
1959
|
+
case 6: return new EidosAdapterError("locked", "SQLite is locked", false, false, 6, extended);
|
|
1960
|
+
case 8: return new EidosAdapterError("read-only", "SQLite is read-only", false, false, 8, extended);
|
|
1961
|
+
case 9: return new EidosAdapterError("cancelled", "SQLite was interrupted", false, false, 9, extended);
|
|
1962
|
+
case 10: return new EidosAdapterError("io-error", "SQLite I/O failed", false, false, 10, extended);
|
|
1963
|
+
case 11: return new EidosAdapterError("corrupt", "SQLite database is corrupt", false, true, 11, extended);
|
|
1964
|
+
case 18: return new EidosAdapterError("resource-limit", "SQLite value is too large", false, false, 18, extended);
|
|
1965
|
+
case 19: return new EidosAdapterError("constraint", "SQLite constraint failed", false, false, 19, extended);
|
|
1966
|
+
case 21: return new EidosAdapterError("protocol-error", "SQLite driver misuse", false, true, 21, extended);
|
|
1967
|
+
case 26: return new EidosAdapterError("not-a-database", "Input is not a SQLite database", false, true, 26, extended);
|
|
1968
|
+
}
|
|
1969
|
+
if (error instanceof RangeError || error instanceof TypeError || /bind|parameter/i.test(message)) return new EidosAdapterError("invalid-argument", message);
|
|
1970
|
+
return new EidosAdapterError("io-error", message, false, false, primary, extended);
|
|
1971
|
+
}
|
|
1972
|
+
};
|
|
1973
|
+
function positiveLimit(value, fallback, label) {
|
|
1974
|
+
const limit = value ?? fallback;
|
|
1975
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 2147483647) throw new EidosAdapterError("invalid-argument", label + " must be a positive JSON integer");
|
|
1976
|
+
return limit;
|
|
1977
|
+
}
|
|
1978
|
+
function compareSqliteVersion(left, right) {
|
|
1979
|
+
const a = left.split(".").map(Number);
|
|
1980
|
+
const b = right.split(".").map(Number);
|
|
1981
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
1982
|
+
const difference = (a[index] ?? 0) - (b[index] ?? 0);
|
|
1983
|
+
if (difference !== 0) return difference;
|
|
1984
|
+
}
|
|
1985
|
+
return 0;
|
|
1986
|
+
}
|
|
1987
|
+
function hex(bytes) {
|
|
1988
|
+
return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
|
|
1989
|
+
}
|
|
1990
|
+
function measureColumns(columns) {
|
|
1991
|
+
return columns.reduce((total, column) => total + UTF8.encode(column.name).byteLength, 0);
|
|
1992
|
+
}
|
|
1993
|
+
function measureRow(row) {
|
|
1994
|
+
return row.reduce((total, value) => {
|
|
1995
|
+
switch (value.tag) {
|
|
1996
|
+
case "null": return total;
|
|
1997
|
+
case "integer": return total + UTF8.encode(value.value).byteLength;
|
|
1998
|
+
case "real": return total + 8;
|
|
1999
|
+
case "text": return total + UTF8.encode(value.value).byteLength;
|
|
2000
|
+
case "blob": return total + value.value.byteLength;
|
|
2001
|
+
}
|
|
2002
|
+
}, 0);
|
|
2003
|
+
}
|
|
2004
|
+
//#endregion
|
|
2005
|
+
export { eidosFileTypeHandler as a, AdapterTransportRuntimeClient as c, transportFitsHostLimit as d, validateAdapterCarrier as f, EidosFileSession as i, AdapterTransportServer as l, EidosFileHandlerRegistry as n, EidosFileRuntimeDataSource as o, validateAdapterEnvelope as p, EidosFileHostError as r, eidosFileSnapshot as s, SQLiteWasmConnectionPort as t, EIDOS_ADAPTER_TRANSPORT_LIMITS as u };
|
|
2006
|
+
|
|
2007
|
+
//# sourceMappingURL=sqlite-wasm-BM6hsxH8.mjs.map
|