@venizia/ignis 0.4.8 → 0.5.0-1
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/esm/base/applications/base.js +5 -2
- package/dist/esm/base/applications/base.js.map +1 -1
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +1 -1
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
- package/dist/esm/components/api-reference/common/keys.d.ts +2 -1
- package/dist/esm/components/api-reference/common/keys.js +4 -1
- package/dist/esm/components/api-reference/common/keys.js.map +1 -1
- package/dist/esm/components/api-reference/common/types.d.ts +1 -1
- package/dist/esm/components/api-reference/common/types.js.map +1 -1
- package/dist/esm/components/api-reference/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/component.js +10 -16
- package/dist/esm/components/auth/authenticate/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/jwks/controller.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/jwks/definitions.d.ts +2 -2
- package/dist/esm/components/auth/authenticate/controllers/service-certs/controller.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/service-certs/definitions.d.ts +2 -2
- package/dist/esm/components/auth/authenticate/services/basic/service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/basic/service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +2 -2
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +3 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +10 -22
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +16 -112
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/service/signer.service.d.ts +11 -0
- package/dist/esm/components/auth/authenticate/services/service/signer.service.js +18 -0
- package/dist/esm/components/auth/authenticate/services/service/signer.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +1 -1
- package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/basic.strategy.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/jwks/issuer.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/jwks/verifier.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/jws.strategy.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
- package/dist/esm/components/auth/authorize/component.js.map +1 -1
- package/dist/esm/components/controller/grpc/common/types.d.ts +1 -1
- package/dist/esm/components/controller/grpc/common/types.js +4 -1
- package/dist/esm/components/controller/grpc/common/types.js.map +1 -1
- package/dist/esm/components/controller/grpc/grpc.component.js.map +1 -1
- package/dist/esm/components/health-check/common/keys.d.ts +4 -2
- package/dist/esm/components/health-check/common/keys.js +7 -2
- package/dist/esm/components/health-check/common/keys.js.map +1 -1
- package/dist/esm/components/health-check/common/types.d.ts +1 -1
- package/dist/esm/components/health-check/common/types.js.map +1 -1
- package/dist/esm/components/health-check/component.js +1 -3
- package/dist/esm/components/health-check/component.js.map +1 -1
- package/dist/esm/components/mail/common/constants.d.ts +8 -0
- package/dist/esm/components/mail/common/constants.js +6 -0
- package/dist/esm/components/mail/common/constants.js.map +1 -1
- package/dist/esm/components/mail/common/errors.d.ts +9 -0
- package/dist/esm/components/mail/common/errors.js +6 -0
- package/dist/esm/components/mail/common/errors.js.map +1 -1
- package/dist/esm/components/mail/common/keys.d.ts +14 -11
- package/dist/esm/components/mail/common/keys.js +34 -11
- package/dist/esm/components/mail/common/keys.js.map +1 -1
- package/dist/esm/components/mail/common/types/message.d.ts +3 -0
- package/dist/esm/components/mail/common/types/message.js.map +1 -1
- package/dist/esm/components/mail/common/types/queue.d.ts +2 -0
- package/dist/esm/components/mail/common/types/queue.js.map +1 -1
- package/dist/esm/components/mail/common/types/template.d.ts +4 -1
- package/dist/esm/components/mail/common/types/template.js.map +1 -1
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.d.ts +2 -0
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +17 -10
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
- package/dist/esm/components/mail/services/mail.service.js +3 -2
- package/dist/esm/components/mail/services/mail.service.js.map +1 -1
- package/dist/esm/components/mail/services/template.service.d.ts +3 -3
- package/dist/esm/components/mail/services/template.service.js +29 -36
- package/dist/esm/components/mail/services/template.service.js.map +1 -1
- package/dist/esm/components/mail/utilities/index.d.ts +1 -0
- package/dist/esm/components/mail/utilities/index.js +1 -0
- package/dist/esm/components/mail/utilities/index.js.map +1 -1
- package/dist/esm/components/mail/utilities/template-renderer.utility.d.ts +31 -0
- package/dist/esm/components/mail/utilities/template-renderer.utility.js +184 -0
- package/dist/esm/components/mail/utilities/template-renderer.utility.js.map +1 -0
- package/dist/esm/components/request-tracker/component.d.ts +2 -1
- package/dist/esm/components/request-tracker/component.js +5 -5
- package/dist/esm/components/request-tracker/component.js.map +1 -1
- package/dist/esm/components/server-info/common/keys.d.ts +2 -1
- package/dist/esm/components/server-info/common/keys.js +4 -1
- package/dist/esm/components/server-info/common/keys.js.map +1 -1
- package/dist/esm/components/server-info/common/types.d.ts +1 -1
- package/dist/esm/components/server-info/common/types.js.map +1 -1
- package/dist/esm/components/server-info/component.js +1 -3
- package/dist/esm/components/server-info/component.js.map +1 -1
- package/dist/esm/components/socket-io/common/keys.d.ts +9 -6
- package/dist/esm/components/socket-io/common/keys.js +19 -6
- package/dist/esm/components/socket-io/common/keys.js.map +1 -1
- package/dist/esm/components/socket-io/component.js +1 -1
- package/dist/esm/components/socket-io/component.js.map +1 -1
- package/dist/esm/components/static-asset/common/keys.d.ts +8 -4
- package/dist/esm/components/static-asset/common/keys.js +10 -3
- package/dist/esm/components/static-asset/common/keys.js.map +1 -1
- package/dist/esm/components/static-asset/component.js +1 -0
- package/dist/esm/components/static-asset/component.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/ingest.utility.d.ts +3 -3
- package/dist/esm/components/static-asset/utilities/ingest.utility.js +14 -18
- package/dist/esm/components/static-asset/utilities/ingest.utility.js.map +1 -1
- package/dist/esm/components/websocket/common/keys.d.ts +12 -10
- package/dist/esm/components/websocket/common/keys.js +31 -10
- package/dist/esm/components/websocket/common/keys.js.map +1 -1
- package/dist/esm/components/websocket/component.js.map +1 -1
- package/dist/presets/app/preset.json +4 -4
- package/dist/presets/lib/preset.json +3 -3
- package/dist/presets/shared/preset.json +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bull-mq-executor.helper.js","sourceRoot":"","sources":["../../../../../../src/components/mail/helpers/executors/bull-mq-executor.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGnE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAS7D,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAGtB,6MAA6M;AAC7M,MAAM,OAAO,wBAAyB,SAAQ,UAAU;IAatD,YAAY,IAA6B;QACvC,K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G,EAAE,EAAE,CAAC;QACzD,MAAM,GAAG,GAAqB;YAC5B,EAAE,EAAE,KAAK;YACT,KAAK;YACL,OAAO;YACP,QAAQ,EAAE,CAAC;YACX,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,EAAE,KAAK,IAAI,CAAC,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC;aACvC,KAAK,CAAC,sDAAsD,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAEnF,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAC9C,iBAAiB,CAAC,uBAAuB,EACzC,GAAG,EACH;YACE,QAAQ,EAAE,OAAO,EAAE,QAAQ;YAC3B,KAAK,EAAE,OAAO,EAAE,KAAK;YACrB,QAAQ,EAAE,OAAO,EAAE,QAAQ,IAAI,YAAY,CAAC,QAAQ;YACpD,OAAO,EAAE;gBACP,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,gBAAgB,CAAC,WAAW;gBAC5D,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,IAAI,YAAY,CAAC,gBAAgB;aAChE;YACD,gBAAgB,EAAE,IAAI;YACtB,2FAA2F;YAC3F,YAAY,EAAE,YAAY,CAAC,oBAAoB;SAChD,CACF,CAAC;QAEF,OAAO;YACL,KAAK,EAAE,OAAO,CAAC,EAAE,IAAI,KAAK;YAC1B,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,0CAA0C;SACpD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { IRedisHelper } from '@venizia/ignis-helpers';\nimport type { TConstValue } from '@/helpers';\nimport { BullMQHelper } from '@venizia/ignis-helpers/bullmq';\nimport type {\n IBullMQMailExecutorOpts,\n IMailProcessorResult,\n IMailQueueExecutor,\n IMailQueueOptions,\n IMailQueueResult,\n IQueueJobPayload,\n} from '../../common';\nimport {\n BullMQExecutorModes,\n MailBackoffTypes,\n MailDefaults,\n MailErrorCodes,\n MailExecutorErrors,\n MailQueueJobNames,\n} from '../../common';\nimport type { Job } from 'bullmq';\n\n/** Mail queue executor backed by BullMQ. The `mode` option decides whether this process holds the queue, the workers, or both; a processor returning `success: false` fails the job so BullMQ retries it. */\nexport class BullMQMailExecutorHelper extends BaseHelper implements IMailQueueExecutor {\n private queueIdentifier: string;\n private queueName: string;\n private mode: TConstValue<typeof BullMQExecutorModes>;\n\n private queueHelper?: BullMQHelper<IQueueJobPayload, IMailQueueResult>;\n private workerHelpers: BullMQHelper<IQueueJobPayload, IMailProcessorResult>[] = [];\n private redisConnection: IRedisHelper;\n private readonly bullmqModule?: typeof import('bullmq');\n private jobIdCounter = 0;\n\n private processor?: (email: string) => Promise<IMailProcessorResult>;\n\n constructor(opts: IBullMQMailExecutorOpts) {\n super({ scope: BullMQMailExecutorHelper.name });\n\n this.mode = opts.mode;\n\n this.redisConnection = opts.redis;\n\n this.bullmqModule = opts.module;\n this.queueIdentifier = opts.queue.identifier;\n this.queueName = opts.queue.name;\n\n this.initQueue(opts.queue);\n }\n\n initQueue(queue: { identifier: string; name: string }) {\n switch (this.mode) {\n case BullMQExecutorModes.QUEUE_ONLY:\n case BullMQExecutorModes.BOTH: {\n this.queueHelper = new BullMQHelper<IQueueJobPayload, IMailQueueResult>({\n identifier: queue.identifier,\n queueName: queue.name,\n redisConnection: this.redisConnection,\n role: 'queue',\n module: this.bullmqModule,\n });\n\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (queue enabled) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n break;\n }\n default: {\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (worker-only mode) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n\n break;\n }\n }\n }\n\n async setProcessor(\n processor: (email: string) => Promise<IMailProcessorResult>,\n opts?: {\n numberOfWorkers?: number;\n concurrencyPerWorker?: number;\n lockDuration?: number;\n },\n ): Promise<void> {\n this.processor = processor;\n\n if (this.mode === BullMQExecutorModes.QUEUE_ONLY) {\n this.logger\n .for(this.setProcessor.name)\n .warn('Skipping worker creation in queue-only mode. Workers will not be started.');\n\n return;\n }\n\n const numberOfWorkers = opts?.numberOfWorkers ?? 1;\n const concurrencyPerWorker = opts?.concurrencyPerWorker ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n await this.clearWorkers();\n\n for (let i = 0; i < numberOfWorkers; i++) {\n this.addWorker({\n workerIdentifier: `${this.queueIdentifier}-worker-${i}`,\n concurrency: concurrencyPerWorker,\n lockDuration,\n });\n }\n\n this.logger\n .for(this.setProcessor.name)\n .info(\n 'Processor registered | Mode: %s | Workers: %d | Concurrency per worker: %d',\n this.mode,\n numberOfWorkers,\n concurrencyPerWorker,\n );\n }\n\n addWorker(opts: { workerIdentifier: string; concurrency?: number; lockDuration?: number }): void {\n if (!this.processor) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const workerIdentifier = opts.workerIdentifier;\n const concurrency = opts?.concurrency ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n const workerHelper = new BullMQHelper<IQueueJobPayload, IMailProcessorResult>({\n identifier: workerIdentifier,\n queueName: this.queueName,\n redisConnection: this.redisConnection,\n role: 'worker',\n module: this.bullmqModule,\n numberOfWorker: concurrency,\n lockDuration,\n onWorkerData: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n const maxAttempts = job.data.options?.attempts ?? MailDefaults.ATTEMPTS;\n\n this.logger\n .for('onWorkerData')\n .info(\n 'Processing job | Worker: %s | jobId: %s | email: %s | attempt: %d/%d',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade + 1,\n maxAttempts,\n );\n\n if (!this.processor) {\n // Returning undefined would let BullMQ mark the job COMPLETED and (with removeOnComplete) delete it - mail silently dropped.\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] ${MailExecutorErrors.PROCESSOR_NOT_SET} | jobId: ${job.data.id}`,\n });\n }\n\n const result = await this.processor(job.data.email);\n\n // A processor reports SMTP rejection by RETURNING `{ success: false }`; BullMQ only treats a REJECTION as failure, so resolving completes the job - no retry, no DLQ.\n if (result?.success === false) {\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] Processor reported failure | jobId: ${job.data.id} | reason: ${result.message}`,\n });\n }\n\n return result;\n },\n onWorkerDataCompleted: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n this.logger\n .for('onWorkerDataCompleted')\n .info(\n 'Job completed | Worker: %s | jobId: %s | email: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n );\n },\n onWorkerDataFail: async (\n job: Job<IQueueJobPayload, IMailProcessorResult> | undefined,\n error: Error,\n ) => {\n if (job) {\n const maxAttempts = job.data.options?.attempts ?? MailDefaults.ATTEMPTS;\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Job failed | Worker: %s | jobId: %s | email: %s | attempt: %d/%d | error: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade,\n maxAttempts,\n error.message,\n );\n } else {\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Worker error (no job) | Worker: %s | error: %s',\n workerIdentifier,\n error.message,\n );\n }\n },\n });\n\n this.workerHelpers.push(workerHelper);\n\n this.logger\n .for(this.addWorker.name)\n .info(\n 'Worker added | Identifier: %s | Concurrency: %d | Total workers: %d',\n workerIdentifier,\n concurrency,\n this.workerHelpers.length,\n );\n }\n\n async removeWorker(index: number): Promise<boolean> {\n if (index < 0 || index >= this.workerHelpers.length) {\n this.logger.for(this.removeWorker.name).warn('Invalid worker index: %d', index);\n\n return false;\n }\n\n // The helper closes the worker, then quits the connections it handed to BullMQ. Dropped from the list BEFORE the close is awaited: a rejecting close must not leave a half-closed worker still counted and still handed jobs.\n const [workerHelper] = this.workerHelpers.splice(index, 1);\n await workerHelper.close();\n\n this.logger\n .for(this.removeWorker.name)\n .info('Worker removed | Index: %d | Remaining workers: %d', index, this.workerHelpers.length);\n\n return true;\n }\n\n /** Closes every worker without stopping at the first failure, always empties the list, and returns failures instead of throwing so teardown can continue. */\n private async closeWorkers(): Promise<Error[]> {\n const workerHelpers = this.workerHelpers;\n this.workerHelpers = [];\n\n const results = await Promise.allSettled(\n workerHelpers.map((workerHelper) => workerHelper.close()),\n );\n\n const failures: Error[] = [];\n\n for (const result of results) {\n if (result.status !== 'rejected') {\n continue;\n }\n\n const error =\n result.reason instanceof Error\n ? result.reason\n : getError({ message: `Worker close failed | reason: ${String(result.reason)}` });\n\n failures.push(error);\n this.logger.for('closeWorkers').error('Failed to close worker | error: %s', error.message);\n }\n\n return failures;\n }\n\n async clearWorkers(): Promise<void> {\n const count = this.workerHelpers.length;\n await this.closeWorkers();\n\n this.logger.for(this.clearWorkers.name).info('All workers cleared | Count: %d', count);\n }\n\n /** Closes the workers, then the queue. Every step runs even if an earlier one failed; failures are reported once, at the end. The Redis helper is the application's, so it stays open. */\n async close(): Promise<void> {\n const result = await this.closeWorkers();\n const failures: Error[] = [...result];\n\n if (this.queueHelper) {\n try {\n await this.queueHelper.close();\n } catch (error) {\n const closeError = error instanceof Error ? error : getError({ message: String(error) });\n failures.push(closeError);\n this.logger.for(this.close.name).error('Failed to close queue | error: %s', closeError);\n }\n }\n\n if (failures.length > 0) {\n throw getError({\n message: `[close] Incomplete BullMQ mail executor teardown | failures: ${failures\n .map((failure) => failure.message)\n .join(' | ')}`,\n });\n }\n\n this.logger.for(this.close.name).info('BullMQ mail executor closed | Mode: %s', this.mode);\n }\n\n getWorkerCount(): number {\n return this.workerHelpers.length;\n }\n\n getMode(): TConstValue<typeof BullMQExecutorModes> {\n return this.mode;\n }\n\n async enqueueVerificationEmail(\n email: string,\n options?: IMailQueueOptions,\n ): Promise<IMailQueueResult> {\n if (this.mode === BullMQExecutorModes.WORKER_ONLY) {\n throw getError({\n message: 'Cannot enqueue jobs in worker-only mode. Set mode to \"queue-only\" or \"both\".',\n });\n }\n\n if (!this.queueHelper) {\n throw getError({\n message: 'Queue helper not initialized. This should not happen in queue-enabled mode.',\n });\n }\n\n if (!this.processor && this.mode !== BullMQExecutorModes.QUEUE_ONLY) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const jobId = `job_${++this.jobIdCounter}_${Date.now()}`;\n const job: IQueueJobPayload = {\n id: jobId,\n email,\n options,\n attempts: 0,\n scheduledAt: Date.now() + (options?.delay ?? 0),\n };\n\n this.logger\n .for(this.enqueueVerificationEmail.name)\n .debug('Queuing email to BullMQ/Redis | jobId: %s | mode: %s', jobId, this.mode);\n\n const bullJob = await this.queueHelper.queue.add(\n MailQueueJobNames.SEND_VERIFICATION_EMAIL,\n job,\n {\n priority: options?.priority,\n delay: options?.delay,\n attempts: options?.attempts ?? MailDefaults.ATTEMPTS,\n backoff: {\n type: options?.backoff?.type ?? MailBackoffTypes.EXPONENTIAL,\n delay: options?.backoff?.delay ?? MailDefaults.BACKOFF_DELAY_MS,\n },\n removeOnComplete: true,\n // Bounded: a failed job holds the recipient's address, and `false` kept every one forever.\n removeOnFail: MailDefaults.FAILED_JOB_RETENTION,\n },\n );\n\n return {\n jobId: bullJob.id ?? jobId,\n queued: true,\n message: 'Email queued successfully (BullMQ/Redis)',\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bull-mq-executor.helper.js","sourceRoot":"","sources":["../../../../../../src/components/mail/helpers/executors/bull-mq-executor.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGnE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAS7D,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,kB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AAK,EAAE,OAAO,CAAC,EAAE,IAAI,KAAK;YAC1B,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,0CAA0C;SACpD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { IRedisHelper } from '@venizia/ignis-helpers';\nimport type { TConstValue } from '@/helpers';\nimport { BullMQHelper } from '@venizia/ignis-helpers/bullmq';\nimport type {\n IBullMQMailExecutorOpts,\n IMailProcessorResult,\n IMailQueueExecutor,\n IMailQueueOptions,\n IMailQueueResult,\n IQueueJobPayload,\n} from '../../common';\nimport {\n BullMQExecutorModes,\n MailBackoffTypes,\n MailDefaults,\n MailErrorCodes,\n MailExecutorErrors,\n MailQueueJobNames,\n} from '../../common';\nimport type { Job } from 'bullmq';\n\n/** Mail queue executor backed by BullMQ. The `mode` option decides whether this process holds the queue, the workers, or both; a processor returning `success: false` fails the job so BullMQ retries it. */\nexport class BullMQMailExecutorHelper extends BaseHelper implements IMailQueueExecutor {\n private queueIdentifier: string;\n private queueName: string;\n private prefix?: string;\n private mode: TConstValue<typeof BullMQExecutorModes>;\n\n private queueHelper?: BullMQHelper<IQueueJobPayload, IMailQueueResult>;\n private workerHelpers: BullMQHelper<IQueueJobPayload, IMailProcessorResult>[] = [];\n private redisConnection: IRedisHelper;\n private readonly bullmqModule?: typeof import('bullmq');\n private jobIdCounter = 0;\n\n private processor?: (email: string) => Promise<IMailProcessorResult>;\n\n constructor(opts: IBullMQMailExecutorOpts) {\n super({ scope: BullMQMailExecutorHelper.name });\n\n this.mode = opts.mode;\n\n this.redisConnection = opts.redis;\n\n this.bullmqModule = opts.module;\n this.queueIdentifier = opts.queue.identifier;\n this.queueName = opts.queue.name;\n this.prefix = opts.queue.prefix;\n\n this.initQueue(opts.queue);\n }\n\n initQueue(queue: { identifier: string; name: string; prefix?: string }) {\n switch (this.mode) {\n case BullMQExecutorModes.QUEUE_ONLY:\n case BullMQExecutorModes.BOTH: {\n this.queueHelper = new BullMQHelper<IQueueJobPayload, IMailQueueResult>({\n identifier: queue.identifier,\n queueName: queue.name,\n redisConnection: this.redisConnection,\n role: 'queue',\n module: this.bullmqModule,\n prefix: queue.prefix,\n });\n\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (queue enabled) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n break;\n }\n default: {\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (worker-only mode) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n\n break;\n }\n }\n }\n\n async setProcessor(\n processor: (email: string) => Promise<IMailProcessorResult>,\n opts?: {\n numberOfWorkers?: number;\n concurrencyPerWorker?: number;\n lockDuration?: number;\n },\n ): Promise<void> {\n this.processor = processor;\n\n if (this.mode === BullMQExecutorModes.QUEUE_ONLY) {\n this.logger\n .for(this.setProcessor.name)\n .warn('Skipping worker creation in queue-only mode. Workers will not be started.');\n\n return;\n }\n\n const numberOfWorkers = opts?.numberOfWorkers ?? 1;\n const concurrencyPerWorker = opts?.concurrencyPerWorker ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n await this.clearWorkers();\n\n for (let i = 0; i < numberOfWorkers; i++) {\n this.addWorker({\n workerIdentifier: `${this.queueIdentifier}-worker-${i}`,\n concurrency: concurrencyPerWorker,\n lockDuration,\n });\n }\n\n this.logger\n .for(this.setProcessor.name)\n .info(\n 'Processor registered | Mode: %s | Workers: %d | Concurrency per worker: %d',\n this.mode,\n numberOfWorkers,\n concurrencyPerWorker,\n );\n }\n\n addWorker(opts: { workerIdentifier: string; concurrency?: number; lockDuration?: number }): void {\n if (!this.processor) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const workerIdentifier = opts.workerIdentifier;\n const concurrency = opts?.concurrency ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n const workerHelper = new BullMQHelper<IQueueJobPayload, IMailProcessorResult>({\n identifier: workerIdentifier,\n queueName: this.queueName,\n redisConnection: this.redisConnection,\n role: 'worker',\n module: this.bullmqModule,\n prefix: this.prefix,\n numberOfWorker: concurrency,\n lockDuration,\n onWorkerData: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n const maxAttempts = job.data.options?.attempts ?? MailDefaults.ATTEMPTS;\n\n this.logger\n .for('onWorkerData')\n .info(\n 'Processing job | Worker: %s | jobId: %s | email: %s | attempt: %d/%d',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade + 1,\n maxAttempts,\n );\n\n if (!this.processor) {\n // Returning undefined would let BullMQ mark the job COMPLETED and (with removeOnComplete) delete it - mail silently dropped.\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] ${MailExecutorErrors.PROCESSOR_NOT_SET} | jobId: ${job.data.id}`,\n });\n }\n\n const result = await this.processor(job.data.email);\n\n // A processor reports SMTP rejection by RETURNING `{ success: false }`; BullMQ only treats a REJECTION as failure, so resolving completes the job - no retry, no DLQ.\n if (result?.success === false) {\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] Processor reported failure | jobId: ${job.data.id} | reason: ${result.message}`,\n });\n }\n\n return result;\n },\n onWorkerDataCompleted: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n this.logger\n .for('onWorkerDataCompleted')\n .info(\n 'Job completed | Worker: %s | jobId: %s | email: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n );\n },\n onWorkerDataFail: async (\n job: Job<IQueueJobPayload, IMailProcessorResult> | undefined,\n error: Error,\n ) => {\n if (job) {\n const maxAttempts = job.data.options?.attempts ?? MailDefaults.ATTEMPTS;\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Job failed | Worker: %s | jobId: %s | email: %s | attempt: %d/%d | error: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade,\n maxAttempts,\n error.message,\n );\n } else {\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Worker error (no job) | Worker: %s | error: %s',\n workerIdentifier,\n error.message,\n );\n }\n },\n });\n\n this.workerHelpers.push(workerHelper);\n\n this.logger\n .for(this.addWorker.name)\n .info(\n 'Worker added | Identifier: %s | Concurrency: %d | Total workers: %d',\n workerIdentifier,\n concurrency,\n this.workerHelpers.length,\n );\n }\n\n async removeWorker(index: number): Promise<boolean> {\n if (index < 0 || index >= this.workerHelpers.length) {\n this.logger.for(this.removeWorker.name).warn('Invalid worker index: %d', index);\n\n return false;\n }\n\n // The helper closes the worker, then quits the connections it handed to BullMQ. Dropped from the list BEFORE the close is awaited: a rejecting close must not leave a half-closed worker still counted and still handed jobs.\n const [workerHelper] = this.workerHelpers.splice(index, 1);\n await workerHelper.close();\n\n this.logger\n .for(this.removeWorker.name)\n .info('Worker removed | Index: %d | Remaining workers: %d', index, this.workerHelpers.length);\n\n return true;\n }\n\n /** Closes every worker without stopping at the first failure, always empties the list, and returns failures instead of throwing so teardown can continue. */\n private async closeWorkers(): Promise<Error[]> {\n const workerHelpers = this.workerHelpers;\n this.workerHelpers = [];\n\n const results = await Promise.allSettled(\n workerHelpers.map((workerHelper) => workerHelper.close()),\n );\n\n const failures: Error[] = [];\n\n for (const result of results) {\n if (result.status !== 'rejected') {\n continue;\n }\n\n const error =\n result.reason instanceof Error\n ? result.reason\n : getError({ message: `Worker close failed | reason: ${String(result.reason)}` });\n\n failures.push(error);\n this.logger.for('closeWorkers').error('Failed to close worker | error: %s', error.message);\n }\n\n return failures;\n }\n\n async clearWorkers(): Promise<void> {\n const count = this.workerHelpers.length;\n await this.closeWorkers();\n\n this.logger.for(this.clearWorkers.name).info('All workers cleared | Count: %d', count);\n }\n\n /** Closes the workers, then the queue. Every step runs even if an earlier one failed; failures are reported once, at the end. The Redis helper is the application's, so it stays open. */\n async close(): Promise<void> {\n const result = await this.closeWorkers();\n const failures: Error[] = [...result];\n\n if (this.queueHelper) {\n try {\n await this.queueHelper.close();\n } catch (error) {\n const closeError = error instanceof Error ? error : getError({ message: String(error) });\n failures.push(closeError);\n this.logger.for(this.close.name).error('Failed to close queue | error: %s', closeError);\n }\n }\n\n if (failures.length > 0) {\n throw getError({\n message: `[close] Incomplete BullMQ mail executor teardown | failures: ${failures\n .map((failure) => failure.message)\n .join(' | ')}`,\n });\n }\n\n this.logger.for(this.close.name).info('BullMQ mail executor closed | Mode: %s', this.mode);\n }\n\n getWorkerCount(): number {\n return this.workerHelpers.length;\n }\n\n getMode(): TConstValue<typeof BullMQExecutorModes> {\n return this.mode;\n }\n\n async enqueueVerificationEmail(\n email: string,\n options?: IMailQueueOptions,\n ): Promise<IMailQueueResult> {\n if (this.mode === BullMQExecutorModes.WORKER_ONLY) {\n throw getError({\n message: 'Cannot enqueue jobs in worker-only mode. Set mode to \"queue-only\" or \"both\".',\n });\n }\n\n if (!this.queueHelper) {\n throw getError({\n message: 'Queue helper not initialized. This should not happen in queue-enabled mode.',\n });\n }\n\n if (!this.processor && this.mode !== BullMQExecutorModes.QUEUE_ONLY) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const jobId = `job_${++this.jobIdCounter}_${Date.now()}`;\n const job: IQueueJobPayload = {\n id: jobId,\n email,\n options,\n attempts: 0,\n scheduledAt: Date.now() + (options?.delay ?? 0),\n };\n\n this.logger\n .for(this.enqueueVerificationEmail.name)\n .debug('Queuing email to BullMQ/Redis | jobId: %s | mode: %s', jobId, this.mode);\n\n const bullJob = await this.queueHelper.add({\n name: MailQueueJobNames.SEND_VERIFICATION_EMAIL,\n data: job,\n opts: {\n priority: options?.priority,\n delay: options?.delay,\n attempts: options?.attempts ?? MailDefaults.ATTEMPTS,\n backoff: {\n type: options?.backoff?.type ?? MailBackoffTypes.EXPONENTIAL,\n delay: options?.backoff?.delay ?? MailDefaults.BACKOFF_DELAY_MS,\n },\n removeOnComplete: true,\n // Bounded: a failed job holds the recipient's address, and `false` kept every one forever.\n removeOnFail: MailDefaults.FAILED_JOB_RETENTION,\n },\n });\n\n return {\n jobId: bullJob.id ?? jobId,\n queued: true,\n message: 'Email queued successfully (BullMQ/Redis)',\n };\n }\n}\n"]}
|
|
@@ -125,9 +125,9 @@ let MailService = MailService_1 = class MailService extends BaseService {
|
|
|
125
125
|
});
|
|
126
126
|
}
|
|
127
127
|
// `rest` goes first below: the recipients, the subject and the body this call rendered are not the options' to replace, and `requireValidate` is a render switch, not a message field.
|
|
128
|
-
const { requireValidate, subject, ...rest } = options ?? {};
|
|
128
|
+
const { requireValidate, missing, subject, ...rest } = options ?? {};
|
|
129
129
|
this.logger.for(this.sendTemplate.name).debug('Rendering template: %s', templateName);
|
|
130
|
-
const html = this.templateEngine.render({ templateName, data, requireValidate });
|
|
130
|
+
const html = this.templateEngine.render({ templateName, data, requireValidate, missing });
|
|
131
131
|
const templateData = this.templateEngine.getTemplate(templateName);
|
|
132
132
|
const renderedSubject = templateData?.subject === undefined
|
|
133
133
|
? MailDefaults.SUBJECT
|
|
@@ -135,6 +135,7 @@ let MailService = MailService_1 = class MailService extends BaseService {
|
|
|
135
135
|
templateData: templateData.subject,
|
|
136
136
|
data,
|
|
137
137
|
requireValidate,
|
|
138
|
+
missing,
|
|
138
139
|
format: MailTemplateFormats.TEXT,
|
|
139
140
|
});
|
|
140
141
|
const message = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mail.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/mail.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AASpD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACpG,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC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C;QACd,CAAC;QAED,OAAO,IAAI,eAAe,CAAC,kBAAkB,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,MAAM,IAAI,GAAG,CAAC;IAClF,CAAC;CACF,CAAA;AA9NY,WAAW;IAEnB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAA;IAEtC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,CAAA;IAEjD,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,oBAAoB,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAA;;GANxD,WAAW,CA8NvB","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport type {\n IMailMessage,\n IMailSendResult,\n IMailService,\n IMailTemplateEngine,\n IMailTransport,\n TMailOptions,\n} from '../common';\nimport { MailDefaults, MailErrorCodes, MailErrors, MailKeys, MailTemplateFormats } from '../common';\nimport { inject } from '@/base/metadata';\nimport { getError, isApplicationError } from '@venizia/ignis-helpers/core';\nimport { ErrorUtility, PromiseUtility } from '@venizia/ignis-helpers';\nimport { MailAttachmentUtility } from '../utilities/attachment.utility';\nimport { MailBodyUtility } from '../utilities/body.utility';\nimport { MailHeaderUtility } from '../utilities/header.utility';\nimport { MailMimeUtility } from '../utilities/mime.utility';\n\n/** Sends mail through the bound transport. `send` validates the message, applies the attachment policy and defaults `from`; failures are thrown as application errors with a mail message code, except `sendBatch`, which reports each failure in its result. */\nexport class MailService extends BaseService implements IMailService {\n constructor(\n @inject({ key: MailKeys.MAIL_OPTIONS })\n protected options: TMailOptions,\n @inject({ key: MailKeys.MAIL_TRANSPORT_INSTANCE })\n protected transport: IMailTransport,\n @inject({ key: MailKeys.MAIL_TEMPLATE_ENGINE, isOptional: true })\n protected templateEngine?: IMailTemplateEngine,\n ) {\n super({ scope: MailService.name });\n this.logger\n .for(this.constructor.name)\n .info('Mail service initialized with provider: %s', this.options.provider);\n }\n\n async send(message: IMailMessage): Promise<IMailSendResult> {\n try {\n this.validateMessage(message);\n\n const emailMessage: IMailMessage = {\n ...message,\n from: message.from ?? this.getDefaultFrom(),\n };\n\n // The one place the attachment policy applies: every transport receives bytes, never a path.\n if (message.attachments) {\n const result2 = await MailAttachmentUtility.resolve({\n attachments: message.attachments,\n attachmentRoot: this.options.attachmentRoot,\n maxBytes: this.options.maxAttachmentBytes ?? MailDefaults.MAX_ATTACHMENT_BYTES,\n });\n emailMessage.attachments = result2;\n }\n\n this.logger.for(this.send.name).debug('Sending email to: %s', emailMessage.to);\n const result = await this.transport.send(emailMessage);\n\n if (result.success) {\n this.logger\n .for(this.send.name)\n .debug('Email sent successfully. MessageId: %s', result.messageId);\n } else {\n this.logger.for(this.send.name).debug('Email send failed: %s', result.error);\n }\n\n return result;\n } catch (error) {\n this.logger.for(this.send.name).error('Error sending email: %s', error);\n MailAttachmentUtility.release({ attachments: message.attachments });\n\n // An error the framework already shaped carries its own status and message code; re-wrapping as 500 would report a caller mistake as a server fault.\n if (isApplicationError(error)) {\n throw error;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.SEND_FAILED,\n // The raw text can carry a file path or a provider detail; it rides in `cause`, which only development responses show.\n message: 'Failed to send email',\n cause: error,\n });\n }\n }\n\n async sendBatch(\n messages: IMailMessage[],\n options?: { concurrency?: number },\n ): Promise<IMailSendResult[]> {\n try {\n const concurrency = options?.concurrency ?? MailDefaults.BATCH_CONCURRENCY;\n this.logger\n .for(this.sendBatch.name)\n .info('Sending batch of %d emails with concurrency: %d', messages.length, concurrency);\n\n const tasks = messages.map((message) => async () => {\n try {\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n return {\n success: false,\n error: ErrorUtility.toError({ error }).message,\n };\n }\n });\n\n const results = await PromiseUtility.executeWithLimit<IMailSendResult>({\n tasks,\n limit: concurrency,\n });\n\n const successCount = results.filter((r) => r.success).length;\n this.logger\n .for(this.sendBatch.name)\n .info(\n 'Batch send completed. Success: %d, Failed: %d',\n successCount,\n results.length - successCount,\n );\n\n return results;\n } catch (error) {\n this.logger.for(this.sendBatch.name).error('Error sending batch emails: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.BATCH_SEND_FAILED,\n message: 'Failed to send batch emails',\n cause: error,\n });\n }\n }\n\n async sendTemplate(opts: {\n templateName: string;\n data: Record<string, unknown>;\n recipients: string | string[];\n options?: Partial<IMailMessage>;\n }): Promise<IMailSendResult> {\n const { templateName, data, recipients, options } = opts;\n\n try {\n if (!this.templateEngine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Template engine not configured',\n });\n }\n\n // `rest` goes first below: the recipients, the subject and the body this call rendered are not the options' to replace, and `requireValidate` is a render switch, not a message field.\n const { requireValidate, subject, ...rest } = options ?? {};\n\n this.logger.for(this.sendTemplate.name).debug('Rendering template: %s', templateName);\n const html = this.templateEngine.render({ templateName, data, requireValidate });\n\n const templateData = this.templateEngine.getTemplate(templateName);\n const renderedSubject =\n templateData?.subject === undefined\n ? MailDefaults.SUBJECT\n : this.templateEngine.render({\n templateData: templateData.subject,\n data,\n requireValidate,\n format: MailTemplateFormats.TEXT,\n });\n\n const message: IMailMessage = {\n ...rest,\n to: recipients,\n subject: subject ?? renderedSubject,\n html,\n };\n\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n this.logger.for(this.sendTemplate.name).error('Error sending template email: %s', error);\n throw error;\n }\n }\n\n async verify(): Promise<boolean> {\n try {\n this.logger.for(this.verify.name).debug('Verifying mail transport connection');\n const isValid = await this.transport.verify();\n this.logger.for(this.verify.name).debug('Verification result: %s', isValid);\n\n return isValid;\n } catch (error) {\n this.logger.for(this.verify.name).error('Verification failed: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.VERIFICATION_FAILED,\n message: 'Mail transport verification failed',\n cause: error,\n });\n }\n }\n\n protected validateMessage(message: IMailMessage): void {\n if (!message.to || (Array.isArray(message.to) && message.to.length === 0)) {\n throw getError({\n error: MailErrors.INVALID_RECIPIENT,\n message: 'Recipient email address is required',\n });\n }\n\n if (!message.subject) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email subject is required',\n });\n }\n\n if (!message.text && !message.html) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email must have either text or html content',\n });\n }\n\n MailBodyUtility.assertIsText({ message });\n MailHeaderUtility.assert({ message });\n }\n\n protected getDefaultFrom(): string {\n const { from, fromName } = this.options;\n\n // A display name is only renderable around an address: `\"Name\" <undefined>` is not a sender.\n if (!from) {\n return MailDefaults.FALLBACK_FROM;\n }\n\n if (!fromName) {\n return from;\n }\n\n return `\"${MailMimeUtility.escapeQuotedString({ value: fromName })}\" <${from}>`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mail.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/mail.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AASpD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACpG,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B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AC;CACF,CAAA;AA/NY,WAAW;IAEnB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAA;IAEtC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,CAAA;IAEjD,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,oBAAoB,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAA;;GANxD,WAAW,CA+NvB","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport type {\n IMailMessage,\n IMailSendResult,\n IMailService,\n IMailTemplateEngine,\n IMailTransport,\n TMailOptions,\n} from '../common';\nimport { MailDefaults, MailErrorCodes, MailErrors, MailKeys, MailTemplateFormats } from '../common';\nimport { inject } from '@/base/metadata';\nimport { getError, isApplicationError } from '@venizia/ignis-helpers/core';\nimport { ErrorUtility, PromiseUtility } from '@venizia/ignis-helpers';\nimport { MailAttachmentUtility } from '../utilities/attachment.utility';\nimport { MailBodyUtility } from '../utilities/body.utility';\nimport { MailHeaderUtility } from '../utilities/header.utility';\nimport { MailMimeUtility } from '../utilities/mime.utility';\n\n/** Sends mail through the bound transport. `send` validates the message, applies the attachment policy and defaults `from`; failures are thrown as application errors with a mail message code, except `sendBatch`, which reports each failure in its result. */\nexport class MailService extends BaseService implements IMailService {\n constructor(\n @inject({ key: MailKeys.MAIL_OPTIONS })\n protected options: TMailOptions,\n @inject({ key: MailKeys.MAIL_TRANSPORT_INSTANCE })\n protected transport: IMailTransport,\n @inject({ key: MailKeys.MAIL_TEMPLATE_ENGINE, isOptional: true })\n protected templateEngine?: IMailTemplateEngine,\n ) {\n super({ scope: MailService.name });\n this.logger\n .for(this.constructor.name)\n .info('Mail service initialized with provider: %s', this.options.provider);\n }\n\n async send(message: IMailMessage): Promise<IMailSendResult> {\n try {\n this.validateMessage(message);\n\n const emailMessage: IMailMessage = {\n ...message,\n from: message.from ?? this.getDefaultFrom(),\n };\n\n // The one place the attachment policy applies: every transport receives bytes, never a path.\n if (message.attachments) {\n const result2 = await MailAttachmentUtility.resolve({\n attachments: message.attachments,\n attachmentRoot: this.options.attachmentRoot,\n maxBytes: this.options.maxAttachmentBytes ?? MailDefaults.MAX_ATTACHMENT_BYTES,\n });\n emailMessage.attachments = result2;\n }\n\n this.logger.for(this.send.name).debug('Sending email to: %s', emailMessage.to);\n const result = await this.transport.send(emailMessage);\n\n if (result.success) {\n this.logger\n .for(this.send.name)\n .debug('Email sent successfully. MessageId: %s', result.messageId);\n } else {\n this.logger.for(this.send.name).debug('Email send failed: %s', result.error);\n }\n\n return result;\n } catch (error) {\n this.logger.for(this.send.name).error('Error sending email: %s', error);\n MailAttachmentUtility.release({ attachments: message.attachments });\n\n // An error the framework already shaped carries its own status and message code; re-wrapping as 500 would report a caller mistake as a server fault.\n if (isApplicationError(error)) {\n throw error;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.SEND_FAILED,\n // The raw text can carry a file path or a provider detail; it rides in `cause`, which only development responses show.\n message: 'Failed to send email',\n cause: error,\n });\n }\n }\n\n async sendBatch(\n messages: IMailMessage[],\n options?: { concurrency?: number },\n ): Promise<IMailSendResult[]> {\n try {\n const concurrency = options?.concurrency ?? MailDefaults.BATCH_CONCURRENCY;\n this.logger\n .for(this.sendBatch.name)\n .info('Sending batch of %d emails with concurrency: %d', messages.length, concurrency);\n\n const tasks = messages.map((message) => async () => {\n try {\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n return {\n success: false,\n error: ErrorUtility.toError({ error }).message,\n };\n }\n });\n\n const results = await PromiseUtility.executeWithLimit<IMailSendResult>({\n tasks,\n limit: concurrency,\n });\n\n const successCount = results.filter((r) => r.success).length;\n this.logger\n .for(this.sendBatch.name)\n .info(\n 'Batch send completed. Success: %d, Failed: %d',\n successCount,\n results.length - successCount,\n );\n\n return results;\n } catch (error) {\n this.logger.for(this.sendBatch.name).error('Error sending batch emails: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.BATCH_SEND_FAILED,\n message: 'Failed to send batch emails',\n cause: error,\n });\n }\n }\n\n async sendTemplate(opts: {\n templateName: string;\n data: Record<string, unknown>;\n recipients: string | string[];\n options?: Partial<IMailMessage>;\n }): Promise<IMailSendResult> {\n const { templateName, data, recipients, options } = opts;\n\n try {\n if (!this.templateEngine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Template engine not configured',\n });\n }\n\n // `rest` goes first below: the recipients, the subject and the body this call rendered are not the options' to replace, and `requireValidate` is a render switch, not a message field.\n const { requireValidate, missing, subject, ...rest } = options ?? {};\n\n this.logger.for(this.sendTemplate.name).debug('Rendering template: %s', templateName);\n const html = this.templateEngine.render({ templateName, data, requireValidate, missing });\n\n const templateData = this.templateEngine.getTemplate(templateName);\n const renderedSubject =\n templateData?.subject === undefined\n ? MailDefaults.SUBJECT\n : this.templateEngine.render({\n templateData: templateData.subject,\n data,\n requireValidate,\n missing,\n format: MailTemplateFormats.TEXT,\n });\n\n const message: IMailMessage = {\n ...rest,\n to: recipients,\n subject: subject ?? renderedSubject,\n html,\n };\n\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n this.logger.for(this.sendTemplate.name).error('Error sending template email: %s', error);\n throw error;\n }\n }\n\n async verify(): Promise<boolean> {\n try {\n this.logger.for(this.verify.name).debug('Verifying mail transport connection');\n const isValid = await this.transport.verify();\n this.logger.for(this.verify.name).debug('Verification result: %s', isValid);\n\n return isValid;\n } catch (error) {\n this.logger.for(this.verify.name).error('Verification failed: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.VERIFICATION_FAILED,\n message: 'Mail transport verification failed',\n cause: error,\n });\n }\n }\n\n protected validateMessage(message: IMailMessage): void {\n if (!message.to || (Array.isArray(message.to) && message.to.length === 0)) {\n throw getError({\n error: MailErrors.INVALID_RECIPIENT,\n message: 'Recipient email address is required',\n });\n }\n\n if (!message.subject) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email subject is required',\n });\n }\n\n if (!message.text && !message.html) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email must have either text or html content',\n });\n }\n\n MailBodyUtility.assertIsText({ message });\n MailHeaderUtility.assert({ message });\n }\n\n protected getDefaultFrom(): string {\n const { from, fromName } = this.options;\n\n // A display name is only renderable around an address: `\"Name\" <undefined>` is not a sender.\n if (!from) {\n return MailDefaults.FALLBACK_FROM;\n }\n\n if (!fromName) {\n return from;\n }\n\n return `\"${MailMimeUtility.escapeQuotedString({ value: fromName })}\" <${from}>`;\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseService } from '@venizia/ignis-kernel';
|
|
2
|
-
import type { IMailTemplateEngine, ITemplate, TMailTemplateFormat } from '../common/index.js';
|
|
2
|
+
import type { IMailTemplateEngine, ITemplate, TMailTemplateFormat, TMailTemplateMissing } from '../common/index.js';
|
|
3
3
|
/** In-memory template store and renderer. Templates registered here are lost on restart. */
|
|
4
4
|
export declare class TemplateEngineService extends BaseService implements IMailTemplateEngine {
|
|
5
5
|
private templates;
|
|
@@ -14,6 +14,7 @@ export declare class TemplateEngineService extends BaseService implements IMailT
|
|
|
14
14
|
templateName?: string;
|
|
15
15
|
data: Record<string, unknown>;
|
|
16
16
|
requireValidate?: boolean;
|
|
17
|
+
missing?: TMailTemplateMissing;
|
|
17
18
|
format?: TMailTemplateFormat;
|
|
18
19
|
}): string;
|
|
19
20
|
getTemplate(name: string): ITemplate | undefined;
|
|
@@ -31,9 +32,8 @@ export declare class TemplateEngineService extends BaseService implements IMailT
|
|
|
31
32
|
};
|
|
32
33
|
renderSimpleTemplate(template: string, data: Record<string, unknown>, opts?: {
|
|
33
34
|
requireValidate?: boolean;
|
|
35
|
+
missing?: TMailTemplateMissing;
|
|
34
36
|
format?: TMailTemplateFormat;
|
|
35
37
|
}): string;
|
|
36
|
-
/** Reads own properties only: `{{constructor}}` or `{{__proto__.x}}` must not reach the prototype chain. */
|
|
37
|
-
private getNestedValue;
|
|
38
38
|
}
|
|
39
39
|
//# sourceMappingURL=template.service.d.ts.map
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { BaseService } from '@venizia/ignis-kernel';
|
|
2
|
-
import { MailErrors
|
|
2
|
+
import { MailErrors } from '../common/index.js';
|
|
3
|
+
import { MailTemplateRenderer } from '../utilities/index.js';
|
|
3
4
|
import { getError } from '@venizia/ignis-helpers/core';
|
|
4
|
-
/** `{{{key}}}` (group 1, raw) or `{{key}}` (group 2). The raw form comes first: `{{key}}` also matches inside it. */
|
|
5
|
-
const PLACEHOLDER = /\{\{\{\s*([\w.]+)\s*\}\}\}|\{\{\s*([\w.]+)\s*\}\}/g;
|
|
6
5
|
/** In-memory template store and renderer. Templates registered here are lost on restart. */
|
|
7
6
|
export class TemplateEngineService extends BaseService {
|
|
8
7
|
constructor() {
|
|
@@ -22,7 +21,7 @@ export class TemplateEngineService extends BaseService {
|
|
|
22
21
|
this.templates.set(name, template);
|
|
23
22
|
}
|
|
24
23
|
render(opts) {
|
|
25
|
-
const { templateData, templateName, data, requireValidate, format } = opts;
|
|
24
|
+
const { templateData, templateName, data, requireValidate, missing, format } = opts;
|
|
26
25
|
if (!templateData && !templateName) {
|
|
27
26
|
throw getError({ message: 'Either templateName or templateData must be provided' });
|
|
28
27
|
}
|
|
@@ -44,7 +43,7 @@ export class TemplateEngineService extends BaseService {
|
|
|
44
43
|
message: `Template has no content: ${templateName}`,
|
|
45
44
|
});
|
|
46
45
|
}
|
|
47
|
-
return this.renderSimpleTemplate(content, data, { requireValidate, format });
|
|
46
|
+
return this.renderSimpleTemplate(content, data, { requireValidate, missing, format });
|
|
48
47
|
}
|
|
49
48
|
getTemplate(name) {
|
|
50
49
|
return this.templates.get(name);
|
|
@@ -65,19 +64,13 @@ export class TemplateEngineService extends BaseService {
|
|
|
65
64
|
}
|
|
66
65
|
validateTemplateData(opts) {
|
|
67
66
|
const { template, data } = opts;
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
allKeys.push(key);
|
|
76
|
-
const value = this.getNestedValue(data, key);
|
|
77
|
-
if (value === undefined || value === null) {
|
|
78
|
-
missingKeys.push(key);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
67
|
+
const { valueKeys, sectionKeys } = MailTemplateRenderer.readKeys({ template });
|
|
68
|
+
// A section key is reported but never missing: an absent section is an optional block, not an error.
|
|
69
|
+
const allKeys = [...valueKeys, ...sectionKeys.filter((key) => !valueKeys.includes(key))];
|
|
70
|
+
const missingKeys = valueKeys.filter((key) => {
|
|
71
|
+
const value = MailTemplateRenderer.read({ data, key });
|
|
72
|
+
return value === undefined || value === null;
|
|
73
|
+
});
|
|
81
74
|
const isValid = missingKeys.length === 0;
|
|
82
75
|
if (!isValid) {
|
|
83
76
|
this.logger
|
|
@@ -96,25 +89,25 @@ export class TemplateEngineService extends BaseService {
|
|
|
96
89
|
});
|
|
97
90
|
}
|
|
98
91
|
}
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
92
|
+
const emptyKeys = [];
|
|
93
|
+
const rendered = MailTemplateRenderer.render({
|
|
94
|
+
template,
|
|
95
|
+
data,
|
|
96
|
+
format: opts?.format,
|
|
97
|
+
missing: opts?.missing,
|
|
98
|
+
onEmpty: (key) => {
|
|
99
|
+
if (!emptyKeys.includes(key)) {
|
|
100
|
+
emptyKeys.push(key);
|
|
101
|
+
}
|
|
102
|
+
},
|
|
109
103
|
});
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
}, obj);
|
|
104
|
+
if (emptyKeys.length > 0) {
|
|
105
|
+
// Keys only, never values: a value is the recipient's data.
|
|
106
|
+
this.logger
|
|
107
|
+
.for(this.renderSimpleTemplate.name)
|
|
108
|
+
.warn('Template rendered with empty values | Keys: %s', emptyKeys.join(', '));
|
|
109
|
+
}
|
|
110
|
+
return rendered;
|
|
118
111
|
}
|
|
119
112
|
}
|
|
120
113
|
//# sourceMappingURL=template.service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/template.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,qHAAqH;AACrH,MAAM,WAAW,GAAG,oDAAoD,CAAC;AAEzE,4FAA4F;AAC5F,MAAM,OAAO,qBAAsB,SAAQ,WAAW;IAGpD;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,qBAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;QAHvC,cAAS,GAA2B,IAAI,GAAG,EAAE,CAAC;QAIpD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC;IAC7E,CAAC;IAED,gBAAgB,CAAC,IAAqE;QACpF,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACxC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,0BAA0B,EAAE,IAAI,CAAC,CAAC;QAEnF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AG,SAAS,IAAI,SAAS,IAAI,EAAE,CAAC;YACzC,MAAM,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YAE7C,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;gBAC1C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,2BAA2B,EAAE,GAAG,CAAC,CAAC;gBAEvF,OAAO,KAAK,CAAC;YACf,CAAC;YAED,+DAA+D;YAC/D,OAAO,MAAM,IAAI,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC3F,CAAC,CAAC,CAAC;IACL,CAAC;IAED,4GAA4G;IACpG,cAAc,CAAC,GAAY,EAAE,IAAY;QAC/C,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAU,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE;YACtD,OAAO,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC;gBACnF,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC;gBAC3B,CAAC,CAAC,SAAS,CAAC;QAChB,CAAC,EAAE,GAAG,CAAC,CAAC;IACV,CAAC;CACF","sourcesContent":["import { BaseService } from '@venizia/ignis-kernel';\nimport type { IMailTemplateEngine, ITemplate, TMailTemplateFormat } from '../common';\nimport { MailErrors, MailTemplateFormats } from '../common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** `{{{key}}}` (group 1, raw) or `{{key}}` (group 2). The raw form comes first: `{{key}}` also matches inside it. */\nconst PLACEHOLDER = /\\{\\{\\{\\s*([\\w.]+)\\s*\\}\\}\\}|\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g;\n\n/** In-memory template store and renderer. Templates registered here are lost on restart. */\nexport class TemplateEngineService extends BaseService implements IMailTemplateEngine {\n private templates: Map<string, ITemplate> = new Map();\n\n constructor() {\n super({ scope: TemplateEngineService.name });\n this.logger.for(this.constructor.name).info('Template engine initialized');\n }\n\n registerTemplate(opts: { name: string; content: string; options?: Partial<ITemplate> }): void {\n const { name, content, options } = opts;\n this.logger.for(this.registerTemplate.name).info('Registering template: %s', name);\n\n const template: ITemplate = {\n name,\n content,\n subject: options?.subject,\n description: options?.description,\n };\n\n this.templates.set(name, template);\n }\n\n render(opts: {\n templateData?: string;\n templateName?: string;\n data: Record<string, unknown>;\n requireValidate?: boolean;\n format?: TMailTemplateFormat;\n }): string {\n const { templateData, templateName, data, requireValidate, format } = opts;\n\n if (!templateData && !templateName) {\n throw getError({ message: 'Either templateName or templateData must be provided' });\n }\n\n let content = templateData;\n\n if (!content && templateName) {\n const template = this.templates.get(templateName);\n\n if (!template) {\n throw getError({\n error: MailErrors.TEMPLATE_NOT_FOUND,\n message: `Template not found: ${templateName}`,\n });\n }\n\n this.logger.for(this.render.name).debug('Rendering template: %s', templateName);\n\n content = template.content;\n }\n\n if (content === undefined) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Template has no content: ${templateName}`,\n });\n }\n\n return this.renderSimpleTemplate(content, data, { requireValidate, format });\n }\n\n getTemplate(name: string): ITemplate | undefined {\n return this.templates.get(name);\n }\n\n listTemplates(): ITemplate[] {\n return Array.from(this.templates.values());\n }\n\n hasTemplate(name: string): boolean {\n return this.templates.has(name);\n }\n\n removeTemplate(name: string): boolean {\n this.logger.for(this.removeTemplate.name).info('Removing template: %s', name);\n\n return this.templates.delete(name);\n }\n\n clearTemplates(): void {\n this.logger.for(this.clearTemplates.name).info('Clearing all templates');\n this.templates.clear();\n }\n\n validateTemplateData(opts: { template: string; data: Record<string, unknown> }): {\n isValid: boolean;\n missingKeys: string[];\n allKeys: string[];\n } {\n const { template, data } = opts;\n const allKeys: string[] = [];\n const missingKeys: string[] = [];\n\n for (const match of template.matchAll(PLACEHOLDER)) {\n const key = match[1] ?? match[2];\n\n if (allKeys.includes(key)) {\n continue;\n }\n\n allKeys.push(key);\n\n const value = this.getNestedValue(data, key);\n\n if (value === undefined || value === null) {\n missingKeys.push(key);\n }\n }\n\n const isValid = missingKeys.length === 0;\n\n if (!isValid) {\n this.logger\n .for(this.validateTemplateData.name)\n .warn('Template validation failed | Missing keys: %s', missingKeys.join(', '));\n }\n\n return { isValid, missingKeys, allKeys };\n }\n\n renderSimpleTemplate(\n template: string,\n data: Record<string, unknown>,\n opts?: { requireValidate?: boolean; format?: TMailTemplateFormat },\n ): string {\n if (opts?.requireValidate) {\n const validation = this.validateTemplateData({ template, data });\n\n if (!validation.isValid) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Missing template data for keys: ${validation.missingKeys.join(', ')}`,\n });\n }\n }\n\n const isHtml = (opts?.format ?? MailTemplateFormats.HTML) === MailTemplateFormats.HTML;\n\n return template.replace(PLACEHOLDER, (match, tripleKey?: string, doubleKey?: string) => {\n const key = tripleKey ?? doubleKey ?? '';\n const value = this.getNestedValue(data, key);\n\n if (value === undefined || value === null) {\n this.logger.for(this.renderSimpleTemplate.name).warn('Missing value for key: %s', key);\n\n return match;\n }\n\n // `{{{key}}}` inserts as it is; `{{key}}` is escaped for HTML.\n return isHtml && tripleKey === undefined ? Bun.escapeHTML(String(value)) : String(value);\n });\n }\n\n /** Reads own properties only: `{{constructor}}` or `{{__proto__.x}}` must not reach the prototype chain. */\n private getNestedValue(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((current, key) => {\n return current !== null && typeof current === 'object' && Object.hasOwn(current, key)\n ? Reflect.get(current, key)\n : undefined;\n }, obj);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"template.service.js","sourceRoot":"","sources":["../../../../../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nimport type {\n IMailTemplateEngine,\n ITemplate,\n TMailTemplateFormat,\n TMailTemplateMissing,\n} from '../common';\nimport { MailErrors } from '../common';\nimport { MailTemplateRenderer } from '../utilities';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** In-memory template store and renderer. Templates registered here are lost on restart. */\nexport class TemplateEngineService extends BaseService implements IMailTemplateEngine {\n private templates: Map<string, ITemplate> = new Map();\n\n constructor() {\n super({ scope: TemplateEngineService.name });\n this.logger.for(this.constructor.name).info('Template engine initialized');\n }\n\n registerTemplate(opts: { name: string; content: string; options?: Partial<ITemplate> }): void {\n const { name, content, options } = opts;\n this.logger.for(this.registerTemplate.name).info('Registering template: %s', name);\n\n const template: ITemplate = {\n name,\n content,\n subject: options?.subject,\n description: options?.description,\n };\n\n this.templates.set(name, template);\n }\n\n render(opts: {\n templateData?: string;\n templateName?: string;\n data: Record<string, unknown>;\n requireValidate?: boolean;\n missing?: TMailTemplateMissing;\n format?: TMailTemplateFormat;\n }): string {\n const { templateData, templateName, data, requireValidate, missing, format } = opts;\n\n if (!templateData && !templateName) {\n throw getError({ message: 'Either templateName or templateData must be provided' });\n }\n\n let content = templateData;\n\n if (!content && templateName) {\n const template = this.templates.get(templateName);\n\n if (!template) {\n throw getError({\n error: MailErrors.TEMPLATE_NOT_FOUND,\n message: `Template not found: ${templateName}`,\n });\n }\n\n this.logger.for(this.render.name).debug('Rendering template: %s', templateName);\n\n content = template.content;\n }\n\n if (content === undefined) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Template has no content: ${templateName}`,\n });\n }\n\n return this.renderSimpleTemplate(content, data, { requireValidate, missing, format });\n }\n\n getTemplate(name: string): ITemplate | undefined {\n return this.templates.get(name);\n }\n\n listTemplates(): ITemplate[] {\n return Array.from(this.templates.values());\n }\n\n hasTemplate(name: string): boolean {\n return this.templates.has(name);\n }\n\n removeTemplate(name: string): boolean {\n this.logger.for(this.removeTemplate.name).info('Removing template: %s', name);\n\n return this.templates.delete(name);\n }\n\n clearTemplates(): void {\n this.logger.for(this.clearTemplates.name).info('Clearing all templates');\n this.templates.clear();\n }\n\n validateTemplateData(opts: { template: string; data: Record<string, unknown> }): {\n isValid: boolean;\n missingKeys: string[];\n allKeys: string[];\n } {\n const { template, data } = opts;\n const { valueKeys, sectionKeys } = MailTemplateRenderer.readKeys({ template });\n // A section key is reported but never missing: an absent section is an optional block, not an error.\n const allKeys = [...valueKeys, ...sectionKeys.filter((key) => !valueKeys.includes(key))];\n const missingKeys = valueKeys.filter((key) => {\n const value = MailTemplateRenderer.read({ data, key });\n\n return value === undefined || value === null;\n });\n\n const isValid = missingKeys.length === 0;\n\n if (!isValid) {\n this.logger\n .for(this.validateTemplateData.name)\n .warn('Template validation failed | Missing keys: %s', missingKeys.join(', '));\n }\n\n return { isValid, missingKeys, allKeys };\n }\n\n renderSimpleTemplate(\n template: string,\n data: Record<string, unknown>,\n opts?: {\n requireValidate?: boolean;\n missing?: TMailTemplateMissing;\n format?: TMailTemplateFormat;\n },\n ): string {\n if (opts?.requireValidate) {\n const validation = this.validateTemplateData({ template, data });\n\n if (!validation.isValid) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Missing template data for keys: ${validation.missingKeys.join(', ')}`,\n });\n }\n }\n\n const emptyKeys: string[] = [];\n const rendered = MailTemplateRenderer.render({\n template,\n data,\n format: opts?.format,\n missing: opts?.missing,\n onEmpty: (key) => {\n if (!emptyKeys.includes(key)) {\n emptyKeys.push(key);\n }\n },\n });\n\n if (emptyKeys.length > 0) {\n // Keys only, never values: a value is the recipient's data.\n this.logger\n .for(this.renderSimpleTemplate.name)\n .warn('Template rendered with empty values | Keys: %s', emptyKeys.join(', '));\n }\n\n return rendered;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC","sourcesContent":["export * from './type.utility';\nexport * from './address.utility';\nexport * from './verification.utility';\nexport * from './mime.utility';\nexport * from './header.utility';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,6BAA6B,CAAC","sourcesContent":["export * from './type.utility';\nexport * from './address.utility';\nexport * from './verification.utility';\nexport * from './mime.utility';\nexport * from './header.utility';\nexport * from './template-renderer.utility';\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { TMailTemplateFormat, TMailTemplateMissing } from '../common/index.js';
|
|
2
|
+
/** Renders placeholders (escaped, raw and dotted) and sections (a list, a flag, its inverse): no partial, no lambda, no delimiter change, no code. */
|
|
3
|
+
export declare class MailTemplateRenderer {
|
|
4
|
+
private static invalid;
|
|
5
|
+
/** Splits a template into text, values and sections; a closing tag that does not match, a section left open and a tag this renderer does not have throw. */
|
|
6
|
+
private static parse;
|
|
7
|
+
/** The keys a template reads outside any section, and the keys of its sections (a section body reads the item first, so its keys are not the data's to check). */
|
|
8
|
+
static readKeys(opts: {
|
|
9
|
+
template: string;
|
|
10
|
+
}): {
|
|
11
|
+
valueKeys: string[];
|
|
12
|
+
sectionKeys: string[];
|
|
13
|
+
};
|
|
14
|
+
/** Own properties only, so a key such as `constructor` or `__proto__.x` never reaches the prototype chain. The first segment picks the innermost scope that has it. */
|
|
15
|
+
private static lookup;
|
|
16
|
+
/** The value of `key` in `data` (own properties only), or `undefined`. */
|
|
17
|
+
static read(opts: {
|
|
18
|
+
data: Record<string, unknown>;
|
|
19
|
+
key: string;
|
|
20
|
+
}): unknown;
|
|
21
|
+
static render(opts: {
|
|
22
|
+
template: string;
|
|
23
|
+
data: Record<string, unknown>;
|
|
24
|
+
format?: TMailTemplateFormat;
|
|
25
|
+
missing?: TMailTemplateMissing;
|
|
26
|
+
/** Called with the key of every placeholder that rendered empty because the data had no value (never the value). */
|
|
27
|
+
onEmpty?: (key: string) => void;
|
|
28
|
+
}): string;
|
|
29
|
+
private static renderNodes;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=template-renderer.utility.d.ts.map
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
2
|
+
import { MailErrors, MailTemplateFormats, MailTemplateMissingModes } from '../common/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* One tag: `{{{key}}}` (group 1), or a placeholder or a section tag (group 2 the sigil `#`, `^` or `/`, group 3 the key; a lone `.` is the current
|
|
5
|
+
* item). The last form only finds the start of a Mustache partial, comment, delimiter change or `&` tag: those are refused. Any other `{{` stays as written.
|
|
6
|
+
*/
|
|
7
|
+
const TAG = /\{\{\{\s*([\w.]+)\s*\}\}\}|\{\{\s*(?:([#^/])\s*)?([\w.]+)\s*\}\}|\{\{\s*[>=!&<]/g;
|
|
8
|
+
/** How many sections may be open at once: deeper than any real template, and a bound on the scope stack. */
|
|
9
|
+
const MAX_DEPTH = 64;
|
|
10
|
+
/** Renders placeholders (escaped, raw and dotted) and sections (a list, a flag, its inverse): no partial, no lambda, no delimiter change, no code. */
|
|
11
|
+
export class MailTemplateRenderer {
|
|
12
|
+
static invalid(opts) {
|
|
13
|
+
return getError({ error: MailErrors.TEMPLATE_INVALID, message: opts.message });
|
|
14
|
+
}
|
|
15
|
+
/** Splits a template into text, values and sections; a closing tag that does not match, a section left open and a tag this renderer does not have throw. */
|
|
16
|
+
static parse(opts) {
|
|
17
|
+
const { template } = opts;
|
|
18
|
+
const root = [];
|
|
19
|
+
const open = [];
|
|
20
|
+
let current = root;
|
|
21
|
+
let cursor = 0;
|
|
22
|
+
for (const match of template.matchAll(TAG)) {
|
|
23
|
+
const [source, rawKey, sigil, key] = match;
|
|
24
|
+
current.push({ type: 'text', text: template.slice(cursor, match.index) });
|
|
25
|
+
cursor = match.index + source.length;
|
|
26
|
+
if (rawKey === undefined && key === undefined) {
|
|
27
|
+
throw MailTemplateRenderer.invalid({ message: `Unsupported template tag: ${source}` });
|
|
28
|
+
}
|
|
29
|
+
if (sigil === '#' || sigil === '^') {
|
|
30
|
+
if (open.length >= MAX_DEPTH) {
|
|
31
|
+
throw MailTemplateRenderer.invalid({
|
|
32
|
+
message: `Template nests sections deeper than ${MAX_DEPTH}`,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const children = [];
|
|
36
|
+
current.push({ type: 'section', key, isInverted: sigil === '^', children });
|
|
37
|
+
open.push({ key, parent: current });
|
|
38
|
+
current = children;
|
|
39
|
+
}
|
|
40
|
+
else if (sigil === '/') {
|
|
41
|
+
const closing = open.pop();
|
|
42
|
+
if (closing?.key !== key) {
|
|
43
|
+
throw MailTemplateRenderer.invalid({
|
|
44
|
+
message: `Template closes {{/${key}}} but ${closing ? `{{#${closing.key}}} is open` : 'no section is open'}`,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
current = closing.parent;
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
current.push({ type: 'value', key: rawKey ?? key, isRaw: rawKey !== undefined, source });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (open.length > 0) {
|
|
54
|
+
throw MailTemplateRenderer.invalid({
|
|
55
|
+
message: `Template leaves {{#${open[open.length - 1].key}}} open`,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
current.push({ type: 'text', text: template.slice(cursor) });
|
|
59
|
+
return root;
|
|
60
|
+
}
|
|
61
|
+
/** The keys a template reads outside any section, and the keys of its sections (a section body reads the item first, so its keys are not the data's to check). */
|
|
62
|
+
static readKeys(opts) {
|
|
63
|
+
const valueKeys = [];
|
|
64
|
+
const sectionKeys = [];
|
|
65
|
+
const visit = (nodes, isTopLevel) => {
|
|
66
|
+
for (const node of nodes) {
|
|
67
|
+
if (node.type === 'value' &&
|
|
68
|
+
isTopLevel &&
|
|
69
|
+
node.key !== '.' &&
|
|
70
|
+
!valueKeys.includes(node.key)) {
|
|
71
|
+
valueKeys.push(node.key);
|
|
72
|
+
}
|
|
73
|
+
if (node.type === 'section') {
|
|
74
|
+
if (!sectionKeys.includes(node.key)) {
|
|
75
|
+
sectionKeys.push(node.key);
|
|
76
|
+
}
|
|
77
|
+
visit(node.children, false);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
visit(MailTemplateRenderer.parse(opts), true);
|
|
82
|
+
return { valueKeys, sectionKeys };
|
|
83
|
+
}
|
|
84
|
+
/** Own properties only, so a key such as `constructor` or `__proto__.x` never reaches the prototype chain. The first segment picks the innermost scope that has it. */
|
|
85
|
+
static lookup(opts) {
|
|
86
|
+
const { scopes, key } = opts;
|
|
87
|
+
if (key === '.') {
|
|
88
|
+
return scopes[scopes.length - 1];
|
|
89
|
+
}
|
|
90
|
+
const [head, ...rest] = key.split('.');
|
|
91
|
+
let start;
|
|
92
|
+
for (let index = scopes.length - 1; index >= 0; index -= 1) {
|
|
93
|
+
const scope = scopes[index];
|
|
94
|
+
if (scope !== null && typeof scope === 'object' && Object.hasOwn(scope, head)) {
|
|
95
|
+
start = Reflect.get(scope, head);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return rest.reduce((current, segment) => current !== null && typeof current === 'object' && Object.hasOwn(current, segment)
|
|
100
|
+
? Reflect.get(current, segment)
|
|
101
|
+
: undefined, start);
|
|
102
|
+
}
|
|
103
|
+
/** The value of `key` in `data` (own properties only), or `undefined`. */
|
|
104
|
+
static read(opts) {
|
|
105
|
+
return MailTemplateRenderer.lookup({ scopes: [opts.data], key: opts.key });
|
|
106
|
+
}
|
|
107
|
+
static render(opts) {
|
|
108
|
+
const { template, data, format = MailTemplateFormats.HTML, missing = MailTemplateMissingModes.EMPTY, onEmpty, } = opts;
|
|
109
|
+
return MailTemplateRenderer.renderNodes({
|
|
110
|
+
nodes: MailTemplateRenderer.parse({ template }),
|
|
111
|
+
scopes: [data],
|
|
112
|
+
isHtml: format === MailTemplateFormats.HTML,
|
|
113
|
+
missing,
|
|
114
|
+
onEmpty,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
static renderNodes(opts) {
|
|
118
|
+
const { nodes, scopes, isHtml, missing, onEmpty } = opts;
|
|
119
|
+
let out = '';
|
|
120
|
+
for (const node of nodes) {
|
|
121
|
+
if (node.type === 'text') {
|
|
122
|
+
out += node.text;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const value = MailTemplateRenderer.lookup({ scopes, key: node.key });
|
|
126
|
+
if (typeof value === 'function') {
|
|
127
|
+
throw MailTemplateRenderer.invalid({
|
|
128
|
+
message: `Template value is a function: ${node.key}`,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
if (node.type === 'section') {
|
|
132
|
+
const isEmpty = !value || (Array.isArray(value) && value.length === 0);
|
|
133
|
+
if (node.isInverted) {
|
|
134
|
+
out += isEmpty
|
|
135
|
+
? MailTemplateRenderer.renderNodes({
|
|
136
|
+
nodes: node.children,
|
|
137
|
+
scopes,
|
|
138
|
+
isHtml,
|
|
139
|
+
missing,
|
|
140
|
+
onEmpty,
|
|
141
|
+
})
|
|
142
|
+
: '';
|
|
143
|
+
}
|
|
144
|
+
else if (!isEmpty) {
|
|
145
|
+
// A list repeats per item, anything else truthy renders once; `{{.}}` is the item, and its keys come before the outer ones.
|
|
146
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
147
|
+
out += MailTemplateRenderer.renderNodes({
|
|
148
|
+
nodes: node.children,
|
|
149
|
+
scopes: [...scopes, item],
|
|
150
|
+
isHtml,
|
|
151
|
+
missing,
|
|
152
|
+
onEmpty,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (value === undefined || value === null) {
|
|
159
|
+
if (missing === MailTemplateMissingModes.THROW) {
|
|
160
|
+
throw getError({
|
|
161
|
+
error: MailErrors.INVALID_CONFIGURATION,
|
|
162
|
+
message: `Missing template data for keys: ${node.key}`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
if (missing === MailTemplateMissingModes.KEEP) {
|
|
166
|
+
out += node.source;
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
onEmpty?.(node.key);
|
|
170
|
+
}
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (typeof value === 'object') {
|
|
174
|
+
throw MailTemplateRenderer.invalid({
|
|
175
|
+
message: `Template value is an object or a list, not text: ${node.key} | resolve it (a locale, a date) before rendering`,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
// `{{{key}}}` inserts as it is; `{{key}}` is escaped for HTML.
|
|
179
|
+
out += isHtml && !node.isRaw ? Bun.escapeHTML(String(value)) : String(value);
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=template-renderer.utility.js.map
|