tempest-express-sdk 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { VERSION } from './chunk-2NB7ZA7G.js';
1
+ export { VERSION } from './chunk-6ZKN2ELQ.js';
2
2
  import { AsyncLocalStorage } from 'async_hooks';
3
3
  import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV31, OpenApiGeneratorV3 } from '@asteasolutions/zod-to-openapi';
4
4
  export { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
@@ -6,7 +6,10 @@ import { z, ZodError } from 'zod';
6
6
  export { z } from 'zod';
7
7
  import { Model, column, sql } from 'tempest-db-js';
8
8
  export { AsyncEngine, AsyncResult, AsyncSession, BaseRepository, Column, DeleteBuilder, InsertBuilder, Model, NoResultError, NodeSqliteDriver, PostgresDialect, RecordNotFound, SelectBuilder, SqliteDialect, SyncEngine, SyncSession, UpdateBuilder, and, belongsTo, column, columnsOf, createEngine, createSyncEngine, del, detectDialect, getDialect, hasMany, insert, join, loadRelations, not, or, parseDatabaseUrl, select, sql, update } from 'tempest-db-js';
9
- import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'crypto';
9
+ import { createHash, randomBytes, timingSafeEqual, randomUUID, createHmac } from 'crypto';
10
+ import { cpus, loadavg, totalmem, freemem } from 'os';
11
+ import { mkdir, writeFile, readFile, rm } from 'fs/promises';
12
+ import { join, dirname } from 'path';
10
13
  import express2, { Router } from 'express';
11
14
  import { getAbsoluteFSPath } from 'swagger-ui-dist';
12
15
 
@@ -6750,6 +6753,1279 @@ var AttemptThrottle = class {
6750
6753
  }
6751
6754
  };
6752
6755
 
6756
+ // src/utils/clientIp.ts
6757
+ var UNKNOWN = "unknown";
6758
+ function getClientIp(req, options = {}) {
6759
+ if (options.trustedHeader) {
6760
+ const value = req.header(options.trustedHeader);
6761
+ if (value) return value.trim();
6762
+ }
6763
+ return req.socket?.remoteAddress ?? req.ip ?? UNKNOWN;
6764
+ }
6765
+ var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
6766
+ function base32Encode(bytes) {
6767
+ let bits = 0;
6768
+ let value = 0;
6769
+ let out = "";
6770
+ for (const byte of bytes) {
6771
+ value = value << 8 | byte;
6772
+ bits += 8;
6773
+ while (bits >= 5) {
6774
+ out += BASE32_ALPHABET[value >>> bits - 5 & 31];
6775
+ bits -= 5;
6776
+ }
6777
+ }
6778
+ if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
6779
+ return out;
6780
+ }
6781
+ function base32Decode(secret) {
6782
+ const clean = secret.toUpperCase().replace(/=+$/, "").replace(/\s/g, "");
6783
+ let bits = 0;
6784
+ let value = 0;
6785
+ const out = [];
6786
+ for (const char of clean) {
6787
+ const index = BASE32_ALPHABET.indexOf(char);
6788
+ if (index === -1) continue;
6789
+ value = value << 5 | index;
6790
+ bits += 5;
6791
+ if (bits >= 8) {
6792
+ out.push(value >>> bits - 8 & 255);
6793
+ bits -= 8;
6794
+ }
6795
+ }
6796
+ return Buffer.from(out);
6797
+ }
6798
+ function hotp(secret, counter, digits) {
6799
+ const buffer = Buffer.alloc(8);
6800
+ buffer.writeUInt32BE(Math.floor(counter / 2 ** 32), 0);
6801
+ buffer.writeUInt32BE(counter >>> 0, 4);
6802
+ const digest = createHmac("sha1", secret).update(buffer).digest();
6803
+ const offset = digest[digest.length - 1] & 15;
6804
+ const binary = (digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255;
6805
+ return (binary % 10 ** digits).toString().padStart(digits, "0");
6806
+ }
6807
+ var TOTPHelper = class {
6808
+ issuer;
6809
+ step;
6810
+ digits;
6811
+ /**
6812
+ * @param options - Issuer label, time step and digit count.
6813
+ */
6814
+ constructor(options) {
6815
+ this.issuer = options.issuer;
6816
+ this.step = options.step ?? 30;
6817
+ this.digits = options.digits ?? 6;
6818
+ }
6819
+ /**
6820
+ * Generate a fresh base32 secret (80 bits).
6821
+ *
6822
+ * @returns A base32-encoded TOTP secret to persist on the user row.
6823
+ */
6824
+ generateSecret() {
6825
+ return base32Encode(randomBytes(10));
6826
+ }
6827
+ /**
6828
+ * Build the `otpauth://` provisioning URI (render as a QR code).
6829
+ *
6830
+ * @param secret - The base32 secret.
6831
+ * @param accountName - Identifier shown next to the issuer (e.g. the email).
6832
+ * @returns The `otpauth://totp/...` URI.
6833
+ */
6834
+ provisioningUri(secret, accountName) {
6835
+ const label = encodeURIComponent(`${this.issuer}:${accountName}`);
6836
+ const params = new URLSearchParams({
6837
+ secret,
6838
+ issuer: this.issuer,
6839
+ algorithm: "SHA1",
6840
+ digits: String(this.digits),
6841
+ period: String(this.step)
6842
+ });
6843
+ return `otpauth://totp/${label}?${params.toString()}`;
6844
+ }
6845
+ /**
6846
+ * Verify a code against the secret for the current time window.
6847
+ *
6848
+ * @param secret - The base32 secret.
6849
+ * @param code - The submitted code.
6850
+ * @param window - Tolerance in steps (±). Default 1 (previous/current/next).
6851
+ * @returns `true` when the code matches within the window.
6852
+ */
6853
+ verify(secret, code, window = 1) {
6854
+ const cleaned = code.trim().replace(/[\s-]/g, "");
6855
+ if (!/^\d+$/.test(cleaned) || cleaned.length !== this.digits) return false;
6856
+ const key = base32Decode(secret);
6857
+ const counter = Math.floor(Date.now() / 1e3 / this.step);
6858
+ for (let offset = -window; offset <= window; offset++) {
6859
+ if (hotp(key, counter + offset, this.digits) === cleaned) return true;
6860
+ }
6861
+ return false;
6862
+ }
6863
+ };
6864
+
6865
+ // src/utils/httpClient.ts
6866
+ var CircuitOpenError = class extends Error {
6867
+ constructor(host) {
6868
+ super(`Circuit breaker is open for host ${host}`);
6869
+ this.host = host;
6870
+ this.name = "CircuitOpenError";
6871
+ }
6872
+ host;
6873
+ };
6874
+ var RetryPolicy = class {
6875
+ /**
6876
+ * @param maxRetries - Additional attempts after the first. Default 2.
6877
+ * @param baseDelayMs - Base backoff in ms (doubles each attempt). Default 100.
6878
+ * @param retryOn - HTTP status codes that trigger a retry. Default 5xx + 429.
6879
+ */
6880
+ constructor(maxRetries = 2, baseDelayMs = 100, retryOn = [429, 500, 502, 503, 504]) {
6881
+ this.maxRetries = maxRetries;
6882
+ this.baseDelayMs = baseDelayMs;
6883
+ this.retryOn = retryOn;
6884
+ }
6885
+ maxRetries;
6886
+ baseDelayMs;
6887
+ retryOn;
6888
+ /** Backoff delay in ms before `attempt` (0-indexed). */
6889
+ sleepFor(attempt) {
6890
+ return this.baseDelayMs * 2 ** attempt;
6891
+ }
6892
+ };
6893
+ var HTTPClient = class {
6894
+ baseUrl;
6895
+ defaultHeaders;
6896
+ timeoutMs;
6897
+ retryPolicy;
6898
+ breakerThreshold;
6899
+ breakerCooldownMs;
6900
+ breakers = /* @__PURE__ */ new Map();
6901
+ /**
6902
+ * @param options - Base URL, headers, timeout, retry and breaker settings.
6903
+ */
6904
+ constructor(options = {}) {
6905
+ this.baseUrl = options.baseUrl ?? "";
6906
+ this.defaultHeaders = options.defaultHeaders ?? {};
6907
+ this.timeoutMs = options.timeoutMs ?? 3e4;
6908
+ this.retryPolicy = options.retryPolicy ?? new RetryPolicy();
6909
+ this.breakerThreshold = options.breakerThreshold ?? 5;
6910
+ this.breakerCooldownMs = options.breakerCooldownMs ?? 3e4;
6911
+ }
6912
+ resolve(url) {
6913
+ return this.baseUrl && !/^https?:\/\//.test(url) ? `${this.baseUrl}${url}` : url;
6914
+ }
6915
+ hostOf(url) {
6916
+ try {
6917
+ return new URL(url).host;
6918
+ } catch {
6919
+ return url;
6920
+ }
6921
+ }
6922
+ breakerCheck(host) {
6923
+ const state = this.breakers.get(host);
6924
+ if (state && state.openUntil > Date.now()) throw new CircuitOpenError(host);
6925
+ }
6926
+ breakerRecord(host, failed) {
6927
+ const state = this.breakers.get(host) ?? { failures: 0, openUntil: 0 };
6928
+ if (failed) {
6929
+ state.failures += 1;
6930
+ if (state.failures >= this.breakerThreshold) {
6931
+ state.openUntil = Date.now() + this.breakerCooldownMs;
6932
+ state.failures = 0;
6933
+ }
6934
+ } else {
6935
+ state.failures = 0;
6936
+ state.openUntil = 0;
6937
+ }
6938
+ this.breakers.set(host, state);
6939
+ }
6940
+ /**
6941
+ * Perform a request with retries and breaker protection.
6942
+ *
6943
+ * @param method - HTTP method.
6944
+ * @param url - Absolute URL or a path resolved against `baseUrl`.
6945
+ * @param init - Extra `fetch` init (headers, body, …).
6946
+ * @returns The `Response`.
6947
+ * @throws {CircuitOpenError} When the per-host breaker is open.
6948
+ */
6949
+ async request(method, url, init = {}) {
6950
+ const target = this.resolve(url);
6951
+ const host = this.hostOf(target);
6952
+ this.breakerCheck(host);
6953
+ let lastError;
6954
+ for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) {
6955
+ const controller = new AbortController();
6956
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
6957
+ try {
6958
+ const response = await fetch(target, {
6959
+ ...init,
6960
+ method,
6961
+ headers: { ...this.defaultHeaders, ...init.headers ?? {} },
6962
+ signal: controller.signal
6963
+ });
6964
+ clearTimeout(timer);
6965
+ if (this.retryPolicy.retryOn.includes(response.status)) {
6966
+ this.breakerRecord(host, true);
6967
+ if (attempt < this.retryPolicy.maxRetries) {
6968
+ await this.sleep(this.retryPolicy.sleepFor(attempt));
6969
+ continue;
6970
+ }
6971
+ return response;
6972
+ }
6973
+ this.breakerRecord(host, false);
6974
+ return response;
6975
+ } catch (error) {
6976
+ clearTimeout(timer);
6977
+ lastError = error;
6978
+ this.breakerRecord(host, true);
6979
+ if (attempt < this.retryPolicy.maxRetries) {
6980
+ await this.sleep(this.retryPolicy.sleepFor(attempt));
6981
+ continue;
6982
+ }
6983
+ }
6984
+ }
6985
+ throw lastError instanceof Error ? lastError : new Error("Request failed");
6986
+ }
6987
+ sleep(ms) {
6988
+ return new Promise((resolve) => setTimeout(resolve, ms));
6989
+ }
6990
+ /** GET request. */
6991
+ get(url, init) {
6992
+ return this.request("GET", url, init);
6993
+ }
6994
+ /** POST request. */
6995
+ post(url, init) {
6996
+ return this.request("POST", url, init);
6997
+ }
6998
+ /** PUT request. */
6999
+ put(url, init) {
7000
+ return this.request("PUT", url, init);
7001
+ }
7002
+ /** PATCH request. */
7003
+ patch(url, init) {
7004
+ return this.request("PATCH", url, init);
7005
+ }
7006
+ /** DELETE request. */
7007
+ delete(url, init) {
7008
+ return this.request("DELETE", url, init);
7009
+ }
7010
+ };
7011
+ function readCpu() {
7012
+ const cores = cpus().length;
7013
+ const load1 = loadavg()[0] ?? 0;
7014
+ return {
7015
+ cores,
7016
+ load1,
7017
+ loadPercent: cores > 0 ? load1 / cores * 100 : 0
7018
+ };
7019
+ }
7020
+ function readMemory() {
7021
+ const total = totalmem();
7022
+ const free = freemem();
7023
+ const used = total - free;
7024
+ return {
7025
+ total,
7026
+ free,
7027
+ used,
7028
+ usedPercent: total > 0 ? used / total * 100 : 0,
7029
+ processRss: process.memoryUsage().rss
7030
+ };
7031
+ }
7032
+ function readSystem() {
7033
+ return {
7034
+ cpu: readCpu(),
7035
+ memory: readMemory(),
7036
+ uptimeSeconds: process.uptime()
7037
+ };
7038
+ }
7039
+ function toPrometheus(snapshot = readSystem()) {
7040
+ const lines = [
7041
+ "# HELP process_cpu_load_percent 1-minute load average as percent of cores",
7042
+ "# TYPE process_cpu_load_percent gauge",
7043
+ `process_cpu_load_percent ${snapshot.cpu.loadPercent}`,
7044
+ "# HELP process_memory_used_percent System memory used percent",
7045
+ "# TYPE process_memory_used_percent gauge",
7046
+ `process_memory_used_percent ${snapshot.memory.usedPercent}`,
7047
+ "# HELP process_memory_rss_bytes Resident set size of the process",
7048
+ "# TYPE process_memory_rss_bytes gauge",
7049
+ `process_memory_rss_bytes ${snapshot.memory.processRss}`,
7050
+ "# HELP process_uptime_seconds Process uptime in seconds",
7051
+ "# TYPE process_uptime_seconds counter",
7052
+ `process_uptime_seconds ${snapshot.uptimeSeconds}`
7053
+ ];
7054
+ return `${lines.join("\n")}
7055
+ `;
7056
+ }
7057
+ var MetricsUtils = {
7058
+ cpu: readCpu,
7059
+ memory: readMemory,
7060
+ system: readSystem,
7061
+ toPrometheus
7062
+ };
7063
+
7064
+ // src/utils/email.ts
7065
+ var EmailUtils = class {
7066
+ /**
7067
+ * @param options - SMTP connection and default sender.
7068
+ */
7069
+ constructor(options) {
7070
+ this.options = options;
7071
+ }
7072
+ options;
7073
+ transport = null;
7074
+ async ready() {
7075
+ if (this.transport) return this.transport;
7076
+ let nodemailer;
7077
+ try {
7078
+ const mod = await import('nodemailer');
7079
+ nodemailer = mod.default ?? mod;
7080
+ } catch (cause) {
7081
+ throw new Error(
7082
+ "EmailUtils requires the 'nodemailer' peer dependency. Install with `npm i nodemailer`.",
7083
+ { cause }
7084
+ );
7085
+ }
7086
+ this.transport = nodemailer.createTransport({
7087
+ host: this.options.host,
7088
+ port: this.options.port ?? 587,
7089
+ secure: this.options.secure ?? false,
7090
+ ...this.options.user ? { auth: { user: this.options.user, pass: this.options.password ?? "" } } : {}
7091
+ });
7092
+ return this.transport;
7093
+ }
7094
+ /**
7095
+ * Send an email message.
7096
+ *
7097
+ * @param message - The message (recipients, subject, body).
7098
+ */
7099
+ async send(message) {
7100
+ const transport = await this.ready();
7101
+ await transport.sendMail({
7102
+ from: message.from ?? this.options.from,
7103
+ to: message.to,
7104
+ subject: message.subject,
7105
+ ...message.text !== void 0 ? { text: message.text } : {},
7106
+ ...message.html !== void 0 ? { html: message.html } : {}
7107
+ });
7108
+ }
7109
+ };
7110
+
7111
+ // src/cache/manager.ts
7112
+ var MemoryCacheManager = class {
7113
+ store = /* @__PURE__ */ new Map();
7114
+ live(key) {
7115
+ const entry = this.store.get(key);
7116
+ if (!entry) return null;
7117
+ if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
7118
+ this.store.delete(key);
7119
+ return null;
7120
+ }
7121
+ return entry;
7122
+ }
7123
+ async get(key) {
7124
+ const entry = this.live(key);
7125
+ return entry ? JSON.parse(entry.value) : null;
7126
+ }
7127
+ async set(key, value, ttlSeconds) {
7128
+ this.store.set(key, {
7129
+ value: JSON.stringify(value),
7130
+ expiresAt: ttlSeconds !== void 0 ? Date.now() + ttlSeconds * 1e3 : null
7131
+ });
7132
+ }
7133
+ async delete(key) {
7134
+ this.store.delete(key);
7135
+ }
7136
+ async has(key) {
7137
+ return this.live(key) !== null;
7138
+ }
7139
+ async clear() {
7140
+ this.store.clear();
7141
+ }
7142
+ };
7143
+ var RedisCacheManager = class {
7144
+ /**
7145
+ * @param client - A connected `redis` (node-redis v4) client or compatible.
7146
+ * @param prefix - Optional key prefix applied to every operation.
7147
+ */
7148
+ constructor(client, prefix = "") {
7149
+ this.client = client;
7150
+ this.prefix = prefix;
7151
+ }
7152
+ client;
7153
+ prefix;
7154
+ key(key) {
7155
+ return this.prefix ? `${this.prefix}${key}` : key;
7156
+ }
7157
+ async get(key) {
7158
+ const raw = await this.client.get(this.key(key));
7159
+ return raw === null ? null : JSON.parse(raw);
7160
+ }
7161
+ async set(key, value, ttlSeconds) {
7162
+ const payload = JSON.stringify(value);
7163
+ await this.client.set(
7164
+ this.key(key),
7165
+ payload,
7166
+ ttlSeconds !== void 0 ? { EX: ttlSeconds } : void 0
7167
+ );
7168
+ }
7169
+ async delete(key) {
7170
+ await this.client.del(this.key(key));
7171
+ }
7172
+ async has(key) {
7173
+ return await this.client.exists(this.key(key)) > 0;
7174
+ }
7175
+ async clear() {
7176
+ await this.client.flushDb();
7177
+ }
7178
+ };
7179
+
7180
+ // src/cache/cached.ts
7181
+ function cached3(fn, options) {
7182
+ return async (...args) => {
7183
+ const key = options.key(...args);
7184
+ const hit = await options.manager.get(key);
7185
+ if (hit !== null) return hit;
7186
+ const result = await fn(...args);
7187
+ await options.manager.set(key, result, options.ttlSeconds);
7188
+ return result;
7189
+ };
7190
+ }
7191
+
7192
+ // src/sessions/store.ts
7193
+ var MemorySessionStore = class {
7194
+ byHash = /* @__PURE__ */ new Map();
7195
+ live(session, idHash) {
7196
+ if (!session) return null;
7197
+ if (session.expiresAt <= Date.now()) {
7198
+ this.byHash.delete(idHash);
7199
+ return null;
7200
+ }
7201
+ return session;
7202
+ }
7203
+ async get(idHash) {
7204
+ return this.live(this.byHash.get(idHash), idHash);
7205
+ }
7206
+ async set(session) {
7207
+ this.byHash.set(session.idHash, session);
7208
+ }
7209
+ async delete(idHash) {
7210
+ this.byHash.delete(idHash);
7211
+ }
7212
+ async deleteByUser(userId) {
7213
+ let count = 0;
7214
+ for (const [hash, session] of this.byHash) {
7215
+ if (session.userId === userId) {
7216
+ this.byHash.delete(hash);
7217
+ count += 1;
7218
+ }
7219
+ }
7220
+ return count;
7221
+ }
7222
+ async listByUser(userId) {
7223
+ const now = Date.now();
7224
+ return [...this.byHash.values()].filter((s) => s.userId === userId && s.expiresAt > now).sort((a, b) => a.createdAt - b.createdAt);
7225
+ }
7226
+ };
7227
+
7228
+ // src/sessions/service.ts
7229
+ var SessionService = class {
7230
+ store;
7231
+ ttlSeconds;
7232
+ /**
7233
+ * @param options - Store and default TTL.
7234
+ */
7235
+ constructor(options) {
7236
+ this.store = options.store;
7237
+ this.ttlSeconds = options.ttlSeconds ?? 60 * 60 * 24 * 7;
7238
+ }
7239
+ /**
7240
+ * Create a session for `userId` and return its one-time cookie value.
7241
+ *
7242
+ * @param userId - The owning user id.
7243
+ * @param data - Arbitrary session payload.
7244
+ * @param ttlSeconds - Override the default lifetime.
7245
+ * @returns The plaintext token (set as a cookie) and the stored session.
7246
+ */
7247
+ async create(userId, data = {}, ttlSeconds) {
7248
+ const { plaintext, tokenHash } = generateOpaqueToken();
7249
+ const now = Date.now();
7250
+ const session = {
7251
+ idHash: tokenHash,
7252
+ userId,
7253
+ data,
7254
+ createdAt: now,
7255
+ expiresAt: now + (ttlSeconds ?? this.ttlSeconds) * 1e3
7256
+ };
7257
+ await this.store.set(session);
7258
+ return { token: plaintext, session };
7259
+ }
7260
+ /**
7261
+ * Resolve an opaque cookie value to its live session.
7262
+ *
7263
+ * @param token - The plaintext cookie value.
7264
+ * @returns The session, or `null` when missing/expired.
7265
+ */
7266
+ async resolve(token) {
7267
+ return this.store.get(hashOpaqueToken(token));
7268
+ }
7269
+ /**
7270
+ * Revoke a single session by its cookie value.
7271
+ *
7272
+ * @param token - The plaintext cookie value.
7273
+ */
7274
+ async destroy(token) {
7275
+ await this.store.delete(hashOpaqueToken(token));
7276
+ }
7277
+ /**
7278
+ * Revoke every session a user owns (global logout).
7279
+ *
7280
+ * @param userId - The user id.
7281
+ * @returns The number of sessions removed.
7282
+ */
7283
+ async destroyByUser(userId) {
7284
+ return this.store.deleteByUser(userId);
7285
+ }
7286
+ /**
7287
+ * List a user's live sessions (e.g. an "active devices" view).
7288
+ *
7289
+ * @param userId - The user id.
7290
+ * @returns The user's sessions, oldest first.
7291
+ */
7292
+ async listByUser(userId) {
7293
+ return this.store.listByUser(userId);
7294
+ }
7295
+ };
7296
+
7297
+ // src/sessions/middleware.ts
7298
+ function parseCookies(header) {
7299
+ const out = {};
7300
+ if (!header) return out;
7301
+ for (const part of header.split(";")) {
7302
+ const index = part.indexOf("=");
7303
+ if (index < 0) continue;
7304
+ const name = part.slice(0, index).trim();
7305
+ const value = part.slice(index + 1).trim();
7306
+ if (name) out[name] = decodeURIComponent(value);
7307
+ }
7308
+ return out;
7309
+ }
7310
+ function sessionCookie(req, cookieName) {
7311
+ return parseCookies(req.header("cookie") ?? void 0)[cookieName] ?? null;
7312
+ }
7313
+ function makeSessionMiddleware(service, options = {}) {
7314
+ const cookieName = options.cookieName ?? "sid";
7315
+ return (req, _res, next) => {
7316
+ const token = sessionCookie(req, cookieName);
7317
+ if (!token) {
7318
+ req.session = null;
7319
+ next();
7320
+ return;
7321
+ }
7322
+ service.resolve(token).then((session) => {
7323
+ req.session = session;
7324
+ next();
7325
+ }).catch(next);
7326
+ };
7327
+ }
7328
+
7329
+ // src/sse/eventStream.ts
7330
+ var ServerSentEvent = class {
7331
+ constructor(init) {
7332
+ this.init = init;
7333
+ }
7334
+ init;
7335
+ /**
7336
+ * Encode to the SSE wire format (terminated by a blank line).
7337
+ *
7338
+ * @returns The encoded event block.
7339
+ */
7340
+ encode() {
7341
+ const lines = [];
7342
+ if (this.init.event) lines.push(`event: ${this.init.event}`);
7343
+ if (this.init.id) lines.push(`id: ${this.init.id}`);
7344
+ if (this.init.retry !== void 0) lines.push(`retry: ${this.init.retry}`);
7345
+ for (const line of this.init.data.split("\n")) lines.push(`data: ${line}`);
7346
+ return `${lines.join("\n")}
7347
+
7348
+ `;
7349
+ }
7350
+ };
7351
+ function deferred() {
7352
+ let resolve;
7353
+ const promise = new Promise((r) => {
7354
+ resolve = r;
7355
+ });
7356
+ return { promise, resolve };
7357
+ }
7358
+ var EventStream = class {
7359
+ queue = [];
7360
+ waiter = null;
7361
+ closed = false;
7362
+ heartbeatSeconds;
7363
+ /**
7364
+ * @param options - Heartbeat configuration.
7365
+ */
7366
+ constructor(options = {}) {
7367
+ this.heartbeatSeconds = options.heartbeatSeconds ?? 15;
7368
+ }
7369
+ /** Enqueue raw SSE-encoded text and wake the iterator. */
7370
+ push(raw) {
7371
+ if (this.closed) return;
7372
+ this.queue.push(raw);
7373
+ this.waiter?.resolve();
7374
+ this.waiter = null;
7375
+ }
7376
+ /**
7377
+ * Publish a data payload as an SSE event.
7378
+ *
7379
+ * @param data - The payload; objects are JSON-encoded.
7380
+ * @param event - Optional event name.
7381
+ */
7382
+ publish(data, event) {
7383
+ const payload = typeof data === "string" ? data : JSON.stringify(data);
7384
+ this.push(
7385
+ new ServerSentEvent({ data: payload, ...event ? { event } : {} }).encode()
7386
+ );
7387
+ }
7388
+ /** Publish a pre-built {@link ServerSentEvent}. */
7389
+ publishEvent(event) {
7390
+ this.push(event.encode());
7391
+ }
7392
+ /** Close the stream; the iterator finishes after draining. */
7393
+ close() {
7394
+ this.closed = true;
7395
+ this.waiter?.resolve();
7396
+ this.waiter = null;
7397
+ }
7398
+ /**
7399
+ * Async iterator yielding encoded SSE chunks, with periodic heartbeats.
7400
+ *
7401
+ * @returns An async iterator of encoded event strings.
7402
+ */
7403
+ async *stream() {
7404
+ const heartbeatMs = this.heartbeatSeconds !== null ? this.heartbeatSeconds * 1e3 : null;
7405
+ while (!this.closed || this.queue.length > 0) {
7406
+ if (this.queue.length > 0) {
7407
+ yield this.queue.shift();
7408
+ continue;
7409
+ }
7410
+ if (this.closed) break;
7411
+ this.waiter = deferred();
7412
+ if (heartbeatMs === null) {
7413
+ await this.waiter.promise;
7414
+ } else {
7415
+ let timer;
7416
+ const heartbeat = new Promise((resolve) => {
7417
+ timer = setTimeout(resolve, heartbeatMs);
7418
+ });
7419
+ await Promise.race([this.waiter.promise, heartbeat]);
7420
+ if (timer) clearTimeout(timer);
7421
+ if (this.queue.length === 0 && !this.closed) yield ": ping\n\n";
7422
+ }
7423
+ }
7424
+ }
7425
+ };
7426
+ async function sseResponse(req, res, stream) {
7427
+ res.setHeader("Content-Type", "text/event-stream");
7428
+ res.setHeader("Cache-Control", "no-cache");
7429
+ res.setHeader("Connection", "keep-alive");
7430
+ res.flushHeaders?.();
7431
+ req.on("close", () => stream.close());
7432
+ for await (const chunk of stream.stream()) {
7433
+ if (res.writableEnded) break;
7434
+ res.write(chunk);
7435
+ }
7436
+ res.end();
7437
+ }
7438
+
7439
+ // src/sse/broker.ts
7440
+ var SSEBroker = class {
7441
+ /**
7442
+ * @param streamOptions - Options applied to every {@link EventStream} created
7443
+ * by {@link register} (e.g. heartbeat interval).
7444
+ */
7445
+ constructor(streamOptions = {}) {
7446
+ this.streamOptions = streamOptions;
7447
+ }
7448
+ streamOptions;
7449
+ channels = /* @__PURE__ */ new Map();
7450
+ /**
7451
+ * Register a new subscriber stream on `channel`.
7452
+ *
7453
+ * @param channel - The channel name.
7454
+ * @returns A fresh {@link EventStream} to serve to the subscriber.
7455
+ */
7456
+ register(channel) {
7457
+ const stream = new EventStream(this.streamOptions);
7458
+ const set = this.channels.get(channel) ?? /* @__PURE__ */ new Set();
7459
+ set.add(stream);
7460
+ this.channels.set(channel, set);
7461
+ return stream;
7462
+ }
7463
+ /**
7464
+ * Remove a subscriber stream from `channel` and close it.
7465
+ *
7466
+ * @param channel - The channel name.
7467
+ * @param stream - The stream to remove.
7468
+ */
7469
+ unregister(channel, stream) {
7470
+ const set = this.channels.get(channel);
7471
+ if (!set) return;
7472
+ set.delete(stream);
7473
+ stream.close();
7474
+ if (set.size === 0) this.channels.delete(channel);
7475
+ }
7476
+ /**
7477
+ * Number of live subscribers on `channel`.
7478
+ *
7479
+ * @param channel - The channel name.
7480
+ * @returns The subscriber count.
7481
+ */
7482
+ localSubscribers(channel) {
7483
+ return this.channels.get(channel)?.size ?? 0;
7484
+ }
7485
+ /**
7486
+ * Publish an event to every subscriber on `channel`.
7487
+ *
7488
+ * @param channel - The channel name.
7489
+ * @param data - The payload (objects are JSON-encoded).
7490
+ * @param event - Optional event name.
7491
+ * @returns The number of subscribers the event was delivered to.
7492
+ */
7493
+ publish(channel, data, event) {
7494
+ const set = this.channels.get(channel);
7495
+ if (!set) return 0;
7496
+ for (const stream of set) stream.publish(data, event);
7497
+ return set.size;
7498
+ }
7499
+ };
7500
+
7501
+ // src/websockets/schemas.ts
7502
+ var wsEnvelopeSchema = z.object({
7503
+ type: z.string().openapi({ description: "Message type discriminator." }),
7504
+ data: z.unknown().optional().openapi({ description: "Arbitrary payload." })
7505
+ }).openapi("WSEnvelope");
7506
+ var WebSocketHub = class {
7507
+ byId = /* @__PURE__ */ new Map();
7508
+ byUser = /* @__PURE__ */ new Map();
7509
+ maxPerUser;
7510
+ /**
7511
+ * @param options - Per-user connection cap.
7512
+ */
7513
+ constructor(options = {}) {
7514
+ this.maxPerUser = options.maxPerUser ?? 5;
7515
+ }
7516
+ /**
7517
+ * Register a new connection for `userId`, evicting the oldest if over cap.
7518
+ *
7519
+ * @param userId - The owning user id.
7520
+ * @param ws - The socket to register.
7521
+ * @returns The created connection record.
7522
+ */
7523
+ register(userId, ws) {
7524
+ const connection = {
7525
+ id: randomUUID(),
7526
+ userId,
7527
+ ws,
7528
+ topics: /* @__PURE__ */ new Set()
7529
+ };
7530
+ this.byId.set(connection.id, connection);
7531
+ const ids = this.byUser.get(userId) ?? /* @__PURE__ */ new Set();
7532
+ ids.add(connection.id);
7533
+ this.byUser.set(userId, ids);
7534
+ if (ids.size > this.maxPerUser) {
7535
+ const oldest = ids.values().next().value;
7536
+ if (oldest) this.unregister(oldest, 1008);
7537
+ }
7538
+ return connection;
7539
+ }
7540
+ /**
7541
+ * Remove a connection and close its socket.
7542
+ *
7543
+ * @param connectionId - The connection id.
7544
+ * @param code - Optional WebSocket close code.
7545
+ */
7546
+ unregister(connectionId, code) {
7547
+ const connection = this.byId.get(connectionId);
7548
+ if (!connection) return;
7549
+ this.byId.delete(connectionId);
7550
+ const ids = this.byUser.get(connection.userId);
7551
+ if (ids) {
7552
+ ids.delete(connectionId);
7553
+ if (ids.size === 0) this.byUser.delete(connection.userId);
7554
+ }
7555
+ try {
7556
+ connection.ws.close(code);
7557
+ } catch {
7558
+ }
7559
+ }
7560
+ /** Subscribe a connection to a topic. */
7561
+ subscribe(connectionId, topic) {
7562
+ this.byId.get(connectionId)?.topics.add(topic);
7563
+ }
7564
+ /** Unsubscribe a connection from a topic. */
7565
+ unsubscribe(connectionId, topic) {
7566
+ this.byId.get(connectionId)?.topics.delete(topic);
7567
+ }
7568
+ /** Serialize and send an envelope to a single connection. */
7569
+ deliver(connection, payload) {
7570
+ try {
7571
+ connection.ws.send(payload);
7572
+ return true;
7573
+ } catch {
7574
+ this.unregister(connection.id);
7575
+ return false;
7576
+ }
7577
+ }
7578
+ /**
7579
+ * Send an envelope to every connection of `userId`.
7580
+ *
7581
+ * @param userId - The target user.
7582
+ * @param envelope - The message envelope.
7583
+ * @returns The number of connections delivered to.
7584
+ */
7585
+ sendTo(userId, envelope) {
7586
+ const ids = this.byUser.get(userId);
7587
+ if (!ids) return 0;
7588
+ const payload = JSON.stringify(envelope);
7589
+ let count = 0;
7590
+ for (const id of [...ids]) {
7591
+ const connection = this.byId.get(id);
7592
+ if (connection && this.deliver(connection, payload)) count += 1;
7593
+ }
7594
+ return count;
7595
+ }
7596
+ /**
7597
+ * Broadcast an envelope to all connections, or only a topic's subscribers.
7598
+ *
7599
+ * @param envelope - The message envelope.
7600
+ * @param topic - Optional topic to scope the broadcast.
7601
+ * @returns The number of connections delivered to.
7602
+ */
7603
+ broadcast(envelope, topic) {
7604
+ const payload = JSON.stringify(envelope);
7605
+ let count = 0;
7606
+ for (const connection of [...this.byId.values()]) {
7607
+ if (topic && !connection.topics.has(topic)) continue;
7608
+ if (this.deliver(connection, payload)) count += 1;
7609
+ }
7610
+ return count;
7611
+ }
7612
+ /** The set of users with at least one live connection. */
7613
+ onlineUsers() {
7614
+ return new Set(this.byUser.keys());
7615
+ }
7616
+ /** Total live connection count. */
7617
+ connectionCount() {
7618
+ return this.byId.size;
7619
+ }
7620
+ /** Number of connections subscribed to `topic`. */
7621
+ topicCount(topic) {
7622
+ let count = 0;
7623
+ for (const connection of this.byId.values()) {
7624
+ if (connection.topics.has(topic)) count += 1;
7625
+ }
7626
+ return count;
7627
+ }
7628
+ };
7629
+
7630
+ // src/websockets/attach.ts
7631
+ function tokenFromUrl(url) {
7632
+ const query = url.includes("?") ? url.slice(url.indexOf("?") + 1) : "";
7633
+ return new URLSearchParams(query).get("token");
7634
+ }
7635
+ async function attachWebSocketHub(server, hub, options = {}) {
7636
+ let ws;
7637
+ try {
7638
+ ws = await import('ws');
7639
+ } catch (cause) {
7640
+ throw new Error(
7641
+ "attachWebSocketHub requires the 'ws' peer dependency. Install with `npm i ws`.",
7642
+ { cause }
7643
+ );
7644
+ }
7645
+ const path = options.path ?? "/ws";
7646
+ const heartbeatMs = (options.heartbeatSeconds ?? 30) * 1e3;
7647
+ const authenticate = options.authenticate ?? (() => "anonymous");
7648
+ const wss = new ws.WebSocketServer({ server, path });
7649
+ wss.on("connection", (socket, req) => {
7650
+ void (async () => {
7651
+ const userId = await authenticate({
7652
+ url: req.url ?? "",
7653
+ headers: req.headers
7654
+ });
7655
+ if (userId === null) {
7656
+ socket.close(1008);
7657
+ return;
7658
+ }
7659
+ const connection = hub.register(userId, socket);
7660
+ let alive = true;
7661
+ socket.on("pong", () => {
7662
+ alive = true;
7663
+ });
7664
+ socket.on("message", (data) => {
7665
+ options.onMessage?.(connection, String(data));
7666
+ });
7667
+ socket.on("close", () => {
7668
+ alive = false;
7669
+ hub.unregister(connection.id);
7670
+ });
7671
+ if (heartbeatMs > 0) {
7672
+ const timer = setInterval(() => {
7673
+ if (!alive) {
7674
+ clearInterval(timer);
7675
+ hub.unregister(connection.id);
7676
+ return;
7677
+ }
7678
+ alive = false;
7679
+ socket.ping();
7680
+ }, heartbeatMs);
7681
+ socket.on("close", () => clearInterval(timer));
7682
+ }
7683
+ })();
7684
+ });
7685
+ return wss;
7686
+ }
7687
+
7688
+ // src/queue/broker.ts
7689
+ var MemoryBroker = class {
7690
+ handlers = /* @__PURE__ */ new Map();
7691
+ async publish(queue, message) {
7692
+ const set = this.handlers.get(queue);
7693
+ if (!set) return;
7694
+ const payload = JSON.parse(JSON.stringify(message));
7695
+ for (const handler of [...set]) await handler(payload);
7696
+ }
7697
+ async subscribe(queue, handler) {
7698
+ const set = this.handlers.get(queue) ?? /* @__PURE__ */ new Set();
7699
+ set.add(handler);
7700
+ this.handlers.set(queue, set);
7701
+ return async () => {
7702
+ set.delete(handler);
7703
+ if (set.size === 0) this.handlers.delete(queue);
7704
+ };
7705
+ }
7706
+ async close() {
7707
+ this.handlers.clear();
7708
+ }
7709
+ };
7710
+ var RabbitBroker = class {
7711
+ /**
7712
+ * @param options - Connection URL and queue durability.
7713
+ */
7714
+ constructor(options) {
7715
+ this.options = options;
7716
+ this.durable = options.durable ?? true;
7717
+ }
7718
+ options;
7719
+ connection = null;
7720
+ channel = null;
7721
+ durable;
7722
+ /** Lazily connect and open a channel. */
7723
+ async ready() {
7724
+ if (this.channel) return this.channel;
7725
+ let amqp;
7726
+ try {
7727
+ amqp = await import('amqplib');
7728
+ } catch (cause) {
7729
+ throw new Error(
7730
+ "RabbitBroker requires the 'amqplib' peer dependency. Install with `npm i amqplib`.",
7731
+ { cause }
7732
+ );
7733
+ }
7734
+ this.connection = await amqp.connect(this.options.url);
7735
+ this.channel = await this.connection.createChannel();
7736
+ return this.channel;
7737
+ }
7738
+ async publish(queue, message) {
7739
+ const channel = await this.ready();
7740
+ await channel.assertQueue(queue, { durable: this.durable });
7741
+ channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)), {
7742
+ persistent: this.durable
7743
+ });
7744
+ }
7745
+ async subscribe(queue, handler) {
7746
+ const channel = await this.ready();
7747
+ await channel.assertQueue(queue, { durable: this.durable });
7748
+ const { consumerTag } = await channel.consume(queue, (msg) => {
7749
+ if (!msg) return;
7750
+ void Promise.resolve(handler(JSON.parse(msg.content.toString()))).then(() => channel.ack(msg)).catch(() => channel.nack(msg, false, false));
7751
+ });
7752
+ return async () => {
7753
+ await channel.cancel(consumerTag);
7754
+ };
7755
+ }
7756
+ async close() {
7757
+ await this.channel?.close();
7758
+ await this.connection?.close();
7759
+ this.channel = null;
7760
+ this.connection = null;
7761
+ }
7762
+ };
7763
+
7764
+ // src/tasks/manager.ts
7765
+ var logger = new JSONLogger("tempest_express_sdk.tasks");
7766
+ var TaskManager = class {
7767
+ broker;
7768
+ queue;
7769
+ handlers = /* @__PURE__ */ new Map();
7770
+ unsubscribe = null;
7771
+ /**
7772
+ * @param options - Broker and queue name.
7773
+ */
7774
+ constructor(options = {}) {
7775
+ this.broker = options.broker ?? new MemoryBroker();
7776
+ this.queue = options.queue ?? "tasks";
7777
+ }
7778
+ /**
7779
+ * Register a handler for a named task.
7780
+ *
7781
+ * @param name - The task name.
7782
+ * @param handler - The handler invoked with the task payload.
7783
+ */
7784
+ register(name, handler) {
7785
+ this.handlers.set(name, handler);
7786
+ }
7787
+ /**
7788
+ * Enqueue a task by name.
7789
+ *
7790
+ * @param name - The registered task name.
7791
+ * @param payload - The JSON-serializable payload.
7792
+ */
7793
+ async enqueue(name, payload = {}) {
7794
+ const envelope = { name, payload };
7795
+ await this.broker.publish(this.queue, envelope);
7796
+ }
7797
+ /**
7798
+ * Start the worker: subscribe to the task queue and dispatch to handlers.
7799
+ * A task with no registered handler is logged and skipped.
7800
+ */
7801
+ async start() {
7802
+ if (this.unsubscribe) return;
7803
+ this.unsubscribe = await this.broker.subscribe(this.queue, async (message) => {
7804
+ const { name, payload } = message;
7805
+ const handler = this.handlers.get(name);
7806
+ if (!handler) {
7807
+ logger.warning("No handler for task", { task: name });
7808
+ return;
7809
+ }
7810
+ await handler(payload);
7811
+ });
7812
+ }
7813
+ /** Stop the worker (stops consuming; does not close the broker). */
7814
+ async stop() {
7815
+ await this.unsubscribe?.();
7816
+ this.unsubscribe = null;
7817
+ }
7818
+ };
7819
+
7820
+ // src/flags/backends.ts
7821
+ function coerceFlag(value) {
7822
+ if (typeof value === "boolean") return value;
7823
+ if (typeof value === "number") return value !== 0;
7824
+ if (typeof value === "string") {
7825
+ return ["1", "true", "on", "yes", "enabled"].includes(value.trim().toLowerCase());
7826
+ }
7827
+ return false;
7828
+ }
7829
+ var MemoryFeatureFlagBackend = class {
7830
+ flags = /* @__PURE__ */ new Map();
7831
+ /**
7832
+ * @param initial - Initial flag → enabled map.
7833
+ */
7834
+ constructor(initial = {}) {
7835
+ for (const [flag, enabled] of Object.entries(initial)) this.flags.set(flag, enabled);
7836
+ }
7837
+ /** Set or override a flag. */
7838
+ set(flag, enabled) {
7839
+ this.flags.set(flag, enabled);
7840
+ }
7841
+ resolve(flag) {
7842
+ return this.flags.has(flag) ? this.flags.get(flag) : null;
7843
+ }
7844
+ };
7845
+ var EnvFeatureFlagBackend = class {
7846
+ /**
7847
+ * @param env - Environment source (defaults to `process.env`).
7848
+ * @param prefix - Env var prefix. Default `FLAG_`.
7849
+ */
7850
+ constructor(env = process.env, prefix = "FLAG_") {
7851
+ this.env = env;
7852
+ this.prefix = prefix;
7853
+ }
7854
+ env;
7855
+ prefix;
7856
+ key(flag) {
7857
+ return this.prefix + flag.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
7858
+ }
7859
+ resolve(flag) {
7860
+ const raw = this.env[this.key(flag)];
7861
+ return raw === void 0 ? null : coerceFlag(raw);
7862
+ }
7863
+ };
7864
+ var CompositeFeatureFlagBackend = class {
7865
+ /**
7866
+ * @param backends - Backends in priority order.
7867
+ */
7868
+ constructor(backends) {
7869
+ this.backends = backends;
7870
+ }
7871
+ backends;
7872
+ async resolve(flag, context) {
7873
+ for (const backend of this.backends) {
7874
+ const answer = await backend.resolve(flag, context);
7875
+ if (answer !== null) return answer;
7876
+ }
7877
+ return null;
7878
+ }
7879
+ };
7880
+
7881
+ // src/flags/service.ts
7882
+ var FeatureFlags = class {
7883
+ /**
7884
+ * @param backend - The resolving backend.
7885
+ * @param defaultEnabled - Value used when the backend returns `null`.
7886
+ */
7887
+ constructor(backend, defaultEnabled = false) {
7888
+ this.backend = backend;
7889
+ this.defaultEnabled = defaultEnabled;
7890
+ }
7891
+ backend;
7892
+ defaultEnabled;
7893
+ /**
7894
+ * Whether `flag` is enabled for the given context.
7895
+ *
7896
+ * @param flag - The flag name.
7897
+ * @param context - Optional evaluation context.
7898
+ * @returns `true` when enabled (or default when the backend is undecided).
7899
+ */
7900
+ async isEnabled(flag, context) {
7901
+ const answer = await this.backend.resolve(flag, context);
7902
+ return answer ?? this.defaultEnabled;
7903
+ }
7904
+ };
7905
+ function makeFlagGuard(flags, flag) {
7906
+ return (_req, _res, next) => {
7907
+ flags.isEnabled(flag).then((enabled) => {
7908
+ if (enabled) next();
7909
+ else next(new NotFoundException({ message: "Not found", details: { flag } }));
7910
+ }).catch(next);
7911
+ };
7912
+ }
7913
+ var LocalUploadStorage = class {
7914
+ root;
7915
+ baseUrl;
7916
+ /**
7917
+ * @param options - Filesystem root and public base URL.
7918
+ */
7919
+ constructor(options) {
7920
+ this.root = options.root;
7921
+ this.baseUrl = options.baseUrl ?? "";
7922
+ }
7923
+ async save(key, data, options = {}) {
7924
+ const target = join(this.root, key);
7925
+ await mkdir(dirname(target), { recursive: true });
7926
+ await writeFile(target, data);
7927
+ return {
7928
+ key,
7929
+ url: this.url(key),
7930
+ size: data.byteLength,
7931
+ ...options.contentType !== void 0 ? { contentType: options.contentType } : {}
7932
+ };
7933
+ }
7934
+ async read(key) {
7935
+ return readFile(join(this.root, key));
7936
+ }
7937
+ async delete(key) {
7938
+ await rm(join(this.root, key), { force: true });
7939
+ }
7940
+ url(key) {
7941
+ const base = this.baseUrl.replace(/\/$/, "");
7942
+ return base ? `${base}/${key}` : `/${key}`;
7943
+ }
7944
+ };
7945
+ function buildContentDisposition(filename, inline = false) {
7946
+ const disposition = inline ? "inline" : "attachment";
7947
+ const encoded = encodeURIComponent(filename);
7948
+ return `${disposition}; filename*=UTF-8''${encoded}`;
7949
+ }
7950
+
7951
+ // src/webpush/schemas.ts
7952
+ var webPushKeysSchema = z.object({
7953
+ p256dh: z.string().openapi({ description: "Client public key (base64url)." }),
7954
+ auth: z.string().openapi({ description: "Client auth secret (base64url)." })
7955
+ }).openapi("WebPushKeys");
7956
+ var webPushSubscriptionSchema = z.object({
7957
+ endpoint: z.string().url().openapi({ description: "Push service endpoint URL." }),
7958
+ keys: webPushKeysSchema
7959
+ }).openapi("WebPushSubscription");
7960
+ var webPushPayloadSchema = z.object({
7961
+ title: z.string().openapi({ description: "Notification title." }),
7962
+ body: z.string().optional().openapi({ description: "Notification body." }),
7963
+ url: z.string().optional().openapi({ description: "URL opened on click." }),
7964
+ data: z.record(z.unknown()).optional().openapi({ description: "Extra data." })
7965
+ }).openapi("WebPushPayload");
7966
+
7967
+ // src/webpush/dispatcher.ts
7968
+ var WebPushError = class extends Error {
7969
+ constructor(message, statusCode) {
7970
+ super(message);
7971
+ this.statusCode = statusCode;
7972
+ this.name = "WebPushError";
7973
+ }
7974
+ statusCode;
7975
+ };
7976
+ var WebPushGoneError = class extends WebPushError {
7977
+ constructor(statusCode) {
7978
+ super("Push subscription is gone", statusCode);
7979
+ this.name = "WebPushGoneError";
7980
+ }
7981
+ };
7982
+ var cached4 = null;
7983
+ async function loadWebPush() {
7984
+ if (cached4) return cached4;
7985
+ try {
7986
+ const mod = await import('web-push');
7987
+ cached4 = mod.default ?? mod;
7988
+ } catch (cause) {
7989
+ throw new Error(
7990
+ "WebPushDispatcher requires the 'web-push' peer dependency. Install with `npm i web-push`.",
7991
+ { cause }
7992
+ );
7993
+ }
7994
+ return cached4;
7995
+ }
7996
+ var WebPushDispatcher = class {
7997
+ /**
7998
+ * @param options - VAPID keys and subject.
7999
+ */
8000
+ constructor(options) {
8001
+ this.options = options;
8002
+ }
8003
+ options;
8004
+ /**
8005
+ * Send a payload to a single subscription.
8006
+ *
8007
+ * @param subscription - The browser push subscription.
8008
+ * @param payload - The notification payload.
8009
+ * @throws {WebPushGoneError} When the subscription is expired (410/404).
8010
+ * @throws {WebPushError} On any other delivery failure.
8011
+ */
8012
+ async send(subscription, payload) {
8013
+ const webpush = await loadWebPush();
8014
+ webpush.setVapidDetails(
8015
+ this.options.subject,
8016
+ this.options.publicKey,
8017
+ this.options.privateKey
8018
+ );
8019
+ try {
8020
+ await webpush.sendNotification(subscription, JSON.stringify(payload));
8021
+ } catch (error) {
8022
+ const status = error.statusCode;
8023
+ if (status === 404 || status === 410) throw new WebPushGoneError(status);
8024
+ throw new WebPushError(error.message, status);
8025
+ }
8026
+ }
8027
+ };
8028
+
6753
8029
  // src/auth/schemas.ts
6754
8030
  var signupSchema = z.object({
6755
8031
  email: z.string().email().openapi({ description: "Login identifier (email)." }),
@@ -6996,7 +8272,7 @@ function makeAuthRouter(options) {
6996
8272
  });
6997
8273
  return router;
6998
8274
  }
6999
- var logger = new JSONLogger("tempest_express_sdk.api.handlers");
8275
+ var logger2 = new JSONLogger("tempest_express_sdk.api.handlers");
7000
8276
  var REQUEST_ID_HEADER = "X-Request-ID";
7001
8277
  function requestIdMiddleware() {
7002
8278
  return (req, res, next) => {
@@ -7037,7 +8313,7 @@ function makeAppExceptionHandler(options = {}) {
7037
8313
  return;
7038
8314
  }
7039
8315
  const isServerError = exc.statusCode >= 500;
7040
- logger.log(isServerError ? serverErrorLevel : "info", "AppException handled", {
8316
+ logger2.log(isServerError ? serverErrorLevel : "info", "AppException handled", {
7041
8317
  path: req.path,
7042
8318
  method: req.method,
7043
8319
  statusCode: exc.statusCode,
@@ -7061,7 +8337,7 @@ function makeUnhandledExceptionHandler(options = {}) {
7061
8337
  const { includeStack = false, logLevel = "error" } = options;
7062
8338
  return (err, req, res, _next) => {
7063
8339
  const error = err instanceof Error ? err : new Error(String(err));
7064
- logger.log(logLevel, "Unhandled exception", {
8340
+ logger2.log(logLevel, "Unhandled exception", {
7065
8341
  path: req.path,
7066
8342
  method: req.method,
7067
8343
  [HTTP_500_MARKER]: true,
@@ -7196,7 +8472,7 @@ function makeHealthRouter(options = {}) {
7196
8472
  });
7197
8473
  return router;
7198
8474
  }
7199
- var logger2 = new JSONLogger("tempest_express_sdk.api.server");
8475
+ var logger3 = new JSONLogger("tempest_express_sdk.api.server");
7200
8476
  function corsMiddleware(origins) {
7201
8477
  const allowAll = origins === "*";
7202
8478
  const allowList = new Set(Array.isArray(origins) ? origins : [origins]);
@@ -7255,12 +8531,12 @@ function runServer(app, options = {}) {
7255
8531
  const port = options.port ?? 8e3;
7256
8532
  return new Promise((resolve) => {
7257
8533
  const server = app.listen(port, host, () => {
7258
- logger2.info("Server listening", { host, port });
8534
+ logger3.info("Server listening", { host, port });
7259
8535
  resolve(server);
7260
8536
  });
7261
8537
  });
7262
8538
  }
7263
8539
 
7264
- export { AppException, AttemptThrottle, BaseController, BaseModel, BaseService, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, ConflictException, DEFAULT_LOCALE, ExpiredTokenException, ForbiddenException, HTTP_500_MARKER, InvalidTokenException, JSONLogger, JWTUtils, MemoryThrottleBackend, MessageCatalog, NotFoundException, PHONE_BR_PATTERN, PasswordUtils, REQUEST_ID_HEADER, Region, TooManyRequestsException, UF, UnauthorizedException, UserAuthService, ValidationException, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, cepField, citiesByUf, cnpjField, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAppExceptionHandler, makeAuthRouter, makeHealthRouter, makeJwtAuthMiddleware, makeUnhandledExceptionHandler, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, setRequestId, signupSchema, statesByRegion, tableNameFor, toDict, toUtc, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken };
8540
+ export { AppException, AttemptThrottle, BaseController, BaseModel, BaseService, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_LOCALE, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, HTTPClient, HTTP_500_MARKER, InvalidTokenException, JSONLogger, JWTUtils, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MetricsUtils, NotFoundException, PHONE_BR_PATTERN, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, Region, RetryPolicy, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TooManyRequestsException, UF, UnauthorizedException, UserAuthService, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached3 as cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
7265
8541
  //# sourceMappingURL=index.js.map
7266
8542
  //# sourceMappingURL=index.js.map