commandkit 1.0.0-dev.20250802020924 → 1.0.0-dev.20250802113354

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.
@@ -1,6 +1,6 @@
1
1
  const require_chunk = require('../chunk-nOFOJqeH.js');
2
2
  const require_constants = require('../constants-B5_Ta7PR.js');
3
- const require_version = require('../version-C-sDC9iq.js');
3
+ const require_version = require('../version-DBZO51VK.js');
4
4
  const node_fs = require_chunk.__toESM(require("node:fs"));
5
5
  const node_path = require_chunk.__toESM(require("node:path"));
6
6
  const node_child_process = require_chunk.__toESM(require("node:child_process"));
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ require('./store-CyzliDXj.js');
37
37
  const require_helpers = require('./helpers-DfV6HlgI.js');
38
38
  require('./app-gCenKq8k.js');
39
39
  require('./ILogger-BMIMljYD.js');
40
- const require_version = require('./version-C-sDC9iq.js');
40
+ const require_version = require('./version-DBZO51VK.js');
41
41
  const require_feature_flags = require('./feature-flags-CNRFFY4k.js');
42
42
  const require_init = require('./init-Dc4Qbgpg.js');
43
43
  const discord_js = require_chunk.__toESM(require("discord.js"));
package/dist/kv/kv.d.ts CHANGED
@@ -3,6 +3,10 @@ import { SerializedValue } from "../serde-BUDI03pX.js";
3
3
  import { DatabaseSync } from "node:sqlite";
4
4
 
5
5
  //#region src/kv/kv.d.ts
6
+ /**
7
+ * Mathematical operators supported by the KV math method
8
+ */
9
+ type KvMathOperator = '+' | '-' | '*' | '/' | '^' | '%';
6
10
  /**
7
11
  * Configuration options for the KV store
8
12
  */
@@ -149,6 +153,36 @@ declare class KV implements Disposable, AsyncDisposable {
149
153
  * ```
150
154
  */
151
155
  setex(key: string, value: any, ttl: number): void;
156
+ /**
157
+ * Performs mathematical operations on numeric values in the KV store
158
+ *
159
+ * @param key - The key to perform math operation on (supports dot notation for nested properties)
160
+ * @param operator - The mathematical operator to apply
161
+ * @param value - The value to use in the operation
162
+ * @returns The updated value after the mathematical operation
163
+ * @throws Error if the existing value is not numeric or if the operation is invalid
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * // Initialize a counter
168
+ * kv.set('counter', 10);
169
+ *
170
+ * // Increment by 5
171
+ * const result1 = kv.math('counter', '+', 5); // 15
172
+ *
173
+ * // Multiply by 2
174
+ * const result2 = kv.math('counter', '*', 2); // 30
175
+ *
176
+ * // Use with bigint
177
+ * kv.set('big_counter', BigInt(1000));
178
+ * const result3 = kv.math('big_counter', '+', BigInt(500)); // 1500n
179
+ *
180
+ * // Use with dot notation
181
+ * kv.set('user:123', { score: 100, level: 5 });
182
+ * const result4 = kv.math('user:123.score', '+', 50); // 150
183
+ * ```
184
+ */
185
+ math(key: string, operator: KvMathOperator, value: number | bigint): number | bigint;
152
186
  /**
153
187
  * Sets expiration for an existing key
154
188
  *
@@ -359,5 +393,5 @@ declare class KV implements Disposable, AsyncDisposable {
359
393
  */
360
394
  declare function openKV(path?: string | Buffer | URL | DatabaseSync, options?: KvOptions): KV;
361
395
  //#endregion
362
- export { KV, KvOptions, type SerializedValue, openKV };
396
+ export { KV, KvMathOperator, KvOptions, type SerializedValue, openKV };
363
397
  //# sourceMappingURL=kv.d.ts.map
package/dist/kv/kv.js CHANGED
@@ -229,6 +229,70 @@ var KV = class KV {
229
229
  }
230
230
  }
231
231
  /**
232
+ * Performs mathematical operations on numeric values in the KV store
233
+ *
234
+ * @param key - The key to perform math operation on (supports dot notation for nested properties)
235
+ * @param operator - The mathematical operator to apply
236
+ * @param value - The value to use in the operation
237
+ * @returns The updated value after the mathematical operation
238
+ * @throws Error if the existing value is not numeric or if the operation is invalid
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * // Initialize a counter
243
+ * kv.set('counter', 10);
244
+ *
245
+ * // Increment by 5
246
+ * const result1 = kv.math('counter', '+', 5); // 15
247
+ *
248
+ * // Multiply by 2
249
+ * const result2 = kv.math('counter', '*', 2); // 30
250
+ *
251
+ * // Use with bigint
252
+ * kv.set('big_counter', BigInt(1000));
253
+ * const result3 = kv.math('big_counter', '+', BigInt(500)); // 1500n
254
+ *
255
+ * // Use with dot notation
256
+ * kv.set('user:123', { score: 100, level: 5 });
257
+ * const result4 = kv.math('user:123.score', '+', 50); // 150
258
+ * ```
259
+ */
260
+ math(key, operator, value) {
261
+ const existingValue = this.get(key);
262
+ if (existingValue === void 0) throw new Error(`Key '${key}' does not exist`);
263
+ if (typeof existingValue !== "number" && typeof existingValue !== "bigint") throw new Error(`Value at key '${key}' is not numeric. Expected number or bigint, got ${typeof existingValue}`);
264
+ const isBigIntOperation = typeof existingValue === "bigint" || typeof value === "bigint";
265
+ const existing = isBigIntOperation ? typeof existingValue === "bigint" ? existingValue : BigInt(existingValue) : existingValue;
266
+ const operand = isBigIntOperation ? typeof value === "bigint" ? value : BigInt(value) : value;
267
+ let result;
268
+ switch (operator) {
269
+ case "+":
270
+ result = existing + operand;
271
+ break;
272
+ case "-":
273
+ result = existing - operand;
274
+ break;
275
+ case "*":
276
+ result = existing * operand;
277
+ break;
278
+ case "/":
279
+ if (operand === 0 || operand === 0n) throw new Error("Division by zero");
280
+ result = existing / operand;
281
+ break;
282
+ case "^":
283
+ if (isBigIntOperation && operand < 0n) throw new Error("Exponentiation with negative exponent is not supported for bigint");
284
+ result = existing ** operand;
285
+ break;
286
+ case "%":
287
+ if (operand === 0 || operand === 0n) throw new Error("Modulo by zero");
288
+ result = existing % operand;
289
+ break;
290
+ default: throw new Error(`Invalid operator: ${operator}`);
291
+ }
292
+ this.set(key, result);
293
+ return result;
294
+ }
295
+ /**
232
296
  * Sets expiration for an existing key
233
297
  *
234
298
  * @param key - The key to set expiration for
package/dist/kv/kv.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"kv.js","names":[],"sources":["../../src/kv/kv.ts"],"sourcesContent":["import { DatabaseSync, StatementSync } from 'node:sqlite';\nimport { deserializer, serializer } from './serde';\nimport { getNestedValue, setNestedValue } from './dotprops';\n\nexport type { SerializedValue } from './serde';\n\n/**\n * Configuration options for the KV store\n */\nexport interface KvOptions {\n /** Enable Write-Ahead Logging for better performance and durability */\n enableWAL?: boolean;\n /** Namespace for the key-value store table */\n namespace?: string;\n}\n\n/**\n * A key-value store implementation using SQLite\n *\n * This class provides a simple, persistent key-value storage solution\n * with support for namespaces, automatic cleanup, iteration, expiration, and JSON serialization.\n *\n * @example\n * ```typescript\n * const kv = new KV('data.db');\n *\n * // Store any JSON-serializable data\n * kv.set('user:123', { name: 'John', age: 30 });\n * kv.set('counter', 42);\n * kv.set('active', true);\n * kv.set('dates', [new Date(), new Date()]);\n *\n * // Use dot notation for nested properties\n * kv.set('user:123.name', 'John');\n * kv.set('user:123.settings.theme', 'dark');\n *\n * // Retrieve data\n * const user = kv.get('user:123'); // { name: 'John', age: 30, settings: { theme: 'dark' } }\n * const name = kv.get('user:123.name'); // 'John'\n * ```\n */\nexport class KV implements Disposable, AsyncDisposable {\n private db: DatabaseSync;\n private statements: Record<string, StatementSync> = {};\n\n /**\n * Creates a new KV store instance\n *\n * @param path - Database file path, buffer, URL, or existing DatabaseSync instance\n * @param options - Configuration options for the KV store\n */\n public constructor(\n path: string | Buffer | URL | DatabaseSync,\n private options: KvOptions = {\n enableWAL: true,\n namespace: 'commandkit_kv',\n },\n ) {\n this.db =\n path instanceof DatabaseSync\n ? path\n : new DatabaseSync(path, { open: true });\n\n if (options.enableWAL) {\n this.db.exec(/* sql */ `PRAGMA journal_mode = WAL;`);\n }\n\n const namespace = this.options.namespace ?? 'commandkit_kv';\n\n this.db.exec(/* sql */ `\n CREATE TABLE IF NOT EXISTS ${namespace} (\n key TEXT PRIMARY KEY,\n value TEXT,\n expires_at INTEGER\n )\n `);\n\n this.statements = {\n get: this.db.prepare(\n /* sql */ `SELECT value, expires_at FROM ${namespace} WHERE key = ?`,\n ),\n set: this.db.prepare(\n /* sql */ `INSERT OR REPLACE INTO ${namespace} (key, value, expires_at) VALUES (?, ?, ?)`,\n ),\n setex: this.db.prepare(\n /* sql */ `INSERT OR REPLACE INTO ${namespace} (key, value, expires_at) VALUES (?, ?, ?)`,\n ),\n delete: this.db.prepare(\n /* sql */ `DELETE FROM ${namespace} WHERE key = ?`,\n ),\n has: this.db.prepare(\n /* sql */ `SELECT COUNT(*) FROM ${namespace} WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)`,\n ),\n keys: this.db.prepare(\n /* sql */ `SELECT key FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n values: this.db.prepare(\n /* sql */ `SELECT value FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n clear: this.db.prepare(/* sql */ `DELETE FROM ${namespace}`),\n count: this.db.prepare(\n /* sql */ `SELECT COUNT(*) FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n all: this.db.prepare(\n /* sql */ `SELECT key, value FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n expire: this.db.prepare(\n /* sql */ `UPDATE ${namespace} SET expires_at = ? WHERE key = ?`,\n ),\n ttl: this.db.prepare(\n /* sql */ `SELECT expires_at FROM ${namespace} WHERE key = ?`,\n ),\n namespaces: this.db.prepare(\n /* sql */ `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,\n ),\n begin: this.db.prepare(/* sql */ `BEGIN TRANSACTION`),\n commit: this.db.prepare(/* sql */ `COMMIT`),\n rollback: this.db.prepare(/* sql */ `ROLLBACK`),\n };\n }\n\n /**\n * Gets the current timestamp in milliseconds\n */\n private getCurrentTime(): number {\n return Date.now();\n }\n\n /**\n * Checks if the database connection is open\n *\n * @returns `true` if the database is open, `false` otherwise\n */\n public isOpen(): boolean {\n return this.db.isOpen;\n }\n\n /**\n * Gets the underlying SQLite database instance\n *\n * @returns The DatabaseSync instance\n */\n public getDatabase(): DatabaseSync {\n return this.db;\n }\n\n /**\n * Closes the database connection\n */\n public close(): void {\n if (this.db.isOpen) this.db.close();\n }\n\n /**\n * Disposable implementation - closes the database when disposed\n */\n public [Symbol.dispose]() {\n this.close();\n }\n\n /**\n * AsyncDisposable implementation - closes the database when disposed\n */\n public async [Symbol.asyncDispose]() {\n this.close();\n }\n\n /**\n * Retrieves a value by key\n *\n * @param key - The key to retrieve (supports dot notation for nested properties)\n * @returns The value associated with the key, or `undefined` if not found or expired\n *\n * @example\n * ```typescript\n * // Store an object\n * kv.set('user:123', { name: 'John', age: 30, settings: { theme: 'dark' } });\n *\n * // Get the entire object\n * const user = kv.get('user:123');\n * // { name: 'John', age: 30, settings: { theme: 'dark' } }\n *\n * // Get nested properties using dot notation\n * const name = kv.get('user:123.name'); // 'John'\n * const theme = kv.get('user:123.settings.theme'); // 'dark'\n * ```\n */\n public get<T = any>(key: string): T | undefined {\n const result = this.statements.get.get(key);\n\n if (!result) return undefined;\n\n // Check if the key has expired\n if (\n result.expires_at &&\n Number(result.expires_at) <= this.getCurrentTime()\n ) {\n this.delete(key);\n return undefined;\n }\n\n const serialized = JSON.parse(result.value as string);\n const deserialized = deserializer(serialized);\n\n // Handle dot notation for nested properties\n if (key.includes('.')) {\n return getNestedValue(deserialized, key.split('.').slice(1).join('.'));\n }\n\n return deserialized;\n }\n\n /**\n * Sets a key-value pair\n *\n * @param key - The key to set (supports dot notation for nested properties)\n * @param value - The value to associate with the key (any JSON-serializable type)\n *\n * @example\n * ```typescript\n * // Store primitive values\n * kv.set('counter', 42);\n * kv.set('active', true);\n * kv.set('name', 'John');\n *\n * // Store objects\n * kv.set('user:123', { name: 'John', age: 30 });\n *\n * // Store arrays\n * kv.set('tags', ['javascript', 'typescript', 'sqlite']);\n *\n * // Store dates\n * kv.set('created', new Date());\n *\n * // Store maps and sets\n * kv.set('permissions', new Map([['admin', true], ['user', false]]));\n * kv.set('unique_ids', new Set([1, 2, 3, 4, 5]));\n *\n * // Use dot notation for nested properties\n * kv.set('user:123.settings.theme', 'dark');\n * kv.set('user:123.settings.notifications', true);\n * ```\n */\n public set(key: string, value: any): void {\n let serializedValue: string;\n\n if (key.includes('.')) {\n // Handle dot notation for nested properties\n const [baseKey, ...pathParts] = key.split('.');\n const path = pathParts.join('.');\n\n // Get existing value or create new object\n const existing = this.get(baseKey) || {};\n setNestedValue(existing, path, value);\n\n const serialized = serializer(existing);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.set.run(baseKey, serializedValue, null);\n } else {\n const serialized = serializer(value);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.set.run(key, serializedValue, null);\n }\n }\n\n /**\n * Sets a key-value pair with expiration\n *\n * @param key - The key to set (supports dot notation for nested properties)\n * @param value - The value to associate with the key (any JSON-serializable type)\n * @param ttl - Time to live in milliseconds\n *\n * @example\n * ```typescript\n * // Set with 1 hour expiration\n * kv.setex('session:123', { userId: 123, token: 'abc123' }, 60 * 60 * 1000);\n *\n * // Set with 5 minutes expiration\n * kv.setex('temp:data', { cached: true, timestamp: Date.now() }, 5 * 60 * 1000);\n *\n * // Use dot notation with expiration\n * kv.setex('user:123.temp_settings', { theme: 'light' }, 30 * 60 * 1000);\n * ```\n */\n public setex(key: string, value: any, ttl: number): void {\n const expiresAt = this.getCurrentTime() + ttl;\n let serializedValue: string;\n\n if (key.includes('.')) {\n // Handle dot notation for nested properties\n const [baseKey, ...pathParts] = key.split('.');\n const path = pathParts.join('.');\n\n // Get existing value or create new object\n const existing = this.get(baseKey) || {};\n setNestedValue(existing, path, value);\n\n const serialized = serializer(existing);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.setex.run(baseKey, serializedValue, expiresAt);\n } else {\n const serialized = serializer(value);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.setex.run(key, serializedValue, expiresAt);\n }\n }\n\n /**\n * Sets expiration for an existing key\n *\n * @param key - The key to set expiration for\n * @param ttl - Time to live in milliseconds\n * @returns `true` if the key exists and expiration was set, `false` otherwise\n *\n * @example\n * ```typescript\n * kv.set('user:123', { name: 'John', age: 30 });\n *\n * // Set 30 minute expiration\n * if (kv.expire('user:123', 30 * 60 * 1000)) {\n * console.log('Expiration set successfully');\n * }\n * ```\n */\n public expire(key: string, ttl: number): boolean {\n if (!this.has(key)) return false;\n\n const expiresAt = this.getCurrentTime() + ttl;\n this.statements.expire.run(expiresAt, key);\n return true;\n }\n\n /**\n * Gets the time to live for a key\n *\n * @param key - The key to check\n * @returns Time to live in milliseconds, or `-1` if the key doesn't exist, or `-2` if the key has no expiration\n *\n * @example\n * ```typescript\n * const ttl = kv.ttl('user:123');\n * if (ttl > 0) {\n * console.log(`Key expires in ${ttl}ms`);\n * } else if (ttl === -2) {\n * console.log('Key has no expiration');\n * } else {\n * console.log('Key does not exist');\n * }\n * ```\n */\n public ttl(key: string): number {\n const result = this.statements.ttl.get(key);\n\n if (!result) return -1; // Key doesn't exist\n\n if (!result.expires_at) return -2; // No expiration\n\n const remaining = Number(result.expires_at) - this.getCurrentTime();\n return remaining > 0 ? remaining : -1; // Expired or doesn't exist\n }\n\n /**\n * Deletes a key-value pair\n *\n * @param key - The key to delete\n *\n * @example\n * ```typescript\n * kv.delete('user:123');\n * kv.delete('user:123.settings.theme'); // Delete nested property\n * ```\n */\n public delete(key: string): void {\n this.statements.delete.run(key);\n }\n\n /**\n * Checks if a key exists and is not expired\n *\n * @param key - The key to check\n * @returns `true` if the key exists and is not expired, `false` otherwise\n *\n * @example\n * ```typescript\n * if (kv.has('user:123')) {\n * console.log('User exists and is not expired');\n * }\n *\n * if (kv.has('user:123.settings.theme')) {\n * console.log('Theme setting exists');\n * }\n * ```\n */\n public has(key: string): boolean {\n const result = this.statements.has.get(key, this.getCurrentTime());\n\n return (\n result?.count !== undefined &&\n result.count !== null &&\n Number(result.count) > 0\n );\n }\n\n /**\n * Gets all keys in the current namespace (excluding expired keys)\n *\n * @returns Array of all non-expired keys\n *\n * @example\n * ```typescript\n * const keys = kv.keys();\n * console.log('All keys:', keys);\n * ```\n */\n public keys(): string[] {\n const result = this.statements.keys.all(this.getCurrentTime());\n\n return result.map((row) => row.key as string);\n }\n\n /**\n * Gets all values in the current namespace (excluding expired keys)\n *\n * @returns Array of all non-expired values\n *\n * @example\n * ```typescript\n * const values = kv.values();\n * console.log('All values:', values);\n * ```\n */\n public values(): any[] {\n const result = this.statements.values.all(this.getCurrentTime());\n\n return result.map((row) => {\n const serialized = JSON.parse(row.value as string);\n return deserializer(serialized);\n });\n }\n\n /**\n * Gets the total number of key-value pairs in the current namespace (excluding expired keys)\n *\n * @returns The count of non-expired key-value pairs\n *\n * @example\n * ```typescript\n * const count = kv.count();\n * console.log(`Total entries: ${count}`);\n * ```\n */\n public count(): number {\n const result = this.statements.count.get(this.getCurrentTime());\n\n return Number(result?.count ?? 0);\n }\n\n /**\n * Removes all key-value pairs from the current namespace\n *\n * @example\n * ```typescript\n * kv.clear(); // Removes all entries in current namespace\n * ```\n */\n public clear(): void {\n this.statements.clear.run();\n }\n\n /**\n * Gets all key-value pairs as an object (excluding expired keys)\n *\n * @returns Object with all non-expired key-value pairs\n *\n * @example\n * ```typescript\n * const all = kv.all();\n * console.log('All entries:', all);\n * // Output: { 'key1': value1, 'key2': value2 }\n * ```\n */\n public all(): Record<string, any> {\n const result = this.statements.all.all(this.getCurrentTime());\n\n return Object.fromEntries(\n result.map((row) => {\n const serialized = JSON.parse(row.value as string);\n return [row.key as string, deserializer(serialized)];\n }),\n );\n }\n\n /**\n * Gets all available namespaces (tables) in the database\n *\n * @returns Array of namespace names\n *\n * @example\n * ```typescript\n * const namespaces = kv.namespaces();\n * console.log('Available namespaces:', namespaces);\n * ```\n */\n public namespaces(): string[] {\n const result = this.statements.namespaces.all();\n\n return result.map((row) => row.name as string);\n }\n\n /**\n * Gets the current namespace name\n *\n * @returns The current namespace string\n */\n public getCurrentNamespace(): string {\n return this.options.namespace ?? 'commandkit_kv';\n }\n\n /**\n * Creates a new KV instance with a different namespace\n *\n * @param namespace - The namespace to use for the new instance\n * @returns A new KV instance with the specified namespace\n *\n * @example\n * ```typescript\n * const userKv = kv.namespace('users');\n * const configKv = kv.namespace('config');\n *\n * userKv.set('123', { name: 'John', age: 30 });\n * configKv.set('theme', 'dark');\n * ```\n */\n public namespace(namespace: string): KV {\n return new KV(this.db, {\n enableWAL: this.options.enableWAL,\n namespace,\n });\n }\n\n /**\n * Iterator implementation for iterating over all non-expired key-value pairs\n *\n * @returns Iterator yielding [key, value] tuples\n *\n * @example\n * ```typescript\n * for (const [key, value] of kv) {\n * console.log(`${key}:`, value);\n * }\n *\n * // Or using spread operator\n * const entries = [...kv];\n * ```\n */\n public *[Symbol.iterator](): Iterator<[string, any]> {\n const result = this.statements.all.iterate(this.getCurrentTime());\n\n for (const row of result) {\n const serialized = JSON.parse(row.value as string);\n yield [row.key as string, deserializer(serialized)];\n }\n }\n\n /**\n * Executes a function within a transaction\n *\n * @param fn - Function to execute within the transaction (can be async)\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * // Synchronous transaction\n * kv.transaction(() => {\n * kv.set('user:123', { name: 'John', age: 30 });\n * kv.set('user:456', { name: 'Jane', age: 25 });\n * // If any operation fails, all changes are rolled back\n * });\n *\n * // Async transaction\n * await kv.transaction(async () => {\n * kv.set('user:123', { name: 'John', age: 30 });\n * await someAsyncOperation();\n * kv.set('user:456', { name: 'Jane', age: 25 });\n * // If any operation fails, all changes are rolled back\n * });\n * ```\n */\n public async transaction<T>(fn: () => T | Promise<T>): Promise<T> {\n try {\n // Begin transaction\n this.statements.begin.run();\n\n // Execute the function\n const result = await fn();\n\n // Commit transaction\n this.statements.commit.run();\n\n return result;\n } catch (error) {\n // Rollback transaction on error\n this.statements.rollback.run();\n throw error;\n }\n }\n}\n\n/**\n * Opens a new KV instance\n *\n * @param path - Database file path, buffer, URL, or existing DatabaseSync instance\n * @param options - Configuration options for the KV store\n * @returns A new KV instance\n */\nexport function openKV(\n path: string | Buffer | URL | DatabaseSync = 'commandkit_kv.db',\n options: KvOptions = { enableWAL: true, namespace: 'commandkit_kv' },\n): KV {\n return new KV(path, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,KAAb,MAAa,GAA0C;CACrD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AM,IAAI,MAAgB;AAClD,UAAO,CAAC,IAAI,KAAe,2BAAa,WAAW,AAAC;EACrD,EAAC,CACH;CACH;;;;;;;;;;;;CAaA,AAAO,aAAuB;EAC5B,MAAM,SAAS,KAAK,WAAW,WAAW,KAAK;AAE/C,SAAO,OAAO,IAAI,CAAC,QAAQ,IAAI,KAAe;CAChD;;;;;;CAOA,AAAO,sBAA8B;AACnC,SAAO,KAAK,QAAQ,aAAa;CACnC;;;;;;;;;;;;;;;;CAiBA,AAAO,UAAU,WAAuB;AACtC,SAAO,IAAI,GAAG,KAAK,IAAI;GACrB,WAAW,KAAK,QAAQ;GACxB;EACD;CACH;;;;;;;;;;;;;;;;CAiBA,EAAS,OAAO,YAAqC;EACnD,MAAM,SAAS,KAAK,WAAW,IAAI,QAAQ,KAAK,gBAAgB,CAAC;AAEjE,OAAK,MAAM,OAAO,QAAQ;GACxB,MAAM,aAAa,KAAK,MAAM,IAAI,MAAgB;GAClD,MAAM,CAAC,IAAI,KAAe,2BAAa,WAAW,AAAC;EACrD;CACF;;;;;;;;;;;;;;;;;;;;;;;;;CA0BA,MAAa,YAAe,IAAsC;AAChE,MAAI;GAEF,KAAK,WAAW,MAAM,KAAK;GAG3B,MAAM,SAAS,MAAM,IAAI;GAGzB,KAAK,WAAW,OAAO,KAAK;AAE5B,UAAO;EACR,SAAQ,OAAO;GAEd,KAAK,WAAW,SAAS,KAAK;AAC9B,SAAM;EACR;CACF;AACF;;;;;;;;AASA,SAAgB,OAChB,OAA6C,oBAC7C,UAAqB;CAAE,WAAW;CAAM,WAAW;AAAiB,GAC/D;AACH,QAAO,IAAI,GAAG,MAAM;AACtB"}
1
+ {"version":3,"file":"kv.js","names":[],"sources":["../../src/kv/kv.ts"],"sourcesContent":["import { DatabaseSync, StatementSync } from 'node:sqlite';\nimport { deserializer, serializer } from './serde';\nimport { getNestedValue, setNestedValue } from './dotprops';\n\nexport type { SerializedValue } from './serde';\n\n/**\n * Mathematical operators supported by the KV math method\n */\nexport type KvMathOperator = '+' | '-' | '*' | '/' | '^' | '%';\n\n/**\n * Configuration options for the KV store\n */\nexport interface KvOptions {\n /** Enable Write-Ahead Logging for better performance and durability */\n enableWAL?: boolean;\n /** Namespace for the key-value store table */\n namespace?: string;\n}\n\n/**\n * A key-value store implementation using SQLite\n *\n * This class provides a simple, persistent key-value storage solution\n * with support for namespaces, automatic cleanup, iteration, expiration, and JSON serialization.\n *\n * @example\n * ```typescript\n * const kv = new KV('data.db');\n *\n * // Store any JSON-serializable data\n * kv.set('user:123', { name: 'John', age: 30 });\n * kv.set('counter', 42);\n * kv.set('active', true);\n * kv.set('dates', [new Date(), new Date()]);\n *\n * // Use dot notation for nested properties\n * kv.set('user:123.name', 'John');\n * kv.set('user:123.settings.theme', 'dark');\n *\n * // Retrieve data\n * const user = kv.get('user:123'); // { name: 'John', age: 30, settings: { theme: 'dark' } }\n * const name = kv.get('user:123.name'); // 'John'\n * ```\n */\nexport class KV implements Disposable, AsyncDisposable {\n private db: DatabaseSync;\n private statements: Record<string, StatementSync> = {};\n\n /**\n * Creates a new KV store instance\n *\n * @param path - Database file path, buffer, URL, or existing DatabaseSync instance\n * @param options - Configuration options for the KV store\n */\n public constructor(\n path: string | Buffer | URL | DatabaseSync,\n private options: KvOptions = {\n enableWAL: true,\n namespace: 'commandkit_kv',\n },\n ) {\n this.db =\n path instanceof DatabaseSync\n ? path\n : new DatabaseSync(path, { open: true });\n\n if (options.enableWAL) {\n this.db.exec(/* sql */ `PRAGMA journal_mode = WAL;`);\n }\n\n const namespace = this.options.namespace ?? 'commandkit_kv';\n\n this.db.exec(/* sql */ `\n CREATE TABLE IF NOT EXISTS ${namespace} (\n key TEXT PRIMARY KEY,\n value TEXT,\n expires_at INTEGER\n )\n `);\n\n this.statements = {\n get: this.db.prepare(\n /* sql */ `SELECT value, expires_at FROM ${namespace} WHERE key = ?`,\n ),\n set: this.db.prepare(\n /* sql */ `INSERT OR REPLACE INTO ${namespace} (key, value, expires_at) VALUES (?, ?, ?)`,\n ),\n setex: this.db.prepare(\n /* sql */ `INSERT OR REPLACE INTO ${namespace} (key, value, expires_at) VALUES (?, ?, ?)`,\n ),\n delete: this.db.prepare(\n /* sql */ `DELETE FROM ${namespace} WHERE key = ?`,\n ),\n has: this.db.prepare(\n /* sql */ `SELECT COUNT(*) FROM ${namespace} WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)`,\n ),\n keys: this.db.prepare(\n /* sql */ `SELECT key FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n values: this.db.prepare(\n /* sql */ `SELECT value FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n clear: this.db.prepare(/* sql */ `DELETE FROM ${namespace}`),\n count: this.db.prepare(\n /* sql */ `SELECT COUNT(*) FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n all: this.db.prepare(\n /* sql */ `SELECT key, value FROM ${namespace} WHERE expires_at IS NULL OR expires_at > ?`,\n ),\n expire: this.db.prepare(\n /* sql */ `UPDATE ${namespace} SET expires_at = ? WHERE key = ?`,\n ),\n ttl: this.db.prepare(\n /* sql */ `SELECT expires_at FROM ${namespace} WHERE key = ?`,\n ),\n namespaces: this.db.prepare(\n /* sql */ `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,\n ),\n begin: this.db.prepare(/* sql */ `BEGIN TRANSACTION`),\n commit: this.db.prepare(/* sql */ `COMMIT`),\n rollback: this.db.prepare(/* sql */ `ROLLBACK`),\n };\n }\n\n /**\n * Gets the current timestamp in milliseconds\n */\n private getCurrentTime(): number {\n return Date.now();\n }\n\n /**\n * Checks if the database connection is open\n *\n * @returns `true` if the database is open, `false` otherwise\n */\n public isOpen(): boolean {\n return this.db.isOpen;\n }\n\n /**\n * Gets the underlying SQLite database instance\n *\n * @returns The DatabaseSync instance\n */\n public getDatabase(): DatabaseSync {\n return this.db;\n }\n\n /**\n * Closes the database connection\n */\n public close(): void {\n if (this.db.isOpen) this.db.close();\n }\n\n /**\n * Disposable implementation - closes the database when disposed\n */\n public [Symbol.dispose]() {\n this.close();\n }\n\n /**\n * AsyncDisposable implementation - closes the database when disposed\n */\n public async [Symbol.asyncDispose]() {\n this.close();\n }\n\n /**\n * Retrieves a value by key\n *\n * @param key - The key to retrieve (supports dot notation for nested properties)\n * @returns The value associated with the key, or `undefined` if not found or expired\n *\n * @example\n * ```typescript\n * // Store an object\n * kv.set('user:123', { name: 'John', age: 30, settings: { theme: 'dark' } });\n *\n * // Get the entire object\n * const user = kv.get('user:123');\n * // { name: 'John', age: 30, settings: { theme: 'dark' } }\n *\n * // Get nested properties using dot notation\n * const name = kv.get('user:123.name'); // 'John'\n * const theme = kv.get('user:123.settings.theme'); // 'dark'\n * ```\n */\n public get<T = any>(key: string): T | undefined {\n const result = this.statements.get.get(key);\n\n if (!result) return undefined;\n\n // Check if the key has expired\n if (\n result.expires_at &&\n Number(result.expires_at) <= this.getCurrentTime()\n ) {\n this.delete(key);\n return undefined;\n }\n\n const serialized = JSON.parse(result.value as string);\n const deserialized = deserializer(serialized);\n\n // Handle dot notation for nested properties\n if (key.includes('.')) {\n return getNestedValue(deserialized, key.split('.').slice(1).join('.'));\n }\n\n return deserialized;\n }\n\n /**\n * Sets a key-value pair\n *\n * @param key - The key to set (supports dot notation for nested properties)\n * @param value - The value to associate with the key (any JSON-serializable type)\n *\n * @example\n * ```typescript\n * // Store primitive values\n * kv.set('counter', 42);\n * kv.set('active', true);\n * kv.set('name', 'John');\n *\n * // Store objects\n * kv.set('user:123', { name: 'John', age: 30 });\n *\n * // Store arrays\n * kv.set('tags', ['javascript', 'typescript', 'sqlite']);\n *\n * // Store dates\n * kv.set('created', new Date());\n *\n * // Store maps and sets\n * kv.set('permissions', new Map([['admin', true], ['user', false]]));\n * kv.set('unique_ids', new Set([1, 2, 3, 4, 5]));\n *\n * // Use dot notation for nested properties\n * kv.set('user:123.settings.theme', 'dark');\n * kv.set('user:123.settings.notifications', true);\n * ```\n */\n public set(key: string, value: any): void {\n let serializedValue: string;\n\n if (key.includes('.')) {\n // Handle dot notation for nested properties\n const [baseKey, ...pathParts] = key.split('.');\n const path = pathParts.join('.');\n\n // Get existing value or create new object\n const existing = this.get(baseKey) || {};\n setNestedValue(existing, path, value);\n\n const serialized = serializer(existing);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.set.run(baseKey, serializedValue, null);\n } else {\n const serialized = serializer(value);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.set.run(key, serializedValue, null);\n }\n }\n\n /**\n * Sets a key-value pair with expiration\n *\n * @param key - The key to set (supports dot notation for nested properties)\n * @param value - The value to associate with the key (any JSON-serializable type)\n * @param ttl - Time to live in milliseconds\n *\n * @example\n * ```typescript\n * // Set with 1 hour expiration\n * kv.setex('session:123', { userId: 123, token: 'abc123' }, 60 * 60 * 1000);\n *\n * // Set with 5 minutes expiration\n * kv.setex('temp:data', { cached: true, timestamp: Date.now() }, 5 * 60 * 1000);\n *\n * // Use dot notation with expiration\n * kv.setex('user:123.temp_settings', { theme: 'light' }, 30 * 60 * 1000);\n * ```\n */\n public setex(key: string, value: any, ttl: number): void {\n const expiresAt = this.getCurrentTime() + ttl;\n let serializedValue: string;\n\n if (key.includes('.')) {\n // Handle dot notation for nested properties\n const [baseKey, ...pathParts] = key.split('.');\n const path = pathParts.join('.');\n\n // Get existing value or create new object\n const existing = this.get(baseKey) || {};\n setNestedValue(existing, path, value);\n\n const serialized = serializer(existing);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.setex.run(baseKey, serializedValue, expiresAt);\n } else {\n const serialized = serializer(value);\n serializedValue = JSON.stringify(serialized);\n\n this.statements.setex.run(key, serializedValue, expiresAt);\n }\n }\n\n /**\n * Performs mathematical operations on numeric values in the KV store\n *\n * @param key - The key to perform math operation on (supports dot notation for nested properties)\n * @param operator - The mathematical operator to apply\n * @param value - The value to use in the operation\n * @returns The updated value after the mathematical operation\n * @throws Error if the existing value is not numeric or if the operation is invalid\n *\n * @example\n * ```typescript\n * // Initialize a counter\n * kv.set('counter', 10);\n *\n * // Increment by 5\n * const result1 = kv.math('counter', '+', 5); // 15\n *\n * // Multiply by 2\n * const result2 = kv.math('counter', '*', 2); // 30\n *\n * // Use with bigint\n * kv.set('big_counter', BigInt(1000));\n * const result3 = kv.math('big_counter', '+', BigInt(500)); // 1500n\n *\n * // Use with dot notation\n * kv.set('user:123', { score: 100, level: 5 });\n * const result4 = kv.math('user:123.score', '+', 50); // 150\n * ```\n */\n public math(\n key: string,\n operator: KvMathOperator,\n value: number | bigint,\n ): number | bigint {\n const existingValue = this.get(key);\n\n if (existingValue === undefined) {\n throw new Error(`Key '${key}' does not exist`);\n }\n\n if (\n typeof existingValue !== 'number' &&\n typeof existingValue !== 'bigint'\n ) {\n throw new Error(\n `Value at key '${key}' is not numeric. Expected number or bigint, got ${typeof existingValue}`,\n );\n }\n\n // Handle mixed number/bigint operations by converting to bigint\n const isBigIntOperation =\n typeof existingValue === 'bigint' || typeof value === 'bigint';\n\n const existing = isBigIntOperation\n ? typeof existingValue === 'bigint'\n ? existingValue\n : BigInt(existingValue)\n : (existingValue as number);\n const operand = isBigIntOperation\n ? typeof value === 'bigint'\n ? value\n : BigInt(value)\n : (value as number);\n\n let result: number | bigint;\n\n switch (operator) {\n case '+':\n result = (existing as any) + (operand as any);\n break;\n case '-':\n result = (existing as any) - (operand as any);\n break;\n case '*':\n result = (existing as any) * (operand as any);\n break;\n case '/':\n if (operand === 0 || operand === 0n) {\n throw new Error('Division by zero');\n }\n result = (existing as any) / (operand as any);\n break;\n case '^':\n if (isBigIntOperation && operand < 0n) {\n throw new Error(\n 'Exponentiation with negative exponent is not supported for bigint',\n );\n }\n result = (existing as any) ** (operand as any);\n break;\n case '%':\n if (operand === 0 || operand === 0n) {\n throw new Error('Modulo by zero');\n }\n result = (existing as any) % (operand as any);\n break;\n default:\n throw new Error(`Invalid operator: ${operator}`);\n }\n\n // Update the value in the store\n this.set(key, result);\n\n return result;\n }\n\n /**\n * Sets expiration for an existing key\n *\n * @param key - The key to set expiration for\n * @param ttl - Time to live in milliseconds\n * @returns `true` if the key exists and expiration was set, `false` otherwise\n *\n * @example\n * ```typescript\n * kv.set('user:123', { name: 'John', age: 30 });\n *\n * // Set 30 minute expiration\n * if (kv.expire('user:123', 30 * 60 * 1000)) {\n * console.log('Expiration set successfully');\n * }\n * ```\n */\n public expire(key: string, ttl: number): boolean {\n if (!this.has(key)) return false;\n\n const expiresAt = this.getCurrentTime() + ttl;\n this.statements.expire.run(expiresAt, key);\n return true;\n }\n\n /**\n * Gets the time to live for a key\n *\n * @param key - The key to check\n * @returns Time to live in milliseconds, or `-1` if the key doesn't exist, or `-2` if the key has no expiration\n *\n * @example\n * ```typescript\n * const ttl = kv.ttl('user:123');\n * if (ttl > 0) {\n * console.log(`Key expires in ${ttl}ms`);\n * } else if (ttl === -2) {\n * console.log('Key has no expiration');\n * } else {\n * console.log('Key does not exist');\n * }\n * ```\n */\n public ttl(key: string): number {\n const result = this.statements.ttl.get(key);\n\n if (!result) return -1; // Key doesn't exist\n\n if (!result.expires_at) return -2; // No expiration\n\n const remaining = Number(result.expires_at) - this.getCurrentTime();\n return remaining > 0 ? remaining : -1; // Expired or doesn't exist\n }\n\n /**\n * Deletes a key-value pair\n *\n * @param key - The key to delete\n *\n * @example\n * ```typescript\n * kv.delete('user:123');\n * kv.delete('user:123.settings.theme'); // Delete nested property\n * ```\n */\n public delete(key: string): void {\n this.statements.delete.run(key);\n }\n\n /**\n * Checks if a key exists and is not expired\n *\n * @param key - The key to check\n * @returns `true` if the key exists and is not expired, `false` otherwise\n *\n * @example\n * ```typescript\n * if (kv.has('user:123')) {\n * console.log('User exists and is not expired');\n * }\n *\n * if (kv.has('user:123.settings.theme')) {\n * console.log('Theme setting exists');\n * }\n * ```\n */\n public has(key: string): boolean {\n const result = this.statements.has.get(key, this.getCurrentTime());\n\n return (\n result?.count !== undefined &&\n result.count !== null &&\n Number(result.count) > 0\n );\n }\n\n /**\n * Gets all keys in the current namespace (excluding expired keys)\n *\n * @returns Array of all non-expired keys\n *\n * @example\n * ```typescript\n * const keys = kv.keys();\n * console.log('All keys:', keys);\n * ```\n */\n public keys(): string[] {\n const result = this.statements.keys.all(this.getCurrentTime());\n\n return result.map((row) => row.key as string);\n }\n\n /**\n * Gets all values in the current namespace (excluding expired keys)\n *\n * @returns Array of all non-expired values\n *\n * @example\n * ```typescript\n * const values = kv.values();\n * console.log('All values:', values);\n * ```\n */\n public values(): any[] {\n const result = this.statements.values.all(this.getCurrentTime());\n\n return result.map((row) => {\n const serialized = JSON.parse(row.value as string);\n return deserializer(serialized);\n });\n }\n\n /**\n * Gets the total number of key-value pairs in the current namespace (excluding expired keys)\n *\n * @returns The count of non-expired key-value pairs\n *\n * @example\n * ```typescript\n * const count = kv.count();\n * console.log(`Total entries: ${count}`);\n * ```\n */\n public count(): number {\n const result = this.statements.count.get(this.getCurrentTime());\n\n return Number(result?.count ?? 0);\n }\n\n /**\n * Removes all key-value pairs from the current namespace\n *\n * @example\n * ```typescript\n * kv.clear(); // Removes all entries in current namespace\n * ```\n */\n public clear(): void {\n this.statements.clear.run();\n }\n\n /**\n * Gets all key-value pairs as an object (excluding expired keys)\n *\n * @returns Object with all non-expired key-value pairs\n *\n * @example\n * ```typescript\n * const all = kv.all();\n * console.log('All entries:', all);\n * // Output: { 'key1': value1, 'key2': value2 }\n * ```\n */\n public all(): Record<string, any> {\n const result = this.statements.all.all(this.getCurrentTime());\n\n return Object.fromEntries(\n result.map((row) => {\n const serialized = JSON.parse(row.value as string);\n return [row.key as string, deserializer(serialized)];\n }),\n );\n }\n\n /**\n * Gets all available namespaces (tables) in the database\n *\n * @returns Array of namespace names\n *\n * @example\n * ```typescript\n * const namespaces = kv.namespaces();\n * console.log('Available namespaces:', namespaces);\n * ```\n */\n public namespaces(): string[] {\n const result = this.statements.namespaces.all();\n\n return result.map((row) => row.name as string);\n }\n\n /**\n * Gets the current namespace name\n *\n * @returns The current namespace string\n */\n public getCurrentNamespace(): string {\n return this.options.namespace ?? 'commandkit_kv';\n }\n\n /**\n * Creates a new KV instance with a different namespace\n *\n * @param namespace - The namespace to use for the new instance\n * @returns A new KV instance with the specified namespace\n *\n * @example\n * ```typescript\n * const userKv = kv.namespace('users');\n * const configKv = kv.namespace('config');\n *\n * userKv.set('123', { name: 'John', age: 30 });\n * configKv.set('theme', 'dark');\n * ```\n */\n public namespace(namespace: string): KV {\n return new KV(this.db, {\n enableWAL: this.options.enableWAL,\n namespace,\n });\n }\n\n /**\n * Iterator implementation for iterating over all non-expired key-value pairs\n *\n * @returns Iterator yielding [key, value] tuples\n *\n * @example\n * ```typescript\n * for (const [key, value] of kv) {\n * console.log(`${key}:`, value);\n * }\n *\n * // Or using spread operator\n * const entries = [...kv];\n * ```\n */\n public *[Symbol.iterator](): Iterator<[string, any]> {\n const result = this.statements.all.iterate(this.getCurrentTime());\n\n for (const row of result) {\n const serialized = JSON.parse(row.value as string);\n yield [row.key as string, deserializer(serialized)];\n }\n }\n\n /**\n * Executes a function within a transaction\n *\n * @param fn - Function to execute within the transaction (can be async)\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * // Synchronous transaction\n * kv.transaction(() => {\n * kv.set('user:123', { name: 'John', age: 30 });\n * kv.set('user:456', { name: 'Jane', age: 25 });\n * // If any operation fails, all changes are rolled back\n * });\n *\n * // Async transaction\n * await kv.transaction(async () => {\n * kv.set('user:123', { name: 'John', age: 30 });\n * await someAsyncOperation();\n * kv.set('user:456', { name: 'Jane', age: 25 });\n * // If any operation fails, all changes are rolled back\n * });\n * ```\n */\n public async transaction<T>(fn: () => T | Promise<T>): Promise<T> {\n try {\n // Begin transaction\n this.statements.begin.run();\n\n // Execute the function\n const result = await fn();\n\n // Commit transaction\n this.statements.commit.run();\n\n return result;\n } catch (error) {\n // Rollback transaction on error\n this.statements.rollback.run();\n throw error;\n }\n }\n}\n\n/**\n * Opens a new KV instance\n *\n * @param path - Database file path, buffer, URL, or existing DatabaseSync instance\n * @param options - Configuration options for the KV store\n * @returns A new KV instance\n */\nexport function openKV(\n path: string | Buffer | URL | DatabaseSync = 'commandkit_kv.db',\n options: KvOptions = { enableWAL: true, namespace: 'commandkit_kv' },\n): KV {\n return new KV(path, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAa,KAAb,MAAa,GAA0C;CACrD,AAAQ;CACR,AAAQ,aAA4C,CAAE;;;;;;;CAQtD,AAAO,YACP,MACQ,UAAqB;EAC3B,WAAW;EACX,WAAW;CACZ,GACD;EAJQ;EAKN,KAAK,KACL,gBAAgB,2BAChB,OACA,IAAI,yBAAa,MAAM,EAAE,MAAM,KAAM;AAErC,MAAI,QAAQ,WACV,KAAK,GAAG,KAAc,CAAC,0BAA0B,CAAC,CAAC;EAGrD,MAAM,YAAY,KAAK,QAAQ,aAAa;EAE5C,KAAK,GAAG,KAAc,CAAC;iCACM,EAAE,UAAU;;;;;IAKzC,CAAC,CAAC;EAEF,KAAK,aAAa;GAChB,KAAK,KAAK,GAAG,QACF,CAAC,8BAA8B,EAAE,UAAU,cAAc,CAAC,CACpE;GACD,KAAK,KAAK,GAAG,QACF,CAAC,uBAAuB,EAAE,UAAU,0CAA0C,CAAC,CACzF;GACD,OAAO,KAAK,GAAG,QACJ,CAAC,uBAAuB,EAAE,UAAU,0CAA0C,CAAC,CACzF;GACD,QAAQ,KAAK,GAAG,QACL,CAAC,YAAY,EAAE,UAAU,cAAc,CAAC,CAClD;GACD,KAAK,KAAK,GAAG,QACF,CAAC,qBAAqB,EAAE,UAAU,yDAAyD,CAAC,CACtG;GACD,MAAM,KAAK,GAAG,QACH,CAAC,gBAAgB,EAAE,UAAU,2CAA2C,CAAC,CACnF;GACD,QAAQ,KAAK,GAAG,QACL,CAAC,kBAAkB,EAAE,UAAU,2CAA2C,CAAC,CACrF;GACD,OAAO,KAAK,GAAG,QAAiB,CAAC,YAAY,EAAE,WAAW,CAAC;GAC3D,OAAO,KAAK,GAAG,QACJ,CAAC,qB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,KAAK,MAAM,IAAI,MAAgB;AAClD,UAAO,CAAC,IAAI,KAAe,2BAAa,WAAW,AAAC;EACrD,EAAC,CACH;CACH;;;;;;;;;;;;CAaA,AAAO,aAAuB;EAC5B,MAAM,SAAS,KAAK,WAAW,WAAW,KAAK;AAE/C,SAAO,OAAO,IAAI,CAAC,QAAQ,IAAI,KAAe;CAChD;;;;;;CAOA,AAAO,sBAA8B;AACnC,SAAO,KAAK,QAAQ,aAAa;CACnC;;;;;;;;;;;;;;;;CAiBA,AAAO,UAAU,WAAuB;AACtC,SAAO,IAAI,GAAG,KAAK,IAAI;GACrB,WAAW,KAAK,QAAQ;GACxB;EACD;CACH;;;;;;;;;;;;;;;;CAiBA,EAAS,OAAO,YAAqC;EACnD,MAAM,SAAS,KAAK,WAAW,IAAI,QAAQ,KAAK,gBAAgB,CAAC;AAEjE,OAAK,MAAM,OAAO,QAAQ;GACxB,MAAM,aAAa,KAAK,MAAM,IAAI,MAAgB;GAClD,MAAM,CAAC,IAAI,KAAe,2BAAa,WAAW,AAAC;EACrD;CACF;;;;;;;;;;;;;;;;;;;;;;;;;CA0BA,MAAa,YAAe,IAAsC;AAChE,MAAI;GAEF,KAAK,WAAW,MAAM,KAAK;GAG3B,MAAM,SAAS,MAAM,IAAI;GAGzB,KAAK,WAAW,OAAO,KAAK;AAE5B,UAAO;EACR,SAAQ,OAAO;GAEd,KAAK,WAAW,SAAS,KAAK;AAC9B,SAAM;EACR;CACF;AACF;;;;;;;;AASA,SAAgB,OAChB,OAA6C,oBAC7C,UAAqB;CAAE,WAAW;CAAM,WAAW;AAAiB,GAC/D;AACH,QAAO,IAAI,GAAG,MAAM;AACtB"}
@@ -6,7 +6,7 @@
6
6
  /**
7
7
  * The current version of CommandKit.
8
8
  */
9
- const version = "1.0.0-dev.20250802020924";
9
+ const version = "1.0.0-dev.20250802113354";
10
10
 
11
11
  //#endregion
12
12
  Object.defineProperty(exports, 'version', {
@@ -15,4 +15,4 @@ Object.defineProperty(exports, 'version', {
15
15
  return version;
16
16
  }
17
17
  });
18
- //# sourceMappingURL=version-C-sDC9iq.js.map
18
+ //# sourceMappingURL=version-DBZO51VK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-C-sDC9iq.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["/**\n * @private\n */\nfunction $version(): string {\n 'use macro';\n return require('../package.json').version;\n}\n\n/**\n * The current version of CommandKit.\n */\nexport const version: string = $version();\n"],"mappings":";;;;;;;;AAWA,MAAa,UAA4B"}
1
+ {"version":3,"file":"version-DBZO51VK.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["/**\n * @private\n */\nfunction $version(): string {\n 'use macro';\n return require('../package.json').version;\n}\n\n/**\n * The current version of CommandKit.\n */\nexport const version: string = $version();\n"],"mappings":";;;;;;;;AAWA,MAAa,UAA4B"}
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
- const require_version = require('./version-C-sDC9iq.js');
1
+ const require_version = require('./version-DBZO51VK.js');
2
2
 
3
3
  exports.version = require_version.version;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "commandkit",
3
3
  "description": "Beginner friendly command & event handler for Discord.js",
4
- "version": "1.0.0-dev.20250802020924",
4
+ "version": "1.0.0-dev.20250802113354",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
7
7
  "main": "./dist/index.js",
@@ -167,7 +167,7 @@
167
167
  "picocolors": "^1.1.1",
168
168
  "rfdc": "^1.3.1",
169
169
  "rimraf": "^6.0.0",
170
- "tsdown": "^0.13.0",
170
+ "tsdown": "^0.13.1",
171
171
  "use-macro": "^1.1.0"
172
172
  },
173
173
  "devDependencies": {
@@ -178,7 +178,7 @@
178
178
  "tsx": "^4.19.2",
179
179
  "typescript": "^5.7.3",
180
180
  "vitest": "^3.0.5",
181
- "tsconfig": "0.0.0-dev.20250802020924"
181
+ "tsconfig": "0.0.0-dev.20250802113354"
182
182
  },
183
183
  "engines": {
184
184
  "node": ">=24"