@seedprotocol/sdk 0.7.3-next.613.g79a8dfd → 0.7.3

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 (239) hide show
  1. package/dist/{db-CQt-gcAl.js → BasePathResolver-Cm4apKRb.js} +2041 -127
  2. package/dist/BasePathResolver-Cm4apKRb.js.map +1 -0
  3. package/dist/{ClientManager-DDA9956Y.js → ClientManager-i3nJASkg.js} +664 -277
  4. package/dist/ClientManager-i3nJASkg.js.map +1 -0
  5. package/dist/{Item-D4FigtYS.js → Item-DBFchXpC.js} +495 -219
  6. package/dist/Item-DBFchXpC.js.map +1 -0
  7. package/dist/{ModelProperty-BDt6AU2h.js → ModelProperty-BS49g01Y.js} +167 -47
  8. package/dist/ModelProperty-BS49g01Y.js.map +1 -0
  9. package/dist/{Schema-B8xqLWkL.js → Schema-CpMNEnUO.js} +53 -42
  10. package/dist/Schema-CpMNEnUO.js.map +1 -0
  11. package/dist/{SchemaValidationService-BPxkfDLU.js → SchemaValidationService-DieV4KL-.js} +13 -14
  12. package/dist/{SchemaValidationService-BPxkfDLU.js.map → SchemaValidationService-DieV4KL-.js.map} +1 -1
  13. package/dist/{backfillMetadataPropertyIds-DuTPcv8t.js → backfillMetadataPropertyIds-DSoOoTnX.js} +14 -7
  14. package/dist/{backfillMetadataPropertyIds-DuTPcv8t.js.map → backfillMetadataPropertyIds-DSoOoTnX.js.map} +1 -1
  15. package/dist/{configurePlatform-YcOiDQBZ.js → configurePlatform-D0lQGAMQ.js} +8 -7
  16. package/dist/{configurePlatform-YcOiDQBZ.js.map → configurePlatform-D0lQGAMQ.js.map} +1 -1
  17. package/dist/detachRowsBeforeDelete-S0q-DJPT.js +50 -0
  18. package/dist/detachRowsBeforeDelete-S0q-DJPT.js.map +1 -0
  19. package/dist/{eas-CpOD74Ke.js → eas-6pjU-OuX.js} +9 -8
  20. package/dist/eas-6pjU-OuX.js.map +1 -0
  21. package/dist/{getItem-B_OoFkd7.js → getItem-CxBNZ-WL.js} +13 -11
  22. package/dist/{getItem-B_OoFkd7.js.map → getItem-CxBNZ-WL.js.map} +1 -1
  23. package/dist/{getPublishPayload-Xl3sRkR-.js → getPublishPayload-CTCvRUoU.js} +50 -18
  24. package/dist/getPublishPayload-CTCvRUoU.js.map +1 -0
  25. package/dist/getPublishUploads-SFHCbf_y.js +648 -0
  26. package/dist/getPublishUploads-SFHCbf_y.js.map +1 -0
  27. package/dist/{index-Xl1_4Lmb.js → index-8O3Uow-Y.js} +125 -57
  28. package/dist/index-8O3Uow-Y.js.map +1 -0
  29. package/dist/{index-CSOQFAOn.js → index-AVFTVp1m.js} +2 -2
  30. package/dist/index-AVFTVp1m.js.map +1 -0
  31. package/dist/index-Cvt5UBz4.js +30 -0
  32. package/dist/index-Cvt5UBz4.js.map +1 -0
  33. package/dist/{index.browser-CjTe0vt1.js → index.browser-DBhxRoe8.js} +554 -165
  34. package/dist/index.browser-DBhxRoe8.js.map +1 -0
  35. package/dist/{index.node-Cfa7npS6.js → index.node-CJhlcNHM.js} +25 -13
  36. package/dist/index.node-CJhlcNHM.js.map +1 -0
  37. package/dist/main.js +30 -47
  38. package/dist/main.js.map +1 -1
  39. package/dist/mimeTypes-DHAHC4eZ.js +204 -0
  40. package/dist/mimeTypes-DHAHC4eZ.js.map +1 -0
  41. package/dist/node.js +19 -21
  42. package/dist/node.js.map +1 -1
  43. package/dist/platform.browser.js +13 -11
  44. package/dist/platform.browser.js.map +1 -1
  45. package/dist/platform.node.js +18 -5
  46. package/dist/platform.node.js.map +1 -1
  47. package/dist/{property-BrXkY1Rg.js → property-DwPD283A.js} +14 -12
  48. package/dist/property-DwPD283A.js.map +1 -0
  49. package/dist/{publishDraftGraph-X0Wr9txE.js → publishDraftGraph-BOn3_Occ.js} +6 -9
  50. package/dist/{publishDraftGraph-X0Wr9txE.js.map → publishDraftGraph-BOn3_Occ.js.map} +1 -1
  51. package/dist/{resetAmbiguousLegacyItemData-Ci6PM_vC.js → resetAmbiguousLegacyItemData-BkYmBeJc.js} +14 -3
  52. package/dist/{resetAmbiguousLegacyItemData-Ci6PM_vC.js.map → resetAmbiguousLegacyItemData-BkYmBeJc.js.map} +1 -1
  53. package/dist/{resolveModelForSyncedSeed-DFVdnYq8.js → resolveModelForSyncedSeed-BL24nLa7.js} +2 -2
  54. package/dist/{resolveModelForSyncedSeed-DFVdnYq8.js.map → resolveModelForSyncedSeed-BL24nLa7.js.map} +1 -1
  55. package/dist/src/Item/Item.d.ts +21 -3
  56. package/dist/src/Item/Item.d.ts.map +1 -1
  57. package/dist/src/Item/service/actors/runPublish.d.ts +11 -2
  58. package/dist/src/Item/service/actors/runPublish.d.ts.map +1 -1
  59. package/dist/src/Item/service/itemMachineSingle.d.ts +12 -2
  60. package/dist/src/Item/service/itemMachineSingle.d.ts.map +1 -1
  61. package/dist/src/ItemProperty/ItemProperty.d.ts +5 -3
  62. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  63. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  64. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts.map +1 -1
  65. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  66. package/dist/src/Model/Model.d.ts +10 -4
  67. package/dist/src/Model/Model.d.ts.map +1 -1
  68. package/dist/src/Model/index.d.ts +2 -2
  69. package/dist/src/ModelProperty/ModelProperty.d.ts +10 -2
  70. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  71. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +3 -0
  72. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  73. package/dist/src/Schema/Schema.d.ts +2 -2
  74. package/dist/src/Schema/Schema.d.ts.map +1 -1
  75. package/dist/src/Schema/index.d.ts +0 -1
  76. package/dist/src/Schema/index.d.ts.map +1 -1
  77. package/dist/src/browser/helpers/FileManager.d.ts +4 -1
  78. package/dist/src/browser/helpers/FileManager.d.ts.map +1 -1
  79. package/dist/src/browser/helpers/tolerantWebAccess.d.ts +79 -4
  80. package/dist/src/browser/helpers/tolerantWebAccess.d.ts.map +1 -1
  81. package/dist/src/browser/workers/FileDownloader.d.ts +19 -4
  82. package/dist/src/browser/workers/FileDownloader.d.ts.map +1 -1
  83. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  84. package/dist/src/client/ClientManager.d.ts +30 -11
  85. package/dist/src/client/ClientManager.d.ts.map +1 -1
  86. package/dist/src/client/actors/platformClassesInit.d.ts +6 -0
  87. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  88. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  89. package/dist/src/client/actors/saveConfig.d.ts +13 -6
  90. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  91. package/dist/src/client/clientManagerMachine.d.ts.map +1 -1
  92. package/dist/src/db/migrateLegacyItemStorageRows.d.ts +57 -0
  93. package/dist/src/db/migrateLegacyItemStorageRows.d.ts.map +1 -0
  94. package/dist/src/db/read/getCompositeChildPaths.d.ts +13 -0
  95. package/dist/src/db/read/getCompositeChildPaths.d.ts.map +1 -0
  96. package/dist/src/db/read/getItems.d.ts.map +1 -1
  97. package/dist/src/db/read/getPublishPayload.d.ts +1 -1
  98. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  99. package/dist/src/db/read/getPublishUploads.d.ts +32 -3
  100. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  101. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  102. package/dist/src/db/write/claimUnpublishedDrafts.d.ts +2 -0
  103. package/dist/src/db/write/claimUnpublishedDrafts.d.ts.map +1 -1
  104. package/dist/src/db/write/convertVerbatimItemStorageRow.d.ts +44 -0
  105. package/dist/src/db/write/convertVerbatimItemStorageRow.d.ts.map +1 -0
  106. package/dist/src/db/write/createNewItem.d.ts.map +1 -1
  107. package/dist/src/eventBus.d.ts +5 -0
  108. package/dist/src/eventBus.d.ts.map +1 -1
  109. package/dist/src/events/files/download.d.ts.map +1 -1
  110. package/dist/src/helpers/FileManager/BaseFileManager.d.ts +3 -3
  111. package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  112. package/dist/src/helpers/FileManager/IFileManager.d.ts +25 -1
  113. package/dist/src/helpers/FileManager/IFileManager.d.ts.map +1 -1
  114. package/dist/src/helpers/arweaveContentTags.d.ts +33 -0
  115. package/dist/src/helpers/arweaveContentTags.d.ts.map +1 -0
  116. package/dist/src/helpers/cachedPropertyRefresh.d.ts +12 -0
  117. package/dist/src/helpers/cachedPropertyRefresh.d.ts.map +1 -0
  118. package/dist/src/helpers/compositeUpload.d.ts +28 -0
  119. package/dist/src/helpers/compositeUpload.d.ts.map +1 -0
  120. package/dist/src/helpers/db.d.ts +3 -0
  121. package/dist/src/helpers/db.d.ts.map +1 -1
  122. package/dist/src/helpers/easSdk.d.ts +16 -0
  123. package/dist/src/helpers/easSdk.d.ts.map +1 -0
  124. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts +16 -0
  125. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts.map +1 -0
  126. package/dist/src/helpers/entity/entityDestroy.d.ts +2 -0
  127. package/dist/src/helpers/entity/entityDestroy.d.ts.map +1 -1
  128. package/dist/src/helpers/itemStorageFile.d.ts +57 -0
  129. package/dist/src/helpers/itemStorageFile.d.ts.map +1 -0
  130. package/dist/src/helpers/mapWithConcurrency.d.ts +7 -0
  131. package/dist/src/helpers/mapWithConcurrency.d.ts.map +1 -0
  132. package/dist/src/helpers/mimeTypes.d.ts +43 -0
  133. package/dist/src/helpers/mimeTypes.d.ts.map +1 -0
  134. package/dist/src/helpers/ownership.d.ts +28 -4
  135. package/dist/src/helpers/ownership.d.ts.map +1 -1
  136. package/dist/src/helpers/property/index.d.ts +37 -51
  137. package/dist/src/helpers/property/index.d.ts.map +1 -1
  138. package/dist/src/helpers/publishConfig.d.ts +27 -8
  139. package/dist/src/helpers/publishConfig.d.ts.map +1 -1
  140. package/dist/src/helpers/storageDir.d.ts +16 -0
  141. package/dist/src/helpers/storageDir.d.ts.map +1 -0
  142. package/dist/src/helpers/tabCoordinator.d.ts +5 -1
  143. package/dist/src/helpers/tabCoordinator.d.ts.map +1 -1
  144. package/dist/src/helpers/tabEvents.d.ts +23 -2
  145. package/dist/src/helpers/tabEvents.d.ts.map +1 -1
  146. package/dist/src/helpers/updateSchema.d.ts +5 -0
  147. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  148. package/dist/src/helpers/waitForEntityIdle.d.ts +5 -0
  149. package/dist/src/helpers/waitForEntityIdle.d.ts.map +1 -1
  150. package/dist/src/imports/json.d.ts +9 -0
  151. package/dist/src/imports/json.d.ts.map +1 -1
  152. package/dist/src/index.d.ts +11 -7
  153. package/dist/src/index.d.ts.map +1 -1
  154. package/dist/src/interfaces/IItem.d.ts +7 -1
  155. package/dist/src/interfaces/IItem.d.ts.map +1 -1
  156. package/dist/src/node/db/Db.d.ts.map +1 -1
  157. package/dist/src/node/helpers/PathResolver.d.ts.map +1 -1
  158. package/dist/src/node/index.d.ts +8 -1
  159. package/dist/src/node/index.d.ts.map +1 -1
  160. package/dist/src/platform/index.browser.d.ts +2 -0
  161. package/dist/src/platform/index.browser.d.ts.map +1 -1
  162. package/dist/src/platform/index.node.d.ts +2 -0
  163. package/dist/src/platform/index.node.d.ts.map +1 -1
  164. package/dist/src/types/fileManager.d.ts +3 -14
  165. package/dist/src/types/fileManager.d.ts.map +1 -1
  166. package/dist/src/types/index.d.ts +12 -1
  167. package/dist/src/types/index.d.ts.map +1 -1
  168. package/dist/src/types/machines.d.ts +2 -0
  169. package/dist/src/types/machines.d.ts.map +1 -1
  170. package/dist/src/types/property.d.ts +8 -0
  171. package/dist/src/types/property.d.ts.map +1 -1
  172. package/dist/src/types/publish.d.ts +14 -0
  173. package/dist/src/types/publish.d.ts.map +1 -1
  174. package/dist/{syncDbWithEas-BU-jZ5bJ.js → syncDbWithEas-Bv2Fe38J.js} +17 -17
  175. package/dist/{syncDbWithEas-BU-jZ5bJ.js.map → syncDbWithEas-Bv2Fe38J.js.map} +1 -1
  176. package/dist/tabEvents-9s2WCYw-.js +335 -0
  177. package/dist/tabEvents-9s2WCYw-.js.map +1 -0
  178. package/dist/tolerantWebAccess-iUu80pAP.js +551 -0
  179. package/dist/tolerantWebAccess-iUu80pAP.js.map +1 -0
  180. package/dist/{updateSeedRevokedAt-iLpzae1i.js → updateSeedRevokedAt-zBfi931j.js} +3 -3
  181. package/dist/{updateSeedRevokedAt-iLpzae1i.js.map → updateSeedRevokedAt-zBfi931j.js.map} +1 -1
  182. package/package.json +11 -12
  183. package/src/node/easLodashRegister.js +4 -0
  184. package/dist/BasePathResolver-BdxCSIzn.js +0 -679
  185. package/dist/BasePathResolver-BdxCSIzn.js.map +0 -1
  186. package/dist/ClientManager-DDA9956Y.js.map +0 -1
  187. package/dist/Item-D4FigtYS.js.map +0 -1
  188. package/dist/ModelProperty-BDt6AU2h.js.map +0 -1
  189. package/dist/Schema-B8xqLWkL.js.map +0 -1
  190. package/dist/cjs/ModelProperty-B-cZm1yU.js +0 -1977
  191. package/dist/cjs/ModelProperty-B-cZm1yU.js.map +0 -1
  192. package/dist/cjs/Schema-STP972Xw.js +0 -5256
  193. package/dist/cjs/Schema-STP972Xw.js.map +0 -1
  194. package/dist/cjs/SchemaValidationService-CKNW1bKg.js +0 -778
  195. package/dist/cjs/SchemaValidationService-CKNW1bKg.js.map +0 -1
  196. package/dist/cjs/backfillMetadataPropertyIds-CP3y1skt.js +0 -89
  197. package/dist/cjs/backfillMetadataPropertyIds-CP3y1skt.js.map +0 -1
  198. package/dist/cjs/eas-CAnUC4wd.js +0 -138
  199. package/dist/cjs/eas-CAnUC4wd.js.map +0 -1
  200. package/dist/cjs/getItem-CWgb3e9G.js +0 -58
  201. package/dist/cjs/getItem-CWgb3e9G.js.map +0 -1
  202. package/dist/cjs/getPublishPayload-BsZWiJ03.js +0 -1603
  203. package/dist/cjs/getPublishPayload-BsZWiJ03.js.map +0 -1
  204. package/dist/cjs/getPublishUploads-BQr8aMVP.js +0 -495
  205. package/dist/cjs/getPublishUploads-BQr8aMVP.js.map +0 -1
  206. package/dist/cjs/index-nA5PxBSs.js +0 -70
  207. package/dist/cjs/index-nA5PxBSs.js.map +0 -1
  208. package/dist/cjs/index-usKaANAq.js +0 -22171
  209. package/dist/cjs/index-usKaANAq.js.map +0 -1
  210. package/dist/cjs/index.browser-BSf8HpnU.js +0 -22
  211. package/dist/cjs/index.browser-BSf8HpnU.js.map +0 -1
  212. package/dist/cjs/property-xMwPhQ5N.js +0 -327
  213. package/dist/cjs/property-xMwPhQ5N.js.map +0 -1
  214. package/dist/cjs/publishDraftGraph-BRWlR1KO.js +0 -403
  215. package/dist/cjs/publishDraftGraph-BRWlR1KO.js.map +0 -1
  216. package/dist/cjs/resetAmbiguousLegacyItemData-8nfkj9rz.js +0 -116
  217. package/dist/cjs/resetAmbiguousLegacyItemData-8nfkj9rz.js.map +0 -1
  218. package/dist/cjs/resolveModelForSyncedSeed-kYRuDWYw.js +0 -49
  219. package/dist/cjs/resolveModelForSyncedSeed-kYRuDWYw.js.map +0 -1
  220. package/dist/cjs/syncDbWithEas-DqRhV8o2.js +0 -886
  221. package/dist/cjs/syncDbWithEas-DqRhV8o2.js.map +0 -1
  222. package/dist/db-CQt-gcAl.js.map +0 -1
  223. package/dist/eas-CpOD74Ke.js.map +0 -1
  224. package/dist/getPublishPayload-Xl3sRkR-.js.map +0 -1
  225. package/dist/getPublishUploads-DHP01KgU.js +0 -484
  226. package/dist/getPublishUploads-DHP01KgU.js.map +0 -1
  227. package/dist/index-BGt4_oPO.js +0 -31
  228. package/dist/index-BGt4_oPO.js.map +0 -1
  229. package/dist/index-CSOQFAOn.js.map +0 -1
  230. package/dist/index-Xl1_4Lmb.js.map +0 -1
  231. package/dist/index.browser-CjTe0vt1.js.map +0 -1
  232. package/dist/index.node-Cfa7npS6.js.map +0 -1
  233. package/dist/main.cjs +0 -84
  234. package/dist/main.cjs.map +0 -1
  235. package/dist/property-BrXkY1Rg.js.map +0 -1
  236. package/dist/tabEvents-BZJMY5uK.js +0 -1344
  237. package/dist/tabEvents-BZJMY5uK.js.map +0 -1
  238. package/dist/tolerantWebAccess-BZ2RA_mb.js +0 -160
  239. package/dist/tolerantWebAccess-BZ2RA_mb.js.map +0 -1
@@ -1,1603 +0,0 @@
1
- 'use strict';
2
-
3
- var main_cjs = require('./index-usKaANAq.js');
4
- var easSdk = require('@ethereum-attestation-service/eas-sdk');
5
- var casing = require('drizzle-orm/casing');
6
- var eas = require('@seedprotocol/eas');
7
- var publishDraftGraph = require('./publishDraftGraph-BRWlR1KO.js');
8
- var property = require('./property-xMwPhQ5N.js');
9
- var lodashEs = require('lodash-es');
10
- var drizzleOrm = require('drizzle-orm');
11
- var debug = require('debug');
12
- require('@noble/hashes/sha3');
13
- require('@noble/hashes/utils');
14
- require('reflect-metadata');
15
- require('immer');
16
- require('xstate');
17
- require('drizzle-orm/sqlite-core');
18
- require('@seedprotocol/arweave');
19
- require('pluralize');
20
- require('@sinclair/typebox');
21
- require('nanoid');
22
- require('nanoid-dictionary');
23
- require('@seedprotocol/query');
24
- require('rxjs');
25
- require('fs/promises');
26
- require('fs');
27
- require('path');
28
- require('url');
29
- require('node:url');
30
- require('@libsql/client');
31
- require('drizzle-orm/libsql');
32
- require('drizzle-orm/libsql/migrator');
33
- require('js-yaml');
34
- require('child_process');
35
- require('@seedprotocol/arweave/node');
36
- require('@seedprotocol/eas/node');
37
-
38
- /** UTF-8 string to 0x-prefixed bytes32 hex (right-padded with zeros). */
39
- function encodeBytes32String(value) {
40
- const bytes = new TextEncoder().encode(value);
41
- if (bytes.length > 32) {
42
- throw new Error(`encodeBytes32String: value exceeds 32 bytes (${bytes.length})`);
43
- }
44
- const hex = Array.from(bytes)
45
- .map((b) => b.toString(16).padStart(2, '0'))
46
- .join('');
47
- return `0x${hex.padEnd(64, '0')}`;
48
- }
49
-
50
- /** Error thrown when publish validation fails. Includes all validation errors for user to fix. */
51
- class PublishValidationFailedError extends Error {
52
- constructor(message, validationErrors) {
53
- super(message);
54
- this.validationErrors = validationErrors;
55
- this.name = 'PublishValidationFailedError';
56
- }
57
- }
58
- /** Validation error code for a relation, list member or image/file ref to an unpublished seed. */
59
- const RELATED_ITEM_UNPUBLISHED_CODE = 'related_item_unpublished';
60
- const describeUnpublishedRelatedItem = (r) => `${r.propertyName} -> ${r.modelName} ${r.seedLocalId} (seed ${r.seedUid})`;
61
- /**
62
- * Thrown before anything is uploaded or attested when the item references items whose seed was
63
- * unpublished: the parent would attest a revoked seed uid. Republish those items (which gives
64
- * them a new seed uid) or remove the references, then publish again.
65
- * See docs/ATTESTATION_REVOCATION.md ("Republishing").
66
- *
67
- * A PublishValidationFailedError, so validateItemForPublish and the publish package's checking
68
- * step report it as validation errors (code `related_item_unpublished`, one per reference).
69
- */
70
- class RelatedItemUnpublishedError extends PublishValidationFailedError {
71
- constructor(unpublishedRelatedItems, otherValidationErrors = []) {
72
- const lines = unpublishedRelatedItems.map(describeUnpublishedRelatedItem);
73
- const message = `Cannot publish: it references ${lines.length} unpublished item${lines.length === 1 ? '' : 's'} ` +
74
- `(their seed attestations were revoked). Republish them or remove the references, then publish again:\n` +
75
- lines.join('\n');
76
- super(message, [
77
- ...unpublishedRelatedItems.map((r) => ({
78
- field: r.propertyName,
79
- message: `${r.propertyName} references unpublished ${r.modelName} ${r.seedLocalId} (seed ${r.seedUid}). ` +
80
- `Republish it or remove the reference.`,
81
- code: RELATED_ITEM_UNPUBLISHED_CODE,
82
- })),
83
- ...otherValidationErrors,
84
- ]);
85
- this.name = 'RelatedItemUnpublishedError';
86
- this.unpublishedRelatedItems = unpublishedRelatedItems;
87
- }
88
- }
89
-
90
- debug('seedSdk:db:getPublishPayload');
91
- /** Case-insensitive dataType match (schema JSON may use "text" vs "Text"). */
92
- const matchesDataType = (actual, expected) => main_cjs.normalizeDataType(actual) === expected;
93
- /** True (and the property is deferred) when `targetSeedLocalId` is an item still in progress. */
94
- function deferIfBackEdge(ctx, property, targetSeedLocalIds) {
95
- if (!targetSeedLocalIds.some((id) => !!id && ctx.newSeedsInProgress?.has(id)))
96
- return false;
97
- ctx.deferredProperties ?? (ctx.deferredProperties = new Set());
98
- ctx.deferredProperties.add(property);
99
- return true;
100
- }
101
- /**
102
- * Checks the seed a relation/list/image ref points at. A revoked (unpublished) seed is recorded in
103
- * `ctx.unpublishedRelatedItems`; a live published one maps the ref to its current uid. Returns
104
- * true when the caller must not walk into the related item (it is published, live or revoked).
105
- */
106
- function noteRelatedSeed(ctx, ref, row, propertyName, modelName) {
107
- if (publishDraftGraph.isUnpublishedSeed(row)) {
108
- ctx.unpublishedRelatedItems ?? (ctx.unpublishedRelatedItems = []);
109
- if (!ctx.unpublishedRelatedItems.some((r) => r.propertyName === propertyName && r.seedLocalId === row.seedLocalId)) {
110
- ctx.unpublishedRelatedItems.push({
111
- propertyName,
112
- modelName: modelName ?? row.type ?? 'unknown',
113
- seedLocalId: row.seedLocalId,
114
- seedUid: row.seedUid,
115
- });
116
- }
117
- return true;
118
- }
119
- if (publishDraftGraph.isLivePublishedSeed(row)) {
120
- if (ref !== row.seedUid) {
121
- ctx.relatedRefUids ?? (ctx.relatedRefUids = new Map());
122
- ctx.relatedRefUids.set(ref, row.seedUid);
123
- }
124
- return true;
125
- }
126
- return false;
127
- }
128
- /** Current uid for a ref noted by noteRelatedSeed, else the ref itself. */
129
- function currentRelatedRef(ctx, ref) {
130
- return ctx.relatedRefUids?.get(ref.trim()) ?? ref;
131
- }
132
- /**
133
- * An EAS uid (0x + 64 hex), as opposed to a local id. A "0x" prefix alone doesn't tell them apart:
134
- * local ids are random alphanumerics, and about 1 in 3,844 starts with "0x".
135
- */
136
- function isUidRef(ref) {
137
- return ref.length === 66 && ref.startsWith('0x');
138
- }
139
- function addValidationError(ctx, message, field, code = 'publish_validation') {
140
- // A property can be validated on more than one path (List of Relation: list + basic); report once.
141
- if (ctx.errors.some((e) => e.message === message && e.field === (field ?? '')))
142
- return;
143
- ctx.errors.push({ field: field ?? '', message, code });
144
- }
145
- /** File/Image/Html value is raw content instead of a storage seed id, so it was never saved/uploaded. */
146
- function addStorageValueNotSavedError(ctx, propertyName, dataType, value) {
147
- addValidationError(ctx, `Invalid value for property: ${propertyName}. Expected a storage seed id ` +
148
- `(${main_cjs.normalizeDataType(dataType)} content must be saved through the property before publishing), ` +
149
- `got ${value.length > 40 ? `${value.slice(0, 40)}…` : value}.`, propertyName, 'publish_storage_value_not_saved');
150
- }
151
- function isStorageTransactionPropertyName(name) {
152
- return name === 'storageTransactionId' || name === 'storage_transaction_id';
153
- }
154
- /**
155
- * Segmentation or naming variants can leave two rows for the same logical field; keep one
156
- * resolved slot so processBasicProperties emits a single storage tx attestation.
157
- */
158
- function replaceStorageTransactionInBasicProperties(itemBasicProperties, resolved) {
159
- const filtered = itemBasicProperties.filter((p) => !isStorageTransactionPropertyName(p.propertyName));
160
- itemBasicProperties.length = 0;
161
- itemBasicProperties.push(...filtered, resolved);
162
- }
163
- /** If multiple storageTransactionId ItemProperty rows slipped in, keep one (last wins). */
164
- function dedupeOneStorageTransactionPropertyInList(itemBasicProperties) {
165
- const nonStorage = [];
166
- const storage = [];
167
- for (const p of itemBasicProperties) {
168
- if (isStorageTransactionPropertyName(p.propertyName)) {
169
- storage.push(p);
170
- }
171
- else {
172
- nonStorage.push(p);
173
- }
174
- }
175
- if (storage.length <= 1)
176
- return;
177
- itemBasicProperties.length = 0;
178
- itemBasicProperties.push(...nonStorage, storage[storage.length - 1]);
179
- }
180
- /**
181
- * Two relation/image props (e.g. content + featureImage) can reference the same File/Image seed.
182
- * Only one child PublishPayload should exist per related seedLocalId; merge propertiesToUpdate instead.
183
- */
184
- function mergeChildPublishPayloadIfDuplicateInBatch(multiPublishPayload, relatedSeedLocalId, publishLocalId, propertySchemaUid) {
185
- const existing = multiPublishPayload.find((p) => p.localId === relatedSeedLocalId);
186
- if (!existing)
187
- return false;
188
- const pts = existing.propertiesToUpdate ?? [];
189
- const already = pts.some((e) => e.publishLocalId === publishLocalId &&
190
- String(e.propertySchemaUid ?? '').toLowerCase() ===
191
- String(propertySchemaUid ?? '').toLowerCase());
192
- if (!already) {
193
- pts.push({ publishLocalId, propertySchemaUid });
194
- }
195
- return true;
196
- }
197
- const getVersionUid = (item) => {
198
- const latestVersion = item.latestVersionUid;
199
- if (latestVersion && typeof latestVersion === 'object' && latestVersion.uid) {
200
- const u = latestVersion.uid;
201
- return eas.isValidEasAttestationUid(u) ? u : main_cjs.ZERO_BYTES32;
202
- }
203
- if (latestVersion && typeof latestVersion === 'string') {
204
- return eas.isValidEasAttestationUid(latestVersion) ? latestVersion : main_cjs.ZERO_BYTES32;
205
- }
206
- return main_cjs.ZERO_BYTES32;
207
- };
208
- /**
209
- * Resolve versionUid when item.latestVersionUid is empty but item has been published (has seedUid).
210
- * Tries DB first, then EAS. If the local versions row still has a placeholder uid after publish,
211
- * EAS fallback queries attestations where refUID=seedUid (Version attestations).
212
- */
213
- async function resolveVersionUid(seedLocalId, seedUid) {
214
- if (!seedLocalId || !seedUid || seedUid === main_cjs.ZERO_BYTES32)
215
- return main_cjs.ZERO_BYTES32;
216
- const published = await main_cjs.getLatestPublishedVersionRow(seedLocalId);
217
- if (published?.uid)
218
- return published.uid;
219
- try {
220
- const { getItemVersionsFromEas } = await Promise.resolve().then(function () { return require('./eas-CAnUC4wd.js'); });
221
- const attestations = await getItemVersionsFromEas({ seedUids: [seedUid] });
222
- const latest = attestations?.[0];
223
- if (latest?.id)
224
- return latest.id;
225
- }
226
- catch {
227
- // EAS client may not be initialized or network error
228
- }
229
- return main_cjs.ZERO_BYTES32;
230
- }
231
- const getPropertyData = async (itemProperty, ctx) => {
232
- const rawDataType = itemProperty.propertyDef?.dataType;
233
- const dataType = rawDataType ? main_cjs.normalizeDataType(String(rawDataType)) : undefined;
234
- const entry = dataType
235
- ? main_cjs.INTERNAL_DATA_TYPES[dataType]
236
- : undefined;
237
- const easDataType = entry?.eas;
238
- if (!easDataType) {
239
- if (ctx) {
240
- addValidationError(ctx, `Unknown or unsupported property data type "${rawDataType ?? 'undefined'}" for property: ${itemProperty.propertyName}. Supported types: ${Object.keys(main_cjs.INTERNAL_DATA_TYPES).join(', ')}.`, itemProperty.propertyName);
241
- }
242
- return null;
243
- }
244
- const ip = itemProperty;
245
- // List of Relation: the EAS name always comes from the property definition (authors → authorIdentityIds),
246
- // never from whatever name the ItemProperty was constructed with or a cached schemaUid.
247
- const listRelationName = main_cjs.listRelationEasPropertyName(itemProperty.propertyName, itemProperty.propertyDef);
248
- const nameForEas = listRelationName ??
249
- (ip.storagePropertyName && ip.storagePropertyName.length > 0
250
- ? ip.storagePropertyName
251
- : itemProperty.propertyName);
252
- const propertyNameForSchema = main_cjs.toSnakeCase(nameForEas);
253
- const schemaDef = `${easDataType} ${propertyNameForSchema}`;
254
- let schemaUid = listRelationName ? undefined : itemProperty.schemaUid;
255
- if (!schemaUid) {
256
- schemaUid = await eas.getEasSchemaUidForSchemaDefinition({ schemaText: schemaDef });
257
- }
258
- if (!schemaUid) {
259
- if (ctx) {
260
- addValidationError(ctx, `EAS schema not found for "${schemaDef}" (property: ${itemProperty.propertyName}). Register it before publishing (ensureEasSchemasForItem).`, itemProperty.propertyName, 'publish_schema_not_found');
261
- }
262
- return null;
263
- }
264
- return {
265
- schemaUid,
266
- easDataType,
267
- schemaDef,
268
- propertyNameForSchema,
269
- };
270
- };
271
- /** Resolve propertyDef from Model for properties that lack it (e.g. cached instances
272
- * created before loadOrCreateProperty was fixed). Ensures both new and existing items get property attestations.
273
- * Also ensures Relation/Image properties have required from schema when missing (for publish validation). */
274
- const ensurePropertyDefs = async (targetItem) => {
275
- targetItem.properties.filter((p) => targetItem.modelName &&
276
- (!p.propertyDef ||
277
- (matchesDataType(p.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Relation) &&
278
- p.propertyDef?.required === undefined)));
279
- let schema;
280
- // Model names are only unique per schema: resolve definitions from this item's own model.
281
- const targetScope = await main_cjs.getItemModelScope(targetItem);
282
- for (const itemProperty of targetItem.properties) {
283
- if (!itemProperty.propertyDef && targetItem.modelName) {
284
- schema = await property.getPropertySchema(targetItem.modelName, itemProperty.propertyName, targetScope);
285
- if (!schema) {
286
- try {
287
- const { Model } = await Promise.resolve().then(function () { return require('./index-usKaANAq.js'); }).then(function (n) { return n.Model$1; });
288
- const normalizedModelName = lodashEs.upperFirst(lodashEs.camelCase(targetItem.modelName));
289
- let model = Model.resolve(normalizedModelName, targetScope);
290
- if (!model?.properties?.length && !targetScope.modelFileId) {
291
- model = Model.findByModelType(casing.toSnakeCase(targetItem.modelName));
292
- }
293
- const modelFound = !!model;
294
- const propsCount = model?.properties?.length ?? 0;
295
- const schemaKeys = [];
296
- if (model?.properties?.length) {
297
- const schemas = main_cjs.modelPropertiesToObject(model.properties);
298
- schemaKeys.push(...Object.keys(schemas));
299
- schema = schemas[itemProperty.propertyName];
300
- }
301
- }
302
- catch (err) {
303
- schema = undefined;
304
- }
305
- }
306
- if (!schema) {
307
- const db = main_cjs.BaseDb.getAppDb();
308
- if (db) {
309
- try {
310
- const normalizedModelName = lodashEs.upperFirst(lodashEs.camelCase(targetItem.modelName));
311
- const modelRecord = await main_cjs.resolveModelRecord(normalizedModelName, targetScope, db);
312
- const modelRecords = modelRecord ? [modelRecord] : [];
313
- if (modelRecords.length > 0 && modelRecords[0].id) {
314
- const propertyRecords = await db
315
- .select()
316
- .from(main_cjs.properties)
317
- .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.properties.modelId, modelRecords[0].id), drizzleOrm.eq(main_cjs.properties.name, itemProperty.propertyName)))
318
- .limit(1);
319
- if (propertyRecords.length > 0) {
320
- const propRecord = propertyRecords[0];
321
- let refModelName;
322
- if (propRecord.refModelId != null) {
323
- const refModelRows = await db
324
- .select({ name: main_cjs.models.name })
325
- .from(main_cjs.models)
326
- .where(drizzleOrm.eq(main_cjs.models.id, propRecord.refModelId))
327
- .limit(1);
328
- refModelName = refModelRows[0]?.name ?? undefined;
329
- }
330
- schema = {
331
- dataType: propRecord.dataType,
332
- ref: refModelName ?? undefined,
333
- refValueType: propRecord.refValueType || undefined,
334
- storageType: propRecord.storageType || undefined,
335
- localStorageDir: propRecord.localStorageDir || undefined,
336
- filenameSuffix: propRecord.filenameSuffix || undefined,
337
- required: propRecord.required ?? undefined,
338
- };
339
- }
340
- }
341
- }
342
- catch {
343
- schema = undefined;
344
- }
345
- }
346
- }
347
- if (schema) {
348
- itemProperty.getService().send({
349
- type: 'updateContext',
350
- propertyRecordSchema: schema,
351
- });
352
- }
353
- }
354
- }
355
- };
356
- const processBasicProperties = async (itemBasicProperties, itemPublishData, ctx, buildOpts) => {
357
- const forceFullSnapshot = buildOpts?.forceFullSnapshot === true;
358
- for (const basicProperty of itemBasicProperties) {
359
- // Skip SDK-internal properties (e.g. publisher) - never attest to EAS
360
- if (main_cjs.INTERNAL_PROPERTY_NAMES.includes(basicProperty.propertyName)) {
361
- continue;
362
- }
363
- if (ctx.deferredProperties?.has(basicProperty)) {
364
- continue;
365
- }
366
- const snapshot = basicProperty.getService().getSnapshot();
367
- const context = 'context' in snapshot ? snapshot.context : null;
368
- const propertyDef = basicProperty.propertyDef ?? (context ? context.propertyRecordSchema : undefined);
369
- const isFileImageHtml = matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.File) ||
370
- matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Image) ||
371
- matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Html);
372
- const isJsonStorage = matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Json) ||
373
- matchesDataType(propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Json);
374
- const isRelation = matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Relation);
375
- // storageTransactionId is usually Text in the schema; .value still prefers renderValue (URL, label).
376
- const isStorageTransactionIdProp = isStorageTransactionPropertyName(basicProperty.propertyName);
377
- // File/Image/Html + Relation + Json storage + storage tx id: use propertyValue (canonical).
378
- // basicProperty.value prefers renderValue (filename, blob URL, display text)—never use that for publish.
379
- const preferPropertyValueForPublish = isFileImageHtml || isRelation || isJsonStorage || isStorageTransactionIdProp;
380
- let value = preferPropertyValueForPublish && context
381
- ? context.propertyValue
382
- : (basicProperty.value ??
383
- (context ? context.propertyValue : undefined));
384
- !!basicProperty.uid;
385
- if (!context) {
386
- continue;
387
- }
388
- // Relation + Image/File/Html/Json refs often expose seedLocalId on context.propertyValue while .value is an object — align for encode + resolve hints
389
- if (matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Relation) ||
390
- isFileImageHtml ||
391
- isJsonStorage) {
392
- const pv = context.propertyValue;
393
- if (typeof value === 'object' || value == null) {
394
- if (typeof pv === 'string' && pv.trim())
395
- value = pv.trim();
396
- else if (pv && typeof pv === 'object' && typeof pv.seedLocalId === 'string')
397
- value = pv.seedLocalId;
398
- }
399
- }
400
- if (!value) {
401
- continue;
402
- }
403
- // Patch mode skips properties that already have an EAS uid. storageTransactionId must still
404
- // attest after Arweave upload when we have a tx id; metadata uid can be stale or set without a chain attestation.
405
- if (basicProperty.uid && !forceFullSnapshot) {
406
- const allowStorageTxAttestation = isStorageTransactionIdProp &&
407
- typeof value === 'string' &&
408
- value.trim() !== '';
409
- if (!allowStorageTxAttestation) {
410
- continue;
411
- }
412
- }
413
- // File/Image/Html values must be a storage seed id by now. Raw content means the property's
414
- // save pipeline never ran or failed (e.g. createNewItem with raw html), so it was never uploaded.
415
- // Relation/image properties are appended to the basic list after processRelationOrImageProperty,
416
- // so this one check covers both paths.
417
- if (isFileImageHtml && typeof value === 'string' && !main_cjs.isStorageSeedRef(value)) {
418
- addStorageValueNotSavedError(ctx, basicProperty.propertyName, propertyDef?.dataType, value);
419
- continue;
420
- }
421
- const propertyData = await getPropertyData(basicProperty, ctx);
422
- if (!propertyData)
423
- continue;
424
- const { schemaUid, easDataType, schemaDef, propertyNameForSchema } = propertyData;
425
- if (!schemaDef)
426
- continue;
427
- // Normalize value: string that parses to array (e.g. from browser storage) -> array
428
- if (schemaDef.startsWith('bytes32[]') && typeof value === 'string' && value.trim().startsWith('[')) {
429
- try {
430
- value = JSON.parse(value);
431
- }
432
- catch {
433
- // fall through to array check
434
- }
435
- }
436
- // Legacy comma-separated ids (pre-JSON List storage)
437
- if (schemaDef.startsWith('bytes32[]') &&
438
- typeof value === 'string' &&
439
- !value.trim().startsWith('[') &&
440
- value.includes(',')) {
441
- value = value
442
- .split(',')
443
- .map((s) => s.trim())
444
- .filter(Boolean);
445
- }
446
- // A ref to a published related item attests that item's current uid.
447
- if (typeof value === 'string' && (isRelation || isFileImageHtml || isJsonStorage)) {
448
- value = currentRelatedRef(ctx, value);
449
- }
450
- if (schemaDef.startsWith('bytes32[]') && !Array.isArray(value)) {
451
- addValidationError(ctx, `Invalid value for property: ${basicProperty.propertyName}. Expected an array of bytes32, got ${value}.`, basicProperty.propertyName);
452
- continue;
453
- }
454
- // Validate against property validation rules (enum, pattern, minLength, maxLength) before encoding
455
- if (propertyDef?.validation) {
456
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CKNW1bKg.js'); });
457
- const validationService = new SchemaValidationService();
458
- const validationResult = validationService.validatePropertyValue(value, main_cjs.normalizeDataType(propertyDef.dataType), propertyDef.validation, propertyDef.refValueType
459
- ? main_cjs.normalizeDataType(propertyDef.refValueType)
460
- : undefined);
461
- if (!validationResult.isValid && validationResult.errors.length > 0) {
462
- const firstError = validationResult.errors[0];
463
- addValidationError(ctx, firstError.message, basicProperty.propertyName, firstError.code ?? 'publish_validation');
464
- continue;
465
- }
466
- }
467
- /** Raw id per list slot (nanoid local id or 0x… uid) for resolvePublishPayloadValues after sequential publish */
468
- let rawListIdsForResolve;
469
- if (schemaDef.startsWith('bytes32[]')) {
470
- const newValues = [];
471
- const rawIds = [];
472
- const iterableValue = Array.isArray(value) ? value
473
- : value != null && typeof value[Symbol.iterator] === 'function' ? value
474
- : [];
475
- for (const seedId of iterableValue) {
476
- const idStr = typeof seedId === 'string'
477
- ? seedId
478
- : seedId &&
479
- typeof seedId === 'object' &&
480
- (seedId.seedLocalId ?? seedId.seedUid ?? seedId.localId ?? seedId.uid)
481
- ? String(seedId.seedLocalId ??
482
- seedId.seedUid ??
483
- '')
484
- : '';
485
- if (!idStr)
486
- continue;
487
- const trimmed = currentRelatedRef(ctx, idStr.trim());
488
- if (!trimmed)
489
- continue;
490
- rawIds.push(trimmed);
491
- if (!isUidRef(trimmed)) {
492
- newValues.push(encodeBytes32String(trimmed));
493
- }
494
- else {
495
- newValues.push(trimmed);
496
- }
497
- }
498
- value = newValues;
499
- const needsUidResolve = rawIds.some((id) => !isUidRef(id));
500
- if (needsUidResolve && rawIds.length > 0) {
501
- rawListIdsForResolve = rawIds;
502
- }
503
- }
504
- // uint256 (Date) must be numeric/BigInt; normalize ISO strings to Unix seconds
505
- if (easDataType === 'uint256' && (typeof value === 'string' || value instanceof Date)) {
506
- const ms = value instanceof Date ? value.getTime() : new Date(value).getTime();
507
- value = BigInt(Math.floor(ms / 1000));
508
- }
509
- let data = [
510
- {
511
- name: propertyNameForSchema,
512
- type: easDataType,
513
- value,
514
- },
515
- ];
516
- let encodedData;
517
- try {
518
- const dataEncoder = new easSdk.SchemaEncoder(schemaDef);
519
- encodedData = dataEncoder.encodeData(data);
520
- }
521
- catch (encodeErr) {
522
- addValidationError(ctx, `Failed to encode property ${basicProperty.propertyName}: ${encodeErr instanceof Error ? encodeErr.message : String(encodeErr)}`, basicProperty.propertyName);
523
- continue;
524
- }
525
- // For storageTransactionId, set refUID to versionUid so it references the Version attestation (contract may use when supported)
526
- const refUid = isStorageTransactionIdProp
527
- ? itemPublishData.versionUid
528
- : main_cjs.defaultAttestationData.refUID;
529
- const attestationEntry = {
530
- schema: schemaUid,
531
- data: [
532
- {
533
- ...main_cjs.defaultAttestationData,
534
- refUID: refUid,
535
- data: encodedData,
536
- },
537
- ],
538
- // Always set so persist can match metadata rows that lack schemaUid
539
- _propertyName: basicProperty.propertyName,
540
- };
541
- // For relation/image properties with seedLocalId, store resolution hints for resolvePublishPayloadValues
542
- const looksLikeLocalSeedRef = typeof value === 'string' &&
543
- !isUidRef(value) &&
544
- /^[a-zA-Z0-9_-]{10,21}$/.test(value.trim());
545
- if (looksLikeLocalSeedRef &&
546
- (easDataType === 'bytes32' || easDataType === 'string')) {
547
- attestationEntry._propertyName = basicProperty.propertyName;
548
- attestationEntry._propertyNameForSchema = propertyNameForSchema;
549
- attestationEntry._schemaDef = schemaDef;
550
- attestationEntry._unresolvedValue = value.trim();
551
- attestationEntry._easDataType = easDataType;
552
- }
553
- if (rawListIdsForResolve && rawListIdsForResolve.length > 0) {
554
- attestationEntry._propertyName = basicProperty.propertyName;
555
- attestationEntry._propertyNameForSchema = propertyNameForSchema;
556
- attestationEntry._schemaDef = schemaDef;
557
- attestationEntry._easDataType = 'bytes32[]';
558
- attestationEntry._rawListIdsForResolve = rawListIdsForResolve;
559
- }
560
- itemPublishData.listOfAttestations.push(attestationEntry);
561
- }
562
- return itemPublishData;
563
- };
564
- const processRelationOrImageProperty = async (relationOrImageProperty, multiPublishPayload, uploadedTransactions, originalSeedLocalId, ctx, buildOpts) => {
565
- const forceFullSnapshot = buildOpts?.forceFullSnapshot === true;
566
- let relationOrImageSchemaUid = relationOrImageProperty.schemaUid;
567
- if (!relationOrImageSchemaUid && relationOrImageProperty.propertyDef) {
568
- const propertyData = await getPropertyData(relationOrImageProperty, ctx);
569
- if (!propertyData)
570
- return multiPublishPayload;
571
- relationOrImageSchemaUid = propertyData.schemaUid;
572
- }
573
- if (!relationOrImageSchemaUid) {
574
- addValidationError(ctx, `Schema uid not found for relation or image property: ${relationOrImageProperty.propertyName}`, relationOrImageProperty.propertyName);
575
- return multiPublishPayload;
576
- }
577
- const snapshot = relationOrImageProperty.getService().getSnapshot();
578
- const context = 'context' in snapshot ? snapshot.context : null;
579
- if (!context) {
580
- return multiPublishPayload;
581
- }
582
- let value = context.propertyValue;
583
- // File/Image/Html/Json metadata is stored with Id suffix (e.g. "textId"); context may not have propertyValue
584
- // if the property was created from schema before metadata loaded. Fallback to metadata lookup.
585
- const isStorageSeed = matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.File) ||
586
- matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Image) ||
587
- matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Html) ||
588
- matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Json) ||
589
- (matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Relation) &&
590
- (matchesDataType(relationOrImageProperty.propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.File) ||
591
- matchesDataType(relationOrImageProperty.propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Image) ||
592
- matchesDataType(relationOrImageProperty.propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Html) ||
593
- matchesDataType(relationOrImageProperty.propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Json)));
594
- if (isStorageSeed && (context.seedLocalId || context.seedUid)) {
595
- const { getPropertyData: getPropertyDataFromDb } = await Promise.resolve().then(function () { return require('./index-usKaANAq.js'); }).then(function (n) { return n.getPropertyData; });
596
- const metaRow = await getPropertyDataFromDb({
597
- propertyName: relationOrImageProperty.propertyName,
598
- seedLocalId: context.seedLocalId,
599
- seedUid: context.seedUid,
600
- });
601
- const fromMeta = metaRow?.propertyValue;
602
- if (typeof fromMeta === 'string' && fromMeta.trim() !== '') {
603
- const idsCtx = main_cjs.resolveSeedIdsFromRefString(main_cjs.normalizeRelationPropertyValue(value) ?? '');
604
- const idsDb = main_cjs.resolveSeedIdsFromRefString(main_cjs.normalizeRelationPropertyValue(fromMeta) ?? '');
605
- if (!value) {
606
- value = fromMeta;
607
- }
608
- else if (!idsCtx.seedLocalId && !idsCtx.seedUid && (idsDb.seedLocalId || idsDb.seedUid)) {
609
- value = fromMeta;
610
- }
611
- }
612
- }
613
- const propertyDef = relationOrImageProperty.propertyDef;
614
- let isRequired = propertyDef?.required === true;
615
- // Resolve required from schema/DB when propertyDef lacks it
616
- if (!isRequired && relationOrImageProperty.modelName) {
617
- const propertyScope = await main_cjs.getItemModelScope(relationOrImageProperty);
618
- let schema = await property.getPropertySchema(relationOrImageProperty.modelName, relationOrImageProperty.propertyName, propertyScope);
619
- if (!schema && main_cjs.BaseDb.getAppDb()) {
620
- const normalizedModelName = lodashEs.upperFirst(lodashEs.camelCase(relationOrImageProperty.modelName));
621
- const modelRecord = await main_cjs.resolveModelRecord(normalizedModelName, propertyScope);
622
- const modelRecords = modelRecord ? [modelRecord] : [];
623
- if (modelRecords.length > 0 && modelRecords[0].id) {
624
- const propertyRecords = await main_cjs.BaseDb.getAppDb()
625
- .select()
626
- .from(main_cjs.properties)
627
- .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.properties.modelId, modelRecords[0].id), drizzleOrm.eq(main_cjs.properties.name, relationOrImageProperty.propertyName)))
628
- .limit(1);
629
- if (propertyRecords.length > 0) {
630
- schema = {
631
- dataType: propertyRecords[0].dataType,
632
- ref: undefined,
633
- required: propertyRecords[0].required ?? undefined,
634
- };
635
- }
636
- }
637
- }
638
- if (schema?.required === true || schema?.required === 1) {
639
- isRequired = true;
640
- }
641
- }
642
- // Required relation/image/file/html/json with no value: cannot publish
643
- if (isRequired && !value) {
644
- const typeLabel = matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.File) ||
645
- matchesDataType(propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.File)
646
- ? 'file'
647
- : matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Image) ||
648
- matchesDataType(propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Image)
649
- ? 'image'
650
- : matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Html) ||
651
- matchesDataType(propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Html)
652
- ? 'html'
653
- : matchesDataType(propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Json) ||
654
- matchesDataType(propertyDef?.refValueType, main_cjs.ModelPropertyDataTypes.Json)
655
- ? 'json'
656
- : 'relation';
657
- const refLabel = propertyDef?.ref ?? propertyDef?.refModelName ?? 'related';
658
- addValidationError(ctx, `Required ${typeLabel} ${relationOrImageProperty.propertyName} has no value. ` +
659
- `A value pointing to a valid ${refLabel} item is required to publish.`, relationOrImageProperty.propertyName);
660
- return multiPublishPayload;
661
- }
662
- if (!value) {
663
- return multiPublishPayload;
664
- }
665
- if (relationOrImageProperty.uid && !forceFullSnapshot) {
666
- return multiPublishPayload;
667
- }
668
- const normalizedRef = main_cjs.normalizeRelationPropertyValue(value);
669
- const { seedLocalId, seedUid } = main_cjs.resolveSeedIdsFromRefString(normalizedRef ?? '');
670
- // Value is not a valid seed reference (local id or 0x uid)
671
- if (!seedLocalId && !seedUid) {
672
- if (isRequired) {
673
- addValidationError(ctx, `Required relation ${relationOrImageProperty.propertyName} has invalid value: ${JSON.stringify(value)}. ` +
674
- `Value must be a valid seed reference (localId or uid) pointing to a ${propertyDef?.ref ?? propertyDef?.refModelName ?? 'related'} item.`, relationOrImageProperty.propertyName);
675
- }
676
- return multiPublishPayload;
677
- }
678
- // The local seed, also when the ref is the old uid of a seed published again since.
679
- const relatedSeed = await publishDraftGraph.findRelatedSeedRow({ seedLocalId, seedUid });
680
- if (!isStorageSeed && deferIfBackEdge(ctx, relationOrImageProperty, [relatedSeed?.seedLocalId ?? seedLocalId])) {
681
- return multiPublishPayload;
682
- }
683
- // Use dynamic import to break circular dependency
684
- const getItemMod = await Promise.resolve().then(function () { return require('./getItem-CWgb3e9G.js'); });
685
- const { getItem } = getItemMod;
686
- const relatedItem = await getItem(relatedSeed ? { seedLocalId: relatedSeed.seedLocalId } : { seedLocalId, seedUid });
687
- if (noteRelatedSeed(ctx, normalizedRef, relatedSeed, relationOrImageProperty.propertyName, relatedItem?.modelName ?? publishDraftGraph.relatedModelNameFromDef(relationOrImageProperty.propertyDef))) {
688
- return multiPublishPayload;
689
- }
690
- // When related item not found (e.g. different DB, not yet created)
691
- if (!relatedItem) {
692
- // An attested uid with no local copy is already published; the parent attests the uid as-is.
693
- if (isRequired && !main_cjs.isPublishedSeedRef(normalizedRef)) {
694
- addValidationError(ctx, `No related item found for required relation: ${relationOrImageProperty.propertyName}. ` +
695
- `Value: ${JSON.stringify(value)} (seedLocalId/seedUid). ` +
696
- `The related item may be missing, in a different database, or the reference may be broken.`, relationOrImageProperty.propertyName);
697
- }
698
- return multiPublishPayload;
699
- }
700
- // When Image/Relation already has seedUid (published), skip creating its payload—only add the property to parent
701
- if (relatedItem.seedUid && relatedItem.seedUid !== main_cjs.ZERO_BYTES32) {
702
- return multiPublishPayload;
703
- }
704
- let modelName;
705
- if (matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Image)) {
706
- modelName = 'Image';
707
- }
708
- if (matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.File)) {
709
- modelName = 'File';
710
- }
711
- if (matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Html)) {
712
- modelName = 'Html';
713
- }
714
- if (matchesDataType(relationOrImageProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Relation)) {
715
- const def = relationOrImageProperty.propertyDef;
716
- modelName = def.ref ?? def.refModelName;
717
- }
718
- if (!modelName) {
719
- addValidationError(ctx, `Model name not found for relation or image property: ${relationOrImageProperty.propertyName}`, relationOrImageProperty.propertyName);
720
- return multiPublishPayload;
721
- }
722
- return processRelatedDraftItem({
723
- relatedItem,
724
- modelName,
725
- // A storage seed (Image/File/Html/Json item) attests its own basic properties; a related model
726
- // item is published with its full property set and the draft items it reaches in turn.
727
- fullDraft: !isStorageSeed,
728
- link: { publishLocalId: originalSeedLocalId, propertySchemaUid: relationOrImageSchemaUid },
729
- reportPropertyName: relationOrImageProperty.propertyName,
730
- multiPublishPayload,
731
- uploadedTransactions,
732
- ctx,
733
- buildOpts,
734
- });
735
- };
736
- /**
737
- * The payload of a draft item (no seed uid) a published item refers to, published with it. Its
738
- * request fills the referring property (`link`) through propertiesToUpdate. With `fullDraft`, the
739
- * item's whole property set is attested: its storage seeds and Html-embedded images, and its own
740
- * relation and list properties, whose draft targets are published with it in turn (depth first,
741
- * see publishDraftGraph.ts). A draft already in the batch only gains the link.
742
- */
743
- async function processRelatedDraftItem({ relatedItem, modelName, fullDraft, link, reportPropertyName, multiPublishPayload, uploadedTransactions, ctx, buildOpts, }) {
744
- const forceFullSnapshot = buildOpts?.forceFullSnapshot === true;
745
- const seedSchemaUid = await main_cjs.getEasSchemaUidForModel(modelName);
746
- if (!seedSchemaUid) {
747
- addValidationError(ctx, `Schema UID not found for model: ${modelName}`, reportPropertyName);
748
- return multiPublishPayload;
749
- }
750
- if (multiPublishPayload.some((p) => p.localId === relatedItem.seedLocalId)) {
751
- if (link) {
752
- mergeChildPublishPayloadIfDuplicateInBatch(multiPublishPayload, relatedItem.seedLocalId, link.publishLocalId, link.propertySchemaUid);
753
- }
754
- return multiPublishPayload;
755
- }
756
- let publishPayload = {
757
- localId: relatedItem.seedLocalId,
758
- seedIsRevocable: true,
759
- versionSchemaUid: main_cjs.VERSION_SCHEMA_UID,
760
- seedUid: main_cjs.ZERO_BYTES32,
761
- seedSchemaUid,
762
- versionUid: getVersionUid(relatedItem),
763
- listOfAttestations: [],
764
- propertiesToUpdate: link ? [{ ...link }] : [],
765
- };
766
- ctx.newSeedsInProgress ?? (ctx.newSeedsInProgress = new Set());
767
- ctx.newSeedsInProgress.add(relatedItem.seedLocalId);
768
- try {
769
- await ensurePropertyDefs(relatedItem);
770
- const segmented = await publishDraftGraph.getSegmentedItemProperties(relatedItem);
771
- const { itemBasicProperties, itemUploadProperties, itemImageProperties: relatedStorageSeedProperties } = segmented;
772
- if (fullDraft) {
773
- // Its own Image/File/Html/Json properties and the images embedded in its Html (as for the item itself).
774
- multiPublishPayload = await processRelatedDraftStorageSeeds(relatedItem, relatedStorageSeedProperties, itemBasicProperties, multiPublishPayload, uploadedTransactions, ctx, buildOpts);
775
- // Its relations and lists: their draft targets are published too (same walk as publishDraftGraph).
776
- const { relationProperties, listProperties } = publishDraftGraph.draftWalkProperties(segmented);
777
- for (const relationProperty of relationProperties) {
778
- multiPublishPayload = await processRelationOrImageProperty(relationProperty, multiPublishPayload, uploadedTransactions, relatedItem.seedLocalId, ctx, buildOpts);
779
- itemBasicProperties.push(relationProperty);
780
- }
781
- for (const listProperty of listProperties) {
782
- multiPublishPayload = await processListProperty(listProperty, multiPublishPayload, uploadedTransactions, relatedItem.seedLocalId, ctx, buildOpts);
783
- itemBasicProperties.push(listProperty);
784
- }
785
- }
786
- const relatedStorageUpload = resolveStorageTransactionUploadSlot(relatedItem, itemUploadProperties);
787
- if (relatedStorageUpload) {
788
- const transactionData = findUploadedTxForSeedLocalId(uploadedTransactions, relatedItem.seedLocalId);
789
- if (transactionData) {
790
- const itemProperty = relatedStorageUpload.itemProperty;
791
- // Publish encoding reads context.propertyValue; do not await ItemProperty.save() here — it
792
- // uses xstate waitFor(10s) for idle and can time out while the machine is busy or still loading.
793
- itemProperty.getService().send({
794
- type: 'updateContext',
795
- propertyValue: transactionData.txId,
796
- renderValue: transactionData.txId,
797
- });
798
- replaceStorageTransactionInBasicProperties(itemBasicProperties, itemProperty);
799
- }
800
- }
801
- for (const p of itemBasicProperties) {
802
- if (isStorageTransactionPropertyName(p.propertyName) &&
803
- !p.propertyDef &&
804
- relatedItem.modelName) {
805
- const schema = await property.getPropertySchema(relatedItem.modelName, 'storageTransactionId', await main_cjs.getItemModelScope(relatedItem));
806
- if (schema) {
807
- p.getService().send({ type: 'updateContext', propertyRecordSchema: schema });
808
- }
809
- }
810
- }
811
- dedupeOneStorageTransactionPropertyInList(itemBasicProperties);
812
- publishPayload = await processBasicProperties(itemBasicProperties, publishPayload, ctx, {
813
- forceFullSnapshot,
814
- });
815
- }
816
- finally {
817
- ctx.newSeedsInProgress.delete(relatedItem.seedLocalId);
818
- }
819
- multiPublishPayload.push(publishPayload);
820
- return multiPublishPayload;
821
- }
822
- /**
823
- * Storage-seed properties (Image/File/Html/Json) of a draft item related to the published one, and
824
- * the images embedded in its Html (htmlEmbeddedImageCoPublish rows it owns): payloads for their seeds,
825
- * and the properties added to `itemBasicProperties` so the related item attests them. Same handling
826
- * as the published item's own (see getPublishPayload).
827
- */
828
- async function processRelatedDraftStorageSeeds(relatedItem, storageSeedProperties, itemBasicProperties, multiPublishPayload, uploadedTransactions, ctx, buildOpts) {
829
- for (const storageSeedProperty of storageSeedProperties) {
830
- multiPublishPayload = await processRelationOrImageProperty(storageSeedProperty, multiPublishPayload, uploadedTransactions, relatedItem.seedLocalId, ctx, buildOpts);
831
- itemBasicProperties.push(storageSeedProperty);
832
- }
833
- return processHtmlEmbeddedCoPublishImagePayloads(relatedItem, multiPublishPayload, uploadedTransactions, ctx, buildOpts);
834
- }
835
- async function resolveHtmlPropertySchemaUidByHtmlSeed(item, htmlSeedLocalId, ctx) {
836
- const want = htmlSeedLocalId.trim();
837
- for (const p of item.properties) {
838
- if (!matchesDataType(p.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Html))
839
- continue;
840
- const snap = p.getService().getSnapshot();
841
- const c = 'context' in snap ? snap.context : null;
842
- const pv = typeof c?.propertyValue === 'string' ? c.propertyValue.trim() : '';
843
- if (pv !== want)
844
- continue;
845
- let uid = p.schemaUid;
846
- if (!uid) {
847
- const pd = await getPropertyData(p, ctx);
848
- uid = pd?.schemaUid;
849
- }
850
- return uid;
851
- }
852
- addValidationError(ctx, `Could not find Html property for embedded image rewrite (html seed ${want}).`, 'html', 'html_embed_schema');
853
- return undefined;
854
- }
855
- async function processHtmlEmbeddedCoPublishImagePayloads(item, multiPublishPayload, uploadedTransactions, ctx, buildOpts) {
856
- const appDb = main_cjs.BaseDb.getAppDb();
857
- if (!appDb)
858
- return multiPublishPayload;
859
- const rows = await appDb
860
- .select()
861
- .from(main_cjs.htmlEmbeddedImageCoPublish)
862
- .where(drizzleOrm.eq(main_cjs.htmlEmbeddedImageCoPublish.parentSeedLocalId, item.seedLocalId));
863
- if (rows.length === 0)
864
- return multiPublishPayload;
865
- const forceFullSnapshot = buildOpts?.forceFullSnapshot === true;
866
- const getItemMod = await Promise.resolve().then(function () { return require('./getItem-CWgb3e9G.js'); });
867
- const { getItem } = getItemMod;
868
- const doneImages = new Set();
869
- for (const row of rows) {
870
- if (doneImages.has(row.imageSeedLocalId))
871
- continue;
872
- doneImages.add(row.imageSeedLocalId);
873
- // An embedded image that is already published is not co-published; one whose seed was revoked
874
- // (unpublished) blocks the publish like an image property pointing at it would.
875
- const imageSeed = await publishDraftGraph.findRelatedSeedRow({ seedLocalId: row.imageSeedLocalId });
876
- if (noteRelatedSeed(ctx, row.imageSeedLocalId, imageSeed, publishDraftGraph.htmlPropertyNameForHtmlSeed(item, row.htmlSeedLocalId), 'Image')) {
877
- continue;
878
- }
879
- // The row's Html seed must still be the value of one of the item's Html properties.
880
- const htmlSchemaUid = await resolveHtmlPropertySchemaUidByHtmlSeed(item, row.htmlSeedLocalId, ctx);
881
- if (!htmlSchemaUid)
882
- continue;
883
- const relatedItem = await getItem({ seedLocalId: row.imageSeedLocalId });
884
- if (!relatedItem) {
885
- addValidationError(ctx, `Embedded Image item not found for seed ${row.imageSeedLocalId}.`, 'html', 'html_embed_image_missing');
886
- continue;
887
- }
888
- if (relatedItem.seedUid && relatedItem.seedUid !== main_cjs.ZERO_BYTES32) {
889
- continue;
890
- }
891
- const seedSchemaUid = await main_cjs.getEasSchemaUidForModel('Image');
892
- if (!seedSchemaUid) {
893
- addValidationError(ctx, `Schema UID not found for model: Image`, 'html');
894
- continue;
895
- }
896
- // Already in the batch (e.g. also the value of an Image property): its payload is there.
897
- if (multiPublishPayload.some((p) => p.localId === relatedItem.seedLocalId)) {
898
- continue;
899
- }
900
- const versionUid = getVersionUid(relatedItem);
901
- // No propertiesToUpdate: the Html refers to the image by its Arweave URL (the data URI is
902
- // rewritten to it before the Html is uploaded), not by seed uid. The Html property holds the Html
903
- // storage seed's uid, which the Html seed's own request writes into it; the contract writes each
904
- // updater's seed uid into the same data[0] (SeedPublishLib.setSeedReference), so an image
905
- // targeting the Html property too would overwrite that reference with the image's seed uid.
906
- let publishPayload = {
907
- localId: relatedItem.seedLocalId,
908
- seedIsRevocable: true,
909
- versionSchemaUid: main_cjs.VERSION_SCHEMA_UID,
910
- seedUid: relatedItem.seedUid || main_cjs.ZERO_BYTES32,
911
- seedSchemaUid,
912
- versionUid,
913
- listOfAttestations: [],
914
- propertiesToUpdate: [],
915
- };
916
- await ensurePropertyDefs(relatedItem);
917
- const { itemBasicProperties, itemUploadProperties } = await publishDraftGraph.getSegmentedItemProperties(relatedItem);
918
- const relatedStorageUpload = resolveStorageTransactionUploadSlot(relatedItem, itemUploadProperties);
919
- if (relatedStorageUpload) {
920
- const transactionData = findUploadedTxForSeedLocalId(uploadedTransactions, relatedItem.seedLocalId);
921
- if (transactionData) {
922
- const itemProperty = relatedStorageUpload.itemProperty;
923
- itemProperty.getService().send({
924
- type: 'updateContext',
925
- propertyValue: transactionData.txId,
926
- renderValue: transactionData.txId,
927
- });
928
- replaceStorageTransactionInBasicProperties(itemBasicProperties, itemProperty);
929
- }
930
- }
931
- for (const p of itemBasicProperties) {
932
- if (isStorageTransactionPropertyName(p.propertyName) &&
933
- !p.propertyDef &&
934
- relatedItem.modelName) {
935
- const schema = await property.getPropertySchema(relatedItem.modelName, 'storageTransactionId', await main_cjs.getItemModelScope(relatedItem));
936
- if (schema) {
937
- p.getService().send({ type: 'updateContext', propertyRecordSchema: schema });
938
- }
939
- }
940
- }
941
- dedupeOneStorageTransactionPropertyInList(itemBasicProperties);
942
- publishPayload = await processBasicProperties(itemBasicProperties, publishPayload, ctx, {
943
- forceFullSnapshot,
944
- });
945
- multiPublishPayload.push(publishPayload);
946
- }
947
- return multiPublishPayload;
948
- }
949
- const processListProperty = async (listProperty, multiPublishPayload, uploadedTransactions, originalSeedLocalId, ctx, buildOpts) => {
950
- const forceFullSnapshot = buildOpts?.forceFullSnapshot === true;
951
- // processListProperty only handles list-of-relations; list-of-primitives go to itemBasicProperties
952
- if (!listProperty.propertyDef?.ref) {
953
- addValidationError(ctx, `processListProperty requires ref (list of relations). List property "${listProperty.propertyName}" has no ref. List-of-primitives should be in itemBasicProperties.`, listProperty.propertyName);
954
- return multiPublishPayload;
955
- }
956
- const snapshot = listProperty.getService().getSnapshot();
957
- const context = 'context' in snapshot ? snapshot.context : null;
958
- if (!context) {
959
- return multiPublishPayload;
960
- }
961
- let value = context.propertyValue;
962
- if (!value) {
963
- return multiPublishPayload;
964
- }
965
- if (listProperty.uid && !forceFullSnapshot) {
966
- return multiPublishPayload;
967
- }
968
- // Always resolve from the property definition; a cached schemaUid may point at a schema
969
- // registered under the schema key (bytes32[] authors) instead of authorIdentityIds.
970
- const propertyData = await getPropertyData(listProperty, ctx);
971
- if (!propertyData)
972
- return multiPublishPayload;
973
- const listPropertySchemaUid = propertyData.schemaUid;
974
- if (typeof value === 'string') {
975
- value = main_cjs.parseListPropertyValueFromStorage(value);
976
- }
977
- const iterableValue = Array.isArray(value)
978
- ? value
979
- : value != null
980
- ? [value]
981
- : [];
982
- const members = [];
983
- for (const seedId of iterableValue) {
984
- const idStr = typeof seedId === 'string'
985
- ? seedId
986
- : seedId &&
987
- typeof seedId === 'object' &&
988
- (seedId.seedLocalId ?? seedId.seedUid ?? seedId.localId ?? seedId.uid);
989
- if (!idStr)
990
- continue;
991
- const { localId: seedLocalId, uid: seedUid } = main_cjs.getCorrectId(idStr);
992
- if (!seedLocalId && !seedUid)
993
- continue;
994
- members.push({ idStr, seedLocalId, seedUid });
995
- }
996
- // A member that is an item still in progress (a cycle back to it) can't be attested in this
997
- // publish, so the list is deferred; its other draft members are still published, unlinked.
998
- const memberSeeds = await Promise.all(members.map((m) => publishDraftGraph.findRelatedSeedRow({ seedLocalId: m.seedLocalId, seedUid: m.seedUid })));
999
- const deferred = deferIfBackEdge(ctx, listProperty, members.map((m, i) => memberSeeds[i]?.seedLocalId ?? m.seedLocalId));
1000
- for (let i = 0; i < members.length; i++) {
1001
- const { idStr, seedLocalId, seedUid } = members[i];
1002
- const relatedSeed = memberSeeds[i] ?? null;
1003
- const memberLocalId = relatedSeed?.seedLocalId ?? seedLocalId;
1004
- if (memberLocalId && ctx.newSeedsInProgress?.has(memberLocalId))
1005
- continue;
1006
- // Use dynamic import to break circular dependency
1007
- const getItemMod = await Promise.resolve().then(function () { return require('./getItem-CWgb3e9G.js'); });
1008
- const { getItem } = getItemMod;
1009
- const relatedItem = await getItem(relatedSeed ? { seedLocalId: relatedSeed.seedLocalId } : { seedLocalId, seedUid });
1010
- if (noteRelatedSeed(ctx, idStr.trim(), relatedSeed, listProperty.propertyName, relatedItem?.modelName ?? publishDraftGraph.relatedModelNameFromDef(listProperty.propertyDef))) {
1011
- continue;
1012
- }
1013
- if (!relatedItem) {
1014
- // An attested uid with no local copy is already published; the list attests the uid as-is.
1015
- if (!main_cjs.isPublishedSeedRef(idStr)) {
1016
- console.error(`No related item found for list property: ${listProperty.propertyName}`);
1017
- }
1018
- continue;
1019
- }
1020
- if (relatedItem.seedUid && relatedItem.seedUid !== main_cjs.ZERO_BYTES32) {
1021
- continue;
1022
- }
1023
- let modelName;
1024
- if (listProperty.propertyDef?.ref || listProperty.propertyDef.refModelName) {
1025
- const def = listProperty.propertyDef;
1026
- modelName = def.ref ?? def.refModelName;
1027
- }
1028
- if (matchesDataType(listProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Image)) {
1029
- modelName = 'Image';
1030
- }
1031
- if (matchesDataType(listProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.File)) {
1032
- modelName = 'File';
1033
- }
1034
- if (matchesDataType(listProperty.propertyDef?.dataType, main_cjs.ModelPropertyDataTypes.Html)) {
1035
- modelName = 'Html';
1036
- }
1037
- if (!modelName) {
1038
- addValidationError(ctx, `Model name not found for list property: ${listProperty.propertyName}`, listProperty.propertyName);
1039
- continue;
1040
- }
1041
- multiPublishPayload = await processRelatedDraftItem({
1042
- relatedItem,
1043
- modelName,
1044
- fullDraft: true,
1045
- link: deferred ? null : { publishLocalId: originalSeedLocalId, propertySchemaUid: listPropertySchemaUid },
1046
- reportPropertyName: listProperty.propertyName,
1047
- multiPublishPayload,
1048
- uploadedTransactions,
1049
- ctx,
1050
- buildOpts,
1051
- });
1052
- }
1053
- return multiPublishPayload;
1054
- };
1055
- /**
1056
- * Same EAS schema + same encoded attestation bytes (data field). Intentionally ignores refUID so
1057
- * duplicate storageTransactionId rows that only differ by ref (e.g. 0x0 vs version uid) collapse.
1058
- */
1059
- function attestationPayloadDedupeKey(att) {
1060
- const schema = String(att.schema ?? '').toLowerCase();
1061
- const dataArr = att.data;
1062
- const d0 = Array.isArray(dataArr) ? dataArr[0] : undefined;
1063
- const dataHex = d0 && typeof d0 === 'object' && d0 !== null && 'data' in d0
1064
- ? String(d0.data ?? '').toLowerCase()
1065
- : '';
1066
- return `${schema}:${dataHex}`;
1067
- }
1068
- /**
1069
- * Collapse duplicate rows in listOfAttestations (same schema + encoded payload).
1070
- */
1071
- function dedupeListOfAttestationsInEachPayload(payload) {
1072
- for (const p of payload) {
1073
- const list = p.listOfAttestations ?? [];
1074
- if (list.length <= 1)
1075
- continue;
1076
- const seen = new Set();
1077
- const out = [];
1078
- for (const a of list) {
1079
- const k = attestationPayloadDedupeKey(a);
1080
- if (seen.has(k))
1081
- continue;
1082
- seen.add(k);
1083
- out.push(a);
1084
- }
1085
- p.listOfAttestations = out;
1086
- }
1087
- return payload;
1088
- }
1089
- /**
1090
- * Merge duplicate PublishPayload rows with the same localId (ordering / batch edge cases).
1091
- * Dedupe listOfAttestations so identical storage tx attestations are not emitted twice.
1092
- */
1093
- function dedupeMultiPublishPayloadByLocalId(payload) {
1094
- const map = new Map();
1095
- const order = [];
1096
- for (const p of payload) {
1097
- const id = p.localId;
1098
- const existing = map.get(id);
1099
- if (!existing) {
1100
- map.set(id, p);
1101
- order.push(id);
1102
- continue;
1103
- }
1104
- const ptu = [...(existing.propertiesToUpdate ?? [])];
1105
- for (const u of p.propertiesToUpdate ?? []) {
1106
- if (!ptu.some((e) => e.publishLocalId === u.publishLocalId &&
1107
- String(e.propertySchemaUid ?? '').toLowerCase() ===
1108
- String(u.propertySchemaUid ?? '').toLowerCase())) {
1109
- ptu.push(u);
1110
- }
1111
- }
1112
- existing.propertiesToUpdate = ptu;
1113
- const seenKeys = new Set((existing.listOfAttestations ?? []).map((a) => attestationPayloadDedupeKey(a)));
1114
- const merged = [...(existing.listOfAttestations ?? [])];
1115
- for (const a of p.listOfAttestations ?? []) {
1116
- const k = attestationPayloadDedupeKey(a);
1117
- if (seenKeys.has(k))
1118
- continue;
1119
- seenKeys.add(k);
1120
- merged.push(a);
1121
- }
1122
- existing.listOfAttestations = merged;
1123
- }
1124
- return order.map((id) => map.get(id)).filter(Boolean);
1125
- }
1126
- /**
1127
- * Child File/Image items may keep storageTransactionId only on the item machine's
1128
- * propertyInstances map; allProperties / item.properties can omit it during publish.
1129
- */
1130
- function getStorageTransactionPropertyFromItemInstances(item) {
1131
- try {
1132
- const svc = item.getService?.();
1133
- if (!svc)
1134
- return undefined;
1135
- const snap = svc.getSnapshot();
1136
- const instances = snap.context?.propertyInstances;
1137
- if (!instances || !(instances instanceof Map))
1138
- return undefined;
1139
- const direct = instances.get('storageTransactionId') ?? instances.get('storage_transaction_id');
1140
- if (direct)
1141
- return direct;
1142
- for (const [, p] of instances) {
1143
- if (p && isStorageTransactionPropertyName(p.propertyName))
1144
- return p;
1145
- }
1146
- }
1147
- catch {
1148
- return undefined;
1149
- }
1150
- return undefined;
1151
- }
1152
- /**
1153
- * Resolve storageTransactionId (+ ItemStorage children) for publish.
1154
- * getSegmentedItemProperties can yield empty itemUploadProperties when the child Item never
1155
- * hydrated storageTransactionId into the upload bucket (e.g. only uri/metadata rows), while
1156
- * getStorageSeedUploads still creates an Arweave upload keyed by child seedLocalId.
1157
- */
1158
- function resolveStorageTransactionUploadSlot(item, itemUploadProperties) {
1159
- const named = itemUploadProperties.find((u) => isStorageTransactionPropertyName(u.itemProperty.propertyName));
1160
- if (named)
1161
- return named;
1162
- if (itemUploadProperties.length === 1)
1163
- return itemUploadProperties[0];
1164
- const all = item.allProperties;
1165
- const fromInstances = getStorageTransactionPropertyFromItemInstances(item);
1166
- const storagePropEarly = all?.['storageTransactionId'] ??
1167
- all?.['storage_transaction_id'] ??
1168
- Object.values(all ?? {}).find((p) => !!p && isStorageTransactionPropertyName(p.propertyName)) ??
1169
- item.properties?.find((p) => isStorageTransactionPropertyName(p.propertyName));
1170
- const storageProp = storagePropEarly ?? fromInstances;
1171
- if (!storageProp)
1172
- return undefined;
1173
- const childProps = item.properties?.filter((p) => p.propertyDef &&
1174
- p.propertyDef.storageType === 'ItemStorage') ?? [];
1175
- return { itemProperty: storageProp, childProperties: childProps };
1176
- }
1177
- function findUploadedTxForSeedLocalId(uploadedTransactions, seedLocalId) {
1178
- const t = seedLocalId.trim();
1179
- return (uploadedTransactions.find((u) => u.seedLocalId === t) ??
1180
- uploadedTransactions.find((u) => u.seedLocalId != null && u.seedLocalId.trim() === t));
1181
- }
1182
- const getPublishPayload = async (item, uploadedTransactions, options) => {
1183
- const validationCtx = { errors: [] };
1184
- const publishMode = options?.publishMode ?? 'patch';
1185
- // A revoked seed can't be published under again: republishing creates a new seed attestation
1186
- // (new seedUid) and a new version carrying every property (see docs/ATTESTATION_REVOCATION.md).
1187
- const hasSeedUid = !!item.seedUid && item.seedUid !== main_cjs.ZERO_BYTES32;
1188
- const republishRevokedSeed = hasSeedUid && (await publishDraftGraph.isSeedRevoked(item.seedLocalId));
1189
- const rootSeedUid = republishRevokedSeed ? main_cjs.ZERO_BYTES32 : item.seedUid || main_cjs.ZERO_BYTES32;
1190
- const forceFullSnapshot = publishMode === 'new_version' || republishRevokedSeed;
1191
- if (publishMode === 'new_version' && (!item.seedUid || item.seedUid === main_cjs.ZERO_BYTES32)) {
1192
- addValidationError(validationCtx, 'Publishing as a new version requires the item to already have a published Seed attestation (seed UID).', 'seedUid', 'publish_new_version_requires_seed');
1193
- }
1194
- let multiPublishPayload = [];
1195
- // The root gets a new seed (draft, or revoked seed published again): related drafts referring
1196
- // back to it can't attest its uid in this publish (see publishDraftGraph.ts).
1197
- if (rootSeedUid === main_cjs.ZERO_BYTES32) {
1198
- validationCtx.newSeedsInProgress = new Set([item.seedLocalId]);
1199
- }
1200
- // Each PublishPayload is generated from a Seed that needs publishing
1201
- // First we need to determine all Seeds to publish
1202
- // That means the Seed of the Item, plus any Seeds pointed to by Relations
1203
- // Check if the item has a schema UID
1204
- let itemSchemaUid = item.schemaUid;
1205
- if (!itemSchemaUid) {
1206
- const schemaUid = await main_cjs.getEasSchemaUidForModel(item.modelName);
1207
- if (!schemaUid) {
1208
- addValidationError(validationCtx, `Schema UID not found for model: ${item.modelName}`);
1209
- itemSchemaUid = main_cjs.ZERO_BYTES32; // placeholder so we can continue collecting errors
1210
- }
1211
- else {
1212
- itemSchemaUid = schemaUid;
1213
- }
1214
- }
1215
- let versionUid = getVersionUid(item);
1216
- if (versionUid === main_cjs.ZERO_BYTES32 && rootSeedUid !== main_cjs.ZERO_BYTES32) {
1217
- versionUid = await resolveVersionUid(item.seedLocalId, rootSeedUid);
1218
- }
1219
- if (forceFullSnapshot && hasSeedUid) {
1220
- versionUid = main_cjs.ZERO_BYTES32;
1221
- }
1222
- let itemPublishData = {
1223
- localId: item.seedLocalId,
1224
- seedUid: rootSeedUid,
1225
- seedIsRevocable: true,
1226
- seedSchemaUid: itemSchemaUid,
1227
- versionSchemaUid: main_cjs.VERSION_SCHEMA_UID,
1228
- versionUid,
1229
- listOfAttestations: [],
1230
- propertiesToUpdate: [],
1231
- };
1232
- await ensurePropertyDefs(item);
1233
- const { itemBasicProperties, itemListProperties, itemUploadProperties, itemImageProperties, itemRelationProperties, } = await publishDraftGraph.getSegmentedItemProperties(item);
1234
- const relationAndImageProperties = [...itemRelationProperties, ...itemImageProperties];
1235
- // Validate required relations have values before processing
1236
- for (const relProp of itemRelationProperties) {
1237
- const snapshot = relProp.getService().getSnapshot();
1238
- const ctx = 'context' in snapshot ? snapshot.context : null;
1239
- const val = ctx ? ctx.renderValue ?? ctx.propertyValue : undefined;
1240
- if (val != null && typeof val === 'string' && val.trim() !== '')
1241
- continue;
1242
- // No value - check if required from propertyDef or DB
1243
- let isRequired = relProp.propertyDef?.required === true;
1244
- if (!isRequired && main_cjs.BaseDb.getAppDb() && item.modelName) {
1245
- const normalizedModelName = lodashEs.upperFirst(lodashEs.camelCase(item.modelName));
1246
- const modelRecord = await main_cjs.resolveModelRecord(normalizedModelName, await main_cjs.getItemModelScope(item));
1247
- const modelRows = modelRecord ? [modelRecord] : [];
1248
- if (modelRows.length > 0) {
1249
- const propRows = await main_cjs.BaseDb.getAppDb()
1250
- .select({ required: main_cjs.properties.required, refModelId: main_cjs.properties.refModelId })
1251
- .from(main_cjs.properties)
1252
- .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.properties.modelId, modelRows[0].id), drizzleOrm.eq(main_cjs.properties.name, relProp.propertyName), drizzleOrm.sql `lower(${main_cjs.properties.dataType}) = 'relation'`))
1253
- .limit(1);
1254
- if (propRows.length > 0 && (propRows[0].required === true || propRows[0].required === 1)) {
1255
- isRequired = true;
1256
- }
1257
- }
1258
- }
1259
- if (isRequired) {
1260
- const refModel = relProp.propertyDef?.ref ?? relProp.propertyDef?.refModelName ?? 'related';
1261
- addValidationError(validationCtx, `Required relation ${relProp.propertyName} has no value. ` +
1262
- `A value pointing to a valid ${refModel} item is required to publish.`, relProp.propertyName);
1263
- }
1264
- }
1265
- const rootStorageUpload = resolveStorageTransactionUploadSlot(item, itemUploadProperties);
1266
- if (rootStorageUpload) {
1267
- const transactionData = findUploadedTxForSeedLocalId(uploadedTransactions, item.seedLocalId);
1268
- if (transactionData) {
1269
- const itemProperty = rootStorageUpload.itemProperty;
1270
- itemProperty.getService().send({
1271
- type: 'updateContext',
1272
- propertyValue: transactionData.txId,
1273
- renderValue: transactionData.txId,
1274
- });
1275
- replaceStorageTransactionInBasicProperties(itemBasicProperties, itemProperty);
1276
- }
1277
- }
1278
- for (const relationProperty of relationAndImageProperties) {
1279
- multiPublishPayload = await processRelationOrImageProperty(relationProperty, multiPublishPayload, uploadedTransactions, item.seedLocalId, validationCtx, { forceFullSnapshot });
1280
- itemBasicProperties.push(relationProperty);
1281
- }
1282
- multiPublishPayload = await processHtmlEmbeddedCoPublishImagePayloads(item, multiPublishPayload, uploadedTransactions, validationCtx, { forceFullSnapshot });
1283
- for (const listProperty of itemListProperties) {
1284
- multiPublishPayload = await processListProperty(listProperty, multiPublishPayload, uploadedTransactions, item.seedLocalId, validationCtx, { forceFullSnapshot });
1285
- itemBasicProperties.push(listProperty);
1286
- }
1287
- for (const p of itemBasicProperties) {
1288
- if (isStorageTransactionPropertyName(p.propertyName) && !p.propertyDef && item.modelName) {
1289
- const schema = await property.getPropertySchema(item.modelName, 'storageTransactionId', await main_cjs.getItemModelScope(item));
1290
- if (schema) {
1291
- p.getService().send({ type: 'updateContext', propertyRecordSchema: schema });
1292
- }
1293
- }
1294
- }
1295
- dedupeOneStorageTransactionPropertyInList(itemBasicProperties);
1296
- itemPublishData = await processBasicProperties(itemBasicProperties, itemPublishData, validationCtx, { forceFullSnapshot });
1297
- multiPublishPayload.push(itemPublishData);
1298
- // Ensure requests are ordered so that when A has propertiesToUpdate pointing to B (publishLocalId),
1299
- // A (the updater) is published before B (the updatee). The contract injects A's seedUid into B's
1300
- // attestation before B is sent to EAS.
1301
- multiPublishPayload = dedupeMultiPublishPayloadByLocalId(multiPublishPayload);
1302
- multiPublishPayload = orderPayloadByDependencies(multiPublishPayload);
1303
- // Ensure attestations referenced in propertiesToUpdate have at least one data element.
1304
- // The contract writes the seed UID into data[0].data; empty data causes Panic 50.
1305
- multiPublishPayload = ensurePropertiesToUpdateAttestationsHaveData(multiPublishPayload);
1306
- multiPublishPayload = dedupeListOfAttestationsInEachPayload(multiPublishPayload);
1307
- if (publishMode === 'new_version') {
1308
- const rootPayload = multiPublishPayload.find((p) => p.localId === item.seedLocalId);
1309
- const listLen = rootPayload?.listOfAttestations?.length ?? 0;
1310
- if (!rootPayload || listLen === 0) {
1311
- addValidationError(validationCtx, 'Publishing as a new version requires at least one property attestation for the item. ' +
1312
- 'Ensure required fields have values and that publishable properties are present.', 'listOfAttestations', 'publish_new_version_empty_snapshot');
1313
- }
1314
- }
1315
- // Stop before anything is uploaded or attested: the payload would attest revoked seed uids.
1316
- if (validationCtx.unpublishedRelatedItems?.length) {
1317
- throw new RelatedItemUnpublishedError(validationCtx.unpublishedRelatedItems, validationCtx.errors);
1318
- }
1319
- if (validationCtx.errors.length > 0) {
1320
- const combinedMessage = validationCtx.errors.map((e) => e.message).join('\n');
1321
- throw new PublishValidationFailedError(`Validation failed (${validationCtx.errors.length} error${validationCtx.errors.length === 1 ? '' : 's'}):\n${combinedMessage}`, validationCtx.errors);
1322
- }
1323
- return multiPublishPayload;
1324
- };
1325
- /**
1326
- * Validates an item for publishing without performing Arweave or EAS work.
1327
- * Use in the checking step to fail fast before creating transactions.
1328
- * Pass empty array for uploadedTransactions when validating before Arweave upload.
1329
- */
1330
- const validateItemForPublish = async (item, uploadedTransactions = [], options) => {
1331
- try {
1332
- await getPublishPayload(item, uploadedTransactions, options);
1333
- return { isValid: true, errors: [] };
1334
- }
1335
- catch (err) {
1336
- if (err instanceof PublishValidationFailedError) {
1337
- return { isValid: false, errors: err.validationErrors };
1338
- }
1339
- throw err;
1340
- }
1341
- };
1342
- /**
1343
- * Normalize a schema UID to 0x-prefixed 64-char hex for comparison.
1344
- */
1345
- function normalizeSchemaUid(v) {
1346
- if (v == null || v === '')
1347
- return '';
1348
- const raw = v.startsWith('0x') ? v.slice(2) : v;
1349
- const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(64, '0').slice(-64);
1350
- return ('0x' + hex).toLowerCase();
1351
- }
1352
- /**
1353
- * Ensure that when request A has propertiesToUpdate with (publishLocalId: B, propertySchemaUid: X),
1354
- * request B has an attestation for schema X with at least one data element. The contract writes
1355
- * the seed UID into data[0].data; empty data causes Panic 50.
1356
- */
1357
- function ensurePropertiesToUpdateAttestationsHaveData(payload) {
1358
- const byLocalId = new Map();
1359
- for (const p of payload) {
1360
- byLocalId.set(p.localId, p);
1361
- }
1362
- const placeholderData = {
1363
- ...main_cjs.defaultAttestationData,
1364
- data: main_cjs.ZERO_BYTES32,
1365
- };
1366
- for (const req of payload) {
1367
- for (const pu of req.propertiesToUpdate ?? []) {
1368
- const targetId = pu.publishLocalId;
1369
- const schemaUid = pu.propertySchemaUid;
1370
- if (!targetId || !schemaUid)
1371
- continue;
1372
- const targetReq = byLocalId.get(targetId);
1373
- if (!targetReq?.listOfAttestations)
1374
- continue;
1375
- const wantSchema = normalizeSchemaUid(schemaUid);
1376
- const att = targetReq.listOfAttestations.find((a) => normalizeSchemaUid(a?.schema) === wantSchema);
1377
- if (!att)
1378
- continue;
1379
- if (!Array.isArray(att.data) || att.data.length === 0) {
1380
- att.data = [placeholderData];
1381
- }
1382
- }
1383
- }
1384
- return payload;
1385
- }
1386
- /**
1387
- * LocalIds in this batch referenced by attestations (bytes32 / bytes32[]) that must publish before this request.
1388
- */
1389
- function collectAttestationLocalRefIds(req, allLocalIds) {
1390
- const refs = [];
1391
- for (const a of req.listOfAttestations ?? []) {
1392
- const att = a;
1393
- if (att._unresolvedValue && allLocalIds.has(att._unresolvedValue)) {
1394
- refs.push(att._unresolvedValue);
1395
- }
1396
- if (Array.isArray(att._rawListIdsForResolve)) {
1397
- for (const id of att._rawListIdsForResolve) {
1398
- const t = id != null ? String(id).trim() : '';
1399
- if (t && allLocalIds.has(t))
1400
- refs.push(t);
1401
- }
1402
- }
1403
- }
1404
- return refs;
1405
- }
1406
- /**
1407
- * Topological sort (Kahn): edge `from → to` means `from` must publish before `to`.
1408
- * - propertiesToUpdate: updater before updatee (contract injection).
1409
- * - _unresolvedValue / _rawListIdsForResolve: referenced seed before request that encodes the ref.
1410
- * The previous DFS visit could order [Post, Image] when Post appeared first in the input array,
1411
- * so resolvedUids was empty when Post was published and attestations kept local ids.
1412
- */
1413
- function orderPayloadByDependencies(payload) {
1414
- if (payload.length <= 1)
1415
- return payload;
1416
- const byLocalId = new Map();
1417
- const allIds = new Set();
1418
- const indexOrder = new Map();
1419
- for (let i = 0; i < payload.length; i++) {
1420
- const p = payload[i];
1421
- byLocalId.set(p.localId, p);
1422
- allIds.add(p.localId);
1423
- indexOrder.set(p.localId, i);
1424
- }
1425
- const indegree = new Map();
1426
- for (const id of allIds)
1427
- indegree.set(id, 0);
1428
- const adj = new Map();
1429
- const addEdge = (from, to) => {
1430
- if (from === to || !allIds.has(from) || !allIds.has(to))
1431
- return;
1432
- if (!adj.has(from))
1433
- adj.set(from, new Set());
1434
- const set = adj.get(from);
1435
- if (set.has(to))
1436
- return;
1437
- set.add(to);
1438
- indegree.set(to, (indegree.get(to) ?? 0) + 1);
1439
- };
1440
- for (const p of payload) {
1441
- for (const u of p.propertiesToUpdate ?? []) {
1442
- const targetId = u.publishLocalId;
1443
- if (targetId && targetId !== p.localId)
1444
- addEdge(p.localId, targetId);
1445
- }
1446
- for (const refId of collectAttestationLocalRefIds(p, allIds)) {
1447
- addEdge(refId, p.localId);
1448
- }
1449
- }
1450
- const zero = [];
1451
- for (const id of allIds) {
1452
- if ((indegree.get(id) ?? 0) === 0)
1453
- zero.push(id);
1454
- }
1455
- zero.sort((a, b) => (indexOrder.get(a) ?? 0) - (indexOrder.get(b) ?? 0));
1456
- const result = [];
1457
- const queue = zero;
1458
- while (queue.length > 0) {
1459
- const id = queue.shift();
1460
- const p = byLocalId.get(id);
1461
- if (p)
1462
- result.push(p);
1463
- for (const to of adj.get(id) ?? []) {
1464
- const next = (indegree.get(to) ?? 0) - 1;
1465
- indegree.set(to, next);
1466
- if (next === 0) {
1467
- queue.push(to);
1468
- queue.sort((a, b) => (indexOrder.get(a) ?? 0) - (indexOrder.get(b) ?? 0));
1469
- }
1470
- }
1471
- }
1472
- if (result.length !== payload.length) {
1473
- const seen = new Set(result.map((r) => r.localId));
1474
- for (const p of payload) {
1475
- if (!seen.has(p.localId))
1476
- result.push(p);
1477
- }
1478
- }
1479
- return result;
1480
- }
1481
- /** Normalize attestation UID to 32-byte hex for SchemaEncoder bytes32 fields. */
1482
- function padUidForBytes32Schema(uid) {
1483
- const t = uid.trim();
1484
- if (!t.startsWith('0x'))
1485
- return uid;
1486
- const hex = t.slice(2).replace(/[^0-9a-fA-F]/g, '');
1487
- if (hex.length === 0)
1488
- return uid;
1489
- return ('0x' + hex.padStart(64, '0').slice(-64)).toLowerCase();
1490
- }
1491
- /**
1492
- * Resolves relation/image property values (seedLocalId) to attestation uids after dependent seeds are published.
1493
- * Call after each payload is published, passing the returned attestation uid for that seed's localId.
1494
- * Returns an updated multiPayload with re-encoded attestations where resolution was applied.
1495
- */
1496
- const resolvePublishPayloadValues = async (multiPayload, resolvedUids) => {
1497
- if (Object.keys(resolvedUids).length === 0) {
1498
- return multiPayload;
1499
- }
1500
- const result = [];
1501
- for (const payload of multiPayload) {
1502
- const updatedAttestations = [];
1503
- for (const attestation of payload.listOfAttestations) {
1504
- const entry = attestation;
1505
- const rawList = entry._rawListIdsForResolve;
1506
- if (rawList &&
1507
- rawList.length > 0 &&
1508
- entry._schemaDef &&
1509
- (entry._propertyNameForSchema || entry._propertyName)) {
1510
- const fieldName = entry._propertyNameForSchema ?? main_cjs.toSnakeCase(entry._propertyName);
1511
- const resolvedValues = [];
1512
- let allSlotsResolved = true;
1513
- for (const id of rawList) {
1514
- const trimmed = id.trim();
1515
- if (isUidRef(trimmed)) {
1516
- resolvedValues.push(padUidForBytes32Schema(trimmed));
1517
- continue;
1518
- }
1519
- const r = resolvedUids[trimmed];
1520
- if (r) {
1521
- resolvedValues.push(padUidForBytes32Schema(r));
1522
- continue;
1523
- }
1524
- allSlotsResolved = false;
1525
- break;
1526
- }
1527
- // Do not encode or clear hints until every slot has a real uid — otherwise sequential
1528
- // publish burns encodeBytes32String(localId) into data and drops _rawListIdsForResolve.
1529
- if (!allSlotsResolved) {
1530
- updatedAttestations.push({
1531
- ...entry,
1532
- data: Array.isArray(entry.data) ? entry.data : [entry.data],
1533
- });
1534
- continue;
1535
- }
1536
- const dataEncoder = new easSdk.SchemaEncoder(entry._schemaDef);
1537
- const encodedData = dataEncoder.encodeData([
1538
- {
1539
- name: fieldName,
1540
- type: 'bytes32[]',
1541
- value: resolvedValues,
1542
- },
1543
- ]);
1544
- const baseData = Array.isArray(entry.data) ? entry.data[0] : entry.data;
1545
- updatedAttestations.push({
1546
- ...entry,
1547
- data: [
1548
- {
1549
- ...baseData,
1550
- data: encodedData,
1551
- },
1552
- ],
1553
- _rawListIdsForResolve: undefined,
1554
- _easDataType: undefined,
1555
- });
1556
- continue;
1557
- }
1558
- const resolvedUid = entry._unresolvedValue && resolvedUids[entry._unresolvedValue];
1559
- const easType = entry._easDataType || 'bytes32';
1560
- if (resolvedUid && entry._schemaDef && (entry._propertyNameForSchema || entry._propertyName)) {
1561
- const fieldName = entry._propertyNameForSchema ?? main_cjs.toSnakeCase(entry._propertyName);
1562
- const valueForEncode = easType === 'bytes32' ? padUidForBytes32Schema(resolvedUid) : resolvedUid;
1563
- const dataEncoder = new easSdk.SchemaEncoder(entry._schemaDef);
1564
- const encodedData = dataEncoder.encodeData([
1565
- {
1566
- name: fieldName,
1567
- type: easType,
1568
- value: valueForEncode,
1569
- },
1570
- ]);
1571
- const baseData = Array.isArray(entry.data) ? entry.data[0] : entry.data;
1572
- updatedAttestations.push({
1573
- ...entry,
1574
- data: [
1575
- {
1576
- ...baseData,
1577
- data: encodedData,
1578
- },
1579
- ],
1580
- _unresolvedValue: undefined,
1581
- });
1582
- }
1583
- else {
1584
- const normalizedEntry = {
1585
- ...entry,
1586
- data: Array.isArray(entry.data) ? entry.data : [entry.data],
1587
- };
1588
- updatedAttestations.push(normalizedEntry);
1589
- }
1590
- }
1591
- result.push({
1592
- ...payload,
1593
- listOfAttestations: updatedAttestations,
1594
- });
1595
- }
1596
- return result;
1597
- };
1598
-
1599
- exports.PublishValidationFailedError = PublishValidationFailedError;
1600
- exports.getPublishPayload = getPublishPayload;
1601
- exports.resolvePublishPayloadValues = resolvePublishPayloadValues;
1602
- exports.validateItemForPublish = validateItemForPublish;
1603
- //# sourceMappingURL=getPublishPayload-BsZWiJ03.js.map