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