@seedprotocol/sdk 0.2.11 → 0.2.13

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.
@@ -1,278 +1,127 @@
1
- import { EventObject, fromCallback } from 'xstate'
2
- import { GET_SCHEMAS } from '@/Item/queries'
3
- import pluralize from 'pluralize'
4
- import { BaseEasClient } from '@/helpers/EasClient/BaseEasClient'
5
- import { BaseQueryClient } from '@/helpers/QueryClient/BaseQueryClient'
6
- import { toSnakeCase } from '@/helpers'
1
+ import { EventObject, fromCallback, Subscription } from 'xstate'
2
+ import { isNode, isReactNative } from '@/shared'
7
3
  import {
8
- models as modelsTable,
9
- modelUids,
10
- properties,
11
- propertyUids,
12
- } from '@/seedSchema'
13
- import { eq } from 'drizzle-orm'
14
- import { SchemaWhereInput } from '@/graphql/gql/graphql'
15
- import { INTERNAL_DATA_TYPES } from '@/helpers/constants'
16
- import { getAddressesFromDb } from '@/helpers/db'
17
- import { eventEmitter } from '@/eventBus'
4
+ GLOBAL_INITIALIZING_CREATE_ALL_ITEMS_SERVICES,
5
+ GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY,
6
+ GLOBAL_INITIALIZING_SEND_CONFIG,
7
+ } from '@/services/internal/constants'
8
+ import debug from 'debug'
9
+ import { FromCallbackInput, GlobalMachineContext } from '@/types'
18
10
  import { BaseDb } from '@/db/Db/BaseDb'
11
+ import { appState } from '@/seedSchema'
12
+ import { like } from 'drizzle-orm'
13
+ import { fetchSchemaUids } from '@/stores/eas'
19
14
 
20
- import { AllItemsMachineContext, FromCallbackInput } from '@/types'
21
-
22
-
23
- type Times = {
24
- initialize?: {
25
- start: number | null
26
- end: number | null
27
- }
28
- fetchDbData?: {
29
- start: number | null
30
- end: number | null
31
- }
32
- fetchSeeds?: {
33
- start: number | null
34
- end: number | null
35
- }
36
- fetchVersions?: {
37
- start: number | null
38
- end: number | null
39
- }
40
- fetchRelatedItems?: {
41
- start: number | null
42
- end: number | null
43
- }
44
- processItems?: {
45
- start: number | null
46
- end: number | null
47
- }
48
- }
49
-
50
- type InternalDataType = keyof typeof INTERNAL_DATA_TYPES;
15
+ const logger = debug('app:services:global:actors:initialize')
51
16
 
52
17
  export const initialize = fromCallback<
53
18
  EventObject,
54
- FromCallbackInput<AllItemsMachineContext>
55
- >(({ sendBack, input: { context } }) => {
56
- const { modelName, modelAddedToDb, ModelClass, times } = context
57
-
58
- const newTimes: Times = {
59
- initialize: {
60
- start: Date.now(),
61
- end: null,
62
- },
63
- }
64
-
65
- let modelNameLowercase: string | undefined
66
- let modelNamePlural: string | undefined
67
- let queryVariables: Record<string, unknown> | undefined
68
- let appDb
69
-
70
- const _initialize = async () => {
71
- appDb = BaseDb.getAppDb()
19
+ FromCallbackInput<GlobalMachineContext, EventObject>
20
+ >(({ sendBack, input: { event, context } }) => {
21
+ const { internalService, models, endpoints, arweaveDomain } = context
72
22
 
73
- // const rows = await getItemsDataFromDb(modelName)
74
- //
75
- // if (rows && rows.length > 0) {
76
- // for (const itemData of rows) {
77
- // const {
78
- // versionLocalId,
79
- // versionUid,
80
- // createdAt,
81
- // seedLocalId,
82
- // seedUid,
83
- // attestationCreatedAt,
84
- // } = itemData
85
- //
86
- // eventEmitter.emit('item.create.request', {
87
- // itemData: {
88
- // versionLocalId,
89
- // versionUid,
90
- // createdAt,
91
- // seedLocalId,
92
- // seedUid,
93
- // attestationCreatedAt,
94
- // },
95
- // ModelClass,
96
- // })
97
- // }
98
- // }
23
+ const { addresses } = event
99
24
 
100
- modelNameLowercase = modelName.toLowerCase()
101
- modelNamePlural = pluralize(modelNameLowercase!)
25
+ let environment = 'browser'
102
26
 
103
- const queryClient = BaseQueryClient.getQueryClient()
104
- const easClient = BaseEasClient.getEasClient()
105
-
106
- const modelSchemas = await queryClient.fetchQuery({
107
- queryKey: [`getSchemas${modelName}`],
108
- queryFn: async () =>
109
- easClient.request(GET_SCHEMAS, {
110
- where: {
111
- schema: {
112
- equals: `bytes32 ${toSnakeCase(modelName)}`,
113
- },
114
- },
115
- }),
116
- })
27
+ if (isNode()) {
28
+ environment = 'node'
29
+ }
117
30
 
118
- if (
119
- !modelSchemas ||
120
- !modelSchemas.schemas ||
121
- modelSchemas.schemas.length === 0
122
- ) {
123
- throw new Error(`No schema found for ${modelName}`)
124
- }
31
+ if (isReactNative()) {
32
+ environment = 'react-native'
33
+ }
125
34
 
126
- const modelSchema = modelSchemas.schemas[0]
35
+ let internalSubscription: Subscription | undefined
36
+ let easSubscription: Subscription | undefined
127
37
 
128
- if (!modelSchema.id) {
129
- throw new Error(
130
- `No schema ID found for schema ${JSON.stringify(modelSchema)}`,
131
- )
38
+ if (environment === 'browser' && models) {
39
+ const _initFileSystem = async (): Promise<void> => {
40
+ return
41
+ // return new Promise((resolve) => {
42
+ // })
132
43
  }
133
44
 
134
- const foundModels = await appDb
135
- .select({
136
- id: modelsTable.id,
137
- name: modelsTable.name,
138
- uid: modelUids.uid,
45
+ const _initInternal = async (): Promise<void> => {
46
+ return new Promise((resolve) => {
47
+ internalSubscription = internalService.subscribe((snapshot) => {
48
+ logger('[sdk] [internal] snapshot', snapshot)
49
+ if (snapshot.value === 'ready') {
50
+ resolve()
51
+ }
52
+ })
53
+ internalService.send({
54
+ type: 'init',
55
+ endpoints,
56
+ addresses,
57
+ arweaveDomain,
58
+ })
139
59
  })
140
- .from(modelsTable)
141
- .leftJoin(modelUids, eq(modelsTable.id, modelUids.modelId))
142
- .where(eq(modelsTable.name, modelName))
143
- .limit(1)
144
-
145
- const foundModel = foundModels[0]
146
-
147
- if (!foundModel) {
148
- sendBack({ type: 'modelNotFound', modelName })
149
- return
150
60
  }
151
61
 
152
- await appDb
153
- .insert(modelUids)
154
- .values({
155
- modelId: foundModel.id,
156
- uid: modelSchema.id,
157
- })
158
- .onConflictDoNothing()
62
+ const _initAllItemsServices = async (): Promise<void> => {
63
+ const appDb = BaseDb.getAppDb()
159
64
 
160
- const foundPropertiesDb = await appDb
161
- .select({
162
- id: properties.id,
163
- name: properties.name,
164
- dataType: properties.dataType,
165
- uid: propertyUids.uid,
166
- })
167
- .from(properties)
168
- .fullJoin(propertyUids, eq(properties.id, propertyUids.propertyId))
169
- .where(eq(properties.modelId, foundModel.id))
65
+ const rows = await appDb
66
+ .select()
67
+ .from(appState)
68
+ .where(like(appState.key, 'snapshot__%'))
170
69
 
171
- if (foundPropertiesDb && foundPropertiesDb.length > 0) {
172
- const queryVariables: { where: SchemaWhereInput } = {
173
- where: {
174
- OR: [],
175
- },
70
+ const payloadObj = {
71
+ create: {},
72
+ restore: {},
176
73
  }
177
74
 
178
- for (const foundPropertyDb of foundPropertiesDb) {
179
- if (foundPropertyDb.name && foundPropertyDb.dataType) {
180
- const easDatatype = INTERNAL_DATA_TYPES[foundPropertyDb.dataType as InternalDataType].eas
75
+ const modelNamesRestored: string[] = []
181
76
 
182
- let easPropertyName = toSnakeCase(foundPropertyDb.name)
183
-
184
- if (foundPropertyDb.dataType === 'Relation') {
185
- easPropertyName += '_id'
186
- }
187
-
188
- queryVariables.where.OR!.push({
189
- schema: {
190
- equals: `${easDatatype} ${easPropertyName}`,
191
- },
192
- })
77
+ if (rows && rows.length > 0) {
78
+ for (const row of rows) {
79
+ const modelName = row.key.replace('snapshot__', '')
80
+ payloadObj.restore[modelName] = JSON.parse(row.value)
81
+ modelNamesRestored.push(modelName)
193
82
  }
194
83
  }
195
-
196
- const foundPropertySchemas = await queryClient.fetchQuery({
197
- queryKey: [`getPropertySchemas${modelName}`],
198
- queryFn: async () => easClient.request(GET_SCHEMAS, queryVariables),
199
- })
200
-
201
- const tempExclusions = ['html', 'json']
202
-
203
- for (const foundProperty of foundPropertiesDb) {
204
- if (tempExclusions.includes(foundProperty.name)) {
205
- continue
206
- }
207
- const easDatatype = INTERNAL_DATA_TYPES[foundProperty.dataType as InternalDataType].eas
208
-
209
- let easPropertyName = toSnakeCase(foundProperty.name)
210
-
211
- if (foundProperty.dataType === 'Relation') {
212
- easPropertyName += '_id'
213
- }
214
-
215
- const regex = new RegExp(`${easDatatype} ${easPropertyName}`)
216
- const propertySchema = foundPropertySchemas.schemas.find((s) =>
217
- regex.test(s.schema),
218
- )
219
-
220
- if (!propertySchema) {
221
- // TODO: We should create the schema here?
222
- continue
84
+ for (const [modelName, ModelClass] of Object.entries(models)) {
85
+ if (!modelNamesRestored.includes(modelName)) {
86
+ payloadObj.create[modelName] = ModelClass
223
87
  }
224
- await appDb
225
- .insert(propertyUids)
226
- .values({
227
- propertyId: foundProperty.id,
228
- uid: propertySchema.id,
229
- })
230
- .onConflictDoNothing()
231
88
  }
89
+ sendBack({
90
+ type: GLOBAL_INITIALIZING_CREATE_ALL_ITEMS_SERVICES,
91
+ ...payloadObj,
92
+ })
232
93
  }
233
94
 
234
- const addresses = await getAddressesFromDb()
235
-
236
- queryVariables = {
237
- where: {
238
- attester: {
239
- in: addresses,
240
- },
241
- schemaId: {
242
- equals: modelSchema.id,
243
- },
244
- decodedDataJson: {
245
- contains: modelSchema.id,
246
- },
247
- },
95
+ const _initEas = async (): Promise<void> => {
96
+ await fetchSchemaUids()
248
97
  }
249
- }
250
98
 
251
- const initializeHandler = () => {
252
- _initialize().then(() => {
253
- sendBack({
254
- type: 'initializeSuccess',
255
- modelName,
256
- modelNameLowercase,
257
- modelNamePlural,
258
- queryVariables,
259
- })
260
- newTimes!.initialize!.end = Date.now()
261
- sendBack({ type: 'updateTimes', times: newTimes })
99
+ _initFileSystem().then(() => {
100
+ logger('[global/actors] File system initialized')
262
101
  })
263
- }
264
102
 
265
- if (modelAddedToDb) {
266
- initializeHandler()
267
- }
103
+ _initInternal()
104
+ .then(() => {
105
+ return _initAllItemsServices()
106
+ })
107
+ .then(() => {
108
+ return _initEas()
109
+ })
110
+ .then(() => {
111
+ logger('[global/actors] Internal initialized')
112
+ sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY })
113
+ internalSubscription?.unsubscribe()
114
+ })
268
115
 
269
- const dbReadyHandler = (event) => {
270
- initializeHandler()
116
+ // _initEas().then(() => {
117
+ // logger('EAS initialized')
118
+ // })
271
119
  }
272
120
 
273
- eventEmitter.addListener('allDbsLoaded', dbReadyHandler)
121
+ sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment })
274
122
 
275
123
  return () => {
276
- eventEmitter.removeListener('allDbsLoaded', dbReadyHandler)
124
+ internalSubscription?.unsubscribe()
125
+ easSubscription?.unsubscribe()
277
126
  }
278
127
  })
@@ -1,5 +1,5 @@
1
1
  export { Model, Property, ImageSrc, List, Text, Json, Relation, } from './browser/schema';
2
- export { Item, ItemProperty, useItems, useItem, useItemProperties, useCreateItem, useItemProperty, useDeleteItem, useGlobalServiceStatus, useServices, getGlobalService, } from './browser';
2
+ export { Item, ItemProperty, useItems, useItem, useItemProperties, useCreateItem, useItemProperty, useDeleteItem, useGlobalServiceStatus, usePublishItem, usePersistedSnapshots, useServices, useService, getGlobalService, } from './browser';
3
3
  export { getCorrectId, BaseArweaveClient, BaseEasClient, BaseFileManager, BaseQueryClient, } from './helpers';
4
4
  export { eventEmitter, } from './eventBus';
5
5
  export { withSeed } from '@/node/webpack';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,QAAQ,GACT,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EACL,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,OAAO,EACP,iBAAiB,EACjB,aAAa,EACb,eAAe,EACf,aAAa,EACb,sBAAsB,EACtB,WAAW,EACX,gBAAgB,GACjB,MAAM,WAAW,CAAA;AAElB,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,eAAe,EAAE,eAAe,GAAG,MAAM,WAAW,CAAA;AAE7G,OAAO,EACL,YAAY,GACb,MAAM,YAAY,CAAA;AAInB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAGzC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,QAAQ,GACT,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EACL,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,OAAO,EACP,iBAAiB,EACjB,aAAa,EACb,eAAe,EACf,aAAa,EACb,sBAAsB,EACtB,cAAc,EACd,qBAAqB,EACrB,WAAW,EACX,UAAU,EACV,gBAAgB,GACjB,MAAM,WAAW,CAAA;AAElB,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,eAAe,EAAE,eAAe,GAAG,MAAM,WAAW,CAAA;AAE7G,OAAO,EACL,YAAY,GACb,MAAM,YAAY,CAAA;AAInB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAGzC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seedprotocol/sdk",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "The SDK for Seed Protocol",
5
5
  "type": "module",
6
6
  "engines": {
@@ -28,7 +28,7 @@
28
28
  "seed": "dist/bin.js"
29
29
  },
30
30
  "author": "Keith Axline <keith@journodao.xyz>",
31
- "license": "Apache-2.0",
31
+ "license": "MIT",
32
32
  "optionalDependencies": {
33
33
  "fsevents": "^2.3.3"
34
34
  },
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-CVbqPojA.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}