@venizia/ignis 0.4.8-15 → 0.4.8-17
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.map +1 -1
- package/dist/esm/components/api-reference/common/types.d.ts +6 -3
- package/dist/esm/components/api-reference/common/types.js.map +1 -1
- package/dist/esm/components/api-reference/component.js +8 -3
- package/dist/esm/components/api-reference/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/component.js +2 -1
- package/dist/esm/components/auth/authenticate/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +2 -2
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +5 -3
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +18 -1
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
- package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +1 -2
- package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
- package/dist/esm/components/mail/common/types/message.d.ts +4 -4
- package/dist/esm/components/mail/common/types/message.js.map +1 -1
- package/dist/esm/components/mail/common/types/options.d.ts +54 -10
- package/dist/esm/components/mail/common/types/options.js.map +1 -1
- package/dist/esm/components/mail/common/types/template.d.ts +2 -2
- package/dist/esm/components/mail/common/types/template.js.map +1 -1
- package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js +7 -2
- package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js.map +1 -1
- package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.d.ts +2 -3
- package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
- package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.d.ts +2 -3
- package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js.map +1 -1
- package/dist/esm/components/mail/services/mail.service.d.ts +1 -2
- package/dist/esm/components/mail/services/mail.service.js.map +1 -1
- package/dist/esm/components/mail/services/template.service.d.ts +3 -4
- package/dist/esm/components/mail/services/template.service.js +1 -1
- package/dist/esm/components/mail/services/template.service.js.map +1 -1
- package/dist/esm/components/mail/utilities/header.utility.d.ts +1 -1
- package/dist/esm/components/mail/utilities/header.utility.js +1 -1
- package/dist/esm/components/mail/utilities/header.utility.js.map +1 -1
- package/dist/esm/components/mail/utilities/type.utility.d.ts +2 -3
- package/dist/esm/components/mail/utilities/type.utility.js +6 -7
- package/dist/esm/components/mail/utilities/type.utility.js.map +1 -1
- package/dist/esm/components/socket-io/handlers/bun.handler.d.ts +13 -3
- package/dist/esm/components/socket-io/handlers/bun.handler.js.map +1 -1
- package/dist/esm/components/static-asset/common/types.d.ts +35 -13
- package/dist/esm/components/static-asset/common/types.js.map +1 -1
- package/dist/esm/components/static-asset/controller/factory.d.ts +2 -2
- package/dist/esm/components/static-asset/controller/routes/context.d.ts +4 -3
- package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/meta-link.utility.d.ts +5 -5
- package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +3 -11
- package/dist/esm/components/static-asset/utilities/toggle.utility.js +3 -14
- package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -1
- package/dist/esm/testing/assert-application-boots.d.ts +2 -2
- package/dist/esm/testing/assert-application-boots.js +6 -2
- package/dist/esm/testing/assert-application-boots.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":"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,C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AM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QAExC,6FAA6F;QAC7F,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,YAAY,CAAC,aAAa,CAAC;QACpC,CAAC;QAED,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;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 { type AnyType } from '@venizia/ignis-helpers/common';\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, AnyType>;\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,MAA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,YAAY,CAAC,aAAa,CAAC;QACpC,CAAC;QAED,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;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,6 +1,5 @@
|
|
|
1
1
|
import { BaseService } from '@venizia/ignis-kernel';
|
|
2
2
|
import type { IMailTemplateEngine, ITemplate, TMailTemplateFormat } from '../common/index.js';
|
|
3
|
-
import type { AnyType } from '@venizia/ignis-helpers/common';
|
|
4
3
|
/** In-memory template store and renderer. Templates registered here are lost on restart. */
|
|
5
4
|
export declare class TemplateEngineService extends BaseService implements IMailTemplateEngine {
|
|
6
5
|
private templates;
|
|
@@ -13,7 +12,7 @@ export declare class TemplateEngineService extends BaseService implements IMailT
|
|
|
13
12
|
render(opts: {
|
|
14
13
|
templateData?: string;
|
|
15
14
|
templateName?: string;
|
|
16
|
-
data: Record<string,
|
|
15
|
+
data: Record<string, unknown>;
|
|
17
16
|
requireValidate?: boolean;
|
|
18
17
|
format?: TMailTemplateFormat;
|
|
19
18
|
}): string;
|
|
@@ -24,13 +23,13 @@ export declare class TemplateEngineService extends BaseService implements IMailT
|
|
|
24
23
|
clearTemplates(): void;
|
|
25
24
|
validateTemplateData(opts: {
|
|
26
25
|
template: string;
|
|
27
|
-
data: Record<string,
|
|
26
|
+
data: Record<string, unknown>;
|
|
28
27
|
}): {
|
|
29
28
|
isValid: boolean;
|
|
30
29
|
missingKeys: string[];
|
|
31
30
|
allKeys: string[];
|
|
32
31
|
};
|
|
33
|
-
renderSimpleTemplate(template: string, data: Record<string,
|
|
32
|
+
renderSimpleTemplate(template: string, data: Record<string, unknown>, opts?: {
|
|
34
33
|
requireValidate?: boolean;
|
|
35
34
|
format?: TMailTemplateFormat;
|
|
36
35
|
}): string;
|
|
@@ -112,7 +112,7 @@ export class TemplateEngineService extends BaseService {
|
|
|
112
112
|
getNestedValue(obj, path) {
|
|
113
113
|
return path.split('.').reduce((current, key) => {
|
|
114
114
|
return current !== null && typeof current === 'object' && Object.hasOwn(current, key)
|
|
115
|
-
? current
|
|
115
|
+
? Reflect.get(current, key)
|
|
116
116
|
: undefined;
|
|
117
117
|
}, obj);
|
|
118
118
|
}
|
|
@@ -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;AAE5D,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,IAA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,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;gBACd,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 type { AnyType } from '@venizia/ignis-helpers/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, AnyType>;\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, AnyType> }): {\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, AnyType>,\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: AnyType, path: string) {\n return path.split('.').reduce((current, key) => {\n return current !== null && typeof current === 'object' && Object.hasOwn(current, key)\n ? current[key]\n : undefined;\n }, obj);\n }\n}\n"]}
|
|
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,MAAM,QAAQ,GAAc;YAC1B,IAAI;YACJ,OAAO;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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,7 +1,7 @@
|
|
|
1
1
|
import { type IMailMessage } from '../common/index.js';
|
|
2
2
|
/** The one place a message is checked for header injection, before any transport sees it. A transport called directly skips it. */
|
|
3
3
|
export declare class MailHeaderUtility {
|
|
4
|
-
/** `value` is `unknown`: the message types end in `[key: string]:
|
|
4
|
+
/** `value` is `unknown`: the message types end in `[key: string]: unknown`, so nothing stops a controller forwarding a request body from putting an array where a string is declared. */
|
|
5
5
|
static assertValue(opts: {
|
|
6
6
|
field: string;
|
|
7
7
|
value: unknown;
|
|
@@ -6,7 +6,7 @@ const HEADER_NAME_PATTERN = /^[\x21-\x39\x3b-\x7e]+$/;
|
|
|
6
6
|
const HEADER_VALUE_FORBIDDEN = /[\r\n\0]/;
|
|
7
7
|
/** The one place a message is checked for header injection, before any transport sees it. A transport called directly skips it. */
|
|
8
8
|
export class MailHeaderUtility {
|
|
9
|
-
/** `value` is `unknown`: the message types end in `[key: string]:
|
|
9
|
+
/** `value` is `unknown`: the message types end in `[key: string]: unknown`, so nothing stops a controller forwarding a request body from putting an array where a string is declared. */
|
|
10
10
|
static assertValue(opts) {
|
|
11
11
|
const { field, value } = opts;
|
|
12
12
|
if (typeof value === 'string' && !HEADER_VALUE_FORBIDDEN.test(value)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"header.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/header.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAqB,MAAM,WAAW,CAAC;AAE1D,sFAAsF;AACtF,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AAEtD,oJAAoJ;AACpJ,MAAM,sBAAsB,GAAG,UAAU,CAAC;AAE1C,mIAAmI;AACnI,MAAM,OAAO,iBAAiB;IAC5B,
|
|
1
|
+
{"version":3,"file":"header.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/header.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAqB,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AC,CAAC;YACxD,CAAC;QACH,CAAC;QAED,iBAAiB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAEpE,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,CAAC;YAC1D,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACpC,MAAM,QAAQ,CAAC;oBACb,KAAK,EAAE,UAAU,CAAC,cAAc;oBAChC,OAAO,EAAE,6EAA6E;iBACvF,CAAC,CAAC;YACL,CAAC;YAED,iBAAiB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,WAAW,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport { MailErrors, type IMailMessage } from '../common';\n\n/** Printable ASCII without the colon: what RFC 5322 allows in a header field name. */\nconst HEADER_NAME_PATTERN = /^[\\x21-\\x39\\x3b-\\x7e]+$/;\n\n/** A value spliced into a header line cannot hold a line break or NUL: it would break out of its line and forge headers or smuggle body content. */\nconst HEADER_VALUE_FORBIDDEN = /[\\r\\n\\0]/;\n\n/** The one place a message is checked for header injection, before any transport sees it. A transport called directly skips it. */\nexport class MailHeaderUtility {\n /** `value` is `unknown`: the message types end in `[key: string]: unknown`, so nothing stops a controller forwarding a request body from putting an array where a string is declared. */\n static assertValue(opts: { field: string; value: unknown }): void {\n const { field, value } = opts;\n\n if (typeof value === 'string' && !HEADER_VALUE_FORBIDDEN.test(value)) {\n return;\n }\n\n throw getError({\n error: MailErrors.INVALID_HEADER,\n message: `Invalid mail header | ${field} must be a string without line breaks or control characters`,\n });\n }\n\n /** Every address field, the subject and the custom headers, names included. */\n static assert(opts: { message: IMailMessage }): void {\n const { from, to, cc, bcc, replyTo, subject, headers } = opts.message;\n const addresses = { from, to, cc, bcc, replyTo };\n\n for (const [field, value] of Object.entries(addresses)) {\n if (value === undefined || value === null) {\n continue;\n }\n\n for (const item of Array.isArray(value) ? value : [value]) {\n MailHeaderUtility.assertValue({ field, value: item });\n }\n }\n\n MailHeaderUtility.assertValue({ field: 'subject', value: subject });\n\n for (const [name, value] of Object.entries(headers ?? {})) {\n if (!HEADER_NAME_PATTERN.test(name)) {\n throw getError({\n error: MailErrors.INVALID_HEADER,\n message: 'Invalid mail header | a header name must be printable ASCII without a colon',\n });\n }\n\n MailHeaderUtility.assertValue({ field: `headers.${name}`, value });\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { AnyType } from '@venizia/ignis-helpers/common';
|
|
2
1
|
import type { IMailTransport, TMailOptions } from '../common/index.js';
|
|
3
2
|
/**
|
|
4
3
|
* Type guards for the mail component. Each takes its value as a positional parameter, not an options
|
|
@@ -7,8 +6,8 @@ import type { IMailTransport, TMailOptions } from '../common/index.js';
|
|
|
7
6
|
*/
|
|
8
7
|
export declare class MailTypeUtility {
|
|
9
8
|
/** Whether `value` is a transport: `send` and `verify` are functions, and `close` is a function or absent. */
|
|
10
|
-
static isTransport(value:
|
|
9
|
+
static isTransport(value: unknown): value is IMailTransport;
|
|
11
10
|
/** Whether `options` has a string `provider` and a truthy `config`; the shape of `config` is not checked. */
|
|
12
|
-
static isValidOptions(options:
|
|
11
|
+
static isValidOptions(options: unknown): options is TMailOptions;
|
|
13
12
|
}
|
|
14
13
|
//# sourceMappingURL=type.utility.d.ts.map
|
|
@@ -9,14 +9,14 @@ export class MailTypeUtility {
|
|
|
9
9
|
if (!value || typeof value !== 'object') {
|
|
10
10
|
return false;
|
|
11
11
|
}
|
|
12
|
-
|
|
13
|
-
if (typeof transport.send !== 'function') {
|
|
12
|
+
if (typeof Reflect.get(value, 'send') !== 'function') {
|
|
14
13
|
return false;
|
|
15
14
|
}
|
|
16
|
-
if (typeof
|
|
15
|
+
if (typeof Reflect.get(value, 'verify') !== 'function') {
|
|
17
16
|
return false;
|
|
18
17
|
}
|
|
19
|
-
|
|
18
|
+
const close = Reflect.get(value, 'close');
|
|
19
|
+
if (close !== undefined && typeof close !== 'function') {
|
|
20
20
|
return false;
|
|
21
21
|
}
|
|
22
22
|
return true;
|
|
@@ -26,11 +26,10 @@ export class MailTypeUtility {
|
|
|
26
26
|
if (!options || typeof options !== 'object') {
|
|
27
27
|
return false;
|
|
28
28
|
}
|
|
29
|
-
|
|
30
|
-
if (typeof opts.provider !== 'string') {
|
|
29
|
+
if (typeof Reflect.get(options, 'provider') !== 'string') {
|
|
31
30
|
return false;
|
|
32
31
|
}
|
|
33
|
-
if (!
|
|
32
|
+
if (!Reflect.get(options, 'config')) {
|
|
34
33
|
return false;
|
|
35
34
|
}
|
|
36
35
|
return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/type.utility.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"type.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/type.utility.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAC1B,8GAA8G;IAC9G,MAAM,CAAC,WAAW,CAAC,KAAc;QAC/B,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACxC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,UAAU,EAAE,CAAC;YACrD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,KAAK,UAAU,EAAE,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,KAAK,GAAY,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QAEnD,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED,6GAA6G;IAC7G,MAAM,CAAC,cAAc,CAAC,OAAgB;QACpC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,KAAK,QAAQ,EAAE,CAAC;YACzD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC;YACpC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import type { IMailTransport, TMailOptions } from '../common';\n\n/**\n * Type guards for the mail component. Each takes its value as a positional parameter, not an options\n * object (V-C-02): a type predicate narrows its own parameter, so `{ value }` could not narrow the\n * caller's variable.\n */\nexport class MailTypeUtility {\n /** Whether `value` is a transport: `send` and `verify` are functions, and `close` is a function or absent. */\n static isTransport(value: unknown): value is IMailTransport {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n if (typeof Reflect.get(value, 'send') !== 'function') {\n return false;\n }\n\n if (typeof Reflect.get(value, 'verify') !== 'function') {\n return false;\n }\n\n const close: unknown = Reflect.get(value, 'close');\n\n if (close !== undefined && typeof close !== 'function') {\n return false;\n }\n\n return true;\n }\n\n /** Whether `options` has a string `provider` and a truthy `config`; the shape of `config` is not checked. */\n static isValidOptions(options: unknown): options is TMailOptions {\n if (!options || typeof options !== 'object') {\n return false;\n }\n\n if (typeof Reflect.get(options, 'provider') !== 'string') {\n return false;\n }\n\n if (!Reflect.get(options, 'config')) {\n return false;\n }\n\n return true;\n }\n}\n"]}
|
|
@@ -5,11 +5,21 @@ export declare class SocketIOBunHandler {
|
|
|
5
5
|
static createEngine(opts: {
|
|
6
6
|
serverOptions: Partial<ServerOptions>;
|
|
7
7
|
}): Promise<{
|
|
8
|
-
engine:
|
|
9
|
-
engineHandler:
|
|
8
|
+
engine: import("@socket.io/bun-engine").Server;
|
|
9
|
+
engineHandler: {
|
|
10
|
+
fetch: (req: Request, server: Bun.Server<import("@socket.io/bun-engine").WebSocketData>) => Response | Promise<Response>;
|
|
11
|
+
websocket: {
|
|
12
|
+
open: (ws: import("@socket.io/bun-engine").BunWebSocket) => void;
|
|
13
|
+
message: (ws: import("@socket.io/bun-engine").BunWebSocket, message: import("@socket.io/bun-engine").RawData) => void;
|
|
14
|
+
close: (ws: import("@socket.io/bun-engine").BunWebSocket, code: number, message: string) => void;
|
|
15
|
+
maxPayloadLength: number;
|
|
16
|
+
};
|
|
17
|
+
idleTimeout: number;
|
|
18
|
+
maxRequestBodySize: number;
|
|
19
|
+
};
|
|
10
20
|
}>;
|
|
11
21
|
static createFetchHandler(opts: {
|
|
12
|
-
engine:
|
|
22
|
+
engine: Awaited<ReturnType<typeof SocketIOBunHandler.createEngine>>['engine'];
|
|
13
23
|
enginePath: string;
|
|
14
24
|
honoServer: OpenAPIHono;
|
|
15
25
|
}): (req: Request, server: TBunServerInstance) => Response | Promise<Response>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bun.handler.js","sourceRoot":"","sources":["../../../../../src/components/socket-io/handlers/bun.handler.ts"],"names":[],"mappings":"AAIA,MAAM,OAAO,kBAAkB;IAC7B,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,
|
|
1
|
+
{"version":3,"file":"bun.handler.js","sourceRoot":"","sources":["../../../../../src/components/socket-io/handlers/bun.handler.ts"],"names":[],"mappings":"AAIA,MAAM,OAAO,kBAAkB;IAC7B,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,IAA+C;QACvE,MAAM,EAAE,aAAa,E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,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAClF,CAAC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { OpenAPIHono } from '@hono/zod-openapi';\nimport type { TBunServerInstance } from '@/base/applications';\nimport type { ServerOptions } from 'socket.io';\n\nexport class SocketIOBunHandler {\n static async createEngine(opts: { serverOptions: Partial<ServerOptions> }) {\n const { serverOptions } = opts;\n const { Server: BunEngine } = await import('@socket.io/bun-engine');\n\n // Extract cors fields explicitly to bridge socket.io/bun-engine type differences\n const corsConfig = typeof serverOptions.cors === 'object' ? serverOptions.cors : undefined;\n const engine = new BunEngine({\n path: serverOptions.path ?? '/socket.io/',\n ...(corsConfig && {\n cors: {\n origin: corsConfig.origin as string | RegExp | (string | RegExp)[] | undefined,\n methods: corsConfig.methods,\n credentials: corsConfig.credentials,\n allowedHeaders: corsConfig.allowedHeaders,\n exposedHeaders: corsConfig.exposedHeaders,\n maxAge: corsConfig.maxAge,\n },\n }),\n });\n\n const engineHandler = engine.handler();\n\n return { engine, engineHandler };\n }\n\n static createFetchHandler(opts: {\n engine: Awaited<ReturnType<typeof SocketIOBunHandler.createEngine>>['engine'];\n enginePath: string;\n honoServer: OpenAPIHono;\n }): (req: Request, server: TBunServerInstance) => Response | Promise<Response> {\n const { engine, enginePath, honoServer } = opts;\n\n return (req: Request, server: TBunServerInstance): Response | Promise<Response> => {\n const url = new URL(req.url);\n\n if (!url.pathname.startsWith(enginePath)) {\n return honoServer.fetch(req, server);\n }\n\n return engine.handleRequest(req, server) ?? new Response(null, { status: 404 });\n };\n }\n}\n"]}
|
|
@@ -1,22 +1,17 @@
|
|
|
1
1
|
import type { BaseRestController, IAuthRouteConfig, TRouteAuthConfig, TRouteContext } from '../../../base/index.js';
|
|
2
2
|
import type { z } from '@hono/zod-openapi';
|
|
3
3
|
import type { IDuration } from '@venizia/ignis-helpers/common';
|
|
4
|
-
import type {
|
|
4
|
+
import type { TTableInsert, TTableObject } from '@venizia/ignis-connectors/postgres';
|
|
5
|
+
import type { TWhere } from '@venizia/ignis-filter';
|
|
6
|
+
import type { TToggle } from '@venizia/ignis-kernel';
|
|
5
7
|
import type { DiskHelper, IBucketRef, IFileStat, IObjectLocation, IObjectRef, IStorageHelper, IUploadResult, StorageTypes, TUploadNaming } from '@venizia/ignis-helpers';
|
|
6
8
|
import type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';
|
|
7
9
|
import type { TConstValue, TValueOrAsyncResolver, ValueOrPromise } from '@venizia/ignis-helpers/common';
|
|
8
|
-
import type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models/index.js';
|
|
10
|
+
import type { TMetaLink, TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models/index.js';
|
|
9
11
|
import type { StaticAssetRouteKeys, TStaticAssetTokenStage } from './constants.js';
|
|
10
12
|
import type { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
|
|
11
|
-
/**
|
|
12
|
-
|
|
13
|
-
* the options. One shape for every switch, so an option is never read from a feature that is off.
|
|
14
|
-
*/
|
|
15
|
-
export type TToggle<Options extends object = Record<never, never>> = {
|
|
16
|
-
use: false;
|
|
17
|
-
} | ({
|
|
18
|
-
use: true;
|
|
19
|
-
} & Options);
|
|
13
|
+
/** The toggle type, shared with the controllers: defined in the kernel. */
|
|
14
|
+
export type { TToggle };
|
|
20
15
|
/** The storage backends a static asset entry can serve from: the helpers that declare one. */
|
|
21
16
|
export type TStaticAssetStorageType = typeof StorageTypes.DISK | typeof StorageTypes.BUN_S3;
|
|
22
17
|
/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written - the scope and the default naming - so the hook may keep it, extend it or ignore it. */
|
|
@@ -162,9 +157,37 @@ export interface IStaticAssetValidateResult<Issue> extends IStaticAssetValidatio
|
|
|
162
157
|
export type TStaticAssetUploadPolicyRequest = {
|
|
163
158
|
files: TStaticAssetUploadPolicyFile[];
|
|
164
159
|
};
|
|
160
|
+
/** The repository verbs the component calls, on MetaLink rows. A `DefaultCRUDRepository` over any `TMetaLinkCompatibleSchema` table satisfies it, and so does a small fake in a test. The contract checks the select row only (see the static-asset usage page for what that leaves to the table). */
|
|
161
|
+
export interface IMetaLinkRepository {
|
|
162
|
+
create(opts: {
|
|
163
|
+
data: TTableInsert<TMetaLinkSchema>;
|
|
164
|
+
}): Promise<{
|
|
165
|
+
count: number;
|
|
166
|
+
data: TMetaLink;
|
|
167
|
+
}>;
|
|
168
|
+
updateBy(opts: {
|
|
169
|
+
data: Partial<TTableInsert<TMetaLinkSchema>>;
|
|
170
|
+
where: TWhere<TMetaLink>;
|
|
171
|
+
}): Promise<{
|
|
172
|
+
count: number;
|
|
173
|
+
data: TMetaLink[] | null;
|
|
174
|
+
}>;
|
|
175
|
+
updateById(opts: {
|
|
176
|
+
id: string;
|
|
177
|
+
data: Partial<TTableInsert<TMetaLinkSchema>>;
|
|
178
|
+
}): Promise<{
|
|
179
|
+
count: number;
|
|
180
|
+
data: TMetaLink;
|
|
181
|
+
}>;
|
|
182
|
+
deleteBy(opts: {
|
|
183
|
+
where: TWhere<TMetaLink>;
|
|
184
|
+
}): Promise<{
|
|
185
|
+
count: number;
|
|
186
|
+
}>;
|
|
187
|
+
}
|
|
165
188
|
/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */
|
|
166
189
|
export type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {
|
|
167
|
-
repository: TValueOrAsyncResolver<
|
|
190
|
+
repository: TValueOrAsyncResolver<IMetaLinkRepository>;
|
|
168
191
|
createMetaLink?: (opts: {
|
|
169
192
|
uploadResult: IUploadResult;
|
|
170
193
|
fileStat: IFileStat;
|
|
@@ -297,5 +320,4 @@ export interface IStaticAssetCommitTokenPayload {
|
|
|
297
320
|
/** Present from `VALIDATED` on: `commit` copies only content that still matches it. */
|
|
298
321
|
pin?: IStaticAssetPin;
|
|
299
322
|
}
|
|
300
|
-
export {};
|
|
301
323
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { BaseRestController, IAuthRouteConfig, TRouteAuthConfig, TRouteContext } from '@/base';\nimport type { z } from '@hono/zod-openapi';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport type { DefaultCRUDRepository, TTableObject } from '@venizia/ignis-connectors/postgres';\nimport type {\n DiskHelper,\n IBucketRef,\n IFileStat,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n StorageTypes,\n TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';\nimport type {\n TConstValue,\n TValueOrAsyncResolver,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\nimport type { StaticAssetRouteKeys, TStaticAssetTokenStage } from './constants';\nimport type { StaticAssetPinnedFile } from '../utilities/pinned-file.utility';\n\n/**\n * A feature that is on or off. `{ use: false }` is the whole off state; `{ use: true, ... }` carries\n * the options. One shape for every switch, so an option is never read from a feature that is off.\n */\nexport type TToggle<Options extends object = Record<never, never>> =\n | { use: false }\n | ({ use: true } & Options);\n\n/** The storage backends a static asset entry can serve from: the helpers that declare one. */\nexport type TStaticAssetStorageType = typeof StorageTypes.DISK | typeof StorageTypes.BUN_S3;\n\n/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written - the scope and the default naming - so the hook may keep it, extend it or ignore it. */\nexport type TStaticAssetObjectKeyResolver = (opts: {\n bucket: IBucketRef;\n file: TUploadNaming;\n defaultKey: string;\n}) => string;\n\n/** Adds routes of the application's own. Registration order decides a path collision, so the same shape serves both the before and the after hook. */\nexport type TStaticAssetDefineExtraRoutes = (opts: {\n controller: BaseRestController;\n helper: IStorageHelper;\n basePath: string;\n}) => void;\n\n/** Path parameters of the object routes. */\nexport type TStaticAssetObjectParams = { objectName: string };\n\n/** Labels recorded on the MetaLink row of an uploaded object. */\nexport type TStaticAssetUploadLabels = {\n principalType?: string;\n principalId?: string;\n variant?: string;\n /** Display order within the principal. Caller-supplied: deriving it would be a non-atomic read of `max(sequence)` then a write of `max + 1`. */\n sequence?: number;\n};\n\n/** Application-chosen strings the commit token signs for one file. The token is signed, not encrypted: no secrets. */\nexport type TStaticAssetTokenMetadata = Record<string, string>;\n\n/** One file of an upload-policy request. `metadata` is the client's hint: `resolvers.metadata` reads it, and only what that returns is signed. */\nexport type TStaticAssetUploadPolicyFile = {\n fileName: string;\n contentType?: string;\n size?: number;\n metadata?: TStaticAssetTokenMetadata;\n};\n\n/** The decisions of a direct upload that belong to the application, each made on a different call. */\nexport type TStaticAssetDirectUploadResolvers = {\n /**\n * Who the upload belongs to. Called on every direct-upload route: the policy route signs the\n * answer into the commit token, and the other routes refuse a token whose owner differs.\n */\n owner: (opts: { context: TRouteContext }) => ValueOrPromise<string>;\n\n /** Per file, at policy time: what the token signs for it, readable again at validate and commit. Absent, a client that sends `metadata` is refused. */\n metadata?: (opts: {\n context: TRouteContext;\n file: TStaticAssetUploadPolicyFile;\n }) => ValueOrPromise<TStaticAssetTokenMetadata>;\n\n commit?: {\n /** At commit time: the final key, in the same bucket and inside the `keyPrefix`. Absent keeps `defaultKey`. */\n destination?: (opts: {\n owner: string;\n metadata: TStaticAssetTokenMetadata;\n file: { fileName: string };\n defaultKey: string;\n }) => ValueOrPromise<{ key: string }>;\n };\n};\n\n/** Enables the signed-policy upload flow, where the client posts bytes straight to the storage and IGNIS only signs the permission and verifies the commit. */\nexport type TStaticAssetDirectUploadOptions = {\n /**\n * Who may use direct upload. Guards every direct-upload route. There is no safe default for a\n * route that hands out a write credential, so leaving it out is allowed only when the entry's\n * `auth` already authenticates or authorizes: then `auth` is the gate. With neither, the\n * component refuses to start.\n */\n authorize?: (opts: { context: TRouteContext }) => ValueOrPromise<boolean>;\n\n /** What the application decides about an upload; `owner` is required, the rest is optional. */\n resolvers: TStaticAssetDirectUploadResolvers;\n\n /** Signs the commit token. Keep it out of the repository and out of the client. */\n secretKey: string;\n\n /** The ceiling the policy carries as `content-length-range`. A signed PUT cannot express this at all, which is why this is a POST policy. */\n maxBytes: number;\n\n /**\n * The most files one upload-policy request may name; more is a 422.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /**\n * Where a policy may write: not empty, ends with `/`, made of valid key segments, and neither\n * inside the entry's `keyPrefix` nor containing it - a pending object must never be readable\n * through the entry's own routes. The final key is NEVER in a policy, so content cannot be\n * replaced after the commit. The lifecycle rule that collects abandoned uploads targets this prefix.\n *\n * @default 'pending/'\n */\n pendingPrefix?: string;\n\n expires?: {\n /**\n * How long the browser may post the bytes: the POST policy's lifetime.\n *\n * @default StoragePresignDefaults.POST_EXPIRES_IN\n */\n upload?: IDuration;\n\n /**\n * How long the commit token stays good, for validating and committing after the upload. The\n * pending object must outlive it, so the lifecycle rule on `pendingPrefix` has to be longer still.\n *\n * @default `upload`\n */\n commit?: IDuration;\n };\n\n /**\n * Checks the pending file. On, the component registers `POST {base}/upload-validate`, which\n * answers the token `commit` takes, and `commit` accepts no other.\n * Build it with `StaticAssetValidation.define`.\n */\n validation: TToggle<IStaticAssetValidation<z.ZodType>>;\n};\n\n/** What a validation answers: whether the file may be committed, and the problems the user should see. */\nexport interface IStaticAssetValidationResult<Issue> {\n isValid: boolean;\n issues: Issue[];\n}\n\n/**\n * The application's own check of an uploaded file, run on the PENDING object before anything is\n * committed. The component owns the route and the refusal; the application owns only this logic.\n * Build it with `StaticAssetValidation.define` so the handler is typed by `issueSchema`.\n */\nexport interface IStaticAssetValidation<IssueSchema extends z.ZodType> {\n /** The shape of ONE issue. It types the handler's answer and documents the route's response. */\n issueSchema: IssueSchema;\n\n /** Runs once per `upload-validate`. Read the file through `file`: every read is pinned to the content `commit` will copy. */\n handler: (opts: {\n file: StaticAssetPinnedFile;\n owner: string;\n metadata: TStaticAssetTokenMetadata;\n }) => ValueOrPromise<IStaticAssetValidationResult<z.infer<IssueSchema>>>;\n}\n\n/** What `validate` answers. `commitToken` is present only when the file is valid: it is the token `commit` takes. */\nexport interface IStaticAssetValidateResult<Issue> extends IStaticAssetValidationResult<Issue> {\n commitToken?: string;\n}\n\n/** Body of the upload policy route: the files the client intends to upload. */\nexport type TStaticAssetUploadPolicyRequest = { files: TStaticAssetUploadPolicyFile[] };\n\n/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */\nexport type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n repository: TValueOrAsyncResolver<DefaultCRUDRepository<Schema>>;\n createMetaLink?: (opts: {\n uploadResult: IUploadResult;\n fileStat: IFileStat;\n /** The caller's labels: form fields on an upload, beside the commit token on a direct one. */\n labels: TStaticAssetUploadLabels;\n }) => ValueOrPromise<{ count: number; data: TTableObject<Schema> }>;\n};\n\n/** The part of a built-in route an application may change. `authenticate` and `authorize` replace the entry's `auth` for this route, and `{ skip: true }` leaves it open. */\nexport type TStaticAssetRouteConfig = Partial<\n Omit<IAuthRouteConfig, 'method' | 'request' | 'responses' | 'authenticate' | 'authorize'>\n> &\n TRouteAuthConfig;\n\n/** Authentication and authorization for every built-in route of an entry; a route's own `authenticate`/`authorize` replaces it for that route. */\nexport type TStaticAssetAuth = TRouteAuthConfig & {\n /**\n * `{ use: true }` leaves `getObjectByName` and `downloadObjectByName` unauthenticated, so a\n * browser can show an image without a token. `listObjects` is NOT public: listing a bucket is not\n * reading an object.\n *\n * @default { use: false }\n */\n publicRead?: TToggle;\n};\n\n/** The name of a built-in route, the key of `routes`. */\nexport type TStaticAssetRouteKey = TConstValue<typeof StaticAssetRouteKeys>;\n\n/**\n * What each built-in route does: `{ use: false }` turns it off, `{ use: true, ... }` turns it on\n * with those overrides. A route left out is on as built.\n */\nexport type TStaticAssetRoutes = Partial<\n Record<TStaticAssetRouteKey, TToggle<TStaticAssetRouteConfig>>\n>;\n\n/** Uploading through the application: the browser sends the bytes to `POST /objects` and the application writes them to the storage. */\nexport type TStaticAssetServerUploadOptions = {\n /** Largest file the route accepts. Absent means no ceiling. Checked against `content-length` before the body is read, then per file after parsing. */\n maxBytes?: number;\n\n /**\n * The most file parts one request may carry; more is refused with 413 before anything is written.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /** The one hook that decides the key an uploaded file is stored under. Absent keeps the default naming. Under a `keyPrefix` a key outside the scope is refused, never rewritten. */\n objectKey?: TStaticAssetObjectKeyResolver;\n};\n\n/** Direct upload is a POST policy, which only S3 can sign, and its pending objects stay out of the served scope only when the entry has a `keyPrefix`. */\ntype TStaticAssetDirectUploadScope =\n | { keyPrefix?: string; directUpload: { use: false } }\n | { keyPrefix: string; directUpload: { use: true } & TStaticAssetDirectUploadOptions };\n\n/** The storage helper decides which direct upload shapes are possible. */\ntype TStaticAssetStorage =\n | ({ helper: BunS3Helper } & TStaticAssetDirectUploadScope)\n | { helper: DiskHelper; keyPrefix?: string; directUpload: { use: false } };\n\n/** One storage backend with its generated controller. Every switch is a toggle; a toggle left out is a type error, so nothing is on or off by accident. */\nexport type TStaticAssetEntry<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n basePath: string;\n\n /** The controller's name. Absent, it is derived from the entry's key. */\n name?: string;\n\n /** The single bucket every route uses. The function form is read per request, so an environment variable can be read lazily. */\n bucket: TValueOrAsyncResolver<string>;\n\n /**\n * The key scope this entry owns, e.g. `inventory/`. Every route refuses a key outside it as a\n * 404 without calling the storage, `listObjects` lists only inside it, and an upload key must\n * land inside it. `maxFolderDepth` counts the folders below it. Required with\n * `directUpload`: it keeps the pending prefix outside everything the routes serve.\n *\n * @default every key in the bucket\n */\n keyPrefix?: string;\n\n /**\n * Folders a key may nest below the `keyPrefix`, for every route of the entry: reads and deletes\n * too, so it holds for keys that arrive by direct upload or ingest.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n\n /**\n * `true` serves a raw nested object path (`/objects/photos/2024/f.jpg`) - a URL shape change; a percent-encoded path keeps working either way.\n *\n * @default false\n */\n rawObjectPath?: boolean;\n\n /** The link stored and returned for an object. Absent builds the URL of this controller's own object route. */\n link?: (opts: IObjectLocation) => string;\n\n /** Authentication and authorization of every built-in route of this entry. Absent leaves every route open; `publicRead` is the only way a read route is public on purpose. */\n auth?: TStaticAssetAuth;\n\n serverUpload: TToggle<TStaticAssetServerUploadOptions>;\n\n /** Every upload also writes a MetaLink row, and the object's deletion removes it. */\n metaLink: TToggle<TMetaLinkConfig<Schema>>;\n\n routes?: TStaticAssetRoutes;\n\n extend?: {\n /** Registered BEFORE every built-in route, so a literal path wins over the catch-all `rawObjectPath` produces. Hono matches in registration order. */\n before?: TStaticAssetDefineExtraRoutes;\n /** Registered after every built-in route. */\n after?: TStaticAssetDefineExtraRoutes;\n };\n} & TStaticAssetStorage;\n\n/** Static asset entries keyed by an application-chosen name; each key becomes one controller. */\nexport type TStaticAssetComponentOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> = Record<string, TStaticAssetEntry<Schema>>;\n\n/** The content a validation read: the ETag, and the version id when the storage has real versions. */\nexport interface IStaticAssetPin {\n etag: string;\n versionId?: string;\n}\n\n/**\n * What a commit token binds: the pending object a policy was issued for, when the grant dies and,\n * who it was issued to and the application's own metadata for the file.\n */\nexport interface IStaticAssetCommitTokenPayload {\n bucket: IBucketRef;\n object: IObjectRef;\n expiresAt: number;\n /** The token commits only for this owner. */\n owner: string;\n /** What `resolvers.metadata` returned for the file; `{}` without one. Signed, not encrypted. */\n metadata: TStaticAssetTokenMetadata;\n stage: TStaticAssetTokenStage;\n /** Present from `VALIDATED` on: `commit` copies only content that still matches it. */\n pin?: IStaticAssetPin;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { BaseRestController, IAuthRouteConfig, TRouteAuthConfig, TRouteContext } from '@/base';\nimport type { z } from '@hono/zod-openapi';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport type { TTableInsert, TTableObject } from '@venizia/ignis-connectors/postgres';\nimport type { TWhere } from '@venizia/ignis-filter';\nimport type { TToggle } from '@venizia/ignis-kernel';\nimport type {\n DiskHelper,\n IBucketRef,\n IFileStat,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n StorageTypes,\n TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';\nimport type {\n TConstValue,\n TValueOrAsyncResolver,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\nimport type { TMetaLink, TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\nimport type { StaticAssetRouteKeys, TStaticAssetTokenStage } from './constants';\nimport type { StaticAssetPinnedFile } from '../utilities/pinned-file.utility';\n\n/** The toggle type, shared with the controllers: defined in the kernel. */\nexport type { TToggle };\n\n/** The storage backends a static asset entry can serve from: the helpers that declare one. */\nexport type TStaticAssetStorageType = typeof StorageTypes.DISK | typeof StorageTypes.BUN_S3;\n\n/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written - the scope and the default naming - so the hook may keep it, extend it or ignore it. */\nexport type TStaticAssetObjectKeyResolver = (opts: {\n bucket: IBucketRef;\n file: TUploadNaming;\n defaultKey: string;\n}) => string;\n\n/** Adds routes of the application's own. Registration order decides a path collision, so the same shape serves both the before and the after hook. */\nexport type TStaticAssetDefineExtraRoutes = (opts: {\n controller: BaseRestController;\n helper: IStorageHelper;\n basePath: string;\n}) => void;\n\n/** Path parameters of the object routes. */\nexport type TStaticAssetObjectParams = { objectName: string };\n\n/** Labels recorded on the MetaLink row of an uploaded object. */\nexport type TStaticAssetUploadLabels = {\n principalType?: string;\n principalId?: string;\n variant?: string;\n /** Display order within the principal. Caller-supplied: deriving it would be a non-atomic read of `max(sequence)` then a write of `max + 1`. */\n sequence?: number;\n};\n\n/** Application-chosen strings the commit token signs for one file. The token is signed, not encrypted: no secrets. */\nexport type TStaticAssetTokenMetadata = Record<string, string>;\n\n/** One file of an upload-policy request. `metadata` is the client's hint: `resolvers.metadata` reads it, and only what that returns is signed. */\nexport type TStaticAssetUploadPolicyFile = {\n fileName: string;\n contentType?: string;\n size?: number;\n metadata?: TStaticAssetTokenMetadata;\n};\n\n/** The decisions of a direct upload that belong to the application, each made on a different call. */\nexport type TStaticAssetDirectUploadResolvers = {\n /**\n * Who the upload belongs to. Called on every direct-upload route: the policy route signs the\n * answer into the commit token, and the other routes refuse a token whose owner differs.\n */\n owner: (opts: { context: TRouteContext }) => ValueOrPromise<string>;\n\n /** Per file, at policy time: what the token signs for it, readable again at validate and commit. Absent, a client that sends `metadata` is refused. */\n metadata?: (opts: {\n context: TRouteContext;\n file: TStaticAssetUploadPolicyFile;\n }) => ValueOrPromise<TStaticAssetTokenMetadata>;\n\n commit?: {\n /** At commit time: the final key, in the same bucket and inside the `keyPrefix`. Absent keeps `defaultKey`. */\n destination?: (opts: {\n owner: string;\n metadata: TStaticAssetTokenMetadata;\n file: { fileName: string };\n defaultKey: string;\n }) => ValueOrPromise<{ key: string }>;\n };\n};\n\n/** Enables the signed-policy upload flow, where the client posts bytes straight to the storage and IGNIS only signs the permission and verifies the commit. */\nexport type TStaticAssetDirectUploadOptions = {\n /**\n * Who may use direct upload. Guards every direct-upload route. There is no safe default for a\n * route that hands out a write credential, so leaving it out is allowed only when the entry's\n * `auth` already authenticates or authorizes: then `auth` is the gate. With neither, the\n * component refuses to start.\n */\n authorize?: (opts: { context: TRouteContext }) => ValueOrPromise<boolean>;\n\n /** What the application decides about an upload; `owner` is required, the rest is optional. */\n resolvers: TStaticAssetDirectUploadResolvers;\n\n /** Signs the commit token. Keep it out of the repository and out of the client. */\n secretKey: string;\n\n /** The ceiling the policy carries as `content-length-range`. A signed PUT cannot express this at all, which is why this is a POST policy. */\n maxBytes: number;\n\n /**\n * The most files one upload-policy request may name; more is a 422.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /**\n * Where a policy may write: not empty, ends with `/`, made of valid key segments, and neither\n * inside the entry's `keyPrefix` nor containing it - a pending object must never be readable\n * through the entry's own routes. The final key is NEVER in a policy, so content cannot be\n * replaced after the commit. The lifecycle rule that collects abandoned uploads targets this prefix.\n *\n * @default 'pending/'\n */\n pendingPrefix?: string;\n\n expires?: {\n /**\n * How long the browser may post the bytes: the POST policy's lifetime.\n *\n * @default StoragePresignDefaults.POST_EXPIRES_IN\n */\n upload?: IDuration;\n\n /**\n * How long the commit token stays good, for validating and committing after the upload. The\n * pending object must outlive it, so the lifecycle rule on `pendingPrefix` has to be longer still.\n *\n * @default `upload`\n */\n commit?: IDuration;\n };\n\n /**\n * Checks the pending file. On, the component registers `POST {base}/upload-validate`, which\n * answers the token `commit` takes, and `commit` accepts no other.\n * Build it with `StaticAssetValidation.define`.\n */\n validation: TToggle<IStaticAssetValidation<z.ZodType>>;\n};\n\n/** What a validation answers: whether the file may be committed, and the problems the user should see. */\nexport interface IStaticAssetValidationResult<Issue> {\n isValid: boolean;\n issues: Issue[];\n}\n\n/**\n * The application's own check of an uploaded file, run on the PENDING object before anything is\n * committed. The component owns the route and the refusal; the application owns only this logic.\n * Build it with `StaticAssetValidation.define` so the handler is typed by `issueSchema`.\n */\nexport interface IStaticAssetValidation<IssueSchema extends z.ZodType> {\n /** The shape of ONE issue. It types the handler's answer and documents the route's response. */\n issueSchema: IssueSchema;\n\n /** Runs once per `upload-validate`. Read the file through `file`: every read is pinned to the content `commit` will copy. */\n handler: (opts: {\n file: StaticAssetPinnedFile;\n owner: string;\n metadata: TStaticAssetTokenMetadata;\n }) => ValueOrPromise<IStaticAssetValidationResult<z.infer<IssueSchema>>>;\n}\n\n/** What `validate` answers. `commitToken` is present only when the file is valid: it is the token `commit` takes. */\nexport interface IStaticAssetValidateResult<Issue> extends IStaticAssetValidationResult<Issue> {\n commitToken?: string;\n}\n\n/** Body of the upload policy route: the files the client intends to upload. */\nexport type TStaticAssetUploadPolicyRequest = { files: TStaticAssetUploadPolicyFile[] };\n\n/** The repository verbs the component calls, on MetaLink rows. A `DefaultCRUDRepository` over any `TMetaLinkCompatibleSchema` table satisfies it, and so does a small fake in a test. The contract checks the select row only (see the static-asset usage page for what that leaves to the table). */\nexport interface IMetaLinkRepository {\n create(opts: {\n data: TTableInsert<TMetaLinkSchema>;\n }): Promise<{ count: number; data: TMetaLink }>;\n updateBy(opts: {\n data: Partial<TTableInsert<TMetaLinkSchema>>;\n where: TWhere<TMetaLink>;\n }): Promise<{ count: number; data: TMetaLink[] | null }>;\n updateById(opts: {\n id: string;\n data: Partial<TTableInsert<TMetaLinkSchema>>;\n }): Promise<{ count: number; data: TMetaLink }>;\n deleteBy(opts: { where: TWhere<TMetaLink> }): Promise<{ count: number }>;\n}\n\n/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */\nexport type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n repository: TValueOrAsyncResolver<IMetaLinkRepository>;\n createMetaLink?: (opts: {\n uploadResult: IUploadResult;\n fileStat: IFileStat;\n /** The caller's labels: form fields on an upload, beside the commit token on a direct one. */\n labels: TStaticAssetUploadLabels;\n }) => ValueOrPromise<{ count: number; data: TTableObject<Schema> }>;\n};\n\n/** The part of a built-in route an application may change. `authenticate` and `authorize` replace the entry's `auth` for this route, and `{ skip: true }` leaves it open. */\nexport type TStaticAssetRouteConfig = Partial<\n Omit<IAuthRouteConfig, 'method' | 'request' | 'responses' | 'authenticate' | 'authorize'>\n> &\n TRouteAuthConfig;\n\n/** Authentication and authorization for every built-in route of an entry; a route's own `authenticate`/`authorize` replaces it for that route. */\nexport type TStaticAssetAuth = TRouteAuthConfig & {\n /**\n * `{ use: true }` leaves `getObjectByName` and `downloadObjectByName` unauthenticated, so a\n * browser can show an image without a token. `listObjects` is NOT public: listing a bucket is not\n * reading an object.\n *\n * @default { use: false }\n */\n publicRead?: TToggle;\n};\n\n/** The name of a built-in route, the key of `routes`. */\nexport type TStaticAssetRouteKey = TConstValue<typeof StaticAssetRouteKeys>;\n\n/**\n * What each built-in route does: `{ use: false }` turns it off, `{ use: true, ... }` turns it on\n * with those overrides. A route left out is on as built.\n */\nexport type TStaticAssetRoutes = Partial<\n Record<TStaticAssetRouteKey, TToggle<TStaticAssetRouteConfig>>\n>;\n\n/** Uploading through the application: the browser sends the bytes to `POST /objects` and the application writes them to the storage. */\nexport type TStaticAssetServerUploadOptions = {\n /** Largest file the route accepts. Absent means no ceiling. Checked against `content-length` before the body is read, then per file after parsing. */\n maxBytes?: number;\n\n /**\n * The most file parts one request may carry; more is refused with 413 before anything is written.\n *\n * @default StaticAssetDefaults.MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n\n /** The one hook that decides the key an uploaded file is stored under. Absent keeps the default naming. Under a `keyPrefix` a key outside the scope is refused, never rewritten. */\n objectKey?: TStaticAssetObjectKeyResolver;\n};\n\n/** Direct upload is a POST policy, which only S3 can sign, and its pending objects stay out of the served scope only when the entry has a `keyPrefix`. */\ntype TStaticAssetDirectUploadScope =\n | { keyPrefix?: string; directUpload: { use: false } }\n | { keyPrefix: string; directUpload: { use: true } & TStaticAssetDirectUploadOptions };\n\n/** The storage helper decides which direct upload shapes are possible. */\ntype TStaticAssetStorage =\n | ({ helper: BunS3Helper } & TStaticAssetDirectUploadScope)\n | { helper: DiskHelper; keyPrefix?: string; directUpload: { use: false } };\n\n/** One storage backend with its generated controller. Every switch is a toggle; a toggle left out is a type error, so nothing is on or off by accident. */\nexport type TStaticAssetEntry<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n basePath: string;\n\n /** The controller's name. Absent, it is derived from the entry's key. */\n name?: string;\n\n /** The single bucket every route uses. The function form is read per request, so an environment variable can be read lazily. */\n bucket: TValueOrAsyncResolver<string>;\n\n /**\n * The key scope this entry owns, e.g. `inventory/`. Every route refuses a key outside it as a\n * 404 without calling the storage, `listObjects` lists only inside it, and an upload key must\n * land inside it. `maxFolderDepth` counts the folders below it. Required with\n * `directUpload`: it keeps the pending prefix outside everything the routes serve.\n *\n * @default every key in the bucket\n */\n keyPrefix?: string;\n\n /**\n * Folders a key may nest below the `keyPrefix`, for every route of the entry: reads and deletes\n * too, so it holds for keys that arrive by direct upload or ingest.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n\n /**\n * `true` serves a raw nested object path (`/objects/photos/2024/f.jpg`) - a URL shape change; a percent-encoded path keeps working either way.\n *\n * @default false\n */\n rawObjectPath?: boolean;\n\n /** The link stored and returned for an object. Absent builds the URL of this controller's own object route. */\n link?: (opts: IObjectLocation) => string;\n\n /** Authentication and authorization of every built-in route of this entry. Absent leaves every route open; `publicRead` is the only way a read route is public on purpose. */\n auth?: TStaticAssetAuth;\n\n serverUpload: TToggle<TStaticAssetServerUploadOptions>;\n\n /** Every upload also writes a MetaLink row, and the object's deletion removes it. */\n metaLink: TToggle<TMetaLinkConfig<Schema>>;\n\n routes?: TStaticAssetRoutes;\n\n extend?: {\n /** Registered BEFORE every built-in route, so a literal path wins over the catch-all `rawObjectPath` produces. Hono matches in registration order. */\n before?: TStaticAssetDefineExtraRoutes;\n /** Registered after every built-in route. */\n after?: TStaticAssetDefineExtraRoutes;\n };\n} & TStaticAssetStorage;\n\n/** Static asset entries keyed by an application-chosen name; each key becomes one controller. */\nexport type TStaticAssetComponentOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> = Record<string, TStaticAssetEntry<Schema>>;\n\n/** The content a validation read: the ETag, and the version id when the storage has real versions. */\nexport interface IStaticAssetPin {\n etag: string;\n versionId?: string;\n}\n\n/**\n * What a commit token binds: the pending object a policy was issued for, when the grant dies and,\n * who it was issued to and the application's own metadata for the file.\n */\nexport interface IStaticAssetCommitTokenPayload {\n bucket: IBucketRef;\n object: IObjectRef;\n expiresAt: number;\n /** The token commits only for this owner. */\n owner: string;\n /** What `resolvers.metadata` returned for the file; `{}` without one. Signed, not encrypted. */\n metadata: TStaticAssetTokenMetadata;\n stage: TStaticAssetTokenStage;\n /** Present from `VALIDATED` on: `commit` copies only content that still matches it. */\n pin?: IStaticAssetPin;\n}\n"]}
|
|
@@ -21,8 +21,8 @@ export declare class StaticAssetControllerFactory {
|
|
|
21
21
|
scope: string;
|
|
22
22
|
args: unknown;
|
|
23
23
|
task: () => Promise<R>;
|
|
24
|
-
}): Promise<
|
|
25
|
-
normalizeCountData<ResponseSchema
|
|
24
|
+
}): Promise<R>;
|
|
25
|
+
normalizeCountData<ResponseSchema, RequestContext extends import("@venizia/ignis-kernel").TRouteContext<import("hono").Env> = import("@venizia/ignis-kernel").TRouteContext<import("hono").Env>, ResponseData extends {
|
|
26
26
|
count: number;
|
|
27
27
|
data?: import("@venizia/ignis-helpers").TNullable<ResponseSchema>;
|
|
28
28
|
} = {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { BaseRestController, TRouteContext, TRouteHandler } from '../../../../base/controllers/index.js';
|
|
2
2
|
import type { IAuthRouteConfig } from '../../../../base/index.js';
|
|
3
3
|
import type { IBucketRef, IObjectRef } from '@venizia/ignis-helpers';
|
|
4
|
-
import type {
|
|
4
|
+
import type { TConstValue } from '@venizia/ignis-helpers/common';
|
|
5
5
|
import { type TStaticAssetRouteKey } from '../../common/index.js';
|
|
6
6
|
import type { StaticAssetUploadCommitService, StaticAssetUploadPolicyService } from '../../services/index.js';
|
|
7
|
+
import type { TMetaLinkCompatibleSchema } from '../../models/index.js';
|
|
7
8
|
import type { IStaticAssetResolvedEntry } from '../../utilities/entry.utility.js';
|
|
8
9
|
import type { TStaticAssetRouteOverride } from '../../utilities/route-options.utility.js';
|
|
9
10
|
/** The part of an entry a route belongs to: a route is registered only when its feature is on. */
|
|
@@ -16,10 +17,10 @@ export declare class StaticAssetFeatures {
|
|
|
16
17
|
}
|
|
17
18
|
export type TStaticAssetFeature = TConstValue<typeof StaticAssetFeatures>;
|
|
18
19
|
/** What every route reads: the entry, resolved once, plus what only the running controller has. The table is erased at this seam on purpose: inside the routes every read and write is on MetaLink COLUMNS. */
|
|
19
|
-
export interface IStaticAssetRouteEnv extends Omit<IStaticAssetResolvedEntry<
|
|
20
|
+
export interface IStaticAssetRouteEnv extends Omit<IStaticAssetResolvedEntry<TMetaLinkCompatibleSchema>, 'directUpload'> {
|
|
20
21
|
logger: BaseRestController['logger'];
|
|
21
22
|
/** The resolved options with the services the component bound: the instances an application resolves from the container. */
|
|
22
|
-
directUpload?: NonNullable<IStaticAssetResolvedEntry<
|
|
23
|
+
directUpload?: NonNullable<IStaticAssetResolvedEntry<TMetaLinkCompatibleSchema>['directUpload']> & {
|
|
23
24
|
policyService: Pick<StaticAssetUploadPolicyService, 'issuePolicies'>;
|
|
24
25
|
commitService: Pick<StaticAssetUploadCommitService, 'commit' | 'validate'>;
|
|
25
26
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../../../../src/components/static-asset/controller/routes/context.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,iBAAiB,GAGlB,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../../../../src/components/static-asset/controller/routes/context.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,iBAAiB,GAGlB,MA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CAAC;QAC/D,CAAC;QAED,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAA2B,OAAO,CAAC,CAAC;QAE7E,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,EAAE,QAAQ,EAAE,GAAG,CAAC,iBAAiB,EAAE,CAAC,EAAE,CAAC;YACvF,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,mBAAmB,EAAE,CAAC,CAAC;QACnE,CAAC;QAED,0BAA0B,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,CAAC;QAE5E,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC;IAC3D,CAAC;CACF","sourcesContent":["import type { BaseRestController, TRouteContext, TRouteHandler } from '@/base/controllers';\nimport type { IAuthRouteConfig } from '@/base';\nimport type { IBucketRef, IObjectRef } from '@venizia/ignis-helpers';\nimport { ResolverUtility } from '@venizia/ignis-helpers/common';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n StaticAssetErrors,\n type TStaticAssetObjectParams,\n type TStaticAssetRouteKey,\n} from '../../common';\nimport type {\n StaticAssetUploadCommitService,\n StaticAssetUploadPolicyService,\n} from '../../services';\nimport type { TMetaLinkCompatibleSchema } from '../../models';\nimport type { IStaticAssetResolvedEntry } from '../../utilities/entry.utility';\nimport { StaticAssetKeyScopeUtility } from '../../utilities/key-scope.utility';\nimport type { TStaticAssetRouteOverride } from '../../utilities/route-options.utility';\n\n/** The part of an entry a route belongs to: a route is registered only when its feature is on. */\nexport class StaticAssetFeatures {\n static readonly OBJECT = 'object';\n static readonly SERVER_UPLOAD = 'serverUpload';\n static readonly DIRECT_UPLOAD = 'directUpload';\n static readonly VALIDATION = 'validation';\n static readonly META_LINK = 'metaLink';\n}\n\nexport type TStaticAssetFeature = TConstValue<typeof StaticAssetFeatures>;\n\n/** What every route reads: the entry, resolved once, plus what only the running controller has. The table is erased at this seam on purpose: inside the routes every read and write is on MetaLink COLUMNS. */\nexport interface IStaticAssetRouteEnv extends Omit<\n IStaticAssetResolvedEntry<TMetaLinkCompatibleSchema>,\n 'directUpload'\n> {\n logger: BaseRestController['logger'];\n /** The resolved options with the services the component bound: the instances an application resolves from the container. */\n directUpload?: NonNullable<\n IStaticAssetResolvedEntry<TMetaLinkCompatibleSchema>['directUpload']\n > & {\n policyService: Pick<StaticAssetUploadPolicyService, 'issuePolicies'>;\n commitService: Pick<StaticAssetUploadCommitService, 'commit' | 'validate'>;\n };\n}\n\nexport interface IStaticAssetRoute {\n key: TStaticAssetRouteKey;\n feature: TStaticAssetFeature;\n\n /** The OpenAPI definition and the handler of one route, side by side. */\n build: (env: IStaticAssetRouteEnv) => {\n config: IAuthRouteConfig;\n handler: TRouteHandler;\n };\n\n /** Middleware the route adds after the application's own. */\n middleware?: (opts: {\n env: IStaticAssetRouteEnv;\n own: TStaticAssetRouteOverride['middleware'];\n }) => TStaticAssetRouteOverride['middleware'];\n}\n\nexport class StaticAssetRouteUtility {\n /** A route builder reaches for an option its feature guarantees; a miss is a bug in the table, never in the input. */\n static requireFeature<T>(opts: { value: T | undefined; feature: TStaticAssetFeature }): T {\n if (opts.value === undefined) {\n throw getError({\n message: `[static-asset] a ${opts.feature} route was built without its ${opts.feature} option`,\n });\n }\n\n return opts.value;\n }\n\n /**\n * The bucket, and for an object route the key, one request names - checked and scoped before any\n * storage call, so a key outside the scope is never even probed.\n */\n static async resolveTarget(opts: {\n ctx: TRouteContext;\n env: IStaticAssetRouteEnv;\n /** An object route also names a key. */\n isObject?: boolean;\n }): Promise<{ bucket: IBucketRef; object: IObjectRef }> {\n const { ctx, env, isObject = false } = opts;\n // Read per request: an application may read an environment variable lazily.\n const bucketName = await ResolverUtility.resolveValueAsync({ value: env.bucket });\n\n if (!env.helper.isValidBucketName({ bucket: { name: bucketName } })) {\n throw getError({ error: StaticAssetErrors.BUCKET_NAME_INVALID });\n }\n\n if (!isObject) {\n return { bucket: { name: bucketName }, object: { key: '' } };\n }\n\n const { objectName: key } = ctx.req.valid<TStaticAssetObjectParams>('param');\n\n if (!env.helper.isValidObjectKey({ object: { key }, maxDepth: env.objectKeyMaxDepth })) {\n throw getError({ error: StaticAssetErrors.OBJECT_NAME_INVALID });\n }\n\n StaticAssetKeyScopeUtility.assertInScope({ key, keyPrefix: env.keyPrefix });\n\n return { bucket: { name: bucketName }, object: { key } };\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IBucketRef, IFileStat, IObjectRef, IStorageHelper, IUploadResult } from '@venizia/ignis-helpers';
|
|
2
|
-
import type {
|
|
2
|
+
import type { TMetaLink, TMetaLinkCompatibleSchema } from '../models/index.js';
|
|
3
3
|
import type { TMetaLinkConfig, TStaticAssetStorageType, TStaticAssetUploadLabels } from '../common/index.js';
|
|
4
4
|
export declare class StaticAssetMetaLinkUtility {
|
|
5
5
|
/** What a stat says about one stored object: the columns a refresh rewrites and a new row starts from. */
|
|
@@ -14,20 +14,20 @@ export declare class StaticAssetMetaLinkUtility {
|
|
|
14
14
|
}): IUploadResult;
|
|
15
15
|
/** The MetaLink row for one stored object. Every path that creates a row goes through here, so each lands exactly the row an ordinary upload does. */
|
|
16
16
|
static createRow(opts: {
|
|
17
|
-
metaLink: TMetaLinkConfig<
|
|
17
|
+
metaLink: TMetaLinkConfig<TMetaLinkCompatibleSchema>;
|
|
18
18
|
helper: IStorageHelper;
|
|
19
19
|
storage: TStaticAssetStorageType;
|
|
20
20
|
uploadResult: IUploadResult;
|
|
21
21
|
fileStat: IFileStat;
|
|
22
22
|
labels: TStaticAssetUploadLabels;
|
|
23
|
-
}): Promise<
|
|
23
|
+
}): Promise<TMetaLink>;
|
|
24
24
|
/**
|
|
25
25
|
* Rewrites the stored-object facts on every row of the pair. Rows per pair are deliberately not
|
|
26
26
|
* unique, and each keeps its own labels and storage type. A `createMetaLink` hook owns `link` and
|
|
27
27
|
* `metadata`, so with one only the stat columns change; without one, `metadata` is merged per row.
|
|
28
28
|
*/
|
|
29
29
|
static refreshRows(opts: {
|
|
30
|
-
metaLink: TMetaLinkConfig<
|
|
30
|
+
metaLink: TMetaLinkConfig<TMetaLinkCompatibleSchema>;
|
|
31
31
|
helper: IStorageHelper;
|
|
32
32
|
bucket: IBucketRef;
|
|
33
33
|
object: IObjectRef;
|
|
@@ -35,7 +35,7 @@ export declare class StaticAssetMetaLinkUtility {
|
|
|
35
35
|
fileStat: IFileStat;
|
|
36
36
|
}): Promise<{
|
|
37
37
|
count: number;
|
|
38
|
-
data:
|
|
38
|
+
data: TMetaLink[];
|
|
39
39
|
}>;
|
|
40
40
|
}
|
|
41
41
|
//# sourceMappingURL=meta-link.utility.d.ts.map
|