@seedprotocol/sdk 0.7.8 → 0.7.9-next.1177.ga3e08ed

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 (419) hide show
  1. package/README.md +1 -1
  2. package/dist/{ClientManager-B1r_8P5Z.js → ClientManager-GZfXErDX.js} +187 -1451
  3. package/dist/ClientManager-GZfXErDX.js.map +1 -0
  4. package/dist/{Item-CjTEShfk.js → Item-0oDoTPhi.js} +175 -238
  5. package/dist/Item-0oDoTPhi.js.map +1 -0
  6. package/dist/{ModelProperty-C3749Wjq.js → ModelProperty-i5flwzQG.js} +41 -40
  7. package/dist/ModelProperty-i5flwzQG.js.map +1 -0
  8. package/dist/{Schema-CX9CTtho.js → Schema-PFZwG9Nl.js} +88 -1623
  9. package/dist/Schema-PFZwG9Nl.js.map +1 -0
  10. package/dist/{SchemaValidationService-T5mqnY8q.js → SchemaValidationService-DnGKel4V.js} +7 -6
  11. package/dist/{SchemaValidationService-T5mqnY8q.js.map → SchemaValidationService-DnGKel4V.js.map} +1 -1
  12. package/dist/{backfillMetadataPropertyIds-DWWkh-Ex.js → backfillMetadataPropertyIds-BbxgavEQ.js} +4 -4
  13. package/dist/{backfillMetadataPropertyIds-DWWkh-Ex.js.map → backfillMetadataPropertyIds-BbxgavEQ.js.map} +1 -1
  14. package/dist/{changeFeed-DcsZ7deG.js → changeFeed-DKdVlUmt.js} +8 -7
  15. package/dist/changeFeed-DKdVlUmt.js.map +1 -0
  16. package/dist/configurePlatform-CrMafpMW.js +29 -0
  17. package/dist/configurePlatform-CrMafpMW.js.map +1 -0
  18. package/dist/db/drizzle/0024_merge_republished_ghost_seeds.sql +29 -0
  19. package/dist/db/drizzle/meta/0024_snapshot.json +1645 -0
  20. package/dist/db/drizzle/meta/_journal.json +7 -0
  21. package/dist/{detachRowsBeforeDelete-Bo_pky-R.js → detachRowsBeforeDelete-DXFYSHRR.js} +2 -3
  22. package/dist/{detachRowsBeforeDelete-Bo_pky-R.js.map → detachRowsBeforeDelete-DXFYSHRR.js.map} +1 -1
  23. package/dist/dist/{ClientManager-B1r_8P5Z.d.ts → ClientManager-GZfXErDX.d.ts} +323 -406
  24. package/dist/dist/ClientManager-GZfXErDX.d.ts.map +1 -0
  25. package/dist/dist/{Item-CjTEShfk.d.ts → Item-0oDoTPhi.d.ts} +85 -91
  26. package/dist/dist/Item-0oDoTPhi.d.ts.map +1 -0
  27. package/dist/dist/{ModelProperty-C3749Wjq.d.ts → ModelProperty-i5flwzQG.d.ts} +1 -1
  28. package/dist/dist/{ModelProperty-C3749Wjq.d.ts.map → ModelProperty-i5flwzQG.d.ts.map} +1 -1
  29. package/dist/dist/{Schema-CX9CTtho.d.ts → Schema-PFZwG9Nl.d.ts} +7 -183
  30. package/dist/dist/Schema-PFZwG9Nl.d.ts.map +1 -0
  31. package/dist/dist/{SchemaValidationService-T5mqnY8q.d.ts → SchemaValidationService-DnGKel4V.d.ts} +1 -1
  32. package/dist/dist/{SchemaValidationService-T5mqnY8q.d.ts.map → SchemaValidationService-DnGKel4V.d.ts.map} +1 -1
  33. package/dist/dist/{backfillMetadataPropertyIds-DWWkh-Ex.d.ts → backfillMetadataPropertyIds-BbxgavEQ.d.ts} +1 -1
  34. package/dist/dist/backfillMetadataPropertyIds-BbxgavEQ.d.ts.map +1 -0
  35. package/dist/dist/{changeFeed-DcsZ7deG.d.ts → changeFeed-DKdVlUmt.d.ts} +17 -20
  36. package/dist/dist/changeFeed-DKdVlUmt.d.ts.map +1 -0
  37. package/dist/dist/configurePlatform-CrMafpMW.d.ts +5 -0
  38. package/dist/dist/configurePlatform-CrMafpMW.d.ts.map +1 -0
  39. package/dist/dist/{detachRowsBeforeDelete-Bo_pky-R.d.ts → detachRowsBeforeDelete-DXFYSHRR.d.ts} +1 -1
  40. package/dist/dist/detachRowsBeforeDelete-DXFYSHRR.d.ts.map +1 -0
  41. package/dist/dist/{eas--9vtNkma.d.ts → eas-dyepi5jz.d.ts} +1 -1
  42. package/dist/dist/eas-dyepi5jz.d.ts.map +1 -0
  43. package/dist/dist/{errors-Do7v6RKu.d.ts → errors-C1qUEZ7A.d.ts} +5 -2
  44. package/dist/dist/errors-C1qUEZ7A.d.ts.map +1 -0
  45. package/dist/dist/{errors-rIWK7gwJ.d.ts → errors-D1zHAqjr.d.ts} +1 -1
  46. package/dist/dist/{errors-rIWK7gwJ.d.ts.map → errors-D1zHAqjr.d.ts.map} +1 -1
  47. package/dist/dist/eventBus-7vxTCc3a.d.ts +18 -0
  48. package/dist/dist/eventBus-7vxTCc3a.d.ts.map +1 -0
  49. package/dist/dist/findSeedRowsByUid-CT3sOXXw.d.ts +13 -0
  50. package/dist/dist/findSeedRowsByUid-CT3sOXXw.d.ts.map +1 -0
  51. package/dist/dist/{getItem-5j22EWWE.d.ts → getItem-Bhjecbia.d.ts} +1 -1
  52. package/dist/dist/getItem-Bhjecbia.d.ts.map +1 -0
  53. package/dist/dist/{getPublishPayload-BGl2SaGK.d.ts → getPublishPayload-DH4rMqXG.d.ts} +1 -1
  54. package/dist/dist/getPublishPayload-DH4rMqXG.d.ts.map +1 -0
  55. package/dist/dist/{getPublishUploads-DVsDx6Xf.d.ts → getPublishUploads-BzUIDA2G.d.ts} +5 -5
  56. package/dist/dist/getPublishUploads-BzUIDA2G.d.ts.map +1 -0
  57. package/dist/dist/index-CkYb3wcU.d.ts +14 -0
  58. package/dist/dist/index-CkYb3wcU.d.ts.map +1 -0
  59. package/dist/dist/{index-Dp4uyZYx.d.ts → index-DJmWkVIK.d.ts} +5 -5
  60. package/dist/dist/index-DJmWkVIK.d.ts.map +1 -0
  61. package/dist/dist/{index-C0SetTd1.d.ts → index-Dx_GTdyQ.d.ts} +1457 -1513
  62. package/dist/dist/index-Dx_GTdyQ.d.ts.map +1 -0
  63. package/dist/dist/{index-CZQrNqvq.d.ts → index-PbnKw2es.d.ts} +1 -1
  64. package/dist/dist/{index-CZQrNqvq.d.ts.map → index-PbnKw2es.d.ts.map} +1 -1
  65. package/dist/dist/{index.browser-Ll71Y_Dl.d.ts → index.browser-i9uPJice.d.ts} +13 -40
  66. package/dist/dist/{index.browser-Ll71Y_Dl.d.ts.map → index.browser-i9uPJice.d.ts.map} +1 -1
  67. package/dist/dist/{index.node-CgltN0cC.d.ts → index.node-CzMwMr_d.d.ts} +2 -45
  68. package/dist/dist/{index.node-CgltN0cC.d.ts.map → index.node-CzMwMr_d.d.ts.map} +1 -1
  69. package/dist/dist/minimumUpgradeVersion-BDhHvHtr.d.ts +9 -0
  70. package/dist/dist/minimumUpgradeVersion-BDhHvHtr.d.ts.map +1 -0
  71. package/dist/dist/{modelPropertyRecordSchemas-C_lYTzMr.d.ts → modelPropertyRecordSchemas-C5lW9aA-.d.ts} +1 -1
  72. package/dist/dist/modelPropertyRecordSchemas-C5lW9aA-.d.ts.map +1 -0
  73. package/dist/dist/platform.browser.d.ts +2 -2
  74. package/dist/dist/platform.node.d.ts +2 -2
  75. package/dist/dist/{property-pcDxNEpy.d.ts → property-BwYtg5Q_.d.ts} +3 -3
  76. package/dist/dist/property-BwYtg5Q_.d.ts.map +1 -0
  77. package/dist/dist/{propertyValidationRules-BEjN0f3-.d.ts → propertyValidationRules-CyHdpcPP.d.ts} +1 -1
  78. package/dist/dist/propertyValidationRules-CyHdpcPP.d.ts.map +1 -0
  79. package/dist/dist/{publishDraftGraph-I5yKe1Xz.d.ts → publishDraftGraph-C5F6b7GK.d.ts} +23 -6
  80. package/dist/dist/publishDraftGraph-C5F6b7GK.d.ts.map +1 -0
  81. package/dist/dist/{resolveModelForSyncedSeed-C5KXn6ex.d.ts → resolveModelForSyncedSeed-4gO9Hfn2.d.ts} +1 -1
  82. package/dist/dist/resolveModelForSyncedSeed-4gO9Hfn2.d.ts.map +1 -0
  83. package/dist/dist/syncDbWithEas-DUu_wjUG.d.ts +13 -0
  84. package/dist/dist/syncDbWithEas-DUu_wjUG.d.ts.map +1 -0
  85. package/dist/dist/{tolerantWebAccess-CIpS7RLk.d.ts → tolerantWebAccess-DecKDGen.d.ts} +1 -1
  86. package/dist/dist/{tolerantWebAccess-CIpS7RLk.d.ts.map → tolerantWebAccess-DecKDGen.d.ts.map} +1 -1
  87. package/dist/dist/{updateSeedRevokedAt-CR4zwn-6.d.ts → updateSeedRevokedAt-CP606vKs.d.ts} +1 -1
  88. package/dist/dist/updateSeedRevokedAt-CP606vKs.d.ts.map +1 -0
  89. package/dist/{eas--9vtNkma.js → eas-dyepi5jz.js} +3 -4
  90. package/dist/eas-dyepi5jz.js.map +1 -0
  91. package/dist/{errors-Do7v6RKu.js → errors-C1qUEZ7A.js} +12 -6
  92. package/dist/errors-C1qUEZ7A.js.map +1 -0
  93. package/dist/{errors-rIWK7gwJ.js → errors-D1zHAqjr.js} +46 -98
  94. package/dist/errors-D1zHAqjr.js.map +1 -0
  95. package/dist/eventBus-7vxTCc3a.js +64 -0
  96. package/dist/eventBus-7vxTCc3a.js.map +1 -0
  97. package/dist/findSeedRowsByUid-CT3sOXXw.js +47 -0
  98. package/dist/findSeedRowsByUid-CT3sOXXw.js.map +1 -0
  99. package/dist/{getItem-5j22EWWE.js → getItem-Bhjecbia.js} +5 -5
  100. package/dist/{getItem-5j22EWWE.js.map → getItem-Bhjecbia.js.map} +1 -1
  101. package/dist/{getPublishPayload-BGl2SaGK.js → getPublishPayload-DH4rMqXG.js} +27 -27
  102. package/dist/getPublishPayload-DH4rMqXG.js.map +1 -0
  103. package/dist/{getPublishUploads-DVsDx6Xf.js → getPublishUploads-BzUIDA2G.js} +64 -95
  104. package/dist/getPublishUploads-BzUIDA2G.js.map +1 -0
  105. package/dist/{index-CJK3F_MK.js → index-CkYb3wcU.js} +9 -8
  106. package/dist/index-CkYb3wcU.js.map +1 -0
  107. package/dist/{index-Dp4uyZYx.js → index-DJmWkVIK.js} +9 -8
  108. package/dist/index-DJmWkVIK.js.map +1 -0
  109. package/dist/{index-C0SetTd1.js → index-Dx_GTdyQ.js} +27 -463
  110. package/dist/index-Dx_GTdyQ.js.map +1 -0
  111. package/dist/{index-CZQrNqvq.js → index-PbnKw2es.js} +2 -2
  112. package/dist/index-PbnKw2es.js.map +1 -0
  113. package/dist/{index.browser-Ll71Y_Dl.js → index.browser-i9uPJice.js} +239 -179
  114. package/dist/index.browser-i9uPJice.js.map +1 -0
  115. package/dist/{index.node-CgltN0cC.js → index.node-CzMwMr_d.js} +51 -216
  116. package/dist/index.node-CzMwMr_d.js.map +1 -0
  117. package/dist/main.js +165 -241
  118. package/dist/main.js.map +1 -1
  119. package/dist/minimumUpgradeVersion-BDhHvHtr.js +81 -0
  120. package/dist/minimumUpgradeVersion-BDhHvHtr.js.map +1 -0
  121. package/dist/{modelPropertyRecordSchemas-C_lYTzMr.js → modelPropertyRecordSchemas-C5lW9aA-.js} +5 -5
  122. package/dist/{modelPropertyRecordSchemas-C_lYTzMr.js.map → modelPropertyRecordSchemas-C5lW9aA-.js.map} +1 -1
  123. package/dist/node.js +14 -221
  124. package/dist/node.js.map +1 -1
  125. package/dist/platform.browser.js +8 -7
  126. package/dist/platform.browser.js.map +1 -1
  127. package/dist/platform.node.js +7 -7
  128. package/dist/{property-pcDxNEpy.js → property-BwYtg5Q_.js} +8 -9
  129. package/dist/property-BwYtg5Q_.js.map +1 -0
  130. package/dist/{propertyValidationRules-BEjN0f3-.js → propertyValidationRules-CyHdpcPP.js} +10 -10
  131. package/dist/{propertyValidationRules-BEjN0f3-.js.map → propertyValidationRules-CyHdpcPP.js.map} +1 -1
  132. package/dist/{publishDraftGraph-I5yKe1Xz.js → publishDraftGraph-C5F6b7GK.js} +104 -35
  133. package/dist/publishDraftGraph-C5F6b7GK.js.map +1 -0
  134. package/dist/{resolveModelForSyncedSeed-C5KXn6ex.js → resolveModelForSyncedSeed-4gO9Hfn2.js} +3 -2
  135. package/dist/{resolveModelForSyncedSeed-C5KXn6ex.js.map → resolveModelForSyncedSeed-4gO9Hfn2.js.map} +1 -1
  136. package/dist/seedSchema/PendingWriteSchema.ts +3 -2
  137. package/dist/src/Item/Item.d.ts +1 -0
  138. package/dist/src/Item/Item.d.ts.map +1 -1
  139. package/dist/src/Item/service/actors/runPublish.d.ts.map +1 -1
  140. package/dist/src/ItemProperty/ItemProperty.d.ts +2 -2
  141. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  142. package/dist/src/ItemProperty/service/propertyMachine.d.ts +1 -1
  143. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  144. package/dist/src/Model/Model.d.ts.map +1 -1
  145. package/dist/src/Model/service/modelMachine.d.ts +0 -20
  146. package/dist/src/Model/service/modelMachine.d.ts.map +1 -1
  147. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +0 -20
  148. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  149. package/dist/src/Schema/service/schemaMachine.d.ts +1 -107
  150. package/dist/src/Schema/service/schemaMachine.d.ts.map +1 -1
  151. package/dist/src/Schema/validation.d.ts +0 -1
  152. package/dist/src/Schema/validation.d.ts.map +1 -1
  153. package/dist/src/browser/db/Db.d.ts +8 -3
  154. package/dist/src/browser/db/Db.d.ts.map +1 -1
  155. package/dist/src/browser/db/createSqlocalDrizzle.d.ts +20 -2
  156. package/dist/src/browser/db/createSqlocalDrizzle.d.ts.map +1 -1
  157. package/dist/src/browser/db/drizzleFiles.d.ts +3 -2
  158. package/dist/src/browser/db/drizzleFiles.d.ts.map +1 -1
  159. package/dist/src/browser/workers/FileDownloader.d.ts +1 -1
  160. package/dist/src/browser/workers/FileDownloader.d.ts.map +1 -1
  161. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  162. package/dist/src/client/actors/fileSystemInit.d.ts.map +1 -1
  163. package/dist/src/client/actors/platformClassesInit.d.ts +1 -1
  164. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  165. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  166. package/dist/src/client/clientManagerMachine.d.ts.map +1 -1
  167. package/dist/src/client/constants.d.ts +0 -51
  168. package/dist/src/client/constants.d.ts.map +1 -1
  169. package/dist/src/db/minimumUpgradeVersion.d.ts +33 -0
  170. package/dist/src/db/minimumUpgradeVersion.d.ts.map +1 -0
  171. package/dist/src/db/read/batchLatestPublishedVersionBySeedLocalIds.d.ts +2 -1
  172. package/dist/src/db/read/batchLatestPublishedVersionBySeedLocalIds.d.ts.map +1 -1
  173. package/dist/src/db/read/findSeedRowsByUid.d.ts +13 -0
  174. package/dist/src/db/read/findSeedRowsByUid.d.ts.map +1 -0
  175. package/dist/src/db/read/getItemData.d.ts.map +1 -1
  176. package/dist/src/db/read/getLatestPublishedVersionRow.d.ts +2 -1
  177. package/dist/src/db/read/getLatestPublishedVersionRow.d.ts.map +1 -1
  178. package/dist/src/db/read/getLatestVersionRow.d.ts +1 -1
  179. package/dist/src/db/read/getLatestVersionRow.d.ts.map +1 -1
  180. package/dist/src/db/read/getPublishPayload.d.ts +4 -0
  181. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  182. package/dist/src/db/read/getPublishUploads.d.ts +1 -3
  183. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  184. package/dist/src/db/read/getRelatedItemsForPublish.d.ts +2 -0
  185. package/dist/src/db/read/getRelatedItemsForPublish.d.ts.map +1 -1
  186. package/dist/src/db/read/itemLoads.d.ts +20 -0
  187. package/dist/src/db/read/itemLoads.d.ts.map +1 -0
  188. package/dist/src/db/read/publishDraftGraph.d.ts +7 -0
  189. package/dist/src/db/read/publishDraftGraph.d.ts.map +1 -1
  190. package/dist/src/db/read/resolveRelatedSeedRef.d.ts +4 -4
  191. package/dist/src/db/read/resolveRelatedSeedRef.d.ts.map +1 -1
  192. package/dist/src/db/read/subqueries/latestVersion.d.ts +14 -0
  193. package/dist/src/db/read/subqueries/latestVersion.d.ts.map +1 -0
  194. package/dist/src/db/read/subqueries/versionData.d.ts +2 -2
  195. package/dist/src/db/read/subqueries/versionData.d.ts.map +1 -1
  196. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  197. package/dist/src/db/write/applyPropertyAttestationUidsFromPublish.d.ts +6 -0
  198. package/dist/src/db/write/applyPropertyAttestationUidsFromPublish.d.ts.map +1 -1
  199. package/dist/src/db/write/easSyncProcess.d.ts +1 -1
  200. package/dist/src/db/write/easSyncProcess.d.ts.map +1 -1
  201. package/dist/src/db/write/updateVersionUid.d.ts +2 -2
  202. package/dist/src/db/write/updateVersionUid.d.ts.map +1 -1
  203. package/dist/src/events/files/download.d.ts +1 -10
  204. package/dist/src/events/files/download.d.ts.map +1 -1
  205. package/dist/src/events/item/easSyncManager.d.ts +0 -1
  206. package/dist/src/events/item/easSyncManager.d.ts.map +1 -1
  207. package/dist/src/events/item/index.d.ts.map +1 -1
  208. package/dist/src/events/item/syncDbWithEas.d.ts +0 -10
  209. package/dist/src/events/item/syncDbWithEas.d.ts.map +1 -1
  210. package/dist/src/helpers/FileManager/BaseFileManager.d.ts +1 -1
  211. package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  212. package/dist/src/helpers/FileManager/IFileManager.d.ts +7 -0
  213. package/dist/src/helpers/FileManager/IFileManager.d.ts.map +1 -1
  214. package/dist/src/helpers/FileManager/errors.d.ts +4 -1
  215. package/dist/src/helpers/FileManager/errors.d.ts.map +1 -1
  216. package/dist/src/helpers/arweaveContentTags.d.ts +1 -2
  217. package/dist/src/helpers/arweaveContentTags.d.ts.map +1 -1
  218. package/dist/src/helpers/constants.d.ts +3 -12
  219. package/dist/src/helpers/constants.d.ts.map +1 -1
  220. package/dist/src/helpers/db.d.ts +3 -28
  221. package/dist/src/helpers/db.d.ts.map +1 -1
  222. package/dist/src/helpers/ethereumUtils.d.ts +0 -2
  223. package/dist/src/helpers/ethereumUtils.d.ts.map +1 -1
  224. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts +2 -1
  225. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts.map +1 -1
  226. package/dist/src/helpers/index.d.ts +0 -7
  227. package/dist/src/helpers/index.d.ts.map +1 -1
  228. package/dist/src/helpers/itemStorageFile.d.ts +2 -2
  229. package/dist/src/helpers/reconcilePropertyDraftRows.d.ts +2 -1
  230. package/dist/src/helpers/reconcilePropertyDraftRows.d.ts.map +1 -1
  231. package/dist/src/helpers/schema.d.ts +0 -73
  232. package/dist/src/helpers/schema.d.ts.map +1 -1
  233. package/dist/src/helpers/updateSchema.d.ts +0 -46
  234. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  235. package/dist/src/imports/index.d.ts +0 -1
  236. package/dist/src/imports/index.d.ts.map +1 -1
  237. package/dist/src/imports/json.d.ts +2 -1
  238. package/dist/src/imports/json.d.ts.map +1 -1
  239. package/dist/src/index.d.ts +4 -6
  240. package/dist/src/index.d.ts.map +1 -1
  241. package/dist/src/node/db/Db.d.ts.map +1 -1
  242. package/dist/src/node/helpers/dotSeedDir.d.ts +7 -0
  243. package/dist/src/node/helpers/dotSeedDir.d.ts.map +1 -0
  244. package/dist/src/node/index.d.ts +0 -5
  245. package/dist/src/node/index.d.ts.map +1 -1
  246. package/dist/src/outbox/index.d.ts +1 -1
  247. package/dist/src/outbox/index.d.ts.map +1 -1
  248. package/dist/src/outbox/itemAppliers.d.ts.map +1 -1
  249. package/dist/src/outbox/outbox.d.ts +3 -19
  250. package/dist/src/outbox/outbox.d.ts.map +1 -1
  251. package/dist/src/platform/configurePlatform.d.ts.map +1 -1
  252. package/dist/src/platform/index.browser.d.ts.map +1 -1
  253. package/dist/src/platform/index.node.d.ts.map +1 -1
  254. package/dist/src/platform/types.d.ts +0 -2
  255. package/dist/src/platform/types.d.ts.map +1 -1
  256. package/dist/src/query/createLocalQueryDataSource.d.ts.map +1 -1
  257. package/dist/src/seedSchema/PendingWriteSchema.d.ts.map +1 -1
  258. package/dist/src/services/write/actors/validateEntity.d.ts +1 -1
  259. package/dist/src/services/write/actors/validateEntity.d.ts.map +1 -1
  260. package/dist/src/services/write/actors/writeToDatabase.d.ts.map +1 -1
  261. package/dist/src/services/write/writeProcessMachine.d.ts +1 -23
  262. package/dist/src/services/write/writeProcessMachine.d.ts.map +1 -1
  263. package/dist/src/stores/eas.d.ts +0 -1
  264. package/dist/src/stores/eas.d.ts.map +1 -1
  265. package/dist/src/types/index.d.ts +1 -18
  266. package/dist/src/types/index.d.ts.map +1 -1
  267. package/dist/src/types/machines.d.ts +1 -32
  268. package/dist/src/types/machines.d.ts.map +1 -1
  269. package/dist/{syncDbWithEas-b4fESZ7C.js → syncDbWithEas-DUu_wjUG.js} +37 -105
  270. package/dist/syncDbWithEas-DUu_wjUG.js.map +1 -0
  271. package/dist/{tolerantWebAccess-CIpS7RLk.js → tolerantWebAccess-DecKDGen.js} +9 -8
  272. package/dist/{tolerantWebAccess-CIpS7RLk.js.map → tolerantWebAccess-DecKDGen.js.map} +1 -1
  273. package/dist/{updateSeedRevokedAt-CR4zwn-6.js → updateSeedRevokedAt-CP606vKs.js} +3 -3
  274. package/dist/{updateSeedRevokedAt-CR4zwn-6.js.map → updateSeedRevokedAt-CP606vKs.js.map} +1 -1
  275. package/package.json +6 -8
  276. package/dist/ClientManager-B1r_8P5Z.js.map +0 -1
  277. package/dist/Item-CjTEShfk.js.map +0 -1
  278. package/dist/ModelProperty-C3749Wjq.js.map +0 -1
  279. package/dist/Schema-CX9CTtho.js.map +0 -1
  280. package/dist/changeFeed-DcsZ7deG.js.map +0 -1
  281. package/dist/configurePlatform-AWild9o4.js +0 -81
  282. package/dist/configurePlatform-AWild9o4.js.map +0 -1
  283. package/dist/dist/ClientManager-B1r_8P5Z.d.ts.map +0 -1
  284. package/dist/dist/Item-CjTEShfk.d.ts.map +0 -1
  285. package/dist/dist/Schema-CX9CTtho.d.ts.map +0 -1
  286. package/dist/dist/backfillMetadataPropertyIds-DWWkh-Ex.d.ts.map +0 -1
  287. package/dist/dist/changeFeed-DcsZ7deG.d.ts.map +0 -1
  288. package/dist/dist/configurePlatform-AWild9o4.d.ts +0 -30
  289. package/dist/dist/configurePlatform-AWild9o4.d.ts.map +0 -1
  290. package/dist/dist/detachRowsBeforeDelete-Bo_pky-R.d.ts.map +0 -1
  291. package/dist/dist/eas--9vtNkma.d.ts.map +0 -1
  292. package/dist/dist/errors-Do7v6RKu.d.ts.map +0 -1
  293. package/dist/dist/getItem-5j22EWWE.d.ts.map +0 -1
  294. package/dist/dist/getPublishPayload-BGl2SaGK.d.ts.map +0 -1
  295. package/dist/dist/getPublishUploads-DVsDx6Xf.d.ts.map +0 -1
  296. package/dist/dist/index-C0SetTd1.d.ts.map +0 -1
  297. package/dist/dist/index-CJK3F_MK.d.ts +0 -14
  298. package/dist/dist/index-CJK3F_MK.d.ts.map +0 -1
  299. package/dist/dist/index-Dp4uyZYx.d.ts.map +0 -1
  300. package/dist/dist/modelPropertyRecordSchemas-C_lYTzMr.d.ts.map +0 -1
  301. package/dist/dist/property-pcDxNEpy.d.ts.map +0 -1
  302. package/dist/dist/propertyValidationRules-BEjN0f3-.d.ts.map +0 -1
  303. package/dist/dist/publishDraftGraph-I5yKe1Xz.d.ts.map +0 -1
  304. package/dist/dist/resetAmbiguousLegacyItemData-0Tin9-JK.d.ts +0 -17
  305. package/dist/dist/resetAmbiguousLegacyItemData-0Tin9-JK.d.ts.map +0 -1
  306. package/dist/dist/resolveModelForSyncedSeed-C5KXn6ex.d.ts.map +0 -1
  307. package/dist/dist/syncDbWithEas-b4fESZ7C.d.ts +0 -22
  308. package/dist/dist/syncDbWithEas-b4fESZ7C.d.ts.map +0 -1
  309. package/dist/dist/updateSeedRevokedAt-CR4zwn-6.d.ts.map +0 -1
  310. package/dist/eas--9vtNkma.js.map +0 -1
  311. package/dist/errors-Do7v6RKu.js.map +0 -1
  312. package/dist/errors-rIWK7gwJ.js.map +0 -1
  313. package/dist/getPublishPayload-BGl2SaGK.js.map +0 -1
  314. package/dist/getPublishUploads-DVsDx6Xf.js.map +0 -1
  315. package/dist/index-C0SetTd1.js.map +0 -1
  316. package/dist/index-CJK3F_MK.js.map +0 -1
  317. package/dist/index-CZQrNqvq.js.map +0 -1
  318. package/dist/index-Dp4uyZYx.js.map +0 -1
  319. package/dist/index.browser-Ll71Y_Dl.js.map +0 -1
  320. package/dist/index.node-CgltN0cC.js.map +0 -1
  321. package/dist/property-pcDxNEpy.js.map +0 -1
  322. package/dist/publishDraftGraph-I5yKe1Xz.js.map +0 -1
  323. package/dist/resetAmbiguousLegacyItemData-0Tin9-JK.js +0 -98
  324. package/dist/resetAmbiguousLegacyItemData-0Tin9-JK.js.map +0 -1
  325. package/dist/src/Schema/service/actors/loadOrCreateSchema.d.ts +0 -5
  326. package/dist/src/Schema/service/actors/loadOrCreateSchema.d.ts.map +0 -1
  327. package/dist/src/browser/db/sqlWasmClient.d.ts +0 -1
  328. package/dist/src/browser/db/sqlWasmClient.d.ts.map +0 -1
  329. package/dist/src/browser/helpers/PathResolver.d.ts +0 -41
  330. package/dist/src/browser/helpers/PathResolver.d.ts.map +0 -1
  331. package/dist/src/browser/index.d.ts +0 -3
  332. package/dist/src/browser/index.d.ts.map +0 -1
  333. package/dist/src/browser/seed.d.ts +0 -21
  334. package/dist/src/browser/seed.d.ts.map +0 -1
  335. package/dist/src/browser/workers/content-hash.d.ts +0 -2
  336. package/dist/src/browser/workers/content-hash.d.ts.map +0 -1
  337. package/dist/src/browser/workers/dbWorker.d.ts +0 -1
  338. package/dist/src/browser/workers/dbWorker.d.ts.map +0 -1
  339. package/dist/src/client/BaseClientManager.d.ts +0 -7
  340. package/dist/src/client/BaseClientManager.d.ts.map +0 -1
  341. package/dist/src/client/actions/setAddresses.d.ts +0 -2
  342. package/dist/src/client/actions/setAddresses.d.ts.map +0 -1
  343. package/dist/src/db/alignRowPublishers.d.ts +0 -25
  344. package/dist/src/db/alignRowPublishers.d.ts.map +0 -1
  345. package/dist/src/db/clearStoredDisplayUrls.d.ts +0 -18
  346. package/dist/src/db/clearStoredDisplayUrls.d.ts.map +0 -1
  347. package/dist/src/db/migrateLegacyItemStorageRows.d.ts +0 -57
  348. package/dist/src/db/migrateLegacyItemStorageRows.d.ts.map +0 -1
  349. package/dist/src/db/read/getExistingItem.d.ts +0 -12
  350. package/dist/src/db/read/getExistingItem.d.ts.map +0 -1
  351. package/dist/src/db/read/getModels.d.ts +0 -5
  352. package/dist/src/db/read/getModels.d.ts.map +0 -1
  353. package/dist/src/db/read/getVersionsForVersionUids.d.ts +0 -10
  354. package/dist/src/db/read/getVersionsForVersionUids.d.ts.map +0 -1
  355. package/dist/src/db/removeForeignAttestationRows.d.ts +0 -27
  356. package/dist/src/db/removeForeignAttestationRows.d.ts.map +0 -1
  357. package/dist/src/db/resetAmbiguousLegacyItemData.d.ts +0 -17
  358. package/dist/src/db/resetAmbiguousLegacyItemData.d.ts.map +0 -1
  359. package/dist/src/db/write/applyArweaveL1TransactionIdLocal.d.ts +0 -14
  360. package/dist/src/db/write/applyArweaveL1TransactionIdLocal.d.ts.map +0 -1
  361. package/dist/src/db/write/convertVerbatimItemStorageRow.d.ts +0 -44
  362. package/dist/src/db/write/convertVerbatimItemStorageRow.d.ts.map +0 -1
  363. package/dist/src/db/write/restoreDataItemIdsOverwrittenByL1.d.ts +0 -18
  364. package/dist/src/db/write/restoreDataItemIdsOverwrittenByL1.d.ts.map +0 -1
  365. package/dist/src/db/write/saveAppState.d.ts +0 -2
  366. package/dist/src/db/write/saveAppState.d.ts.map +0 -1
  367. package/dist/src/eslint-rules/align-imports.d.ts +0 -12
  368. package/dist/src/eslint-rules/align-imports.d.ts.map +0 -1
  369. package/dist/src/events/files/index.d.ts +0 -4
  370. package/dist/src/events/files/index.d.ts.map +0 -1
  371. package/dist/src/events/index.d.ts +0 -13
  372. package/dist/src/events/index.d.ts.map +0 -1
  373. package/dist/src/events/services/allItems.d.ts +0 -6
  374. package/dist/src/events/services/allItems.d.ts.map +0 -1
  375. package/dist/src/events/services/index.d.ts +0 -3
  376. package/dist/src/events/services/index.d.ts.map +0 -1
  377. package/dist/src/helpers/ArweaveClient/index.d.ts +0 -30
  378. package/dist/src/helpers/ArweaveClient/index.d.ts.map +0 -1
  379. package/dist/src/helpers/PathResolver/BasePathResolver.d.ts +0 -26
  380. package/dist/src/helpers/PathResolver/BasePathResolver.d.ts.map +0 -1
  381. package/dist/src/helpers/PathResolver/IPathResolver.d.ts +0 -16
  382. package/dist/src/helpers/PathResolver/IPathResolver.d.ts.map +0 -1
  383. package/dist/src/helpers/easRevokedFilter.d.ts +0 -2
  384. package/dist/src/helpers/easRevokedFilter.d.ts.map +0 -1
  385. package/dist/src/helpers/file/fetchAll/actors.d.ts +0 -16
  386. package/dist/src/helpers/file/fetchAll/actors.d.ts.map +0 -1
  387. package/dist/src/helpers/file/fetchAll/index.d.ts +0 -58
  388. package/dist/src/helpers/file/fetchAll/index.d.ts.map +0 -1
  389. package/dist/src/helpers/files.d.ts +0 -10
  390. package/dist/src/helpers/files.d.ts.map +0 -1
  391. package/dist/src/helpers/updateMachineContext.d.ts +0 -7
  392. package/dist/src/helpers/updateMachineContext.d.ts.map +0 -1
  393. package/dist/src/imports/markdown.d.ts +0 -40
  394. package/dist/src/imports/markdown.d.ts.map +0 -1
  395. package/dist/src/node/constants.d.ts +0 -2
  396. package/dist/src/node/constants.d.ts.map +0 -1
  397. package/dist/src/node/db/index.d.ts +0 -5
  398. package/dist/src/node/db/index.d.ts.map +0 -1
  399. package/dist/src/node/helpers/PathResolver.d.ts +0 -44
  400. package/dist/src/node/helpers/PathResolver.d.ts.map +0 -1
  401. package/dist/src/node/helpers/scripts.d.ts +0 -14
  402. package/dist/src/node/helpers/scripts.d.ts.map +0 -1
  403. package/dist/src/node/seed.d.ts +0 -1
  404. package/dist/src/node/seed.d.ts.map +0 -1
  405. package/dist/src/node/webpack/fs-proxy.d.ts +0 -4
  406. package/dist/src/node/webpack/fs-proxy.d.ts.map +0 -1
  407. package/dist/src/node/webpack/index.d.ts +0 -7
  408. package/dist/src/node/webpack/index.d.ts.map +0 -1
  409. package/dist/src/services/events.d.ts +0 -2
  410. package/dist/src/services/events.d.ts.map +0 -1
  411. package/dist/src/testing/platformTestHandle.d.ts +0 -8
  412. package/dist/src/testing/platformTestHandle.d.ts.map +0 -1
  413. package/dist/src/types/browser.d.ts +0 -24
  414. package/dist/src/types/browser.d.ts.map +0 -1
  415. package/dist/src/types/seedProtocol.d.ts +0 -16
  416. package/dist/src/types/seedProtocol.d.ts.map +0 -1
  417. package/dist/src/types/services.d.ts +0 -1
  418. package/dist/src/types/services.d.ts.map +0 -1
  419. package/dist/syncDbWithEas-b4fESZ7C.js.map +0 -1
@@ -1,1268 +1,13 @@
1
1
  import { fromCallback, setup, assign, createActor } from 'xstate';
2
- import { ay as SEED_PROTOCOL_SCHEMA_NAME, G as BaseDb, B as schemas, aQ as addSchemaToDb, i as isDataType, M as ModelPropertyDataTypes, aj as generateId, R as addModelsToDb, t as models, r as modelSchemas, w as properties, Q as BaseFileManager, aU as loadModelsFromDbForSchema, aV as mergeDbModelsIntoSchemaModels, aN as isInternalSchema, aW as clearNameMatchLevels } from './index-C0SetTd1.js';
3
- import { h as getRefValueType, T as createRowsWrittenSignal, U as createModelsFromJson, F as listCompleteSchemaFiles, V as getLatestSchemaVersion, l as loadSchemaFromFile, W as jsonPropertiesToSchemaProperties, G as loadAllSchemasFromDb, z as getClient } from './ClientManager-B1r_8P5Z.js';
2
+ import { L as BaseDb, aq as SEED_PROTOCOL_SCHEMA_NAME, J as schemas, Q as BaseFileManager, aL as loadModelsFromDbForSchema, aM as mergeDbModelsIntoSchemaModels, aF as isInternalSchema, p as models, z as modelSchemas, aN as addSchemaToDb, ad as generateId, i as isDataType, M as ModelPropertyDataTypes, aO as addModelsToDb, E as properties, aP as clearNameMatchLevels } from './index-Dx_GTdyQ.js';
3
+ import { SchemaValidationService } from './SchemaValidationService-DnGKel4V.js';
4
+ import { A as listCompleteSchemaFiles, N as getLatestSchemaVersion, O as createRowsWrittenSignal, P as createModelsFromJson, l as loadSchemaFromFile, Q as jsonPropertiesToSchemaProperties, B as loadAllSchemasFromDb, v as getClient } from './ClientManager-GZfXErDX.js';
4
5
  import { eq, desc, and } from 'drizzle-orm';
5
6
  import debug from 'debug';
6
- import { c as currentEvictionEpoch, w as writeProcessMachine, M as Model, g as getDraftSaveError, C as ConflictError, r as recordSchemaDestroy, f as finishSchemaDestroy, e as setupEntityLiveQuery, t as trackDraftSave } from './errors-rIWK7gwJ.js';
7
+ import { c as currentEvictionEpoch, M as Model, g as getDraftSaveError, C as ConflictError, r as recordSchemaDestroy, f as finishSchemaDestroy, e as setupEntityLiveQuery, t as trackDraftSave } from './errors-D1zHAqjr.js';
7
8
  import 'pluralize';
8
9
  import '@seedprotocol/eas';
9
- import { SchemaValidationService } from './SchemaValidationService-T5mqnY8q.js';
10
- import { ak as ActorKeyedState, Q as DEFAULT_READY_TIMEOUT_MS, C as waitForEntityIdle, R as createReactiveProxy, T as findEntity, X as ClientManagerState, al as clearDestroySubscriptions, U as forceRemoveFromCaches, am as unloadEntity, V as runDestroyLifecycle } from './Item-CjTEShfk.js';
11
-
12
- const logger$d = debug('seedSdk:schema:actors:loadOrCreateSchema');
13
- /**
14
- * Query model IDs (schemaFileId) from database for a given schema
15
- * This is used to populate _liveQueryModelIds immediately when loading a schema
16
- * @param schemaId - The database ID of the schema
17
- * @returns Array of model file IDs (schemaFileId) for models linked to this schema
18
- */
19
- const getModelIdsForSchema$1 = async (schemaId) => {
20
- const db = BaseDb.getAppDb();
21
- if (!db) {
22
- logger$d('Database not available, cannot query model IDs');
23
- return [];
24
- }
25
- try {
26
- const modelRecords = await db
27
- .select({
28
- modelFileId: models.schemaFileId,
29
- })
30
- .from(modelSchemas)
31
- .innerJoin(models, eq(modelSchemas.modelId, models.id))
32
- .where(eq(modelSchemas.schemaId, schemaId));
33
- const modelIds = modelRecords
34
- .map((row) => row.modelFileId)
35
- .filter((id) => id !== null && id !== undefined);
36
- logger$d(`Found ${modelIds.length} model IDs for schema (id: ${schemaId}): ${modelIds.join(', ')}`);
37
- return modelIds;
38
- }
39
- catch (error) {
40
- logger$d(`Error querying model IDs for schema ${schemaId}:`, error);
41
- return [];
42
- }
43
- };
44
- /**
45
- * Create Model instances for all model IDs to ensure they're cached before getContext runs
46
- * This ensures that Model.getById() in Schema.getContext() will find the instances
47
- * @param modelIds - Array of model file IDs to create instances for
48
- */
49
- const createModelInstances$2 = async (modelIds, evictionEpoch) => {
50
- if (modelIds.length === 0) {
51
- return;
52
- }
53
- try {
54
- const _mod_0 = await import('./errors-rIWK7gwJ.js');
55
- const _ns_0 = _mod_0.i;
56
- const modelMod = _ns_0;
57
- const { Model } = modelMod;
58
- // Create instances for all model IDs in parallel
59
- // Model.createById() will check cache first, then query DB and create if needed
60
- const createPromises = modelIds.map(async (modelFileId) => {
61
- try {
62
- // Not if the schema was evicted (Schema.destroy, test cleanup) since this load started
63
- const schemaHold = Model.takeSchemaHold(modelFileId);
64
- const model = await Model.createById(modelFileId, { evictionEpoch, ...(!schemaHold && { hold: false }) });
65
- if (!model && schemaHold)
66
- Model.dropSchemaHold(modelFileId);
67
- if (model) {
68
- logger$d(`Created/cached Model instance for modelFileId "${modelFileId}"`);
69
- }
70
- else {
71
- logger$d(`Model.createById returned undefined for modelFileId "${modelFileId}" (may not exist in DB yet)`);
72
- }
73
- }
74
- catch (error) {
75
- logger$d(`Error creating Model instance for modelFileId "${modelFileId}": ${error}`);
76
- // Don't throw - continue with other models
77
- }
78
- });
79
- await Promise.all(createPromises);
80
- logger$d(`Finished creating/caching ${modelIds.length} Model instances`);
81
- }
82
- catch (error) {
83
- logger$d(`Error in createModelInstances: ${error}`);
84
- // Don't throw - this is best-effort to pre-populate cache
85
- }
86
- };
87
- /**
88
- * Verify that properties are persisted to the database for a given model
89
- * This is important in browser environments where database writes may not be immediately visible
90
- * @param modelId - Database ID of the model
91
- * @param modelName - Name of the model (for logging)
92
- * @param maxRetries - Maximum number of retry attempts
93
- * @param retryDelay - Delay between retries in milliseconds
94
- * @returns Promise that resolves when properties are found, or rejects if not found after max retries
95
- */
96
- const verifyPropertiesPersisted = async (modelId, modelName, maxRetries = 10, retryDelay = 100) => {
97
- const db = BaseDb.getAppDb();
98
- if (!db) {
99
- throw new Error('Database not available for property verification');
100
- }
101
- for (let attempt = 0; attempt < maxRetries; attempt++) {
102
- const props = await db
103
- .select()
104
- .from(properties)
105
- .where(eq(properties.modelId, modelId))
106
- .limit(1);
107
- if (props.length > 0) {
108
- logger$d(`Verified properties exist for model "${modelName}" (modelId: ${modelId}) after ${attempt + 1} attempt(s)`);
109
- return;
110
- }
111
- if (attempt < maxRetries - 1) {
112
- logger$d(`Properties not yet visible for model "${modelName}" (modelId: ${modelId}), retrying in ${retryDelay}ms (attempt ${attempt + 1}/${maxRetries})`);
113
- await new Promise(resolve => setTimeout(resolve, retryDelay));
114
- }
115
- }
116
- throw new Error(`Properties not found for model "${modelName}" (modelId: ${modelId}) after ${maxRetries} attempts. This may indicate a database write issue in the browser environment.`);
117
- };
118
- /**
119
- * Sanitize a schema name to be filesystem-safe
120
- * Replaces all special characters (except alphanumeric, hyphens, underscores) with underscores
121
- * Converts spaces to underscores
122
- * Removes leading/trailing underscores
123
- *
124
- * @param name - Schema name to sanitize
125
- * @returns Sanitized name safe for use in filenames
126
- */
127
- const sanitizeSchemaName$1 = (name) => {
128
- return name
129
- .replace(/[^a-zA-Z0-9\s_-]/g, '_') // Replace special chars (except spaces, hyphens, underscores) with underscore
130
- .replace(/\s+/g, '_') // Convert spaces to underscores
131
- .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores
132
- .replace(/_+/g, '_'); // Collapse multiple underscores to single
133
- };
134
- /**
135
- * Generate filename for a schema
136
- * Format: {schemaFileId}_{schemaName}_v{version}.json
137
- *
138
- * The ID-first format ensures all files for a schema group together when sorted alphabetically.
139
- *
140
- * @param name - Schema name
141
- * @param version - Schema version
142
- * @param schemaFileId - Schema file ID (required)
143
- */
144
- const getSchemaFilename = (name, version, schemaFileId) => {
145
- const sanitizedName = sanitizeSchemaName$1(name);
146
- return `${schemaFileId}_${sanitizedName}_v${version}.json`;
147
- };
148
- /**
149
- * Get the full file path for a schema
150
- * Format: {schemaFileId}_{schemaName}_v{version}.json
151
- *
152
- * The ID-first format ensures all files for a schema group together when sorted alphabetically.
153
- *
154
- * @param name - Schema name
155
- * @param version - Schema version
156
- * @param schemaFileId - Schema file ID (required)
157
- */
158
- const getSchemaFilePath$2 = (name, version, schemaFileId) => {
159
- const path = BaseFileManager.getPathModule();
160
- const filename = getSchemaFilename(name, version, schemaFileId);
161
- const workingDir = BaseFileManager.getWorkingDir();
162
- return path.join(workingDir, filename);
163
- };
164
- const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
165
- const evictionEpoch = currentEvictionEpoch();
166
- const _loadOrCreateSchema = async () => {
167
- const { schemaName } = context;
168
- // Check if this is an internal SDK schema (should not create files in app directory) — use static import so consumer bundles resolve correctly
169
- const isInternal = isInternalSchema(schemaName);
170
- if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
171
- // For Seed Protocol, always load from internal file, never create new
172
- logger$d(`Loading internal Seed Protocol schema from SDK`);
173
- try {
174
- const _mod_1 = await import('./ClientManager-B1r_8P5Z.js');
175
- const _ns_1 = _mod_1.Y;
176
- const internalSchema = _ns_1;
177
- const schemaFile = internalSchema.default;
178
- // Check if it exists in database, if not, add it
179
- const db = BaseDb.getAppDb();
180
- if (db && schemaFile.id) {
181
- const existing = await db
182
- .select()
183
- .from(schemas)
184
- .where(eq(schemas.schemaFileId, schemaFile.id))
185
- .limit(1);
186
- let schemaRecord = existing.length > 0 ? existing[0] : null;
187
- if (existing.length === 0) {
188
- // Add to database if not present
189
- const schemaData = JSON.stringify(schemaFile, null, 2);
190
- schemaRecord = await addSchemaToDb({
191
- name: schemaName,
192
- version: schemaFile.version,
193
- createdAt: new Date(schemaFile.metadata.createdAt).getTime(),
194
- updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
195
- }, schemaFile.id, schemaData, false);
196
- logger$d(`Added Seed Protocol schema to database`);
197
- // Also add models and properties to database
198
- // Convert to JsonImportSchema format for processing
199
- const importData = {
200
- name: schemaName,
201
- models: Object.fromEntries(Object.entries(schemaFile.models || {}).map(([modelName, model]) => [
202
- modelName,
203
- {
204
- ...model,
205
- // Remove id field for import format
206
- id: undefined,
207
- properties: Object.fromEntries(Object.entries(model.properties || {}).map(([propName, prop]) => {
208
- const schemaProp = prop;
209
- const jsonProp = {
210
- type: schemaProp.dataType || schemaProp.type,
211
- };
212
- // Copy other properties
213
- Object.keys(schemaProp).forEach(key => {
214
- if (key !== 'id' && key !== 'dataType') {
215
- jsonProp[key] = schemaProp[key];
216
- }
217
- });
218
- // Handle Relation type
219
- if (schemaProp.ref || schemaProp.refModelName) {
220
- jsonProp.model = schemaProp.refModelName || schemaProp.ref;
221
- }
222
- // Handle List type (case-insensitive refValueType)
223
- const listRefValueType = getRefValueType(schemaProp);
224
- if (isDataType(schemaProp.dataType, ModelPropertyDataTypes.List) && listRefValueType) {
225
- jsonProp.refValueType = listRefValueType;
226
- if (schemaProp.ref || schemaProp.refModelName) {
227
- jsonProp.ref = schemaProp.refModelName || schemaProp.ref;
228
- }
229
- }
230
- // Handle storage configuration
231
- if (schemaProp.storageType || schemaProp.localStorageDir || schemaProp.filenameSuffix) {
232
- jsonProp.storage = {
233
- type: schemaProp.storageType === 'ItemStorage' ? 'ItemStorage' : 'PropertyStorage',
234
- path: schemaProp.localStorageDir,
235
- extension: schemaProp.filenameSuffix,
236
- };
237
- }
238
- return [propName, jsonProp];
239
- })),
240
- },
241
- ])),
242
- };
243
- // Generate schema ID if missing
244
- if (!schemaFile.id) {
245
- schemaFile.id = generateId();
246
- logger$d('Generated schema ID for schema:', schemaFile.id);
247
- }
248
- // Extract schemaFileIds from JSON file and generate missing ones BEFORE creating models
249
- // This ensures Model instances are created with correct IDs
250
- const modelFileIds = new Map();
251
- const propertyFileIds = new Map();
252
- for (const [modelName, model] of Object.entries(schemaFile.models || {})) {
253
- // Generate model ID if missing
254
- if (!model.id) {
255
- model.id = generateId();
256
- logger$d(`Generated model ID for ${modelName}:`, model.id);
257
- // Update the schemaFile object so it's included in schemaData
258
- schemaFile.models[modelName].id = model.id;
259
- }
260
- modelFileIds.set(modelName, model.id);
261
- const propIds = new Map();
262
- for (const [propName, prop] of Object.entries(model.properties || {})) {
263
- // Generate property ID if missing
264
- if (!prop.id) {
265
- prop.id = generateId();
266
- logger$d(`Generated property ID for ${modelName}.${propName}:`, prop.id);
267
- // Update the schemaFile object so it's included in schemaData
268
- schemaFile.models[modelName].properties[propName].id = prop.id;
269
- }
270
- propIds.set(propName, prop.id);
271
- }
272
- if (propIds.size > 0) {
273
- propertyFileIds.set(modelName, propIds);
274
- }
275
- }
276
- // Convert JSON models to Model classes, passing modelFileIds and propertyFileIds so Model instances use correct IDs.
277
- // addModelsToDb below writes their rows; the models adopt them once it has run.
278
- const rowsWritten = createRowsWrittenSignal();
279
- const modelDefinitions = await createModelsFromJson(importData, modelFileIds, propertyFileIds, schemaRecord ? rowsWritten.promise : undefined);
280
- // Add models to database and link them to the schema with schemaFileIds
281
- if (Object.keys(modelDefinitions).length > 0 && schemaRecord) {
282
- await addModelsToDb(modelDefinitions, schemaRecord, undefined, {
283
- schemaFileId: schemaFile.id,
284
- modelFileIds,
285
- propertyFileIds,
286
- }).finally(rowsWritten.settle);
287
- logger$d(`Added ${Object.keys(modelDefinitions).length} models and their properties to database for Seed Protocol schema`);
288
- // Verify properties are persisted (important for browser environments)
289
- // Query the database to get model IDs that were just created
290
- const modelLinks = await db
291
- .select({
292
- modelId: modelSchemas.modelId,
293
- modelName: models.name,
294
- })
295
- .from(modelSchemas)
296
- .innerJoin(models, eq(modelSchemas.modelId, models.id))
297
- .where(eq(modelSchemas.schemaId, schemaRecord.id));
298
- // Verify properties for at least one model (Seed model if available)
299
- const seedModelLink = modelLinks.find((link) => link.modelName === 'Seed');
300
- if (seedModelLink && seedModelLink.modelId) {
301
- await verifyPropertiesPersisted(seedModelLink.modelId, 'Seed', 10, 100);
302
- }
303
- else if (modelLinks.length > 0 && modelLinks[0].modelId) {
304
- // Fallback to first model if Seed not found
305
- await verifyPropertiesPersisted(modelLinks[0].modelId, modelLinks[0].modelName || 'unknown', 10, 100);
306
- }
307
- }
308
- }
309
- else {
310
- // Schema exists, but always ensure models/properties are in database
311
- // This handles the case where schema was added but models weren't (from previous code)
312
- // or where models were added but properties weren't
313
- // Check if models are linked to the schema
314
- const modelLinks = await db
315
- .select({
316
- modelId: modelSchemas.modelId,
317
- modelName: models.name,
318
- })
319
- .from(modelSchemas)
320
- .innerJoin(models, eq(modelSchemas.modelId, models.id))
321
- .where(eq(modelSchemas.schemaId, schemaRecord.id));
322
- // Check if we have all expected models
323
- const expectedModelNames = Object.keys(schemaFile.models || {});
324
- const linkedModelNames = modelLinks
325
- .map((link) => link.modelName)
326
- .filter((n) => n !== null);
327
- const missingModels = expectedModelNames.filter(name => !linkedModelNames.includes(name));
328
- // Check if properties exist for linked models
329
- let missingProperties = false;
330
- if (modelLinks.length > 0) {
331
- for (const link of modelLinks) {
332
- if (link.modelId) {
333
- const props = await db
334
- .select()
335
- .from(properties)
336
- .where(eq(properties.modelId, link.modelId))
337
- .limit(1);
338
- if (props.length === 0) {
339
- missingProperties = true;
340
- break;
341
- }
342
- }
343
- }
344
- }
345
- // If models are missing or properties are missing, add them
346
- if (missingModels.length > 0 || missingProperties || modelLinks.length === 0) {
347
- logger$d(`Seed Protocol schema exists but models/properties incomplete (missing models: ${missingModels.length}, missing properties: ${missingProperties}), adding them now`);
348
- // Convert SchemaFileFormat to JsonImportSchema format
349
- // Schema format: { dataType, ref, refValueType, storageType, localStorageDir, filenameSuffix }
350
- // JSON import format: { type, model, items, storage: { type, path, extension } }
351
- const importData = {
352
- name: schemaName,
353
- models: Object.fromEntries(Object.entries(schemaFile.models || {}).map(([modelName, model]) => [
354
- modelName,
355
- {
356
- ...model,
357
- id: undefined,
358
- properties: Object.fromEntries(Object.entries(model.properties || {}).map(([propName, prop]) => {
359
- const schemaProp = prop;
360
- const jsonProp = {
361
- type: schemaProp.dataType || schemaProp.type,
362
- };
363
- // Handle Relation type
364
- if (schemaProp.ref || schemaProp.refModelName) {
365
- jsonProp.model = schemaProp.refModelName || schemaProp.ref;
366
- }
367
- // Handle List type (support both refValueType and legacy items, case-insensitive)
368
- if (isDataType(schemaProp.dataType, ModelPropertyDataTypes.List) || isDataType(schemaProp.type, ModelPropertyDataTypes.List)) {
369
- const refValueType = getRefValueType(schemaProp);
370
- if (refValueType) {
371
- jsonProp.refValueType = refValueType;
372
- const ref = schemaProp.ref ?? schemaProp.refModelName ?? schemaProp.items?.model;
373
- if (ref)
374
- jsonProp.ref = ref;
375
- }
376
- }
377
- // Handle storage configuration
378
- if (schemaProp.storageType || schemaProp.localStorageDir || schemaProp.filenameSuffix) {
379
- jsonProp.storage = {
380
- type: schemaProp.storageType === 'ItemStorage' ? 'ItemStorage' : 'PropertyStorage',
381
- path: schemaProp.localStorageDir,
382
- extension: schemaProp.filenameSuffix,
383
- };
384
- }
385
- return [propName, jsonProp];
386
- })),
387
- },
388
- ])),
389
- };
390
- // Generate schema ID if missing
391
- if (!schemaFile.id) {
392
- schemaFile.id = generateId();
393
- logger$d('Generated schema ID for schema:', schemaFile.id);
394
- }
395
- // Extract schemaFileIds from JSON file and generate missing ones BEFORE creating models
396
- // This ensures Model instances are created with correct IDs
397
- const modelFileIds = new Map();
398
- const propertyFileIds = new Map();
399
- for (const [modelName, model] of Object.entries(schemaFile.models || {})) {
400
- // Generate model ID if missing
401
- if (!model.id) {
402
- model.id = generateId();
403
- logger$d(`Generated model ID for ${modelName}:`, model.id);
404
- // Update the schemaFile object so it's included in schemaData
405
- schemaFile.models[modelName].id = model.id;
406
- }
407
- modelFileIds.set(modelName, model.id);
408
- const propIds = new Map();
409
- for (const [propName, prop] of Object.entries(model.properties || {})) {
410
- // Generate property ID if missing
411
- if (!prop.id) {
412
- prop.id = generateId();
413
- logger$d(`Generated property ID for ${modelName}.${propName}:`, prop.id);
414
- // Update the schemaFile object so it's included in schemaData
415
- schemaFile.models[modelName].properties[propName].id = prop.id;
416
- }
417
- propIds.set(propName, prop.id);
418
- }
419
- if (propIds.size > 0) {
420
- propertyFileIds.set(modelName, propIds);
421
- }
422
- }
423
- // Convert JSON models to Model classes, passing modelFileIds and propertyFileIds so Model instances use correct IDs.
424
- // addModelsToDb below writes their rows; the models adopt them once it has run.
425
- const rowsWritten = createRowsWrittenSignal();
426
- const modelDefinitions = await createModelsFromJson(importData, modelFileIds, propertyFileIds, rowsWritten.promise);
427
- // Verify all expected models are in modelDefinitions
428
- const missingFromDefinitions = expectedModelNames.filter(name => !Object.keys(modelDefinitions).includes(name));
429
- if (missingFromDefinitions.length > 0) {
430
- console.warn(`[loadOrCreateSchema] WARNING: Some expected models are missing from modelDefinitions: ${missingFromDefinitions.join(', ')}`);
431
- }
432
- if (Object.keys(modelDefinitions).length > 0) {
433
- await addModelsToDb(modelDefinitions, schemaRecord, undefined, {
434
- schemaFileId: schemaFile.id,
435
- modelFileIds,
436
- propertyFileIds,
437
- }).finally(rowsWritten.settle);
438
- logger$d(`Added ${Object.keys(modelDefinitions).length} models and their properties to database for existing Seed Protocol schema`);
439
- // Small delay to ensure database writes are visible (important for browser environments)
440
- await new Promise(resolve => setTimeout(resolve, 200));
441
- // Verify properties are persisted (important for browser environments)
442
- // Re-query model links to get updated model IDs
443
- // Retry querying until all expected models are visible
444
- const expectedModelNames = Object.keys(schemaFile.models || {});
445
- let updatedModelLinks = [];
446
- const maxRetries = 10;
447
- const retryDelay = 100;
448
- for (let attempt = 0; attempt < maxRetries; attempt++) {
449
- updatedModelLinks = await db
450
- .select({
451
- modelId: modelSchemas.modelId,
452
- modelName: models.name,
453
- })
454
- .from(modelSchemas)
455
- .innerJoin(models, eq(modelSchemas.modelId, models.id))
456
- .where(eq(modelSchemas.schemaId, schemaRecord.id));
457
- const linkedModelNames = updatedModelLinks
458
- .map((link) => link.modelName)
459
- .filter((n) => n !== null);
460
- const allModelsPresent = expectedModelNames.every(name => linkedModelNames.includes(name));
461
- if (allModelsPresent) {
462
- break;
463
- }
464
- if (attempt < maxRetries - 1) {
465
- await new Promise(resolve => setTimeout(resolve, retryDelay));
466
- }
467
- }
468
- // Verify properties for at least one model (Seed model if available)
469
- const seedModelLink = updatedModelLinks.find((link) => link.modelName === 'Seed');
470
- if (seedModelLink && seedModelLink.modelId) {
471
- await verifyPropertiesPersisted(seedModelLink.modelId, 'Seed', 10, 100);
472
- }
473
- else if (updatedModelLinks.length > 0 && updatedModelLinks[0].modelId) {
474
- // Fallback to first model if Seed not found
475
- await verifyPropertiesPersisted(updatedModelLinks[0].modelId, updatedModelLinks[0].modelName || 'unknown', 10, 100);
476
- }
477
- }
478
- }
479
- else {
480
- logger$d(`Seed Protocol schema exists with all models and properties already in database`);
481
- }
482
- }
483
- // Query model IDs from database to populate _liveQueryModelIds immediately
484
- let modelIds = [];
485
- if (schemaRecord && schemaRecord.id) {
486
- modelIds = await getModelIdsForSchema$1(schemaRecord.id);
487
- // Create Model instances so they're cached before getContext runs
488
- await createModelInstances$2(modelIds, evictionEpoch);
489
- }
490
- sendBack({
491
- type: 'loadOrCreateSchemaSuccess',
492
- schema: schemaFile,
493
- _liveQueryModelIds: modelIds,
494
- });
495
- return;
496
- }
497
- else {
498
- // No database available, send schema without model IDs
499
- sendBack({
500
- type: 'loadOrCreateSchemaSuccess',
501
- schema: schemaFile,
502
- _liveQueryModelIds: [],
503
- });
504
- return;
505
- }
506
- }
507
- catch (error) {
508
- logger$d(`Error loading internal Seed Protocol schema: ${error}`);
509
- // Fall through to normal loading logic
510
- }
511
- }
512
- if (!schemaName) {
513
- throw new Error('Schema name is required');
514
- }
515
- const db = BaseDb.getAppDb();
516
- if (!db) {
517
- throw new Error('Database not found');
518
- }
519
- // STEP 1: Query database first for existing schema (prefer drafts)
520
- // First try by name (most common case)
521
- let dbSchemas = await db
522
- .select()
523
- .from(schemas)
524
- .where(eq(schemas.name, schemaName))
525
- .orderBy(desc(schemas.isDraft), desc(schemas.version))
526
- .limit(1);
527
- // If not found by name, also try querying by schemaFileId directly
528
- // This handles the case where an ID is passed instead of a name (e.g., 'test-schema-1')
529
- if (dbSchemas.length === 0) {
530
- logger$d(`No schema found by name "${schemaName}", trying to find by schemaFileId`);
531
- const schemasByFileId = await db
532
- .select()
533
- .from(schemas)
534
- .where(eq(schemas.schemaFileId, schemaName))
535
- .orderBy(desc(schemas.isDraft), desc(schemas.version))
536
- .limit(1);
537
- if (schemasByFileId.length > 0) {
538
- logger$d(`Found schema by schemaFileId "${schemaName}" (name in DB: ${schemasByFileId[0].name})`);
539
- dbSchemas = schemasByFileId;
540
- }
541
- }
542
- // If not found by name, or if found but it's not a draft, try to find by schemaFileId from file
543
- // This handles the case where a draft's name was changed but we're loading by the old name
544
- const shouldTrySchemaFileId = dbSchemas.length === 0 || (dbSchemas.length > 0 && dbSchemas[0].isDraft === false);
545
- if (shouldTrySchemaFileId) {
546
- // First, try to get schemaFileId from file if it exists
547
- const completeSchemas = await listCompleteSchemaFiles();
548
- const matchingFileSchemas = completeSchemas.filter((s) => s.name === schemaName);
549
- if (matchingFileSchemas.length > 0) {
550
- const latestFile = matchingFileSchemas.reduce((prev, current) => current.version > prev.version ? current : prev);
551
- // Read file to get schemaFileId
552
- try {
553
- const content = await BaseFileManager.readFileAsString(latestFile.filePath);
554
- const fileSchema = JSON.parse(content);
555
- if (fileSchema.id) {
556
- // Look up by schemaFileId - query for DRAFTS first, then published
557
- // This ensures we find the draft even if there's also a published version
558
- const draftsByFileId = await db
559
- .select()
560
- .from(schemas)
561
- .where(and(eq(schemas.schemaFileId, fileSchema.id), eq(schemas.isDraft, true)))
562
- .orderBy(desc(schemas.version))
563
- .limit(1);
564
- if (draftsByFileId.length > 0) {
565
- logger$d(`Found DRAFT by schemaFileId ${fileSchema.id} (name in DB: ${draftsByFileId[0].name}, requested name: ${schemaName})`);
566
- dbSchemas = draftsByFileId;
567
- }
568
- else {
569
- // No draft found, check for any record with this schemaFileId
570
- const dbSchemasByFileId = await db
571
- .select()
572
- .from(schemas)
573
- .where(eq(schemas.schemaFileId, fileSchema.id))
574
- .orderBy(desc(schemas.isDraft), desc(schemas.version))
575
- .limit(1);
576
- if (dbSchemasByFileId.length > 0) {
577
- const foundSchema = dbSchemasByFileId[0];
578
- logger$d(`Found schema by schemaFileId ${fileSchema.id} (name in DB: ${foundSchema.name}, requested name: ${schemaName}, isDraft: ${foundSchema.isDraft})`);
579
- // Always prefer the one found by schemaFileId if we didn't find anything by name
580
- // OR if the one found by schemaFileId is a draft (even if we found a non-draft by name)
581
- if (foundSchema.isDraft === true || dbSchemas.length === 0) {
582
- dbSchemas = dbSchemasByFileId;
583
- logger$d(`Using schema found by schemaFileId (isDraft: ${foundSchema.isDraft})`);
584
- }
585
- else if (foundSchema.isDraft === false && dbSchemas.length > 0 && dbSchemas[0].isDraft === false) {
586
- // Both are non-drafts, prefer the one found by schemaFileId (more reliable)
587
- dbSchemas = dbSchemasByFileId;
588
- logger$d(`Both schemas are non-drafts, using the one found by schemaFileId`);
589
- }
590
- else {
591
- logger$d(`Keeping schema found by name (isDraft: ${dbSchemas[0].isDraft}) over schemaFileId result (isDraft: ${foundSchema.isDraft})`);
592
- }
593
- }
594
- }
595
- }
596
- }
597
- catch (error) {
598
- logger$d(`Error reading file to get schemaFileId: ${error}`);
599
- }
600
- }
601
- // If still not found and no file exists, try querying all drafts to see if any have metadata.name matching
602
- // This handles the case where a draft was renamed but there's no file (draft-only schema)
603
- if (dbSchemas.length === 0) {
604
- logger$d(`No schema found by name "${schemaName}" and no matching file, checking all drafts for potential match`);
605
- const allDrafts = await db
606
- .select()
607
- .from(schemas)
608
- .where(eq(schemas.isDraft, true))
609
- .orderBy(desc(schemas.version));
610
- logger$d(`Checking ${allDrafts.length} drafts for normalized name match`);
611
- // Check each draft's schemaData to see if metadata.name matches
612
- // Use case-insensitive and normalized comparison to handle name changes like "blog-schema" -> "Blog Schema"
613
- const normalizeName = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, '');
614
- const normalizedRequested = normalizeName(schemaName);
615
- logger$d(`Normalized requested name: "${schemaName}" -> "${normalizedRequested}"`);
616
- for (const draft of allDrafts) {
617
- if (draft.schemaData) {
618
- try {
619
- const draftSchema = JSON.parse(draft.schemaData);
620
- const draftMetadataName = draftSchema.metadata?.name || '';
621
- const draftDbName = draft.name || '';
622
- // Check if normalized names match (handles "blog-schema" vs "Blog Schema")
623
- const normalizedDraftMetadata = normalizeName(draftMetadataName);
624
- const normalizedDraftDb = normalizeName(draftDbName);
625
- logger$d(`Checking draft: DB name="${draftDbName}" (normalized: "${normalizedDraftDb}"), metadata.name="${draftMetadataName}" (normalized: "${normalizedDraftMetadata}")`);
626
- if (normalizedDraftMetadata === normalizedRequested || normalizedDraftDb === normalizedRequested) {
627
- dbSchemas = [draft];
628
- logger$d(`Found draft by normalized name match: DB name="${draftDbName}", metadata.name="${draftMetadataName}", requested="${schemaName}" (normalized: "${normalizedRequested}")`);
629
- break;
630
- }
631
- }
632
- catch (error) {
633
- logger$d(`Error parsing draft schemaData: ${error}`);
634
- // Skip drafts with invalid schemaData
635
- continue;
636
- }
637
- }
638
- else {
639
- logger$d(`Draft ${draft.name} (id: ${draft.id}) has no schemaData, skipping`);
640
- }
641
- }
642
- if (dbSchemas.length === 0) {
643
- logger$d(`No draft found matching normalized name "${normalizedRequested}"`);
644
- }
645
- }
646
- }
647
- if (dbSchemas.length > 0) {
648
- const dbSchema = dbSchemas[0];
649
- logger$d(`Found schema record: name="${dbSchema.name}", isDraft=${dbSchema.isDraft}, hasSchemaData=${!!dbSchema.schemaData}, schemaFileId="${dbSchema.schemaFileId}"`);
650
- // If it's a draft, load from schemaData
651
- if (dbSchema.isDraft === true && dbSchema.schemaData) {
652
- try {
653
- const schemaFile = JSON.parse(dbSchema.schemaData);
654
- logger$d(`Found draft schema ${schemaName} v${schemaFile.version} in database (DB name: ${dbSchema.name}, metadata.name: ${schemaFile.metadata?.name})`);
655
- // CRITICAL: Ensure schema.id matches schemaFileId from database (database is source of truth)
656
- if (dbSchema.schemaFileId && schemaFile.id !== dbSchema.schemaFileId) {
657
- logger$d(`Fixing schema ID mismatch: schema.id="${schemaFile.id}" does not match schemaFileId="${dbSchema.schemaFileId}" from database. Using database value as source of truth.`);
658
- schemaFile.id = dbSchema.schemaFileId;
659
- }
660
- else if (!schemaFile.id && dbSchema.schemaFileId) {
661
- logger$d(`Schema missing id, using schemaFileId from database: "${dbSchema.schemaFileId}"`);
662
- schemaFile.id = dbSchema.schemaFileId;
663
- }
664
- // Verify metadata matches what we expect
665
- if (schemaFile.metadata?.name !== dbSchema.name) {
666
- logger$d(`WARNING: Metadata name mismatch! DB name="${dbSchema.name}", metadata.name="${schemaFile.metadata?.name}"`);
667
- }
668
- // Build merged models without mutating schemaFile (read-only approach)
669
- let mergedModels = { ...(schemaFile.models || {}) };
670
- // Ensure models are populated (fallback for seed-protocol if missing)
671
- if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
672
- try {
673
- const _mod_2 = await import('./ClientManager-B1r_8P5Z.js');
674
- const _ns_2 = _mod_2.Y;
675
- const internalSchema = _ns_2;
676
- const internalSchemaFile = internalSchema.default;
677
- mergedModels = { ...(internalSchemaFile.models || {}) };
678
- logger$d(`Populated models for seed-protocol schema from internal file`);
679
- }
680
- catch (error) {
681
- logger$d(`Error loading internal seed-protocol schema for models:`, error);
682
- }
683
- }
684
- // CRITICAL: Merge models from database (model_schemas join table) with models from schemaData
685
- // This ensures models added to the database are included even if they're not in schemaData
686
- if (dbSchema.id) {
687
- const dbModels = await loadModelsFromDbForSchema(dbSchema.id);
688
- if (Object.keys(dbModels).length > 0) {
689
- logger$d(`Found ${Object.keys(dbModels).length} models in database for schema ${schemaName}: ${Object.keys(dbModels).join(', ')}`);
690
- // Merge: database models take precedence for properties, but preserve schemaData models for full structure
691
- mergedModels = mergeDbModelsIntoSchemaModels(mergedModels, dbModels);
692
- }
693
- }
694
- // Create new schemaFile object with merged models (read-only approach)
695
- const finalSchemaFile = {
696
- ...schemaFile,
697
- models: mergedModels,
698
- };
699
- // Query model IDs from database to populate _liveQueryModelIds immediately
700
- let modelIds = [];
701
- if (dbSchema.id) {
702
- modelIds = await getModelIdsForSchema$1(dbSchema.id);
703
- // Create Model instances so they're cached before getContext runs
704
- await createModelInstances$2(modelIds, evictionEpoch);
705
- }
706
- // Track conflict detection metadata
707
- const loadedAt = Date.now();
708
- const dbVersion = dbSchema.version;
709
- const dbUpdatedAt = dbSchema.updatedAt || loadedAt;
710
- sendBack({
711
- type: 'loadOrCreateSchemaSuccess',
712
- schema: finalSchemaFile,
713
- loadedAt,
714
- dbVersion,
715
- dbUpdatedAt,
716
- _liveQueryModelIds: modelIds,
717
- });
718
- return;
719
- }
720
- catch (error) {
721
- logger$d(`Error parsing schemaData for ${schemaName}:`, error);
722
- // Fall through to file-based loading
723
- }
724
- }
725
- // If it's not a draft and has schemaFileId, try to load from file
726
- // BUT: First check if there's a draft with the same schemaFileId (in case name changed)
727
- if (dbSchema.isDraft === false && dbSchema.schemaFileId) {
728
- logger$d(`Schema is not a draft (isDraft=${dbSchema.isDraft}), checking if there's a draft with same schemaFileId before loading from file`);
729
- // Check for a draft with the same schemaFileId (handles name changes)
730
- const draftsByFileId = await db
731
- .select()
732
- .from(schemas)
733
- .where(and(eq(schemas.schemaFileId, dbSchema.schemaFileId), eq(schemas.isDraft, true)))
734
- .orderBy(desc(schemas.version))
735
- .limit(1);
736
- if (draftsByFileId.length > 0 && draftsByFileId[0].schemaData) {
737
- logger$d(`Found draft with same schemaFileId (name: "${draftsByFileId[0].name}"), using it instead of published version`);
738
- try {
739
- const schemaFile = JSON.parse(draftsByFileId[0].schemaData);
740
- logger$d(`Found draft schema ${schemaName} v${schemaFile.version} in database (DB name: ${draftsByFileId[0].name}, metadata.name: ${schemaFile.metadata?.name})`);
741
- // CRITICAL: Ensure schema.id matches schemaFileId from database (database is source of truth)
742
- if (draftsByFileId[0].schemaFileId && schemaFile.id !== draftsByFileId[0].schemaFileId) {
743
- logger$d(`Fixing schema ID mismatch: schema.id="${schemaFile.id}" does not match schemaFileId="${draftsByFileId[0].schemaFileId}" from database. Using database value as source of truth.`);
744
- schemaFile.id = draftsByFileId[0].schemaFileId;
745
- }
746
- else if (!schemaFile.id && draftsByFileId[0].schemaFileId) {
747
- logger$d(`Schema missing id, using schemaFileId from database: "${draftsByFileId[0].schemaFileId}"`);
748
- schemaFile.id = draftsByFileId[0].schemaFileId;
749
- }
750
- // CRITICAL: Merge models from database (model_schemas join table) with models from schemaData
751
- // This ensures models added to the database are included even if they're not in schemaData
752
- if (draftsByFileId[0].id) {
753
- const dbModels = await loadModelsFromDbForSchema(draftsByFileId[0].id);
754
- if (Object.keys(dbModels).length > 0) {
755
- logger$d(`Found ${Object.keys(dbModels).length} models in database for draft schema ${schemaName}: ${Object.keys(dbModels).join(', ')}`);
756
- // Merge: database models take precedence for properties, but preserve schemaData models for full structure
757
- let mergedModels = { ...(schemaFile.models || {}) };
758
- mergedModels = mergeDbModelsIntoSchemaModels(mergedModels, dbModels);
759
- // Update schemaFile with merged models
760
- schemaFile.models = mergedModels;
761
- }
762
- }
763
- // Query model IDs from database to populate _liveQueryModelIds immediately
764
- let modelIds = [];
765
- if (draftsByFileId[0].id) {
766
- modelIds = await getModelIdsForSchema$1(draftsByFileId[0].id);
767
- // Create Model instances so they're cached before getContext runs
768
- await createModelInstances$2(modelIds, evictionEpoch);
769
- }
770
- // Track conflict detection metadata
771
- const loadedAt = Date.now();
772
- const dbVersion = draftsByFileId[0].version || schemaFile.version;
773
- const dbUpdatedAt = draftsByFileId[0].updatedAt || loadedAt;
774
- sendBack({
775
- type: 'loadOrCreateSchemaSuccess',
776
- schema: schemaFile,
777
- loadedAt,
778
- dbVersion,
779
- dbUpdatedAt,
780
- _liveQueryModelIds: modelIds,
781
- });
782
- return;
783
- }
784
- catch (error) {
785
- logger$d(`Error parsing draft schemaData: ${error}, falling back to file`);
786
- }
787
- }
788
- logger$d(`No draft found with same schemaFileId, will try to load from file instead of schemaData`);
789
- // Try ID-based file lookup first (preferred)
790
- let schemaFile = null;
791
- if (dbSchema.schemaFileId) {
792
- try {
793
- // Try to find file by schemaFileId in the complete schemas list
794
- const completeSchemas = await listCompleteSchemaFiles();
795
- // Match version too: the row is per schema name, so after a new version is imported
796
- // under a new id it can carry the newer version with the older version's schemaFileId.
797
- const idBasedMatch = completeSchemas.find((s) => s.schemaFileId === dbSchema.schemaFileId && s.version === dbSchema.version);
798
- if (idBasedMatch) {
799
- logger$d(`Found schema file by schemaFileId: ${idBasedMatch.filePath}`);
800
- const content = await BaseFileManager.readFileAsString(idBasedMatch.filePath);
801
- schemaFile = JSON.parse(content);
802
- }
803
- else {
804
- // Try direct file path lookup by ID
805
- const idBasedPath = getSchemaFilePath$2(dbSchema.name, dbSchema.version, dbSchema.schemaFileId);
806
- try {
807
- const content = await BaseFileManager.readFileAsString(idBasedPath);
808
- schemaFile = JSON.parse(content);
809
- logger$d(`Found schema file by direct ID-based path: ${idBasedPath}`);
810
- }
811
- catch {
812
- // ID-based file doesn't exist, fall through to name-based
813
- }
814
- }
815
- }
816
- catch (error) {
817
- logger$d(`Error loading ID-based file: ${error}, falling back to name-based`);
818
- }
819
- }
820
- // Fall back to name-based file lookup (backward compatibility)
821
- if (!schemaFile) {
822
- const completeSchemas = await listCompleteSchemaFiles();
823
- const matchingSchemas = completeSchemas.filter((s) => s.name === schemaName);
824
- if (matchingSchemas.length > 0) {
825
- // Find the schema with the highest version
826
- const latest = matchingSchemas.reduce((prev, current) => current.version > prev.version ? current : prev);
827
- // Read the file directly to get SchemaFileFormat
828
- const content = await BaseFileManager.readFileAsString(latest.filePath);
829
- schemaFile = JSON.parse(content);
830
- }
831
- }
832
- if (schemaFile) {
833
- // Build merged models without mutating schemaFile (read-only approach)
834
- let mergedModels = { ...(schemaFile.models || {}) };
835
- // Ensure models are populated (fallback for seed-protocol if missing)
836
- if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
837
- try {
838
- const _mod_3 = await import('./ClientManager-B1r_8P5Z.js');
839
- const _ns_3 = _mod_3.Y;
840
- const internalSchema = _ns_3;
841
- const internalSchemaFile = internalSchema.default;
842
- mergedModels = { ...(internalSchemaFile.models || {}) };
843
- logger$d(`Populated models for seed-protocol schema from internal file`);
844
- }
845
- catch (error) {
846
- logger$d(`Error loading internal seed-protocol schema for models:`, error);
847
- }
848
- }
849
- // CRITICAL: Merge models from database (model_schemas join table) with models from file
850
- // This ensures models added to the database are included even if they're not in the file
851
- if (dbSchema.id) {
852
- const dbModels = await loadModelsFromDbForSchema(dbSchema.id);
853
- if (Object.keys(dbModels).length > 0) {
854
- logger$d(`Found ${Object.keys(dbModels).length} models in database for schema ${schemaName}: ${Object.keys(dbModels).join(', ')}`);
855
- // Merge: database models take precedence for properties, but preserve file models for full structure
856
- mergedModels = mergeDbModelsIntoSchemaModels(mergedModels, dbModels);
857
- }
858
- }
859
- logger$d(`Found existing schema ${schemaName} v${schemaFile.version} from file`);
860
- // Debug: Log what we're sending
861
- logger$d(`Sending schema with ${Object.keys(schemaFile.models || {}).length} models: ${Object.keys(schemaFile.models || {}).join(', ')}`);
862
- // Query model IDs from database to populate _liveQueryModelIds immediately
863
- let modelIds = [];
864
- if (dbSchema.id) {
865
- modelIds = await getModelIdsForSchema$1(dbSchema.id);
866
- // Create Model instances so they're cached before getContext runs
867
- await createModelInstances$2(modelIds, evictionEpoch);
868
- }
869
- // Track conflict detection metadata from DB record
870
- const loadedAt = Date.now();
871
- const dbVersion = dbSchema.version || schemaFile.version;
872
- const dbUpdatedAt = dbSchema.updatedAt || loadedAt;
873
- sendBack({
874
- type: 'loadOrCreateSchemaSuccess',
875
- schema: schemaFile,
876
- loadedAt,
877
- dbVersion,
878
- dbUpdatedAt,
879
- _liveQueryModelIds: modelIds,
880
- });
881
- return;
882
- }
883
- // File doesn't exist, but we have schemaData in database - use it as fallback
884
- if (dbSchema.schemaData) {
885
- try {
886
- const schemaFile = JSON.parse(dbSchema.schemaData);
887
- logger$d(`Found published schema ${schemaName} v${schemaFile.version} in database (file not found, using schemaData)`);
888
- // Build merged models without mutating schemaFile (read-only approach)
889
- let mergedModels = { ...(schemaFile.models || {}) };
890
- // Ensure models are populated (fallback for seed-protocol if missing)
891
- if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
892
- try {
893
- const _mod_4 = await import('./ClientManager-B1r_8P5Z.js');
894
- const _ns_4 = _mod_4.Y;
895
- const internalSchema = _ns_4;
896
- const internalSchemaFile = internalSchema.default;
897
- mergedModels = { ...(internalSchemaFile.models || {}) };
898
- logger$d(`Populated models for seed-protocol schema from internal file`);
899
- }
900
- catch (error) {
901
- logger$d(`Error loading internal seed-protocol schema for models:`, error);
902
- }
903
- }
904
- // CRITICAL: Merge models from database (model_schemas join table) with models from schemaData
905
- // This ensures models added to the database are included even if they're not in schemaData
906
- if (dbSchema.id) {
907
- const dbModels = await loadModelsFromDbForSchema(dbSchema.id);
908
- if (Object.keys(dbModels).length > 0) {
909
- logger$d(`Found ${Object.keys(dbModels).length} models in database for schema ${schemaName}: ${Object.keys(dbModels).join(', ')}`);
910
- // Merge: database models take precedence for properties, but preserve schemaData models for full structure
911
- mergedModels = mergeDbModelsIntoSchemaModels(mergedModels, dbModels);
912
- }
913
- }
914
- // Query model IDs from database to populate _liveQueryModelIds immediately
915
- let modelIds = [];
916
- if (dbSchema.id) {
917
- modelIds = await getModelIdsForSchema$1(dbSchema.id);
918
- // Create Model instances so they're cached before getContext runs
919
- await createModelInstances$2(modelIds, evictionEpoch);
920
- }
921
- // Track conflict detection metadata
922
- const loadedAt = Date.now();
923
- const dbVersion = dbSchema.version || schemaFile.version;
924
- const dbUpdatedAt = dbSchema.updatedAt || loadedAt;
925
- sendBack({
926
- type: 'loadOrCreateSchemaSuccess',
927
- schema: schemaFile,
928
- loadedAt,
929
- dbVersion,
930
- dbUpdatedAt,
931
- _liveQueryModelIds: modelIds,
932
- });
933
- return;
934
- }
935
- catch (error) {
936
- logger$d(`Error parsing schemaData for published schema ${schemaName}:`, error);
937
- // Fall through to try internal schema or file-based loading
938
- }
939
- }
940
- // If schemaData is missing, try to load from internal schema file for seed-protocol
941
- if (!dbSchema.schemaData && schemaName === 'Seed Protocol') {
942
- try {
943
- const _mod_5 = await import('./ClientManager-B1r_8P5Z.js');
944
- const _ns_5 = _mod_5.Y;
945
- const internalSchema = _ns_5;
946
- const schemaFile = internalSchema.default;
947
- logger$d(`Found seed-protocol schema in internal file (schemaData missing, using internal schema)`);
948
- // Update database with schemaData for future loads
949
- const schemaData = JSON.stringify(schemaFile, null, 2);
950
- await addSchemaToDb({
951
- name: schemaName,
952
- version: dbSchema.version,
953
- createdAt: dbSchema.createdAt || new Date().getTime(),
954
- updatedAt: new Date().getTime(),
955
- }, dbSchema.schemaFileId || schemaFile.id, schemaData, false);
956
- // Query model IDs from database to populate _liveQueryModelIds immediately
957
- let modelIds = [];
958
- if (dbSchema.id) {
959
- modelIds = await getModelIdsForSchema$1(dbSchema.id);
960
- // Create Model instances so they're cached before getContext runs
961
- await createModelInstances$2(modelIds, evictionEpoch);
962
- }
963
- sendBack({
964
- type: 'loadOrCreateSchemaSuccess',
965
- schema: schemaFile,
966
- _liveQueryModelIds: modelIds,
967
- });
968
- return;
969
- }
970
- catch (error) {
971
- logger$d(`Error loading internal seed-protocol schema:`, error);
972
- // Fall through to file-based loading
973
- }
974
- }
975
- }
976
- }
977
- // STEP 2: Check for existing schema files (for backward compatibility)
978
- // BUT: Only load from file if we didn't find a draft in the database
979
- // This prevents loading old file data when a draft with a renamed schema exists
980
- const completeSchemas = await listCompleteSchemaFiles();
981
- const matchingSchemas = completeSchemas.filter((s) => s.name === schemaName);
982
- if (matchingSchemas.length > 0) {
983
- // Before loading from file, check if there's a draft in the database that might match
984
- // (This handles the case where the schema was renamed but the file still has the old name)
985
- const allDrafts = await db
986
- .select()
987
- .from(schemas)
988
- .where(eq(schemas.isDraft, true))
989
- .orderBy(desc(schemas.version));
990
- const normalizeName = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, '');
991
- const normalizedRequested = normalizeName(schemaName);
992
- // Check if any draft matches by normalized name
993
- let matchingDraft = null;
994
- for (const draft of allDrafts) {
995
- if (draft.schemaData) {
996
- try {
997
- const draftSchema = JSON.parse(draft.schemaData);
998
- const draftMetadataName = draftSchema.metadata?.name || '';
999
- const draftDbName = draft.name || '';
1000
- const normalizedDraftMetadata = normalizeName(draftMetadataName);
1001
- const normalizedDraftDb = normalizeName(draftDbName);
1002
- if (normalizedDraftMetadata === normalizedRequested || normalizedDraftDb === normalizedRequested) {
1003
- matchingDraft = draft;
1004
- logger$d(`Found matching draft in database (DB name: "${draftDbName}", metadata.name: "${draftMetadataName}") - preferring it over file with old name "${schemaName}"`);
1005
- break;
1006
- }
1007
- }
1008
- catch {
1009
- continue;
1010
- }
1011
- }
1012
- }
1013
- // If we found a matching draft, use it instead of the file
1014
- if (matchingDraft && matchingDraft.schemaData) {
1015
- try {
1016
- const schemaFile = JSON.parse(matchingDraft.schemaData);
1017
- logger$d(`Loading draft from database instead of file (draft has name "${matchingDraft.name}", file has "${schemaName}")`);
1018
- // Query model IDs from database to populate _liveQueryModelIds immediately
1019
- let modelIds = [];
1020
- if (matchingDraft.id) {
1021
- modelIds = await getModelIdsForSchema$1(matchingDraft.id);
1022
- // Create Model instances so they're cached before getContext runs
1023
- await createModelInstances$2(modelIds, evictionEpoch);
1024
- }
1025
- // Track conflict detection metadata
1026
- const loadedAt = Date.now();
1027
- const dbVersion = matchingDraft.version || schemaFile.version;
1028
- const dbUpdatedAt = matchingDraft.updatedAt || loadedAt;
1029
- sendBack({
1030
- type: 'loadOrCreateSchemaSuccess',
1031
- schema: schemaFile,
1032
- loadedAt,
1033
- dbVersion,
1034
- dbUpdatedAt,
1035
- _liveQueryModelIds: modelIds,
1036
- });
1037
- return;
1038
- }
1039
- catch (error) {
1040
- logger$d(`Error parsing draft schemaData, falling back to file: ${error}`);
1041
- }
1042
- }
1043
- // No matching draft found, proceed with loading from file
1044
- // Find the schema with the highest version
1045
- const latest = matchingSchemas.reduce((prev, current) => current.version > prev.version ? current : prev);
1046
- // Read the file directly to get SchemaFileFormat
1047
- const content = await BaseFileManager.readFileAsString(latest.filePath);
1048
- const schemaFile = JSON.parse(content);
1049
- // Build merged models without mutating schemaFile (read-only approach)
1050
- let mergedModels = { ...(schemaFile.models || {}) };
1051
- // Ensure models are populated (fallback for seed-protocol if missing)
1052
- if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
1053
- try {
1054
- const _mod_6 = await import('./ClientManager-B1r_8P5Z.js');
1055
- const _ns_6 = _mod_6.Y;
1056
- const internalSchema = _ns_6;
1057
- const internalSchemaFile = internalSchema.default;
1058
- mergedModels = { ...(internalSchemaFile.models || {}) };
1059
- logger$d(`Populated models for seed-protocol schema from internal file`);
1060
- }
1061
- catch (error) {
1062
- logger$d(`Error loading internal seed-protocol schema for models:`, error);
1063
- }
1064
- }
1065
- logger$d(`Found existing schema ${schemaName} v${schemaFile.version} from file`);
1066
- // Query model IDs from database if schema exists in DB
1067
- let modelIds = [];
1068
- try {
1069
- const db = BaseDb.getAppDb();
1070
- if (db && schemaFile.id) {
1071
- const schemaRecords = await db
1072
- .select()
1073
- .from(schemas)
1074
- .where(eq(schemas.schemaFileId, schemaFile.id))
1075
- .limit(1);
1076
- if (schemaRecords.length > 0 && schemaRecords[0].id) {
1077
- modelIds = await getModelIdsForSchema$1(schemaRecords[0].id);
1078
- // Create Model instances so they're cached before getContext runs
1079
- await createModelInstances$2(modelIds, evictionEpoch);
1080
- }
1081
- }
1082
- }
1083
- catch (error) {
1084
- logger$d(`Error querying model IDs for schema from file: ${error}`);
1085
- }
1086
- // Track conflict detection metadata (no DB record, use file metadata)
1087
- const loadedAt = Date.now();
1088
- const dbVersion = schemaFile.version;
1089
- const dbUpdatedAt = new Date(schemaFile.metadata.updatedAt).getTime() || loadedAt;
1090
- sendBack({
1091
- type: 'loadOrCreateSchemaSuccess',
1092
- schema: schemaFile,
1093
- loadedAt,
1094
- dbVersion,
1095
- dbUpdatedAt,
1096
- _liveQueryModelIds: modelIds,
1097
- });
1098
- return;
1099
- }
1100
- // STEP 3: Before creating new schema, check database one more time for any existing record
1101
- // This handles the case where a schema exists in DB but wasn't found by name (e.g., name mismatch)
1102
- // or where the file lookup failed but the DB has the correct schemaFileId
1103
- let existingDbSchema;
1104
- try {
1105
- const dbCheck = await db
1106
- .select()
1107
- .from(schemas)
1108
- .where(eq(schemas.name, schemaName))
1109
- .orderBy(desc(schemas.version))
1110
- .limit(1);
1111
- if (dbCheck.length > 0) {
1112
- const foundSchema = dbCheck[0];
1113
- existingDbSchema = foundSchema;
1114
- logger$d(`Found existing DB record for "${schemaName}" before creating new schema (schemaFileId: ${foundSchema.schemaFileId}, isDraft: ${foundSchema.isDraft})`);
1115
- // If we have a schemaFileId, check if file exists with that ID
1116
- if (foundSchema.schemaFileId) {
1117
- const filePath = getSchemaFilePath$2(schemaName, foundSchema.version, foundSchema.schemaFileId);
1118
- const fileExists = await BaseFileManager.pathExists(filePath);
1119
- if (fileExists) {
1120
- logger$d(`File exists for schemaFileId ${foundSchema.schemaFileId}, loading it instead of creating new schema`);
1121
- const content = await BaseFileManager.readFileAsString(filePath);
1122
- const schemaFile = JSON.parse(content);
1123
- // Ensure schema.id matches schemaFileId from database
1124
- if (schemaFile.id !== foundSchema.schemaFileId) {
1125
- logger$d(`Fixing schema ID mismatch: file has id="${schemaFile.id}", DB has schemaFileId="${foundSchema.schemaFileId}". Using DB value.`);
1126
- schemaFile.id = foundSchema.schemaFileId;
1127
- }
1128
- // Query model IDs from database to populate _liveQueryModelIds immediately
1129
- let modelIds = [];
1130
- if (foundSchema.id) {
1131
- modelIds = await getModelIdsForSchema$1(foundSchema.id);
1132
- // Create Model instances so they're cached before getContext runs
1133
- await createModelInstances$2(modelIds, evictionEpoch);
1134
- }
1135
- // Track conflict detection metadata
1136
- const loadedAt = Date.now();
1137
- const dbVersion = foundSchema.version || schemaFile.version;
1138
- const dbUpdatedAt = foundSchema.updatedAt || loadedAt;
1139
- sendBack({
1140
- type: 'loadOrCreateSchemaSuccess',
1141
- schema: schemaFile,
1142
- loadedAt,
1143
- dbVersion,
1144
- dbUpdatedAt,
1145
- _liveQueryModelIds: modelIds,
1146
- });
1147
- return;
1148
- }
1149
- }
1150
- // If it's a draft, load it from schemaData
1151
- if (foundSchema.isDraft === true && foundSchema.schemaData) {
1152
- try {
1153
- const schemaFile = JSON.parse(foundSchema.schemaData);
1154
- // Ensure schema.id matches schemaFileId from database
1155
- if (foundSchema.schemaFileId && schemaFile.id !== foundSchema.schemaFileId) {
1156
- logger$d(`Fixing schema ID mismatch: schemaData has id="${schemaFile.id}", DB has schemaFileId="${foundSchema.schemaFileId}". Using DB value.`);
1157
- schemaFile.id = foundSchema.schemaFileId;
1158
- }
1159
- logger$d(`Loading existing draft from database instead of creating new schema`);
1160
- // Query model IDs from database to populate _liveQueryModelIds immediately
1161
- let modelIds = [];
1162
- if (foundSchema.id) {
1163
- modelIds = await getModelIdsForSchema$1(foundSchema.id);
1164
- // Create Model instances so they're cached before getContext runs
1165
- await createModelInstances$2(modelIds, evictionEpoch);
1166
- }
1167
- // Track conflict detection metadata
1168
- const loadedAt = Date.now();
1169
- const dbVersion = foundSchema.version || schemaFile.version;
1170
- const dbUpdatedAt = foundSchema.updatedAt || loadedAt;
1171
- sendBack({
1172
- type: 'loadOrCreateSchemaSuccess',
1173
- schema: schemaFile,
1174
- loadedAt,
1175
- dbVersion,
1176
- dbUpdatedAt,
1177
- _liveQueryModelIds: modelIds,
1178
- });
1179
- return;
1180
- }
1181
- catch (error) {
1182
- logger$d(`Error parsing existing draft schemaData: ${error}, will create new schema`);
1183
- }
1184
- }
1185
- }
1186
- }
1187
- catch (error) {
1188
- logger$d(`Error checking database before creating new schema: ${error}, proceeding with creation`);
1189
- }
1190
- // STEP 4: Create new schema as draft in database (NOT in file yet)
1191
- const latestVersion = existingDbSchema?.version ? existingDbSchema.version + 1 : await getLatestSchemaVersion(schemaName);
1192
- const newVersion = latestVersion + 1;
1193
- const now = new Date().toISOString();
1194
- const newSchema = {
1195
- $schema: 'https://seedprotocol.org/schemas/data-model/v1',
1196
- version: newVersion,
1197
- id: generateId(), // Generate schema ID when first written
1198
- metadata: {
1199
- name: schemaName,
1200
- createdAt: now,
1201
- updatedAt: now,
1202
- },
1203
- models: {},
1204
- enums: {},
1205
- migrations: [
1206
- {
1207
- version: newVersion,
1208
- timestamp: now,
1209
- description: 'Initial schema',
1210
- changes: [],
1211
- },
1212
- ],
1213
- };
1214
- // Save to database as draft FIRST (before creating any file)
1215
- const schemaData = JSON.stringify(newSchema, null, 2);
1216
- await addSchemaToDb({
1217
- name: schemaName,
1218
- version: newVersion,
1219
- createdAt: new Date(now).getTime(),
1220
- updatedAt: new Date(now).getTime(),
1221
- }, newSchema.id, // schemaFileId
1222
- schemaData, // Full schema content
1223
- true);
1224
- logger$d(`Created new draft schema ${schemaName} v${newVersion} in database`);
1225
- // Query model IDs from database for newly created schema
1226
- let modelIds = [];
1227
- try {
1228
- const db = BaseDb.getAppDb();
1229
- if (db && newSchema.id) {
1230
- const schemaRecords = await db
1231
- .select()
1232
- .from(schemas)
1233
- .where(eq(schemas.schemaFileId, newSchema.id))
1234
- .limit(1);
1235
- if (schemaRecords.length > 0 && schemaRecords[0].id) {
1236
- modelIds = await getModelIdsForSchema$1(schemaRecords[0].id);
1237
- // Create Model instances so they're cached before getContext runs
1238
- await createModelInstances$2(modelIds, evictionEpoch);
1239
- }
1240
- }
1241
- }
1242
- catch (error) {
1243
- logger$d(`Error querying model IDs for new schema: ${error}`);
1244
- }
1245
- // Track conflict detection metadata for new schema
1246
- const loadedAt = Date.now();
1247
- const dbVersion = newVersion;
1248
- const dbUpdatedAt = new Date(now).getTime();
1249
- sendBack({
1250
- type: 'loadOrCreateSchemaSuccess',
1251
- schema: newSchema,
1252
- loadedAt,
1253
- dbVersion,
1254
- dbUpdatedAt,
1255
- _liveQueryModelIds: modelIds,
1256
- });
1257
- };
1258
- _loadOrCreateSchema().catch((error) => {
1259
- logger$d('Error loading or creating schema:', error);
1260
- sendBack({ type: 'loadOrCreateSchemaError', error });
1261
- });
1262
- return () => {
1263
- // Cleanup function (optional)
1264
- };
1265
- });
10
+ import { aj as ActorKeyedState, N as DEFAULT_READY_TIMEOUT_MS, B as waitForEntityIdle, P as createReactiveProxy, R as findEntity, W as ClientManagerState, ak as clearDestroySubscriptions, S as forceRemoveFromCaches, al as unloadEntity, T as runDestroyLifecycle } from './Item-0oDoTPhi.js';
1266
11
 
1267
12
  const validationService = new SchemaValidationService();
1268
13
  // Validation timeout in milliseconds (10 seconds)
@@ -1378,9 +123,9 @@ const createModelInstances$1 = async (modelIds, evictionEpoch) => {
1378
123
  return;
1379
124
  }
1380
125
  try {
1381
- const _mod_7 = await import('./errors-rIWK7gwJ.js');
1382
- const _ns_7 = _mod_7.i;
1383
- const mod = _ns_7;
126
+ const _mod_0 = await import('./errors-D1zHAqjr.js');
127
+ const _ns_0 = _mod_0.i;
128
+ const mod = _ns_0;
1384
129
  const Model = mod?.Model ?? mod?.default;
1385
130
  if (!Model) {
1386
131
  logger$c('Model not available from dynamic import');
@@ -1430,9 +175,9 @@ const checkExistingSchema = fromCallback(({ sendBack, input: { context } }) => {
1430
175
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
1431
176
  // For Seed Protocol, check if it exists in database
1432
177
  try {
1433
- const _mod_8 = await import('./ClientManager-B1r_8P5Z.js');
1434
- const _ns_8 = _mod_8.Y;
1435
- const internalSchema = _ns_8;
178
+ const _mod_1 = await import('./ClientManager-GZfXErDX.js');
179
+ const _ns_1 = _mod_1.T;
180
+ const internalSchema = _ns_1;
1436
181
  const schemaFile = internalSchema.default;
1437
182
  if (db && schemaFile.id) {
1438
183
  const existing = await db
@@ -1766,9 +511,9 @@ const writeSchemaToDb = fromCallback(({ sendBack, input }) => {
1766
511
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
1767
512
  // For Seed Protocol, load from internal file
1768
513
  logger$b(`Loading internal Seed Protocol schema from SDK`);
1769
- const _mod_9 = await import('./ClientManager-B1r_8P5Z.js');
1770
- const _ns_9 = _mod_9.Y;
1771
- const internalSchema = _ns_9;
514
+ const _mod_2 = await import('./ClientManager-GZfXErDX.js');
515
+ const _ns_2 = _mod_2.T;
516
+ const internalSchema = _ns_2;
1772
517
  finalSchema = internalSchema.default;
1773
518
  const db = BaseDb.getAppDb();
1774
519
  if (db && finalSchema.id) {
@@ -2239,9 +984,9 @@ const createModelInstances = fromCallback(({ sendBack, input }) => {
2239
984
  return;
2240
985
  }
2241
986
  try {
2242
- const _mod_10 = await import('./errors-rIWK7gwJ.js');
2243
- const _ns_10 = _mod_10.i;
2244
- const modelMod = _ns_10;
987
+ const _mod_3 = await import('./errors-D1zHAqjr.js');
988
+ const _ns_3 = _mod_3.i;
989
+ const modelMod = _ns_3;
2245
990
  const { Model } = modelMod;
2246
991
  // Create instances for all model IDs in parallel
2247
992
  // Model.createById() will check cache first, then query DB and create if needed
@@ -2331,9 +1076,9 @@ const verifyModelInstancesInCache = fromCallback(({ sendBack, input }) => {
2331
1076
  }
2332
1077
  try {
2333
1078
  const result = await verifyWithRetry$2(async () => {
2334
- const _mod_11 = await import('./errors-rIWK7gwJ.js');
2335
- const _ns_11 = _mod_11.i;
2336
- const modelMod = _ns_11;
1079
+ const _mod_4 = await import('./errors-D1zHAqjr.js');
1080
+ const _ns_4 = _mod_4.i;
1081
+ const modelMod = _ns_4;
2337
1082
  const { Model } = modelMod;
2338
1083
  // Check each model ID in the cache
2339
1084
  const verifiedInstances = [];
@@ -2390,9 +1135,9 @@ const writePropertiesToDb = fromCallback(({ sendBack, input }) => {
2390
1135
  const _write = async () => {
2391
1136
  const { modelIds } = input;
2392
1137
  try {
2393
- const _mod_12 = await import('./index-C0SetTd1.js');
2394
- const _ns_12 = _mod_12.bj;
2395
- const modelSchemaMod = _ns_12;
1138
+ const _mod_5 = await import('./index-Dx_GTdyQ.js');
1139
+ const _ns_5 = _mod_5.ba;
1140
+ const modelSchemaMod = _ns_5;
2396
1141
  const { models: modelsTable, properties: propertiesTable } = modelSchemaMod;
2397
1142
  const drizzleMod = await import('drizzle-orm');
2398
1143
  const { eq } = drizzleMod;
@@ -2580,11 +1325,11 @@ const createPropertyInstances = fromCallback(({ sendBack, input }) => {
2580
1325
  return;
2581
1326
  }
2582
1327
  try {
2583
- const modProp = await import('./ModelProperty-C3749Wjq.js');
1328
+ const modProp = await import('./ModelProperty-i5flwzQG.js');
2584
1329
  const ModelProperty = modProp?.ModelProperty ?? modProp?.default;
2585
- const _mod_13 = await import('./errors-rIWK7gwJ.js');
2586
- const _ns_13 = _mod_13.i;
2587
- const modModel = _ns_13;
1330
+ const _mod_6 = await import('./errors-D1zHAqjr.js');
1331
+ const _ns_6 = _mod_6.i;
1332
+ const modModel = _ns_6;
2588
1333
  const Model = modModel?.Model ?? modModel?.default;
2589
1334
  if (!ModelProperty || !Model) {
2590
1335
  logger$3('ModelProperty or Model not available from dynamic import');
@@ -2689,7 +1434,7 @@ const verifyPropertyInstancesInCache = fromCallback(({ sendBack, input }) => {
2689
1434
  }
2690
1435
  try {
2691
1436
  const result = await verifyWithRetry(async () => {
2692
- const mod = await import('./ModelProperty-C3749Wjq.js');
1437
+ const mod = await import('./ModelProperty-i5flwzQG.js');
2693
1438
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
2694
1439
  if (!ModelProperty) {
2695
1440
  throw new Error('ModelProperty not available from dynamic import');
@@ -2747,9 +1492,7 @@ const schemaMachine = setup({
2747
1492
  events: {},
2748
1493
  },
2749
1494
  actors: {
2750
- loadOrCreateSchema,
2751
1495
  validateSchema,
2752
- writeProcessMachine,
2753
1496
  // Staged loading actors
2754
1497
  checkExistingSchema,
2755
1498
  writeSchemaToDb,
@@ -2779,34 +1522,47 @@ const schemaMachine = setup({
2779
1522
  _liveQueryModelIds: [],
2780
1523
  }),
2781
1524
  on: {
2782
- updateContext: {
2783
- actions: assign(({ context, event }) => {
2784
- const newContext = Object.assign({}, context);
2785
- // Check if this is only updating internal fields
2786
- Object.keys(event).every((key) => {
2787
- return key === 'type' || key.startsWith('_');
2788
- });
2789
- for (let i = 0; i < Object.keys(event).length; i++) {
2790
- const key = Object.keys(event)[i];
2791
- if (key === 'type') {
2792
- continue;
1525
+ updateContext: [{
1526
+ actions: assign(({ context, event }) => {
1527
+ const newContext = Object.assign({}, context);
1528
+ // Check if this is only updating internal fields
1529
+ Object.keys(event).every((key) => {
1530
+ return key === 'type' || key.startsWith('_');
1531
+ });
1532
+ for (let i = 0; i < Object.keys(event).length; i++) {
1533
+ const key = Object.keys(event)[i];
1534
+ if (key === 'type') {
1535
+ continue;
1536
+ }
1537
+ if (key in newContext || key.startsWith('_')) {
1538
+ newContext[key] = event[key];
1539
+ }
2793
1540
  }
2794
- if (key in newContext || key.startsWith('_')) {
2795
- newContext[key] = event[key];
1541
+ // Clear validation errors on context update (will be re-validated if needed)
1542
+ newContext._validationErrors = undefined;
1543
+ return newContext;
1544
+ }),
1545
+ // Only trigger validation if we're updating non-internal fields
1546
+ guard: ({ event }) => {
1547
+ return !Object.keys(event).every((key) => {
1548
+ return key === 'type' || key.startsWith('_');
1549
+ });
1550
+ },
1551
+ target: '.validating',
1552
+ }, {
1553
+ // Internal-only updates (e.g. the _dbUpdatedAt refresh after a draft save) are applied
1554
+ // without re-validating. Dropping them made the next save's conflict check compare
1555
+ // against a stale _dbUpdatedAt.
1556
+ actions: assign(({ context, event }) => {
1557
+ const newContext = Object.assign({}, context);
1558
+ for (const key of Object.keys(event)) {
1559
+ if (key.startsWith('_')) {
1560
+ newContext[key] = event[key];
1561
+ }
2796
1562
  }
2797
- }
2798
- // Clear validation errors on context update (will be re-validated if needed)
2799
- newContext._validationErrors = undefined;
2800
- return newContext;
2801
- }),
2802
- // Only trigger validation if we're updating non-internal fields
2803
- guard: ({ event }) => {
2804
- return !Object.keys(event).every((key) => {
2805
- return key === 'type' || key.startsWith('_');
2806
- });
2807
- },
2808
- target: '.validating',
2809
- },
1563
+ return newContext;
1564
+ }),
1565
+ }],
2810
1566
  validateSchema: {
2811
1567
  target: '.validating',
2812
1568
  },
@@ -3209,61 +1965,8 @@ const schemaMachine = setup({
3209
1965
  },
3210
1966
  },
3211
1967
  },
3212
- on: {
3213
- // Keep backward compatibility with old loadOrCreateSchema (for external callers)
3214
- loadOrCreateSchemaSuccess: {
3215
- target: 'idle',
3216
- actions: assign(({ event }) => {
3217
- return {
3218
- schemaName: event.schema.metadata.name,
3219
- $schema: event.schema.$schema,
3220
- version: event.schema.version,
3221
- metadata: event.schema.metadata,
3222
- models: event.schema.models,
3223
- enums: event.schema.enums,
3224
- migrations: event.schema.migrations,
3225
- nameMatch: event.schema.nameMatch,
3226
- _isDraft: false,
3227
- _editedProperties: new Set(),
3228
- _validationErrors: undefined,
3229
- id: event.schema.id, // schemaFileId (string)
3230
- _dbId: event._dbId, // Database integer ID
3231
- _loadedAt: event.loadedAt,
3232
- _dbVersion: event.dbVersion,
3233
- _dbUpdatedAt: event.dbUpdatedAt,
3234
- _liveQueryModelIds: event._liveQueryModelIds || [],
3235
- };
3236
- }),
3237
- },
3238
- loadOrCreateSchemaError: {
3239
- target: 'error',
3240
- },
3241
- },
3242
1968
  },
3243
1969
  idle: {
3244
- entry: assign({
3245
- writeProcess: ({ spawn, context }) => {
3246
- if (!context.writeProcess && context.id) {
3247
- return spawn(writeProcessMachine, {
3248
- input: {
3249
- entityType: 'schema',
3250
- entityId: context.id,
3251
- entityData: {
3252
- name: context.schemaName,
3253
- $schema: context.$schema,
3254
- version: context.version,
3255
- metadata: context.metadata,
3256
- models: context.models,
3257
- enums: context.enums,
3258
- migrations: context.migrations,
3259
- nameMatch: context.nameMatch,
3260
- },
3261
- },
3262
- });
3263
- }
3264
- return context.writeProcess;
3265
- },
3266
- }),
3267
1970
  on: {
3268
1971
  validateSchema: {
3269
1972
  target: 'validating',
@@ -3271,16 +1974,6 @@ const schemaMachine = setup({
3271
1974
  reloadFromDb: {
3272
1975
  target: 'loading',
3273
1976
  },
3274
- requestWrite: {
3275
- actions: ({ context, event }) => {
3276
- if (context.writeProcess) {
3277
- context.writeProcess.send({
3278
- type: 'startWrite',
3279
- data: event.data,
3280
- });
3281
- }
3282
- },
3283
- },
3284
1977
  },
3285
1978
  // No `always: hasValidationErrors -> validating` here: validation is re-run when the context changes
3286
1979
  // (updateContext) or on request (validateSchema). Re-entering while errors exist would loop
@@ -3709,9 +2402,9 @@ async function loadSchemaWithRenames(schemaFilePath, modelRenames) {
3709
2402
  updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
3710
2403
  };
3711
2404
  // Use dynamic import to break circular dependency
3712
- const _mod_14 = await import('./index-C0SetTd1.js');
3713
- const _ns_14 = _mod_14.bo;
3714
- const dbMod = _ns_14;
2405
+ const _mod_7 = await import('./index-Dx_GTdyQ.js');
2406
+ const _ns_7 = _mod_7.bf;
2407
+ const dbMod = _ns_7;
3715
2408
  const { addSchemaToDb, addModelsToDb } = dbMod;
3716
2409
  // Add schema to database with schemaFileId
3717
2410
  const schemaRecord = await addSchemaToDb(schemaInput, schemaFile.id);
@@ -3833,9 +2526,9 @@ async function renameModelProperty(schemaName, modelName, oldPropertyName, newPr
3833
2526
  await BaseFileManager.waitForFileWithContent(newFilePath);
3834
2527
  logger$1(`Renamed property ${oldPropertyName} to ${newPropertyName} in schema ${schemaName} v${newVersion}`);
3835
2528
  // Migrate metadata rows so ItemProperty values follow the new name (prevents duplicate ItemProperties)
3836
- const _mod_15 = await import('./index-C0SetTd1.js');
3837
- const _ns_15 = _mod_15.bo;
3838
- const { migrateMetadataForPropertyRename } = _ns_15;
2529
+ const _mod_8 = await import('./index-Dx_GTdyQ.js');
2530
+ const _ns_8 = _mod_8.bf;
2531
+ const { migrateMetadataForPropertyRename } = _ns_8;
3839
2532
  const migratedCount = await migrateMetadataForPropertyRename(modelName, oldPropertyName, newPropertyName, oldProperty.id, { schemaName });
3840
2533
  if (migratedCount > 0) {
3841
2534
  logger$1(`Migrated ${migratedCount} metadata rows for property rename`);
@@ -3852,238 +2545,10 @@ async function renameModelProperty(schemaName, modelName, oldPropertyName, newPr
3852
2545
  deferredSchemaReloads.add(reload);
3853
2546
  return newFilePath;
3854
2547
  }
3855
- /**
3856
- * Delete a model from a schema
3857
- * @param schemaName - The name of the schema
3858
- * @param modelName - The name of the model to delete
3859
- * @param options - Optional deletion options
3860
- * @returns The file path of the new schema version
3861
- * @throws Error if schema or model not found
3862
- */
3863
- async function deleteModelFromSchema(schemaName, modelName, options = {}) {
3864
- const { removeReferencingProperties = false } = options;
3865
- // Get the latest version
3866
- const latestVersion = await getLatestSchemaVersion(schemaName);
3867
- if (latestVersion === 0) {
3868
- throw new Error(`Schema ${schemaName} not found`);
3869
- }
3870
- // Get schemaFileId from database
3871
- const schemaFileId = await getSchemaFileId(schemaName);
3872
- // Load the latest schema file
3873
- const latestFilePath = getSchemaFilePath(schemaName, latestVersion, schemaFileId);
3874
- const content = await BaseFileManager.readFileAsString(latestFilePath);
3875
- const schemaFile = JSON.parse(content);
3876
- if (!schemaFile.$schema) {
3877
- throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
3878
- }
3879
- if (!schemaFile.models[modelName]) {
3880
- throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
3881
- }
3882
- // Create new version without the model
3883
- // Preserve IDs for remaining models and properties
3884
- const newVersion = latestVersion + 1;
3885
- const updatedSchema = {
3886
- ...schemaFile,
3887
- version: newVersion,
3888
- id: schemaFile.id, // Preserve schema ID
3889
- metadata: {
3890
- ...schemaFile.metadata,
3891
- updatedAt: new Date().toISOString(),
3892
- },
3893
- // Preserve IDs for remaining models and their properties
3894
- models: Object.fromEntries(Object.entries(schemaFile.models)
3895
- .filter(([name]) => name !== modelName)
3896
- .map(([name, model]) => [
3897
- name,
3898
- {
3899
- ...model,
3900
- id: model.id, // Preserve model ID
3901
- properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
3902
- propName,
3903
- { ...prop, id: prop.id }, // Preserve property ID
3904
- ])),
3905
- },
3906
- ])),
3907
- migrations: [
3908
- ...schemaFile.migrations,
3909
- {
3910
- version: newVersion,
3911
- timestamp: new Date().toISOString(),
3912
- description: `Deleted model ${modelName} from schema`,
3913
- changes: [
3914
- {
3915
- type: 'model_delete',
3916
- modelName,
3917
- removeReferencingProperties,
3918
- },
3919
- ],
3920
- },
3921
- ],
3922
- };
3923
- // Remove the model
3924
- delete updatedSchema.models[modelName];
3925
- // Handle properties that reference this model
3926
- const propertiesToRemove = [];
3927
- for (const [otherModelName, model] of Object.entries(updatedSchema.models)) {
3928
- for (const [propertyName, property] of Object.entries(model.properties)) {
3929
- // Check if property references the deleted model
3930
- if (property.model === modelName || property.ref === modelName || property.items?.model === modelName) {
3931
- if (removeReferencingProperties) {
3932
- // Mark for removal
3933
- propertiesToRemove.push({ modelName: otherModelName, propertyName });
3934
- }
3935
- else {
3936
- // Remove the reference (set to null or remove model field)
3937
- if (property.model === modelName) {
3938
- delete property.model;
3939
- }
3940
- if (property.ref === modelName && (isDataType(property.type, ModelPropertyDataTypes.List) || isDataType(property.dataType, ModelPropertyDataTypes.List))) {
3941
- delete property.ref;
3942
- }
3943
- if (property.items?.model === modelName) {
3944
- delete property.items.model;
3945
- }
3946
- }
3947
- }
3948
- }
3949
- }
3950
- // Remove properties if requested
3951
- if (removeReferencingProperties) {
3952
- for (const { modelName: mName, propertyName } of propertiesToRemove) {
3953
- delete updatedSchema.models[mName].properties[propertyName];
3954
- updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
3955
- type: 'property_delete',
3956
- modelName: mName,
3957
- propertyName,
3958
- reason: `Referenced deleted model ${modelName}`,
3959
- });
3960
- }
3961
- }
3962
- else {
3963
- // Update migration to note which properties were updated
3964
- const updatedProperties = [];
3965
- for (const [otherModelName, model] of Object.entries(updatedSchema.models)) {
3966
- for (const [propertyName, property] of Object.entries(model.properties)) {
3967
- if (property.model === modelName || property.ref === modelName || property.items?.model === modelName) {
3968
- updatedProperties.push({ modelName: otherModelName, propertyName });
3969
- }
3970
- }
3971
- }
3972
- if (updatedProperties.length > 0) {
3973
- updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
3974
- type: 'properties_updated',
3975
- properties: updatedProperties,
3976
- reason: `Removed references to deleted model ${modelName}`,
3977
- });
3978
- }
3979
- }
3980
- // Write the new schema version using ID-based naming (preferred)
3981
- const newFilePath = getSchemaFilePath(schemaName, newVersion, updatedSchema.id ?? undefined);
3982
- const newContent = JSON.stringify(updatedSchema, null, 2);
3983
- // Ensure the directory exists before saving
3984
- const path = BaseFileManager.getPathModule();
3985
- const dir = path.dirname(newFilePath);
3986
- await BaseFileManager.createDirIfNotExists(dir);
3987
- await BaseFileManager.saveFile(newFilePath, newContent);
3988
- // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
3989
- await BaseFileManager.waitForFileWithContent(newFilePath);
3990
- logger$1(`Deleted model ${modelName} from schema ${schemaName} v${newVersion}`);
3991
- // Load the new schema file
3992
- await loadSchemaFromFile(newFilePath);
3993
- return newFilePath;
3994
- }
3995
- /**
3996
- * Delete a property from a model in a schema
3997
- * @param schemaName - The name of the schema
3998
- * @param modelName - The name of the model
3999
- * @param propertyName - The name of the property to delete
4000
- * @param options - Optional deletion options
4001
- * @returns The file path of the new schema version
4002
- * @throws Error if schema, model, or property not found
4003
- */
4004
- async function deletePropertyFromModel(schemaName, modelName, propertyName, _options = {}) {
4005
- // Get the latest version
4006
- const latestVersion = await getLatestSchemaVersion(schemaName);
4007
- if (latestVersion === 0) {
4008
- throw new Error(`Schema ${schemaName} not found`);
4009
- }
4010
- // Get schemaFileId from database
4011
- const schemaFileId = await getSchemaFileId(schemaName);
4012
- // Load the latest schema file
4013
- const latestFilePath = getSchemaFilePath(schemaName, latestVersion, schemaFileId);
4014
- const content = await BaseFileManager.readFileAsString(latestFilePath);
4015
- const schemaFile = JSON.parse(content);
4016
- if (!schemaFile.$schema) {
4017
- throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
4018
- }
4019
- const model = schemaFile.models[modelName];
4020
- if (!model) {
4021
- throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
4022
- }
4023
- if (!model.properties[propertyName]) {
4024
- throw new Error(`Property ${propertyName} not found in model ${modelName} of schema ${schemaName}`);
4025
- }
4026
- // Create new version without the property
4027
- // Preserve IDs for schema, models, and remaining properties
4028
- const newVersion = latestVersion + 1;
4029
- const updatedSchema = {
4030
- ...schemaFile,
4031
- version: newVersion,
4032
- id: schemaFile.id, // Preserve schema ID
4033
- metadata: {
4034
- ...schemaFile.metadata,
4035
- updatedAt: new Date().toISOString(),
4036
- },
4037
- models: Object.fromEntries(Object.entries(schemaFile.models).map(([mName, m]) => [
4038
- mName,
4039
- {
4040
- ...m,
4041
- id: m.id, // Preserve model ID
4042
- properties: Object.fromEntries(Object.entries(m.properties)
4043
- .filter(([propName]) => !(mName === modelName && propName === propertyName))
4044
- .map(([propName, prop]) => [
4045
- propName,
4046
- { ...prop, id: prop.id }, // Preserve property ID
4047
- ])),
4048
- },
4049
- ])),
4050
- migrations: [
4051
- ...schemaFile.migrations,
4052
- {
4053
- version: newVersion,
4054
- timestamp: new Date().toISOString(),
4055
- description: `Deleted property ${modelName}.${propertyName} from schema`,
4056
- changes: [
4057
- {
4058
- type: 'property_delete',
4059
- modelName,
4060
- propertyName,
4061
- },
4062
- ],
4063
- },
4064
- ],
4065
- };
4066
- // Write the new schema version using ID-based naming (preferred)
4067
- const newFilePath = getSchemaFilePath(schemaName, newVersion, updatedSchema.id ?? undefined);
4068
- const newContent = JSON.stringify(updatedSchema, null, 2);
4069
- // Ensure the directory exists before saving
4070
- const path = BaseFileManager.getPathModule();
4071
- const dir = path.dirname(newFilePath);
4072
- await BaseFileManager.createDirIfNotExists(dir);
4073
- await BaseFileManager.saveFile(newFilePath, newContent);
4074
- // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
4075
- await BaseFileManager.waitForFileWithContent(newFilePath);
4076
- logger$1(`Deleted property ${propertyName} from model ${modelName} in schema ${schemaName} v${newVersion}`);
4077
- // Load the new schema file
4078
- await loadSchemaFromFile(newFilePath);
4079
- return newFilePath;
4080
- }
4081
2548
 
4082
2549
  var updateSchema = /*#__PURE__*/Object.freeze({
4083
2550
  __proto__: null,
4084
2551
  convertPropertyToSchemaUpdate: convertPropertyToSchemaUpdate,
4085
- deleteModelFromSchema: deleteModelFromSchema,
4086
- deletePropertyFromModel: deletePropertyFromModel,
4087
2552
  getModelNameFromId: getModelNameFromId,
4088
2553
  renameModelProperty: renameModelProperty,
4089
2554
  updateModelProperties: updateModelProperties,
@@ -4834,7 +3299,7 @@ class Schema {
4834
3299
  const modelDbId = modelInstance.getService().getSnapshot().context._dbId;
4835
3300
  const db = BaseDb.getAppDb();
4836
3301
  if (propertyContexts.length === 0 && modelDbId && db) {
4837
- const { ModelProperty } = await import('./ModelProperty-C3749Wjq.js');
3302
+ const { ModelProperty } = await import('./ModelProperty-i5flwzQG.js');
4838
3303
  const rows = await db.select().from(properties).where(eq(properties.modelId, modelDbId));
4839
3304
  propertyContexts = rows.map((row) => {
4840
3305
  const cached = row.schemaFileId ? ModelProperty.getById(row.schemaFileId) : undefined;
@@ -5000,7 +3465,7 @@ class Schema {
5000
3465
  savedSchema: publishedSchema,
5001
3466
  });
5002
3467
  // Clear edited flags on all ModelProperty instances and in database
5003
- const modelPropertyMod = await import('./ModelProperty-C3749Wjq.js');
3468
+ const modelPropertyMod = await import('./ModelProperty-i5flwzQG.js');
5004
3469
  const { ModelProperty } = modelPropertyMod;
5005
3470
  for (const propertyKey of context._editedProperties) {
5006
3471
  const [modelName, propertyName] = propertyKey.split(':');
@@ -5023,9 +3488,9 @@ class Schema {
5023
3488
  try {
5024
3489
  if (db && modelName && propertyName) {
5025
3490
  // Find this schema's model by name
5026
- const _mod_16 = await import('./index-C0SetTd1.js');
5027
- const _ns_16 = _mod_16.bn;
5028
- const { resolveModelRecord } = _ns_16;
3491
+ const _mod_9 = await import('./index-Dx_GTdyQ.js');
3492
+ const _ns_9 = _mod_9.be;
3493
+ const { resolveModelRecord } = _ns_9;
5029
3494
  const modelRecord = await resolveModelRecord(modelName, { schemaName: thisSchemaName }, db);
5030
3495
  const modelRecords = modelRecord ? [modelRecord] : [];
5031
3496
  if (modelRecords.length > 0) {
@@ -5655,12 +4120,12 @@ class Schema {
5655
4120
  // instances too, or a re-import would get them back with dangling _dbIds.
5656
4121
  if (schemaName) {
5657
4122
  const evictedModelNames = Model.evictForSchema(schemaName);
5658
- const { ModelProperty } = await import('./ModelProperty-C3749Wjq.js');
4123
+ const { ModelProperty } = await import('./ModelProperty-i5flwzQG.js');
5659
4124
  ModelProperty.evictForModels(evictedModelNames, schemaName);
5660
4125
  // Evicting stops new writes but not ones already running; let those land before deleting their rows
5661
- const _mod_17 = await import('./errors-rIWK7gwJ.js');
5662
- const _ns_17 = _mod_17.h;
5663
- const { waitForInFlightWrites } = _ns_17;
4126
+ const _mod_10 = await import('./errors-D1zHAqjr.js');
4127
+ const _ns_10 = _mod_10.h;
4128
+ const { waitForInFlightWrites } = _ns_10;
5664
4129
  await waitForInFlightWrites();
5665
4130
  }
5666
4131
  await runDestroyLifecycle(this, {
@@ -5691,7 +4156,7 @@ class Schema {
5691
4156
  .map((r) => r.modelId)
5692
4157
  .filter((id) => id != null)),
5693
4158
  ];
5694
- const { detachModelRows } = await import('./detachRowsBeforeDelete-Bo_pky-R.js');
4159
+ const { detachModelRows } = await import('./detachRowsBeforeDelete-DXFYSHRR.js');
5695
4160
  await detachModelRows(db, modelIds);
5696
4161
  await db.delete(modelSchemas).where(inArray(modelSchemas.schemaId, schemaIds));
5697
4162
  for (const modelId of modelIds) {
@@ -5706,9 +4171,9 @@ class Schema {
5706
4171
  // the destroyed schema back on the next Schema.all().
5707
4172
  // Match on name as well as id: versions imported from complete schema files can each
5708
4173
  // have their own id, and any version left behind would bring the schema back.
5709
- const _mod_18 = await import('./ClientManager-B1r_8P5Z.js');
5710
- const _ns_18 = _mod_18.X;
5711
- const { listCompleteSchemaFiles } = _ns_18;
4174
+ const _mod_11 = await import('./ClientManager-GZfXErDX.js');
4175
+ const _ns_11 = _mod_11.S;
4176
+ const { listCompleteSchemaFiles } = _ns_11;
5712
4177
  const files = await listCompleteSchemaFiles().catch(() => []);
5713
4178
  const fs = await BaseFileManager.getFs();
5714
4179
  const names = new Set([schemaName, metadataName].filter(Boolean));
@@ -5901,5 +4366,5 @@ var Schema$1 = /*#__PURE__*/Object.freeze({
5901
4366
  schemaInstanceState: schemaInstanceState
5902
4367
  });
5903
4368
 
5904
- export { Schema as S, deletePropertyFromModel as a, Schema$1 as b, deleteModelFromSchema as d, renameModelProperty as r, schemaMachine as s, updateModelProperties as u };
5905
- //# sourceMappingURL=Schema-CX9CTtho.js.map
4369
+ export { Schema as S, Schema$1 as a, renameModelProperty as r, schemaMachine as s, updateModelProperties as u };
4370
+ //# sourceMappingURL=Schema-PFZwG9Nl.js.map