@seedprotocol/sdk 0.4.3 → 0.4.5

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 (199) hide show
  1. package/README.md +38 -348
  2. package/dist/{ArweaveClient-CleX_4Gw.js → ArweaveClient-CgWK-JgT.js} +8 -8
  3. package/dist/{ArweaveClient-CleX_4Gw.js.map → ArweaveClient-CgWK-JgT.js.map} +1 -1
  4. package/dist/{ArweaveClient-BvJ1FhQ5.js → ArweaveClient-WcG8CZAE.js} +8 -8
  5. package/dist/{ArweaveClient-BvJ1FhQ5.js.map → ArweaveClient-WcG8CZAE.js.map} +1 -1
  6. package/dist/{Db-DX08SxS9.js → Db-DjFdIdR9.js} +9 -16
  7. package/dist/{Db-DX08SxS9.js.map → Db-DjFdIdR9.js.map} +1 -1
  8. package/dist/{Db-BPnO1-_p.js → Db-DjofXdeU.js} +9 -9
  9. package/dist/{Db-BPnO1-_p.js.map → Db-DjofXdeU.js.map} +1 -1
  10. package/dist/{EasClient-BwhUcPjY.js → EasClient-Aojewp6P.js} +8 -8
  11. package/dist/{EasClient-CJSs38Db.js.map → EasClient-Aojewp6P.js.map} +1 -1
  12. package/dist/{EasClient-CJSs38Db.js → EasClient-BVFXp2O6.js} +8 -8
  13. package/dist/{EasClient-BwhUcPjY.js.map → EasClient-BVFXp2O6.js.map} +1 -1
  14. package/dist/{FileManager-B1tdLMsX.js → FileManager-C9zr4AJe.js} +8 -8
  15. package/dist/{FileManager-B1tdLMsX.js.map → FileManager-C9zr4AJe.js.map} +1 -1
  16. package/dist/{FileManager-Ct91ZhOE.js → FileManager-CxGJLw5C.js} +8 -8
  17. package/dist/{FileManager-Ct91ZhOE.js.map → FileManager-CxGJLw5C.js.map} +1 -1
  18. package/dist/Item/Item.d.ts +28 -7
  19. package/dist/Item/Item.d.ts.map +1 -1
  20. package/dist/Item/service/actors/runPublish.d.ts +5 -0
  21. package/dist/Item/service/actors/runPublish.d.ts.map +1 -0
  22. package/dist/Item/service/itemMachineSingle.d.ts +10 -5
  23. package/dist/Item/service/itemMachineSingle.d.ts.map +1 -1
  24. package/dist/ItemProperty/ItemProperty.d.ts +30 -5
  25. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  26. package/dist/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +1 -1
  27. package/dist/ItemProperty/service/propertyMachine.d.ts +10 -10
  28. package/dist/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  29. package/dist/Model/Model.d.ts +27 -20
  30. package/dist/Model/Model.d.ts.map +1 -1
  31. package/dist/Model/index.d.ts +1 -1
  32. package/dist/Model/service/actors/createModelProperties.d.ts.map +1 -1
  33. package/dist/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  34. package/dist/Model/service/actors/validateModel.d.ts.map +1 -1
  35. package/dist/Model/service/modelMachine.d.ts +18 -3
  36. package/dist/Model/service/modelMachine.d.ts.map +1 -1
  37. package/dist/ModelProperty/ModelProperty.d.ts +25 -2
  38. package/dist/ModelProperty/ModelProperty.d.ts.map +1 -1
  39. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  40. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  41. package/dist/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  42. package/dist/ModelProperty/service/modelPropertyMachine.d.ts +17 -3
  43. package/dist/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  44. package/dist/{ModelProperty-Cr3BmgkC.js → ModelProperty-CGdkocQ8.js} +349 -817
  45. package/dist/ModelProperty-CGdkocQ8.js.map +1 -0
  46. package/dist/{PathResolver-DJdxE_OK.js → PathResolver-CX6GHoTS.js} +8 -8
  47. package/dist/{PathResolver-DJdxE_OK.js.map → PathResolver-CX6GHoTS.js.map} +1 -1
  48. package/dist/{PathResolver-BErmcZqP.js → PathResolver-z_WX47_o.js} +8 -8
  49. package/dist/{PathResolver-BErmcZqP.js.map → PathResolver-z_WX47_o.js.map} +1 -1
  50. package/dist/{QueryClient-DIu9c-w6.js → QueryClient-ByKPdRmE.js} +8 -8
  51. package/dist/{QueryClient-DIu9c-w6.js.map → QueryClient-ByKPdRmE.js.map} +1 -1
  52. package/dist/{QueryClient-D2mv63gP.js → QueryClient-Cb1iJO-x.js} +8 -8
  53. package/dist/{QueryClient-D2mv63gP.js.map → QueryClient-Cb1iJO-x.js.map} +1 -1
  54. package/dist/Schema/Schema.d.ts +24 -3
  55. package/dist/Schema/Schema.d.ts.map +1 -1
  56. package/dist/Schema/service/actors/checkExistingSchema.d.ts.map +1 -1
  57. package/dist/Schema/service/actors/createPropertyInstances.d.ts.map +1 -1
  58. package/dist/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  59. package/dist/Schema/service/actors/verifyPropertyInstancesInCache.d.ts.map +1 -1
  60. package/dist/Schema/service/actors/writeModelsToDb.d.ts.map +1 -1
  61. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  62. package/dist/Schema/service/actors/writeSchemaToDb.d.ts.map +1 -1
  63. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  64. package/dist/Schema/service/schemaMachine.d.ts +17 -3
  65. package/dist/Schema/service/schemaMachine.d.ts.map +1 -1
  66. package/dist/{Schema-DeKabJ0T.js → Schema-D1eqDHyt.js} +995 -186
  67. package/dist/Schema-D1eqDHyt.js.map +1 -0
  68. package/dist/{SchemaValidationService-cTlURuDt.js → SchemaValidationService-DyttFaV_.js} +7 -7
  69. package/dist/{SchemaValidationService-cTlURuDt.js.map → SchemaValidationService-DyttFaV_.js.map} +1 -1
  70. package/dist/browser/db/Db.d.ts.map +1 -1
  71. package/dist/browser/react/SeedProvider.d.ts +30 -0
  72. package/dist/browser/react/SeedProvider.d.ts.map +1 -0
  73. package/dist/browser/react/index.d.ts +4 -1
  74. package/dist/browser/react/index.d.ts.map +1 -1
  75. package/dist/browser/react/item.d.ts +10 -6
  76. package/dist/browser/react/item.d.ts.map +1 -1
  77. package/dist/browser/react/itemProperty.d.ts +37 -1
  78. package/dist/browser/react/itemProperty.d.ts.map +1 -1
  79. package/dist/browser/react/liveQuery.d.ts.map +1 -1
  80. package/dist/browser/react/model.d.ts +21 -7
  81. package/dist/browser/react/model.d.ts.map +1 -1
  82. package/dist/browser/react/modelProperty.d.ts +23 -0
  83. package/dist/browser/react/modelProperty.d.ts.map +1 -1
  84. package/dist/browser/react/queryClient.d.ts +28 -0
  85. package/dist/browser/react/queryClient.d.ts.map +1 -0
  86. package/dist/browser/react/schema.d.ts +8 -0
  87. package/dist/browser/react/schema.d.ts.map +1 -1
  88. package/dist/browser/react/trash.d.ts +5 -2
  89. package/dist/browser/react/trash.d.ts.map +1 -1
  90. package/dist/cjs/{ModelProperty-MkN5Rmx7.js → ModelProperty-BeJvgKMw.js} +377 -477
  91. package/dist/cjs/ModelProperty-BeJvgKMw.js.map +1 -0
  92. package/dist/cjs/{Schema-B5cr_JVK.js → Schema-CVs9J6eP.js} +709 -263
  93. package/dist/cjs/Schema-CVs9J6eP.js.map +1 -0
  94. package/dist/cjs/{SchemaValidationService-BgIzc3-r.js → SchemaValidationService-CDKcVRFQ.js} +4 -4
  95. package/dist/cjs/{SchemaValidationService-BgIzc3-r.js.map → SchemaValidationService-CDKcVRFQ.js.map} +1 -1
  96. package/dist/cjs/{getItem-CVJJPky2.js → getItem-B5RYPvrG.js} +4 -4
  97. package/dist/cjs/{getItem-CVJJPky2.js.map → getItem-B5RYPvrG.js.map} +1 -1
  98. package/dist/cjs/{getPublishPayload-DbOc3WA-.js → getPublishPayload-BD1qRob1.js} +26 -11
  99. package/dist/cjs/getPublishPayload-BD1qRob1.js.map +1 -0
  100. package/dist/cjs/{getPublishUploads-NzioLz-3.js → getPublishUploads-CnC9aYxs.js} +5 -5
  101. package/dist/cjs/getPublishUploads-CnC9aYxs.js.map +1 -0
  102. package/dist/cjs/{getSegmentedItemProperties-BsaklLwI.js → getSegmentedItemProperties-B_njnntx.js} +2 -2
  103. package/dist/cjs/{getSegmentedItemProperties-BsaklLwI.js.map → getSegmentedItemProperties-B_njnntx.js.map} +1 -1
  104. package/dist/cjs/{index-BmIVfqGN.js → index-BeKPbbk0.js} +12715 -12384
  105. package/dist/cjs/index-BeKPbbk0.js.map +1 -0
  106. package/dist/cjs/{index-C_0angRB.js → index-Dnywap_P.js} +4 -4
  107. package/dist/cjs/index-Dnywap_P.js.map +1 -0
  108. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  109. package/dist/client/actors/processSchemaFiles.d.ts.map +1 -1
  110. package/dist/client/actors/saveAppState.d.ts.map +1 -1
  111. package/dist/db/read/getItemData.d.ts.map +1 -1
  112. package/dist/db/read/getItems.d.ts.map +1 -1
  113. package/dist/db/read/getModelPropertiesData.d.ts +19 -0
  114. package/dist/db/read/getModelPropertiesData.d.ts.map +1 -0
  115. package/dist/db/read/getModelsData.d.ts +15 -0
  116. package/dist/db/read/getModelsData.d.ts.map +1 -0
  117. package/dist/db/read/getPublishPayload.d.ts.map +1 -1
  118. package/dist/db/read/getPublishUploads.d.ts +1 -7
  119. package/dist/db/read/getPublishUploads.d.ts.map +1 -1
  120. package/dist/db/read/getSchemaUidForModel.d.ts.map +1 -1
  121. package/dist/db/write/updateSeedUid.d.ts +7 -0
  122. package/dist/db/write/updateSeedUid.d.ts.map +1 -0
  123. package/dist/eas.d.ts.map +1 -1
  124. package/dist/events/item/index.d.ts.map +1 -1
  125. package/dist/events/item/syncDbWithEas.d.ts.map +1 -1
  126. package/dist/{getItem-CcttmUY_.js → getItem-BB5HBCbK.js} +8 -8
  127. package/dist/{getItem-CcttmUY_.js.map → getItem-BB5HBCbK.js.map} +1 -1
  128. package/dist/{getPublishPayload-NFpqbd_H.js → getPublishPayload-uLm0AqN_.js} +29 -14
  129. package/dist/getPublishPayload-uLm0AqN_.js.map +1 -0
  130. package/dist/{getPublishUploads-Cpb9vgwE.js → getPublishUploads-Dc-HqhO8.js} +9 -9
  131. package/dist/getPublishUploads-Dc-HqhO8.js.map +1 -0
  132. package/dist/{getSegmentedItemProperties-DiyQPMgI.js → getSegmentedItemProperties-BrIqFNfD.js} +2 -2
  133. package/dist/{getSegmentedItemProperties-DiyQPMgI.js.map → getSegmentedItemProperties-BrIqFNfD.js.map} +1 -1
  134. package/dist/helpers/db.d.ts +12 -0
  135. package/dist/helpers/db.d.ts.map +1 -1
  136. package/dist/helpers/entity/entityDestroy.d.ts +41 -0
  137. package/dist/helpers/entity/entityDestroy.d.ts.map +1 -0
  138. package/dist/helpers/entity/index.d.ts +1 -0
  139. package/dist/helpers/entity/index.d.ts.map +1 -1
  140. package/dist/helpers/index.d.ts +1 -0
  141. package/dist/helpers/index.d.ts.map +1 -1
  142. package/dist/helpers/property/index.d.ts +12 -12
  143. package/dist/helpers/property/index.d.ts.map +1 -1
  144. package/dist/helpers/reactiveProxy.d.ts.map +1 -1
  145. package/dist/helpers/schema.d.ts.map +1 -1
  146. package/dist/helpers/updateSchema.d.ts +9 -0
  147. package/dist/helpers/updateSchema.d.ts.map +1 -1
  148. package/dist/helpers/waitForEntityIdle.d.ts +2 -2
  149. package/dist/helpers/waitForEntityIdle.d.ts.map +1 -1
  150. package/dist/imports/json.d.ts.map +1 -1
  151. package/dist/{index-r45w9hEq.js → index-2FcQHgKp.js} +2 -2
  152. package/dist/index-2FcQHgKp.js.map +1 -0
  153. package/dist/{json-I3vJhXo8.js → index-DPll6EAp.js} +12450 -12121
  154. package/dist/index-DPll6EAp.js.map +1 -0
  155. package/dist/{index-CRuq6HVi.js → index-LEY0Og1p.js} +9 -9
  156. package/dist/index-LEY0Og1p.js.map +1 -0
  157. package/dist/index.d.ts +3 -1
  158. package/dist/index.d.ts.map +1 -1
  159. package/dist/interfaces/IItem.d.ts +2 -0
  160. package/dist/interfaces/IItem.d.ts.map +1 -1
  161. package/dist/interfaces/IItemProperty.d.ts +1 -0
  162. package/dist/interfaces/IItemProperty.d.ts.map +1 -1
  163. package/dist/main.cjs +3 -3
  164. package/dist/main.js +999 -1033
  165. package/dist/main.js.map +1 -1
  166. package/dist/node.js +16 -16
  167. package/dist/node.js.map +1 -1
  168. package/dist/{property-Dy09KTxg.js → property-B15X7jLX.js} +7 -5
  169. package/dist/property-B15X7jLX.js.map +1 -0
  170. package/dist/{queries-LZYSuhtz.js → queries-BPDSpiEX.js} +2 -2
  171. package/dist/{queries-LZYSuhtz.js.map → queries-BPDSpiEX.js.map} +1 -1
  172. package/dist/services/write/actors/validateEntity.d.ts.map +1 -1
  173. package/dist/services/write/actors/writeToDatabase.d.ts.map +1 -1
  174. package/dist/services/write/writeProcessMachine.d.ts +1 -1
  175. package/dist/types/index.d.ts +9 -0
  176. package/dist/types/index.d.ts.map +1 -1
  177. package/dist/types/item.d.ts +12 -0
  178. package/dist/types/item.d.ts.map +1 -1
  179. package/dist/types/property.d.ts +6 -0
  180. package/dist/types/property.d.ts.map +1 -1
  181. package/dist/types/publish.d.ts +9 -0
  182. package/dist/types/publish.d.ts.map +1 -0
  183. package/package.json +12 -4
  184. package/dist/ModelProperty-Cr3BmgkC.js.map +0 -1
  185. package/dist/Schema-DeKabJ0T.js.map +0 -1
  186. package/dist/cjs/ModelProperty-MkN5Rmx7.js.map +0 -1
  187. package/dist/cjs/Schema-B5cr_JVK.js.map +0 -1
  188. package/dist/cjs/getPublishPayload-DbOc3WA-.js.map +0 -1
  189. package/dist/cjs/getPublishUploads-NzioLz-3.js.map +0 -1
  190. package/dist/cjs/index-BmIVfqGN.js.map +0 -1
  191. package/dist/cjs/index-C_0angRB.js.map +0 -1
  192. package/dist/events/item/publish.d.ts +0 -7
  193. package/dist/events/item/publish.d.ts.map +0 -1
  194. package/dist/getPublishPayload-NFpqbd_H.js.map +0 -1
  195. package/dist/getPublishUploads-Cpb9vgwE.js.map +0 -1
  196. package/dist/index-CRuq6HVi.js.map +0 -1
  197. package/dist/index-r45w9hEq.js.map +0 -1
  198. package/dist/json-I3vJhXo8.js.map +0 -1
  199. package/dist/property-Dy09KTxg.js.map +0 -1
@@ -1,358 +1,38 @@
1
1
  'use strict';
2
2
 
3
3
  var xstate = require('xstate');
4
- var main_cjs = require('./index-BmIVfqGN.js');
5
- require('pluralize');
6
- var drizzleOrm = require('drizzle-orm');
4
+ var Schema = require('./Schema-CVs9J6eP.js');
5
+ var main_cjs = require('./index-BeKPbbk0.js');
7
6
  var debug = require('debug');
8
-
9
- const logger$4 = debug('seedSdk:helpers:updateSchema');
10
- /**
11
- * Get the file path for a schema file
12
- */
13
- /**
14
- * Sanitize a schema name to be filesystem-safe
15
- * Replaces all special characters (except alphanumeric, hyphens, underscores) with underscores
16
- * Converts spaces to underscores
17
- * Removes leading/trailing underscores
18
- *
19
- * @param name - Schema name to sanitize
20
- * @returns Sanitized name safe for use in filenames
21
- */
22
- const sanitizeSchemaName = (name) => {
23
- return name
24
- .replace(/[^a-zA-Z0-9\s_-]/g, '_') // Replace special chars (except spaces, hyphens, underscores) with underscore
25
- .replace(/\s+/g, '_') // Convert spaces to underscores
26
- .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores
27
- .replace(/_+/g, '_'); // Collapse multiple underscores to single
28
- };
29
- /**
30
- * Get the full file path for a schema
31
- * Format: {schemaFileId}_{schemaName}_v{version}.json
32
- *
33
- * The ID-first format ensures all files for a schema group together when sorted alphabetically.
34
- *
35
- * @param name - Schema name
36
- * @param version - Schema version
37
- * @param schemaFileId - Schema file ID (required)
38
- */
39
- const getSchemaFilePath = (name, version, schemaFileId) => {
40
- const path = main_cjs.BaseFileManager.getPathModule();
41
- const workingDir = main_cjs.BaseFileManager.getWorkingDir();
42
- const sanitizedName = sanitizeSchemaName(name);
43
- const filename = schemaFileId
44
- ? `${schemaFileId}_${sanitizedName}_v${version}.json`
45
- : `${sanitizedName}_v${version}.json`;
46
- return path.join(workingDir, filename);
47
- };
48
- /**
49
- * Get schemaFileId from database for a schema
50
- * @param schemaName - Schema name
51
- * @returns Schema file ID
52
- * @throws Error if schema not found or missing schemaFileId
53
- */
54
- async function getSchemaFileId(schemaName) {
55
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
56
- const db = BaseDb.getAppDb();
57
- const { schemas } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.SchemaSchema; });
58
- const { eq, desc } = await import('drizzle-orm');
59
- const dbSchema = await db
60
- .select()
61
- .from(schemas)
62
- .where(eq(schemas.name, schemaName))
63
- .orderBy(desc(schemas.version))
64
- .limit(1);
65
- if (dbSchema.length === 0 || !dbSchema[0].schemaFileId) {
66
- throw new Error(`Schema ${schemaName} not found in database or missing schemaFileId`);
67
- }
68
- return dbSchema[0].schemaFileId;
69
- }
70
- /**
71
- * Get model name from modelId
72
- * @param modelId - The model ID to look up
73
- * @returns The model name, or undefined if not found
74
- */
75
- async function getModelNameFromId(modelId) {
76
- if (!modelId) {
77
- return undefined;
78
- }
79
- const db = main_cjs.BaseDb.getAppDb();
80
- if (!db) {
81
- throw new Error('Database not found');
82
- }
83
- const modelRecords = await db
84
- .select()
85
- .from(main_cjs.models)
86
- .where(drizzleOrm.eq(main_cjs.models.id, modelId))
87
- .limit(1);
88
- if (modelRecords.length === 0) {
89
- return undefined;
90
- }
91
- return modelRecords[0].name;
92
- }
93
- /**
94
- * Convert a TProperty/ModelPropertyMachineContext to SchemaPropertyUpdate format
95
- * This function converts the internal property representation to the schema file format
96
- * @param property - The TProperty instance to convert
97
- * @param modelName - The name of the model this property belongs to
98
- * @param propertyName - The name of the property
99
- * @returns A SchemaPropertyUpdate object ready to be passed to updateModelProperties
100
- */
101
- async function convertPropertyToSchemaUpdate(property, modelName, propertyName) {
102
- const updates = {};
103
- // Convert dataType to type
104
- if (property.dataType) {
105
- updates.type = property.dataType;
106
- }
107
- // Handle Relation type
108
- if (property.dataType === main_cjs.ModelPropertyDataTypes.Relation) {
109
- if (property.ref) {
110
- updates.model = property.ref;
111
- }
112
- else if (property.refModelId) {
113
- // If ref is not set but refModelId is, get the model name from the database
114
- const refModelName = await getModelNameFromId(property.refModelId);
115
- if (refModelName) {
116
- updates.model = refModelName;
117
- }
118
- }
119
- }
120
- // Handle List type
121
- if (property.dataType === main_cjs.ModelPropertyDataTypes.List) {
122
- if (property.refValueType) {
123
- updates.items = {
124
- type: property.refValueType,
125
- };
126
- if (property.ref) {
127
- updates.items.model = property.ref;
128
- }
129
- else if (property.refModelId) {
130
- // If ref is not set but refModelId is, get the model name from the database
131
- const refModelName = await getModelNameFromId(property.refModelId);
132
- if (refModelName) {
133
- updates.items.model = refModelName;
134
- }
135
- }
136
- }
137
- }
138
- // Handle storage configuration (for Text properties with storage)
139
- if (property.storageType || property.localStorageDir || property.filenameSuffix) {
140
- const storageType = property.storageType || 'ItemStorage'; // Default to ItemStorage if not specified
141
- updates.storage = {
142
- type: storageType,
143
- };
144
- if (property.localStorageDir) {
145
- updates.storage.path = property.localStorageDir;
146
- }
147
- if (property.filenameSuffix) {
148
- updates.storage.extension = property.filenameSuffix;
149
- }
150
- }
151
- return {
152
- modelName,
153
- propertyName,
154
- updates,
155
- };
156
- }
157
- /**
158
- * Update model properties in a schema and create a new version
159
- * @param schemaName - The name of the schema to update
160
- * @param propertyUpdates - Array of property updates to apply
161
- * @param modelUpdates - Optional array of model renames
162
- * @returns The file path of the new schema version
163
- * @throws Error if schema not found or updates are invalid
164
- */
165
- async function updateModelProperties(schemaName, propertyUpdates, modelUpdates) {
166
- // Get the latest version of the schema
167
- const latestVersion = await main_cjs.getLatestSchemaVersion(schemaName);
168
- if (latestVersion === 0) {
169
- throw new Error(`Schema ${schemaName} not found`);
170
- }
171
- // Get schemaFileId from database
172
- const schemaFileId = await getSchemaFileId(schemaName);
173
- // Load the latest schema file
174
- const latestFilePath = getSchemaFilePath(schemaName, latestVersion, schemaFileId);
175
- const content = await main_cjs.BaseFileManager.readFileAsString(latestFilePath);
176
- const schemaFile = JSON.parse(content);
177
- if (!schemaFile.$schema) {
178
- throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
179
- }
180
- // Create a copy of the schema for the new version
181
- // Preserve schema ID and all model/property IDs
182
- const newVersion = latestVersion + 1;
183
- const updatedSchema = {
184
- ...schemaFile,
185
- version: newVersion,
186
- // Preserve schema ID from previous version
187
- id: schemaFile.id,
188
- metadata: {
189
- ...schemaFile.metadata,
190
- updatedAt: new Date().toISOString(),
191
- },
192
- // Deep copy models to preserve IDs
193
- models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
194
- modelName,
195
- {
196
- ...model,
197
- // Preserve model ID
198
- id: model.id,
199
- // Deep copy properties to preserve IDs
200
- properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
201
- propName,
202
- {
203
- ...prop,
204
- // Preserve property ID
205
- id: prop.id,
206
- },
207
- ])),
208
- },
209
- ])),
210
- migrations: [
211
- ...schemaFile.migrations,
212
- {
213
- version: newVersion,
214
- timestamp: new Date().toISOString(),
215
- description: `Updated model properties: ${propertyUpdates.map(u => `${u.modelName}.${u.propertyName}`).join(', ')}`,
216
- changes: propertyUpdates.map(update => ({
217
- type: 'property_update',
218
- modelName: update.modelName,
219
- propertyName: update.propertyName,
220
- updates: update.updates,
221
- })),
222
- },
223
- ],
224
- };
225
- // Apply property updates
226
- for (const update of propertyUpdates) {
227
- const model = updatedSchema.models[update.modelName];
228
- if (!model) {
229
- throw new Error(`Model ${update.modelName} not found in schema ${schemaName}`);
230
- }
231
- if (!model.properties[update.propertyName]) {
232
- throw new Error(`Property ${update.propertyName} not found in model ${update.modelName} of schema ${schemaName}`);
233
- }
234
- // Update the property with new values
235
- const property = model.properties[update.propertyName];
236
- Object.assign(property, update.updates);
237
- }
238
- // Write the new schema version to file using ID-based naming (preferred)
239
- const newFilePath = getSchemaFilePath(schemaName, newVersion, updatedSchema.id ?? undefined);
240
- const newContent = JSON.stringify(updatedSchema, null, 2);
241
- await main_cjs.BaseFileManager.saveFile(newFilePath, newContent);
242
- // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
243
- await main_cjs.BaseFileManager.waitForFileWithContent(newFilePath);
244
- logger$4(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
245
- // Load the new schema file to process models and add them to the database
246
- // Extract model renames from migrations to pass to database update
247
- const modelRenames = new Map();
248
- const latestMigration = updatedSchema.migrations[updatedSchema.migrations.length - 1];
249
- for (const change of latestMigration.changes) {
250
- if (change.type === 'model_rename') {
251
- modelRenames.set(change.oldName, change.newName);
252
- }
253
- }
254
- // Load schema with model renames handled
255
- await loadSchemaWithRenames(newFilePath, modelRenames);
256
- return newFilePath;
257
- }
258
- /**
259
- * Load a schema file and handle model renames in the database
260
- * This is a helper function that processes model renames before loading
261
- */
262
- async function loadSchemaWithRenames(schemaFilePath, modelRenames) {
263
- const content = await main_cjs.BaseFileManager.readFileAsString(schemaFilePath);
264
- const schemaFile = JSON.parse(content);
265
- if (!schemaFile.$schema) {
266
- throw new Error(`File ${schemaFilePath} is not a complete schema file (missing $schema field).`);
267
- }
268
- const schemaName = schemaFile.metadata?.name;
269
- const version = schemaFile.version;
270
- if (!schemaName) {
271
- throw new Error('Schema name is required in metadata.name');
272
- }
273
- // Convert to JsonImportSchema format for processing
274
- // Remove id fields for JsonImportSchema format (they're not part of the import format)
275
- const importData = {
276
- name: schemaName,
277
- models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
278
- modelName,
279
- {
280
- description: model.description,
281
- properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
282
- propName,
283
- {
284
- type: prop.type || 'string', // Ensure type is present
285
- ...prop,
286
- // Remove id field for import format (not part of JsonImportSchema)
287
- },
288
- ])),
289
- indexes: model.indexes,
290
- },
291
- ])),
292
- };
293
- // Use dynamic import to break circular dependency
294
- const { createModelsFromJson } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.json; });
295
- // Generate schema ID if missing
296
- if (!schemaFile.id) {
297
- const { generateId } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.index; });
298
- schemaFile.id = generateId();
299
- logger$4('Generated schema ID for schema:', schemaFile.id);
300
- }
301
- // Extract schemaFileIds from JSON file and generate missing ones BEFORE creating models
302
- // This ensures Model instances are created with correct IDs
303
- const modelFileIds = new Map();
304
- const propertyFileIds = new Map();
305
- const { generateId } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.index; });
306
- for (const [modelName, model] of Object.entries(schemaFile.models)) {
307
- // Generate model ID if missing
308
- if (!model.id) {
309
- model.id = generateId();
310
- logger$4(`Generated model ID for ${modelName}:`, model.id);
311
- }
312
- modelFileIds.set(modelName, model.id);
313
- const propIds = new Map();
314
- for (const [propName, prop] of Object.entries(model.properties)) {
315
- // Generate property ID if missing
316
- if (!prop.id) {
317
- prop.id = generateId();
318
- logger$4(`Generated property ID for ${modelName}.${propName}:`, prop.id);
319
- }
320
- propIds.set(propName, prop.id);
321
- }
322
- if (propIds.size > 0) {
323
- propertyFileIds.set(modelName, propIds);
324
- }
325
- }
326
- // Convert JSON models to Model classes, passing modelFileIds and propertyFileIds so Model instances use correct IDs
327
- const modelDefinitions = await createModelsFromJson(importData, modelFileIds, propertyFileIds);
328
- // Convert schema file metadata to schema input for database
329
- const schemaInput = {
330
- name: schemaName,
331
- version,
332
- schemaFileId: schemaFile.id || null,
333
- schemaData: null,
334
- isDraft: false,
335
- isEdited: false,
336
- createdAt: new Date(schemaFile.metadata.createdAt).getTime(),
337
- updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
338
- };
339
- // Use dynamic import to break circular dependency
340
- const { addSchemaToDb, addModelsToDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.db; });
341
- // Add schema to database with schemaFileId
342
- const schemaRecord = await addSchemaToDb(schemaInput, schemaFile.id);
343
- // Add models to database with model renames handled and schemaFileIds
344
- await addModelsToDb(modelDefinitions, schemaRecord, modelRenames, {
345
- schemaFileId: schemaFile.id,
346
- modelFileIds,
347
- propertyFileIds,
348
- });
349
- // Models are now Model instances, no registration needed
350
- // They should be created via Model.create() and are accessible via Model static methods
351
- for (const [modelName] of Object.entries(modelDefinitions)) {
352
- logger$4('loadSchemaWithRenames - model available:', modelName);
353
- }
354
- return schemaFilePath;
355
- }
7
+ var drizzleOrm = require('drizzle-orm');
8
+ require('./SchemaValidationService-CDKcVRFQ.js');
9
+ require('@sinclair/typebox/value');
10
+ require('reflect-metadata');
11
+ require('pluralize');
12
+ require('@sinclair/typebox');
13
+ require('immer');
14
+ require('drizzle-orm/sqlite-core');
15
+ require('nanoid');
16
+ require('nanoid-dictionary');
17
+ require('ethers');
18
+ require('rxjs');
19
+ require('lodash-es');
20
+ require('drizzle-orm/casing');
21
+ require('eventemitter3');
22
+ require('arweave');
23
+ require('fs/promises');
24
+ require('fs');
25
+ require('path');
26
+ require('@libsql/client');
27
+ require('drizzle-orm/libsql');
28
+ require('drizzle-kit/api');
29
+ require('js-yaml');
30
+ require('ts-import');
31
+ require('glob');
32
+ require('rimraf');
33
+ require('child_process');
34
+ require('url');
35
+ require('graphql-request');
356
36
 
357
37
  const logger$3 = debug('seedSdk:modelProperty:actors:saveToSchema');
358
38
  /**
@@ -362,11 +42,11 @@ const logger$3 = debug('seedSdk:modelProperty:actors:saveToSchema');
362
42
  */
363
43
  async function getSchemaNameFromModel(modelName) {
364
44
  // Get the latest schema files and find which one contains this model
365
- const { listLatestSchemaFiles } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema$1; });
45
+ const { listLatestSchemaFiles } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.schema$1; });
366
46
  const latestSchemas = await listLatestSchemaFiles();
367
47
  for (const schema of latestSchemas) {
368
48
  try {
369
- const { BaseFileManager } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseFileManager$1; });
49
+ const { BaseFileManager } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.BaseFileManager$1; });
370
50
  const content = await BaseFileManager.readFileAsString(schema.filePath);
371
51
  const schemaFile = JSON.parse(content);
372
52
  if (schemaFile.models && schemaFile.models[modelName]) {
@@ -383,7 +63,7 @@ async function getSchemaNameFromModel(modelName) {
383
63
  const saveToSchema = xstate.fromCallback(({ sendBack, input: { context } }) => {
384
64
  const _saveToSchema = async () => {
385
65
  // Use dynamic import to break circular dependency
386
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-BgIzc3-r.js'); });
66
+ const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CDKcVRFQ.js'); });
387
67
  const validationService = new SchemaValidationService();
388
68
  // Validate property structure before saving
389
69
  const validationResult = validationService.validatePropertyStructure(context);
@@ -406,15 +86,14 @@ const saveToSchema = xstate.fromCallback(({ sendBack, input: { context } }) => {
406
86
  throw new Error(`Schema not found for model: ${context.modelName}`);
407
87
  }
408
88
  // Convert property context to SchemaPropertyUpdate
409
- const propertyUpdate = await convertPropertyToSchemaUpdate(context, context.modelName, context.name);
89
+ const propertyUpdate = await Schema.convertPropertyToSchemaUpdate(context, context.modelName, context.name);
410
90
  // Update the schema with the property changes
411
- await updateModelProperties(schemaName, [propertyUpdate]);
91
+ await Schema.updateModelProperties(schemaName, [propertyUpdate]);
412
92
  // Clear isEdited flag in database after saving to schema file
413
93
  try {
414
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
415
- const { properties: propertiesTable, models: modelsTable } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema; });
94
+ const { properties: propertiesTable, models: modelsTable } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.schema; });
416
95
  const { eq, and } = await import('drizzle-orm');
417
- const db = BaseDb.getAppDb();
96
+ const db = main_cjs.BaseDb.getAppDb();
418
97
  if (db && context.modelName && context.name) {
419
98
  // Find model by name
420
99
  const modelRecords = await db
@@ -456,54 +135,89 @@ const saveToSchema = xstate.fromCallback(({ sendBack, input: { context } }) => {
456
135
  };
457
136
  });
458
137
 
459
- var saveToSchema$1 = /*#__PURE__*/Object.freeze({
460
- __proto__: null,
461
- getSchemaNameFromModel: getSchemaNameFromModel,
462
- saveToSchema: saveToSchema
463
- });
464
-
465
138
  const logger$2 = debug('seedSdk:modelProperty:actors:compareAndMarkDraft');
466
139
  const compareAndMarkDraft = xstate.fromCallback(({ sendBack, input: { context } }) => {
467
140
  const _compareAndMarkDraft = async () => {
141
+ // Fill modelName/dataType from _originalValues when missing, then from DB by schemaFileId
142
+ let fullContext = {
143
+ ...context,
144
+ modelName: context.modelName ?? context._originalValues?.modelName,
145
+ dataType: context.dataType ?? context._originalValues?.dataType,
146
+ };
147
+ const schemaFileIdForResolve = fullContext._propertyFileId || (typeof fullContext.id === 'string' ? fullContext.id : undefined);
148
+ if (schemaFileIdForResolve && (fullContext.modelName === undefined || fullContext.dataType === undefined)) {
149
+ try {
150
+ const { getPropertyModelNameAndDataType, getModelNameByModelId } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.db; });
151
+ let fromDb;
152
+ for (let attempt = 0; attempt < 6; attempt++) {
153
+ fromDb = await getPropertyModelNameAndDataType(schemaFileIdForResolve);
154
+ if (fromDb)
155
+ break;
156
+ if (attempt < 5)
157
+ await new Promise((r) => setTimeout(r, 40));
158
+ }
159
+ if (fromDb) {
160
+ fullContext = {
161
+ ...fullContext,
162
+ modelName: fullContext.modelName ?? fromDb.modelName,
163
+ dataType: fullContext.dataType ?? fromDb.dataType,
164
+ };
165
+ }
166
+ if (fullContext.modelName === undefined && schemaFileIdForResolve) {
167
+ const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
168
+ const ModelProperty = mod?.ModelProperty ?? mod?.default;
169
+ const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileIdForResolve);
170
+ if (pendingModelId != null) {
171
+ const modelName = await getModelNameByModelId(pendingModelId);
172
+ if (modelName) {
173
+ fullContext = { ...fullContext, modelName };
174
+ }
175
+ }
176
+ }
177
+ }
178
+ catch {
179
+ // ignore
180
+ }
181
+ }
182
+ const schemaFileId = fullContext._propertyFileId || (typeof fullContext.id === 'string' ? fullContext.id : undefined);
468
183
  // If _originalValues is not set, we still need to save to database if the property exists
469
184
  // This handles the case where the name is changed before _originalValues is initialized
470
- if (!context._originalValues) {
185
+ if (!fullContext._originalValues) {
471
186
  logger$2('No original values to compare against');
472
- logger$2(`[compareAndMarkDraft] Context: modelName=${context.modelName}, name=${context.name}, id=${context.id}, _propertyFileId=${context._propertyFileId}`);
187
+ logger$2(`[compareAndMarkDraft] Context: modelName=${fullContext.modelName}, name=${fullContext.name}, id=${fullContext.id}, _propertyFileId=${fullContext._propertyFileId}`);
473
188
  // If we have a name and modelName, try to save to database anyway
474
189
  // This ensures name changes are persisted even if _originalValues isn't initialized yet
475
190
  // We need either schemaFileId (id or _propertyFileId) to find the property in the database
476
- const schemaFileId = context._propertyFileId || (typeof context.id === 'string' ? context.id : undefined);
477
- if (context.modelName && context.name && schemaFileId) {
191
+ if (fullContext.modelName && fullContext.name && schemaFileId) {
478
192
  logger$2(`[compareAndMarkDraft] _originalValues not set, but saving to database anyway for property ${context.modelName}:${context.name} (schemaFileId: ${schemaFileId})`);
479
193
  try {
480
- const { savePropertyToDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.db; });
194
+ const { savePropertyToDb } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.db; });
481
195
  // Ensure _propertyFileId is set for savePropertyToDb to find the property
482
196
  const contextWithFileId = {
483
- ...context,
197
+ ...fullContext,
484
198
  _propertyFileId: schemaFileId,
485
199
  };
486
200
  await savePropertyToDb(contextWithFileId);
487
- logger$2(`[compareAndMarkDraft] Successfully saved property ${context.modelName}:${context.name} to database (no _originalValues)`);
201
+ logger$2(`[compareAndMarkDraft] Successfully saved property ${fullContext.modelName}:${fullContext.name} to database (no _originalValues)`);
488
202
  }
489
203
  catch (error) {
490
204
  logger$2(`[compareAndMarkDraft] Error saving property to database (no _originalValues): ${error}`);
491
205
  // Don't throw - this is a best-effort save, but log the error for debugging
492
- console.error(`[compareAndMarkDraft] Failed to save property ${context.modelName}:${context.name}:`, error);
206
+ console.error(`[compareAndMarkDraft] Failed to save property ${fullContext.modelName}:${fullContext.name}:`, error);
493
207
  }
494
208
  }
495
209
  else {
496
- logger$2(`[compareAndMarkDraft] Cannot save property ${context.modelName}:${context.name} - missing required fields (schemaFileId: ${schemaFileId})`);
210
+ logger$2(`[compareAndMarkDraft] Cannot save property ${fullContext.modelName}:${fullContext.name} - missing required fields (schemaFileId: ${schemaFileId})`);
497
211
  }
498
212
  return;
499
213
  }
500
- logger$2(`[compareAndMarkDraft] Comparing: context.name=${context.name}, _originalValues.name=${context._originalValues?.name}`);
214
+ logger$2(`[compareAndMarkDraft] Comparing: context.name=${fullContext.name}, _originalValues.name=${fullContext._originalValues?.name}`);
501
215
  // Compare current values with original
502
216
  // Only compare property fields, not internal fields
503
217
  const propertyFields = ['name', 'dataType', 'ref', 'refModelName', 'refModelId', 'refValueType', 'storageType', 'localStorageDir', 'filenameSuffix', 'modelName', 'modelId'];
504
218
  const hasChanges = propertyFields.some(key => {
505
- const currentValue = context[key];
506
- const originalValue = context._originalValues?.[key];
219
+ const currentValue = fullContext[key];
220
+ const originalValue = fullContext._originalValues?.[key];
507
221
  // Handle name changes specifically
508
222
  if (key === 'name') {
509
223
  const nameChanged = currentValue !== originalValue;
@@ -514,8 +228,8 @@ const compareAndMarkDraft = xstate.fromCallback(({ sendBack, input: { context }
514
228
  }
515
229
  // Handle ref fields - compare by name
516
230
  if (key === 'ref' || key === 'refModelName') {
517
- const currentRef = context.refModelName || context.ref;
518
- const originalRef = context._originalValues?.refModelName || context._originalValues?.ref;
231
+ const currentRef = fullContext.refModelName || fullContext.ref;
232
+ const originalRef = fullContext._originalValues?.refModelName || fullContext._originalValues?.ref;
519
233
  // Both undefined/null means no ref, so they're the same
520
234
  if (!currentRef && !originalRef)
521
235
  return false;
@@ -533,53 +247,54 @@ const compareAndMarkDraft = xstate.fromCallback(({ sendBack, input: { context }
533
247
  return currentValue !== originalValue;
534
248
  });
535
249
  if (hasChanges) {
536
- logger$2(`Property ${context.modelName}:${context.name} has changes, marking as edited`);
537
- logger$2(`[compareAndMarkDraft] Context when saving: id=${context.id}, _propertyFileId=${context._propertyFileId}, name=${context.name}, _originalValues.name=${context._originalValues?.name}`);
250
+ logger$2(`Property ${fullContext.modelName}:${fullContext.name} has changes, marking as edited`);
251
+ logger$2(`[compareAndMarkDraft] Context when saving: id=${fullContext.id}, _propertyFileId=${fullContext._propertyFileId}, name=${fullContext.name}, _originalValues.name=${fullContext._originalValues?.name}`);
538
252
  // Use dynamic import to break circular dependency
539
- const { savePropertyToDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.db; });
253
+ const { savePropertyToDb } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.db; });
540
254
  // Save to database (but not JSON file) - always save to DB when there are changes
541
255
  try {
542
- await savePropertyToDb(context);
543
- logger$2(`[compareAndMarkDraft] Successfully saved property ${context.modelName}:${context.name} to database`);
256
+ await savePropertyToDb(fullContext);
257
+ logger$2(`[compareAndMarkDraft] Successfully saved property ${fullContext.modelName}:${fullContext.name} to database`);
544
258
  }
545
259
  catch (error) {
546
260
  logger$2(`[compareAndMarkDraft] Error saving property to database: ${error}`);
547
261
  throw error;
548
262
  }
549
263
  // Mark schema as draft if schema name is available
550
- if (context._schemaName) {
264
+ if (fullContext._schemaName) {
551
265
  // Get the Schema instance and mark it as draft
552
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-B5cr_JVK.js'); });
553
- const schema = Schema.create(context._schemaName);
266
+ const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
267
+ const schema = Schema.create(fullContext._schemaName, {
268
+ waitForReady: false,
269
+ });
554
270
  // Send event to Schema machine to mark as draft
555
271
  schema.getService().send({
556
272
  type: 'markAsDraft',
557
- propertyKey: `${context.modelName}:${context.name}`,
273
+ propertyKey: `${fullContext.modelName}:${fullContext.name}`,
558
274
  });
559
275
  }
560
276
  }
561
277
  else {
562
278
  // No changes - clear edited flag in database and context
563
- logger$2(`Property ${context.modelName}:${context.name} has no changes`);
279
+ logger$2(`Property ${fullContext.modelName}:${fullContext.name} has no changes`);
564
280
  // Clear isEdited flag in database
565
281
  try {
566
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
567
- const { properties: propertiesTable, models: modelsTable } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema; });
282
+ const { properties: propertiesTable, models: modelsTable } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.schema; });
568
283
  const { eq, and } = await import('drizzle-orm');
569
- const db = BaseDb.getAppDb();
570
- if (db && context.modelName && context.name) {
284
+ const db = main_cjs.BaseDb.getAppDb();
285
+ if (db && fullContext.modelName && fullContext.name) {
571
286
  // Find model by name
572
287
  const modelRecords = await db
573
288
  .select({ id: modelsTable.id })
574
289
  .from(modelsTable)
575
- .where(eq(modelsTable.name, context.modelName))
290
+ .where(eq(modelsTable.name, fullContext.modelName))
576
291
  .limit(1);
577
292
  if (modelRecords.length > 0) {
578
293
  // Find property by name and modelId
579
294
  const propertyRecords = await db
580
295
  .select({ id: propertiesTable.id })
581
296
  .from(propertiesTable)
582
- .where(and(eq(propertiesTable.name, context.name), eq(propertiesTable.modelId, modelRecords[0].id)))
297
+ .where(and(eq(propertiesTable.name, fullContext.name), eq(propertiesTable.modelId, modelRecords[0].id)))
583
298
  .limit(1);
584
299
  if (propertyRecords.length > 0) {
585
300
  // Clear isEdited flag in database
@@ -587,7 +302,7 @@ const compareAndMarkDraft = xstate.fromCallback(({ sendBack, input: { context }
587
302
  .update(propertiesTable)
588
303
  .set({ isEdited: false })
589
304
  .where(eq(propertiesTable.id, propertyRecords[0].id));
590
- logger$2(`Cleared isEdited flag in database for property ${context.modelName}:${context.name}`);
305
+ logger$2(`Cleared isEdited flag in database for property ${fullContext.modelName}:${fullContext.name}`);
591
306
  }
592
307
  }
593
308
  }
@@ -614,20 +329,82 @@ const compareAndMarkDraft = xstate.fromCallback(({ sendBack, input: { context }
614
329
  const logger$1 = debug('seedSdk:modelProperty:actors:validateProperty');
615
330
  const validateProperty = xstate.fromCallback(({ sendBack, input: { context } }) => {
616
331
  const _validateProperty = async () => {
617
- console.log('[validateProperty] Starting validation for property:', context.name);
332
+ // Use full context for validation: fill modelName/dataType from _originalValues when missing, then
333
+ // from DB by schemaFileId (context.id) so just-created renames don't fail structure validation.
334
+ let fullContext = {
335
+ ...context,
336
+ modelName: context.modelName ?? context._originalValues?.modelName,
337
+ dataType: context.dataType ?? context._originalValues?.dataType,
338
+ };
339
+ const schemaFileId = typeof context.id === 'string' ? context.id : undefined;
340
+ if (schemaFileId && (fullContext.modelName === undefined || fullContext.dataType === undefined)) {
341
+ // Brief wait so trackPendingWrite from ModelProperty.create() has time to run (it's in setTimeout(0))
342
+ await new Promise((r) => setTimeout(r, 60));
343
+ try {
344
+ const { getPropertyModelNameAndDataType, getModelNameByModelId } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.db; });
345
+ // Try pending write first (property row may not exist yet)
346
+ if (fullContext.modelName === undefined && schemaFileId) {
347
+ const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
348
+ const ModelProperty = mod?.ModelProperty ?? mod?.default;
349
+ const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileId);
350
+ if (pendingModelId != null) {
351
+ const modelName = await getModelNameByModelId(pendingModelId);
352
+ if (modelName) {
353
+ fullContext = { ...fullContext, modelName };
354
+ }
355
+ }
356
+ }
357
+ // Then DB property lookup with retry (catches row after initial write)
358
+ let fromDb;
359
+ for (let attempt = 0; attempt < 6; attempt++) {
360
+ fromDb = await getPropertyModelNameAndDataType(schemaFileId);
361
+ if (fromDb)
362
+ break;
363
+ if (attempt < 5)
364
+ await new Promise((r) => setTimeout(r, 40));
365
+ }
366
+ if (fromDb) {
367
+ fullContext = {
368
+ ...fullContext,
369
+ modelName: fullContext.modelName ?? fromDb.modelName,
370
+ dataType: fullContext.dataType ?? fromDb.dataType,
371
+ };
372
+ }
373
+ // If still no modelName, try pending write again (may have been set during retries)
374
+ if (fullContext.modelName === undefined && schemaFileId) {
375
+ const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
376
+ const ModelProperty = mod?.ModelProperty ?? mod?.default;
377
+ const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileId);
378
+ if (pendingModelId != null) {
379
+ const modelName = await getModelNameByModelId(pendingModelId);
380
+ if (modelName) {
381
+ fullContext = { ...fullContext, modelName };
382
+ }
383
+ }
384
+ }
385
+ }
386
+ catch {
387
+ // ignore
388
+ }
389
+ }
390
+ // Last resort for structure validation: TProperty requires dataType; allow name+id to pass if we have schemaFileId
391
+ if (fullContext.dataType === undefined && (fullContext.modelName !== undefined || schemaFileId)) {
392
+ fullContext = { ...fullContext, dataType: (fullContext.dataType ?? context._originalValues?.dataType) || 'Text' };
393
+ }
394
+ console.log('[validateProperty] Starting validation for property:', fullContext.name);
618
395
  console.log('[validateProperty] Context:', {
619
- name: context.name,
620
- modelName: context.modelName,
621
- _schemaName: context._schemaName,
622
- _originalValues: context._originalValues
396
+ name: fullContext.name,
397
+ modelName: fullContext.modelName,
398
+ _schemaName: fullContext._schemaName,
399
+ _originalValues: fullContext._originalValues
623
400
  });
624
401
  // Use dynamic imports to break circular dependencies
625
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-BgIzc3-r.js'); });
402
+ const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CDKcVRFQ.js'); });
626
403
  const validationService = new SchemaValidationService();
627
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-B5cr_JVK.js'); });
404
+ const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
628
405
  // Validate property structure
629
406
  console.log('[validateProperty] Validating property structure...');
630
- const structureResult = validationService.validatePropertyStructure(context);
407
+ const structureResult = validationService.validatePropertyStructure(fullContext);
631
408
  console.log('[validateProperty] Structure validation result:', structureResult.isValid);
632
409
  if (!structureResult.isValid) {
633
410
  console.log('[validateProperty] Structure validation failed:', structureResult.errors);
@@ -636,11 +413,13 @@ const validateProperty = xstate.fromCallback(({ sendBack, input: { context } })
636
413
  }
637
414
  console.log('[validateProperty] Structure validation passed');
638
415
  // If we have schema name and model name, validate against schema
639
- console.log('[validateProperty] Checking schema validation:', { hasSchemaName: !!context._schemaName, hasModelName: !!context.modelName });
640
- if (context._schemaName && context.modelName) {
416
+ console.log('[validateProperty] Checking schema validation:', { hasSchemaName: !!fullContext._schemaName, hasModelName: !!fullContext.modelName });
417
+ if (fullContext._schemaName && fullContext.modelName) {
641
418
  try {
642
- console.log('[validateProperty] Creating schema instance:', context._schemaName);
643
- const schema = Schema.create(context._schemaName);
419
+ console.log('[validateProperty] Creating schema instance:', fullContext._schemaName);
420
+ const schema = Schema.create(fullContext._schemaName, {
421
+ waitForReady: false,
422
+ });
644
423
  const schemaSnapshot = schema.getService().getSnapshot();
645
424
  const schemaStatus = schemaSnapshot.value;
646
425
  console.log('[validateProperty] Schema status:', schemaStatus);
@@ -653,28 +432,28 @@ const validateProperty = xstate.fromCallback(({ sendBack, input: { context } })
653
432
  if (schemaContext.models && Object.keys(schemaContext.models).length > 0) {
654
433
  // If property name has changed, validate against the original name (from schema file)
655
434
  // This handles the case where a property is renamed - the schema file still has the old name
656
- const propertyNameToValidate = context._originalValues?.name && context._originalValues.name !== context.name
657
- ? context._originalValues.name
658
- : context.name || '';
435
+ const propertyNameToValidate = fullContext._originalValues?.name && fullContext._originalValues.name !== fullContext.name
436
+ ? fullContext._originalValues.name
437
+ : fullContext.name || '';
659
438
  console.log('[validateProperty] Validating against schema:', {
660
- modelName: context.modelName,
439
+ modelName: fullContext.modelName,
661
440
  propertyNameToValidate,
662
- originalName: context._originalValues?.name,
663
- currentName: context.name
441
+ originalName: fullContext._originalValues?.name,
442
+ currentName: fullContext.name
664
443
  });
665
- const schemaResult = validationService.validateProperty(schemaContext, context.modelName, propertyNameToValidate, context);
444
+ const schemaResult = validationService.validateProperty(schemaContext, fullContext.modelName, propertyNameToValidate, fullContext);
666
445
  console.log('[validateProperty] Schema validation result:', { isValid: schemaResult.isValid, errors: schemaResult.errors.length, errorCodes: schemaResult.errors.map(e => e.code) });
667
446
  if (!schemaResult.isValid) {
668
447
  // If property was renamed, some validation errors are expected (like property_not_found, missing_type)
669
448
  // Only fail if it's a critical error that's not related to the rename
670
- const isRenamed = context._originalValues?.name && context._originalValues.name !== context.name;
449
+ const isRenamed = fullContext._originalValues?.name && fullContext._originalValues.name !== fullContext.name;
671
450
  const criticalErrors = schemaResult.errors.filter(err => {
672
451
  // Allow property_not_found and missing_type errors when property is renamed
673
452
  if (isRenamed && (err.code === 'property_not_found' || err.code === 'missing_type')) {
674
453
  return false; // Not critical
675
454
  }
676
455
  // For non-renamed properties, only allow property_not_found if we're validating with the same name
677
- if (err.code === 'property_not_found' && propertyNameToValidate === context.name) {
456
+ if (err.code === 'property_not_found' && propertyNameToValidate === fullContext.name) {
678
457
  return false; // Not critical
679
458
  }
680
459
  return true; // Critical error
@@ -808,6 +587,15 @@ const modelPropertyMachine = xstate.setup({
808
587
  }
809
588
  newContext[key] = value;
810
589
  }
590
+ // Preserve modelName and dataType from context or _originalValues so validation and savePropertyToDb
591
+ // never run with missing required/needed fields (e.g. when a just-created property is renamed before
592
+ // the full context is available from the creator).
593
+ if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
594
+ newContext.modelName = context._originalValues.modelName;
595
+ }
596
+ if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
597
+ newContext.dataType = context._originalValues.dataType;
598
+ }
811
599
  // Compare with original values and set _isEdited flag (only for non-internal updates)
812
600
  if (!onlyInternalFields && context._originalValues) {
813
601
  const hasChanges = Object.keys(event).some((key) => {
@@ -877,6 +665,23 @@ const modelPropertyMachine = xstate.setup({
877
665
  _schemaName: event.schemaName,
878
666
  })),
879
667
  },
668
+ destroyStarted: {
669
+ actions: xstate.assign({ _destroyInProgress: true, _destroyError: null }),
670
+ },
671
+ destroyDone: {
672
+ actions: xstate.assign({ _destroyInProgress: false }),
673
+ },
674
+ destroyError: {
675
+ actions: xstate.assign(({ event }) => ({
676
+ _destroyInProgress: false,
677
+ _destroyError: event.error instanceof Error
678
+ ? { message: event.error.message, name: event.error.name }
679
+ : { message: String(event.error) },
680
+ })),
681
+ },
682
+ clearDestroyError: {
683
+ actions: xstate.assign({ _destroyError: null }),
684
+ },
880
685
  },
881
686
  states: {
882
687
  idle: {
@@ -1002,6 +807,32 @@ const modelPropertyMachine = xstate.setup({
1002
807
  },
1003
808
  });
1004
809
 
810
+ /**
811
+ * Returns property rows for a model identified by modelFileId (model's schemaFileId).
812
+ * Resolves modelFileId -> modelId via models table, then selects all properties where modelId = ?.
813
+ * Each row includes schemaFileId for use with ModelProperty.createById(schemaFileId).
814
+ */
815
+ const getModelPropertiesData = async (modelFileId) => {
816
+ const appDb = main_cjs.BaseDb.getAppDb();
817
+ if (!appDb || !modelFileId) {
818
+ return [];
819
+ }
820
+ const modelRows = await appDb
821
+ .select({ id: main_cjs.models.id })
822
+ .from(main_cjs.models)
823
+ .where(drizzleOrm.eq(main_cjs.models.schemaFileId, modelFileId))
824
+ .limit(1);
825
+ if (modelRows.length === 0) {
826
+ return [];
827
+ }
828
+ const modelId = modelRows[0].id;
829
+ const rows = await appDb
830
+ .select()
831
+ .from(main_cjs.properties)
832
+ .where(drizzleOrm.eq(main_cjs.properties.modelId, modelId));
833
+ return rows;
834
+ };
835
+
1005
836
  const logger = debug('seedSdk:modelProperty:ModelProperty');
1006
837
  // Define the property keys from TProperty
1007
838
  const TPropertyKeys = [
@@ -1168,27 +999,24 @@ class ModelProperty {
1168
999
  return fallbackIsEdited;
1169
1000
  }
1170
1001
  try {
1171
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
1172
- const { properties: propertiesTable, models: modelsTable } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema; });
1173
- const { eq, and } = await import('drizzle-orm');
1174
- const db = BaseDb.getAppDb();
1002
+ const db = main_cjs.BaseDb.getAppDb();
1175
1003
  if (!db) {
1176
1004
  return fallbackIsEdited;
1177
1005
  }
1178
1006
  // Find model by name
1179
1007
  const modelRecords = await db
1180
- .select({ id: modelsTable.id })
1181
- .from(modelsTable)
1182
- .where(eq(modelsTable.name, property.modelName))
1008
+ .select({ id: main_cjs.models.id })
1009
+ .from(main_cjs.models)
1010
+ .where(drizzleOrm.eq(main_cjs.models.name, property.modelName))
1183
1011
  .limit(1);
1184
1012
  if (modelRecords.length === 0) {
1185
1013
  return fallbackIsEdited;
1186
1014
  }
1187
1015
  // Find property by name and modelId
1188
1016
  const propertyRecords = await db
1189
- .select({ isEdited: propertiesTable.isEdited })
1190
- .from(propertiesTable)
1191
- .where(and(eq(propertiesTable.name, property.name), eq(propertiesTable.modelId, modelRecords[0].id)))
1017
+ .select({ isEdited: main_cjs.properties.isEdited })
1018
+ .from(main_cjs.properties)
1019
+ .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.properties.name, property.name), drizzleOrm.eq(main_cjs.properties.modelId, modelRecords[0].id)))
1192
1020
  .limit(1);
1193
1021
  if (propertyRecords.length > 0) {
1194
1022
  return propertyRecords[0].isEdited ?? false;
@@ -1209,18 +1037,14 @@ class ModelProperty {
1209
1037
  return undefined;
1210
1038
  }
1211
1039
  try {
1212
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
1213
- const seedSchema = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema; });
1214
- const modelsTable = seedSchema.models;
1215
- const { eq } = await import('drizzle-orm');
1216
- const db = BaseDb.getAppDb();
1040
+ const db = main_cjs.BaseDb.getAppDb();
1217
1041
  if (!db) {
1218
1042
  return undefined;
1219
1043
  }
1220
1044
  const refModelRecords = await db
1221
1045
  .select()
1222
- .from(modelsTable)
1223
- .where(eq(modelsTable.name, refModelName))
1046
+ .from(main_cjs.models)
1047
+ .where(drizzleOrm.eq(main_cjs.models.name, refModelName))
1224
1048
  .limit(1);
1225
1049
  if (refModelRecords.length > 0 && refModelRecords[0].id) {
1226
1050
  return refModelRecords[0].id;
@@ -1241,13 +1065,11 @@ class ModelProperty {
1241
1065
  return undefined;
1242
1066
  }
1243
1067
  try {
1244
- const { Model } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.Model$1; });
1245
- const { modelPropertiesToObject } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.model; });
1246
- const model = await Model.getByNameAsync(property.modelName);
1068
+ const model = await main_cjs.Model.getByNameAsync(property.modelName);
1247
1069
  if (!model || !model.properties || model.properties.length === 0) {
1248
1070
  return undefined;
1249
1071
  }
1250
- const schema = modelPropertiesToObject(model.properties);
1072
+ const schema = main_cjs.modelPropertiesToObject(model.properties);
1251
1073
  // Get the schema file value for this property
1252
1074
  const schemaFileValue = schema[property.name];
1253
1075
  if (!schemaFileValue) {
@@ -1291,22 +1113,16 @@ class ModelProperty {
1291
1113
  // Try to get schema name from database first (more reliable)
1292
1114
  if (this.modelId) {
1293
1115
  try {
1294
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
1295
- const seedSchema = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema; });
1296
- const modelsTable = seedSchema.models;
1297
- const modelSchemas = seedSchema.modelSchemas;
1298
- const schemas = seedSchema.schemas;
1299
- const { eq } = await import('drizzle-orm');
1300
- const db = BaseDb.getAppDb();
1116
+ const db = main_cjs.BaseDb.getAppDb();
1301
1117
  if (db) {
1302
1118
  const modelSchemaRecords = await db
1303
1119
  .select({
1304
- schemaName: schemas.name,
1120
+ schemaName: main_cjs.schemas.name,
1305
1121
  })
1306
- .from(modelSchemas)
1307
- .innerJoin(schemas, eq(modelSchemas.schemaId, schemas.id))
1308
- .innerJoin(modelsTable, eq(modelSchemas.modelId, modelsTable.id))
1309
- .where(eq(modelsTable.id, this.modelId))
1122
+ .from(main_cjs.modelSchemas)
1123
+ .innerJoin(main_cjs.schemas, drizzleOrm.eq(main_cjs.modelSchemas.schemaId, main_cjs.schemas.id))
1124
+ .innerJoin(main_cjs.models, drizzleOrm.eq(main_cjs.modelSchemas.modelId, main_cjs.models.id))
1125
+ .where(drizzleOrm.eq(main_cjs.models.id, this.modelId))
1310
1126
  .limit(1);
1311
1127
  if (modelSchemaRecords.length > 0) {
1312
1128
  schemaName = modelSchemaRecords[0].schemaName;
@@ -1319,7 +1135,6 @@ class ModelProperty {
1319
1135
  }
1320
1136
  // Fall back to schema file lookup if database didn't work
1321
1137
  if (!schemaName) {
1322
- const { getSchemaNameFromModel } = await Promise.resolve().then(function () { return saveToSchema$1; });
1323
1138
  schemaName = await getSchemaNameFromModel(modelName);
1324
1139
  }
1325
1140
  if (schemaName) {
@@ -1344,10 +1159,12 @@ class ModelProperty {
1344
1159
  schemaName,
1345
1160
  });
1346
1161
  }
1347
- static create(property) {
1162
+ static create(property, options) {
1348
1163
  if (!property) {
1349
1164
  throw new Error('Property is required');
1350
1165
  }
1166
+ const waitForReady = options?.waitForReady !== false;
1167
+ const readyTimeout = options?.readyTimeout ?? 5000;
1351
1168
  // Debug: Log what's being passed to create()
1352
1169
  console.log(`[ModelProperty.create] Input property data:`, JSON.stringify({
1353
1170
  name: property.name,
@@ -1421,7 +1238,9 @@ class ModelProperty {
1421
1238
  instance,
1422
1239
  refCount: refCount + 1,
1423
1240
  });
1424
- return instance;
1241
+ if (!waitForReady)
1242
+ return instance;
1243
+ return main_cjs.waitForEntityIdle(instance, { timeout: readyTimeout }).then(() => instance);
1425
1244
  }
1426
1245
  // Debug: Log what's being passed to the constructor
1427
1246
  console.log(`[ModelProperty.create] propertyWithId before constructor:`, JSON.stringify({
@@ -1496,8 +1315,7 @@ class ModelProperty {
1496
1315
  else if (typeof propertyWithId.modelId === 'string') {
1497
1316
  // modelId is a string (modelFileId), need to convert to database ID
1498
1317
  try {
1499
- const { getModelIdByFileId } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.db; });
1500
- resolvedModelId = await getModelIdByFileId(propertyWithId.modelId);
1318
+ resolvedModelId = await main_cjs.getModelIdByFileId(propertyWithId.modelId);
1501
1319
  logger(`Converted modelFileId "${propertyWithId.modelId}" to database modelId: ${resolvedModelId}`);
1502
1320
  }
1503
1321
  catch (error) {
@@ -1509,10 +1327,9 @@ class ModelProperty {
1509
1327
  // If we still don't have a modelId, try to resolve it from modelName
1510
1328
  if (!resolvedModelId && propertyWithId.modelName) {
1511
1329
  try {
1512
- const { getModelId } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.db; });
1513
1330
  // Get schemaName from context if available
1514
1331
  const schemaName = snapshot.context._schemaName;
1515
- resolvedModelId = await getModelId(propertyWithId.modelName, schemaName);
1332
+ resolvedModelId = await main_cjs.getModelId(propertyWithId.modelName, schemaName);
1516
1333
  logger(`Resolved modelId for model "${propertyWithId.modelName}": ${resolvedModelId}`);
1517
1334
  }
1518
1335
  catch (error) {
@@ -1583,7 +1400,9 @@ class ModelProperty {
1583
1400
  // Start checking after a short delay to allow state machine to initialize
1584
1401
  setTimeout(checkAndSend, 0);
1585
1402
  }
1586
- return proxiedInstance;
1403
+ if (!waitForReady)
1404
+ return proxiedInstance;
1405
+ return main_cjs.waitForEntityIdle(proxiedInstance, { timeout: readyTimeout }).then(() => proxiedInstance);
1587
1406
  }
1588
1407
  /**
1589
1408
  * Get ModelProperty instance by propertyFileId from static cache
@@ -1616,10 +1435,7 @@ class ModelProperty {
1616
1435
  return cachedInstance;
1617
1436
  }
1618
1437
  // Query database to get property data from ID
1619
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.BaseDb$1; });
1620
- const { properties: propertiesTable, models: modelsTable } = await Promise.resolve().then(function () { return require('./index-BmIVfqGN.js'); }).then(function (n) { return n.schema; });
1621
- const { eq } = await import('drizzle-orm');
1622
- const db = BaseDb.getAppDb();
1438
+ const db = main_cjs.BaseDb.getAppDb();
1623
1439
  console.log('db', !!db);
1624
1440
  if (!db) {
1625
1441
  console.log('db not found');
@@ -1627,13 +1443,13 @@ class ModelProperty {
1627
1443
  }
1628
1444
  const testRecords = await db
1629
1445
  .select()
1630
- .from(propertiesTable)
1446
+ .from(main_cjs.properties)
1631
1447
  .limit(100);
1632
1448
  console.log('testRecords', testRecords);
1633
1449
  const propertyRecords = await db
1634
1450
  .select()
1635
- .from(propertiesTable)
1636
- .where(eq(propertiesTable.schemaFileId, propertyFileId))
1451
+ .from(main_cjs.properties)
1452
+ .where(drizzleOrm.eq(main_cjs.properties.schemaFileId, propertyFileId))
1637
1453
  .limit(1);
1638
1454
  console.log('propertyRecords', propertyRecords);
1639
1455
  if (propertyRecords.length === 0) {
@@ -1642,9 +1458,9 @@ class ModelProperty {
1642
1458
  const propertyRecord = propertyRecords[0];
1643
1459
  // Get model name
1644
1460
  const modelRecords = await db
1645
- .select({ name: modelsTable.name })
1646
- .from(modelsTable)
1647
- .where(eq(modelsTable.id, propertyRecord.modelId))
1461
+ .select({ name: main_cjs.models.name })
1462
+ .from(main_cjs.models)
1463
+ .where(drizzleOrm.eq(main_cjs.models.id, propertyRecord.modelId))
1648
1464
  .limit(1);
1649
1465
  if (modelRecords.length === 0) {
1650
1466
  return undefined;
@@ -1667,17 +1483,17 @@ class ModelProperty {
1667
1483
  // Get ref model name if applicable
1668
1484
  if (propertyRecord.refModelId) {
1669
1485
  const refModelRecords = await db
1670
- .select({ name: modelsTable.name })
1671
- .from(modelsTable)
1672
- .where(eq(modelsTable.id, propertyRecord.refModelId))
1486
+ .select({ name: main_cjs.models.name })
1487
+ .from(main_cjs.models)
1488
+ .where(drizzleOrm.eq(main_cjs.models.id, propertyRecord.refModelId))
1673
1489
  .limit(1);
1674
1490
  if (refModelRecords.length > 0) {
1675
1491
  propertyData.refModelName = refModelRecords[0].name;
1676
1492
  propertyData.ref = refModelRecords[0].name;
1677
1493
  }
1678
1494
  }
1679
- // Create ModelProperty instance
1680
- const instance = this.create(propertyData);
1495
+ // Create ModelProperty instance (sync for createById so we can send updateContext)
1496
+ const instance = this.create(propertyData, { waitForReady: false });
1681
1497
  // Set isEdited from database after creation
1682
1498
  if (isEditedFromDb) {
1683
1499
  instance._service.send({
@@ -1705,6 +1521,32 @@ class ModelProperty {
1705
1521
  readyTimeout,
1706
1522
  });
1707
1523
  }
1524
+ /**
1525
+ * Get all ModelProperty instances for a model.
1526
+ * Loads property rows from DB for the given modelFileId, creates instances via createById, optionally waits for idle.
1527
+ */
1528
+ static async all(modelFileId, options) {
1529
+ const { waitForReady = false, readyTimeout = 5000 } = options ?? {};
1530
+ if (!modelFileId) {
1531
+ return [];
1532
+ }
1533
+ const rows = await getModelPropertiesData(modelFileId);
1534
+ const instances = [];
1535
+ for (const row of rows) {
1536
+ if (row.schemaFileId) {
1537
+ const instance = await this.createById(row.schemaFileId);
1538
+ if (instance) {
1539
+ instances.push(instance);
1540
+ }
1541
+ }
1542
+ }
1543
+ if (waitForReady && instances.length > 0) {
1544
+ await Promise.all(instances.map((p) => main_cjs.waitForEntityIdle(p, {
1545
+ timeout: readyTimeout,
1546
+ })));
1547
+ }
1548
+ return instances;
1549
+ }
1708
1550
  /**
1709
1551
  * Track a pending write for a property
1710
1552
  */
@@ -1743,6 +1585,13 @@ class ModelProperty {
1743
1585
  .filter(([_, write]) => write.modelId === modelId && write.status !== 'error')
1744
1586
  .map(([propertyFileId]) => propertyFileId);
1745
1587
  }
1588
+ /**
1589
+ * Get modelId for a property that has a pending write (row may not be in DB yet).
1590
+ * Used to resolve modelName when validating a just-created property rename.
1591
+ */
1592
+ static getPendingModelId(propertyFileId) {
1593
+ return this.pendingWrites.get(propertyFileId)?.modelId;
1594
+ }
1746
1595
  getService() {
1747
1596
  return this._service;
1748
1597
  }
@@ -1849,6 +1698,60 @@ class ModelProperty {
1849
1698
  // Service might already be stopped
1850
1699
  }
1851
1700
  }
1701
+ /**
1702
+ * Destroy the model property: remove from caches, delete from database, update Schema context, stop service.
1703
+ */
1704
+ async destroy() {
1705
+ const context = this._getSnapshotContext();
1706
+ const cacheKey = context.modelName && context.name
1707
+ ? `${context.modelName}:${context.name}`
1708
+ : (context.id ?? '');
1709
+ if (!cacheKey)
1710
+ return;
1711
+ main_cjs.forceRemoveFromCaches(this, {
1712
+ getCacheKeys: () => [cacheKey],
1713
+ caches: [ModelProperty.instanceCache],
1714
+ });
1715
+ await main_cjs.runDestroyLifecycle(this, {
1716
+ getService: (instance) => instance._service,
1717
+ doDestroy: async () => {
1718
+ const db = main_cjs.BaseDb.getAppDb();
1719
+ const schemaName = context._schemaName;
1720
+ const modelName = context.modelName;
1721
+ const propertyName = context.name;
1722
+ if (!modelName || !propertyName)
1723
+ return;
1724
+ if (db && schemaName) {
1725
+ const propertyRecords = await db
1726
+ .select({ propertyId: main_cjs.properties.id })
1727
+ .from(main_cjs.properties)
1728
+ .innerJoin(main_cjs.models, drizzleOrm.eq(main_cjs.properties.modelId, main_cjs.models.id))
1729
+ .innerJoin(main_cjs.modelSchemas, drizzleOrm.eq(main_cjs.models.id, main_cjs.modelSchemas.modelId))
1730
+ .innerJoin(main_cjs.schemas, drizzleOrm.eq(main_cjs.modelSchemas.schemaId, main_cjs.schemas.id))
1731
+ .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.schemas.name, schemaName), drizzleOrm.eq(main_cjs.models.name, modelName), drizzleOrm.eq(main_cjs.properties.name, propertyName)))
1732
+ .limit(1);
1733
+ if (propertyRecords.length > 0 && propertyRecords[0].propertyId != null) {
1734
+ await db
1735
+ .delete(main_cjs.properties)
1736
+ .where(drizzleOrm.eq(main_cjs.properties.id, propertyRecords[0].propertyId));
1737
+ }
1738
+ }
1739
+ if (schemaName) {
1740
+ const schema = Schema.Schema.create(schemaName, { waitForReady: false });
1741
+ const snapshot = schema.getService().getSnapshot();
1742
+ const schemaContext = snapshot.context;
1743
+ if (schemaContext.models?.[modelName]?.properties?.[propertyName]) {
1744
+ const updatedModels = { ...schemaContext.models };
1745
+ const updatedProperties = { ...updatedModels[modelName].properties };
1746
+ delete updatedProperties[propertyName];
1747
+ updatedModels[modelName] = { ...updatedModels[modelName], properties: updatedProperties };
1748
+ schema.getService().send({ type: 'updateContext', models: updatedModels });
1749
+ schema.getService().send({ type: 'markAsDraft', propertyKey: `property:${modelName}:${propertyName}` });
1750
+ }
1751
+ }
1752
+ },
1753
+ });
1754
+ }
1852
1755
  }
1853
1756
  ModelProperty.instanceCache = new Map();
1854
1757
  // Pending writes tracking
@@ -1860,7 +1763,4 @@ var ModelProperty$1 = /*#__PURE__*/Object.freeze({
1860
1763
  });
1861
1764
 
1862
1765
  exports.ModelProperty = ModelProperty;
1863
- exports.ModelProperty$1 = ModelProperty$1;
1864
- exports.convertPropertyToSchemaUpdate = convertPropertyToSchemaUpdate;
1865
- exports.updateModelProperties = updateModelProperties;
1866
- //# sourceMappingURL=ModelProperty-MkN5Rmx7.js.map
1766
+ //# sourceMappingURL=ModelProperty-BeJvgKMw.js.map