@seedprotocol/sdk 0.1.47 → 0.1.48

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 (141) hide show
  1. package/dist/bin.js.map +1 -1
  2. package/dist/constants-BLctWkrn.js.map +1 -1
  3. package/dist/{index-DWf9Ls94.js → index-DMIKRod-.js} +3995 -3995
  4. package/dist/index-DMIKRod-.js.map +1 -0
  5. package/dist/{index-B2WbNudj.js → index-wKss7188.js} +10 -10
  6. package/dist/index-wKss7188.js.map +1 -0
  7. package/dist/main.js +7 -7
  8. package/dist/{seed.schema.config-mBqth17w.js → seed.schema.config-C0M8Rcti.js} +7 -7
  9. package/dist/seed.schema.config-C0M8Rcti.js.map +1 -0
  10. package/dist/src/AppStateSchema.ts +10 -0
  11. package/dist/src/Attestation.ts +21 -0
  12. package/dist/src/ConfigSchema.ts +15 -0
  13. package/dist/src/ItemProperty.ts +383 -0
  14. package/dist/src/MetadataSchema.ts +28 -0
  15. package/dist/src/ModelSchema.ts +46 -0
  16. package/dist/src/ModelUidSchema.ts +16 -0
  17. package/dist/src/PropertyUidSchema.ts +16 -0
  18. package/dist/src/Schema.ts +17 -0
  19. package/dist/src/SeedSchema.ts +29 -0
  20. package/dist/src/VersionSchema.ts +16 -0
  21. package/dist/src/actors.ts +10 -0
  22. package/dist/src/addModelsToDb.ts +150 -0
  23. package/dist/src/allItems.ts +23 -0
  24. package/dist/src/arweave.ts +37 -0
  25. package/dist/src/browser.app.db.config.ts +27 -0
  26. package/dist/src/browser.seed.db.config.ts +33 -0
  27. package/dist/src/browser.ts +30 -0
  28. package/dist/src/checkStatus.ts +50 -0
  29. package/dist/src/client.ts +85 -0
  30. package/dist/src/configureFs.ts +81 -0
  31. package/dist/src/connectToDb.ts +74 -0
  32. package/dist/src/connectionManager.ts +67 -0
  33. package/dist/src/constants.ts +118 -0
  34. package/dist/src/create.ts +39 -0
  35. package/dist/src/createItem.ts +15 -0
  36. package/dist/src/createItemMachine.ts +37 -0
  37. package/dist/src/createPublishAttempt.ts +16 -0
  38. package/dist/src/createSeeds.ts +24 -0
  39. package/dist/src/createVersion.ts +33 -0
  40. package/dist/src/db.ts +247 -0
  41. package/dist/src/dbMachine.ts +181 -0
  42. package/dist/src/deleteItem.ts +19 -0
  43. package/dist/src/download.ts +289 -0
  44. package/dist/src/drizzle.ts +82 -0
  45. package/dist/src/environment.ts +15 -0
  46. package/dist/src/eventBus.ts +5 -0
  47. package/dist/src/events.ts +14 -0
  48. package/dist/src/fetchDataFromEas.ts +90 -0
  49. package/dist/src/fetchDbData.ts +16 -0
  50. package/dist/src/fetchRelatedItems.ts +179 -0
  51. package/dist/src/fetchSeeds.ts +44 -0
  52. package/dist/src/fetchVersions.ts +41 -0
  53. package/dist/src/files.ts +16 -0
  54. package/dist/src/fragment-masking.ts +87 -0
  55. package/dist/src/fsProxy.ts +36 -0
  56. package/dist/src/getItem.ts +189 -0
  57. package/dist/src/getItemProperties.ts +162 -0
  58. package/dist/src/getItems.ts +75 -0
  59. package/dist/src/getMetadata.ts +40 -0
  60. package/dist/src/getModelSchemas.ts +88 -0
  61. package/dist/src/getSchemaForModel.ts +42 -0
  62. package/dist/src/getSeedData.ts +34 -0
  63. package/dist/src/getVersionData.ts +58 -0
  64. package/dist/src/getVersionsForVersionUids.ts +39 -0
  65. package/dist/src/globalMachine.ts +259 -0
  66. package/dist/src/gql.ts +113 -0
  67. package/dist/src/graphql.ts +3201 -0
  68. package/dist/src/helpers.ts +150 -0
  69. package/dist/src/hydrateExistingItem.ts +137 -0
  70. package/dist/src/hydrateFromDb.ts +254 -0
  71. package/dist/src/hydrateNewItem.ts +34 -0
  72. package/dist/src/index.d.ts +5 -0
  73. package/dist/src/index.ts +21 -0
  74. package/dist/src/init.ts +61 -0
  75. package/dist/src/initialize.ts +127 -0
  76. package/dist/src/internalMachine.ts +220 -0
  77. package/dist/src/item.ts +324 -0
  78. package/dist/src/itemMachineAll.ts +158 -0
  79. package/dist/src/itemMachineSingle.ts +175 -0
  80. package/dist/src/loadAppDb.ts +47 -0
  81. package/dist/src/logger.ts +33 -0
  82. package/dist/src/machine.ts +55 -0
  83. package/dist/src/machines.ts +58 -0
  84. package/dist/src/migrate.ts +288 -0
  85. package/dist/src/model.ts +71 -0
  86. package/dist/src/modelClass.ts +19 -0
  87. package/dist/src/node.app.db.config.ts +40 -0
  88. package/dist/src/prepareDb.ts +34 -0
  89. package/dist/src/preparePublishRequestData.ts +81 -0
  90. package/dist/src/processItems.ts +71 -0
  91. package/dist/src/property.ts +161 -0
  92. package/dist/src/propertyMachine.ts +154 -0
  93. package/dist/src/publish.ts +31 -0
  94. package/dist/src/publishMachine.ts +77 -0
  95. package/dist/src/queries.ts +13 -0
  96. package/dist/src/read.ts +174 -0
  97. package/dist/src/recoverDeletedItem.ts +14 -0
  98. package/dist/src/request.ts +54 -0
  99. package/dist/src/requestAll.ts +157 -0
  100. package/dist/src/resolveRelatedValue.ts +348 -0
  101. package/dist/src/resolveRemoteStorage.ts +87 -0
  102. package/dist/src/save.ts +183 -0
  103. package/dist/src/saveConfig.ts +79 -0
  104. package/dist/src/saveDataToDb.ts +145 -0
  105. package/dist/src/saveMetadata.ts +18 -0
  106. package/dist/src/saveValueToDb.ts +94 -0
  107. package/dist/src/seed.schema.config.ts +25 -0
  108. package/dist/src/seed.ts +37 -0
  109. package/dist/src/seedData.ts +0 -0
  110. package/dist/src/seedProtocol.ts +17 -0
  111. package/dist/src/services.ts +359 -0
  112. package/dist/src/sqlWasmClient.ts +88 -0
  113. package/dist/src/syncDbWithEas.ts +686 -0
  114. package/dist/src/trash.ts +29 -0
  115. package/dist/src/ts-to-proto.ts +101 -0
  116. package/dist/src/types.ts +12 -0
  117. package/dist/src/upload.ts +86 -0
  118. package/dist/src/validate.ts +42 -0
  119. package/dist/src/validateInput.ts +33 -0
  120. package/dist/src/validateItemData.ts +20 -0
  121. package/dist/src/waitForDb.ts +23 -0
  122. package/dist/src/wasm.d.ts +8300 -0
  123. package/dist/src/write.ts +366 -0
  124. package/dist/types/src/browser/db/read/getModelSchemas.d.ts.map +1 -1
  125. package/dist/types/src/browser/item/single/actors/hydrateExistingItem.d.ts +3 -1
  126. package/dist/types/src/browser/item/single/actors/hydrateExistingItem.d.ts.map +1 -1
  127. package/dist/types/src/browser/item/single/actors/saveDataToDb.d.ts +3 -3
  128. package/dist/types/src/browser/item/single/itemMachineSingle.d.ts +3 -3
  129. package/dist/types/src/browser/property/ItemProperty.d.ts +7 -7
  130. package/dist/types/src/browser/property/ItemProperty.d.ts.map +1 -1
  131. package/dist/types/src/browser/property/actors/resolveRemoteStorage.d.ts +3 -3
  132. package/dist/types/src/browser/react/trash.d.ts +1 -1
  133. package/dist/types/src/browser/react/trash.d.ts.map +1 -1
  134. package/dist/types/src/browser/services/db/dbMachine.d.ts +6 -6
  135. package/dist/types/src/browser/services/publish/publishMachine.d.ts +17 -17
  136. package/dist/types/src/types/machines.d.ts +4 -0
  137. package/dist/types/src/types/machines.d.ts.map +1 -1
  138. package/package.json +1 -1
  139. package/dist/index-B2WbNudj.js.map +0 -1
  140. package/dist/index-DWf9Ls94.js.map +0 -1
  141. package/dist/seed.schema.config-mBqth17w.js.map +0 -1
@@ -0,0 +1,183 @@
1
+ import { Attestation } from '@/browser/gql/graphql'
2
+ import { sql } from 'drizzle-orm'
3
+ import { generateId } from '@/shared/helpers'
4
+ import { escapeSqliteString } from '@/shared/helpers/db'
5
+ import { camelCase } from 'lodash-es'
6
+
7
+ import { getVersionsForVersionUids } from '@/browser/db/read/getVersionsForVersionUids'
8
+ import debug from 'debug'
9
+ import { getAppDb } from '@/browser/db/sqlWasmClient'
10
+
11
+ const logger = debug('app:property:save')
12
+
13
+ const relationValuesToExclude = [
14
+ '0x0000000000000000000000000000000000000000000000000000000000000020',
15
+ ]
16
+
17
+ const seedUidToLocalId = new Map<string, string>()
18
+ const seedUidToModelType = new Map<string, string>()
19
+
20
+ const versionUidToLocalId = new Map<string, string>()
21
+ const versionUidToSeedUid = new Map<string, string>()
22
+
23
+ const propertyUidToLocalId = new Map<string, string>()
24
+
25
+ export const savePropertiesToDb = async (properties: Attestation[]) => {
26
+ const appDb = getAppDb()
27
+
28
+ const propertyUids = properties.map((property) => property.id)
29
+ const versionUids = properties.map((property) => property.refUID)
30
+
31
+ const existingRecordsQuery = await appDb.run(
32
+ sql.raw(
33
+ `SELECT uid, local_id
34
+ FROM metadata
35
+ WHERE uid IN ('${propertyUids.join("','")}');`,
36
+ ),
37
+ )
38
+
39
+ const existingRecordsUids = new Set<string>()
40
+
41
+ if (
42
+ existingRecordsQuery &&
43
+ existingRecordsQuery.rows &&
44
+ existingRecordsQuery.rows.length > 0
45
+ ) {
46
+ for (const row of existingRecordsQuery.rows) {
47
+ existingRecordsUids.add(row[0])
48
+ propertyUidToLocalId.set(row[0], row[1])
49
+ }
50
+ }
51
+
52
+ const newProperties = properties.filter(
53
+ (property) => !existingRecordsUids.has(property.id),
54
+ )
55
+
56
+ if (newProperties.length === 0) {
57
+ return { propertyUids }
58
+ }
59
+
60
+ let insertPropertiesQuery = `INSERT INTO metadata (local_id, uid, schema_uid, property_name, property_value,
61
+ eas_data_type, version_uid, version_local_id, seed_uid,
62
+ seed_local_id, model_type, created_at, attestation_created_at,
63
+ attestation_raw)
64
+ VALUES `
65
+
66
+ for (let i = 0; i < newProperties.length; i++) {
67
+ const property = newProperties[i]
68
+ const propertyLocalId = generateId()
69
+ const metadata = JSON.parse(property.decodedDataJson)[0].value
70
+
71
+ let propertyNameSnake = metadata.name
72
+
73
+ if (!propertyNameSnake) {
74
+ propertyNameSnake = metadata.name
75
+ }
76
+
77
+ if (!propertyNameSnake) {
78
+ logger(
79
+ '[item/events] [syncDbWithEas] no propertyName found for property: ',
80
+ property,
81
+ )
82
+ return
83
+ }
84
+
85
+ let isRelation = false
86
+ let refValueType = 'single'
87
+ let refResolvedValue
88
+ let refResolvedDisplayValue
89
+
90
+ if (
91
+ (propertyNameSnake.endsWith('_id') ||
92
+ propertyNameSnake.endsWith('_ids')) &&
93
+ propertyNameSnake !== 'storage_transaction_id' &&
94
+ propertyNameSnake !== 'storage_provider_transaction_id'
95
+ ) {
96
+ isRelation = true
97
+ let isList = false
98
+
99
+ if (Array.isArray(metadata.value)) {
100
+ isList = true
101
+ refValueType = 'list'
102
+
103
+ // const relatedValuesQuery = await appDb.run(
104
+ // sql.raw(
105
+ // `SELECT s.uid, MAX(v.attestation_created_at) as last_published_at
106
+ // FROM seeds s
107
+ // JOIN versions v ON s.local_id = v.seed_local_id
108
+ // JOIN metadata m ON v.local_id = m.version_local_id
109
+ // WHERE s.uid IN ('${metadata.value.join("','")}')
110
+ // AND m.property_name = 'storage_transation_id';`,
111
+ // ),
112
+ // )
113
+ //
114
+ // if (
115
+ // relatedValuesQuery &&
116
+ // relatedValuesQuery.rows &&
117
+ // relatedValuesQuery.rows.length > 0
118
+ // ) {
119
+ // for (const row of relatedValuesQuery.rows) {
120
+ // // relatedSeedUids.add(row[0])
121
+ // }
122
+ // }
123
+ }
124
+
125
+ if (!isList) {
126
+ if (relationValuesToExclude.includes(metadata.value)) {
127
+ continue
128
+ }
129
+ }
130
+ }
131
+
132
+ const versionsData = await getVersionsForVersionUids(versionUids)
133
+
134
+ for (const version of versionsData) {
135
+ const { seedUid, seedLocalId, uid, localId } = version
136
+ versionUidToLocalId.set(uid, localId)
137
+ versionUidToSeedUid.set(uid, seedUid)
138
+ seedUidToLocalId.set(seedUid, seedLocalId)
139
+ }
140
+
141
+ let propertyValue = metadata.value
142
+
143
+ if (typeof propertyValue !== 'string') {
144
+ propertyValue = JSON.stringify(propertyValue)
145
+ }
146
+
147
+ const propertyName = camelCase(propertyNameSnake)
148
+ propertyValue = escapeSqliteString(propertyValue)
149
+ const easDataType = metadata.type
150
+ const versionUid = property.refUID
151
+ const versionLocalId = versionUidToLocalId.get(versionUid)
152
+ const attestationCreatedAt = property.timeCreated * 1000
153
+ const attestationRaw = escapeSqliteString(JSON.stringify(property))
154
+ const seedUid = versionUidToSeedUid.get(versionUid)
155
+ const seedLocalId = seedUidToLocalId.get(seedUid!)
156
+ const modelType = seedUidToModelType.get(seedUid!)
157
+
158
+ const valuesString = `('${propertyLocalId}', '${property.id}', '${property.schemaId}', '${propertyName}', '${propertyValue}', '${easDataType}', '${versionUid}', '${versionLocalId}', '${seedUid}', '${seedLocalId}', '${modelType}',
159
+ ${Date.now()}, ${attestationCreatedAt}, '${attestationRaw}')`
160
+
161
+ if (i < newProperties.length - 1) {
162
+ insertPropertiesQuery += valuesString + ', '
163
+ }
164
+
165
+ if (i === newProperties.length - 1) {
166
+ insertPropertiesQuery += valuesString + ';'
167
+ }
168
+
169
+ propertyUidToLocalId.set(property.id, propertyLocalId)
170
+ }
171
+
172
+ if (insertPropertiesQuery.endsWith('VALUES ')) {
173
+ return { propertyUids }
174
+ }
175
+
176
+ if (insertPropertiesQuery.endsWith(', ')) {
177
+ insertPropertiesQuery = insertPropertiesQuery.slice(0, -2) + ';'
178
+ }
179
+
180
+ await appDb.run(sql.raw(insertPropertiesQuery))
181
+
182
+ return { propertyUids }
183
+ }
@@ -0,0 +1,79 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { INTERNAL_SAVING_CONFIG_SUCCESS } from '@/browser/services/internal/constants'
3
+ import { getAppDb } from '@/browser/db/sqlWasmClient'
4
+ import { sql } from 'drizzle-orm'
5
+ import debug from 'debug'
6
+ import { FromCallbackInput, InternalMachineContext } from '@/types'
7
+ import { appState } from '@/shared/seedSchema'
8
+
9
+ const logger = debug('app:services:internal:actors:saveConfig')
10
+
11
+ export const saveConfig = fromCallback<
12
+ EventObject,
13
+ FromCallbackInput<InternalMachineContext>
14
+ >(({ sendBack, input: { context } }) => {
15
+ if (typeof window === 'undefined') {
16
+ console.error('seedInitBrowser called from non-browser context')
17
+ sendBack({
18
+ type: 'error',
19
+ error: 'Browser method called from non-browser context',
20
+ })
21
+ }
22
+
23
+ const { endpoints, addresses } = context
24
+
25
+ if (!endpoints) {
26
+ throw new Error('saveConfig called with invalid endpoints')
27
+ }
28
+
29
+ const _saveConfig = async (): Promise<void> => {
30
+ // logger('[sdk] [internal/actors] starting _saveConfig')
31
+ const appDb = getAppDb()
32
+ if (!appDb) {
33
+ throw new Error('App DB not found')
34
+ }
35
+ const endpointsValueString = JSON.stringify(endpoints)
36
+ const addressesValueString = JSON.stringify(addresses)
37
+ // TODO: Figure out how to define on conflict with multiple rows added
38
+ try {
39
+ // logger('[sdk] [internal/actors] Saving endpoints to db')
40
+ await appDb
41
+ .insert(appState)
42
+ .values({
43
+ key: 'endpoints',
44
+ value: endpointsValueString,
45
+ })
46
+ .onConflictDoUpdate({
47
+ target: appState.key,
48
+ set: {
49
+ value: endpointsValueString,
50
+ },
51
+ setWhere: sql`key = 'endpoints'`,
52
+ })
53
+ // logger('[sdk] [internal/actors] Saving addresses to db')
54
+ await appDb
55
+ .insert(appState)
56
+ .values({
57
+ key: 'addresses',
58
+ value: addressesValueString,
59
+ })
60
+ .onConflictDoUpdate({
61
+ target: appState.key,
62
+ set: {
63
+ value: addressesValueString,
64
+ },
65
+ setWhere: sql`key = 'addresses'`,
66
+ })
67
+ logger('[sdk] [internal/actors] Should be done saving')
68
+ } catch (error) {
69
+ console.error('Error saving config:', error)
70
+ }
71
+ }
72
+
73
+ _saveConfig().then(() => {
74
+ logger('[sdk] [internal/actors] Successfully saved config')
75
+ return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS })
76
+ })
77
+
78
+ return () => {}
79
+ })
@@ -0,0 +1,145 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { itemMachineSingle } from '@/browser/item/single/itemMachineSingle'
3
+ import { sql } from 'drizzle-orm'
4
+ import { escapeSqliteString } from '@/shared/helpers/db'
5
+ import { generateId } from '@/shared/helpers'
6
+ import { getAppDb } from '@/browser/db/sqlWasmClient'
7
+
8
+ const relatedSnakeCaseToCamelCase = (snakeCase: string): string => {
9
+ let camelCasePropertyName = snakeCase
10
+
11
+ camelCasePropertyName = camelCasePropertyName.replace(/_(id|ids)$/, '')
12
+
13
+ return camelCasePropertyName
14
+ .toLowerCase()
15
+ .replace(/[-_][a-z]/g, (group) => group.slice(-1).toUpperCase())
16
+ }
17
+
18
+ export const saveDataToDb = fromCallback<EventObject, typeof itemMachineSingle>(
19
+ ({ sendBack, input: { context } }) => {
20
+ const {
21
+ modelName,
22
+ modelTableName,
23
+ versionUid,
24
+ versionLocalId,
25
+ seedLocalId,
26
+ propertiesBySchemaUid,
27
+ } = context
28
+
29
+ const _saveDataToDb = async (): Promise<void> => {
30
+ const appDb = getAppDb()
31
+
32
+ // Write fetched data from EAS to the database
33
+ await appDb.run(
34
+ sql.raw(
35
+ `INSERT INTO ${modelTableName} (version_local_id, seed_local_id, version_uid, created_at)
36
+ VALUES ('${versionLocalId}', '${seedLocalId}', '${versionUid}', ${new Date().getTime()});`,
37
+ ),
38
+ )
39
+
40
+ const existingItemQuery = await appDb.run(
41
+ sql.raw(
42
+ `SELECT id, version_local_id, version_uid, seed_local_id, created_at
43
+ FROM ${modelTableName}
44
+ WHERE version_local_id = '${versionLocalId}';`,
45
+ ),
46
+ )
47
+
48
+ let itemDbId
49
+
50
+ if (
51
+ existingItemQuery &&
52
+ existingItemQuery.rows &&
53
+ existingItemQuery.rows.length > 0
54
+ ) {
55
+ itemDbId = existingItemQuery.rows[0][0]
56
+ }
57
+
58
+ if (typeof itemDbId === 'undefined') {
59
+ console.error(
60
+ '[singleItemActors] [saveDataToDb] itemDbId not found in rows: ',
61
+ existingItemQuery.rows,
62
+ )
63
+ return
64
+ }
65
+
66
+ for (const [schemaUid, properties] of Object.entries(
67
+ propertiesBySchemaUid,
68
+ )) {
69
+ for (const property of properties) {
70
+ const json = JSON.parse(property.decodedDataJson)
71
+ const attestationValue = json[0].value
72
+ let propertyValue = attestationValue.value
73
+
74
+ if (typeof propertyValue === 'string') {
75
+ propertyValue = escapeSqliteString(propertyValue)
76
+ }
77
+
78
+ const camelCasePropertyName = relatedSnakeCaseToCamelCase(
79
+ attestationValue.name,
80
+ )
81
+
82
+ let attestationCreatedAt = property.timeCreated * 1000
83
+
84
+ await appDb.run(
85
+ sql.raw(
86
+ `INSERT INTO metadata (uid,
87
+ local_id,
88
+ property_name,
89
+ property_value,
90
+ model_type,
91
+ schema_uid,
92
+ version_uid,
93
+ eas_data_type,
94
+ created_at,
95
+ attestation_created_at)
96
+ VALUES ('${property.id}', '${generateId()}', '${attestationValue.name}', '${propertyValue}',
97
+ '${modelTableName}', '${schemaUid}',
98
+ '${versionUid}',
99
+ '${attestationValue.type}',
100
+ ${new Date().getTime()}, ${attestationCreatedAt}, ${itemDbId})
101
+ ON CONFLICT DO NOTHING;`,
102
+ ),
103
+ )
104
+
105
+ // sendBack({
106
+ // type: 'updateValue',
107
+ // propertyName: camelCasePropertyName,
108
+ // propertyValue,
109
+ // source: 'eas',
110
+ // })
111
+ }
112
+ }
113
+ // const propertiesQuery = (await appDb.run(
114
+ // sql.raw(
115
+ // `SELECT property_name, property_value, schema_uid
116
+ // FROM metadata
117
+ // WHERE version_uid = '${versionUid}'
118
+ // ORDER BY created_at DESC;`,
119
+ // ),
120
+ // )) as { rows: Array<[string, string]> }
121
+
122
+ // propertiesQuery.rows?.forEach((row) => {
123
+ // const propertyName = relatedSnakeCaseToCamelCase(row[0] as string)
124
+ // let propertyValue = row[1] as string
125
+ // const schemaUid = row[2] as string
126
+ // if (isJSONString(propertyValue)) {
127
+ // propertyValue = JSON.parse(propertyValue)
128
+ // }
129
+ // sendBack({
130
+ // type: 'updateValue',
131
+ // propertyName,
132
+ // propertyValue,
133
+ // schemaUid,
134
+ // source: 'db',
135
+ // })
136
+ // })
137
+
138
+ return
139
+ }
140
+
141
+ _saveDataToDb().then(() => {
142
+ sendBack({ type: 'saveDataToDbSuccess' })
143
+ })
144
+ },
145
+ )
@@ -0,0 +1,18 @@
1
+ import { metadata, MetadataType } from '@/shared/seedSchema'
2
+ import { getAppDb } from '../sqlWasmClient'
3
+ import { eq } from 'drizzle-orm'
4
+
5
+ export const saveMetadata = async (
6
+ metadataRecord: Partial<MetadataType>,
7
+ metadataValues: Partial<MetadataType>,
8
+ ) => {
9
+ const appDb = getAppDb()
10
+
11
+ await appDb
12
+ .update(metadata)
13
+ .set({
14
+ ...metadataValues,
15
+ updatedAt: Date.now(),
16
+ })
17
+ .where(eq(metadata.localId, metadataRecord.localId))
18
+ }
@@ -0,0 +1,94 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { propertyMachine } from '@/browser/property/propertyMachine'
3
+ import { createSeed, updateItemPropertyValue } from '@/browser/db/write'
4
+ import { fs } from '@zenfs/core'
5
+ import { getContentUrlFromPath } from '@/browser/helpers'
6
+ import { createVersion } from '@/browser/db/write/createVersion'
7
+
8
+ export const saveValueToDb = fromCallback<EventObject, typeof propertyMachine>(
9
+ ({ sendBack, input: { context, event } }) => {
10
+ const {
11
+ localId,
12
+ propertyName: propertyNameRaw,
13
+ seedLocalId,
14
+ propertyValue: existingValue,
15
+ propertyRecordSchema,
16
+ itemModelName,
17
+ schemaUid,
18
+ } = context
19
+
20
+ let { newValue } = event
21
+
22
+ if (existingValue === newValue) {
23
+ sendBack({ type: 'saveValueToDbSuccess' })
24
+ return
25
+ }
26
+
27
+ const _saveValueToDb = async () => {
28
+ let refResolvedValue
29
+ let refResolvedDisplayValue
30
+ let refSeedType
31
+ let propertyName = propertyNameRaw
32
+ let versionLocalId
33
+
34
+ if (
35
+ propertyRecordSchema &&
36
+ propertyRecordSchema.dataType === 'Relation'
37
+ ) {
38
+ refResolvedValue = newValue
39
+
40
+ if (!propertyName.endsWith('Id')) {
41
+ propertyName = `${propertyName}Id`
42
+ }
43
+
44
+ let fileType
45
+
46
+ const dirs = await fs.promises.readdir('/files')
47
+
48
+ for (const dir of dirs) {
49
+ const files = await fs.promises.readdir(`/files/${dir}`)
50
+ if (files.includes(newValue)) {
51
+ fileType = dir
52
+ break
53
+ }
54
+ }
55
+
56
+ if (fileType === 'images') {
57
+ const filePath = `/files/images/${newValue}`
58
+ refResolvedDisplayValue = await getContentUrlFromPath(filePath)
59
+ refSeedType = 'image'
60
+ newValue = await createSeed({
61
+ type: refSeedType,
62
+ })
63
+ versionLocalId = await createVersion({
64
+ seedLocalId: newValue,
65
+ seedType: refSeedType,
66
+ })
67
+ }
68
+ }
69
+
70
+ await updateItemPropertyValue({
71
+ propertyLocalId: localId,
72
+ propertyName,
73
+ newValue,
74
+ seedLocalId,
75
+ refSeedType,
76
+ refResolvedValue,
77
+ refResolvedDisplayValue,
78
+ versionLocalId,
79
+ modelName: itemModelName,
80
+ schemaUid,
81
+ })
82
+
83
+ sendBack({
84
+ type: 'updateContext',
85
+ propertyValue: newValue,
86
+ renderValue: refResolvedDisplayValue,
87
+ })
88
+ }
89
+
90
+ _saveValueToDb().then(() => {
91
+ sendBack({ type: 'saveValueToDbSuccess' })
92
+ })
93
+ },
94
+ )
@@ -0,0 +1,25 @@
1
+ import { Model, Text } from '@/browser'
2
+
3
+ @Model
4
+ class Seed {
5
+ @Text() uid!: string
6
+ @Text() type!: string
7
+ }
8
+
9
+ @Model
10
+ class Version {
11
+ @Text() seedUid!: string
12
+ @Text() note!: string
13
+ }
14
+
15
+ @Model
16
+ class Metadata {
17
+ @Text() key!: string
18
+ @Text() value!: string
19
+ }
20
+
21
+ export const models = {
22
+ Seed,
23
+ Version,
24
+ Metadata,
25
+ }
@@ -0,0 +1,37 @@
1
+ import { isBrowser, isNode, isReactNative } from '@/shared/environment'
2
+ import { Endpoints, SeedConstructorOptions } from '@/types/types'
3
+ import { Subject } from 'rxjs'
4
+
5
+ type Environment = 'node' | 'browser' | 'react-native'
6
+
7
+ abstract class SeedBase {
8
+ private readonly _env: Environment = 'browser'
9
+ protected _subject: Subject<void> = new Subject<void>()
10
+
11
+ constructor(props: { endpoints: Endpoints }) {
12
+ console.log('Seed constructor called')
13
+ if (isNode()) {
14
+ this._env = 'node'
15
+ }
16
+ if (isBrowser()) {
17
+ this._env = 'browser'
18
+ }
19
+ if (isReactNative()) {
20
+ this._env = 'react-native'
21
+ }
22
+ }
23
+
24
+ async initialize() {}
25
+
26
+ subscribe(callback: (event: any) => void) {
27
+ return this._subject.subscribe(callback)
28
+ }
29
+ }
30
+
31
+ class SeedSync extends SeedBase {
32
+ constructor(props: SeedConstructorOptions) {
33
+ super(props)
34
+ }
35
+ }
36
+
37
+ export { SeedBase, SeedSync }
File without changes
@@ -0,0 +1,17 @@
1
+ import { Attestation } from '@/browser/gql/graphql'
2
+
3
+ export type PropertyToUpdateWithSeed = {
4
+ publishLocalId: string
5
+ propertySchemaUid: string
6
+ }
7
+
8
+ export type PublishRequestData = {
9
+ localId: string
10
+ seedIsRevocable: boolean
11
+ seedSchemaUid: string
12
+ seedUid?: string
13
+ versionSchemaUid: string
14
+ versionUid?: string
15
+ propertiesToUpdate: PropertyToUpdateWithSeed[]
16
+ listOfAttestations: Attestation[]
17
+ }