@sidekickdb/platform 0.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
package/src/schema.ts ADDED
@@ -0,0 +1,497 @@
1
+ import {
2
+ AttrsDefs,
3
+ CardinalityKind,
4
+ DataAttrDef,
5
+ EntityDef,
6
+ InstantDBAttr,
7
+ InstantDBCheckedDataType,
8
+ InstantDBIdent,
9
+ InstantSchemaDef,
10
+ LinkAttrDef,
11
+ RoomsDef,
12
+ } from '@sidekickdb/core';
13
+
14
+ import {
15
+ indentLines,
16
+ joinWithTrailingSep,
17
+ sortedEntries,
18
+ formatKey,
19
+ GenericSchemaDef,
20
+ } from './util.ts';
21
+
22
+ export type InstantAPIPlatformSchema = {
23
+ refs: Record<string, InstantDBAttr>;
24
+ blobs: Record<string, Record<string, InstantDBAttr>>;
25
+ };
26
+
27
+ export type InstantAPISchemaPlanAddAttrStep = {
28
+ type: 'add-attr';
29
+ friendlyDescription: string;
30
+ attr: InstantDBAttr;
31
+ };
32
+
33
+ export type InstantAPISchemaPlanDeleteAttrStep = {
34
+ type: 'delete-attr';
35
+ friendlyDescription: string;
36
+ attrId: string;
37
+ };
38
+
39
+ export type InstantAPISchemaPlanUpdateAttrStep = {
40
+ type: 'update-attr';
41
+ friendlyDescription: string;
42
+ attr: InstantDBAttr;
43
+ };
44
+
45
+ export type InstantAPISchemaPlanIndexStep = {
46
+ type: 'index';
47
+ friendlyDescription: string;
48
+ attrId: string;
49
+ forwardIdentity: InstantDBIdent;
50
+ };
51
+
52
+ export type InstantAPISchemaPlanRemoveIndexStep = {
53
+ type: 'remove-index';
54
+ friendlyDescription: string;
55
+ attrId: string;
56
+ forwardIdentity: InstantDBIdent;
57
+ };
58
+
59
+ export type InstantAPISchemaPlanUniqueStep = {
60
+ type: 'unique';
61
+ friendlyDescription: string;
62
+ attrId: string;
63
+ forwardIdentity: InstantDBIdent;
64
+ };
65
+
66
+ export type InstantAPISchemaPlanRemoveUniqueStep = {
67
+ type: 'remove-unique';
68
+ friendlyDescription: string;
69
+ attrId: string;
70
+ forwardIdentity: InstantDBIdent;
71
+ };
72
+
73
+ export type InstantAPISchemaPlanRequiredStep = {
74
+ type: 'required';
75
+ friendlyDescription: string;
76
+ attrId: string;
77
+ forwardIdentity: InstantDBIdent;
78
+ };
79
+
80
+ export type InstantAPISchemaPlanRemoveRequiredStep = {
81
+ type: 'remove-required';
82
+ friendlyDescription: string;
83
+ attrId: string;
84
+ forwardIdentity: InstantDBIdent;
85
+ };
86
+
87
+ export type InstantAPISchemaPlanCheckDataTypeStep = {
88
+ type: 'check-data-type';
89
+ friendlyDescription: string;
90
+ attrId: string;
91
+ forwardIdentity: InstantDBIdent;
92
+ checkedDataType: InstantDBCheckedDataType;
93
+ };
94
+
95
+ export type InstantAPISchemaPlanRemoveDataTypeStep = {
96
+ type: 'remove-data-type';
97
+ friendlyDescription: string;
98
+ attrId: string;
99
+ forwardIdentity: InstantDBIdent;
100
+ };
101
+
102
+ type InstantBackgroundSchemaBaseJob = {
103
+ id: string;
104
+ createdAt: Date;
105
+ updatedAt: Date;
106
+ status: 'completed' | 'waiting' | 'processing' | 'errored';
107
+ workEstimate: number | null;
108
+ workCompleted: number | null;
109
+ error?:
110
+ | 'invalid-triple-error'
111
+ | 'invalid-attr-state-error'
112
+ | 'triple-not-unique-error'
113
+ | 'triple-too-large-error'
114
+ | 'missing-required-error'
115
+ | 'unexpected-error';
116
+ invalidTriplesSample?: {
117
+ entityId: string;
118
+ value: any;
119
+ jsonType:
120
+ | 'string'
121
+ | 'number'
122
+ | 'boolean'
123
+ | 'null'
124
+ | 'object'
125
+ | 'array'
126
+ | 'date';
127
+ }[];
128
+ };
129
+
130
+ type InstantBackgroundSchemaBaseJobWithInvalidTriples =
131
+ InstantBackgroundSchemaBaseJob & {
132
+ invalidTriplesSample?: {
133
+ entityId: string;
134
+ value: any;
135
+ jsonType:
136
+ | 'string'
137
+ | 'number'
138
+ | 'boolean'
139
+ | 'null'
140
+ | 'object'
141
+ | 'array'
142
+ | 'date';
143
+ }[];
144
+ };
145
+
146
+ export interface InstantBackgroundSchemaRemoveDataTypeJob
147
+ extends InstantBackgroundSchemaBaseJob {
148
+ type: 'remove-data-type';
149
+ }
150
+
151
+ export interface InstantBackgroundSchemaCheckDataTypeJob
152
+ extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
153
+ type: 'check-data-type';
154
+ checkedDataType: InstantDBCheckedDataType;
155
+ }
156
+
157
+ export interface InstantBackgroundSchemaAddIndexJob
158
+ extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
159
+ type: 'index';
160
+ }
161
+
162
+ export interface InstantBackgroundSchemaRemoveIndexJob
163
+ extends InstantBackgroundSchemaBaseJob {
164
+ type: 'remove-index';
165
+ }
166
+
167
+ export interface InstantBackgroundSchemaAddUniqueJob
168
+ extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
169
+ type: 'unique';
170
+ invalidUniqueValue?: any;
171
+ }
172
+
173
+ export interface InstantBackgroundSchemaRemoveUniqueJob
174
+ extends InstantBackgroundSchemaBaseJob {
175
+ type: 'remove-unique';
176
+ }
177
+
178
+ export interface InstantBackgroundSchemaAddRequiredJob
179
+ extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
180
+ type: 'required';
181
+ }
182
+
183
+ export interface InstantBackgroundSchemaRemoveRequiredJob
184
+ extends InstantBackgroundSchemaBaseJob {
185
+ type: 'remove-required';
186
+ }
187
+
188
+ export type InstantAPISchemaPlanStep =
189
+ | InstantAPISchemaPlanAddAttrStep
190
+ | InstantAPISchemaPlanDeleteAttrStep
191
+ | InstantAPISchemaPlanUpdateAttrStep
192
+ | InstantAPISchemaPlanIndexStep
193
+ | InstantAPISchemaPlanRemoveIndexStep
194
+ | InstantAPISchemaPlanUniqueStep
195
+ | InstantAPISchemaPlanRemoveUniqueStep
196
+ | InstantAPISchemaPlanRequiredStep
197
+ | InstantAPISchemaPlanRemoveRequiredStep
198
+ | InstantAPISchemaPlanCheckDataTypeStep
199
+ | InstantAPISchemaPlanRemoveDataTypeStep;
200
+
201
+ type BackgroundJobByStep = {
202
+ index: InstantBackgroundSchemaAddIndexJob;
203
+ 'remove-index': InstantBackgroundSchemaRemoveIndexJob;
204
+ unique: InstantBackgroundSchemaAddUniqueJob;
205
+ 'remove-unique': InstantBackgroundSchemaRemoveUniqueJob;
206
+ required: InstantBackgroundSchemaAddRequiredJob;
207
+ 'remove-required': InstantBackgroundSchemaRemoveRequiredJob;
208
+ 'check-data-type': InstantBackgroundSchemaCheckDataTypeJob;
209
+ 'remove-data-type': InstantBackgroundSchemaRemoveDataTypeJob;
210
+ };
211
+
212
+ // Adds the proper flavor of the backgroundJob type to the steps
213
+ // that run in the background
214
+ export type WithBackgroundJob<P extends { type: string }> =
215
+ P['type'] extends keyof BackgroundJobByStep
216
+ ? P & { backgroundJob: BackgroundJobByStep[P['type']] }
217
+ : P;
218
+
219
+ export type InstantAPISchemaPushAddAttrStep =
220
+ WithBackgroundJob<InstantAPISchemaPlanAddAttrStep>;
221
+
222
+ export type InstantAPISchemaPushUpdateAttrStep =
223
+ WithBackgroundJob<InstantAPISchemaPlanUpdateAttrStep>;
224
+
225
+ export type InstantAPISchemaPushIndexStep =
226
+ WithBackgroundJob<InstantAPISchemaPlanIndexStep>;
227
+
228
+ export type InstantAPISchemaPushRemoveIndexStep =
229
+ WithBackgroundJob<InstantAPISchemaPlanRemoveIndexStep>;
230
+
231
+ export type InstantAPISchemaPushUniqueStep =
232
+ WithBackgroundJob<InstantAPISchemaPlanUniqueStep>;
233
+
234
+ export type InstantAPISchemaPushRemoveUniqueStep =
235
+ WithBackgroundJob<InstantAPISchemaPlanRemoveUniqueStep>;
236
+
237
+ export type InstantAPISchemaPushRequiredStep =
238
+ WithBackgroundJob<InstantAPISchemaPlanRequiredStep>;
239
+
240
+ export type InstantAPISchemaPushRemoveRequiredStep =
241
+ WithBackgroundJob<InstantAPISchemaPlanRemoveRequiredStep>;
242
+
243
+ export type InstantAPISchemaPushCheckDataTypeStep =
244
+ WithBackgroundJob<InstantAPISchemaPlanCheckDataTypeStep>;
245
+
246
+ export type InstantAPISchemaPushRemoveDataTypeStep =
247
+ WithBackgroundJob<InstantAPISchemaPlanRemoveDataTypeStep>;
248
+
249
+ export type InstantAPISchemaPushStep =
250
+ | InstantAPISchemaPushAddAttrStep
251
+ | InstantAPISchemaPushUpdateAttrStep
252
+ | InstantAPISchemaPushIndexStep
253
+ | InstantAPISchemaPushRemoveIndexStep
254
+ | InstantAPISchemaPushUniqueStep
255
+ | InstantAPISchemaPushRemoveUniqueStep
256
+ | InstantAPISchemaPushRequiredStep
257
+ | InstantAPISchemaPushRemoveRequiredStep
258
+ | InstantAPISchemaPushCheckDataTypeStep
259
+ | InstantAPISchemaPushRemoveDataTypeStep;
260
+
261
+ function attrDefToCodeString([name, attr]: [
262
+ string,
263
+ DataAttrDef<string, boolean, boolean>,
264
+ ]) {
265
+ const type =
266
+ (attr.metadata.derivedType as any)?.type || attr.valueType || 'any';
267
+ const unique = attr.config.unique ? '.unique()' : '';
268
+ const index = attr.config.indexed ? '.indexed()' : '';
269
+ const required = attr.required ? '' : '.optional()';
270
+ return `${formatKey(name)}: i.${type}()${unique}${index}${required}`;
271
+ }
272
+
273
+ function entityDefToCodeStr(
274
+ name: string,
275
+ edef: EntityDef<
276
+ AttrsDefs,
277
+ Record<string, LinkAttrDef<CardinalityKind, string>>,
278
+ any
279
+ >,
280
+ ) {
281
+ const attrBlock = joinWithTrailingSep(
282
+ sortedEntries(edef.attrs).map(attrDefToCodeString),
283
+ ',\n',
284
+ ',',
285
+ );
286
+
287
+ // a block of code for each entity
288
+ return `${formatKey(name)}: i.entity({${attrBlock.length ? '\n' : ''}${indentLines(attrBlock, 2)}${attrBlock.length ? '\n' : ''}})`;
289
+ }
290
+
291
+ export function identEtype(ident: InstantDBIdent) {
292
+ return ident[1];
293
+ }
294
+
295
+ export function identLabel(ident: InstantDBIdent) {
296
+ return ident[2];
297
+ }
298
+
299
+ export function identName(ident: InstantDBIdent) {
300
+ return `${identEtype(ident)}.${identLabel(ident)}`;
301
+ }
302
+
303
+ export function attrFwdLabel(attr: InstantDBAttr) {
304
+ return attr['forward-identity']?.[2];
305
+ }
306
+
307
+ export function attrFwdEtype(attr: InstantDBAttr) {
308
+ return attr['forward-identity']?.[1];
309
+ }
310
+
311
+ export function attrRevLabel(attr: InstantDBAttr) {
312
+ return attr['reverse-identity']?.[2];
313
+ }
314
+
315
+ export function attrRevEtype(attr: InstantDBAttr) {
316
+ return attr['reverse-identity']?.[1];
317
+ }
318
+
319
+ export function attrFwdName(attr: InstantDBAttr) {
320
+ return `${attrFwdEtype(attr)}.${attrFwdLabel(attr)}`;
321
+ }
322
+
323
+ export function attrRevName(attr: InstantDBAttr) {
324
+ if (attr['reverse-identity']) {
325
+ return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`;
326
+ }
327
+ }
328
+
329
+ function roomDefToCodeStr(room: RoomsDef[string]) {
330
+ let ret = '{';
331
+
332
+ if (room.presence) {
333
+ ret += `\n${indentLines(entityDefToCodeStr('presence', room.presence), 4)},`;
334
+ }
335
+
336
+ if (room.topics) {
337
+ ret += `\n "topics": {`;
338
+
339
+ for (const [topicName, topicConfig] of Object.entries(room.topics)) {
340
+ ret += `\n${indentLines(entityDefToCodeStr(topicName, topicConfig), 6)},`;
341
+ }
342
+ ret += `\n }`;
343
+ }
344
+
345
+ ret += ret === '{' ? '}' : '\n }';
346
+
347
+ return ret;
348
+ }
349
+
350
+ function roomsCodeStr(rooms: RoomsDef) {
351
+ let ret = '{';
352
+
353
+ for (const [roomType, roomDef] of Object.entries(rooms)) {
354
+ ret += `\n ${formatKey(roomType)}: ${roomDefToCodeStr(roomDef)},`;
355
+ }
356
+ ret += ret === '{' ? '}' : '\n}';
357
+
358
+ return ret;
359
+ }
360
+
361
+ export function generateSchemaTypescriptFile(
362
+ prevSchema: GenericSchemaDef | null | undefined,
363
+ newSchema: GenericSchemaDef,
364
+ instantModuleName: string,
365
+ ): string {
366
+ // entities
367
+ const entitiesEntriesCode = joinWithTrailingSep(
368
+ sortedEntries(newSchema.entities).map(([etype, entityDef]) =>
369
+ entityDefToCodeStr(etype, entityDef),
370
+ ),
371
+ ',\n',
372
+ ',',
373
+ );
374
+
375
+ const entitiesObjCode = `{\n${indentLines(entitiesEntriesCode, 2)}\n}`;
376
+
377
+ const linksEntriesCode = JSON.stringify(newSchema.links, null, 2).trim();
378
+
379
+ // rooms
380
+ const rooms = prevSchema?.rooms || {};
381
+ const roomsCode = roomsCodeStr(rooms);
382
+ const kv = (k: string, v: string) => {
383
+ return indentLines(`${k}: ${v}`, 2);
384
+ };
385
+
386
+ const code = `// Docs: https://sidekickdb.co/docs/modeling-data
387
+
388
+ import { i } from "${instantModuleName ?? '@sidekickdb/core'}";
389
+
390
+ const _schema = i.schema({
391
+ ${kv('entities', entitiesObjCode)},
392
+ ${kv('links', linksEntriesCode)},
393
+ ${kv('rooms', roomsCode)}
394
+ });
395
+
396
+ // This helps TypeScript display nicer intellisense
397
+ type _AppSchema = typeof _schema;
398
+ interface AppSchema extends _AppSchema {}
399
+ const schema: AppSchema = _schema;
400
+
401
+ export type { AppSchema }
402
+ export default schema;
403
+ `;
404
+
405
+ return code;
406
+ }
407
+
408
+ export class SchemaValidationError extends Error {
409
+ constructor(message: string) {
410
+ super(message);
411
+ this.name = 'SchemaValidationError';
412
+ }
413
+ }
414
+
415
+ export function collectSystemCatalogIdentNames(currentAttrs: InstantDBAttr[]) {
416
+ const allSystemIdents = currentAttrs
417
+ .filter((attr) => attr.catalog === 'system')
418
+ .flatMap((attr) =>
419
+ [attr['forward-identity'], attr['reverse-identity']].filter(Boolean),
420
+ )
421
+ .filter((x): x is NonNullable<typeof x> => Boolean(x));
422
+
423
+ let res: Record<string, Set<string>> = {};
424
+
425
+ for (const [_, etype, label] of allSystemIdents) {
426
+ res[etype] = res[etype] || new Set();
427
+ res[etype].add(label);
428
+ }
429
+
430
+ return res;
431
+ }
432
+
433
+ export const validateSchema = (
434
+ schema: GenericSchemaDef,
435
+ systemCatalogIdentNames: Record<string, Set<string>>,
436
+ ) => {
437
+ const entityNames = Object.keys(schema.entities);
438
+
439
+ for (const [etype, entityDef] of Object.entries(schema.entities)) {
440
+ if (!etype.startsWith('$')) continue;
441
+ if (!systemCatalogIdentNames[etype]) {
442
+ throw new SchemaValidationError(
443
+ 'The $ keyword is reserved for system namespaces.' +
444
+ `\nYou can't create '${etype}'. Perhaps call it '${etype.slice(1)}' instead?`,
445
+ );
446
+ }
447
+ for (const [attrName, attrDef] of Object.entries(entityDef.attrs)) {
448
+ if (systemCatalogIdentNames[etype].has(attrName)) {
449
+ continue;
450
+ }
451
+ if (attrDef.required) {
452
+ throw new SchemaValidationError(
453
+ `The '${etype}' namespace is managed by the system and can't modify required constraints yet.` +
454
+ `\nMake sure to set ${etype}.${attrName} as optional.` +
455
+ `\n i.e { ${attrName}: i.${attrDef.valueType}().optional() }`,
456
+ );
457
+ }
458
+ }
459
+ }
460
+
461
+ for (const link of Object.values(schema.links)) {
462
+ if (
463
+ systemCatalogIdentNames[link.forward.on] &&
464
+ !systemCatalogIdentNames[link.forward.on].has(link.forward.label) &&
465
+ link.forward.required
466
+ ) {
467
+ throw new SchemaValidationError(
468
+ `The ${link.forward.on} namespace is managed by the system and can't modify required constraints yet.` +
469
+ `\nMake sure to set ${link.forward.on}${link.forward.label} as 'optional'.` +
470
+ `\n i.e { 'on': '${link.forward.on}', 'label': ${link.forward.label}, 'required': false }`,
471
+ );
472
+ }
473
+
474
+ if (link.forward.has === 'many' && link.forward.onDelete === 'cascade') {
475
+ throw new SchemaValidationError(
476
+ `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: "cascade" with has: "many"`,
477
+ );
478
+ }
479
+ if (link.reverse.has === 'many' && link.reverse.onDelete === 'cascade') {
480
+ throw new SchemaValidationError(
481
+ `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: "cascade" with has: "many"`,
482
+ );
483
+ }
484
+
485
+ const linkDisplay = `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label}`;
486
+ if (!entityNames.includes(link.forward.on)) {
487
+ throw new SchemaValidationError(
488
+ `${linkDisplay} connects to non existing entity "${link.forward.on}".`,
489
+ );
490
+ }
491
+ if (!entityNames.includes(link.reverse.on)) {
492
+ throw new SchemaValidationError(
493
+ `${linkDisplay} connects to non existing entity "${link.forward.on}".`,
494
+ );
495
+ }
496
+ }
497
+ };
@@ -0,0 +1,119 @@
1
+ import { requireApiURI } from '@sidekickdb/core';
2
+ import { InstantOAuthError } from './oauthCommon.ts';
3
+
4
+ export async function exchangeCodeForToken({
5
+ code,
6
+ clientId,
7
+ clientSecret,
8
+ redirectUri,
9
+ apiURI: apiURIOpt,
10
+ }: {
11
+ code: string;
12
+ clientId: string;
13
+ clientSecret: string;
14
+ redirectUri: string;
15
+ apiURI?: string;
16
+ }): Promise<{
17
+ accessToken: string;
18
+ refreshToken: string;
19
+ expiresAt: Date;
20
+ scopes: string;
21
+ tokenType: 'Bearer';
22
+ }> {
23
+ const apiURI = requireApiURI(apiURIOpt, {
24
+ target: 'exchangeCodeForToken()',
25
+ });
26
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
27
+ method: 'POST',
28
+ headers: { 'Content-type': 'application/json' },
29
+ body: JSON.stringify({
30
+ grant_type: 'authorization_code',
31
+ code,
32
+ redirect_uri: redirectUri,
33
+ client_id: clientId,
34
+ client_secret: clientSecret,
35
+ }),
36
+ });
37
+
38
+ if (!res.ok) {
39
+ const text = await res.text();
40
+ let error;
41
+
42
+ try {
43
+ const json = JSON.parse(text);
44
+ error = {
45
+ error: json.error,
46
+ errorDescription: json.error_description,
47
+ message: `OAuth error: ${json.error || 'server_error'}`,
48
+ };
49
+ } catch (e) {
50
+ error = {
51
+ error: 'server_error',
52
+ message: 'OAuth error: server_error',
53
+ };
54
+ }
55
+
56
+ throw new InstantOAuthError(error);
57
+ }
58
+
59
+ const json = (await res.json()) as {
60
+ access_token: string;
61
+ refresh_token: string;
62
+ expires_in: number;
63
+ scopes: string;
64
+ token_type: 'Bearer';
65
+ };
66
+
67
+ return {
68
+ accessToken: json.access_token,
69
+ expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),
70
+ refreshToken: json.refresh_token,
71
+ scopes: json.scopes,
72
+ tokenType: json.token_type,
73
+ };
74
+ }
75
+
76
+ export async function exchangeRefreshToken({
77
+ clientId,
78
+ clientSecret,
79
+ refreshToken,
80
+ apiURI: apiURIOpt,
81
+ }: {
82
+ clientId: string;
83
+ clientSecret: string;
84
+ refreshToken: string;
85
+ apiURI?: string;
86
+ }): Promise<{
87
+ accessToken: string;
88
+ expiresAt: Date;
89
+ scopes: string;
90
+ tokenType: 'Bearer';
91
+ }> {
92
+ const apiURI = requireApiURI(apiURIOpt, {
93
+ target: 'exchangeRefreshToken()',
94
+ });
95
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
96
+ method: 'POST',
97
+ headers: { 'Content-Type': 'application/json' },
98
+ body: JSON.stringify({
99
+ grant_type: 'refresh_token',
100
+ refresh_token: refreshToken,
101
+ client_id: clientId,
102
+ client_secret: clientSecret,
103
+ }),
104
+ });
105
+
106
+ const json = (await res.json()) as {
107
+ access_token: string;
108
+ expires_in: number;
109
+ scopes: string;
110
+ token_type: 'Bearer';
111
+ };
112
+
113
+ return {
114
+ accessToken: json.access_token,
115
+ expiresAt: new Date((json.expires_in - 30) * 1000),
116
+ scopes: json.scopes,
117
+ tokenType: json.token_type,
118
+ };
119
+ }