@seedprotocol/publish 0.6.8 → 0.6.9

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 (51) hide show
  1. package/README.md +0 -18
  2. package/dist/chainConfig-CA1Hrrjg.js +1387 -0
  3. package/dist/chainConfig-CA1Hrrjg.js.map +1 -0
  4. package/dist/chainConfig-CYy0XJ0M.js +1283 -0
  5. package/dist/chainConfig-CYy0XJ0M.js.map +1 -0
  6. package/dist/config.d.ts +0 -7
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/ensureAutomationSessionKey-Bw74ZSGI.js +85 -0
  9. package/dist/ensureAutomationSessionKey-Bw74ZSGI.js.map +1 -0
  10. package/dist/ensureAutomationSessionKey-CeUbjcCl.js +85 -0
  11. package/dist/ensureAutomationSessionKey-CeUbjcCl.js.map +1 -0
  12. package/dist/ensureModularPublishBootstrap-BhYNmLzT.js +24 -0
  13. package/dist/ensureModularPublishBootstrap-BhYNmLzT.js.map +1 -0
  14. package/dist/ensureModularPublishBootstrap-Bsw1xSCt.js +24 -0
  15. package/dist/ensureModularPublishBootstrap-Bsw1xSCt.js.map +1 -0
  16. package/dist/ensureSmartWalletThenPublish-Bm58tc-b.js +48 -0
  17. package/dist/ensureSmartWalletThenPublish-Bm58tc-b.js.map +1 -0
  18. package/dist/ensureSmartWalletThenPublish-Dta2AOyJ.js +48 -0
  19. package/dist/ensureSmartWalletThenPublish-Dta2AOyJ.js.map +1 -0
  20. package/dist/helpers/abi/executor.d.ts +4 -7
  21. package/dist/helpers/abi/executor.d.ts.map +1 -1
  22. package/dist/helpers/abi/publisher.d.ts +7 -74
  23. package/dist/helpers/abi/publisher.d.ts.map +1 -1
  24. package/dist/helpers/contracts/index.d.ts +6 -18
  25. package/dist/helpers/contracts/index.d.ts.map +1 -1
  26. package/dist/index.d.ts +1 -2
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +352 -377
  29. package/dist/index.js.map +1 -1
  30. package/dist/managedAccountAdmin-DJMw6UH6.js +29 -0
  31. package/dist/managedAccountAdmin-DJMw6UH6.js.map +1 -0
  32. package/dist/managedAccountAdmin-NXD66lP5.js +29 -0
  33. package/dist/managedAccountAdmin-NXD66lP5.js.map +1 -0
  34. package/dist/publishAuthorization-BEqRnP2h.js +3925 -0
  35. package/dist/publishAuthorization-BEqRnP2h.js.map +1 -0
  36. package/dist/publishAuthorization-DjVrnMC0.js +3925 -0
  37. package/dist/publishAuthorization-DjVrnMC0.js.map +1 -0
  38. package/dist/publishThirdwebClient-CBD9sKJR.js +18 -0
  39. package/dist/publishThirdwebClient-CBD9sKJR.js.map +1 -0
  40. package/dist/publishThirdwebClient-Ce7iBIsj.js +18 -0
  41. package/dist/publishThirdwebClient-Ce7iBIsj.js.map +1 -0
  42. package/dist/resolveRevokeAccount-DJKfLlyK.js +38 -0
  43. package/dist/resolveRevokeAccount-DJKfLlyK.js.map +1 -0
  44. package/dist/resolveRevokeAccount-mzR11KJ4.js +38 -0
  45. package/dist/resolveRevokeAccount-mzR11KJ4.js.map +1 -0
  46. package/dist/thirdweb.js +56 -56
  47. package/dist/worker-CbtzcKG6.js +69 -0
  48. package/dist/worker-CbtzcKG6.js.map +1 -0
  49. package/dist/worker-DHUm-TeQ.js +69 -0
  50. package/dist/worker-DHUm-TeQ.js.map +1 -0
  51. package/package.json +6 -6
@@ -0,0 +1,3925 @@
1
+ import { t as e } from "./rolldown-runtime-Dy4uBu1J.js";
2
+ import { B as t, D as n, E as r, F as i, G as a, I as o, J as s, K as c, L as l, M as u, N as d, P as f, R as p, T as m, U as h, W as g, X as _, Y as v, Z as y, _ as b, _t as x, a as S, at as ee, c as te, ct as C, dt as ne, et as re, f as ie, h as ae, ht as oe, it as se, k as ce, lt as le, mt as ue, nt as de, o as w, ot as fe, pt as pe, q as me, r as he, rt as ge, st as T, t as E, tt as _e, u as ve, ut as ye, v as be, vt as xe, z as Se } from "./chainConfig-CA1Hrrjg.js";
3
+ import { a as Ce, o as we, r as D, s as Te, t as Ee } from "./errors-Du3LNbJN.js";
4
+ import { t as O } from "./publishThirdwebClient-CBD9sKJR.js";
5
+ import { BaseArweaveClient as De, BaseDb as k, BaseFileManager as A, INTERNAL_DATA_TYPES as Oe, Item as j, ModelPropertyDataTypes as ke, applyPropertyAttestationUidsFromPublish as Ae, arweaveL1FinalizeJobs as je, assertLocalDbChain as Me, getCorrectId as Ne, getEasSchemaForItemProperty as Pe, getItemPropertiesFromEas as Fe, getRelatedItemsForPublish as Ie, getSegmentedItemProperties as Le, getUploadPipelineTransactionStatus as Re, htmlEmbeddedImageCoPublish as ze, isItemOwned as Be, isPublishedSeedRef as Ve, itemHasPublishUploadCandidates as He, listRelationEasPropertyName as Ue, normalizeDataType as We, normalizeRelationPropertyValue as Ge, prepareHtmlEmbeddedImagesForPublish as Ke, publishProcesses as M, resolvePublishPayloadValues as qe, resolveSeedIdsFromRefString as Je, rewriteHtmlEmbeddedImagesOnDisk as Ye, setSchemaUidForModel as Xe, setSchemaUidForSchemaDefinition as Ze, updateVersionUid as Qe, validateItemForPublish as $e } from "@seedprotocol/sdk";
6
+ import { BaseError as et, decodeAbiParameters as tt, decodeErrorResult as nt, encodeAbiParameters as rt, parseEther as it, parseEventLogs as at, toFunctionSelector as ot, zeroAddress as st } from "viem";
7
+ import { deploySmartAccount as ct, getContract as lt, sendTransaction as ut } from "thirdweb";
8
+ import { ethers as N, keccak256 as dt, toUtf8Bytes as ft } from "ethers";
9
+ import { PUBLISH_AUTHORIZATION_DEFAULT_EXPIRATION_SECS as pt, PUBLISH_AUTHORIZATION_SCHEMA_DEF as mt, PUBLISH_AUTHORIZATION_SCHEMA_DEF as ht, PUBLISH_AUTHORIZATION_SCHEMA_NAME as gt, PUBLISH_AUTHORIZATION_SCHEMA_NAME as _t, PUBLISH_AUTHORIZATION_SCOPES as vt, PUBLISH_AUTHORIZATION_SCOPES as yt, assessPublishAuthorization as bt, decodePublishAuthorizationData as xt, getPublishAuthorizationFromEas as St, isValidEasAttestationUid as Ct, normalizeBytes32Hex as wt } from "@seedprotocol/eas";
10
+ import { createContext as Tt, useContext as Et, useEffect as Dt, useRef as Ot, useState as kt } from "react";
11
+ import At from "arweave";
12
+ import { NO_EXPIRATION as jt, SchemaEncoder as Mt, SchemaRegistry as Nt, ZERO_ADDRESS as Pt, ZERO_BYTES32 as Ft } from "@ethereum-attestation-service/eas-sdk";
13
+ import { assign as P, createActor as It, enqueueActions as Lt, fromCallback as F, fromPromise as I, setup as Rt } from "xstate";
14
+ import L from "debug";
15
+ import { and as zt, desc as Bt, eq as R } from "drizzle-orm";
16
+ import { createWallet as Vt, inAppWallet as Ht } from "thirdweb/wallets";
17
+ import { useActiveAccount as Ut } from "thirdweb/react";
18
+ import { getInstalledModules as Wt, installModule as Gt } from "thirdweb/modules";
19
+ //#region src/react/PublishConfigContext.tsx
20
+ var Kt = Tt(null);
21
+ function qt() {
22
+ let e = Et(Kt);
23
+ if (!e) throw Error("usePublishConfig: PublishConfig is missing. Pass config to PublishProvider or call initPublish() before render.");
24
+ return e;
25
+ }
26
+ //#endregion
27
+ //#region src/helpers/describeRevert.ts
28
+ var Jt = [
29
+ {
30
+ type: "error",
31
+ name: "PublishIndexOutOfBounds",
32
+ inputs: [{
33
+ name: "targetIndex",
34
+ type: "uint256"
35
+ }, {
36
+ name: "length",
37
+ type: "uint256"
38
+ }]
39
+ },
40
+ {
41
+ type: "error",
42
+ name: "UnknownPublishLocalId",
43
+ inputs: [{
44
+ name: "publishLocalId",
45
+ type: "string"
46
+ }]
47
+ },
48
+ {
49
+ type: "error",
50
+ name: "PublishTargetAlreadyAttested",
51
+ inputs: [{
52
+ name: "requestIndex",
53
+ type: "uint256"
54
+ }, {
55
+ name: "targetIndex",
56
+ type: "uint256"
57
+ }]
58
+ },
59
+ {
60
+ type: "error",
61
+ name: "EmptyAttestationData",
62
+ inputs: [{
63
+ name: "targetIndex",
64
+ type: "uint256"
65
+ }, {
66
+ name: "propertySchemaUid",
67
+ type: "bytes32"
68
+ }]
69
+ },
70
+ {
71
+ type: "error",
72
+ name: "PropertyToUpdateNotFound",
73
+ inputs: [
74
+ {
75
+ name: "requestIndex",
76
+ type: "uint256"
77
+ },
78
+ {
79
+ name: "targetIndex",
80
+ type: "uint256"
81
+ },
82
+ {
83
+ name: "propertySchemaUid",
84
+ type: "bytes32"
85
+ }
86
+ ]
87
+ },
88
+ {
89
+ type: "error",
90
+ name: "AmbiguousPropertyToUpdate",
91
+ inputs: [{
92
+ name: "targetIndex",
93
+ type: "uint256"
94
+ }, {
95
+ name: "propertySchemaUid",
96
+ type: "bytes32"
97
+ }]
98
+ },
99
+ {
100
+ type: "error",
101
+ name: "InvalidEAS",
102
+ inputs: [{
103
+ name: "eas",
104
+ type: "address"
105
+ }]
106
+ },
107
+ {
108
+ type: "error",
109
+ name: "AttestationFailed",
110
+ inputs: [{
111
+ name: "schemaUid",
112
+ type: "bytes32"
113
+ }]
114
+ },
115
+ {
116
+ type: "error",
117
+ name: "Unauthorized",
118
+ inputs: [{
119
+ name: "caller",
120
+ type: "address"
121
+ }]
122
+ },
123
+ {
124
+ type: "error",
125
+ name: "InvalidAddress",
126
+ inputs: [{
127
+ name: "addr",
128
+ type: "address"
129
+ }]
130
+ },
131
+ {
132
+ type: "error",
133
+ name: "SeedExecutorAlreadyInstalled",
134
+ inputs: []
135
+ },
136
+ {
137
+ type: "error",
138
+ name: "SeedExecutorNotInstalled",
139
+ inputs: []
140
+ },
141
+ {
142
+ type: "error",
143
+ name: "NotSeedExecutor",
144
+ inputs: [{
145
+ name: "caller",
146
+ type: "address"
147
+ }]
148
+ },
149
+ {
150
+ type: "error",
151
+ name: "UnsupportedExecutionMode",
152
+ inputs: [{
153
+ name: "mode",
154
+ type: "bytes32"
155
+ }]
156
+ },
157
+ {
158
+ type: "error",
159
+ name: "TargetNotAllowed",
160
+ inputs: [{
161
+ name: "target",
162
+ type: "address"
163
+ }]
164
+ },
165
+ {
166
+ type: "error",
167
+ name: "SelectorNotAllowed",
168
+ inputs: [{
169
+ name: "selector",
170
+ type: "bytes4"
171
+ }]
172
+ },
173
+ {
174
+ type: "error",
175
+ name: "ValueMismatch",
176
+ inputs: [{
177
+ name: "encodedValue",
178
+ type: "uint256"
179
+ }, {
180
+ name: "sentValue",
181
+ type: "uint256"
182
+ }]
183
+ },
184
+ ...le,
185
+ ...ne
186
+ ];
187
+ function Yt(e) {
188
+ if (e instanceof et) return e.walk((e) => {
189
+ let t = e.data;
190
+ return typeof t == "string" && t.startsWith("0x") && t.length > 2;
191
+ })?.data;
192
+ }
193
+ function Xt(e) {
194
+ if (Yt(e)) return !0;
195
+ let t = e instanceof et ? `${e.shortMessage} ${e.details}` : String(e);
196
+ return /revert/i.test(t);
197
+ }
198
+ var Zt = "reverted with no data. The target likely has no matching function or the account cannot run executor calls";
199
+ function Qt(e, t = Zt) {
200
+ if (!e || e === "0x") return t;
201
+ try {
202
+ let t = nt({
203
+ abi: Jt,
204
+ data: e
205
+ }), n = t.args?.length ? `(${t.args.map(String).join(", ")})` : "";
206
+ return `reverted with ${t.errorName}${n}`;
207
+ } catch {
208
+ return `reverted with data ${e}`;
209
+ }
210
+ }
211
+ function $t(e, t) {
212
+ return t && t !== "0x" ? `The publish UserOp in transaction ${e} ${Qt(t)}.` : `The publish UserOp in transaction ${e} failed with no revert reason. That usually means it ran out of gas (the bundler's gas estimate was too low), not that the publish data is wrong. To confirm, run \`npx hardhat seed:explain-userop --network <network> --tx ${e}\` in seed-protocol.`;
213
+ }
214
+ function en(e) {
215
+ let { txHash: t, revertData: n, sender: r, cause: i } = e, a = !!n && n !== "0x";
216
+ return new D($t(t, n), a ? "USEROP_REVERTED" : "USEROP_FAILED_NO_REASON", r, i);
217
+ }
218
+ function tn(e) {
219
+ let t = [];
220
+ for (let n = e; n && t.length < 6; n = n.cause) t.push(n);
221
+ return t;
222
+ }
223
+ var nn;
224
+ function rn(e) {
225
+ return nn ??= new Map(Jt.filter((e) => e.type === "error").map((e) => [ot(`${e.name}(${e.inputs.map((e) => e.type).join(",")})`), e.name])), nn.get(e.toLowerCase());
226
+ }
227
+ function an(e, t) {
228
+ for (let n of tn(e)) {
229
+ let r = String(n.message ?? "").match(/UserOp failed at txHash: (0x[0-9a-f]{64})/i);
230
+ if (r) return en({
231
+ txHash: r[1],
232
+ sender: t,
233
+ cause: e
234
+ });
235
+ let i = n.signature;
236
+ if (n.name === "AbiErrorSignatureNotFoundError" && typeof i == "string") {
237
+ let n = rn(i);
238
+ if (n) return new D(`The publish transaction reverted with ${n} (its arguments were not decoded).`, "USEROP_REVERTED", t, e);
239
+ }
240
+ }
241
+ return e;
242
+ }
243
+ //#endregion
244
+ //#region src/helpers/blockchain.ts
245
+ var z = () => {
246
+ let e = De.getArweaveJsApiConfig(), t = At;
247
+ return Object.keys(t).includes("default") && t.default ? t.default.init(e) : t.init(e);
248
+ };
249
+ //#endregion
250
+ //#region src/helpers/schemaRegistry.ts
251
+ async function B(e) {
252
+ return re(e);
253
+ }
254
+ function on(e) {
255
+ return c(e);
256
+ }
257
+ //#endregion
258
+ //#region src/helpers/nameSchemaAttestation.ts
259
+ var sn = "0x0000000000000000000000000000000000000000";
260
+ function cn(e) {
261
+ let n = new Mt("bytes32 schemaId,string name").encodeData([{
262
+ name: "schemaId",
263
+ value: e.schemaUid,
264
+ type: "bytes32"
265
+ }, {
266
+ name: "name",
267
+ value: e.schemaName,
268
+ type: "string"
269
+ }]);
270
+ return t({
271
+ schema: pe,
272
+ data: {
273
+ recipient: sn,
274
+ expirationTime: BigInt(jt),
275
+ revocable: !0,
276
+ refUID: Ft,
277
+ data: n,
278
+ value: 0n
279
+ }
280
+ });
281
+ }
282
+ //#endregion
283
+ //#region src/services/publish/helpers/ensureEasSchemas.ts
284
+ var V = "0x0000000000000000000000000000000000000000", H = !0, ln = "bytes32 schemaId,string name", un = "bytes32 version", dn = /* @__PURE__ */ new Set();
285
+ function fn(e) {
286
+ return e.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
287
+ }
288
+ async function pn(e) {
289
+ let { itemRelationProperties: t, itemImageProperties: n, itemListProperties: r } = await Le(e), i = /* @__PURE__ */ new Set();
290
+ e.modelName && i.add(e.modelName);
291
+ for (let e of t) {
292
+ let t = e.propertyDef?.ref;
293
+ t && i.add(t);
294
+ }
295
+ for (let e of n) {
296
+ let t = We(e.propertyDef?.dataType);
297
+ t === ke.File ? i.add("File") : t === ke.Html ? i.add("Html") : i.add("Image");
298
+ }
299
+ for (let e of r) {
300
+ let t = e.propertyDef?.ref;
301
+ t && i.add(t);
302
+ }
303
+ return i;
304
+ }
305
+ async function U(e, t) {
306
+ let n = await e.sendTransaction(t);
307
+ await T(n.transactionHash);
308
+ }
309
+ function mn(e) {
310
+ let t = We(e);
311
+ return Oe[t]?.eas ?? "string";
312
+ }
313
+ function hn(e, t) {
314
+ if (e) throw Error(`schema "${t}" is not registered; automation keys can't register schemas. Call ensureEasSchemasForItem with the owner wallet first.`);
315
+ }
316
+ async function gn() {
317
+ let e = he().id;
318
+ if (dn.has(e)) return;
319
+ let t = Nt.getSchemaUID(un, V, H), n = [[ln, pe], [un, t]], r = [];
320
+ for (let [e, t] of n) await B(t) || r.push(`"${e}" (${t})`);
321
+ if (r.length > 0) throw Error(`Seed base schema${r.length > 1 ? "s" : ""} ${r.join(" and ")} not registered on chain ${e}. The protocol registers base schemas for each supported chain (seed-protocol: bun run seed:ensure-schemas).`);
322
+ dn.add(e);
323
+ }
324
+ async function _n(e, t) {
325
+ if (typeof t?.blockSchemaRegistration == "boolean") return t.blockSchemaRegistration;
326
+ let n = t?.managedAddress?.trim();
327
+ if (!n || !m(e)) return !1;
328
+ let { isAutomationSessionActive: r } = await import("./ensureAutomationSessionKey-Bw74ZSGI.js").then((e) => e.n);
329
+ return r(n, e.signer.address);
330
+ }
331
+ async function vn(e, t, n) {
332
+ await yn(e, t, n);
333
+ }
334
+ async function yn(e, t, r) {
335
+ let i = await _n(t, r), a = m(t) ? t.txSender : n(t) ? t : (() => {
336
+ throw Error("@seedprotocol/publish: ensureEasSchemasForItem requires a PublishWallet or SeedTxSender");
337
+ })();
338
+ await gn();
339
+ let { itemBasicProperties: o, itemRelationProperties: s, itemImageProperties: c, itemListProperties: l } = await Le(e), u = [
340
+ ...o,
341
+ ...s,
342
+ ...c,
343
+ ...l
344
+ ], d = /* @__PURE__ */ new Set(), f = await pn(e), p = /* @__PURE__ */ new Set();
345
+ for (let e of f) {
346
+ let t = `bytes32 ${fn(e)}`, n = Nt.getSchemaUID(t, V, H);
347
+ if (await B(n)) {
348
+ Xe({
349
+ modelName: e,
350
+ schemaUid: n
351
+ });
352
+ continue;
353
+ }
354
+ if (p.has(n)) {
355
+ Xe({
356
+ modelName: e,
357
+ schemaUid: n
358
+ });
359
+ continue;
360
+ }
361
+ hn(i, t);
362
+ try {
363
+ await U(a, on({
364
+ schema: t,
365
+ resolverAddress: V,
366
+ revocable: H
367
+ }));
368
+ } catch (t) {
369
+ throw Error(`Failed to register EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
370
+ }
371
+ try {
372
+ await U(a, cn({
373
+ schemaUid: n,
374
+ schemaName: fn(e)
375
+ }));
376
+ } catch (t) {
377
+ throw Error(`Failed to name EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
378
+ }
379
+ p.add(n), Xe({
380
+ modelName: e,
381
+ schemaUid: n
382
+ });
383
+ }
384
+ let h = "string storage_transaction_id", g = Nt.getSchemaUID(h, V, H);
385
+ if (await B(g)) Ze({
386
+ text: h,
387
+ schemaUid: g
388
+ });
389
+ else if (!d.has(g) && (f.has("Image") || f.has("File") || f.has("Html"))) {
390
+ hn(i, h);
391
+ try {
392
+ await U(a, on({
393
+ schema: h,
394
+ resolverAddress: V,
395
+ revocable: H
396
+ })), await U(a, cn({
397
+ schemaUid: g,
398
+ schemaName: "storage_transaction_id"
399
+ }));
400
+ } catch (e) {
401
+ throw Error(`Failed to register EAS schema for storageTransactionId: ${e instanceof Error ? e.message : String(e)}`);
402
+ }
403
+ d.add(g), Ze({
404
+ text: h,
405
+ schemaUid: g
406
+ });
407
+ }
408
+ for (let e of u) {
409
+ if (!e.propertyDef) continue;
410
+ let t = mn(e.propertyDef.dataType), n = e, r = Ue(e.propertyName, e.propertyDef), o = r ?? (n.storagePropertyName && n.storagePropertyName.length > 0 ? n.storagePropertyName : e.propertyName), s = fn(o), c = `${t} ${s}`;
411
+ if (r && !s.endsWith("_ids")) throw Error(`Refusing to register "${c}" for list-relation property ${e.propertyName}: list relations attest as <singular>_<ref>_ids.`);
412
+ let l = [
413
+ "string",
414
+ "address",
415
+ "bool",
416
+ "bytes",
417
+ "bytes32",
418
+ "uint8",
419
+ "uint16",
420
+ "uint32",
421
+ "uint64",
422
+ "uint128",
423
+ "uint256"
424
+ ].includes(t) ? t : void 0, u = await Pe({
425
+ schemaUid: r ? void 0 : e.schemaUid,
426
+ propertyName: o,
427
+ easDataType: l
428
+ });
429
+ if (u) {
430
+ let e = await B(u.id);
431
+ if (e && e.schema === c) {
432
+ Ze({
433
+ text: c,
434
+ schemaUid: u.id
435
+ });
436
+ continue;
437
+ }
438
+ }
439
+ let f = Nt.getSchemaUID(c, V, H);
440
+ if (await B(f)) {
441
+ Ze({
442
+ text: c,
443
+ schemaUid: f
444
+ });
445
+ continue;
446
+ }
447
+ if (d.has(f)) {
448
+ Ze({
449
+ text: c,
450
+ schemaUid: f
451
+ });
452
+ continue;
453
+ }
454
+ hn(i, c);
455
+ try {
456
+ await U(a, on({
457
+ schema: c,
458
+ resolverAddress: V,
459
+ revocable: H
460
+ }));
461
+ } catch (t) {
462
+ throw Error(`Failed to register EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
463
+ }
464
+ try {
465
+ await U(a, cn({
466
+ schemaUid: f,
467
+ schemaName: s
468
+ }));
469
+ } catch (t) {
470
+ throw Error(`Failed to name EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
471
+ }
472
+ d.add(f), Ze({
473
+ text: c,
474
+ schemaUid: f
475
+ });
476
+ }
477
+ let _ = await Ie(e);
478
+ for (let e of _) await yn(e, t, {
479
+ managedAddress: r?.managedAddress,
480
+ blockSchemaRegistration: i
481
+ });
482
+ }
483
+ //#endregion
484
+ //#region src/services/publish/actors/utils.ts
485
+ var W = "0x" + "0".repeat(64), bn = async (e) => {
486
+ let t;
487
+ try {
488
+ t = await j.find({ seedLocalId: e });
489
+ } catch {}
490
+ return t || new Promise((t) => {
491
+ let n = setInterval(() => {
492
+ try {
493
+ j.find({ seedLocalId: e }).then((e) => {
494
+ e && (clearInterval(n), t(e));
495
+ });
496
+ } catch {}
497
+ }, 200);
498
+ });
499
+ };
500
+ function xn(e) {
501
+ if (!e || typeof e != "object") return;
502
+ let t = e;
503
+ if (Array.isArray(t.data_root)) return {
504
+ data_root: new Uint8Array(t.data_root),
505
+ chunks: (t.chunks ?? []).map((e) => ({
506
+ ...e,
507
+ dataHash: new Uint8Array(e.dataHash ?? [])
508
+ })),
509
+ proofs: (t.proofs ?? []).map((e) => ({
510
+ ...e,
511
+ proof: new Uint8Array(e.proof ?? [])
512
+ }))
513
+ };
514
+ }
515
+ function Sn(e) {
516
+ return {
517
+ data_root: Array.from(e.data_root),
518
+ chunks: e.chunks.map((e) => ({
519
+ ...e,
520
+ dataHash: Array.from(e.dataHash)
521
+ })),
522
+ proofs: e.proofs.map((e) => ({
523
+ ...e,
524
+ proof: Array.from(e.proof)
525
+ }))
526
+ };
527
+ }
528
+ //#endregion
529
+ //#region src/services/publish/actors/createArweaveTransactions.ts
530
+ var Cn = I(async ({ input: { context: e } }) => {
531
+ let { item: t } = e;
532
+ t.getPublishUploads || (t = await bn(t.seedLocalId));
533
+ let n = {};
534
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
535
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
536
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
537
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = w(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, s = e.arweaveJwk ?? a.arweaveJwk, c = i.map((e) => ({
538
+ versionLocalId: e.versionLocalId,
539
+ itemPropertyName: e.itemPropertyName,
540
+ transactionJson: e.transactionToSign.toJSON()
541
+ })), l;
542
+ if (o) l = await o(c);
543
+ else if (s) {
544
+ let e = z(), t = s;
545
+ l = [];
546
+ for (let n of c) {
547
+ let r = e.transactions.fromRaw(n.transactionJson);
548
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
549
+ let i = r.toJSON();
550
+ l.push({
551
+ transaction: {
552
+ ...i,
553
+ chunks: r.chunks ? Sn(r.chunks) : void 0
554
+ },
555
+ versionId: n.versionLocalId,
556
+ modelName: n.itemPropertyName
557
+ });
558
+ }
559
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
560
+ let u = z();
561
+ return {
562
+ arweaveTransactions: l.map((e) => {
563
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = xn(t);
564
+ return i && (r.chunks = i), {
565
+ transaction: u.transactions.fromRaw(r),
566
+ versionId: e.versionId,
567
+ modelName: e.modelName
568
+ };
569
+ }),
570
+ publishUploads: i
571
+ };
572
+ }), wn = I(async ({ input: { context: e } }) => {
573
+ let { item: t } = e;
574
+ t.getPublishUploads || (t = await bn(t.seedLocalId));
575
+ let n = {};
576
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
577
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
578
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
579
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = w(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, s = e.arweaveJwk ?? a.arweaveJwk, c = i.map((e) => ({
580
+ versionLocalId: e.versionLocalId,
581
+ itemPropertyName: e.itemPropertyName,
582
+ transactionJson: e.transactionToSign.toJSON()
583
+ })), l;
584
+ if (o) l = await o(c);
585
+ else if (s) {
586
+ let e = z(), t = s;
587
+ l = [];
588
+ for (let n of c) {
589
+ let r = e.transactions.fromRaw(n.transactionJson);
590
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
591
+ let i = r.toJSON();
592
+ l.push({
593
+ transaction: {
594
+ ...i,
595
+ chunks: r.chunks ? Sn(r.chunks) : void 0
596
+ },
597
+ versionId: n.versionLocalId,
598
+ modelName: n.itemPropertyName
599
+ });
600
+ }
601
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
602
+ let u = z();
603
+ return {
604
+ arweaveTransactions: l.map((e) => {
605
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = xn(t);
606
+ return i && (r.chunks = i), {
607
+ transaction: u.transactions.fromRaw(r),
608
+ versionId: e.versionId,
609
+ modelName: e.modelName
610
+ };
611
+ }),
612
+ publishUploads: i
613
+ };
614
+ }), Tn = I(async ({ input: { context: e } }) => {
615
+ let t = e.htmlEmbeddedDataUriPolicy ?? "materialize";
616
+ return { deferredHtmlSeedLocalIds: (await Ke(e.item, t)).deferredHtmlSeedLocalIds };
617
+ });
618
+ //#endregion
619
+ //#region src/services/publish/actors/rewritingHtmlEmbedded.ts
620
+ function En(e, t) {
621
+ let n = [], r = Math.min(e?.length ?? 0, t?.length ?? 0);
622
+ for (let i = 0; i < r; i++) {
623
+ let r = e[i], a = t[i], o = r.transaction?.id;
624
+ typeof o == "string" && o.length > 0 && n.push({
625
+ txId: o,
626
+ seedLocalId: a.seedLocalId,
627
+ versionLocalId: a.versionLocalId
628
+ });
629
+ }
630
+ return n;
631
+ }
632
+ var Dn = I(async ({ input: { context: e } }) => {
633
+ let t = En(e.htmlEmbeddedPhase1ArweaveTransactions, e.htmlEmbeddedPhase1PublishUploads);
634
+ await Ye(e.item.seedLocalId, t);
635
+ }), On = (e, t, n) => {
636
+ let r = [];
637
+ return e && r.push({
638
+ name: "Content-SHA-256",
639
+ value: e
640
+ }), t && r.push({
641
+ name: "Content-Type",
642
+ value: t
643
+ }), n?.length && r.push(...n), r;
644
+ }, kn = async (e) => {
645
+ let t = (e instanceof Uint8Array, new Uint8Array(e)), n = await crypto.subtle.digest("SHA-256", t);
646
+ return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
647
+ }, An = {
648
+ png: "image/png",
649
+ jpg: "image/jpeg",
650
+ jpeg: "image/jpeg",
651
+ gif: "image/gif",
652
+ webp: "image/webp",
653
+ svg: "image/svg+xml",
654
+ html: "text/html",
655
+ htm: "text/html",
656
+ json: "application/json",
657
+ txt: "text/plain"
658
+ }, jn = (e) => {
659
+ let t = e.split(".").pop()?.toLowerCase();
660
+ return t ? An[t] : void 0;
661
+ }, Mn = async (e) => typeof Blob < "u" && e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : new Uint8Array(e), Nn = (e) => {
662
+ switch (e) {
663
+ case "Image": return A.getFilesPath("images");
664
+ case "File": return A.getFilesPath("files");
665
+ case "Html": return A.getFilesPath("html");
666
+ case "Json": return A.getFilesPath("json");
667
+ default: return A.getFilesPath("images");
668
+ }
669
+ }, Pn = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
670
+ function Fn(e) {
671
+ let t = Pn.exec((e ?? "").trim());
672
+ if (!t) return null;
673
+ try {
674
+ let e = t[1].toLowerCase().trim(), n = t[2].replace(/\s/g, "");
675
+ return {
676
+ mimeType: e,
677
+ bytes: Uint8Array.from(atob(n), (e) => e.charCodeAt(0))
678
+ };
679
+ } catch {
680
+ return null;
681
+ }
682
+ }
683
+ var In = async (e, t, n, r) => {
684
+ let i = r?.arweaveUploadTags, a = e.itemProperty, o = [];
685
+ for (let t of e.childProperties) {
686
+ let e = t.localStoragePath;
687
+ e && !e.endsWith("undefined") && await A.pathExists(e) && o.push({
688
+ propertyName: t.propertyName,
689
+ localStoragePath: e
690
+ });
691
+ }
692
+ let s;
693
+ if ((!o || o.length === 0) && n?.localStoragePath) {
694
+ let e = n.localStoragePath;
695
+ if (e && !e.endsWith("undefined") && await A.pathExists(e)) try {
696
+ s = await Mn(await A.readFileAsBuffer(e));
697
+ } catch {
698
+ s = await Mn((await A.getFs()).readFileSync(e));
699
+ }
700
+ }
701
+ if (o.length > 0) {
702
+ let e = "===FILE_SEPARATOR===", t = "", n = await A.getFs();
703
+ for (let r of o) {
704
+ let i;
705
+ try {
706
+ i = await n.promises.readFile(r.localStoragePath);
707
+ } catch {
708
+ i = n.readFileSync(r.localStoragePath);
709
+ }
710
+ t += `${e}${r.propertyName}${e}${i}`;
711
+ }
712
+ s = typeof document < "u" ? new TextEncoder().encode(t) : new Uint8Array(Buffer.from(t));
713
+ }
714
+ if (!s) return t;
715
+ let c = new Uint8Array(s), l = await kn(c), u;
716
+ o.length === 0 && n?.localStoragePath ? u = jn(n.localStoragePath) : o.length > 0 && (u = "application/octet-stream");
717
+ let d = n ? n.localId : a.localId, f = n ? n.propertyName : a.propertyName;
718
+ return t.push({
719
+ data: c,
720
+ contentHash: l,
721
+ contentType: u,
722
+ tags: On(l, u, i),
723
+ itemPropertyName: f,
724
+ itemPropertyLocalId: d,
725
+ seedLocalId: a.seedLocalId,
726
+ versionLocalId: a.versionLocalId
727
+ }), t;
728
+ }, Ln = async (e, t) => {
729
+ let n = [], r = t?.arweaveUploadTags;
730
+ for (let i of e) {
731
+ let e = i.getService().getSnapshot(), a = "context" in e ? e.context : null;
732
+ if (!a) continue;
733
+ let o = a.propertyValue, s = a.refResolvedValue;
734
+ if (!s) continue;
735
+ let { localId: c } = Ne(o ?? "");
736
+ if (!c) continue;
737
+ let l = i.propertyDef?.refValueType ?? i.propertyDef?.dataType ?? "Image";
738
+ if (l === ke.Html) {
739
+ if (t?.deferHtmlStorageSeedLocalIds?.includes(c) || t?.onlyHtmlStorageSeedLocalIds?.length && !t.onlyHtmlStorageSeedLocalIds.includes(c)) continue;
740
+ } else if (t?.onlyHtmlStorageSeedLocalIds?.length) continue;
741
+ let u = `${Nn(l)}/${s}`;
742
+ if (!await A.pathExists(u)) continue;
743
+ let d = await Mn(await A.readFileAsBuffer(u)), f = await kn(d), p = jn(s);
744
+ n.push({
745
+ data: d,
746
+ contentHash: f,
747
+ contentType: p,
748
+ tags: On(f, p, r),
749
+ itemPropertyName: i.propertyName,
750
+ itemPropertyLocalId: i.localId,
751
+ seedLocalId: c,
752
+ versionLocalId: i.versionLocalId
753
+ });
754
+ }
755
+ return n;
756
+ };
757
+ async function Rn(e, t, n) {
758
+ let r = k.getAppDb();
759
+ if (!r || n?.onlyHtmlStorageSeedLocalIds?.length) return t;
760
+ let i = await r.select().from(ze).where(R(ze.parentSeedLocalId, e.seedLocalId)), a = new Set(t.map((e) => e.seedLocalId));
761
+ for (let e of i) {
762
+ if (a.has(e.imageSeedLocalId)) continue;
763
+ let r = await j.find({
764
+ seedLocalId: e.imageSeedLocalId,
765
+ modelName: "Image"
766
+ });
767
+ if (!r) continue;
768
+ let i = r.internalProperties.storageTransactionId ?? r.allProperties.storageTransactionId, o = i?.getService().getSnapshot(), s = o && "context" in o ? o.context : void 0, c = Fn(typeof s?.propertyValue == "string" ? s.propertyValue ?? "" : ""), l = [];
769
+ if (c && i && i.localId && i.versionLocalId) {
770
+ let e = await kn(c.bytes);
771
+ l = [{
772
+ data: c.bytes,
773
+ contentHash: e,
774
+ contentType: c.mimeType,
775
+ tags: On(e, c.mimeType, n?.arweaveUploadTags),
776
+ itemPropertyName: i.propertyName,
777
+ itemPropertyLocalId: i.localId,
778
+ seedLocalId: r.seedLocalId,
779
+ versionLocalId: i.versionLocalId
780
+ }];
781
+ }
782
+ for (let e of l) a.has(e.seedLocalId) || (t.push(e), a.add(e.seedLocalId));
783
+ }
784
+ return t;
785
+ }
786
+ var zn = async (e, t = [], n, r) => {
787
+ let { itemUploadProperties: i, itemRelationProperties: a, itemImageProperties: o } = await Le(e);
788
+ if (!n && r?.onlyHtmlStorageSeedLocalIds?.length) {
789
+ let e = await Ln(o, r);
790
+ return t.push(...e), t;
791
+ }
792
+ for (let e of i) t = await In(e, t, n, r);
793
+ let s = await Ln(o, r);
794
+ if (t.push(...s), !n && !r?.onlyHtmlStorageSeedLocalIds?.length && (t = await Rn(e, t, r)), r?.skipRelationRecursion) return t;
795
+ for (let e of a) {
796
+ let n = e.getService().getSnapshot(), i = "context" in n ? n.context : null;
797
+ if (!i) continue;
798
+ let a = i.propertyValue;
799
+ if (!a || e.uid) continue;
800
+ let { seedLocalId: o, seedUid: s } = Je(Ge(a) ?? "");
801
+ if (!o && !s) throw Error(`Invalid relation value for ${e.propertyName}: expected local seed id or 0x uid`);
802
+ let c = await j.find({
803
+ seedLocalId: o,
804
+ seedUid: s
805
+ });
806
+ if (!c) {
807
+ if (Ve(a)) continue;
808
+ throw Error(`No relatedItem found for ${e.propertyName}`);
809
+ }
810
+ t = await zn(c, t, e, r);
811
+ }
812
+ return t;
813
+ }, Bn = 3, Vn = new TextEncoder().encode("seed-recovery"), Hn = 32, Un = 18446744073709551615n;
814
+ function Wn(e, t, n) {
815
+ let r = N.solidityPackedKeccak256([
816
+ "uint256",
817
+ "address",
818
+ "uint64"
819
+ ], [
820
+ BigInt(t),
821
+ e,
822
+ n & Un
823
+ ]);
824
+ return N.getBytes(r);
825
+ }
826
+ function Gn(e) {
827
+ if (e.length === 0) return new Uint8Array([0]);
828
+ if (e.length !== Hn) throw Error(`ANS-104 target/anchor must be empty or ${Hn} bytes, got ${e.length}`);
829
+ let t = /* @__PURE__ */ new Uint8Array(33);
830
+ return t[0] = 1, t.set(e, 1), t;
831
+ }
832
+ function Kn(e) {
833
+ return typeof e == "object" && !!e && "privateKey" in e && typeof e.privateKey == "string";
834
+ }
835
+ function qn(e, t, n) {
836
+ let r = e >= 0 ? e << 1 : ~e << 1 | 1, i = n;
837
+ do {
838
+ let e = r & 127;
839
+ r >>>= 7, t[i++] = r ? e | 128 : e;
840
+ } while (r);
841
+ return i - n;
842
+ }
843
+ var Jn = (e) => {
844
+ if (!e?.length) return /* @__PURE__ */ new Uint8Array();
845
+ let t = new TextEncoder(), n = /* @__PURE__ */ new Uint8Array(16), r = [], i = (e) => {
846
+ let t = qn(e, n, 0);
847
+ r.push(n.slice(0, t));
848
+ };
849
+ i(e.length);
850
+ for (let n of e) {
851
+ let e = t.encode(n.name), a = t.encode(n.value);
852
+ i(e.length), r.push(e), i(a.length), r.push(a);
853
+ }
854
+ i(0);
855
+ let a = r.reduce((e, t) => e + t.length, 0), o = new Uint8Array(a), s = 0;
856
+ for (let e of r) o.set(e, s), s += e.length;
857
+ return o;
858
+ }, Yn = (e) => {
859
+ let t = /* @__PURE__ */ new Uint8Array(8), n = new DataView(t.buffer);
860
+ return n.setUint32(0, e & 4294967295, !0), n.setUint32(4, Math.floor(e / 4294967296), !0), t;
861
+ };
862
+ async function Xn(e) {
863
+ return new Uint8Array(await crypto.subtle.digest("SHA-384", e));
864
+ }
865
+ function Zn(e, t) {
866
+ let n = new Uint8Array(e.length + t.length);
867
+ return n.set(e, 0), n.set(t, e.length), n;
868
+ }
869
+ async function Qn(e) {
870
+ let t = new TextEncoder();
871
+ if (Array.isArray(e)) {
872
+ let n = await Xn(Zn(t.encode("list"), t.encode(e.length.toString())));
873
+ for (let t of e) {
874
+ let e = await Qn(t);
875
+ n = await Xn(Zn(n, e));
876
+ }
877
+ return n;
878
+ }
879
+ return Xn(Zn(await Xn(Zn(t.encode("blob"), t.encode(e.byteLength.toString()))), await Xn(e)));
880
+ }
881
+ async function $n(e, t, n, r, i) {
882
+ let a = new TextEncoder();
883
+ return Qn([
884
+ a.encode("dataitem"),
885
+ a.encode("1"),
886
+ a.encode(Bn.toString()),
887
+ e,
888
+ t,
889
+ n,
890
+ r,
891
+ i
892
+ ]);
893
+ }
894
+ function er(e, t, n, r, i) {
895
+ let a = Jn(t), o = Yn(t.length), s = Yn(a.length), c = [
896
+ e,
897
+ Gn(r),
898
+ Gn(i),
899
+ o,
900
+ s,
901
+ a,
902
+ n
903
+ ], l = c.reduce((e, t) => e + t.length, 0), u = new Uint8Array(l), d = 0;
904
+ for (let e of c) u.set(e, d), d += e.length;
905
+ return u;
906
+ }
907
+ async function tr(e, t) {
908
+ let n = /* @__PURE__ */ new Uint8Array(2);
909
+ new DataView(n.buffer).setUint16(0, Bn, !0);
910
+ let r = 67 + t.length, i = new Uint8Array(r);
911
+ i.set(n, 0), i.set(e, 2), i.set(t, 67);
912
+ let a = await crypto.subtle.digest("SHA-256", new Uint8Array(e));
913
+ return {
914
+ id: sr(new Uint8Array(a)),
915
+ raw: i
916
+ };
917
+ }
918
+ var nr = async (e, t, n, r = /* @__PURE__ */ new Uint8Array()) => {
919
+ let i = N.SigningKey.computePublicKey(t.privateKey, !1), a = N.getBytes(i), o = Jn(n), s = /* @__PURE__ */ new Uint8Array(), c = await $n(a, s, r, o, e);
920
+ return tr(N.getBytes(await t.signMessage(c)), er(a, n, e, s, r));
921
+ }, rr = async (e, t, n, r = /* @__PURE__ */ new Uint8Array()) => {
922
+ let i = N.hexlify(Vn), a = await t.signMessage({ message: { raw: i } }), o = N.hashMessage(Vn), s = N.SigningKey.recoverPublicKey(o, a), c = N.getBytes(s), l = Jn(n), u = /* @__PURE__ */ new Uint8Array(), d = await $n(c, u, r, l, e), f = N.hexlify(d), p = await t.signMessage({ message: { raw: f } });
923
+ return tr(N.getBytes(p), er(c, n, e, u, r));
924
+ };
925
+ function ir(e) {
926
+ if (e.length < 133) return null;
927
+ let t = e[132];
928
+ if (t !== 0 && t !== 1) return null;
929
+ let n = t === 1;
930
+ if (n && e.length < 165) return null;
931
+ let r = 132 + (n ? 33 : 1);
932
+ if (e.length < r + 1) return null;
933
+ let i = e[r];
934
+ if (i !== 0 && i !== 1) return null;
935
+ let a = i === 1;
936
+ return a && e.length < r + 33 ? null : r + (a ? 33 : 1);
937
+ }
938
+ function ar(e) {
939
+ let t = ir(e);
940
+ if (t == null) return null;
941
+ let n = e[132] === 1, r = n ? e.slice(133, 165) : /* @__PURE__ */ new Uint8Array(), i = 132 + (n ? 33 : 1);
942
+ return {
943
+ rawTarget: r,
944
+ rawAnchor: e[i] === 1 ? e.slice(i + 1, i + 33) : /* @__PURE__ */ new Uint8Array(),
945
+ tagsStart: t
946
+ };
947
+ }
948
+ async function or(e) {
949
+ let t = ar(e);
950
+ if (t == null) return !1;
951
+ let { rawTarget: n, rawAnchor: r, tagsStart: i } = t, a = i + 16;
952
+ if (e.length < a) return !1;
953
+ let o = new DataView(e.buffer, e.byteOffset, e.byteLength);
954
+ if (o.getUint16(0, !0) !== Bn) return !1;
955
+ let s = e.slice(2, 67), c = e.slice(67, 132), l = Number(o.getUint32(i + 8, !0) + o.getUint32(i + 12, !0) * 4294967296), u = i + 16 + l;
956
+ if (e.length < u) return !1;
957
+ let d = e.slice(i + 16, u), f = e.slice(u);
958
+ try {
959
+ let e = await $n(c, n, r, d, f), t = N.hashMessage(e), i = N.hexlify(s), a = N.SigningKey.recoverPublicKey(t, i), o = N.getBytes(a);
960
+ return o.length === c.length && o.every((e, t) => e === c[t]);
961
+ } catch {
962
+ return !1;
963
+ }
964
+ }
965
+ var sr = (e) => {
966
+ let t = "";
967
+ for (let n of e) t += String.fromCharCode(n);
968
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
969
+ }, cr = L("seedProtocol:createArweaveDataItems");
970
+ async function lr(e, t, n) {
971
+ let r, i;
972
+ if (t) r = (await t(e)).map((e) => ({
973
+ transaction: { id: e.transaction.id },
974
+ versionId: e.versionId,
975
+ modelName: e.modelName
976
+ }));
977
+ else if (n) {
978
+ let t = [], a = Date.now();
979
+ for (let r = 0; r < e.length; r++) {
980
+ let i = e[r], o = i.tags, s = /* @__PURE__ */ new Uint8Array(8);
981
+ crypto.getRandomValues(s);
982
+ let c = (new DataView(s.buffer).getBigUint64(0, !1) ^ BigInt(r)) & 18446744073709551615n, l;
983
+ if (Kn(n)) {
984
+ let e = Wn(n.address, a, c);
985
+ l = await nr(i.data, n, o, e);
986
+ } else {
987
+ let e = m(n) ? n.signer : n, t = Wn(e.address, a, c);
988
+ l = await rr(i.data, e, o, t);
989
+ }
990
+ if (!await or(l.raw)) throw cr("DataItem verification failed: id=%s modelName=%s", l.id, i.itemPropertyName), Error(`DataItem signature verification failed for ${i.itemPropertyName}. The signing key may not match the owner, or the payload may have been modified.`);
991
+ t.push(l);
992
+ }
993
+ i = t, r = t.map((t, n) => ({
994
+ transaction: { id: t.id },
995
+ versionId: e[n]?.versionLocalId,
996
+ modelName: e[n]?.itemPropertyName
997
+ }));
998
+ } else throw Error("@seedprotocol/publish: useArweaveBundler requires signDataItems or dataItemSigner (pass at createPublish or in PublishProvider config)");
999
+ let a = e.map((e) => ({
1000
+ itemPropertyName: e.itemPropertyName,
1001
+ itemPropertyLocalId: e.itemPropertyLocalId,
1002
+ seedLocalId: e.seedLocalId,
1003
+ versionLocalId: e.versionLocalId,
1004
+ transactionToSign: null
1005
+ }));
1006
+ return {
1007
+ arweaveTransactions: r,
1008
+ publishUploads: a,
1009
+ signedDataItems: i
1010
+ };
1011
+ }
1012
+ var ur = I(async ({ input: { context: e } }) => {
1013
+ let { item: t } = e;
1014
+ t.getPublishUploads || (t = await bn(t.seedLocalId));
1015
+ let n = {};
1016
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
1017
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
1018
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
1019
+ let i = await zn(t, [], void 0, Object.keys(n).length ? n : void 0), a = w();
1020
+ return lr(i, e.signDataItems ?? a.signDataItems, e.dataItemSigner ?? a.dataItemSigner);
1021
+ });
1022
+ //#endregion
1023
+ //#region src/services/publish/actors/createArweaveDataItemsPhase2.ts
1024
+ async function dr(e) {
1025
+ let { item: t } = e;
1026
+ t.getPublishUploads || (t = await bn(t.seedLocalId));
1027
+ let n = {};
1028
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
1029
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
1030
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
1031
+ let i = await zn(t, [], void 0, Object.keys(n).length ? n : void 0), a = w(), o = e.signDataItems ?? a.signDataItems, s = e.dataItemSigner ?? a.dataItemSigner;
1032
+ return i.length === 0 ? {
1033
+ arweaveTransactions: [],
1034
+ publishUploads: [],
1035
+ signedDataItems: void 0
1036
+ } : lr(i, o, s);
1037
+ }
1038
+ var fr = I(async ({ input: { context: e } }) => dr(e)), pr = 8192;
1039
+ function mr(e) {
1040
+ let t = new Uint8Array(e), n = "";
1041
+ for (let e = 0; e < t.length; e += pr) {
1042
+ let r = t.subarray(e, Math.min(e + pr, t.length));
1043
+ n += String.fromCharCode.apply(null, r);
1044
+ }
1045
+ return btoa(n);
1046
+ }
1047
+ async function hr(e) {
1048
+ let t = [];
1049
+ for (let [n, r] of e.entries()) {
1050
+ let e = r;
1051
+ if (typeof e == "object" && e && "arrayBuffer" in e) {
1052
+ let r = mr(await e.arrayBuffer()), i = e;
1053
+ t.push({
1054
+ name: n,
1055
+ value: r,
1056
+ encoding: "base64",
1057
+ filename: i.name || void 0
1058
+ });
1059
+ } else t.push({
1060
+ name: n,
1061
+ value: String(r)
1062
+ });
1063
+ }
1064
+ return t;
1065
+ }
1066
+ function gr(e, t, n) {
1067
+ let r = ["Upload server returned ", String(e)], i = t && typeof t == "object" && "message" in t ? String(t.message) : t && typeof t == "object" && "error" in t ? String(t.error) : null;
1068
+ return i ? r.push(`: ${i}`) : n && r.push(` (${n})`), r.join("");
1069
+ }
1070
+ function _r(e) {
1071
+ if (!e) return "Upload server unavailable. Please try again or check your connection.";
1072
+ let t = e.toLowerCase();
1073
+ return /other side closed|econnreset|socket hang up|connection closed/i.test(t) ? "Upload server closed the connection. It may be busy or the request may be too large—try again." : /etimedout|timeout/i.test(t) ? "Upload request timed out. Please try again." : /enotfound|getaddrinfo|dns/i.test(t) ? "Upload server could not be reached. Check the upload URL and your network." : "Upload failed. Please try again or check the upload server.";
1074
+ }
1075
+ async function vr(e, t, n) {
1076
+ let r = typeof window < "u" ? window.Main : void 0;
1077
+ if (r?.uploadArweaveStart) {
1078
+ let n = await hr(t);
1079
+ return r.uploadArweaveStart(e, n);
1080
+ }
1081
+ let i = await fetch(e, {
1082
+ method: "POST",
1083
+ body: t
1084
+ }), a = await i.json().catch(() => ({}));
1085
+ return {
1086
+ status: i.status,
1087
+ body: a
1088
+ };
1089
+ }
1090
+ //#endregion
1091
+ //#region src/services/publish/actors/sendReimbursementRequest.ts
1092
+ var yr = I(async ({ input: { context: e, event: t } }) => {
1093
+ let { arweaveTransactions: n = [], transactionKeys: r, reimbursementTransactionId: i } = e;
1094
+ if (i) return { transactionId: i };
1095
+ let a = n.map(({ transaction: e }) => e), o = new FormData();
1096
+ for (let e of a) {
1097
+ let { data: t, chunks: n, ...r } = e, i = t instanceof Blob ? t : new Blob([t]);
1098
+ o.append(`${e.id}-data`, i, `${e.id}-data`);
1099
+ let a = new Blob([JSON.stringify(n)], { type: "application/json" });
1100
+ o.append(`${e.id}-chunks`, a, `${e.id}-chunks`);
1101
+ let s = new Blob([JSON.stringify(r)], { type: "application/json" });
1102
+ o.append(`${e.id}-json`, s, `${e.id}-json`);
1103
+ }
1104
+ let { uploadApiBaseUrl: s } = w(), { status: c, body: l, message: u } = await vr(`${s}/api/upload/arweave/start`, o, s);
1105
+ if (c >= 300 || c < 200) {
1106
+ let e = c === 0 ? u : null;
1107
+ e && console.error("[upload]", e);
1108
+ let t = c === 0 ? _r(e) : gr(c, l, r);
1109
+ throw Error(t);
1110
+ }
1111
+ return l;
1112
+ }), br = I(async ({ input: { context: e, event: t } }) => {
1113
+ let { requestResponse: n, reimbursementTransactionId: r } = e;
1114
+ if (!n) throw Error("No request response");
1115
+ if (!r) throw Error("No reimbursement transaction id");
1116
+ let i = z();
1117
+ await new Promise((e, t) => {
1118
+ let n = setInterval(async () => {
1119
+ let t;
1120
+ try {
1121
+ t = await i.transactions.getStatus(r);
1122
+ } catch {
1123
+ return;
1124
+ }
1125
+ t && t.confirmed && (clearInterval(n), e());
1126
+ }, 5e3);
1127
+ });
1128
+ }), G = L("seedProtocol:services:publish:actors");
1129
+ function xr(e) {
1130
+ if (e instanceof Uint8Array) return e;
1131
+ if (e instanceof ArrayBuffer) return new Uint8Array(e);
1132
+ throw Error("Transaction data must be Uint8Array or ArrayBuffer for upload resume");
1133
+ }
1134
+ var Sr = F(({ sendBack: e, input: t }) => {
1135
+ let n = t.context, r = (n.arweaveTransactions ?? []).map(({ transaction: e }) => e), i = z(), a = n.uploaderState && typeof n.currentTransactionIndex == "number", o = a ? n.currentTransactionIndex : 0;
1136
+ (async () => {
1137
+ let t = r.length;
1138
+ for (let s = o; s < t; s++) {
1139
+ let c = r[s];
1140
+ if (!c) continue;
1141
+ let l = i.transactions.fromRaw(c);
1142
+ if (!await i.transactions.verify(l)) throw Error("Transaction verification failed");
1143
+ let u, d = n.uploaderState;
1144
+ if (a && s === o && d) {
1145
+ let e = l.data, t = e instanceof Uint8Array ? e : xr(e);
1146
+ u = await i.transactions.getUploader(d, t);
1147
+ } else u = await i.transactions.getUploader(l, l.data);
1148
+ for (; !u.isComplete;) {
1149
+ G("uploading chunk"), G(`uploader.pctComplete: ${u.pctComplete}`), G(`uploader.uploadedChunks: ${u.uploadedChunks}`), G(`uploader.totalChunks: ${u.totalChunks}`), G(u.lastResponseError), G(u.lastResponseStatus);
1150
+ try {
1151
+ await u.uploadChunk(), e({
1152
+ type: "updatePercentage",
1153
+ completionPercentage: Math.trunc((s + u.pctComplete / 100) / t * 100),
1154
+ uploaderState: u.toJSON(),
1155
+ currentTransactionIndex: s
1156
+ }), G(`${u.pctComplete}% complete, ${u.uploadedChunks}/${u.totalChunks}`);
1157
+ } catch (e) {
1158
+ G(e);
1159
+ }
1160
+ }
1161
+ }
1162
+ return "done";
1163
+ })().then((t) => {
1164
+ e({
1165
+ type: "uploadComplete",
1166
+ result: t
1167
+ });
1168
+ }).catch((t) => {
1169
+ e({
1170
+ type: "uploadError",
1171
+ error: t
1172
+ });
1173
+ });
1174
+ }), Cr = 12e4, wr = Function("s", "return import(s)"), Tr = null, Er = async () => {
1175
+ if (Tr) return Tr;
1176
+ if (typeof window < "u") return null;
1177
+ try {
1178
+ let e = await wr(`node:${["fs", "promises"].join("/")}`);
1179
+ return Tr = {
1180
+ readFile: e.readFile,
1181
+ stat: e.stat
1182
+ }, Tr;
1183
+ } catch {
1184
+ return null;
1185
+ }
1186
+ }, Dr = F(({ sendBack: e, input: { context: t } }) => {
1187
+ let { signedDataItems: n } = t, { uploadApiBaseUrl: r, useArweaveBundler: i } = w();
1188
+ if (!i || !r) {
1189
+ e({
1190
+ type: "uploadError",
1191
+ error: /* @__PURE__ */ Error("Arweave bundler not configured. Set useArweaveBundler and uploadApiBaseUrl.")
1192
+ });
1193
+ return;
1194
+ }
1195
+ let a = `${r.replace(/\/$/, "")}/api/upload/arweave/batch`;
1196
+ if (!n || n.length === 0) {
1197
+ e({
1198
+ type: "uploadComplete",
1199
+ result: "done"
1200
+ });
1201
+ return;
1202
+ }
1203
+ (async () => {
1204
+ let e = n, t = e.length, r = Array(t).fill(null), i = async (e, t) => {
1205
+ let n = e;
1206
+ if (n.raw != null && (n.raw instanceof Uint8Array || Buffer.isBuffer(n.raw))) return n.raw.byteLength;
1207
+ if (typeof n.getRaw == "function") {
1208
+ let e = n.getRaw(), i = e instanceof Promise ? await e : e, a = Buffer.isBuffer(i) ? i : Buffer.from(i);
1209
+ return r[t] = a, a.length;
1210
+ }
1211
+ if (n.filename != null) {
1212
+ let e = await Er();
1213
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
1214
+ return (await e.stat(n.filename)).size;
1215
+ }
1216
+ throw Error("Cannot get raw bytes from DataItem");
1217
+ }, o = 4, s = [];
1218
+ for (let n = 0; n < t; n++) {
1219
+ let t = await i(e[n], n);
1220
+ s.push(t), o += 4 + t;
1221
+ }
1222
+ let c = Buffer.alloc(o), l = 0;
1223
+ c.writeUInt32BE(t, l), l += 4;
1224
+ for (let n = 0; n < t; n++) {
1225
+ let t = s[n], i = r[n];
1226
+ if (i) {
1227
+ c.writeUInt32BE(t, l), l += 4, i.copy(c, l), l += t;
1228
+ continue;
1229
+ }
1230
+ let a = e[n];
1231
+ if (a.raw != null && (a.raw instanceof Uint8Array || Buffer.isBuffer(a.raw))) {
1232
+ c.writeUInt32BE(t, l), l += 4, c.set(a.raw, l), l += t;
1233
+ continue;
1234
+ }
1235
+ if (a.filename != null) {
1236
+ let e = await Er();
1237
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
1238
+ let t = await e.readFile(a.filename);
1239
+ c.writeUInt32BE(t.length, l), l += 4, t.copy(c, l), l += t.length;
1240
+ continue;
1241
+ }
1242
+ throw Error("Cannot get raw bytes from DataItem");
1243
+ }
1244
+ let u = new AbortController(), d = setTimeout(() => u.abort(), Cr), f;
1245
+ try {
1246
+ f = await fetch(a, {
1247
+ method: "POST",
1248
+ headers: { "Content-Type": "application/octet-stream" },
1249
+ body: c,
1250
+ signal: u.signal
1251
+ });
1252
+ } catch (e) {
1253
+ throw clearTimeout(d), e instanceof Error && e.name === "AbortError" ? Error(`Arweave batch upload timed out after ${Cr / 1e3}s (upload API did not respond). Check uploadApiBaseUrl and network.`) : e;
1254
+ }
1255
+ if (clearTimeout(d), !f.ok) throw Error(`Batch upload failed: ${f.status}`);
1256
+ let p = await f.json().catch(() => ({})), m = typeof p.failed == "number" ? p.failed : 0;
1257
+ if (m > 0) {
1258
+ let e = p.total ?? "?", t = p.succeeded ?? 0;
1259
+ throw Error(`Arweave batch upload failed: ${m} of ${e} item(s) failed (${t} succeeded)`);
1260
+ }
1261
+ })().then(() => e({
1262
+ type: "uploadComplete",
1263
+ result: "done"
1264
+ })).catch((t) => e({
1265
+ type: "uploadError",
1266
+ error: t
1267
+ }));
1268
+ }), Or = /* @__PURE__ */ e({
1269
+ ExternalWalletsForDeploy: () => Hr,
1270
+ appMetadata: () => Gr,
1271
+ deployManagedAccountViaFactory: () => Wr,
1272
+ deploySmartWalletContract: () => Ur,
1273
+ getConnectedAccount: () => qr,
1274
+ getConnectedManagedAccountAddress: () => Kr,
1275
+ getConnectedModularAccount: () => Jr,
1276
+ getManagedAccountWallet: () => Qr,
1277
+ getModularAccountWallet: () => ei,
1278
+ getSharedPublishInAppWalletStorage: () => Mr,
1279
+ getSmartWalletAddressForAdmin: () => Rr,
1280
+ getWalletsForConnectButton: () => ti,
1281
+ isSmartWalletDeployed: () => zr,
1282
+ pollSmartWalletDeployed: () => Br,
1283
+ resolveSmartWalletForPublish: () => Vr,
1284
+ syncPublishInAppAuthToken: () => Nr,
1285
+ useActiveSmartWalletContract: () => Lr,
1286
+ useLocalWalletAccount: () => Ir,
1287
+ wallets: () => Fr
1288
+ }), kr = L("permaPress:helpers:thirdweb"), Ar = "seedProtocol:inAppPublish:", jr = null;
1289
+ function Mr() {
1290
+ return jr ||= {
1291
+ getItem: async (e) => typeof window > "u" ? null : localStorage.getItem(Ar + e),
1292
+ setItem: async (e, t) => {
1293
+ typeof window > "u" || localStorage.setItem(Ar + e, t);
1294
+ },
1295
+ removeItem: async (e) => {
1296
+ typeof window > "u" || localStorage.removeItem(Ar + e);
1297
+ }
1298
+ }, jr;
1299
+ }
1300
+ function Nr() {
1301
+ if (typeof window > "u") return {
1302
+ syncedBareToPrefixed: !1,
1303
+ syncedPrefixedToBare: !1
1304
+ };
1305
+ let { thirdwebClientId: e } = w();
1306
+ if (!e) return {
1307
+ syncedBareToPrefixed: !1,
1308
+ syncedPrefixedToBare: !1
1309
+ };
1310
+ try {
1311
+ let t = `walletToken-${e}`, n = `${Ar}${t}`, r = localStorage.getItem(t), i = localStorage.getItem(n), a = !1, o = !1;
1312
+ return r && !i && (localStorage.setItem(n, r), a = !0), i && !r && (localStorage.setItem(t, i), o = !0), i && r && r !== i && (localStorage.setItem(t, i), o = !0), {
1313
+ syncedBareToPrefixed: a,
1314
+ syncedPrefixedToBare: o
1315
+ };
1316
+ } catch {
1317
+ return {
1318
+ syncedBareToPrefixed: !1,
1319
+ syncedPrefixedToBare: !1
1320
+ };
1321
+ }
1322
+ }
1323
+ async function Pr(e = b()) {
1324
+ Nr();
1325
+ let t = Qr();
1326
+ return await t.autoConnect({
1327
+ client: O(),
1328
+ chain: e
1329
+ }), t;
1330
+ }
1331
+ var Fr = [Vt("io.metamask")], Ir = () => {
1332
+ let [e, t] = kt(null);
1333
+ return Vt("io.metamask"), Ot(!1), Dt(() => {}, []), e;
1334
+ }, Lr = () => {
1335
+ let e = Ut(), [t, n] = kt(null);
1336
+ return Dt(() => {
1337
+ e && e.address && n(lt({
1338
+ client: O(),
1339
+ chain: b(),
1340
+ address: e.address
1341
+ }));
1342
+ }, [e]), t;
1343
+ };
1344
+ async function Rr(e, t = "0x") {
1345
+ return _(e, t);
1346
+ }
1347
+ async function zr(e) {
1348
+ return ee(e);
1349
+ }
1350
+ async function Br(e, t, n) {
1351
+ return fe(e, t, n);
1352
+ }
1353
+ async function Vr(e) {
1354
+ if (!e) return { needsDeploy: !0 };
1355
+ if (await zr(e.address)) return {
1356
+ address: e.address,
1357
+ account: e
1358
+ };
1359
+ let t = await Rr(e.address);
1360
+ return await zr(t) ? {
1361
+ address: t,
1362
+ account: e
1363
+ } : { needsDeploy: !0 };
1364
+ }
1365
+ var Hr = [Vt("io.metamask"), Vt("me.rainbow")], Ur = async (e) => {
1366
+ let t = lt({
1367
+ client: O(),
1368
+ chain: b(),
1369
+ address: e.address
1370
+ }), n = await ct({
1371
+ smartAccount: e,
1372
+ chain: b(),
1373
+ client: O(),
1374
+ accountContract: t
1375
+ });
1376
+ return kr("deploySmartAccount result:", n), n;
1377
+ };
1378
+ async function Wr(e) {
1379
+ let { asThirdwebPublishWallet: t } = await import("./chainConfig-CA1Hrrjg.js").then((e) => e.g), n = t(e.signingAccount), r = Se(e.adminAddress, e.data ?? "0x");
1380
+ await n.txSender.sendTransaction(r);
1381
+ }
1382
+ var Gr = {
1383
+ name: "Seed Protocol",
1384
+ description: "Seed Protocol",
1385
+ url: "https://seedprotocol.io"
1386
+ };
1387
+ async function Kr(e = b()) {
1388
+ let t = (await Pr(e)).getAccount();
1389
+ if (!t) throw Error("Failed to get managed account");
1390
+ return t.address;
1391
+ }
1392
+ async function qr() {
1393
+ try {
1394
+ let e = ei();
1395
+ return await e.autoConnect({
1396
+ client: O(),
1397
+ chain: b()
1398
+ }), e.getAccount() ?? null;
1399
+ } catch {
1400
+ return null;
1401
+ }
1402
+ }
1403
+ async function Jr() {
1404
+ return qr();
1405
+ }
1406
+ function Yr(e) {
1407
+ let t = b(e).id, n = e.managedAccountFactoryAddress ?? oe[t];
1408
+ if (!n) throw Error(`@seedprotocol/publish: no ManagedAccount factory is known for chain ${t}. Pass managedAccountFactoryAddress in publish config, or use the EOA / direct EAS path.`);
1409
+ return n;
1410
+ }
1411
+ var Xr = [
1412
+ "farcaster",
1413
+ "email",
1414
+ "passkey",
1415
+ "phone"
1416
+ ], Zr = null, Qr = (e) => {
1417
+ let t = e ?? S(), n = b(t ?? void 0), r = t ? Yr(t) : te(), { bundlerUrl: i, sponsorGas: a } = ve(t);
1418
+ if (!i && be(n)) throw Error(`@seedprotocol/publish: chain ${n.id} is local, so Thirdweb's hosted bundler cannot reach it. Set PublishConfig.thirdweb.bundlerUrl to the chain's bundler (seedTwinConfig does this for the twin).`);
1419
+ let o = [
1420
+ n.id,
1421
+ n.rpc,
1422
+ r,
1423
+ i ?? "",
1424
+ a
1425
+ ].join("|").toLowerCase();
1426
+ return Zr?.key !== o && (Zr = {
1427
+ key: o,
1428
+ wallet: Ht({
1429
+ storage: Mr(),
1430
+ auth: { options: [...Xr] },
1431
+ executionMode: {
1432
+ mode: "EIP4337",
1433
+ smartAccount: {
1434
+ chain: n,
1435
+ factoryAddress: r,
1436
+ sponsorGas: a,
1437
+ ...i ? { overrides: { bundlerUrl: i } } : {}
1438
+ }
1439
+ }
1440
+ })
1441
+ }), Zr.wallet;
1442
+ }, $r = null, ei = (e) => {
1443
+ let t = e ?? S(), { modularWalletMode: n, sponsorGas: r } = ve(t);
1444
+ if (n === "EIP7702") {
1445
+ let e = b(t ?? void 0);
1446
+ if (be(e)) throw Error(`@seedprotocol/publish: chain ${e.id} is local, and Thirdweb's EIP-7702 mode needs its hosted bundler, which cannot reach it. Set PublishConfig.thirdweb.modularWalletMode to 'EOA' and fund the in-app EOA (seedTwinConfig does this for the twin).`);
1447
+ }
1448
+ let i = `${n}|${r}`;
1449
+ return $r?.key !== i && ($r = {
1450
+ key: i,
1451
+ wallet: Ht({
1452
+ storage: Mr(),
1453
+ auth: { options: [...Xr] },
1454
+ executionMode: n === "EOA" ? { mode: "EOA" } : {
1455
+ mode: "EIP7702",
1456
+ sponsorGas: r
1457
+ }
1458
+ })
1459
+ }), $r.wallet;
1460
+ }, ti = (e) => {
1461
+ let t = e ?? S() ?? void 0;
1462
+ return t?.useModularExecutor ? [ei(t)] : [Qr(t)];
1463
+ }, ni = () => `The executor module could not be installed on your publishing account on ${E()}. Reconnect and try again, or contact support if this persists.`;
1464
+ async function ri(e, t, n) {
1465
+ let { modularAccountModuleContract: r } = n;
1466
+ if (!r || !await ee(e)) return;
1467
+ let i = await de(e);
1468
+ if (i) {
1469
+ await ii(e, i.executor, r);
1470
+ return;
1471
+ }
1472
+ let a = lt({
1473
+ client: O(),
1474
+ chain: b(),
1475
+ address: e
1476
+ });
1477
+ try {
1478
+ let e = await Wt({ contract: a }), n = r.toLowerCase();
1479
+ if (e.some((e) => e.implementation?.toLowerCase() === n)) return;
1480
+ let i = Gt({
1481
+ contract: a,
1482
+ moduleContract: r,
1483
+ data: rt([{ type: "address" }], [w().easContractAddress])
1484
+ }), o = await ut({
1485
+ transaction: i,
1486
+ account: t
1487
+ });
1488
+ await T(o.transactionHash);
1489
+ } catch (t) {
1490
+ if (we(t)) return;
1491
+ throw new D(ni(), "EXECUTOR_MODULE_NOT_INSTALLED", e, t);
1492
+ }
1493
+ }
1494
+ async function ii(e, t, n) {
1495
+ if (t.toLowerCase() !== n.trim().toLowerCase()) throw new D(`Your publishing account's Seed executor is ${t}, but publish config sets modularAccountModuleContract to ${n}. Point modularAccountModuleContract at the account's executor.`, "EXECUTOR_MODULE_NOT_INSTALLED", e);
1496
+ try {
1497
+ if (await _e(e, t)) return;
1498
+ let { getManagedAccountAdmin: n } = await import("./managedAccountAdmin-NXD66lP5.js").then((e) => e.n), r = await ae(await n(e)).txSender.sendTransaction(g(e));
1499
+ await T(r.transactionHash);
1500
+ } catch (t) {
1501
+ throw t instanceof D ? t : new D(ni(), "EXECUTOR_MODULE_NOT_INSTALLED", e, t);
1502
+ }
1503
+ }
1504
+ //#endregion
1505
+ //#region src/helpers/ensureManagedAccountReady.ts
1506
+ var ai = () => `Could not connect the managed publishing account on ${E()}. Reconnect with the same sign-in method and try again.`, oi = () => `Your publishing smart account is not deployed on ${E()} yet. Complete wallet setup, enable autoDeployManagedAccount in config if appropriate, then try again.`, si = () => `The managed account could not be confirmed on ${E()} after deployment. Wait a moment and retry, or check your network connection.`, ci = () => `Automatic deployment of the managed publishing account failed on ${E()}. Retry or deploy the account through your wallet provider.`;
1507
+ async function li() {
1508
+ let { useModularExecutor: e } = w();
1509
+ if (!e) return { kind: "skip" };
1510
+ let t;
1511
+ try {
1512
+ t = await Kr(b());
1513
+ } catch (e) {
1514
+ return {
1515
+ kind: "unavailable",
1516
+ cause: e
1517
+ };
1518
+ }
1519
+ return await zr(t) ? {
1520
+ kind: "ready",
1521
+ managedAddress: t
1522
+ } : {
1523
+ kind: "not_deployed",
1524
+ managedAddress: t
1525
+ };
1526
+ }
1527
+ async function ui() {
1528
+ Nr();
1529
+ let e = Qr();
1530
+ await e.autoConnect({
1531
+ client: O(),
1532
+ chain: b()
1533
+ });
1534
+ let t = e.getAccount();
1535
+ if (!t) throw new D(ai(), "MANAGED_ACCOUNT_UNAVAILABLE");
1536
+ return t;
1537
+ }
1538
+ var di = 9e4;
1539
+ async function fi(e) {
1540
+ let t;
1541
+ try {
1542
+ await Promise.race([Ur(e), new Promise((e, n) => {
1543
+ t = setTimeout(() => n(/* @__PURE__ */ Error(`Managed account deploy timed out after ${di / 1e3}s`)), di);
1544
+ })]);
1545
+ } finally {
1546
+ t != null && clearTimeout(t);
1547
+ }
1548
+ }
1549
+ async function pi(e) {
1550
+ let t = w(), n = await ui(), { fromThirdwebAccount: r } = await import("./chainConfig-CA1Hrrjg.js").then((e) => e.g), i = {
1551
+ managedAddress: e,
1552
+ managedSigningAccount: r(n)
1553
+ };
1554
+ try {
1555
+ if (t.deployManagedAccount) await t.deployManagedAccount(i);
1556
+ else {
1557
+ let e = await Jr();
1558
+ if (e) {
1559
+ let t = ei();
1560
+ await t.autoConnect({
1561
+ client: O(),
1562
+ chain: b()
1563
+ }), await Wr({
1564
+ adminAddress: t.getAdminAccount?.()?.address ?? e.address,
1565
+ signingAccount: e
1566
+ });
1567
+ } else await fi(n);
1568
+ }
1569
+ } catch (t) {
1570
+ if (await Br(e, /UserOp|user operation/i.test(Te(t)) ? 15 : 5)) return;
1571
+ throw new D(ci(), "MANAGED_ACCOUNT_NOT_DEPLOYED", e, t);
1572
+ }
1573
+ if (!await Br(e)) throw new D(si(), "MANAGED_ACCOUNT_NOT_DEPLOYED", e);
1574
+ }
1575
+ async function mi() {
1576
+ let e = w();
1577
+ if (!e.useModularExecutor) throw Error("runModularExecutorPublishPrep: useModularExecutor is false");
1578
+ let t = await li();
1579
+ if (t.kind === "unavailable") return {
1580
+ ok: !1,
1581
+ error: new D(ai(), "MANAGED_ACCOUNT_UNAVAILABLE", void 0, t.cause)
1582
+ };
1583
+ if (t.kind === "not_deployed") {
1584
+ if (e.autoDeployManagedAccount) {
1585
+ try {
1586
+ await pi(t.managedAddress);
1587
+ } catch (e) {
1588
+ return {
1589
+ ok: !1,
1590
+ error: Ce(e) ? e : new D(ci(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress, e)
1591
+ };
1592
+ }
1593
+ if (t = await li(), t.kind !== "ready") return {
1594
+ ok: !1,
1595
+ error: new D(si(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.kind === "not_deployed" ? t.managedAddress : void 0)
1596
+ };
1597
+ } else return {
1598
+ ok: !1,
1599
+ error: new D(oi(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress)
1600
+ };
1601
+ }
1602
+ if (t.kind === "ready") {
1603
+ if (e.modularAccountModuleContract) try {
1604
+ let n = await ui();
1605
+ await ri(t.managedAddress, n, e);
1606
+ } catch (e) {
1607
+ console.warn(`[@seedprotocol/publish] Executor module setup failed on ${E()}; publishing continues, but publish automation needs it.`, e);
1608
+ }
1609
+ return {
1610
+ ok: !0,
1611
+ managedAddress: t.managedAddress
1612
+ };
1613
+ }
1614
+ throw Error("runModularExecutorPublishPrep: unexpected readiness state");
1615
+ }
1616
+ //#endregion
1617
+ //#region src/helpers/executorModuleReadiness.ts
1618
+ var hi = "This ManagedAccount predates the Seed executor router extension, so the Seed executor cannot act for it and publish automation is not available for this account.", gi = "The Seed executor is not installed for this ManagedAccount, so automation session keys cannot publish through it. The account admin installs it (installSeedExecutor), which enrollPublishAutomation does.", _i = "The Seed executor module is configured with a different EAS contract for this ManagedAccount than publish config. Automation session keys cannot change it.", vi = "Could not read the Seed executor module state for this ManagedAccount.";
1619
+ function yi() {
1620
+ let e = w().modularAccountModuleContract?.trim();
1621
+ if (!e || !/^0x[0-9a-fA-F]{40}$/.test(e)) throw Error("@seedprotocol/publish: publish automation requires PublishConfig.modularAccountModuleContract (executor module).");
1622
+ return e;
1623
+ }
1624
+ async function bi(e) {
1625
+ return await de(e) === null;
1626
+ }
1627
+ async function xi(e) {
1628
+ let t = yi(), n = e, r, i;
1629
+ try {
1630
+ r = await v(t, n), i = r ? await s(t, n) : st;
1631
+ } catch (t) {
1632
+ throw new D(vi, "AUTOMATION_UNSUPPORTED_ACCOUNT", e, t);
1633
+ }
1634
+ if (!r) {
1635
+ let t = await bi(n) ? hi : gi;
1636
+ throw new D(t, "AUTOMATION_UNSUPPORTED_ACCOUNT", e);
1637
+ }
1638
+ let a = w().easContractAddress?.toLowerCase();
1639
+ if (a && i.toLowerCase() !== a) throw new D(_i, "AUTOMATION_UNSUPPORTED_ACCOUNT", e);
1640
+ }
1641
+ function Si(e) {
1642
+ let t = e instanceof et ? `${e.shortMessage} ${e.details} ${e.message}` : String(e);
1643
+ return /insufficient funds|insufficient balance/i.test(t);
1644
+ }
1645
+ async function Ci(e) {
1646
+ let { managedAddress: t, tx: n, action: r, code: i = "AUTOMATION_PREFLIGHT_FAILED", requireSimulation: a = !0 } = e, o = (e) => se().call({
1647
+ account: t,
1648
+ to: n.to,
1649
+ data: n.data,
1650
+ value: n.value,
1651
+ ...e ? { stateOverride: [{
1652
+ address: t,
1653
+ balance: it("1000")
1654
+ }] } : {}
1655
+ });
1656
+ try {
1657
+ try {
1658
+ await o(!1);
1659
+ } catch (e) {
1660
+ if (!Si(e)) throw e;
1661
+ await o(!0);
1662
+ }
1663
+ } catch (e) {
1664
+ let n = Xt(e);
1665
+ if (!n && !a) return;
1666
+ let o = n ? Qt(Yt(e)) : "could not be simulated";
1667
+ throw new D(`Simulated ${r} from ${t} ${o}; nothing was sent.`, i, t, e);
1668
+ }
1669
+ }
1670
+ //#endregion
1671
+ //#region src/helpers/resolvePublishWallet.ts
1672
+ function wi(e) {
1673
+ if (m(e.wallet)) return e.wallet;
1674
+ if (m(e.account)) return e.account;
1675
+ let t = ce();
1676
+ if (t) return t;
1677
+ throw Error("@seedprotocol/publish: no PublishWallet available. Pass fromEthersWallet / fromEip1193Provider / fromThirdwebAccount, or call setPublishWallet / useSeedWallet.");
1678
+ }
1679
+ //#endregion
1680
+ //#region src/services/publish/actors/persistSeedUid.ts
1681
+ var Ti = L("seedProtocol:services:publish:actors:persistSeedUid"), Ei = "0x" + "0".repeat(64), Di = 15e3;
1682
+ function Oi(e, t) {
1683
+ let n = e.seedLocalId, r = n ? t.find((e) => e?.localId === n) : void 0, i = r?.seedUid && r.seedUid !== Ei ? r.seedUid : t[0]?.seedUid;
1684
+ i && i !== Ei && (e.seedUid = i);
1685
+ }
1686
+ async function ki(e, t, n) {
1687
+ let r = e.persistSeedUid;
1688
+ if (typeof r != "function") return;
1689
+ let i = new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("persistSeedUid timed out")), Di));
1690
+ try {
1691
+ await Promise.race([r.call(e, t, n), i]);
1692
+ } catch (e) {
1693
+ Ti("persistSeedUid failed (attestations already on-chain):", e);
1694
+ }
1695
+ }
1696
+ //#endregion
1697
+ //#region src/services/publish/helpers/verifyArweaveTransactionsExist.ts
1698
+ async function Ai(e) {
1699
+ if (e.length === 0) return;
1700
+ let { arweaveUploadVerificationBaseUrl: t } = w(), n = await Promise.all(e.map((e) => Re(t, e)));
1701
+ for (let t = 0; t < e.length; t++) {
1702
+ let r = e[t], i = n[t];
1703
+ if (i) {
1704
+ if (i.status === 404) throw Error(`Arweave transaction ${r} not found. Upload may have failed. Delete this publish record and try again.`);
1705
+ if (i.status !== 200) {
1706
+ let e = i.status === 504 ? "request timed out (upload service did not respond in time)" : `status: ${i.status}`;
1707
+ throw Error(`Arweave transaction ${r} is not yet available from the upload service (${e}). Wait and retry.`);
1708
+ }
1709
+ }
1710
+ }
1711
+ }
1712
+ //#endregion
1713
+ //#region src/services/publish/actors/seedUidHelpers.ts
1714
+ function K(e) {
1715
+ return e == null || e === "" ? W : ("0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(64, "0").slice(-64)).toLowerCase();
1716
+ }
1717
+ function ji(e, t, n) {
1718
+ if (!t || !e.logs?.length) return;
1719
+ let r = K(t);
1720
+ if (r === W) return;
1721
+ let i = n ? C : ye;
1722
+ try {
1723
+ let t = at({
1724
+ abi: i,
1725
+ eventName: "CreatedAttestation",
1726
+ logs: e.logs,
1727
+ strict: !1
1728
+ });
1729
+ for (let e of t) {
1730
+ let t = e.args?.result;
1731
+ if (t?.attestationUid && K(t.schemaUid) === r) {
1732
+ let e = t.attestationUid;
1733
+ return e && K(e) !== W ? e : void 0;
1734
+ }
1735
+ }
1736
+ } catch {}
1737
+ }
1738
+ function Mi(e, t, n, r) {
1739
+ let i = t.toLowerCase(), a = e.logs?.filter((e) => e.address && e.address.toLowerCase() === i);
1740
+ if (!a?.length) return {};
1741
+ try {
1742
+ if (r) {
1743
+ let e = at({
1744
+ abi: C,
1745
+ eventName: "SeedPublished",
1746
+ logs: a,
1747
+ strict: !1
1748
+ })[0];
1749
+ if (!e) return {};
1750
+ let t = e.args;
1751
+ return {
1752
+ seedUid: t?.seedUid && K(t.seedUid) !== W ? t.seedUid : void 0,
1753
+ versionUid: t?.versionUid && K(t.versionUid) !== W ? t.versionUid : void 0
1754
+ };
1755
+ }
1756
+ let e = at({
1757
+ abi: ye,
1758
+ eventName: "SeedPublished",
1759
+ logs: a,
1760
+ strict: !1
1761
+ })[0];
1762
+ if (!e) return {};
1763
+ let t = e.args?.returnedDataFromEAS;
1764
+ if (!t || t === "0x") return {};
1765
+ let i = tt([{ type: "bytes32[]" }], t)[0];
1766
+ if (!i?.length) return {};
1767
+ let o = n, s = i[o], c = i[o + 1];
1768
+ return {
1769
+ seedUid: s && s !== W ? s : i.length === 1 && i[0] && i[0] !== W ? i[0] : void 0,
1770
+ versionUid: c && c !== W ? c : void 0
1771
+ };
1772
+ } catch {
1773
+ return {};
1774
+ }
1775
+ }
1776
+ function Ni(e, t, n, r) {
1777
+ return Mi(e, t, n, r).seedUid;
1778
+ }
1779
+ function Pi(e, t, n) {
1780
+ if (!t || !e.logs?.length) return;
1781
+ let r = K(t);
1782
+ if (r === W) return;
1783
+ let i = n ? C : ye;
1784
+ try {
1785
+ let t = at({
1786
+ abi: i,
1787
+ eventName: "CreatedAttestation",
1788
+ logs: e.logs,
1789
+ strict: !1
1790
+ });
1791
+ for (let e of t) {
1792
+ let t = e.args?.result;
1793
+ if (t?.attestationUid && K(t.schemaUid) === r) {
1794
+ let e = t.attestationUid;
1795
+ return e && K(e) !== W ? e : void 0;
1796
+ }
1797
+ }
1798
+ } catch {}
1799
+ }
1800
+ function Fi(e, t) {
1801
+ if (!e.logs?.length) return [];
1802
+ let n = t ? C : ye;
1803
+ try {
1804
+ let t = at({
1805
+ abi: n,
1806
+ eventName: "CreatedAttestation",
1807
+ logs: e.logs,
1808
+ strict: !1
1809
+ }), r = [];
1810
+ for (let e of t) {
1811
+ let t = e.args?.result;
1812
+ if (!t?.attestationUid) continue;
1813
+ let n = t.attestationUid;
1814
+ if (!n || K(n) === W) continue;
1815
+ let i = t.schemaUid;
1816
+ i && r.push({
1817
+ schemaUid: i,
1818
+ attestationUid: n
1819
+ });
1820
+ }
1821
+ return r;
1822
+ } catch {
1823
+ return [];
1824
+ }
1825
+ }
1826
+ function Ii(e, t) {
1827
+ let n = t.toLowerCase(), r = e.logs?.filter((e) => e.address && e.address.toLowerCase() === n);
1828
+ if (!r?.length) return [];
1829
+ try {
1830
+ let e = at({
1831
+ abi: ye,
1832
+ eventName: "SeedPublished",
1833
+ logs: r,
1834
+ strict: !1
1835
+ })[0];
1836
+ if (!e) return [];
1837
+ let t = e.args?.returnedDataFromEAS;
1838
+ return !t || t === "0x" ? [] : tt([{ type: "bytes32[]" }], t)[0] ?? [];
1839
+ } catch {
1840
+ return [];
1841
+ }
1842
+ }
1843
+ function Li(e, t, n) {
1844
+ if (!n.length) return [];
1845
+ let r = Ii(e, t), i = n.length;
1846
+ if (r.length < i) return [];
1847
+ let a = [];
1848
+ for (let e = 0; e < i; e++) {
1849
+ let t = r[e], i = n[e]?.schema;
1850
+ t && K(t) !== W && i && a.push({
1851
+ schemaUid: i,
1852
+ attestationUid: t
1853
+ });
1854
+ }
1855
+ return a;
1856
+ }
1857
+ function Ri(e) {
1858
+ let t = Fi(e.receipt, e.useModularExecutor);
1859
+ if (t.length) return t;
1860
+ let n = i(e.receipt, e.easContractAddress);
1861
+ return n.length ? n.map((e) => ({
1862
+ schemaUid: e.schemaUid,
1863
+ attestationUid: e.uid
1864
+ })) : e.useModularExecutor ? [] : Li(e.receipt, e.contractAddressForEvents, e.listOfAttestations ?? []);
1865
+ }
1866
+ //#endregion
1867
+ //#region src/services/publish/helpers/receiptAttestationMs.ts
1868
+ async function q(e) {
1869
+ let t = e?.blockNumber;
1870
+ return t == null ? Date.now() : await ge(t) ?? Date.now();
1871
+ }
1872
+ //#endregion
1873
+ //#region src/services/publish/actors/publishRequestNormalize.ts
1874
+ var zi = 64, J = (e) => {
1875
+ if (e == null) return "0x" + "0".repeat(zi);
1876
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(zi, "0").slice(-64);
1877
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1878
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1879
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(zi, "0").slice(-64);
1880
+ }
1881
+ return "0x" + "0".repeat(zi);
1882
+ }, Bi = (e) => {
1883
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1884
+ if (typeof e == "string") {
1885
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1886
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1887
+ }
1888
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1889
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1890
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1891
+ }
1892
+ return "0x";
1893
+ };
1894
+ function Vi(e) {
1895
+ let t = new Set(e.map((e) => e?.localId).filter((e) => !!e));
1896
+ return e.some((e) => (e?.listOfAttestations ?? []).some((e) => {
1897
+ let n = e;
1898
+ return n._unresolvedValue && t.has(n._unresolvedValue) ? !0 : Array.isArray(n._rawListIdsForResolve) ? n._rawListIdsForResolve.some((e) => e && t.has(String(e).trim())) : !1;
1899
+ }));
1900
+ }
1901
+ function Hi(e, t) {
1902
+ return (e ?? []).filter((e) => e.publishLocalId && t.has(e.publishLocalId));
1903
+ }
1904
+ var Ui = {
1905
+ recipient: Pt,
1906
+ expirationTime: BigInt(0),
1907
+ revocable: !0,
1908
+ refUID: W,
1909
+ data: W,
1910
+ value: BigInt(0)
1911
+ };
1912
+ function Wi(e) {
1913
+ let t = (e?.listOfAttestations ?? []).map((e) => {
1914
+ let t = Array.isArray(e?.data) ? e.data : [];
1915
+ return {
1916
+ schema: J(e?.schema),
1917
+ data: t.map((e) => ({
1918
+ ...e,
1919
+ refUID: J(e?.refUID),
1920
+ data: Bi(e?.data),
1921
+ expirationTime: e?.expirationTime == null ? BigInt(0) : BigInt(e.expirationTime),
1922
+ value: e?.value == null ? BigInt(0) : BigInt(e.value)
1923
+ })),
1924
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
1925
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
1926
+ };
1927
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
1928
+ ...e,
1929
+ propertySchemaUid: J(e?.propertySchemaUid)
1930
+ }));
1931
+ return {
1932
+ ...e,
1933
+ seedUid: J(e?.seedUid),
1934
+ seedSchemaUid: J(e?.seedSchemaUid),
1935
+ versionUid: J(e?.versionUid),
1936
+ versionSchemaUid: J(e?.versionSchemaUid),
1937
+ listOfAttestations: t,
1938
+ propertiesToUpdate: n
1939
+ };
1940
+ }
1941
+ function Gi(e, t) {
1942
+ for (let n of e) for (let e of n?.propertiesToUpdate ?? []) {
1943
+ let n = e?.publishLocalId, r = J(e?.propertySchemaUid);
1944
+ if (!n || !r) continue;
1945
+ let i = t.get(n);
1946
+ if (!i?.listOfAttestations) continue;
1947
+ let a = i.listOfAttestations.find((e) => J(e?.schema)?.toLowerCase() === r?.toLowerCase());
1948
+ a && (!Array.isArray(a.data) || a.data.length === 0) && (a.data = [{
1949
+ ...Ui,
1950
+ refUID: W
1951
+ }]);
1952
+ }
1953
+ }
1954
+ //#endregion
1955
+ //#region src/services/arweaveL1Finalize/enqueue.ts
1956
+ var Ki = "pending_l1";
1957
+ async function qi(e) {
1958
+ let { useArweaveBundler: t } = w();
1959
+ if (!t) return;
1960
+ let n = e.arweaveTransactions ?? [], r = e.publishUploads ?? [];
1961
+ if (n.length === 0 || n.length !== r.length) return;
1962
+ let i = k.getAppDb();
1963
+ if (!i) return;
1964
+ let a = Date.now();
1965
+ for (let e = 0; e < n.length; e++) {
1966
+ let t = n[e], o = r[e];
1967
+ if (!o) continue;
1968
+ let s = t.transaction?.id;
1969
+ if (s && typeof s == "string") try {
1970
+ await i.insert(je).values({
1971
+ seedLocalId: o.seedLocalId,
1972
+ dataItemId: s,
1973
+ versionLocalId: o.versionLocalId ?? null,
1974
+ itemPropertyName: o.itemPropertyName ?? null,
1975
+ phase: Ki,
1976
+ createdAt: a,
1977
+ updatedAt: a
1978
+ }).onConflictDoNothing();
1979
+ } catch {}
1980
+ }
1981
+ }
1982
+ //#endregion
1983
+ //#region src/helpers/ensureManagedAccountEasConfigured.ts
1984
+ var Ji = () => `Could not verify or set the EAS contract address on your publishing account on ${E()}.`, Yi = "ManagedAccount EAS pointer does not match publish config. Configure EAS with the user’s ManagedAccount wallet before automation publish (session keys cannot call setEas).", Xi = (e) => `Your publishing account's Seed extension uses EAS ${e}, but publish config sets easContractAddress to a different contract. The extension's EAS is fixed at deployment; fix easContractAddress.`;
1985
+ function Zi(e) {
1986
+ return e.toLowerCase();
1987
+ }
1988
+ function Qi(e) {
1989
+ let { easContractAddress: t } = w(), n = Zi(t);
1990
+ if (!n || n === Zi(st)) throw new D("Publish config is missing a valid easContractAddress.", "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
1991
+ return n;
1992
+ }
1993
+ async function $i(e) {
1994
+ try {
1995
+ let t = await y(e);
1996
+ return Zi(typeof t == "string" ? t : String(t));
1997
+ } catch (t) {
1998
+ throw new D(Ji(), "MANAGED_ACCOUNT_SET_EAS_FAILED", e, t);
1999
+ }
2000
+ }
2001
+ async function ea(e) {
2002
+ let t = Qi(e);
2003
+ if (await $i(e) !== t) throw new D(Yi, "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2004
+ }
2005
+ async function ta(e, t) {
2006
+ let r = Qi(e), i = await $i(e);
2007
+ if (i !== r) {
2008
+ if (i !== Zi(st)) throw new D(Xi(i), "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2009
+ try {
2010
+ let r = typeof t == "function" ? await t() : t, i = m(r) ? r.txSender : n(r) ? r : (() => {
2011
+ throw Error("@seedprotocol/publish: ensureManagedAccountEasConfigured requires PublishWallet or SeedTxSender");
2012
+ })(), { easContractAddress: a } = w(), o = me(e, a), s = await i.sendTransaction(o);
2013
+ await T(s.transactionHash);
2014
+ } catch (t) {
2015
+ throw new D(Ji(), "MANAGED_ACCOUNT_SET_EAS_FAILED", e, t);
2016
+ }
2017
+ }
2018
+ }
2019
+ //#endregion
2020
+ //#region src/services/publish/actors/createAttestations.ts
2021
+ var na = L("seedProtocol:services:publish:actors");
2022
+ function ra(e) {
2023
+ return !!e && /^0x[0-9a-fA-F]{40}$/.test(e.trim());
2024
+ }
2025
+ function ia(e) {
2026
+ let { useModularExecutor: t, publisherAddress: n, modularAccountModuleContract: r, managedAddress: i, routeToExecutorModule: a } = e;
2027
+ if (t) {
2028
+ if (!i) throw Error("resolvePublishRouting: managedAddress is required when useModularExecutor is true");
2029
+ let e = r?.trim();
2030
+ if (a) {
2031
+ if (!ra(e)) throw Error("resolvePublishRouting: modularAccountModuleContract is required when routeToExecutorModule is true");
2032
+ return {
2033
+ txTargetAddress: e,
2034
+ contractAddressForEvents: e
2035
+ };
2036
+ }
2037
+ return {
2038
+ txTargetAddress: i,
2039
+ contractAddressForEvents: e || i
2040
+ };
2041
+ }
2042
+ return {
2043
+ txTargetAddress: n,
2044
+ contractAddressForEvents: n
2045
+ };
2046
+ }
2047
+ async function aa(e) {
2048
+ let { receipt: t, seedLocalId: n, versionSchemaUid: r, contractAddressForEvents: i, listOfAttestationsCount: a, useModularExecutor: o, publisherAddress: s } = e;
2049
+ if (!n) return;
2050
+ let c = Pi(t, r, o) ?? Mi(t, i, a, o).versionUid, l = c ? J(c) : void 0;
2051
+ if (!l || l === W) return;
2052
+ let u = await q(t);
2053
+ await Qe({
2054
+ seedLocalId: n,
2055
+ versionUid: l,
2056
+ publisher: s,
2057
+ attestationCreatedAt: u
2058
+ });
2059
+ }
2060
+ function oa(e, t) {
2061
+ return !e || !t ? !1 : J(e).toLowerCase() === J(t).toLowerCase();
2062
+ }
2063
+ function sa(e, t, n) {
2064
+ return !n || t >= e.length ? t : oa(e[t]?.schemaUid, n) ? t + 1 : t;
2065
+ }
2066
+ async function ca(e) {
2067
+ let { receipt: t, normalizedRequests: n, useModularExecutor: r, contractAddressForEvents: i } = e, { easContractAddress: a } = w(), o = Ri({
2068
+ receipt: t,
2069
+ useModularExecutor: r,
2070
+ easContractAddress: a,
2071
+ contractAddressForEvents: i,
2072
+ listOfAttestations: n.flatMap((e) => e.listOfAttestations ?? [])
2073
+ });
2074
+ if (!o.length) {
2075
+ na("persistPropertyMetadataUidsFromContractReceipt: no property attestation pairs");
2076
+ return;
2077
+ }
2078
+ let s = await q(t), c = 0;
2079
+ for (let e of n) {
2080
+ let n = e.listOfAttestations ?? [];
2081
+ if ((!e.seedUid || J(e.seedUid) === W) && (c = sa(o, c, e.seedSchemaUid)), c = sa(o, c, e.versionSchemaUid), !n.length) continue;
2082
+ let a = n.length, l = o.slice(c, c + a);
2083
+ if (c += a, !l.length) continue;
2084
+ let u = Math.min(l.length, a), d = e.versionUid && J(e.versionUid) !== W ? J(e.versionUid) : void 0;
2085
+ d ||= Pi(t, e.versionSchemaUid, r) ?? Mi(t, i, a, r).versionUid, await Ae({
2086
+ seedLocalId: e.localId,
2087
+ attestationCreatedAtMs: s ?? null,
2088
+ versionUid: d && J(d) !== W ? J(d) : null,
2089
+ pairs: l.slice(0, u).map((e, t) => ({
2090
+ schemaUid: e.schemaUid,
2091
+ attestationUid: e.attestationUid,
2092
+ propertyName: typeof n[t]?._propertyName == "string" && n[t]._propertyName !== "" ? n[t]._propertyName : void 0
2093
+ }))
2094
+ });
2095
+ }
2096
+ }
2097
+ var la = I(async ({ input: { context: e } }) => {
2098
+ let { address: t, account: n, wallet: r } = e, i = e.arweaveTransactions ?? [], o = e.publishUploads ?? [], { item: s } = e, { modularAccountModuleContract: c, useModularExecutor: l } = w();
2099
+ if (!t || typeof t != "string" || !t.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
2100
+ if (!r && !n) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
2101
+ if (!l && !await ee(t)) throw Error("EOA publishing must use the direct EAS path (multiPublish requires a deployed publisher contract). If you see this, attestation routing is misconfigured.");
2102
+ if (!s?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
2103
+ if (typeof s.getPublishUploads != "function" && (s = await bn(s.seedLocalId)), i.length !== o.length) throw Error("Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.");
2104
+ let u = ia({
2105
+ useModularExecutor: !1,
2106
+ publisherAddress: t
2107
+ }), d = wi(e), f = !1;
2108
+ await vn(s, d, { managedAddress: t });
2109
+ let p = i.map((e, t) => {
2110
+ let n = e.transaction?.id;
2111
+ if (!n || typeof n != "string") throw Error("Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.");
2112
+ let r = o[t];
2113
+ if (!r) throw Error("Publish upload index mismatch");
2114
+ return {
2115
+ ...r,
2116
+ txId: n
2117
+ };
2118
+ });
2119
+ await Ai(p.map((e) => e.txId));
2120
+ let m = await s.getPublishPayload(p, { publishMode: e.publishMode ?? "patch" }), g = Array.isArray(m) ? m : [m];
2121
+ if (l) {
2122
+ let e = d?.signer?.address, n = !1;
2123
+ if (t && e) {
2124
+ let { isAutomationSessionActive: r } = await import("./ensureAutomationSessionKey-Bw74ZSGI.js").then((e) => e.n);
2125
+ n = await r(t, e);
2126
+ }
2127
+ if (n) {
2128
+ let e = c?.trim();
2129
+ if (!ra(e)) throw Error("@seedprotocol/publish: automation publish requires PublishConfig.modularAccountModuleContract (executor module). Session keys are module-only and cannot call the ManagedAccount directly.");
2130
+ u = ia({
2131
+ useModularExecutor: l,
2132
+ publisherAddress: t,
2133
+ modularAccountModuleContract: e,
2134
+ managedAddress: t,
2135
+ routeToExecutorModule: !0
2136
+ }), f = !0, await xi(t);
2137
+ } else {
2138
+ let e = await mi();
2139
+ if (!e.ok) throw e.error;
2140
+ u = ia({
2141
+ useModularExecutor: l,
2142
+ publisherAddress: t,
2143
+ modularAccountModuleContract: c,
2144
+ managedAddress: e.managedAddress
2145
+ });
2146
+ let { ensureModularPublishBootstrap: n } = await import("./ensureModularPublishBootstrap-Bsw1xSCt.js").then((e) => e.n), { fromThirdwebAccount: r } = await import("./chainConfig-CA1Hrrjg.js").then((e) => e.g);
2147
+ d = r(await n(e.managedAddress));
2148
+ }
2149
+ } else await ta(t, d);
2150
+ let _ = async (e) => {
2151
+ let n = u.txTargetAddress, r = f ? h(n, e, 5000000n) : a(n, e, 5000000n);
2152
+ await Ci(f ? {
2153
+ managedAddress: t,
2154
+ tx: r,
2155
+ action: "multiPublish via the executor module"
2156
+ } : {
2157
+ managedAddress: d.txSender.address,
2158
+ tx: r,
2159
+ action: "multiPublish",
2160
+ code: "PUBLISH_PREFLIGHT_FAILED",
2161
+ requireSimulation: !1
2162
+ });
2163
+ try {
2164
+ return await d.txSender.sendTransaction(r);
2165
+ } catch (e) {
2166
+ throw an(e, d.txSender.address);
2167
+ }
2168
+ }, v = g.length > 1 && Vi(g), y, b = null, x = [];
2169
+ if (v) {
2170
+ let e = structuredClone(g), n = {};
2171
+ for (let r = 0; r < e.length; r++) {
2172
+ e = await qe(e, n);
2173
+ let i = e[r], a = /* @__PURE__ */ new Set([i.localId]), o = Wi({
2174
+ ...i,
2175
+ propertiesToUpdate: Hi(i.propertiesToUpdate, a)
2176
+ }), s = /* @__PURE__ */ new Map([[o.localId, o]]);
2177
+ Gi([o], s);
2178
+ let c = await _([o]), d = await T(c.transactionHash);
2179
+ if (!d) throw Error("Failed to send transaction");
2180
+ b = d;
2181
+ let f = o?.listOfAttestations?.length ?? 0;
2182
+ for (let e of Fi(d, l)) e.attestationUid && x.push(e.attestationUid);
2183
+ await aa({
2184
+ receipt: d,
2185
+ seedLocalId: i.localId,
2186
+ versionSchemaUid: o.versionSchemaUid,
2187
+ contractAddressForEvents: u.contractAddressForEvents,
2188
+ listOfAttestationsCount: f,
2189
+ useModularExecutor: l,
2190
+ publisherAddress: t
2191
+ });
2192
+ let p = !o.seedUid || J(o.seedUid) === W, m = o?.seedSchemaUid;
2193
+ if (p) {
2194
+ let t = ji(d, m, l) ?? Ni(d, u.contractAddressForEvents, f, l);
2195
+ t && (n[i.localId] = t, e[r] = {
2196
+ ...e[r],
2197
+ seedUid: t
2198
+ }, x.push(t));
2199
+ }
2200
+ await ca({
2201
+ receipt: d,
2202
+ normalizedRequests: [o],
2203
+ useModularExecutor: l,
2204
+ contractAddressForEvents: u.contractAddressForEvents
2205
+ });
2206
+ }
2207
+ for (let t of e) {
2208
+ let e = t?.localId, r = t?.seedUid;
2209
+ e && r && J(r) !== W && (n[e] = J(r));
2210
+ }
2211
+ y = (await qe(structuredClone(g), n)).map((e) => Wi({
2212
+ ...e,
2213
+ seedUid: n[e.localId] ?? e.seedUid
2214
+ }));
2215
+ } else {
2216
+ let e = g.map((e) => Wi(e));
2217
+ Gi(e, new Map(e.map((e) => [e?.localId, e])));
2218
+ let n = Array.isArray(m) ? e : [e[0]], r = await _(n), i = await T(r.transactionHash);
2219
+ if (!i) throw Error("Failed to send transaction");
2220
+ b = i;
2221
+ for (let e of Fi(i, l)) e.attestationUid && x.push(e.attestationUid);
2222
+ let a = e.find((e) => e?.localId === s.seedLocalId) ?? e[0];
2223
+ await aa({
2224
+ receipt: i,
2225
+ seedLocalId: a?.localId,
2226
+ versionSchemaUid: a?.versionSchemaUid,
2227
+ contractAddressForEvents: u.contractAddressForEvents,
2228
+ listOfAttestationsCount: a?.listOfAttestations?.length ?? 0,
2229
+ useModularExecutor: l,
2230
+ publisherAddress: t
2231
+ }), await ca({
2232
+ receipt: i,
2233
+ normalizedRequests: n,
2234
+ useModularExecutor: l,
2235
+ contractAddressForEvents: u.contractAddressForEvents
2236
+ });
2237
+ let o = e[0], c = o?.seedUid, d = c === W || !c, f = o?.listOfAttestations?.length ?? 0, p = o?.seedSchemaUid, h = d ? ji(i, p, l) ?? Ni(i, u.contractAddressForEvents, f, l) : void 0;
2238
+ h && x.push(h), y = h && e.length > 0 ? [{
2239
+ ...e[0],
2240
+ seedUid: h
2241
+ }, ...e.slice(1)] : e;
2242
+ }
2243
+ Oi(s, y);
2244
+ let S = s, te = y.find((e) => e?.localId === s.seedLocalId)?.seedUid;
2245
+ te && te !== W && await ki(S, t, b ? await q(b) : void 0), na("requestData", m), qi(e);
2246
+ try {
2247
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
2248
+ await e(s.seedLocalId);
2249
+ } catch {}
2250
+ let { collectPublishedBatch: C } = await import("./collectBatchUids-CnIe9jUB.js").then((e) => e.t), ne = y.find((e) => e?.localId === s.seedLocalId) ?? y[0];
2251
+ for (let e of y) e?.seedUid && x.push(String(e.seedUid)), e?.versionUid && x.push(String(e.versionUid));
2252
+ return {
2253
+ easPayload: m,
2254
+ publishedBatch: ne?.seedUid ? C({
2255
+ seedUid: String(ne.seedUid),
2256
+ versionUid: ne.versionUid ? String(ne.versionUid) : void 0,
2257
+ extraUids: x
2258
+ }) : null
2259
+ };
2260
+ }), ua = L("seedProtocol:services:publish:verifyAttestations"), da = "0x" + "0".repeat(64), fa = 64, pa = (e) => e == null ? "0x" + "0".repeat(fa) : typeof e == "string" ? "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(fa, "0").slice(-64) : "0x" + "0".repeat(fa), ma = 5e3, ha = 6;
2261
+ async function ga({ normalizedRequests: e, item: t }) {
2262
+ let n = t.seedLocalId;
2263
+ for (let t of e) {
2264
+ if (t.listOfAttestations.length === 0 || t.versionUid === da) continue;
2265
+ let e = t.listOfAttestations.map((e) => pa(e.schema).toLowerCase()), r = [], i;
2266
+ for (let e = 1; e <= ha; e++) try {
2267
+ e > 1 && await new Promise((e) => setTimeout(e, ma)), r = await Fe({ versionUids: [t.versionUid] });
2268
+ break;
2269
+ } catch (t) {
2270
+ if (i = t, ua("verifyAttestations attempt %d failed:", e, t), e === ha) throw ua("verifyAttestations: giving up after %d attempts", ha), i;
2271
+ }
2272
+ let a = r.map((e) => e.schemaId ? pa(e.schemaId).toLowerCase() : "").filter(Boolean), o = new Set(a);
2273
+ if (e.filter((e) => !o.has(e)).length > 0) throw new Ee(`Publish verification failed: Seed and Version attestations were created, but property/metadata attestations are missing or incomplete. Expected ${e.length} property attestations for schema(s) ${e.join(", ")}; found ${a.length}. Use PublishManager.retryAttestations('${n}') to retry.`, n, e, a, "METADATA_PROPERTIES_MISSING");
2274
+ }
2275
+ }
2276
+ //#endregion
2277
+ //#region src/services/publish/actors/createAttestationsDirectToEas.ts
2278
+ var _a = L("seedProtocol:services:publish:createAttestationsDirectToEas"), va = 64, Y = (e) => {
2279
+ if (e == null) return "0x" + "0".repeat(va);
2280
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(va, "0").slice(-64);
2281
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
2282
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
2283
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(va, "0").slice(-64);
2284
+ }
2285
+ return "0x" + "0".repeat(va);
2286
+ }, ya = (e) => {
2287
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
2288
+ if (typeof e == "string") {
2289
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
2290
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
2291
+ }
2292
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
2293
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
2294
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
2295
+ }
2296
+ return "0x";
2297
+ }, ba = async (e) => {
2298
+ let t;
2299
+ try {
2300
+ t = await j.find({ seedLocalId: e });
2301
+ } catch {}
2302
+ return t || new Promise((t) => {
2303
+ let n = setInterval(() => {
2304
+ try {
2305
+ j.find({ seedLocalId: e }).then((e) => {
2306
+ e && (clearInterval(n), t(e));
2307
+ });
2308
+ } catch {}
2309
+ }, 200);
2310
+ });
2311
+ }, xa = I(async ({ input: { context: e, event: t } }) => {
2312
+ let { address: n, account: r, wallet: a } = e, s = e.arweaveTransactions ?? [], c = e.publishUploads ?? [], { item: p } = e;
2313
+ if (!n || typeof n != "string" || !n.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
2314
+ if (!a && !r) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
2315
+ if (!p?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
2316
+ if (typeof p.getPublishUploads != "function" && (p = await ba(p.seedLocalId)), s.length !== c.length) throw Error("Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.");
2317
+ let m = wi(e), h = m.txSender;
2318
+ await vn(p, m, { managedAddress: n });
2319
+ let g = s.map((e, t) => {
2320
+ let n = e.transaction?.id;
2321
+ if (!n || typeof n != "string") throw Error("Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.");
2322
+ let r = c[t];
2323
+ if (!r) throw Error("Publish upload index mismatch");
2324
+ return {
2325
+ ...r,
2326
+ txId: n
2327
+ };
2328
+ });
2329
+ await Ai(g.map((e) => e.txId));
2330
+ let _ = await p.getPublishPayload(g, { publishMode: e.publishMode ?? "patch" }), v = (Array.isArray(_) ? _ : [_]).map((e) => {
2331
+ let t = (e?.listOfAttestations ?? []).map((e) => {
2332
+ let t = Array.isArray(e?.data) ? e.data : [];
2333
+ return {
2334
+ schema: Y(e?.schema),
2335
+ data: t.map((e) => ({
2336
+ ...e,
2337
+ refUID: Y(e?.refUID),
2338
+ data: ya(e?.data)
2339
+ })),
2340
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
2341
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
2342
+ };
2343
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
2344
+ ...e,
2345
+ propertySchemaUid: Y(e?.propertySchemaUid)
2346
+ }));
2347
+ return {
2348
+ ...e,
2349
+ seedUid: Y(e?.seedUid),
2350
+ seedSchemaUid: Y(e?.seedSchemaUid),
2351
+ versionUid: Y(e?.versionUid),
2352
+ versionSchemaUid: Y(e?.versionSchemaUid),
2353
+ listOfAttestations: t,
2354
+ propertiesToUpdate: n
2355
+ };
2356
+ }), y = new Map(v.map((e) => [e.localId, e])), b = {
2357
+ recipient: Pt,
2358
+ expirationTime: BigInt(0),
2359
+ revocable: !0,
2360
+ refUID: u,
2361
+ data: u,
2362
+ value: BigInt(0)
2363
+ };
2364
+ for (let e of v) for (let t of e.propertiesToUpdate ?? []) {
2365
+ let e = t.publishLocalId, n = Y(t.propertySchemaUid);
2366
+ if (!e || !n) continue;
2367
+ let r = y.get(e);
2368
+ if (!r?.listOfAttestations) continue;
2369
+ let i = r.listOfAttestations.find((e) => Y(e?.schema)?.toLowerCase() === n?.toLowerCase());
2370
+ i && (!Array.isArray(i.data) || i.data.length === 0) && (i.data = [{
2371
+ ...b,
2372
+ refUID: u
2373
+ }]);
2374
+ }
2375
+ let x = Date.now(), S = [];
2376
+ for (let e = 0; e < v.length; e++) {
2377
+ let t = v[e], r = t.seedUid, a = t.versionUid;
2378
+ if (r === u) {
2379
+ let e = o({
2380
+ schema: t.seedSchemaUid,
2381
+ data: {
2382
+ refUID: u,
2383
+ data: d(t.seedSchemaUid),
2384
+ revocable: t.seedIsRevocable
2385
+ }
2386
+ }), n = await h.sendTransaction(e), i = await T(n.transactionHash);
2387
+ if (!i) throw Error("Failed to create Seed attestation");
2388
+ x = await q(i);
2389
+ let { easContractAddress: a } = w(), s = f(i, a);
2390
+ if (!s || s === u) throw Error("Failed to get Seed UID from attestation receipt");
2391
+ r = s, t.seedUid = s, S.push(s), _a("created Seed attestation", r);
2392
+ } else r !== u && S.push(r);
2393
+ if (r !== u && a === u) {
2394
+ let e = o({
2395
+ schema: t.versionSchemaUid,
2396
+ data: {
2397
+ refUID: r,
2398
+ data: d(t.versionSchemaUid),
2399
+ revocable: !0
2400
+ }
2401
+ }), i = await h.sendTransaction(e), s = await T(i.transactionHash);
2402
+ if (!s) throw Error("Failed to create Version attestation");
2403
+ x = await q(s);
2404
+ let { easContractAddress: c } = w(), l = f(s, c);
2405
+ if (!l || l === u) throw Error("Failed to get Version UID from attestation receipt");
2406
+ a = l, t.versionUid = l, S.push(l), await Qe({
2407
+ seedLocalId: t.localId,
2408
+ versionUid: l,
2409
+ publisher: n,
2410
+ attestationCreatedAt: x
2411
+ }), _a("created Version attestation", a);
2412
+ } else a !== u && S.push(a);
2413
+ for (let e of t.listOfAttestations) for (let t of e.data) t.refUID = a;
2414
+ for (let e of t.propertiesToUpdate ?? []) {
2415
+ let t = y.get(e.publishLocalId);
2416
+ if (!t?.listOfAttestations) continue;
2417
+ let n = Y(e.propertySchemaUid), i = t.listOfAttestations.find((e) => Y(e?.schema)?.toLowerCase() === n?.toLowerCase());
2418
+ i?.data?.[0] && (i.data[0].data = d(r));
2419
+ }
2420
+ let s = t.listOfAttestations.map((e) => ({
2421
+ schema: e.schema,
2422
+ data: e.data.map((e) => ({
2423
+ recipient: e.recipient ?? Pt,
2424
+ expirationTime: e.expirationTime ?? 0n,
2425
+ revocable: e.revocable ?? !0,
2426
+ refUID: e.refUID ?? u,
2427
+ data: e.data ?? "0x",
2428
+ value: e.value ?? 0n
2429
+ }))
2430
+ }));
2431
+ if (s.length > 0) {
2432
+ let n = l(s), r = await h.sendTransaction(n), o = await T(r.transactionHash);
2433
+ if (!o) throw Error("Failed to create property attestations");
2434
+ x = await q(o), _a("created property attestations for request", e);
2435
+ let { easContractAddress: c } = w(), d = i(o, c);
2436
+ for (let e of d) e.uid && S.push(e.uid);
2437
+ let f = t.listOfAttestations, p = d.length === f.length;
2438
+ await Ae({
2439
+ seedLocalId: t.localId,
2440
+ attestationCreatedAtMs: x ?? null,
2441
+ versionUid: a === u ? null : a,
2442
+ pairs: d.map((e, t) => ({
2443
+ schemaUid: e.schemaUid,
2444
+ attestationUid: e.uid,
2445
+ propertyName: p && typeof f[t]?._propertyName == "string" && f[t]._propertyName !== "" ? f[t]._propertyName : void 0
2446
+ }))
2447
+ });
2448
+ }
2449
+ }
2450
+ Oi(p, v);
2451
+ let ee = p;
2452
+ v[0]?.seedUid && v[0].seedUid !== u && await ki(ee, n, x);
2453
+ try {
2454
+ await ga({
2455
+ normalizedRequests: v,
2456
+ item: p
2457
+ });
2458
+ } catch (e) {
2459
+ throw e instanceof Ee || _a("verifyAttestations failed (non-verification error):", e), e;
2460
+ }
2461
+ _a("direct EAS publish complete"), qi(e);
2462
+ try {
2463
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
2464
+ await e(p.seedLocalId);
2465
+ } catch {}
2466
+ let { collectPublishedBatch: te } = await import("./collectBatchUids-CnIe9jUB.js").then((e) => e.t), C = v.find((e) => e?.localId === p.seedLocalId) ?? v[0];
2467
+ return {
2468
+ easPayload: _,
2469
+ publishedBatch: C?.seedUid ? te({
2470
+ seedUid: String(C.seedUid),
2471
+ versionUid: C.versionUid ? String(C.versionUid) : void 0,
2472
+ extraUids: S
2473
+ }) : null
2474
+ };
2475
+ }), Sa = async (e) => {
2476
+ let t;
2477
+ try {
2478
+ t = await j.find({ seedLocalId: e });
2479
+ } catch {}
2480
+ return t || new Promise((t) => {
2481
+ let n = setInterval(() => {
2482
+ j.find({ seedLocalId: e }).then((e) => {
2483
+ e && (clearInterval(n), t(e));
2484
+ }).catch(() => {});
2485
+ }, 200);
2486
+ });
2487
+ };
2488
+ async function Ca(e) {
2489
+ let t = typeof e.getPublishUploads == "function" ? e : await Sa(e.seedLocalId);
2490
+ return await He(t);
2491
+ }
2492
+ //#endregion
2493
+ //#region src/services/publish/actors/checking.ts
2494
+ var X = /* @__PURE__ */ new Set();
2495
+ async function wa(e) {
2496
+ let t = w();
2497
+ return t.useDirectEas ? "directEas" : t.useModularExecutor || await ee(e) ? "multiPublish" : "directEas";
2498
+ }
2499
+ var Ta = F(({ sendBack: e, input: { context: t } }) => {
2500
+ let { item: n, account: r, wallet: i, publishMode: a, address: o } = t;
2501
+ return (async () => {
2502
+ if (!await Be(n)) {
2503
+ e({ type: "notOwner" });
2504
+ return;
2505
+ }
2506
+ if (X.has(n.seedLocalId)) {
2507
+ e({ type: "redundantPublishProcess" });
2508
+ return;
2509
+ }
2510
+ X.add(n.seedLocalId);
2511
+ try {
2512
+ await Me(), await ie();
2513
+ let t = i ?? r;
2514
+ t && await vn(n, t, { managedAddress: typeof o == "string" ? o : void 0 });
2515
+ let s = await $e(n, [], { publishMode: a ?? "patch" });
2516
+ if (!s.isValid) {
2517
+ X.delete(n.seedLocalId), e({
2518
+ type: "validationFailed",
2519
+ errors: s.errors
2520
+ });
2521
+ return;
2522
+ }
2523
+ if (!o || typeof o != "string" || !o.trim()) {
2524
+ X.delete(n.seedLocalId), e({
2525
+ type: "validationFailed",
2526
+ errors: [{ message: "No publisher address for publish. Connect a wallet and try again." }]
2527
+ });
2528
+ return;
2529
+ }
2530
+ let c;
2531
+ try {
2532
+ c = await wa(o.trim());
2533
+ } catch (t) {
2534
+ X.delete(n.seedLocalId), e({
2535
+ type: "checkingFailed",
2536
+ error: Error(`Could not verify whether the publisher is a deployed contract on ${E()}. Check your RPC connection and retry.`, { cause: t })
2537
+ });
2538
+ return;
2539
+ }
2540
+ let l = await Ca(n), u = w().useArweaveBundler, d = { attestationStrategy: c };
2541
+ e(l ? u ? {
2542
+ type: "validPublishProcessBundler",
2543
+ ...d
2544
+ } : {
2545
+ type: "validPublishProcess",
2546
+ ...d
2547
+ } : {
2548
+ type: "skipArweave",
2549
+ ...d
2550
+ });
2551
+ } catch (t) {
2552
+ X.delete(n.seedLocalId), console.error("[checking] failed", t), e({
2553
+ type: "checkingFailed",
2554
+ error: t instanceof Error ? t : Error(String(t))
2555
+ });
2556
+ }
2557
+ })().catch((t) => {
2558
+ X.delete(n.seedLocalId), console.error("[checking] unhandled rejection", t), e({
2559
+ type: "checkingFailed",
2560
+ error: t instanceof Error ? t : Error(String(t))
2561
+ });
2562
+ }), () => {
2563
+ X.delete(n.seedLocalId);
2564
+ };
2565
+ }), { SUCCESS: Ea, FAILURE: Z } = xe;
2566
+ function Da(e) {
2567
+ let t = e.attestationStrategy;
2568
+ return t === "directEas" || t !== "multiPublish" && w().useDirectEas;
2569
+ }
2570
+ function Oa(e) {
2571
+ let t = e.attestationStrategy;
2572
+ return t === "multiPublish" || t !== "directEas" && !w().useDirectEas;
2573
+ }
2574
+ function Q(e) {
2575
+ let t = e;
2576
+ return t.error ?? t.data;
2577
+ }
2578
+ var ka = Rt({
2579
+ types: {
2580
+ context: {},
2581
+ input: {}
2582
+ },
2583
+ actors: {
2584
+ createArweaveTransactions: Cn,
2585
+ createArweaveTransactionsPhase2: wn,
2586
+ createArweaveDataItems: ur,
2587
+ createArweaveDataItemsPhase2: fr,
2588
+ sendReimbursementRequest: yr,
2589
+ pollForConfirmation: br,
2590
+ uploadData: Sr,
2591
+ uploadViaBundler: Dr,
2592
+ createAttestations: la,
2593
+ createAttestationsDirectToEas: xa,
2594
+ checking: Ta,
2595
+ preparingHtmlEmbedded: Tn,
2596
+ rewritingHtmlEmbedded: Dn
2597
+ },
2598
+ actions: {
2599
+ handleError: ({ event: e }) => {
2600
+ let t = Q(e);
2601
+ t == null ? console.error("Unknown error (full event):", e) : console.error(t);
2602
+ },
2603
+ assignErrorCreatingArweaveTransactions: P({
2604
+ error: ({ event: e }) => Q(e),
2605
+ errorStep: () => "creatingArweaveTransactions"
2606
+ }),
2607
+ assignErrorCreatingArweaveDataItems: P({
2608
+ error: ({ event: e }) => Q(e),
2609
+ errorStep: () => "creatingArweaveDataItems"
2610
+ }),
2611
+ assignErrorSendingReimbursementRequest: P({
2612
+ error: ({ event: e }) => Q(e),
2613
+ errorStep: () => "sendingReimbursementRequest"
2614
+ }),
2615
+ assignErrorPollingForConfirmation: P({
2616
+ error: ({ event: e }) => Q(e),
2617
+ errorStep: () => "pollingForConfirmation"
2618
+ }),
2619
+ assignErrorUploadingData: P({
2620
+ error: ({ event: e }) => Q(e),
2621
+ errorStep: () => "uploadingData"
2622
+ }),
2623
+ assignErrorPreparingHtmlEmbedded: P({
2624
+ error: ({ event: e }) => Q(e),
2625
+ errorStep: () => "preparingHtmlEmbedded"
2626
+ }),
2627
+ assignErrorRewritingHtmlEmbedded: P({
2628
+ error: ({ event: e }) => Q(e),
2629
+ errorStep: () => "rewritingHtmlEmbedded"
2630
+ }),
2631
+ assignErrorCreatingArweaveTransactionsPhase2: P({
2632
+ error: ({ event: e }) => Q(e),
2633
+ errorStep: () => "creatingArweaveTransactionsPhase2"
2634
+ }),
2635
+ assignErrorUploadingDataPhase2: P({
2636
+ error: ({ event: e }) => Q(e),
2637
+ errorStep: () => "uploadingDataPhase2"
2638
+ }),
2639
+ assignErrorUploadingViaBundler: P({
2640
+ error: ({ event: e }) => Q(e),
2641
+ errorStep: () => "uploadingViaBundler"
2642
+ }),
2643
+ assignErrorCreatingArweaveDataItemsPhase2: P({
2644
+ error: ({ event: e }) => Q(e),
2645
+ errorStep: () => "creatingArweaveDataItemsPhase2"
2646
+ }),
2647
+ assignErrorUploadingViaBundlerPhase2: P({
2648
+ error: ({ event: e }) => Q(e),
2649
+ errorStep: () => "uploadingViaBundlerPhase2"
2650
+ }),
2651
+ assignErrorCreatingAttestations: P({
2652
+ error: ({ event: e }) => Q(e),
2653
+ errorStep: () => "creatingAttestations"
2654
+ }),
2655
+ assignErrorCreatingAttestationsDirectToEas: P({
2656
+ error: ({ event: e }) => Q(e),
2657
+ errorStep: () => "creatingAttestationsDirectToEas"
2658
+ }),
2659
+ assignAccountFromRetry: P({
2660
+ wallet: ({ event: e }) => {
2661
+ let t = e;
2662
+ return t.wallet ?? t.account;
2663
+ },
2664
+ account: ({ event: e }) => {
2665
+ let t = e;
2666
+ return t.wallet ?? t.account;
2667
+ }
2668
+ }),
2669
+ assignErrorNotOwner: P({
2670
+ error: () => /* @__PURE__ */ Error("Item is read-only: you do not own this item. Only the publisher can publish."),
2671
+ errorStep: () => "checking"
2672
+ }),
2673
+ assignErrorValidationFailed: P({
2674
+ error: ({ event: e }) => {
2675
+ let t = e.errors ?? [], n = t.length > 0 ? `Validation failed (${t.length} error${t.length === 1 ? "" : "s"}):\n${t.map((e) => e.message).join("\n")}` : "Validation failed", r = Error(n);
2676
+ return r.validationErrors = t, r;
2677
+ },
2678
+ errorStep: () => "checking"
2679
+ }),
2680
+ assignErrorCheckingFailed: P({
2681
+ error: ({ event: e }) => {
2682
+ let t = e.error;
2683
+ return t instanceof Error ? t : Error(String(t ?? "Publish check failed"));
2684
+ },
2685
+ errorStep: () => "checking"
2686
+ })
2687
+ }
2688
+ }).createMachine({
2689
+ id: "publish",
2690
+ initial: "checking",
2691
+ context: ({ input: e }) => e,
2692
+ states: {
2693
+ checking: {
2694
+ on: {
2695
+ notOwner: {
2696
+ target: Z,
2697
+ actions: ["assignErrorNotOwner", "handleError"]
2698
+ },
2699
+ validationFailed: {
2700
+ target: Z,
2701
+ actions: ["assignErrorValidationFailed", "handleError"]
2702
+ },
2703
+ redundantPublishProcess: { target: "stopping" },
2704
+ checkingFailed: {
2705
+ target: Z,
2706
+ actions: ["assignErrorCheckingFailed", "handleError"]
2707
+ },
2708
+ validPublishProcess: {
2709
+ target: "preparingHtmlEmbedded",
2710
+ actions: P({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2711
+ },
2712
+ validPublishProcessBundler: {
2713
+ target: "preparingHtmlEmbedded",
2714
+ actions: P({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2715
+ },
2716
+ skipArweave: [{
2717
+ guard: ({ context: e }) => Da(e),
2718
+ target: "creatingAttestationsDirectToEas",
2719
+ actions: P({
2720
+ arweaveTransactions: () => [],
2721
+ publishUploads: () => [],
2722
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2723
+ })
2724
+ }, {
2725
+ guard: ({ context: e }) => Oa(e),
2726
+ target: "creatingAttestations",
2727
+ actions: P({
2728
+ arweaveTransactions: () => [],
2729
+ publishUploads: () => [],
2730
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2731
+ })
2732
+ }]
2733
+ },
2734
+ invoke: {
2735
+ src: "checking",
2736
+ input: ({ context: e }) => ({ context: e })
2737
+ }
2738
+ },
2739
+ preparingHtmlEmbedded: { invoke: {
2740
+ src: "preparingHtmlEmbedded",
2741
+ input: ({ context: e }) => ({ context: e }),
2742
+ onDone: [{
2743
+ guard: () => w().useArweaveBundler,
2744
+ target: "creatingArweaveDataItems",
2745
+ actions: P({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2746
+ }, {
2747
+ target: "creatingArweaveTransactions",
2748
+ actions: P({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2749
+ }],
2750
+ onError: {
2751
+ target: Z,
2752
+ actions: ["assignErrorPreparingHtmlEmbedded", "handleError"]
2753
+ }
2754
+ } },
2755
+ creatingArweaveTransactions: { invoke: {
2756
+ src: "createArweaveTransactions",
2757
+ input: ({ context: e, event: t }) => ({
2758
+ context: e,
2759
+ event: t
2760
+ }),
2761
+ onDone: {
2762
+ target: "sendingReimbursementRequest",
2763
+ actions: P({
2764
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2765
+ publishUploads: ({ event: e }) => e.output.publishUploads
2766
+ })
2767
+ },
2768
+ onError: {
2769
+ target: "failure",
2770
+ actions: ["assignErrorCreatingArweaveTransactions", "handleError"]
2771
+ }
2772
+ } },
2773
+ creatingArweaveDataItems: { invoke: {
2774
+ src: "createArweaveDataItems",
2775
+ input: ({ context: e, event: t }) => ({
2776
+ context: e,
2777
+ event: t
2778
+ }),
2779
+ onDone: {
2780
+ target: "uploadingViaBundler",
2781
+ actions: P({
2782
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2783
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2784
+ signedDataItems: ({ event: e }) => e.output.signedDataItems
2785
+ })
2786
+ },
2787
+ onError: {
2788
+ target: "failure",
2789
+ actions: ["assignErrorCreatingArweaveDataItems", "handleError"]
2790
+ }
2791
+ } },
2792
+ sendingReimbursementRequest: { invoke: {
2793
+ src: "sendReimbursementRequest",
2794
+ input: ({ context: e, event: t }) => ({
2795
+ context: e,
2796
+ event: t
2797
+ }),
2798
+ onDone: {
2799
+ target: "pollingForConfirmation",
2800
+ actions: P({
2801
+ requestResponse: ({ event: e }) => e.output,
2802
+ reimbursementTransactionId: ({ event: e }) => e.output.transactionId
2803
+ })
2804
+ },
2805
+ onError: {
2806
+ target: "failure",
2807
+ actions: ["assignErrorSendingReimbursementRequest", "handleError"]
2808
+ }
2809
+ } },
2810
+ pollingForConfirmation: { invoke: {
2811
+ src: "pollForConfirmation",
2812
+ input: ({ context: e, event: t }) => ({
2813
+ context: e,
2814
+ event: t
2815
+ }),
2816
+ onDone: {
2817
+ target: "uploadingData",
2818
+ actions: P({ reimbursementConfirmed: !0 })
2819
+ },
2820
+ onError: {
2821
+ target: "failure",
2822
+ actions: ["assignErrorPollingForConfirmation", "handleError"]
2823
+ }
2824
+ } },
2825
+ uploadingViaBundler: {
2826
+ on: {
2827
+ uploadComplete: [
2828
+ {
2829
+ guard: ({ context: e }) => Da(e),
2830
+ target: "creatingAttestationsDirectToEas",
2831
+ actions: P({
2832
+ completionPercentage: 100,
2833
+ signedDataItems: () => void 0,
2834
+ arweaveUploadData: () => void 0
2835
+ })
2836
+ },
2837
+ {
2838
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2839
+ target: "rewritingHtmlEmbedded",
2840
+ actions: P({
2841
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2842
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? [],
2843
+ signedDataItems: () => void 0,
2844
+ arweaveUploadData: () => void 0
2845
+ })
2846
+ },
2847
+ {
2848
+ guard: ({ context: e }) => Oa(e),
2849
+ target: "creatingAttestations",
2850
+ actions: P({
2851
+ completionPercentage: 100,
2852
+ signedDataItems: () => void 0,
2853
+ arweaveUploadData: () => void 0
2854
+ })
2855
+ }
2856
+ ],
2857
+ uploadError: {
2858
+ target: "failure",
2859
+ actions: ["assignErrorUploadingViaBundler", "handleError"]
2860
+ }
2861
+ },
2862
+ invoke: {
2863
+ src: "uploadViaBundler",
2864
+ input: ({ context: e }) => ({ context: e })
2865
+ }
2866
+ },
2867
+ creatingArweaveDataItemsPhase2: { invoke: {
2868
+ src: "createArweaveDataItemsPhase2",
2869
+ input: ({ context: e, event: t }) => ({
2870
+ context: e,
2871
+ event: t
2872
+ }),
2873
+ onDone: {
2874
+ target: "uploadingViaBundlerPhase2",
2875
+ actions: P({
2876
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2877
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2878
+ signedDataItems: ({ event: e }) => e.output.signedDataItems,
2879
+ uploaderState: () => void 0,
2880
+ currentTransactionIndex: () => void 0
2881
+ })
2882
+ },
2883
+ onError: {
2884
+ target: Z,
2885
+ actions: ["assignErrorCreatingArweaveDataItemsPhase2", "handleError"]
2886
+ }
2887
+ } },
2888
+ uploadingViaBundlerPhase2: {
2889
+ on: {
2890
+ uploadComplete: [{
2891
+ guard: ({ context: e }) => Da(e),
2892
+ target: "creatingAttestationsDirectToEas",
2893
+ actions: P({
2894
+ completionPercentage: 100,
2895
+ signedDataItems: () => void 0,
2896
+ arweaveUploadData: () => void 0
2897
+ })
2898
+ }, {
2899
+ guard: ({ context: e }) => Oa(e),
2900
+ target: "creatingAttestations",
2901
+ actions: P({
2902
+ completionPercentage: 100,
2903
+ signedDataItems: () => void 0,
2904
+ arweaveUploadData: () => void 0,
2905
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2906
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2907
+ })
2908
+ }],
2909
+ uploadError: {
2910
+ target: Z,
2911
+ actions: ["assignErrorUploadingViaBundlerPhase2", "handleError"]
2912
+ }
2913
+ },
2914
+ invoke: {
2915
+ src: "uploadViaBundler",
2916
+ input: ({ context: e }) => ({ context: e })
2917
+ }
2918
+ },
2919
+ uploadingData: {
2920
+ on: {
2921
+ updatePercentage: { actions: P({
2922
+ completionPercentage: ({ event: e }) => e.completionPercentage,
2923
+ uploaderState: ({ event: e }) => e.uploaderState,
2924
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2925
+ }) },
2926
+ uploadComplete: [
2927
+ {
2928
+ guard: ({ context: e }) => Da(e),
2929
+ target: "creatingAttestationsDirectToEas",
2930
+ actions: P({ completionPercentage: 100 })
2931
+ },
2932
+ {
2933
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2934
+ target: "rewritingHtmlEmbedded",
2935
+ actions: P({
2936
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2937
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? []
2938
+ })
2939
+ },
2940
+ {
2941
+ guard: ({ context: e }) => Oa(e),
2942
+ target: "creatingAttestations",
2943
+ actions: P({ completionPercentage: 100 })
2944
+ }
2945
+ ],
2946
+ uploadError: {
2947
+ target: "failure",
2948
+ actions: ["assignErrorUploadingData", "handleError"]
2949
+ }
2950
+ },
2951
+ invoke: {
2952
+ src: "uploadData",
2953
+ input: ({ context: e }) => ({ context: e })
2954
+ }
2955
+ },
2956
+ rewritingHtmlEmbedded: { invoke: {
2957
+ src: "rewritingHtmlEmbedded",
2958
+ input: ({ context: e }) => ({ context: e }),
2959
+ onDone: [{
2960
+ guard: () => !w().useArweaveBundler,
2961
+ target: "creatingArweaveTransactionsPhase2"
2962
+ }, {
2963
+ guard: () => w().useArweaveBundler,
2964
+ target: "creatingArweaveDataItemsPhase2"
2965
+ }],
2966
+ onError: {
2967
+ target: Z,
2968
+ actions: ["assignErrorRewritingHtmlEmbedded", "handleError"]
2969
+ }
2970
+ } },
2971
+ creatingArweaveTransactionsPhase2: { invoke: {
2972
+ src: "createArweaveTransactionsPhase2",
2973
+ input: ({ context: e, event: t }) => ({
2974
+ context: e,
2975
+ event: t
2976
+ }),
2977
+ onDone: {
2978
+ target: "uploadingDataPhase2",
2979
+ actions: P({
2980
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2981
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2982
+ uploaderState: () => void 0,
2983
+ currentTransactionIndex: () => void 0
2984
+ })
2985
+ },
2986
+ onError: {
2987
+ target: Z,
2988
+ actions: ["assignErrorCreatingArweaveTransactionsPhase2", "handleError"]
2989
+ }
2990
+ } },
2991
+ uploadingDataPhase2: {
2992
+ on: {
2993
+ updatePercentage: { actions: P({
2994
+ completionPercentage: ({ event: e }) => e.completionPercentage,
2995
+ uploaderState: ({ event: e }) => e.uploaderState,
2996
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2997
+ }) },
2998
+ uploadComplete: [{
2999
+ guard: ({ context: e }) => Da(e),
3000
+ target: "creatingAttestationsDirectToEas",
3001
+ actions: P({ completionPercentage: 100 })
3002
+ }, {
3003
+ guard: ({ context: e }) => Oa(e),
3004
+ target: "creatingAttestations",
3005
+ actions: P({
3006
+ completionPercentage: 100,
3007
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
3008
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
3009
+ })
3010
+ }],
3011
+ uploadError: {
3012
+ target: Z,
3013
+ actions: ["assignErrorUploadingDataPhase2", "handleError"]
3014
+ }
3015
+ },
3016
+ invoke: {
3017
+ src: "uploadData",
3018
+ input: ({ context: e }) => ({ context: e })
3019
+ }
3020
+ },
3021
+ creatingAttestations: { invoke: {
3022
+ src: "createAttestations",
3023
+ input: ({ context: e, event: t }) => ({
3024
+ context: e,
3025
+ event: t
3026
+ }),
3027
+ onDone: {
3028
+ target: Ea,
3029
+ actions: P({
3030
+ easPayload: ({ event: e }) => e.output?.easPayload,
3031
+ publishedBatch: ({ event: e }) => e.output?.publishedBatch ?? null
3032
+ })
3033
+ },
3034
+ onError: {
3035
+ target: "attestationFailureRecoverable",
3036
+ actions: ["assignErrorCreatingAttestations", "handleError"]
3037
+ }
3038
+ } },
3039
+ attestationFailureRecoverable: { on: { retry: {
3040
+ target: "creatingAttestations",
3041
+ actions: ["assignAccountFromRetry"]
3042
+ } } },
3043
+ creatingAttestationsDirectToEas: { invoke: {
3044
+ src: "createAttestationsDirectToEas",
3045
+ input: ({ context: e, event: t }) => ({
3046
+ context: e,
3047
+ event: t
3048
+ }),
3049
+ onDone: {
3050
+ target: Ea,
3051
+ actions: P({
3052
+ easPayload: ({ event: e }) => e.output?.easPayload,
3053
+ publishedBatch: ({ event: e }) => e.output?.publishedBatch ?? null
3054
+ })
3055
+ },
3056
+ onError: {
3057
+ target: "attestationFailureRecoverableDirectToEas",
3058
+ actions: ["assignErrorCreatingAttestationsDirectToEas", "handleError"]
3059
+ }
3060
+ } },
3061
+ attestationFailureRecoverableDirectToEas: { on: { retry: {
3062
+ target: "creatingAttestationsDirectToEas",
3063
+ actions: ["assignAccountFromRetry"]
3064
+ } } },
3065
+ stopping: {
3066
+ entry: ({ context: e }) => {
3067
+ console.log(`Actor for ${e.item?.seedLocalId} stopped`);
3068
+ },
3069
+ type: "final"
3070
+ },
3071
+ [Ea]: {
3072
+ entry: ({ context: e }) => {
3073
+ let t = e.publishedBatch, n = e.onPublished;
3074
+ if (!n || !t?.seedUid) return;
3075
+ let r = e.item?.seedLocalId;
3076
+ r && Promise.resolve(n({
3077
+ seedLocalId: r,
3078
+ seedUid: t.seedUid,
3079
+ versionUid: t.versionUid,
3080
+ attestationUids: t.attestationUids
3081
+ })).catch((e) => {
3082
+ console.warn("[publish] onPublished callback failed:", e);
3083
+ });
3084
+ },
3085
+ type: "final"
3086
+ },
3087
+ [Z]: {
3088
+ entry: ({ context: e }) => {},
3089
+ type: "final"
3090
+ }
3091
+ }
3092
+ }), Aa = P(({ context: e, event: t }) => {
3093
+ let n = t, r = n.publishProcesses ?? /* @__PURE__ */ new Map(), i = n.subscriptions ?? /* @__PURE__ */ new Map();
3094
+ return {
3095
+ publishProcesses: new Map(r),
3096
+ subscriptions: new Map(i)
3097
+ };
3098
+ }), ja = null;
3099
+ function Ma(e) {
3100
+ ja = e;
3101
+ }
3102
+ function Na() {
3103
+ return ja;
3104
+ }
3105
+ //#endregion
3106
+ //#region src/services/publishManager/actors/subscribe.ts
3107
+ var Pa = L("seedProtocol:services:PublishManager:actors:subscribe");
3108
+ function Fa(e) {
3109
+ let t = e.value;
3110
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
3111
+ }
3112
+ function Ia(e) {
3113
+ return ue.includes(e);
3114
+ }
3115
+ var La = F(({ receive: e, input: { publishProcess: t, seedLocalId: n } }) => {
3116
+ let r = Na(), i = null, a = () => {
3117
+ i != null && (clearInterval(i), i = null);
3118
+ }, o = (e) => {
3119
+ let o = Fa(e);
3120
+ Ia(o) && i == null && r ? i = setInterval(() => {
3121
+ try {
3122
+ let e = t.getSnapshot();
3123
+ if (e.status === "done") {
3124
+ a();
3125
+ return;
3126
+ }
3127
+ if (!Ia(Fa(e))) {
3128
+ a();
3129
+ return;
3130
+ }
3131
+ } catch {
3132
+ return;
3133
+ }
3134
+ r?.savePublish(n, t);
3135
+ }, x) : Ia(o) || a();
3136
+ }, s = t.subscribe(async (e) => {
3137
+ Pa("Publish state:", e.value), r && (e.status === "done" ? (a(), r.savePublish(n, t, { triggerPublishDone: !0 })) : (r.savePublish(n, t), o(e)));
3138
+ });
3139
+ e(({ type: e }) => {
3140
+ e === "UNSUBSCRIBE" && (Pa("Received UNSUBSCRIBE event"), a(), s.unsubscribe(), r?.removeSubscription(n));
3141
+ });
3142
+ }), Ra = /* @__PURE__ */ new Map(), za = 1;
3143
+ function Ba(e) {
3144
+ let t = za++;
3145
+ return Ra.set(t, e), t;
3146
+ }
3147
+ function Va(e, t) {
3148
+ if (e == null) return;
3149
+ let n = Ra.get(e);
3150
+ n && (Ra.delete(e), n(t));
3151
+ }
3152
+ //#endregion
3153
+ //#region src/services/publishManager/actions/createPublish.ts
3154
+ function Ha(e) {
3155
+ if (e) {
3156
+ if (m(e)) return e;
3157
+ if (r(e)) {
3158
+ let t = ce();
3159
+ if (t && t.signer.address.toLowerCase() === e.address.toLowerCase()) return t;
3160
+ throw Error("@seedprotocol/publish: createPublish requires a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.");
3161
+ }
3162
+ throw Error("@seedprotocol/publish: createPublish account must be a PublishWallet. Thirdweb Account must be wrapped with fromThirdwebAccount from @seedprotocol/publish/thirdweb.");
3163
+ }
3164
+ }
3165
+ function Ua(e) {
3166
+ if (e) {
3167
+ if (e instanceof N.Wallet) return e;
3168
+ if (m(e)) return e.signer;
3169
+ if (r(e)) return e;
3170
+ }
3171
+ }
3172
+ var Wa = Lt(({ event: e, enqueue: t }) => {
3173
+ let { item: n, address: r, account: i, options: a, createToken: o } = e;
3174
+ if (!(r != null && typeof r == "string" && r.trim().length > 0)) {
3175
+ console.warn("[createPublish] No valid wallet address; skipping spawn."), Va(o, void 0);
3176
+ return;
3177
+ }
3178
+ t.assign(({ context: e, spawn: t }) => {
3179
+ let { publishProcesses: s } = e;
3180
+ if (s && s.has(n.seedLocalId)) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" already exists.`), Va(o, void 0), e;
3181
+ let c = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `run_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, l = w(), u = [...l.arweaveUploadTags ?? [], ...a?.arweaveUploadTags ?? []], d = Ha(i) ?? ce() ?? void 0, f = t(ka, { input: {
3182
+ item: n,
3183
+ address: r,
3184
+ wallet: d,
3185
+ account: d,
3186
+ modelName: n.modelName,
3187
+ schemaId: n.schemaUid,
3188
+ signDataItems: a?.signDataItems,
3189
+ dataItemSigner: Ua(a?.dataItemSigner),
3190
+ signArweaveTransactions: a?.signArweaveTransactions,
3191
+ arweaveJwk: a?.arweaveJwk,
3192
+ publishMode: a?.publishMode ?? "patch",
3193
+ publishRunId: c,
3194
+ arweaveUploadTags: u.length ? u : void 0,
3195
+ htmlEmbeddedDataUriPolicy: a?.htmlEmbeddedDataUriPolicy ?? l.htmlEmbeddedDataUriPolicy ?? "materialize",
3196
+ onPublished: a?.onPublished ?? l.onPublished
3197
+ } });
3198
+ s.set(n.seedLocalId, f);
3199
+ let p = new Map(e.settledPublishes);
3200
+ return p.delete(n.seedLocalId), Va(o, f), {
3201
+ ...e,
3202
+ publishProcesses: s,
3203
+ settledPublishes: p
3204
+ };
3205
+ }), t.assign(({ context: e, spawn: t }) => {
3206
+ let { subscriptions: r, publishProcesses: i } = e, a = i.get(n.seedLocalId);
3207
+ if (!a) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" does not exist.`), e;
3208
+ if (r.has(n.seedLocalId)) return console.warn(`Subscription with seedLocalId "${n.seedLocalId}" already exists.`), e;
3209
+ let o = t(La, { input: {
3210
+ publishProcess: a,
3211
+ seedLocalId: n.seedLocalId
3212
+ } });
3213
+ return r.set(n.seedLocalId, o), {
3214
+ ...e,
3215
+ subscriptions: new Map(r)
3216
+ };
3217
+ });
3218
+ }), Ga = ({ context: e, event: t }) => {
3219
+ let { seedLocalId: n, account: r } = t, i = e.publishProcesses.get(n);
3220
+ if (!i) {
3221
+ console.warn(`Publish process with seedLocalId "${n}" does not exist.`);
3222
+ return;
3223
+ }
3224
+ let a = r == null ? ce() ?? void 0 : m(r) ? r : void 0;
3225
+ r != null && !a && console.warn("[retryAttestations] account must be a PublishWallet. Use fromThirdwebAccount / fromEip1193Provider / fromEthersWallet."), i.send({
3226
+ type: "retry",
3227
+ account: a,
3228
+ wallet: a
3229
+ });
3230
+ };
3231
+ //#endregion
3232
+ //#region src/services/publishManager/actions/stopScopedOrStandaloneChild.ts
3233
+ function Ka(e, t, n) {
3234
+ t._parent === e ? n.stopChild(t) : t.stop();
3235
+ }
3236
+ //#endregion
3237
+ //#region src/services/publishManager/actors/savePublish.ts
3238
+ var qa = L("seedProtocol:services:PublishManager:actors:savePublish"), Ja = /* @__PURE__ */ new Map();
3239
+ function Ya(e, t) {
3240
+ let n = (Ja.get(e) ?? Promise.resolve()).then(t);
3241
+ return Ja.set(e, n.catch(() => {})), n;
3242
+ }
3243
+ function Xa(e) {
3244
+ return e === "completed" || e === "failed" || e === "interrupted";
3245
+ }
3246
+ function Za(e) {
3247
+ return e.status === "done" ? e.value === "success" ? "completed" : e.value === "failure" ? "failed" : "completed" : "in_progress";
3248
+ }
3249
+ var Qa = 500, $a = 2e3, eo = 100;
3250
+ function to(e) {
3251
+ return JSON.stringify(e, (e, t) => typeof t == "bigint" ? t.toString() : t);
3252
+ }
3253
+ function no(e) {
3254
+ if (typeof e != "object" || !e) return;
3255
+ let t = e, n = t.snapshot, r = (t.context ?? n?.context)?.publishRunId;
3256
+ return typeof r == "string" && r.length > 0 ? r : void 0;
3257
+ }
3258
+ function ro(e) {
3259
+ if (e instanceof Error) return e.message;
3260
+ if (typeof e == "object") {
3261
+ let t = e.message;
3262
+ return typeof t == "string" ? t : void 0;
3263
+ }
3264
+ return String(e);
3265
+ }
3266
+ function io(e) {
3267
+ if (typeof e != "object" || !e) return;
3268
+ let t = e.code;
3269
+ return typeof t == "string" && t.length > 0 ? t.slice(0, eo) : void 0;
3270
+ }
3271
+ function ao(e, t) {
3272
+ if (!e?.error || t !== "failed" && t !== "in_progress") return {};
3273
+ let n = e.error, r = ro(n)?.slice(0, Qa), i = e.errorStep, a = io(n), o;
3274
+ if (n instanceof Error && n.stack) o = n.stack.slice(0, $a);
3275
+ else if (typeof n == "object" && n) try {
3276
+ o = JSON.stringify(n).slice(0, $a);
3277
+ } catch {
3278
+ o = String(n).slice(0, $a);
3279
+ }
3280
+ else n != null && (o = String(n).slice(0, $a));
3281
+ return {
3282
+ ...r === void 0 ? {} : { errorMessage: r },
3283
+ errorStep: i,
3284
+ ...n instanceof Error || r !== void 0 ? { errorDetails: o } : {},
3285
+ errorCode: a ?? null
3286
+ };
3287
+ }
3288
+ function oo(e) {
3289
+ return Ya(e, async () => {
3290
+ let t = k.getAppDb();
3291
+ if (!t) {
3292
+ qa("markInProgressPublishInterrupted: DB not ready, skipping");
3293
+ return;
3294
+ }
3295
+ let n = await t.select().from(M).where(zt(R(M.seedLocalId, e), R(M.status, "in_progress"))).orderBy(Bt(M.updatedAt)).limit(1);
3296
+ if (n.length === 0) return;
3297
+ let r = Date.now();
3298
+ await t.update(M).set({
3299
+ status: "interrupted",
3300
+ completedAt: r,
3301
+ updatedAt: r,
3302
+ errorMessage: null,
3303
+ errorStep: null,
3304
+ errorDetails: null,
3305
+ errorCode: null
3306
+ }).where(R(M.id, n[0].id));
3307
+ });
3308
+ }
3309
+ var so = F(({ sendBack: e, input: { persistedSnapshot: t, seedLocalId: n, triggerPublishDone: r } }) => {
3310
+ qa("savePublish seedLocalId", n);
3311
+ let i = t;
3312
+ Ya(n, async () => {
3313
+ let a = k.getAppDb();
3314
+ if (!a) {
3315
+ qa("savePublish: DB not ready, skipping"), e({
3316
+ type: "SAVE_PUBLISH_DONE",
3317
+ seedLocalId: n,
3318
+ triggerPublishDone: r
3319
+ });
3320
+ return;
3321
+ }
3322
+ let o = await a.select().from(M).where(zt(R(M.seedLocalId, n), R(M.status, "in_progress"))).orderBy(Bt(M.updatedAt)).limit(1), s = typeof t == "string" ? t : to(t), c = Za(i), l = Date.now(), u = ao(i.context, c);
3323
+ if (o.length > 0) {
3324
+ let e = o[0];
3325
+ await a.update(M).set({
3326
+ persistedSnapshot: s,
3327
+ status: c,
3328
+ updatedAt: l,
3329
+ ...i.status === "done" && c !== "in_progress" ? { completedAt: l } : {},
3330
+ ...u
3331
+ }).where(R(M.id, e.id));
3332
+ } else {
3333
+ let e = no(i);
3334
+ if (e != null && c === "in_progress" && i.status !== "done") {
3335
+ let t = (await a.select().from(M).where(R(M.seedLocalId, n)).orderBy(Bt(M.startedAt)).limit(1))[0];
3336
+ if (t && Xa(t.status)) try {
3337
+ if (no(JSON.parse(t.persistedSnapshot)) === e) {
3338
+ qa("savePublish: skip stale insert — same publishRunId as latest terminal row", n, e);
3339
+ return;
3340
+ }
3341
+ } catch {}
3342
+ }
3343
+ let t = i.context?.item, r = i.context?.modelName ?? t?.modelName ?? "", o = i.context?.schemaId ?? t?.schemaId;
3344
+ await a.insert(M).values({
3345
+ seedLocalId: n,
3346
+ modelName: r,
3347
+ schemaId: o ?? null,
3348
+ status: c,
3349
+ startedAt: l,
3350
+ persistedSnapshot: s,
3351
+ createdAt: l,
3352
+ updatedAt: l,
3353
+ ...u
3354
+ });
3355
+ }
3356
+ }).then(() => {
3357
+ e({
3358
+ type: "SAVE_PUBLISH_DONE",
3359
+ seedLocalId: n,
3360
+ triggerPublishDone: r
3361
+ });
3362
+ }).catch((t) => {
3363
+ qa("savePublish error", t), e({
3364
+ type: "SAVE_PUBLISH_DONE",
3365
+ seedLocalId: n,
3366
+ triggerPublishDone: r
3367
+ });
3368
+ });
3369
+ }), co = Lt(({ context: e, event: t, enqueue: n, self: r }) => {
3370
+ let { publishProcesses: i, subscriptions: a } = e, { seedLocalId: o } = t;
3371
+ oo(o).catch((e) => {
3372
+ console.warn(`[stopPublish] Failed to mark publish_processes row interrupted for "${o}":`, e);
3373
+ });
3374
+ let s = i.get(o);
3375
+ if (!s) {
3376
+ console.warn(`Publish process with seedLocalId "${o}" does not exist.`);
3377
+ return;
3378
+ }
3379
+ Ka(r, s, n);
3380
+ let c = a.get(o);
3381
+ c && Ka(r, c, n);
3382
+ let l = new Map(i);
3383
+ l.delete(o);
3384
+ let u = new Map(a);
3385
+ u.delete(o), n.assign({
3386
+ publishProcesses: l,
3387
+ subscriptions: u
3388
+ });
3389
+ }), lo = L("seedProtocol:PublishManager:index"), uo = Lt(({ context: e, enqueue: t, self: n }) => {
3390
+ lo("Stopping all actors..."), e.publishProcesses.forEach((e) => {
3391
+ Ka(n, e, t);
3392
+ }), e.subscriptions.forEach((e) => {
3393
+ Ka(n, e, t);
3394
+ }), t.assign({
3395
+ publishProcesses: /* @__PURE__ */ new Map(),
3396
+ subscriptions: /* @__PURE__ */ new Map()
3397
+ });
3398
+ }), fo = Lt(({ context: e, event: t, enqueue: n }) => {
3399
+ let { seedLocalId: r } = t, i = e.publishProcesses.get(r);
3400
+ if (!i) {
3401
+ console.warn(`Publish process with seedLocalId "${r}" does not exist.`);
3402
+ return;
3403
+ }
3404
+ n.stopChild(i);
3405
+ let a = e.subscriptions.get(r);
3406
+ a && n.stopChild(a);
3407
+ let o = new Map(e.publishProcesses);
3408
+ o.delete(r);
3409
+ let s = new Map(e.subscriptions);
3410
+ s.delete(r), n.assign({
3411
+ publishProcesses: o,
3412
+ subscriptions: s
3413
+ });
3414
+ }), po = P(({ context: e, event: t }) => {
3415
+ let { subscriptions: n } = e, { seedLocalId: r, newSubscription: i } = t;
3416
+ return i && n.set(r, i), { subscriptions: new Map(n) };
3417
+ }), mo = ["signedDataItems", "arweaveUploadData"];
3418
+ function ho(e) {
3419
+ if (typeof e != "object" || !e) return e;
3420
+ let t = { ...e };
3421
+ for (let e of mo) delete t[e];
3422
+ return t;
3423
+ }
3424
+ function go(e) {
3425
+ if (typeof e != "object" || !e) return e;
3426
+ let t = e, n = { ...t };
3427
+ t.context != null && typeof t.context == "object" && (n.context = ho(t.context));
3428
+ let r = t.snapshot;
3429
+ if (typeof r == "object" && r) {
3430
+ let e = r, t = { ...e };
3431
+ e.context != null && typeof e.context == "object" && (t.context = ho(e.context)), n.snapshot = t;
3432
+ }
3433
+ return n;
3434
+ }
3435
+ function _o(e) {
3436
+ try {
3437
+ return go(e.getPersistedSnapshot?.() ?? e.getSnapshot());
3438
+ } catch {
3439
+ let t = e.getSnapshot(), n = t.context;
3440
+ if (!n?.item) return go(t);
3441
+ let r = n.item;
3442
+ return go({
3443
+ ...t,
3444
+ context: {
3445
+ ...n,
3446
+ item: {
3447
+ seedLocalId: r.seedLocalId,
3448
+ modelName: r.modelName,
3449
+ schemaId: r.schemaId
3450
+ }
3451
+ }
3452
+ });
3453
+ }
3454
+ }
3455
+ var vo = P(({ context: e, event: t, spawn: n }) => {
3456
+ let { publishProcesses: r } = e, { seedLocalId: i, publishProcess: a, triggerPublishDone: o } = t;
3457
+ if (!a) return e;
3458
+ let s = new Map(r);
3459
+ s.set(i, a);
3460
+ let c = _o(a);
3461
+ return n(so, {
3462
+ id: `savePublish_${i}_${Date.now()}`,
3463
+ input: {
3464
+ persistedSnapshot: c,
3465
+ seedLocalId: i,
3466
+ triggerPublishDone: o
3467
+ }
3468
+ }), { publishProcesses: s };
3469
+ }), yo = P(({ context: e, event: t }) => {
3470
+ let { publishProcesses: n, subscriptions: r, settledPublishes: i } = e, a = t.seedLocalId, o = r.get(a);
3471
+ o && o.send({ type: "UNSUBSCRIBE" });
3472
+ let s = n.get(a), c = new Map(n);
3473
+ c.delete(a);
3474
+ let l = new Map(r);
3475
+ l.delete(a);
3476
+ let u = new Map(i);
3477
+ return s && u.set(a, s), {
3478
+ publishProcesses: c,
3479
+ subscriptions: l,
3480
+ settledPublishes: u
3481
+ };
3482
+ }), bo = P(({ context: e, event: t }) => {
3483
+ let { subscriptions: n } = e, r = t.seedLocalId, i = new Map(n);
3484
+ return i.delete(r), { subscriptions: i };
3485
+ }), xo = 6e4, So = 2e3;
3486
+ function Co(e, t) {
3487
+ let n = typeof process < "u" ? process.env[e] : void 0;
3488
+ if (n == null || n === "") return t;
3489
+ let r = Number(n);
3490
+ return Number.isFinite(r) && r >= 0 ? r : t;
3491
+ }
3492
+ async function wo(e, t) {
3493
+ let n = Date.now() + e;
3494
+ for (; Date.now() < n;) {
3495
+ try {
3496
+ if (k.isAppDbReady() && k.getAppDb()) return !0;
3497
+ } catch {}
3498
+ await new Promise((e) => setTimeout(e, t));
3499
+ }
3500
+ return !1;
3501
+ }
3502
+ function To(e) {
3503
+ let t = e.value;
3504
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
3505
+ }
3506
+ function Eo(e) {
3507
+ let t = To(e);
3508
+ if (t === "pollingForConfirmation" && (!e.context?.reimbursementTransactionId || !e.context?.requestResponse)) return !1;
3509
+ if (t === "uploadingData") {
3510
+ let t = e.context?.arweaveTransactions, n = e.context?.publishUploads;
3511
+ if (!Array.isArray(t) || t.length === 0 || !Array.isArray(n)) return !1;
3512
+ }
3513
+ return !0;
3514
+ }
3515
+ function Do(e) {
3516
+ return typeof e == "object" && !!e && "xstate$$type" in e && e.xstate$$type === 1 && typeof e.id == "string";
3517
+ }
3518
+ function Oo(e, t, n) {
3519
+ e.context = e.context ?? {};
3520
+ let r = e.context.item;
3521
+ if (Do(r)) {
3522
+ e.context.item = {
3523
+ seedLocalId: t,
3524
+ modelName: e.context.modelName ?? n.modelName ?? "",
3525
+ schemaId: e.context.schemaId ?? n.schemaId ?? void 0
3526
+ };
3527
+ return;
3528
+ }
3529
+ e.context.item = {
3530
+ ...typeof r == "object" && r && !Array.isArray(r) ? r : {},
3531
+ seedLocalId: t,
3532
+ modelName: r?.modelName ?? e.context.modelName ?? n.modelName ?? "",
3533
+ schemaId: r?.schemaId ?? e.context.schemaId ?? n.schemaId ?? void 0
3534
+ };
3535
+ }
3536
+ var ko = F(({ sendBack: e, input: { context: t } }) => {
3537
+ let n = async () => {
3538
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
3539
+ if (!await wo(Co("SEED_PUBLISH_RESTORE_WAIT_MS", xo), Co("SEED_PUBLISH_RESTORE_POLL_MS", So))) return {
3540
+ newPublishProcesses: e,
3541
+ newSubscriptions: t
3542
+ };
3543
+ let n = k.getAppDb();
3544
+ if (!n) return {
3545
+ newPublishProcesses: e,
3546
+ newSubscriptions: t
3547
+ };
3548
+ let r = await n.select().from(M).where(R(M.status, "in_progress")), i = /* @__PURE__ */ new Map(), a = [...r].sort((e, t) => (t.updatedAt ?? t.createdAt ?? 0) - (e.updatedAt ?? e.createdAt ?? 0));
3549
+ for (let e of a) i.has(e.seedLocalId) || i.set(e.seedLocalId, e);
3550
+ let o = Array.from(i.values());
3551
+ for (let n of o) {
3552
+ let r;
3553
+ try {
3554
+ r = JSON.parse(n.persistedSnapshot);
3555
+ } catch {
3556
+ continue;
3557
+ }
3558
+ if (r.status === "done") continue;
3559
+ let i = r.context?.item?.seedLocalId ?? n.seedLocalId;
3560
+ if (!i || !Eo(r)) continue;
3561
+ Oo(r, i, n);
3562
+ let a = It(ka, {
3563
+ snapshot: r,
3564
+ input: void 0
3565
+ }), o = It(La, { input: {
3566
+ publishProcess: a,
3567
+ seedLocalId: i
3568
+ } });
3569
+ e.set(i, a), t.set(i, o), a.start(), o.start();
3570
+ }
3571
+ return {
3572
+ newPublishProcesses: e,
3573
+ newSubscriptions: t
3574
+ };
3575
+ }, r = () => ({
3576
+ newPublishProcesses: /* @__PURE__ */ new Map(),
3577
+ newSubscriptions: /* @__PURE__ */ new Map()
3578
+ });
3579
+ n().then((t) => {
3580
+ let { newPublishProcesses: n, newSubscriptions: i } = t ?? r();
3581
+ e({
3582
+ type: "RESTORE_FROM_DB_DONE",
3583
+ publishProcesses: n,
3584
+ subscriptions: i
3585
+ });
3586
+ }).catch(() => {
3587
+ let { newPublishProcesses: t, newSubscriptions: n } = r();
3588
+ e({
3589
+ type: "RESTORE_FROM_DB_DONE",
3590
+ publishProcesses: t,
3591
+ subscriptions: n
3592
+ });
3593
+ });
3594
+ }), Ao = P(({ context: e, event: t }) => ({ pendingCreates: [...e.pendingCreates ?? [], t] })), jo = Lt(({ context: e, enqueue: t }) => {
3595
+ let n = e.pendingCreates ?? [];
3596
+ if (n.length !== 0) {
3597
+ t.assign({ pendingCreates: [] });
3598
+ for (let e of n) t.raise(e);
3599
+ }
3600
+ }), Mo = L("seedProtocol:PublishManager:index"), No = Rt({
3601
+ types: {
3602
+ context: {},
3603
+ input: {},
3604
+ events: {}
3605
+ },
3606
+ actors: { restoreFromDb: ko },
3607
+ actions: {
3608
+ assignRestoreFromDb: Aa,
3609
+ createPublish: Wa,
3610
+ queueCreatePublish: Ao,
3611
+ drainPendingCreates: jo,
3612
+ addSubscription: po,
3613
+ requestSavePublish: vo,
3614
+ publishDone: yo,
3615
+ removeSubscription: bo,
3616
+ retryAttestations: Ga,
3617
+ stopPublish: co,
3618
+ stopAll: uo,
3619
+ query: fo
3620
+ }
3621
+ }).createMachine({
3622
+ id: "publishManager",
3623
+ initial: "restoreFromDb",
3624
+ context: {
3625
+ publishProcesses: /* @__PURE__ */ new Map(),
3626
+ subscriptions: /* @__PURE__ */ new Map(),
3627
+ pendingCreates: [],
3628
+ settledPublishes: /* @__PURE__ */ new Map()
3629
+ },
3630
+ states: {
3631
+ restoreFromDb: {
3632
+ on: {
3633
+ RESTORE_FROM_DB_DONE: {
3634
+ target: "active",
3635
+ actions: ["assignRestoreFromDb"]
3636
+ },
3637
+ CREATE_PUBLISH: { actions: ["queueCreatePublish"] }
3638
+ },
3639
+ invoke: {
3640
+ src: "restoreFromDb",
3641
+ input: ({ context: e }) => ({ context: e })
3642
+ }
3643
+ },
3644
+ active: {
3645
+ entry: "drainPendingCreates",
3646
+ on: {
3647
+ CREATE_PUBLISH: { actions: ["createPublish"] },
3648
+ ADD_SUBSCRIPTION: { actions: ["addSubscription"] },
3649
+ REQUEST_SAVE_PUBLISH: { actions: ["requestSavePublish"] },
3650
+ SAVE_PUBLISH_DONE: [{
3651
+ guard: ({ event: e }) => e.triggerPublishDone === !0,
3652
+ actions: ["publishDone"]
3653
+ }],
3654
+ PUBLISH_DONE: { actions: ["publishDone"] },
3655
+ REMOVE_SUBSCRIPTION: { actions: ["removeSubscription"] },
3656
+ RETRY_ATTESTATIONS: { actions: ["retryAttestations"] },
3657
+ STOP_PUBLISH: { actions: ["stopPublish"] },
3658
+ QUERY: { actions: ["query"] },
3659
+ STOP_ALL: { actions: ["stopAll"] }
3660
+ }
3661
+ }
3662
+ }
3663
+ }), $ = It(No, { input: {
3664
+ publishProcesses: /* @__PURE__ */ new Map(),
3665
+ subscriptions: /* @__PURE__ */ new Map(),
3666
+ pendingCreates: [],
3667
+ settledPublishes: /* @__PURE__ */ new Map()
3668
+ } }), Po = !1;
3669
+ function Fo() {
3670
+ if (!Po) {
3671
+ try {
3672
+ $.start();
3673
+ } catch (e) {
3674
+ let t = e instanceof Error ? e.message : String(e);
3675
+ if (!/already started/i.test(t)) throw e;
3676
+ }
3677
+ Po = !0;
3678
+ }
3679
+ }
3680
+ Ma({
3681
+ savePublish: (e, t, n) => {
3682
+ $.send({
3683
+ type: "REQUEST_SAVE_PUBLISH",
3684
+ seedLocalId: e,
3685
+ publishProcess: t,
3686
+ triggerPublishDone: n?.triggerPublishDone
3687
+ });
3688
+ },
3689
+ onPublishDone: (e) => {
3690
+ $.send({
3691
+ type: "PUBLISH_DONE",
3692
+ seedLocalId: e
3693
+ });
3694
+ },
3695
+ removeSubscription: (e) => {
3696
+ $.send({
3697
+ type: "REMOVE_SUBSCRIPTION",
3698
+ seedLocalId: e
3699
+ });
3700
+ }
3701
+ });
3702
+ var Io = $.subscribe((e) => {
3703
+ Mo("PublishManager snapshot:", e);
3704
+ });
3705
+ typeof document < "u" && (Fo(), window.addEventListener("load", () => {
3706
+ Mo("PublishManager started");
3707
+ }), window.addEventListener("beforeunload", () => {
3708
+ Io.unsubscribe(), $.stop();
3709
+ }));
3710
+ var Lo = {
3711
+ getService: () => $,
3712
+ ready: () => (Fo(), $.getSnapshot().value === "active" ? Promise.resolve() : new Promise((e) => {
3713
+ let t = $.subscribe((n) => {
3714
+ n.value === "active" && (t.unsubscribe(), e());
3715
+ });
3716
+ $.getSnapshot().value === "active" && (t.unsubscribe(), e());
3717
+ })),
3718
+ createPublish: (e, t, n, r) => new Promise((i) => {
3719
+ let a = Ba(i);
3720
+ $.send({
3721
+ type: "CREATE_PUBLISH",
3722
+ item: e,
3723
+ address: t,
3724
+ account: n,
3725
+ options: r,
3726
+ createToken: a
3727
+ });
3728
+ }),
3729
+ retryAttestations: (e, t) => $.send({
3730
+ type: "RETRY_ATTESTATIONS",
3731
+ seedLocalId: e,
3732
+ account: t
3733
+ }),
3734
+ stopPublish: (e) => $.send({
3735
+ type: "STOP_PUBLISH",
3736
+ seedLocalId: e
3737
+ }),
3738
+ query: (e) => $.send({
3739
+ type: "QUERY",
3740
+ seedLocalId: e
3741
+ }),
3742
+ stopAll: () => $.send({ type: "STOP_ALL" }),
3743
+ getPublish: (e) => {
3744
+ let t = $.getSnapshot().context;
3745
+ return t.publishProcesses.get(e) ?? t.settledPublishes.get(e);
3746
+ },
3747
+ savePublish: (e, t) => $.send({
3748
+ type: "REQUEST_SAVE_PUBLISH",
3749
+ seedLocalId: e,
3750
+ publishProcess: t
3751
+ }),
3752
+ addSubscription: (e, t) => $.send({
3753
+ type: "ADD_SUBSCRIPTION",
3754
+ seedLocalId: e,
3755
+ newSubscription: t
3756
+ }),
3757
+ removeSubscription: (e) => $.send({
3758
+ type: "REMOVE_SUBSCRIPTION",
3759
+ seedLocalId: e
3760
+ })
3761
+ };
3762
+ //#endregion
3763
+ //#region src/helpers/approvedTargetsForAutomationPublish.ts
3764
+ function Ro() {
3765
+ let e = w().modularAccountModuleContract?.trim();
3766
+ if (!e || !/^0x[0-9a-fA-F]{40}$/.test(e)) throw Error("@seedprotocol/publish: session keys require PublishConfig.modularAccountModuleContract (their only approved target is the Seed executor module).");
3767
+ return [e.toLowerCase()];
3768
+ }
3769
+ //#endregion
3770
+ //#region src/helpers/automationSessionKeyPermissions.ts
3771
+ var zo = "publish,revoke";
3772
+ function Bo(e) {
3773
+ let t = {
3774
+ approvedTargets: Ro(),
3775
+ nativeTokenLimitPerTransaction: 0
3776
+ };
3777
+ return typeof e?.expiresAt == "number" && e.expiresAt > 0 && (t.expiresAt = Math.trunc(e.expiresAt)), t;
3778
+ }
3779
+ function Vo(e, t = zo) {
3780
+ let n = `${[...e.approvedTargets].map((e) => e.toLowerCase()).sort().join(",")}|${e.nativeTokenLimitPerTransaction}|${e.expiresAt ?? 0}|${t.trim()}`;
3781
+ return dt(ft(n));
3782
+ }
3783
+ function Ho(e) {
3784
+ let t = {
3785
+ approvedTargets: e.approvedTargets,
3786
+ nativeTokenLimitPerTransaction: e.nativeTokenLimitPerTransaction
3787
+ };
3788
+ return e.expiresAt != null && e.expiresAt > 0 ? {
3789
+ ...t,
3790
+ permissionEndTimestamp: /* @__PURE__ */ new Date(e.expiresAt * 1e3)
3791
+ } : t;
3792
+ }
3793
+ //#endregion
3794
+ //#region src/services/publishAuthorization/index.ts
3795
+ var Uo = "0x0000000000000000000000000000000000000000", Wo = !0, Go = "0x0000000000000000000000000000000000000000";
3796
+ function Ko(e) {
3797
+ if (m(e)) return e.txSender;
3798
+ if (n(e)) return e;
3799
+ throw Error("@seedprotocol/publish: publish authorization write APIs require a PublishWallet or SeedTxSender");
3800
+ }
3801
+ async function qo(e, t) {
3802
+ let n = await e.sendTransaction(t);
3803
+ return T(n.transactionHash);
3804
+ }
3805
+ function Jo(e, t) {
3806
+ let n = t.trim();
3807
+ if (!/^0x[0-9a-fA-F]{40}$/.test(n)) throw Error(`@seedprotocol/publish: ${e} must be a valid address`);
3808
+ return n;
3809
+ }
3810
+ function Yo() {
3811
+ return Nt.getSchemaUID(mt, Uo, Wo);
3812
+ }
3813
+ async function Xo(e) {
3814
+ let t = Ko(e), n = Yo();
3815
+ return await B(n) || (await qo(t, on({
3816
+ schema: mt,
3817
+ resolverAddress: Uo,
3818
+ revocable: Wo
3819
+ })), await qo(t, cn({
3820
+ schemaUid: n,
3821
+ schemaName: gt
3822
+ }))), n;
3823
+ }
3824
+ function Zo(e) {
3825
+ return new Mt(mt).encodeData([
3826
+ {
3827
+ name: "identity",
3828
+ value: e.identity,
3829
+ type: "address"
3830
+ },
3831
+ {
3832
+ name: "sessionKey",
3833
+ value: e.sessionKey,
3834
+ type: "address"
3835
+ },
3836
+ {
3837
+ name: "app",
3838
+ value: e.app,
3839
+ type: "address"
3840
+ },
3841
+ {
3842
+ name: "scopes",
3843
+ value: e.scopes,
3844
+ type: "string"
3845
+ },
3846
+ {
3847
+ name: "grantedAt",
3848
+ value: e.grantedAt,
3849
+ type: "uint64"
3850
+ },
3851
+ {
3852
+ name: "expiresAt",
3853
+ value: e.expiresAt,
3854
+ type: "uint64"
3855
+ },
3856
+ {
3857
+ name: "permissionsHash",
3858
+ value: wt(e.permissionsHash),
3859
+ type: "bytes32"
3860
+ }
3861
+ ]);
3862
+ }
3863
+ async function Qo(e) {
3864
+ let t = Ko(e.wallet), n = e.ensureSchema === !1 ? Yo() : await Xo(e.wallet), r = Jo("identity", e.identity), i = Jo("sessionKey", e.sessionKey), a = e.app?.trim() ? Jo("app", e.app) : Go, s = e.grantedAt ?? Math.floor(Date.now() / 1e3), c = typeof e.expiresAt == "number" && e.expiresAt > 0 ? Math.trunc(e.expiresAt) : 0, l = e.scopes ?? vt, u = wt(e.permissionsHash ?? Vo(Bo({ expiresAt: c > 0 ? c : void 0 }), l === vt ? "publish,revoke" : l));
3865
+ if (u === Ft) throw Error("@seedprotocol/publish: attestPublishAuthorization requires a non-zero permissionsHash");
3866
+ let d = typeof e.expirationTime == "number" && e.expirationTime > 0 ? e.expirationTime : c > 0 ? c : s + pt, p = Zo({
3867
+ identity: r,
3868
+ sessionKey: i,
3869
+ app: a,
3870
+ scopes: l,
3871
+ grantedAt: s,
3872
+ expiresAt: c,
3873
+ permissionsHash: u
3874
+ }), m = await qo(t, o({
3875
+ schema: n,
3876
+ data: {
3877
+ recipient: i,
3878
+ expirationTime: BigInt(d),
3879
+ revocable: !0,
3880
+ refUID: Ft,
3881
+ data: p,
3882
+ value: 0n
3883
+ }
3884
+ }));
3885
+ if (!m) throw Error("@seedprotocol/publish: attestPublishAuthorization failed — no receipt");
3886
+ let { easContractAddress: h } = w(), g = f(m, h);
3887
+ if (!g || !Ct(g)) throw Error("@seedprotocol/publish: attestPublishAuthorization failed — could not parse attestation UID");
3888
+ return {
3889
+ uid: g,
3890
+ schemaUid: n,
3891
+ permissionsHash: u,
3892
+ grantedAt: s,
3893
+ expiresAt: c,
3894
+ expirationTime: d
3895
+ };
3896
+ }
3897
+ async function $o(e) {
3898
+ let t = Ko(e.wallet), n = e.schemaUid ?? Yo(), r = wt(e.uid);
3899
+ if (!Ct(r)) throw Error("@seedprotocol/publish: revokePublishAuthorization requires a valid attestation uid");
3900
+ if (!await qo(t, p([{
3901
+ schema: n,
3902
+ data: [{ uid: r }]
3903
+ }]))) throw Error("@seedprotocol/publish: revokePublishAuthorization failed — no receipt");
3904
+ }
3905
+ async function es(e) {
3906
+ let t = (await St({
3907
+ identities: e.identities,
3908
+ excludeRevoked: !1
3909
+ })).find((t) => t.id?.toLowerCase() === e.uid.toLowerCase());
3910
+ if (!t) return null;
3911
+ let n = xt(t.decodedDataJson ?? "[]"), r = typeof t.expirationTime == "number" ? t.expirationTime : typeof t.expirationTime == "string" ? Number(t.expirationTime) : null;
3912
+ return {
3913
+ uid: t.id,
3914
+ decoded: n,
3915
+ assess: bt({
3916
+ decoded: n,
3917
+ expirationTime: r
3918
+ }),
3919
+ expirationTime: r
3920
+ };
3921
+ }
3922
+ //#endregion
3923
+ export { Kt as $, Kr as A, Nr as B, pi as C, Wr as D, Gr as E, Rr as F, Wn as G, Lr as H, ti as I, cn as J, or as K, zr as L, Qr as M, ei as N, Ur as O, Mr as P, en as Q, Br as R, mi as S, Hr as T, Ir as U, Or as V, Fr as W, on as X, B as Y, z as Z, ea as _, Qo as a, Ci as b, Yo as c, Bo as d, qt as et, Vo as f, ka as g, Lo as h, es as i, Jr as j, qr as k, $o as l, Ro as m, _t as n, Zo as o, Ho as p, vn as q, yt as r, Xo as s, ht as t, zo as u, ta as v, ri as w, li as x, xi as y, Vr as z };
3924
+
3925
+ //# sourceMappingURL=publishAuthorization-BEqRnP2h.js.map