@seedprotocol/sdk 0.1.53 → 0.1.55

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 (64) hide show
  1. package/dist/{index-5a9z-kqT.js → index-BkzKfVvD.js} +3 -3
  2. package/dist/index-BkzKfVvD.js.map +1 -0
  3. package/dist/{index-DcXK4ERW.js → index-D4my8yy8.js} +1493 -1079
  4. package/dist/index-D4my8yy8.js.map +1 -0
  5. package/dist/main.js +2 -2
  6. package/dist/{seed.schema.config-BtfzZOfM.js → seed.schema.config-BHZSMMmL.js} +2 -2
  7. package/dist/{seed.schema.config-BtfzZOfM.js.map → seed.schema.config-BHZSMMmL.js.map} +1 -1
  8. package/dist/src/ItemProperty.ts +114 -68
  9. package/dist/src/createMetadata.ts +36 -0
  10. package/dist/src/download.ts +6 -2
  11. package/dist/src/getItem.ts +12 -37
  12. package/dist/src/getItemProperty.ts +34 -0
  13. package/dist/src/getItems.ts +11 -18
  14. package/dist/src/getVersionData.ts +36 -48
  15. package/dist/src/hydrateFromDb.ts +11 -15
  16. package/dist/src/propertyMachine.ts +80 -18
  17. package/dist/src/resolveRelatedValue.ts +4 -0
  18. package/dist/src/saveImageSrc.ts +200 -0
  19. package/dist/src/saveItemStorage.ts +145 -0
  20. package/dist/src/saveRelation.ts +112 -0
  21. package/dist/src/syncDbWithEas.ts +1 -1
  22. package/dist/src/versionData.ts +24 -0
  23. package/dist/src/write.ts +27 -7
  24. package/dist/types/src/browser/db/read/getItem.d.ts.map +1 -1
  25. package/dist/types/src/browser/db/read/getItemProperty.d.ts +6 -0
  26. package/dist/types/src/browser/db/read/getItemProperty.d.ts.map +1 -0
  27. package/dist/types/src/browser/db/read/getItems.d.ts.map +1 -1
  28. package/dist/types/src/browser/db/read/getVersionData.d.ts +5 -14
  29. package/dist/types/src/browser/db/read/getVersionData.d.ts.map +1 -1
  30. package/dist/types/src/browser/db/read/subqueries/versionData.d.ts +70 -0
  31. package/dist/types/src/browser/db/read/subqueries/versionData.d.ts.map +1 -0
  32. package/dist/types/src/browser/db/write/createMetadata.d.ts +6 -0
  33. package/dist/types/src/browser/db/write/createMetadata.d.ts.map +1 -0
  34. package/dist/types/src/browser/db/write.d.ts.map +1 -1
  35. package/dist/types/src/browser/events/files/download.d.ts.map +1 -1
  36. package/dist/types/src/browser/item/Item.d.ts +1 -7
  37. package/dist/types/src/browser/item/Item.d.ts.map +1 -1
  38. package/dist/types/src/browser/property/ItemProperty.d.ts +24 -8
  39. package/dist/types/src/browser/property/ItemProperty.d.ts.map +1 -1
  40. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  41. package/dist/types/src/browser/property/actors/resolveRelatedValue.d.ts.map +1 -1
  42. package/dist/types/src/browser/property/actors/saveValueToDb/index.d.ts +8 -0
  43. package/dist/types/src/browser/property/actors/saveValueToDb/index.d.ts.map +1 -0
  44. package/dist/types/src/browser/property/actors/saveValueToDb/saveImageSrc.d.ts +5 -0
  45. package/dist/types/src/browser/property/actors/saveValueToDb/saveImageSrc.d.ts.map +1 -0
  46. package/dist/types/src/browser/property/actors/saveValueToDb/saveItemStorage.d.ts +5 -0
  47. package/dist/types/src/browser/property/actors/saveValueToDb/saveItemStorage.d.ts.map +1 -0
  48. package/dist/types/src/browser/property/actors/saveValueToDb/saveRelation.d.ts +5 -0
  49. package/dist/types/src/browser/property/actors/saveValueToDb/saveRelation.d.ts.map +1 -0
  50. package/dist/types/src/browser/property/index.d.ts +9 -9
  51. package/dist/types/src/browser/property/propertyMachine.d.ts.map +1 -1
  52. package/dist/types/src/browser/schema/file/fetchAll/actors.d.ts.map +1 -1
  53. package/dist/types/src/shared/helpers/index.d.ts +1 -1
  54. package/dist/types/src/shared/helpers/index.d.ts.map +1 -1
  55. package/dist/types/src/types/item.d.ts +17 -0
  56. package/dist/types/src/types/item.d.ts.map +1 -1
  57. package/dist/types/src/types/property.d.ts +15 -0
  58. package/dist/types/src/types/property.d.ts.map +1 -1
  59. package/package.json +1 -1
  60. package/dist/index-5a9z-kqT.js.map +0 -1
  61. package/dist/index-DcXK4ERW.js.map +0 -1
  62. package/dist/src/saveValueToDb.ts +0 -94
  63. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts +0 -2
  64. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts.map +0 -1
@@ -2,8 +2,8 @@ import { b as __awaiter, d as __rest, i as internalPropertyNames, I as INTERNAL_
2
2
  import path, { basename } from 'path';
3
3
  import 'reflect-metadata';
4
4
  import { Type } from '@sinclair/typebox';
5
- import { fromCallback, assign, setup, createActor, waitFor, emit, raise } from 'xstate';
6
- import { sql, relations, and, eq, max, or, inArray, like, isNotNull, isNull, count, desc, getTableColumns } from 'drizzle-orm';
5
+ import { fromCallback, assign, createActor, waitFor, setup, emit, raise } from 'xstate';
6
+ import { sql, relations, and, eq, max, or, count, isNotNull, isNull, inArray, like, getTableColumns, gt } from 'drizzle-orm';
7
7
  import { fs, configureSingle } from '@zenfs/core';
8
8
  import 'dayjs';
9
9
  import { customAlphabet } from 'nanoid';
@@ -16,6 +16,7 @@ import { QueryClient } from '@tanstack/react-query';
16
16
  import { GraphQLClient } from 'graphql-request';
17
17
  import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
18
18
  import { persistQueryClient } from '@tanstack/react-query-persist-client';
19
+ import { useState, useEffect, useRef, useCallback } from 'react';
19
20
  import { BehaviorSubject } from 'rxjs';
20
21
  import { immerable, produce, enableMapSet } from 'immer';
21
22
  import pluralize from 'pluralize';
@@ -23,7 +24,6 @@ import { createBrowserInspector } from '@statelyai/inspect';
23
24
  import { drizzle } from 'drizzle-orm/sqlite-proxy';
24
25
  import { WebAccess } from '@zenfs/dom';
25
26
  import Arweave from 'arweave';
26
- import { useState, useEffect, useRef, useCallback } from 'react';
27
27
  import { useImmer } from 'use-immer';
28
28
  import { useSelector } from '@xstate/react';
29
29
 
@@ -250,20 +250,22 @@ const getMimeType = (base64) => {
250
250
  return null; // MIME type could not be determined
251
251
  }
252
252
  };
253
- const getImageDataType = (data) => {
253
+ const getDataTypeFromString = (data) => {
254
+ const nonImageBase64Regex = /^(?!data:image\/(?:jpeg|png|gif|bmp|webp);base64,)[A-Za-z0-9+/=]+$/;
255
+ if (nonImageBase64Regex.test(data)) {
256
+ return 'base64';
257
+ }
254
258
  // Regular expression for base64 (simple version, checking for base64 format)
255
- const base64Regex = /^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/;
259
+ const imageBase64Regex = /^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/;
260
+ if (imageBase64Regex.test(data)) {
261
+ return 'imageBase64';
262
+ }
256
263
  // Regular expression for URL (simple version, checking for common URL format)
257
264
  const urlRegex = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/;
258
- if (base64Regex.test(data)) {
259
- return 'base64';
260
- }
261
- else if (urlRegex.test(data)) {
265
+ if (urlRegex.test(data)) {
262
266
  return 'url';
263
267
  }
264
- else {
265
- return null;
266
- }
268
+ return null;
267
269
  };
268
270
  const convertTxIdToImageSrc = (txId) => __awaiter(void 0, void 0, void 0, function* () {
269
271
  const imageFilePath = `/files/images/${txId}`;
@@ -514,6 +516,9 @@ const refResolvedValueToContentUrl = new Map();
514
516
  const seedUidToContentUrl = new Map();
515
517
  const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
516
518
  const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, seedLocalId, schemaUid, } = context;
519
+ if (seedLocalId === 'AhiILhtcVq') {
520
+ console.log('[resolveRelatedValue] seedLocalId', seedLocalId);
521
+ }
517
522
  const _resolveRelatedValue = () => __awaiter(void 0, void 0, void 0, function* () {
518
523
  if (!propertyValue || !isRelation) {
519
524
  return;
@@ -930,19 +935,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
930
935
  }
931
936
  propertyNameQuery = or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, missingPropertyNameVariant));
932
937
  }
933
- const selectFromStatement = db
934
- .select({
935
- localId: metadata.localId,
936
- uid: metadata.uid,
937
- propertyName: metadata.propertyName,
938
- propertyValue: metadata.propertyValue,
939
- seedLocalId: metadata.seedLocalId,
940
- seedUid: metadata.seedUid,
941
- schemaUid: metadata.schemaUid,
942
- refResolvedValue: metadata.refResolvedValue,
943
- refResolvedDisplayValue: metadata.refResolvedDisplayValue,
944
- })
945
- .from(metadata);
938
+ const selectFromStatement = db.select().from(metadata);
946
939
  if (seedUid && !seedLocalId) {
947
940
  hydrateQuery = selectFromStatement.where(and(eq(metadata.seedUid, seedUid), propertyNameQuery));
948
941
  }
@@ -960,7 +953,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
960
953
  return;
961
954
  }
962
955
  const firstRow = rows[0];
963
- const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, refResolvedValue, refResolvedDisplayValue, } = firstRow;
956
+ const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, versionLocalId: versionLocalIdFromDb, versionUid: versionUidFromDb, refValueType, refResolvedValue, refResolvedDisplayValue, localStorageDir, } = firstRow;
964
957
  if (propertyName && !propertyNameFromDb) {
965
958
  logger$m(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
966
959
  }
@@ -987,13 +980,17 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
987
980
  propertyValue: propertyValueFromDb,
988
981
  seedLocalId: seedLocalIdFromDb,
989
982
  seedUid: seedUidFromDb,
983
+ versionLocalId: versionLocalIdFromDb,
984
+ versionUid: versionUidFromDb,
990
985
  schemaUid: schemaUidFromDb,
991
- resolveValue: refResolvedValue,
992
- resolveDisplayValue: refResolvedDisplayValue,
986
+ refValueType,
987
+ localStorageDir,
988
+ resolvedValue: refResolvedValue,
989
+ resolvedDisplayValue: refResolvedDisplayValue,
993
990
  renderValue: refResolvedDisplayValue,
994
991
  });
995
992
  if (propertyNameFromDb === 'storageTransactionId') {
996
- const { Item } = yield import('./index-5a9z-kqT.js');
993
+ const { Item } = yield import('./index-BkzKfVvD.js');
997
994
  const item = yield Item.find({
998
995
  seedLocalId,
999
996
  modelName: itemModelName,
@@ -1062,36 +1059,26 @@ const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoc
1062
1059
  return rows[0];
1063
1060
  });
1064
1061
 
1065
- const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId }) {
1066
- const getVersionStatement = `SELECT local_id,
1067
- uid,
1068
- seed_local_id,
1069
- seed_uid,
1070
- seed_type,
1071
- note,
1072
- attestation_created_at,
1073
- attestation_raw,
1074
- created_at,
1075
- updated_at
1076
- FROM versions
1077
- WHERE local_id = '${seedLocalId}';`;
1078
- const { rows } = yield runQueryForStatement(getVersionStatement);
1079
- if (!rows || !rows.length) {
1062
+ const getVersionData$1 = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
1063
+ const appDb = getAppDb();
1064
+ const whereClauses = [];
1065
+ if (seedLocalId) {
1066
+ whereClauses.push(eq(versions.localId, seedLocalId));
1067
+ }
1068
+ if (localId) {
1069
+ whereClauses.push(eq(versions.localId, localId));
1070
+ }
1071
+ if (uid) {
1072
+ whereClauses.push(eq(versions.uid, uid));
1073
+ }
1074
+ const queryRows = yield appDb
1075
+ .select()
1076
+ .from(versions)
1077
+ .where(and(...whereClauses));
1078
+ if (!queryRows || !queryRows.length) {
1080
1079
  return;
1081
1080
  }
1082
- const seedValues = rows[0];
1083
- return {
1084
- localId: seedValues[0],
1085
- uid: seedValues[1],
1086
- seedLocalId: seedValues[2],
1087
- seedUid: seedValues[3],
1088
- seedType: seedValues[4],
1089
- note: seedValues[5],
1090
- attestationCreatedAt: seedValues[6],
1091
- attestationRaw: seedValues[7],
1092
- createdAt: seedValues[8],
1093
- updatedAt: seedValues[9],
1094
- };
1081
+ return queryRows[0];
1095
1082
  });
1096
1083
 
1097
1084
  const eventEmitter = new EventEmitter();
@@ -1110,6 +1097,35 @@ const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedL
1110
1097
  return newVersionLocalId;
1111
1098
  });
1112
1099
 
1100
+ const createMetadata = (metadataValues, propertyRecordSchema) => __awaiter(void 0, void 0, void 0, function* () {
1101
+ const appDb = getAppDb();
1102
+ metadataValues.localId = generateId();
1103
+ if (propertyRecordSchema &&
1104
+ propertyRecordSchema.localStorageDir &&
1105
+ propertyRecordSchema.storageType === 'ItemStorage') {
1106
+ metadataValues.refResolvedValue = `${metadataValues.seedLocalId}${propertyRecordSchema.filenameSuffix}`;
1107
+ metadataValues.refValueType = 'file';
1108
+ }
1109
+ return appDb
1110
+ .insert(metadata)
1111
+ .values(Object.assign(Object.assign({}, metadataValues), { createdAt: Date.now(), updatedAt: Date.now() }))
1112
+ .returning();
1113
+ });
1114
+
1115
+ const modelStore = new Map();
1116
+ const getModels = () => {
1117
+ return Object.fromEntries(modelStore);
1118
+ };
1119
+ const getModel = (modelName) => {
1120
+ return modelStore.get(modelName);
1121
+ };
1122
+ const getModelNames = () => {
1123
+ return Array.from(modelStore.keys());
1124
+ };
1125
+ const setModel = (modelName, model) => {
1126
+ modelStore.set(modelName, model);
1127
+ };
1128
+
1113
1129
  const logger$l = debug('app:write');
1114
1130
  const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
1115
1131
  if (!modelName || (!seedLocalId && !seedUid)) {
@@ -1129,19 +1145,36 @@ const createSeed = (_a) => __awaiter(void 0, [_a], void 0, function* ({ type, se
1129
1145
  return newSeedLocalId;
1130
1146
  });
1131
1147
  const createNewItem = (_a) => __awaiter(void 0, void 0, void 0, function* () {
1148
+ var _b;
1132
1149
  var { modelName } = _a, propertyData = __rest(_a, ["modelName"]);
1133
1150
  if (!modelName) {
1134
1151
  throw new Error('A model name is required for createNewItem');
1135
1152
  }
1136
- const appDb = getAppDb();
1153
+ getAppDb();
1137
1154
  const seedType = modelName.toLowerCase();
1138
1155
  const newSeedId = yield createSeed({ type: seedType });
1139
1156
  const newVersionId = yield createVersion({ seedLocalId: newSeedId });
1157
+ const propertySchemas = (_b = getModel(modelName)) === null || _b === void 0 ? void 0 : _b.schema;
1140
1158
  for (const [propertyName, propertyValue] of Object.entries(propertyData)) {
1141
- yield appDb.run(sql.raw(`INSERT INTO metadata (seed_local_id, version_local_id, property_name, property_value, model_type, created_at,
1142
- attestation_created_at)
1143
- VALUES ('${newSeedId}', '${newVersionId}', '${propertyName}', '${propertyValue}', '${seedType}', ${Date.now()},
1144
- ${Date.now()});`));
1159
+ let propertyRecordSchema;
1160
+ if (propertySchemas && propertySchemas[propertyName]) {
1161
+ propertyRecordSchema = propertySchemas[propertyName];
1162
+ }
1163
+ yield createMetadata({
1164
+ seedLocalId: newSeedId,
1165
+ versionLocalId: newVersionId,
1166
+ propertyName,
1167
+ propertyValue,
1168
+ modelName,
1169
+ }, propertyRecordSchema);
1170
+ // await appDb.run(
1171
+ // sql.raw(
1172
+ // `INSERT INTO metadata (seed_local_id, version_local_id, property_name, property_value, model_type, created_at,
1173
+ // attestation_created_at)
1174
+ // VALUES ('${newSeedId}', '${newVersionId}', '${propertyName}', '${propertyValue}', '${seedType}', ${Date.now()},
1175
+ // ${Date.now()});`,
1176
+ // ),
1177
+ // )
1145
1178
  }
1146
1179
  // eventEmitter.emit(`item.requestAll`, { modelName })
1147
1180
  return {
@@ -1208,7 +1241,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1208
1241
  return;
1209
1242
  }
1210
1243
  const seedDataFromDb = yield getSeedData({ seedLocalId });
1211
- const versionDataFromDb = yield getVersionData({ versionLocalId });
1244
+ const versionDataFromDb = yield getVersionData$1({ versionLocalId });
1212
1245
  // Here we don't have a local-only record so we need to create a new one
1213
1246
  const newLocalId = generateId();
1214
1247
  const newPropertyStatement = `INSERT INTO metadata (local_id,
@@ -1252,7 +1285,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1252
1285
  }
1253
1286
  }
1254
1287
  if (!versionUid) {
1255
- const versionData = yield getVersionData({ versionLocalId });
1288
+ const versionData = yield getVersionData$1({ versionLocalId });
1256
1289
  if (versionData) {
1257
1290
  versionUid = versionData.uid;
1258
1291
  }
@@ -1435,234 +1468,262 @@ const updateMachineContext = {
1435
1468
  }),
1436
1469
  };
1437
1470
 
1438
- const saveValueToDb = fromCallback(({ sendBack, input: { context, event } }) => {
1439
- const { localId, propertyName: propertyNameRaw, seedLocalId, propertyValue: existingValue, propertyRecordSchema, itemModelName, schemaUid, } = context;
1440
- let { newValue } = event;
1471
+ const readFileAsArrayBuffer = (file) => __awaiter(void 0, void 0, void 0, function* () {
1472
+ return new Promise((resolve) => {
1473
+ const reader = new FileReader();
1474
+ reader.onload = (e) => __awaiter(void 0, void 0, void 0, function* () {
1475
+ const arrayBuffer = e.target.result;
1476
+ resolve(arrayBuffer);
1477
+ });
1478
+ reader.readAsArrayBuffer(file);
1479
+ });
1480
+ });
1481
+ const fetchImage = (url) => __awaiter(void 0, void 0, void 0, function* () {
1482
+ const response = yield fetch(url);
1483
+ const mimeType = response.headers.get('Content-Type');
1484
+ const imageBuffer = yield response.arrayBuffer();
1485
+ const bytes = new Uint8Array(imageBuffer);
1486
+ const binaryString = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), '');
1487
+ let base64 = btoa(binaryString);
1488
+ if (mimeType) {
1489
+ base64 = `data:${mimeType};base64,${base64}`;
1490
+ }
1491
+ return base64;
1492
+ });
1493
+ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
1494
+ const { localId, propertyName: propertyNameRaw, propertyValue: existingValue, propertyRecordSchema, itemModelName, seedLocalId, seedUid, versionLocalId, versionUid, schemaUid, } = context;
1495
+ let newValue;
1496
+ if (event) {
1497
+ newValue = event.newValue;
1498
+ }
1441
1499
  if (existingValue === newValue) {
1442
1500
  sendBack({ type: 'saveValueToDbSuccess' });
1443
1501
  return;
1444
1502
  }
1445
- const _saveValueToDb = () => __awaiter(void 0, void 0, void 0, function* () {
1446
- let refResolvedValue;
1447
- let refResolvedDisplayValue;
1448
- let refSeedType;
1503
+ const _saveImageSrc = () => __awaiter(void 0, void 0, void 0, function* () {
1449
1504
  let propertyName = propertyNameRaw;
1450
- let versionLocalId;
1451
- if (propertyRecordSchema &&
1452
- propertyRecordSchema.dataType === 'Relation') {
1453
- refResolvedValue = newValue;
1454
- if (!propertyName.endsWith('Id')) {
1455
- propertyName = `${propertyName}Id`;
1456
- }
1457
- let fileType;
1458
- const dirs = yield fs.promises.readdir('/files');
1459
- for (const dir of dirs) {
1460
- const files = yield fs.promises.readdir(`/files/${dir}`);
1461
- if (files.includes(newValue)) {
1462
- fileType = dir;
1463
- break;
1464
- }
1465
- }
1466
- if (fileType === 'images') {
1467
- const filePath = `/files/images/${newValue}`;
1468
- refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
1469
- refSeedType = 'image';
1470
- newValue = yield createSeed({
1471
- type: refSeedType,
1472
- });
1473
- versionLocalId = yield createVersion({
1474
- seedLocalId: newValue,
1475
- seedType: refSeedType,
1476
- });
1505
+ if (!propertyNameRaw.endsWith('Id')) {
1506
+ propertyName = `${propertyName}Id`;
1507
+ }
1508
+ let newValueType;
1509
+ let fileData;
1510
+ let mimeType;
1511
+ let fileName;
1512
+ if (typeof newValue === 'string') {
1513
+ newValueType = getDataTypeFromString(newValue);
1514
+ }
1515
+ if (newValueType === 'imageBase64') {
1516
+ mimeType = getMimeType(newValue);
1517
+ }
1518
+ if (newValueType === 'url') {
1519
+ fileData = yield fetchImage(newValue);
1520
+ }
1521
+ if (newValue instanceof File) {
1522
+ fileName = newValue.name;
1523
+ mimeType = newValue.type;
1524
+ fileData = yield readFileAsArrayBuffer(newValue);
1525
+ }
1526
+ if (!fileData) {
1527
+ throw new Error('No file data found');
1528
+ }
1529
+ const newImageSeedLocalId = yield createSeed({
1530
+ type: 'image',
1531
+ });
1532
+ if (!fileName) {
1533
+ fileName = newImageSeedLocalId;
1534
+ if (mimeType) {
1535
+ fileName += `.${mimeType.split('/')[1]}`;
1477
1536
  }
1478
1537
  }
1479
- yield updateItemPropertyValue({
1480
- propertyLocalId: localId,
1481
- propertyName,
1482
- newValue,
1483
- seedLocalId,
1484
- refSeedType,
1485
- refResolvedValue,
1486
- refResolvedDisplayValue,
1487
- versionLocalId,
1488
- modelName: itemModelName,
1489
- schemaUid,
1538
+ const filePath = `/files/images/${fileName}`;
1539
+ yield createVersion({
1540
+ seedLocalId: newImageSeedLocalId,
1541
+ seedType: 'image',
1490
1542
  });
1543
+ if (fileData instanceof ArrayBuffer) {
1544
+ yield fs.promises.writeFile(filePath, new Uint8Array(fileData));
1545
+ }
1546
+ if (typeof fileData === 'string') {
1547
+ yield fs.promises.writeFile(filePath, fileData);
1548
+ }
1549
+ const refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
1550
+ if (!localId) {
1551
+ yield createMetadata({
1552
+ propertyName,
1553
+ propertyValue: newImageSeedLocalId,
1554
+ seedLocalId,
1555
+ seedUid,
1556
+ versionLocalId,
1557
+ versionUid,
1558
+ modelName: itemModelName,
1559
+ schemaUid,
1560
+ refSeedType: 'image',
1561
+ refResolvedDisplayValue,
1562
+ refResolvedValue: fileName,
1563
+ }, propertyRecordSchema);
1564
+ }
1565
+ if (localId) {
1566
+ yield updateItemPropertyValue({
1567
+ propertyLocalId: localId,
1568
+ propertyName: propertyNameRaw,
1569
+ newValue: newImageSeedLocalId,
1570
+ seedLocalId,
1571
+ versionLocalId,
1572
+ modelName: itemModelName,
1573
+ schemaUid,
1574
+ refSeedType: 'image',
1575
+ refResolvedDisplayValue,
1576
+ refResolvedValue: fileName,
1577
+ });
1578
+ }
1491
1579
  sendBack({
1492
1580
  type: 'updateContext',
1493
- propertyValue: newValue,
1581
+ propertyValue: newImageSeedLocalId,
1582
+ refSeedType: 'image',
1494
1583
  renderValue: refResolvedDisplayValue,
1584
+ resolvedDisplayValue: refResolvedDisplayValue,
1585
+ resolvedValue: fileName,
1495
1586
  });
1496
1587
  });
1497
- _saveValueToDb().then(() => {
1498
- sendBack({ type: 'saveValueToDbSuccess' });
1588
+ _saveImageSrc().then(() => {
1589
+ sendBack({ type: 'saveImageSrcSuccess' });
1499
1590
  });
1500
1591
  });
1501
1592
 
1502
- const propertyMachine = setup({
1503
- types: {
1504
- context: {},
1505
- },
1506
- actors: {
1507
- waitForDb: waitForDb$1,
1508
- hydrateFromDb,
1509
- initialize: initialize$3,
1510
- resolveRelatedValue,
1511
- resolveRemoteStorage,
1512
- saveValueToDb,
1513
- },
1514
- }).createMachine({
1515
- id: 'itemProperty',
1516
- initial: 'waitingForDb',
1517
- context: ({ input }) => input,
1518
- on: {
1519
- updatePropertyValue: {
1520
- target: '.resolvingRelatedValue',
1521
- guard: ({ context }) => !context.isDbReady,
1522
- actions: assign(({ event }) => {
1523
- return {
1524
- propertyValue: event.propertyValue,
1525
- };
1526
- }),
1527
- },
1528
- updateRenderValue: {
1529
- actions: assign(({ event, context }) => {
1530
- return {
1531
- renderValue: event.renderValue,
1532
- };
1533
- }),
1534
- },
1535
- save: {
1536
- actions: assign({
1537
- isSaving: true,
1538
- }),
1539
- target: '.saving',
1540
- },
1541
- updateContext: updateMachineContext,
1542
- },
1543
- states: {
1544
- idle: {},
1545
- waitingForDb: {
1546
- on: {
1547
- waitForDbSuccess: {
1548
- target: 'hydratingFromDb',
1549
- actions: assign({
1550
- isDbReady: true,
1551
- }),
1552
- },
1553
- },
1554
- invoke: {
1555
- src: 'waitForDb',
1556
- input: ({ context }) => ({ context }),
1557
- },
1558
- },
1559
- hydratingFromDb: {
1560
- on: {
1561
- hydrateFromDbSuccess: 'initializing',
1562
- },
1563
- invoke: {
1564
- src: 'hydrateFromDb',
1565
- input: ({ context }) => ({ context }),
1566
- },
1567
- },
1568
- initializing: {
1569
- on: {
1570
- initializeSuccess: 'idle',
1571
- isRelatedProperty: {
1572
- target: 'resolvingRelatedValue',
1573
- },
1574
- hasRemoteBackup: {
1575
- target: 'resolvingRemoteStorage',
1576
- },
1577
- },
1578
- invoke: {
1579
- src: 'initialize',
1580
- input: ({ context, event }) => ({ context, event }),
1581
- },
1582
- },
1583
- resolvingRelatedValue: {
1584
- on: {
1585
- resolvingRelatedValueSuccess: {
1586
- target: 'idle',
1587
- actions: assign({
1588
- resolvedDisplayValue: ({ event }) => event.resolvedDisplayValue,
1589
- resolvedValue: ({ event }) => event.resolvedValue,
1590
- }),
1591
- },
1592
- resolvingRelatedValueDone: {
1593
- target: 'idle',
1594
- },
1595
- },
1596
- invoke: {
1597
- src: 'resolveRelatedValue',
1598
- input: ({ context }) => ({ context }),
1599
- },
1600
- },
1601
- resolvingRemoteStorage: {
1602
- on: {
1603
- resolveRemoteStorageSuccess: {
1604
- target: 'idle',
1605
- },
1606
- },
1607
- invoke: {
1608
- src: 'resolveRemoteStorage',
1609
- input: ({ context }) => ({ context }),
1610
- },
1611
- },
1612
- saving: {
1613
- on: {
1614
- saveValueToDbSuccess: {
1615
- target: 'idle',
1616
- actions: assign({
1617
- isSaving: false,
1618
- }),
1619
- },
1620
- saveValueToDbFailure: {
1621
- target: 'idle',
1622
- actions: assign({
1623
- isSaving: false,
1624
- }),
1625
- },
1626
- },
1627
- invoke: {
1628
- src: 'saveValueToDb',
1629
- input: ({ context, event }) => ({ context, event }),
1630
- },
1631
- },
1632
- },
1633
- // conflict: {
1634
- // on: {
1635
- // resolveConflict: {
1636
- // target: 'saving',
1637
- // actions: assign({
1638
- // data: ({ context, event }) => event.output,
1639
- // }),
1640
- // },
1641
- // },
1642
- // },
1643
- });
1644
-
1645
- const modelStore = new Map();
1646
- const getModels = () => {
1647
- return Object.fromEntries(modelStore);
1648
- };
1649
- const getModel = (modelName) => {
1650
- return modelStore.get(modelName);
1651
- };
1652
- const getModelNames = () => {
1653
- return Array.from(modelStore.keys());
1654
- };
1655
- const setModel = (modelName, model) => {
1656
- modelStore.set(modelName, model);
1657
- };
1658
-
1659
- var _a$2;
1660
- const logger$k = debug('app:property:class');
1661
- const namesThatEndWithId = [];
1662
- class ItemProperty {
1663
- // private constructor(localIdOrUid) {
1664
- // }
1665
- constructor({ propertyValue, seedUid, seedLocalId, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1593
+ const saveRelation = fromCallback(({ sendBack, input: { context, event } }) => {
1594
+ const { localId, propertyName: propertyNameRaw, versionLocalId, seedUid, seedLocalId, propertyValue: existingValue, propertyRecordSchema, } = context;
1595
+ if (!propertyRecordSchema) {
1596
+ throw new Error('Missing propertyRecordSchema');
1597
+ }
1598
+ let newValue;
1599
+ if (event) {
1600
+ newValue = event.newValue;
1601
+ }
1602
+ const _saveRelation = () => __awaiter(void 0, void 0, void 0, function* () {
1603
+ let propertyName = propertyNameRaw;
1604
+ if (!propertyName.endsWith('Id')) {
1605
+ propertyName = `${propertyName}Id`;
1606
+ }
1607
+ let newValueType;
1608
+ if (typeof newValue === 'string') {
1609
+ newValueType = getDataTypeFromString(newValue);
1610
+ }
1611
+ if (newValue instanceof File) {
1612
+ newValueType = 'file';
1613
+ }
1614
+ if (propertyRecordSchema.dataType === 'ImageSrc') {
1615
+ sendBack({
1616
+ type: 'saveImageSrc',
1617
+ newValue,
1618
+ newValueType,
1619
+ });
1620
+ return false;
1621
+ }
1622
+ return true;
1623
+ // let fileType
1624
+ //
1625
+ // const dirs = await fs.promises.readdir('/files')
1626
+ //
1627
+ // for (const dir of dirs) {
1628
+ // const files = await fs.promises.readdir(`/files/${dir}`)
1629
+ // if (newValue && files.includes(newValue as string)) {
1630
+ // fileType = dir
1631
+ // break
1632
+ // }
1633
+ // }
1634
+ //
1635
+ // if (newValue && fileType === 'images') {
1636
+ // const filePath = `/files/images/${newValue}`
1637
+ // refResolvedDisplayValue = await getContentUrlFromPath(filePath)
1638
+ // refSeedType = 'image'
1639
+ // newValue = await createSeed({
1640
+ // type: refSeedType,
1641
+ // })
1642
+ // await createVersion({
1643
+ // seedLocalId,
1644
+ // seedUid,
1645
+ // seedType: refSeedType,
1646
+ // })
1647
+ // }
1648
+ //
1649
+ // await updateItemPropertyValue({
1650
+ // propertyLocalId: localId,
1651
+ // propertyName,
1652
+ // newValue,
1653
+ // seedLocalId,
1654
+ // refSeedType,
1655
+ // refResolvedValue,
1656
+ // refResolvedDisplayValue,
1657
+ // versionLocalId,
1658
+ // modelName: itemModelName,
1659
+ // schemaUid,
1660
+ // })
1661
+ });
1662
+ _saveRelation().then((isDone) => {
1663
+ if (isDone) {
1664
+ sendBack({ type: 'saveRelationSuccess' });
1665
+ }
1666
+ });
1667
+ });
1668
+
1669
+ const getVersionData = () => {
1670
+ const appDb = getAppDb();
1671
+ return appDb.$with('versionData').as(appDb
1672
+ .select({
1673
+ seedLocalId: versions.seedLocalId,
1674
+ seedUid: versions.seedUid,
1675
+ latestVersionUid: versions.uid,
1676
+ latestVersionLocalId: versions.localId,
1677
+ versionsCount: count(versions.localId).as('versionsCount'),
1678
+ lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
1679
+ lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
1680
+ })
1681
+ .from(versions)
1682
+ .groupBy(versions.seedLocalId));
1683
+ };
1684
+
1685
+ const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
1686
+ const appDb = getAppDb();
1687
+ const conditions = [];
1688
+ if (modelName) {
1689
+ conditions.push(eq(seeds.type, modelName.toLowerCase()));
1690
+ }
1691
+ if (deleted) {
1692
+ conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
1693
+ }
1694
+ if (!deleted) {
1695
+ conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
1696
+ }
1697
+ const versionData = getVersionData();
1698
+ let query = appDb
1699
+ .with(versionData)
1700
+ .select({
1701
+ seedLocalId: seeds.localId,
1702
+ seedUid: seeds.uid,
1703
+ schemaUid: seeds.schemaUid,
1704
+ modelName: sql `${modelName}`,
1705
+ attestationCreatedAt: seeds.attestationCreatedAt,
1706
+ versionsCount: versionData.versionsCount,
1707
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
1708
+ lastLocalUpdateAt: versionData.lastLocalUpdateAt,
1709
+ createdAt: seeds.createdAt,
1710
+ })
1711
+ .from(seeds)
1712
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
1713
+ .where(and(...conditions))
1714
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
1715
+ .groupBy(seeds.localId);
1716
+ const itemsData = (yield query);
1717
+ return itemsData;
1718
+ });
1719
+
1720
+ var _a$2;
1721
+ const logger$k = debug('app:property:class');
1722
+ const namesThatEndWithId = [];
1723
+ class ItemProperty {
1724
+ // private constructor(localIdOrUid) {
1725
+ // }
1726
+ constructor({ propertyValue, seedUid, seedLocalId, versionLocalId, versionUid, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1666
1727
  this._isRelation = false;
1667
1728
  this._isList = false;
1668
1729
  this[_a$2] = true;
@@ -1673,12 +1734,13 @@ class ItemProperty {
1673
1734
  if (!propertyName) {
1674
1735
  throw new Error(`Property name not provided`);
1675
1736
  }
1676
- this._lastRenderedValue = propertyValue;
1677
1737
  const serviceInput = {
1678
1738
  propertyValue,
1679
- seedUid,
1680
1739
  propertyName,
1681
1740
  seedLocalId,
1741
+ seedUid,
1742
+ versionLocalId,
1743
+ versionUid,
1682
1744
  itemModelName,
1683
1745
  storageTransactionId,
1684
1746
  propertyRecordSchema: ModelClass.schema[propertyName],
@@ -1723,8 +1785,12 @@ class ItemProperty {
1723
1785
  this._service = createActor(propertyMachine, {
1724
1786
  input: serviceInput,
1725
1787
  });
1726
- this._subscription = this._service.subscribe((snapshot) => {
1788
+ this._subscription = this._service.subscribe((snapshot) => __awaiter(this, void 0, void 0, function* () {
1789
+ if (!snapshot || !snapshot.context) {
1790
+ return;
1791
+ }
1727
1792
  const { context } = snapshot;
1793
+ const { propertyRecordSchema } = context;
1728
1794
  // if (this.uid && !cacheHasProperty(this.uid)) {
1729
1795
  // addPropertyToCache(this)
1730
1796
  // }
@@ -1746,7 +1812,21 @@ class ItemProperty {
1746
1812
  // this._updateResponseListener,
1747
1813
  // )
1748
1814
  }
1749
- const renderValue = context.renderValue || context.propertyValue;
1815
+ let renderValue;
1816
+ if (propertyRecordSchema &&
1817
+ propertyRecordSchema.storageType &&
1818
+ propertyRecordSchema.storageType === 'ItemStorage' &&
1819
+ context.resolvedValue &&
1820
+ context.localStorageDir) {
1821
+ const filePath = `/files/${context.localStorageDir}/${context.resolvedValue}`;
1822
+ const exists = yield fs.promises.exists(filePath);
1823
+ if (exists) {
1824
+ renderValue = yield fs.promises.readFile(filePath, 'utf-8');
1825
+ }
1826
+ }
1827
+ if (!renderValue) {
1828
+ renderValue = context.renderValue || context.propertyValue;
1829
+ }
1750
1830
  let transformedPropertyName = propertyName;
1751
1831
  const skipTransform = internalPropertyNames.includes(propertyName) || !!this._alias;
1752
1832
  if (!skipTransform && transformedPropertyName.endsWith('Id')) {
@@ -1766,14 +1846,14 @@ class ItemProperty {
1766
1846
  if (context.seedUid) {
1767
1847
  eventEmitter.emit(`item.${itemModelName}.${context.seedUid}.update`);
1768
1848
  }
1769
- });
1849
+ }));
1770
1850
  this._service.start();
1771
1851
  }
1772
1852
  _updateResponseListener(event) {
1773
1853
  logger$k(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1774
1854
  }
1775
1855
  static create(props) {
1776
- const { propertyName, seedLocalId, seedUid } = props;
1856
+ const { propertyName, seedLocalId, seedUid, versionLocalId, versionUid } = props;
1777
1857
  if (!propertyName || (!seedLocalId && !seedUid)) {
1778
1858
  return;
1779
1859
  }
@@ -1842,32 +1922,35 @@ class ItemProperty {
1842
1922
  getService() {
1843
1923
  return this._service;
1844
1924
  }
1925
+ _getSnapshot() {
1926
+ return this._service.getSnapshot();
1927
+ }
1845
1928
  get localId() {
1846
- return this._service.getSnapshot().context.localId;
1929
+ return this._getSnapshot().context.localId;
1847
1930
  }
1848
1931
  get uid() {
1849
- return this._service.getSnapshot().context.uid;
1932
+ return this._getSnapshot().context.uid;
1850
1933
  }
1851
1934
  get seedLocalId() {
1852
- return this._service.getSnapshot().context.seedLocalId;
1935
+ return this._getSnapshot().context.seedLocalId;
1853
1936
  }
1854
1937
  get seedUid() {
1855
- return this._service.getSnapshot().context.seedUid;
1938
+ return this._getSnapshot().context.seedUid;
1856
1939
  }
1857
1940
  get propertyName() {
1858
1941
  if (this._alias) {
1859
1942
  return this._alias;
1860
1943
  }
1861
- return this._service.getSnapshot().context.propertyName;
1944
+ return this._getSnapshot().context.propertyName;
1862
1945
  }
1863
1946
  get itemModelName() {
1864
- return this._service.getSnapshot().context.itemModelName;
1947
+ return this._getSnapshot().context.itemModelName;
1865
1948
  }
1866
1949
  get propertyDef() {
1867
- return this._service.getSnapshot().context.propertyRecordSchema;
1950
+ return this._getSnapshot().context.propertyRecordSchema;
1868
1951
  }
1869
1952
  get status() {
1870
- return this._service.getSnapshot().value;
1953
+ return this._getSnapshot().value;
1871
1954
  }
1872
1955
  get alias() {
1873
1956
  return this._alias;
@@ -1892,7 +1975,7 @@ class ItemProperty {
1892
1975
  });
1893
1976
  }
1894
1977
  get published() {
1895
- return !!this._service.getSnapshot().context.uid;
1978
+ return !!this._getSnapshot().context.uid;
1896
1979
  }
1897
1980
  subscribe(callback) {
1898
1981
  return this._subject.subscribe(callback);
@@ -1921,84 +2004,6 @@ class ItemProperty {
1921
2004
  _a$2 = immerable;
1922
2005
  ItemProperty.instanceCache = new Map();
1923
2006
 
1924
- const TPropertyDataType = Type.Union([
1925
- Type.Literal('Text'),
1926
- Type.Literal('Number'),
1927
- Type.Literal('List'),
1928
- Type.Literal('Relation'),
1929
- Type.Literal('ImageSrc'),
1930
- Type.Literal('FileSrc'),
1931
- Type.Literal('Json'),
1932
- Type.Literal('Blob'),
1933
- ]);
1934
- const TStorageType = Type.Union([
1935
- Type.Literal('ItemStorage'), // Looks for a storageTransactionId property on the item
1936
- Type.Literal('PropertyStorage'), // Looks for a storageTransactionId value on the property
1937
- ]);
1938
- const TProperty = Type.Object({
1939
- id: Type.Optional(Type.Number()),
1940
- name: Type.Optional(Type.String()),
1941
- dataType: TPropertyDataType,
1942
- ref: Type.Optional(Type.String()),
1943
- modelId: Type.Optional(Type.Number()),
1944
- refModelId: Type.Optional(Type.Number()),
1945
- refValueType: Type.Optional(TPropertyDataType),
1946
- storageType: Type.Optional(TStorageType),
1947
- localStorageDir: Type.Optional(Type.String()),
1948
- filenameSuffix: Type.Optional(Type.String()),
1949
- });
1950
- const TPropertyConstructor = Type.Function([
1951
- Type.Optional(Type.Union([Type.String(), TStorageType])),
1952
- Type.Optional(Type.Union([Type.String(), TPropertyDataType])),
1953
- Type.Optional(Type.String()),
1954
- ], TProperty);
1955
- Type.Record(TPropertyDataType, TPropertyConstructor);
1956
- const Property = {
1957
- Text: (storageType, localStorageDir, filenameSuffix) => ({
1958
- dataType: 'Text',
1959
- storageType,
1960
- localStorageDir,
1961
- filenameSuffix,
1962
- TObject: Type.String(),
1963
- }),
1964
- Json: () => ({ dataType: 'Json' }),
1965
- Blob: () => ({ dataType: 'Blob' }),
1966
- Number: () => ({ dataType: 'Number' }),
1967
- List: (ref, refValueType) => ({
1968
- dataType: 'List',
1969
- ref,
1970
- refValueType,
1971
- }),
1972
- Relation: (ref, refValueType) => ({
1973
- dataType: 'Relation',
1974
- ref,
1975
- refValueType,
1976
- }),
1977
- ImageSrc: () => ({ dataType: 'ImageSrc' }),
1978
- };
1979
- const PropertyMetadataKey = Symbol('property');
1980
- const PropertyConstructor = (propertyType) => {
1981
- return function (parentClassPrototype, propertyKey) {
1982
- const existingProperties = Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype) || [];
1983
- existingProperties.push({ propertyKey, propertyType });
1984
- // console.log('existingProperties', existingProperties)
1985
- // console.log('propertyKey', propertyKey)
1986
- // console.log('propertyType', propertyType)
1987
- // console.log('PropertyMetadataKey', PropertyMetadataKey)
1988
- // console.log('typeof target', typeof target)
1989
- Reflect.defineMetadata(PropertyMetadataKey, existingProperties, parentClassPrototype);
1990
- // console.log(
1991
- // `After adding ${propertyKey}:`,
1992
- // Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype),
1993
- // )
1994
- };
1995
- };
1996
- const Text = (storageType, srcDir, filenameSuffix) => PropertyConstructor(Property.Text(storageType, srcDir, filenameSuffix));
1997
- const Json = () => PropertyConstructor(Property.Json());
1998
- const ImageSrc = () => PropertyConstructor(Property.ImageSrc());
1999
- const Relation = (ref, refValueType) => PropertyConstructor(Property.Relation(ref, refValueType)); // Adjust for actual relation type
2000
- const List = (ref, reValueType) => PropertyConstructor(Property.List(ref, reValueType)); // Adjust for actual list type
2001
-
2002
2007
  const waitForDb = fromCallback(({ sendBack }) => {
2003
2008
  const _waitForDb = new Promise((resolve) => {
2004
2009
  const interval = setInterval(() => {
@@ -2553,7 +2558,7 @@ const createMetadataRecordsForStorageTransactionId = (storageTransactionIdProper
2553
2558
  versionLocalId,
2554
2559
  versionUid,
2555
2560
  refValueType: 'file',
2556
- refResolvedValue: `${propertyValue}.${propertyDef.filenameSuffix}`,
2561
+ refResolvedValue: `${propertyValue}${propertyDef.filenameSuffix}`,
2557
2562
  modelType: seedUidToModelType.get(seedUid),
2558
2563
  createdAt: Date.now(),
2559
2564
  updatedAt: Date.now(),
@@ -2894,7 +2899,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2894
2899
  if (!models$1) {
2895
2900
  return;
2896
2901
  }
2897
- const { models: SeedModels } = yield import('./seed.schema.config-BtfzZOfM.js');
2902
+ const { models: SeedModels } = yield import('./seed.schema.config-BHZSMMmL.js');
2898
2903
  const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
2899
2904
  let hasModelsInDb = false;
2900
2905
  const schemaDefsByModelName = new Map();
@@ -3866,39 +3871,6 @@ const getArweave = () => {
3866
3871
  });
3867
3872
  };
3868
3873
 
3869
- const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
3870
- const appDb = getAppDb();
3871
- const conditions = [];
3872
- if (modelName) {
3873
- conditions.push(eq(seeds.type, modelName.toLowerCase()));
3874
- }
3875
- if (deleted) {
3876
- conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
3877
- }
3878
- if (!deleted) {
3879
- conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
3880
- }
3881
- let query = appDb
3882
- .select({
3883
- seedLocalId: seeds.localId,
3884
- seedUid: seeds.uid,
3885
- schemaUid: seeds.schemaUid,
3886
- modelName: sql `${modelName}`,
3887
- attestationCreatedAt: seeds.attestationCreatedAt,
3888
- versionsCount: count(versions.localId),
3889
- lastVersionPublishedAt: max(versions.attestationCreatedAt),
3890
- lastLocalUpdateAt: max(versions.createdAt),
3891
- createdAt: seeds.createdAt,
3892
- })
3893
- .from(seeds)
3894
- .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
3895
- .where(and(...conditions))
3896
- .orderBy(desc(seeds.createdAt))
3897
- .groupBy(seeds.localId);
3898
- const itemsData = (yield query);
3899
- return itemsData;
3900
- });
3901
-
3902
3874
  const getMetadata = (props) => __awaiter(void 0, void 0, void 0, function* () {
3903
3875
  const appDb = getAppDb();
3904
3876
  let storageTransactionId;
@@ -4067,7 +4039,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
4067
4039
  if (contentType !== 'json' &&
4068
4040
  contentType !== 'base64' &&
4069
4041
  contentType !== 'html') {
4070
- const possibleImageType = getImageDataType(dataString);
4042
+ const possibleImageType = getDataTypeFromString(dataString);
4071
4043
  if (!possibleImageType) {
4072
4044
  logger$b(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
4073
4045
  continue;
@@ -5085,665 +5057,112 @@ const createPublishAttempt = fromCallback(({ sendBack, input: { context } }) =>
5085
5057
  });
5086
5058
  });
5087
5059
 
5088
- const logger$5 = debug('app:react:services');
5089
- const finalStrings = ['idle', 'ready', 'done', 'success'];
5090
- const getServiceName = (service) => {
5091
- let name = 'actor';
5092
- if (service && service.uniqueKey) {
5093
- name = service.uniqueKey;
5094
- }
5095
- if (service && !service.uniqueKey && service.logic && service.logic.config) {
5096
- name = getServiceUniqueKey(service);
5097
- }
5098
- return name;
5099
- };
5100
- const getServiceValue = (service) => {
5101
- let value;
5102
- if (service && service.getSnapshot() && service.getSnapshot().value) {
5103
- value = service.getSnapshot().value;
5104
- }
5105
- if (getServiceName(service) === 'global') {
5106
- if (value &&
5107
- typeof value === 'object' &&
5108
- Object.keys(value).length > 0 &&
5109
- Object.keys(value)[0] === 'initialized') {
5110
- value = 'ready';
5111
- }
5112
- }
5113
- if (value && typeof value === 'object') {
5114
- value = JSON.stringify(value);
5115
- }
5116
- return value;
5117
- };
5118
- const getServiceUniqueKey = (service) => {
5119
- if (!service || !service.logic || !service.logic.config) {
5120
- return;
5121
- }
5122
- const config = service.logic.config;
5123
- if (!config.id) {
5124
- return;
5125
- }
5126
- let uniqueKey = config.id;
5127
- if (config.id.includes('@seedSdk/')) {
5128
- uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
5129
- }
5130
- let snapshot;
5131
- try {
5132
- snapshot = service.getSnapshot();
5133
- }
5134
- catch (error) {
5135
- logger$5('Error:', error);
5136
- return uniqueKey;
5137
- }
5138
- if (snapshot) {
5139
- const context = snapshot.context;
5140
- if (context && context.dbName) {
5141
- uniqueKey = context.dbName;
5142
- }
5143
- if (context && context.modelNamePlural) {
5144
- uniqueKey = context.modelNamePlural;
5145
- }
5146
- if (context && context.modelName) {
5147
- uniqueKey = pluralize(context.modelName.toLowerCase());
5060
+ const preparePublishRequestData = fromCallback(({ sendBack, input: { context } }) => {
5061
+ const { localId } = context;
5062
+ const _preparePublishRequestData = () => __awaiter(void 0, void 0, void 0, function* () {
5063
+ const item = yield Item.find({ seedLocalId: localId });
5064
+ if (!item) {
5065
+ return false;
5148
5066
  }
5149
- }
5150
- return uniqueKey;
5151
- };
5152
- const useIsDbReady = () => {
5153
- const [isDbReady, setIsDbReady] = useState(false);
5154
- const { internalStatus } = useGlobalServiceStatus();
5155
- useEffect(() => {
5156
- if (internalStatus === 'ready') {
5157
- setIsDbReady(true);
5067
+ const appDb = getAppDb();
5068
+ const modelsRows = yield appDb
5069
+ .select({
5070
+ modelName: models.name,
5071
+ schemaUid: modelUids.uid,
5072
+ })
5073
+ .from(models)
5074
+ .leftJoin(modelUids, eq(modelUids.modelId, models.id))
5075
+ .where(eq(models.name, 'Version'));
5076
+ if (!modelsRows || modelsRows.length === 0) {
5077
+ sendBack({ type: 'preparePublishRequestDataError' });
5078
+ return false;
5158
5079
  }
5159
- }, [internalStatus]);
5160
- return isDbReady;
5161
- };
5162
- const useServices = () => {
5163
- const [actors, setActors] = useState([]);
5164
- const [percentComplete, setPercentComplete] = useState(5);
5165
- const actorsMap = new Map();
5166
- useEffect(() => {
5167
- const globalServiceListener = (event) => {
5168
- if (event && event.type === 'init') {
5169
- return;
5170
- }
5171
- if (event.actorRef &&
5172
- event.actorRef.logic &&
5173
- event.actorRef.logic.config) {
5174
- const service = event.actorRef;
5175
- const services = [service];
5176
- if (service.logic.config.id === MachineIds.GLOBAL) {
5177
- const context = service.getSnapshot().context;
5178
- const keys = Object.keys(context);
5179
- for (const key of keys) {
5180
- if (!key.startsWith('internal') && key.endsWith('Service')) {
5181
- const allItemsService = context[key];
5182
- services.push(allItemsService);
5183
- }
5184
- }
5185
- }
5186
- services.forEach((innerService) => {
5187
- const uniqueKey = getServiceUniqueKey(innerService);
5188
- if (!uniqueKey) {
5189
- return;
5190
- }
5191
- innerService.uniqueKey = uniqueKey;
5192
- actorsMap.set(uniqueKey, innerService);
5193
- });
5194
- let actorsArray = Array.from(actorsMap.values());
5195
- actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
5196
- setActors(produce(actors, (draft) => {
5197
- return actorsArray;
5198
- }));
5199
- }
5200
- };
5201
- eventEmitter.addListener('inspect.globalService', globalServiceListener);
5202
- return () => {
5203
- eventEmitter.removeListener('inspect.globalService', globalServiceListener);
5080
+ const versionSchemaUid = modelsRows[0].schemaUid;
5081
+ yield item.getEditedProperties();
5082
+ yield getModelSchemas();
5083
+ // const dataEncoder = new SchemaEncoder(modelProperty.schemaDefinition,)
5084
+ // const encodedData = dataEncoder.encodeData(data,)
5085
+ //
5086
+ // itemData.listOfAttestations.push({
5087
+ // schema : modelProperty.schemaUid,
5088
+ // data : [
5089
+ // {
5090
+ // ...defaultAttestationData,
5091
+ // data : encodedData,
5092
+ // },
5093
+ // ],
5094
+ // },)
5095
+ const publishRequestData = {
5096
+ seedIsRevocable: false,
5097
+ seedSchemaUid: item.schemaUid,
5098
+ seedUid: item.seedUid,
5099
+ versionSchemaUid,
5100
+ versionUid: item.latestVersionUid,
5101
+ listOfAttestations: [],
5204
5102
  };
5205
- }, []);
5206
- useEffect(() => {
5207
- const globalService = actors.find((actor) => getServiceName(actor) === 'global');
5208
- const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
5209
- if (!globalService || !internalService) {
5210
- return;
5211
- }
5212
- if (getServiceValue(globalService) === 'ready' &&
5213
- getServiceValue(internalService) === 'ready') {
5214
- const denominator = actors.length;
5215
- const finishedActors = actors.filter((actor) => {
5216
- const value = getServiceValue(actor);
5217
- return finalStrings.includes(value);
5218
- });
5219
- const numerator = finishedActors.length;
5220
- const percentComplete = (numerator / denominator) * 100;
5221
- setPercentComplete(percentComplete);
5222
- }
5223
- }, [actors]);
5224
- return {
5225
- services: actors,
5226
- percentComplete,
5227
- };
5228
- };
5229
- const useGlobalServiceStatus = () => {
5230
- const globalService = getGlobalService();
5231
- const status = useSelector(globalService, (snapshot) => {
5232
- return snapshot.value;
5103
+ sendBack(Object.assign({ type: 'updateContext' }, publishRequestData));
5104
+ return true;
5233
5105
  });
5234
- const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
5235
- if (!snapshot) {
5236
- return;
5106
+ _preparePublishRequestData().then((success) => {
5107
+ if (success) {
5108
+ sendBack({ type: 'preparePublishRequestDataSuccess' });
5237
5109
  }
5238
- return snapshot.value;
5239
- });
5240
- useSelector(globalService, (snapshot) => {
5241
- return snapshot.context.internalService;
5242
5110
  });
5243
- return {
5244
- status,
5245
- internalStatus,
5246
- };
5247
- };
5111
+ });
5248
5112
 
5249
- const logger$4 = debug('app:react:item');
5250
- const useItem = ({ modelName, seedLocalId, seedUid }) => {
5251
- const [itemData, setItemData] = useImmer({});
5252
- const [item, setItem] = useState();
5253
- const [itemSubscription, setItemSubscription] = useState();
5254
- const { status, internalStatus } = useGlobalServiceStatus();
5255
- const isReadingDb = useRef(false);
5256
- const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5257
- const updateItem = useCallback((newItem) => {
5258
- setItemData((draft) => {
5259
- Object.keys(newItem.properties).forEach((propertyName) => {
5260
- const value = newItem[propertyName];
5261
- draft[propertyName] = value;
5262
- });
5263
- });
5264
- }, []);
5265
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5266
- if (isReadingDb.current ||
5267
- internalStatus !== 'ready' ||
5268
- (!seedUid && !seedLocalId)) {
5269
- return;
5113
+ const logger$5 = debug('app:services:publish:actors:upload');
5114
+ const upload = fromCallback(({ sendBack, input: { context } }) => {
5115
+ const { localId } = context;
5116
+ const _upload = () => __awaiter(void 0, void 0, void 0, function* () {
5117
+ const item = yield Item.find({ seedLocalId: localId });
5118
+ if (!item) {
5119
+ logger$5('no item with localId', localId);
5120
+ return false;
5270
5121
  }
5271
- isReadingDb.current = true;
5272
- const foundItem = yield Item.find({
5273
- modelName,
5274
- seedLocalId,
5275
- seedUid,
5276
- });
5277
- if (!foundItem) {
5278
- logger$4('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
5279
- return;
5122
+ const editedProperties = yield item.getEditedProperties();
5123
+ for (const propertyData of editedProperties) {
5124
+ if (propertyData.refSeedType === 'image') ;
5280
5125
  }
5281
- setItem(foundItem);
5282
- updateItem(foundItem);
5283
- isReadingDb.current = false;
5284
- }), [internalStatus]);
5285
- const listenerRef = useRef(readFromDb);
5286
- useEffect(() => {
5287
- listenerRef.current = readFromDb;
5288
- }, [readFromDb]);
5289
- useEffect(() => {
5290
- if (internalStatus === 'ready') {
5291
- listenerRef.current();
5126
+ const uploadItems = [];
5127
+ for (const editedPropertyData of editedProperties) {
5128
+ const propertyName = editedPropertyData.propertyName;
5129
+ const editedProperty = item.properties[propertyName];
5130
+ if (!editedProperty || !editedProperty.propertyDef) {
5131
+ continue;
5132
+ }
5133
+ if (editedProperty.propertyDef.refValueType &&
5134
+ editedProperty.propertyDef.refValueType === 'ImageSrc') {
5135
+ const context = editedProperty.getService().getSnapshot().context;
5136
+ const imageSeedId = context.propertyValue;
5137
+ getCorrectId(imageSeedId);
5138
+ }
5139
+ if (editedProperty.propertyDef.storageType === 'ItemStorage' &&
5140
+ editedProperty.propertyDef.localStorageDir) ;
5292
5141
  }
5293
- }, [internalStatus, status]);
5294
- useEffect(() => {
5295
- if (item && !itemSubscription) {
5296
- const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
5297
- const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
5298
- if (!newItem) {
5299
- logger$4('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
5300
- return;
5301
- }
5302
- updateItem(newItem);
5303
- setItem(newItem);
5304
- }));
5305
- setItemSubscription(subscription);
5142
+ if (uploadItems.length === 0) {
5143
+ return true;
5306
5144
  }
5307
- return () => {
5308
- itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
5309
- };
5310
- }, [item, itemSubscription]);
5311
- useEffect(() => {
5312
- const seedId = seedUid || seedLocalId;
5313
- eventEmitter.addListener(`item.${modelName}.${seedId}.update`, () => {
5314
- listenerRef.current();
5315
- });
5316
- return () => {
5317
- eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
5318
- };
5319
- }, []);
5320
- return {
5321
- item,
5322
- itemData,
5323
- itemStatus,
5324
- };
5325
- };
5326
- const useItems = ({ modelName, deleted }) => {
5327
- const [items, setItems] = useImmer([]);
5328
- const [isReadingDb, setIsReadingDb] = useState(false);
5329
- const [isInitialized, setIsInitialized] = useState(false);
5330
- const isDbReady = useIsDbReady();
5331
- const modelNameRef = useRef(modelName);
5332
- const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
5333
- if (!event ||
5334
- !event.modelName ||
5335
- event.modelName !== modelNameRef.current ||
5336
- isReadingDb) {
5337
- return;
5145
+ // const turbo = TurboFactory.unauthenticated()
5146
+ // turbo.uploadSignedDataItem()
5147
+ //
5148
+ // const { id, owner, dataCaches, fastFinalityIndexes } = await turbo.uploadFile(() => {
5149
+ // fileStreamFactory => () => fs.createReadStream(filePath),
5150
+ // fileSizeFactory => () => fileSize,
5151
+ // });
5152
+ return false;
5153
+ });
5154
+ _upload().then((isValid) => {
5155
+ if (isValid) {
5156
+ sendBack({ type: 'uploadSuccess' });
5338
5157
  }
5339
- setIsReadingDb(true);
5340
- const allItems = yield Item.all(modelNameRef.current, deleted);
5341
- setItems(() => allItems);
5342
- setIsReadingDb(false);
5343
- }), [modelName, isReadingDb]);
5344
- useEffect(() => {
5345
- if (isDbReady && !isInitialized) {
5346
- const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
5347
- yield readFromDb({ modelName });
5348
- setIsInitialized(true);
5349
- });
5350
- _fetchItems();
5351
- }
5352
- }, [isInitialized, isDbReady]);
5353
- useEffect(() => {
5354
- eventEmitter.addListener('item.requestAll', readFromDb);
5355
- return () => {
5356
- eventEmitter.removeListener('item.requestAll');
5357
- };
5358
- }, []);
5359
- return {
5360
- items: orderBy(items, [
5361
- (item) => item.lastVersionPublishedAt ||
5362
- item.attestationCreatedAt ||
5363
- item.createdAt,
5364
- ], ['desc']).slice(0, 10),
5365
- isReadingDb,
5366
- isInitialized,
5367
- };
5368
- };
5369
- const useItemIsReady = () => {
5370
- const [itemListenersReady, setItemListenersReady] = useState(false);
5371
- const itemEventListenersHandler = useCallback((_) => {
5372
- setItemListenersReady(true);
5373
- }, []);
5374
- useEffect(() => {
5375
- const areReady = getAreItemEventHandlersReady();
5376
- if (areReady) {
5377
- itemEventListenersHandler(true);
5378
- }
5379
- eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
5380
- return () => {
5381
- eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
5382
- };
5383
- }, []);
5384
- return {
5385
- isReady: itemListenersReady,
5386
- };
5387
- };
5388
- const useCreateItem = (modelName) => {
5389
- const [isCreatingItem, setIsCreatingItem] = useState(false);
5390
- const { isReady } = useItemIsReady();
5391
- const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
5392
- if (!isReady) {
5393
- console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
5394
- return;
5395
- }
5396
- if (isCreatingItem) {
5397
- // TODO: should we setup a queue for this?
5398
- console.error(`[useCreateItem] [createItem] already creating item`, itemData);
5399
- return;
5400
- }
5401
- setIsCreatingItem(true);
5402
- const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
5403
- yield Item.find({ modelName, seedLocalId });
5404
- eventEmitter.emit('item.requestAll', { modelName });
5405
- setIsCreatingItem(false);
5406
- }), [isCreatingItem, isReady]);
5407
- return {
5408
- createItem,
5409
- isCreatingItem,
5410
- };
5411
- };
5412
-
5413
- const logger$3 = debug('app:react:property');
5414
- const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
5415
- const [property, setProperty] = useState();
5416
- const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5417
- const [isInitialized, setIsInitialized] = useState(false);
5418
- // const isDbReady = useMemo(() => useIsDbReady(), [])
5419
- const { internalStatus } = useGlobalServiceStatus();
5420
- const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
5421
- if (!snapshot || !snapshot.context) {
5422
- return;
5423
- }
5424
- return snapshot.context.renderValue || snapshot.context.propertyValue;
5425
5158
  });
5426
- const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5427
- // useEffect(() => {
5428
- // if (property && property.value !== value) {
5429
- // readFromDb()
5430
- // }
5431
- // }, [property, value])
5432
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5433
- if (internalStatus !== 'ready' ||
5434
- isReadingFromDb ||
5435
- (!seedLocalId && !seedUid)) {
5436
- return;
5437
- }
5438
- setIsReadingFromDb(true);
5439
- const foundProperty = yield ItemProperty.find({
5440
- propertyName,
5441
- seedLocalId,
5442
- seedUid,
5443
- });
5444
- setIsReadingFromDb(false);
5445
- if (!foundProperty) {
5446
- logger$3(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
5447
- return;
5448
- }
5449
- if (foundProperty.status === 'waitingForDb') {
5450
- foundProperty.getService().send({ type: 'waitForDbSuccess' });
5451
- }
5452
- setProperty(foundProperty);
5453
- setIsInitialized(true);
5454
- }), [internalStatus, isReadingFromDb]);
5455
- // let count = 0
5456
- //
5457
- // const refresh = useCallback(() => {
5458
- // count++
5459
- // console.log('[useItemPropertyTest] [refresh] property', property)
5460
- // }, [property])
5461
- useEffect(() => {
5462
- if (internalStatus === 'ready') {
5463
- readFromDb();
5464
- }
5465
- }, [internalStatus]);
5466
- // useEffect(() => {
5467
- // eventEmitter.addListener(
5468
- // `property.${seedUid || seedLocalId}.${propertyName}.update`,
5469
- // (event) => {
5470
- // refresh()
5471
- // },
5472
- // )
5473
- //
5474
- // return () => {
5475
- // eventEmitter.removeListener(
5476
- // `property.${seedUid || seedLocalId}.${propertyName}.update`,
5477
- // )
5478
- // }
5479
- // }, [])
5480
- return {
5481
- property,
5482
- isInitialized,
5483
- isReadingFromDb,
5484
- value,
5485
- status,
5486
- };
5487
- };
5488
- const useItemProperties = (item) => {
5489
- const [propertyObj, setPropertyObj] = useImmer({});
5490
- useState(false);
5491
- const updatePropertyObj = useCallback((event) => {
5492
- if (!item) {
5493
- console.error('[XXXXXX] [updatePropertyObj] no item when expected');
5494
- return;
5495
- }
5496
- const { propertyName, propertyValue } = event;
5497
- if (!propertyName) {
5498
- return;
5499
- }
5500
- setPropertyObj((draft) => {
5501
- draft[propertyName] = propertyValue;
5502
- });
5503
- }, [item]);
5504
- useEffect(() => {
5505
- if (!item) {
5506
- return;
5507
- }
5508
- const eventKey = `item.${item.seedLocalId}.property.update`;
5509
- eventEmitter.addListener(eventKey, updatePropertyObj);
5510
- return () => {
5511
- eventEmitter.removeListener(eventKey, updatePropertyObj);
5512
- };
5513
- }, [item]);
5514
- return {
5515
- properties: propertyObj,
5516
- };
5517
- };
5518
-
5519
- debug('app:react:db');
5520
-
5521
- const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
5522
- const appDb = getAppDb();
5523
- yield appDb
5524
- .update(seeds)
5525
- .set({
5526
- _markedForDeletion: 1,
5527
- })
5528
- .where(or(eq(seeds.localId, seedLocalId), eq(seeds.uid, seedUid)));
5529
- });
5530
-
5531
- const useDeleteItem = () => {
5532
- const [isDeletingItem, setIsDeletingItem] = useState(false);
5533
- const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
5534
- if (!item) {
5535
- return;
5536
- }
5537
- setIsDeletingItem(true);
5538
- const { modelName } = item.getService().getSnapshot().context;
5539
- yield deleteItem({ seedLocalId: item.seedLocalId });
5540
- eventEmitter.emit('item.requestAll', { modelName });
5541
- setIsDeletingItem(false);
5542
- }), [isDeletingItem]);
5543
- useEffect(() => { }, []);
5544
- return {
5545
- deleteItem: destroy,
5546
- isDeletingItem,
5547
- };
5548
- };
5549
-
5550
- const logger$2 = debug('app:services:events');
5551
- const handleServiceSaveState = (event) => {
5552
- const { state, serviceId } = event;
5553
- logger$2(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
5554
- localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state));
5555
- };
5556
- const setupServicesEventHandlers = () => {
5557
- eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
5558
- };
5559
-
5560
- const saveServiceHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
5561
- const globalService = getGlobalService();
5562
- if (!globalService || !globalService.getSnapshot().context) {
5563
- return;
5564
- }
5565
- const { modelName } = event;
5566
- const nameOfService = `${modelName}Service`;
5567
- const service = globalService.getSnapshot().context[nameOfService];
5568
- yield writeAppState(`snapshot__${modelName}`, JSON.stringify(service.getPersistedSnapshot()));
5569
5159
  });
5570
5160
 
5571
- const setupServiceHandlers = () => {
5572
- eventEmitter.addListener('service.save', saveServiceHandler);
5573
- };
5574
-
5575
- const client = {
5576
- init: ({ config, addresses }) => {
5577
- const { endpoints, models } = config;
5578
- for (const [key, value] of Object.entries(models)) {
5579
- setModel(key, value);
5580
- }
5581
- setupFsListeners();
5582
- setupAllItemsEventHandlers();
5583
- setupServicesEventHandlers();
5584
- setupServiceHandlers();
5585
- if (areFsListenersReady()) {
5586
- eventEmitter.emit('fs.init');
5587
- }
5588
- if (!areFsListenersReady()) {
5589
- console.error('fs listeners not ready during init');
5590
- }
5591
- globalService.send({ type: 'init', endpoints, models, addresses });
5592
- import('./seed.schema.config-BtfzZOfM.js').then(({ models }) => {
5593
- for (const [key, value] of Object.entries(models)) {
5594
- setModel(key, value);
5595
- }
5596
- });
5597
- },
5598
- subscribe: (callback) => {
5599
- callback({
5600
- type: '@xstate.snapshot',
5601
- actorRef: globalService,
5602
- snapshot: globalService.getSnapshot(),
5603
- });
5604
- eventEmitter.addListener('globalService', callback);
5605
- return {
5606
- unsubscribe: () => {
5607
- eventEmitter.removeListener('globalService', callback);
5608
- },
5609
- };
5610
- },
5611
- on: (outerEvent, callback) => {
5612
- eventEmitter.addListener(outerEvent, callback);
5613
- return {
5614
- unsubscribe: () => {
5615
- eventEmitter.removeListener(outerEvent, callback);
5616
- },
5617
- };
5618
- },
5619
- getSeedClass: () => __awaiter(void 0, void 0, void 0, function* () {
5620
- return new Promise((resolve) => {
5621
- const subscription = globalService.subscribe((snapshot) => {
5622
- if (snapshot.status === 'done') {
5623
- resolve(snapshot.output);
5624
- }
5625
- });
5626
- globalService.send({ type: 'getSeed' });
5627
- subscription.unsubscribe();
5628
- });
5629
- }),
5630
- getModel: (modelName) => {
5631
- return getModel(modelName);
5632
- },
5633
- getModels: () => {
5634
- return getModels();
5635
- },
5636
- getModelNames: () => {
5637
- return getModelNames();
5638
- },
5639
- };
5640
-
5641
- const preparePublishRequestData = fromCallback(({ sendBack, input: { context } }) => {
5642
- const { localId } = context;
5643
- const _preparePublishRequestData = () => __awaiter(void 0, void 0, void 0, function* () {
5644
- const item = yield Item.find({ seedLocalId: localId });
5645
- if (!item) {
5646
- return false;
5647
- }
5648
- const appDb = getAppDb();
5649
- const modelsRows = yield appDb
5650
- .select({
5651
- modelName: models.name,
5652
- schemaUid: modelUids.uid,
5653
- })
5654
- .from(models)
5655
- .leftJoin(modelUids, eq(modelUids.modelId, models.id))
5656
- .where(eq(models.name, 'Version'));
5657
- if (!modelsRows || modelsRows.length === 0) {
5658
- sendBack({ type: 'preparePublishRequestDataError' });
5659
- return false;
5660
- }
5661
- const versionSchemaUid = modelsRows[0].schemaUid;
5662
- yield item.getEditedProperties();
5663
- yield getModelSchemas();
5664
- // const dataEncoder = new SchemaEncoder(modelProperty.schemaDefinition,)
5665
- // const encodedData = dataEncoder.encodeData(data,)
5666
- //
5667
- // itemData.listOfAttestations.push({
5668
- // schema : modelProperty.schemaUid,
5669
- // data : [
5670
- // {
5671
- // ...defaultAttestationData,
5672
- // data : encodedData,
5673
- // },
5674
- // ],
5675
- // },)
5676
- const publishRequestData = {
5677
- seedIsRevocable: false,
5678
- seedSchemaUid: item.schemaUid,
5679
- seedUid: item.seedUid,
5680
- versionSchemaUid,
5681
- versionUid: item.latestVersionUid,
5682
- listOfAttestations: [],
5683
- };
5684
- sendBack(Object.assign({ type: 'updateContext' }, publishRequestData));
5685
- return true;
5686
- });
5687
- _preparePublishRequestData().then((success) => {
5688
- if (success) {
5689
- sendBack({ type: 'preparePublishRequestDataSuccess' });
5690
- }
5691
- });
5692
- });
5693
-
5694
- const logger$1 = debug('app:services:publish:actors:upload');
5695
- const upload = fromCallback(({ sendBack, input: { context } }) => {
5696
- const { localId } = context;
5697
- const _upload = () => __awaiter(void 0, void 0, void 0, function* () {
5698
- const item = yield Item.find({ seedLocalId: localId });
5699
- if (!item) {
5700
- logger$1('no item with localId', localId);
5701
- return false;
5702
- }
5703
- const editedProperties = yield item.getEditedProperties();
5704
- for (const propertyData of editedProperties) {
5705
- if (propertyData.refSeedType === 'image') ;
5706
- }
5707
- const uploadItems = [];
5708
- for (const editedPropertyData of editedProperties) {
5709
- const propertyName = editedPropertyData.propertyName;
5710
- const editedProperty = item.properties[propertyName];
5711
- if (!editedProperty || !editedProperty.propertyDef) {
5712
- continue;
5713
- }
5714
- if (editedProperty.propertyDef.refValueType &&
5715
- editedProperty.propertyDef.refValueType === 'ImageSrc') {
5716
- const context = editedProperty.getService().getSnapshot().context;
5717
- const imageSeedId = context.propertyValue;
5718
- getCorrectId(imageSeedId);
5719
- }
5720
- if (editedProperty.propertyDef.storageType === 'ItemStorage' &&
5721
- editedProperty.propertyDef.localStorageDir) ;
5722
- }
5723
- if (uploadItems.length === 0) {
5724
- return true;
5725
- }
5726
- // const turbo = TurboFactory.unauthenticated()
5727
- // turbo.uploadSignedDataItem()
5728
- //
5729
- // const { id, owner, dataCaches, fastFinalityIndexes } = await turbo.uploadFile(() => {
5730
- // fileStreamFactory => () => fs.createReadStream(filePath),
5731
- // fileSizeFactory => () => fileSize,
5732
- // });
5733
- return false;
5734
- });
5735
- _upload().then((isValid) => {
5736
- if (isValid) {
5737
- sendBack({ type: 'uploadSuccess' });
5738
- }
5739
- });
5740
- });
5741
-
5742
- const { VALIDATING_ITEM_DATA, CREATING_PUBLISH_ATTEMPT, PREPARING_PUBLISH_REQUEST_DATA, UPLOADING, PUBLISHING, IDLE, } = PublishMachineStates;
5743
- const publishMachine = setup({
5744
- types: {
5745
- context: {},
5746
- input: {},
5161
+ const { VALIDATING_ITEM_DATA, CREATING_PUBLISH_ATTEMPT, PREPARING_PUBLISH_REQUEST_DATA, UPLOADING, PUBLISHING, IDLE, } = PublishMachineStates;
5162
+ const publishMachine = setup({
5163
+ types: {
5164
+ context: {},
5165
+ input: {},
5747
5166
  },
5748
5167
  actors: {
5749
5168
  validateItemData,
@@ -6562,7 +5981,7 @@ const getItemProperties = (_a) => __awaiter(void 0, [_a], void 0, function* ({ s
6562
5981
  // })
6563
5982
  // }
6564
5983
 
6565
- const logger = debug('app:db:queries:getItem');
5984
+ const logger$4 = debug('app:db:queries:getItem');
6566
5985
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
6567
5986
  if (!seedLocalId && !seedUid) {
6568
5987
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -6570,7 +5989,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6570
5989
  if (seedUid && !seedLocalId) {
6571
5990
  const seedData = yield getSeedData({ seedUid });
6572
5991
  if (!seedData) {
6573
- logger('[db/queries] [getItem] no seedData seedUid', seedUid);
5992
+ logger$4('[db/queries] [getItem] no seedData seedUid', seedUid);
6574
5993
  return;
6575
5994
  }
6576
5995
  seedLocalId = seedData.localId;
@@ -6587,32 +6006,17 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
6587
6006
  if (seedLocalId && !seedUid) {
6588
6007
  whereClauses.push(eq(seeds.localId, seedLocalId));
6589
6008
  }
6590
- // const uidWhereClause: SQL = seedUid
6591
- // ? eq(seeds.uid, seedUid)
6592
- // : isNull(seeds.uid)
6593
- // const localWhereClause: SQL = seedLocalId
6594
- // ? eq(seeds.localId, seedLocalId)
6595
- // : isNull(seeds.localId)
6596
- // whereClauses.push(or(localWhereClause, uidWhereClause) as SQL)
6597
- const latestVersions = appDb.$with('latestVersions').as(appDb
6598
- .select({
6599
- localId: versions.localId,
6600
- uid: versions.uid,
6601
- seedLocalId: versions.seedLocalId,
6602
- seedUid: versions.seedUid,
6603
- })
6604
- .from(versions)
6605
- .groupBy(versions.seedLocalId));
6009
+ const versionData = getVersionData();
6606
6010
  const itemDataRows = yield appDb
6607
- .with(latestVersions)
6608
- .select(Object.assign(Object.assign({}, rest), { seedLocalId: seeds.localId, seedUid: seeds.uid, versionsCount: count(versions.localId), lastVersionPublishedAt: max(versions.attestationCreatedAt), latestVersionUid: latestVersions.uid }))
6011
+ .with(versionData)
6012
+ .select(Object.assign(Object.assign({}, rest), { seedLocalId: seeds.localId, seedUid: seeds.uid, versionsCount: versionData.versionsCount, lastVersionPublishedAt: versionData.lastVersionPublishedAt, latestVersionUid: versionData.latestVersionUid, latestVersionLocalId: versionData.latestVersionLocalId }))
6609
6013
  .from(seeds)
6610
- .leftJoin(versions, eq(versions.seedLocalId, seeds.localId))
6611
- .leftJoin(latestVersions, eq(versions.seedLocalId, latestVersions.seedLocalId))
6612
- .where(and(...whereClauses))
6014
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
6015
+ .where(and(...whereClauses, gt(versionData.versionsCount, 0)))
6016
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
6613
6017
  .groupBy(seeds.localId);
6614
6018
  if (!itemDataRows || itemDataRows.length === 0) {
6615
- logger('[db/queries] [getItemDataFromDb] no itemDataRows');
6019
+ logger$4('[db/queries] [getItemDataFromDb] no itemDataRows');
6616
6020
  return;
6617
6021
  }
6618
6022
  let itemData = itemDataRows[0];
@@ -6686,7 +6090,7 @@ class Item {
6686
6090
  },
6687
6091
  });
6688
6092
  });
6689
- const { modelName, seedUid, schemaUid, seedLocalId } = initialValues;
6093
+ const { modelName, seedUid, schemaUid, seedLocalId, latestVersionLocalId, latestVersionUid, } = initialValues;
6690
6094
  const ModelClass = getModel(modelName);
6691
6095
  if (ModelClass &&
6692
6096
  Object.keys(ModelClass === null || ModelClass === void 0 ? void 0 : ModelClass.schema).includes('storageTransactionId') &&
@@ -6699,15 +6103,14 @@ class Item {
6699
6103
  seedUid,
6700
6104
  schemaUid,
6701
6105
  ModelClass,
6106
+ latestVersionLocalId,
6107
+ latestVersionUid,
6702
6108
  storageTransactionId: this._storageTransactionId,
6703
6109
  },
6704
6110
  });
6705
6111
  this._subscription = this._service.subscribe((snapshot) => {
6706
6112
  const { context } = snapshot;
6707
- if (
6708
- // snapshot.value === 'waitingForDb' ||
6709
- // snapshot.value === 'initializing' ||
6710
- !context ||
6113
+ if (!context ||
6711
6114
  !context.propertyInstances ||
6712
6115
  context.propertyInstances.size === 0) {
6713
6116
  return;
@@ -6739,6 +6142,8 @@ class Item {
6739
6142
  const itemPropertyBase = {
6740
6143
  seedLocalId,
6741
6144
  seedUid,
6145
+ versionLocalId: latestVersionLocalId,
6146
+ versionUid: latestVersionUid,
6742
6147
  itemModelName: modelName,
6743
6148
  schemaUid,
6744
6149
  };
@@ -6762,6 +6167,9 @@ class Item {
6762
6167
  }
6763
6168
  static create(props) {
6764
6169
  return __awaiter(this, void 0, void 0, function* () {
6170
+ if (!props.seedUid) {
6171
+ console.log('Creating new item without seedUid');
6172
+ }
6765
6173
  if (props.seedUid || props.seedLocalId) {
6766
6174
  const seedId = (props.seedUid || props.seedLocalId);
6767
6175
  if (Item.instanceCache.has(seedId)) {
@@ -6806,6 +6214,10 @@ class Item {
6806
6214
  seedLocalId,
6807
6215
  seedUid,
6808
6216
  });
6217
+ if (!itemData) {
6218
+ console.error('No item data found', { modelName, seedLocalId, seedUid });
6219
+ return;
6220
+ }
6809
6221
  return Item.create(Object.assign(Object.assign({}, itemData), { modelName }));
6810
6222
  });
6811
6223
  }
@@ -6882,6 +6294,1008 @@ class Item {
6882
6294
  _a$1 = immerable;
6883
6295
  Item.instanceCache = new Map();
6884
6296
 
6297
+ const logger$3 = debug('app:react:services');
6298
+ const finalStrings = ['idle', 'ready', 'done', 'success'];
6299
+ const getServiceName = (service) => {
6300
+ let name = 'actor';
6301
+ if (service && service.uniqueKey) {
6302
+ name = service.uniqueKey;
6303
+ }
6304
+ if (service && !service.uniqueKey && service.logic && service.logic.config) {
6305
+ name = getServiceUniqueKey(service);
6306
+ }
6307
+ return name;
6308
+ };
6309
+ const getServiceValue = (service) => {
6310
+ let value;
6311
+ if (service && service.getSnapshot() && service.getSnapshot().value) {
6312
+ value = service.getSnapshot().value;
6313
+ }
6314
+ if (getServiceName(service) === 'global') {
6315
+ if (value &&
6316
+ typeof value === 'object' &&
6317
+ Object.keys(value).length > 0 &&
6318
+ Object.keys(value)[0] === 'initialized') {
6319
+ value = 'ready';
6320
+ }
6321
+ }
6322
+ if (value && typeof value === 'object') {
6323
+ value = JSON.stringify(value);
6324
+ }
6325
+ return value;
6326
+ };
6327
+ const getServiceUniqueKey = (service) => {
6328
+ if (!service || !service.logic || !service.logic.config) {
6329
+ return;
6330
+ }
6331
+ const config = service.logic.config;
6332
+ if (!config.id) {
6333
+ return;
6334
+ }
6335
+ let uniqueKey = config.id;
6336
+ if (config.id.includes('@seedSdk/')) {
6337
+ uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
6338
+ }
6339
+ let snapshot;
6340
+ try {
6341
+ snapshot = service.getSnapshot();
6342
+ }
6343
+ catch (error) {
6344
+ logger$3('Error:', error);
6345
+ return uniqueKey;
6346
+ }
6347
+ if (snapshot) {
6348
+ const context = snapshot.context;
6349
+ if (context && context.dbName) {
6350
+ uniqueKey = context.dbName;
6351
+ }
6352
+ if (context && context.modelNamePlural) {
6353
+ uniqueKey = context.modelNamePlural;
6354
+ }
6355
+ if (context && context.modelName) {
6356
+ uniqueKey = pluralize(context.modelName.toLowerCase());
6357
+ }
6358
+ }
6359
+ return uniqueKey;
6360
+ };
6361
+ const useIsDbReady = () => {
6362
+ const [isDbReady, setIsDbReady] = useState(false);
6363
+ const { internalStatus } = useGlobalServiceStatus();
6364
+ useEffect(() => {
6365
+ if (internalStatus === 'ready') {
6366
+ setIsDbReady(true);
6367
+ }
6368
+ }, [internalStatus]);
6369
+ return isDbReady;
6370
+ };
6371
+ const useServices = () => {
6372
+ const [actors, setActors] = useState([]);
6373
+ const [percentComplete, setPercentComplete] = useState(5);
6374
+ const actorsMap = new Map();
6375
+ useEffect(() => {
6376
+ const globalServiceListener = (event) => {
6377
+ if (event && event.type === 'init') {
6378
+ return;
6379
+ }
6380
+ if (event.actorRef &&
6381
+ event.actorRef.logic &&
6382
+ event.actorRef.logic.config) {
6383
+ const service = event.actorRef;
6384
+ const services = [service];
6385
+ if (service.logic.config.id === MachineIds.GLOBAL) {
6386
+ const context = service.getSnapshot().context;
6387
+ const keys = Object.keys(context);
6388
+ for (const key of keys) {
6389
+ if (!key.startsWith('internal') && key.endsWith('Service')) {
6390
+ const allItemsService = context[key];
6391
+ services.push(allItemsService);
6392
+ }
6393
+ }
6394
+ }
6395
+ services.forEach((innerService) => {
6396
+ const uniqueKey = getServiceUniqueKey(innerService);
6397
+ if (!uniqueKey) {
6398
+ return;
6399
+ }
6400
+ innerService.uniqueKey = uniqueKey;
6401
+ actorsMap.set(uniqueKey, innerService);
6402
+ });
6403
+ let actorsArray = Array.from(actorsMap.values());
6404
+ actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
6405
+ setActors(produce(actors, (draft) => {
6406
+ return actorsArray;
6407
+ }));
6408
+ }
6409
+ };
6410
+ eventEmitter.addListener('inspect.globalService', globalServiceListener);
6411
+ return () => {
6412
+ eventEmitter.removeListener('inspect.globalService', globalServiceListener);
6413
+ };
6414
+ }, []);
6415
+ useEffect(() => {
6416
+ const globalService = actors.find((actor) => getServiceName(actor) === 'global');
6417
+ const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
6418
+ if (!globalService || !internalService) {
6419
+ return;
6420
+ }
6421
+ if (getServiceValue(globalService) === 'ready' &&
6422
+ getServiceValue(internalService) === 'ready') {
6423
+ const denominator = actors.length;
6424
+ const finishedActors = actors.filter((actor) => {
6425
+ const value = getServiceValue(actor);
6426
+ return finalStrings.includes(value);
6427
+ });
6428
+ const numerator = finishedActors.length;
6429
+ const percentComplete = (numerator / denominator) * 100;
6430
+ setPercentComplete(percentComplete);
6431
+ }
6432
+ }, [actors]);
6433
+ return {
6434
+ services: actors,
6435
+ percentComplete,
6436
+ };
6437
+ };
6438
+ const useGlobalServiceStatus = () => {
6439
+ const globalService = getGlobalService();
6440
+ const status = useSelector(globalService, (snapshot) => {
6441
+ return snapshot.value;
6442
+ });
6443
+ const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
6444
+ if (!snapshot) {
6445
+ return;
6446
+ }
6447
+ return snapshot.value;
6448
+ });
6449
+ useSelector(globalService, (snapshot) => {
6450
+ return snapshot.context.internalService;
6451
+ });
6452
+ return {
6453
+ status,
6454
+ internalStatus,
6455
+ };
6456
+ };
6457
+
6458
+ const logger$2 = debug('app:react:item');
6459
+ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6460
+ const [itemData, setItemData] = useImmer({});
6461
+ const [item, setItem] = useState();
6462
+ const [itemSubscription, setItemSubscription] = useState();
6463
+ const { status, internalStatus } = useGlobalServiceStatus();
6464
+ const isReadingDb = useRef(false);
6465
+ const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6466
+ const updateItem = useCallback((newItem) => {
6467
+ setItemData((draft) => {
6468
+ Object.keys(newItem.properties).forEach((propertyName) => {
6469
+ const value = newItem[propertyName];
6470
+ draft[propertyName] = value;
6471
+ });
6472
+ });
6473
+ }, []);
6474
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6475
+ if (isReadingDb.current ||
6476
+ internalStatus !== 'ready' ||
6477
+ (!seedUid && !seedLocalId)) {
6478
+ return;
6479
+ }
6480
+ isReadingDb.current = true;
6481
+ const foundItem = yield Item.find({
6482
+ modelName,
6483
+ seedLocalId,
6484
+ seedUid,
6485
+ });
6486
+ if (!foundItem) {
6487
+ logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6488
+ return;
6489
+ }
6490
+ setItem(foundItem);
6491
+ updateItem(foundItem);
6492
+ isReadingDb.current = false;
6493
+ }), [internalStatus]);
6494
+ const listenerRef = useRef(readFromDb);
6495
+ useEffect(() => {
6496
+ listenerRef.current = readFromDb;
6497
+ }, [readFromDb]);
6498
+ useEffect(() => {
6499
+ if (internalStatus === 'ready') {
6500
+ listenerRef.current();
6501
+ }
6502
+ }, [internalStatus, status]);
6503
+ useEffect(() => {
6504
+ if (item && !itemSubscription) {
6505
+ const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6506
+ const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6507
+ if (!newItem) {
6508
+ logger$2('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6509
+ return;
6510
+ }
6511
+ updateItem(newItem);
6512
+ setItem(newItem);
6513
+ }));
6514
+ setItemSubscription(subscription);
6515
+ }
6516
+ return () => {
6517
+ itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
6518
+ };
6519
+ }, [item, itemSubscription]);
6520
+ useEffect(() => {
6521
+ const seedId = seedUid || seedLocalId;
6522
+ eventEmitter.addListener(`item.${modelName}.${seedId}.update`, () => {
6523
+ listenerRef.current();
6524
+ });
6525
+ return () => {
6526
+ eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
6527
+ };
6528
+ }, []);
6529
+ return {
6530
+ item,
6531
+ itemData,
6532
+ itemStatus,
6533
+ };
6534
+ };
6535
+ const useItems = ({ modelName, deleted }) => {
6536
+ const [items, setItems] = useImmer([]);
6537
+ const [isReadingDb, setIsReadingDb] = useState(false);
6538
+ const [isInitialized, setIsInitialized] = useState(false);
6539
+ const isDbReady = useIsDbReady();
6540
+ const modelNameRef = useRef(modelName);
6541
+ const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
6542
+ if (!event ||
6543
+ !event.modelName ||
6544
+ event.modelName !== modelNameRef.current ||
6545
+ isReadingDb) {
6546
+ return;
6547
+ }
6548
+ setIsReadingDb(true);
6549
+ const allItems = yield Item.all(modelNameRef.current, deleted);
6550
+ setItems(() => allItems);
6551
+ setIsReadingDb(false);
6552
+ }), [modelName, isReadingDb]);
6553
+ useEffect(() => {
6554
+ if (isDbReady && !isInitialized) {
6555
+ const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
6556
+ yield readFromDb({ modelName });
6557
+ setIsInitialized(true);
6558
+ });
6559
+ _fetchItems();
6560
+ }
6561
+ }, [isInitialized, isDbReady]);
6562
+ useEffect(() => {
6563
+ eventEmitter.addListener('item.requestAll', readFromDb);
6564
+ return () => {
6565
+ eventEmitter.removeListener('item.requestAll');
6566
+ };
6567
+ }, []);
6568
+ return {
6569
+ items: orderBy(items, [
6570
+ (item) => item.lastVersionPublishedAt ||
6571
+ item.attestationCreatedAt ||
6572
+ item.createdAt,
6573
+ ], ['desc']).slice(0, 10),
6574
+ isReadingDb,
6575
+ isInitialized,
6576
+ };
6577
+ };
6578
+ const useItemIsReady = () => {
6579
+ const [itemListenersReady, setItemListenersReady] = useState(false);
6580
+ const itemEventListenersHandler = useCallback((_) => {
6581
+ setItemListenersReady(true);
6582
+ }, []);
6583
+ useEffect(() => {
6584
+ const areReady = getAreItemEventHandlersReady();
6585
+ if (areReady) {
6586
+ itemEventListenersHandler(true);
6587
+ }
6588
+ eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6589
+ return () => {
6590
+ eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6591
+ };
6592
+ }, []);
6593
+ return {
6594
+ isReady: itemListenersReady,
6595
+ };
6596
+ };
6597
+ const useCreateItem = (modelName) => {
6598
+ const [isCreatingItem, setIsCreatingItem] = useState(false);
6599
+ const { isReady } = useItemIsReady();
6600
+ const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6601
+ if (!isReady) {
6602
+ console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
6603
+ return;
6604
+ }
6605
+ if (isCreatingItem) {
6606
+ // TODO: should we setup a queue for this?
6607
+ console.error(`[useCreateItem] [createItem] already creating item`, itemData);
6608
+ return;
6609
+ }
6610
+ setIsCreatingItem(true);
6611
+ const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6612
+ yield Item.find({ modelName, seedLocalId });
6613
+ eventEmitter.emit('item.requestAll', { modelName });
6614
+ setIsCreatingItem(false);
6615
+ }), [isCreatingItem, isReady]);
6616
+ return {
6617
+ createItem,
6618
+ isCreatingItem,
6619
+ };
6620
+ };
6621
+
6622
+ const logger$1 = debug('app:react:property');
6623
+ const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6624
+ const [property, setProperty] = useState();
6625
+ const [isReadingFromDb, setIsReadingFromDb] = useState(false);
6626
+ const [isInitialized, setIsInitialized] = useState(false);
6627
+ // const isDbReady = useMemo(() => useIsDbReady(), [])
6628
+ const { internalStatus } = useGlobalServiceStatus();
6629
+ const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
6630
+ if (!snapshot || !snapshot.context) {
6631
+ return;
6632
+ }
6633
+ return snapshot.context.renderValue || snapshot.context.propertyValue;
6634
+ });
6635
+ const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6636
+ // useEffect(() => {
6637
+ // if (property && property.value !== value) {
6638
+ // readFromDb()
6639
+ // }
6640
+ // }, [property, value])
6641
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6642
+ if (internalStatus !== 'ready' ||
6643
+ isReadingFromDb ||
6644
+ (!seedLocalId && !seedUid)) {
6645
+ return;
6646
+ }
6647
+ setIsReadingFromDb(true);
6648
+ const foundProperty = yield ItemProperty.find({
6649
+ propertyName,
6650
+ seedLocalId,
6651
+ seedUid,
6652
+ });
6653
+ setIsReadingFromDb(false);
6654
+ if (!foundProperty) {
6655
+ logger$1(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6656
+ return;
6657
+ }
6658
+ if (foundProperty.status === 'waitingForDb') {
6659
+ foundProperty.getService().send({ type: 'waitForDbSuccess' });
6660
+ }
6661
+ setProperty(foundProperty);
6662
+ setIsInitialized(true);
6663
+ }), [internalStatus, isReadingFromDb]);
6664
+ // let count = 0
6665
+ //
6666
+ // const refresh = useCallback(() => {
6667
+ // count++
6668
+ // console.log('[useItemPropertyTest] [refresh] property', property)
6669
+ // }, [property])
6670
+ useEffect(() => {
6671
+ if (internalStatus === 'ready') {
6672
+ readFromDb();
6673
+ }
6674
+ }, [internalStatus]);
6675
+ // useEffect(() => {
6676
+ // eventEmitter.addListener(
6677
+ // `property.${seedUid || seedLocalId}.${propertyName}.update`,
6678
+ // (event) => {
6679
+ // refresh()
6680
+ // },
6681
+ // )
6682
+ //
6683
+ // return () => {
6684
+ // eventEmitter.removeListener(
6685
+ // `property.${seedUid || seedLocalId}.${propertyName}.update`,
6686
+ // )
6687
+ // }
6688
+ // }, [])
6689
+ return {
6690
+ property,
6691
+ isInitialized,
6692
+ isReadingFromDb,
6693
+ value,
6694
+ status,
6695
+ };
6696
+ };
6697
+ const useItemProperties = (item) => {
6698
+ const [propertyObj, setPropertyObj] = useImmer({});
6699
+ useState(false);
6700
+ const updatePropertyObj = useCallback((event) => {
6701
+ if (!item) {
6702
+ console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6703
+ return;
6704
+ }
6705
+ const { propertyName, propertyValue } = event;
6706
+ if (!propertyName) {
6707
+ return;
6708
+ }
6709
+ setPropertyObj((draft) => {
6710
+ draft[propertyName] = propertyValue;
6711
+ });
6712
+ }, [item]);
6713
+ useEffect(() => {
6714
+ if (!item) {
6715
+ return;
6716
+ }
6717
+ const eventKey = `item.${item.seedLocalId}.property.update`;
6718
+ eventEmitter.addListener(eventKey, updatePropertyObj);
6719
+ return () => {
6720
+ eventEmitter.removeListener(eventKey, updatePropertyObj);
6721
+ };
6722
+ }, [item]);
6723
+ return {
6724
+ properties: propertyObj,
6725
+ };
6726
+ };
6727
+
6728
+ debug('app:react:db');
6729
+
6730
+ const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
6731
+ const appDb = getAppDb();
6732
+ yield appDb
6733
+ .update(seeds)
6734
+ .set({
6735
+ _markedForDeletion: 1,
6736
+ })
6737
+ .where(or(eq(seeds.localId, seedLocalId), eq(seeds.uid, seedUid)));
6738
+ });
6739
+
6740
+ const useDeleteItem = () => {
6741
+ const [isDeletingItem, setIsDeletingItem] = useState(false);
6742
+ const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6743
+ if (!item) {
6744
+ return;
6745
+ }
6746
+ setIsDeletingItem(true);
6747
+ const { modelName } = item.getService().getSnapshot().context;
6748
+ yield deleteItem({ seedLocalId: item.seedLocalId });
6749
+ eventEmitter.emit('item.requestAll', { modelName });
6750
+ setIsDeletingItem(false);
6751
+ }), [isDeletingItem]);
6752
+ useEffect(() => { }, []);
6753
+ return {
6754
+ deleteItem: destroy,
6755
+ isDeletingItem,
6756
+ };
6757
+ };
6758
+
6759
+ const logger = debug('app:services:events');
6760
+ const handleServiceSaveState = (event) => {
6761
+ const { state, serviceId } = event;
6762
+ logger(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6763
+ localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state));
6764
+ };
6765
+ const setupServicesEventHandlers = () => {
6766
+ eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
6767
+ };
6768
+
6769
+ const saveServiceHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6770
+ const globalService = getGlobalService();
6771
+ if (!globalService || !globalService.getSnapshot().context) {
6772
+ return;
6773
+ }
6774
+ const { modelName } = event;
6775
+ const nameOfService = `${modelName}Service`;
6776
+ const service = globalService.getSnapshot().context[nameOfService];
6777
+ yield writeAppState(`snapshot__${modelName}`, JSON.stringify(service.getPersistedSnapshot()));
6778
+ });
6779
+
6780
+ const setupServiceHandlers = () => {
6781
+ eventEmitter.addListener('service.save', saveServiceHandler);
6782
+ };
6783
+
6784
+ const client = {
6785
+ init: ({ config, addresses }) => {
6786
+ const { endpoints, models } = config;
6787
+ for (const [key, value] of Object.entries(models)) {
6788
+ setModel(key, value);
6789
+ }
6790
+ setupFsListeners();
6791
+ setupAllItemsEventHandlers();
6792
+ setupServicesEventHandlers();
6793
+ setupServiceHandlers();
6794
+ if (areFsListenersReady()) {
6795
+ eventEmitter.emit('fs.init');
6796
+ }
6797
+ if (!areFsListenersReady()) {
6798
+ console.error('fs listeners not ready during init');
6799
+ }
6800
+ globalService.send({ type: 'init', endpoints, models, addresses });
6801
+ import('./seed.schema.config-BHZSMMmL.js').then(({ models }) => {
6802
+ for (const [key, value] of Object.entries(models)) {
6803
+ setModel(key, value);
6804
+ }
6805
+ });
6806
+ },
6807
+ subscribe: (callback) => {
6808
+ callback({
6809
+ type: '@xstate.snapshot',
6810
+ actorRef: globalService,
6811
+ snapshot: globalService.getSnapshot(),
6812
+ });
6813
+ eventEmitter.addListener('globalService', callback);
6814
+ return {
6815
+ unsubscribe: () => {
6816
+ eventEmitter.removeListener('globalService', callback);
6817
+ },
6818
+ };
6819
+ },
6820
+ on: (outerEvent, callback) => {
6821
+ eventEmitter.addListener(outerEvent, callback);
6822
+ return {
6823
+ unsubscribe: () => {
6824
+ eventEmitter.removeListener(outerEvent, callback);
6825
+ },
6826
+ };
6827
+ },
6828
+ getSeedClass: () => __awaiter(void 0, void 0, void 0, function* () {
6829
+ return new Promise((resolve) => {
6830
+ const subscription = globalService.subscribe((snapshot) => {
6831
+ if (snapshot.status === 'done') {
6832
+ resolve(snapshot.output);
6833
+ }
6834
+ });
6835
+ globalService.send({ type: 'getSeed' });
6836
+ subscription.unsubscribe();
6837
+ });
6838
+ }),
6839
+ getModel: (modelName) => {
6840
+ return getModel(modelName);
6841
+ },
6842
+ getModels: () => {
6843
+ return getModels();
6844
+ },
6845
+ getModelNames: () => {
6846
+ return getModelNames();
6847
+ },
6848
+ };
6849
+
6850
+ const getItemPropertyData = (props) => __awaiter(void 0, void 0, void 0, function* () {
6851
+ const appDb = getAppDb();
6852
+ const whereClauses = [];
6853
+ const tableColumns = getTableColumns(metadata);
6854
+ for (const [propertyName, propertyValue] of Object.entries(props)) {
6855
+ if (Object.keys(tableColumns).includes(propertyName)) {
6856
+ whereClauses.push(eq(tableColumns[propertyName], propertyValue));
6857
+ }
6858
+ }
6859
+ const queryRows = yield appDb
6860
+ .select()
6861
+ .from(metadata)
6862
+ .where(and(...whereClauses));
6863
+ if (!queryRows || queryRows.length === 0) {
6864
+ return;
6865
+ }
6866
+ return queryRows[0];
6867
+ });
6868
+
6869
+ const saveItemStorage = fromCallback(({ sendBack, input: { context, event } }) => {
6870
+ const { localId, seedLocalId, seedUid, propertyName, propertyRecordSchema, itemModelName, propertyValue: existingValue, } = context;
6871
+ if (!propertyRecordSchema) {
6872
+ throw new Error('Missing propertyRecordSchema');
6873
+ }
6874
+ let newValue;
6875
+ if (event) {
6876
+ newValue = event.newValue;
6877
+ }
6878
+ if (existingValue === newValue) {
6879
+ sendBack({ type: 'saveValueToDbSuccess' });
6880
+ return;
6881
+ }
6882
+ const _saveItemStorage = () => __awaiter(void 0, void 0, void 0, function* () {
6883
+ // Save value to file
6884
+ const appDb = getAppDb();
6885
+ let propertyData;
6886
+ if (localId) {
6887
+ propertyData = yield getItemPropertyData({
6888
+ localId,
6889
+ });
6890
+ }
6891
+ if (!localId && seedLocalId) {
6892
+ const itemData = yield getItemDataFromDb({
6893
+ seedLocalId,
6894
+ });
6895
+ if (itemData) {
6896
+ const whereClauses = [
6897
+ eq(metadata.propertyName, propertyName),
6898
+ eq(metadata.seedLocalId, seedLocalId),
6899
+ ];
6900
+ if (itemData.latestVersionLocalId) {
6901
+ whereClauses.push(eq(metadata.versionLocalId, itemData.latestVersionLocalId));
6902
+ }
6903
+ const queryRows = yield appDb
6904
+ .select()
6905
+ .from(metadata)
6906
+ .where(and(...whereClauses));
6907
+ if (queryRows && queryRows.length) {
6908
+ propertyData = queryRows[0];
6909
+ }
6910
+ if (!propertyData) {
6911
+ const propertyDataRows = yield createMetadata({
6912
+ propertyName,
6913
+ modelType: itemModelName.toLowerCase(),
6914
+ seedLocalId,
6915
+ seedUid,
6916
+ versionLocalId: itemData.latestVersionLocalId,
6917
+ versionUid: itemData.latestVersionUid,
6918
+ localStorageDir: propertyRecordSchema.localStorageDir,
6919
+ refValueType: 'file',
6920
+ }, propertyRecordSchema);
6921
+ propertyData = propertyDataRows[0];
6922
+ }
6923
+ // propertyData = {
6924
+ // propertyName,
6925
+ // seedLocalId,
6926
+ // seedUid,
6927
+ // versionLocalId: itemData.latestVersionLocalId,
6928
+ // versionUid: itemData.latestVersionUid,
6929
+ // schemaUid: itemData.schemaUid,
6930
+ // }
6931
+ }
6932
+ }
6933
+ const localStorageDir = propertyRecordSchema.localStorageDir || propertyData.localStorageDir;
6934
+ const fileName = propertyData.refResolvedValue ||
6935
+ `${propertyData.seedLocalId}${propertyRecordSchema.filenameSuffix}`;
6936
+ if (!localStorageDir || !fileName) {
6937
+ throw new Error(`Missing localStorageDir: ${localStorageDir} or fileName: ${fileName}`);
6938
+ }
6939
+ const filePath = `/files/${localStorageDir}/${fileName}`;
6940
+ yield fs.promises.writeFile(filePath, newValue);
6941
+ yield appDb
6942
+ .update(metadata)
6943
+ .set({
6944
+ refResolvedValue: fileName,
6945
+ })
6946
+ .where(eq(metadata.localId, propertyData.localId));
6947
+ sendBack({
6948
+ type: 'updateContext',
6949
+ renderValue: newValue,
6950
+ });
6951
+ return true;
6952
+ });
6953
+ _saveItemStorage().then((success) => {
6954
+ if (success) {
6955
+ sendBack({ type: 'saveItemStorageSuccess' });
6956
+ }
6957
+ });
6958
+ });
6959
+
6960
+ const analyzeInput = fromCallback(({ sendBack, input: { context, event } }) => {
6961
+ const { localId, propertyName: propertyNameRaw, seedLocalId, versionLocalId, propertyValue: existingValue, propertyRecordSchema, itemModelName, schemaUid, } = context;
6962
+ let newValue;
6963
+ if (event) {
6964
+ newValue = event.newValue;
6965
+ }
6966
+ if (existingValue === newValue) {
6967
+ sendBack({ type: 'saveValueToDbSuccess' });
6968
+ return;
6969
+ }
6970
+ if (!propertyRecordSchema) {
6971
+ throw new Error('Missing propertyRecordSchema');
6972
+ }
6973
+ const _analyzeInput = () => __awaiter(void 0, void 0, void 0, function* () {
6974
+ let propertyName = propertyNameRaw;
6975
+ if (propertyRecordSchema.refValueType !== 'ImageSrc' &&
6976
+ propertyRecordSchema.dataType === 'Relation') {
6977
+ sendBack({
6978
+ type: 'saveRelation',
6979
+ newValue,
6980
+ });
6981
+ return false;
6982
+ }
6983
+ if (propertyRecordSchema.refValueType === 'ImageSrc' ||
6984
+ propertyRecordSchema.dataType === 'ImageSrc') {
6985
+ sendBack({
6986
+ type: 'saveImageSrc',
6987
+ newValue,
6988
+ });
6989
+ return false;
6990
+ }
6991
+ if (propertyRecordSchema.storageType &&
6992
+ propertyRecordSchema.storageType === 'ItemStorage') {
6993
+ sendBack({
6994
+ type: 'saveItemStorage',
6995
+ newValue,
6996
+ });
6997
+ return false;
6998
+ }
6999
+ yield updateItemPropertyValue({
7000
+ propertyLocalId: localId,
7001
+ propertyName,
7002
+ newValue,
7003
+ seedLocalId,
7004
+ versionLocalId,
7005
+ modelName: itemModelName,
7006
+ schemaUid,
7007
+ });
7008
+ sendBack({
7009
+ type: 'updateContext',
7010
+ propertyValue: newValue,
7011
+ });
7012
+ return true;
7013
+ });
7014
+ _analyzeInput().then((isDone) => {
7015
+ if (isDone) {
7016
+ sendBack({ type: 'saveValueToDbSuccess' });
7017
+ }
7018
+ });
7019
+ });
7020
+
7021
+ // import { updateMachineContext } from '@/browser/helpers'
7022
+ const propertyMachine = setup({
7023
+ types: {
7024
+ context: {},
7025
+ input: {},
7026
+ },
7027
+ // actions: {
7028
+ // updateContext: updateMachineContext,
7029
+ // },
7030
+ actors: {
7031
+ waitForDb: waitForDb$1,
7032
+ hydrateFromDb,
7033
+ initialize: initialize$3,
7034
+ resolveRelatedValue,
7035
+ resolveRemoteStorage,
7036
+ analyzeInput,
7037
+ saveImageSrc,
7038
+ saveRelation,
7039
+ saveItemStorage,
7040
+ },
7041
+ }).createMachine({
7042
+ id: 'itemProperty',
7043
+ initial: 'waitingForDb',
7044
+ context: ({ input }) => input,
7045
+ on: {
7046
+ updatePropertyValue: {
7047
+ target: '.resolvingRelatedValue',
7048
+ guard: ({ context }) => !context.isDbReady,
7049
+ actions: assign(({ event }) => {
7050
+ return {
7051
+ propertyValue: event.propertyValue,
7052
+ };
7053
+ }),
7054
+ },
7055
+ updateRenderValue: {
7056
+ actions: assign(({ event, context }) => {
7057
+ return {
7058
+ renderValue: event.renderValue,
7059
+ };
7060
+ }),
7061
+ },
7062
+ save: {
7063
+ actions: assign({
7064
+ isSaving: true,
7065
+ }),
7066
+ target: '.saving',
7067
+ },
7068
+ updateContext: {
7069
+ actions: assign(({ context, event }) => {
7070
+ const newContext = Object.assign({}, context);
7071
+ for (let i = 0; i < Object.keys(event).length; i++) {
7072
+ const key = Object.keys(event)[i];
7073
+ if (key === 'type') {
7074
+ continue;
7075
+ }
7076
+ newContext[key] = event[key];
7077
+ }
7078
+ return newContext;
7079
+ }),
7080
+ },
7081
+ },
7082
+ states: {
7083
+ idle: {},
7084
+ waitingForDb: {
7085
+ on: {
7086
+ waitForDbSuccess: {
7087
+ target: 'hydratingFromDb',
7088
+ actions: assign({
7089
+ isDbReady: true,
7090
+ }),
7091
+ },
7092
+ },
7093
+ invoke: {
7094
+ src: 'waitForDb',
7095
+ input: ({ context }) => ({ context }),
7096
+ },
7097
+ },
7098
+ hydratingFromDb: {
7099
+ on: {
7100
+ hydrateFromDbSuccess: 'initializing',
7101
+ },
7102
+ invoke: {
7103
+ src: 'hydrateFromDb',
7104
+ input: ({ context }) => ({ context }),
7105
+ },
7106
+ },
7107
+ initializing: {
7108
+ on: {
7109
+ initializeSuccess: 'idle',
7110
+ isRelatedProperty: {
7111
+ target: 'resolvingRelatedValue',
7112
+ },
7113
+ hasRemoteBackup: {
7114
+ target: 'resolvingRemoteStorage',
7115
+ },
7116
+ },
7117
+ invoke: {
7118
+ src: 'initialize',
7119
+ input: ({ context, event }) => ({ context, event }),
7120
+ },
7121
+ },
7122
+ resolvingRelatedValue: {
7123
+ on: {
7124
+ resolvingRelatedValueSuccess: {
7125
+ target: 'idle',
7126
+ actions: assign({
7127
+ resolvedDisplayValue: ({ event }) => event.resolvedDisplayValue,
7128
+ resolvedValue: ({ event }) => event.resolvedValue,
7129
+ }),
7130
+ },
7131
+ resolvingRelatedValueDone: {
7132
+ target: 'idle',
7133
+ },
7134
+ },
7135
+ invoke: {
7136
+ src: 'resolveRelatedValue',
7137
+ input: ({ context }) => ({ context }),
7138
+ },
7139
+ },
7140
+ resolvingRemoteStorage: {
7141
+ on: {
7142
+ resolveRemoteStorageSuccess: {
7143
+ target: 'idle',
7144
+ },
7145
+ },
7146
+ invoke: {
7147
+ src: 'resolveRemoteStorage',
7148
+ input: ({ context }) => ({ context }),
7149
+ },
7150
+ },
7151
+ saving: {
7152
+ initial: 'analyzingInput',
7153
+ states: {
7154
+ analyzingInput: {
7155
+ on: {
7156
+ saveValueToDbSuccess: {
7157
+ target: 'doneSaving',
7158
+ },
7159
+ saveImageSrc: 'savingImageSrc',
7160
+ saveRelation: 'savingRelation',
7161
+ saveItemStorage: 'savingItemStorage',
7162
+ },
7163
+ invoke: {
7164
+ src: 'analyzeInput',
7165
+ input: ({ context, event }) => ({ context, event }),
7166
+ },
7167
+ },
7168
+ savingImageSrc: {
7169
+ on: {
7170
+ saveImageSrcSuccess: 'doneSaving',
7171
+ },
7172
+ invoke: {
7173
+ src: 'saveImageSrc',
7174
+ input: ({ context, event }) => ({ context, event }),
7175
+ },
7176
+ },
7177
+ savingRelation: {
7178
+ on: {
7179
+ saveRelationSuccess: 'doneSaving',
7180
+ },
7181
+ invoke: {
7182
+ src: 'saveRelation',
7183
+ input: ({ context, event }) => ({ context, event }),
7184
+ },
7185
+ },
7186
+ savingItemStorage: {
7187
+ on: {
7188
+ saveItemStorageSuccess: 'doneSaving',
7189
+ },
7190
+ invoke: {
7191
+ src: 'saveItemStorage',
7192
+ input: ({ context, event }) => ({ context, event }),
7193
+ },
7194
+ },
7195
+ doneSaving: {
7196
+ type: 'final',
7197
+ },
7198
+ },
7199
+ onDone: {
7200
+ target: 'idle',
7201
+ actions: assign(({ context }) => {
7202
+ return {
7203
+ isSaving: false,
7204
+ };
7205
+ }),
7206
+ },
7207
+ },
7208
+ },
7209
+ // conflict: {
7210
+ // on: {
7211
+ // resolveConflict: {
7212
+ // target: 'saving',
7213
+ // actions: assign({
7214
+ // data: ({ context, event }) => event.output,
7215
+ // }),
7216
+ // },
7217
+ // },
7218
+ // },
7219
+ });
7220
+
7221
+ const TPropertyDataType = Type.Union([
7222
+ Type.Literal('Text'),
7223
+ Type.Literal('Number'),
7224
+ Type.Literal('List'),
7225
+ Type.Literal('Relation'),
7226
+ Type.Literal('ImageSrc'),
7227
+ Type.Literal('FileSrc'),
7228
+ Type.Literal('Json'),
7229
+ Type.Literal('Blob'),
7230
+ ]);
7231
+ const TStorageType = Type.Union([
7232
+ Type.Literal('ItemStorage'), // Looks for a storageTransactionId property on the item
7233
+ Type.Literal('PropertyStorage'), // Looks for a storageTransactionId value on the property
7234
+ ]);
7235
+ const TProperty = Type.Object({
7236
+ id: Type.Optional(Type.Number()),
7237
+ name: Type.Optional(Type.String()),
7238
+ dataType: TPropertyDataType,
7239
+ ref: Type.Optional(Type.String()),
7240
+ modelId: Type.Optional(Type.Number()),
7241
+ refModelId: Type.Optional(Type.Number()),
7242
+ refValueType: Type.Optional(TPropertyDataType),
7243
+ storageType: Type.Optional(TStorageType),
7244
+ localStorageDir: Type.Optional(Type.String()),
7245
+ filenameSuffix: Type.Optional(Type.String()),
7246
+ });
7247
+ const TPropertyConstructor = Type.Function([
7248
+ Type.Optional(Type.Union([Type.String(), TStorageType, Type.Undefined()])),
7249
+ Type.Optional(Type.Union([Type.String(), TPropertyDataType])),
7250
+ Type.Optional(Type.String()),
7251
+ ], TProperty);
7252
+ Type.Record(TPropertyDataType, TPropertyConstructor);
7253
+ const Property = {
7254
+ Text: (storageType, localStorageDir, filenameSuffix) => ({
7255
+ dataType: 'Text',
7256
+ storageType,
7257
+ localStorageDir,
7258
+ filenameSuffix,
7259
+ TObject: Type.String(),
7260
+ }),
7261
+ Json: () => ({ dataType: 'Json' }),
7262
+ Blob: () => ({ dataType: 'Blob' }),
7263
+ Number: () => ({ dataType: 'Number' }),
7264
+ List: (ref, refValueType) => ({
7265
+ dataType: 'List',
7266
+ ref,
7267
+ refValueType,
7268
+ }),
7269
+ Relation: (ref, refValueType) => ({
7270
+ dataType: 'Relation',
7271
+ ref,
7272
+ refValueType,
7273
+ }),
7274
+ ImageSrc: () => ({ dataType: 'ImageSrc' }),
7275
+ };
7276
+ const PropertyMetadataKey = Symbol('property');
7277
+ const PropertyConstructor = (propertyType) => {
7278
+ return function (parentClassPrototype, propertyKey) {
7279
+ const existingProperties = Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype) || [];
7280
+ existingProperties.push({ propertyKey, propertyType });
7281
+ // console.log('existingProperties', existingProperties)
7282
+ // console.log('propertyKey', propertyKey)
7283
+ // console.log('propertyType', propertyType)
7284
+ // console.log('PropertyMetadataKey', PropertyMetadataKey)
7285
+ // console.log('typeof target', typeof target)
7286
+ Reflect.defineMetadata(PropertyMetadataKey, existingProperties, parentClassPrototype);
7287
+ // console.log(
7288
+ // `After adding ${propertyKey}:`,
7289
+ // Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype),
7290
+ // )
7291
+ };
7292
+ };
7293
+ const Text = (storageType, srcDir, filenameSuffix) => PropertyConstructor(Property.Text(storageType, srcDir, filenameSuffix));
7294
+ const Json = () => PropertyConstructor(Property.Json());
7295
+ const ImageSrc = () => PropertyConstructor(Property.ImageSrc());
7296
+ const Relation = (ref, refValueType) => PropertyConstructor(Property.Relation(ref, refValueType)); // Adjust for actual relation type
7297
+ const List = (ref, reValueType) => PropertyConstructor(Property.List(ref, reValueType)); // Adjust for actual list type
7298
+
6885
7299
  const TModelValues = Type.Record(Type.String(), Type.Any());
6886
7300
  const TModelSchema = Type.Record(Type.String(), TProperty);
6887
7301
  const TModelClass = Type.Object({
@@ -6956,4 +7370,4 @@ if (isNode()) {
6956
7370
  }
6957
7371
 
6958
7372
  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 };
6959
- //# sourceMappingURL=index-DcXK4ERW.js.map
7373
+ //# sourceMappingURL=index-D4my8yy8.js.map