franchising 0.0.0-stage → 0.1.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 (227) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +88 -2
  3. package/dist/accounts-B4bnTXUd.js +242 -0
  4. package/dist/accounts-B4bnTXUd.js.map +1 -0
  5. package/dist/accounts-TyMPSHM0.cjs +313 -0
  6. package/dist/accounts-TyMPSHM0.cjs.map +1 -0
  7. package/dist/adapters-DM59AJfR.d.cts +216 -0
  8. package/dist/adapters-DM59AJfR.d.ts +216 -0
  9. package/dist/cli/template-assets/api/src/errors/codes.ts +17 -0
  10. package/dist/cli/template-assets/api/src/errors/index.ts +16 -0
  11. package/dist/cli/template-assets/api/src/filters/exception.ts +53 -0
  12. package/dist/cli/template-assets/api/src/main.ts +189 -0
  13. package/dist/cli/template-assets/api/src/modules/health/controller.ts +23 -0
  14. package/dist/cli/template-assets/api/src/modules/health/dto/response.dto.ts +23 -0
  15. package/dist/cli/template-assets/api/src/modules/health/module.ts +12 -0
  16. package/dist/cli/template-assets/api/src/modules/health/service.ts +54 -0
  17. package/dist/cli/template-assets/api/src/modules/messaging/module.ts +7 -0
  18. package/dist/cli/template-assets/api/src/modules/messaging/service.ts +74 -0
  19. package/dist/cli/template-assets/api/src/shared/exceptions.ts +40 -0
  20. package/dist/cli/template-assets/api/src/shared/response.ts +31 -0
  21. package/dist/cli/template-assets/api/src/telemetry.ts +59 -0
  22. package/dist/cli/template-assets/api/src/types.ts +8 -0
  23. package/dist/cli/template-assets/cloudflare/cache.service.ts +23 -0
  24. package/dist/cli/template-assets/cloudflare/queue.service.ts +22 -0
  25. package/dist/cli/template-assets/cloudflare/worker.ts +33 -0
  26. package/dist/cli/template-assets/packages/jobs/src/index.ts +49 -0
  27. package/dist/cli/template-assets/packages/queue-runtime/src/index.ts +54 -0
  28. package/dist/cli/template-assets/root/dot-dockerignore +11 -0
  29. package/dist/cli/template-assets/root/dot-editorconfig +13 -0
  30. package/dist/cli/template-assets/root/dot-oxfmtrc.json +9 -0
  31. package/dist/cli/template-assets/root/dot-oxlintrc.json +47 -0
  32. package/dist/cli/template-assets/root/lefthook.yml +18 -0
  33. package/dist/cli/template-assets/web/postcss.config.mjs +9 -0
  34. package/dist/cli/template-assets/web/src/app/(app)/dashboard/page.tsx +5 -0
  35. package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +25 -0
  36. package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +75 -0
  37. package/dist/cli/template-assets/web/src/app/globals.css +48 -0
  38. package/dist/cli/template-assets/web/src/app/layout.tsx +30 -0
  39. package/dist/cli/template-assets/web/src/app/page.tsx +20 -0
  40. package/dist/cli/template-assets/web/src/components/overview/overview-panel.tsx +27 -0
  41. package/dist/cli/template-assets/web/src/components/shell/app-shell.tsx +37 -0
  42. package/dist/cli/template-assets/web/src/components/shell/providers.tsx +22 -0
  43. package/dist/cli/template-assets/web/src/lib/api-client.ts +57 -0
  44. package/dist/cli/template-assets/web/src/lib/auth-client.ts +15 -0
  45. package/dist/cli/template-assets/web/src/lib/server-auth.ts +38 -0
  46. package/dist/cli/template-assets/web/src/types/api.ts +18 -0
  47. package/dist/cli/template-assets/worker/src/app.module.ts +5 -0
  48. package/dist/cli/template-assets/worker/src/env.ts +8 -0
  49. package/dist/cli/template-assets/worker/src/main.ts +25 -0
  50. package/dist/cli/template-assets/worker/src/modules/queue/config.ts +16 -0
  51. package/dist/cli/template-assets/worker/src/modules/queue/module.ts +11 -0
  52. package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +105 -0
  53. package/dist/cli/template-assets/worker/src/modules/queue/repository.ts +16 -0
  54. package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +17 -0
  55. package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +12 -0
  56. package/dist/cli/template-assets/worker-messaging/jobs-messaging.ts +12 -0
  57. package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +39 -0
  58. package/dist/cli/template-assets/worker-messaging/src/env.ts +14 -0
  59. package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +59 -0
  60. package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +8 -0
  61. package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +113 -0
  62. package/dist/cli.js +1218 -0
  63. package/dist/cn-BVOnrSza.js +1 -0
  64. package/dist/constants-C4iP0--i.js +38 -0
  65. package/dist/constants-C4iP0--i.js.map +1 -0
  66. package/dist/constants-rCR-LNSN.cjs +91 -0
  67. package/dist/constants-rCR-LNSN.cjs.map +1 -0
  68. package/dist/decorate-BR5FVX5x.js +14 -0
  69. package/dist/decorate-R-oqksAh.cjs +25 -0
  70. package/dist/decorateParam-BFJPEGKJ.cjs +13 -0
  71. package/dist/decorateParam-CKE7_J1s.js +8 -0
  72. package/dist/define-adapter-Cc0QrfKt.cjs +16 -0
  73. package/dist/define-adapter-Cc0QrfKt.cjs.map +1 -0
  74. package/dist/define-adapter-DRcXno3j.js +11 -0
  75. package/dist/define-adapter-DRcXno3j.js.map +1 -0
  76. package/dist/dispatcher-BsD7cO2w.cjs +84 -0
  77. package/dist/dispatcher-BsD7cO2w.cjs.map +1 -0
  78. package/dist/dispatcher-DA_l1Vkv.js +73 -0
  79. package/dist/dispatcher-DA_l1Vkv.js.map +1 -0
  80. package/dist/errors-DxHoXrLd.d.cts +46 -0
  81. package/dist/errors-DxHoXrLd.d.ts +46 -0
  82. package/dist/http/index.cjs +440 -0
  83. package/dist/http/index.cjs.map +1 -0
  84. package/dist/http/index.d.cts +257 -0
  85. package/dist/http/index.d.ts +257 -0
  86. package/dist/http/index.js +400 -0
  87. package/dist/http/index.js.map +1 -0
  88. package/dist/http/swagger.cjs +122 -0
  89. package/dist/http/swagger.cjs.map +1 -0
  90. package/dist/http/swagger.d.cts +59 -0
  91. package/dist/http/swagger.d.ts +59 -0
  92. package/dist/http/swagger.js +117 -0
  93. package/dist/http/swagger.js.map +1 -0
  94. package/dist/index-B3UOHsA9.d.ts +679 -0
  95. package/dist/index-Bdl0AiNM.d.ts +1262 -0
  96. package/dist/index-By8b4ksT.d.ts +25 -0
  97. package/dist/index-C1KmT8dQ.d.ts +174 -0
  98. package/dist/index-CYT1PFzo.d.cts +679 -0
  99. package/dist/index-Cj-10Q5F.d.cts +174 -0
  100. package/dist/index-DDSaLjXV.d.cts +25 -0
  101. package/dist/index-FTrYdHfq.d.cts +1262 -0
  102. package/dist/index.cjs +1 -0
  103. package/dist/index.d.cts +4 -0
  104. package/dist/index.d.ts +4 -0
  105. package/dist/index.js +1 -0
  106. package/dist/label-BqmJoVE-.cjs +1 -0
  107. package/dist/label-XeChe1Bu.js +1 -0
  108. package/dist/messaging/index.cjs +1 -0
  109. package/dist/messaging/index.d.cts +1775 -0
  110. package/dist/messaging/index.d.ts +1775 -0
  111. package/dist/messaging/index.js +1 -0
  112. package/dist/misc-BpM_lMTx.js +1 -0
  113. package/dist/misc-DkqJOm1V.cjs +1 -0
  114. package/dist/operational-CnxdBwVG.d.cts +13 -0
  115. package/dist/operational-CnxdBwVG.d.ts +13 -0
  116. package/dist/redaction-DhuHTlHA.js +124 -0
  117. package/dist/redaction-DhuHTlHA.js.map +1 -0
  118. package/dist/redaction-uRIQbTwZ.cjs +171 -0
  119. package/dist/redaction-uRIQbTwZ.cjs.map +1 -0
  120. package/dist/rolldown-runtime-auK_WOaK.cjs +1 -0
  121. package/dist/rolldown-runtime-xuxB8TGW.cjs +32 -0
  122. package/dist/runtime-C95UYYLb.cjs +111 -0
  123. package/dist/runtime-C95UYYLb.cjs.map +1 -0
  124. package/dist/runtime-DG2oBFYw.js +88 -0
  125. package/dist/runtime-DG2oBFYw.js.map +1 -0
  126. package/dist/skills-C1uwr9Pp.js +4 -0
  127. package/dist/skills-DuE-XnBp.js +1 -0
  128. package/dist/sso/client.cjs +37 -0
  129. package/dist/sso/client.cjs.map +1 -0
  130. package/dist/sso/client.d.cts +90 -0
  131. package/dist/sso/client.d.ts +90 -0
  132. package/dist/sso/client.js +36 -0
  133. package/dist/sso/client.js.map +1 -0
  134. package/dist/sso/index.cjs +833 -0
  135. package/dist/sso/index.cjs.map +1 -0
  136. package/dist/sso/index.d.cts +3 -0
  137. package/dist/sso/index.d.ts +3 -0
  138. package/dist/sso/index.js +821 -0
  139. package/dist/sso/index.js.map +1 -0
  140. package/dist/sso/nestjs.cjs +169 -0
  141. package/dist/sso/nestjs.cjs.map +1 -0
  142. package/dist/sso/nestjs.d.cts +92 -0
  143. package/dist/sso/nestjs.d.ts +92 -0
  144. package/dist/sso/nestjs.js +151 -0
  145. package/dist/sso/nestjs.js.map +1 -0
  146. package/dist/sso/resource.cjs +124 -0
  147. package/dist/sso/resource.cjs.map +1 -0
  148. package/dist/sso/resource.d.cts +3 -0
  149. package/dist/sso/resource.d.ts +3 -0
  150. package/dist/sso/resource.js +114 -0
  151. package/dist/sso/resource.js.map +1 -0
  152. package/dist/status-CRvlFPIs.js +13 -0
  153. package/dist/status-CRvlFPIs.js.map +1 -0
  154. package/dist/status-DtK6OHtj.cjs +24 -0
  155. package/dist/status-DtK6OHtj.cjs.map +1 -0
  156. package/dist/team-CJVAg4HH.d.cts +157 -0
  157. package/dist/team-CJVAg4HH.d.ts +157 -0
  158. package/dist/telemetry/adapters.cjs +6 -0
  159. package/dist/telemetry/adapters.d.cts +3 -0
  160. package/dist/telemetry/adapters.d.ts +3 -0
  161. package/dist/telemetry/adapters.js +4 -0
  162. package/dist/telemetry/betterstack.cjs +74 -0
  163. package/dist/telemetry/betterstack.cjs.map +1 -0
  164. package/dist/telemetry/betterstack.d.cts +12 -0
  165. package/dist/telemetry/betterstack.d.ts +12 -0
  166. package/dist/telemetry/betterstack.js +71 -0
  167. package/dist/telemetry/betterstack.js.map +1 -0
  168. package/dist/telemetry/index.cjs +1237 -0
  169. package/dist/telemetry/index.cjs.map +1 -0
  170. package/dist/telemetry/index.d.cts +114 -0
  171. package/dist/telemetry/index.d.ts +114 -0
  172. package/dist/telemetry/index.js +1205 -0
  173. package/dist/telemetry/index.js.map +1 -0
  174. package/dist/telemetry/posthog.cjs +72 -0
  175. package/dist/telemetry/posthog.cjs.map +1 -0
  176. package/dist/telemetry/posthog.d.cts +10 -0
  177. package/dist/telemetry/posthog.d.ts +10 -0
  178. package/dist/telemetry/posthog.js +71 -0
  179. package/dist/telemetry/posthog.js.map +1 -0
  180. package/dist/telemetry/register.cjs +6 -0
  181. package/dist/telemetry/register.d.cts +14 -0
  182. package/dist/telemetry/register.d.ts +14 -0
  183. package/dist/telemetry/register.js +3 -0
  184. package/dist/telemetry/testing.cjs +54 -0
  185. package/dist/telemetry/testing.cjs.map +1 -0
  186. package/dist/telemetry/testing.d.cts +15 -0
  187. package/dist/telemetry/testing.d.ts +15 -0
  188. package/dist/telemetry/testing.js +52 -0
  189. package/dist/telemetry/testing.js.map +1 -0
  190. package/dist/telemetry.mock-BSsx7L6S.cjs +45 -0
  191. package/dist/telemetry.mock-BSsx7L6S.cjs.map +1 -0
  192. package/dist/telemetry.mock-BZRpy63c.js +40 -0
  193. package/dist/telemetry.mock-BZRpy63c.js.map +1 -0
  194. package/dist/telemetry.mock-C1wXuf-M.d.cts +4 -0
  195. package/dist/telemetry.mock-CdaxofJ7.d.ts +4 -0
  196. package/dist/ui/chart.cjs +6 -0
  197. package/dist/ui/chart.d.cts +34 -0
  198. package/dist/ui/chart.d.ts +34 -0
  199. package/dist/ui/chart.js +6 -0
  200. package/dist/ui/form.cjs +1 -0
  201. package/dist/ui/form.d.cts +23 -0
  202. package/dist/ui/form.d.ts +23 -0
  203. package/dist/ui/form.js +1 -0
  204. package/dist/ui/hooks.cjs +1 -0
  205. package/dist/ui/hooks.d.cts +66 -0
  206. package/dist/ui/hooks.d.ts +66 -0
  207. package/dist/ui/hooks.js +1 -0
  208. package/dist/ui/index.cjs +1 -0
  209. package/dist/ui/index.d.cts +3 -0
  210. package/dist/ui/index.d.ts +3 -0
  211. package/dist/ui/index.js +1 -0
  212. package/dist/ui/styles.css +2 -0
  213. package/dist/ui/utils.cjs +1 -0
  214. package/dist/ui/utils.d.cts +199 -0
  215. package/dist/ui/utils.d.ts +199 -0
  216. package/dist/ui/utils.js +1 -0
  217. package/dist/use-mobile-BbeIMRgE.cjs +1 -0
  218. package/dist/use-mobile-Cdd4Lp7p.js +1 -0
  219. package/dist/use-mobile-ecpyXWz3.d.cts +10 -0
  220. package/dist/use-mobile-ecpyXWz3.d.ts +10 -0
  221. package/dist/verifier-BIBtPCVi.cjs +119 -0
  222. package/dist/verifier-BIBtPCVi.cjs.map +1 -0
  223. package/dist/verifier-DNdy5Ynw.js +90 -0
  224. package/dist/verifier-DNdy5Ynw.js.map +1 -0
  225. package/dist/version-CPunTYCY.js +1 -0
  226. package/dist/version-CfUi3iAV.cjs +1 -0
  227. package/package.json +523 -5
@@ -0,0 +1,1237 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_rolldown_runtime = require("../rolldown-runtime-xuxB8TGW.cjs");
3
+ const require_dispatcher = require("../dispatcher-BsD7cO2w.cjs");
4
+ const require_runtime = require("../runtime-C95UYYLb.cjs");
5
+ const require_decorate = require("../decorate-R-oqksAh.cjs");
6
+ const require_decorateParam = require("../decorateParam-BFJPEGKJ.cjs");
7
+ const require_redaction = require("../redaction-uRIQbTwZ.cjs");
8
+ const require_telemetry_mock = require("../telemetry.mock-BSsx7L6S.cjs");
9
+ let _nestjs_common = require("@nestjs/common");
10
+ let _nestjs_core = require("@nestjs/core");
11
+ let pino = require("pino");
12
+ pino = require_rolldown_runtime.__toESM(pino, 1);
13
+ let node_async_hooks = require("node:async_hooks");
14
+ let _opentelemetry_api = require("@opentelemetry/api");
15
+ let nestjs_pino = require("nestjs-pino");
16
+ let _opentelemetry_api_logs = require("@opentelemetry/api-logs");
17
+ let fastify = require("fastify");
18
+ let rxjs = require("rxjs");
19
+ let rxjs_operators = require("rxjs/operators");
20
+
21
+ // src/modules/telemetry/shared/context/context.ts
22
+ const storage = new node_async_hooks.AsyncLocalStorage();
23
+ function baseContext() {
24
+ const span = _opentelemetry_api.trace.getActiveSpan()?.spanContext();
25
+ return {
26
+ service: require_runtime.readEnv("OTEL_SERVICE_NAME", "SERVICE_NAME") ?? "unknown-service",
27
+ product: require_runtime.readEnv("TELEMETRY_PRODUCT"),
28
+ environment: require_runtime.readEnv("NODE_ENV") ?? "development",
29
+ release: require_runtime.readEnv("OTEL_SERVICE_VERSION", "RELEASE", "RAILWAY_DEPLOYMENT_ID", "GIT_SHA"),
30
+ traceId: span?.traceId,
31
+ spanId: span?.spanId,
32
+ ...storage.getStore()
33
+ };
34
+ }
35
+ let TelemetryContext = class TelemetryContext {
36
+ logger;
37
+ constructor(logger) {
38
+ this.logger = logger;
39
+ }
40
+ get() {
41
+ return baseContext();
42
+ }
43
+ assign(context) {
44
+ const current = storage.getStore();
45
+ if (current) Object.assign(current, context);
46
+ try {
47
+ this.logger?.assign({
48
+ actor_id: context.actorId,
49
+ organization_id: context.organizationId,
50
+ job_id: context.jobId,
51
+ correlation_id: context.correlationId
52
+ });
53
+ } catch {}
54
+ }
55
+ identify(actorId) {
56
+ this.assign({ actorId });
57
+ }
58
+ organization(organizationId) {
59
+ this.assign({ organizationId });
60
+ }
61
+ run(context, fn) {
62
+ return storage.run({
63
+ ...storage.getStore(),
64
+ ...context
65
+ }, fn);
66
+ }
67
+ };
68
+ TelemetryContext = require_decorate.__decorate([
69
+ (0, _nestjs_common.Injectable)(),
70
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Optional)()),
71
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(nestjs_pino.PinoLogger)),
72
+ require_decorate.__decorateMetadata("design:paramtypes", [Object])
73
+ ], TelemetryContext);
74
+
75
+ // src/modules/telemetry/shared/logging/otel.ts
76
+ const otelLogger = _opentelemetry_api_logs.logs.getLogger("@rockdev/telemetry", void 0, { includeTraceContext: true });
77
+ function severity(level) {
78
+ if (level >= 60) return {
79
+ text: "fatal",
80
+ number: _opentelemetry_api_logs.SeverityNumber.FATAL
81
+ };
82
+ if (level >= 50) return {
83
+ text: "error",
84
+ number: _opentelemetry_api_logs.SeverityNumber.ERROR
85
+ };
86
+ if (level >= 40) return {
87
+ text: "warn",
88
+ number: _opentelemetry_api_logs.SeverityNumber.WARN
89
+ };
90
+ if (level >= 30) return {
91
+ text: "info",
92
+ number: _opentelemetry_api_logs.SeverityNumber.INFO
93
+ };
94
+ if (level >= 20) return {
95
+ text: "debug",
96
+ number: _opentelemetry_api_logs.SeverityNumber.DEBUG
97
+ };
98
+ return {
99
+ text: "trace",
100
+ number: _opentelemetry_api_logs.SeverityNumber.TRACE
101
+ };
102
+ }
103
+ function toAnyValue(value) {
104
+ if (value instanceof Error) {
105
+ const safeError = require_redaction.sanitizeError(value);
106
+ return toAnyValue({
107
+ name: safeError.name,
108
+ message: safeError.message,
109
+ ...safeError.stack ? { stack: safeError.stack } : {}
110
+ });
111
+ }
112
+ if (typeof value === "string") return require_redaction.sanitizeText(value);
113
+ if (Array.isArray(value)) return value.map(toAnyValue);
114
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, require_redaction.isSensitiveKey(key) ? "[REDACTED]" : toAnyValue(child)]));
115
+ if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) return value;
116
+ return String(value);
117
+ }
118
+ function toLogRecord(args, level) {
119
+ const [first, second, ...rest] = args;
120
+ const body = {};
121
+ if (first && typeof first === "object" && !Array.isArray(first)) {
122
+ const safe = toAnyValue(first);
123
+ if (safe && typeof safe === "object" && !Array.isArray(safe)) Object.assign(body, safe);
124
+ if (second !== void 0 && typeof second !== "string") body.arguments = toAnyValue(second);
125
+ } else if (first !== void 0) body.message = typeof first === "string" ? require_redaction.sanitizeText(first) : toAnyValue(first);
126
+ if (typeof second === "string") body.message = require_redaction.sanitizeText(second);
127
+ if (rest.length > 0) body.arguments = toAnyValue(rest);
128
+ const currentSeverity = severity(level);
129
+ return {
130
+ body,
131
+ severityNumber: currentSeverity.number,
132
+ severityText: currentSeverity.text,
133
+ ...typeof body.event === "string" ? { eventName: body.event } : {}
134
+ };
135
+ }
136
+ function emitPinoLog(args, level) {
137
+ if (process.env.TELEMETRY_ENABLED === "false" || process.env.TELEMETRY_LOGS_ENABLED === "false") return;
138
+ try {
139
+ otelLogger.emit(toLogRecord(args, level));
140
+ } catch {}
141
+ }
142
+ function createTelemetryPinoHooks() {
143
+ return { logMethod(args, method, level) {
144
+ emitPinoLog(args, level);
145
+ method.apply(this, args);
146
+ } };
147
+ }
148
+
149
+ // src/modules/telemetry/shared/state/operational.ts
150
+ let TelemetryOperationalState = class TelemetryOperationalState {
151
+ signals = new Map([
152
+ "errors",
153
+ "events",
154
+ "logs",
155
+ "metrics",
156
+ "tracing"
157
+ ].map((signal) => [signal, {
158
+ failed: false,
159
+ failureCount: 0
160
+ }]));
161
+ recordFailure(signal) {
162
+ const current = this.signals.get(signal);
163
+ if (!current) return;
164
+ current.failed = true;
165
+ current.failureCount += 1;
166
+ current.lastFailureAt = (/* @__PURE__ */ new Date()).toISOString();
167
+ }
168
+ status(signal) {
169
+ return { ...this.signals.get(signal) ?? {
170
+ failed: false,
171
+ failureCount: 0
172
+ } };
173
+ }
174
+ };
175
+ TelemetryOperationalState = require_decorate.__decorate([(0, _nestjs_common.Injectable)()], TelemetryOperationalState);
176
+
177
+ // src/modules/telemetry/types/telemetry.ts
178
+ var Telemetry = class {};
179
+
180
+ // src/modules/telemetry/core/checked-telemetry.ts
181
+ var CheckedTelemetry = class extends Telemetry {
182
+ target;
183
+ adapters;
184
+ options;
185
+ constructor(target, adapters, options = {}) {
186
+ super();
187
+ this.target = target;
188
+ this.adapters = adapters;
189
+ this.options = options;
190
+ }
191
+ debug(event, attributes) {
192
+ this.require("logs", "telemetry.debug()");
193
+ this.target.debug(event, attributes);
194
+ }
195
+ info(event, attributes) {
196
+ this.require("logs", "telemetry.info()");
197
+ this.target.info(event, attributes);
198
+ }
199
+ warn(event, attributes) {
200
+ this.require("logs", "telemetry.warn()");
201
+ this.target.warn(event, attributes);
202
+ }
203
+ error(event, error, attributes) {
204
+ this.require("logs", "telemetry.error()");
205
+ this.target.error(event, error, attributes);
206
+ }
207
+ event(event, attributes) {
208
+ this.require("events", "telemetry.event()");
209
+ this.target.event(event, attributes);
210
+ }
211
+ captureException(error, attributes, options) {
212
+ this.require("errors", "telemetry.captureException()");
213
+ this.target.captureException(error, attributes, options);
214
+ }
215
+ async span(name, fn, attributes) {
216
+ this.require("tracing", "telemetry.span()");
217
+ return this.target.span(name, fn, attributes);
218
+ }
219
+ increment(name, value, attributes) {
220
+ this.require("metrics", "telemetry.increment()");
221
+ this.target.increment(name, value, attributes);
222
+ }
223
+ histogram(name, value, attributes) {
224
+ this.require("metrics", "telemetry.histogram()");
225
+ this.target.histogram(name, value, attributes);
226
+ }
227
+ async trackDependency(options, fn) {
228
+ this.requireDependency("telemetry.trackDependency()");
229
+ return this.target.trackDependency(options, fn);
230
+ }
231
+ runJob(options, fn) {
232
+ try {
233
+ this.requireDependency("telemetry.runJob()");
234
+ } catch (error) {
235
+ return Promise.reject(error);
236
+ }
237
+ return this.target.runJob(options, fn);
238
+ }
239
+ async fetch(input, init, options) {
240
+ this.requireDependency("telemetry.fetch()");
241
+ return this.target.fetch(input, init, options);
242
+ }
243
+ traceparent() {
244
+ return this.target.traceparent();
245
+ }
246
+ getContext() {
247
+ return this.target.getContext();
248
+ }
249
+ shutdown() {
250
+ return this.target.shutdown();
251
+ }
252
+ disabled(capability) {
253
+ if (process.env.TELEMETRY_ENABLED === "false") return true;
254
+ if (capability === "metrics") return process.env.TELEMETRY_METRICS_ENABLED === "false";
255
+ if (capability === "tracing") return this.options.tracing === false || process.env.TELEMETRY_TRACING_ENABLED === "false";
256
+ if (capability === "errors") return this.options.errors === false;
257
+ return false;
258
+ }
259
+ require(capability, operation) {
260
+ if (this.disabled(capability)) return;
261
+ this.adapters.assertSupports(capability, operation);
262
+ }
263
+ requireDependency(operation) {
264
+ this.require("tracing", operation);
265
+ this.require("metrics", operation);
266
+ this.require("errors", operation);
267
+ }
268
+ };
269
+
270
+ // src/modules/telemetry/shared/context/adapter.ts
271
+ function adapterContext(context) {
272
+ return require_redaction.sanitizeAttributes({ ...context });
273
+ }
274
+
275
+ // src/modules/telemetry/shared/di/tokens.ts
276
+ const TELEMETRY_OPTIONS = Symbol("TELEMETRY_OPTIONS");
277
+
278
+ // src/modules/telemetry/shared/utils/case.ts
279
+ function snakeCase(value) {
280
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[.-]/g, "_").toLowerCase();
281
+ }
282
+
283
+ // src/modules/telemetry/shared/logging/attributes.ts
284
+ function logAttributes(context, attributes) {
285
+ const record = {};
286
+ for (const [key, value] of Object.entries({
287
+ requestId: context.requestId,
288
+ traceId: context.traceId,
289
+ spanId: context.spanId,
290
+ service: context.service,
291
+ product: context.product,
292
+ environment: context.environment,
293
+ release: context.release,
294
+ actorId: context.actorId,
295
+ organizationId: context.organizationId,
296
+ jobId: context.jobId,
297
+ correlationId: context.correlationId,
298
+ ...attributes
299
+ })) if (value !== void 0) record[snakeCase(key)] = value;
300
+ return require_redaction.sanitizeAttributes(record);
301
+ }
302
+
303
+ // src/modules/telemetry/shared/metrics/instruments.ts
304
+ const meter = _opentelemetry_api.metrics.getMeter("@rockdev/telemetry");
305
+ const counters = /* @__PURE__ */ new Map();
306
+ const histograms = /* @__PURE__ */ new Map();
307
+
308
+ // src/modules/telemetry/shared/metrics/metrics.ts
309
+ const ALLOWED_METRIC_ATTRIBUTES = /* @__PURE__ */ new Set([
310
+ "service",
311
+ "route",
312
+ "method",
313
+ "status",
314
+ "statusCode",
315
+ "statusClass",
316
+ "result",
317
+ "dependency",
318
+ "operation",
319
+ "queue",
320
+ "job",
321
+ "product",
322
+ "channel",
323
+ "provider",
324
+ "priority",
325
+ "reason"
326
+ ]);
327
+ function validValue(key, value) {
328
+ if (typeof value !== "string" || value.length === 0 || value.length > 100) return false;
329
+ if (require_redaction.containsSensitiveText(value) || require_redaction.isLikelyIdentifier(value)) return false;
330
+ if (key === "route") return (value === "unmatched" || value.startsWith("/")) && !value.includes("?") && !value.includes("://") && !value.split("/").some((segment) => /^\d+$/.test(segment));
331
+ if (key === "method") return /^[A-Z]+$/.test(value);
332
+ if (key === "statusCode") return /^[1-5]\d\d$/.test(value);
333
+ if (key === "statusClass") return /^[1-5]xx$/.test(value);
334
+ if (key === "result") return value === "success" || value === "error";
335
+ return true;
336
+ }
337
+ function sanitizeMetricAttributes(attributes) {
338
+ if (!attributes) return {
339
+ attributes: void 0,
340
+ rejectedKeys: []
341
+ };
342
+ const valid = {};
343
+ const rejectedKeys = [];
344
+ for (const [rawKey, value] of Object.entries(attributes)) {
345
+ const key = rawKey;
346
+ if (!ALLOWED_METRIC_ATTRIBUTES.has(key) || require_redaction.isSensitiveKey(rawKey) || !validValue(key, value)) {
347
+ rejectedKeys.push(rawKey);
348
+ continue;
349
+ }
350
+ valid[key] = value;
351
+ }
352
+ return {
353
+ attributes: valid,
354
+ rejectedKeys
355
+ };
356
+ }
357
+
358
+ // src/modules/telemetry/core/telemetry.service.ts
359
+ let TelemetryService = class TelemetryService extends Telemetry {
360
+ logger;
361
+ context;
362
+ operationalState;
363
+ options;
364
+ adapters;
365
+ constructor(logger, context, operationalState, options = {}, adapters) {
366
+ super();
367
+ this.logger = logger;
368
+ this.context = context;
369
+ this.operationalState = operationalState;
370
+ this.options = options;
371
+ this.adapters = adapters;
372
+ }
373
+ debug(event, attributes) {
374
+ this.write("debug", event, attributes);
375
+ }
376
+ info(event, attributes) {
377
+ this.write("info", event, attributes);
378
+ }
379
+ warn(event, attributes) {
380
+ this.write("warn", event, attributes);
381
+ }
382
+ error(event, error, attributes) {
383
+ this.writeError(event, error, attributes);
384
+ }
385
+ event(event, attributes) {
386
+ try {
387
+ const context = this.getContext();
388
+ const safeAttributes = logAttributes(context, attributes);
389
+ this.logger.info({
390
+ event,
391
+ event_kind: "product",
392
+ ...safeAttributes
393
+ });
394
+ this.adapters?.captureEvent?.({
395
+ event,
396
+ attributes: safeAttributes,
397
+ context: adapterContext(context)
398
+ });
399
+ } catch {
400
+ this.operationalState.recordFailure("events");
401
+ }
402
+ }
403
+ captureException(error, attributes, options) {
404
+ this.error("exception.captured", error, attributes);
405
+ if (this.options.errors === false) return;
406
+ const reportError = require_redaction.sanitizeError(error, process.env.TELEMETRY_ERROR_STACK_ENABLED !== "false");
407
+ const reportContext = {
408
+ request: require_redaction.sanitizeAttributes({ ...this.getContext() }),
409
+ attributes: require_redaction.sanitizeAttributes(attributes)
410
+ };
411
+ this.adapters?.captureException?.({
412
+ error: reportError,
413
+ context: reportContext,
414
+ ...options?.fingerprint ? { fingerprint: options.fingerprint } : {}
415
+ });
416
+ }
417
+ async span(name, fn, attributes = {}) {
418
+ if (this.options.tracing === false || process.env.TELEMETRY_TRACING_ENABLED === "false") return fn({
419
+ setAttributes() {},
420
+ addEvent() {}
421
+ });
422
+ try {
423
+ return _opentelemetry_api.trace.getTracer(this.getContext().service).startActiveSpan(name, { attributes: require_redaction.sanitizeAttributes(attributes) }, async (span) => {
424
+ const startedAt = performance.now();
425
+ const events = [];
426
+ let spanError;
427
+ let spanAttributes = require_redaction.sanitizeAttributes(attributes);
428
+ const facade = {
429
+ setAttributes: (values) => {
430
+ const safe = require_redaction.sanitizeAttributes(values);
431
+ spanAttributes = {
432
+ ...spanAttributes,
433
+ ...safe
434
+ };
435
+ span.setAttributes(safe);
436
+ },
437
+ addEvent: (event, values) => {
438
+ const safe = require_redaction.sanitizeAttributes(values);
439
+ events.push({
440
+ name: event,
441
+ attributes: safe
442
+ });
443
+ span.addEvent(event, safe);
444
+ }
445
+ };
446
+ try {
447
+ return await fn(facade);
448
+ } catch (error) {
449
+ spanError = require_redaction.sanitizeError(error);
450
+ try {
451
+ span.recordException(require_redaction.sanitizeError(error));
452
+ span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
453
+ } catch {
454
+ this.operationalState.recordFailure("tracing");
455
+ }
456
+ throw error;
457
+ } finally {
458
+ this.adapters?.captureSpan?.({
459
+ name,
460
+ durationMs: performance.now() - startedAt,
461
+ attributes: spanAttributes,
462
+ events,
463
+ context: adapterContext(this.getContext()),
464
+ ...spanError ? { error: spanError } : {}
465
+ });
466
+ try {
467
+ span.end();
468
+ } catch {
469
+ this.operationalState.recordFailure("tracing");
470
+ }
471
+ }
472
+ });
473
+ } catch {
474
+ this.operationalState.recordFailure("tracing");
475
+ return fn({
476
+ setAttributes() {},
477
+ addEvent() {}
478
+ });
479
+ }
480
+ }
481
+ increment(name, value = 1, attributes) {
482
+ if (process.env.TELEMETRY_METRICS_ENABLED === "false") return;
483
+ const sanitized = sanitizeMetricAttributes(attributes);
484
+ this.warnRejectedMetricAttributes(name, sanitized.rejectedKeys);
485
+ try {
486
+ const instrument = counters.get(name) ?? meter.createCounter(name);
487
+ counters.set(name, instrument);
488
+ instrument.add(value, sanitized.attributes);
489
+ this.adapters?.captureMetric?.({
490
+ type: "counter",
491
+ name,
492
+ value,
493
+ attributes: sanitized.attributes ?? {},
494
+ context: adapterContext(this.getContext())
495
+ });
496
+ } catch {
497
+ this.operationalState.recordFailure("metrics");
498
+ }
499
+ }
500
+ histogram(name, value, attributes) {
501
+ if (process.env.TELEMETRY_METRICS_ENABLED === "false") return;
502
+ const sanitized = sanitizeMetricAttributes(attributes);
503
+ this.warnRejectedMetricAttributes(name, sanitized.rejectedKeys);
504
+ try {
505
+ const instrument = histograms.get(name) ?? meter.createHistogram(name, { unit: "ms" });
506
+ histograms.set(name, instrument);
507
+ instrument.record(value, sanitized.attributes);
508
+ this.adapters?.captureMetric?.({
509
+ type: "histogram",
510
+ name,
511
+ value,
512
+ attributes: sanitized.attributes ?? {},
513
+ context: adapterContext(this.getContext())
514
+ });
515
+ } catch {
516
+ this.operationalState.recordFailure("metrics");
517
+ }
518
+ }
519
+ async trackDependency(options, fn) {
520
+ const startedAt = performance.now();
521
+ try {
522
+ const result = await this.span(`dependency.${options.name}.${options.operation}`, async () => fn(), {
523
+ "dependency.name": options.name,
524
+ "operation.name": options.operation
525
+ });
526
+ this.increment("rock_dependency_requests_total", 1, {
527
+ dependency: options.name,
528
+ operation: options.operation,
529
+ result: "success"
530
+ });
531
+ return result;
532
+ } catch (error) {
533
+ this.increment("rock_dependency_requests_total", 1, {
534
+ dependency: options.name,
535
+ operation: options.operation,
536
+ result: "error"
537
+ });
538
+ this.captureException(error, {
539
+ dependency: options.name,
540
+ operation: options.operation
541
+ });
542
+ throw error;
543
+ } finally {
544
+ this.histogram("rock_dependency_request_duration_ms", performance.now() - startedAt, {
545
+ dependency: options.name,
546
+ operation: options.operation
547
+ });
548
+ }
549
+ }
550
+ runJob(options, fn) {
551
+ const run = () => this.context.run({
552
+ ...options.jobId ? { jobId: options.jobId } : {},
553
+ ...options.correlationId ? { correlationId: options.correlationId } : {}
554
+ }, () => this.trackDependency({
555
+ name: `queue.${options.queue}`,
556
+ operation: options.job
557
+ }, fn));
558
+ if (!options.traceparent) return run();
559
+ const parent = _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), { traceparent: options.traceparent });
560
+ return _opentelemetry_api.context.with(parent, run);
561
+ }
562
+ async fetch(input, init, options) {
563
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
564
+ let host = "unknown";
565
+ let path = url;
566
+ try {
567
+ const parsed = new URL(url);
568
+ host = parsed.host;
569
+ path = parsed.pathname;
570
+ } catch {}
571
+ const method = (init?.method ?? (input instanceof Request ? input.method : void 0) ?? "GET").toUpperCase();
572
+ const dependency = options?.dependency ?? host;
573
+ const operation = options?.operation ?? `${method} ${path}`;
574
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : {}));
575
+ _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), headers, { set: (carrier, key, value) => carrier.set(key, String(value)) });
576
+ return this.trackDependency({
577
+ name: dependency,
578
+ operation
579
+ }, () => this.span(`http.client.${dependency}`, async (span) => {
580
+ const response = await fetch(input, {
581
+ ...init,
582
+ headers
583
+ });
584
+ span.setAttributes({ "http.response.status_code": response.status });
585
+ return response;
586
+ }, {
587
+ "http.request.method": method,
588
+ "server.address": host,
589
+ "url.path": path,
590
+ ...options?.attributes
591
+ }));
592
+ }
593
+ traceparent() {
594
+ const carrier = {};
595
+ try {
596
+ _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), carrier);
597
+ } catch {
598
+ this.operationalState.recordFailure("tracing");
599
+ return;
600
+ }
601
+ return carrier.traceparent;
602
+ }
603
+ getContext() {
604
+ return this.context.get();
605
+ }
606
+ async shutdown() {
607
+ await Promise.allSettled([this.adapters?.shutdown() ?? Promise.resolve(), require_runtime.shutdownTelemetry().catch(() => {
608
+ this.operationalState.recordFailure("logs");
609
+ this.operationalState.recordFailure("metrics");
610
+ this.operationalState.recordFailure("tracing");
611
+ })]);
612
+ }
613
+ write(level, event, attributes) {
614
+ try {
615
+ const context = this.getContext();
616
+ const safeAttributes = logAttributes(context, attributes);
617
+ this.logger[level]({
618
+ event,
619
+ ...safeAttributes
620
+ });
621
+ this.adapters?.captureLog?.({
622
+ level,
623
+ event,
624
+ attributes: safeAttributes,
625
+ context: adapterContext(context)
626
+ });
627
+ } catch {
628
+ this.operationalState.recordFailure("logs");
629
+ }
630
+ }
631
+ writeError(event, error, attributes) {
632
+ try {
633
+ const context = this.getContext();
634
+ const safeAttributes = logAttributes(context, attributes);
635
+ this.logger.error({
636
+ event,
637
+ err: require_redaction.sanitizeError(error),
638
+ ...safeAttributes
639
+ });
640
+ this.adapters?.captureLog?.({
641
+ level: "error",
642
+ event,
643
+ attributes: safeAttributes,
644
+ context: adapterContext(context)
645
+ });
646
+ } catch {
647
+ this.operationalState.recordFailure("logs");
648
+ }
649
+ }
650
+ warnRejectedMetricAttributes(metricName, rejectedKeys) {
651
+ if (rejectedKeys.length === 0) return;
652
+ this.write("warn", "telemetry.metric_attributes_rejected", {
653
+ metricName,
654
+ rejectedAttributeKeys: rejectedKeys
655
+ });
656
+ }
657
+ };
658
+ TelemetryService = require_decorate.__decorate([
659
+ (0, _nestjs_common.Injectable)(),
660
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(nestjs_pino.PinoLogger)),
661
+ require_decorateParam.__decorateParam(1, (0, _nestjs_common.Inject)(TelemetryContext)),
662
+ require_decorateParam.__decorateParam(2, (0, _nestjs_common.Inject)(TelemetryOperationalState)),
663
+ require_decorateParam.__decorateParam(3, (0, _nestjs_common.Inject)(TELEMETRY_OPTIONS)),
664
+ require_decorateParam.__decorateParam(4, (0, _nestjs_common.Inject)(require_dispatcher.TelemetryAdapterDispatcher)),
665
+ require_decorate.__decorateMetadata("design:paramtypes", [
666
+ Object,
667
+ typeof TelemetryContext === "undefined" ? Object : TelemetryContext,
668
+ typeof TelemetryOperationalState === "undefined" ? Object : TelemetryOperationalState,
669
+ Object,
670
+ typeof require_dispatcher.TelemetryAdapterDispatcher === "undefined" ? Object : require_dispatcher.TelemetryAdapterDispatcher
671
+ ])
672
+ ], TelemetryService);
673
+
674
+ // src/modules/telemetry/core/create-telemetry.ts
675
+ function createTelemetry(options = {}) {
676
+ const context = new TelemetryContext();
677
+ const operationalState = new TelemetryOperationalState();
678
+ const logger = (0, pino.default)({
679
+ hooks: createTelemetryPinoHooks(),
680
+ level: process.env.LOG_LEVEL ?? "info",
681
+ redact: {
682
+ paths: require_redaction.DEFAULT_REDACT_PATHS,
683
+ censor: "[REDACTED]"
684
+ }
685
+ });
686
+ const adapters = new require_dispatcher.TelemetryAdapterDispatcher(options.adapters ?? [], operationalState);
687
+ return new CheckedTelemetry(new TelemetryService(logger, context, operationalState, options, adapters), adapters, options);
688
+ }
689
+
690
+ // src/modules/telemetry/shared/tracing/span.ts
691
+ function recordError(span, error) {
692
+ try {
693
+ span.recordException(require_redaction.sanitizeError(error));
694
+ span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
695
+ } catch {}
696
+ }
697
+ function endSpan(span) {
698
+ try {
699
+ span.end();
700
+ } catch {}
701
+ }
702
+
703
+ // src/modules/telemetry/shared/utils/promise.ts
704
+ function isPromiseLike(value) {
705
+ return typeof value === "object" && value !== null && typeof value.then === "function";
706
+ }
707
+
708
+ // src/modules/telemetry/core/trace.decorator.ts
709
+ function Trace(name, attributes = {}) {
710
+ return (_target, _propertyKey, descriptor) => {
711
+ const typedDescriptor = descriptor;
712
+ const original = typedDescriptor.value;
713
+ if (!original) return;
714
+ typedDescriptor.value = function traced(...args) {
715
+ const invoke = () => original.apply(this, args);
716
+ if (process.env.TELEMETRY_TRACING_ENABLED === "false") return invoke();
717
+ try {
718
+ return _opentelemetry_api.trace.getTracer(require_runtime.readEnv("OTEL_SERVICE_NAME") ?? "unknown-service").startActiveSpan(name, { attributes: require_redaction.sanitizeAttributes(attributes) }, (span) => {
719
+ try {
720
+ const result = invoke();
721
+ if (!isPromiseLike(result)) {
722
+ endSpan(span);
723
+ return result;
724
+ }
725
+ return result.then((value) => {
726
+ endSpan(span);
727
+ return value;
728
+ }, (error) => {
729
+ recordError(span, error);
730
+ endSpan(span);
731
+ throw error;
732
+ });
733
+ } catch (error) {
734
+ recordError(span, error);
735
+ endSpan(span);
736
+ throw error;
737
+ }
738
+ });
739
+ } catch {
740
+ return invoke();
741
+ }
742
+ };
743
+ };
744
+ }
745
+
746
+ // src/modules/telemetry/nest/health/indicator.ts
747
+ let TelemetryHealthIndicator = class TelemetryHealthIndicator {
748
+ operationalState;
749
+ options = {};
750
+ status() {
751
+ const enabled = process.env.TELEMETRY_ENABLED !== "false";
752
+ return { telemetry: {
753
+ status: enabled ? "up" : "disabled",
754
+ errors: enabled && this.options.errors !== false && process.env.TELEMETRY_ERRORS_ENABLED !== "false",
755
+ events: enabled,
756
+ metrics: enabled && process.env.TELEMETRY_METRICS_ENABLED !== "false",
757
+ tracing: enabled && this.options.tracing !== false && process.env.TELEMETRY_TRACING_ENABLED !== "false",
758
+ otlpConfigured: Boolean(this.options.adapters?.some((adapter) => adapter.otlp?.())),
759
+ adapters: (this.options.adapters ?? []).map((adapter) => adapter.name),
760
+ signals: {
761
+ errors: this.operationalState.status("errors"),
762
+ events: this.operationalState.status("events"),
763
+ logs: this.operationalState.status("logs"),
764
+ metrics: this.operationalState.status("metrics"),
765
+ tracing: this.operationalState.status("tracing")
766
+ }
767
+ } };
768
+ }
769
+ };
770
+ require_decorate.__decorate([(0, _nestjs_common.Inject)(TelemetryOperationalState), require_decorate.__decorateMetadata("design:type", typeof TelemetryOperationalState === "undefined" ? Object : TelemetryOperationalState)], TelemetryHealthIndicator.prototype, "operationalState", void 0);
771
+ require_decorate.__decorate([(0, _nestjs_common.Inject)(TELEMETRY_OPTIONS), require_decorate.__decorateMetadata("design:type", Object)], TelemetryHealthIndicator.prototype, "options", void 0);
772
+ TelemetryHealthIndicator = require_decorate.__decorate([(0, _nestjs_common.Injectable)()], TelemetryHealthIndicator);
773
+
774
+ // src/modules/telemetry/shared/http/log.ts
775
+ function resolveHttpSuccessLogsEnabled(logging) {
776
+ if (logging?.httpSuccessLogs !== void 0) return logging.httpSuccessLogs;
777
+ if (process.env.TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED === "false") return false;
778
+ if (process.env.TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED === "true") return true;
779
+ return true;
780
+ }
781
+ function positiveFiniteNumber(value) {
782
+ return Number.isFinite(value) && value > 0 ? value : void 0;
783
+ }
784
+ function resolveHttpSlowRequestMs(logging) {
785
+ if (logging?.httpSlowRequestMs !== void 0) return positiveFiniteNumber(logging.httpSlowRequestMs);
786
+ const configured = process.env.TELEMETRY_HTTP_SLOW_REQUEST_MS;
787
+ if (configured === void 0 || configured.trim() === "") return void 0;
788
+ return positiveFiniteNumber(Number(configured));
789
+ }
790
+ function httpLogLevel(response, error, successLogsEnabled) {
791
+ const statusCode = response.statusCode ?? 500;
792
+ if (!error && !successLogsEnabled && statusCode < 400) return "silent";
793
+ if (error || statusCode >= 500) return "error";
794
+ if (statusCode >= 400) return "warn";
795
+ return "info";
796
+ }
797
+ function requestRoute(request) {
798
+ return request.route?.path ?? request.routerPath ?? request.routeOptions?.url ?? "unmatched";
799
+ }
800
+ function clientIp(request) {
801
+ return request.ip ?? request.socket?.remoteAddress;
802
+ }
803
+ function httpRequestLog(request) {
804
+ return {
805
+ request_id: typeof request.id === "string" ? request.id : void 0,
806
+ method: request.method,
807
+ route: requestRoute(request),
808
+ client_ip: clientIp(request)
809
+ };
810
+ }
811
+ function httpResponseLog(response) {
812
+ return { status_code: response.statusCode };
813
+ }
814
+ function httpCompletionLog(request, response, value, error = false) {
815
+ return {
816
+ event: error ? "request.failed" : "request.completed",
817
+ request_id: typeof request.id === "string" ? request.id : void 0,
818
+ method: request.method,
819
+ route: requestRoute(request),
820
+ client_ip: clientIp(request),
821
+ status_code: response.statusCode,
822
+ duration_ms: value?.responseTime
823
+ };
824
+ }
825
+
826
+ // src/modules/telemetry/shared/http/request.ts
827
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
828
+ function resolveRequestId(headers, header = "x-request-id") {
829
+ const incoming = headers?.[header.toLowerCase()];
830
+ const value = Array.isArray(incoming) ? incoming[0] : incoming;
831
+ return typeof value === "string" && UUID_PATTERN.test(value) ? value : crypto.randomUUID();
832
+ }
833
+ function isRequestId(value) {
834
+ return typeof value === "string" && UUID_PATTERN.test(value);
835
+ }
836
+ function createTelemetryFastifyOptions(options = {}) {
837
+ const requestIdHeader = options.requestId?.header ?? "x-request-id";
838
+ const excludedLogPaths = new Set(options.logging?.excludePaths ?? []);
839
+ const httpSuccessLogsEnabled = resolveHttpSuccessLogsEnabled(options.logging);
840
+ return {
841
+ requestIdHeader,
842
+ logController: new TelemetryFastifyLogController({
843
+ disableRequestLogging: (request) => excludedLogPaths.has((request.url ?? "").split("?")[0] ?? ""),
844
+ requestIdLogLabel: "request_id"
845
+ }, httpSuccessLogsEnabled),
846
+ genReqId: (request) => isRequestId(request.id) ? request.id : resolveRequestId(request.headers, requestIdHeader),
847
+ logger: {
848
+ level: options.logging?.level ?? process.env.LOG_LEVEL ?? "info",
849
+ redact: {
850
+ paths: [...require_redaction.DEFAULT_REDACT_PATHS, ...options.logging?.redact ?? []],
851
+ censor: "[REDACTED]"
852
+ },
853
+ serializers: {
854
+ req: httpRequestLog,
855
+ res: httpResponseLog
856
+ },
857
+ customSuccessObject: httpCompletionLog,
858
+ customErrorObject: (request, response, value) => httpCompletionLog(request, response, value, true)
859
+ }
860
+ };
861
+ }
862
+ var TelemetryFastifyLogController = class extends fastify.LogController {
863
+ httpSuccessLogsEnabled;
864
+ constructor(options, httpSuccessLogsEnabled) {
865
+ super(options);
866
+ this.httpSuccessLogsEnabled = httpSuccessLogsEnabled;
867
+ }
868
+ incomingRequest(request) {
869
+ if (this.isLogDisabled(request) || !this.httpSuccessLogsEnabled) return;
870
+ request.log.info({ req: httpRequestLog(request) }, "incoming request");
871
+ }
872
+ requestCompleted(error, request, reply) {
873
+ if (this.isLogDisabled(request)) return;
874
+ const fields = httpCompletionLog(request, reply, { responseTime: reply.elapsedTime }, Boolean(error));
875
+ if (error) reply.log.error({
876
+ ...fields,
877
+ err: require_redaction.sanitizeError(error)
878
+ }, "request errored");
879
+ else {
880
+ const level = httpLogLevel(reply, error, this.httpSuccessLogsEnabled);
881
+ if (level === "silent") return;
882
+ if (level === "error") reply.log.error(fields, "request completed");
883
+ else if (level === "warn") reply.log.warn(fields, "request completed");
884
+ else reply.log.info(fields, "request completed");
885
+ }
886
+ }
887
+ defaultErrorLog(error, request, reply) {
888
+ if (this.isLogDisabled(request)) return;
889
+ reply.log.error({
890
+ ...httpCompletionLog(request, reply, void 0, true),
891
+ err: require_redaction.sanitizeError(error)
892
+ }, "request failed");
893
+ }
894
+ routeNotFound(request, reply) {
895
+ if (this.isLogDisabled(request)) return;
896
+ reply.log.info(httpCompletionLog(request, reply), "route not found");
897
+ }
898
+ };
899
+
900
+ // src/modules/telemetry/shared/http/error-response.ts
901
+ function defaultCode(statusCode) {
902
+ return {
903
+ 400: "BAD_REQUEST",
904
+ 401: "UNAUTHORIZED",
905
+ 403: "FORBIDDEN",
906
+ 404: "NOT_FOUND",
907
+ 409: "CONFLICT",
908
+ 422: "UNPROCESSABLE_ENTITY",
909
+ 429: "RATE_LIMITED",
910
+ 502: "UPSTREAM_ERROR"
911
+ }[statusCode] ?? (statusCode >= 500 ? "INTERNAL_ERROR" : "REQUEST_FAILED");
912
+ }
913
+ function defaultMessage(exception, statusCode) {
914
+ if (statusCode >= 500) return "Internal server error";
915
+ if (!(exception instanceof _nestjs_common.HttpException)) return "Request failed";
916
+ const response = exception.getResponse();
917
+ if (typeof response === "string") return response;
918
+ if (response && typeof response === "object" && "message" in response) {
919
+ const message = response.message;
920
+ return Array.isArray(message) ? message.join(". ") : String(message);
921
+ }
922
+ return exception.message;
923
+ }
924
+
925
+ // src/modules/telemetry/nest/filters/exception.ts
926
+ let TelemetryExceptionFilter = class TelemetryExceptionFilter extends _nestjs_core.BaseExceptionFilter {
927
+ telemetry;
928
+ options;
929
+ constructor(telemetry, options) {
930
+ super();
931
+ this.telemetry = telemetry;
932
+ this.options = options;
933
+ }
934
+ catch(exception, host) {
935
+ const status = exception instanceof _nestjs_common.HttpException ? exception.getStatus() : 500;
936
+ if (status >= 500 || status === 429) this.telemetry.captureException(exception, { statusCode: status });
937
+ const requestId = this.telemetry.getContext().requestId;
938
+ const formatted = this.options.http?.mapException?.(exception, {
939
+ statusCode: status,
940
+ requestId
941
+ }) ?? {
942
+ code: defaultCode(status),
943
+ message: defaultMessage(exception, status)
944
+ };
945
+ const response = host.switchToHttp().getResponse();
946
+ const reply = response.status?.(status) ?? response.code?.(status) ?? response;
947
+ const body = { error: {
948
+ ...formatted,
949
+ requestId
950
+ } };
951
+ if ("json" in response && typeof response.json === "function") response.json(body);
952
+ else if ("send" in response && typeof response.send === "function") response.send(body);
953
+ else if (typeof reply.send === "function") reply.send(body);
954
+ }
955
+ };
956
+ TelemetryExceptionFilter = require_decorate.__decorate([
957
+ (0, _nestjs_common.Catch)(),
958
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(TelemetryService)),
959
+ require_decorateParam.__decorateParam(1, (0, _nestjs_common.Inject)(TELEMETRY_OPTIONS)),
960
+ require_decorate.__decorateMetadata("design:paramtypes", [typeof TelemetryService === "undefined" ? Object : TelemetryService, Object])
961
+ ], TelemetryExceptionFilter);
962
+
963
+ // src/modules/telemetry/nest/interceptor.ts
964
+ let TelemetryHttpInterceptor = class TelemetryHttpInterceptor {
965
+ telemetry;
966
+ context;
967
+ options;
968
+ constructor(telemetry, context, options) {
969
+ this.telemetry = telemetry;
970
+ this.context = context;
971
+ this.options = options;
972
+ }
973
+ intercept(executionContext, next) {
974
+ if (executionContext.getType() !== "http") return next.handle();
975
+ const http = executionContext.switchToHttp();
976
+ const request = http.getRequest();
977
+ const response = http.getResponse();
978
+ const requestId = request.id;
979
+ const requestIdHeader = this.options.requestId?.header ?? "x-request-id";
980
+ const responseHeaders = response;
981
+ if (requestId) {
982
+ responseHeaders.setHeader?.(requestIdHeader, requestId);
983
+ responseHeaders.header?.(requestIdHeader, requestId);
984
+ }
985
+ const route = requestRoute(request);
986
+ const startedAt = performance.now();
987
+ const extracted = this.options.context?.extract?.(request);
988
+ if (extracted) this.context.assign(extracted);
989
+ const httpMetricsEnabled = this.options.metrics?.http !== false;
990
+ const httpSuccessLogsEnabled = resolveHttpSuccessLogsEnabled(this.options.logging);
991
+ const httpSlowRequestMs = resolveHttpSlowRequestMs(this.options.logging);
992
+ return new rxjs.Observable((subscriber) => {
993
+ let streamFailed = false;
994
+ if (httpMetricsEnabled) this.telemetry.increment("rock_http_requests_active", 1, {
995
+ method: request.method,
996
+ route
997
+ });
998
+ return next.handle().pipe((0, rxjs_operators.tap)({ error: () => streamFailed = true }), (0, rxjs_operators.finalize)(() => {
999
+ const statusCode = response.statusCode ?? 500;
1000
+ const durationMs = performance.now() - startedAt;
1001
+ const attributes = {
1002
+ method: request.method,
1003
+ route,
1004
+ statusCode: String(statusCode),
1005
+ statusClass: `${Math.floor(statusCode / 100)}xx`
1006
+ };
1007
+ if (httpMetricsEnabled) {
1008
+ this.telemetry.increment("rock_http_requests_total", 1, attributes);
1009
+ this.telemetry.increment("rock_http_requests_active", -1, {
1010
+ method: request.method,
1011
+ route
1012
+ });
1013
+ this.telemetry.histogram("rock_http_request_duration_ms", durationMs, attributes);
1014
+ }
1015
+ if (!streamFailed && !httpSuccessLogsEnabled && httpSlowRequestMs !== void 0 && statusCode < 400 && durationMs >= httpSlowRequestMs) this.telemetry.warn("http.request_slow", {
1016
+ method: request.method,
1017
+ route,
1018
+ statusCode,
1019
+ durationMs,
1020
+ thresholdMs: httpSlowRequestMs
1021
+ });
1022
+ })).subscribe(subscriber);
1023
+ });
1024
+ }
1025
+ };
1026
+ TelemetryHttpInterceptor = require_decorate.__decorate([(0, _nestjs_common.Injectable)(), require_decorate.__decorateMetadata("design:paramtypes", [
1027
+ Object,
1028
+ Object,
1029
+ Object
1030
+ ])], TelemetryHttpInterceptor);
1031
+
1032
+ // src/modules/telemetry/nest/loggers/nest.ts
1033
+ let TelemetryNestLogger = class TelemetryNestLogger {
1034
+ logger;
1035
+ constructor(logger) {
1036
+ this.logger = logger;
1037
+ }
1038
+ log(message, ...optionalParams) {
1039
+ this.write("info", message, optionalParams);
1040
+ }
1041
+ error(message, ...optionalParams) {
1042
+ this.write("error", message, optionalParams);
1043
+ }
1044
+ warn(message, ...optionalParams) {
1045
+ this.write("warn", message, optionalParams);
1046
+ }
1047
+ debug(message, ...optionalParams) {
1048
+ this.write("debug", message, optionalParams);
1049
+ }
1050
+ verbose(message, ...optionalParams) {
1051
+ this.write("trace", message, optionalParams);
1052
+ }
1053
+ fatal(message, ...optionalParams) {
1054
+ this.write("fatal", message, optionalParams);
1055
+ }
1056
+ write(level, message, optionalParams) {
1057
+ this.logger[level].call(this.logger, this.sanitizeLogValue(message), ...optionalParams.map((value) => this.sanitizeLogValue(value)));
1058
+ }
1059
+ sanitizeLogValue(value) {
1060
+ if (value instanceof Error) return require_redaction.sanitizeError(value);
1061
+ if (typeof value === "string") return require_redaction.sanitizeText(value);
1062
+ return require_redaction.sanitize(value);
1063
+ }
1064
+ };
1065
+ TelemetryNestLogger = require_decorate.__decorate([
1066
+ (0, _nestjs_common.Injectable)(),
1067
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(nestjs_pino.PinoLogger)),
1068
+ require_decorate.__decorateMetadata("design:paramtypes", [Object])
1069
+ ], TelemetryNestLogger);
1070
+
1071
+ // src/modules/telemetry/nest/middlewares/context.ts
1072
+ let TelemetryContextMiddleware = class TelemetryContextMiddleware {
1073
+ context;
1074
+ options;
1075
+ constructor(context, options) {
1076
+ this.context = context;
1077
+ this.options = options;
1078
+ }
1079
+ use(request, response, next) {
1080
+ const requestIdHeader = this.options.requestId?.header ?? "x-request-id";
1081
+ const requestId = isRequestId(request.id) ? request.id : resolveRequestId(request.headers, requestIdHeader);
1082
+ request.id = requestId;
1083
+ response.setHeader?.(requestIdHeader, requestId);
1084
+ response.header?.(requestIdHeader, requestId);
1085
+ this.context.run({
1086
+ requestId,
1087
+ ...this.options.context?.extract?.(request)
1088
+ }, next);
1089
+ }
1090
+ };
1091
+ TelemetryContextMiddleware = require_decorate.__decorate([
1092
+ (0, _nestjs_common.Injectable)(),
1093
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(TelemetryContext)),
1094
+ require_decorateParam.__decorateParam(1, (0, _nestjs_common.Inject)(TELEMETRY_OPTIONS)),
1095
+ require_decorate.__decorateMetadata("design:paramtypes", [typeof TelemetryContext === "undefined" ? Object : TelemetryContext, Object])
1096
+ ], TelemetryContextMiddleware);
1097
+
1098
+ // src/modules/telemetry/nest/shutdown.ts
1099
+ let TelemetryShutdownService = class TelemetryShutdownService {
1100
+ telemetry;
1101
+ constructor(telemetry) {
1102
+ this.telemetry = telemetry;
1103
+ }
1104
+ onApplicationBootstrap() {
1105
+ if (require_runtime.isTelemetryRegistered() || process.env.TELEMETRY_ENABLED === "false") return;
1106
+ this.telemetry.warn("telemetry.sdk_not_registered", { hint: "call registerTelemetry({ adapters }) as the first statement of the process entrypoint" });
1107
+ }
1108
+ async onApplicationShutdown() {
1109
+ await this.telemetry.shutdown();
1110
+ }
1111
+ };
1112
+ TelemetryShutdownService = require_decorate.__decorate([
1113
+ (0, _nestjs_common.Injectable)(),
1114
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(TelemetryService)),
1115
+ require_decorate.__decorateMetadata("design:paramtypes", [typeof TelemetryService === "undefined" ? Object : TelemetryService])
1116
+ ], TelemetryShutdownService);
1117
+
1118
+ // src/modules/telemetry/nest/module.ts
1119
+ var _TelemetryModule;
1120
+ let TelemetryModule = _TelemetryModule = class TelemetryModule {
1121
+ _options;
1122
+ constructor(_options) {
1123
+ this._options = _options;
1124
+ }
1125
+ configure(consumer) {
1126
+ consumer.apply(TelemetryContextMiddleware).forRoutes({
1127
+ path: "*",
1128
+ method: _nestjs_common.RequestMethod.ALL
1129
+ });
1130
+ }
1131
+ static forRoot(options = {}) {
1132
+ const requestIdHeader = options.requestId?.header ?? "x-request-id";
1133
+ const excludedLogPaths = new Set(options.logging?.excludePaths ?? []);
1134
+ const httpSuccessLogsEnabled = resolveHttpSuccessLogsEnabled(options.logging);
1135
+ return {
1136
+ global: true,
1137
+ module: _TelemetryModule,
1138
+ imports: [nestjs_pino.LoggerModule.forRoot({ pinoHttp: {
1139
+ hooks: createTelemetryPinoHooks(),
1140
+ level: options.logging?.level ?? process.env.LOG_LEVEL ?? "info",
1141
+ customLogLevel: (_request, response, error) => httpLogLevel(response, error, httpSuccessLogsEnabled),
1142
+ redact: {
1143
+ paths: [...require_redaction.DEFAULT_REDACT_PATHS, ...options.logging?.redact ?? []],
1144
+ censor: "[REDACTED]"
1145
+ },
1146
+ genReqId(request, response) {
1147
+ const id = isRequestId(request.id) ? request.id : resolveRequestId(request.headers, requestIdHeader);
1148
+ response.setHeader?.(requestIdHeader, id);
1149
+ return id;
1150
+ },
1151
+ serializers: {
1152
+ req: httpRequestLog,
1153
+ res: httpResponseLog
1154
+ },
1155
+ customSuccessObject: (request, response, value) => httpCompletionLog(request, response, value),
1156
+ customErrorObject: (request, response) => httpCompletionLog(request, response, void 0, true),
1157
+ autoLogging: { ignore: (request) => excludedLogPaths.has((request.url ?? "").split("?")[0] ?? "") }
1158
+ } })],
1159
+ providers: [
1160
+ {
1161
+ provide: TELEMETRY_OPTIONS,
1162
+ useValue: options
1163
+ },
1164
+ TelemetryContext,
1165
+ TelemetryContextMiddleware,
1166
+ TelemetryOperationalState,
1167
+ {
1168
+ provide: require_dispatcher.TelemetryAdapterDispatcher,
1169
+ useFactory: (state) => new require_dispatcher.TelemetryAdapterDispatcher(options.adapters ?? [], state),
1170
+ inject: [TelemetryOperationalState]
1171
+ },
1172
+ TelemetryService,
1173
+ TelemetryExceptionFilter,
1174
+ TelemetryHealthIndicator,
1175
+ TelemetryShutdownService,
1176
+ TelemetryNestLogger,
1177
+ {
1178
+ provide: Telemetry,
1179
+ useFactory: (service, dispatcher) => new CheckedTelemetry(service, dispatcher, options),
1180
+ inject: [TelemetryService, require_dispatcher.TelemetryAdapterDispatcher]
1181
+ },
1182
+ ...options.http?.filter === false ? [] : [{
1183
+ provide: _nestjs_core.APP_FILTER,
1184
+ useExisting: TelemetryExceptionFilter
1185
+ }],
1186
+ {
1187
+ provide: _nestjs_core.APP_INTERCEPTOR,
1188
+ useFactory: (telemetry, context) => new TelemetryHttpInterceptor(telemetry, context, options),
1189
+ inject: [TelemetryService, TelemetryContext]
1190
+ }
1191
+ ],
1192
+ exports: [
1193
+ Telemetry,
1194
+ TelemetryContext,
1195
+ TelemetryHealthIndicator,
1196
+ TelemetryNestLogger
1197
+ ]
1198
+ };
1199
+ }
1200
+ };
1201
+ TelemetryModule = _TelemetryModule = require_decorate.__decorate([
1202
+ (0, _nestjs_common.Module)({}),
1203
+ require_decorateParam.__decorateParam(0, (0, _nestjs_common.Inject)(TELEMETRY_OPTIONS)),
1204
+ require_decorate.__decorateMetadata("design:paramtypes", [Object])
1205
+ ], TelemetryModule);
1206
+
1207
+ exports.Telemetry = Telemetry;
1208
+ Object.defineProperty(exports, "TelemetryContext", {
1209
+ enumerable: true,
1210
+ get: function () {
1211
+ return TelemetryContext;
1212
+ }
1213
+ });
1214
+ exports.TelemetryError = require_dispatcher.TelemetryError;
1215
+ Object.defineProperty(exports, "TelemetryHealthIndicator", {
1216
+ enumerable: true,
1217
+ get: function () {
1218
+ return TelemetryHealthIndicator;
1219
+ }
1220
+ });
1221
+ Object.defineProperty(exports, "TelemetryModule", {
1222
+ enumerable: true,
1223
+ get: function () {
1224
+ return TelemetryModule;
1225
+ }
1226
+ });
1227
+ Object.defineProperty(exports, "TelemetryNestLogger", {
1228
+ enumerable: true,
1229
+ get: function () {
1230
+ return TelemetryNestLogger;
1231
+ }
1232
+ });
1233
+ exports.Trace = Trace;
1234
+ exports.createTelemetry = createTelemetry;
1235
+ exports.createTelemetryFastifyOptions = createTelemetryFastifyOptions;
1236
+ exports.createTelemetryMock = require_telemetry_mock.createTelemetryMock;
1237
+ //# sourceMappingURL=index.cjs.map