@cequrebackends/cequre-ts 0.13.0 → 0.15.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.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Vercel WebSocket stub.
3
+ *
4
+ * Vercel serverless does NOT support WebSocket connections.
5
+ * The websocket property is set to undefined in withVercel().
6
+ *
7
+ * For realtime, use SSE (VercelSSEProvider) or a third-party
8
+ * service (Pusher, Ably, PartyKit).
9
+ *
10
+ * This file exists for adapter file parity (8 files matching Bun/Node).
11
+ */
12
+ export declare const CequreWebsocket: undefined;
@@ -1,10 +1,12 @@
1
1
  // @bun
2
2
  import {
3
- CequreError,
3
+ CequreError
4
+ } from "./index-qzzg2p5r.js";
5
+ import {
4
6
  __esm,
5
7
  __export,
6
8
  __toCommonJS
7
- } from "./index-17yswtmg.js";
9
+ } from "./index-cpw1bjf1.js";
8
10
 
9
11
  // shared/core/openapi.ts
10
12
  var exports_openapi = {};
@@ -1,11 +1,10 @@
1
1
  // @bun
2
2
  import {
3
- CequreError,
4
3
  __esm,
5
4
  __export,
6
5
  __require,
7
6
  __toCommonJS
8
- } from "./index-17yswtmg.js";
7
+ } from "./index-cpw1bjf1.js";
9
8
 
10
9
  // shared/utils/kv/adapters/memory.ts
11
10
  function getLog() {
@@ -123,7 +122,16 @@ var log = null;
123
122
  var init_memory = () => {};
124
123
 
125
124
  // shared/utils/kv/adapters/sqlite.ts
126
- import { Database } from "bun:sqlite";
125
+ function getBunDatabase() {
126
+ if (!BunDatabase) {
127
+ try {
128
+ BunDatabase = __require("bun:sqlite").Database;
129
+ } catch {
130
+ throw new Error("[Cequre KV (SQLite)] SQLite adapter requires Bun runtime (bun:sqlite).");
131
+ }
132
+ }
133
+ return BunDatabase;
134
+ }
127
135
  function getLog2() {
128
136
  if (!log2) {
129
137
  const { createLogger } = (init_logger(), __toCommonJS(exports_logger));
@@ -145,6 +153,7 @@ class SQLiteAdapter {
145
153
  stmtCount;
146
154
  constructor(options) {
147
155
  const dbPath = options?.path ?? "./data/cequre-kv.sqlite";
156
+ const DB = getBunDatabase();
148
157
  if (dbPath !== ":memory:") {
149
158
  const dir = dbPath.substring(0, dbPath.lastIndexOf("/"));
150
159
  if (dir) {
@@ -154,7 +163,7 @@ class SQLiteAdapter {
154
163
  } catch {}
155
164
  }
156
165
  }
157
- this.db = new Database(dbPath);
166
+ this.db = new DB(dbPath);
158
167
  this.db.run("PRAGMA journal_mode = WAL");
159
168
  this.db.run("PRAGMA synchronous = NORMAL");
160
169
  this.db.run(`
@@ -256,7 +265,7 @@ class SQLiteAdapter {
256
265
  getLog2().debug("SQLite KV adapter closed");
257
266
  }
258
267
  }
259
- var log2 = null;
268
+ var BunDatabase = null, log2 = null;
260
269
  var init_sqlite = () => {};
261
270
 
262
271
  // adapters/bun/bun-redis-cache.ts
@@ -356,6 +365,105 @@ class RedisAdapter {
356
365
  var _log = null;
357
366
  var init_bun_redis_cache = () => {};
358
367
 
368
+ // adapters/vercel/upstash-kv.ts
369
+ class UpstashKVAdapter {
370
+ url;
371
+ token;
372
+ constructor(options) {
373
+ this.url = options?.url || process.env.UPSTASH_REDIS_REST_URL || "";
374
+ this.token = options?.token || process.env.UPSTASH_REDIS_REST_TOKEN || "";
375
+ if (!this.url || !this.token) {
376
+ console.warn("[Cequre KV (Upstash)] UPSTASH_REDIS_REST_URL or UPSTASH_REDIS_REST_TOKEN not set \u2014 KV operations will fail.");
377
+ }
378
+ }
379
+ async command(args) {
380
+ const res = await fetch(this.url, {
381
+ method: "POST",
382
+ headers: {
383
+ Authorization: `Bearer ${this.token}`,
384
+ "Content-Type": "application/json"
385
+ },
386
+ body: JSON.stringify(args)
387
+ });
388
+ if (!res.ok) {
389
+ throw new Error(`Upstash Redis error: ${res.status} ${await res.text()}`);
390
+ }
391
+ const data = await res.json();
392
+ return data.result;
393
+ }
394
+ async get(key) {
395
+ const result = await this.command(["GET", key]);
396
+ if (result === null)
397
+ return null;
398
+ try {
399
+ return JSON.parse(result);
400
+ } catch {
401
+ return result;
402
+ }
403
+ }
404
+ async getMany(keys) {
405
+ const result = new Map;
406
+ if (keys.length === 0)
407
+ return result;
408
+ const values = await this.command(["MGET", ...keys]);
409
+ for (let i = 0;i < keys.length; i++) {
410
+ const key = keys[i];
411
+ if (key === undefined)
412
+ continue;
413
+ const value = values[i];
414
+ if (value !== null && value !== undefined) {
415
+ try {
416
+ result.set(key, JSON.parse(value));
417
+ } catch {
418
+ result.set(key, value);
419
+ }
420
+ }
421
+ }
422
+ return result;
423
+ }
424
+ async set(key, value, ttl) {
425
+ const serialized = JSON.stringify(value);
426
+ if (ttl != null && ttl > 0) {
427
+ await this.command(["SET", key, serialized, "EX", String(ttl)]);
428
+ } else {
429
+ await this.command(["SET", key, serialized]);
430
+ }
431
+ }
432
+ async setMany(entries) {
433
+ await Promise.all(entries.map(({ key, value, ttl }) => this.set(key, value, ttl)));
434
+ }
435
+ async delete(key) {
436
+ const deleted = await this.command(["DEL", key]);
437
+ return deleted > 0;
438
+ }
439
+ async deleteMany(keys) {
440
+ if (keys.length === 0)
441
+ return 0;
442
+ return await this.command(["DEL", ...keys]);
443
+ }
444
+ async has(key) {
445
+ const exists = await this.command(["EXISTS", key]);
446
+ return exists > 0;
447
+ }
448
+ async keys(prefix) {
449
+ if (!prefix) {
450
+ return await this.command(["KEYS", "*"]);
451
+ }
452
+ return await this.command(["KEYS", `${prefix}*`]);
453
+ }
454
+ async count() {
455
+ return await this.command(["DBSIZE"]);
456
+ }
457
+ async clear() {
458
+ await this.command(["FLUSHDB"]);
459
+ }
460
+ cleanup() {
461
+ return 0;
462
+ }
463
+ close() {}
464
+ }
465
+ var init_upstash_kv = () => {};
466
+
359
467
  // shared/utils/kv/types.ts
360
468
  var init_types = () => {};
361
469
 
@@ -372,6 +480,9 @@ class CequreKV {
372
480
  } else if (driver === "redis") {
373
481
  this.adapter = new RedisAdapter(options.redis);
374
482
  this.isCleanupNative = true;
483
+ } else if (driver === "upstash") {
484
+ this.adapter = new UpstashKVAdapter(options.upstash);
485
+ this.isCleanupNative = true;
375
486
  } else {
376
487
  this.adapter = new SQLiteAdapter(options.sqlite);
377
488
  this.isCleanupNative = false;
@@ -431,6 +542,7 @@ var init_kv = __esm(() => {
431
542
  init_memory();
432
543
  init_sqlite();
433
544
  init_bun_redis_cache();
545
+ init_upstash_kv();
434
546
  init_types();
435
547
  });
436
548
 
@@ -450,7 +562,7 @@ function getErrorKV() {
450
562
  return kvStore;
451
563
  }
452
564
  function createStream() {
453
- if (Bun.env.NODE_ENV !== "production" && Bun.env.NODE_ENV !== "test") {
565
+ if (env.NODE_ENV !== "production" && env.NODE_ENV !== "test") {
454
566
  return pretty({
455
567
  colorize: true,
456
568
  translateTime: "yyyy-mm-dd HH:MM:ss.l",
@@ -536,11 +648,12 @@ function createLogger(component) {
536
648
  }
537
649
  return logger.child({ component });
538
650
  }
539
- var LOG_LEVEL, ERROR_LOG_KV, kvStore = null, consoleStream, logger;
651
+ var env, LOG_LEVEL, ERROR_LOG_KV, kvStore = null, consoleStream, logger;
540
652
  var init_logger = __esm(() => {
541
653
  init_kv();
542
- LOG_LEVEL = Bun.env.CEQURE_LOG_LEVEL || Bun.env.LOG_LEVEL || (Bun.env.NODE_ENV === "test" ? "silent" : "info");
543
- ERROR_LOG_KV = Bun.env.CEQURE_ERROR_LOG_KV === "true";
654
+ env = typeof process !== "undefined" ? process.env : typeof Bun !== "undefined" ? Bun.env : {};
655
+ LOG_LEVEL = env.CEQURE_LOG_LEVEL || env.LOG_LEVEL || (env.NODE_ENV === "test" ? "silent" : "info");
656
+ ERROR_LOG_KV = env.CEQURE_ERROR_LOG_KV === "true";
544
657
  consoleStream = createStream();
545
658
  logger = consoleStream ? pino({ name: "cequre", level: LOG_LEVEL }, consoleStream) : pino({ name: "cequre", level: LOG_LEVEL });
546
659
  if (ERROR_LOG_KV) {
@@ -554,197 +667,4 @@ var init_logger = __esm(() => {
554
667
  }
555
668
  });
556
669
 
557
- // shared/utils/queue-manager.ts
558
- import { Queue as BullQueue, Worker as BullWorker, QueueEvents as BullQueueEvents } from "bullmq";
559
- import { Effect } from "effect";
560
- init_logger();
561
-
562
- class BullMQQueueAdapter {
563
- queue;
564
- constructor(queue) {
565
- this.queue = queue;
566
- }
567
- async add(name, data, opts) {
568
- return this.queue.add(name, data, opts);
569
- }
570
- async addBulk(jobs) {
571
- const bulkJobs = jobs.map((job) => ({
572
- name: job.name,
573
- data: job.data,
574
- opts: job.opts
575
- }));
576
- return this.queue.addBulk(bulkJobs);
577
- }
578
- async getRepeatableJobs() {
579
- return this.queue.getRepeatableJobs();
580
- }
581
- async removeRepeatableByKey(key) {
582
- return this.queue.removeRepeatableByKey(key);
583
- }
584
- async disconnect() {
585
- await this.queue.close();
586
- }
587
- }
588
-
589
- class CequreQueueManager {
590
- static instance;
591
- queues = new Map;
592
- workers = new Map;
593
- queueEvents = new Map;
594
- config;
595
- closing = false;
596
- constructor(config) {
597
- this.config = config;
598
- if (!this.config.bullmq?.connection) {
599
- throw CequreError.NotConfigured('CequreQueueManager: bullmq provider requires "bullmq.connection"');
600
- }
601
- }
602
- getBullMQBaseOptions() {
603
- return {
604
- ...this.config.bullmq.prefix ? { prefix: this.config.bullmq.prefix } : {},
605
- connection: {
606
- ...this.config.bullmq.connection,
607
- maxRetriesPerRequest: null
608
- }
609
- };
610
- }
611
- static initialize(config) {
612
- if (!CequreQueueManager.instance) {
613
- CequreQueueManager.instance = new CequreQueueManager(config);
614
- }
615
- return CequreQueueManager.instance;
616
- }
617
- static getInstance() {
618
- if (!CequreQueueManager.instance) {
619
- throw CequreError.NotConfigured("CequreQueueManager not initialized. Call initialize() first.");
620
- }
621
- return CequreQueueManager.instance;
622
- }
623
- getQueue(name) {
624
- const existing = this.queues.get(name);
625
- if (existing)
626
- return existing;
627
- const queue = new BullQueue(name, {
628
- ...this.config.defaultQueueOptions ?? {},
629
- ...this.getBullMQBaseOptions()
630
- });
631
- queue.on("error", (err) => {
632
- if (err?.message?.includes("Connection is closed"))
633
- return;
634
- logger.error(err, `[ ${name.toUpperCase()} QUEUE ] Error`);
635
- });
636
- const wrapped = new BullMQQueueAdapter(queue);
637
- this.queues.set(name, wrapped);
638
- return wrapped;
639
- }
640
- async addJob(queueName, jobName, data, opts) {
641
- const queue = this.getQueue(queueName);
642
- return queue.add(jobName, data, opts);
643
- }
644
- async addBulk(queueName, jobs) {
645
- const queue = this.getQueue(queueName);
646
- return queue.addBulk(jobs);
647
- }
648
- async registerWorker(queueName, handler, options) {
649
- const existing = this.workers.get(queueName);
650
- const queueNameForLogs = `[ ${queueName?.toUpperCase()} WORKER ]`;
651
- if (existing) {
652
- logger.warn(`${queueNameForLogs} Replacing existing worker for queue "${queueName}"`);
653
- try {
654
- await existing.close();
655
- } catch (err) {
656
- logger.error(err, `${queueNameForLogs} Error closing old worker for "${queueName}"`);
657
- }
658
- this.workers.delete(queueName);
659
- }
660
- const worker = new BullWorker(queueName, async (job) => await handler(job), {
661
- ...this.config.defaultWorkerOptions ?? {},
662
- ...options ?? {},
663
- ...this.getBullMQBaseOptions()
664
- });
665
- worker.on("completed", (job) => {
666
- logger.info(`${queueNameForLogs} Job ${job.id} completed`);
667
- });
668
- worker.on("failed", (job, err) => {
669
- logger.error(err, `${queueNameForLogs} Job ${job?.id ?? "unknown"} failed`);
670
- });
671
- worker.on("error", (err) => {
672
- if (err?.message?.includes("Connection is closed"))
673
- return;
674
- logger.error(err, `${queueNameForLogs} Worker error`);
675
- });
676
- await worker.waitUntilReady();
677
- logger.info(`${queueNameForLogs} Worker is ready and listening . . .`);
678
- const wrapped = {
679
- close: async () => {
680
- await worker.close();
681
- },
682
- waitUntilReady: async () => {
683
- await worker.waitUntilReady();
684
- }
685
- };
686
- this.workers.set(queueName, wrapped);
687
- return wrapped;
688
- }
689
- getQueueEvents(name) {
690
- const existing = this.queueEvents.get(name);
691
- if (existing)
692
- return existing;
693
- const events = new BullQueueEvents(name, {
694
- ...this.getBullMQBaseOptions()
695
- });
696
- events.on("error", (err) => {
697
- if (err?.message?.includes("Connection is closed"))
698
- return;
699
- logger.error(err, `[ ${name.toUpperCase()} QUEUE EVENTS ] Error`);
700
- });
701
- const wrapped = {
702
- disconnect: async () => {
703
- await events.close();
704
- }
705
- };
706
- this.queueEvents.set(name, wrapped);
707
- return wrapped;
708
- }
709
- static _reset() {
710
- CequreQueueManager.instance = undefined;
711
- }
712
- static async _resetAndClose() {
713
- const existing = CequreQueueManager.instance;
714
- CequreQueueManager.instance = undefined;
715
- if (existing) {
716
- await existing.close();
717
- }
718
- }
719
- async close() {
720
- if (this.closing)
721
- return;
722
- this.closing = true;
723
- const closeItemEffect = (item, label) => Effect.tryPromise({
724
- try: async () => {
725
- if (item.close)
726
- await item.close();
727
- else if (item.disconnect)
728
- await item.disconnect();
729
- },
730
- catch: (err) => err
731
- }).pipe(Effect.catchAll((err) => Effect.sync(() => {
732
- logger.error(err, `[QueueManager] Error closing ${label}`);
733
- })));
734
- const closeGroupEffect = (items, label) => Effect.all(items.map((item) => closeItemEffect(item, label)), { concurrency: "unbounded" });
735
- const workers = Array.from(this.workers.values());
736
- const queueEvents = Array.from(this.queueEvents.values());
737
- const queues = Array.from(this.queues.values());
738
- await Effect.runPromise(Effect.gen(function* () {
739
- yield* closeGroupEffect(workers, "worker");
740
- yield* closeGroupEffect(queueEvents, "queue events");
741
- yield* closeGroupEffect(queues, "queue");
742
- }));
743
- this.workers.clear();
744
- this.queueEvents.clear();
745
- this.queues.clear();
746
- this.closing = false;
747
- }
748
- }
749
-
750
- export { logger, CequreErrorLogs, createLogger, exports_logger, init_logger, RedisAdapter, init_bun_redis_cache, CequreKV, init_kv, CequreQueueManager };
670
+ export { logger, CequreErrorLogs, createLogger, exports_logger, init_logger, RedisAdapter, init_bun_redis_cache, UpstashKVAdapter, init_upstash_kv, CequreKV, init_kv };
@@ -0,0 +1,62 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toCommonJS = (from) => {
10
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
+ if (entry)
12
+ return entry;
13
+ entry = __defProp({}, "__esModule", { value: true });
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (var key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(entry, key))
17
+ __defProp(entry, key, {
18
+ get: __accessProp.bind(from, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ __moduleCache.set(from, entry);
23
+ return entry;
24
+ };
25
+ var __moduleCache;
26
+ var __returnValue = (v) => v;
27
+ function __exportSetter(name, newValue) {
28
+ this[name] = __returnValue.bind(null, newValue);
29
+ }
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, {
33
+ get: all[name],
34
+ enumerable: true,
35
+ configurable: true,
36
+ set: __exportSetter.bind(all, name)
37
+ });
38
+ };
39
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
40
+ var __require = import.meta.require;
41
+
42
+ // shared/core/ulid.ts
43
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
44
+ var TIME_LEN = 10;
45
+ var RANDOM_LEN = 16;
46
+ function ulid(seedTime = Date.now()) {
47
+ let str = "";
48
+ let now = seedTime;
49
+ for (let len = TIME_LEN;len > 0; len--) {
50
+ const mod = now % 32;
51
+ str = ENCODING.charAt(mod) + str;
52
+ now = (now - mod) / 32;
53
+ }
54
+ const randomBytes = new Uint8Array(RANDOM_LEN);
55
+ crypto.getRandomValues(randomBytes);
56
+ for (let i = 0;i < RANDOM_LEN; i++) {
57
+ str += ENCODING.charAt(randomBytes[i] & 31);
58
+ }
59
+ return str;
60
+ }
61
+
62
+ export { __toCommonJS, __export, __esm, __require, ulid };
@@ -1,64 +1,4 @@
1
1
  // @bun
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- function __accessProp(key) {
7
- return this[key];
8
- }
9
- var __toCommonJS = (from) => {
10
- var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
- if (entry)
12
- return entry;
13
- entry = __defProp({}, "__esModule", { value: true });
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (var key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(entry, key))
17
- __defProp(entry, key, {
18
- get: __accessProp.bind(from, key),
19
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
- });
21
- }
22
- __moduleCache.set(from, entry);
23
- return entry;
24
- };
25
- var __moduleCache;
26
- var __returnValue = (v) => v;
27
- function __exportSetter(name, newValue) {
28
- this[name] = __returnValue.bind(null, newValue);
29
- }
30
- var __export = (target, all) => {
31
- for (var name in all)
32
- __defProp(target, name, {
33
- get: all[name],
34
- enumerable: true,
35
- configurable: true,
36
- set: __exportSetter.bind(all, name)
37
- });
38
- };
39
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
40
- var __require = import.meta.require;
41
-
42
- // shared/core/ulid.ts
43
- var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
44
- var TIME_LEN = 10;
45
- var RANDOM_LEN = 16;
46
- function ulid(seedTime = Date.now()) {
47
- let str = "";
48
- let now = seedTime;
49
- for (let len = TIME_LEN;len > 0; len--) {
50
- const mod = now % 32;
51
- str = ENCODING.charAt(mod) + str;
52
- now = (now - mod) / 32;
53
- }
54
- const randomBytes = new Uint8Array(RANDOM_LEN);
55
- crypto.getRandomValues(randomBytes);
56
- for (let i = 0;i < RANDOM_LEN; i++) {
57
- str += ENCODING.charAt(randomBytes[i] & 31);
58
- }
59
- return str;
60
- }
61
-
62
2
  // shared/utils/url.ts
63
3
  function extractPathname(url) {
64
4
  const protocolIndex = url.indexOf("://");
@@ -172,4 +112,4 @@ function toErrorResponse(error, request, adapter) {
172
112
  });
173
113
  }
174
114
 
175
- export { __toCommonJS, __export, __esm, __require, ulid, extractPathname, CequreError, parseConstraintError, getConstraintErrorMessage, getConstraintErrorStatus, buildErrorResponse, toErrorResponse };
115
+ export { extractPathname, CequreError, parseConstraintError, getConstraintErrorMessage, getConstraintErrorStatus, buildErrorResponse, toErrorResponse };