@seedprotocol/sdk 0.4.4 → 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 (100) hide show
  1. package/README.md +38 -348
  2. package/dist/{ArweaveClient-DkNLWiSZ.js → ArweaveClient-CgWK-JgT.js} +8 -8
  3. package/dist/{ArweaveClient-DkNLWiSZ.js.map → ArweaveClient-CgWK-JgT.js.map} +1 -1
  4. package/dist/{ArweaveClient-CczHvccG.js → ArweaveClient-WcG8CZAE.js} +8 -8
  5. package/dist/{ArweaveClient-CczHvccG.js.map → ArweaveClient-WcG8CZAE.js.map} +1 -1
  6. package/dist/{Db-DJvjXVlp.js → Db-DjFdIdR9.js} +9 -9
  7. package/dist/{Db-DJvjXVlp.js.map → Db-DjFdIdR9.js.map} +1 -1
  8. package/dist/{Db-BzQR2KX9.js → Db-DjofXdeU.js} +9 -9
  9. package/dist/{Db-BzQR2KX9.js.map → Db-DjofXdeU.js.map} +1 -1
  10. package/dist/{EasClient-CHQYmjj2.js → EasClient-Aojewp6P.js} +8 -8
  11. package/dist/{EasClient-CodrIgW-.js.map → EasClient-Aojewp6P.js.map} +1 -1
  12. package/dist/{EasClient-CodrIgW-.js → EasClient-BVFXp2O6.js} +8 -8
  13. package/dist/{EasClient-CHQYmjj2.js.map → EasClient-BVFXp2O6.js.map} +1 -1
  14. package/dist/{FileManager-BbvkZJCH.js → FileManager-C9zr4AJe.js} +8 -8
  15. package/dist/{FileManager-BbvkZJCH.js.map → FileManager-C9zr4AJe.js.map} +1 -1
  16. package/dist/{FileManager-BIVsDnMu.js → FileManager-CxGJLw5C.js} +8 -8
  17. package/dist/{FileManager-BIVsDnMu.js.map → FileManager-CxGJLw5C.js.map} +1 -1
  18. package/dist/Item/Item.d.ts.map +1 -1
  19. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  20. package/dist/Model/Model.d.ts.map +1 -1
  21. package/dist/ModelProperty/ModelProperty.d.ts.map +1 -1
  22. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  23. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  24. package/dist/{ModelProperty-gjcA83Mq.js → ModelProperty-CGdkocQ8.js} +31 -766
  25. package/dist/ModelProperty-CGdkocQ8.js.map +1 -0
  26. package/dist/{PathResolver-kGzba-zC.js → PathResolver-CX6GHoTS.js} +8 -8
  27. package/dist/{PathResolver-kGzba-zC.js.map → PathResolver-CX6GHoTS.js.map} +1 -1
  28. package/dist/{PathResolver-9zAzPhee.js → PathResolver-z_WX47_o.js} +8 -8
  29. package/dist/{PathResolver-9zAzPhee.js.map → PathResolver-z_WX47_o.js.map} +1 -1
  30. package/dist/{QueryClient-C7ZkTT0z.js → QueryClient-ByKPdRmE.js} +8 -8
  31. package/dist/{QueryClient-C7ZkTT0z.js.map → QueryClient-ByKPdRmE.js.map} +1 -1
  32. package/dist/{QueryClient-CEtsek7Q.js → QueryClient-Cb1iJO-x.js} +8 -8
  33. package/dist/{QueryClient-CEtsek7Q.js.map → QueryClient-Cb1iJO-x.js.map} +1 -1
  34. package/dist/Schema/Schema.d.ts.map +1 -1
  35. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  36. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  37. package/dist/{Schema-ClTcpgbt.js → Schema-D1eqDHyt.js} +758 -60
  38. package/dist/Schema-D1eqDHyt.js.map +1 -0
  39. package/dist/{SchemaValidationService-BfoEiHNr.js → SchemaValidationService-DyttFaV_.js} +7 -7
  40. package/dist/{SchemaValidationService-BfoEiHNr.js.map → SchemaValidationService-DyttFaV_.js.map} +1 -1
  41. package/dist/cjs/{ModelProperty-BRKRREYP.js → ModelProperty-BeJvgKMw.js} +62 -436
  42. package/dist/cjs/ModelProperty-BeJvgKMw.js.map +1 -0
  43. package/dist/cjs/{Schema-CV9hMg8m.js → Schema-CVs9J6eP.js} +426 -91
  44. package/dist/cjs/Schema-CVs9J6eP.js.map +1 -0
  45. package/dist/cjs/{SchemaValidationService-DUtQUerg.js → SchemaValidationService-CDKcVRFQ.js} +3 -3
  46. package/dist/cjs/{SchemaValidationService-DUtQUerg.js.map → SchemaValidationService-CDKcVRFQ.js.map} +1 -1
  47. package/dist/cjs/{getItem-BThT-UOt.js → getItem-B5RYPvrG.js} +3 -3
  48. package/dist/cjs/{getItem-BThT-UOt.js.map → getItem-B5RYPvrG.js.map} +1 -1
  49. package/dist/cjs/{getPublishPayload-CKZ7rVbU.js → getPublishPayload-BD1qRob1.js} +6 -6
  50. package/dist/cjs/getPublishPayload-BD1qRob1.js.map +1 -0
  51. package/dist/cjs/{getPublishUploads-CuGIvV-Q.js → getPublishUploads-CnC9aYxs.js} +4 -4
  52. package/dist/cjs/{getPublishUploads-CuGIvV-Q.js.map → getPublishUploads-CnC9aYxs.js.map} +1 -1
  53. package/dist/cjs/{getSegmentedItemProperties-BCJXJlTR.js → getSegmentedItemProperties-B_njnntx.js} +2 -2
  54. package/dist/cjs/{getSegmentedItemProperties-BCJXJlTR.js.map → getSegmentedItemProperties-B_njnntx.js.map} +1 -1
  55. package/dist/cjs/{index-C3j3m34a.js → index-BeKPbbk0.js} +11466 -11546
  56. package/dist/cjs/index-BeKPbbk0.js.map +1 -0
  57. package/dist/cjs/{index-CbTBDqTJ.js → index-Dnywap_P.js} +3 -3
  58. package/dist/cjs/index-Dnywap_P.js.map +1 -0
  59. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  60. package/dist/client/actors/saveAppState.d.ts.map +1 -1
  61. package/dist/eas.d.ts.map +1 -1
  62. package/dist/{getItem-BWPo8wd0.js → getItem-BB5HBCbK.js} +8 -8
  63. package/dist/{getItem-BWPo8wd0.js.map → getItem-BB5HBCbK.js.map} +1 -1
  64. package/dist/{getPublishPayload-Caw2laZM.js → getPublishPayload-uLm0AqN_.js} +10 -10
  65. package/dist/getPublishPayload-uLm0AqN_.js.map +1 -0
  66. package/dist/{getPublishUploads-MlyBuoXh.js → getPublishUploads-Dc-HqhO8.js} +9 -9
  67. package/dist/{getPublishUploads-MlyBuoXh.js.map → getPublishUploads-Dc-HqhO8.js.map} +1 -1
  68. package/dist/{getSegmentedItemProperties-COLLdDo4.js → getSegmentedItemProperties-BrIqFNfD.js} +2 -2
  69. package/dist/{getSegmentedItemProperties-COLLdDo4.js.map → getSegmentedItemProperties-BrIqFNfD.js.map} +1 -1
  70. package/dist/helpers/schema.d.ts.map +1 -1
  71. package/dist/helpers/updateSchema.d.ts.map +1 -1
  72. package/dist/imports/json.d.ts.map +1 -1
  73. package/dist/{index-D2OGsG4v.js → index-2FcQHgKp.js} +2 -2
  74. package/dist/index-2FcQHgKp.js.map +1 -0
  75. package/dist/{ClientManager-DoHUt8tU.js → index-DPll6EAp.js} +11460 -11538
  76. package/dist/index-DPll6EAp.js.map +1 -0
  77. package/dist/{index-B9i_mXXp.js → index-LEY0Og1p.js} +9 -9
  78. package/dist/index-LEY0Og1p.js.map +1 -0
  79. package/dist/main.cjs +2 -2
  80. package/dist/main.js +13 -13
  81. package/dist/main.js.map +1 -1
  82. package/dist/node.js +15 -15
  83. package/dist/{property-fK7tSUDX.js → property-B15X7jLX.js} +4 -4
  84. package/dist/property-B15X7jLX.js.map +1 -0
  85. package/dist/{queries-DGOk16cd.js → queries-BPDSpiEX.js} +2 -2
  86. package/dist/{queries-DGOk16cd.js.map → queries-BPDSpiEX.js.map} +1 -1
  87. package/dist/services/write/actors/writeToDatabase.d.ts.map +1 -1
  88. package/package.json +6 -2
  89. package/dist/ClientManager-DoHUt8tU.js.map +0 -1
  90. package/dist/ModelProperty-gjcA83Mq.js.map +0 -1
  91. package/dist/Schema-ClTcpgbt.js.map +0 -1
  92. package/dist/cjs/ModelProperty-BRKRREYP.js.map +0 -1
  93. package/dist/cjs/Schema-CV9hMg8m.js.map +0 -1
  94. package/dist/cjs/getPublishPayload-CKZ7rVbU.js.map +0 -1
  95. package/dist/cjs/index-C3j3m34a.js.map +0 -1
  96. package/dist/cjs/index-CbTBDqTJ.js.map +0 -1
  97. package/dist/getPublishPayload-Caw2laZM.js.map +0 -1
  98. package/dist/index-B9i_mXXp.js.map +0 -1
  99. package/dist/index-D2OGsG4v.js.map +0 -1
  100. package/dist/property-fK7tSUDX.js.map +0 -1
@@ -1,22 +1,737 @@
1
1
  import { fromCallback, setup, assign, createActor } from 'xstate';
2
- import { aG as SEED_PROTOCOL_SCHEMA_NAME, p as BaseDb, W as schemas, aH as addSchemaToDb, ag as generateId, ae as createModelsFromJson, a2 as addModelsToDb, q as models, G as modelSchemas, r as properties, aE as listCompleteSchemaFiles, s as BaseFileManager, aI as loadModelsFromDbForSchema, ad as getLatestSchemaVersion, aJ as isInternalSchema, aK as createModelFromJson, M as Model, af as writeProcessMachine, ah as waitForEntityIdle, ai as createReactiveProxy, aj as findEntity, aq as loadAllSchemasFromDb, aL as ConflictError, aM as unloadEntity, aN as clearDestroySubscriptions, ak as forceRemoveFromCaches, al as runDestroyLifecycle, aO as setupEntityLiveQuery } from './ClientManager-DoHUt8tU.js';
2
+ import { a as ModelPropertyDataTypes, aG as getLatestSchemaVersion, x as BaseFileManager, p as BaseDb, q as models, W as schemas, ae as generateId, aH as createModelsFromJson, aa as loadSchemaFromFile, aI as SEED_PROTOCOL_SCHEMA_NAME, aJ as addSchemaToDb, a2 as addModelsToDb, G as modelSchemas, r as properties, aE as listCompleteSchemaFiles, aK as loadModelsFromDbForSchema, aL as isInternalSchema, aM as createModelFromJson, M as Model, ad as writeProcessMachine, af as waitForEntityIdle, ag as createReactiveProxy, ah as findEntity, aq as loadAllSchemasFromDb, aN as ConflictError, am as getClient, an as ClientManagerState, aO as unloadEntity, aP as clearDestroySubscriptions, ai as forceRemoveFromCaches, aj as runDestroyLifecycle, aQ as setupEntityLiveQuery } from './index-DPll6EAp.js';
3
3
  import { eq, desc, and } from 'drizzle-orm';
4
4
  import debug from 'debug';
5
- import { SchemaValidationService } from './SchemaValidationService-BfoEiHNr.js';
6
- import { M as ModelProperty, c as convertPropertyToSchemaUpdate, w as writeFullSchemaNewVersion, u as updateModelProperties } from './ModelProperty-gjcA83Mq.js';
5
+ import { SchemaValidationService } from './SchemaValidationService-DyttFaV_.js';
7
6
  import 'pluralize';
8
- import 'rxjs';
9
- import 'lodash-es';
10
- import 'drizzle-orm/casing';
11
- import '@sinclair/typebox';
12
- import 'arweave';
13
- import 'eventemitter3';
14
- import 'drizzle-orm/sqlite-core';
15
- import 'nanoid';
16
- import 'nanoid-dictionary';
17
- import 'ethers';
18
- import '@sinclair/typebox/value';
19
- import 'reflect-metadata';
7
+
8
+ const logger$d = debug('seedSdk:helpers:updateSchema');
9
+ /**
10
+ * Get the file path for a schema file
11
+ */
12
+ /**
13
+ * Sanitize a schema name to be filesystem-safe
14
+ * Replaces all special characters (except alphanumeric, hyphens, underscores) with underscores
15
+ * Converts spaces to underscores
16
+ * Removes leading/trailing underscores
17
+ *
18
+ * @param name - Schema name to sanitize
19
+ * @returns Sanitized name safe for use in filenames
20
+ */
21
+ const sanitizeSchemaName$1 = (name) => {
22
+ return name
23
+ .replace(/[^a-zA-Z0-9\s_-]/g, '_') // Replace special chars (except spaces, hyphens, underscores) with underscore
24
+ .replace(/\s+/g, '_') // Convert spaces to underscores
25
+ .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores
26
+ .replace(/_+/g, '_'); // Collapse multiple underscores to single
27
+ };
28
+ /**
29
+ * Get the full file path for a schema
30
+ * Format: {schemaFileId}_{schemaName}_v{version}.json
31
+ *
32
+ * The ID-first format ensures all files for a schema group together when sorted alphabetically.
33
+ *
34
+ * @param name - Schema name
35
+ * @param version - Schema version
36
+ * @param schemaFileId - Schema file ID (required)
37
+ */
38
+ const getSchemaFilePath$2 = (name, version, schemaFileId) => {
39
+ const path = BaseFileManager.getPathModule();
40
+ const workingDir = BaseFileManager.getWorkingDir();
41
+ const sanitizedName = sanitizeSchemaName$1(name);
42
+ const filename = schemaFileId
43
+ ? `${schemaFileId}_${sanitizedName}_v${version}.json`
44
+ : `${sanitizedName}_v${version}.json`;
45
+ return path.join(workingDir, filename);
46
+ };
47
+ /**
48
+ * Get schemaFileId from database for a schema
49
+ * @param schemaName - Schema name
50
+ * @returns Schema file ID
51
+ * @throws Error if schema not found or missing schemaFileId
52
+ */
53
+ async function getSchemaFileId(schemaName) {
54
+ const db = BaseDb.getAppDb();
55
+ if (!db)
56
+ throw new Error('Database not available');
57
+ const dbSchema = await db
58
+ .select()
59
+ .from(schemas)
60
+ .where(eq(schemas.name, schemaName))
61
+ .orderBy(desc(schemas.version))
62
+ .limit(1);
63
+ if (dbSchema.length === 0 || !dbSchema[0].schemaFileId) {
64
+ throw new Error(`Schema ${schemaName} not found in database or missing schemaFileId`);
65
+ }
66
+ return dbSchema[0].schemaFileId;
67
+ }
68
+ /**
69
+ * Write the full schema to a new version file (e.g. when new models were added).
70
+ * Used when _editedProperties contains 'schema:models' and there are no property-level updates.
71
+ * @param schemaName - Schema name
72
+ * @param schema - Full schema object (e.g. from _buildModelsFromInstances)
73
+ * @returns The file path of the new schema version
74
+ */
75
+ async function writeFullSchemaNewVersion(schemaName, schema) {
76
+ const latestVersion = await getLatestSchemaVersion(schemaName);
77
+ const newVersion = latestVersion + 1;
78
+ const schemaWithNewVersion = {
79
+ ...schema,
80
+ version: newVersion,
81
+ metadata: {
82
+ ...schema.metadata,
83
+ updatedAt: new Date().toISOString(),
84
+ },
85
+ migrations: [
86
+ ...(schema.migrations || []),
87
+ {
88
+ version: newVersion,
89
+ timestamp: new Date().toISOString(),
90
+ description: 'New schema version (e.g. new models added)',
91
+ changes: [{ type: 'full_schema_write' }],
92
+ },
93
+ ],
94
+ };
95
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, schema.id ?? (await getSchemaFileId(schemaName)));
96
+ const newContent = JSON.stringify(schemaWithNewVersion, null, 2);
97
+ await BaseFileManager.saveFile(newFilePath, newContent);
98
+ await BaseFileManager.waitForFileWithContent(newFilePath);
99
+ logger$d(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
100
+ return newFilePath;
101
+ }
102
+ /**
103
+ * Get model name from modelId
104
+ * @param modelId - The model ID to look up
105
+ * @returns The model name, or undefined if not found
106
+ */
107
+ async function getModelNameFromId(modelId) {
108
+ if (!modelId) {
109
+ return undefined;
110
+ }
111
+ const db = BaseDb.getAppDb();
112
+ if (!db) {
113
+ throw new Error('Database not found');
114
+ }
115
+ const modelRecords = await db
116
+ .select()
117
+ .from(models)
118
+ .where(eq(models.id, modelId))
119
+ .limit(1);
120
+ if (modelRecords.length === 0) {
121
+ return undefined;
122
+ }
123
+ return modelRecords[0].name;
124
+ }
125
+ /**
126
+ * Convert a TProperty/ModelPropertyMachineContext to SchemaPropertyUpdate format
127
+ * This function converts the internal property representation to the schema file format
128
+ * @param property - The TProperty instance to convert
129
+ * @param modelName - The name of the model this property belongs to
130
+ * @param propertyName - The name of the property
131
+ * @returns A SchemaPropertyUpdate object ready to be passed to updateModelProperties
132
+ */
133
+ async function convertPropertyToSchemaUpdate(property, modelName, propertyName) {
134
+ const updates = {};
135
+ // Convert dataType to type
136
+ if (property.dataType) {
137
+ updates.type = property.dataType;
138
+ }
139
+ // Handle Relation type
140
+ if (property.dataType === ModelPropertyDataTypes.Relation) {
141
+ if (property.ref) {
142
+ updates.model = property.ref;
143
+ }
144
+ else if (property.refModelId) {
145
+ // If ref is not set but refModelId is, get the model name from the database
146
+ const refModelName = await getModelNameFromId(property.refModelId);
147
+ if (refModelName) {
148
+ updates.model = refModelName;
149
+ }
150
+ }
151
+ }
152
+ // Handle List type
153
+ if (property.dataType === ModelPropertyDataTypes.List) {
154
+ if (property.refValueType) {
155
+ updates.items = {
156
+ type: property.refValueType,
157
+ };
158
+ if (property.ref) {
159
+ updates.items.model = property.ref;
160
+ }
161
+ else if (property.refModelId) {
162
+ // If ref is not set but refModelId is, get the model name from the database
163
+ const refModelName = await getModelNameFromId(property.refModelId);
164
+ if (refModelName) {
165
+ updates.items.model = refModelName;
166
+ }
167
+ }
168
+ }
169
+ }
170
+ // Handle storage configuration (for Text properties with storage)
171
+ if (property.storageType || property.localStorageDir || property.filenameSuffix) {
172
+ const storageType = property.storageType || 'ItemStorage'; // Default to ItemStorage if not specified
173
+ updates.storage = {
174
+ type: storageType,
175
+ };
176
+ if (property.localStorageDir) {
177
+ updates.storage.path = property.localStorageDir;
178
+ }
179
+ if (property.filenameSuffix) {
180
+ updates.storage.extension = property.filenameSuffix;
181
+ }
182
+ }
183
+ return {
184
+ modelName,
185
+ propertyName,
186
+ updates,
187
+ };
188
+ }
189
+ /**
190
+ * Update model properties in a schema and create a new version
191
+ * @param schemaName - The name of the schema to update
192
+ * @param propertyUpdates - Array of property updates to apply
193
+ * @param modelUpdates - Optional array of model renames
194
+ * @returns The file path of the new schema version
195
+ * @throws Error if schema not found or updates are invalid
196
+ */
197
+ async function updateModelProperties(schemaName, propertyUpdates, modelUpdates) {
198
+ // Get the latest version of the schema
199
+ const latestVersion = await getLatestSchemaVersion(schemaName);
200
+ if (latestVersion === 0) {
201
+ throw new Error(`Schema ${schemaName} not found`);
202
+ }
203
+ // Get schemaFileId from database
204
+ const schemaFileId = await getSchemaFileId(schemaName);
205
+ // Load the latest schema file
206
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
207
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
208
+ const schemaFile = JSON.parse(content);
209
+ if (!schemaFile.$schema) {
210
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
211
+ }
212
+ // Create a copy of the schema for the new version
213
+ // Preserve schema ID and all model/property IDs
214
+ const newVersion = latestVersion + 1;
215
+ const updatedSchema = {
216
+ ...schemaFile,
217
+ version: newVersion,
218
+ // Preserve schema ID from previous version
219
+ id: schemaFile.id,
220
+ metadata: {
221
+ ...schemaFile.metadata,
222
+ updatedAt: new Date().toISOString(),
223
+ },
224
+ // Deep copy models to preserve IDs
225
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
226
+ modelName,
227
+ {
228
+ ...model,
229
+ // Preserve model ID
230
+ id: model.id,
231
+ // Deep copy properties to preserve IDs
232
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
233
+ propName,
234
+ {
235
+ ...prop,
236
+ // Preserve property ID
237
+ id: prop.id,
238
+ },
239
+ ])),
240
+ },
241
+ ])),
242
+ migrations: [
243
+ ...schemaFile.migrations,
244
+ {
245
+ version: newVersion,
246
+ timestamp: new Date().toISOString(),
247
+ description: `Updated model properties: ${propertyUpdates.map(u => `${u.modelName}.${u.propertyName}`).join(', ')}`,
248
+ changes: propertyUpdates.map(update => ({
249
+ type: 'property_update',
250
+ modelName: update.modelName,
251
+ propertyName: update.propertyName,
252
+ updates: update.updates,
253
+ })),
254
+ },
255
+ ],
256
+ };
257
+ // Apply model renames first (if any)
258
+ if (modelUpdates && modelUpdates.length > 0) {
259
+ for (const modelUpdate of modelUpdates) {
260
+ if (updatedSchema.models[modelUpdate.oldName]) {
261
+ // Rename the model in the models object
262
+ updatedSchema.models[modelUpdate.newName] = updatedSchema.models[modelUpdate.oldName];
263
+ delete updatedSchema.models[modelUpdate.oldName];
264
+ // Update any property references to this model
265
+ for (const modelName in updatedSchema.models) {
266
+ const model = updatedSchema.models[modelName];
267
+ for (const propertyName in model.properties) {
268
+ const property = model.properties[propertyName];
269
+ if (property.model === modelUpdate.oldName) {
270
+ property.model = modelUpdate.newName;
271
+ }
272
+ if (property.items?.model === modelUpdate.oldName) {
273
+ property.items.model = modelUpdate.newName;
274
+ }
275
+ }
276
+ }
277
+ // Add to migration changes
278
+ updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
279
+ type: 'model_rename',
280
+ oldName: modelUpdate.oldName,
281
+ newName: modelUpdate.newName,
282
+ });
283
+ }
284
+ }
285
+ }
286
+ // Apply property updates
287
+ for (const update of propertyUpdates) {
288
+ const model = updatedSchema.models[update.modelName];
289
+ if (!model) {
290
+ throw new Error(`Model ${update.modelName} not found in schema ${schemaName}`);
291
+ }
292
+ if (!model.properties[update.propertyName]) {
293
+ throw new Error(`Property ${update.propertyName} not found in model ${update.modelName} of schema ${schemaName}`);
294
+ }
295
+ // Update the property with new values
296
+ const property = model.properties[update.propertyName];
297
+ Object.assign(property, update.updates);
298
+ }
299
+ // Write the new schema version to file using ID-based naming (preferred)
300
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
301
+ const newContent = JSON.stringify(updatedSchema, null, 2);
302
+ await BaseFileManager.saveFile(newFilePath, newContent);
303
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
304
+ await BaseFileManager.waitForFileWithContent(newFilePath);
305
+ logger$d(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
306
+ // Load the new schema file to process models and add them to the database
307
+ // Extract model renames from migrations to pass to database update
308
+ const modelRenames = new Map();
309
+ const latestMigration = updatedSchema.migrations[updatedSchema.migrations.length - 1];
310
+ for (const change of latestMigration.changes) {
311
+ if (change.type === 'model_rename') {
312
+ modelRenames.set(change.oldName, change.newName);
313
+ }
314
+ }
315
+ // Load schema with model renames handled
316
+ await loadSchemaWithRenames(newFilePath, modelRenames);
317
+ return newFilePath;
318
+ }
319
+ /**
320
+ * Load a schema file and handle model renames in the database
321
+ * This is a helper function that processes model renames before loading
322
+ */
323
+ async function loadSchemaWithRenames(schemaFilePath, modelRenames) {
324
+ const content = await BaseFileManager.readFileAsString(schemaFilePath);
325
+ const schemaFile = JSON.parse(content);
326
+ if (!schemaFile.$schema) {
327
+ throw new Error(`File ${schemaFilePath} is not a complete schema file (missing $schema field).`);
328
+ }
329
+ const schemaName = schemaFile.metadata?.name;
330
+ const version = schemaFile.version;
331
+ if (!schemaName) {
332
+ throw new Error('Schema name is required in metadata.name');
333
+ }
334
+ // Convert to JsonImportSchema format for processing
335
+ // Remove id fields for JsonImportSchema format (they're not part of the import format)
336
+ const importData = {
337
+ name: schemaName,
338
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
339
+ modelName,
340
+ {
341
+ description: model.description,
342
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
343
+ propName,
344
+ {
345
+ type: prop.type || 'string', // Ensure type is present
346
+ ...prop,
347
+ // Remove id field for import format (not part of JsonImportSchema)
348
+ },
349
+ ])),
350
+ indexes: model.indexes,
351
+ },
352
+ ])),
353
+ };
354
+ // Generate schema ID if missing
355
+ if (!schemaFile.id) {
356
+ schemaFile.id = generateId();
357
+ logger$d('Generated schema ID for schema:', schemaFile.id);
358
+ }
359
+ // Extract schemaFileIds from JSON file and generate missing ones BEFORE creating models
360
+ // This ensures Model instances are created with correct IDs
361
+ const modelFileIds = new Map();
362
+ const propertyFileIds = new Map();
363
+ for (const [modelName, model] of Object.entries(schemaFile.models)) {
364
+ // Generate model ID if missing
365
+ if (!model.id) {
366
+ model.id = generateId();
367
+ logger$d(`Generated model ID for ${modelName}:`, model.id);
368
+ }
369
+ modelFileIds.set(modelName, model.id);
370
+ const propIds = new Map();
371
+ for (const [propName, prop] of Object.entries(model.properties)) {
372
+ // Generate property ID if missing
373
+ if (!prop.id) {
374
+ prop.id = generateId();
375
+ logger$d(`Generated property ID for ${modelName}.${propName}:`, prop.id);
376
+ }
377
+ propIds.set(propName, prop.id);
378
+ }
379
+ if (propIds.size > 0) {
380
+ propertyFileIds.set(modelName, propIds);
381
+ }
382
+ }
383
+ // Convert JSON models to Model classes, passing modelFileIds and propertyFileIds so Model instances use correct IDs
384
+ const modelDefinitions = await createModelsFromJson(importData, modelFileIds, propertyFileIds);
385
+ // Convert schema file metadata to schema input for database
386
+ const schemaInput = {
387
+ name: schemaName,
388
+ version,
389
+ schemaFileId: schemaFile.id || null,
390
+ schemaData: null,
391
+ isDraft: false,
392
+ isEdited: false,
393
+ createdAt: new Date(schemaFile.metadata.createdAt).getTime(),
394
+ updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
395
+ };
396
+ // Use dynamic import to break circular dependency
397
+ const { addSchemaToDb, addModelsToDb } = await import('./index-DPll6EAp.js').then(function (n) { return n.aT; });
398
+ // Add schema to database with schemaFileId
399
+ const schemaRecord = await addSchemaToDb(schemaInput, schemaFile.id);
400
+ // Add models to database with model renames handled and schemaFileIds
401
+ await addModelsToDb(modelDefinitions, schemaRecord, modelRenames, {
402
+ schemaFileId: schemaFile.id,
403
+ modelFileIds,
404
+ propertyFileIds,
405
+ });
406
+ // Models are now Model instances, no registration needed
407
+ // They should be created via Model.create() and are accessible via Model static methods
408
+ for (const [modelName] of Object.entries(modelDefinitions)) {
409
+ logger$d('loadSchemaWithRenames - model available:', modelName);
410
+ }
411
+ return schemaFilePath;
412
+ }
413
+ /**
414
+ * Rename a property in a model
415
+ * This is a convenience function that updates the property name
416
+ * Note: This creates a new property and you may want to handle the old property separately
417
+ * @param schemaName - The name of the schema
418
+ * @param modelName - The name of the model
419
+ * @param oldPropertyName - The current property name
420
+ * @param newPropertyName - The new property name
421
+ * @returns The file path of the new schema version
422
+ */
423
+ async function renameModelProperty(schemaName, modelName, oldPropertyName, newPropertyName) {
424
+ // Get the latest version
425
+ const latestVersion = await getLatestSchemaVersion(schemaName);
426
+ if (latestVersion === 0) {
427
+ throw new Error(`Schema ${schemaName} not found`);
428
+ }
429
+ // Get schemaFileId from database
430
+ const schemaFileId = await getSchemaFileId(schemaName);
431
+ // Load the latest schema file
432
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
433
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
434
+ const schemaFile = JSON.parse(content);
435
+ if (!schemaFile.$schema) {
436
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
437
+ }
438
+ const model = schemaFile.models[modelName];
439
+ if (!model) {
440
+ throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
441
+ }
442
+ if (!model.properties[oldPropertyName]) {
443
+ throw new Error(`Property ${oldPropertyName} not found in model ${modelName} of schema ${schemaName}`);
444
+ }
445
+ if (model.properties[newPropertyName]) {
446
+ throw new Error(`Property ${newPropertyName} already exists in model ${modelName} of schema ${schemaName}`);
447
+ }
448
+ // Create new version with renamed property
449
+ // Preserve all IDs - when renaming, we keep the same property ID
450
+ const newVersion = latestVersion + 1;
451
+ const oldProperty = model.properties[oldPropertyName];
452
+ const updatedSchema = {
453
+ ...schemaFile,
454
+ version: newVersion,
455
+ id: schemaFile.id, // Preserve schema ID
456
+ metadata: {
457
+ ...schemaFile.metadata,
458
+ updatedAt: new Date().toISOString(),
459
+ },
460
+ models: {
461
+ ...schemaFile.models,
462
+ [modelName]: {
463
+ ...model,
464
+ id: model.id, // Preserve model ID
465
+ properties: {
466
+ ...Object.fromEntries(Object.entries(model.properties)
467
+ .filter(([name]) => name !== oldPropertyName)
468
+ .map(([name, prop]) => [name, { ...prop, id: prop.id }])),
469
+ [newPropertyName]: {
470
+ ...oldProperty,
471
+ id: oldProperty.id, // Preserve property ID when renaming
472
+ },
473
+ },
474
+ },
475
+ },
476
+ migrations: [
477
+ ...schemaFile.migrations,
478
+ {
479
+ version: newVersion,
480
+ timestamp: new Date().toISOString(),
481
+ description: `Renamed property ${modelName}.${oldPropertyName} to ${newPropertyName}`,
482
+ changes: [
483
+ {
484
+ type: 'property_rename',
485
+ modelName,
486
+ oldPropertyName,
487
+ newPropertyName,
488
+ },
489
+ ],
490
+ },
491
+ ],
492
+ };
493
+ // Remove the old property name
494
+ delete updatedSchema.models[modelName].properties[oldPropertyName];
495
+ // Write the new schema version using ID-based naming (preferred)
496
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
497
+ const newContent = JSON.stringify(updatedSchema, null, 2);
498
+ // Ensure the directory exists before saving
499
+ const path = BaseFileManager.getPathModule();
500
+ const dir = path.dirname(newFilePath);
501
+ await BaseFileManager.createDirIfNotExists(dir);
502
+ await BaseFileManager.saveFile(newFilePath, newContent);
503
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
504
+ await BaseFileManager.waitForFileWithContent(newFilePath);
505
+ logger$d(`Renamed property ${oldPropertyName} to ${newPropertyName} in schema ${schemaName} v${newVersion}`);
506
+ // Load the new schema file
507
+ await loadSchemaFromFile(newFilePath);
508
+ return newFilePath;
509
+ }
510
+ /**
511
+ * Delete a model from a schema
512
+ * @param schemaName - The name of the schema
513
+ * @param modelName - The name of the model to delete
514
+ * @param options - Optional deletion options
515
+ * @returns The file path of the new schema version
516
+ * @throws Error if schema or model not found
517
+ */
518
+ async function deleteModelFromSchema(schemaName, modelName, options = {}) {
519
+ const { removeReferencingProperties = false } = options;
520
+ // Get the latest version
521
+ const latestVersion = await getLatestSchemaVersion(schemaName);
522
+ if (latestVersion === 0) {
523
+ throw new Error(`Schema ${schemaName} not found`);
524
+ }
525
+ // Get schemaFileId from database
526
+ const schemaFileId = await getSchemaFileId(schemaName);
527
+ // Load the latest schema file
528
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
529
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
530
+ const schemaFile = JSON.parse(content);
531
+ if (!schemaFile.$schema) {
532
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
533
+ }
534
+ if (!schemaFile.models[modelName]) {
535
+ throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
536
+ }
537
+ // Create new version without the model
538
+ // Preserve IDs for remaining models and properties
539
+ const newVersion = latestVersion + 1;
540
+ const updatedSchema = {
541
+ ...schemaFile,
542
+ version: newVersion,
543
+ id: schemaFile.id, // Preserve schema ID
544
+ metadata: {
545
+ ...schemaFile.metadata,
546
+ updatedAt: new Date().toISOString(),
547
+ },
548
+ // Preserve IDs for remaining models and their properties
549
+ models: Object.fromEntries(Object.entries(schemaFile.models)
550
+ .filter(([name]) => name !== modelName)
551
+ .map(([name, model]) => [
552
+ name,
553
+ {
554
+ ...model,
555
+ id: model.id, // Preserve model ID
556
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
557
+ propName,
558
+ { ...prop, id: prop.id }, // Preserve property ID
559
+ ])),
560
+ },
561
+ ])),
562
+ migrations: [
563
+ ...schemaFile.migrations,
564
+ {
565
+ version: newVersion,
566
+ timestamp: new Date().toISOString(),
567
+ description: `Deleted model ${modelName} from schema`,
568
+ changes: [
569
+ {
570
+ type: 'model_delete',
571
+ modelName,
572
+ removeReferencingProperties,
573
+ },
574
+ ],
575
+ },
576
+ ],
577
+ };
578
+ // Remove the model
579
+ delete updatedSchema.models[modelName];
580
+ // Handle properties that reference this model
581
+ const propertiesToRemove = [];
582
+ for (const [otherModelName, model] of Object.entries(updatedSchema.models)) {
583
+ for (const [propertyName, property] of Object.entries(model.properties)) {
584
+ // Check if property references the deleted model
585
+ if (property.model === modelName || property.items?.model === modelName) {
586
+ if (removeReferencingProperties) {
587
+ // Mark for removal
588
+ propertiesToRemove.push({ modelName: otherModelName, propertyName });
589
+ }
590
+ else {
591
+ // Remove the reference (set to null or remove model field)
592
+ if (property.model === modelName) {
593
+ delete property.model;
594
+ }
595
+ if (property.items?.model === modelName) {
596
+ delete property.items.model;
597
+ // If items only had model, we might want to remove items entirely
598
+ // But for now, just remove the model reference
599
+ }
600
+ }
601
+ }
602
+ }
603
+ }
604
+ // Remove properties if requested
605
+ if (removeReferencingProperties) {
606
+ for (const { modelName: mName, propertyName } of propertiesToRemove) {
607
+ delete updatedSchema.models[mName].properties[propertyName];
608
+ updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
609
+ type: 'property_delete',
610
+ modelName: mName,
611
+ propertyName,
612
+ reason: `Referenced deleted model ${modelName}`,
613
+ });
614
+ }
615
+ }
616
+ else {
617
+ // Update migration to note which properties were updated
618
+ const updatedProperties = [];
619
+ for (const [otherModelName, model] of Object.entries(updatedSchema.models)) {
620
+ for (const [propertyName, property] of Object.entries(model.properties)) {
621
+ if (property.model === modelName || property.items?.model === modelName) {
622
+ updatedProperties.push({ modelName: otherModelName, propertyName });
623
+ }
624
+ }
625
+ }
626
+ if (updatedProperties.length > 0) {
627
+ updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
628
+ type: 'properties_updated',
629
+ properties: updatedProperties,
630
+ reason: `Removed references to deleted model ${modelName}`,
631
+ });
632
+ }
633
+ }
634
+ // Write the new schema version using ID-based naming (preferred)
635
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
636
+ const newContent = JSON.stringify(updatedSchema, null, 2);
637
+ // Ensure the directory exists before saving
638
+ const path = BaseFileManager.getPathModule();
639
+ const dir = path.dirname(newFilePath);
640
+ await BaseFileManager.createDirIfNotExists(dir);
641
+ await BaseFileManager.saveFile(newFilePath, newContent);
642
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
643
+ await BaseFileManager.waitForFileWithContent(newFilePath);
644
+ logger$d(`Deleted model ${modelName} from schema ${schemaName} v${newVersion}`);
645
+ // Load the new schema file
646
+ await loadSchemaFromFile(newFilePath);
647
+ return newFilePath;
648
+ }
649
+ /**
650
+ * Delete a property from a model in a schema
651
+ * @param schemaName - The name of the schema
652
+ * @param modelName - The name of the model
653
+ * @param propertyName - The name of the property to delete
654
+ * @param options - Optional deletion options
655
+ * @returns The file path of the new schema version
656
+ * @throws Error if schema, model, or property not found
657
+ */
658
+ async function deletePropertyFromModel(schemaName, modelName, propertyName, options = {}) {
659
+ // Get the latest version
660
+ const latestVersion = await getLatestSchemaVersion(schemaName);
661
+ if (latestVersion === 0) {
662
+ throw new Error(`Schema ${schemaName} not found`);
663
+ }
664
+ // Get schemaFileId from database
665
+ const schemaFileId = await getSchemaFileId(schemaName);
666
+ // Load the latest schema file
667
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
668
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
669
+ const schemaFile = JSON.parse(content);
670
+ if (!schemaFile.$schema) {
671
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
672
+ }
673
+ const model = schemaFile.models[modelName];
674
+ if (!model) {
675
+ throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
676
+ }
677
+ if (!model.properties[propertyName]) {
678
+ throw new Error(`Property ${propertyName} not found in model ${modelName} of schema ${schemaName}`);
679
+ }
680
+ // Create new version without the property
681
+ // Preserve IDs for schema, models, and remaining properties
682
+ const newVersion = latestVersion + 1;
683
+ const updatedSchema = {
684
+ ...schemaFile,
685
+ version: newVersion,
686
+ id: schemaFile.id, // Preserve schema ID
687
+ metadata: {
688
+ ...schemaFile.metadata,
689
+ updatedAt: new Date().toISOString(),
690
+ },
691
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([mName, m]) => [
692
+ mName,
693
+ {
694
+ ...m,
695
+ id: m.id, // Preserve model ID
696
+ properties: Object.fromEntries(Object.entries(m.properties)
697
+ .filter(([propName]) => !(mName === modelName && propName === propertyName))
698
+ .map(([propName, prop]) => [
699
+ propName,
700
+ { ...prop, id: prop.id }, // Preserve property ID
701
+ ])),
702
+ },
703
+ ])),
704
+ migrations: [
705
+ ...schemaFile.migrations,
706
+ {
707
+ version: newVersion,
708
+ timestamp: new Date().toISOString(),
709
+ description: `Deleted property ${modelName}.${propertyName} from schema`,
710
+ changes: [
711
+ {
712
+ type: 'property_delete',
713
+ modelName,
714
+ propertyName,
715
+ },
716
+ ],
717
+ },
718
+ ],
719
+ };
720
+ // Write the new schema version using ID-based naming (preferred)
721
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
722
+ const newContent = JSON.stringify(updatedSchema, null, 2);
723
+ // Ensure the directory exists before saving
724
+ const path = BaseFileManager.getPathModule();
725
+ const dir = path.dirname(newFilePath);
726
+ await BaseFileManager.createDirIfNotExists(dir);
727
+ await BaseFileManager.saveFile(newFilePath, newContent);
728
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
729
+ await BaseFileManager.waitForFileWithContent(newFilePath);
730
+ logger$d(`Deleted property ${propertyName} from model ${modelName} in schema ${schemaName} v${newVersion}`);
731
+ // Load the new schema file
732
+ await loadSchemaFromFile(newFilePath);
733
+ return newFilePath;
734
+ }
20
735
 
21
736
  const logger$c = debug('seedSdk:schema:actors:loadOrCreateSchema');
22
737
  /**
@@ -60,7 +775,7 @@ const createModelInstances$2 = async (modelIds) => {
60
775
  return;
61
776
  }
62
777
  try {
63
- const { Model } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
778
+ const { Model } = await import('./index-DPll6EAp.js').then(function (n) { return n.aW; });
64
779
  // Create instances for all model IDs in parallel
65
780
  // Model.createById() will check cache first, then query DB and create if needed
66
781
  const createPromises = modelIds.map(async (modelFileId) => {
@@ -173,7 +888,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
173
888
  logger$c(`Loading internal Seed Protocol schema from SDK`);
174
889
  console.log('[loadOrCreateSchema] Loading internal Seed Protocol schema from SDK');
175
890
  try {
176
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
891
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
177
892
  const schemaFile = internalSchema.default;
178
893
  console.log('[loadOrCreateSchema] Loaded schema file, models count:', Object.keys(schemaFile.models || {}).length);
179
894
  // Check if it exists in database, if not, add it
@@ -673,7 +1388,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
673
1388
  // Ensure models are populated (fallback for seed-protocol if missing)
674
1389
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
675
1390
  try {
676
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1391
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
677
1392
  const internalSchemaFile = internalSchema.default;
678
1393
  mergedModels = { ...(internalSchemaFile.models || {}) };
679
1394
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -868,7 +1583,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
868
1583
  // Ensure models are populated (fallback for seed-protocol if missing)
869
1584
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
870
1585
  try {
871
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1586
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
872
1587
  const internalSchemaFile = internalSchema.default;
873
1588
  mergedModels = { ...(internalSchemaFile.models || {}) };
874
1589
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -940,7 +1655,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
940
1655
  // Ensure models are populated (fallback for seed-protocol if missing)
941
1656
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
942
1657
  try {
943
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1658
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
944
1659
  const internalSchemaFile = internalSchema.default;
945
1660
  mergedModels = { ...(internalSchemaFile.models || {}) };
946
1661
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -1009,7 +1724,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
1009
1724
  // If schemaData is missing, try to load from internal schema file for seed-protocol
1010
1725
  if (!dbSchema.schemaData && schemaName === 'Seed Protocol') {
1011
1726
  try {
1012
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1727
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
1013
1728
  const schemaFile = internalSchema.default;
1014
1729
  logger$c(`Found seed-protocol schema in internal file (schemaData missing, using internal schema)`);
1015
1730
  // Update database with schemaData for future loads
@@ -1118,7 +1833,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
1118
1833
  // Ensure models are populated (fallback for seed-protocol if missing)
1119
1834
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
1120
1835
  try {
1121
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1836
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
1122
1837
  const internalSchemaFile = internalSchema.default;
1123
1838
  mergedModels = { ...(internalSchemaFile.models || {}) };
1124
1839
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -1434,20 +2149,15 @@ const addModelsMachine = setup({
1434
2149
  }),
1435
2150
  createModelInstances: fromCallback(({ sendBack, input }) => {
1436
2151
  const _createInstances = async () => {
1437
- const { Schema } = await Promise.resolve().then(function () { return Schema$1; });
1438
- const { BaseDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aP; });
1439
- const { models: modelsTable } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aQ; });
1440
- const { eq } = await import('drizzle-orm');
1441
- const { generateId } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aS; });
1442
2152
  const debug = (await import('debug')).default;
1443
2153
  const logger = debug('seedSdk:schema:addModels:createInstances');
2154
+ const { Schema: SchemaClass, schemaInstanceState } = await Promise.resolve().then(function () { return Schema$1; });
1444
2155
  const schemaName = input.schemaContext.metadata?.name || input.schemaContext.schemaName;
1445
- const schemaInstance = Schema.create(schemaName, {
2156
+ const schemaInstance = SchemaClass.create(schemaName, {
1446
2157
  waitForReady: false,
1447
2158
  });
1448
2159
  const modelInstances = new Map();
1449
2160
  // Get instance state to store model instances
1450
- const { schemaInstanceState } = await Promise.resolve().then(function () { return Schema$1; });
1451
2161
  const instanceState = schemaInstanceState.get(schemaInstance);
1452
2162
  if (!instanceState) {
1453
2163
  throw new Error('Schema instance state not found');
@@ -1462,8 +2172,8 @@ const addModelsMachine = setup({
1462
2172
  if (db) {
1463
2173
  const dbModels = await db
1464
2174
  .select()
1465
- .from(modelsTable)
1466
- .where(eq(modelsTable.name, modelName))
2175
+ .from(models)
2176
+ .where(eq(models.name, modelName))
1467
2177
  .limit(1);
1468
2178
  if (dbModels.length > 0 && dbModels[0].schemaFileId) {
1469
2179
  modelFileId = dbModels[0].schemaFileId;
@@ -1665,9 +2375,6 @@ const addModelsMachine = setup({
1665
2375
  const _persist = async () => {
1666
2376
  const debug = (await import('debug')).default;
1667
2377
  const logger = debug('seedSdk:schema:addModels:persist');
1668
- const { BaseDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aP; });
1669
- const { schemas: schemasTable } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aU; });
1670
- const { eq } = await import('drizzle-orm');
1671
2378
  // Only process in browser environment where store is available
1672
2379
  if (typeof window === 'undefined') {
1673
2380
  logger('Not in browser environment, skipping store update');
@@ -1703,8 +2410,8 @@ const addModelsMachine = setup({
1703
2410
  logger(`Looking up schema by schemaFileId: ${schemaFileId} (attempt ${attempt + 1})`);
1704
2411
  const schemasById = await db
1705
2412
  .select()
1706
- .from(schemasTable)
1707
- .where(eq(schemasTable.schemaFileId, schemaFileId))
2413
+ .from(schemas)
2414
+ .where(eq(schemas.schemaFileId, schemaFileId))
1708
2415
  .limit(1);
1709
2416
  if (schemasById.length > 0) {
1710
2417
  schemaRecord = schemasById[0];
@@ -1720,12 +2427,11 @@ const addModelsMachine = setup({
1720
2427
  // FALLBACK: If not found by schemaFileId, try by name (prefer draft records)
1721
2428
  if (!schemaRecord) {
1722
2429
  logger(`Looking up schema by name: "${schemaName}" (attempt ${attempt + 1})`);
1723
- const { desc } = await import('drizzle-orm');
1724
2430
  const schemasByName = await db
1725
2431
  .select()
1726
- .from(schemasTable)
1727
- .where(eq(schemasTable.name, schemaName))
1728
- .orderBy(desc(schemasTable.isDraft), desc(schemasTable.version))
2432
+ .from(schemas)
2433
+ .where(eq(schemas.name, schemaName))
2434
+ .orderBy(desc(schemas.isDraft), desc(schemas.version))
1729
2435
  .limit(10); // Get multiple to find drafts
1730
2436
  if (schemasByName.length > 0) {
1731
2437
  // Prefer draft records
@@ -2024,7 +2730,7 @@ const createModelInstances$1 = async (modelIds) => {
2024
2730
  return;
2025
2731
  }
2026
2732
  try {
2027
- const mod = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
2733
+ const mod = await import('./index-DPll6EAp.js').then(function (n) { return n.aW; });
2028
2734
  const Model = mod?.Model ?? mod?.default;
2029
2735
  if (!Model) {
2030
2736
  logger$b('Model not available from dynamic import');
@@ -2069,7 +2775,7 @@ const checkExistingSchema = fromCallback(({ sendBack, input: { context } }) => {
2069
2775
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
2070
2776
  // For Seed Protocol, check if it exists in database
2071
2777
  try {
2072
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
2778
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
2073
2779
  const schemaFile = internalSchema.default;
2074
2780
  if (db && schemaFile.id) {
2075
2781
  const existing = await db
@@ -2427,7 +3133,7 @@ const writeSchemaToDb = fromCallback(({ sendBack, input }) => {
2427
3133
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
2428
3134
  // For Seed Protocol, load from internal file
2429
3135
  logger$a(`Loading internal Seed Protocol schema from SDK`);
2430
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
3136
+ const internalSchema = await import('./index-DPll6EAp.js').then(function (n) { return n.aV; });
2431
3137
  finalSchema = internalSchema.default;
2432
3138
  const db = BaseDb.getAppDb();
2433
3139
  if (db && finalSchema.id) {
@@ -2895,7 +3601,7 @@ const createModelInstances = fromCallback(({ sendBack, input }) => {
2895
3601
  return;
2896
3602
  }
2897
3603
  try {
2898
- const { Model } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
3604
+ const { Model } = await import('./index-DPll6EAp.js').then(function (n) { return n.aW; });
2899
3605
  // Create instances for all model IDs in parallel
2900
3606
  // Model.createById() will check cache first, then query DB and create if needed
2901
3607
  const createPromises = modelIds.map(async (modelFileId) => {
@@ -2980,7 +3686,7 @@ const verifyModelInstancesInCache = fromCallback(({ sendBack, input }) => {
2980
3686
  }
2981
3687
  try {
2982
3688
  const result = await verifyWithRetry$2(async () => {
2983
- const { Model } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
3689
+ const { Model } = await import('./index-DPll6EAp.js').then(function (n) { return n.aW; });
2984
3690
  // Check each model ID in the cache
2985
3691
  const verifiedInstances = [];
2986
3692
  const missingIds = [];
@@ -3036,8 +3742,7 @@ const writePropertiesToDb = fromCallback(({ sendBack, input }) => {
3036
3742
  const _write = async () => {
3037
3743
  const { modelIds } = input;
3038
3744
  try {
3039
- const { BaseDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aP; });
3040
- const { models: modelsTable, properties: propertiesTable } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aQ; });
3745
+ const { models: modelsTable, properties: propertiesTable } = await import('./index-DPll6EAp.js').then(function (n) { return n.aR; });
3041
3746
  const { eq } = await import('drizzle-orm');
3042
3747
  const db = BaseDb.getAppDb();
3043
3748
  if (!db) {
@@ -3223,9 +3928,9 @@ const createPropertyInstances = fromCallback(({ sendBack, input }) => {
3223
3928
  return;
3224
3929
  }
3225
3930
  try {
3226
- const modProp = await import('./ModelProperty-gjcA83Mq.js').then(function (n) { return n.b; });
3931
+ const modProp = await import('./ModelProperty-CGdkocQ8.js');
3227
3932
  const ModelProperty = modProp?.ModelProperty ?? modProp?.default;
3228
- const modModel = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
3933
+ const modModel = await import('./index-DPll6EAp.js').then(function (n) { return n.aW; });
3229
3934
  const Model = modModel?.Model ?? modModel?.default;
3230
3935
  if (!ModelProperty || !Model) {
3231
3936
  logger$2('ModelProperty or Model not available from dynamic import');
@@ -3330,7 +4035,7 @@ const verifyPropertyInstancesInCache = fromCallback(({ sendBack, input }) => {
3330
4035
  }
3331
4036
  try {
3332
4037
  const result = await verifyWithRetry(async () => {
3333
- const mod = await import('./ModelProperty-gjcA83Mq.js').then(function (n) { return n.b; });
4038
+ const mod = await import('./ModelProperty-CGdkocQ8.js');
3334
4039
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
3335
4040
  if (!ModelProperty) {
3336
4041
  throw new Error('ModelProperty not available from dynamic import');
@@ -4910,7 +5615,6 @@ class Schema {
4910
5615
  throw new ConflictError(errorMessage, conflictCheck);
4911
5616
  }
4912
5617
  const context = this._getSnapshotContext();
4913
- const { addSchemaToDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aW; });
4914
5618
  if (!context._isDraft || !context._editedProperties || context._editedProperties.size === 0) {
4915
5619
  logger('No changes to save');
4916
5620
  return '';
@@ -4957,6 +5661,7 @@ class Schema {
4957
5661
  .limit(1);
4958
5662
  // Collect all edited properties and convert them to SchemaPropertyUpdate format
4959
5663
  const propertyUpdates = [];
5664
+ const { ModelProperty } = await import('./ModelProperty-CGdkocQ8.js');
4960
5665
  for (const propertyKey of context._editedProperties) {
4961
5666
  // Skip schema-level changes (like schema name changes)
4962
5667
  if (propertyKey === 'schema:name') {
@@ -4986,7 +5691,6 @@ class Schema {
4986
5691
  // When only new models were added, _editedProperties contains 'schema:models' and we write the full schema
4987
5692
  if (context._editedProperties.has('schema:models')) {
4988
5693
  const newFilePath = await writeFullSchemaNewVersion(this.schemaName, currentSchema);
4989
- const { BaseFileManager } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aR; });
4990
5694
  const fileContent = await BaseFileManager.readFileAsString(newFilePath);
4991
5695
  const publishedSchema = JSON.parse(fileContent);
4992
5696
  if (dbSchema.length > 0) {
@@ -5016,7 +5720,6 @@ class Schema {
5016
5720
  const newFilePath = await updateModelProperties(this.schemaName, propertyUpdates);
5017
5721
  // STEP 3: After file is written, update database to mark as published (isDraft = false)
5018
5722
  // Load the file to get the final schema with IDs
5019
- const { BaseFileManager } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aR; });
5020
5723
  const fileContent = await BaseFileManager.readFileAsString(newFilePath);
5021
5724
  const publishedSchema = JSON.parse(fileContent);
5022
5725
  // Update database record: set isDraft = false and update schemaFileId
@@ -5211,9 +5914,6 @@ class Schema {
5211
5914
  saveDraftLogger(`Client check: cacheIsStale=${cacheIsStale}, shouldRecheck=${shouldRecheck}, cachedValue=${cachedClientInitialized}, timeSinceCheck=${now - clientCheckTime}ms`);
5212
5915
  if (shouldRecheck) {
5213
5916
  try {
5214
- // Use dynamic import for browser compatibility (require() doesn't work in browsers)
5215
- const { getClient } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.a_; });
5216
- const { ClientManagerState } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aT; });
5217
5917
  const client = getClient();
5218
5918
  const clientSnapshot = client.getService().getSnapshot();
5219
5919
  // Check if state is IDLE (primary check) - isInitialized is set in entry action so should be true
@@ -5284,8 +5984,6 @@ class Schema {
5284
5984
  _editedProperties: new Set(),
5285
5985
  };
5286
5986
  }
5287
- const { addSchemaToDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aW; });
5288
- const { generateId } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aS; });
5289
5987
  const db = BaseDb.getAppDb();
5290
5988
  if (!db) {
5291
5989
  throw new Error('Database not found');
@@ -5852,5 +6550,5 @@ var Schema$1 = /*#__PURE__*/Object.freeze({
5852
6550
  schemaInstanceState: schemaInstanceState
5853
6551
  });
5854
6552
 
5855
- export { Schema, schemaInstanceState };
5856
- //# sourceMappingURL=Schema-ClTcpgbt.js.map
6553
+ export { Schema as S, deleteModelFromSchema as a, Schema$1 as b, convertPropertyToSchemaUpdate as c, deletePropertyFromModel as d, renameModelProperty as r, updateModelProperties as u };
6554
+ //# sourceMappingURL=Schema-D1eqDHyt.js.map