@casual-simulation/aux-records 3.8.1 → 3.10.2

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 (239) hide show
  1. package/AIChatInterface.d.ts +7 -43
  2. package/AIChatInterface.js +8 -6
  3. package/AIChatInterface.js.map +1 -1
  4. package/AIController.js +44 -49
  5. package/AIController.js.map +1 -1
  6. package/AIOpenAIRealtimeInterface.d.ts +1 -1
  7. package/AnthropicAIChatInterface.js +4 -4
  8. package/AnthropicAIChatInterface.js.map +1 -1
  9. package/AuthController.d.ts +78 -10
  10. package/AuthController.js +230 -166
  11. package/AuthController.js.map +1 -1
  12. package/AuthStore.d.ts +317 -4
  13. package/BigIntPatch.d.ts +1 -0
  14. package/BigIntPatch.js +24 -0
  15. package/BigIntPatch.js.map +1 -0
  16. package/BlockadeLabsGenerateSkyboxInterface.js +4 -4
  17. package/BlockadeLabsGenerateSkyboxInterface.js.map +1 -1
  18. package/CachingConfigStore.d.ts +8 -1
  19. package/CachingConfigStore.js +50 -0
  20. package/CachingConfigStore.js.map +1 -1
  21. package/ComIdConfig.d.ts +132 -86
  22. package/ComIdConfig.js +5 -5
  23. package/ComIdConfig.js.map +1 -1
  24. package/ConfigurationStore.d.ts +1393 -3
  25. package/ConfigurationStore.js +49 -0
  26. package/ConfigurationStore.js.map +1 -1
  27. package/DataRecordsController.js +28 -28
  28. package/DataRecordsController.js.map +1 -1
  29. package/EventRecordsController.js +9 -9
  30. package/EventRecordsController.js.map +1 -1
  31. package/FileRecordsController.js +18 -17
  32. package/FileRecordsController.js.map +1 -1
  33. package/GoogleAIChatInterface.js +4 -4
  34. package/GoogleAIChatInterface.js.map +1 -1
  35. package/HttpTestUtils.d.ts +48 -0
  36. package/HttpTestUtils.js +256 -0
  37. package/HttpTestUtils.js.map +1 -0
  38. package/LivekitController.js +2 -2
  39. package/LivekitController.js.map +1 -1
  40. package/LoomController.js +3 -4
  41. package/LoomController.js.map +1 -1
  42. package/MemoryStore.d.ts +60 -7
  43. package/MemoryStore.js +427 -59
  44. package/MemoryStore.js.map +1 -1
  45. package/MetricsStore.d.ts +11 -0
  46. package/ModerationConfiguration.d.ts +11 -85
  47. package/ModerationConfiguration.js +17 -17
  48. package/ModerationConfiguration.js.map +1 -1
  49. package/ModerationController.js +9 -11
  50. package/ModerationController.js.map +1 -1
  51. package/OpenAIChatInterface.js +8 -13
  52. package/OpenAIChatInterface.js.map +1 -1
  53. package/OpenAIImageInterface.js +4 -5
  54. package/OpenAIImageInterface.js.map +1 -1
  55. package/PolicyController.js +66 -73
  56. package/PolicyController.js.map +1 -1
  57. package/PolicyStore.d.ts +59 -33
  58. package/PolicyStore.js +35 -1
  59. package/PolicyStore.js.map +1 -1
  60. package/PrivoClient.d.ts +3 -1
  61. package/PrivoClient.js +2 -4
  62. package/PrivoClient.js.map +1 -1
  63. package/PrivoConfiguration.d.ts +6 -72
  64. package/PrivoConfiguration.js +30 -31
  65. package/PrivoConfiguration.js.map +1 -1
  66. package/README.md +276 -2
  67. package/RateLimitController.js +2 -2
  68. package/RateLimitController.js.map +1 -1
  69. package/RecordsClient.d.ts +3 -1
  70. package/RecordsClient.js +6 -6
  71. package/RecordsClient.js.map +1 -1
  72. package/RecordsController.d.ts +145 -3
  73. package/RecordsController.js +399 -61
  74. package/RecordsController.js.map +1 -1
  75. package/RecordsServer.d.ts +1932 -1109
  76. package/RecordsStore.d.ts +99 -14
  77. package/RecordsStore.js +8 -10
  78. package/RecordsStore.js.map +1 -1
  79. package/ServerConfig.d.ts +698 -9867
  80. package/ServerConfig.js +457 -377
  81. package/ServerConfig.js.map +1 -1
  82. package/SloydInterface.js +1 -1
  83. package/SloydInterface.js.map +1 -1
  84. package/StabilityAIImageInterface.js +6 -9
  85. package/StabilityAIImageInterface.js.map +1 -1
  86. package/StripeInterface.d.ts +431 -287
  87. package/StripeInterface.js +21 -1
  88. package/StripeInterface.js.map +1 -1
  89. package/SubscriptionConfigBuilder.d.ts +10 -1
  90. package/SubscriptionConfigBuilder.js +72 -41
  91. package/SubscriptionConfigBuilder.js.map +1 -1
  92. package/SubscriptionConfiguration.d.ts +606 -6334
  93. package/SubscriptionConfiguration.js +460 -277
  94. package/SubscriptionConfiguration.js.map +1 -1
  95. package/SubscriptionController.d.ts +677 -4
  96. package/SubscriptionController.js +2986 -186
  97. package/SubscriptionController.js.map +1 -1
  98. package/SystemNotificationMessenger.d.ts +14 -70
  99. package/SystemNotificationMessenger.js +17 -20
  100. package/SystemNotificationMessenger.js.map +1 -1
  101. package/TestUtils.d.ts +18 -3
  102. package/TestUtils.js +84 -8
  103. package/TestUtils.js.map +1 -1
  104. package/TypeUtils.d.ts +991 -0
  105. package/TypeUtils.js +2 -0
  106. package/TypeUtils.js.map +1 -0
  107. package/Utils.d.ts +59 -0
  108. package/Utils.js +507 -3
  109. package/Utils.js.map +1 -1
  110. package/Validations.d.ts +24 -108
  111. package/Validations.js +62 -45
  112. package/Validations.js.map +1 -1
  113. package/ViewTemplateRenderer.d.ts +39 -0
  114. package/ViewTemplateRenderer.js +19 -0
  115. package/ViewTemplateRenderer.js.map +1 -0
  116. package/contracts/ContractRecordsController.d.ts +58 -0
  117. package/contracts/ContractRecordsController.js +144 -0
  118. package/contracts/ContractRecordsController.js.map +1 -0
  119. package/contracts/ContractRecordsStore.d.ts +285 -0
  120. package/contracts/ContractRecordsStore.js +19 -0
  121. package/contracts/ContractRecordsStore.js.map +1 -0
  122. package/contracts/MemoryContractRecordsStore.d.ts +27 -0
  123. package/contracts/MemoryContractRecordsStore.js +124 -0
  124. package/contracts/MemoryContractRecordsStore.js.map +1 -0
  125. package/contracts/index.d.ts +4 -0
  126. package/contracts/index.js +21 -0
  127. package/contracts/index.js.map +1 -0
  128. package/crud/CrudHelpers.d.ts +25 -26
  129. package/crud/CrudHelpers.js +1 -1
  130. package/crud/CrudHelpers.js.map +1 -1
  131. package/crud/CrudRecordsController.js +13 -16
  132. package/crud/CrudRecordsController.js.map +1 -1
  133. package/crud/CrudRecordsControllerTests.d.ts +2 -2
  134. package/crud/CrudRecordsControllerTests.js +605 -580
  135. package/crud/CrudRecordsControllerTests.js.map +1 -1
  136. package/crud/MemoryCrudRecordsStore.js +1 -2
  137. package/crud/MemoryCrudRecordsStore.js.map +1 -1
  138. package/crud/sub/MemorySubCrudRecordsStore.js +4 -6
  139. package/crud/sub/MemorySubCrudRecordsStore.js.map +1 -1
  140. package/crud/sub/SubCrudRecordsController.js +8 -8
  141. package/crud/sub/SubCrudRecordsController.js.map +1 -1
  142. package/database/DatabaseRecordsController.js +1 -2
  143. package/database/DatabaseRecordsController.js.map +1 -1
  144. package/database/SqliteDatabaseInterface.js +1 -2
  145. package/database/SqliteDatabaseInterface.js.map +1 -1
  146. package/dns/DNSDomainNameValidator.d.ts +11 -0
  147. package/dns/DNSDomainNameValidator.js +59 -0
  148. package/dns/DNSDomainNameValidator.js.map +1 -0
  149. package/dns/DomainNameValidator.d.ts +36 -0
  150. package/dns/DomainNameValidator.js +19 -0
  151. package/dns/DomainNameValidator.js.map +1 -0
  152. package/dns/index.d.ts +3 -0
  153. package/dns/index.js +20 -0
  154. package/dns/index.js.map +1 -0
  155. package/financial/FinancialController.d.ts +272 -0
  156. package/financial/FinancialController.js +762 -0
  157. package/financial/FinancialController.js.map +1 -0
  158. package/financial/FinancialInterface.d.ts +352 -0
  159. package/financial/FinancialInterface.js +642 -0
  160. package/financial/FinancialInterface.js.map +1 -0
  161. package/financial/FinancialStore.d.ts +186 -0
  162. package/financial/FinancialStore.js +19 -0
  163. package/financial/FinancialStore.js.map +1 -0
  164. package/financial/MemoryFinancialInterface.d.ts +23 -0
  165. package/financial/MemoryFinancialInterface.js +592 -0
  166. package/financial/MemoryFinancialInterface.js.map +1 -0
  167. package/financial/TigerBeetleFinancialInterface.d.ts +46 -0
  168. package/financial/TigerBeetleFinancialInterface.js +109 -0
  169. package/financial/TigerBeetleFinancialInterface.js.map +1 -0
  170. package/financial/TigerBeetleTestUtils.d.ts +40 -0
  171. package/financial/TigerBeetleTestUtils.js +185 -0
  172. package/financial/TigerBeetleTestUtils.js.map +1 -0
  173. package/financial/Types.d.ts +1 -0
  174. package/financial/Types.js +801 -0
  175. package/financial/Types.js.map +1 -0
  176. package/financial/index.d.ts +6 -0
  177. package/financial/index.js +24 -0
  178. package/financial/index.js.map +1 -0
  179. package/index.d.ts +4 -0
  180. package/index.js +3 -0
  181. package/index.js.map +1 -1
  182. package/notifications/NotificationRecordsController.js +14 -14
  183. package/notifications/NotificationRecordsController.js.map +1 -1
  184. package/notifications/WebPushInterface.d.ts +24 -155
  185. package/notifications/WebPushInterface.js +2 -2
  186. package/notifications/WebPushInterface.js.map +1 -1
  187. package/package.json +72 -70
  188. package/packages/version/MemoryPackageVersionRecordsStore.js +12 -15
  189. package/packages/version/MemoryPackageVersionRecordsStore.js.map +1 -1
  190. package/packages/version/PackageVersionRecordsController.d.ts +19 -0
  191. package/packages/version/PackageVersionRecordsController.js +102 -22
  192. package/packages/version/PackageVersionRecordsController.js.map +1 -1
  193. package/packages/version/PackageVersionRecordsStore.js +6 -8
  194. package/packages/version/PackageVersionRecordsStore.js.map +1 -1
  195. package/purchasable-items/MemoryPurchasableItemRecordsStore.d.ts +7 -0
  196. package/purchasable-items/MemoryPurchasableItemRecordsStore.js +33 -0
  197. package/purchasable-items/MemoryPurchasableItemRecordsStore.js.map +1 -0
  198. package/purchasable-items/PurchasableItemRecordsController.d.ts +16 -0
  199. package/purchasable-items/PurchasableItemRecordsController.js +72 -0
  200. package/purchasable-items/PurchasableItemRecordsController.js.map +1 -0
  201. package/purchasable-items/PurchasableItemRecordsStore.d.ts +66 -0
  202. package/purchasable-items/PurchasableItemRecordsStore.js +2 -0
  203. package/purchasable-items/PurchasableItemRecordsStore.js.map +1 -0
  204. package/purchasable-items/index.d.ts +4 -0
  205. package/purchasable-items/index.js +21 -0
  206. package/purchasable-items/index.js.map +1 -0
  207. package/queue/MemoryQueue.js +1 -1
  208. package/queue/MemoryQueue.js.map +1 -1
  209. package/search/MemorySearchInterface.js +1 -2
  210. package/search/MemorySearchInterface.js.map +1 -1
  211. package/search/SearchRecordsController.d.ts +66 -244
  212. package/search/SearchRecordsController.js +35 -36
  213. package/search/SearchRecordsController.js.map +1 -1
  214. package/search/SearchSyncProcessor.d.ts +7 -83
  215. package/search/TypesenseSearchInterface.js +8 -11
  216. package/search/TypesenseSearchInterface.js.map +1 -1
  217. package/tracing/TracingDecorators.js +5 -8
  218. package/tracing/TracingDecorators.js.map +1 -1
  219. package/webhooks/WebhookEnvironment.d.ts +36 -560
  220. package/webhooks/WebhookEnvironment.js +1 -1
  221. package/webhooks/WebhookEnvironment.js.map +1 -1
  222. package/webhooks/WebhookRecordsController.js +14 -16
  223. package/webhooks/WebhookRecordsController.js.map +1 -1
  224. package/websockets/MemoryLockStore.d.ts +18 -0
  225. package/websockets/MemoryLockStore.js +2 -0
  226. package/websockets/MemoryLockStore.js.map +1 -0
  227. package/websockets/MemoryTempInstRecordsStore.js +15 -27
  228. package/websockets/MemoryTempInstRecordsStore.js.map +1 -1
  229. package/websockets/MemoryWebsocketConnectionStore.js +6 -8
  230. package/websockets/MemoryWebsocketConnectionStore.js.map +1 -1
  231. package/websockets/MemoryWebsocketMessenger.js +1 -2
  232. package/websockets/MemoryWebsocketMessenger.js.map +1 -1
  233. package/websockets/SplitInstRecordsStore.js +2 -2
  234. package/websockets/SplitInstRecordsStore.js.map +1 -1
  235. package/websockets/WebsocketController.d.ts +5 -0
  236. package/websockets/WebsocketController.js +122 -83
  237. package/websockets/WebsocketController.js.map +1 -1
  238. package/RecordsServer.js +0 -6435
  239. package/RecordsServer.js.map +0 -1
@@ -5,13 +5,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
7
  import { action, createInitializationUpdate, hasValue, ON_WEBHOOK_ACTION_NAME, } from '@casual-simulation/aux-common/bots';
8
- import { constructInitializationUpdate, YjsPartitionImpl, } from '@casual-simulation/aux-common/partitions';
8
+ import { constructInitializationUpdate, updateToNewStateUpdate, YjsPartitionImpl, } from '@casual-simulation/aux-common/partitions';
9
9
  import { device, deviceError, deviceResult, } from '@casual-simulation/aux-common/common/RemoteActions';
10
10
  import { fromByteArray, toByteArray } from 'base64-js';
11
11
  import { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs';
12
12
  import { WebsocketEventTypes } from '@casual-simulation/aux-common/websockets/WebsocketEvents';
13
13
  import { sumBy } from 'es-toolkit/compat';
14
- import { PRIVATE_MARKER, DEFAULT_BRANCH_NAME, tryParseJson, parseRecordKey, PUBLIC_READ_MARKER, } from '@casual-simulation/aux-common';
14
+ import { PRIVATE_MARKER, DEFAULT_BRANCH_NAME, tryParseJson, parseRecordKey, PUBLIC_READ_MARKER, failure, isFailure, genericResult, success, compareVersions, } from '@casual-simulation/aux-common';
15
15
  import { getMarkerResourcesForCreation } from '../PolicyController';
16
16
  import { SplitInstRecordsStore } from './SplitInstRecordsStore';
17
17
  import { v4 as uuid, v7 as uuidv7 } from 'uuid';
@@ -127,7 +127,6 @@ export class WebsocketController {
127
127
  }
128
128
  }
129
129
  async disconnect(connectionId) {
130
- var _a;
131
130
  const loadedConnections = await this._connectionStore.getConnections(connectionId);
132
131
  await this._connectionStore.clearConnection(connectionId);
133
132
  for (let connection of loadedConnections) {
@@ -135,8 +134,9 @@ export class WebsocketController {
135
134
  if (connection.temporary) {
136
135
  const count = await this._connectionStore.countConnectionsByBranch(connection.mode, connection.recordName, connection.inst, connection.branch);
137
136
  if (count <= 0) {
138
- const branch = (_a = (await this._instStore.getBranchByName(connection.recordName, connection.inst, connection.branch))) !== null && _a !== void 0 ? _a : (await this._temporaryStore.getBranchByName(connection.recordName, connection.inst, connection.branch));
139
- if (branch === null || branch === void 0 ? void 0 : branch.temporary) {
137
+ const branch = (await this._instStore.getBranchByName(connection.recordName, connection.inst, connection.branch)) ??
138
+ (await this._temporaryStore.getBranchByName(connection.recordName, connection.inst, connection.branch));
139
+ if (branch?.temporary) {
140
140
  console.log('[WebsocketController] Deleting temporary branch', connection.recordName, connection.inst, connection.branch);
141
141
  await this._temporaryStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
142
142
  await this._instStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
@@ -156,7 +156,6 @@ export class WebsocketController {
156
156
  }
157
157
  }
158
158
  async watchBranch(connectionId, event) {
159
- var _a, _b, _c, _d;
160
159
  if (!event) {
161
160
  console.warn('[CasualRepoServer] Trying to watch branch with a null event!');
162
161
  return;
@@ -201,7 +200,7 @@ export class WebsocketController {
201
200
  }
202
201
  const config = await this._config.getSubscriptionConfiguration();
203
202
  if (!recordName) {
204
- if (((_b = (_a = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _a === void 0 ? void 0 : _a.publicInsts) === null || _b === void 0 ? void 0 : _b.allowed) === false) {
203
+ if (config?.defaultFeatures?.publicInsts?.allowed === false) {
205
204
  await this.messenger.sendMessage([connectionId], {
206
205
  type: 'repo/watch_branch_result',
207
206
  success: false,
@@ -233,7 +232,8 @@ export class WebsocketController {
233
232
  maxConnections = features.insts.maxActiveConnectionsPerInst;
234
233
  }
235
234
  else if (!recordName &&
236
- typeof ((_d = (_c = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _c === void 0 ? void 0 : _c.publicInsts) === null || _d === void 0 ? void 0 : _d.maxActiveConnectionsPerInst) === 'number') {
235
+ typeof config?.defaultFeatures?.publicInsts
236
+ ?.maxActiveConnectionsPerInst === 'number') {
237
237
  maxConnections =
238
238
  config.defaultFeatures.publicInsts.maxActiveConnectionsPerInst;
239
239
  }
@@ -309,7 +309,6 @@ export class WebsocketController {
309
309
  await Promise.all(promises);
310
310
  }
311
311
  async unwatchBranch(connectionId, recordName, inst, branch) {
312
- var _a;
313
312
  if (!branch) {
314
313
  console.warn('[CasualRepoServer] Trying to unwatch branch with a null event!');
315
314
  return;
@@ -321,8 +320,9 @@ export class WebsocketController {
321
320
  if (connection.temporary) {
322
321
  const count = await this._connectionStore.countConnectionsByBranch('branch', recordName, inst, branch);
323
322
  if (count <= 0) {
324
- const branch = (_a = (await this._instStore.getBranchByName(connection.recordName, connection.inst, connection.branch))) !== null && _a !== void 0 ? _a : (await this._temporaryStore.getBranchByName(connection.recordName, connection.inst, connection.branch));
325
- if (branch === null || branch === void 0 ? void 0 : branch.temporary) {
323
+ const branch = (await this._instStore.getBranchByName(connection.recordName, connection.inst, connection.branch)) ??
324
+ (await this._temporaryStore.getBranchByName(connection.recordName, connection.inst, connection.branch));
325
+ if (branch?.temporary) {
326
326
  await this._temporaryStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
327
327
  // Delete the branch from the permentent store even if it is temporary
328
328
  // because it is possible that the branch was created before temporary branches were only stored in the temporary store.
@@ -342,7 +342,6 @@ export class WebsocketController {
342
342
  }
343
343
  }
344
344
  async addUpdates(connectionId, event) {
345
- var _a, _b, _c, _d, _e;
346
345
  if (!event) {
347
346
  console.warn('[CasualRepoServer] Trying to add atoms with a null event!');
348
347
  return;
@@ -380,12 +379,13 @@ export class WebsocketController {
380
379
  }
381
380
  }
382
381
  if (event.updates) {
383
- let branch = (_a = (await this._instStore.getBranchByName(event.recordName, event.inst, event.branch))) !== null && _a !== void 0 ? _a : (await this._temporaryStore.getBranchByName(event.recordName, event.inst, event.branch));
382
+ let branch = (await this._instStore.getBranchByName(event.recordName, event.inst, event.branch)) ??
383
+ (await this._temporaryStore.getBranchByName(event.recordName, event.inst, event.branch));
384
384
  const updateSize = sumBy(event.updates, (u) => Buffer.byteLength(u, 'utf8'));
385
385
  const config = await this._config.getSubscriptionConfiguration();
386
386
  let features = null;
387
387
  if (!event.recordName) {
388
- if (((_c = (_b = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _b === void 0 ? void 0 : _b.publicInsts) === null || _c === void 0 ? void 0 : _c.allowed) === false) {
388
+ if (config?.defaultFeatures?.publicInsts?.allowed === false) {
389
389
  await this.sendError(connectionId, -1, {
390
390
  success: false,
391
391
  errorCode: 'not_authorized',
@@ -545,7 +545,7 @@ export class WebsocketController {
545
545
  maxInstSize = features.insts.maxBytesPerInst;
546
546
  }
547
547
  else if (!event.recordName &&
548
- typeof ((_e = (_d = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _d === void 0 ? void 0 : _d.publicInsts) === null || _e === void 0 ? void 0 : _e.maxBytesPerInst) ===
548
+ typeof config?.defaultFeatures?.publicInsts?.maxBytesPerInst ===
549
549
  'number') {
550
550
  maxInstSize =
551
551
  config.defaultFeatures.publicInsts.maxBytesPerInst;
@@ -630,15 +630,15 @@ export class WebsocketController {
630
630
  }
631
631
  }
632
632
  async addUserUpdates(request) {
633
- var _a, _b, _c, _d, _e;
634
- console.log(`[CausalRepoServer] [namespace: ${request.recordName}/${request.inst}/${request.branch}, userId: ${request.userId}] Add Updates`);
633
+ console.log(`[WebsocketController] [namespace: ${request.recordName}/${request.inst}/${request.branch}, userId: ${request.userId}] Add Updates`);
635
634
  if (request.updates) {
636
- let branch = (_a = (await this._instStore.getBranchByName(request.recordName, request.inst, request.branch))) !== null && _a !== void 0 ? _a : (await this._temporaryStore.getBranchByName(request.recordName, request.inst, request.branch));
635
+ let branch = (await this._instStore.getBranchByName(request.recordName, request.inst, request.branch)) ??
636
+ (await this._temporaryStore.getBranchByName(request.recordName, request.inst, request.branch));
637
637
  const updateSize = sumBy(request.updates, (u) => Buffer.byteLength(u, 'utf8'));
638
638
  const config = await this._config.getSubscriptionConfiguration();
639
639
  let features = null;
640
640
  if (!request.recordName) {
641
- if (((_c = (_b = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _b === void 0 ? void 0 : _b.publicInsts) === null || _c === void 0 ? void 0 : _c.allowed) === false) {
641
+ if (config?.defaultFeatures?.publicInsts?.allowed === false) {
642
642
  return {
643
643
  success: false,
644
644
  errorCode: 'not_authorized',
@@ -647,7 +647,7 @@ export class WebsocketController {
647
647
  }
648
648
  }
649
649
  if (!branch) {
650
- console.log(`[CausalRepoServer] [namespace: ${request.recordName}/${request.inst}/${request.branch}, userId: ${request.userId}] Branch not found!`);
650
+ console.log(`[WebsocketController] [namespace: ${request.recordName}/${request.inst}/${request.branch}, userId: ${request.userId}] Branch not found!`);
651
651
  const instResult = await this._getOrCreateInst(request.recordName, request.inst, request.userId, config, null, undefined);
652
652
  if (instResult.success === false) {
653
653
  return instResult;
@@ -716,7 +716,7 @@ export class WebsocketController {
716
716
  maxInstSize = features.insts.maxBytesPerInst;
717
717
  }
718
718
  else if (!request.recordName &&
719
- typeof ((_e = (_d = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _d === void 0 ? void 0 : _d.publicInsts) === null || _e === void 0 ? void 0 : _e.maxBytesPerInst) ===
719
+ typeof config?.defaultFeatures?.publicInsts?.maxBytesPerInst ===
720
720
  'number') {
721
721
  maxInstSize =
722
722
  config.defaultFeatures.publicInsts.maxBytesPerInst;
@@ -742,7 +742,7 @@ export class WebsocketController {
742
742
  else {
743
743
  const result = await this._instStore.addUpdates(request.recordName, request.inst, request.branch, request.updates, updateSize);
744
744
  if (result.success === false) {
745
- console.log(`[CausalRepoServer] [namespace: ${request.recordName}/${request.inst}/${request.branch}, userId: ${request.userId}] Failed to add updates`, result);
745
+ console.log(`[WebsocketController] [namespace: ${request.recordName}/${request.inst}/${request.branch}, userId: ${request.userId}] Failed to add updates`, result);
746
746
  if (result.errorCode === 'max_size_reached') {
747
747
  if (result.success === false) {
748
748
  return {
@@ -947,7 +947,7 @@ export class WebsocketController {
947
947
  ? await this._connectionStore.countConnectionsByBranch('branch', recordName, inst, branch)
948
948
  : await this._connectionStore.countConnections();
949
949
  const currentConnection = await this._connectionStore.getConnection(connectionId);
950
- if (recordName && (currentConnection === null || currentConnection === void 0 ? void 0 : currentConnection.token)) {
950
+ if (recordName && currentConnection?.token) {
951
951
  const authorized = await this._connectionStore.isAuthorizedInst(connectionId, recordName, inst, 'token');
952
952
  if (!authorized) {
953
953
  await this.sendError(connectionId, -1, {
@@ -966,7 +966,7 @@ export class WebsocketController {
966
966
  }
967
967
  if (recordName) {
968
968
  const config = await this._config.getSubscriptionConfiguration();
969
- const instResult = await this._getInst(recordName, inst, currentConnection === null || currentConnection === void 0 ? void 0 : currentConnection.userId, config);
969
+ const instResult = await this._getInst(recordName, inst, currentConnection?.userId, config);
970
970
  if (instResult.success === false) {
971
971
  await this.sendError(connectionId, -1, instResult);
972
972
  return;
@@ -997,7 +997,6 @@ export class WebsocketController {
997
997
  * @param auxVersion The AUX version to return.
998
998
  */
999
999
  async getBranchData(userId, recordName, inst, branch, auxVersion = 1) {
1000
- var _a;
1001
1000
  console.log(`[WebsocketController] [namespace: ${recordName}/${inst}/${branch}] Get Data`);
1002
1001
  if (recordName) {
1003
1002
  const config = await this._config.getSubscriptionConfiguration();
@@ -1013,7 +1012,7 @@ export class WebsocketController {
1013
1012
  };
1014
1013
  }
1015
1014
  }
1016
- const updates = (_a = (await this._instStore.getCurrentUpdates(recordName, inst, branch))) !== null && _a !== void 0 ? _a : {
1015
+ const updates = (await this._instStore.getCurrentUpdates(recordName, inst, branch)) ?? {
1017
1016
  updates: [],
1018
1017
  timestamps: [],
1019
1018
  instSizeInBytes: 0,
@@ -1111,7 +1110,6 @@ export class WebsocketController {
1111
1110
  }
1112
1111
  }
1113
1112
  async getUpdates(connectionId, recordName, inst, branch) {
1114
- var _a;
1115
1113
  if (!branch) {
1116
1114
  console.warn('[CasualRepoServer] Trying to get branch with a null branch!');
1117
1115
  return;
@@ -1171,7 +1169,7 @@ export class WebsocketController {
1171
1169
  });
1172
1170
  return;
1173
1171
  }
1174
- const updates = (_a = (await this._instStore.getAllUpdates(recordName, inst, branch))) !== null && _a !== void 0 ? _a : {
1172
+ const updates = (await this._instStore.getAllUpdates(recordName, inst, branch)) ?? {
1175
1173
  updates: [],
1176
1174
  timestamps: [],
1177
1175
  };
@@ -1411,7 +1409,6 @@ export class WebsocketController {
1411
1409
  * @param request The request to load the package.
1412
1410
  */
1413
1411
  async installPackage(request) {
1414
- var _a, _b;
1415
1412
  if (!this._packageVersions) {
1416
1413
  return {
1417
1414
  success: false,
@@ -1420,8 +1417,8 @@ export class WebsocketController {
1420
1417
  };
1421
1418
  }
1422
1419
  const userId = request.userId;
1423
- const key = (_a = request.package.key) !== null && _a !== void 0 ? _a : {};
1424
- console.log(`[CausalRepoServer] [namespace: ${request.recordName}/${request.inst}, ${userId}, package: ${request.package.recordName}/${request.package.address}@${formatVersionSpecifier(key)}] Install Package`);
1420
+ const key = request.package.key ?? {};
1421
+ console.log(`[WebsocketController] [namespace: ${request.recordName}/${request.inst}, ${userId}, package: ${request.package.recordName}/${request.package.address}@${formatVersionSpecifier(key)}] Install Package`);
1425
1422
  const p = await this._packageVersions.getItem({
1426
1423
  recordName: request.package.recordName,
1427
1424
  address: request.package.address,
@@ -1430,23 +1427,26 @@ export class WebsocketController {
1430
1427
  instances: request.instances,
1431
1428
  });
1432
1429
  if (p.success === false) {
1433
- console.error(`[CausalRepoServer] [userId: ${userId}] Unable to load package.`, p);
1430
+ console.error(`[WebsocketController] [userId: ${userId}] Unable to load package.`, p);
1434
1431
  return p;
1435
1432
  }
1436
1433
  if (p.auxFile.success === false) {
1437
- console.error(`[CausalRepoServer] [userId: ${userId}] Unable to load package file.`, p.auxFile);
1434
+ console.error(`[WebsocketController] [userId: ${userId}] Unable to load package file.`, p.auxFile);
1438
1435
  return p.auxFile;
1439
1436
  }
1440
1437
  const loadedPackageStore = this._instStore;
1441
1438
  const loadedPackage = await loadedPackageStore.isPackageLoaded(request.recordName, request.inst, p.item.packageId);
1442
1439
  if (loadedPackage) {
1443
- // Already loaded
1444
- console.log(`[CausalRepoServer] [userId: ${userId}] Package already loaded.`);
1445
- return {
1446
- success: true,
1447
- packageLoadId: loadedPackage.id,
1448
- package: p.item,
1449
- };
1440
+ if (loadedPackage.packageVersionId === p.item.id) {
1441
+ // Already loaded
1442
+ console.log(`[WebsocketController] [userId: ${userId}] Package already loaded.`);
1443
+ return {
1444
+ success: true,
1445
+ packageLoadId: loadedPackage.id,
1446
+ package: p.item,
1447
+ };
1448
+ }
1449
+ // try to install a different version
1450
1450
  }
1451
1451
  // check that the user and target inst has the ability to run the package
1452
1452
  const context = await this._policies.constructAuthorizationContext({
@@ -1467,61 +1467,65 @@ export class WebsocketController {
1467
1467
  if (authorization.success === false) {
1468
1468
  return authorization;
1469
1469
  }
1470
- const fileResponse = await fetch(p.auxFile.requestUrl, {
1471
- method: p.auxFile.requestMethod,
1472
- headers: new Headers(p.auxFile.requestHeaders),
1473
- });
1474
- if (fileResponse.status >= 300) {
1475
- console.error(`[CausalRepoServer] [userId: ${userId}] Unable to load package file.`);
1476
- // Failed
1477
- return {
1478
- success: false,
1479
- errorCode: 'invalid_file_data',
1480
- errorMessage: 'The package file could not be loaded.',
1481
- };
1470
+ const packageData = await this._loadPackageVersion(userId, p);
1471
+ if (isFailure(packageData)) {
1472
+ return genericResult(packageData);
1482
1473
  }
1483
- const json = await fileResponse.text();
1484
- const packageData = tryParseJson(json);
1485
- if (packageData.success === false) {
1486
- console.error(`[CausalRepoServer] [userId: ${userId}] Unable to parse package file.`, packageData);
1487
- return {
1488
- success: false,
1489
- errorCode: 'invalid_file_data',
1490
- errorMessage: 'The package file could not be parsed. It must be valid JSON.',
1491
- };
1492
- }
1493
- const parsed = STORED_AUX_SCHEMA.safeParse(packageData.value);
1494
- if (parsed.success === false) {
1495
- console.error(`[CausalRepoServer] [userId: ${userId}] Unable to parse package file.`, packageData);
1496
- return {
1497
- success: false,
1498
- errorCode: 'invalid_file_data',
1499
- errorMessage: 'The package file could not be parsed.',
1500
- issues: parsed.error.issues,
1501
- };
1502
- }
1503
- const updates = parsed.data.version === 2
1504
- ? parsed.data.updates.map((u) => u.update)
1474
+ let updates = packageData.value.version === 2
1475
+ ? packageData.value.updates
1505
1476
  : [
1506
- constructInitializationUpdate(createInitializationUpdate(Object.values(parsed.data.state))).update,
1477
+ constructInitializationUpdate(createInitializationUpdate(Object.values(packageData.value.state))),
1507
1478
  ];
1508
- const timestamps = parsed.data.version === 2
1509
- ? parsed.data.updates.map((u) => u.timestamp)
1510
- : [0];
1511
- const branch = (_b = request.branch) !== null && _b !== void 0 ? _b : DEFAULT_BRANCH_NAME;
1479
+ const branch = request.branch ?? DEFAULT_BRANCH_NAME;
1480
+ if (loadedPackage) {
1481
+ // Different version
1482
+ const existingPackageVersion = await this._packageVersions.getItemById({
1483
+ packageVersionId: loadedPackage.packageVersionId,
1484
+ userId: userId,
1485
+ instances: request.instances,
1486
+ });
1487
+ if (existingPackageVersion.success === false) {
1488
+ console.error(`[WebsocketController] [userId: ${userId}] Unable to get existing package version.`, existingPackageVersion);
1489
+ return existingPackageVersion;
1490
+ }
1491
+ else {
1492
+ if (compareVersions(p.item.key, existingPackageVersion.item.key) <= 0) {
1493
+ if (!request.downgrade) {
1494
+ return {
1495
+ success: false,
1496
+ errorCode: 'invalid_request',
1497
+ errorMessage: `Cannot install version ${formatVersionSpecifier(p.item.key)} because a newer version (${formatVersionSpecifier(existingPackageVersion.item.key)}) of this package is already installed. If you want to downgrade the package, you must set the downgrade option to true.`,
1498
+ };
1499
+ }
1500
+ else {
1501
+ console.log(`[WebsocketController] [userId: ${userId}] Downgrading package from version ${loadedPackage.packageVersionId} to ${p.item.id}.`);
1502
+ }
1503
+ }
1504
+ const existingUpdates = await this._instStore.getCurrentUpdates(request.recordName, request.inst, branch);
1505
+ updates = [
1506
+ updateToNewStateUpdate(existingUpdates.updates.map((u, i) => ({
1507
+ id: i,
1508
+ update: u,
1509
+ timestamp: 0,
1510
+ })), updates),
1511
+ ];
1512
+ }
1513
+ }
1514
+ const updateBase64 = updates.map((u) => u.update);
1515
+ const timestamps = updates.map((u) => u.timestamp);
1512
1516
  const result = await this.addUserUpdates({
1513
1517
  userId: request.userId,
1514
1518
  userRole: request.userRole,
1515
1519
  recordName: request.recordName,
1516
1520
  inst: request.inst,
1517
1521
  branch,
1518
- updates: updates,
1522
+ updates: updateBase64,
1519
1523
  timestamps: timestamps,
1520
1524
  });
1521
1525
  if (result.success === false) {
1522
1526
  return result;
1523
1527
  }
1524
- const loadedPackageId = uuidv7();
1528
+ const loadedPackageId = loadedPackage?.id ?? uuidv7();
1525
1529
  await loadedPackageStore.saveLoadedPackage({
1526
1530
  id: loadedPackageId,
1527
1531
  recordName: request.recordName,
@@ -1537,6 +1541,42 @@ export class WebsocketController {
1537
1541
  package: p.item,
1538
1542
  };
1539
1543
  }
1544
+ async _loadPackageVersion(userId, p) {
1545
+ if (p.auxFile.success === false) {
1546
+ return failure(p.auxFile);
1547
+ }
1548
+ const fileResponse = await fetch(p.auxFile.requestUrl, {
1549
+ method: p.auxFile.requestMethod,
1550
+ headers: new Headers(p.auxFile.requestHeaders),
1551
+ });
1552
+ if (fileResponse.status >= 300) {
1553
+ console.error(`[WebsocketController] [userId: ${userId}] Unable to load package file.`);
1554
+ // Failed
1555
+ return failure({
1556
+ errorCode: 'invalid_file_data',
1557
+ errorMessage: 'The package file could not be loaded.',
1558
+ });
1559
+ }
1560
+ const json = await fileResponse.text();
1561
+ const packageData = tryParseJson(json);
1562
+ if (packageData.success === false) {
1563
+ console.error(`[WebsocketController] [userId: ${userId}] Unable to parse package file.`, packageData);
1564
+ return failure({
1565
+ errorCode: 'invalid_file_data',
1566
+ errorMessage: 'The package file could not be parsed. It must be valid JSON.',
1567
+ });
1568
+ }
1569
+ const parsed = STORED_AUX_SCHEMA.safeParse(packageData.value);
1570
+ if (parsed.success === false) {
1571
+ console.error(`[WebsocketController] [userId: ${userId}] Unable to parse package file.`, packageData);
1572
+ return failure({
1573
+ errorCode: 'invalid_file_data',
1574
+ errorMessage: 'The package file could not be parsed.',
1575
+ issues: parsed.error.issues,
1576
+ });
1577
+ }
1578
+ return success(parsed.data);
1579
+ }
1540
1580
  async listInstalledPackages(request) {
1541
1581
  if (!this._packageVersions) {
1542
1582
  return {
@@ -1606,8 +1646,7 @@ export class WebsocketController {
1606
1646
  * @param timeMs The current time in unix time in miliseconds.
1607
1647
  */
1608
1648
  async rateLimitExceeded(connectionId, retryAfter, totalHits, timeMs) {
1609
- var _a;
1610
- const lastHit = (_a = (await this._connectionStore.getConnectionRateLimitExceededTime(connectionId))) !== null && _a !== void 0 ? _a : -Infinity;
1649
+ const lastHit = (await this._connectionStore.getConnectionRateLimitExceededTime(connectionId)) ?? -Infinity;
1611
1650
  const difference = timeMs - lastHit;
1612
1651
  await this._connectionStore.setConnectionRateLimitExceededTime(connectionId, timeMs);
1613
1652
  if (difference >= 1000) {