@sidekickdb/platform 0.0.0 → 2.0.0

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 (197) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/.turbo/turbo-build.log +50 -0
  5. package/LICENSE.md +202 -0
  6. package/NOTICE +27 -0
  7. package/README.md +444 -2
  8. package/__tests__/src/apiURI.test.ts +58 -0
  9. package/__tests__/src/backupDownload.test.ts +427 -0
  10. package/__tests__/src/backups.test.ts +168 -0
  11. package/__tests__/src/clerk.test.ts +13 -0
  12. package/__tests__/src/consts.test.ts +11 -0
  13. package/__tests__/src/migrations.test.ts +885 -0
  14. package/__tests__/src/perms.test.ts +102 -0
  15. package/__tests__/src/rename.test.ts +126 -0
  16. package/__tests__/src/schema.push.e2e.test.ts +186 -0
  17. package/__tests__/src/schema.test.ts +644 -0
  18. package/__tests__/src/typescript-schema.test.ts +117 -0
  19. package/dist/commonjs/ProgressPromise.d.ts +18 -0
  20. package/dist/commonjs/ProgressPromise.d.ts.map +1 -0
  21. package/dist/commonjs/ProgressPromise.js +77 -0
  22. package/dist/commonjs/ProgressPromise.js.map +1 -0
  23. package/dist/commonjs/api.d.ts +480 -0
  24. package/dist/commonjs/api.d.ts.map +1 -0
  25. package/dist/commonjs/api.js +1132 -0
  26. package/dist/commonjs/api.js.map +1 -0
  27. package/dist/commonjs/backupDownload.d.ts +89 -0
  28. package/dist/commonjs/backupDownload.d.ts.map +1 -0
  29. package/dist/commonjs/backupDownload.js +357 -0
  30. package/dist/commonjs/backupDownload.js.map +1 -0
  31. package/dist/commonjs/backups.d.ts +146 -0
  32. package/dist/commonjs/backups.d.ts.map +1 -0
  33. package/dist/commonjs/backups.js +248 -0
  34. package/dist/commonjs/backups.js.map +1 -0
  35. package/dist/commonjs/clerk.d.ts +2 -0
  36. package/dist/commonjs/clerk.d.ts.map +1 -0
  37. package/dist/commonjs/clerk.js +29 -0
  38. package/dist/commonjs/clerk.js.map +1 -0
  39. package/dist/commonjs/consts.d.ts +11 -0
  40. package/dist/commonjs/consts.d.ts.map +1 -0
  41. package/dist/commonjs/consts.js +17 -0
  42. package/dist/commonjs/consts.js.map +1 -0
  43. package/dist/commonjs/crypto.d.ts +4 -0
  44. package/dist/commonjs/crypto.d.ts.map +1 -0
  45. package/dist/commonjs/crypto.js +26 -0
  46. package/dist/commonjs/crypto.js.map +1 -0
  47. package/dist/commonjs/index.d.ts +18 -0
  48. package/dist/commonjs/index.d.ts.map +1 -0
  49. package/dist/commonjs/index.js +61 -0
  50. package/dist/commonjs/index.js.map +1 -0
  51. package/dist/commonjs/migrationUtils.d.ts +4 -0
  52. package/dist/commonjs/migrationUtils.d.ts.map +1 -0
  53. package/dist/commonjs/migrationUtils.js +52 -0
  54. package/dist/commonjs/migrationUtils.js.map +1 -0
  55. package/dist/commonjs/migrations.d.ts +99 -0
  56. package/dist/commonjs/migrations.d.ts.map +1 -0
  57. package/dist/commonjs/migrations.js +597 -0
  58. package/dist/commonjs/migrations.js.map +1 -0
  59. package/dist/commonjs/oauth.d.ts +98 -0
  60. package/dist/commonjs/oauth.d.ts.map +1 -0
  61. package/dist/commonjs/oauth.js +277 -0
  62. package/dist/commonjs/oauth.js.map +1 -0
  63. package/dist/commonjs/oauthCommon.d.ts +12 -0
  64. package/dist/commonjs/oauthCommon.d.ts.map +1 -0
  65. package/dist/commonjs/oauthCommon.js +26 -0
  66. package/dist/commonjs/oauthCommon.js.map +1 -0
  67. package/dist/commonjs/package.json +3 -0
  68. package/dist/commonjs/perms.d.ts +3 -0
  69. package/dist/commonjs/perms.d.ts.map +1 -0
  70. package/dist/commonjs/perms.js +66 -0
  71. package/dist/commonjs/perms.js.map +1 -0
  72. package/dist/commonjs/relationships.d.ts +7 -0
  73. package/dist/commonjs/relationships.d.ts.map +1 -0
  74. package/dist/commonjs/relationships.js +46 -0
  75. package/dist/commonjs/relationships.js.map +1 -0
  76. package/dist/commonjs/schema.d.ts +161 -0
  77. package/dist/commonjs/schema.d.ts.map +1 -0
  78. package/dist/commonjs/schema.js +174 -0
  79. package/dist/commonjs/schema.js.map +1 -0
  80. package/dist/commonjs/serverOAuth.d.ts +25 -0
  81. package/dist/commonjs/serverOAuth.d.ts.map +1 -0
  82. package/dist/commonjs/serverOAuth.js +72 -0
  83. package/dist/commonjs/serverOAuth.js.map +1 -0
  84. package/dist/commonjs/typescript-schema.d.ts +17 -0
  85. package/dist/commonjs/typescript-schema.d.ts.map +1 -0
  86. package/dist/commonjs/typescript-schema.js +314 -0
  87. package/dist/commonjs/typescript-schema.js.map +1 -0
  88. package/dist/commonjs/util.d.ts +13 -0
  89. package/dist/commonjs/util.d.ts.map +1 -0
  90. package/dist/commonjs/util.js +55 -0
  91. package/dist/commonjs/util.js.map +1 -0
  92. package/dist/commonjs/version.d.ts +3 -0
  93. package/dist/commonjs/version.d.ts.map +1 -0
  94. package/dist/commonjs/version.js +5 -0
  95. package/dist/commonjs/version.js.map +1 -0
  96. package/dist/esm/ProgressPromise.d.ts +18 -0
  97. package/dist/esm/ProgressPromise.d.ts.map +1 -0
  98. package/dist/esm/ProgressPromise.js +73 -0
  99. package/dist/esm/ProgressPromise.js.map +1 -0
  100. package/dist/esm/api.d.ts +480 -0
  101. package/dist/esm/api.d.ts.map +1 -0
  102. package/dist/esm/api.js +1121 -0
  103. package/dist/esm/api.js.map +1 -0
  104. package/dist/esm/backupDownload.d.ts +89 -0
  105. package/dist/esm/backupDownload.d.ts.map +1 -0
  106. package/dist/esm/backupDownload.js +354 -0
  107. package/dist/esm/backupDownload.js.map +1 -0
  108. package/dist/esm/backups.d.ts +146 -0
  109. package/dist/esm/backups.d.ts.map +1 -0
  110. package/dist/esm/backups.js +237 -0
  111. package/dist/esm/backups.js.map +1 -0
  112. package/dist/esm/clerk.d.ts +2 -0
  113. package/dist/esm/clerk.d.ts.map +1 -0
  114. package/dist/esm/clerk.js +26 -0
  115. package/dist/esm/clerk.js.map +1 -0
  116. package/dist/esm/consts.d.ts +11 -0
  117. package/dist/esm/consts.d.ts.map +1 -0
  118. package/dist/esm/consts.js +13 -0
  119. package/dist/esm/consts.js.map +1 -0
  120. package/dist/esm/crypto.d.ts +4 -0
  121. package/dist/esm/crypto.d.ts.map +1 -0
  122. package/dist/esm/crypto.js +21 -0
  123. package/dist/esm/crypto.js.map +1 -0
  124. package/dist/esm/index.d.ts +18 -0
  125. package/dist/esm/index.d.ts.map +1 -0
  126. package/dist/esm/index.js +17 -0
  127. package/dist/esm/index.js.map +1 -0
  128. package/dist/esm/migrationUtils.d.ts +4 -0
  129. package/dist/esm/migrationUtils.d.ts.map +1 -0
  130. package/dist/esm/migrationUtils.js +47 -0
  131. package/dist/esm/migrationUtils.js.map +1 -0
  132. package/dist/esm/migrations.d.ts +99 -0
  133. package/dist/esm/migrations.d.ts.map +1 -0
  134. package/dist/esm/migrations.js +588 -0
  135. package/dist/esm/migrations.js.map +1 -0
  136. package/dist/esm/oauth.d.ts +98 -0
  137. package/dist/esm/oauth.d.ts.map +1 -0
  138. package/dist/esm/oauth.js +268 -0
  139. package/dist/esm/oauth.js.map +1 -0
  140. package/dist/esm/oauthCommon.d.ts +12 -0
  141. package/dist/esm/oauthCommon.d.ts.map +1 -0
  142. package/dist/esm/oauthCommon.js +22 -0
  143. package/dist/esm/oauthCommon.js.map +1 -0
  144. package/dist/esm/package.json +3 -0
  145. package/dist/esm/perms.d.ts +3 -0
  146. package/dist/esm/perms.d.ts.map +1 -0
  147. package/dist/esm/perms.js +62 -0
  148. package/dist/esm/perms.js.map +1 -0
  149. package/dist/esm/relationships.d.ts +7 -0
  150. package/dist/esm/relationships.d.ts.map +1 -0
  151. package/dist/esm/relationships.js +43 -0
  152. package/dist/esm/relationships.js.map +1 -0
  153. package/dist/esm/schema.d.ts +161 -0
  154. package/dist/esm/schema.d.ts.map +1 -0
  155. package/dist/esm/schema.js +158 -0
  156. package/dist/esm/schema.js.map +1 -0
  157. package/dist/esm/serverOAuth.d.ts +25 -0
  158. package/dist/esm/serverOAuth.d.ts.map +1 -0
  159. package/dist/esm/serverOAuth.js +68 -0
  160. package/dist/esm/serverOAuth.js.map +1 -0
  161. package/dist/esm/typescript-schema.d.ts +17 -0
  162. package/dist/esm/typescript-schema.d.ts.map +1 -0
  163. package/dist/esm/typescript-schema.js +310 -0
  164. package/dist/esm/typescript-schema.js.map +1 -0
  165. package/dist/esm/util.d.ts +13 -0
  166. package/dist/esm/util.d.ts.map +1 -0
  167. package/dist/esm/util.js +46 -0
  168. package/dist/esm/util.js.map +1 -0
  169. package/dist/esm/version.d.ts +3 -0
  170. package/dist/esm/version.d.ts.map +1 -0
  171. package/dist/esm/version.js +3 -0
  172. package/dist/esm/version.js.map +1 -0
  173. package/dist/standalone/index.js +13747 -0
  174. package/dist/standalone/index.umd.cjs +72 -0
  175. package/package.json +69 -3
  176. package/src/ProgressPromise.ts +97 -0
  177. package/src/api.ts +1903 -0
  178. package/src/backupDownload.ts +519 -0
  179. package/src/backups.ts +342 -0
  180. package/src/clerk.ts +24 -0
  181. package/src/consts.ts +22 -0
  182. package/src/crypto.ts +28 -0
  183. package/src/index.ts +147 -0
  184. package/src/migrationUtils.ts +56 -0
  185. package/src/migrations.ts +920 -0
  186. package/src/oauth.ts +390 -0
  187. package/src/oauthCommon.ts +38 -0
  188. package/src/perms.ts +81 -0
  189. package/src/relationships.ts +57 -0
  190. package/src/schema.ts +497 -0
  191. package/src/serverOAuth.ts +119 -0
  192. package/src/typescript-schema.ts +439 -0
  193. package/src/util.ts +77 -0
  194. package/src/version.ts +3 -0
  195. package/tsconfig.dev.json +14 -0
  196. package/tsconfig.json +14 -0
  197. package/vite.config.ts +19 -0
@@ -0,0 +1,1132 @@
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.PlatformApi = exports.PlatformApiMissingAuthError = void 0;
7
+ exports.apiSchemaToAttrs = apiSchemaToAttrs;
8
+ exports.apiSchemaToInstantSchemaDef = apiSchemaToInstantSchemaDef;
9
+ exports.translatePlanSteps = translatePlanSteps;
10
+ const core_1 = require("@sidekickdb/core");
11
+ const webhooks_1 = require("@sidekickdb/webhooks");
12
+ const backups_ts_1 = require("./backups.js");
13
+ const version_ts_1 = __importDefault(require("./version.js"));
14
+ const schema_ts_1 = require("./schema.js");
15
+ const ProgressPromise_ts_1 = require("./ProgressPromise.js");
16
+ const util_ts_1 = require("./util.js");
17
+ const serverOAuth_ts_1 = require("./serverOAuth.js");
18
+ const migrations_ts_1 = require("./migrations.js");
19
+ async function jsonFetch(input, init) {
20
+ const headers = {
21
+ ...(init?.headers || {}),
22
+ 'Instant-Platform-Version': version_ts_1.default,
23
+ 'Instant-Core-Version': core_1.version,
24
+ 'X-Instant-Source': 'platform-sdk',
25
+ 'X-Instant-Version': version_ts_1.default,
26
+ };
27
+ const res = await fetch(input, { ...init, headers });
28
+ if (res.status === 200) {
29
+ const json = await res.json();
30
+ return Promise.resolve(json);
31
+ }
32
+ const body = await res.text();
33
+ try {
34
+ const json = JSON.parse(body);
35
+ return Promise.reject(new core_1.InstantAPIError({ status: res.status, body: json }));
36
+ }
37
+ catch (_e) {
38
+ return Promise.reject(new core_1.InstantAPIError({
39
+ status: res.status,
40
+ body: { type: undefined, message: body },
41
+ }));
42
+ }
43
+ }
44
+ function attrDefForType(type) {
45
+ switch (type) {
46
+ case 'string':
47
+ return core_1.i.string();
48
+ case 'any':
49
+ return core_1.i.any();
50
+ case 'json':
51
+ return core_1.i.json();
52
+ case 'boolean':
53
+ return core_1.i.boolean();
54
+ case 'date':
55
+ return core_1.i.date();
56
+ case 'number':
57
+ return core_1.i.number();
58
+ default: {
59
+ const neverType = type;
60
+ throw new Error(`Unknown type ${neverType}.`);
61
+ }
62
+ }
63
+ }
64
+ function apiSchemaAttrToDataAttrDef(attr) {
65
+ const derivedType = (0, util_ts_1.deriveClientType)(attr);
66
+ let i = attrDefForType(derivedType.type);
67
+ if (attr['unique?']) {
68
+ i = i.unique();
69
+ }
70
+ if (attr['index?']) {
71
+ i = i.indexed();
72
+ }
73
+ if (!attr['required?']) {
74
+ i = i.optional();
75
+ }
76
+ i.metadata.derivedType = derivedType;
77
+ return i;
78
+ }
79
+ function apiSchemaBlobToEntityDef(attrs) {
80
+ const defs = {};
81
+ for (const [label, attr] of (0, util_ts_1.sortedEntries)(attrs)) {
82
+ if (label === 'id') {
83
+ continue;
84
+ }
85
+ defs[label] = apiSchemaAttrToDataAttrDef(attr);
86
+ }
87
+ return core_1.i.entity(defs);
88
+ }
89
+ function apiSchemaAttrToLinkName(attr) {
90
+ const [, fe, flabel] = attr['forward-identity'];
91
+ return `${fe}${(0, util_ts_1.capitalizeFirstLetter)(flabel)}`;
92
+ }
93
+ function apiSchemaAttrToLinkDef(attr) {
94
+ const [, fe, flabel] = attr['forward-identity'];
95
+ const [, re, rlabel] = attr['reverse-identity'];
96
+ const [fhas, rhas] = util_ts_1.rels[`${attr.cardinality}-${attr['unique?']}`];
97
+ return {
98
+ forward: {
99
+ on: fe,
100
+ has: fhas,
101
+ label: flabel,
102
+ required: attr['required?'] || undefined,
103
+ onDelete: attr['on-delete'] === 'cascade' ? 'cascade' : undefined,
104
+ },
105
+ reverse: {
106
+ on: re,
107
+ has: rhas,
108
+ label: rlabel,
109
+ onDelete: attr['on-delete-reverse'] === 'cascade'
110
+ ? 'cascade'
111
+ : undefined,
112
+ },
113
+ };
114
+ }
115
+ function apiSchemaToAttrs(apiSchema) {
116
+ let res = [];
117
+ for (const [_, attrs] of (0, util_ts_1.sortedEntries)(apiSchema.blobs)) {
118
+ Object.values(attrs).forEach((a) => {
119
+ res.push(a);
120
+ });
121
+ }
122
+ for (const [_, a] of (0, util_ts_1.sortedEntries)(apiSchema.refs)) {
123
+ res.push(a);
124
+ }
125
+ return res;
126
+ }
127
+ function apiSchemaToInstantSchemaDef(apiSchema) {
128
+ const entities = {};
129
+ for (const [etype, attrs] of (0, util_ts_1.sortedEntries)(apiSchema.blobs)) {
130
+ entities[etype] = apiSchemaBlobToEntityDef(attrs);
131
+ }
132
+ const links = {};
133
+ for (const [_name, attr] of (0, util_ts_1.sortedEntries)(apiSchema.refs)) {
134
+ const link = apiSchemaAttrToLinkDef(attr);
135
+ const linkName = apiSchemaAttrToLinkName(attr);
136
+ links[linkName] = link;
137
+ }
138
+ return core_1.i.schema({ entities, links });
139
+ }
140
+ function coerceApp(app) {
141
+ const base = {
142
+ id: app.id,
143
+ title: app.title,
144
+ createdAt: new Date(app.created_at),
145
+ orgId: app.org_id,
146
+ ...(app['admin-token'] ? { adminToken: app['admin-token'] } : {}),
147
+ };
148
+ // `in` narrows the union, so it’s safe to read `perms` / `schema`
149
+ // when the property exists. :contentReference[oaicite:0]{index=0}
150
+ const permsPart = ('perms' in app ? { perms: app.perms } : {});
151
+ const schemaPart = ('schema' in app
152
+ ? {
153
+ schema: apiSchemaToInstantSchemaDef(app.schema),
154
+ }
155
+ : {});
156
+ return { ...base, ...permsPart, ...schemaPart };
157
+ }
158
+ function coerceOrg(org) {
159
+ return {
160
+ id: org.id,
161
+ title: org.title,
162
+ createdAt: new Date(org.created_at),
163
+ };
164
+ }
165
+ async function getApps(apiURI, token, opts) {
166
+ const url = new URL(`${apiURI}/superadmin/apps`);
167
+ const include = [];
168
+ if (opts?.includePerms) {
169
+ include.push('perms');
170
+ }
171
+ if (opts?.includeSchema) {
172
+ include.push('schema');
173
+ }
174
+ if (include.length) {
175
+ url.searchParams.set('include', include.join(','));
176
+ }
177
+ const resp = await jsonFetch(url.toString(), {
178
+ method: 'GET',
179
+ headers: {
180
+ Authorization: `Bearer ${token}`,
181
+ },
182
+ });
183
+ return { apps: resp.apps.map(coerceApp) };
184
+ }
185
+ async function getOrgs(apiURI, token) {
186
+ const url = new URL(`${apiURI}/superadmin/orgs`);
187
+ const resp = await jsonFetch(url.toString(), {
188
+ method: 'GET',
189
+ headers: {
190
+ Authorization: `Bearer ${token}`,
191
+ },
192
+ });
193
+ return { orgs: resp.orgs.map(coerceOrg) };
194
+ }
195
+ async function getAppsForOrg(apiURI, token, orgId, opts) {
196
+ const url = new URL(`${apiURI}/superadmin/orgs/${orgId}/apps`);
197
+ const include = [];
198
+ if (opts?.includePerms) {
199
+ include.push('perms');
200
+ }
201
+ if (opts?.includeSchema) {
202
+ include.push('schema');
203
+ }
204
+ if (include.length) {
205
+ url.searchParams.set('include', include.join(','));
206
+ }
207
+ const resp = await jsonFetch(url.toString(), {
208
+ method: 'GET',
209
+ headers: {
210
+ Authorization: `Bearer ${token}`,
211
+ },
212
+ });
213
+ return { apps: resp.apps.map(coerceApp) };
214
+ }
215
+ async function getAppAPISchema(apiURI, token, appId) {
216
+ const { schema: apiSchema } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/schema`, {
217
+ method: 'GET',
218
+ headers: {
219
+ Authorization: `Bearer ${token}`,
220
+ },
221
+ });
222
+ return apiSchema;
223
+ }
224
+ async function getAppSchema(apiURI, token, appId) {
225
+ const apiSchema = await getAppAPISchema(apiURI, token, appId);
226
+ return { schema: apiSchemaToInstantSchemaDef(apiSchema) };
227
+ }
228
+ async function getAppPerms(apiURI, token, appId) {
229
+ return await jsonFetch(`${apiURI}/superadmin/apps/${appId}/perms`, {
230
+ method: 'GET',
231
+ headers: {
232
+ Authorization: `Bearer ${token}`,
233
+ },
234
+ });
235
+ }
236
+ async function getApp(apiURI, token, appId, opts) {
237
+ let permsPromise = null;
238
+ let schemaPromise = null;
239
+ if (opts?.includePerms) {
240
+ permsPromise = getAppPerms(apiURI, token, appId);
241
+ }
242
+ if (opts?.includeSchema) {
243
+ schemaPromise = getAppSchema(apiURI, token, appId);
244
+ }
245
+ const { app: apiApp } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}`, {
246
+ method: 'GET',
247
+ headers: {
248
+ Authorization: `Bearer ${token}`,
249
+ },
250
+ });
251
+ if (!permsPromise && !schemaPromise) {
252
+ const app = coerceApp(apiApp);
253
+ return { app };
254
+ }
255
+ const app = {
256
+ ...coerceApp(apiApp),
257
+ ...(permsPromise ? { perms: (await permsPromise).perms } : {}),
258
+ ...(schemaPromise ? { schema: (await schemaPromise).schema } : {}),
259
+ };
260
+ return {
261
+ app,
262
+ };
263
+ }
264
+ async function createApp(apiURI, token, fields) {
265
+ const apiFields = fields;
266
+ apiFields.org_id = fields.orgId;
267
+ const { app } = await jsonFetch(`${apiURI}/superadmin/apps`, {
268
+ method: 'POST',
269
+ headers: {
270
+ 'Content-Type': 'application/json',
271
+ Authorization: `Bearer ${token}`,
272
+ },
273
+ body: JSON.stringify(apiFields),
274
+ });
275
+ const withAdminToken = {
276
+ ...coerceApp(app),
277
+ adminToken: app['admin-token'],
278
+ };
279
+ return {
280
+ app: withAdminToken,
281
+ };
282
+ }
283
+ async function createTemporaryApp(apiURI, fields) {
284
+ const response = await jsonFetch(`${apiURI}/dash/apps/ephemeral`, {
285
+ method: 'POST',
286
+ headers: {
287
+ 'Content-Type': 'application/json',
288
+ },
289
+ body: JSON.stringify(fields),
290
+ });
291
+ const withAdminToken = {
292
+ ...coerceApp(response.app),
293
+ adminToken: response.app['admin-token'],
294
+ };
295
+ return {
296
+ app: withAdminToken,
297
+ expiresMs: response.expires_ms,
298
+ };
299
+ }
300
+ async function updateApp(apiURI, token, appId, fields) {
301
+ const { app } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}`, {
302
+ method: 'POST',
303
+ headers: {
304
+ 'Content-Type': 'application/json',
305
+ Authorization: `Bearer ${token}`,
306
+ },
307
+ body: JSON.stringify(fields),
308
+ });
309
+ return { app: coerceApp(app) };
310
+ }
311
+ async function deleteApp(apiURI, token, appId) {
312
+ const { app } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}`, {
313
+ method: 'DELETE',
314
+ headers: {
315
+ 'Content-Type': 'application/json',
316
+ Authorization: `Bearer ${token}`,
317
+ },
318
+ });
319
+ return { app: coerceApp(app) };
320
+ }
321
+ function translatePlanStep(apiStep, currentAttrs) {
322
+ const [stepType, stepParams] = apiStep;
323
+ switch (stepType) {
324
+ case 'add-attr': {
325
+ const attr = stepParams;
326
+ const attrName = (0, schema_ts_1.attrFwdName)(attr);
327
+ const friendlyDescription = attr['value-type'] === 'blob'
328
+ ? (0, schema_ts_1.attrFwdLabel)(attr) === 'id'
329
+ ? `Create new entity ${attrName}.`
330
+ : `Add attribute ${attrName}.`
331
+ : `Link ${attrName} to ${(0, schema_ts_1.attrRevName)(attr)}.`;
332
+ return { type: 'add-attr', friendlyDescription, attr };
333
+ }
334
+ case 'update-attr': {
335
+ const attr = stepParams;
336
+ return {
337
+ type: 'update-attr',
338
+ friendlyDescription: `Update attribute ${(0, schema_ts_1.attrFwdName)(attr)}.`,
339
+ attr,
340
+ };
341
+ }
342
+ case 'index': {
343
+ return {
344
+ type: 'index',
345
+ friendlyDescription: `Add index to ${(0, schema_ts_1.identName)(stepParams['forward-identity'])}.`,
346
+ attrId: stepParams['attr-id'],
347
+ forwardIdentity: stepParams['forward-identity'],
348
+ };
349
+ }
350
+ case 'remove-index': {
351
+ return {
352
+ type: 'remove-index',
353
+ friendlyDescription: `Remove index from ${(0, schema_ts_1.identName)(stepParams['forward-identity'])}.`,
354
+ attrId: stepParams['attr-id'],
355
+ forwardIdentity: stepParams['forward-identity'],
356
+ };
357
+ }
358
+ case 'unique': {
359
+ return {
360
+ type: 'unique',
361
+ friendlyDescription: `Ensure that ${(0, schema_ts_1.identName)(stepParams['forward-identity'])} is unique.`,
362
+ attrId: stepParams['attr-id'],
363
+ forwardIdentity: stepParams['forward-identity'],
364
+ };
365
+ }
366
+ case 'remove-unique': {
367
+ return {
368
+ type: 'remove-unique',
369
+ friendlyDescription: `Remove uniqueness constraint from ${(0, schema_ts_1.identName)(stepParams['forward-identity'])}.`,
370
+ attrId: stepParams['attr-id'],
371
+ forwardIdentity: stepParams['forward-identity'],
372
+ };
373
+ }
374
+ case 'required': {
375
+ return {
376
+ type: 'required',
377
+ friendlyDescription: `Make ${(0, schema_ts_1.identName)(stepParams['forward-identity'])} a required attribute.`,
378
+ attrId: stepParams['attr-id'],
379
+ forwardIdentity: stepParams['forward-identity'],
380
+ };
381
+ }
382
+ case 'remove-required': {
383
+ return {
384
+ type: 'remove-required',
385
+ friendlyDescription: `Allow ${(0, schema_ts_1.identName)(stepParams['forward-identity'])} to be missing or null.`,
386
+ attrId: stepParams['attr-id'],
387
+ forwardIdentity: stepParams['forward-identity'],
388
+ };
389
+ }
390
+ case 'check-data-type': {
391
+ const forwardIdentity = stepParams['forward-identity'];
392
+ const dataType = stepParams['checked-data-type'];
393
+ return {
394
+ type: 'check-data-type',
395
+ friendlyDescription: `Enforce data type of ${(0, schema_ts_1.identName)(forwardIdentity)} as type ${dataType}.`,
396
+ attrId: stepParams['attr-id'],
397
+ forwardIdentity,
398
+ checkedDataType: dataType,
399
+ };
400
+ }
401
+ case 'remove-data-type': {
402
+ const forwardIdentity = stepParams['forward-identity'];
403
+ return {
404
+ type: 'remove-data-type',
405
+ friendlyDescription: `Stop enforcing data type of ${(0, schema_ts_1.identName)(forwardIdentity)}.`,
406
+ attrId: stepParams['attr-id'],
407
+ forwardIdentity: stepParams['forward-identity'],
408
+ };
409
+ }
410
+ case 'delete-attr': {
411
+ const attrId = stepParams;
412
+ const attr = currentAttrs.find((a) => a.id === attrId);
413
+ const friendlyName = attr ? (0, schema_ts_1.identName)(attr['forward-identity']) : attrId;
414
+ return {
415
+ type: 'delete-attr',
416
+ attrId: stepParams,
417
+ friendlyDescription: `Delete attribute ${friendlyName}.`,
418
+ };
419
+ }
420
+ default: {
421
+ // Get a type error if we ignore a case
422
+ const unknownType = stepType;
423
+ throw new Error(`Unknown schema operation ${unknownType}.`);
424
+ }
425
+ }
426
+ }
427
+ function translatePlanSteps(apiSteps, currentAttrs) {
428
+ return apiSteps.map((step) => translatePlanStep(step, currentAttrs));
429
+ }
430
+ function translatePushStep(apiStep, jobs, currentAttrs) {
431
+ const [stepType, stepParams] = apiStep;
432
+ if (stepType === 'add-attr' ||
433
+ stepType === 'update-attr' ||
434
+ stepType === 'delete-attr') {
435
+ const planStep = translatePlanStep(apiStep, currentAttrs);
436
+ if (planStep.type !== 'add-attr' &&
437
+ planStep.type !== 'update-attr' &&
438
+ planStep.type !== 'delete-attr') {
439
+ // This is just here for typescript
440
+ throw new Error('Invalid step.');
441
+ }
442
+ return planStep;
443
+ }
444
+ const jobId = stepParams['job-id'];
445
+ const job = jobs.find((j) => j.id === jobId);
446
+ const planStep = translatePlanStep(apiStep, currentAttrs);
447
+ const backgroundJob = formatJob(job);
448
+ if (planStep.type !== backgroundJob.type) {
449
+ throw new Error('Invalid type');
450
+ }
451
+ return { ...planStep, backgroundJob };
452
+ }
453
+ function translatePushSteps(apiSteps, jobs, currentAttrs) {
454
+ return apiSteps.map((step) => translatePushStep(step, jobs, currentAttrs));
455
+ }
456
+ function shouldOverwrite(body) {
457
+ if ('renames' in body && !body.overwrite) {
458
+ throw new Error('If you pass in `renames`, you _must_ pass in `overwrite: true`');
459
+ }
460
+ return !!body.overwrite;
461
+ }
462
+ async function planSchemaPush(apiURI, token, appId, body) {
463
+ const resp = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/schema/push/plan`, {
464
+ method: 'POST',
465
+ headers: {
466
+ 'Content-Type': 'application/json',
467
+ Authorization: `Bearer ${token}`,
468
+ },
469
+ body: JSON.stringify({
470
+ ...body,
471
+ check_types: true,
472
+ supports_background_updates: true,
473
+ }),
474
+ });
475
+ const currentAttrs = resp['current-attrs'];
476
+ return {
477
+ newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),
478
+ currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),
479
+ steps: translatePlanSteps(resp['steps'], currentAttrs),
480
+ };
481
+ }
482
+ async function planSchemaPushOverwriteInternal(apiURI, token, appId, body) {
483
+ const apiSchema = await getAppAPISchema(apiURI, token, appId);
484
+ const currentSchema = apiSchemaToInstantSchemaDef(apiSchema);
485
+ const currentAttrs = apiSchemaToAttrs(apiSchema);
486
+ const systemCatalogIdentNames = (0, schema_ts_1.collectSystemCatalogIdentNames)(currentAttrs);
487
+ const newSchema = body.schema;
488
+ (0, schema_ts_1.validateSchema)(newSchema, systemCatalogIdentNames);
489
+ const renames = ('renames' in body ? body.renames : null) || [];
490
+ const renameSelector = (0, migrations_ts_1.buildAutoRenameSelector)(renames);
491
+ const diffResult = await (0, migrations_ts_1.diffSchemas)(currentSchema, newSchema, renameSelector, systemCatalogIdentNames);
492
+ const txSteps = (0, migrations_ts_1.convertTxSteps)(diffResult, currentAttrs);
493
+ return {
494
+ currentSchema,
495
+ currentAttrs,
496
+ txSteps: txSteps,
497
+ steps: translatePlanSteps(txSteps, currentAttrs),
498
+ };
499
+ }
500
+ async function planSchemaPushOverwrite(apiURI, token, appId, body) {
501
+ const { currentSchema, steps } = await planSchemaPushOverwriteInternal(apiURI, token, appId, body);
502
+ return {
503
+ newSchema: body.schema,
504
+ currentSchema: currentSchema,
505
+ steps: steps,
506
+ };
507
+ }
508
+ function allJobsComplete(jobs) {
509
+ if (jobs.length === 0) {
510
+ return true;
511
+ }
512
+ return jobs.every((j) => j.job_status === 'completed' || j.job_status === 'errored');
513
+ }
514
+ function latestJobUpdate(jobs) {
515
+ const res = jobs.reduce((acc, job) => {
516
+ if (job.updated_at) {
517
+ const d = new Date(job.updated_at);
518
+ if (!acc || d > acc) {
519
+ return d;
520
+ }
521
+ }
522
+ return acc;
523
+ }, null);
524
+ return res;
525
+ }
526
+ async function jobFetchLoop(apiURI, token, appId, groupId, startingJobs, onFetch) {
527
+ let interval = 100;
528
+ let lastJobs = startingJobs;
529
+ let errorCount = 0;
530
+ while (!allJobsComplete(lastJobs)) {
531
+ await new Promise((resolve) => setTimeout(resolve, interval));
532
+ try {
533
+ const nextJobs = (await jsonFetch(`${apiURI}/dash/apps/${appId}/indexing-jobs/group/${groupId}`, {
534
+ method: 'GET',
535
+ headers: {
536
+ Authorization: `Bearer ${token}`,
537
+ },
538
+ })).jobs;
539
+ onFetch(nextJobs);
540
+ if (allJobsComplete(nextJobs)) {
541
+ return nextJobs;
542
+ }
543
+ errorCount = 0;
544
+ const lastUpdate = latestJobUpdate(lastJobs);
545
+ const thisUpdate = latestJobUpdate(nextJobs);
546
+ lastJobs = nextJobs;
547
+ interval =
548
+ thisUpdate === null || (lastUpdate && lastUpdate >= thisUpdate)
549
+ ? Math.min(interval * 2, 10000)
550
+ : 100;
551
+ }
552
+ catch (e) {
553
+ if (errorCount > 3) {
554
+ throw e;
555
+ }
556
+ else {
557
+ errorCount++;
558
+ interval = Math.min(interval * 2, 10000);
559
+ }
560
+ }
561
+ }
562
+ return lastJobs;
563
+ }
564
+ function formatJob(job) {
565
+ const baseJob = {
566
+ id: job.id,
567
+ createdAt: new Date(job.created_at),
568
+ updatedAt: new Date(job.updated_at),
569
+ status: job.job_status,
570
+ workEstimate: job.work_estimate,
571
+ workCompleted: job.work_completed,
572
+ error: job.error,
573
+ invalidTriplesSample: job.invalid_triples_sample?.map((s) => {
574
+ return { entityId: s.entity_id, value: s.value, jsonType: s.json_type };
575
+ }),
576
+ };
577
+ switch (job.job_type) {
578
+ case 'remove-data-type':
579
+ case 'index':
580
+ case 'remove-index':
581
+ case 'required':
582
+ case 'remove-required':
583
+ case 'remove-unique': {
584
+ return { ...baseJob, type: job.job_type };
585
+ }
586
+ case 'check-data-type': {
587
+ return {
588
+ ...baseJob,
589
+ type: job.job_type,
590
+ checkedDataType: job.checked_data_type,
591
+ };
592
+ }
593
+ case 'unique': {
594
+ return {
595
+ ...baseJob,
596
+ type: job.job_type,
597
+ invalidUniqueValue: job.invalid_unique_value,
598
+ };
599
+ }
600
+ default: {
601
+ const neverType = job.job_type;
602
+ throw new Error(`Unknown job type: ${neverType}.`);
603
+ }
604
+ }
605
+ }
606
+ function stepSummary(steps) {
607
+ const inProgress = steps.filter((s) => 'backgroundJob' in s &&
608
+ (s.backgroundJob.status === 'processing' ||
609
+ s.backgroundJob.status === 'waiting'));
610
+ const completed = steps.filter((s) => !('backgroundJob' in s) || s.backgroundJob.status === 'completed');
611
+ const errored = steps.filter((s) => 'backgroundJob' in s && s.backgroundJob.status === 'errored');
612
+ return {
613
+ friendlyDescription: inProgress.length
614
+ ? `Completing ${inProgress.length} of ${steps.length} schema operations.`
615
+ : `Finished ${steps.length} schema operation${steps.length === 1 ? '' : 's'}${errored.length
616
+ ? `, with ${errored.length} error${errored.length > 1 ? 's' : ''}`
617
+ : '.'}`,
618
+ totalCount: steps.length,
619
+ inProgressCount: inProgress.length,
620
+ completedCount: completed.length,
621
+ errorCount: errored.length,
622
+ steps,
623
+ inProgressSteps: inProgress,
624
+ completedSteps: completed,
625
+ erroredSteps: errored,
626
+ };
627
+ }
628
+ function schemaPush(apiURI, token, appId, body) {
629
+ return new ProgressPromise_ts_1.ProgressPromise(async (progress, resolve, reject) => {
630
+ try {
631
+ const currentAPISchema = await getAppAPISchema(apiURI, token, appId);
632
+ const currentAttrs = apiSchemaToAttrs(currentAPISchema);
633
+ const resp = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/schema/push/apply`, {
634
+ method: 'POST',
635
+ headers: {
636
+ 'Content-Type': 'application/json',
637
+ Authorization: `Bearer ${token}`,
638
+ },
639
+ body: JSON.stringify({
640
+ ...body,
641
+ check_types: true,
642
+ supports_background_updates: true,
643
+ }),
644
+ });
645
+ const indexingJobs = resp['indexing-jobs'];
646
+ const jobs = !indexingJobs
647
+ ? []
648
+ : await jobFetchLoop(apiURI, token, appId, indexingJobs['group-id'], indexingJobs['jobs'], (jobs) => {
649
+ progress(stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)));
650
+ });
651
+ const schemaRes = await getAppSchema(apiURI, token, appId);
652
+ resolve({
653
+ newSchema: schemaRes.schema,
654
+ steps: translatePushSteps(resp.steps, jobs, currentAttrs),
655
+ summary: stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),
656
+ });
657
+ }
658
+ catch (e) {
659
+ reject(e);
660
+ }
661
+ });
662
+ }
663
+ function schemaPushOverwrite(apiURI, token, appId, body) {
664
+ return new ProgressPromise_ts_1.ProgressPromise(async (progress, resolve, reject) => {
665
+ try {
666
+ const { currentAttrs, txSteps } = await planSchemaPushOverwriteInternal(apiURI, token, appId, body);
667
+ const resp = await jsonFetch(`${apiURI}/dash/apps/${appId}/schema/steps/apply`, {
668
+ method: 'POST',
669
+ headers: {
670
+ 'Content-Type': 'application/json',
671
+ Authorization: `Bearer ${token}`,
672
+ },
673
+ body: JSON.stringify({
674
+ steps: txSteps,
675
+ }),
676
+ });
677
+ const indexingJobs = resp['indexing-jobs'];
678
+ const jobs = !indexingJobs
679
+ ? []
680
+ : await jobFetchLoop(apiURI, token, appId, indexingJobs['group-id'], indexingJobs['jobs'], (jobs) => {
681
+ progress(stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)));
682
+ });
683
+ const schemaRes = await getAppSchema(apiURI, token, appId);
684
+ resolve({
685
+ newSchema: schemaRes.schema,
686
+ steps: translatePushSteps(resp.steps, jobs, currentAttrs),
687
+ summary: stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),
688
+ });
689
+ }
690
+ catch (e) {
691
+ reject(e);
692
+ }
693
+ });
694
+ }
695
+ async function pushPerms(apiURI, token, appId, body) {
696
+ const result = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/perms`, {
697
+ method: 'POST',
698
+ headers: {
699
+ 'Content-Type': 'application/json',
700
+ Authorization: `Bearer ${token}`,
701
+ },
702
+ body: JSON.stringify({ code: body.perms }),
703
+ });
704
+ return { perms: result.rules.code };
705
+ }
706
+ async function tokenInfo(apiURI, token) {
707
+ const result = await jsonFetch(`${apiURI}/platform/oauth/token-info?access_token=${token}`, {
708
+ method: 'GET',
709
+ });
710
+ return {
711
+ tokenType: result.token_type,
712
+ scopes: result.scopes,
713
+ expiresAt: new Date(Date.now() + (result.expires_in - 60) * 1000),
714
+ };
715
+ }
716
+ class PlatformApiMissingAuthError extends Error {
717
+ constructor() {
718
+ super('PlatformApi was not provided auth.');
719
+ }
720
+ }
721
+ exports.PlatformApiMissingAuthError = PlatformApiMissingAuthError;
722
+ /**
723
+ * API methods for the Platform API
724
+ *
725
+ * Usage:
726
+ *
727
+ * ```ts
728
+ * import { PlatformApi } from '@sidekickdb/platform';
729
+ *
730
+ * const api = new PlatformApi({
731
+ * apiURI: 'https://sidekick.example.com',
732
+ * auth: { token: 'oauth-access-token' },
733
+ * });
734
+ * const { apps } = await api.getApps({
735
+ * includeSchema: true,
736
+ * includePerms: true,
737
+ * });
738
+ * ```
739
+ */
740
+ class PlatformApi {
741
+ #auth;
742
+ #apiURI;
743
+ /**
744
+ * @param config – Runtime configuration.
745
+ * @param config.auth.token – OAuth access-token obtained via the oauth flow
746
+ * or a personal access token.
747
+ * @param config.apiURI – URL of your SidekickDB server. Required.
748
+ * @throws {MissingApiURIError} When `apiURI` is missing.
749
+ */
750
+ constructor(config) {
751
+ this.#auth = config?.auth;
752
+ this.#apiURI = (0, core_1.requireApiURI)(config?.apiURI, {
753
+ target: 'new PlatformApi()',
754
+ });
755
+ }
756
+ token() {
757
+ if (!this.#auth) {
758
+ throw new PlatformApiMissingAuthError();
759
+ }
760
+ if ('token' in this.#auth) {
761
+ return this.#auth.token;
762
+ }
763
+ return this.#auth.accessToken;
764
+ }
765
+ canRefreshToken() {
766
+ if (!this.#auth) {
767
+ throw new PlatformApiMissingAuthError();
768
+ }
769
+ return ('refreshToken' in this.#auth &&
770
+ 'clientId' in this.#auth &&
771
+ 'clientSecret' in this.#auth &&
772
+ this.#auth.refreshToken != null &&
773
+ this.#auth.clientId != null &&
774
+ this.#auth.clientSecret != null);
775
+ }
776
+ async refreshToken() {
777
+ if (!this.#auth) {
778
+ throw new PlatformApiMissingAuthError();
779
+ }
780
+ if (!this.canRefreshToken() ||
781
+ // Checked in canRefreshToken, but this lets
782
+ // typescript refine this.#auth here
783
+ !('clientId' in this.#auth)) {
784
+ return null;
785
+ }
786
+ const token = await (0, serverOAuth_ts_1.exchangeRefreshToken)({
787
+ apiURI: this.#apiURI,
788
+ clientId: this.#auth.clientId,
789
+ clientSecret: this.#auth.clientSecret,
790
+ refreshToken: this.#auth.refreshToken,
791
+ });
792
+ this.#auth.accessToken = token.accessToken;
793
+ if (this.#auth.onRefresh) {
794
+ await this.#auth.onRefresh(token);
795
+ }
796
+ return token;
797
+ }
798
+ async withRetry(f, args) {
799
+ let attempt = 0;
800
+ const [apiURI, tokenInArg, ...restArgs] = args;
801
+ let token = tokenInArg;
802
+ while (attempt < 2) {
803
+ try {
804
+ return await f(apiURI, token, ...restArgs);
805
+ }
806
+ catch (e) {
807
+ if (e instanceof core_1.InstantAPIError &&
808
+ (e.status === 401 ||
809
+ e.body?.type === 'record-expired' ||
810
+ (e.body?.type === 'record-not-found' &&
811
+ e.body.hint['record-type'].match(/token/i))) &&
812
+ this.canRefreshToken()) {
813
+ const refreshedToken = await this.refreshToken();
814
+ if (refreshedToken) {
815
+ token = refreshedToken.accessToken;
816
+ attempt++;
817
+ continue;
818
+ }
819
+ }
820
+ throw e;
821
+ }
822
+ }
823
+ }
824
+ /**
825
+ * Fetch a single app by its id.
826
+ *
827
+ * ```ts
828
+ * const { app } = await api.getApp('MY_APP_ID', {
829
+ * includeSchema: true,
830
+ * includePerms: true,
831
+ * });
832
+ * ```
833
+ *
834
+ * @template Opts – Narrow the shape of the response via the
835
+ * {@link AppDataOpts} flags.
836
+ * @param appId – UUID of the app.
837
+ * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
838
+ * @returns A typed wrapper containing the app, whose shape is expanded
839
+ * according to `Opts`.
840
+ */
841
+ async getApp(appId, opts) {
842
+ return this.withRetry(getApp, [this.#apiURI, this.token(), appId, opts]);
843
+ }
844
+ /**
845
+ * List **all apps** owned by the auth owner.
846
+ *
847
+ * ```ts
848
+ * const { apps } = await api.getApps({
849
+ * includeSchema: true,
850
+ * includePerms: true,
851
+ * });
852
+ * ```
853
+ *
854
+ * @template Opts – Same as {@link getApp}.
855
+ * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
856
+ * @returns An array wrapper; each element’s shape follows `Opts`.
857
+ */
858
+ async getApps(opts) {
859
+ return this.withRetry(getApps, [this.#apiURI, this.token(), opts]);
860
+ }
861
+ /**
862
+ * List **all orgs** that the auth owner is a member of.
863
+ *
864
+ * ```ts
865
+ * const { orgs } = await api.getOrgs();
866
+ * ```
867
+ *
868
+ * @returns An array of orgs
869
+ */
870
+ async getOrgs() {
871
+ return this.withRetry(getOrgs, [this.#apiURI, this.token()]);
872
+ }
873
+ /**
874
+ * List **all apps** owned by the auth owner.
875
+ *
876
+ * ```ts
877
+ * const { apps } = await api.getApps({
878
+ * includeSchema: true,
879
+ * includePerms: true,
880
+ * });
881
+ * ```
882
+ *
883
+ * @template Opts – Same as {@link getApp}.
884
+ * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
885
+ * @returns An array wrapper; each element’s shape follows `Opts`.
886
+ */
887
+ async getAppsForOrg(orgId, opts) {
888
+ return this.withRetry(getAppsForOrg, [
889
+ this.#apiURI,
890
+ this.token(),
891
+ orgId,
892
+ opts,
893
+ ]);
894
+ }
895
+ /**
896
+ * Gets the schema for an app by its id.
897
+ *
898
+ * ```ts
899
+ * const { schema } = await api.getSchema('MY_APP_ID');
900
+ * ```
901
+ *
902
+ * @param appId -- UUID of the app
903
+ */
904
+ async getSchema(appId) {
905
+ return this.withRetry(getAppSchema, [this.#apiURI, this.token(), appId]);
906
+ }
907
+ /**
908
+ * Gets the permissions for an app by its id.
909
+ *
910
+ * ```ts
911
+ * const { perms } = await api.getPerms('MY_APP_ID');
912
+ * ```
913
+ *
914
+ * @param appId -- UUID of the app
915
+ */
916
+ async getPerms(appId) {
917
+ return this.withRetry(getAppPerms, [this.#apiURI, this.token(), appId]);
918
+ }
919
+ /**
920
+ * Create a new app.
921
+ *
922
+ * The app will be placed in the authenticated user's account
923
+ * if no orgId is provided.
924
+ *
925
+ * Optionally set permissions and schema.
926
+ *
927
+ * ```ts
928
+ * const { app } = await api.createApp({
929
+ * title: 'My new app',
930
+ * // Optional permissions
931
+ * perms: { $default: { allow: { $default: 'false' } } },
932
+ * // Optional schema
933
+ * schema: i.schema({
934
+ * entities: { books: i.entity({ title: i.string() }) },
935
+ * }),
936
+ * });
937
+ * ```
938
+ *
939
+ * @param fields
940
+ * @param fields.title -- Title for app
941
+ * @param fields.schema -- Optional schema for the app
942
+ * @param fields.perms -- Optional permissions for the app
943
+ * @param fields.orgId -- Optional id of the org that the app will be placed in
944
+ */
945
+ async createApp(fields) {
946
+ return this.withRetry(createApp, [this.#apiURI, this.token(), fields]);
947
+ }
948
+ /**
949
+ * Create a new temporary app.
950
+ *
951
+ * Optionally set permissions and schema.
952
+ *
953
+ * ```ts
954
+ * const { app } = await api.createTemporaryApp({
955
+ * title: 'My new app',
956
+ * // Optional permissions
957
+ * perms: { $default: { allow: { $default: 'false' } } },
958
+ * // Optional schema
959
+ * schema: i.schema({
960
+ * entities: { books: i.entity({ title: i.string() }) },
961
+ * }),
962
+ * });
963
+ * ```
964
+ *
965
+ * @param fields
966
+ * @param fields.title -- Title for app
967
+ * @param fields.schema -- Optional schema for the app
968
+ * @param fields.perms -- Optional permissions for the app
969
+ */
970
+ async createTemporaryApp(fields) {
971
+ return createTemporaryApp(this.#apiURI, fields);
972
+ }
973
+ /**
974
+ * Update the title of an app by its id.
975
+ *
976
+ * ```ts
977
+ * const { app } = await api.updateApp('MY_APP_ID', {
978
+ * title: 'New title',
979
+ * });
980
+ * ```
981
+ *
982
+ * @param appId -- UUID of the app
983
+ * @param fields.title -- New title for the app
984
+ */
985
+ async updateApp(appId, fields) {
986
+ return this.withRetry(updateApp, [
987
+ this.#apiURI,
988
+ this.token(),
989
+ appId,
990
+ fields,
991
+ ]);
992
+ }
993
+ /**
994
+ * Delete an app by its id.
995
+ *
996
+ * ```ts
997
+ * const { app } = await api.deleteApp('MY_APP_ID');
998
+ * ```
999
+ *
1000
+ * @param appId -- UUID of the app
1001
+ */
1002
+ async deleteApp(appId) {
1003
+ return this.withRetry(deleteApp, [this.#apiURI, this.token(), appId]);
1004
+ }
1005
+ /**
1006
+ * Dry-run a **schema push** and receive a _plan_ of steps the server would
1007
+ * execute.
1008
+ *
1009
+ * ```ts
1010
+ * const { steps } = await api.planSchemaPush(appId, body);
1011
+ * ```
1012
+ */
1013
+ async planSchemaPush(appId, body) {
1014
+ const useOverwrite = shouldOverwrite(body);
1015
+ return this.withRetry(useOverwrite ? planSchemaPushOverwrite : planSchemaPush, [this.#apiURI, this.token(), appId, body]);
1016
+ }
1017
+ /**
1018
+ * Execute a **schema push**. The server returns a long-running job
1019
+ * represented as a {@link ProgressPromise}: you can both `await` the final
1020
+ * result **or** subscribe to intermediate status updates.
1021
+ *
1022
+ * ```ts
1023
+ * // 1) Subscribe to progress
1024
+ * const schema = i.schema({
1025
+ * entities: {
1026
+ * books: i.entity({
1027
+ * title: i.string().indexed(),
1028
+ * }),
1029
+ * },
1030
+ * });
1031
+ * const job = api.schemaPush(appId, { overwrite: true, schema: schema });
1032
+ * job
1033
+ * .then(({ summary }) => console.log('done!', summary))
1034
+ * .catch((e) => console.error(e));
1035
+ * job.subscribe({
1036
+ * next: (status) => renderProgress(status),
1037
+ * });
1038
+ *
1039
+ * // 2) Or just await it
1040
+ * const result = await api.schemaPush(appId, { schema: schema });
1041
+ * ```
1042
+ */
1043
+ schemaPush(appId, body) {
1044
+ if (!this.#auth) {
1045
+ throw new PlatformApiMissingAuthError();
1046
+ }
1047
+ return new ProgressPromise_ts_1.ProgressPromise(async (progress, resolve, reject) => {
1048
+ try {
1049
+ const useOverwrite = shouldOverwrite(body);
1050
+ const pushFn = useOverwrite ? schemaPushOverwrite : schemaPush;
1051
+ // It's tricky to add withRetry to the background process that fetches the jobs,
1052
+ // so we'll just refresh the token at the start.
1053
+ if (this.canRefreshToken()) {
1054
+ try {
1055
+ await this.refreshToken();
1056
+ }
1057
+ catch (_e) { }
1058
+ }
1059
+ pushFn(this.#apiURI, this.token(), appId, body).subscribe({
1060
+ complete(v) {
1061
+ resolve(v);
1062
+ },
1063
+ error(e) {
1064
+ reject(e);
1065
+ },
1066
+ next(v) {
1067
+ progress(v);
1068
+ },
1069
+ });
1070
+ }
1071
+ catch (e) {
1072
+ reject(e);
1073
+ }
1074
+ });
1075
+ }
1076
+ /**
1077
+ * Update permission rules for an app by its id.
1078
+ *
1079
+ * Completely replaces the current rule set.
1080
+ *
1081
+ * ```ts
1082
+ * const { steps } = await api.pushPerms(appId, {
1083
+ * perms: {
1084
+ * $default: { allow: { $default: 'false' } },
1085
+ * books: { allow: { view: 'true', $default: 'false' } },
1086
+ * },
1087
+ * });
1088
+ * ```
1089
+ */
1090
+ async pushPerms(appId, body) {
1091
+ if (!this.#auth) {
1092
+ throw new PlatformApiMissingAuthError();
1093
+ }
1094
+ return this.withRetry(pushPerms, [this.#apiURI, this.token(), appId, body]);
1095
+ }
1096
+ async tokenInfo() {
1097
+ if (!this.#auth) {
1098
+ throw new PlatformApiMissingAuthError();
1099
+ }
1100
+ return this.withRetry(tokenInfo, [this.#apiURI, this.token()]);
1101
+ }
1102
+ /**
1103
+ * Returns a {@link Webhooks} instance scoped to `appId`. You don't need
1104
+ * auth on this PlatformApi to verify signatures or process incoming
1105
+ * deliveries — only `webhooks(appId).manager.*` requires it, and those
1106
+ * calls are routed through {@link withRetry}, so an expired access token
1107
+ * is transparently refreshed.
1108
+ *
1109
+ * Pass `schema` (e.g. from {@link apiSchemaToInstantSchemaDef}) for typed
1110
+ * handler records and typed `namespaces` on `manager.create`/`update`.
1111
+ */
1112
+ webhooks(appId, opts) {
1113
+ const withAuth = (operation) => this.withRetry((_apiURI, token) => operation(token), [this.#apiURI, this.token()]);
1114
+ return new webhooks_1.Webhooks({
1115
+ appId,
1116
+ apiURI: this.#apiURI,
1117
+ schema: opts?.schema,
1118
+ withAuth,
1119
+ });
1120
+ }
1121
+ /**
1122
+ * Returns a {@link BackupsManager} scoped to `appId` for listing an app's
1123
+ * backups and downloading their contents. Calls are routed through
1124
+ * {@link withRetry}, so an expired access token is transparently refreshed.
1125
+ */
1126
+ backups(appId) {
1127
+ const withAuth = (operation) => this.withRetry((_apiURI, token) => operation(token), [this.#apiURI, this.token()]);
1128
+ return new backups_ts_1.BackupsManager({ appId, apiURI: this.#apiURI, withAuth });
1129
+ }
1130
+ }
1131
+ exports.PlatformApi = PlatformApi;
1132
+ //# sourceMappingURL=api.js.map