@basictech/nextjs 0.1.0 → 0.2.0-beta.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.
package/src/sync.ts ADDED
@@ -0,0 +1,75 @@
1
+ import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
2
+
3
+ export function sync() {
4
+ console.log("sync");
5
+
6
+ async function storeFileToOPFS(fileName: string, fileContent: string | ArrayBuffer) {
7
+ if (!('storage' in navigator && 'getDirectory' in navigator.storage)) {
8
+ console.error('OPFS is not supported in this browser');
9
+ return;
10
+ }
11
+
12
+ try {
13
+ const root = await navigator.storage.getDirectory();
14
+
15
+ // Create or open a file
16
+ const fileHandle = await root.getFileHandle(fileName, { create: true });
17
+
18
+ const writable = await fileHandle.createWritable();
19
+
20
+ await writable.write(fileContent);
21
+
22
+ await writable.close();
23
+
24
+ console.log(`File "${fileName}" has been stored in OPFS`);
25
+ } catch (error) {
26
+ console.error('Error storing file to OPFS:', error);
27
+ }
28
+ }
29
+
30
+
31
+ // storeFileToOPFS(fileName, fileContent);
32
+
33
+ const log = console.log;
34
+ const error = console.error;
35
+
36
+ // const start = (sqlite3 : any) => {
37
+ // log('Running SQLite3 version', sqlite3.version.libVersion);
38
+ // const db = new sqlite3.oo1.DB('/mydb.sqlite3', 'ct');
39
+
40
+ // const result = db.exec('SELECT * FROM sqlite_master');
41
+ // // Your SQLite code here.
42
+ // };
43
+
44
+ const initializeSQLite = async () => {
45
+ try {
46
+ log('Loading and initializing SQLite3 module...');
47
+ const sqlite3 = await sqlite3InitModule({
48
+ print: log,
49
+ printErr: error,
50
+ });
51
+ log('Done initializing. Running demo...');
52
+ log(sqlite3.version.libVersion);
53
+
54
+ const db = new sqlite3.oo1.DB('/mydb.sqlite3', 'ct');
55
+ const result = db.exec('SELECT * FROM sqlite_master');
56
+
57
+
58
+
59
+ log(result);
60
+
61
+
62
+ // start(sqlite3);
63
+ } catch (err: any) {
64
+
65
+ error('Initialization error:', err.name, err.message);
66
+ }
67
+ };
68
+
69
+ initializeSQLite();
70
+
71
+
72
+
73
+
74
+
75
+ }
@@ -1,268 +0,0 @@
1
- //@ts-nocheck
2
- import React, { createContext, useContext, useEffect, useState } from 'react'
3
- import { jwtDecode} from 'jwt-decode'
4
-
5
- import { get, add, update, deleteRecord } from './db'
6
-
7
- type User = {
8
- name?: string,
9
- email?: string,
10
- id?: string,
11
- primaryEmailAddress?: {
12
- emailAddress: string
13
- },
14
- fullName?: string
15
- }
16
-
17
- export const BasicContext = createContext<{
18
- unicorn: string,
19
- isLoaded: boolean,
20
- isSignedIn: boolean,
21
- user: User | null,
22
- signout: () => void,
23
- signin: () => void,
24
- getToken: () => Promise<string>,
25
- getSignInLink: () => string,
26
- db: any
27
- }>({
28
- unicorn: "🦄",
29
- isLoaded: false,
30
- isSignedIn: false,
31
- user: null,
32
- signout: () => {},
33
- signin: () => {},
34
- getToken: () => new Promise(() => {}),
35
- getSignInLink: () => "",
36
- db: {}
37
- });
38
-
39
- type Token = {
40
- access_token: string,
41
- token_type: string,
42
- expires_in: number,
43
- refresh: string,
44
- }
45
-
46
- export function BasicProvider({children, project_id}: {children: React.ReactNode, project_id: string}) {
47
- const [isLoaded, setIsLoaded] = useState(false)
48
- const [isSignedIn, setIsSignedIn] = useState(false)
49
- const [token, setToken] = useState<Token | null>(null)
50
- const [authCode, setAuthCode] = useState<string | null>(null)
51
- const [user, setUser] = useState<User>({})
52
-
53
- //todo:
54
- //add random state to signin link & verify random state
55
-
56
- const getSignInLink = () => {
57
- console.log('getting sign in link...')
58
-
59
- const randomState = Math.random().toString(36).substring(7);
60
-
61
- let baseUrl = "https://api.basic.tech/auth/authorize"
62
- baseUrl += `?client_id=${project_id}`
63
- baseUrl += `&redirect_uri=${encodeURIComponent(window.location.href)}`
64
- baseUrl += `&response_type=code`
65
- baseUrl += `&scope=openid`
66
- baseUrl += `&state=1234zyx`
67
-
68
- return baseUrl;
69
- }
70
-
71
- const signin = () => {
72
- console.log('signing in: ', getSignInLink())
73
- const signInLink = getSignInLink()
74
- //todo: change to the other thing?
75
- window.location.href = signInLink;
76
- }
77
-
78
- const signout = () => {
79
- console.log('signing out!')
80
- setUser({})
81
- setIsSignedIn(false)
82
- setToken(null)
83
- setAuthCode(null)
84
- document.cookie = `basic_token=; Secure; SameSite=Strict`;
85
- }
86
-
87
- const getToken = async () : Promise<string> => {
88
- console.log('getting token...')
89
-
90
- if (!token) {
91
- console.log('no token found')
92
- return ''
93
- }
94
-
95
- const decoded = jwtDecode(token?.access_token)
96
- const isExpired = decoded.exp && decoded.exp < Date.now() / 1000
97
-
98
- if (isExpired) {
99
- console.log('token is expired - refreshing ...')
100
- const newToken = await fetchToken(token?.refresh)
101
- return newToken?.access_token || ''
102
- }
103
-
104
- return token?.access_token || ''
105
- }
106
-
107
- function getCookie(name: string) {
108
- let cookieValue = '';
109
- if (document.cookie && document.cookie !== '') {
110
- const cookies = document.cookie.split(';');
111
- for (let i = 0; i < cookies.length; i++) {
112
- const cookie = cookies[i].trim();
113
- if (cookie.substring(0, name.length + 1) === (name + '=')) {
114
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
115
- break;
116
- }
117
- }
118
- }
119
- return cookieValue;
120
- }
121
-
122
- const fetchToken = async (code: string) => {
123
- const token = await fetch('https://api.basic.tech/auth/token', {
124
- method: 'POST',
125
- headers: {
126
- 'Content-Type': 'application/json'
127
- },
128
- body: JSON.stringify({code: code})
129
- })
130
- .then(response => response.json())
131
- .catch(error => console.error('Error:', error))
132
-
133
- if (token.error) {
134
- console.log('error fetching token', token.error)
135
- return
136
- } else {
137
- // console.log('token', token)
138
- setToken(token)
139
- }
140
- return token
141
- }
142
-
143
- useEffect(() => {
144
- let cookie_token = getCookie('basic_token')
145
- if (cookie_token !== '') {
146
- setToken(JSON.parse(cookie_token))
147
- }
148
-
149
- if (window.location.search.includes('code')) {
150
- let code = window.location.search.split('code=')[1].split('&')[0]
151
- // console.log('code found', code)
152
-
153
- // todo: check state is valid
154
- setAuthCode(code) // remove this? dont need to store code?
155
- fetchToken(code)
156
-
157
- window.history.pushState({}, document.title, "/");
158
-
159
- } else {
160
- setIsLoaded(true)
161
- }
162
- }, [])
163
-
164
- useEffect(() => {
165
- async function fetchUser (acc_token: string) {
166
- const user = await fetch('https://api.basic.tech/auth/userInfo', {
167
- method: 'GET',
168
- headers: {
169
- 'Authorization': `Bearer ${acc_token}`
170
- }
171
- })
172
- .then(response => response.json())
173
- .catch(error => console.error('Error:', error))
174
-
175
- if (user.error) {
176
- console.log('error fetching user', user.error)
177
- // refreshToken()
178
- return
179
- } else {
180
- // console.log('user', user)
181
- document.cookie = `basic_token=${JSON.stringify(token)}; Secure; SameSite=Strict`;
182
- setUser(user)
183
- setIsSignedIn(true)
184
- setIsLoaded(true)
185
- }
186
- }
187
-
188
- async function checkToken () {
189
- if (!token) {
190
- console.log('error: no user token found')
191
- return
192
- }
193
-
194
- const decoded = jwtDecode(token?.access_token)
195
- const isExpired = decoded.exp && decoded.exp < Date.now() / 1000
196
-
197
- if (isExpired) {
198
- console.log('token is expired - refreshing ...')
199
- const newToken = await fetchToken(token?.refresh)
200
- fetchUser(newToken.access_token)
201
- } else {
202
- fetchUser(token.access_token)
203
- }
204
- }
205
-
206
- if (token) {
207
- checkToken()
208
- setIsLoaded(true)
209
- }
210
- }, [token])
211
-
212
-
213
-
214
-
215
- const db = (tableName : string) => {
216
- const checkSignIn = () => {
217
- if (!isSignedIn) {
218
- throw new Error('cannot use db. user not logged in.')
219
- }
220
- }
221
-
222
- return {
223
- get: async () => {
224
- checkSignIn()
225
- const tok = await getToken()
226
- return get({projectId: project_id, accountId: user.id, tableName: tableName, token: tok } )
227
- },
228
- add: async (value: any) => {
229
- checkSignIn()
230
- const tok = await getToken()
231
- return add({projectId: project_id, accountId: user.id, tableName: tableName, value: value, token: tok } )
232
- },
233
- update: async (id: string,value : any) => {
234
- checkSignIn()
235
- const tok = await getToken()
236
- return update({projectId: project_id, accountId: user.id, tableName: tableName, id: id, value: value, token: tok } )
237
- },
238
- delete: async (id: string) => {
239
- checkSignIn()
240
- const tok = await getToken()
241
- return deleteRecord({projectId: project_id, accountId: user.id, tableName: tableName, id: id, token: tok } )
242
- }
243
-
244
- }
245
-
246
- }
247
-
248
- return (
249
- <BasicContext.Provider value={{
250
- unicorn: "🦄",
251
- isLoaded,
252
- isSignedIn,
253
- user,
254
- signout,
255
- signin,
256
- getToken,
257
- getSignInLink,
258
- db,
259
-
260
- }}>
261
- {children}
262
- </BasicContext.Provider>
263
- )
264
- }
265
-
266
- export function useBasic() {
267
- return useContext(BasicContext);
268
- }
package/src/db.ts DELETED
@@ -1,55 +0,0 @@
1
- //@ts-nocheck
2
-
3
- const baseUrl = 'https://api.basic.tech';
4
- // const baseUrl = 'http://localhost:3000';
5
-
6
-
7
- async function get({ projectId, accountId, tableName, token }) {
8
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}`;
9
- const response = await fetch(url, {
10
- headers: {
11
- 'Authorization': `Bearer ${token}`
12
- }
13
- });
14
- return response.json();
15
- }
16
-
17
- async function add({ projectId, accountId, tableName, value, token }) {
18
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}`;
19
- const response = await fetch(url, {
20
- method: 'POST',
21
- headers: {
22
- 'Content-Type': 'application/json',
23
- 'Authorization': `Bearer ${token}`
24
- },
25
- body: JSON.stringify({"value": value})
26
- });
27
- return response.json();
28
- }
29
-
30
- async function update({ projectId, accountId, tableName, id, value, token }) {
31
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}/${id}`;
32
- const response = await fetch(url, {
33
- method: 'PATCH',
34
- headers: {
35
- 'Content-Type': 'application/json',
36
- 'Authorization': `Bearer ${token}`
37
- },
38
- body: JSON.stringify({id: id, value: value})
39
- });
40
- return response.json();
41
- }
42
-
43
- async function deleteRecord({ projectId, accountId, tableName, id, token }) {
44
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}/${id}`;
45
- const response = await fetch(url, {
46
- method: 'DELETE',
47
- headers: {
48
- 'Authorization': `Bearer ${token}`
49
- }
50
- });
51
- return response.json();
52
- }
53
-
54
- export { get, add, update, deleteRecord };
55
-