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