@terreno/api 57.3.0 → 57.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +6 -0
  3. package/dist/adminTypes.d.ts +7 -0
  4. package/dist/adminTypes.js +6 -1
  5. package/dist/api.d.ts +10 -0
  6. package/dist/api.js +99 -36
  7. package/dist/audit/auditApp.d.ts +30 -0
  8. package/dist/audit/auditApp.js +155 -0
  9. package/dist/audit/auditEventModel.d.ts +29 -0
  10. package/dist/audit/auditEventModel.js +102 -0
  11. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  12. package/dist/audit/cloudTasksEnqueue.js +162 -0
  13. package/dist/audit/diff.d.ts +10 -0
  14. package/dist/audit/diff.js +230 -0
  15. package/dist/audit/processQueue.d.ts +6 -0
  16. package/dist/audit/processQueue.js +101 -0
  17. package/dist/audit/rbacSink.d.ts +2 -0
  18. package/dist/audit/rbacSink.js +82 -0
  19. package/dist/audit/record.d.ts +56 -0
  20. package/dist/audit/record.js +373 -0
  21. package/dist/betterAuth.d.ts +6 -0
  22. package/dist/betterAuthSetup.js +1 -1
  23. package/dist/collectionRegistry.d.ts +3 -1
  24. package/dist/collectionRegistry.js +25 -0
  25. package/dist/index.d.ts +26 -1
  26. package/dist/index.js +48 -2
  27. package/dist/mcp/query.d.ts +0 -13
  28. package/dist/mcp/query.js +8 -8
  29. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  30. package/dist/migrations/fixtures/all-down/20260910120000-one.js +49 -0
  31. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  32. package/dist/migrations/fixtures/all-down/20260910120001-two.js +49 -0
  33. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  34. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +45 -0
  35. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  36. package/dist/migrations/fixtures/bad-name/not-a-migration.js +45 -0
  37. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  38. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  39. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  40. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +45 -0
  41. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  42. package/dist/migrations/fixtures/valid/20260910120001-beta.js +49 -0
  43. package/dist/migrations/generate.d.ts +17 -0
  44. package/dist/migrations/generate.js +277 -0
  45. package/dist/migrations/load.d.ts +20 -0
  46. package/dist/migrations/load.js +236 -0
  47. package/dist/migrations/lock.d.ts +13 -0
  48. package/dist/migrations/lock.js +145 -0
  49. package/dist/migrations/runner.d.ts +42 -0
  50. package/dist/migrations/runner.js +503 -0
  51. package/dist/migrations/schemaCatalog.d.ts +44 -0
  52. package/dist/migrations/schemaCatalog.js +326 -0
  53. package/dist/migrations/types.d.ts +87 -0
  54. package/dist/migrations/types.js +7 -0
  55. package/dist/models/notification.d.ts +2 -0
  56. package/dist/models/notification.js +62 -0
  57. package/dist/models/notificationPreference.d.ts +2 -0
  58. package/dist/models/notificationPreference.js +49 -0
  59. package/dist/notifications/notificationService.d.ts +40 -0
  60. package/dist/notifications/notificationService.js +323 -0
  61. package/dist/notifications/notificationsApp.d.ts +18 -0
  62. package/dist/notifications/notificationsApp.js +250 -0
  63. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  64. package/dist/notifications/notificationsBeforeSend.js +77 -0
  65. package/dist/openApi.d.ts +1 -7
  66. package/dist/openApi.js +7 -6
  67. package/dist/openApiBuilder.d.ts +14 -3
  68. package/dist/openApiValidator.d.ts +13 -1
  69. package/dist/openApiValidator.js +200 -36
  70. package/dist/orgs/orgContext.d.ts +23 -0
  71. package/dist/orgs/orgContext.js +198 -0
  72. package/dist/orgs/orgPermissions.d.ts +4 -0
  73. package/dist/orgs/orgPermissions.js +77 -0
  74. package/dist/orgs/orgPlugin.d.ts +13 -0
  75. package/dist/orgs/orgPlugin.js +84 -0
  76. package/dist/orgs/organizationModel.d.ts +13 -0
  77. package/dist/orgs/organizationModel.js +301 -0
  78. package/dist/orgs/organizationSettings.d.ts +19 -0
  79. package/dist/orgs/organizationSettings.js +120 -0
  80. package/dist/orgs/orgsApp.d.ts +28 -0
  81. package/dist/orgs/orgsApp.js +678 -0
  82. package/dist/permissions.d.ts +7 -13
  83. package/dist/permissions.js +8 -31
  84. package/dist/rateLimit/middleware.d.ts +0 -8
  85. package/dist/rateLimit/middleware.js +2 -3
  86. package/dist/rateLimit/mongoStore.d.ts +1 -0
  87. package/dist/rateLimit/mongoStore.js +1 -0
  88. package/dist/rateLimit/policies.d.ts +0 -4
  89. package/dist/rateLimit/policies.js +5 -7
  90. package/dist/rateLimit/redisStore.d.ts +1 -0
  91. package/dist/rateLimit/redisStore.js +1 -0
  92. package/dist/rbac/access.js +30 -13
  93. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  94. package/dist/rbac/membershipOrgAdminSource.js +122 -0
  95. package/dist/rbac/modelRouterAccess.d.ts +3 -0
  96. package/dist/rbac/modelRouterAccess.js +3 -0
  97. package/dist/rbac/resolve.js +60 -31
  98. package/dist/rbac/roleModel.d.ts +2 -5
  99. package/dist/rbac/roleModel.js +18 -4
  100. package/dist/rbac/statements.d.ts +10 -1
  101. package/dist/rbac/statements.js +19 -2
  102. package/dist/rbac/types.d.ts +5 -0
  103. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  104. package/dist/realtime/changeStreamWatcher.js +110 -64
  105. package/dist/realtime/deprecation.d.ts +1 -0
  106. package/dist/realtime/deprecation.js +1 -0
  107. package/dist/realtime/realtimeApp.d.ts +1 -0
  108. package/dist/realtime/realtimeApp.js +1 -0
  109. package/dist/schemaMetadata.js +16 -5
  110. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  111. package/dist/sync/adminBroadcastScope.js +194 -0
  112. package/dist/sync/adminWindowAccess.d.ts +13 -0
  113. package/dist/sync/adminWindowAccess.js +96 -0
  114. package/dist/sync/adminWindowMutation.d.ts +88 -0
  115. package/dist/sync/adminWindowMutation.js +247 -0
  116. package/dist/sync/executors.d.ts +9 -3
  117. package/dist/sync/executors.js +190 -159
  118. package/dist/sync/mutationHandler.d.ts +5 -2
  119. package/dist/sync/mutationHandler.js +191 -71
  120. package/dist/sync/registry.js +4 -0
  121. package/dist/sync/routes.d.ts +13 -0
  122. package/dist/sync/routes.js +113 -56
  123. package/dist/sync/socketHandlers.d.ts +8 -2
  124. package/dist/sync/socketHandlers.js +144 -50
  125. package/dist/sync/streams.d.ts +2 -0
  126. package/dist/sync/streams.js +7 -1
  127. package/dist/sync/syncApp.d.ts +2 -1
  128. package/dist/sync/syncApp.js +2 -1
  129. package/dist/sync/syncBatch.d.ts +5 -2
  130. package/dist/sync/syncBatch.js +4 -4
  131. package/dist/sync/types.d.ts +18 -0
  132. package/dist/terrenoApp.d.ts +29 -0
  133. package/dist/terrenoApp.js +91 -54
  134. package/dist/tests/createTestData.d.ts +1 -3
  135. package/dist/tests/createTestData.js +3 -5
  136. package/dist/tests/models.d.ts +1 -0
  137. package/dist/tests/models.js +9 -2
  138. package/dist/tests/testHelper.d.ts +0 -5
  139. package/dist/tests/testHelper.js +2 -9
  140. package/dist/types/authToken.d.ts +3 -3
  141. package/dist/types/mcpServiceToken.d.ts +2 -2
  142. package/dist/types/membership.d.ts +23 -0
  143. package/dist/types/membership.js +2 -0
  144. package/dist/types/notification.d.ts +28 -0
  145. package/dist/types/notification.js +2 -0
  146. package/dist/types/notificationPreference.d.ts +20 -0
  147. package/dist/types/notificationPreference.js +2 -0
  148. package/dist/types/organization.d.ts +36 -0
  149. package/dist/types/organization.js +2 -0
  150. package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
  151. package/dist/webhooks/idempotency/webhookReceipt.js +7 -7
  152. package/dist/webhooks/rawBody.d.ts +1 -0
  153. package/dist/webhooks/rawBody.js +1 -0
  154. package/package.json +31 -25
  155. package/src/__snapshots__/openApi.test.ts.snap +192 -54
  156. package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
  157. package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
  158. package/src/adminTypes.ts +8 -0
  159. package/src/api.test.ts +39 -2
  160. package/src/api.ts +68 -0
  161. package/src/audit/auditApp.test.ts +243 -0
  162. package/src/audit/auditApp.ts +139 -0
  163. package/src/audit/auditEventModel.ts +156 -0
  164. package/src/audit/auditRouter.test.ts +456 -0
  165. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  166. package/src/audit/cloudTasksEnqueue.ts +104 -0
  167. package/src/audit/diff.ts +163 -0
  168. package/src/audit/processQueue.ts +69 -0
  169. package/src/audit/rbacSink.test.ts +86 -0
  170. package/src/audit/rbacSink.ts +42 -0
  171. package/src/audit/record.test.ts +402 -0
  172. package/src/audit/record.ts +328 -0
  173. package/src/auth.test.ts +1 -1
  174. package/src/betterAuth.ts +7 -0
  175. package/src/betterAuthSetup.test.ts +27 -0
  176. package/src/betterAuthSetup.ts +1 -0
  177. package/src/collectionRegistry.test.ts +8 -9
  178. package/src/collectionRegistry.ts +21 -1
  179. package/src/express.d.ts +2 -0
  180. package/src/expressServer.test.ts +50 -2
  181. package/src/index.ts +69 -0
  182. package/src/mcp/handlers.test.ts +275 -0
  183. package/src/mcp/query.ts +3 -3
  184. package/src/mcp/toolGenerator.test.ts +81 -0
  185. package/src/migrations/cli.test.ts +376 -0
  186. package/src/migrations/cli.ts +283 -0
  187. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  188. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  189. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  190. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  191. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  192. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  193. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  194. package/src/migrations/generate.test.ts +333 -0
  195. package/src/migrations/generate.ts +216 -0
  196. package/src/migrations/load.test.ts +103 -0
  197. package/src/migrations/load.ts +124 -0
  198. package/src/migrations/lock.test.ts +133 -0
  199. package/src/migrations/lock.ts +118 -0
  200. package/src/migrations/runner.test.ts +504 -0
  201. package/src/migrations/runner.ts +358 -0
  202. package/src/migrations/schemaCatalog.test.ts +159 -0
  203. package/src/migrations/schemaCatalog.ts +262 -0
  204. package/src/migrations/types.ts +94 -0
  205. package/src/models/notification.ts +68 -0
  206. package/src/models/notificationPreference.ts +62 -0
  207. package/src/notifications/notificationService.ts +254 -0
  208. package/src/notifications/notificationsApp.test.ts +505 -0
  209. package/src/notifications/notificationsApp.ts +200 -0
  210. package/src/notifications/notificationsBeforeSend.ts +51 -0
  211. package/src/openApi.test.ts +0 -1
  212. package/src/openApi.ts +2 -1
  213. package/src/openApiBuilder.ts +14 -3
  214. package/src/openApiValidator.test.ts +221 -2
  215. package/src/openApiValidator.ts +218 -33
  216. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  217. package/src/orgs/orgContext.test.ts +259 -0
  218. package/src/orgs/orgContext.ts +151 -0
  219. package/src/orgs/orgPermissions.test.ts +105 -0
  220. package/src/orgs/orgPermissions.ts +40 -0
  221. package/src/orgs/orgPlugin.test.ts +130 -0
  222. package/src/orgs/orgPlugin.ts +70 -0
  223. package/src/orgs/orgRbac.test.ts +267 -0
  224. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  225. package/src/orgs/organizationModel.test.ts +205 -0
  226. package/src/orgs/organizationModel.ts +257 -0
  227. package/src/orgs/organizationSettings.test.ts +113 -0
  228. package/src/orgs/organizationSettings.ts +126 -0
  229. package/src/orgs/orgsApp.test.ts +382 -0
  230. package/src/orgs/orgsApp.ts +563 -0
  231. package/src/permissions.test.ts +62 -36
  232. package/src/permissions.ts +8 -30
  233. package/src/rateLimit/middleware.ts +1 -1
  234. package/src/rateLimit/mongoStore.ts +1 -0
  235. package/src/rateLimit/policies.ts +2 -2
  236. package/src/rateLimit/redisStore.ts +1 -0
  237. package/src/rbac/access.ts +11 -3
  238. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  239. package/src/rbac/modelRouterAccess.ts +3 -0
  240. package/src/rbac/permissionUtils.test.ts +26 -5
  241. package/src/rbac/resolve.test.ts +34 -2
  242. package/src/rbac/resolve.ts +26 -7
  243. package/src/rbac/roleModel.test.ts +34 -1
  244. package/src/rbac/roleModel.ts +17 -1
  245. package/src/rbac/statements.test.ts +19 -0
  246. package/src/rbac/statements.ts +19 -1
  247. package/src/rbac/types.ts +5 -0
  248. package/src/realtime/changeStreamWatcher.ts +73 -33
  249. package/src/realtime/deprecation.ts +1 -0
  250. package/src/realtime/realtime.test.ts +357 -185
  251. package/src/realtime/realtimeApp.ts +1 -0
  252. package/src/schemaMetadata.test.ts +14 -0
  253. package/src/schemaMetadata.ts +5 -5
  254. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  255. package/src/sync/adminBroadcastScope.test.ts +155 -0
  256. package/src/sync/adminBroadcastScope.ts +123 -0
  257. package/src/sync/adminWindowAccess.test.ts +57 -0
  258. package/src/sync/adminWindowAccess.ts +32 -0
  259. package/src/sync/adminWindowMutation.test.ts +450 -0
  260. package/src/sync/adminWindowMutation.ts +283 -0
  261. package/src/sync/executors.ts +33 -6
  262. package/src/sync/mutationHandler.test.ts +277 -1
  263. package/src/sync/mutationHandler.ts +171 -29
  264. package/src/sync/registry.ts +4 -0
  265. package/src/sync/routes.ts +52 -8
  266. package/src/sync/socketHandlers.ts +154 -58
  267. package/src/sync/streams.ts +6 -0
  268. package/src/sync/sync.test.ts +3 -2
  269. package/src/sync/syncApp.ts +2 -1
  270. package/src/sync/syncBatch.ts +7 -2
  271. package/src/sync/syncRoutes.test.ts +297 -3
  272. package/src/sync/syncSocket.test.ts +229 -0
  273. package/src/sync/types.ts +20 -0
  274. package/src/terrenoApp.migrations.test.ts +114 -0
  275. package/src/terrenoApp.test.ts +41 -0
  276. package/src/terrenoApp.ts +94 -31
  277. package/src/tests/createTestData.ts +2 -2
  278. package/src/tests/models.ts +10 -2
  279. package/src/tests/testHelper.ts +1 -7
  280. package/src/types/authToken.ts +2 -4
  281. package/src/types/mcpServiceToken.ts +1 -7
  282. package/src/types/membership.ts +48 -0
  283. package/src/types/notification.ts +34 -0
  284. package/src/types/notificationPreference.ts +28 -0
  285. package/src/types/organization.ts +49 -0
  286. package/src/webhooks/idempotency/webhookReceipt.ts +4 -7
  287. package/src/webhooks/rawBody.test.ts +33 -0
  288. package/src/webhooks/rawBody.ts +1 -0
  289. package/tsconfig.json +1 -1
  290. package/tsconfig.typedoc.json +2 -1
  291. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  292. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  293. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __read = (this && this.__read) || function (o, n) {
39
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
40
+ if (!m) return o;
41
+ var i = m.call(o), r, ar = [], e;
42
+ try {
43
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
44
+ }
45
+ catch (error) { e = { error: error }; }
46
+ finally {
47
+ try {
48
+ if (r && !r.done && (m = i["return"])) m.call(i);
49
+ }
50
+ finally { if (e) throw e.error; }
51
+ }
52
+ return ar;
53
+ };
54
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
55
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
56
+ if (ar || !(i in from)) {
57
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
58
+ ar[i] = from[i];
59
+ }
60
+ }
61
+ return to.concat(ar || Array.prototype.slice.call(from));
62
+ };
63
+ var __values = (this && this.__values) || function(o) {
64
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
65
+ if (m) return m.call(o);
66
+ if (o && typeof o.length === "number") return {
67
+ next: function () {
68
+ if (o && i >= o.length) o = void 0;
69
+ return { value: o && o[i++], done: !o };
70
+ }
71
+ };
72
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.generateMigration = exports.lastSchemaAfter = void 0;
76
+ /**
77
+ * Write a timestamped migration file from the current Mongoose models vs the last
78
+ * committed `schemaAfter` snapshot in `migrations/`.
79
+ */
80
+ var promises_1 = require("node:fs/promises");
81
+ var node_path_1 = require("node:path");
82
+ var luxon_1 = require("luxon");
83
+ var errors_1 = require("../errors");
84
+ var load_1 = require("./load");
85
+ var schemaCatalog_1 = require("./schemaCatalog");
86
+ var emptyCatalog = function () {
87
+ return { models: {} };
88
+ };
89
+ var slugify = function (name) {
90
+ var slug = name
91
+ .toLowerCase()
92
+ .replace(/[^a-z0-9]+/g, "-")
93
+ .replace(/^-+|-+$/g, "");
94
+ return slug.length > 0 ? slug : "auto";
95
+ };
96
+ var lastSchemaAfter = function (catalogs) {
97
+ var _a;
98
+ for (var index = catalogs.length - 1; index >= 0; index -= 1) {
99
+ var snapshot = (_a = catalogs[index]) === null || _a === void 0 ? void 0 : _a.schemaAfter;
100
+ if (snapshot && typeof snapshot === "object") {
101
+ return snapshot;
102
+ }
103
+ }
104
+ return undefined;
105
+ };
106
+ exports.lastSchemaAfter = lastSchemaAfter;
107
+ var describeOp = function (op) {
108
+ var _a, _b;
109
+ return "".concat(op.kind, " ").concat(op.modelName, " ").concat((_b = (_a = op.path) !== null && _a !== void 0 ? _a : op.toPath) !== null && _b !== void 0 ? _b : JSON.stringify(op.keys));
110
+ };
111
+ var mongoIndexName = function (keys) {
112
+ return Object.entries(keys)
113
+ .map(function (_a) {
114
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
115
+ return "".concat(key, "_").concat(value);
116
+ })
117
+ .join("_");
118
+ };
119
+ var renderIndexCall = function (_a) {
120
+ var collection = _a.collection, keys = _a.keys, kind = _a.kind;
121
+ var name = mongoIndexName(keys);
122
+ if (kind === "dropIndex") {
123
+ return " await ctx.mongoose.connection.collection(".concat(JSON.stringify(collection), ").dropIndex(").concat(JSON.stringify(name), ");");
124
+ }
125
+ return " await ctx.mongoose.connection.collection(".concat(JSON.stringify(collection), ").createIndex(").concat(JSON.stringify(keys), ", {name: ").concat(JSON.stringify(name), "});");
126
+ };
127
+ var renderUnsafeBody = function (_a) {
128
+ var e_1, _b;
129
+ var _c, _d;
130
+ var catalog = _a.catalog, ops = _a.ops, reverse = _a.reverse;
131
+ var detail = ops.map(describeOp).join("; ");
132
+ var ordered = reverse ? __spreadArray([], __read(ops), false).reverse() : ops;
133
+ var safeIndexComments = [];
134
+ try {
135
+ for (var ordered_1 = __values(ordered), ordered_1_1 = ordered_1.next(); !ordered_1_1.done; ordered_1_1 = ordered_1.next()) {
136
+ var op = ordered_1_1.value;
137
+ if (!op.safe || !op.keys || (op.kind !== "addIndex" && op.kind !== "dropIndex")) {
138
+ continue;
139
+ }
140
+ var collection = (_d = (_c = catalog.models[op.modelName]) === null || _c === void 0 ? void 0 : _c.collection) !== null && _d !== void 0 ? _d : op.modelName;
141
+ var kind = void 0;
142
+ if (op.kind === "addIndex") {
143
+ kind = reverse ? "dropIndex" : "createIndex";
144
+ }
145
+ else {
146
+ kind = reverse ? "createIndex" : "dropIndex";
147
+ }
148
+ safeIndexComments.push(" // ".concat(renderIndexCall({ collection: collection, keys: op.keys, kind: kind }).trim()));
149
+ }
150
+ }
151
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
152
+ finally {
153
+ try {
154
+ if (ordered_1_1 && !ordered_1_1.done && (_b = ordered_1.return)) _b.call(ordered_1);
155
+ }
156
+ finally { if (e_1) throw e_1.error; }
157
+ }
158
+ var commentBlock = safeIndexComments.length > 0
159
+ ? " // Keep these safe index operations when replacing the stub:\n".concat(safeIndexComments.join("\n"), "\n")
160
+ : "";
161
+ return "".concat(commentBlock, " throw new Error(").concat(JSON.stringify("Unsafe migration stub: ".concat(detail, ". Replace this stub with a backfill before applying.")), ");");
162
+ };
163
+ var renderSafeUp = function (ops, catalog) {
164
+ var e_2, _a;
165
+ var _b, _c;
166
+ var lines = [" if (ctx.dryRun) {", " return;", " }"];
167
+ try {
168
+ for (var ops_1 = __values(ops), ops_1_1 = ops_1.next(); !ops_1_1.done; ops_1_1 = ops_1.next()) {
169
+ var op = ops_1_1.value;
170
+ var collection = (_c = (_b = catalog.models[op.modelName]) === null || _b === void 0 ? void 0 : _b.collection) !== null && _c !== void 0 ? _c : op.modelName;
171
+ if (op.kind === "addIndex" && op.keys) {
172
+ lines.push(renderIndexCall({ collection: collection, keys: op.keys, kind: "createIndex" }));
173
+ continue;
174
+ }
175
+ if (op.kind === "dropIndex" && op.keys) {
176
+ lines.push(renderIndexCall({ collection: collection, keys: op.keys, kind: "dropIndex" }));
177
+ continue;
178
+ }
179
+ if (op.kind === "addOptionalField") {
180
+ lines.push(" // Optional field ".concat(op.modelName, ".").concat(op.path, " is schemaless in Mongo; snapshot only."));
181
+ }
182
+ }
183
+ }
184
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
185
+ finally {
186
+ try {
187
+ if (ops_1_1 && !ops_1_1.done && (_a = ops_1.return)) _a.call(ops_1);
188
+ }
189
+ finally { if (e_2) throw e_2.error; }
190
+ }
191
+ return lines.join("\n");
192
+ };
193
+ var renderSafeDown = function (ops, catalog) {
194
+ var e_3, _a;
195
+ var _b, _c;
196
+ var lines = [" if (ctx.dryRun) {", " return;", " }"];
197
+ try {
198
+ for (var _d = __values(__spreadArray([], __read(ops), false).reverse()), _e = _d.next(); !_e.done; _e = _d.next()) {
199
+ var op = _e.value;
200
+ var collection = (_c = (_b = catalog.models[op.modelName]) === null || _b === void 0 ? void 0 : _b.collection) !== null && _c !== void 0 ? _c : op.modelName;
201
+ if (op.kind === "addIndex" && op.keys) {
202
+ lines.push(renderIndexCall({ collection: collection, keys: op.keys, kind: "dropIndex" }));
203
+ continue;
204
+ }
205
+ if (op.kind === "dropIndex" && op.keys) {
206
+ lines.push(renderIndexCall({ collection: collection, keys: op.keys, kind: "createIndex" }));
207
+ }
208
+ }
209
+ }
210
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
211
+ finally {
212
+ try {
213
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
214
+ }
215
+ finally { if (e_3) throw e_3.error; }
216
+ }
217
+ return lines.join("\n");
218
+ };
219
+ var renderFile = function (_a) {
220
+ var catalog = _a.catalog, id = _a.id, ops = _a.ops;
221
+ var unsafe = ops.some(function (op) { return !op.safe; });
222
+ var upBody = unsafe
223
+ ? renderUnsafeBody({ catalog: catalog, ops: ops, reverse: false })
224
+ : renderSafeUp(ops, catalog);
225
+ var downBody = unsafe
226
+ ? renderUnsafeBody({ catalog: catalog, ops: ops, reverse: true })
227
+ : renderSafeDown(ops, catalog);
228
+ return "export const id = ".concat(JSON.stringify(id), ";\n\nexport const schemaAfter = ").concat(JSON.stringify(catalog), ";\n\nexport const up = async (ctx) => {\n").concat(upBody, "\n};\n\nexport const down = async (ctx) => {\n").concat(downBody, "\n};\n");
229
+ };
230
+ var generateMigration = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
231
+ var previous, loaded, error_1, message, catalog, diff, id, path;
232
+ var _c;
233
+ var dir = _b.dir, models = _b.models, _d = _b.name, name = _d === void 0 ? "auto" : _d, _e = _b.now, now = _e === void 0 ? function () { return luxon_1.DateTime.now(); } : _e;
234
+ return __generator(this, function (_f) {
235
+ switch (_f.label) {
236
+ case 0: return [4 /*yield*/, (0, promises_1.mkdir)(dir, { recursive: true })];
237
+ case 1:
238
+ _f.sent();
239
+ previous = emptyCatalog();
240
+ _f.label = 2;
241
+ case 2:
242
+ _f.trys.push([2, 4, , 5]);
243
+ return [4 /*yield*/, (0, load_1.checkMigrationFiles)({ dir: dir })];
244
+ case 3:
245
+ loaded = _f.sent();
246
+ previous = (_c = (0, exports.lastSchemaAfter)(loaded)) !== null && _c !== void 0 ? _c : emptyCatalog();
247
+ return [3 /*break*/, 5];
248
+ case 4:
249
+ error_1 = _f.sent();
250
+ message = error_1 instanceof Error ? error_1.message : String(error_1);
251
+ if (!message.includes("ENOENT")) {
252
+ throw error_1;
253
+ }
254
+ return [3 /*break*/, 5];
255
+ case 5:
256
+ if (models.length === 0) {
257
+ throw new errors_1.APIError({
258
+ detail: "Pass a --models module that exports models or {models: Model[]}.",
259
+ status: 400,
260
+ title: "No Mongoose models found",
261
+ });
262
+ }
263
+ catalog = (0, schemaCatalog_1.buildSchemaCatalog)({ models: models });
264
+ diff = (0, schemaCatalog_1.diffSchemaCatalog)({ after: catalog, before: previous });
265
+ if (diff.ops.length === 0) {
266
+ return [2 /*return*/, { noop: true, path: null }];
267
+ }
268
+ id = "".concat(now().toUTC().toFormat("yyyyMMddHHmmss"), "-").concat(slugify(name));
269
+ path = (0, node_path_1.join)(dir, "".concat(id, ".ts"));
270
+ return [4 /*yield*/, (0, promises_1.writeFile)(path, renderFile({ catalog: catalog, id: id, ops: diff.ops }), "utf8")];
271
+ case 6:
272
+ _f.sent();
273
+ return [2 /*return*/, { noop: false, path: path }];
274
+ }
275
+ });
276
+ }); };
277
+ exports.generateMigration = generateMigration;
@@ -0,0 +1,20 @@
1
+ import type { LoadedMigration } from "./types";
2
+ export declare const MIGRATION_FILENAME: RegExp;
3
+ /**
4
+ * Pick a real on-disk migrations directory.
5
+ * `bun build --compile` rewrites `import.meta.url` to `$bunfs`, which is not
6
+ * scandir-able. Prefer an explicit real `dir`, then `MIGRATIONS_DIR`, then
7
+ * `<cwd>/migrations`.
8
+ */
9
+ export declare const resolveMigrationDir: ({ cwd, dir, envDir, }: {
10
+ cwd?: string;
11
+ dir?: string;
12
+ envDir?: string;
13
+ }) => string;
14
+ export declare const checkMigrationFiles: ({ dir }: {
15
+ dir: string;
16
+ }) => Promise<LoadedMigration[]>;
17
+ /** Public alias for `checkMigrationFiles`; kept as a wrapper so Knip does not treat it as a duplicate export. */
18
+ export declare const loadMigrations: ({ dir }: {
19
+ dir: string;
20
+ }) => Promise<LoadedMigration[]>;
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __generator = (this && this.__generator) || function (thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
46
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
+ }
70
+ };
71
+ var __values = (this && this.__values) || function(o) {
72
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
73
+ if (m) return m.call(o);
74
+ if (o && typeof o.length === "number") return {
75
+ next: function () {
76
+ if (o && i >= o.length) o = void 0;
77
+ return { value: o && o[i++], done: !o };
78
+ }
79
+ };
80
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
81
+ };
82
+ Object.defineProperty(exports, "__esModule", { value: true });
83
+ exports.loadMigrations = exports.checkMigrationFiles = exports.resolveMigrationDir = exports.MIGRATION_FILENAME = void 0;
84
+ /**
85
+ * Load and validate timestamped `migrations/<YYYYMMDDHHmmss>-<slug>.ts` files
86
+ * without connecting to Mongo. Used by `terreno-migrate check` and as input to the runner.
87
+ */
88
+ var node_crypto_1 = require("node:crypto");
89
+ var promises_1 = require("node:fs/promises");
90
+ var node_path_1 = require("node:path");
91
+ var node_url_1 = require("node:url");
92
+ var errors_1 = require("../errors");
93
+ exports.MIGRATION_FILENAME = /^(\d{14})-[a-z0-9-]+\.ts$/;
94
+ /** Bun compile (`bun build --compile`) puts modules on a virtual FS. */
95
+ var isBunVirtualFsPath = function (value) {
96
+ return value.includes("$bunfs");
97
+ };
98
+ /**
99
+ * Pick a real on-disk migrations directory.
100
+ * `bun build --compile` rewrites `import.meta.url` to `$bunfs`, which is not
101
+ * scandir-able. Prefer an explicit real `dir`, then `MIGRATIONS_DIR`, then
102
+ * `<cwd>/migrations`.
103
+ */
104
+ var resolveMigrationDir = function (_a) {
105
+ var _b = _a.cwd, cwd = _b === void 0 ? process.cwd() : _b, dir = _a.dir, _c = _a.envDir, envDir = _c === void 0 ? process.env.MIGRATIONS_DIR : _c;
106
+ if (dir && !isBunVirtualFsPath(dir)) {
107
+ return dir;
108
+ }
109
+ if (envDir) {
110
+ return envDir;
111
+ }
112
+ return (0, node_path_1.join)(cwd, "migrations");
113
+ };
114
+ exports.resolveMigrationDir = resolveMigrationDir;
115
+ var readMigrationFilenames = function (dir) { return __awaiter(void 0, void 0, void 0, function () {
116
+ var error_1, code;
117
+ return __generator(this, function (_a) {
118
+ switch (_a.label) {
119
+ case 0:
120
+ _a.trys.push([0, 2, , 3]);
121
+ return [4 /*yield*/, (0, promises_1.readdir)(dir)];
122
+ case 1: return [2 /*return*/, _a.sent()];
123
+ case 2:
124
+ error_1 = _a.sent();
125
+ code = error_1.code;
126
+ if (code === "ENOENT") {
127
+ throw new errors_1.APIError({
128
+ detail: "No directory at ".concat(dir),
129
+ status: 404,
130
+ title: "Migration directory not found",
131
+ });
132
+ }
133
+ throw error_1;
134
+ case 3: return [2 /*return*/];
135
+ }
136
+ });
137
+ }); };
138
+ var checksumOf = function (source) {
139
+ return (0, node_crypto_1.createHash)("sha256").update(source).digest("hex");
140
+ };
141
+ var expectedIdFromFilename = function (filename) {
142
+ return filename.replace(/\.ts$/, "");
143
+ };
144
+ var checkMigrationFiles = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
145
+ var resolvedDir, entries, files, loaded, seenIds, files_1, files_1_1, filename, source, mod, expectedId, e_1_1;
146
+ var e_1, _c;
147
+ var dir = _b.dir;
148
+ return __generator(this, function (_d) {
149
+ switch (_d.label) {
150
+ case 0:
151
+ resolvedDir = (0, exports.resolveMigrationDir)({ dir: dir });
152
+ return [4 /*yield*/, readMigrationFilenames(resolvedDir)];
153
+ case 1:
154
+ entries = _d.sent();
155
+ files = entries.filter(function (name) { return name.endsWith(".ts"); }).sort();
156
+ loaded = [];
157
+ seenIds = new Set();
158
+ _d.label = 2;
159
+ case 2:
160
+ _d.trys.push([2, 8, 9, 10]);
161
+ files_1 = __values(files), files_1_1 = files_1.next();
162
+ _d.label = 3;
163
+ case 3:
164
+ if (!!files_1_1.done) return [3 /*break*/, 7];
165
+ filename = files_1_1.value;
166
+ if (!exports.MIGRATION_FILENAME.test(filename)) {
167
+ throw new errors_1.APIError({
168
+ detail: "Expected YYYYMMDDHHmmss-slug.ts, received ".concat(filename),
169
+ status: 400,
170
+ title: "Invalid migration filename",
171
+ });
172
+ }
173
+ return [4 /*yield*/, (0, promises_1.readFile)((0, node_path_1.join)(resolvedDir, filename), "utf8")];
174
+ case 4:
175
+ source = _d.sent();
176
+ return [4 /*yield*/, Promise.resolve("".concat((0, node_url_1.pathToFileURL)((0, node_path_1.join)(resolvedDir, filename)).href)).then(function (s) { return __importStar(require(s)); })];
177
+ case 5:
178
+ mod = (_d.sent());
179
+ expectedId = expectedIdFromFilename(filename);
180
+ if (mod.id !== expectedId) {
181
+ throw new errors_1.APIError({
182
+ detail: "File ".concat(filename, " exported id ").concat(String(mod.id)),
183
+ status: 400,
184
+ title: "Migration id does not match filename",
185
+ });
186
+ }
187
+ if (typeof mod.up !== "function") {
188
+ throw new errors_1.APIError({
189
+ detail: "".concat(filename, " must export an up function"),
190
+ status: 400,
191
+ title: "Migration missing up",
192
+ });
193
+ }
194
+ if (seenIds.has(mod.id)) {
195
+ throw new errors_1.APIError({
196
+ detail: "Duplicate migration id ".concat(mod.id),
197
+ status: 400,
198
+ title: "Duplicate migration id",
199
+ });
200
+ }
201
+ seenIds.add(mod.id);
202
+ loaded.push({
203
+ checksum: checksumOf(source),
204
+ down: mod.down,
205
+ id: mod.id,
206
+ schemaAfter: mod.schemaAfter,
207
+ up: mod.up,
208
+ });
209
+ _d.label = 6;
210
+ case 6:
211
+ files_1_1 = files_1.next();
212
+ return [3 /*break*/, 3];
213
+ case 7: return [3 /*break*/, 10];
214
+ case 8:
215
+ e_1_1 = _d.sent();
216
+ e_1 = { error: e_1_1 };
217
+ return [3 /*break*/, 10];
218
+ case 9:
219
+ try {
220
+ if (files_1_1 && !files_1_1.done && (_c = files_1.return)) _c.call(files_1);
221
+ }
222
+ finally { if (e_1) throw e_1.error; }
223
+ return [7 /*endfinally*/];
224
+ case 10: return [2 /*return*/, loaded];
225
+ }
226
+ });
227
+ }); };
228
+ exports.checkMigrationFiles = checkMigrationFiles;
229
+ /** Public alias for `checkMigrationFiles`; kept as a wrapper so Knip does not treat it as a duplicate export. */
230
+ var loadMigrations = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
231
+ var dir = _b.dir;
232
+ return __generator(this, function (_c) {
233
+ return [2 /*return*/, (0, exports.checkMigrationFiles)({ dir: dir })];
234
+ });
235
+ }); };
236
+ exports.loadMigrations = loadMigrations;
@@ -0,0 +1,13 @@
1
+ import { DateTime } from "luxon";
2
+ import type mongoose from "mongoose";
3
+ /** Default lock lifetime before another runner may steal it. */
4
+ export declare const MIGRATION_LOCK_TTL_MS: number;
5
+ export interface WithMigrationLockOptions<T> {
6
+ connection: mongoose.Connection;
7
+ fn: () => Promise<T>;
8
+ ttlMs?: number;
9
+ pollMs?: number;
10
+ holder?: string;
11
+ now?: () => DateTime;
12
+ }
13
+ export declare const withMigrationLock: <T>({ connection, fn, holder, now, pollMs, ttlMs, }: WithMigrationLockOptions<T>) => Promise<T>;