@classytic/arc 1.1.0 → 2.1.3

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 (200) hide show
  1. package/README.md +247 -794
  2. package/bin/arc.js +91 -52
  3. package/dist/EventTransport-BkUDYZEb.d.mts +99 -0
  4. package/dist/HookSystem-BsGV-j2l.mjs +404 -0
  5. package/dist/ResourceRegistry-7Ic20ZMw.mjs +249 -0
  6. package/dist/adapters/index.d.mts +5 -0
  7. package/dist/adapters/index.mjs +3 -0
  8. package/dist/audit/index.d.mts +81 -0
  9. package/dist/audit/index.mjs +275 -0
  10. package/dist/audit/mongodb.d.mts +5 -0
  11. package/dist/audit/mongodb.mjs +3 -0
  12. package/dist/audited-CGdLiSlE.mjs +140 -0
  13. package/dist/auth/index.d.mts +188 -0
  14. package/dist/auth/index.mjs +1096 -0
  15. package/dist/auth/redis-session.d.mts +43 -0
  16. package/dist/auth/redis-session.mjs +75 -0
  17. package/dist/betterAuthOpenApi-DjWDddNc.mjs +249 -0
  18. package/dist/cache/index.d.mts +145 -0
  19. package/dist/cache/index.mjs +91 -0
  20. package/dist/caching-GSDJcA6-.mjs +93 -0
  21. package/dist/chunk-C7Uep-_p.mjs +20 -0
  22. package/dist/circuitBreaker-DYhWBW_D.mjs +1096 -0
  23. package/dist/cli/commands/describe.d.mts +18 -0
  24. package/dist/cli/commands/describe.mjs +238 -0
  25. package/dist/cli/commands/docs.d.mts +13 -0
  26. package/dist/cli/commands/docs.mjs +52 -0
  27. package/dist/cli/commands/{generate.d.ts → generate.d.mts} +3 -2
  28. package/dist/cli/commands/generate.mjs +357 -0
  29. package/dist/cli/commands/{init.d.ts → init.d.mts} +11 -8
  30. package/dist/cli/commands/{init.js → init.mjs} +807 -617
  31. package/dist/cli/commands/introspect.d.mts +10 -0
  32. package/dist/cli/commands/introspect.mjs +75 -0
  33. package/dist/cli/index.d.mts +16 -0
  34. package/dist/cli/index.mjs +156 -0
  35. package/dist/constants-DdXFXQtN.mjs +84 -0
  36. package/dist/core/index.d.mts +5 -0
  37. package/dist/core/index.mjs +4 -0
  38. package/dist/createApp-D2D5XXaV.mjs +559 -0
  39. package/dist/defineResource-PXzSJ15_.mjs +2197 -0
  40. package/dist/discovery/index.d.mts +46 -0
  41. package/dist/discovery/index.mjs +109 -0
  42. package/dist/docs/index.d.mts +162 -0
  43. package/dist/docs/index.mjs +74 -0
  44. package/dist/elevation-DGo5shaX.d.mts +87 -0
  45. package/dist/elevation-DSTbVvYj.mjs +113 -0
  46. package/dist/errorHandler-C3GY3_ow.mjs +108 -0
  47. package/dist/errorHandler-CW3OOeYq.d.mts +72 -0
  48. package/dist/errors-DAWRdiYP.d.mts +124 -0
  49. package/dist/errors-DBANPbGr.mjs +211 -0
  50. package/dist/eventPlugin-BEOvaDqo.mjs +229 -0
  51. package/dist/eventPlugin-H6wDDjGO.d.mts +124 -0
  52. package/dist/events/index.d.mts +53 -0
  53. package/dist/events/index.mjs +51 -0
  54. package/dist/events/transports/redis-stream-entry.d.mts +2 -0
  55. package/dist/events/transports/redis-stream-entry.mjs +177 -0
  56. package/dist/events/transports/redis.d.mts +76 -0
  57. package/dist/events/transports/redis.mjs +124 -0
  58. package/dist/externalPaths-SyPF2tgK.d.mts +50 -0
  59. package/dist/factory/index.d.mts +63 -0
  60. package/dist/factory/index.mjs +3 -0
  61. package/dist/fastifyAdapter-C8DlE0YH.d.mts +216 -0
  62. package/dist/fields-Bi_AVKSo.d.mts +109 -0
  63. package/dist/fields-CTd_CrKr.mjs +114 -0
  64. package/dist/hooks/index.d.mts +4 -0
  65. package/dist/hooks/index.mjs +3 -0
  66. package/dist/idempotency/index.d.mts +96 -0
  67. package/dist/idempotency/index.mjs +319 -0
  68. package/dist/idempotency/mongodb.d.mts +2 -0
  69. package/dist/idempotency/mongodb.mjs +114 -0
  70. package/dist/idempotency/redis.d.mts +2 -0
  71. package/dist/idempotency/redis.mjs +103 -0
  72. package/dist/index.d.mts +260 -0
  73. package/dist/index.mjs +104 -0
  74. package/dist/integrations/event-gateway.d.mts +46 -0
  75. package/dist/integrations/event-gateway.mjs +43 -0
  76. package/dist/integrations/index.d.mts +5 -0
  77. package/dist/integrations/index.mjs +1 -0
  78. package/dist/integrations/jobs.d.mts +103 -0
  79. package/dist/integrations/jobs.mjs +123 -0
  80. package/dist/integrations/streamline.d.mts +60 -0
  81. package/dist/integrations/streamline.mjs +125 -0
  82. package/dist/integrations/websocket.d.mts +82 -0
  83. package/dist/integrations/websocket.mjs +288 -0
  84. package/dist/interface-CSNjltAc.d.mts +77 -0
  85. package/dist/interface-DTbsvIWe.d.mts +54 -0
  86. package/dist/interface-e9XfSsUV.d.mts +1097 -0
  87. package/dist/introspectionPlugin-B3JkrjwU.mjs +53 -0
  88. package/dist/keys-DhqDRxv3.mjs +42 -0
  89. package/dist/logger-ByrvQWZO.mjs +78 -0
  90. package/dist/memory-B2v7KrCB.mjs +143 -0
  91. package/dist/migrations/index.d.mts +156 -0
  92. package/dist/migrations/index.mjs +260 -0
  93. package/dist/mongodb-ClykrfGo.d.mts +118 -0
  94. package/dist/mongodb-DNKEExbf.mjs +93 -0
  95. package/dist/mongodb-Dg8O_gvd.d.mts +71 -0
  96. package/dist/openapi-9nB_kiuR.mjs +525 -0
  97. package/dist/org/index.d.mts +68 -0
  98. package/dist/org/index.mjs +513 -0
  99. package/dist/org/types.d.mts +82 -0
  100. package/dist/org/types.mjs +1 -0
  101. package/dist/permissions/index.d.mts +278 -0
  102. package/dist/permissions/index.mjs +579 -0
  103. package/dist/plugins/index.d.mts +172 -0
  104. package/dist/plugins/index.mjs +522 -0
  105. package/dist/plugins/response-cache.d.mts +87 -0
  106. package/dist/plugins/response-cache.mjs +283 -0
  107. package/dist/plugins/tracing-entry.d.mts +2 -0
  108. package/dist/plugins/tracing-entry.mjs +185 -0
  109. package/dist/pluralize-CM-jZg7p.mjs +86 -0
  110. package/dist/policies/{index.d.ts → index.d.mts} +204 -170
  111. package/dist/policies/index.mjs +321 -0
  112. package/dist/presets/{index.d.ts → index.d.mts} +62 -131
  113. package/dist/presets/index.mjs +143 -0
  114. package/dist/presets/multiTenant.d.mts +24 -0
  115. package/dist/presets/multiTenant.mjs +113 -0
  116. package/dist/presets-BTeYbw7h.d.mts +57 -0
  117. package/dist/presets-CeFtfDR8.mjs +119 -0
  118. package/dist/prisma-C3iornoK.d.mts +274 -0
  119. package/dist/prisma-DJbMt3yf.mjs +627 -0
  120. package/dist/queryCachePlugin-B6R0d4av.mjs +138 -0
  121. package/dist/queryCachePlugin-Q6SYuHZ6.d.mts +71 -0
  122. package/dist/redis-UwjEp8Ea.d.mts +49 -0
  123. package/dist/redis-stream-CBg0upHI.d.mts +103 -0
  124. package/dist/registry/index.d.mts +11 -0
  125. package/dist/registry/index.mjs +4 -0
  126. package/dist/requestContext-xi6OKBL-.mjs +55 -0
  127. package/dist/schemaConverter-Dtg0Kt9T.mjs +98 -0
  128. package/dist/schemas/index.d.mts +63 -0
  129. package/dist/schemas/index.mjs +82 -0
  130. package/dist/scope/index.d.mts +21 -0
  131. package/dist/scope/index.mjs +65 -0
  132. package/dist/sessionManager-D_iEHjQl.d.mts +186 -0
  133. package/dist/sse-DkqQ1uxb.mjs +123 -0
  134. package/dist/testing/index.d.mts +907 -0
  135. package/dist/testing/index.mjs +1976 -0
  136. package/dist/tracing-8CEbhF0w.d.mts +70 -0
  137. package/dist/typeGuards-DwxA1t_L.mjs +9 -0
  138. package/dist/types/index.d.mts +946 -0
  139. package/dist/types/index.mjs +14 -0
  140. package/dist/types-B0dhNrnd.d.mts +445 -0
  141. package/dist/types-Beqn1Un7.mjs +38 -0
  142. package/dist/types-DelU6kln.mjs +25 -0
  143. package/dist/types-RLkFVgaw.d.mts +101 -0
  144. package/dist/utils/index.d.mts +747 -0
  145. package/dist/utils/index.mjs +6 -0
  146. package/package.json +194 -68
  147. package/dist/BaseController-DVAiHxEQ.d.ts +0 -233
  148. package/dist/adapters/index.d.ts +0 -237
  149. package/dist/adapters/index.js +0 -668
  150. package/dist/arcCorePlugin-CsShQdyP.d.ts +0 -273
  151. package/dist/audit/index.d.ts +0 -195
  152. package/dist/audit/index.js +0 -319
  153. package/dist/auth/index.d.ts +0 -47
  154. package/dist/auth/index.js +0 -174
  155. package/dist/cli/commands/docs.d.ts +0 -11
  156. package/dist/cli/commands/docs.js +0 -474
  157. package/dist/cli/commands/generate.js +0 -334
  158. package/dist/cli/commands/introspect.d.ts +0 -8
  159. package/dist/cli/commands/introspect.js +0 -338
  160. package/dist/cli/index.d.ts +0 -4
  161. package/dist/cli/index.js +0 -3269
  162. package/dist/core/index.d.ts +0 -220
  163. package/dist/core/index.js +0 -2786
  164. package/dist/createApp-Ce9wl8W9.d.ts +0 -77
  165. package/dist/docs/index.d.ts +0 -166
  166. package/dist/docs/index.js +0 -658
  167. package/dist/errors-8WIxGS_6.d.ts +0 -122
  168. package/dist/events/index.d.ts +0 -117
  169. package/dist/events/index.js +0 -89
  170. package/dist/factory/index.d.ts +0 -38
  171. package/dist/factory/index.js +0 -1652
  172. package/dist/hooks/index.d.ts +0 -4
  173. package/dist/hooks/index.js +0 -199
  174. package/dist/idempotency/index.d.ts +0 -323
  175. package/dist/idempotency/index.js +0 -500
  176. package/dist/index-B4t03KQ0.d.ts +0 -1366
  177. package/dist/index.d.ts +0 -135
  178. package/dist/index.js +0 -4756
  179. package/dist/migrations/index.d.ts +0 -185
  180. package/dist/migrations/index.js +0 -274
  181. package/dist/org/index.d.ts +0 -129
  182. package/dist/org/index.js +0 -220
  183. package/dist/permissions/index.d.ts +0 -144
  184. package/dist/permissions/index.js +0 -103
  185. package/dist/plugins/index.d.ts +0 -46
  186. package/dist/plugins/index.js +0 -1069
  187. package/dist/policies/index.js +0 -196
  188. package/dist/presets/index.js +0 -384
  189. package/dist/presets/multiTenant.d.ts +0 -39
  190. package/dist/presets/multiTenant.js +0 -112
  191. package/dist/registry/index.d.ts +0 -16
  192. package/dist/registry/index.js +0 -253
  193. package/dist/testing/index.d.ts +0 -618
  194. package/dist/testing/index.js +0 -48020
  195. package/dist/types/index.d.ts +0 -4
  196. package/dist/types/index.js +0 -8
  197. package/dist/types-B99TBmFV.d.ts +0 -76
  198. package/dist/types-BvckRbs2.d.ts +0 -143
  199. package/dist/utils/index.d.ts +0 -679
  200. package/dist/utils/index.js +0 -931
@@ -0,0 +1,53 @@
1
+ import fp from "fastify-plugin";
2
+
3
+ //#region src/registry/introspectionPlugin.ts
4
+ /**
5
+ * Introspection Plugin
6
+ *
7
+ * Exposes resource registry via API endpoints.
8
+ */
9
+ const introspectionPlugin = async (fastify, opts = {}) => {
10
+ const { prefix = "/_resources", authRoles = ["superadmin"], enabled = true } = opts;
11
+ if (!enabled) {
12
+ fastify.log?.debug?.("Introspection plugin disabled");
13
+ return;
14
+ }
15
+ const typedFastify = fastify;
16
+ const authMiddleware = authRoles.length > 0 && typedFastify.authenticate ? [typedFastify.authenticate, typedFastify.authorize?.(...authRoles)].filter(Boolean) : [];
17
+ const getRegistry = () => fastify.arc?.registry;
18
+ await fastify.register(async (instance) => {
19
+ instance.get("/", { preHandler: authMiddleware }, async (_req, _reply) => {
20
+ return getRegistry()?.getIntrospection() ?? {
21
+ resources: [],
22
+ stats: {},
23
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
24
+ };
25
+ });
26
+ instance.get("/stats", { preHandler: authMiddleware }, async (_req, _reply) => {
27
+ return getRegistry()?.getStats() ?? {
28
+ totalResources: 0,
29
+ byModule: {},
30
+ presetUsage: {},
31
+ totalRoutes: 0,
32
+ totalEvents: 0
33
+ };
34
+ });
35
+ instance.get("/:name", {
36
+ schema: { params: {
37
+ type: "object",
38
+ properties: { name: { type: "string" } },
39
+ required: ["name"]
40
+ } },
41
+ preHandler: authMiddleware
42
+ }, async (req, reply) => {
43
+ const resource = getRegistry()?.get(req.params.name);
44
+ if (!resource) return reply.code(404).send({ error: `Resource '${req.params.name}' not found` });
45
+ return resource;
46
+ });
47
+ }, { prefix });
48
+ fastify.log?.debug?.(`Introspection API at ${prefix}`);
49
+ };
50
+ var introspectionPlugin_default = fp(introspectionPlugin, { name: "arc-introspection" });
51
+
52
+ //#endregion
53
+ export { introspectionPlugin_default as n, introspectionPlugin as t };
@@ -0,0 +1,42 @@
1
+ //#region src/cache/keys.ts
2
+ /**
3
+ * Cache Key Utilities
4
+ *
5
+ * Deterministic, scope-safe key generation for QueryCache.
6
+ * Keys include resource version, operation, params hash, and user/org scope
7
+ * to ensure multi-tenant isolation and O(1) version-based invalidation.
8
+ */
9
+ /** Build a deterministic cache key for a query */
10
+ function buildQueryKey(resource, operation, resourceVersion, params, userId, orgId) {
11
+ return `arc:${resource}:${resourceVersion}:${operation}:${hashParams(params)}:u=${userId ?? "anon"}:o=${orgId ?? "pub"}`;
12
+ }
13
+ /** Resource version key — stored in CacheStore, bumped on mutations */
14
+ function versionKey(resource) {
15
+ return `arc:ver:${resource}`;
16
+ }
17
+ /** Tag version key — stored in CacheStore, bumped on cross-resource invalidation */
18
+ function tagVersionKey(tag) {
19
+ return `arc:tagver:${tag}`;
20
+ }
21
+ /**
22
+ * Stable hash for query params.
23
+ * Sorts keys recursively, serializes to JSON, then applies djb2 hash.
24
+ * Returns hex string.
25
+ */
26
+ function hashParams(params) {
27
+ return djb2(stableStringify(params)).toString(36);
28
+ }
29
+ function stableStringify(value) {
30
+ if (value === null || value === void 0) return "";
31
+ if (typeof value !== "object") return String(value);
32
+ if (Array.isArray(value)) return "[" + value.map(stableStringify).join(",") + "]";
33
+ return "{" + Object.keys(value).sort().map((k) => k + ":" + stableStringify(value[k])).join(",") + "}";
34
+ }
35
+ function djb2(str) {
36
+ let hash = 5381;
37
+ for (let i = 0; i < str.length; i++) hash = (hash << 5) + hash + str.charCodeAt(i) >>> 0;
38
+ return hash;
39
+ }
40
+
41
+ //#endregion
42
+ export { versionKey as i, hashParams as n, tagVersionKey as r, buildQueryKey as t };
@@ -0,0 +1,78 @@
1
+ import { t as __exportAll } from "./chunk-C7Uep-_p.mjs";
2
+
3
+ //#region src/logger/index.ts
4
+ var logger_exports = /* @__PURE__ */ __exportAll({
5
+ arcLog: () => arcLog,
6
+ configureArcLogger: () => configureArcLogger
7
+ });
8
+ let globalOptions = {};
9
+ /**
10
+ * Configure the Arc logger globally.
11
+ *
12
+ * Called automatically by `createApp({ debug })`, but can also be
13
+ * called manually for standalone usage outside of `createApp`.
14
+ */
15
+ function configureArcLogger(options) {
16
+ globalOptions = { ...options };
17
+ }
18
+ /**
19
+ * Create a module-scoped logger.
20
+ *
21
+ * Debug and info messages are gated by the `ARC_DEBUG` env var or
22
+ * `createApp({ debug })` option. Warnings always show (unless
23
+ * `ARC_SUPPRESS_WARNINGS=1`). Errors always show.
24
+ *
25
+ * @param module - Module name (e.g., 'scope', 'elevation', 'sse', 'preset')
26
+ * @returns Logger instance for that module
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const log = arcLog('elevation');
31
+ * log.debug('Checking elevation header');
32
+ * log.warn('No authenticate decorator found');
33
+ * ```
34
+ */
35
+ function arcLog(module) {
36
+ const prefix = `[arc:${module}]`;
37
+ return {
38
+ debug(...args) {
39
+ if (isDebugEnabled(module)) getWriter().debug(prefix, ...args);
40
+ },
41
+ info(...args) {
42
+ if (isDebugEnabled(module)) getWriter().info(prefix, ...args);
43
+ },
44
+ warn(...args) {
45
+ if (isSuppressed()) return;
46
+ getWriter().warn(prefix, ...args);
47
+ },
48
+ error(...args) {
49
+ getWriter().error(prefix, ...args);
50
+ }
51
+ };
52
+ }
53
+ function getWriter() {
54
+ return globalOptions.writer ?? console;
55
+ }
56
+ function isDebugEnabled(module) {
57
+ const configDebug = globalOptions.debug;
58
+ if (configDebug !== void 0 && configDebug !== false) return matchesModule(configDebug, module);
59
+ const envDebug = typeof process !== "undefined" ? process.env?.ARC_DEBUG : void 0;
60
+ if (envDebug) return matchesModule(envDebug, module);
61
+ return false;
62
+ }
63
+ function matchesModule(debug, module) {
64
+ if (debug === true) return true;
65
+ if (typeof debug === "string") {
66
+ const normalized = debug.trim();
67
+ if (normalized === "1" || normalized === "true" || normalized === "*") return true;
68
+ return normalized.split(",").map((s) => s.trim()).includes(module);
69
+ }
70
+ return false;
71
+ }
72
+ function isSuppressed() {
73
+ const env = typeof process !== "undefined" ? process.env?.ARC_SUPPRESS_WARNINGS : void 0;
74
+ return env === "1" || env === "true";
75
+ }
76
+
77
+ //#endregion
78
+ export { configureArcLogger as n, logger_exports as r, arcLog as t };
@@ -0,0 +1,143 @@
1
+ import { t as __exportAll } from "./chunk-C7Uep-_p.mjs";
2
+
3
+ //#region src/cache/memory.ts
4
+ var memory_exports = /* @__PURE__ */ __exportAll({
5
+ MemoryCacheStore: () => MemoryCacheStore,
6
+ default: () => MemoryCacheStore
7
+ });
8
+ /**
9
+ * In-memory LRU+TTL cache store with hard entry cap and memory budget.
10
+ * - LRU eviction when `maxEntries` or `maxMemoryBytes` is reached
11
+ * - TTL expiration on read + periodic cleanup
12
+ * - Entry size guard to avoid runaway memory usage
13
+ * - Stats tracking for observability
14
+ */
15
+ var MemoryCacheStore = class {
16
+ name = "memory-cache";
17
+ cache = /* @__PURE__ */ new Map();
18
+ defaultTtlMs;
19
+ maxEntries;
20
+ maxEntryBytes;
21
+ maxMemoryBytes;
22
+ evictionWatermark;
23
+ logger;
24
+ cleanupTimer;
25
+ currentBytes = 0;
26
+ _hits = 0;
27
+ _misses = 0;
28
+ _evictions = 0;
29
+ constructor(options = {}) {
30
+ this.defaultTtlMs = options.defaultTtlMs ?? 6e4;
31
+ this.maxEntries = clamp(options.maxEntries ?? 1e3, 1, 1e5);
32
+ this.maxEntryBytes = clamp(options.maxEntryBytes ?? 256 * 1024, 1024, 10 * 1024 * 1024);
33
+ this.maxMemoryBytes = options.maxMemoryBytes ?? 50 * 1024 * 1024;
34
+ this.evictionWatermark = clamp(options.evictionWatermark ?? .9, .5, 1);
35
+ this.logger = options.logger ?? console;
36
+ const cleanupIntervalMs = clamp(options.cleanupIntervalMs ?? 3e4, 1e3, 600 * 1e3);
37
+ this.cleanupTimer = setInterval(() => this.cleanupExpired(), cleanupIntervalMs);
38
+ if (this.cleanupTimer.unref) this.cleanupTimer.unref();
39
+ }
40
+ async get(key) {
41
+ const entry = this.cache.get(key);
42
+ if (!entry) {
43
+ this._misses++;
44
+ return;
45
+ }
46
+ if (entry.expiresAt <= Date.now()) {
47
+ this.removeEntry(key, entry);
48
+ this._misses++;
49
+ return;
50
+ }
51
+ this.cache.delete(key);
52
+ this.cache.set(key, entry);
53
+ this._hits++;
54
+ return entry.value;
55
+ }
56
+ async set(key, value, options = {}) {
57
+ const ttlMs = options.ttlMs ?? this.defaultTtlMs;
58
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) return;
59
+ const size = this.estimateSize(value);
60
+ if (size > this.maxEntryBytes) {
61
+ this.logger.warn(`[MemoryCacheStore] Skipping oversized entry for key '${key}' (${size} bytes > ${this.maxEntryBytes} bytes)`);
62
+ return;
63
+ }
64
+ const existing = this.cache.get(key);
65
+ if (existing) {
66
+ this.currentBytes -= existing.size;
67
+ this.cache.delete(key);
68
+ }
69
+ this.cache.set(key, {
70
+ value,
71
+ size,
72
+ expiresAt: Date.now() + ttlMs
73
+ });
74
+ this.currentBytes += size;
75
+ this.evictToLimit();
76
+ if (this.maxMemoryBytes > 0) this.evictToMemoryLimit();
77
+ }
78
+ async delete(key) {
79
+ const entry = this.cache.get(key);
80
+ if (entry) this.removeEntry(key, entry);
81
+ }
82
+ async clear() {
83
+ this.cache.clear();
84
+ this.currentBytes = 0;
85
+ }
86
+ async close() {
87
+ clearInterval(this.cleanupTimer);
88
+ this.cache.clear();
89
+ this.currentBytes = 0;
90
+ }
91
+ stats() {
92
+ return {
93
+ entries: this.cache.size,
94
+ memoryBytes: this.currentBytes,
95
+ hits: this._hits,
96
+ misses: this._misses,
97
+ evictions: this._evictions
98
+ };
99
+ }
100
+ removeEntry(key, entry) {
101
+ this.cache.delete(key);
102
+ this.currentBytes -= entry.size;
103
+ }
104
+ evictToLimit() {
105
+ while (this.cache.size > this.maxEntries) {
106
+ const oldestKey = this.cache.keys().next().value;
107
+ if (!oldestKey) break;
108
+ const entry = this.cache.get(oldestKey);
109
+ this.removeEntry(oldestKey, entry);
110
+ this._evictions++;
111
+ }
112
+ }
113
+ evictToMemoryLimit() {
114
+ const target = this.maxMemoryBytes * this.evictionWatermark;
115
+ while (this.currentBytes > this.maxMemoryBytes && this.cache.size > 0) {
116
+ const oldestKey = this.cache.keys().next().value;
117
+ if (!oldestKey) break;
118
+ const entry = this.cache.get(oldestKey);
119
+ this.removeEntry(oldestKey, entry);
120
+ this._evictions++;
121
+ if (this.currentBytes <= target) break;
122
+ }
123
+ }
124
+ cleanupExpired() {
125
+ const now = Date.now();
126
+ for (const [key, entry] of this.cache.entries()) if (entry.expiresAt <= now) this.removeEntry(key, entry);
127
+ }
128
+ estimateSize(value) {
129
+ try {
130
+ const json = JSON.stringify(value);
131
+ if (!json) return 0;
132
+ return Buffer.byteLength(json, "utf8");
133
+ } catch {
134
+ return this.maxEntryBytes + 1;
135
+ }
136
+ }
137
+ };
138
+ function clamp(value, min, max) {
139
+ return Math.min(max, Math.max(min, value));
140
+ }
141
+
142
+ //#endregion
143
+ export { memory_exports as n, MemoryCacheStore as t };
@@ -0,0 +1,156 @@
1
+ import mongoose from "mongoose";
2
+
3
+ //#region src/migrations/index.d.ts
4
+ interface Migration {
5
+ /** Migration version (sequential number) */
6
+ version: number;
7
+ /** Resource name this migration applies to */
8
+ resource: string;
9
+ /** Description of the migration */
10
+ description?: string;
11
+ /**
12
+ * Forward migration (apply schema change)
13
+ */
14
+ up: (db: mongoose.mongo.Db) => Promise<void>;
15
+ /**
16
+ * Backward migration (revert schema change)
17
+ */
18
+ down: (db: mongoose.mongo.Db) => Promise<void>;
19
+ /**
20
+ * Optional validation that data is compatible after migration
21
+ */
22
+ validate?: (db: mongoose.mongo.Db) => Promise<boolean>;
23
+ }
24
+ interface MigrationRecord {
25
+ version: number;
26
+ resource: string;
27
+ description?: string;
28
+ appliedAt: Date;
29
+ executionTime: number;
30
+ }
31
+ /**
32
+ * Define a migration
33
+ */
34
+ declare function defineMigration(migration: Migration): Migration;
35
+ /**
36
+ * Migration Runner
37
+ *
38
+ * Manages execution of migrations with tracking and rollback support.
39
+ */
40
+ declare class MigrationRunner {
41
+ private readonly collectionName;
42
+ private readonly db;
43
+ constructor(db: mongoose.mongo.Db);
44
+ /**
45
+ * Run all pending migrations
46
+ */
47
+ up(migrations: Migration[]): Promise<void>;
48
+ /**
49
+ * Rollback last migration
50
+ */
51
+ down(migrations: Migration[]): Promise<void>;
52
+ /**
53
+ * Rollback to specific version
54
+ */
55
+ downTo(migrations: Migration[], targetVersion: number): Promise<void>;
56
+ /**
57
+ * Get all applied migrations
58
+ */
59
+ getAppliedMigrations(): Promise<MigrationRecord[]>;
60
+ /**
61
+ * Get pending migrations
62
+ */
63
+ getPendingMigrations(migrations: Migration[]): Promise<Migration[]>;
64
+ /**
65
+ * Check if migrations are up to date
66
+ */
67
+ isUpToDate(migrations: Migration[]): Promise<boolean>;
68
+ /**
69
+ * Run a single migration
70
+ */
71
+ private runMigration;
72
+ /**
73
+ * Record a completed migration
74
+ */
75
+ private recordMigration;
76
+ /**
77
+ * Remove a migration record
78
+ */
79
+ private removeMigration;
80
+ }
81
+ /**
82
+ * Schema version definition for resources
83
+ */
84
+ interface SchemaVersion {
85
+ version: number;
86
+ migrations: Migration[];
87
+ }
88
+ /**
89
+ * Add versioning to resource definition
90
+ *
91
+ * @example
92
+ * export default defineResource({
93
+ * name: 'product',
94
+ * version: 2,
95
+ * migrations: [productV1ToV2Migration],
96
+ * // ... rest of resource definition
97
+ * });
98
+ */
99
+ declare function withSchemaVersion(version: number, migrations: Migration[]): SchemaVersion;
100
+ /**
101
+ * Global migration registry
102
+ */
103
+ declare class MigrationRegistry {
104
+ private migrations;
105
+ /**
106
+ * Register a migration
107
+ */
108
+ register(migration: Migration): void;
109
+ /**
110
+ * Register multiple migrations
111
+ */
112
+ registerMany(migrations: Migration[]): void;
113
+ /**
114
+ * Get all migrations for a resource
115
+ */
116
+ getForResource(resource: string): Migration[];
117
+ /**
118
+ * Get all migrations
119
+ */
120
+ getAll(): Migration[];
121
+ /**
122
+ * Get migration by resource and version
123
+ */
124
+ get(resource: string, version: number): Migration | undefined;
125
+ /**
126
+ * Clear all registrations
127
+ */
128
+ clear(): void;
129
+ }
130
+ /**
131
+ * Global migration registry instance
132
+ */
133
+ declare const migrationRegistry: MigrationRegistry;
134
+ /**
135
+ * Common migration helpers
136
+ */
137
+ declare const migrationHelpers: {
138
+ /**
139
+ * Rename a field across all documents
140
+ */
141
+ renameField: (collection: string, oldName: string, newName: string) => Migration;
142
+ /**
143
+ * Add a new field with default value
144
+ */
145
+ addField: (collection: string, fieldName: string, defaultValue: unknown) => Migration;
146
+ /**
147
+ * Remove a field
148
+ */
149
+ removeField: (collection: string, fieldName: string) => Migration;
150
+ /**
151
+ * Create an index
152
+ */
153
+ createIndex: (collection: string, fields: Record<string, 1 | -1>, options?: Record<string, unknown>) => Migration;
154
+ };
155
+ //#endregion
156
+ export { Migration, MigrationRecord, MigrationRegistry, MigrationRunner, SchemaVersion, defineMigration, migrationHelpers, migrationRegistry, withSchemaVersion };