Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
build(tsconfig): enable the full TypeScript strict family
Yudhi Armyndharis9a0267dae8ab
diff --git a/src/common/utils/dto-strict-coercion.spec.ts b/src/common/utils/dto-strict-coercion.spec.tsindex 49a06ac7a..a8d04f86a 100644--- a/src/common/utils/dto-strict-coercion.spec.ts+++ b/src/common/utils/dto-strict-coercion.spec.ts@@ -1,6 +1,6 @@import 'reflect-metadata';import { getMetadataStorage, validate } from 'class-validator';-import { plainToInstance } from 'class-transformer';+import { ClassConstructor, plainToInstance } from 'class-transformer';import { readdirSync, statSync } from 'fs';import { join } from 'path';@@ -54,11 +54,9 @@ dtoFiles(SRC).forEach(file => {require(file);});-interface ValidatedClass {- new (...args: never[]): object;- name: string;- prototype: object;-}+// class-transformer's own constructor type, not a hand-rolled copy: `plainToInstance` is what these+// are handed to, so its contract is the one that has to hold.+type ValidatedClass = ClassConstructor<object> & { name: string; prototype: object };function registeredClasses(): ValidatedClass[] {const storage = getMetadataStorage() as unknown as { validationMetadatas?: Map<unknown, unknown> };diff --git a/src/core/agent-tools/session-scope-invariant.spec.ts b/src/core/agent-tools/session-scope-invariant.spec.tsindex 1d855cd5e..3744a470d 100644--- a/src/core/agent-tools/session-scope-invariant.spec.ts+++ b/src/core/agent-tools/session-scope-invariant.spec.ts@@ -4,7 +4,7 @@ import { messageTools } from './tools/message.tools';import { contactTools } from './tools/contact.tools';import { groupTools } from './tools/group.tools';import { webhookTools } from './tools/webhook.tools';-import type { ToolDescriptor } from './tool-descriptor';+import type { AnyToolDescriptor } from './tool-descriptor';// Registry-level invariant (not a per-tool enumeration): EVERY sessionScoped tool must require a// non-empty sessionId. tool-invoker only passes sessionId into the allowedSessions fence when it is a@@ -13,7 +13,7 @@ import type { ToolDescriptor } from './tool-descriptor';// This catches a FUTURE tool authored with z.string().optional() — no test edit needed when one is added.describe('agent-tool registry: every sessionScoped tool requires a non-empty sessionId', () => {// Handlers are never invoked here; stub services are fine — we only inspect the schema/flags.- const allTools: ToolDescriptor[] = [+ const allTools: AnyToolDescriptor[] = [...sessionTools({} as never),...messageTools({} as never),...contactTools({} as never),diff --git a/src/core/agent-tools/tool-descriptor.ts b/src/core/agent-tools/tool-descriptor.tsindex 40dd38ba3..0d8c8d3d8 100644--- a/src/core/agent-tools/tool-descriptor.ts+++ b/src/core/agent-tools/tool-descriptor.ts@@ -24,3 +24,20 @@ export interface ToolDescriptor<I = unknown> {/** Calls the service. Receives validated input + the resolved, scoped key. */handler: (input: I, apiKey: ApiKey) => Promise<unknown>;}++/**+ * A descriptor with its input type erased, for storing tools of different shapes in one list.+ *+ * The handler parameter is `never`, not `unknown`. Under `strictFunctionTypes` parameters are checked+ * CONTRAVARIANTLY, so a handler that accepts a specific validated shape is assignable to one+ * accepting `never` but not to one accepting `unknown` — and `unknown` would be the wrong promise+ * anyway, since the registry cannot hand a handler just anything.+ *+ * What makes the erasure sound is the invoker: it parses `inputSchema` first, so a handler only ever+ * receives a value its own schema accepted. The one cast that bridges the two lives there, next to+ * the parse that justifies it, rather than being spread across every tool definition.+ */+export type AnyToolDescriptor = Omit<ToolDescriptor, 'inputSchema' | 'handler'> & {+ inputSchema: z.ZodType;+ handler: (input: never, apiKey: ApiKey) => Promise<unknown>;+};diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.tsindex a9aac59b1..97ee1c0cf 100644--- a/src/core/agent-tools/tool-invoker.ts+++ b/src/core/agent-tools/tool-invoker.ts@@ -1,7 +1,7 @@import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';import { ZodError } from 'zod';import type { AuthService } from '../../modules/auth/auth.service';-import type { ToolDescriptor } from './tool-descriptor';+import type { AnyToolDescriptor } from './tool-descriptor';/*** Run one tool call with REST-equivalent guarantees, reusing core's own auth:@@ -21,7 +21,7 @@ import type { ToolDescriptor } from './tool-descriptor';* thrown from a handler body is NOT surfaced here. Re-thrown after the callback.*/export async function invokeTool(- tool: ToolDescriptor,+ tool: AnyToolDescriptor,rawInput: unknown,rawKey: string | undefined,authService: AuthService,@@ -71,5 +71,7 @@ export async function invokeTool(}throw e;}- return tool.handler(input, apiKey);+ // The single cast the erasure needs, placed next to the parse that justifies it: `input` is+ // whatever this tool's own `inputSchema` just accepted, which is exactly what its handler declares.+ return tool.handler(input as never, apiKey);}diff --git a/src/core/agent-tools/tool-registry.service.ts b/src/core/agent-tools/tool-registry.service.tsindex 8ee49c8c4..480e08886 100644--- a/src/core/agent-tools/tool-registry.service.ts+++ b/src/core/agent-tools/tool-registry.service.ts@@ -1,11 +1,11 @@import { Injectable } from '@nestjs/common';-import type { ToolDescriptor } from './tool-descriptor';+import type { AnyToolDescriptor } from './tool-descriptor';@Injectable()export class ToolRegistryService {- private readonly byName = new Map<string, ToolDescriptor>();+ private readonly byName = new Map<string, AnyToolDescriptor>();- constructor(tools: ToolDescriptor[]) {+ constructor(tools: AnyToolDescriptor[]) {for (const t of tools) {if (this.byName.has(t.name)) {throw new Error(`Duplicate agent tool name: ${t.name}`);@@ -14,12 +14,12 @@ export class ToolRegistryService {}}- list(opts: { readOnly?: boolean } = {}): ToolDescriptor[] {+ list(opts: { readOnly?: boolean } = {}): AnyToolDescriptor[] {const all = [...this.byName.values()];return opts.readOnly ? all.filter(t => t.tier === 'read') : all;}- get(name: string): ToolDescriptor | undefined {+ get(name: string): AnyToolDescriptor | undefined {return this.byName.get(name);}}diff --git a/src/core/agent-tools/tools/contact.tools.ts b/src/core/agent-tools/tools/contact.tools.tsindex 41b5f6911..49abdbe73 100644--- a/src/core/agent-tools/tools/contact.tools.ts+++ b/src/core/agent-tools/tools/contact.tools.ts@@ -1,11 +1,11 @@import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { ContactService } from '../../../modules/contact/contact.service';-import type { ToolDescriptor } from '../tool-descriptor';+import type { AnyToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');-export function contactTools(contact: ContactService): ToolDescriptor[] {+export function contactTools(contact: ContactService): AnyToolDescriptor[] {return [{name: 'ContactFindAll',diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsindex b74002996..bfe8f845d 100644--- a/src/core/agent-tools/tools/group.tools.ts+++ b/src/core/agent-tools/tools/group.tools.ts@@ -6,11 +6,11 @@ import {GROUP_NAME_MAX_LENGTH,GROUP_PARTICIPANTS_MAX,} from '../../../modules/group/dto/group.dto';-import type { ToolDescriptor } from '../tool-descriptor';+import type { AnyToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');-export function groupTools(group: GroupService): ToolDescriptor[] {+export function groupTools(group: GroupService): AnyToolDescriptor[] {return [{name: 'GroupFindAll',diff --git a/src/core/agent-tools/tools/message.tools.ts b/src/core/agent-tools/tools/message.tools.tsindex a5b9772cd..7e524f265 100644--- a/src/core/agent-tools/tools/message.tools.ts+++ b/src/core/agent-tools/tools/message.tools.ts@@ -8,11 +8,11 @@ import {LOCATION_TEXT_MAX_LENGTH,REACTION_EMOJI_MAX_LENGTH,} from '../../../modules/message/dto/message-actions.dto';-import type { ToolDescriptor } from '../tool-descriptor';+import type { AnyToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');-export function messageTools(message: MessageService): ToolDescriptor[] {+export function messageTools(message: MessageService): AnyToolDescriptor[] {return [{name: 'MessageList',diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsindex 9c57747bb..7a747a39a 100644--- a/src/core/agent-tools/tools/session.tools.ts+++ b/src/core/agent-tools/tools/session.tools.ts@@ -3,11 +3,11 @@ import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { ChatState } from '../../../engine/interfaces/whatsapp-engine.interface';import type { SessionService } from '../../../modules/session/session.service';import { SessionResponseDto } from '../../../modules/session/dto/session-response.dto';-import type { ToolDescriptor } from '../tool-descriptor';+import type { AnyToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');-export function sessionTools(session: SessionService): ToolDescriptor[] {+export function sessionTools(session: SessionService): AnyToolDescriptor[] {return [{name: 'SessionFindAll',diff --git a/src/core/agent-tools/tools/tool-input-caps.spec.ts b/src/core/agent-tools/tools/tool-input-caps.spec.tsindex 2adff1aa5..024e856fd 100644--- a/src/core/agent-tools/tools/tool-input-caps.spec.ts+++ b/src/core/agent-tools/tools/tool-input-caps.spec.ts@@ -22,7 +22,7 @@ import {GroupSubjectDto,ParticipantsDto,} from '../../../modules/group/dto/group.dto';-import type { ToolDescriptor } from '../tool-descriptor';+import type { AnyToolDescriptor } from '../tool-descriptor';import { messageTools } from './message.tools';import { groupTools } from './group.tools';@@ -33,7 +33,7 @@ const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };const messages = messageTools({} as unknown as MessageService);const groups = groupTools({} as unknown as GroupService);-function tool(name: string): ToolDescriptor {+function tool(name: string): AnyToolDescriptor {const found = [...messages, ...groups].find(t => t.name === name);if (!found) throw new Error(`tool not registered: ${name}`);return found;diff --git a/src/core/agent-tools/tools/webhook.tools.ts b/src/core/agent-tools/tools/webhook.tools.tsindex 87f9c58cb..cb7d043da 100644--- a/src/core/agent-tools/tools/webhook.tools.ts+++ b/src/core/agent-tools/tools/webhook.tools.ts@@ -2,11 +2,11 @@ import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { WebhookService } from '../../../modules/webhook/webhook.service';import { WebhookResponseDto } from '../../../modules/webhook/dto/webhook.dto';-import type { ToolDescriptor } from '../tool-descriptor';+import type { AnyToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');-export function webhookTools(webhook: WebhookService): ToolDescriptor[] {+export function webhookTools(webhook: WebhookService): AnyToolDescriptor[] {return [{name: 'WebhooksList',diff --git a/src/core/hooks/hook-manager.service.ts b/src/core/hooks/hook-manager.service.tsindex 778736614..cbba9360e 100644--- a/src/core/hooks/hook-manager.service.ts+++ b/src/core/hooks/hook-manager.service.ts@@ -166,7 +166,9 @@ export class HookManager {throw result.error;}} catch (error) {- this.logger.error(`Hook error in ${registration.pluginId} for ${event}: ${error}`);+ this.logger.error(+ `Hook error in ${registration.pluginId} for ${event}: ${error instanceof Error ? error.message : String(error)}`,+ );// Continue to next handler, don't break the chain on error}}diff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.tsindex 44e10ab8b..7401408ee 100644--- a/src/core/plugins/conversation-send-facade.ts+++ b/src/core/plugins/conversation-send-facade.ts@@ -7,7 +7,7 @@ import {export interface ConversationSendDeps {manifest: PluginManifest;- assertPermission: (manifest: PluginManifest, permission: string) => void;+ assertPermission: (manifest: PluginManifest, permission: PluginCapabilityPermission) => void;// Full session gate for THIS plugin (manifest scope AND operator activation), bound to the plugin by// the loader — so conversation.send is confined to activated sessions like every other capability.assertSessionActive: (sessionId: string) => void;diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.tsindex 4b486aa25..34ea14474 100644--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts@@ -2,7 +2,7 @@ import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { PluginLoaderService } from './plugin-loader.service';import { PluginStorageService } from './plugin-storage.service';-import { HookManager } from '../hooks';+import { HookContext, HookEvent, HookHandler, HookManager } from '../hooks';import { IPlugin, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';import { PluginWorkerHost } from './sandbox/plugin-worker-host';import { PluginLogLevel } from './sandbox/protocol';@@ -177,13 +177,20 @@ describe('PluginLoaderService — sandbox tier routing', () => {});describe('PluginLoaderService — sandbox hook error surfacing', () => {- type Handler = (hookCtx: { data: unknown; sessionId?: string; source: string }) => Promise<unknown>;-const loggerOf = (loader: TestableLoader): { warn: jest.Mock; log: jest.Mock } =>(loader as unknown as { logger: { warn: jest.Mock; log: jest.Mock } }).logger;+ /** A context in the shape the emitters actually build — the shim reads `event` to route. */+ const ctx = (event: HookEvent): HookContext => ({+ event,+ data: {},+ sessionId: 's1',+ timestamp: new Date(0),+ source: 'Engine',+ });+/** Enable p1, subscribe it to `event`, and return the shim the loader registered for it. */- const setupShim = async (loader: TestableLoader, event: string): Promise<Handler> => {+ const setupShim = async (loader: TestableLoader, event: HookEvent): Promise<HookHandler> => {seed(loader, { builtIn: false, instance: null });const hookManager = (loader as unknown as { hookManager: HookManager }).hookManager;const registerSpy = jest.spyOn(hookManager, 'register');@@ -201,18 +208,18 @@ describe('PluginLoaderService — sandbox hook error surfacing', () => {loader.hosts[0].dispatchHook.mockResolvedValue({ continue: true, error: 'boom' });const warnSpy = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);- await handler({ data: {}, sessionId: 's1', source: 'Engine' });+ await handler(ctx('message:sent'));expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Sandboxed plugin p1 hook 'message:sent' handler failed: boom"),expect.objectContaining({ action: 'sandbox_hook_error', pluginId: 'p1', event: 'message:sent' }),);// A second failure inside the rate-limit window is counted, not logged again.- await handler({ data: {}, sessionId: 's1', source: 'Engine' });+ await handler(ctx('message:sent'));expect(warnSpy).toHaveBeenCalledTimes(1);// The chain still fails open: the shim resolves continue:true for the hook manager.- await expect(handler({ data: {}, sessionId: 's1', source: 'Engine' })).resolves.toEqual({ continue: true });+ await expect(handler(ctx('message:sent'))).resolves.toEqual({ continue: true });// The health surface carries the last hook error without overriding the worker's own verdict.const health = await loader.checkPluginHealth('p1');@@ -235,7 +242,7 @@ describe('PluginLoaderService — sandbox hook error surfacing', () => {loader.hosts[0].dispatchHook.mockResolvedValue({ continue: true, error: 'boom' });jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);- await handler({ data: {}, sessionId: 's1', source: 'Engine' });+ await handler(ctx('message:sent'));expect((await loader.checkPluginHealth('p1')).message).toContain('last hook error');// Worker crashes (intentional=false): the host is dropped without any disable running.@@ -252,7 +259,7 @@ describe('PluginLoaderService — sandbox hook error surfacing', () => {loader.hosts[0].dispatchHook.mockResolvedValue({ continue: false, data: { n: 1 } });const warnSpy = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);- await expect(handler({ data: {}, sessionId: 's1', source: 'Engine' })).resolves.toEqual({+ await expect(handler(ctx('message:sent'))).resolves.toEqual({continue: false,data: { n: 1 },});diff --git a/src/engine/adapters/baileys-stored-message.entity.ts b/src/engine/adapters/baileys-stored-message.entity.tsindex 3e2f8a675..7116d2e5b 100644--- a/src/engine/adapters/baileys-stored-message.entity.ts+++ b/src/engine/adapters/baileys-stored-message.entity.ts@@ -14,21 +14,21 @@ import { Session } from '../../modules/session/entities/session.entity';@Index(['sessionId', 'createdAt']) // eviction orderingexport class BaileysStoredMessage {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column()- sessionId: string;+ sessionId!: string;@ManyToOne(() => Session, { onDelete: 'CASCADE' })@JoinColumn({ name: 'sessionId' })session?: Session;@Column()- waMessageId: string;+ waMessageId!: string;@Column({ type: 'text' })- serializedMessage: string;+ serializedMessage!: string;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;}diff --git a/src/engine/identity/lid-mapping.entity.ts b/src/engine/identity/lid-mapping.entity.tsindex 9b52d6cd2..9a2f48e5d 100644--- a/src/engine/identity/lid-mapping.entity.ts+++ b/src/engine/identity/lid-mapping.entity.ts@@ -16,16 +16,16 @@ import { Column, Entity, Index, PrimaryColumn, UpdateDateColumn } from 'typeorm'export class LidMapping {/** The lid number (bare, device-stripped - the user-part of `<lid>@lid`). */@PrimaryColumn()- lid: string;+ lid!: string;/** E.164 phone digits, or null when the lid is known-but-unresolved (a cached negative result). */@Column({ type: 'varchar', nullable: true })- phone: string | null;+ phone!: string | null;/** The session that last wrote this row. Provenance/debugging only; not a foreign key. */@Column({ type: 'varchar', nullable: true })- sessionId: string | null;+ sessionId!: string | null;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.tsindex 90e98b791..c2efd8c98 100644--- a/src/modules/audit/entities/audit-log.entity.ts+++ b/src/modules/audit/entities/audit-log.entity.ts@@ -76,53 +76,53 @@ export enum AuditSeverity {@Entity('audit_logs')export class AuditLog {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Index()@Column({ type: 'varchar', length: 50 })- action: AuditAction;+ action!: AuditAction;@Column({ type: 'varchar', length: 10, default: AuditSeverity.INFO })- severity: AuditSeverity;+ severity!: AuditSeverity;@Index()@Column({ type: 'varchar', length: 36, nullable: true })- apiKeyId: string | null;+ apiKeyId!: string | null;@Column({ type: 'varchar', length: 100, nullable: true })- apiKeyName: string | null;+ apiKeyName!: string | null;@Index()@Column({ type: 'varchar', length: 36, nullable: true })- sessionId: string | null;+ sessionId!: string | null;@Column({ type: 'varchar', length: 100, nullable: true })- sessionName: string | null;+ sessionName!: string | null;@Column({ type: 'varchar', length: 45, nullable: true })- ipAddress: string | null;+ ipAddress!: string | null;@Column({ type: 'varchar', length: 500, nullable: true })- userAgent: string | null;+ userAgent!: string | null;@Column({ type: 'varchar', length: 10, nullable: true })- method: string | null;+ method!: string | null;@Column({ type: 'varchar', length: 500, nullable: true })- path: string | null;+ path!: string | null;@Column({ type: 'int', nullable: true })- statusCode: number | null;+ statusCode!: number | null;// The "main" database connection is always SQLite (boot config),// so we use simple-json regardless of the user's data DB choice.@Column({ type: 'simple-json', nullable: true })- metadata: Record<string, unknown> | null;+ metadata!: Record<string, unknown> | null;@Column({ type: 'text', nullable: true })- errorMessage: string | null;+ errorMessage!: string | null;@Index()@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;}diff --git a/src/modules/auth/dto/api-key.dto.ts b/src/modules/auth/dto/api-key.dto.tsindex 25b3bfa64..c9f677590 100644--- a/src/modules/auth/dto/api-key.dto.ts+++ b/src/modules/auth/dto/api-key.dto.ts@@ -11,7 +11,7 @@ export class CreateApiKeyDto {@IsString()@MinLength(3)@MaxLength(100)- name: string;+ name!: string;@ApiPropertyOptional({description: 'Role/permission level',@@ -52,18 +52,18 @@ export class CreateApiKeyDto {export class ApiKeyResponseDto {@ApiProperty()- id: string;+ id!: string;@ApiProperty()- name: string;+ name!: string;@ApiProperty({description: 'First 8 characters of the key (for identification)',})- keyPrefix: string;+ keyPrefix!: string;@ApiProperty({ enum: ApiKeyRole })- role: ApiKeyRole;+ role!: ApiKeyRole;@ApiPropertyOptional()allowedIps?: string[];@@ -72,7 +72,7 @@ export class ApiKeyResponseDto {allowedSessions?: string[];@ApiProperty()- isActive: boolean;+ isActive!: boolean;@ApiPropertyOptional()expiresAt?: Date;@@ -81,10 +81,10 @@ export class ApiKeyResponseDto {lastUsedAt?: Date;@ApiProperty()- usageCount: number;+ usageCount!: number;@ApiProperty()- createdAt: Date;+ createdAt!: Date;}export class ApiKeyCreatedResponseDto extends ApiKeyResponseDto {@@ -92,7 +92,7 @@ export class ApiKeyCreatedResponseDto extends ApiKeyResponseDto {description: 'Full API key (only shown once at creation)',example: 'owa_k1_abc123...',})- apiKey: string;+ apiKey!: string;}export class UpdateApiKeyDto {diff --git a/src/modules/auth/entities/api-key.entity.ts b/src/modules/auth/entities/api-key.entity.tsindex 27469143c..fa75a1f05 100644--- a/src/modules/auth/entities/api-key.entity.ts+++ b/src/modules/auth/entities/api-key.entity.ts@@ -9,48 +9,48 @@ export enum ApiKeyRole {@Entity('api_keys')export class ApiKey {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column({ type: 'varchar', length: 100 })- name: string;+ name!: string;@Index({ unique: true })@Column({ type: 'varchar', length: 64 })- keyHash: string;+ keyHash!: string;// 12 to fit the 12-char prefix that auth.service writes (was varchar(8); harmless on the// hardcoded-SQLite `main` connection, but kept consistent with the code).@Column({ type: 'varchar', length: 12 })- keyPrefix: string;+ keyPrefix!: string;@Column({type: 'varchar',length: 20,default: ApiKeyRole.OPERATOR,})- role: ApiKeyRole;+ role!: ApiKeyRole;@Column({ type: 'simple-array', nullable: true })- allowedIps: string[] | null;+ allowedIps!: string[] | null;@Column({ type: 'simple-array', nullable: true })- allowedSessions: string[] | null;+ allowedSessions!: string[] | null;@Column({ type: 'boolean', default: true })- isActive: boolean;+ isActive!: boolean;@Column({ type: 'datetime', nullable: true })- expiresAt: Date | null;+ expiresAt!: Date | null;@Column({ type: 'datetime', nullable: true })- lastUsedAt: Date | null;+ lastUsedAt!: Date | null;@Column({ type: 'int', default: 0 })- usageCount: number;+ usageCount!: number;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/src/modules/catalog/dto/send-product.dto.ts b/src/modules/catalog/dto/send-product.dto.tsindex ed66240be..701f87b73 100644--- a/src/modules/catalog/dto/send-product.dto.ts+++ b/src/modules/catalog/dto/send-product.dto.ts@@ -5,11 +5,11 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';export class SendProductDto {@ApiProperty({ description: 'Chat to send the product card to (@c.us or @g.us).', example: '[email protected]' })@IsString()- chatId: string;+ chatId!: string;@ApiProperty({ description: 'Catalog product id to send.', example: 'product-42' })@IsString()- productId: string;+ productId!: string;@ApiPropertyOptional({ description: 'Optional body text accompanying the product card.', example: 'Back in stock!' })@IsOptional()@@ -20,7 +20,7 @@ export class SendProductDto {export class SendCatalogDto {@ApiProperty({ description: 'Chat to send the catalog to (@c.us or @g.us).', example: '[email protected]' })@IsString()- chatId: string;+ chatId!: string;@ApiPropertyOptional({description: 'Optional body text accompanying the catalog.',diff --git a/src/modules/channel/dto/create-channel.dto.ts b/src/modules/channel/dto/create-channel.dto.tsindex e60bf01f0..3971106d0 100644--- a/src/modules/channel/dto/create-channel.dto.ts+++ b/src/modules/channel/dto/create-channel.dto.ts@@ -8,7 +8,7 @@ export class CreateChannelDto {// Bounds a runaway payload rather than mirroring a protocol limit; WhatsApp's own editor stops// well short of this.@MaxLength(100)- name: string;+ name!: string;@ApiPropertyOptional({ description: 'Channel description', example: 'Release notes and downtime notices' })@IsOptional()diff --git a/src/modules/channel/dto/mute-channel.dto.ts b/src/modules/channel/dto/mute-channel.dto.tsindex 00904fbfd..ef5da2150 100644--- a/src/modules/channel/dto/mute-channel.dto.ts+++ b/src/modules/channel/dto/mute-channel.dto.ts@@ -11,5 +11,5 @@ export class MuteChannelDto {// so an unguarded `false` sent as a string would mute instead of unmuting.@ToStrictBoolean()@IsBoolean()- mute: boolean;+ mute!: boolean;}diff --git a/src/modules/channel/dto/subscribe-channel.dto.ts b/src/modules/channel/dto/subscribe-channel.dto.tsindex 00930c2f9..2b3ec0eab 100644--- a/src/modules/channel/dto/subscribe-channel.dto.ts+++ b/src/modules/channel/dto/subscribe-channel.dto.ts@@ -6,5 +6,5 @@ export class SubscribeChannelDto {@ApiProperty({ description: 'Channel invite code' })@IsString()@IsNotEmpty()- inviteCode: string;+ inviteCode!: string;}diff --git a/src/modules/contact/dto/upsert-contact.dto.ts b/src/modules/contact/dto/upsert-contact.dto.tsindex 748f3b8b7..58bcd5b07 100644--- a/src/modules/contact/dto/upsert-contact.dto.ts+++ b/src/modules/contact/dto/upsert-contact.dto.ts@@ -9,7 +9,7 @@ export class UpsertContactDto {@IsString()@MinLength(1)@MaxLength(ADDRESSBOOK_NAME_MAX_LENGTH)- firstName: string;+ firstName!: string;@ApiPropertyOptional({description: "The contact's last name. Omit for a single-name contact — WhatsApp allows those.",diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex 725b5057c..8640d72de 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -405,7 +405,9 @@ export class DockerService implements OnModuleInit {this.logger.log(`Created and started container: ${spec.name}`);return true;} catch (error) {- this.logger.error(`Failed to create service ${profile}: ${error instanceof Error ? error.message : error}`);+ this.logger.error(+ `Failed to create service ${profile}: ${error instanceof Error ? error.message : String(error)}`,+ );return false;}}diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex fd8e3a0d4..f27d06d1f 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -91,7 +91,7 @@ const EVICTION_MESSAGES: Record<ApiKeyEvictionReason, string> = {})export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect, OnModuleDestroy {@WebSocketServer()- server: Server;+ server!: Server;private logger = new Logger('EventsGateway');diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex 1cd99ccef..10b3d9166 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -37,7 +37,7 @@ export class CreateGroupDto {@IsString()@IsNotEmpty()@MaxLength(GROUP_NAME_MAX_LENGTH)- name: string;+ name!: string;@ApiProperty({description: 'Participant WhatsApp IDs (e.g. [email protected])',@@ -48,7 +48,7 @@ export class CreateGroupDto {@ArrayNotEmpty()@ArrayMaxSize(GROUP_PARTICIPANTS_MAX)@IsString({ each: true })- participants: string[];+ participants!: string[];}export class ParticipantsDto {@@ -61,7 +61,7 @@ export class ParticipantsDto {@ArrayNotEmpty()@ArrayMaxSize(GROUP_PARTICIPANTS_MAX)@IsString({ each: true })- participants: string[];+ participants!: string[];}export class GroupSubjectDto {@@ -69,7 +69,7 @@ export class GroupSubjectDto {@IsString()@IsNotEmpty()@MaxLength(GROUP_NAME_MAX_LENGTH)- subject: string;+ subject!: string;}export class GroupDescriptionDto {@@ -79,7 +79,7 @@ export class GroupDescriptionDto {})@IsString()@MaxLength(GROUP_DESCRIPTION_MAX_LENGTH)- description: string;+ description!: string;}export class JoinGroupDto {@@ -90,7 +90,7 @@ export class JoinGroupDto {@IsString()@IsNotEmpty()@MaxLength(128)- inviteCode: string;+ inviteCode!: string;}/**diff --git a/src/modules/infra/dto/import-storage.dto.ts b/src/modules/infra/dto/import-storage.dto.tsindex 353e06e5e..5f9a65b71 100644--- a/src/modules/infra/dto/import-storage.dto.ts+++ b/src/modules/infra/dto/import-storage.dto.ts@@ -10,5 +10,5 @@ export class ImportStorageDto {@ApiProperty({ description: 'Path to the tar.gz file to import (must be inside the data directory)' })@IsString()@IsNotEmpty()- filePath: string;+ filePath!: string;}diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.tsindex 8c347dfa1..442ea01cd 100644--- a/src/modules/infra/infra-config.controller.ts+++ b/src/modules/infra/infra-config.controller.ts@@ -407,7 +407,7 @@ export class InfraConfigController {removalResult.errors.push(`Failed to stop ${profile}`);}} catch (err) {- removalResult.errors.push(`Error stopping ${profile}: ${err}`);+ removalResult.errors.push(`Error stopping ${profile}: ${err instanceof Error ? err.message : String(err)}`);}}this.logger.log('Teardown result', { removalResult });diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex 0f69fbdb8..3d356630d 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -386,7 +386,12 @@ export class InfraDataController {for (const importer of TABLE_IMPORTERS) {const rows = data.tables[importer.key];if (!rows?.length) continue;- for (const row of rows) {+ for (const untypedRow of rows) {+ // `rows` was read from `data.tables[importer.key]`, so it holds exactly the row type this+ // descriptor's id/map/skip declare. That correlation is what the erased importer type+ // cannot carry, and this loop is the one place it is known — so the cast lives here rather+ // than at each of the three uses below.+ const row = untypedRow as never;const skipWarning = importer.skip?.(row);if (skipWarning != null) {warnings.push(skipWarning);@@ -396,7 +401,9 @@ export class InfraDataController {await insert(importer.sql, importer.map(row));counts[importer.key]++;} catch (err) {- warnings.push(`Failed to import ${importer.label} ${importer.id(row)}: ${err}`);+ warnings.push(+ `Failed to import ${importer.label} ${importer.id(row)}: ${err instanceof Error ? err.message : String(err)}`,+ );}}}diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex 2c42c5863..aa8bab22a 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -33,17 +33,28 @@ export interface TableImporter<K extends keyof MigrationTables = keyof Migrationskip?: (row: MigrationTables[K][number]) => string | null;}-// Registers one concrete descriptor into the union-keyed TABLE_IMPORTERS array. The return type-// widens the row-specific id/map/skip to the union of all row types; sound because the import loop-// only ever feeds a descriptor rows read from data.tables[its own key].-function defineTableImporter<K extends keyof MigrationTables>(importer: TableImporter<K>): TableImporter {+/**+ * A registered importer with its row type erased, which is what the union-keyed TABLE_IMPORTERS+ * array holds. The row-consuming members take `never` rather than the union of every row type: a+ * holder of the erased form cannot know which row type a given descriptor wants, and `never` is the+ * only parameter type that every concrete `TableImporter<K>` can be assigned to. Soundness comes+ * from the import loop, which only ever hands a descriptor rows read from `data.tables[its key]`.+ */+export type AnyTableImporter = Omit<TableImporter, 'id' | 'map' | 'skip'> & {+ id: (row: never) => string;+ map: (row: never) => unknown[];+ skip?: (row: never) => string | null;+};++// Registers one concrete descriptor into the union-keyed TABLE_IMPORTERS array.+function defineTableImporter<K extends keyof MigrationTables>(importer: TableImporter<K>): AnyTableImporter {return importer;}// Restore order is FK order: sessions first (webhooks/messages/templates/etc. reference it), the// standalone cache/DLQ tables after. The per-block comments from the former inline import blocks// live on their descriptor entries.-export const TABLE_IMPORTERS: TableImporter[] = [+export const TABLE_IMPORTERS: AnyTableImporter[] = [// Import sessions firstdefineTableImporter({key: 'sessions',diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.tsindex b18199dba..2667faf62 100644--- a/src/modules/integration/dto/instance.dto.ts+++ b/src/modules/integration/dto/instance.dto.ts@@ -14,7 +14,7 @@ export class CreateInstanceDto {})@IsString()@Matches(INSTANCE_ID_PATTERN, { message: 'instanceId must match ^[a-zA-Z0-9_-]{1,64}$' })- instanceId: string;+ instanceId!: string;@ApiPropertyOptional({description: 'Session id the instance is scoped to. Omit for all sessions.',@@ -86,31 +86,31 @@ export class UpdateInstanceDto {// integration-instance responses are otherwise opaque to generated clients.export class InstanceView {@ApiProperty({ description: 'Instance row id.' })- id: string;+ id!: string;@ApiProperty({ description: 'Plugin id this instance belongs to.' })- pluginId: string;+ pluginId!: string;@ApiProperty({ description: 'Operator-chosen instance id (unique within the plugin).' })- instanceId: string;+ instanceId!: string;@ApiPropertyOptional({description: 'Session id the instance is scoped to, or null for all sessions.',nullable: true,})- sessionScope: string | null;+ sessionScope!: string | null;@ApiProperty({description:"Ingress HMAC secret. Masked ('***') on every read; plaintext returned only once on create/regenerate-secret.",})- secret: string;+ secret!: string;@ApiPropertyOptional({description: "Provider verify-token. Masked ('***') on reads when set; plaintext on create/regenerate-secret.",nullable: true,})- verifyToken: string | null;+ verifyToken!: string | null;@ApiPropertyOptional({description:@@ -118,23 +118,23 @@ export class InstanceView {nullable: true,type: Object,})- config: Record<string, unknown> | null;+ config!: Record<string, unknown> | null;@ApiProperty({ description: 'Whether ingress is accepted and dispatch is active.' })- enabled: boolean;+ enabled!: boolean;@ApiProperty({ description: 'Creation timestamp.' })- createdAt: Date;+ createdAt!: Date;@ApiProperty({ description: 'Last update timestamp.' })- updatedAt: Date;+ updatedAt!: Date;@ApiProperty({description: 'Ingress URLs the provider posts webhook deliveries to.',type: () => IngressUrl,isArray: true,})- ingressUrls: IngressUrl[];+ ingressUrls!: IngressUrl[];}export type MintedInstance = InstanceView; // identical shape; `secret` carries the plaintext oncediff --git a/src/modules/integration/entities/conversation-mapping.entity.ts b/src/modules/integration/entities/conversation-mapping.entity.tsindex 1667330aa..78c42c4a2 100644--- a/src/modules/integration/entities/conversation-mapping.entity.ts+++ b/src/modules/integration/entities/conversation-mapping.entity.ts@@ -10,29 +10,29 @@ export type HandoverState = 'bot' | 'human' | 'closed';@Index('UQ_conversation_mappings_reverse', ['pluginId', 'instanceId', 'providerConversationId'], { unique: true })export class ConversationMapping {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column()- sessionId: string;+ sessionId!: string;@Column()- chatId: string;+ chatId!: string;@Column()- pluginId: string;+ pluginId!: string;@Column()- instanceId: string;+ instanceId!: string;@Column()- providerConversationId: string;+ providerConversationId!: string;@Column({ default: 'bot' })- handoverState: HandoverState;+ handoverState!: HandoverState;@Column({ type: jsonColumnType(), nullable: true })- metadata: Record<string, unknown> | null;+ metadata!: Record<string, unknown> | null;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/src/modules/integration/entities/ingress-event.entity.ts b/src/modules/integration/entities/ingress-event.entity.tsindex 06faac1bf..c5c80e5cf 100644--- a/src/modules/integration/entities/ingress-event.entity.ts+++ b/src/modules/integration/entities/ingress-event.entity.ts@@ -32,50 +32,50 @@ export class IngressEvent {// Host-minted uuid (crypto.randomUUID()), NOT DB-generated — the id and the jobId (= deliveryId)// are decoupled on purpose. @PrimaryColumn, not @PrimaryGeneratedColumn.@PrimaryColumn()- id: string;+ id!: string;@Column()- instanceId: string;+ instanceId!: string;@Column()- pluginId: string;+ pluginId!: string;@Column()- providerDeliveryId: string;+ providerDeliveryId!: string;@Column()- route: string;+ route!: string;// NULL once the dispatch outcome is recorded (see the storage-shape comment above). The reconciler// only replays 'pending' rows, which always still carry the payload. NULL on a 'pending' row is// unreadable history (e.g. imported without one) — the reconciler skips it loudly.@Column({ type: jsonColumnType(), nullable: true })- payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string } | null;+ payload!: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string } | null;// sha256 hex of the rawBody, written at recordOrSkip. Survives payload retirement so operators can// still correlate a dedup row with a provider delivery without storing the payload. NULL on rows// that predate the column (no backfill — their payloads are retired anyway).@Column({ type: 'varchar', nullable: true })- payloadHash: string | null;+ payloadHash!: string | null;@Column({ type: 'varchar', nullable: true })- sessionId: string | null;+ sessionId!: string | null;// Nullable by design (see the IngressDispatchState comment above): NO DB default, because the// default 'pending' would also stamp pre-upgrade rows on the synchronize path and the reconciler// would replay the whole dedup log on deploy. New rows are 'pending' via recordOrSkip explicitly;// migration-managed DBs backfill existing rows to 'dispatched' instead.@Column({ type: 'varchar', nullable: true })- dispatchState: IngressDispatchState | null;+ dispatchState!: IngressDispatchState | null;// Dispatch-attempt counter the reconciler caps its replay budget against; the live path bumps it// on a swallowed inline-dispatch failure so those retries count too.@Column({ type: 'int', default: 0 })- dispatchAttempts: number;+ dispatchAttempts!: number;@Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })- lastDispatchAt: Date | null;+ lastDispatchAt!: Date | null;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;}diff --git a/src/modules/integration/entities/integration-delivery-failure.entity.ts b/src/modules/integration/entities/integration-delivery-failure.entity.tsindex 80e7e2630..fdb08014c 100644--- a/src/modules/integration/entities/integration-delivery-failure.entity.ts+++ b/src/modules/integration/entities/integration-delivery-failure.entity.ts@@ -7,35 +7,35 @@ import { jsonColumnType } from '../../../common/utils/column-types';@Index('IDX_integration_delivery_failures_instance', ['pluginId', 'instanceId'])export class IntegrationDeliveryFailure {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column()- direction: 'inbound' | 'outbound';+ direction!: 'inbound' | 'outbound';@Column()- pluginId: string;+ pluginId!: string;@Column()- instanceId: string;+ instanceId!: string;@Column({ type: 'varchar', nullable: true })- sessionId: string | null;+ sessionId!: string | null;@Column({ type: 'varchar', nullable: true })- deliveryId: string | null;+ deliveryId!: string | null;@Column({ type: 'int' })- attempts: number;+ attempts!: number;@Column({ type: 'text' })- lastError: string;+ lastError!: string;@Column({ type: jsonColumnType(), nullable: true })- payload: Record<string, unknown> | null;+ payload!: Record<string, unknown> | null;@Column({ default: false })- redriven: boolean;+ redriven!: boolean;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;}diff --git a/src/modules/integration/entities/plugin-instance.entity.ts b/src/modules/integration/entities/plugin-instance.entity.tsindex eb999170e..2165e7598 100644--- a/src/modules/integration/entities/plugin-instance.entity.ts+++ b/src/modules/integration/entities/plugin-instance.entity.ts@@ -7,34 +7,34 @@ import { jsonColumnType } from '../../../common/utils/column-types';@Index('UQ_plugin_instances_plugin_instance', ['pluginId', 'instanceId'], { unique: true })export class PluginInstance {@PrimaryColumn()- id: string; // `${pluginId}:${instanceId}`+ id!: string; // `${pluginId}:${instanceId}`@Column()- pluginId: string;+ pluginId!: string;@Column()- instanceId: string;+ instanceId!: string;@Column({ type: 'varchar', nullable: true })- sessionScope: string | null; // resolved session id this instance acts on; null = inherit manifest.sessions+ sessionScope!: string | null; // resolved session id this instance acts on; null = inherit manifest.sessions@Column()- secret: string; // host-minted ingress HMAC secret; stored plaintext, masked to '***' on API reads+ secret!: string; // host-minted ingress HMAC secret; stored plaintext, masked to '***' on API reads// (via PluginInstanceService.maskedView + the provisioning controller's reveal flag), exposed// in full only on mint and regenerate-secret. Note: instance `config` is NOT secret-redacted.@Column({ type: 'varchar', nullable: true })- verifyToken: string | null; // optional provider challenge token+ verifyToken!: string | null; // optional provider challenge token@Column({ type: jsonColumnType(), nullable: true })- config: Record<string, unknown> | null;+ config!: Record<string, unknown> | null;@Column({ default: true })- enabled: boolean;+ enabled!: boolean;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/src/modules/integration/ingress-url.ts b/src/modules/integration/ingress-url.tsindex 1603ee79e..9b4916b42 100644--- a/src/modules/integration/ingress-url.ts+++ b/src/modules/integration/ingress-url.ts@@ -2,12 +2,12 @@ import { ApiProperty } from '@nestjs/swagger';export class IngressUrl {@ApiProperty({ description: 'Plugin-declared route segment the provider posts to.' })- route: string;+ route!: string;@ApiProperty({description: 'Full ingress URL (BASE_URL + plugin/instance/route), or a relative path when BASE_URL is unset.',})- url: string;+ url!: string;}// Absolute URL from BASE_URL when set (trailing slash trimmed), else a relative path the operatordiff --git a/src/modules/label/dto/add-label.dto.ts b/src/modules/label/dto/add-label.dto.tsindex 20731b37d..acafd4eef 100644--- a/src/modules/label/dto/add-label.dto.ts+++ b/src/modules/label/dto/add-label.dto.ts@@ -6,5 +6,5 @@ export class AddLabelDto {@ApiProperty({ description: 'Label ID to add to the chat' })@IsString()@IsNotEmpty()- labelId: string;+ labelId!: string;}diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex aa5efc372..b27d1ec5f 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -1,6 +1,7 @@import { ForbiddenException, HttpException, Logger, UnauthorizedException } from '@nestjs/common';import type { HttpAdapterHost } from '@nestjs/core';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import type { AnySchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';@@ -106,8 +107,10 @@ function buildServer(tool.name,{description: tool.description,- // inputSchema accepts AnySchema (zod v4 $ZodType is compatible)- inputSchema: tool.inputSchema as Parameters<typeof server.registerTool>[1]['inputSchema'],+ // The SDK's InputArgs is inferred from this property. Widening it to the whole+ // `ZodRawShapeCompat | AnySchema` constraint would collapse the callback type it derives, so+ // the cast names AnySchema exactly — which zod v4's $ZodType satisfies.+ inputSchema: tool.inputSchema as AnySchema,annotations: {readOnlyHint: tool.tier === 'read',destructiveHint: tool.destructive ?? false,diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.tsindex ebf9eb9ac..790c4259a 100644--- a/src/modules/message/dto/bulk-message.dto.ts+++ b/src/modules/message/dto/bulk-message.dto.ts@@ -88,16 +88,16 @@ class BulkMessageContentDto {class BulkMessageItemDto {@ApiProperty({ description: 'Recipient chat ID', example: '[email protected]' })@IsString()- chatId: string;+ chatId!: string;@ApiProperty({ description: 'Message type', enum: ['text', 'image', 'video', 'audio', 'document'] })@IsIn(['text', 'image', 'video', 'audio', 'document'])- type: 'text' | 'image' | 'video' | 'audio' | 'document';+ type!: 'text' | 'image' | 'video' | 'audio' | 'document';@ApiProperty({ description: 'Message content based on type' })@ValidateNested()@Type(() => BulkMessageContentDto)- content: BulkMessageContentDto;+ content!: BulkMessageContentDto;@ApiPropertyOptional({ description: 'Variables for template substitution' })@IsOptional()@@ -141,7 +141,7 @@ export class SendBulkMessageDto {@ArrayMaxSize(100)@ValidateNested({ each: true })@Type(() => BulkMessageItemDto)- messages: BulkMessageItemDto[];+ messages!: BulkMessageItemDto[];@ApiPropertyOptional({ description: 'Batch processing options' })@IsOptional()@@ -152,17 +152,17 @@ export class SendBulkMessageDto {export class BulkMessageResponseDto {@ApiProperty()- batchId: string;+ batchId!: string;@ApiProperty()- status: string;+ status!: string;@ApiProperty()- totalMessages: number;+ totalMessages!: number;@ApiPropertyOptional()estimatedCompletionTime?: string;@ApiProperty()- statusUrl: string;+ statusUrl!: string;}diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex 08581c942..f94a1e0b3 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -32,17 +32,17 @@ export class SendLocationDto {@ApiProperty({ description: 'Chat ID (e.g. [email protected])' })@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty({ example: -6.2088 })@ToStrictNumber()@IsLatitude()- latitude: number;+ latitude!: number;@ApiProperty({ example: 106.8456 })@ToStrictNumber()@IsLongitude()- longitude: number;+ longitude!: number;@ApiPropertyOptional({ maxLength: LOCATION_TEXT_MAX_LENGTH })@IsOptional()@@ -61,32 +61,32 @@ export class SendContactDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty({ maxLength: CONTACT_NAME_MAX_LENGTH })@IsString()@IsNotEmpty()@MaxLength(CONTACT_NAME_MAX_LENGTH)- contactName: string;+ contactName!: string;@ApiProperty({ maxLength: CONTACT_NUMBER_MAX_LENGTH })@IsString()@IsNotEmpty()@MaxLength(CONTACT_NUMBER_MAX_LENGTH)- contactNumber: string;+ contactNumber!: string;}export class SendPollDto {@ApiProperty({ description: 'Chat ID (e.g. [email protected] or [email protected])' })@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty({ description: 'Poll question / title', maxLength: 255, example: 'Where should we meet?' })@IsString()@IsNotEmpty()@MaxLength(255)- name: string;+ name!: string;// WhatsApp itself caps polls at 12 options and ~100 chars per option; validating here keeps the// failure a clean 400 instead of an engine error deep in the send path.@@ -101,7 +101,7 @@ export class SendPollDto {@IsString({ each: true })@IsNotEmpty({ each: true })@MaxLength(100, { each: true })- options: string[];+ options!: string[];@ApiPropertyOptional({ description: 'Allow voters to pick several options (default single choice)' })// Read strictly for the same reason as DeleteMessageDto.forEveryone: without it the pipe's@@ -117,48 +117,48 @@ export class ReplyMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- quotedMessageId: string;+ quotedMessageId!: string;// Same body cap as SendTextMessageDto.text — a reply cannot exceed what a send allows.@ApiProperty({ maxLength: MESSAGE_TEXT_MAX_LENGTH })@IsString()@IsNotEmpty()@MaxLength(MESSAGE_TEXT_MAX_LENGTH)- text: string;+ text!: string;}export class ForwardMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- fromChatId: string;+ fromChatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- toChatId: string;+ toChatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;}export class ReactMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;// Empty string is VALID — it removes the reaction (endpoint contract). So @IsString, not @IsNotEmpty.@ApiProperty({@@ -167,19 +167,19 @@ export class ReactMessageDto {})@IsString()@MaxLength(REACTION_EMOJI_MAX_LENGTH)- emoji: string;+ emoji!: string;}export class DeleteMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;@ApiPropertyOptional({ description: 'Delete for everyone (default true)' })// The field's only purpose is to say "no, delete locally" — the default is already true@@ -203,12 +203,12 @@ export class PinMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;@ApiPropertyOptional({description: 'Pin duration in seconds: 86400 (24h), 604800 (7d) or 2592000 (30d). Defaults to 24h.',@@ -231,12 +231,12 @@ export class VotePollDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty({ description: 'The poll creation message to vote on.' })@IsString()@IsNotEmpty()- pollMessageId: string;+ pollMessageId!: string;@ApiProperty({description:@@ -248,55 +248,55 @@ export class VotePollDto {@IsArray()@ArrayMaxSize(POLL_VOTE_MAX_OPTIONS)@IsString({ each: true })- options: string[];+ options!: string[];}export class StarMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;@ApiProperty({ description: 'true to star, false to remove the star.' })// Read strictly for the same reason as DeleteMessageDto.forEveryone: implicit conversion would// turn the string "false" into boolean true, silently inverting the caller's intent.@ToStrictBoolean()@IsBoolean()- star: boolean;+ star!: boolean;}export class UnpinMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;}export class EditMessageDto {@ApiProperty()@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty()@IsString()@IsNotEmpty()- messageId: string;+ messageId!: string;// Same body cap as SendTextMessageDto.text — an edit cannot exceed what a send allows.@ApiProperty({ description: 'New text body for the message', maxLength: 4096 })@IsString()@IsNotEmpty()@MaxLength(4096)- body: string;+ body!: string;}diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 9ebdfbb55..37409a0b9 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -29,7 +29,7 @@ export class CustomLinkPreviewDto {@IsString()@IsNotEmpty()@MaxLength(2048)- url: string;+ url!: string;@ApiProperty({description: 'Required: WhatsApp will not render a preview without a title.',@@ -39,7 +39,7 @@ export class CustomLinkPreviewDto {@IsString()@IsNotEmpty()@MaxLength(256)- title: string;+ title!: string;@ApiPropertyOptional({ description: 'Preview description', example: 'Read the announcement.', maxLength: 1024 })@IsOptional()@@ -55,7 +55,7 @@ export class SendTextMessageDto {})@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty({description: 'Text message content',@@ -65,7 +65,7 @@ export class SendTextMessageDto {@IsString()@IsNotEmpty()@MaxLength(MESSAGE_TEXT_MAX_LENGTH)- text: string;+ text!: string;@ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })@IsOptional()@@ -111,7 +111,7 @@ export class SendMediaMessageDto {})@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiPropertyOptional({description: 'Media URL (http/https)',@@ -194,11 +194,11 @@ export class MessageResponseDto {'not come online since the send stays at `sent` too.',example: '[email protected]_3EB0123456789',})- messageId: string;+ messageId!: string;@ApiProperty({description: 'Unix timestamp (seconds) at which the gateway accepted the message for sending.',example: 1706868000,})- timestamp: number;+ timestamp!: number;}diff --git a/src/modules/message/dto/send-template.dto.ts b/src/modules/message/dto/send-template.dto.tsindex 14b6c56c3..1a6b0ebb3 100644--- a/src/modules/message/dto/send-template.dto.ts+++ b/src/modules/message/dto/send-template.dto.ts@@ -8,7 +8,7 @@ export class SendTemplateMessageDto {})@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiPropertyOptional({description: 'Template ID to render. Provide either templateId or templateName.',diff --git a/src/modules/message/entities/message-batch.entity.ts b/src/modules/message/entities/message-batch.entity.tsindex 0210552cf..5f697ad16 100644--- a/src/modules/message/entities/message-batch.entity.ts+++ b/src/modules/message/entities/message-batch.entity.ts@@ -42,19 +42,19 @@ export interface BatchProgress {@Unique('UQ_message_batches_session_id_batch_id', ['sessionId', 'batchId'])export class MessageBatch {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column({ name: 'batch_id' })- batchId: string;+ batchId!: string;@Column({ name: 'session_id' })- sessionId: string;+ sessionId!: string;@Column({ type: 'varchar', default: BatchStatus.PENDING })- status: BatchStatus;+ status!: BatchStatus;@Column({ type: jsonColumnType() })- messages: Array<{+ messages!: Array<{chatId: string;type: string;content: Record<string, unknown>;@@ -62,30 +62,30 @@ export class MessageBatch {}>;@Column({ type: jsonColumnType(), nullable: true })- options: {+ options!: {delayBetweenMessages: number;randomizeDelay: boolean;stopOnError: boolean;};@Column({ type: jsonColumnType(), nullable: true })- progress: BatchProgress;+ progress!: BatchProgress;@Column({ type: jsonColumnType(), nullable: true })- results: BatchMessageResult[];+ results!: BatchMessageResult[];@Column({ name: 'current_index', default: 0 })- currentIndex: number;+ currentIndex!: number;@CreateDateColumn({ name: 'created_at' })- createdAt: Date;+ createdAt!: Date;@UpdateDateColumn({ name: 'updated_at' })- updatedAt: Date;+ updatedAt!: Date;@Column({ name: 'started_at', type: dateColumnType(), nullable: true, transformer: DateTransformer })- startedAt: Date | null;+ startedAt!: Date | null;@Column({ name: 'completed_at', type: dateColumnType(), nullable: true, transformer: DateTransformer })- completedAt: Date | null;+ completedAt!: Date | null;}diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex 07d4daaaf..492bdced6 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -39,18 +39,18 @@ export enum MessageStatus {@Index('UQ_messages_sessionId_waMessageId', ['sessionId', 'waMessageId'], { unique: true })export class Message {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;// No standalone @Index here: sessionId-only lookups are already served by the composite indexes// that lead with sessionId — (sessionId, createdAt) above and the unique (sessionId, waMessageId).@Column()- sessionId: string;+ sessionId!: string;@Column({ nullable: true })- waMessageId: string;+ waMessageId!: string;@Column()- chatId: string;+ chatId!: string;/** Human-readable name for the chat (contact pushName, group name, etc). Populated on save when available — null for legacy rows. */@Column({ nullable: true })@@ -65,28 +65,28 @@ export class Message {author?: string;@Column()- from: string;+ from!: string;@Column()- to: string;+ to!: string;@Column({ type: 'text', nullable: true })- body: string;+ body!: string;@Column({ default: 'text' })- type: string;+ type!: string;@Column({type: 'varchar',default: MessageDirection.OUTGOING,})- direction: MessageDirection;+ direction!: MessageDirection;@Column({ type: 'bigint', nullable: true, transformer: bigintToNumberTransformer })- timestamp: number;+ timestamp!: number;@Column({ type: jsonColumnType(), nullable: true })- metadata: Record<string, unknown>;+ metadata!: Record<string, unknown>;/*** Storage key of this message's archived media, or null when nothing was archived — which is the@@ -107,7 +107,7 @@ export class Message {default: MessageStatus.SENT,})@Index()- status: MessageStatus;+ status!: MessageStatus;// Standalone index for the createdAt-only range predicates of the stats aggregates — the// composite above leads with sessionId, so it can't serve them (SQLite needs ANALYZE stats for@@ -115,5 +115,5 @@ export class Message {// synchronize-disabled deployments, so both schema paths converge on one index.@CreateDateColumn()@Index('IDX_messages_createdAt')- createdAt: Date;+ createdAt!: Date;}diff --git a/src/modules/profile/dto/profile.dto.ts b/src/modules/profile/dto/profile.dto.tsindex f1bae075e..3e0cf296c 100644--- a/src/modules/profile/dto/profile.dto.ts+++ b/src/modules/profile/dto/profile.dto.ts@@ -6,7 +6,7 @@ export class SetProfileNameDto {@IsString()@IsNotEmpty()@MaxLength(25)- name: string;+ name!: string;}export class SetProfileStatusDto {@@ -16,7 +16,7 @@ export class SetProfileStatusDto {})@IsString()@MaxLength(139)- status: string;+ status!: string;}/**diff --git a/src/modules/search/dto/search-query.dto.ts b/src/modules/search/dto/search-query.dto.tsindex ebd936a83..7af5e9839 100644--- a/src/modules/search/dto/search-query.dto.ts+++ b/src/modules/search/dto/search-query.dto.ts@@ -16,7 +16,7 @@ export class SearchQueryDto {@ApiProperty({ description: 'Search term (required, non-empty)' })@IsString()@IsNotEmpty()- q: string;+ q!: string;@ApiPropertyOptional({ description: 'Restrict to a single session' })@IsOptional()diff --git a/src/modules/session/dto/archive-chat.dto.ts b/src/modules/session/dto/archive-chat.dto.tsindex a7c88211f..0f3e8b2f3 100644--- a/src/modules/session/dto/archive-chat.dto.ts+++ b/src/modules/session/dto/archive-chat.dto.ts@@ -14,12 +14,12 @@ export class ArchiveChatDto {@Matches(/^[^\s@]+@[^\s@]+$/, {message: 'chatId must be a valid chat JID in the form localpart@host',})- chatId: string;+ chatId!: string;@ApiProperty({ description: 'true to archive, false to unarchive.' })// Read strictly: under the pipe's implicit conversion the string "false" would become boolean// true, archiving a chat the caller asked to restore.@ToStrictBoolean()@IsBoolean()- archive: boolean;+ archive!: boolean;}diff --git a/src/modules/session/dto/create-session.dto.ts b/src/modules/session/dto/create-session.dto.tsindex 063c4f281..fc49daa58 100644--- a/src/modules/session/dto/create-session.dto.ts+++ b/src/modules/session/dto/create-session.dto.ts@@ -14,7 +14,7 @@ export class CreateSessionDto {@Matches(/^[a-zA-Z0-9-]+$/, {message: 'Session name can only contain letters, numbers, and hyphens',})- name: string;+ name!: string;@ApiPropertyOptional({description:diff --git a/src/modules/session/dto/delete-chat.dto.ts b/src/modules/session/dto/delete-chat.dto.tsindex 250ab7d78..b561eee9c 100644--- a/src/modules/session/dto/delete-chat.dto.ts+++ b/src/modules/session/dto/delete-chat.dto.ts@@ -13,5 +13,5 @@ export class DeleteChatDto {@Matches(/^[^\s@]+@[^\s@]+$/, {message: 'chatId must be a valid chat JID in the form localpart@host',})- chatId: string;+ chatId!: string;}diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.tsindex b7ae660c8..08511923e 100644--- a/src/modules/session/dto/mark-chat-read.dto.ts+++ b/src/modules/session/dto/mark-chat-read.dto.ts@@ -14,5 +14,5 @@ export class MarkChatReadDto {@Matches(/^[^\s@]+@[^\s@]+$/, {message: 'chatId must be a valid chat JID in the form localpart@host',})- chatId: string;+ chatId!: string;}diff --git a/src/modules/session/dto/presence.dto.ts b/src/modules/session/dto/presence.dto.tsindex 84fb4ca6f..087cc9057 100644--- a/src/modules/session/dto/presence.dto.ts+++ b/src/modules/session/dto/presence.dto.ts@@ -13,12 +13,12 @@ export class SubscribePresenceDto {@Matches(/^[^\s@]+@[^\s@]+$/, {message: 'chatId must be a valid chat JID in the form localpart@host',})- chatId: string;+ chatId!: string;}export class ParticipantPresenceDto {@ApiProperty({ description: 'Participant id. In a 1:1 chat this is the chat itself.', example: '[email protected]' })- id: string;+ id!: string;@ApiProperty({enum: ['available', 'unavailable', 'composing', 'recording', 'paused'],@@ -27,7 +27,7 @@ export class ParticipantPresenceDto {'they stopped without sending. `available`/`unavailable` describe reachability.',example: 'composing',})- state: string;+ state!: string;@ApiPropertyOptional({type: Number,@@ -41,10 +41,10 @@ export class ParticipantPresenceDto {export class ChatPresenceResponseDto {@ApiProperty({ example: '[email protected]' })- chatId: string;+ chatId!: string;@ApiProperty({ type: [ParticipantPresenceDto] })- participants: ParticipantPresenceDto[];+ participants!: ParticipantPresenceDto[];@ApiPropertyOptional({ type: Number, description: 'Online member count, groups only.', example: 3 })groupOnlineCount?: number;@@ -57,5 +57,5 @@ export class ChatPresenceResponseDto {'an old `observedAt` means the state is stale rather than steady.',example: '2026-08-03T12:00:00Z',})- observedAt: Date;+ observedAt!: Date;}diff --git a/src/modules/session/dto/request-pairing-code.dto.ts b/src/modules/session/dto/request-pairing-code.dto.tsindex bff9b7226..23d460355 100644--- a/src/modules/session/dto/request-pairing-code.dto.ts+++ b/src/modules/session/dto/request-pairing-code.dto.ts@@ -12,13 +12,13 @@ export class RequestPairingCodeDto {@Matches(/^[0-9]{6,15}$/, {message: 'phoneNumber must be digits only in international format (country code + number), e.g. 628123456789',})- phoneNumber: string;+ phoneNumber!: string;}export class PairingCodeResponseDto {@ApiProperty({ description: 'The 8-character pairing code to enter in WhatsApp.', example: 'ABCD1234' })- pairingCode: string;+ pairingCode!: string;@ApiProperty({ description: 'Current session status.', example: 'qr_ready' })- status: string;+ status!: string;}diff --git a/src/modules/session/dto/send-chat-state.dto.ts b/src/modules/session/dto/send-chat-state.dto.tsindex e7259e63b..0c3036fc9 100644--- a/src/modules/session/dto/send-chat-state.dto.ts+++ b/src/modules/session/dto/send-chat-state.dto.ts@@ -12,7 +12,7 @@ export class SendChatStateDto {})@IsString()@IsNotEmpty()- chatId: string;+ chatId!: string;@ApiProperty({description: "Presence to send: 'typing' or 'recording' shows the indicator; 'paused' clears it",@@ -20,5 +20,5 @@ export class SendChatStateDto {example: 'typing',})@IsIn(['typing', 'recording', 'paused'])- state: ChatState;+ state!: ChatState;}diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 48fd3e164..b38013688 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -12,7 +12,7 @@ export class AccountRestrictionDto {'seeing either alongside a `ready` status is not possible.',example: 'reachout_timelock',})- kind: 'reachout_timelock' | 'tos_block' | 'proxy_block';+ kind!: 'reachout_timelock' | 'tos_block' | 'proxy_block';@ApiProperty({description:@@ -20,7 +20,7 @@ export class AccountRestrictionDto {'so a value newer than this gateway is still surfaced rather than flattened.',example: 'BIZ_QUALITY',})- code: string;+ code!: string;@ApiPropertyOptional({type: String,@@ -36,13 +36,13 @@ export class AccountRestrictionDto {export class SessionResponseDto {@ApiProperty({ example: 'sess_123e4567-e89b-12d3-a456-426614174000' })- id: string;+ id!: string;@ApiProperty({ example: 'my-bot' })- name: string;+ name!: string;@ApiProperty({ enum: SessionStatus, example: SessionStatus.READY })- status: SessionStatus;+ status!: SessionStatus;@ApiPropertyOptional({ type: String, example: '628123456789', nullable: true })phone?: string | null;@@ -57,10 +57,10 @@ export class SessionResponseDto {lastActive?: Date | null;@ApiProperty({ example: '2025-02-02T09:00:00Z' })- createdAt: Date;+ createdAt!: Date;@ApiProperty({ example: '2025-02-02T10:00:00Z' })- updatedAt: Date;+ updatedAt!: Date;@ApiPropertyOptional({type: String,@@ -92,7 +92,7 @@ export class SessionResponseDto {'Derived per request from live process state, so it is never persisted and never historical.',example: true,})- engineLoaded: boolean;+ engineLoaded!: boolean;/*** Map a Session entity to the public response shape, stripping sensitive@@ -135,8 +135,8 @@ export class QRCodeResponseDto {description: 'QR code as data URL',example: 'data:image/png;base64,...',})- qrCode: string;+ qrCode!: string;@ApiProperty({ enum: SessionStatus, example: SessionStatus.QR_READY })- status: SessionStatus;+ status!: SessionStatus;}diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.tsindex 09cf863a7..df21ab905 100644--- a/src/modules/session/entities/session.entity.ts+++ b/src/modules/session/entities/session.entity.ts@@ -17,45 +17,45 @@ export enum SessionStatus {@Entity('sessions')export class Session {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column({ type: 'varchar', length: 100, unique: true })- name: string;+ name!: string;@Column({type: 'varchar',length: 50,default: SessionStatus.CREATED,})- status: SessionStatus;+ status!: SessionStatus;@Column({ type: 'varchar', length: 20, nullable: true })- phone: string | null;+ phone!: string | null;@Column({ type: 'varchar', length: 100, nullable: true })- pushName: string | null;+ pushName!: string | null;@Column({ type: jsonColumnType(), default: '{}' })- config: Record<string, unknown>;+ config!: Record<string, unknown>;// Phase 3: Proxy per session@Column({ type: 'varchar', length: 255, nullable: true })- proxyUrl: string | null;+ proxyUrl!: string | null;@Column({ type: 'varchar', length: 10, nullable: true })- proxyType: 'http' | 'https' | 'socks4' | 'socks5' | null;+ proxyType!: 'http' | 'https' | 'socks4' | 'socks5' | null;@Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })- connectedAt: Date | null;+ connectedAt!: Date | null;@Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })- lastActiveAt: Date | null;+ lastActiveAt!: Date | null;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;/*** Transient (non-persisted) human-readable reason for the most recent terminaldiff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex 544bdee7c..4d5f6f2fe 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -1,7 +1,7 @@import * as fs from 'fs';import * as os from 'os';import * as path from 'path';-import { DataSource, Repository } from 'typeorm';+import { DataSource, DeepPartial, Repository } from 'typeorm';import { ConfigService } from '@nestjs/config';jest.mock('archiver', () => ({ default: jest.fn() }));@@ -233,10 +233,10 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {// from an unexplained omission — and nothing retries it.const saveSpy = jest.spyOn(repository, 'save');let calls = 0;- saveSpy.mockImplementation((row: never) => {+ saveSpy.mockImplementation((row: DeepPartial<StatusUpdate>) => {calls += 1;if (calls === 2) return Promise.reject(new Error('db blip')); // the post-write update- return Promise.resolve(row);+ return Promise.resolve(row as DeepPartial<StatusUpdate> & StatusUpdate);});try {const { row } = await service.ingest('sess', {diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.tsindex c634017e6..76513d21b 100644--- a/src/modules/status/dto/send-media-status.dto.ts+++ b/src/modules/status/dto/send-media-status.dto.ts@@ -43,7 +43,7 @@ export class SendImageStatusDto {@IsDefined()@ValidateNested()@Type(() => StatusMediaInput)- image: StatusMediaInput;+ image!: StatusMediaInput;@ApiPropertyOptional({ description: 'Optional caption.', example: 'New drop!', maxLength: 1024 })@IsOptional()@@ -74,7 +74,7 @@ export class SendVideoStatusDto {@IsDefined()@ValidateNested()@Type(() => StatusMediaInput)- video: StatusMediaInput;+ video!: StatusMediaInput;@ApiPropertyOptional({ description: 'Optional caption.', example: 'Demo', maxLength: 1024 })@IsOptional()diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.tsindex d613fba93..e47c12b78 100644--- a/src/modules/status/dto/send-text-status.dto.ts+++ b/src/modules/status/dto/send-text-status.dto.ts@@ -6,7 +6,7 @@ export class SendTextStatusDto {@ApiProperty({ description: 'Status text body.', example: 'Out for delivery 📦', maxLength: 4096 })@IsString()@MaxLength(4096)- text: string;+ text!: string;@ApiPropertyOptional({ description: 'Background color (hex).', example: '#25D366' })@IsOptional()diff --git a/src/modules/template/dto/template.dto.ts b/src/modules/template/dto/template.dto.tsindex 2f4f5d195..39d3154be 100644--- a/src/modules/template/dto/template.dto.ts+++ b/src/modules/template/dto/template.dto.ts@@ -14,7 +14,7 @@ export class CreateTemplateDto {@IsString()@IsNotEmpty()@MaxLength(NAME_MAX_LENGTH)- name: string;+ name!: string;@ApiProperty({description: 'Template body with {{variable}} placeholders',@@ -24,7 +24,7 @@ export class CreateTemplateDto {@IsString()@IsNotEmpty()@MaxLength(BODY_MAX_LENGTH)- body: string;+ body!: string;@ApiPropertyOptional({description: 'Optional header text, prepended to the rendered body',@@ -77,16 +77,16 @@ export class UpdateTemplateDto {export class TemplateResponseDto {@ApiProperty()- id: string;+ id!: string;@ApiProperty()- sessionId: string;+ sessionId!: string;@ApiProperty()- name: string;+ name!: string;@ApiProperty()- body: string;+ body!: string;@ApiPropertyOptional({ type: String, nullable: true })header?: string | null;@@ -95,8 +95,8 @@ export class TemplateResponseDto {footer?: string | null;@ApiProperty()- createdAt: Date;+ createdAt!: Date;@ApiProperty()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/src/modules/template/entities/template.entity.ts b/src/modules/template/entities/template.entity.tsindex 96adc6bf3..605b71e81 100644--- a/src/modules/template/entities/template.entity.ts+++ b/src/modules/template/entities/template.entity.ts@@ -16,32 +16,32 @@ import { Session } from '../../session/entities/session.entity';@Entity('templates')export class Template {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;// varchar (not uuid) to match the authoritative migration DDL and sessions.id; the data connection// runs synchronize:false, so a 'uuid' decorator here would only mislead schema diffs / a stray sync.@Column({ type: 'varchar' })- sessionId: string;+ sessionId!: string;@ManyToOne(() => Session, { onDelete: 'CASCADE' })@JoinColumn({ name: 'sessionId' })- session: Session;+ session!: Session;@Column({ type: 'varchar', length: 100 })- name: string;+ name!: string;@Column({ type: 'text' })- body: string;+ body!: string;@Column({ type: 'text', nullable: true })- header: string | null;+ header!: string | null;@Column({ type: 'text', nullable: true })- footer: string | null;+ footer!: string | null;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 8a8d1a71a..f84675d7a 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -70,7 +70,7 @@ export class CreateWebhookDto {// require_tld:false allows hostnames without a dot (e.g. http://localhost:3000); the SSRF// guard still decides whether the host is actually allowed to be delivered to.@IsUrl({ require_tld: false })- url: string;+ url!: string;@ApiPropertyOptional({description: "Event types to subscribe to. '*' subscribes to all events.",@@ -185,19 +185,19 @@ export class UpdateWebhookDto {export class WebhookResponseDto {@Expose()@ApiProperty()- id: string;+ id!: string;@Expose()@ApiProperty()- sessionId: string;+ sessionId!: string;@Expose()@ApiProperty()- url: string;+ url!: string;@Expose()@ApiProperty()- events: string[];+ events!: string[];@Expose()@ApiPropertyOptional({ description: FILTERS_API_DESCRIPTION, example: FILTERS_API_EXAMPLE })@@ -205,11 +205,11 @@ export class WebhookResponseDto {@Expose()@ApiProperty()- active: boolean;+ active!: boolean;@Expose()@ApiProperty()- retryCount: number;+ retryCount!: number;@Expose()@ApiPropertyOptional()@@ -217,11 +217,11 @@ export class WebhookResponseDto {@Expose()@ApiProperty()- createdAt: Date;+ createdAt!: Date;@Expose()@ApiProperty()- updatedAt: Date;+ updatedAt!: Date;static fromEntity(entity: Webhook): WebhookResponseDto {return plainToInstance(WebhookResponseDto, entity, { excludeExtraneousValues: true });diff --git a/src/modules/webhook/entities/webhook-delivery-failure.entity.ts b/src/modules/webhook/entities/webhook-delivery-failure.entity.tsindex 8ef6be0d1..0d0d0bab2 100644--- a/src/modules/webhook/entities/webhook-delivery-failure.entity.ts+++ b/src/modules/webhook/entities/webhook-delivery-failure.entity.ts@@ -13,39 +13,39 @@ import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from@Index('IDX_webhook_delivery_failures_sessionId', ['sessionId'])export class WebhookDeliveryFailure {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;@Column()- webhookId: string;+ webhookId!: string;@Column()- sessionId: string;+ sessionId!: string;@Column()- event: string;+ event!: string;@Column()- url: string;+ url!: string;/** The idempotency key the receiver would have deduped on (lets an operator correlate the lost event). */@Column({ nullable: true })- idempotencyKey: string;+ idempotencyKey!: string;@Column({ nullable: true })- deliveryId: string;+ deliveryId!: string;/** Total attempts made before giving up. */@Column({ type: 'int' })- attempts: number;+ attempts!: number;/** Last HTTP status, when the failure was a non-2xx response (null for a network/timeout/SSRF error). */@Column({ type: 'int', nullable: true })- lastStatusCode: number | null;+ lastStatusCode!: number | null;@Column({ type: 'text' })- lastError: string;+ lastError!: string;/** When the delivery was finally abandoned. */@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;}diff --git a/src/modules/webhook/entities/webhook.entity.ts b/src/modules/webhook/entities/webhook.entity.tsindex aac0a9a02..dbcdf695c 100644--- a/src/modules/webhook/entities/webhook.entity.ts+++ b/src/modules/webhook/entities/webhook.entity.ts@@ -16,7 +16,7 @@ import { WebhookFilters } from '../filters/filter-types';@Entity('webhooks')export class Webhook {@PrimaryGeneratedColumn('uuid')- id: string;+ id!: string;// varchar (not uuid) to match the authoritative migration DDL and sessions.id; the data connection// runs synchronize:false, so a 'uuid' decorator here would only mislead schema diffs / a stray sync.@@ -24,40 +24,40 @@ export class Webhook {// AddWebhooksSessionIdIndex migration, which creates the index on migration-managed DBs).@Index('IDX_webhooks_sessionId')@Column({ type: 'varchar' })- sessionId: string;+ sessionId!: string;@ManyToOne(() => Session, { onDelete: 'CASCADE' })@JoinColumn({ name: 'sessionId' })- session: Session;+ session!: Session;@Column({ type: 'varchar', length: 2048 })- url: string;+ url!: string;@Column({ type: jsonColumnType(), default: '["message.received"]' })- events: string[];+ events!: string[];@Column({ type: 'varchar', length: 255, nullable: true })- secret: string | null;+ secret!: string | null;@Column({ type: jsonColumnType(), default: '{}' })- headers: Record<string, string>;+ headers!: Record<string, string>;// Optional smart pre-filter. Null/absent means "no filtering" (fire on every subscribed event).@Column({ type: jsonColumnType(), nullable: true })- filters: WebhookFilters | null;+ filters!: WebhookFilters | null;@Column({ type: 'boolean', default: true })- active: boolean;+ active!: boolean;@Column({ type: 'int', default: 3 })- retryCount: number;+ retryCount!: number;@Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })- lastTriggeredAt: Date | null;+ lastTriggeredAt!: Date | null;@CreateDateColumn()- createdAt: Date;+ createdAt!: Date;@UpdateDateColumn()- updatedAt: Date;+ updatedAt!: Date;}diff --git a/tsconfig.json b/tsconfig.jsonindex b665ed643..c535e5e47 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -21,16 +21,10 @@// TypeScript 6 no longer auto-includes every node_modules/@types package: the globals the// project relies on must be listed. node covers src; jest covers the colocated *.spec.ts."types": ["node", "jest"],- "strictNullChecks": true,+ // The whole strict family, which is also TypeScript 6's own default. Entity and DTO properties+ // the framework populates carry `!`, since no constructor assigns them.+ "strict": true,"forceConsistentCasingInFileNames": true,- "noImplicitAny": true,- "strictBindCallApply": true,- // TypeScript 6 defaults the whole strict family ON. This project opts into strict flags- // selectively (see the explicit trues above); these three stay off pending their own migrations —- // strictPropertyInitialization alone flags ~260 TypeORM entity properties.- "strictPropertyInitialization": false,- "strictFunctionTypes": false,- "useUnknownInCatchVariables": false,"noFallthroughCasesInSwitch": true},"exclude": ["node_modules", "dist", "dashboard"],