@seedprotocol/sdk 0.3.0 → 0.3.1

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 (200) hide show
  1. package/dist/{ArweaveClient-CmJYeuq1.js → ArweaveClient-C0g0es2v.js} +2 -2
  2. package/dist/{ArweaveClient-EXXrXUzz.js.map → ArweaveClient-C0g0es2v.js.map} +1 -1
  3. package/dist/{ArweaveClient-EXXrXUzz.js → ArweaveClient-CzkBgiZY.js} +2 -2
  4. package/dist/{ArweaveClient-CmJYeuq1.js.map → ArweaveClient-CzkBgiZY.js.map} +1 -1
  5. package/dist/{Db-CESKJH-G.js → Db-C4oog-0n.js} +3 -3
  6. package/dist/{Db-CESKJH-G.js.map → Db-C4oog-0n.js.map} +1 -1
  7. package/dist/{Db-DiTPSbQ8.js → Db-VPouegkr.js} +3 -3
  8. package/dist/{Db-DiTPSbQ8.js.map → Db-VPouegkr.js.map} +1 -1
  9. package/dist/{EasClient-BesHK2bO.js → EasClient-B9a3NsTi.js} +2 -2
  10. package/dist/{EasClient-BesHK2bO.js.map → EasClient-B9a3NsTi.js.map} +1 -1
  11. package/dist/{EasClient-Cop6WtWl.js → EasClient-DQ93i2ci.js} +2 -2
  12. package/dist/{EasClient-Cop6WtWl.js.map → EasClient-DQ93i2ci.js.map} +1 -1
  13. package/dist/{FileManager-DTzkncLh.js → FileManager-_ErxVuwb.js} +8 -5
  14. package/dist/FileManager-_ErxVuwb.js.map +1 -0
  15. package/dist/{Item-B5Tz-Y7t.js → Item-D9HFPxsK.js} +3 -3
  16. package/dist/{Item-B5Tz-Y7t.js.map → Item-D9HFPxsK.js.map} +1 -1
  17. package/dist/{ItemProperty-DBV0Iib_.js → ItemProperty-BdtvKrEy.js} +3 -3
  18. package/dist/{ItemProperty-DBV0Iib_.js.map → ItemProperty-BdtvKrEy.js.map} +1 -1
  19. package/dist/{QueryClient-C7a0NHCt.js → QueryClient-Bmnv_moN.js} +2 -2
  20. package/dist/{QueryClient-C7a0NHCt.js.map → QueryClient-Bmnv_moN.js.map} +1 -1
  21. package/dist/{QueryClient-BnwbHtqe.js → QueryClient-hzOtFe99.js} +2 -2
  22. package/dist/{QueryClient-BnwbHtqe.js.map → QueryClient-hzOtFe99.js.map} +1 -1
  23. package/dist/bin.js +5 -5
  24. package/dist/bin.js.map +1 -1
  25. package/dist/{constants-CWg2B3Au.js → constants-Bhl5dZpN.js} +4 -1
  26. package/dist/constants-Bhl5dZpN.js.map +1 -0
  27. package/dist/{index-CQ9FS10O.js → index-BAtjd9W-.js} +3 -3
  28. package/dist/index-BAtjd9W-.js.map +1 -0
  29. package/dist/{index-BHGJ-Es9.js → index-BSR5hv7Q.js} +59 -27
  30. package/dist/index-BSR5hv7Q.js.map +1 -0
  31. package/dist/main.js +2 -2
  32. package/dist/{seed.schema.config-DDzfQguf.js → seed.schema.config-BxJYabim.js} +3 -3
  33. package/dist/{seed.schema.config-DDzfQguf.js.map → seed.schema.config-BxJYabim.js.map} +1 -1
  34. package/dist/src/AppStateSchema.ts +10 -0
  35. package/dist/src/ArweaveClient.ts +13 -0
  36. package/dist/src/Attestation.ts +21 -0
  37. package/dist/src/BaseArweaveClient.ts +13 -0
  38. package/dist/src/BaseClientManager.ts +35 -0
  39. package/dist/src/BaseDb.ts +35 -0
  40. package/dist/src/BaseEasClient.ts +14 -0
  41. package/dist/src/BaseFileManager.ts +60 -0
  42. package/dist/src/BaseItem.ts +413 -0
  43. package/dist/src/BaseItemProperty.ts +416 -0
  44. package/dist/src/BaseQueryClient.ts +13 -0
  45. package/dist/src/ClientManager.ts +63 -0
  46. package/dist/src/ConfigSchema.ts +15 -0
  47. package/dist/src/Db.ts +82 -0
  48. package/dist/src/EasClient.ts +13 -0
  49. package/dist/src/FileDownloader.ts +63 -0
  50. package/dist/src/FileManager.ts +59 -0
  51. package/dist/src/IDb.ts +7 -0
  52. package/dist/src/IEasClient.ts +2 -0
  53. package/dist/src/IItem.ts +26 -0
  54. package/dist/src/IItemProperty.ts +28 -0
  55. package/dist/src/IQueryClient.ts +11 -0
  56. package/dist/src/ImageResizer.ts +81 -0
  57. package/dist/src/Item.ts +12 -0
  58. package/dist/src/ItemProperty.ts +9 -0
  59. package/dist/src/MetadataSchema.ts +28 -0
  60. package/dist/src/ModelSchema.ts +46 -0
  61. package/dist/src/ModelUidSchema.ts +16 -0
  62. package/dist/src/PropertyUidSchema.ts +16 -0
  63. package/dist/src/QueryClient.ts +26 -0
  64. package/dist/src/Schema.ts +17 -0
  65. package/dist/src/SeedProtocolSdk.d.ts +19 -0
  66. package/dist/src/SeedSchema.ts +29 -0
  67. package/dist/src/VersionSchema.ts +16 -0
  68. package/dist/src/actors.ts +295 -0
  69. package/dist/src/addModelsToDb.ts +152 -0
  70. package/dist/src/allItems.ts +31 -0
  71. package/dist/src/analyzeInput.ts +144 -0
  72. package/dist/src/browser.app.db.config.ts +27 -0
  73. package/dist/src/browser.ts +30 -0
  74. package/dist/src/checkStatus.ts +57 -0
  75. package/dist/src/clientManagerMachine.ts +59 -0
  76. package/dist/src/configureFs.ts +98 -0
  77. package/dist/src/connectToDb.ts +41 -0
  78. package/dist/src/connectionManager.ts +67 -0
  79. package/dist/src/constants.ts +125 -0
  80. package/dist/src/content-hash.ts +30 -0
  81. package/dist/src/create.ts +39 -0
  82. package/dist/src/createMetadata.ts +77 -0
  83. package/dist/src/createNewItem.ts +61 -0
  84. package/dist/src/createPublishAttempt.ts +16 -0
  85. package/dist/src/createSeed.ts +31 -0
  86. package/dist/src/createSeeds.ts +24 -0
  87. package/dist/src/createVersion.ts +33 -0
  88. package/dist/src/dbMachine.ts +182 -0
  89. package/dist/src/deleteItem.ts +19 -0
  90. package/dist/src/download.ts +208 -0
  91. package/dist/src/drizzle.ts +78 -0
  92. package/dist/src/eas.ts +40 -0
  93. package/dist/src/environment.ts +35 -0
  94. package/dist/src/eventBus.ts +5 -0
  95. package/dist/src/events.ts +14 -0
  96. package/dist/src/fetchDataFromEas.ts +94 -0
  97. package/dist/src/fetchDbData.ts +19 -0
  98. package/dist/src/fetchRelatedItems.ts +184 -0
  99. package/dist/src/fetchSeeds.ts +45 -0
  100. package/dist/src/fetchVersions.ts +49 -0
  101. package/dist/src/files.ts +81 -0
  102. package/dist/src/filesDownload.ts +326 -0
  103. package/dist/src/fragment-masking.ts +87 -0
  104. package/dist/src/getExistingItem.ts +60 -0
  105. package/dist/src/getItem.ts +32 -0
  106. package/dist/src/getItemData.ts +99 -0
  107. package/dist/src/getItemProperties.ts +56 -0
  108. package/dist/src/getItemProperty.ts +34 -0
  109. package/dist/src/getItems.ts +70 -0
  110. package/dist/src/getMetadata.ts +40 -0
  111. package/dist/src/getModelSchemas.ts +89 -0
  112. package/dist/src/getPropertyData.ts +50 -0
  113. package/dist/src/getPublishPayload.ts +355 -0
  114. package/dist/src/getPublishUploads.ts +207 -0
  115. package/dist/src/getRelationValueData.ts +27 -0
  116. package/dist/src/getSchemaForItemProperty.ts +68 -0
  117. package/dist/src/getSchemaForModel.ts +42 -0
  118. package/dist/src/getSchemaUidForModel.ts +32 -0
  119. package/dist/src/getSeedData.ts +34 -0
  120. package/dist/src/getSegmentedItemProperties.ts +65 -0
  121. package/dist/src/getStorageTransactionIdForSeedUid.ts +38 -0
  122. package/dist/src/getVersionData.ts +46 -0
  123. package/dist/src/getVersionsForVersionUids.ts +39 -0
  124. package/dist/src/globalMachine.ts +280 -0
  125. package/dist/src/gql.ts +118 -0
  126. package/dist/src/graphql.ts +3209 -0
  127. package/dist/src/helpers.ts +273 -0
  128. package/dist/src/hydrateExistingItem.ts +137 -0
  129. package/dist/src/hydrateFromDb.ts +270 -0
  130. package/dist/src/hydrateNewItem.ts +34 -0
  131. package/dist/src/imageResize.ts +507 -0
  132. package/dist/src/index.d.ts +5 -0
  133. package/dist/src/index.ts +4 -0
  134. package/dist/src/initialize.ts +124 -0
  135. package/dist/src/internalMachine.ts +241 -0
  136. package/dist/src/itemMachineAll.ts +157 -0
  137. package/dist/src/itemMachineSingle.ts +158 -0
  138. package/dist/src/loadAppDb.ts +44 -0
  139. package/dist/src/machines.ts +66 -0
  140. package/dist/src/metadataLatest.ts +34 -0
  141. package/dist/src/migrate.ts +57 -0
  142. package/dist/src/model.ts +72 -0
  143. package/dist/src/modelClass.ts +19 -0
  144. package/dist/src/node.app.db.config.ts +41 -0
  145. package/dist/src/prepareDb.ts +29 -0
  146. package/dist/src/preparePublishRequestData.ts +81 -0
  147. package/dist/src/processItems.ts +74 -0
  148. package/dist/src/property.ts +156 -0
  149. package/dist/src/propertyMachine.ts +202 -0
  150. package/dist/src/publish.ts +28 -0
  151. package/dist/src/publishMachine.ts +77 -0
  152. package/dist/src/queries.ts +13 -0
  153. package/dist/src/recoverDeletedItem.ts +14 -0
  154. package/dist/src/reload.ts +33 -0
  155. package/dist/src/request.ts +45 -0
  156. package/dist/src/requestAll.ts +157 -0
  157. package/dist/src/resolveRelatedValue.ts +367 -0
  158. package/dist/src/resolveRemoteStorage.ts +88 -0
  159. package/dist/src/saveAppState.ts +50 -0
  160. package/dist/src/saveConfig.ts +106 -0
  161. package/dist/src/saveDataToDb.ts +145 -0
  162. package/dist/src/saveImageSrc.ts +242 -0
  163. package/dist/src/saveItemStorage.ts +156 -0
  164. package/dist/src/saveMetadata.ts +18 -0
  165. package/dist/src/savePublishService.ts +30 -0
  166. package/dist/src/saveRelation.ts +112 -0
  167. package/dist/src/seed.schema.config.ts +25 -0
  168. package/dist/src/seed.ts +10 -0
  169. package/dist/src/seedProtocol.ts +17 -0
  170. package/dist/src/services.ts +365 -0
  171. package/dist/src/setAddresses.ts +16 -0
  172. package/dist/src/sqlWasmClient.ts +88 -0
  173. package/dist/src/syncDbWithEas.ts +628 -0
  174. package/dist/src/trash.ts +29 -0
  175. package/dist/src/ts-to-proto.ts +101 -0
  176. package/dist/src/types.ts +12 -0
  177. package/dist/src/updateItemPropertyValue.ts +243 -0
  178. package/dist/src/updateMachineContext.ts +21 -0
  179. package/dist/src/updateMetadata.ts +59 -0
  180. package/dist/src/upload.ts +86 -0
  181. package/dist/src/validate.ts +45 -0
  182. package/dist/src/validateInput.ts +43 -0
  183. package/dist/src/validateItemData.ts +20 -0
  184. package/dist/src/versionData.ts +24 -0
  185. package/dist/src/waitForDb.ts +25 -0
  186. package/dist/src/waitForFiles.ts +41 -0
  187. package/dist/src/wasm.d.ts +8300 -0
  188. package/dist/types/scripts/bin.d.ts.map +1 -1
  189. package/dist/types/src/browser/helpers/FileManager.d.ts +2 -1
  190. package/dist/types/src/browser/helpers/FileManager.d.ts.map +1 -1
  191. package/dist/types/src/helpers/FileManager/BaseFileManager.d.ts +1 -0
  192. package/dist/types/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  193. package/dist/types/src/node/helpers/FileManager.d.ts +2 -1
  194. package/dist/types/src/node/helpers/FileManager.d.ts.map +1 -1
  195. package/package.json +3 -3
  196. package/dist/FileManager-DTzkncLh.js.map +0 -1
  197. package/dist/constants-CWg2B3Au.js.map +0 -1
  198. package/dist/index-BHGJ-Es9.js.map +0 -1
  199. package/dist/index-CQ9FS10O.js.map +0 -1
  200. package/dist/package.json +0 -189
@@ -0,0 +1,31 @@
1
+ import { generateId } from '@/helpers'
2
+ import { seeds } from '@/seedSchema'
3
+ import { BaseDb } from '@/db/Db/BaseDb'
4
+ import { getSchemaUidForModel } from '@/db/read/getSchemaUidForModel'
5
+
6
+ type CreateSeedProps = {
7
+ type: string
8
+ seedUid?: string
9
+ }
10
+
11
+ export const createSeed = async ({ type, seedUid }: CreateSeedProps): Promise<string> => {
12
+ const schemaUid = await getSchemaUidForModel(type)
13
+
14
+ if (!schemaUid) {
15
+ throw new Error(`No schema found for model type: ${type}`)
16
+ }
17
+
18
+ const appDb = BaseDb.getAppDb()
19
+
20
+ const newSeedLocalId = generateId()
21
+
22
+ await appDb.insert(seeds).values({
23
+ localId: newSeedLocalId,
24
+ type,
25
+ uid: seedUid,
26
+ createdAt: Date.now(),
27
+ schemaUid,
28
+ })
29
+
30
+ return newSeedLocalId
31
+ }
@@ -0,0 +1,24 @@
1
+ import { seeds, SeedType } from '@/seedSchema'
2
+ import { BaseDb } from '@/db/Db/BaseDb'
3
+
4
+ type CreateSeeds = (newSeeds: Partial<SeedType>[]) => Promise<string[]>
5
+
6
+ export const createSeeds: CreateSeeds = async (
7
+ newSeeds: Partial<SeedType>[],
8
+ ) => {
9
+ const appDb = BaseDb.getAppDb()
10
+
11
+ const results = await appDb
12
+ .insert(seeds)
13
+ .values(newSeeds)
14
+ .returning({ uid: seeds.uid })
15
+
16
+ const newUids = results.reduce((acc, result) => {
17
+ if (result.uid) {
18
+ acc.push(result.uid)
19
+ }
20
+ return acc
21
+ }, [] as string[])
22
+
23
+ return newUids
24
+ }
@@ -0,0 +1,33 @@
1
+ import { generateId } from '@/helpers'
2
+ import { versions } from '@/seedSchema'
3
+ import { BaseDb } from '../Db/BaseDb'
4
+
5
+ type CreateVersionProps = {
6
+ seedLocalId?: string
7
+ seedUid?: string
8
+ seedType?: string
9
+ uid?: string
10
+ }
11
+ type CreateVersion = (props: CreateVersionProps) => Promise<string>
12
+
13
+ export const createVersion: CreateVersion = async ({
14
+ seedLocalId,
15
+ seedUid,
16
+ seedType,
17
+ uid,
18
+ }) => {
19
+ const appDb = BaseDb.getAppDb()
20
+
21
+ const newVersionLocalId = generateId()
22
+
23
+ await appDb.insert(versions).values({
24
+ localId: newVersionLocalId,
25
+ createdAt: Date.now(),
26
+ seedLocalId,
27
+ seedUid: seedUid ?? 'NULL',
28
+ seedType,
29
+ uid: uid || 'NULL',
30
+ })
31
+
32
+ return newVersionLocalId
33
+ }
@@ -0,0 +1,182 @@
1
+ import { assign, setup } from 'xstate'
2
+ import {
3
+ DB_CHECK_STATUS_EXISTS,
4
+ DB_CHECK_STATUS_UPDATE_PATHS,
5
+ DB_CREATING_SUCCESS,
6
+ DB_MIGRATING_SUCCESS,
7
+ DB_MIGRATING_WAIT,
8
+ DB_VALIDATING_SUCCESS,
9
+ DB_VALIDATING_WAIT,
10
+ DB_WAITING_FOR_FILES_RECEIVED,
11
+ DbState,
12
+ MachineIds,
13
+ } from '../internal/constants'
14
+ import debug from 'debug'
15
+ import { DbServiceContext } from '@/types'
16
+ import { checkStatus } from '@/services/db/actors/checkStatus'
17
+ import { connectToDb } from '@/services/db/actors/connectToDb'
18
+ import { validate } from '@/services/db/actors/validate'
19
+ import { migrate } from '@/services/db/actors/migrate'
20
+ import { waitForFiles } from './actors/waitForFiles'
21
+
22
+ const logger = debug('app:services:db:machine')
23
+
24
+ const {
25
+ CHECKING_STATUS,
26
+ VALIDATING,
27
+ WAITING_FOR_FILES,
28
+ CONNECTING_TO_DB,
29
+ MIGRATING,
30
+ } = DbState
31
+
32
+ const dbMachine = setup({
33
+ types: {
34
+ context: {} as Partial<DbServiceContext>,
35
+ input: {} as Partial<DbServiceContext> | undefined,
36
+ },
37
+ actors: {
38
+ checkStatus,
39
+ validate,
40
+ connectToDb,
41
+ migrate,
42
+ waitForFiles,
43
+ },
44
+ }).createMachine({
45
+ id: MachineIds.DB,
46
+ initial: CHECKING_STATUS,
47
+ context: ({ input }) => input as DbServiceContext,
48
+ on: {
49
+ [DB_WAITING_FOR_FILES_RECEIVED]: {
50
+ actions: assign({
51
+ hasFiles: ({ event }) => {
52
+ logger('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event)
53
+ return true
54
+ },
55
+ }),
56
+ },
57
+ updateHasFiles: {
58
+ target: `.${CHECKING_STATUS}`,
59
+ actions: assign({
60
+ hasFiles: ({ context, event }) => {
61
+ logger('[db/machine] updateHasFiles event:', event)
62
+ logger('[db/machine] updateHasFiles context:', context)
63
+ return event.hasFiles
64
+ },
65
+ }),
66
+ },
67
+ },
68
+ // always: {
69
+ // target: `.${CHECKING_STATUS}`,
70
+ // guard: ({ context, event }) => context.hasFiles && event.type === 'updateHasFiles',
71
+ // },
72
+ states: {
73
+ idle: {
74
+ on: {
75
+ start: CHECKING_STATUS,
76
+ },
77
+ meta: {
78
+ displayText: 'DB starting ...',
79
+ percentComplete: 0,
80
+ },
81
+ },
82
+ [CHECKING_STATUS]: {
83
+ on: {
84
+ [DB_CHECK_STATUS_UPDATE_PATHS]: {
85
+ actions: assign({
86
+ pathToDb: ({ event }) => event.pathToDb,
87
+ pathToDir: ({ event }) => event.pathToDir,
88
+ pathToDbDir: ({ event }) => event.pathToDbDir,
89
+ }),
90
+ },
91
+ [DB_CHECK_STATUS_EXISTS]: CONNECTING_TO_DB,
92
+ },
93
+ invoke: {
94
+ src: 'checkStatus',
95
+ input: ({ context, event }) => ({ context, event }),
96
+ },
97
+ meta: {
98
+ displayText: 'Checking DB status',
99
+ percentComplete: 60,
100
+ },
101
+ },
102
+ [CONNECTING_TO_DB]: {
103
+ on: {
104
+ [DB_CREATING_SUCCESS]: {
105
+ target: VALIDATING,
106
+ actions: assign({
107
+ dbId: ({ event }) => event.dbId,
108
+ }),
109
+ },
110
+ },
111
+ invoke: {
112
+ src: 'connectToDb',
113
+ input: ({ context }) => ({ context }),
114
+ },
115
+ meta: {
116
+ displayText: 'Connecting to local DB',
117
+ percentComplete: 70,
118
+ },
119
+ },
120
+ [VALIDATING]: {
121
+ on: {
122
+ [DB_VALIDATING_SUCCESS]: {
123
+ target: MIGRATING,
124
+ // guard: ({ context }) => context.hasFiles,
125
+ },
126
+ [DB_VALIDATING_WAIT]: {
127
+ target: WAITING_FOR_FILES,
128
+ // guard: ({ context }) => !context.hasFiles,
129
+ },
130
+ },
131
+ invoke: {
132
+ src: 'validate',
133
+ input: ({ context }) => ({ context }),
134
+ },
135
+ meta: {
136
+ displayText: 'Validating DB',
137
+ percentComplete: 80,
138
+ },
139
+ },
140
+ // Here we're waiting for migration and schema files to be downloaded
141
+ [WAITING_FOR_FILES]: {
142
+ on: {
143
+ [DB_WAITING_FOR_FILES_RECEIVED]: {
144
+ target: MIGRATING,
145
+ actions: assign({
146
+ hasFiles: true,
147
+ }),
148
+ },
149
+ [DB_MIGRATING_SUCCESS]: 'ready',
150
+ },
151
+ invoke: {
152
+ src: 'waitForFiles',
153
+ input: ({ context }) => ({ context }),
154
+ },
155
+ },
156
+ [MIGRATING]: {
157
+ on: {
158
+ [DB_MIGRATING_WAIT]: WAITING_FOR_FILES,
159
+ [DB_MIGRATING_SUCCESS]: {
160
+ target: 'ready',
161
+ },
162
+ },
163
+ invoke: {
164
+ src: 'migrate',
165
+ input: ({ context }) => ({ context }),
166
+ },
167
+ meta: {
168
+ displayText: 'Migrating DB',
169
+ percentComplete: 90,
170
+ },
171
+ },
172
+ ready: {
173
+ target: 'idle',
174
+ meta: {
175
+ displayText: 'Wrapping up the db ...',
176
+ percentComplete: 100,
177
+ },
178
+ },
179
+ },
180
+ })
181
+
182
+ export { dbMachine }
@@ -0,0 +1,19 @@
1
+ import { BaseDb } from '@/db/Db/BaseDb'
2
+ import { seeds } from '@/seedSchema'
3
+ import { eq, or } from 'drizzle-orm'
4
+
5
+ type DeleteItemProps = {
6
+ seedLocalId?: string
7
+ seedUid?: string
8
+ }
9
+ type DeleteItem = (props: DeleteItemProps) => Promise<void>
10
+ export const deleteItem: DeleteItem = async ({ seedLocalId, seedUid }) => {
11
+ const appDb = BaseDb.getAppDb()
12
+
13
+ await appDb
14
+ .update(seeds)
15
+ .set({
16
+ _markedForDeletion: 1,
17
+ })
18
+ .where(or(eq(seeds.localId, seedLocalId), eq(seeds.uid, seedUid)))
19
+ }
@@ -0,0 +1,208 @@
1
+ import { syncDbFiles } from '@/services/internal/helpers'
2
+ import { eventEmitter } from '@/eventBus'
3
+ import fs from '@zenfs/core'
4
+ import { ARWEAVE_HOST } from '@/services/internal/constants'
5
+ import { appState } from '@/seedSchema'
6
+ import { eq } from 'drizzle-orm'
7
+ import { getAddressesFromDb } from '@/helpers/db'
8
+ import {
9
+ BaseFileManager,
10
+ } from '@/helpers'
11
+ import { GET_FILES_METADATA } from '@/schema/file/queries'
12
+ import debug from 'debug'
13
+ import { getGlobalService } from '@/services'
14
+ import { waitFor } from 'xstate'
15
+ import { getMetadata } from '@/db/read/getMetadata'
16
+ import { saveMetadata } from '@/db/write/saveMetadata'
17
+ import { GET_TRANSACTION_TAGS } from '@/helpers/ArweaveClient/queries'
18
+ import { saveAppState } from '@/db/write/saveAppState'
19
+ import { BaseDb } from '@/db/Db/BaseDb'
20
+ import { BaseEasClient, BaseQueryClient, BaseArweaveClient } from '@/helpers'
21
+ import { getArweave } from '@/helpers/ArweaveClient'
22
+ import { isBrowser } from '@/helpers/environment'
23
+
24
+
25
+ const logger = debug('app:files:download')
26
+
27
+
28
+ export const downloadAllFilesRequestHandler = async ({
29
+ endpoints,
30
+ eventId,
31
+ }) => {
32
+
33
+ if (!isBrowser()) {
34
+ return
35
+ }
36
+
37
+ await syncDbFiles(endpoints)
38
+
39
+ eventEmitter.emit('fs.downloadAll.success', { eventId })
40
+ eventEmitter.emit('fs.downloadAllBinary.request', { endpoints })
41
+ }
42
+
43
+ export const downloadAllFilesBinaryRequestHandler = async () => {
44
+ let addresses: string[] | undefined
45
+
46
+ if (BaseDb.isAppDbReady()) {
47
+ addresses = await getAddressesFromDb()
48
+ }
49
+
50
+ if (!BaseDb.isAppDbReady()) {
51
+ const globalService = getGlobalService()
52
+ const internalService = globalService.getSnapshot().context.internalService
53
+ if (internalService) {
54
+ await waitFor(internalService, (snapshot) => {
55
+ return snapshot.value === 'ready'
56
+ })
57
+ addresses = await getAddressesFromDb()
58
+ }
59
+ }
60
+
61
+ if (!addresses || addresses.length === 0) {
62
+ return
63
+ }
64
+
65
+ const queryClient = BaseQueryClient.getQueryClient()
66
+ const easClient = BaseEasClient.getEasClient()
67
+
68
+ const { filesMetadata } = await queryClient.fetchQuery({
69
+ queryKey: ['getFilesMetadata', ...addresses],
70
+ queryFn: async () =>
71
+ easClient.request(GET_FILES_METADATA, {
72
+ where: {
73
+ attester: {
74
+ in: addresses,
75
+ },
76
+ schema: {
77
+ is: {
78
+ id: {
79
+ equals:
80
+ '0x55fdefb36fcbbaebeb7d6b41dc3a1a9666e4e42154267c889de064faa7ede517',
81
+ },
82
+ },
83
+ },
84
+ },
85
+ }),
86
+ })
87
+
88
+ await BaseFileManager.createDirIfNotExists('/files')
89
+ await BaseFileManager.createDirIfNotExists('/files/html')
90
+ await BaseFileManager.createDirIfNotExists('/files/json')
91
+ await BaseFileManager.createDirIfNotExists('/files/images')
92
+
93
+ const appDb = BaseDb.getAppDb()
94
+
95
+ if (!appDb) {
96
+ console.warn('[fetchAll/actors] [fetchAllBinaryData] seedDb not available')
97
+ return []
98
+ }
99
+
100
+ const excludedTransactionsQuery = await appDb
101
+ .select()
102
+ .from(appState)
103
+ .where(eq(appState.key, 'excludedTransactions'))
104
+
105
+ let excludedTransactions = new Set<string>()
106
+
107
+ if (excludedTransactionsQuery && excludedTransactionsQuery.length === 1) {
108
+ const valueString = excludedTransactionsQuery[0].value
109
+ if (valueString) {
110
+ const excludedTransactionsArray = JSON.parse(valueString)
111
+ excludedTransactions = new Set(excludedTransactionsArray)
112
+ }
113
+ }
114
+
115
+ const transactionIds = []
116
+
117
+ for (const fileMetadata of filesMetadata) {
118
+ const json = JSON.parse(fileMetadata.decodedDataJson)
119
+ const transactionId = json[0].value.value
120
+ if (excludedTransactions.has(transactionId)) {
121
+ continue
122
+ }
123
+ transactionIds.push(transactionId)
124
+ }
125
+
126
+ const arweave = getArweave()
127
+
128
+ if (!arweave) {
129
+ console.warn(
130
+ '[fetchAll/actors] [fetchAllBinaryData] arweave not available',
131
+ )
132
+ return []
133
+ }
134
+
135
+ const arweaveClient = BaseArweaveClient.getArweaveClient()
136
+
137
+ const transactionIdsToDownload = []
138
+
139
+ for (const transactionId of transactionIds) {
140
+
141
+ try {
142
+ const res = await fetch(
143
+ `https://${ARWEAVE_HOST}/tx/${transactionId}/status`,
144
+ )
145
+
146
+ if (res.status !== 200) {
147
+ logger(
148
+ `[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`,
149
+ )
150
+
151
+ excludedTransactions.add(transactionId)
152
+
153
+ await saveAppState(
154
+ 'excludedTransactions',
155
+ JSON.stringify(Array.from(excludedTransactions)),
156
+ )
157
+
158
+ continue
159
+ }
160
+
161
+ const { tags: tagsResult } = await queryClient.fetchQuery({
162
+ queryKey: ['getTransactionTags', transactionId],
163
+ queryFn: async () =>
164
+ arweaveClient.request(GET_TRANSACTION_TAGS, {
165
+ transactionId,
166
+ }),
167
+ })
168
+
169
+ const tags = tagsResult.tags || []
170
+
171
+ if (tagsResult.tags && tagsResult.tags.length > 0) {
172
+ for (const { name, value } of tags) {
173
+ if (name === 'Content-SHA-256') {
174
+ const metadataRecord = await getMetadata({
175
+ storageTransactionId: transactionId,
176
+ })
177
+
178
+ if (metadataRecord) {
179
+ await saveMetadata(metadataRecord, {
180
+ contentHash: value,
181
+ })
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ transactionIdsToDownload.push(transactionId)
188
+
189
+
190
+
191
+ } catch (error) {
192
+ logger(error)
193
+ }
194
+ }
195
+
196
+ console.log('[download] Calling downloadAllFiles with transactionIdsToDownload', transactionIdsToDownload)
197
+
198
+ await BaseFileManager.downloadAllFiles({
199
+ transactionIds: transactionIdsToDownload,
200
+ arweaveHost: ARWEAVE_HOST,
201
+ excludedTransactions,
202
+ })
203
+
204
+ await BaseFileManager.resizeAllImages({
205
+ width: 480,
206
+ height: 480,
207
+ })
208
+ }
@@ -0,0 +1,78 @@
1
+ import path from 'path'
2
+ import fs from 'fs'
3
+ import pluralize from 'pluralize'
4
+ import { camelCase, snakeCase } from 'lodash-es'
5
+ import * as nunjucks from 'nunjucks'
6
+ import { ILoader } from 'nunjucks'
7
+ import { ModelClassType } from '@/types'
8
+ import { SCHEMA_NJK } from '@/helpers/constants'
9
+ import {
10
+ appGeneratedSchemaDir,
11
+ dotSeedDir,
12
+ templatePath,
13
+ } from '@/node/constants'
14
+ import { getTsImport } from '@/node/helpers'
15
+
16
+ const TemplateLoader: ILoader = {
17
+ getSource: (name: string) => {
18
+ let templateFilePath
19
+ if (name.includes(templatePath)) {
20
+ templateFilePath = name
21
+ } else {
22
+ templateFilePath = path.join(templatePath, path.basename(name))
23
+ }
24
+ const src = fs.readFileSync(templateFilePath, 'utf-8')
25
+
26
+ return {
27
+ path: name,
28
+ src,
29
+ noCache: false,
30
+ }
31
+ },
32
+ }
33
+
34
+ // Configure Nunjucks
35
+ const env = new nunjucks.Environment(TemplateLoader)
36
+
37
+ env.addFilter('camelCase', camelCase)
38
+ env.addFilter('snakeCase', snakeCase)
39
+ env.addFilter('pluralize', pluralize)
40
+
41
+ const generateDrizzleSchemaCode = (
42
+ modelName: string,
43
+ modelClass: ModelClassType,
44
+ ): string => {
45
+ const listProperties = Object.entries(modelClass.schema).filter(
46
+ ([key, propertyDef]) => propertyDef?.dataType === 'List',
47
+ )
48
+
49
+ const filePath = path.join(templatePath, SCHEMA_NJK)
50
+
51
+ const schemaCode = env.render(filePath, {
52
+ modelName,
53
+ modelClass,
54
+ listProperties,
55
+ })
56
+
57
+ return schemaCode
58
+ }
59
+
60
+ export const createDrizzleSchemaFilesFromConfig = async () => {
61
+ const schemaFilePath = path.join(dotSeedDir, 'schema.ts') // Developer created file with model definitions
62
+
63
+ const { models } = await getTsImport<{
64
+ models: Record<string, ModelClassType>
65
+ }>(schemaFilePath)
66
+
67
+ for (const [modelName, modelClass] of Object.entries(models)) {
68
+ const code = generateDrizzleSchemaCode(modelName, modelClass)
69
+
70
+ if (!fs.existsSync(appGeneratedSchemaDir)) {
71
+ fs.mkdirSync(appGeneratedSchemaDir)
72
+ }
73
+
74
+ const filePath = path.join(appGeneratedSchemaDir, `${modelName}Schema.ts`)
75
+
76
+ await fs.promises.writeFile(filePath, code).catch((e) => console.error(e))
77
+ }
78
+ }
@@ -0,0 +1,40 @@
1
+ import { toSnakeCase } from '@/helpers'
2
+ import { getSchemaForItemProperty } from '@/helpers/getSchemaForItemProperty'
3
+
4
+ const schemaUidForSchemaDefinition = new Map<string, string>()
5
+
6
+ export const setSchemaUidForSchemaDefinition = ({ text, schemaUid }) => {
7
+ const propertySnakeCase = toSnakeCase(text)
8
+ schemaUidForSchemaDefinition.set(propertySnakeCase, schemaUid)
9
+ }
10
+
11
+ export const getSchemaUidForSchemaDefinition = (schemaText: string) => {
12
+ const textSnakeCase = toSnakeCase(schemaText)
13
+ if (!schemaUidForSchemaDefinition.has(textSnakeCase)) {
14
+ return
15
+ }
16
+ return schemaUidForSchemaDefinition.get(textSnakeCase)
17
+ }
18
+
19
+ export const fetchSchemaUids = async () => {
20
+ const versionSchemaUid = await getSchemaForItemProperty({
21
+ propertyName: 'version',
22
+ easDataType: 'bytes32',
23
+ })
24
+ if (versionSchemaUid) {
25
+ setSchemaUidForSchemaDefinition({
26
+ text: 'version',
27
+ schemaUid: versionSchemaUid,
28
+ })
29
+ }
30
+ const imageSchemaUid = await getSchemaForItemProperty({
31
+ propertyName: 'image',
32
+ easDataType: 'bytes32',
33
+ })
34
+ if (imageSchemaUid) {
35
+ setSchemaUidForSchemaDefinition({
36
+ text: 'image',
37
+ schemaUid: imageSchemaUid,
38
+ })
39
+ }
40
+ }
@@ -0,0 +1,35 @@
1
+ export const isNode = (): boolean => {
2
+ return (
3
+ typeof process !== 'undefined' &&
4
+ process.versions != null &&
5
+ process.versions.node != null
6
+ )
7
+ }
8
+
9
+ export const isBrowser = (): boolean => {
10
+ return !isElectron() && typeof window !== 'undefined' && typeof window.document !== 'undefined'
11
+ }
12
+
13
+ export const isReactNative = (): boolean => {
14
+ return typeof navigator !== 'undefined' && navigator.product === 'ReactNative'
15
+ }
16
+
17
+ export const isElectron = (): boolean => {
18
+ return typeof process !== 'undefined' && process.versions != null && process.versions.electron != null;
19
+ }
20
+
21
+ export const getEnvironment = (): string => {
22
+ if (isBrowser()) {
23
+ return 'browser'
24
+ }
25
+
26
+ if (isElectron()) {
27
+ return 'electron'
28
+ }
29
+
30
+ if (isReactNative()) {
31
+ return 'react-native'
32
+ }
33
+
34
+ return 'node'
35
+ }
@@ -0,0 +1,5 @@
1
+ import EventEmitter from 'eventemitter3'
2
+
3
+ const eventEmitter = new EventEmitter()
4
+
5
+ export { eventEmitter }
@@ -0,0 +1,14 @@
1
+ import { eventEmitter } from '@/eventBus'
2
+ import debug from 'debug'
3
+
4
+ const logger = debug('app:services:events')
5
+
6
+ const handleServiceSaveState = (event: any) => {
7
+ const { state, serviceId } = event
8
+ logger(`[browser] [service.saveState.request] serviceId: ${serviceId}`)
9
+ localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state))
10
+ }
11
+
12
+ export const setupServicesEventHandlers = () => {
13
+ eventEmitter.addListener('service.saveState.request', handleServiceSaveState)
14
+ }