@seedprotocol/sdk 0.1.18 → 0.1.20

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 (170) hide show
  1. package/dist/bin.js +102 -228
  2. package/dist/bin.js.map +1 -1
  3. package/dist/constants-KW2RTtZB.js +97 -0
  4. package/dist/constants-KW2RTtZB.js.map +1 -0
  5. package/dist/{events-So24__c6.js → index-B299zGP9.js} +1773 -1748
  6. package/dist/index-B299zGP9.js.map +1 -0
  7. package/dist/{index-Cgo0-c0n.js → index-Ul8aVKpd.js} +19 -18
  8. package/dist/index-Ul8aVKpd.js.map +1 -0
  9. package/dist/main.js +16 -416
  10. package/dist/main.js.map +1 -1
  11. package/dist/node/codegen/templates/index.njk +8 -0
  12. package/dist/{seed-DGCfCUOn.js → seed-B5wj0Uk8.js} +20 -19
  13. package/dist/seed-B5wj0Uk8.js.map +1 -0
  14. package/dist/{seed-CFk2xaH7.js → seed-Q9tT10q-.js} +3 -2
  15. package/dist/seed-Q9tT10q-.js.map +1 -0
  16. package/dist/{seed-BgRaREFr.js → seed-Y2OY2Tg_.js} +19 -18
  17. package/dist/seed-Y2OY2Tg_.js.map +1 -0
  18. package/dist/{seed.schema.config-DYkIbj49.js → seed.schema.config-DZC8TNja.js} +15 -14
  19. package/dist/seed.schema.config-DZC8TNja.js.map +1 -0
  20. package/dist/shared/configs/browser.app.db.config.ts +1 -6
  21. package/dist/shared/{sdkSchema/modelUidSchema.ts → seedSchema/ModelUidSchema.ts} +1 -1
  22. package/dist/shared/{sdkSchema/propertyUidSchema.ts → seedSchema/PropertyUidSchema.ts} +1 -1
  23. package/dist/shared/seedSchema/index.ts +8 -0
  24. package/dist/types/scripts/bin.d.ts.map +1 -1
  25. package/dist/types/src/browser/db/index.d.ts +1 -4
  26. package/dist/types/src/browser/db/index.d.ts.map +1 -1
  27. package/dist/types/src/browser/db/read.d.ts +1 -1
  28. package/dist/types/src/browser/db/read.d.ts.map +1 -1
  29. package/dist/types/src/browser/db/save.d.ts.map +1 -1
  30. package/dist/types/src/browser/db/sqlWasmClient.d.ts +8 -1
  31. package/dist/types/src/browser/db/sqlWasmClient.d.ts.map +1 -1
  32. package/dist/types/src/browser/db/write.d.ts.map +1 -1
  33. package/dist/types/src/browser/events/files/download.d.ts.map +1 -1
  34. package/dist/types/src/browser/events/item/syncDbWithEas.d.ts +2 -1
  35. package/dist/types/src/browser/events/item/syncDbWithEas.d.ts.map +1 -1
  36. package/dist/types/src/browser/events/property/save.d.ts.map +1 -1
  37. package/dist/types/src/browser/events/property/saveRelation.d.ts.map +1 -1
  38. package/dist/types/src/browser/item/all/actors/fetchRelatedItems.d.ts +2 -1
  39. package/dist/types/src/browser/item/all/actors/fetchRelatedItems.d.ts.map +1 -1
  40. package/dist/types/src/browser/item/all/actors/initialize.d.ts.map +1 -1
  41. package/dist/types/src/browser/item/class.d.ts +1 -1
  42. package/dist/types/src/browser/item/class.d.ts.map +1 -1
  43. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts +1 -2
  44. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  45. package/dist/types/src/browser/property/actors/initialize.d.ts +1 -2
  46. package/dist/types/src/browser/property/actors/initialize.d.ts.map +1 -1
  47. package/dist/types/src/browser/property/actors/waitForDb.d.ts +3 -1
  48. package/dist/types/src/browser/property/actors/waitForDb.d.ts.map +1 -1
  49. package/dist/types/src/browser/property/class.d.ts.map +1 -1
  50. package/dist/types/src/browser/react/property.d.ts +2 -1
  51. package/dist/types/src/browser/react/property.d.ts.map +1 -1
  52. package/dist/types/src/browser/react/services.d.ts +1 -6
  53. package/dist/types/src/browser/react/services.d.ts.map +1 -1
  54. package/dist/types/src/browser/schema/file/fetchAll/actors.d.ts.map +1 -1
  55. package/dist/types/src/browser/services/db/actors/checkStatus.d.ts +4 -0
  56. package/dist/types/src/browser/services/db/actors/checkStatus.d.ts.map +1 -0
  57. package/dist/types/src/browser/services/db/actors/connectToDb.d.ts +4 -0
  58. package/dist/types/src/browser/services/db/actors/connectToDb.d.ts.map +1 -0
  59. package/dist/types/src/browser/services/db/actors/migrate.d.ts +5 -0
  60. package/dist/types/src/browser/services/db/actors/migrate.d.ts.map +1 -0
  61. package/dist/types/src/browser/services/db/actors/validate.d.ts +3 -0
  62. package/dist/types/src/browser/services/db/actors/validate.d.ts.map +1 -0
  63. package/dist/types/src/browser/services/db/dbMachine.d.ts +48 -0
  64. package/dist/types/src/browser/services/db/dbMachine.d.ts.map +1 -0
  65. package/dist/types/src/browser/services/global/actors/addModelsToDb.d.ts +4 -0
  66. package/dist/types/src/browser/services/global/actors/addModelsToDb.d.ts.map +1 -0
  67. package/dist/types/src/browser/services/global/actors/getSchemaForModel.d.ts +4 -0
  68. package/dist/types/src/browser/services/global/actors/getSchemaForModel.d.ts.map +1 -0
  69. package/dist/types/src/browser/services/global/actors/initialize.d.ts +3 -1
  70. package/dist/types/src/browser/services/global/actors/initialize.d.ts.map +1 -1
  71. package/dist/types/src/browser/services/global/globalMachine.d.ts +72 -4
  72. package/dist/types/src/browser/services/global/globalMachine.d.ts.map +1 -1
  73. package/dist/types/src/browser/services/internal/actors/configureFs.d.ts +3 -1
  74. package/dist/types/src/browser/services/internal/actors/configureFs.d.ts.map +1 -1
  75. package/dist/types/src/browser/services/internal/actors/loadAppDb.d.ts +3 -1
  76. package/dist/types/src/browser/services/internal/actors/loadAppDb.d.ts.map +1 -1
  77. package/dist/types/src/browser/services/internal/actors/prepareDb.d.ts +2 -1
  78. package/dist/types/src/browser/services/internal/actors/prepareDb.d.ts.map +1 -1
  79. package/dist/types/src/browser/services/internal/actors/saveConfig.d.ts +3 -1
  80. package/dist/types/src/browser/services/internal/actors/saveConfig.d.ts.map +1 -1
  81. package/dist/types/src/browser/services/internal/constants.d.ts +0 -8
  82. package/dist/types/src/browser/services/internal/constants.d.ts.map +1 -1
  83. package/dist/types/src/browser/services/internal/internalMachine.d.ts +1 -2
  84. package/dist/types/src/browser/services/internal/internalMachine.d.ts.map +1 -1
  85. package/dist/types/src/browser/services/syncDbWithEas/actors.d.ts.map +1 -1
  86. package/dist/types/src/node/codegen/drizzle.d.ts +1 -1
  87. package/dist/types/src/node/codegen/drizzle.d.ts.map +1 -1
  88. package/dist/types/src/node/constants.d.ts +2 -9
  89. package/dist/types/src/node/constants.d.ts.map +1 -1
  90. package/dist/types/src/node/db/index.d.ts +2 -2
  91. package/dist/types/src/node/db/index.d.ts.map +1 -1
  92. package/dist/types/src/node/db/node.app.db.config.d.ts +4 -0
  93. package/dist/types/src/node/db/node.app.db.config.d.ts.map +1 -0
  94. package/dist/types/src/node/helpers/index.d.ts +1 -1
  95. package/dist/types/src/node/helpers/index.d.ts.map +1 -1
  96. package/dist/types/src/shared/configs/browser.app.db.config.d.ts.map +1 -1
  97. package/dist/types/src/shared/helpers/constants.d.ts +0 -5
  98. package/dist/types/src/shared/helpers/constants.d.ts.map +1 -1
  99. package/dist/types/src/shared/helpers/db.d.ts.map +1 -1
  100. package/dist/types/src/shared/seedSchema/AppStateSchema.d.ts.map +1 -0
  101. package/dist/types/src/shared/{sdkSchema/configSchema.d.ts → seedSchema/ConfigSchema.d.ts} +1 -1
  102. package/dist/types/src/shared/seedSchema/ConfigSchema.d.ts.map +1 -0
  103. package/dist/types/src/{browser/db → shared}/seedSchema/MetadataSchema.d.ts.map +1 -1
  104. package/dist/types/src/shared/{sdkSchema/modelSchema.d.ts → seedSchema/ModelSchema.d.ts} +1 -1
  105. package/dist/types/src/shared/seedSchema/ModelSchema.d.ts.map +1 -0
  106. package/dist/types/src/shared/{sdkSchema/modelUidSchema.d.ts → seedSchema/ModelUidSchema.d.ts} +1 -1
  107. package/dist/types/src/shared/seedSchema/ModelUidSchema.d.ts.map +1 -0
  108. package/dist/types/src/shared/{sdkSchema/propertyUidSchema.d.ts → seedSchema/PropertyUidSchema.d.ts} +1 -1
  109. package/dist/types/src/shared/seedSchema/PropertyUidSchema.d.ts.map +1 -0
  110. package/dist/types/src/shared/seedSchema/SeedSchema.d.ts.map +1 -0
  111. package/dist/types/src/shared/seedSchema/VersionSchema.d.ts.map +1 -0
  112. package/dist/types/src/shared/seedSchema/index.d.ts +9 -0
  113. package/dist/types/src/shared/seedSchema/index.d.ts.map +1 -0
  114. package/dist/types/src/types/item.d.ts +2 -2
  115. package/dist/types/src/types/item.d.ts.map +1 -1
  116. package/dist/types/src/types/machines.d.ts +45 -2
  117. package/dist/types/src/types/machines.d.ts.map +1 -1
  118. package/dist/types/src/types/services.d.ts +1 -0
  119. package/dist/types/src/types/services.d.ts.map +1 -0
  120. package/package.json +42 -42
  121. package/dist/browser/db/seedSchema/index.ts +0 -4
  122. package/dist/events-So24__c6.js.map +0 -1
  123. package/dist/index-Cgo0-c0n.js.map +0 -1
  124. package/dist/seed-BgRaREFr.js.map +0 -1
  125. package/dist/seed-CFk2xaH7.js.map +0 -1
  126. package/dist/seed-DGCfCUOn.js.map +0 -1
  127. package/dist/seed.schema.config-DYkIbj49.js.map +0 -1
  128. package/dist/shared/configs/sdk.db.config.ts +0 -33
  129. package/dist/shared/sdkSchema/index.ts +0 -4
  130. package/dist/types/src/browser/db/seedSchema/AppStateSchema.d.ts.map +0 -1
  131. package/dist/types/src/browser/db/seedSchema/SeedSchema.d.ts.map +0 -1
  132. package/dist/types/src/browser/db/seedSchema/VersionSchema.d.ts.map +0 -1
  133. package/dist/types/src/browser/db/seedSchema/index.d.ts +0 -5
  134. package/dist/types/src/browser/db/seedSchema/index.d.ts.map +0 -1
  135. package/dist/types/src/browser/events/item/delete.d.ts +0 -2
  136. package/dist/types/src/browser/events/item/delete.d.ts.map +0 -1
  137. package/dist/types/src/browser/services/db/actors.d.ts +0 -12
  138. package/dist/types/src/browser/services/db/actors.d.ts.map +0 -1
  139. package/dist/types/src/browser/services/db/machine.d.ts +0 -3
  140. package/dist/types/src/browser/services/db/machine.d.ts.map +0 -1
  141. package/dist/types/src/browser/services/global/actors.d.ts +0 -4
  142. package/dist/types/src/browser/services/global/actors.d.ts.map +0 -1
  143. package/dist/types/src/browser/services/internal/actors/loadSdkDb.d.ts +0 -2
  144. package/dist/types/src/browser/services/internal/actors/loadSdkDb.d.ts.map +0 -1
  145. package/dist/types/src/browser/services/internal/actors/loadSeedDb.d.ts +0 -2
  146. package/dist/types/src/browser/services/internal/actors/loadSeedDb.d.ts.map +0 -1
  147. package/dist/types/src/node/db/helpers.d.ts +0 -2
  148. package/dist/types/src/node/db/helpers.d.ts.map +0 -1
  149. package/dist/types/src/node/db/internal.d.ts +0 -5
  150. package/dist/types/src/node/db/internal.d.ts.map +0 -1
  151. package/dist/types/src/shared/configs/sdk.db.config.d.ts +0 -3
  152. package/dist/types/src/shared/configs/sdk.db.config.d.ts.map +0 -1
  153. package/dist/types/src/shared/sdkSchema/configSchema.d.ts.map +0 -1
  154. package/dist/types/src/shared/sdkSchema/index.d.ts +0 -5
  155. package/dist/types/src/shared/sdkSchema/index.d.ts.map +0 -1
  156. package/dist/types/src/shared/sdkSchema/modelSchema.d.ts.map +0 -1
  157. package/dist/types/src/shared/sdkSchema/modelUidSchema.d.ts.map +0 -1
  158. package/dist/types/src/shared/sdkSchema/propertyUidSchema.d.ts.map +0 -1
  159. package/dist/types/src/sqlite.d.ts +0 -2
  160. package/dist/types/src/sqlite.d.ts.map +0 -1
  161. /package/dist/{browser/db → shared}/seedSchema/AppStateSchema.ts +0 -0
  162. /package/dist/shared/{sdkSchema/configSchema.ts → seedSchema/ConfigSchema.ts} +0 -0
  163. /package/dist/{browser/db → shared}/seedSchema/MetadataSchema.ts +0 -0
  164. /package/dist/shared/{sdkSchema/modelSchema.ts → seedSchema/ModelSchema.ts} +0 -0
  165. /package/dist/{browser/db → shared}/seedSchema/SeedSchema.ts +0 -0
  166. /package/dist/{browser/db → shared}/seedSchema/VersionSchema.ts +0 -0
  167. /package/dist/types/src/{browser/db → shared}/seedSchema/AppStateSchema.d.ts +0 -0
  168. /package/dist/types/src/{browser/db → shared}/seedSchema/MetadataSchema.d.ts +0 -0
  169. /package/dist/types/src/{browser/db → shared}/seedSchema/SeedSchema.d.ts +0 -0
  170. /package/dist/types/src/{browser/db → shared}/seedSchema/VersionSchema.d.ts +0 -0
@@ -1,30 +1,31 @@
1
+ import { _ as __awaiter, d as __rest, i as internalPropertyNames, I as INTERNAL_DATA_TYPES } from './constants-KW2RTtZB.js';
2
+ import path, { basename } from 'path';
3
+ import 'reflect-metadata';
4
+ import { Type } from '@sinclair/typebox';
1
5
  import { fromCallback, setup, assign, createActor, waitFor, emit } from 'xstate';
2
- import { createBrowserInspector } from '@statelyai/inspect';
6
+ import { sql, relations, and, eq, max, or, count, isNull } from 'drizzle-orm';
3
7
  import { fs, configureSingle } from '@zenfs/core';
4
- import { sql, count, max, eq, and, or, isNull, relations } from 'drizzle-orm';
5
- import { drizzle } from 'drizzle-orm/sqlite-proxy';
8
+ import 'dayjs';
9
+ import { customAlphabet } from 'nanoid';
10
+ import * as nanoIdDictionary from 'nanoid-dictionary';
6
11
  import debug from 'debug';
12
+ import { startCase, debounce, camelCase, orderBy } from 'lodash-es';
13
+ import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
14
+ import EventEmitter from 'eventemitter3';
7
15
  import { QueryClient } from '@tanstack/react-query';
8
16
  import { GraphQLClient } from 'graphql-request';
9
17
  import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
10
18
  import { persistQueryClient } from '@tanstack/react-query-persist-client';
11
- import path, { basename } from 'path';
12
- import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
13
- import 'dayjs';
14
- import { customAlphabet } from 'nanoid';
15
- import * as nanoIdDictionary from 'nanoid-dictionary';
16
- import { WebAccess } from '@zenfs/dom';
17
- import Arweave from 'arweave';
18
- import { startCase, debounce, camelCase, orderBy } from 'lodash-es';
19
+ import { BehaviorSubject } from 'rxjs';
20
+ import { immerable, produce, enableMapSet } from 'immer';
19
21
  import pluralize from 'pluralize';
22
+ import Arweave from 'arweave';
20
23
  import { useState, useCallback, useEffect, useRef } from 'react';
21
- import { BehaviorSubject } from 'rxjs';
22
- import { immerable, produce } from 'immer';
23
24
  import { useImmer } from 'use-immer';
24
25
  import { useSelector } from '@xstate/react';
25
- import 'reflect-metadata';
26
- import { Type } from '@sinclair/typebox';
27
- import EventEmitter from 'eventemitter3';
26
+ import { createBrowserInspector } from '@statelyai/inspect';
27
+ import { drizzle } from 'drizzle-orm/sqlite-proxy';
28
+ import { WebAccess } from '@zenfs/dom';
28
29
 
29
30
  const isNode = () => {
30
31
  return (typeof process !== 'undefined' &&
@@ -38,686 +39,208 @@ const isReactNative = () => {
38
39
  return typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
39
40
  };
40
41
 
41
- /******************************************************************************
42
- Copyright (c) Microsoft Corporation.
43
-
44
- Permission to use, copy, modify, and/or distribute this software for any
45
- purpose with or without fee is hereby granted.
46
-
47
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
48
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
49
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
50
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
51
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
52
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
53
- PERFORMANCE OF THIS SOFTWARE.
54
- ***************************************************************************** */
55
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
56
-
57
-
58
- function __rest(s, e) {
59
- var t = {};
60
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
61
- t[p] = s[p];
62
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
63
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
64
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
65
- t[p[i]] = s[p[i]];
66
- }
67
- return t;
68
- }
69
-
70
- function __decorate(decorators, target, key, desc) {
71
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
72
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
73
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
74
- return c > 3 && r && Object.defineProperty(target, key, r), r;
75
- }
76
-
77
- function __metadata(metadataKey, metadataValue) {
78
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
79
- }
80
-
81
- function __awaiter(thisArg, _arguments, P, generator) {
82
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
83
- return new (P || (P = Promise))(function (resolve, reject) {
84
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
85
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
86
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
87
- step((generator = generator.apply(thisArg, _arguments || [])).next());
88
- });
89
- }
90
-
91
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
92
- var e = new Error(message);
93
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
42
+ const withSeed$1 = (config, webpack, isServer) => {
43
+ // If you need to include directories outside of the project root
44
+ // config.module.rules.push({
45
+ // test: /\.ts$/,
46
+ // include: [path.resolve(process.cwd(), 'schema.ts')],
47
+ // use: 'ts-loader',
48
+ // })
49
+ config.plugins.push(
50
+ // new webpack.DefinePlugin({
51
+ // __dirname: JSON.stringify(__dirname),
52
+ // }),
53
+ new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
54
+ resource.request = resource.request.replace(/^node:/, '');
55
+ }));
56
+ // config.externals.push({
57
+ // 'fsevents': 'commonjs2 fsevents',
58
+ // })
59
+ // console.log('__dirname:', __dirname)
60
+ // console.log('process.cwd():', process.cwd())
61
+ // console.log('crypto-browserify exists:', fs.existsSync(path.resolve(process.cwd(), './node_modules/crypto-browserify')))
62
+ // console.log('path-browserify exists:', fs.existsSync(path.resolve(process.cwd(), './node_modules/path-browserify')))
63
+ if (!isServer) {
64
+ console.log('config.resolve.alias:', config.resolve.alias);
65
+ config.resolve.alias['fs'] = path.resolve(process.cwd(), './node_modules/@zenfs/core');
66
+ config.resolve.alias['node:fs'] = path.resolve(process.cwd(), './node_modules/@zenfs/core');
67
+ config.resolve.alias['@schema'] = path.resolve(process.cwd(), 'schema.ts');
68
+ // config.resolve.alias['crypto'] = path.resolve(process.cwd(), './node_modules/crypto-browserify')
69
+ // config.resolve.alias['node:crypto'] = path.resolve(process.cwd(), './node_modules/crypto-browserify')
70
+ config.resolve.alias['node:path'] = path.resolve(process.cwd(), './node_modules/path-browserify');
71
+ config.resolve.alias['path'] = path.resolve(process.cwd(), './node_modules/path-browserify');
72
+ }
73
+ if (isServer) {
74
+ config.externals.push('@sqlite.org/sqlite-wasm');
75
+ config.externals.push('nunjucks');
76
+ config.externals.push('chokidar');
77
+ config.externals.push('arweave');
78
+ }
79
+ // config.module.rules.push({
80
+ // test: /seed\.config\.mjs$/,
81
+ // use: [
82
+ // {
83
+ // loader: 'babel-loader',
84
+ // options: {
85
+ // plugins: ['@babel/plugin-syntax-dynamic-import'],
86
+ // },
87
+ // },
88
+ // ],
89
+ // })
90
+ return config;
94
91
  };
95
92
 
96
- var MachineIds;
97
- (function (MachineIds) {
98
- MachineIds["GLOBAL"] = "@seedSdk/global";
99
- MachineIds["INTERNAL"] = "@seedSdk/internal";
100
- MachineIds["DB"] = "@seedSdk/db";
101
- MachineIds["EAS"] = "@seedSdk/eas";
102
- MachineIds["ITEM"] = "@seedSdk/item";
103
- MachineIds["ALL_ITEMS"] = "@seedSdk/allItems";
104
- MachineIds["MODEL"] = "@seedSdk/model";
105
- MachineIds["FILE_SYSTEM"] = "@seedSdk/fileSystem";
106
- })(MachineIds || (MachineIds = {}));
107
- const { INTERNAL, DB, GLOBAL, EAS, MODEL } = MachineIds;
108
- var GlobalState;
109
- (function (GlobalState) {
110
- GlobalState["UNINITIALIZED"] = "uninitialized";
111
- GlobalState["INITIALIZING"] = "initializing";
112
- GlobalState["INITIALIZED"] = "initialized";
113
- GlobalState["GETTING_SEED_CLASS"] = "gettingSeedClass";
114
- GlobalState["GETTING_SCHEMA_FOR_MODEL"] = "gettingSchemaForModel";
115
- GlobalState["GETTING_TABLE_FOR_MODEL"] = "gettingTableForModel";
116
- GlobalState["GETTING_MODEL_CLASS"] = "gettingModelClass";
117
- GlobalState["ADDING_MODELS_TO_DB"] = "addingModelsToDb";
118
- })(GlobalState || (GlobalState = {}));
119
- const { UNINITIALIZED: UNINITIALIZED$1, INITIALIZING: INITIALIZING$1, INITIALIZED: INITIALIZED$1, GETTING_SEED_CLASS: GETTING_SEED_CLASS$1, GETTING_SCHEMA_FOR_MODEL: GETTING_SCHEMA_FOR_MODEL$1, GETTING_TABLE_FOR_MODEL, GETTING_MODEL_CLASS, ADDING_MODELS_TO_DB: ADDING_MODELS_TO_DB$1, } = GlobalState;
120
- var InternalState;
121
- (function (InternalState) {
122
- InternalState["IDLE"] = "idle";
123
- InternalState["INITIALIZING"] = "initializing";
124
- InternalState["VALIDATING_INPUT"] = "validatingInput";
125
- InternalState["CONFIGURING_FS"] = "configuringFs";
126
- InternalState["LOADING_SEED_DB"] = "loadingSeedDb";
127
- InternalState["SAVING_CONFIG"] = "savingConfig";
128
- InternalState["LOADING_DBS"] = "loadingDbs";
129
- InternalState["LOADING_APP_DB"] = "loadingAppDb";
130
- InternalState["LOADING_SDK_DB"] = "loadingSdkDb";
131
- })(InternalState || (InternalState = {}));
132
- const { VALIDATING_INPUT: VALIDATING_INPUT$1, CONFIGURING_FS: CONFIGURING_FS$1, LOADING_SEED_DB: LOADING_SEED_DB$1, LOADING_APP_DB: LOADING_APP_DB$1, LOADING_SDK_DB: LOADING_SDK_DB$1, } = InternalState;
133
- var DbState;
134
- (function (DbState) {
135
- DbState["CHECKING_STATUS"] = "checkingStatus";
136
- DbState["WAITING_FOR_FILES"] = "waitingForFiles";
137
- DbState["VALIDATING"] = "validating";
138
- DbState["CONNECTING_TO_DB"] = "connectingToDb";
139
- // FETCHING_MIGRATIONS = 'fetchingMigrations',
140
- DbState["MIGRATING"] = "migrating";
141
- })(DbState || (DbState = {}));
142
- const { CHECKING_STATUS: CHECKING_STATUS$1, VALIDATING: VALIDATING$1, CONNECTING_TO_DB: CONNECTING_TO_DB$1, WAITING_FOR_FILES: WAITING_FOR_FILES$1, MIGRATING: MIGRATING$1, } = DbState;
143
- const INTERNAL_VALIDATING_INPUT_SUCCESS = `${INTERNAL}.${VALIDATING_INPUT$1}.success`;
144
- const INTERNAL_CONFIGURING_FS_SUCCESS = `${INTERNAL}.${CONFIGURING_FS$1}.success`;
145
- const INTERNAL_LOADING_SEED_DB_SUCCESS = `${INTERNAL}.${LOADING_SEED_DB$1}.success`;
146
- const INTERNAL_LOADING_APP_DB_SUCCESS = `${INTERNAL}.${LOADING_APP_DB$1}.success`;
147
- const INTERNAL_LOADING_SDK_DB_SUCCESS = `${INTERNAL}.${LOADING_SDK_DB$1}.success`;
148
- const INTERNAL_SAVING_CONFIG_SUCCESS = `${INTERNAL}.savingConfig.success`;
149
- const GLOBAL_INITIALIZING_SEND_CONFIG = `${GLOBAL}.${INITIALIZING$1}.sendConfig`;
150
- const GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY = `${GLOBAL}.${INITIALIZING$1}.internalServiceReady`;
151
- const GLOBAL_ADDING_MODELS_TO_DB_SUCCESS = `${GLOBAL}.${ADDING_MODELS_TO_DB$1}.success`;
152
- const DB_CHECK_STATUS_UPDATE_PATHS = `${DB}.${CHECKING_STATUS$1}.updatePaths`;
153
- const DB_CHECK_STATUS_EXISTS = `${DB}.${CHECKING_STATUS$1}.exists`;
154
- const DB_VALIDATING_SUCCESS = `${DB}.${VALIDATING$1}.success`;
155
- const DB_VALIDATING_WAIT = `${DB}.${VALIDATING$1}.wait`;
156
- const DB_MIGRATING_WAIT = `${DB}.${MIGRATING$1}.wait`;
157
- const DB_MIGRATING_SUCCESS = `${DB}.${MIGRATING$1}.success`;
158
- const DB_CREATING_SUCCESS = `${DB}.${CONNECTING_TO_DB$1}.success`;
159
- const DB_WAITING_FOR_FILES_RECEIVED = `${DB}.${WAITING_FOR_FILES$1}.filesReceived`;
160
- const DB_ON_SNAPSHOT = `${DB}.onSnapshot`;
161
- const CHILD_SNAPSHOT = 'childSnapshot';
162
- const DB_NAME_SEED = 'seed_db';
163
- const DB_NAME_APP = 'app_db';
164
- const DB_NAME_SDK_CONFIG = 'sdk_config_db';
165
- const DB_DIR_NAME_SEED = 'seed';
166
- const DB_DIR_NAME_APP = 'app';
167
- const DB_DIR_NAME_SDK = 'sdk';
168
- const BROWSER_FS_TOP_DIR = 'app-files';
169
- const EAS_ENDPOINT = process.env.NEXT_PUBLIC_EAS_ENDPOINT ||
170
- process.env.EAS_ENDPOINT ||
171
- 'https://optimism-sepolia.easscan.org/graphql';
172
- const ARWEAVE_HOST = process.env.NEXT_PUBLIC_ARWEAVE_HOST || 'permagate.io';
173
-
174
93
  let sqlite3InitModule;
175
- let sqliteWasmClient$1;
94
+ let sqliteWasmClient;
176
95
  let isPreparing = false;
177
-
178
- const getSqlite = async () => {
179
- if (sqliteWasmClient$1) {
180
- return sqliteWasmClient$1
181
- }
182
- if (typeof window === 'undefined') {
183
- throw new Error('validateInput called from non-browser context')
184
- }
185
-
186
- if (isPreparing) {
187
- return
188
- }
189
-
190
- isPreparing = true;
191
-
192
- if (!sqlite3InitModule) {
193
- sqlite3InitModule = await import('@sqlite.org/sqlite-wasm');
194
- }
195
-
196
- if (!window.sqlite3Worker1Promiser) {
197
- await sqlite3InitModule();
198
- }
199
-
200
- if (!window.sqlite3Worker1Promiser) {
201
- console.error('window.sqlite3Worker1Promiser not found');
202
- isPreparing = false;
203
- return
204
- }
205
-
206
- try {
207
- sqliteWasmClient$1 = await window.sqlite3Worker1Promiser.v2().catch((err) => {
208
- console.error('Error initializing sqliteWasmClient:', err);
209
- isPreparing = false;
210
- });
211
- } catch (err) {
212
- console.error('Error initializing sqliteWasmClient:', err);
213
- isPreparing = false;
214
- }
96
+ const getSqliteWasmClient = () => __awaiter(void 0, void 0, void 0, function* () {
97
+ if (sqliteWasmClient) {
98
+ return sqliteWasmClient;
99
+ }
100
+ if (typeof window === 'undefined') {
101
+ throw new Error('validateInput called from non-browser context');
102
+ }
103
+ if (isPreparing) {
104
+ return;
105
+ }
106
+ isPreparing = true;
107
+ if (!sqlite3InitModule) {
108
+ sqlite3InitModule = yield import('@sqlite.org/sqlite-wasm');
109
+ }
110
+ if (!window.sqlite3Worker1Promiser) {
111
+ yield sqlite3InitModule();
112
+ }
113
+ if (!window.sqlite3Worker1Promiser) {
114
+ console.error('window.sqlite3Worker1Promiser not found');
115
+ isPreparing = false;
116
+ return;
117
+ }
118
+ try {
119
+ sqliteWasmClient = yield window.sqlite3Worker1Promiser.v2().catch((err) => {
120
+ console.error('Error initializing sqliteWasmClient:', err);
121
+ isPreparing = false;
122
+ });
123
+ }
124
+ catch (err) {
125
+ console.error('Error initializing sqliteWasmClient:', err);
126
+ isPreparing = false;
127
+ }
128
+ return sqliteWasmClient;
129
+ });
130
+ let appDb;
131
+ const setAppDb = (db) => {
132
+ appDb = db;
133
+ };
134
+ const getAppDb = () => {
135
+ if (!appDb) {
136
+ throw new Error('getAppDb: appDb is undefined');
137
+ }
138
+ return appDb;
139
+ };
140
+ const isAppDbReady = () => {
141
+ return !!appDb;
215
142
  };
143
+ const runQueryForStatement = (statement) => __awaiter(void 0, void 0, void 0, function* () {
144
+ const appDb = getAppDb();
145
+ return appDb.run(sql.raw(statement));
146
+ });
216
147
 
217
- const logger$l = debug('app:db:actors');
218
- let seedDb;
219
- let appDb;
220
- let sdkConfigDb;
221
- let sqliteWasmClient;
222
- const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
223
- const { dbName, dirName } = context;
224
- logger$l('[db/actors] checkStatus context', context);
225
- const pathToDir = `${BROWSER_FS_TOP_DIR}/${dirName}`;
226
- const pathToDbDir = `${pathToDir}/db`;
227
- const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
228
- sendBack({
229
- type: DB_CHECK_STATUS_UPDATE_PATHS,
230
- pathToDb,
231
- pathToDir,
232
- pathToDbDir,
233
- });
234
- const _checkStatus = () => __awaiter(void 0, void 0, void 0, function* () {
235
- // logger('[db/actors] _checkStatus pathToDb', pathToDb)
236
- // const exists = await fs.promises.exists(pathToJournal)
237
- // if (exists) {
238
- // sendBack({
239
- // type: DB_CHECK_STATUS_EXISTS,
240
- // })
241
- // return
242
- // }
243
- //
244
- // return new Promise((resolve) => {
245
- // sendBack({ type: DB_CHECK_STATUS_DOES_NOT_EXIST })
246
- //
247
- // })
148
+ const waitForDb$1 = fromCallback(({ sendBack }) => {
149
+ const _waitForDb = new Promise((resolve) => {
150
+ const interval = setInterval(() => {
151
+ const appDb = getAppDb();
152
+ if (appDb) {
153
+ clearInterval(interval);
154
+ resolve();
155
+ }
156
+ }, 100);
248
157
  });
249
- _checkStatus().then(() => {
250
- sendBack({ type: DB_CHECK_STATUS_EXISTS });
251
- return;
158
+ _waitForDb.then(() => {
159
+ sendBack({ type: 'waitForDbSuccess' });
252
160
  });
253
161
  });
254
- const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
255
- logger$l('[db/actors] connectToDb context', context);
256
- const { dbName, pathToDir } = context;
257
- let isConnecting = false;
258
- let dbId;
259
- const _create = () => __awaiter(void 0, void 0, void 0, function* () {
260
- if (isConnecting) {
162
+
163
+ const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
164
+ const { isRelation, propertyName, storageTransactionId, seedLocalId } = context;
165
+ if (isRelation) {
166
+ sendBack({ type: 'isRelatedProperty' });
167
+ sendBack({ type: 'initializeSuccess' });
168
+ return;
169
+ }
170
+ if (!isRelation) {
171
+ if ((propertyName !== 'html' && propertyName !== 'json') ||
172
+ !storageTransactionId) {
173
+ sendBack({ type: 'initializeSuccess' });
261
174
  return;
262
175
  }
263
- isConnecting = true;
264
- let response;
265
- if (!sqliteWasmClient) {
266
- sqliteWasmClient = yield getSqlite();
267
- }
268
- //@ts-ignore
269
- response = yield sqliteWasmClient('config-get', {});
270
- logger$l(response);
271
- logger$l('Running SQLite3 version', response.result.version.libVersion);
272
- //@ts-ignore
273
- response = yield sqliteWasmClient('open', {
274
- filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
176
+ const _getContentsFromFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
177
+ if (propertyName === 'html') {
178
+ const renderValue = yield fs.promises
179
+ .readFile(`/files/html/${storageTransactionId}.html`, 'utf8')
180
+ .catch((error) => {
181
+ console.warn('Error reading html file', error);
182
+ });
183
+ sendBack({ type: 'updateRenderValue', renderValue });
184
+ return;
185
+ }
186
+ if (propertyName === 'json') {
187
+ const renderValue = yield fs.promises
188
+ .readFile(`/files/json/${storageTransactionId}.json`, 'utf8')
189
+ .catch((error) => {
190
+ console.warn('Error reading json file', error);
191
+ });
192
+ sendBack({ type: 'updateRenderValue', renderValue });
193
+ return;
194
+ }
275
195
  });
276
- logger$l(response);
277
- dbId = response.dbId;
278
- // logger(`dbId: ${dbId}`)
279
- logger$l('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
280
- });
281
- const interval = setInterval(() => {
282
- // TODO: Add a timeout
283
- // TODO: Add a cancel token to the promise so we can prevent more loops starting while we're checking the successful outcome
284
- if (dbId) {
285
- // logger(
286
- // '[db/actors] opening sqliteWasm connection with dbId:',
287
- // dbId,
288
- // )
289
- clearInterval(interval);
290
- sendBack({ type: DB_CREATING_SUCCESS, dbId });
291
- return;
292
- }
293
- _create()
294
- .then(() => {
295
- return;
296
- })
297
- .catch((e) => {
298
- isConnecting = false;
196
+ _getContentsFromFileSystem().then(() => {
197
+ sendBack({ type: 'initializeSuccess' });
299
198
  });
300
- }, 500);
301
- return () => {
302
- if (interval) {
303
- clearInterval(interval);
304
- }
305
- };
199
+ }
306
200
  });
307
- const validate = fromCallback(({ sendBack, input: { context } }) => {
308
- const { pathToDir, pathToDb } = context;
309
- const pathsToCheck = [
310
- pathToDir,
311
- `${pathToDir}/db`,
312
- `${pathToDir}/db/meta`,
313
- `${pathToDir}/db/meta/_journal.json`,
314
- ];
315
- const _validate = () => __awaiter(void 0, void 0, void 0, function* () {
316
- // If any of the necessary files don't exist, we wipe them all and recreate
317
- let exists = false;
318
- for (const path of pathsToCheck) {
319
- exists = yield fs.promises.exists(path);
320
- if (!exists) {
321
- sendBack({
322
- type: DB_VALIDATING_WAIT,
323
- });
324
- return false;
325
- }
326
- }
327
- return exists;
328
- });
329
- _validate().then(() => {
330
- sendBack({ type: DB_VALIDATING_SUCCESS, pathToDb, pathToDir });
201
+
202
+ const logger$n = debug('app:shared:helpers');
203
+ const { alphanumeric } = nanoIdDictionary;
204
+ const generateId = () => {
205
+ return customAlphabet(alphanumeric, 10)();
206
+ };
207
+ const toSnakeCase = (str) => {
208
+ return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
209
+ };
210
+ const identifyString = (str) => {
211
+ try {
212
+ JSON.parse(str);
213
+ return 'json';
214
+ }
215
+ catch (e) {
216
+ // Not JSON
217
+ }
218
+ if (!str) {
331
219
  return;
332
- });
333
- });
334
- const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void 0, [dbId_1, params_1, sql_1, dbName_1, ...args_1], void 0, function* (dbId, params, sql, dbName, retries = 2) {
335
- const rowsToReturnRaw = [];
336
- const sqliteWasmClient = yield getSqlite();
337
- // For a single exec command, the callback potentially gets called several times -- once for each row.
338
- // So we need to collect all rows into a final array to return (execResult).
339
- const rowsToReturn = yield new Promise((resolve, reject) => {
340
- sqliteWasmClient('exec', {
341
- dbId,
342
- sql,
343
- bind: params,
344
- callback: (result) => {
345
- // Checks if this is the final callback of the query
346
- if (!result || !result.row || !result.rowNumber) {
347
- const returnResult = [];
348
- // Before returning the array, we process it to match the expected output format
349
- // const rowsToReturnProcessed = rowsToReturnRaw.reduce((acc, curr) => {
350
- // if (
351
- // Array.isArray(curr.row) &&
352
- // curr.row?.length > 0 &&
353
- // curr.columnNames.length > 0
354
- // ) {
355
- // const returnObj: ReturnObj = {
356
- // database: dbName,
357
- // }
358
- //
359
- // const values = []
360
- //
361
- // curr.columnNames.forEach((colName, index: number) => {
362
- // if (curr.row && curr.row[index]) {
363
- // returnObj[colName] = curr.row[index]
364
- // values.push(curr.row[index])
365
- // }
366
- // })
367
- // // rowsValueStrings.push(`(${values.join(', ')})`)
368
- // acc.push(returnObj)
369
- // }
370
- // return acc
371
- // }, [] as string[])
372
- for (const currRow of rowsToReturnRaw) {
373
- // const values: string[] = []
374
- // currRow.columnNames.forEach((colName, index: number) => {
375
- // if (currRow.row) {
376
- // values.push(currRow.row[index])
377
- // }
378
- // })
379
- // logger(`[db/actors] [dbExec] currRow`, currRow)
380
- returnResult.push(currRow.row);
381
- }
382
- resolve(returnResult);
383
- }
384
- else {
385
- // If not the final response, add this row to the return array
386
- rowsToReturnRaw.push(result);
387
- }
388
- },
389
- }).catch((error) => __awaiter(void 0, void 0, void 0, function* () {
390
- reject(error);
391
- }));
392
- });
393
- // logger(`[db/actors] [dbExec] rowsToReturn`, rowsToReturn)
394
- // logger(`[db/actors] [dbExec] rowsValues`, rowsValues)
395
- return rowsToReturn || [];
396
- });
397
- const migrate = fromCallback(({ sendBack, input: { context } }) => {
398
- const { pathToDbDir, dirName, dbId, dbName } = context;
399
- logger$l('[db/actors] migrate context', context);
400
- const schemaGlobString = `${BROWSER_FS_TOP_DIR}/${dirName}/schema/*`;
401
- const isSeedDb = dbName === DB_NAME_SEED;
402
- const isAppDb = dbName === DB_NAME_APP;
403
- const isSdkConfigDb = dbName === DB_NAME_SDK_CONFIG;
404
- if (!sqliteWasmClient) {
405
- throw new Error('Sqlite wasm client not initialized');
406
220
  }
407
- let journalExists = false;
408
- // const _initFs = async (): Promise<void> => {
409
- // const handle = await navigator.storage.getDirectory()
410
- // // await configure({ backend: WebAccess, handle })
411
- // await configureSingle({
412
- // backend: WebAccess,
413
- // handle,
414
- // })
415
- // }
416
- //
417
- // _initFs()
418
- const _checkForFiles = () => __awaiter(void 0, void 0, void 0, function* () {
419
- const { fs } = yield import('@zenfs/core');
420
- journalExists = yield fs.promises.exists(`/${pathToDbDir}/meta/_journal.json`);
421
- if (!journalExists) {
422
- window.location.reload();
423
- // setTimeout(() => {
424
- // _checkForFiles().then(() => {
425
- // return
426
- // })
427
- // }, 500)
428
- }
429
- });
430
- const _migrate = () => __awaiter(void 0, void 0, void 0, function* () {
431
- const drizzleDb = drizzle((sql, params, method) => __awaiter(void 0, void 0, void 0, function* () {
432
- try {
433
- // logger(
434
- // `executing sql on ${dbName} with id: ${dbId} and method: ${method}`,
435
- // sql,
436
- // )
437
- const finalResult = yield dbExec(dbId, params, sql, dbName);
438
- // logger(`finalResult with method: ${method}`, finalResult)
439
- // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.
440
- // When the method is get, you should return a value as {rows: string[]}.
441
- // Otherwise, you should return {rows: string[][]}.
442
- return { rows: finalResult };
443
- }
444
- catch (e) {
445
- console.error('Error from sqlite proxy server: ', JSON.stringify(e));
446
- return { rows: [] };
447
- }
448
- }), {
449
- schema: schemaGlobString,
450
- // logger: true,
451
- });
452
- const { migrate: drizzleMigrate } = yield import('drizzle-orm/sqlite-proxy/migrator');
453
- const { readMigrationFiles } = yield import('drizzle-orm/migrator');
454
- try {
455
- const migrations = readMigrationFiles({
456
- migrationsFolder: pathToDbDir,
457
- });
458
- if (migrations.length > 0) {
459
- const incomingMigrationHashes = migrations.map((migration) => migration.hash);
460
- let existingMigrationHashes;
461
- let rows = [];
462
- try {
463
- const query = yield drizzleDb.run(sql.raw(`SELECT hash, created_at
464
- FROM main.__drizzle_migrations;`));
465
- rows = query.rows;
466
- }
467
- catch (e) {
468
- rows = [];
469
- }
470
- if (rows && rows.length > 0) {
471
- existingMigrationHashes = rows.map((row) => row[0]);
472
- }
473
- if (existingMigrationHashes) {
474
- let shouldRebuildDb = false;
475
- for (const existingHash of existingMigrationHashes) {
476
- if (!incomingMigrationHashes.includes(existingHash)) {
477
- shouldRebuildDb = true;
478
- break;
479
- }
480
- }
481
- if (shouldRebuildDb) {
482
- yield fs.promises.unlink(`${pathToDbDir}/${dbName}.sqlite3`);
483
- }
484
- }
485
- }
486
- yield drizzleMigrate(drizzleDb, (queriesToRun) => __awaiter(void 0, void 0, void 0, function* () {
487
- // logger('queriesToRun', queriesToRun)
488
- for (const query of queriesToRun) {
489
- // logger('query', query)
490
- yield drizzleDb.run(sql.raw(query));
491
- }
492
- }), {
493
- migrationsFolder: pathToDbDir,
494
- });
495
- }
496
- catch (error) {
497
- console.error('Error migrating database: ', error);
498
- window.location.reload();
499
- }
500
- // TODO: We're currently only using seedDb for appState ... should we drop it?
501
- // Or do we want to store Seeds and Versions separately from appDb and sdkConfigDb?
502
- if (isSeedDb) {
503
- seedDb = drizzleDb;
504
- }
505
- if (isAppDb) {
506
- appDb = drizzleDb;
507
- // const createTempTableQuery = await appDb.run(
508
- // sql.raw(
509
- // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,
510
- // ),
511
- // )
512
- //
513
- // logger(
514
- // '[db/actors] [migrate] createTempTableQuery',
515
- // createTempTableQuery,
516
- // )
517
- // const triggersQuery = await appDb.run(
518
- // sql.raw(
519
- // `SELECT name
520
- // FROM main.sqlite_master
521
- // WHERE type = 'trigger';`,
522
- // ),
523
- // )
524
- //
525
- // logger('[db/actors] [migrate] triggersQuery', triggersQuery)
526
- //
527
- // const triggers = triggersQuery.rows.map((row) => row[0])
528
- //
529
- // const tablesQuery = await appDb.run(
530
- // sql.raw(
531
- // `SELECT name
532
- // FROM main.sqlite_master
533
- // WHERE type = 'table';`,
534
- // ),
535
- // )
536
- //
537
- // logger('[db/actors] [migrate] tablesQuery', tablesQuery)
538
- //
539
- // const tableNames = tablesQuery.rows.map((row) => row[0])
540
- // logger('[db/actors] [migrate] tableNames', tableNames)
541
- // for (const tableName of tableNames) {
542
- // const triggerName = `after_insert_${tableName}`
543
- // if (triggers.includes(triggerName)) {
544
- // continue
545
- // }
546
- // const createTriggerQuery = await appDb.run(
547
- // sql.raw(
548
- // `CREATE TRIGGER after_insert_${tableName}
549
- // AFTER INSERT ON ${tableName}
550
- // BEGIN
551
- // DELETE FROM temp_last_inserted_id;
552
- // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);
553
- // END;`,
554
- // ),
555
- // )
556
- //
557
- // logger(
558
- // '[db/actors] [migrate] createTriggerQuery',
559
- // createTriggerQuery,
560
- // )
561
- // }
562
- }
563
- if (isSdkConfigDb) {
564
- sdkConfigDb = drizzleDb;
565
- }
566
- });
567
- _checkForFiles()
568
- .then(() => {
569
- if (((isSeedDb && !seedDb) ||
570
- (isAppDb && !appDb) ||
571
- (isSdkConfigDb && !sdkConfigDb)) &&
572
- journalExists) {
573
- return _migrate();
574
- }
575
- })
576
- .then(() => {
577
- sendBack({ type: DB_MIGRATING_SUCCESS, dbName });
578
- });
579
- return () => { };
580
- });
581
- const getDb = (dbName) => {
582
- if (dbName === DB_NAME_SEED && seedDb) {
583
- return seedDb;
221
+ if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
222
+ return 'html';
584
223
  }
585
- if (dbName === DB_NAME_APP && appDb) {
586
- return appDb;
224
+ // Simple markdown checks (very naive)
225
+ if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
226
+ return 'markdown';
587
227
  }
588
- if (dbName === DB_NAME_SDK_CONFIG && sdkConfigDb) {
589
- return sdkConfigDb;
228
+ if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
229
+ return 'base64';
590
230
  }
591
- return null;
231
+ // Default to plain text if unsure
232
+ return 'text';
592
233
  };
593
- const getAppDb = () => {
594
- const appDb = getDb(DB_NAME_APP);
595
- if (!appDb) {
596
- throw new Error('getAppDb: appDb is undefined');
234
+ const getMimeType = (base64) => {
235
+ if (!base64 || !Object.hasOwn(base64, 'match')) {
236
+ return null;
597
237
  }
598
- return appDb;
599
- };
600
- const getSdkDb = () => {
601
- const sdkDb = getDb(DB_NAME_SDK_CONFIG);
602
- if (!sdkDb) {
603
- throw new Error('getSdkDb: sdkDb is undefined');
604
- }
605
- return sdkDb;
606
- };
607
- // export const getDb = fromCallback<EventObject, typeof dbMachine>(
608
- // ({ sendBack, receive, input: { event } }) => {
609
- // const { dbName } = event
610
- //
611
- // const _getDb = async (): Promise<void> => {
612
- // const db = await drizzle(dbName)
613
- // sendBack({ type: 'returningDb', db })
614
- // }
615
- //
616
- // _getDb().then(() => {
617
- // return
618
- // })
619
- //
620
- // return () => {}
621
- // },
622
- // )
623
-
624
- const waitForDb$1 = fromCallback(({ sendBack }) => {
625
- const _waitForDb = new Promise((resolve) => {
626
- const interval = setInterval(() => {
627
- const appDb = getDb(DB_NAME_APP);
628
- const sdkConfigDb = getSdkDb();
629
- if (appDb || !sdkConfigDb) {
630
- clearInterval(interval);
631
- resolve();
632
- }
633
- }, 100);
634
- });
635
- _waitForDb.then(() => {
636
- sendBack({ type: 'waitForDbSuccess' });
637
- });
638
- });
639
-
640
- const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
641
- const { isRelation, propertyName, storageTransactionId, seedLocalId } = context;
642
- if (isRelation) {
643
- sendBack({ type: 'isRelatedProperty' });
644
- sendBack({ type: 'initializeSuccess' });
645
- return;
646
- }
647
- if (!isRelation) {
648
- if ((propertyName !== 'html' && propertyName !== 'json') ||
649
- !storageTransactionId) {
650
- sendBack({ type: 'initializeSuccess' });
651
- return;
652
- }
653
- const _getContentsFromFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
654
- if (propertyName === 'html') {
655
- const renderValue = yield fs.promises
656
- .readFile(`/files/html/${storageTransactionId}.html`, 'utf8')
657
- .catch((error) => {
658
- console.warn('Error reading html file', error);
659
- });
660
- sendBack({ type: 'updateRenderValue', renderValue });
661
- return;
662
- }
663
- if (propertyName === 'json') {
664
- const renderValue = yield fs.promises
665
- .readFile(`/files/json/${storageTransactionId}.json`, 'utf8')
666
- .catch((error) => {
667
- console.warn('Error reading json file', error);
668
- });
669
- sendBack({ type: 'updateRenderValue', renderValue });
670
- return;
671
- }
672
- });
673
- _getContentsFromFileSystem().then(() => {
674
- sendBack({ type: 'initializeSuccess' });
675
- });
676
- }
677
- });
678
-
679
- const logger$k = debug('app:shared:helpers');
680
- const { alphanumeric } = nanoIdDictionary;
681
- const generateId = () => {
682
- return customAlphabet(alphanumeric, 10)();
683
- };
684
- const toSnakeCase = (str) => {
685
- return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
686
- };
687
- const identifyString = (str) => {
688
- try {
689
- JSON.parse(str);
690
- return 'json';
691
- }
692
- catch (e) {
693
- // Not JSON
694
- }
695
- if (!str) {
696
- return;
697
- }
698
- if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
699
- return 'html';
700
- }
701
- // Simple markdown checks (very naive)
702
- if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
703
- return 'markdown';
704
- }
705
- if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
706
- return 'base64';
707
- }
708
- // Default to plain text if unsure
709
- return 'text';
710
- };
711
- const getMimeType = (base64) => {
712
- if (!base64 || !Object.hasOwn(base64, 'match')) {
713
- return null;
714
- }
715
- const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
716
- if (result && result.length > 1) {
717
- return result[1];
718
- }
719
- else {
720
- return null; // MIME type could not be determined
238
+ const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
239
+ if (result && result.length > 1) {
240
+ return result[1];
241
+ }
242
+ else {
243
+ return null; // MIME type could not be determined
721
244
  }
722
245
  };
723
246
  const getImageDataType = (data) => {
@@ -739,7 +262,7 @@ const convertTxIdToImageSrc = (txId) => __awaiter(void 0, void 0, void 0, functi
739
262
  const imageFilePath = `/files/images/${txId}`;
740
263
  const fileExists = yield fs.promises.exists(imageFilePath);
741
264
  if (!fileExists) {
742
- logger$k(`[ItemView] [updateImageSrc] ${imageFilePath} does not exist`);
265
+ logger$n(`[ItemView] [updateImageSrc] ${imageFilePath} does not exist`);
743
266
  return;
744
267
  }
745
268
  const uint = yield fs.promises.readFile(imageFilePath);
@@ -817,30 +340,70 @@ const appState = sqliteTable('appState', {
817
340
  updatedAt: int('updated_at'),
818
341
  });
819
342
 
820
- const getItemsData = (modelName) => __awaiter(void 0, void 0, void 0, function* () {
821
- const appDb = getAppDb();
822
- const itemsData = (yield appDb
823
- .select({
824
- seedLocalId: seeds.localId,
825
- seedUid: seeds.uid,
826
- schemaUid: seeds.schemaUid,
827
- modelName: sql `${modelName}`,
828
- attestationCreatedAt: seeds.attestationCreatedAt,
829
- versionsCount: count(versions.localId),
830
- lastVersionPublishedAt: max(versions.attestationCreatedAt),
831
- lastLocalUpdateAt: max(versions.createdAt),
832
- })
833
- .from(seeds)
834
- .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
835
- .where(and(eq(seeds.type, modelName.toLowerCase()), or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0))))
836
- .groupBy(seeds.localId));
837
- return itemsData;
343
+ sqliteTable('config', {
344
+ id: int('id').primaryKey({ autoIncrement: true }),
345
+ key: text('key').notNull(),
346
+ text: text('text'),
347
+ json: text('json', { mode: 'json' }),
348
+ blob: blob('blob', { mode: 'buffer' }),
349
+ }, () => {
350
+ return {
351
+ // Add a custom check constraint
352
+ atLeastOneNotNull: check('hasValue', sql `key IS NOT NULL OR text IS NOT NULL OR json IS NOT NULL OR blob IS NOT NULL`),
353
+ };
838
354
  });
839
355
 
840
- const runQueryForStatement = (statement) => __awaiter(void 0, void 0, void 0, function* () {
841
- const appDb = getAppDb();
842
- return appDb.run(sql.raw(statement));
356
+ const models = sqliteTable('models', {
357
+ id: int('id').primaryKey({ autoIncrement: true }),
358
+ name: text('name').notNull(),
359
+ });
360
+ relations(models, ({ many }) => ({
361
+ properties: many(properties),
362
+ }));
363
+ const properties = sqliteTable('properties', {
364
+ id: int('id').primaryKey({ autoIncrement: true }),
365
+ name: text('name').notNull(),
366
+ dataType: text('data_type').notNull(),
367
+ readEndpoint: text('read_endpoint'),
368
+ updateEndpoint: text('update_endpoint'),
369
+ modelId: int('model_id')
370
+ .notNull()
371
+ .references(() => models.id),
372
+ refModelId: int('ref_model_id').references(() => models.id),
373
+ refValueType: text('ref_value_type'),
374
+ }, (table) => {
375
+ return {
376
+ uniqueNameModelId: unique('unique_name_model_id').on(table.name, table.modelId),
377
+ };
378
+ });
379
+ relations(properties, ({ one }) => ({
380
+ model: one(models),
381
+ refModel: one(models),
382
+ }));
383
+
384
+ const modelUids = sqliteTable('model_uids', {
385
+ id: int('id').primaryKey({ autoIncrement: true }),
386
+ uid: text('uid').notNull(),
387
+ modelId: int('model_id')
388
+ .notNull()
389
+ .unique()
390
+ .references(() => models.id),
391
+ });
392
+ relations(modelUids, ({ many, one }) => ({
393
+ model: one(models),
394
+ }));
395
+
396
+ const propertyUids = sqliteTable('property_uids', {
397
+ id: int('id').primaryKey({ autoIncrement: true }),
398
+ uid: text('uid').notNull(),
399
+ propertyId: int('property_id')
400
+ .notNull()
401
+ .unique()
402
+ .references(() => models.id),
843
403
  });
404
+ relations(propertyUids, ({ one }) => ({
405
+ property: one(properties),
406
+ }));
844
407
 
845
408
  const getPropertyData = (propertyName, seedLocalId) => __awaiter(void 0, void 0, void 0, function* () {
846
409
  const query = `SELECT local_id,
@@ -1314,71 +877,6 @@ const resolveRemoteStorage = fromCallback(({ sendBack, input: { context } }) =>
1314
877
  });
1315
878
  });
1316
879
 
1317
- sqliteTable('config', {
1318
- id: int('id').primaryKey({ autoIncrement: true }),
1319
- key: text('key').notNull(),
1320
- text: text('text'),
1321
- json: text('json', { mode: 'json' }),
1322
- blob: blob('blob', { mode: 'buffer' }),
1323
- }, () => {
1324
- return {
1325
- // Add a custom check constraint
1326
- atLeastOneNotNull: check('hasValue', sql `key IS NOT NULL OR text IS NOT NULL OR json IS NOT NULL OR blob IS NOT NULL`),
1327
- };
1328
- });
1329
-
1330
- const models = sqliteTable('models', {
1331
- id: int('id').primaryKey({ autoIncrement: true }),
1332
- name: text('name').notNull(),
1333
- });
1334
- relations(models, ({ many }) => ({
1335
- properties: many(properties),
1336
- }));
1337
- const properties = sqliteTable('properties', {
1338
- id: int('id').primaryKey({ autoIncrement: true }),
1339
- name: text('name').notNull(),
1340
- dataType: text('data_type').notNull(),
1341
- readEndpoint: text('read_endpoint'),
1342
- updateEndpoint: text('update_endpoint'),
1343
- modelId: int('model_id')
1344
- .notNull()
1345
- .references(() => models.id),
1346
- refModelId: int('ref_model_id').references(() => models.id),
1347
- refValueType: text('ref_value_type'),
1348
- }, (table) => {
1349
- return {
1350
- uniqueNameModelId: unique('unique_name_model_id').on(table.name, table.modelId),
1351
- };
1352
- });
1353
- relations(properties, ({ one }) => ({
1354
- model: one(models),
1355
- refModel: one(models),
1356
- }));
1357
-
1358
- const modelUids = sqliteTable('model_uids', {
1359
- id: int('id').primaryKey({ autoIncrement: true }),
1360
- uid: text('uid').notNull(),
1361
- modelId: int('model_id')
1362
- .notNull()
1363
- .unique()
1364
- .references(() => models.id),
1365
- });
1366
- relations(modelUids, ({ many, one }) => ({
1367
- model: one(models),
1368
- }));
1369
-
1370
- const propertyUids = sqliteTable('property_uids', {
1371
- id: int('id').primaryKey({ autoIncrement: true }),
1372
- uid: text('uid').notNull(),
1373
- propertyId: int('property_id')
1374
- .notNull()
1375
- .unique()
1376
- .references(() => models.id),
1377
- });
1378
- relations(propertyUids, ({ one }) => ({
1379
- property: one(properties),
1380
- }));
1381
-
1382
880
  const writeAppState = (db, key, value) => __awaiter(void 0, void 0, void 0, function* () {
1383
881
  yield db
1384
882
  .insert(appState)
@@ -1400,109 +898,17 @@ const escapeSqliteString = (value) => {
1400
898
  }
1401
899
  return value.replace(/'/g, "''");
1402
900
  };
1403
- const createOrUpdate = (db, table, values) => __awaiter(void 0, void 0, void 0, function* () {
1404
- const startTime = Date.now();
1405
- const valueFilters = [];
1406
- const propertiesToExcludeFromDb = ['ref'];
1407
- const safeValues = Object.keys(values).reduce((acc, key) => {
1408
- if (!propertiesToExcludeFromDb.includes(key)) {
1409
- acc[key] = values[key];
1410
- }
1411
- return acc;
1412
- }, {});
1413
- for (const [key, value] of Object.entries(safeValues)) {
1414
- let finalValue = value;
1415
- if (key === 'TObject') {
1416
- continue;
1417
- }
1418
- if (typeof value === 'object') {
1419
- finalValue = JSON.stringify(value);
1420
- }
1421
- const column = table[key];
1422
- if (!column) {
1423
- throw new Error(`Column not found for ${key}`);
1424
- }
1425
- if (typeof finalValue === 'undefined') {
1426
- finalValue = null;
1427
- }
1428
- if (finalValue === null) {
1429
- valueFilters.push(isNull(table[key]));
1430
- continue;
1431
- }
1432
- valueFilters.push(eq(table[key], finalValue));
901
+ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
902
+ const appDb = getAppDb();
903
+ if (!appDb) {
904
+ return new Promise((resolve) => {
905
+ setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
906
+ const addresses = yield getAddressesFromDb();
907
+ resolve(addresses);
908
+ }), 500);
909
+ });
1433
910
  }
1434
- const doneWithFilters = Date.now();
1435
- // console.log('valueFilters:', valueFilters)
1436
- // for ( const filter of valueFilters ) {
1437
- // console.log('filter:', Object.keys(filter))
1438
- // }
1439
- // Build a query to find the record based on properties
1440
- const existingRecords = yield db
1441
- .select()
1442
- .from(table)
1443
- .where(and(...valueFilters));
1444
- const doneWithExistingRecords = Date.now();
1445
- if (existingRecords.length > 1) {
1446
- throw new Error('Multiple records found');
1447
- }
1448
- if (existingRecords.length > 0) {
1449
- // If record exists, update it
1450
- yield db
1451
- .update(table)
1452
- .set(safeValues)
1453
- .where(and(...valueFilters));
1454
- console.log('updatedRecord:', Object.assign(Object.assign({}, existingRecords[0]), safeValues));
1455
- const doneWithUpdate = Date.now();
1456
- console.log('[helpers/db] [createOrUpdate] filters duration:', doneWithFilters - startTime);
1457
- console.log('[helpers/db] [createOrUpdate] existingRecords duration:', doneWithExistingRecords - doneWithFilters);
1458
- console.log('[helpers/db] [createOrUpdate] update duration:', doneWithUpdate - doneWithExistingRecords);
1459
- return existingRecords[0];
1460
- }
1461
- else {
1462
- // If no record exists, create a new one
1463
- const newRecord = yield db.insert(table).values(safeValues).returning();
1464
- console.log('newRecord:', newRecord);
1465
- return newRecord[0];
1466
- }
1467
- });
1468
- const addModelsToInternalDb = (db, models$1) => __awaiter(void 0, void 0, void 0, function* () {
1469
- for (const [modelName, modelClass] of Object.entries(models$1)) {
1470
- console.log('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
1471
- const modelRecord = yield createOrUpdate(db, models, {
1472
- name: modelName,
1473
- });
1474
- for (let [propertyName, propertyValues] of Object.entries(modelClass.schema)) {
1475
- if (!propertyValues) {
1476
- throw new Error(`Property values not found for ${propertyName}`);
1477
- }
1478
- propertyValues.name = propertyName;
1479
- propertyValues.modelId = modelRecord.id;
1480
- for (let [key, value] of Object.entries(propertyValues)) {
1481
- if (key === 'ref') {
1482
- const refModel = yield createOrUpdate(db, models, {
1483
- name: value,
1484
- });
1485
- // delete propertyValues.ref
1486
- propertyValues.refModelId = refModel.id;
1487
- }
1488
- }
1489
- const propertyRecord = yield createOrUpdate(db, properties, propertyValues);
1490
- console.log('propertyRecord:', propertyRecord);
1491
- }
1492
- console.log('[helpers/db] [addModelsToInternalDb] done modelName:', modelName);
1493
- }
1494
- });
1495
- const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
1496
- const seedDb = getDb(DB_NAME_SEED);
1497
- if (!seedDb) {
1498
- return new Promise((resolve) => {
1499
- setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
1500
- const addresses = yield getAddressesFromDb();
1501
- resolve(addresses);
1502
- }), 500);
1503
- });
1504
- }
1505
- const appStatesRecords = yield seedDb
911
+ const appStatesRecords = yield appDb
1506
912
  .select()
1507
913
  .from(appState)
1508
914
  .where(eq(appState.key, 'addresses'))
@@ -1518,7 +924,7 @@ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* ()
1518
924
  return JSON.parse(addressArrayString);
1519
925
  });
1520
926
 
1521
- const logger$j = debug('app:property:actors:hydrateFromDb');
927
+ const logger$m = debug('app:property:actors:hydrateFromDb');
1522
928
  const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1523
929
  const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
1524
930
  let propertyName = propertyNameRaw;
@@ -1586,23 +992,23 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1586
992
  const firstRow = rows[0];
1587
993
  const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, refResolvedValue, refResolvedDisplayValue, } = firstRow;
1588
994
  if (propertyName && !propertyNameFromDb) {
1589
- logger$j(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
995
+ logger$m(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
1590
996
  }
1591
997
  if (propertyName &&
1592
998
  propertyNameFromDb &&
1593
999
  !propertyNameFromDb.includes(propertyName) &&
1594
1000
  !propertyName.includes(propertyNameFromDb) &&
1595
1001
  propertyNameFromDb !== propertyName) {
1596
- logger$j(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1002
+ logger$m(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1597
1003
  }
1598
1004
  if (propertyValue && propertyValueFromDb !== propertyValue) {
1599
- logger$j(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1005
+ logger$m(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1600
1006
  }
1601
1007
  if (seedLocalIdFromDb !== seedLocalId) {
1602
- logger$j(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1008
+ logger$m(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1603
1009
  }
1604
1010
  if (seedUidFromDb !== seedUid) {
1605
- logger$j(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1011
+ logger$m(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1606
1012
  }
1607
1013
  sendBack({
1608
1014
  type: 'updateContext',
@@ -1617,7 +1023,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1617
1023
  renderValue: refResolvedDisplayValue,
1618
1024
  });
1619
1025
  if (propertyNameFromDb === 'storageTransactionId') {
1620
- const { Item } = yield import('./index-Cgo0-c0n.js');
1026
+ const { Item } = yield import('./index-Ul8aVKpd.js');
1621
1027
  const item = yield Item.find({
1622
1028
  seedLocalId,
1623
1029
  modelName: itemModelName,
@@ -1635,7 +1041,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1635
1041
  const renderValue = yield fs.promises
1636
1042
  .readFile(htmlFilePath, 'utf8')
1637
1043
  .catch((error) => {
1638
- logger$j('Error reading html file', error);
1044
+ logger$m('Error reading html file', error);
1639
1045
  });
1640
1046
  property
1641
1047
  .getService()
@@ -1716,7 +1122,7 @@ const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seed
1716
1122
 
1717
1123
  const eventEmitter = new EventEmitter();
1718
1124
 
1719
- const logger$i = debug('app:write');
1125
+ const logger$l = debug('app:write');
1720
1126
  const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
1721
1127
  if (!modelName || (!seedLocalId && !seedUid)) {
1722
1128
  return;
@@ -1794,7 +1200,7 @@ const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoca
1794
1200
  });
1795
1201
  const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ propertyLocalId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, }) {
1796
1202
  if (!propertyLocalId && !seedLocalId) {
1797
- logger$i(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1203
+ logger$l(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1798
1204
  return;
1799
1205
  }
1800
1206
  let safeNewValue = newValue;
@@ -1833,7 +1239,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1833
1239
  const schemaUid = mostRecentRecord[9];
1834
1240
  const easDataType = mostRecentRecord[10];
1835
1241
  if (propertyValueFromDb === newValue) {
1836
- logger$i(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1242
+ logger$l(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1837
1243
  return;
1838
1244
  }
1839
1245
  // This means we already have a local-only record so we should just update that one
@@ -1929,6 +1335,76 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1929
1335
  sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
1930
1336
  });
1931
1337
 
1338
+ var MachineIds;
1339
+ (function (MachineIds) {
1340
+ MachineIds["GLOBAL"] = "@seedSdk/global";
1341
+ MachineIds["INTERNAL"] = "@seedSdk/internal";
1342
+ MachineIds["DB"] = "@seedSdk/db";
1343
+ MachineIds["EAS"] = "@seedSdk/eas";
1344
+ MachineIds["ITEM"] = "@seedSdk/item";
1345
+ MachineIds["ALL_ITEMS"] = "@seedSdk/allItems";
1346
+ MachineIds["MODEL"] = "@seedSdk/model";
1347
+ MachineIds["FILE_SYSTEM"] = "@seedSdk/fileSystem";
1348
+ })(MachineIds || (MachineIds = {}));
1349
+ const { INTERNAL, DB, GLOBAL, EAS, MODEL } = MachineIds;
1350
+ var GlobalState;
1351
+ (function (GlobalState) {
1352
+ GlobalState["UNINITIALIZED"] = "uninitialized";
1353
+ GlobalState["INITIALIZING"] = "initializing";
1354
+ GlobalState["INITIALIZED"] = "initialized";
1355
+ GlobalState["GETTING_SEED_CLASS"] = "gettingSeedClass";
1356
+ GlobalState["GETTING_SCHEMA_FOR_MODEL"] = "gettingSchemaForModel";
1357
+ GlobalState["GETTING_TABLE_FOR_MODEL"] = "gettingTableForModel";
1358
+ GlobalState["GETTING_MODEL_CLASS"] = "gettingModelClass";
1359
+ GlobalState["ADDING_MODELS_TO_DB"] = "addingModelsToDb";
1360
+ })(GlobalState || (GlobalState = {}));
1361
+ const { UNINITIALIZED: UNINITIALIZED$1, INITIALIZING: INITIALIZING$1, INITIALIZED: INITIALIZED$1, GETTING_SEED_CLASS: GETTING_SEED_CLASS$1, GETTING_SCHEMA_FOR_MODEL: GETTING_SCHEMA_FOR_MODEL$1, GETTING_TABLE_FOR_MODEL, GETTING_MODEL_CLASS, ADDING_MODELS_TO_DB: ADDING_MODELS_TO_DB$1, } = GlobalState;
1362
+ var InternalState;
1363
+ (function (InternalState) {
1364
+ InternalState["IDLE"] = "idle";
1365
+ InternalState["INITIALIZING"] = "initializing";
1366
+ InternalState["VALIDATING_INPUT"] = "validatingInput";
1367
+ InternalState["CONFIGURING_FS"] = "configuringFs";
1368
+ InternalState["LOADING_SEED_DB"] = "loadingSeedDb";
1369
+ InternalState["SAVING_CONFIG"] = "savingConfig";
1370
+ InternalState["LOADING_APP_DB"] = "loadingAppDb";
1371
+ InternalState["LOADING_SDK_DB"] = "loadingSdkDb";
1372
+ })(InternalState || (InternalState = {}));
1373
+ const { VALIDATING_INPUT: VALIDATING_INPUT$1, CONFIGURING_FS: CONFIGURING_FS$1, LOADING_SEED_DB, LOADING_APP_DB: LOADING_APP_DB$1 } = InternalState;
1374
+ var DbState;
1375
+ (function (DbState) {
1376
+ DbState["CHECKING_STATUS"] = "checkingStatus";
1377
+ DbState["WAITING_FOR_FILES"] = "waitingForFiles";
1378
+ DbState["VALIDATING"] = "validating";
1379
+ DbState["CONNECTING_TO_DB"] = "connectingToDb";
1380
+ // FETCHING_MIGRATIONS = 'fetchingMigrations',
1381
+ DbState["MIGRATING"] = "migrating";
1382
+ })(DbState || (DbState = {}));
1383
+ const { CHECKING_STATUS: CHECKING_STATUS$1, VALIDATING: VALIDATING$1, CONNECTING_TO_DB: CONNECTING_TO_DB$1, WAITING_FOR_FILES: WAITING_FOR_FILES$1, MIGRATING: MIGRATING$1, } = DbState;
1384
+ const INTERNAL_VALIDATING_INPUT_SUCCESS = `${INTERNAL}.${VALIDATING_INPUT$1}.success`;
1385
+ const INTERNAL_CONFIGURING_FS_SUCCESS = `${INTERNAL}.${CONFIGURING_FS$1}.success`;
1386
+ const INTERNAL_LOADING_APP_DB_SUCCESS = `${INTERNAL}.${LOADING_APP_DB$1}.success`;
1387
+ const INTERNAL_SAVING_CONFIG_SUCCESS = `${INTERNAL}.savingConfig.success`;
1388
+ const GLOBAL_INITIALIZING_SEND_CONFIG = `${GLOBAL}.${INITIALIZING$1}.sendConfig`;
1389
+ const GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY = `${GLOBAL}.${INITIALIZING$1}.internalServiceReady`;
1390
+ const GLOBAL_ADDING_MODELS_TO_DB_SUCCESS = `${GLOBAL}.${ADDING_MODELS_TO_DB$1}.success`;
1391
+ const DB_CHECK_STATUS_UPDATE_PATHS = `${DB}.${CHECKING_STATUS$1}.updatePaths`;
1392
+ const DB_CHECK_STATUS_EXISTS = `${DB}.${CHECKING_STATUS$1}.exists`;
1393
+ const DB_VALIDATING_SUCCESS = `${DB}.${VALIDATING$1}.success`;
1394
+ const DB_VALIDATING_WAIT = `${DB}.${VALIDATING$1}.wait`;
1395
+ const DB_MIGRATING_WAIT = `${DB}.${MIGRATING$1}.wait`;
1396
+ const DB_MIGRATING_SUCCESS = `${DB}.${MIGRATING$1}.success`;
1397
+ const DB_CREATING_SUCCESS = `${DB}.${CONNECTING_TO_DB$1}.success`;
1398
+ const DB_WAITING_FOR_FILES_RECEIVED = `${DB}.${WAITING_FOR_FILES$1}.filesReceived`;
1399
+ const DB_ON_SNAPSHOT = `${DB}.onSnapshot`;
1400
+ const CHILD_SNAPSHOT = 'childSnapshot';
1401
+ const DB_NAME_APP = 'app_db';
1402
+ const BROWSER_FS_TOP_DIR = 'app-files';
1403
+ const EAS_ENDPOINT = process.env.NEXT_PUBLIC_EAS_ENDPOINT ||
1404
+ process.env.EAS_ENDPOINT ||
1405
+ 'https://optimism-sepolia.easscan.org/graphql';
1406
+ const ARWEAVE_HOST = process.env.NEXT_PUBLIC_ARWEAVE_HOST || 'permagate.io';
1407
+
1932
1408
  const queryClient = new QueryClient({
1933
1409
  defaultOptions: {
1934
1410
  queries: {
@@ -2190,49 +1666,6 @@ const propertyMachine = setup({
2190
1666
  // },
2191
1667
  });
2192
1668
 
2193
- const APP_DB_CONFIG = 'browser.app.db.config.ts';
2194
- const SDK_DB_CONFIG = 'sdk.db.config.ts';
2195
- const SEED_DB_CONFIG = 'browser.seed.db.config.ts';
2196
- const SCHEMA_NJK = 'schema.njk';
2197
- const SCHEMA_TS = 'schema.ts';
2198
- const INTERNAL_DATA_TYPES = {
2199
- Text: {
2200
- eas: 'string',
2201
- },
2202
- Number: {
2203
- eas: 'uint8',
2204
- },
2205
- ImageSrc: {
2206
- eas: 'string',
2207
- },
2208
- Relation: {
2209
- eas: 'bytes32',
2210
- },
2211
- List: {
2212
- eas: 'bytes32[]',
2213
- },
2214
- };
2215
- const internalPropertyNames = [
2216
- 'localId',
2217
- 'uid',
2218
- 'seedLocalId',
2219
- 'seedUid',
2220
- 'schemaUid',
2221
- 'attestationCreatedAt',
2222
- 'createdAt',
2223
- 'updatedAt',
2224
- 'versionsCount',
2225
- 'lastVersionPublishedAt',
2226
- 'versionLocalId',
2227
- 'lastLocalUpdateAt',
2228
- 'storageTransactionId',
2229
- 'versionUid',
2230
- 'refSeedType',
2231
- 'refValueType',
2232
- 'resolvedValue',
2233
- 'resolvedDisplayValue',
2234
- ];
2235
-
2236
1669
  const modelStore = new Map();
2237
1670
  const getModels = () => {
2238
1671
  return Object.fromEntries(modelStore);
@@ -2247,8 +1680,8 @@ const setModel = (modelName, model) => {
2247
1680
  modelStore.set(modelName, model);
2248
1681
  };
2249
1682
 
2250
- var _a$1;
2251
- const logger$h = debug('app:property:class');
1683
+ var _a$2;
1684
+ const logger$k = debug('app:property:class');
2252
1685
  const namesThatEndWithId = [];
2253
1686
  class ItemProperty {
2254
1687
  // private constructor(localIdOrUid) {
@@ -2256,7 +1689,7 @@ class ItemProperty {
2256
1689
  constructor({ propertyValue, seedUid, seedLocalId, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
2257
1690
  this._isRelation = false;
2258
1691
  this._isList = false;
2259
- this[_a$1] = true;
1692
+ this[_a$2] = true;
2260
1693
  const ModelClass = getModel(itemModelName);
2261
1694
  if (!ModelClass) {
2262
1695
  throw new Error(`Model ${itemModelName} not found`);
@@ -2296,7 +1729,7 @@ class ItemProperty {
2296
1729
  serviceInput.propertyValue = JSON.parse(propertyValue);
2297
1730
  }
2298
1731
  catch (e) {
2299
- logger$h('List property value is not JSON', e);
1732
+ logger$k('List property value is not JSON', e);
2300
1733
  }
2301
1734
  }
2302
1735
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -2358,7 +1791,7 @@ class ItemProperty {
2358
1791
  this._service.start();
2359
1792
  }
2360
1793
  _updateResponseListener(event) {
2361
- logger$h(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1794
+ logger$k(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
2362
1795
  }
2363
1796
  static create(props) {
2364
1797
  const { propertyName, seedLocalId, uid } = props;
@@ -2397,6 +1830,9 @@ class ItemProperty {
2397
1830
  }
2398
1831
  static find(_b) {
2399
1832
  return __awaiter(this, arguments, void 0, function* ({ propertyName, seedLocalId, }) {
1833
+ if (!seedLocalId || !propertyName) {
1834
+ return;
1835
+ }
2400
1836
  const cacheKey = ItemProperty.cacheKey(seedLocalId, propertyName);
2401
1837
  if (this.instanceCache.has(cacheKey)) {
2402
1838
  const { instance, refCount } = this.instanceCache.get(cacheKey);
@@ -2494,11 +1930,11 @@ class ItemProperty {
2494
1930
  }
2495
1931
  unload() {
2496
1932
  this._service.stop();
2497
- logger$h(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1933
+ logger$k(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
2498
1934
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
2499
1935
  }
2500
1936
  }
2501
- _a$1 = immerable;
1937
+ _a$2 = immerable;
2502
1938
  ItemProperty.instanceCache = new Map();
2503
1939
 
2504
1940
  const TPropertyDataType = Type.Union([
@@ -2562,7 +1998,7 @@ const List = (ref, reValueType) => PropertyConstructor(Property.List(ref, reValu
2562
1998
  const waitForDb = fromCallback(({ sendBack }) => {
2563
1999
  const _waitForDb = new Promise((resolve) => {
2564
2000
  const interval = setInterval(() => {
2565
- const appDb = getDb(DB_NAME_APP);
2001
+ const appDb = getAppDb();
2566
2002
  if (appDb) {
2567
2003
  clearInterval(interval);
2568
2004
  resolve();
@@ -3206,8 +2642,8 @@ const getRelatedSeedsAndVersions = () => __awaiter(void 0, void 0, void 0, funct
3206
2642
  });
3207
2643
  });
3208
2644
  const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, function* () {
3209
- const sdkConfigDb = getSdkDb();
3210
- const { modelSchemas, schemaStringToModelRecord, modelRecords } = yield getModelSchemas({ sdkConfigDb });
2645
+ const appDb = getAppDb();
2646
+ const { modelSchemas, schemaStringToModelRecord, modelRecords } = yield getModelSchemas({ sdkConfigDb: appDb });
3211
2647
  if (!modelSchemas ||
3212
2648
  !modelSchemas.schemas ||
3213
2649
  modelSchemas.schemas.length === 0) {
@@ -3220,7 +2656,7 @@ const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, f
3220
2656
  throw new Error(`Model not found for schema ${modelSchema.schema}`);
3221
2657
  }
3222
2658
  schemaUids.push(modelSchema.id);
3223
- yield sdkConfigDb
2659
+ yield appDb
3224
2660
  .insert(modelUids)
3225
2661
  .values({
3226
2662
  modelId: foundModel.id,
@@ -3228,7 +2664,7 @@ const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, f
3228
2664
  })
3229
2665
  .onConflictDoNothing();
3230
2666
  yield processPropertiesFoundInDb({
3231
- sdkConfigDb,
2667
+ sdkConfigDb: appDb,
3232
2668
  foundModel,
3233
2669
  });
3234
2670
  }
@@ -3696,6 +3132,26 @@ const itemMachineSingle = setup({
3696
3132
  },
3697
3133
  });
3698
3134
 
3135
+ const getItemsData = (modelName) => __awaiter(void 0, void 0, void 0, function* () {
3136
+ const appDb = getAppDb();
3137
+ const itemsData = (yield appDb
3138
+ .select({
3139
+ seedLocalId: seeds.localId,
3140
+ seedUid: seeds.uid,
3141
+ schemaUid: seeds.schemaUid,
3142
+ modelName: sql `${modelName}`,
3143
+ attestationCreatedAt: seeds.attestationCreatedAt,
3144
+ versionsCount: count(versions.localId),
3145
+ lastVersionPublishedAt: max(versions.attestationCreatedAt),
3146
+ lastLocalUpdateAt: max(versions.createdAt),
3147
+ })
3148
+ .from(seeds)
3149
+ .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
3150
+ .where(and(eq(seeds.type, modelName.toLowerCase()), or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0))))
3151
+ .groupBy(seeds.localId));
3152
+ return itemsData;
3153
+ });
3154
+
3699
3155
  const getPropertiesForSeed = (seedLocalId, seedUid) => __awaiter(void 0, void 0, void 0, function* () {
3700
3156
  if (seedLocalId && !seedUid) {
3701
3157
  const seedQueryStatement = `SELECT uid
@@ -3783,7 +3239,7 @@ const getPropertiesForSeed = (seedLocalId, seedUid) => __awaiter(void 0, void 0,
3783
3239
  return propertiesData;
3784
3240
  });
3785
3241
 
3786
- const logger$g = debug('app:db:queries:getItem');
3242
+ const logger$j = debug('app:db:queries:getItem');
3787
3243
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
3788
3244
  if (!seedLocalId && !seedUid) {
3789
3245
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -3791,7 +3247,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
3791
3247
  if (seedUid && !seedLocalId) {
3792
3248
  const seedData = yield getSeedData({ seedUid });
3793
3249
  if (!seedData) {
3794
- logger$g('[db/queries] [getItem] no seedData seedUid', seedUid);
3250
+ logger$j('[db/queries] [getItem] no seedData seedUid', seedUid);
3795
3251
  return;
3796
3252
  }
3797
3253
  seedLocalId = seedData.localId;
@@ -3846,10 +3302,10 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
3846
3302
  return initObj;
3847
3303
  });
3848
3304
 
3849
- var _a;
3305
+ var _a$1;
3850
3306
  class Item {
3851
3307
  constructor(initialValues) {
3852
- this[_a] = true;
3308
+ this[_a$1] = true;
3853
3309
  this._propertiesSubject = new BehaviorSubject({});
3854
3310
  this.subscribe = (callback) => {
3855
3311
  return this._service.subscribe((snapshot) => {
@@ -3962,6 +3418,9 @@ class Item {
3962
3418
  }
3963
3419
  static find(_b) {
3964
3420
  return __awaiter(this, arguments, void 0, function* ({ modelName, seedLocalId, seedUid, }) {
3421
+ if (!modelName || (!seedLocalId && !seedUid)) {
3422
+ return;
3423
+ }
3965
3424
  const itemData = yield getItemDataFromDb({
3966
3425
  modelName,
3967
3426
  seedLocalId,
@@ -4020,7 +3479,7 @@ class Item {
4020
3479
  this._service.stop();
4021
3480
  }
4022
3481
  }
4023
- _a = immerable;
3482
+ _a$1 = immerable;
4024
3483
  Item.instanceCache = new Map();
4025
3484
 
4026
3485
  const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
@@ -4034,9 +3493,9 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4034
3493
  let modelNameLowercase;
4035
3494
  let modelNamePlural;
4036
3495
  let queryVariables;
4037
- let sdkConfigDb;
3496
+ let appDb;
4038
3497
  const _initialize = () => __awaiter(void 0, void 0, void 0, function* () {
4039
- sdkConfigDb = getSdkDb();
3498
+ appDb = getAppDb();
4040
3499
  // const rows = await getItemsDataFromDb(modelName)
4041
3500
  //
4042
3501
  // if (rows && rows.length > 0) {
@@ -4086,7 +3545,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4086
3545
  if (!modelSchema.id) {
4087
3546
  throw new Error(`No schema ID found for schema ${JSON.stringify(modelSchema)}`);
4088
3547
  }
4089
- const foundModels = yield sdkConfigDb
3548
+ const foundModels = yield appDb
4090
3549
  .select({
4091
3550
  id: models.id,
4092
3551
  name: models.name,
@@ -4101,14 +3560,14 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4101
3560
  sendBack({ type: 'modelNotFound', modelName });
4102
3561
  return;
4103
3562
  }
4104
- yield sdkConfigDb
3563
+ yield appDb
4105
3564
  .insert(modelUids)
4106
3565
  .values({
4107
3566
  modelId: foundModel.id,
4108
3567
  uid: modelSchema.id,
4109
3568
  })
4110
3569
  .onConflictDoNothing();
4111
- const foundPropertiesDb = yield sdkConfigDb
3570
+ const foundPropertiesDb = yield appDb
4112
3571
  .select({
4113
3572
  id: properties.id,
4114
3573
  name: properties.name,
@@ -4158,7 +3617,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4158
3617
  // TODO: We should create the schema here?
4159
3618
  continue;
4160
3619
  }
4161
- yield sdkConfigDb
3620
+ yield appDb
4162
3621
  .insert(propertyUids)
4163
3622
  .values({
4164
3623
  propertyId: foundProperty.id,
@@ -4167,10 +3626,6 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4167
3626
  .onConflictDoNothing();
4168
3627
  }
4169
3628
  }
4170
- const seedDb = getDb(DB_NAME_SEED);
4171
- if (!seedDb) {
4172
- throw new Error('Seed DB not found');
4173
- }
4174
3629
  const addresses = yield getAddressesFromDb();
4175
3630
  queryVariables = {
4176
3631
  where: {
@@ -4219,7 +3674,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
4219
3674
  return () => { };
4220
3675
  });
4221
3676
 
4222
- const logger$f = debug('app:allItemsActors:fetchSeeds');
3677
+ const logger$i = debug('app:allItemsActors:fetchSeeds');
4223
3678
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4224
3679
  const { queryVariables, modelName } = context;
4225
3680
  if (!queryVariables) {
@@ -4229,7 +3684,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4229
3684
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
4230
3685
  const queryKey = [`getSeeds${modelName}`];
4231
3686
  const cachedResults = queryClient.getQueryData(queryKey);
4232
- logger$f(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
3687
+ logger$i(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4233
3688
  const results = yield queryClient.fetchQuery({
4234
3689
  queryKey,
4235
3690
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -4272,14 +3727,7 @@ const fetchVersions = fromCallback(({ sendBack, input: { context } }) => {
4272
3727
 
4273
3728
  const fetchRelatedItems = fromCallback(({ sendBack, input: { context } }) => {
4274
3729
  const { ModelClass, modelName } = context;
4275
- const sdkConfigDb = getSdkDb();
4276
- const seedDb = getDb(DB_NAME_SEED);
4277
- if (!sdkConfigDb) {
4278
- throw new Error('SDK DB not found');
4279
- }
4280
- if (!seedDb) {
4281
- throw new Error('Seed DB not found');
4282
- }
3730
+ const appDb = getAppDb();
4283
3731
  const relatedProperties = new Map();
4284
3732
  const relatedVersionsBySeedUid = new Map();
4285
3733
  const schemaUidsByModelName = new Map();
@@ -4296,7 +3744,7 @@ const fetchRelatedItems = fromCallback(({ sendBack, input: { context } }) => {
4296
3744
  const addresses = yield getAddressesFromDb();
4297
3745
  // Get the models they point to from sdkConfigDb
4298
3746
  for (const [propertyName, propertyDef] of relatedProperties.entries()) {
4299
- const relatedModelQuery = yield sdkConfigDb
3747
+ const relatedModelQuery = yield appDb
4300
3748
  .select({
4301
3749
  id: models.id,
4302
3750
  name: models.name,
@@ -4800,555 +4248,540 @@ const getArweave = () => {
4800
4248
  });
4801
4249
  };
4802
4250
 
4803
- const logger$e = debug('app:react:db');
4804
- const useDbsAreReady = () => {
4805
- const [dbsAreReady, setDbsAreReady] = useState(false);
4806
- const update = useCallback(() => {
4807
- if (dbsAreReady) {
4251
+ const initSeedSync = () => {
4252
+ if (isNode()) {
4253
+ return {
4254
+ Model,
4255
+ Property,
4256
+ ImageSrc,
4257
+ List,
4258
+ Text,
4259
+ Json,
4260
+ Relation,
4261
+ withSeed: withSeed$1,
4262
+ };
4263
+ }
4264
+ else {
4265
+ return {
4266
+ Model,
4267
+ Property,
4268
+ ImageSrc,
4269
+ Relation,
4270
+ Text,
4271
+ List,
4272
+ Json,
4273
+ };
4274
+ }
4275
+ };
4276
+
4277
+ const logger$h = debug('app:services:global:actors:initialize');
4278
+ const initialize = fromCallback(({ sendBack, input: { event, context } }) => {
4279
+ const { internalService, models, endpoints } = context;
4280
+ const { addresses } = event;
4281
+ let environment = 'browser';
4282
+ if (isNode()) {
4283
+ environment = 'node';
4284
+ }
4285
+ if (isReactNative()) {
4286
+ environment = 'react-native';
4287
+ }
4288
+ let internalSubscription;
4289
+ if (environment === 'browser' && models) {
4290
+ const _initFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
4808
4291
  return;
4809
- }
4810
- setDbsAreReady(true);
4811
- }, []);
4812
- useEffect(() => {
4813
- let globalSubscription;
4814
- let internalSubscription;
4815
- const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
4816
- const globalService = getGlobalService();
4817
- const internalService = globalService.getSnapshot().context.internalService;
4818
- if (!internalService) {
4819
- logger$e('[useDbsAreReady] [useEffect] no internalService');
4820
- globalSubscription = globalService.subscribe(({ context }) => {
4821
- if (!internalSubscription && context && context.internalService) {
4822
- globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
4823
- internalSubscription = context.internalService.subscribe((snapshot) => {
4824
- if (snapshot.value === 'ready') {
4825
- update();
4826
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4827
- }
4828
- });
4292
+ // return new Promise((resolve) => {
4293
+ // })
4294
+ });
4295
+ const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
4296
+ return new Promise((resolve) => {
4297
+ internalSubscription = internalService.subscribe((snapshot) => {
4298
+ logger$h('[sdk] [internal] snapshot', snapshot);
4299
+ if (snapshot.value === 'ready') {
4300
+ resolve();
4829
4301
  }
4830
4302
  });
4831
- return;
4832
- }
4833
- const currentState = internalService.getSnapshot().value;
4834
- if (currentState === 'ready') {
4835
- update();
4836
- return;
4837
- }
4838
- internalSubscription = internalService.subscribe((snapshot) => {
4839
- if (snapshot.value === 'ready') {
4840
- update();
4841
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4842
- }
4303
+ internalService.send({ type: 'init', endpoints, addresses });
4843
4304
  });
4844
4305
  });
4845
- _waitForDbs();
4846
- return () => {
4847
- if (globalSubscription) {
4848
- globalSubscription.unsubscribe();
4849
- }
4850
- if (internalSubscription) {
4851
- internalSubscription.unsubscribe();
4852
- }
4853
- };
4854
- }, []);
4855
- return {
4856
- dbsAreReady,
4306
+ _initFileSystem().then(() => {
4307
+ logger$h('[global/actors] File system initialized');
4308
+ });
4309
+ _initInternal().then(() => {
4310
+ logger$h('[global/actors] Internal initialized');
4311
+ sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
4312
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4313
+ });
4314
+ // _initEas().then(() => {
4315
+ // logger('EAS initialized')
4316
+ // })
4317
+ }
4318
+ sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment });
4319
+ return () => {
4320
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4857
4321
  };
4858
- };
4322
+ });
4859
4323
 
4860
- const logger$d = debug('app:react:services');
4861
- const finalStrings = ['idle', 'ready', 'done', 'success'];
4862
- const getServiceName = (service) => {
4863
- let name = 'actor';
4864
- if (service && service.uniqueKey) {
4865
- name = service.uniqueKey;
4324
+ const logger$g = debug('app:services:global:actors:getSchemaForModel');
4325
+ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
4326
+ const { modelName } = event;
4327
+ if (!modelName) {
4328
+ console.warn('No modelName found');
4329
+ return;
4866
4330
  }
4867
- if (service && !service.uniqueKey && service.logic && service.logic.config) {
4868
- name = getServiceUniqueKey(service);
4331
+ const { models } = context;
4332
+ if (!models) {
4333
+ console.warn('No models found');
4334
+ return;
4869
4335
  }
4870
- return name;
4871
- };
4872
- const getServiceValue = (service) => {
4873
- let value;
4874
- if (service && service.getSnapshot() && service.getSnapshot().value) {
4875
- value = service.getSnapshot().value;
4336
+ const model = Object.entries(models).find(([modelNameFromConfig]) => modelNameFromConfig === modelName);
4337
+ if (!model) {
4338
+ throw new Error(`Model ${modelName} not found`);
4876
4339
  }
4877
- if (getServiceName(service) === 'global') {
4878
- if (value &&
4879
- typeof value === 'object' &&
4880
- Object.keys(value).length > 0 &&
4881
- Object.keys(value)[0] === 'initialized') {
4882
- value = 'ready';
4340
+ logger$g('[service/actor] [getSchemaForModel] model:', model);
4341
+ sendBack({ type: 'schemaForModel', schema: model.schema });
4342
+ return () => { };
4343
+ });
4344
+
4345
+ const logger$f = debug('app:services:global:actors:addModelsToDb');
4346
+ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
4347
+ const { models: models$1 } = context;
4348
+ const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
4349
+ var _a;
4350
+ const appDb = getAppDb();
4351
+ if (!models$1) {
4352
+ return;
4883
4353
  }
4884
- }
4885
- return value;
4886
- };
4887
- const getServiceUniqueKey = (service) => {
4888
- if (!service || !service.logic || !service.logic.config) {
4889
- return;
4890
- }
4891
- const config = service.logic.config;
4892
- if (!config.id) {
4893
- return;
4894
- }
4895
- let uniqueKey = config.id;
4896
- if (config.id.includes('@seedSdk/')) {
4897
- uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
4898
- }
4899
- let snapshot;
4900
- try {
4901
- snapshot = service.getSnapshot();
4902
- }
4903
- catch (error) {
4904
- logger$d('Error:', error);
4905
- return uniqueKey;
4906
- }
4907
- if (snapshot) {
4908
- const context = snapshot.context;
4909
- if (context && context.dbName) {
4910
- uniqueKey = context.dbName;
4354
+ const { models: SeedModels } = yield import('./seed.schema.config-DZC8TNja.js');
4355
+ const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
4356
+ let hasModelsInDb = false;
4357
+ const schemaDefsByModelName = new Map();
4358
+ for (const [modelName, _] of Object.entries(allModels)) {
4359
+ logger$f('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
4360
+ let foundModel;
4361
+ const foundModelsQuery = yield appDb
4362
+ .select()
4363
+ .from(models)
4364
+ .where(eq(models.name, modelName));
4365
+ if (!foundModelsQuery || foundModelsQuery.length === 0) {
4366
+ yield appDb.insert(models).values({
4367
+ name: modelName,
4368
+ });
4369
+ logger$f('[global/actors] [addModelsToDb] inserted model:', modelName);
4370
+ const foundModels = yield appDb
4371
+ .select({
4372
+ id: models.id,
4373
+ name: models.name,
4374
+ uid: modelUids.uid,
4375
+ })
4376
+ .from(models)
4377
+ .leftJoin(modelUids, eq(models.id, modelUids.modelId))
4378
+ .where(eq(models.name, modelName))
4379
+ .limit(1);
4380
+ foundModel = foundModels[0];
4381
+ }
4382
+ if (foundModelsQuery && foundModelsQuery.length > 0) {
4383
+ foundModel = foundModelsQuery[0];
4384
+ }
4385
+ if (!foundModel) {
4386
+ hasModelsInDb = false;
4387
+ break;
4388
+ }
4389
+ schemaDefsByModelName.set(modelName, {
4390
+ dbId: foundModel.id,
4391
+ schemaDef: `bytes32 ${toSnakeCase(modelName)}`,
4392
+ });
4911
4393
  }
4912
- if (context && context.modelNamePlural) {
4913
- uniqueKey = context.modelNamePlural;
4394
+ if (!hasModelsInDb) {
4395
+ return false;
4914
4396
  }
4915
- if (context && context.modelName) {
4916
- uniqueKey = pluralize(context.modelName.toLowerCase());
4397
+ const schemaDefs = Array.from(schemaDefsByModelName.values()).map(({ schemaDef }) => schemaDef);
4398
+ const { schemas } = yield queryClient.fetchQuery({
4399
+ queryKey: [`getSchemasVersion`],
4400
+ queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
4401
+ return easClient.request(GET_SCHEMAS, {
4402
+ where: {
4403
+ schema: {
4404
+ in: schemaDefs,
4405
+ },
4406
+ },
4407
+ });
4408
+ }),
4409
+ });
4410
+ if (!schemas || schemas.length === 0) {
4411
+ throw new Error(`No schemas found`);
4917
4412
  }
4918
- }
4919
- return uniqueKey;
4920
- };
4921
- const useServices = () => {
4922
- const [actors, setActors] = useState([]);
4923
- const [percentComplete, setPercentComplete] = useState(5);
4924
- const actorsMap = new Map();
4925
- useEffect(() => {
4926
- const globalServiceListener = (event) => {
4927
- if (event && event.type === 'init') {
4928
- return;
4929
- }
4930
- if (event.actorRef &&
4931
- event.actorRef.logic &&
4932
- event.actorRef.logic.config) {
4933
- const uniqueKey = getServiceUniqueKey(event.actorRef);
4934
- if (!uniqueKey) {
4935
- return;
4936
- }
4937
- event.actorRef.uniqueKey = uniqueKey;
4938
- actorsMap.set(uniqueKey, event.actorRef);
4939
- let actorsArray = Array.from(actorsMap.values());
4940
- actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
4941
- setActors(produce(actors, (draft) => {
4942
- return actorsArray;
4943
- }));
4413
+ for (const schema of schemas) {
4414
+ const modelId = (_a = Array.from(schemaDefsByModelName.values()).find(({ schemaDef }) => schemaDef === schema.schema)) === null || _a === void 0 ? void 0 : _a.dbId;
4415
+ if (!modelId) {
4416
+ throw new Error(`No modelId found for schema ${schema.schema}`);
4944
4417
  }
4945
- };
4946
- eventEmitter.addListener('inspect.globalService', globalServiceListener);
4947
- return () => {
4948
- eventEmitter.removeListener('inspect.globalService', globalServiceListener);
4949
- };
4950
- }, []);
4951
- useEffect(() => {
4952
- const globalService = actors.find((actor) => getServiceName(actor) === 'global');
4953
- const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
4954
- if (!globalService || !internalService) {
4955
- return;
4956
- }
4957
- if (getServiceValue(globalService) === 'ready' &&
4958
- getServiceValue(internalService) === 'ready') {
4959
- const denominator = actors.length;
4960
- const finishedActors = actors.filter((actor) => {
4961
- const value = getServiceValue(actor);
4962
- return finalStrings.includes(value);
4963
- });
4964
- const numerator = finishedActors.length;
4965
- const percentComplete = (numerator / denominator) * 100;
4966
- setPercentComplete(percentComplete);
4418
+ yield appDb
4419
+ .insert(modelUids)
4420
+ .values({
4421
+ modelId,
4422
+ uid: schema.id,
4423
+ })
4424
+ .onConflictDoNothing();
4967
4425
  }
4968
- }, [actors]);
4969
- return {
4970
- services: actors,
4971
- percentComplete,
4972
- };
4973
- };
4974
- const useGlobalServiceStatus = () => {
4975
- const globalService = getGlobalService();
4976
- const status = useSelector(globalService, (snapshot) => {
4977
- return snapshot.value;
4978
4426
  });
4979
- const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
4980
- if (!snapshot) {
4981
- return;
4427
+ _addModelsToDb().then((hasModelsInDb) => {
4428
+ sendBack({ type: GLOBAL_ADDING_MODELS_TO_DB_SUCCESS });
4429
+ for (const [modelName, model] of Object.entries(models$1)) {
4430
+ const service = context[`${modelName}Service`];
4431
+ service.send({ type: 'modelsFound' });
4982
4432
  }
4983
- return snapshot.value;
4433
+ eventEmitter.emit('syncDbWithEas');
4434
+ return;
4984
4435
  });
4985
- useSelector(globalService, (snapshot) => {
4986
- return snapshot.context.internalService;
4436
+ return () => { };
4437
+ });
4438
+
4439
+ const logger$e = debug('app:services:db:actors:checkStatus');
4440
+ const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
4441
+ const { dbName } = context;
4442
+ logger$e('[db/actors] checkStatus context', context);
4443
+ const pathToDir = `${BROWSER_FS_TOP_DIR}`;
4444
+ const pathToDbDir = `${pathToDir}/db`;
4445
+ const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
4446
+ sendBack({
4447
+ type: DB_CHECK_STATUS_UPDATE_PATHS,
4448
+ pathToDb,
4449
+ pathToDir,
4450
+ pathToDbDir,
4987
4451
  });
4988
- return {
4989
- status,
4990
- internalStatus,
4991
- };
4992
- };
4452
+ const _checkStatus = () => __awaiter(void 0, void 0, void 0, function* () {
4453
+ // logger('[db/actors] _checkStatus pathToDb', pathToDb)
4454
+ // const exists = await fs.promises.exists(pathToJournal)
4455
+ // if (exists) {
4456
+ // sendBack({
4457
+ // type: DB_CHECK_STATUS_EXISTS,
4458
+ // })
4459
+ // return
4460
+ // }
4461
+ //
4462
+ // return new Promise((resolve) => {
4463
+ // sendBack({ type: DB_CHECK_STATUS_DOES_NOT_EXIST })
4464
+ //
4465
+ // })
4466
+ });
4467
+ _checkStatus().then(() => {
4468
+ sendBack({ type: DB_CHECK_STATUS_EXISTS });
4469
+ return;
4470
+ });
4471
+ });
4993
4472
 
4994
- const logger$c = debug('app:react:item');
4995
- const useItem = ({ modelName, seedLocalId, seedUid }) => {
4996
- const [item, setItem] = useImmer(undefined);
4997
- const [itemSubscription, setItemSubscription] = useState();
4998
- const { status, internalStatus } = useGlobalServiceStatus();
4999
- const isReadingDb = useRef(false);
5000
- const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5001
- const updateItem = useCallback((newItem) => {
5002
- setItem(() => newItem);
5003
- }, []);
5004
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5005
- if (isReadingDb.current ||
5006
- internalStatus !== 'ready' ||
5007
- (!seedUid && !seedLocalId)) {
4473
+ const logger$d = debug('app:services:db:actors:connectToDb');
4474
+ const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
4475
+ logger$d('[db/actors] connectToDb context', context);
4476
+ const { dbName, pathToDir } = context;
4477
+ let isConnecting = false;
4478
+ let dbId;
4479
+ const _create = () => __awaiter(void 0, void 0, void 0, function* () {
4480
+ if (isConnecting) {
5008
4481
  return;
5009
4482
  }
5010
- isReadingDb.current = true;
5011
- const foundItem = yield Item.find({
5012
- modelName,
5013
- seedLocalId,
5014
- seedUid,
4483
+ isConnecting = true;
4484
+ let response;
4485
+ const sqliteWasmClient = yield getSqliteWasmClient();
4486
+ //@ts-ignore
4487
+ response = yield sqliteWasmClient('config-get', {});
4488
+ logger$d(response);
4489
+ logger$d('Running SQLite3 version', response.result.version.libVersion);
4490
+ //@ts-ignore
4491
+ response = yield sqliteWasmClient('open', {
4492
+ filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
5015
4493
  });
5016
- if (!foundItem) {
5017
- logger$c('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
4494
+ logger$d(response);
4495
+ dbId = response.dbId;
4496
+ // logger(`dbId: ${dbId}`)
4497
+ logger$d('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
4498
+ });
4499
+ const interval = setInterval(() => {
4500
+ // TODO: Add a timeout
4501
+ // TODO: Add a cancel token to the promise so we can prevent more loops starting while we're checking the successful outcome
4502
+ if (dbId) {
4503
+ // logger(
4504
+ // '[db/actors] opening sqliteWasm connection with dbId:',
4505
+ // dbId,
4506
+ // )
4507
+ clearInterval(interval);
4508
+ sendBack({ type: DB_CREATING_SUCCESS, dbId });
5018
4509
  return;
5019
4510
  }
5020
- updateItem(foundItem);
5021
- isReadingDb.current = false;
5022
- }), [internalStatus]);
5023
- useEffect(() => {
5024
- if (internalStatus === 'ready') {
5025
- readFromDb();
5026
- }
5027
- }, [internalStatus, status]);
5028
- useEffect(() => {
5029
- if (item && !itemSubscription) {
5030
- const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
5031
- const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
5032
- if (!newItem) {
5033
- logger$c('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
5034
- return;
5035
- }
5036
- setItem(() => newItem);
5037
- }));
5038
- setItemSubscription(subscription);
5039
- }
5040
- return () => {
5041
- itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
5042
- };
5043
- }, [item, itemSubscription]);
5044
- useEffect(() => {
5045
- const seedId = seedUid || seedLocalId;
5046
- eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
5047
- return () => {
5048
- eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
5049
- };
5050
- }, []);
5051
- return {
5052
- item,
5053
- itemStatus,
5054
- };
5055
- };
5056
- const useItems = ({ modelName, options }) => {
5057
- const [items, setItems] = useImmer([]);
5058
- const [isReadingDb, setIsReadingDb] = useState(false);
5059
- const [isInitialized, setIsInitialized] = useState(false);
5060
- const { dbsAreReady } = useDbsAreReady();
5061
- const modelNameRef = useRef(modelName);
5062
- const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
5063
- if (!event ||
5064
- !event.modelName ||
5065
- event.modelName !== modelNameRef.current ||
5066
- isReadingDb) {
5067
- return;
5068
- }
5069
- setIsReadingDb(true);
5070
- const allItems = yield Item.all(modelNameRef.current);
5071
- setItems(() => allItems);
5072
- setIsReadingDb(false);
5073
- }), [modelName]);
5074
- useEffect(() => {
5075
- if (dbsAreReady && !isInitialized) {
5076
- const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
5077
- yield readFromDb({ modelName });
5078
- setIsInitialized(true);
5079
- });
5080
- _fetchItems();
5081
- }
5082
- }, [dbsAreReady, isInitialized]);
5083
- useEffect(() => {
5084
- eventEmitter.addListener('item.requestAll', readFromDb);
5085
- return () => {
5086
- eventEmitter.removeListener('item.requestAll');
5087
- };
5088
- }, []);
5089
- return {
5090
- items: orderBy(items, [
5091
- (item) => item.lastVersionPublishedAt ||
5092
- item.attestationCreatedAt ||
5093
- item.createdAt,
5094
- ], ['desc']).slice(0, 10),
5095
- isReadingDb,
5096
- isInitialized,
5097
- };
5098
- };
5099
- const useItemIsReady = () => {
5100
- const [itemListenersReady, setItemListenersReady] = useState(false);
5101
- const itemEventListenersHandler = useCallback((_) => {
5102
- setItemListenersReady(true);
5103
- }, []);
5104
- useEffect(() => {
5105
- const areReady = getAreItemEventHandlersReady();
5106
- if (areReady) {
5107
- itemEventListenersHandler(true);
5108
- }
5109
- eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
5110
- return () => {
5111
- eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
5112
- };
5113
- }, []);
5114
- return {
5115
- isReady: itemListenersReady,
5116
- };
5117
- };
5118
- const useCreateItem = (modelName) => {
5119
- const [isCreatingItem, setIsCreatingItem] = useState(false);
5120
- const { isReady } = useItemIsReady();
5121
- const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
5122
- if (!isReady) {
5123
- console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
5124
- return;
5125
- }
5126
- if (isCreatingItem) {
5127
- // TODO: should we setup a queue for this?
5128
- console.error(`[useCreateItem] [createItem] already creating item`, itemData);
5129
- return;
5130
- }
5131
- setIsCreatingItem(true);
5132
- const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
5133
- yield Item.find({ modelName, seedLocalId });
5134
- eventEmitter.emit('item.requestAll', { modelName });
5135
- setIsCreatingItem(false);
5136
- }), [isCreatingItem, isReady]);
5137
- return {
5138
- createItem,
5139
- isCreatingItem,
5140
- };
5141
- };
5142
- const useDeleteItem = () => {
5143
- const [isDeletingItem, setIsDeletingItem] = useState(false);
5144
- const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
5145
- if (!item) {
4511
+ _create()
4512
+ .then(() => {
5146
4513
  return;
4514
+ })
4515
+ .catch((e) => {
4516
+ isConnecting = false;
4517
+ });
4518
+ }, 500);
4519
+ return () => {
4520
+ if (interval) {
4521
+ clearInterval(interval);
5147
4522
  }
5148
- setIsDeletingItem(true);
5149
- const { modelName } = item.getService().getSnapshot().context;
5150
- yield deleteItem({ seedLocalId: item.seedLocalId });
5151
- eventEmitter.emit('item.requestAll', { modelName });
5152
- setIsDeletingItem(false);
5153
- }), [isDeletingItem]);
5154
- useEffect(() => { }, []);
5155
- return {
5156
- deleteItem: destroy,
5157
- isDeletingItem,
5158
4523
  };
5159
- };
4524
+ });
5160
4525
 
5161
- const logger$b = debug('app:react:property');
5162
- const useItemProperty = (propertyName, seedLocalId) => {
5163
- const [property, setProperty] = useImmer(undefined);
5164
- const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5165
- const [isInitialized, setIsInitialized] = useState(false);
5166
- const { dbsAreReady } = useDbsAreReady();
5167
- const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
5168
- if (!snapshot || !snapshot.context) {
5169
- return;
4526
+ const validate = fromCallback(({ sendBack, input: { context } }) => {
4527
+ const { pathToDir, pathToDb } = context;
4528
+ const pathsToCheck = [
4529
+ pathToDir,
4530
+ `${pathToDir}/db`,
4531
+ `${pathToDir}/db/meta`,
4532
+ `${pathToDir}/db/meta/_journal.json`,
4533
+ ];
4534
+ const _validate = () => __awaiter(void 0, void 0, void 0, function* () {
4535
+ // If any of the necessary files don't exist, we wipe them all and recreate
4536
+ let exists = false;
4537
+ for (const path of pathsToCheck) {
4538
+ exists = yield fs.promises.exists(path);
4539
+ if (!exists) {
4540
+ sendBack({
4541
+ type: DB_VALIDATING_WAIT,
4542
+ });
4543
+ return false;
4544
+ }
5170
4545
  }
5171
- return snapshot.context.renderValue || snapshot.context.propertyValue;
4546
+ return exists;
5172
4547
  });
5173
- const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5174
- useEffect(() => {
5175
- if (dbsAreReady && property && property.value !== value) {
5176
- readFromDb();
5177
- }
5178
- }, [dbsAreReady, property, value]);
5179
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5180
- if (!dbsAreReady && isReadingFromDb) {
5181
- return;
5182
- }
5183
- setIsReadingFromDb(true);
5184
- const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
5185
- setIsReadingFromDb(false);
5186
- if (!foundProperty) {
5187
- logger$b(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
5188
- return;
5189
- }
5190
- setProperty(() => foundProperty);
5191
- setIsInitialized(true);
5192
- }), [dbsAreReady, isReadingFromDb]);
5193
- useEffect(() => {
5194
- readFromDb();
5195
- }, []);
5196
- // TODO: How can we force a re-render when the property is updated?
5197
- // Right now, the value will trigger an update because it's using a selector
5198
- // and a change is pushed to the hook listener.
5199
- return {
5200
- property,
5201
- isInitialized,
5202
- isReadingFromDb,
5203
- value,
5204
- status,
5205
- };
5206
- };
5207
- const useItemProperties = (item) => {
5208
- const [propertyObj, setPropertyObj] = useImmer({});
5209
- useState(false);
5210
- const updatePropertyObj = useCallback((event) => {
5211
- if (!item) {
5212
- console.error('[XXXXXX] [updatePropertyObj] no item when expected');
5213
- return;
5214
- }
5215
- const { propertyName, propertyValue } = event;
5216
- if (!propertyName) {
5217
- return;
5218
- }
5219
- setPropertyObj((draft) => {
5220
- draft[propertyName] = propertyValue;
5221
- });
5222
- }, [item]);
5223
- useEffect(() => {
5224
- if (!item) {
5225
- return;
5226
- }
5227
- const eventKey = `item.${item.seedLocalId}.property.update`;
5228
- eventEmitter.addListener(eventKey, updatePropertyObj);
5229
- return () => {
5230
- eventEmitter.removeListener(eventKey, updatePropertyObj);
5231
- };
5232
- }, [item]);
5233
- return {
5234
- properties: propertyObj,
5235
- };
5236
- };
4548
+ _validate().then(() => {
4549
+ sendBack({ type: DB_VALIDATING_SUCCESS, pathToDb, pathToDir });
4550
+ return;
4551
+ });
4552
+ });
5237
4553
 
5238
- const logger$a = debug('app:global:actors');
5239
- const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
5240
- const { models: models$1 } = context;
5241
- const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
5242
- var _a;
5243
- const sdkConfigDb = getSdkDb();
5244
- if (!models$1) {
5245
- return;
5246
- }
5247
- const { models: SeedModels } = yield import('./seed.schema.config-DYkIbj49.js');
5248
- const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
5249
- let hasModelsInDb = false;
5250
- const schemaDefsByModelName = new Map();
5251
- for (const [modelName, _] of Object.entries(allModels)) {
5252
- logger$a('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
5253
- let foundModel;
5254
- const foundModelsQuery = yield sdkConfigDb
5255
- .select()
5256
- .from(models)
5257
- .where(eq(models.name, modelName));
5258
- if (!foundModelsQuery || foundModelsQuery.length === 0) {
5259
- yield sdkConfigDb.insert(models).values({
5260
- name: modelName,
5261
- });
5262
- logger$a('[global/actors] [addModelsToDb] inserted model:', modelName);
5263
- const foundModels = yield sdkConfigDb
5264
- .select({
5265
- id: models.id,
5266
- name: models.name,
5267
- uid: modelUids.uid,
5268
- })
5269
- .from(models)
5270
- .leftJoin(modelUids, eq(models.id, modelUids.modelId))
5271
- .where(eq(models.name, modelName))
5272
- .limit(1);
5273
- foundModel = foundModels[0];
4554
+ const logger$c = debug('app:services:db:actors:migrate');
4555
+ const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void 0, [dbId_1, params_1, sql_1, dbName_1, ...args_1], void 0, function* (dbId, params, sql, dbName, retries = 2) {
4556
+ const rowsToReturnRaw = [];
4557
+ const sqliteWasmClient = yield getSqliteWasmClient();
4558
+ // For a single exec command, the callback potentially gets called several times -- once for each row.
4559
+ // So we need to collect all rows into a final array to return (execResult).
4560
+ const rowsToReturn = yield new Promise((resolve, reject) => {
4561
+ sqliteWasmClient('exec', {
4562
+ dbId,
4563
+ sql,
4564
+ bind: params,
4565
+ callback: (result) => {
4566
+ // Checks if this is the final callback of the query
4567
+ if (!result || !result.row || !result.rowNumber) {
4568
+ const returnResult = [];
4569
+ // Before returning the array, we process it to match the expected output format
4570
+ // const rowsToReturnProcessed = rowsToReturnRaw.reduce((acc, curr) => {
4571
+ // if (
4572
+ // Array.isArray(curr.row) &&
4573
+ // curr.row?.length > 0 &&
4574
+ // curr.columnNames.length > 0
4575
+ // ) {
4576
+ // const returnObj: ReturnObj = {
4577
+ // database: dbName,
4578
+ // }
4579
+ //
4580
+ // const values = []
4581
+ //
4582
+ // curr.columnNames.forEach((colName, index: number) => {
4583
+ // if (curr.row && curr.row[index]) {
4584
+ // returnObj[colName] = curr.row[index]
4585
+ // values.push(curr.row[index])
4586
+ // }
4587
+ // })
4588
+ // // rowsValueStrings.push(`(${values.join(', ')})`)
4589
+ // acc.push(returnObj)
4590
+ // }
4591
+ // return acc
4592
+ // }, [] as string[])
4593
+ for (const currRow of rowsToReturnRaw) {
4594
+ // const values: string[] = []
4595
+ // currRow.columnNames.forEach((colName, index: number) => {
4596
+ // if (currRow.row) {
4597
+ // values.push(currRow.row[index])
4598
+ // }
4599
+ // })
4600
+ // logger(`[db/actors] [dbExec] currRow`, currRow)
4601
+ returnResult.push(currRow.row);
4602
+ }
4603
+ resolve(returnResult);
4604
+ }
4605
+ else {
4606
+ // If not the final response, add this row to the return array
4607
+ rowsToReturnRaw.push(result);
4608
+ }
4609
+ },
4610
+ }).catch((error) => __awaiter(void 0, void 0, void 0, function* () {
4611
+ reject(error);
4612
+ }));
4613
+ });
4614
+ // logger(`[db/actors] [dbExec] rowsToReturn`, rowsToReturn)
4615
+ // logger(`[db/actors] [dbExec] rowsValues`, rowsValues)
4616
+ return rowsToReturn || [];
4617
+ });
4618
+ const migrate = fromCallback(({ sendBack, input: { context } }) => {
4619
+ const { pathToDbDir, dirName, dbId, dbName } = context;
4620
+ logger$c('[db/actors] migrate context', context);
4621
+ const schemaGlobString = `${BROWSER_FS_TOP_DIR}/${dirName}/schema/*`;
4622
+ let journalExists = false;
4623
+ // const _initFs = async (): Promise<void> => {
4624
+ // const handle = await navigator.storage.getDirectory()
4625
+ // // await configure({ backend: WebAccess, handle })
4626
+ // await configureSingle({
4627
+ // backend: WebAccess,
4628
+ // handle,
4629
+ // })
4630
+ // }
4631
+ //
4632
+ // _initFs()
4633
+ const _checkForFiles = () => __awaiter(void 0, void 0, void 0, function* () {
4634
+ const { fs } = yield import('@zenfs/core');
4635
+ journalExists = yield fs.promises.exists(`/${pathToDbDir}/meta/_journal.json`);
4636
+ if (!journalExists) {
4637
+ window.location.reload();
4638
+ // setTimeout(() => {
4639
+ // _checkForFiles().then(() => {
4640
+ // return
4641
+ // })
4642
+ // }, 500)
4643
+ }
4644
+ });
4645
+ const _migrate = () => __awaiter(void 0, void 0, void 0, function* () {
4646
+ const drizzleDb = drizzle((sql, params, method) => __awaiter(void 0, void 0, void 0, function* () {
4647
+ try {
4648
+ // logger(
4649
+ // `executing sql on ${dbName} with id: ${dbId} and method: ${method}`,
4650
+ // sql,
4651
+ // )
4652
+ const finalResult = yield dbExec(dbId, params, sql, dbName);
4653
+ // logger(`finalResult with method: ${method}`, finalResult)
4654
+ // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.
4655
+ // When the method is get, you should return a value as {rows: string[]}.
4656
+ // Otherwise, you should return {rows: string[][]}.
4657
+ return { rows: finalResult };
5274
4658
  }
5275
- if (foundModelsQuery && foundModelsQuery.length > 0) {
5276
- foundModel = foundModelsQuery[0];
4659
+ catch (e) {
4660
+ console.error('Error from sqlite proxy server: ', JSON.stringify(e));
4661
+ return { rows: [] };
5277
4662
  }
5278
- if (!foundModel) {
5279
- hasModelsInDb = false;
5280
- break;
4663
+ }), {
4664
+ schema: schemaGlobString,
4665
+ // logger: true,
4666
+ });
4667
+ const { migrate: drizzleMigrate } = yield import('drizzle-orm/sqlite-proxy/migrator');
4668
+ const { readMigrationFiles } = yield import('drizzle-orm/migrator');
4669
+ try {
4670
+ const migrations = readMigrationFiles({
4671
+ migrationsFolder: pathToDbDir,
4672
+ });
4673
+ if (migrations.length > 0) {
4674
+ const incomingMigrationHashes = migrations.map((migration) => migration.hash);
4675
+ let existingMigrationHashes;
4676
+ let rows = [];
4677
+ try {
4678
+ const query = yield drizzleDb.run(sql.raw(`SELECT hash, created_at
4679
+ FROM main.__drizzle_migrations;`));
4680
+ rows = query.rows;
4681
+ }
4682
+ catch (e) {
4683
+ rows = [];
4684
+ }
4685
+ if (rows && rows.length > 0) {
4686
+ existingMigrationHashes = rows.map((row) => row[0]);
4687
+ }
4688
+ if (existingMigrationHashes) {
4689
+ let shouldRebuildDb = false;
4690
+ for (const existingHash of existingMigrationHashes) {
4691
+ if (!incomingMigrationHashes.includes(existingHash)) {
4692
+ shouldRebuildDb = true;
4693
+ break;
4694
+ }
4695
+ }
4696
+ if (shouldRebuildDb) {
4697
+ yield fs.promises.unlink(`${pathToDbDir}/${dbName}.sqlite3`);
4698
+ }
4699
+ }
5281
4700
  }
5282
- schemaDefsByModelName.set(modelName, {
5283
- dbId: foundModel.id,
5284
- schemaDef: `bytes32 ${toSnakeCase(modelName)}`,
4701
+ yield drizzleMigrate(drizzleDb, (queriesToRun) => __awaiter(void 0, void 0, void 0, function* () {
4702
+ // logger('queriesToRun', queriesToRun)
4703
+ for (const query of queriesToRun) {
4704
+ // logger('query', query)
4705
+ yield drizzleDb.run(sql.raw(query));
4706
+ }
4707
+ }), {
4708
+ migrationsFolder: pathToDbDir,
5285
4709
  });
5286
4710
  }
5287
- if (!hasModelsInDb) {
5288
- return false;
5289
- }
5290
- const schemaDefs = Array.from(schemaDefsByModelName.values()).map(({ schemaDef }) => schemaDef);
5291
- const { schemas } = yield queryClient.fetchQuery({
5292
- queryKey: [`getSchemasVersion`],
5293
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
5294
- return easClient.request(GET_SCHEMAS, {
5295
- where: {
5296
- schema: {
5297
- in: schemaDefs,
5298
- },
5299
- },
5300
- });
5301
- }),
5302
- });
5303
- if (!schemas || schemas.length === 0) {
5304
- throw new Error(`No schemas found`);
5305
- }
5306
- for (const schema of schemas) {
5307
- const modelId = (_a = Array.from(schemaDefsByModelName.values()).find(({ schemaDef }) => schemaDef === schema.schema)) === null || _a === void 0 ? void 0 : _a.dbId;
5308
- if (!modelId) {
5309
- throw new Error(`No modelId found for schema ${schema.schema}`);
5310
- }
5311
- yield sdkConfigDb
5312
- .insert(modelUids)
5313
- .values({
5314
- modelId,
5315
- uid: schema.id,
5316
- })
5317
- .onConflictDoNothing();
4711
+ catch (error) {
4712
+ console.error('Error migrating database: ', error);
4713
+ window.location.reload();
5318
4714
  }
4715
+ setAppDb(drizzleDb);
4716
+ // const createTempTableQuery = await appDb.run(
4717
+ // sql.raw(
4718
+ // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,
4719
+ // ),
4720
+ // )
4721
+ //
4722
+ // logger(
4723
+ // '[db/actors] [migrate] createTempTableQuery',
4724
+ // createTempTableQuery,
4725
+ // )
4726
+ // const triggersQuery = await appDb.run(
4727
+ // sql.raw(
4728
+ // `SELECT name
4729
+ // FROM main.sqlite_master
4730
+ // WHERE type = 'trigger';`,
4731
+ // ),
4732
+ // )
4733
+ //
4734
+ // logger('[db/actors] [migrate] triggersQuery', triggersQuery)
4735
+ //
4736
+ // const triggers = triggersQuery.rows.map((row) => row[0])
4737
+ //
4738
+ // const tablesQuery = await appDb.run(
4739
+ // sql.raw(
4740
+ // `SELECT name
4741
+ // FROM main.sqlite_master
4742
+ // WHERE type = 'table';`,
4743
+ // ),
4744
+ // )
4745
+ //
4746
+ // logger('[db/actors] [migrate] tablesQuery', tablesQuery)
4747
+ //
4748
+ // const tableNames = tablesQuery.rows.map((row) => row[0])
4749
+ // logger('[db/actors] [migrate] tableNames', tableNames)
4750
+ // for (const tableName of tableNames) {
4751
+ // const triggerName = `after_insert_${tableName}`
4752
+ // if (triggers.includes(triggerName)) {
4753
+ // continue
4754
+ // }
4755
+ // const createTriggerQuery = await appDb.run(
4756
+ // sql.raw(
4757
+ // `CREATE TRIGGER after_insert_${tableName}
4758
+ // AFTER INSERT ON ${tableName}
4759
+ // BEGIN
4760
+ // DELETE FROM temp_last_inserted_id;
4761
+ // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);
4762
+ // END;`,
4763
+ // ),
4764
+ // )
4765
+ //
4766
+ // logger(
4767
+ // '[db/actors] [migrate] createTriggerQuery',
4768
+ // createTriggerQuery,
4769
+ // )
4770
+ // }
5319
4771
  });
5320
- _addModelsToDb().then((hasModelsInDb) => {
5321
- sendBack({ type: GLOBAL_ADDING_MODELS_TO_DB_SUCCESS });
5322
- for (const [modelName, model] of Object.entries(models$1)) {
5323
- const service = context[`${modelName}Service`];
5324
- service.send({ type: 'modelsFound' });
4772
+ _checkForFiles()
4773
+ .then(() => {
4774
+ if (journalExists) {
4775
+ return _migrate();
5325
4776
  }
5326
- eventEmitter.emit('syncDbWithEas');
5327
- return;
4777
+ })
4778
+ .then(() => {
4779
+ sendBack({ type: DB_MIGRATING_SUCCESS, dbName });
5328
4780
  });
5329
4781
  return () => { };
5330
4782
  });
5331
- const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
5332
- const { modelName } = event;
5333
- if (!modelName) {
5334
- console.warn('No modelName found');
5335
- return;
5336
- }
5337
- const { models } = context;
5338
- if (!models) {
5339
- console.warn('No models found');
5340
- return;
5341
- }
5342
- const model = Object.entries(models).find(([modelNameFromConfig]) => modelNameFromConfig === modelName);
5343
- if (!model) {
5344
- throw new Error(`Model ${modelName} not found`);
5345
- }
5346
- logger$a('[service/actor] [getSchemaForModel] model:', model);
5347
- sendBack({ type: 'schemaForModel', schema: model.schema });
5348
- return () => { };
5349
- });
5350
4783
 
5351
- const logger$9 = debug('app:services:db:machine');
4784
+ const logger$b = debug('app:services:db:machine');
5352
4785
  const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
5353
4786
  const dbMachine = setup({
5354
4787
  types: {
@@ -5369,7 +4802,7 @@ const dbMachine = setup({
5369
4802
  [DB_WAITING_FOR_FILES_RECEIVED]: {
5370
4803
  actions: assign({
5371
4804
  hasFiles: ({ event }) => {
5372
- logger$9('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
4805
+ logger$b('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
5373
4806
  return true;
5374
4807
  },
5375
4808
  }),
@@ -5378,8 +4811,8 @@ const dbMachine = setup({
5378
4811
  target: `.${CHECKING_STATUS}`,
5379
4812
  actions: assign({
5380
4813
  hasFiles: ({ context, event }) => {
5381
- logger$9('[db/machine] updateHasFiles event:', event);
5382
- logger$9('[db/machine] updateHasFiles context:', context);
4814
+ logger$b('[db/machine] updateHasFiles event:', event);
4815
+ logger$b('[db/machine] updateHasFiles context:', context);
5383
4816
  return event.hasFiles;
5384
4817
  },
5385
4818
  }),
@@ -5572,13 +5005,13 @@ class SqliteConnectionManager {
5572
5005
  }
5573
5006
  }
5574
5007
 
5575
- const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
5008
+ const prepareDb = fromCallback(({ sendBack }) => {
5576
5009
  let sqliteWasmClient;
5577
5010
  const _prepareDb = () => __awaiter(void 0, void 0, void 0, function* () {
5578
5011
  if (typeof window === 'undefined') {
5579
5012
  return;
5580
5013
  }
5581
- sqliteWasmClient = yield getSqlite();
5014
+ sqliteWasmClient = yield getSqliteWasmClient();
5582
5015
  });
5583
5016
  const interval = setInterval(() => {
5584
5017
  // TODO: Add a timeout
@@ -5600,7 +5033,7 @@ const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
5600
5033
  };
5601
5034
  });
5602
5035
 
5603
- const logger$8 = debug('app:services:internal:helpers');
5036
+ const logger$a = debug('app:services:internal:helpers');
5604
5037
  /**
5605
5038
  * Recursively create directories if they don't exist.
5606
5039
  * @param {string} dirPath - The directory path to create.
@@ -5676,7 +5109,7 @@ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, f
5676
5109
  if (JSON.stringify(error).includes('File exists')) {
5677
5110
  yield fs.promises.readFile(localFilePath, 'utf-8');
5678
5111
  }
5679
- logger$8(`[Error] Failed to download file from ${url}:`, error);
5112
+ logger$a(`[Error] Failed to download file from ${url}:`, error);
5680
5113
  }
5681
5114
  busy = false;
5682
5115
  });
@@ -5714,17 +5147,31 @@ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePat
5714
5147
  const fileList = yield fetchDirectory(filePaths);
5715
5148
  yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
5716
5149
  yield confirmFilesExist(fileList);
5717
- logger$8('[syncDbFiles] Files synced!');
5150
+ logger$a('[syncDbFiles] Files synced!');
5718
5151
  });
5719
5152
 
5720
- const logger$7 = debug('app:files:download');
5153
+ const logger$9 = debug('app:files:download');
5721
5154
  const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
5722
5155
  yield syncDbFiles(endpoints);
5723
5156
  eventEmitter.emit('fs.downloadAll.success', { eventId });
5724
5157
  eventEmitter.emit('fs.downloadAllBinary.request', { endpoints });
5725
5158
  });
5726
5159
  const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, void 0, function* () {
5727
- const addresses = yield getAddressesFromDb();
5160
+ let addresses;
5161
+ if (isAppDbReady()) {
5162
+ addresses = yield getAddressesFromDb();
5163
+ }
5164
+ if (!isAppDbReady()) {
5165
+ const globalService = getGlobalService();
5166
+ const internalService = globalService.getSnapshot().context.internalService;
5167
+ if (internalService) {
5168
+ yield waitFor(internalService, (snapshot) => snapshot.value === 'ready');
5169
+ addresses = yield getAddressesFromDb();
5170
+ }
5171
+ }
5172
+ if (!addresses || addresses.length === 0) {
5173
+ return;
5174
+ }
5728
5175
  const { filesMetadata } = yield queryClient.fetchQuery({
5729
5176
  queryKey: ['getFilesMetadata', ...addresses],
5730
5177
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
@@ -5756,15 +5203,15 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5756
5203
  if (!(yield fs.promises.exists('/files/images'))) {
5757
5204
  yield fs.promises.mkdir('/files/images', { recursive: true });
5758
5205
  }
5759
- const seedDb = getDb(DB_NAME_SEED);
5760
- if (!seedDb) {
5206
+ const appDb = getAppDb();
5207
+ if (!appDb) {
5761
5208
  console.warn('[fetchAll/actors] [fetchAllBinaryData] seedDb not available');
5762
5209
  return [];
5763
5210
  }
5764
5211
  for (const fileMetadata of filesMetadata) {
5765
5212
  const json = JSON.parse(fileMetadata.decodedDataJson);
5766
5213
  const transactionId = json[0].value.value;
5767
- const excludedTransactionsQuery = yield seedDb
5214
+ const excludedTransactionsQuery = yield appDb
5768
5215
  .select()
5769
5216
  .from(appState)
5770
5217
  .where(eq(appState.key, 'excludedTransactions'));
@@ -5787,9 +5234,9 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5787
5234
  try {
5788
5235
  const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
5789
5236
  if (res.status !== 200) {
5790
- logger$7(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
5237
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
5791
5238
  excludedTransactions.add(transactionId);
5792
- yield writeAppState(seedDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
5239
+ yield writeAppState(appDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
5793
5240
  continue;
5794
5241
  }
5795
5242
  const dataString = yield arweave.transactions
@@ -5801,7 +5248,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5801
5248
  console.error(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`, error);
5802
5249
  });
5803
5250
  if (!dataString) {
5804
- logger$7(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
5251
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
5805
5252
  }
5806
5253
  let contentType = identifyString(dataString);
5807
5254
  if (contentType !== 'json' &&
@@ -5809,7 +5256,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5809
5256
  contentType !== 'html') {
5810
5257
  const possibleImageType = getImageDataType(dataString);
5811
5258
  if (!possibleImageType) {
5812
- logger$7(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
5259
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
5813
5260
  continue;
5814
5261
  }
5815
5262
  contentType = possibleImageType;
@@ -5872,7 +5319,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5872
5319
  }
5873
5320
  }
5874
5321
  catch (error) {
5875
- logger$7(error);
5322
+ logger$9(error);
5876
5323
  }
5877
5324
  }
5878
5325
  });
@@ -5918,15 +5365,14 @@ const isFsInitialized = () => {
5918
5365
  return isInitialized;
5919
5366
  };
5920
5367
 
5921
- const logger$6 = debug('app:internal:actors:configureFs');
5368
+ const logger$8 = debug('app:internal:actors:configureFs');
5922
5369
  const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5923
- const { endpoints, seedDbService, appDbService, sdkDbService } = context;
5924
- logger$6('[internal/actors] [configureFs] Configuring FS');
5925
- const services = [seedDbService, appDbService, sdkDbService];
5370
+ const { endpoints, appDbService } = context;
5371
+ logger$8('[internal/actors] [configureFs] Configuring FS');
5926
5372
  const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
5927
- logger$6('[internal/actors] [configureFs] calling _configureFs');
5928
- logger$6('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
5929
- logger$6('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
5373
+ logger$8('[internal/actors] [configureFs] calling _configureFs');
5374
+ logger$8('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
5375
+ logger$8('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
5930
5376
  yield waitForEvent({
5931
5377
  req: {
5932
5378
  eventLabel: 'fs.downloadAll.request',
@@ -5936,29 +5382,26 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5936
5382
  eventLabel: 'fs.downloadAll.success',
5937
5383
  },
5938
5384
  });
5939
- yield Promise.all(services.map((service) => __awaiter(void 0, void 0, void 0, function* () {
5940
- const { dirName } = service.getSnapshot().context;
5941
- const journalPath = `${BROWSER_FS_TOP_DIR}/${dirName}/db/meta/_journal.json`;
5942
- const journalExists = yield fs.promises.exists(journalPath);
5943
- if (journalExists) {
5944
- service.send({ type: DB_WAITING_FOR_FILES_RECEIVED });
5945
- }
5946
- // return new Promise<void>((resolve) => {
5947
- // const interval = setInterval(() => {
5948
- // journalExistsSync = fs.existsSync(journalPath)
5949
- // logger(
5950
- // '[internal/actors] [configureFs] journalExistsSync:',
5951
- // journalExistsSync,
5952
- // )
5953
- // if (journalExistsSync) {
5954
- // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
5955
- // clearInterval(interval)
5956
- // resolve()
5957
- // }
5958
- // }, 200)
5959
- // })
5960
- })));
5961
- logger$6('[internal/actors] [configureFs] fs configured!');
5385
+ const journalPath = `${BROWSER_FS_TOP_DIR}/db/meta/_journal.json`;
5386
+ const journalExists = yield fs.promises.exists(journalPath);
5387
+ if (journalExists) {
5388
+ appDbService.send({ type: DB_WAITING_FOR_FILES_RECEIVED });
5389
+ }
5390
+ // return new Promise<void>((resolve) => {
5391
+ // const interval = setInterval(() => {
5392
+ // journalExistsSync = fs.existsSync(journalPath)
5393
+ // logger(
5394
+ // '[internal/actors] [configureFs] journalExistsSync:',
5395
+ // journalExistsSync,
5396
+ // )
5397
+ // if (journalExistsSync) {
5398
+ // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
5399
+ // clearInterval(interval)
5400
+ // resolve()
5401
+ // }
5402
+ // }, 200)
5403
+ // })
5404
+ logger$8('[internal/actors] [configureFs] fs configured!');
5962
5405
  });
5963
5406
  // Some of our dependencies use fs sync functions, which don't work with
5964
5407
  // OPFS. ZenFS creates an async cache of all files so that the sync functions
@@ -5971,33 +5414,8 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5971
5414
  return () => { };
5972
5415
  });
5973
5416
 
5974
- const loadSeedDb = fromCallback(({ sendBack, input: { context } }) => {
5975
- const { seedDbService } = context;
5976
- if (seedDbService.getSnapshot().value === 'ready') {
5977
- sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5978
- return () => { };
5979
- }
5980
- let subscription;
5981
- const _loadSeedDb = () => __awaiter(void 0, void 0, void 0, function* () {
5982
- yield waitFor(seedDbService, (snapshot) => snapshot.value === 'ready');
5983
- subscription = seedDbService.subscribe({
5984
- next: (snapshot) => {
5985
- sendBack({ type: DB_ON_SNAPSHOT, dbName: DB_NAME_SEED, snapshot });
5986
- },
5987
- });
5988
- });
5989
- _loadSeedDb().then(() => {
5990
- sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5991
- });
5992
- return () => {
5993
- if (subscription) {
5994
- subscription.unsubscribe();
5995
- }
5996
- };
5997
- });
5998
-
5999
- const logger$5 = debug('app:services:internal:actors:saveConfig');
6000
- const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
5417
+ const logger$7 = debug('app:services:internal:actors:saveConfig');
5418
+ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
6001
5419
  if (typeof window === 'undefined') {
6002
5420
  console.error('seedInitBrowser called from non-browser context');
6003
5421
  sendBack({
@@ -6011,16 +5429,16 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
6011
5429
  }
6012
5430
  const _saveConfig = () => __awaiter(void 0, void 0, void 0, function* () {
6013
5431
  // logger('[sdk] [internal/actors] starting _saveConfig')
6014
- const seedDb = getDb(DB_NAME_SEED);
6015
- if (!seedDb) {
6016
- throw new Error('Seed DB not found');
5432
+ const appDb = getAppDb();
5433
+ if (!appDb) {
5434
+ throw new Error('App DB not found');
6017
5435
  }
6018
5436
  const endpointsValueString = JSON.stringify(endpoints);
6019
5437
  const addressesValueString = JSON.stringify(addresses);
6020
5438
  // TODO: Figure out how to define on conflict with multiple rows added
6021
5439
  try {
6022
5440
  // logger('[sdk] [internal/actors] Saving endpoints to db')
6023
- yield seedDb
5441
+ yield appDb
6024
5442
  .insert(appState)
6025
5443
  .values({
6026
5444
  key: 'endpoints',
@@ -6034,7 +5452,7 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
6034
5452
  setWhere: sql `key = 'endpoints'`,
6035
5453
  });
6036
5454
  // logger('[sdk] [internal/actors] Saving addresses to db')
6037
- yield seedDb
5455
+ yield appDb
6038
5456
  .insert(appState)
6039
5457
  .values({
6040
5458
  key: 'addresses',
@@ -6047,20 +5465,20 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
6047
5465
  },
6048
5466
  setWhere: sql `key = 'addresses'`,
6049
5467
  });
6050
- logger$5('[sdk] [internal/actors] Should be done saving');
5468
+ logger$7('[sdk] [internal/actors] Should be done saving');
6051
5469
  }
6052
5470
  catch (error) {
6053
5471
  console.error('Error saving config:', error);
6054
5472
  }
6055
5473
  });
6056
5474
  _saveConfig().then(() => {
6057
- logger$5('[sdk] [internal/actors] Successfully saved config');
5475
+ logger$7('[sdk] [internal/actors] Successfully saved config');
6058
5476
  return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
6059
5477
  });
6060
5478
  return () => { };
6061
5479
  });
6062
5480
 
6063
- const logger$4 = debug('app:services:internal:actors:loadAppDb');
5481
+ const logger$6 = debug('app:services:internal:actors:loadAppDb');
6064
5482
  const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
6065
5483
  const { appDbService } = context;
6066
5484
  let subscription;
@@ -6081,42 +5499,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
6081
5499
  });
6082
5500
  _loadAppDb().then(() => {
6083
5501
  sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
6084
- logger$4('[sdk] [internal/actors] Successfully loaded app DB');
6085
- });
6086
- return () => {
6087
- if (subscription) {
6088
- subscription.unsubscribe();
6089
- }
6090
- };
6091
- });
6092
-
6093
- const logger$3 = debug('app:internal:actors:loadSdkDb');
6094
- const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
6095
- const { sdkDbService } = context;
6096
- logger$3('[sdk] [internal/actors] Loading SDK DB');
6097
- let subscription;
6098
- const _loadSdkDb = () => __awaiter(void 0, void 0, void 0, function* () {
6099
- return new Promise((resolve) => {
6100
- if (sdkDbService.getSnapshot().value === 'ready') {
6101
- return resolve();
6102
- }
6103
- subscription = sdkDbService.subscribe({
6104
- next: (snapshot) => {
6105
- if (snapshot.value === 'ready') {
6106
- return resolve();
6107
- }
6108
- sendBack({
6109
- type: DB_ON_SNAPSHOT,
6110
- dbName: DB_NAME_SDK_CONFIG,
6111
- snapshot,
6112
- });
6113
- },
6114
- });
6115
- });
6116
- });
6117
- _loadSdkDb().then(() => {
6118
- sendBack({ type: INTERNAL_LOADING_SDK_DB_SUCCESS });
6119
- logger$3('[sdk] [internal/actors] Successfully loaded SDK DB');
5502
+ logger$6('[sdk] [internal/actors] Successfully loaded app DB');
6120
5503
  });
6121
5504
  return () => {
6122
5505
  if (subscription) {
@@ -6125,11 +5508,11 @@ const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
6125
5508
  };
6126
5509
  });
6127
5510
 
6128
- const logger$2 = debug('app:services:internal:machine');
5511
+ const logger$5 = debug('app:services:internal:machine');
6129
5512
  createBrowserInspector({
6130
5513
  autoStart: false,
6131
5514
  });
6132
- const { IDLE, VALIDATING_INPUT, SAVING_CONFIG, CONFIGURING_FS, LOADING_DBS, LOADING_SEED_DB, LOADING_APP_DB, LOADING_SDK_DB, } = InternalState;
5515
+ const { IDLE, VALIDATING_INPUT, SAVING_CONFIG, CONFIGURING_FS, LOADING_APP_DB, } = InternalState;
6133
5516
  // Create the state machine
6134
5517
  const internalMachine = setup({
6135
5518
  types: {
@@ -6140,10 +5523,8 @@ const internalMachine = setup({
6140
5523
  prepareDb,
6141
5524
  validateInput,
6142
5525
  configureFs,
6143
- loadSeedDb,
6144
- saveConfig,
6145
5526
  loadAppDb,
6146
- loadSdkDb,
5527
+ saveConfig,
6147
5528
  },
6148
5529
  }).createMachine({
6149
5530
  id: MachineIds.INTERNAL,
@@ -6158,27 +5539,10 @@ const internalMachine = setup({
6158
5539
  init: {
6159
5540
  target: VALIDATING_INPUT,
6160
5541
  actions: [
6161
- assign({
6162
- seedDbService: ({ spawn }) => spawn(dbMachine, {
6163
- input: {
6164
- dbName: DB_NAME_SEED,
6165
- dirName: DB_DIR_NAME_SEED,
6166
- },
6167
- }),
6168
- }),
6169
5542
  assign({
6170
5543
  appDbService: ({ spawn }) => spawn(dbMachine, {
6171
5544
  input: {
6172
5545
  dbName: DB_NAME_APP,
6173
- dirName: DB_DIR_NAME_APP,
6174
- },
6175
- }),
6176
- }),
6177
- assign({
6178
- sdkDbService: ({ spawn }) => spawn(dbMachine, {
6179
- input: {
6180
- dbName: DB_NAME_SDK_CONFIG,
6181
- dirName: DB_DIR_NAME_SDK,
6182
5546
  },
6183
5547
  }),
6184
5548
  }),
@@ -6224,7 +5588,7 @@ const internalMachine = setup({
6224
5588
  [CONFIGURING_FS]: {
6225
5589
  on: {
6226
5590
  [INTERNAL_CONFIGURING_FS_SUCCESS]: {
6227
- target: LOADING_SEED_DB,
5591
+ target: LOADING_APP_DB,
6228
5592
  actions: assign({ hasFiles: true }),
6229
5593
  },
6230
5594
  },
@@ -6238,32 +5602,24 @@ const internalMachine = setup({
6238
5602
  },
6239
5603
  tags: ['loading'],
6240
5604
  },
6241
- // We run this before the other DBs because it holds the config we need to
6242
- // rebuild. If we get interrupted after this then we don't have to start
6243
- // from scratch.
6244
- [LOADING_SEED_DB]: {
5605
+ [LOADING_APP_DB]: {
6245
5606
  on: {
6246
- [INTERNAL_LOADING_SEED_DB_SUCCESS]: SAVING_CONFIG,
6247
- // [DB_ON_SNAPSHOT]: {
6248
- // actions: emit(({ event: { snapshot } }) => {
6249
- // return { type: CHILD_SNAPSHOT, snapshot }
6250
- // }),
6251
- // },
5607
+ [INTERNAL_LOADING_APP_DB_SUCCESS]: {
5608
+ target: SAVING_CONFIG,
5609
+ actions: () => {
5610
+ logger$5('[sdk] [internal/index] App DB loaded!');
5611
+ },
5612
+ },
6252
5613
  },
6253
5614
  invoke: {
6254
- src: 'loadSeedDb',
5615
+ src: 'loadAppDb',
6255
5616
  input: ({ context, event }) => ({ context, event }),
6256
5617
  },
6257
- meta: {
6258
- displayText: 'Loading seed database',
6259
- percentComplete: 50,
6260
- },
6261
- tags: ['loading'],
6262
5618
  },
6263
5619
  // Save developer's config to DB
6264
5620
  [SAVING_CONFIG]: {
6265
5621
  on: {
6266
- [INTERNAL_SAVING_CONFIG_SUCCESS]: LOADING_DBS,
5622
+ [INTERNAL_SAVING_CONFIG_SUCCESS]: 'ready',
6267
5623
  },
6268
5624
  invoke: {
6269
5625
  src: 'saveConfig',
@@ -6275,77 +5631,9 @@ const internalMachine = setup({
6275
5631
  },
6276
5632
  tags: ['loading'],
6277
5633
  },
6278
- // The DBs can be loaded in parallel since they are independent of each other
6279
- [LOADING_DBS]: {
6280
- type: 'parallel',
6281
- states: {
6282
- [LOADING_APP_DB]: {
6283
- initial: 'loading',
6284
- states: {
6285
- loading: {
6286
- on: {
6287
- [INTERNAL_LOADING_APP_DB_SUCCESS]: {
6288
- target: 'appDbLoaded',
6289
- actions: () => {
6290
- logger$2('[sdk] [internal/index] App DB loaded!');
6291
- },
6292
- },
6293
- },
6294
- invoke: {
6295
- src: 'loadAppDb',
6296
- input: ({ context, event }) => ({ context, event }),
6297
- },
6298
- },
6299
- appDbLoaded: {
6300
- type: 'final',
6301
- entry: () => {
6302
- logger$2('[sdk] [internal/index] Entered appDbLoaded!');
6303
- },
6304
- },
6305
- },
6306
- },
6307
- [LOADING_SDK_DB]: {
6308
- initial: 'loading',
6309
- states: {
6310
- loading: {
6311
- on: {
6312
- [INTERNAL_LOADING_SDK_DB_SUCCESS]: {
6313
- target: 'sdkConfigDbLoaded',
6314
- actions: () => {
6315
- logger$2('[sdk] [internal/index] SDK Config DB loaded!');
6316
- },
6317
- },
6318
- },
6319
- invoke: {
6320
- src: 'loadSdkDb',
6321
- input: ({ context, event }) => ({ context, event }),
6322
- },
6323
- },
6324
- sdkConfigDbLoaded: {
6325
- type: 'final',
6326
- entry: () => {
6327
- logger$2('[sdk] [internal/index] Entered sdkConfigDbLoaded!');
6328
- },
6329
- },
6330
- },
6331
- },
6332
- },
6333
- onDone: {
6334
- target: 'ready',
6335
- actions: () => {
6336
- logger$2('[sdk] [internal/index] All DBs loaded! Should be headed to ready');
6337
- eventEmitter.emit('allDbsLoaded');
6338
- },
6339
- },
6340
- meta: {
6341
- displayText: 'Loading databases',
6342
- percentComplete: 90,
6343
- },
6344
- tags: ['loading'],
6345
- },
6346
5634
  ready: {
6347
5635
  entry: () => {
6348
- logger$2('[sdk] [internal/index] Ready!');
5636
+ logger$5('[sdk] [internal/index] Ready!');
6349
5637
  },
6350
5638
  meta: {
6351
5639
  displayText: "Crossing the t's ...",
@@ -6360,7 +5648,7 @@ const internalMachine = setup({
6360
5648
  },
6361
5649
  },
6362
5650
  entry: () => {
6363
- logger$2('[sdk] [internal/index] Error!');
5651
+ logger$5('[sdk] [internal/index] Error!');
6364
5652
  },
6365
5653
  meta: {
6366
5654
  displayText: 'Whoops! Something went wrong.',
@@ -6370,53 +5658,39 @@ const internalMachine = setup({
6370
5658
  },
6371
5659
  },
6372
5660
  });
6373
-
6374
- const logger$1 = debug('app:global:actors');
6375
- const initialize = fromCallback(({ sendBack, input: { event, context } }) => {
6376
- const { internalService, models, endpoints } = context;
6377
- const { addresses } = event;
6378
- let environment = 'browser';
6379
- if (isNode()) {
6380
- environment = 'node';
6381
- }
6382
- if (isReactNative()) {
6383
- environment = 'react-native';
6384
- }
6385
- let internalSubscription;
6386
- if (environment === 'browser' && models) {
6387
- const _initFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
6388
- return;
6389
- // return new Promise((resolve) => {
6390
- // })
6391
- });
6392
- const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
6393
- return new Promise((resolve) => {
6394
- internalSubscription = internalService.subscribe((snapshot) => {
6395
- logger$1('[sdk] [internal] snapshot', snapshot);
6396
- if (snapshot.value === 'ready') {
6397
- resolve();
6398
- }
6399
- });
6400
- internalService.send({ type: 'init', endpoints, addresses });
6401
- });
6402
- });
6403
- _initFileSystem().then(() => {
6404
- logger$1('[global/actors] File system initialized');
6405
- });
6406
- _initInternal().then(() => {
6407
- logger$1('[global/actors] Internal initialized');
6408
- sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
6409
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
6410
- });
6411
- // _initEas().then(() => {
6412
- // logger('EAS initialized')
6413
- // })
6414
- }
6415
- sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment });
6416
- return () => {
6417
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
6418
- };
6419
- });
5661
+ // const internalService = createActor(internalMachine, {
5662
+ // input: {},
5663
+ // inspect: (inspEvent) => {
5664
+ // if (inspEvent.type === '@xstate.snapshot') {
5665
+ // if (
5666
+ // inspEvent.event &&
5667
+ // inspEvent.event.snapshot &&
5668
+ // inspEvent.event.snapshot.value
5669
+ // ) {
5670
+ // logger(
5671
+ // `[internalService] ${inspEvent.event.snapshot.value}`,
5672
+ // inspEvent,
5673
+ // )
5674
+ // return
5675
+ // }
5676
+ //
5677
+ // if (inspEvent.snapshot && inspEvent.snapshot.value) {
5678
+ // logger(`[internalService] ${inspEvent.snapshot.value}`, inspEvent)
5679
+ // return
5680
+ // }
5681
+ //
5682
+ // // logger(`[internalService] Uncaught event`, inspEvent)
5683
+ // }
5684
+ // },
5685
+ // })
5686
+ // internalService.subscribe((snapshot) => {
5687
+ // globalService.send({ type: INTERNAL_SERVICE_SNAPSHOT, snapshot })
5688
+ // })
5689
+ //
5690
+ // internalService.on(CHILD_SNAPSHOT, (emitted) => {
5691
+ // globalService.send({ ...emitted })
5692
+ // })
5693
+ // internalService.start()
6420
5694
 
6421
5695
  const { UNINITIALIZED, INITIALIZING, INITIALIZED, GETTING_SEED_CLASS, GETTING_SCHEMA_FOR_MODEL, ADDING_MODELS_TO_DB, } = GlobalState;
6422
5696
  createBrowserInspector({
@@ -6458,14 +5732,6 @@ const globalMachine = setup({
6458
5732
  },
6459
5733
  });
6460
5734
  },
6461
- // fileSystemService: ({ spawn, event }) => {
6462
- // return spawn(fileSystemMachine, {
6463
- // systemId: MachineIds.FILE_SYSTEM,
6464
- // input: {
6465
- // addresses: event.addresses,
6466
- // },
6467
- // })
6468
- // },
6469
5735
  }),
6470
5736
  assign(({ event, spawn }) => {
6471
5737
  const allItemsServices = {};
@@ -6549,11 +5815,11 @@ const globalMachine = setup({
6549
5815
  (_a) => __awaiter(void 0, [_a], void 0, function* ({ context }) {
6550
5816
  let SeedClass;
6551
5817
  if (context.environment === 'node') {
6552
- const { SeedNode } = yield import('./seed-DGCfCUOn.js');
5818
+ const { SeedNode } = yield import('./seed-B5wj0Uk8.js');
6553
5819
  SeedClass = SeedNode;
6554
5820
  }
6555
5821
  else {
6556
- const { SeedBrowser } = yield import('./seed-BgRaREFr.js');
5822
+ const { SeedBrowser } = yield import('./seed-Y2OY2Tg_.js');
6557
5823
  SeedClass = SeedBrowser;
6558
5824
  }
6559
5825
  return SeedClass;
@@ -6647,6 +5913,444 @@ const globalService = createActor(globalMachine, {
6647
5913
  globalService.start();
6648
5914
  const getGlobalService = () => globalService;
6649
5915
 
5916
+ const logger$4 = debug('app:react:db');
5917
+ const useDbsAreReady = () => {
5918
+ const [dbsAreReady, setDbsAreReady] = useState(false);
5919
+ const update = useCallback(() => {
5920
+ if (dbsAreReady) {
5921
+ return;
5922
+ }
5923
+ setDbsAreReady(true);
5924
+ }, []);
5925
+ useEffect(() => {
5926
+ let globalSubscription;
5927
+ let internalSubscription;
5928
+ const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
5929
+ const globalService = getGlobalService();
5930
+ const internalService = globalService.getSnapshot().context.internalService;
5931
+ if (!internalService) {
5932
+ logger$4('[useDbsAreReady] [useEffect] no internalService');
5933
+ globalSubscription = globalService.subscribe(({ context }) => {
5934
+ if (!internalSubscription && context && context.internalService) {
5935
+ globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
5936
+ internalSubscription = context.internalService.subscribe((snapshot) => {
5937
+ if (snapshot.value === 'ready') {
5938
+ update();
5939
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5940
+ }
5941
+ });
5942
+ }
5943
+ });
5944
+ return;
5945
+ }
5946
+ const currentState = internalService.getSnapshot().value;
5947
+ if (currentState === 'ready') {
5948
+ update();
5949
+ return;
5950
+ }
5951
+ internalSubscription = internalService.subscribe((snapshot) => {
5952
+ if (snapshot.value === 'ready') {
5953
+ update();
5954
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5955
+ }
5956
+ });
5957
+ });
5958
+ _waitForDbs();
5959
+ return () => {
5960
+ if (globalSubscription) {
5961
+ globalSubscription.unsubscribe();
5962
+ }
5963
+ if (internalSubscription) {
5964
+ internalSubscription.unsubscribe();
5965
+ }
5966
+ };
5967
+ }, []);
5968
+ return {
5969
+ dbsAreReady,
5970
+ };
5971
+ };
5972
+
5973
+ const logger$3 = debug('app:react:services');
5974
+ const finalStrings = ['idle', 'ready', 'done', 'success'];
5975
+ const getServiceName = (service) => {
5976
+ let name = 'actor';
5977
+ if (service && service.uniqueKey) {
5978
+ name = service.uniqueKey;
5979
+ }
5980
+ if (service && !service.uniqueKey && service.logic && service.logic.config) {
5981
+ name = getServiceUniqueKey(service);
5982
+ }
5983
+ return name;
5984
+ };
5985
+ const getServiceValue = (service) => {
5986
+ let value;
5987
+ if (service && service.getSnapshot() && service.getSnapshot().value) {
5988
+ value = service.getSnapshot().value;
5989
+ }
5990
+ if (getServiceName(service) === 'global') {
5991
+ if (value &&
5992
+ typeof value === 'object' &&
5993
+ Object.keys(value).length > 0 &&
5994
+ Object.keys(value)[0] === 'initialized') {
5995
+ value = 'ready';
5996
+ }
5997
+ }
5998
+ if (value && typeof value === 'object') {
5999
+ value = JSON.stringify(value);
6000
+ }
6001
+ return value;
6002
+ };
6003
+ const getServiceUniqueKey = (service) => {
6004
+ if (!service || !service.logic || !service.logic.config) {
6005
+ return;
6006
+ }
6007
+ const config = service.logic.config;
6008
+ if (!config.id) {
6009
+ return;
6010
+ }
6011
+ let uniqueKey = config.id;
6012
+ if (config.id.includes('@seedSdk/')) {
6013
+ uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
6014
+ }
6015
+ let snapshot;
6016
+ try {
6017
+ snapshot = service.getSnapshot();
6018
+ }
6019
+ catch (error) {
6020
+ logger$3('Error:', error);
6021
+ return uniqueKey;
6022
+ }
6023
+ if (snapshot) {
6024
+ const context = snapshot.context;
6025
+ if (context && context.dbName) {
6026
+ uniqueKey = context.dbName;
6027
+ }
6028
+ if (context && context.modelNamePlural) {
6029
+ uniqueKey = context.modelNamePlural;
6030
+ }
6031
+ if (context && context.modelName) {
6032
+ uniqueKey = pluralize(context.modelName.toLowerCase());
6033
+ }
6034
+ }
6035
+ return uniqueKey;
6036
+ };
6037
+ const useServices = () => {
6038
+ const [actors, setActors] = useState([]);
6039
+ const [percentComplete, setPercentComplete] = useState(5);
6040
+ const actorsMap = new Map();
6041
+ useEffect(() => {
6042
+ const globalServiceListener = (event) => {
6043
+ if (event && event.type === 'init') {
6044
+ return;
6045
+ }
6046
+ if (event.actorRef &&
6047
+ event.actorRef.logic &&
6048
+ event.actorRef.logic.config) {
6049
+ const uniqueKey = getServiceUniqueKey(event.actorRef);
6050
+ if (!uniqueKey) {
6051
+ return;
6052
+ }
6053
+ event.actorRef.uniqueKey = uniqueKey;
6054
+ actorsMap.set(uniqueKey, event.actorRef);
6055
+ let actorsArray = Array.from(actorsMap.values());
6056
+ actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
6057
+ setActors(produce(actors, (draft) => {
6058
+ return actorsArray;
6059
+ }));
6060
+ }
6061
+ };
6062
+ eventEmitter.addListener('inspect.globalService', globalServiceListener);
6063
+ return () => {
6064
+ eventEmitter.removeListener('inspect.globalService', globalServiceListener);
6065
+ };
6066
+ }, []);
6067
+ useEffect(() => {
6068
+ const globalService = actors.find((actor) => getServiceName(actor) === 'global');
6069
+ const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
6070
+ if (!globalService || !internalService) {
6071
+ return;
6072
+ }
6073
+ if (getServiceValue(globalService) === 'ready' &&
6074
+ getServiceValue(internalService) === 'ready') {
6075
+ const denominator = actors.length;
6076
+ const finishedActors = actors.filter((actor) => {
6077
+ const value = getServiceValue(actor);
6078
+ return finalStrings.includes(value);
6079
+ });
6080
+ const numerator = finishedActors.length;
6081
+ const percentComplete = (numerator / denominator) * 100;
6082
+ setPercentComplete(percentComplete);
6083
+ }
6084
+ }, [actors]);
6085
+ return {
6086
+ services: actors,
6087
+ percentComplete,
6088
+ };
6089
+ };
6090
+ const useGlobalServiceStatus = () => {
6091
+ const globalService = getGlobalService();
6092
+ const status = useSelector(globalService, (snapshot) => {
6093
+ return snapshot.value;
6094
+ });
6095
+ const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
6096
+ if (!snapshot) {
6097
+ return;
6098
+ }
6099
+ return snapshot.value;
6100
+ });
6101
+ useSelector(globalService, (snapshot) => {
6102
+ return snapshot.context.internalService;
6103
+ });
6104
+ return {
6105
+ status,
6106
+ internalStatus,
6107
+ };
6108
+ };
6109
+
6110
+ const logger$2 = debug('app:react:item');
6111
+ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6112
+ const [item, setItem] = useImmer(undefined);
6113
+ const [itemSubscription, setItemSubscription] = useState();
6114
+ const { status, internalStatus } = useGlobalServiceStatus();
6115
+ const isReadingDb = useRef(false);
6116
+ const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6117
+ const updateItem = useCallback((newItem) => {
6118
+ setItem(() => newItem);
6119
+ }, []);
6120
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6121
+ if (isReadingDb.current ||
6122
+ internalStatus !== 'ready' ||
6123
+ (!seedUid && !seedLocalId)) {
6124
+ return;
6125
+ }
6126
+ isReadingDb.current = true;
6127
+ const foundItem = yield Item.find({
6128
+ modelName,
6129
+ seedLocalId,
6130
+ seedUid,
6131
+ });
6132
+ if (!foundItem) {
6133
+ logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6134
+ return;
6135
+ }
6136
+ updateItem(foundItem);
6137
+ isReadingDb.current = false;
6138
+ }), [internalStatus]);
6139
+ useEffect(() => {
6140
+ if (internalStatus === 'ready') {
6141
+ readFromDb();
6142
+ }
6143
+ }, [internalStatus, status]);
6144
+ useEffect(() => {
6145
+ if (item && !itemSubscription) {
6146
+ const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6147
+ const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6148
+ if (!newItem) {
6149
+ logger$2('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6150
+ return;
6151
+ }
6152
+ setItem(() => newItem);
6153
+ }));
6154
+ setItemSubscription(subscription);
6155
+ }
6156
+ return () => {
6157
+ itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
6158
+ };
6159
+ }, [item, itemSubscription]);
6160
+ useEffect(() => {
6161
+ const seedId = seedUid || seedLocalId;
6162
+ eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
6163
+ return () => {
6164
+ eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
6165
+ };
6166
+ }, []);
6167
+ return {
6168
+ item,
6169
+ itemStatus,
6170
+ };
6171
+ };
6172
+ const useItems = ({ modelName, options }) => {
6173
+ const [items, setItems] = useImmer([]);
6174
+ const [isReadingDb, setIsReadingDb] = useState(false);
6175
+ const [isInitialized, setIsInitialized] = useState(false);
6176
+ const { dbsAreReady } = useDbsAreReady();
6177
+ const modelNameRef = useRef(modelName);
6178
+ const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
6179
+ if (!event ||
6180
+ !event.modelName ||
6181
+ event.modelName !== modelNameRef.current ||
6182
+ isReadingDb) {
6183
+ return;
6184
+ }
6185
+ setIsReadingDb(true);
6186
+ const allItems = yield Item.all(modelNameRef.current);
6187
+ setItems(() => allItems);
6188
+ setIsReadingDb(false);
6189
+ }), [modelName]);
6190
+ useEffect(() => {
6191
+ if (dbsAreReady && !isInitialized) {
6192
+ const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
6193
+ yield readFromDb({ modelName });
6194
+ setIsInitialized(true);
6195
+ });
6196
+ _fetchItems();
6197
+ }
6198
+ }, [dbsAreReady, isInitialized]);
6199
+ useEffect(() => {
6200
+ eventEmitter.addListener('item.requestAll', readFromDb);
6201
+ return () => {
6202
+ eventEmitter.removeListener('item.requestAll');
6203
+ };
6204
+ }, []);
6205
+ return {
6206
+ items: orderBy(items, [
6207
+ (item) => item.lastVersionPublishedAt ||
6208
+ item.attestationCreatedAt ||
6209
+ item.createdAt,
6210
+ ], ['desc']).slice(0, 10),
6211
+ isReadingDb,
6212
+ isInitialized,
6213
+ };
6214
+ };
6215
+ const useItemIsReady = () => {
6216
+ const [itemListenersReady, setItemListenersReady] = useState(false);
6217
+ const itemEventListenersHandler = useCallback((_) => {
6218
+ setItemListenersReady(true);
6219
+ }, []);
6220
+ useEffect(() => {
6221
+ const areReady = getAreItemEventHandlersReady();
6222
+ if (areReady) {
6223
+ itemEventListenersHandler(true);
6224
+ }
6225
+ eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6226
+ return () => {
6227
+ eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6228
+ };
6229
+ }, []);
6230
+ return {
6231
+ isReady: itemListenersReady,
6232
+ };
6233
+ };
6234
+ const useCreateItem = (modelName) => {
6235
+ const [isCreatingItem, setIsCreatingItem] = useState(false);
6236
+ const { isReady } = useItemIsReady();
6237
+ const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6238
+ if (!isReady) {
6239
+ console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
6240
+ return;
6241
+ }
6242
+ if (isCreatingItem) {
6243
+ // TODO: should we setup a queue for this?
6244
+ console.error(`[useCreateItem] [createItem] already creating item`, itemData);
6245
+ return;
6246
+ }
6247
+ setIsCreatingItem(true);
6248
+ const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6249
+ yield Item.find({ modelName, seedLocalId });
6250
+ eventEmitter.emit('item.requestAll', { modelName });
6251
+ setIsCreatingItem(false);
6252
+ }), [isCreatingItem, isReady]);
6253
+ return {
6254
+ createItem,
6255
+ isCreatingItem,
6256
+ };
6257
+ };
6258
+ const useDeleteItem = () => {
6259
+ const [isDeletingItem, setIsDeletingItem] = useState(false);
6260
+ const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6261
+ if (!item) {
6262
+ return;
6263
+ }
6264
+ setIsDeletingItem(true);
6265
+ const { modelName } = item.getService().getSnapshot().context;
6266
+ yield deleteItem({ seedLocalId: item.seedLocalId });
6267
+ eventEmitter.emit('item.requestAll', { modelName });
6268
+ setIsDeletingItem(false);
6269
+ }), [isDeletingItem]);
6270
+ useEffect(() => { }, []);
6271
+ return {
6272
+ deleteItem: destroy,
6273
+ isDeletingItem,
6274
+ };
6275
+ };
6276
+
6277
+ const logger$1 = debug('app:react:property');
6278
+ const useItemProperty = (propertyName, seedLocalId) => {
6279
+ const [property, setProperty] = useImmer(undefined);
6280
+ const [isReadingFromDb, setIsReadingFromDb] = useState(false);
6281
+ const [isInitialized, setIsInitialized] = useState(false);
6282
+ const { dbsAreReady } = useDbsAreReady();
6283
+ const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
6284
+ if (!snapshot || !snapshot.context) {
6285
+ return;
6286
+ }
6287
+ return snapshot.context.renderValue || snapshot.context.propertyValue;
6288
+ });
6289
+ const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6290
+ useEffect(() => {
6291
+ if (dbsAreReady && property && property.value !== value) {
6292
+ readFromDb();
6293
+ }
6294
+ }, [dbsAreReady, property, value]);
6295
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6296
+ if (!propertyName || !seedLocalId || (!dbsAreReady && isReadingFromDb)) {
6297
+ return;
6298
+ }
6299
+ setIsReadingFromDb(true);
6300
+ const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
6301
+ setIsReadingFromDb(false);
6302
+ if (!foundProperty) {
6303
+ logger$1(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6304
+ return;
6305
+ }
6306
+ setProperty(() => foundProperty);
6307
+ setIsInitialized(true);
6308
+ }), [dbsAreReady, isReadingFromDb]);
6309
+ useEffect(() => {
6310
+ readFromDb();
6311
+ }, []);
6312
+ // TODO: How can we force a re-render when the property is updated?
6313
+ // Right now, the value will trigger an update because it's using a selector
6314
+ // and a change is pushed to the hook listener.
6315
+ return {
6316
+ property,
6317
+ isInitialized,
6318
+ isReadingFromDb,
6319
+ value,
6320
+ status,
6321
+ };
6322
+ };
6323
+ const useItemProperties = (item) => {
6324
+ const [propertyObj, setPropertyObj] = useImmer({});
6325
+ useState(false);
6326
+ const updatePropertyObj = useCallback((event) => {
6327
+ if (!item) {
6328
+ console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6329
+ return;
6330
+ }
6331
+ const { propertyName, propertyValue } = event;
6332
+ if (!propertyName) {
6333
+ return;
6334
+ }
6335
+ setPropertyObj((draft) => {
6336
+ draft[propertyName] = propertyValue;
6337
+ });
6338
+ }, [item]);
6339
+ useEffect(() => {
6340
+ if (!item) {
6341
+ return;
6342
+ }
6343
+ const eventKey = `item.${item.seedLocalId}.property.update`;
6344
+ eventEmitter.addListener(eventKey, updatePropertyObj);
6345
+ return () => {
6346
+ eventEmitter.removeListener(eventKey, updatePropertyObj);
6347
+ };
6348
+ }, [item]);
6349
+ return {
6350
+ properties: propertyObj,
6351
+ };
6352
+ };
6353
+
6650
6354
  const logger = debug('app:services:events');
6651
6355
  const handleServiceSaveState = (event) => {
6652
6356
  const { state, serviceId } = event;
@@ -6657,5 +6361,326 @@ const setupServicesEventHandlers = () => {
6657
6361
  eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
6658
6362
  };
6659
6363
 
6660
- export { useDeleteItem as $, APP_DB_CONFIG as A, setupFsListeners as B, CHILD_SNAPSHOT as C, DB_NAME_SDK_CONFIG as D, setupAllItemsEventHandlers as E, setupServicesEventHandlers as F, GET_SCHEMAS as G, globalService as H, Item as I, Json as J, getModel as K, List as L, Model as M, getModels as N, getModelNames as O, Property as P, areFsListenersReady as Q, Relation as R, SCHEMA_NJK as S, Text as T, ItemProperty as U, useItems as V, useItem as W, useItemProperties as X, useCreateItem as Y, useItemProperty as Z, __awaiter as _, GET_SEEDS as a, useServices as a0, getGlobalService as a1, getCorrectId as a2, 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, internalMachine as h, itemMachineSingle as i, isNode as j, isBrowser as k, isReactNative as l, __decorate as m, __metadata as n, models as o, SCHEMA_TS as p, SDK_DB_CONFIG as q, SEED_DB_CONFIG as r, addModelsToInternalDb as s, ImageSrc as t, createNewMetadataFromExistingRecord as u, generateId as v, eventEmitter as w, getDb as x, DB_NAME_APP as y, setModel as z };
6661
- //# sourceMappingURL=events-So24__c6.js.map
6364
+ const propertySaveHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6365
+ const { localId, seedLocalId, propertyName, propertyValue, seedUid, modelType, refSeedType, } = event;
6366
+ const appDb = getAppDb();
6367
+ if (!appDb) {
6368
+ throw new Error('initialize: appDb is undefined');
6369
+ }
6370
+ if (!seedUid && !seedLocalId) {
6371
+ throw new Error('seedUid and seedLocalId are both undefined');
6372
+ }
6373
+ if (seedUid && !seedLocalId) {
6374
+ throw new Error("seedUid is defined but seedLocalId is not. This shouldn't happen since seedLocalIds are saved to the db at the same time as seedUid.");
6375
+ }
6376
+ let recordToUpdate;
6377
+ let recordToUseAsSource;
6378
+ let localRecordQuery;
6379
+ const selectStatement = `SELECT local_id, uid, property_value, seed_local_id, seed_uid, created_at, attestation_created_at, schema_uid, model_type, version_local_id, version_uid, eas_data_type, ref_value_type, ref_schema_uid, ref_seed_type, ref_resolved_value, ref_resolved_display_value, attestation_raw`;
6380
+ if (localId) {
6381
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6382
+ FROM metadata
6383
+ WHERE local_id = '${localId}'
6384
+ ORDER BY created_at DESC;
6385
+ `));
6386
+ }
6387
+ if (!localId && !seedLocalId && seedUid) {
6388
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6389
+ FROM metadata
6390
+ WHERE seed_uid = '${seedUid}'
6391
+ AND property_name = '${propertyName}'
6392
+ ORDER BY created_at DESC;
6393
+ `));
6394
+ }
6395
+ if (!localId && seedLocalId && !seedUid) {
6396
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6397
+ FROM metadata
6398
+ WHERE seed_local_id = '${seedLocalId}'
6399
+ AND property_name = '${propertyName}'
6400
+ ORDER BY created_at DESC;
6401
+ `));
6402
+ }
6403
+ if (!localId && seedLocalId && seedUid) {
6404
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6405
+ FROM metadata
6406
+ WHERE seed_local_id = '${seedLocalId}'
6407
+ AND seed_uid = '${seedUid}'
6408
+ AND property_name = '${propertyName}'
6409
+ ORDER BY created_at DESC;
6410
+ `));
6411
+ }
6412
+ if (localRecordQuery &&
6413
+ localRecordQuery.rows &&
6414
+ localRecordQuery.rows.length > 0) {
6415
+ const propertyValueFromDb = localRecordQuery.rows[0][2];
6416
+ if (propertyValueFromDb === propertyValue) {
6417
+ // This should be a no-op since the property is already properly saved to the local db.
6418
+ return;
6419
+ }
6420
+ const localIdFromDb = localRecordQuery.rows[0][0];
6421
+ const uidFromDb = localRecordQuery.rows[0][1];
6422
+ const shouldUpdate = !!localId || !uidFromDb;
6423
+ const shouldCreateNew = !!localIdFromDb && !!uidFromDb;
6424
+ if (shouldUpdate) {
6425
+ recordToUpdate = {
6426
+ localId: localId || localIdFromDb,
6427
+ };
6428
+ }
6429
+ if (shouldCreateNew) {
6430
+ recordToUseAsSource = {
6431
+ localId: localIdFromDb,
6432
+ uid: uidFromDb,
6433
+ propertyValue: localRecordQuery.rows[0][2],
6434
+ seedLocalId: localRecordQuery.rows[0][3],
6435
+ seedUid: localRecordQuery.rows[0][4],
6436
+ createdAt: localRecordQuery.rows[0][5],
6437
+ attestationCreatedAt: localRecordQuery.rows[0][6],
6438
+ schemaUid: localRecordQuery.rows[0][7],
6439
+ modelType: localRecordQuery.rows[0][8],
6440
+ versionLocalId: localRecordQuery.rows[0][9],
6441
+ versionUid: localRecordQuery.rows[0][10],
6442
+ easDataType: localRecordQuery.rows[0][11],
6443
+ refValueType: localRecordQuery.rows[0][12],
6444
+ refSchemaUid: localRecordQuery.rows[0][13],
6445
+ refSeedType: localRecordQuery.rows[0][14],
6446
+ refResolvedValue: localRecordQuery.rows[0][15],
6447
+ refResolvedDisplayValue: localRecordQuery.rows[0][16],
6448
+ attestationRaw: localRecordQuery.rows[0][17],
6449
+ };
6450
+ }
6451
+ }
6452
+ if (recordToUpdate) {
6453
+ yield appDb.run(sql.raw(`UPDATE metadata
6454
+ SET property_value = '${propertyValue}'
6455
+ WHERE local_id = '${recordToUpdate.localId}';
6456
+ `));
6457
+ }
6458
+ if (recordToUseAsSource) {
6459
+ yield createNewMetadataFromExistingRecord({
6460
+ existingRecord: recordToUseAsSource,
6461
+ propertyName,
6462
+ propertyValue,
6463
+ });
6464
+ }
6465
+ if (!recordToUpdate && !recordToUseAsSource) {
6466
+ const newLocalId = generateId();
6467
+ yield appDb.run(sql.raw(`INSERT INTO metadata (local_id, seed_local_id, seed_uid, property_name, property_value, created_at, updated_at,
6468
+ model_type, ref_seed_type)
6469
+ VALUES ('${newLocalId}', '${seedLocalId}', '${seedUid}', '${propertyName}', '${propertyValue}',
6470
+ ${Date.now()}, ${Date.now()}, '${modelType.toLowerCase()}',
6471
+ ${refSeedType ? `'${refSeedType.toLowerCase()}'` : 'NULL'});
6472
+ `));
6473
+ }
6474
+ eventEmitter.emit(`property.${seedLocalId}.${propertyName}.save.response`, {
6475
+ status: 'success',
6476
+ });
6477
+ });
6478
+
6479
+ const propertySaveRelationHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6480
+ const { localId, seedLocalId, propertyName, propertyValue, seedUid, modelType, refSeedType, } = event;
6481
+ const appDb = getAppDb();
6482
+ if (!appDb) {
6483
+ throw new Error('initialize: appDb is undefined');
6484
+ }
6485
+ if (!seedUid && !seedLocalId) {
6486
+ throw new Error('seedUid and seedLocalId are both undefined');
6487
+ }
6488
+ if (seedUid && !seedLocalId) {
6489
+ throw new Error("seedUid is defined but seedLocalId is not. This shouldn't happen since seedLocalIds are saved to the db at the same time as seedUid.");
6490
+ }
6491
+ let recordToUpdate;
6492
+ let recordToUseAsSource;
6493
+ let localRecordQuery;
6494
+ const selectStatement = `SELECT local_id, uid, property_value, seed_local_id, seed_uid, created_at, attestation_created_at, schema_uid, model_type, version_local_id, version_uid, eas_data_type, ref_value_type, ref_schema_uid, ref_seed_type, ref_resolved_value, ref_resolved_display_value, attestation_raw`;
6495
+ if (localId) {
6496
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6497
+ FROM metadata
6498
+ WHERE local_id = '${localId}'
6499
+ ORDER BY created_at DESC;
6500
+ `));
6501
+ }
6502
+ if (!localId && !seedLocalId && seedUid) {
6503
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6504
+ FROM metadata
6505
+ WHERE seed_uid = '${seedUid}'
6506
+ AND property_name = '${propertyName}'
6507
+ ORDER BY created_at DESC;
6508
+ `));
6509
+ }
6510
+ if (!localId && seedLocalId && !seedUid) {
6511
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6512
+ FROM metadata
6513
+ WHERE seed_local_id = '${seedLocalId}'
6514
+ AND property_name = '${propertyName}'
6515
+ ORDER BY created_at DESC;
6516
+ `));
6517
+ }
6518
+ if (!localId && seedLocalId && seedUid) {
6519
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6520
+ FROM metadata
6521
+ WHERE seed_local_id = '${seedLocalId}'
6522
+ AND seed_uid = '${seedUid}'
6523
+ AND property_name = '${propertyName}'
6524
+ ORDER BY created_at DESC;
6525
+ `));
6526
+ }
6527
+ if (localRecordQuery &&
6528
+ localRecordQuery.rows &&
6529
+ localRecordQuery.rows.length > 0) {
6530
+ const propertyValueFromDb = localRecordQuery.rows[0][2];
6531
+ if (propertyValueFromDb === propertyValue) {
6532
+ // This should be a no-op since the property is already properly saved to the local db.
6533
+ return;
6534
+ }
6535
+ const localIdFromDb = localRecordQuery.rows[0][0];
6536
+ const uidFromDb = localRecordQuery.rows[0][1];
6537
+ const shouldUpdate = !!localId || !uidFromDb;
6538
+ const shouldCreateNew = !!localIdFromDb && !!uidFromDb;
6539
+ if (shouldUpdate) {
6540
+ recordToUpdate = {
6541
+ localId: localId || localIdFromDb,
6542
+ };
6543
+ }
6544
+ if (shouldCreateNew) {
6545
+ recordToUseAsSource = {
6546
+ localId: localIdFromDb,
6547
+ uid: uidFromDb,
6548
+ propertyValue: localRecordQuery.rows[0][2],
6549
+ seedLocalId: localRecordQuery.rows[0][3],
6550
+ seedUid: localRecordQuery.rows[0][4],
6551
+ createdAt: localRecordQuery.rows[0][5],
6552
+ attestationCreatedAt: localRecordQuery.rows[0][6],
6553
+ schemaUid: localRecordQuery.rows[0][7],
6554
+ modelType: localRecordQuery.rows[0][8],
6555
+ versionLocalId: localRecordQuery.rows[0][9],
6556
+ versionUid: localRecordQuery.rows[0][10],
6557
+ easDataType: localRecordQuery.rows[0][11],
6558
+ refValueType: localRecordQuery.rows[0][12],
6559
+ refSchemaUid: localRecordQuery.rows[0][13],
6560
+ refSeedType: localRecordQuery.rows[0][14],
6561
+ refResolvedValue: localRecordQuery.rows[0][15],
6562
+ refResolvedDisplayValue: localRecordQuery.rows[0][16],
6563
+ attestationRaw: localRecordQuery.rows[0][17],
6564
+ };
6565
+ }
6566
+ }
6567
+ if (recordToUpdate) {
6568
+ yield appDb.run(sql.raw(`UPDATE metadata
6569
+ SET property_value = '${propertyValue}'
6570
+ WHERE local_id = '${recordToUpdate.localId}';
6571
+ `));
6572
+ }
6573
+ if (recordToUseAsSource) {
6574
+ yield createNewMetadataFromExistingRecord({
6575
+ existingRecord: recordToUseAsSource,
6576
+ propertyName,
6577
+ propertyValue,
6578
+ });
6579
+ }
6580
+ if (!recordToUpdate && !recordToUseAsSource) {
6581
+ const newSeedLocalId = generateId();
6582
+ yield appDb.run(sql.raw(`INSERT INTO seeds (local_id, type, created_at, updated_at)
6583
+ VALUES ('${newSeedLocalId}', '${refSeedType.toLowerCase()}', ${Date.now()}, ${Date.now()});
6584
+ `));
6585
+ const newVersionLocalId = generateId();
6586
+ yield appDb.run(sql.raw(`INSERT INTO versions (local_id, seed_local_id, created_at, updated_at)
6587
+ VALUES ('${newVersionLocalId}', '${newSeedLocalId}', ${Date.now()}, ${Date.now()});
6588
+ `));
6589
+ const newPropertyLocalId = generateId();
6590
+ yield appDb.run(sql.raw(`INSERT INTO metadata (local_id, seed_local_id, version_local_id, property_name, property_value,
6591
+ ref_resolved_value, created_at,
6592
+ updated_at,
6593
+ model_type)
6594
+ VALUES ('${newPropertyLocalId}', '${seedLocalId}', '${newVersionLocalId}', '${propertyName}',
6595
+ '${newSeedLocalId}', '${propertyValue}',
6596
+ ${Date.now()}, ${Date.now()}, '${modelType.toLowerCase()}');
6597
+ `));
6598
+ }
6599
+ eventEmitter.emit(`property.${seedLocalId}.${propertyName}.saveRelation.response`, {
6600
+ status: 'success',
6601
+ });
6602
+ });
6603
+
6604
+ const setupPropertyEventHandlers = () => {
6605
+ eventEmitter.addListener('property.request', (event) => {
6606
+ console.log('property.request', event);
6607
+ });
6608
+ eventEmitter.addListener('property.save.request', propertySaveHandler);
6609
+ eventEmitter.addListener('property.saveRelation.request', propertySaveRelationHandler);
6610
+ };
6611
+
6612
+ const client = {
6613
+ init: ({ config, addresses }) => {
6614
+ const { endpoints, models } = config;
6615
+ for (const [key, value] of Object.entries(models)) {
6616
+ setModel(key, value);
6617
+ }
6618
+ setupFsListeners();
6619
+ setupAllItemsEventHandlers();
6620
+ setupServicesEventHandlers();
6621
+ setupPropertyEventHandlers();
6622
+ if (areFsListenersReady()) {
6623
+ eventEmitter.emit('fs.init');
6624
+ }
6625
+ if (!areFsListenersReady()) {
6626
+ console.error('fs listeners not ready during init');
6627
+ }
6628
+ globalService.send({ type: 'init', endpoints, models, addresses });
6629
+ import('./seed.schema.config-DZC8TNja.js').then(({ models }) => {
6630
+ for (const [key, value] of Object.entries(models)) {
6631
+ setModel(key, value);
6632
+ }
6633
+ });
6634
+ },
6635
+ subscribe: (callback) => {
6636
+ callback({
6637
+ type: '@xstate.snapshot',
6638
+ actorRef: globalService,
6639
+ snapshot: globalService.getSnapshot(),
6640
+ });
6641
+ eventEmitter.addListener('globalService', callback);
6642
+ return {
6643
+ unsubscribe: () => {
6644
+ eventEmitter.removeListener('globalService', callback);
6645
+ },
6646
+ };
6647
+ },
6648
+ on: (outerEvent, callback) => {
6649
+ eventEmitter.addListener(outerEvent, callback);
6650
+ return {
6651
+ unsubscribe: () => {
6652
+ eventEmitter.removeListener(outerEvent, callback);
6653
+ },
6654
+ };
6655
+ },
6656
+ getSeedClass: () => __awaiter(void 0, void 0, void 0, function* () {
6657
+ return new Promise((resolve) => {
6658
+ const subscription = globalService.subscribe((snapshot) => {
6659
+ if (snapshot.status === 'done') {
6660
+ resolve(snapshot.output);
6661
+ }
6662
+ });
6663
+ globalService.send({ type: 'getSeed' });
6664
+ subscription.unsubscribe();
6665
+ });
6666
+ }),
6667
+ getModel: (modelName) => {
6668
+ return getModel(modelName);
6669
+ },
6670
+ getModels: () => {
6671
+ return getModels();
6672
+ },
6673
+ getModelNames: () => {
6674
+ return getModelNames();
6675
+ },
6676
+ };
6677
+
6678
+ var _a;
6679
+ enableMapSet();
6680
+ let withSeed;
6681
+ if (isNode()) {
6682
+ withSeed = (_a = initSeedSync()) === null || _a === void 0 ? void 0 : _a.withSeed;
6683
+ }
6684
+
6685
+ export { CHILD_SNAPSHOT as C, 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, internalMachine as h, itemMachineSingle as i, isNode as j, isBrowser as k, isReactNative as l, ImageSrc as m, ItemProperty as n, useItem as o, useItemProperties as p, useCreateItem as q, useItemProperty as r, useDeleteItem as s, useServices as t, useItems as u, getGlobalService as v, withSeed as w, client as x, getCorrectId as y };
6686
+ //# sourceMappingURL=index-B299zGP9.js.map