@seedprotocol/publish 0.4.31 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +64 -18
  3. package/dist/config-Q3y4Fab2.js +936 -0
  4. package/dist/config-Q3y4Fab2.js.map +1 -0
  5. package/dist/config-bUKEs4Uf.js +511 -0
  6. package/dist/config-bUKEs4Uf.js.map +1 -0
  7. package/dist/config.d.ts +42 -4
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/ensureManagedAccountEasConfigured-BXF7gQCi.js +1270 -0
  10. package/dist/ensureManagedAccountEasConfigured-BXF7gQCi.js.map +1 -0
  11. package/dist/ensureManagedAccountEasConfigured-BxdK_Vhf.js +1204 -0
  12. package/dist/ensureManagedAccountEasConfigured-BxdK_Vhf.js.map +1 -0
  13. package/dist/ensureManagedAccountEasConfigured-CZGguM7q.js +1177 -0
  14. package/dist/ensureManagedAccountEasConfigured-CZGguM7q.js.map +1 -0
  15. package/dist/ensureManagedAccountEasConfigured-CZS__-ha.js +1177 -0
  16. package/dist/ensureManagedAccountEasConfigured-CZS__-ha.js.map +1 -0
  17. package/dist/ensureManagedAccountEasConfigured-D2_Jjjxt.js +1192 -0
  18. package/dist/ensureManagedAccountEasConfigured-D2_Jjjxt.js.map +1 -0
  19. package/dist/ensureManagedAccountEasConfigured-DDFBEb-B.js +1192 -0
  20. package/dist/ensureManagedAccountEasConfigured-DDFBEb-B.js.map +1 -0
  21. package/dist/ensureManagedAccountEasConfigured-zcyqhWPe.js +1270 -0
  22. package/dist/ensureManagedAccountEasConfigured-zcyqhWPe.js.map +1 -0
  23. package/dist/ensureModularPublishBootstrap-2agkGdih.js +124 -0
  24. package/dist/ensureModularPublishBootstrap-2agkGdih.js.map +1 -0
  25. package/dist/ensureModularPublishBootstrap-B5i_dQrv.js +124 -0
  26. package/dist/ensureModularPublishBootstrap-B5i_dQrv.js.map +1 -0
  27. package/dist/ensureModularPublishBootstrap-BSXyZgld.js +124 -0
  28. package/dist/ensureModularPublishBootstrap-BSXyZgld.js.map +1 -0
  29. package/dist/ensureModularPublishBootstrap-C0gx7sbt.js +124 -0
  30. package/dist/ensureModularPublishBootstrap-C0gx7sbt.js.map +1 -0
  31. package/dist/ensureModularPublishBootstrap-DHNo4j6X.js +124 -0
  32. package/dist/ensureModularPublishBootstrap-DHNo4j6X.js.map +1 -0
  33. package/dist/ensureModularPublishBootstrap-DQ-oruO1.js +124 -0
  34. package/dist/ensureModularPublishBootstrap-DQ-oruO1.js.map +1 -0
  35. package/dist/ensureModularPublishBootstrap-QRGGgnkz.js +124 -0
  36. package/dist/ensureModularPublishBootstrap-QRGGgnkz.js.map +1 -0
  37. package/dist/ensureSmartWalletThenPublish-BmeIFGIX.js +47 -0
  38. package/dist/ensureSmartWalletThenPublish-BmeIFGIX.js.map +1 -0
  39. package/dist/ensureSmartWalletThenPublish-CR4N0M9S.js +47 -0
  40. package/dist/ensureSmartWalletThenPublish-CR4N0M9S.js.map +1 -0
  41. package/dist/ensureSmartWalletThenPublish-CRza0sML.js +47 -0
  42. package/dist/ensureSmartWalletThenPublish-CRza0sML.js.map +1 -0
  43. package/dist/ensureSmartWalletThenPublish-DzOnwM-9.js +47 -0
  44. package/dist/ensureSmartWalletThenPublish-DzOnwM-9.js.map +1 -0
  45. package/dist/ensureSmartWalletThenPublish-UFczP8th.js +47 -0
  46. package/dist/ensureSmartWalletThenPublish-UFczP8th.js.map +1 -0
  47. package/dist/ensureSmartWalletThenPublish-k085lqDO.js +47 -0
  48. package/dist/ensureSmartWalletThenPublish-k085lqDO.js.map +1 -0
  49. package/dist/ensureSmartWalletThenPublish-xcHGv06S.js +47 -0
  50. package/dist/ensureSmartWalletThenPublish-xcHGv06S.js.map +1 -0
  51. package/dist/helpers/abi/eas.d.ts +203 -0
  52. package/dist/helpers/abi/eas.d.ts.map +1 -0
  53. package/dist/helpers/abi/executor.d.ts +33 -0
  54. package/dist/helpers/abi/executor.d.ts.map +1 -0
  55. package/dist/helpers/abi/factory.d.ts +31 -0
  56. package/dist/helpers/abi/factory.d.ts.map +1 -0
  57. package/dist/helpers/abi/publisher.d.ts +199 -0
  58. package/dist/helpers/abi/publisher.d.ts.map +1 -0
  59. package/dist/helpers/abi/schemaRegistry.d.ts +45 -0
  60. package/dist/helpers/abi/schemaRegistry.d.ts.map +1 -0
  61. package/dist/helpers/adapters/eip1193.d.ts +17 -0
  62. package/dist/helpers/adapters/eip1193.d.ts.map +1 -0
  63. package/dist/helpers/adapters/permissionlessTxSender.d.ts +11 -0
  64. package/dist/helpers/adapters/permissionlessTxSender.d.ts.map +1 -0
  65. package/dist/helpers/adapters/thirdwebAccount.d.ts +13 -0
  66. package/dist/helpers/adapters/thirdwebAccount.d.ts.map +1 -0
  67. package/dist/helpers/arweave.d.ts +4 -4
  68. package/dist/helpers/arweave.d.ts.map +1 -1
  69. package/dist/helpers/chainClient.d.ts +15 -0
  70. package/dist/helpers/chainClient.d.ts.map +1 -0
  71. package/dist/helpers/chainConfig.d.ts +12 -0
  72. package/dist/helpers/chainConfig.d.ts.map +1 -0
  73. package/dist/helpers/constants.d.ts +1 -2
  74. package/dist/helpers/constants.d.ts.map +1 -1
  75. package/dist/helpers/contracts/index.d.ts +90 -0
  76. package/dist/helpers/contracts/index.d.ts.map +1 -0
  77. package/dist/helpers/defaultChain.d.ts +4 -0
  78. package/dist/helpers/defaultChain.d.ts.map +1 -0
  79. package/dist/helpers/easDirect.d.ts +7 -76
  80. package/dist/helpers/easDirect.d.ts.map +1 -1
  81. package/dist/helpers/ensureEip7702ModularAccountReady.d.ts +1 -4
  82. package/dist/helpers/ensureEip7702ModularAccountReady.d.ts.map +1 -1
  83. package/dist/helpers/ensureExecutorModule.d.ts +1 -9
  84. package/dist/helpers/ensureExecutorModule.d.ts.map +1 -1
  85. package/dist/helpers/ensureManagedAccountEasConfigured.d.ts +2 -5
  86. package/dist/helpers/ensureManagedAccountEasConfigured.d.ts.map +1 -1
  87. package/dist/helpers/ensureManagedAccountReady.d.ts.map +1 -1
  88. package/dist/helpers/ensureManagedSignerSessionKey.d.ts +1 -0
  89. package/dist/helpers/ensureManagedSignerSessionKey.d.ts.map +1 -1
  90. package/dist/helpers/ensureSmartWalletThenPublish.d.ts +3 -13
  91. package/dist/helpers/ensureSmartWalletThenPublish.d.ts.map +1 -1
  92. package/dist/helpers/ensureWalletThenPublish.d.ts +21 -0
  93. package/dist/helpers/ensureWalletThenPublish.d.ts.map +1 -0
  94. package/dist/helpers/nameSchemaAttestation.d.ts +7 -0
  95. package/dist/helpers/nameSchemaAttestation.d.ts.map +1 -0
  96. package/dist/helpers/publishWalletRegistry.d.ts +19 -0
  97. package/dist/helpers/publishWalletRegistry.d.ts.map +1 -0
  98. package/dist/helpers/resolvePublishWallet.d.ts +7 -0
  99. package/dist/helpers/resolvePublishWallet.d.ts.map +1 -0
  100. package/dist/helpers/schemaRegistry.d.ts +11 -0
  101. package/dist/helpers/schemaRegistry.d.ts.map +1 -0
  102. package/dist/helpers/seedSigner.d.ts +62 -0
  103. package/dist/helpers/seedSigner.d.ts.map +1 -0
  104. package/dist/helpers/thirdweb.d.ts +14 -2
  105. package/dist/helpers/thirdweb.d.ts.map +1 -1
  106. package/dist/index.d.ts +11 -11
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +283 -5171
  109. package/dist/index.js.map +1 -1
  110. package/dist/publishManager-1vLf1ZHv.js +3005 -0
  111. package/dist/publishManager-1vLf1ZHv.js.map +1 -0
  112. package/dist/publishManager-5hUL8Of5.js +3007 -0
  113. package/dist/publishManager-5hUL8Of5.js.map +1 -0
  114. package/dist/publishManager-BO4sSSvo.js +3007 -0
  115. package/dist/publishManager-BO4sSSvo.js.map +1 -0
  116. package/dist/publishManager-BOICv9Yl.js +3008 -0
  117. package/dist/publishManager-BOICv9Yl.js.map +1 -0
  118. package/dist/publishManager-CCXWxiT1.js +3008 -0
  119. package/dist/publishManager-CCXWxiT1.js.map +1 -0
  120. package/dist/publishManager-Ccot_poQ.js +3008 -0
  121. package/dist/publishManager-Ccot_poQ.js.map +1 -0
  122. package/dist/publishManager-De3uWE-p.js +3007 -0
  123. package/dist/publishManager-De3uWE-p.js.map +1 -0
  124. package/dist/react/ConnectButton.d.ts.map +1 -1
  125. package/dist/react/PublishConfigContext.d.ts +4 -0
  126. package/dist/react/PublishConfigContext.d.ts.map +1 -0
  127. package/dist/react/PublishProvider.d.ts +7 -1
  128. package/dist/react/PublishProvider.d.ts.map +1 -1
  129. package/dist/react/PublishProvider.thirdweb.d.ts +11 -0
  130. package/dist/react/PublishProvider.thirdweb.d.ts.map +1 -0
  131. package/dist/react/useSeedWallet.d.ts +17 -0
  132. package/dist/react/useSeedWallet.d.ts.map +1 -0
  133. package/dist/resolveRevokeAccount-BGVjf-kI.js +30 -0
  134. package/dist/resolveRevokeAccount-BGVjf-kI.js.map +1 -0
  135. package/dist/resolveRevokeAccount-BRwOBTJ4.js +30 -0
  136. package/dist/resolveRevokeAccount-BRwOBTJ4.js.map +1 -0
  137. package/dist/resolveRevokeAccount-C0ZWAcHX.js +30 -0
  138. package/dist/resolveRevokeAccount-C0ZWAcHX.js.map +1 -0
  139. package/dist/resolveRevokeAccount-CKcr55EY.js +30 -0
  140. package/dist/resolveRevokeAccount-CKcr55EY.js.map +1 -0
  141. package/dist/resolveRevokeAccount-DNvuOQ1c.js +30 -0
  142. package/dist/resolveRevokeAccount-DNvuOQ1c.js.map +1 -0
  143. package/dist/resolveRevokeAccount-DvEPXZKI.js +30 -0
  144. package/dist/resolveRevokeAccount-DvEPXZKI.js.map +1 -0
  145. package/dist/resolveRevokeAccount-rOof3dUA.js +30 -0
  146. package/dist/resolveRevokeAccount-rOof3dUA.js.map +1 -0
  147. package/dist/seedSigner-BvK5WjmV.js +66 -0
  148. package/dist/seedSigner-BvK5WjmV.js.map +1 -0
  149. package/dist/services/PublishManager/actions/createPublish.d.ts.map +1 -1
  150. package/dist/services/PublishManager/actions/retryAttestations.d.ts +3 -2
  151. package/dist/services/PublishManager/actions/retryAttestations.d.ts.map +1 -1
  152. package/dist/services/PublishManager/actors/restoreFromDb.d.ts.map +1 -1
  153. package/dist/services/PublishManager/index.d.ts +2 -2
  154. package/dist/services/PublishManager/index.d.ts.map +1 -1
  155. package/dist/services/publish/actors/checking.d.ts.map +1 -1
  156. package/dist/services/publish/actors/createArweaveDataItems.d.ts.map +1 -1
  157. package/dist/services/publish/actors/createAttestations.d.ts.map +1 -1
  158. package/dist/services/publish/actors/createAttestationsDirectToEas.d.ts.map +1 -1
  159. package/dist/services/publish/actors/seedUidHelpers.d.ts +1 -17
  160. package/dist/services/publish/actors/seedUidHelpers.d.ts.map +1 -1
  161. package/dist/services/publish/helpers/ensureEasSchemas.d.ts +2 -5
  162. package/dist/services/publish/helpers/ensureEasSchemas.d.ts.map +1 -1
  163. package/dist/services/publish/helpers/receiptAttestationMs.d.ts +1 -3
  164. package/dist/services/publish/helpers/receiptAttestationMs.d.ts.map +1 -1
  165. package/dist/services/publish/index.d.ts.map +1 -1
  166. package/dist/services/revoke/revokeAttestations.d.ts +1 -3
  167. package/dist/services/revoke/revokeAttestations.d.ts.map +1 -1
  168. package/dist/services/upload/uploadMachine.d.ts +1 -1
  169. package/dist/thirdweb.d.ts +17 -0
  170. package/dist/thirdweb.d.ts.map +1 -0
  171. package/dist/thirdweb.js +176 -0
  172. package/dist/thirdweb.js.map +1 -0
  173. package/dist/types.d.ts +9 -4
  174. package/dist/types.d.ts.map +1 -1
  175. package/dist/worker-B3R2zwxm.js +69 -0
  176. package/dist/worker-B3R2zwxm.js.map +1 -0
  177. package/dist/worker-BVc0OzNI.js +105 -0
  178. package/dist/worker-BVc0OzNI.js.map +1 -0
  179. package/dist/worker-BWERw2Le.js +69 -0
  180. package/dist/worker-BWERw2Le.js.map +1 -0
  181. package/dist/worker-Bb3a6nOf.js +69 -0
  182. package/dist/worker-Bb3a6nOf.js.map +1 -0
  183. package/dist/worker-BqeFFnN_.js +69 -0
  184. package/dist/worker-BqeFFnN_.js.map +1 -0
  185. package/dist/worker-CqCsdQeT.js +69 -0
  186. package/dist/worker-CqCsdQeT.js.map +1 -0
  187. package/dist/worker-QZN_HMAs.js +69 -0
  188. package/dist/worker-QZN_HMAs.js.map +1 -0
  189. package/dist/worker-VilzVQ8C.js +69 -0
  190. package/dist/worker-VilzVQ8C.js.map +1 -0
  191. package/dist/worker-j_9ajZZU.js +100 -0
  192. package/dist/worker-j_9ajZZU.js.map +1 -0
  193. package/package.json +20 -5
@@ -0,0 +1,3008 @@
1
+ import { $ as e, A as t, Ct as n, E as r, Et as i, G as a, K as o, N as s, O as c, Q as l, St as u, Tt as d, Y as f, Z as p, _t as m, a as h, bt as g, c as _, ct as v, d as ee, et as y, ft as b, g as te, h as ne, ht as re, i as ie, k as ae, l as oe, nt as se, o as ce, ot as le, pt as ue, q as de, rt as fe, t as pe, tt as me, u as he, v as ge, w as _e, xt as ve } from "./ensureManagedAccountEasConfigured-zcyqhWPe.js";
2
+ import { BaseArweaveClient as ye, BaseDb as x, BaseFileManager as S, INTERNAL_DATA_TYPES as be, Item as C, ModelPropertyDataTypes as xe, applyPropertyAttestationUidsFromPublish as Se, arweaveL1FinalizeJobs as Ce, getCorrectId as we, getEasSchemaForItemProperty as Te, getItemPropertiesFromEas as Ee, getRelatedItemsForPublish as De, getSegmentedItemProperties as Oe, getUploadPipelineTransactionStatus as ke, htmlEmbeddedImageCoPublish as Ae, isItemOwned as je, itemHasPublishUploadCandidates as Me, prepareHtmlEmbeddedImagesForPublish as Ne, publishProcesses as w, resolvePublishPayloadValues as Pe, rewriteHtmlEmbeddedImagesOnDisk as Fe, setSchemaUidForModel as Ie, setSchemaUidForSchemaDefinition as T, updateVersionUid as Le, validateItemForPublish as Re } from "@seedprotocol/sdk";
3
+ import { decodeAbiParameters as ze, encodeAbiParameters as Be, parseEventLogs as E } from "viem";
4
+ import { getContract as Ve, sendTransaction as He } from "thirdweb";
5
+ import { optimismSepolia as Ue } from "thirdweb/chains";
6
+ import { ethers as D } from "ethers";
7
+ import { NO_EXPIRATION as We, SchemaEncoder as Ge, SchemaRegistry as Ke, ZERO_ADDRESS as qe, ZERO_BYTES32 as Je } from "@ethereum-attestation-service/eas-sdk";
8
+ import { assign as O, createActor as Ye, enqueueActions as Xe, fromCallback as k, fromPromise as A, setup as Ze } from "xstate";
9
+ import Qe from "arweave";
10
+ import j from "debug";
11
+ import { and as $e, desc as et, eq as M } from "drizzle-orm";
12
+ import { getInstalledModules as tt, installModule as nt } from "thirdweb/modules";
13
+ //#region src/helpers/schemaRegistry.ts
14
+ async function rt(e) {
15
+ return b(e);
16
+ }
17
+ function it(e) {
18
+ return v(e);
19
+ }
20
+ //#endregion
21
+ //#region src/helpers/nameSchemaAttestation.ts
22
+ var at = "0x0000000000000000000000000000000000000000";
23
+ function ot(e) {
24
+ let t = new Ge("bytes32 schemaId,string name").encodeData([{
25
+ name: "schemaId",
26
+ value: e.schemaUid,
27
+ type: "bytes32"
28
+ }, {
29
+ name: "name",
30
+ value: e.schemaName,
31
+ type: "string"
32
+ }]);
33
+ return fe({
34
+ schema: u,
35
+ data: {
36
+ recipient: at,
37
+ expirationTime: BigInt(We),
38
+ revocable: !0,
39
+ refUID: Je,
40
+ data: t,
41
+ value: 0n
42
+ }
43
+ });
44
+ }
45
+ //#endregion
46
+ //#region src/services/publish/helpers/ensureEasSchemas.ts
47
+ var N = "0x0000000000000000000000000000000000000000", P = !0;
48
+ function st(e) {
49
+ return e.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
50
+ }
51
+ async function ct(e) {
52
+ let { itemRelationProperties: t, itemImageProperties: n, itemListProperties: r } = await Oe(e), i = /* @__PURE__ */ new Set();
53
+ e.modelName && i.add(e.modelName);
54
+ for (let e of t) {
55
+ let t = e.propertyDef?.ref;
56
+ t && i.add(t);
57
+ }
58
+ for (let e of n) {
59
+ let t = e.propertyDef?.dataType;
60
+ t === "File" ? i.add("File") : t === "Html" ? i.add("Html") : i.add("Image");
61
+ }
62
+ for (let e of r) {
63
+ let t = e.propertyDef?.ref;
64
+ t && i.add(t);
65
+ }
66
+ return i;
67
+ }
68
+ async function F(e, t) {
69
+ await m((await e.sendTransaction(t)).transactionHash);
70
+ }
71
+ async function I(e, t) {
72
+ let n = a(t) ? t.txSender : de(t) ? t : (() => {
73
+ throw Error("@seedprotocol/publish: ensureEasSchemasForItem requires a PublishWallet or SeedTxSender");
74
+ })(), { itemBasicProperties: r, itemRelationProperties: i, itemImageProperties: o, itemListProperties: s } = await Oe(e), c = [
75
+ ...r,
76
+ ...i,
77
+ ...o,
78
+ ...s
79
+ ], l = /* @__PURE__ */ new Set(), u = await ct(e), d = /* @__PURE__ */ new Set();
80
+ for (let e of u) {
81
+ let t = `bytes32 ${st(e)}`, r = Ke.getSchemaUID(t, N, P);
82
+ if (await rt(r)) {
83
+ Ie({
84
+ modelName: e,
85
+ schemaUid: r
86
+ });
87
+ continue;
88
+ }
89
+ if (d.has(r)) {
90
+ Ie({
91
+ modelName: e,
92
+ schemaUid: r
93
+ });
94
+ continue;
95
+ }
96
+ try {
97
+ await F(n, it({
98
+ schema: t,
99
+ resolverAddress: N,
100
+ revocable: P
101
+ }));
102
+ } catch (t) {
103
+ throw Error(`Failed to register EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
104
+ }
105
+ try {
106
+ await F(n, ot({
107
+ schemaUid: r,
108
+ schemaName: st(e)
109
+ }));
110
+ } catch (t) {
111
+ throw Error(`Failed to name EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
112
+ }
113
+ d.add(r), Ie({
114
+ modelName: e,
115
+ schemaUid: r
116
+ });
117
+ }
118
+ let f = "string storage_transaction_id", p = Ke.getSchemaUID(f, N, P);
119
+ if (await rt(p)) T({
120
+ text: f,
121
+ schemaUid: p
122
+ });
123
+ else if (!l.has(p) && (u.has("Image") || u.has("File") || u.has("Html"))) {
124
+ try {
125
+ await F(n, it({
126
+ schema: f,
127
+ resolverAddress: N,
128
+ revocable: P
129
+ })), await F(n, ot({
130
+ schemaUid: p,
131
+ schemaName: "storage_transaction_id"
132
+ }));
133
+ } catch (e) {
134
+ throw Error(`Failed to register EAS schema for storageTransactionId: ${e instanceof Error ? e.message : String(e)}`);
135
+ }
136
+ l.add(p), T({
137
+ text: f,
138
+ schemaUid: p
139
+ });
140
+ }
141
+ for (let e of c) {
142
+ if (!e.propertyDef) continue;
143
+ let t = be[e.propertyDef.dataType]?.eas ?? "string", r = e, i = r.storagePropertyName && r.storagePropertyName.length > 0 ? r.storagePropertyName : e.propertyName, a = st(i), o = `${t} ${a}`, s = [
144
+ "string",
145
+ "address",
146
+ "bool",
147
+ "bytes",
148
+ "bytes32",
149
+ "uint8",
150
+ "uint16",
151
+ "uint32",
152
+ "uint64",
153
+ "uint128",
154
+ "uint256"
155
+ ].includes(t) ? t : void 0, c = await Te({
156
+ schemaUid: e.schemaUid,
157
+ propertyName: i,
158
+ easDataType: s
159
+ });
160
+ if (c) {
161
+ let e = await rt(c.id);
162
+ if (e && e.schema === o) {
163
+ T({
164
+ text: o,
165
+ schemaUid: c.id
166
+ });
167
+ continue;
168
+ }
169
+ }
170
+ let u = Ke.getSchemaUID(o, N, P);
171
+ if (await rt(u)) {
172
+ T({
173
+ text: o,
174
+ schemaUid: u
175
+ });
176
+ continue;
177
+ }
178
+ if (l.has(u)) {
179
+ T({
180
+ text: o,
181
+ schemaUid: u
182
+ });
183
+ continue;
184
+ }
185
+ try {
186
+ await F(n, it({
187
+ schema: o,
188
+ resolverAddress: N,
189
+ revocable: P
190
+ }));
191
+ } catch (t) {
192
+ throw Error(`Failed to register EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
193
+ }
194
+ try {
195
+ await F(n, ot({
196
+ schemaUid: u,
197
+ schemaName: a
198
+ }));
199
+ } catch (t) {
200
+ throw Error(`Failed to name EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
201
+ }
202
+ l.add(u), T({
203
+ text: o,
204
+ schemaUid: u
205
+ });
206
+ }
207
+ let m = await De(e);
208
+ for (let e of m) await I(e, n);
209
+ }
210
+ //#endregion
211
+ //#region src/helpers/blockchain.ts
212
+ var L = () => {
213
+ let e = ye.getHost(), t = Qe;
214
+ return Object.keys(t).includes("default") && t.default ? t.default.init({
215
+ host: e,
216
+ protocol: "https"
217
+ }) : t.init({
218
+ host: e,
219
+ protocol: "https"
220
+ });
221
+ }, R = "0x" + "0".repeat(64), z = async (e) => {
222
+ let t;
223
+ try {
224
+ t = await C.find({ seedLocalId: e });
225
+ } catch {}
226
+ return t || new Promise((t) => {
227
+ let n = setInterval(() => {
228
+ try {
229
+ C.find({ seedLocalId: e }).then((e) => {
230
+ e && (clearInterval(n), t(e));
231
+ });
232
+ } catch {}
233
+ }, 200);
234
+ });
235
+ };
236
+ function lt(e) {
237
+ if (!e || typeof e != "object") return;
238
+ let t = e;
239
+ if (Array.isArray(t.data_root)) return {
240
+ data_root: new Uint8Array(t.data_root),
241
+ chunks: (t.chunks ?? []).map((e) => ({
242
+ ...e,
243
+ dataHash: new Uint8Array(e.dataHash ?? [])
244
+ })),
245
+ proofs: (t.proofs ?? []).map((e) => ({
246
+ ...e,
247
+ proof: new Uint8Array(e.proof ?? [])
248
+ }))
249
+ };
250
+ }
251
+ function ut(e) {
252
+ return {
253
+ data_root: Array.from(e.data_root),
254
+ chunks: e.chunks.map((e) => ({
255
+ ...e,
256
+ dataHash: Array.from(e.dataHash)
257
+ })),
258
+ proofs: e.proofs.map((e) => ({
259
+ ...e,
260
+ proof: Array.from(e.proof)
261
+ }))
262
+ };
263
+ }
264
+ //#endregion
265
+ //#region src/services/publish/actors/createArweaveTransactions.ts
266
+ var dt = A(async ({ input: { context: e } }) => {
267
+ let { item: t } = e;
268
+ t.getPublishUploads || (t = await z(t.seedLocalId));
269
+ let n = {};
270
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
271
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
272
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
273
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = s(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, c = e.arweaveJwk ?? a.arweaveJwk, l = i.map((e) => ({
274
+ versionLocalId: e.versionLocalId,
275
+ itemPropertyName: e.itemPropertyName,
276
+ transactionJson: e.transactionToSign.toJSON()
277
+ })), u;
278
+ if (o) u = await o(l);
279
+ else if (c) {
280
+ let e = L(), t = c;
281
+ u = [];
282
+ for (let n of l) {
283
+ let r = e.transactions.fromRaw(n.transactionJson);
284
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
285
+ let i = r.toJSON();
286
+ u.push({
287
+ transaction: {
288
+ ...i,
289
+ chunks: r.chunks ? ut(r.chunks) : void 0
290
+ },
291
+ versionId: n.versionLocalId,
292
+ modelName: n.itemPropertyName
293
+ });
294
+ }
295
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
296
+ let d = L();
297
+ return {
298
+ arweaveTransactions: u.map((e) => {
299
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = lt(t);
300
+ return i && (r.chunks = i), {
301
+ transaction: d.transactions.fromRaw(r),
302
+ versionId: e.versionId,
303
+ modelName: e.modelName
304
+ };
305
+ }),
306
+ publishUploads: i
307
+ };
308
+ }), ft = A(async ({ input: { context: e } }) => {
309
+ let { item: t } = e;
310
+ t.getPublishUploads || (t = await z(t.seedLocalId));
311
+ let n = {};
312
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
313
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
314
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
315
+ let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = s(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, c = e.arweaveJwk ?? a.arweaveJwk, l = i.map((e) => ({
316
+ versionLocalId: e.versionLocalId,
317
+ itemPropertyName: e.itemPropertyName,
318
+ transactionJson: e.transactionToSign.toJSON()
319
+ })), u;
320
+ if (o) u = await o(l);
321
+ else if (c) {
322
+ let e = L(), t = c;
323
+ u = [];
324
+ for (let n of l) {
325
+ let r = e.transactions.fromRaw(n.transactionJson);
326
+ r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
327
+ let i = r.toJSON();
328
+ u.push({
329
+ transaction: {
330
+ ...i,
331
+ chunks: r.chunks ? ut(r.chunks) : void 0
332
+ },
333
+ versionId: n.versionLocalId,
334
+ modelName: n.itemPropertyName
335
+ });
336
+ }
337
+ } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
338
+ let d = L();
339
+ return {
340
+ arweaveTransactions: u.map((e) => {
341
+ let { chunks: t, ...n } = e.transaction, r = { ...n }, i = lt(t);
342
+ return i && (r.chunks = i), {
343
+ transaction: d.transactions.fromRaw(r),
344
+ versionId: e.versionId,
345
+ modelName: e.modelName
346
+ };
347
+ }),
348
+ publishUploads: i
349
+ };
350
+ }), pt = A(async ({ input: { context: e } }) => {
351
+ let t = e.htmlEmbeddedDataUriPolicy ?? "materialize";
352
+ return { deferredHtmlSeedLocalIds: (await Ne(e.item, t)).deferredHtmlSeedLocalIds };
353
+ });
354
+ //#endregion
355
+ //#region src/services/publish/actors/rewritingHtmlEmbedded.ts
356
+ function mt(e, t) {
357
+ let n = [], r = Math.min(e?.length ?? 0, t?.length ?? 0);
358
+ for (let i = 0; i < r; i++) {
359
+ let r = e[i], a = t[i], o = r.transaction?.id;
360
+ typeof o == "string" && o.length > 0 && n.push({
361
+ txId: o,
362
+ seedLocalId: a.seedLocalId,
363
+ versionLocalId: a.versionLocalId
364
+ });
365
+ }
366
+ return n;
367
+ }
368
+ var ht = A(async ({ input: { context: e } }) => {
369
+ let t = mt(e.htmlEmbeddedPhase1ArweaveTransactions, e.htmlEmbeddedPhase1PublishUploads);
370
+ await Fe(e.item.seedLocalId, t);
371
+ }), gt = (e, t, n) => {
372
+ let r = [];
373
+ return e && r.push({
374
+ name: "Content-SHA-256",
375
+ value: e
376
+ }), t && r.push({
377
+ name: "Content-Type",
378
+ value: t
379
+ }), n?.length && r.push(...n), r;
380
+ }, _t = async (e) => {
381
+ let t = (e instanceof Uint8Array, new Uint8Array(e)), n = await crypto.subtle.digest("SHA-256", t);
382
+ return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
383
+ }, vt = {
384
+ png: "image/png",
385
+ jpg: "image/jpeg",
386
+ jpeg: "image/jpeg",
387
+ gif: "image/gif",
388
+ webp: "image/webp",
389
+ svg: "image/svg+xml",
390
+ html: "text/html",
391
+ htm: "text/html",
392
+ json: "application/json",
393
+ txt: "text/plain"
394
+ }, yt = (e) => {
395
+ let t = e.split(".").pop()?.toLowerCase();
396
+ return t ? vt[t] : void 0;
397
+ }, bt = async (e) => typeof Blob < "u" && e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : new Uint8Array(e), xt = (e) => {
398
+ switch (e) {
399
+ case "Image": return S.getFilesPath("images");
400
+ case "File": return S.getFilesPath("files");
401
+ case "Html": return S.getFilesPath("html");
402
+ case "Json": return S.getFilesPath("json");
403
+ default: return S.getFilesPath("images");
404
+ }
405
+ }, St = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
406
+ function Ct(e) {
407
+ let t = St.exec((e ?? "").trim());
408
+ if (!t) return null;
409
+ try {
410
+ let e = t[1].toLowerCase().trim(), n = t[2].replace(/\s/g, "");
411
+ return {
412
+ mimeType: e,
413
+ bytes: Uint8Array.from(atob(n), (e) => e.charCodeAt(0))
414
+ };
415
+ } catch {
416
+ return null;
417
+ }
418
+ }
419
+ var wt = async (e, t, n, r) => {
420
+ let i = r?.arweaveUploadTags, a = e.itemProperty, o = [];
421
+ for (let t of e.childProperties) {
422
+ let e = t.localStoragePath;
423
+ !e || e.endsWith("undefined") || await S.pathExists(e) && o.push({
424
+ propertyName: t.propertyName,
425
+ localStoragePath: e
426
+ });
427
+ }
428
+ let s;
429
+ if ((!o || o.length === 0) && n?.localStoragePath) {
430
+ let e = n.localStoragePath;
431
+ if (e && !e.endsWith("undefined") && await S.pathExists(e)) try {
432
+ s = await bt(await S.readFileAsBuffer(e));
433
+ } catch {
434
+ s = await bt((await S.getFs()).readFileSync(e));
435
+ }
436
+ }
437
+ if (o.length > 0) {
438
+ let e = "===FILE_SEPARATOR===", t = "", n = await S.getFs();
439
+ for (let r of o) {
440
+ let i;
441
+ try {
442
+ i = await n.promises.readFile(r.localStoragePath);
443
+ } catch {
444
+ i = n.readFileSync(r.localStoragePath);
445
+ }
446
+ t += `${e}${r.propertyName}${e}${i}`;
447
+ }
448
+ s = typeof document < "u" ? new TextEncoder().encode(t) : new Uint8Array(Buffer.from(t));
449
+ }
450
+ if (!s) return t;
451
+ let c = new Uint8Array(s), l = await _t(c), u;
452
+ o.length === 0 && n?.localStoragePath ? u = yt(n.localStoragePath) : o.length > 0 && (u = "application/octet-stream");
453
+ let d = n ? n.localId : a.localId, f = n ? n.propertyName : a.propertyName;
454
+ return t.push({
455
+ data: c,
456
+ contentHash: l,
457
+ contentType: u,
458
+ tags: gt(l, u, i),
459
+ itemPropertyName: f,
460
+ itemPropertyLocalId: d,
461
+ seedLocalId: a.seedLocalId,
462
+ versionLocalId: a.versionLocalId
463
+ }), t;
464
+ }, Tt = async (e, t) => {
465
+ let n = [], r = t?.arweaveUploadTags;
466
+ for (let i of e) {
467
+ let e = i.getService().getSnapshot(), a = "context" in e ? e.context : null;
468
+ if (!a) continue;
469
+ let o = a.propertyValue, s = a.refResolvedValue;
470
+ if (!s) continue;
471
+ let { localId: c } = we(o ?? "");
472
+ if (!c) continue;
473
+ let l = i.propertyDef?.refValueType ?? i.propertyDef?.dataType ?? "Image";
474
+ if (l === xe.Html) {
475
+ if (t?.deferHtmlStorageSeedLocalIds?.includes(c) || t?.onlyHtmlStorageSeedLocalIds?.length && !t.onlyHtmlStorageSeedLocalIds.includes(c)) continue;
476
+ } else if (t?.onlyHtmlStorageSeedLocalIds?.length) continue;
477
+ let u = `${xt(l)}/${s}`;
478
+ if (!await S.pathExists(u)) continue;
479
+ let d = await bt(await S.readFileAsBuffer(u)), f = await _t(d), p = yt(s);
480
+ n.push({
481
+ data: d,
482
+ contentHash: f,
483
+ contentType: p,
484
+ tags: gt(f, p, r),
485
+ itemPropertyName: i.propertyName,
486
+ itemPropertyLocalId: i.localId,
487
+ seedLocalId: c,
488
+ versionLocalId: i.versionLocalId
489
+ });
490
+ }
491
+ return n;
492
+ };
493
+ async function Et(e, t, n) {
494
+ let r = x.getAppDb();
495
+ if (!r || n?.onlyHtmlStorageSeedLocalIds?.length) return t;
496
+ let i = await r.select().from(Ae).where(M(Ae.parentSeedLocalId, e.seedLocalId)), a = new Set(t.map((e) => e.seedLocalId));
497
+ for (let e of i) {
498
+ if (a.has(e.imageSeedLocalId)) continue;
499
+ let r = await C.find({
500
+ seedLocalId: e.imageSeedLocalId,
501
+ modelName: "Image"
502
+ });
503
+ if (!r) continue;
504
+ let i = r.internalProperties.storageTransactionId ?? r.allProperties.storageTransactionId, o = i?.getService().getSnapshot(), s = o && "context" in o ? o.context : void 0, c = Ct(typeof s?.propertyValue == "string" ? s.propertyValue ?? "" : ""), l = [];
505
+ if (c && i && i.localId && i.versionLocalId) {
506
+ let e = await _t(c.bytes);
507
+ l = [{
508
+ data: c.bytes,
509
+ contentHash: e,
510
+ contentType: c.mimeType,
511
+ tags: gt(e, c.mimeType, n?.arweaveUploadTags),
512
+ itemPropertyName: i.propertyName,
513
+ itemPropertyLocalId: i.localId,
514
+ seedLocalId: r.seedLocalId,
515
+ versionLocalId: i.versionLocalId
516
+ }];
517
+ }
518
+ for (let e of l) a.has(e.seedLocalId) || (t.push(e), a.add(e.seedLocalId));
519
+ }
520
+ return t;
521
+ }
522
+ var Dt = async (e, t = [], n, r) => {
523
+ let { itemUploadProperties: i, itemRelationProperties: a, itemImageProperties: o } = await Oe(e);
524
+ if (!n && r?.onlyHtmlStorageSeedLocalIds?.length) {
525
+ let e = await Tt(o, r);
526
+ return t.push(...e), t;
527
+ }
528
+ for (let e of i) t = await wt(e, t, n, r);
529
+ let s = await Tt(o, r);
530
+ if (t.push(...s), !n && !r?.onlyHtmlStorageSeedLocalIds?.length && (t = await Et(e, t, r)), r?.skipRelationRecursion) return t;
531
+ for (let e of a) {
532
+ let n = e.getService().getSnapshot(), i = "context" in n ? n.context : null;
533
+ if (!i) continue;
534
+ let a = i.propertyValue;
535
+ if (!a || e.uid) continue;
536
+ let { localId: o, uid: s } = we(a), c = await C.find({
537
+ seedLocalId: o,
538
+ seedUid: s
539
+ });
540
+ if (!c) throw Error(`No relatedItem found for ${e.propertyName}`);
541
+ t = await Dt(c, t, e, r);
542
+ }
543
+ return t;
544
+ }, Ot = 3, kt = new TextEncoder().encode("seed-recovery"), At = 32, jt = 18446744073709551615n;
545
+ function Mt(e, t, n) {
546
+ let r = D.solidityPackedKeccak256([
547
+ "uint256",
548
+ "address",
549
+ "uint64"
550
+ ], [
551
+ BigInt(t),
552
+ e,
553
+ n & jt
554
+ ]);
555
+ return D.getBytes(r);
556
+ }
557
+ function Nt(e) {
558
+ if (e.length === 0) return new Uint8Array([0]);
559
+ if (e.length !== At) throw Error(`ANS-104 target/anchor must be empty or ${At} bytes, got ${e.length}`);
560
+ let t = new Uint8Array(33);
561
+ return t[0] = 1, t.set(e, 1), t;
562
+ }
563
+ function Pt(e) {
564
+ return typeof e == "object" && !!e && "privateKey" in e && typeof e.privateKey == "string";
565
+ }
566
+ function Ft(e, t, n) {
567
+ let r = e >= 0 ? e << 1 : ~e << 1 | 1, i = n;
568
+ do {
569
+ let e = r & 127;
570
+ r >>>= 7, t[i++] = r ? e | 128 : e;
571
+ } while (r);
572
+ return i - n;
573
+ }
574
+ var It = (e) => {
575
+ if (!e?.length) return new Uint8Array();
576
+ let t = new TextEncoder(), n = new Uint8Array(16), r = [], i = (e) => {
577
+ let t = Ft(e, n, 0);
578
+ r.push(n.slice(0, t));
579
+ };
580
+ i(e.length);
581
+ for (let n of e) {
582
+ let e = t.encode(n.name), a = t.encode(n.value);
583
+ i(e.length), r.push(e), i(a.length), r.push(a);
584
+ }
585
+ i(0);
586
+ let a = r.reduce((e, t) => e + t.length, 0), o = new Uint8Array(a), s = 0;
587
+ for (let e of r) o.set(e, s), s += e.length;
588
+ return o;
589
+ }, Lt = (e) => {
590
+ let t = new Uint8Array(8), n = new DataView(t.buffer);
591
+ return n.setUint32(0, e & 4294967295, !0), n.setUint32(4, Math.floor(e / 4294967296), !0), t;
592
+ };
593
+ async function B(e) {
594
+ return new Uint8Array(await crypto.subtle.digest("SHA-384", e));
595
+ }
596
+ function Rt(e, t) {
597
+ let n = new Uint8Array(e.length + t.length);
598
+ return n.set(e, 0), n.set(t, e.length), n;
599
+ }
600
+ async function zt(e) {
601
+ let t = new TextEncoder();
602
+ if (Array.isArray(e)) {
603
+ let n = await B(Rt(t.encode("list"), t.encode(e.length.toString())));
604
+ for (let t of e) {
605
+ let e = await zt(t);
606
+ n = await B(Rt(n, e));
607
+ }
608
+ return n;
609
+ }
610
+ return B(Rt(await B(Rt(t.encode("blob"), t.encode(e.byteLength.toString()))), await B(e)));
611
+ }
612
+ async function Bt(e, t, n, r, i) {
613
+ let a = new TextEncoder();
614
+ return zt([
615
+ a.encode("dataitem"),
616
+ a.encode("1"),
617
+ a.encode(Ot.toString()),
618
+ e,
619
+ t,
620
+ n,
621
+ r,
622
+ i
623
+ ]);
624
+ }
625
+ function Vt(e, t, n, r, i) {
626
+ let a = It(t), o = Lt(t.length), s = Lt(a.length), c = [
627
+ e,
628
+ Nt(r),
629
+ Nt(i),
630
+ o,
631
+ s,
632
+ a,
633
+ n
634
+ ], l = c.reduce((e, t) => e + t.length, 0), u = new Uint8Array(l), d = 0;
635
+ for (let e of c) u.set(e, d), d += e.length;
636
+ return u;
637
+ }
638
+ async function Ht(e, t) {
639
+ let n = new Uint8Array(2);
640
+ new DataView(n.buffer).setUint16(0, Ot, !0);
641
+ let r = 67 + t.length, i = new Uint8Array(r);
642
+ i.set(n, 0), i.set(e, 2), i.set(t, 67);
643
+ let a = await crypto.subtle.digest("SHA-256", new Uint8Array(e));
644
+ return {
645
+ id: Jt(new Uint8Array(a)),
646
+ raw: i
647
+ };
648
+ }
649
+ var Ut = async (e, t, n, r = new Uint8Array()) => {
650
+ let i = D.SigningKey.computePublicKey(t.privateKey, !1), a = D.getBytes(i), o = It(n), s = new Uint8Array(), c = await Bt(a, s, r, o, e);
651
+ return Ht(D.getBytes(await t.signMessage(c)), Vt(a, n, e, s, r));
652
+ }, Wt = async (e, t, n, r = new Uint8Array()) => {
653
+ let i = D.hexlify(kt), a = await t.signMessage({ message: { raw: i } }), o = D.hashMessage(kt), s = D.SigningKey.recoverPublicKey(o, a), c = D.getBytes(s), l = It(n), u = new Uint8Array(), d = await Bt(c, u, r, l, e), f = D.hexlify(d), p = await t.signMessage({ message: { raw: f } });
654
+ return Ht(D.getBytes(p), Vt(c, n, e, u, r));
655
+ };
656
+ function Gt(e) {
657
+ if (e.length < 133) return null;
658
+ let t = e[132];
659
+ if (t !== 0 && t !== 1) return null;
660
+ let n = t === 1;
661
+ if (n && e.length < 165) return null;
662
+ let r = 132 + (n ? 33 : 1);
663
+ if (e.length < r + 1) return null;
664
+ let i = e[r];
665
+ if (i !== 0 && i !== 1) return null;
666
+ let a = i === 1;
667
+ return a && e.length < r + 33 ? null : r + (a ? 33 : 1);
668
+ }
669
+ function Kt(e) {
670
+ let t = Gt(e);
671
+ if (t == null) return null;
672
+ let n = e[132] === 1, r = n ? e.slice(133, 165) : new Uint8Array(), i = 132 + (n ? 33 : 1);
673
+ return {
674
+ rawTarget: r,
675
+ rawAnchor: e[i] === 1 ? e.slice(i + 1, i + 33) : new Uint8Array(),
676
+ tagsStart: t
677
+ };
678
+ }
679
+ async function qt(e) {
680
+ let t = Kt(e);
681
+ if (t == null) return !1;
682
+ let { rawTarget: n, rawAnchor: r, tagsStart: i } = t, a = i + 16;
683
+ if (e.length < a) return !1;
684
+ let o = new DataView(e.buffer, e.byteOffset, e.byteLength);
685
+ if (o.getUint16(0, !0) !== Ot) return !1;
686
+ 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;
687
+ if (e.length < u) return !1;
688
+ let d = e.slice(i + 16, u), f = e.slice(u);
689
+ try {
690
+ let e = await Bt(c, n, r, d, f), t = D.hashMessage(e), i = D.hexlify(s), a = D.SigningKey.recoverPublicKey(t, i), o = D.getBytes(a);
691
+ return o.length === c.length && o.every((e, t) => e === c[t]);
692
+ } catch {
693
+ return !1;
694
+ }
695
+ }
696
+ var Jt = (e) => {
697
+ let t = "";
698
+ for (let n of e) t += String.fromCharCode(n);
699
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
700
+ }, Yt = j("seedProtocol:createArweaveDataItems");
701
+ async function Xt(e, t, n) {
702
+ let r, i;
703
+ if (t) r = (await t(e)).map((e) => ({
704
+ transaction: { id: e.transaction.id },
705
+ versionId: e.versionId,
706
+ modelName: e.modelName
707
+ }));
708
+ else if (n) {
709
+ let t = [], o = Date.now();
710
+ for (let r = 0; r < e.length; r++) {
711
+ let i = e[r], s = i.tags, c = new Uint8Array(8);
712
+ crypto.getRandomValues(c);
713
+ let l = (new DataView(c.buffer).getBigUint64(0, !1) ^ BigInt(r)) & 18446744073709551615n, u;
714
+ if (Pt(n)) {
715
+ let e = Mt(n.address, o, l);
716
+ u = await Ut(i.data, n, s, e);
717
+ } else {
718
+ let e = a(n) ? n.signer : n, t = Mt(e.address, o, l);
719
+ u = await Wt(i.data, e, s, t);
720
+ }
721
+ if (!await qt(u.raw)) throw Yt("DataItem verification failed: id=%s modelName=%s", u.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.`);
722
+ t.push(u);
723
+ }
724
+ i = t, r = t.map((t, n) => ({
725
+ transaction: { id: t.id },
726
+ versionId: e[n]?.versionLocalId,
727
+ modelName: e[n]?.itemPropertyName
728
+ }));
729
+ } else throw Error("@seedprotocol/publish: useArweaveBundler requires signDataItems or dataItemSigner (pass at createPublish or in PublishProvider config)");
730
+ let o = e.map((e) => ({
731
+ itemPropertyName: e.itemPropertyName,
732
+ itemPropertyLocalId: e.itemPropertyLocalId,
733
+ seedLocalId: e.seedLocalId,
734
+ versionLocalId: e.versionLocalId,
735
+ transactionToSign: null
736
+ }));
737
+ return {
738
+ arweaveTransactions: r,
739
+ publishUploads: o,
740
+ signedDataItems: i
741
+ };
742
+ }
743
+ var Zt = A(async ({ input: { context: e } }) => {
744
+ let { item: t } = e;
745
+ t.getPublishUploads || (t = await z(t.seedLocalId));
746
+ let n = {};
747
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
748
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
749
+ r?.length && (n.deferHtmlStorageSeedLocalIds = r);
750
+ let i = await Dt(t, [], void 0, Object.keys(n).length ? n : void 0), a = s();
751
+ return Xt(i, e.signDataItems ?? a.signDataItems, e.dataItemSigner ?? a.dataItemSigner);
752
+ });
753
+ //#endregion
754
+ //#region src/services/publish/actors/createArweaveDataItemsPhase2.ts
755
+ async function Qt(e) {
756
+ let { item: t } = e;
757
+ t.getPublishUploads || (t = await z(t.seedLocalId));
758
+ let n = {};
759
+ e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
760
+ let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
761
+ r?.length && (n.onlyHtmlStorageSeedLocalIds = r, n.skipRelationRecursion = !0);
762
+ let i = await Dt(t, [], void 0, Object.keys(n).length ? n : void 0), a = s(), o = e.signDataItems ?? a.signDataItems, c = e.dataItemSigner ?? a.dataItemSigner;
763
+ return i.length === 0 ? {
764
+ arweaveTransactions: [],
765
+ publishUploads: [],
766
+ signedDataItems: void 0
767
+ } : Xt(i, o, c);
768
+ }
769
+ var $t = A(async ({ input: { context: e } }) => Qt(e)), en = 8192;
770
+ function tn(e) {
771
+ let t = new Uint8Array(e), n = "";
772
+ for (let e = 0; e < t.length; e += en) {
773
+ let r = t.subarray(e, Math.min(e + en, t.length));
774
+ n += String.fromCharCode.apply(null, r);
775
+ }
776
+ return btoa(n);
777
+ }
778
+ async function nn(e) {
779
+ let t = [];
780
+ for (let [n, r] of e.entries()) {
781
+ let e = r;
782
+ if (typeof e == "object" && e && "arrayBuffer" in e) {
783
+ let r = tn(await e.arrayBuffer()), i = e;
784
+ t.push({
785
+ name: n,
786
+ value: r,
787
+ encoding: "base64",
788
+ filename: i.name || void 0
789
+ });
790
+ } else t.push({
791
+ name: n,
792
+ value: String(r)
793
+ });
794
+ }
795
+ return t;
796
+ }
797
+ function rn(e, t, n) {
798
+ 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;
799
+ return i ? r.push(`: ${i}`) : n && r.push(` (${n})`), r.join("");
800
+ }
801
+ function an(e) {
802
+ if (!e) return "Upload server unavailable. Please try again or check your connection.";
803
+ let t = e.toLowerCase();
804
+ 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.";
805
+ }
806
+ async function on(e, t, n) {
807
+ let r = typeof window < "u" ? window.Main : void 0;
808
+ if (r?.uploadArweaveStart) {
809
+ let n = await nn(t);
810
+ return r.uploadArweaveStart(e, n);
811
+ }
812
+ let i = await fetch(e, {
813
+ method: "POST",
814
+ body: t
815
+ }), a = await i.json().catch(() => ({}));
816
+ return {
817
+ status: i.status,
818
+ body: a
819
+ };
820
+ }
821
+ //#endregion
822
+ //#region src/services/publish/actors/sendReimbursementRequest.ts
823
+ var sn = A(async ({ input: { context: e, event: t } }) => {
824
+ let { arweaveTransactions: n = [], transactionKeys: r, reimbursementTransactionId: i } = e;
825
+ if (i) return { transactionId: i };
826
+ let a = n.map(({ transaction: e }) => e), o = new FormData();
827
+ for (let e of a) {
828
+ let { data: t, chunks: n, ...r } = e, i = t instanceof Blob ? t : new Blob([t]);
829
+ o.append(`${e.id}-data`, i, `${e.id}-data`);
830
+ let a = new Blob([JSON.stringify(n)], { type: "application/json" });
831
+ o.append(`${e.id}-chunks`, a, `${e.id}-chunks`);
832
+ let s = new Blob([JSON.stringify(r)], { type: "application/json" });
833
+ o.append(`${e.id}-json`, s, `${e.id}-json`);
834
+ }
835
+ let { uploadApiBaseUrl: c } = s(), { status: l, body: u, message: d } = await on(`${c}/api/upload/arweave/start`, o, c);
836
+ if (l >= 300 || l < 200) {
837
+ let e = l === 0 ? d : null;
838
+ e && console.error("[upload]", e);
839
+ let t = l === 0 ? an(e) : rn(l, u, r);
840
+ throw Error(t);
841
+ }
842
+ return u;
843
+ }), cn = A(async ({ input: { context: e, event: t } }) => {
844
+ let { requestResponse: n, reimbursementTransactionId: r } = e;
845
+ if (!n) throw Error("No request response");
846
+ if (!r) throw Error("No reimbursement transaction id");
847
+ let i = L();
848
+ await new Promise((e, t) => {
849
+ let n = setInterval(async () => {
850
+ let t;
851
+ try {
852
+ t = await i.transactions.getStatus(r);
853
+ } catch {
854
+ return;
855
+ }
856
+ t && t.confirmed && (clearInterval(n), e());
857
+ }, 5e3);
858
+ });
859
+ }), V = j("seedProtocol:services:publish:actors");
860
+ function ln(e) {
861
+ if (e instanceof Uint8Array) return e;
862
+ if (e instanceof ArrayBuffer) return new Uint8Array(e);
863
+ throw Error("Transaction data must be Uint8Array or ArrayBuffer for upload resume");
864
+ }
865
+ var un = k(({ sendBack: e, input: t }) => {
866
+ let n = t.context, r = (n.arweaveTransactions ?? []).map(({ transaction: e }) => e), i = L(), a = n.uploaderState && typeof n.currentTransactionIndex == "number", o = a ? n.currentTransactionIndex : 0;
867
+ (async () => {
868
+ let t = r.length;
869
+ for (let s = o; s < t; s++) {
870
+ let c = r[s];
871
+ if (!c) continue;
872
+ let l = i.transactions.fromRaw(c);
873
+ if (!await i.transactions.verify(l)) throw Error("Transaction verification failed");
874
+ let u, d = n.uploaderState;
875
+ if (a && s === o && d) {
876
+ let e = l.data, t = e instanceof Uint8Array ? e : ln(e);
877
+ u = await i.transactions.getUploader(d, t);
878
+ } else u = await i.transactions.getUploader(l, l.data);
879
+ for (; !u.isComplete;) {
880
+ V("uploading chunk"), V(`uploader.pctComplete: ${u.pctComplete}`), V(`uploader.uploadedChunks: ${u.uploadedChunks}`), V(`uploader.totalChunks: ${u.totalChunks}`), V(u.lastResponseError), V(u.lastResponseStatus);
881
+ try {
882
+ await u.uploadChunk(), e({
883
+ type: "updatePercentage",
884
+ completionPercentage: Math.trunc((s + u.pctComplete / 100) / t * 100),
885
+ uploaderState: u.toJSON(),
886
+ currentTransactionIndex: s
887
+ }), V(`${u.pctComplete}% complete, ${u.uploadedChunks}/${u.totalChunks}`);
888
+ } catch (e) {
889
+ V(e);
890
+ }
891
+ }
892
+ }
893
+ return "done";
894
+ })().then((t) => {
895
+ e({
896
+ type: "uploadComplete",
897
+ result: t
898
+ });
899
+ }).catch((t) => {
900
+ e({
901
+ type: "uploadError",
902
+ error: t
903
+ });
904
+ });
905
+ }), dn = 12e4, fn = Function("s", "return import(s)"), pn = null, mn = async () => {
906
+ if (pn) return pn;
907
+ if (typeof window < "u") return null;
908
+ try {
909
+ let e = await fn(`node:${["fs", "promises"].join("/")}`);
910
+ return pn = {
911
+ readFile: e.readFile,
912
+ stat: e.stat
913
+ }, pn;
914
+ } catch {
915
+ return null;
916
+ }
917
+ }, hn = k(({ sendBack: e, input: { context: t } }) => {
918
+ let { signedDataItems: n } = t, { uploadApiBaseUrl: r, useArweaveBundler: i } = s();
919
+ if (!i || !r) {
920
+ e({
921
+ type: "uploadError",
922
+ error: /* @__PURE__ */ Error("Arweave bundler not configured. Set useArweaveBundler and uploadApiBaseUrl.")
923
+ });
924
+ return;
925
+ }
926
+ let a = `${r.replace(/\/$/, "")}/api/upload/arweave/batch`;
927
+ if (!n || n.length === 0) {
928
+ e({
929
+ type: "uploadComplete",
930
+ result: "done"
931
+ });
932
+ return;
933
+ }
934
+ (async () => {
935
+ let e = n, t = e.length, r = Array(t).fill(null), i = async (e, t) => {
936
+ let n = e;
937
+ if (n.raw != null && (n.raw instanceof Uint8Array || Buffer.isBuffer(n.raw))) return n.raw.byteLength;
938
+ if (typeof n.getRaw == "function") {
939
+ let e = n.getRaw(), i = e instanceof Promise ? await e : e, a = Buffer.isBuffer(i) ? i : Buffer.from(i);
940
+ return r[t] = a, a.length;
941
+ }
942
+ if (n.filename != null) {
943
+ let e = await mn();
944
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
945
+ return (await e.stat(n.filename)).size;
946
+ }
947
+ throw Error("Cannot get raw bytes from DataItem");
948
+ }, o = 4, s = [];
949
+ for (let n = 0; n < t; n++) {
950
+ let t = await i(e[n], n);
951
+ s.push(t), o += 4 + t;
952
+ }
953
+ let c = Buffer.alloc(o), l = 0;
954
+ c.writeUInt32BE(t, l), l += 4;
955
+ for (let n = 0; n < t; n++) {
956
+ let t = s[n], i = r[n];
957
+ if (i) {
958
+ c.writeUInt32BE(t, l), l += 4, i.copy(c, l), l += t;
959
+ continue;
960
+ }
961
+ let a = e[n];
962
+ if (a.raw != null && (a.raw instanceof Uint8Array || Buffer.isBuffer(a.raw))) {
963
+ c.writeUInt32BE(t, l), l += 4, c.set(a.raw, l), l += t;
964
+ continue;
965
+ }
966
+ if (a.filename != null) {
967
+ let e = await mn();
968
+ if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
969
+ let t = await e.readFile(a.filename);
970
+ c.writeUInt32BE(t.length, l), l += 4, t.copy(c, l), l += t.length;
971
+ continue;
972
+ }
973
+ throw Error("Cannot get raw bytes from DataItem");
974
+ }
975
+ let u = new AbortController(), d = setTimeout(() => u.abort(), dn), f;
976
+ try {
977
+ f = await fetch(a, {
978
+ method: "POST",
979
+ headers: { "Content-Type": "application/octet-stream" },
980
+ body: c,
981
+ signal: u.signal
982
+ });
983
+ } catch (e) {
984
+ throw clearTimeout(d), e instanceof Error && e.name === "AbortError" ? Error(`Arweave batch upload timed out after ${dn / 1e3}s (upload API did not respond). Check uploadApiBaseUrl and network.`) : e;
985
+ }
986
+ if (clearTimeout(d), !f.ok) throw Error(`Batch upload failed: ${f.status}`);
987
+ let p = await f.json().catch(() => ({})), m = typeof p.failed == "number" ? p.failed : 0;
988
+ if (m > 0) {
989
+ let e = p.total ?? "?", t = p.succeeded ?? 0;
990
+ throw Error(`Arweave batch upload failed: ${m} of ${e} item(s) failed (${t} succeeded)`);
991
+ }
992
+ })().then(() => e({
993
+ type: "uploadComplete",
994
+ result: "done"
995
+ })).catch((t) => e({
996
+ type: "uploadError",
997
+ error: t
998
+ }));
999
+ }), gn = "The executor module could not be installed on your publishing account on Optimism Sepolia. Reconnect and try again, or contact support if this persists.";
1000
+ async function _n(e, t, n) {
1001
+ let { modularAccountModuleContract: i } = n;
1002
+ if (!i) return;
1003
+ let a = Ve({
1004
+ client: ce(),
1005
+ chain: Ue,
1006
+ address: e
1007
+ });
1008
+ if (await re(e)) try {
1009
+ let e = await tt({ contract: a }), n = i.toLowerCase();
1010
+ if (e.some((e) => e.implementation?.toLowerCase() === n)) return;
1011
+ await m((await He({
1012
+ transaction: nt({
1013
+ contract: a,
1014
+ moduleContract: i,
1015
+ data: Be([{ type: "address" }], [ve])
1016
+ }),
1017
+ account: t
1018
+ })).transactionHash);
1019
+ } catch (t) {
1020
+ if (ae(t)) return;
1021
+ throw new r(gn, "EXECUTOR_MODULE_NOT_INSTALLED", e, t);
1022
+ }
1023
+ }
1024
+ //#endregion
1025
+ //#region src/helpers/ensureManagedAccountReady.ts
1026
+ var vn = "Could not connect the managed publishing account on Optimism Sepolia. Reconnect with the same sign-in method and try again.", yn = "Your publishing smart account is not deployed on Optimism Sepolia yet. Complete wallet setup, enable autoDeployManagedAccount in config if appropriate, then try again.", bn = "The managed account could not be confirmed on Optimism Sepolia after deployment. Wait a moment and retry, or check your network connection.", xn = "Automatic deployment of the managed publishing account failed on Optimism Sepolia. Retry or deploy the account through your wallet provider.";
1027
+ async function Sn() {
1028
+ let { useModularExecutor: e } = s();
1029
+ if (!e) return { kind: "skip" };
1030
+ let t;
1031
+ try {
1032
+ t = await _(Ue);
1033
+ } catch (e) {
1034
+ return {
1035
+ kind: "unavailable",
1036
+ cause: e
1037
+ };
1038
+ }
1039
+ return await ne(t) ? {
1040
+ kind: "ready",
1041
+ managedAddress: t
1042
+ } : {
1043
+ kind: "not_deployed",
1044
+ managedAddress: t
1045
+ };
1046
+ }
1047
+ async function Cn() {
1048
+ ge();
1049
+ let e = he();
1050
+ await e.autoConnect({
1051
+ client: ce(),
1052
+ chain: Ue
1053
+ });
1054
+ let t = e.getAccount();
1055
+ if (!t) throw new r(vn, "MANAGED_ACCOUNT_UNAVAILABLE");
1056
+ return t;
1057
+ }
1058
+ var wn = 9e4;
1059
+ async function Tn(e) {
1060
+ let t;
1061
+ try {
1062
+ await Promise.race([h(e), new Promise((e, n) => {
1063
+ t = setTimeout(() => n(/* @__PURE__ */ Error(`Managed account deploy timed out after ${wn / 1e3}s`)), wn);
1064
+ })]);
1065
+ } finally {
1066
+ t != null && clearTimeout(t);
1067
+ }
1068
+ }
1069
+ async function En(e) {
1070
+ let n = s(), i = await Cn(), { fromThirdwebAccount: a } = await import("./ensureManagedAccountEasConfigured-zcyqhWPe.js").then((e) => e.R), o = {
1071
+ managedAddress: e,
1072
+ managedSigningAccount: a(i)
1073
+ };
1074
+ try {
1075
+ if (n.deployManagedAccount) await n.deployManagedAccount(o);
1076
+ else {
1077
+ let e = await oe();
1078
+ if (e) {
1079
+ let t = ee();
1080
+ await t.autoConnect({
1081
+ client: ce(),
1082
+ chain: Ue
1083
+ }), await ie({
1084
+ adminAddress: t.getAdminAccount?.()?.address ?? e.address,
1085
+ signingAccount: e
1086
+ });
1087
+ } else await Tn(i);
1088
+ }
1089
+ } catch (n) {
1090
+ if (await te(e, /UserOp|user operation/i.test(t(n)) ? 15 : 5)) return;
1091
+ throw new r(xn, "MANAGED_ACCOUNT_NOT_DEPLOYED", e, n);
1092
+ }
1093
+ if (!await te(e)) throw new r(bn, "MANAGED_ACCOUNT_NOT_DEPLOYED", e);
1094
+ }
1095
+ async function Dn() {
1096
+ let e = s();
1097
+ if (!e.useModularExecutor) throw Error("runModularExecutorPublishPrep: useModularExecutor is false");
1098
+ let t = await Sn();
1099
+ if (t.kind === "unavailable") return {
1100
+ ok: !1,
1101
+ error: new r(vn, "MANAGED_ACCOUNT_UNAVAILABLE", void 0, t.cause)
1102
+ };
1103
+ if (t.kind === "not_deployed") if (e.autoDeployManagedAccount) {
1104
+ try {
1105
+ await En(t.managedAddress);
1106
+ } catch (e) {
1107
+ return {
1108
+ ok: !1,
1109
+ error: c(e) ? e : new r(xn, "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress, e)
1110
+ };
1111
+ }
1112
+ if (t = await Sn(), t.kind !== "ready") return {
1113
+ ok: !1,
1114
+ error: new r(bn, "MANAGED_ACCOUNT_NOT_DEPLOYED", t.kind === "not_deployed" ? t.managedAddress : void 0)
1115
+ };
1116
+ } else return {
1117
+ ok: !1,
1118
+ error: new r(yn, "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress)
1119
+ };
1120
+ if (t.kind === "ready") {
1121
+ if (e.modularAccountModuleContract) try {
1122
+ let n = await Cn();
1123
+ await _n(t.managedAddress, n, e);
1124
+ } catch (e) {
1125
+ return c(e) ? {
1126
+ ok: !1,
1127
+ error: e
1128
+ } : {
1129
+ ok: !1,
1130
+ error: new r("Executor module setup failed on Optimism Sepolia.", "EXECUTOR_MODULE_NOT_INSTALLED", t.managedAddress, e)
1131
+ };
1132
+ }
1133
+ return {
1134
+ ok: !0,
1135
+ managedAddress: t.managedAddress
1136
+ };
1137
+ }
1138
+ throw Error("runModularExecutorPublishPrep: unexpected readiness state");
1139
+ }
1140
+ //#endregion
1141
+ //#region src/helpers/resolvePublishWallet.ts
1142
+ function On(e) {
1143
+ if (a(e.wallet)) return e.wallet;
1144
+ if (a(e.account)) return e.account;
1145
+ let t = f();
1146
+ if (t) return t;
1147
+ throw Error("@seedprotocol/publish: no PublishWallet available. Pass fromEthersWallet / fromEip1193Provider / fromThirdwebAccount, or call setPublishWallet / useSeedWallet.");
1148
+ }
1149
+ //#endregion
1150
+ //#region src/services/publish/actors/persistSeedUid.ts
1151
+ var kn = j("seedProtocol:services:publish:actors:persistSeedUid"), An = "0x" + "0".repeat(64), jn = 15e3;
1152
+ function Mn(e, t) {
1153
+ let n = e.seedLocalId, r = n ? t.find((e) => e?.localId === n) : void 0, i = r?.seedUid && r.seedUid !== An ? r.seedUid : t[0]?.seedUid;
1154
+ i && i !== An && (e.seedUid = i);
1155
+ }
1156
+ async function Nn(e, t, n) {
1157
+ let r = e.persistSeedUid;
1158
+ if (typeof r != "function") return;
1159
+ let i = new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("persistSeedUid timed out")), jn));
1160
+ try {
1161
+ await Promise.race([r.call(e, t, n), i]);
1162
+ } catch (e) {
1163
+ kn("persistSeedUid failed (attestations already on-chain):", e);
1164
+ }
1165
+ }
1166
+ //#endregion
1167
+ //#region src/services/publish/helpers/verifyArweaveTransactionsExist.ts
1168
+ async function Pn(e) {
1169
+ if (e.length === 0) return;
1170
+ let { arweaveUploadVerificationBaseUrl: t } = s(), n = await Promise.all(e.map((e) => ke(t, e)));
1171
+ for (let t = 0; t < e.length; t++) {
1172
+ let r = e[t], i = n[t];
1173
+ if (i) {
1174
+ if (i.status === 404) throw Error(`Arweave transaction ${r} not found. Upload may have failed. Delete this publish record and try again.`);
1175
+ if (i.status !== 200) {
1176
+ let e = i.status === 504 ? "request timed out (upload service did not respond in time)" : `status: ${i.status}`;
1177
+ throw Error(`Arweave transaction ${r} is not yet available from the upload service (${e}). Wait and retry.`);
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+ //#endregion
1183
+ //#region src/helpers/abi/executor.ts
1184
+ var Fn = [{
1185
+ type: "event",
1186
+ name: "CreatedAttestation",
1187
+ inputs: [{
1188
+ name: "result",
1189
+ type: "tuple",
1190
+ indexed: !1,
1191
+ components: [{
1192
+ name: "schemaUid",
1193
+ type: "bytes32"
1194
+ }, {
1195
+ name: "attestationUid",
1196
+ type: "bytes32"
1197
+ }]
1198
+ }]
1199
+ }, {
1200
+ type: "event",
1201
+ name: "SeedPublished",
1202
+ inputs: [{
1203
+ name: "seedUid",
1204
+ type: "bytes32",
1205
+ indexed: !1
1206
+ }, {
1207
+ name: "versionUid",
1208
+ type: "bytes32",
1209
+ indexed: !1
1210
+ }]
1211
+ }];
1212
+ //#endregion
1213
+ //#region src/services/publish/actors/seedUidHelpers.ts
1214
+ function H(e) {
1215
+ return e == null || e === "" ? R : ("0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(64, "0").slice(-64)).toLowerCase();
1216
+ }
1217
+ function In(e, t, n) {
1218
+ if (!t || !e.logs?.length) return;
1219
+ let r = H(t);
1220
+ if (r === R) return;
1221
+ let i = n ? Fn : g;
1222
+ try {
1223
+ let t = E({
1224
+ abi: i,
1225
+ eventName: "CreatedAttestation",
1226
+ logs: e.logs,
1227
+ strict: !1
1228
+ });
1229
+ for (let e of t) {
1230
+ let t = e.args?.result;
1231
+ if (t?.attestationUid && H(t.schemaUid) === r) {
1232
+ let e = t.attestationUid;
1233
+ return e && H(e) !== R ? e : void 0;
1234
+ }
1235
+ }
1236
+ } catch {}
1237
+ }
1238
+ function Ln(e, t, n, r) {
1239
+ let i = t.toLowerCase(), a = e.logs?.filter((e) => e.address && e.address.toLowerCase() === i);
1240
+ if (!a?.length) return {};
1241
+ try {
1242
+ if (r) {
1243
+ let e = E({
1244
+ abi: Fn,
1245
+ eventName: "SeedPublished",
1246
+ logs: a,
1247
+ strict: !1
1248
+ })[0];
1249
+ if (!e) return {};
1250
+ let t = e.args;
1251
+ return {
1252
+ seedUid: t?.seedUid && H(t.seedUid) !== R ? t.seedUid : void 0,
1253
+ versionUid: t?.versionUid && H(t.versionUid) !== R ? t.versionUid : void 0
1254
+ };
1255
+ }
1256
+ let e = E({
1257
+ abi: g,
1258
+ eventName: "SeedPublished",
1259
+ logs: a,
1260
+ strict: !1
1261
+ })[0];
1262
+ if (!e) return {};
1263
+ let t = e.args?.returnedDataFromEAS;
1264
+ if (!t || t === "0x") return {};
1265
+ let i = ze([{ type: "bytes32[]" }], t)[0];
1266
+ if (!i?.length) return {};
1267
+ let o = n, s = i[o], c = i[o + 1];
1268
+ return {
1269
+ seedUid: s && s !== R ? s : i.length === 1 && i[0] && i[0] !== R ? i[0] : void 0,
1270
+ versionUid: c && c !== R ? c : void 0
1271
+ };
1272
+ } catch {
1273
+ return {};
1274
+ }
1275
+ }
1276
+ function Rn(e, t, n, r) {
1277
+ return Ln(e, t, n, r).seedUid;
1278
+ }
1279
+ function zn(e, t, n) {
1280
+ if (!t || !e.logs?.length) return;
1281
+ let r = H(t);
1282
+ if (r === R) return;
1283
+ let i = n ? Fn : g;
1284
+ try {
1285
+ let t = E({
1286
+ abi: i,
1287
+ eventName: "CreatedAttestation",
1288
+ logs: e.logs,
1289
+ strict: !1
1290
+ });
1291
+ for (let e of t) {
1292
+ let t = e.args?.result;
1293
+ if (t?.attestationUid && H(t.schemaUid) === r) {
1294
+ let e = t.attestationUid;
1295
+ return e && H(e) !== R ? e : void 0;
1296
+ }
1297
+ }
1298
+ } catch {}
1299
+ }
1300
+ function Bn(e, t) {
1301
+ if (!e.logs?.length) return [];
1302
+ let n = t ? Fn : g;
1303
+ try {
1304
+ let t = E({
1305
+ abi: n,
1306
+ eventName: "CreatedAttestation",
1307
+ logs: e.logs,
1308
+ strict: !1
1309
+ }), r = [];
1310
+ for (let e of t) {
1311
+ let t = e.args?.result;
1312
+ if (!t?.attestationUid) continue;
1313
+ let n = t.attestationUid;
1314
+ if (!n || H(n) === R) continue;
1315
+ let i = t.schemaUid;
1316
+ i && r.push({
1317
+ schemaUid: i,
1318
+ attestationUid: n
1319
+ });
1320
+ }
1321
+ return r;
1322
+ } catch {
1323
+ return [];
1324
+ }
1325
+ }
1326
+ //#endregion
1327
+ //#region src/services/publish/helpers/receiptAttestationMs.ts
1328
+ async function U(e) {
1329
+ let t = e?.blockNumber;
1330
+ return t == null ? Date.now() : await ue(t) ?? Date.now();
1331
+ }
1332
+ //#endregion
1333
+ //#region src/services/publish/actors/publishRequestNormalize.ts
1334
+ var Vn = 64, W = (e) => {
1335
+ if (e == null) return "0x" + "0".repeat(Vn);
1336
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(Vn, "0").slice(-64);
1337
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1338
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1339
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(Vn, "0").slice(-64);
1340
+ }
1341
+ return "0x" + "0".repeat(Vn);
1342
+ }, Hn = (e) => {
1343
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1344
+ if (typeof e == "string") {
1345
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1346
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1347
+ }
1348
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1349
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1350
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1351
+ }
1352
+ return "0x";
1353
+ };
1354
+ function Un(e) {
1355
+ let t = new Set(e.map((e) => e?.localId).filter((e) => !!e));
1356
+ return e.some((e) => (e?.listOfAttestations ?? []).some((e) => {
1357
+ let n = e;
1358
+ return n._unresolvedValue && t.has(n._unresolvedValue) ? !0 : Array.isArray(n._rawListIdsForResolve) ? n._rawListIdsForResolve.some((e) => e && t.has(String(e).trim())) : !1;
1359
+ }));
1360
+ }
1361
+ function Wn(e, t) {
1362
+ return (e ?? []).filter((e) => e.publishLocalId && t.has(e.publishLocalId));
1363
+ }
1364
+ var Gn = {
1365
+ recipient: qe,
1366
+ expirationTime: BigInt(0),
1367
+ revocable: !0,
1368
+ refUID: R,
1369
+ data: R,
1370
+ value: BigInt(0)
1371
+ };
1372
+ function Kn(e) {
1373
+ let t = (e?.listOfAttestations ?? []).map((e) => {
1374
+ let t = Array.isArray(e?.data) ? e.data : [];
1375
+ return {
1376
+ schema: W(e?.schema),
1377
+ data: t.map((e) => ({
1378
+ ...e,
1379
+ refUID: W(e?.refUID),
1380
+ data: Hn(e?.data),
1381
+ expirationTime: e?.expirationTime == null ? BigInt(0) : BigInt(e.expirationTime),
1382
+ value: e?.value == null ? BigInt(0) : BigInt(e.value)
1383
+ })),
1384
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
1385
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
1386
+ };
1387
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
1388
+ ...e,
1389
+ propertySchemaUid: W(e?.propertySchemaUid)
1390
+ }));
1391
+ return {
1392
+ ...e,
1393
+ seedUid: W(e?.seedUid),
1394
+ seedSchemaUid: W(e?.seedSchemaUid),
1395
+ versionUid: W(e?.versionUid),
1396
+ versionSchemaUid: W(e?.versionSchemaUid),
1397
+ listOfAttestations: t,
1398
+ propertiesToUpdate: n
1399
+ };
1400
+ }
1401
+ function qn(e, t) {
1402
+ for (let n of e) for (let e of n?.propertiesToUpdate ?? []) {
1403
+ let n = e?.publishLocalId, r = W(e?.propertySchemaUid);
1404
+ if (!n || !r) continue;
1405
+ let i = t.get(n);
1406
+ if (!i?.listOfAttestations) continue;
1407
+ let a = i.listOfAttestations.find((e) => W(e?.schema)?.toLowerCase() === r?.toLowerCase());
1408
+ a && (!Array.isArray(a.data) || a.data.length === 0) && (a.data = [{
1409
+ ...Gn,
1410
+ refUID: R
1411
+ }]);
1412
+ }
1413
+ }
1414
+ //#endregion
1415
+ //#region src/services/arweaveL1Finalize/enqueue.ts
1416
+ var Jn = "pending_l1";
1417
+ async function Yn(e) {
1418
+ let { useArweaveBundler: t } = s();
1419
+ if (!t) return;
1420
+ let n = e.arweaveTransactions ?? [], r = e.publishUploads ?? [];
1421
+ if (n.length === 0 || n.length !== r.length) return;
1422
+ let i = x.getAppDb();
1423
+ if (!i) return;
1424
+ let a = Date.now();
1425
+ for (let e = 0; e < n.length; e++) {
1426
+ let t = n[e], o = r[e];
1427
+ if (!o) continue;
1428
+ let s = t.transaction?.id;
1429
+ if (!(!s || typeof s != "string")) try {
1430
+ await i.insert(Ce).values({
1431
+ seedLocalId: o.seedLocalId,
1432
+ dataItemId: s,
1433
+ versionLocalId: o.versionLocalId ?? null,
1434
+ itemPropertyName: o.itemPropertyName ?? null,
1435
+ phase: Jn,
1436
+ createdAt: a,
1437
+ updatedAt: a
1438
+ }).onConflictDoNothing();
1439
+ } catch {}
1440
+ }
1441
+ }
1442
+ //#endregion
1443
+ //#region src/services/publish/actors/createAttestations.ts
1444
+ var Xn = j("seedProtocol:services:publish:actors");
1445
+ function Zn(e) {
1446
+ let { useModularExecutor: t, publisherAddress: n, modularAccountModuleContract: r, managedAddress: i } = e;
1447
+ if (t) {
1448
+ if (!i) throw Error("resolvePublishRouting: managedAddress is required when useModularExecutor is true");
1449
+ return {
1450
+ txTargetAddress: i,
1451
+ contractAddressForEvents: r || i
1452
+ };
1453
+ }
1454
+ return {
1455
+ txTargetAddress: n,
1456
+ contractAddressForEvents: n
1457
+ };
1458
+ }
1459
+ async function Qn(e) {
1460
+ let { receipt: t, seedLocalId: n, versionSchemaUid: r, contractAddressForEvents: i, listOfAttestationsCount: a, useModularExecutor: o, publisherAddress: s } = e;
1461
+ if (!n) return;
1462
+ let c = zn(t, r, o) ?? Ln(t, i, a, o).versionUid, l = c ? W(c) : void 0;
1463
+ !l || l === R || await Le({
1464
+ seedLocalId: n,
1465
+ versionUid: l,
1466
+ publisher: s,
1467
+ attestationCreatedAt: await U(t)
1468
+ });
1469
+ }
1470
+ function $n(e, t) {
1471
+ return !e || !t ? !1 : W(e).toLowerCase() === W(t).toLowerCase();
1472
+ }
1473
+ function er(e, t, n) {
1474
+ return !n || t >= e.length ? t : $n(e[t]?.schemaUid, n) ? t + 1 : t;
1475
+ }
1476
+ async function tr(e) {
1477
+ let { receipt: t, normalizedRequests: n, useModularExecutor: r } = e, i = Bn(t, r);
1478
+ if (!i.length) return;
1479
+ let a = await U(t), o = 0;
1480
+ for (let e of n) {
1481
+ let n = e.listOfAttestations ?? [];
1482
+ if (!n.length) continue;
1483
+ (!e.seedUid || W(e.seedUid) === R) && (o = er(i, o, e.seedSchemaUid)), o = er(i, o, e.versionSchemaUid);
1484
+ let s = n.length, c = i.slice(o, o + s);
1485
+ if (o += s, !c.length) continue;
1486
+ let l = Math.min(c.length, s), u = e.versionUid && W(e.versionUid) !== R ? W(e.versionUid) : void 0;
1487
+ u ||= zn(t, e.versionSchemaUid, r), await Se({
1488
+ seedLocalId: e.localId,
1489
+ attestationCreatedAtMs: a ?? null,
1490
+ versionUid: u && W(u) !== R ? W(u) : null,
1491
+ pairs: c.slice(0, l).map((e, t) => ({
1492
+ schemaUid: e.schemaUid,
1493
+ attestationUid: e.attestationUid,
1494
+ propertyName: typeof n[t]?._propertyName == "string" && n[t]._propertyName !== "" ? n[t]._propertyName : void 0
1495
+ }))
1496
+ });
1497
+ }
1498
+ }
1499
+ var nr = A(async ({ input: { context: e } }) => {
1500
+ let { address: t, account: n, wallet: r } = e, i = e.arweaveTransactions ?? [], a = e.publishUploads ?? [], { item: o } = e, { modularAccountModuleContract: c, useModularExecutor: l } = s();
1501
+ if (!t || typeof t != "string" || !t.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
1502
+ if (!r && !n) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
1503
+ if (!l && !await re(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.");
1504
+ if (!o?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
1505
+ if (typeof o.getPublishUploads != "function" && (o = await z(o.seedLocalId)), i.length !== a.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.");
1506
+ let u = Zn({
1507
+ useModularExecutor: !1,
1508
+ publisherAddress: t
1509
+ }), d = On(e);
1510
+ await I(o, d);
1511
+ let f = i.map((e, t) => {
1512
+ let n = e.transaction?.id;
1513
+ 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.");
1514
+ let r = a[t];
1515
+ if (!r) throw Error("Publish upload index mismatch");
1516
+ return {
1517
+ ...r,
1518
+ txId: n
1519
+ };
1520
+ });
1521
+ await Pn(f.map((e) => e.txId));
1522
+ let p = await o.getPublishPayload(f, { publishMode: e.publishMode ?? "patch" }), h = Array.isArray(p) ? p : [p];
1523
+ if (l) {
1524
+ let e = await Dn();
1525
+ if (!e.ok) throw e.error;
1526
+ u = Zn({
1527
+ useModularExecutor: l,
1528
+ publisherAddress: t,
1529
+ modularAccountModuleContract: c,
1530
+ managedAddress: e.managedAddress
1531
+ });
1532
+ let { ensureModularPublishBootstrap: n } = await import("./ensureModularPublishBootstrap-QRGGgnkz.js").then((e) => e.n), { fromThirdwebAccount: r } = await import("./ensureManagedAccountEasConfigured-zcyqhWPe.js").then((e) => e.R);
1533
+ d = r(await n(e.managedAddress));
1534
+ } else await pe(t, d);
1535
+ let g = h.length > 1 && Un(h), _, v = null;
1536
+ if (g) {
1537
+ let e = structuredClone(h), n = {};
1538
+ for (let r = 0; r < e.length; r++) {
1539
+ e = await Pe(e, n);
1540
+ let i = e[r], a = new Set([i.localId]), o = Kn({
1541
+ ...i,
1542
+ propertiesToUpdate: Wn(i.propertiesToUpdate, a)
1543
+ }), s = new Map([[o.localId, o]]);
1544
+ qn([o], s);
1545
+ let c = le(u.txTargetAddress, [o], 5000000n), f = await m((await d.txSender.sendTransaction(c)).transactionHash);
1546
+ if (!f) throw Error("Failed to send transaction");
1547
+ v = f;
1548
+ let p = o?.listOfAttestations?.length ?? 0;
1549
+ await Qn({
1550
+ receipt: f,
1551
+ seedLocalId: i.localId,
1552
+ versionSchemaUid: o.versionSchemaUid,
1553
+ contractAddressForEvents: u.contractAddressForEvents,
1554
+ listOfAttestationsCount: p,
1555
+ useModularExecutor: l,
1556
+ publisherAddress: t
1557
+ });
1558
+ let h = !o.seedUid || W(o.seedUid) === R, g = o?.seedSchemaUid;
1559
+ if (h) {
1560
+ let t = In(f, g, l) ?? Rn(f, u.contractAddressForEvents, p, l);
1561
+ t && (n[i.localId] = t, e[r] = {
1562
+ ...e[r],
1563
+ seedUid: t
1564
+ });
1565
+ }
1566
+ await tr({
1567
+ receipt: f,
1568
+ normalizedRequests: [o],
1569
+ useModularExecutor: l
1570
+ });
1571
+ }
1572
+ for (let t of e) {
1573
+ let e = t?.localId, r = t?.seedUid;
1574
+ e && r && W(r) !== R && (n[e] = W(r));
1575
+ }
1576
+ _ = (await Pe(structuredClone(h), n)).map((e) => Kn({
1577
+ ...e,
1578
+ seedUid: n[e.localId] ?? e.seedUid
1579
+ }));
1580
+ } else {
1581
+ let e = h.map((e) => Kn(e));
1582
+ qn(e, new Map(e.map((e) => [e?.localId, e])));
1583
+ let n = Array.isArray(p) ? e : [e[0]], r = le(u.txTargetAddress, n, 5000000n), i = await m((await d.txSender.sendTransaction(r)).transactionHash);
1584
+ if (!i) throw Error("Failed to send transaction");
1585
+ v = i;
1586
+ let a = e.find((e) => e?.localId === o.seedLocalId) ?? e[0];
1587
+ await Qn({
1588
+ receipt: i,
1589
+ seedLocalId: a?.localId,
1590
+ versionSchemaUid: a?.versionSchemaUid,
1591
+ contractAddressForEvents: u.contractAddressForEvents,
1592
+ listOfAttestationsCount: a?.listOfAttestations?.length ?? 0,
1593
+ useModularExecutor: l,
1594
+ publisherAddress: t
1595
+ }), await tr({
1596
+ receipt: i,
1597
+ normalizedRequests: n,
1598
+ useModularExecutor: l
1599
+ });
1600
+ let s = e[0], c = s?.seedUid, f = c === R || !c, g = s?.listOfAttestations?.length ?? 0, ee = s?.seedSchemaUid, y = f ? In(i, ee, l) ?? Rn(i, u.contractAddressForEvents, g, l) : void 0;
1601
+ _ = y && e.length > 0 ? [{
1602
+ ...e[0],
1603
+ seedUid: y
1604
+ }, ...e.slice(1)] : e;
1605
+ }
1606
+ Mn(o, _);
1607
+ let ee = o, y = _.find((e) => e?.localId === o.seedLocalId)?.seedUid;
1608
+ y && y !== R && await Nn(ee, t, v ? await U(v) : void 0), Xn("requestData", p), Yn(e);
1609
+ try {
1610
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
1611
+ await e(o.seedLocalId);
1612
+ } catch {}
1613
+ return { easPayload: p };
1614
+ }), rr = j("seedProtocol:services:publish:verifyAttestations"), ir = "0x" + "0".repeat(64), ar = 64, or = (e) => e == null ? "0x" + "0".repeat(ar) : typeof e == "string" ? "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(ar, "0").slice(-64) : "0x" + "0".repeat(ar), sr = 5e3, cr = 6;
1615
+ async function lr({ normalizedRequests: e, item: t }) {
1616
+ let n = t.seedLocalId;
1617
+ for (let t of e) {
1618
+ if (t.listOfAttestations.length === 0 || t.versionUid === ir) continue;
1619
+ let e = t.listOfAttestations.map((e) => or(e.schema).toLowerCase()), r = [], i;
1620
+ for (let e = 1; e <= cr; e++) try {
1621
+ e > 1 && await new Promise((e) => setTimeout(e, sr)), r = await Ee({ versionUids: [t.versionUid] });
1622
+ break;
1623
+ } catch (t) {
1624
+ if (i = t, rr("verifyAttestations attempt %d failed:", e, t), e === cr) throw rr("verifyAttestations: giving up after %d attempts", cr), i;
1625
+ }
1626
+ let a = r.map((e) => e.schemaId ? or(e.schemaId).toLowerCase() : "").filter(Boolean), o = new Set(a);
1627
+ if (e.filter((e) => !o.has(e)).length > 0) throw new _e(`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");
1628
+ }
1629
+ }
1630
+ //#endregion
1631
+ //#region src/services/publish/actors/createAttestationsDirectToEas.ts
1632
+ var G = j("seedProtocol:services:publish:createAttestationsDirectToEas"), ur = 64, K = (e) => {
1633
+ if (e == null) return "0x" + "0".repeat(ur);
1634
+ if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(ur, "0").slice(-64);
1635
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1636
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1637
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(ur, "0").slice(-64);
1638
+ }
1639
+ return "0x" + "0".repeat(ur);
1640
+ }, dr = (e) => {
1641
+ if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1642
+ if (typeof e == "string") {
1643
+ let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1644
+ return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1645
+ }
1646
+ if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1647
+ let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1648
+ return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1649
+ }
1650
+ return "0x";
1651
+ }, fr = async (e) => {
1652
+ let t;
1653
+ try {
1654
+ t = await C.find({ seedLocalId: e });
1655
+ } catch {}
1656
+ return t || new Promise((t) => {
1657
+ let n = setInterval(() => {
1658
+ try {
1659
+ C.find({ seedLocalId: e }).then((e) => {
1660
+ e && (clearInterval(n), t(e));
1661
+ });
1662
+ } catch {}
1663
+ }, 200);
1664
+ });
1665
+ }, pr = A(async ({ input: { context: t, event: n } }) => {
1666
+ let { address: r, account: i, wallet: a } = t, o = t.arweaveTransactions ?? [], c = t.publishUploads ?? [], { item: u } = t;
1667
+ if (!r || typeof r != "string" || !r.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
1668
+ if (!a && !i) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
1669
+ if (!u?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
1670
+ if (typeof u.getPublishUploads != "function" && (u = await fr(u.seedLocalId)), o.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.");
1671
+ let d = On(t), f = d.txSender;
1672
+ await I(u, d);
1673
+ let h = o.map((e, t) => {
1674
+ let n = e.transaction?.id;
1675
+ 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.");
1676
+ let r = c[t];
1677
+ if (!r) throw Error("Publish upload index mismatch");
1678
+ return {
1679
+ ...r,
1680
+ txId: n
1681
+ };
1682
+ });
1683
+ await Pn(h.map((e) => e.txId));
1684
+ let g = await u.getPublishPayload(h, { publishMode: t.publishMode ?? "patch" }), _ = (Array.isArray(g) ? g : [g]).map((e) => {
1685
+ let t = (e?.listOfAttestations ?? []).map((e) => {
1686
+ let t = Array.isArray(e?.data) ? e.data : [];
1687
+ return {
1688
+ schema: K(e?.schema),
1689
+ data: t.map((e) => ({
1690
+ ...e,
1691
+ refUID: K(e?.refUID),
1692
+ data: dr(e?.data)
1693
+ })),
1694
+ ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
1695
+ ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
1696
+ };
1697
+ }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
1698
+ ...e,
1699
+ propertySchemaUid: K(e?.propertySchemaUid)
1700
+ }));
1701
+ return {
1702
+ ...e,
1703
+ seedUid: K(e?.seedUid),
1704
+ seedSchemaUid: K(e?.seedSchemaUid),
1705
+ versionUid: K(e?.versionUid),
1706
+ versionSchemaUid: K(e?.versionSchemaUid),
1707
+ listOfAttestations: t,
1708
+ propertiesToUpdate: n
1709
+ };
1710
+ }), v = new Map(_.map((e) => [e.localId, e])), ee = {
1711
+ recipient: qe,
1712
+ expirationTime: BigInt(0),
1713
+ revocable: !0,
1714
+ refUID: p,
1715
+ data: p,
1716
+ value: BigInt(0)
1717
+ };
1718
+ for (let e of _) for (let t of e.propertiesToUpdate ?? []) {
1719
+ let e = t.publishLocalId, n = K(t.propertySchemaUid);
1720
+ if (!e || !n) continue;
1721
+ let r = v.get(e);
1722
+ if (!r?.listOfAttestations) continue;
1723
+ let i = r.listOfAttestations.find((e) => K(e?.schema)?.toLowerCase() === n?.toLowerCase());
1724
+ i && (!Array.isArray(i.data) || i.data.length === 0) && (i.data = [{
1725
+ ...ee,
1726
+ refUID: p
1727
+ }]);
1728
+ }
1729
+ let b = Date.now();
1730
+ for (let t = 0; t < _.length; t++) {
1731
+ let n = _[t], i = n.seedUid, a = n.versionUid;
1732
+ if (i === p) {
1733
+ let t = me({
1734
+ schema: n.seedSchemaUid,
1735
+ data: {
1736
+ refUID: p,
1737
+ data: l(n.seedSchemaUid),
1738
+ revocable: n.seedIsRevocable
1739
+ }
1740
+ }), r = await m((await f.sendTransaction(t)).transactionHash);
1741
+ if (!r) throw Error("Failed to create Seed attestation");
1742
+ b = await U(r);
1743
+ let { easContractAddress: a } = s(), o = e(r, a);
1744
+ if (!o || o === p) throw Error("Failed to get Seed UID from attestation receipt");
1745
+ i = o, n.seedUid = o, G("created Seed attestation", i);
1746
+ }
1747
+ if (i !== p && a === p) {
1748
+ let t = me({
1749
+ schema: n.versionSchemaUid,
1750
+ data: {
1751
+ refUID: i,
1752
+ data: l(n.versionSchemaUid),
1753
+ revocable: !0
1754
+ }
1755
+ }), o = await m((await f.sendTransaction(t)).transactionHash);
1756
+ if (!o) throw Error("Failed to create Version attestation");
1757
+ b = await U(o);
1758
+ let { easContractAddress: c } = s(), u = e(o, c);
1759
+ if (!u || u === p) throw Error("Failed to get Version UID from attestation receipt");
1760
+ a = u, n.versionUid = u, await Le({
1761
+ seedLocalId: n.localId,
1762
+ versionUid: u,
1763
+ publisher: r,
1764
+ attestationCreatedAt: b
1765
+ }), G("created Version attestation", a);
1766
+ }
1767
+ for (let e of n.listOfAttestations) for (let t of e.data) t.refUID = a;
1768
+ for (let e of n.propertiesToUpdate ?? []) {
1769
+ let t = v.get(e.publishLocalId);
1770
+ if (!t?.listOfAttestations) continue;
1771
+ let n = K(e.propertySchemaUid), r = t.listOfAttestations.find((e) => K(e?.schema)?.toLowerCase() === n?.toLowerCase());
1772
+ r?.data?.[0] && (r.data[0].data = l(i));
1773
+ }
1774
+ let o = n.listOfAttestations.map((e) => ({
1775
+ schema: e.schema,
1776
+ data: e.data.map((e) => ({
1777
+ recipient: e.recipient ?? qe,
1778
+ expirationTime: e.expirationTime ?? 0n,
1779
+ revocable: e.revocable ?? !0,
1780
+ refUID: e.refUID ?? p,
1781
+ data: e.data ?? "0x",
1782
+ value: e.value ?? 0n
1783
+ }))
1784
+ }));
1785
+ if (o.length > 0) {
1786
+ let e = se(o), r = await m((await f.sendTransaction(e)).transactionHash);
1787
+ if (!r) throw Error("Failed to create property attestations");
1788
+ b = await U(r), G("created property attestations for request", t);
1789
+ let { easContractAddress: i } = s(), c = y(r, i), l = n.listOfAttestations, u = c.length === l.length;
1790
+ await Se({
1791
+ seedLocalId: n.localId,
1792
+ attestationCreatedAtMs: b ?? null,
1793
+ versionUid: a === p ? null : a,
1794
+ pairs: c.map((e, t) => ({
1795
+ schemaUid: e.schemaUid,
1796
+ attestationUid: e.uid,
1797
+ propertyName: u && typeof l[t]?._propertyName == "string" && l[t]._propertyName !== "" ? l[t]._propertyName : void 0
1798
+ }))
1799
+ });
1800
+ }
1801
+ }
1802
+ Mn(u, _);
1803
+ let te = u;
1804
+ _[0]?.seedUid && _[0].seedUid !== p && await Nn(te, r, b);
1805
+ try {
1806
+ await lr({
1807
+ normalizedRequests: _,
1808
+ item: u
1809
+ });
1810
+ } catch (e) {
1811
+ throw e instanceof _e || G("verifyAttestations failed (non-verification error):", e), e;
1812
+ }
1813
+ G("direct EAS publish complete"), Yn(t);
1814
+ try {
1815
+ let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk");
1816
+ await e(u.seedLocalId);
1817
+ } catch {}
1818
+ return { easPayload: g };
1819
+ }), mr = async (e) => {
1820
+ let t;
1821
+ try {
1822
+ t = await C.find({ seedLocalId: e });
1823
+ } catch {}
1824
+ return t || new Promise((t) => {
1825
+ let n = setInterval(() => {
1826
+ C.find({ seedLocalId: e }).then((e) => {
1827
+ e && (clearInterval(n), t(e));
1828
+ }).catch(() => {});
1829
+ }, 200);
1830
+ });
1831
+ };
1832
+ async function hr(e) {
1833
+ return await Me(typeof e.getPublishUploads == "function" ? e : await mr(e.seedLocalId));
1834
+ }
1835
+ //#endregion
1836
+ //#region src/services/publish/actors/checking.ts
1837
+ var q = /* @__PURE__ */ new Set();
1838
+ async function gr(e) {
1839
+ let t = s();
1840
+ return t.useDirectEas ? "directEas" : t.useModularExecutor || await re(e) ? "multiPublish" : "directEas";
1841
+ }
1842
+ var _r = k(({ sendBack: e, input: { context: t } }) => {
1843
+ let { item: n, account: r, wallet: i, publishMode: a, address: o } = t;
1844
+ return (async () => {
1845
+ if (!await je(n)) {
1846
+ e({ type: "notOwner" });
1847
+ return;
1848
+ }
1849
+ if (q.has(n.seedLocalId)) {
1850
+ e({ type: "redundantPublishProcess" });
1851
+ return;
1852
+ }
1853
+ q.add(n.seedLocalId);
1854
+ try {
1855
+ let t = i ?? r;
1856
+ t && await I(n, t);
1857
+ let c = await Re(n, [], { publishMode: a ?? "patch" });
1858
+ if (!c.isValid) {
1859
+ q.delete(n.seedLocalId), e({
1860
+ type: "validationFailed",
1861
+ errors: c.errors
1862
+ });
1863
+ return;
1864
+ }
1865
+ if (!o || typeof o != "string" || !o.trim()) {
1866
+ q.delete(n.seedLocalId), e({
1867
+ type: "validationFailed",
1868
+ errors: [{ message: "No publisher address for publish. Connect a wallet and try again." }]
1869
+ });
1870
+ return;
1871
+ }
1872
+ let l;
1873
+ try {
1874
+ l = await gr(o.trim());
1875
+ } catch (t) {
1876
+ q.delete(n.seedLocalId), e({
1877
+ type: "checkingFailed",
1878
+ error: Error("Could not verify whether the publisher is a deployed contract on Optimism Sepolia. Check your RPC connection and retry.", { cause: t })
1879
+ });
1880
+ return;
1881
+ }
1882
+ let u = await hr(n), d = s().useArweaveBundler, f = { attestationStrategy: l };
1883
+ e(u ? d ? {
1884
+ type: "validPublishProcessBundler",
1885
+ ...f
1886
+ } : {
1887
+ type: "validPublishProcess",
1888
+ ...f
1889
+ } : {
1890
+ type: "skipArweave",
1891
+ ...f
1892
+ });
1893
+ } catch (t) {
1894
+ q.delete(n.seedLocalId), console.error("[checking] failed", t), e({
1895
+ type: "checkingFailed",
1896
+ error: t instanceof Error ? t : Error(String(t))
1897
+ });
1898
+ }
1899
+ })().catch((t) => {
1900
+ q.delete(n.seedLocalId), console.error("[checking] unhandled rejection", t), e({
1901
+ type: "checkingFailed",
1902
+ error: t instanceof Error ? t : Error(String(t))
1903
+ });
1904
+ }), () => {
1905
+ q.delete(n.seedLocalId);
1906
+ };
1907
+ }), { SUCCESS: vr, FAILURE: J } = i;
1908
+ function Y(e) {
1909
+ let t = e.attestationStrategy;
1910
+ return t === "directEas" ? !0 : t === "multiPublish" ? !1 : s().useDirectEas;
1911
+ }
1912
+ function X(e) {
1913
+ let t = e.attestationStrategy;
1914
+ return t === "multiPublish" ? !0 : t === "directEas" ? !1 : !s().useDirectEas;
1915
+ }
1916
+ function Z(e) {
1917
+ let t = e;
1918
+ return t.error ?? t.data;
1919
+ }
1920
+ var yr = Ze({
1921
+ types: {
1922
+ context: {},
1923
+ input: {}
1924
+ },
1925
+ actors: {
1926
+ createArweaveTransactions: dt,
1927
+ createArweaveTransactionsPhase2: ft,
1928
+ createArweaveDataItems: Zt,
1929
+ createArweaveDataItemsPhase2: $t,
1930
+ sendReimbursementRequest: sn,
1931
+ pollForConfirmation: cn,
1932
+ uploadData: un,
1933
+ uploadViaBundler: hn,
1934
+ createAttestations: nr,
1935
+ createAttestationsDirectToEas: pr,
1936
+ checking: _r,
1937
+ preparingHtmlEmbedded: pt,
1938
+ rewritingHtmlEmbedded: ht
1939
+ },
1940
+ actions: {
1941
+ handleError: ({ event: e }) => {
1942
+ let t = Z(e);
1943
+ t == null ? console.error("Unknown error (full event):", e) : console.error(t);
1944
+ },
1945
+ assignErrorCreatingArweaveTransactions: O({
1946
+ error: ({ event: e }) => Z(e),
1947
+ errorStep: () => "creatingArweaveTransactions"
1948
+ }),
1949
+ assignErrorCreatingArweaveDataItems: O({
1950
+ error: ({ event: e }) => Z(e),
1951
+ errorStep: () => "creatingArweaveDataItems"
1952
+ }),
1953
+ assignErrorSendingReimbursementRequest: O({
1954
+ error: ({ event: e }) => Z(e),
1955
+ errorStep: () => "sendingReimbursementRequest"
1956
+ }),
1957
+ assignErrorPollingForConfirmation: O({
1958
+ error: ({ event: e }) => Z(e),
1959
+ errorStep: () => "pollingForConfirmation"
1960
+ }),
1961
+ assignErrorUploadingData: O({
1962
+ error: ({ event: e }) => Z(e),
1963
+ errorStep: () => "uploadingData"
1964
+ }),
1965
+ assignErrorPreparingHtmlEmbedded: O({
1966
+ error: ({ event: e }) => Z(e),
1967
+ errorStep: () => "preparingHtmlEmbedded"
1968
+ }),
1969
+ assignErrorRewritingHtmlEmbedded: O({
1970
+ error: ({ event: e }) => Z(e),
1971
+ errorStep: () => "rewritingHtmlEmbedded"
1972
+ }),
1973
+ assignErrorCreatingArweaveTransactionsPhase2: O({
1974
+ error: ({ event: e }) => Z(e),
1975
+ errorStep: () => "creatingArweaveTransactionsPhase2"
1976
+ }),
1977
+ assignErrorUploadingDataPhase2: O({
1978
+ error: ({ event: e }) => Z(e),
1979
+ errorStep: () => "uploadingDataPhase2"
1980
+ }),
1981
+ assignErrorUploadingViaBundler: O({
1982
+ error: ({ event: e }) => Z(e),
1983
+ errorStep: () => "uploadingViaBundler"
1984
+ }),
1985
+ assignErrorCreatingArweaveDataItemsPhase2: O({
1986
+ error: ({ event: e }) => Z(e),
1987
+ errorStep: () => "creatingArweaveDataItemsPhase2"
1988
+ }),
1989
+ assignErrorUploadingViaBundlerPhase2: O({
1990
+ error: ({ event: e }) => Z(e),
1991
+ errorStep: () => "uploadingViaBundlerPhase2"
1992
+ }),
1993
+ assignErrorCreatingAttestations: O({
1994
+ error: ({ event: e }) => Z(e),
1995
+ errorStep: () => "creatingAttestations"
1996
+ }),
1997
+ assignErrorCreatingAttestationsDirectToEas: O({
1998
+ error: ({ event: e }) => Z(e),
1999
+ errorStep: () => "creatingAttestationsDirectToEas"
2000
+ }),
2001
+ assignAccountFromRetry: O({
2002
+ wallet: ({ event: e }) => {
2003
+ let t = e;
2004
+ return t.wallet ?? t.account;
2005
+ },
2006
+ account: ({ event: e }) => {
2007
+ let t = e;
2008
+ return t.wallet ?? t.account;
2009
+ }
2010
+ }),
2011
+ assignErrorNotOwner: O({
2012
+ error: () => /* @__PURE__ */ Error("Item is read-only: you do not own this item. Only the publisher can publish."),
2013
+ errorStep: () => "checking"
2014
+ }),
2015
+ assignErrorValidationFailed: O({
2016
+ error: ({ event: e }) => {
2017
+ 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);
2018
+ return r.validationErrors = t, r;
2019
+ },
2020
+ errorStep: () => "checking"
2021
+ }),
2022
+ assignErrorCheckingFailed: O({
2023
+ error: ({ event: e }) => {
2024
+ let t = e.error;
2025
+ return t instanceof Error ? t : Error(String(t ?? "Publish check failed"));
2026
+ },
2027
+ errorStep: () => "checking"
2028
+ })
2029
+ }
2030
+ }).createMachine({
2031
+ id: "publish",
2032
+ initial: "checking",
2033
+ context: ({ input: e }) => e,
2034
+ states: {
2035
+ checking: {
2036
+ on: {
2037
+ notOwner: {
2038
+ target: J,
2039
+ actions: ["assignErrorNotOwner", "handleError"]
2040
+ },
2041
+ validationFailed: {
2042
+ target: J,
2043
+ actions: ["assignErrorValidationFailed", "handleError"]
2044
+ },
2045
+ redundantPublishProcess: { target: "stopping" },
2046
+ checkingFailed: {
2047
+ target: J,
2048
+ actions: ["assignErrorCheckingFailed", "handleError"]
2049
+ },
2050
+ validPublishProcess: {
2051
+ target: "preparingHtmlEmbedded",
2052
+ actions: O({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2053
+ },
2054
+ validPublishProcessBundler: {
2055
+ target: "preparingHtmlEmbedded",
2056
+ actions: O({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2057
+ },
2058
+ skipArweave: [{
2059
+ guard: ({ context: e }) => Y(e),
2060
+ target: "creatingAttestationsDirectToEas",
2061
+ actions: O({
2062
+ arweaveTransactions: () => [],
2063
+ publishUploads: () => [],
2064
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2065
+ })
2066
+ }, {
2067
+ guard: ({ context: e }) => X(e),
2068
+ target: "creatingAttestations",
2069
+ actions: O({
2070
+ arweaveTransactions: () => [],
2071
+ publishUploads: () => [],
2072
+ attestationStrategy: ({ event: e }) => e.attestationStrategy
2073
+ })
2074
+ }]
2075
+ },
2076
+ invoke: {
2077
+ src: "checking",
2078
+ input: ({ context: e }) => ({ context: e })
2079
+ }
2080
+ },
2081
+ preparingHtmlEmbedded: { invoke: {
2082
+ src: "preparingHtmlEmbedded",
2083
+ input: ({ context: e }) => ({ context: e }),
2084
+ onDone: [{
2085
+ guard: () => s().useArweaveBundler,
2086
+ target: "creatingArweaveDataItems",
2087
+ actions: O({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2088
+ }, {
2089
+ target: "creatingArweaveTransactions",
2090
+ actions: O({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2091
+ }],
2092
+ onError: {
2093
+ target: J,
2094
+ actions: ["assignErrorPreparingHtmlEmbedded", "handleError"]
2095
+ }
2096
+ } },
2097
+ creatingArweaveTransactions: { invoke: {
2098
+ src: "createArweaveTransactions",
2099
+ input: ({ context: e, event: t }) => ({
2100
+ context: e,
2101
+ event: t
2102
+ }),
2103
+ onDone: {
2104
+ target: "sendingReimbursementRequest",
2105
+ actions: O({
2106
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2107
+ publishUploads: ({ event: e }) => e.output.publishUploads
2108
+ })
2109
+ },
2110
+ onError: {
2111
+ target: "failure",
2112
+ actions: ["assignErrorCreatingArweaveTransactions", "handleError"]
2113
+ }
2114
+ } },
2115
+ creatingArweaveDataItems: { invoke: {
2116
+ src: "createArweaveDataItems",
2117
+ input: ({ context: e, event: t }) => ({
2118
+ context: e,
2119
+ event: t
2120
+ }),
2121
+ onDone: {
2122
+ target: "uploadingViaBundler",
2123
+ actions: O({
2124
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2125
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2126
+ signedDataItems: ({ event: e }) => e.output.signedDataItems
2127
+ })
2128
+ },
2129
+ onError: {
2130
+ target: "failure",
2131
+ actions: ["assignErrorCreatingArweaveDataItems", "handleError"]
2132
+ }
2133
+ } },
2134
+ sendingReimbursementRequest: { invoke: {
2135
+ src: "sendReimbursementRequest",
2136
+ input: ({ context: e, event: t }) => ({
2137
+ context: e,
2138
+ event: t
2139
+ }),
2140
+ onDone: {
2141
+ target: "pollingForConfirmation",
2142
+ actions: O({
2143
+ requestResponse: ({ event: e }) => e.output,
2144
+ reimbursementTransactionId: ({ event: e }) => e.output.transactionId
2145
+ })
2146
+ },
2147
+ onError: {
2148
+ target: "failure",
2149
+ actions: ["assignErrorSendingReimbursementRequest", "handleError"]
2150
+ }
2151
+ } },
2152
+ pollingForConfirmation: { invoke: {
2153
+ src: "pollForConfirmation",
2154
+ input: ({ context: e, event: t }) => ({
2155
+ context: e,
2156
+ event: t
2157
+ }),
2158
+ onDone: {
2159
+ target: "uploadingData",
2160
+ actions: O({ reimbursementConfirmed: !0 })
2161
+ },
2162
+ onError: {
2163
+ target: "failure",
2164
+ actions: ["assignErrorPollingForConfirmation", "handleError"]
2165
+ }
2166
+ } },
2167
+ uploadingViaBundler: {
2168
+ on: {
2169
+ uploadComplete: [
2170
+ {
2171
+ guard: ({ context: e }) => Y(e),
2172
+ target: "creatingAttestationsDirectToEas",
2173
+ actions: O({
2174
+ completionPercentage: 100,
2175
+ signedDataItems: () => void 0,
2176
+ arweaveUploadData: () => void 0
2177
+ })
2178
+ },
2179
+ {
2180
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2181
+ target: "rewritingHtmlEmbedded",
2182
+ actions: O({
2183
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2184
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? [],
2185
+ signedDataItems: () => void 0,
2186
+ arweaveUploadData: () => void 0
2187
+ })
2188
+ },
2189
+ {
2190
+ guard: ({ context: e }) => X(e),
2191
+ target: "creatingAttestations",
2192
+ actions: O({
2193
+ completionPercentage: 100,
2194
+ signedDataItems: () => void 0,
2195
+ arweaveUploadData: () => void 0
2196
+ })
2197
+ }
2198
+ ],
2199
+ uploadError: {
2200
+ target: "failure",
2201
+ actions: ["assignErrorUploadingViaBundler", "handleError"]
2202
+ }
2203
+ },
2204
+ invoke: {
2205
+ src: "uploadViaBundler",
2206
+ input: ({ context: e }) => ({ context: e })
2207
+ }
2208
+ },
2209
+ creatingArweaveDataItemsPhase2: { invoke: {
2210
+ src: "createArweaveDataItemsPhase2",
2211
+ input: ({ context: e, event: t }) => ({
2212
+ context: e,
2213
+ event: t
2214
+ }),
2215
+ onDone: {
2216
+ target: "uploadingViaBundlerPhase2",
2217
+ actions: O({
2218
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2219
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2220
+ signedDataItems: ({ event: e }) => e.output.signedDataItems,
2221
+ uploaderState: () => void 0,
2222
+ currentTransactionIndex: () => void 0
2223
+ })
2224
+ },
2225
+ onError: {
2226
+ target: J,
2227
+ actions: ["assignErrorCreatingArweaveDataItemsPhase2", "handleError"]
2228
+ }
2229
+ } },
2230
+ uploadingViaBundlerPhase2: {
2231
+ on: {
2232
+ uploadComplete: [{
2233
+ guard: ({ context: e }) => Y(e),
2234
+ target: "creatingAttestationsDirectToEas",
2235
+ actions: O({
2236
+ completionPercentage: 100,
2237
+ signedDataItems: () => void 0,
2238
+ arweaveUploadData: () => void 0
2239
+ })
2240
+ }, {
2241
+ guard: ({ context: e }) => X(e),
2242
+ target: "creatingAttestations",
2243
+ actions: O({
2244
+ completionPercentage: 100,
2245
+ signedDataItems: () => void 0,
2246
+ arweaveUploadData: () => void 0,
2247
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2248
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2249
+ })
2250
+ }],
2251
+ uploadError: {
2252
+ target: J,
2253
+ actions: ["assignErrorUploadingViaBundlerPhase2", "handleError"]
2254
+ }
2255
+ },
2256
+ invoke: {
2257
+ src: "uploadViaBundler",
2258
+ input: ({ context: e }) => ({ context: e })
2259
+ }
2260
+ },
2261
+ uploadingData: {
2262
+ on: {
2263
+ updatePercentage: { actions: O({
2264
+ completionPercentage: ({ event: e }) => e.completionPercentage,
2265
+ uploaderState: ({ event: e }) => e.uploaderState,
2266
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2267
+ }) },
2268
+ uploadComplete: [
2269
+ {
2270
+ guard: ({ context: e }) => Y(e),
2271
+ target: "creatingAttestationsDirectToEas",
2272
+ actions: O({ completionPercentage: 100 })
2273
+ },
2274
+ {
2275
+ guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2276
+ target: "rewritingHtmlEmbedded",
2277
+ actions: O({
2278
+ htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2279
+ htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? []
2280
+ })
2281
+ },
2282
+ {
2283
+ guard: ({ context: e }) => X(e),
2284
+ target: "creatingAttestations",
2285
+ actions: O({ completionPercentage: 100 })
2286
+ }
2287
+ ],
2288
+ uploadError: {
2289
+ target: "failure",
2290
+ actions: ["assignErrorUploadingData", "handleError"]
2291
+ }
2292
+ },
2293
+ invoke: {
2294
+ src: "uploadData",
2295
+ input: ({ context: e }) => ({ context: e })
2296
+ }
2297
+ },
2298
+ rewritingHtmlEmbedded: { invoke: {
2299
+ src: "rewritingHtmlEmbedded",
2300
+ input: ({ context: e }) => ({ context: e }),
2301
+ onDone: [{
2302
+ guard: () => !s().useArweaveBundler,
2303
+ target: "creatingArweaveTransactionsPhase2"
2304
+ }, {
2305
+ guard: () => s().useArweaveBundler,
2306
+ target: "creatingArweaveDataItemsPhase2"
2307
+ }],
2308
+ onError: {
2309
+ target: J,
2310
+ actions: ["assignErrorRewritingHtmlEmbedded", "handleError"]
2311
+ }
2312
+ } },
2313
+ creatingArweaveTransactionsPhase2: { invoke: {
2314
+ src: "createArweaveTransactionsPhase2",
2315
+ input: ({ context: e, event: t }) => ({
2316
+ context: e,
2317
+ event: t
2318
+ }),
2319
+ onDone: {
2320
+ target: "uploadingDataPhase2",
2321
+ actions: O({
2322
+ arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2323
+ publishUploads: ({ event: e }) => e.output.publishUploads,
2324
+ uploaderState: () => void 0,
2325
+ currentTransactionIndex: () => void 0
2326
+ })
2327
+ },
2328
+ onError: {
2329
+ target: J,
2330
+ actions: ["assignErrorCreatingArweaveTransactionsPhase2", "handleError"]
2331
+ }
2332
+ } },
2333
+ uploadingDataPhase2: {
2334
+ on: {
2335
+ updatePercentage: { actions: O({
2336
+ completionPercentage: ({ event: e }) => e.completionPercentage,
2337
+ uploaderState: ({ event: e }) => e.uploaderState,
2338
+ currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2339
+ }) },
2340
+ uploadComplete: [{
2341
+ guard: ({ context: e }) => Y(e),
2342
+ target: "creatingAttestationsDirectToEas",
2343
+ actions: O({ completionPercentage: 100 })
2344
+ }, {
2345
+ guard: ({ context: e }) => X(e),
2346
+ target: "creatingAttestations",
2347
+ actions: O({
2348
+ completionPercentage: 100,
2349
+ publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2350
+ arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2351
+ })
2352
+ }],
2353
+ uploadError: {
2354
+ target: J,
2355
+ actions: ["assignErrorUploadingDataPhase2", "handleError"]
2356
+ }
2357
+ },
2358
+ invoke: {
2359
+ src: "uploadData",
2360
+ input: ({ context: e }) => ({ context: e })
2361
+ }
2362
+ },
2363
+ creatingAttestations: { invoke: {
2364
+ src: "createAttestations",
2365
+ input: ({ context: e, event: t }) => ({
2366
+ context: e,
2367
+ event: t
2368
+ }),
2369
+ onDone: {
2370
+ target: vr,
2371
+ actions: O({ easPayload: ({ event: e }) => e.output?.easPayload })
2372
+ },
2373
+ onError: {
2374
+ target: "attestationFailureRecoverable",
2375
+ actions: ["assignErrorCreatingAttestations", "handleError"]
2376
+ }
2377
+ } },
2378
+ attestationFailureRecoverable: { on: { retry: {
2379
+ target: "creatingAttestations",
2380
+ actions: ["assignAccountFromRetry"]
2381
+ } } },
2382
+ creatingAttestationsDirectToEas: { invoke: {
2383
+ src: "createAttestationsDirectToEas",
2384
+ input: ({ context: e, event: t }) => ({
2385
+ context: e,
2386
+ event: t
2387
+ }),
2388
+ onDone: {
2389
+ target: vr,
2390
+ actions: O({ easPayload: ({ event: e }) => e.output?.easPayload })
2391
+ },
2392
+ onError: {
2393
+ target: "attestationFailureRecoverableDirectToEas",
2394
+ actions: ["assignErrorCreatingAttestationsDirectToEas", "handleError"]
2395
+ }
2396
+ } },
2397
+ attestationFailureRecoverableDirectToEas: { on: { retry: {
2398
+ target: "creatingAttestationsDirectToEas",
2399
+ actions: ["assignAccountFromRetry"]
2400
+ } } },
2401
+ stopping: {
2402
+ entry: ({ context: e }) => {
2403
+ console.log(`Actor for ${e.item?.seedLocalId} stopped`);
2404
+ },
2405
+ type: "final"
2406
+ },
2407
+ [vr]: {
2408
+ entry: ({ context: e }) => {},
2409
+ type: "final"
2410
+ },
2411
+ [J]: {
2412
+ entry: ({ context: e }) => {},
2413
+ type: "final"
2414
+ }
2415
+ }
2416
+ }), br = O(({ context: e, event: t }) => {
2417
+ let n = t, r = n.publishProcesses ?? /* @__PURE__ */ new Map(), i = n.subscriptions ?? /* @__PURE__ */ new Map();
2418
+ return {
2419
+ publishProcesses: new Map(r),
2420
+ subscriptions: new Map(i)
2421
+ };
2422
+ }), xr = null;
2423
+ function Sr(e) {
2424
+ xr = e;
2425
+ }
2426
+ function Cr() {
2427
+ return xr;
2428
+ }
2429
+ //#endregion
2430
+ //#region src/services/publishManager/actors/subscribe.ts
2431
+ var wr = j("seedProtocol:services:PublishManager:actors:subscribe");
2432
+ function Tr(e) {
2433
+ let t = e.value;
2434
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
2435
+ }
2436
+ function Er(e) {
2437
+ return n.includes(e);
2438
+ }
2439
+ var Dr = k(({ receive: e, input: { publishProcess: t, seedLocalId: n } }) => {
2440
+ let r = Cr(), i = null, a = () => {
2441
+ i != null && (clearInterval(i), i = null);
2442
+ }, o = (e) => {
2443
+ let o = Tr(e);
2444
+ Er(o) && i == null && r ? i = setInterval(() => {
2445
+ try {
2446
+ let e = t.getSnapshot();
2447
+ if (e.status === "done") {
2448
+ a();
2449
+ return;
2450
+ }
2451
+ if (!Er(Tr(e))) {
2452
+ a();
2453
+ return;
2454
+ }
2455
+ } catch {
2456
+ return;
2457
+ }
2458
+ r?.savePublish(n, t);
2459
+ }, d) : Er(o) || a();
2460
+ }, s = t.subscribe(async (e) => {
2461
+ wr("Publish state:", e.value), r && (e.status === "done" ? (a(), r.savePublish(n, t, { triggerPublishDone: !0 })) : (r.savePublish(n, t), o(e)));
2462
+ });
2463
+ e(({ type: e }) => {
2464
+ e === "UNSUBSCRIBE" && (wr("Received UNSUBSCRIBE event"), a(), s.unsubscribe(), r?.removeSubscription(n));
2465
+ });
2466
+ });
2467
+ //#endregion
2468
+ //#region src/services/publishManager/actions/createPublish.ts
2469
+ function Or(e) {
2470
+ if (e) {
2471
+ if (a(e)) return e;
2472
+ if (o(e)) {
2473
+ let t = f();
2474
+ if (t && t.signer.address.toLowerCase() === e.address.toLowerCase()) return t;
2475
+ throw Error("@seedprotocol/publish: createPublish requires a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.");
2476
+ }
2477
+ throw Error("@seedprotocol/publish: createPublish account must be a PublishWallet. Thirdweb Account must be wrapped with fromThirdwebAccount from @seedprotocol/publish/thirdweb.");
2478
+ }
2479
+ }
2480
+ function kr(e) {
2481
+ if (e) {
2482
+ if (e instanceof D.Wallet) return e;
2483
+ if (a(e)) return e.signer;
2484
+ if (o(e)) return e;
2485
+ }
2486
+ }
2487
+ var Ar = Xe(({ event: e, enqueue: t }) => {
2488
+ let { item: n, address: r, account: i, options: a } = e;
2489
+ if (!(r != null && typeof r == "string" && r.trim().length > 0)) {
2490
+ console.warn("[createPublish] No valid wallet address; skipping spawn.");
2491
+ return;
2492
+ }
2493
+ t.assign(({ context: e, spawn: t }) => {
2494
+ let { publishProcesses: o } = e;
2495
+ if (o && o.has(n.seedLocalId)) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" already exists.`), e;
2496
+ let c = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `run_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, l = s(), u = [...l.arweaveUploadTags ?? [], ...a?.arweaveUploadTags ?? []], d = Or(i) ?? f() ?? void 0, p = t(yr, { input: {
2497
+ item: n,
2498
+ address: r,
2499
+ wallet: d,
2500
+ account: d,
2501
+ modelName: n.modelName,
2502
+ schemaId: n.schemaUid,
2503
+ signDataItems: a?.signDataItems,
2504
+ dataItemSigner: kr(a?.dataItemSigner),
2505
+ signArweaveTransactions: a?.signArweaveTransactions,
2506
+ arweaveJwk: a?.arweaveJwk,
2507
+ publishMode: a?.publishMode ?? "patch",
2508
+ publishRunId: c,
2509
+ arweaveUploadTags: u.length ? u : void 0,
2510
+ htmlEmbeddedDataUriPolicy: a?.htmlEmbeddedDataUriPolicy ?? l.htmlEmbeddedDataUriPolicy ?? "materialize"
2511
+ } });
2512
+ return o.set(n.seedLocalId, p), {
2513
+ ...e,
2514
+ publishProcesses: o
2515
+ };
2516
+ }), t.assign(({ context: e, spawn: t }) => {
2517
+ let { subscriptions: r, publishProcesses: i } = e, a = i.get(n.seedLocalId);
2518
+ if (!a) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" does not exist.`), e;
2519
+ if (r.has(n.seedLocalId)) return console.warn(`Subscription with seedLocalId "${n.seedLocalId}" already exists.`), e;
2520
+ let o = t(Dr, { input: {
2521
+ publishProcess: a,
2522
+ seedLocalId: n.seedLocalId
2523
+ } });
2524
+ return r.set(n.seedLocalId, o), {
2525
+ ...e,
2526
+ subscriptions: new Map(r)
2527
+ };
2528
+ });
2529
+ }), jr = ({ context: e, event: t }) => {
2530
+ let { seedLocalId: n, account: r } = t, i = e.publishProcesses.get(n);
2531
+ if (!i) {
2532
+ console.warn(`Publish process with seedLocalId "${n}" does not exist.`);
2533
+ return;
2534
+ }
2535
+ let o = r == null ? f() ?? void 0 : a(r) ? r : void 0;
2536
+ r != null && !o && console.warn("[retryAttestations] account must be a PublishWallet. Use fromThirdwebAccount / fromEip1193Provider / fromEthersWallet."), i.send({
2537
+ type: "retry",
2538
+ account: o,
2539
+ wallet: o
2540
+ });
2541
+ };
2542
+ //#endregion
2543
+ //#region src/services/publishManager/actions/stopScopedOrStandaloneChild.ts
2544
+ function Mr(e, t, n) {
2545
+ t._parent === e ? n.stopChild(t) : t.stop();
2546
+ }
2547
+ //#endregion
2548
+ //#region src/services/publishManager/actors/savePublish.ts
2549
+ var Q = j("seedProtocol:services:PublishManager:actors:savePublish"), Nr = /* @__PURE__ */ new Map();
2550
+ function Pr(e, t) {
2551
+ let n = (Nr.get(e) ?? Promise.resolve()).then(t);
2552
+ return Nr.set(e, n.catch(() => {})), n;
2553
+ }
2554
+ function Fr(e) {
2555
+ return e === "completed" || e === "failed" || e === "interrupted";
2556
+ }
2557
+ function Ir(e) {
2558
+ return e.status === "done" ? e.value === "success" ? "completed" : e.value === "failure" ? "failed" : "completed" : "in_progress";
2559
+ }
2560
+ var Lr = 500, Rr = 2e3;
2561
+ function zr(e) {
2562
+ return JSON.stringify(e, (e, t) => typeof t == "bigint" ? t.toString() : t);
2563
+ }
2564
+ function Br(e) {
2565
+ if (typeof e != "object" || !e) return;
2566
+ let t = e, n = t.snapshot, r = (t.context ?? n?.context)?.publishRunId;
2567
+ return typeof r == "string" && r.length > 0 ? r : void 0;
2568
+ }
2569
+ function Vr(e, t) {
2570
+ if (!e?.error || t !== "failed" && t !== "in_progress") return {};
2571
+ let n = e.error, r = n == null ? void 0 : (n instanceof Error ? n.message : String(n)).slice(0, Lr), i = e.errorStep, a;
2572
+ if (n instanceof Error && n.stack) a = n.stack.slice(0, Rr);
2573
+ else if (typeof n == "object" && n) try {
2574
+ a = JSON.stringify(n).slice(0, Rr);
2575
+ } catch {
2576
+ a = String(n).slice(0, Rr);
2577
+ }
2578
+ else n != null && (a = String(n).slice(0, Rr));
2579
+ return {
2580
+ errorMessage: r ?? void 0,
2581
+ errorStep: i,
2582
+ errorDetails: a
2583
+ };
2584
+ }
2585
+ function Hr(e) {
2586
+ return Pr(e, async () => {
2587
+ let t = x.getAppDb();
2588
+ if (!t) {
2589
+ Q("markInProgressPublishInterrupted: DB not ready, skipping");
2590
+ return;
2591
+ }
2592
+ let n = await t.select().from(w).where($e(M(w.seedLocalId, e), M(w.status, "in_progress"))).orderBy(et(w.updatedAt)).limit(1);
2593
+ if (n.length === 0) return;
2594
+ let r = Date.now();
2595
+ await t.update(w).set({
2596
+ status: "interrupted",
2597
+ completedAt: r,
2598
+ updatedAt: r,
2599
+ errorMessage: null,
2600
+ errorStep: null,
2601
+ errorDetails: null
2602
+ }).where(M(w.id, n[0].id));
2603
+ });
2604
+ }
2605
+ var Ur = k(({ sendBack: e, input: { persistedSnapshot: t, seedLocalId: n, triggerPublishDone: r } }) => {
2606
+ Q("savePublish seedLocalId", n);
2607
+ let i = t;
2608
+ Pr(n, async () => {
2609
+ let a = x.getAppDb();
2610
+ if (!a) {
2611
+ Q("savePublish: DB not ready, skipping"), e({
2612
+ type: "SAVE_PUBLISH_DONE",
2613
+ seedLocalId: n,
2614
+ triggerPublishDone: r
2615
+ });
2616
+ return;
2617
+ }
2618
+ let o = await a.select().from(w).where($e(M(w.seedLocalId, n), M(w.status, "in_progress"))).orderBy(et(w.updatedAt)).limit(1), s = typeof t == "string" ? t : zr(t), c = Ir(i), l = Date.now(), u = Vr(i.context, c);
2619
+ if (o.length > 0) {
2620
+ let e = o[0];
2621
+ await a.update(w).set({
2622
+ persistedSnapshot: s,
2623
+ status: c,
2624
+ updatedAt: l,
2625
+ ...i.status === "done" && c !== "in_progress" ? { completedAt: l } : {},
2626
+ ...u
2627
+ }).where(M(w.id, e.id));
2628
+ } else {
2629
+ let e = Br(i);
2630
+ if (e != null && c === "in_progress" && i.status !== "done") {
2631
+ let t = (await a.select().from(w).where(M(w.seedLocalId, n)).orderBy(et(w.startedAt)).limit(1))[0];
2632
+ if (t && Fr(t.status)) try {
2633
+ if (Br(JSON.parse(t.persistedSnapshot)) === e) {
2634
+ Q("savePublish: skip stale insert — same publishRunId as latest terminal row", n, e);
2635
+ return;
2636
+ }
2637
+ } catch {}
2638
+ }
2639
+ let t = i.context?.item, r = i.context?.modelName ?? t?.modelName ?? "", o = i.context?.schemaId ?? t?.schemaId;
2640
+ await a.insert(w).values({
2641
+ seedLocalId: n,
2642
+ modelName: r,
2643
+ schemaId: o ?? null,
2644
+ status: c,
2645
+ startedAt: l,
2646
+ persistedSnapshot: s,
2647
+ createdAt: l,
2648
+ updatedAt: l,
2649
+ ...u
2650
+ });
2651
+ }
2652
+ }).then(() => {
2653
+ e({
2654
+ type: "SAVE_PUBLISH_DONE",
2655
+ seedLocalId: n,
2656
+ triggerPublishDone: r
2657
+ });
2658
+ }).catch((t) => {
2659
+ Q("savePublish error", t), e({
2660
+ type: "SAVE_PUBLISH_DONE",
2661
+ seedLocalId: n,
2662
+ triggerPublishDone: r
2663
+ });
2664
+ });
2665
+ }), Wr = Xe(({ context: e, event: t, enqueue: n, self: r }) => {
2666
+ let { publishProcesses: i, subscriptions: a } = e, { seedLocalId: o } = t;
2667
+ Hr(o).catch((e) => {
2668
+ console.warn(`[stopPublish] Failed to mark publish_processes row interrupted for "${o}":`, e);
2669
+ });
2670
+ let s = i.get(o);
2671
+ if (!s) {
2672
+ console.warn(`Publish process with seedLocalId "${o}" does not exist.`);
2673
+ return;
2674
+ }
2675
+ Mr(r, s, n);
2676
+ let c = a.get(o);
2677
+ c && Mr(r, c, n);
2678
+ let l = new Map(i);
2679
+ l.delete(o);
2680
+ let u = new Map(a);
2681
+ u.delete(o), n.assign({
2682
+ publishProcesses: l,
2683
+ subscriptions: u
2684
+ });
2685
+ }), Gr = j("seedProtocol:PublishManager:index"), Kr = Xe(({ context: e, enqueue: t, self: n }) => {
2686
+ Gr("Stopping all actors..."), e.publishProcesses.forEach((e) => {
2687
+ Mr(n, e, t);
2688
+ }), e.subscriptions.forEach((e) => {
2689
+ Mr(n, e, t);
2690
+ }), t.assign({
2691
+ publishProcesses: /* @__PURE__ */ new Map(),
2692
+ subscriptions: /* @__PURE__ */ new Map()
2693
+ });
2694
+ }), qr = Xe(({ context: e, event: t, enqueue: n }) => {
2695
+ let { seedLocalId: r } = t, i = e.publishProcesses.get(r);
2696
+ if (!i) {
2697
+ console.warn(`Publish process with seedLocalId "${r}" does not exist.`);
2698
+ return;
2699
+ }
2700
+ n.stopChild(i);
2701
+ let a = e.subscriptions.get(r);
2702
+ a && n.stopChild(a);
2703
+ let o = new Map(e.publishProcesses);
2704
+ o.delete(r);
2705
+ let s = new Map(e.subscriptions);
2706
+ s.delete(r), n.assign({
2707
+ publishProcesses: o,
2708
+ subscriptions: s
2709
+ });
2710
+ }), Jr = O(({ context: e, event: t }) => {
2711
+ let { subscriptions: n } = e, { seedLocalId: r, newSubscription: i } = t;
2712
+ return i && n.set(r, i), { subscriptions: new Map(n) };
2713
+ }), Yr = ["signedDataItems", "arweaveUploadData"];
2714
+ function Xr(e) {
2715
+ if (typeof e != "object" || !e) return e;
2716
+ let t = { ...e };
2717
+ for (let e of Yr) delete t[e];
2718
+ return t;
2719
+ }
2720
+ function Zr(e) {
2721
+ if (typeof e != "object" || !e) return e;
2722
+ let t = e, n = { ...t };
2723
+ t.context != null && typeof t.context == "object" && (n.context = Xr(t.context));
2724
+ let r = t.snapshot;
2725
+ if (typeof r == "object" && r) {
2726
+ let e = r, t = { ...e };
2727
+ e.context != null && typeof e.context == "object" && (t.context = Xr(e.context)), n.snapshot = t;
2728
+ }
2729
+ return n;
2730
+ }
2731
+ function Qr(e) {
2732
+ try {
2733
+ return Zr(e.getPersistedSnapshot?.() ?? e.getSnapshot());
2734
+ } catch {
2735
+ let t = e.getSnapshot(), n = t.context;
2736
+ if (!n?.item) return Zr(t);
2737
+ let r = n.item;
2738
+ return Zr({
2739
+ ...t,
2740
+ context: {
2741
+ ...n,
2742
+ item: {
2743
+ seedLocalId: r.seedLocalId,
2744
+ modelName: r.modelName,
2745
+ schemaId: r.schemaId
2746
+ }
2747
+ }
2748
+ });
2749
+ }
2750
+ }
2751
+ var $r = O(({ context: e, event: t, spawn: n }) => {
2752
+ let { publishProcesses: r } = e, { seedLocalId: i, publishProcess: a, triggerPublishDone: o } = t;
2753
+ if (!a) return e;
2754
+ let s = new Map(r);
2755
+ s.set(i, a);
2756
+ let c = Qr(a);
2757
+ return n(Ur, {
2758
+ id: `savePublish_${i}_${Date.now()}`,
2759
+ input: {
2760
+ persistedSnapshot: c,
2761
+ seedLocalId: i,
2762
+ triggerPublishDone: o
2763
+ }
2764
+ }), { publishProcesses: s };
2765
+ }), ei = O(({ context: e, event: t }) => {
2766
+ let { publishProcesses: n, subscriptions: r } = e, i = t.seedLocalId, a = r.get(i);
2767
+ a && a.send({ type: "UNSUBSCRIBE" });
2768
+ let o = new Map(n);
2769
+ o.delete(i);
2770
+ let s = new Map(r);
2771
+ return s.delete(i), {
2772
+ publishProcesses: o,
2773
+ subscriptions: s
2774
+ };
2775
+ }), ti = O(({ context: e, event: t }) => {
2776
+ let { subscriptions: n } = e, r = t.seedLocalId, i = new Map(n);
2777
+ return i.delete(r), { subscriptions: i };
2778
+ }), ni = 6e4, ri = 2e3;
2779
+ async function ii(e) {
2780
+ let t = Date.now() + e;
2781
+ for (; Date.now() < t;) {
2782
+ try {
2783
+ if (x.isAppDbReady() && x.getAppDb()) return !0;
2784
+ } catch {}
2785
+ await new Promise((e) => setTimeout(e, ri));
2786
+ }
2787
+ return !1;
2788
+ }
2789
+ function ai(e) {
2790
+ let t = e.value;
2791
+ return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
2792
+ }
2793
+ function oi(e) {
2794
+ let t = ai(e);
2795
+ if (t === "pollingForConfirmation" && (!e.context?.reimbursementTransactionId || !e.context?.requestResponse)) return !1;
2796
+ if (t === "uploadingData") {
2797
+ let t = e.context?.arweaveTransactions, n = e.context?.publishUploads;
2798
+ if (!Array.isArray(t) || t.length === 0 || !Array.isArray(n)) return !1;
2799
+ }
2800
+ return !0;
2801
+ }
2802
+ function si(e) {
2803
+ return typeof e == "object" && !!e && "xstate$$type" in e && e.xstate$$type === 1 && typeof e.id == "string";
2804
+ }
2805
+ function ci(e, t, n) {
2806
+ e.context = e.context ?? {};
2807
+ let r = e.context.item;
2808
+ if (si(r)) {
2809
+ e.context.item = {
2810
+ seedLocalId: t,
2811
+ modelName: e.context.modelName ?? n.modelName ?? "",
2812
+ schemaId: e.context.schemaId ?? n.schemaId ?? void 0
2813
+ };
2814
+ return;
2815
+ }
2816
+ e.context.item = {
2817
+ ...typeof r == "object" && r && !Array.isArray(r) ? r : {},
2818
+ seedLocalId: t,
2819
+ modelName: r?.modelName ?? e.context.modelName ?? n.modelName ?? "",
2820
+ schemaId: r?.schemaId ?? e.context.schemaId ?? n.schemaId ?? void 0
2821
+ };
2822
+ }
2823
+ var li = k(({ sendBack: e, input: { context: t } }) => {
2824
+ (async () => {
2825
+ let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
2826
+ if (!await ii(ni)) return e({
2827
+ type: "RESTORE_FROM_DB_DONE",
2828
+ publishProcesses: t,
2829
+ subscriptions: n
2830
+ }), {
2831
+ newPublishProcesses: t,
2832
+ newSubscriptions: n
2833
+ };
2834
+ let r = x.getAppDb();
2835
+ if (!r) return e({
2836
+ type: "RESTORE_FROM_DB_DONE",
2837
+ publishProcesses: t,
2838
+ subscriptions: n
2839
+ }), {
2840
+ newPublishProcesses: t,
2841
+ newSubscriptions: n
2842
+ };
2843
+ let i = await r.select().from(w).where(M(w.status, "in_progress")), a = /* @__PURE__ */ new Map(), o = [...i].sort((e, t) => (t.updatedAt ?? t.createdAt ?? 0) - (e.updatedAt ?? e.createdAt ?? 0));
2844
+ for (let e of o) a.has(e.seedLocalId) || a.set(e.seedLocalId, e);
2845
+ let s = Array.from(a.values());
2846
+ for (let e of s) {
2847
+ let r;
2848
+ try {
2849
+ r = JSON.parse(e.persistedSnapshot);
2850
+ } catch {
2851
+ continue;
2852
+ }
2853
+ if (r.status === "done") continue;
2854
+ let i = r.context?.item?.seedLocalId ?? e.seedLocalId;
2855
+ if (!i || !oi(r)) continue;
2856
+ ci(r, i, e);
2857
+ let a = Ye(yr, {
2858
+ snapshot: r,
2859
+ input: void 0
2860
+ }), o = Ye(Dr, { input: {
2861
+ publishProcess: a,
2862
+ seedLocalId: i
2863
+ } });
2864
+ t.set(i, a), n.set(i, o), a.start(), o.start();
2865
+ }
2866
+ return {
2867
+ newPublishProcesses: t,
2868
+ newSubscriptions: n
2869
+ };
2870
+ })().then((t) => {
2871
+ if (!t) return;
2872
+ let { newPublishProcesses: n, newSubscriptions: r } = t;
2873
+ e({
2874
+ type: "RESTORE_FROM_DB_DONE",
2875
+ publishProcesses: n,
2876
+ subscriptions: r
2877
+ });
2878
+ });
2879
+ }), ui = j("seedProtocol:PublishManager:index"), $ = Ye(Ze({
2880
+ types: {
2881
+ context: {},
2882
+ input: {},
2883
+ events: {}
2884
+ },
2885
+ actors: { restoreFromDb: li },
2886
+ actions: {
2887
+ assignRestoreFromDb: br,
2888
+ createPublish: Ar,
2889
+ addSubscription: Jr,
2890
+ requestSavePublish: $r,
2891
+ publishDone: ei,
2892
+ removeSubscription: ti,
2893
+ retryAttestations: jr,
2894
+ stopPublish: Wr,
2895
+ stopAll: Kr,
2896
+ query: qr
2897
+ }
2898
+ }).createMachine({
2899
+ id: "publishManager",
2900
+ initial: "restoreFromDb",
2901
+ context: {
2902
+ publishProcesses: /* @__PURE__ */ new Map(),
2903
+ subscriptions: /* @__PURE__ */ new Map()
2904
+ },
2905
+ states: {
2906
+ restoreFromDb: {
2907
+ on: { RESTORE_FROM_DB_DONE: {
2908
+ target: "active",
2909
+ actions: ["assignRestoreFromDb"]
2910
+ } },
2911
+ invoke: {
2912
+ src: "restoreFromDb",
2913
+ input: ({ context: e }) => ({ context: e })
2914
+ }
2915
+ },
2916
+ active: { on: {
2917
+ CREATE_PUBLISH: { actions: ["createPublish"] },
2918
+ ADD_SUBSCRIPTION: { actions: ["addSubscription"] },
2919
+ REQUEST_SAVE_PUBLISH: { actions: ["requestSavePublish"] },
2920
+ SAVE_PUBLISH_DONE: [{
2921
+ guard: ({ event: e }) => e.triggerPublishDone === !0,
2922
+ actions: ["publishDone"]
2923
+ }],
2924
+ PUBLISH_DONE: { actions: ["publishDone"] },
2925
+ REMOVE_SUBSCRIPTION: { actions: ["removeSubscription"] },
2926
+ RETRY_ATTESTATIONS: { actions: ["retryAttestations"] },
2927
+ STOP_PUBLISH: { actions: ["stopPublish"] },
2928
+ QUERY: { actions: ["query"] },
2929
+ STOP_ALL: { actions: ["stopAll"] }
2930
+ } }
2931
+ }
2932
+ }), { input: {
2933
+ publishProcesses: /* @__PURE__ */ new Map(),
2934
+ subscriptions: /* @__PURE__ */ new Map()
2935
+ } });
2936
+ Sr({
2937
+ savePublish: (e, t, n) => {
2938
+ $.send({
2939
+ type: "REQUEST_SAVE_PUBLISH",
2940
+ seedLocalId: e,
2941
+ publishProcess: t,
2942
+ triggerPublishDone: n?.triggerPublishDone
2943
+ });
2944
+ },
2945
+ onPublishDone: (e) => {
2946
+ $.send({
2947
+ type: "PUBLISH_DONE",
2948
+ seedLocalId: e
2949
+ });
2950
+ },
2951
+ removeSubscription: (e) => {
2952
+ $.send({
2953
+ type: "REMOVE_SUBSCRIPTION",
2954
+ seedLocalId: e
2955
+ });
2956
+ }
2957
+ });
2958
+ var di = $.subscribe((e) => {
2959
+ ui("PublishManager snapshot:", e);
2960
+ });
2961
+ typeof document < "u" && ($.start(), window.addEventListener("load", () => {
2962
+ ui("PublishManager started");
2963
+ }), window.addEventListener("beforeunload", () => {
2964
+ di.unsubscribe(), $.stop();
2965
+ }));
2966
+ var fi = {
2967
+ getService: () => $,
2968
+ createPublish: (e, t, n, r) => $.send({
2969
+ type: "CREATE_PUBLISH",
2970
+ item: e,
2971
+ address: t,
2972
+ account: n,
2973
+ options: r
2974
+ }),
2975
+ retryAttestations: (e, t) => $.send({
2976
+ type: "RETRY_ATTESTATIONS",
2977
+ seedLocalId: e,
2978
+ account: t
2979
+ }),
2980
+ stopPublish: (e) => $.send({
2981
+ type: "STOP_PUBLISH",
2982
+ seedLocalId: e
2983
+ }),
2984
+ query: (e) => $.send({
2985
+ type: "QUERY",
2986
+ seedLocalId: e
2987
+ }),
2988
+ stopAll: () => $.send({ type: "STOP_ALL" }),
2989
+ getPublish: (e) => $.getSnapshot().context.publishProcesses.get(e),
2990
+ savePublish: (e, t) => $.send({
2991
+ type: "REQUEST_SAVE_PUBLISH",
2992
+ seedLocalId: e,
2993
+ publishProcess: t
2994
+ }),
2995
+ addSubscription: (e, t) => $.send({
2996
+ type: "ADD_SUBSCRIPTION",
2997
+ seedLocalId: e,
2998
+ newSubscription: t
2999
+ }),
3000
+ removeSubscription: (e) => $.send({
3001
+ type: "REMOVE_SUBSCRIPTION",
3002
+ seedLocalId: e
3003
+ })
3004
+ };
3005
+ //#endregion
3006
+ export { En as a, qt as c, Dn as i, L as l, yr as n, _n as o, Sn as r, Mt as s, fi as t, I as u };
3007
+
3008
+ //# sourceMappingURL=publishManager-BOICv9Yl.js.map