@getstrata/bootstrap 0.2.28 → 0.2.29

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 (35) hide show
  1. package/dist/bootstrap/http/securedRouteModelBinding.d.ts +2 -2
  2. package/dist/bootstrap/schedule.d.ts +2 -1
  3. package/dist/bootstrap/web/forms.d.ts +1 -1
  4. package/dist/entries/applicationRegistry.js +2 -0
  5. package/dist/entries/buildModuleRoutes.js +2 -0
  6. package/dist/entries/buildWebModuleRoutes.js +2 -0
  7. package/dist/entries/cache/modelCacheTags.js +2 -0
  8. package/dist/entries/config.js +2 -0
  9. package/dist/entries/context.js +76 -3157
  10. package/dist/entries/contracts.js +2 -0
  11. package/dist/entries/createRoutes.js +1468 -0
  12. package/dist/entries/createSpaRoutes.js +2 -0
  13. package/dist/entries/createWebRoutes.js +2 -0
  14. package/dist/entries/dependencies.js +76 -3157
  15. package/dist/entries/discoverModules.js +2 -0
  16. package/dist/entries/health.js +3 -0
  17. package/dist/entries/http/securedRouteModelBinding.js +6 -293
  18. package/dist/entries/httpKernel.js +2 -0
  19. package/dist/entries/listeners/invalidateCacheOnModelWrite.js +2 -0
  20. package/dist/entries/membershipService.js +2 -0
  21. package/dist/entries/metricsRoutes.js +2 -0
  22. package/dist/entries/providers/view.js +6 -623
  23. package/dist/entries/providers.js +69 -3157
  24. package/dist/entries/queue/defaultJobs.js +7 -465
  25. package/dist/entries/routeRegistry.js +2 -0
  26. package/dist/entries/schedule.js +49 -0
  27. package/dist/entries/secretsGuard.js +9 -0
  28. package/dist/entries/web/forms.js +4 -18
  29. package/dist/entries/web/routing.js +18 -304
  30. package/dist/entries/web/server.js +2 -0
  31. package/dist/entries/web/session.js +3 -26
  32. package/dist/entries/web/slug.js +2 -0
  33. package/dist/index-sfreg6q3.js +0 -0
  34. package/dist/index.js +69 -3322
  35. package/package.json +12 -2
@@ -1,4 +1,14 @@
1
1
  // @bun
2
+ var __jsonParse = (a) => JSON.parse(a);
3
+
4
+ // ../../src/bootstrap/providers/auth.ts
5
+ import {
6
+ AuthManager,
7
+ CompositeGuard,
8
+ DatabaseTokenGuard,
9
+ GuestGuard
10
+ } from "@getstrata/core/auth/guard";
11
+
2
12
  // ../../src/config/auth.ts
3
13
  var authConfig = {
4
14
  allowDevHeaders: (process.env.AUTH_DEV_HEADERS ?? "true") !== "false",
@@ -230,6 +240,7 @@ var db = new Proxy(function database() {}, {
230
240
  return typeof value === "function" ? value.bind(connection) : value;
231
241
  }
232
242
  });
243
+ var connection_default = db;
233
244
 
234
245
  // ../../src/modules/user/apiTokenTable.ts
235
246
  import { defineTable } from "@getstrata/core/database";
@@ -410,145 +421,9 @@ import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core
410
421
  import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
411
422
 
412
423
  // ../../src/modules/user/provider.ts
424
+ var userRepositoryToken = "user.repository";
413
425
  var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
414
426
 
415
- // ../../src/core/errors/http.ts
416
- class HttpError extends Error {
417
- status;
418
- details;
419
- constructor(status, message, details) {
420
- super(message);
421
- this.name = new.target.name;
422
- this.status = status;
423
- this.details = details;
424
- }
425
- }
426
-
427
- class BadRequestError extends HttpError {
428
- constructor(message = "Bad Request", details) {
429
- super(400, message, details);
430
- }
431
- }
432
- class ConflictError extends HttpError {
433
- constructor(message = "Conflict", details) {
434
- super(409, message, details);
435
- }
436
- }
437
-
438
- class UnprocessableEntityError extends HttpError {
439
- constructor(message = "Unprocessable Entity", details) {
440
- super(422, message, details);
441
- }
442
- }
443
- class ForbiddenError2 extends HttpError {
444
- constructor(message = "Forbidden", details) {
445
- super(403, message, details);
446
- }
447
- }
448
-
449
- class UnauthorizedError2 extends HttpError {
450
- constructor(message = "Unauthorized", details) {
451
- super(401, message, details);
452
- }
453
- }
454
- class PreconditionFailedError extends HttpError {
455
- constructor(message = "Precondition Failed", details) {
456
- super(412, message, details);
457
- }
458
- }
459
-
460
- // ../../src/core/auth/authContext.ts
461
- var authContext = createAsyncContextStore("@getstrata/authContext");
462
- function currentAuthUser() {
463
- return authContext.getStore() ?? null;
464
- }
465
-
466
- // ../../src/core/auth/guard.ts
467
- function devHeaderAbilities(role) {
468
- if (role === "admin") {
469
- return [...ADMIN_ABILITIES];
470
- }
471
- return [...MEMBER_ABILITIES];
472
- }
473
-
474
- class GuestGuard {
475
- resolve(request) {
476
- const userId = request.headers.get("x-authenticated-user-id");
477
- if (!userId) {
478
- return null;
479
- }
480
- const role = request.headers.get("x-authenticated-user-role");
481
- return {
482
- id: userId,
483
- abilities: devHeaderAbilities(role),
484
- ...role ? { role } : {}
485
- };
486
- }
487
- }
488
- class DatabaseTokenGuard {
489
- container;
490
- constructor(container) {
491
- this.container = container;
492
- }
493
- async resolve(request) {
494
- const authorization = request.headers.get("authorization");
495
- if (!authorization?.startsWith("Bearer ")) {
496
- return null;
497
- }
498
- const token = authorization.slice("Bearer ".length).trim();
499
- if (!token) {
500
- return null;
501
- }
502
- if (!this.container.has(tokenServiceToken)) {
503
- return null;
504
- }
505
- const tokenService = this.container.resolve(tokenServiceToken);
506
- return await tokenService.resolveUserFromToken(token);
507
- }
508
- }
509
-
510
- class CompositeGuard {
511
- guards;
512
- constructor(guards) {
513
- this.guards = guards;
514
- }
515
- async resolve(request) {
516
- for (const guard of this.guards) {
517
- const user = await Promise.resolve(guard.resolve(request));
518
- if (user) {
519
- return user;
520
- }
521
- }
522
- return null;
523
- }
524
- }
525
-
526
- class AuthManager {
527
- guard;
528
- constructor(guard) {
529
- this.guard = guard;
530
- }
531
- async resolve(request) {
532
- if (request) {
533
- return await Promise.resolve(this.guard.resolve(request));
534
- }
535
- return currentAuthUser();
536
- }
537
- user(request) {
538
- return this.resolve(request);
539
- }
540
- async check(request) {
541
- return await this.user(request) !== null;
542
- }
543
- async requireUser(request) {
544
- const user = await this.user(request);
545
- if (!user) {
546
- throw new UnauthorizedError2;
547
- }
548
- return user;
549
- }
550
- }
551
-
552
427
  // ../../src/core/auth/sessionCookie.ts
553
428
  import { createHmac, timingSafeEqual } from "crypto";
554
429
  var SESSION_COOKIE = "workhub_session";
@@ -649,378 +524,8 @@ var authProvider = {
649
524
  };
650
525
  var auth_default = authProvider;
651
526
 
652
- // ../../src/core/cache/redisCacheStore.ts
653
- var {RedisClient } = globalThis.Bun;
654
- var KEY_PREFIX = "workhub:cache:";
655
- var TAG_PREFIX = "workhub:cache:tag:";
656
-
657
- class RedisCacheStore {
658
- ttlMs;
659
- maxEntries;
660
- client;
661
- inflight = new Map;
662
- keyTags = new Map;
663
- constructor(redisUrl, ttlMs, maxEntries) {
664
- this.ttlMs = ttlMs;
665
- this.maxEntries = maxEntries;
666
- this.client = new RedisClient(redisUrl);
667
- }
668
- async get(key) {
669
- const raw = await this.client.get(this.storageKey(key));
670
- if (raw === null) {
671
- return;
672
- }
673
- return JSON.parse(raw);
674
- }
675
- async set(key, value, ttlMs) {
676
- const resolvedTtlMs = ttlMs ?? this.ttlMs;
677
- const payload = JSON.stringify(value);
678
- if (resolvedTtlMs > 0) {
679
- await this.client.psetex(this.storageKey(key), resolvedTtlMs, payload);
680
- } else {
681
- await this.client.set(this.storageKey(key), payload);
682
- }
683
- await this.enforceMaxEntries();
684
- }
685
- async getOrSet(key, loader, ttlMs) {
686
- const cached = await this.get(key);
687
- if (cached !== undefined) {
688
- return cached;
689
- }
690
- const inflightRequest = this.inflight.get(key);
691
- if (inflightRequest) {
692
- return inflightRequest;
693
- }
694
- const pendingRequest = loader().then(async (value) => {
695
- await this.set(key, value, ttlMs);
696
- return value;
697
- }).finally(() => {
698
- this.inflight.delete(key);
699
- });
700
- this.inflight.set(key, pendingRequest);
701
- return pendingRequest;
702
- }
703
- async attachTags(key, tags) {
704
- if (tags.length === 0) {
705
- return;
706
- }
707
- let tagsForKey = this.keyTags.get(key);
708
- if (!tagsForKey) {
709
- tagsForKey = new Set;
710
- this.keyTags.set(key, tagsForKey);
711
- }
712
- for (const tag of tags) {
713
- tagsForKey.add(tag);
714
- await this.client.sadd(this.tagKey(tag), key);
715
- }
716
- }
717
- async flushTags(tags) {
718
- const keysToRemove = new Set;
719
- for (const tag of tags) {
720
- const members = await this.client.smembers(this.tagKey(tag));
721
- for (const member of members) {
722
- keysToRemove.add(member);
723
- }
724
- }
725
- let removed = 0;
726
- for (const key of keysToRemove) {
727
- if (await this.invalidate(key)) {
728
- removed += 1;
729
- }
730
- }
731
- for (const tag of tags) {
732
- await this.client.del(this.tagKey(tag));
733
- }
734
- return removed;
735
- }
736
- async invalidate(key) {
737
- const deleted = await this.client.del(this.storageKey(key));
738
- await this.detachKeyFromTags(key);
739
- return deleted > 0;
740
- }
741
- async invalidateByPrefix(prefix) {
742
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
743
- let removed = 0;
744
- for (const storageKey of keys) {
745
- const key = storageKey.slice(KEY_PREFIX.length);
746
- if (key === prefix || key.startsWith(`${prefix}?`)) {
747
- if (await this.invalidate(key)) {
748
- removed += 1;
749
- }
750
- }
751
- }
752
- return removed;
753
- }
754
- async clear() {
755
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
756
- if (keys.length > 0) {
757
- await this.client.del(...keys);
758
- }
759
- const tagKeys = await this.client.keys(`${TAG_PREFIX}*`);
760
- if (tagKeys.length > 0) {
761
- await this.client.del(...tagKeys);
762
- }
763
- this.inflight.clear();
764
- this.keyTags.clear();
765
- }
766
- async size() {
767
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
768
- return keys.length;
769
- }
770
- storageKey(key) {
771
- return `${KEY_PREFIX}${key}`;
772
- }
773
- tagKey(tag) {
774
- return `${TAG_PREFIX}${tag}`;
775
- }
776
- async detachKeyFromTags(key) {
777
- const tags = this.keyTags.get(key);
778
- if (!tags) {
779
- return;
780
- }
781
- for (const tag of tags) {
782
- await this.client.srem(this.tagKey(tag), key);
783
- }
784
- this.keyTags.delete(key);
785
- }
786
- async enforceMaxEntries() {
787
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
788
- if (keys.length <= this.maxEntries) {
789
- return;
790
- }
791
- const overflow = keys.length - this.maxEntries;
792
- const keysToRemove = keys.slice(0, overflow);
793
- if (keysToRemove.length > 0) {
794
- await this.client.del(...keysToRemove);
795
- }
796
- }
797
- }
798
- var redisCacheStore_default = RedisCacheStore;
799
-
800
- // ../../src/core/cache/simpleCache.ts
801
- class SimpleCache {
802
- ttlMs;
803
- maxEntries;
804
- cache = new Map;
805
- inflight = new Map;
806
- tagIndex = new Map;
807
- keyTags = new Map;
808
- constructor(ttlMs = 3600000, maxEntries = 100) {
809
- this.ttlMs = ttlMs;
810
- this.maxEntries = maxEntries;
811
- if (!Number.isFinite(ttlMs) || ttlMs < 0) {
812
- throw new RangeError("ttlMs must be a non-negative number.");
813
- }
814
- if (!Number.isInteger(maxEntries) || maxEntries < 1) {
815
- throw new RangeError("maxEntries must be a positive integer.");
816
- }
817
- }
818
- get(key) {
819
- return this.getFreshEntry(key)?.value;
820
- }
821
- set(key, value, ttlMs) {
822
- const now = Date.now();
823
- const resolvedTtlMs = ttlMs ?? this.ttlMs;
824
- this.cache.set(key, {
825
- value,
826
- expiresAt: now + resolvedTtlMs,
827
- lastAccessedAt: now
828
- });
829
- this.evictOverflow();
830
- }
831
- async getOrSet(key, loader, ttlMs) {
832
- this.pruneExpired();
833
- const cachedEntry = this.getFreshEntry(key);
834
- if (cachedEntry) {
835
- return cachedEntry.value;
836
- }
837
- const inflightRequest = this.inflight.get(key);
838
- if (inflightRequest) {
839
- return inflightRequest;
840
- }
841
- const pendingRequest = loader().then((value) => {
842
- this.set(key, value, ttlMs);
843
- return value;
844
- }).finally(() => {
845
- this.inflight.delete(key);
846
- });
847
- this.inflight.set(key, pendingRequest);
848
- return pendingRequest;
849
- }
850
- attachTags(key, tags) {
851
- if (tags.length === 0) {
852
- return;
853
- }
854
- let tagsForKey = this.keyTags.get(key);
855
- if (!tagsForKey) {
856
- tagsForKey = new Set;
857
- this.keyTags.set(key, tagsForKey);
858
- }
859
- for (const tag of tags) {
860
- tagsForKey.add(tag);
861
- let keysForTag = this.tagIndex.get(tag);
862
- if (!keysForTag) {
863
- keysForTag = new Set;
864
- this.tagIndex.set(tag, keysForTag);
865
- }
866
- keysForTag.add(key);
867
- }
868
- }
869
- flushTags(tags) {
870
- const keysToRemove = new Set;
871
- for (const tag of tags) {
872
- const keys = this.tagIndex.get(tag);
873
- if (!keys) {
874
- continue;
875
- }
876
- for (const key of keys) {
877
- keysToRemove.add(key);
878
- }
879
- }
880
- let removed = 0;
881
- for (const key of keysToRemove) {
882
- if (this.invalidate(key)) {
883
- removed += 1;
884
- }
885
- }
886
- for (const tag of tags) {
887
- this.tagIndex.delete(tag);
888
- }
889
- return removed;
890
- }
891
- invalidate(key) {
892
- const removed = this.cache.delete(key);
893
- if (removed) {
894
- this.detachKeyFromTags(key);
895
- }
896
- return removed;
897
- }
898
- invalidateByPrefix(prefix) {
899
- let removed = 0;
900
- for (const key of [...this.cache.keys()]) {
901
- if (key === prefix || key.startsWith(`${prefix}?`)) {
902
- if (this.invalidate(key)) {
903
- removed += 1;
904
- }
905
- }
906
- }
907
- return removed;
908
- }
909
- clear() {
910
- this.cache.clear();
911
- this.inflight.clear();
912
- this.tagIndex.clear();
913
- this.keyTags.clear();
914
- }
915
- size() {
916
- this.pruneExpired();
917
- return this.cache.size;
918
- }
919
- detachKeyFromTags(key) {
920
- const tags = this.keyTags.get(key);
921
- if (!tags) {
922
- return;
923
- }
924
- for (const tag of tags) {
925
- const keys = this.tagIndex.get(tag);
926
- if (!keys) {
927
- continue;
928
- }
929
- keys.delete(key);
930
- if (keys.size === 0) {
931
- this.tagIndex.delete(tag);
932
- }
933
- }
934
- this.keyTags.delete(key);
935
- }
936
- getFreshEntry(key) {
937
- const entry = this.cache.get(key);
938
- if (!entry) {
939
- return;
940
- }
941
- if (entry.expiresAt <= Date.now()) {
942
- this.invalidate(key);
943
- return;
944
- }
945
- entry.lastAccessedAt = Date.now();
946
- return entry;
947
- }
948
- pruneExpired() {
949
- const now = Date.now();
950
- for (const [key, entry] of this.cache.entries()) {
951
- if (entry.expiresAt <= now) {
952
- this.invalidate(key);
953
- }
954
- }
955
- }
956
- evictOverflow() {
957
- while (this.cache.size > this.maxEntries) {
958
- let oldestKey;
959
- let oldestAccessTime = Number.POSITIVE_INFINITY;
960
- for (const [key, entry] of this.cache.entries()) {
961
- if (entry.lastAccessedAt < oldestAccessTime) {
962
- oldestAccessTime = entry.lastAccessedAt;
963
- oldestKey = key;
964
- }
965
- }
966
- if (!oldestKey) {
967
- return;
968
- }
969
- this.invalidate(oldestKey);
970
- }
971
- }
972
- }
973
- var simpleCache_default = SimpleCache;
974
-
975
- // ../../src/core/cache/simpleCacheStore.ts
976
- class SimpleCacheStore {
977
- cache;
978
- constructor(cache) {
979
- this.cache = cache;
980
- }
981
- get(key) {
982
- return Promise.resolve(this.cache.get(key));
983
- }
984
- set(key, value, ttlMs) {
985
- this.cache.set(key, value, ttlMs);
986
- return Promise.resolve();
987
- }
988
- getOrSet(key, loader, ttlMs) {
989
- return this.cache.getOrSet(key, loader, ttlMs);
990
- }
991
- attachTags(key, tags) {
992
- this.cache.attachTags(key, tags);
993
- return Promise.resolve();
994
- }
995
- flushTags(tags) {
996
- return Promise.resolve(this.cache.flushTags(tags));
997
- }
998
- invalidate(key) {
999
- return Promise.resolve(this.cache.invalidate(key));
1000
- }
1001
- invalidateByPrefix(prefix) {
1002
- return Promise.resolve(this.cache.invalidateByPrefix(prefix));
1003
- }
1004
- clear() {
1005
- this.cache.clear();
1006
- return Promise.resolve();
1007
- }
1008
- size() {
1009
- return Promise.resolve(this.cache.size());
1010
- }
1011
- }
1012
- var simpleCacheStore_default = SimpleCacheStore;
1013
-
1014
- // ../../src/core/cache/createCacheStore.ts
1015
- function createCacheStore(options) {
1016
- if (options.driver === "redis") {
1017
- if (!options.redisUrl) {
1018
- throw new Error('CACHE_DRIVER="redis" requires REDIS_URL to be set.');
1019
- }
1020
- return new redisCacheStore_default(options.redisUrl, options.ttlMs, options.maxEntries);
1021
- }
1022
- return new simpleCacheStore_default(new simpleCache_default(options.ttlMs, options.maxEntries));
1023
- }
527
+ // ../../src/bootstrap/providers/cache.ts
528
+ import { createCacheStore } from "@getstrata/core/cache/createCacheStore";
1024
529
 
1025
530
  // ../../src/core/cache/taggedCache.ts
1026
531
  class TaggedCache {
@@ -1098,6 +603,9 @@ var cacheProvider = {
1098
603
  };
1099
604
  var cache_default = cacheProvider;
1100
605
 
606
+ // ../../src/bootstrap/providers/config.ts
607
+ import { validateEnv } from "@getstrata/core/config/envSchema";
608
+
1101
609
  // ../../src/config/app.ts
1102
610
  var appConfig = {
1103
611
  name: "WorkHub",
@@ -1114,34 +622,6 @@ var queueConfig = {
1114
622
  backoffMs: Number(process.env.QUEUE_BACKOFF_MS ?? "1000")
1115
623
  };
1116
624
 
1117
- // ../../src/core/config/envSchema.ts
1118
- function validateEnv(schema, env = process.env) {
1119
- const resolved = {};
1120
- for (const [name, rule] of Object.entries(schema)) {
1121
- const rawValue = env[name];
1122
- const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
1123
- if (value === undefined || value.trim() === "") {
1124
- if (rule.required) {
1125
- throw new Error(`Missing required environment variable "${name}".`);
1126
- }
1127
- continue;
1128
- }
1129
- if (rule.integer) {
1130
- const parsed = Number.parseInt(value, 10);
1131
- const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
1132
- if (!Number.isInteger(parsed) || parsed < minimum) {
1133
- const comparison = minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
1134
- throw new Error(`Environment variable "${name}" must be ${comparison}.`);
1135
- }
1136
- }
1137
- if (rule.pattern && !rule.pattern.test(value)) {
1138
- throw new Error(`Environment variable "${name}" has an invalid format.`);
1139
- }
1140
- resolved[name] = value;
1141
- }
1142
- return resolved;
1143
- }
1144
-
1145
625
  // ../../src/bootstrap/env.ts
1146
626
  import { defineEnvSchema } from "@getstrata/core/config/envSchema";
1147
627
  var appEnvSchema = defineEnvSchema({
@@ -1261,39 +741,8 @@ var configProvider = {
1261
741
  };
1262
742
  var config_default = configProvider;
1263
743
 
1264
- // ../../src/core/events/eventBus.ts
1265
- class EventBus {
1266
- constructor() {}
1267
- listeners = new Map;
1268
- listen(event, listener) {
1269
- const handlers = this.listeners.get(event) ?? new Set;
1270
- handlers.add(listener);
1271
- this.listeners.set(event, handlers);
1272
- return () => {
1273
- handlers.delete(listener);
1274
- if (handlers.size === 0) {
1275
- this.listeners.delete(event);
1276
- }
1277
- };
1278
- }
1279
- async dispatch(event, payload) {
1280
- const handlers = this.listeners.get(event);
1281
- if (!handlers || handlers.size === 0) {
1282
- return;
1283
- }
1284
- for (const handler of handlers) {
1285
- await handler(payload);
1286
- }
1287
- }
1288
- }
1289
- var eventBus = new EventBus;
1290
-
1291
- // ../../src/core/events/index.ts
1292
- function modelEventName(tableName, action) {
1293
- return `${tableName}.${action}`;
1294
- }
1295
-
1296
744
  // ../../src/bootstrap/providers/events.ts
745
+ import { eventBus } from "@getstrata/core/events";
1297
746
  var eventsProvider = {
1298
747
  name: "core.events",
1299
748
  register({ container }) {
@@ -1330,7 +779,7 @@ function discoverListeners() {
1330
779
  }
1331
780
 
1332
781
  // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
1333
- import { eventBus as eventBus2, modelEventName as modelEventName2 } from "@getstrata/core/events";
782
+ import { eventBus as eventBus2, modelEventName } from "@getstrata/core/events";
1334
783
  import InvalidateCacheTagsJob from "@getstrata/core/jobs/invalidateCacheTagsJob";
1335
784
  import { createTrackedJob } from "@getstrata/core/queue/createAppQueue";
1336
785
 
@@ -1424,7 +873,7 @@ var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-d
1424
873
  function registerInvalidateCacheOnModelWriteListeners(bus = eventBus2) {
1425
874
  for (const tableName of discoverModelTableNames()) {
1426
875
  for (const action of MODEL_WRITE_ACTIONS) {
1427
- bus.listen(modelEventName2(tableName, action), async () => {
876
+ bus.listen(modelEventName(tableName, action), async () => {
1428
877
  const tags = cacheTagsForModelWrite(tableName, action);
1429
878
  if (tags.length === 0) {
1430
879
  return;
@@ -1466,46 +915,8 @@ var listenersProvider = {
1466
915
  };
1467
916
  var listeners_default = listenersProvider;
1468
917
 
1469
- // ../../src/core/auth/policy.ts
1470
- var BLOCKED_POLICY_ACTIONS = new Set([
1471
- "constructor",
1472
- "toString",
1473
- "valueOf",
1474
- "hasOwnProperty",
1475
- "isPrototypeOf",
1476
- "propertyIsEnumerable",
1477
- "__proto__"
1478
- ]);
1479
-
1480
- class PolicyGate {
1481
- constructor() {}
1482
- policies = new Map;
1483
- register(resource, policy) {
1484
- this.policies.set(resource, policy);
1485
- }
1486
- allows(resource, action, user, model) {
1487
- const policy = this.policies.get(resource);
1488
- if (!policy) {
1489
- return false;
1490
- }
1491
- if (BLOCKED_POLICY_ACTIONS.has(action) || !(action in policy)) {
1492
- return false;
1493
- }
1494
- const handler = policy[action];
1495
- if (typeof handler !== "function") {
1496
- return false;
1497
- }
1498
- const resolvedUser = user === undefined ? currentAuthUser() : user;
1499
- return model === undefined ? handler.call(policy, resolvedUser) : handler.call(policy, resolvedUser, model);
1500
- }
1501
- authorize(resource, action, user, model) {
1502
- if (!this.allows(resource, action, user, model)) {
1503
- throw new ForbiddenError2;
1504
- }
1505
- }
1506
- }
1507
-
1508
918
  // ../../src/bootstrap/providers/policy.ts
919
+ import { PolicyGate } from "@getstrata/core/auth/policy";
1509
920
  var policyProvider = {
1510
921
  name: "core.policy",
1511
922
  register({ container }) {
@@ -1514,2349 +925,58 @@ var policyProvider = {
1514
925
  };
1515
926
  var policy_default = policyProvider;
1516
927
 
1517
- // ../../src/core/pagination/index.ts
1518
- function buildPaginationMeta(input) {
1519
- const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
1520
- return {
1521
- page: input.page,
1522
- per_page: input.perPage,
1523
- total: input.total,
1524
- last_page: lastPage
1525
- };
1526
- }
928
+ // ../../src/bootstrap/providers/queue.ts
929
+ import {
930
+ createAppQueue,
931
+ createFailedJobService,
932
+ FAILED_JOB_SERVICE_TOKEN
933
+ } from "@getstrata/core/queue/createAppQueue";
1527
934
 
1528
- // ../../src/core/database/errors.ts
1529
- function isPostgresError(error) {
1530
- return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
935
+ // ../../src/bootstrap/queue/defaultJobs.ts
936
+ import DispatchWebhookJob from "@getstrata/core/jobs/dispatchWebhookJob";
937
+ import InvalidateCacheTagsJob2 from "@getstrata/core/jobs/invalidateCacheTagsJob";
938
+ import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
939
+ import { resolveApplicationCache as resolveApplicationCache2 } from "@getstrata/core/runtime/applicationRegistry";
940
+ function registerDefaultJobs() {
941
+ jobRegistry.register("cache.invalidate-tags", () => {
942
+ return new InvalidateCacheTagsJob2(resolveApplicationCache2());
943
+ });
944
+ jobRegistry.register("webhook.dispatch", () => new DispatchWebhookJob);
1531
945
  }
1532
- function getPostgresSqlState(error) {
1533
- if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
1534
- return error.errno;
946
+
947
+ // ../../src/bootstrap/providers/queue.ts
948
+ var queueProvider = {
949
+ name: "core.queue",
950
+ register({ container, config }) {
951
+ const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
952
+ const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
953
+ config.set("queue.driver", driver);
954
+ const failedJobs = createFailedJobService();
955
+ container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
956
+ container.set(CORE_QUEUE_TOKEN, createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs, registerDefaultJobs));
1535
957
  }
1536
- if (typeof error.errno === "number") {
1537
- return String(error.errno).padStart(5, "0");
958
+ };
959
+ var queue_default = queueProvider;
960
+
961
+ // ../../src/bootstrap/providers/storage.ts
962
+ import { createStorageDriver, StorageManager } from "@getstrata/core/storage/storage";
963
+ var storageProvider = {
964
+ name: "core.storage",
965
+ register({ dependencies }) {
966
+ dependencies.storage = new StorageManager(createStorageDriver());
1538
967
  }
1539
- if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
1540
- return error.code;
1541
- }
1542
- return;
1543
- }
1544
- function mapDatabaseError(error) {
1545
- if (error instanceof HttpError) {
1546
- return error;
1547
- }
1548
- if (!isPostgresError(error)) {
1549
- const message = error instanceof Error ? error.message : "Database operation failed.";
1550
- return new BadRequestError(message);
1551
- }
1552
- const sqlState = getPostgresSqlState(error);
1553
- switch (sqlState) {
1554
- case "23505":
1555
- return new ConflictError(error.detail ?? "A record with these values already exists.", {
1556
- constraint: error.constraint
1557
- });
1558
- case "23503":
1559
- return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
1560
- constraint: error.constraint
1561
- });
1562
- case "23502":
1563
- return new BadRequestError(error.detail ?? "Required field is missing.", {
1564
- constraint: error.constraint
1565
- });
1566
- case "23514":
1567
- return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
1568
- constraint: error.constraint
1569
- });
1570
- default:
1571
- return new BadRequestError(error.message ?? "Database operation failed.", {
1572
- code: error.code,
1573
- sqlState
1574
- });
1575
- }
1576
- }
1577
- async function withDatabaseErrorHandling(operation) {
1578
- try {
1579
- return await operation();
1580
- } catch (error) {
1581
- throw mapDatabaseError(error);
1582
- }
1583
- }
1584
-
1585
- // ../../src/core/database/query.ts
1586
- function quoteIdentifier(identifier) {
1587
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
1588
- throw new Error(`Invalid SQL identifier: ${identifier}`);
1589
- }
1590
- return `"${identifier}"`;
1591
- }
1592
- function qualifyColumn(tableName, column) {
1593
- return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
1594
- }
1595
- function resolveQualifiedColumn(defaultTable, columnName) {
1596
- if (columnName.includes(".")) {
1597
- const [table, column] = columnName.split(".", 2);
1598
- if (!table || !column) {
1599
- throw new Error(`Invalid qualified column: ${columnName}`);
1600
- }
1601
- return qualifyColumn(table, column);
1602
- }
1603
- return qualifyColumn(defaultTable, columnName);
1604
- }
1605
- function parseQualifiedColumn(reference) {
1606
- const [table, column] = reference.split(".", 2);
1607
- if (!table || !column) {
1608
- throw new Error(`Join columns must be qualified as table.column: ${reference}`);
1609
- }
1610
- return { table, column };
1611
- }
1612
- function normalizeDirection(direction = "ASC") {
1613
- return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
1614
- }
1615
- function isQueryOperator(value) {
1616
- return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
1617
- }
1618
- function pushParam(values, value) {
1619
- values.push(value);
1620
- return `$${values.length}`;
1621
- }
1622
- function buildInClause(column, values, params) {
1623
- if (values.length === 0) {
1624
- return "1 = 0";
1625
- }
1626
- const placeholders = values.map((value) => pushParam(params, value)).join(", ");
1627
- return `${column} IN (${placeholders})`;
1628
- }
1629
- function buildOperatorClauses(column, operator, params) {
1630
- const clauses = [];
1631
- if (operator.isNull === true) {
1632
- clauses.push(`${column} IS NULL`);
1633
- }
1634
- if (operator.isNull === false) {
1635
- clauses.push(`${column} IS NOT NULL`);
1636
- }
1637
- if (operator.eq !== undefined) {
1638
- if (operator.eq === null) {
1639
- clauses.push(`${column} IS NULL`);
1640
- } else {
1641
- clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
1642
- }
1643
- }
1644
- if (operator.in !== undefined) {
1645
- clauses.push(buildInClause(column, operator.in, params));
1646
- }
1647
- if (operator.gt !== undefined) {
1648
- clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
1649
- }
1650
- if (operator.gte !== undefined) {
1651
- clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
1652
- }
1653
- if (operator.lt !== undefined) {
1654
- clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
1655
- }
1656
- if (operator.lte !== undefined) {
1657
- clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
1658
- }
1659
- if (operator.ilike !== undefined) {
1660
- clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
1661
- }
1662
- if (operator.tsMatch !== undefined) {
1663
- clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
1664
- }
1665
- return clauses;
1666
- }
1667
- function appendWhereParts(tableName, where, params) {
1668
- const clauses = [];
1669
- for (const [columnName, filterValue] of Object.entries(where)) {
1670
- if (filterValue === undefined) {
1671
- continue;
1672
- }
1673
- const column = resolveQualifiedColumn(tableName, columnName);
1674
- if (Array.isArray(filterValue)) {
1675
- clauses.push(buildInClause(column, filterValue, params));
1676
- continue;
1677
- }
1678
- if (isQueryOperator(filterValue)) {
1679
- clauses.push(...buildOperatorClauses(column, filterValue, params));
1680
- continue;
1681
- }
1682
- if (filterValue === null) {
1683
- clauses.push(`${column} IS NULL`);
1684
- continue;
1685
- }
1686
- clauses.push(`${column} = ${pushParam(params, filterValue)}`);
1687
- }
1688
- return clauses.join(" AND ");
1689
- }
1690
- function buildWhereNodeClause(tableName, node, params) {
1691
- if ("where" in node) {
1692
- return appendWhereParts(tableName, node.where, params);
1693
- }
1694
- const grouped = buildWhereGroupClause(tableName, node.group, params);
1695
- if (!grouped) {
1696
- return "";
1697
- }
1698
- return grouped.includes(" OR ") ? `(${grouped})` : grouped;
1699
- }
1700
- function buildWhereGroupClause(tableName, nodes, params) {
1701
- let result = "";
1702
- for (const node of nodes) {
1703
- const part = buildWhereNodeClause(tableName, node, params);
1704
- if (!part) {
1705
- continue;
1706
- }
1707
- if (!result) {
1708
- result = part;
1709
- continue;
1710
- }
1711
- result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
1712
- }
1713
- if (!result) {
1714
- return "";
1715
- }
1716
- return result;
1717
- }
1718
- function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
1719
- const nodes = [];
1720
- if (Object.keys(where).length > 0) {
1721
- nodes.push({ kind: "and", where });
1722
- }
1723
- nodes.push(...whereNodes);
1724
- const combined = buildWhereGroupClause(tableName, nodes, params);
1725
- return {
1726
- clause: combined ? ` WHERE ${combined}` : "",
1727
- params
1728
- };
1729
- }
1730
- function resolveSoftDeleteColumn(table) {
1731
- if (!table.softDeletes) {
1732
- return null;
1733
- }
1734
- if (table.softDeletes === true) {
1735
- return "deleted_at";
1736
- }
1737
- return table.softDeletes.column ?? "deleted_at";
1738
- }
1739
- function appendSoftDeleteScope(table, options, clauses) {
1740
- const column = resolveSoftDeleteColumn(table);
1741
- if (!column) {
1742
- return;
1743
- }
1744
- const qualifiedColumn = qualifyColumn(table.name, column);
1745
- if (options.onlyTrashed) {
1746
- clauses.push(`${qualifiedColumn} IS NOT NULL`);
1747
- return;
1748
- }
1749
- if (!options.withTrashed) {
1750
- clauses.push(`${qualifiedColumn} IS NULL`);
1751
- }
1752
- }
1753
- function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
1754
- const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
1755
- const softDeleteClauses = [];
1756
- appendSoftDeleteScope(table, options, softDeleteClauses);
1757
- if (softDeleteClauses.length === 0) {
1758
- return { clause, params: whereParams };
1759
- }
1760
- const base = clause.replace(/^ WHERE /, "");
1761
- const scope = softDeleteClauses.join(" AND ");
1762
- return {
1763
- clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
1764
- params: whereParams
1765
- };
1766
- }
1767
- function isQueryOrder(value) {
1768
- return "column" in value;
1769
- }
1770
- function normalizeOrderBy(orderBy) {
1771
- if (!orderBy) {
1772
- return [];
1773
- }
1774
- if (Array.isArray(orderBy)) {
1775
- return orderBy;
1776
- }
1777
- if (isQueryOrder(orderBy)) {
1778
- return [orderBy];
1779
- }
1780
- return Object.entries(orderBy).map(([column, direction]) => ({
1781
- column,
1782
- direction
1783
- }));
1784
- }
1785
- function buildOrderByClause(tableName, orderBy) {
1786
- const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
1787
- return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
1788
- });
1789
- return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
1790
- }
1791
- function buildGroupByClause(tableName, groupBy) {
1792
- if (!groupBy) {
1793
- return "";
1794
- }
1795
- const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
1796
- const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
1797
- return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
1798
- }
1799
- function buildHavingClause(tableName, having, params) {
1800
- if (!having) {
1801
- return "";
1802
- }
1803
- const body = appendWhereParts(tableName, having, params);
1804
- return body.length > 0 ? ` HAVING ${body}` : "";
1805
- }
1806
- function buildJoinClause(joins = []) {
1807
- return joins.map((join3) => {
1808
- const joinType = join3.type === "left" ? "LEFT JOIN" : "INNER JOIN";
1809
- const onClause = join3.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
1810
- return ` ${joinType} ${quoteIdentifier(join3.table)} ON ${onClause}`;
1811
- }).join("");
1812
- }
1813
- function buildLimitClause(limit) {
1814
- if (limit === undefined) {
1815
- return "";
1816
- }
1817
- if (!Number.isInteger(limit) || limit <= 0) {
1818
- throw new Error("Query limit must be a positive integer.");
1819
- }
1820
- return ` LIMIT ${limit}`;
1821
- }
1822
- function buildOffsetClause(offset) {
1823
- if (offset === undefined) {
1824
- return "";
1825
- }
1826
- if (!Number.isInteger(offset) || offset < 0) {
1827
- throw new Error("Query offset must be a non-negative integer.");
1828
- }
1829
- return ` OFFSET ${offset}`;
1830
- }
1831
- function buildReturningColumns(table) {
1832
- return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
1833
- }
1834
- function buildSelectList(table, select, params = []) {
1835
- if (!select || select.length === 0) {
1836
- return buildReturningColumns(table);
1837
- }
1838
- return select.map((item) => {
1839
- if (item.kind === "column") {
1840
- const column2 = qualifyColumn(item.table, item.column);
1841
- return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
1842
- }
1843
- if (item.kind === "literalText") {
1844
- return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
1845
- }
1846
- const column = qualifyColumn(item.table, item.column);
1847
- const placeholder = pushParam(params, item.query);
1848
- return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
1849
- }).join(", ");
1850
- }
1851
- function getDefinedColumnEntries(table, values, options = {}) {
1852
- const record = values;
1853
- const excluded = new Set(options.exclude ?? []);
1854
- return table.columns.flatMap((column) => {
1855
- if (excluded.has(column) || !Object.hasOwn(record, column)) {
1856
- return [];
1857
- }
1858
- const value = record[column];
1859
- if (value === undefined) {
1860
- return [];
1861
- }
1862
- return [[column, value]];
1863
- });
1864
- }
1865
- function buildSelectQuery(table, options = {}, whereNodes = []) {
1866
- const params = [];
1867
- const columns = buildSelectList(table, options.select, params);
1868
- const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
1869
- const joins = buildJoinClause(options.joins);
1870
- const groupBy = buildGroupByClause(table.name, options.groupBy);
1871
- const havingClause = buildHavingClause(table.name, options.having, params);
1872
- const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
1873
- const limit = buildLimitClause(options.limit);
1874
- const offset = buildOffsetClause(options.offset);
1875
- return {
1876
- text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
1877
- params
1878
- };
1879
- }
1880
- function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
1881
- const params = [];
1882
- const { clause, params: whereParams } = buildQueryWhereClause(table, {
1883
- where,
1884
- withTrashed: options.withTrashed,
1885
- onlyTrashed: options.onlyTrashed
1886
- }, whereNodes);
1887
- params.push(...whereParams);
1888
- const joins = buildJoinClause(options.joins);
1889
- const groupBy = buildGroupByClause(table.name, options.groupBy);
1890
- return {
1891
- text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
1892
- params
1893
- };
1894
- }
1895
- function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
1896
- assertSafeProjectionExpression(expression);
1897
- const params = [];
1898
- const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
1899
- params.push(...whereParams);
1900
- const joins = buildJoinClause(options.joins);
1901
- const groupBy = buildGroupByClause(table.name, options.groupBy);
1902
- const orderBy = buildOrderByClause(table.name, options.orderBy);
1903
- const limit = buildLimitClause(options.limit);
1904
- return {
1905
- text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
1906
- params
1907
- };
1908
- }
1909
- var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
1910
- function assertSafeProjectionExpression(expression) {
1911
- if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
1912
- throw new Error(`Unsafe projection expression: ${expression}`);
1913
- }
1914
- }
1915
- function buildGroupedCountQuery(table, column, where = {}, options = {}) {
1916
- const qualifiedColumn = qualifyColumn(table.name, column);
1917
- const { clause, params } = buildQueryWhereClause(table, {
1918
- where,
1919
- ...options
1920
- });
1921
- return {
1922
- text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
1923
- params
1924
- };
1925
- }
1926
- function buildInsertQuery(table, values) {
1927
- const entries = getDefinedColumnEntries(table, values);
1928
- if (entries.length === 0) {
1929
- throw new Error(`Cannot insert into ${table.name} without any column values.`);
1930
- }
1931
- const params = [];
1932
- const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
1933
- const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
1934
- const returningColumns = buildReturningColumns(table);
1935
- return {
1936
- text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
1937
- params
1938
- };
1939
- }
1940
- function buildUpdateQuery(table, id, changes) {
1941
- const entries = getDefinedColumnEntries(table, changes, {
1942
- exclude: [table.primaryKey]
1943
- });
1944
- if (entries.length === 0) {
1945
- throw new Error(`Cannot update ${table.name} without any changed column values.`);
1946
- }
1947
- const params = [];
1948
- const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
1949
- const primaryKeyPlaceholder = pushParam(params, id);
1950
- const returningColumns = buildReturningColumns(table);
1951
- const scopeClauses = [];
1952
- appendSoftDeleteScope(table, {}, scopeClauses);
1953
- const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
1954
- return {
1955
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
1956
- params
1957
- };
1958
- }
1959
- function buildSoftDeleteByIdQuery(table, id, deletedAt) {
1960
- const deletedAtColumn = resolveSoftDeleteColumn(table);
1961
- if (!deletedAtColumn) {
1962
- throw new Error(`Table ${table.name} does not support soft deletes.`);
1963
- }
1964
- const returningColumns = buildReturningColumns(table);
1965
- const scopeClauses = [];
1966
- appendSoftDeleteScope(table, {}, scopeClauses);
1967
- const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
1968
- return {
1969
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
1970
- params: [deletedAt, id]
1971
- };
1972
- }
1973
- function buildRestoreByIdQuery(table, id) {
1974
- const deletedAtColumn = resolveSoftDeleteColumn(table);
1975
- if (!deletedAtColumn) {
1976
- throw new Error(`Table ${table.name} does not support soft deletes.`);
1977
- }
1978
- const returningColumns = buildReturningColumns(table);
1979
- return {
1980
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
1981
- params: [null, id]
1982
- };
1983
- }
1984
- function buildDeleteByIdQuery(table, id) {
1985
- return {
1986
- text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
1987
- params: [id]
1988
- };
1989
- }
1990
-
1991
- // ../../src/core/database/relationships.ts
1992
- function indexHasManyRelation(parents, children, relation) {
1993
- const groups = new Map;
1994
- for (const parent of parents) {
1995
- groups.set(parent[relation.localKey], []);
1996
- }
1997
- for (const child of children) {
1998
- const key = child[relation.foreignKey];
1999
- const group = groups.get(key);
2000
- if (!group) {
2001
- continue;
2002
- }
2003
- group.push(child);
2004
- }
2005
- return groups;
2006
- }
2007
- function indexBelongsToRelation(children, parents, relation) {
2008
- const parentsById = new Map;
2009
- for (const parent of parents) {
2010
- parentsById.set(parent[relation.ownerKey], parent);
2011
- }
2012
- const result = new Map;
2013
- for (const child of children) {
2014
- const foreignKey = child[relation.foreignKey];
2015
- const parent = parentsById.get(foreignKey);
2016
- if (parent) {
2017
- result.set(foreignKey, parent);
2018
- }
2019
- }
2020
- return result;
2021
- }
2022
- function indexMorphManyRelation(parents, children, relation) {
2023
- const groups = new Map;
2024
- for (const parent of parents) {
2025
- groups.set(parent[relation.localKey], []);
2026
- }
2027
- for (const child of children) {
2028
- if (child[relation.morphTypeKey] !== relation.morphType) {
2029
- continue;
2030
- }
2031
- const key = child[relation.morphIdKey];
2032
- const group = groups.get(key);
2033
- if (!group) {
2034
- continue;
2035
- }
2036
- group.push(child);
2037
- }
2038
- return groups;
2039
- }
2040
- function indexMorphToRelation(children, parentsByType, relation) {
2041
- const result = new Map;
2042
- for (const child of children) {
2043
- const morphType = String(child[relation.morphTypeKey]);
2044
- const parents = parentsByType.get(morphType);
2045
- if (!parents) {
2046
- continue;
2047
- }
2048
- const parent = parents.get(child[relation.morphIdKey]);
2049
- if (parent) {
2050
- result.set(child[relation.morphIdKey], parent);
2051
- }
2052
- }
2053
- return result;
2054
- }
2055
-
2056
- // ../../src/core/database/boundConnection.ts
2057
- var boundConnectionHolder = {
2058
- connection: null
2059
- };
2060
- function getBoundDatabaseConnection() {
2061
- return boundConnectionHolder.connection;
2062
- }
2063
-
2064
- // ../../src/core/database/repositoryConnection.ts
2065
- function resolveRepositoryConnection() {
2066
- return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
2067
- }
2068
- var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
2069
- apply(_target, _thisArg, args) {
2070
- return resolveRepositoryConnection()(...args);
2071
- },
2072
- get(_target, property) {
2073
- const connection = resolveRepositoryConnection();
2074
- const value = connection[property];
2075
- return typeof value === "function" ? value.bind(connection) : value;
2076
- }
2077
- });
2078
-
2079
- // ../../src/core/database/whereBuilder.ts
2080
- class WhereBuilder {
2081
- nodes = [];
2082
- where(where) {
2083
- this.nodes.push({ kind: "and", where });
2084
- return this;
2085
- }
2086
- orWhere(where) {
2087
- this.nodes.push({ kind: "or", where });
2088
- return this;
2089
- }
2090
- whereGroup(fn) {
2091
- const nested = new WhereBuilder;
2092
- fn(nested);
2093
- if (nested.nodes.length > 0) {
2094
- this.nodes.push({ kind: "and", group: nested.nodes });
2095
- }
2096
- return this;
2097
- }
2098
- orWhereGroup(fn) {
2099
- const nested = new WhereBuilder;
2100
- fn(nested);
2101
- if (nested.nodes.length > 0) {
2102
- this.nodes.push({ kind: "or", group: nested.nodes });
2103
- }
2104
- return this;
2105
- }
2106
- }
2107
-
2108
- // ../../src/core/database/repositoryQuery.ts
2109
- class RepositoryQuery {
2110
- repository;
2111
- whereClause;
2112
- queryOptions;
2113
- eagerLoads = [];
2114
- whereNodes = [];
2115
- constructor(repository, whereClause = {}, queryOptions = {}) {
2116
- this.repository = repository;
2117
- this.whereClause = whereClause;
2118
- this.queryOptions = queryOptions;
2119
- }
2120
- where(input) {
2121
- if (typeof input === "function") {
2122
- const builder = new WhereBuilder;
2123
- input(builder);
2124
- this.whereNodes.push(...builder.nodes);
2125
- return this;
2126
- }
2127
- this.whereClause = { ...this.whereClause, ...input };
2128
- return this;
2129
- }
2130
- orWhere(input) {
2131
- if (typeof input === "function") {
2132
- const builder = new WhereBuilder;
2133
- input(builder);
2134
- if (builder.nodes.length > 0) {
2135
- this.whereNodes.push({ kind: "or", group: builder.nodes });
2136
- }
2137
- return this;
2138
- }
2139
- this.whereNodes.push({ kind: "or", where: input });
2140
- return this;
2141
- }
2142
- orderBy(orderBy) {
2143
- this.queryOptions = { ...this.queryOptions, orderBy };
2144
- return this;
2145
- }
2146
- limit(limit) {
2147
- this.queryOptions = { ...this.queryOptions, limit };
2148
- return this;
2149
- }
2150
- offset(offset) {
2151
- this.queryOptions = { ...this.queryOptions, offset };
2152
- return this;
2153
- }
2154
- join(left, right) {
2155
- return this.addJoin("inner", left, right);
2156
- }
2157
- leftJoin(left, right) {
2158
- return this.addJoin("left", left, right);
2159
- }
2160
- groupBy(groupBy) {
2161
- this.queryOptions = { ...this.queryOptions, groupBy };
2162
- return this;
2163
- }
2164
- having(having) {
2165
- this.queryOptions = { ...this.queryOptions, having };
2166
- return this;
2167
- }
2168
- withHasMany(as, relation, childRepository, options = {}) {
2169
- this.eagerLoads.push({
2170
- kind: "hasMany",
2171
- as,
2172
- relation,
2173
- repository: childRepository,
2174
- options
2175
- });
2176
- return this;
2177
- }
2178
- withBelongsTo(as, relation, parentRepository, options = {}) {
2179
- this.eagerLoads.push({
2180
- kind: "belongsTo",
2181
- as,
2182
- relation,
2183
- repository: parentRepository,
2184
- options
2185
- });
2186
- return this;
2187
- }
2188
- withMorphMany(as, relation, childRepository, options = {}) {
2189
- this.eagerLoads.push({
2190
- kind: "morphMany",
2191
- as,
2192
- relation,
2193
- repository: childRepository,
2194
- options
2195
- });
2196
- return this;
2197
- }
2198
- withMorphOne(as, relation, childRepository, options = {}) {
2199
- this.eagerLoads.push({
2200
- kind: "morphOne",
2201
- as,
2202
- relation,
2203
- repository: childRepository,
2204
- options
2205
- });
2206
- return this;
2207
- }
2208
- withMorphTo(as, relation, repositoriesByType, options = {}) {
2209
- this.eagerLoads.push({
2210
- kind: "morphTo",
2211
- as,
2212
- relation,
2213
- repository: this.repository,
2214
- morphRepositories: repositoriesByType,
2215
- options
2216
- });
2217
- return this;
2218
- }
2219
- async get() {
2220
- const rows = await this.repository.findAll(this.buildOptions());
2221
- return await this.attach(rows);
2222
- }
2223
- async first() {
2224
- const rows = await this.get();
2225
- return rows[0] ?? null;
2226
- }
2227
- async paginate(options) {
2228
- return await this.repository.paginate({
2229
- ...this.buildOptions(),
2230
- page: options.page,
2231
- perPage: options.perPage
2232
- });
2233
- }
2234
- buildOptions() {
2235
- return {
2236
- ...this.queryOptions,
2237
- where: this.whereClause,
2238
- whereNodes: this.whereNodes
2239
- };
2240
- }
2241
- addJoin(type, left, right) {
2242
- const leftRef = parseQualifiedColumn(left);
2243
- const rightRef = parseQualifiedColumn(right);
2244
- const table = type === "inner" ? rightRef.table : rightRef.table;
2245
- const joins = this.queryOptions.joins ?? [];
2246
- const existing = joins.find((join3) => join3.table === table && join3.type === type);
2247
- if (existing) {
2248
- existing.on.push({ left: leftRef, right: rightRef });
2249
- return this;
2250
- }
2251
- this.queryOptions = {
2252
- ...this.queryOptions,
2253
- joins: [
2254
- ...joins,
2255
- {
2256
- type,
2257
- table,
2258
- on: [{ left: leftRef, right: rightRef }]
2259
- }
2260
- ]
2261
- };
2262
- return this;
2263
- }
2264
- async attach(rows) {
2265
- if (rows.length === 0 || this.eagerLoads.length === 0) {
2266
- return rows.map((row) => ({ ...row }));
2267
- }
2268
- let result = rows.map((row) => ({ ...row }));
2269
- for (const load of this.eagerLoads) {
2270
- if (load.kind === "hasMany") {
2271
- const relation2 = load.relation;
2272
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
2273
- result = result.map((row) => ({
2274
- ...row,
2275
- [load.as]: grouped2.get(row[relation2.localKey]) ?? []
2276
- }));
2277
- continue;
2278
- }
2279
- if (load.kind === "morphMany") {
2280
- const relation2 = load.relation;
2281
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation2, load.options);
2282
- result = result.map((row) => ({
2283
- ...row,
2284
- [load.as]: grouped2.get(row[relation2.localKey]) ?? []
2285
- }));
2286
- continue;
2287
- }
2288
- if (load.kind === "morphOne") {
2289
- const relation2 = load.relation;
2290
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation2, load.options);
2291
- result = result.map((row) => ({
2292
- ...row,
2293
- [load.as]: grouped2.get(row[relation2.localKey])
2294
- }));
2295
- continue;
2296
- }
2297
- if (load.kind === "morphTo") {
2298
- const relation2 = load.relation;
2299
- const grouped2 = await this.repository.loadMorphToForChildren(rows, relation2, load.morphRepositories ?? new Map, load.options);
2300
- result = result.map((row) => ({
2301
- ...row,
2302
- [load.as]: grouped2.get(row[relation2.morphIdKey])
2303
- }));
2304
- continue;
2305
- }
2306
- const relation = load.relation;
2307
- const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
2308
- result = result.map((row) => ({
2309
- ...row,
2310
- [load.as]: grouped.get(row[relation.foreignKey])
2311
- }));
2312
- }
2313
- return result;
2314
- }
2315
- }
2316
-
2317
- // ../../src/core/database/baseRepository.ts
2318
- class BaseRepository5 {
2319
- table;
2320
- connection;
2321
- constructor(table, connection = repositoryConnection) {
2322
- this.table = table;
2323
- this.connection = connection;
2324
- }
2325
- async findAll(options = {}) {
2326
- return await withDatabaseErrorHandling(async () => {
2327
- const { whereNodes, ...queryOptions } = options;
2328
- const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
2329
- return await this.connection.unsafe(text, params);
2330
- });
2331
- }
2332
- async paginate(options) {
2333
- const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
2334
- const total = await this.countWhere(where, {
2335
- withTrashed: options.withTrashed,
2336
- onlyTrashed: options.onlyTrashed,
2337
- joins: options.joins,
2338
- groupBy: options.groupBy
2339
- }, whereNodes);
2340
- const offset = (page - 1) * perPage;
2341
- const data = await this.findAll({
2342
- ...queryOptions,
2343
- where,
2344
- whereNodes,
2345
- limit: perPage,
2346
- offset
2347
- });
2348
- return {
2349
- data,
2350
- meta: buildPaginationMeta({ page, perPage, total })
2351
- };
2352
- }
2353
- async chunk(count, callback, options = {}) {
2354
- if (!Number.isInteger(count) || count <= 0) {
2355
- throw new Error("Chunk size must be a positive integer.");
2356
- }
2357
- let offset = 0;
2358
- while (true) {
2359
- const rows = await this.findAll({
2360
- ...options,
2361
- limit: count,
2362
- offset
2363
- });
2364
- if (rows.length === 0) {
2365
- return;
2366
- }
2367
- const shouldContinue = await callback(rows);
2368
- if (shouldContinue === false || rows.length < count) {
2369
- return;
2370
- }
2371
- offset += count;
2372
- }
2373
- }
2374
- async cursorPaginate(options) {
2375
- const {
2376
- perPage,
2377
- cursor,
2378
- cursorColumn = this.table.primaryKey,
2379
- direction = "asc",
2380
- where = {},
2381
- whereNodes,
2382
- ...queryOptions
2383
- } = options;
2384
- if (!Number.isInteger(perPage) || perPage <= 0) {
2385
- throw new Error("Cursor page size must be a positive integer.");
2386
- }
2387
- const cursorWhere = { ...where };
2388
- if (cursor !== undefined) {
2389
- cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
2390
- }
2391
- const rows = await this.findAll({
2392
- ...queryOptions,
2393
- where: cursorWhere,
2394
- whereNodes,
2395
- orderBy: { [cursorColumn]: direction },
2396
- limit: perPage + 1
2397
- });
2398
- const hasMore = rows.length > perPage;
2399
- const data = hasMore ? rows.slice(0, perPage) : rows;
2400
- const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
2401
- const prevCursor = cursor ?? null;
2402
- return {
2403
- data,
2404
- meta: {
2405
- per_page: perPage,
2406
- next_cursor: nextCursor,
2407
- prev_cursor: prevCursor,
2408
- has_more: hasMore
2409
- }
2410
- };
2411
- }
2412
- async findById(id) {
2413
- return await this.firstOrNull({
2414
- [this.table.primaryKey]: id
2415
- });
2416
- }
2417
- async findByIdOrThrow(id, errorFactory) {
2418
- const record = await this.findById(id);
2419
- if (record) {
2420
- return record;
2421
- }
2422
- throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
2423
- }
2424
- async findByIds(ids) {
2425
- const uniqueIds = [...new Set(ids)];
2426
- if (uniqueIds.length === 0) {
2427
- return [];
2428
- }
2429
- return await this.findWhere({
2430
- [this.table.primaryKey]: uniqueIds
2431
- });
2432
- }
2433
- async firstOrNull(where, options = {}) {
2434
- const [record] = await this.findAll({ ...options, where, limit: 1 });
2435
- return record ?? null;
2436
- }
2437
- async create(values) {
2438
- return await withDatabaseErrorHandling(async () => {
2439
- const { text, params } = buildInsertQuery(this.table, values);
2440
- const [record] = await this.connection.unsafe(text, params);
2441
- if (!record) {
2442
- throw new Error(`Insert into ${this.table.name} did not return a record.`);
2443
- }
2444
- const entity = record;
2445
- await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
2446
- return entity;
2447
- });
2448
- }
2449
- async updateById(id, changes) {
2450
- return await withDatabaseErrorHandling(async () => {
2451
- const { text, params } = buildUpdateQuery(this.table, id, changes);
2452
- const [record] = await this.connection.unsafe(text, params);
2453
- const entity = record ?? null;
2454
- if (entity) {
2455
- await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
2456
- }
2457
- return entity;
2458
- });
2459
- }
2460
- async updateByIdOrThrow(id, changes, errorFactory) {
2461
- const record = await this.updateById(id, changes);
2462
- if (record) {
2463
- return record;
2464
- }
2465
- throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
2466
- }
2467
- async deleteById(id) {
2468
- if (resolveSoftDeleteColumn(this.table)) {
2469
- return await this.softDeleteById(id);
2470
- }
2471
- return await this.forceDeleteById(id);
2472
- }
2473
- async softDeleteById(id) {
2474
- return await withDatabaseErrorHandling(async () => {
2475
- const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
2476
- const [record] = await this.connection.unsafe(text, params);
2477
- if (!record) {
2478
- return false;
2479
- }
2480
- await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
2481
- return true;
2482
- });
2483
- }
2484
- async forceDeleteById(id) {
2485
- return await withDatabaseErrorHandling(async () => {
2486
- const { text, params } = buildDeleteByIdQuery(this.table, id);
2487
- const [row] = await this.connection.unsafe(text, params);
2488
- if (!row) {
2489
- return false;
2490
- }
2491
- await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
2492
- id
2493
- });
2494
- return true;
2495
- });
2496
- }
2497
- async restoreById(id) {
2498
- return await withDatabaseErrorHandling(async () => {
2499
- const { text, params } = buildRestoreByIdQuery(this.table, id);
2500
- const [record] = await this.connection.unsafe(text, params);
2501
- if (!record) {
2502
- return null;
2503
- }
2504
- const entity = record;
2505
- await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
2506
- return entity;
2507
- });
2508
- }
2509
- withConnection(connection) {
2510
- const clone = Object.create(Object.getPrototypeOf(this));
2511
- Object.assign(clone, this);
2512
- clone.connection = connection;
2513
- return clone;
2514
- }
2515
- getConnection() {
2516
- return this.connection;
2517
- }
2518
- getTable() {
2519
- return this.table;
2520
- }
2521
- query(where = {}) {
2522
- return new RepositoryQuery(this, where);
2523
- }
2524
- async findWhere(where, options = {}) {
2525
- return await this.findAll({ ...options, where });
2526
- }
2527
- async countWhere(where = {}, options = {}, whereNodes = []) {
2528
- const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
2529
- const [row] = await this.connection.unsafe(text, params);
2530
- return Number(row?.count ?? 0);
2531
- }
2532
- async averageColumn(column, where = {}) {
2533
- const qualifiedColumn = qualifyColumn(this.table.name, column);
2534
- return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
2535
- }
2536
- async averageExpression(expression, alias, where = {}) {
2537
- const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
2538
- const [row] = await this.connection.unsafe(text, params);
2539
- return Math.round(Number(row?.[alias] ?? 0));
2540
- }
2541
- async pluckNumberValues(expression, alias, options = {}) {
2542
- const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
2543
- const rows = await this.connection.unsafe(text, params);
2544
- return rows.flatMap((row) => {
2545
- const value = row[alias];
2546
- return value === null || value === undefined ? [] : [Number(value)];
2547
- });
2548
- }
2549
- async countGroupedBy(column, where = {}) {
2550
- const { text, params } = buildGroupedCountQuery(this.table, column, where);
2551
- const rows = await this.connection.unsafe(text, params);
2552
- return rows.map(({ value, count }) => ({
2553
- value,
2554
- count: Number(count)
2555
- }));
2556
- }
2557
- async findByHasManyRelation(relation, parentId, options = {}) {
2558
- return await this.findWhere({
2559
- [relation.foreignKey]: parentId
2560
- }, options);
2561
- }
2562
- async loadHasManyForParents(parents, relation, options = {}) {
2563
- if (parents.length === 0) {
2564
- return indexHasManyRelation(parents, [], relation);
2565
- }
2566
- const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
2567
- const children = await this.findWhere({
2568
- [relation.foreignKey]: parentIds
2569
- }, options);
2570
- return indexHasManyRelation(parents, children, relation);
2571
- }
2572
- async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
2573
- if (children.length === 0) {
2574
- return new Map;
2575
- }
2576
- const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
2577
- const parents = await parentRepository.withConnection(this.connection).findWhere({
2578
- [relation.ownerKey]: ownerIds
2579
- }, options);
2580
- return indexBelongsToRelation(children, parents, relation);
2581
- }
2582
- async loadMorphManyForParents(parents, relation, options = {}) {
2583
- if (parents.length === 0) {
2584
- return indexMorphManyRelation(parents, [], relation);
2585
- }
2586
- const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
2587
- const children = await this.findWhere({
2588
- [relation.morphTypeKey]: relation.morphType,
2589
- [relation.morphIdKey]: parentIds
2590
- }, options);
2591
- return indexMorphManyRelation(parents, children, relation);
2592
- }
2593
- async loadMorphOneForParents(parents, relation, options = {}) {
2594
- const grouped = await this.loadMorphManyForParents(parents, relation, options);
2595
- const result = new Map;
2596
- for (const parent of parents) {
2597
- const matches = grouped.get(parent[relation.localKey]) ?? [];
2598
- result.set(parent[relation.localKey], matches[0]);
2599
- }
2600
- return result;
2601
- }
2602
- async loadMorphToForChildren(children, relation, repositoriesByType, options = {}) {
2603
- if (children.length === 0) {
2604
- return new Map;
2605
- }
2606
- const idsByType = new Map;
2607
- for (const child of children) {
2608
- const morphType = String(child[relation.morphTypeKey]);
2609
- const morphId = child[relation.morphIdKey];
2610
- const ids = idsByType.get(morphType) ?? new Set;
2611
- ids.add(morphId);
2612
- idsByType.set(morphType, ids);
2613
- }
2614
- const parentsByType = new Map;
2615
- for (const [morphType, ids] of idsByType) {
2616
- const repository = repositoriesByType.get(morphType);
2617
- if (!repository) {
2618
- continue;
2619
- }
2620
- const ownerKey = repository.getTable().primaryKey;
2621
- const parents = await repository.withConnection(this.connection).findWhere({
2622
- [ownerKey]: [...ids]
2623
- }, options);
2624
- const indexed = new Map;
2625
- for (const parent of parents) {
2626
- indexed.set(parent[ownerKey], parent);
2627
- }
2628
- parentsByType.set(morphType, indexed);
2629
- }
2630
- return indexMorphToRelation(children, parentsByType, relation);
2631
- }
2632
- }
2633
- var baseRepository_default = BaseRepository5;
2634
- // ../../src/core/database/model.ts
2635
- var modelRepositories = new WeakMap;
2636
- var modelGlobalScopes = new WeakMap;
2637
- var modelBooted = new WeakSet;
2638
- // ../../src/core/database/schema/columnDefinition.ts
2639
- class ColumnDefinition {
2640
- name;
2641
- kind;
2642
- length;
2643
- isNullable = false;
2644
- isPrimary = false;
2645
- isUnique = false;
2646
- autoIncrement = false;
2647
- defaultValue;
2648
- checkExpression;
2649
- foreignKey;
2650
- constructor(name, kind) {
2651
- this.name = name;
2652
- this.kind = kind;
2653
- }
2654
- nullable() {
2655
- this.isNullable = true;
2656
- return this;
2657
- }
2658
- notNullable() {
2659
- this.isNullable = false;
2660
- return this;
2661
- }
2662
- default(value) {
2663
- if (typeof value === "boolean") {
2664
- this.defaultValue = value ? "TRUE" : "FALSE";
2665
- return this;
2666
- }
2667
- if (typeof value === "number") {
2668
- this.defaultValue = String(value);
2669
- return this;
2670
- }
2671
- this.defaultValue = `'${value.replace(/'/g, "''")}'`;
2672
- return this;
2673
- }
2674
- defaultRaw(expression) {
2675
- this.defaultValue = expression;
2676
- return this;
2677
- }
2678
- unique() {
2679
- this.isUnique = true;
2680
- return this;
2681
- }
2682
- primary() {
2683
- this.isPrimary = true;
2684
- return this;
2685
- }
2686
- check(expression) {
2687
- this.checkExpression = expression;
2688
- return this;
2689
- }
2690
- }
2691
-
2692
- class ForeignIdColumnDefinition extends ColumnDefinition {
2693
- constructor(name) {
2694
- super(name, "foreignId");
2695
- this.notNullable();
2696
- }
2697
- references(table, column = "id") {
2698
- this.foreignKey = {
2699
- referencesTable: table,
2700
- referencesColumn: column
2701
- };
2702
- return this;
2703
- }
2704
- constrained(table) {
2705
- const referencesTable = table ?? inferReferencedTable(this.name);
2706
- return this.references(referencesTable);
2707
- }
2708
- cascadeOnDelete() {
2709
- if (!this.foreignKey) {
2710
- throw new Error(`Foreign key is not defined for column ${this.name}`);
2711
- }
2712
- this.foreignKey.onDelete = "cascade";
2713
- return this;
2714
- }
2715
- nullOnDelete() {
2716
- if (!this.foreignKey) {
2717
- throw new Error(`Foreign key is not defined for column ${this.name}`);
2718
- }
2719
- this.foreignKey.onDelete = "set null";
2720
- return this;
2721
- }
2722
- }
2723
- function inferReferencedTable(columnName) {
2724
- if (!columnName.endsWith("_id")) {
2725
- throw new Error(`Cannot infer referenced table from column ${columnName}`);
2726
- }
2727
- return columnName.slice(0, -3);
2728
- }
2729
-
2730
- // ../../src/core/database/schema/blueprint.ts
2731
- class Blueprint {
2732
- table;
2733
- action;
2734
- columns = [];
2735
- indexes = [];
2736
- droppedColumns = [];
2737
- droppedIndexes = [];
2738
- constructor(table, action) {
2739
- this.table = table;
2740
- this.action = action;
2741
- }
2742
- id(name = "id") {
2743
- const column = new ColumnDefinition(name, "id");
2744
- column.primary();
2745
- column.autoIncrement = true;
2746
- this.columns.push(column);
2747
- return column;
2748
- }
2749
- string(name, length) {
2750
- const column = new ColumnDefinition(name, "string");
2751
- column.length = length;
2752
- column.notNullable();
2753
- this.columns.push(column);
2754
- return column;
2755
- }
2756
- text(name) {
2757
- const column = new ColumnDefinition(name, "text");
2758
- column.notNullable();
2759
- this.columns.push(column);
2760
- return column;
2761
- }
2762
- boolean(name) {
2763
- const column = new ColumnDefinition(name, "boolean");
2764
- column.notNullable();
2765
- this.columns.push(column);
2766
- return column;
2767
- }
2768
- integer(name) {
2769
- const column = new ColumnDefinition(name, "integer");
2770
- column.notNullable();
2771
- this.columns.push(column);
2772
- return column;
2773
- }
2774
- bigInteger(name) {
2775
- const column = new ColumnDefinition(name, "bigInteger");
2776
- column.notNullable();
2777
- this.columns.push(column);
2778
- return column;
2779
- }
2780
- timestamp(name) {
2781
- const column = new ColumnDefinition(name, "timestamp");
2782
- column.notNullable();
2783
- this.columns.push(column);
2784
- return column;
2785
- }
2786
- json(name) {
2787
- const column = new ColumnDefinition(name, "json");
2788
- column.notNullable();
2789
- this.columns.push(column);
2790
- return column;
2791
- }
2792
- jsonb(name) {
2793
- const column = new ColumnDefinition(name, "jsonb");
2794
- column.notNullable();
2795
- this.columns.push(column);
2796
- return column;
2797
- }
2798
- foreignId(name) {
2799
- const column = new ForeignIdColumnDefinition(name);
2800
- this.columns.push(column);
2801
- return column;
2802
- }
2803
- timestamps() {
2804
- this.timestamp("created_at").defaultRaw("NOW()");
2805
- this.timestamp("updated_at").defaultRaw("NOW()");
2806
- }
2807
- softDeletes() {
2808
- this.timestamp("deleted_at").nullable();
2809
- }
2810
- dropColumn(name) {
2811
- this.droppedColumns.push(name);
2812
- }
2813
- dropSoftDeletes() {
2814
- this.dropColumn("deleted_at");
2815
- this.dropIndex(`idx_${this.table}_deleted_at`);
2816
- }
2817
- dropIndex(name) {
2818
- this.droppedIndexes.push(name);
2819
- }
2820
- unique(columns, name) {
2821
- this.indexes.push({
2822
- name,
2823
- columns: Array.isArray(columns) ? columns : [columns],
2824
- kind: "unique"
2825
- });
2826
- }
2827
- index(columns, options = {}) {
2828
- this.indexes.push({
2829
- name: options.name,
2830
- columns: Array.isArray(columns) ? columns : [columns],
2831
- kind: "index",
2832
- order: options.order
2833
- });
2834
- }
2835
- partialIndex(columns, where, nameOrOptions) {
2836
- const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
2837
- this.indexes.push({
2838
- name: options.name,
2839
- columns: Array.isArray(columns) ? columns : [columns],
2840
- kind: options.unique ? "uniquePartial" : "partial",
2841
- where
2842
- });
2843
- }
2844
- fullText(columns, name) {
2845
- this.indexes.push({
2846
- name,
2847
- columns: Array.isArray(columns) ? columns : [columns],
2848
- kind: "fullText"
2849
- });
2850
- }
2851
- ginIndex(column, name) {
2852
- this.indexes.push({
2853
- name,
2854
- columns: [column],
2855
- kind: "gin"
2856
- });
2857
- }
2858
- }
2859
- // ../../src/core/database/schema/errors.ts
2860
- class UnsupportedSchemaFeatureError extends Error {
2861
- constructor(feature, driver) {
2862
- super(`${feature} is not supported for the ${driver} driver`);
2863
- this.name = "UnsupportedSchemaFeatureError";
2864
- }
2865
- }
2866
- // ../../src/core/database/schema/grammars/grammar.ts
2867
- function compileColumnType(driver, column) {
2868
- switch (column.kind) {
2869
- case "id":
2870
- return compileIdType(driver);
2871
- case "string":
2872
- return compileStringType(driver, column.length);
2873
- case "text":
2874
- return compileTextType(driver);
2875
- case "boolean":
2876
- return compileBooleanType(driver);
2877
- case "integer":
2878
- case "foreignId":
2879
- return compileIntegerType(driver);
2880
- case "bigInteger":
2881
- return compileBigIntegerType(driver);
2882
- case "timestamp":
2883
- return compileTimestampType(driver);
2884
- case "json":
2885
- return compileJsonType(driver);
2886
- case "jsonb":
2887
- return compileJsonbType(driver);
2888
- default:
2889
- throw new Error(`Unsupported column kind: ${column.kind}`);
2890
- }
2891
- }
2892
- function compileIdType(driver) {
2893
- switch (driver) {
2894
- case "pgsql":
2895
- return "SERIAL";
2896
- case "mysql":
2897
- return "BIGINT UNSIGNED";
2898
- case "sqlite":
2899
- return "INTEGER";
2900
- }
2901
- }
2902
- function compileStringType(driver, length) {
2903
- switch (driver) {
2904
- case "pgsql":
2905
- return "TEXT";
2906
- case "mysql":
2907
- return length ? `VARCHAR(${length})` : "VARCHAR(255)";
2908
- case "sqlite":
2909
- return "TEXT";
2910
- }
2911
- }
2912
- function compileTextType(driver) {
2913
- switch (driver) {
2914
- case "pgsql":
2915
- case "sqlite":
2916
- return "TEXT";
2917
- case "mysql":
2918
- return "TEXT";
2919
- }
2920
- }
2921
- function compileBooleanType(driver) {
2922
- switch (driver) {
2923
- case "pgsql":
2924
- return "BOOLEAN";
2925
- case "mysql":
2926
- return "BOOLEAN";
2927
- case "sqlite":
2928
- return "INTEGER";
2929
- }
2930
- }
2931
- function compileIntegerType(driver) {
2932
- switch (driver) {
2933
- case "pgsql":
2934
- return "INTEGER";
2935
- case "mysql":
2936
- return "INT";
2937
- case "sqlite":
2938
- return "INTEGER";
2939
- }
2940
- }
2941
- function compileBigIntegerType(driver) {
2942
- switch (driver) {
2943
- case "pgsql":
2944
- return "BIGINT";
2945
- case "mysql":
2946
- return "BIGINT";
2947
- case "sqlite":
2948
- return "INTEGER";
2949
- }
2950
- }
2951
- function compileTimestampType(driver) {
2952
- switch (driver) {
2953
- case "pgsql":
2954
- return "TIMESTAMPTZ";
2955
- case "mysql":
2956
- return "TIMESTAMP";
2957
- case "sqlite":
2958
- return "TEXT";
2959
- }
2960
- }
2961
- function compileJsonType(driver) {
2962
- switch (driver) {
2963
- case "pgsql":
2964
- return "JSONB";
2965
- case "mysql":
2966
- return "JSON";
2967
- case "sqlite":
2968
- return "TEXT";
2969
- }
2970
- }
2971
- function compileJsonbType(driver) {
2972
- switch (driver) {
2973
- case "pgsql":
2974
- return "JSONB";
2975
- case "mysql":
2976
- return "JSON";
2977
- case "sqlite":
2978
- return "TEXT";
2979
- }
2980
- }
2981
-
2982
- // ../../src/core/database/schema/grammars/compileStatements.ts
2983
- function compileCreateTable(driver, blueprint) {
2984
- const table = quoteIdentifier(blueprint.table);
2985
- const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
2986
- for (const index of blueprint.indexes) {
2987
- if (index.kind === "unique" && index.columns.length > 1) {
2988
- const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2989
- parts.push(`UNIQUE (${columns})`);
2990
- }
2991
- }
2992
- const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
2993
- ${parts.join(`,
2994
- `)}
2995
- )`];
2996
- for (const index of blueprint.indexes) {
2997
- if (index.kind === "unique" && index.columns.length === 1) {
2998
- continue;
2999
- }
3000
- if (index.kind === "index") {
3001
- statements.push(compileIndex(driver, blueprint.table, index));
3002
- } else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
3003
- statements.push(...compileSpecialIndex(driver, blueprint.table, index));
3004
- }
3005
- }
3006
- return statements;
3007
- }
3008
- function compileAlterTable(driver, blueprint) {
3009
- const statements = [];
3010
- const table = quoteIdentifier(blueprint.table);
3011
- for (const column of blueprint.columns) {
3012
- const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
3013
- statements.push(`ALTER TABLE ${table}
3014
- ${addPrefix} ${compileColumn(driver, column, "alter")}`);
3015
- }
3016
- for (const columnName of blueprint.droppedColumns) {
3017
- const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
3018
- statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
3019
- }
3020
- for (const indexName of blueprint.droppedIndexes) {
3021
- statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
3022
- }
3023
- for (const index of blueprint.indexes) {
3024
- if (index.kind === "index" || index.kind === "unique") {
3025
- statements.push(compileIndex(driver, blueprint.table, index));
3026
- } else {
3027
- statements.push(...compileSpecialIndex(driver, blueprint.table, index));
3028
- }
3029
- }
3030
- return statements;
3031
- }
3032
- function compileDropTable(driver, tableName) {
3033
- const cascade = driver === "pgsql" ? " CASCADE" : "";
3034
- return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
3035
- }
3036
- function compileColumn(driver, column, mode) {
3037
- const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
3038
- if (column.autoIncrement && driver === "mysql") {
3039
- parts[1] = `${parts[1]} AUTO_INCREMENT`;
3040
- }
3041
- if (column.isPrimary && mode === "create") {
3042
- if (driver === "sqlite") {
3043
- parts.push("PRIMARY KEY AUTOINCREMENT");
3044
- } else {
3045
- parts.push("PRIMARY KEY");
3046
- }
3047
- } else if (!column.isNullable) {
3048
- parts.push("NOT NULL");
3049
- } else if (column.isNullable) {
3050
- parts.push("NULL");
3051
- }
3052
- if (column.defaultValue !== undefined) {
3053
- parts.push(`DEFAULT ${column.defaultValue}`);
3054
- }
3055
- if (column.isUnique) {
3056
- parts.push("UNIQUE");
3057
- }
3058
- if (column.checkExpression) {
3059
- parts.push(`CHECK (${column.checkExpression})`);
3060
- }
3061
- if (column.foreignKey) {
3062
- const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
3063
- const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
3064
- let clause = `REFERENCES ${reference}`;
3065
- if (onDelete === "cascade") {
3066
- clause += " ON DELETE CASCADE";
3067
- } else if (onDelete === "set null") {
3068
- clause += " ON DELETE SET NULL";
3069
- }
3070
- parts.push(clause);
3071
- }
3072
- return parts.join(" ");
3073
- }
3074
- function compileIndex(_driver, tableName, index) {
3075
- const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
3076
- const columns = index.columns.map((column) => {
3077
- const quoted = quoteIdentifier(column);
3078
- if (index.order === "desc") {
3079
- return `${quoted} DESC`;
3080
- }
3081
- return quoted;
3082
- }).join(", ");
3083
- const unique = index.kind === "unique" ? "UNIQUE " : "";
3084
- return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
3085
- }
3086
- function compileSpecialIndex(driver, tableName, index) {
3087
- const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
3088
- const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
3089
- switch (index.kind) {
3090
- case "partial":
3091
- case "uniquePartial": {
3092
- if (driver !== "pgsql") {
3093
- throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
3094
- }
3095
- const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
3096
- return [
3097
- `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
3098
- ];
3099
- }
3100
- case "gin": {
3101
- if (driver !== "pgsql") {
3102
- throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
3103
- }
3104
- return [
3105
- `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
3106
- ];
3107
- }
3108
- case "fullText": {
3109
- if (driver === "mysql") {
3110
- return [
3111
- `CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
3112
- ];
3113
- }
3114
- if (driver === "pgsql") {
3115
- throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
3116
- }
3117
- throw new UnsupportedSchemaFeatureError("fullText()", driver);
3118
- }
3119
- default:
3120
- return [];
3121
- }
3122
- }
3123
- function defaultIndexName(tableName, columns, kind) {
3124
- return `idx_${tableName}_${columns.join("_")}_${kind}`;
3125
- }
3126
- function compileBlueprint(driver, blueprint) {
3127
- switch (blueprint.action) {
3128
- case "create":
3129
- return compileCreateTable(driver, blueprint);
3130
- case "alter":
3131
- return compileAlterTable(driver, blueprint);
3132
- case "drop":
3133
- return compileDropTable(driver, blueprint.table);
3134
- default:
3135
- throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
3136
- }
3137
- }
3138
- // ../../src/core/database/schema/grammars/createGrammar.ts
3139
- function createGrammar(driver) {
3140
- return {
3141
- driver,
3142
- compile(blueprint) {
3143
- return compileBlueprint(driver, blueprint);
3144
- }
3145
- };
3146
- }
3147
-
3148
- // ../../src/core/database/schema/grammars/mysqlGrammar.ts
3149
- var MySqlGrammar = createGrammar("mysql");
3150
-
3151
- // ../../src/core/database/schema/grammars/postgresGrammar.ts
3152
- var PostgresGrammar = createGrammar("pgsql");
3153
-
3154
- // ../../src/core/database/schema/grammars/sqliteGrammar.ts
3155
- var SqliteGrammar = createGrammar("sqlite");
3156
-
3157
- // ../../src/core/database/schema/grammars/index.ts
3158
- function grammarForDriver(driver) {
3159
- switch (driver) {
3160
- case "pgsql":
3161
- return PostgresGrammar;
3162
- case "mysql":
3163
- return MySqlGrammar;
3164
- case "sqlite":
3165
- return SqliteGrammar;
3166
- default:
3167
- throw new Error(`Unsupported database driver: ${driver}`);
3168
- }
3169
- }
3170
- // ../../src/core/database/schema/schema.ts
3171
- class SchemaBuilder {
3172
- #driver;
3173
- #statements = [];
3174
- constructor(driver) {
3175
- this.#driver = driver;
3176
- }
3177
- create(table, callback) {
3178
- const blueprint = new Blueprint(table, "create");
3179
- callback(blueprint);
3180
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3181
- return this;
3182
- }
3183
- table(table, callback) {
3184
- const blueprint = new Blueprint(table, "alter");
3185
- callback(blueprint);
3186
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3187
- return this;
3188
- }
3189
- drop(table) {
3190
- const blueprint = new Blueprint(table, "drop");
3191
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3192
- return this;
3193
- }
3194
- toSql() {
3195
- return [...this.#statements];
3196
- }
3197
- async execute(db2) {
3198
- for (const statement of this.#statements) {
3199
- await db2.unsafe(statement);
3200
- }
3201
- }
3202
- }
3203
- // ../../src/core/database/table.ts
3204
- function defineTable5(definition) {
3205
- return definition;
3206
- }
3207
- // ../../src/core/queue/failedJobTable.ts
3208
- var failedJobTable = defineTable5({
3209
- name: "failed_job",
3210
- primaryKey: "id",
3211
- columns: ["id", "job_name", "payload", "exception", "failed_at"],
3212
- defaultOrderBy: { column: "failed_at", direction: "DESC" }
3213
- });
3214
-
3215
- // ../../src/core/queue/failedJobRepository.ts
3216
- class FailedJobRepository extends baseRepository_default {
3217
- constructor() {
3218
- super(failedJobTable);
3219
- }
3220
- }
3221
- var failedJobRepository_default = FailedJobRepository;
3222
-
3223
- // ../../src/core/queue/failedJobService.ts
3224
- class FailedJobService {
3225
- repository;
3226
- constructor(repository) {
3227
- this.repository = repository;
3228
- }
3229
- async recordFailure(input) {
3230
- return await this.repository.create({
3231
- job_name: input.jobName,
3232
- payload: input.payload,
3233
- exception: input.exception,
3234
- failed_at: new Date
3235
- });
3236
- }
3237
- listRecent(limit = 50) {
3238
- return this.repository.findAll({
3239
- limit,
3240
- orderBy: { column: "failed_at", direction: "DESC" }
3241
- });
3242
- }
3243
- async retry(id) {
3244
- const failedJob = await this.repository.findByIdOrThrow(id, (jobId) => new Error(`Failed job ${jobId} not found.`));
3245
- await this.repository.deleteById(id);
3246
- return failedJob;
3247
- }
3248
- async delete(id) {
3249
- const deleted = await this.repository.deleteById(id);
3250
- if (!deleted) {
3251
- throw new Error(`Failed job ${id} not found.`);
3252
- }
3253
- }
3254
- async flush() {
3255
- const jobs = await this.repository.findAll();
3256
- let deleted = 0;
3257
- for (const job of jobs) {
3258
- if (await this.repository.deleteById(job.id)) {
3259
- deleted += 1;
3260
- }
3261
- }
3262
- return deleted;
3263
- }
3264
- }
3265
- var failedJobService_default = FailedJobService;
3266
-
3267
- // ../../src/core/queue/jobRegistry.ts
3268
- class JobRegistry {
3269
- factories = new Map;
3270
- instances = new WeakMap;
3271
- register(name, factory) {
3272
- this.factories.set(name, factory);
3273
- }
3274
- resolveName(job) {
3275
- return this.instances.get(job);
3276
- }
3277
- track(name, job) {
3278
- this.instances.set(job, name);
3279
- return job;
3280
- }
3281
- create(name) {
3282
- const factory = this.factories.get(name);
3283
- if (!factory) {
3284
- return;
3285
- }
3286
- return factory();
3287
- }
3288
- names() {
3289
- return [...this.factories.keys()];
3290
- }
3291
- }
3292
- var JOB_REGISTRY_KEY = Symbol.for("@getstrata/jobRegistry");
3293
- function readSharedJobRegistry() {
3294
- const globalRegistry = globalThis[JOB_REGISTRY_KEY];
3295
- if (globalRegistry) {
3296
- return globalRegistry;
3297
- }
3298
- const registry = new JobRegistry;
3299
- globalThis[JOB_REGISTRY_KEY] = registry;
3300
- return registry;
3301
- }
3302
- var jobRegistry = readSharedJobRegistry();
3303
-
3304
- // ../../src/core/queue/jobRunner.ts
3305
- async function runQueueJob(envelope, failedJobs) {
3306
- const job = jobRegistry.create(envelope.name);
3307
- if (!job) {
3308
- throw new Error(`Unknown job "${envelope.name}".`);
3309
- }
3310
- const attempts = envelope.attempts ?? 0;
3311
- try {
3312
- await job.handle(envelope.payload);
3313
- } catch (error) {
3314
- const nextAttempt = attempts + 1;
3315
- const maxAttempts = job.maxAttempts ?? queueConfig.maxAttempts;
3316
- if (nextAttempt < maxAttempts) {
3317
- const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
3318
- await new Promise((resolve) => setTimeout(resolve, backoffMs * nextAttempt));
3319
- await runQueueJob({
3320
- ...envelope,
3321
- attempts: nextAttempt
3322
- }, failedJobs);
3323
- return;
3324
- }
3325
- await failedJobs.recordFailure({
3326
- jobName: envelope.name,
3327
- payload: envelope.payload,
3328
- exception: error instanceof Error ? error.stack ?? error.message : String(error)
3329
- });
3330
- throw error;
3331
- }
3332
- }
3333
-
3334
- // ../../src/core/queue/redisQueue.ts
3335
- var {RedisClient: RedisClient2 } = globalThis.Bun;
3336
- var QUEUE_LIST_KEY = "workhub:queue:default";
3337
- var QUEUE_HIGH_KEY = "workhub:queue:high";
3338
- var QUEUE_LOW_KEY = "workhub:queue:low";
3339
- function queueKeyForPriority(priority = "default") {
3340
- switch (priority) {
3341
- case "high":
3342
- return QUEUE_HIGH_KEY;
3343
- case "low":
3344
- return QUEUE_LOW_KEY;
3345
- default:
3346
- return QUEUE_LIST_KEY;
3347
- }
3348
- }
3349
- class RedisQueue {
3350
- client;
3351
- constructor(redisUrl) {
3352
- this.client = new RedisClient2(redisUrl);
3353
- }
3354
- async dispatch(job, payload) {
3355
- const name = jobRegistry.resolveName(job);
3356
- if (!name) {
3357
- throw new Error("Job is not registered with the queue worker registry.");
3358
- }
3359
- const envelope = {
3360
- name,
3361
- payload,
3362
- attempts: 0
3363
- };
3364
- const queueKey = queueKeyForPriority(job.priority);
3365
- await this.client.lpush(queueKey, JSON.stringify(envelope));
3366
- }
3367
- }
3368
-
3369
- // ../../src/core/queue/resilientQueue.ts
3370
- class ResilientQueue {
3371
- failedJobs;
3372
- asyncDispatch;
3373
- constructor(failedJobs, asyncDispatch = false) {
3374
- this.failedJobs = failedJobs;
3375
- this.asyncDispatch = asyncDispatch;
3376
- }
3377
- async dispatch(job, payload) {
3378
- const name = jobRegistry.resolveName(job);
3379
- if (!name) {
3380
- throw new Error("Job is not registered with the queue worker registry.");
3381
- }
3382
- const envelope = {
3383
- name,
3384
- payload,
3385
- attempts: 0
3386
- };
3387
- if (this.asyncDispatch) {
3388
- setTimeout(() => {
3389
- runQueueJob(envelope, this.failedJobs).catch((error) => {
3390
- console.error("[ResilientQueue] Job failed:", error);
3391
- });
3392
- }, 0);
3393
- return;
3394
- }
3395
- await runQueueJob(envelope, this.failedJobs);
3396
- }
3397
- }
3398
-
3399
- // ../../src/core/queue/publicQueue.ts
3400
- function createFailedJobService() {
3401
- return new failedJobService_default(new failedJobRepository_default);
3402
- }
3403
- function createProductionQueue(driver, options = {}) {
3404
- options.registerJobs?.();
3405
- const failedJobs = options.failedJobs ?? createFailedJobService();
3406
- if (driver === "redis") {
3407
- if (!options.redisUrl) {
3408
- throw new Error('QUEUE_DRIVER="redis" requires REDIS_URL to be set.');
3409
- }
3410
- return new RedisQueue(options.redisUrl);
3411
- }
3412
- return new ResilientQueue(failedJobs, driver === "async");
3413
- }
3414
-
3415
- // ../../src/core/queue/createAppQueue.ts
3416
- var FAILED_JOB_SERVICE_TOKEN = "core.failedJobs";
3417
- function createAppQueue(driver, redisUrl, failedJobs = createFailedJobService(), registerJobs) {
3418
- return createProductionQueue(driver, {
3419
- redisUrl,
3420
- failedJobs,
3421
- registerJobs
3422
- });
3423
- }
3424
-
3425
- // ../../src/core/jobs/dispatchWebhookJob.ts
3426
- import { createHmac as createHmac2 } from "crypto";
3427
-
3428
- // ../../src/core/queue/index.ts
3429
- class Job {
3430
- maxAttempts;
3431
- backoffMs;
3432
- priority;
3433
- }
3434
-
3435
- // ../../src/core/security/safeUrl.ts
3436
- import { lookup as dnsLookupImpl } from "dns/promises";
3437
- var dnsLookup = dnsLookupImpl;
3438
- var BLOCKED_HOSTNAMES = new Set([
3439
- "localhost",
3440
- "127.0.0.1",
3441
- "0.0.0.0",
3442
- "::1",
3443
- "metadata.google.internal"
3444
- ]);
3445
- function isPrivateIpv4(hostname) {
3446
- const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
3447
- if (!match) {
3448
- return false;
3449
- }
3450
- const octets = match.slice(1, 5).map((part) => Number.parseInt(part, 10));
3451
- if (octets.some((octet) => octet < 0 || octet > 255)) {
3452
- return true;
3453
- }
3454
- const [a = 0, b = 0] = octets;
3455
- if (a === 10) {
3456
- return true;
3457
- }
3458
- if (a === 127) {
3459
- return true;
3460
- }
3461
- if (a === 0) {
3462
- return true;
3463
- }
3464
- if (a === 169 && b === 254) {
3465
- return true;
3466
- }
3467
- if (a === 172 && b >= 16 && b <= 31) {
3468
- return true;
3469
- }
3470
- if (a === 192 && b === 168) {
3471
- return true;
3472
- }
3473
- return false;
3474
- }
3475
- function isBlockedHostname(hostname) {
3476
- const normalized = hostname.trim().toLowerCase();
3477
- if (normalized.length === 0) {
3478
- return true;
3479
- }
3480
- if (BLOCKED_HOSTNAMES.has(normalized)) {
3481
- return true;
3482
- }
3483
- if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
3484
- return true;
3485
- }
3486
- if (normalized.includes(":")) {
3487
- return true;
3488
- }
3489
- return isPrivateIpv4(normalized);
3490
- }
3491
- function assertSafeOutboundUrl(rawUrl, options = {}) {
3492
- let parsed;
3493
- try {
3494
- parsed = new URL(rawUrl);
3495
- } catch {
3496
- throw new BadRequestError("Webhook URL is invalid.");
3497
- }
3498
- if (parsed.protocol !== "https:" && !(options.allowHttp && parsed.protocol === "http:")) {
3499
- throw new BadRequestError("Webhook URL must use HTTPS.");
3500
- }
3501
- if (parsed.username || parsed.password) {
3502
- throw new BadRequestError("Webhook URL must not include credentials.");
3503
- }
3504
- if (isBlockedHostname(parsed.hostname)) {
3505
- throw new BadRequestError("Webhook URL targets a blocked host.");
3506
- }
3507
- return parsed;
3508
- }
3509
- function isBlockedIpAddress(address) {
3510
- return isBlockedHostname(address.trim().toLowerCase());
3511
- }
3512
- async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
3513
- const parsed = assertSafeOutboundUrl(rawUrl, options);
3514
- if (options.resolveDns === false) {
3515
- return parsed;
3516
- }
3517
- const hostname = parsed.hostname.trim().toLowerCase();
3518
- const results = await dnsLookup(hostname, { all: true, verbatim: true });
3519
- if (results.some((result) => isBlockedIpAddress(result.address))) {
3520
- throw new BadRequestError("Webhook URL targets a blocked host.");
3521
- }
3522
- return parsed;
3523
- }
3524
-
3525
- // ../../src/core/security/safeFetch.ts
3526
- var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
3527
- async function safeFetch(input, init = {}, options = {}) {
3528
- const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
3529
- const maxRedirects = options.maxRedirects ?? 0;
3530
- const resolveDns = options.resolveDns ?? appConfig.env === "production";
3531
- const urlOptions = { allowHttp: options.allowHttp, resolveDns };
3532
- const controller = new AbortController;
3533
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
3534
- try {
3535
- let currentUrl = (await assertSafeOutboundUrlResolved(input, urlOptions)).toString();
3536
- let redirectCount = 0;
3537
- while (true) {
3538
- const response = await fetch(currentUrl, {
3539
- ...init,
3540
- signal: controller.signal,
3541
- redirect: "manual"
3542
- });
3543
- if (response.status >= 300 && response.status < 400) {
3544
- const location = response.headers.get("location");
3545
- if (!location || redirectCount >= maxRedirects) {
3546
- return response;
3547
- }
3548
- currentUrl = (await assertSafeOutboundUrlResolved(new URL(location, currentUrl).toString(), urlOptions)).toString();
3549
- redirectCount += 1;
3550
- continue;
3551
- }
3552
- return response;
3553
- }
3554
- } finally {
3555
- clearTimeout(timeout);
3556
- }
3557
- }
3558
-
3559
- // ../../src/core/jobs/dispatchWebhookJob.ts
3560
- class DispatchWebhookJob extends Job {
3561
- maxAttempts = 3;
3562
- backoffMs = 2000;
3563
- async handle(payload) {
3564
- const rows = await repositoryConnection`
3565
- SELECT id, url, secret
3566
- FROM webhook
3567
- WHERE id = ${payload.webhookId} AND active = TRUE
3568
- LIMIT 1
3569
- `;
3570
- const webhook = rows[0];
3571
- if (!webhook) {
3572
- return;
3573
- }
3574
- const body = JSON.stringify({ event: payload.event, payload: payload.payload });
3575
- const signature = createHmac2("sha256", webhook.secret).update(body).digest("hex");
3576
- assertSafeOutboundUrl(webhook.url, { allowHttp: appConfig.env !== "production" });
3577
- let responseStatus = null;
3578
- let errorMessage = null;
3579
- try {
3580
- const response = await safeFetch(webhook.url, {
3581
- method: "POST",
3582
- headers: {
3583
- "content-type": "application/json",
3584
- "x-workhub-signature": signature
3585
- },
3586
- body
3587
- }, { allowHttp: appConfig.env !== "production" });
3588
- responseStatus = response.status;
3589
- if (!response.ok) {
3590
- throw new Error(`Webhook delivery failed with status ${response.status}.`);
3591
- }
3592
- } catch (error) {
3593
- errorMessage = error instanceof Error ? error.message : String(error);
3594
- await repositoryConnection`
3595
- INSERT INTO webhook_delivery (webhook_id, event, payload, response_status, error)
3596
- VALUES (
3597
- ${webhook.id},
3598
- ${payload.event},
3599
- ${JSON.stringify(payload.payload)}::jsonb,
3600
- ${responseStatus},
3601
- ${errorMessage}
3602
- )
3603
- `;
3604
- throw error instanceof Error ? error : new Error(errorMessage);
3605
- }
3606
- await repositoryConnection`
3607
- INSERT INTO webhook_delivery (webhook_id, event, payload, response_status)
3608
- VALUES (
3609
- ${webhook.id},
3610
- ${payload.event},
3611
- ${JSON.stringify(payload.payload)}::jsonb,
3612
- ${responseStatus}
3613
- )
3614
- `;
3615
- }
3616
- }
3617
- var dispatchWebhookJob_default = DispatchWebhookJob;
3618
-
3619
- // ../../src/core/jobs/invalidateCacheTagsJob.ts
3620
- class InvalidateCacheTagsJob2 extends Job {
3621
- cache;
3622
- constructor(cache) {
3623
- super();
3624
- this.cache = cache;
3625
- }
3626
- async handle(payload) {
3627
- await this.cache.tags(...payload.tags).flush();
3628
- }
3629
- }
3630
- var invalidateCacheTagsJob_default = InvalidateCacheTagsJob2;
3631
-
3632
- // ../../src/core/contracts/di.ts
3633
- function getRequiredDependency(dependencies, key) {
3634
- const dependency = dependencies[key];
3635
- if (dependency === undefined) {
3636
- throw new Error(`Required dependency "${key}" is not registered.`);
3637
- }
3638
- return dependency;
3639
- }
3640
-
3641
- // ../../src/core/contracts/serviceTokens.ts
3642
- var CORE_POLICY_GATE_TOKEN2 = "core.policyGate";
3643
- var CORE_AUTH_TOKEN2 = "core.auth";
3644
-
3645
- // ../../src/core/logging/logger.ts
3646
- class Logger {
3647
- channel;
3648
- constructor(channel = "app") {
3649
- this.channel = channel;
3650
- }
3651
- write(level, message, context = {}) {
3652
- const entry = {
3653
- level,
3654
- channel: this.channel,
3655
- message,
3656
- timestamp: new Date().toISOString(),
3657
- ...context
3658
- };
3659
- const line = JSON.stringify(entry);
3660
- if (level === "error") {
3661
- console.error(line);
3662
- return;
3663
- }
3664
- console.log(line);
3665
- }
3666
- debug(message, context) {
3667
- this.write("debug", message, context);
3668
- }
3669
- info(message, context) {
3670
- this.write("info", message, context);
3671
- }
3672
- warn(message, context) {
3673
- this.write("warn", message, context);
3674
- }
3675
- error(message, context) {
3676
- this.write("error", message, context);
3677
- }
3678
- }
3679
- var appLogger = new Logger("app");
3680
-
3681
- // ../../src/core/runtime/applicationRegistry.ts
3682
- var APPLICATION_CONTEXT_KEY = Symbol.for("@getstrata/applicationContext");
3683
- var activeContext;
3684
- function readStoredApplicationContext() {
3685
- if (activeContext) {
3686
- return activeContext;
3687
- }
3688
- const globalContext = globalThis[APPLICATION_CONTEXT_KEY];
3689
- if (globalContext) {
3690
- activeContext = globalContext;
3691
- }
3692
- return activeContext;
3693
- }
3694
- function requireActiveApplicationContext() {
3695
- const context = readStoredApplicationContext();
3696
- if (!context) {
3697
- throw new Error("The application context has not been bootstrapped.");
3698
- }
3699
- return context;
3700
- }
3701
- function resolveApplicationCache2() {
3702
- return getRequiredDependency(requireActiveApplicationContext().dependencies, "cache");
3703
- }
3704
- function resolveApplicationAuth2() {
3705
- return requireActiveApplicationContext().container.resolve(CORE_AUTH_TOKEN2);
3706
- }
3707
- function resolveApplicationPolicyGate2() {
3708
- return requireActiveApplicationContext().container.resolve(CORE_POLICY_GATE_TOKEN2);
3709
- }
3710
-
3711
- // ../../src/bootstrap/queue/defaultJobs.ts
3712
- function registerDefaultJobs() {
3713
- jobRegistry.register("cache.invalidate-tags", () => {
3714
- return new invalidateCacheTagsJob_default(resolveApplicationCache2());
3715
- });
3716
- jobRegistry.register("webhook.dispatch", () => new dispatchWebhookJob_default);
3717
- }
3718
-
3719
- // ../../src/bootstrap/providers/queue.ts
3720
- var queueProvider = {
3721
- name: "core.queue",
3722
- register({ container, config }) {
3723
- const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
3724
- const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
3725
- config.set("queue.driver", driver);
3726
- const failedJobs = createFailedJobService();
3727
- container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
3728
- container.set(CORE_QUEUE_TOKEN, createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs, registerDefaultJobs));
3729
- }
3730
- };
3731
- var queue_default = queueProvider;
3732
-
3733
- // ../../src/core/storage/storage.ts
3734
- import { mkdir, readFile, unlink, writeFile } from "fs/promises";
3735
- import { dirname, join as join3 } from "path";
3736
- var {S3Client } = globalThis.Bun;
3737
-
3738
- class LocalStorageDriver {
3739
- rootDirectory;
3740
- constructor(rootDirectory) {
3741
- this.rootDirectory = rootDirectory;
3742
- }
3743
- resolveRootDirectory() {
3744
- return this.rootDirectory ?? process.env.STORAGE_PATH ?? "storage";
3745
- }
3746
- resolvePath(path) {
3747
- return join3(this.resolveRootDirectory(), path.replace(/^\/+/, ""));
3748
- }
3749
- async put(path, contents) {
3750
- const absolutePath = this.resolvePath(path);
3751
- await mkdir(dirname(absolutePath), { recursive: true });
3752
- await writeFile(absolutePath, contents);
3753
- return path;
3754
- }
3755
- async get(path) {
3756
- try {
3757
- return await readFile(this.resolvePath(path));
3758
- } catch {
3759
- return null;
3760
- }
3761
- }
3762
- async delete(path) {
3763
- try {
3764
- await unlink(this.resolvePath(path));
3765
- return true;
3766
- } catch {
3767
- return false;
3768
- }
3769
- }
3770
- }
3771
-
3772
- class S3StorageDriver {
3773
- client;
3774
- constructor(client) {
3775
- this.client = client;
3776
- }
3777
- async put(path, contents) {
3778
- await this.client.write(path.replace(/^\/+/, ""), contents);
3779
- return path;
3780
- }
3781
- async get(path) {
3782
- const normalizedPath = path.replace(/^\/+/, "");
3783
- const file = this.client.file(normalizedPath);
3784
- if (!await file.exists()) {
3785
- return null;
3786
- }
3787
- return new Uint8Array(await file.arrayBuffer());
3788
- }
3789
- async delete(path) {
3790
- try {
3791
- await this.client.unlink(path.replace(/^\/+/, ""));
3792
- return true;
3793
- } catch {
3794
- return false;
3795
- }
3796
- }
3797
- }
3798
-
3799
- class StorageManager {
3800
- driver;
3801
- constructor(driver) {
3802
- this.driver = driver;
3803
- }
3804
- put(path, contents) {
3805
- return this.driver.put(path, contents);
3806
- }
3807
- get(path) {
3808
- return this.driver.get(path);
3809
- }
3810
- delete(path) {
3811
- return this.driver.delete(path);
3812
- }
3813
- }
3814
- function resolveS3Config() {
3815
- const accessKeyId = process.env.AWS_ACCESS_KEY_ID?.trim();
3816
- const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY?.trim();
3817
- const bucket = process.env.AWS_BUCKET?.trim();
3818
- if (!accessKeyId || !secretAccessKey || !bucket) {
3819
- throw new Error('STORAGE_DRIVER="s3" requires AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_BUCKET.');
3820
- }
3821
- return {
3822
- accessKeyId,
3823
- secretAccessKey,
3824
- bucket,
3825
- ...process.env.AWS_REGION?.trim() ? { region: process.env.AWS_REGION.trim() } : {},
3826
- ...process.env.AWS_ENDPOINT?.trim() ? { endpoint: process.env.AWS_ENDPOINT.trim() } : {}
3827
- };
3828
- }
3829
- function createS3Client(config = resolveS3Config()) {
3830
- return new S3Client({
3831
- accessKeyId: config.accessKeyId,
3832
- secretAccessKey: config.secretAccessKey,
3833
- bucket: config.bucket,
3834
- ...config.region ? { region: config.region } : {},
3835
- ...config.endpoint ? { endpoint: config.endpoint } : {}
3836
- });
3837
- }
3838
- function createStorageDriver() {
3839
- const driver = process.env.STORAGE_DRIVER ?? "local";
3840
- if (driver === "s3") {
3841
- return new S3StorageDriver(createS3Client());
3842
- }
3843
- return new LocalStorageDriver;
3844
- }
3845
-
3846
- // ../../src/bootstrap/providers/storage.ts
3847
- var storageProvider = {
3848
- name: "core.storage",
3849
- register({ dependencies }) {
3850
- dependencies.storage = new StorageManager(createStorageDriver());
3851
- }
3852
- };
3853
- var storage_default = storageProvider;
3854
-
3855
- // ../../src/config/frontend.ts
3856
- function readFrontendMode() {
3857
- const mode = (process.env.FRONTEND_MODE ?? "api").trim();
3858
- if (mode === "server-htmx") {
3859
- return "server-htmx";
968
+ };
969
+ var storage_default = storageProvider;
970
+
971
+ // ../../src/bootstrap/providers/view.ts
972
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
973
+ import { DEFAULT_VIEWS_DIRECTORY, EtaViewEngine, resolveWebLayoutData } from "@getstrata/core/view";
974
+
975
+ // ../../src/config/frontend.ts
976
+ function readFrontendMode() {
977
+ const mode = (process.env.FRONTEND_MODE ?? "api").trim();
978
+ if (mode === "server-htmx") {
979
+ return "server-htmx";
3860
980
  }
3861
981
  if (mode === "spa-react") {
3862
982
  return "spa-react";
@@ -3870,214 +990,6 @@ function isSpaEnabled() {
3870
990
  return readFrontendMode() === "spa-react";
3871
991
  }
3872
992
 
3873
- // ../../src/core/http/requestMetaContext.ts
3874
- var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
3875
- function currentRequestMeta() {
3876
- return requestMetaContext.getStore() ?? {
3877
- ipAddress: null,
3878
- userAgent: null
3879
- };
3880
- }
3881
-
3882
- // ../../src/core/view/etaViewEngine.ts
3883
- import { join as join4 } from "path";
3884
- import { Eta } from "eta";
3885
- var DEFAULT_VIEWS_DIRECTORY = join4(process.cwd(), "resources/views");
3886
- var DEFAULT_LAYOUT = "layouts/app.eta";
3887
-
3888
- class EtaViewEngine {
3889
- eta;
3890
- resolveLayoutData;
3891
- constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
3892
- this.eta = new Eta({
3893
- views: viewsDirectory,
3894
- autoTrim: false
3895
- });
3896
- this.resolveLayoutData = resolveLayoutData;
3897
- }
3898
- async render(name, data = {}, options = {}) {
3899
- const template = name.endsWith(".eta") ? name : `${name}.eta`;
3900
- const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
3901
- const mergedData = { ...layoutData, ...data };
3902
- const body = await this.eta.renderAsync(template, mergedData);
3903
- const layout = options.layout ?? DEFAULT_LAYOUT;
3904
- if (layout === false) {
3905
- return body;
3906
- }
3907
- const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
3908
- return await this.eta.renderAsync(layoutTemplate, {
3909
- ...mergedData,
3910
- body
3911
- });
3912
- }
3913
- }
3914
- // ../../src/core/http/cookies.ts
3915
- function readRequestCookie(request, name) {
3916
- const cookies = request.cookies;
3917
- if (cookies && typeof cookies.get === "function") {
3918
- const value = cookies.get(name);
3919
- if (value) {
3920
- return value;
3921
- }
3922
- }
3923
- const header = request.headers.get("cookie");
3924
- if (!header) {
3925
- return null;
3926
- }
3927
- for (const part of header.split(";")) {
3928
- const idx = part.indexOf("=");
3929
- if (idx === -1)
3930
- continue;
3931
- const cookieName = part.slice(0, idx).trim();
3932
- if (cookieName !== name)
3933
- continue;
3934
- return decodeURIComponent(part.slice(idx + 1).trim());
3935
- }
3936
- return null;
3937
- }
3938
-
3939
- // ../../src/core/http/csrfToken.ts
3940
- var CSRF_COOKIE = "workhub_csrf";
3941
- var CSRF_TTL_MS = 60 * 60 * 1000;
3942
- function resolveCsrfSecret() {
3943
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
3944
- }
3945
- function csrfVerifyOptions() {
3946
- return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
3947
- }
3948
- function createCsrfTokenCookie() {
3949
- const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
3950
- return {
3951
- token,
3952
- cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
3953
- };
3954
- }
3955
- function resolveCsrfToken(request) {
3956
- const cookieValue = readRequestCookie(request, CSRF_COOKIE);
3957
- if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
3958
- return { token: cookieValue };
3959
- }
3960
- return createCsrfTokenCookie();
3961
- }
3962
- function resolveCsrfTokenForRequest(request) {
3963
- const metaToken = currentRequestMeta().csrfToken;
3964
- if (metaToken) {
3965
- return metaToken;
3966
- }
3967
- return resolveCsrfToken(request).token;
3968
- }
3969
-
3970
- // ../../src/core/http/flashSession.ts
3971
- import { createHmac as createHmac3, timingSafeEqual as timingSafeEqual2 } from "crypto";
3972
- var FLASH_COOKIE = "workhub_flash";
3973
- var FLASH_TTL_MS = 60 * 1000;
3974
- function resolveFlashSecret() {
3975
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
3976
- }
3977
- function signFlashPayload(payload, issuedAt) {
3978
- const signature = createHmac3("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
3979
- return `${payload}.${issuedAt}.${signature}`;
3980
- }
3981
- function readFlashCookie(request) {
3982
- const cookieHeader = request.headers.get("cookie");
3983
- if (!cookieHeader) {
3984
- return null;
3985
- }
3986
- for (const part of cookieHeader.split(";")) {
3987
- const [name, ...rest] = part.trim().split("=");
3988
- if (name === FLASH_COOKIE) {
3989
- return decodeURIComponent(rest.join("="));
3990
- }
3991
- }
3992
- return null;
3993
- }
3994
- function parseFlashCookie(cookieValue) {
3995
- const parts = cookieValue.split(".");
3996
- if (parts.length < 3) {
3997
- return null;
3998
- }
3999
- const signature = parts.pop();
4000
- const issuedAtRaw = parts.pop();
4001
- const payload = parts.join(".");
4002
- if (!signature || !issuedAtRaw || !payload) {
4003
- return null;
4004
- }
4005
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
4006
- if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
4007
- return null;
4008
- }
4009
- const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
4010
- if (!expectedSignature) {
4011
- return null;
4012
- }
4013
- const expectedBuffer = Buffer.from(expectedSignature);
4014
- const actualBuffer = Buffer.from(signature);
4015
- if (expectedBuffer.length !== actualBuffer.length) {
4016
- return null;
4017
- }
4018
- if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
4019
- return null;
4020
- }
4021
- try {
4022
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
4023
- if (!parsed?.message || typeof parsed.message !== "string") {
4024
- return null;
4025
- }
4026
- if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
4027
- return null;
4028
- }
4029
- return parsed;
4030
- } catch {
4031
- return null;
4032
- }
4033
- }
4034
- function pullFlash(request) {
4035
- const cookieValue = readFlashCookie(request);
4036
- if (!cookieValue) {
4037
- return null;
4038
- }
4039
- return parseFlashCookie(cookieValue);
4040
- }
4041
-
4042
- // ../../src/core/view/webLayoutData.ts
4043
- async function resolveWebLayoutData(container, request) {
4044
- const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
4045
- const flash = request ? currentRequestMeta().flash ?? pullFlash(request) : null;
4046
- const authUser = currentAuthUser();
4047
- if (!authUser) {
4048
- return { authUser: null, csrfToken, flash };
4049
- }
4050
- const userId = Number(authUser.id);
4051
- if (!Number.isInteger(userId) || userId <= 0) {
4052
- return { authUser: null, csrfToken, flash };
4053
- }
4054
- if (!container.has(tokenServiceToken)) {
4055
- return {
4056
- authUser: {
4057
- id: userId,
4058
- email: "",
4059
- role: authUser.role ?? "member"
4060
- },
4061
- csrfToken,
4062
- flash
4063
- };
4064
- }
4065
- const tokenService = container.resolve(tokenServiceToken);
4066
- try {
4067
- const user = await tokenService.findByIdOrThrow(userId);
4068
- return {
4069
- authUser: {
4070
- id: userId,
4071
- email: user.email ?? "",
4072
- role: authUser.role ?? user.role ?? "member"
4073
- },
4074
- csrfToken,
4075
- flash
4076
- };
4077
- } catch {
4078
- return { authUser: null, csrfToken, flash };
4079
- }
4080
- }
4081
993
  // ../../src/bootstrap/providers/view.ts
4082
994
  var CORE_VIEW_TOKEN = "core.view";
4083
995
  var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";