@seedprotocol/sdk 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/{BasePathResolver-ndE8XTpw.js → BasePathResolver-DRT09oVv.js} +2 -2
  2. package/dist/{BasePathResolver-ndE8XTpw.js.map → BasePathResolver-DRT09oVv.js.map} +1 -1
  3. package/dist/{ClientManager-DLleL_2e.js → ClientManager-DngaZdw6.js} +20 -20
  4. package/dist/{ClientManager-DLleL_2e.js.map → ClientManager-DngaZdw6.js.map} +1 -1
  5. package/dist/{Item-zBFWQDU9.js → Item-ZUAmf943.js} +118 -72
  6. package/dist/{Item-zBFWQDU9.js.map → Item-ZUAmf943.js.map} +1 -1
  7. package/dist/{ModelProperty-lth9L37R.js → ModelProperty-6llK4MTH.js} +64 -35
  8. package/dist/ModelProperty-6llK4MTH.js.map +1 -0
  9. package/dist/{Schema-DOhlrQ-N.js → Schema-D-Ud-XYw.js} +106 -57
  10. package/dist/Schema-D-Ud-XYw.js.map +1 -0
  11. package/dist/{SchemaValidationService-DDKr5piy.js → SchemaValidationService-IoS7JquP.js} +7 -7
  12. package/dist/{SchemaValidationService-DDKr5piy.js.map → SchemaValidationService-IoS7JquP.js.map} +1 -1
  13. package/dist/{backfillMetadataPropertyIds-fG3ujaSh.js → backfillMetadataPropertyIds-BlVeE7w7.js} +4 -4
  14. package/dist/{backfillMetadataPropertyIds-fG3ujaSh.js.map → backfillMetadataPropertyIds-BlVeE7w7.js.map} +1 -1
  15. package/dist/cjs/{ModelProperty-BEsIHAjk.js → ModelProperty-Dv7AQfmQ.js} +59 -30
  16. package/dist/cjs/ModelProperty-Dv7AQfmQ.js.map +1 -0
  17. package/dist/cjs/{Schema-qEp5mH1N.js → Schema-BHVp1g-M.js} +93 -44
  18. package/dist/cjs/Schema-BHVp1g-M.js.map +1 -0
  19. package/dist/cjs/{SchemaValidationService-CWEnZmOH.js → SchemaValidationService-BSU9knjf.js} +2 -2
  20. package/dist/cjs/{SchemaValidationService-CWEnZmOH.js.map → SchemaValidationService-BSU9knjf.js.map} +1 -1
  21. package/dist/cjs/{backfillMetadataPropertyIds-tw8JGMT0.js → backfillMetadataPropertyIds-WIovQ_d8.js} +3 -3
  22. package/dist/cjs/{backfillMetadataPropertyIds-tw8JGMT0.js.map → backfillMetadataPropertyIds-WIovQ_d8.js.map} +1 -1
  23. package/dist/cjs/{eas-CLiV2Hmn.js → eas-CUYXdr2t.js} +3 -3
  24. package/dist/cjs/{eas-CLiV2Hmn.js.map → eas-CUYXdr2t.js.map} +1 -1
  25. package/dist/cjs/{getItem-DSRtx_68.js → getItem-z1tHu0hu.js} +2 -2
  26. package/dist/cjs/{getItem-DSRtx_68.js.map → getItem-z1tHu0hu.js.map} +1 -1
  27. package/dist/cjs/{getLatestVersionRow-DVizNNoI.js → getLatestVersionRow-CcaabxIW.js} +2 -2
  28. package/dist/cjs/{getLatestVersionRow-DVizNNoI.js.map → getLatestVersionRow-CcaabxIW.js.map} +1 -1
  29. package/dist/cjs/{getPublishPayload-D5-dYtNq.js → getPublishPayload-CEP_e-Kv.js} +160 -204
  30. package/dist/cjs/getPublishPayload-CEP_e-Kv.js.map +1 -0
  31. package/dist/cjs/{getPublishUploads-B5Lq6q-_.js → getPublishUploads-Ctn5k1k6.js} +49 -10
  32. package/dist/cjs/getPublishUploads-Ctn5k1k6.js.map +1 -0
  33. package/dist/cjs/{index-C66AfYDG.js → index-Cvvt0-5B.js} +244 -87
  34. package/dist/cjs/index-Cvvt0-5B.js.map +1 -0
  35. package/dist/cjs/{index-B3UDbm1C.js → index-DfGhF1dc.js} +3 -3
  36. package/dist/cjs/index-DfGhF1dc.js.map +1 -0
  37. package/dist/cjs/{property-BVJIP7SX.js → property-DbEPQ1m9.js} +5 -5
  38. package/dist/cjs/{property-BVJIP7SX.js.map → property-DbEPQ1m9.js.map} +1 -1
  39. package/dist/cjs/publishDraftGraph-C38gf302.js +403 -0
  40. package/dist/cjs/publishDraftGraph-C38gf302.js.map +1 -0
  41. package/dist/cjs/{resetAmbiguousLegacyItemData-BaZqUui9.js → resetAmbiguousLegacyItemData-CfMhRHwK.js} +2 -2
  42. package/dist/cjs/{resetAmbiguousLegacyItemData-BaZqUui9.js.map → resetAmbiguousLegacyItemData-CfMhRHwK.js.map} +1 -1
  43. package/dist/cjs/{resolveModelForSyncedSeed-CC6dQctx.js → resolveModelForSyncedSeed-CNYaLOir.js} +2 -2
  44. package/dist/cjs/{resolveModelForSyncedSeed-CC6dQctx.js.map → resolveModelForSyncedSeed-CNYaLOir.js.map} +1 -1
  45. package/dist/cjs/{syncDbWithEas-Dk96sAG-.js → syncDbWithEas-d1iOdTTI.js} +20 -7
  46. package/dist/cjs/{syncDbWithEas-Dk96sAG-.js.map → syncDbWithEas-d1iOdTTI.js.map} +1 -1
  47. package/dist/{configurePlatform-BMoPG9vY.js → configurePlatform-CZpjyuCo.js} +4 -4
  48. package/dist/{configurePlatform-BMoPG9vY.js.map → configurePlatform-CZpjyuCo.js.map} +1 -1
  49. package/dist/{db-BJZN0a0a.js → db-Lw0KVZmc.js} +11 -11
  50. package/dist/{db-BJZN0a0a.js.map → db-Lw0KVZmc.js.map} +1 -1
  51. package/dist/{eas-B0hsMLqt.js → eas-CQ-Smzk2.js} +6 -6
  52. package/dist/{eas-B0hsMLqt.js.map → eas-CQ-Smzk2.js.map} +1 -1
  53. package/dist/{getItem-DEh4WfHG.js → getItem-CSfSok9f.js} +5 -5
  54. package/dist/{getItem-DEh4WfHG.js.map → getItem-CSfSok9f.js.map} +1 -1
  55. package/dist/{getLatestVersionRow-Brrl1AnW.js → getLatestVersionRow-72Atl9vB.js} +5 -5
  56. package/dist/{getLatestVersionRow-Brrl1AnW.js.map → getLatestVersionRow-72Atl9vB.js.map} +1 -1
  57. package/dist/{getPublishPayload-H032DHC7.js → getPublishPayload-76_KfB5Y.js} +155 -200
  58. package/dist/getPublishPayload-76_KfB5Y.js.map +1 -0
  59. package/dist/{getPublishUploads-CR66RlGJ.js → getPublishUploads-CqgMBD8f.js} +52 -13
  60. package/dist/getPublishUploads-CqgMBD8f.js.map +1 -0
  61. package/dist/{index-B0LgJblD.js → index-5b3JsS55.js} +2 -2
  62. package/dist/index-5b3JsS55.js.map +1 -0
  63. package/dist/{index-6bJuv5Tt.js → index-BpgD305l.js} +9 -9
  64. package/dist/{index-6bJuv5Tt.js.map → index-BpgD305l.js.map} +1 -1
  65. package/dist/{index-DtfjeuxC.js → index-Y-yYyRBf.js} +166 -75
  66. package/dist/index-Y-yYyRBf.js.map +1 -0
  67. package/dist/{index.browser-CNrqhvEA.js → index.browser-DaTzn79x.js} +9 -9
  68. package/dist/{index.browser-CNrqhvEA.js.map → index.browser-DaTzn79x.js.map} +1 -1
  69. package/dist/{index.node-DrHiTuOr.js → index.node-NYKqFOoe.js} +5 -5
  70. package/dist/{index.node-DrHiTuOr.js.map → index.node-NYKqFOoe.js.map} +1 -1
  71. package/dist/main.cjs +1 -1
  72. package/dist/main.js +257 -181
  73. package/dist/main.js.map +1 -1
  74. package/dist/node.js +12 -12
  75. package/dist/platform.browser.js +5 -5
  76. package/dist/platform.node.js +3 -3
  77. package/dist/{property-D2Nnsmm1.js → property-ByaiSyUK.js} +10 -10
  78. package/dist/{property-D2Nnsmm1.js.map → property-ByaiSyUK.js.map} +1 -1
  79. package/dist/publishDraftGraph-BRm6Pq3Q.js +405 -0
  80. package/dist/publishDraftGraph-BRm6Pq3Q.js.map +1 -0
  81. package/dist/{resetAmbiguousLegacyItemData-BqbHNUYk.js → resetAmbiguousLegacyItemData-B4dX6ZA1.js} +2 -2
  82. package/dist/{resetAmbiguousLegacyItemData-BqbHNUYk.js.map → resetAmbiguousLegacyItemData-B4dX6ZA1.js.map} +1 -1
  83. package/dist/{resolveModelForSyncedSeed-DQK6JfXS.js → resolveModelForSyncedSeed-B0tco3zG.js} +2 -2
  84. package/dist/{resolveModelForSyncedSeed-DQK6JfXS.js.map → resolveModelForSyncedSeed-B0tco3zG.js.map} +1 -1
  85. package/dist/src/Item/Item.d.ts +11 -0
  86. package/dist/src/Item/Item.d.ts.map +1 -1
  87. package/dist/src/ItemProperty/ItemProperty.d.ts +10 -0
  88. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  89. package/dist/src/Model/Model.d.ts +15 -2
  90. package/dist/src/Model/Model.d.ts.map +1 -1
  91. package/dist/src/Model/service/actors/createModelProperties.d.ts.map +1 -1
  92. package/dist/src/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  93. package/dist/src/Model/service/actors/validateModel.d.ts.map +1 -1
  94. package/dist/src/Model/service/modelMachine.d.ts.map +1 -1
  95. package/dist/src/ModelProperty/ModelProperty.d.ts +9 -1
  96. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  97. package/dist/src/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  98. package/dist/src/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  99. package/dist/src/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  100. package/dist/src/Schema/Schema.d.ts +7 -0
  101. package/dist/src/Schema/Schema.d.ts.map +1 -1
  102. package/dist/src/Schema/service/actors/checkExistingSchema.d.ts.map +1 -1
  103. package/dist/src/Schema/service/actors/createModelInstances.d.ts.map +1 -1
  104. package/dist/src/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  105. package/dist/src/db/read/getPublishPayload.d.ts +9 -0
  106. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  107. package/dist/src/db/read/getPublishUploads.d.ts +5 -0
  108. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  109. package/dist/src/db/read/publishDraftGraph.d.ts +57 -0
  110. package/dist/src/db/read/publishDraftGraph.d.ts.map +1 -0
  111. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  112. package/dist/src/helpers/entity/entityLiveQuery.d.ts.map +1 -1
  113. package/dist/src/helpers/entity/evictionEpoch.d.ts +18 -0
  114. package/dist/src/helpers/entity/evictionEpoch.d.ts.map +1 -0
  115. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts +28 -6
  116. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts.map +1 -1
  117. package/dist/src/index.d.ts +2 -1
  118. package/dist/src/index.d.ts.map +1 -1
  119. package/dist/src/services/write/actors/validateEntity.d.ts.map +1 -1
  120. package/dist/src/types/item.d.ts +7 -8
  121. package/dist/src/types/item.d.ts.map +1 -1
  122. package/dist/{syncDbWithEas-LRKr_NZF.js → syncDbWithEas-BPap9Sru.js} +14 -14
  123. package/dist/{syncDbWithEas-LRKr_NZF.js.map → syncDbWithEas-BPap9Sru.js.map} +1 -1
  124. package/dist/{tabEvents-DYI2GU7i.js → tabEvents-C6NXS6Jl.js} +6 -6
  125. package/dist/{tabEvents-DYI2GU7i.js.map → tabEvents-C6NXS6Jl.js.map} +1 -1
  126. package/dist/{tolerantWebAccess-CzOBz5M6.js → tolerantWebAccess-NBQ1NB4i.js} +6 -6
  127. package/dist/{tolerantWebAccess-CzOBz5M6.js.map → tolerantWebAccess-NBQ1NB4i.js.map} +1 -1
  128. package/dist/{updateSeedRevokedAt-B58ORbY3.js → updateSeedRevokedAt-CYwgVNlM.js} +3 -3
  129. package/dist/{updateSeedRevokedAt-B58ORbY3.js.map → updateSeedRevokedAt-CYwgVNlM.js.map} +1 -1
  130. package/package.json +8 -10
  131. package/dist/ModelProperty-lth9L37R.js.map +0 -1
  132. package/dist/Schema-DOhlrQ-N.js.map +0 -1
  133. package/dist/cjs/ModelProperty-BEsIHAjk.js.map +0 -1
  134. package/dist/cjs/Schema-qEp5mH1N.js.map +0 -1
  135. package/dist/cjs/getPublishPayload-D5-dYtNq.js.map +0 -1
  136. package/dist/cjs/getPublishUploads-B5Lq6q-_.js.map +0 -1
  137. package/dist/cjs/getSegmentedItemProperties-giHO7R3d.js +0 -147
  138. package/dist/cjs/getSegmentedItemProperties-giHO7R3d.js.map +0 -1
  139. package/dist/cjs/index-B3UDbm1C.js.map +0 -1
  140. package/dist/cjs/index-C66AfYDG.js.map +0 -1
  141. package/dist/getPublishPayload-H032DHC7.js.map +0 -1
  142. package/dist/getPublishUploads-CR66RlGJ.js.map +0 -1
  143. package/dist/getSegmentedItemProperties-C2EJ2G0N.js +0 -147
  144. package/dist/getSegmentedItemProperties-C2EJ2G0N.js.map +0 -1
  145. package/dist/index-B0LgJblD.js.map +0 -1
  146. package/dist/index-DtfjeuxC.js.map +0 -1
  147. package/dist/src/browser/helpers/index.d.ts +0 -4
  148. package/dist/src/browser/helpers/index.d.ts.map +0 -1
@@ -377,9 +377,14 @@ let revokeExecutor = null;
377
377
  function getRevokeExecutor() {
378
378
  return revokeExecutor;
379
379
  }
380
+ let getAdditionalSyncAddresses = null;
381
+ function getGetAdditionalSyncAddresses() {
382
+ return getAdditionalSyncAddresses;
383
+ }
380
384
 
381
385
  var publishConfig = /*#__PURE__*/Object.freeze({
382
386
  __proto__: null,
387
+ getGetAdditionalSyncAddresses: getGetAdditionalSyncAddresses,
383
388
  getPublisherForNewSeedsWithTimeout: getPublisherForNewSeedsWithTimeout,
384
389
  getRevokeExecutor: getRevokeExecutor,
385
390
  getUploadExecutor: getUploadExecutor
@@ -4421,6 +4426,22 @@ const convertTxIdToImage = async (txId) => {
4421
4426
  return URL.createObjectURL(imageBlob);
4422
4427
  };
4423
4428
 
4429
+ /**
4430
+ * Common getters and utilities for entity classes
4431
+ * These work with any entity that has a getService() method returning an XState actor
4432
+ */
4433
+ /**
4434
+ * Get the current state value from an entity's service
4435
+ */
4436
+ /**
4437
+ * Whether an actor has been stopped (unload, destroy, or Schema eviction). Async work started by an
4438
+ * entity (DB lookups, retry timers) must check this before sending, since a stopped actor ignores
4439
+ * events and XState warns about every one of them.
4440
+ */
4441
+ function isActorStopped(actor) {
4442
+ return actor.getSnapshot().status === 'stopped';
4443
+ }
4444
+
4424
4445
  const logger$w = debug('seedSdk:model:actors:loadOrCreateModel');
4425
4446
  /**
4426
4447
  * Create ModelProperty instances for all property IDs to ensure they're cached
@@ -4432,7 +4453,7 @@ const createPropertyInstances = async (propertyFileIds) => {
4432
4453
  return;
4433
4454
  }
4434
4455
  try {
4435
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BEsIHAjk.js'); });
4456
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-Dv7AQfmQ.js'); });
4436
4457
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
4437
4458
  if (!ModelProperty) {
4438
4459
  logger$w('createPropertyInstances: ModelProperty not available from dynamic import');
@@ -4463,7 +4484,7 @@ const createPropertyInstances = async (propertyFileIds) => {
4463
4484
  // Don't throw - this is best-effort to pre-populate cache
4464
4485
  }
4465
4486
  };
4466
- const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } }) => {
4487
+ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context }, self }) => {
4467
4488
  const _loadOrCreateModel = async () => {
4468
4489
  const { modelName, schemaName, id, _idFromSchema } = context; // id is now the schemaFileId (string)
4469
4490
  if (!modelName || !schemaName) {
@@ -4602,7 +4623,9 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
4602
4623
  .map((record) => record.schemaFileId)
4603
4624
  .filter((id) => id !== null && id !== undefined);
4604
4625
  if (propertyFileIds.length > 0) {
4605
- await createPropertyInstances(propertyFileIds);
4626
+ // Not for a model stopped meanwhile (unloaded, or evicted with its schema)
4627
+ if (!isActorStopped(self))
4628
+ await createPropertyInstances(propertyFileIds);
4606
4629
  }
4607
4630
  // Generate schemaFileId if not set
4608
4631
  if (!schemaFileId) {
@@ -4643,8 +4666,11 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
4643
4666
  // Step 2: Fallback to Schema context (only if database doesn't have the model)
4644
4667
  // This handles the case where model exists in schema file but not yet in database
4645
4668
  try {
4646
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); });
4669
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-BHVp1g-M.js'); });
4647
4670
  const { Schema } = schemaMod;
4671
+ // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
4672
+ if (isActorStopped(self))
4673
+ return;
4648
4674
  const schema = Schema.create(schemaName, { waitForReady: false });
4649
4675
  const schemaSnapshot = schema.getService().getSnapshot();
4650
4676
  // Wait for schema to load if it's still loading
@@ -4885,10 +4911,12 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
4885
4911
  }
4886
4912
  // Mark schema as draft when a new model is created so saveNewVersion() can persist it
4887
4913
  try {
4888
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); });
4914
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-BHVp1g-M.js'); });
4889
4915
  const { Schema } = schemaMod;
4890
- const schema = Schema.create(schemaName, { waitForReady: false });
4891
- schema.getService().send({ type: 'markAsDraft', propertyKey: 'schema:models' });
4916
+ if (!isActorStopped(self)) {
4917
+ const schema = Schema.create(schemaName, { waitForReady: false });
4918
+ schema.getService().send({ type: 'markAsDraft', propertyKey: 'schema:models' });
4919
+ }
4892
4920
  }
4893
4921
  catch (err) {
4894
4922
  logger$w(`Failed to mark schema as draft after creating model: ${err}`);
@@ -4909,7 +4937,7 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
4909
4937
  const logger$v = debug('seedSdk:model:actors:validateModel');
4910
4938
  // Validation timeout in milliseconds (10 seconds)
4911
4939
  const VALIDATION_TIMEOUT_MS = 10000;
4912
- const validateModel = xstate.fromCallback(({ sendBack, input: { context } }) => {
4940
+ const validateModel = xstate.fromCallback(({ sendBack, input: { context }, self }) => {
4913
4941
  let hasResponded = false;
4914
4942
  // Timeout handler to ensure we always respond
4915
4943
  const timeoutId = setTimeout(() => {
@@ -4929,10 +4957,10 @@ const validateModel = xstate.fromCallback(({ sendBack, input: { context } }) =>
4929
4957
  const _validateModel = async () => {
4930
4958
  try {
4931
4959
  // Use dynamic imports to break circular dependencies
4932
- const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-CWEnZmOH.js'); });
4960
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-BSU9knjf.js'); });
4933
4961
  const { SchemaValidationService } = validationServiceMod;
4934
4962
  const validationService = new SchemaValidationService();
4935
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); });
4963
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-BHVp1g-M.js'); });
4936
4964
  const { Schema } = schemaMod;
4937
4965
  // Validate model structure
4938
4966
  const structureResult = validationService.validateModelStructure(context);
@@ -4947,6 +4975,9 @@ const validateModel = xstate.fromCallback(({ sendBack, input: { context } }) =>
4947
4975
  // If we have schema name, validate against schema
4948
4976
  // CRITICAL: Use validateModelAgainstSchema which doesn't require the model to be in schema context
4949
4977
  // This allows validation BEFORE registration, preventing update loops
4978
+ // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
4979
+ if (isActorStopped(self))
4980
+ return;
4950
4981
  if (context.schemaName) {
4951
4982
  try {
4952
4983
  const schema = Schema.create(context.schemaName, {
@@ -5029,7 +5060,11 @@ const validateModel = xstate.fromCallback(({ sendBack, input: { context } }) =>
5029
5060
  });
5030
5061
 
5031
5062
  const logger$u = debug('seedSdk:model:actors:createModelProperties');
5032
- const createModelProperties = xstate.fromCallback(({ sendBack, input }) => {
5063
+ const createModelProperties = xstate.fromCallback(({ sendBack, input, self }) => {
5064
+ // The model was stopped (unloaded, or evicted with its schema by Schema.destroy / test cleanup) while
5065
+ // this ran: stopping it stops this actor too, but can't cancel the awaits below. A stopped model
5066
+ // creates no properties (they'd be cached for a model that's gone, and write rows under it).
5067
+ const stopped = () => isActorStopped(self);
5033
5068
  const _createProperties = async () => {
5034
5069
  const { context, propertyDefinitions } = input;
5035
5070
  const { id, _dbId, modelName, schemaName } = context;
@@ -5042,7 +5077,7 @@ const createModelProperties = xstate.fromCallback(({ sendBack, input }) => {
5042
5077
  return;
5043
5078
  }
5044
5079
  logger$u(`Creating ${Object.keys(propertyDefinitions).length} properties for model "${modelName}" (id: ${_dbId})`);
5045
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BEsIHAjk.js'); });
5080
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-Dv7AQfmQ.js'); });
5046
5081
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
5047
5082
  if (!ModelProperty) {
5048
5083
  logger$u('ModelProperty not available from dynamic import');
@@ -5096,6 +5131,10 @@ const createModelProperties = xstate.fromCallback(({ sendBack, input }) => {
5096
5131
  // Continue without refModelId - it will be resolved later in _initializeOriginalValues
5097
5132
  }
5098
5133
  }
5134
+ if (stopped()) {
5135
+ logger$u(`Model "${modelName}" was stopped while creating its properties; not creating the rest`);
5136
+ return;
5137
+ }
5099
5138
  // Create ModelProperty instance
5100
5139
  // This will load from DB if it exists, or create new instance
5101
5140
  // The property should already be in DB from writeModelToDb
@@ -5134,6 +5173,37 @@ const createModelProperties = xstate.fromCallback(({ sendBack, input }) => {
5134
5173
  };
5135
5174
  });
5136
5175
 
5176
+ /**
5177
+ * Eviction epochs: lets work that was started before a schema's Model/ModelProperty instances were
5178
+ * evicted (Schema.destroy, test cleanup) tell, when it finishes, that it must not put instances for
5179
+ * that schema back in the caches. Stopping the evicted actors can't cancel such work (a DB lookup
5180
+ * that ends in Model.create, a model's property creation), and finishing it after the eviction would
5181
+ * rebuild instances from rows that are about to be deleted, which then write themselves again.
5182
+ *
5183
+ * Capture `currentEvictionEpoch()` when the work starts; before creating or caching an instance, skip
5184
+ * it when `schemaEvictedSince(schemaName, epoch)`. Work started after an eviction is unaffected.
5185
+ */
5186
+ let epoch = 0;
5187
+ const lastEvictionBySchema = new Map();
5188
+ function currentEvictionEpoch() {
5189
+ return epoch;
5190
+ }
5191
+ /** Called by Model.evictForSchema. */
5192
+ function recordSchemaEviction(schemaName) {
5193
+ epoch += 1;
5194
+ lastEvictionBySchema.set(schemaName, epoch);
5195
+ }
5196
+ /** True when the schema's instances were evicted after `since` (an epoch from currentEvictionEpoch). */
5197
+ function schemaEvictedSince(schemaName, since) {
5198
+ if (epoch === since || !schemaName)
5199
+ return false;
5200
+ return (lastEvictionBySchema.get(schemaName) ?? 0) > since;
5201
+ }
5202
+ /** True when any schema was evicted after `since` (cheap check before looking up which schemas apply). */
5203
+ function anyEvictionSince(since) {
5204
+ return epoch !== since;
5205
+ }
5206
+
5137
5207
  const logger$t = debug('seedSdk:write:validateEntity');
5138
5208
  // XState v5 type inference bug: fromPromise types are inverted
5139
5209
  // We use type assertion to work around this
@@ -5141,6 +5211,18 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
5141
5211
  // Type assertion to fix XState v5 type inference bug
5142
5212
  // Convert through unknown to avoid type overlap error
5143
5213
  const entityInput = input;
5214
+ // Validation awaits imports before looking up the schema; the entity can be evicted with its
5215
+ // schema meanwhile (Schema.destroy, test cleanup). Schema.create would then load the evicted
5216
+ // schema again, and its load re-creates the schema's models from rows being deleted.
5217
+ const evictionEpoch = currentEvictionEpoch();
5218
+ /** The schema to validate against; throws (validation then skips the schema check) once it was evicted. */
5219
+ const schemaForValidation = async (schemaName) => {
5220
+ const { Schema } = await Promise.resolve().then(function () { return require('./Schema-BHVp1g-M.js'); });
5221
+ if (schemaEvictedSince(schemaName, evictionEpoch)) {
5222
+ throw new Error(`Schema "${schemaName}" was evicted during validation`);
5223
+ }
5224
+ return Schema.create(schemaName, { waitForReady: false });
5225
+ };
5144
5226
  const _validate = async () => {
5145
5227
  try {
5146
5228
  const msg = `[validateEntity] Starting validation for ${entityInput.entityType}`;
@@ -5151,7 +5233,7 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
5151
5233
  const structureMsg = `[validateEntity] Validating model structure`;
5152
5234
  logger$t(structureMsg);
5153
5235
  // Use existing Model validation
5154
- const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-CWEnZmOH.js'); });
5236
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-BSU9knjf.js'); });
5155
5237
  const { SchemaValidationService } = validationServiceMod;
5156
5238
  const validationService = new SchemaValidationService();
5157
5239
  // Validate model structure
@@ -5169,11 +5251,7 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
5169
5251
  if (entityInput.entityData.schemaName) {
5170
5252
  try {
5171
5253
  logger$t(`[validateEntity] Validating model against schema "${entityInput.entityData.schemaName}"`);
5172
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); });
5173
- const { Schema } = schemaMod;
5174
- const schema = Schema.create(entityInput.entityData.schemaName, {
5175
- waitForReady: false,
5176
- });
5254
+ const schema = await schemaForValidation(entityInput.entityData.schemaName);
5177
5255
  const schemaSnapshot = schema.getService().getSnapshot();
5178
5256
  const schemaStatus = schemaSnapshot.value;
5179
5257
  logger$t(`[validateEntity] Schema status: ${schemaStatus}`);
@@ -5205,7 +5283,7 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
5205
5283
  }
5206
5284
  else if (entityInput.entityType === 'modelProperty') {
5207
5285
  // Use existing ModelProperty validation
5208
- const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-CWEnZmOH.js'); });
5286
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-BSU9knjf.js'); });
5209
5287
  const { SchemaValidationService } = validationServiceMod;
5210
5288
  const validationService = new SchemaValidationService();
5211
5289
  // Validate property structure
@@ -5220,11 +5298,7 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
5220
5298
  // If schema name and model name provided, validate against schema
5221
5299
  if (entityInput.entityData._schemaName && entityInput.entityData.modelName) {
5222
5300
  try {
5223
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); });
5224
- const { Schema } = schemaMod;
5225
- const schema = Schema.create(entityInput.entityData._schemaName, {
5226
- waitForReady: false,
5227
- });
5301
+ const schema = await schemaForValidation(entityInput.entityData._schemaName);
5228
5302
  const schemaSnapshot = schema.getService().getSnapshot();
5229
5303
  const schemaStatus = schemaSnapshot.value;
5230
5304
  if (schemaStatus === 'idle') {
@@ -5249,7 +5323,7 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
5249
5323
  }
5250
5324
  else if (entityInput.entityType === 'schema') {
5251
5325
  // Schema validation - use existing validation
5252
- const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-CWEnZmOH.js'); });
5326
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-BSU9knjf.js'); });
5253
5327
  const { SchemaValidationService } = validationServiceMod;
5254
5328
  const validationService = new SchemaValidationService();
5255
5329
  const schemaResult = validationService.validateSchema(entityInput.entityData);
@@ -5338,7 +5412,7 @@ const writeToDatabase = xstate.fromCallback(({ sendBack, input }) => {
5338
5412
  // initial write completes is not overwritten by the stale requestWrite payload.
5339
5413
  let dataToWrite = input.entityData;
5340
5414
  try {
5341
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BEsIHAjk.js'); });
5415
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-Dv7AQfmQ.js'); });
5342
5416
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
5343
5417
  if (ModelProperty && typeof ModelProperty.getById === 'function') {
5344
5418
  const instance = ModelProperty.getById(input.entityId);
@@ -5721,16 +5795,23 @@ const modelMachine = xstate.setup({
5721
5795
  ({ context, event, self }) => {
5722
5796
  if (event._liveQueryPropertyIds !== undefined) {
5723
5797
  const newPropertyIds = event._liveQueryPropertyIds;
5798
+ // The model can be evicted with its schema (Schema.destroy, test cleanup) before the
5799
+ // timer and import below run: then create nothing, and drop lookups an eviction overtakes.
5800
+ const evictionEpoch = currentEvictionEpoch();
5724
5801
  // Use setTimeout to check after assign has been applied
5725
5802
  setTimeout(() => {
5726
- self.getSnapshot();
5803
+ const snapshot = self.getSnapshot();
5804
+ if (snapshot.status === 'stopped')
5805
+ return;
5727
5806
  // Create ModelProperty instances for any new property IDs
5728
5807
  if (Array.isArray(newPropertyIds) && newPropertyIds.length > 0) {
5729
5808
  // Import and create instances asynchronously (fire-and-forget)
5730
- Promise.resolve().then(function () { return require('./ModelProperty-BEsIHAjk.js'); }).then(({ ModelProperty }) => {
5809
+ Promise.resolve().then(function () { return require('./ModelProperty-Dv7AQfmQ.js'); }).then(({ ModelProperty }) => {
5810
+ if (self.getSnapshot().status === 'stopped')
5811
+ return;
5731
5812
  const createPromises = newPropertyIds.map(async (propertyFileId) => {
5732
5813
  try {
5733
- const property = await ModelProperty.createById(propertyFileId);
5814
+ const property = await ModelProperty.createById(propertyFileId, { evictionEpoch });
5734
5815
  if (property) {
5735
5816
  logger$q(`[modelMachine] Created/cached ModelProperty instance for propertyFileId "${propertyFileId}" after _liveQueryPropertyIds update`);
5736
5817
  }
@@ -6455,7 +6536,7 @@ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid, m
6455
6536
  const schemaNameToTry = schemaName ?? model$1?.schemaName;
6456
6537
  if (schemaNameToTry) {
6457
6538
  try {
6458
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); });
6539
+ const { Schema } = await Promise.resolve().then(function () { return require('./Schema-BHVp1g-M.js'); });
6459
6540
  const schemaInstance = Schema.create(schemaNameToTry, { waitForReady: false });
6460
6541
  const schemaContext = schemaInstance.getService().getSnapshot().context;
6461
6542
  if (schemaContext.models?.[modelName]?.properties) {
@@ -6508,7 +6589,7 @@ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid, m
6508
6589
  }
6509
6590
  }
6510
6591
  if (Object.keys(propertySchemas).length === 0) {
6511
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
6592
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
6512
6593
  const { ModelPropertyDataTypes } = schemaMod;
6513
6594
  const KNOWN_MODEL_FALLBACKS = {
6514
6595
  Post: {
@@ -6525,7 +6606,7 @@ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid, m
6525
6606
  }
6526
6607
  }
6527
6608
  // Fallbacks above may return schema-file shape ({ type, model, items }); normalize to dataType/ref/refValueType.
6528
- const { normalizePropertyRecordSchema } = await Promise.resolve().then(function () { return require('./property-BVJIP7SX.js'); });
6609
+ const { normalizePropertyRecordSchema } = await Promise.resolve().then(function () { return require('./property-DbEPQ1m9.js'); });
6529
6610
  propertySchemas = Object.fromEntries(Object.entries(propertySchemas).map(([name, def]) => [name, normalizePropertyRecordSchema(def)]));
6530
6611
  // Collapse rows that map to the same instance key (e.g. authorIdentityIds + authors -> authors).
6531
6612
  // ItemProperty.create cache does not sync propertyValue on hit; processing order would otherwise
@@ -6558,7 +6639,7 @@ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid, m
6558
6639
  // Infer propertyRecordSchema from metadata when schema is missing (enables persistence)
6559
6640
  let propSchema = propertySchemas[propertyName];
6560
6641
  if (!propSchema && isRefTypeFromMeta) {
6561
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
6642
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
6562
6643
  const { ModelPropertyDataTypes } = schemaMod;
6563
6644
  propSchema = {
6564
6645
  dataType: refSeedType === 'html' ? ModelPropertyDataTypes.Html
@@ -6825,14 +6906,23 @@ const runPublish = xstate.fromCallback(({ sendBack, input: { context } }) => {
6825
6906
  sendBack({ type: 'publishError', error: new Error(`Item not found for seedLocalId: ${seedLocalId}`) });
6826
6907
  return;
6827
6908
  }
6828
- const getPublishUploadsMod = await Promise.resolve().then(function () { return require('./getPublishUploads-B5Lq6q-_.js'); });
6909
+ const getPublishUploadsMod = await Promise.resolve().then(function () { return require('./getPublishUploads-Ctn5k1k6.js'); });
6829
6910
  const { getPublishUploads } = getPublishUploadsMod;
6830
- const getPublishPayloadMod = await Promise.resolve().then(function () { return require('./getPublishPayload-D5-dYtNq.js'); });
6911
+ const getPublishPayloadMod = await Promise.resolve().then(function () { return require('./getPublishPayload-CEP_e-Kv.js'); });
6831
6912
  const { getPublishPayload } = getPublishPayloadMod;
6832
6913
  const uploads = await getPublishUploads(item);
6833
6914
  let uploadedTransactions = [];
6834
6915
  const executor = getUploadExecutor();
6835
- if (executor && uploads.length > 0) ;
6916
+ if (executor && uploads.length > 0) {
6917
+ for (const upload of uploads) {
6918
+ const { txId } = await executor(upload);
6919
+ uploadedTransactions.push({
6920
+ txId,
6921
+ seedLocalId: upload.seedLocalId,
6922
+ versionLocalId: upload.versionLocalId,
6923
+ });
6924
+ }
6925
+ }
6836
6926
  await getPublishPayload(item, uploadedTransactions);
6837
6927
  logger$o('runPublish: payload prepared (upload/EAS submit stubbed)');
6838
6928
  sendBack({ type: 'publishSuccess' });
@@ -7770,7 +7860,7 @@ const resolveRelatedValue = xstate.fromCallback(({ sendBack, input: { context }
7770
7860
  const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, populatedFromDb, schemaUid, } = context;
7771
7861
  const _resolveRelatedValue = async () => {
7772
7862
  // Use dynamic import to break circular dependency
7773
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
7863
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
7774
7864
  const { ModelPropertyDataTypes } = schemaMod;
7775
7865
  if (!propertyValue || !isRelation || populatedFromDb) {
7776
7866
  return;
@@ -8264,7 +8354,7 @@ const hydrateFromDb = xstate.fromCallback(({ sendBack, input: { context } }) =>
8264
8354
  // to use dynamically imported ModelPropertyDataTypes
8265
8355
  const _hydrateFromDb = async () => {
8266
8356
  // Use dynamic import to break circular dependency
8267
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
8357
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
8268
8358
  const { ModelPropertyDataTypes } = schemaMod;
8269
8359
  const appDb = BaseDb.getAppDb();
8270
8360
  const whereClauses = [];
@@ -8641,7 +8731,7 @@ const loadOrCreateProperty = xstate.fromCallback(({ sendBack, input: { context }
8641
8731
  };
8642
8732
  // Merge with schema from file/DB to get validation rules (enum, pattern, etc.) - properties table doesn't store these
8643
8733
  try {
8644
- const { getPropertySchema } = await Promise.resolve().then(function () { return require('./property-BVJIP7SX.js'); });
8734
+ const { getPropertySchema } = await Promise.resolve().then(function () { return require('./property-DbEPQ1m9.js'); });
8645
8735
  let schemaFromFile = await getPropertySchema(normalizedModelName, propertyName, {
8646
8736
  modelFileId: modelRecord?.schemaFileId ?? modelFileId,
8647
8737
  });
@@ -9062,9 +9152,9 @@ const analyzeInput = xstate.fromCallback(({ sendBack, input: { context, event }
9062
9152
  }
9063
9153
  const _analyzeInput = async () => {
9064
9154
  // Use dynamic import to break circular dependency
9065
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
9155
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
9066
9156
  const { ModelPropertyDataTypes } = schemaMod;
9067
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CWEnZmOH.js'); });
9157
+ const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-BSU9knjf.js'); });
9068
9158
  let propertyName = propertyNameRaw;
9069
9159
  if (!propertyName) {
9070
9160
  throw new Error('propertyName is required');
@@ -9554,7 +9644,7 @@ const createMetadata = async (metadataValues, propertyRecordSchema, options) =>
9554
9644
  propertyRecordSchema?.validation &&
9555
9645
  metadataValues.propertyValue != null &&
9556
9646
  metadataValues.propertyValue !== '') {
9557
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CWEnZmOH.js'); });
9647
+ const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-BSU9knjf.js'); });
9558
9648
  const validationService = new SchemaValidationService();
9559
9649
  const validationResult = validationService.validatePropertyValue(metadataValues.propertyValue, normalizeDataType(propertyRecordSchema.dataType), propertyRecordSchema.validation, propertyRecordSchema.refValueType
9560
9650
  ? normalizeDataType(String(propertyRecordSchema.refValueType))
@@ -10136,7 +10226,7 @@ const saveRelation = xstate.fromCallback(({ sendBack, input: { context, event }
10136
10226
  }
10137
10227
  const _saveRelation = async () => {
10138
10228
  // Use dynamic import to break circular dependency
10139
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
10229
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
10140
10230
  const { ModelPropertyDataTypes } = schemaMod;
10141
10231
  if (!propertyNameRaw) {
10142
10232
  throw new Error('propertyName is required');
@@ -11102,7 +11192,7 @@ class ItemProperty {
11102
11192
  return;
11103
11193
  }
11104
11194
  // Use dynamic import to break circular dependency
11105
- const schemaMod = await Promise.resolve().then(function () { return require('./index-B3UDbm1C.js'); });
11195
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-DfGhF1dc.js'); });
11106
11196
  const { ModelPropertyDataTypes } = schemaMod;
11107
11197
  const { context } = snapshot;
11108
11198
  const { propertyRecordSchema } = context;
@@ -11763,6 +11853,29 @@ class ItemProperty {
11763
11853
  return result;
11764
11854
  return waitForEntityIdle(result, { timeout: readyTimeout }).then(() => result);
11765
11855
  }
11856
+ /**
11857
+ * The cached ItemProperty when it can be read right now (idle, not saving), the state
11858
+ * `ItemProperty.find()` waits for. Otherwise undefined. Unlike `find`, it takes no cache hold, so
11859
+ * React hooks can call it during render.
11860
+ */
11861
+ static peekReady({ propertyName, seedLocalId, seedUid, }) {
11862
+ if (!propertyName)
11863
+ return undefined;
11864
+ // Same key order as find(), then the other id: instances are cached under both when both are known.
11865
+ const keys = [seedUid, seedLocalId]
11866
+ .filter((id) => typeof id === 'string' && id.length > 0)
11867
+ .map((id) => this.cacheKey(id, propertyName));
11868
+ for (const key of keys) {
11869
+ const instance = this.instanceCache.get(key)?.instance;
11870
+ if (!instance)
11871
+ continue;
11872
+ const snap = instance.getService().getSnapshot();
11873
+ if (snap.status !== 'active' || snap.value !== 'idle' || snap.context?.isSaving)
11874
+ return undefined;
11875
+ return instance;
11876
+ }
11877
+ return undefined;
11878
+ }
11766
11879
  static async find({ propertyName, seedLocalId, seedUid, modelName: modelNameOption, waitForReady = true, readyTimeout = 5000, }) {
11767
11880
  if ((!seedLocalId && !seedUid) || !propertyName) {
11768
11881
  return undefined;
@@ -12478,7 +12591,7 @@ class Item {
12478
12591
  const revokedAt = Math.floor(Date.now() / 1000);
12479
12592
  // The executor stamps the revoked version rows; the latest version is now the newest one left
12480
12593
  // (a local draft) or none, never a revoked one.
12481
- const { getLatestVersionRow } = await Promise.resolve().then(function () { return require('./getLatestVersionRow-DVizNNoI.js'); });
12594
+ const { getLatestVersionRow } = await Promise.resolve().then(function () { return require('./getLatestVersionRow-CcaabxIW.js'); });
12482
12595
  const head = await getLatestVersionRow(this.seedLocalId);
12483
12596
  this._service.send({
12484
12597
  type: 'updateContext',
@@ -12524,12 +12637,12 @@ class Item {
12524
12637
  };
12525
12638
  this.getPublishUploads = async (options) => {
12526
12639
  // Use dynamic import to break circular dependency
12527
- const getPublishUploadsMod = await Promise.resolve().then(function () { return require('./getPublishUploads-B5Lq6q-_.js'); });
12640
+ const getPublishUploadsMod = await Promise.resolve().then(function () { return require('./getPublishUploads-Ctn5k1k6.js'); });
12528
12641
  const { getPublishUploads } = getPublishUploadsMod;
12529
12642
  return await getPublishUploads(this, [], undefined, options);
12530
12643
  };
12531
12644
  this.getPublishPayload = async (uploadedTransactions, options) => {
12532
- const getPublishPayloadMod = await Promise.resolve().then(function () { return require('./getPublishPayload-D5-dYtNq.js'); });
12645
+ const getPublishPayloadMod = await Promise.resolve().then(function () { return require('./getPublishPayload-CEP_e-Kv.js'); });
12533
12646
  const { getPublishPayload } = getPublishPayloadMod;
12534
12647
  return await getPublishPayload(this, uploadedTransactions, options);
12535
12648
  };
@@ -12546,7 +12659,7 @@ class Item {
12546
12659
  });
12547
12660
  // Publish has recorded the version it attested (updateVersionUid): reflect it here too, as
12548
12661
  // the versions liveQuery does in the browser. After a republish this is the new version.
12549
- const { getLatestVersionRow } = await Promise.resolve().then(function () { return require('./getLatestVersionRow-DVizNNoI.js'); });
12662
+ const { getLatestVersionRow } = await Promise.resolve().then(function () { return require('./getLatestVersionRow-CcaabxIW.js'); });
12550
12663
  const head = await getLatestVersionRow(seedLocalId);
12551
12664
  if (head?.localId) {
12552
12665
  this._service.send({
@@ -12802,6 +12915,38 @@ class Item {
12802
12915
  }
12803
12916
  }
12804
12917
  }
12918
+ /**
12919
+ * Idle, and not the shell the item machine can be in when it reaches `idle` before
12920
+ * `propertyInstances` is merged (an item with a version but no property instances yet).
12921
+ */
12922
+ static isItemSnapshotReadyForRead(snap) {
12923
+ if (!snap || !('value' in snap) || snap.value !== 'idle') {
12924
+ return false;
12925
+ }
12926
+ const ctx = snap.context || {};
12927
+ const versionsCount = ctx.versionsCount ?? 0;
12928
+ const hasHeadVersion = !!ctx.latestVersionLocalId;
12929
+ if (versionsCount === 0 && !hasHeadVersion) {
12930
+ return true;
12931
+ }
12932
+ return (ctx.propertyInstances?.size ?? 0) > 0;
12933
+ }
12934
+ /**
12935
+ * The cached Item for a seedLocalId or seedUid when it can be read right now: idle and hydrated,
12936
+ * so at least what `Item.find()` would wait for. Otherwise undefined. Unlike `getById`, it takes
12937
+ * no cache hold, so React hooks can call it during render.
12938
+ */
12939
+ static peekReady(id) {
12940
+ if (!id)
12941
+ return undefined;
12942
+ const instance = this.findItemInstanceCacheEntryById(id)?.instance;
12943
+ if (!instance)
12944
+ return undefined;
12945
+ const snap = instance.getService().getSnapshot();
12946
+ if (snap.status !== 'active')
12947
+ return undefined;
12948
+ return this.isItemSnapshotReadyForRead(snap) ? instance : undefined;
12949
+ }
12805
12950
  /**
12806
12951
  * Item machine can reach `idle` before `propertyInstances` is merged (race) or while
12807
12952
  * child ItemProperty actors are still hydrating. useItems / Item.all must not return that shell.
@@ -12814,16 +12959,7 @@ class Item {
12814
12959
  if ('value' in snap && snap.value === 'error') {
12815
12960
  throw new Error('Entity failed to load');
12816
12961
  }
12817
- if (!('value' in snap) || snap.value !== 'idle') {
12818
- return false;
12819
- }
12820
- const ctx = snap.context || {};
12821
- const versionsCount = ctx.versionsCount ?? 0;
12822
- const hasHeadVersion = !!ctx.latestVersionLocalId;
12823
- if (versionsCount === 0 && !hasHeadVersion) {
12824
- return true;
12825
- }
12826
- return (ctx.propertyInstances?.size ?? 0) > 0;
12962
+ return Item.isItemSnapshotReadyForRead(snap);
12827
12963
  }, { timeout: readyTimeout });
12828
12964
  }
12829
12965
  catch (e) {
@@ -14313,7 +14449,7 @@ const runEasSync = xstate.fromPromise(async ({ input, }) => {
14313
14449
  requestPayload: input.requestPayload,
14314
14450
  persistedSnapshot: input.runningSnapshot,
14315
14451
  });
14316
- const { runSyncFromEas } = await Promise.resolve().then(function () { return require('./syncDbWithEas-Dk96sAG-.js'); });
14452
+ const { runSyncFromEas } = await Promise.resolve().then(function () { return require('./syncDbWithEas-d1iOdTTI.js'); });
14317
14453
  try {
14318
14454
  // Sync checks for rows and then inserts the rest (no unique index on uids), so syncs in
14319
14455
  // different tabs take turns. A sync can run for minutes, so wait without a timeout.
@@ -18976,22 +19112,6 @@ var ClientManager$1 = /*#__PURE__*/Object.freeze({
18976
19112
  getClient: getClient
18977
19113
  });
18978
19114
 
18979
- /**
18980
- * Common getters and utilities for entity classes
18981
- * These work with any entity that has a getService() method returning an XState actor
18982
- */
18983
- /**
18984
- * Get the current state value from an entity's service
18985
- */
18986
- /**
18987
- * Whether an actor has been stopped (unload, destroy, or Schema eviction). Async work started by an
18988
- * entity (DB lookups, retry timers) must check this before sending, since a stopped actor ignores
18989
- * events and XState warns about every one of them.
18990
- */
18991
- function isActorStopped(actor) {
18992
- return actor.getSnapshot().status === 'stopped';
18993
- }
18994
-
18995
19115
  /**
18996
19116
  * Set up liveQuery subscription for an entity
18997
19117
  * This enables cross-instance synchronization (e.g., changes in other tabs/windows)
@@ -19017,7 +19137,10 @@ function setupEntityLiveQuery(instance, config) {
19017
19137
  const initialIds = config.extractEntityIds(initialRows);
19018
19138
  if (initialIds.length > 0) {
19019
19139
  logger(`Initial query returned ${initialIds.length} entities`);
19020
- // Create child instances if provided
19140
+ // Create child instances if provided (not for a stopped entity: an unloaded or evicted
19141
+ // parent must not re-cache its children)
19142
+ if (isActorStopped(instance.getService()))
19143
+ return;
19021
19144
  if (config.createChildInstances) {
19022
19145
  await config.createChildInstances(initialIds);
19023
19146
  }
@@ -19048,7 +19171,9 @@ function setupEntityLiveQuery(instance, config) {
19048
19171
  }
19049
19172
  logger(`Query returned ${rows.length} rows`);
19050
19173
  const ids = config.extractEntityIds(rows);
19051
- // Create child instances if provided (before updating context)
19174
+ // Create child instances if provided (before updating context; not for a stopped entity)
19175
+ if (isActorStopped(instance.getService()))
19176
+ return;
19052
19177
  if (config.createChildInstances && ids.length > 0) {
19053
19178
  await config.createChildInstances(ids);
19054
19179
  }
@@ -19189,7 +19314,7 @@ const saveDraftLogger = debug('seedSdk:model:saveDraftToDb');
19189
19314
  // Lazy import cache for ModelProperty to avoid circular dependency
19190
19315
  // Eagerly start loading to minimize delay on first access
19191
19316
  let ModelPropertyClass = null;
19192
- const modelPropertyImportPromise = Promise.resolve().then(function () { return require('./ModelProperty-BEsIHAjk.js'); })
19317
+ const modelPropertyImportPromise = Promise.resolve().then(function () { return require('./ModelProperty-Dv7AQfmQ.js'); })
19193
19318
  .then(module => {
19194
19319
  ModelPropertyClass = module.ModelProperty;
19195
19320
  return ModelPropertyClass;
@@ -19205,7 +19330,7 @@ function getModelProperty() {
19205
19330
  return ModelPropertyClass;
19206
19331
  }
19207
19332
  // Lazy import for Schema to avoid circular dependency
19208
- const schemaImportPromise = Promise.resolve().then(function () { return require('./Schema-qEp5mH1N.js'); })
19333
+ const schemaImportPromise = Promise.resolve().then(function () { return require('./Schema-BHVp1g-M.js'); })
19209
19334
  .then(module => module.Schema)
19210
19335
  .catch(() => null);
19211
19336
  // WeakMap to store mutable state per Model instance
@@ -19703,6 +19828,9 @@ class Model {
19703
19828
  resolve();
19704
19829
  }, 10000);
19705
19830
  });
19831
+ // Unloaded or evicted (e.g. Schema.destroy) while it loaded: a stopped model never writes
19832
+ if (isActorStopped(proxiedInstance._service))
19833
+ return;
19706
19834
  // Only write if validation passed (model is in idle state, not error)
19707
19835
  const finalSnapshot = proxiedInstance._service.getSnapshot();
19708
19836
  if (finalSnapshot.value === 'idle' && (!finalSnapshot.context._validationErrors || finalSnapshot.context._validationErrors.length === 0)) {
@@ -19826,8 +19954,8 @@ class Model {
19826
19954
  }
19827
19955
  logger$2(`WARNING: Could not verify schema exists in database: ${error}. Proceeding anyway.`);
19828
19956
  }
19829
- // Track pending write
19830
- Model.trackPendingWrite(finalSnapshot.context.id, schemaId); // id is now the schemaFileId (string)
19957
+ const pendingModelFileId = finalSnapshot.context.id;
19958
+ const pendingSchemaId = schemaId;
19831
19959
  // Wait for writeProcess to be spawned (it's spawned in idle state entry action)
19832
19960
  // Retry a few times if writeProcess isn't available yet
19833
19961
  let retries = 0;
@@ -19838,6 +19966,8 @@ class Model {
19838
19966
  return;
19839
19967
  const currentSnapshot = proxiedInstance._service.getSnapshot();
19840
19968
  if (currentSnapshot.context.writeProcess) {
19969
+ // Track pending write (only once it really starts: a stopped model leaves none behind)
19970
+ Model.trackPendingWrite(pendingModelFileId, pendingSchemaId); // id is now the schemaFileId (string)
19841
19971
  logger$2(`Triggering write process for model "${finalSnapshot.context.modelName}" (schemaId: ${schemaId})`);
19842
19972
  // Use pending property definitions if available, otherwise convert from ModelProperty instances
19843
19973
  let propertiesObject = {};
@@ -20058,6 +20188,7 @@ class Model {
20058
20188
  if (scope.modelFileId || scope.schemaName) {
20059
20189
  const db = BaseDb.getAppDb();
20060
20190
  if (db) {
20191
+ const evictionEpoch = currentEvictionEpoch();
20061
20192
  try {
20062
20193
  const rows = await db
20063
20194
  .select({
@@ -20074,6 +20205,9 @@ class Model {
20074
20205
  .limit(1);
20075
20206
  const record = rows[0];
20076
20207
  if (record?.modelName && record.schemaName && record.modelFileId) {
20208
+ // Its schema was evicted while we read the row: don't bring the model back.
20209
+ if (schemaEvictedSince(record.schemaName, evictionEpoch))
20210
+ return undefined;
20077
20211
  return this.create(record.modelName, record.schemaName, { id: record.modelFileId });
20078
20212
  }
20079
20213
  }
@@ -20092,7 +20226,7 @@ class Model {
20092
20226
  * @param schemaName - Optional schema name (will query DB if not provided)
20093
20227
  * @returns The Model instance if found, undefined otherwise
20094
20228
  */
20095
- static async getByNameAsync(modelName, schemaName) {
20229
+ static async getByNameAsync(modelName, schemaName, options) {
20096
20230
  // First try cache
20097
20231
  const cached = this.getByName(modelName, schemaName);
20098
20232
  if (cached) {
@@ -20104,6 +20238,7 @@ class Model {
20104
20238
  if (!db) {
20105
20239
  return undefined;
20106
20240
  }
20241
+ const evictionEpoch = options?.evictionEpoch ?? currentEvictionEpoch();
20107
20242
  try {
20108
20243
  // Query model by name (throws AmbiguousModelError when several schemas define it)
20109
20244
  const { resolveModelRecord } = await Promise.resolve().then(function () { return resolveModelRecord$1; });
@@ -20129,6 +20264,10 @@ class Model {
20129
20264
  if (!record.modelName || !record.schemaName || !record.modelFileId) {
20130
20265
  return undefined;
20131
20266
  }
20267
+ // Its schema was evicted while we read the row: don't bring the model back.
20268
+ if (schemaEvictedSince(record.schemaName, evictionEpoch)) {
20269
+ return undefined;
20270
+ }
20132
20271
  // Create model instance (will be cached)
20133
20272
  return this.create(record.modelName, record.schemaName, {
20134
20273
  id: record.modelFileId, // id is now the schemaFileId (string)
@@ -20150,7 +20289,7 @@ class Model {
20150
20289
  * @param modelFileId - The model file ID to look up
20151
20290
  * @returns The Model instance if found, undefined otherwise
20152
20291
  */
20153
- static async createById(modelFileId) {
20292
+ static async createById(modelFileId, options) {
20154
20293
  if (!modelFileId) {
20155
20294
  return undefined;
20156
20295
  }
@@ -20166,6 +20305,7 @@ class Model {
20166
20305
  logger$2(`Model.createById: Database not available for ID "${modelFileId}"`);
20167
20306
  return undefined;
20168
20307
  }
20308
+ const evictionEpoch = options?.evictionEpoch ?? currentEvictionEpoch();
20169
20309
  try {
20170
20310
  // Query model by schemaFileId and join to get schema name
20171
20311
  const modelRecords = await db
@@ -20188,6 +20328,12 @@ class Model {
20188
20328
  logger$2(`Model.createById: Missing modelName or schemaName for ID "${modelFileId}"`);
20189
20329
  return undefined;
20190
20330
  }
20331
+ // Its schema was evicted while we read the row (e.g. a Schema live query in flight during
20332
+ // Schema.destroy or test cleanup): don't bring the model back.
20333
+ if (schemaEvictedSince(schemaName, evictionEpoch)) {
20334
+ logger$2(`Model.createById: schema "${schemaName}" was evicted during the lookup of "${modelFileId}"`);
20335
+ return undefined;
20336
+ }
20191
20337
  // Step 3: Create model using existing create method (which will handle caching)
20192
20338
  logger$2(`Model.createById: Creating model "${modelName}" in schema "${schemaName}" from ID "${modelFileId}"`);
20193
20339
  return this.create(modelName, schemaName, {
@@ -20242,6 +20388,7 @@ class Model {
20242
20388
  logger$2(`Model.createBySchemaId: Database not available for schema "${schemaIdentifier}"`);
20243
20389
  return [];
20244
20390
  }
20391
+ const evictionEpoch = currentEvictionEpoch();
20245
20392
  try {
20246
20393
  // Query all models for this schema - support both schemaFileId and schema name
20247
20394
  const modelRecords = await db
@@ -20264,6 +20411,10 @@ class Model {
20264
20411
  if (!record.modelName || !record.schemaName || !record.modelFileId) {
20265
20412
  continue;
20266
20413
  }
20414
+ // Its schema was evicted while we read the rows: don't bring its models back.
20415
+ if (schemaEvictedSince(record.schemaName, evictionEpoch)) {
20416
+ continue;
20417
+ }
20267
20418
  // Check cache first
20268
20419
  const cached = this.getById(record.modelFileId);
20269
20420
  if (cached) {
@@ -20710,6 +20861,8 @@ class Model {
20710
20861
  * @returns names of the evicted models (so callers can evict their ModelProperty instances)
20711
20862
  */
20712
20863
  static evictForSchema(schemaName) {
20864
+ // Work already running for this schema's models must not re-cache them when it finishes.
20865
+ recordSchemaEviction(schemaName);
20713
20866
  const instances = new Set();
20714
20867
  for (const { instance } of this.instanceCacheById.values())
20715
20868
  instances.add(instance);
@@ -21242,7 +21395,7 @@ function resolveSdkDrizzleMigrationsDir(sdkRootDir) {
21242
21395
  })();
21243
21396
  // Also resolve relative to this module so temp-cwd tests / odd roots still find
21244
21397
  // packages/sdk/src/db/drizzle (or dist/db/drizzle after publish).
21245
- const moduleDir = path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cjs/index-C66AfYDG.js', document.baseURI).href))));
21398
+ const moduleDir = path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cjs/index-Cvvt0-5B.js', document.baseURI).href))));
21246
21399
  const candidates = [
21247
21400
  path.join(root, 'db', 'drizzle'), // production: sdkRoot is dist/
21248
21401
  path.join(root, 'dist', 'db', 'drizzle'), // sdk package root with built dist
@@ -21312,10 +21465,10 @@ class NodeDb {
21312
21465
  logger$1('[Db.prepareDb] running migrations from %s', outDir);
21313
21466
  await migrator.migrate(db, { migrationsFolder: outDir });
21314
21467
  this.db = db;
21315
- const { backfillMetadataPropertyIds } = await Promise.resolve().then(function () { return require('./backfillMetadataPropertyIds-tw8JGMT0.js'); });
21468
+ const { backfillMetadataPropertyIds } = await Promise.resolve().then(function () { return require('./backfillMetadataPropertyIds-WIovQ_d8.js'); });
21316
21469
  await backfillMetadataPropertyIds();
21317
21470
  // One-time: clear item data whose model can't be determined (seeds.model_file_id, migration 0015)
21318
- const { resetAmbiguousLegacyItemData } = await Promise.resolve().then(function () { return require('./resetAmbiguousLegacyItemData-BaZqUui9.js'); });
21471
+ const { resetAmbiguousLegacyItemData } = await Promise.resolve().then(function () { return require('./resetAmbiguousLegacyItemData-CfMhRHwK.js'); });
21319
21472
  await resetAmbiguousLegacyItemData();
21320
21473
  return this.db;
21321
21474
  }
@@ -21842,6 +21995,7 @@ exports.VERSION_SCHEMA_UID = VERSION_SCHEMA_UID;
21842
21995
  exports.ZERO_BYTES32 = ZERO_BYTES32;
21843
21996
  exports.addModelsToDb = addModelsToDb$1;
21844
21997
  exports.addSchemaToDb = addSchemaToDb;
21998
+ exports.anyEvictionSince = anyEvictionSince;
21845
21999
  exports.appState = appState;
21846
22000
  exports.arweaveL1FinalizeJobs = arweaveL1FinalizeJobs;
21847
22001
  exports.assertLocalDbChain = assertLocalDbChain;
@@ -21851,6 +22005,7 @@ exports.commandExists = commandExists;
21851
22005
  exports.config = config;
21852
22006
  exports.createModelsFromJson = createModelsFromJson;
21853
22007
  exports.createReactiveProxy = createReactiveProxy;
22008
+ exports.currentEvictionEpoch = currentEvictionEpoch;
21854
22009
  exports.db = db;
21855
22010
  exports.defaultAttestationData = defaultAttestationData;
21856
22011
  exports.easSyncProcesses = easSyncProcesses;
@@ -21866,6 +22021,7 @@ exports.getClient = getClient;
21866
22021
  exports.getContentHash = getContentHash;
21867
22022
  exports.getCorrectId = getCorrectId;
21868
22023
  exports.getEasSchemaUidForModel = getEasSchemaUidForModel;
22024
+ exports.getGetAdditionalSyncAddresses = getGetAdditionalSyncAddresses;
21869
22025
  exports.getItemData = getItemData;
21870
22026
  exports.getItemModelScope = getItemModelScope;
21871
22027
  exports.getItemStoragePropertiesForModel = getItemStoragePropertiesForModel;
@@ -21918,6 +22074,7 @@ exports.saveModelsFromMarkdown = saveModelsFromMarkdown;
21918
22074
  exports.scheduleBulkFilesDownloadFromEasSync = scheduleBulkFilesDownloadFromEasSync;
21919
22075
  exports.schema = schema$1;
21920
22076
  exports.schema$1 = schema;
22077
+ exports.schemaEvictedSince = schemaEvictedSince;
21921
22078
  exports.schemas = schemas;
21922
22079
  exports.seeds = seeds;
21923
22080
  exports.selectInBatches = selectInBatches;
@@ -21935,4 +22092,4 @@ exports.withSeed = withSeed;
21935
22092
  exports.writeInBatches = writeInBatches;
21936
22093
  exports.writeProcessMachine = writeProcessMachine;
21937
22094
  exports.writeToDatabase = writeToDatabase$1;
21938
- //# sourceMappingURL=index-C66AfYDG.js.map
22095
+ //# sourceMappingURL=index-Cvvt0-5B.js.map