@seedprotocol/sdk 0.4.5 → 0.4.7

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 (168) hide show
  1. package/dist/{ArweaveClient-WcG8CZAE.js → ArweaveClient-BdQaTOZ4.js} +3 -3
  2. package/dist/{ArweaveClient-WcG8CZAE.js.map → ArweaveClient-BdQaTOZ4.js.map} +1 -1
  3. package/dist/{ArweaveClient-CgWK-JgT.js → ArweaveClient-nrTU_rhU.js} +3 -3
  4. package/dist/{ArweaveClient-CgWK-JgT.js.map → ArweaveClient-nrTU_rhU.js.map} +1 -1
  5. package/dist/{Db-DjofXdeU.js → Db-CWKaeNQH.js} +7 -104
  6. package/dist/Db-CWKaeNQH.js.map +1 -0
  7. package/dist/{Db-DjFdIdR9.js → Db-Cq4q88X_.js} +21 -5
  8. package/dist/Db-Cq4q88X_.js.map +1 -0
  9. package/dist/{EasClient-Aojewp6P.js → EasClient-Du9_TULE.js} +2 -2
  10. package/dist/{EasClient-BVFXp2O6.js.map → EasClient-Du9_TULE.js.map} +1 -1
  11. package/dist/{EasClient-BVFXp2O6.js → EasClient-ZCIE6UQq.js} +2 -2
  12. package/dist/{EasClient-Aojewp6P.js.map → EasClient-ZCIE6UQq.js.map} +1 -1
  13. package/dist/{FileManager-C9zr4AJe.js → FileManager-Cub9icdd.js} +4 -3
  14. package/dist/FileManager-Cub9icdd.js.map +1 -0
  15. package/dist/{FileManager-CxGJLw5C.js → FileManager-HSFEess-.js} +2 -2
  16. package/dist/{FileManager-CxGJLw5C.js.map → FileManager-HSFEess-.js.map} +1 -1
  17. package/dist/Item/Item.d.ts +2 -0
  18. package/dist/Item/Item.d.ts.map +1 -1
  19. package/dist/Item/service/actors/fetchDataFromEas.d.ts.map +1 -1
  20. package/dist/Item/service/actors/loadOrCreateItem.d.ts.map +1 -1
  21. package/dist/Item/service/actors/runPublish.d.ts.map +1 -1
  22. package/dist/Item/service/itemMachineSingle.d.ts.map +1 -1
  23. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  24. package/dist/ItemProperty/service/actors/hydrateFromDb.d.ts.map +1 -1
  25. package/dist/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +1 -1
  26. package/dist/ItemProperty/service/actors/resolveRelatedValue.d.ts.map +1 -1
  27. package/dist/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  28. package/dist/ItemProperty/service/actors/saveValueToDb/saveRelation.d.ts.map +1 -1
  29. package/dist/Model/Model.d.ts +5 -0
  30. package/dist/Model/Model.d.ts.map +1 -1
  31. package/dist/Model/service/actors/createModelProperties.d.ts.map +1 -1
  32. package/dist/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  33. package/dist/Model/service/actors/validateModel.d.ts.map +1 -1
  34. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  35. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  36. package/dist/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  37. package/dist/{ModelProperty-CGdkocQ8.js → ModelProperty-D4zaeIOT.js} +52 -18
  38. package/dist/ModelProperty-D4zaeIOT.js.map +1 -0
  39. package/dist/{PathResolver-z_WX47_o.js → PathResolver-DVLBs_qi.js} +2 -2
  40. package/dist/{PathResolver-z_WX47_o.js.map → PathResolver-DVLBs_qi.js.map} +1 -1
  41. package/dist/{PathResolver-CX6GHoTS.js → PathResolver-T1yEDECb.js} +2 -2
  42. package/dist/{PathResolver-CX6GHoTS.js.map → PathResolver-T1yEDECb.js.map} +1 -1
  43. package/dist/{QueryClient-Cb1iJO-x.js → QueryClient-DcKDQuwz.js} +2 -2
  44. package/dist/{QueryClient-Cb1iJO-x.js.map → QueryClient-DcKDQuwz.js.map} +1 -1
  45. package/dist/{QueryClient-ByKPdRmE.js → QueryClient-Vs9KN5kS.js} +2 -2
  46. package/dist/{QueryClient-ByKPdRmE.js.map → QueryClient-Vs9KN5kS.js.map} +1 -1
  47. package/dist/Schema/Schema.d.ts.map +1 -1
  48. package/dist/Schema/service/actors/createModelInstances.d.ts.map +1 -1
  49. package/dist/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  50. package/dist/Schema/service/actors/verifyModelInstancesInCache.d.ts.map +1 -1
  51. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  52. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  53. package/dist/{Schema-D1eqDHyt.js → Schema-SbwqmoMM.js} +63 -24
  54. package/dist/Schema-SbwqmoMM.js.map +1 -0
  55. package/dist/{SchemaValidationService-DyttFaV_.js → SchemaValidationService-DHGIw4Nx.js} +2 -2
  56. package/dist/{SchemaValidationService-DyttFaV_.js.map → SchemaValidationService-DHGIw4Nx.js.map} +1 -1
  57. package/dist/browser/db/drizzleFiles.d.ts +3 -2
  58. package/dist/browser/db/drizzleFiles.d.ts.map +1 -1
  59. package/dist/browser/helpers/FileManager.d.ts.map +1 -1
  60. package/dist/browser/react/item.d.ts +2 -0
  61. package/dist/browser/react/item.d.ts.map +1 -1
  62. package/dist/browser/react/itemProperty.d.ts.map +1 -1
  63. package/dist/cjs/{ModelProperty-BeJvgKMw.js → ModelProperty-DpjD0o0E.js} +32 -18
  64. package/dist/cjs/ModelProperty-DpjD0o0E.js.map +1 -0
  65. package/dist/cjs/{Schema-CVs9J6eP.js → Schema-DkSBMBwz.js} +33 -24
  66. package/dist/cjs/Schema-DkSBMBwz.js.map +1 -0
  67. package/dist/cjs/{SchemaValidationService-CDKcVRFQ.js → SchemaValidationService-O3FCMROl.js} +2 -2
  68. package/dist/cjs/{SchemaValidationService-CDKcVRFQ.js.map → SchemaValidationService-O3FCMROl.js.map} +1 -1
  69. package/dist/cjs/{getItem-B5RYPvrG.js → getItem-BeAVMk54.js} +2 -2
  70. package/dist/cjs/{getItem-B5RYPvrG.js.map → getItem-BeAVMk54.js.map} +1 -1
  71. package/dist/cjs/{getPublishPayload-BD1qRob1.js → getPublishPayload-CoLriAMV.js} +7 -5
  72. package/dist/cjs/getPublishPayload-CoLriAMV.js.map +1 -0
  73. package/dist/cjs/{getPublishUploads-CnC9aYxs.js → getPublishUploads-DDsT9zZ6.js} +3 -3
  74. package/dist/cjs/{getPublishUploads-CnC9aYxs.js.map → getPublishUploads-DDsT9zZ6.js.map} +1 -1
  75. package/dist/cjs/{getSegmentedItemProperties-B_njnntx.js → getSegmentedItemProperties-DGR0utR5.js} +2 -2
  76. package/dist/cjs/{getSegmentedItemProperties-B_njnntx.js.map → getSegmentedItemProperties-DGR0utR5.js.map} +1 -1
  77. package/dist/cjs/{index-BeKPbbk0.js → index-B95Ng80C.js} +629 -241
  78. package/dist/cjs/index-B95Ng80C.js.map +1 -0
  79. package/dist/cjs/{index-Dnywap_P.js → index-CvcOtzbi.js} +2 -2
  80. package/dist/cjs/index-CvcOtzbi.js.map +1 -0
  81. package/dist/cjs/ownership-Dm5ER1nI.js +103 -0
  82. package/dist/cjs/ownership-Dm5ER1nI.js.map +1 -0
  83. package/dist/client/ClientManager.d.ts +54 -43
  84. package/dist/client/ClientManager.d.ts.map +1 -1
  85. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  86. package/dist/client/actors/saveConfig.d.ts.map +1 -1
  87. package/dist/client/clientManagerMachine.d.ts.map +1 -1
  88. package/dist/db/drizzle/drizzle/0004_add_publisher_to_seeds.sql +1 -0
  89. package/dist/db/drizzle/drizzle/meta/0004_snapshot.json +857 -0
  90. package/dist/db/drizzle/drizzle/meta/_journal.json +7 -0
  91. package/dist/db/read/getItemData.d.ts.map +1 -1
  92. package/dist/db/read/getItems.d.ts +2 -0
  93. package/dist/db/read/getItems.d.ts.map +1 -1
  94. package/dist/db/read/getModelSchemas.d.ts.map +1 -1
  95. package/dist/db/read/getPublishPayload.d.ts.map +1 -1
  96. package/dist/db/write/createNewItem.d.ts.map +1 -1
  97. package/dist/eas.d.ts.map +1 -1
  98. package/dist/events/files/download.d.ts.map +1 -1
  99. package/dist/events/item/syncDbWithEas.d.ts.map +1 -1
  100. package/dist/{getItem-BB5HBCbK.js → getItem-CqrJt-Ee.js} +2 -2
  101. package/dist/{getItem-BB5HBCbK.js.map → getItem-CqrJt-Ee.js.map} +1 -1
  102. package/dist/{getPublishPayload-uLm0AqN_.js → getPublishPayload-BRgULCf3.js} +7 -5
  103. package/dist/getPublishPayload-BRgULCf3.js.map +1 -0
  104. package/dist/{getPublishUploads-Dc-HqhO8.js → getPublishUploads-B0WArDfp.js} +3 -3
  105. package/dist/{getPublishUploads-Dc-HqhO8.js.map → getPublishUploads-B0WArDfp.js.map} +1 -1
  106. package/dist/{getSegmentedItemProperties-BrIqFNfD.js → getSegmentedItemProperties-DZL9Ymd4.js} +2 -2
  107. package/dist/{getSegmentedItemProperties-BrIqFNfD.js.map → getSegmentedItemProperties-DZL9Ymd4.js.map} +1 -1
  108. package/dist/helpers/addresses.d.ts +12 -0
  109. package/dist/helpers/addresses.d.ts.map +1 -0
  110. package/dist/helpers/db.d.ts +11 -0
  111. package/dist/helpers/db.d.ts.map +1 -1
  112. package/dist/helpers/ownership.d.ts +16 -0
  113. package/dist/helpers/ownership.d.ts.map +1 -0
  114. package/dist/helpers/property.d.ts.map +1 -1
  115. package/dist/helpers/updateSchema.d.ts.map +1 -1
  116. package/dist/imports/json.d.ts.map +1 -1
  117. package/dist/{index-2FcQHgKp.js → index-BIPPEMVY.js} +2 -2
  118. package/dist/index-BIPPEMVY.js.map +1 -0
  119. package/dist/{index-LEY0Og1p.js → index-BnF3MRZ8.js} +3 -3
  120. package/dist/index-BnF3MRZ8.js.map +1 -0
  121. package/dist/{index-DPll6EAp.js → index-zsq08F5p.js} +644 -154
  122. package/dist/index-zsq08F5p.js.map +1 -0
  123. package/dist/main.cjs +1 -1
  124. package/dist/main.js +20 -14
  125. package/dist/main.js.map +1 -1
  126. package/dist/node/db/Db.d.ts.map +1 -1
  127. package/dist/node.js +10 -10
  128. package/dist/ownership-CSsweVap.js +85 -0
  129. package/dist/ownership-CSsweVap.js.map +1 -0
  130. package/dist/{property-B15X7jLX.js → property-Cqh_o0zx.js} +10 -4
  131. package/dist/property-Cqh_o0zx.js.map +1 -0
  132. package/dist/{queries-BPDSpiEX.js → queries-DSBgjcJJ.js} +2 -2
  133. package/dist/{queries-BPDSpiEX.js.map → queries-DSBgjcJJ.js.map} +1 -1
  134. package/dist/seedSchema/ModelSchemaSchema.d.ts +1 -1
  135. package/dist/seedSchema/ModelSchemaSchema.ts +4 -4
  136. package/dist/seedSchema/ModelUidSchema.ts +1 -1
  137. package/dist/seedSchema/PropertyUidSchema.ts +1 -1
  138. package/dist/seedSchema/SeedSchema.d.ts +19 -0
  139. package/dist/seedSchema/SeedSchema.d.ts.map +1 -1
  140. package/dist/seedSchema/SeedSchema.ts +1 -0
  141. package/dist/seedSchema/index.d.ts +10 -10
  142. package/dist/seedSchema/index.d.ts.map +1 -1
  143. package/dist/seedSchema/index.ts +10 -10
  144. package/dist/services/publish/actors/preparePublishRequestData.d.ts.map +1 -1
  145. package/dist/services/publish/actors/upload.d.ts.map +1 -1
  146. package/dist/services/write/actors/validateEntity.d.ts.map +1 -1
  147. package/dist/types/index.d.ts +11 -1
  148. package/dist/types/index.d.ts.map +1 -1
  149. package/dist/types/item.d.ts +1 -0
  150. package/dist/types/item.d.ts.map +1 -1
  151. package/dist/types/machines.d.ts +2 -0
  152. package/dist/types/machines.d.ts.map +1 -1
  153. package/package.json +4 -11
  154. package/dist/Db-DjFdIdR9.js.map +0 -1
  155. package/dist/Db-DjofXdeU.js.map +0 -1
  156. package/dist/FileManager-C9zr4AJe.js.map +0 -1
  157. package/dist/ModelProperty-CGdkocQ8.js.map +0 -1
  158. package/dist/Schema-D1eqDHyt.js.map +0 -1
  159. package/dist/cjs/ModelProperty-BeJvgKMw.js.map +0 -1
  160. package/dist/cjs/Schema-CVs9J6eP.js.map +0 -1
  161. package/dist/cjs/getPublishPayload-BD1qRob1.js.map +0 -1
  162. package/dist/cjs/index-BeKPbbk0.js.map +0 -1
  163. package/dist/cjs/index-Dnywap_P.js.map +0 -1
  164. package/dist/getPublishPayload-uLm0AqN_.js.map +0 -1
  165. package/dist/index-2FcQHgKp.js.map +0 -1
  166. package/dist/index-DPll6EAp.js.map +0 -1
  167. package/dist/index-LEY0Og1p.js.map +0 -1
  168. package/dist/property-B15X7jLX.js.map +0 -1
@@ -1,13 +1,13 @@
1
1
  import { waitFor, fromCallback, fromPromise, setup, assign, createActor } from 'xstate';
2
2
  import { sqliteTable, integer, text, unique, int, blob } from 'drizzle-orm/sqlite-core';
3
- import { relations, eq, and, isNull, isNotNull, not, or, max, count, getTableColumns, sql, gt, inArray, desc } from 'drizzle-orm';
3
+ import { relations, eq, and, isNull, isNotNull, not, or, max, count, getTableColumns, sql, inArray, gt, desc } from 'drizzle-orm';
4
4
  import { customAlphabet } from 'nanoid';
5
5
  import * as nanoIdDictionary from 'nanoid-dictionary';
6
6
  import debug from 'debug';
7
7
  import pluralize from 'pluralize';
8
8
  import { ZeroAddress } from 'ethers';
9
9
  import { BehaviorSubject } from 'rxjs';
10
- import { startCase, orderBy, throttle, camelCase } from 'lodash-es';
10
+ import { startCase, upperFirst, camelCase, orderBy, throttle } from 'lodash-es';
11
11
  import { toSnakeCase as toSnakeCase$1 } from 'drizzle-orm/casing';
12
12
  import EventEmitter from 'eventemitter3';
13
13
  import 'arweave';
@@ -424,6 +424,30 @@ const generateId = () => {
424
424
  const toSnakeCase = (str) => {
425
425
  return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
426
426
  };
427
+ const identifyString = (str) => {
428
+ try {
429
+ JSON.parse(str);
430
+ return 'json';
431
+ }
432
+ catch (e) {
433
+ // Not JSON
434
+ }
435
+ if (!str) {
436
+ return;
437
+ }
438
+ if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
439
+ return 'html';
440
+ }
441
+ // Simple markdown checks (very naive)
442
+ if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
443
+ return 'markdown';
444
+ }
445
+ if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
446
+ return 'base64';
447
+ }
448
+ // Default to plain text if unsure
449
+ return 'text';
450
+ };
427
451
  const getMimeType = (base64) => {
428
452
  if (!base64) {
429
453
  return null;
@@ -510,6 +534,12 @@ const convertTxIdToImage = async (txId) => {
510
534
  const getArweaveUrlForTransaction = (storageTransactionId) => {
511
535
  return BaseArweaveClient.getRawUrl(storageTransactionId);
512
536
  };
537
+ const getExecutionTime = async (task, args) => {
538
+ const start = Date.now();
539
+ await task(...args);
540
+ return Date.now() - start;
541
+ };
542
+ const capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
513
543
  const parseEasRelationPropertyName = (easPropertyName) => {
514
544
  // Split the input string on the first underscore
515
545
  const [singularProperty, modelName, idSegment] = easPropertyName.split('_');
@@ -525,6 +555,25 @@ const parseEasRelationPropertyName = (easPropertyName) => {
525
555
  isList, // True if the property is a list (e.g., 'ids' is present)
526
556
  };
527
557
  };
558
+ const isBinary = (arrayBuffer) => {
559
+ const view = new Uint8Array(arrayBuffer);
560
+ let nonTextCount = 0;
561
+ const threshold = 0.2; // Adjust as needed (e.g., 20% non-text implies binary)
562
+ for (let i = 0; i < view.length; i++) {
563
+ const byte = view[i];
564
+ // ASCII printable characters (32-126) and common whitespace (9, 10, 13)
565
+ if ((byte >= 32 && byte <= 126) || // Printable ASCII
566
+ byte === 9 || byte === 10 || byte === 13 // Tab, LF, CR
567
+ ) {
568
+ continue;
569
+ }
570
+ nonTextCount++;
571
+ if (nonTextCount / view.length > threshold) {
572
+ return true; // More than threshold are non-text bytes
573
+ }
574
+ }
575
+ return false; // Fewer than threshold are non-text bytes
576
+ };
528
577
 
529
578
  var index = /*#__PURE__*/Object.freeze({
530
579
  __proto__: null,
@@ -532,12 +581,16 @@ var index = /*#__PURE__*/Object.freeze({
532
581
  BaseEasClient: BaseEasClient,
533
582
  BaseFileManager: BaseFileManager,
534
583
  BaseQueryClient: BaseQueryClient,
584
+ capitalizeFirstLetter: capitalizeFirstLetter,
535
585
  convertTxIdToImage: convertTxIdToImage,
536
586
  generateId: generateId,
537
587
  getArweaveUrlForTransaction: getArweaveUrlForTransaction,
538
588
  getCorrectId: getCorrectId,
539
589
  getDataTypeFromString: getDataTypeFromString,
590
+ getExecutionTime: getExecutionTime,
540
591
  getMimeType: getMimeType,
592
+ identifyString: identifyString,
593
+ isBinary: isBinary,
541
594
  parseEasRelationPropertyName: parseEasRelationPropertyName,
542
595
  toSnakeCase: toSnakeCase,
543
596
  waitForEntityIdle: waitForEntityIdle
@@ -554,7 +607,7 @@ const createPropertyInstances = async (propertyFileIds) => {
554
607
  return;
555
608
  }
556
609
  try {
557
- const mod = await import('./ModelProperty-CGdkocQ8.js');
610
+ const mod = await import('./ModelProperty-D4zaeIOT.js');
558
611
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
559
612
  if (!ModelProperty) {
560
613
  logger$s('createPropertyInstances: ModelProperty not available from dynamic import');
@@ -637,7 +690,8 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
637
690
  // schemaFileId to match the database, both will point to the same cached instance.
638
691
  if (dbSchemaFileId) {
639
692
  try {
640
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
693
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
694
+ const { Model } = modelMod;
641
695
  // Access instanceCacheById via type assertion since it's protected
642
696
  const cacheById = Model.instanceCacheById;
643
697
  if (cacheById.has(dbSchemaFileId)) {
@@ -742,7 +796,10 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
742
796
  // Step 2: Fallback to Schema context (only if database doesn't have the model)
743
797
  // This handles the case where model exists in schema file but not yet in database
744
798
  try {
745
- const { Schema } = await import('./Schema-D1eqDHyt.js').then(function (n) { return n.b; });
799
+ const _mod_0 = await import('./Schema-SbwqmoMM.js');
800
+ const _ns_0 = _mod_0.b;
801
+ const schemaMod = _ns_0;
802
+ const { Schema } = schemaMod;
746
803
  const schema = Schema.create(schemaName, { waitForReady: false });
747
804
  const schemaSnapshot = schema.getService().getSnapshot();
748
805
  // Wait for schema to load if it's still loading
@@ -813,7 +870,8 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
813
870
  let finalModelName = modelName;
814
871
  if (db) {
815
872
  // Check if this is an internal schema (Seed Protocol)
816
- const { isInternalSchema } = await Promise.resolve().then(function () { return constants; });
873
+ const constantsMod = await Promise.resolve().then(function () { return constants; });
874
+ const { isInternalSchema } = constantsMod;
817
875
  const isInternal = isInternalSchema(schemaName);
818
876
  // Only skip duplicate check if:
819
877
  // 1. We found a model record to use (modelRecord is set), OR
@@ -828,7 +886,8 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
828
886
  const existingNumbers = new Set(existingNumbersFromSchemaContext ?? []);
829
887
  // First, check Model cache for models (includes models from imported schemas that may not be in DB yet)
830
888
  try {
831
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
889
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
890
+ const { Model } = modelMod;
832
891
  // Check name-based cache for this schema
833
892
  // Skip the current model (context.id): Model.create() adds the new instance to the cache
834
893
  // before this callback runs, so we must not count it as a duplicate.
@@ -887,8 +946,10 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
887
946
  }
888
947
  // Also check database for models (in case they're persisted but not in Schema context)
889
948
  if (db) {
890
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
891
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
949
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
950
+ const { modelSchemas } = modelSchemaSchemaMod;
951
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
952
+ const { schemas: schemasTable } = schemaSchemaMod;
892
953
  // Query all models for this schema to check for duplicates (case-insensitive)
893
954
  logger$s(`Checking database for duplicate model names in schema "${schemaName}"`);
894
955
  const allModelsForSchema = await db
@@ -961,7 +1022,8 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
961
1022
  }
962
1023
  // Runtime creates use a placeholder cache key in Model.create; move it to the final name. Skip when schema model (_idFromSchema).
963
1024
  if (!_idFromSchema) {
964
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
1025
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
1026
+ const { Model } = modelMod;
965
1027
  Model.updateNameIndex('__pending__' + schemaFileId, finalModelName, schemaName, schemaFileId);
966
1028
  }
967
1029
  // If model name was changed, store it in a temporary internal field so loadOrCreateModelSuccess can apply it
@@ -980,7 +1042,10 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
980
1042
  }
981
1043
  // Mark schema as draft when a new model is created so saveNewVersion() can persist it
982
1044
  try {
983
- const { Schema } = await import('./Schema-D1eqDHyt.js').then(function (n) { return n.b; });
1045
+ const _mod_1 = await import('./Schema-SbwqmoMM.js');
1046
+ const _ns_1 = _mod_1.b;
1047
+ const schemaMod = _ns_1;
1048
+ const { Schema } = schemaMod;
984
1049
  const schema = Schema.create(schemaName, { waitForReady: false });
985
1050
  schema.getService().send({ type: 'markAsDraft', propertyKey: 'schema:models' });
986
1051
  }
@@ -1023,9 +1088,13 @@ const validateModel = fromCallback(({ sendBack, input: { context } }) => {
1023
1088
  const _validateModel = async () => {
1024
1089
  try {
1025
1090
  // Use dynamic imports to break circular dependencies
1026
- const { SchemaValidationService } = await import('./SchemaValidationService-DyttFaV_.js');
1091
+ const validationServiceMod = await import('./SchemaValidationService-DHGIw4Nx.js');
1092
+ const { SchemaValidationService } = validationServiceMod;
1027
1093
  const validationService = new SchemaValidationService();
1028
- const { Schema } = await import('./Schema-D1eqDHyt.js').then(function (n) { return n.b; });
1094
+ const _mod_2 = await import('./Schema-SbwqmoMM.js');
1095
+ const _ns_2 = _mod_2.b;
1096
+ const schemaMod = _ns_2;
1097
+ const { Schema } = schemaMod;
1029
1098
  // Validate model structure
1030
1099
  const structureResult = validationService.validateModelStructure(context);
1031
1100
  if (!structureResult.isValid) {
@@ -1136,19 +1205,21 @@ const createModelProperties = fromCallback(({ sendBack, input }) => {
1136
1205
  return;
1137
1206
  }
1138
1207
  logger$q(`Creating ${Object.keys(propertyDefinitions).length} properties for model "${modelName}" (id: ${_dbId})`);
1139
- const mod = await import('./ModelProperty-CGdkocQ8.js');
1208
+ const mod = await import('./ModelProperty-D4zaeIOT.js');
1140
1209
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
1141
1210
  if (!ModelProperty) {
1142
1211
  logger$q('ModelProperty not available from dynamic import');
1143
1212
  sendBack({ type: 'createModelPropertiesError', error: new Error('ModelProperty not available') });
1144
1213
  return;
1145
1214
  }
1146
- const { eq } = await import('drizzle-orm');
1215
+ const drizzleMod = await import('drizzle-orm');
1216
+ const { eq } = drizzleMod;
1147
1217
  const db = BaseDb.getAppDb();
1148
1218
  for (const [propName, propData] of Object.entries(propertyDefinitions)) {
1149
1219
  // Use provided ID or generate a random one
1150
1220
  // IDs should be generated in the import process before creating properties
1151
- const { generateId } = await Promise.resolve().then(function () { return index; });
1221
+ const helpersMod = await Promise.resolve().then(function () { return index; });
1222
+ const { generateId } = helpersMod;
1152
1223
  const propertyFileId = propData.id || generateId();
1153
1224
  logger$q(`Creating property "${propName}" with fileId "${propertyFileId}"`);
1154
1225
  // Query database to get refModelId if the property has ref/refModelName
@@ -1239,7 +1310,8 @@ const validateEntity = fromPromise(async ({ input }) => {
1239
1310
  logger$p(structureMsg);
1240
1311
  console.log(structureMsg); // Always log to console
1241
1312
  // Use existing Model validation
1242
- const { SchemaValidationService } = await import('./SchemaValidationService-DyttFaV_.js');
1313
+ const validationServiceMod = await import('./SchemaValidationService-DHGIw4Nx.js');
1314
+ const { SchemaValidationService } = validationServiceMod;
1243
1315
  const validationService = new SchemaValidationService();
1244
1316
  // Validate model structure
1245
1317
  const structureResult = validationService.validateModelStructure(entityInput.entityData);
@@ -1257,7 +1329,10 @@ const validateEntity = fromPromise(async ({ input }) => {
1257
1329
  if (entityInput.entityData.schemaName) {
1258
1330
  try {
1259
1331
  logger$p(`[validateEntity] Validating model against schema "${entityInput.entityData.schemaName}"`);
1260
- const { Schema } = await import('./Schema-D1eqDHyt.js').then(function (n) { return n.b; });
1332
+ const _mod_3 = await import('./Schema-SbwqmoMM.js');
1333
+ const _ns_3 = _mod_3.b;
1334
+ const schemaMod = _ns_3;
1335
+ const { Schema } = schemaMod;
1261
1336
  const schema = Schema.create(entityInput.entityData.schemaName, {
1262
1337
  waitForReady: false,
1263
1338
  });
@@ -1292,7 +1367,8 @@ const validateEntity = fromPromise(async ({ input }) => {
1292
1367
  }
1293
1368
  else if (entityInput.entityType === 'modelProperty') {
1294
1369
  // Use existing ModelProperty validation
1295
- const { SchemaValidationService } = await import('./SchemaValidationService-DyttFaV_.js');
1370
+ const validationServiceMod = await import('./SchemaValidationService-DHGIw4Nx.js');
1371
+ const { SchemaValidationService } = validationServiceMod;
1296
1372
  const validationService = new SchemaValidationService();
1297
1373
  // Validate property structure
1298
1374
  const structureResult = validationService.validatePropertyStructure(entityInput.entityData);
@@ -1306,7 +1382,10 @@ const validateEntity = fromPromise(async ({ input }) => {
1306
1382
  // If schema name and model name provided, validate against schema
1307
1383
  if (entityInput.entityData._schemaName && entityInput.entityData.modelName) {
1308
1384
  try {
1309
- const { Schema } = await import('./Schema-D1eqDHyt.js').then(function (n) { return n.b; });
1385
+ const _mod_4 = await import('./Schema-SbwqmoMM.js');
1386
+ const _ns_4 = _mod_4.b;
1387
+ const schemaMod = _ns_4;
1388
+ const { Schema } = schemaMod;
1310
1389
  const schema = Schema.create(entityInput.entityData._schemaName, {
1311
1390
  waitForReady: false,
1312
1391
  });
@@ -1334,7 +1413,8 @@ const validateEntity = fromPromise(async ({ input }) => {
1334
1413
  }
1335
1414
  else if (entityInput.entityType === 'schema') {
1336
1415
  // Schema validation - use existing validation
1337
- const { SchemaValidationService } = await import('./SchemaValidationService-DyttFaV_.js');
1416
+ const validationServiceMod = await import('./SchemaValidationService-DHGIw4Nx.js');
1417
+ const { SchemaValidationService } = validationServiceMod;
1338
1418
  const validationService = new SchemaValidationService();
1339
1419
  const schemaResult = validationService.validateSchema(entityInput.entityData);
1340
1420
  if (!schemaResult.isValid) {
@@ -1370,6 +1450,7 @@ const seeds = sqliteTable('seeds', {
1370
1450
  uid: text('uid'),
1371
1451
  schemaUid: text('schema_uid'),
1372
1452
  type: text('type'),
1453
+ publisher: text('publisher'),
1373
1454
  attestationRaw: text('attestation_raw'),
1374
1455
  attestationCreatedAt: int('attestation_created_at'),
1375
1456
  createdAt: int('created_at'),
@@ -1493,6 +1574,42 @@ const escapeSqliteString = (value) => {
1493
1574
  }
1494
1575
  return value.replace(/'/g, "''");
1495
1576
  };
1577
+ const getObjectForRow = (row) => {
1578
+ const obj = {};
1579
+ row.columnNames.forEach((colName, index) => {
1580
+ const value = row.row[index];
1581
+ if (typeof value !== 'string') {
1582
+ obj[colName] = row.row[index];
1583
+ return;
1584
+ }
1585
+ // Try to parse the value as JSON
1586
+ try {
1587
+ obj[colName] = JSON.parse(value);
1588
+ }
1589
+ catch (e) {
1590
+ // If it fails, just set the value as a string
1591
+ obj[colName] = value;
1592
+ }
1593
+ });
1594
+ return obj;
1595
+ };
1596
+ const getSqlResultObject = (queryResult) => {
1597
+ if (!queryResult || !queryResult.rows || queryResult.rows.length === 0) {
1598
+ return;
1599
+ }
1600
+ let obj;
1601
+ if (queryResult.rows.length === 1) {
1602
+ obj = getObjectForRow(queryResult.rows[0]);
1603
+ }
1604
+ if (queryResult.rows.length > 1) {
1605
+ obj = queryResult.rows.reduce((acc, row) => {
1606
+ const rowObj = getObjectForRow(row);
1607
+ acc.push(rowObj);
1608
+ return acc;
1609
+ }, []);
1610
+ }
1611
+ return obj;
1612
+ };
1496
1613
  const createOrUpdate = async (db, table, values) => {
1497
1614
  const valueFilters = [];
1498
1615
  const propertiesToExcludeFromDb = ['ref'];
@@ -1828,7 +1945,7 @@ async function checkIfPropertyIsEdited(modelName, propertyName, schemaFileValue)
1828
1945
  const cacheKey = `${modelName}:${propertyName}`;
1829
1946
  // First, check the in-memory cache (for current session edits)
1830
1947
  // Robust dynamic import for consumer re-bundling (named or default export)
1831
- const mod = await import('./ModelProperty-CGdkocQ8.js');
1948
+ const mod = await import('./ModelProperty-D4zaeIOT.js');
1832
1949
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
1833
1950
  if (!ModelProperty) {
1834
1951
  logger$o('ModelProperty not available from dynamic import');
@@ -2071,7 +2188,8 @@ const addModelsToDb$1 = async (models, schema, modelRenames, schemaFileData) =>
2071
2188
  schema = pendingProperties;
2072
2189
  }
2073
2190
  else {
2074
- const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
2191
+ const modelHelpersMod = await Promise.resolve().then(function () { return model; });
2192
+ const { modelPropertiesToObject } = modelHelpersMod;
2075
2193
  const modelProperties = modelClass.properties || [];
2076
2194
  schema = modelPropertiesToObject(modelProperties);
2077
2195
  }
@@ -2091,7 +2209,8 @@ const addModelsToDb$1 = async (models, schema, modelRenames, schemaFileData) =>
2091
2209
  // If no propertyFileId from map, generate a random ID
2092
2210
  // IDs should be generated in the import process before calling addModelsToDb
2093
2211
  if (!propertyFileId) {
2094
- const { generateId } = await Promise.resolve().then(function () { return index; });
2212
+ const helpersIndexMod = await Promise.resolve().then(function () { return index; });
2213
+ const { generateId } = helpersIndexMod;
2095
2214
  propertyFileId = generateId();
2096
2215
  logger$o(`Generated propertyFileId "${propertyFileId}" for property "${modelName}:${propertyName}" (not found in propertyFileIds map)`);
2097
2216
  }
@@ -2506,13 +2625,49 @@ const savePropertyToDb = async (property) => {
2506
2625
  logger$o(`Created property ${property.modelName}:${property.name} in database`);
2507
2626
  }
2508
2627
  };
2509
- const getAddressesFromDb = async () => {
2628
+ function parseAddressConfig(value) {
2629
+ if (!value)
2630
+ return null;
2631
+ try {
2632
+ const parsed = JSON.parse(value);
2633
+ if (Array.isArray(parsed)) {
2634
+ return { owned: parsed, watched: [] };
2635
+ }
2636
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.owned)) {
2637
+ return {
2638
+ owned: parsed.owned,
2639
+ watched: Array.isArray(parsed.watched) ? parsed.watched : [],
2640
+ };
2641
+ }
2642
+ return null;
2643
+ }
2644
+ catch {
2645
+ return null;
2646
+ }
2647
+ }
2648
+ const getOwnedAddressesFromDb = async () => {
2649
+ const config = await getAddressConfigFromDb();
2650
+ return config?.owned ?? [];
2651
+ };
2652
+ const getWatchedAddressesFromDb = async () => {
2653
+ const config = await getAddressConfigFromDb();
2654
+ return config?.watched ?? [];
2655
+ };
2656
+ /**
2657
+ * Returns owned + watched addresses. Use for EAS sync and file download.
2658
+ */
2659
+ const getAllAddressesFromDb = async () => {
2660
+ const config = await getAddressConfigFromDb();
2661
+ if (!config)
2662
+ return [];
2663
+ return [...config.owned, ...config.watched];
2664
+ };
2665
+ async function getAddressConfigFromDb() {
2510
2666
  const appDb = BaseDb.getAppDb();
2511
2667
  if (!appDb) {
2512
2668
  return new Promise((resolve) => {
2513
2669
  setTimeout(async () => {
2514
- const addresses = await getAddressesFromDb();
2515
- resolve(addresses);
2670
+ resolve(await getAddressConfigFromDb());
2516
2671
  }, 500);
2517
2672
  });
2518
2673
  }
@@ -2522,14 +2677,25 @@ const getAddressesFromDb = async () => {
2522
2677
  .where(eq(appState.key, 'addresses'))
2523
2678
  .limit(1);
2524
2679
  if (!appStatesRecords || appStatesRecords.length === 0) {
2525
- throw new Error('No appStatesRecords for addresses found');
2680
+ return null;
2526
2681
  }
2527
- const addressRecord = appStatesRecords[0];
2528
- const addressArrayString = addressRecord.value;
2529
- if (!addressArrayString) {
2682
+ const addressArrayString = appStatesRecords[0].value;
2683
+ return parseAddressConfig(addressArrayString);
2684
+ }
2685
+ const getAddressesFromDb = async () => {
2686
+ const config = await getAddressConfigFromDb();
2687
+ if (!config || config.owned.length === 0) {
2530
2688
  throw new Error('No addresses found');
2531
2689
  }
2532
- return JSON.parse(addressArrayString);
2690
+ return config.owned;
2691
+ };
2692
+ /**
2693
+ * Like getAddressesFromDb but returns [] instead of throwing when no addresses are configured.
2694
+ * Returns owned addresses. Use getAllAddressesFromDb for sync (owned + watched).
2695
+ */
2696
+ const getAddressesFromDbOptional = async () => {
2697
+ const config = await getAddressConfigFromDb();
2698
+ return config?.owned ?? [];
2533
2699
  };
2534
2700
  /**
2535
2701
  * Write model to database and create model_schemas join entry
@@ -2636,7 +2802,8 @@ async function writeModelToDb(modelFileId, data) {
2636
2802
  throw new Error(`Model with id ${modelId} does not exist in database. Cannot create join record.`);
2637
2803
  }
2638
2804
  // Verify schemaId exists and get name/fileId for invalidation broadcast
2639
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
2805
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
2806
+ const { schemas: schemasTable } = schemaSchemaMod;
2640
2807
  const schemaCheck = await db
2641
2808
  .select({
2642
2809
  id: schemasTable.id,
@@ -2702,7 +2869,8 @@ async function writeModelToDb(modelFileId, data) {
2702
2869
  else {
2703
2870
  // Generate random propertyFileId
2704
2871
  // IDs should be generated in the import process before calling writeModelToDb
2705
- const { generateId } = await Promise.resolve().then(function () { return index; });
2872
+ const helpersIndexMod = await Promise.resolve().then(function () { return index; });
2873
+ const { generateId } = helpersIndexMod;
2706
2874
  propertyFileId = generateId();
2707
2875
  logger$o(`Generated propertyFileId "${propertyFileId}" for property "${data.modelName}:${propName}"`);
2708
2876
  }
@@ -2828,6 +2996,68 @@ async function writePropertyToDb(propertyFileId, data, isEdited = false) {
2828
2996
  }
2829
2997
  }
2830
2998
  }
2999
+ /**
3000
+ * Get schema database ID from schema name or schemaFileId
3001
+ * @param schemaNameOrFileId - Schema name (string) or schemaFileId (string)
3002
+ * @returns Schema database ID
3003
+ * @throws Error if schema not found
3004
+ */
3005
+ async function getSchemaId(schemaNameOrFileId) {
3006
+ const db = BaseDb.getAppDb();
3007
+ if (!db) {
3008
+ throw new Error('Database not available');
3009
+ }
3010
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
3011
+ const { schemas: schemasTable } = schemaSchemaMod;
3012
+ const drizzleMod = await import('drizzle-orm');
3013
+ const { eq, desc } = drizzleMod;
3014
+ // Try to find by schemaFileId first (more reliable)
3015
+ let records = await db
3016
+ .select()
3017
+ .from(schemasTable)
3018
+ .where(eq(schemasTable.schemaFileId, schemaNameOrFileId))
3019
+ .orderBy(desc(schemasTable.version))
3020
+ .limit(1);
3021
+ // If not found by schemaFileId, try by name
3022
+ if (records.length === 0) {
3023
+ records = await db
3024
+ .select()
3025
+ .from(schemasTable)
3026
+ .where(eq(schemasTable.name, schemaNameOrFileId))
3027
+ .orderBy(desc(schemasTable.version))
3028
+ .limit(1);
3029
+ }
3030
+ if (records.length === 0) {
3031
+ throw new Error(`Schema "${schemaNameOrFileId}" not found in database`);
3032
+ }
3033
+ return records[0].id;
3034
+ }
3035
+ /**
3036
+ * Get schema database ID from schemaFileId
3037
+ * @param schemaFileId - The schema file ID
3038
+ * @returns Schema database ID
3039
+ * @throws Error if schema not found
3040
+ */
3041
+ async function getSchemaIdByFileId(schemaFileId) {
3042
+ const db = BaseDb.getAppDb();
3043
+ if (!db) {
3044
+ throw new Error('Database not available');
3045
+ }
3046
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
3047
+ const { schemas: schemasTable } = schemaSchemaMod;
3048
+ const drizzleMod = await import('drizzle-orm');
3049
+ const { eq, desc } = drizzleMod;
3050
+ const records = await db
3051
+ .select()
3052
+ .from(schemasTable)
3053
+ .where(eq(schemasTable.schemaFileId, schemaFileId))
3054
+ .orderBy(desc(schemasTable.version))
3055
+ .limit(1);
3056
+ if (records.length === 0) {
3057
+ throw new Error(`Schema with file ID "${schemaFileId}" not found in database`);
3058
+ }
3059
+ return records[0].id;
3060
+ }
2831
3061
  /**
2832
3062
  * Get model database ID from model name or modelFileId
2833
3063
  * @param modelNameOrFileId - Model name (string) or modelFileId (string)
@@ -2840,8 +3070,10 @@ async function getModelId(modelNameOrFileId, schemaNameOrId) {
2840
3070
  if (!db) {
2841
3071
  throw new Error('Database not available');
2842
3072
  }
2843
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
2844
- const { eq, and, or } = await import('drizzle-orm');
3073
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
3074
+ const { models: modelsTable } = modelSchemaMod;
3075
+ const drizzleMod = await import('drizzle-orm');
3076
+ const { eq, and, or } = drizzleMod;
2845
3077
  // Try to find by modelFileId first (more reliable)
2846
3078
  let records = await db
2847
3079
  .select()
@@ -2853,8 +3085,10 @@ async function getModelId(modelNameOrFileId, schemaNameOrId) {
2853
3085
  [eq(modelsTable.name, modelNameOrFileId)];
2854
3086
  // If schema is provided, narrow the search
2855
3087
  if (schemaNameOrId !== undefined) {
2856
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
2857
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
3088
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
3089
+ const { modelSchemas } = modelSchemaSchemaMod;
3090
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
3091
+ const { schemas: schemasTable } = schemaSchemaMod;
2858
3092
  if (typeof schemaNameOrId === 'number') {
2859
3093
  // schemaNameOrId is schemaId
2860
3094
  records = await db
@@ -2901,8 +3135,10 @@ async function getModelIdByFileId(modelFileId) {
2901
3135
  if (!db) {
2902
3136
  throw new Error('Database not available');
2903
3137
  }
2904
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
2905
- const { eq } = await import('drizzle-orm');
3138
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
3139
+ const { models: modelsTable } = modelSchemaMod;
3140
+ const drizzleMod = await import('drizzle-orm');
3141
+ const { eq } = drizzleMod;
2906
3142
  const records = await db
2907
3143
  .select()
2908
3144
  .from(modelsTable)
@@ -2921,10 +3157,18 @@ var db = /*#__PURE__*/Object.freeze({
2921
3157
  createOrUpdate: createOrUpdate,
2922
3158
  escapeSqliteString: escapeSqliteString,
2923
3159
  getAddressesFromDb: getAddressesFromDb,
3160
+ getAddressesFromDbOptional: getAddressesFromDbOptional,
3161
+ getAllAddressesFromDb: getAllAddressesFromDb,
2924
3162
  getModelId: getModelId,
2925
3163
  getModelIdByFileId: getModelIdByFileId,
2926
3164
  getModelNameByModelId: getModelNameByModelId,
3165
+ getObjectForRow: getObjectForRow,
3166
+ getOwnedAddressesFromDb: getOwnedAddressesFromDb,
2927
3167
  getPropertyModelNameAndDataType: getPropertyModelNameAndDataType,
3168
+ getSchemaId: getSchemaId,
3169
+ getSchemaIdByFileId: getSchemaIdByFileId,
3170
+ getSqlResultObject: getSqlResultObject,
3171
+ getWatchedAddressesFromDb: getWatchedAddressesFromDb,
2928
3172
  loadModelsFromDbForSchema: loadModelsFromDbForSchema,
2929
3173
  renameModelInDb: renameModelInDb,
2930
3174
  savePropertyToDb: savePropertyToDb,
@@ -2978,7 +3222,7 @@ const writeToDatabase = fromCallback(({ sendBack, input }) => {
2978
3222
  // initial write completes is not overwritten by the stale requestWrite payload.
2979
3223
  let dataToWrite = input.entityData;
2980
3224
  try {
2981
- const mod = await import('./ModelProperty-CGdkocQ8.js');
3225
+ const mod = await import('./ModelProperty-D4zaeIOT.js');
2982
3226
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
2983
3227
  if (ModelProperty && typeof ModelProperty.getById === 'function') {
2984
3228
  const instance = ModelProperty.getById(input.entityId);
@@ -3369,7 +3613,7 @@ const modelMachine = setup({
3369
3613
  // Create ModelProperty instances for any new property IDs
3370
3614
  if (Array.isArray(newPropertyIds) && newPropertyIds.length > 0) {
3371
3615
  // Import and create instances asynchronously (fire-and-forget)
3372
- import('./ModelProperty-CGdkocQ8.js').then(({ ModelProperty }) => {
3616
+ import('./ModelProperty-D4zaeIOT.js').then(({ ModelProperty }) => {
3373
3617
  const createPromises = newPropertyIds.map(async (propertyFileId) => {
3374
3618
  try {
3375
3619
  const property = await ModelProperty.createById(propertyFileId);
@@ -4215,7 +4459,8 @@ const fetchDataFromEas = fromCallback(({ sendBack, input: { context } }) => {
4215
4459
  }
4216
4460
  else if (modelName) {
4217
4461
  // Dynamic import to break circular dependency
4218
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
4462
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
4463
+ const { Model } = modelMod;
4219
4464
  const model = Model.getByName(modelName);
4220
4465
  modelSchema = model?.properties ? modelPropertiesToObject(model.properties) : undefined;
4221
4466
  }
@@ -4334,33 +4579,56 @@ var versionData = /*#__PURE__*/Object.freeze({
4334
4579
 
4335
4580
  const logger$k = debug('seedSdk:item:actors:loadOrCreateItem');
4336
4581
  /**
4337
- * Create ItemProperty instances for all metadata records to ensure they're cached
4582
+ * Create ItemProperty instances for all metadata records to ensure they're cached.
4583
+ * Passes propertyRecordSchema from Model when available (Fix 3: enables value persistence for runtime-created models).
4338
4584
  * @param metadataRows - Array of metadata records to create ItemProperty instances for
4339
4585
  * @param seedLocalId - Seed local ID
4340
4586
  * @param seedUid - Seed UID
4587
+ * @param modelName - Model name for resolving propertyRecordSchema from Model
4341
4588
  * @returns Map of propertyName -> ItemProperty instance
4342
4589
  */
4343
- const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid) => {
4590
+ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid, modelName) => {
4344
4591
  const propertyInstances = new Map();
4345
4592
  if (metadataRows.length === 0) {
4346
4593
  return propertyInstances;
4347
4594
  }
4348
4595
  try {
4349
- const { ItemProperty } = await Promise.resolve().then(function () { return ItemProperty$1; });
4350
- // Create instances for all metadata records in parallel
4596
+ const itemPropertyMod = await Promise.resolve().then(function () { return ItemProperty$1; });
4597
+ const { ItemProperty } = itemPropertyMod;
4598
+ const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
4599
+ const { Model } = await Promise.resolve().then(function () { return Model$1; });
4600
+ // Resolve Model and build property schemas for propertyRecordSchema (Fix 3)
4601
+ let propertySchemas = {};
4602
+ const model$1 = Model.getByName(modelName);
4603
+ if (model$1?.properties?.length) {
4604
+ propertySchemas = modelPropertiesToObject(model$1.properties);
4605
+ }
4606
+ // Create instances for all metadata records in parallel with propertyRecordSchema
4351
4607
  const createPromises = metadataRows.map(async (metaRow) => {
4352
4608
  try {
4353
- const property = await ItemProperty.find({
4354
- propertyName: metaRow.propertyName,
4609
+ const propertyName = metaRow.propertyName;
4610
+ if (!propertyName) {
4611
+ logger$k(`Metadata row missing propertyName, skipping`);
4612
+ return;
4613
+ }
4614
+ const createProps = {
4615
+ propertyName,
4355
4616
  seedLocalId,
4356
4617
  seedUid,
4357
- });
4618
+ modelName,
4619
+ propertyValue: metaRow.propertyValue ?? undefined,
4620
+ versionLocalId: metaRow.versionLocalId ?? undefined,
4621
+ versionUid: metaRow.versionUid ?? undefined,
4622
+ schemaUid: metaRow.schemaUid ?? undefined,
4623
+ propertyRecordSchema: propertySchemas[propertyName] ?? undefined,
4624
+ };
4625
+ const property = ItemProperty.create(createProps, { waitForReady: false });
4358
4626
  if (property) {
4359
- propertyInstances.set(metaRow.propertyName, property);
4360
- logger$k(`Created/cached ItemProperty instance for propertyName "${metaRow.propertyName}"`);
4627
+ propertyInstances.set(propertyName, property);
4628
+ logger$k(`Created/cached ItemProperty instance for propertyName "${propertyName}" with propertyRecordSchema: ${!!createProps.propertyRecordSchema}`);
4361
4629
  }
4362
4630
  else {
4363
- logger$k(`ItemProperty.find returned undefined for propertyName "${metaRow.propertyName}"`);
4631
+ logger$k(`ItemProperty.create returned undefined for propertyName "${propertyName}"`);
4364
4632
  }
4365
4633
  }
4366
4634
  catch (error) {
@@ -4380,7 +4648,6 @@ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid) =
4380
4648
  const loadOrCreateItem = fromCallback(({ sendBack, input: { context } }) => {
4381
4649
  const _loadOrCreateItem = async () => {
4382
4650
  const { seedLocalId, seedUid, modelName } = context;
4383
- console.log(`[loadOrCreateItem] Called for modelName: ${modelName}, seedLocalId: ${seedLocalId}, seedUid: ${seedUid}`);
4384
4651
  logger$k(`loadOrCreateItem called for modelName: ${modelName}, seedLocalId: ${seedLocalId}, seedUid: ${seedUid}`);
4385
4652
  if (!seedLocalId && !seedUid) {
4386
4653
  throw new Error('seedLocalId or seedUid is required');
@@ -4492,16 +4759,11 @@ const loadOrCreateItem = fromCallback(({ sendBack, input: { context } }) => {
4492
4759
  .from(metadata$1)
4493
4760
  .where(and(eq(metadata$1.seedLocalId, resolvedSeedLocalId), eq(metadata$1.versionLocalId, latestVersionLocalId)));
4494
4761
  logger$k(`Found ${metadataRecords.length} metadata records for version ${latestVersionLocalId}`);
4495
- console.log(`[loadOrCreateItem] Found ${metadataRecords.length} metadata records for version ${latestVersionLocalId}`);
4496
- if (metadataRecords.length > 0) {
4497
- console.log(`[loadOrCreateItem] Metadata property names:`, metadataRecords.map((r) => r.propertyName));
4498
- }
4499
4762
  // Step 4: Create ItemProperty instances from metadata records
4500
4763
  // This ensures they're in the cache when Item.properties getter is called
4501
4764
  const propertyInstances = metadataRecords.length > 0
4502
- ? await createItemPropertyInstances(metadataRecords, resolvedSeedLocalId, resolvedSeedUid)
4765
+ ? await createItemPropertyInstances(metadataRecords, resolvedSeedLocalId, resolvedSeedUid, modelName)
4503
4766
  : new Map();
4504
- console.log(`[loadOrCreateItem] Created ${propertyInstances.size} property instances:`, Array.from(propertyInstances.keys()));
4505
4767
  // Step 5: Return loaded item data with property instances
4506
4768
  sendBack({
4507
4769
  type: 'loadOrCreateItemSuccess',
@@ -4539,14 +4801,17 @@ const runPublish = fromCallback(({ sendBack, input: { context } }) => {
4539
4801
  return;
4540
4802
  }
4541
4803
  try {
4542
- const { Item } = await Promise.resolve().then(function () { return Item$1; });
4804
+ const itemMod = await Promise.resolve().then(function () { return Item$1; });
4805
+ const { Item } = itemMod;
4543
4806
  const item = await Item.find({ seedLocalId });
4544
4807
  if (!item) {
4545
4808
  sendBack({ type: 'publishError', error: new Error(`Item not found for seedLocalId: ${seedLocalId}`) });
4546
4809
  return;
4547
4810
  }
4548
- const { getPublishUploads } = await import('./getPublishUploads-Dc-HqhO8.js');
4549
- const { getPublishPayload } = await import('./getPublishPayload-uLm0AqN_.js');
4811
+ const getPublishUploadsMod = await import('./getPublishUploads-B0WArDfp.js');
4812
+ const { getPublishUploads } = getPublishUploadsMod;
4813
+ const getPublishPayloadMod = await import('./getPublishPayload-BRgULCf3.js');
4814
+ const { getPublishPayload } = getPublishPayloadMod;
4550
4815
  await getPublishUploads(item);
4551
4816
  // For first iteration: no Arweave sign/upload - pass empty uploadedTransactions.
4552
4817
  // Real upload/submit can be wired in later.
@@ -4718,14 +4983,18 @@ const itemMachineSingle = setup({
4718
4983
  actions: assign(({ context, event }) => {
4719
4984
  const item = event.item;
4720
4985
  const existingPropertyInstances = context.propertyInstances || new Map();
4721
- console.log(`[itemMachine] loadOrCreateItemSuccess for modelName: ${context.modelName}, propertyInstances from event:`, item.propertyInstances ? Array.from(item.propertyInstances.keys()) : 'none');
4722
- // Merge property instances from loadOrCreateItem
4986
+ // Merge property instances from loadOrCreateItem (Fix 2: preserve existing when it has propertyRecordSchema and incoming doesn't)
4723
4987
  if (item.propertyInstances) {
4724
4988
  for (const [propertyName, propertyInstance] of item.propertyInstances) {
4989
+ const existing = existingPropertyInstances.get(propertyName);
4990
+ const existingHasSchema = existing?.propertyDef;
4991
+ const incomingHasSchema = propertyInstance?.propertyDef;
4992
+ if (existingHasSchema && !incomingHasSchema) {
4993
+ continue; // Preserve existing instance with schema
4994
+ }
4725
4995
  existingPropertyInstances.set(propertyName, propertyInstance);
4726
4996
  }
4727
4997
  }
4728
- console.log(`[itemMachine] After merge, total propertyInstances:`, Array.from(existingPropertyInstances.keys()));
4729
4998
  return {
4730
4999
  ...context,
4731
5000
  seedLocalId: item.seedLocalId || context.seedLocalId,
@@ -5081,6 +5350,26 @@ const getItemData = async ({ modelName, seedLocalId, seedUid, }) => {
5081
5350
  }
5082
5351
  const seedRow = seedRows[0];
5083
5352
  const resolvedSeedLocalId = seedRow.seedLocalId;
5353
+ // Fix 5: Derive schemaName for multi-schema Model resolution (models -> model_schemas -> schemas)
5354
+ let schemaName;
5355
+ const normalizedModelName = modelName ? startCase(modelName) : (seedRow.type ? startCase(seedRow.type) : undefined);
5356
+ if (appDb && normalizedModelName) {
5357
+ try {
5358
+ const schemaRows = await appDb
5359
+ .select({ schemaName: schemas.name })
5360
+ .from(models$1)
5361
+ .innerJoin(modelSchemas, eq(models$1.id, modelSchemas.modelId))
5362
+ .innerJoin(schemas, eq(modelSchemas.schemaId, schemas.id))
5363
+ .where(eq(models$1.name, normalizedModelName))
5364
+ .limit(1);
5365
+ if (schemaRows.length > 0 && schemaRows[0].schemaName) {
5366
+ schemaName = schemaRows[0].schemaName;
5367
+ }
5368
+ }
5369
+ catch (error) {
5370
+ logger$i('[getItemData] Error deriving schemaName:', error);
5371
+ }
5372
+ }
5084
5373
  // Now get version data if it exists - query versions table directly
5085
5374
  let versionRow = {
5086
5375
  versionsCount: 0,
@@ -5111,6 +5400,7 @@ const getItemData = async ({ modelName, seedLocalId, seedUid, }) => {
5111
5400
  let itemData = {
5112
5401
  ...seedRow,
5113
5402
  ...versionRow,
5403
+ schemaName,
5114
5404
  };
5115
5405
  const propertiesData = await getItemProperties({
5116
5406
  seedLocalId,
@@ -5134,12 +5424,28 @@ const getItemData = async ({ modelName, seedLocalId, seedUid, }) => {
5134
5424
  return itemData;
5135
5425
  };
5136
5426
 
5137
- const getItemsData = async ({ modelName, deleted, }) => {
5427
+ const getItemsData = async ({ modelName, deleted, includeEas = false, addressFilter, }) => {
5138
5428
  const appDb = BaseDb.getAppDb();
5139
5429
  const conditions = [];
5430
+ if (!includeEas) {
5431
+ conditions.push(or(isNull(seeds.uid), eq(seeds.uid, '')));
5432
+ }
5140
5433
  if (modelName) {
5141
5434
  conditions.push(eq(seeds.type, toSnakeCase$1(modelName)));
5142
5435
  }
5436
+ if (addressFilter === 'owned') {
5437
+ const ownedAddresses = await getOwnedAddressesFromDb();
5438
+ if (ownedAddresses.length > 0) {
5439
+ conditions.push(or(inArray(seeds.publisher, ownedAddresses), isNull(seeds.publisher)));
5440
+ }
5441
+ }
5442
+ else if (addressFilter === 'watched') {
5443
+ const watchedAddresses = await getWatchedAddressesFromDb();
5444
+ if (watchedAddresses.length === 0) {
5445
+ return [];
5446
+ }
5447
+ conditions.push(inArray(seeds.publisher, watchedAddresses));
5448
+ }
5143
5449
  if (deleted) {
5144
5450
  conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
5145
5451
  }
@@ -5276,7 +5582,8 @@ const getModelSchemasFromEas = async () => {
5276
5582
  const queryClient = BaseQueryClient.getQueryClient();
5277
5583
  const easClient = BaseEasClient.getEasClient();
5278
5584
  // Dynamic import to break circular dependency
5279
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
5585
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
5586
+ const { Model } = modelMod;
5280
5587
  const allModels = await Model.all();
5281
5588
  const modelNames = allModels.map(m => m.modelName).filter((name) => !!name);
5282
5589
  // If there are no models, return empty array instead of querying
@@ -5630,7 +5937,8 @@ const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
5630
5937
  const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, populatedFromDb, schemaUid, } = context;
5631
5938
  const _resolveRelatedValue = async () => {
5632
5939
  // Use dynamic import to break circular dependency
5633
- const { ModelPropertyDataTypes } = await import('./index-LEY0Og1p.js');
5940
+ const schemaMod = await import('./index-BnF3MRZ8.js');
5941
+ const { ModelPropertyDataTypes } = schemaMod;
5634
5942
  if (!propertyValue || !isRelation || populatedFromDb) {
5635
5943
  return;
5636
5944
  }
@@ -5968,7 +6276,8 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
5968
6276
  // to use dynamically imported ModelPropertyDataTypes
5969
6277
  const _hydrateFromDb = async () => {
5970
6278
  // Use dynamic import to break circular dependency
5971
- const { ModelPropertyDataTypes } = await import('./index-LEY0Og1p.js');
6279
+ const schemaMod = await import('./index-BnF3MRZ8.js');
6280
+ const { ModelPropertyDataTypes } = schemaMod;
5972
6281
  const appDb = BaseDb.getAppDb();
5973
6282
  const whereClauses = [];
5974
6283
  // Re-check types with dynamically imported ModelPropertyDataTypes
@@ -6120,7 +6429,8 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
6120
6429
  if (propertyRecordSchema &&
6121
6430
  propertyRecordSchema.storageType &&
6122
6431
  propertyRecordSchema.storageType === 'ItemStorage') {
6123
- const { Item } = await Promise.resolve().then(function () { return Item$1; });
6432
+ const itemMod = await Promise.resolve().then(function () { return Item$1; });
6433
+ const { Item } = itemMod;
6124
6434
  const item = await Item.find({
6125
6435
  seedLocalId: seedLocalId ?? undefined,
6126
6436
  modelName,
@@ -6197,8 +6507,8 @@ const loadOrCreateProperty = fromCallback(({ sendBack, input: { context } }) =>
6197
6507
  const modelName = metadataRecord.modelType || context.modelName;
6198
6508
  if (modelName) {
6199
6509
  try {
6200
- // Normalize to PascalCase so "post" (from seeds.type/metadata) matches "Post" in models table
6201
- const normalizedModelName = startCase(modelName);
6510
+ // Normalize snake_case to PascalCase: "test_post" -> "TestPost" (startCase gives "Test Post" which fails)
6511
+ const normalizedModelName = upperFirst(camelCase(modelName));
6202
6512
  // Query properties table to get property schema
6203
6513
  const modelRecords = await db
6204
6514
  .select({ id: models$1.id })
@@ -6229,6 +6539,28 @@ const loadOrCreateProperty = fromCallback(({ sendBack, input: { context } }) =>
6229
6539
  // Continue without propertyRecordSchema
6230
6540
  }
6231
6541
  }
6542
+ if (!propertyRecordSchema && modelName) {
6543
+ try {
6544
+ const { Model } = await Promise.resolve().then(function () { return Model$1; });
6545
+ const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
6546
+ const normalizedModelName = upperFirst(camelCase(modelName));
6547
+ // Try PascalCase first ("post" -> "Post"); then findByModelType for names with spaces ("new_model" -> "New model")
6548
+ let model$1 = Model.getByName(normalizedModelName);
6549
+ if (!model$1?.properties?.length) {
6550
+ model$1 = Model.findByModelType(toSnakeCase$1(modelName));
6551
+ }
6552
+ if (model$1?.properties?.length) {
6553
+ const schemas = modelPropertiesToObject(model$1.properties);
6554
+ propertyRecordSchema = schemas[propertyName];
6555
+ if (propertyRecordSchema) {
6556
+ logger$f(`Fallback: loaded propertyRecordSchema from Model for propertyName "${propertyName}"`);
6557
+ }
6558
+ }
6559
+ }
6560
+ catch (error) {
6561
+ logger$f(`Fallback Model lookup failed for propertyName "${propertyName}": ${error}`);
6562
+ }
6563
+ }
6232
6564
  // Return loaded property data
6233
6565
  sendBack({
6234
6566
  type: 'loadOrCreatePropertySuccess',
@@ -6440,7 +6772,8 @@ const analyzeInput = fromCallback(({ sendBack, input: { context, event } }) => {
6440
6772
  }
6441
6773
  const _analyzeInput = async () => {
6442
6774
  // Use dynamic import to break circular dependency
6443
- const { ModelPropertyDataTypes } = await import('./index-LEY0Og1p.js');
6775
+ const schemaMod = await import('./index-BnF3MRZ8.js');
6776
+ const { ModelPropertyDataTypes } = schemaMod;
6444
6777
  let propertyName = propertyNameRaw;
6445
6778
  if (!propertyName) {
6446
6779
  throw new Error('propertyName is required');
@@ -6797,7 +7130,8 @@ const saveRelation = fromCallback(({ sendBack, input: { context, event } }) => {
6797
7130
  }
6798
7131
  const _saveRelation = async () => {
6799
7132
  // Use dynamic import to break circular dependency
6800
- const { ModelPropertyDataTypes } = await import('./index-LEY0Og1p.js');
7133
+ const schemaMod = await import('./index-BnF3MRZ8.js');
7134
+ const { ModelPropertyDataTypes } = schemaMod;
6801
7135
  if (!propertyNameRaw) {
6802
7136
  throw new Error('propertyName is required');
6803
7137
  }
@@ -7499,6 +7833,32 @@ Promise.resolve().then(function () { return Model$1; }).then(module => {
7499
7833
  // Return a default module structure to maintain type consistency
7500
7834
  return {};
7501
7835
  });
7836
+ /**
7837
+ * Resolve propertyRecordSchema from in-memory Model (Fix 6: enables value persistence when useItemProperty path doesn't go through loadOrCreateItem).
7838
+ * Tries getByName(pascalCase) first; if that fails (e.g. "New model" vs "NewModel"), falls back to findByModelType(modelType).
7839
+ */
7840
+ const resolvePropertyRecordSchemaFromModel = async (modelName, propertyName, modelType) => {
7841
+ if (!modelName && !modelType)
7842
+ return undefined;
7843
+ try {
7844
+ const { Model } = await Promise.resolve().then(function () { return Model$1; });
7845
+ const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
7846
+ let model$1 = modelName ? Model.getByName(modelName) : undefined;
7847
+ if (!model$1?.properties?.length && modelType) {
7848
+ model$1 = Model.findByModelType(modelType);
7849
+ }
7850
+ if (!model$1?.properties?.length)
7851
+ return undefined;
7852
+ const schemas = modelPropertiesToObject(model$1.properties);
7853
+ const schema = schemas[propertyName];
7854
+ return schema;
7855
+ }
7856
+ catch {
7857
+ return undefined;
7858
+ }
7859
+ };
7860
+ /** Convert modelType (snake_case from DB) to Model name (PascalCase). startCase adds spaces ("Test Post"); Model names are "TestPost". */
7861
+ const modelTypeToModelName = (modelType) => modelType ? upperFirst(camelCase(modelType)) : '';
7502
7862
  const logger$d = debug('seedSdk:property:class');
7503
7863
  // Define tracked properties for the Proxy
7504
7864
  // These properties will be read from/written to the actor context
@@ -7595,7 +7955,8 @@ class ItemProperty {
7595
7955
  return;
7596
7956
  }
7597
7957
  // Use dynamic import to break circular dependency
7598
- const { ModelPropertyDataTypes } = await import('./index-LEY0Og1p.js');
7958
+ const schemaMod = await import('./index-BnF3MRZ8.js');
7959
+ const { ModelPropertyDataTypes } = schemaMod;
7599
7960
  const { context } = snapshot;
7600
7961
  const { propertyRecordSchema } = context;
7601
7962
  if (context.seedLocalId && context.propertyName) {
@@ -7708,9 +8069,14 @@ class ItemProperty {
7708
8069
  setupState.subscriptionSetUp = true;
7709
8070
  logger(`[ItemProperty._setupLiveQuerySubscription] Setting up liveQuery for propertyName: ${propertyName}, seedLocalId: ${seedLocalId}`);
7710
8071
  try {
7711
- const { metadata } = await import('./index-2FcQHgKp.js').then(function (n) { return n.s; });
7712
- const { eq, and, isNotNull } = await import('drizzle-orm');
7713
- const { getMetadataLatest } = await Promise.resolve().then(function () { return metadataLatest; });
8072
+ const _mod_5 = await import('./index-BIPPEMVY.js');
8073
+ const _ns_5 = _mod_5.s;
8074
+ const seedSchemaMod = _ns_5;
8075
+ const { metadata } = seedSchemaMod;
8076
+ const drizzleMod = await import('drizzle-orm');
8077
+ const { eq, and, isNotNull } = drizzleMod;
8078
+ const metadataLatestMod = await Promise.resolve().then(function () { return metadataLatest; });
8079
+ const { getMetadataLatest } = metadataLatestMod;
7714
8080
  const db = BaseDb.getAppDb();
7715
8081
  if (!db) {
7716
8082
  logger('[ItemProperty._setupLiveQuerySubscription] Database not available');
@@ -7980,10 +8346,14 @@ class ItemProperty {
7980
8346
  return undefined;
7981
8347
  }
7982
8348
  // Ensure modelName for constructor: metadata may have modelType only, or neither (e.g. when Item passes it)
8349
+ // Use modelTypeToModelName: modelType is snake_case ("test_post"); Model names are PascalCase ("TestPost")
7983
8350
  const data = propertyData;
7984
8351
  const modelName = data.modelName ??
7985
- ((data.modelType ? startCase(data.modelType) : '') || modelNameOption || '');
7986
- foundProperty = ItemProperty.create({ ...propertyData, modelName }, { waitForReady: false });
8352
+ ((data.modelType ? modelTypeToModelName(data.modelType) : '') || modelNameOption || '');
8353
+ // Fix 6: resolve propertyRecordSchema from Model so value setter can persist (useItemProperty path)
8354
+ // Pass modelType for fallback: "New model" -> "new_model" can't be reversed to exact name; findByModelType handles it
8355
+ const propertyRecordSchema = await resolvePropertyRecordSchemaFromModel(modelName, propertyName, data.modelType);
8356
+ foundProperty = ItemProperty.create({ ...propertyData, modelName, propertyRecordSchema }, { waitForReady: false });
7987
8357
  }
7988
8358
  if (!foundProperty) {
7989
8359
  return undefined;
@@ -8006,9 +8376,16 @@ class ItemProperty {
8006
8376
  const propertiesData = await getItemProperties({ seedLocalId, seedUid });
8007
8377
  const instances = [];
8008
8378
  for (const data of propertiesData) {
8379
+ const d = data;
8380
+ const modelName = d.modelName ?? (d.modelType ? modelTypeToModelName(d.modelType) : '') ?? '';
8381
+ // Fix 6: resolve propertyRecordSchema from Model so value setter can persist
8382
+ const propertyRecordSchema = d.propertyName
8383
+ ? await resolvePropertyRecordSchemaFromModel(modelName, d.propertyName, d.modelType)
8384
+ : undefined;
8009
8385
  const createProps = {
8010
8386
  ...data,
8011
- modelName: data.modelName ?? data.modelType ?? '',
8387
+ modelName,
8388
+ propertyRecordSchema,
8012
8389
  };
8013
8390
  const instance = this.create(createProps, { waitForReady: false });
8014
8391
  if (instance) {
@@ -8143,10 +8520,15 @@ class ItemProperty {
8143
8520
  });
8144
8521
  }
8145
8522
  async save() {
8523
+ const ctx = this._getSnapshotContext();
8524
+ const { assertItemOwned } = await import('./ownership-CSsweVap.js');
8525
+ await assertItemOwned({
8526
+ seedLocalId: ctx?.seedLocalId ?? undefined,
8527
+ seedUid: ctx?.seedUid ?? undefined,
8528
+ });
8146
8529
  await waitFor(this._service, (snapshot) => !snapshot.context.isSaving && snapshot.value === 'idle', {
8147
8530
  timeout: 10000,
8148
8531
  });
8149
- const ctx = this._getSnapshotContext();
8150
8532
  const canonicalId = ctx?.seedLocalId ?? ctx?.seedUid;
8151
8533
  if (canonicalId) {
8152
8534
  eventEmitter.emit('itemProperty.saved', { seedLocalId: ctx.seedLocalId, seedUid: ctx.seedUid });
@@ -8223,8 +8605,12 @@ class ItemProperty {
8223
8605
  if (!propertyName || (!seedLocalId && !seedUid))
8224
8606
  return;
8225
8607
  if (db) {
8226
- const { metadata } = await import('./index-2FcQHgKp.js').then(function (n) { return n.s; });
8227
- const { and, eq, or } = await import('drizzle-orm');
8608
+ const _mod_6 = await import('./index-BIPPEMVY.js');
8609
+ const _ns_6 = _mod_6.s;
8610
+ const seedSchemaMod = _ns_6;
8611
+ const { metadata } = seedSchemaMod;
8612
+ const drizzleMod = await import('drizzle-orm');
8613
+ const { and, eq, or } = drizzleMod;
8228
8614
  const conditions = [eq(metadata.propertyName, propertyName)];
8229
8615
  if (seedLocalId && seedUid) {
8230
8616
  conditions.push(or(eq(metadata.seedLocalId, seedLocalId), eq(metadata.seedUid, seedUid)));
@@ -8239,7 +8625,8 @@ class ItemProperty {
8239
8625
  await db.delete(metadata).where(and(...conditions));
8240
8626
  }
8241
8627
  }
8242
- const { Item } = await Promise.resolve().then(function () { return Item$1; });
8628
+ const itemMod = await Promise.resolve().then(function () { return Item$1; });
8629
+ const { Item } = itemMod;
8243
8630
  const item = Item.getById((seedLocalId || seedUid));
8244
8631
  if (item) {
8245
8632
  item.getService().send({ type: 'removePropertyInstance', propertyName });
@@ -8265,14 +8652,22 @@ const createNewItem = async ({ modelName, ...propertyData }) => {
8265
8652
  const newSeedId = await createSeed({ type: seedType });
8266
8653
  const newVersionId = await createVersion({ seedLocalId: newSeedId, seedType: toSnakeCase$1(modelName) });
8267
8654
  // Dynamic import to break circular dependency
8268
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
8655
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
8656
+ const { Model } = modelMod;
8269
8657
  const model = await Model.getByNameAsync(modelName);
8270
8658
  const propertySchemas = model?.properties ? modelPropertiesToObject(model.properties) : undefined;
8271
- for (const [propertyName, propertyValue] of Object.entries(propertyData)) {
8272
- let propertyRecordSchema;
8273
- if (propertySchemas && propertySchemas[propertyName]) {
8274
- propertyRecordSchema = propertySchemas[propertyName];
8275
- }
8659
+ // Build set of all properties to create metadata for: union of model schema + propertyData
8660
+ // This ensures we create metadata for ALL model properties even when creating with no initial values
8661
+ // (fixes first-item persistence: loadOrCreateItem needs metadata rows to run createItemPropertyInstances)
8662
+ const allPropertyNames = new Set(Object.keys(propertyData));
8663
+ if (propertySchemas) {
8664
+ for (const name of Object.keys(propertySchemas)) {
8665
+ allPropertyNames.add(name);
8666
+ }
8667
+ }
8668
+ for (const propertyName of allPropertyNames) {
8669
+ const propertyValue = propertyData[propertyName];
8670
+ const propertyRecordSchema = propertySchemas?.[propertyName];
8276
8671
  await createMetadata({
8277
8672
  seedLocalId: newSeedId,
8278
8673
  versionLocalId: newVersionId,
@@ -8439,6 +8834,8 @@ class Item {
8439
8834
  });
8440
8835
  };
8441
8836
  this.publish = async () => {
8837
+ const { assertItemOwned } = await import('./ownership-CSsweVap.js');
8838
+ await assertItemOwned(this);
8442
8839
  this._service.send({ type: 'startPublish' });
8443
8840
  return new Promise((resolve, reject) => {
8444
8841
  let wasPublishing = false;
@@ -8473,12 +8870,14 @@ class Item {
8473
8870
  };
8474
8871
  this.getPublishUploads = async () => {
8475
8872
  // Use dynamic import to break circular dependency
8476
- const { getPublishUploads } = await import('./getPublishUploads-Dc-HqhO8.js');
8873
+ const getPublishUploadsMod = await import('./getPublishUploads-B0WArDfp.js');
8874
+ const { getPublishUploads } = getPublishUploadsMod;
8477
8875
  return await getPublishUploads(this);
8478
8876
  };
8479
8877
  this.getPublishPayload = async (uploadedTransactions) => {
8480
8878
  // Use dynamic import to break circular dependency
8481
- const { getPublishPayload } = await import('./getPublishPayload-uLm0AqN_.js');
8879
+ const getPublishPayloadMod = await import('./getPublishPayload-BRgULCf3.js');
8880
+ const { getPublishPayload } = getPublishPayloadMod;
8482
8881
  return await getPublishPayload(this, uploadedTransactions);
8483
8882
  };
8484
8883
  this.persistSeedUid = async () => {
@@ -8753,8 +9152,10 @@ class Item {
8753
9152
  let modelRecords;
8754
9153
  // If we have a schema name, join with modelSchemas to filter by schema
8755
9154
  if (schemaName) {
8756
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
8757
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
9155
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
9156
+ const { modelSchemas } = modelSchemaSchemaMod;
9157
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
9158
+ const { schemas: schemasTable } = schemaSchemaMod;
8758
9159
  modelRecords = await db
8759
9160
  .select({ id: models$1.id })
8760
9161
  .from(models$1)
@@ -9006,8 +9407,8 @@ class Item {
9006
9407
  }
9007
9408
  }
9008
9409
  static async all(modelName, deleted, options) {
9009
- const { waitForReady = false, readyTimeout = 5000 } = options ?? {};
9010
- const itemsData = await getItemsData({ modelName, deleted });
9410
+ const { waitForReady = false, readyTimeout = 5000, includeEas = false, addressFilter, } = options ?? {};
9411
+ const itemsData = await getItemsData({ modelName, deleted, includeEas, addressFilter });
9011
9412
  const itemInstances = [];
9012
9413
  for (const itemData of itemsData) {
9013
9414
  itemInstances.push(await Item.create({
@@ -9344,9 +9745,14 @@ class Item {
9344
9745
  setupState.subscriptionSetUp = true;
9345
9746
  logger(`[Item._setupLiveQuerySubscription] Setting up liveQuery for seedLocalId: ${seedLocalId}`);
9346
9747
  try {
9347
- const { seeds, versions, metadata } = await import('./index-2FcQHgKp.js').then(function (n) { return n.s; });
9348
- const { eq, and } = await import('drizzle-orm');
9349
- const { getVersionData } = await Promise.resolve().then(function () { return versionData; });
9748
+ const _mod_7 = await import('./index-BIPPEMVY.js');
9749
+ const _ns_7 = _mod_7.s;
9750
+ const seedSchemaMod = _ns_7;
9751
+ const { seeds, versions, metadata } = seedSchemaMod;
9752
+ const drizzleMod = await import('drizzle-orm');
9753
+ const { eq, and } = drizzleMod;
9754
+ const versionDataMod = await Promise.resolve().then(function () { return versionData; });
9755
+ const { getVersionData } = versionDataMod;
9350
9756
  const db = BaseDb.getAppDb();
9351
9757
  if (!db) {
9352
9758
  logger('[Item._setupLiveQuerySubscription] Database not available');
@@ -9389,7 +9795,8 @@ class Item {
9389
9795
  // CRITICAL: Create ItemProperty instances BEFORE updating context
9390
9796
  if (initialMetadataIds.length > 0) {
9391
9797
  try {
9392
- const { ItemProperty } = await Promise.resolve().then(function () { return ItemProperty$1; });
9798
+ const itemPropertyMod = await Promise.resolve().then(function () { return ItemProperty$1; });
9799
+ const { ItemProperty } = itemPropertyMod;
9393
9800
  const itemModelName = this._service.getSnapshot().context.modelName;
9394
9801
  const createPromises = initialMetadata.map(async (metaRow) => {
9395
9802
  try {
@@ -9497,7 +9904,8 @@ class Item {
9497
9904
  // CRITICAL: Create ItemProperty instances BEFORE updating context
9498
9905
  if (metadataRows.length > 0) {
9499
9906
  try {
9500
- const { ItemProperty } = await Promise.resolve().then(function () { return ItemProperty$1; });
9907
+ const itemPropertyMod = await Promise.resolve().then(function () { return ItemProperty$1; });
9908
+ const { ItemProperty } = itemPropertyMod;
9501
9909
  const itemModelName = this._service.getSnapshot().context.modelName;
9502
9910
  const createPromises = metadataRows.map(async (metaRow) => {
9503
9911
  try {
@@ -9618,6 +10026,8 @@ class Item {
9618
10026
  * Destroy the item: soft delete in DB, remove from caches, clean up subscriptions, stop service.
9619
10027
  */
9620
10028
  async destroy() {
10029
+ const { assertItemOwned } = await import('./ownership-CSsweVap.js');
10030
+ await assertItemOwned(this);
9621
10031
  const context = this._getSnapshotContext();
9622
10032
  const cacheKey = context.seedUid || context.seedLocalId;
9623
10033
  const cacheKeys = cacheKey ? [cacheKey] : [];
@@ -9659,6 +10069,24 @@ class ConflictError extends Error {
9659
10069
  }
9660
10070
  }
9661
10071
 
10072
+ /**
10073
+ * Normalizes AddressConfiguration to { owned, watched }.
10074
+ * - string[] -> { owned: addresses, watched: [] }
10075
+ * - { owned, watched? } -> { owned, watched: watched ?? [] }
10076
+ */
10077
+ function normalizeAddressConfig(addresses) {
10078
+ if (!addresses) {
10079
+ return { owned: [], watched: [] };
10080
+ }
10081
+ if (Array.isArray(addresses)) {
10082
+ return { owned: addresses, watched: [] };
10083
+ }
10084
+ return {
10085
+ owned: addresses.owned ?? [],
10086
+ watched: addresses.watched ?? [],
10087
+ };
10088
+ }
10089
+
9662
10090
  const isNode = () => {
9663
10091
  return (typeof process !== 'undefined' &&
9664
10092
  process.versions != null &&
@@ -9695,7 +10123,8 @@ const setupServicesEventHandlers = () => {
9695
10123
  const schemaStringToModelRecord = new Map();
9696
10124
  const getModelSchemas = async () => {
9697
10125
  // Dynamic import to break circular dependency
9698
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
10126
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
10127
+ const { Model } = modelMod;
9699
10128
  const allModels = await Model.all();
9700
10129
  const modelRecords = [];
9701
10130
  const appDb = BaseDb.getAppDb();
@@ -9797,6 +10226,7 @@ const saveEasSeedsToDb = async ({ itemSeeds }) => {
9797
10226
  uid: seed.id,
9798
10227
  schemaUid: seed.schemaId,
9799
10228
  type: seed.schema.schemaNames[0].name,
10229
+ publisher: seed.attester,
9800
10230
  createdAt: Date.now(),
9801
10231
  attestationCreatedAt: seed.timeCreated * 1000,
9802
10232
  attestationRaw,
@@ -9930,7 +10360,8 @@ const saveEasPropertiesToDb = async ({ itemProperties, itemSeeds, }) => {
9930
10360
  isSavingToDb = true;
9931
10361
  const propertyUids = itemProperties.map((property) => property.id);
9932
10362
  // Dynamic import to break circular dependency
9933
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
10363
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
10364
+ const { Model } = modelMod;
9934
10365
  const allModels = await Model.all();
9935
10366
  const models = Object.fromEntries(allModels.map(m => [m.modelName, m]));
9936
10367
  const appDb = BaseDb.getAppDb();
@@ -10115,6 +10546,10 @@ const getRelatedSeedsAndVersions = async () => {
10115
10546
  });
10116
10547
  };
10117
10548
  const syncDbWithEasHandler = throttle(async (_) => {
10549
+ const addresses = await getAllAddressesFromDb();
10550
+ if (!addresses || addresses.length === 0) {
10551
+ return;
10552
+ }
10118
10553
  const appDb = BaseDb.getAppDb();
10119
10554
  const { schemaStringToModelRecord } = await getModelSchemas();
10120
10555
  const modelSchemas = await getModelSchemasFromEas();
@@ -10152,7 +10587,6 @@ const syncDbWithEasHandler = throttle(async (_) => {
10152
10587
  if (schemaUids.length === 0) {
10153
10588
  return;
10154
10589
  }
10155
- const addresses = await getAddressesFromDb();
10156
10590
  const itemSeeds = await getSeedsFromSchemaUids({
10157
10591
  schemaUids,
10158
10592
  addresses,
@@ -10254,21 +10688,21 @@ const platformClassesInit = fromCallback(({ sendBack, input: { context, event }
10254
10688
  let PathResolver;
10255
10689
  let EasClient;
10256
10690
  if (isBrowser()) {
10257
- FileManager = (await import('./FileManager-C9zr4AJe.js')).FileManager;
10258
- Db = (await import('./Db-DjFdIdR9.js')).Db;
10259
- QueryClient = (await import('./QueryClient-ByKPdRmE.js')).QueryClient;
10260
- ArweaveClient = (await import('./ArweaveClient-CgWK-JgT.js')).ArweaveClient;
10261
- PathResolver = (await import('./PathResolver-CX6GHoTS.js')).PathResolver;
10262
- EasClient = (await import('./EasClient-Aojewp6P.js')).EasClient;
10691
+ FileManager = (await import('./FileManager-Cub9icdd.js')).FileManager;
10692
+ Db = (await import('./Db-Cq4q88X_.js')).Db;
10693
+ QueryClient = (await import('./QueryClient-Vs9KN5kS.js')).QueryClient;
10694
+ ArweaveClient = (await import('./ArweaveClient-nrTU_rhU.js')).ArweaveClient;
10695
+ PathResolver = (await import('./PathResolver-T1yEDECb.js')).PathResolver;
10696
+ EasClient = (await import('./EasClient-ZCIE6UQq.js')).EasClient;
10263
10697
  }
10264
10698
  else if (isNode()) {
10265
10699
  console.log('isNode');
10266
- FileManager = (await import('./FileManager-CxGJLw5C.js')).FileManager;
10267
- Db = (await import('./Db-DjofXdeU.js')).Db;
10268
- QueryClient = (await import('./QueryClient-Cb1iJO-x.js')).QueryClient;
10269
- ArweaveClient = (await import('./ArweaveClient-WcG8CZAE.js')).ArweaveClient;
10270
- PathResolver = (await import('./PathResolver-z_WX47_o.js')).PathResolver;
10271
- EasClient = (await import('./EasClient-BVFXp2O6.js')).EasClient;
10700
+ FileManager = (await import('./FileManager-HSFEess-.js')).FileManager;
10701
+ Db = (await import('./Db-CWKaeNQH.js')).Db;
10702
+ QueryClient = (await import('./QueryClient-DcKDQuwz.js')).QueryClient;
10703
+ ArweaveClient = (await import('./ArweaveClient-BdQaTOZ4.js')).ArweaveClient;
10704
+ PathResolver = (await import('./PathResolver-DVLBs_qi.js')).PathResolver;
10705
+ EasClient = (await import('./EasClient-Du9_TULE.js')).EasClient;
10272
10706
  }
10273
10707
  else {
10274
10708
  throw new Error(`Unable to determine environment. isBrowser()=${isBrowser()}, isNode()=${isNode()}. Platform-specific implementations could not be loaded.`);
@@ -10328,11 +10762,14 @@ const platformClassesInit = fromCallback(({ sendBack, input: { context, event }
10328
10762
  }
10329
10763
  // If it's an absolute path that exists or is a valid filesystem path, use it as-is
10330
10764
  }
10765
+ const normalizedAddresses = normalizeAddressConfig(addresses);
10331
10766
  sendBack({ type: 'updateContext', context: {
10332
10767
  models: models || {},
10333
10768
  endpoints,
10334
10769
  arweaveDomain,
10335
- addresses: addresses || [],
10770
+ addresses: normalizedAddresses.owned,
10771
+ ownedAddresses: normalizedAddresses.owned,
10772
+ watchedAddresses: normalizedAddresses.watched,
10336
10773
  filesDir: normalizedFilesDir,
10337
10774
  dbConfig,
10338
10775
  } });
@@ -10516,11 +10953,12 @@ const downloadAllFilesRequestHandler = async ({ endpoints, eventId, }) => {
10516
10953
  const downloadAllFilesBinaryRequestHandler = async () => {
10517
10954
  let addresses;
10518
10955
  if (BaseDb.isAppDbReady()) {
10519
- addresses = await getAddressesFromDb();
10956
+ addresses = await getAllAddressesFromDb();
10520
10957
  }
10521
10958
  if (!BaseDb.isAppDbReady()) {
10522
10959
  // Wait for ClientManager to be ready (DB_INIT state or later)
10523
- const { getClient } = await Promise.resolve().then(function () { return ClientManager$1; });
10960
+ const clientManagerMod = await Promise.resolve().then(function () { return ClientManager$1; });
10961
+ const { getClient } = clientManagerMod;
10524
10962
  const clientManager = getClient();
10525
10963
  const clientService = clientManager.getService();
10526
10964
  await waitFor(clientService, (snapshot) => {
@@ -10532,7 +10970,7 @@ const downloadAllFilesBinaryRequestHandler = async () => {
10532
10970
  state === 'addModelsToDb' ||
10533
10971
  state === 'idle';
10534
10972
  }, { timeout: 30000 });
10535
- addresses = await getAddressesFromDb();
10973
+ addresses = await getAllAddressesFromDb();
10536
10974
  }
10537
10975
  if (!addresses || addresses.length === 0) {
10538
10976
  return;
@@ -10884,7 +11322,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
10884
11322
  const logger$5 = debug('seedSdk:client:actors:saveConfig');
10885
11323
  const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
10886
11324
  logger$5('saveConfig starting');
10887
- const { endpoints, addresses, arweaveDomain } = context;
11325
+ const { endpoints, addresses, ownedAddresses, watchedAddresses, arweaveDomain } = context;
10888
11326
  // Validate endpoints - required for proper initialization
10889
11327
  // If endpoints are missing or invalid, initialization should fail
10890
11328
  if (!endpoints || !endpoints.filePaths || !endpoints.files) {
@@ -10904,7 +11342,9 @@ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
10904
11342
  throw new Error('App DB not found');
10905
11343
  }
10906
11344
  const endpointsValueString = JSON.stringify(endpoints);
10907
- const addressesValueString = JSON.stringify(addresses);
11345
+ const owned = ownedAddresses ?? addresses ?? [];
11346
+ const watched = watchedAddresses ?? [];
11347
+ const addressesValueString = JSON.stringify({ owned, watched });
10908
11348
  // TODO: Figure out how to define on conflict with multiple rows added
10909
11349
  await appDb
10910
11350
  .insert(appState)
@@ -10918,7 +11358,7 @@ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
10918
11358
  value: endpointsValueString,
10919
11359
  },
10920
11360
  });
10921
- if (addresses) {
11361
+ if (owned.length > 0 || watched.length > 0) {
10922
11362
  await appDb
10923
11363
  .insert(appState)
10924
11364
  .values({
@@ -11458,8 +11898,10 @@ const logger$3 = debug('seedSdk:imports:json');
11458
11898
  * @returns Promise that resolves when properties are found, or rejects if not found after max retries
11459
11899
  */
11460
11900
  const verifyPropertiesPersisted = async (db, modelId, modelName, maxRetries = 10, retryDelay = 100) => {
11461
- const { properties: propertiesTable } = await Promise.resolve().then(function () { return ModelSchema; });
11462
- const { eq } = await import('drizzle-orm');
11901
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
11902
+ const { properties: propertiesTable } = modelSchemaMod;
11903
+ const drizzleMod = await import('drizzle-orm');
11904
+ const { eq } = drizzleMod;
11463
11905
  console.log(`[verifyPropertiesPersisted] Starting verification for model "${modelName}" (modelId: ${modelId})`);
11464
11906
  for (let attempt = 0; attempt < maxRetries; attempt++) {
11465
11907
  const props = await db
@@ -11775,7 +12217,8 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11775
12217
  schemaFile = transformImportToSchemaFile(importData, version);
11776
12218
  }
11777
12219
  // Check if this is an internal SDK schema (should not create files in app directory)
11778
- const { isInternalSchema } = await Promise.resolve().then(function () { return constants; });
12220
+ const constantsMod = await Promise.resolve().then(function () { return constants; });
12221
+ const { isInternalSchema } = constantsMod;
11779
12222
  const isInternal = isInternalSchema(schemaFile.metadata.name, schemaFile.id);
11780
12223
  if (isInternal) {
11781
12224
  logger$3(`Skipping file creation for internal schema: ${schemaFile.metadata.name}`);
@@ -11869,7 +12312,8 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11869
12312
  updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
11870
12313
  };
11871
12314
  // Use dynamic import to break circular dependency
11872
- const { addSchemaToDb, addModelsToDb } = await Promise.resolve().then(function () { return db; });
12315
+ const dbMod = await Promise.resolve().then(function () { return db; });
12316
+ const { addSchemaToDb, addModelsToDb } = dbMod;
11873
12317
  // Try to add schema and models to database if database is available
11874
12318
  try {
11875
12319
  const db = BaseDb.getAppDb();
@@ -11890,9 +12334,12 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11890
12334
  // CRITICAL: Verify all expected models are linked via join table
11891
12335
  // Retry querying until all models are visible (browser environments may have delays)
11892
12336
  const expectedModelNames = Object.keys(schemaFile.models || {});
11893
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
11894
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
11895
- const { eq, and } = await import('drizzle-orm');
12337
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
12338
+ const { modelSchemas } = modelSchemaSchemaMod;
12339
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
12340
+ const { models: modelsTable } = modelSchemaMod;
12341
+ const drizzleMod = await import('drizzle-orm');
12342
+ const { eq, and } = drizzleMod;
11896
12343
  let allModelsLinked = false;
11897
12344
  for (let attempt = 0; attempt < 10; attempt++) {
11898
12345
  const modelLinks = await db
@@ -12063,10 +12510,11 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
12063
12510
  }
12064
12511
  }
12065
12512
  }
12066
- // After properties are created, ensure schemaFile has the correct IDs from database
12513
+ // After properties are created (internal schema path), ensure schemaFile has the correct IDs from database
12067
12514
  // Query the database to get the actual schemaFileId values that were used
12068
12515
  // This ensures schemaData matches what's actually in the database
12069
- const { properties: propertiesTable } = await Promise.resolve().then(function () { return ModelSchema; });
12516
+ const modelSchemaMod1 = await Promise.resolve().then(function () { return ModelSchema; });
12517
+ const { properties: propertiesTable } = modelSchemaMod1;
12070
12518
  let schemaFileUpdated = false;
12071
12519
  for (const [modelName, modelFileId] of modelFileIds.entries()) {
12072
12520
  // Get model record to find modelId
@@ -12099,7 +12547,8 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
12099
12547
  // This is important even if nothing changed, to ensure consistency
12100
12548
  const updatedSchemaData = JSON.stringify(schemaFile, null, 2);
12101
12549
  // Update the schema record in the database with current schemaData
12102
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
12550
+ const schemaSchemaMod1 = await Promise.resolve().then(function () { return SchemaSchema; });
12551
+ const { schemas: schemasTable } = schemaSchemaMod1;
12103
12552
  await db
12104
12553
  .update(schemasTable)
12105
12554
  .set({ schemaData: updatedSchemaData })
@@ -12313,7 +12762,8 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12313
12762
  updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
12314
12763
  };
12315
12764
  // Use dynamic import to break circular dependency
12316
- const { addSchemaToDb, addModelsToDb } = await Promise.resolve().then(function () { return db; });
12765
+ const dbMod = await Promise.resolve().then(function () { return db; });
12766
+ const { addSchemaToDb, addModelsToDb } = dbMod;
12317
12767
  // Try to add schema and models to database if database is available
12318
12768
  try {
12319
12769
  const db = BaseDb.getAppDb();
@@ -12335,9 +12785,12 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12335
12785
  await new Promise(resolve => setTimeout(resolve, 200));
12336
12786
  console.log(`[importJsonSchema] Starting property verification for schema "${schemaName}" (schemaRecord.id: ${schemaRecord.id})`);
12337
12787
  // Query the database to get model IDs that were just created
12338
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
12339
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
12340
- const { eq } = await import('drizzle-orm');
12788
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
12789
+ const { modelSchemas } = modelSchemaSchemaMod;
12790
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
12791
+ const { models: modelsTable } = modelSchemaMod;
12792
+ const drizzleMod = await import('drizzle-orm');
12793
+ const { eq } = drizzleMod;
12341
12794
  // Try to find models directly by schemaFileId first (more reliable than join table)
12342
12795
  const seedModelId = modelFileIds.get('Seed');
12343
12796
  let seedModel = [];
@@ -12399,10 +12852,11 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12399
12852
  }
12400
12853
  }
12401
12854
  }
12402
- // After properties are created, ensure schemaFile has the correct IDs from database
12855
+ // After properties are created (file path), ensure schemaFile has the correct IDs from database
12403
12856
  // Query the database to get the actual schemaFileId values that were used
12404
12857
  // This ensures schemaData matches what's actually in the database
12405
- const { properties: propertiesTable } = await Promise.resolve().then(function () { return ModelSchema; });
12858
+ const modelSchemaMod2 = await Promise.resolve().then(function () { return ModelSchema; });
12859
+ const { properties: propertiesTable } = modelSchemaMod2;
12406
12860
  let schemaFileUpdated = false;
12407
12861
  for (const [modelName, modelFileId] of modelFileIds.entries()) {
12408
12862
  // Get model record to find modelId
@@ -12435,7 +12889,8 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12435
12889
  // This is important even if nothing changed, to ensure consistency
12436
12890
  const updatedSchemaData = JSON.stringify(schemaFile, null, 2);
12437
12891
  // Update the schema record in the database with current schemaData
12438
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
12892
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
12893
+ const { schemas: schemasTable } = schemaSchemaMod;
12439
12894
  await db
12440
12895
  .update(schemasTable)
12441
12896
  .set({ schemaData: updatedSchemaData })
@@ -12476,7 +12931,8 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12476
12931
  */
12477
12932
  const createModelFromJson = async (modelName, modelDef, schemaName, modelFileId, // Optional modelFileId from JSON file
12478
12933
  propertyFileIds) => {
12479
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
12934
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
12935
+ const { Model } = modelMod;
12480
12936
  // Convert JSON properties to schema format
12481
12937
  const convertedProperties = {};
12482
12938
  if (modelDef.properties) {
@@ -12981,14 +13437,17 @@ const clientManagerMachine = setup({
12981
13437
  actions: [
12982
13438
  assign(({ event, spawn }) => {
12983
13439
  const { addresses } = event;
13440
+ const normalized = normalizeAddressConfig(addresses);
12984
13441
  spawn('saveAppState', {
12985
13442
  input: {
12986
13443
  key: 'addresses',
12987
- value: addresses,
13444
+ value: { owned: normalized.owned, watched: normalized.watched },
12988
13445
  },
12989
13446
  });
12990
13447
  return {
12991
- addresses,
13448
+ addresses: normalized.owned,
13449
+ ownedAddresses: normalized.owned,
13450
+ watchedAddresses: normalized.watched,
12992
13451
  isSaving: true,
12993
13452
  };
12994
13453
  })
@@ -13061,6 +13520,8 @@ const clientInstance = {
13061
13520
  isSaving: false,
13062
13521
  endpoints: undefined,
13063
13522
  addresses: undefined,
13523
+ ownedAddresses: undefined,
13524
+ watchedAddresses: undefined,
13064
13525
  models: undefined,
13065
13526
  arweaveDomain: undefined,
13066
13527
  filesDir: undefined,
@@ -13115,9 +13576,17 @@ const clientInstance = {
13115
13576
  },
13116
13577
  getAddresses: async () => {
13117
13578
  ensureInitialized();
13118
- const db = await BaseDb.getAppDb();
13119
- const results = await db.select().from(appState).where(eq(appState.key, 'addresses'));
13120
- return JSON.parse(results[0]?.value);
13579
+ const owned = await getOwnedAddressesFromDb();
13580
+ const watched = await getWatchedAddressesFromDb();
13581
+ return { owned, watched };
13582
+ },
13583
+ getOwnedAddresses: async () => {
13584
+ ensureInitialized();
13585
+ return getOwnedAddressesFromDb();
13586
+ },
13587
+ getWatchedAddresses: async () => {
13588
+ ensureInitialized();
13589
+ return getWatchedAddressesFromDb();
13121
13590
  },
13122
13591
  addModel: async (modelDef) => {
13123
13592
  const db = await BaseDb.getAppDb();
@@ -13327,7 +13796,7 @@ const saveDraftLogger = debug('seedSdk:model:saveDraftToDb');
13327
13796
  // Lazy import cache for ModelProperty to avoid circular dependency
13328
13797
  // Eagerly start loading to minimize delay on first access
13329
13798
  let ModelPropertyClass = null;
13330
- const modelPropertyImportPromise = import('./ModelProperty-CGdkocQ8.js')
13799
+ const modelPropertyImportPromise = import('./ModelProperty-D4zaeIOT.js')
13331
13800
  .then(module => {
13332
13801
  ModelPropertyClass = module.ModelProperty;
13333
13802
  return ModelPropertyClass;
@@ -13344,7 +13813,7 @@ function getModelProperty() {
13344
13813
  }
13345
13814
  // Lazy import cache for Schema to avoid circular dependency
13346
13815
  let SchemaClass = null;
13347
- const schemaImportPromise = import('./Schema-D1eqDHyt.js').then(function (n) { return n.b; })
13816
+ const schemaImportPromise = (async () => { const _mod_8 = await import('./Schema-SbwqmoMM.js'); return _mod_8.b; })()
13348
13817
  .then(module => {
13349
13818
  SchemaClass = module.Schema;
13350
13819
  return SchemaClass;
@@ -13860,7 +14329,11 @@ class Model {
13860
14329
  // Step 11: Register with schema if requested, OR trigger write if properties are provided
13861
14330
  // If properties are provided, we need to write the model to get modelId for property creation
13862
14331
  // If schema provided, trigger write process instead of registration
13863
- const shouldTriggerWrite = (registerWithSchema && schemaInstance) || (options?.properties && Object.keys(options.properties).length > 0);
14332
+ // When schemaName is passed as string (e.g. useCreateModel), we must trigger write so runtime-created
14333
+ // models get persisted to DB and show up in useModels (which queries the database).
14334
+ const shouldTriggerWrite = (registerWithSchema && schemaInstance) ||
14335
+ (options?.properties && Object.keys(options.properties).length > 0) ||
14336
+ typeof schemaNameOrSchema === 'string';
13864
14337
  if (shouldTriggerWrite) {
13865
14338
  queueMicrotask(async () => {
13866
14339
  try {
@@ -14143,6 +14616,22 @@ class Model {
14143
14616
  }
14144
14617
  return undefined;
14145
14618
  }
14619
+ /**
14620
+ * Find Model by modelType (snake_case from DB/metadata).
14621
+ * Handles model names with spaces: "new_model" -> finds "New model" (toSnakeCase("New model") === "new_model").
14622
+ */
14623
+ static findByModelType(modelType) {
14624
+ if (!modelType)
14625
+ return undefined;
14626
+ for (const [nameKey, id] of this.instanceCacheByName.entries()) {
14627
+ const parts = nameKey.split(':', 2);
14628
+ const cachedModelName = parts[1];
14629
+ if (cachedModelName && toSnakeCase$1(cachedModelName) === modelType) {
14630
+ return this.getById(id);
14631
+ }
14632
+ }
14633
+ return undefined;
14634
+ }
14146
14635
  /**
14147
14636
  * Get all Model instances for a schema from cache only (synchronous).
14148
14637
  * Includes models created at runtime via Model.create() that may not yet be in schema context.
@@ -14845,7 +15334,8 @@ class Model {
14845
15334
  doDestroy: async () => {
14846
15335
  const db = BaseDb.getAppDb();
14847
15336
  if (db && modelFileId) {
14848
- const { eq } = await import('drizzle-orm');
15337
+ const drizzleMod = await import('drizzle-orm');
15338
+ const { eq } = drizzleMod;
14849
15339
  const modelRecords = await db
14850
15340
  .select()
14851
15341
  .from(models$1)
@@ -15176,5 +15666,5 @@ const Date$1 = () => PropertyConstructor(Property.Date());
15176
15666
  Type.Record(Type.String(), Type.Any());
15177
15667
  Type.Record(Type.String(), TProperty);
15178
15668
 
15179
- export { getItemData as $, config as A, Boolean$1 as B, metadata$1 as C, Date$1 as D, EAS_ENDPOINT as E, modelRelations as F, modelSchemas as G, modelUids as H, Image as I, Json as J, modelsRelations as K, List as L, Model as M, Number$1 as N, propertiesRelations as O, Property as P, propertyUidRelations as Q, Relation as R, SEED_CONFIG_FILE as S, TPropertyDataType as T, propertyUids as U, VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA as V, schemas as W, seeds as X, versions as Y, ZERO_BYTES32 as Z, graphql as _, ModelPropertyDataTypes as a, Item as a0, saveAppState as a1, addModelsToDb$1 as a2, SCHEMA_NJK as a3, ItemProperty as a4, eventEmitter as a5, ClientManager as a6, INIT_SCRIPT_SUCCESS_MESSAGE as a7, SCHEMA_TS as a8, importJsonSchema as a9, SeedModels as aA, getArweaveUrlForTransaction as aB, createSchema as aC, readSchema as aD, listCompleteSchemaFiles as aE, getSchemaNameFromId as aF, getLatestSchemaVersion as aG, createModelsFromJson as aH, SEED_PROTOCOL_SCHEMA_NAME as aI, addSchemaToDb as aJ, loadModelsFromDbForSchema as aK, isInternalSchema as aL, createModelFromJson as aM, ConflictError as aN, unloadEntity as aO, clearDestroySubscriptions as aP, setupEntityLiveQuery as aQ, ModelSchema as aR, BaseFileManager$1 as aS, db as aT, schema as aU, SEEDPROTOCOL_Seed_Protocol_v1 as aV, Model$1 as aW, loadSchemaFromFile as aa, readJsonImportFile as ab, transformImportToSchemaFile as ac, writeProcessMachine as ad, generateId as ae, waitForEntityIdle as af, createReactiveProxy as ag, findEntity as ah, forceRemoveFromCaches as ai, runDestroyLifecycle as aj, getModelIdByFileId as ak, getModelId as al, getClient as am, ClientManagerState as an, getVersionData$1 as ao, createNewItem as ap, loadAllSchemasFromDb as aq, getSeedsBySchemaName as ar, GET_SEEDS as as, getItemVersionsFromEas as at, getItemPropertiesFromEas as au, setSchemaUidForSchemaDefinition as av, parseEasRelationPropertyName as aw, getModelSchemasFromEas as ax, getSchemaUidBySchemaName as ay, getSeedsFromSchemaUids as az, TStorageType as b, TProperty as c, TPropertyConstructor as d, PropertyMetadataKey as e, PropertyConstructor as f, Text as g, TValidationRules as h, getSchemaUidForModel as i, getCorrectId as j, defaultAttestationData as k, INTERNAL_DATA_TYPES as l, getSchemaUidForSchemaDefinition as m, getSchemaForItemProperty as n, modelPropertiesToObject as o, BaseDb as p, models$1 as q, properties as r, BaseQueryClient as s, toSnakeCase as t, BaseArweaveClient as u, BasePathResolver as v, BaseEasClient as w, BaseFileManager as x, appState as y, SEED_CONFIG_FALLBACKS as z };
15180
- //# sourceMappingURL=index-DPll6EAp.js.map
15669
+ export { graphql as $, appState as A, Boolean$1 as B, SEED_CONFIG_FALLBACKS as C, Date$1 as D, EAS_ENDPOINT as E, config as F, metadata$1 as G, modelRelations as H, Image as I, Json as J, modelSchemas as K, List as L, Model as M, Number$1 as N, modelUids as O, Property as P, modelsRelations as Q, Relation as R, SEED_CONFIG_FILE as S, TPropertyDataType as T, propertiesRelations as U, VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA as V, propertyUidRelations as W, propertyUids as X, schemas as Y, ZERO_BYTES32 as Z, versions as _, ModelPropertyDataTypes as a, getItemData as a0, Item as a1, saveAppState as a2, addModelsToDb$1 as a3, SCHEMA_NJK as a4, ItemProperty as a5, eventEmitter as a6, ClientManager as a7, INIT_SCRIPT_SUCCESS_MESSAGE as a8, SCHEMA_TS as a9, getSeedsFromSchemaUids as aA, SeedModels as aB, getArweaveUrlForTransaction as aC, createSchema as aD, readSchema as aE, listCompleteSchemaFiles as aF, getSchemaNameFromId as aG, getLatestSchemaVersion as aH, createModelsFromJson as aI, SEED_PROTOCOL_SCHEMA_NAME as aJ, addSchemaToDb as aK, loadModelsFromDbForSchema as aL, isInternalSchema as aM, createModelFromJson as aN, ConflictError as aO, unloadEntity as aP, clearDestroySubscriptions as aQ, setupEntityLiveQuery as aR, ModelSchema as aS, BaseFileManager$1 as aT, db as aU, schema as aV, SEEDPROTOCOL_Seed_Protocol_v1 as aW, Model$1 as aX, importJsonSchema as aa, loadSchemaFromFile as ab, readJsonImportFile as ac, transformImportToSchemaFile as ad, writeProcessMachine as ae, generateId as af, waitForEntityIdle as ag, createReactiveProxy as ah, findEntity as ai, forceRemoveFromCaches as aj, runDestroyLifecycle as ak, getModelIdByFileId as al, getModelId as am, getClient as an, ClientManagerState as ao, getVersionData$1 as ap, createNewItem as aq, loadAllSchemasFromDb as ar, getSeedsBySchemaName as as, GET_SEEDS as at, getItemVersionsFromEas as au, getItemPropertiesFromEas as av, setSchemaUidForSchemaDefinition as aw, parseEasRelationPropertyName as ax, getModelSchemasFromEas as ay, getSchemaUidBySchemaName as az, TStorageType as b, TProperty as c, TPropertyConstructor as d, PropertyMetadataKey as e, PropertyConstructor as f, Text as g, TValidationRules as h, getOwnedAddressesFromDb as i, BaseDb as j, getSchemaUidForModel as k, getCorrectId as l, defaultAttestationData as m, INTERNAL_DATA_TYPES as n, getSchemaUidForSchemaDefinition as o, getSchemaForItemProperty as p, modelPropertiesToObject as q, models$1 as r, seeds as s, toSnakeCase as t, properties as u, BaseQueryClient as v, BaseArweaveClient as w, BasePathResolver as x, BaseEasClient as y, BaseFileManager as z };
15670
+ //# sourceMappingURL=index-zsq08F5p.js.map