@superlayer/admin 1.0.67

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 (54) hide show
  1. package/LICENSE.md +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +30 -0
  4. package/dist/commonjs/__types__/typeUtils.d.ts +20 -0
  5. package/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
  6. package/dist/commonjs/__types__/typeUtils.js +5 -0
  7. package/dist/commonjs/__types__/typeUtils.js.map +1 -0
  8. package/dist/commonjs/__types__/typesTests.d.ts +2 -0
  9. package/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
  10. package/dist/commonjs/__types__/typesTests.js +88 -0
  11. package/dist/commonjs/__types__/typesTests.js.map +1 -0
  12. package/dist/commonjs/index.d.ts +608 -0
  13. package/dist/commonjs/index.d.ts.map +1 -0
  14. package/dist/commonjs/index.js +1050 -0
  15. package/dist/commonjs/index.js.map +1 -0
  16. package/dist/commonjs/package.json +3 -0
  17. package/dist/commonjs/polyfill.d.ts +17 -0
  18. package/dist/commonjs/polyfill.d.ts.map +1 -0
  19. package/dist/commonjs/polyfill.js +26 -0
  20. package/dist/commonjs/polyfill.js.map +1 -0
  21. package/dist/commonjs/subscribe.d.ts +39 -0
  22. package/dist/commonjs/subscribe.d.ts.map +1 -0
  23. package/dist/commonjs/subscribe.js +306 -0
  24. package/dist/commonjs/subscribe.js.map +1 -0
  25. package/dist/commonjs/version.d.ts +3 -0
  26. package/dist/commonjs/version.d.ts.map +1 -0
  27. package/dist/commonjs/version.js +5 -0
  28. package/dist/commonjs/version.js.map +1 -0
  29. package/dist/esm/__types__/typeUtils.d.ts +20 -0
  30. package/dist/esm/__types__/typeUtils.d.ts.map +1 -0
  31. package/dist/esm/__types__/typeUtils.js +4 -0
  32. package/dist/esm/__types__/typeUtils.js.map +1 -0
  33. package/dist/esm/__types__/typesTests.d.ts +2 -0
  34. package/dist/esm/__types__/typesTests.d.ts.map +1 -0
  35. package/dist/esm/__types__/typesTests.js +86 -0
  36. package/dist/esm/__types__/typesTests.js.map +1 -0
  37. package/dist/esm/index.d.ts +608 -0
  38. package/dist/esm/index.d.ts.map +1 -0
  39. package/dist/esm/index.js +1037 -0
  40. package/dist/esm/index.js.map +1 -0
  41. package/dist/esm/package.json +3 -0
  42. package/dist/esm/polyfill.d.ts +17 -0
  43. package/dist/esm/polyfill.d.ts.map +1 -0
  44. package/dist/esm/polyfill.js +22 -0
  45. package/dist/esm/polyfill.js.map +1 -0
  46. package/dist/esm/subscribe.d.ts +39 -0
  47. package/dist/esm/subscribe.d.ts.map +1 -0
  48. package/dist/esm/subscribe.js +300 -0
  49. package/dist/esm/subscribe.js.map +1 -0
  50. package/dist/esm/version.d.ts +3 -0
  51. package/dist/esm/version.d.ts.map +1 -0
  52. package/dist/esm/version.js +3 -0
  53. package/dist/esm/version.js.map +1 -0
  54. package/package.json +78 -0
@@ -0,0 +1,1037 @@
1
+ import { validate as uuidValidate } from 'uuid';
2
+ import { tx, lookup, getOps, i, id, txInit, version as coreVersion, InstantAPIError, setInstantWarningsEnabled, InstantError, validateQuery, validateTransactions, createInstantRouteHandler, SSEConnection, InstantStream, } from '@superlayer/core';
3
+ import version from "./version.js";
4
+ import { subscribe, } from "./subscribe.js";
5
+ import { parseCookie } from 'cookie';
6
+ import { EventSource } from '@instantdb/eventsource';
7
+ import { MessageEventPolyfill } from "./polyfill.js";
8
+ import { Webhooks, WebhooksManager, } from '@superlayer/webhooks';
9
+ function configWithDefaults(config) {
10
+ const defaultConfig = {
11
+ apiURI: 'https://api.interfacedb.com',
12
+ };
13
+ const r = { ...defaultConfig, ...config };
14
+ return r;
15
+ }
16
+ function instantConfigWithDefaults(config) {
17
+ const defaultConfig = {
18
+ apiURI: 'https://api.interfacedb.com',
19
+ };
20
+ const r = { ...defaultConfig, ...config };
21
+ if (!r.apiURI) {
22
+ r.apiURI = defaultConfig.apiURI;
23
+ }
24
+ return r;
25
+ }
26
+ function withImpersonation(headers, opts) {
27
+ if ('email' in opts) {
28
+ headers['as-email'] = opts.email;
29
+ }
30
+ else if ('token' in opts) {
31
+ headers['as-token'] = opts.token;
32
+ }
33
+ else if ('guest' in opts) {
34
+ headers['as-guest'] = 'true';
35
+ }
36
+ return headers;
37
+ }
38
+ function validateConfigAndImpersonation(config, impersonationOpts) {
39
+ if (impersonationOpts &&
40
+ ('token' in impersonationOpts || 'guest' in impersonationOpts)) {
41
+ // adminToken is not required for `token` or `guest` impersonation
42
+ return;
43
+ }
44
+ if (config.adminToken) {
45
+ // An adminToken is provided.
46
+ return;
47
+ }
48
+ if (impersonationOpts && 'email' in impersonationOpts) {
49
+ throw new Error('Admin token required. To impersonate users with an email you must pass `adminToken` to `init`.');
50
+ }
51
+ throw new Error('Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.');
52
+ }
53
+ function authorizedHeaders(config, impersonationOpts) {
54
+ validateConfigAndImpersonation(config, impersonationOpts);
55
+ const { adminToken, appId } = config;
56
+ const headers = {
57
+ 'content-type': 'application/json',
58
+ 'app-id': appId,
59
+ };
60
+ if (adminToken) {
61
+ headers.authorization = `Bearer ${adminToken}`;
62
+ }
63
+ return impersonationOpts
64
+ ? withImpersonation(headers, impersonationOpts)
65
+ : headers;
66
+ }
67
+ // NextJS 13 and 14 cache fetch requests by default.
68
+ //
69
+ // Since adminDB.query uses fetch, this means that it would also cache by default.
70
+ //
71
+ // We don't want this behavior. `adminDB.query` should return the latest result by default.
72
+ //
73
+ // To get around this, we set an explicit `cache` header for NextJS 13 and 14.
74
+ // This is no longer needed in NextJS 15 onwards, as the default is `no-store` again.
75
+ // Once NextJS 13 and 14 are no longer common, we can remove this code.
76
+ function isNextJSVersionThatCachesFetchByDefault() {
77
+ return (
78
+ // NextJS 13 onwards added a `__nextPatched` property to the fetch function
79
+ fetch['__nextPatched'] &&
80
+ // NextJS 15 onwards _also_ added a global `next-patch` symbol.
81
+ !globalThis[Symbol.for('next-patch')]);
82
+ }
83
+ function getDefaultFetchOpts() {
84
+ return isNextJSVersionThatCachesFetchByDefault() ? { cache: 'no-store' } : {};
85
+ }
86
+ async function jsonReject(rejectFn, res) {
87
+ const body = await res.text();
88
+ try {
89
+ const json = JSON.parse(body);
90
+ return rejectFn(new InstantAPIError({ status: res.status, body: json }));
91
+ }
92
+ catch (_e) {
93
+ return rejectFn(new InstantAPIError({
94
+ status: res.status,
95
+ body: { type: undefined, message: body },
96
+ }));
97
+ }
98
+ }
99
+ async function jsonFetch(input, init) {
100
+ const defaultFetchOpts = getDefaultFetchOpts();
101
+ const headers = {
102
+ ...(init?.headers || {}),
103
+ 'Instant-Admin-Version': version,
104
+ 'Instant-Core-Version': coreVersion,
105
+ };
106
+ const res = await fetch(input, { ...defaultFetchOpts, ...init, headers });
107
+ if (res.status === 200) {
108
+ const json = await res.json();
109
+ return Promise.resolve(json);
110
+ }
111
+ return jsonReject((x) => Promise.reject(x), res);
112
+ }
113
+ function makeEventSourceWrapper(opts) {
114
+ return class EventSourceWrapper {
115
+ source;
116
+ static OPEN = EventSource.OPEN;
117
+ static CONNECTING = EventSource.CONNECTING;
118
+ static CLOSED = EventSource.CLOSED;
119
+ url;
120
+ constructor(url) {
121
+ this.url = url;
122
+ this.source = this.#createEventSource(url);
123
+ }
124
+ get onopen() {
125
+ return this.source.onopen;
126
+ }
127
+ set onopen(fn) {
128
+ this.source.onopen = fn;
129
+ }
130
+ get onmessage() {
131
+ return this.source.onmessage;
132
+ }
133
+ set onmessage(fn) {
134
+ this.source.onmessage = fn;
135
+ }
136
+ get onerror() {
137
+ return this.source.onerror;
138
+ }
139
+ set onerror(fn) {
140
+ this.source.onerror = fn;
141
+ }
142
+ get readyState() {
143
+ return this.source.readyState;
144
+ }
145
+ close() {
146
+ this.source.close();
147
+ }
148
+ #createEventSource(url) {
149
+ const es = new EventSource(url, {
150
+ messageEvent: MessageEventPolyfill,
151
+ fetch(input, init) {
152
+ return fetch(input, {
153
+ ...init,
154
+ method: 'POST',
155
+ headers: opts.headers,
156
+ body: JSON.stringify({
157
+ 'inference?': opts.inference,
158
+ versions: {
159
+ '@instantdb/admin': version,
160
+ '@instantdb/core': coreVersion,
161
+ },
162
+ }),
163
+ });
164
+ },
165
+ });
166
+ return es;
167
+ }
168
+ };
169
+ }
170
+ /**
171
+ *
172
+ * The first step: init your application!
173
+ *
174
+ * Visit https://interfacedb.com/dash to get your `appId` :)
175
+ *
176
+ * @example
177
+ * import { init } from "@superlayer/admin"
178
+ *
179
+ * const db = init({
180
+ * appId: process.env.INSTANT_APP_ID!,
181
+ * adminToken: process.env.INSTANT_APP_ADMIN_TOKEN
182
+ * })
183
+ *
184
+ * // You can also provide a schema for type safety and editor autocomplete!
185
+ *
186
+ * import { init } from "@superlayer/admin"
187
+ * import schema from ""../instant.schema.ts";
188
+ *
189
+ * const db = init({
190
+ * appId: process.env.INSTANT_APP_ID!,
191
+ * adminToken: process.env.INSTANT_APP_ADMIN_TOKEN,
192
+ * schema,
193
+ * })
194
+ * // To learn more: https://interfacedb.com/docs/modeling-data
195
+ */
196
+ function init(
197
+ // Allows config with missing `useDateObjects`, but keeps `UseDates`
198
+ // as a non-nullable in the InstantConfig type.
199
+ config) {
200
+ if (!config.appId || !uuidValidate(config.appId)) {
201
+ console.warn('warning: Instant Admin DB must be initialized with a valid appId. Received: ' +
202
+ JSON.stringify(config.appId));
203
+ }
204
+ const configStrict = {
205
+ ...config,
206
+ appId: config.appId?.trim(),
207
+ adminToken: config.adminToken?.trim(),
208
+ useDateObjects: (config.useDateObjects ?? false),
209
+ };
210
+ return new InstantAdminDatabase(configStrict);
211
+ }
212
+ /**
213
+ * @deprecated
214
+ * `init_experimental` is deprecated. You can replace it with `init`.
215
+ *
216
+ * @example
217
+ *
218
+ * // Before
219
+ * import { init_experimental } from "@superlayer/admin"
220
+ * const db = init_experimental({ ... });
221
+ *
222
+ * // After
223
+ * import { init } from "@superlayer/admin"
224
+ * const db = init({ ... });
225
+ */
226
+ const init_experimental = init;
227
+ function steps(inputChunks) {
228
+ const chunks = Array.isArray(inputChunks) ? inputChunks : [inputChunks];
229
+ return chunks.flatMap(getOps);
230
+ }
231
+ class Rooms {
232
+ config;
233
+ constructor(config) {
234
+ this.config = config;
235
+ }
236
+ async getPresence(roomType, roomId) {
237
+ const res = await jsonFetch(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(roomType)}&room-id=${roomId}`, {
238
+ method: 'GET',
239
+ headers: authorizedHeaders(this.config),
240
+ });
241
+ return res.sessions || {};
242
+ }
243
+ }
244
+ class Auth {
245
+ config;
246
+ constructor(config) {
247
+ this.config = config;
248
+ this.createToken = this.createToken.bind(this);
249
+ }
250
+ /**
251
+ * Generates a magic code for the user with the given email.
252
+ * This is useful if you want to use your own email provider
253
+ * to send magic codes.
254
+ *
255
+ * @example
256
+ * // Generate a magic code
257
+ * const { code } = await db.auth.generateMagicCode({ email })
258
+ * // Send the magic code to the user with your own email provider
259
+ * await customEmailProvider.sendMagicCode(email, code)
260
+ *
261
+ * @see https://interfacedb.com/docs/backend#custom-magic-codes
262
+ */
263
+ generateMagicCode = async (email) => {
264
+ return jsonFetch(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
265
+ method: 'POST',
266
+ headers: authorizedHeaders(this.config),
267
+ body: JSON.stringify({ email }),
268
+ });
269
+ };
270
+ /**
271
+ * Sends a magic code to the user with the given email.
272
+ * This uses Instant's built-in email provider.
273
+ *
274
+ * @example
275
+ * // Send an email to user with magic code
276
+ * await db.auth.sendMagicCode({ email })
277
+ *
278
+ * @see https://interfacedb.com/docs/backend#custom-magic-codes
279
+ */
280
+ sendMagicCode = async (email) => {
281
+ return jsonFetch(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
282
+ method: 'POST',
283
+ headers: authorizedHeaders(this.config),
284
+ body: JSON.stringify({ email }),
285
+ });
286
+ };
287
+ /**
288
+ * @deprecated Use {@link checkMagicCode} instead to get the `created` field
289
+ * and support `extraFields`.
290
+ *
291
+ * @see https://interfacedb.com/docs/backend#custom-magic-codes
292
+ */
293
+ verifyMagicCode = async (email, code) => {
294
+ const { user } = await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
295
+ method: 'POST',
296
+ headers: authorizedHeaders(this.config),
297
+ body: JSON.stringify({ email, code }),
298
+ });
299
+ return user;
300
+ };
301
+ /**
302
+ * Verifies a magic code and returns the user along with whether
303
+ * the user was newly created. Supports `extraFields` to set custom
304
+ * `$users` properties at signup.
305
+ *
306
+ * @example
307
+ * const { user, created } = await db.auth.checkMagicCode(
308
+ * email,
309
+ * code,
310
+ * { extraFields: { nickname: 'ari' } },
311
+ * );
312
+ *
313
+ * @see https://interfacedb.com/docs/backend#custom-magic-codes
314
+ */
315
+ checkMagicCode = async (email, code, options) => {
316
+ const res = await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
317
+ method: 'POST',
318
+ headers: authorizedHeaders(this.config),
319
+ body: JSON.stringify({
320
+ email,
321
+ code,
322
+ ...(options?.extraFields
323
+ ? { 'extra-fields': options.extraFields }
324
+ : {}),
325
+ }),
326
+ });
327
+ return { user: res.user, created: res.created };
328
+ };
329
+ async createToken(input) {
330
+ const body = typeof input === 'string' ? { email: input } : input;
331
+ const ret = await jsonFetch(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
332
+ method: 'POST',
333
+ headers: authorizedHeaders(this.config),
334
+ body: JSON.stringify(body),
335
+ });
336
+ return ret.user.refresh_token;
337
+ }
338
+ /**
339
+ * Verifies a given token and returns the associated user.
340
+ *
341
+ * This is often useful for writing custom endpoints, where you need
342
+ * to authenticate users.
343
+ *
344
+ * @example
345
+ * app.post('/custom_endpoint', async (req, res) => {
346
+ * const user = await db.auth.verifyToken(req.headers['token'])
347
+ * if (!user) {
348
+ * return res.status(401).send('Uh oh, you are not authenticated')
349
+ * }
350
+ * // ...
351
+ * })
352
+ * @see https://interfacedb.com/docs/backend#custom-endpoints
353
+ */
354
+ verifyToken = async (token) => {
355
+ const res = await jsonFetch(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
356
+ method: 'POST',
357
+ headers: { 'content-type': 'application/json' },
358
+ body: JSON.stringify({
359
+ 'app-id': this.config.appId,
360
+ 'refresh-token': token,
361
+ }),
362
+ });
363
+ return res.user;
364
+ };
365
+ /**
366
+ * Retrieves an app user by id, email, or refresh token.
367
+ * Resolves to `null` when no user matches; throws on malformed
368
+ * input or auth errors.
369
+ *
370
+ * @example
371
+ * const user = await db.auth.getUser({ email });
372
+ * if (!user) {
373
+ * console.log("No user found");
374
+ * return;
375
+ * }
376
+ * console.log("Found user:", user);
377
+ *
378
+ * @see https://interfacedb.com/docs/backend#retrieve-a-user
379
+ */
380
+ getUser = async (params) => {
381
+ const qs = new URLSearchParams(Object.entries(params)).toString();
382
+ const response = await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${qs}`, {
383
+ method: 'GET',
384
+ headers: authorizedHeaders(this.config),
385
+ });
386
+ return response.user;
387
+ };
388
+ /**
389
+ * Deletes an app user by id, email, or refresh token.
390
+ * Resolves to `null` when no user matches; throws on malformed
391
+ * input or auth errors.
392
+ *
393
+ * NB: This _only_ deletes the user; it does not delete all user data.
394
+ * You will need to handle this manually.
395
+ *
396
+ * @example
397
+ * const deletedUser = await db.auth.deleteUser({ email });
398
+ * if (!deletedUser) {
399
+ * console.log("No user found to delete");
400
+ * return;
401
+ * }
402
+ * console.log("Deleted user:", deletedUser);
403
+ *
404
+ * @see https://interfacedb.com/docs/backend#delete-a-user
405
+ */
406
+ deleteUser = async (params) => {
407
+ const qs = new URLSearchParams(Object.entries(params)).toString();
408
+ const response = await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${qs}`, {
409
+ method: 'DELETE',
410
+ headers: authorizedHeaders(this.config),
411
+ });
412
+ return response.deleted;
413
+ };
414
+ async signOut(input) {
415
+ // If input is a string, we assume it's an email.
416
+ // This is because of backwards compatibility: we used to only
417
+ // accept email strings. Eventually we can remove this
418
+ const params = typeof input === 'string' ? { email: input } : input;
419
+ const config = this.config;
420
+ await jsonFetch(`${config.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
421
+ method: 'POST',
422
+ headers: authorizedHeaders(config),
423
+ body: JSON.stringify(params),
424
+ });
425
+ }
426
+ /**
427
+ * Get instant user from Request
428
+ *
429
+ * Reads cookies and gets a validated user
430
+ * @param req The request containing a cookie synced with createInstantRouteHandler
431
+ * @param opts Allow disabling validation of refresh token
432
+ */
433
+ getUserFromRequest = async (req, opts) => {
434
+ const cookieHeader = req.headers.get('cookie') || '';
435
+ const parsedCookie = parseCookie(cookieHeader);
436
+ const cookieName = 'instant_user_' + this.config.appId;
437
+ if (!parsedCookie[cookieName]) {
438
+ return null;
439
+ }
440
+ const value = parsedCookie[cookieName];
441
+ const user = JSON.parse(value);
442
+ if (!user?.refresh_token) {
443
+ return null;
444
+ }
445
+ if (opts?.disableValidation) {
446
+ return user;
447
+ }
448
+ const verified = await this.verifyToken(user.refresh_token);
449
+ return verified;
450
+ };
451
+ }
452
+ const isNodeReadable = (v) => v &&
453
+ typeof v === 'object' &&
454
+ typeof v.pipe === 'function' &&
455
+ typeof v.read === 'function';
456
+ const isWebReadable = (v) => v && typeof v.getReader === 'function';
457
+ /**
458
+ * Functions to manage file storage.
459
+ */
460
+ class Storage {
461
+ config;
462
+ impersonationOpts;
463
+ constructor(config, impersonationOpts) {
464
+ this.config = config;
465
+ this.impersonationOpts = impersonationOpts;
466
+ }
467
+ /**
468
+ * Uploads file at the provided path. Accepts a Buffer or a Readable stream.
469
+ *
470
+ * @see https://interfacedb.com/docs/storage
471
+ * @example
472
+ * const buffer = fs.readFileSync('demo.png');
473
+ * const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer);
474
+ */
475
+ uploadFile = async (path, file, metadata = {}) => {
476
+ const headers = {
477
+ ...authorizedHeaders(this.config, this.impersonationOpts),
478
+ path,
479
+ };
480
+ if (metadata.contentDisposition) {
481
+ headers['content-disposition'] = metadata.contentDisposition;
482
+ }
483
+ // headers.content-type will become "undefined" (string)
484
+ // if not removed from the object
485
+ delete headers['content-type'];
486
+ if (metadata.contentType) {
487
+ headers['content-type'] = metadata.contentType;
488
+ }
489
+ let duplex;
490
+ if (isNodeReadable(file)) {
491
+ duplex = 'half'; // one-way stream
492
+ }
493
+ if (isNodeReadable(file) || isWebReadable(file)) {
494
+ if (!metadata.fileSize) {
495
+ throw new Error('fileSize is required in metadata when uploading streams');
496
+ }
497
+ headers['content-length'] = metadata.fileSize.toString();
498
+ }
499
+ let options = {
500
+ method: 'PUT',
501
+ headers,
502
+ body: file,
503
+ ...(duplex && { duplex }),
504
+ };
505
+ return jsonFetch(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`, options);
506
+ };
507
+ /**
508
+ * Deletes a file by its path name (e.g. "photos/demo.png").
509
+ *
510
+ * @deprecated Use `db.transact` to delete files instead:
511
+ * @example
512
+ * // Delete by id
513
+ * await db.transact(db.tx.$files[fileId].delete());
514
+ *
515
+ * // Delete by path
516
+ * await db.transact(db.tx.$files[lookup('path', 'photos/demo.png')].delete());
517
+ *
518
+ * @see https://interfacedb.com/docs/storage
519
+ */
520
+ delete = async (pathname) => {
521
+ return jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(pathname)}`, {
522
+ method: 'DELETE',
523
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
524
+ });
525
+ };
526
+ /**
527
+ * Deletes multiple files by their path names.
528
+ *
529
+ * @deprecated Use `db.transact` to delete files instead:
530
+ * @example
531
+ * // Delete multiple files by path
532
+ * const paths = ['images/1.png', 'images/2.png', 'images/3.png'];
533
+ * await db.transact(paths.map(p => db.tx.$files[lookup('path', p)].delete()));
534
+ *
535
+ * @see https://interfacedb.com/docs/storage
536
+ */
537
+ deleteMany = async (pathnames) => {
538
+ return jsonFetch(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
539
+ method: 'POST',
540
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
541
+ body: JSON.stringify({ filenames: pathnames }),
542
+ });
543
+ };
544
+ /**
545
+ * @deprecated. This method will be removed in the future. Use `uploadFile`
546
+ * instead
547
+ */
548
+ upload = async (pathname, file, metadata = {}) => {
549
+ const { data: presignedUrl } = await jsonFetch(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
550
+ method: 'POST',
551
+ headers: authorizedHeaders(this.config),
552
+ body: JSON.stringify({
553
+ app_id: this.config.appId,
554
+ filename: pathname,
555
+ }),
556
+ });
557
+ const headers = {};
558
+ const contentType = metadata.contentType;
559
+ if (contentType) {
560
+ headers['Content-Type'] = contentType;
561
+ }
562
+ const { ok } = await fetch(presignedUrl, {
563
+ method: 'PUT',
564
+ body: file,
565
+ headers,
566
+ });
567
+ return ok;
568
+ };
569
+ /**
570
+ * @deprecated. This method will be removed in the future. Use `query` instead
571
+ * @example
572
+ * const files = await db.query({ $files: {}})
573
+ */
574
+ list = async () => {
575
+ const { data } = await jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
576
+ method: 'GET',
577
+ headers: authorizedHeaders(this.config),
578
+ });
579
+ return data;
580
+ };
581
+ /**
582
+ * @deprecated. getDownloadUrl will be removed in the future.
583
+ * Use `query` instead to query and fetch for valid urls
584
+ *
585
+ * db.useQuery({
586
+ * $files: {
587
+ * $: {
588
+ * where: {
589
+ * path: "moop.png"
590
+ * }
591
+ * }
592
+ * }
593
+ * })
594
+ */
595
+ getDownloadUrl = async (pathname) => {
596
+ const { data } = await jsonFetch(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(pathname)}`, {
597
+ method: 'GET',
598
+ headers: authorizedHeaders(this.config),
599
+ });
600
+ return data;
601
+ };
602
+ }
603
+ /**
604
+ * Functions to manage streams.
605
+ */
606
+ class Streams {
607
+ #ensureInstantStream;
608
+ constructor(ensureInstantStream) {
609
+ this.#ensureInstantStream = ensureInstantStream;
610
+ }
611
+ /**
612
+ * Creates a new ReadableStream for the given clientId.
613
+ *
614
+ * @example
615
+ * const stream = db.streams.createReadStream({clientId: clientId})
616
+ * for await (const chunk of stream) {
617
+ * console.log(chunk);
618
+ * }
619
+ */
620
+ createReadStream = (opts) => {
621
+ return this.#ensureInstantStream().createReadStream(opts);
622
+ };
623
+ /**
624
+ * Creates a new WritableStream for the given clientId.
625
+ *
626
+ * @example
627
+ * const writeStream = db.streams.createWriteStream({clientId: clientId})
628
+ * const writer = writeStream.getWriter();
629
+ * writer.write('Hello world');
630
+ * writer.close();
631
+ */
632
+ createWriteStream = (opts) => {
633
+ return this.#ensureInstantStream().createWriteStream(opts);
634
+ };
635
+ }
636
+ function createLogger(isEnabled, baseLogger = console) {
637
+ return {
638
+ info: isEnabled ? (...args) => baseLogger.info(...args) : () => { },
639
+ debug: isEnabled ? (...args) => baseLogger.debug(...args) : () => { },
640
+ error: isEnabled ? (...args) => baseLogger.error(...args) : () => { },
641
+ };
642
+ }
643
+ /**
644
+ *
645
+ * The first step: init your application!
646
+ *
647
+ * Visit https://interfacedb.com/dash to get your `appId` and `adminToken` :)
648
+ *
649
+ * @example
650
+ * const db = init({ appId: "my-app-id", adminToken: "my-admin-token" })
651
+ */
652
+ class InstantAdminDatabase {
653
+ config;
654
+ auth;
655
+ storage;
656
+ streams;
657
+ rooms;
658
+ impersonationOpts;
659
+ webhooks;
660
+ #sseConnection = null;
661
+ #sseBackoff = 0;
662
+ #instantStream = null;
663
+ #log;
664
+ tx = txInit();
665
+ constructor(_config) {
666
+ this.config = instantConfigWithDefaults(_config);
667
+ this.auth = new Auth(this.config);
668
+ this.storage = new Storage(this.config, this.impersonationOpts);
669
+ this.streams = new Streams(this.#ensureInstantStream.bind(this));
670
+ this.rooms = new Rooms(this.config);
671
+ this.webhooks = new Webhooks(this.config, jsonFetch);
672
+ this.#log = createLogger(!!this.config.verbose, this.config.logger);
673
+ }
674
+ /**
675
+ * Sometimes you want to scope queries to a specific user.
676
+ *
677
+ * You can provide a user's auth token, email, or impersonate a guest.
678
+ *
679
+ * @see https://interfacedb.com/docs/backend#impersonating-users
680
+ * @example
681
+ * await db.asUser({email: "stopa@instantdb.com"}).query({ goals: {} })
682
+ */
683
+ asUser = (opts) => {
684
+ const newClient = new InstantAdminDatabase({
685
+ ...this.config,
686
+ });
687
+ newClient.impersonationOpts = opts;
688
+ newClient.storage = new Storage(this.config, opts);
689
+ return newClient;
690
+ };
691
+ /**
692
+ * Use this to query your data!
693
+ *
694
+ * @see https://interfacedb.com/docs/instaql
695
+ *
696
+ * @example
697
+ * // fetch all goals
698
+ * await db.query({ goals: {} })
699
+ *
700
+ * // goals where the title is "Get Fit"
701
+ * await db.query({ goals: { $: { where: { title: "Get Fit" } } } })
702
+ *
703
+ * // all goals, _alongside_ their todos
704
+ * await db.query({ goals: { todos: {} } })
705
+ */
706
+ query = (query, opts = {}) => {
707
+ if (query && opts && 'ruleParams' in opts) {
708
+ query = { $$ruleParams: opts['ruleParams'], ...query };
709
+ }
710
+ if (!this.config.disableValidation) {
711
+ validateQuery(query, this.config.schema);
712
+ }
713
+ const fetchOpts = opts.fetchOpts || {};
714
+ const fetchOptsHeaders = fetchOpts['headers'] || {};
715
+ return jsonFetch(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
716
+ ...fetchOpts,
717
+ method: 'POST',
718
+ headers: {
719
+ ...fetchOptsHeaders,
720
+ ...authorizedHeaders(this.config, this.impersonationOpts),
721
+ },
722
+ body: JSON.stringify({
723
+ query: query,
724
+ 'inference?': !!this.config.schema,
725
+ }),
726
+ });
727
+ };
728
+ /**
729
+ * Use this to to get a live view of your data!
730
+ *
731
+ * @see https://www.interfacedb.com/docs/backend
732
+ *
733
+ * @example
734
+ * // create a subscription to a query
735
+ * const query = { goals: { $: { where: { title: "Get Fit" } } } }
736
+ * const sub = db.subscribeQuery(query);
737
+ *
738
+ * // iterate through the results with an async iterator
739
+ * for await (const payload of sub) {
740
+ * if (payload.error) {
741
+ * console.log(payload.error);
742
+ * // Stop the subscription
743
+ * sub.close();
744
+ * } else {
745
+ * console.log(payload.data);
746
+ * }
747
+ * }
748
+ *
749
+ * // Stop the subscription
750
+ * sub.close();
751
+ *
752
+ * // Create a subscription with a callback
753
+ * const sub = db.subscribeQuery(query, (payload) => {
754
+ * if (payload.error) {
755
+ * console.log(payload.error);
756
+ * // Stop the subscription
757
+ * sub.close();
758
+ * } else {
759
+ * console.log(payload.data);
760
+ * }
761
+ * });
762
+ */
763
+ subscribeQuery(query, cb, opts = {}) {
764
+ if (query && opts && 'ruleParams' in opts) {
765
+ query = { $$ruleParams: opts['ruleParams'], ...query };
766
+ }
767
+ if (!this.config.disableValidation) {
768
+ validateQuery(query, this.config.schema);
769
+ }
770
+ const fetchOpts = opts.fetchOpts || {};
771
+ const fetchOptsHeaders = fetchOpts['headers'] || {};
772
+ const headers = {
773
+ ...fetchOptsHeaders,
774
+ ...authorizedHeaders(this.config, this.impersonationOpts),
775
+ };
776
+ const inference = !!this.config.schema;
777
+ return subscribe(query, cb, {
778
+ headers,
779
+ inference,
780
+ apiURI: this.config.apiURI,
781
+ });
782
+ }
783
+ /**
784
+ * Use this to write data! You can create, update, delete, and link objects
785
+ *
786
+ * @see https://interfacedb.com/docs/instaml
787
+ *
788
+ * @example
789
+ * // Create a new object in the `goals` namespace
790
+ * const goalId = id();
791
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
792
+ *
793
+ * // Update the title
794
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
795
+ *
796
+ * // Delete it
797
+ * db.transact(db.tx.goals[goalId].delete())
798
+ *
799
+ * // Or create an association:
800
+ * todoId = id();
801
+ * db.transact([
802
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
803
+ * db.tx.goals[goalId].link({todos: todoId}),
804
+ * ])
805
+ */
806
+ transact = (inputChunks) => {
807
+ if (!this.config.disableValidation) {
808
+ validateTransactions(inputChunks, this.config.schema);
809
+ }
810
+ return jsonFetch(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
811
+ method: 'POST',
812
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
813
+ body: JSON.stringify({
814
+ steps: steps(inputChunks),
815
+ 'throw-on-missing-attrs?': !!this.config.schema,
816
+ }),
817
+ });
818
+ };
819
+ /**
820
+ * Like `query`, but returns debugging information
821
+ * for permissions checks along with the result.
822
+ * Useful for inspecting the values returned by the permissions checks.
823
+ * Note, this will return debug information for *all* entities
824
+ * that match the query's `where` clauses.
825
+ *
826
+ * Requires a user/guest context to be set with `asUser`,
827
+ * since permissions checks are user-specific.
828
+ *
829
+ * Accepts an optional configuration object with a `rules` key.
830
+ * The provided rules will override the rules in the database for the query.
831
+ *
832
+ * @see https://interfacedb.com/docs/instaql
833
+ *
834
+ * @example
835
+ * await db.asUser({ guest: true }).debugQuery(
836
+ * { goals: {} },
837
+ * { rules: { goals: { allow: { read: "auth.id != null" } } }
838
+ * )
839
+ */
840
+ debugQuery = async (query, opts) => {
841
+ if (query && opts && 'ruleParams' in opts) {
842
+ query = { $$ruleParams: opts['ruleParams'], ...query };
843
+ }
844
+ const body = {
845
+ query,
846
+ 'rules-override': opts?.rules,
847
+ 'inference?': opts?.cardinalityInference ?? !!this.config.schema,
848
+ };
849
+ if (opts?.ip) {
850
+ body['ip-override'] = opts.ip;
851
+ }
852
+ if (opts?.origin) {
853
+ body['origin-override'] = opts.origin;
854
+ }
855
+ const response = await jsonFetch(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
856
+ method: 'POST',
857
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
858
+ body: JSON.stringify(body),
859
+ });
860
+ return {
861
+ result: response.result,
862
+ checkResults: response['check-results'],
863
+ };
864
+ };
865
+ /**
866
+ * Like `transact`, but does not write to the database.
867
+ * Returns debugging information for permissions checks.
868
+ * Useful for inspecting the values returned by the permissions checks.
869
+ *
870
+ * Requires a user/guest context to be set with `asUser`,
871
+ * since permissions checks are user-specific.
872
+ *
873
+ * Accepts an optional configuration object with a `rules` key.
874
+ * The provided rules will override the rules in the database for the duration of the transaction.
875
+ *
876
+ * @example
877
+ * const goalId = id();
878
+ * db.asUser({ guest: true }).debugTransact(
879
+ * [db.tx.goals[goalId].update({title: "Get fit"})],
880
+ * { rules: { goals: { allow: { update: "auth.id != null" } } }
881
+ * )
882
+ */
883
+ debugTransact = (inputChunks, opts) => {
884
+ const body = {
885
+ steps: steps(inputChunks),
886
+ 'rules-override': opts?.rules,
887
+ // @ts-expect-error because we're using a private API (for now)
888
+ 'dangerously-commit-tx': opts?.__dangerouslyCommit,
889
+ };
890
+ if (opts?.ip) {
891
+ body['ip-override'] = opts.ip;
892
+ }
893
+ if (opts?.origin) {
894
+ body['origin-override'] = opts.origin;
895
+ }
896
+ return jsonFetch(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`, {
897
+ method: 'POST',
898
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
899
+ body: JSON.stringify(body),
900
+ });
901
+ };
902
+ #setupSSEConnection() {
903
+ if (this.#sseConnection) {
904
+ this.#sseConnection.close();
905
+ }
906
+ const headers = {
907
+ ...authorizedHeaders(this.config, this.impersonationOpts),
908
+ };
909
+ const inference = !!this.config.schema;
910
+ const ES = makeEventSourceWrapper({ headers, inference });
911
+ const conn = new SSEConnection(ES, `${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`, `${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);
912
+ conn.onopen = this.#onopen;
913
+ conn.onmessage = this.#onmessage;
914
+ conn.onclose = this.#onclose;
915
+ conn.onerror = this.#onerror;
916
+ this.#sseConnection = conn;
917
+ return conn;
918
+ }
919
+ #ensureSSEConnection() {
920
+ return this.#sseConnection || this.#setupSSEConnection();
921
+ }
922
+ #trySend(eventId, msg) {
923
+ const sseConnection = this.#ensureSSEConnection();
924
+ this.#log.info('[send]', eventId, msg, {
925
+ isOpen: sseConnection.isOpen(),
926
+ });
927
+ if (sseConnection.isOpen()) {
928
+ sseConnection.send({ 'client-event-id': eventId, ...msg });
929
+ }
930
+ }
931
+ #setupInstantStream() {
932
+ this.#ensureSSEConnection();
933
+ const instantStream = new InstantStream({
934
+ WStream: this.config.WritableStream || WritableStream,
935
+ RStream: this.config.ReadableStream || ReadableStream,
936
+ trySend: (eventId, msg) => {
937
+ this.#trySend(eventId, msg);
938
+ },
939
+ log: this.#log,
940
+ });
941
+ this.#instantStream = instantStream;
942
+ return instantStream;
943
+ }
944
+ #ensureInstantStream() {
945
+ return this.#instantStream || this.#setupInstantStream();
946
+ }
947
+ #onopen = (e) => {
948
+ if (e.target !== this.#sseConnection) {
949
+ this.#log.info('[socket][open]', e.target.id, 'skip; this is no longer the current transport');
950
+ return;
951
+ }
952
+ this.#log.info('[socket][open]', e.target.id);
953
+ this.#sseBackoff = 0;
954
+ this.#instantStream?.onConnectionStatusChange('authenticated');
955
+ };
956
+ #onclose = (e) => {
957
+ if (e.target !== this.#sseConnection) {
958
+ this.#log.info('[socket][close]', e.target.id, 'skip; this is no longer the current transport');
959
+ return;
960
+ }
961
+ this.#log.info('[socket][close]', e.target.id);
962
+ this.#instantStream?.onConnectionStatusChange('closed');
963
+ if (this.#sseConnection) {
964
+ this.#sseConnection = null;
965
+ if (!this.#connectionIsIdle()) {
966
+ // We didn't remove the sse connection, and we have streams we care about, so let's try again
967
+ setTimeout(() => this.#ensureSSEConnection(), this.#sseBackoff);
968
+ this.#sseBackoff = Math.min(15000, Math.max(this.#sseBackoff, 500) * 2);
969
+ }
970
+ }
971
+ };
972
+ #onerror = (e) => {
973
+ if (e.target !== this.#sseConnection) {
974
+ this.#log.info('[socket][error]', e.target.id, 'skip; this is no longer the current transport');
975
+ return;
976
+ }
977
+ this.#log.info('[socket][error]', e.target.id);
978
+ this.#instantStream?.onConnectionStatusChange('closed');
979
+ };
980
+ #connectionIsIdle() {
981
+ return !this.#instantStream || !this.#instantStream.hasActiveStreams();
982
+ }
983
+ #maybeShutdownConnection() {
984
+ if (this.#sseConnection && this.#connectionIsIdle()) {
985
+ const conn = this.#sseConnection;
986
+ this.#log.info('cleaning up unused socket', conn.id);
987
+ this.#sseConnection = null;
988
+ conn.close();
989
+ }
990
+ }
991
+ #onmessage = (e) => {
992
+ if (e.target !== this.#sseConnection) {
993
+ this.#log.info('[socket][message]', e.target.id, 'skip; this is no longer the current transport');
994
+ return;
995
+ }
996
+ const msg = e.message;
997
+ this.#log.info('[receive]', msg);
998
+ switch (msg.op) {
999
+ case 'start-stream-ok': {
1000
+ this.#instantStream?.onStartStreamOk(msg);
1001
+ break;
1002
+ }
1003
+ case 'stream-flushed': {
1004
+ this.#instantStream?.onStreamFlushed(msg);
1005
+ break;
1006
+ }
1007
+ case 'append-failed': {
1008
+ this.#instantStream?.onAppendFailed(msg);
1009
+ break;
1010
+ }
1011
+ case 'stream-append': {
1012
+ this.#instantStream?.onStreamAppend(msg);
1013
+ break;
1014
+ }
1015
+ case 'error': {
1016
+ switch (msg['original-event']?.op) {
1017
+ case 'start-stream':
1018
+ case 'append-stream':
1019
+ case 'subscribe-stream':
1020
+ case 'unsubscribe-stream': {
1021
+ this.#instantStream?.onRecieveError(msg);
1022
+ break;
1023
+ }
1024
+ }
1025
+ break;
1026
+ }
1027
+ }
1028
+ // Closes the connection if we don't have any items pending
1029
+ this.#maybeShutdownConnection();
1030
+ };
1031
+ }
1032
+ export { init, init_experimental, id, tx, lookup, i, createInstantRouteHandler, Webhooks, WebhooksManager,
1033
+ // error
1034
+ InstantAPIError,
1035
+ // warnings
1036
+ setInstantWarningsEnabled, InstantError, };
1037
+ //# sourceMappingURL=index.js.map