@stacksjs/router 0.70.228 → 0.70.230

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ export declare function runHealthProbes(probes: HealthProbe[], options?: HealthProbeOptions): Promise<ApplicationHealthResult>;
2
+ export declare function checkApplicationHealth(options?: HealthProbeOptions): Promise<ApplicationHealthResult>;
3
+ export declare interface ApplicationHealthCheck {
4
+ ok: boolean
5
+ message?: string
6
+ ms: number
7
+ }
8
+ export declare interface ApplicationHealthResult {
9
+ status: 'healthy' | 'degraded'
10
+ checks: Record<string, ApplicationHealthCheck>
11
+ timestamp: number
12
+ }
13
+ export declare interface HealthProbe {
14
+ name: string
15
+ run: () => Promise<unknown>
16
+ }
17
+ export declare interface HealthProbeOptions {
18
+ timeoutMs?: number
19
+ now?: () => number
20
+ }
package/dist/health.js ADDED
@@ -0,0 +1,56 @@
1
+ export async function runHealthProbes(probes, options = {}) {
2
+ const timeoutMs = options.timeoutMs ?? 1500, now = options.now ?? Date.now, entries = await Promise.all(probes.map(async ({ name, run }) => {
3
+ const startedAt = now();
4
+ let timeout;
5
+ try {
6
+ await Promise.race([
7
+ run(),
8
+ new Promise((_resolve, reject) => {
9
+ timeout = setTimeout(() => reject(Error("timeout")), timeoutMs);
10
+ })
11
+ ]);
12
+ return [name, { ok: !0, ms: Math.max(0, now() - startedAt) }];
13
+ } catch (error) {
14
+ return [name, {
15
+ ok: !1,
16
+ ms: Math.max(0, now() - startedAt),
17
+ message: error instanceof Error ? error.message : String(error)
18
+ }];
19
+ } finally {
20
+ if (timeout)
21
+ clearTimeout(timeout);
22
+ }
23
+ })), checks = Object.fromEntries(entries);
24
+ return {
25
+ status: Object.values(checks).every((check) => check.ok) ? "healthy" : "degraded",
26
+ checks,
27
+ timestamp: now()
28
+ };
29
+ }
30
+ export async function checkApplicationHealth(options = {}) {
31
+ return runHealthProbes([
32
+ {
33
+ name: "database",
34
+ async run() {
35
+ const { db } = await import("@stacksjs/database"), unsafe = db.unsafe;
36
+ if (typeof unsafe !== "function")
37
+ throw Error("database driver does not expose a raw health probe");
38
+ await unsafe.call(db, "SELECT 1");
39
+ }
40
+ },
41
+ {
42
+ name: "cache",
43
+ async run() {
44
+ const { cache } = await import("@stacksjs/cache"), key = `__health__:${Date.now()}`;
45
+ let stored = !1;
46
+ try {
47
+ await cache.set(key, 1, 5);
48
+ stored = !0;
49
+ } finally {
50
+ if (stored)
51
+ await cache.del(key);
52
+ }
53
+ }
54
+ }
55
+ ], options);
56
+ }
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export type { MiddlewareConfig, Request } from './middleware';
8
8
  // framework defaults tree (stacksjs/stacks#1863, T-10).
9
9
  export type { RouteDefinition, RouteRegistry } from './route-types';
10
10
  export type { PathParamRejection, SanitizePathParamOptions } from './path-sanitize';
11
+ export type { ApplicationHealthCheck, ApplicationHealthResult, HealthProbe, HealthProbeOptions } from './health';
11
12
  export type { StreamOptions } from './stacks-router';
12
13
  export type { SignedUrlOptions, SignedUrlVerifyResult } from './signed-url';
13
14
  export type { EncryptedSessionStoreOptions } from './encrypted-session-store';
@@ -50,6 +51,9 @@ export { rateLimit, rateLimitStatus, clearRateLimit } from './rate-limit';
50
51
  // filesystem paths; the helper enforces no-traversal / no-absolute /
51
52
  // no-null-byte / length ceiling at a single chokepoint.
52
53
  export { PathParamError, safePathParam, sanitizePathParam } from './path-sanitize';
54
+ // Shared dependency probes used by the public load-balancer endpoint and
55
+ // authenticated operational dashboards.
56
+ export { checkApplicationHealth, runHealthProbes } from './health';
53
57
  // Export the streaming-response helper for SSE / NDJSON / chunked
54
58
  // binary returns (stacksjs/stacks#1870 R-4). Actions can return
55
59
  // `stream(asyncGen, { type: 'sse' })` and the router pipes it back
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ export { listRegisteredRoutes, routeParams } from "./stacks-router";
18
18
  export { isApiRequest, JSON_CONTENT_TYPE } from "./api-shape";
19
19
  export { rateLimit, rateLimitStatus, clearRateLimit } from "./rate-limit";
20
20
  export { PathParamError, safePathParam, sanitizePathParam } from "./path-sanitize";
21
+ export { checkApplicationHealth, runHealthProbes } from "./health";
21
22
  export { stream } from "./stacks-router";
22
23
  export { signedUrl, signUrl, verifySignedUrl, verifySignedUrlMiddleware } from "./signed-url";
23
24
  export { EncryptedSessionStore } from "./encrypted-session-store";
@@ -1,3 +1,4 @@
1
+ import type { Collection } from '@stacksjs/types';
1
2
  import type { FileInfo } from '@stacksjs/bun-router';
2
3
  /**
3
4
  * Stacks-specific marker fields attached to the request by the
@@ -37,18 +38,25 @@ export declare interface StacksRequestMacros {
37
38
  except?: <T extends Record<string, unknown>>(keys: string[]) => T
38
39
  has?: (key: string | string[]) => boolean
39
40
  hasAny?: (keys: string[]) => boolean
40
- missing?: (key: string) => boolean
41
- filled?: (key: string) => boolean
41
+ missing?: (key: string | string[]) => boolean
42
+ filled?: (key: string | string[]) => boolean
43
+ merge?: (data: Record<string, unknown>) => void
44
+ keys?: () => string[]
42
45
  integer?: (key: string, defaultValue?: number) => number
43
46
  float?: (key: string, defaultValue?: number) => number
44
47
  boolean?: (key: string, defaultValue?: boolean) => boolean
45
48
  string?: (key: string, defaultValue?: string) => string
46
- array?: <T = unknown>(key: string, defaultValue?: T[]) => T[]
49
+ array?: <T = unknown>(key: string) => T[]
50
+ date?: (key: string, format?: string) => Date | null
51
+ enum?: <T extends Record<string, string | number>>(key: string, enumType: T) => T[keyof T] | null
52
+ collect?: <T = unknown>(key: string) => Collection<T>
53
+ whenHas?: <T>(key: string, callback: (value: T) => void, defaultCallback?: () => void) => void
54
+ whenFilled?: <T>(key: string, callback: (value: T) => void, defaultCallback?: () => void) => void
55
+ isValue?: (key: string, value: unknown) => boolean
47
56
  file?: (key: string) => FileInfo | null
48
- files?: (key: string) => FileInfo[]
57
+ getFiles?: (key: string) => FileInfo[]
49
58
  hasFile?: (key: string) => boolean
50
59
  allFiles?: () => Record<string, FileInfo | FileInfo[]>
51
- getFiles?: () => Record<string, FileInfo | FileInfo[]>
52
60
  user?: () => Promise<unknown>
53
61
  userToken?: () => Promise<unknown>
54
62
  tokenCan?: (ability: string) => Promise<boolean>
@@ -4,10 +4,12 @@ import process from "node:process";
4
4
  import { Buffer } from "node:buffer";
5
5
  import { existsSync } from "node:fs";
6
6
  import { timingSafeEqual } from "node:crypto";
7
+ import { collect } from "@stacksjs/collections";
7
8
  import { log, report } from "@stacksjs/logging";
8
9
  import { path as p } from "@stacksjs/path";
9
10
  import { UploadedFile } from "@stacksjs/storage";
10
11
  import { applyRequestEnhancements, Router } from "@stacksjs/bun-router";
12
+ import { checkApplicationHealth } from "./health";
11
13
  const ROUTER_INSTANCES_KEY = Symbol.for("@stacksjs/router:loaded-instances"), loadedRouterInstances = globalThis[ROUTER_INSTANCES_KEY] ??= new Set;
12
14
  loadedRouterInstances.add(import.meta.path);
13
15
  const MULTI_INSTANCE_WARNED_KEY = Symbol.for("@stacksjs/router:multi-instance-warned");
@@ -661,6 +663,7 @@ async function resolveStringHandlerUncached(handlerPath) {
661
663
  req._skipCsrf = !0;
662
664
  if (actionForcesJson)
663
665
  req._forceJson = !0;
666
+ req._requestValidationRules = action.validations ?? modelValidationRules(action.modelDefinition ?? action.model);
664
667
  try {
665
668
  if (action.validations) {
666
669
  const validationResult = await validateActionInput(req, action.validations);
@@ -719,6 +722,17 @@ export async function validateActionInput(req, validations) {
719
722
  errors
720
723
  };
721
724
  }
725
+ function modelValidationRules(model) {
726
+ if (!model?.attributes || typeof model.attributes !== "object")
727
+ return;
728
+ const rules = {};
729
+ for (const [field, attribute] of Object.entries(model.attributes)) {
730
+ const validation = attribute?.validation;
731
+ if (validation?.rule)
732
+ rules[field] = validation;
733
+ }
734
+ return Object.keys(rules).length > 0 ? rules : void 0;
735
+ }
722
736
  async function getRequestInput(req, validations) {
723
737
  const input = {}, q = req.query;
724
738
  if (q)
@@ -839,6 +853,10 @@ function getAllInputFor(req) {
839
853
  req._allInputCache = input;
840
854
  return input;
841
855
  }
856
+ function flashInputFor(req, keys) {
857
+ const input = getAllInputFor(req);
858
+ req._oldInput = keys ? Object.fromEntries(keys.filter((key) => (key in input)).map((key) => [key, input[key]])) : { ...input };
859
+ }
842
860
  const REQUEST_METHODS = {
843
861
  get(key, defaultValue) {
844
862
  const value = getAllInputFor(this)[key];
@@ -889,6 +907,12 @@ const REQUEST_METHODS = {
889
907
  return key.every((k) => !(k in input) || input[k] === void 0);
890
908
  return !(key in input) || input[key] === void 0;
891
909
  },
910
+ merge(data) {
911
+ Object.assign(getAllInputFor(this), data);
912
+ },
913
+ keys() {
914
+ return Object.keys(getAllInputFor(this));
915
+ },
892
916
  string(key, defaultValue = "") {
893
917
  const value = getAllInputFor(this)[key];
894
918
  return value !== void 0 && value !== null ? String(value) : defaultValue;
@@ -935,6 +959,91 @@ const REQUEST_METHODS = {
935
959
  return value;
936
960
  return value !== void 0 && value !== null ? [value] : [];
937
961
  },
962
+ date(key) {
963
+ const value = getAllInputFor(this)[key];
964
+ if (value === void 0 || value === null || value === "")
965
+ return null;
966
+ const parsed = new Date(value);
967
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
968
+ },
969
+ enum(key, enumType) {
970
+ const value = getAllInputFor(this)[key];
971
+ if (value === void 0 || value === null)
972
+ return null;
973
+ if (Object.values(enumType).includes(value))
974
+ return value;
975
+ const enumKey = String(value);
976
+ return enumKey in enumType ? enumType[enumKey] : null;
977
+ },
978
+ collect(key) {
979
+ const value = getAllInputFor(this)[key];
980
+ if (Array.isArray(value))
981
+ return collect(value);
982
+ return collect(value === void 0 || value === null ? [] : [value]);
983
+ },
984
+ whenHas(key, callback, defaultCallback) {
985
+ const input = getAllInputFor(this);
986
+ if (key in input && input[key] !== void 0)
987
+ callback(input[key]);
988
+ else
989
+ defaultCallback?.();
990
+ },
991
+ whenFilled(key, callback, defaultCallback) {
992
+ const value = getAllInputFor(this)[key];
993
+ if (value !== void 0 && value !== null && value !== "" && !(Array.isArray(value) && value.length === 0))
994
+ callback(value);
995
+ else
996
+ defaultCallback?.();
997
+ },
998
+ isValue(key, value) {
999
+ return getAllInputFor(this)[key] === value;
1000
+ },
1001
+ async validate(rules, messages = {}) {
1002
+ const selectedRules = rules ?? this._requestValidationRules;
1003
+ if (!selectedRules || Object.keys(selectedRules).length === 0) {
1004
+ const input = getAllInputFor(this);
1005
+ this._validatedInput = input;
1006
+ return input;
1007
+ }
1008
+ const normalized = {};
1009
+ for (const [field, definition] of Object.entries(selectedRules)) {
1010
+ if (typeof definition === "string")
1011
+ throw TypeError(`String validation rules are not supported for "${field}". Use schema validators.`);
1012
+ if (definition && typeof definition === "object" && "rule" in definition) {
1013
+ const message = messages[field];
1014
+ normalized[field] = message ? { ...definition, message } : definition;
1015
+ } else
1016
+ normalized[field] = definition;
1017
+ }
1018
+ const { validate } = await import("@stacksjs/validation"), validated = await validate(this, normalized);
1019
+ this._validatedInput = validated;
1020
+ return validated;
1021
+ },
1022
+ getValidated() {
1023
+ return this._validatedInput ?? {};
1024
+ },
1025
+ safe() {
1026
+ const data = this._validatedInput ?? {};
1027
+ return {
1028
+ all: () => ({ ...data }),
1029
+ get: (key, defaultValue) => (key in data) ? data[key] : defaultValue,
1030
+ only: (keys) => Object.fromEntries(keys.filter((key) => (key in data)).map((key) => [key, data[key]])),
1031
+ except: (keys) => Object.fromEntries(Object.entries(data).filter(([key]) => !keys.includes(key)))
1032
+ };
1033
+ },
1034
+ old(key, defaultValue) {
1035
+ return this._oldInput?.[key] ?? defaultValue;
1036
+ },
1037
+ flashInput(keys) {
1038
+ flashInputFor(this, keys);
1039
+ },
1040
+ flashInputOnly(keys) {
1041
+ flashInputFor(this, keys);
1042
+ },
1043
+ flashInputExcept(keys) {
1044
+ const input = getAllInputFor(this);
1045
+ this._oldInput = Object.fromEntries(Object.entries(input).filter(([key]) => !keys.includes(key)));
1046
+ },
938
1047
  file(key) {
939
1048
  const file = (this.files || {})[key];
940
1049
  if (!file)
@@ -961,6 +1070,24 @@ const REQUEST_METHODS = {
961
1070
  result[key] = new UploadedFile(value);
962
1071
  return result;
963
1072
  },
1073
+ getParams() {
1074
+ return { ...this.params };
1075
+ },
1076
+ isEmpty() {
1077
+ return Object.keys(getAllInputFor(this)).length === 0;
1078
+ },
1079
+ browser() {
1080
+ return this.headers.get("sec-ch-ua") || this.headers.get("user-agent");
1081
+ },
1082
+ ipForRateLimit() {
1083
+ const ip = this.ip;
1084
+ if (typeof ip === "function")
1085
+ return ip.call(this) || null;
1086
+ return typeof ip === "string" && ip ? ip : null;
1087
+ },
1088
+ getMethod() {
1089
+ return this.method.toUpperCase();
1090
+ },
964
1091
  async user() {
965
1092
  return this._authenticatedUser;
966
1093
  },
@@ -1218,41 +1345,8 @@ export function createStacksRouter(config = {}) {
1218
1345
  },
1219
1346
  health() {
1220
1347
  bunRouter.get("/api/health", async () => {
1221
- const checks = {}, probe = async (name, fn) => {
1222
- const start = Date.now();
1223
- try {
1224
- const ac = new AbortController, t = setTimeout(() => ac.abort(), 1500);
1225
- await Promise.race([
1226
- fn(),
1227
- new Promise((_, rej) => ac.signal.addEventListener("abort", () => rej(Error("timeout"))))
1228
- ]);
1229
- clearTimeout(t);
1230
- checks[name] = { ok: !0, ms: Date.now() - start };
1231
- } catch (err) {
1232
- checks[name] = {
1233
- ok: !1,
1234
- ms: Date.now() - start,
1235
- message: err instanceof Error ? err.message : String(err)
1236
- };
1237
- }
1238
- };
1239
- await Promise.all([
1240
- probe("database", async () => {
1241
- const { db } = await import("@stacksjs/database");
1242
- await db.unsafe?.("SELECT 1");
1243
- }),
1244
- probe("cache", async () => {
1245
- const { cache } = await import("@stacksjs/cache"), k = `__health__:${Date.now()}`;
1246
- await cache.set(k, 1, 5);
1247
- await cache.del(k);
1248
- })
1249
- ]);
1250
- const healthy = Object.values(checks).every((c) => c.ok), body = {
1251
- status: healthy ? "healthy" : "degraded",
1252
- checks,
1253
- timestamp: Date.now()
1254
- };
1255
- return Response.json(body, { status: healthy ? 200 : 503 });
1348
+ const health = await checkApplicationHealth();
1349
+ return Response.json(health, { status: health.status === "healthy" ? 200 : 503 });
1256
1350
  });
1257
1351
  bunRouter.get("/__routes", (req) => {
1258
1352
  if (!isExposeRoutesAuthorized(req))
@@ -1288,7 +1382,10 @@ export function createStacksRouter(config = {}) {
1288
1382
  if (!isExposeRoutesAuthorized(req))
1289
1383
  return Response.json({ error: "disabled" }, { status: 404 });
1290
1384
  try {
1291
- const { generateOpenApi } = await import("@stacksjs/api"), spec = await generateOpenApi();
1385
+ const { generateOpenApi } = await import("@stacksjs/api"), spec = await generateOpenApi({
1386
+ write: !1,
1387
+ portable: !1
1388
+ });
1292
1389
  return Response.json(spec);
1293
1390
  } catch (err) {
1294
1391
  return Response.json({ error: "OpenAPI generation failed", message: err instanceof Error ? err.message : String(err) }, { status: 500 });
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/router",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.228",
5
+ "version": "0.70.230",
6
6
  "description": "The Stacks framework router.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -54,19 +54,20 @@
54
54
  "prepublishOnly": "bun run build"
55
55
  },
56
56
  "dependencies": {
57
- "@stacksjs/bun-router": "^0.0.20",
57
+ "@stacksjs/bun-router": "^0.0.21",
58
+ "@stacksjs/collections": "0.70.230",
58
59
  "ts-rate-limiter": "^0.4.2"
59
60
  },
60
61
  "devDependencies": {
61
- "@stacksjs/actions": "0.70.228",
62
- "@stacksjs/config": "0.70.228",
62
+ "@stacksjs/actions": "0.70.230",
63
+ "@stacksjs/config": "0.70.230",
63
64
  "better-dx": "^0.2.17",
64
- "@stacksjs/error-handling": "0.70.228",
65
- "@stacksjs/logging": "0.70.228",
66
- "@stacksjs/orm": "0.70.228",
67
- "@stacksjs/path": "0.70.228",
68
- "@stacksjs/storage": "0.70.228",
69
- "@stacksjs/types": "0.70.228",
70
- "@stacksjs/validation": "0.70.228"
65
+ "@stacksjs/error-handling": "0.70.230",
66
+ "@stacksjs/logging": "0.70.230",
67
+ "@stacksjs/orm": "0.70.230",
68
+ "@stacksjs/path": "0.70.230",
69
+ "@stacksjs/storage": "0.70.230",
70
+ "@stacksjs/types": "0.70.230",
71
+ "@stacksjs/validation": "0.70.230"
71
72
  }
72
73
  }