space-data-module-sdk 0.9.0 → 0.9.2

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.
@@ -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,13 @@
5
5
  import {
6
6
  HOST_OPERATIONS,
7
7
  decodeHostCall,
8
+ decodeSqlValues,
8
9
  encodeHostCallResult,
10
+ encodeModuleConfig,
11
+ encodeSqlValues,
9
12
  } from "../standards/runtimeContracts.js";
10
13
  import * as hostOps from "../generated/runtime/aligned/HostOps_aligned.js";
14
+ import { deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
11
15
  import { base64ToBytes, bytesToBase64 } from "../utils/encoding.js";
12
16
 
13
17
  const textDecoder = new TextDecoder();
@@ -71,6 +75,182 @@ function splitGcm(data) {
71
75
  }
72
76
  const concat = (a, b) => { const out = new Uint8Array(a.length + b.length); out.set(a, 0); out.set(b, a.length); return out; };
73
77
 
78
+ // ---- the Go node's handler shapes (sdn-server internal/modulert/typed_hostcall_ops.go), bytes as Uint8Array ---------
79
+
80
+ const failed = (message, code = "failed") => Object.assign(new Error(message), { hostcallCode: code });
81
+ const str = (v) => (v === undefined || v === null ? "" : String(v));
82
+ /** An answer's time (RFC 3339 text, a Date or unix ms) as unix ms; undefined when not given, 0 when unreadable. */
83
+ function ms(v) {
84
+ if (v === undefined || v === null || v === "") return undefined;
85
+ if (v instanceof Date) return BigInt(Number.isFinite(v.getTime()) ? v.getTime() : 0);
86
+ if (typeof v === "bigint") return v;
87
+ if (typeof v === "number") return BigInt(Number.isFinite(v) ? Math.trunc(v) : 0);
88
+ const t = Date.parse(String(v));
89
+ return BigInt(Number.isFinite(t) ? t : 0);
90
+ }
91
+ const enumName = (values, v) => Object.keys(values).find((k) => values[k] === Number(v ?? 0)) ?? "";
92
+ 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);
93
+
94
+ // A probe view per record class: the generated accessors say each field's JS type (bigint / number / boolean / string).
95
+ const probes = new Map();
96
+ function probeOf(Class) {
97
+ let view = probes.get(Class);
98
+ if (!view) probes.set(Class, (view = Class.fromPointer(new ArrayBuffer(Class.SIZE), 0)));
99
+ return view;
100
+ }
101
+ function toBigInt(v) {
102
+ if (typeof v === "bigint") return v;
103
+ if (typeof v === "boolean") return v ? 1n : 0n;
104
+ if (typeof v === "string" && /^-?\d+$/.test(v.trim())) return BigInt(v.trim());
105
+ const n = Number(v);
106
+ return BigInt(Number.isFinite(n) ? Math.trunc(n) : 0);
107
+ }
108
+ /** Field values (FIELD_NAME: value) as the record of class `Class` takes them; undeclared fields and null / undefined left out. */
109
+ function fitClass(Class, record) {
110
+ const view = probeOf(Class), proto = Class.prototype, out = {};
111
+ for (const [field, v] of Object.entries(record || {})) {
112
+ if (v === undefined || v === null) continue;
113
+ const g = field[0].toLowerCase() + field.slice(1);
114
+ if (typeof proto[`set${field}`] !== "function") {
115
+ if (typeof proto[g] === "function" && typeof proto[`setHas${field}`] === "function" && typeof v === "object") out[field] = fitClass(view[g]().constructor, v);
116
+ continue;
117
+ }
118
+ const kind = typeof view[g]();
119
+ out[field] = kind === "bigint" ? toBigInt(v) : kind === "number" ? (Number.isFinite(Number(v)) ? Number(v) : 0) : kind === "boolean" ? v === true || v === "true" : String(v);
120
+ }
121
+ return out;
122
+ }
123
+ const fit = (type, record) => fitClass(hostOps[type], record);
124
+ /** A handler object's scalar values whose upper-cased keys the record declares (the Go node's recordFromObject). */
125
+ function fromObject(type, object) {
126
+ const record = {};
127
+ for (const [key, v] of Object.entries(object || {})) {
128
+ if (["string", "number", "boolean", "bigint"].includes(typeof v)) record[key.toUpperCase()] = v;
129
+ }
130
+ return fit(type, record);
131
+ }
132
+ /** A record's set fields as the handlers' lower-case keys (zero / empty = not given; the Go node's defaultTypedRequest). */
133
+ function lower(record) {
134
+ const out = {};
135
+ for (const [field, v] of Object.entries(record || {})) {
136
+ if (v === null || v === undefined || v === "" || v === false || v === 0 || v === 0n) continue;
137
+ if (Array.isArray(v) && v.length === 0) continue;
138
+ out[field.toLowerCase()] = typeof v === "bigint" ? Number(v) : v;
139
+ }
140
+ return out;
141
+ }
142
+ /** Bytes [len u32 LE][bytes]... (the size-prefixed record stream on raw "records"). */
143
+ function sizePrefixed(chunks) {
144
+ const out = new Uint8Array(chunks.reduce((n, c) => n + 4 + c.length, 0));
145
+ const view = new DataView(out.buffer);
146
+ let at = 0;
147
+ for (const c of chunks) { view.setUint32(at, c.length, true); out.set(c, at + 4); at += 4 + c.length; }
148
+ return out;
149
+ }
150
+ const MAX_SAFE = 2 ** 53;
151
+ /**
152
+ * Raw "params" (FlatSQL's tagged parameter encoding) -> the handlers' tagged params ({t, v}): an i64 beyond 2^53
153
+ * travels as text, bytes as Uint8Array (the Go node: base64).
154
+ */
155
+ function sqlParams(raw) {
156
+ if (!raw.params) return undefined;
157
+ let values;
158
+ try { values = decodeSqlValues(raw.params); } catch (error) { throw failed(`params: ${error.message}`, "invalid-params"); }
159
+ return values.map(({ t, v }) => {
160
+ if (t === "null") return { t };
161
+ if (t === "i64") return { t, v: v > BigInt(MAX_SAFE) || v < -BigInt(MAX_SAFE) ? v.toString() : Number(v) };
162
+ return { t, v };
163
+ });
164
+ }
165
+ const deliverOf = (params) => (enumName(deliverMode, params?.DELIVER) === "Ref" ? "ref" : undefined);
166
+ function withDeliver(request, params) {
167
+ delete request.deliver;
168
+ const deliver = deliverOf(params);
169
+ if (deliver) request.deliver = deliver;
170
+ return request;
171
+ }
172
+ function sqlRequest({ params, raw }) {
173
+ const request = { sql: text(raw.sql) ?? "" };
174
+ const tagged = sqlParams(raw);
175
+ if (tagged) request.params = tagged;
176
+ return withDeliver(request, params);
177
+ }
178
+ const bodyRef = (ref) => ({ TOKEN: ref.token, SIZE: ref.size, FRAMES: ref.frames ?? -1, FNV1A64: str(ref.fnv1a64) });
179
+ /** {rows, columns, stream: bytes | ref: {token, size, frames, fnv1a64}} -> StreamResult-shaped record + raw "stream". */
180
+ function streamAnswer(v, type = "StreamResult") {
181
+ const record = { ROWS: v?.rows ?? 0, COLUMNS: v?.columns ?? 0 };
182
+ const answer = { raw: {} };
183
+ if (v?.ref && typeof v.ref === "object") record.REF = bodyRef(v.ref);
184
+ else if (binary(v?.stream)) answer.raw.stream = binary(v.stream);
185
+ answer.result = fit(type, record);
186
+ return answer;
187
+ }
188
+ /** A rows-answer cell (a JSON value) as a tagged SQL value: an integer is i64, any other number f64. */
189
+ function sqlCell(v) {
190
+ if (v === null || v === undefined) return { t: "null" };
191
+ if (typeof v === "boolean") return { t: "bool", v };
192
+ if (typeof v === "number") return Number.isInteger(v) ? { t: "i64", v: BigInt(v) } : { t: "f64", v };
193
+ if (typeof v === "string") return { t: "str", v };
194
+ throw failed(`storage.query_sandboxed: a cell is a ${Array.isArray(v) ? "list" : typeof v} (nested values are not SQL values)`);
195
+ }
196
+ /**
197
+ * plugin.getConfig: the config as one ModuleConfig FlatBuffer (MCFG) on raw "config" - number arrays NumberList, string
198
+ * arrays StringList, nested objects and arrays of objects TableList, keys sorted (encodeModuleConfig). Unset values
199
+ * (null / undefined) are left out; a value with no config kind (a Date, a function, a list mixing kinds) is refused.
200
+ */
201
+ function configOf(value, path) {
202
+ if (value === null || value === undefined) return undefined;
203
+ if (typeof value === "bigint") return Number(value);
204
+ if (Array.isArray(value)) return value.filter((v) => v !== null && v !== undefined).map((v, i) => configOf(v, `${path}.${i}`));
205
+ if (typeof value === "object") {
206
+ if (value instanceof Date || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) throw failed(`plugin.getConfig: ${path} is a ${value.constructor?.name ?? "object"}`);
207
+ const out = {};
208
+ for (const key of Object.keys(value)) { const v = configOf(value[key], path ? `${path}.${key}` : key); if (v !== undefined) out[key] = v; }
209
+ return out;
210
+ }
211
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
212
+ throw failed(`plugin.getConfig: ${path} is a ${typeof value}`);
213
+ }
214
+ function moduleConfig(config) {
215
+ const plain = configOf(config ?? {}, "") ?? {};
216
+ if (Array.isArray(plain) || typeof plain !== "object") throw failed("plugin.getConfig: the config is not an object");
217
+ try {
218
+ return encodeModuleConfig(plain);
219
+ } catch (error) {
220
+ throw failed(`plugin.getConfig: ${error.message}`);
221
+ }
222
+ }
223
+ function secretRequest({ params, raw }) {
224
+ const request = { id: str(params?.ID) };
225
+ if (params?.USERNAME) request.username = params.USERNAME;
226
+ if (raw.secret) request.secret = text(raw.secret);
227
+ return request;
228
+ }
229
+ function secretStatus(v) {
230
+ return { result: fit("SecretResult", {
231
+ ID: str(v?.id), CONFIGURED: v?.configured === true || v?.stored === true, USERNAME_MASKED: str(v?.username_masked),
232
+ UPDATED_MS: ms(v?.updated_at ?? v?.updatedAt) ?? 0n, VERIFIED_MS: ms(v?.verified_at) ?? 0n,
233
+ }) };
234
+ }
235
+ function nodeText(what) {
236
+ return (v) => {
237
+ if (v === undefined || v === null || v === "") throw failed(`node ${what} not available`);
238
+ return { raw: { value: String(v) } };
239
+ };
240
+ }
241
+ // p2p: the handler's entries -> P2pPnmEntry (the PNM's publish time as unix ms, the signature as hex).
242
+ function pnmEntry(e) {
243
+ return fit("P2pPnmEntry", {
244
+ 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,
245
+ 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,
246
+ SIGNATURE_HEX: e.signature ?? e.signature_hex, SIGNATURE_VERIFIED: e.signature_verified, ATTRIBUTION: e.attribution, PNM_INDEX: e.pnm_index ?? -1,
247
+ PUBLISHER_KEY_HEX: e.publisher_key ?? e.publisher_key_hex, PUBLISHER_KEY_SOURCE: e.publisher_key_source,
248
+ });
249
+ }
250
+ const p2pRecords = (v) => (binary(v?.records) ? { records: binary(v.records) } : {});
251
+ const p2pRequest = ({ params }) => withDeliver(lower(params), params);
252
+ const objects = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []);
253
+
74
254
  // Per operation: in(call) -> the host's params; out(value) -> { result, lists, raw }. Operations not listed here pass
75
255
  // their record's fields as camelCase options and answer a record from the host's camelCase fields.
76
256
  const ADAPTERS = {
@@ -156,6 +336,181 @@ const ADAPTERS = {
156
336
  "crypto.ed25519.publicKeyFromSeed": { in: ({ raw }) => ({ seed: raw.private_key }), out: data },
157
337
  "crypto.ed25519.sign": { in: ({ raw }) => ({ message: raw.data, seed: raw.private_key }), out: data },
158
338
  "crypto.ed25519.verify": { in: ({ raw }) => ({ message: raw.data, signature: raw.signature, publicKey: raw.public_key }), out: bool },
339
+
340
+ // ---- the Go node's operations, through the embedder's adapters (adapterOperations.js) ------------------------------
341
+ "plugin.getConfig": { in: () => ({}), out: (v) => ({ raw: { config: moduleConfig(v) } }) },
342
+ "node.peerId": { in: () => ({}), out: nodeText("peer ID") },
343
+ "node.publicKey": { in: () => ({}), out: nodeText("public key") },
344
+ "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) } }) },
345
+ "secrets.status": { in: secretRequest, out: secretStatus },
346
+ "secrets.put": { in: secretRequest, out: secretStatus },
347
+ "secrets.clear": { in: secretRequest, out: () => ({}) },
348
+ // storage: {schema, data} -> {cid}
349
+ "storage.write": { in: ({ params, raw }) => ({ ...lower(params), data: raw.data ?? new Uint8Array(0) }), out: (v) => ({ result: fit("StorageWriteResult", { CID: str(v?.cid) }) }) },
350
+ // the store's records ({CID, RowID, PeerID, Timestamp, MaterializedAt, SourceTags, Data}) -> list "records_meta" + the
351
+ // size-prefixed records on raw "records"
352
+ "storage.query": {
353
+ in: ({ params }) => lower(params),
354
+ out: (v) => {
355
+ const meta = [], chunks = [];
356
+ for (const r of objects(Array.isArray(v) ? v : v?.records)) {
357
+ const tags = r.SourceTags || {}, data = binary(r.Data) ?? new Uint8Array(0);
358
+ chunks.push(data);
359
+ meta.push(fit("StoredRecordMeta", {
360
+ 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,
361
+ LENGTH: data.length, PROVIDER_ID: str(tags.ProviderID), SOURCE_NAME: str(tags.SourceName), BATCH_ID: str(tags.BatchID),
362
+ PRODUCER_PEER_ID: str(tags.ProducerPeerID), LICENSE: str(tags.License),
363
+ }));
364
+ }
365
+ return { lists: { records_meta: meta }, raw: { records: sizePrefixed(chunks) } };
366
+ },
367
+ },
368
+ "storage.delete": { in: ({ params }) => lower(params), out: () => ({}) },
369
+ // {schema, provider_id, source_name, before_ms, batch, max_deletes} -> {deleted, missing, capped}
370
+ "storage.expire": { in: ({ params }) => lower(params), out: (v) => ({ result: fromObject("StorageExpireResult", v) }) },
371
+ // flat source tags, reconcile "duplicates" | "none" | "current", records, archive {source, name, raw}, provenance
372
+ // {source, json} (the "provenance" record as a JSON document, keys lower-cased)
373
+ "storage.ingest_with_source": {
374
+ in: ({ params, raw, lists }) => {
375
+ const request = lower(params);
376
+ delete request.archive_source; delete request.archive_name;
377
+ request.reconcile = enumName(reconcileKind, params?.RECONCILE).toLowerCase();
378
+ if (raw.records) request.records = raw.records;
379
+ if (raw.archive) request.archive = { source: str(params?.ARCHIVE_SOURCE), name: str(params?.ARCHIVE_NAME), raw: raw.archive };
380
+ const provenance = lists.provenance?.[0], attributes = lists.provenance_attributes;
381
+ if (provenance || attributes?.length) {
382
+ const document = {};
383
+ if (attributes?.length) document.attributes = attributes.map((a) => ({ name: str(a.NAME), value: str(a.VALUE) }));
384
+ for (const [key, v] of Object.entries(provenance || {})) document[key.toLowerCase()] = typeof v === "bigint" ? Number(v) : v ?? "";
385
+ const sorted = Object.fromEntries(Object.keys(document).sort().map((k) => [k, document[k]]));
386
+ request.provenance = { source: str(params?.SOURCE_NAME), json: textEncoder.encode(JSON.stringify(sorted)) };
387
+ }
388
+ return request;
389
+ },
390
+ out: (v) => {
391
+ const result = fromObject("StorageIngestResult", v);
392
+ if (v?.provenance) result.PROVENANCE_FILE = str(v.provenance);
393
+ return { result };
394
+ },
395
+ },
396
+ "storage.flatsql_query_stream": { in: sqlRequest, out: (v) => streamAnswer(v) },
397
+ "storage.flatsql_epoch_stream": { in: ({ params }) => withDeliver(lower(params), params), out: (v) => streamAnswer(v) },
398
+ // want "stream" answers like flatsql_query_stream (KIND Stream); "rows" ({kind: "rows", json}) with list "columns"
399
+ // and raw "cells" (tagged SQL values, row-major)
400
+ "storage.query_sandboxed": {
401
+ in: (call) => ({ ...sqlRequest(call), want: enumName(sandboxWant, call.params?.WANT).toLowerCase() }),
402
+ out: (v) => {
403
+ if (v?.kind !== "rows") {
404
+ const answer = streamAnswer(v, "SandboxQueryResult");
405
+ answer.result.KIND = sandboxWant.Stream;
406
+ return answer;
407
+ }
408
+ const doc = typeof v.json === "string" ? v.json : binary(v.json) ? text(binary(v.json)) : undefined;
409
+ if (doc === undefined) throw failed("storage.query_sandboxed: rows answer carries no rows");
410
+ let rows;
411
+ try { rows = JSON.parse(doc); } catch (error) { throw failed(`storage.query_sandboxed: ${error.message}`); }
412
+ if (!Array.isArray(rows)) throw failed("storage.query_sandboxed: rows are not a JSON array");
413
+ const columns = rows.length && rows[0] && typeof rows[0] === "object" ? Object.keys(rows[0]) : [];
414
+ const cells = [];
415
+ for (const row of rows) {
416
+ if (!row || typeof row !== "object" || Array.isArray(row)) throw failed("storage.query_sandboxed: a row is not an object");
417
+ for (const cell of Object.values(row)) cells.push(sqlCell(cell));
418
+ }
419
+ return {
420
+ result: fit("SandboxQueryResult", { KIND: sandboxWant.Rows, ROWS: rows.length, COLUMNS: columns.length }),
421
+ lists: { columns: columns.map((c) => ({ VALUE: c })) },
422
+ raw: { cells: encodeSqlValues(cells) },
423
+ };
424
+ },
425
+ },
426
+ // {tables: [{name, kind, source, records, columns: [name | {name, placeholder}]}], caps: {timeout_ms, max_rows, max_bytes}}
427
+ "storage.query_surface": {
428
+ in: () => ({}),
429
+ out: (v) => {
430
+ const tables = [], columns = [];
431
+ for (const t of objects(v?.tables)) {
432
+ const name = str(t.name);
433
+ tables.push(fit("SurfaceTable", { NAME: name, KIND: str(t.kind), SOURCE: str(t.source), RECORDS: t.records ?? 0 }));
434
+ for (const c of Array.isArray(t.columns) ? t.columns : []) {
435
+ if (typeof c === "string") columns.push(fit("SurfaceColumn", { TABLE: name, NAME: c }));
436
+ else if (c && typeof c === "object") columns.push(fit("SurfaceColumn", { TABLE: name, NAME: str(c.name), PLACEHOLDER: c.placeholder === true }));
437
+ }
438
+ }
439
+ const caps = v?.caps && typeof v.caps === "object" ? v.caps : null;
440
+ return {
441
+ ...(caps ? { result: fit("QuerySurfaceLimits", { TIMEOUT_MS: caps.timeout_ms ?? 0, MAX_ROWS: caps.max_rows ?? 0, MAX_BYTES: caps.max_bytes ?? 0 }) } : {}),
442
+ lists: { tables, columns },
443
+ };
444
+ },
445
+ },
446
+ "storage.flatsql_cache_key": {
447
+ in: (call) => {
448
+ const request = { ...lower(call.params), ...sqlRequest(call) };
449
+ if (call.lists.projection) request.projection = call.lists.projection.map((p) => str(p.VALUE));
450
+ return request;
451
+ },
452
+ out: (v) => ({ raw: { value: str(v?.key) } }),
453
+ },
454
+ // p2p: the frames ($EPM / $PNM, size-prefixed and concatenated) on raw "records"
455
+ "p2p.peers_snapshot": {
456
+ in: p2pRequest,
457
+ out: (v) => {
458
+ const peers = [], addresses = [], standards = [];
459
+ for (const p of objects(v?.peers)) {
460
+ 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 }));
461
+ for (const a of Array.isArray(p.addrs) ? p.addrs : []) addresses.push(fit("P2pPeerValue", { PEER_ID: str(p.peer_id), VALUE: str(a) }));
462
+ for (const s of Array.isArray(p.standards) ? p.standards : []) standards.push(fit("P2pPeerValue", { PEER_ID: str(p.peer_id), VALUE: str(s) }));
463
+ }
464
+ return { result: fromObject("P2pSummary", v), lists: { peers, peer_addresses: addresses, peer_standards: standards }, raw: p2pRecords(v) };
465
+ },
466
+ },
467
+ "p2p.standards_snapshot": { in: p2pRequest, out: (v) => ({ lists: { entries: objects(v?.entries).map(pnmEntry) }, raw: p2pRecords(v) }) },
468
+ "p2p.pnm_history": { in: p2pRequest, out: (v) => ({ result: fromObject("P2pSummary", v), lists: { entries: objects(v?.entries).map(pnmEntry) }, raw: p2pRecords(v) }) },
469
+ // {known, reason, pinned, self, fresh, standard, schema, pnm, serving: {batch_id, ..., pnm, ref | stream}}: the served
470
+ // batch's PNM pointer when one is served, else the newest
471
+ "p2p.latest_dataset": {
472
+ in: p2pRequest,
473
+ out: (v) => {
474
+ const serving = v?.serving && typeof v.serving === "object" ? v.serving : {};
475
+ const pnm = (serving.pnm && typeof serving.pnm === "object" ? serving.pnm : v?.pnm) || {};
476
+ const result = fit("P2pLatestDataset", {
477
+ KNOWN: v?.known === true, REASON: v?.reason, PINNED: v?.pinned, SELF: v?.self, FRESH: v?.fresh, STANDARD: v?.standard, SCHEMA: v?.schema,
478
+ 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),
479
+ PNM_SIGNATURE_VERIFIED: pnm.signature_verified, PNM_ATTRIBUTION: pnm.attribution,
480
+ BATCH_ID: serving.batch_id, PROVIDER_ID: serving.provider_id, SOURCE_NAME: serving.source_name, RECORD_COUNT: serving.record_count,
481
+ BYTE_COUNT: serving.byte_count, PARTS: serving.parts, PUBLISHED_MS: ms(serving.published_at), ETAG_FNV1A64: serving.etag_fnv1a64,
482
+ REF: serving.ref && typeof serving.ref === "object" ? bodyRef(serving.ref) : undefined,
483
+ });
484
+ return { result, raw: binary(serving.stream) ? { stream: binary(serving.stream) } : {} };
485
+ },
486
+ },
487
+ // node status and activity
488
+ "node_status_read.status": {
489
+ in: () => ({}),
490
+ out: (v) => {
491
+ const store = v?.store || {}, service = v?.service || {};
492
+ const record = {
493
+ 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,
494
+ STORAGE_PATH: str(store.storage_path), SERVICE_STATE: str(service.state), SERVICE_MODE: str(service.mode),
495
+ };
496
+ if (v?.disk && typeof v.disk === "object") {
497
+ 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 });
498
+ }
499
+ const history = [];
500
+ if (v?.bandwidth && typeof v.bandwidth === "object") {
501
+ const bw = v.bandwidth;
502
+ 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 });
503
+ for (const s of objects(bw.history)) {
504
+ 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 }));
505
+ }
506
+ }
507
+ return { result: fit("NodeStatusReport", record), lists: { bandwidth_history: history } };
508
+ },
509
+ },
510
+ "node_activity_read.activity": {
511
+ in: ({ params }) => lower(params),
512
+ 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) })) } }),
513
+ },
159
514
  };
160
515
  function data(v) { return { raw: { data: bytesOf(v) ?? new Uint8Array(0) } }; }
161
516
  function bool(v) { return { result: { VALUE: Boolean(v) } }; }
@@ -193,10 +548,12 @@ export function typedResultOf(call, value) {
193
548
  export function hostcallErrorCode(error) {
194
549
  if (error?.hostcallCode) return error.hostcallCode;
195
550
  const name = error?.name ?? error?.constructor?.name ?? "";
196
- if (name === "HostCapabilityError" || error?.code === "host-capability-denied") return "not-authorized";
551
+ if (name === "HostCapabilityError" || name === "BrowserHostCapabilityError" || error?.code === "host-capability-denied") return "not-authorized";
197
552
  if (name === "HostFilesystemScopeError") return "sandbox";
198
553
  if (name === "AbortError" || name === "TimeoutError" || /timed out/i.test(error?.message ?? "")) return "timeout";
199
554
  if (/^Unknown .* operation|not available in the synchronous hostcall ABI|does not implement/.test(error?.message ?? "")) return "unsupported";
555
+ // a string or list that does not fit its aligned record (the Go node's recordErr)
556
+ if (/exceeds? the record/.test(error?.message ?? "")) return "too-large";
200
557
  if (error instanceof RangeError || error instanceof TypeError) return "invalid-params";
201
558
  return "failed";
202
559
  }
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
- capabilityAdapters?: Record<string, Record<string, (...args: any[]) => unknown>>;
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
- capabilityAdapters?: Record<string, Record<string, (...args: any[]) => unknown>>;
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[];