@seedprotocol/sdk 0.4.32 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/dist/BasePathResolver-BDgc7c4T.js +485 -0
  2. package/dist/BasePathResolver-BDgc7c4T.js.map +1 -0
  3. package/dist/{ModelProperty-e_hXSFvf.js → ModelProperty-D-ysg8zA.js} +37 -43
  4. package/dist/ModelProperty-D-ysg8zA.js.map +1 -0
  5. package/dist/{Schema-DonRkUOJ.js → Schema-CyCftnKI.js} +40 -40
  6. package/dist/{Schema-DonRkUOJ.js.map → Schema-CyCftnKI.js.map} +1 -1
  7. package/dist/{SchemaValidationService-DcmfhQae.js → SchemaValidationService-POM6jHbJ.js} +9 -5
  8. package/dist/{SchemaValidationService-DcmfhQae.js.map → SchemaValidationService-POM6jHbJ.js.map} +1 -1
  9. package/dist/{backfillMetadataPropertyIds-CKTfvFgQ.js → backfillMetadataPropertyIds-DzZw57iJ.js} +3 -11
  10. package/dist/{backfillMetadataPropertyIds-CKTfvFgQ.js.map → backfillMetadataPropertyIds-DzZw57iJ.js.map} +1 -1
  11. package/dist/cjs/{ModelProperty-BQYU5hPQ.js → ModelProperty-CmuGJvyi.js} +25 -26
  12. package/dist/cjs/{ModelProperty-BQYU5hPQ.js.map → ModelProperty-CmuGJvyi.js.map} +1 -1
  13. package/dist/cjs/{Schema-BcRHcQ0W.js → Schema-gpFnZMhB.js} +28 -29
  14. package/dist/cjs/{Schema-BcRHcQ0W.js.map → Schema-gpFnZMhB.js.map} +1 -1
  15. package/dist/cjs/{SchemaValidationService-CQNDgyZl.js → SchemaValidationService-E3xTSRai.js} +9 -10
  16. package/dist/cjs/{SchemaValidationService-CQNDgyZl.js.map → SchemaValidationService-E3xTSRai.js.map} +1 -1
  17. package/dist/cjs/{backfillMetadataPropertyIds-Dn4oVmEv.js → backfillMetadataPropertyIds-_bivrvRs.js} +11 -12
  18. package/dist/cjs/{backfillMetadataPropertyIds-Dn4oVmEv.js.map → backfillMetadataPropertyIds-_bivrvRs.js.map} +1 -1
  19. package/dist/cjs/eas-BwDKJmlb.js +112 -0
  20. package/dist/cjs/eas-BwDKJmlb.js.map +1 -0
  21. package/dist/cjs/{getItem-DpnPrzl3.js → getItem-MShQw3sz.js} +11 -12
  22. package/dist/cjs/{getItem-DpnPrzl3.js.map → getItem-MShQw3sz.js.map} +1 -1
  23. package/dist/cjs/{getPublishPayload-CGKMEL3H.js → getPublishPayload-C1nOOXp_.js} +93 -83
  24. package/dist/cjs/getPublishPayload-C1nOOXp_.js.map +1 -0
  25. package/dist/cjs/{getPublishUploads-DeI0f2UN.js → getPublishUploads-BjgxgrKD.js} +17 -18
  26. package/dist/cjs/{getPublishUploads-DeI0f2UN.js.map → getPublishUploads-BjgxgrKD.js.map} +1 -1
  27. package/dist/cjs/{getSegmentedItemProperties-BgS_FhAx.js → getSegmentedItemProperties-Cuw7wcxb.js} +64 -15
  28. package/dist/cjs/getSegmentedItemProperties-Cuw7wcxb.js.map +1 -0
  29. package/dist/cjs/{index-BnAqr2le.js → index-9Z2FOvLD.js} +12 -13
  30. package/dist/cjs/index-9Z2FOvLD.js.map +1 -0
  31. package/dist/cjs/{index-ByozbTn_.js → index-vk2DeF2D.js} +1237 -3235
  32. package/dist/cjs/index-vk2DeF2D.js.map +1 -0
  33. package/dist/cjs/index.browser-BSf8HpnU.js +22 -0
  34. package/dist/cjs/index.browser-BSf8HpnU.js.map +1 -0
  35. package/dist/cjs/{ownership-CsWuaNfH.js → ownership-DhWda0J9.js} +11 -25
  36. package/dist/cjs/{ownership-CsWuaNfH.js.map → ownership-DhWda0J9.js.map} +1 -1
  37. package/dist/cjs/{property-CeR45LMx.js → property-D3Ww2_Qh.js} +13 -14
  38. package/dist/cjs/{property-CeR45LMx.js.map → property-D3Ww2_Qh.js.map} +1 -1
  39. package/dist/cjs/{syncDbWithEas-CA2Lum5V.js → syncDbWithEas-Dht3_7UD.js} +26 -39
  40. package/dist/cjs/syncDbWithEas-Dht3_7UD.js.map +1 -0
  41. package/dist/configurePlatform-R5neRbQ9.js +27 -0
  42. package/dist/configurePlatform-R5neRbQ9.js.map +1 -0
  43. package/dist/constants-B5S5JPDK.js +660 -0
  44. package/dist/constants-B5S5JPDK.js.map +1 -0
  45. package/dist/constants-DMHTYMgJ.js +120 -0
  46. package/dist/constants-DMHTYMgJ.js.map +1 -0
  47. package/dist/db-Cvh84NY7.js +1972 -0
  48. package/dist/db-Cvh84NY7.js.map +1 -0
  49. package/dist/eas-D9b7z2Wn.js +68 -0
  50. package/dist/eas-D9b7z2Wn.js.map +1 -0
  51. package/dist/{getItem-GOXWo_Iy.js → getItem-B81V3m4S.js} +10 -6
  52. package/dist/{getItem-GOXWo_Iy.js.map → getItem-B81V3m4S.js.map} +1 -1
  53. package/dist/{getPublishPayload-D16enahU.js → getPublishPayload-CNYsn8-6.js} +87 -74
  54. package/dist/getPublishPayload-CNYsn8-6.js.map +1 -0
  55. package/dist/{getPublishUploads-wGqH19UY.js → getPublishUploads-D9rPHkB7.js} +14 -10
  56. package/dist/{getPublishUploads-wGqH19UY.js.map → getPublishUploads-D9rPHkB7.js.map} +1 -1
  57. package/dist/{getSegmentedItemProperties-Be3kYWY3.js → getSegmentedItemProperties-Bg3_b-b1.js} +18 -15
  58. package/dist/getSegmentedItemProperties-Bg3_b-b1.js.map +1 -0
  59. package/dist/{index-BcXKZQpX.js → index--F3Wolt5.js} +1171 -5452
  60. package/dist/index--F3Wolt5.js.map +1 -0
  61. package/dist/{index-BFyMxc7e.js → index-QMrBK-L3.js} +2 -2
  62. package/dist/index-QMrBK-L3.js.map +1 -0
  63. package/dist/index-oi4roUVf.js +22 -0
  64. package/dist/index-oi4roUVf.js.map +1 -0
  65. package/dist/index.node-Bow8kHew.js +503 -0
  66. package/dist/index.node-Bow8kHew.js.map +1 -0
  67. package/dist/main.cjs +16 -15
  68. package/dist/main.cjs.map +1 -1
  69. package/dist/main.js +31 -22
  70. package/dist/main.js.map +1 -1
  71. package/dist/node.js +37 -363
  72. package/dist/node.js.map +1 -1
  73. package/dist/{ownership-C17YhE7J.js → ownership-BF_ZUKIp.js} +13 -9
  74. package/dist/{ownership-C17YhE7J.js.map → ownership-BF_ZUKIp.js.map} +1 -1
  75. package/dist/platform.browser.js +3499 -0
  76. package/dist/platform.browser.js.map +1 -0
  77. package/dist/platform.node.js +19 -0
  78. package/dist/platform.node.js.map +1 -0
  79. package/dist/{property-CRAau-Q-.js → property-BdyDfcSc.js} +14 -11
  80. package/dist/property-BdyDfcSc.js.map +1 -0
  81. package/dist/src/Item/Item.d.ts.map +1 -1
  82. package/dist/src/Item/service/actors/fetchDataFromEas.d.ts.map +1 -1
  83. package/dist/src/Model/service/actors/createModelProperties.d.ts.map +1 -1
  84. package/dist/src/Model/service/modelMachine.d.ts +1 -1
  85. package/dist/src/browser/db/Db.d.ts +17 -18
  86. package/dist/src/browser/db/Db.d.ts.map +1 -1
  87. package/dist/src/browser/helpers/ArweaveClient.d.ts +10 -27
  88. package/dist/src/browser/helpers/ArweaveClient.d.ts.map +1 -1
  89. package/dist/src/browser/helpers/EasClient.d.ts +6 -4
  90. package/dist/src/browser/helpers/EasClient.d.ts.map +1 -1
  91. package/dist/src/browser/helpers/FileManager.d.ts +27 -26
  92. package/dist/src/browser/helpers/FileManager.d.ts.map +1 -1
  93. package/dist/src/browser/helpers/PathResolver.d.ts +6 -5
  94. package/dist/src/browser/helpers/PathResolver.d.ts.map +1 -1
  95. package/dist/src/browser/helpers/QueryClient.d.ts +6 -5
  96. package/dist/src/browser/helpers/QueryClient.d.ts.map +1 -1
  97. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  98. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  99. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  100. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  101. package/dist/src/db/Db/BaseDb.d.ts +6 -26
  102. package/dist/src/db/Db/BaseDb.d.ts.map +1 -1
  103. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  104. package/dist/src/db/write/createMetadata.d.ts.map +1 -1
  105. package/dist/src/db/write/updateMetadata.d.ts.map +1 -1
  106. package/dist/src/eas.d.ts +4 -37
  107. package/dist/src/eas.d.ts.map +1 -1
  108. package/dist/src/helpers/ArweaveClient/BaseArweaveClient.d.ts +1 -101
  109. package/dist/src/helpers/ArweaveClient/BaseArweaveClient.d.ts.map +1 -1
  110. package/dist/src/helpers/ArweaveClient/arweaveL1UploadApi.d.ts +1 -51
  111. package/dist/src/helpers/ArweaveClient/arweaveL1UploadApi.d.ts.map +1 -1
  112. package/dist/src/helpers/ArweaveClient/index.d.ts +2 -2
  113. package/dist/src/helpers/ArweaveClient/index.d.ts.map +1 -1
  114. package/dist/src/helpers/ArweaveClient/selectReadGateway.d.ts +1 -15
  115. package/dist/src/helpers/ArweaveClient/selectReadGateway.d.ts.map +1 -1
  116. package/dist/src/helpers/ArweaveClient/uploadApiVerification.d.ts +1 -22
  117. package/dist/src/helpers/ArweaveClient/uploadApiVerification.d.ts.map +1 -1
  118. package/dist/src/helpers/EasClient/BaseEasClient.d.ts +1 -9
  119. package/dist/src/helpers/EasClient/BaseEasClient.d.ts.map +1 -1
  120. package/dist/src/helpers/FileManager/BaseFileManager.d.ts +4 -2
  121. package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  122. package/dist/src/helpers/FileManager/IFileManager.d.ts +44 -0
  123. package/dist/src/helpers/FileManager/IFileManager.d.ts.map +1 -0
  124. package/dist/src/helpers/PathResolver/BasePathResolver.d.ts +16 -12
  125. package/dist/src/helpers/PathResolver/BasePathResolver.d.ts.map +1 -1
  126. package/dist/src/helpers/PathResolver/IPathResolver.d.ts +16 -0
  127. package/dist/src/helpers/PathResolver/IPathResolver.d.ts.map +1 -0
  128. package/dist/src/helpers/QueryClient/BaseQueryClient.d.ts +1 -6
  129. package/dist/src/helpers/QueryClient/BaseQueryClient.d.ts.map +1 -1
  130. package/dist/src/helpers/constants.d.ts +4 -22
  131. package/dist/src/helpers/constants.d.ts.map +1 -1
  132. package/dist/src/helpers/db.d.ts.map +1 -1
  133. package/dist/src/helpers/easPropertyCanonical.d.ts +1 -14
  134. package/dist/src/helpers/easPropertyCanonical.d.ts.map +1 -1
  135. package/dist/src/helpers/easRevokedFilter.d.ts +1 -9
  136. package/dist/src/helpers/easRevokedFilter.d.ts.map +1 -1
  137. package/dist/src/helpers/easUid.d.ts +1 -12
  138. package/dist/src/helpers/easUid.d.ts.map +1 -1
  139. package/dist/src/helpers/ethereumUtils.d.ts +5 -0
  140. package/dist/src/helpers/ethereumUtils.d.ts.map +1 -0
  141. package/dist/src/helpers/file/fetchAll/index.d.ts +1 -1
  142. package/dist/src/helpers/file/fetchAll/index.d.ts.map +1 -1
  143. package/dist/src/helpers/gateway/gatewayState.d.ts +2 -0
  144. package/dist/src/helpers/gateway/gatewayState.d.ts.map +1 -0
  145. package/dist/src/helpers/gateway/resolveSeedGatewayEndpoints.d.ts +2 -0
  146. package/dist/src/helpers/gateway/resolveSeedGatewayEndpoints.d.ts.map +1 -0
  147. package/dist/src/helpers/gateway/seedGatewayConfig.d.ts +2 -0
  148. package/dist/src/helpers/gateway/seedGatewayConfig.d.ts.map +1 -0
  149. package/dist/src/helpers/generateId.d.ts +2 -0
  150. package/dist/src/helpers/generateId.d.ts.map +1 -0
  151. package/dist/src/helpers/getSchemaForItemProperty.d.ts +1 -1
  152. package/dist/src/helpers/getSchemaForItemProperty.d.ts.map +1 -1
  153. package/dist/src/helpers/getSegmentedItemProperties.d.ts.map +1 -1
  154. package/dist/src/helpers/index.d.ts +15 -10
  155. package/dist/src/helpers/index.d.ts.map +1 -1
  156. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts +7 -0
  157. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts.map +1 -0
  158. package/dist/src/helpers/mediaRef.d.ts.map +1 -1
  159. package/dist/src/helpers/property/index.d.ts.map +1 -1
  160. package/dist/src/index.d.ts +9 -7
  161. package/dist/src/index.d.ts.map +1 -1
  162. package/dist/src/interfaces/IDb.d.ts +11 -0
  163. package/dist/src/interfaces/IDb.d.ts.map +1 -1
  164. package/dist/src/node/db/Db.d.ts +22 -37
  165. package/dist/src/node/db/Db.d.ts.map +1 -1
  166. package/dist/src/node/helpers/ArweaveClient.d.ts +4 -30
  167. package/dist/src/node/helpers/ArweaveClient.d.ts.map +1 -1
  168. package/dist/src/node/helpers/EasClient.d.ts +4 -6
  169. package/dist/src/node/helpers/EasClient.d.ts.map +1 -1
  170. package/dist/src/node/helpers/FileManager.d.ts +26 -25
  171. package/dist/src/node/helpers/FileManager.d.ts.map +1 -1
  172. package/dist/src/node/helpers/PathResolver.d.ts +6 -5
  173. package/dist/src/node/helpers/PathResolver.d.ts.map +1 -1
  174. package/dist/src/node/helpers/QueryClient.d.ts +4 -6
  175. package/dist/src/node/helpers/QueryClient.d.ts.map +1 -1
  176. package/dist/src/node/helpers/scripts.d.ts +5 -7
  177. package/dist/src/node/helpers/scripts.d.ts.map +1 -1
  178. package/dist/src/node/index.d.ts +2 -9
  179. package/dist/src/node/index.d.ts.map +1 -1
  180. package/dist/src/node/webpack/index.d.ts +1 -1
  181. package/dist/src/node/webpack/index.d.ts.map +1 -1
  182. package/dist/src/platform/configurePlatform.d.ts +6 -0
  183. package/dist/src/platform/configurePlatform.d.ts.map +1 -0
  184. package/dist/src/platform/index.browser.d.ts +3 -0
  185. package/dist/src/platform/index.browser.d.ts.map +1 -0
  186. package/dist/src/platform/index.d.ts +9 -0
  187. package/dist/src/platform/index.d.ts.map +1 -0
  188. package/dist/src/platform/index.node.d.ts +3 -0
  189. package/dist/src/platform/index.node.d.ts.map +1 -0
  190. package/dist/src/platform/types.d.ts +14 -0
  191. package/dist/src/platform/types.d.ts.map +1 -0
  192. package/dist/src/stores/eas.d.ts +1 -18
  193. package/dist/src/stores/eas.d.ts.map +1 -1
  194. package/dist/src/testing/platformTestHandle.d.ts +8 -0
  195. package/dist/src/testing/platformTestHandle.d.ts.map +1 -0
  196. package/dist/src/types/gateway.d.ts +2 -0
  197. package/dist/src/types/gateway.d.ts.map +1 -0
  198. package/dist/src/types/index.d.ts +5 -0
  199. package/dist/src/types/index.d.ts.map +1 -1
  200. package/dist/src/types/item.d.ts +1 -1
  201. package/dist/src/types/item.d.ts.map +1 -1
  202. package/dist/src/types/machines.d.ts +10 -0
  203. package/dist/src/types/machines.d.ts.map +1 -1
  204. package/dist/src/types/seedProtocol.d.ts +1 -1
  205. package/dist/src/types/seedProtocol.d.ts.map +1 -1
  206. package/dist/src/vite/index.d.ts +2 -47
  207. package/dist/src/vite/index.d.ts.map +1 -1
  208. package/dist/{syncDbWithEas-CB5aXPtf.js → syncDbWithEas-DMOJHtkP.js} +20 -15
  209. package/dist/syncDbWithEas-DMOJHtkP.js.map +1 -0
  210. package/dist/{updateSeedRevokedAt-BIu5Q4Po.js → updateSeedRevokedAt-Ba0OhDQj.js} +2 -2
  211. package/dist/{updateSeedRevokedAt-BIu5Q4Po.js.map → updateSeedRevokedAt-Ba0OhDQj.js.map} +1 -1
  212. package/dist/vite.cjs +5 -481
  213. package/dist/vite.cjs.map +1 -1
  214. package/dist/vite.js +1 -483
  215. package/dist/vite.js.map +1 -1
  216. package/package.json +42 -37
  217. package/dist/ArweaveClient-CZpZgmR2.js +0 -204
  218. package/dist/ArweaveClient-CZpZgmR2.js.map +0 -1
  219. package/dist/ArweaveClient-Cs7AL9dp.js +0 -204
  220. package/dist/ArweaveClient-Cs7AL9dp.js.map +0 -1
  221. package/dist/Db-CF6R7HIy.js +0 -2098
  222. package/dist/Db-CF6R7HIy.js.map +0 -1
  223. package/dist/Db-CZkONsdT.js +0 -248
  224. package/dist/Db-CZkONsdT.js.map +0 -1
  225. package/dist/EasClient-PXOzSzPG.js +0 -29
  226. package/dist/EasClient-PXOzSzPG.js.map +0 -1
  227. package/dist/EasClient-qfTiM2we.js +0 -29
  228. package/dist/EasClient-qfTiM2we.js.map +0 -1
  229. package/dist/FileManager-5GkHtxF7.js +0 -1256
  230. package/dist/FileManager-5GkHtxF7.js.map +0 -1
  231. package/dist/FileManager-jORQ8Bb6.js +0 -177
  232. package/dist/FileManager-jORQ8Bb6.js.map +0 -1
  233. package/dist/ModelProperty-e_hXSFvf.js.map +0 -1
  234. package/dist/PathResolver-B4_X69Rd.js +0 -204
  235. package/dist/PathResolver-B4_X69Rd.js.map +0 -1
  236. package/dist/PathResolver-Dz0RVGIz.js +0 -78
  237. package/dist/PathResolver-Dz0RVGIz.js.map +0 -1
  238. package/dist/QueryClient-CXHZ239d.js +0 -51
  239. package/dist/QueryClient-CXHZ239d.js.map +0 -1
  240. package/dist/QueryClient-D_UK4YLm.js +0 -35
  241. package/dist/QueryClient-D_UK4YLm.js.map +0 -1
  242. package/dist/arweave-default-shim.js +0 -6
  243. package/dist/cjs/getPublishPayload-CGKMEL3H.js.map +0 -1
  244. package/dist/cjs/getSegmentedItemProperties-BgS_FhAx.js.map +0 -1
  245. package/dist/cjs/index-BnAqr2le.js.map +0 -1
  246. package/dist/cjs/index-ByozbTn_.js.map +0 -1
  247. package/dist/cjs/syncDbWithEas-CA2Lum5V.js.map +0 -1
  248. package/dist/debug-default-shim.js +0 -27
  249. package/dist/getPublishPayload-D16enahU.js.map +0 -1
  250. package/dist/getSegmentedItemProperties-Be3kYWY3.js.map +0 -1
  251. package/dist/index-BFyMxc7e.js.map +0 -1
  252. package/dist/index-BcXKZQpX.js.map +0 -1
  253. package/dist/index-C9p-skT3.js +0 -18
  254. package/dist/index-C9p-skT3.js.map +0 -1
  255. package/dist/property-CRAau-Q-.js.map +0 -1
  256. package/dist/queries-Ct7CcQ3g.js +0 -16
  257. package/dist/queries-Ct7CcQ3g.js.map +0 -1
  258. package/dist/src/Item/queries.d.ts +0 -27
  259. package/dist/src/Item/queries.d.ts.map +0 -1
  260. package/dist/src/graphql/fragments/Attestation.d.ts +0 -2
  261. package/dist/src/graphql/fragments/Attestation.d.ts.map +0 -1
  262. package/dist/src/graphql/fragments/Schema.d.ts +0 -2
  263. package/dist/src/graphql/fragments/Schema.d.ts.map +0 -1
  264. package/dist/src/graphql/fragments/index.d.ts +0 -3
  265. package/dist/src/graphql/fragments/index.d.ts.map +0 -1
  266. package/dist/src/graphql/gql/fragment-masking.d.ts +0 -20
  267. package/dist/src/graphql/gql/fragment-masking.d.ts.map +0 -1
  268. package/dist/src/graphql/gql/gql.d.ts +0 -107
  269. package/dist/src/graphql/gql/gql.d.ts.map +0 -1
  270. package/dist/src/graphql/gql/graphql.d.ts +0 -2969
  271. package/dist/src/graphql/gql/graphql.d.ts.map +0 -1
  272. package/dist/src/graphql/gql/index.d.ts +0 -3
  273. package/dist/src/graphql/gql/index.d.ts.map +0 -1
  274. package/dist/src/helpers/ArweaveClient/queries.d.ts +0 -13
  275. package/dist/src/helpers/ArweaveClient/queries.d.ts.map +0 -1
  276. package/dist/src/helpers/file/queries.d.ts +0 -9
  277. package/dist/src/helpers/file/queries.d.ts.map +0 -1
  278. package/dist/src/helpers/image/queries.d.ts +0 -7
  279. package/dist/src/helpers/image/queries.d.ts.map +0 -1
  280. package/dist/src/node/codegen/drizzle.d.ts +0 -5
  281. package/dist/src/node/codegen/drizzle.d.ts.map +0 -1
  282. package/dist/src/node/codegen/index.d.ts +0 -2
  283. package/dist/src/node/codegen/index.d.ts.map +0 -1
  284. package/dist/src/node/codegen/ts-to-proto.d.ts +0 -9
  285. package/dist/src/node/codegen/ts-to-proto.d.ts.map +0 -1
  286. package/dist/src/node/db/node.app.db.config.d.ts +0 -4
  287. package/dist/src/node/db/node.app.db.config.d.ts.map +0 -1
  288. package/dist/src/node/helpers/index.d.ts +0 -3
  289. package/dist/src/node/helpers/index.d.ts.map +0 -1
  290. package/dist/src/vite/arweave-default-shim.d.ts +0 -4
  291. package/dist/src/vite/arweave-default-shim.d.ts.map +0 -1
  292. package/dist/src/vite/debug-default-shim.d.ts +0 -3
  293. package/dist/src/vite/debug-default-shim.d.ts.map +0 -1
  294. package/dist/src/vite/easFix.d.ts +0 -2
  295. package/dist/src/vite/easFix.d.ts.map +0 -1
  296. package/dist/syncDbWithEas-CB5aXPtf.js.map +0 -1
  297. /package/dist/db/drizzle/{drizzle/0000_married_malice.sql → 0000_married_malice.sql} +0 -0
  298. /package/dist/db/drizzle/{drizzle/0001_sweet_bruce_banner.sql → 0001_sweet_bruce_banner.sql} +0 -0
  299. /package/dist/db/drizzle/{drizzle/0002_bitter_proudstar.sql → 0002_bitter_proudstar.sql} +0 -0
  300. /package/dist/db/drizzle/{drizzle/0003_cultured_senator_kelly.sql → 0003_cultured_senator_kelly.sql} +0 -0
  301. /package/dist/db/drizzle/{drizzle/0004_add_publisher_to_seeds.sql → 0004_add_publisher_to_seeds.sql} +0 -0
  302. /package/dist/db/drizzle/{drizzle/0005_bright_lily_hollister.sql → 0005_bright_lily_hollister.sql} +0 -0
  303. /package/dist/db/drizzle/{drizzle/0006_add_publisher_to_versions_and_metadata.sql → 0006_add_publisher_to_versions_and_metadata.sql} +0 -0
  304. /package/dist/db/drizzle/{drizzle/0007_add_required_to_properties.sql → 0007_add_required_to_properties.sql} +0 -0
  305. /package/dist/db/drizzle/{drizzle/0008_add_revoked_at_to_seeds.sql → 0008_add_revoked_at_to_seeds.sql} +0 -0
  306. /package/dist/db/drizzle/{drizzle/0009_happy_namor.sql → 0009_happy_namor.sql} +0 -0
  307. /package/dist/db/drizzle/{drizzle/0010_add_arweave_l1_finalize_jobs.sql → 0010_add_arweave_l1_finalize_jobs.sql} +0 -0
  308. /package/dist/db/drizzle/{drizzle/0011_normalize_placeholder_uids.sql → 0011_normalize_placeholder_uids.sql} +0 -0
  309. /package/dist/db/drizzle/{drizzle/0012_html_embedded_image_co_publish.sql → 0012_html_embedded_image_co_publish.sql} +0 -0
  310. /package/dist/db/drizzle/{drizzle/0013_eas_sync_processes.sql → 0013_eas_sync_processes.sql} +0 -0
  311. /package/dist/db/drizzle/{drizzle/meta → meta}/0000_snapshot.json +0 -0
  312. /package/dist/db/drizzle/{drizzle/meta → meta}/0001_snapshot.json +0 -0
  313. /package/dist/db/drizzle/{drizzle/meta → meta}/0002_snapshot.json +0 -0
  314. /package/dist/db/drizzle/{drizzle/meta → meta}/0003_snapshot.json +0 -0
  315. /package/dist/db/drizzle/{drizzle/meta → meta}/0004_snapshot.json +0 -0
  316. /package/dist/db/drizzle/{drizzle/meta → meta}/0005_snapshot.json +0 -0
  317. /package/dist/db/drizzle/{drizzle/meta → meta}/0006_snapshot.json +0 -0
  318. /package/dist/db/drizzle/{drizzle/meta → meta}/0007_snapshot.json +0 -0
  319. /package/dist/db/drizzle/{drizzle/meta → meta}/0008_snapshot.json +0 -0
  320. /package/dist/db/drizzle/{drizzle/meta → meta}/0009_snapshot.json +0 -0
  321. /package/dist/db/drizzle/{drizzle/meta → meta}/0010_snapshot.json +0 -0
  322. /package/dist/db/drizzle/{drizzle/meta → meta}/0013_snapshot.json +0 -0
  323. /package/dist/db/drizzle/{drizzle/meta → meta}/_journal.json +0 -0
@@ -0,0 +1,3499 @@
1
+ import { B as BaseDb, b as appState, t as BasePathResolver, a as BaseFileManager } from './BasePathResolver-BDgc7c4T.js';
2
+ import debug from 'debug';
3
+ import { sql } from 'drizzle-orm';
4
+ import { readMigrationFiles } from 'drizzle-orm/migrator';
5
+ import { drizzle } from 'drizzle-orm/sqlite-proxy';
6
+ import { migrate } from 'drizzle-orm/sqlite-proxy/migrator';
7
+ import { E as EAS_ENDPOINT } from './constants-B5S5JPDK.js';
8
+ import { s as schema } from './index-QMrBK-L3.js';
9
+ import { SQLocalDrizzle } from 'sqlocal/drizzle';
10
+ import { Observable, distinctUntilChanged } from 'rxjs';
11
+ import { BaseArweaveClient, GET_TRANSACTION_TAGS } from '@seedprotocol/arweave';
12
+ import { GraphQLClient } from 'graphql-request';
13
+ import Arweave from 'arweave';
14
+ import { BaseEasClient, BaseQueryClient } from '@seedprotocol/eas';
15
+ import { QueryClient } from '@tanstack/react-query';
16
+ import 'drizzle-orm/sqlite-core';
17
+ import 'xstate';
18
+ import 'pluralize';
19
+ import '@sinclair/typebox';
20
+ import 'nanoid';
21
+ import 'nanoid-dictionary';
22
+
23
+ const saveAppState = async (key, value) => {
24
+ const appDb = BaseDb.getAppDb();
25
+ await appDb
26
+ .insert(appState)
27
+ .values({
28
+ key,
29
+ value,
30
+ })
31
+ .onConflictDoUpdate({
32
+ target: appState.key,
33
+ set: {
34
+ value,
35
+ },
36
+ });
37
+ };
38
+
39
+ class BrowserPathResolver {
40
+ /** @deprecated Prefer BasePathResolver static methods or configure(). */
41
+ static getInstance() {
42
+ return BasePathResolver.getInstance();
43
+ }
44
+ /**
45
+ * Gets the root directory containing node_modules
46
+ * Note: In browser, this returns a virtual path based on OPFS
47
+ */
48
+ getRootWithNodeModules() {
49
+ // In browser, we use OPFS which doesn't have traditional paths
50
+ // Return a virtual root path
51
+ return '/';
52
+ }
53
+ /**
54
+ * Gets the SDK root directory
55
+ * Note: In browser, this returns a virtual path
56
+ */
57
+ getSdkRootDir() {
58
+ // In browser, SDK is bundled, so we return a virtual path
59
+ return '/sdk';
60
+ }
61
+ getNodeModulesDir() {
62
+ // In browser, node_modules don't exist in the traditional sense
63
+ return '/node_modules';
64
+ }
65
+ /**
66
+ * Gets the .seed directory path
67
+ * Note: In browser, this returns the OPFS path where .seed data is stored
68
+ */
69
+ getDotSeedDir(schemaFileDir) {
70
+ // In browser, .seed directory is stored in OPFS
71
+ // The actual path is handled by the FileManager
72
+ return '/.seed';
73
+ }
74
+ /**
75
+ * Finds the Seed Protocol config file
76
+ * Note: In browser, config files are not accessible via filesystem
77
+ */
78
+ findConfigFile(searchDir) {
79
+ // In browser, config files are typically embedded in the bundle
80
+ // or loaded via fetch/import
81
+ return null;
82
+ }
83
+ /**
84
+ * Gets paths for app-specific directories
85
+ * Note: In browser, these are virtual paths for OPFS
86
+ */
87
+ getAppPaths(schemaFileDir) {
88
+ const dotSeedDir = this.getDotSeedDir(schemaFileDir);
89
+ return {
90
+ sdkRootDir: this.getSdkRootDir(),
91
+ dotSeedDir,
92
+ nodeModulesDir: this.getNodeModulesDir(),
93
+ appSchemaDir: `${dotSeedDir}/schema`,
94
+ appDbDir: `${dotSeedDir}/db`,
95
+ appMetaDir: `${dotSeedDir}/db/meta`,
96
+ };
97
+ }
98
+ }
99
+ BasePathResolver.configure(new BrowserPathResolver());
100
+
101
+ var filesDownload = `(
102
+ ${function () {
103
+ const identifyString = (str) => {
104
+ try {
105
+ JSON.parse(str);
106
+ return 'json';
107
+ }
108
+ catch (e) {
109
+ // Not JSON
110
+ }
111
+ if (!str) {
112
+ return;
113
+ }
114
+ if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
115
+ return 'html';
116
+ }
117
+ // Simple markdown checks (very naive)
118
+ if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
119
+ return 'markdown';
120
+ }
121
+ if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
122
+ return 'base64';
123
+ }
124
+ // Default to plain text if unsure
125
+ return 'text';
126
+ };
127
+ const getMimeType = (base64) => {
128
+ if (!base64) {
129
+ return null;
130
+ }
131
+ const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
132
+ if (result && result.length > 1) {
133
+ return result[1];
134
+ }
135
+ else {
136
+ return null; // MIME type could not be determined
137
+ }
138
+ };
139
+ const getDataTypeFromString = (data) => {
140
+ const nonImageBase64Regex = /^(?!data:image\/(?:jpeg|png|gif|bmp|webp);base64,)[A-Za-z0-9+/=]+$/;
141
+ if (nonImageBase64Regex.test(data)) {
142
+ return 'base64';
143
+ }
144
+ // Regular expression for base64 (simple version, checking for base64 format)
145
+ const imageBase64Regex = /^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/;
146
+ if (imageBase64Regex.test(data)) {
147
+ return 'imageBase64';
148
+ }
149
+ // Regular expression for URL (simple version, checking for common URL format)
150
+ const urlRegex = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/;
151
+ if (urlRegex.test(data)) {
152
+ return 'url';
153
+ }
154
+ return null;
155
+ };
156
+ const isBinary = (arrayBuffer) => {
157
+ const view = new Uint8Array(arrayBuffer);
158
+ let nonTextCount = 0;
159
+ const threshold = 0.2; // Adjust as needed (e.g., 20% non-text implies binary)
160
+ for (let i = 0; i < view.length; i++) {
161
+ const byte = view[i];
162
+ // ASCII printable characters (32-126) and common whitespace (9, 10, 13)
163
+ if ((byte >= 32 && byte <= 126) || // Printable ASCII
164
+ byte === 9 || byte === 10 || byte === 13 // Tab, LF, CR
165
+ ) {
166
+ continue;
167
+ }
168
+ nonTextCount++;
169
+ if (nonTextCount / view.length > threshold) {
170
+ return true; // More than threshold are non-text bytes
171
+ }
172
+ }
173
+ return false; // Fewer than threshold are non-text bytes
174
+ };
175
+ const saveBufferToOPFS = async (filePath, buffer) => {
176
+ // Access the OPFS root directory
177
+ const rootHandle = await navigator.storage.getDirectory();
178
+ // Split the filePath into directory segments and file name
179
+ const segments = filePath.split('/').filter(Boolean);
180
+ const fileName = segments.pop(); // Extract the file name
181
+ if (!fileName) {
182
+ throw new Error('Invalid file path: No file name provided.');
183
+ }
184
+ // Traverse or create directories as needed
185
+ let currentDirHandle = rootHandle;
186
+ for (const segment of segments) {
187
+ currentDirHandle = await currentDirHandle.getDirectoryHandle(segment, { create: true });
188
+ }
189
+ // Create or open the file in OPFS
190
+ const fileHandleAsync = await currentDirHandle.getFileHandle(fileName, { create: true });
191
+ const fileHandle = await fileHandleAsync.createSyncAccessHandle();
192
+ // Write the buffer to the file
193
+ fileHandle.write(buffer);
194
+ fileHandle.flush();
195
+ fileHandle.close();
196
+ };
197
+ const getFilesPath = (filesRoot, ...parts) => {
198
+ const root = filesRoot.replace(/\/$/, '');
199
+ return [root, ...parts].filter(Boolean).join('/').replace(/\/+/g, '/');
200
+ };
201
+ const downloadFiles = async ({ transactionIds, arweaveHost, filesRoot = '/files', }) => {
202
+ let arrayBuffer;
203
+ for (const transactionId of transactionIds) {
204
+ try {
205
+ const response = await fetch((() => {
206
+ const base = arweaveHost.trim().startsWith('http')
207
+ ? arweaveHost.trim().replace(/\/$/, '')
208
+ : (() => {
209
+ const h = arweaveHost.trim();
210
+ const protocol = h.startsWith('127.0.0.1') || h.startsWith('localhost') || h.includes(':1984')
211
+ ? 'http'
212
+ : 'https';
213
+ return `${protocol}://${h}`;
214
+ })();
215
+ return `${base}/raw/${transactionId}`;
216
+ })());
217
+ arrayBuffer = await response.arrayBuffer();
218
+ }
219
+ catch (error) {
220
+ globalThis.postMessage({
221
+ message: 'excludeTransaction',
222
+ transactionId,
223
+ });
224
+ continue;
225
+ }
226
+ let dataString;
227
+ const isBinaryData = isBinary(arrayBuffer);
228
+ if (!isBinaryData) {
229
+ const decoder = new TextDecoder('utf-8');
230
+ const text = decoder.decode(arrayBuffer);
231
+ dataString = text;
232
+ }
233
+ if (dataString && dataString.startsWith('===FILE_SEPARATOR===')) {
234
+ const dataStringParts = dataString
235
+ .split('===FILE_SEPARATOR===')
236
+ .slice(1);
237
+ if (dataStringParts.length % 2 !== 0) {
238
+ throw new Error('Input array must have an even number of elements.');
239
+ }
240
+ for (let i = 0; i < dataStringParts.length; i += 2) {
241
+ const contentType = dataStringParts[i];
242
+ const content = dataStringParts[i + 1];
243
+ const encoder = new TextEncoder();
244
+ if (contentType === 'html') {
245
+ const fileName = `${transactionId}.html`;
246
+ const buffer = encoder.encode(content);
247
+ saveBufferToOPFS(getFilesPath(filesRoot, 'html', fileName), buffer);
248
+ }
249
+ if (contentType === 'json') {
250
+ const fileName = `${transactionId}.json`;
251
+ const buffer = encoder.encode(content);
252
+ saveBufferToOPFS(getFilesPath(filesRoot, 'json', fileName), buffer);
253
+ }
254
+ }
255
+ continue;
256
+ }
257
+ if (!dataString && arrayBuffer) {
258
+ saveBufferToOPFS(getFilesPath(filesRoot, 'images', transactionId), new Uint8Array(arrayBuffer));
259
+ continue;
260
+ }
261
+ if (!dataString) {
262
+ continue;
263
+ }
264
+ let contentType = identifyString(dataString);
265
+ if (contentType !== 'json' &&
266
+ contentType !== 'base64' &&
267
+ contentType !== 'html') {
268
+ const possibleImageType = getDataTypeFromString(dataString);
269
+ if (!possibleImageType) {
270
+ continue;
271
+ }
272
+ contentType = possibleImageType;
273
+ }
274
+ if (contentType === 'url') {
275
+ const url = dataString;
276
+ let buffer;
277
+ try {
278
+ const response = await fetch(url);
279
+ buffer = await response.arrayBuffer();
280
+ }
281
+ catch (error) {
282
+ globalThis.postMessage({
283
+ message: 'excludeTransaction',
284
+ transactionId,
285
+ });
286
+ continue;
287
+ }
288
+ const bufferUint8Array = new Uint8Array(buffer);
289
+ // Extract the file extension from the URL
290
+ const extensionMatch = url.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i);
291
+ if (!extensionMatch) {
292
+ throw new Error('Unable to determine the file extension from the URL.');
293
+ }
294
+ extensionMatch[0]; // e.g., ".jpg"
295
+ // Set the file name (you can customize this)
296
+ // const fileNameFromUrl = `${transactionId}${fileExtension}`
297
+ await saveBufferToOPFS(getFilesPath(filesRoot, 'images', transactionId), bufferUint8Array);
298
+ continue;
299
+ }
300
+ const mimeType = getMimeType(dataString);
301
+ let fileExtension = mimeType;
302
+ if (fileExtension && fileExtension?.startsWith('image')) {
303
+ fileExtension = fileExtension.replace('image/', '');
304
+ }
305
+ let fileName = transactionId;
306
+ if (contentType === 'base64') {
307
+ if (fileExtension) {
308
+ fileName += `.${fileExtension}`;
309
+ }
310
+ // Remove the Base64 header if it exists (e.g., "data:image/png;base64,")
311
+ const base64Data = dataString.split(',').pop() || '';
312
+ // Decode the Base64 string to binary
313
+ const binaryString = atob(base64Data);
314
+ const length = binaryString.length;
315
+ const binaryData = new Uint8Array(length);
316
+ for (let i = 0; i < length; i++) {
317
+ binaryData[i] = binaryString.charCodeAt(i);
318
+ }
319
+ await saveBufferToOPFS(getFilesPath(filesRoot, 'images', fileName), binaryData);
320
+ }
321
+ if (contentType === 'html') {
322
+ fileName += '.html';
323
+ const encoder = new TextEncoder();
324
+ const buffer = encoder.encode(dataString);
325
+ await saveBufferToOPFS(getFilesPath(filesRoot, 'html', fileName), buffer);
326
+ }
327
+ if (contentType === 'json') {
328
+ fileName += '.json';
329
+ const encoder = new TextEncoder();
330
+ const buffer = encoder.encode(dataString);
331
+ await saveBufferToOPFS(getFilesPath(filesRoot, 'json', fileName), buffer);
332
+ }
333
+ }
334
+ };
335
+ onmessage = async (e) => {
336
+ const { debug, filesRoot } = e.data;
337
+ if (!debug) {
338
+ console.log = () => { };
339
+ }
340
+ await downloadFiles({ ...e.data, filesRoot });
341
+ globalThis.postMessage({
342
+ message: 'filesDownload onmessage done',
343
+ done: true,
344
+ });
345
+ };
346
+ }.toString()}
347
+ )()`;
348
+
349
+ const logger$4 = debug('seedSdk:browser:workers:FileDownloader');
350
+ class FileDownloader {
351
+ constructor() {
352
+ this.workersArchive = [];
353
+ this.downloadAll = async ({ transactionIds, arweaveHost, excludedTransactions }) => {
354
+ if (this.workersArchive.length > 0) {
355
+ for (let i = 0; i < this.workersArchive.length; i++) {
356
+ this.workersArchive[i].terminate();
357
+ delete this.workersArchive[i];
358
+ }
359
+ this.workersArchive = [];
360
+ }
361
+ const worker = new Worker(this.workerBlobUrl);
362
+ this.workersArchive.push(worker);
363
+ const localExcludedTransactions = new Set(excludedTransactions);
364
+ return new Promise((resolve, reject) => {
365
+ worker.onmessage = (e) => {
366
+ logger$4('filesDownload main thread onmessage', e.data);
367
+ if (e.data.message === 'excludeTransaction') {
368
+ localExcludedTransactions.add(e.data.transactionId);
369
+ }
370
+ if (e.data.done) {
371
+ saveAppState('excludedTransactions', JSON.stringify(Array.from(localExcludedTransactions)))
372
+ .then(() => {
373
+ resolve(e.data);
374
+ })
375
+ .catch((error) => {
376
+ reject(error);
377
+ });
378
+ }
379
+ if (e.data.error) {
380
+ reject(e.data.error);
381
+ }
382
+ };
383
+ worker.postMessage({
384
+ transactionIds,
385
+ arweaveHost,
386
+ debug: logger$4.enabled,
387
+ filesRoot: BaseFileManager.getWorkingDir(),
388
+ });
389
+ });
390
+ };
391
+ this.cores = Math.min(navigator.hardwareConcurrency || 4, 4);
392
+ this.workerBlobUrl = globalThis.URL.createObjectURL(new Blob([filesDownload], { type: 'application/javascript' }));
393
+ }
394
+ }
395
+
396
+ var imageResize = `(
397
+ ${function () {
398
+ async function listFilesInDirectory(directoryHandle) {
399
+ const entries = [];
400
+ for await (const [name, handle] of directoryHandle.entries()) {
401
+ entries.push({
402
+ name,
403
+ kind: handle.kind,
404
+ });
405
+ }
406
+ return entries;
407
+ }
408
+ const getFileHandle = async (path, rootHandle = null) => {
409
+ // Split the path into segments
410
+ const segments = path.split('/').filter(Boolean);
411
+ // Start from the root directory if not provided
412
+ if (!rootHandle) {
413
+ rootHandle = await navigator.storage.getDirectory();
414
+ }
415
+ let currentHandle = rootHandle;
416
+ // Traverse the path segments
417
+ for (let i = 0; i < segments.length; i++) {
418
+ const segment = segments[i];
419
+ const isLastSegment = i === segments.length - 1;
420
+ try {
421
+ for await (const [name, handle] of currentHandle.entries()) {
422
+ if (name !== segment) {
423
+ continue;
424
+ }
425
+ if (isLastSegment) {
426
+ if (handle.kind === 'file') {
427
+ return handle; // Return the file handle if found
428
+ }
429
+ else {
430
+ throw new Error(`Path '${path}' refers to a directory, not a file.`);
431
+ }
432
+ }
433
+ else if (handle.kind === 'directory') {
434
+ currentHandle = handle; // Traverse into the directory
435
+ }
436
+ else {
437
+ throw new Error(`Invalid path segment '${segment}'`);
438
+ }
439
+ }
440
+ }
441
+ catch (err) {
442
+ if (err instanceof Error && err.name === 'NotFoundError') {
443
+ throw new Error(`Path '${path}' does not exist.`);
444
+ }
445
+ else {
446
+ throw err;
447
+ }
448
+ }
449
+ }
450
+ throw new Error(`Path '${path}' could not be resolved.`);
451
+ };
452
+ async function getFileFromOPFS(path) {
453
+ const fileHandleAsync = await getFileHandle(path);
454
+ const file = await fileHandleAsync.getFile();
455
+ return file;
456
+ }
457
+ /** Infer MIME from magic bytes. OPFS File may have empty type, causing createImageBitmap to fail. */
458
+ async function getBlobWithInferredMime(file) {
459
+ const buf = await file.arrayBuffer();
460
+ const bytes = new Uint8Array(buf);
461
+ let mime = file.type;
462
+ if (!mime || mime === '') {
463
+ if (bytes[0] === 0xff && bytes[1] === 0xd8)
464
+ mime = 'image/jpeg';
465
+ else if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)
466
+ mime = 'image/png';
467
+ else if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x52 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50)
468
+ mime = 'image/webp';
469
+ else if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46)
470
+ mime = 'image/gif';
471
+ else if (bytes[0] === 0x42 && bytes[1] === 0x4d)
472
+ mime = 'image/bmp';
473
+ else if (bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70 && bytes[8] === 0x61 && bytes[9] === 0x76 && bytes[10] === 0x69 && bytes[11] === 0x66)
474
+ mime = 'image/avif';
475
+ else if (bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70 && bytes[8] === 0x68 && bytes[9] === 0x65 && bytes[10] === 0x69 && bytes[11] === 0x63)
476
+ mime = 'image/heic';
477
+ else
478
+ mime = 'image/jpeg';
479
+ }
480
+ return new Blob([buf], { type: mime });
481
+ }
482
+ const DEFAULT_CONFIG = {
483
+ argorithm: 'null',
484
+ processByHalf: true,
485
+ quality: 0.5,
486
+ maxWidth: 800,
487
+ maxHeight: 600,
488
+ debug: false,
489
+ mimeType: 'image/jpeg',
490
+ };
491
+ function isIos() {
492
+ if (typeof navigator === 'undefined')
493
+ return false;
494
+ if (!navigator.userAgent)
495
+ return false;
496
+ return /iPad|iPhone|iPod/.test(navigator.userAgent);
497
+ }
498
+ const getTargetHeight = (srcHeight, scale, config) => {
499
+ return Math.min(Math.floor(srcHeight * scale), config.maxHeight);
500
+ };
501
+ const findMaxWidth = (config, canvas) => {
502
+ //Let's find the max available width for scaled image
503
+ const ratio = canvas.width / canvas.height;
504
+ let mWidth = Math.min(canvas.width, config.maxWidth, ratio * config.maxHeight);
505
+ if (config.maxSize &&
506
+ config.maxSize > 0 &&
507
+ config.maxSize < (canvas.width * canvas.height) / 1000)
508
+ mWidth = Math.min(mWidth, Math.floor((config.maxSize * 1000) / canvas.height));
509
+ if (!!config.scaleRatio)
510
+ mWidth = Math.min(mWidth, Math.floor(config.scaleRatio * canvas.width));
511
+ const rHeight = getTargetHeight(canvas.height, mWidth / canvas.width, config);
512
+ // console.log(
513
+ // 'browser-image-resizer: original image size = ' +
514
+ // canvas.width +
515
+ // ' px (width) X ' +
516
+ // canvas.height +
517
+ // ' px (height)'
518
+ // );
519
+ // console.log(
520
+ // 'browser-image-resizer: scaled image size = ' +
521
+ // mWidth +
522
+ // ' px (width) X ' +
523
+ // rHeight +
524
+ // ' px (height)'
525
+ // );
526
+ if (mWidth <= 0) {
527
+ mWidth = 1;
528
+ console.warn("browser-image-resizer: image size is too small");
529
+ }
530
+ if (isIos() && mWidth * rHeight > 167777216) {
531
+ console.error("browser-image-resizer: image size is too large for iOS WebKit.", mWidth, rHeight);
532
+ throw new Error("browser-image-resizer: image size is too large for iOS WebKit.");
533
+ }
534
+ return mWidth;
535
+ };
536
+ /**
537
+ * Hermite resize, multicore version - fast image resize/resample using Hermite filter.
538
+ */
539
+ const resample = (srcCanvas, destCanvas, config) => {
540
+ return new Promise((resolve, reject) => {
541
+ const ratio_h = srcCanvas.height / destCanvas.height;
542
+ const cores = Math.min(navigator.hardwareConcurrency || 4, 4);
543
+ //prepare source and target data for workers
544
+ const ctx = srcCanvas.getContext('2d');
545
+ if (!ctx)
546
+ return reject('Canvas is empty (resample)');
547
+ const data_part = [];
548
+ const block_height = Math.ceil(srcCanvas.height / cores / 2) * 2;
549
+ let end_y = -1;
550
+ for (let c = 0; c < cores; c++) {
551
+ //source
552
+ const offset_y = end_y + 1;
553
+ if (offset_y >= srcCanvas.height) {
554
+ //size too small, nothing left for this core
555
+ continue;
556
+ }
557
+ end_y = Math.min(offset_y + block_height - 1, srcCanvas.height - 1);
558
+ const current_block_height = Math.min(block_height, srcCanvas.height - offset_y);
559
+ data_part.push({
560
+ source: ctx.getImageData(0, offset_y, srcCanvas.width, block_height),
561
+ startY: Math.ceil(offset_y / ratio_h),
562
+ height: current_block_height
563
+ });
564
+ }
565
+ //start
566
+ const destCtx = destCanvas.getContext('2d');
567
+ if (!destCtx)
568
+ return reject('Canvas is empty (resample dest)');
569
+ for (let c = 0; c < data_part.length; c++) {
570
+ //draw
571
+ const height_part = Math.ceil(data_part[c].height / ratio_h);
572
+ const target = destCtx.createImageData(destCanvas.width, height_part);
573
+ // target.data.set(event.data.target);
574
+ destCtx.putImageData(target, 0, data_part[c].startY);
575
+ }
576
+ });
577
+ };
578
+ /**
579
+ * Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
580
+ */
581
+ const resampleSingle = (srcCanvasData, destCanvasData) => {
582
+ const ratio_w = srcCanvasData.width / destCanvasData.width;
583
+ const ratio_h = srcCanvasData.height / destCanvasData.height;
584
+ const ratio_w_half = Math.ceil(ratio_w / 2);
585
+ const ratio_h_half = Math.ceil(ratio_h / 2);
586
+ const data = srcCanvasData.data;
587
+ const data2 = destCanvasData.data;
588
+ for (let j = 0; j < destCanvasData.height; j++) {
589
+ for (let i = 0; i < destCanvasData.width; i++) {
590
+ const x2 = (i + j * destCanvasData.width) * 4;
591
+ let weight = 0;
592
+ let weights = 0;
593
+ let weights_alpha = 0;
594
+ let gx_r = 0;
595
+ let gx_g = 0;
596
+ let gx_b = 0;
597
+ let gx_a = 0;
598
+ const center_y = j * ratio_h;
599
+ const xx_start = Math.floor(i * ratio_w);
600
+ const xx_stop = Math.min(Math.ceil((i + 1) * ratio_w), srcCanvasData.width);
601
+ const yy_start = Math.floor(j * ratio_h);
602
+ const yy_stop = Math.min(Math.ceil((j + 1) * ratio_h), srcCanvasData.height);
603
+ for (let yy = yy_start; yy < yy_stop; yy++) {
604
+ let dy = Math.abs(center_y - yy) / ratio_h_half;
605
+ let center_x = i * ratio_w;
606
+ let w0 = dy * dy; //pre-calc part of w
607
+ for (let xx = xx_start; xx < xx_stop; xx++) {
608
+ let dx = Math.abs(center_x - xx) / ratio_w_half;
609
+ let w = Math.sqrt(w0 + dx * dx);
610
+ if (w >= 1) {
611
+ //pixel too far
612
+ continue;
613
+ }
614
+ //hermite filter
615
+ weight = 2 * w * w * w - 3 * w * w + 1;
616
+ let pos_x = 4 * (xx + yy * srcCanvasData.width);
617
+ //alpha
618
+ gx_a += weight * data[pos_x + 3];
619
+ weights_alpha += weight;
620
+ //colors
621
+ if (data[pos_x + 3] < 255)
622
+ weight = weight * data[pos_x + 3] / 250;
623
+ gx_r += weight * data[pos_x];
624
+ gx_g += weight * data[pos_x + 1];
625
+ gx_b += weight * data[pos_x + 2];
626
+ weights += weight;
627
+ }
628
+ }
629
+ data2[x2] = gx_r / weights;
630
+ data2[x2 + 1] = gx_g / weights;
631
+ data2[x2 + 2] = gx_b / weights;
632
+ data2[x2 + 3] = gx_a / weights_alpha;
633
+ }
634
+ }
635
+ };
636
+ /**
637
+ * Hermite resize. Detect cpu count and use best option for user.
638
+ */
639
+ const resampleAuto = (srcCanvas, destCanvas, config) => {
640
+ if (!!globalThis.Worker && navigator.hardwareConcurrency > 1 && config?.argorithm !== 'hermite_single') {
641
+ //workers supported and we have at least 2 cpu cores - using multithreading
642
+ return resample(srcCanvas, destCanvas);
643
+ }
644
+ else {
645
+ //1 cpu version
646
+ const { srcImgData, destImgData } = getImageData(srcCanvas, destCanvas);
647
+ resampleSingle(srcImgData, destImgData);
648
+ destCanvas.getContext('2d').putImageData(destImgData, 0, 0);
649
+ return;
650
+ }
651
+ };
652
+ async function scaleCanvasWithAlgorithm(canvas, config) {
653
+ const scale = config.outputWidth / canvas.width;
654
+ const scaled = new OffscreenCanvas(Math.floor(config.outputWidth), getTargetHeight(canvas.height, scale, config));
655
+ switch (config.algorithm) {
656
+ case 'hermite': {
657
+ await resampleAuto(canvas, scaled, config);
658
+ break;
659
+ }
660
+ case 'hermite_single': {
661
+ const { srcImgData, destImgData } = getImageData(canvas, scaled);
662
+ resampleSingle(srcImgData, destImgData);
663
+ scaled?.getContext('2d')?.putImageData(destImgData, 0, 0);
664
+ break;
665
+ }
666
+ case 'bilinear': {
667
+ // const { srcImgData, destImgData } = getImageData(canvas, scaled);
668
+ // bilinear(srcImgData, destImgData, scale);
669
+ // scaled?.getContext('2d')?.putImageData(destImgData, 0, 0);
670
+ break;
671
+ }
672
+ default: {
673
+ scaled.getContext('2d')?.drawImage(canvas, 0, 0, scaled.width, scaled.height);
674
+ break;
675
+ }
676
+ }
677
+ return scaled;
678
+ }
679
+ const getHalfScaleCanvas = (src) => {
680
+ const half = new OffscreenCanvas(src.width / 2, src.height / 2);
681
+ half
682
+ ?.getContext('2d')
683
+ ?.drawImage(src, 0, 0, half.width, half.height);
684
+ return half;
685
+ };
686
+ const getImageData = (canvas, scaled) => {
687
+ const srcImgData = canvas
688
+ ?.getContext('2d')
689
+ ?.getImageData(0, 0, canvas.width, canvas.height);
690
+ const destImgData = scaled
691
+ ?.getContext('2d')
692
+ ?.createImageData(scaled.width, scaled.height);
693
+ if (!srcImgData || !destImgData)
694
+ throw Error('Canvas is empty (scaleCanvasWithAlgorithm). You should run this script after the document is ready.');
695
+ return { srcImgData, destImgData };
696
+ };
697
+ async function saveBlobToOPFS(filePath, blob) {
698
+ // Access the OPFS root directory
699
+ const rootHandle = await navigator.storage.getDirectory();
700
+ // Split the filePath into directory segments and file name
701
+ const segments = filePath.split('/').filter(Boolean);
702
+ const fileName = segments.pop(); // Extract the file name
703
+ if (!fileName) {
704
+ throw new Error('Invalid file path: No file name provided.');
705
+ }
706
+ // Traverse or create directories as needed
707
+ let currentDirHandle = rootHandle;
708
+ for (const segment of segments) {
709
+ currentDirHandle = await currentDirHandle.getDirectoryHandle(segment, { create: true });
710
+ }
711
+ // Create or open the file in OPFS
712
+ const fileHandle = await currentDirHandle.getFileHandle(fileName, { create: true });
713
+ // Write the Blob to the file
714
+ const writableStream = await fileHandle.createWritable();
715
+ await writableStream.write(blob);
716
+ await writableStream.close();
717
+ }
718
+ const imageResize = async (filePath, width, height) => {
719
+ const config = {
720
+ ...DEFAULT_CONFIG,
721
+ algorithm: 'hermite_single',
722
+ mimeType: 'image/webp',
723
+ maxWidth: width,
724
+ maxHeight: height,
725
+ };
726
+ const rootHandle = await navigator.storage.getDirectory();
727
+ // List files in the root directory
728
+ await listFilesInDirectory(rootHandle);
729
+ const file = await getFileFromOPFS(filePath);
730
+ const blobWithMime = await getBlobWithInferredMime(file);
731
+ const imageBitmap = await createImageBitmap(blobWithMime);
732
+ let converting;
733
+ if (isIos() && imageBitmap.width * imageBitmap.height > 16777216) {
734
+ const scale = Math.sqrt(16777216 / (imageBitmap.width * imageBitmap.height));
735
+ converting = new OffscreenCanvas(Math.floor(imageBitmap.width * scale), Math.floor(imageBitmap.height * scale));
736
+ converting.getContext('2d')?.drawImage(imageBitmap, 0, 0, converting.width, converting.height);
737
+ }
738
+ else {
739
+ converting = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
740
+ converting.getContext('2d')?.drawImage(imageBitmap, 0, 0);
741
+ }
742
+ const maxWidth = findMaxWidth(config, converting);
743
+ if (!maxWidth) {
744
+ throw Error(`browser-image-resizer: maxWidth is ${maxWidth}!!`);
745
+ }
746
+ while (config.processByHalf && converting.width >= 2 * maxWidth) {
747
+ converting = getHalfScaleCanvas(converting);
748
+ }
749
+ if (converting.width > maxWidth) {
750
+ converting = await scaleCanvasWithAlgorithm(converting, Object.assign(config, { outputWidth: maxWidth }));
751
+ }
752
+ if (config.mimeType === null) {
753
+ return converting;
754
+ }
755
+ const resizedBlob = await converting.convertToBlob({ type: config.mimeType, quality: config.quality });
756
+ const pathSegments = filePath.split('/');
757
+ const fileName = pathSegments.pop();
758
+ if (!fileName) {
759
+ throw Error('Invalid file path: No file name provided.');
760
+ }
761
+ const newSegments = [
762
+ ...pathSegments,
763
+ width,
764
+ ];
765
+ const fileNameParts = fileName.split('.');
766
+ const newFileName = `${fileNameParts[0]}.webp`;
767
+ const newDirPath = newSegments.join('/');
768
+ const newFilePath = `${newDirPath}/${newFileName}`;
769
+ await saveBlobToOPFS(newFilePath, resizedBlob);
770
+ globalThis.postMessage({
771
+ done: true,
772
+ filePath: newFilePath,
773
+ });
774
+ };
775
+ onmessage = async (e) => {
776
+ const { filePath, width, height, debug } = e.data;
777
+ if (!debug) {
778
+ console.log = () => { };
779
+ }
780
+ try {
781
+ await imageResize(filePath, width, height);
782
+ }
783
+ catch (err) {
784
+ globalThis.postMessage({ error: err instanceof Error ? err.message : String(err) });
785
+ }
786
+ };
787
+ }.toString()}
788
+ )()`;
789
+
790
+ const logger$3 = debug('seedSdk:browser:workers:ImageResizer');
791
+ class ImageResizer {
792
+ constructor() {
793
+ this.workersArchive = new Map();
794
+ this.cores = Math.min(navigator.hardwareConcurrency || 4, 4);
795
+ this.workerBlobUrl = globalThis.URL.createObjectURL(new Blob([imageResize], { type: 'application/javascript' }));
796
+ }
797
+ async resize({ filePath, width, height }) {
798
+ if (this.workersArchive.has(filePath)) {
799
+ const savedWorker = this.workersArchive.get(filePath);
800
+ savedWorker?.terminate();
801
+ logger$3('[ImageResizer.resize] Terminated worker for filePath due to incoming request', filePath);
802
+ this.workersArchive.delete(filePath);
803
+ }
804
+ const worker = new Worker(this.workerBlobUrl);
805
+ this.workersArchive.set(filePath, worker);
806
+ return new Promise((resolve, reject) => {
807
+ worker.onmessage = (e) => {
808
+ logger$3('[ImageResizer.resize] main thread onmessage', e.data);
809
+ if (e.data.done) {
810
+ const savedWorker = this.workersArchive.get(filePath);
811
+ savedWorker?.terminate();
812
+ logger$3('[ImageResizer.resize] Terminated worker for filePath due to done', filePath);
813
+ this.workersArchive.delete(filePath);
814
+ resolve(e.data);
815
+ }
816
+ if (e.data.error) {
817
+ reject(e.data.error);
818
+ }
819
+ };
820
+ worker.onerror = (err) => {
821
+ reject(err);
822
+ };
823
+ worker.postMessage({
824
+ filePath,
825
+ width,
826
+ height,
827
+ debug: logger$3.enabled,
828
+ });
829
+ });
830
+ }
831
+ async resizeAll({ width, height }) {
832
+ const fs = await BaseFileManager.getFs();
833
+ const imageDir = BaseFileManager.getFilesPath('images');
834
+ let imageFilesStats = await fs.promises.readdir(imageDir, {
835
+ withFileTypes: true
836
+ });
837
+ imageFilesStats = imageFilesStats.filter((file) => file.isFile());
838
+ const imageFiles = imageFilesStats.map((file) => file.path);
839
+ const widthDir = `${imageDir}/${width}`;
840
+ await BaseFileManager.createDirIfNotExists(widthDir);
841
+ for (const imageFile of imageFiles) {
842
+ const resizedImageExists = await BaseFileManager.pathExists(`${widthDir}/${imageFile}`);
843
+ if (!resizedImageExists) {
844
+ await this.resize({ filePath: `${imageDir}/${imageFile}`, width, height });
845
+ }
846
+ }
847
+ }
848
+ }
849
+
850
+ const logger$2 = debug('seedSdk:browser:helpers:FileManager');
851
+ /**
852
+ * Browser-safe path helpers for SDK virtual file paths.
853
+ * We intentionally avoid Node/CJS path polyfills here to keep browser bundles ESM-safe.
854
+ * Provides the subset of Node path APIs used via BaseFileManager.getPathModule().
855
+ */
856
+ const pathCompat = {
857
+ dirname(filePath) {
858
+ if (!filePath)
859
+ return '.';
860
+ const normalized = filePath.replace(/\\/g, '/');
861
+ if (normalized === '/')
862
+ return '/';
863
+ const trimmed = normalized.endsWith('/') && normalized.length > 1
864
+ ? normalized.slice(0, -1)
865
+ : normalized;
866
+ const lastSlash = trimmed.lastIndexOf('/');
867
+ if (lastSlash === -1)
868
+ return '.';
869
+ if (lastSlash === 0)
870
+ return '/';
871
+ return trimmed.slice(0, lastSlash);
872
+ },
873
+ basename(filePath) {
874
+ if (!filePath)
875
+ return '';
876
+ const normalized = filePath.replace(/\\/g, '/');
877
+ if (normalized === '/')
878
+ return '/';
879
+ const trimmed = normalized.endsWith('/') && normalized.length > 1
880
+ ? normalized.slice(0, -1)
881
+ : normalized;
882
+ const lastSlash = trimmed.lastIndexOf('/');
883
+ return lastSlash === -1 ? trimmed : trimmed.slice(lastSlash + 1);
884
+ },
885
+ isAbsolute(filePath) {
886
+ if (!filePath)
887
+ return false;
888
+ const normalized = filePath.replace(/\\/g, '/');
889
+ return normalized.startsWith('/');
890
+ },
891
+ join(...segments) {
892
+ if (segments.length === 0)
893
+ return '.';
894
+ const joined = segments
895
+ .filter((s) => s != null && s !== '')
896
+ .map((s) => String(s).replace(/\\/g, '/'))
897
+ .join('/');
898
+ return pathCompat.normalize(joined);
899
+ },
900
+ resolve(...segments) {
901
+ // POSIX-like resolve for virtual paths: walk right-to-left until absolute.
902
+ let resolved = '';
903
+ let absolute = false;
904
+ for (let i = segments.length - 1; i >= 0 && !absolute; i--) {
905
+ const segment = segments[i];
906
+ if (segment == null || segment === '')
907
+ continue;
908
+ const normalized = String(segment).replace(/\\/g, '/');
909
+ resolved = resolved ? `${normalized}/${resolved}` : normalized;
910
+ absolute = pathCompat.isAbsolute(normalized);
911
+ }
912
+ // Browser has no process.cwd(); treat unresolved relative paths as root-relative.
913
+ if (!absolute) {
914
+ resolved = `/${resolved}`;
915
+ }
916
+ return pathCompat.normalize(resolved);
917
+ },
918
+ normalize(filePath) {
919
+ if (!filePath)
920
+ return '.';
921
+ const normalized = filePath.replace(/\\/g, '/');
922
+ const absolute = normalized.startsWith('/');
923
+ const parts = normalized.split('/');
924
+ const stack = [];
925
+ for (const part of parts) {
926
+ if (!part || part === '.')
927
+ continue;
928
+ if (part === '..') {
929
+ if (stack.length > 0 && stack[stack.length - 1] !== '..') {
930
+ stack.pop();
931
+ }
932
+ else if (!absolute) {
933
+ stack.push('..');
934
+ }
935
+ continue;
936
+ }
937
+ stack.push(part);
938
+ }
939
+ const result = stack.join('/');
940
+ if (absolute)
941
+ return `/${result}`;
942
+ return result || '.';
943
+ },
944
+ };
945
+ /** OPFS / ZenFS can throw NotReadableError while a file is still settling after write. */
946
+ function isTransientOpfsReadError(error) {
947
+ if (error instanceof DOMException && error.name === 'NotReadableError') {
948
+ return true;
949
+ }
950
+ const message = error instanceof Error ? error.message : String(error);
951
+ // Chromium wording when getFile/read races a writer or stale handle
952
+ if (message.includes('permission problems') && message.includes('reference')) {
953
+ return true;
954
+ }
955
+ return false;
956
+ }
957
+ function sleep(ms) {
958
+ return new Promise((resolve) => setTimeout(resolve, ms));
959
+ }
960
+ class BrowserFileManager {
961
+ constructor() {
962
+ this.zenfsCache = null;
963
+ }
964
+ async getFs() {
965
+ if (!this.zenfsCache) {
966
+ this.zenfsCache = await import('@zenfs/core');
967
+ }
968
+ return this.zenfsCache;
969
+ }
970
+ getFsSync() {
971
+ if (!this.zenfsCache) {
972
+ throw new Error('File system not initialized. Call getFs() or initializeFileSystem() first.');
973
+ }
974
+ return this.zenfsCache;
975
+ }
976
+ async getContentUrlFromPath(path) {
977
+ const fileExists = await this.pathExists(path);
978
+ if (fileExists) {
979
+ const file = await this.readFile(path);
980
+ return URL.createObjectURL(file);
981
+ }
982
+ }
983
+ async initializeFileSystem(workingDir) {
984
+ const zenfs = await this.getFs();
985
+ const zenfsDomMod = await import('@zenfs/dom');
986
+ const { WebAccess } = zenfsDomMod;
987
+ const { configureSingle } = zenfs;
988
+ const handle = await navigator.storage.getDirectory();
989
+ // await configure({
990
+ // mounts: {
991
+ // '/': {
992
+ // backend: WebAccess,
993
+ // handle,
994
+ // },
995
+ // },
996
+ // disableUpdateOnRead: true,
997
+ // onlySyncOnClose: true,
998
+ // })
999
+ await configureSingle({
1000
+ backend: WebAccess,
1001
+ handle,
1002
+ });
1003
+ // Cache is already set in getFs(), so no need to set it again
1004
+ }
1005
+ async downloadAllFiles({ transactionIds, arweaveHost, excludedTransactions, }) {
1006
+ const fileDownloader = new FileDownloader();
1007
+ await fileDownloader.downloadAll({ transactionIds, arweaveHost, excludedTransactions });
1008
+ }
1009
+ async resizeImage({ filePath, width, height }) {
1010
+ const imageResizer = new ImageResizer();
1011
+ await imageResizer.resize({ filePath, width, height });
1012
+ }
1013
+ async resizeAllImages({ width, height }) {
1014
+ const imageResizer = new ImageResizer();
1015
+ await imageResizer.resizeAll({ width, height });
1016
+ }
1017
+ async listImageFiles() {
1018
+ return this.listFiles('images');
1019
+ }
1020
+ async listFiles(dir) {
1021
+ const targetDir = BaseFileManager.getFilesPath(dir);
1022
+ const exists = await this.pathExists(targetDir);
1023
+ if (!exists) {
1024
+ return [];
1025
+ }
1026
+ const zenfs = await this.getFs();
1027
+ const entries = await zenfs.promises.readdir(targetDir, { withFileTypes: true });
1028
+ return entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
1029
+ }
1030
+ async pathExists(filePath) {
1031
+ try {
1032
+ const zenfs = await this.getFs();
1033
+ await zenfs.promises.access(filePath, zenfs.constants.F_OK);
1034
+ return true;
1035
+ }
1036
+ catch (error) {
1037
+ // ENOENT means the file doesn't exist, which is expected
1038
+ if (error?.code === 'ENOENT' || error?.errno === -2) {
1039
+ return false;
1040
+ }
1041
+ // For other errors, re-throw them
1042
+ throw error;
1043
+ }
1044
+ }
1045
+ async createDirIfNotExists(filePath) {
1046
+ if (!(await this.pathExists(filePath))) {
1047
+ try {
1048
+ const zenfs = await this.getFs();
1049
+ await zenfs.promises.mkdir(filePath, { recursive: true });
1050
+ }
1051
+ catch (error) {
1052
+ // This is a no-op. We tried to create a directory that already exists.
1053
+ logger$2('Attempted to create a directory that already exists');
1054
+ }
1055
+ }
1056
+ }
1057
+ /**
1058
+ * Waits for a file to exist at the specified path.
1059
+ * @param {string} filePath - The path of the file to check.
1060
+ * @param {number} interval - The interval in milliseconds between checks (default: 500ms).
1061
+ * @param {number} timeout - The timeout in milliseconds to wait for the file to exist (default: 10s).
1062
+ * @returns {Promise<boolean>} - Resolves to true if the file exists within the timeout period, otherwise false.
1063
+ */
1064
+ async waitForFile(filePath, interval = 1000, timeout = 60000) {
1065
+ // const fs = await this.getFs()
1066
+ // const fsNode = await import('node:fs')
1067
+ const pathExists = await this.pathExists(filePath);
1068
+ if (pathExists) {
1069
+ return true;
1070
+ }
1071
+ return new Promise((resolve, reject) => {
1072
+ const startTime = Date.now();
1073
+ let isBusy = false;
1074
+ const cancelableInterval = new CancelableInterval(async (stop) => {
1075
+ logger$2('waitForFile', filePath);
1076
+ if (isBusy) {
1077
+ return;
1078
+ }
1079
+ isBusy = true;
1080
+ // // TODO: Needs to read from OPFS
1081
+ // const exists = await BaseFileManager.pathExists(filePath)
1082
+ // if (exists) {
1083
+ // stop()
1084
+ // resolve(true)
1085
+ // }
1086
+ const pathExists = await this.pathExists(filePath);
1087
+ if (pathExists) {
1088
+ stop();
1089
+ resolve(true);
1090
+ }
1091
+ if (Date.now() - startTime >= timeout) {
1092
+ stop();
1093
+ reject(new Error('Timeout exceeded while waiting for file'));
1094
+ }
1095
+ isBusy = false;
1096
+ }, interval);
1097
+ cancelableInterval.start();
1098
+ // const _interval = setInterval(async () => {
1099
+ // logger('waitForFile', filePath)
1100
+ // if (isBusy) {
1101
+ // return
1102
+ // }
1103
+ // isBusy = true
1104
+ // // TODO: Needs to read from OPFS
1105
+ // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {
1106
+ // clearInterval(_interval)
1107
+ // resolve(true)
1108
+ // }
1109
+ // const pathExists = await this.pathExists(filePath)
1110
+ // if (pathExists) {
1111
+ // clearInterval(_interval)
1112
+ // resolve(true)
1113
+ // }
1114
+ // if (Date.now() - startTime >= timeout) {
1115
+ // clearInterval(_interval)
1116
+ // reject(new Error('Timeout exceeded while waiting for file'))
1117
+ // }
1118
+ // isBusy = false
1119
+ // }, interval)
1120
+ // retry(
1121
+ // {
1122
+ // times: Math.ceil(timeout / interval),
1123
+ // interval: interval,
1124
+ // },
1125
+ // (callback: Function) => {
1126
+ // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {
1127
+ // return callback(null, true) // File exists, finish with success
1128
+ // }
1129
+ // if (Date.now() - startTime >= timeout) {
1130
+ // return callback(new Error('Timeout exceeded while waiting for file'))
1131
+ // }
1132
+ // callback(new Error('File does not exist yet')) // Retry with this error
1133
+ // },
1134
+ // (err: Error, result: boolean) => {
1135
+ // if (err) {
1136
+ // return resolve(false) // Resolve as false if timeout or error occurs
1137
+ // }
1138
+ // resolve(result) // Resolve as true if file exists
1139
+ // },
1140
+ // )
1141
+ });
1142
+ }
1143
+ /**
1144
+ * Waits for a file to exist and have content (non-zero size).
1145
+ * This is important for browser/OPFS where writes may not be immediately readable.
1146
+ * @param {string} filePath - The path of the file to check.
1147
+ * @param {number} interval - The interval in milliseconds between checks (default: 100ms).
1148
+ * @param {number} timeout - The timeout in milliseconds to wait (default: 5s).
1149
+ * @returns {Promise<boolean>} - Resolves to true if the file exists with content within the timeout period.
1150
+ */
1151
+ async waitForFileWithContent(filePath, interval = 100, timeout = 5000) {
1152
+ // First wait for file to exist
1153
+ await this.waitForFile(filePath, interval, timeout);
1154
+ // Now wait for file to have content
1155
+ return new Promise((resolve, reject) => {
1156
+ const startTime = Date.now();
1157
+ let isBusy = false;
1158
+ const cancelableInterval = new CancelableInterval(async (stop) => {
1159
+ logger$2('waitForFileWithContent', filePath);
1160
+ if (isBusy) {
1161
+ return;
1162
+ }
1163
+ isBusy = true;
1164
+ try {
1165
+ // Try to read the file to check if it has content
1166
+ const file = await this.readFile(filePath);
1167
+ if (file.size > 0) {
1168
+ stop();
1169
+ resolve(true);
1170
+ return;
1171
+ }
1172
+ // File exists but is 0 bytes, continue waiting
1173
+ }
1174
+ catch (error) {
1175
+ // If error is about file being 0 bytes, not readable, or I/O error, continue waiting
1176
+ const errorMessage = error?.message || String(error);
1177
+ if (errorMessage.includes('0 bytes') ||
1178
+ errorMessage.includes('ENOENT') ||
1179
+ errorMessage.includes('EIO') ||
1180
+ errorMessage.includes('Input/output error') ||
1181
+ isTransientOpfsReadError(error)) ;
1182
+ else {
1183
+ // Other errors should be thrown
1184
+ stop();
1185
+ reject(error);
1186
+ return;
1187
+ }
1188
+ }
1189
+ if (Date.now() - startTime >= timeout) {
1190
+ stop();
1191
+ reject(new Error(`Timeout exceeded while waiting for file ${filePath} to have content`));
1192
+ return;
1193
+ }
1194
+ isBusy = false;
1195
+ }, interval);
1196
+ cancelableInterval.start();
1197
+ });
1198
+ }
1199
+ async saveFile(filePath, content) {
1200
+ const zenfs = await this.getFs();
1201
+ // Convert content to a format that zenfs.writeFile accepts
1202
+ let writeContent;
1203
+ if (typeof content === 'string') {
1204
+ writeContent = content;
1205
+ }
1206
+ else if (content instanceof Blob) {
1207
+ const arrayBuffer = await content.arrayBuffer();
1208
+ writeContent = new Uint8Array(arrayBuffer);
1209
+ }
1210
+ else if (content instanceof ArrayBuffer) {
1211
+ writeContent = new Uint8Array(content);
1212
+ }
1213
+ else {
1214
+ throw new Error('Unsupported content type');
1215
+ }
1216
+ await zenfs.writeFile(filePath, writeContent);
1217
+ await this.waitForFileWithContent(filePath, 100, 5000);
1218
+ // try {
1219
+ // // Get a handle to the OPFS root directory
1220
+ // const root = await navigator.storage.getDirectory();
1221
+ // // Split the file path into directory and file name
1222
+ // const pathParts = filePath.split('/');
1223
+ // const fileName = pathParts.pop();
1224
+ // if (!fileName) throw new Error('Invalid file path');
1225
+ // // Traverse directories and create them if they don't exist
1226
+ // let currentDir = root;
1227
+ // for (const part of pathParts) {
1228
+ // if (part !== '') {
1229
+ // currentDir = await currentDir.getDirectoryHandle(part, { create: true });
1230
+ // }
1231
+ // }
1232
+ // // Get the file handle and create the file if it doesn't exist
1233
+ // const fileHandle = await currentDir.getFileHandle(fileName, { create: true });
1234
+ // // Create a writable stream and write the content
1235
+ // const writable = await fileHandle.createWritable();
1236
+ // if (typeof content === 'string' || content instanceof Uint8Array) {
1237
+ // await writable.write(content);
1238
+ // } else if (content instanceof Blob) {
1239
+ // await writable.write(content);
1240
+ // } else if (content instanceof ArrayBuffer) {
1241
+ // await writable.write(new Blob([content]));
1242
+ // } else {
1243
+ // throw new Error('Unsupported content type');
1244
+ // }
1245
+ // await writable.close();
1246
+ // logger(`File written successfully: ${filePath}`);
1247
+ // } catch (error) {
1248
+ // console.error(`Error writing to OPFS: ${error.message}`);
1249
+ // }
1250
+ }
1251
+ saveFileSync(filePath, content) {
1252
+ // Note: This is a synchronous wrapper, but zenfs operations may still be async under the hood
1253
+ // For true sync operations in browser, we'd need to use OPFS sync access handles
1254
+ // For now, we'll use zenfs.writeFileSync which should be available
1255
+ const zenfs = this.getFsSync();
1256
+ // Convert content to a format that zenfs.writeFileSync accepts
1257
+ let writeContent;
1258
+ if (typeof content === 'string') {
1259
+ writeContent = content;
1260
+ }
1261
+ else if (content instanceof Blob) {
1262
+ // Blob cannot be converted synchronously - throw error
1263
+ throw new Error('Blob content not supported in saveFileSync. Use saveFile() instead or convert to ArrayBuffer first.');
1264
+ }
1265
+ else if (content instanceof ArrayBuffer) {
1266
+ writeContent = new Uint8Array(content);
1267
+ }
1268
+ else {
1269
+ throw new Error('Unsupported content type');
1270
+ }
1271
+ zenfs.writeFileSync(filePath, writeContent);
1272
+ }
1273
+ async readFile(filePath) {
1274
+ const zenfs = await this.getFs();
1275
+ const maxAttempts = 3;
1276
+ const baseDelayMs = 50;
1277
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
1278
+ try {
1279
+ const data = await zenfs.promises.readFile(filePath);
1280
+ return new File([new Uint8Array(data)], filePath);
1281
+ }
1282
+ catch (error) {
1283
+ if (!isTransientOpfsReadError(error) || attempt === maxAttempts - 1) {
1284
+ throw error;
1285
+ }
1286
+ await sleep(baseDelayMs * (attempt + 1));
1287
+ }
1288
+ }
1289
+ throw new Error('readFile: exhausted retries');
1290
+ // try {
1291
+ // // Get a handle to the OPFS root directory
1292
+ // const root = await navigator.storage.getDirectory();
1293
+ // // Split the file path into directory and file name
1294
+ // const pathParts = filePath.split('/');
1295
+ // const fileName = pathParts.pop();
1296
+ // if (!fileName) throw new Error('Invalid file path');
1297
+ // // Traverse directories to reach the target file
1298
+ // let currentDir = root;
1299
+ // for (const part of pathParts) {
1300
+ // if (part !== '') {
1301
+ // currentDir = await currentDir.getDirectoryHandle(part, { create: false });
1302
+ // }
1303
+ // }
1304
+ // // Get the file handle
1305
+ // const fileHandle = await currentDir.getFileHandle(fileName, { create: false });
1306
+ // // Get the file and read it as an ArrayBuffer
1307
+ // return await fileHandle.getFile();
1308
+ // } catch (error) {
1309
+ // console.error(`Error reading from OPFS: ${error.message}`);
1310
+ // throw error;
1311
+ // }
1312
+ }
1313
+ readFileSync(filePath) {
1314
+ // Note: This is a synchronous wrapper, but zenfs operations may still be async under the hood
1315
+ // For true sync operations in browser, we'd need to use OPFS sync access handles
1316
+ // For now, we'll use zenfs.readFileSync which should be available
1317
+ const zenfs = this.getFsSync();
1318
+ const file = zenfs.readFileSync(filePath);
1319
+ return new File([new Uint8Array(file)], filePath);
1320
+ }
1321
+ async readFileAsBuffer(filePath) {
1322
+ try {
1323
+ // Get the file and read it as an ArrayBuffer
1324
+ const file = await this.readFile(filePath);
1325
+ const arrayBuffer = await file.arrayBuffer();
1326
+ // Convert ArrayBuffer to Blob
1327
+ return new Blob([arrayBuffer]);
1328
+ }
1329
+ catch (error) {
1330
+ const errorMessage = error instanceof Error ? error.message : String(error);
1331
+ console.error(`Error reading from OPFS: ${errorMessage}`);
1332
+ throw error;
1333
+ }
1334
+ }
1335
+ async readFileAsString(filePath) {
1336
+ const blob = await this.readFileAsBuffer(filePath);
1337
+ return blob.text();
1338
+ }
1339
+ getParentDirPath(filePath) {
1340
+ return pathCompat.dirname(filePath);
1341
+ }
1342
+ getFilenameFromPath(filePath) {
1343
+ return pathCompat.basename(filePath);
1344
+ }
1345
+ getPathModule() {
1346
+ return pathCompat;
1347
+ }
1348
+ }
1349
+ class CancelableInterval {
1350
+ constructor(task, interval) {
1351
+ this.task = task;
1352
+ this.interval = interval;
1353
+ this.intervalId = null;
1354
+ this.currentTaskAbortController = null;
1355
+ }
1356
+ start() {
1357
+ this.intervalId = window.setInterval(async () => {
1358
+ if (this.currentTaskAbortController) {
1359
+ // Cancel the previous running task
1360
+ this.currentTaskAbortController.abort();
1361
+ }
1362
+ // Create a new abort controller for the current task
1363
+ this.currentTaskAbortController = new AbortController();
1364
+ const signal = this.currentTaskAbortController.signal;
1365
+ try {
1366
+ await this.taskWithCancellation(signal);
1367
+ }
1368
+ catch (error) {
1369
+ if (error instanceof DOMException && error.name === 'AbortError') {
1370
+ logger$2('Previous task was canceled.');
1371
+ }
1372
+ else {
1373
+ console.error('Task error:', error);
1374
+ }
1375
+ this.stop();
1376
+ }
1377
+ }, this.interval);
1378
+ }
1379
+ async taskWithCancellation(signal) {
1380
+ await this.task(() => this.stop());
1381
+ if (signal.aborted) {
1382
+ throw new DOMException('Task was aborted', 'AbortError');
1383
+ }
1384
+ }
1385
+ stop() {
1386
+ if (this.intervalId !== null) {
1387
+ clearInterval(this.intervalId);
1388
+ this.intervalId = null;
1389
+ }
1390
+ if (this.currentTaskAbortController) {
1391
+ this.currentTaskAbortController.abort();
1392
+ }
1393
+ }
1394
+ }
1395
+ BaseFileManager.configure(new BrowserFileManager());
1396
+
1397
+ // This file embeds the drizzle migration files as strings for browser runtime
1398
+ // These files are copied from packages/sdk/src/db/drizzle at build time
1399
+ // Individual migration SQL files
1400
+ const migrationSql_0000_married_malice = `CREATE TABLE \`appState\` (
1401
+ \`key\` text,
1402
+ \`value\` text,
1403
+ \`created_at\` integer,
1404
+ \`updated_at\` integer
1405
+ );
1406
+ --> statement-breakpoint
1407
+ CREATE UNIQUE INDEX \`appState_key_unique\` ON \`appState\` (\`key\`);--> statement-breakpoint
1408
+ CREATE TABLE \`config\` (
1409
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1410
+ \`key\` text NOT NULL,
1411
+ \`text\` text,
1412
+ \`json\` text,
1413
+ \`blob\` blob
1414
+ );
1415
+ --> statement-breakpoint
1416
+ CREATE TABLE \`metadata\` (
1417
+ \`local_id\` text,
1418
+ \`uid\` text,
1419
+ \`property_name\` text,
1420
+ \`property_value\` text,
1421
+ \`schema_uid\` text,
1422
+ \`model_type\` text,
1423
+ \`seed_local_id\` text,
1424
+ \`seed_uid\` text,
1425
+ \`version_local_id\` text,
1426
+ \`version_uid\` text,
1427
+ \`eas_data_type\` text,
1428
+ \`ref_value_type\` text,
1429
+ \`ref_schema_uid\` text,
1430
+ \`ref_seed_type\` text,
1431
+ \`ref_resolved_value\` text,
1432
+ \`ref_resolved_display_value\` text,
1433
+ \`local_storage_dir\` text,
1434
+ \`attestation_raw\` text,
1435
+ \`attestation_created_at\` integer,
1436
+ \`content_hash\` text,
1437
+ \`created_at\` integer,
1438
+ \`updated_at\` integer
1439
+ );
1440
+ --> statement-breakpoint
1441
+ CREATE UNIQUE INDEX \`metadata_local_id_unique\` ON \`metadata\` (\`local_id\`);--> statement-breakpoint
1442
+ CREATE TABLE \`models\` (
1443
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1444
+ \`name\` text NOT NULL,
1445
+ \`schema_file_id\` text
1446
+ );
1447
+ --> statement-breakpoint
1448
+ CREATE TABLE \`properties\` (
1449
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1450
+ \`name\` text NOT NULL,
1451
+ \`data_type\` text NOT NULL,
1452
+ \`model_id\` integer NOT NULL,
1453
+ \`ref_model_id\` integer,
1454
+ \`ref_value_type\` text,
1455
+ \`schema_file_id\` text,
1456
+ FOREIGN KEY (\`model_id\`) REFERENCES \`models\`(\`id\`) ON UPDATE no action ON DELETE no action,
1457
+ FOREIGN KEY (\`ref_model_id\`) REFERENCES \`models\`(\`id\`) ON UPDATE no action ON DELETE no action
1458
+ );
1459
+ --> statement-breakpoint
1460
+ CREATE UNIQUE INDEX \`unique_name_model_id\` ON \`properties\` (\`name\`,\`model_id\`);--> statement-breakpoint
1461
+ CREATE TABLE \`model_schemas\` (
1462
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1463
+ \`model_id\` integer,
1464
+ \`schema_id\` integer,
1465
+ FOREIGN KEY (\`model_id\`) REFERENCES \`models\`(\`id\`) ON UPDATE no action ON DELETE no action,
1466
+ FOREIGN KEY (\`schema_id\`) REFERENCES \`schemas\`(\`id\`) ON UPDATE no action ON DELETE no action
1467
+ );
1468
+ --> statement-breakpoint
1469
+ CREATE TABLE \`model_uids\` (
1470
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1471
+ \`uid\` text NOT NULL,
1472
+ \`model_id\` integer NOT NULL,
1473
+ FOREIGN KEY (\`model_id\`) REFERENCES \`models\`(\`id\`) ON UPDATE no action ON DELETE no action
1474
+ );
1475
+ --> statement-breakpoint
1476
+ CREATE UNIQUE INDEX \`model_uids_model_id_unique\` ON \`model_uids\` (\`model_id\`);--> statement-breakpoint
1477
+ CREATE TABLE \`property_uids\` (
1478
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1479
+ \`uid\` text NOT NULL,
1480
+ \`property_id\` integer NOT NULL,
1481
+ FOREIGN KEY (\`property_id\`) REFERENCES \`models\`(\`id\`) ON UPDATE no action ON DELETE no action
1482
+ );
1483
+ --> statement-breakpoint
1484
+ CREATE UNIQUE INDEX \`property_uids_property_id_unique\` ON \`property_uids\` (\`property_id\`);--> statement-breakpoint
1485
+ CREATE TABLE \`schemas\` (
1486
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1487
+ \`name\` text NOT NULL,
1488
+ \`version\` integer NOT NULL,
1489
+ \`schema_file_id\` text,
1490
+ \`created_at\` integer,
1491
+ \`updated_at\` integer
1492
+ );
1493
+ --> statement-breakpoint
1494
+ CREATE TABLE \`seeds\` (
1495
+ \`local_id\` text,
1496
+ \`uid\` text,
1497
+ \`schema_uid\` text,
1498
+ \`type\` text,
1499
+ \`attestation_raw\` text,
1500
+ \`attestation_created_at\` integer,
1501
+ \`created_at\` integer,
1502
+ \`updated_at\` integer,
1503
+ \`_marked_for_deletion\` integer
1504
+ );
1505
+ --> statement-breakpoint
1506
+ CREATE UNIQUE INDEX \`seeds_local_id_unique\` ON \`seeds\` (\`local_id\`);--> statement-breakpoint
1507
+ CREATE TABLE \`versions\` (
1508
+ \`local_id\` text,
1509
+ \`uid\` text,
1510
+ \`seed_local_id\` text,
1511
+ \`seed_uid\` text,
1512
+ \`seed_type\` text,
1513
+ \`note\` text,
1514
+ \`created_at\` integer,
1515
+ \`updated_at\` integer,
1516
+ \`attestation_created_at\` integer,
1517
+ \`attestation_raw\` text
1518
+ );
1519
+ --> statement-breakpoint
1520
+ CREATE UNIQUE INDEX \`versions_local_id_unique\` ON \`versions\` (\`local_id\`);`;
1521
+ const migrationSql_0001_sweet_bruce_banner = `ALTER TABLE \`schemas\` ADD \`schema_data\` text;--> statement-breakpoint
1522
+ ALTER TABLE \`schemas\` ADD \`is_draft\` integer;`;
1523
+ const migrationSql_0002_bitter_proudstar = `CREATE UNIQUE INDEX \`unique_schema_file_id\` ON \`models\` (\`schema_file_id\`);--> statement-breakpoint
1524
+ CREATE UNIQUE INDEX \`unique_property_schema_file_id\` ON \`properties\` (\`schema_file_id\`);--> statement-breakpoint
1525
+ CREATE UNIQUE INDEX \`unique_schema_schema_file_id\` ON \`schemas\` (\`schema_file_id\`);`;
1526
+ const migrationSql_0003_cultured_senator_kelly = `ALTER TABLE \`models\` ADD \`is_edited\` integer;--> statement-breakpoint
1527
+ ALTER TABLE \`properties\` ADD \`is_edited\` integer;--> statement-breakpoint
1528
+ ALTER TABLE \`schemas\` ADD \`is_edited\` integer;`;
1529
+ const migrationSql_0004_add_publisher_to_seeds = `ALTER TABLE \`seeds\` ADD \`publisher\` text;`;
1530
+ const migrationSql_0005_bright_lily_hollister = `CREATE TABLE \`publish_processes\` (
1531
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1532
+ \`seed_local_id\` text NOT NULL,
1533
+ \`model_name\` text NOT NULL,
1534
+ \`schema_id\` text,
1535
+ \`status\` text NOT NULL,
1536
+ \`started_at\` integer NOT NULL,
1537
+ \`completed_at\` integer,
1538
+ \`error_message\` text,
1539
+ \`error_step\` text,
1540
+ \`error_details\` text,
1541
+ \`persisted_snapshot\` text NOT NULL,
1542
+ \`seed_id\` text,
1543
+ \`existing_seed_uid\` text,
1544
+ \`created_at\` integer,
1545
+ \`updated_at\` integer
1546
+ );
1547
+ --> statement-breakpoint
1548
+ CREATE TABLE \`upload_processes\` (
1549
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1550
+ \`reimbursement_confirmed\` integer NOT NULL,
1551
+ \`reimbursement_transaction_id\` text,
1552
+ \`transaction_keys\` text,
1553
+ \`persisted_snapshot\` text NOT NULL,
1554
+ \`created_at\` integer,
1555
+ \`updated_at\` integer
1556
+ );
1557
+ `;
1558
+ const migrationSql_0006_add_publisher_to_versions_and_metadata = `ALTER TABLE \`versions\` ADD \`publisher\` text;
1559
+ --> statement-breakpoint
1560
+ ALTER TABLE \`metadata\` ADD \`publisher\` text;
1561
+ `;
1562
+ const migrationSql_0007_add_required_to_properties = `ALTER TABLE \`properties\` ADD \`required\` integer DEFAULT 0;
1563
+ `;
1564
+ const migrationSql_0008_add_revoked_at_to_seeds = `ALTER TABLE \`seeds\` ADD \`revoked_at\` integer;
1565
+ `;
1566
+ const migrationSql_0009_happy_namor = `PRAGMA foreign_keys=OFF;--> statement-breakpoint
1567
+ CREATE TABLE \`__new_property_uids\` (
1568
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1569
+ \`uid\` text NOT NULL,
1570
+ \`property_id\` integer NOT NULL,
1571
+ FOREIGN KEY (\`property_id\`) REFERENCES \`properties\`(\`id\`) ON UPDATE no action ON DELETE no action
1572
+ );
1573
+ --> statement-breakpoint
1574
+ INSERT INTO \`__new_property_uids\`("id", "uid", "property_id") SELECT "id", "uid", "property_id" FROM \`property_uids\`;--> statement-breakpoint
1575
+ DROP TABLE \`property_uids\`;--> statement-breakpoint
1576
+ ALTER TABLE \`__new_property_uids\` RENAME TO \`property_uids\`;--> statement-breakpoint
1577
+ PRAGMA foreign_keys=ON;--> statement-breakpoint
1578
+ CREATE UNIQUE INDEX \`property_uids_property_id_unique\` ON \`property_uids\` (\`property_id\`);--> statement-breakpoint
1579
+ ALTER TABLE \`metadata\` ADD \`property_id\` integer REFERENCES properties(id);`;
1580
+ const migrationSql_0010_add_arweave_l1_finalize_jobs = `CREATE TABLE \`arweave_l1_finalize_jobs\` (
1581
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1582
+ \`seed_local_id\` text NOT NULL,
1583
+ \`data_item_id\` text NOT NULL,
1584
+ \`l1_transaction_id\` text,
1585
+ \`bundle_id\` text,
1586
+ \`version_local_id\` text,
1587
+ \`item_property_name\` text,
1588
+ \`phase\` text NOT NULL,
1589
+ \`status_json\` text,
1590
+ \`error_message\` text,
1591
+ \`created_at\` integer NOT NULL,
1592
+ \`updated_at\` integer NOT NULL
1593
+ );
1594
+ --> statement-breakpoint
1595
+ CREATE UNIQUE INDEX \`arweave_l1_finalize_jobs_data_item_id_unique\` ON \`arweave_l1_finalize_jobs\` (\`data_item_id\`);
1596
+ `;
1597
+ const migrationSql_0011_normalize_placeholder_uids = `UPDATE \`versions\` SET \`uid\` = NULL WHERE \`uid\` = 'NULL';
1598
+ --> statement-breakpoint
1599
+ UPDATE \`versions\` SET \`seed_uid\` = NULL WHERE \`seed_uid\` = 'NULL';
1600
+ --> statement-breakpoint
1601
+ UPDATE \`metadata\` SET \`uid\` = NULL WHERE \`uid\` = 'NULL';
1602
+ --> statement-breakpoint
1603
+ UPDATE \`metadata\` SET \`version_uid\` = NULL WHERE \`version_uid\` = 'NULL';
1604
+ --> statement-breakpoint
1605
+ UPDATE \`seeds\` SET \`uid\` = NULL WHERE \`uid\` = 'NULL';
1606
+ `;
1607
+ const migrationSql_0012_html_embedded_image_co_publish = `CREATE TABLE \`html_embedded_image_co_publish\` (
1608
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1609
+ \`parent_seed_local_id\` text NOT NULL,
1610
+ \`html_seed_local_id\` text NOT NULL,
1611
+ \`image_seed_local_id\` text NOT NULL,
1612
+ \`stable_key\` text NOT NULL,
1613
+ \`created_at\` integer NOT NULL
1614
+ );
1615
+ --> statement-breakpoint
1616
+ CREATE UNIQUE INDEX \`html_embed_co_pub_parent_html_stable\` ON \`html_embedded_image_co_publish\` (\`parent_seed_local_id\`,\`html_seed_local_id\`,\`stable_key\`);
1617
+ `;
1618
+ const migrationSql_0013_eas_sync_processes = `CREATE TABLE \`eas_sync_processes\` (
1619
+ \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
1620
+ \`status\` text NOT NULL,
1621
+ \`started_at\` integer NOT NULL,
1622
+ \`completed_at\` integer,
1623
+ \`request_payload\` text NOT NULL,
1624
+ \`error_message\` text,
1625
+ \`error_details\` text,
1626
+ \`persisted_snapshot\` text NOT NULL,
1627
+ \`created_at\` integer,
1628
+ \`updated_at\` integer
1629
+ );
1630
+ `;
1631
+ // Journal JSON file
1632
+ const journalJson = `{
1633
+ "version": "7",
1634
+ "dialect": "sqlite",
1635
+ "entries": [
1636
+ {
1637
+ "idx": 0,
1638
+ "version": "6",
1639
+ "when": 1765976502903,
1640
+ "tag": "0000_married_malice",
1641
+ "breakpoints": true
1642
+ },
1643
+ {
1644
+ "idx": 1,
1645
+ "version": "6",
1646
+ "when": 1766010851770,
1647
+ "tag": "0001_sweet_bruce_banner",
1648
+ "breakpoints": true
1649
+ },
1650
+ {
1651
+ "idx": 2,
1652
+ "version": "6",
1653
+ "when": 1767621120087,
1654
+ "tag": "0002_bitter_proudstar",
1655
+ "breakpoints": true
1656
+ },
1657
+ {
1658
+ "idx": 3,
1659
+ "version": "6",
1660
+ "when": 1768415440282,
1661
+ "tag": "0003_cultured_senator_kelly",
1662
+ "breakpoints": true
1663
+ },
1664
+ {
1665
+ "idx": 4,
1666
+ "version": "6",
1667
+ "when": 1768500000000,
1668
+ "tag": "0004_add_publisher_to_seeds",
1669
+ "breakpoints": true
1670
+ },
1671
+ {
1672
+ "idx": 5,
1673
+ "version": "6",
1674
+ "when": 1772489937031,
1675
+ "tag": "0005_bright_lily_hollister",
1676
+ "breakpoints": true
1677
+ },
1678
+ {
1679
+ "idx": 6,
1680
+ "version": "6",
1681
+ "when": 1772600000000,
1682
+ "tag": "0006_add_publisher_to_versions_and_metadata",
1683
+ "breakpoints": true
1684
+ },
1685
+ {
1686
+ "idx": 7,
1687
+ "version": "6",
1688
+ "when": 1772700000000,
1689
+ "tag": "0007_add_required_to_properties",
1690
+ "breakpoints": true
1691
+ },
1692
+ {
1693
+ "idx": 8,
1694
+ "version": "6",
1695
+ "when": 1772800000000,
1696
+ "tag": "0008_add_revoked_at_to_seeds",
1697
+ "breakpoints": true
1698
+ },
1699
+ {
1700
+ "idx": 9,
1701
+ "version": "6",
1702
+ "when": 1773924021107,
1703
+ "tag": "0009_happy_namor",
1704
+ "breakpoints": true
1705
+ },
1706
+ {
1707
+ "idx": 10,
1708
+ "version": "6",
1709
+ "when": 1774000000000,
1710
+ "tag": "0010_add_arweave_l1_finalize_jobs",
1711
+ "breakpoints": true
1712
+ },
1713
+ {
1714
+ "idx": 11,
1715
+ "version": "6",
1716
+ "when": 1774100000000,
1717
+ "tag": "0011_normalize_placeholder_uids",
1718
+ "breakpoints": true
1719
+ },
1720
+ {
1721
+ "idx": 12,
1722
+ "version": "6",
1723
+ "when": 1774200000000,
1724
+ "tag": "0012_html_embedded_image_co_publish",
1725
+ "breakpoints": true
1726
+ },
1727
+ {
1728
+ "idx": 13,
1729
+ "version": "6",
1730
+ "when": 1774300000000,
1731
+ "tag": "0013_eas_sync_processes",
1732
+ "breakpoints": true
1733
+ }
1734
+ ]
1735
+ }`;
1736
+ // Snapshot JSON file - this is large, so we'll import it dynamically if needed
1737
+ // For now, we'll read it from the actual file if ?raw works, otherwise we'll need to embed it
1738
+ const snapshotJson = `{
1739
+ "version": "6",
1740
+ "dialect": "sqlite",
1741
+ "id": "a9e8f7d6-c5b4-4321-a0b9-c8d7e6f5a4b3",
1742
+ "prevId": "ff2318d5-236f-4157-82ae-10ccb44c0e0c",
1743
+ "tables": {
1744
+ "appState": {
1745
+ "name": "appState",
1746
+ "columns": {
1747
+ "key": {
1748
+ "name": "key",
1749
+ "type": "text",
1750
+ "primaryKey": false,
1751
+ "notNull": false,
1752
+ "autoincrement": false
1753
+ },
1754
+ "value": {
1755
+ "name": "value",
1756
+ "type": "text",
1757
+ "primaryKey": false,
1758
+ "notNull": false,
1759
+ "autoincrement": false
1760
+ },
1761
+ "created_at": {
1762
+ "name": "created_at",
1763
+ "type": "integer",
1764
+ "primaryKey": false,
1765
+ "notNull": false,
1766
+ "autoincrement": false
1767
+ },
1768
+ "updated_at": {
1769
+ "name": "updated_at",
1770
+ "type": "integer",
1771
+ "primaryKey": false,
1772
+ "notNull": false,
1773
+ "autoincrement": false
1774
+ }
1775
+ },
1776
+ "indexes": {
1777
+ "appState_key_unique": {
1778
+ "name": "appState_key_unique",
1779
+ "columns": [
1780
+ "key"
1781
+ ],
1782
+ "isUnique": true
1783
+ }
1784
+ },
1785
+ "foreignKeys": {},
1786
+ "compositePrimaryKeys": {},
1787
+ "uniqueConstraints": {},
1788
+ "checkConstraints": {}
1789
+ },
1790
+ "config": {
1791
+ "name": "config",
1792
+ "columns": {
1793
+ "id": {
1794
+ "name": "id",
1795
+ "type": "integer",
1796
+ "primaryKey": true,
1797
+ "notNull": true,
1798
+ "autoincrement": true
1799
+ },
1800
+ "key": {
1801
+ "name": "key",
1802
+ "type": "text",
1803
+ "primaryKey": false,
1804
+ "notNull": true,
1805
+ "autoincrement": false
1806
+ },
1807
+ "text": {
1808
+ "name": "text",
1809
+ "type": "text",
1810
+ "primaryKey": false,
1811
+ "notNull": false,
1812
+ "autoincrement": false
1813
+ },
1814
+ "json": {
1815
+ "name": "json",
1816
+ "type": "text",
1817
+ "primaryKey": false,
1818
+ "notNull": false,
1819
+ "autoincrement": false
1820
+ },
1821
+ "blob": {
1822
+ "name": "blob",
1823
+ "type": "blob",
1824
+ "primaryKey": false,
1825
+ "notNull": false,
1826
+ "autoincrement": false
1827
+ }
1828
+ },
1829
+ "indexes": {},
1830
+ "foreignKeys": {},
1831
+ "compositePrimaryKeys": {},
1832
+ "uniqueConstraints": {},
1833
+ "checkConstraints": {}
1834
+ },
1835
+ "metadata": {
1836
+ "name": "metadata",
1837
+ "columns": {
1838
+ "local_id": {
1839
+ "name": "local_id",
1840
+ "type": "text",
1841
+ "primaryKey": false,
1842
+ "notNull": false,
1843
+ "autoincrement": false
1844
+ },
1845
+ "uid": {
1846
+ "name": "uid",
1847
+ "type": "text",
1848
+ "primaryKey": false,
1849
+ "notNull": false,
1850
+ "autoincrement": false
1851
+ },
1852
+ "property_id": {
1853
+ "name": "property_id",
1854
+ "type": "integer",
1855
+ "primaryKey": false,
1856
+ "notNull": false,
1857
+ "autoincrement": false
1858
+ },
1859
+ "property_name": {
1860
+ "name": "property_name",
1861
+ "type": "text",
1862
+ "primaryKey": false,
1863
+ "notNull": false,
1864
+ "autoincrement": false
1865
+ },
1866
+ "property_value": {
1867
+ "name": "property_value",
1868
+ "type": "text",
1869
+ "primaryKey": false,
1870
+ "notNull": false,
1871
+ "autoincrement": false
1872
+ },
1873
+ "schema_uid": {
1874
+ "name": "schema_uid",
1875
+ "type": "text",
1876
+ "primaryKey": false,
1877
+ "notNull": false,
1878
+ "autoincrement": false
1879
+ },
1880
+ "model_type": {
1881
+ "name": "model_type",
1882
+ "type": "text",
1883
+ "primaryKey": false,
1884
+ "notNull": false,
1885
+ "autoincrement": false
1886
+ },
1887
+ "seed_local_id": {
1888
+ "name": "seed_local_id",
1889
+ "type": "text",
1890
+ "primaryKey": false,
1891
+ "notNull": false,
1892
+ "autoincrement": false
1893
+ },
1894
+ "seed_uid": {
1895
+ "name": "seed_uid",
1896
+ "type": "text",
1897
+ "primaryKey": false,
1898
+ "notNull": false,
1899
+ "autoincrement": false
1900
+ },
1901
+ "version_local_id": {
1902
+ "name": "version_local_id",
1903
+ "type": "text",
1904
+ "primaryKey": false,
1905
+ "notNull": false,
1906
+ "autoincrement": false
1907
+ },
1908
+ "version_uid": {
1909
+ "name": "version_uid",
1910
+ "type": "text",
1911
+ "primaryKey": false,
1912
+ "notNull": false,
1913
+ "autoincrement": false
1914
+ },
1915
+ "eas_data_type": {
1916
+ "name": "eas_data_type",
1917
+ "type": "text",
1918
+ "primaryKey": false,
1919
+ "notNull": false,
1920
+ "autoincrement": false
1921
+ },
1922
+ "ref_value_type": {
1923
+ "name": "ref_value_type",
1924
+ "type": "text",
1925
+ "primaryKey": false,
1926
+ "notNull": false,
1927
+ "autoincrement": false
1928
+ },
1929
+ "ref_schema_uid": {
1930
+ "name": "ref_schema_uid",
1931
+ "type": "text",
1932
+ "primaryKey": false,
1933
+ "notNull": false,
1934
+ "autoincrement": false
1935
+ },
1936
+ "ref_seed_type": {
1937
+ "name": "ref_seed_type",
1938
+ "type": "text",
1939
+ "primaryKey": false,
1940
+ "notNull": false,
1941
+ "autoincrement": false
1942
+ },
1943
+ "ref_resolved_value": {
1944
+ "name": "ref_resolved_value",
1945
+ "type": "text",
1946
+ "primaryKey": false,
1947
+ "notNull": false,
1948
+ "autoincrement": false
1949
+ },
1950
+ "ref_resolved_display_value": {
1951
+ "name": "ref_resolved_display_value",
1952
+ "type": "text",
1953
+ "primaryKey": false,
1954
+ "notNull": false,
1955
+ "autoincrement": false
1956
+ },
1957
+ "local_storage_dir": {
1958
+ "name": "local_storage_dir",
1959
+ "type": "text",
1960
+ "primaryKey": false,
1961
+ "notNull": false,
1962
+ "autoincrement": false
1963
+ },
1964
+ "attestation_raw": {
1965
+ "name": "attestation_raw",
1966
+ "type": "text",
1967
+ "primaryKey": false,
1968
+ "notNull": false,
1969
+ "autoincrement": false
1970
+ },
1971
+ "attestation_created_at": {
1972
+ "name": "attestation_created_at",
1973
+ "type": "integer",
1974
+ "primaryKey": false,
1975
+ "notNull": false,
1976
+ "autoincrement": false
1977
+ },
1978
+ "content_hash": {
1979
+ "name": "content_hash",
1980
+ "type": "text",
1981
+ "primaryKey": false,
1982
+ "notNull": false,
1983
+ "autoincrement": false
1984
+ },
1985
+ "created_at": {
1986
+ "name": "created_at",
1987
+ "type": "integer",
1988
+ "primaryKey": false,
1989
+ "notNull": false,
1990
+ "autoincrement": false
1991
+ },
1992
+ "updated_at": {
1993
+ "name": "updated_at",
1994
+ "type": "integer",
1995
+ "primaryKey": false,
1996
+ "notNull": false,
1997
+ "autoincrement": false
1998
+ },
1999
+ "publisher": {
2000
+ "name": "publisher",
2001
+ "type": "text",
2002
+ "primaryKey": false,
2003
+ "notNull": false,
2004
+ "autoincrement": false
2005
+ }
2006
+ },
2007
+ "indexes": {
2008
+ "metadata_local_id_unique": {
2009
+ "name": "metadata_local_id_unique",
2010
+ "columns": [
2011
+ "local_id"
2012
+ ],
2013
+ "isUnique": true
2014
+ }
2015
+ },
2016
+ "foreignKeys": {
2017
+ "metadata_property_id_properties_id_fk": {
2018
+ "name": "metadata_property_id_properties_id_fk",
2019
+ "tableFrom": "metadata",
2020
+ "tableTo": "properties",
2021
+ "columnsFrom": [
2022
+ "property_id"
2023
+ ],
2024
+ "columnsTo": [
2025
+ "id"
2026
+ ],
2027
+ "onDelete": "no action",
2028
+ "onUpdate": "no action"
2029
+ }
2030
+ },
2031
+ "compositePrimaryKeys": {},
2032
+ "uniqueConstraints": {},
2033
+ "checkConstraints": {}
2034
+ },
2035
+ "models": {
2036
+ "name": "models",
2037
+ "columns": {
2038
+ "id": {
2039
+ "name": "id",
2040
+ "type": "integer",
2041
+ "primaryKey": true,
2042
+ "notNull": true,
2043
+ "autoincrement": true
2044
+ },
2045
+ "name": {
2046
+ "name": "name",
2047
+ "type": "text",
2048
+ "primaryKey": false,
2049
+ "notNull": true,
2050
+ "autoincrement": false
2051
+ },
2052
+ "schema_file_id": {
2053
+ "name": "schema_file_id",
2054
+ "type": "text",
2055
+ "primaryKey": false,
2056
+ "notNull": false,
2057
+ "autoincrement": false
2058
+ },
2059
+ "is_edited": {
2060
+ "name": "is_edited",
2061
+ "type": "integer",
2062
+ "primaryKey": false,
2063
+ "notNull": false,
2064
+ "autoincrement": false
2065
+ }
2066
+ },
2067
+ "indexes": {
2068
+ "unique_schema_file_id": {
2069
+ "name": "unique_schema_file_id",
2070
+ "columns": [
2071
+ "schema_file_id"
2072
+ ],
2073
+ "isUnique": true
2074
+ }
2075
+ },
2076
+ "foreignKeys": {},
2077
+ "compositePrimaryKeys": {},
2078
+ "uniqueConstraints": {},
2079
+ "checkConstraints": {}
2080
+ },
2081
+ "properties": {
2082
+ "name": "properties",
2083
+ "columns": {
2084
+ "id": {
2085
+ "name": "id",
2086
+ "type": "integer",
2087
+ "primaryKey": true,
2088
+ "notNull": true,
2089
+ "autoincrement": true
2090
+ },
2091
+ "name": {
2092
+ "name": "name",
2093
+ "type": "text",
2094
+ "primaryKey": false,
2095
+ "notNull": true,
2096
+ "autoincrement": false
2097
+ },
2098
+ "data_type": {
2099
+ "name": "data_type",
2100
+ "type": "text",
2101
+ "primaryKey": false,
2102
+ "notNull": true,
2103
+ "autoincrement": false
2104
+ },
2105
+ "model_id": {
2106
+ "name": "model_id",
2107
+ "type": "integer",
2108
+ "primaryKey": false,
2109
+ "notNull": true,
2110
+ "autoincrement": false
2111
+ },
2112
+ "ref_model_id": {
2113
+ "name": "ref_model_id",
2114
+ "type": "integer",
2115
+ "primaryKey": false,
2116
+ "notNull": false,
2117
+ "autoincrement": false
2118
+ },
2119
+ "ref_value_type": {
2120
+ "name": "ref_value_type",
2121
+ "type": "text",
2122
+ "primaryKey": false,
2123
+ "notNull": false,
2124
+ "autoincrement": false
2125
+ },
2126
+ "schema_file_id": {
2127
+ "name": "schema_file_id",
2128
+ "type": "text",
2129
+ "primaryKey": false,
2130
+ "notNull": false,
2131
+ "autoincrement": false
2132
+ },
2133
+ "is_edited": {
2134
+ "name": "is_edited",
2135
+ "type": "integer",
2136
+ "primaryKey": false,
2137
+ "notNull": false,
2138
+ "autoincrement": false
2139
+ },
2140
+ "required": {
2141
+ "name": "required",
2142
+ "type": "integer",
2143
+ "primaryKey": false,
2144
+ "notNull": false,
2145
+ "autoincrement": false
2146
+ }
2147
+ },
2148
+ "indexes": {
2149
+ "unique_name_model_id": {
2150
+ "name": "unique_name_model_id",
2151
+ "columns": [
2152
+ "name",
2153
+ "model_id"
2154
+ ],
2155
+ "isUnique": true
2156
+ },
2157
+ "unique_property_schema_file_id": {
2158
+ "name": "unique_property_schema_file_id",
2159
+ "columns": [
2160
+ "schema_file_id"
2161
+ ],
2162
+ "isUnique": true
2163
+ }
2164
+ },
2165
+ "foreignKeys": {
2166
+ "properties_model_id_models_id_fk": {
2167
+ "name": "properties_model_id_models_id_fk",
2168
+ "tableFrom": "properties",
2169
+ "tableTo": "models",
2170
+ "columnsFrom": [
2171
+ "model_id"
2172
+ ],
2173
+ "columnsTo": [
2174
+ "id"
2175
+ ],
2176
+ "onDelete": "no action",
2177
+ "onUpdate": "no action"
2178
+ },
2179
+ "properties_ref_model_id_models_id_fk": {
2180
+ "name": "properties_ref_model_id_models_id_fk",
2181
+ "tableFrom": "properties",
2182
+ "tableTo": "models",
2183
+ "columnsFrom": [
2184
+ "ref_model_id"
2185
+ ],
2186
+ "columnsTo": [
2187
+ "id"
2188
+ ],
2189
+ "onDelete": "no action",
2190
+ "onUpdate": "no action"
2191
+ }
2192
+ },
2193
+ "compositePrimaryKeys": {},
2194
+ "uniqueConstraints": {},
2195
+ "checkConstraints": {}
2196
+ },
2197
+ "model_schemas": {
2198
+ "name": "model_schemas",
2199
+ "columns": {
2200
+ "id": {
2201
+ "name": "id",
2202
+ "type": "integer",
2203
+ "primaryKey": true,
2204
+ "notNull": true,
2205
+ "autoincrement": true
2206
+ },
2207
+ "model_id": {
2208
+ "name": "model_id",
2209
+ "type": "integer",
2210
+ "primaryKey": false,
2211
+ "notNull": false,
2212
+ "autoincrement": false
2213
+ },
2214
+ "schema_id": {
2215
+ "name": "schema_id",
2216
+ "type": "integer",
2217
+ "primaryKey": false,
2218
+ "notNull": false,
2219
+ "autoincrement": false
2220
+ }
2221
+ },
2222
+ "indexes": {},
2223
+ "foreignKeys": {
2224
+ "model_schemas_model_id_models_id_fk": {
2225
+ "name": "model_schemas_model_id_models_id_fk",
2226
+ "tableFrom": "model_schemas",
2227
+ "tableTo": "models",
2228
+ "columnsFrom": [
2229
+ "model_id"
2230
+ ],
2231
+ "columnsTo": [
2232
+ "id"
2233
+ ],
2234
+ "onDelete": "no action",
2235
+ "onUpdate": "no action"
2236
+ },
2237
+ "model_schemas_schema_id_schemas_id_fk": {
2238
+ "name": "model_schemas_schema_id_schemas_id_fk",
2239
+ "tableFrom": "model_schemas",
2240
+ "tableTo": "schemas",
2241
+ "columnsFrom": [
2242
+ "schema_id"
2243
+ ],
2244
+ "columnsTo": [
2245
+ "id"
2246
+ ],
2247
+ "onDelete": "no action",
2248
+ "onUpdate": "no action"
2249
+ }
2250
+ },
2251
+ "compositePrimaryKeys": {},
2252
+ "uniqueConstraints": {},
2253
+ "checkConstraints": {}
2254
+ },
2255
+ "model_uids": {
2256
+ "name": "model_uids",
2257
+ "columns": {
2258
+ "id": {
2259
+ "name": "id",
2260
+ "type": "integer",
2261
+ "primaryKey": true,
2262
+ "notNull": true,
2263
+ "autoincrement": true
2264
+ },
2265
+ "uid": {
2266
+ "name": "uid",
2267
+ "type": "text",
2268
+ "primaryKey": false,
2269
+ "notNull": true,
2270
+ "autoincrement": false
2271
+ },
2272
+ "model_id": {
2273
+ "name": "model_id",
2274
+ "type": "integer",
2275
+ "primaryKey": false,
2276
+ "notNull": true,
2277
+ "autoincrement": false
2278
+ }
2279
+ },
2280
+ "indexes": {
2281
+ "model_uids_model_id_unique": {
2282
+ "name": "model_uids_model_id_unique",
2283
+ "columns": [
2284
+ "model_id"
2285
+ ],
2286
+ "isUnique": true
2287
+ }
2288
+ },
2289
+ "foreignKeys": {
2290
+ "model_uids_model_id_models_id_fk": {
2291
+ "name": "model_uids_model_id_models_id_fk",
2292
+ "tableFrom": "model_uids",
2293
+ "tableTo": "models",
2294
+ "columnsFrom": [
2295
+ "model_id"
2296
+ ],
2297
+ "columnsTo": [
2298
+ "id"
2299
+ ],
2300
+ "onDelete": "no action",
2301
+ "onUpdate": "no action"
2302
+ }
2303
+ },
2304
+ "compositePrimaryKeys": {},
2305
+ "uniqueConstraints": {},
2306
+ "checkConstraints": {}
2307
+ },
2308
+ "property_uids": {
2309
+ "name": "property_uids",
2310
+ "columns": {
2311
+ "id": {
2312
+ "name": "id",
2313
+ "type": "integer",
2314
+ "primaryKey": true,
2315
+ "notNull": true,
2316
+ "autoincrement": true
2317
+ },
2318
+ "uid": {
2319
+ "name": "uid",
2320
+ "type": "text",
2321
+ "primaryKey": false,
2322
+ "notNull": true,
2323
+ "autoincrement": false
2324
+ },
2325
+ "property_id": {
2326
+ "name": "property_id",
2327
+ "type": "integer",
2328
+ "primaryKey": false,
2329
+ "notNull": true,
2330
+ "autoincrement": false
2331
+ }
2332
+ },
2333
+ "indexes": {
2334
+ "property_uids_property_id_unique": {
2335
+ "name": "property_uids_property_id_unique",
2336
+ "columns": [
2337
+ "property_id"
2338
+ ],
2339
+ "isUnique": true
2340
+ }
2341
+ },
2342
+ "foreignKeys": {
2343
+ "property_uids_property_id_properties_id_fk": {
2344
+ "name": "property_uids_property_id_properties_id_fk",
2345
+ "tableFrom": "property_uids",
2346
+ "tableTo": "properties",
2347
+ "columnsFrom": [
2348
+ "property_id"
2349
+ ],
2350
+ "columnsTo": [
2351
+ "id"
2352
+ ],
2353
+ "onDelete": "no action",
2354
+ "onUpdate": "no action"
2355
+ }
2356
+ },
2357
+ "compositePrimaryKeys": {},
2358
+ "uniqueConstraints": {},
2359
+ "checkConstraints": {}
2360
+ },
2361
+ "publish_processes": {
2362
+ "name": "publish_processes",
2363
+ "columns": {
2364
+ "id": {
2365
+ "name": "id",
2366
+ "type": "integer",
2367
+ "primaryKey": true,
2368
+ "notNull": true,
2369
+ "autoincrement": true
2370
+ },
2371
+ "seed_local_id": {
2372
+ "name": "seed_local_id",
2373
+ "type": "text",
2374
+ "primaryKey": false,
2375
+ "notNull": true,
2376
+ "autoincrement": false
2377
+ },
2378
+ "model_name": {
2379
+ "name": "model_name",
2380
+ "type": "text",
2381
+ "primaryKey": false,
2382
+ "notNull": true,
2383
+ "autoincrement": false
2384
+ },
2385
+ "schema_id": {
2386
+ "name": "schema_id",
2387
+ "type": "text",
2388
+ "primaryKey": false,
2389
+ "notNull": false,
2390
+ "autoincrement": false
2391
+ },
2392
+ "status": {
2393
+ "name": "status",
2394
+ "type": "text",
2395
+ "primaryKey": false,
2396
+ "notNull": true,
2397
+ "autoincrement": false
2398
+ },
2399
+ "started_at": {
2400
+ "name": "started_at",
2401
+ "type": "integer",
2402
+ "primaryKey": false,
2403
+ "notNull": true,
2404
+ "autoincrement": false
2405
+ },
2406
+ "completed_at": {
2407
+ "name": "completed_at",
2408
+ "type": "integer",
2409
+ "primaryKey": false,
2410
+ "notNull": false,
2411
+ "autoincrement": false
2412
+ },
2413
+ "error_message": {
2414
+ "name": "error_message",
2415
+ "type": "text",
2416
+ "primaryKey": false,
2417
+ "notNull": false,
2418
+ "autoincrement": false
2419
+ },
2420
+ "error_step": {
2421
+ "name": "error_step",
2422
+ "type": "text",
2423
+ "primaryKey": false,
2424
+ "notNull": false,
2425
+ "autoincrement": false
2426
+ },
2427
+ "error_details": {
2428
+ "name": "error_details",
2429
+ "type": "text",
2430
+ "primaryKey": false,
2431
+ "notNull": false,
2432
+ "autoincrement": false
2433
+ },
2434
+ "persisted_snapshot": {
2435
+ "name": "persisted_snapshot",
2436
+ "type": "text",
2437
+ "primaryKey": false,
2438
+ "notNull": true,
2439
+ "autoincrement": false
2440
+ },
2441
+ "seed_id": {
2442
+ "name": "seed_id",
2443
+ "type": "text",
2444
+ "primaryKey": false,
2445
+ "notNull": false,
2446
+ "autoincrement": false
2447
+ },
2448
+ "existing_seed_uid": {
2449
+ "name": "existing_seed_uid",
2450
+ "type": "text",
2451
+ "primaryKey": false,
2452
+ "notNull": false,
2453
+ "autoincrement": false
2454
+ },
2455
+ "created_at": {
2456
+ "name": "created_at",
2457
+ "type": "integer",
2458
+ "primaryKey": false,
2459
+ "notNull": false,
2460
+ "autoincrement": false
2461
+ },
2462
+ "updated_at": {
2463
+ "name": "updated_at",
2464
+ "type": "integer",
2465
+ "primaryKey": false,
2466
+ "notNull": false,
2467
+ "autoincrement": false
2468
+ }
2469
+ },
2470
+ "indexes": {},
2471
+ "foreignKeys": {},
2472
+ "compositePrimaryKeys": {},
2473
+ "uniqueConstraints": {},
2474
+ "checkConstraints": {}
2475
+ },
2476
+ "schemas": {
2477
+ "name": "schemas",
2478
+ "columns": {
2479
+ "id": {
2480
+ "name": "id",
2481
+ "type": "integer",
2482
+ "primaryKey": true,
2483
+ "notNull": true,
2484
+ "autoincrement": true
2485
+ },
2486
+ "name": {
2487
+ "name": "name",
2488
+ "type": "text",
2489
+ "primaryKey": false,
2490
+ "notNull": true,
2491
+ "autoincrement": false
2492
+ },
2493
+ "version": {
2494
+ "name": "version",
2495
+ "type": "integer",
2496
+ "primaryKey": false,
2497
+ "notNull": true,
2498
+ "autoincrement": false
2499
+ },
2500
+ "schema_file_id": {
2501
+ "name": "schema_file_id",
2502
+ "type": "text",
2503
+ "primaryKey": false,
2504
+ "notNull": false,
2505
+ "autoincrement": false
2506
+ },
2507
+ "schema_data": {
2508
+ "name": "schema_data",
2509
+ "type": "text",
2510
+ "primaryKey": false,
2511
+ "notNull": false,
2512
+ "autoincrement": false
2513
+ },
2514
+ "is_draft": {
2515
+ "name": "is_draft",
2516
+ "type": "integer",
2517
+ "primaryKey": false,
2518
+ "notNull": false,
2519
+ "autoincrement": false
2520
+ },
2521
+ "is_edited": {
2522
+ "name": "is_edited",
2523
+ "type": "integer",
2524
+ "primaryKey": false,
2525
+ "notNull": false,
2526
+ "autoincrement": false
2527
+ },
2528
+ "created_at": {
2529
+ "name": "created_at",
2530
+ "type": "integer",
2531
+ "primaryKey": false,
2532
+ "notNull": false,
2533
+ "autoincrement": false
2534
+ },
2535
+ "updated_at": {
2536
+ "name": "updated_at",
2537
+ "type": "integer",
2538
+ "primaryKey": false,
2539
+ "notNull": false,
2540
+ "autoincrement": false
2541
+ }
2542
+ },
2543
+ "indexes": {
2544
+ "unique_schema_schema_file_id": {
2545
+ "name": "unique_schema_schema_file_id",
2546
+ "columns": [
2547
+ "schema_file_id"
2548
+ ],
2549
+ "isUnique": true
2550
+ }
2551
+ },
2552
+ "foreignKeys": {},
2553
+ "compositePrimaryKeys": {},
2554
+ "uniqueConstraints": {},
2555
+ "checkConstraints": {}
2556
+ },
2557
+ "seeds": {
2558
+ "name": "seeds",
2559
+ "columns": {
2560
+ "local_id": {
2561
+ "name": "local_id",
2562
+ "type": "text",
2563
+ "primaryKey": false,
2564
+ "notNull": false,
2565
+ "autoincrement": false
2566
+ },
2567
+ "uid": {
2568
+ "name": "uid",
2569
+ "type": "text",
2570
+ "primaryKey": false,
2571
+ "notNull": false,
2572
+ "autoincrement": false
2573
+ },
2574
+ "schema_uid": {
2575
+ "name": "schema_uid",
2576
+ "type": "text",
2577
+ "primaryKey": false,
2578
+ "notNull": false,
2579
+ "autoincrement": false
2580
+ },
2581
+ "type": {
2582
+ "name": "type",
2583
+ "type": "text",
2584
+ "primaryKey": false,
2585
+ "notNull": false,
2586
+ "autoincrement": false
2587
+ },
2588
+ "publisher": {
2589
+ "name": "publisher",
2590
+ "type": "text",
2591
+ "primaryKey": false,
2592
+ "notNull": false,
2593
+ "autoincrement": false
2594
+ },
2595
+ "attestation_raw": {
2596
+ "name": "attestation_raw",
2597
+ "type": "text",
2598
+ "primaryKey": false,
2599
+ "notNull": false,
2600
+ "autoincrement": false
2601
+ },
2602
+ "attestation_created_at": {
2603
+ "name": "attestation_created_at",
2604
+ "type": "integer",
2605
+ "primaryKey": false,
2606
+ "notNull": false,
2607
+ "autoincrement": false
2608
+ },
2609
+ "created_at": {
2610
+ "name": "created_at",
2611
+ "type": "integer",
2612
+ "primaryKey": false,
2613
+ "notNull": false,
2614
+ "autoincrement": false
2615
+ },
2616
+ "updated_at": {
2617
+ "name": "updated_at",
2618
+ "type": "integer",
2619
+ "primaryKey": false,
2620
+ "notNull": false,
2621
+ "autoincrement": false
2622
+ },
2623
+ "_marked_for_deletion": {
2624
+ "name": "_marked_for_deletion",
2625
+ "type": "integer",
2626
+ "primaryKey": false,
2627
+ "notNull": false,
2628
+ "autoincrement": false
2629
+ },
2630
+ "revoked_at": {
2631
+ "name": "revoked_at",
2632
+ "type": "integer",
2633
+ "primaryKey": false,
2634
+ "notNull": false,
2635
+ "autoincrement": false
2636
+ }
2637
+ },
2638
+ "indexes": {
2639
+ "seeds_local_id_unique": {
2640
+ "name": "seeds_local_id_unique",
2641
+ "columns": [
2642
+ "local_id"
2643
+ ],
2644
+ "isUnique": true
2645
+ }
2646
+ },
2647
+ "foreignKeys": {},
2648
+ "compositePrimaryKeys": {},
2649
+ "uniqueConstraints": {},
2650
+ "checkConstraints": {}
2651
+ },
2652
+ "upload_processes": {
2653
+ "name": "upload_processes",
2654
+ "columns": {
2655
+ "id": {
2656
+ "name": "id",
2657
+ "type": "integer",
2658
+ "primaryKey": true,
2659
+ "notNull": true,
2660
+ "autoincrement": true
2661
+ },
2662
+ "reimbursement_confirmed": {
2663
+ "name": "reimbursement_confirmed",
2664
+ "type": "integer",
2665
+ "primaryKey": false,
2666
+ "notNull": true,
2667
+ "autoincrement": false
2668
+ },
2669
+ "reimbursement_transaction_id": {
2670
+ "name": "reimbursement_transaction_id",
2671
+ "type": "text",
2672
+ "primaryKey": false,
2673
+ "notNull": false,
2674
+ "autoincrement": false
2675
+ },
2676
+ "transaction_keys": {
2677
+ "name": "transaction_keys",
2678
+ "type": "text",
2679
+ "primaryKey": false,
2680
+ "notNull": false,
2681
+ "autoincrement": false
2682
+ },
2683
+ "persisted_snapshot": {
2684
+ "name": "persisted_snapshot",
2685
+ "type": "text",
2686
+ "primaryKey": false,
2687
+ "notNull": true,
2688
+ "autoincrement": false
2689
+ },
2690
+ "created_at": {
2691
+ "name": "created_at",
2692
+ "type": "integer",
2693
+ "primaryKey": false,
2694
+ "notNull": false,
2695
+ "autoincrement": false
2696
+ },
2697
+ "updated_at": {
2698
+ "name": "updated_at",
2699
+ "type": "integer",
2700
+ "primaryKey": false,
2701
+ "notNull": false,
2702
+ "autoincrement": false
2703
+ }
2704
+ },
2705
+ "indexes": {},
2706
+ "foreignKeys": {},
2707
+ "compositePrimaryKeys": {},
2708
+ "uniqueConstraints": {},
2709
+ "checkConstraints": {}
2710
+ },
2711
+ "versions": {
2712
+ "name": "versions",
2713
+ "columns": {
2714
+ "local_id": {
2715
+ "name": "local_id",
2716
+ "type": "text",
2717
+ "primaryKey": false,
2718
+ "notNull": false,
2719
+ "autoincrement": false
2720
+ },
2721
+ "uid": {
2722
+ "name": "uid",
2723
+ "type": "text",
2724
+ "primaryKey": false,
2725
+ "notNull": false,
2726
+ "autoincrement": false
2727
+ },
2728
+ "seed_local_id": {
2729
+ "name": "seed_local_id",
2730
+ "type": "text",
2731
+ "primaryKey": false,
2732
+ "notNull": false,
2733
+ "autoincrement": false
2734
+ },
2735
+ "seed_uid": {
2736
+ "name": "seed_uid",
2737
+ "type": "text",
2738
+ "primaryKey": false,
2739
+ "notNull": false,
2740
+ "autoincrement": false
2741
+ },
2742
+ "seed_type": {
2743
+ "name": "seed_type",
2744
+ "type": "text",
2745
+ "primaryKey": false,
2746
+ "notNull": false,
2747
+ "autoincrement": false
2748
+ },
2749
+ "note": {
2750
+ "name": "note",
2751
+ "type": "text",
2752
+ "primaryKey": false,
2753
+ "notNull": false,
2754
+ "autoincrement": false
2755
+ },
2756
+ "created_at": {
2757
+ "name": "created_at",
2758
+ "type": "integer",
2759
+ "primaryKey": false,
2760
+ "notNull": false,
2761
+ "autoincrement": false
2762
+ },
2763
+ "updated_at": {
2764
+ "name": "updated_at",
2765
+ "type": "integer",
2766
+ "primaryKey": false,
2767
+ "notNull": false,
2768
+ "autoincrement": false
2769
+ },
2770
+ "attestation_created_at": {
2771
+ "name": "attestation_created_at",
2772
+ "type": "integer",
2773
+ "primaryKey": false,
2774
+ "notNull": false,
2775
+ "autoincrement": false
2776
+ },
2777
+ "attestation_raw": {
2778
+ "name": "attestation_raw",
2779
+ "type": "text",
2780
+ "primaryKey": false,
2781
+ "notNull": false,
2782
+ "autoincrement": false
2783
+ },
2784
+ "publisher": {
2785
+ "name": "publisher",
2786
+ "type": "text",
2787
+ "primaryKey": false,
2788
+ "notNull": false,
2789
+ "autoincrement": false
2790
+ }
2791
+ },
2792
+ "indexes": {
2793
+ "versions_local_id_unique": {
2794
+ "name": "versions_local_id_unique",
2795
+ "columns": [
2796
+ "local_id"
2797
+ ],
2798
+ "isUnique": true
2799
+ }
2800
+ },
2801
+ "foreignKeys": {},
2802
+ "compositePrimaryKeys": {},
2803
+ "uniqueConstraints": {},
2804
+ "checkConstraints": {}
2805
+ },
2806
+ "arweave_l1_finalize_jobs": {
2807
+ "name": "arweave_l1_finalize_jobs",
2808
+ "columns": {
2809
+ "id": {
2810
+ "name": "id",
2811
+ "type": "integer",
2812
+ "primaryKey": true,
2813
+ "notNull": true,
2814
+ "autoincrement": true
2815
+ },
2816
+ "seed_local_id": {
2817
+ "name": "seed_local_id",
2818
+ "type": "text",
2819
+ "primaryKey": false,
2820
+ "notNull": true,
2821
+ "autoincrement": false
2822
+ },
2823
+ "data_item_id": {
2824
+ "name": "data_item_id",
2825
+ "type": "text",
2826
+ "primaryKey": false,
2827
+ "notNull": true,
2828
+ "autoincrement": false
2829
+ },
2830
+ "l1_transaction_id": {
2831
+ "name": "l1_transaction_id",
2832
+ "type": "text",
2833
+ "primaryKey": false,
2834
+ "notNull": false,
2835
+ "autoincrement": false
2836
+ },
2837
+ "bundle_id": {
2838
+ "name": "bundle_id",
2839
+ "type": "text",
2840
+ "primaryKey": false,
2841
+ "notNull": false,
2842
+ "autoincrement": false
2843
+ },
2844
+ "version_local_id": {
2845
+ "name": "version_local_id",
2846
+ "type": "text",
2847
+ "primaryKey": false,
2848
+ "notNull": false,
2849
+ "autoincrement": false
2850
+ },
2851
+ "item_property_name": {
2852
+ "name": "item_property_name",
2853
+ "type": "text",
2854
+ "primaryKey": false,
2855
+ "notNull": false,
2856
+ "autoincrement": false
2857
+ },
2858
+ "phase": {
2859
+ "name": "phase",
2860
+ "type": "text",
2861
+ "primaryKey": false,
2862
+ "notNull": true,
2863
+ "autoincrement": false
2864
+ },
2865
+ "status_json": {
2866
+ "name": "status_json",
2867
+ "type": "text",
2868
+ "primaryKey": false,
2869
+ "notNull": false,
2870
+ "autoincrement": false
2871
+ },
2872
+ "error_message": {
2873
+ "name": "error_message",
2874
+ "type": "text",
2875
+ "primaryKey": false,
2876
+ "notNull": false,
2877
+ "autoincrement": false
2878
+ },
2879
+ "created_at": {
2880
+ "name": "created_at",
2881
+ "type": "integer",
2882
+ "primaryKey": false,
2883
+ "notNull": true,
2884
+ "autoincrement": false
2885
+ },
2886
+ "updated_at": {
2887
+ "name": "updated_at",
2888
+ "type": "integer",
2889
+ "primaryKey": false,
2890
+ "notNull": true,
2891
+ "autoincrement": false
2892
+ }
2893
+ },
2894
+ "indexes": {
2895
+ "arweave_l1_finalize_jobs_data_item_id_unique": {
2896
+ "name": "arweave_l1_finalize_jobs_data_item_id_unique",
2897
+ "columns": [
2898
+ "data_item_id"
2899
+ ],
2900
+ "isUnique": true
2901
+ }
2902
+ },
2903
+ "foreignKeys": {},
2904
+ "compositePrimaryKeys": {},
2905
+ "uniqueConstraints": {},
2906
+ "checkConstraints": {}
2907
+ },
2908
+ "eas_sync_processes": {
2909
+ "name": "eas_sync_processes",
2910
+ "columns": {
2911
+ "id": {
2912
+ "name": "id",
2913
+ "type": "integer",
2914
+ "primaryKey": true,
2915
+ "notNull": true,
2916
+ "autoincrement": true
2917
+ },
2918
+ "status": {
2919
+ "name": "status",
2920
+ "type": "text",
2921
+ "primaryKey": false,
2922
+ "notNull": true,
2923
+ "autoincrement": false
2924
+ },
2925
+ "started_at": {
2926
+ "name": "started_at",
2927
+ "type": "integer",
2928
+ "primaryKey": false,
2929
+ "notNull": true,
2930
+ "autoincrement": false
2931
+ },
2932
+ "completed_at": {
2933
+ "name": "completed_at",
2934
+ "type": "integer",
2935
+ "primaryKey": false,
2936
+ "notNull": false,
2937
+ "autoincrement": false
2938
+ },
2939
+ "request_payload": {
2940
+ "name": "request_payload",
2941
+ "type": "text",
2942
+ "primaryKey": false,
2943
+ "notNull": true,
2944
+ "autoincrement": false
2945
+ },
2946
+ "error_message": {
2947
+ "name": "error_message",
2948
+ "type": "text",
2949
+ "primaryKey": false,
2950
+ "notNull": false,
2951
+ "autoincrement": false
2952
+ },
2953
+ "error_details": {
2954
+ "name": "error_details",
2955
+ "type": "text",
2956
+ "primaryKey": false,
2957
+ "notNull": false,
2958
+ "autoincrement": false
2959
+ },
2960
+ "persisted_snapshot": {
2961
+ "name": "persisted_snapshot",
2962
+ "type": "text",
2963
+ "primaryKey": false,
2964
+ "notNull": true,
2965
+ "autoincrement": false
2966
+ },
2967
+ "created_at": {
2968
+ "name": "created_at",
2969
+ "type": "integer",
2970
+ "primaryKey": false,
2971
+ "notNull": false,
2972
+ "autoincrement": false
2973
+ },
2974
+ "updated_at": {
2975
+ "name": "updated_at",
2976
+ "type": "integer",
2977
+ "primaryKey": false,
2978
+ "notNull": false,
2979
+ "autoincrement": false
2980
+ }
2981
+ },
2982
+ "indexes": {},
2983
+ "foreignKeys": {},
2984
+ "compositePrimaryKeys": {},
2985
+ "uniqueConstraints": {},
2986
+ "checkConstraints": {}
2987
+ }
2988
+ },
2989
+ "views": {},
2990
+ "enums": {},
2991
+ "_meta": {
2992
+ "schemas": {},
2993
+ "tables": {},
2994
+ "columns": {}
2995
+ },
2996
+ "internal": {
2997
+ "indexes": {}
2998
+ }
2999
+ }`;
3000
+
3001
+ var drizzleFiles = /*#__PURE__*/Object.freeze({
3002
+ __proto__: null,
3003
+ journalJson: journalJson,
3004
+ migrationSql_0000_married_malice: migrationSql_0000_married_malice,
3005
+ migrationSql_0001_sweet_bruce_banner: migrationSql_0001_sweet_bruce_banner,
3006
+ migrationSql_0002_bitter_proudstar: migrationSql_0002_bitter_proudstar,
3007
+ migrationSql_0003_cultured_senator_kelly: migrationSql_0003_cultured_senator_kelly,
3008
+ migrationSql_0004_add_publisher_to_seeds: migrationSql_0004_add_publisher_to_seeds,
3009
+ migrationSql_0005_bright_lily_hollister: migrationSql_0005_bright_lily_hollister,
3010
+ migrationSql_0006_add_publisher_to_versions_and_metadata: migrationSql_0006_add_publisher_to_versions_and_metadata,
3011
+ migrationSql_0007_add_required_to_properties: migrationSql_0007_add_required_to_properties,
3012
+ migrationSql_0008_add_revoked_at_to_seeds: migrationSql_0008_add_revoked_at_to_seeds,
3013
+ migrationSql_0009_happy_namor: migrationSql_0009_happy_namor,
3014
+ migrationSql_0010_add_arweave_l1_finalize_jobs: migrationSql_0010_add_arweave_l1_finalize_jobs,
3015
+ migrationSql_0011_normalize_placeholder_uids: migrationSql_0011_normalize_placeholder_uids,
3016
+ migrationSql_0012_html_embedded_image_co_publish: migrationSql_0012_html_embedded_image_co_publish,
3017
+ migrationSql_0013_eas_sync_processes: migrationSql_0013_eas_sync_processes,
3018
+ snapshotJson: snapshotJson
3019
+ });
3020
+
3021
+ const logger$1 = debug('seedSdk:browser:db:Db');
3022
+ class BrowserDb {
3023
+ getAppDb() {
3024
+ return this.appDb;
3025
+ }
3026
+ isAppDbReady() {
3027
+ return !!this.appDb;
3028
+ }
3029
+ async prepareDb(filesDir) {
3030
+ logger$1('[Db.prepareDb] preparing database');
3031
+ this.filesDir = filesDir;
3032
+ try {
3033
+ // Copy drizzle migration files from src/db/drizzle to filesDir/db
3034
+ await this.copyDrizzleFiles(filesDir);
3035
+ // Ensure meta directory exists
3036
+ const metaDirPath = `${filesDir}/db/meta`;
3037
+ await BaseFileManager.createDirIfNotExists(metaDirPath);
3038
+ // Ensure _journal.json file exists in meta directory
3039
+ const journalFilePath = `${metaDirPath}/_journal.json`;
3040
+ const journalExists = await BaseFileManager.pathExists(journalFilePath);
3041
+ if (!journalExists) {
3042
+ await BaseFileManager.saveFile(journalFilePath, JSON.stringify({
3043
+ version: 1,
3044
+ dialect: 'sqlite',
3045
+ entries: [],
3046
+ }, null, 2));
3047
+ }
3048
+ // Wait for journal file to be fully written before proceeding with migration
3049
+ // This is critical in browser/OPFS where writes may not be immediately readable
3050
+ logger$1('[Db.prepareDb] waiting for journal file to be fully written...');
3051
+ await BaseFileManager.waitForFileWithContent(journalFilePath, 100, 5000);
3052
+ logger$1('[Db.prepareDb] journal file is ready');
3053
+ // Initialize SQLocalDrizzle with reactive: true to enable reactive queries
3054
+ const sqlocalDrizzle = new SQLocalDrizzle({
3055
+ databasePath: `${this.filesDir}/db/seed.db`,
3056
+ reactive: true // Enable reactive queries
3057
+ });
3058
+ const { driver, batchDriver } = sqlocalDrizzle;
3059
+ // Store SQLocalDrizzle instance for reactive queries
3060
+ this.sqlocalInstance = sqlocalDrizzle;
3061
+ // Create db instance but do NOT set this.appDb yet. restoreFromDb (and other
3062
+ // callers of getAppDb()) must not see the db until migrations have completed,
3063
+ // otherwise they may query tables (e.g. publish_processes) that don't exist yet.
3064
+ const db = drizzle(driver, batchDriver, {
3065
+ schema,
3066
+ });
3067
+ logger$1('[Db.prepareDb] database prepared');
3068
+ await this.runMigrations(db);
3069
+ this.appDb = db;
3070
+ const { backfillMetadataPropertyIds } = await import('./backfillMetadataPropertyIds-DzZw57iJ.js');
3071
+ await backfillMetadataPropertyIds();
3072
+ return this.appDb;
3073
+ }
3074
+ catch (error) {
3075
+ logger$1('[Db.prepareDb] error', JSON.stringify(error));
3076
+ throw error;
3077
+ }
3078
+ }
3079
+ // static async prepareDb(filesDir: string) {
3080
+ // console.log('prepareDb', filesDir)
3081
+ // if (Db.sqliteWasmClient) {
3082
+ // return this.dbId
3083
+ // }
3084
+ // this.filesDir = filesDir
3085
+ // this.pathToDb = `${filesDir}/db/${DB_NAME_APP}.db`
3086
+ // if (typeof document === 'undefined') {
3087
+ // return
3088
+ // }
3089
+ // let promiser
3090
+ // try {
3091
+ // let sqlite3Worker1Promiser
3092
+ // const sqliteWasm = await import('@sqlite.org/sqlite-wasm')
3093
+ // if (sqliteWasm && sqliteWasm.sqlite3Worker1Promiser) {
3094
+ // sqlite3Worker1Promiser = sqliteWasm.sqlite3Worker1Promiser
3095
+ // }
3096
+ // if (!sqlite3Worker1Promiser && window.sqlite3Worker1Promiser) {
3097
+ // sqlite3Worker1Promiser = window.sqlite3Worker1Promiser
3098
+ // }
3099
+ // if (!sqlite3Worker1Promiser) {
3100
+ // throw new Error('Failed to load sqlite3Worker1Promiser')
3101
+ // }
3102
+ // promiser = await new Promise<(event: string, config: Record<string, unknown>) => Promise<any>>((resolve) => {
3103
+ // const _promiser = sqlite3Worker1Promiser({
3104
+ // onready: () => {
3105
+ // resolve(_promiser);
3106
+ // },
3107
+ // });
3108
+ // }).catch((error) => {
3109
+ // console.error('Error from sqlite proxy server: ', JSON.stringify(error))
3110
+ // });
3111
+ // } catch ( e ) {
3112
+ // console.error('Error from sqlite proxy server: ', JSON.stringify(e))
3113
+ // }
3114
+ // if (!promiser) {
3115
+ // throw new Error('Failed to create promiser')
3116
+ // }
3117
+ // this.sqliteWasmClient = promiser
3118
+ // const responseGet = await this.sqliteWasmClient('config-get', {});
3119
+ // logger('[Db.prepareDb] Running SQLite3 version', responseGet.result.version.libVersion);
3120
+ // const responseOpen = await this.sqliteWasmClient('open', {
3121
+ // filename: `file:${filesDir}/db/${DB_NAME_APP}.db?vfs=opfs`,
3122
+ // });
3123
+ // const { dbId } = responseOpen;
3124
+ // logger(
3125
+ // '[Db.prepareDb] OPFS is available, created persisted database at',
3126
+ // responseOpen.result.filename.replace(/^file:(.*?)\?vfs=opfs/, '$1'),
3127
+ // );
3128
+ // logger('[Db.prepareDb] dbId', dbId)
3129
+ // this.dbId = dbId
3130
+ // await this.migrate()
3131
+ // }
3132
+ async connectToDb(filesDir) {
3133
+ return this.dbId;
3134
+ }
3135
+ async copyDrizzleFiles(filesDir) {
3136
+ logger$1('[Db.copyDrizzleFiles] copying drizzle migration files');
3137
+ try {
3138
+ // Ensure db directory exists
3139
+ const dbDirPath = `${filesDir}/db`;
3140
+ await BaseFileManager.createDirIfNotExists(dbDirPath);
3141
+ // Ensure meta directory exists
3142
+ const metaDirPath = `${dbDirPath}/meta`;
3143
+ await BaseFileManager.createDirIfNotExists(metaDirPath);
3144
+ // Parse journal JSON to get all migration entries
3145
+ const journal = JSON.parse(journalJson);
3146
+ const entries = journal.entries || [];
3147
+ if (entries.length === 0) {
3148
+ logger$1('[Db.copyDrizzleFiles] no migration entries found in journal');
3149
+ return;
3150
+ }
3151
+ // Copy each migration SQL file (always overwrite to ensure they're up-to-date)
3152
+ // Each migration is exported as a separate variable (e.g., migrationSql_0000_married_malice)
3153
+ for (let i = 0; i < entries.length; i++) {
3154
+ const entry = entries[i];
3155
+ const tag = entry.tag; // e.g., "0000_married_malice"
3156
+ const migrationFileName = `${tag}.sql`;
3157
+ const migrationPath = `${dbDirPath}/${migrationFileName}`;
3158
+ // Get the SQL for this migration from the exported variable
3159
+ const migrationVarName = `migrationSql_${tag}`;
3160
+ const migrationContent = drizzleFiles[migrationVarName];
3161
+ if (!migrationContent) {
3162
+ logger$1(`[Db.copyDrizzleFiles] ERROR: No migration content found for ${migrationFileName} (variable: ${migrationVarName})`);
3163
+ throw new Error(`No migration content found for ${migrationFileName}. Expected variable: ${migrationVarName}`);
3164
+ }
3165
+ await BaseFileManager.saveFile(migrationPath, migrationContent.trim());
3166
+ logger$1(`[Db.copyDrizzleFiles] copied/updated migration SQL file: ${migrationFileName}`);
3167
+ }
3168
+ // Copy journal JSON file (always overwrite to ensure it's up-to-date with all migrations)
3169
+ const journalPath = `${metaDirPath}/_journal.json`;
3170
+ await BaseFileManager.saveFile(journalPath, journalJson);
3171
+ logger$1('[Db.copyDrizzleFiles] copied/updated journal JSON file');
3172
+ // Copy snapshot JSON file (use the latest snapshot based on the highest idx in journal)
3173
+ // Snapshot files are named like: 0000_snapshot.json, 0001_snapshot.json, etc.
3174
+ // The tag format is like "0000_married_malice", so we extract the numeric prefix
3175
+ const latestEntry = entries[entries.length - 1];
3176
+ const tagPrefixMatch = latestEntry.tag.match(/^(\d+_)/);
3177
+ const tagPrefix = tagPrefixMatch ? tagPrefixMatch[1] : '0000_';
3178
+ const snapshotFileName = `${tagPrefix}snapshot.json`;
3179
+ const snapshotPath = `${metaDirPath}/${snapshotFileName}`;
3180
+ // Always overwrite snapshot to ensure it's up-to-date
3181
+ await BaseFileManager.saveFile(snapshotPath, snapshotJson);
3182
+ logger$1(`[Db.copyDrizzleFiles] copied/updated snapshot JSON file: ${snapshotFileName}`);
3183
+ logger$1('[Db.copyDrizzleFiles] drizzle files copied successfully');
3184
+ }
3185
+ catch (error) {
3186
+ logger$1('[Db.copyDrizzleFiles] error copying drizzle files', error);
3187
+ // Don't throw - the files might already exist or migration might work without them
3188
+ // The migration will fail later if the files are truly needed
3189
+ }
3190
+ }
3191
+ /** Internal migration runner. Used by prepareDb before appDb is set. */
3192
+ async runMigrations(db, pathToDbDir) {
3193
+ const migrationsFolder = pathToDbDir ?? `${this.filesDir}/db`;
3194
+ try {
3195
+ logger$1('[Db.runMigrations] calling readMigrationFiles');
3196
+ const migrations = readMigrationFiles({
3197
+ migrationsFolder,
3198
+ });
3199
+ logger$1('[Db.runMigrations] migrations', migrations);
3200
+ await migrate(db, async (queriesToRun) => {
3201
+ logger$1('queriesToRun', queriesToRun);
3202
+ for (const query of queriesToRun) {
3203
+ logger$1('query', query);
3204
+ await db.run(sql.raw(query));
3205
+ }
3206
+ }, {
3207
+ migrationsFolder,
3208
+ });
3209
+ logger$1('[Db.runMigrations] migrations completed');
3210
+ }
3211
+ catch (error) {
3212
+ logger$1('[Db.runMigrations] error', JSON.stringify(error));
3213
+ throw error;
3214
+ }
3215
+ }
3216
+ async migrate(pathToDbDir, _dbName, _dbId) {
3217
+ const targetDb = this.appDb;
3218
+ if (!targetDb) {
3219
+ throw new Error('Database not prepared');
3220
+ }
3221
+ await this.runMigrations(targetDb, pathToDbDir);
3222
+ }
3223
+ // Legacy commented migrate/exec implementation archived at
3224
+ // docs/archive/commented/browser-Db-legacy-migrate.ts.txt
3225
+ /**
3226
+ * Execute a reactive query that emits new results whenever the underlying data changes.
3227
+ *
3228
+ * Supports two usage patterns:
3229
+ * 1. SQL tag function: liveQuery((sql) => sql`SELECT * FROM models`)
3230
+ * 2. Drizzle query builder: liveQuery(db.select().from(models))
3231
+ *
3232
+ * @param query - SQL query function or Drizzle query builder
3233
+ * @returns Observable that emits arrays of query results
3234
+ *
3235
+ * @example
3236
+ * ```typescript
3237
+ * // Using SQL tag function
3238
+ * const models$ = Db.liveQuery<ModelRow>(
3239
+ * (sql) => sql`SELECT * FROM models WHERE schema_file_id = ${schemaId}`
3240
+ * )
3241
+ *
3242
+ * // Using Drizzle query builder
3243
+ * const models$ = Db.liveQuery<ModelRow>(
3244
+ * appDb.select().from(models).where(eq(models.schemaFileId, schemaId))
3245
+ * )
3246
+ *
3247
+ * models$.subscribe(models => {
3248
+ * console.log('Models updated:', models)
3249
+ * })
3250
+ * ```
3251
+ */
3252
+ liveQuery(query) {
3253
+ if (!this.sqlocalInstance) {
3254
+ throw new Error('Database not initialized. Call prepareDb first.');
3255
+ }
3256
+ if (!this.sqlocalInstance.reactiveQuery) {
3257
+ throw new Error('Reactive queries not enabled. Initialize SQLocalDrizzle with reactive: true.');
3258
+ }
3259
+ const baseObservable = new Observable((subscriber) => {
3260
+ const reactiveQueryResult = this.sqlocalInstance.reactiveQuery(query);
3261
+ const subscription = reactiveQueryResult.subscribe((data) => {
3262
+ subscriber.next(data);
3263
+ }, (err) => {
3264
+ console.error('[BaseDb.liveQuery] SQLocal reactiveQuery error:', err);
3265
+ subscriber.error(err);
3266
+ });
3267
+ return () => {
3268
+ subscription.unsubscribe();
3269
+ };
3270
+ });
3271
+ // Compare stable JSON snapshots via keySelector. SQLocal may reuse one array reference
3272
+ // and mutate rows in place; comparing (prev, curr) on the same reference makes
3273
+ // JSON.stringify(prev) === JSON.stringify(curr) after mutation and suppresses emissions.
3274
+ return baseObservable.pipe(distinctUntilChanged((a, b) => a === b, (x) => JSON.stringify(x)));
3275
+ }
3276
+ }
3277
+ BaseDb.configure(new BrowserDb());
3278
+
3279
+ const logger = debug("seedSdk:browser:ArweaveClient");
3280
+ // Cached Arweave instance (keyed by gateway so setHost / protocol changes apply)
3281
+ let _arweaveInstance = null;
3282
+ let _arweaveGatewayKey = null;
3283
+ /**
3284
+ * Get or create the Arweave instance for browser
3285
+ */
3286
+ const getArweaveInstance = () => {
3287
+ const gatewayKey = `${BaseArweaveClient.getProtocol()}://${BaseArweaveClient.getHost()}`;
3288
+ if (_arweaveInstance && _arweaveGatewayKey === gatewayKey) {
3289
+ return _arweaveInstance;
3290
+ }
3291
+ _arweaveGatewayKey = gatewayKey;
3292
+ const host = BaseArweaveClient.getHost();
3293
+ const protocol = BaseArweaveClient.getProtocol();
3294
+ // Handle both ES modules and CommonJS exports from arweave package
3295
+ if ("default" in Arweave && typeof Arweave.default?.init === "function") {
3296
+ _arweaveInstance = Arweave.default.init({
3297
+ host,
3298
+ protocol,
3299
+ });
3300
+ }
3301
+ else {
3302
+ _arweaveInstance = Arweave.init({
3303
+ host,
3304
+ protocol,
3305
+ });
3306
+ }
3307
+ return _arweaveInstance;
3308
+ };
3309
+ class BrowserArweaveClient {
3310
+ getArweaveClient() {
3311
+ return new GraphQLClient(BaseArweaveClient.getEndpoint());
3312
+ }
3313
+ async getTransactionStatus(transactionId) {
3314
+ const url = BaseArweaveClient.getStatusUrl(transactionId);
3315
+ try {
3316
+ const response = await fetch(url);
3317
+ if (response.status === 404) {
3318
+ return {
3319
+ status: 404,
3320
+ confirmed: null,
3321
+ };
3322
+ }
3323
+ if (!response.ok) {
3324
+ return {
3325
+ status: response.status,
3326
+ confirmed: null,
3327
+ };
3328
+ }
3329
+ if (response.body) {
3330
+ await response.body.cancel();
3331
+ }
3332
+ return {
3333
+ status: 200,
3334
+ confirmed: null,
3335
+ };
3336
+ }
3337
+ catch (error) {
3338
+ logger("Error fetching transaction status:", error);
3339
+ return {
3340
+ status: 500,
3341
+ confirmed: null,
3342
+ };
3343
+ }
3344
+ }
3345
+ async getTransactionData(transactionId, options) {
3346
+ const arweave = getArweaveInstance();
3347
+ try {
3348
+ const data = await arweave.transactions.getData(transactionId, {
3349
+ decode: options?.decode ?? true,
3350
+ string: options?.string ?? false,
3351
+ });
3352
+ if (options?.string && typeof data === "string") {
3353
+ return data;
3354
+ }
3355
+ // Ensure we return Uint8Array
3356
+ if (data instanceof Uint8Array) {
3357
+ return data;
3358
+ }
3359
+ // Handle string data when not requesting string
3360
+ if (typeof data === "string") {
3361
+ return new TextEncoder().encode(data);
3362
+ }
3363
+ return data;
3364
+ }
3365
+ catch (error) {
3366
+ logger("Error fetching transaction data:", error);
3367
+ throw error;
3368
+ }
3369
+ }
3370
+ async getTransactionTags(transactionId) {
3371
+ const client = this.getArweaveClient();
3372
+ try {
3373
+ const result = await client.request(GET_TRANSACTION_TAGS, { transactionId });
3374
+ if (!result.tags?.tags) {
3375
+ return [];
3376
+ }
3377
+ return result.tags.tags.map((tag) => ({
3378
+ name: tag.name,
3379
+ value: tag.value,
3380
+ }));
3381
+ }
3382
+ catch (error) {
3383
+ logger("Error fetching transaction tags:", error);
3384
+ return [];
3385
+ }
3386
+ }
3387
+ async createTransaction(data, options) {
3388
+ const arweave = getArweaveInstance();
3389
+ const tx = await arweave.createTransaction({
3390
+ data,
3391
+ });
3392
+ // Add tags if provided
3393
+ if (options?.tags) {
3394
+ for (const tag of options.tags) {
3395
+ tx.addTag(tag.name, tag.value);
3396
+ }
3397
+ }
3398
+ return tx;
3399
+ }
3400
+ async downloadFiles(params) {
3401
+ const { transactionIds, excludedTransactions } = params;
3402
+ const results = [];
3403
+ const baseUrl = BaseArweaveClient.getBaseUrl();
3404
+ for (const transactionId of transactionIds) {
3405
+ // Skip excluded transactions
3406
+ if (excludedTransactions?.has(transactionId)) {
3407
+ continue;
3408
+ }
3409
+ try {
3410
+ const url = `${baseUrl}/raw/${transactionId}`;
3411
+ const response = await fetch(url);
3412
+ if (!response.ok) {
3413
+ results.push({
3414
+ transactionId,
3415
+ success: false,
3416
+ error: `HTTP ${response.status}: ${response.statusText}`,
3417
+ });
3418
+ continue;
3419
+ }
3420
+ const arrayBuffer = await response.arrayBuffer();
3421
+ const data = new Uint8Array(arrayBuffer);
3422
+ // Detect content type
3423
+ const contentType = response.headers.get("content-type") || undefined;
3424
+ results.push({
3425
+ transactionId,
3426
+ success: true,
3427
+ contentType,
3428
+ data,
3429
+ });
3430
+ }
3431
+ catch (error) {
3432
+ logger(`Error downloading transaction ${transactionId}:`, error);
3433
+ results.push({
3434
+ transactionId,
3435
+ success: false,
3436
+ error: error instanceof Error ? error.message : String(error),
3437
+ });
3438
+ }
3439
+ }
3440
+ return results;
3441
+ }
3442
+ }
3443
+ BaseArweaveClient.configure(new BrowserArweaveClient());
3444
+
3445
+ class BrowserEasClient {
3446
+ getEasClient() {
3447
+ if (!this.easClient) {
3448
+ this.easClient = new GraphQLClient(EAS_ENDPOINT);
3449
+ }
3450
+ return this.easClient;
3451
+ }
3452
+ }
3453
+ BaseEasClient.configure(new BrowserEasClient());
3454
+
3455
+ class BrowserQueryClient {
3456
+ getQueryClient() {
3457
+ const reactQueryClient = new QueryClient({
3458
+ defaultOptions: {
3459
+ queries: {
3460
+ networkMode: 'offlineFirst',
3461
+ gcTime: 1000 * 60 * 60 * 24, // 24 hours
3462
+ },
3463
+ },
3464
+ });
3465
+ const queryClient = {
3466
+ fetchQuery: async (options) => {
3467
+ const { queryKey, queryFn, networkMode, staleTime } = options;
3468
+ return reactQueryClient.fetchQuery({
3469
+ queryKey,
3470
+ queryFn,
3471
+ networkMode: networkMode,
3472
+ staleTime,
3473
+ });
3474
+ },
3475
+ getQueryData: (queryKey) => {
3476
+ return reactQueryClient.getQueryData(queryKey);
3477
+ },
3478
+ removeQueries: async (filters) => {
3479
+ await reactQueryClient.removeQueries(filters);
3480
+ },
3481
+ };
3482
+ return queryClient;
3483
+ }
3484
+ }
3485
+ BaseQueryClient.configure(new BrowserQueryClient());
3486
+
3487
+ function createPlatformServices() {
3488
+ return {
3489
+ pathResolver: new BrowserPathResolver(),
3490
+ fileManager: new BrowserFileManager(),
3491
+ db: new BrowserDb(),
3492
+ arweaveClient: new BrowserArweaveClient(),
3493
+ easClient: new BrowserEasClient(),
3494
+ queryClient: new BrowserQueryClient(),
3495
+ };
3496
+ }
3497
+
3498
+ export { createPlatformServices };
3499
+ //# sourceMappingURL=platform.browser.js.map