space-data-module-sdk 0.8.27 → 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/README.md +5 -4
- package/docs/assembly.js +0 -18
- package/docs/assets/ai-credits/ai-credits.js +116 -0
- package/docs/assets/sdn-chrome/sdn-chrome.css +434 -0
- package/docs/assets/sdn-chrome/sdn-chrome.js +236 -0
- package/docs/browser-wasmedge-isomorphic.html +29 -41
- package/docs/byo-wasm-quickstart.html +29 -41
- package/docs/conformance.html +29 -41
- package/docs/events-abi.html +29 -41
- package/docs/families/analytics.html +29 -41
- package/docs/families/attitude.html +29 -41
- package/docs/families/behavior.html +29 -41
- package/docs/families/breakup.html +29 -41
- package/docs/families/conjunction.html +29 -41
- package/docs/families/data-source.html +29 -41
- package/docs/families/effects.html +29 -41
- package/docs/families/environment.html +29 -41
- package/docs/families/estimation.html +29 -41
- package/docs/families/gnc.html +29 -41
- package/docs/families/maneuver.html +29 -41
- package/docs/families/obstruction.html +29 -41
- package/docs/families/propagator.html +29 -41
- package/docs/families/propulsion.html +29 -41
- package/docs/families/reentry.html +29 -41
- package/docs/families/rf.html +29 -41
- package/docs/families/scheduler.html +29 -41
- package/docs/families/sensor.html +29 -41
- package/docs/families/signature.html +29 -41
- package/docs/flatsql-host-contract.html +29 -41
- package/docs/flatsql-streaming-standard.html +29 -41
- package/docs/gpu-module-abi.html +29 -41
- package/docs/index.html +43 -47
- package/docs/isomorphic-pthreads.html +29 -41
- package/docs/isomorphic-sdn-runtime-plan.html +29 -41
- package/docs/language-runtime-matrix.html +29 -41
- package/docs/media/module-sdk-reel-poster.webp +0 -0
- package/docs/media/module-sdk-reel.mp4 +0 -0
- package/docs/media/module-sdk-reel.webm +0 -0
- package/docs/media/reel/reel.css +53 -0
- package/docs/media/reel/reel.js +272 -0
- package/docs/module-bundle-runtime-plan.html +29 -41
- package/docs/module-publication-standard.html +29 -41
- package/docs/node-red-default-node-parity.html +29 -41
- package/docs/protect-and-sign.html +29 -41
- package/docs/protocol-installation.html +29 -41
- package/docs/publication-submission.html +29 -41
- package/docs/secrets-capability.html +29 -41
- package/docs/styles.css +89 -157
- package/docs/testing-harness.html +29 -41
- package/docs/tri-runtime-parity-gate.html +29 -41
- package/docs/tri-runtime-parity.html +29 -41
- package/package.json +5 -3
- package/schemas/runtime/FlowNotice.fbs +39 -0
- package/schemas/runtime/HostOps.fbs +455 -0
- package/schemas/runtime/HttpRequest.fbs +25 -0
- package/schemas/runtime/HttpResponse.fbs +24 -0
- package/schemas/runtime/IngestRequest.fbs +61 -0
- package/schemas/runtime/IngestResult.fbs +23 -0
- package/schemas/runtime/ModuleConfig.fbs +41 -0
- package/schemas/runtime/RuntimeCommon.fbs +33 -0
- package/schemas/runtime/TimerTick.fbs +18 -0
- package/src/capabilities.js +3 -0
- package/src/compiler/compileModule.js +20 -2
- package/src/generated/runtime/aligned/HostOps_aligned.js +3913 -0
- package/src/generated/runtime/aligned/HostOps_aligned.ts +4605 -0
- package/src/generated/runtime/aligned/HostOps_enums.js +12 -0
- package/src/generated/runtime/aligned/HostOps_enums.ts +6 -0
- package/src/generated/runtime/cpp/FlowNotice_generated.h +367 -0
- package/src/generated/runtime/cpp/HostOps_aligned.h +3540 -0
- package/src/generated/runtime/cpp/HttpRequest_generated.h +317 -0
- package/src/generated/runtime/cpp/HttpResponse_generated.h +315 -0
- package/src/generated/runtime/cpp/IngestRequest_generated.h +829 -0
- package/src/generated/runtime/cpp/IngestResult_generated.h +319 -0
- package/src/generated/runtime/cpp/ModuleConfig_generated.h +604 -0
- package/src/generated/runtime/cpp/RuntimeCommon_generated.h +410 -0
- package/src/generated/runtime/cpp/TimerTick_generated.h +229 -0
- package/src/generated/runtime/sdn/runtime/ArchiveTarget.js +78 -0
- package/src/generated/runtime/sdn/runtime/ArchiveTarget.ts +104 -0
- package/src/generated/runtime/sdn/runtime/ConfigEntry.js +202 -0
- package/src/generated/runtime/sdn/runtime/ConfigEntry.ts +251 -0
- package/src/generated/runtime/sdn/runtime/ConfigTable.js +80 -0
- package/src/generated/runtime/sdn/runtime/ConfigTable.ts +97 -0
- package/src/generated/runtime/sdn/runtime/FlowNotice.js +196 -0
- package/src/generated/runtime/sdn/runtime/FlowNotice.ts +254 -0
- package/src/generated/runtime/sdn/runtime/Header.js +79 -0
- package/src/generated/runtime/sdn/runtime/Header.ts +100 -0
- package/src/generated/runtime/sdn/runtime/HttpRequest.js +216 -0
- package/src/generated/runtime/sdn/runtime/HttpRequest.ts +265 -0
- package/src/generated/runtime/sdn/runtime/HttpResponse.js +216 -0
- package/src/generated/runtime/sdn/runtime/HttpResponse.ts +267 -0
- package/src/generated/runtime/sdn/runtime/IngestRequest.js +121 -0
- package/src/generated/runtime/sdn/runtime/IngestRequest.ts +155 -0
- package/src/generated/runtime/sdn/runtime/IngestResult.js +184 -0
- package/src/generated/runtime/sdn/runtime/IngestResult.ts +235 -0
- package/src/generated/runtime/sdn/runtime/ModuleConfig.js +92 -0
- package/src/generated/runtime/sdn/runtime/ModuleConfig.ts +114 -0
- package/src/generated/runtime/sdn/runtime/Provenance.js +320 -0
- package/src/generated/runtime/sdn/runtime/Provenance.ts +405 -0
- package/src/generated/runtime/sdn/runtime/SourceTags.js +181 -0
- package/src/generated/runtime/sdn/runtime/SourceTags.ts +253 -0
- package/src/generated/runtime/sdn/runtime/TimerTick.js +119 -0
- package/src/generated/runtime/sdn/runtime/TimerTick.ts +148 -0
- package/src/generated/runtime/sdn/runtime/configValueKind.js +12 -0
- package/src/generated/runtime/sdn/runtime/configValueKind.ts +19 -0
- package/src/generated/runtime/sdn/runtime/flowNoticeKind.js +11 -0
- package/src/generated/runtime/sdn/runtime/flowNoticeKind.ts +34 -0
- package/src/generated/runtime/sdn/runtime/reconcileMode.js +9 -0
- package/src/generated/runtime/sdn/runtime/reconcileMode.ts +23 -0
- package/src/generated/runtime/sdn/runtime.js +16 -0
- package/src/generated/runtime/sdn/runtime.ts +17 -0
- package/src/host/abi.js +32 -6
- package/src/host/adapterOperations.js +79 -0
- package/src/host/browserHost.js +65 -2
- package/src/host/cpp/typedHostcall.hpp +252 -0
- package/src/host/hostWorkerBundleSources.js +3 -3
- package/src/host/nodeHost.js +50 -0
- package/src/host/typedDispatch.js +582 -0
- package/src/index.d.ts +25 -2
- package/src/invoke/codec.js +3 -2
- package/src/standards/runtimeContracts.js +596 -0
- package/src/standards/sharedCatalog.js +27 -0
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
// The SDK JS hosts' side of the typed hostcall (an SDS $PIV invocation, module -> host; see HOST_OPERATIONS in
|
|
2
|
+
// src/standards/runtimeContracts.js): a decoded call's aligned records, list ports and raw ports become the arguments
|
|
3
|
+
// the host's operation already takes, and its answer becomes the operation's result record, list and raw ports. The
|
|
4
|
+
// hosts' own methods are unchanged; only the wire is typed.
|
|
5
|
+
import {
|
|
6
|
+
HOST_OPERATIONS,
|
|
7
|
+
decodeHostCall,
|
|
8
|
+
decodeSqlValues,
|
|
9
|
+
encodeHostCallResult,
|
|
10
|
+
encodeSqlValues,
|
|
11
|
+
} from "../standards/runtimeContracts.js";
|
|
12
|
+
import * as hostOps from "../generated/runtime/aligned/HostOps_aligned.js";
|
|
13
|
+
import { deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
|
|
14
|
+
import { base64ToBytes, bytesToBase64 } from "../utils/encoding.js";
|
|
15
|
+
|
|
16
|
+
const textDecoder = new TextDecoder();
|
|
17
|
+
const textEncoder = new TextEncoder();
|
|
18
|
+
const text = (bytes) => (bytes === undefined ? undefined : textDecoder.decode(bytes));
|
|
19
|
+
const bytesOf = (value) => (value === undefined || value === null ? undefined : value instanceof Uint8Array ? value : typeof value === "string" ? textEncoder.encode(value) : new Uint8Array(value));
|
|
20
|
+
const items = (values) => (values || []).map((v) => ({ VALUE: String(v) }));
|
|
21
|
+
const unix = (value) => BigInt(Math.round(value instanceof Date ? value.getTime() : Number(value)));
|
|
22
|
+
|
|
23
|
+
/** FIELD_NAME -> fieldName */
|
|
24
|
+
const camel = (field) => field.toLowerCase().replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
25
|
+
/** fieldName -> FIELD_NAME */
|
|
26
|
+
const upper = (key) => key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
|
|
27
|
+
|
|
28
|
+
/** A record's set fields as the host's camelCase options (zero / empty = not given). */
|
|
29
|
+
function optionsOf(record) {
|
|
30
|
+
const out = {};
|
|
31
|
+
for (const [field, value] of Object.entries(record || {})) {
|
|
32
|
+
if (value === null || value === undefined || value === "" || value === 0 || value === 0n || value === false) continue;
|
|
33
|
+
out[camel(field)] = typeof value === "bigint" ? Number(value) : value;
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** The host's camelCase answer as a record of `type` (fields the record does not have are left out). */
|
|
38
|
+
function recordOf(type, value) {
|
|
39
|
+
if (!type || !value || typeof value !== "object") return null;
|
|
40
|
+
const record = {};
|
|
41
|
+
for (const [key, v] of Object.entries(value)) {
|
|
42
|
+
if (v === null || v === undefined || v instanceof Uint8Array || typeof v === "object") continue;
|
|
43
|
+
record[upper(key)] = v;
|
|
44
|
+
}
|
|
45
|
+
return pick(type, record);
|
|
46
|
+
}
|
|
47
|
+
// Only the fields the record declares (the encoder refuses unknown fields).
|
|
48
|
+
function pick(type, record) {
|
|
49
|
+
const proto = hostOps[type]?.prototype;
|
|
50
|
+
if (!proto) return record;
|
|
51
|
+
return Object.fromEntries(Object.entries(record).filter(([k]) => typeof proto[`set${k}`] === "function"));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** "name: value" lines -> header object, and back. */
|
|
55
|
+
function headersIn(block) {
|
|
56
|
+
if (!block) return undefined;
|
|
57
|
+
const headers = {};
|
|
58
|
+
for (const line of text(block).split(/\r?\n/)) {
|
|
59
|
+
const at = line.indexOf(":");
|
|
60
|
+
if (at > 0) headers[line.slice(0, at).trim()] = line.slice(at + 1).trim();
|
|
61
|
+
}
|
|
62
|
+
return headers;
|
|
63
|
+
}
|
|
64
|
+
function headersOut(headers) {
|
|
65
|
+
if (!headers) return undefined;
|
|
66
|
+
const entries = typeof headers.entries === "function" && !(headers instanceof Map) && !Array.isArray(headers) ? Array.from(headers.entries()) : headers instanceof Map ? Array.from(headers) : Object.entries(headers);
|
|
67
|
+
return entries.map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : v}`).join("\r\n");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const GCM_TAG = 16;
|
|
71
|
+
function splitGcm(data) {
|
|
72
|
+
if (!data || data.length < GCM_TAG) throw Object.assign(new Error("AES-GCM data is shorter than its 16-byte tag"), { hostcallCode: "invalid-params" });
|
|
73
|
+
return { ciphertext: data.subarray(0, data.length - GCM_TAG), tag: data.subarray(data.length - GCM_TAG) };
|
|
74
|
+
}
|
|
75
|
+
const concat = (a, b) => { const out = new Uint8Array(a.length + b.length); out.set(a, 0); out.set(b, a.length); return out; };
|
|
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
|
+
|
|
249
|
+
// Per operation: in(call) -> the host's params; out(value) -> { result, lists, raw }. Operations not listed here pass
|
|
250
|
+
// their record's fields as camelCase options and answer a record from the host's camelCase fields.
|
|
251
|
+
const ADAPTERS = {
|
|
252
|
+
"host.runtimeTarget": { out: (v) => ({ raw: { value: String(v) } }) },
|
|
253
|
+
"host.listCapabilities": { out: (v) => ({ lists: { items: items(v) } }) },
|
|
254
|
+
"host.listSupportedCapabilities": { out: (v) => ({ lists: { items: items(v) } }) },
|
|
255
|
+
"host.listOperations": { out: (v) => ({ lists: { items: items(v) } }) },
|
|
256
|
+
"host.hasCapability": { in: ({ params }) => ({ capability: params?.CAPABILITY }), out: (v) => ({ result: { VALUE: Boolean(v) } }) },
|
|
257
|
+
"clock.now": { out: (v) => ({ result: { UNIX_MS: unix(v) } }) },
|
|
258
|
+
"clock.nowIso": { out: (v) => ({ raw: { value: String(v) } }) },
|
|
259
|
+
"clock.monotonicNow": { out: (v) => ({ result: { VALUE: Number(v) } }) },
|
|
260
|
+
"random.bytes": { in: ({ params }) => ({ length: params?.LENGTH || 32 }), out: (v) => ({ raw: { data: bytesOf(v) } }) },
|
|
261
|
+
"timers.delay": { in: ({ params }) => ({ ms: params?.MS ?? 0 }), out: () => ({}) },
|
|
262
|
+
"schedule.parse": {
|
|
263
|
+
in: ({ params }) => ({ expression: params?.EXPRESSION }),
|
|
264
|
+
out: (v) => ({ lists: { fields: Object.entries(v || {}).filter(([, f]) => f && typeof f === "object" && Array.isArray(f.values)).map(([name, f]) => ({ NAME: name, SOURCE: String(f.source ?? ""), HAS_WILDCARD: Boolean(f.hasWildcard), VALUES: f.values })) } }),
|
|
265
|
+
},
|
|
266
|
+
"schedule.matches": { in: ({ params }) => ({ expression: params?.EXPRESSION, date: params?.AT_MS ? new Date(Number(params.AT_MS)) : new Date() }), out: (v) => ({ result: { VALUE: Boolean(v) } }) },
|
|
267
|
+
"schedule.next": { in: ({ params }) => ({ expression: params?.EXPRESSION, from: params?.AT_MS ? new Date(Number(params.AT_MS)) : new Date() }), out: (v) => ({ result: { UNIX_MS: unix(v) } }) },
|
|
268
|
+
"http.request": {
|
|
269
|
+
in: ({ params, raw }) => ({
|
|
270
|
+
url: text(raw.url), method: params?.METHOD || "GET", headers: headersIn(raw.headers), body: raw.body,
|
|
271
|
+
timeoutMs: params?.TIMEOUT_MS || undefined, responseType: "bytes", redirect: params?.NO_REDIRECTS ? "manual" : "follow",
|
|
272
|
+
maxBytes: params?.MAX_BYTES ? Number(params.MAX_BYTES) : undefined,
|
|
273
|
+
}),
|
|
274
|
+
out: (v, { params }) => {
|
|
275
|
+
const body = bytesOf(v?.body) ?? new Uint8Array(0);
|
|
276
|
+
if (params?.MAX_BYTES && body.length > Number(params.MAX_BYTES)) throw Object.assign(new Error(`HTTP body of ${body.length} bytes exceeds MAX_BYTES ${params.MAX_BYTES}`), { hostcallCode: "too-large" });
|
|
277
|
+
return { result: { STATUS: v?.status ?? 0, RETRIEVED_MS: BigInt(Date.now()) }, raw: { url: String(v?.url ?? ""), headers: headersOut(v?.headers) ?? "", body } };
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
"websocket.exchange": {
|
|
281
|
+
in: ({ params, raw }) => ({
|
|
282
|
+
url: text(raw.url), protocols: raw.protocols ? text(raw.protocols).split(",").map((p) => p.trim()).filter(Boolean) : undefined,
|
|
283
|
+
message: raw.message === undefined ? undefined : params?.MESSAGE_IS_TEXT ? text(raw.message) : raw.message,
|
|
284
|
+
timeoutMs: params?.TIMEOUT_MS || undefined, expectResponse: !params?.NO_RESPONSE, responseType: "bytes",
|
|
285
|
+
}),
|
|
286
|
+
out: (v) => ({ result: { PROTOCOL: v?.protocol ?? "", EXTENSIONS: v?.extensions ?? "", CLOSE_CODE: v?.closeCode ?? -1, CLOSE_REASON: v?.closeReason ?? "", BODY_IS_TEXT: typeof v?.body === "string" }, raw: { url: String(v?.url ?? ""), ...(v?.body == null ? {} : { body: bytesOf(v.body) }) } }),
|
|
287
|
+
},
|
|
288
|
+
"mqtt.publish": { in: ({ params, raw }) => ({ ...optionsOf(params), keepAliveSeconds: params?.KEEP_ALIVE_S || undefined, payload: raw.payload, password: text(raw.password) }), out: (v) => ({ result: recordOf("MqttResult", v) }) },
|
|
289
|
+
"mqtt.subscribeOnce": { in: ({ params, raw }) => ({ ...optionsOf(params), keepAliveSeconds: params?.KEEP_ALIVE_S || undefined, password: text(raw.password), responseType: "bytes" }), out: (v) => ({ result: recordOf("MqttResult", v), raw: v?.payload == null && v?.body == null ? {} : { body: bytesOf(v.payload ?? v.body) } }) },
|
|
290
|
+
"tcp.request": socket(),
|
|
291
|
+
"udp.request": socket(),
|
|
292
|
+
"tls.request": socket(({ raw }) => ({ ca: text(raw.ca), cert: text(raw.cert), key: text(raw.key) })),
|
|
293
|
+
"filesystem.resolvePath": { in: ({ raw }) => ({ path: text(raw.path) }), out: (v) => ({ raw: { path: String(v) } }) },
|
|
294
|
+
"filesystem.readFile": { in: ({ raw }) => ({ path: text(raw.path) }), out: (v) => ({ raw: { data: bytesOf(v) } }) },
|
|
295
|
+
"filesystem.writeFile": { in: ({ raw }) => ({ path: text(raw.path), value: raw.data ?? new Uint8Array(0) }), out: () => ({}) },
|
|
296
|
+
"filesystem.appendFile": { in: ({ raw }) => ({ path: text(raw.path), value: raw.data ?? new Uint8Array(0) }), out: () => ({}) },
|
|
297
|
+
"filesystem.deleteFile": { in: ({ raw }) => ({ path: text(raw.path) }), out: () => ({}) },
|
|
298
|
+
"filesystem.mkdir": { in: ({ params, raw }) => ({ path: text(raw.path), recursive: !params?.NOT_RECURSIVE }), out: () => ({}) },
|
|
299
|
+
"filesystem.readdir": { in: ({ raw }) => ({ path: text(raw.path) ?? "." }), out: (v) => ({ lists: { entries: (v || []).map((e) => ({ NAME: e.name, IS_FILE: Boolean(e.isFile), IS_DIRECTORY: Boolean(e.isDirectory) })) } }) },
|
|
300
|
+
"filesystem.stat": { in: ({ raw }) => ({ path: text(raw.path) }), out: (v) => ({ result: { SIZE: BigInt(v?.size ?? 0), IS_FILE: Boolean(v?.isFile), IS_DIRECTORY: Boolean(v?.isDirectory), CTIME_MS: Number(v?.ctimeMs ?? 0), MTIME_MS: Number(v?.mtimeMs ?? 0) }, raw: { path: String(v?.path ?? "") } }) },
|
|
301
|
+
"filesystem.rename": { in: ({ raw }) => ({ fromPath: text(raw.path), toPath: text(raw.to_path) }), out: () => ({}) },
|
|
302
|
+
"exec.execFile": {
|
|
303
|
+
in: ({ params, raw, lists }) => ({
|
|
304
|
+
file: text(raw.file), args: (lists.args || []).map((a) => a.VALUE), cwd: text(raw.cwd), input: raw.input,
|
|
305
|
+
env: lists.env ? Object.fromEntries(lists.env.map((e) => [e.NAME, e.VALUE])) : undefined, timeoutMs: params?.TIMEOUT_MS || undefined,
|
|
306
|
+
}),
|
|
307
|
+
out: (v) => ({ result: { EXIT_CODE: v?.exitCode ?? -1, SIGNAL: v?.signal ?? "" }, raw: { stdout: bytesOf(v?.stdout) ?? new Uint8Array(0), stderr: bytesOf(v?.stderr) ?? new Uint8Array(0) } }),
|
|
308
|
+
},
|
|
309
|
+
"context.get": { in: ({ params }) => ({ scope: params?.SCOPE, key: params?.KEY }), out: (v) => ({ result: { VALUE: v !== undefined && v !== null }, raw: v == null ? {} : { value: bytesOf(v) } }) },
|
|
310
|
+
"context.set": { in: ({ params, raw }) => ({ scope: params?.SCOPE, key: params?.KEY, value: raw.value ?? new Uint8Array(0) }), out: () => ({}) },
|
|
311
|
+
"context.delete": { in: ({ params }) => ({ scope: params?.SCOPE, key: params?.KEY }), out: (v) => ({ result: { VALUE: Boolean(v) } }) },
|
|
312
|
+
"context.listKeys": { in: ({ params }) => ({ scope: params?.SCOPE }), out: (v) => ({ lists: { items: items(v) } }) },
|
|
313
|
+
"context.listScopes": { out: (v) => ({ lists: { items: items(v) } }) },
|
|
314
|
+
// crypto: keys, data, signatures and nonces are raw frames; AES-GCM data carries its 16-byte tag at the end
|
|
315
|
+
"crypto.sha256": { in: ({ raw }) => ({ value: raw.data ?? new Uint8Array(0) }), out: data },
|
|
316
|
+
"crypto.sha512": { in: ({ raw }) => ({ value: raw.data ?? new Uint8Array(0) }), out: data },
|
|
317
|
+
"crypto.hkdf": { in: ({ params, raw }) => ({ ikm: raw.ikm, salt: raw.salt ?? new Uint8Array(0), info: raw.info, length: params?.LENGTH || 32 }), out: data },
|
|
318
|
+
"crypto.aesGcmEncrypt": { in: ({ raw }) => ({ key: raw.key, plaintext: raw.data ?? new Uint8Array(0), iv: raw.nonce, aad: raw.aad }), out: (v, { raw }) => ({ raw: { data: concat(v.ciphertext, v.tag), nonce: raw.nonce } }) },
|
|
319
|
+
"crypto.aesGcmDecrypt": { in: ({ raw }) => ({ key: raw.key, ...splitGcm(raw.data), iv: raw.nonce, aad: raw.aad }), out: data },
|
|
320
|
+
"crypto.x25519.generateKeypair": { out: (v) => ({ raw: { private_key: v.privateKey, public_key: v.publicKey } }) },
|
|
321
|
+
"crypto.x25519.publicKey": { in: ({ raw }) => ({ privateKey: raw.private_key }), out: data },
|
|
322
|
+
"crypto.x25519.sharedSecret": { in: ({ raw }) => ({ privateKey: raw.private_key, publicKey: raw.public_key }), out: data },
|
|
323
|
+
// the sealed box's envelope is its protected blob: ciphertext + tag with the SDS $REC / $ENC records appended
|
|
324
|
+
"crypto.sealedBox.encryptForRecipient": { in: ({ raw }) => ({ plaintext: raw.data ?? new Uint8Array(0), recipientPublicKey: raw.public_key, context: raw.info ? text(raw.info) : undefined }), out: (v) => ({ raw: { data: base64ToBytes(v.protectedBlobBase64) } }) },
|
|
325
|
+
"crypto.sealedBox.decryptFromEnvelope": { in: ({ raw }) => ({ envelope: { protectedBlobBase64: bytesToBase64(raw.envelope ?? raw.data) }, recipientPrivateKey: raw.private_key }), out: data },
|
|
326
|
+
"crypto.secp256k1.publicKeyFromPrivate": { in: ({ raw }) => ({ privateKey: raw.private_key }), out: data },
|
|
327
|
+
"crypto.secp256k1.sign": { in: ({ raw }) => ({ message: raw.data, privateKey: raw.private_key }), out: data },
|
|
328
|
+
"crypto.secp256k1.verify": { in: ({ raw }) => ({ message: raw.data, signature: raw.signature, publicKey: raw.public_key }), out: bool },
|
|
329
|
+
"crypto.secp256k1.signDigest": { in: ({ raw }) => ({ digest: raw.data, privateKey: raw.private_key }), out: data },
|
|
330
|
+
"crypto.secp256k1.verifyDigest": { in: ({ raw }) => ({ digest: raw.data, signature: raw.signature, publicKey: raw.public_key }), out: bool },
|
|
331
|
+
"crypto.ed25519.publicKeyFromSeed": { in: ({ raw }) => ({ seed: raw.private_key }), out: data },
|
|
332
|
+
"crypto.ed25519.sign": { in: ({ raw }) => ({ message: raw.data, seed: raw.private_key }), out: data },
|
|
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
|
+
},
|
|
509
|
+
};
|
|
510
|
+
function data(v) { return { raw: { data: bytesOf(v) ?? new Uint8Array(0) } }; }
|
|
511
|
+
function bool(v) { return { result: { VALUE: Boolean(v) } }; }
|
|
512
|
+
function socket(extra = () => ({})) {
|
|
513
|
+
return {
|
|
514
|
+
in: (call) => {
|
|
515
|
+
const { params, raw } = call;
|
|
516
|
+
const options = optionsOf(params);
|
|
517
|
+
delete options.noResponse; delete options.allowUnauthorized; delete options.serverName;
|
|
518
|
+
return {
|
|
519
|
+
...options, data: raw.data, responseEncoding: "bytes",
|
|
520
|
+
expectResponse: !params?.NO_RESPONSE, rejectUnauthorized: !params?.ALLOW_UNAUTHORIZED,
|
|
521
|
+
servername: params?.SERVER_NAME || undefined, ...extra(call),
|
|
522
|
+
};
|
|
523
|
+
},
|
|
524
|
+
out: (v) => ({ result: recordOf("SocketResult", v), raw: v?.body == null ? {} : { body: bytesOf(v.body) } }),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** The host's params for a decoded typed call. */
|
|
529
|
+
export function hostParamsOf(call) {
|
|
530
|
+
const adapter = ADAPTERS[call.op];
|
|
531
|
+
if (adapter?.in) return adapter.in(call);
|
|
532
|
+
return { ...optionsOf(call.params), ...Object.fromEntries(Object.entries(call.raw).map(([k, v]) => [camel(k), v])) };
|
|
533
|
+
}
|
|
534
|
+
/** The typed answer ({ result, lists, raw }) for the host's value. */
|
|
535
|
+
export function typedResultOf(call, value) {
|
|
536
|
+
const adapter = ADAPTERS[call.op];
|
|
537
|
+
if (adapter?.out) return adapter.out(value, call);
|
|
538
|
+
const spec = HOST_OPERATIONS[call.op];
|
|
539
|
+
return { result: spec?.result ? recordOf(spec.result, value) : undefined };
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** The HOSTCALL_ERROR_CODES code for a host error. */
|
|
543
|
+
export function hostcallErrorCode(error) {
|
|
544
|
+
if (error?.hostcallCode) return error.hostcallCode;
|
|
545
|
+
const name = error?.name ?? error?.constructor?.name ?? "";
|
|
546
|
+
if (name === "HostCapabilityError" || name === "BrowserHostCapabilityError" || error?.code === "host-capability-denied") return "not-authorized";
|
|
547
|
+
if (name === "HostFilesystemScopeError") return "sandbox";
|
|
548
|
+
if (name === "AbortError" || name === "TimeoutError" || /timed out/i.test(error?.message ?? "")) return "timeout";
|
|
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";
|
|
552
|
+
if (error instanceof RangeError || error instanceof TypeError) return "invalid-params";
|
|
553
|
+
return "failed";
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Answer one typed hostcall payload: decode the $PIV request, run `dispatch(op, params)` (sync, or a Promise when
|
|
558
|
+
* `allowAsync`), and encode the $PIV response. Errors become STATUS FAILED with their code; nothing throws.
|
|
559
|
+
*/
|
|
560
|
+
export function answerTypedHostCall(payload, dispatch, { allowAsync = false } = {}) {
|
|
561
|
+
let call;
|
|
562
|
+
const failure = (error) => encodeHostCallResult({ ok: false, error: { code: hostcallErrorCode(error), message: String(error?.message ?? error) } });
|
|
563
|
+
const success = (value) => {
|
|
564
|
+
try { return encodeHostCallResult({ ok: true, op: call.op, ...typedResultOf(call, value) }); } catch (error) { return failure(error); }
|
|
565
|
+
};
|
|
566
|
+
try {
|
|
567
|
+
call = decodeHostCall(payload);
|
|
568
|
+
if (!HOST_OPERATIONS[call.op]) throw Object.assign(new Error(`Unknown host operation "${call.op}".`), { hostcallCode: "unsupported" });
|
|
569
|
+
const value = dispatch(call.op, hostParamsOf(call));
|
|
570
|
+
if (value && typeof value.then === "function") {
|
|
571
|
+
if (!allowAsync) {
|
|
572
|
+
if (typeof value.catch === "function") value.catch(() => {});
|
|
573
|
+
throw Object.assign(new Error(`Operation "${call.op}" is not available in the synchronous hostcall ABI.`), { hostcallCode: "unsupported" });
|
|
574
|
+
}
|
|
575
|
+
return value.then(success, failure);
|
|
576
|
+
}
|
|
577
|
+
return success(value);
|
|
578
|
+
} catch (error) {
|
|
579
|
+
if (error && !error.hostcallCode && call === undefined) error.hostcallCode = "invalid-params";
|
|
580
|
+
return failure(error);
|
|
581
|
+
}
|
|
582
|
+
}
|
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[];
|