@thru/sdk 0.2.22

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.
Files changed (73) hide show
  1. package/README.abi.md +112 -0
  2. package/README.md +342 -0
  3. package/dist/abi/index.cjs +946 -0
  4. package/dist/abi/index.cjs.map +1 -0
  5. package/dist/abi/index.d.cts +331 -0
  6. package/dist/abi/index.d.ts +331 -0
  7. package/dist/abi/index.js +892 -0
  8. package/dist/abi/index.js.map +1 -0
  9. package/dist/abi/wasm/bundler/abi_reflect_wasm.d.ts +65 -0
  10. package/dist/abi/wasm/bundler/abi_reflect_wasm.js +5 -0
  11. package/dist/abi/wasm/bundler/abi_reflect_wasm_bg.js +412 -0
  12. package/dist/abi/wasm/bundler/abi_reflect_wasm_bg.wasm +0 -0
  13. package/dist/abi/wasm/bundler/abi_reflect_wasm_bg.wasm.d.ts +24 -0
  14. package/dist/abi/wasm/bundler/package.json +17 -0
  15. package/dist/abi/wasm/node/abi_reflect_wasm.d.ts +65 -0
  16. package/dist/abi/wasm/node/abi_reflect_wasm.js +425 -0
  17. package/dist/abi/wasm/node/abi_reflect_wasm_bg.wasm +0 -0
  18. package/dist/abi/wasm/node/abi_reflect_wasm_bg.wasm.d.ts +24 -0
  19. package/dist/abi/wasm/node/package.json +11 -0
  20. package/dist/abi/wasm/web/abi_reflect_wasm.d.ts +114 -0
  21. package/dist/abi/wasm/web/abi_reflect_wasm.js +499 -0
  22. package/dist/abi/wasm/web/abi_reflect_wasm_bg.wasm +0 -0
  23. package/dist/abi/wasm/web/abi_reflect_wasm_bg.wasm.d.ts +24 -0
  24. package/dist/abi/wasm/web/package.json +15 -0
  25. package/dist/chunk-CVBQ4UPL.js +3614 -0
  26. package/dist/chunk-CVBQ4UPL.js.map +1 -0
  27. package/dist/chunk-NSBPE2FW.js +15 -0
  28. package/dist/chunk-NSBPE2FW.js.map +1 -0
  29. package/dist/chunk-RL3Q6FDE.js +105 -0
  30. package/dist/chunk-RL3Q6FDE.js.map +1 -0
  31. package/dist/chunk-UDIXYJXC.js +260 -0
  32. package/dist/chunk-UDIXYJXC.js.map +1 -0
  33. package/dist/chunk-YQDWOMNO.js +271 -0
  34. package/dist/chunk-YQDWOMNO.js.map +1 -0
  35. package/dist/client-Cfi7zRLm.d.cts +1247 -0
  36. package/dist/client-worIo0a3.d.ts +1247 -0
  37. package/dist/client.cjs +3791 -0
  38. package/dist/client.cjs.map +1 -0
  39. package/dist/client.d.cts +7 -0
  40. package/dist/client.d.ts +7 -0
  41. package/dist/client.js +7 -0
  42. package/dist/client.js.map +1 -0
  43. package/dist/crypto/index.cjs +170 -0
  44. package/dist/crypto/index.cjs.map +1 -0
  45. package/dist/crypto/index.d.cts +60 -0
  46. package/dist/crypto/index.d.ts +60 -0
  47. package/dist/crypto/index.js +5 -0
  48. package/dist/crypto/index.js.map +1 -0
  49. package/dist/helpers/index.cjs +270 -0
  50. package/dist/helpers/index.cjs.map +1 -0
  51. package/dist/helpers/index.d.cts +15 -0
  52. package/dist/helpers/index.d.ts +15 -0
  53. package/dist/helpers/index.js +4 -0
  54. package/dist/helpers/index.js.map +1 -0
  55. package/dist/metafile-cjs.json +1 -0
  56. package/dist/metafile-esm.json +1 -0
  57. package/dist/proto/index.cjs +433 -0
  58. package/dist/proto/index.cjs.map +1 -0
  59. package/dist/proto/index.d.cts +435 -0
  60. package/dist/proto/index.d.ts +435 -0
  61. package/dist/proto/index.js +4 -0
  62. package/dist/proto/index.js.map +1 -0
  63. package/dist/sdk.cjs +4137 -0
  64. package/dist/sdk.cjs.map +1 -0
  65. package/dist/sdk.d.cts +36 -0
  66. package/dist/sdk.d.ts +36 -0
  67. package/dist/sdk.js +7 -0
  68. package/dist/sdk.js.map +1 -0
  69. package/dist/streaming_service_pb-DvCdJiCr.d.cts +4877 -0
  70. package/dist/streaming_service_pb-DvCdJiCr.d.ts +4877 -0
  71. package/dist/webcrypto-LTajLAad.d.cts +3 -0
  72. package/dist/webcrypto-LTajLAad.d.ts +3 -0
  73. package/package.json +88 -0
@@ -0,0 +1,946 @@
1
+ 'use strict';
2
+
3
+ var yaml = require('yaml');
4
+
5
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
6
+ function _interopNamespace(e) {
7
+ if (e && e.__esModule) return e;
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var yaml__namespace = /*#__PURE__*/_interopNamespace(yaml);
25
+
26
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
27
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
28
+ }) : x)(function(x) {
29
+ if (typeof require !== "undefined") return require.apply(this, arguments);
30
+ throw Error('Dynamic require of "' + x + '" is not supported');
31
+ });
32
+
33
+ // src/abi/utils/bytes.ts
34
+ function hexToBytes(hex) {
35
+ let normalized = hex.trim().replace(/[\s_]/g, "");
36
+ if (normalized.startsWith("0x") || normalized.startsWith("0X")) {
37
+ normalized = normalized.slice(2);
38
+ }
39
+ if (normalized.length === 0) return new Uint8Array();
40
+ if (normalized.length % 2 !== 0) {
41
+ throw new Error("Hex input must contain an even number of characters");
42
+ }
43
+ const bytes = new Uint8Array(normalized.length / 2);
44
+ for (let i = 0; i < normalized.length; i += 2) {
45
+ const byte = Number.parseInt(normalized.slice(i, i + 2), 16);
46
+ if (Number.isNaN(byte)) {
47
+ throw new Error("Hex input contains non-hexadecimal characters");
48
+ }
49
+ bytes[i / 2] = byte;
50
+ }
51
+ return bytes;
52
+ }
53
+ function toUint8Array(input) {
54
+ if (input instanceof Uint8Array) {
55
+ return input;
56
+ }
57
+ if (ArrayBuffer.isView(input)) {
58
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
59
+ }
60
+ if (input instanceof ArrayBuffer) {
61
+ return new Uint8Array(input);
62
+ }
63
+ if (Array.isArray(input)) {
64
+ return Uint8Array.from(input);
65
+ }
66
+ throw new TypeError("Unsupported buffer input");
67
+ }
68
+
69
+ // src/abi/utils/runtime.ts
70
+ function isNodeRuntime() {
71
+ return typeof process !== "undefined" && Boolean(process.versions?.node);
72
+ }
73
+
74
+ // src/abi/wasmBridge.ts
75
+ var configuredWasmUrl;
76
+ function configureWasm(url) {
77
+ if (cachedBindings) {
78
+ console.warn("configureWasm called after WASM was already loaded. Configuration ignored.");
79
+ return;
80
+ }
81
+ configuredWasmUrl = url;
82
+ }
83
+ var wasmDir = resolveWasmDir();
84
+ var bindingsPromise;
85
+ var cachedBindings;
86
+ var dynamicImport = new Function("specifier", "return import(specifier)");
87
+ var resolveModuleUrl = new Function("path", "base", "return new URL(path, base).href");
88
+ function isObjectLike(value) {
89
+ return typeof value === "object" && value !== null || typeof value === "function";
90
+ }
91
+ function hasWasmBinding(value, name) {
92
+ return isObjectLike(value) && typeof value[name] === "function";
93
+ }
94
+ function isWasmReflectBindings(value) {
95
+ return hasWasmBinding(value, "reflect") && hasWasmBinding(value, "reflect_instruction") && hasWasmBinding(value, "format_reflection");
96
+ }
97
+ function describeImportedBindings(value) {
98
+ if (value === null) return "null";
99
+ if (Array.isArray(value)) return "array";
100
+ return typeof value;
101
+ }
102
+ function unwrapImportedBindings(imported, relativePath) {
103
+ const defaultExport = isObjectLike(imported) ? imported.default : void 0;
104
+ const candidate = defaultExport ?? imported;
105
+ if (isWasmReflectBindings(candidate)) {
106
+ return candidate;
107
+ }
108
+ if (isWasmReflectBindings(imported)) {
109
+ return imported;
110
+ }
111
+ throw new Error(
112
+ `WASM bindings import did not return a module object for ${relativePath} (received ${describeImportedBindings(imported)})`
113
+ );
114
+ }
115
+ function resolveImportMetaUrl() {
116
+ const url = (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href));
117
+ if (typeof url === "string" && url.length > 0) return url;
118
+ const location = typeof globalThis.location === "object" && globalThis.location ? globalThis.location : void 0;
119
+ if (typeof location?.href === "string" && location.href.length > 0) {
120
+ return location.href;
121
+ }
122
+ return "file:///";
123
+ }
124
+ async function importModule(specifier) {
125
+ return dynamicImport(specifier);
126
+ }
127
+ function requireModule(moduleUrl) {
128
+ try {
129
+ const requireFn = typeof __require === "function" ? __require : void 0;
130
+ if (!requireFn) return void 0;
131
+ const specifier = moduleUrl.startsWith("file:") ? decodeURIComponent(new URL(moduleUrl).pathname) : moduleUrl;
132
+ return requireFn(specifier);
133
+ } catch {
134
+ return void 0;
135
+ }
136
+ }
137
+ function resolveWasmDir() {
138
+ const url = resolveImportMetaUrl();
139
+ if (url.includes("/src/abi/")) return "../../wasm/abi";
140
+ if (url.includes("/dist/")) return "./wasm";
141
+ return "./wasm";
142
+ }
143
+ async function loadBindings() {
144
+ if (cachedBindings) {
145
+ return cachedBindings;
146
+ }
147
+ if (!bindingsPromise) {
148
+ let loader;
149
+ if (isNodeRuntime()) {
150
+ loader = loadNodeBindings();
151
+ } else if (configuredWasmUrl) {
152
+ loader = loadWebBindings(configuredWasmUrl);
153
+ } else {
154
+ loader = loadBundlerBindings();
155
+ }
156
+ bindingsPromise = loader.then(
157
+ (bindings) => {
158
+ cachedBindings = bindings;
159
+ return bindings;
160
+ },
161
+ (err) => {
162
+ bindingsPromise = void 0;
163
+ throw err;
164
+ }
165
+ );
166
+ }
167
+ return bindingsPromise;
168
+ }
169
+ async function loadWebBindings(wasmUrl) {
170
+ const moduleUrl = resolveModuleUrl(`${wasmDir}/web/abi_reflect_wasm.js`, resolveImportMetaUrl());
171
+ const mod = await importModule(moduleUrl);
172
+ await mod.default(wasmUrl);
173
+ return mod;
174
+ }
175
+ async function loadBundlerBindings() {
176
+ const mod = await importBindings("bundler/abi_reflect_wasm.js");
177
+ return mod;
178
+ }
179
+ async function loadNodeBindings() {
180
+ const relativePath = "node/abi_reflect_wasm.js";
181
+ const moduleUrl = resolveModuleUrl(`${wasmDir}/${relativePath}`, resolveImportMetaUrl());
182
+ const imported = requireModule(moduleUrl) ?? await importModule(moduleUrl);
183
+ const mod = unwrapImportedBindings(imported, relativePath);
184
+ if (typeof mod.wasm_start === "function") {
185
+ mod.wasm_start();
186
+ }
187
+ return mod;
188
+ }
189
+ async function importBindings(relativePath) {
190
+ const moduleUrl = resolveModuleUrl(`${wasmDir}/${relativePath}`, resolveImportMetaUrl());
191
+ const imported = await importModule(moduleUrl);
192
+ return unwrapImportedBindings(imported, relativePath);
193
+ }
194
+ async function callReflect(abiYaml, typeName, buffer) {
195
+ const bindings = await loadBindings();
196
+ const result = bindings.reflect(abiYaml, typeName, buffer);
197
+ return JSON.parse(result);
198
+ }
199
+ async function callLayoutIr(abiYaml) {
200
+ const bindings = await loadBindings();
201
+ const result = bindings.build_layout_ir(abiYaml);
202
+ return JSON.parse(result);
203
+ }
204
+ async function callReflectInstruction(abiYaml, buffer) {
205
+ const bindings = await loadBindings();
206
+ const result = bindings.reflect_instruction(abiYaml, buffer);
207
+ return JSON.parse(result);
208
+ }
209
+ async function callReflectAccount(abiYaml, buffer) {
210
+ const bindings = await loadBindings();
211
+ const result = bindings.reflect_account(abiYaml, buffer);
212
+ return JSON.parse(result);
213
+ }
214
+ async function callReflectEvent(abiYaml, buffer) {
215
+ const bindings = await loadBindings();
216
+ const result = bindings.reflect_event(abiYaml, buffer);
217
+ return JSON.parse(result);
218
+ }
219
+ async function reflect(abiYaml, typeName, payload) {
220
+ if (payload.type === "binary") {
221
+ return callReflect(abiYaml, typeName, toUint8Array(payload.value));
222
+ }
223
+ if (payload.type === "hex") {
224
+ return callReflect(abiYaml, typeName, hexToBytes(payload.value));
225
+ }
226
+ throw new Error(`Invalid payload type`);
227
+ }
228
+ async function buildLayoutIr(abiYaml) {
229
+ return callLayoutIr(abiYaml);
230
+ }
231
+ async function reflectInstruction(abiYaml, payload) {
232
+ if (payload.type === "binary") {
233
+ return callReflectInstruction(abiYaml, toUint8Array(payload.value));
234
+ }
235
+ if (payload.type === "hex") {
236
+ return callReflectInstruction(abiYaml, hexToBytes(payload.value));
237
+ }
238
+ throw new Error(`Invalid payload type`);
239
+ }
240
+ async function reflectAccount(abiYaml, payload) {
241
+ if (payload.type === "binary") {
242
+ return callReflectAccount(abiYaml, toUint8Array(payload.value));
243
+ }
244
+ if (payload.type === "hex") {
245
+ return callReflectAccount(abiYaml, hexToBytes(payload.value));
246
+ }
247
+ throw new Error(`Invalid payload type`);
248
+ }
249
+ async function reflectEvent(abiYaml, payload) {
250
+ if (payload.type === "binary") {
251
+ return callReflectEvent(abiYaml, toUint8Array(payload.value));
252
+ }
253
+ if (payload.type === "hex") {
254
+ return callReflectEvent(abiYaml, hexToBytes(payload.value));
255
+ }
256
+ throw new Error(`Invalid payload type`);
257
+ }
258
+ async function ensureWasmLoaded() {
259
+ await loadBindings();
260
+ }
261
+ function requireBindings() {
262
+ if (cachedBindings) {
263
+ return cachedBindings;
264
+ }
265
+ throw new Error("WASM bindings are not loaded. Call ensureWasmLoaded() first.");
266
+ }
267
+ function formatReflection(raw, options) {
268
+ const bindings = requireBindings();
269
+ const serialized = JSON.stringify(raw);
270
+ if (options && Object.keys(options).length > 0) {
271
+ const optionsJson = JSON.stringify(options);
272
+ const result2 = bindings.format_reflection_with_options(serialized, optionsJson);
273
+ return JSON.parse(result2);
274
+ }
275
+ const result = bindings.format_reflection(serialized);
276
+ return JSON.parse(result);
277
+ }
278
+ async function callReflectWithManifest(manifest, rootPackage, typeName, buffer) {
279
+ const bindings = await loadBindings();
280
+ const manifestJson = JSON.stringify(manifest);
281
+ const result = bindings.reflect_with_manifest(manifestJson, rootPackage, typeName, buffer);
282
+ return JSON.parse(result);
283
+ }
284
+ async function callReflectInstructionWithManifest(manifest, rootPackage, buffer) {
285
+ const bindings = await loadBindings();
286
+ const manifestJson = JSON.stringify(manifest);
287
+ const result = bindings.reflect_instruction_with_manifest(manifestJson, rootPackage, buffer);
288
+ return JSON.parse(result);
289
+ }
290
+ async function callReflectAccountWithManifest(manifest, rootPackage, buffer) {
291
+ const bindings = await loadBindings();
292
+ const manifestJson = JSON.stringify(manifest);
293
+ const result = bindings.reflect_account_with_manifest(manifestJson, rootPackage, buffer);
294
+ return JSON.parse(result);
295
+ }
296
+ async function callReflectEventWithManifest(manifest, rootPackage, buffer) {
297
+ const bindings = await loadBindings();
298
+ const manifestJson = JSON.stringify(manifest);
299
+ const result = bindings.reflect_event_with_manifest(manifestJson, rootPackage, buffer);
300
+ return JSON.parse(result);
301
+ }
302
+ async function reflectWithManifest(manifest, rootPackage, typeName, payload) {
303
+ if (payload.type === "binary") {
304
+ return callReflectWithManifest(manifest, rootPackage, typeName, toUint8Array(payload.value));
305
+ }
306
+ if (payload.type === "hex") {
307
+ return callReflectWithManifest(manifest, rootPackage, typeName, hexToBytes(payload.value));
308
+ }
309
+ throw new Error(`Invalid payload type`);
310
+ }
311
+ async function reflectInstructionWithManifest(manifest, rootPackage, payload) {
312
+ if (payload.type === "binary") {
313
+ return callReflectInstructionWithManifest(manifest, rootPackage, toUint8Array(payload.value));
314
+ }
315
+ if (payload.type === "hex") {
316
+ return callReflectInstructionWithManifest(manifest, rootPackage, hexToBytes(payload.value));
317
+ }
318
+ throw new Error(`Invalid payload type`);
319
+ }
320
+ async function reflectAccountWithManifest(manifest, rootPackage, payload) {
321
+ if (payload.type === "binary") {
322
+ return callReflectAccountWithManifest(manifest, rootPackage, toUint8Array(payload.value));
323
+ }
324
+ if (payload.type === "hex") {
325
+ return callReflectAccountWithManifest(manifest, rootPackage, hexToBytes(payload.value));
326
+ }
327
+ throw new Error(`Invalid payload type`);
328
+ }
329
+ async function reflectEventWithManifest(manifest, rootPackage, payload) {
330
+ if (payload.type === "binary") {
331
+ return callReflectEventWithManifest(manifest, rootPackage, toUint8Array(payload.value));
332
+ }
333
+ if (payload.type === "hex") {
334
+ return callReflectEventWithManifest(manifest, rootPackage, hexToBytes(payload.value));
335
+ }
336
+ throw new Error(`Invalid payload type`);
337
+ }
338
+ async function buildLayoutIrWithManifest(manifest, rootPackage) {
339
+ const bindings = await loadBindings();
340
+ const manifestJson = JSON.stringify(manifest);
341
+ const result = bindings.build_layout_ir_with_manifest(manifestJson, rootPackage);
342
+ return JSON.parse(result);
343
+ }
344
+ async function getManifestPackages(manifest) {
345
+ const bindings = await loadBindings();
346
+ const manifestJson = JSON.stringify(manifest);
347
+ const result = bindings.get_manifest_packages(manifestJson);
348
+ return JSON.parse(result);
349
+ }
350
+ async function validateManifest(manifest) {
351
+ const bindings = await loadBindings();
352
+ const manifestJson = JSON.stringify(manifest);
353
+ const result = bindings.validate_manifest(manifestJson);
354
+ return JSON.parse(result);
355
+ }
356
+
357
+ // src/abi/imports/types.ts
358
+ var ResolutionError = class extends Error {
359
+ constructor(code, message, details) {
360
+ super(message);
361
+ this.code = code;
362
+ this.details = details;
363
+ this.name = "ResolutionError";
364
+ }
365
+ };
366
+ var ABI_ACCOUNT_HEADER_SIZE = 45;
367
+ var ABI_STATE_OPEN = 0;
368
+ var ABI_STATE_FINALIZED = 1;
369
+ var DEFAULT_RPC_ENDPOINTS = {
370
+ mainnet: "https://rpc.thru.network",
371
+ testnet: "https://rpc-testnet.thru.network"
372
+ };
373
+
374
+ // src/abi/imports/onchainFetcher.ts
375
+ var ABI_ACCOUNT_SUFFIX = "_abi_account";
376
+ var ABI_ACCOUNT_SUFFIX_BYTES = new TextEncoder().encode(ABI_ACCOUNT_SUFFIX);
377
+ var ABI_META_HEADER_SIZE = 4;
378
+ var ABI_META_BODY_SIZE = 96;
379
+ var ABI_META_ACCOUNT_SIZE = ABI_META_HEADER_SIZE + ABI_META_BODY_SIZE;
380
+ var ABI_META_VERSION = 1;
381
+ var ABI_META_KIND_OFFICIAL = 0;
382
+ var ABI_META_KIND_EXTERNAL = 1;
383
+ var DEFAULT_ABI_MANAGER_PROGRAM_ID = "taWqAAOSe9pavaaMpkc9VbSLBUMbuW6Mk59sZlSbcNHsJA";
384
+ async function sha256Bytes(data) {
385
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
386
+ return new Uint8Array(hashBuffer);
387
+ }
388
+ function concatBytes(...chunks) {
389
+ const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
390
+ const out = new Uint8Array(total);
391
+ let offset = 0;
392
+ for (const chunk of chunks) {
393
+ out.set(chunk, offset);
394
+ offset += chunk.length;
395
+ }
396
+ return out;
397
+ }
398
+ function abiMetaBodyForProgram(program) {
399
+ const body = new Uint8Array(ABI_META_BODY_SIZE);
400
+ body.set(program.slice(0, 32), 0);
401
+ return body;
402
+ }
403
+ async function deriveAbiAccountSeed(kind, body) {
404
+ return sha256Bytes(concatBytes(new Uint8Array([kind]), body, ABI_ACCOUNT_SUFFIX_BYTES));
405
+ }
406
+ async function createProgramDefinedAccountAddress(owner, isEphemeral, seed) {
407
+ const flag = new Uint8Array([isEphemeral ? 1 : 0]);
408
+ return sha256Bytes(concatBytes(owner, flag, seed));
409
+ }
410
+ async function deriveAbiAccountAddress(kind, body, owner, isEphemeral) {
411
+ const seed = await deriveAbiAccountSeed(kind, body);
412
+ return createProgramDefinedAccountAddress(owner, isEphemeral, seed);
413
+ }
414
+ async function deriveOfficialAbiAddress(programAddress, abiManagerProgramId = DEFAULT_ABI_MANAGER_PROGRAM_ID) {
415
+ const programBytes = decodeAddress(programAddress);
416
+ const managerBytes = decodeAddress(abiManagerProgramId);
417
+ const body = abiMetaBodyForProgram(programBytes);
418
+ return deriveAbiAccountAddress(ABI_META_KIND_OFFICIAL, body, managerBytes, false);
419
+ }
420
+ function parseAbiMetaAccount(data) {
421
+ if (data.length < ABI_META_ACCOUNT_SIZE) {
422
+ throw new Error(
423
+ `ABI meta account data too short: ${data.length} bytes, expected at least ${ABI_META_ACCOUNT_SIZE}`
424
+ );
425
+ }
426
+ const version = data[0];
427
+ const kind = data[1];
428
+ const flags = data[2] | data[3] << 8;
429
+ const body = data.slice(ABI_META_HEADER_SIZE, ABI_META_HEADER_SIZE + ABI_META_BODY_SIZE);
430
+ if (version !== ABI_META_VERSION) {
431
+ throw new Error(`Unsupported ABI meta version: ${version}`);
432
+ }
433
+ if (kind !== ABI_META_KIND_OFFICIAL && kind !== ABI_META_KIND_EXTERNAL) {
434
+ throw new Error(`Unsupported ABI meta kind: ${kind}`);
435
+ }
436
+ return { version, kind, flags, body };
437
+ }
438
+ function parseAbiAccountData(data) {
439
+ if (data.length < ABI_ACCOUNT_HEADER_SIZE) {
440
+ throw new Error(
441
+ `ABI account data too short: ${data.length} bytes, expected at least ${ABI_ACCOUNT_HEADER_SIZE}`
442
+ );
443
+ }
444
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
445
+ const abiMetaAccount = data.slice(0, 32);
446
+ const revision = view.getBigUint64(32, true);
447
+ const state = data[40];
448
+ const contentSize = view.getUint32(41, true);
449
+ if (state !== ABI_STATE_OPEN && state !== ABI_STATE_FINALIZED) {
450
+ throw new Error(`Invalid ABI account state: ${state}`);
451
+ }
452
+ const expectedSize = ABI_ACCOUNT_HEADER_SIZE + contentSize;
453
+ if (data.length < expectedSize) {
454
+ throw new Error(
455
+ `ABI account data truncated: ${data.length} bytes, expected ${expectedSize}`
456
+ );
457
+ }
458
+ const contentBytes = data.slice(ABI_ACCOUNT_HEADER_SIZE, expectedSize);
459
+ const content = new TextDecoder().decode(contentBytes);
460
+ return {
461
+ abiMetaAccount,
462
+ revision,
463
+ state,
464
+ content
465
+ };
466
+ }
467
+ function revisionMatches(revision, spec) {
468
+ switch (spec.type) {
469
+ case "latest":
470
+ return true;
471
+ case "exact":
472
+ return revision === BigInt(spec.value);
473
+ case "minimum":
474
+ return revision >= BigInt(spec.value);
475
+ case "atSlot":
476
+ return true;
477
+ default:
478
+ return false;
479
+ }
480
+ }
481
+ function versionContextForRevision(spec) {
482
+ if (spec.type === "atSlot") {
483
+ return { version: { case: "slot", value: spec.slot } };
484
+ }
485
+ return { version: { case: "current", value: {} } };
486
+ }
487
+ var OnchainFetcher = class {
488
+ constructor(config = {}) {
489
+ this.rpcEndpoints = { ...DEFAULT_RPC_ENDPOINTS, ...config.rpcEndpoints };
490
+ this.thruClient = config.thruClient;
491
+ const managerId = config.abiManagerProgramId ?? DEFAULT_ABI_MANAGER_PROGRAM_ID;
492
+ this.abiManagerProgramId = decodeAddress(managerId);
493
+ this.abiManagerIsEphemeral = config.abiManagerIsEphemeral ?? false;
494
+ }
495
+ /**
496
+ * Fetch ABI content from an on-chain account.
497
+ *
498
+ * The `revision` parameter controls both how the account is selected
499
+ * server-side (via version_context when `atSlot` is used) and whether the
500
+ * returned revision is validated against an expected value (`exact` /
501
+ * `minimum`). For `atSlot`, the returned `FetchResult.revision` reflects
502
+ * the revision that was active at that slot.
503
+ */
504
+ async fetch(address, target, network, revision) {
505
+ const addressBytes = this.parseAddress(address);
506
+ let abiAddress;
507
+ if (target === "program") {
508
+ const body = abiMetaBodyForProgram(addressBytes);
509
+ abiAddress = await deriveAbiAccountAddress(
510
+ ABI_META_KIND_OFFICIAL,
511
+ body,
512
+ this.abiManagerProgramId,
513
+ this.abiManagerIsEphemeral
514
+ );
515
+ } else if (target === "abi-meta") {
516
+ const metaData = await this.fetchAccountData(addressBytes, network, revision);
517
+ const meta = parseAbiMetaAccount(metaData);
518
+ abiAddress = await deriveAbiAccountAddress(
519
+ meta.kind,
520
+ meta.body,
521
+ this.abiManagerProgramId,
522
+ this.abiManagerIsEphemeral
523
+ );
524
+ } else {
525
+ abiAddress = addressBytes;
526
+ }
527
+ const accountData = await this.fetchAccountData(abiAddress, network, revision);
528
+ const parsed = parseAbiAccountData(accountData);
529
+ if (!revisionMatches(parsed.revision, revision)) {
530
+ const revisionStr = revision.type === "exact" ? `exactly ${revision.value}` : revision.type === "minimum" ? `at least ${revision.value}` : revision.type === "atSlot" ? `active at slot ${revision.slot}` : "latest";
531
+ throw new Error(
532
+ `ABI revision mismatch: got ${parsed.revision}, expected ${revisionStr}`
533
+ );
534
+ }
535
+ return {
536
+ abiYaml: parsed.content,
537
+ revision: parsed.revision,
538
+ isFinalized: parsed.state === ABI_STATE_FINALIZED
539
+ };
540
+ }
541
+ /**
542
+ * Get the RPC endpoint for a network.
543
+ */
544
+ getRpcEndpoint(network) {
545
+ const endpoint = this.rpcEndpoints[network];
546
+ if (!endpoint) {
547
+ throw new Error(
548
+ `Unknown network: ${network}. Configure rpcEndpoints for this network.`
549
+ );
550
+ }
551
+ return endpoint;
552
+ }
553
+ parseAddress(address) {
554
+ return decodeAddress(address);
555
+ }
556
+ async fetchAccountData(address, network, revision) {
557
+ if (this.thruClient) {
558
+ return this.fetchWithThruClient(address, revision);
559
+ }
560
+ if (revision.type === "atSlot") {
561
+ throw new Error(
562
+ "Slot-aware ABI fetch requires a ThruClient; the HTTP/JSON-RPC fallback does not support historical slot queries"
563
+ );
564
+ }
565
+ return this.fetchWithHttp(address, network);
566
+ }
567
+ async fetchWithThruClient(address, revision) {
568
+ if (!this.thruClient) {
569
+ throw new Error("ThruClient not configured");
570
+ }
571
+ const response = await this.thruClient.query.getRawAccount({
572
+ address: { value: address },
573
+ versionContext: versionContextForRevision(revision)
574
+ });
575
+ if (!response.rawData) {
576
+ throw new Error("Account not found or has no data");
577
+ }
578
+ return response.rawData;
579
+ }
580
+ async fetchWithHttp(address, network) {
581
+ const endpoint = this.getRpcEndpoint(network);
582
+ const addressStr = encodeThruAddress(address);
583
+ const response = await fetch(`${endpoint}/v1/accounts/${addressStr}:raw`, {
584
+ method: "GET",
585
+ headers: {
586
+ Accept: "application/json"
587
+ }
588
+ });
589
+ if (!response.ok) {
590
+ if (response.status === 404) {
591
+ throw new Error(`ABI account not found: ${addressStr}`);
592
+ }
593
+ throw new Error(`Failed to fetch account: ${response.status} ${response.statusText}`);
594
+ }
595
+ const json = await response.json();
596
+ if (!json.rawData) {
597
+ throw new Error("Account has no data");
598
+ }
599
+ return base64Decode(json.rawData);
600
+ }
601
+ };
602
+ var BASE64_URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
603
+ function decodeAddress(address) {
604
+ if (address.startsWith("ta") && address.length === 46) {
605
+ return decodeThruAddress(address);
606
+ }
607
+ throw new Error(`Invalid Thru address format: ${address} (expected 46-char ta-prefixed address)`);
608
+ }
609
+ function decodeThruAddress(address) {
610
+ if (address.length !== 46 || !address.startsWith("ta")) {
611
+ throw new Error(`Invalid Thru address: ${address}`);
612
+ }
613
+ const invlut = new Int16Array(256);
614
+ invlut.fill(-1);
615
+ for (let i = 0; i < BASE64_URL_ALPHABET.length; i += 1) {
616
+ invlut[BASE64_URL_ALPHABET.charCodeAt(i)] = i;
617
+ }
618
+ let inIdx = 2;
619
+ let inSz = 40;
620
+ let outIdx = 0;
621
+ let checksum = 0;
622
+ const out = new Uint8Array(32);
623
+ while (inSz >= 4) {
624
+ const a2 = invlut[address.charCodeAt(inIdx + 0)];
625
+ const b2 = invlut[address.charCodeAt(inIdx + 1)];
626
+ const c2 = invlut[address.charCodeAt(inIdx + 2)];
627
+ const d2 = invlut[address.charCodeAt(inIdx + 3)];
628
+ if (a2 < 0 || b2 < 0 || c2 < 0 || d2 < 0) {
629
+ throw new Error(`Invalid Thru address character at ${inIdx}`);
630
+ }
631
+ const triple2 = a2 << 18 | b2 << 12 | c2 << 6 | d2;
632
+ const temp12 = triple2 >> 16 & 255;
633
+ checksum += temp12;
634
+ out[outIdx++] = temp12;
635
+ const temp22 = triple2 >> 8 & 255;
636
+ checksum += temp22;
637
+ out[outIdx++] = temp22;
638
+ const temp3 = triple2 & 255;
639
+ checksum += temp3;
640
+ out[outIdx++] = temp3;
641
+ inIdx += 4;
642
+ inSz -= 4;
643
+ }
644
+ const a = invlut[address.charCodeAt(inIdx + 0)];
645
+ const b = invlut[address.charCodeAt(inIdx + 1)];
646
+ const c = invlut[address.charCodeAt(inIdx + 2)];
647
+ const d = invlut[address.charCodeAt(inIdx + 3)];
648
+ if (a < 0 || b < 0 || c < 0 || d < 0) {
649
+ throw new Error(`Invalid Thru address character at ${inIdx}`);
650
+ }
651
+ const triple = a << 18 | b << 12 | c << 6 | d;
652
+ const temp1 = triple >> 16 & 255;
653
+ checksum += temp1;
654
+ out[outIdx++] = temp1;
655
+ const temp2 = triple >> 8 & 255;
656
+ checksum += temp2;
657
+ out[outIdx++] = temp2;
658
+ const incomingChecksum = triple & 255;
659
+ if ((checksum & 255) !== incomingChecksum) {
660
+ throw new Error("Invalid Thru address checksum");
661
+ }
662
+ return out;
663
+ }
664
+ function encodeThruAddress(bytes) {
665
+ if (bytes.length !== 32) {
666
+ throw new Error(`Expected 32 bytes, got ${bytes.length}`);
667
+ }
668
+ function maskForBits(bits) {
669
+ return bits === 0 ? 0 : (1 << bits) - 1;
670
+ }
671
+ let output = "ta";
672
+ let checksum = 0;
673
+ let accumulator = 0;
674
+ let bitsCollected = 0;
675
+ for (let i = 0; i < 30; i++) {
676
+ const byte = bytes[i];
677
+ checksum += byte;
678
+ accumulator = accumulator << 8 | byte;
679
+ bitsCollected += 8;
680
+ while (bitsCollected >= 6) {
681
+ const index = accumulator >> bitsCollected - 6 & 63;
682
+ output += BASE64_URL_ALPHABET[index];
683
+ bitsCollected -= 6;
684
+ accumulator &= maskForBits(bitsCollected);
685
+ }
686
+ }
687
+ const secondLast = bytes[30];
688
+ checksum += secondLast;
689
+ accumulator = accumulator << 8 | secondLast;
690
+ bitsCollected += 8;
691
+ const last = bytes[31];
692
+ checksum += last;
693
+ accumulator = accumulator << 8 | last;
694
+ bitsCollected += 8;
695
+ accumulator = accumulator << 8 | checksum & 255;
696
+ bitsCollected += 8;
697
+ while (bitsCollected >= 6) {
698
+ const index = accumulator >> bitsCollected - 6 & 63;
699
+ output += BASE64_URL_ALPHABET[index];
700
+ bitsCollected -= 6;
701
+ accumulator &= maskForBits(bitsCollected);
702
+ }
703
+ return output;
704
+ }
705
+ function base64Decode(str) {
706
+ const binaryStr = atob(str);
707
+ const bytes = new Uint8Array(binaryStr.length);
708
+ for (let i = 0; i < binaryStr.length; i++) {
709
+ bytes[i] = binaryStr.charCodeAt(i);
710
+ }
711
+ return bytes;
712
+ }
713
+ async function resolveImports(rootAbiYaml, config = {}) {
714
+ const resolver = new ImportResolver(config);
715
+ return resolver.resolve(rootAbiYaml);
716
+ }
717
+ function createManifest(result) {
718
+ return result.manifest;
719
+ }
720
+ var ImportResolver = class {
721
+ constructor(config = {}) {
722
+ this.onchainFetcher = config.onchainFetcher ?? new OnchainFetcher({
723
+ rpcEndpoints: { ...DEFAULT_RPC_ENDPOINTS, ...config.rpcEndpoints }
724
+ });
725
+ this.maxDepth = config.maxDepth ?? 10;
726
+ this.visited = /* @__PURE__ */ new Map();
727
+ this.inProgress = /* @__PURE__ */ new Set();
728
+ }
729
+ async resolve(rootAbiYaml) {
730
+ this.visited.clear();
731
+ this.inProgress.clear();
732
+ const rootPackage = await this.resolvePackage(rootAbiYaml, false, 0);
733
+ const allPackages = Array.from(this.visited.values());
734
+ const manifest = {};
735
+ for (const pkg of allPackages) {
736
+ manifest[pkg.id.packageName] = pkg.abiYaml;
737
+ }
738
+ return {
739
+ root: rootPackage,
740
+ allPackages,
741
+ manifest
742
+ };
743
+ }
744
+ async resolvePackage(abiYaml, isRemote, depth) {
745
+ if (depth > this.maxDepth) {
746
+ throw new ResolutionError(
747
+ "CYCLIC_DEPENDENCY",
748
+ `Maximum resolution depth (${this.maxDepth}) exceeded`
749
+ );
750
+ }
751
+ const abiFile = this.parseAbiYaml(abiYaml);
752
+ const packageId = this.extractPackageId(abiFile);
753
+ const canonicalKey = `${packageId.packageName}@${packageId.version}`;
754
+ if (this.inProgress.has(canonicalKey)) {
755
+ throw new ResolutionError(
756
+ "CYCLIC_DEPENDENCY",
757
+ `Cyclic dependency detected: ${canonicalKey}`
758
+ );
759
+ }
760
+ const existing = this.visited.get(canonicalKey);
761
+ if (existing) {
762
+ return existing;
763
+ }
764
+ for (const [key, pkg] of this.visited) {
765
+ if (pkg.id.packageName === packageId.packageName && pkg.id.version !== packageId.version) {
766
+ throw new ResolutionError(
767
+ "VERSION_CONFLICT",
768
+ `Version conflict for ${packageId.packageName}: ${pkg.id.version} vs ${packageId.version}`,
769
+ { existing: pkg.id, conflicting: packageId }
770
+ );
771
+ }
772
+ }
773
+ this.inProgress.add(canonicalKey);
774
+ const imports = abiFile.abi.imports ?? [];
775
+ const dependencies = [];
776
+ for (const importYaml of imports) {
777
+ const importSource = this.normalizeImportSource(importYaml);
778
+ if (isRemote && importSource.type === "path") {
779
+ throw new ResolutionError(
780
+ "UNSUPPORTED_IMPORT_TYPE",
781
+ `Remote package ${packageId.packageName} cannot import local path: ${importSource.path}`
782
+ );
783
+ }
784
+ const childIsRemote = importSource.type !== "path";
785
+ const depPackage = await this.resolveImport(importSource, childIsRemote, depth + 1);
786
+ dependencies.push(depPackage.id);
787
+ }
788
+ this.inProgress.delete(canonicalKey);
789
+ const resolvedPackage = {
790
+ id: packageId,
791
+ source: { type: "path", path: "<root>" },
792
+ abiYaml,
793
+ dependencies,
794
+ isRemote
795
+ };
796
+ this.visited.set(canonicalKey, resolvedPackage);
797
+ return resolvedPackage;
798
+ }
799
+ async resolveImport(source, parentIsRemote, depth) {
800
+ switch (source.type) {
801
+ case "path":
802
+ throw new ResolutionError(
803
+ "UNSUPPORTED_IMPORT_TYPE",
804
+ `Path imports are not supported in browser. Use CLI 'bundle' command. Path: ${source.path}`
805
+ );
806
+ case "git":
807
+ throw new ResolutionError(
808
+ "UNSUPPORTED_IMPORT_TYPE",
809
+ `Git imports are not supported in browser. Use CLI 'bundle' command. URL: ${source.url}`
810
+ );
811
+ case "http":
812
+ throw new ResolutionError(
813
+ "UNSUPPORTED_IMPORT_TYPE",
814
+ `HTTP imports are not supported in browser. Use CLI 'bundle' command. URL: ${source.url}`
815
+ );
816
+ case "onchain":
817
+ return this.resolveOnchainImport(source, depth);
818
+ default:
819
+ throw new ResolutionError(
820
+ "UNSUPPORTED_IMPORT_TYPE",
821
+ `Unknown import type: ${source.type}`
822
+ );
823
+ }
824
+ }
825
+ async resolveOnchainImport(source, depth) {
826
+ const result = await this.onchainFetcher.fetch(
827
+ source.address,
828
+ source.target,
829
+ source.network,
830
+ source.revision
831
+ );
832
+ const resolved = await this.resolvePackage(result.abiYaml, true, depth);
833
+ resolved.source = source;
834
+ resolved.isRemote = true;
835
+ return resolved;
836
+ }
837
+ parseAbiYaml(yamlContent) {
838
+ try {
839
+ const parsed = yaml__namespace.parse(yamlContent);
840
+ if (!parsed || typeof parsed !== "object") {
841
+ throw new Error("Invalid ABI YAML: not an object");
842
+ }
843
+ if (!parsed.abi || typeof parsed.abi !== "object") {
844
+ throw new Error("Invalid ABI YAML: missing 'abi' section");
845
+ }
846
+ return parsed;
847
+ } catch (error) {
848
+ throw new ResolutionError(
849
+ "PARSE_ERROR",
850
+ `Failed to parse ABI YAML: ${error instanceof Error ? error.message : String(error)}`,
851
+ error
852
+ );
853
+ }
854
+ }
855
+ extractPackageId(abiFile) {
856
+ const metadata = abiFile.abi;
857
+ if (!metadata.package) {
858
+ throw new ResolutionError("PARSE_ERROR", "ABI missing 'package' field");
859
+ }
860
+ return {
861
+ packageName: metadata.package,
862
+ version: metadata["package-version"] ?? "0.0.0"
863
+ };
864
+ }
865
+ normalizeImportSource(source) {
866
+ switch (source.type) {
867
+ case "path":
868
+ return { type: "path", path: source.path };
869
+ case "git":
870
+ return {
871
+ type: "git",
872
+ url: source.url,
873
+ ref: source.ref,
874
+ path: source.path
875
+ };
876
+ case "http":
877
+ return { type: "http", url: source.url };
878
+ case "onchain": {
879
+ const revision = this.parseRevisionSpec(source.revision);
880
+ return {
881
+ type: "onchain",
882
+ address: source.address,
883
+ target: source.target ?? "program",
884
+ network: source.network,
885
+ revision
886
+ };
887
+ }
888
+ default:
889
+ throw new ResolutionError(
890
+ "UNSUPPORTED_IMPORT_TYPE",
891
+ `Unknown import type: ${source.type}`
892
+ );
893
+ }
894
+ }
895
+ parseRevisionSpec(revision) {
896
+ if (revision === void 0 || revision === "latest") {
897
+ return { type: "latest" };
898
+ }
899
+ if (typeof revision === "number") {
900
+ return { type: "exact", value: revision };
901
+ }
902
+ if (typeof revision === "string") {
903
+ if (revision.startsWith(">=")) {
904
+ const value2 = parseInt(revision.slice(2), 10);
905
+ if (isNaN(value2)) {
906
+ throw new Error(`Invalid minimum revision: ${revision}`);
907
+ }
908
+ return { type: "minimum", value: value2 };
909
+ }
910
+ const value = parseInt(revision, 10);
911
+ if (!isNaN(value)) {
912
+ return { type: "exact", value };
913
+ }
914
+ }
915
+ throw new Error(`Invalid revision specification: ${revision}`);
916
+ }
917
+ };
918
+
919
+ exports.ABI_ACCOUNT_HEADER_SIZE = ABI_ACCOUNT_HEADER_SIZE;
920
+ exports.ABI_STATE_FINALIZED = ABI_STATE_FINALIZED;
921
+ exports.ABI_STATE_OPEN = ABI_STATE_OPEN;
922
+ exports.DEFAULT_RPC_ENDPOINTS = DEFAULT_RPC_ENDPOINTS;
923
+ exports.OnchainFetcher = OnchainFetcher;
924
+ exports.ResolutionError = ResolutionError;
925
+ exports.buildLayoutIr = buildLayoutIr;
926
+ exports.buildLayoutIrWithManifest = buildLayoutIrWithManifest;
927
+ exports.configureWasm = configureWasm;
928
+ exports.createManifest = createManifest;
929
+ exports.deriveOfficialAbiAddress = deriveOfficialAbiAddress;
930
+ exports.ensureWasmLoaded = ensureWasmLoaded;
931
+ exports.formatReflection = formatReflection;
932
+ exports.getManifestPackages = getManifestPackages;
933
+ exports.parseAbiAccountData = parseAbiAccountData;
934
+ exports.reflect = reflect;
935
+ exports.reflectAccount = reflectAccount;
936
+ exports.reflectAccountWithManifest = reflectAccountWithManifest;
937
+ exports.reflectEvent = reflectEvent;
938
+ exports.reflectEventWithManifest = reflectEventWithManifest;
939
+ exports.reflectInstruction = reflectInstruction;
940
+ exports.reflectInstructionWithManifest = reflectInstructionWithManifest;
941
+ exports.reflectWithManifest = reflectWithManifest;
942
+ exports.resolveImports = resolveImports;
943
+ exports.revisionMatches = revisionMatches;
944
+ exports.validateManifest = validateManifest;
945
+ //# sourceMappingURL=index.cjs.map
946
+ //# sourceMappingURL=index.cjs.map