@zktx.io/sui-move-builder 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,499 +1,15 @@
1
- // src/tomlParser.ts
2
- function stripInlineComment(line) {
3
- let inQuote = false;
4
- let quoteChar = "";
5
- for (let i = 0; i < line.length; i++) {
6
- const ch = line[i];
7
- if ((ch === '"' || ch === "'") && (!inQuote || ch === quoteChar)) {
8
- inQuote = !inQuote;
9
- quoteChar = ch;
10
- }
11
- if (!inQuote && ch === "#") {
12
- return line.slice(0, i);
13
- }
14
- }
15
- return line;
16
- }
17
- function parseScalar(value) {
18
- const trimmed = value.trim();
19
- if (!trimmed) return "";
20
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
21
- return trimmed.slice(1, -1);
22
- }
23
- if (trimmed === "true") return true;
24
- if (trimmed === "false") return false;
25
- const num = Number(trimmed);
26
- if (!Number.isNaN(num)) return num;
27
- return trimmed;
28
- }
29
- function parseInlineTable(value) {
30
- const result = {};
31
- const inner = value.trim().replace(/^\{/, "").replace(/\}$/, "");
32
- let current = "";
33
- let inQuote = false;
34
- let quoteChar = "";
35
- const parts = [];
36
- for (let i = 0; i < inner.length; i++) {
37
- const ch = inner[i];
38
- if ((ch === '"' || ch === "'") && (!inQuote || ch === quoteChar)) {
39
- inQuote = !inQuote;
40
- quoteChar = ch;
41
- }
42
- if (!inQuote && ch === ",") {
43
- parts.push(current);
44
- current = "";
45
- continue;
46
- }
47
- current += ch;
48
- }
49
- if (current.trim()) {
50
- parts.push(current);
51
- }
52
- for (const part of parts) {
53
- const eq = part.indexOf("=");
54
- if (eq === -1) continue;
55
- const key = part.slice(0, eq).trim();
56
- const val = part.slice(eq + 1).trim();
57
- result[key] = parseScalar(val);
58
- }
59
- return result;
60
- }
61
- function parseToml(content) {
62
- const result = {
63
- package: {},
64
- dependencies: {},
65
- addresses: {}
66
- };
67
- let section = null;
68
- const lines = content.split(/\r?\n/);
69
- for (const rawLine of lines) {
70
- const line = stripInlineComment(rawLine).trim();
71
- if (!line) continue;
72
- const sectionMatch = line.match(/^\[([^\]]+)\]$/);
73
- if (sectionMatch) {
74
- section = sectionMatch[1].trim();
75
- continue;
76
- }
77
- const eq = line.indexOf("=");
78
- if (eq === -1 || !section) continue;
79
- const key = line.slice(0, eq).trim();
80
- const value = line.slice(eq + 1).trim();
81
- if (section === "package") {
82
- result.package[key.replace(/-/g, "_")] = parseScalar(value);
83
- } else if (section === "dependencies") {
84
- if (value.startsWith("{")) {
85
- result.dependencies[key] = parseInlineTable(value);
86
- } else {
87
- result.dependencies[key] = parseScalar(value);
88
- }
89
- } else if (section === "addresses") {
90
- result.addresses[key] = parseScalar(value);
91
- }
92
- }
93
- return result;
94
- }
95
-
96
- // src/resolver.ts
97
- var Resolver = class {
98
- constructor(fetcher) {
99
- this.fetcher = fetcher;
100
- this.globalAddresses = {};
101
- this.visited = /* @__PURE__ */ new Set();
102
- this.dependencyFiles = {};
103
- this.systemDepsLoaded = /* @__PURE__ */ new Set();
104
- }
105
- async resolve(rootMoveToml, rootFiles) {
106
- const parsedToml = parseToml(rootMoveToml);
107
- if (parsedToml.addresses) {
108
- this.mergeAddresses(parsedToml.addresses);
109
- }
110
- if (parsedToml.dependencies) {
111
- await this.resolveDeps(parsedToml.dependencies);
112
- await this.injectSystemDepsFromRoot(parsedToml.dependencies);
113
- }
114
- const finalMoveToml = this.reconstructMoveToml(parsedToml, this.globalAddresses);
115
- const finalFiles = { ...rootFiles, "Move.toml": finalMoveToml };
116
- return {
117
- files: JSON.stringify(finalFiles),
118
- dependencies: JSON.stringify(this.dependencyFiles)
119
- };
120
- }
121
- mergeAddresses(addresses) {
122
- for (const [name, val] of Object.entries(addresses)) {
123
- this.globalAddresses[name] = this.normalizeAddress(val);
124
- }
125
- }
126
- normalizeAddress(addr) {
127
- if (!addr) return addr;
128
- let clean = addr;
129
- if (clean.startsWith("0x")) clean = clean.slice(2);
130
- if (/^[0-9a-fA-F]+$/.test(clean)) {
131
- return "0x" + clean.padStart(64, "0");
132
- }
133
- return addr;
134
- }
135
- async resolveDeps(depsObj, parentContext = null) {
136
- for (const [name, depInfo] of Object.entries(depsObj)) {
137
- let gitUrl;
138
- let rev;
139
- let subdir;
140
- if (depInfo.git) {
141
- gitUrl = depInfo.git;
142
- rev = depInfo.rev;
143
- subdir = depInfo.subdir;
144
- } else if (depInfo.local) {
145
- if (!parentContext) continue;
146
- gitUrl = parentContext.git;
147
- rev = parentContext.rev;
148
- subdir = this.resolvePath(parentContext.subdir || "", depInfo.local);
149
- } else {
150
- continue;
151
- }
152
- const cacheKey = `${gitUrl}|${rev}|${subdir || ""}`;
153
- if (this.visited.has(cacheKey)) continue;
154
- this.visited.add(cacheKey);
155
- const files = await this.fetcher.fetch(gitUrl, rev, subdir);
156
- let pkgMoveToml = null;
157
- for (const [path, content] of Object.entries(files)) {
158
- if (path.endsWith("Move.toml")) {
159
- pkgMoveToml = content;
160
- break;
161
- }
162
- }
163
- if (pkgMoveToml) {
164
- const parsed = parseToml(pkgMoveToml);
165
- if (parsed.addresses) {
166
- this.mergeAddresses(parsed.addresses);
167
- }
168
- if (parsed.dependencies) {
169
- await this.resolveDeps(parsed.dependencies, { git: gitUrl, rev, subdir });
170
- }
171
- }
172
- for (const [path, content] of Object.entries(files)) {
173
- if (path.endsWith(".move") || path.endsWith("Move.toml")) {
174
- const targetPath = `dependencies/${name}/${path}`;
175
- this.dependencyFiles[targetPath] = content;
176
- }
177
- }
178
- }
179
- }
180
- resolvePath(base, relative) {
181
- const stack = base.split("/").filter((p) => p && p !== ".");
182
- const parts = relative.split("/").filter((p) => p && p !== ".");
183
- for (const part of parts) {
184
- if (part === "..") {
185
- stack.pop();
186
- } else {
187
- stack.push(part);
188
- }
189
- }
190
- return stack.join("/");
191
- }
192
- reconstructMoveToml(originalParsed, addresses) {
193
- let newToml = `[package]
194
- name = "${originalParsed.package.name}"
195
- version = "${originalParsed.package.version}"
196
- `;
197
- if (originalParsed.package.edition) {
198
- newToml += `edition = "${originalParsed.package.edition}"
199
- `;
200
- }
201
- newToml += `
1
+ var g=class{async fetch(e,t,s){throw new Error("Not implemented")}async fetchFile(e,t,s){throw new Error("Not implemented")}},m=class extends g{constructor(){super(),this.cache=new Map}async fetch(e,t,s){let{owner:i,repo:o}=this.parseGitUrl(e);if(!i||!o)throw new Error(`Invalid git URL: ${e}`);let c=`https://api.github.com/repos/${i}/${o}/git/trees/${t}?recursive=1`,l;try{let d=await fetch(c);if(!d.ok)throw d.status===403||d.status===429?new Error("GitHub API rate limit exceeded."):new Error(`Failed to fetch tree: ${d.statusText}`);l=await d.json()}catch{return{}}let r={},a=[];for(let d of l.tree){if(d.type!=="blob")continue;let u=d.path;if(s){if(!d.path.startsWith(s))continue;u=d.path.slice(s.length),u.startsWith("/")&&(u=u.slice(1))}if(!u.endsWith(".move")&&u!=="Move.toml")continue;let f=`https://raw.githubusercontent.com/${i}/${o}/${t}/${d.path}`,b=this.fetchContent(f).then($=>{$&&(r[u]=$)});a.push(b)}return await Promise.all(a),r}async fetchFile(e,t,s){let{owner:i,repo:o}=this.parseGitUrl(e);if(!i||!o)throw new Error(`Invalid git URL: ${e}`);let c=`https://raw.githubusercontent.com/${i}/${o}/${t}/${s}`;return this.fetchContent(c)}async fetchContent(e){if(this.cache.has(e))return this.cache.get(e)??null;try{let t=await fetch(e);if(!t.ok)return null;let s=await t.text();return this.cache.set(e,s),s}catch{return null}}parseGitUrl(e){try{let s=new URL(e).pathname.split("/").filter(i=>i);if(s.length>=2){let i=s[1];return i.endsWith(".git")&&(i=i.slice(0,-4)),{owner:s[0],repo:i}}}catch{}return{owner:null,repo:null}}};function D(n){let e=!1,t="";for(let s=0;s<n.length;s++){let i=n[s];if((i==='"'||i==="'")&&(!e||i===t)&&(e=!e,t=i),!e&&i==="#")return n.slice(0,s)}return n}function h(n){let e=n.trim();if(!e)return"";if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e==="true")return!0;if(e==="false")return!1;let t=Number(e);return Number.isNaN(t)?e:t}function P(n){let e={},t=n.trim().replace(/^\{/,"").replace(/\}$/,""),s="",i=!1,o="",c=[];for(let l=0;l<t.length;l++){let r=t[l];if((r==='"'||r==="'")&&(!i||r===o)&&(i=!i,o=r),!i&&r===","){c.push(s),s="";continue}s+=r}s.trim()&&c.push(s);for(let l of c){let r=l.indexOf("=");if(r===-1)continue;let a=l.slice(0,r).trim(),d=l.slice(r+1).trim();e[a]=h(d)}return e}function y(n){let e={package:{},dependencies:{},addresses:{}},t=null,s=n.split(/\r?\n/);for(let i of s){let o=D(i).trim();if(!o)continue;let c=o.match(/^\[([^\]]+)\]$/);if(c){t=c[1].trim();continue}let l=o.indexOf("=");if(l===-1||!t)continue;let r=o.slice(0,l).trim(),a=o.slice(l+1).trim();t==="package"?e.package[r.replace(/-/g,"_")]=h(a):t==="dependencies"?a.startsWith("{")?e.dependencies[r]=P(a):e.dependencies[r]=h(a):t==="addresses"&&(e.addresses[r]=h(a))}return e}var v=class{constructor(e){this.fetcher=e,this.globalAddresses={},this.visited=new Set,this.dependencyFiles={},this.systemDepsLoaded=new Set}async resolve(e,t){let s=y(e);s.addresses&&this.mergeAddresses(s.addresses),s.dependencies&&await this.resolveDeps(s.dependencies),await this.injectSystemDeps(s.dependencies);let i=this.reconstructMoveToml(s,this.globalAddresses),o={...t,"Move.toml":i};return{files:JSON.stringify(o),dependencies:JSON.stringify(this.dependencyFiles)}}mergeAddresses(e){for(let[t,s]of Object.entries(e))this.globalAddresses[t]=this.normalizeAddress(s)}normalizeAddress(e){if(!e)return e;let t=e;return t.startsWith("0x")&&(t=t.slice(2)),/^[0-9a-fA-F]+$/.test(t)?"0x"+t.padStart(64,"0"):e}async resolveDeps(e,t=null){for(let[s,i]of Object.entries(e)){let o,c,l;if(i.git)o=i.git,c=i.rev,l=i.subdir;else if(i.local){if(!t)continue;o=t.git,c=t.rev,l=this.resolvePath(t.subdir||"",i.local)}else continue;let r=`${o}|${c}|${l||""}`;if(this.visited.has(r))continue;this.visited.add(r);let a=await this.fetcher.fetch(o,c,l),d=null;for(let[u,f]of Object.entries(a))if(u.endsWith("Move.toml")){d=f;break}if(d){let u=y(d);u.addresses&&this.mergeAddresses(u.addresses),u.dependencies&&await this.resolveDeps(u.dependencies,{git:o,rev:c,subdir:l})}for(let[u,f]of Object.entries(a))if(u.endsWith(".move")||u.endsWith("Move.toml")){let b=`dependencies/${s}/${u}`;this.dependencyFiles[b]=f}}}resolvePath(e,t){let s=e.split("/").filter(o=>o&&o!=="."),i=t.split("/").filter(o=>o&&o!==".");for(let o of i)o===".."?s.pop():s.push(o);return s.join("/")}reconstructMoveToml(e,t){let s=`[package]
2
+ name = "${e.package.name}"
3
+ version = "${e.package.version}"
4
+ `;if(e.package.edition&&(s+=`edition = "${e.package.edition}"
5
+ `),s+=`
202
6
  [dependencies]
203
- `;
204
- if (originalParsed.dependencies) {
205
- for (const [name, info] of Object.entries(originalParsed.dependencies)) {
206
- newToml += `${name} = { git = "${info.git}", rev = "${info.rev}" }
207
- `;
208
- }
209
- }
210
- newToml += `
7
+ `,e.dependencies)for(let[i,o]of Object.entries(e.dependencies))s+=`${i} = { git = "${o.git}", rev = "${o.rev}" }
8
+ `;s+=`
211
9
  [addresses]
212
- `;
213
- for (const [addrName, addrVal] of Object.entries(addresses)) {
214
- newToml += `${addrName} = "${addrVal}"
215
- `;
216
- }
217
- return newToml;
218
- }
219
- async injectSystemDepsFromRoot(depsObj) {
220
- for (const depInfo of Object.values(depsObj)) {
221
- if (!depInfo || !depInfo.git || !depInfo.rev) continue;
222
- if (!this.isSuiRepo(depInfo.git)) continue;
223
- await this.addImplicitSystemDepsForRepo(depInfo.git, depInfo.rev);
224
- return;
225
- }
226
- }
227
- async addImplicitSystemDepsForRepo(gitUrl, rev) {
228
- if (!this.isSuiRepo(gitUrl)) return;
229
- const cacheKey = `${gitUrl}|${rev}`;
230
- if (this.systemDepsLoaded.has(cacheKey)) return;
231
- this.systemDepsLoaded.add(cacheKey);
232
- const manifestPath = "crates/sui-framework-snapshot/manifest.json";
233
- if (!this.fetcher.fetchFile) return;
234
- let packages = null;
235
- try {
236
- const manifestText = await this.fetcher.fetchFile(gitUrl, rev, manifestPath);
237
- if (manifestText) {
238
- const manifest = JSON.parse(manifestText);
239
- const versions = Object.keys(manifest).map((v) => Number(v)).filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
240
- const latestVersion = versions[versions.length - 1];
241
- const latest = manifest[String(latestVersion)];
242
- if (latest && latest.packages) {
243
- packages = latest.packages;
244
- }
245
- }
246
- } catch (e) {
247
- }
248
- if (!packages) {
249
- packages = [
250
- { name: "MoveStdlib", id: "0x1" },
251
- { name: "Sui", id: "0x2" },
252
- { name: "SuiSystem", id: "0x3" },
253
- { name: "Bridge", id: "0xb" }
254
- ];
255
- }
256
- for (const pkg of packages) {
257
- if (!pkg || !pkg.name || !pkg.id) continue;
258
- if (pkg.name === "DeepBook") continue;
259
- const targetPath = `dependencies/${pkg.name}/Move.toml`;
260
- if (this.dependencyFiles[targetPath]) continue;
261
- const moveToml = [
262
- "[package]",
263
- `name = "${pkg.name}"`,
264
- 'version = "0.0.0"',
265
- `published-at = "${pkg.id}"`,
266
- ""
267
- ].join("\n");
268
- this.dependencyFiles[targetPath] = moveToml;
269
- }
270
- }
271
- isSuiRepo(gitUrl) {
272
- return gitUrl.includes("github.com/MystenLabs/sui");
273
- }
274
- };
275
- async function resolve(rootMoveTomlContent, rootSourceFiles, fetcher) {
276
- const resolver = new Resolver(fetcher);
277
- return resolver.resolve(rootMoveTomlContent, rootSourceFiles);
278
- }
279
-
280
- // src/fetcher.ts
281
- var Fetcher = class {
282
- /** Fetch a package. Return map of path -> content. */
283
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
284
- async fetch(_gitUrl, _rev, _subdir) {
285
- throw new Error("Not implemented");
286
- }
287
- /** Fetch a single file from a repository. */
288
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
289
- async fetchFile(_gitUrl, _rev, _path) {
290
- throw new Error("Not implemented");
291
- }
292
- };
293
- var GitHubFetcher = class extends Fetcher {
294
- constructor() {
295
- super();
296
- this.cache = /* @__PURE__ */ new Map();
297
- }
298
- async fetch(gitUrl, rev, subdir) {
299
- const { owner, repo } = this.parseGitUrl(gitUrl);
300
- if (!owner || !repo) {
301
- throw new Error(`Invalid git URL: ${gitUrl}`);
302
- }
303
- const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${rev}?recursive=1`;
304
- let treeData;
305
- try {
306
- const resp = await fetch(treeUrl);
307
- if (!resp.ok) {
308
- if (resp.status === 403 || resp.status === 429) {
309
- throw new Error("GitHub API rate limit exceeded.");
310
- }
311
- throw new Error(`Failed to fetch tree: ${resp.statusText}`);
312
- }
313
- treeData = await resp.json();
314
- } catch (e) {
315
- return {};
316
- }
317
- const files = {};
318
- const fetchPromises = [];
319
- for (const item of treeData.tree) {
320
- if (item.type !== "blob") continue;
321
- let relativePath = item.path;
322
- if (subdir) {
323
- if (!item.path.startsWith(subdir)) continue;
324
- relativePath = item.path.slice(subdir.length);
325
- if (relativePath.startsWith("/")) {
326
- relativePath = relativePath.slice(1);
327
- }
328
- }
329
- if (!relativePath.endsWith(".move") && relativePath !== "Move.toml") {
330
- continue;
331
- }
332
- const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${rev}/${item.path}`;
333
- const p = this.fetchContent(rawUrl).then((content) => {
334
- if (content) {
335
- files[relativePath] = content;
336
- }
337
- });
338
- fetchPromises.push(p);
339
- }
340
- await Promise.all(fetchPromises);
341
- return files;
342
- }
343
- async fetchFile(gitUrl, rev, path) {
344
- const { owner, repo } = this.parseGitUrl(gitUrl);
345
- if (!owner || !repo) {
346
- throw new Error(`Invalid git URL: ${gitUrl}`);
347
- }
348
- const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${rev}/${path}`;
349
- return this.fetchContent(rawUrl);
350
- }
351
- async fetchContent(url) {
352
- if (this.cache.has(url)) {
353
- return this.cache.get(url) ?? null;
354
- }
355
- try {
356
- const resp = await fetch(url);
357
- if (!resp.ok) return null;
358
- const text = await resp.text();
359
- this.cache.set(url, text);
360
- return text;
361
- } catch (e) {
362
- return null;
363
- }
364
- }
365
- parseGitUrl(url) {
366
- try {
367
- const urlObj = new URL(url);
368
- const parts = urlObj.pathname.split("/").filter((p) => p);
369
- if (parts.length >= 2) {
370
- let repo = parts[1];
371
- if (repo.endsWith(".git")) {
372
- repo = repo.slice(0, -4);
373
- }
374
- return { owner: parts[0], repo };
375
- }
376
- } catch (e) {
377
- }
378
- return { owner: null, repo: null };
379
- }
380
- };
381
-
382
- // src/index.ts
383
- var wasmUrl = (() => {
384
- try {
385
- return new URL("./sui_move_wasm_bg.wasm", import.meta.url);
386
- } catch {
387
- return "./sui_move_wasm_bg.wasm";
388
- }
389
- })();
390
- var wasmReady;
391
- async function loadWasm(customWasm) {
392
- if (!wasmReady) {
393
- wasmReady = import("./sui_move_wasm.js").then(async (mod) => {
394
- await mod.default(customWasm ?? wasmUrl);
395
- return mod;
396
- });
397
- }
398
- return wasmReady;
399
- }
400
- function toJson(value) {
401
- return JSON.stringify(value ?? {});
402
- }
403
- function asFailure(err) {
404
- const msg = err instanceof Error ? err.message : typeof err === "string" ? err : "Unknown error";
405
- return { success: false, error: msg };
406
- }
407
- function ensureCompileResult(result) {
408
- if (typeof result !== "object" || result === null) {
409
- throw new Error("Unexpected compile result shape from wasm");
410
- }
411
- const asAny = result;
412
- if (typeof asAny.success === "function" && typeof asAny.output === "function") {
413
- return asAny;
414
- }
415
- if (typeof asAny.success === "boolean" && typeof asAny.output === "string") {
416
- return {
417
- success: () => asAny.success,
418
- output: () => asAny.output
419
- };
420
- }
421
- throw new Error("Unexpected compile result shape from wasm");
422
- }
423
- function parseCompileResult(output) {
424
- const toHex = (bytes) => bytes.map((b) => b.toString(16).padStart(2, "0")).join("");
425
- try {
426
- const parsed = JSON.parse(output);
427
- if (!parsed.modules || !parsed.dependencies || !parsed.digest) {
428
- throw new Error("missing fields in compiler output");
429
- }
430
- const digestHex = typeof parsed.digest === "string" ? parsed.digest : toHex(parsed.digest);
431
- return {
432
- success: true,
433
- modules: parsed.modules,
434
- dependencies: parsed.dependencies,
435
- digest: digestHex
436
- };
437
- } catch (error) {
438
- return asFailure(error);
439
- }
440
- }
441
- async function initMoveCompiler(options) {
442
- await loadWasm(options?.wasm);
443
- }
444
- async function buildMovePackage(input) {
445
- try {
446
- const mod = await loadWasm(input.wasm);
447
- const raw = input.ansiColor && typeof mod.compile_with_color === "function" ? mod.compile_with_color(
448
- toJson(input.files),
449
- toJson(input.dependencies ?? {}),
450
- true
451
- ) : mod.compile(
452
- toJson(input.files),
453
- toJson(input.dependencies ?? {})
454
- );
455
- const result = ensureCompileResult(raw);
456
- const ok = result.success();
457
- const output = result.output();
458
- if (!ok) {
459
- return asFailure(output);
460
- }
461
- return parseCompileResult(output);
462
- } catch (error) {
463
- return asFailure(error);
464
- }
465
- }
466
- async function getSuiMoveVersion(options) {
467
- const mod = await loadWasm(options?.wasm);
468
- return mod.sui_move_version();
469
- }
470
- async function getSuiVersion(options) {
471
- const mod = await loadWasm(options?.wasm);
472
- return mod.sui_version();
473
- }
474
- async function getWasmBindings(options) {
475
- return loadWasm(options?.wasm);
476
- }
477
- async function compileRaw(filesJson, depsJson, options) {
478
- const mod = await loadWasm(options?.wasm);
479
- const raw = options?.ansiColor && typeof mod.compile_with_color === "function" ? mod.compile_with_color(filesJson, depsJson, true) : mod.compile(filesJson, depsJson);
480
- const result = ensureCompileResult(raw);
481
- return {
482
- success: result.success(),
483
- output: result.output()
484
- };
485
- }
486
- export {
487
- Fetcher,
488
- GitHubFetcher,
489
- Resolver,
490
- buildMovePackage,
491
- compileRaw,
492
- getSuiMoveVersion,
493
- getSuiVersion,
494
- getWasmBindings,
495
- initMoveCompiler,
496
- parseToml,
497
- resolve
498
- };
499
- //# sourceMappingURL=index.js.map
10
+ `;for(let[i,o]of Object.entries(t))s+=`${i} = "${o}"
11
+ `;return s}async injectSystemDeps(e){if(e){for(let s of Object.values(e))if(!(!s||!s.git||!s.rev)&&this.isSuiRepo(s.git)){await this.addImplicitSystemDepsForRepo(s.git,s.rev);break}}this.dependencyFiles["dependencies/MoveStdlib/Move.toml"]||this.addFallbackSystemDeps()}async addImplicitSystemDepsForRepo(e,t){if(!this.isSuiRepo(e))return;let s=`${e}|${t}`;if(this.systemDepsLoaded.has(s))return;this.systemDepsLoaded.add(s);let i="crates/sui-framework-snapshot/manifest.json";if(!this.fetcher.fetchFile)return;let o=null;try{let c=await this.fetcher.fetchFile(e,t,i);if(c){let l=JSON.parse(c),r=Object.keys(l).map(u=>Number(u)).filter(u=>!Number.isNaN(u)).sort((u,f)=>u-f),a=r[r.length-1],d=l[String(a)];d&&d.packages&&(o=d.packages)}}catch{}o||(o=this.fallbackSystemPackages());for(let c of o)!c||!c.name||!c.id||c.name!=="DeepBook"&&this.addSystemDep(c.name,c.id)}addFallbackSystemDeps(){for(let e of this.fallbackSystemPackages())!e||!e.name||!e.id||e.name!=="DeepBook"&&this.addSystemDep(e.name,e.id)}addSystemDep(e,t){let s=`dependencies/${e}/Move.toml`;if(this.dependencyFiles[s])return;let i=["[package]",`name = "${e}"`,'version = "0.0.0"',`published-at = "${this.normalizeAddress(t)}"`,""].join(`
12
+ `);this.dependencyFiles[s]=i}fallbackSystemPackages(){return[{name:"MoveStdlib",id:"0x1"},{name:"Sui",id:"0x2"},{name:"SuiSystem",id:"0x3"},{name:"Bridge",id:"0xb"}]}isSuiRepo(e){return e.includes("github.com/MystenLabs/sui")}};async function S(n,e,t){return new v(t).resolve(n,e)}var j=(()=>{try{return new URL("./sui_move_wasm_bg.wasm",import.meta.url)}catch{return"./sui_move_wasm_bg.wasm"}})(),k;async function p(n){return k||(k=import("./sui_move_wasm.js").then(async e=>(await e.default(n??j),e))),k}function w(n){return JSON.stringify(n??{})}function R(n){return{success:!1,error:n instanceof Error?n.message:typeof n=="string"?n:"Unknown error"}}function F(n){if(typeof n!="object"||n===null)throw new Error("Unexpected compile result shape from wasm");let e=n;if(typeof e.success=="function"&&typeof e.output=="function")return e;if(typeof e.success=="boolean"&&typeof e.output=="string")return{success:()=>e.success,output:()=>e.output};throw new Error("Unexpected compile result shape from wasm")}function W(n){let e=t=>t.map(s=>s.toString(16).padStart(2,"0")).join("");try{let t=JSON.parse(n);if(!t.modules||!t.dependencies||!t.digest)throw new Error("missing fields in compiler output");let s=typeof t.digest=="string"?t.digest:e(t.digest);return{success:!0,modules:t.modules,dependencies:t.dependencies,digest:s}}catch(t){return R(t)}}function _(n){if(!n)return n;let e=n;return e.startsWith("0x")&&(e=e.slice(2)),/^[0-9a-fA-F]+$/.test(e)?"0x"+e.padStart(64,"0"):n}function L(n){let e={std:"0x1",sui:"0x2",sui_system:"0x3",bridge:"0xb"},t=n.split(/\r?\n/),s=/^\s*\[[^\]]+\]\s*$/,i=-1,o=t.length;for(let r=0;r<t.length;r++)if(/^\s*\[addresses\]\s*$/.test(t[r])){i=r;for(let a=r+1;a<t.length;a++)if(s.test(t[a])){o=a;break}break}let c=new Set;if(i>=0)for(let r=i+1;r<o;r++){let a=t[r].trim();if(!a||a.startsWith("#"))continue;let d=a.match(/^([A-Za-z0-9_.-]+)\s*=/);d&&c.add(d[1])}let l=Object.entries(e).filter(([r])=>!c.has(r)).map(([r,a])=>`${r} = "${_(a)}"`);return l.length===0?n:(i>=0?t.splice(o,0,...l):t.push("","[addresses]",...l),t.join(`
13
+ `))}function U(n){let e=[{name:"Sui",git:"https://github.com/MystenLabs/sui.git",subdir:"crates/sui-framework/packages/sui-framework",rev:"framework/mainnet"},{name:"MoveStdlib",git:"https://github.com/MystenLabs/sui.git",subdir:"crates/sui-framework/packages/move-stdlib",rev:"framework/mainnet"}],t=n.split(/\r?\n/),s=/^\s*\[[^\]]+\]\s*$/,i=-1,o=t.length;for(let r=0;r<t.length;r++)if(/^\s*\[dependencies\]\s*$/.test(t[r])){i=r;for(let a=r+1;a<t.length;a++)if(s.test(t[a])){o=a;break}break}let c=new Set;if(i>=0)for(let r=i+1;r<o;r++){let a=t[r].trim();if(!a||a.startsWith("#"))continue;let d=a.match(/^([A-Za-z0-9_.-]+)\s*=/);d&&c.add(d[1])}let l=e.filter(r=>!c.has(r.name)).map(r=>`${r.name} = { git = "${r.git}", subdir = "${r.subdir}", rev = "${r.rev}" }`);return l.length===0?n:(i>=0?t.splice(o,0,...l):t.push("","[dependencies]",...l),t.join(`
14
+ `))}function B(n){let e={...n??{}};if(e["dependencies/MoveStdlib/Move.toml"])return e;let t=[{name:"MoveStdlib",id:"0x1"},{name:"Sui",id:"0x2"},{name:"SuiSystem",id:"0x3"},{name:"Bridge",id:"0xb"}];for(let s of t){let i=`dependencies/${s.name}/Move.toml`;e[i]||(e[i]=["[package]",`name = "${s.name}"`,'version = "0.0.0"',`published-at = "${_(s.id)}"`,""].join(`
15
+ `))}return e}function x(n){return!!(n?.["dependencies/MoveStdlib/Move.toml"]&&n?.["dependencies/Sui/Move.toml"])}function M(n){return typeof n=="string"?JSON.parse(n):n}async function C(n){await p(n?.wasm)}async function z(n){try{let e=n.dependencies??{},t={...n.files},s=typeof t["Move.toml"]=="string";if(n.autoSystemDeps&&s){let a=L(t["Move.toml"]);x(e)||(a=U(a)),t["Move.toml"]=a}if(n.autoSystemDeps&&!x(e)&&s){let a=await S(t["Move.toml"],t,new m);t=M(a.files),e=M(a.dependencies)}else n.autoSystemDeps&&(e=B(e));let i=await p(n.wasm),o=n.ansiColor&&typeof i.compile_with_color=="function"?i.compile_with_color(w(t),w(e),!0):i.compile(w(t),w(e)),c=F(o),l=c.success(),r=c.output();return l?W(r):R(r)}catch(e){return R(e)}}async function H(n){return(await p(n?.wasm)).sui_move_version()}async function G(n){return(await p(n?.wasm)).sui_version()}async function J(n){return p(n?.wasm)}async function q(n,e,t){let s=await p(t?.wasm),i=t?.ansiColor&&typeof s.compile_with_color=="function"?s.compile_with_color(n,e,!0):s.compile(n,e),o=F(i);return{success:o.success(),output:o.output()}}export{g as Fetcher,m as GitHubFetcher,v as Resolver,z as buildMovePackage,q as compileRaw,H as getSuiMoveVersion,G as getSuiVersion,J as getWasmBindings,C as initMoveCompiler,y as parseToml,S as resolve};
@@ -23,16 +23,15 @@ export interface InitOutput {
23
23
  readonly memory: WebAssembly.Memory;
24
24
  readonly __wbg_movecompilerresult_free: (a: number, b: number) => void;
25
25
  readonly movecompilerresult_success: (a: number) => number;
26
- readonly movecompilerresult_output: (a: number) => [number, number];
27
- readonly sui_move_version: () => [number, number];
26
+ readonly movecompilerresult_output: (a: number, b: number) => void;
27
+ readonly sui_move_version: (a: number) => void;
28
28
  readonly compile: (a: number, b: number, c: number, d: number) => number;
29
29
  readonly compile_with_color: (a: number, b: number, c: number, d: number, e: number) => number;
30
- readonly sui_version: () => [number, number];
31
- readonly __wbindgen_free: (a: number, b: number, c: number) => void;
32
- readonly __wbindgen_malloc: (a: number, b: number) => number;
33
- readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
34
- readonly __wbindgen_externrefs: WebAssembly.Table;
35
- readonly __wbindgen_start: () => void;
30
+ readonly sui_version: (a: number) => void;
31
+ readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
32
+ readonly __wbindgen_export: (a: number, b: number, c: number) => void;
33
+ readonly __wbindgen_export2: (a: number, b: number) => number;
34
+ readonly __wbindgen_export3: (a: number, b: number, c: number, d: number) => number;
36
35
  }
37
36
 
38
37
  export type SyncInitInput = BufferSource | WebAssembly.Module;