@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perms.js","sourceRoot":"","sources":["../../src/perms.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAA+B,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MA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CAAC,OAAO,EAAE;QACzB,cAAc;QACd,UAAU,EAAE,QAAQ;QACpB,aAAa,EAAE,KAAK;QACpB,OAAO,EAAE,CAAC,YAAY,CAAC;KACxB,CAAC,CAAC;IACH,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,+BAA+B,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC;IAC9E,CAAC;IAED,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { parse, type ParseResult, type File } from '@babel/parser';\nimport { astToJson } from './typescript-schema.ts';\n\nexport function generatePermsTypescriptFile(\n permsCode: null | Record<string, any>,\n instantModuleName: string,\n) {\n const rulesTxt =\n permsCode && Object.keys(permsCode).length\n ? JSON.stringify(permsCode, null, 2)\n : `{\n /**\n * Welcome to SidekickDB's permission system!\n * Right now your rules are empty. To start filling them in, check out the docs:\n * https://sidekickdb.co/docs/permissions\n *\n * Here's an example to give you a feel:\n * posts: {\n * allow: {\n * view: \"true\",\n * create: \"isOwner\",\n * update: \"isOwner\",\n * delete: \"isOwner\",\n * },\n * bind: {\"isOwner\": \"auth.id != null && auth.id == data.ownerId\"},\n * },\n */\n}\n`.trim();\n\n return `// Docs: https://sidekickdb.co/docs/permissions\n\nimport type { InstantRules } from \"${instantModuleName ?? '@sidekickdb/core'}\";\n\nconst rules = ${rulesTxt} satisfies InstantRules;\n\nexport default rules;\n`;\n}\n\nfunction astToPermsCode(ast: ParseResult<File>): Record<string, any> {\n for (const n of ast.program.body) {\n if (\n n.type !== 'VariableDeclaration' ||\n n.declarations.length !== 1 ||\n n.declarations[0].id.type !== 'Identifier' ||\n n.declarations[0].id.name !== 'rules'\n ) {\n continue;\n }\n\n const node = n.declarations[0];\n\n if (!node.init || node.init.type !== 'TSSatisfiesExpression') {\n throw new Error(`Could not extract rules`);\n }\n\n return astToJson(node.init.expression) as Record<string, any>;\n }\n\n throw new Error(\n 'Could not extract rules, did not find the rules variable declaration.',\n );\n}\n\nexport function permsTypescriptFileToCode(\n content: string,\n sourceFilename: string,\n) {\n const ast = parse(content, {\n sourceFilename,\n sourceType: 'module',\n errorRecovery: false,\n plugins: ['typescript'],\n });\n if (ast.errors?.length) {\n throw new Error(`Could not parse perms file. ${ast.errors[0].reasonCode}.`);\n }\n\n return astToPermsCode(ast);\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export type RelationshipKinds = `many-many` | 'one-one' | 'one-many' | 'many-one';
2
+ export declare const relationshipConstraints: Record<RelationshipKinds, {
3
+ cardinality: 'one' | 'many';
4
+ 'unique?': boolean;
5
+ }>;
6
+ export declare const relationshipConstraintsInverse: Record<string, RelationshipKinds>;
7
+ //# sourceMappingURL=relationships.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relationships.d.ts","sourceRoot":"","sources":["../../src/relationships.ts"],"names":[],"mappings":"AACA,MAAM,MAAM,iBAAiB,GACzB,WAAW,GACX,SAAS,GACT,UAAU,GACV,UAAU,CAAC;AAEf,eAAO,MAAM,uBAAuB,EAAE,MAAM,CAC1C,iBAAiB,EACjB;IAAE,WAAW,EAAE,KAAK,GAAG,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAuCpD,CAAC;AAEF,eAAO,MAAM,8BAA8B,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAM1E,CAAC"}
@@ -0,0 +1,43 @@
1
+ export const relationshipConstraints = {
2
+ /**
3
+ * users has_many tags
4
+ * tags has_many users
5
+ */
6
+ 'many-many': {
7
+ cardinality: 'many',
8
+ 'unique?': false,
9
+ },
10
+ /**
11
+ * users has_one profile
12
+ * profiles has_one owner
13
+ */
14
+ 'one-one': {
15
+ cardinality: 'one',
16
+ 'unique?': true,
17
+ },
18
+ /**
19
+ * users has_many posts
20
+ * posts has_one author
21
+ * [?users :users/posts ?posts]
22
+ * <---------------> unique!
23
+ */
24
+ 'many-one': {
25
+ cardinality: 'many',
26
+ 'unique?': true,
27
+ },
28
+ /**
29
+ * posts has_one owner
30
+ * users has_many owned_posts
31
+ * [?posts :posts/user ?users]
32
+ * <---------------> unique!
33
+ */
34
+ 'one-many': {
35
+ cardinality: 'one',
36
+ 'unique?': false,
37
+ },
38
+ };
39
+ export const relationshipConstraintsInverse = Object.fromEntries(Object.entries(relationshipConstraints).map(([k, v]) => [
40
+ `${v.cardinality}-${v['unique?']}`,
41
+ k,
42
+ ]));
43
+ //# sourceMappingURL=relationships.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relationships.js","sourceRoot":"","sources":["../../src/relationships.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,uBAAuB,GAGhC;IACF;;;OAGG;IACH,WAAW,EAAE;QACX,WAAW,EAAE,MAAM;QACnB,SAAS,EAAE,KAAK;KACjB;IACD;;;OAGG;IACH,SAAS,EAAE;QACT,WAAW,EAAE,KAAK;QAClB,SAAS,EAAE,IAAI;KAChB;IACD;;;;;OAKG;IACH,UAAU,EAAE;QACV,WAAW,EAAE,MAAM;QACnB,SAAS,EAAE,IAAI;KAChB;IAED;;;;;OAKG;IACH,UAAU,EAAE;QACV,WAAW,EAAE,KAAK;QAClB,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,8BAA8B,GACzC,MAAM,CAAC,WAAW,CAChB,MAAM,CAAC,OAAO,CAAC,uBAAuB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC;IACtD,GAAG,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,SAAS,CAAC,EAAE;IAClC,CAAsB;CACvB,CAAC,CACH,CAAC","sourcesContent":["// Copied from www/lib/relationships.ts\nexport type RelationshipKinds =\n | `many-many`\n | 'one-one'\n | 'one-many'\n | 'many-one';\n\nexport const relationshipConstraints: Record<\n RelationshipKinds,\n { cardinality: 'one' | 'many'; 'unique?': boolean }\n> = {\n /**\n * users has_many tags\n * tags has_many users\n */\n 'many-many': {\n cardinality: 'many',\n 'unique?': false,\n },\n /**\n * users has_one profile\n * profiles has_one owner\n */\n 'one-one': {\n cardinality: 'one',\n 'unique?': true,\n },\n /**\n * users has_many posts\n * posts has_one author\n * [?users :users/posts ?posts]\n * <---------------> unique!\n */\n 'many-one': {\n cardinality: 'many',\n 'unique?': true,\n },\n\n /**\n * posts has_one owner\n * users has_many owned_posts\n * [?posts :posts/user ?users]\n * <---------------> unique!\n */\n 'one-many': {\n cardinality: 'one',\n 'unique?': false,\n },\n};\n\nexport const relationshipConstraintsInverse: Record<string, RelationshipKinds> =\n Object.fromEntries(\n Object.entries(relationshipConstraints).map(([k, v]) => [\n `${v.cardinality}-${v['unique?']}`,\n k as RelationshipKinds,\n ]),\n );\n"]}
@@ -0,0 +1,161 @@
1
+ import { InstantDBAttr, InstantDBCheckedDataType, InstantDBIdent } from '@sidekickdb/core';
2
+ import { GenericSchemaDef } from './util.ts';
3
+ export type InstantAPIPlatformSchema = {
4
+ refs: Record<string, InstantDBAttr>;
5
+ blobs: Record<string, Record<string, InstantDBAttr>>;
6
+ };
7
+ export type InstantAPISchemaPlanAddAttrStep = {
8
+ type: 'add-attr';
9
+ friendlyDescription: string;
10
+ attr: InstantDBAttr;
11
+ };
12
+ export type InstantAPISchemaPlanDeleteAttrStep = {
13
+ type: 'delete-attr';
14
+ friendlyDescription: string;
15
+ attrId: string;
16
+ };
17
+ export type InstantAPISchemaPlanUpdateAttrStep = {
18
+ type: 'update-attr';
19
+ friendlyDescription: string;
20
+ attr: InstantDBAttr;
21
+ };
22
+ export type InstantAPISchemaPlanIndexStep = {
23
+ type: 'index';
24
+ friendlyDescription: string;
25
+ attrId: string;
26
+ forwardIdentity: InstantDBIdent;
27
+ };
28
+ export type InstantAPISchemaPlanRemoveIndexStep = {
29
+ type: 'remove-index';
30
+ friendlyDescription: string;
31
+ attrId: string;
32
+ forwardIdentity: InstantDBIdent;
33
+ };
34
+ export type InstantAPISchemaPlanUniqueStep = {
35
+ type: 'unique';
36
+ friendlyDescription: string;
37
+ attrId: string;
38
+ forwardIdentity: InstantDBIdent;
39
+ };
40
+ export type InstantAPISchemaPlanRemoveUniqueStep = {
41
+ type: 'remove-unique';
42
+ friendlyDescription: string;
43
+ attrId: string;
44
+ forwardIdentity: InstantDBIdent;
45
+ };
46
+ export type InstantAPISchemaPlanRequiredStep = {
47
+ type: 'required';
48
+ friendlyDescription: string;
49
+ attrId: string;
50
+ forwardIdentity: InstantDBIdent;
51
+ };
52
+ export type InstantAPISchemaPlanRemoveRequiredStep = {
53
+ type: 'remove-required';
54
+ friendlyDescription: string;
55
+ attrId: string;
56
+ forwardIdentity: InstantDBIdent;
57
+ };
58
+ export type InstantAPISchemaPlanCheckDataTypeStep = {
59
+ type: 'check-data-type';
60
+ friendlyDescription: string;
61
+ attrId: string;
62
+ forwardIdentity: InstantDBIdent;
63
+ checkedDataType: InstantDBCheckedDataType;
64
+ };
65
+ export type InstantAPISchemaPlanRemoveDataTypeStep = {
66
+ type: 'remove-data-type';
67
+ friendlyDescription: string;
68
+ attrId: string;
69
+ forwardIdentity: InstantDBIdent;
70
+ };
71
+ type InstantBackgroundSchemaBaseJob = {
72
+ id: string;
73
+ createdAt: Date;
74
+ updatedAt: Date;
75
+ status: 'completed' | 'waiting' | 'processing' | 'errored';
76
+ workEstimate: number | null;
77
+ workCompleted: number | null;
78
+ error?: 'invalid-triple-error' | 'invalid-attr-state-error' | 'triple-not-unique-error' | 'triple-too-large-error' | 'missing-required-error' | 'unexpected-error';
79
+ invalidTriplesSample?: {
80
+ entityId: string;
81
+ value: any;
82
+ jsonType: 'string' | 'number' | 'boolean' | 'null' | 'object' | 'array' | 'date';
83
+ }[];
84
+ };
85
+ type InstantBackgroundSchemaBaseJobWithInvalidTriples = InstantBackgroundSchemaBaseJob & {
86
+ invalidTriplesSample?: {
87
+ entityId: string;
88
+ value: any;
89
+ jsonType: 'string' | 'number' | 'boolean' | 'null' | 'object' | 'array' | 'date';
90
+ }[];
91
+ };
92
+ export interface InstantBackgroundSchemaRemoveDataTypeJob extends InstantBackgroundSchemaBaseJob {
93
+ type: 'remove-data-type';
94
+ }
95
+ export interface InstantBackgroundSchemaCheckDataTypeJob extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
96
+ type: 'check-data-type';
97
+ checkedDataType: InstantDBCheckedDataType;
98
+ }
99
+ export interface InstantBackgroundSchemaAddIndexJob extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
100
+ type: 'index';
101
+ }
102
+ export interface InstantBackgroundSchemaRemoveIndexJob extends InstantBackgroundSchemaBaseJob {
103
+ type: 'remove-index';
104
+ }
105
+ export interface InstantBackgroundSchemaAddUniqueJob extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
106
+ type: 'unique';
107
+ invalidUniqueValue?: any;
108
+ }
109
+ export interface InstantBackgroundSchemaRemoveUniqueJob extends InstantBackgroundSchemaBaseJob {
110
+ type: 'remove-unique';
111
+ }
112
+ export interface InstantBackgroundSchemaAddRequiredJob extends InstantBackgroundSchemaBaseJobWithInvalidTriples {
113
+ type: 'required';
114
+ }
115
+ export interface InstantBackgroundSchemaRemoveRequiredJob extends InstantBackgroundSchemaBaseJob {
116
+ type: 'remove-required';
117
+ }
118
+ export type InstantAPISchemaPlanStep = InstantAPISchemaPlanAddAttrStep | InstantAPISchemaPlanDeleteAttrStep | InstantAPISchemaPlanUpdateAttrStep | InstantAPISchemaPlanIndexStep | InstantAPISchemaPlanRemoveIndexStep | InstantAPISchemaPlanUniqueStep | InstantAPISchemaPlanRemoveUniqueStep | InstantAPISchemaPlanRequiredStep | InstantAPISchemaPlanRemoveRequiredStep | InstantAPISchemaPlanCheckDataTypeStep | InstantAPISchemaPlanRemoveDataTypeStep;
119
+ type BackgroundJobByStep = {
120
+ index: InstantBackgroundSchemaAddIndexJob;
121
+ 'remove-index': InstantBackgroundSchemaRemoveIndexJob;
122
+ unique: InstantBackgroundSchemaAddUniqueJob;
123
+ 'remove-unique': InstantBackgroundSchemaRemoveUniqueJob;
124
+ required: InstantBackgroundSchemaAddRequiredJob;
125
+ 'remove-required': InstantBackgroundSchemaRemoveRequiredJob;
126
+ 'check-data-type': InstantBackgroundSchemaCheckDataTypeJob;
127
+ 'remove-data-type': InstantBackgroundSchemaRemoveDataTypeJob;
128
+ };
129
+ export type WithBackgroundJob<P extends {
130
+ type: string;
131
+ }> = P['type'] extends keyof BackgroundJobByStep ? P & {
132
+ backgroundJob: BackgroundJobByStep[P['type']];
133
+ } : P;
134
+ export type InstantAPISchemaPushAddAttrStep = WithBackgroundJob<InstantAPISchemaPlanAddAttrStep>;
135
+ export type InstantAPISchemaPushUpdateAttrStep = WithBackgroundJob<InstantAPISchemaPlanUpdateAttrStep>;
136
+ export type InstantAPISchemaPushIndexStep = WithBackgroundJob<InstantAPISchemaPlanIndexStep>;
137
+ export type InstantAPISchemaPushRemoveIndexStep = WithBackgroundJob<InstantAPISchemaPlanRemoveIndexStep>;
138
+ export type InstantAPISchemaPushUniqueStep = WithBackgroundJob<InstantAPISchemaPlanUniqueStep>;
139
+ export type InstantAPISchemaPushRemoveUniqueStep = WithBackgroundJob<InstantAPISchemaPlanRemoveUniqueStep>;
140
+ export type InstantAPISchemaPushRequiredStep = WithBackgroundJob<InstantAPISchemaPlanRequiredStep>;
141
+ export type InstantAPISchemaPushRemoveRequiredStep = WithBackgroundJob<InstantAPISchemaPlanRemoveRequiredStep>;
142
+ export type InstantAPISchemaPushCheckDataTypeStep = WithBackgroundJob<InstantAPISchemaPlanCheckDataTypeStep>;
143
+ export type InstantAPISchemaPushRemoveDataTypeStep = WithBackgroundJob<InstantAPISchemaPlanRemoveDataTypeStep>;
144
+ export type InstantAPISchemaPushStep = InstantAPISchemaPushAddAttrStep | InstantAPISchemaPushUpdateAttrStep | InstantAPISchemaPushIndexStep | InstantAPISchemaPushRemoveIndexStep | InstantAPISchemaPushUniqueStep | InstantAPISchemaPushRemoveUniqueStep | InstantAPISchemaPushRequiredStep | InstantAPISchemaPushRemoveRequiredStep | InstantAPISchemaPushCheckDataTypeStep | InstantAPISchemaPushRemoveDataTypeStep;
145
+ export declare function identEtype(ident: InstantDBIdent): string;
146
+ export declare function identLabel(ident: InstantDBIdent): string;
147
+ export declare function identName(ident: InstantDBIdent): string;
148
+ export declare function attrFwdLabel(attr: InstantDBAttr): string;
149
+ export declare function attrFwdEtype(attr: InstantDBAttr): string;
150
+ export declare function attrRevLabel(attr: InstantDBAttr): string | undefined;
151
+ export declare function attrRevEtype(attr: InstantDBAttr): string | undefined;
152
+ export declare function attrFwdName(attr: InstantDBAttr): string;
153
+ export declare function attrRevName(attr: InstantDBAttr): string | undefined;
154
+ export declare function generateSchemaTypescriptFile(prevSchema: GenericSchemaDef | null | undefined, newSchema: GenericSchemaDef, instantModuleName: string): string;
155
+ export declare class SchemaValidationError extends Error {
156
+ constructor(message: string);
157
+ }
158
+ export declare function collectSystemCatalogIdentNames(currentAttrs: InstantDBAttr[]): Record<string, Set<string>>;
159
+ export declare const validateSchema: (schema: GenericSchemaDef, systemCatalogIdentNames: Record<string, Set<string>>) => void;
160
+ export {};
161
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,aAAa,EACb,wBAAwB,EACxB,cAAc,EAIf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAKL,gBAAgB,EACjB,MAAM,WAAW,CAAC;AAEnB,MAAM,MAAM,wBAAwB,GAAG;IACrC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC;CACtD,CAAC;AAEF,MAAM,MAAM,+BAA+B,GAAG;IAC5C,IAAI,EAAE,UAAU,CAAC;IACjB,mBAAmB,E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ED,wBAAgB,UAAU,CAAC,KAAK,EAAE,cAAc,UAE/C;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,UAE9C;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,aAAa,UAE/C;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,aAAa,UAE/C;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,aAAa,sBAE/C;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,aAAa,sBAE/C;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,aAAa,UAE9C;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,aAAa,sBAI9C;AAkCD,wBAAgB,4BAA4B,CAC1C,UAAU,EAAE,gBAAgB,GAAG,IAAI,GAAG,SAAS,EAC/C,SAAS,EAAE,gBAAgB,EAC3B,iBAAiB,EAAE,MAAM,GACxB,MAAM,CAyCR;AAED,qBAAa,qBAAsB,SAAQ,KAAK;gBAClC,OAAO,EAAE,MAAM;CAI5B;AAED,wBAAgB,8BAA8B,CAAC,YAAY,EAAE,aAAa,EAAE,+BAgB3E;AAED,eAAO,MAAM,cAAc,GACzB,QAAQ,gBAAgB,EACxB,yBAAyB,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,SA8DrD,CAAC"}
@@ -0,0 +1,158 @@
1
+ import { indentLines, joinWithTrailingSep, sortedEntries, formatKey, } from "./util.js";
2
+ function attrDefToCodeString([name, attr]) {
3
+ const type = attr.metadata.derivedType?.type || attr.valueType || 'any';
4
+ const unique = attr.config.unique ? '.unique()' : '';
5
+ const index = attr.config.indexed ? '.indexed()' : '';
6
+ const required = attr.required ? '' : '.optional()';
7
+ return `${formatKey(name)}: i.${type}()${unique}${index}${required}`;
8
+ }
9
+ function entityDefToCodeStr(name, edef) {
10
+ const attrBlock = joinWithTrailingSep(sortedEntries(edef.attrs).map(attrDefToCodeString), ',\n', ',');
11
+ // a block of code for each entity
12
+ return `${formatKey(name)}: i.entity({${attrBlock.length ? '\n' : ''}${indentLines(attrBlock, 2)}${attrBlock.length ? '\n' : ''}})`;
13
+ }
14
+ export function identEtype(ident) {
15
+ return ident[1];
16
+ }
17
+ export function identLabel(ident) {
18
+ return ident[2];
19
+ }
20
+ export function identName(ident) {
21
+ return `${identEtype(ident)}.${identLabel(ident)}`;
22
+ }
23
+ export function attrFwdLabel(attr) {
24
+ return attr['forward-identity']?.[2];
25
+ }
26
+ export function attrFwdEtype(attr) {
27
+ return attr['forward-identity']?.[1];
28
+ }
29
+ export function attrRevLabel(attr) {
30
+ return attr['reverse-identity']?.[2];
31
+ }
32
+ export function attrRevEtype(attr) {
33
+ return attr['reverse-identity']?.[1];
34
+ }
35
+ export function attrFwdName(attr) {
36
+ return `${attrFwdEtype(attr)}.${attrFwdLabel(attr)}`;
37
+ }
38
+ export function attrRevName(attr) {
39
+ if (attr['reverse-identity']) {
40
+ return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`;
41
+ }
42
+ }
43
+ function roomDefToCodeStr(room) {
44
+ let ret = '{';
45
+ if (room.presence) {
46
+ ret += `\n${indentLines(entityDefToCodeStr('presence', room.presence), 4)},`;
47
+ }
48
+ if (room.topics) {
49
+ ret += `\n "topics": {`;
50
+ for (const [topicName, topicConfig] of Object.entries(room.topics)) {
51
+ ret += `\n${indentLines(entityDefToCodeStr(topicName, topicConfig), 6)},`;
52
+ }
53
+ ret += `\n }`;
54
+ }
55
+ ret += ret === '{' ? '}' : '\n }';
56
+ return ret;
57
+ }
58
+ function roomsCodeStr(rooms) {
59
+ let ret = '{';
60
+ for (const [roomType, roomDef] of Object.entries(rooms)) {
61
+ ret += `\n ${formatKey(roomType)}: ${roomDefToCodeStr(roomDef)},`;
62
+ }
63
+ ret += ret === '{' ? '}' : '\n}';
64
+ return ret;
65
+ }
66
+ export function generateSchemaTypescriptFile(prevSchema, newSchema, instantModuleName) {
67
+ // entities
68
+ const entitiesEntriesCode = joinWithTrailingSep(sortedEntries(newSchema.entities).map(([etype, entityDef]) => entityDefToCodeStr(etype, entityDef)), ',\n', ',');
69
+ const entitiesObjCode = `{\n${indentLines(entitiesEntriesCode, 2)}\n}`;
70
+ const linksEntriesCode = JSON.stringify(newSchema.links, null, 2).trim();
71
+ // rooms
72
+ const rooms = prevSchema?.rooms || {};
73
+ const roomsCode = roomsCodeStr(rooms);
74
+ const kv = (k, v) => {
75
+ return indentLines(`${k}: ${v}`, 2);
76
+ };
77
+ const code = `// Docs: https://sidekickdb.co/docs/modeling-data
78
+
79
+ import { i } from "${instantModuleName ?? '@sidekickdb/core'}";
80
+
81
+ const _schema = i.schema({
82
+ ${kv('entities', entitiesObjCode)},
83
+ ${kv('links', linksEntriesCode)},
84
+ ${kv('rooms', roomsCode)}
85
+ });
86
+
87
+ // This helps TypeScript display nicer intellisense
88
+ type _AppSchema = typeof _schema;
89
+ interface AppSchema extends _AppSchema {}
90
+ const schema: AppSchema = _schema;
91
+
92
+ export type { AppSchema }
93
+ export default schema;
94
+ `;
95
+ return code;
96
+ }
97
+ export class SchemaValidationError extends Error {
98
+ constructor(message) {
99
+ super(message);
100
+ this.name = 'SchemaValidationError';
101
+ }
102
+ }
103
+ export function collectSystemCatalogIdentNames(currentAttrs) {
104
+ const allSystemIdents = currentAttrs
105
+ .filter((attr) => attr.catalog === 'system')
106
+ .flatMap((attr) => [attr['forward-identity'], attr['reverse-identity']].filter(Boolean))
107
+ .filter((x) => Boolean(x));
108
+ let res = {};
109
+ for (const [_, etype, label] of allSystemIdents) {
110
+ res[etype] = res[etype] || new Set();
111
+ res[etype].add(label);
112
+ }
113
+ return res;
114
+ }
115
+ export const validateSchema = (schema, systemCatalogIdentNames) => {
116
+ const entityNames = Object.keys(schema.entities);
117
+ for (const [etype, entityDef] of Object.entries(schema.entities)) {
118
+ if (!etype.startsWith('$'))
119
+ continue;
120
+ if (!systemCatalogIdentNames[etype]) {
121
+ throw new SchemaValidationError('The $ keyword is reserved for system namespaces.' +
122
+ `\nYou can't create '${etype}'. Perhaps call it '${etype.slice(1)}' instead?`);
123
+ }
124
+ for (const [attrName, attrDef] of Object.entries(entityDef.attrs)) {
125
+ if (systemCatalogIdentNames[etype].has(attrName)) {
126
+ continue;
127
+ }
128
+ if (attrDef.required) {
129
+ throw new SchemaValidationError(`The '${etype}' namespace is managed by the system and can't modify required constraints yet.` +
130
+ `\nMake sure to set ${etype}.${attrName} as optional.` +
131
+ `\n i.e { ${attrName}: i.${attrDef.valueType}().optional() }`);
132
+ }
133
+ }
134
+ }
135
+ for (const link of Object.values(schema.links)) {
136
+ if (systemCatalogIdentNames[link.forward.on] &&
137
+ !systemCatalogIdentNames[link.forward.on].has(link.forward.label) &&
138
+ link.forward.required) {
139
+ throw new SchemaValidationError(`The ${link.forward.on} namespace is managed by the system and can't modify required constraints yet.` +
140
+ `\nMake sure to set ${link.forward.on}${link.forward.label} as 'optional'.` +
141
+ `\n i.e { 'on': '${link.forward.on}', 'label': ${link.forward.label}, 'required': false }`);
142
+ }
143
+ if (link.forward.has === 'many' && link.forward.onDelete === 'cascade') {
144
+ throw new SchemaValidationError(`${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: "cascade" with has: "many"`);
145
+ }
146
+ if (link.reverse.has === 'many' && link.reverse.onDelete === 'cascade') {
147
+ throw new SchemaValidationError(`${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: "cascade" with has: "many"`);
148
+ }
149
+ const linkDisplay = `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label}`;
150
+ if (!entityNames.includes(link.forward.on)) {
151
+ throw new SchemaValidationError(`${linkDisplay} connects to non existing entity "${link.forward.on}".`);
152
+ }
153
+ if (!entityNames.includes(link.reverse.on)) {
154
+ throw new SchemaValidationError(`${linkDisplay} connects to non existing entity "${link.forward.on}".`);
155
+ }
156
+ }
157
+ };
158
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../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AAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,2CAA2C,CAC9H,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACzG,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,qBAAqB,CAC7B,GAAG,WAAW,qCAAqC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CACvE,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,qBAAqB,CAC7B,GAAG,WAAW,qCAAqC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CACvE,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC,CAAC","sourcesContent":["import {\n AttrsDefs,\n CardinalityKind,\n DataAttrDef,\n EntityDef,\n InstantDBAttr,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantSchemaDef,\n LinkAttrDef,\n RoomsDef,\n} from '@sidekickdb/core';\n\nimport {\n indentLines,\n joinWithTrailingSep,\n sortedEntries,\n formatKey,\n GenericSchemaDef,\n} from './util.ts';\n\nexport type InstantAPIPlatformSchema = {\n refs: Record<string, InstantDBAttr>;\n blobs: Record<string, Record<string, InstantDBAttr>>;\n};\n\nexport type InstantAPISchemaPlanAddAttrStep = {\n type: 'add-attr';\n friendlyDescription: string;\n attr: InstantDBAttr;\n};\n\nexport type InstantAPISchemaPlanDeleteAttrStep = {\n type: 'delete-attr';\n friendlyDescription: string;\n attrId: string;\n};\n\nexport type InstantAPISchemaPlanUpdateAttrStep = {\n type: 'update-attr';\n friendlyDescription: string;\n attr: InstantDBAttr;\n};\n\nexport type InstantAPISchemaPlanIndexStep = {\n type: 'index';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveIndexStep = {\n type: 'remove-index';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanUniqueStep = {\n type: 'unique';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveUniqueStep = {\n type: 'remove-unique';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRequiredStep = {\n type: 'required';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveRequiredStep = {\n type: 'remove-required';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanCheckDataTypeStep = {\n type: 'check-data-type';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n checkedDataType: InstantDBCheckedDataType;\n};\n\nexport type InstantAPISchemaPlanRemoveDataTypeStep = {\n type: 'remove-data-type';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\ntype InstantBackgroundSchemaBaseJob = {\n id: string;\n createdAt: Date;\n updatedAt: Date;\n status: 'completed' | 'waiting' | 'processing' | 'errored';\n workEstimate: number | null;\n workCompleted: number | null;\n error?:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n};\n\ntype InstantBackgroundSchemaBaseJobWithInvalidTriples =\n InstantBackgroundSchemaBaseJob & {\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n };\n\nexport interface InstantBackgroundSchemaRemoveDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-data-type';\n}\n\nexport interface InstantBackgroundSchemaCheckDataTypeJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'check-data-type';\n checkedDataType: InstantDBCheckedDataType;\n}\n\nexport interface InstantBackgroundSchemaAddIndexJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'index';\n}\n\nexport interface InstantBackgroundSchemaRemoveIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-index';\n}\n\nexport interface InstantBackgroundSchemaAddUniqueJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'unique';\n invalidUniqueValue?: any;\n}\n\nexport interface InstantBackgroundSchemaRemoveUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-unique';\n}\n\nexport interface InstantBackgroundSchemaAddRequiredJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'required';\n}\n\nexport interface InstantBackgroundSchemaRemoveRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-required';\n}\n\nexport type InstantAPISchemaPlanStep =\n | InstantAPISchemaPlanAddAttrStep\n | InstantAPISchemaPlanDeleteAttrStep\n | InstantAPISchemaPlanUpdateAttrStep\n | InstantAPISchemaPlanIndexStep\n | InstantAPISchemaPlanRemoveIndexStep\n | InstantAPISchemaPlanUniqueStep\n | InstantAPISchemaPlanRemoveUniqueStep\n | InstantAPISchemaPlanRequiredStep\n | InstantAPISchemaPlanRemoveRequiredStep\n | InstantAPISchemaPlanCheckDataTypeStep\n | InstantAPISchemaPlanRemoveDataTypeStep;\n\ntype BackgroundJobByStep = {\n index: InstantBackgroundSchemaAddIndexJob;\n 'remove-index': InstantBackgroundSchemaRemoveIndexJob;\n unique: InstantBackgroundSchemaAddUniqueJob;\n 'remove-unique': InstantBackgroundSchemaRemoveUniqueJob;\n required: InstantBackgroundSchemaAddRequiredJob;\n 'remove-required': InstantBackgroundSchemaRemoveRequiredJob;\n 'check-data-type': InstantBackgroundSchemaCheckDataTypeJob;\n 'remove-data-type': InstantBackgroundSchemaRemoveDataTypeJob;\n};\n\n// Adds the proper flavor of the backgroundJob type to the steps\n// that run in the background\nexport type WithBackgroundJob<P extends { type: string }> =\n P['type'] extends keyof BackgroundJobByStep\n ? P & { backgroundJob: BackgroundJobByStep[P['type']] }\n : P;\n\nexport type InstantAPISchemaPushAddAttrStep =\n WithBackgroundJob<InstantAPISchemaPlanAddAttrStep>;\n\nexport type InstantAPISchemaPushUpdateAttrStep =\n WithBackgroundJob<InstantAPISchemaPlanUpdateAttrStep>;\n\nexport type InstantAPISchemaPushIndexStep =\n WithBackgroundJob<InstantAPISchemaPlanIndexStep>;\n\nexport type InstantAPISchemaPushRemoveIndexStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveIndexStep>;\n\nexport type InstantAPISchemaPushUniqueStep =\n WithBackgroundJob<InstantAPISchemaPlanUniqueStep>;\n\nexport type InstantAPISchemaPushRemoveUniqueStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveUniqueStep>;\n\nexport type InstantAPISchemaPushRequiredStep =\n WithBackgroundJob<InstantAPISchemaPlanRequiredStep>;\n\nexport type InstantAPISchemaPushRemoveRequiredStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveRequiredStep>;\n\nexport type InstantAPISchemaPushCheckDataTypeStep =\n WithBackgroundJob<InstantAPISchemaPlanCheckDataTypeStep>;\n\nexport type InstantAPISchemaPushRemoveDataTypeStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveDataTypeStep>;\n\nexport type InstantAPISchemaPushStep =\n | InstantAPISchemaPushAddAttrStep\n | InstantAPISchemaPushUpdateAttrStep\n | InstantAPISchemaPushIndexStep\n | InstantAPISchemaPushRemoveIndexStep\n | InstantAPISchemaPushUniqueStep\n | InstantAPISchemaPushRemoveUniqueStep\n | InstantAPISchemaPushRequiredStep\n | InstantAPISchemaPushRemoveRequiredStep\n | InstantAPISchemaPushCheckDataTypeStep\n | InstantAPISchemaPushRemoveDataTypeStep;\n\nfunction attrDefToCodeString([name, attr]: [\n string,\n DataAttrDef<string, boolean, boolean>,\n]) {\n const type =\n (attr.metadata.derivedType as any)?.type || attr.valueType || 'any';\n const unique = attr.config.unique ? '.unique()' : '';\n const index = attr.config.indexed ? '.indexed()' : '';\n const required = attr.required ? '' : '.optional()';\n return `${formatKey(name)}: i.${type}()${unique}${index}${required}`;\n}\n\nfunction entityDefToCodeStr(\n name: string,\n edef: EntityDef<\n AttrsDefs,\n Record<string, LinkAttrDef<CardinalityKind, string>>,\n any\n >,\n) {\n const attrBlock = joinWithTrailingSep(\n sortedEntries(edef.attrs).map(attrDefToCodeString),\n ',\\n',\n ',',\n );\n\n // a block of code for each entity\n return `${formatKey(name)}: i.entity({${attrBlock.length ? '\\n' : ''}${indentLines(attrBlock, 2)}${attrBlock.length ? '\\n' : ''}})`;\n}\n\nexport function identEtype(ident: InstantDBIdent) {\n return ident[1];\n}\n\nexport function identLabel(ident: InstantDBIdent) {\n return ident[2];\n}\n\nexport function identName(ident: InstantDBIdent) {\n return `${identEtype(ident)}.${identLabel(ident)}`;\n}\n\nexport function attrFwdLabel(attr: InstantDBAttr) {\n return attr['forward-identity']?.[2];\n}\n\nexport function attrFwdEtype(attr: InstantDBAttr) {\n return attr['forward-identity']?.[1];\n}\n\nexport function attrRevLabel(attr: InstantDBAttr) {\n return attr['reverse-identity']?.[2];\n}\n\nexport function attrRevEtype(attr: InstantDBAttr) {\n return attr['reverse-identity']?.[1];\n}\n\nexport function attrFwdName(attr: InstantDBAttr) {\n return `${attrFwdEtype(attr)}.${attrFwdLabel(attr)}`;\n}\n\nexport function attrRevName(attr: InstantDBAttr) {\n if (attr['reverse-identity']) {\n return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`;\n }\n}\n\nfunction roomDefToCodeStr(room: RoomsDef[string]) {\n let ret = '{';\n\n if (room.presence) {\n ret += `\\n${indentLines(entityDefToCodeStr('presence', room.presence), 4)},`;\n }\n\n if (room.topics) {\n ret += `\\n \"topics\": {`;\n\n for (const [topicName, topicConfig] of Object.entries(room.topics)) {\n ret += `\\n${indentLines(entityDefToCodeStr(topicName, topicConfig), 6)},`;\n }\n ret += `\\n }`;\n }\n\n ret += ret === '{' ? '}' : '\\n }';\n\n return ret;\n}\n\nfunction roomsCodeStr(rooms: RoomsDef) {\n let ret = '{';\n\n for (const [roomType, roomDef] of Object.entries(rooms)) {\n ret += `\\n ${formatKey(roomType)}: ${roomDefToCodeStr(roomDef)},`;\n }\n ret += ret === '{' ? '}' : '\\n}';\n\n return ret;\n}\n\nexport function generateSchemaTypescriptFile(\n prevSchema: GenericSchemaDef | null | undefined,\n newSchema: GenericSchemaDef,\n instantModuleName: string,\n): string {\n // entities\n const entitiesEntriesCode = joinWithTrailingSep(\n sortedEntries(newSchema.entities).map(([etype, entityDef]) =>\n entityDefToCodeStr(etype, entityDef),\n ),\n ',\\n',\n ',',\n );\n\n const entitiesObjCode = `{\\n${indentLines(entitiesEntriesCode, 2)}\\n}`;\n\n const linksEntriesCode = JSON.stringify(newSchema.links, null, 2).trim();\n\n // rooms\n const rooms = prevSchema?.rooms || {};\n const roomsCode = roomsCodeStr(rooms);\n const kv = (k: string, v: string) => {\n return indentLines(`${k}: ${v}`, 2);\n };\n\n const code = `// Docs: https://sidekickdb.co/docs/modeling-data\n\nimport { i } from \"${instantModuleName ?? '@sidekickdb/core'}\";\n\nconst _schema = i.schema({\n${kv('entities', entitiesObjCode)},\n${kv('links', linksEntriesCode)},\n${kv('rooms', roomsCode)}\n});\n\n// This helps TypeScript display nicer intellisense\ntype _AppSchema = typeof _schema;\ninterface AppSchema extends _AppSchema {}\nconst schema: AppSchema = _schema;\n\nexport type { AppSchema }\nexport default schema;\n`;\n\n return code;\n}\n\nexport class SchemaValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SchemaValidationError';\n }\n}\n\nexport function collectSystemCatalogIdentNames(currentAttrs: InstantDBAttr[]) {\n const allSystemIdents = currentAttrs\n .filter((attr) => attr.catalog === 'system')\n .flatMap((attr) =>\n [attr['forward-identity'], attr['reverse-identity']].filter(Boolean),\n )\n .filter((x): x is NonNullable<typeof x> => Boolean(x));\n\n let res: Record<string, Set<string>> = {};\n\n for (const [_, etype, label] of allSystemIdents) {\n res[etype] = res[etype] || new Set();\n res[etype].add(label);\n }\n\n return res;\n}\n\nexport const validateSchema = (\n schema: GenericSchemaDef,\n systemCatalogIdentNames: Record<string, Set<string>>,\n) => {\n const entityNames = Object.keys(schema.entities);\n\n for (const [etype, entityDef] of Object.entries(schema.entities)) {\n if (!etype.startsWith('$')) continue;\n if (!systemCatalogIdentNames[etype]) {\n throw new SchemaValidationError(\n 'The $ keyword is reserved for system namespaces.' +\n `\\nYou can't create '${etype}'. Perhaps call it '${etype.slice(1)}' instead?`,\n );\n }\n for (const [attrName, attrDef] of Object.entries(entityDef.attrs)) {\n if (systemCatalogIdentNames[etype].has(attrName)) {\n continue;\n }\n if (attrDef.required) {\n throw new SchemaValidationError(\n `The '${etype}' namespace is managed by the system and can't modify required constraints yet.` +\n `\\nMake sure to set ${etype}.${attrName} as optional.` +\n `\\n i.e { ${attrName}: i.${attrDef.valueType}().optional() }`,\n );\n }\n }\n }\n\n for (const link of Object.values(schema.links)) {\n if (\n systemCatalogIdentNames[link.forward.on] &&\n !systemCatalogIdentNames[link.forward.on].has(link.forward.label) &&\n link.forward.required\n ) {\n throw new SchemaValidationError(\n `The ${link.forward.on} namespace is managed by the system and can't modify required constraints yet.` +\n `\\nMake sure to set ${link.forward.on}${link.forward.label} as 'optional'.` +\n `\\n i.e { 'on': '${link.forward.on}', 'label': ${link.forward.label}, 'required': false }`,\n );\n }\n\n if (link.forward.has === 'many' && link.forward.onDelete === 'cascade') {\n throw new SchemaValidationError(\n `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: \"cascade\" with has: \"many\"`,\n );\n }\n if (link.reverse.has === 'many' && link.reverse.onDelete === 'cascade') {\n throw new SchemaValidationError(\n `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: \"cascade\" with has: \"many\"`,\n );\n }\n\n const linkDisplay = `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label}`;\n if (!entityNames.includes(link.forward.on)) {\n throw new SchemaValidationError(\n `${linkDisplay} connects to non existing entity \"${link.forward.on}\".`,\n );\n }\n if (!entityNames.includes(link.reverse.on)) {\n throw new SchemaValidationError(\n `${linkDisplay} connects to non existing entity \"${link.forward.on}\".`,\n );\n }\n }\n};\n"]}
@@ -0,0 +1,25 @@
1
+ export declare function exchangeCodeForToken({ code, clientId, clientSecret, redirectUri, apiURI: apiURIOpt, }: {
2
+ code: string;
3
+ clientId: string;
4
+ clientSecret: string;
5
+ redirectUri: string;
6
+ apiURI?: string;
7
+ }): Promise<{
8
+ accessToken: string;
9
+ refreshToken: string;
10
+ expiresAt: Date;
11
+ scopes: string;
12
+ tokenType: 'Bearer';
13
+ }>;
14
+ export declare function exchangeRefreshToken({ clientId, clientSecret, refreshToken, apiURI: apiURIOpt, }: {
15
+ clientId: string;
16
+ clientSecret: string;
17
+ refreshToken: string;
18
+ apiURI?: string;
19
+ }): Promise<{
20
+ accessToken: string;
21
+ expiresAt: Date;
22
+ scopes: string;
23
+ tokenType: 'Bearer';
24
+ }>;
25
+ //# sourceMappingURL=serverOAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverOAuth.d.ts","sourceRoot":"","sources":["../../src/serverOAuth.ts"],"names":[],"mappings":"AAGA,wBAAsB,oBAAoB,CAAC,EACzC,IAAI,EACJ,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,MAAM,EAAE,SAAS,GAClB,EAAE;IACD,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,IAAI,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,QAAQ,CAAC;CACrB,CAAC,CAoDD;AAED,wBAAsB,oBAAoB,CAAC,EACzC,QAAQ,EACR,YAAY,EACZ,YAAY,EACZ,MAAM,EAAE,SAAS,GAClB,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,IAAI,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,QAAQ,CAAC;CACrB,CAAC,CA4BD"}
@@ -0,0 +1,68 @@
1
+ import { requireApiURI } from '@sidekickdb/core';
2
+ import { InstantOAuthError } from "./oauthCommon.js";
3
+ export async function exchangeCodeForToken({ code, clientId, clientSecret, redirectUri, apiURI: apiURIOpt, }) {
4
+ const apiURI = requireApiURI(apiURIOpt, {
5
+ target: 'exchangeCodeForToken()',
6
+ });
7
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
8
+ method: 'POST',
9
+ headers: { 'Content-type': 'application/json' },
10
+ body: JSON.stringify({
11
+ grant_type: 'authorization_code',
12
+ code,
13
+ redirect_uri: redirectUri,
14
+ client_id: clientId,
15
+ client_secret: clientSecret,
16
+ }),
17
+ });
18
+ if (!res.ok) {
19
+ const text = await res.text();
20
+ let error;
21
+ try {
22
+ const json = JSON.parse(text);
23
+ error = {
24
+ error: json.error,
25
+ errorDescription: json.error_description,
26
+ message: `OAuth error: ${json.error || 'server_error'}`,
27
+ };
28
+ }
29
+ catch (e) {
30
+ error = {
31
+ error: 'server_error',
32
+ message: 'OAuth error: server_error',
33
+ };
34
+ }
35
+ throw new InstantOAuthError(error);
36
+ }
37
+ const json = (await res.json());
38
+ return {
39
+ accessToken: json.access_token,
40
+ expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),
41
+ refreshToken: json.refresh_token,
42
+ scopes: json.scopes,
43
+ tokenType: json.token_type,
44
+ };
45
+ }
46
+ export async function exchangeRefreshToken({ clientId, clientSecret, refreshToken, apiURI: apiURIOpt, }) {
47
+ const apiURI = requireApiURI(apiURIOpt, {
48
+ target: 'exchangeRefreshToken()',
49
+ });
50
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
51
+ method: 'POST',
52
+ headers: { 'Content-Type': 'application/json' },
53
+ body: JSON.stringify({
54
+ grant_type: 'refresh_token',
55
+ refresh_token: refreshToken,
56
+ client_id: clientId,
57
+ client_secret: clientSecret,
58
+ }),
59
+ });
60
+ const json = (await res.json());
61
+ return {
62
+ accessToken: json.access_token,
63
+ expiresAt: new Date((json.expires_in - 30) * 1000),
64
+ scopes: json.scopes,
65
+ tokenType: json.token_type,
66
+ };
67
+ }
68
+ //# sourceMappingURL=serverOAuth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverOAuth.js","sourceRoot":"","sources":["../../src/serverOAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,EACzC,IAAI,EACJ,QAAQ,EACR,YAAY,EACZ,WA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AAI,CAAC,UAAU,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC;QAC/D,YAAY,EAAE,IAAI,CAAC,aAAa;QAChC,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,SAAS,EAAE,IAAI,CAAC,UAAU;KAC3B,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,EACzC,QAAQ,EACR,YAAY,EACZ,YAAY,EACZ,MAAM,EAAE,SAAS,GAMlB;IAMC,MAAM,MAAM,GAAG,aAAa,CAAC,SAAS,EAAE;QACtC,MAAM,EAAE,wBAAwB;KACjC,CAAC,CAAC;IACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,uBAAuB,EAAE;QACxD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;QAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;YACnB,UAAU,EAAE,eAAe;YAC3B,aAAa,EAAE,YAAY;YAC3B,SAAS,EAAE,QAAQ;YACnB,aAAa,EAAE,YAAY;SAC5B,CAAC;KACH,CAAC,CAAC;IAEH,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAK7B,CAAC;IAEF,OAAO;QACL,WAAW,EAAE,IAAI,CAAC,YAAY;QAC9B,SAAS,EAAE,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC;QAClD,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,SAAS,EAAE,IAAI,CAAC,UAAU;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { requireApiURI } from '@sidekickdb/core';\nimport { InstantOAuthError } from './oauthCommon.ts';\n\nexport async function exchangeCodeForToken({\n code,\n clientId,\n clientSecret,\n redirectUri,\n apiURI: apiURIOpt,\n}: {\n code: string;\n clientId: string;\n clientSecret: string;\n redirectUri: string;\n apiURI?: string;\n}): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n}> {\n const apiURI = requireApiURI(apiURIOpt, {\n target: 'exchangeCodeForToken()',\n });\n const res = await fetch(`${apiURI}/platform/oauth/token`, {\n method: 'POST',\n headers: { 'Content-type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n });\n\n if (!res.ok) {\n const text = await res.text();\n let error;\n\n try {\n const json = JSON.parse(text);\n error = {\n error: json.error,\n errorDescription: json.error_description,\n message: `OAuth error: ${json.error || 'server_error'}`,\n };\n } catch (e) {\n error = {\n error: 'server_error',\n message: 'OAuth error: server_error',\n };\n }\n\n throw new InstantOAuthError(error);\n }\n\n const json = (await res.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n };\n\n return {\n accessToken: json.access_token,\n expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),\n refreshToken: json.refresh_token,\n scopes: json.scopes,\n tokenType: json.token_type,\n };\n}\n\nexport async function exchangeRefreshToken({\n clientId,\n clientSecret,\n refreshToken,\n apiURI: apiURIOpt,\n}: {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n apiURI?: string;\n}): Promise<{\n accessToken: string;\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n}> {\n const apiURI = requireApiURI(apiURIOpt, {\n target: 'exchangeRefreshToken()',\n });\n const res = await fetch(`${apiURI}/platform/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n });\n\n const json = (await res.json()) as {\n access_token: string;\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n };\n\n return {\n accessToken: json.access_token,\n expiresAt: new Date((json.expires_in - 30) * 1000),\n scopes: json.scopes,\n tokenType: json.token_type,\n };\n}\n"]}
@@ -0,0 +1,17 @@
1
+ import type { Node } from '@babel/types';
2
+ import { GenericSchemaDef } from './util.ts';
3
+ type JsonValue = string | number | boolean | null | JsonValue[] | {
4
+ [key: string]: JsonValue;
5
+ };
6
+ /**
7
+ * Converts a Babel AST node into a JavaScript object/value,
8
+ * suitable for JSON serialization.
9
+ * Throws errors for unsupported AST structures.
10
+ * @param {Node | null} node - The Babel AST node to convert.
11
+ * @returns {JsonValue | null} The JavaScript representation.
12
+ * @throws {Error} If the AST node or its structure is not convertible to JSON.
13
+ */
14
+ export declare function astToJson(node: Node | null): JsonValue | null;
15
+ export declare function schemaTypescriptFileToInstantSchema(content: string, sourceFilename?: string): GenericSchemaDef;
16
+ export {};
17
+ //# sourceMappingURL=typescript-schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typescript-schema.d.ts","sourceRoot":"","sources":["../../src/typescript-schema.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAIV,IAAI,EAQL,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAG7C,KAAK,SAAS,GACV,MAAM,GACN,MAAM,GACN,OAAO,GACP,IAAI,GACJ,SAAS,EAAE,GACX;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEjC;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CAqF7D;AA8SD,wBAAgB,mCAAmC,CACjD,OAAO,EAAE,MAAM,EACf,cAAc,GAAE,MAA4B,GAC3C,gBAAgB,CAclB"}