franchising 0.0.0-stage → 0.2.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.
- package/LICENSE +61 -0
- package/README.md +96 -2
- package/dist/accounts-B4bnTXUd.js +242 -0
- package/dist/accounts-B4bnTXUd.js.map +1 -0
- package/dist/accounts-TyMPSHM0.cjs +313 -0
- package/dist/accounts-TyMPSHM0.cjs.map +1 -0
- package/dist/adapters-DM59AJfR.d.cts +216 -0
- package/dist/adapters-DM59AJfR.d.ts +216 -0
- package/dist/cli/template-assets/api/src/errors/codes.ts +17 -0
- package/dist/cli/template-assets/api/src/errors/index.ts +16 -0
- package/dist/cli/template-assets/api/src/filters/exception.ts +53 -0
- package/dist/cli/template-assets/api/src/main.ts +189 -0
- package/dist/cli/template-assets/api/src/modules/health/controller.ts +23 -0
- package/dist/cli/template-assets/api/src/modules/health/dto/response.dto.ts +23 -0
- package/dist/cli/template-assets/api/src/modules/health/module.ts +12 -0
- package/dist/cli/template-assets/api/src/modules/health/service.ts +54 -0
- package/dist/cli/template-assets/api/src/modules/messaging/module.ts +7 -0
- package/dist/cli/template-assets/api/src/modules/messaging/service.ts +74 -0
- package/dist/cli/template-assets/api/src/shared/exceptions.ts +40 -0
- package/dist/cli/template-assets/api/src/shared/response.ts +31 -0
- package/dist/cli/template-assets/api/src/telemetry.ts +59 -0
- package/dist/cli/template-assets/api/src/types.ts +8 -0
- package/dist/cli/template-assets/cloudflare/cache.service.ts +23 -0
- package/dist/cli/template-assets/cloudflare/queue.service.ts +22 -0
- package/dist/cli/template-assets/cloudflare/worker.ts +33 -0
- package/dist/cli/template-assets/packages/jobs/src/index.ts +49 -0
- package/dist/cli/template-assets/packages/queue-runtime/src/index.ts +54 -0
- package/dist/cli/template-assets/root/dot-dockerignore +11 -0
- package/dist/cli/template-assets/root/dot-editorconfig +13 -0
- package/dist/cli/template-assets/root/dot-oxfmtrc.json +9 -0
- package/dist/cli/template-assets/root/dot-oxlintrc.json +47 -0
- package/dist/cli/template-assets/root/lefthook.yml +18 -0
- package/dist/cli/template-assets/web/postcss.config.mjs +9 -0
- package/dist/cli/template-assets/web/src/app/(app)/dashboard/page.tsx +5 -0
- package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +25 -0
- package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +75 -0
- package/dist/cli/template-assets/web/src/app/globals.css +48 -0
- package/dist/cli/template-assets/web/src/app/layout.tsx +30 -0
- package/dist/cli/template-assets/web/src/app/page.tsx +20 -0
- package/dist/cli/template-assets/web/src/components/overview/overview-panel.tsx +27 -0
- package/dist/cli/template-assets/web/src/components/shell/app-shell.tsx +37 -0
- package/dist/cli/template-assets/web/src/components/shell/providers.tsx +22 -0
- package/dist/cli/template-assets/web/src/lib/api-client.ts +57 -0
- package/dist/cli/template-assets/web/src/lib/auth-client.ts +15 -0
- package/dist/cli/template-assets/web/src/lib/server-auth.ts +38 -0
- package/dist/cli/template-assets/web/src/types/api.ts +18 -0
- package/dist/cli/template-assets/worker/src/app.module.ts +5 -0
- package/dist/cli/template-assets/worker/src/env.ts +8 -0
- package/dist/cli/template-assets/worker/src/main.ts +25 -0
- package/dist/cli/template-assets/worker/src/modules/queue/config.ts +16 -0
- package/dist/cli/template-assets/worker/src/modules/queue/module.ts +11 -0
- package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +105 -0
- package/dist/cli/template-assets/worker/src/modules/queue/repository.ts +16 -0
- package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +17 -0
- package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +12 -0
- package/dist/cli/template-assets/worker-messaging/jobs-messaging.ts +12 -0
- package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +39 -0
- package/dist/cli/template-assets/worker-messaging/src/env.ts +14 -0
- package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +59 -0
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +8 -0
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +113 -0
- package/dist/cli.js +1218 -0
- package/dist/cn-BVOnrSza.js +1 -0
- package/dist/constants-C4iP0--i.js +38 -0
- package/dist/constants-C4iP0--i.js.map +1 -0
- package/dist/constants-rCR-LNSN.cjs +91 -0
- package/dist/constants-rCR-LNSN.cjs.map +1 -0
- package/dist/core-BidJDmSN.cjs +759 -0
- package/dist/core-BidJDmSN.cjs.map +1 -0
- package/dist/core-C-EFrEd6.js +710 -0
- package/dist/core-C-EFrEd6.js.map +1 -0
- package/dist/decorate-BR5FVX5x.js +14 -0
- package/dist/decorate-R-oqksAh.cjs +25 -0
- package/dist/decorateParam-BFJPEGKJ.cjs +13 -0
- package/dist/decorateParam-CKE7_J1s.js +8 -0
- package/dist/define-adapter-Cc0QrfKt.cjs +16 -0
- package/dist/define-adapter-Cc0QrfKt.cjs.map +1 -0
- package/dist/define-adapter-DRcXno3j.js +11 -0
- package/dist/define-adapter-DRcXno3j.js.map +1 -0
- package/dist/dispatcher-BsD7cO2w.cjs +84 -0
- package/dist/dispatcher-BsD7cO2w.cjs.map +1 -0
- package/dist/dispatcher-DA_l1Vkv.js +73 -0
- package/dist/dispatcher-DA_l1Vkv.js.map +1 -0
- package/dist/errors-DxHoXrLd.d.cts +46 -0
- package/dist/errors-DxHoXrLd.d.ts +46 -0
- package/dist/http/index.cjs +440 -0
- package/dist/http/index.cjs.map +1 -0
- package/dist/http/index.d.cts +257 -0
- package/dist/http/index.d.ts +257 -0
- package/dist/http/index.js +400 -0
- package/dist/http/index.js.map +1 -0
- package/dist/http/swagger.cjs +122 -0
- package/dist/http/swagger.cjs.map +1 -0
- package/dist/http/swagger.d.cts +59 -0
- package/dist/http/swagger.d.ts +59 -0
- package/dist/http/swagger.js +117 -0
- package/dist/http/swagger.js.map +1 -0
- package/dist/index--EJQTnHy.d.cts +174 -0
- package/dist/index-B3aVdDMV.d.cts +51 -0
- package/dist/index-BDYdEWl2.d.cts +833 -0
- package/dist/index-BDYdEWl2.d.ts +833 -0
- package/dist/index-Bdl0AiNM.d.ts +1262 -0
- package/dist/index-By8b4ksT.d.ts +25 -0
- package/dist/index-ByS2IC02.d.ts +51 -0
- package/dist/index-DDSaLjXV.d.cts +25 -0
- package/dist/index-FTrYdHfq.d.cts +1262 -0
- package/dist/index-u3ArUXO0.d.ts +174 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -0
- package/dist/label-BqmJoVE-.cjs +1 -0
- package/dist/label-XeChe1Bu.js +1 -0
- package/dist/messaging/index.cjs +1 -0
- package/dist/messaging/index.d.cts +1775 -0
- package/dist/messaging/index.d.ts +1775 -0
- package/dist/messaging/index.js +1 -0
- package/dist/misc-BpM_lMTx.js +1 -0
- package/dist/misc-DkqJOm1V.cjs +1 -0
- package/dist/operational-CnxdBwVG.d.cts +13 -0
- package/dist/operational-CnxdBwVG.d.ts +13 -0
- package/dist/redaction-DhuHTlHA.js +124 -0
- package/dist/redaction-DhuHTlHA.js.map +1 -0
- package/dist/redaction-uRIQbTwZ.cjs +171 -0
- package/dist/redaction-uRIQbTwZ.cjs.map +1 -0
- package/dist/rolldown-runtime-auK_WOaK.cjs +1 -0
- package/dist/rolldown-runtime-xuxB8TGW.cjs +32 -0
- package/dist/sdk-B2Lp3JCz.cjs +45 -0
- package/dist/sdk-B2Lp3JCz.cjs.map +1 -0
- package/dist/sdk-IGOHpAeG.js +22 -0
- package/dist/sdk-IGOHpAeG.js.map +1 -0
- package/dist/skills-C1uwr9Pp.js +4 -0
- package/dist/skills-DuE-XnBp.js +1 -0
- package/dist/sso/client.cjs +37 -0
- package/dist/sso/client.cjs.map +1 -0
- package/dist/sso/client.d.cts +89 -0
- package/dist/sso/client.d.ts +89 -0
- package/dist/sso/client.js +36 -0
- package/dist/sso/client.js.map +1 -0
- package/dist/sso/index.cjs +833 -0
- package/dist/sso/index.cjs.map +1 -0
- package/dist/sso/index.d.cts +2 -0
- package/dist/sso/index.d.ts +2 -0
- package/dist/sso/index.js +821 -0
- package/dist/sso/index.js.map +1 -0
- package/dist/sso/nestjs.cjs +169 -0
- package/dist/sso/nestjs.cjs.map +1 -0
- package/dist/sso/nestjs.d.cts +92 -0
- package/dist/sso/nestjs.d.ts +92 -0
- package/dist/sso/nestjs.js +151 -0
- package/dist/sso/nestjs.js.map +1 -0
- package/dist/sso/resource.cjs +124 -0
- package/dist/sso/resource.cjs.map +1 -0
- package/dist/sso/resource.d.cts +3 -0
- package/dist/sso/resource.d.ts +3 -0
- package/dist/sso/resource.js +114 -0
- package/dist/sso/resource.js.map +1 -0
- package/dist/status-CRvlFPIs.js +13 -0
- package/dist/status-CRvlFPIs.js.map +1 -0
- package/dist/status-DtK6OHtj.cjs +24 -0
- package/dist/status-DtK6OHtj.cjs.map +1 -0
- package/dist/telemetry/adapters.cjs +6 -0
- package/dist/telemetry/adapters.d.cts +3 -0
- package/dist/telemetry/adapters.d.ts +3 -0
- package/dist/telemetry/adapters.js +4 -0
- package/dist/telemetry/betterstack.cjs +74 -0
- package/dist/telemetry/betterstack.cjs.map +1 -0
- package/dist/telemetry/betterstack.d.cts +12 -0
- package/dist/telemetry/betterstack.d.ts +12 -0
- package/dist/telemetry/betterstack.js +71 -0
- package/dist/telemetry/betterstack.js.map +1 -0
- package/dist/telemetry/core.cjs +11 -0
- package/dist/telemetry/core.d.cts +4 -0
- package/dist/telemetry/core.d.ts +4 -0
- package/dist/telemetry/core.js +5 -0
- package/dist/telemetry/index.cjs +524 -0
- package/dist/telemetry/index.cjs.map +1 -0
- package/dist/telemetry/index.d.cts +68 -0
- package/dist/telemetry/index.d.ts +68 -0
- package/dist/telemetry/index.js +499 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/posthog.cjs +72 -0
- package/dist/telemetry/posthog.cjs.map +1 -0
- package/dist/telemetry/posthog.d.cts +10 -0
- package/dist/telemetry/posthog.d.ts +10 -0
- package/dist/telemetry/posthog.js +71 -0
- package/dist/telemetry/posthog.js.map +1 -0
- package/dist/telemetry/register.cjs +88 -0
- package/dist/telemetry/register.cjs.map +1 -0
- package/dist/telemetry/register.d.cts +14 -0
- package/dist/telemetry/register.d.ts +14 -0
- package/dist/telemetry/register.js +85 -0
- package/dist/telemetry/register.js.map +1 -0
- package/dist/telemetry/testing.cjs +54 -0
- package/dist/telemetry/testing.cjs.map +1 -0
- package/dist/telemetry/testing.d.cts +15 -0
- package/dist/telemetry/testing.d.ts +15 -0
- package/dist/telemetry/testing.js +52 -0
- package/dist/telemetry/testing.js.map +1 -0
- package/dist/telemetry.mock-BSsx7L6S.cjs +45 -0
- package/dist/telemetry.mock-BSsx7L6S.cjs.map +1 -0
- package/dist/telemetry.mock-BZRpy63c.js +40 -0
- package/dist/telemetry.mock-BZRpy63c.js.map +1 -0
- package/dist/telemetry.mock-C1wXuf-M.d.cts +4 -0
- package/dist/telemetry.mock-CdaxofJ7.d.ts +4 -0
- package/dist/ui/chart.cjs +6 -0
- package/dist/ui/chart.d.cts +34 -0
- package/dist/ui/chart.d.ts +34 -0
- package/dist/ui/chart.js +6 -0
- package/dist/ui/form.cjs +1 -0
- package/dist/ui/form.d.cts +23 -0
- package/dist/ui/form.d.ts +23 -0
- package/dist/ui/form.js +1 -0
- package/dist/ui/hooks.cjs +1 -0
- package/dist/ui/hooks.d.cts +66 -0
- package/dist/ui/hooks.d.ts +66 -0
- package/dist/ui/hooks.js +1 -0
- package/dist/ui/index.cjs +1 -0
- package/dist/ui/index.d.cts +3 -0
- package/dist/ui/index.d.ts +3 -0
- package/dist/ui/index.js +1 -0
- package/dist/ui/styles.css +2 -0
- package/dist/ui/utils.cjs +1 -0
- package/dist/ui/utils.d.cts +199 -0
- package/dist/ui/utils.d.ts +199 -0
- package/dist/ui/utils.js +1 -0
- package/dist/use-mobile-BbeIMRgE.cjs +1 -0
- package/dist/use-mobile-Cdd4Lp7p.js +1 -0
- package/dist/use-mobile-ecpyXWz3.d.cts +10 -0
- package/dist/use-mobile-ecpyXWz3.d.ts +10 -0
- package/dist/verifier-BIBtPCVi.cjs +119 -0
- package/dist/verifier-BIBtPCVi.cjs.map +1 -0
- package/dist/verifier-DNdy5Ynw.js +90 -0
- package/dist/verifier-DNdy5Ynw.js.map +1 -0
- package/dist/version-B0ADow60.js +1 -0
- package/dist/version-CMkha8JJ.cjs +1 -0
- package/package.json +539 -5
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
type TelemetryAttributes = Record<string, unknown>;
|
|
2
|
+
type MetricAttributes = Partial<{
|
|
3
|
+
service: string;
|
|
4
|
+
product: string;
|
|
5
|
+
route: string;
|
|
6
|
+
method: string;
|
|
7
|
+
status: string;
|
|
8
|
+
statusCode: string;
|
|
9
|
+
statusClass: string;
|
|
10
|
+
result: 'success' | 'error';
|
|
11
|
+
dependency: string;
|
|
12
|
+
operation: string;
|
|
13
|
+
queue: string;
|
|
14
|
+
job: string;
|
|
15
|
+
channel: string;
|
|
16
|
+
provider: string;
|
|
17
|
+
priority: string;
|
|
18
|
+
reason: string;
|
|
19
|
+
}>;
|
|
20
|
+
interface TelemetryRequestContext {
|
|
21
|
+
requestId?: string | undefined;
|
|
22
|
+
traceId?: string | undefined;
|
|
23
|
+
spanId?: string | undefined;
|
|
24
|
+
service: string;
|
|
25
|
+
/** Rockfeller product this process belongs to, e.g. 'messaging'. */
|
|
26
|
+
product?: string | undefined;
|
|
27
|
+
environment: string;
|
|
28
|
+
release?: string | undefined;
|
|
29
|
+
actorId?: string | undefined;
|
|
30
|
+
/** Tenant of the request. In Rockfeller products this is the organization. */
|
|
31
|
+
organizationId?: string | undefined;
|
|
32
|
+
jobId?: string | undefined;
|
|
33
|
+
/** Business correlation id, propagated across processes alongside the trace. */
|
|
34
|
+
correlationId?: string | undefined;
|
|
35
|
+
}
|
|
36
|
+
interface TelemetrySpan {
|
|
37
|
+
setAttributes(attributes: TelemetryAttributes): void;
|
|
38
|
+
addEvent(name: string, attributes?: TelemetryAttributes): void;
|
|
39
|
+
}
|
|
40
|
+
interface AuthTelemetryContext {
|
|
41
|
+
actorId?: string;
|
|
42
|
+
organizationId?: string;
|
|
43
|
+
}
|
|
44
|
+
interface TelemetryHttpErrorContext {
|
|
45
|
+
statusCode: number;
|
|
46
|
+
requestId?: string | undefined;
|
|
47
|
+
}
|
|
48
|
+
interface TelemetryHttpErrorResponse {
|
|
49
|
+
code: string;
|
|
50
|
+
message: string;
|
|
51
|
+
}
|
|
52
|
+
interface TelemetryOptions {
|
|
53
|
+
adapters?: TelemetryAdapter[];
|
|
54
|
+
/** Rockfeller product name, emitted on every signal. */
|
|
55
|
+
product?: string;
|
|
56
|
+
requestId?: {
|
|
57
|
+
header?: string;
|
|
58
|
+
};
|
|
59
|
+
logging?: {
|
|
60
|
+
redact?: string[];
|
|
61
|
+
level?: string;
|
|
62
|
+
excludePaths?: string[];
|
|
63
|
+
httpSuccessLogs?: boolean;
|
|
64
|
+
httpSlowRequestMs?: number;
|
|
65
|
+
};
|
|
66
|
+
metrics?: {
|
|
67
|
+
http?: boolean;
|
|
68
|
+
};
|
|
69
|
+
tracing?: boolean;
|
|
70
|
+
errors?: boolean;
|
|
71
|
+
context?: {
|
|
72
|
+
extract?: (request: unknown) => AuthTelemetryContext | undefined;
|
|
73
|
+
};
|
|
74
|
+
http?: {
|
|
75
|
+
/**
|
|
76
|
+
* Register the built-in catch-all exception filter. Set to `false` when
|
|
77
|
+
* the application already owns a global filter and its own error
|
|
78
|
+
* envelope: two catch-all filters in the same chain means the response
|
|
79
|
+
* shape depends on Nest's registration order, which is not a contract
|
|
80
|
+
* to build on. With `false`, report exceptions from your own filter via
|
|
81
|
+
* `Telemetry.captureException()`.
|
|
82
|
+
*
|
|
83
|
+
* @defaultValue true
|
|
84
|
+
*/
|
|
85
|
+
filter?: boolean;
|
|
86
|
+
mapException?: (exception: unknown, context: TelemetryHttpErrorContext) => TelemetryHttpErrorResponse | undefined;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
interface DependencyOptions {
|
|
90
|
+
name: string;
|
|
91
|
+
operation: string;
|
|
92
|
+
}
|
|
93
|
+
interface JobOptions {
|
|
94
|
+
queue: string;
|
|
95
|
+
job: string;
|
|
96
|
+
jobId?: string;
|
|
97
|
+
/** W3C traceparent captured by the producer, to continue the trace. */
|
|
98
|
+
traceparent?: string;
|
|
99
|
+
/** Business correlation id carried in the job payload. */
|
|
100
|
+
correlationId?: string;
|
|
101
|
+
}
|
|
102
|
+
interface CaptureExceptionOptions {
|
|
103
|
+
/**
|
|
104
|
+
* Stable grouping key. Prefer a domain error code over a stack trace:
|
|
105
|
+
* it survives refactors and groups by cause instead of by call site.
|
|
106
|
+
*/
|
|
107
|
+
fingerprint?: string;
|
|
108
|
+
}
|
|
109
|
+
interface TelemetryFetchOptions {
|
|
110
|
+
/** Dependency name for the span/metrics, e.g. 'resend'. Defaults to the hostname. */
|
|
111
|
+
dependency?: string;
|
|
112
|
+
/** Operation being performed, e.g. 'domains.create'. */
|
|
113
|
+
operation?: string;
|
|
114
|
+
/** Extra span attributes. Sanitized before emission. */
|
|
115
|
+
attributes?: TelemetryAttributes;
|
|
116
|
+
}
|
|
117
|
+
declare abstract class Telemetry {
|
|
118
|
+
abstract debug(event: string, attributes?: TelemetryAttributes): void;
|
|
119
|
+
abstract info(event: string, attributes?: TelemetryAttributes): void;
|
|
120
|
+
abstract warn(event: string, attributes?: TelemetryAttributes): void;
|
|
121
|
+
abstract error(event: string, error?: unknown, attributes?: TelemetryAttributes): void;
|
|
122
|
+
abstract event(event: string, attributes?: TelemetryAttributes): void;
|
|
123
|
+
abstract captureException(error: unknown, attributes?: TelemetryAttributes, options?: CaptureExceptionOptions): void;
|
|
124
|
+
abstract span<T>(name: string, fn: (span: TelemetrySpan) => Promise<T>, attributes?: TelemetryAttributes): Promise<T>;
|
|
125
|
+
abstract increment(name: string, value?: number, attributes?: MetricAttributes): void;
|
|
126
|
+
abstract histogram(name: string, value: number, attributes?: MetricAttributes): void;
|
|
127
|
+
abstract trackDependency<T>(options: DependencyOptions, fn: () => Promise<T>): Promise<T>;
|
|
128
|
+
abstract runJob<T>(options: JobOptions, fn: () => Promise<T>): Promise<T>;
|
|
129
|
+
/**
|
|
130
|
+
* Instrumented `fetch`. Required on Bun, where the global `fetch` is
|
|
131
|
+
* invisible to OpenTelemetry auto-instrumentation and therefore neither
|
|
132
|
+
* creates a span nor propagates `traceparent`.
|
|
133
|
+
*/
|
|
134
|
+
abstract fetch(input: string | URL | Request, init?: RequestInit, options?: TelemetryFetchOptions): Promise<Response>;
|
|
135
|
+
/** W3C traceparent for the active span, to hand to another process. */
|
|
136
|
+
abstract traceparent(): string | undefined;
|
|
137
|
+
abstract getContext(): TelemetryRequestContext;
|
|
138
|
+
abstract shutdown(): Promise<void>;
|
|
139
|
+
}
|
|
140
|
+
type TelemetryLogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
141
|
+
/**
|
|
142
|
+
* What an adapter supports. A facade call fails with `TelemetryError` when
|
|
143
|
+
* adapters are configured and none of them declares the capability it needs.
|
|
144
|
+
*/
|
|
145
|
+
interface TelemetryAdapterCapabilities {
|
|
146
|
+
logs: boolean;
|
|
147
|
+
/** Omit for backwards-compatible adapters that do not consume product events. */
|
|
148
|
+
events?: boolean;
|
|
149
|
+
metrics: boolean;
|
|
150
|
+
tracing: boolean;
|
|
151
|
+
errors: boolean;
|
|
152
|
+
}
|
|
153
|
+
interface TelemetryLogRecord {
|
|
154
|
+
level: TelemetryLogLevel;
|
|
155
|
+
event: string;
|
|
156
|
+
attributes: TelemetryAttributes;
|
|
157
|
+
context: TelemetryRequestContext;
|
|
158
|
+
}
|
|
159
|
+
/** A product event, intentionally distinct from an operational log. */
|
|
160
|
+
interface TelemetryEventRecord {
|
|
161
|
+
event: string;
|
|
162
|
+
attributes: TelemetryAttributes;
|
|
163
|
+
context: TelemetryRequestContext;
|
|
164
|
+
}
|
|
165
|
+
interface TelemetryMetricRecord {
|
|
166
|
+
type: 'counter' | 'histogram';
|
|
167
|
+
name: string;
|
|
168
|
+
value: number;
|
|
169
|
+
attributes: MetricAttributes;
|
|
170
|
+
context: TelemetryRequestContext;
|
|
171
|
+
}
|
|
172
|
+
interface TelemetrySpanEventRecord {
|
|
173
|
+
name: string;
|
|
174
|
+
attributes: TelemetryAttributes;
|
|
175
|
+
}
|
|
176
|
+
interface TelemetrySpanRecord {
|
|
177
|
+
name: string;
|
|
178
|
+
durationMs: number;
|
|
179
|
+
attributes: TelemetryAttributes;
|
|
180
|
+
events: TelemetrySpanEventRecord[];
|
|
181
|
+
context: TelemetryRequestContext;
|
|
182
|
+
error?: Error;
|
|
183
|
+
}
|
|
184
|
+
interface TelemetryExceptionRecord {
|
|
185
|
+
error: Error;
|
|
186
|
+
context: {
|
|
187
|
+
request: TelemetryRequestContext;
|
|
188
|
+
attributes: TelemetryAttributes;
|
|
189
|
+
};
|
|
190
|
+
/** Stable grouping key, preferred over provider stack-trace grouping. */
|
|
191
|
+
fingerprint?: string;
|
|
192
|
+
}
|
|
193
|
+
interface TelemetryOtlpConfiguration {
|
|
194
|
+
endpoint: string;
|
|
195
|
+
headers?: Record<string, string> | undefined;
|
|
196
|
+
signals: Pick<TelemetryAdapterCapabilities, 'logs' | 'metrics' | 'tracing'>;
|
|
197
|
+
}
|
|
198
|
+
interface TelemetryAdapter {
|
|
199
|
+
name: string;
|
|
200
|
+
capabilities: TelemetryAdapterCapabilities;
|
|
201
|
+
initialize?(): void | Promise<void>;
|
|
202
|
+
otlp?(): TelemetryOtlpConfiguration | undefined;
|
|
203
|
+
captureLog?(record: TelemetryLogRecord): void | Promise<void>;
|
|
204
|
+
captureEvent?(record: TelemetryEventRecord): void | Promise<void>;
|
|
205
|
+
captureMetric?(record: TelemetryMetricRecord): void | Promise<void>;
|
|
206
|
+
captureSpan?(record: TelemetrySpanRecord): void | Promise<void>;
|
|
207
|
+
captureException?(record: TelemetryExceptionRecord): void | Promise<void>;
|
|
208
|
+
shutdown?(): void | Promise<void>;
|
|
209
|
+
}
|
|
210
|
+
interface TelemetryAdapterDefinition<TOptions> {
|
|
211
|
+
name: string;
|
|
212
|
+
capabilities: TelemetryAdapterCapabilities;
|
|
213
|
+
create(options: TOptions): Omit<TelemetryAdapter, 'name' | 'capabilities'>;
|
|
214
|
+
}
|
|
215
|
+
export { TelemetryRequestContext as C, TelemetryOptions as S, Telemetry as _, TelemetryExceptionRecord as a, TelemetryHttpErrorContext as b, TelemetryMetricRecord as c, TelemetrySpanRecord as d, AuthTelemetryContext as f, MetricAttributes as g, JobOptions as h, TelemetryEventRecord as i, TelemetryOtlpConfiguration as l, DependencyOptions as m, TelemetryAdapterCapabilities as n, TelemetryLogLevel as o, CaptureExceptionOptions as p, TelemetryAdapterDefinition as r, TelemetryLogRecord as s, TelemetryAdapter as t, TelemetrySpanEventRecord as u, TelemetryAttributes as v, TelemetrySpan as w, TelemetryHttpErrorResponse as x, TelemetryFetchOptions as y };
|
|
216
|
+
//# sourceMappingURL=adapters-DM59AJfR.d.ts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codigos de erro da API.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* O cliente decide o que fazer pelo codigo, nunca pela mensagem: mensagem e
|
|
6
|
+
* texto de interface e muda sem aviso.
|
|
7
|
+
*/
|
|
8
|
+
export const ErrorCodes = {
|
|
9
|
+
BAD_REQUEST: 'BAD_REQUEST',
|
|
10
|
+
UNAUTHORIZED: 'UNAUTHORIZED',
|
|
11
|
+
FORBIDDEN: 'FORBIDDEN',
|
|
12
|
+
NOT_FOUND: 'NOT_FOUND',
|
|
13
|
+
CONFLICT: 'CONFLICT',
|
|
14
|
+
VALIDATION_FAILED: 'VALIDATION_FAILED',
|
|
15
|
+
UPSTREAM_FAILED: 'UPSTREAM_FAILED',
|
|
16
|
+
INTERNAL_ERROR: 'INTERNAL_ERROR',
|
|
17
|
+
} as const;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ErrorCodes } from './codes';
|
|
2
|
+
|
|
3
|
+
export { ErrorCodes };
|
|
4
|
+
|
|
5
|
+
export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
|
|
6
|
+
|
|
7
|
+
export const ErrorMessages: Record<ErrorCode, string> = {
|
|
8
|
+
[ErrorCodes.BAD_REQUEST]: 'Invalid request.',
|
|
9
|
+
[ErrorCodes.UNAUTHORIZED]: 'Authentication required.',
|
|
10
|
+
[ErrorCodes.FORBIDDEN]: 'Access denied.',
|
|
11
|
+
[ErrorCodes.NOT_FOUND]: 'Resource not found.',
|
|
12
|
+
[ErrorCodes.CONFLICT]: 'Conflict with the current state.',
|
|
13
|
+
[ErrorCodes.VALIDATION_FAILED]: 'Invalid data.',
|
|
14
|
+
[ErrorCodes.UPSTREAM_FAILED]: 'External service unavailable.',
|
|
15
|
+
[ErrorCodes.INTERNAL_ERROR]: 'Internal error.',
|
|
16
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ArgumentsHost,
|
|
3
|
+
Catch,
|
|
4
|
+
type ExceptionFilter,
|
|
5
|
+
HttpException,
|
|
6
|
+
HttpStatus,
|
|
7
|
+
Logger,
|
|
8
|
+
} from '@nestjs/common';
|
|
9
|
+
import { ErrorCodes } from '../errors';
|
|
10
|
+
import { error } from '../shared/response';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Traduz qualquer excecao para o envelope de erro da API.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* Sem o filtro, uma falha inesperada sai no formato padrao do Nest — outro
|
|
17
|
+
* contrato, e com a mensagem original do stack. Aqui ela vira
|
|
18
|
+
* `INTERNAL_ERROR`, e o detalhe fica so no log do servidor.
|
|
19
|
+
*/
|
|
20
|
+
@Catch()
|
|
21
|
+
export class ApiExceptionFilter implements ExceptionFilter {
|
|
22
|
+
private readonly logger = new Logger(ApiExceptionFilter.name);
|
|
23
|
+
|
|
24
|
+
catch(exception: unknown, host: ArgumentsHost) {
|
|
25
|
+
const response = host.switchToHttp().getResponse();
|
|
26
|
+
|
|
27
|
+
if (exception instanceof HttpException) {
|
|
28
|
+
const payload = exception.getResponse();
|
|
29
|
+
|
|
30
|
+
/*
|
|
31
|
+
* Os atalhos de `shared/exceptions` ja entregam o envelope pronto. O
|
|
32
|
+
* que chega fora dele vem do proprio Nest — o ValidationPipe, por
|
|
33
|
+
* exemplo — e precisa ser reembalado.
|
|
34
|
+
*/
|
|
35
|
+
const body =
|
|
36
|
+
typeof payload === 'object' &&
|
|
37
|
+
payload !== null &&
|
|
38
|
+
'ok' in payload
|
|
39
|
+
? payload
|
|
40
|
+
: error(ErrorCodes.VALIDATION_FAILED, payload);
|
|
41
|
+
|
|
42
|
+
return response.status(exception.getStatus()).send(body);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
this.logger.error(
|
|
46
|
+
exception instanceof Error ? exception.stack : String(exception),
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
return response
|
|
50
|
+
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
|
51
|
+
.send(error(ErrorCodes.INTERNAL_ERROR));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
// #if telemetry
|
|
3
|
+
/*
|
|
4
|
+
* Antes de qualquer `@nestjs/*`: o import e avaliado na ordem em que aparece,
|
|
5
|
+
* e a auto-instrumentacao precisa envolver o Nest, o banco e os clients HTTP
|
|
6
|
+
* antes de eles existirem.
|
|
7
|
+
*/
|
|
8
|
+
import './telemetry';
|
|
9
|
+
// #endif
|
|
10
|
+
import { Logger, ValidationPipe, VersioningType } from '@nestjs/common';
|
|
11
|
+
import { NestFactory } from '@nestjs/core';
|
|
12
|
+
import {
|
|
13
|
+
FastifyAdapter,
|
|
14
|
+
type NestFastifyApplication,
|
|
15
|
+
} from '@nestjs/platform-fastify';
|
|
16
|
+
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
|
17
|
+
// #if telemetry
|
|
18
|
+
import {
|
|
19
|
+
createTelemetryFastifyOptions,
|
|
20
|
+
TelemetryNestLogger,
|
|
21
|
+
} from 'franchising/telemetry';
|
|
22
|
+
// #endif
|
|
23
|
+
import scalarApiReference from '@scalar/fastify-api-reference';
|
|
24
|
+
// #if inlineAuth
|
|
25
|
+
import { fromNodeHeaders } from 'better-auth/node';
|
|
26
|
+
import { createAuth } from './auth';
|
|
27
|
+
import { DatabaseService } from './modules/database/database.service';
|
|
28
|
+
// #if messaging
|
|
29
|
+
import { MessagingService } from './modules/messaging/service';
|
|
30
|
+
// #endif
|
|
31
|
+
// #endif
|
|
32
|
+
import { AppModule } from './app.module';
|
|
33
|
+
import { env } from './env';
|
|
34
|
+
import { ApiExceptionFilter } from './filters/exception';
|
|
35
|
+
import { API_DOCS_PATH, API_VERSION, API_VERSION_PREFIX } from './types';
|
|
36
|
+
|
|
37
|
+
async function bootstrap() {
|
|
38
|
+
// #if telemetry
|
|
39
|
+
/*
|
|
40
|
+
* O Fastify cria o proprio logger antes de os modulos Nest carregarem.
|
|
41
|
+
* A fabrica garante que o log nativo tambem carregue `request_id`, que e o
|
|
42
|
+
* que permite ligar uma linha de acesso ao resto do rastro.
|
|
43
|
+
*/
|
|
44
|
+
const app = await NestFactory.create<NestFastifyApplication>(
|
|
45
|
+
AppModule,
|
|
46
|
+
/*
|
|
47
|
+
* O cast existe porque o tipo devolvido pela fabrica e mais largo que a
|
|
48
|
+
* assinatura do adapter do Nest; as opcoes sao as mesmas do Fastify.
|
|
49
|
+
*/
|
|
50
|
+
new FastifyAdapter(
|
|
51
|
+
createTelemetryFastifyOptions({
|
|
52
|
+
logging: { excludePaths: [`/${API_VERSION_PREFIX}/health`] },
|
|
53
|
+
}) as ConstructorParameters<typeof FastifyAdapter>[0],
|
|
54
|
+
),
|
|
55
|
+
{ bodyParser: false, bufferLogs: true },
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
app.useLogger(app.get(TelemetryNestLogger));
|
|
59
|
+
// #else
|
|
60
|
+
const app = await NestFactory.create<NestFastifyApplication>(
|
|
61
|
+
AppModule,
|
|
62
|
+
new FastifyAdapter(),
|
|
63
|
+
{ bodyParser: false },
|
|
64
|
+
);
|
|
65
|
+
// #endif
|
|
66
|
+
|
|
67
|
+
app.enableShutdownHooks();
|
|
68
|
+
|
|
69
|
+
/*
|
|
70
|
+
* Versao no caminho, sem prefixo global: a rota nasce em `/v1/...`. Assim
|
|
71
|
+
* uma mudanca incompativel sobe `/v2` e convive com quem ainda chama `/v1`,
|
|
72
|
+
* em vez de quebrar todo cliente de uma vez.
|
|
73
|
+
*/
|
|
74
|
+
app.enableVersioning({
|
|
75
|
+
type: VersioningType.URI,
|
|
76
|
+
defaultVersion: API_VERSION,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
app.enableCors({ origin: env.CLIENT_ORIGIN, credentials: true });
|
|
80
|
+
app.useGlobalPipes(
|
|
81
|
+
new ValidationPipe({
|
|
82
|
+
whitelist: true,
|
|
83
|
+
forbidNonWhitelisted: true,
|
|
84
|
+
transform: true,
|
|
85
|
+
}),
|
|
86
|
+
);
|
|
87
|
+
app.useGlobalFilters(new ApiExceptionFilter());
|
|
88
|
+
|
|
89
|
+
// #if inlineAuth
|
|
90
|
+
/*
|
|
91
|
+
* O Better Auth trata as proprias rotas antes do Nest: ele fala HTTP puro,
|
|
92
|
+
* e passar pelo pipeline do Nest quebraria o corpo cru que a assinatura
|
|
93
|
+
* dos provedores precisa.
|
|
94
|
+
*/
|
|
95
|
+
const auth = createAuth({
|
|
96
|
+
databaseService: app.get(DatabaseService),
|
|
97
|
+
// #if messaging
|
|
98
|
+
messagingService: app.get(MessagingService),
|
|
99
|
+
// #endif
|
|
100
|
+
});
|
|
101
|
+
const httpAdapter = app.getHttpAdapter().getInstance();
|
|
102
|
+
|
|
103
|
+
httpAdapter.all(`/${API_VERSION_PREFIX}/auth/*`, async (request, reply) => {
|
|
104
|
+
const url = new URL(request.url, env.BETTER_AUTH_URL);
|
|
105
|
+
const response = await auth.handler(
|
|
106
|
+
new Request(url, {
|
|
107
|
+
method: request.method,
|
|
108
|
+
headers: fromNodeHeaders(request.headers),
|
|
109
|
+
...(['GET', 'HEAD'].includes(request.method)
|
|
110
|
+
? {}
|
|
111
|
+
: { body: JSON.stringify(request.body) }),
|
|
112
|
+
}),
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
reply.status(response.status);
|
|
116
|
+
response.headers.forEach((value, key) => reply.header(key, value));
|
|
117
|
+
|
|
118
|
+
return reply.send(await response.text());
|
|
119
|
+
});
|
|
120
|
+
// #endif
|
|
121
|
+
|
|
122
|
+
if (env.API_DOCS_ENABLED) {
|
|
123
|
+
const document = SwaggerModule.createDocument(
|
|
124
|
+
app,
|
|
125
|
+
new DocumentBuilder()
|
|
126
|
+
.setTitle('__ROCK_PROJECT_NAME__')
|
|
127
|
+
.setDescription(
|
|
128
|
+
'Sucesso responde `{ ok: true, data }`; erro responde `{ ok: false, code, message, errors? }`.',
|
|
129
|
+
)
|
|
130
|
+
.setVersion('1.0.0')
|
|
131
|
+
.addBearerAuth(
|
|
132
|
+
{
|
|
133
|
+
type: 'http',
|
|
134
|
+
scheme: 'bearer',
|
|
135
|
+
bearerFormat: 'API key',
|
|
136
|
+
description: 'Chave de API do projeto.',
|
|
137
|
+
},
|
|
138
|
+
'apiKey',
|
|
139
|
+
)
|
|
140
|
+
/*
|
|
141
|
+
* Preenche o cartao "Base URL" e e o host dos exemplos de
|
|
142
|
+
* cURL: sem ele o Scalar cai em caminho relativo e o trecho
|
|
143
|
+
* copiado nao roda.
|
|
144
|
+
*/
|
|
145
|
+
.addServer(env.API_URL, 'Servidor atual')
|
|
146
|
+
.build(),
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
/*
|
|
150
|
+
* O Scalar substitui a UI do Swagger: mesma spec vinda dos decorators,
|
|
151
|
+
* com busca, exemplos de cliente e tema escuro.
|
|
152
|
+
*/
|
|
153
|
+
await app.register(scalarApiReference as never, {
|
|
154
|
+
routePrefix: `/${API_DOCS_PATH}`,
|
|
155
|
+
// O plugin loga uma linha por asset servido; nada disso interessa.
|
|
156
|
+
logLevel: 'silent',
|
|
157
|
+
configuration: {
|
|
158
|
+
content: document,
|
|
159
|
+
pageTitle: '__ROCK_PROJECT_NAME__',
|
|
160
|
+
theme: 'elysiajs',
|
|
161
|
+
layout: 'modern',
|
|
162
|
+
darkMode: true,
|
|
163
|
+
/*
|
|
164
|
+
* Tira a barra de Deploy/Share, o painel de dev tools e o botao
|
|
165
|
+
* de servidor MCP: sao ganchos para produtos da Scalar, nao
|
|
166
|
+
* para a nossa documentacao.
|
|
167
|
+
*/
|
|
168
|
+
showDeveloperTools: 'never',
|
|
169
|
+
mcp: { disabled: true },
|
|
170
|
+
defaultOpenFirstTag: true,
|
|
171
|
+
defaultHttpClient: { targetKey: 'shell', clientKey: 'curl' },
|
|
172
|
+
documentDownloadType: 'json',
|
|
173
|
+
searchHotKey: 'k',
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
await app.listen(env.PORT, '0.0.0.0');
|
|
179
|
+
|
|
180
|
+
const logger = new Logger('Bootstrap');
|
|
181
|
+
|
|
182
|
+
logger.log(`API em http://localhost:${env.PORT}/${API_VERSION_PREFIX}`);
|
|
183
|
+
|
|
184
|
+
if (env.API_DOCS_ENABLED) {
|
|
185
|
+
logger.log(`Docs em http://localhost:${env.PORT}/${API_DOCS_PATH}`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
void bootstrap();
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Controller, Get } from '@nestjs/common';
|
|
2
|
+
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
|
3
|
+
// #if authModule
|
|
4
|
+
import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
|
|
5
|
+
// #endif
|
|
6
|
+
import { ok } from '../../shared/response';
|
|
7
|
+
import { HealthService } from './service';
|
|
8
|
+
|
|
9
|
+
@ApiTags('Saude')
|
|
10
|
+
@Controller('health')
|
|
11
|
+
export class HealthController {
|
|
12
|
+
constructor(private readonly service: HealthService) {}
|
|
13
|
+
|
|
14
|
+
@Get()
|
|
15
|
+
// #if authModule
|
|
16
|
+
@AllowAnonymous()
|
|
17
|
+
// #endif
|
|
18
|
+
@ApiOperation({ summary: 'Verifica a disponibilidade da API' })
|
|
19
|
+
@ApiOkResponse({ description: 'Estado da API e das dependencias.' })
|
|
20
|
+
async check() {
|
|
21
|
+
return ok(await this.service.check());
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ApiProperty } from '@nestjs/swagger';
|
|
2
|
+
|
|
3
|
+
export class HealthResponseDto {
|
|
4
|
+
@ApiProperty({ example: 'ok', enum: ['ok', 'degraded'] })
|
|
5
|
+
status!: string;
|
|
6
|
+
|
|
7
|
+
@ApiProperty({ example: '__ROCK_PROJECT_SLUG__' })
|
|
8
|
+
service!: string;
|
|
9
|
+
|
|
10
|
+
@ApiProperty({ example: 120, description: 'Segundos desde o boot.' })
|
|
11
|
+
uptime!: number;
|
|
12
|
+
|
|
13
|
+
@ApiProperty({ example: true })
|
|
14
|
+
database!: boolean;
|
|
15
|
+
|
|
16
|
+
@ApiProperty({ example: true })
|
|
17
|
+
cache!: boolean;
|
|
18
|
+
// #if telemetry
|
|
19
|
+
|
|
20
|
+
@ApiProperty({ description: 'Estado dos exportadores de telemetria.' })
|
|
21
|
+
telemetry!: unknown;
|
|
22
|
+
// #endif
|
|
23
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { CacheModule } from '../cache/cache.module';
|
|
3
|
+
import { DatabaseModule } from '../database/database.module';
|
|
4
|
+
import { HealthController } from './controller';
|
|
5
|
+
import { HealthService } from './service';
|
|
6
|
+
|
|
7
|
+
@Module({
|
|
8
|
+
imports: [CacheModule, DatabaseModule],
|
|
9
|
+
controllers: [HealthController],
|
|
10
|
+
providers: [HealthService],
|
|
11
|
+
})
|
|
12
|
+
export class HealthModule {}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
// #if telemetry
|
|
3
|
+
import { TelemetryHealthIndicator } from 'franchising/telemetry';
|
|
4
|
+
// #endif
|
|
5
|
+
import { CacheService } from '../cache/cache.service';
|
|
6
|
+
import { DatabaseService } from '../database/database.service';
|
|
7
|
+
import type { HealthResponseDto } from './dto/response.dto';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Sonda de disponibilidade.
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* Toca banco e cache de proposito: um healthcheck que so responde "ok" prova
|
|
14
|
+
* apenas que o processo subiu, e segue verde com o banco fora do ar — que e
|
|
15
|
+
* justamente quando o orquestrador precisaria reiniciar a instancia.
|
|
16
|
+
*/
|
|
17
|
+
@Injectable()
|
|
18
|
+
export class HealthService {
|
|
19
|
+
constructor(
|
|
20
|
+
private readonly database: DatabaseService,
|
|
21
|
+
private readonly cacheService: CacheService,
|
|
22
|
+
// #if telemetry
|
|
23
|
+
private readonly telemetryHealth: TelemetryHealthIndicator,
|
|
24
|
+
// #endif
|
|
25
|
+
) {}
|
|
26
|
+
|
|
27
|
+
async check(): Promise<HealthResponseDto> {
|
|
28
|
+
const [database, cache] = await Promise.all([
|
|
29
|
+
this.probe(() => this.database.ping()),
|
|
30
|
+
this.probe(() => this.cacheService.ping()),
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
status: database && cache ? 'ok' : 'degraded',
|
|
35
|
+
service: '__ROCK_PROJECT_SLUG__',
|
|
36
|
+
uptime: Math.round(process.uptime()),
|
|
37
|
+
database,
|
|
38
|
+
cache,
|
|
39
|
+
// #if telemetry
|
|
40
|
+
telemetry: this.telemetryHealth.status(),
|
|
41
|
+
// #endif
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private async probe(run: () => Promise<unknown>): Promise<boolean> {
|
|
46
|
+
try {
|
|
47
|
+
await run();
|
|
48
|
+
|
|
49
|
+
return true;
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Global, Module } from '@nestjs/common';
|
|
2
|
+
import { MessagingService } from './service';
|
|
3
|
+
|
|
4
|
+
/* Global porque o Better Auth precisa dele na fabrica da instancia. */
|
|
5
|
+
@Global()
|
|
6
|
+
@Module({ providers: [MessagingService], exports: [MessagingService] })
|
|
7
|
+
export class MessagingModule {}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// #if telemetry
|
|
2
|
+
import { Injectable } from '@nestjs/common';
|
|
3
|
+
import { Telemetry } from 'franchising/telemetry';
|
|
4
|
+
// #else
|
|
5
|
+
import { Injectable, Logger } from '@nestjs/common';
|
|
6
|
+
// #endif
|
|
7
|
+
import { Messaging } from 'franchising/messaging';
|
|
8
|
+
import { env } from '../../env';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Envio de e-mail pela plataforma Messaging.
|
|
12
|
+
*
|
|
13
|
+
* @remarks
|
|
14
|
+
* Todo e-mail transacional sai por aqui, e nao por um provedor configurado
|
|
15
|
+
* direto na app: remetente, dominio e politica de retentativa ficam num lugar
|
|
16
|
+
* so, e trocar de provedor nao encosta neste projeto.
|
|
17
|
+
*
|
|
18
|
+
* O SDK nao lanca por erro de API — devolve `{ data, error }`. Uma falha vira
|
|
19
|
+
* log e nao derruba o fluxo que a disparou: quem pediu a redefinicao de senha
|
|
20
|
+
* nao deve tomar 500 porque o e-mail nao saiu.
|
|
21
|
+
*/
|
|
22
|
+
@Injectable()
|
|
23
|
+
export class MessagingService {
|
|
24
|
+
// #if telemetry
|
|
25
|
+
constructor(private readonly telemetry: Telemetry) {}
|
|
26
|
+
// #else
|
|
27
|
+
private readonly logger = new Logger(MessagingService.name);
|
|
28
|
+
// #endif
|
|
29
|
+
|
|
30
|
+
private readonly client = new Messaging({ secret: env.MESSAGING_API_KEY });
|
|
31
|
+
|
|
32
|
+
async sendEmail(input: {
|
|
33
|
+
to: string;
|
|
34
|
+
subject: string;
|
|
35
|
+
html: string;
|
|
36
|
+
}): Promise<boolean> {
|
|
37
|
+
const { error } = await this.client.emails.send({
|
|
38
|
+
to: input.to,
|
|
39
|
+
from: env.MESSAGING_FROM,
|
|
40
|
+
subject: input.subject,
|
|
41
|
+
html: input.html,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
if (error) {
|
|
45
|
+
// #if telemetry
|
|
46
|
+
/*
|
|
47
|
+
* Atributos separados, e nao interpolados na mensagem: e o que
|
|
48
|
+
* permite filtrar por `code` depois. Nada de destinatario aqui —
|
|
49
|
+
* e-mail e dado pessoal e nao entra em log.
|
|
50
|
+
*/
|
|
51
|
+
this.telemetry.error('email.send_failed', error, {
|
|
52
|
+
code: error.code,
|
|
53
|
+
subject: input.subject,
|
|
54
|
+
});
|
|
55
|
+
// #else
|
|
56
|
+
this.logger.error(
|
|
57
|
+
JSON.stringify({
|
|
58
|
+
event: 'email.send_failed',
|
|
59
|
+
code: error.code,
|
|
60
|
+
reason: error.message,
|
|
61
|
+
}),
|
|
62
|
+
);
|
|
63
|
+
// #endif
|
|
64
|
+
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// #if telemetry
|
|
69
|
+
this.telemetry.info('email.sent', { subject: input.subject });
|
|
70
|
+
// #endif
|
|
71
|
+
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
}
|