@seedprotocol/sdk 0.1.67 → 0.1.69

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 (30) hide show
  1. package/dist/{index-BJn9UAOX.js → index-VSlWKRIZ.js} +6 -6
  2. package/dist/index-VSlWKRIZ.js.map +1 -0
  3. package/dist/{index-nGDuz8NN.js → index-YshZfGRu.js} +569 -535
  4. package/dist/index-YshZfGRu.js.map +1 -0
  5. package/dist/main.js +4 -4
  6. package/dist/{seed.schema.config-miFErQ6h.js → seed.schema.config-BEvGEHkp.js} +5 -5
  7. package/dist/{seed.schema.config-miFErQ6h.js.map → seed.schema.config-BEvGEHkp.js.map} +1 -1
  8. package/dist/src/createMetadata.ts +4 -0
  9. package/dist/src/getItems.ts +2 -0
  10. package/dist/src/getVersionData.ts +1 -1
  11. package/dist/src/hydrateFromDb.ts +19 -0
  12. package/dist/src/propertyMachine.ts +12 -0
  13. package/dist/src/saveImageSrc.ts +11 -2
  14. package/dist/src/updateItemPropertyValue.ts +230 -0
  15. package/dist/src/write.ts +2 -228
  16. package/dist/types/src/browser/db/read/getItems.d.ts.map +1 -1
  17. package/dist/types/src/browser/db/read/getVersionData.d.ts +1 -1
  18. package/dist/types/src/browser/db/read/getVersionData.d.ts.map +1 -1
  19. package/dist/types/src/browser/db/write/createMetadata.d.ts.map +1 -1
  20. package/dist/types/src/browser/db/write/updateItemPropertyValue.d.ts +5 -0
  21. package/dist/types/src/browser/db/write/updateItemPropertyValue.d.ts.map +1 -0
  22. package/dist/types/src/browser/db/write.d.ts +0 -16
  23. package/dist/types/src/browser/db/write.d.ts.map +1 -1
  24. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  25. package/dist/types/src/browser/property/actors/saveValueToDb/index.d.ts.map +1 -1
  26. package/dist/types/src/browser/property/actors/saveValueToDb/saveImageSrc.d.ts.map +1 -1
  27. package/dist/types/src/browser/property/propertyMachine.d.ts.map +1 -1
  28. package/package.json +1 -1
  29. package/dist/index-BJn9UAOX.js.map +0 -1
  30. package/dist/index-nGDuz8NN.js.map +0 -1
@@ -11,15 +11,15 @@ import * as nanoIdDictionary from 'nanoid-dictionary';
11
11
  import debug from 'debug';
12
12
  import { startCase, debounce, camelCase, orderBy } from 'lodash-es';
13
13
  import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
14
+ import { useState, useEffect, useRef, useCallback } from 'react';
15
+ import { BehaviorSubject } from 'rxjs';
16
+ import { immerable, produce, enableMapSet } from 'immer';
17
+ import pluralize from 'pluralize';
14
18
  import EventEmitter from 'eventemitter3';
15
19
  import { QueryClient } from '@tanstack/react-query';
16
20
  import { GraphQLClient } from 'graphql-request';
17
21
  import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
18
22
  import { persistQueryClient } from '@tanstack/react-query-persist-client';
19
- import { useState, useEffect, useRef, useCallback } from 'react';
20
- import { BehaviorSubject } from 'rxjs';
21
- import { immerable, produce, enableMapSet } from 'immer';
22
- import pluralize from 'pluralize';
23
23
  import { createBrowserInspector } from '@statelyai/inspect';
24
24
  import { drizzle } from 'drizzle-orm/sqlite-proxy';
25
25
  import { WebAccess } from '@zenfs/dom';
@@ -1004,6 +1004,24 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1004
1004
  typeof propertyValueFromDb === 'string') {
1005
1005
  propertyValueProcessed = propertyValueFromDb.split(',');
1006
1006
  }
1007
+ if (seedLocalIdFromDb === 'sAFXuO7Uez') {
1008
+ console.log(`[hydrateFromDb] sending updateContext with:`, {
1009
+ type: 'updateContext',
1010
+ localId,
1011
+ uid,
1012
+ propertyValue: propertyValueProcessed,
1013
+ seedLocalId: seedLocalIdFromDb,
1014
+ seedUid: seedUidFromDb,
1015
+ versionLocalId: versionLocalIdFromDb,
1016
+ versionUid: versionUidFromDb,
1017
+ schemaUid: schemaUidFromDb,
1018
+ refValueType,
1019
+ localStorageDir,
1020
+ resolvedValue: refResolvedValue,
1021
+ resolvedDisplayValue: refResolvedDisplayValue,
1022
+ renderValue: refResolvedDisplayValue,
1023
+ });
1024
+ }
1007
1025
  sendBack({
1008
1026
  type: 'updateContext',
1009
1027
  localId,
@@ -1023,7 +1041,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1023
1041
  if (propertyRecordSchema &&
1024
1042
  propertyRecordSchema.storageType &&
1025
1043
  propertyRecordSchema.storageType === 'ItemStorage') {
1026
- const { Item } = yield import('./index-BJn9UAOX.js');
1044
+ const { Item } = yield import('./index-VSlWKRIZ.js');
1027
1045
  const item = yield Item.find({
1028
1046
  seedLocalId,
1029
1047
  modelName: itemModelName,
@@ -1046,47 +1064,59 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1046
1064
  });
1047
1065
  });
1048
1066
 
1049
- const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
1067
+ const getVersionData$1 = () => {
1050
1068
  const appDb = getAppDb();
1051
- let query;
1052
- const queryBase = appDb.select().from(seeds);
1053
- if (seedLocalId) {
1054
- query = queryBase.where(eq(seeds.localId, seedLocalId));
1055
- }
1056
- if (seedUid) {
1057
- query = queryBase.where(eq(seeds.uid, seedUid));
1058
- }
1059
- const rows = yield query;
1060
- if (!rows || !rows.length) {
1061
- return;
1062
- }
1063
- return rows[0];
1064
- });
1069
+ return appDb.$with('versionData').as(appDb
1070
+ .select({
1071
+ seedLocalId: versions.seedLocalId,
1072
+ seedUid: versions.seedUid,
1073
+ latestVersionUid: versions.uid,
1074
+ latestVersionLocalId: versions.localId,
1075
+ versionsCount: count(versions.localId).as('versionsCount'),
1076
+ lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
1077
+ lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
1078
+ })
1079
+ .from(versions)
1080
+ .groupBy(versions.seedLocalId));
1081
+ };
1065
1082
 
1066
- const getVersionData$1 = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
1083
+ const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
1067
1084
  const appDb = getAppDb();
1068
- const whereClauses = [];
1069
- if (seedLocalId) {
1070
- whereClauses.push(eq(versions.localId, seedLocalId));
1071
- }
1072
- if (localId) {
1073
- whereClauses.push(eq(versions.localId, localId));
1085
+ const conditions = [];
1086
+ if (modelName) {
1087
+ conditions.push(eq(seeds.type, modelName.toLowerCase()));
1074
1088
  }
1075
- if (uid) {
1076
- whereClauses.push(eq(versions.uid, uid));
1089
+ if (deleted) {
1090
+ conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
1077
1091
  }
1078
- const queryRows = yield appDb
1079
- .select()
1080
- .from(versions)
1081
- .where(and(...whereClauses));
1082
- if (!queryRows || !queryRows.length) {
1083
- return;
1092
+ if (!deleted) {
1093
+ conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
1084
1094
  }
1085
- return queryRows[0];
1095
+ const versionData = getVersionData$1();
1096
+ let query = appDb
1097
+ .with(versionData)
1098
+ .select({
1099
+ seedLocalId: seeds.localId,
1100
+ seedUid: seeds.uid,
1101
+ schemaUid: seeds.schemaUid,
1102
+ modelName: sql `${modelName}`,
1103
+ attestationCreatedAt: seeds.attestationCreatedAt,
1104
+ versionsCount: versionData.versionsCount,
1105
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
1106
+ lastLocalUpdateAt: versionData.lastLocalUpdateAt,
1107
+ latestVersionUid: versionData.latestVersionUid,
1108
+ latestVersionLocalId: versionData.latestVersionLocalId,
1109
+ createdAt: seeds.createdAt,
1110
+ })
1111
+ .from(seeds)
1112
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
1113
+ .where(and(gt(versionData.versionsCount, 0), ...conditions))
1114
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
1115
+ .groupBy(seeds.localId);
1116
+ const itemsData = (yield query);
1117
+ return itemsData;
1086
1118
  });
1087
1119
 
1088
- const eventEmitter = new EventEmitter();
1089
-
1090
1120
  const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid, seedType, uid, }) {
1091
1121
  const appDb = getAppDb();
1092
1122
  const newVersionLocalId = generateId();
@@ -1104,6 +1134,9 @@ const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedL
1104
1134
  const createMetadata = (metadataValues, propertyRecordSchema) => __awaiter(void 0, void 0, void 0, function* () {
1105
1135
  const appDb = getAppDb();
1106
1136
  metadataValues.localId = generateId();
1137
+ if (!metadataValues.modelType && metadataValues.modelName) {
1138
+ metadataValues.modelType = metadataValues.modelName.toLowerCase();
1139
+ }
1107
1140
  if (propertyRecordSchema &&
1108
1141
  propertyRecordSchema.localStorageDir &&
1109
1142
  propertyRecordSchema.storageType === 'ItemStorage') {
@@ -1130,13 +1163,7 @@ const setModel = (modelName, model) => {
1130
1163
  modelStore.set(modelName, model);
1131
1164
  };
1132
1165
 
1133
- const logger$l = debug('app:write');
1134
- const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
1135
- if (!modelName || (!seedLocalId && !seedUid)) {
1136
- return;
1137
- }
1138
- eventEmitter.emit(`item.${modelName}.${seedUid || seedLocalId}.update`);
1139
- };
1166
+ debug('app:write');
1140
1167
  const createSeed = (_a) => __awaiter(void 0, [_a], void 0, function* ({ type, seedUid }) {
1141
1168
  const appDb = getAppDb();
1142
1169
  const newSeedLocalId = generateId();
@@ -1186,148 +1213,6 @@ const createNewItem = (_a) => __awaiter(void 0, void 0, void 0, function* () {
1186
1213
  versionLocalId: newVersionId,
1187
1214
  };
1188
1215
  });
1189
- const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ propertyLocalId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, }) {
1190
- if (!propertyLocalId && !seedLocalId) {
1191
- logger$l(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1192
- return;
1193
- }
1194
- let safeNewValue = newValue;
1195
- if (typeof newValue === 'string' &&
1196
- !refResolvedDisplayValue &&
1197
- !refResolvedValue) {
1198
- safeNewValue = escapeSqliteString(newValue);
1199
- }
1200
- const appDb = getAppDb();
1201
- yield appDb
1202
- .select()
1203
- .from(metadata)
1204
- .where(and(eq(metadata.propertyName, propertyName), eq(metadata.seedLocalId, seedLocalId)))
1205
- .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'));
1206
- const mostRecentRecordStatement = `SELECT local_id,
1207
- uid,
1208
- property_name,
1209
- property_value,
1210
- model_type,
1211
- seed_uid,
1212
- seed_local_id,
1213
- version_local_id,
1214
- version_uid,
1215
- schema_uid,
1216
- eas_data_type
1217
- FROM metadata
1218
- WHERE property_name = '${propertyName}'
1219
- AND seed_local_id = '${seedLocalId}'
1220
- ORDER BY COALESCE(attestation_created_at, created_at) DESC;`;
1221
- const { rows } = yield runQueryForStatement(mostRecentRecordStatement);
1222
- if (rows && rows.length > 0) {
1223
- const mostRecentRecord = rows[0];
1224
- const localId = mostRecentRecord[0];
1225
- const uid = mostRecentRecord[1];
1226
- const propertyNameFromDb = mostRecentRecord[2];
1227
- const propertyValueFromDb = mostRecentRecord[3];
1228
- const modelType = mostRecentRecord[4];
1229
- const seedUid = mostRecentRecord[5];
1230
- const seedLocalIdFromDb = mostRecentRecord[6];
1231
- const versionLocalId = mostRecentRecord[7];
1232
- mostRecentRecord[8];
1233
- const schemaUid = mostRecentRecord[9];
1234
- const easDataType = mostRecentRecord[10];
1235
- if (propertyValueFromDb === newValue) {
1236
- logger$l(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1237
- return;
1238
- }
1239
- // This means we already have a local-only record so we should just update that one
1240
- if (!uid) {
1241
- const updatePropertyStatement = `UPDATE metadata
1242
- SET property_value = '${safeNewValue}',
1243
- ref_seed_type = ${refSeedType ? `'${refSeedType}'` : 'NULL'},
1244
- ref_resolved_value = ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
1245
- ref_resolved_display_value = ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
1246
- updated_at = ${Date.now()}
1247
- WHERE local_id = '${localId}';`;
1248
- yield runQueryForStatement(updatePropertyStatement);
1249
- sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
1250
- return;
1251
- }
1252
- const seedDataFromDb = yield getSeedData({ seedLocalId });
1253
- const versionDataFromDb = yield getVersionData$1({ versionLocalId });
1254
- // Here we don't have a local-only record so we need to create a new one
1255
- const newLocalId = generateId();
1256
- const newPropertyStatement = `INSERT INTO metadata (local_id,
1257
- property_name,
1258
- property_value,
1259
- model_type,
1260
- seed_uid,
1261
- seed_local_id,
1262
- version_local_id,
1263
- version_uid,
1264
- schema_uid,
1265
- eas_data_type,
1266
- ref_seed_type,
1267
- ref_resolved_value,
1268
- ref_resolved_display_value,
1269
- created_at)
1270
- VALUES ('${newLocalId}',
1271
- '${propertyNameFromDb}',
1272
- '${safeNewValue}',
1273
- '${modelType}',
1274
- ${(seedDataFromDb === null || seedDataFromDb === void 0 ? void 0 : seedDataFromDb.uid) ? `'${seedDataFromDb.uid}'` : 'NULL'},
1275
- '${seedLocalIdFromDb}',
1276
- '${versionLocalId}',
1277
- ${(versionDataFromDb === null || versionDataFromDb === void 0 ? void 0 : versionDataFromDb.uid) ? `'${versionDataFromDb.uid}'` : 'NULL'},
1278
- '${schemaUid}',
1279
- ${easDataType ? `'${easDataType}'` : 'NULL'},
1280
- ${refSeedType ? `'${refSeedType}'` : 'NULL'},
1281
- ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
1282
- ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
1283
- ${Date.now()});`;
1284
- yield runQueryForStatement(newPropertyStatement);
1285
- sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
1286
- return;
1287
- }
1288
- // Here there are no records for this property on this seed so we should create one
1289
- const newLocalId = generateId();
1290
- if (!seedUid) {
1291
- const seedData = yield getSeedData({ seedLocalId });
1292
- if (seedData) {
1293
- seedUid = seedData.uid;
1294
- }
1295
- }
1296
- if (!versionUid) {
1297
- const versionData = yield getVersionData$1({ versionLocalId });
1298
- if (versionData) {
1299
- versionUid = versionData.uid;
1300
- }
1301
- }
1302
- const newPropertyStatement = `INSERT INTO metadata (local_id,
1303
- property_name,
1304
- property_value,
1305
- model_type,
1306
- seed_uid,
1307
- seed_local_id,
1308
- version_local_id,
1309
- version_uid,
1310
- schema_uid,
1311
- ref_seed_type,
1312
- ref_resolved_value,
1313
- ref_resolved_display_value,
1314
- created_at)
1315
- VALUES ('${newLocalId}',
1316
- '${propertyName}',
1317
- '${safeNewValue}',
1318
- '${modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase()}',
1319
- ${seedUid ? `'${seedUid}'` : 'NULL'},
1320
- '${seedLocalId}',
1321
- '${versionLocalId}',
1322
- ${versionUid ? `'${versionUid}'` : 'NULL'},
1323
- '${schemaUid}',
1324
- ${refSeedType ? `'${refSeedType}'` : 'NULL'},
1325
- ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
1326
- ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
1327
- ${Date.now()});`;
1328
- yield runQueryForStatement(newPropertyStatement);
1329
- sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
1330
- });
1331
1216
  const writeAppState = (key, value) => __awaiter(void 0, void 0, void 0, function* () {
1332
1217
  const appDb = getAppDb();
1333
1218
  yield appDb
@@ -1344,6 +1229,8 @@ const writeAppState = (key, value) => __awaiter(void 0, void 0, void 0, function
1344
1229
  });
1345
1230
  });
1346
1231
 
1232
+ const eventEmitter = new EventEmitter();
1233
+
1347
1234
  var MachineIds;
1348
1235
  (function (MachineIds) {
1349
1236
  MachineIds["GLOBAL"] = "@seedSdk/global";
@@ -1477,279 +1364,22 @@ const updateMachineContext = {
1477
1364
  }),
1478
1365
  };
1479
1366
 
1480
- const readFileAsArrayBuffer = (file) => __awaiter(void 0, void 0, void 0, function* () {
1481
- return new Promise((resolve) => {
1482
- const reader = new FileReader();
1483
- reader.onload = (e) => __awaiter(void 0, void 0, void 0, function* () {
1484
- const arrayBuffer = e.target.result;
1485
- resolve(arrayBuffer);
1486
- });
1487
- reader.readAsArrayBuffer(file);
1488
- });
1489
- });
1490
- const fetchImage = (url) => __awaiter(void 0, void 0, void 0, function* () {
1491
- const response = yield fetch(url);
1492
- const mimeType = response.headers.get('Content-Type');
1493
- const imageBuffer = yield response.arrayBuffer();
1494
- const bytes = new Uint8Array(imageBuffer);
1495
- const binaryString = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), '');
1496
- let base64 = btoa(binaryString);
1497
- if (mimeType) {
1498
- base64 = `data:${mimeType};base64,${base64}`;
1499
- }
1500
- return base64;
1501
- });
1502
- const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
1503
- const { localId, propertyName: propertyNameRaw, propertyValue: existingValue, propertyRecordSchema, itemModelName, seedLocalId, seedUid, versionLocalId, versionUid, schemaUid, } = context;
1504
- let newValue;
1505
- if (event) {
1506
- newValue = event.newValue;
1507
- }
1508
- if (existingValue === newValue) {
1509
- sendBack({ type: 'saveValueToDbSuccess' });
1510
- return;
1511
- }
1512
- const _saveImageSrc = () => __awaiter(void 0, void 0, void 0, function* () {
1513
- let propertyName = propertyNameRaw;
1514
- if (!propertyNameRaw.endsWith('Id')) {
1515
- propertyName = `${propertyName}Id`;
1367
+ var _a$2;
1368
+ const logger$l = debug('app:property:class');
1369
+ const namesThatEndWithId = [];
1370
+ class ItemProperty {
1371
+ // private constructor(localIdOrUid) {
1372
+ // }
1373
+ constructor({ propertyValue, seedUid, seedLocalId, versionLocalId, versionUid, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1374
+ this._isRelation = false;
1375
+ this._isList = false;
1376
+ this[_a$2] = true;
1377
+ const ModelClass = getModel(itemModelName);
1378
+ if (!ModelClass) {
1379
+ throw new Error(`Model ${itemModelName} not found`);
1516
1380
  }
1517
- let newValueType;
1518
- let fileData;
1519
- let mimeType;
1520
- let fileName;
1521
- if (typeof newValue === 'string') {
1522
- newValueType = getDataTypeFromString(newValue);
1523
- }
1524
- if (newValueType === 'imageBase64') {
1525
- mimeType = getMimeType(newValue);
1526
- const base64Data = newValue.split(',')[1]; // Strip the Base64 prefix
1527
- const binaryString = atob(base64Data);
1528
- const binaryLength = binaryString.length;
1529
- const binaryArray = new Uint8Array(binaryLength);
1530
- for (let i = 0; i < binaryLength; i++) {
1531
- binaryArray[i] = binaryString.charCodeAt(i);
1532
- }
1533
- fileData = binaryArray.buffer;
1534
- }
1535
- if (newValueType === 'url') {
1536
- fileData = yield fetchImage(newValue);
1537
- }
1538
- if (newValue instanceof File) {
1539
- fileName = newValue.name;
1540
- mimeType = newValue.type;
1541
- fileData = yield readFileAsArrayBuffer(newValue);
1542
- }
1543
- if (!fileData) {
1544
- throw new Error('No file data found');
1545
- }
1546
- const newImageSeedLocalId = yield createSeed({
1547
- type: 'image',
1548
- });
1549
- if (!fileName) {
1550
- fileName = newImageSeedLocalId;
1551
- if (mimeType) {
1552
- fileName += `.${mimeType.split('/')[1]}`;
1553
- }
1554
- }
1555
- const filePath = `/files/images/${fileName}`;
1556
- yield createVersion({
1557
- seedLocalId: newImageSeedLocalId,
1558
- seedType: 'image',
1559
- });
1560
- if (fileData instanceof ArrayBuffer) {
1561
- yield fs.promises.writeFile(filePath, new Uint8Array(fileData));
1562
- }
1563
- if (typeof fileData === 'string') {
1564
- yield fs.promises.writeFile(filePath, fileData);
1565
- }
1566
- const refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
1567
- if (!localId) {
1568
- yield createMetadata({
1569
- propertyName,
1570
- propertyValue: newImageSeedLocalId,
1571
- seedLocalId,
1572
- seedUid,
1573
- versionLocalId,
1574
- versionUid,
1575
- modelName: itemModelName,
1576
- schemaUid,
1577
- refSeedType: 'image',
1578
- refResolvedDisplayValue,
1579
- refResolvedValue: fileName,
1580
- }, propertyRecordSchema);
1581
- }
1582
- if (localId) {
1583
- yield updateItemPropertyValue({
1584
- propertyLocalId: localId,
1585
- propertyName: propertyNameRaw,
1586
- newValue: newImageSeedLocalId,
1587
- seedLocalId,
1588
- versionLocalId,
1589
- modelName: itemModelName,
1590
- schemaUid,
1591
- refSeedType: 'image',
1592
- refResolvedDisplayValue,
1593
- refResolvedValue: fileName,
1594
- });
1595
- }
1596
- sendBack({
1597
- type: 'updateContext',
1598
- propertyValue: newImageSeedLocalId,
1599
- refSeedType: 'image',
1600
- renderValue: refResolvedDisplayValue,
1601
- resolvedDisplayValue: refResolvedDisplayValue,
1602
- resolvedValue: fileName,
1603
- });
1604
- });
1605
- _saveImageSrc().then(() => {
1606
- sendBack({ type: 'saveImageSrcSuccess' });
1607
- });
1608
- });
1609
-
1610
- const saveRelation = fromCallback(({ sendBack, input: { context, event } }) => {
1611
- const { localId, propertyName: propertyNameRaw, versionLocalId, seedUid, seedLocalId, propertyValue: existingValue, propertyRecordSchema, } = context;
1612
- if (!propertyRecordSchema) {
1613
- throw new Error('Missing propertyRecordSchema');
1614
- }
1615
- let newValue;
1616
- if (event) {
1617
- newValue = event.newValue;
1618
- }
1619
- const _saveRelation = () => __awaiter(void 0, void 0, void 0, function* () {
1620
- let propertyName = propertyNameRaw;
1621
- if (!propertyName.endsWith('Id')) {
1622
- propertyName = `${propertyName}Id`;
1623
- }
1624
- let newValueType;
1625
- if (typeof newValue === 'string') {
1626
- newValueType = getDataTypeFromString(newValue);
1627
- }
1628
- if (newValue instanceof File) {
1629
- newValueType = 'file';
1630
- }
1631
- if (propertyRecordSchema.dataType === 'ImageSrc') {
1632
- sendBack({
1633
- type: 'saveImageSrc',
1634
- newValue,
1635
- newValueType,
1636
- });
1637
- return false;
1638
- }
1639
- return true;
1640
- // let fileType
1641
- //
1642
- // const dirs = await fs.promises.readdir('/files')
1643
- //
1644
- // for (const dir of dirs) {
1645
- // const files = await fs.promises.readdir(`/files/${dir}`)
1646
- // if (newValue && files.includes(newValue as string)) {
1647
- // fileType = dir
1648
- // break
1649
- // }
1650
- // }
1651
- //
1652
- // if (newValue && fileType === 'images') {
1653
- // const filePath = `/files/images/${newValue}`
1654
- // refResolvedDisplayValue = await getContentUrlFromPath(filePath)
1655
- // refSeedType = 'image'
1656
- // newValue = await createSeed({
1657
- // type: refSeedType,
1658
- // })
1659
- // await createVersion({
1660
- // seedLocalId,
1661
- // seedUid,
1662
- // seedType: refSeedType,
1663
- // })
1664
- // }
1665
- //
1666
- // await updateItemPropertyValue({
1667
- // propertyLocalId: localId,
1668
- // propertyName,
1669
- // newValue,
1670
- // seedLocalId,
1671
- // refSeedType,
1672
- // refResolvedValue,
1673
- // refResolvedDisplayValue,
1674
- // versionLocalId,
1675
- // modelName: itemModelName,
1676
- // schemaUid,
1677
- // })
1678
- });
1679
- _saveRelation().then((isDone) => {
1680
- if (isDone) {
1681
- sendBack({ type: 'saveRelationSuccess' });
1682
- }
1683
- });
1684
- });
1685
-
1686
- const getVersionData = () => {
1687
- const appDb = getAppDb();
1688
- return appDb.$with('versionData').as(appDb
1689
- .select({
1690
- seedLocalId: versions.seedLocalId,
1691
- seedUid: versions.seedUid,
1692
- latestVersionUid: versions.uid,
1693
- latestVersionLocalId: versions.localId,
1694
- versionsCount: count(versions.localId).as('versionsCount'),
1695
- lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
1696
- lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
1697
- })
1698
- .from(versions)
1699
- .groupBy(versions.seedLocalId));
1700
- };
1701
-
1702
- const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
1703
- const appDb = getAppDb();
1704
- const conditions = [];
1705
- if (modelName) {
1706
- conditions.push(eq(seeds.type, modelName.toLowerCase()));
1707
- }
1708
- if (deleted) {
1709
- conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
1710
- }
1711
- if (!deleted) {
1712
- conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
1713
- }
1714
- const versionData = getVersionData();
1715
- let query = appDb
1716
- .with(versionData)
1717
- .select({
1718
- seedLocalId: seeds.localId,
1719
- seedUid: seeds.uid,
1720
- schemaUid: seeds.schemaUid,
1721
- modelName: sql `${modelName}`,
1722
- attestationCreatedAt: seeds.attestationCreatedAt,
1723
- versionsCount: versionData.versionsCount,
1724
- lastVersionPublishedAt: versionData.lastVersionPublishedAt,
1725
- lastLocalUpdateAt: versionData.lastLocalUpdateAt,
1726
- createdAt: seeds.createdAt,
1727
- })
1728
- .from(seeds)
1729
- .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
1730
- .where(and(gt(versionData.versionsCount, 0), ...conditions))
1731
- .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
1732
- .groupBy(seeds.localId);
1733
- const itemsData = (yield query);
1734
- return itemsData;
1735
- });
1736
-
1737
- var _a$2;
1738
- const logger$k = debug('app:property:class');
1739
- const namesThatEndWithId = [];
1740
- class ItemProperty {
1741
- // private constructor(localIdOrUid) {
1742
- // }
1743
- constructor({ propertyValue, seedUid, seedLocalId, versionLocalId, versionUid, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1744
- this._isRelation = false;
1745
- this._isList = false;
1746
- this[_a$2] = true;
1747
- const ModelClass = getModel(itemModelName);
1748
- if (!ModelClass) {
1749
- throw new Error(`Model ${itemModelName} not found`);
1750
- }
1751
- if (!propertyName) {
1752
- throw new Error(`Property name not provided`);
1381
+ if (!propertyName) {
1382
+ throw new Error(`Property name not provided`);
1753
1383
  }
1754
1384
  const serviceInput = {
1755
1385
  propertyValue,
@@ -1785,7 +1415,7 @@ class ItemProperty {
1785
1415
  serviceInput.propertyValue = JSON.parse(propertyValue);
1786
1416
  }
1787
1417
  catch (e) {
1788
- logger$k('List property value is not JSON', e);
1418
+ logger$l('List property value is not JSON', e);
1789
1419
  }
1790
1420
  }
1791
1421
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -1867,7 +1497,7 @@ class ItemProperty {
1867
1497
  this._service.start();
1868
1498
  }
1869
1499
  _updateResponseListener(event) {
1870
- logger$k(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1500
+ logger$l(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1871
1501
  }
1872
1502
  static create(props) {
1873
1503
  const { propertyName, seedLocalId, seedUid, versionLocalId, versionUid } = props;
@@ -2014,7 +1644,7 @@ class ItemProperty {
2014
1644
  }
2015
1645
  unload() {
2016
1646
  this._service.stop();
2017
- logger$k(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1647
+ logger$l(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
2018
1648
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
2019
1649
  }
2020
1650
  }
@@ -2810,7 +2440,7 @@ const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, f
2810
2440
  trailing: false,
2811
2441
  });
2812
2442
 
2813
- const logger$j = debug('app:services:global:actors:initialize');
2443
+ const logger$k = debug('app:services:global:actors:initialize');
2814
2444
  const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2815
2445
  const { internalService, models, endpoints } = context;
2816
2446
  const { addresses } = event;
@@ -2831,7 +2461,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2831
2461
  const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
2832
2462
  return new Promise((resolve) => {
2833
2463
  internalSubscription = internalService.subscribe((snapshot) => {
2834
- logger$j('[sdk] [internal] snapshot', snapshot);
2464
+ logger$k('[sdk] [internal] snapshot', snapshot);
2835
2465
  if (snapshot.value === 'ready') {
2836
2466
  resolve();
2837
2467
  }
@@ -2865,14 +2495,14 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2865
2495
  sendBack(Object.assign({ type: GLOBAL_INITIALIZING_CREATE_ALL_ITEMS_SERVICES }, payloadObj));
2866
2496
  });
2867
2497
  _initFileSystem().then(() => {
2868
- logger$j('[global/actors] File system initialized');
2498
+ logger$k('[global/actors] File system initialized');
2869
2499
  });
2870
2500
  _initInternal()
2871
2501
  .then(() => {
2872
2502
  return _initAllItemsServices();
2873
2503
  })
2874
2504
  .then(() => {
2875
- logger$j('[global/actors] Internal initialized');
2505
+ logger$k('[global/actors] Internal initialized');
2876
2506
  sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
2877
2507
  internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
2878
2508
  });
@@ -2886,7 +2516,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2886
2516
  };
2887
2517
  });
2888
2518
 
2889
- const logger$i = debug('app:services:global:actors:getSchemaForModel');
2519
+ const logger$j = debug('app:services:global:actors:getSchemaForModel');
2890
2520
  const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
2891
2521
  const { modelName } = event;
2892
2522
  if (!modelName) {
@@ -2902,12 +2532,12 @@ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } })
2902
2532
  if (!model) {
2903
2533
  throw new Error(`Model ${modelName} not found`);
2904
2534
  }
2905
- logger$i('[service/actor] [getSchemaForModel] model:', model);
2535
+ logger$j('[service/actor] [getSchemaForModel] model:', model);
2906
2536
  sendBack({ type: 'schemaForModel', schema: model.schema });
2907
2537
  return () => { };
2908
2538
  });
2909
2539
 
2910
- const logger$h = debug('app:services:global:actors:addModelsToDb');
2540
+ const logger$i = debug('app:services:global:actors:addModelsToDb');
2911
2541
  const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2912
2542
  const { models: models$1 } = context;
2913
2543
  const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
@@ -2916,12 +2546,12 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2916
2546
  if (!models$1) {
2917
2547
  return;
2918
2548
  }
2919
- const { models: SeedModels } = yield import('./seed.schema.config-miFErQ6h.js');
2549
+ const { models: SeedModels } = yield import('./seed.schema.config-BEvGEHkp.js');
2920
2550
  const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
2921
2551
  let hasModelsInDb = false;
2922
2552
  const schemaDefsByModelName = new Map();
2923
2553
  for (const [modelName, _] of Object.entries(allModels)) {
2924
- logger$h('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2554
+ logger$i('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2925
2555
  let foundModel;
2926
2556
  const foundModelsQuery = yield appDb
2927
2557
  .select()
@@ -2931,7 +2561,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2931
2561
  yield appDb.insert(models).values({
2932
2562
  name: modelName,
2933
2563
  });
2934
- logger$h('[global/actors] [addModelsToDb] inserted model:', modelName);
2564
+ logger$i('[global/actors] [addModelsToDb] inserted model:', modelName);
2935
2565
  const foundModels = yield appDb
2936
2566
  .select({
2937
2567
  id: models.id,
@@ -3001,10 +2631,10 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
3001
2631
  return () => { };
3002
2632
  });
3003
2633
 
3004
- const logger$g = debug('app:services:db:actors:checkStatus');
2634
+ const logger$h = debug('app:services:db:actors:checkStatus');
3005
2635
  const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
3006
2636
  const { dbName } = context;
3007
- logger$g('[db/actors] checkStatus context', context);
2637
+ logger$h('[db/actors] checkStatus context', context);
3008
2638
  const pathToDir = `${BROWSER_FS_TOP_DIR}`;
3009
2639
  const pathToDbDir = `${pathToDir}/db`;
3010
2640
  const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
@@ -3035,9 +2665,9 @@ const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
3035
2665
  });
3036
2666
  });
3037
2667
 
3038
- const logger$f = debug('app:services:db:actors:connectToDb');
2668
+ const logger$g = debug('app:services:db:actors:connectToDb');
3039
2669
  const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
3040
- logger$f('[db/actors] connectToDb context', context);
2670
+ logger$g('[db/actors] connectToDb context', context);
3041
2671
  const { dbName, pathToDir } = context;
3042
2672
  let isConnecting = false;
3043
2673
  let dbId;
@@ -3050,16 +2680,16 @@ const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
3050
2680
  const sqliteWasmClient = yield getSqliteWasmClient();
3051
2681
  //@ts-ignore
3052
2682
  response = yield sqliteWasmClient('config-get', {});
3053
- logger$f(response);
3054
- logger$f('Running SQLite3 version', response.result.version.libVersion);
2683
+ logger$g(response);
2684
+ logger$g('Running SQLite3 version', response.result.version.libVersion);
3055
2685
  //@ts-ignore
3056
2686
  response = yield sqliteWasmClient('open', {
3057
2687
  filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
3058
2688
  });
3059
- logger$f(response);
2689
+ logger$g(response);
3060
2690
  dbId = response.dbId;
3061
2691
  // logger(`dbId: ${dbId}`)
3062
- logger$f('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
2692
+ logger$g('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
3063
2693
  });
3064
2694
  const interval = setInterval(() => {
3065
2695
  // TODO: Add a timeout
@@ -3116,7 +2746,7 @@ const validate = fromCallback(({ sendBack, input: { context } }) => {
3116
2746
  });
3117
2747
  });
3118
2748
 
3119
- const logger$e = debug('app:services:db:actors:migrate');
2749
+ const logger$f = debug('app:services:db:actors:migrate');
3120
2750
  const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void 0, [dbId_1, params_1, sql_1, dbName_1, ...args_1], void 0, function* (dbId, params, sql, dbName, retries = 2) {
3121
2751
  const rowsToReturnRaw = [];
3122
2752
  const sqliteWasmClient = yield getSqliteWasmClient();
@@ -3182,7 +2812,7 @@ const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void
3182
2812
  });
3183
2813
  const migrate = fromCallback(({ sendBack, input: { context } }) => {
3184
2814
  const { pathToDbDir, dbId, dbName } = context;
3185
- logger$e('[db/actors] migrate context', context);
2815
+ logger$f('[db/actors] migrate context', context);
3186
2816
  const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`;
3187
2817
  let journalExists = false;
3188
2818
  // const _initFs = async (): Promise<void> => {
@@ -3346,7 +2976,7 @@ const migrate = fromCallback(({ sendBack, input: { context } }) => {
3346
2976
  return () => { };
3347
2977
  });
3348
2978
 
3349
- const logger$d = debug('app:services:db:machine');
2979
+ const logger$e = debug('app:services:db:machine');
3350
2980
  const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
3351
2981
  const dbMachine = setup({
3352
2982
  types: {
@@ -3367,7 +2997,7 @@ const dbMachine = setup({
3367
2997
  [DB_WAITING_FOR_FILES_RECEIVED]: {
3368
2998
  actions: assign({
3369
2999
  hasFiles: ({ event }) => {
3370
- logger$d('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3000
+ logger$e('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3371
3001
  return true;
3372
3002
  },
3373
3003
  }),
@@ -3376,8 +3006,8 @@ const dbMachine = setup({
3376
3006
  target: `.${CHECKING_STATUS}`,
3377
3007
  actions: assign({
3378
3008
  hasFiles: ({ context, event }) => {
3379
- logger$d('[db/machine] updateHasFiles event:', event);
3380
- logger$d('[db/machine] updateHasFiles context:', context);
3009
+ logger$e('[db/machine] updateHasFiles event:', event);
3010
+ logger$e('[db/machine] updateHasFiles context:', context);
3381
3011
  return event.hasFiles;
3382
3012
  },
3383
3013
  }),
@@ -3598,7 +3228,7 @@ const prepareDb = fromCallback(({ sendBack }) => {
3598
3228
  };
3599
3229
  });
3600
3230
 
3601
- const logger$c = debug('app:services:internal:helpers');
3231
+ const logger$d = debug('app:services:internal:helpers');
3602
3232
  /**
3603
3233
  * Recursively create directories if they don't exist.
3604
3234
  * @param {string} dirPath - The directory path to create.
@@ -3674,7 +3304,7 @@ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, f
3674
3304
  if (JSON.stringify(error).includes('File exists')) {
3675
3305
  yield fs.promises.readFile(localFilePath, 'utf-8');
3676
3306
  }
3677
- logger$c(`[Error] Failed to download file from ${url}:`, error);
3307
+ logger$d(`[Error] Failed to download file from ${url}:`, error);
3678
3308
  }
3679
3309
  busy = false;
3680
3310
  });
@@ -3712,7 +3342,7 @@ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePat
3712
3342
  const fileList = yield fetchDirectory(filePaths);
3713
3343
  yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
3714
3344
  yield confirmFilesExist(fileList);
3715
- logger$c('[syncDbFiles] Files synced!');
3345
+ logger$d('[syncDbFiles] Files synced!');
3716
3346
  });
3717
3347
 
3718
3348
  const uploadBinaryData = fromCallback(({ sendBack, receive, input }) => { });
@@ -3935,7 +3565,7 @@ const GET_TRANSACTION_TAGS = graphql(/* GraphQL */ `
3935
3565
  }
3936
3566
  `);
3937
3567
 
3938
- const logger$b = debug('app:files:download');
3568
+ const logger$c = debug('app:files:download');
3939
3569
  const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
3940
3570
  yield syncDbFiles(endpoints);
3941
3571
  eventEmitter.emit('fs.downloadAll.success', { eventId });
@@ -4019,7 +3649,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4019
3649
  try {
4020
3650
  const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
4021
3651
  if (res.status !== 200) {
4022
- logger$b(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
3652
+ logger$c(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
4023
3653
  excludedTransactions.add(transactionId);
4024
3654
  yield writeAppState('excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
4025
3655
  continue;
@@ -4056,7 +3686,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4056
3686
  // string: true,
4057
3687
  // })
4058
3688
  if (!dataString) {
4059
- logger$b(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
3689
+ logger$c(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
4060
3690
  }
4061
3691
  let contentType = identifyString(dataString);
4062
3692
  if (contentType !== 'json' &&
@@ -4064,7 +3694,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4064
3694
  contentType !== 'html') {
4065
3695
  const possibleImageType = getDataTypeFromString(dataString);
4066
3696
  if (!possibleImageType) {
4067
- logger$b(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
3697
+ logger$c(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
4068
3698
  continue;
4069
3699
  }
4070
3700
  contentType = possibleImageType;
@@ -4127,7 +3757,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4127
3757
  }
4128
3758
  }
4129
3759
  catch (error) {
4130
- logger$b(error);
3760
+ logger$c(error);
4131
3761
  }
4132
3762
  }
4133
3763
  });
@@ -4173,14 +3803,14 @@ const isFsInitialized = () => {
4173
3803
  return isInitialized;
4174
3804
  };
4175
3805
 
4176
- const logger$a = debug('app:internal:actors:configureFs');
3806
+ const logger$b = debug('app:internal:actors:configureFs');
4177
3807
  const configureFs = fromCallback(({ sendBack, input: { context } }) => {
4178
3808
  const { endpoints, appDbService } = context;
4179
- logger$a('[internal/actors] [configureFs] Configuring FS');
3809
+ logger$b('[internal/actors] [configureFs] Configuring FS');
4180
3810
  const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
4181
- logger$a('[internal/actors] [configureFs] calling _configureFs');
4182
- logger$a('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
4183
- logger$a('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
3811
+ logger$b('[internal/actors] [configureFs] calling _configureFs');
3812
+ logger$b('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
3813
+ logger$b('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
4184
3814
  yield waitForEvent({
4185
3815
  req: {
4186
3816
  eventLabel: 'fs.downloadAll.request',
@@ -4209,7 +3839,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
4209
3839
  // }
4210
3840
  // }, 200)
4211
3841
  // })
4212
- logger$a('[internal/actors] [configureFs] fs configured!');
3842
+ logger$b('[internal/actors] [configureFs] fs configured!');
4213
3843
  });
4214
3844
  // Some of our dependencies use fs sync functions, which don't work with
4215
3845
  // OPFS. ZenFS creates an async cache of all files so that the sync functions
@@ -4222,7 +3852,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
4222
3852
  return () => { };
4223
3853
  });
4224
3854
 
4225
- const logger$9 = debug('app:services:internal:actors:saveConfig');
3855
+ const logger$a = debug('app:services:internal:actors:saveConfig');
4226
3856
  const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
4227
3857
  if (typeof window === 'undefined') {
4228
3858
  console.error('seedInitBrowser called from non-browser context');
@@ -4273,20 +3903,20 @@ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
4273
3903
  },
4274
3904
  setWhere: sql `key = 'addresses'`,
4275
3905
  });
4276
- logger$9('[sdk] [internal/actors] Should be done saving');
3906
+ logger$a('[sdk] [internal/actors] Should be done saving');
4277
3907
  }
4278
3908
  catch (error) {
4279
3909
  console.error('Error saving config:', error);
4280
3910
  }
4281
3911
  });
4282
3912
  _saveConfig().then(() => {
4283
- logger$9('[sdk] [internal/actors] Successfully saved config');
3913
+ logger$a('[sdk] [internal/actors] Successfully saved config');
4284
3914
  return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
4285
3915
  });
4286
3916
  return () => { };
4287
3917
  });
4288
3918
 
4289
- const logger$8 = debug('app:services:internal:actors:loadAppDb');
3919
+ const logger$9 = debug('app:services:internal:actors:loadAppDb');
4290
3920
  const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4291
3921
  const { appDbService } = context;
4292
3922
  let subscription;
@@ -4307,7 +3937,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4307
3937
  });
4308
3938
  _loadAppDb().then(() => {
4309
3939
  sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
4310
- logger$8('[sdk] [internal/actors] Successfully loaded app DB');
3940
+ logger$9('[sdk] [internal/actors] Successfully loaded app DB');
4311
3941
  });
4312
3942
  return () => {
4313
3943
  if (subscription) {
@@ -4316,7 +3946,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4316
3946
  };
4317
3947
  });
4318
3948
 
4319
- const logger$7 = debug('app:services:internal:machine');
3949
+ const logger$8 = debug('app:services:internal:machine');
4320
3950
  createBrowserInspector({
4321
3951
  autoStart: false,
4322
3952
  });
@@ -4415,7 +4045,7 @@ const internalMachine = setup({
4415
4045
  [INTERNAL_LOADING_APP_DB_SUCCESS]: {
4416
4046
  target: SAVING_CONFIG,
4417
4047
  actions: () => {
4418
- logger$7('[sdk] [internal/index] App DB loaded!');
4048
+ logger$8('[sdk] [internal/index] App DB loaded!');
4419
4049
  },
4420
4050
  },
4421
4051
  },
@@ -4441,7 +4071,7 @@ const internalMachine = setup({
4441
4071
  },
4442
4072
  ready: {
4443
4073
  entry: () => {
4444
- logger$7('[sdk] [internal/index] Ready!');
4074
+ logger$8('[sdk] [internal/index] Ready!');
4445
4075
  },
4446
4076
  meta: {
4447
4077
  displayText: "Crossing the t's ...",
@@ -4456,7 +4086,7 @@ const internalMachine = setup({
4456
4086
  },
4457
4087
  },
4458
4088
  entry: () => {
4459
- logger$7('[sdk] [internal/index] Error!');
4089
+ logger$8('[sdk] [internal/index] Error!');
4460
4090
  },
4461
4091
  meta: {
4462
4092
  displayText: 'Whoops! Something went wrong.',
@@ -4692,7 +4322,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
4692
4322
  return () => { };
4693
4323
  });
4694
4324
 
4695
- const logger$6 = debug('app:allItemsActors:fetchSeeds');
4325
+ const logger$7 = debug('app:allItemsActors:fetchSeeds');
4696
4326
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4697
4327
  const { queryVariables, modelName } = context;
4698
4328
  if (!queryVariables) {
@@ -4702,7 +4332,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4702
4332
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
4703
4333
  const queryKey = [`getSeeds${modelName}`];
4704
4334
  const cachedResults = queryClient.getQueryData(queryKey);
4705
- logger$6(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4335
+ logger$7(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4706
4336
  const results = yield queryClient.fetchQuery({
4707
4337
  queryKey,
4708
4338
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -5133,13 +4763,13 @@ const preparePublishRequestData = fromCallback(({ sendBack, input: { context } }
5133
4763
  });
5134
4764
  });
5135
4765
 
5136
- const logger$5 = debug('app:services:publish:actors:upload');
4766
+ const logger$6 = debug('app:services:publish:actors:upload');
5137
4767
  const upload = fromCallback(({ sendBack, input: { context } }) => {
5138
4768
  const { localId } = context;
5139
4769
  const _upload = () => __awaiter(void 0, void 0, void 0, function* () {
5140
4770
  const item = yield Item.find({ seedLocalId: localId });
5141
4771
  if (!item) {
5142
- logger$5('no item with localId', localId);
4772
+ logger$6('no item with localId', localId);
5143
4773
  return false;
5144
4774
  }
5145
4775
  const editedProperties = yield item.getEditedProperties();
@@ -6004,7 +5634,24 @@ const getItemProperties = (_a) => __awaiter(void 0, [_a], void 0, function* ({ s
6004
5634
  // })
6005
5635
  // }
6006
5636
 
6007
- const logger$4 = debug('app:db:queries:getItem');
5637
+ const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
5638
+ const appDb = getAppDb();
5639
+ let query;
5640
+ const queryBase = appDb.select().from(seeds);
5641
+ if (seedLocalId) {
5642
+ query = queryBase.where(eq(seeds.localId, seedLocalId));
5643
+ }
5644
+ if (seedUid) {
5645
+ query = queryBase.where(eq(seeds.uid, seedUid));
5646
+ }
5647
+ const rows = yield query;
5648
+ if (!rows || !rows.length) {
5649
+ return;
5650
+ }
5651
+ return rows[0];
5652
+ });
5653
+
5654
+ const logger$5 = debug('app:db:queries:getItem');
6008
5655
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
6009
5656
  if (!seedLocalId && !seedUid) {
6010
5657
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -6012,7 +5659,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6012
5659
  if (seedUid && !seedLocalId) {
6013
5660
  const seedData = yield getSeedData({ seedUid });
6014
5661
  if (!seedData) {
6015
- logger$4('[db/queries] [getItem] no seedData seedUid', seedUid);
5662
+ logger$5('[db/queries] [getItem] no seedData seedUid', seedUid);
6016
5663
  return;
6017
5664
  }
6018
5665
  seedLocalId = seedData.localId;
@@ -6029,7 +5676,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6029
5676
  if (seedLocalId && !seedUid) {
6030
5677
  whereClauses.push(eq(seeds.localId, seedLocalId));
6031
5678
  }
6032
- const versionData = getVersionData();
5679
+ const versionData = getVersionData$1();
6033
5680
  const itemDataRows = yield appDb
6034
5681
  .with(versionData)
6035
5682
  .select(Object.assign(Object.assign({}, rest), { seedLocalId: seeds.localId, seedUid: seeds.uid, versionsCount: versionData.versionsCount, lastVersionPublishedAt: versionData.lastVersionPublishedAt, latestVersionUid: versionData.latestVersionUid, latestVersionLocalId: versionData.latestVersionLocalId }))
@@ -6039,7 +5686,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6039
5686
  .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
6040
5687
  .groupBy(seeds.localId);
6041
5688
  if (!itemDataRows || itemDataRows.length === 0) {
6042
- logger$4('[db/queries] [getItemDataFromDb] no itemDataRows');
5689
+ logger$5('[db/queries] [getItemDataFromDb] no itemDataRows');
6043
5690
  return;
6044
5691
  }
6045
5692
  let itemData = itemDataRows[0];
@@ -6315,7 +5962,7 @@ class Item {
6315
5962
  _a$1 = immerable;
6316
5963
  Item.instanceCache = new Map();
6317
5964
 
6318
- const logger$3 = debug('app:react:services');
5965
+ const logger$4 = debug('app:react:services');
6319
5966
  const finalStrings = ['idle', 'ready', 'done', 'success'];
6320
5967
  const getServiceName = (service) => {
6321
5968
  let name = 'actor';
@@ -6362,7 +6009,7 @@ const getServiceUniqueKey = (service) => {
6362
6009
  snapshot = service.getSnapshot();
6363
6010
  }
6364
6011
  catch (error) {
6365
- logger$3('Error:', error);
6012
+ logger$4('Error:', error);
6366
6013
  return uniqueKey;
6367
6014
  }
6368
6015
  if (snapshot) {
@@ -6466,7 +6113,7 @@ const useGlobalServiceStatus = () => {
6466
6113
  };
6467
6114
  };
6468
6115
 
6469
- const logger$2 = debug('app:react:item');
6116
+ const logger$3 = debug('app:react:item');
6470
6117
  const useItem = ({ modelName, seedLocalId, seedUid }) => {
6471
6118
  // const [itemSubscription, setItemSubscription] = useState<
6472
6119
  // Subscription | undefined
@@ -6543,7 +6190,7 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6543
6190
  seedUid,
6544
6191
  });
6545
6192
  if (!foundItem) {
6546
- logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6193
+ logger$3('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6547
6194
  isReadingDb.current = false;
6548
6195
  return;
6549
6196
  }
@@ -6565,7 +6212,7 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6565
6212
  const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6566
6213
  const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6567
6214
  if (!newItem) {
6568
- logger$2('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6215
+ logger$3('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6569
6216
  return;
6570
6217
  }
6571
6218
  updateItem(newItem);
@@ -6682,7 +6329,7 @@ const useCreateItem = (modelName) => {
6682
6329
  };
6683
6330
  };
6684
6331
 
6685
- const logger$1 = debug('app:react:property');
6332
+ const logger$2 = debug('app:react:property');
6686
6333
  const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6687
6334
  const [property, setProperty] = useState();
6688
6335
  const [isInitialized, setIsInitialized] = useState(false);
@@ -6708,7 +6355,7 @@ const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6708
6355
  seedUid,
6709
6356
  });
6710
6357
  if (!foundProperty) {
6711
- logger$1(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6358
+ logger$2(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6712
6359
  isReadingDb.current = false;
6713
6360
  return;
6714
6361
  }
@@ -6805,10 +6452,10 @@ const useDeleteItem = () => {
6805
6452
  };
6806
6453
  };
6807
6454
 
6808
- const logger = debug('app:services:events');
6455
+ const logger$1 = debug('app:services:events');
6809
6456
  const handleServiceSaveState = (event) => {
6810
6457
  const { state, serviceId } = event;
6811
- logger(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6458
+ logger$1(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6812
6459
  localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state));
6813
6460
  };
6814
6461
  const setupServicesEventHandlers = () => {
@@ -6851,7 +6498,7 @@ const client = {
6851
6498
  console.error('fs listeners not ready during init');
6852
6499
  }
6853
6500
  globalService.send({ type: 'init', endpoints, models, addresses });
6854
- import('./seed.schema.config-miFErQ6h.js').then(({ models }) => {
6501
+ import('./seed.schema.config-BEvGEHkp.js').then(({ models }) => {
6855
6502
  for (const [key, value] of Object.entries(models)) {
6856
6503
  setModel(key, value);
6857
6504
  }
@@ -6900,14 +6547,395 @@ const client = {
6900
6547
  },
6901
6548
  };
6902
6549
 
6903
- const getItemPropertyData = (props) => __awaiter(void 0, void 0, void 0, function* () {
6550
+ const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
6904
6551
  const appDb = getAppDb();
6905
6552
  const whereClauses = [];
6906
- const tableColumns = getTableColumns(metadata);
6907
- for (const [propertyName, propertyValue] of Object.entries(props)) {
6908
- if (Object.keys(tableColumns).includes(propertyName)) {
6909
- whereClauses.push(eq(tableColumns[propertyName], propertyValue));
6910
- }
6553
+ if (seedLocalId) {
6554
+ whereClauses.push(eq(versions.localId, seedLocalId));
6555
+ }
6556
+ if (localId) {
6557
+ whereClauses.push(eq(versions.localId, localId));
6558
+ }
6559
+ if (uid) {
6560
+ whereClauses.push(eq(versions.uid, uid));
6561
+ }
6562
+ const queryRows = yield appDb
6563
+ .select()
6564
+ .from(versions)
6565
+ .where(and(...whereClauses));
6566
+ if (!queryRows || !queryRows.length) {
6567
+ return;
6568
+ }
6569
+ return queryRows[0];
6570
+ });
6571
+
6572
+ const logger = debug('app:write:updateItemPropertyValue');
6573
+ const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
6574
+ if (!modelName || (!seedLocalId && !seedUid)) {
6575
+ return;
6576
+ }
6577
+ eventEmitter.emit(`item.${modelName}.${seedUid || seedLocalId}.update`);
6578
+ };
6579
+ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, localStorageDir, }) {
6580
+ if (!localId && !seedLocalId) {
6581
+ logger(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
6582
+ return;
6583
+ }
6584
+ let safeNewValue = newValue;
6585
+ if (typeof newValue === 'string' &&
6586
+ !refResolvedDisplayValue &&
6587
+ !refResolvedValue) {
6588
+ safeNewValue = escapeSqliteString(newValue);
6589
+ }
6590
+ const appDb = getAppDb();
6591
+ const rows = yield appDb
6592
+ .select()
6593
+ .from(metadata)
6594
+ .where(and(eq(metadata.propertyName, propertyName), eq(metadata.seedLocalId, seedLocalId)))
6595
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'));
6596
+ // const mostRecentRecordStatement = `SELECT local_id,
6597
+ // uid,
6598
+ // property_name,
6599
+ // property_value,
6600
+ // model_type,
6601
+ // seed_uid,
6602
+ // seed_local_id,
6603
+ // version_local_id,
6604
+ // version_uid,
6605
+ // schema_uid,
6606
+ // eas_data_type
6607
+ // FROM metadata
6608
+ // WHERE property_name = '${propertyName}'
6609
+ // AND seed_local_id = '${seedLocalId}'
6610
+ // ORDER BY COALESCE(attestation_created_at, created_at) DESC;`
6611
+ //
6612
+ // const { rows } = await runQueryForStatement(mostRecentRecordStatement)
6613
+ if (rows && rows.length > 0) {
6614
+ const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, modelType, seedUid, seedLocalId: seedLocalIdFromDb, versionLocalId, versionUid, schemaUid, easDataType, localStorageDir: localStorageDirFromDb, refSeedType: refSeedTypeFromDb, refResolvedValue: refResolvedValueFromDb, refResolvedDisplayValue: refResolvedDisplayValueFromDb, } = rows[0];
6615
+ if (propertyValueFromDb === newValue &&
6616
+ modelType === (modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase()) &&
6617
+ refSeedTypeFromDb === refSeedType &&
6618
+ refResolvedValueFromDb === refResolvedValue) {
6619
+ logger(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
6620
+ return;
6621
+ }
6622
+ // This means we already have a local-only record so we should just update that one
6623
+ if (!uid) {
6624
+ const updatePropertyStatement = `UPDATE metadata
6625
+ SET property_value = '${safeNewValue}',
6626
+ ref_seed_type = ${refSeedType ? `'${refSeedType}'` : 'NULL'},
6627
+ ref_resolved_value = ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
6628
+ ref_resolved_display_value = ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
6629
+ updated_at = ${Date.now()}
6630
+ WHERE local_id = '${localId}';`;
6631
+ yield runQueryForStatement(updatePropertyStatement);
6632
+ sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6633
+ return;
6634
+ }
6635
+ const seedDataFromDb = yield getSeedData({ seedLocalId });
6636
+ const versionDataFromDb = yield getVersionData({ localId: versionLocalId });
6637
+ // Here we don't have a local-only record so we need to create a new one
6638
+ const newLocalId = generateId();
6639
+ const newPropertyStatement = `INSERT INTO metadata (local_id,
6640
+ property_name,
6641
+ property_value,
6642
+ model_type,
6643
+ seed_uid,
6644
+ seed_local_id,
6645
+ version_local_id,
6646
+ version_uid,
6647
+ schema_uid,
6648
+ eas_data_type,
6649
+ ref_seed_type,
6650
+ ref_resolved_value,
6651
+ ref_resolved_display_value,
6652
+ local_storage_dir,
6653
+ created_at)
6654
+ VALUES ('${newLocalId}',
6655
+ '${propertyNameFromDb}',
6656
+ '${safeNewValue}',
6657
+ '${modelType || (modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase())}',
6658
+ ${(seedDataFromDb === null || seedDataFromDb === void 0 ? void 0 : seedDataFromDb.uid) ? `'${seedDataFromDb.uid}'` : 'NULL'},
6659
+ '${seedLocalIdFromDb}',
6660
+ '${versionLocalId}',
6661
+ ${(versionDataFromDb === null || versionDataFromDb === void 0 ? void 0 : versionDataFromDb.uid) ? `'${versionDataFromDb.uid}'` : 'NULL'},
6662
+ '${schemaUid}',
6663
+ ${easDataType ? `'${easDataType}'` : 'NULL'},
6664
+ ${refSeedType ? `'${refSeedType}'` : 'NULL'},
6665
+ ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
6666
+ ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
6667
+ ${localStorageDir ? `'${localStorageDir}'` : 'NULL'},
6668
+ ${Date.now()});`;
6669
+ yield runQueryForStatement(newPropertyStatement);
6670
+ sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6671
+ return;
6672
+ }
6673
+ // Here there are no records for this property on this seed so we should create one
6674
+ const newLocalId = generateId();
6675
+ if (!seedUid) {
6676
+ const seedData = yield getSeedData({ seedLocalId });
6677
+ if (seedData) {
6678
+ seedUid = seedData.uid;
6679
+ }
6680
+ }
6681
+ if (!versionUid) {
6682
+ const versionData = yield getVersionData({ localId: versionLocalId });
6683
+ if (versionData) {
6684
+ versionUid = versionData.uid;
6685
+ }
6686
+ }
6687
+ const newPropertyStatement = `INSERT INTO metadata (local_id,
6688
+ property_name,
6689
+ property_value,
6690
+ model_type,
6691
+ seed_uid,
6692
+ seed_local_id,
6693
+ version_local_id,
6694
+ version_uid,
6695
+ schema_uid,
6696
+ ref_seed_type,
6697
+ ref_resolved_value,
6698
+ ref_resolved_display_value,
6699
+ local_storage_dir,
6700
+ created_at)
6701
+ VALUES ('${newLocalId}',
6702
+ '${propertyName}',
6703
+ '${safeNewValue}',
6704
+ '${modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase()}',
6705
+ ${seedUid ? `'${seedUid}'` : 'NULL'},
6706
+ '${seedLocalId}',
6707
+ '${versionLocalId}',
6708
+ ${versionUid ? `'${versionUid}'` : 'NULL'},
6709
+ '${schemaUid}',
6710
+ ${refSeedType ? `'${refSeedType}'` : 'NULL'},
6711
+ ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
6712
+ ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
6713
+ ${Date.now()});`;
6714
+ yield runQueryForStatement(newPropertyStatement);
6715
+ sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6716
+ });
6717
+
6718
+ const readFileAsArrayBuffer = (file) => __awaiter(void 0, void 0, void 0, function* () {
6719
+ return new Promise((resolve) => {
6720
+ const reader = new FileReader();
6721
+ reader.onload = (e) => __awaiter(void 0, void 0, void 0, function* () {
6722
+ const arrayBuffer = e.target.result;
6723
+ resolve(arrayBuffer);
6724
+ });
6725
+ reader.readAsArrayBuffer(file);
6726
+ });
6727
+ });
6728
+ const fetchImage = (url) => __awaiter(void 0, void 0, void 0, function* () {
6729
+ const response = yield fetch(url);
6730
+ const mimeType = response.headers.get('Content-Type');
6731
+ const imageBuffer = yield response.arrayBuffer();
6732
+ const bytes = new Uint8Array(imageBuffer);
6733
+ const binaryString = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), '');
6734
+ let base64 = btoa(binaryString);
6735
+ if (mimeType) {
6736
+ base64 = `data:${mimeType};base64,${base64}`;
6737
+ }
6738
+ return base64;
6739
+ });
6740
+ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
6741
+ const { localId, propertyName: propertyNameRaw, propertyValue: existingValue, propertyRecordSchema, itemModelName, seedLocalId, seedUid, versionLocalId, versionUid, schemaUid, } = context;
6742
+ if (seedLocalId === 'qpIzW1e52r') {
6743
+ console.log(`[saveImageSrc] versionLocaId is : ${versionLocalId}`);
6744
+ }
6745
+ let newValue;
6746
+ if (event) {
6747
+ newValue = event.newValue;
6748
+ }
6749
+ if (existingValue === newValue) {
6750
+ sendBack({ type: 'saveValueToDbSuccess' });
6751
+ return;
6752
+ }
6753
+ const _saveImageSrc = () => __awaiter(void 0, void 0, void 0, function* () {
6754
+ let propertyName = propertyNameRaw;
6755
+ if (!propertyNameRaw.endsWith('Id')) {
6756
+ propertyName = `${propertyName}Id`;
6757
+ }
6758
+ let newValueType;
6759
+ let fileData;
6760
+ let mimeType;
6761
+ let fileName;
6762
+ if (typeof newValue === 'string') {
6763
+ newValueType = getDataTypeFromString(newValue);
6764
+ }
6765
+ if (newValueType === 'imageBase64') {
6766
+ mimeType = getMimeType(newValue);
6767
+ const base64Data = newValue.split(',')[1]; // Strip the Base64 prefix
6768
+ const binaryString = atob(base64Data);
6769
+ const binaryLength = binaryString.length;
6770
+ const binaryArray = new Uint8Array(binaryLength);
6771
+ for (let i = 0; i < binaryLength; i++) {
6772
+ binaryArray[i] = binaryString.charCodeAt(i);
6773
+ }
6774
+ fileData = binaryArray.buffer;
6775
+ }
6776
+ if (newValueType === 'url') {
6777
+ fileData = yield fetchImage(newValue);
6778
+ }
6779
+ if (newValue instanceof File) {
6780
+ fileName = newValue.name;
6781
+ mimeType = newValue.type;
6782
+ fileData = yield readFileAsArrayBuffer(newValue);
6783
+ }
6784
+ if (!fileData) {
6785
+ throw new Error('No file data found');
6786
+ }
6787
+ const newImageSeedLocalId = yield createSeed({
6788
+ type: 'image',
6789
+ });
6790
+ if (!fileName) {
6791
+ fileName = newImageSeedLocalId;
6792
+ if (mimeType) {
6793
+ fileName += `.${mimeType.split('/')[1]}`;
6794
+ }
6795
+ }
6796
+ const filePath = `/files/images/${fileName}`;
6797
+ yield createVersion({
6798
+ seedLocalId: newImageSeedLocalId,
6799
+ seedType: 'image',
6800
+ });
6801
+ if (fileData instanceof ArrayBuffer) {
6802
+ yield fs.promises.writeFile(filePath, new Uint8Array(fileData));
6803
+ }
6804
+ if (typeof fileData === 'string') {
6805
+ yield fs.promises.writeFile(filePath, fileData);
6806
+ }
6807
+ const refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
6808
+ if (!localId) {
6809
+ yield createMetadata({
6810
+ propertyName,
6811
+ propertyValue: newImageSeedLocalId,
6812
+ seedLocalId,
6813
+ seedUid,
6814
+ versionLocalId,
6815
+ versionUid,
6816
+ modelName: itemModelName,
6817
+ schemaUid,
6818
+ refSeedType: 'image',
6819
+ refResolvedDisplayValue,
6820
+ refResolvedValue: fileName,
6821
+ localStorageDir: '/images',
6822
+ easDataType: 'bytes32',
6823
+ }, propertyRecordSchema);
6824
+ }
6825
+ if (localId) {
6826
+ yield updateItemPropertyValue({
6827
+ localId: localId,
6828
+ propertyName: propertyNameRaw,
6829
+ newValue: newImageSeedLocalId,
6830
+ seedLocalId,
6831
+ versionLocalId,
6832
+ modelName: itemModelName,
6833
+ schemaUid,
6834
+ refSeedType: 'image',
6835
+ refResolvedDisplayValue,
6836
+ refResolvedValue: fileName,
6837
+ localStorageDir: '/images',
6838
+ easDataType: 'bytes32',
6839
+ });
6840
+ }
6841
+ sendBack({
6842
+ type: 'updateContext',
6843
+ propertyValue: newImageSeedLocalId,
6844
+ refSeedType: 'image',
6845
+ renderValue: refResolvedDisplayValue,
6846
+ resolvedDisplayValue: refResolvedDisplayValue,
6847
+ resolvedValue: fileName,
6848
+ });
6849
+ });
6850
+ _saveImageSrc().then(() => {
6851
+ sendBack({ type: 'saveImageSrcSuccess' });
6852
+ });
6853
+ });
6854
+
6855
+ const saveRelation = fromCallback(({ sendBack, input: { context, event } }) => {
6856
+ const { localId, propertyName: propertyNameRaw, versionLocalId, seedUid, seedLocalId, propertyValue: existingValue, propertyRecordSchema, } = context;
6857
+ if (!propertyRecordSchema) {
6858
+ throw new Error('Missing propertyRecordSchema');
6859
+ }
6860
+ let newValue;
6861
+ if (event) {
6862
+ newValue = event.newValue;
6863
+ }
6864
+ const _saveRelation = () => __awaiter(void 0, void 0, void 0, function* () {
6865
+ let propertyName = propertyNameRaw;
6866
+ if (!propertyName.endsWith('Id')) {
6867
+ propertyName = `${propertyName}Id`;
6868
+ }
6869
+ let newValueType;
6870
+ if (typeof newValue === 'string') {
6871
+ newValueType = getDataTypeFromString(newValue);
6872
+ }
6873
+ if (newValue instanceof File) {
6874
+ newValueType = 'file';
6875
+ }
6876
+ if (propertyRecordSchema.dataType === 'ImageSrc') {
6877
+ sendBack({
6878
+ type: 'saveImageSrc',
6879
+ newValue,
6880
+ newValueType,
6881
+ });
6882
+ return false;
6883
+ }
6884
+ return true;
6885
+ // let fileType
6886
+ //
6887
+ // const dirs = await fs.promises.readdir('/files')
6888
+ //
6889
+ // for (const dir of dirs) {
6890
+ // const files = await fs.promises.readdir(`/files/${dir}`)
6891
+ // if (newValue && files.includes(newValue as string)) {
6892
+ // fileType = dir
6893
+ // break
6894
+ // }
6895
+ // }
6896
+ //
6897
+ // if (newValue && fileType === 'images') {
6898
+ // const filePath = `/files/images/${newValue}`
6899
+ // refResolvedDisplayValue = await getContentUrlFromPath(filePath)
6900
+ // refSeedType = 'image'
6901
+ // newValue = await createSeed({
6902
+ // type: refSeedType,
6903
+ // })
6904
+ // await createVersion({
6905
+ // seedLocalId,
6906
+ // seedUid,
6907
+ // seedType: refSeedType,
6908
+ // })
6909
+ // }
6910
+ //
6911
+ // await updateItemPropertyValue({
6912
+ // propertyLocalId: localId,
6913
+ // propertyName,
6914
+ // newValue,
6915
+ // seedLocalId,
6916
+ // refSeedType,
6917
+ // refResolvedValue,
6918
+ // refResolvedDisplayValue,
6919
+ // versionLocalId,
6920
+ // modelName: itemModelName,
6921
+ // schemaUid,
6922
+ // })
6923
+ });
6924
+ _saveRelation().then((isDone) => {
6925
+ if (isDone) {
6926
+ sendBack({ type: 'saveRelationSuccess' });
6927
+ }
6928
+ });
6929
+ });
6930
+
6931
+ const getItemPropertyData = (props) => __awaiter(void 0, void 0, void 0, function* () {
6932
+ const appDb = getAppDb();
6933
+ const whereClauses = [];
6934
+ const tableColumns = getTableColumns(metadata);
6935
+ for (const [propertyName, propertyValue] of Object.entries(props)) {
6936
+ if (Object.keys(tableColumns).includes(propertyName)) {
6937
+ whereClauses.push(eq(tableColumns[propertyName], propertyValue));
6938
+ }
6911
6939
  }
6912
6940
  const queryRows = yield appDb
6913
6941
  .select()
@@ -7051,7 +7079,7 @@ const analyzeInput = fromCallback(({ sendBack, input: { context, event } }) => {
7051
7079
  return false;
7052
7080
  }
7053
7081
  yield updateItemPropertyValue({
7054
- propertyLocalId: localId,
7082
+ localId: localId,
7055
7083
  propertyName,
7056
7084
  newValue,
7057
7085
  seedLocalId,
@@ -7123,6 +7151,9 @@ const propertyMachine = setup({
7123
7151
  updateContext: {
7124
7152
  actions: assign(({ context, event }) => {
7125
7153
  const newContext = Object.assign({}, context);
7154
+ if (context.seedLocalId === 'qpIzW1e52r') {
7155
+ console.log(`[updateContext] before update versionLocalId is ${context.versionLocalId}`);
7156
+ }
7126
7157
  for (let i = 0; i < Object.keys(event).length; i++) {
7127
7158
  const key = Object.keys(event)[i];
7128
7159
  if (key === 'type') {
@@ -7130,6 +7161,9 @@ const propertyMachine = setup({
7130
7161
  }
7131
7162
  newContext[key] = event[key];
7132
7163
  }
7164
+ if (context.seedLocalId === 'qpIzW1e52r') {
7165
+ console.log(`[updateContext] after update versionLocalId is ${newContext.versionLocalId}`);
7166
+ }
7133
7167
  return newContext;
7134
7168
  }),
7135
7169
  },
@@ -7425,4 +7459,4 @@ if (isNode()) {
7425
7459
  }
7426
7460
 
7427
7461
  export { GET_SCHEMAS as G, Item as I, Json as J, List as L, Model as M, Property as P, Relation as R, Text as T, GET_SEEDS as a, GET_SEED_IDS as b, GET_STORAGE_TRANSACTION_ID as c, GET_VERSIONS as d, GET_PROPERTIES as e, GET_ALL_PROPERTIES_FOR_ALL_VERSIONS as f, itemMachineAll as g, ImageSrc as h, itemMachineSingle as i, ItemProperty as j, useItem as k, useItemProperties as l, useCreateItem as m, useItemProperty as n, useDeleteItem as o, useGlobalServiceStatus as p, useServices as q, getGlobalService as r, client as s, getCorrectId as t, useItems as u, withSeed as w };
7428
- //# sourceMappingURL=index-nGDuz8NN.js.map
7462
+ //# sourceMappingURL=index-YshZfGRu.js.map