space-data-module-sdk 0.9.0 → 0.9.1
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/package.json +1 -1
- package/schemas/runtime/HostOps.fbs +24 -22
- package/schemas/runtime/IngestRequest.fbs +3 -0
- package/src/capabilities.js +3 -0
- package/src/generated/runtime/aligned/HostOps_aligned.js +133 -144
- package/src/generated/runtime/aligned/HostOps_aligned.ts +138 -153
- package/src/generated/runtime/aligned/HostOps_enums.js +1 -3
- package/src/generated/runtime/aligned/HostOps_enums.ts +0 -1
- package/src/generated/runtime/cpp/HostOps_aligned.h +111 -118
- package/src/generated/runtime/cpp/IngestRequest_generated.h +70 -5
- package/src/generated/runtime/sdn/runtime/Provenance.js +37 -5
- package/src/generated/runtime/sdn/runtime/Provenance.ts +42 -5
- package/src/host/abi.js +12 -3
- package/src/host/adapterOperations.js +79 -0
- package/src/host/browserHost.js +63 -2
- package/src/host/cpp/typedHostcall.hpp +51 -0
- package/src/host/hostWorkerBundleSources.js +3 -3
- package/src/host/nodeHost.js +49 -0
- package/src/host/typedDispatch.js +353 -1
- package/src/index.d.ts +25 -2
- package/src/standards/runtimeContracts.js +67 -7
package/src/host/nodeHost.js
CHANGED
|
@@ -40,6 +40,13 @@ import {
|
|
|
40
40
|
nextCronOccurrence,
|
|
41
41
|
parseCronExpression,
|
|
42
42
|
} from "./cron.js";
|
|
43
|
+
import {
|
|
44
|
+
ADAPTER_CAPABILITIES,
|
|
45
|
+
ADAPTER_OPERATIONS,
|
|
46
|
+
callServiceAdapter,
|
|
47
|
+
normalizePluginConfig,
|
|
48
|
+
resolveServiceAdapters,
|
|
49
|
+
} from "./adapterOperations.js";
|
|
43
50
|
|
|
44
51
|
const textEncoder = new TextEncoder();
|
|
45
52
|
const textDecoder = new TextDecoder();
|
|
@@ -71,9 +78,12 @@ export const NodeHostSupportedCapabilities = Object.freeze([
|
|
|
71
78
|
"crypto_kdf",
|
|
72
79
|
"wallet_sign",
|
|
73
80
|
"process_exec",
|
|
81
|
+
// served through the embedder's capability adapters (adapterOperations.js)
|
|
82
|
+
...ADAPTER_CAPABILITIES,
|
|
74
83
|
]);
|
|
75
84
|
|
|
76
85
|
export const NodeHostSupportedOperations = Object.freeze([
|
|
86
|
+
"plugin.getConfig",
|
|
77
87
|
"clock.now",
|
|
78
88
|
"clock.monotonicNow",
|
|
79
89
|
"clock.nowIso",
|
|
@@ -132,6 +142,7 @@ export const NodeHostSupportedOperations = Object.freeze([
|
|
|
132
142
|
"crypto.ed25519.publicKeyFromSeed",
|
|
133
143
|
"crypto.ed25519.sign",
|
|
134
144
|
"crypto.ed25519.verify",
|
|
145
|
+
...Object.keys(ADAPTER_OPERATIONS),
|
|
135
146
|
]);
|
|
136
147
|
|
|
137
148
|
function cloneValue(value) {
|
|
@@ -1544,6 +1555,8 @@ export class NodeHost {
|
|
|
1544
1555
|
this._walletSignAdapter = capabilityAdapters.walletSign;
|
|
1545
1556
|
this._protocolHandleAdapter = capabilityAdapters.protocolHandle;
|
|
1546
1557
|
this._protocolDialAdapter = capabilityAdapters.protocolDial;
|
|
1558
|
+
this._serviceAdapters = resolveServiceAdapters(options);
|
|
1559
|
+
this._config = normalizePluginConfig(options.config);
|
|
1547
1560
|
if (typeof this.fetch !== "function") {
|
|
1548
1561
|
throw new TypeError(
|
|
1549
1562
|
"A fetch implementation is required to create a Node host.",
|
|
@@ -1558,6 +1571,16 @@ export class NodeHost {
|
|
|
1558
1571
|
? createFileContextStore(options.contextFilePath)
|
|
1559
1572
|
: createInMemoryContextStore();
|
|
1560
1573
|
|
|
1574
|
+
// The module's config (options.config), as the Go node's plugin.getConfig serves it: no capability needed.
|
|
1575
|
+
this.plugin = Object.freeze({
|
|
1576
|
+
getConfig: () => structuredClone(this._config),
|
|
1577
|
+
});
|
|
1578
|
+
// The node's identity, from the embedder's node adapter (values or functions): no capability needed.
|
|
1579
|
+
this.node = Object.freeze({
|
|
1580
|
+
peerId: () => this.serveAdapterOperation("node.peerId"),
|
|
1581
|
+
publicKey: () => this.serveAdapterOperation("node.publicKey"),
|
|
1582
|
+
});
|
|
1583
|
+
|
|
1561
1584
|
this.clock = Object.freeze({
|
|
1562
1585
|
now: () => this.#withCapability("clock", "clock.now", () => Date.now()),
|
|
1563
1586
|
monotonicNow: () =>
|
|
@@ -2185,9 +2208,32 @@ export class NodeHost {
|
|
|
2185
2208
|
return normalized;
|
|
2186
2209
|
}
|
|
2187
2210
|
|
|
2211
|
+
/**
|
|
2212
|
+
* Serve one of the operations the embedder's capability adapters answer (ADAPTER_OPERATIONS: secrets, storage,
|
|
2213
|
+
* p2p, node): the capability check, then the adapter's method with the handler-shaped params. Synchronous when
|
|
2214
|
+
* the adapter answers synchronously.
|
|
2215
|
+
*/
|
|
2216
|
+
serveAdapterOperation(operation, params = {}) {
|
|
2217
|
+
const served = ADAPTER_OPERATIONS[operation];
|
|
2218
|
+
if (!served) {
|
|
2219
|
+
throw new Error(`Unknown Node host operation "${operation}".`);
|
|
2220
|
+
}
|
|
2221
|
+
if (served.capability) {
|
|
2222
|
+
this.assertCapability(served.capability, operation);
|
|
2223
|
+
}
|
|
2224
|
+
return callServiceAdapter(
|
|
2225
|
+
this._serviceAdapters[served.adapter],
|
|
2226
|
+
served.adapter,
|
|
2227
|
+
served.method,
|
|
2228
|
+
params ?? {},
|
|
2229
|
+
);
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2188
2232
|
async invoke(operation, params = {}) {
|
|
2189
2233
|
const normalized = assertNonEmptyString(operation, "Host operation");
|
|
2190
2234
|
switch (normalized) {
|
|
2235
|
+
case "plugin.getConfig":
|
|
2236
|
+
return this.plugin.getConfig();
|
|
2191
2237
|
case "host.runtimeTarget":
|
|
2192
2238
|
return this.runtimeTarget;
|
|
2193
2239
|
case "host.listCapabilities":
|
|
@@ -2343,6 +2389,9 @@ export class NodeHost {
|
|
|
2343
2389
|
params.publicKey,
|
|
2344
2390
|
);
|
|
2345
2391
|
default:
|
|
2392
|
+
if (ADAPTER_OPERATIONS[normalized]) {
|
|
2393
|
+
return this.serveAdapterOperation(normalized, params);
|
|
2394
|
+
}
|
|
2346
2395
|
throw new Error(`Unknown Node host operation "${normalized}".`);
|
|
2347
2396
|
}
|
|
2348
2397
|
}
|
|
@@ -5,9 +5,12 @@
|
|
|
5
5
|
import {
|
|
6
6
|
HOST_OPERATIONS,
|
|
7
7
|
decodeHostCall,
|
|
8
|
+
decodeSqlValues,
|
|
8
9
|
encodeHostCallResult,
|
|
10
|
+
encodeSqlValues,
|
|
9
11
|
} from "../standards/runtimeContracts.js";
|
|
10
12
|
import * as hostOps from "../generated/runtime/aligned/HostOps_aligned.js";
|
|
13
|
+
import { deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
|
|
11
14
|
import { base64ToBytes, bytesToBase64 } from "../utils/encoding.js";
|
|
12
15
|
|
|
13
16
|
const textDecoder = new TextDecoder();
|
|
@@ -71,6 +74,178 @@ function splitGcm(data) {
|
|
|
71
74
|
}
|
|
72
75
|
const concat = (a, b) => { const out = new Uint8Array(a.length + b.length); out.set(a, 0); out.set(b, a.length); return out; };
|
|
73
76
|
|
|
77
|
+
// ---- the Go node's handler shapes (sdn-server internal/modulert/typed_hostcall_ops.go), bytes as Uint8Array ---------
|
|
78
|
+
|
|
79
|
+
const failed = (message, code = "failed") => Object.assign(new Error(message), { hostcallCode: code });
|
|
80
|
+
const str = (v) => (v === undefined || v === null ? "" : String(v));
|
|
81
|
+
/** An answer's time (RFC 3339 text, a Date or unix ms) as unix ms; undefined when not given, 0 when unreadable. */
|
|
82
|
+
function ms(v) {
|
|
83
|
+
if (v === undefined || v === null || v === "") return undefined;
|
|
84
|
+
if (v instanceof Date) return BigInt(Number.isFinite(v.getTime()) ? v.getTime() : 0);
|
|
85
|
+
if (typeof v === "bigint") return v;
|
|
86
|
+
if (typeof v === "number") return BigInt(Number.isFinite(v) ? Math.trunc(v) : 0);
|
|
87
|
+
const t = Date.parse(String(v));
|
|
88
|
+
return BigInt(Number.isFinite(t) ? t : 0);
|
|
89
|
+
}
|
|
90
|
+
const enumName = (values, v) => Object.keys(values).find((k) => values[k] === Number(v ?? 0)) ?? "";
|
|
91
|
+
const binary = (v) => (v instanceof Uint8Array ? v : ArrayBuffer.isView(v) ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : v instanceof ArrayBuffer ? new Uint8Array(v) : undefined);
|
|
92
|
+
|
|
93
|
+
// A probe view per record class: the generated accessors say each field's JS type (bigint / number / boolean / string).
|
|
94
|
+
const probes = new Map();
|
|
95
|
+
function probeOf(Class) {
|
|
96
|
+
let view = probes.get(Class);
|
|
97
|
+
if (!view) probes.set(Class, (view = Class.fromPointer(new ArrayBuffer(Class.SIZE), 0)));
|
|
98
|
+
return view;
|
|
99
|
+
}
|
|
100
|
+
function toBigInt(v) {
|
|
101
|
+
if (typeof v === "bigint") return v;
|
|
102
|
+
if (typeof v === "boolean") return v ? 1n : 0n;
|
|
103
|
+
if (typeof v === "string" && /^-?\d+$/.test(v.trim())) return BigInt(v.trim());
|
|
104
|
+
const n = Number(v);
|
|
105
|
+
return BigInt(Number.isFinite(n) ? Math.trunc(n) : 0);
|
|
106
|
+
}
|
|
107
|
+
/** Field values (FIELD_NAME: value) as the record of class `Class` takes them; undeclared fields and null / undefined left out. */
|
|
108
|
+
function fitClass(Class, record) {
|
|
109
|
+
const view = probeOf(Class), proto = Class.prototype, out = {};
|
|
110
|
+
for (const [field, v] of Object.entries(record || {})) {
|
|
111
|
+
if (v === undefined || v === null) continue;
|
|
112
|
+
const g = field[0].toLowerCase() + field.slice(1);
|
|
113
|
+
if (typeof proto[`set${field}`] !== "function") {
|
|
114
|
+
if (typeof proto[g] === "function" && typeof proto[`setHas${field}`] === "function" && typeof v === "object") out[field] = fitClass(view[g]().constructor, v);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const kind = typeof view[g]();
|
|
118
|
+
out[field] = kind === "bigint" ? toBigInt(v) : kind === "number" ? (Number.isFinite(Number(v)) ? Number(v) : 0) : kind === "boolean" ? v === true || v === "true" : String(v);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
const fit = (type, record) => fitClass(hostOps[type], record);
|
|
123
|
+
/** A handler object's scalar values whose upper-cased keys the record declares (the Go node's recordFromObject). */
|
|
124
|
+
function fromObject(type, object) {
|
|
125
|
+
const record = {};
|
|
126
|
+
for (const [key, v] of Object.entries(object || {})) {
|
|
127
|
+
if (["string", "number", "boolean", "bigint"].includes(typeof v)) record[key.toUpperCase()] = v;
|
|
128
|
+
}
|
|
129
|
+
return fit(type, record);
|
|
130
|
+
}
|
|
131
|
+
/** A record's set fields as the handlers' lower-case keys (zero / empty = not given; the Go node's defaultTypedRequest). */
|
|
132
|
+
function lower(record) {
|
|
133
|
+
const out = {};
|
|
134
|
+
for (const [field, v] of Object.entries(record || {})) {
|
|
135
|
+
if (v === null || v === undefined || v === "" || v === false || v === 0 || v === 0n) continue;
|
|
136
|
+
if (Array.isArray(v) && v.length === 0) continue;
|
|
137
|
+
out[field.toLowerCase()] = typeof v === "bigint" ? Number(v) : v;
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
/** Bytes [len u32 LE][bytes]... (the size-prefixed record stream on raw "records"). */
|
|
142
|
+
function sizePrefixed(chunks) {
|
|
143
|
+
const out = new Uint8Array(chunks.reduce((n, c) => n + 4 + c.length, 0));
|
|
144
|
+
const view = new DataView(out.buffer);
|
|
145
|
+
let at = 0;
|
|
146
|
+
for (const c of chunks) { view.setUint32(at, c.length, true); out.set(c, at + 4); at += 4 + c.length; }
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
const MAX_SAFE = 2 ** 53;
|
|
150
|
+
/**
|
|
151
|
+
* Raw "params" (FlatSQL's tagged parameter encoding) -> the handlers' tagged params ({t, v}): an i64 beyond 2^53
|
|
152
|
+
* travels as text, bytes as Uint8Array (the Go node: base64).
|
|
153
|
+
*/
|
|
154
|
+
function sqlParams(raw) {
|
|
155
|
+
if (!raw.params) return undefined;
|
|
156
|
+
let values;
|
|
157
|
+
try { values = decodeSqlValues(raw.params); } catch (error) { throw failed(`params: ${error.message}`, "invalid-params"); }
|
|
158
|
+
return values.map(({ t, v }) => {
|
|
159
|
+
if (t === "null") return { t };
|
|
160
|
+
if (t === "i64") return { t, v: v > BigInt(MAX_SAFE) || v < -BigInt(MAX_SAFE) ? v.toString() : Number(v) };
|
|
161
|
+
return { t, v };
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
const deliverOf = (params) => (enumName(deliverMode, params?.DELIVER) === "Ref" ? "ref" : undefined);
|
|
165
|
+
function withDeliver(request, params) {
|
|
166
|
+
delete request.deliver;
|
|
167
|
+
const deliver = deliverOf(params);
|
|
168
|
+
if (deliver) request.deliver = deliver;
|
|
169
|
+
return request;
|
|
170
|
+
}
|
|
171
|
+
function sqlRequest({ params, raw }) {
|
|
172
|
+
const request = { sql: text(raw.sql) ?? "" };
|
|
173
|
+
const tagged = sqlParams(raw);
|
|
174
|
+
if (tagged) request.params = tagged;
|
|
175
|
+
return withDeliver(request, params);
|
|
176
|
+
}
|
|
177
|
+
const bodyRef = (ref) => ({ TOKEN: ref.token, SIZE: ref.size, FRAMES: ref.frames ?? -1, FNV1A64: str(ref.fnv1a64) });
|
|
178
|
+
/** {rows, columns, stream: bytes | ref: {token, size, frames, fnv1a64}} -> StreamResult-shaped record + raw "stream". */
|
|
179
|
+
function streamAnswer(v, type = "StreamResult") {
|
|
180
|
+
const record = { ROWS: v?.rows ?? 0, COLUMNS: v?.columns ?? 0 };
|
|
181
|
+
const answer = { raw: {} };
|
|
182
|
+
if (v?.ref && typeof v.ref === "object") record.REF = bodyRef(v.ref);
|
|
183
|
+
else if (binary(v?.stream)) answer.raw.stream = binary(v.stream);
|
|
184
|
+
answer.result = fit(type, record);
|
|
185
|
+
return answer;
|
|
186
|
+
}
|
|
187
|
+
/** A rows-answer cell (a JSON value) as a tagged SQL value: an integer is i64, any other number f64. */
|
|
188
|
+
function sqlCell(v) {
|
|
189
|
+
if (v === null || v === undefined) return { t: "null" };
|
|
190
|
+
if (typeof v === "boolean") return { t: "bool", v };
|
|
191
|
+
if (typeof v === "number") return Number.isInteger(v) ? { t: "i64", v: BigInt(v) } : { t: "f64", v };
|
|
192
|
+
if (typeof v === "string") return { t: "str", v };
|
|
193
|
+
throw failed(`storage.query_sandboxed: a cell is a ${Array.isArray(v) ? "list" : typeof v} (nested values are not SQL values)`);
|
|
194
|
+
}
|
|
195
|
+
/** plugin.getConfig: the config flattened into dotted-path entries ("targets.0.provider_id"), keys sorted. */
|
|
196
|
+
function configEntries(config) {
|
|
197
|
+
const entries = [];
|
|
198
|
+
const walk = (prefix, value) => {
|
|
199
|
+
if (value === null || value === undefined) return;
|
|
200
|
+
if (Array.isArray(value)) { value.forEach((item, i) => walk(`${prefix}.${i}`, item)); return; }
|
|
201
|
+
if (typeof value === "object" && !(value instanceof Date)) {
|
|
202
|
+
for (const key of Object.keys(value).sort()) walk(prefix ? `${prefix}.${key}` : key, value[key]);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (typeof value === "boolean") entries.push({ KEY: prefix, KIND: 2, BOOL_VALUE: value });
|
|
206
|
+
else if (typeof value === "string") entries.push({ KEY: prefix, KIND: 0, STRING_VALUE: value });
|
|
207
|
+
else if (typeof value === "number" || typeof value === "bigint") entries.push({ KEY: prefix, KIND: 1, NUMBER_VALUE: Number(value) });
|
|
208
|
+
else throw failed(`plugin.getConfig: ${prefix} is a ${value instanceof Date ? "Date" : typeof value}`);
|
|
209
|
+
};
|
|
210
|
+
walk("", config ?? {});
|
|
211
|
+
for (const e of entries) {
|
|
212
|
+
if (textEncoder.encode(e.KEY).length > 255 || textEncoder.encode(e.STRING_VALUE ?? "").length > 255) {
|
|
213
|
+
throw failed(`plugin.getConfig: ${e.KEY} does not fit a ConfigEntry (255 bytes)`, "too-large");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return entries;
|
|
217
|
+
}
|
|
218
|
+
function secretRequest({ params, raw }) {
|
|
219
|
+
const request = { id: str(params?.ID) };
|
|
220
|
+
if (params?.USERNAME) request.username = params.USERNAME;
|
|
221
|
+
if (raw.secret) request.secret = text(raw.secret);
|
|
222
|
+
return request;
|
|
223
|
+
}
|
|
224
|
+
function secretStatus(v) {
|
|
225
|
+
return { result: fit("SecretResult", {
|
|
226
|
+
ID: str(v?.id), CONFIGURED: v?.configured === true || v?.stored === true, USERNAME_MASKED: str(v?.username_masked),
|
|
227
|
+
UPDATED_MS: ms(v?.updated_at ?? v?.updatedAt) ?? 0n, VERIFIED_MS: ms(v?.verified_at) ?? 0n,
|
|
228
|
+
}) };
|
|
229
|
+
}
|
|
230
|
+
function nodeText(what) {
|
|
231
|
+
return (v) => {
|
|
232
|
+
if (v === undefined || v === null || v === "") throw failed(`node ${what} not available`);
|
|
233
|
+
return { raw: { value: String(v) } };
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
// p2p: the handler's entries -> P2pPnmEntry (the PNM's publish time as unix ms, the signature as hex).
|
|
237
|
+
function pnmEntry(e) {
|
|
238
|
+
return fit("P2pPnmEntry", {
|
|
239
|
+
PEER_ID: e.peer_id, PUBLISHER_PEER_ID: e.publisher_peer_id, GOSSIP_PEER_ID: e.gossip_peer_id, STANDARD: e.standard, SCHEMA: e.schema,
|
|
240
|
+
FILE_ID: e.file_id, FILE_NAME: e.file_name, CID: e.cid, PUBLISH_MS: ms(e.publish_timestamp ?? e.publish_ms), SIGNATURE_TYPE: e.signature_type,
|
|
241
|
+
SIGNATURE_HEX: e.signature ?? e.signature_hex, SIGNATURE_VERIFIED: e.signature_verified, ATTRIBUTION: e.attribution, PNM_INDEX: e.pnm_index ?? -1,
|
|
242
|
+
PUBLISHER_KEY_HEX: e.publisher_key ?? e.publisher_key_hex, PUBLISHER_KEY_SOURCE: e.publisher_key_source,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const p2pRecords = (v) => (binary(v?.records) ? { records: binary(v.records) } : {});
|
|
246
|
+
const p2pRequest = ({ params }) => withDeliver(lower(params), params);
|
|
247
|
+
const objects = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []);
|
|
248
|
+
|
|
74
249
|
// Per operation: in(call) -> the host's params; out(value) -> { result, lists, raw }. Operations not listed here pass
|
|
75
250
|
// their record's fields as camelCase options and answer a record from the host's camelCase fields.
|
|
76
251
|
const ADAPTERS = {
|
|
@@ -156,6 +331,181 @@ const ADAPTERS = {
|
|
|
156
331
|
"crypto.ed25519.publicKeyFromSeed": { in: ({ raw }) => ({ seed: raw.private_key }), out: data },
|
|
157
332
|
"crypto.ed25519.sign": { in: ({ raw }) => ({ message: raw.data, seed: raw.private_key }), out: data },
|
|
158
333
|
"crypto.ed25519.verify": { in: ({ raw }) => ({ message: raw.data, signature: raw.signature, publicKey: raw.public_key }), out: bool },
|
|
334
|
+
|
|
335
|
+
// ---- the Go node's operations, through the embedder's adapters (adapterOperations.js) ------------------------------
|
|
336
|
+
"plugin.getConfig": { in: () => ({}), out: (v) => ({ lists: { entries: configEntries(v) } }) },
|
|
337
|
+
"node.peerId": { in: () => ({}), out: nodeText("peer ID") },
|
|
338
|
+
"node.publicKey": { in: () => ({}), out: nodeText("public key") },
|
|
339
|
+
"secrets.get": { in: secretRequest, out: (v) => ({ result: fit("SecretResult", { ID: str(v?.id), USERNAME: str(v?.username), CONFIGURED: true }), raw: { secret: bytesOf(v?.secret) ?? new Uint8Array(0) } }) },
|
|
340
|
+
"secrets.status": { in: secretRequest, out: secretStatus },
|
|
341
|
+
"secrets.put": { in: secretRequest, out: secretStatus },
|
|
342
|
+
"secrets.clear": { in: secretRequest, out: () => ({}) },
|
|
343
|
+
// storage: {schema, data} -> {cid}
|
|
344
|
+
"storage.write": { in: ({ params, raw }) => ({ ...lower(params), data: raw.data ?? new Uint8Array(0) }), out: (v) => ({ result: fit("StorageWriteResult", { CID: str(v?.cid) }) }) },
|
|
345
|
+
// the store's records ({CID, RowID, PeerID, Timestamp, MaterializedAt, SourceTags, Data}) -> list "records_meta" + the
|
|
346
|
+
// size-prefixed records on raw "records"
|
|
347
|
+
"storage.query": {
|
|
348
|
+
in: ({ params }) => lower(params),
|
|
349
|
+
out: (v) => {
|
|
350
|
+
const meta = [], chunks = [];
|
|
351
|
+
for (const r of objects(Array.isArray(v) ? v : v?.records)) {
|
|
352
|
+
const tags = r.SourceTags || {}, data = binary(r.Data) ?? new Uint8Array(0);
|
|
353
|
+
chunks.push(data);
|
|
354
|
+
meta.push(fit("StoredRecordMeta", {
|
|
355
|
+
CID: str(r.CID), ROW_ID: r.RowID ?? 0, PEER_ID: str(r.PeerID), TIMESTAMP_MS: ms(r.Timestamp) ?? 0n, MATERIALIZED_MS: ms(r.MaterializedAt) ?? 0n,
|
|
356
|
+
LENGTH: data.length, PROVIDER_ID: str(tags.ProviderID), SOURCE_NAME: str(tags.SourceName), BATCH_ID: str(tags.BatchID),
|
|
357
|
+
PRODUCER_PEER_ID: str(tags.ProducerPeerID), LICENSE: str(tags.License),
|
|
358
|
+
}));
|
|
359
|
+
}
|
|
360
|
+
return { lists: { records_meta: meta }, raw: { records: sizePrefixed(chunks) } };
|
|
361
|
+
},
|
|
362
|
+
},
|
|
363
|
+
"storage.delete": { in: ({ params }) => lower(params), out: () => ({}) },
|
|
364
|
+
// {schema, provider_id, source_name, before_ms, batch, max_deletes} -> {deleted, missing, capped}
|
|
365
|
+
"storage.expire": { in: ({ params }) => lower(params), out: (v) => ({ result: fromObject("StorageExpireResult", v) }) },
|
|
366
|
+
// flat source tags, reconcile "duplicates" | "none" | "current", records, archive {source, name, raw}, provenance
|
|
367
|
+
// {source, json} (the "provenance" record as a JSON document, keys lower-cased)
|
|
368
|
+
"storage.ingest_with_source": {
|
|
369
|
+
in: ({ params, raw, lists }) => {
|
|
370
|
+
const request = lower(params);
|
|
371
|
+
delete request.archive_source; delete request.archive_name;
|
|
372
|
+
request.reconcile = enumName(reconcileKind, params?.RECONCILE).toLowerCase();
|
|
373
|
+
if (raw.records) request.records = raw.records;
|
|
374
|
+
if (raw.archive) request.archive = { source: str(params?.ARCHIVE_SOURCE), name: str(params?.ARCHIVE_NAME), raw: raw.archive };
|
|
375
|
+
const provenance = lists.provenance?.[0], attributes = lists.provenance_attributes;
|
|
376
|
+
if (provenance || attributes?.length) {
|
|
377
|
+
const document = {};
|
|
378
|
+
if (attributes?.length) document.attributes = attributes.map((a) => ({ name: str(a.NAME), value: str(a.VALUE) }));
|
|
379
|
+
for (const [key, v] of Object.entries(provenance || {})) document[key.toLowerCase()] = typeof v === "bigint" ? Number(v) : v ?? "";
|
|
380
|
+
const sorted = Object.fromEntries(Object.keys(document).sort().map((k) => [k, document[k]]));
|
|
381
|
+
request.provenance = { source: str(params?.SOURCE_NAME), json: textEncoder.encode(JSON.stringify(sorted)) };
|
|
382
|
+
}
|
|
383
|
+
return request;
|
|
384
|
+
},
|
|
385
|
+
out: (v) => {
|
|
386
|
+
const result = fromObject("StorageIngestResult", v);
|
|
387
|
+
if (v?.provenance) result.PROVENANCE_FILE = str(v.provenance);
|
|
388
|
+
return { result };
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
"storage.flatsql_query_stream": { in: sqlRequest, out: (v) => streamAnswer(v) },
|
|
392
|
+
"storage.flatsql_epoch_stream": { in: ({ params }) => withDeliver(lower(params), params), out: (v) => streamAnswer(v) },
|
|
393
|
+
// want "stream" answers like flatsql_query_stream (KIND Stream); "rows" ({kind: "rows", json}) with list "columns"
|
|
394
|
+
// and raw "cells" (tagged SQL values, row-major)
|
|
395
|
+
"storage.query_sandboxed": {
|
|
396
|
+
in: (call) => ({ ...sqlRequest(call), want: enumName(sandboxWant, call.params?.WANT).toLowerCase() }),
|
|
397
|
+
out: (v) => {
|
|
398
|
+
if (v?.kind !== "rows") {
|
|
399
|
+
const answer = streamAnswer(v, "SandboxQueryResult");
|
|
400
|
+
answer.result.KIND = sandboxWant.Stream;
|
|
401
|
+
return answer;
|
|
402
|
+
}
|
|
403
|
+
const doc = typeof v.json === "string" ? v.json : binary(v.json) ? text(binary(v.json)) : undefined;
|
|
404
|
+
if (doc === undefined) throw failed("storage.query_sandboxed: rows answer carries no rows");
|
|
405
|
+
let rows;
|
|
406
|
+
try { rows = JSON.parse(doc); } catch (error) { throw failed(`storage.query_sandboxed: ${error.message}`); }
|
|
407
|
+
if (!Array.isArray(rows)) throw failed("storage.query_sandboxed: rows are not a JSON array");
|
|
408
|
+
const columns = rows.length && rows[0] && typeof rows[0] === "object" ? Object.keys(rows[0]) : [];
|
|
409
|
+
const cells = [];
|
|
410
|
+
for (const row of rows) {
|
|
411
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) throw failed("storage.query_sandboxed: a row is not an object");
|
|
412
|
+
for (const cell of Object.values(row)) cells.push(sqlCell(cell));
|
|
413
|
+
}
|
|
414
|
+
return {
|
|
415
|
+
result: fit("SandboxQueryResult", { KIND: sandboxWant.Rows, ROWS: rows.length, COLUMNS: columns.length }),
|
|
416
|
+
lists: { columns: columns.map((c) => ({ VALUE: c })) },
|
|
417
|
+
raw: { cells: encodeSqlValues(cells) },
|
|
418
|
+
};
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
// {tables: [{name, kind, source, records, columns: [name | {name, placeholder}]}], caps: {timeout_ms, max_rows, max_bytes}}
|
|
422
|
+
"storage.query_surface": {
|
|
423
|
+
in: () => ({}),
|
|
424
|
+
out: (v) => {
|
|
425
|
+
const tables = [], columns = [];
|
|
426
|
+
for (const t of objects(v?.tables)) {
|
|
427
|
+
const name = str(t.name);
|
|
428
|
+
tables.push(fit("SurfaceTable", { NAME: name, KIND: str(t.kind), SOURCE: str(t.source), RECORDS: t.records ?? 0 }));
|
|
429
|
+
for (const c of Array.isArray(t.columns) ? t.columns : []) {
|
|
430
|
+
if (typeof c === "string") columns.push(fit("SurfaceColumn", { TABLE: name, NAME: c }));
|
|
431
|
+
else if (c && typeof c === "object") columns.push(fit("SurfaceColumn", { TABLE: name, NAME: str(c.name), PLACEHOLDER: c.placeholder === true }));
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const caps = v?.caps && typeof v.caps === "object" ? v.caps : null;
|
|
435
|
+
return {
|
|
436
|
+
...(caps ? { result: fit("QuerySurfaceLimits", { TIMEOUT_MS: caps.timeout_ms ?? 0, MAX_ROWS: caps.max_rows ?? 0, MAX_BYTES: caps.max_bytes ?? 0 }) } : {}),
|
|
437
|
+
lists: { tables, columns },
|
|
438
|
+
};
|
|
439
|
+
},
|
|
440
|
+
},
|
|
441
|
+
"storage.flatsql_cache_key": {
|
|
442
|
+
in: (call) => {
|
|
443
|
+
const request = { ...lower(call.params), ...sqlRequest(call) };
|
|
444
|
+
if (call.lists.projection) request.projection = call.lists.projection.map((p) => str(p.VALUE));
|
|
445
|
+
return request;
|
|
446
|
+
},
|
|
447
|
+
out: (v) => ({ raw: { value: str(v?.key) } }),
|
|
448
|
+
},
|
|
449
|
+
// p2p: the frames ($EPM / $PNM, size-prefixed and concatenated) on raw "records"
|
|
450
|
+
"p2p.peers_snapshot": {
|
|
451
|
+
in: p2pRequest,
|
|
452
|
+
out: (v) => {
|
|
453
|
+
const peers = [], addresses = [], standards = [];
|
|
454
|
+
for (const p of objects(v?.peers)) {
|
|
455
|
+
peers.push(fit("P2pPeer", { PEER_ID: str(p.peer_id), CONNECTED: p.connected === true, SELF: p.self === true, EPM_INDEX: p.epm_index ?? -1, AGENT_VERSION: p.agent_version }));
|
|
456
|
+
for (const a of Array.isArray(p.addrs) ? p.addrs : []) addresses.push(fit("P2pPeerValue", { PEER_ID: str(p.peer_id), VALUE: str(a) }));
|
|
457
|
+
for (const s of Array.isArray(p.standards) ? p.standards : []) standards.push(fit("P2pPeerValue", { PEER_ID: str(p.peer_id), VALUE: str(s) }));
|
|
458
|
+
}
|
|
459
|
+
return { result: fromObject("P2pSummary", v), lists: { peers, peer_addresses: addresses, peer_standards: standards }, raw: p2pRecords(v) };
|
|
460
|
+
},
|
|
461
|
+
},
|
|
462
|
+
"p2p.standards_snapshot": { in: p2pRequest, out: (v) => ({ lists: { entries: objects(v?.entries).map(pnmEntry) }, raw: p2pRecords(v) }) },
|
|
463
|
+
"p2p.pnm_history": { in: p2pRequest, out: (v) => ({ result: fromObject("P2pSummary", v), lists: { entries: objects(v?.entries).map(pnmEntry) }, raw: p2pRecords(v) }) },
|
|
464
|
+
// {known, reason, pinned, self, fresh, standard, schema, pnm, serving: {batch_id, ..., pnm, ref | stream}}: the served
|
|
465
|
+
// batch's PNM pointer when one is served, else the newest
|
|
466
|
+
"p2p.latest_dataset": {
|
|
467
|
+
in: p2pRequest,
|
|
468
|
+
out: (v) => {
|
|
469
|
+
const serving = v?.serving && typeof v.serving === "object" ? v.serving : {};
|
|
470
|
+
const pnm = (serving.pnm && typeof serving.pnm === "object" ? serving.pnm : v?.pnm) || {};
|
|
471
|
+
const result = fit("P2pLatestDataset", {
|
|
472
|
+
KNOWN: v?.known === true, REASON: v?.reason, PINNED: v?.pinned, SELF: v?.self, FRESH: v?.fresh, STANDARD: v?.standard, SCHEMA: v?.schema,
|
|
473
|
+
PNM_CID: pnm.CID ?? pnm.cid, PNM_FILE_ID: pnm.FILE_ID ?? pnm.file_id, PNM_PUBLISH_MS: ms(pnm.PUBLISH_TIMESTAMP ?? pnm.publish_timestamp),
|
|
474
|
+
PNM_SIGNATURE_VERIFIED: pnm.signature_verified, PNM_ATTRIBUTION: pnm.attribution,
|
|
475
|
+
BATCH_ID: serving.batch_id, PROVIDER_ID: serving.provider_id, SOURCE_NAME: serving.source_name, RECORD_COUNT: serving.record_count,
|
|
476
|
+
BYTE_COUNT: serving.byte_count, PARTS: serving.parts, PUBLISHED_MS: ms(serving.published_at), ETAG_FNV1A64: serving.etag_fnv1a64,
|
|
477
|
+
REF: serving.ref && typeof serving.ref === "object" ? bodyRef(serving.ref) : undefined,
|
|
478
|
+
});
|
|
479
|
+
return { result, raw: binary(serving.stream) ? { stream: binary(serving.stream) } : {} };
|
|
480
|
+
},
|
|
481
|
+
},
|
|
482
|
+
// node status and activity
|
|
483
|
+
"node_status_read.status": {
|
|
484
|
+
in: () => ({}),
|
|
485
|
+
out: (v) => {
|
|
486
|
+
const store = v?.store || {}, service = v?.service || {};
|
|
487
|
+
const record = {
|
|
488
|
+
UPTIME_S: v?.uptime_seconds ?? 0, STARTED_MS: ms(v?.started_at) ?? 0n, STORE_TOTAL_BYTES: store.total_bytes ?? 0, STORE_TOTAL_RECORDS: store.total_records ?? 0,
|
|
489
|
+
STORAGE_PATH: str(store.storage_path), SERVICE_STATE: str(service.state), SERVICE_MODE: str(service.mode),
|
|
490
|
+
};
|
|
491
|
+
if (v?.disk && typeof v.disk === "object") {
|
|
492
|
+
Object.assign(record, { HAS_DISK: true, DISK_CAPACITY_BYTES: v.disk.capacity_bytes ?? 0, DISK_FREE_BYTES: v.disk.free_bytes ?? 0, DISK_AVAILABLE_BYTES: v.disk.available_bytes ?? 0 });
|
|
493
|
+
}
|
|
494
|
+
const history = [];
|
|
495
|
+
if (v?.bandwidth && typeof v.bandwidth === "object") {
|
|
496
|
+
const bw = v.bandwidth;
|
|
497
|
+
Object.assign(record, { HAS_BANDWIDTH: true, TOTAL_IN_BYTES: bw.total_in_bytes ?? 0, TOTAL_OUT_BYTES: bw.total_out_bytes ?? 0, RATE_IN_BPS: bw.rate_in_bps ?? 0, RATE_OUT_BPS: bw.rate_out_bps ?? 0 });
|
|
498
|
+
for (const s of objects(bw.history)) {
|
|
499
|
+
history.push(fit("NodeBandwidthSample", { TS_MS: ms(s.ts) ?? 0n, TOTAL_IN_BYTES: s.total_in_bytes ?? 0, TOTAL_OUT_BYTES: s.total_out_bytes ?? 0, RATE_IN_BPS: s.rate_in_bps ?? 0, RATE_OUT_BPS: s.rate_out_bps ?? 0 }));
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return { result: fit("NodeStatusReport", record), lists: { bandwidth_history: history } };
|
|
503
|
+
},
|
|
504
|
+
},
|
|
505
|
+
"node_activity_read.activity": {
|
|
506
|
+
in: ({ params }) => lower(params),
|
|
507
|
+
out: (v) => ({ lists: { events: objects(v?.events).map((e) => fit("NodeActivityEvent", { TS_MS: ms(e.ts) ?? 0n, KIND: str(e.kind), DETAIL: str(e.detail), PEER_ID: str(e.peer_id) })) } }),
|
|
508
|
+
},
|
|
159
509
|
};
|
|
160
510
|
function data(v) { return { raw: { data: bytesOf(v) ?? new Uint8Array(0) } }; }
|
|
161
511
|
function bool(v) { return { result: { VALUE: Boolean(v) } }; }
|
|
@@ -193,10 +543,12 @@ export function typedResultOf(call, value) {
|
|
|
193
543
|
export function hostcallErrorCode(error) {
|
|
194
544
|
if (error?.hostcallCode) return error.hostcallCode;
|
|
195
545
|
const name = error?.name ?? error?.constructor?.name ?? "";
|
|
196
|
-
if (name === "HostCapabilityError" || error?.code === "host-capability-denied") return "not-authorized";
|
|
546
|
+
if (name === "HostCapabilityError" || name === "BrowserHostCapabilityError" || error?.code === "host-capability-denied") return "not-authorized";
|
|
197
547
|
if (name === "HostFilesystemScopeError") return "sandbox";
|
|
198
548
|
if (name === "AbortError" || name === "TimeoutError" || /timed out/i.test(error?.message ?? "")) return "timeout";
|
|
199
549
|
if (/^Unknown .* operation|not available in the synchronous hostcall ABI|does not implement/.test(error?.message ?? "")) return "unsupported";
|
|
550
|
+
// a string or list that does not fit its aligned record (the Go node's recordErr)
|
|
551
|
+
if (/exceeds? the record/.test(error?.message ?? "")) return "too-large";
|
|
200
552
|
if (error instanceof RangeError || error instanceof TypeError) return "invalid-params";
|
|
201
553
|
return "failed";
|
|
202
554
|
}
|
package/src/index.d.ts
CHANGED
|
@@ -1424,6 +1424,9 @@ export interface BrowserEdgeShims {
|
|
|
1424
1424
|
capabilityAdapters?: Record<string, Record<string, (...args: any[]) => unknown>>;
|
|
1425
1425
|
}
|
|
1426
1426
|
|
|
1427
|
+
/** An embedder's capability adapter: methods (sync or async) or plain values by operation method, or invoke(). */
|
|
1428
|
+
export type HostServiceAdapter = Record<string, unknown>;
|
|
1429
|
+
|
|
1427
1430
|
export interface BrowserHostOptions {
|
|
1428
1431
|
capabilities?: string[];
|
|
1429
1432
|
edgeShims?: BrowserEdgeShims;
|
|
@@ -1443,7 +1446,14 @@ export interface BrowserHostOptions {
|
|
|
1443
1446
|
walletSign?: Record<string, (...args: any[]) => unknown> | null;
|
|
1444
1447
|
protocolHandle?: Record<string, (...args: any[]) => unknown> | null;
|
|
1445
1448
|
protocolDial?: Record<string, (...args: any[]) => unknown> | null;
|
|
1446
|
-
|
|
1449
|
+
/** The Go node's capability handlers (secrets, storage, p2p, node), bytes as Uint8Array. */
|
|
1450
|
+
secrets?: HostServiceAdapter | null;
|
|
1451
|
+
storage?: HostServiceAdapter | null;
|
|
1452
|
+
p2p?: HostServiceAdapter | null;
|
|
1453
|
+
node?: HostServiceAdapter | null;
|
|
1454
|
+
capabilityAdapters?: Record<string, HostServiceAdapter>;
|
|
1455
|
+
/** The module's config, served by plugin.getConfig (default {}). */
|
|
1456
|
+
config?: Record<string, unknown>;
|
|
1447
1457
|
}
|
|
1448
1458
|
|
|
1449
1459
|
export interface NodeHostOptions {
|
|
@@ -1500,7 +1510,14 @@ export interface NodeHostOptions {
|
|
|
1500
1510
|
walletSign?: Record<string, (...args: any[]) => unknown> | null;
|
|
1501
1511
|
protocolHandle?: Record<string, (...args: any[]) => unknown> | null;
|
|
1502
1512
|
protocolDial?: Record<string, (...args: any[]) => unknown> | null;
|
|
1503
|
-
|
|
1513
|
+
/** The Go node's capability handlers (secrets, storage, p2p, node), bytes as Uint8Array. */
|
|
1514
|
+
secrets?: HostServiceAdapter | null;
|
|
1515
|
+
storage?: HostServiceAdapter | null;
|
|
1516
|
+
p2p?: HostServiceAdapter | null;
|
|
1517
|
+
node?: HostServiceAdapter | null;
|
|
1518
|
+
capabilityAdapters?: Record<string, HostServiceAdapter>;
|
|
1519
|
+
/** The module's config, served by plugin.getConfig (default {}). */
|
|
1520
|
+
config?: Record<string, unknown>;
|
|
1504
1521
|
}
|
|
1505
1522
|
|
|
1506
1523
|
export class HostCapabilityError extends Error {
|
|
@@ -1768,6 +1785,9 @@ export class NodeHost {
|
|
|
1768
1785
|
listOperations(): string[];
|
|
1769
1786
|
hasCapability(capability: string): boolean;
|
|
1770
1787
|
assertCapability(capability: string, operation?: string | null): string;
|
|
1788
|
+
plugin: { getConfig(): Record<string, unknown> };
|
|
1789
|
+
node: { peerId(): unknown; publicKey(): unknown };
|
|
1790
|
+
serveAdapterOperation(operation: string, params?: Record<string, any>): unknown;
|
|
1771
1791
|
invoke(operation: string, params?: Record<string, any>): Promise<any>;
|
|
1772
1792
|
}
|
|
1773
1793
|
|
|
@@ -1866,6 +1886,9 @@ export class BrowserHost {
|
|
|
1866
1886
|
listOperations(): string[];
|
|
1867
1887
|
hasCapability(capability: string): boolean;
|
|
1868
1888
|
assertCapability(capability: string, operation?: string | null): void;
|
|
1889
|
+
plugin: { getConfig(): Record<string, unknown> };
|
|
1890
|
+
node: { peerId(): unknown; publicKey(): unknown };
|
|
1891
|
+
serveAdapterOperation(operation: string, params?: Record<string, any>): unknown;
|
|
1869
1892
|
}
|
|
1870
1893
|
|
|
1871
1894
|
export const NodeHostSupportedCapabilities: readonly string[];
|