@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,588 @@
1
+ import { id, } from '@sidekickdb/core';
2
+ import { attrDefToNewAttrTx, linkDefToNewAttrTx } from "./migrationUtils.js";
3
+ import { relationshipConstraints } from "./relationships.js";
4
+ const getExistingAttrThrowing = (ident, existingAttrs) => {
5
+ const found = existingAttrs.find((attr) => {
6
+ return (attr['forward-identity'][1] === ident.namespace &&
7
+ attr['forward-identity'][2] === ident.attrName);
8
+ }) || null;
9
+ if (!found) {
10
+ throw new Error(`Attribute ${ident.namespace}.${ident.attrName} not found`);
11
+ }
12
+ return found;
13
+ };
14
+ const convertSimpleConstraintUpdate = (tx, existing) => {
15
+ const found = getExistingAttrThrowing(tx.identifier, existing);
16
+ return {
17
+ 'attr-id': found.id,
18
+ 'forward-identity': found['forward-identity'],
19
+ };
20
+ };
21
+ // converts migration operations from Identifier (namespace/name) based
22
+ // into transaction steps that use database ids
23
+ const CONVERTERS = {
24
+ index: convertSimpleConstraintUpdate,
25
+ unique: convertSimpleConstraintUpdate,
26
+ required: convertSimpleConstraintUpdate,
27
+ 'remove-index': convertSimpleConstraintUpdate,
28
+ 'remove-unique': convertSimpleConstraintUpdate,
29
+ 'remove-required': convertSimpleConstraintUpdate,
30
+ 'delete-attr': (from, existing) => {
31
+ const found = getExistingAttrThrowing(from.identifier, existing);
32
+ return found.id;
33
+ },
34
+ 'update-attr': (from, existing) => {
35
+ const found = getExistingAttrThrowing(from.identifier, existing);
36
+ return {
37
+ id: found.id,
38
+ 'forward-identity': from.partialAttr['forward-identity']
39
+ ? [
40
+ found.id,
41
+ from.partialAttr['forward-identity'].namespace,
42
+ from.partialAttr['forward-identity'].attrName,
43
+ ]
44
+ : undefined,
45
+ 'reverse-identity': from.partialAttr['reverse-identity']
46
+ ? [
47
+ found.id,
48
+ from.partialAttr['reverse-identity'].namespace,
49
+ from.partialAttr['reverse-identity'].attrName,
50
+ ]
51
+ : undefined,
52
+ cardinality: from.partialAttr['cardinality']
53
+ ? from.partialAttr['cardinality']
54
+ : undefined,
55
+ 'on-delete': from.partialAttr['on-delete']
56
+ ? from.partialAttr['on-delete']
57
+ : undefined,
58
+ 'on-delete-reverse': from.partialAttr['on-delete-reverse']
59
+ ? from.partialAttr['on-delete-reverse']
60
+ : undefined,
61
+ };
62
+ },
63
+ 'add-attr': (from, _existing) => {
64
+ const attrId = id();
65
+ const forwardIdentity = [
66
+ attrId,
67
+ from.identifier.namespace,
68
+ from.identifier.attrName,
69
+ ];
70
+ const steps = [];
71
+ // First, create the attribute without unique, required, or indexed
72
+ steps.push([
73
+ 'add-attr',
74
+ {
75
+ 'forward-identity': forwardIdentity,
76
+ 'reverse-identity': from['reverse-identity']
77
+ ? [
78
+ id(),
79
+ from['reverse-identity'].namespace,
80
+ from['reverse-identity'].attrName,
81
+ ]
82
+ : null,
83
+ 'inferred-types': null,
84
+ 'value-type': from['value-type'],
85
+ id: attrId,
86
+ cardinality: from.cardinality,
87
+ 'index?': false,
88
+ 'required?': false,
89
+ 'unique?': false,
90
+ catalog: 'user',
91
+ 'on-delete': from['on-delete'],
92
+ 'on-delete-reverse': from['on-delete-reverse'],
93
+ 'checked-data-type': from['checked-data-type'],
94
+ },
95
+ ]);
96
+ // Then add separate steps for unique, required, and indexed
97
+ if (from['unique?']) {
98
+ steps.push([
99
+ 'unique',
100
+ {
101
+ 'attr-id': attrId,
102
+ 'forward-identity': forwardIdentity,
103
+ },
104
+ ]);
105
+ }
106
+ if (from['required?']) {
107
+ steps.push([
108
+ 'required',
109
+ {
110
+ 'attr-id': attrId,
111
+ 'forward-identity': forwardIdentity,
112
+ },
113
+ ]);
114
+ }
115
+ if (from['index?']) {
116
+ steps.push([
117
+ 'index',
118
+ {
119
+ 'attr-id': attrId,
120
+ 'forward-identity': forwardIdentity,
121
+ },
122
+ ]);
123
+ }
124
+ return steps;
125
+ },
126
+ 'remove-data-type': convertSimpleConstraintUpdate,
127
+ 'check-data-type': (from, existing) => {
128
+ const found = getExistingAttrThrowing(from.identifier, existing);
129
+ return {
130
+ 'attr-id': found.id,
131
+ 'checked-data-type': from['checked-data-type'],
132
+ 'forward-identity': found['forward-identity'],
133
+ };
134
+ },
135
+ };
136
+ function isSystemCatalogAttr(systemCatalogIdentNames, entityName, attrName) {
137
+ return !!systemCatalogIdentNames[entityName]?.has(attrName);
138
+ }
139
+ export const convertTxSteps = (txs, existingAttrs) => {
140
+ if (!existingAttrs) {
141
+ throw new Error('Existing attributes are required');
142
+ }
143
+ const result = [];
144
+ txs.forEach((tx) => {
145
+ const converter = CONVERTERS[tx.type];
146
+ if (!converter) {
147
+ throw new Error(`Unknown transaction type: ${tx.type}`);
148
+ }
149
+ const converted = converter(tx, existingAttrs);
150
+ if (Array.isArray(converted)) {
151
+ result.push(...converted);
152
+ }
153
+ else {
154
+ result.push([tx.type, converted]);
155
+ }
156
+ });
157
+ return result;
158
+ };
159
+ export const diffSchemas = async (oldSchema, newSchema, resolveFn, systemCatalogIdentNames) => {
160
+ const transactions = [];
161
+ const oldEntities = oldSchema.entities;
162
+ const newEntities = newSchema.entities;
163
+ const oldEntityNames = Object.keys(oldEntities);
164
+ const newEntityNames = Object.keys(newEntities);
165
+ const deletedEntityNames = oldEntityNames.filter((name) => !newEntityNames.includes(name));
166
+ for (const entityName of deletedEntityNames) {
167
+ Object.keys(oldEntities[entityName].attrs).forEach((attrName) => {
168
+ if (isSystemCatalogAttr(systemCatalogIdentNames, entityName, attrName))
169
+ return;
170
+ transactions.push({
171
+ type: 'delete-attr',
172
+ identifier: {
173
+ attrName,
174
+ namespace: entityName,
175
+ },
176
+ });
177
+ });
178
+ if (isSystemCatalogAttr(systemCatalogIdentNames, entityName, 'id')) {
179
+ continue;
180
+ }
181
+ transactions.push({
182
+ type: 'delete-attr',
183
+ identifier: {
184
+ attrName: 'id',
185
+ namespace: entityName,
186
+ },
187
+ });
188
+ }
189
+ const addedEntityNames = newEntityNames.filter((name) => !oldEntityNames.includes(name));
190
+ for (const entityName of addedEntityNames) {
191
+ if (!isSystemCatalogAttr(systemCatalogIdentNames, entityName, 'id')) {
192
+ transactions.push({
193
+ type: 'add-attr',
194
+ 'forward-identity': {
195
+ namespace: entityName,
196
+ attrName: 'id',
197
+ },
198
+ identifier: {
199
+ attrName: 'id',
200
+ namespace: entityName,
201
+ },
202
+ 'index?': false,
203
+ 'required?': true,
204
+ cardinality: 'one',
205
+ 'unique?': true,
206
+ 'value-type': 'blob',
207
+ });
208
+ }
209
+ for (const attrName of Object.keys(newEntities[entityName].attrs)) {
210
+ if (isSystemCatalogAttr(systemCatalogIdentNames, entityName, attrName)) {
211
+ continue;
212
+ }
213
+ const attrInSchema = newEntities[entityName].attrs[attrName];
214
+ transactions.push(attrDefToNewAttrTx(attrInSchema, entityName, attrName));
215
+ }
216
+ }
217
+ const innerEntityNames = oldEntityNames.filter((name) => newEntityNames.includes(name));
218
+ for (const entityName of innerEntityNames) {
219
+ // BLOB ATTRIBUTES
220
+ const addedFields = Object.keys(newEntities[entityName].attrs).filter((field) => {
221
+ if (isSystemCatalogAttr(systemCatalogIdentNames, entityName, field))
222
+ return false;
223
+ const oldEntityHasIt = Object.keys(oldEntities[entityName].attrs).includes(field);
224
+ return !oldEntityHasIt;
225
+ });
226
+ const removedFields = Object.keys(oldEntities[entityName].attrs).filter((field) => {
227
+ if (isSystemCatalogAttr(systemCatalogIdentNames, entityName, field))
228
+ return false;
229
+ const newEntityHasIt = Object.keys(newEntities[entityName].attrs).includes(field);
230
+ return !newEntityHasIt;
231
+ });
232
+ const resolved = await resolveRenames(addedFields, removedFields, resolveFn, {
233
+ type: 'attribute',
234
+ entityName: entityName,
235
+ });
236
+ const consistentFields = Object.keys(oldEntities[entityName].attrs).filter((field) => Object.keys(newEntities[entityName].attrs).includes(field));
237
+ consistentFields.forEach((fieldName) => {
238
+ if (isSystemCatalogAttr(systemCatalogIdentNames, entityName, fieldName)) {
239
+ return;
240
+ }
241
+ transactions.push(...compareBlobs({
242
+ attrName: fieldName,
243
+ namespace: entityName,
244
+ }, oldEntities[entityName].attrs[fieldName], newEntities[entityName].attrs[fieldName]));
245
+ });
246
+ resolved.deleted.forEach((attrName) => {
247
+ transactions.push({
248
+ type: 'delete-attr',
249
+ identifier: {
250
+ attrName,
251
+ namespace: entityName,
252
+ },
253
+ });
254
+ });
255
+ resolved.created.forEach((createdName) => {
256
+ const attrInSchema = newSchema.entities[entityName].attrs[createdName];
257
+ transactions.push(attrDefToNewAttrTx(attrInSchema, entityName, createdName));
258
+ });
259
+ resolved.renamed.forEach((renamed) => {
260
+ transactions.push({
261
+ type: 'update-attr',
262
+ identifier: {
263
+ attrName: renamed.from,
264
+ namespace: entityName,
265
+ },
266
+ partialAttr: {
267
+ 'value-type': 'blob',
268
+ cardinality: 'one',
269
+ 'forward-identity': {
270
+ attrName: renamed.to,
271
+ namespace: entityName,
272
+ },
273
+ },
274
+ });
275
+ transactions.push(...compareBlobs({
276
+ attrName: renamed.from,
277
+ namespace: entityName,
278
+ }, oldEntities[entityName].attrs[renamed.from], newEntities[entityName].attrs[renamed.to]));
279
+ });
280
+ }
281
+ const oldLinks = Object.values(oldSchema.links).filter((link) => !isSystemCatalogAttr(systemCatalogIdentNames, link.forward.on, link.forward.label));
282
+ const newLinks = Object.values(newSchema.links).filter((link) => !isSystemCatalogAttr(systemCatalogIdentNames, link.forward.on, link.forward.label));
283
+ // Group links by their forward namespace-label combination for comparison
284
+ const createLinkKey = (link) => `${link.forward.on}<->${link.reverse.on}`;
285
+ const createLinkIdentity = (link) => `${link.forward.on}.${link.forward.label}<->${link.reverse.on}.${link.reverse.label}`;
286
+ const newLinksByKey = new Map();
287
+ const oldLinksByKey = new Map();
288
+ for (const link of newLinks) {
289
+ const key = createLinkKey(link);
290
+ const links = newLinksByKey.get(key) || [];
291
+ links.push(link);
292
+ newLinksByKey.set(key, links);
293
+ }
294
+ for (const link of oldLinks) {
295
+ const key = createLinkKey(link);
296
+ const links = oldLinksByKey.get(key) || [];
297
+ links.push(link);
298
+ oldLinksByKey.set(key, links);
299
+ }
300
+ const allLinkKeys = new Set([
301
+ ...oldLinksByKey.keys(),
302
+ ...newLinksByKey.keys(),
303
+ ]);
304
+ for (const linkKey of allLinkKeys) {
305
+ const oldLinksInGroup = oldLinksByKey.get(linkKey) || [];
306
+ const newLinksInGroup = newLinksByKey.get(linkKey) || [];
307
+ const oldIdentities = oldLinksInGroup.map((link) => createLinkIdentity(link));
308
+ const newIdentities = newLinksInGroup.map((link) => createLinkIdentity(link));
309
+ const addedIdentities = newIdentities.filter((identity) => !oldIdentities.includes(identity));
310
+ const removedIdentities = oldIdentities.filter((identity) => !newIdentities.includes(identity));
311
+ const consistentIdentities = oldIdentities.filter((identity) => newIdentities.includes(identity));
312
+ consistentIdentities.forEach((identity) => {
313
+ const oldLink = oldLinksInGroup.find((l) => createLinkIdentity(l) === identity);
314
+ const newLink = newLinksInGroup.find((l) => createLinkIdentity(l) === identity);
315
+ if (!oldLink || !newLink)
316
+ return;
317
+ transactions.push(...compareLinks({
318
+ namespace: oldLink.forward.on,
319
+ attrName: oldLink.forward.label,
320
+ }, oldLink, newLink));
321
+ });
322
+ const resolved = await resolveRenames(addedIdentities, removedIdentities, resolveFn, {
323
+ type: 'link',
324
+ forwardEntityName: oldLinksInGroup[0]?.forward.on,
325
+ reverseEntityName: oldLinksInGroup[0]?.reverse.on,
326
+ });
327
+ resolved.deleted.forEach((identity) => {
328
+ const link = oldLinksInGroup.find((l) => createLinkIdentity(l) === identity);
329
+ if (!link)
330
+ return;
331
+ transactions.push({
332
+ type: 'delete-attr',
333
+ identifier: {
334
+ attrName: link.forward.label,
335
+ namespace: link.forward.on,
336
+ },
337
+ });
338
+ });
339
+ resolved.created.forEach((identity) => {
340
+ const link = newLinksInGroup.find((l) => createLinkIdentity(l) === identity);
341
+ if (!link)
342
+ return;
343
+ transactions.push(linkDefToNewAttrTx(link));
344
+ });
345
+ resolved.renamed.forEach((renamed) => {
346
+ const oldLink = oldLinksInGroup.find((l) => createLinkIdentity(l) === renamed.from);
347
+ const newLink = newLinksInGroup.find((l) => createLinkIdentity(l) === renamed.to);
348
+ if (!oldLink || !newLink)
349
+ return;
350
+ transactions.push({
351
+ type: 'update-attr',
352
+ identifier: {
353
+ attrName: oldLink.forward.label,
354
+ namespace: oldLink.forward.on,
355
+ },
356
+ partialAttr: {
357
+ 'value-type': 'ref',
358
+ cardinality: newLink.forward.has === 'one' ? 'one' : 'many',
359
+ 'forward-identity': {
360
+ attrName: newLink.forward.label,
361
+ namespace: newLink.forward.on,
362
+ },
363
+ 'reverse-identity': {
364
+ attrName: newLink.reverse.label,
365
+ namespace: newLink.reverse.on,
366
+ },
367
+ },
368
+ });
369
+ transactions.push(...compareLinks({
370
+ attrName: oldLink.forward.label,
371
+ namespace: oldLink.forward.on,
372
+ }, oldLink, newLink));
373
+ });
374
+ }
375
+ return transactions;
376
+ };
377
+ export const compareBlobs = (identity, oldBlob, newBlob) => {
378
+ const results = [];
379
+ const sendType = (type) => {
380
+ results.push({
381
+ type,
382
+ identifier: identity,
383
+ });
384
+ };
385
+ // check if index needs to be added
386
+ if (oldBlob.isIndexed === false && newBlob.isIndexed === true)
387
+ sendType('index');
388
+ // check if index needs to be removed
389
+ if (oldBlob.isIndexed === true && newBlob.isIndexed === false)
390
+ sendType('remove-index');
391
+ // check if needs to become unique
392
+ if (oldBlob.config.unique === false && newBlob.config.unique === true)
393
+ sendType('unique');
394
+ // check if needs to become non-unique
395
+ if (oldBlob.config.unique === true && newBlob.config.unique === false)
396
+ sendType('remove-unique');
397
+ // check if needs to become required
398
+ if (oldBlob.required === false && newBlob.required === true)
399
+ sendType('required');
400
+ // check if needs to become non-required
401
+ if (oldBlob.required === true && newBlob.required === false)
402
+ sendType('remove-required');
403
+ // check if data type needs to be changed / added
404
+ if (oldBlob.valueType !== 'json' && newBlob.valueType === 'json') {
405
+ results.push({
406
+ type: 'remove-data-type',
407
+ identifier: identity,
408
+ });
409
+ }
410
+ else if (oldBlob.valueType !== newBlob.valueType &&
411
+ newBlob.valueType !== 'json') {
412
+ results.push({
413
+ type: 'check-data-type',
414
+ identifier: identity,
415
+ 'checked-data-type': newBlob.valueType,
416
+ });
417
+ }
418
+ return results;
419
+ };
420
+ export const compareLinks = (identity, oldLink, newLink) => {
421
+ const results = [];
422
+ const oldRelationship = `${oldLink.forward.has}-${oldLink.reverse.has}`;
423
+ const { cardinality: oldCardinal, 'unique?': oldUnique } = relationshipConstraints[oldRelationship];
424
+ const oldRequired = !!oldLink.forward.required;
425
+ const newRelationship = `${newLink.forward.has}-${newLink.reverse.has}`;
426
+ const { cardinality: newCardinal, 'unique?': newUnique } = relationshipConstraints[newRelationship];
427
+ const newRequired = !!newLink.forward.required;
428
+ if (!oldUnique && newUnique) {
429
+ results.push({
430
+ type: 'unique',
431
+ identifier: identity,
432
+ });
433
+ }
434
+ if (!newUnique && newUnique !== oldUnique) {
435
+ results.push({
436
+ type: 'remove-unique',
437
+ identifier: identity,
438
+ });
439
+ }
440
+ if (newRequired !== oldRequired) {
441
+ results.push({
442
+ type: newRequired ? 'required' : 'remove-required',
443
+ identifier: identity,
444
+ });
445
+ }
446
+ if (oldLink.reverse.onDelete !== newLink.reverse.onDelete ||
447
+ oldLink.forward.onDelete !== newLink.forward.onDelete ||
448
+ oldCardinal !== newCardinal) {
449
+ results.push({
450
+ type: 'update-attr',
451
+ identifier: identity,
452
+ partialAttr: {
453
+ 'value-type': 'ref',
454
+ 'on-delete-reverse': newLink.reverse.onDelete,
455
+ 'on-delete': newLink.forward.onDelete,
456
+ cardinality: newCardinal,
457
+ },
458
+ });
459
+ }
460
+ return results;
461
+ };
462
+ export const isRenamePromptItem = (item) => {
463
+ if (typeof item === 'object')
464
+ return true;
465
+ return false;
466
+ };
467
+ const resolveRenames = async (newItems, missingItems, resolveFn, extraInfo) => {
468
+ if (missingItems.length === 0 || newItems.length === 0) {
469
+ return {
470
+ created: newItems,
471
+ deleted: missingItems,
472
+ renamed: [],
473
+ };
474
+ }
475
+ const result = { created: [], renamed: [], deleted: [] };
476
+ let index = 0;
477
+ let leftMissing = [...missingItems];
478
+ do {
479
+ const created = newItems[index];
480
+ const renames = leftMissing.map((it) => {
481
+ return { from: it, to: created };
482
+ });
483
+ const promptData = [created, ...renames];
484
+ const data = await resolveFn(created, promptData, extraInfo);
485
+ if (isRenamePromptItem(data)) {
486
+ if (data.from !== data.to) {
487
+ result.renamed.push(data);
488
+ }
489
+ delete leftMissing[leftMissing.indexOf(data.from)];
490
+ leftMissing = leftMissing.filter(Boolean);
491
+ }
492
+ else {
493
+ result.created.push(created);
494
+ }
495
+ index += 1;
496
+ } while (index < newItems.length);
497
+ result.deleted.push(...leftMissing);
498
+ return result;
499
+ };
500
+ function validateRenameLookup(lookup) {
501
+ const [etype, label] = lookup.split('.').map((x) => x.trim());
502
+ if (!etype || !label) {
503
+ throw new Error(`Invalid lookup. Got '${lookup}'. We expect a pattern like 'entityname.columname;.` +
504
+ 'For example: posts.title');
505
+ }
506
+ }
507
+ // RenameMap goes from `to` -> `from`
508
+ function parseRenameCommands(renames) {
509
+ // Parse rename options: format is "from:to"
510
+ // note that it saves backwards since we will be testing against the base
511
+ // case of a created attr
512
+ const renameMap = new Map();
513
+ for (const renameStr of renames) {
514
+ let [from, to] = renameStr.split(':').map((x) => x.trim());
515
+ if (!from || !to) {
516
+ throw new Error(`Invalid rename command: ${renameStr}. We could not parse a distinct 'from' and 'to'.` +
517
+ " The structure should look like 'from:to'. For example: 'posts.name:posts.title'");
518
+ }
519
+ validateRenameLookup(from);
520
+ validateRenameLookup(to);
521
+ renameMap.set(to.trim(), from.trim());
522
+ }
523
+ return renameMap;
524
+ }
525
+ /**
526
+ * Given a list of RenameCommands, builds a cusotm `resolveFn` for
527
+ * `diffSchemas`, which automatically resolves rename conflicts with these commands.
528
+ */
529
+ export function buildAutoRenameSelector(renames) {
530
+ const renameMap = parseRenameCommands(renames);
531
+ const renameFn = async function (created, promptData, extraInfo) {
532
+ let lookupNames = [];
533
+ if (extraInfo?.type === 'attribute' && extraInfo?.entityName) {
534
+ lookupNames = [`${extraInfo.entityName}.${created}`];
535
+ }
536
+ else if (extraInfo?.type === 'link') {
537
+ // Extract both forward and reverse parts
538
+ const parts = created.split('<->');
539
+ lookupNames = [parts[0], parts[1]];
540
+ }
541
+ else {
542
+ return created;
543
+ }
544
+ // Try to find a match in the rename map using the lookup names
545
+ let fromAttr = null;
546
+ for (const lookupName of lookupNames) {
547
+ if (renameMap.has(lookupName)) {
548
+ fromAttr = renameMap.get(lookupName) || null;
549
+ break;
550
+ }
551
+ }
552
+ if (fromAttr) {
553
+ let fromValue;
554
+ if (extraInfo?.type === 'attribute') {
555
+ fromValue = fromAttr.split('.').pop();
556
+ }
557
+ else {
558
+ const matchingItem = promptData.find((item) => {
559
+ const itemStr = typeof item === 'string' ? item : item.from;
560
+ const itemParts = itemStr.split('<->');
561
+ return itemParts[0] === fromAttr || itemParts[1] === fromAttr;
562
+ });
563
+ if (matchingItem) {
564
+ fromValue =
565
+ typeof matchingItem === 'string' ? matchingItem : matchingItem.from;
566
+ }
567
+ else {
568
+ return created;
569
+ }
570
+ }
571
+ const hasMatch = promptData.some((item) => {
572
+ if (typeof item === 'string') {
573
+ return item === fromValue;
574
+ }
575
+ else if (item.from) {
576
+ return item.from === fromValue;
577
+ }
578
+ return false;
579
+ });
580
+ if (fromValue && hasMatch) {
581
+ return { from: fromValue, to: created };
582
+ }
583
+ }
584
+ return created;
585
+ };
586
+ return renameFn;
587
+ }
588
+ //# sourceMappingURL=migrations.js.map