@appwrite.io/console 0.0.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 (228) hide show
  1. package/.github/workflows/publish.yml +18 -0
  2. package/CHANGELOG.md +1 -0
  3. package/LICENSE +12 -0
  4. package/README.md +111 -0
  5. package/dist/cjs/package.json +3 -0
  6. package/dist/esm/package.json +3 -0
  7. package/docs/examples/account/create-anonymous-session.md +18 -0
  8. package/docs/examples/account/create-email-session.md +18 -0
  9. package/docs/examples/account/create-j-w-t.md +18 -0
  10. package/docs/examples/account/create-magic-u-r-l-session.md +18 -0
  11. package/docs/examples/account/create-o-auth2session.md +14 -0
  12. package/docs/examples/account/create-phone-session.md +18 -0
  13. package/docs/examples/account/create-phone-verification.md +18 -0
  14. package/docs/examples/account/create-recovery.md +18 -0
  15. package/docs/examples/account/create-verification.md +18 -0
  16. package/docs/examples/account/create.md +18 -0
  17. package/docs/examples/account/delete-session.md +18 -0
  18. package/docs/examples/account/delete-sessions.md +18 -0
  19. package/docs/examples/account/get-prefs.md +18 -0
  20. package/docs/examples/account/get-session.md +18 -0
  21. package/docs/examples/account/get.md +18 -0
  22. package/docs/examples/account/list-logs.md +18 -0
  23. package/docs/examples/account/list-sessions.md +18 -0
  24. package/docs/examples/account/update-email.md +18 -0
  25. package/docs/examples/account/update-magic-u-r-l-session.md +18 -0
  26. package/docs/examples/account/update-name.md +18 -0
  27. package/docs/examples/account/update-password.md +18 -0
  28. package/docs/examples/account/update-phone-session.md +18 -0
  29. package/docs/examples/account/update-phone-verification.md +18 -0
  30. package/docs/examples/account/update-phone.md +18 -0
  31. package/docs/examples/account/update-prefs.md +18 -0
  32. package/docs/examples/account/update-recovery.md +18 -0
  33. package/docs/examples/account/update-session.md +18 -0
  34. package/docs/examples/account/update-status.md +18 -0
  35. package/docs/examples/account/update-verification.md +18 -0
  36. package/docs/examples/avatars/get-browser.md +14 -0
  37. package/docs/examples/avatars/get-credit-card.md +14 -0
  38. package/docs/examples/avatars/get-favicon.md +14 -0
  39. package/docs/examples/avatars/get-flag.md +14 -0
  40. package/docs/examples/avatars/get-image.md +14 -0
  41. package/docs/examples/avatars/get-initials.md +14 -0
  42. package/docs/examples/avatars/get-q-r.md +14 -0
  43. package/docs/examples/databases/create-boolean-attribute.md +18 -0
  44. package/docs/examples/databases/create-collection.md +18 -0
  45. package/docs/examples/databases/create-datetime-attribute.md +18 -0
  46. package/docs/examples/databases/create-document.md +18 -0
  47. package/docs/examples/databases/create-email-attribute.md +18 -0
  48. package/docs/examples/databases/create-enum-attribute.md +18 -0
  49. package/docs/examples/databases/create-float-attribute.md +18 -0
  50. package/docs/examples/databases/create-index.md +18 -0
  51. package/docs/examples/databases/create-integer-attribute.md +18 -0
  52. package/docs/examples/databases/create-ip-attribute.md +18 -0
  53. package/docs/examples/databases/create-string-attribute.md +18 -0
  54. package/docs/examples/databases/create-url-attribute.md +18 -0
  55. package/docs/examples/databases/create.md +18 -0
  56. package/docs/examples/databases/delete-attribute.md +18 -0
  57. package/docs/examples/databases/delete-collection.md +18 -0
  58. package/docs/examples/databases/delete-document.md +18 -0
  59. package/docs/examples/databases/delete-index.md +18 -0
  60. package/docs/examples/databases/delete.md +18 -0
  61. package/docs/examples/databases/get-attribute.md +18 -0
  62. package/docs/examples/databases/get-collection-usage.md +18 -0
  63. package/docs/examples/databases/get-collection.md +18 -0
  64. package/docs/examples/databases/get-database-usage.md +18 -0
  65. package/docs/examples/databases/get-document.md +18 -0
  66. package/docs/examples/databases/get-index.md +18 -0
  67. package/docs/examples/databases/get-usage.md +18 -0
  68. package/docs/examples/databases/get.md +18 -0
  69. package/docs/examples/databases/list-attributes.md +18 -0
  70. package/docs/examples/databases/list-collection-logs.md +18 -0
  71. package/docs/examples/databases/list-collections.md +18 -0
  72. package/docs/examples/databases/list-document-logs.md +18 -0
  73. package/docs/examples/databases/list-documents.md +18 -0
  74. package/docs/examples/databases/list-indexes.md +18 -0
  75. package/docs/examples/databases/list-logs.md +18 -0
  76. package/docs/examples/databases/list.md +18 -0
  77. package/docs/examples/databases/update-collection.md +18 -0
  78. package/docs/examples/databases/update-document.md +18 -0
  79. package/docs/examples/databases/update.md +18 -0
  80. package/docs/examples/functions/create-build.md +18 -0
  81. package/docs/examples/functions/create-deployment.md +18 -0
  82. package/docs/examples/functions/create-execution.md +18 -0
  83. package/docs/examples/functions/create-variable.md +18 -0
  84. package/docs/examples/functions/create.md +18 -0
  85. package/docs/examples/functions/delete-deployment.md +18 -0
  86. package/docs/examples/functions/delete-variable.md +18 -0
  87. package/docs/examples/functions/delete.md +18 -0
  88. package/docs/examples/functions/get-deployment.md +18 -0
  89. package/docs/examples/functions/get-execution.md +18 -0
  90. package/docs/examples/functions/get-function-usage.md +18 -0
  91. package/docs/examples/functions/get-usage.md +18 -0
  92. package/docs/examples/functions/get-variable.md +18 -0
  93. package/docs/examples/functions/get.md +18 -0
  94. package/docs/examples/functions/list-deployments.md +18 -0
  95. package/docs/examples/functions/list-executions.md +18 -0
  96. package/docs/examples/functions/list-runtimes.md +18 -0
  97. package/docs/examples/functions/list-variables.md +18 -0
  98. package/docs/examples/functions/list.md +18 -0
  99. package/docs/examples/functions/update-deployment.md +18 -0
  100. package/docs/examples/functions/update-variable.md +18 -0
  101. package/docs/examples/functions/update.md +18 -0
  102. package/docs/examples/graphql/mutation.md +18 -0
  103. package/docs/examples/graphql/query.md +18 -0
  104. package/docs/examples/health/get-antivirus.md +18 -0
  105. package/docs/examples/health/get-cache.md +18 -0
  106. package/docs/examples/health/get-d-b.md +18 -0
  107. package/docs/examples/health/get-queue-certificates.md +18 -0
  108. package/docs/examples/health/get-queue-functions.md +18 -0
  109. package/docs/examples/health/get-queue-logs.md +18 -0
  110. package/docs/examples/health/get-queue-webhooks.md +18 -0
  111. package/docs/examples/health/get-storage-local.md +18 -0
  112. package/docs/examples/health/get-time.md +18 -0
  113. package/docs/examples/health/get.md +18 -0
  114. package/docs/examples/locale/get.md +18 -0
  115. package/docs/examples/locale/list-continents.md +18 -0
  116. package/docs/examples/locale/list-countries-e-u.md +18 -0
  117. package/docs/examples/locale/list-countries-phones.md +18 -0
  118. package/docs/examples/locale/list-countries.md +18 -0
  119. package/docs/examples/locale/list-currencies.md +18 -0
  120. package/docs/examples/locale/list-languages.md +18 -0
  121. package/docs/examples/projects/create-domain.md +18 -0
  122. package/docs/examples/projects/create-key.md +18 -0
  123. package/docs/examples/projects/create-platform.md +18 -0
  124. package/docs/examples/projects/create-webhook.md +18 -0
  125. package/docs/examples/projects/create.md +18 -0
  126. package/docs/examples/projects/delete-domain.md +18 -0
  127. package/docs/examples/projects/delete-key.md +18 -0
  128. package/docs/examples/projects/delete-platform.md +18 -0
  129. package/docs/examples/projects/delete-webhook.md +18 -0
  130. package/docs/examples/projects/delete.md +18 -0
  131. package/docs/examples/projects/get-domain.md +18 -0
  132. package/docs/examples/projects/get-key.md +18 -0
  133. package/docs/examples/projects/get-platform.md +18 -0
  134. package/docs/examples/projects/get-usage.md +18 -0
  135. package/docs/examples/projects/get-webhook.md +18 -0
  136. package/docs/examples/projects/get.md +18 -0
  137. package/docs/examples/projects/list-domains.md +18 -0
  138. package/docs/examples/projects/list-keys.md +18 -0
  139. package/docs/examples/projects/list-platforms.md +18 -0
  140. package/docs/examples/projects/list-webhooks.md +18 -0
  141. package/docs/examples/projects/list.md +18 -0
  142. package/docs/examples/projects/update-auth-duration.md +18 -0
  143. package/docs/examples/projects/update-auth-limit.md +18 -0
  144. package/docs/examples/projects/update-auth-sessions-limit.md +18 -0
  145. package/docs/examples/projects/update-auth-status.md +18 -0
  146. package/docs/examples/projects/update-domain-verification.md +18 -0
  147. package/docs/examples/projects/update-key.md +18 -0
  148. package/docs/examples/projects/update-o-auth2.md +18 -0
  149. package/docs/examples/projects/update-platform.md +18 -0
  150. package/docs/examples/projects/update-service-status.md +18 -0
  151. package/docs/examples/projects/update-webhook-signature.md +18 -0
  152. package/docs/examples/projects/update-webhook.md +18 -0
  153. package/docs/examples/projects/update.md +18 -0
  154. package/docs/examples/storage/create-bucket.md +18 -0
  155. package/docs/examples/storage/create-file.md +18 -0
  156. package/docs/examples/storage/delete-bucket.md +18 -0
  157. package/docs/examples/storage/delete-file.md +18 -0
  158. package/docs/examples/storage/get-bucket-usage.md +18 -0
  159. package/docs/examples/storage/get-bucket.md +18 -0
  160. package/docs/examples/storage/get-file-download.md +14 -0
  161. package/docs/examples/storage/get-file-preview.md +14 -0
  162. package/docs/examples/storage/get-file-view.md +14 -0
  163. package/docs/examples/storage/get-file.md +18 -0
  164. package/docs/examples/storage/get-usage.md +18 -0
  165. package/docs/examples/storage/list-buckets.md +18 -0
  166. package/docs/examples/storage/list-files.md +18 -0
  167. package/docs/examples/storage/update-bucket.md +18 -0
  168. package/docs/examples/storage/update-file.md +18 -0
  169. package/docs/examples/teams/create-membership.md +18 -0
  170. package/docs/examples/teams/create.md +18 -0
  171. package/docs/examples/teams/delete-membership.md +18 -0
  172. package/docs/examples/teams/delete.md +18 -0
  173. package/docs/examples/teams/get-membership.md +18 -0
  174. package/docs/examples/teams/get.md +18 -0
  175. package/docs/examples/teams/list-logs.md +18 -0
  176. package/docs/examples/teams/list-memberships.md +18 -0
  177. package/docs/examples/teams/list.md +18 -0
  178. package/docs/examples/teams/update-membership-roles.md +18 -0
  179. package/docs/examples/teams/update-membership-status.md +18 -0
  180. package/docs/examples/teams/update.md +18 -0
  181. package/docs/examples/users/create-argon2user.md +18 -0
  182. package/docs/examples/users/create-bcrypt-user.md +18 -0
  183. package/docs/examples/users/create-m-d5user.md +18 -0
  184. package/docs/examples/users/create-p-h-pass-user.md +18 -0
  185. package/docs/examples/users/create-s-h-a-user.md +18 -0
  186. package/docs/examples/users/create-scrypt-modified-user.md +18 -0
  187. package/docs/examples/users/create-scrypt-user.md +18 -0
  188. package/docs/examples/users/create.md +18 -0
  189. package/docs/examples/users/delete-session.md +18 -0
  190. package/docs/examples/users/delete-sessions.md +18 -0
  191. package/docs/examples/users/delete.md +18 -0
  192. package/docs/examples/users/get-prefs.md +18 -0
  193. package/docs/examples/users/get-usage.md +18 -0
  194. package/docs/examples/users/get.md +18 -0
  195. package/docs/examples/users/list-logs.md +18 -0
  196. package/docs/examples/users/list-memberships.md +18 -0
  197. package/docs/examples/users/list-sessions.md +18 -0
  198. package/docs/examples/users/list.md +18 -0
  199. package/docs/examples/users/update-email-verification.md +18 -0
  200. package/docs/examples/users/update-email.md +18 -0
  201. package/docs/examples/users/update-name.md +18 -0
  202. package/docs/examples/users/update-password.md +18 -0
  203. package/docs/examples/users/update-phone-verification.md +18 -0
  204. package/docs/examples/users/update-phone.md +18 -0
  205. package/docs/examples/users/update-prefs.md +18 -0
  206. package/docs/examples/users/update-status.md +18 -0
  207. package/package.json +40 -0
  208. package/rollup.config.js +31 -0
  209. package/src/client.ts +472 -0
  210. package/src/id.ts +9 -0
  211. package/src/index.ts +17 -0
  212. package/src/models.ts +2540 -0
  213. package/src/permission.ts +22 -0
  214. package/src/query.ts +56 -0
  215. package/src/role.ts +34 -0
  216. package/src/service.ts +30 -0
  217. package/src/services/account.ts +1009 -0
  218. package/src/services/avatars.ts +351 -0
  219. package/src/services/databases.ts +1525 -0
  220. package/src/services/functions.ts +814 -0
  221. package/src/services/graphql.ts +68 -0
  222. package/src/services/health.ts +202 -0
  223. package/src/services/locale.ts +150 -0
  224. package/src/services/projects.ts +1235 -0
  225. package/src/services/storage.ts +691 -0
  226. package/src/services/teams.ts +445 -0
  227. package/src/services/users.ts +1020 -0
  228. package/tsconfig.json +24 -0
@@ -0,0 +1,18 @@
1
+ import { Client, Users } from "@appwrite.io/console";
2
+
3
+ const client = new Client();
4
+
5
+ const users = new Users(client);
6
+
7
+ client
8
+ .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = users.updatePrefs('[USER_ID]', {});
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Users } from "@appwrite.io/console";
2
+
3
+ const client = new Client();
4
+
5
+ const users = new Users(client);
6
+
7
+ client
8
+ .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = users.updateStatus('[USER_ID]', false);
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@appwrite.io/console",
3
+ "homepage": "https://appwrite.io/support",
4
+ "description": "Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API",
5
+ "version": "0.0.1",
6
+ "license": "BSD-3-Clause",
7
+ "main": "dist/cjs/sdk.js",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/esm/sdk.js",
11
+ "require": "./dist/cjs/sdk.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "module": "dist/esm/sdk.js",
16
+ "types": "types/index.d.ts",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/appwrite/sdk-for-console"
20
+ },
21
+ "scripts": {
22
+ "build": "npm run build:types && npm run build:libs",
23
+ "build:types": "tsc --declaration --emitDeclarationOnly --outDir types",
24
+ "build:libs": "rollup -c"
25
+ },
26
+ "devDependencies": {
27
+ "@rollup/plugin-typescript": "8.3.2",
28
+ "playwright": "1.15.0",
29
+ "rollup": "2.75.4",
30
+ "serve-handler": "6.1.0",
31
+ "tslib": "2.4.0",
32
+ "typescript": "4.7.2"
33
+ },
34
+ "dependencies": {
35
+ "cross-fetch": "3.1.5",
36
+ "isomorphic-form-data": "2.0.0"
37
+ },
38
+ "jsdelivr": "dist/iife/sdk.js",
39
+ "unpkg": "dist/iife/sdk.js"
40
+ }
@@ -0,0 +1,31 @@
1
+ import pkg from "./package.json";
2
+ import typescript from "@rollup/plugin-typescript";
3
+
4
+ export default {
5
+ external: Object.keys(pkg.dependencies),
6
+ input: "src/index.ts",
7
+ plugins: [typescript()],
8
+ output: [
9
+ {
10
+ format: "cjs",
11
+ file: pkg.main,
12
+ esModule: false,
13
+ sourcemap: true,
14
+ },
15
+ {
16
+ format: "es",
17
+ file: pkg.module,
18
+ sourcemap: true,
19
+ },
20
+ {
21
+ format: "iife",
22
+ file: pkg.jsdelivr,
23
+ name: "Appwrite",
24
+ extend: true,
25
+ globals: {
26
+ "cross-fetch": "window",
27
+ "FormData": "FormData",
28
+ },
29
+ },
30
+ ],
31
+ };
package/src/client.ts ADDED
@@ -0,0 +1,472 @@
1
+ import 'isomorphic-form-data';
2
+ import { fetch } from 'cross-fetch';
3
+ import { Models } from './models';
4
+ import { Service } from './service';
5
+
6
+ type Payload = {
7
+ [key: string]: any;
8
+ }
9
+
10
+ type Headers = {
11
+ [key: string]: string;
12
+ }
13
+
14
+ type RealtimeResponse = {
15
+ type: 'error' | 'event' | 'connected' | 'response';
16
+ data: RealtimeResponseAuthenticated | RealtimeResponseConnected | RealtimeResponseError | RealtimeResponseEvent<unknown>;
17
+ }
18
+
19
+ type RealtimeRequest = {
20
+ type: 'authentication';
21
+ data: RealtimeRequestAuthenticate;
22
+ }
23
+
24
+ export type RealtimeResponseEvent<T extends unknown> = {
25
+ events: string[];
26
+ channels: string[];
27
+ timestamp: number;
28
+ payload: T;
29
+ }
30
+
31
+ type RealtimeResponseError = {
32
+ code: number;
33
+ message: string;
34
+ }
35
+
36
+ type RealtimeResponseConnected = {
37
+ channels: string[];
38
+ user?: object;
39
+ }
40
+
41
+ type RealtimeResponseAuthenticated = {
42
+ to: string;
43
+ success: boolean;
44
+ user: object;
45
+ }
46
+
47
+ type RealtimeRequestAuthenticate = {
48
+ session: string;
49
+ }
50
+
51
+ type Realtime = {
52
+ socket?: WebSocket;
53
+ timeout?: number;
54
+ url?: string;
55
+ lastMessage?: RealtimeResponse;
56
+ channels: Set<string>;
57
+ subscriptions: Map<number, {
58
+ channels: string[];
59
+ callback: (payload: RealtimeResponseEvent<any>) => void
60
+ }>;
61
+ subscriptionsCounter: number;
62
+ reconnect: boolean;
63
+ reconnectAttempts: number;
64
+ getTimeout: () => number;
65
+ connect: () => void;
66
+ createSocket: () => void;
67
+ cleanUp: (channels: string[]) => void;
68
+ onMessage: (event: MessageEvent) => void;
69
+ }
70
+
71
+ export type UploadProgress = {
72
+ $id: string;
73
+ progress: number;
74
+ sizeUploaded: number;
75
+ chunksTotal: number;
76
+ chunksUploaded: number;
77
+ }
78
+
79
+ class AppwriteException extends Error {
80
+ code: number;
81
+ response: string;
82
+ type: string;
83
+ constructor(message: string, code: number = 0, type: string = '', response: string = '') {
84
+ super(message);
85
+ this.name = 'AppwriteException';
86
+ this.message = message;
87
+ this.code = code;
88
+ this.type = type;
89
+ this.response = response;
90
+ }
91
+ }
92
+
93
+ class Client {
94
+ config = {
95
+ endpoint: 'https://HOSTNAME/v1',
96
+ endpointRealtime: '',
97
+ project: '',
98
+ key: '',
99
+ jwt: '',
100
+ locale: '',
101
+ mode: '',
102
+ };
103
+ headers: Headers = {
104
+ 'x-sdk-name': 'Console',
105
+ 'x-sdk-platform': 'console',
106
+ 'x-sdk-language': 'web',
107
+ 'x-sdk-version': '0.0.1',
108
+ 'X-Appwrite-Response-Format': '1.0.0',
109
+ };
110
+
111
+ /**
112
+ * Set Endpoint
113
+ *
114
+ * Your project endpoint
115
+ *
116
+ * @param {string} endpoint
117
+ *
118
+ * @returns {this}
119
+ */
120
+ setEndpoint(endpoint: string): this {
121
+ this.config.endpoint = endpoint;
122
+ this.config.endpointRealtime = this.config.endpointRealtime || this.config.endpoint.replace('https://', 'wss://').replace('http://', 'ws://');
123
+
124
+ return this;
125
+ }
126
+
127
+ /**
128
+ * Set Realtime Endpoint
129
+ *
130
+ * @param {string} endpointRealtime
131
+ *
132
+ * @returns {this}
133
+ */
134
+ setEndpointRealtime(endpointRealtime: string): this {
135
+ this.config.endpointRealtime = endpointRealtime;
136
+
137
+ return this;
138
+ }
139
+
140
+ /**
141
+ * Set Project
142
+ *
143
+ * Your project ID
144
+ *
145
+ * @param value string
146
+ *
147
+ * @return {this}
148
+ */
149
+ setProject(value: string): this {
150
+ this.headers['X-Appwrite-Project'] = value;
151
+ this.config.project = value;
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Set Key
157
+ *
158
+ * Your secret API key
159
+ *
160
+ * @param value string
161
+ *
162
+ * @return {this}
163
+ */
164
+ setKey(value: string): this {
165
+ this.headers['X-Appwrite-Key'] = value;
166
+ this.config.key = value;
167
+ return this;
168
+ }
169
+
170
+ /**
171
+ * Set JWT
172
+ *
173
+ * Your secret JSON Web Token
174
+ *
175
+ * @param value string
176
+ *
177
+ * @return {this}
178
+ */
179
+ setJWT(value: string): this {
180
+ this.headers['X-Appwrite-JWT'] = value;
181
+ this.config.jwt = value;
182
+ return this;
183
+ }
184
+
185
+ /**
186
+ * Set Locale
187
+ *
188
+ * @param value string
189
+ *
190
+ * @return {this}
191
+ */
192
+ setLocale(value: string): this {
193
+ this.headers['X-Appwrite-Locale'] = value;
194
+ this.config.locale = value;
195
+ return this;
196
+ }
197
+
198
+ /**
199
+ * Set Mode
200
+ *
201
+ * @param value string
202
+ *
203
+ * @return {this}
204
+ */
205
+ setMode(value: string): this {
206
+ this.headers['X-Appwrite-Mode'] = value;
207
+ this.config.mode = value;
208
+ return this;
209
+ }
210
+
211
+
212
+ private realtime: Realtime = {
213
+ socket: undefined,
214
+ timeout: undefined,
215
+ url: '',
216
+ channels: new Set(),
217
+ subscriptions: new Map(),
218
+ subscriptionsCounter: 0,
219
+ reconnect: true,
220
+ reconnectAttempts: 0,
221
+ lastMessage: undefined,
222
+ connect: () => {
223
+ clearTimeout(this.realtime.timeout);
224
+ this.realtime.timeout = window?.setTimeout(() => {
225
+ this.realtime.createSocket();
226
+ }, 50);
227
+ },
228
+ getTimeout: () => {
229
+ switch (true) {
230
+ case this.realtime.reconnectAttempts < 5:
231
+ return 1000;
232
+ case this.realtime.reconnectAttempts < 15:
233
+ return 5000;
234
+ case this.realtime.reconnectAttempts < 100:
235
+ return 10_000;
236
+ default:
237
+ return 60_000;
238
+ }
239
+ },
240
+ createSocket: () => {
241
+ if (this.realtime.channels.size < 1) return;
242
+
243
+ const channels = new URLSearchParams();
244
+ channels.set('project', this.config.project);
245
+ this.realtime.channels.forEach(channel => {
246
+ channels.append('channels[]', channel);
247
+ });
248
+
249
+ const url = this.config.endpointRealtime + '/realtime?' + channels.toString();
250
+
251
+ if (
252
+ url !== this.realtime.url || // Check if URL is present
253
+ !this.realtime.socket || // Check if WebSocket has not been created
254
+ this.realtime.socket?.readyState > WebSocket.OPEN // Check if WebSocket is CLOSING (3) or CLOSED (4)
255
+ ) {
256
+ if (
257
+ this.realtime.socket &&
258
+ this.realtime.socket?.readyState < WebSocket.CLOSING // Close WebSocket if it is CONNECTING (0) or OPEN (1)
259
+ ) {
260
+ this.realtime.reconnect = false;
261
+ this.realtime.socket.close();
262
+ }
263
+
264
+ this.realtime.url = url;
265
+ this.realtime.socket = new WebSocket(url);
266
+ this.realtime.socket.addEventListener('message', this.realtime.onMessage);
267
+ this.realtime.socket.addEventListener('open', _event => {
268
+ this.realtime.reconnectAttempts = 0;
269
+ });
270
+ this.realtime.socket.addEventListener('close', event => {
271
+ if (
272
+ !this.realtime.reconnect ||
273
+ (
274
+ this.realtime?.lastMessage?.type === 'error' && // Check if last message was of type error
275
+ (<RealtimeResponseError>this.realtime?.lastMessage.data).code === 1008 // Check for policy violation 1008
276
+ )
277
+ ) {
278
+ this.realtime.reconnect = true;
279
+ return;
280
+ }
281
+
282
+ const timeout = this.realtime.getTimeout();
283
+ console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason);
284
+
285
+ setTimeout(() => {
286
+ this.realtime.reconnectAttempts++;
287
+ this.realtime.createSocket();
288
+ }, timeout);
289
+ })
290
+ }
291
+ },
292
+ onMessage: (event) => {
293
+ try {
294
+ const message: RealtimeResponse = JSON.parse(event.data);
295
+ this.realtime.lastMessage = message;
296
+ switch (message.type) {
297
+ case 'connected':
298
+ const cookie = JSON.parse(window.localStorage.getItem('cookieFallback') ?? '{}');
299
+ const session = cookie?.[`a_session_${this.config.project}`];
300
+ const messageData = <RealtimeResponseConnected>message.data;
301
+
302
+ if (session && !messageData.user) {
303
+ this.realtime.socket?.send(JSON.stringify(<RealtimeRequest>{
304
+ type: 'authentication',
305
+ data: {
306
+ session
307
+ }
308
+ }));
309
+ }
310
+ break;
311
+ case 'event':
312
+ let data = <RealtimeResponseEvent<unknown>>message.data;
313
+ if (data?.channels) {
314
+ const isSubscribed = data.channels.some(channel => this.realtime.channels.has(channel));
315
+ if (!isSubscribed) return;
316
+ this.realtime.subscriptions.forEach(subscription => {
317
+ if (data.channels.some(channel => subscription.channels.includes(channel))) {
318
+ setTimeout(() => subscription.callback(data));
319
+ }
320
+ })
321
+ }
322
+ break;
323
+ case 'error':
324
+ throw message.data;
325
+ default:
326
+ break;
327
+ }
328
+ } catch (e) {
329
+ console.error(e);
330
+ }
331
+ },
332
+ cleanUp: channels => {
333
+ this.realtime.channels.forEach(channel => {
334
+ if (channels.includes(channel)) {
335
+ let found = Array.from(this.realtime.subscriptions).some(([_key, subscription] )=> {
336
+ return subscription.channels.includes(channel);
337
+ })
338
+
339
+ if (!found) {
340
+ this.realtime.channels.delete(channel);
341
+ }
342
+ }
343
+ })
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Subscribes to Appwrite events and passes you the payload in realtime.
349
+ *
350
+ * @param {string|string[]} channels
351
+ * Channel to subscribe - pass a single channel as a string or multiple with an array of strings.
352
+ *
353
+ * Possible channels are:
354
+ * - account
355
+ * - collections
356
+ * - collections.[ID]
357
+ * - collections.[ID].documents
358
+ * - documents
359
+ * - documents.[ID]
360
+ * - files
361
+ * - files.[ID]
362
+ * - executions
363
+ * - executions.[ID]
364
+ * - functions.[ID]
365
+ * - teams
366
+ * - teams.[ID]
367
+ * - memberships
368
+ * - memberships.[ID]
369
+ * @param {(payload: RealtimeMessage) => void} callback Is called on every realtime update.
370
+ * @returns {() => void} Unsubscribes from events.
371
+ */
372
+ subscribe<T extends unknown>(channels: string | string[], callback: (payload: RealtimeResponseEvent<T>) => void): () => void {
373
+ let channelArray = typeof channels === 'string' ? [channels] : channels;
374
+ channelArray.forEach(channel => this.realtime.channels.add(channel));
375
+
376
+ const counter = this.realtime.subscriptionsCounter++;
377
+ this.realtime.subscriptions.set(counter, {
378
+ channels: channelArray,
379
+ callback
380
+ });
381
+
382
+ this.realtime.connect();
383
+
384
+ return () => {
385
+ this.realtime.subscriptions.delete(counter);
386
+ this.realtime.cleanUp(channelArray);
387
+ this.realtime.connect();
388
+ }
389
+ }
390
+
391
+ async call(method: string, url: URL, headers: Headers = {}, params: Payload = {}): Promise<any> {
392
+ method = method.toUpperCase();
393
+
394
+
395
+ headers = Object.assign({}, this.headers, headers);
396
+
397
+ let options: RequestInit = {
398
+ method,
399
+ headers,
400
+ credentials: 'include'
401
+ };
402
+
403
+ if (typeof window !== 'undefined' && window.localStorage) {
404
+ headers['X-Fallback-Cookies'] = window.localStorage.getItem('cookieFallback') ?? '';
405
+ }
406
+
407
+ if (method === 'GET') {
408
+ for (const [key, value] of Object.entries(Service.flatten(params))) {
409
+ url.searchParams.append(key, value);
410
+ }
411
+ } else {
412
+ switch (headers['content-type']) {
413
+ case 'application/json':
414
+ options.body = JSON.stringify(params);
415
+ break;
416
+
417
+ case 'multipart/form-data':
418
+ let formData = new FormData();
419
+
420
+ for (const key in params) {
421
+ if (Array.isArray(params[key])) {
422
+ params[key].forEach((value: any) => {
423
+ formData.append(key + '[]', value);
424
+ })
425
+ } else {
426
+ formData.append(key, params[key]);
427
+ }
428
+ }
429
+
430
+ options.body = formData;
431
+ delete headers['content-type'];
432
+ break;
433
+ }
434
+ }
435
+
436
+ try {
437
+ let data = null;
438
+ const response = await fetch(url.toString(), options);
439
+
440
+ if (response.headers.get('content-type')?.includes('application/json')) {
441
+ data = await response.json();
442
+ } else {
443
+ data = {
444
+ message: await response.text()
445
+ };
446
+ }
447
+
448
+ if (400 <= response.status) {
449
+ throw new AppwriteException(data?.message, response.status, data?.type, data);
450
+ }
451
+
452
+ const cookieFallback = response.headers.get('X-Fallback-Cookies');
453
+
454
+ if (typeof window !== 'undefined' && window.localStorage && cookieFallback) {
455
+ window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.');
456
+ window.localStorage.setItem('cookieFallback', cookieFallback);
457
+ }
458
+
459
+ return data;
460
+ } catch (e) {
461
+ if (e instanceof AppwriteException) {
462
+ throw e;
463
+ }
464
+ throw new AppwriteException((<Error>e).message);
465
+ }
466
+ }
467
+ }
468
+
469
+ export { Client, AppwriteException };
470
+ export { Query } from './query';
471
+ export type { Models, Payload };
472
+ export type { QueryTypes, QueryTypesList } from './query';
package/src/id.ts ADDED
@@ -0,0 +1,9 @@
1
+ export class ID {
2
+ public static custom(id: string): string {
3
+ return id
4
+ }
5
+
6
+ public static unique(): string {
7
+ return 'unique()'
8
+ }
9
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ export { Client, Query, AppwriteException } from './client';
2
+ export { Account } from './services/account';
3
+ export { Avatars } from './services/avatars';
4
+ export { Databases } from './services/databases';
5
+ export { Functions } from './services/functions';
6
+ export { Graphql } from './services/graphql';
7
+ export { Health } from './services/health';
8
+ export { Locale } from './services/locale';
9
+ export { Projects } from './services/projects';
10
+ export { Storage } from './services/storage';
11
+ export { Teams } from './services/teams';
12
+ export { Users } from './services/users';
13
+ export type { Models, Payload, RealtimeResponseEvent, UploadProgress } from './client';
14
+ export type { QueryTypes, QueryTypesList } from './query';
15
+ export { Permission } from './permission';
16
+ export { Role } from './role';
17
+ export { ID } from './id';