@guren/server 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/{Application-DN9Ndl37.d.ts → Application-BvBqgc2k.d.ts} +204 -22
  2. package/dist/{AuthManager-SfhCNkAU.d.ts → AuthManager-C84xF5ks.d.ts} +1 -1
  3. package/dist/{BroadcastManager-CGWl9rUO.d.ts → BroadcastManager-D8KoJxiV.d.ts} +21 -0
  4. package/dist/{CacheManager-BkvHEOZX.d.ts → CacheManager-BmDzUKrF.d.ts} +17 -0
  5. package/dist/{ConsoleKernel-DxmUxdAz.d.ts → ConsoleKernel-Dw9X9qZY.d.ts} +1 -1
  6. package/dist/{I18nManager-BiSoczfV.d.ts → I18nManager-CmUqj6bU.d.ts} +1 -1
  7. package/dist/{McpServiceProvider-JW6PDVMD.js → McpServiceProvider-TZWQWXCT.js} +2 -2
  8. package/dist/{Scheduler-BstvSca7.d.ts → Scheduler-pZiT8i57.d.ts} +2 -0
  9. package/dist/{api-token-BSSCLlFW.d.ts → api-token-COQHXyM_.d.ts} +123 -1
  10. package/dist/auth/index.d.ts +5 -5
  11. package/dist/auth/index.js +3 -1
  12. package/dist/authorization/index.js +2 -2
  13. package/dist/broadcasting/index.d.ts +2 -2
  14. package/dist/broadcasting/index.js +2 -1
  15. package/dist/cache/index.d.ts +2 -2
  16. package/dist/cache/index.js +2 -1
  17. package/dist/{chunk-EGU5KB7V.js → chunk-4SBGSJNT.js} +31 -1
  18. package/dist/{chunk-THSX7OOR.js → chunk-63SKW5PS.js} +3 -0
  19. package/dist/{chunk-2T6JN4VR.js → chunk-AUXQISW5.js} +169 -14
  20. package/dist/chunk-DCYKSYAT.js +63 -0
  21. package/dist/{chunk-ZRBLZY3M.js → chunk-FZD2AKJI.js} +1 -1
  22. package/dist/{chunk-HLXL2AYJ.js → chunk-JIT7QVMJ.js} +2 -2
  23. package/dist/{chunk-HKQSAFSN.js → chunk-MC752CQT.js} +15 -0
  24. package/dist/{chunk-WVY45EIW.js → chunk-NQCZQAJL.js} +93 -28
  25. package/dist/{chunk-VT5KRDPH.js → chunk-NYQGAWDN.js} +49 -1
  26. package/dist/{chunk-44F7JQ7I.js → chunk-XMQZENBP.js} +35 -1
  27. package/dist/{client-CKXJLsTe.d.ts → client-BQwF2b9Y.d.ts} +7 -0
  28. package/dist/{email-verification-CAeArjui.d.ts → email-verification-H_WlpsVH.d.ts} +1 -1
  29. package/dist/{errors-JOOPDDQ6.js → errors-PUNHAFL2.js} +1 -1
  30. package/dist/i18n/index.d.ts +2 -2
  31. package/dist/index.d.ts +129 -19
  32. package/dist/index.js +314 -105
  33. package/dist/lambda/index.d.ts +8 -8
  34. package/dist/mcp/index.d.ts +54 -20
  35. package/dist/mcp/index.js +2 -2
  36. package/dist/notifications/index.d.ts +8 -8
  37. package/dist/queue/index.d.ts +8 -8
  38. package/dist/redis/index.d.ts +11 -21
  39. package/dist/redis/index.js +42 -6
  40. package/dist/runtime/index.d.ts +8 -8
  41. package/dist/runtime/index.js +1 -1
  42. package/dist/scheduling/index.d.ts +2 -2
  43. package/dist/scheduling/index.js +2 -1
  44. package/package.json +2 -2
@@ -38,6 +38,13 @@ var MemorySessionStore = class {
38
38
  async destroy(id) {
39
39
  this.store.delete(id);
40
40
  }
41
+ async touch(id, ttlSeconds) {
42
+ const entry = this.store.get(id);
43
+ if (!entry || entry.expiresAt <= this.now()) {
44
+ return;
45
+ }
46
+ entry.expiresAt = this.now() + ttlSeconds * 1e3;
47
+ }
41
48
  };
42
49
  var DEFAULT_COOKIE_NAME = "guren.session";
43
50
  var DEFAULT_TTL_SECONDS = 60 * 60 * 2;
@@ -126,11 +133,16 @@ var SessionImpl = class {
126
133
  /**
127
134
  * Age flash data: move `new` → `old`, clear previous `old`.
128
135
  * Called at the start of each request by the session middleware.
136
+ * Only dirties the session when there was flash data to age — otherwise
137
+ * every request carrying a session would persist unconditionally.
129
138
  */
130
139
  ageFlashData() {
140
+ const hadFlash = this.hasFlash();
131
141
  this._flash.old = { ...this._flash.new };
132
142
  this._flash.new = {};
133
- this.dirty = true;
143
+ if (hadFlash) {
144
+ this.dirty = true;
145
+ }
134
146
  }
135
147
  markTouched() {
136
148
  this.dirty = true;
@@ -142,10 +154,16 @@ var SessionImpl = class {
142
154
  return this.regenerated;
143
155
  }
144
156
  shouldPersist() {
145
- return this.dirty || this.isNew;
157
+ return this.dirty || this.isNew && this.hasContent();
158
+ }
159
+ hasContent() {
160
+ return Object.keys(this.data).length > 0 || this.hasFlash();
161
+ }
162
+ hasFlash() {
163
+ return Object.keys(this._flash.new).length > 0 || Object.keys(this._flash.old).length > 0;
146
164
  }
147
165
  snapshot() {
148
- const hasFlash = Object.keys(this._flash.new).length > 0 || Object.keys(this._flash.old).length > 0;
166
+ const hasFlash = this.hasFlash();
149
167
  return {
150
168
  ...this.data,
151
169
  ...hasFlash ? { _flash: { new: { ...this._flash.new }, old: { ...this._flash.old } } } : {}
@@ -155,6 +173,25 @@ var SessionImpl = class {
155
173
  return this.originalId;
156
174
  }
157
175
  };
176
+ var TESTING_SESSION_HEADER = "x-testing-session";
177
+ function resolveTestingSession(ctx) {
178
+ if (!process.env.GUREN_TESTING) {
179
+ return null;
180
+ }
181
+ const rawSession = ctx.req.header(TESTING_SESSION_HEADER);
182
+ if (!rawSession) {
183
+ return null;
184
+ }
185
+ try {
186
+ const parsed = JSON.parse(rawSession);
187
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
188
+ return null;
189
+ }
190
+ return parsed;
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
158
195
  function encodeBase64Url(value) {
159
196
  return Buffer.from(value, "utf8").toString("base64url");
160
197
  }
@@ -216,7 +253,9 @@ function createSessionMiddleware(options = {}) {
216
253
  const existingId = signer.verify(getCookie(ctx, cookieName));
217
254
  const sessionId = existingId ?? globalThis.crypto.randomUUID();
218
255
  const isNew = !existingId;
219
- const initialData = existingId ? await store.read(existingId) ?? {} : {};
256
+ const storedData = existingId ? await store.read(existingId) ?? {} : {};
257
+ const testingData = resolveTestingSession(ctx);
258
+ const initialData = testingData ? { ...storedData, ...testingData } : storedData;
220
259
  const session = new SessionImpl(sessionId, initialData, isNew);
221
260
  session.ageFlashData();
222
261
  ctx.set(SESSION_CONTEXT_KEY, session);
@@ -236,7 +275,11 @@ function createSessionMiddleware(options = {}) {
236
275
  }
237
276
  if (!session.shouldPersist()) {
238
277
  if (existingId) {
239
- await store.write(existingId, session.snapshot(), ttlSeconds);
278
+ if (store.touch) {
279
+ await store.touch(existingId, ttlSeconds);
280
+ } else {
281
+ await store.write(existingId, session.snapshot(), ttlSeconds);
282
+ }
240
283
  setCookie(ctx, cookieName, signer.sign(existingId), {
241
284
  path: cookiePath,
242
285
  domain: cookieDomain,
@@ -1270,6 +1313,29 @@ function getApiTokenOrFail(ctx) {
1270
1313
  return result;
1271
1314
  }
1272
1315
 
1316
+ // src/support/redirect-target.ts
1317
+ function normalizeRedirectTarget(value) {
1318
+ return value.replace(/\\/g, "/");
1319
+ }
1320
+ function isAppRelativePath(value) {
1321
+ return value.startsWith("/") && !value.startsWith("//");
1322
+ }
1323
+ function hostMatchesAllowlist(target, allowedHosts) {
1324
+ const hostname = target.hostname.toLowerCase();
1325
+ const host = target.host.toLowerCase();
1326
+ for (const allowed of allowedHosts) {
1327
+ if (allowed.startsWith("*.")) {
1328
+ const suffix = allowed.slice(1).toLowerCase();
1329
+ if (hostname.endsWith(suffix) && hostname.length > suffix.length) {
1330
+ return true;
1331
+ }
1332
+ } else if (host === allowed.toLowerCase()) {
1333
+ return true;
1334
+ }
1335
+ }
1336
+ return false;
1337
+ }
1338
+
1273
1339
  // src/auth/oauth/index.ts
1274
1340
  var DEFAULT_STATE_EXPIRES_IN = 10 * 60 * 1e3;
1275
1341
  var DEFAULT_STATE_LENGTH = 24;
@@ -1311,6 +1377,13 @@ var MemoryOAuthStateStore = class {
1311
1377
  async delete(stateHash) {
1312
1378
  this.states.delete(stateHash);
1313
1379
  }
1380
+ async consume(stateHash) {
1381
+ const payload = this.states.get(stateHash);
1382
+ if (!payload) return null;
1383
+ this.states.delete(stateHash);
1384
+ if (payload.expiresAt.getTime() <= Date.now()) return null;
1385
+ return payload;
1386
+ }
1314
1387
  clear() {
1315
1388
  this.states.clear();
1316
1389
  }
@@ -1324,7 +1397,8 @@ var OAuthManager = class {
1324
1397
  this.stateConfig = {
1325
1398
  expiresIn: options.stateConfig?.expiresIn ?? DEFAULT_STATE_EXPIRES_IN,
1326
1399
  stateLength: options.stateConfig?.stateLength ?? DEFAULT_STATE_LENGTH,
1327
- hashAlgorithm: options.stateConfig?.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM
1400
+ hashAlgorithm: options.stateConfig?.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM,
1401
+ allowedRedirectHosts: options.stateConfig?.allowedRedirectHosts ?? []
1328
1402
  };
1329
1403
  }
1330
1404
  registerProvider(name, config) {
@@ -1354,13 +1428,24 @@ var OAuthManager = class {
1354
1428
  return { url, state, expiresAt };
1355
1429
  }
1356
1430
  async user(providerName, payload) {
1431
+ const { profile } = await this.handleCallback(providerName, payload);
1432
+ return profile;
1433
+ }
1434
+ /**
1435
+ * Verify the callback and return the user profile together with the
1436
+ * sanitized `redirectTo` stored at authorize time. `redirectTo` is safe to
1437
+ * pass to a redirect response: app-relative paths and allowlisted hosts
1438
+ * only.
1439
+ */
1440
+ async handleCallback(providerName, payload) {
1357
1441
  const provider = this.getProvider(providerName);
1358
1442
  const verified = await verifyOAuthState(payload.state, providerName, this.stateStore, this.stateConfig);
1359
1443
  if (!verified) {
1360
1444
  throw new AuthenticationException("Invalid or expired OAuth state.");
1361
1445
  }
1362
1446
  const token = await exchangeOAuthCode(provider, payload.code);
1363
- return fetchOAuthUserProfile(provider, token);
1447
+ const profile = await fetchOAuthUserProfile(provider, token);
1448
+ return { profile, redirectTo: verified.redirectTo };
1364
1449
  }
1365
1450
  };
1366
1451
  function createOAuthManager(options = {}) {
@@ -1371,18 +1456,46 @@ async function createOAuthState(provider, store, config = {}, redirectTo, fixedS
1371
1456
  const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
1372
1457
  const expiresAt = new Date(Date.now() + (config.expiresIn ?? DEFAULT_STATE_EXPIRES_IN));
1373
1458
  const stateHash = hashToken(state, hashAlgorithm);
1374
- await store.store(stateHash, { provider, redirectTo, expiresAt });
1459
+ await store.store(stateHash, {
1460
+ provider,
1461
+ redirectTo: sanitizeOAuthRedirect(redirectTo, config.allowedRedirectHosts),
1462
+ expiresAt
1463
+ });
1375
1464
  return { state, expiresAt };
1376
1465
  }
1377
1466
  async function verifyOAuthState(state, provider, store, config = {}) {
1378
1467
  const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
1379
1468
  const stateHash = hashToken(state, hashAlgorithm);
1469
+ const payload = typeof store.consume === "function" ? await store.consume(stateHash) : await findAndDeleteState(store, stateHash);
1470
+ if (!payload) return null;
1471
+ if (payload.provider !== provider) return null;
1472
+ return { ...payload, redirectTo: sanitizeOAuthRedirect(payload.redirectTo, config.allowedRedirectHosts) };
1473
+ }
1474
+ async function findAndDeleteState(store, stateHash) {
1380
1475
  const payload = await store.find(stateHash);
1381
1476
  if (!payload) return null;
1382
1477
  await store.delete(stateHash);
1383
- if (payload.provider !== provider) return null;
1384
1478
  return payload;
1385
1479
  }
1480
+ function sanitizeOAuthRedirect(redirectTo, allowedHosts = []) {
1481
+ const value = redirectTo?.trim();
1482
+ if (!value) {
1483
+ return void 0;
1484
+ }
1485
+ const normalized = normalizeRedirectTarget(value);
1486
+ if (isAppRelativePath(normalized)) {
1487
+ return normalized;
1488
+ }
1489
+ try {
1490
+ const target = new URL(normalized);
1491
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
1492
+ return void 0;
1493
+ }
1494
+ return hostMatchesAllowlist(target, allowedHosts) ? normalized : void 0;
1495
+ } catch {
1496
+ return void 0;
1497
+ }
1498
+ }
1386
1499
  function buildOAuthAuthorizeUrl(provider, state, options = {}) {
1387
1500
  const url = new URL(provider.authorizeUrl);
1388
1501
  url.searchParams.set("response_type", "code");
@@ -1450,9 +1563,23 @@ async function fetchOAuthUserProfile(provider, token) {
1450
1563
  throw new AuthenticationException(`OAuth user fetch failed (${response.status}).`);
1451
1564
  }
1452
1565
  const raw = await response.json();
1453
- if (provider.mapProfile) {
1454
- return provider.mapProfile(raw, token);
1566
+ const profile = provider.mapProfile ? provider.mapProfile(raw, token) : defaultProfileFromUserInfo(raw, token, provider.emailVerifiedKey);
1567
+ if (!profile.email && provider.fetchFallbackEmail) {
1568
+ const fallback = await provider.fetchFallbackEmail(token);
1569
+ const email = typeof fallback === "string" ? fallback : fallback?.email;
1570
+ if (email) {
1571
+ const emailVerified = typeof fallback === "string" ? void 0 : fallback?.emailVerified;
1572
+ return { ...profile, email, emailVerified };
1573
+ }
1455
1574
  }
1575
+ return profile;
1576
+ }
1577
+ var DEFAULT_EMAIL_VERIFIED_KEY = "email_verified";
1578
+ function readEmailVerified(raw, key = DEFAULT_EMAIL_VERIFIED_KEY) {
1579
+ const value = raw[key];
1580
+ return typeof value === "boolean" ? value : void 0;
1581
+ }
1582
+ function defaultProfileFromUserInfo(raw, token, emailVerifiedKey) {
1456
1583
  const idCandidate = raw.id ?? raw.sub;
1457
1584
  const id = typeof idCandidate === "string" || typeof idCandidate === "number" ? String(idCandidate) : "";
1458
1585
  if (!id) {
@@ -1461,19 +1588,41 @@ async function fetchOAuthUserProfile(provider, token) {
1461
1588
  return {
1462
1589
  id,
1463
1590
  email: typeof raw.email === "string" ? raw.email : void 0,
1591
+ emailVerified: readEmailVerified(raw, emailVerifiedKey),
1464
1592
  name: typeof raw.name === "string" ? raw.name : void 0,
1465
1593
  avatar: typeof raw.avatar_url === "string" ? raw.avatar_url : typeof raw.picture === "string" ? raw.picture : typeof raw.avatar === "string" ? raw.avatar : void 0,
1466
1594
  token,
1467
1595
  raw
1468
1596
  };
1469
1597
  }
1598
+ async function fetchGitHubPrimaryEmail(token) {
1599
+ const response = await fetch("https://api.github.com/user/emails", {
1600
+ headers: {
1601
+ Accept: "application/vnd.github+json",
1602
+ Authorization: `Bearer ${token.accessToken}`,
1603
+ "User-Agent": "guren-oauth"
1604
+ }
1605
+ });
1606
+ if (!response.ok) {
1607
+ return void 0;
1608
+ }
1609
+ const emails = await response.json();
1610
+ if (!Array.isArray(emails)) {
1611
+ return void 0;
1612
+ }
1613
+ const primary = emails.find(
1614
+ (entry) => typeof entry === "object" && entry !== null && entry.primary === true && entry.verified === true && typeof entry.email === "string"
1615
+ );
1616
+ return primary ? { email: primary.email, emailVerified: true } : void 0;
1617
+ }
1470
1618
  function createGitHubOAuthProviderConfig(input) {
1471
1619
  return {
1472
1620
  ...input,
1473
1621
  authorizeUrl: "https://github.com/login/oauth/authorize",
1474
1622
  tokenUrl: "https://github.com/login/oauth/access_token",
1475
1623
  userInfoUrl: "https://api.github.com/user",
1476
- scopes: input.scopes ?? ["read:user", "user:email"]
1624
+ scopes: input.scopes ?? ["read:user", "user:email"],
1625
+ fetchFallbackEmail: fetchGitHubPrimaryEmail
1477
1626
  };
1478
1627
  }
1479
1628
  function createGoogleOAuthProviderConfig(input) {
@@ -1482,7 +1631,8 @@ function createGoogleOAuthProviderConfig(input) {
1482
1631
  authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
1483
1632
  tokenUrl: "https://oauth2.googleapis.com/token",
1484
1633
  userInfoUrl: "https://openidconnect.googleapis.com/v1/userinfo",
1485
- scopes: input.scopes ?? ["openid", "profile", "email"]
1634
+ scopes: input.scopes ?? ["openid", "profile", "email"],
1635
+ emailVerifiedKey: "email_verified"
1486
1636
  };
1487
1637
  }
1488
1638
  function createDiscordOAuthProviderConfig(input) {
@@ -1491,7 +1641,8 @@ function createDiscordOAuthProviderConfig(input) {
1491
1641
  authorizeUrl: "https://discord.com/api/oauth2/authorize",
1492
1642
  tokenUrl: "https://discord.com/api/oauth2/token",
1493
1643
  userInfoUrl: "https://discord.com/api/users/@me",
1494
- scopes: input.scopes ?? ["identify", "email"]
1644
+ scopes: input.scopes ?? ["identify", "email"],
1645
+ emailVerifiedKey: "verified"
1495
1646
  };
1496
1647
  }
1497
1648
  function buildOAuthRedirectUrl(baseUrl, token, email) {
@@ -1517,6 +1668,9 @@ export {
1517
1668
  parseTokenUrl,
1518
1669
  SessionGuard,
1519
1670
  AuthManager,
1671
+ normalizeRedirectTarget,
1672
+ isAppRelativePath,
1673
+ hostMatchesAllowlist,
1520
1674
  MemoryApiTokenStore,
1521
1675
  createApiToken,
1522
1676
  parseApiToken,
@@ -1536,6 +1690,7 @@ export {
1536
1690
  createOAuthManager,
1537
1691
  createOAuthState,
1538
1692
  verifyOAuthState,
1693
+ sanitizeOAuthRedirect,
1539
1694
  buildOAuthAuthorizeUrl,
1540
1695
  exchangeOAuthCode,
1541
1696
  fetchOAuthUserProfile,
@@ -0,0 +1,63 @@
1
+ // src/hot-reload/hot-disposables.ts
2
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("guren.server.hotDisposables");
3
+ function getRegistry() {
4
+ const scope = globalThis;
5
+ return scope[REGISTRY_KEY] ??= /* @__PURE__ */ new Map();
6
+ }
7
+ function isHotReloadRuntime() {
8
+ return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
9
+ }
10
+ var SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set(["unknown", "native", "<anonymous>"]);
11
+ var LOCATION_SUFFIX = /:\d+(?::\d+)?$/;
12
+ function parseFrameLocation(frame) {
13
+ const location = frame.match(/\(([^()]*)\)\s*$/)?.[1] ?? frame.match(/^\s*at\s+(.+?)\s*$/)?.[1];
14
+ if (!location || !LOCATION_SUFFIX.test(location)) {
15
+ return void 0;
16
+ }
17
+ return location.replace(LOCATION_SUFFIX, "");
18
+ }
19
+ function describeCallerFile(stack) {
20
+ for (const frame of stack?.split("\n").slice(2) ?? []) {
21
+ const path = parseFrameLocation(frame);
22
+ if (path && !SYNTHETIC_FRAME_PATHS.has(path)) {
23
+ return path;
24
+ }
25
+ }
26
+ return void 0;
27
+ }
28
+ function hotReloadKey(scope, stack, target) {
29
+ if (!isHotReloadRuntime()) {
30
+ return void 0;
31
+ }
32
+ const callerFile = describeCallerFile(stack);
33
+ return callerFile ? `${scope}|${callerFile}|${target}` : void 0;
34
+ }
35
+ function claimHotDisposable(scope, stack, target, dispose) {
36
+ const key = hotReloadKey(scope, stack, target);
37
+ if (!key) {
38
+ return void 0;
39
+ }
40
+ const registry = getRegistry();
41
+ const previous = registry.get(key);
42
+ registry.delete(key);
43
+ if (previous && previous !== dispose) {
44
+ try {
45
+ previous();
46
+ } catch (error) {
47
+ console.warn("[guren] Failed to stop the previous hot-reload disposable:", error);
48
+ }
49
+ }
50
+ registry.set(key, dispose);
51
+ return {
52
+ release() {
53
+ if (registry.get(key) === dispose) {
54
+ registry.delete(key);
55
+ }
56
+ }
57
+ };
58
+ }
59
+
60
+ export {
61
+ isHotReloadRuntime,
62
+ claimHotDisposable
63
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AuthorizationException
3
- } from "./chunk-THSX7OOR.js";
3
+ } from "./chunk-63SKW5PS.js";
4
4
 
5
5
  // src/authorization/Gate.ts
6
6
  var Response = {
@@ -6,7 +6,7 @@ import standard from "figlet/importable-fonts/Standard.js";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@guren/server",
9
- version: "1.2.0",
9
+ version: "1.4.0",
10
10
  type: "module",
11
11
  license: "MIT",
12
12
  repository: {
@@ -115,7 +115,7 @@ var package_default = {
115
115
  test: "bun test"
116
116
  },
117
117
  dependencies: {
118
- "@guren/orm": "^1.0.1",
118
+ "@guren/orm": "^1.2.0",
119
119
  "@modelcontextprotocol/sdk": "^1.27.1",
120
120
  chalk: "^5.3.0",
121
121
  consola: "^3.4.2",
@@ -1,3 +1,8 @@
1
+ import {
2
+ claimHotDisposable,
3
+ isHotReloadRuntime
4
+ } from "./chunk-DCYKSYAT.js";
5
+
1
6
  // src/scheduling/CronParser.ts
2
7
  function parseField(field, min, max) {
3
8
  const values = /* @__PURE__ */ new Set();
@@ -671,6 +676,8 @@ var Scheduler = class {
671
676
  interval = null;
672
677
  isRunning = false;
673
678
  lastCheck = null;
679
+ /** This scheduler's claim on its hot-reload slot while it is running. */
680
+ hotReloadClaim;
674
681
  constructor(options = {}) {
675
682
  this.options = {
676
683
  timezone: options.timezone ?? "UTC",
@@ -730,6 +737,12 @@ var Scheduler = class {
730
737
  }
731
738
  this.isRunning = true;
732
739
  this.options.logger("Scheduler started");
740
+ this.hotReloadClaim = claimHotDisposable(
741
+ "scheduler",
742
+ isHotReloadRuntime() ? new Error().stack : void 0,
743
+ this.options.timezone,
744
+ () => this.stop()
745
+ );
733
746
  this.tick();
734
747
  this.interval = setInterval(() => {
735
748
  this.tick();
@@ -749,6 +762,8 @@ var Scheduler = class {
749
762
  clearInterval(this.interval);
750
763
  this.interval = null;
751
764
  }
765
+ this.hotReloadClaim?.release();
766
+ this.hotReloadClaim = void 0;
752
767
  this.isRunning = false;
753
768
  this.options.logger("Scheduler stopped");
754
769
  }
@@ -1,9 +1,12 @@
1
1
  import {
2
- ServiceProvider
3
- } from "./chunk-VT5KRDPH.js";
2
+ MCP_ENDPOINT_PATH,
3
+ ServiceProvider,
4
+ createMcpAccessGuard,
5
+ isMcpEndpointEnabled
6
+ } from "./chunk-NYQGAWDN.js";
4
7
 
5
8
  // src/mcp/create-mcp-server.ts
6
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
9
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
7
10
  import { z } from "zod";
8
11
  function createMcpServer(options) {
9
12
  const { cwd, cli, version = "0.2.0" } = options;
@@ -23,6 +26,29 @@ function createMcpServer(options) {
23
26
  return { content: [{ type: "text", text }] };
24
27
  }
25
28
  );
29
+ server.tool(
30
+ "guren_entity_context",
31
+ "Get everything about one entity in a single bundle: model (table, columns, relationships, reverse references), routes with validation schemas, controller actions, Inertia pages with props, resource, policy, seeders, and tests. Prefer this over guren_get_context when working on a specific model.",
32
+ {
33
+ entity: z.string().describe('Model class name (e.g., "User"). Case-insensitive.'),
34
+ module: z.string().optional().describe('Module name to disambiguate same-named models across modules/; "app" selects the application root'),
35
+ format: z.enum(["json", "markdown"]).default("markdown").describe("Output format")
36
+ },
37
+ async ({ entity, module, format }) => {
38
+ try {
39
+ const ctx = await cli.generateEntityContext(entity, { cwd, module });
40
+ const text = format === "markdown" ? cli.renderEntityContextMarkdown(ctx) : JSON.stringify(ctx, null, 2);
41
+ return { content: [{ type: "text", text }] };
42
+ } catch (error) {
43
+ return {
44
+ content: [
45
+ { type: "text", text: error instanceof Error ? error.message : String(error) }
46
+ ],
47
+ isError: true
48
+ };
49
+ }
50
+ }
51
+ );
26
52
  server.tool(
27
53
  "guren_check",
28
54
  "Validate route-to-controller-to-page consistency, check for empty controller methods, missing test files, and missing generated manifests.",
@@ -151,35 +177,52 @@ function createMcpServer(options) {
151
177
  );
152
178
  server.tool(
153
179
  "guren_codegen",
154
- "Generate type-safe route, page, data, and channel type manifests (.guren/*.gen.ts files).",
180
+ "Generate the type-safe route, page, data, and channel manifests plus the API client (.guren/ and types/generated/).",
155
181
  {},
156
182
  async () => {
157
183
  const originalCwd = process.cwd();
158
184
  try {
159
185
  process.chdir(cwd);
186
+ const options2 = { cwd, force: true };
160
187
  const generated = [];
161
- try {
162
- await cli.generateRouteTypes({ cwd });
163
- generated.push(".guren/routes.gen.ts");
164
- } catch {
165
- }
166
- try {
167
- await cli.generatePageTypes({ cwd });
168
- generated.push(".guren/pages.gen.ts");
169
- } catch {
170
- }
171
- try {
172
- await cli.generateDataTypes({ cwd });
173
- generated.push(".guren/data.gen.ts");
174
- } catch {
175
- }
176
- try {
177
- await cli.generateChannelTypes({ cwd });
178
- generated.push(".guren/channels.gen.ts");
179
- } catch {
180
- }
188
+ const skipped = [];
189
+ let failed = false;
190
+ const run = async (artifacts, generate) => {
191
+ try {
192
+ const result = await generate();
193
+ if (result?.outputPath === "") {
194
+ skipped.push({ artifacts, reason: "nothing to generate" });
195
+ } else {
196
+ generated.push(...artifacts);
197
+ }
198
+ return result;
199
+ } catch (error) {
200
+ failed = true;
201
+ skipped.push({
202
+ artifacts,
203
+ reason: error instanceof Error ? error.message : String(error)
204
+ });
205
+ }
206
+ };
207
+ const routes = await run(
208
+ [".guren/routes.gen.ts", "types/generated/routes.d.ts"],
209
+ () => cli.generateRouteTypes(options2)
210
+ );
211
+ await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options2));
212
+ await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options2));
213
+ await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options2));
214
+ await run([".guren/api-client.gen.ts"], () => {
215
+ if (!routes?.definitions) {
216
+ throw new Error("route generation produced no manifest to build a client from");
217
+ }
218
+ return cli.generateApiClientTypes(routes.definitions, options2);
219
+ });
181
220
  return {
182
- content: [{ type: "text", text: JSON.stringify({ generated }, null, 2) }]
221
+ content: [{ type: "text", text: JSON.stringify({ generated, skipped }, null, 2) }],
222
+ // A generator that found nothing to describe is not a failure — an
223
+ // app with no page components is a normal shape — so only a thrown
224
+ // one makes the run an error, even when other artifacts landed.
225
+ isError: failed
183
226
  };
184
227
  } finally {
185
228
  process.chdir(originalCwd);
@@ -206,6 +249,26 @@ function createMcpServer(options) {
206
249
  };
207
250
  }
208
251
  );
252
+ server.resource(
253
+ "entity-context",
254
+ new ResourceTemplate("guren://context/{entity}", { list: void 0 }),
255
+ {
256
+ description: "Entity-centric context bundle: model, routes, controller, pages, resource, policy. For same-named models across modules, use the guren_entity_context tool with its module argument instead.",
257
+ mimeType: "text/markdown"
258
+ },
259
+ async (uri, variables) => {
260
+ const ctx = await cli.generateEntityContext(String(variables.entity), { cwd });
261
+ return {
262
+ contents: [
263
+ {
264
+ uri: uri.href,
265
+ mimeType: "text/markdown",
266
+ text: cli.renderEntityContextMarkdown(ctx)
267
+ }
268
+ ]
269
+ };
270
+ }
271
+ );
209
272
  server.resource(
210
273
  "guidelines",
211
274
  "guren://guidelines",
@@ -331,7 +394,7 @@ var McpServiceProvider = class extends ServiceProvider {
331
394
  register() {
332
395
  }
333
396
  async boot() {
334
- if (process.env.NODE_ENV === "production") {
397
+ if (!isMcpEndpointEnabled()) {
335
398
  return;
336
399
  }
337
400
  const app = this.container.make("app");
@@ -342,8 +405,10 @@ var McpServiceProvider = class extends ServiceProvider {
342
405
  // @ts-ignore — @guren/cli is available at runtime via the app's dependencies
343
406
  import("@guren/cli")
344
407
  ]);
345
- hono.all("/_guren/mcp", async (c) => {
346
- const mcpServer = createMcpServer({ cwd, cli });
408
+ const routeAwareCli = cli.createFreshContextApi ? { ...cli, ...cli.createFreshContextApi() } : cli;
409
+ hono.use(MCP_ENDPOINT_PATH, createMcpAccessGuard());
410
+ hono.all(MCP_ENDPOINT_PATH, async (c) => {
411
+ const mcpServer = createMcpServer({ cwd, cli: routeAwareCli });
347
412
  const transport = new WebStandardStreamableHTTPServerTransport({
348
413
  sessionIdGenerator: void 0
349
414
  });