@seedprotocol/sdk 0.1.67 → 0.1.70

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 (31) hide show
  1. package/dist/{index-BJn9UAOX.js → index-B6WilINl.js} +6 -6
  2. package/dist/index-B6WilINl.js.map +1 -0
  3. package/dist/{index-nGDuz8NN.js → index-Cy1fke9s.js} +575 -535
  4. package/dist/index-Cy1fke9s.js.map +1 -0
  5. package/dist/main.js +4 -4
  6. package/dist/{seed.schema.config-miFErQ6h.js → seed.schema.config-dylVDX7W.js} +5 -5
  7. package/dist/{seed.schema.config-miFErQ6h.js.map → seed.schema.config-dylVDX7W.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 +28 -1
  12. package/dist/src/index.ts +104 -19
  13. package/dist/src/propertyMachine.ts +12 -0
  14. package/dist/src/saveImageSrc.ts +11 -2
  15. package/dist/src/updateItemPropertyValue.ts +230 -0
  16. package/dist/src/write.ts +2 -228
  17. package/dist/types/src/browser/db/read/getItems.d.ts.map +1 -1
  18. package/dist/types/src/browser/db/read/getVersionData.d.ts +1 -1
  19. package/dist/types/src/browser/db/read/getVersionData.d.ts.map +1 -1
  20. package/dist/types/src/browser/db/write/createMetadata.d.ts.map +1 -1
  21. package/dist/types/src/browser/db/write/updateItemPropertyValue.d.ts +5 -0
  22. package/dist/types/src/browser/db/write/updateItemPropertyValue.d.ts.map +1 -0
  23. package/dist/types/src/browser/db/write.d.ts +0 -16
  24. package/dist/types/src/browser/db/write.d.ts.map +1 -1
  25. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  26. package/dist/types/src/browser/property/actors/saveValueToDb/index.d.ts.map +1 -1
  27. package/dist/types/src/browser/property/actors/saveValueToDb/saveImageSrc.d.ts.map +1 -1
  28. package/dist/types/src/browser/property/propertyMachine.d.ts.map +1 -1
  29. package/package.json +1 -1
  30. package/dist/index-BJn9UAOX.js.map +0 -1
  31. 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';
@@ -989,7 +989,13 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
989
989
  urlNeedsToBeRefreshed = true;
990
990
  }
991
991
  if (urlNeedsToBeRefreshed) {
992
- const filePath = `/files/${localStorageDir}/${refResolvedValue}`;
992
+ let dir = localStorageDir;
993
+ if (!dir &&
994
+ propertyRecordSchema &&
995
+ propertyRecordSchema.refValueType === 'ImageSrc') {
996
+ dir = 'images';
997
+ }
998
+ const filePath = `/files/${dir}/${refResolvedValue}`;
993
999
  const fileExists = yield fs.promises.exists(filePath);
994
1000
  if (fileExists) {
995
1001
  const fileContents = yield fs.promises.readFile(filePath);
@@ -1004,6 +1010,24 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1004
1010
  typeof propertyValueFromDb === 'string') {
1005
1011
  propertyValueProcessed = propertyValueFromDb.split(',');
1006
1012
  }
1013
+ if (seedLocalIdFromDb === 'sAFXuO7Uez') {
1014
+ console.log(`[hydrateFromDb] sending updateContext with:`, {
1015
+ type: 'updateContext',
1016
+ localId,
1017
+ uid,
1018
+ propertyValue: propertyValueProcessed,
1019
+ seedLocalId: seedLocalIdFromDb,
1020
+ seedUid: seedUidFromDb,
1021
+ versionLocalId: versionLocalIdFromDb,
1022
+ versionUid: versionUidFromDb,
1023
+ schemaUid: schemaUidFromDb,
1024
+ refValueType,
1025
+ localStorageDir,
1026
+ resolvedValue: refResolvedValue,
1027
+ resolvedDisplayValue: refResolvedDisplayValue,
1028
+ renderValue: refResolvedDisplayValue,
1029
+ });
1030
+ }
1007
1031
  sendBack({
1008
1032
  type: 'updateContext',
1009
1033
  localId,
@@ -1023,7 +1047,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1023
1047
  if (propertyRecordSchema &&
1024
1048
  propertyRecordSchema.storageType &&
1025
1049
  propertyRecordSchema.storageType === 'ItemStorage') {
1026
- const { Item } = yield import('./index-BJn9UAOX.js');
1050
+ const { Item } = yield import('./index-B6WilINl.js');
1027
1051
  const item = yield Item.find({
1028
1052
  seedLocalId,
1029
1053
  modelName: itemModelName,
@@ -1046,47 +1070,59 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1046
1070
  });
1047
1071
  });
1048
1072
 
1049
- const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
1073
+ const getVersionData$1 = () => {
1050
1074
  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
- });
1075
+ return appDb.$with('versionData').as(appDb
1076
+ .select({
1077
+ seedLocalId: versions.seedLocalId,
1078
+ seedUid: versions.seedUid,
1079
+ latestVersionUid: versions.uid,
1080
+ latestVersionLocalId: versions.localId,
1081
+ versionsCount: count(versions.localId).as('versionsCount'),
1082
+ lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
1083
+ lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
1084
+ })
1085
+ .from(versions)
1086
+ .groupBy(versions.seedLocalId));
1087
+ };
1065
1088
 
1066
- const getVersionData$1 = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
1089
+ const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
1067
1090
  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));
1091
+ const conditions = [];
1092
+ if (modelName) {
1093
+ conditions.push(eq(seeds.type, modelName.toLowerCase()));
1074
1094
  }
1075
- if (uid) {
1076
- whereClauses.push(eq(versions.uid, uid));
1095
+ if (deleted) {
1096
+ conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
1077
1097
  }
1078
- const queryRows = yield appDb
1079
- .select()
1080
- .from(versions)
1081
- .where(and(...whereClauses));
1082
- if (!queryRows || !queryRows.length) {
1083
- return;
1098
+ if (!deleted) {
1099
+ conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
1084
1100
  }
1085
- return queryRows[0];
1101
+ const versionData = getVersionData$1();
1102
+ let query = appDb
1103
+ .with(versionData)
1104
+ .select({
1105
+ seedLocalId: seeds.localId,
1106
+ seedUid: seeds.uid,
1107
+ schemaUid: seeds.schemaUid,
1108
+ modelName: sql `${modelName}`,
1109
+ attestationCreatedAt: seeds.attestationCreatedAt,
1110
+ versionsCount: versionData.versionsCount,
1111
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
1112
+ lastLocalUpdateAt: versionData.lastLocalUpdateAt,
1113
+ latestVersionUid: versionData.latestVersionUid,
1114
+ latestVersionLocalId: versionData.latestVersionLocalId,
1115
+ createdAt: seeds.createdAt,
1116
+ })
1117
+ .from(seeds)
1118
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
1119
+ .where(and(gt(versionData.versionsCount, 0), ...conditions))
1120
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
1121
+ .groupBy(seeds.localId);
1122
+ const itemsData = (yield query);
1123
+ return itemsData;
1086
1124
  });
1087
1125
 
1088
- const eventEmitter = new EventEmitter();
1089
-
1090
1126
  const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid, seedType, uid, }) {
1091
1127
  const appDb = getAppDb();
1092
1128
  const newVersionLocalId = generateId();
@@ -1104,6 +1140,9 @@ const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedL
1104
1140
  const createMetadata = (metadataValues, propertyRecordSchema) => __awaiter(void 0, void 0, void 0, function* () {
1105
1141
  const appDb = getAppDb();
1106
1142
  metadataValues.localId = generateId();
1143
+ if (!metadataValues.modelType && metadataValues.modelName) {
1144
+ metadataValues.modelType = metadataValues.modelName.toLowerCase();
1145
+ }
1107
1146
  if (propertyRecordSchema &&
1108
1147
  propertyRecordSchema.localStorageDir &&
1109
1148
  propertyRecordSchema.storageType === 'ItemStorage') {
@@ -1130,13 +1169,7 @@ const setModel = (modelName, model) => {
1130
1169
  modelStore.set(modelName, model);
1131
1170
  };
1132
1171
 
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
- };
1172
+ debug('app:write');
1140
1173
  const createSeed = (_a) => __awaiter(void 0, [_a], void 0, function* ({ type, seedUid }) {
1141
1174
  const appDb = getAppDb();
1142
1175
  const newSeedLocalId = generateId();
@@ -1186,148 +1219,6 @@ const createNewItem = (_a) => __awaiter(void 0, void 0, void 0, function* () {
1186
1219
  versionLocalId: newVersionId,
1187
1220
  };
1188
1221
  });
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
1222
  const writeAppState = (key, value) => __awaiter(void 0, void 0, void 0, function* () {
1332
1223
  const appDb = getAppDb();
1333
1224
  yield appDb
@@ -1344,6 +1235,8 @@ const writeAppState = (key, value) => __awaiter(void 0, void 0, void 0, function
1344
1235
  });
1345
1236
  });
1346
1237
 
1238
+ const eventEmitter = new EventEmitter();
1239
+
1347
1240
  var MachineIds;
1348
1241
  (function (MachineIds) {
1349
1242
  MachineIds["GLOBAL"] = "@seedSdk/global";
@@ -1477,276 +1370,19 @@ const updateMachineContext = {
1477
1370
  }),
1478
1371
  };
1479
1372
 
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`;
1516
- }
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`);
1373
+ var _a$2;
1374
+ const logger$l = debug('app:property:class');
1375
+ const namesThatEndWithId = [];
1376
+ class ItemProperty {
1377
+ // private constructor(localIdOrUid) {
1378
+ // }
1379
+ constructor({ propertyValue, seedUid, seedLocalId, versionLocalId, versionUid, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1380
+ this._isRelation = false;
1381
+ this._isList = false;
1382
+ this[_a$2] = true;
1383
+ const ModelClass = getModel(itemModelName);
1384
+ if (!ModelClass) {
1385
+ throw new Error(`Model ${itemModelName} not found`);
1750
1386
  }
1751
1387
  if (!propertyName) {
1752
1388
  throw new Error(`Property name not provided`);
@@ -1785,7 +1421,7 @@ class ItemProperty {
1785
1421
  serviceInput.propertyValue = JSON.parse(propertyValue);
1786
1422
  }
1787
1423
  catch (e) {
1788
- logger$k('List property value is not JSON', e);
1424
+ logger$l('List property value is not JSON', e);
1789
1425
  }
1790
1426
  }
1791
1427
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -1867,7 +1503,7 @@ class ItemProperty {
1867
1503
  this._service.start();
1868
1504
  }
1869
1505
  _updateResponseListener(event) {
1870
- logger$k(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1506
+ logger$l(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1871
1507
  }
1872
1508
  static create(props) {
1873
1509
  const { propertyName, seedLocalId, seedUid, versionLocalId, versionUid } = props;
@@ -2014,7 +1650,7 @@ class ItemProperty {
2014
1650
  }
2015
1651
  unload() {
2016
1652
  this._service.stop();
2017
- logger$k(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1653
+ logger$l(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
2018
1654
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
2019
1655
  }
2020
1656
  }
@@ -2810,7 +2446,7 @@ const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, f
2810
2446
  trailing: false,
2811
2447
  });
2812
2448
 
2813
- const logger$j = debug('app:services:global:actors:initialize');
2449
+ const logger$k = debug('app:services:global:actors:initialize');
2814
2450
  const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2815
2451
  const { internalService, models, endpoints } = context;
2816
2452
  const { addresses } = event;
@@ -2831,7 +2467,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2831
2467
  const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
2832
2468
  return new Promise((resolve) => {
2833
2469
  internalSubscription = internalService.subscribe((snapshot) => {
2834
- logger$j('[sdk] [internal] snapshot', snapshot);
2470
+ logger$k('[sdk] [internal] snapshot', snapshot);
2835
2471
  if (snapshot.value === 'ready') {
2836
2472
  resolve();
2837
2473
  }
@@ -2865,14 +2501,14 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2865
2501
  sendBack(Object.assign({ type: GLOBAL_INITIALIZING_CREATE_ALL_ITEMS_SERVICES }, payloadObj));
2866
2502
  });
2867
2503
  _initFileSystem().then(() => {
2868
- logger$j('[global/actors] File system initialized');
2504
+ logger$k('[global/actors] File system initialized');
2869
2505
  });
2870
2506
  _initInternal()
2871
2507
  .then(() => {
2872
2508
  return _initAllItemsServices();
2873
2509
  })
2874
2510
  .then(() => {
2875
- logger$j('[global/actors] Internal initialized');
2511
+ logger$k('[global/actors] Internal initialized');
2876
2512
  sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
2877
2513
  internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
2878
2514
  });
@@ -2886,7 +2522,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2886
2522
  };
2887
2523
  });
2888
2524
 
2889
- const logger$i = debug('app:services:global:actors:getSchemaForModel');
2525
+ const logger$j = debug('app:services:global:actors:getSchemaForModel');
2890
2526
  const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
2891
2527
  const { modelName } = event;
2892
2528
  if (!modelName) {
@@ -2902,12 +2538,12 @@ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } })
2902
2538
  if (!model) {
2903
2539
  throw new Error(`Model ${modelName} not found`);
2904
2540
  }
2905
- logger$i('[service/actor] [getSchemaForModel] model:', model);
2541
+ logger$j('[service/actor] [getSchemaForModel] model:', model);
2906
2542
  sendBack({ type: 'schemaForModel', schema: model.schema });
2907
2543
  return () => { };
2908
2544
  });
2909
2545
 
2910
- const logger$h = debug('app:services:global:actors:addModelsToDb');
2546
+ const logger$i = debug('app:services:global:actors:addModelsToDb');
2911
2547
  const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2912
2548
  const { models: models$1 } = context;
2913
2549
  const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
@@ -2916,12 +2552,12 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2916
2552
  if (!models$1) {
2917
2553
  return;
2918
2554
  }
2919
- const { models: SeedModels } = yield import('./seed.schema.config-miFErQ6h.js');
2555
+ const { models: SeedModels } = yield import('./seed.schema.config-dylVDX7W.js');
2920
2556
  const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
2921
2557
  let hasModelsInDb = false;
2922
2558
  const schemaDefsByModelName = new Map();
2923
2559
  for (const [modelName, _] of Object.entries(allModels)) {
2924
- logger$h('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2560
+ logger$i('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2925
2561
  let foundModel;
2926
2562
  const foundModelsQuery = yield appDb
2927
2563
  .select()
@@ -2931,7 +2567,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2931
2567
  yield appDb.insert(models).values({
2932
2568
  name: modelName,
2933
2569
  });
2934
- logger$h('[global/actors] [addModelsToDb] inserted model:', modelName);
2570
+ logger$i('[global/actors] [addModelsToDb] inserted model:', modelName);
2935
2571
  const foundModels = yield appDb
2936
2572
  .select({
2937
2573
  id: models.id,
@@ -3001,10 +2637,10 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
3001
2637
  return () => { };
3002
2638
  });
3003
2639
 
3004
- const logger$g = debug('app:services:db:actors:checkStatus');
2640
+ const logger$h = debug('app:services:db:actors:checkStatus');
3005
2641
  const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
3006
2642
  const { dbName } = context;
3007
- logger$g('[db/actors] checkStatus context', context);
2643
+ logger$h('[db/actors] checkStatus context', context);
3008
2644
  const pathToDir = `${BROWSER_FS_TOP_DIR}`;
3009
2645
  const pathToDbDir = `${pathToDir}/db`;
3010
2646
  const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
@@ -3035,9 +2671,9 @@ const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
3035
2671
  });
3036
2672
  });
3037
2673
 
3038
- const logger$f = debug('app:services:db:actors:connectToDb');
2674
+ const logger$g = debug('app:services:db:actors:connectToDb');
3039
2675
  const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
3040
- logger$f('[db/actors] connectToDb context', context);
2676
+ logger$g('[db/actors] connectToDb context', context);
3041
2677
  const { dbName, pathToDir } = context;
3042
2678
  let isConnecting = false;
3043
2679
  let dbId;
@@ -3050,16 +2686,16 @@ const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
3050
2686
  const sqliteWasmClient = yield getSqliteWasmClient();
3051
2687
  //@ts-ignore
3052
2688
  response = yield sqliteWasmClient('config-get', {});
3053
- logger$f(response);
3054
- logger$f('Running SQLite3 version', response.result.version.libVersion);
2689
+ logger$g(response);
2690
+ logger$g('Running SQLite3 version', response.result.version.libVersion);
3055
2691
  //@ts-ignore
3056
2692
  response = yield sqliteWasmClient('open', {
3057
2693
  filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
3058
2694
  });
3059
- logger$f(response);
2695
+ logger$g(response);
3060
2696
  dbId = response.dbId;
3061
2697
  // logger(`dbId: ${dbId}`)
3062
- logger$f('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
2698
+ logger$g('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
3063
2699
  });
3064
2700
  const interval = setInterval(() => {
3065
2701
  // TODO: Add a timeout
@@ -3116,7 +2752,7 @@ const validate = fromCallback(({ sendBack, input: { context } }) => {
3116
2752
  });
3117
2753
  });
3118
2754
 
3119
- const logger$e = debug('app:services:db:actors:migrate');
2755
+ const logger$f = debug('app:services:db:actors:migrate');
3120
2756
  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
2757
  const rowsToReturnRaw = [];
3122
2758
  const sqliteWasmClient = yield getSqliteWasmClient();
@@ -3182,7 +2818,7 @@ const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void
3182
2818
  });
3183
2819
  const migrate = fromCallback(({ sendBack, input: { context } }) => {
3184
2820
  const { pathToDbDir, dbId, dbName } = context;
3185
- logger$e('[db/actors] migrate context', context);
2821
+ logger$f('[db/actors] migrate context', context);
3186
2822
  const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`;
3187
2823
  let journalExists = false;
3188
2824
  // const _initFs = async (): Promise<void> => {
@@ -3346,7 +2982,7 @@ const migrate = fromCallback(({ sendBack, input: { context } }) => {
3346
2982
  return () => { };
3347
2983
  });
3348
2984
 
3349
- const logger$d = debug('app:services:db:machine');
2985
+ const logger$e = debug('app:services:db:machine');
3350
2986
  const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
3351
2987
  const dbMachine = setup({
3352
2988
  types: {
@@ -3367,7 +3003,7 @@ const dbMachine = setup({
3367
3003
  [DB_WAITING_FOR_FILES_RECEIVED]: {
3368
3004
  actions: assign({
3369
3005
  hasFiles: ({ event }) => {
3370
- logger$d('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3006
+ logger$e('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3371
3007
  return true;
3372
3008
  },
3373
3009
  }),
@@ -3376,8 +3012,8 @@ const dbMachine = setup({
3376
3012
  target: `.${CHECKING_STATUS}`,
3377
3013
  actions: assign({
3378
3014
  hasFiles: ({ context, event }) => {
3379
- logger$d('[db/machine] updateHasFiles event:', event);
3380
- logger$d('[db/machine] updateHasFiles context:', context);
3015
+ logger$e('[db/machine] updateHasFiles event:', event);
3016
+ logger$e('[db/machine] updateHasFiles context:', context);
3381
3017
  return event.hasFiles;
3382
3018
  },
3383
3019
  }),
@@ -3598,7 +3234,7 @@ const prepareDb = fromCallback(({ sendBack }) => {
3598
3234
  };
3599
3235
  });
3600
3236
 
3601
- const logger$c = debug('app:services:internal:helpers');
3237
+ const logger$d = debug('app:services:internal:helpers');
3602
3238
  /**
3603
3239
  * Recursively create directories if they don't exist.
3604
3240
  * @param {string} dirPath - The directory path to create.
@@ -3674,7 +3310,7 @@ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, f
3674
3310
  if (JSON.stringify(error).includes('File exists')) {
3675
3311
  yield fs.promises.readFile(localFilePath, 'utf-8');
3676
3312
  }
3677
- logger$c(`[Error] Failed to download file from ${url}:`, error);
3313
+ logger$d(`[Error] Failed to download file from ${url}:`, error);
3678
3314
  }
3679
3315
  busy = false;
3680
3316
  });
@@ -3712,7 +3348,7 @@ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePat
3712
3348
  const fileList = yield fetchDirectory(filePaths);
3713
3349
  yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
3714
3350
  yield confirmFilesExist(fileList);
3715
- logger$c('[syncDbFiles] Files synced!');
3351
+ logger$d('[syncDbFiles] Files synced!');
3716
3352
  });
3717
3353
 
3718
3354
  const uploadBinaryData = fromCallback(({ sendBack, receive, input }) => { });
@@ -3935,7 +3571,7 @@ const GET_TRANSACTION_TAGS = graphql(/* GraphQL */ `
3935
3571
  }
3936
3572
  `);
3937
3573
 
3938
- const logger$b = debug('app:files:download');
3574
+ const logger$c = debug('app:files:download');
3939
3575
  const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
3940
3576
  yield syncDbFiles(endpoints);
3941
3577
  eventEmitter.emit('fs.downloadAll.success', { eventId });
@@ -4019,7 +3655,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4019
3655
  try {
4020
3656
  const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
4021
3657
  if (res.status !== 200) {
4022
- logger$b(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
3658
+ logger$c(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
4023
3659
  excludedTransactions.add(transactionId);
4024
3660
  yield writeAppState('excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
4025
3661
  continue;
@@ -4056,7 +3692,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4056
3692
  // string: true,
4057
3693
  // })
4058
3694
  if (!dataString) {
4059
- logger$b(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
3695
+ logger$c(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
4060
3696
  }
4061
3697
  let contentType = identifyString(dataString);
4062
3698
  if (contentType !== 'json' &&
@@ -4064,7 +3700,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4064
3700
  contentType !== 'html') {
4065
3701
  const possibleImageType = getDataTypeFromString(dataString);
4066
3702
  if (!possibleImageType) {
4067
- logger$b(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
3703
+ logger$c(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
4068
3704
  continue;
4069
3705
  }
4070
3706
  contentType = possibleImageType;
@@ -4127,7 +3763,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4127
3763
  }
4128
3764
  }
4129
3765
  catch (error) {
4130
- logger$b(error);
3766
+ logger$c(error);
4131
3767
  }
4132
3768
  }
4133
3769
  });
@@ -4173,14 +3809,14 @@ const isFsInitialized = () => {
4173
3809
  return isInitialized;
4174
3810
  };
4175
3811
 
4176
- const logger$a = debug('app:internal:actors:configureFs');
3812
+ const logger$b = debug('app:internal:actors:configureFs');
4177
3813
  const configureFs = fromCallback(({ sendBack, input: { context } }) => {
4178
3814
  const { endpoints, appDbService } = context;
4179
- logger$a('[internal/actors] [configureFs] Configuring FS');
3815
+ logger$b('[internal/actors] [configureFs] Configuring FS');
4180
3816
  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());
3817
+ logger$b('[internal/actors] [configureFs] calling _configureFs');
3818
+ logger$b('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
3819
+ logger$b('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
4184
3820
  yield waitForEvent({
4185
3821
  req: {
4186
3822
  eventLabel: 'fs.downloadAll.request',
@@ -4209,7 +3845,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
4209
3845
  // }
4210
3846
  // }, 200)
4211
3847
  // })
4212
- logger$a('[internal/actors] [configureFs] fs configured!');
3848
+ logger$b('[internal/actors] [configureFs] fs configured!');
4213
3849
  });
4214
3850
  // Some of our dependencies use fs sync functions, which don't work with
4215
3851
  // OPFS. ZenFS creates an async cache of all files so that the sync functions
@@ -4222,7 +3858,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
4222
3858
  return () => { };
4223
3859
  });
4224
3860
 
4225
- const logger$9 = debug('app:services:internal:actors:saveConfig');
3861
+ const logger$a = debug('app:services:internal:actors:saveConfig');
4226
3862
  const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
4227
3863
  if (typeof window === 'undefined') {
4228
3864
  console.error('seedInitBrowser called from non-browser context');
@@ -4273,20 +3909,20 @@ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
4273
3909
  },
4274
3910
  setWhere: sql `key = 'addresses'`,
4275
3911
  });
4276
- logger$9('[sdk] [internal/actors] Should be done saving');
3912
+ logger$a('[sdk] [internal/actors] Should be done saving');
4277
3913
  }
4278
3914
  catch (error) {
4279
3915
  console.error('Error saving config:', error);
4280
3916
  }
4281
3917
  });
4282
3918
  _saveConfig().then(() => {
4283
- logger$9('[sdk] [internal/actors] Successfully saved config');
3919
+ logger$a('[sdk] [internal/actors] Successfully saved config');
4284
3920
  return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
4285
3921
  });
4286
3922
  return () => { };
4287
3923
  });
4288
3924
 
4289
- const logger$8 = debug('app:services:internal:actors:loadAppDb');
3925
+ const logger$9 = debug('app:services:internal:actors:loadAppDb');
4290
3926
  const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4291
3927
  const { appDbService } = context;
4292
3928
  let subscription;
@@ -4307,7 +3943,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4307
3943
  });
4308
3944
  _loadAppDb().then(() => {
4309
3945
  sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
4310
- logger$8('[sdk] [internal/actors] Successfully loaded app DB');
3946
+ logger$9('[sdk] [internal/actors] Successfully loaded app DB');
4311
3947
  });
4312
3948
  return () => {
4313
3949
  if (subscription) {
@@ -4316,7 +3952,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4316
3952
  };
4317
3953
  });
4318
3954
 
4319
- const logger$7 = debug('app:services:internal:machine');
3955
+ const logger$8 = debug('app:services:internal:machine');
4320
3956
  createBrowserInspector({
4321
3957
  autoStart: false,
4322
3958
  });
@@ -4415,7 +4051,7 @@ const internalMachine = setup({
4415
4051
  [INTERNAL_LOADING_APP_DB_SUCCESS]: {
4416
4052
  target: SAVING_CONFIG,
4417
4053
  actions: () => {
4418
- logger$7('[sdk] [internal/index] App DB loaded!');
4054
+ logger$8('[sdk] [internal/index] App DB loaded!');
4419
4055
  },
4420
4056
  },
4421
4057
  },
@@ -4441,7 +4077,7 @@ const internalMachine = setup({
4441
4077
  },
4442
4078
  ready: {
4443
4079
  entry: () => {
4444
- logger$7('[sdk] [internal/index] Ready!');
4080
+ logger$8('[sdk] [internal/index] Ready!');
4445
4081
  },
4446
4082
  meta: {
4447
4083
  displayText: "Crossing the t's ...",
@@ -4456,7 +4092,7 @@ const internalMachine = setup({
4456
4092
  },
4457
4093
  },
4458
4094
  entry: () => {
4459
- logger$7('[sdk] [internal/index] Error!');
4095
+ logger$8('[sdk] [internal/index] Error!');
4460
4096
  },
4461
4097
  meta: {
4462
4098
  displayText: 'Whoops! Something went wrong.',
@@ -4692,7 +4328,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
4692
4328
  return () => { };
4693
4329
  });
4694
4330
 
4695
- const logger$6 = debug('app:allItemsActors:fetchSeeds');
4331
+ const logger$7 = debug('app:allItemsActors:fetchSeeds');
4696
4332
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4697
4333
  const { queryVariables, modelName } = context;
4698
4334
  if (!queryVariables) {
@@ -4702,7 +4338,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4702
4338
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
4703
4339
  const queryKey = [`getSeeds${modelName}`];
4704
4340
  const cachedResults = queryClient.getQueryData(queryKey);
4705
- logger$6(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4341
+ logger$7(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4706
4342
  const results = yield queryClient.fetchQuery({
4707
4343
  queryKey,
4708
4344
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -5133,13 +4769,13 @@ const preparePublishRequestData = fromCallback(({ sendBack, input: { context } }
5133
4769
  });
5134
4770
  });
5135
4771
 
5136
- const logger$5 = debug('app:services:publish:actors:upload');
4772
+ const logger$6 = debug('app:services:publish:actors:upload');
5137
4773
  const upload = fromCallback(({ sendBack, input: { context } }) => {
5138
4774
  const { localId } = context;
5139
4775
  const _upload = () => __awaiter(void 0, void 0, void 0, function* () {
5140
4776
  const item = yield Item.find({ seedLocalId: localId });
5141
4777
  if (!item) {
5142
- logger$5('no item with localId', localId);
4778
+ logger$6('no item with localId', localId);
5143
4779
  return false;
5144
4780
  }
5145
4781
  const editedProperties = yield item.getEditedProperties();
@@ -6004,7 +5640,24 @@ const getItemProperties = (_a) => __awaiter(void 0, [_a], void 0, function* ({ s
6004
5640
  // })
6005
5641
  // }
6006
5642
 
6007
- const logger$4 = debug('app:db:queries:getItem');
5643
+ const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
5644
+ const appDb = getAppDb();
5645
+ let query;
5646
+ const queryBase = appDb.select().from(seeds);
5647
+ if (seedLocalId) {
5648
+ query = queryBase.where(eq(seeds.localId, seedLocalId));
5649
+ }
5650
+ if (seedUid) {
5651
+ query = queryBase.where(eq(seeds.uid, seedUid));
5652
+ }
5653
+ const rows = yield query;
5654
+ if (!rows || !rows.length) {
5655
+ return;
5656
+ }
5657
+ return rows[0];
5658
+ });
5659
+
5660
+ const logger$5 = debug('app:db:queries:getItem');
6008
5661
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
6009
5662
  if (!seedLocalId && !seedUid) {
6010
5663
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -6012,7 +5665,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6012
5665
  if (seedUid && !seedLocalId) {
6013
5666
  const seedData = yield getSeedData({ seedUid });
6014
5667
  if (!seedData) {
6015
- logger$4('[db/queries] [getItem] no seedData seedUid', seedUid);
5668
+ logger$5('[db/queries] [getItem] no seedData seedUid', seedUid);
6016
5669
  return;
6017
5670
  }
6018
5671
  seedLocalId = seedData.localId;
@@ -6029,7 +5682,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6029
5682
  if (seedLocalId && !seedUid) {
6030
5683
  whereClauses.push(eq(seeds.localId, seedLocalId));
6031
5684
  }
6032
- const versionData = getVersionData();
5685
+ const versionData = getVersionData$1();
6033
5686
  const itemDataRows = yield appDb
6034
5687
  .with(versionData)
6035
5688
  .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 +5692,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6039
5692
  .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
6040
5693
  .groupBy(seeds.localId);
6041
5694
  if (!itemDataRows || itemDataRows.length === 0) {
6042
- logger$4('[db/queries] [getItemDataFromDb] no itemDataRows');
5695
+ logger$5('[db/queries] [getItemDataFromDb] no itemDataRows');
6043
5696
  return;
6044
5697
  }
6045
5698
  let itemData = itemDataRows[0];
@@ -6315,7 +5968,7 @@ class Item {
6315
5968
  _a$1 = immerable;
6316
5969
  Item.instanceCache = new Map();
6317
5970
 
6318
- const logger$3 = debug('app:react:services');
5971
+ const logger$4 = debug('app:react:services');
6319
5972
  const finalStrings = ['idle', 'ready', 'done', 'success'];
6320
5973
  const getServiceName = (service) => {
6321
5974
  let name = 'actor';
@@ -6362,7 +6015,7 @@ const getServiceUniqueKey = (service) => {
6362
6015
  snapshot = service.getSnapshot();
6363
6016
  }
6364
6017
  catch (error) {
6365
- logger$3('Error:', error);
6018
+ logger$4('Error:', error);
6366
6019
  return uniqueKey;
6367
6020
  }
6368
6021
  if (snapshot) {
@@ -6466,7 +6119,7 @@ const useGlobalServiceStatus = () => {
6466
6119
  };
6467
6120
  };
6468
6121
 
6469
- const logger$2 = debug('app:react:item');
6122
+ const logger$3 = debug('app:react:item');
6470
6123
  const useItem = ({ modelName, seedLocalId, seedUid }) => {
6471
6124
  // const [itemSubscription, setItemSubscription] = useState<
6472
6125
  // Subscription | undefined
@@ -6543,7 +6196,7 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6543
6196
  seedUid,
6544
6197
  });
6545
6198
  if (!foundItem) {
6546
- logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6199
+ logger$3('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6547
6200
  isReadingDb.current = false;
6548
6201
  return;
6549
6202
  }
@@ -6565,7 +6218,7 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6565
6218
  const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6566
6219
  const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6567
6220
  if (!newItem) {
6568
- logger$2('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6221
+ logger$3('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6569
6222
  return;
6570
6223
  }
6571
6224
  updateItem(newItem);
@@ -6682,7 +6335,7 @@ const useCreateItem = (modelName) => {
6682
6335
  };
6683
6336
  };
6684
6337
 
6685
- const logger$1 = debug('app:react:property');
6338
+ const logger$2 = debug('app:react:property');
6686
6339
  const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6687
6340
  const [property, setProperty] = useState();
6688
6341
  const [isInitialized, setIsInitialized] = useState(false);
@@ -6708,7 +6361,7 @@ const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6708
6361
  seedUid,
6709
6362
  });
6710
6363
  if (!foundProperty) {
6711
- logger$1(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6364
+ logger$2(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6712
6365
  isReadingDb.current = false;
6713
6366
  return;
6714
6367
  }
@@ -6805,10 +6458,10 @@ const useDeleteItem = () => {
6805
6458
  };
6806
6459
  };
6807
6460
 
6808
- const logger = debug('app:services:events');
6461
+ const logger$1 = debug('app:services:events');
6809
6462
  const handleServiceSaveState = (event) => {
6810
6463
  const { state, serviceId } = event;
6811
- logger(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6464
+ logger$1(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6812
6465
  localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state));
6813
6466
  };
6814
6467
  const setupServicesEventHandlers = () => {
@@ -6851,7 +6504,7 @@ const client = {
6851
6504
  console.error('fs listeners not ready during init');
6852
6505
  }
6853
6506
  globalService.send({ type: 'init', endpoints, models, addresses });
6854
- import('./seed.schema.config-miFErQ6h.js').then(({ models }) => {
6507
+ import('./seed.schema.config-dylVDX7W.js').then(({ models }) => {
6855
6508
  for (const [key, value] of Object.entries(models)) {
6856
6509
  setModel(key, value);
6857
6510
  }
@@ -6900,18 +6553,399 @@ const client = {
6900
6553
  },
6901
6554
  };
6902
6555
 
6903
- const getItemPropertyData = (props) => __awaiter(void 0, void 0, void 0, function* () {
6556
+ const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
6904
6557
  const appDb = getAppDb();
6905
6558
  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
- }
6559
+ if (seedLocalId) {
6560
+ whereClauses.push(eq(versions.localId, seedLocalId));
6561
+ }
6562
+ if (localId) {
6563
+ whereClauses.push(eq(versions.localId, localId));
6564
+ }
6565
+ if (uid) {
6566
+ whereClauses.push(eq(versions.uid, uid));
6911
6567
  }
6912
6568
  const queryRows = yield appDb
6913
6569
  .select()
6914
- .from(metadata)
6570
+ .from(versions)
6571
+ .where(and(...whereClauses));
6572
+ if (!queryRows || !queryRows.length) {
6573
+ return;
6574
+ }
6575
+ return queryRows[0];
6576
+ });
6577
+
6578
+ const logger = debug('app:write:updateItemPropertyValue');
6579
+ const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
6580
+ if (!modelName || (!seedLocalId && !seedUid)) {
6581
+ return;
6582
+ }
6583
+ eventEmitter.emit(`item.${modelName}.${seedUid || seedLocalId}.update`);
6584
+ };
6585
+ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, localStorageDir, }) {
6586
+ if (!localId && !seedLocalId) {
6587
+ logger(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
6588
+ return;
6589
+ }
6590
+ let safeNewValue = newValue;
6591
+ if (typeof newValue === 'string' &&
6592
+ !refResolvedDisplayValue &&
6593
+ !refResolvedValue) {
6594
+ safeNewValue = escapeSqliteString(newValue);
6595
+ }
6596
+ const appDb = getAppDb();
6597
+ const rows = yield appDb
6598
+ .select()
6599
+ .from(metadata)
6600
+ .where(and(eq(metadata.propertyName, propertyName), eq(metadata.seedLocalId, seedLocalId)))
6601
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'));
6602
+ // const mostRecentRecordStatement = `SELECT local_id,
6603
+ // uid,
6604
+ // property_name,
6605
+ // property_value,
6606
+ // model_type,
6607
+ // seed_uid,
6608
+ // seed_local_id,
6609
+ // version_local_id,
6610
+ // version_uid,
6611
+ // schema_uid,
6612
+ // eas_data_type
6613
+ // FROM metadata
6614
+ // WHERE property_name = '${propertyName}'
6615
+ // AND seed_local_id = '${seedLocalId}'
6616
+ // ORDER BY COALESCE(attestation_created_at, created_at) DESC;`
6617
+ //
6618
+ // const { rows } = await runQueryForStatement(mostRecentRecordStatement)
6619
+ if (rows && rows.length > 0) {
6620
+ 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];
6621
+ if (propertyValueFromDb === newValue &&
6622
+ modelType === (modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase()) &&
6623
+ refSeedTypeFromDb === refSeedType &&
6624
+ refResolvedValueFromDb === refResolvedValue) {
6625
+ logger(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
6626
+ return;
6627
+ }
6628
+ // This means we already have a local-only record so we should just update that one
6629
+ if (!uid) {
6630
+ const updatePropertyStatement = `UPDATE metadata
6631
+ SET property_value = '${safeNewValue}',
6632
+ ref_seed_type = ${refSeedType ? `'${refSeedType}'` : 'NULL'},
6633
+ ref_resolved_value = ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
6634
+ ref_resolved_display_value = ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
6635
+ updated_at = ${Date.now()}
6636
+ WHERE local_id = '${localId}';`;
6637
+ yield runQueryForStatement(updatePropertyStatement);
6638
+ sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6639
+ return;
6640
+ }
6641
+ const seedDataFromDb = yield getSeedData({ seedLocalId });
6642
+ const versionDataFromDb = yield getVersionData({ localId: versionLocalId });
6643
+ // Here we don't have a local-only record so we need to create a new one
6644
+ const newLocalId = generateId();
6645
+ const newPropertyStatement = `INSERT INTO metadata (local_id,
6646
+ property_name,
6647
+ property_value,
6648
+ model_type,
6649
+ seed_uid,
6650
+ seed_local_id,
6651
+ version_local_id,
6652
+ version_uid,
6653
+ schema_uid,
6654
+ eas_data_type,
6655
+ ref_seed_type,
6656
+ ref_resolved_value,
6657
+ ref_resolved_display_value,
6658
+ local_storage_dir,
6659
+ created_at)
6660
+ VALUES ('${newLocalId}',
6661
+ '${propertyNameFromDb}',
6662
+ '${safeNewValue}',
6663
+ '${modelType || (modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase())}',
6664
+ ${(seedDataFromDb === null || seedDataFromDb === void 0 ? void 0 : seedDataFromDb.uid) ? `'${seedDataFromDb.uid}'` : 'NULL'},
6665
+ '${seedLocalIdFromDb}',
6666
+ '${versionLocalId}',
6667
+ ${(versionDataFromDb === null || versionDataFromDb === void 0 ? void 0 : versionDataFromDb.uid) ? `'${versionDataFromDb.uid}'` : 'NULL'},
6668
+ '${schemaUid}',
6669
+ ${easDataType ? `'${easDataType}'` : 'NULL'},
6670
+ ${refSeedType ? `'${refSeedType}'` : 'NULL'},
6671
+ ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
6672
+ ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
6673
+ ${localStorageDir ? `'${localStorageDir}'` : 'NULL'},
6674
+ ${Date.now()});`;
6675
+ yield runQueryForStatement(newPropertyStatement);
6676
+ sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6677
+ return;
6678
+ }
6679
+ // Here there are no records for this property on this seed so we should create one
6680
+ const newLocalId = generateId();
6681
+ if (!seedUid) {
6682
+ const seedData = yield getSeedData({ seedLocalId });
6683
+ if (seedData) {
6684
+ seedUid = seedData.uid;
6685
+ }
6686
+ }
6687
+ if (!versionUid) {
6688
+ const versionData = yield getVersionData({ localId: versionLocalId });
6689
+ if (versionData) {
6690
+ versionUid = versionData.uid;
6691
+ }
6692
+ }
6693
+ const newPropertyStatement = `INSERT INTO metadata (local_id,
6694
+ property_name,
6695
+ property_value,
6696
+ model_type,
6697
+ seed_uid,
6698
+ seed_local_id,
6699
+ version_local_id,
6700
+ version_uid,
6701
+ schema_uid,
6702
+ ref_seed_type,
6703
+ ref_resolved_value,
6704
+ ref_resolved_display_value,
6705
+ local_storage_dir,
6706
+ created_at)
6707
+ VALUES ('${newLocalId}',
6708
+ '${propertyName}',
6709
+ '${safeNewValue}',
6710
+ '${modelName === null || modelName === void 0 ? void 0 : modelName.toLowerCase()}',
6711
+ ${seedUid ? `'${seedUid}'` : 'NULL'},
6712
+ '${seedLocalId}',
6713
+ '${versionLocalId}',
6714
+ ${versionUid ? `'${versionUid}'` : 'NULL'},
6715
+ '${schemaUid}',
6716
+ ${refSeedType ? `'${refSeedType}'` : 'NULL'},
6717
+ ${refResolvedValue ? `'${refResolvedValue}'` : 'NULL'},
6718
+ ${refResolvedDisplayValue ? `'${refResolvedDisplayValue}'` : 'NULL'},
6719
+ ${Date.now()});`;
6720
+ yield runQueryForStatement(newPropertyStatement);
6721
+ sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6722
+ });
6723
+
6724
+ const readFileAsArrayBuffer = (file) => __awaiter(void 0, void 0, void 0, function* () {
6725
+ return new Promise((resolve) => {
6726
+ const reader = new FileReader();
6727
+ reader.onload = (e) => __awaiter(void 0, void 0, void 0, function* () {
6728
+ const arrayBuffer = e.target.result;
6729
+ resolve(arrayBuffer);
6730
+ });
6731
+ reader.readAsArrayBuffer(file);
6732
+ });
6733
+ });
6734
+ const fetchImage = (url) => __awaiter(void 0, void 0, void 0, function* () {
6735
+ const response = yield fetch(url);
6736
+ const mimeType = response.headers.get('Content-Type');
6737
+ const imageBuffer = yield response.arrayBuffer();
6738
+ const bytes = new Uint8Array(imageBuffer);
6739
+ const binaryString = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), '');
6740
+ let base64 = btoa(binaryString);
6741
+ if (mimeType) {
6742
+ base64 = `data:${mimeType};base64,${base64}`;
6743
+ }
6744
+ return base64;
6745
+ });
6746
+ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
6747
+ const { localId, propertyName: propertyNameRaw, propertyValue: existingValue, propertyRecordSchema, itemModelName, seedLocalId, seedUid, versionLocalId, versionUid, schemaUid, } = context;
6748
+ if (seedLocalId === 'qpIzW1e52r') {
6749
+ console.log(`[saveImageSrc] versionLocaId is : ${versionLocalId}`);
6750
+ }
6751
+ let newValue;
6752
+ if (event) {
6753
+ newValue = event.newValue;
6754
+ }
6755
+ if (existingValue === newValue) {
6756
+ sendBack({ type: 'saveValueToDbSuccess' });
6757
+ return;
6758
+ }
6759
+ const _saveImageSrc = () => __awaiter(void 0, void 0, void 0, function* () {
6760
+ let propertyName = propertyNameRaw;
6761
+ if (!propertyNameRaw.endsWith('Id')) {
6762
+ propertyName = `${propertyName}Id`;
6763
+ }
6764
+ let newValueType;
6765
+ let fileData;
6766
+ let mimeType;
6767
+ let fileName;
6768
+ if (typeof newValue === 'string') {
6769
+ newValueType = getDataTypeFromString(newValue);
6770
+ }
6771
+ if (newValueType === 'imageBase64') {
6772
+ mimeType = getMimeType(newValue);
6773
+ const base64Data = newValue.split(',')[1]; // Strip the Base64 prefix
6774
+ const binaryString = atob(base64Data);
6775
+ const binaryLength = binaryString.length;
6776
+ const binaryArray = new Uint8Array(binaryLength);
6777
+ for (let i = 0; i < binaryLength; i++) {
6778
+ binaryArray[i] = binaryString.charCodeAt(i);
6779
+ }
6780
+ fileData = binaryArray.buffer;
6781
+ }
6782
+ if (newValueType === 'url') {
6783
+ fileData = yield fetchImage(newValue);
6784
+ }
6785
+ if (newValue instanceof File) {
6786
+ fileName = newValue.name;
6787
+ mimeType = newValue.type;
6788
+ fileData = yield readFileAsArrayBuffer(newValue);
6789
+ }
6790
+ if (!fileData) {
6791
+ throw new Error('No file data found');
6792
+ }
6793
+ const newImageSeedLocalId = yield createSeed({
6794
+ type: 'image',
6795
+ });
6796
+ if (!fileName) {
6797
+ fileName = newImageSeedLocalId;
6798
+ if (mimeType) {
6799
+ fileName += `.${mimeType.split('/')[1]}`;
6800
+ }
6801
+ }
6802
+ const filePath = `/files/images/${fileName}`;
6803
+ yield createVersion({
6804
+ seedLocalId: newImageSeedLocalId,
6805
+ seedType: 'image',
6806
+ });
6807
+ if (fileData instanceof ArrayBuffer) {
6808
+ yield fs.promises.writeFile(filePath, new Uint8Array(fileData));
6809
+ }
6810
+ if (typeof fileData === 'string') {
6811
+ yield fs.promises.writeFile(filePath, fileData);
6812
+ }
6813
+ const refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
6814
+ if (!localId) {
6815
+ yield createMetadata({
6816
+ propertyName,
6817
+ propertyValue: newImageSeedLocalId,
6818
+ seedLocalId,
6819
+ seedUid,
6820
+ versionLocalId,
6821
+ versionUid,
6822
+ modelName: itemModelName,
6823
+ schemaUid,
6824
+ refSeedType: 'image',
6825
+ refResolvedDisplayValue,
6826
+ refResolvedValue: fileName,
6827
+ localStorageDir: '/images',
6828
+ easDataType: 'bytes32',
6829
+ }, propertyRecordSchema);
6830
+ }
6831
+ if (localId) {
6832
+ yield updateItemPropertyValue({
6833
+ localId: localId,
6834
+ propertyName: propertyNameRaw,
6835
+ newValue: newImageSeedLocalId,
6836
+ seedLocalId,
6837
+ versionLocalId,
6838
+ modelName: itemModelName,
6839
+ schemaUid,
6840
+ refSeedType: 'image',
6841
+ refResolvedDisplayValue,
6842
+ refResolvedValue: fileName,
6843
+ localStorageDir: '/images',
6844
+ easDataType: 'bytes32',
6845
+ });
6846
+ }
6847
+ sendBack({
6848
+ type: 'updateContext',
6849
+ propertyValue: newImageSeedLocalId,
6850
+ refSeedType: 'image',
6851
+ renderValue: refResolvedDisplayValue,
6852
+ resolvedDisplayValue: refResolvedDisplayValue,
6853
+ resolvedValue: fileName,
6854
+ });
6855
+ });
6856
+ _saveImageSrc().then(() => {
6857
+ sendBack({ type: 'saveImageSrcSuccess' });
6858
+ });
6859
+ });
6860
+
6861
+ const saveRelation = fromCallback(({ sendBack, input: { context, event } }) => {
6862
+ const { localId, propertyName: propertyNameRaw, versionLocalId, seedUid, seedLocalId, propertyValue: existingValue, propertyRecordSchema, } = context;
6863
+ if (!propertyRecordSchema) {
6864
+ throw new Error('Missing propertyRecordSchema');
6865
+ }
6866
+ let newValue;
6867
+ if (event) {
6868
+ newValue = event.newValue;
6869
+ }
6870
+ const _saveRelation = () => __awaiter(void 0, void 0, void 0, function* () {
6871
+ let propertyName = propertyNameRaw;
6872
+ if (!propertyName.endsWith('Id')) {
6873
+ propertyName = `${propertyName}Id`;
6874
+ }
6875
+ let newValueType;
6876
+ if (typeof newValue === 'string') {
6877
+ newValueType = getDataTypeFromString(newValue);
6878
+ }
6879
+ if (newValue instanceof File) {
6880
+ newValueType = 'file';
6881
+ }
6882
+ if (propertyRecordSchema.dataType === 'ImageSrc') {
6883
+ sendBack({
6884
+ type: 'saveImageSrc',
6885
+ newValue,
6886
+ newValueType,
6887
+ });
6888
+ return false;
6889
+ }
6890
+ return true;
6891
+ // let fileType
6892
+ //
6893
+ // const dirs = await fs.promises.readdir('/files')
6894
+ //
6895
+ // for (const dir of dirs) {
6896
+ // const files = await fs.promises.readdir(`/files/${dir}`)
6897
+ // if (newValue && files.includes(newValue as string)) {
6898
+ // fileType = dir
6899
+ // break
6900
+ // }
6901
+ // }
6902
+ //
6903
+ // if (newValue && fileType === 'images') {
6904
+ // const filePath = `/files/images/${newValue}`
6905
+ // refResolvedDisplayValue = await getContentUrlFromPath(filePath)
6906
+ // refSeedType = 'image'
6907
+ // newValue = await createSeed({
6908
+ // type: refSeedType,
6909
+ // })
6910
+ // await createVersion({
6911
+ // seedLocalId,
6912
+ // seedUid,
6913
+ // seedType: refSeedType,
6914
+ // })
6915
+ // }
6916
+ //
6917
+ // await updateItemPropertyValue({
6918
+ // propertyLocalId: localId,
6919
+ // propertyName,
6920
+ // newValue,
6921
+ // seedLocalId,
6922
+ // refSeedType,
6923
+ // refResolvedValue,
6924
+ // refResolvedDisplayValue,
6925
+ // versionLocalId,
6926
+ // modelName: itemModelName,
6927
+ // schemaUid,
6928
+ // })
6929
+ });
6930
+ _saveRelation().then((isDone) => {
6931
+ if (isDone) {
6932
+ sendBack({ type: 'saveRelationSuccess' });
6933
+ }
6934
+ });
6935
+ });
6936
+
6937
+ const getItemPropertyData = (props) => __awaiter(void 0, void 0, void 0, function* () {
6938
+ const appDb = getAppDb();
6939
+ const whereClauses = [];
6940
+ const tableColumns = getTableColumns(metadata);
6941
+ for (const [propertyName, propertyValue] of Object.entries(props)) {
6942
+ if (Object.keys(tableColumns).includes(propertyName)) {
6943
+ whereClauses.push(eq(tableColumns[propertyName], propertyValue));
6944
+ }
6945
+ }
6946
+ const queryRows = yield appDb
6947
+ .select()
6948
+ .from(metadata)
6915
6949
  .where(and(...whereClauses));
6916
6950
  if (!queryRows || queryRows.length === 0) {
6917
6951
  return;
@@ -7051,7 +7085,7 @@ const analyzeInput = fromCallback(({ sendBack, input: { context, event } }) => {
7051
7085
  return false;
7052
7086
  }
7053
7087
  yield updateItemPropertyValue({
7054
- propertyLocalId: localId,
7088
+ localId: localId,
7055
7089
  propertyName,
7056
7090
  newValue,
7057
7091
  seedLocalId,
@@ -7123,6 +7157,9 @@ const propertyMachine = setup({
7123
7157
  updateContext: {
7124
7158
  actions: assign(({ context, event }) => {
7125
7159
  const newContext = Object.assign({}, context);
7160
+ if (context.seedLocalId === 'qpIzW1e52r') {
7161
+ console.log(`[updateContext] before update versionLocalId is ${context.versionLocalId}`);
7162
+ }
7126
7163
  for (let i = 0; i < Object.keys(event).length; i++) {
7127
7164
  const key = Object.keys(event)[i];
7128
7165
  if (key === 'type') {
@@ -7130,6 +7167,9 @@ const propertyMachine = setup({
7130
7167
  }
7131
7168
  newContext[key] = event[key];
7132
7169
  }
7170
+ if (context.seedLocalId === 'qpIzW1e52r') {
7171
+ console.log(`[updateContext] after update versionLocalId is ${newContext.versionLocalId}`);
7172
+ }
7133
7173
  return newContext;
7134
7174
  }),
7135
7175
  },
@@ -7425,4 +7465,4 @@ if (isNode()) {
7425
7465
  }
7426
7466
 
7427
7467
  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
7468
+ //# sourceMappingURL=index-Cy1fke9s.js.map