@cosmicdrift/kumiko-bundled-features 0.377.0 → 0.378.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/cap-counter/stock-cap-guard.js +8 -0
  2. package/dist/config/web/i18n.js +1 -0
  3. package/dist/inbound-mail-foundation/handlers/list-accounts.query.d.ts +1 -1
  4. package/dist/inbound-mail-foundation/handlers/list-accounts.query.js +11 -3
  5. package/dist/mail-foundation/i18n.d.ts +5 -2
  6. package/dist/mail-foundation/i18n.js +3 -2
  7. package/dist/mail-transport-smtp/i18n.d.ts +1 -1
  8. package/dist/mail-transport-smtp/i18n.js +1 -1
  9. package/dist/template-resolver/compile-document-body.d.ts +3 -0
  10. package/dist/template-resolver/compile-document-body.js +50 -3
  11. package/dist/template-resolver/constants.d.ts +3 -0
  12. package/dist/template-resolver/constants.js +2 -0
  13. package/dist/template-resolver/document-blocks.d.ts +2 -2
  14. package/dist/template-resolver/document-blocks.js +1 -0
  15. package/dist/template-resolver/document-images.d.ts +2 -0
  16. package/dist/template-resolver/document-images.js +28 -0
  17. package/dist/template-resolver/document-sanitizer.d.ts +1 -1
  18. package/dist/template-resolver/document-sanitizer.js +20 -0
  19. package/dist/template-resolver/document-schema.d.ts +2 -1
  20. package/dist/template-resolver/document-schema.js +4 -0
  21. package/dist/template-resolver/feature.d.ts +9 -0
  22. package/dist/template-resolver/feature.js +58 -33
  23. package/dist/template-resolver/handlers/collection-item.query.js +2 -1
  24. package/dist/template-resolver/handlers/collection-list.query.js +2 -1
  25. package/dist/template-resolver/handlers/collection-set.write.js +2 -2
  26. package/dist/template-resolver/handlers/collection-shared.d.ts +1 -2
  27. package/dist/template-resolver/handlers/collection-shared.js +0 -4
  28. package/dist/template-resolver/handlers/copy-locale.write.d.ts +2 -1
  29. package/dist/template-resolver/handlers/copy-locale.write.js +67 -63
  30. package/dist/template-resolver/handlers/discard-draft.write.d.ts +3 -2
  31. package/dist/template-resolver/handlers/discard-draft.write.js +18 -6
  32. package/dist/template-resolver/handlers/import-bundle.write.d.ts +2 -1
  33. package/dist/template-resolver/handlers/import-bundle.write.js +30 -25
  34. package/dist/template-resolver/handlers/overview.query.d.ts +2 -1
  35. package/dist/template-resolver/handlers/overview.query.js +46 -42
  36. package/dist/template-resolver/handlers/patch-draft.write.d.ts +2 -1
  37. package/dist/template-resolver/handlers/patch-draft.write.js +92 -86
  38. package/dist/template-resolver/handlers/reset-to-system.write.d.ts +2 -1
  39. package/dist/template-resolver/handlers/reset-to-system.write.js +51 -44
  40. package/dist/template-resolver/handlers/resource-link-pdf.write.d.ts +2 -1
  41. package/dist/template-resolver/handlers/resource-link-pdf.write.js +34 -28
  42. package/dist/template-resolver/handlers/resource-remove.write.d.ts +2 -1
  43. package/dist/template-resolver/handlers/resource-remove.write.js +39 -33
  44. package/dist/template-resolver/handlers/resource-upload.write.d.ts +2 -1
  45. package/dist/template-resolver/handlers/resource-upload.write.js +104 -96
  46. package/dist/template-resolver/handlers/send-test-shared.d.ts +5 -0
  47. package/dist/template-resolver/handlers/send-test-shared.js +19 -0
  48. package/dist/template-resolver/handlers/send-test-status.query.d.ts +9 -0
  49. package/dist/template-resolver/handlers/send-test-status.query.js +18 -0
  50. package/dist/template-resolver/handlers/send-test.write.d.ts +2 -1
  51. package/dist/template-resolver/handlers/send-test.write.js +87 -89
  52. package/dist/template-resolver/handlers/set.write.d.ts +2 -1
  53. package/dist/template-resolver/handlers/set.write.js +94 -90
  54. package/dist/template-resolver/handlers/toggle-status.write.d.ts +6 -7
  55. package/dist/template-resolver/handlers/toggle-status.write.js +28 -10
  56. package/dist/template-resolver/handlers/upsert-tenant.write.d.ts +2 -1
  57. package/dist/template-resolver/handlers/upsert-tenant.write.js +30 -24
  58. package/dist/template-resolver/index.d.ts +4 -2
  59. package/dist/template-resolver/index.js +3 -1
  60. package/dist/template-resolver/qualified-names.d.ts +2 -0
  61. package/dist/template-resolver/qualified-names.js +2 -0
  62. package/dist/template-resolver/template-edit-policy.d.ts +22 -0
  63. package/dist/template-resolver/template-edit-policy.js +45 -0
  64. package/dist/template-resolver/template-preview.js +7 -2
  65. package/dist/template-resolver/template-validation.js +33 -13
  66. package/dist/template-resolver/web/document-editor-extensions.d.ts +1 -0
  67. package/dist/template-resolver/web/document-editor-extensions.js +21 -1
  68. package/dist/template-resolver/web/document-tiptap-editor.d.ts +1 -1
  69. package/dist/template-resolver/web/document-tiptap-editor.js +22 -6
  70. package/dist/template-resolver/web/document-toolbar-blocks.d.ts +2 -0
  71. package/dist/template-resolver/web/i18n.js +4 -0
  72. package/package.json +8 -8
  73. package/src/cap-counter/changes.json +12 -0
  74. package/src/inbound-mail-foundation/changes.json +6 -0
  75. package/src/mail-foundation/changes.json +6 -0
  76. package/src/template-resolver/changes.json +20 -0
@@ -5,6 +5,7 @@ import { FileRefTooLargeError, fileContextForTenant, readFileRefContent, } from
5
5
  import { attachmentFileNameSchema } from "../../shared/index.js";
6
6
  import { TemplateResolverErrors } from "../qualified-names.js";
7
7
  import { prepareTemplateAttachmentBeforeTransaction, prepareTemplateResourceBeforeTransaction, readTemplateResourceMaxBytes, storePreparedTemplateAttachment, storePreparedTemplateResource, } from "../store-template-resource.js";
8
+ import { refuseTemplateEditById, templateEditAccess, } from "../template-edit-policy.js";
8
9
  import { RESOURCE_PURPOSES, resourceKeySchema, resourceTargetTenantId } from "./resource-shared.js";
9
10
  function attachmentTargetOf(input) {
10
11
  const { templateId, key, fileName } = input;
@@ -16,113 +17,120 @@ function attachmentTargetOf(input) {
16
17
  // Purpose "image": stores a re-encoded image as a FileRef and, with templateId + key, links it into
17
18
  // the template; without templateId it only creates the FileRef (the branding logo upload path).
18
19
  // Purpose "attachment": stores the file as uploaded and links it as a mail attachment.
19
- export const resourceUploadWrite = defineWriteHandler({
20
- name: "resource-upload",
21
- schema: z
22
- .object({
23
- templateId: z.string().min(1).optional(),
24
- key: resourceKeySchema.optional(),
25
- /** An unclaimed upload of the caller (POST /api/files without entityType). */
26
- sourceFileRefId: z.uuid(),
27
- /** Cross-tenant target — SystemAdmin only. */
28
- tenantIdOverride: z.string().min(1).optional(),
29
- /** "attachment" links a PDF/PNG/JPEG as a file attached to every mail of the template. */
30
- purpose: z.enum(RESOURCE_PURPOSES).default("image"),
31
- /** Name the recipient sees; required for purpose "attachment". */
32
- fileName: z.string().optional(),
33
- })
34
- .refine((p) => p.purpose === "attachment" || (p.templateId === undefined) === (p.key === undefined), {
35
- message: "templateId and key must be given together",
36
- path: ["key"],
37
- }),
38
- access: { roles: ["TenantAdmin", "SystemAdmin"] },
39
- description: "Turns a file uploaded via POST /api/files (multipart, no entityType) into a template resource. With purpose image (default) the upload is checked against the resource-max-bytes cap, re-encoded to a supported image format and stored as a new file; with templateId and key it is linked into that template under the key, without them only the file is created. With purpose attachment, templateId, key and fileName are required: a PDF, PNG or JPEG is stored unchanged and linked into a mail template as a file attached to every mail sent from it, at most 10 per template. A cap above the files route's maxUploadSize has no effect.",
40
- beforeTransaction: async (event, ctx) => {
41
- const { templateId, key, sourceFileRefId, purpose, fileName } = event.payload;
42
- const attachmentTarget = purpose === "attachment" ? attachmentTargetOf({ templateId, key, fileName }) : null;
43
- if (purpose === "attachment" && attachmentTarget === null) {
44
- return writeFailure(new UnprocessableError(TemplateResolverErrors.attachmentInvalid, {
45
- i18nKey: "templateResolver.errors.attachment.invalid",
46
- details: { code: "target_required" },
47
- }));
48
- }
49
- const maxBytes = await readTemplateResourceMaxBytes(ctx.config, ctx.registry);
50
- // The source is read from the session tenant only: with tenantIdOverride the upload
51
- // sits in the admin's own tenant while the normalized file lands in the target tenant.
52
- // Only the caller's own unclaimed upload qualifies, so a record-attached image of
53
- // someone else cannot be copied into a template.
54
- let source;
55
- try {
56
- source = await readFileRefContent({
57
- db: ctx.db,
58
- filesForTenant: (tid) => fileContextForTenant(ctx, ctx.user.tenantId, tid),
59
- fileRefId: sourceFileRefId,
60
- allowedTenantIds: [event.user.tenantId],
61
- unclaimedUploadOf: event.user.id,
62
- maxBytes,
63
- });
64
- }
65
- catch (cause) {
66
- if (cause instanceof FileRefTooLargeError) {
67
- return writeFailure(new UnprocessableError(TemplateResolverErrors.resourceTooLarge, {
68
- i18nKey: "templateResolver.errors.resource.tooLarge",
69
- details: { maxBytes, size: cause.size },
20
+ export function makeResourceUploadWrite(policy) {
21
+ return defineWriteHandler({
22
+ name: "resource-upload",
23
+ schema: z
24
+ .object({
25
+ templateId: z.string().min(1).optional(),
26
+ key: resourceKeySchema.optional(),
27
+ /** An unclaimed upload of the caller (POST /api/files without entityType). */
28
+ sourceFileRefId: z.uuid(),
29
+ /** Cross-tenant target — SystemAdmin only. */
30
+ tenantIdOverride: z.string().min(1).optional(),
31
+ /** "attachment" links a PDF/PNG/JPEG as a file attached to every mail of the template. */
32
+ purpose: z.enum(RESOURCE_PURPOSES).default("image"),
33
+ /** Name the recipient sees; required for purpose "attachment". */
34
+ fileName: z.string().optional(),
35
+ })
36
+ .refine((p) => p.purpose === "attachment" || (p.templateId === undefined) === (p.key === undefined), {
37
+ message: "templateId and key must be given together",
38
+ path: ["key"],
39
+ }),
40
+ access: templateEditAccess(policy.tenantEditable),
41
+ description: "Turns a file uploaded via POST /api/files (multipart, no entityType) into a template resource. With purpose image (default) the upload is checked against the resource-max-bytes cap, re-encoded to a supported image format and stored as a new file; with templateId and key it is linked into that template under the key, without them only the file is created. With purpose attachment, templateId, key and fileName are required: a PDF, PNG or JPEG is stored unchanged and linked into a mail template as a file attached to every mail sent from it, at most 10 per template. A cap above the files route's maxUploadSize has no effect. Only a SystemAdmin and the roles of the templates the app lists in tenantEditable may use it; such a role may link only into those templates.",
42
+ beforeTransaction: async (event, ctx) => {
43
+ const { templateId, key, sourceFileRefId, purpose, fileName } = event.payload;
44
+ const attachmentTarget = purpose === "attachment" ? attachmentTargetOf({ templateId, key, fileName }) : null;
45
+ if (purpose === "attachment" && attachmentTarget === null) {
46
+ return writeFailure(new UnprocessableError(TemplateResolverErrors.attachmentInvalid, {
47
+ i18nKey: "templateResolver.errors.attachment.invalid",
48
+ details: { code: "target_required" },
70
49
  }));
71
50
  }
72
- throw cause;
73
- }
74
- if (source === null)
75
- return writeFailure(new NotFoundError("file-ref", sourceFileRefId));
76
- // The source upload stays as an unclaimed file: bundled-features cannot reach the fileRef executor to delete it.
77
- const tenantId = resourceTargetTenantId(event.payload.tenantIdOverride, event.user.tenantId);
78
- if (attachmentTarget !== null) {
79
- return prepareTemplateAttachmentBeforeTransaction({
51
+ if (templateId !== undefined) {
52
+ const refused = await refuseTemplateEditById(ctx.db, policy, event.user, resourceTargetTenantId(event.payload.tenantIdOverride, event.user.tenantId), templateId);
53
+ if (refused !== null)
54
+ return refused;
55
+ }
56
+ const maxBytes = await readTemplateResourceMaxBytes(ctx.config, ctx.registry);
57
+ // The source is read from the session tenant only: with tenantIdOverride the upload
58
+ // sits in the admin's own tenant while the normalized file lands in the target tenant.
59
+ // Only the caller's own unclaimed upload qualifies, so a record-attached image of
60
+ // someone else cannot be copied into a template.
61
+ let source;
62
+ try {
63
+ source = await readFileRefContent({
64
+ db: ctx.db,
65
+ filesForTenant: (tid) => fileContextForTenant(ctx, ctx.user.tenantId, tid),
66
+ fileRefId: sourceFileRefId,
67
+ allowedTenantIds: [event.user.tenantId],
68
+ unclaimedUploadOf: event.user.id,
69
+ maxBytes,
70
+ });
71
+ }
72
+ catch (cause) {
73
+ if (cause instanceof FileRefTooLargeError) {
74
+ return writeFailure(new UnprocessableError(TemplateResolverErrors.resourceTooLarge, {
75
+ i18nKey: "templateResolver.errors.resource.tooLarge",
76
+ details: { maxBytes, size: cause.size },
77
+ }));
78
+ }
79
+ throw cause;
80
+ }
81
+ if (source === null)
82
+ return writeFailure(new NotFoundError("file-ref", sourceFileRefId));
83
+ // The source upload stays as an unclaimed file: bundled-features cannot reach the fileRef executor to delete it.
84
+ const tenantId = resourceTargetTenantId(event.payload.tenantIdOverride, event.user.tenantId);
85
+ if (attachmentTarget !== null) {
86
+ return prepareTemplateAttachmentBeforeTransaction({
87
+ ctx,
88
+ user: event.user,
89
+ tenantId,
90
+ bytes: source.content,
91
+ maxBytes,
92
+ ...attachmentTarget,
93
+ });
94
+ }
95
+ return prepareTemplateResourceBeforeTransaction({
80
96
  ctx,
81
97
  user: event.user,
82
98
  tenantId,
83
99
  bytes: source.content,
84
100
  maxBytes,
85
- ...attachmentTarget,
101
+ ...(templateId !== undefined && { templateId }),
102
+ ...(key !== undefined && { key }),
86
103
  });
87
- }
88
- return prepareTemplateResourceBeforeTransaction({
89
- ctx,
90
- user: event.user,
91
- tenantId,
92
- bytes: source.content,
93
- maxBytes,
94
- ...(templateId !== undefined && { templateId }),
95
- ...(key !== undefined && { key }),
96
- });
97
- },
98
- handler: async (event, ctx) => {
99
- const { templateId, key } = event.payload;
100
- const tenantId = resourceTargetTenantId(event.payload.tenantIdOverride, event.user.tenantId);
101
- const { prepared } = event;
102
- if (prepared.kind === "attachment") {
103
- // The phase accepts attachments only with a complete target, so these are set.
104
- if (templateId === undefined || key === undefined) {
105
- return writeFailure(new UnprocessableError(TemplateResolverErrors.attachmentInvalid, {
106
- i18nKey: "templateResolver.errors.attachment.invalid",
107
- details: { code: "target_required" },
108
- }));
104
+ },
105
+ handler: async (event, ctx) => {
106
+ const { templateId, key } = event.payload;
107
+ const tenantId = resourceTargetTenantId(event.payload.tenantIdOverride, event.user.tenantId);
108
+ const { prepared } = event;
109
+ if (prepared.kind === "attachment") {
110
+ // The phase accepts attachments only with a complete target, so these are set.
111
+ if (templateId === undefined || key === undefined) {
112
+ return writeFailure(new UnprocessableError(TemplateResolverErrors.attachmentInvalid, {
113
+ i18nKey: "templateResolver.errors.attachment.invalid",
114
+ details: { code: "target_required" },
115
+ }));
116
+ }
117
+ return storePreparedTemplateAttachment({
118
+ ctx,
119
+ user: event.user,
120
+ tenantId,
121
+ prepared,
122
+ templateId,
123
+ key,
124
+ });
109
125
  }
110
- return storePreparedTemplateAttachment({
126
+ return storePreparedTemplateResource({
111
127
  ctx,
112
128
  user: event.user,
113
129
  tenantId,
114
130
  prepared,
115
- templateId,
116
- key,
131
+ ...(templateId !== undefined && { templateId }),
132
+ ...(key !== undefined && { key }),
117
133
  });
118
- }
119
- return storePreparedTemplateResource({
120
- ctx,
121
- user: event.user,
122
- tenantId,
123
- prepared,
124
- ...(templateId !== undefined && { templateId }),
125
- ...(key !== undefined && { key }),
126
- });
127
- },
128
- });
134
+ },
135
+ });
136
+ }
@@ -0,0 +1,5 @@
1
+ import type { HandlerContext, Registry, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { type ChannelContext } from "../../delivery/index.ts";
3
+ export declare function emailChannelOf(registry: Registry): import("../../delivery/types.ts").DeliveryChannel | undefined;
4
+ export declare function testMailChannelContext(ctx: HandlerContext, user: SessionUser): ChannelContext;
5
+ export declare function resolveTestMailAddress(channel: NonNullable<ReturnType<typeof emailChannelOf>>, channelContext: ChannelContext, user: SessionUser): Promise<string | null>;
@@ -0,0 +1,19 @@
1
+ import { collectChannels, createEmailAttachmentReader, EMAIL_CHANNEL_NAME, } from "../../delivery/index.js";
2
+ import { fileContextForTenant } from "../../file-foundation/index.js";
3
+ export function emailChannelOf(registry) {
4
+ return collectChannels(registry).find((channel) => channel.name === EMAIL_CHANNEL_NAME);
5
+ }
6
+ export function testMailChannelContext(ctx, user) {
7
+ return {
8
+ db: ctx.db,
9
+ registry: ctx.registry,
10
+ sseBroker: undefined,
11
+ tenantId: user.tenantId,
12
+ secrets: ctx.secrets,
13
+ config: ctx.config,
14
+ readAttachment: createEmailAttachmentReader(ctx.db, ctx.registry, user.tenantId, ctx.config, (tenantId) => fileContextForTenant(ctx, ctx.user.tenantId, tenantId)),
15
+ };
16
+ }
17
+ export async function resolveTestMailAddress(channel, channelContext, user) {
18
+ return (await channel.resolve?.(user.id, channelContext)) ?? null;
19
+ }
@@ -0,0 +1,9 @@
1
+ import * as z from "zod";
2
+ export type SendTestStatus = {
3
+ readonly canSend: true;
4
+ readonly reason: null;
5
+ } | {
6
+ readonly canSend: false;
7
+ readonly reason: "no_channel" | "no_address";
8
+ };
9
+ export declare const sendTestStatusQuery: import("@cosmicdrift/kumiko-types/define-handler").QueryHandlerDefinition<"send-test-status", z.ZodObject<{}, z.core.$strip>, SendTestStatus, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap>;
@@ -0,0 +1,18 @@
1
+ import { defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import * as z from "zod";
3
+ import { emailChannelOf, resolveTestMailAddress, testMailChannelContext, } from "./send-test-shared.js";
4
+ export const sendTestStatusQuery = defineQueryHandler({
5
+ name: "send-test-status",
6
+ schema: z.object({}),
7
+ access: { roles: ["TenantAdmin", "SystemAdmin"] },
8
+ description: "Tells whether send-test can reach the calling user: canSend is true when an email channel is mounted and resolves an address for the caller, otherwise reason is no_channel or no_address; the address itself is never returned.",
9
+ handler: async (query, ctx) => {
10
+ const channel = emailChannelOf(ctx.registry);
11
+ if (channel === undefined)
12
+ return { canSend: false, reason: "no_channel" };
13
+ const address = await resolveTestMailAddress(channel, testMailChannelContext(ctx, query.user), query.user);
14
+ return address === null
15
+ ? { canSend: false, reason: "no_address" }
16
+ : { canSend: true, reason: null };
17
+ },
18
+ });
@@ -1,5 +1,6 @@
1
1
  import * as z from "zod";
2
- export declare const sendTestWrite: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"send-test", z.ZodObject<{
2
+ import { type TemplateEditPolicy } from "../template-edit-policy.ts";
3
+ export declare function makeSendTestWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"send-test", z.ZodObject<{
3
4
  slug: z.ZodString;
4
5
  locale: z.ZodString;
5
6
  content: z.ZodOptional<z.ZodString>;
@@ -1,16 +1,13 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import * as z from "zod";
4
- import { collectChannels, createEmailAttachmentReader, EMAIL_CHANNEL_NAME, } from "../../delivery/index.js";
5
- import { fileContextForTenant } from "../../file-foundation/index.js";
6
4
  import { TEST_MAIL_SUBJECT_PREFIX } from "../constants.js";
7
5
  import { TemplateResolverErrors } from "../qualified-names.js";
6
+ import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
8
7
  import { renderTemplatePreview } from "../template-preview.js";
8
+ import { emailChannelOf, resolveTestMailAddress, testMailChannelContext, } from "./send-test-shared.js";
9
9
  import { localeSchema, templateSlugSchema } from "./shared.js";
10
10
  const TEST_MAIL_RATE_LIMIT = { limit: 10, windowSeconds: 3600 };
11
- function emailChannelOf(registry) {
12
- return collectChannels(registry).find((channel) => channel.name === EMAIL_CHANNEL_NAME);
13
- }
14
11
  // Transport errors can carry provider responses or the address, so the client only gets a fixed code.
15
12
  function testMailFailed(code) {
16
13
  return writeFailure(new UnprocessableError(TemplateResolverErrors.testMailFailed, {
@@ -23,89 +20,90 @@ function errorCodeOf(error) {
23
20
  return typeof code === "string" ? code : undefined;
24
21
  }
25
22
  // The only recipient is the caller's own address, resolved server-side, so the handler can never mail a third party.
26
- export const sendTestWrite = defineWriteHandler({
27
- name: "send-test",
28
- schema: z.object({
29
- slug: templateSlugSchema,
30
- locale: localeSchema,
31
- content: z.string().max(200_000).optional(),
32
- meta: z.unknown().optional(),
33
- variableSchema: z.record(z.string(), z.unknown()).default({}),
34
- variables: z.record(z.string(), z.unknown()).optional(),
35
- includeAttachments: z.boolean().default(true),
36
- prefixSubject: z.boolean().default(true),
37
- }),
38
- access: { roles: ["TenantAdmin", "SystemAdmin"] },
39
- rateLimit: { per: "user+handler", ...TEST_MAIL_RATE_LIMIT },
40
- description: "Sends the rendered preview of a mail template draft, or of the stored template when no content is given, to the calling user's own address with the subject prefixed by [TEST] unless prefixSubject is false, carrying the inline images and, unless includeAttachments is false, the files attached to the template; there is no recipient input, the sample values come from the declared variable examples unless variables replaces them (checked against the variable schema), and a draft that fails the write rules is rejected without sending.",
41
- handler: async (event, ctx) => {
42
- const { includeAttachments, prefixSubject, ...previewPayload } = event.payload;
43
- const outcome = await renderTemplatePreview(ctx, event.user, {
44
- ...previewPayload,
45
- kind: "mail",
46
- });
47
- if (!outcome.ok)
48
- return writeFailure(outcome.error);
49
- const { preview, sender } = outcome;
50
- const mailAttachments = includeAttachments
51
- ? outcome.mailAttachments
52
- : outcome.mailAttachments.filter((ref) => ref.kind === "inline");
53
- const channel = emailChannelOf(ctx.registry);
54
- if (channel === undefined) {
55
- return writeFailure(new UnprocessableError(TemplateResolverErrors.testMailNoChannel, {
56
- i18nKey: "templateResolver.errors.testMail.noChannel",
57
- }));
58
- }
59
- const channelContext = {
60
- db: ctx.db,
61
- registry: ctx.registry,
62
- sseBroker: undefined,
63
- tenantId: event.user.tenantId,
64
- secrets: ctx.secrets,
65
- config: ctx.config,
66
- readAttachment: createEmailAttachmentReader(ctx.db, ctx.registry, event.user.tenantId, ctx.config, (tenantId) => fileContextForTenant(ctx, ctx.user.tenantId, tenantId)),
67
- };
68
- const address = (await channel.resolve?.(event.user.id, channelContext)) ?? null;
69
- if (address === null) {
70
- return writeFailure(new UnprocessableError(TemplateResolverErrors.testMailNoAddress, {
71
- i18nKey: "templateResolver.errors.testMail.noAddress",
72
- }));
73
- }
74
- const subject = `${prefixSubject ? TEST_MAIL_SUBJECT_PREFIX : ""}${preview.subject ?? ""}`;
75
- let sentStatus;
76
- try {
77
- const result = await channel.send(address, {
78
- // The template slug is the notification name, so the test mail takes the transport the real mail takes.
79
- notificationType: event.payload.slug,
80
- title: subject,
81
- body: undefined,
82
- data: undefined,
83
- locale: event.payload.locale,
84
- }, channelContext, {
85
- subject,
86
- html: preview.html,
87
- text: preview.text ?? "",
88
- ...sender,
89
- attachments: mailAttachments,
90
- });
91
- sentStatus = result.status;
92
- }
93
- catch (error) {
94
- // Class and code only: the message can carry the address or a provider response body.
95
- ctx.log?.warn("template test mail: channel threw", {
96
- tenantId: event.user.tenantId,
97
- errorClass: error instanceof Error ? error.name : typeof error,
98
- errorCode: errorCodeOf(error),
23
+ export function makeSendTestWrite(policy) {
24
+ return defineWriteHandler({
25
+ name: "send-test",
26
+ schema: z.object({
27
+ slug: templateSlugSchema,
28
+ locale: localeSchema,
29
+ content: z.string().max(200_000).optional(),
30
+ meta: z.unknown().optional(),
31
+ variableSchema: z.record(z.string(), z.unknown()).default({}),
32
+ variables: z.record(z.string(), z.unknown()).optional(),
33
+ includeAttachments: z.boolean().default(true),
34
+ prefixSubject: z.boolean().default(true),
35
+ }),
36
+ access: templateEditAccess(policy.tenantEditable),
37
+ rateLimit: { per: "user+handler", ...TEST_MAIL_RATE_LIMIT },
38
+ description: "Sends the rendered preview of a mail template draft, or of the stored template when no content is given, to the calling user's own address with the subject prefixed by [TEST] unless prefixSubject is false, carrying the inline images and, unless includeAttachments is false, the files attached to the template; there is no recipient input, the sample values come from the declared variable examples unless variables replaces them (checked against the variable schema), and a draft that fails the write rules is rejected without sending.",
39
+ handler: async (event, ctx) => {
40
+ // Sending a test is part of editing, so it follows the same edit policy as the editor writes.
41
+ const refused = refuseTemplateEdit(policy, event.user, {
42
+ slug: event.payload.slug,
43
+ kind: "mail",
99
44
  });
100
- return testMailFailed("channel_error");
101
- }
102
- if (sentStatus !== "sent") {
103
- ctx.log?.warn("template test mail: channel did not send", {
104
- tenantId: event.user.tenantId,
105
- status: sentStatus,
45
+ if (refused !== null)
46
+ return refused;
47
+ const { includeAttachments, prefixSubject, ...previewPayload } = event.payload;
48
+ const outcome = await renderTemplatePreview(ctx, event.user, {
49
+ ...previewPayload,
50
+ kind: "mail",
106
51
  });
107
- return testMailFailed("not_sent");
108
- }
109
- return { isSuccess: true, data: { subject, checks: preview.checks } };
110
- },
111
- });
52
+ if (!outcome.ok)
53
+ return writeFailure(outcome.error);
54
+ const { preview, sender } = outcome;
55
+ const mailAttachments = includeAttachments
56
+ ? outcome.mailAttachments
57
+ : outcome.mailAttachments.filter((ref) => ref.kind === "inline");
58
+ const channel = emailChannelOf(ctx.registry);
59
+ if (channel === undefined) {
60
+ return writeFailure(new UnprocessableError(TemplateResolverErrors.testMailNoChannel, {
61
+ i18nKey: "templateResolver.errors.testMail.noChannel",
62
+ }));
63
+ }
64
+ const channelContext = testMailChannelContext(ctx, event.user);
65
+ const address = await resolveTestMailAddress(channel, channelContext, event.user);
66
+ if (address === null) {
67
+ return writeFailure(new UnprocessableError(TemplateResolverErrors.testMailNoAddress, {
68
+ i18nKey: "templateResolver.errors.testMail.noAddress",
69
+ }));
70
+ }
71
+ const subject = `${prefixSubject ? TEST_MAIL_SUBJECT_PREFIX : ""}${preview.subject ?? ""}`;
72
+ let sentStatus;
73
+ try {
74
+ const result = await channel.send(address, {
75
+ // The template slug is the notification name, so the test mail takes the transport the real mail takes.
76
+ notificationType: event.payload.slug,
77
+ title: subject,
78
+ body: undefined,
79
+ data: undefined,
80
+ locale: event.payload.locale,
81
+ }, channelContext, {
82
+ subject,
83
+ html: preview.html,
84
+ text: preview.text ?? "",
85
+ ...sender,
86
+ attachments: mailAttachments,
87
+ });
88
+ sentStatus = result.status;
89
+ }
90
+ catch (error) {
91
+ // Class and code only: the message can carry the address or a provider response body.
92
+ ctx.log?.warn("template test mail: channel threw", {
93
+ tenantId: event.user.tenantId,
94
+ errorClass: error instanceof Error ? error.name : typeof error,
95
+ errorCode: errorCodeOf(error),
96
+ });
97
+ return testMailFailed("channel_error");
98
+ }
99
+ if (sentStatus !== "sent") {
100
+ ctx.log?.warn("template test mail: channel did not send", {
101
+ tenantId: event.user.tenantId,
102
+ status: sentStatus,
103
+ });
104
+ return testMailFailed("not_sent");
105
+ }
106
+ return { isSuccess: true, data: { subject, checks: preview.checks } };
107
+ },
108
+ });
109
+ }
@@ -1,5 +1,6 @@
1
1
  import * as z from "zod";
2
- export declare const setWrite: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"set", z.ZodObject<{
2
+ import { type TemplateEditPolicy } from "../template-edit-policy.ts";
3
+ export declare function makeSetWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"set", z.ZodObject<{
3
4
  slug: z.ZodString;
4
5
  locale: z.ZodString;
5
6
  kind: z.ZodOptional<z.ZodEnum<{