@gadicc/loom 1.16.1 → 1.17.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 (91) hide show
  1. package/README.md +14 -0
  2. package/esm/_dnt.polyfills.d.ts +6 -0
  3. package/esm/_dnt.polyfills.d.ts.map +1 -1
  4. package/esm/mod.d.ts +2 -0
  5. package/esm/mod.d.ts.map +1 -1
  6. package/esm/mod.js +2 -0
  7. package/esm/src/cli/mod.d.ts +1 -1
  8. package/esm/src/cli/mod.d.ts.map +1 -1
  9. package/esm/src/cli/mod.js +1034 -2
  10. package/esm/src/mail/errors.d.ts +33 -0
  11. package/esm/src/mail/errors.d.ts.map +1 -0
  12. package/esm/src/mail/errors.js +89 -0
  13. package/esm/src/mail/memory.d.ts +30 -0
  14. package/esm/src/mail/memory.d.ts.map +1 -0
  15. package/esm/src/mail/memory.js +340 -0
  16. package/esm/src/mail/mod.d.ts +7 -0
  17. package/esm/src/mail/mod.d.ts.map +1 -0
  18. package/esm/src/mail/mod.js +6 -0
  19. package/esm/src/mail/postal.d.ts +57 -0
  20. package/esm/src/mail/postal.d.ts.map +1 -0
  21. package/esm/src/mail/postal.js +238 -0
  22. package/esm/src/mail/retry.d.ts +9 -0
  23. package/esm/src/mail/retry.d.ts.map +1 -0
  24. package/esm/src/mail/retry.js +19 -0
  25. package/esm/src/mail/service.d.ts +23 -0
  26. package/esm/src/mail/service.d.ts.map +1 -0
  27. package/esm/src/mail/service.js +185 -0
  28. package/esm/src/mail/types.d.ts +176 -0
  29. package/esm/src/mail/types.d.ts.map +1 -0
  30. package/esm/src/mail/types.js +1 -0
  31. package/esm/src/mui/mail.d.ts +29 -0
  32. package/esm/src/mui/mail.d.ts.map +1 -0
  33. package/esm/src/mui/mail.js +114 -0
  34. package/esm/src/mui/mailView.d.ts +20 -0
  35. package/esm/src/mui/mailView.d.ts.map +1 -0
  36. package/esm/src/mui/mailView.js +26 -0
  37. package/esm/src/mui/mod.d.ts +1 -0
  38. package/esm/src/mui/mod.d.ts.map +1 -1
  39. package/esm/src/mui/mod.js +1 -0
  40. package/esm/src/next/mail/mod.d.ts +3 -0
  41. package/esm/src/next/mail/mod.d.ts.map +1 -0
  42. package/esm/src/next/mail/mod.js +2 -0
  43. package/esm/src/next/mail/route.d.ts +12 -0
  44. package/esm/src/next/mail/route.d.ts.map +1 -0
  45. package/esm/src/next/mail/route.js +43 -0
  46. package/package.json +55 -2
  47. package/script/_dnt.polyfills.d.ts +6 -0
  48. package/script/_dnt.polyfills.d.ts.map +1 -1
  49. package/script/mod.d.ts +2 -0
  50. package/script/mod.d.ts.map +1 -1
  51. package/script/mod.js +2 -0
  52. package/script/src/cli/mod.d.ts +1 -1
  53. package/script/src/cli/mod.d.ts.map +1 -1
  54. package/script/src/cli/mod.js +1034 -2
  55. package/script/src/mail/errors.d.ts +33 -0
  56. package/script/src/mail/errors.d.ts.map +1 -0
  57. package/script/src/mail/errors.js +97 -0
  58. package/script/src/mail/memory.d.ts +30 -0
  59. package/script/src/mail/memory.d.ts.map +1 -0
  60. package/script/src/mail/memory.js +345 -0
  61. package/script/src/mail/mod.d.ts +7 -0
  62. package/script/src/mail/mod.d.ts.map +1 -0
  63. package/script/src/mail/mod.js +22 -0
  64. package/script/src/mail/postal.d.ts +57 -0
  65. package/script/src/mail/postal.d.ts.map +1 -0
  66. package/script/src/mail/postal.js +245 -0
  67. package/script/src/mail/retry.d.ts +9 -0
  68. package/script/src/mail/retry.d.ts.map +1 -0
  69. package/script/src/mail/retry.js +22 -0
  70. package/script/src/mail/service.d.ts +23 -0
  71. package/script/src/mail/service.d.ts.map +1 -0
  72. package/script/src/mail/service.js +189 -0
  73. package/script/src/mail/types.d.ts +176 -0
  74. package/script/src/mail/types.d.ts.map +1 -0
  75. package/script/src/mail/types.js +2 -0
  76. package/script/src/mui/mail.d.ts +29 -0
  77. package/script/src/mui/mail.d.ts.map +1 -0
  78. package/script/src/mui/mail.js +159 -0
  79. package/script/src/mui/mailView.d.ts +20 -0
  80. package/script/src/mui/mailView.d.ts.map +1 -0
  81. package/script/src/mui/mailView.js +32 -0
  82. package/script/src/mui/mod.d.ts +1 -0
  83. package/script/src/mui/mod.d.ts.map +1 -1
  84. package/script/src/mui/mod.js +1 -0
  85. package/script/src/next/mail/mod.d.ts +3 -0
  86. package/script/src/next/mail/mod.d.ts.map +1 -0
  87. package/script/src/next/mail/mod.js +18 -0
  88. package/script/src/next/mail/route.d.ts +12 -0
  89. package/script/src/next/mail/route.d.ts.map +1 -0
  90. package/script/src/next/mail/route.js +46 -0
  91. package/skills/loom-mail/SKILL.md +68 -0
@@ -97,6 +97,12 @@ const managedSkills = [
97
97
  relativePackagePath: "skills/loom-files",
98
98
  skillName: "loom-files",
99
99
  },
100
+ {
101
+ featureKey: "mail",
102
+ label: "loom mail skill",
103
+ relativePackagePath: "skills/loom-mail",
104
+ skillName: "loom-mail",
105
+ },
100
106
  ];
101
107
  const featureDefinitions = [
102
108
  {
@@ -119,6 +125,10 @@ const featureDefinitions = [
119
125
  key: "jobs",
120
126
  description: "Shared App Router admin jobs pages, route handlers, direct-run helpers, and job controller wiring.",
121
127
  },
128
+ {
129
+ key: "mail",
130
+ description: "Durable outgoing mail, Postal transport/webhooks, and admin-gated test-mail UI.",
131
+ },
122
132
  {
123
133
  key: "pwa",
124
134
  description: "Shared Serwist PWA worker, provider lifecycle, update prompts, and build wiring.",
@@ -170,6 +180,13 @@ const DEFAULT_MINIO_ENDPOINT = "http://127.0.0.1:9000";
170
180
  const API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION = 3;
171
181
  const API_KEY_AUDIT_SCHEMA_DEFAULT_EXPORT = "loomApiKeyAuditEventsTable";
172
182
  const API_KEY_AUDIT_SCHEMA_DEFAULT_TABLE = "loom_api_key_audit_events";
183
+ const MAIL_SCHEMA_BLUEPRINT_VERSION = 1;
184
+ const MAIL_SCHEMA_DEFAULT_EXPORTS = [
185
+ "loomMailMessagesTable",
186
+ "loomMailDeliveriesTable",
187
+ "loomMailEventsTable",
188
+ ];
189
+ const MAIL_SCHEMA_DEFAULT_TABLE = "loom_mail_messages";
173
190
  const PWA_DEFAULT_DEPENDENCIES = {
174
191
  "@serwist/next": "^9.5.11",
175
192
  };
@@ -1417,6 +1434,145 @@ export const ${exportName} = pgTable(
1417
1434
  );
1418
1435
  `;
1419
1436
  }
1437
+ function buildMailSchemaText(config) {
1438
+ const [messagesExport, deliveriesExport, eventsExport] = [
1439
+ config.exports[0] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[0],
1440
+ config.exports[1] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[1],
1441
+ config.exports[2] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[2],
1442
+ ];
1443
+ const messagesTable = config.tableName;
1444
+ const tablePrefix = messagesTable.endsWith("_messages")
1445
+ ? messagesTable.slice(0, -"_messages".length)
1446
+ : messagesTable;
1447
+ const deliveriesTable = `${tablePrefix}_deliveries`;
1448
+ const eventsTable = `${tablePrefix}_events`;
1449
+ const indexName = (table, suffix) => filesSchemaIndexName(table, suffix);
1450
+ return `import { sql } from "drizzle-orm";
1451
+ import {
1452
+ index,
1453
+ integer,
1454
+ jsonb,
1455
+ pgTable,
1456
+ text,
1457
+ timestamp,
1458
+ uniqueIndex,
1459
+ uuid,
1460
+ } from "drizzle-orm/pg-core";
1461
+
1462
+ // Loom-managed schema blueprint: mail v${MAIL_SCHEMA_BLUEPRINT_VERSION}.
1463
+ // Keep app-specific domain associations in separate local schema files.
1464
+ export const ${messagesExport} = pgTable(
1465
+ "${messagesTable}",
1466
+ {
1467
+ id: uuid("id").default(sql\`uuid_generate_v7()\`).primaryKey(),
1468
+ provider: text("provider").notNull(),
1469
+ status: text("status").notNull().default("queued"),
1470
+ fromEmail: text("from_email").notNull(),
1471
+ fromName: text("from_name"),
1472
+ to: jsonb("to").notNull().$type<string[]>().default(sql\`'[]'::jsonb\`),
1473
+ cc: jsonb("cc").notNull().$type<string[]>().default(sql\`'[]'::jsonb\`),
1474
+ bcc: jsonb("bcc").notNull().$type<string[]>().default(sql\`'[]'::jsonb\`),
1475
+ subject: text("subject").notNull(),
1476
+ plainBody: text("plain_body"),
1477
+ htmlBody: text("html_body"),
1478
+ replyTo: text("reply_to"),
1479
+ tag: text("tag"),
1480
+ headers: jsonb("headers").notNull().$type<Record<string, string>>()
1481
+ .default(sql\`'{}'::jsonb\`),
1482
+ attachments: jsonb("attachments").notNull()
1483
+ .$type<Array<{ contentType?: string | null; data: string; name: string }>>()
1484
+ .default(sql\`'[]'::jsonb\`),
1485
+ metadata: jsonb("metadata").notNull().$type<Record<string, unknown>>()
1486
+ .default(sql\`'{}'::jsonb\`),
1487
+ providerMessageId: text("provider_message_id"),
1488
+ attemptCount: integer("attempt_count").notNull().default(0),
1489
+ availableAt: timestamp("available_at", { mode: "date", withTimezone: true })
1490
+ .notNull().defaultNow(),
1491
+ leaseToken: text("lease_token"),
1492
+ leaseExpiresAt: timestamp("lease_expires_at", { mode: "date", withTimezone: true }),
1493
+ lastErrorCode: text("last_error_code"),
1494
+ lastErrorMessage: text("last_error_message"),
1495
+ sentAt: timestamp("sent_at", { mode: "date", withTimezone: true }),
1496
+ failedAt: timestamp("failed_at", { mode: "date", withTimezone: true }),
1497
+ deliveredAt: timestamp("delivered_at", { mode: "date", withTimezone: true }),
1498
+ cancelledAt: timestamp("cancelled_at", { mode: "date", withTimezone: true }),
1499
+ createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
1500
+ .notNull().defaultNow(),
1501
+ updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
1502
+ .notNull().defaultNow(),
1503
+ },
1504
+ (table) => [
1505
+ index("${indexName(messagesTable, "outbox_idx")}").on(
1506
+ table.status,
1507
+ table.availableAt,
1508
+ table.leaseExpiresAt,
1509
+ ),
1510
+ index("${indexName(messagesTable, "provider_message_idx")}").on(
1511
+ table.provider,
1512
+ table.providerMessageId,
1513
+ ),
1514
+ index("${indexName(messagesTable, "created_idx")}").on(table.createdAt),
1515
+ ],
1516
+ );
1517
+
1518
+ export const ${deliveriesExport} = pgTable(
1519
+ "${deliveriesTable}",
1520
+ {
1521
+ id: uuid("id").default(sql\`uuid_generate_v7()\`).primaryKey(),
1522
+ messageId: uuid("message_id").notNull()
1523
+ .references(() => ${messagesExport}.id, { onDelete: "cascade" }),
1524
+ kind: text("kind").notNull(),
1525
+ email: text("email").notNull(),
1526
+ status: text("status").notNull().default("queued"),
1527
+ providerDeliveryId: text("provider_delivery_id"),
1528
+ providerToken: text("provider_token"),
1529
+ lastErrorCode: text("last_error_code"),
1530
+ lastErrorMessage: text("last_error_message"),
1531
+ deliveredAt: timestamp("delivered_at", { mode: "date", withTimezone: true }),
1532
+ createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
1533
+ .notNull().defaultNow(),
1534
+ updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
1535
+ .notNull().defaultNow(),
1536
+ },
1537
+ (table) => [
1538
+ index("${indexName(deliveriesTable, "message_idx")}").on(table.messageId),
1539
+ index("${indexName(deliveriesTable, "provider_delivery_idx")}").on(
1540
+ table.providerDeliveryId,
1541
+ ),
1542
+ index("${indexName(deliveriesTable, "recipient_idx")}").on(table.email),
1543
+ ],
1544
+ );
1545
+
1546
+ export const ${eventsExport} = pgTable(
1547
+ "${eventsTable}",
1548
+ {
1549
+ id: uuid("id").default(sql\`uuid_generate_v7()\`).primaryKey(),
1550
+ messageId: uuid("message_id").notNull()
1551
+ .references(() => ${messagesExport}.id, { onDelete: "cascade" }),
1552
+ deliveryId: uuid("delivery_id")
1553
+ .references(() => ${deliveriesExport}.id, { onDelete: "set null" }),
1554
+ provider: text("provider").notNull(),
1555
+ providerEventId: text("provider_event_id"),
1556
+ eventType: text("event_type").notNull(),
1557
+ sourceEvent: text("source_event").notNull(),
1558
+ payload: jsonb("payload").notNull().$type<Record<string, unknown>>()
1559
+ .default(sql\`'{}'::jsonb\`),
1560
+ occurredAt: timestamp("occurred_at", { mode: "date", withTimezone: true })
1561
+ .notNull().defaultNow(),
1562
+ },
1563
+ (table) => [
1564
+ index("${indexName(eventsTable, "message_occurred_idx")}").on(
1565
+ table.messageId,
1566
+ table.occurredAt,
1567
+ ),
1568
+ uniqueIndex("${indexName(eventsTable, "provider_event_unique")}").on(
1569
+ table.provider,
1570
+ table.providerEventId,
1571
+ ),
1572
+ ],
1573
+ );
1574
+ `;
1575
+ }
1420
1576
  function getFilesDefaultSchemaConfig(dbConfig) {
1421
1577
  const baseConfig = {
1422
1578
  blueprint: "files",
@@ -1432,6 +1588,20 @@ function getFilesDefaultSchemaConfig(dbConfig) {
1432
1588
  hash: hashManagedSchemaText(buildFilesSchemaText(baseConfig)),
1433
1589
  };
1434
1590
  }
1591
+ function getMailDefaultSchemaConfig(dbConfig) {
1592
+ const baseConfig = {
1593
+ blueprint: "mail",
1594
+ exports: [...MAIL_SCHEMA_DEFAULT_EXPORTS],
1595
+ mode: "managed-local",
1596
+ module: join(dbConfig.dirs.schemaDir, "loomMail.ts"),
1597
+ tableName: MAIL_SCHEMA_DEFAULT_TABLE,
1598
+ version: MAIL_SCHEMA_BLUEPRINT_VERSION,
1599
+ };
1600
+ return {
1601
+ ...baseConfig,
1602
+ hash: hashManagedSchemaText(buildMailSchemaText(baseConfig)),
1603
+ };
1604
+ }
1435
1605
  function getApiKeysDefaultSchemaConfig(dbConfig) {
1436
1606
  const baseConfig = {
1437
1607
  blueprint: "api-key-audit",
@@ -1527,6 +1697,23 @@ function mergeManagedLocalSchemaConfig(dbConfig, schemaConfig) {
1527
1697
  hashManagedSchemaText(buildFilesSchemaText(merged)),
1528
1698
  };
1529
1699
  }
1700
+ function mergeMailSchemaConfig(dbConfig, schemaConfig) {
1701
+ const defaults = getMailDefaultSchemaConfig(dbConfig);
1702
+ const merged = {
1703
+ ...defaults,
1704
+ ...schemaConfig,
1705
+ blueprint: "mail",
1706
+ exports: schemaConfig?.exports?.length === 3
1707
+ ? schemaConfig.exports
1708
+ : defaults.exports,
1709
+ mode: "managed-local",
1710
+ };
1711
+ return {
1712
+ ...merged,
1713
+ hash: schemaConfig?.hash ??
1714
+ hashManagedSchemaText(buildMailSchemaText(merged)),
1715
+ };
1716
+ }
1530
1717
  function getFilesConfig(framework, dbConfig, featureConfig) {
1531
1718
  const appRoot = framework.srcDir ? "src/app" : "app";
1532
1719
  const filesRoot = framework.srcDir ? "src/files" : "files";
@@ -1550,6 +1737,44 @@ function getFilesConfig(framework, dbConfig, featureConfig) {
1550
1737
  },
1551
1738
  };
1552
1739
  }
1740
+ function getMailConfig(framework, dbConfig, packageJson, featureConfig, jobsActive) {
1741
+ const appRoot = framework.srcDir ? "src/app" : "app";
1742
+ const mailRoot = framework.srcDir ? "src/mail" : "mail";
1743
+ const jobsRoot = framework.srcDir ? "src/jobs" : "jobs";
1744
+ return {
1745
+ entrypoints: {
1746
+ adminPage: featureConfig?.entrypoints?.adminPage ??
1747
+ `${appRoot}/admin/mail/page.tsx`,
1748
+ webhookRoute: featureConfig?.entrypoints?.webhookRoute ??
1749
+ `${appRoot}/api/mail/postal/route.ts`,
1750
+ },
1751
+ jobs: {
1752
+ enabled: featureConfig?.jobs?.enabled ?? jobsActive,
1753
+ },
1754
+ modules: {
1755
+ accessModule: featureConfig?.modules?.accessModule ??
1756
+ `${mailRoot}/access.ts`,
1757
+ actionsModule: featureConfig?.modules?.actionsModule ??
1758
+ `${mailRoot}/actions.ts`,
1759
+ jobModule: featureConfig?.modules?.jobModule ??
1760
+ `${jobsRoot}/mail-drain.ts`,
1761
+ repositoryModule: featureConfig?.modules?.repositoryModule ??
1762
+ `${mailRoot}/repository.ts`,
1763
+ serviceModule: featureConfig?.modules?.serviceModule ??
1764
+ `${mailRoot}/service.ts`,
1765
+ transportModule: featureConfig?.modules?.transportModule ??
1766
+ `${mailRoot}/transport.ts`,
1767
+ },
1768
+ provider: "postal",
1769
+ schema: mergeMailSchemaConfig(dbConfig, featureConfig?.schema),
1770
+ ui: {
1771
+ adapter: featureConfig?.ui?.adapter ??
1772
+ (hasPackageDependency(packageJson, "@mui/material")
1773
+ ? "mui"
1774
+ : "headless"),
1775
+ },
1776
+ };
1777
+ }
1553
1778
  function normalizeText(text) {
1554
1779
  return text.replaceAll("\r\n", "\n");
1555
1780
  }
@@ -4059,6 +4284,560 @@ export const { GET, POST } = createFilesRouteHandlers({
4059
4284
  });
4060
4285
  `;
4061
4286
  }
4287
+ function mailAccessTemplate() {
4288
+ return `// Generated deny-all boundary. Replace with the app's fresh admin check.
4289
+ export async function authorizeMailAdmin(): Promise<void> {
4290
+ throw new Error("Mail admin access policy is not configured.");
4291
+ }
4292
+ `;
4293
+ }
4294
+ function mailTransportTemplate() {
4295
+ return `import type { LoomMailTransport } from "@gadicc/loom/mail";
4296
+ import {
4297
+ createPostalMailTransport,
4298
+ type PostalWebhookPublicKey,
4299
+ } from "@gadicc/loom/mail/postal";
4300
+
4301
+ function requireEnv(name: "POSTAL_API_KEY" | "POSTAL_FROM_EMAIL" | "POSTAL_HOST") {
4302
+ const value = process.env[name]?.trim();
4303
+ if (!value) throw new Error(\`\${name} is not set.\`);
4304
+ return value;
4305
+ }
4306
+
4307
+ export const mailTransport: LoomMailTransport = {
4308
+ provider: "postal",
4309
+ send(message) {
4310
+ return createPostalMailTransport({
4311
+ apiKey: requireEnv("POSTAL_API_KEY"),
4312
+ host: requireEnv("POSTAL_HOST"),
4313
+ }).send(message);
4314
+ },
4315
+ };
4316
+
4317
+ export function getDefaultMailFromEmail() {
4318
+ return requireEnv("POSTAL_FROM_EMAIL");
4319
+ }
4320
+
4321
+ export function getPostalWebhookPublicKeys(): PostalWebhookPublicKey[] {
4322
+ const raw = process.env.POSTAL_WEBHOOK_PUBLIC_KEYS?.trim();
4323
+ if (!raw) throw new Error("POSTAL_WEBHOOK_PUBLIC_KEYS is not set.");
4324
+ const parsed = JSON.parse(raw) as unknown;
4325
+ if (!Array.isArray(parsed)) {
4326
+ throw new Error("POSTAL_WEBHOOK_PUBLIC_KEYS must be a JSON array of public JWKs.");
4327
+ }
4328
+ return parsed.map((candidate) => {
4329
+ if (
4330
+ typeof candidate !== "object" || candidate === null ||
4331
+ !("kid" in candidate) || typeof candidate.kid !== "string" ||
4332
+ !("kty" in candidate) || candidate.kty !== "RSA"
4333
+ ) {
4334
+ throw new Error("Every Postal webhook key must be an RSA JWK with a kid.");
4335
+ }
4336
+ return candidate as PostalWebhookPublicKey;
4337
+ });
4338
+ }
4339
+ `;
4340
+ }
4341
+ function mailServiceTemplate(config) {
4342
+ return `import { createLoomMailService } from "@gadicc/loom/mail";
4343
+ import { mailRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4344
+ import {
4345
+ getDefaultMailFromEmail,
4346
+ mailTransport,
4347
+ } from "${toAliasImportPath(config.modules.transportModule)}";
4348
+
4349
+ export const mailService = createLoomMailService({
4350
+ get defaultFromEmail() {
4351
+ return getDefaultMailFromEmail();
4352
+ },
4353
+ repository: mailRepository,
4354
+ transport: mailTransport,
4355
+ });
4356
+ `;
4357
+ }
4358
+ function mailRepositoryTemplate(config, dbConfig) {
4359
+ const [messages, deliveries, events] = [
4360
+ config.schema.exports[0] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[0],
4361
+ config.schema.exports[1] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[1],
4362
+ config.schema.exports[2] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[2],
4363
+ ];
4364
+ return `import { and, asc, desc, eq, lte, or } from "drizzle-orm";
4365
+ import type {
4366
+ LoomMailDeliveryRecord,
4367
+ LoomMailDeliveryStatus,
4368
+ LoomMailMessageRecord,
4369
+ LoomMailRepository,
4370
+ } from "@gadicc/loom/mail";
4371
+ import { db } from "${toAliasImportPath(dbConfig.modules.neonFullModule)}";
4372
+ import {
4373
+ ${deliveries},
4374
+ ${events},
4375
+ ${messages},
4376
+ } from "${toAliasImportPath(config.schema.module)}";
4377
+
4378
+ type MessageRow = typeof ${messages}.$inferSelect;
4379
+ type MessageInsert = typeof ${messages}.$inferInsert;
4380
+ type DeliveryRow = typeof ${deliveries}.$inferSelect;
4381
+
4382
+ function toMessage(row: MessageRow): LoomMailMessageRecord {
4383
+ return row as LoomMailMessageRecord;
4384
+ }
4385
+
4386
+ function toDelivery(row: DeliveryRow): LoomMailDeliveryRecord {
4387
+ return row as LoomMailDeliveryRecord;
4388
+ }
4389
+
4390
+ function aggregateStatus(statuses: LoomMailDeliveryStatus[]) {
4391
+ if (statuses.length === 0) return "sent" as const;
4392
+ if (statuses.every((status) => status === "delivered")) return "delivered" as const;
4393
+ const terminal = new Set<LoomMailDeliveryStatus>([
4394
+ "bounced", "cancelled", "delivered", "failed",
4395
+ ]);
4396
+ if (statuses.every((status) => terminal.has(status))) {
4397
+ return statuses.includes("delivered") ? "partially_delivered" as const : "failed" as const;
4398
+ }
4399
+ return "sent" as const;
4400
+ }
4401
+
4402
+ export const mailRepository = {
4403
+ async cancel(messageId, occurredAt) {
4404
+ return db.transaction(async (trx) => {
4405
+ const [current] = await trx.select().from(${messages})
4406
+ .where(eq(${messages}.id, messageId)).limit(1).for("update");
4407
+ if (!current || !["queued", "failed"].includes(current.status)) return false;
4408
+ await trx.update(${messages}).set({
4409
+ cancelledAt: occurredAt,
4410
+ leaseExpiresAt: null,
4411
+ leaseToken: null,
4412
+ status: "cancelled",
4413
+ updatedAt: occurredAt,
4414
+ }).where(eq(${messages}.id, messageId));
4415
+ await trx.update(${deliveries}).set({ status: "cancelled", updatedAt: occurredAt })
4416
+ .where(and(eq(${deliveries}.messageId, messageId), eq(${deliveries}.status, "queued")));
4417
+ await trx.insert(${events}).values({
4418
+ eventType: "cancelled",
4419
+ messageId,
4420
+ payload: {},
4421
+ provider: current.provider,
4422
+ sourceEvent: "cancelled",
4423
+ occurredAt,
4424
+ });
4425
+ return true;
4426
+ });
4427
+ },
4428
+
4429
+ async claim(request) {
4430
+ return db.transaction(async (trx) => {
4431
+ const due = or(
4432
+ eq(${messages}.status, "queued"),
4433
+ and(eq(${messages}.status, "sending"), lte(${messages}.leaseExpiresAt, request.now)),
4434
+ );
4435
+ const [current] = await trx.select().from(${messages})
4436
+ .where(and(
4437
+ request.messageId ? eq(${messages}.id, request.messageId) : undefined,
4438
+ lte(${messages}.availableAt, request.now),
4439
+ due,
4440
+ ))
4441
+ .orderBy(asc(${messages}.availableAt), asc(${messages}.createdAt))
4442
+ .limit(1)
4443
+ .for("update", { skipLocked: true });
4444
+ if (!current) return null;
4445
+ const [claimed] = await trx.update(${messages}).set({
4446
+ attemptCount: current.attemptCount + 1,
4447
+ leaseExpiresAt: request.leaseExpiresAt,
4448
+ leaseToken: request.leaseToken,
4449
+ status: "sending",
4450
+ updatedAt: request.now,
4451
+ }).where(eq(${messages}.id, current.id)).returning();
4452
+ if (!claimed) return null;
4453
+ await trx.insert(${events}).values({
4454
+ eventType: "attempted",
4455
+ messageId: current.id,
4456
+ payload: {
4457
+ attemptCount: claimed.attemptCount,
4458
+ leaseExpiresAt: request.leaseExpiresAt.toISOString(),
4459
+ },
4460
+ provider: current.provider,
4461
+ sourceEvent: "attempted",
4462
+ occurredAt: request.now,
4463
+ });
4464
+ return toMessage(claimed) as ReturnType<typeof toMessage> & {
4465
+ leaseExpiresAt: Date;
4466
+ leaseToken: string;
4467
+ status: "sending";
4468
+ };
4469
+ });
4470
+ },
4471
+
4472
+ async completeFailure(input) {
4473
+ return db.transaction(async (trx) => {
4474
+ const [updated] = await trx.update(${messages}).set({
4475
+ availableAt: input.retryAt ?? input.occurredAt,
4476
+ failedAt: input.retryAt ? null : input.occurredAt,
4477
+ lastErrorCode: input.failure.code,
4478
+ lastErrorMessage: input.failure.message,
4479
+ leaseExpiresAt: null,
4480
+ leaseToken: null,
4481
+ status: input.retryAt ? "queued" : "failed",
4482
+ updatedAt: input.occurredAt,
4483
+ }).where(and(
4484
+ eq(${messages}.id, input.messageId),
4485
+ eq(${messages}.status, "sending"),
4486
+ eq(${messages}.leaseToken, input.leaseToken),
4487
+ )).returning({ provider: ${messages}.provider });
4488
+ if (!updated) return false;
4489
+ await trx.insert(${events}).values({
4490
+ eventType: input.retryAt ? "retry_scheduled" : "failed",
4491
+ messageId: input.messageId,
4492
+ payload: {
4493
+ code: input.failure.code,
4494
+ message: input.failure.message,
4495
+ retryAt: input.retryAt?.toISOString() ?? null,
4496
+ retryable: input.failure.retryable,
4497
+ ...input.failure.payload,
4498
+ },
4499
+ provider: updated.provider,
4500
+ sourceEvent: input.retryAt ? "retry_scheduled" : "failed",
4501
+ occurredAt: input.occurredAt,
4502
+ });
4503
+ return true;
4504
+ });
4505
+ },
4506
+
4507
+ async completeSuccess(input) {
4508
+ return db.transaction(async (trx) => {
4509
+ const [updated] = await trx.update(${messages}).set({
4510
+ lastErrorCode: null,
4511
+ lastErrorMessage: null,
4512
+ leaseExpiresAt: null,
4513
+ leaseToken: null,
4514
+ providerMessageId: input.result.providerMessageId,
4515
+ sentAt: input.occurredAt,
4516
+ status: "sent",
4517
+ updatedAt: input.occurredAt,
4518
+ }).where(and(
4519
+ eq(${messages}.id, input.messageId),
4520
+ eq(${messages}.status, "sending"),
4521
+ eq(${messages}.leaseToken, input.leaseToken),
4522
+ )).returning({ provider: ${messages}.provider });
4523
+ if (!updated) return false;
4524
+ for (const result of input.result.deliveries) {
4525
+ await trx.update(${deliveries}).set({
4526
+ providerDeliveryId: result.providerDeliveryId,
4527
+ providerToken: result.providerToken,
4528
+ status: "accepted",
4529
+ updatedAt: input.occurredAt,
4530
+ }).where(and(
4531
+ eq(${deliveries}.messageId, input.messageId),
4532
+ eq(${deliveries}.email, result.email),
4533
+ eq(${deliveries}.status, "queued"),
4534
+ ));
4535
+ }
4536
+ await trx.insert(${events}).values({
4537
+ eventType: "sent",
4538
+ messageId: input.messageId,
4539
+ payload: {
4540
+ providerMessageId: input.result.providerMessageId,
4541
+ providerResponse: input.result.providerResponse ?? {},
4542
+ },
4543
+ provider: updated.provider,
4544
+ sourceEvent: "sent",
4545
+ occurredAt: input.occurredAt,
4546
+ });
4547
+ return true;
4548
+ });
4549
+ },
4550
+
4551
+ async enqueue(input, occurredAt) {
4552
+ return db.transaction(async (trx) => {
4553
+ const [message] = await trx.insert(${messages}).values({
4554
+ ...input,
4555
+ availableAt: occurredAt,
4556
+ createdAt: occurredAt,
4557
+ updatedAt: occurredAt,
4558
+ } as MessageInsert).returning();
4559
+ if (!message) throw new Error("Failed to enqueue mail.");
4560
+ const recipients = [
4561
+ ...input.to.map((email) => ({ email, kind: "to" })),
4562
+ ...input.cc.map((email) => ({ email, kind: "cc" })),
4563
+ ...input.bcc.map((email) => ({ email, kind: "bcc" })),
4564
+ ];
4565
+ await trx.insert(${deliveries}).values(recipients.map((recipient) => ({
4566
+ ...recipient,
4567
+ messageId: message.id,
4568
+ createdAt: occurredAt,
4569
+ updatedAt: occurredAt,
4570
+ })));
4571
+ await trx.insert(${events}).values({
4572
+ eventType: "queued",
4573
+ messageId: message.id,
4574
+ payload: { bcc: input.bcc, cc: input.cc, to: input.to },
4575
+ provider: input.provider,
4576
+ sourceEvent: "queued",
4577
+ occurredAt,
4578
+ });
4579
+ return toMessage(message);
4580
+ });
4581
+ },
4582
+
4583
+ async findById(messageId) {
4584
+ const [row] = await db.select().from(${messages})
4585
+ .where(eq(${messages}.id, messageId)).limit(1);
4586
+ return row ? toMessage(row) : null;
4587
+ },
4588
+
4589
+ async listDeliveries(messageId: string) {
4590
+ const rows = await db.select().from(${deliveries})
4591
+ .where(eq(${deliveries}.messageId, messageId));
4592
+ return rows.map(toDelivery);
4593
+ },
4594
+
4595
+ async listRecent(limit = 100) {
4596
+ const rows = await db.select().from(${messages})
4597
+ .orderBy(desc(${messages}.createdAt)).limit(limit);
4598
+ return rows.map(toMessage);
4599
+ },
4600
+
4601
+ async recordProviderEvent(event) {
4602
+ return db.transaction(async (trx) => {
4603
+ let [delivery] = event.providerDeliveryId
4604
+ ? await trx.select().from(${deliveries})
4605
+ .where(eq(${deliveries}.providerDeliveryId, event.providerDeliveryId)).limit(1)
4606
+ : [];
4607
+ let [message] = delivery
4608
+ ? await trx.select().from(${messages})
4609
+ .where(eq(${messages}.id, delivery.messageId)).limit(1)
4610
+ : event.providerMessageId
4611
+ ? await trx.select().from(${messages})
4612
+ .where(and(
4613
+ eq(${messages}.provider, event.provider),
4614
+ eq(${messages}.providerMessageId, event.providerMessageId),
4615
+ )).limit(1)
4616
+ : [];
4617
+ if (message && message.provider !== event.provider) {
4618
+ return { inserted: false, messageId: null };
4619
+ }
4620
+ if (!message) return { inserted: false, messageId: null };
4621
+ if (!delivery && event.recipient) {
4622
+ [delivery] = await trx.select().from(${deliveries}).where(and(
4623
+ eq(${deliveries}.messageId, message.id),
4624
+ eq(${deliveries}.email, event.recipient),
4625
+ )).limit(1);
4626
+ }
4627
+ const [inserted] = await trx.insert(${events}).values({
4628
+ deliveryId: delivery?.id ?? null,
4629
+ eventType: event.eventType,
4630
+ messageId: message.id,
4631
+ occurredAt: event.occurredAt,
4632
+ payload: event.payload,
4633
+ provider: event.provider,
4634
+ providerEventId: event.providerEventId,
4635
+ sourceEvent: event.sourceEvent,
4636
+ }).onConflictDoNothing().returning({ id: ${events}.id });
4637
+ if (!inserted) return { inserted: false, messageId: message.id };
4638
+
4639
+ if (delivery && event.eventType !== "unknown") {
4640
+ const nextStatus = event.eventType;
4641
+ await trx.update(${deliveries}).set({
4642
+ deliveredAt: nextStatus === "delivered" ? event.occurredAt : delivery.deliveredAt,
4643
+ lastErrorCode: ["bounced", "failed", "held"].includes(nextStatus)
4644
+ ? event.sourceEvent : delivery.lastErrorCode,
4645
+ lastErrorMessage: ["bounced", "failed", "held"].includes(nextStatus)
4646
+ ? String(event.payload.message ?? event.sourceEvent) : delivery.lastErrorMessage,
4647
+ status: nextStatus,
4648
+ updatedAt: event.occurredAt,
4649
+ }).where(eq(${deliveries}.id, delivery.id));
4650
+ }
4651
+ const statusRows = await trx.select({ status: ${deliveries}.status })
4652
+ .from(${deliveries}).where(eq(${deliveries}.messageId, message.id));
4653
+ const status = aggregateStatus(
4654
+ statusRows.map((row) => row.status as LoomMailDeliveryStatus),
4655
+ );
4656
+ await trx.update(${messages}).set({
4657
+ deliveredAt: status === "delivered" ? event.occurredAt : message.deliveredAt,
4658
+ failedAt: status === "failed" ? event.occurredAt : message.failedAt,
4659
+ status,
4660
+ updatedAt: event.occurredAt,
4661
+ }).where(eq(${messages}.id, message.id));
4662
+ return { inserted: true, messageId: message.id };
4663
+ });
4664
+ },
4665
+ } satisfies LoomMailRepository & {
4666
+ listDeliveries(messageId: string): Promise<LoomMailDeliveryRecord[]>;
4667
+ listRecent(limit?: number): Promise<LoomMailMessageRecord[]>;
4668
+ };
4669
+ `;
4670
+ }
4671
+ function mailActionsTemplate(config) {
4672
+ const adminPath = config.entrypoints.adminPage
4673
+ .replace(/^src\/app|^app/, "")
4674
+ .replace(/\/page\.tsx$/, "") || "/";
4675
+ return `"use server";
4676
+
4677
+ import { LoomMailDeliveryError } from "@gadicc/loom/mail";
4678
+ import { revalidatePath } from "next/cache";
4679
+ import { authorizeMailAdmin } from "${toAliasImportPath(config.modules.accessModule)}";
4680
+ import { mailRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4681
+ import { mailService } from "${toAliasImportPath(config.modules.serviceModule)}";
4682
+
4683
+ export interface MailTestActionState {
4684
+ message: string | null;
4685
+ messageId?: string;
4686
+ status: "error" | "idle" | "success";
4687
+ }
4688
+
4689
+ function text(formData: FormData, key: string) {
4690
+ const value = formData.get(key);
4691
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
4692
+ }
4693
+
4694
+ function recipients(value?: string) {
4695
+ return (value ?? "").split(/[,\\n]+/).map((item) => item.trim()).filter(Boolean);
4696
+ }
4697
+
4698
+ export async function sendTestMail(
4699
+ _previous: MailTestActionState,
4700
+ formData: FormData,
4701
+ ): Promise<MailTestActionState> {
4702
+ await authorizeMailAdmin();
4703
+ try {
4704
+ const result = await mailService.sendMail({
4705
+ bcc: recipients(text(formData, "bcc")),
4706
+ cc: recipients(text(formData, "cc")),
4707
+ htmlBody: text(formData, "htmlBody"),
4708
+ metadata: { sentFromMailAdmin: true },
4709
+ plainBody: text(formData, "plainBody"),
4710
+ replyTo: text(formData, "replyTo"),
4711
+ subject: text(formData, "subject") ?? "",
4712
+ tag: text(formData, "tag"),
4713
+ to: recipients(text(formData, "to")),
4714
+ });
4715
+ revalidatePath("${adminPath}");
4716
+ return {
4717
+ message: "Test email accepted by the provider.",
4718
+ messageId: result.message.id,
4719
+ status: "success",
4720
+ };
4721
+ } catch (error) {
4722
+ return {
4723
+ message: error instanceof Error ? error.message : "Mail send failed.",
4724
+ messageId: error instanceof LoomMailDeliveryError ? error.messageId : undefined,
4725
+ status: "error",
4726
+ };
4727
+ }
4728
+ }
4729
+
4730
+ function requiredMessageId(formData: FormData) {
4731
+ const messageId = text(formData, "messageId");
4732
+ if (!messageId) throw new Error("Missing mail message id.");
4733
+ return messageId;
4734
+ }
4735
+
4736
+ export async function cancelMail(formData: FormData) {
4737
+ await authorizeMailAdmin();
4738
+ if (!await mailService.cancelMail(requiredMessageId(formData))) {
4739
+ throw new Error("Mail message cannot be cancelled in its current state.");
4740
+ }
4741
+ revalidatePath("${adminPath}");
4742
+ }
4743
+
4744
+ export async function retryMail(formData: FormData) {
4745
+ await authorizeMailAdmin();
4746
+ const sourceId = requiredMessageId(formData);
4747
+ const source = await mailRepository.findById(sourceId);
4748
+ if (!source) throw new Error("Mail message not found.");
4749
+ await mailService.sendMail({
4750
+ attachments: source.attachments,
4751
+ bcc: source.bcc,
4752
+ cc: source.cc,
4753
+ fromEmail: source.fromEmail,
4754
+ fromName: source.fromName ?? undefined,
4755
+ headers: source.headers,
4756
+ htmlBody: source.htmlBody ?? undefined,
4757
+ metadata: { ...source.metadata, retriedFromMessageId: source.id },
4758
+ plainBody: source.plainBody ?? undefined,
4759
+ replyTo: source.replyTo ?? undefined,
4760
+ subject: source.subject,
4761
+ tag: source.tag ?? undefined,
4762
+ to: source.to,
4763
+ });
4764
+ revalidatePath("${adminPath}");
4765
+ }
4766
+ `;
4767
+ }
4768
+ function mailAdminPageTemplate(config) {
4769
+ if (config.ui.adapter !== "mui") {
4770
+ return `import { authorizeMailAdmin } from "${toAliasImportPath(config.modules.accessModule)}";
4771
+
4772
+ export default async function MailAdminPage() {
4773
+ await authorizeMailAdmin();
4774
+ return <main><h1>Mail</h1><p>Connect an app-owned admin UI to the Loom mail service.</p></main>;
4775
+ }
4776
+ `;
4777
+ }
4778
+ return `import { AdminMailConsole, type MailAdminRow } from "@gadicc/loom/mui/mail";
4779
+ import { authorizeMailAdmin } from "${toAliasImportPath(config.modules.accessModule)}";
4780
+ import { cancelMail, retryMail, sendTestMail } from "${toAliasImportPath(config.modules.actionsModule)}";
4781
+ import { mailRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4782
+
4783
+ export default async function MailAdminPage() {
4784
+ await authorizeMailAdmin();
4785
+ const messages = await mailRepository.listRecent(100);
4786
+ const deliveries = await Promise.all(
4787
+ messages.map((message) => mailRepository.listDeliveries(message.id)),
4788
+ );
4789
+ const rows: MailAdminRow[] = messages.map((message, index) => ({
4790
+ createdAt: message.createdAt.toISOString(),
4791
+ id: message.id,
4792
+ providerMessageId: message.providerMessageId,
4793
+ recipients: (deliveries[index] ?? []).map((delivery) => ({
4794
+ email: delivery.email,
4795
+ kind: delivery.kind,
4796
+ status: delivery.status,
4797
+ })),
4798
+ status: message.status,
4799
+ subject: message.subject,
4800
+ tag: message.tag,
4801
+ }));
4802
+ return (
4803
+ <AdminMailConsole
4804
+ cancelAction={cancelMail}
4805
+ retryAction={retryMail}
4806
+ rows={rows}
4807
+ testAction={sendTestMail}
4808
+ />
4809
+ );
4810
+ }
4811
+ `;
4812
+ }
4813
+ function mailWebhookRouteTemplate(config) {
4814
+ return `import { createPostalWebhookRouteHandler } from "@gadicc/loom/next/mail";
4815
+ import { mailService } from "${toAliasImportPath(config.modules.serviceModule)}";
4816
+ import { getPostalWebhookPublicKeys } from "${toAliasImportPath(config.modules.transportModule)}";
4817
+
4818
+ export const POST = createPostalWebhookRouteHandler({
4819
+ handleEvent: (event) => mailService.handleProviderEvent(event),
4820
+ publicKeys: getPostalWebhookPublicKeys,
4821
+ });
4822
+ `;
4823
+ }
4824
+ function mailJobTemplate(config) {
4825
+ return `import type { Job } from "@gadicc/loom/jobs";
4826
+ import { mailService } from "${toAliasImportPath(config.modules.serviceModule)}";
4827
+
4828
+ export const meta = {
4829
+ id: "mail-drain",
4830
+ desc: "Deliver due messages from the durable mail outbox.",
4831
+ };
4832
+
4833
+ export const handler: Job["handler"] = async (job, params) => {
4834
+ const parsed = typeof params.limit === "string" ? Number(params.limit) : Number.NaN;
4835
+ const limit = Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 20;
4836
+ const result = await mailService.drain(limit);
4837
+ job.json({ result });
4838
+ };
4839
+ `;
4840
+ }
4062
4841
  async function readTsModuleNames(path) {
4063
4842
  try {
4064
4843
  const entries = await readdir(path, { withFileTypes: true });
@@ -4101,7 +4880,9 @@ function getLatestManagedSchemaConfig(schema) {
4101
4880
  ? schema.idGeneration === "uuid-v7"
4102
4881
  ? FILES_SCHEMA_UUID_V7_BLUEPRINT_VERSION
4103
4882
  : FILES_SCHEMA_UUID_V4_BLUEPRINT_VERSION
4104
- : API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION,
4883
+ : schema.blueprint === "mail"
4884
+ ? MAIL_SCHEMA_BLUEPRINT_VERSION
4885
+ : API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION,
4105
4886
  };
4106
4887
  return {
4107
4888
  ...latest,
@@ -4114,6 +4895,8 @@ function getManagedSchemaText(schema) {
4114
4895
  return buildApiKeyAuditSchemaText(schema);
4115
4896
  case "files":
4116
4897
  return buildFilesSchemaText(schema);
4898
+ case "mail":
4899
+ return buildMailSchemaText(schema);
4117
4900
  }
4118
4901
  }
4119
4902
  function getSchemaBarrelExportLine(schema, dbConfig) {
@@ -4295,8 +5078,25 @@ export async function syncDbSchemas(cwd) {
4295
5078
  suggestions.add("Move API-key audit schema additions to separate local schema files, then rerun `loom db schemas sync`.");
4296
5079
  }
4297
5080
  }
5081
+ const mailFeature = manifest.features.mail;
5082
+ if (mailFeature?.status === "active") {
5083
+ const mailConfig = getMailConfig(framework, dbConfig, (await readProjectPackageJson(cwd)).packageJson, mailFeature.config, manifest.features.jobs?.status === "active");
5084
+ const materialized = await materializeManagedSchema(cwd, mailConfig.schema, dbConfig);
5085
+ changedFiles.push(...materialized.changedFiles);
5086
+ issues.push(...materialized.issues);
5087
+ notes.push(...materialized.notes);
5088
+ if (!materialized.issues.length) {
5089
+ mailConfig.schema = materialized.schema;
5090
+ mailFeature.config = mailConfig;
5091
+ manifest.features.mail = mailFeature;
5092
+ }
5093
+ else {
5094
+ suggestions.add("Move mail schema additions to separate local schema files, then rerun `loom db schemas sync`.");
5095
+ }
5096
+ }
4298
5097
  if ((!filesFeature || filesFeature.status !== "active") &&
4299
- (!apiKeysFeature || apiKeysFeature.status !== "active")) {
5098
+ (!apiKeysFeature || apiKeysFeature.status !== "active") &&
5099
+ (!mailFeature || mailFeature.status !== "active")) {
4300
5100
  notes.push("No active Loom-managed DB schemas are configured.");
4301
5101
  }
4302
5102
  const manifestPath = join(cwd, "loom.json");
@@ -6523,6 +7323,93 @@ async function applyFilesFeature(cwd, framework, manifest, activate) {
6523
7323
  manifest.features.files = feature;
6524
7324
  return { changedFiles, notes };
6525
7325
  }
7326
+ async function applyMailFeature(cwd, framework, manifest, activate) {
7327
+ const changedFiles = [];
7328
+ const notes = [];
7329
+ const currentFeature = manifest.features.mail;
7330
+ if (!activate && currentFeature?.status !== "active") {
7331
+ return { changedFiles, notes };
7332
+ }
7333
+ for (const dependency of ["auth", "db"]) {
7334
+ if (manifest.features[dependency]?.status !== "active") {
7335
+ if (activate) {
7336
+ throw new Error(`The mail feature requires the active ${dependency} feature. Run \`loom add ${dependency}\` first.`);
7337
+ }
7338
+ notes.push(`Mail requires the active ${dependency} feature.`);
7339
+ return { changedFiles, notes };
7340
+ }
7341
+ }
7342
+ const { packageJson } = await readProjectPackageJson(cwd);
7343
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
7344
+ const config = getMailConfig(framework, dbConfig, packageJson, currentFeature?.config, manifest.features.jobs?.status === "active");
7345
+ const feature = currentFeature
7346
+ ? structuredClone(currentFeature)
7347
+ : { status: "planned" };
7348
+ if (activate && feature.status !== "active") {
7349
+ feature.status = "active";
7350
+ feature.activatedOn ??= todayIso();
7351
+ }
7352
+ if (activate) {
7353
+ const materialized = await materializeManagedSchema(cwd, config.schema, dbConfig);
7354
+ if (materialized.issues.length) {
7355
+ throw new Error(materialized.issues.join("\n"));
7356
+ }
7357
+ changedFiles.push(...materialized.changedFiles);
7358
+ notes.push(...materialized.notes);
7359
+ config.schema = materialized.schema;
7360
+ notes.push("No migration was generated. Review the mail schema diff, then create and apply the app-local migration deliberately.", "Configure POSTAL_API_KEY, POSTAL_HOST, POSTAL_FROM_EMAIL, and POSTAL_WEBHOOK_PUBLIC_KEYS before sending mail or receiving webhooks.");
7361
+ }
7362
+ const scaffolds = [
7363
+ [config.modules.accessModule, mailAccessTemplate(), "admin access policy"],
7364
+ [
7365
+ config.modules.repositoryModule,
7366
+ mailRepositoryTemplate(config, dbConfig),
7367
+ "repository",
7368
+ ],
7369
+ [
7370
+ config.modules.transportModule,
7371
+ mailTransportTemplate(),
7372
+ "Postal transport",
7373
+ ],
7374
+ [config.modules.serviceModule, mailServiceTemplate(config), "service"],
7375
+ [
7376
+ config.modules.actionsModule,
7377
+ mailActionsTemplate(config),
7378
+ "admin actions",
7379
+ ],
7380
+ [config.entrypoints.adminPage, mailAdminPageTemplate(config), "admin page"],
7381
+ [
7382
+ config.entrypoints.webhookRoute,
7383
+ mailWebhookRouteTemplate(config),
7384
+ "Postal webhook route",
7385
+ ],
7386
+ ];
7387
+ if (config.jobs.enabled) {
7388
+ scaffolds.push([
7389
+ config.modules.jobModule,
7390
+ mailJobTemplate(config),
7391
+ "outbox drain job",
7392
+ ]);
7393
+ }
7394
+ for (const [relativePath, text, label] of scaffolds) {
7395
+ const scaffoldState = await scaffoldTextFile(join(cwd, relativePath), text);
7396
+ if (scaffoldState === "created") {
7397
+ changedFiles.push(relativePath);
7398
+ }
7399
+ else if (activate && scaffoldState === "preserved") {
7400
+ notes.push(`Preserved existing mail ${label}: ${relativePath}`);
7401
+ }
7402
+ }
7403
+ if (config.ui.adapter === "mui") {
7404
+ notes.push(`Scaffolded the MUI mail log and test-mail surface at ${config.entrypoints.adminPage}; it remains deny-all until authorizeMailAdmin() is connected to the app's fresh admin check.`);
7405
+ }
7406
+ if (config.jobs.enabled) {
7407
+ notes.push(`Register ${config.modules.jobModule} in the app-owned jobs catalogs and scheduling policy; Loom did not rewrite them.`);
7408
+ }
7409
+ feature.config = config;
7410
+ manifest.features.mail = feature;
7411
+ return { changedFiles, notes };
7412
+ }
6526
7413
  async function applyApiKeysFeature(cwd, framework, manifest, activate) {
6527
7414
  const changedFiles = [];
6528
7415
  const notes = [];
@@ -7281,6 +8168,147 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
7281
8168
  warnings,
7282
8169
  };
7283
8170
  }
8171
+ async function checkMailFeature(cwd, framework, manifest, options) {
8172
+ const issues = [];
8173
+ const suggestions = new Set();
8174
+ const warnings = [];
8175
+ const feature = manifest.features.mail;
8176
+ if (!feature || feature.status !== "active") {
8177
+ return { issues, suggestions: [], warnings };
8178
+ }
8179
+ for (const dependency of ["auth", "db"]) {
8180
+ if (manifest.features[dependency]?.status !== "active") {
8181
+ issues.push(`Mail feature requires the active ${dependency} feature.`);
8182
+ suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
8183
+ }
8184
+ }
8185
+ if (issues.length)
8186
+ return { issues, suggestions: [...suggestions], warnings };
8187
+ const { packageJson } = await readProjectPackageJson(cwd);
8188
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
8189
+ const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
8190
+ const schema = config.schema;
8191
+ const latestSchema = getLatestManagedSchemaConfig(schema);
8192
+ if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
8193
+ issues.push("Mail must use the managed-local mail schema blueprint.");
8194
+ suggestions.add("Run `loom add mail` to restore the mail schema config.");
8195
+ }
8196
+ if (schema.exports.length !== 3) {
8197
+ issues.push("Mail schema must configure message, delivery, and event exports.");
8198
+ }
8199
+ if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
8200
+ issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
8201
+ }
8202
+ else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
8203
+ warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
8204
+ suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
8205
+ }
8206
+ const schemaText = await readTextIfExists(join(cwd, schema.module));
8207
+ if (!schemaText) {
8208
+ issues.push(`Mail schema file is missing: ${schema.module}`);
8209
+ suggestions.add("Run `loom db schemas sync`.");
8210
+ }
8211
+ else {
8212
+ const currentHash = hashManagedSchemaText(schemaText);
8213
+ if (currentHash !== schema.hash) {
8214
+ if (currentHash === latestSchema.hash) {
8215
+ warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
8216
+ suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
8217
+ }
8218
+ else {
8219
+ issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
8220
+ suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
8221
+ }
8222
+ }
8223
+ const barrelText = await readTextIfExists(join(cwd, dbConfig.dirs.schemaDir, "index.ts"));
8224
+ if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
8225
+ issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
8226
+ suggestions.add("Run `loom db schemas sync`.");
8227
+ }
8228
+ }
8229
+ const requiredFiles = [
8230
+ config.modules.accessModule,
8231
+ config.modules.actionsModule,
8232
+ config.modules.repositoryModule,
8233
+ config.modules.serviceModule,
8234
+ config.modules.transportModule,
8235
+ config.entrypoints.adminPage,
8236
+ config.entrypoints.webhookRoute,
8237
+ ...(config.jobs.enabled ? [config.modules.jobModule] : []),
8238
+ ];
8239
+ for (const relativePath of requiredFiles) {
8240
+ if (!await exists(join(cwd, relativePath))) {
8241
+ issues.push(`Mail scaffold file is missing: ${relativePath}`);
8242
+ suggestions.add("Run `loom add mail` to restore missing scaffolds.");
8243
+ }
8244
+ }
8245
+ const accessText = await readTextIfExists(join(cwd, config.modules.accessModule));
8246
+ if (accessText && !accessText.includes("authorizeMailAdmin")) {
8247
+ issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
8248
+ }
8249
+ const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
8250
+ if (generatedDenyAll) {
8251
+ const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
8252
+ if (options.production)
8253
+ issues.push(message);
8254
+ else
8255
+ warnings.push(message);
8256
+ suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
8257
+ }
8258
+ const contentChecks = [
8259
+ [
8260
+ config.modules.repositoryModule,
8261
+ "@gadicc/loom/mail",
8262
+ "Mail repository is not typed against the shared mail contract",
8263
+ ],
8264
+ [
8265
+ config.modules.serviceModule,
8266
+ "createLoomMailService",
8267
+ "Mail service is not wired to the shared durable service",
8268
+ ],
8269
+ [
8270
+ config.modules.transportModule,
8271
+ "createPostalMailTransport",
8272
+ "Mail transport is not wired to the Postal adapter",
8273
+ ],
8274
+ [
8275
+ config.modules.transportModule,
8276
+ "POSTAL_WEBHOOK_PUBLIC_KEYS",
8277
+ "Mail transport does not configure Postal webhook public keys",
8278
+ ],
8279
+ [
8280
+ config.entrypoints.webhookRoute,
8281
+ "createPostalWebhookRouteHandler",
8282
+ "Mail webhook route does not use the signed shared route handler",
8283
+ ],
8284
+ [
8285
+ config.modules.actionsModule,
8286
+ "authorizeMailAdmin",
8287
+ "Mail admin actions do not enforce the app-owned admin boundary",
8288
+ ],
8289
+ [
8290
+ config.entrypoints.adminPage,
8291
+ "authorizeMailAdmin",
8292
+ "Mail admin page does not enforce the app-owned admin boundary",
8293
+ ],
8294
+ ];
8295
+ for (const [relativePath, snippet, label] of contentChecks) {
8296
+ const text = await readTextIfExists(join(cwd, relativePath));
8297
+ if (text && !text.includes(snippet)) {
8298
+ issues.push(`${label}: ${relativePath}`);
8299
+ suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
8300
+ }
8301
+ }
8302
+ if (config.ui.adapter === "mui" &&
8303
+ !hasPackageDependency(packageJson, "@mui/material")) {
8304
+ issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
8305
+ }
8306
+ if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
8307
+ warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
8308
+ suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
8309
+ }
8310
+ return { issues, suggestions: [...suggestions], warnings };
8311
+ }
7284
8312
  function packageDependencySpec(packageJson, dependencyName) {
7285
8313
  return packageJson.dependencies?.[dependencyName] ??
7286
8314
  packageJson.devDependencies?.[dependencyName];
@@ -7769,6 +8797,10 @@ const featureHooks = {
7769
8797
  apply: applyJobsFeature,
7770
8798
  check: checkJobsFeature,
7771
8799
  },
8800
+ mail: {
8801
+ apply: applyMailFeature,
8802
+ check: checkMailFeature,
8803
+ },
7772
8804
  pwa: {
7773
8805
  apply: applyPwaFeature,
7774
8806
  check: checkPwaFeature,