@gadicc/loom 1.16.0 → 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 (99) 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/migrationEnv.d.ts +5 -0
  8. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  9. package/esm/src/cli/migrationEnv.js +10 -0
  10. package/esm/src/cli/mod.d.ts +1 -1
  11. package/esm/src/cli/mod.d.ts.map +1 -1
  12. package/esm/src/cli/mod.js +1065 -5
  13. package/esm/src/mail/errors.d.ts +33 -0
  14. package/esm/src/mail/errors.d.ts.map +1 -0
  15. package/esm/src/mail/errors.js +89 -0
  16. package/esm/src/mail/memory.d.ts +30 -0
  17. package/esm/src/mail/memory.d.ts.map +1 -0
  18. package/esm/src/mail/memory.js +340 -0
  19. package/esm/src/mail/mod.d.ts +7 -0
  20. package/esm/src/mail/mod.d.ts.map +1 -0
  21. package/esm/src/mail/mod.js +6 -0
  22. package/esm/src/mail/postal.d.ts +57 -0
  23. package/esm/src/mail/postal.d.ts.map +1 -0
  24. package/esm/src/mail/postal.js +238 -0
  25. package/esm/src/mail/retry.d.ts +9 -0
  26. package/esm/src/mail/retry.d.ts.map +1 -0
  27. package/esm/src/mail/retry.js +19 -0
  28. package/esm/src/mail/service.d.ts +23 -0
  29. package/esm/src/mail/service.d.ts.map +1 -0
  30. package/esm/src/mail/service.js +185 -0
  31. package/esm/src/mail/types.d.ts +176 -0
  32. package/esm/src/mail/types.d.ts.map +1 -0
  33. package/esm/src/mail/types.js +1 -0
  34. package/esm/src/mui/mail.d.ts +29 -0
  35. package/esm/src/mui/mail.d.ts.map +1 -0
  36. package/esm/src/mui/mail.js +114 -0
  37. package/esm/src/mui/mailView.d.ts +20 -0
  38. package/esm/src/mui/mailView.d.ts.map +1 -0
  39. package/esm/src/mui/mailView.js +26 -0
  40. package/esm/src/mui/mod.d.ts +1 -0
  41. package/esm/src/mui/mod.d.ts.map +1 -1
  42. package/esm/src/mui/mod.js +1 -0
  43. package/esm/src/next/mail/mod.d.ts +3 -0
  44. package/esm/src/next/mail/mod.d.ts.map +1 -0
  45. package/esm/src/next/mail/mod.js +2 -0
  46. package/esm/src/next/mail/route.d.ts +12 -0
  47. package/esm/src/next/mail/route.d.ts.map +1 -0
  48. package/esm/src/next/mail/route.js +43 -0
  49. package/package.json +55 -2
  50. package/script/_dnt.polyfills.d.ts +6 -0
  51. package/script/_dnt.polyfills.d.ts.map +1 -1
  52. package/script/mod.d.ts +2 -0
  53. package/script/mod.d.ts.map +1 -1
  54. package/script/mod.js +2 -0
  55. package/script/src/cli/migrationEnv.d.ts +5 -0
  56. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  57. package/script/src/cli/migrationEnv.js +11 -0
  58. package/script/src/cli/mod.d.ts +1 -1
  59. package/script/src/cli/mod.d.ts.map +1 -1
  60. package/script/src/cli/mod.js +1064 -4
  61. package/script/src/mail/errors.d.ts +33 -0
  62. package/script/src/mail/errors.d.ts.map +1 -0
  63. package/script/src/mail/errors.js +97 -0
  64. package/script/src/mail/memory.d.ts +30 -0
  65. package/script/src/mail/memory.d.ts.map +1 -0
  66. package/script/src/mail/memory.js +345 -0
  67. package/script/src/mail/mod.d.ts +7 -0
  68. package/script/src/mail/mod.d.ts.map +1 -0
  69. package/script/src/mail/mod.js +22 -0
  70. package/script/src/mail/postal.d.ts +57 -0
  71. package/script/src/mail/postal.d.ts.map +1 -0
  72. package/script/src/mail/postal.js +245 -0
  73. package/script/src/mail/retry.d.ts +9 -0
  74. package/script/src/mail/retry.d.ts.map +1 -0
  75. package/script/src/mail/retry.js +22 -0
  76. package/script/src/mail/service.d.ts +23 -0
  77. package/script/src/mail/service.d.ts.map +1 -0
  78. package/script/src/mail/service.js +189 -0
  79. package/script/src/mail/types.d.ts +176 -0
  80. package/script/src/mail/types.d.ts.map +1 -0
  81. package/script/src/mail/types.js +2 -0
  82. package/script/src/mui/mail.d.ts +29 -0
  83. package/script/src/mui/mail.d.ts.map +1 -0
  84. package/script/src/mui/mail.js +159 -0
  85. package/script/src/mui/mailView.d.ts +20 -0
  86. package/script/src/mui/mailView.d.ts.map +1 -0
  87. package/script/src/mui/mailView.js +32 -0
  88. package/script/src/mui/mod.d.ts +1 -0
  89. package/script/src/mui/mod.d.ts.map +1 -1
  90. package/script/src/mui/mod.js +1 -0
  91. package/script/src/next/mail/mod.d.ts +3 -0
  92. package/script/src/next/mail/mod.d.ts.map +1 -0
  93. package/script/src/next/mail/mod.js +18 -0
  94. package/script/src/next/mail/route.d.ts +12 -0
  95. package/script/src/next/mail/route.d.ts.map +1 -0
  96. package/script/src/next/mail/route.js +46 -0
  97. package/skills/loom/SKILL.md +5 -0
  98. package/skills/loom-db/SKILL.md +6 -3
  99. package/skills/loom-mail/SKILL.md +68 -0
@@ -167,6 +167,12 @@ const managedSkills = [
167
167
  relativePackagePath: "skills/loom-files",
168
168
  skillName: "loom-files",
169
169
  },
170
+ {
171
+ featureKey: "mail",
172
+ label: "loom mail skill",
173
+ relativePackagePath: "skills/loom-mail",
174
+ skillName: "loom-mail",
175
+ },
170
176
  ];
171
177
  const featureDefinitions = [
172
178
  {
@@ -189,6 +195,10 @@ const featureDefinitions = [
189
195
  key: "jobs",
190
196
  description: "Shared App Router admin jobs pages, route handlers, direct-run helpers, and job controller wiring.",
191
197
  },
198
+ {
199
+ key: "mail",
200
+ description: "Durable outgoing mail, Postal transport/webhooks, and admin-gated test-mail UI.",
201
+ },
192
202
  {
193
203
  key: "pwa",
194
204
  description: "Shared Serwist PWA worker, provider lifecycle, update prompts, and build wiring.",
@@ -240,6 +250,13 @@ const DEFAULT_MINIO_ENDPOINT = "http://127.0.0.1:9000";
240
250
  const API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION = 3;
241
251
  const API_KEY_AUDIT_SCHEMA_DEFAULT_EXPORT = "loomApiKeyAuditEventsTable";
242
252
  const API_KEY_AUDIT_SCHEMA_DEFAULT_TABLE = "loom_api_key_audit_events";
253
+ const MAIL_SCHEMA_BLUEPRINT_VERSION = 1;
254
+ const MAIL_SCHEMA_DEFAULT_EXPORTS = [
255
+ "loomMailMessagesTable",
256
+ "loomMailDeliveriesTable",
257
+ "loomMailEventsTable",
258
+ ];
259
+ const MAIL_SCHEMA_DEFAULT_TABLE = "loom_mail_messages";
243
260
  const PWA_DEFAULT_DEPENDENCIES = {
244
261
  "@serwist/next": "^9.5.11",
245
262
  };
@@ -1487,6 +1504,145 @@ export const ${exportName} = pgTable(
1487
1504
  );
1488
1505
  `;
1489
1506
  }
1507
+ function buildMailSchemaText(config) {
1508
+ const [messagesExport, deliveriesExport, eventsExport] = [
1509
+ config.exports[0] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[0],
1510
+ config.exports[1] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[1],
1511
+ config.exports[2] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[2],
1512
+ ];
1513
+ const messagesTable = config.tableName;
1514
+ const tablePrefix = messagesTable.endsWith("_messages")
1515
+ ? messagesTable.slice(0, -"_messages".length)
1516
+ : messagesTable;
1517
+ const deliveriesTable = `${tablePrefix}_deliveries`;
1518
+ const eventsTable = `${tablePrefix}_events`;
1519
+ const indexName = (table, suffix) => filesSchemaIndexName(table, suffix);
1520
+ return `import { sql } from "drizzle-orm";
1521
+ import {
1522
+ index,
1523
+ integer,
1524
+ jsonb,
1525
+ pgTable,
1526
+ text,
1527
+ timestamp,
1528
+ uniqueIndex,
1529
+ uuid,
1530
+ } from "drizzle-orm/pg-core";
1531
+
1532
+ // Loom-managed schema blueprint: mail v${MAIL_SCHEMA_BLUEPRINT_VERSION}.
1533
+ // Keep app-specific domain associations in separate local schema files.
1534
+ export const ${messagesExport} = pgTable(
1535
+ "${messagesTable}",
1536
+ {
1537
+ id: uuid("id").default(sql\`uuid_generate_v7()\`).primaryKey(),
1538
+ provider: text("provider").notNull(),
1539
+ status: text("status").notNull().default("queued"),
1540
+ fromEmail: text("from_email").notNull(),
1541
+ fromName: text("from_name"),
1542
+ to: jsonb("to").notNull().$type<string[]>().default(sql\`'[]'::jsonb\`),
1543
+ cc: jsonb("cc").notNull().$type<string[]>().default(sql\`'[]'::jsonb\`),
1544
+ bcc: jsonb("bcc").notNull().$type<string[]>().default(sql\`'[]'::jsonb\`),
1545
+ subject: text("subject").notNull(),
1546
+ plainBody: text("plain_body"),
1547
+ htmlBody: text("html_body"),
1548
+ replyTo: text("reply_to"),
1549
+ tag: text("tag"),
1550
+ headers: jsonb("headers").notNull().$type<Record<string, string>>()
1551
+ .default(sql\`'{}'::jsonb\`),
1552
+ attachments: jsonb("attachments").notNull()
1553
+ .$type<Array<{ contentType?: string | null; data: string; name: string }>>()
1554
+ .default(sql\`'[]'::jsonb\`),
1555
+ metadata: jsonb("metadata").notNull().$type<Record<string, unknown>>()
1556
+ .default(sql\`'{}'::jsonb\`),
1557
+ providerMessageId: text("provider_message_id"),
1558
+ attemptCount: integer("attempt_count").notNull().default(0),
1559
+ availableAt: timestamp("available_at", { mode: "date", withTimezone: true })
1560
+ .notNull().defaultNow(),
1561
+ leaseToken: text("lease_token"),
1562
+ leaseExpiresAt: timestamp("lease_expires_at", { mode: "date", withTimezone: true }),
1563
+ lastErrorCode: text("last_error_code"),
1564
+ lastErrorMessage: text("last_error_message"),
1565
+ sentAt: timestamp("sent_at", { mode: "date", withTimezone: true }),
1566
+ failedAt: timestamp("failed_at", { mode: "date", withTimezone: true }),
1567
+ deliveredAt: timestamp("delivered_at", { mode: "date", withTimezone: true }),
1568
+ cancelledAt: timestamp("cancelled_at", { mode: "date", withTimezone: true }),
1569
+ createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
1570
+ .notNull().defaultNow(),
1571
+ updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
1572
+ .notNull().defaultNow(),
1573
+ },
1574
+ (table) => [
1575
+ index("${indexName(messagesTable, "outbox_idx")}").on(
1576
+ table.status,
1577
+ table.availableAt,
1578
+ table.leaseExpiresAt,
1579
+ ),
1580
+ index("${indexName(messagesTable, "provider_message_idx")}").on(
1581
+ table.provider,
1582
+ table.providerMessageId,
1583
+ ),
1584
+ index("${indexName(messagesTable, "created_idx")}").on(table.createdAt),
1585
+ ],
1586
+ );
1587
+
1588
+ export const ${deliveriesExport} = pgTable(
1589
+ "${deliveriesTable}",
1590
+ {
1591
+ id: uuid("id").default(sql\`uuid_generate_v7()\`).primaryKey(),
1592
+ messageId: uuid("message_id").notNull()
1593
+ .references(() => ${messagesExport}.id, { onDelete: "cascade" }),
1594
+ kind: text("kind").notNull(),
1595
+ email: text("email").notNull(),
1596
+ status: text("status").notNull().default("queued"),
1597
+ providerDeliveryId: text("provider_delivery_id"),
1598
+ providerToken: text("provider_token"),
1599
+ lastErrorCode: text("last_error_code"),
1600
+ lastErrorMessage: text("last_error_message"),
1601
+ deliveredAt: timestamp("delivered_at", { mode: "date", withTimezone: true }),
1602
+ createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
1603
+ .notNull().defaultNow(),
1604
+ updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
1605
+ .notNull().defaultNow(),
1606
+ },
1607
+ (table) => [
1608
+ index("${indexName(deliveriesTable, "message_idx")}").on(table.messageId),
1609
+ index("${indexName(deliveriesTable, "provider_delivery_idx")}").on(
1610
+ table.providerDeliveryId,
1611
+ ),
1612
+ index("${indexName(deliveriesTable, "recipient_idx")}").on(table.email),
1613
+ ],
1614
+ );
1615
+
1616
+ export const ${eventsExport} = pgTable(
1617
+ "${eventsTable}",
1618
+ {
1619
+ id: uuid("id").default(sql\`uuid_generate_v7()\`).primaryKey(),
1620
+ messageId: uuid("message_id").notNull()
1621
+ .references(() => ${messagesExport}.id, { onDelete: "cascade" }),
1622
+ deliveryId: uuid("delivery_id")
1623
+ .references(() => ${deliveriesExport}.id, { onDelete: "set null" }),
1624
+ provider: text("provider").notNull(),
1625
+ providerEventId: text("provider_event_id"),
1626
+ eventType: text("event_type").notNull(),
1627
+ sourceEvent: text("source_event").notNull(),
1628
+ payload: jsonb("payload").notNull().$type<Record<string, unknown>>()
1629
+ .default(sql\`'{}'::jsonb\`),
1630
+ occurredAt: timestamp("occurred_at", { mode: "date", withTimezone: true })
1631
+ .notNull().defaultNow(),
1632
+ },
1633
+ (table) => [
1634
+ index("${indexName(eventsTable, "message_occurred_idx")}").on(
1635
+ table.messageId,
1636
+ table.occurredAt,
1637
+ ),
1638
+ uniqueIndex("${indexName(eventsTable, "provider_event_unique")}").on(
1639
+ table.provider,
1640
+ table.providerEventId,
1641
+ ),
1642
+ ],
1643
+ );
1644
+ `;
1645
+ }
1490
1646
  function getFilesDefaultSchemaConfig(dbConfig) {
1491
1647
  const baseConfig = {
1492
1648
  blueprint: "files",
@@ -1502,6 +1658,20 @@ function getFilesDefaultSchemaConfig(dbConfig) {
1502
1658
  hash: hashManagedSchemaText(buildFilesSchemaText(baseConfig)),
1503
1659
  };
1504
1660
  }
1661
+ function getMailDefaultSchemaConfig(dbConfig) {
1662
+ const baseConfig = {
1663
+ blueprint: "mail",
1664
+ exports: [...MAIL_SCHEMA_DEFAULT_EXPORTS],
1665
+ mode: "managed-local",
1666
+ module: (0, node_path_1.join)(dbConfig.dirs.schemaDir, "loomMail.ts"),
1667
+ tableName: MAIL_SCHEMA_DEFAULT_TABLE,
1668
+ version: MAIL_SCHEMA_BLUEPRINT_VERSION,
1669
+ };
1670
+ return {
1671
+ ...baseConfig,
1672
+ hash: hashManagedSchemaText(buildMailSchemaText(baseConfig)),
1673
+ };
1674
+ }
1505
1675
  function getApiKeysDefaultSchemaConfig(dbConfig) {
1506
1676
  const baseConfig = {
1507
1677
  blueprint: "api-key-audit",
@@ -1597,6 +1767,23 @@ function mergeManagedLocalSchemaConfig(dbConfig, schemaConfig) {
1597
1767
  hashManagedSchemaText(buildFilesSchemaText(merged)),
1598
1768
  };
1599
1769
  }
1770
+ function mergeMailSchemaConfig(dbConfig, schemaConfig) {
1771
+ const defaults = getMailDefaultSchemaConfig(dbConfig);
1772
+ const merged = {
1773
+ ...defaults,
1774
+ ...schemaConfig,
1775
+ blueprint: "mail",
1776
+ exports: schemaConfig?.exports?.length === 3
1777
+ ? schemaConfig.exports
1778
+ : defaults.exports,
1779
+ mode: "managed-local",
1780
+ };
1781
+ return {
1782
+ ...merged,
1783
+ hash: schemaConfig?.hash ??
1784
+ hashManagedSchemaText(buildMailSchemaText(merged)),
1785
+ };
1786
+ }
1600
1787
  function getFilesConfig(framework, dbConfig, featureConfig) {
1601
1788
  const appRoot = framework.srcDir ? "src/app" : "app";
1602
1789
  const filesRoot = framework.srcDir ? "src/files" : "files";
@@ -1620,6 +1807,44 @@ function getFilesConfig(framework, dbConfig, featureConfig) {
1620
1807
  },
1621
1808
  };
1622
1809
  }
1810
+ function getMailConfig(framework, dbConfig, packageJson, featureConfig, jobsActive) {
1811
+ const appRoot = framework.srcDir ? "src/app" : "app";
1812
+ const mailRoot = framework.srcDir ? "src/mail" : "mail";
1813
+ const jobsRoot = framework.srcDir ? "src/jobs" : "jobs";
1814
+ return {
1815
+ entrypoints: {
1816
+ adminPage: featureConfig?.entrypoints?.adminPage ??
1817
+ `${appRoot}/admin/mail/page.tsx`,
1818
+ webhookRoute: featureConfig?.entrypoints?.webhookRoute ??
1819
+ `${appRoot}/api/mail/postal/route.ts`,
1820
+ },
1821
+ jobs: {
1822
+ enabled: featureConfig?.jobs?.enabled ?? jobsActive,
1823
+ },
1824
+ modules: {
1825
+ accessModule: featureConfig?.modules?.accessModule ??
1826
+ `${mailRoot}/access.ts`,
1827
+ actionsModule: featureConfig?.modules?.actionsModule ??
1828
+ `${mailRoot}/actions.ts`,
1829
+ jobModule: featureConfig?.modules?.jobModule ??
1830
+ `${jobsRoot}/mail-drain.ts`,
1831
+ repositoryModule: featureConfig?.modules?.repositoryModule ??
1832
+ `${mailRoot}/repository.ts`,
1833
+ serviceModule: featureConfig?.modules?.serviceModule ??
1834
+ `${mailRoot}/service.ts`,
1835
+ transportModule: featureConfig?.modules?.transportModule ??
1836
+ `${mailRoot}/transport.ts`,
1837
+ },
1838
+ provider: "postal",
1839
+ schema: mergeMailSchemaConfig(dbConfig, featureConfig?.schema),
1840
+ ui: {
1841
+ adapter: featureConfig?.ui?.adapter ??
1842
+ (hasPackageDependency(packageJson, "@mui/material")
1843
+ ? "mui"
1844
+ : "headless"),
1845
+ },
1846
+ };
1847
+ }
1623
1848
  function normalizeText(text) {
1624
1849
  return text.replaceAll("\r\n", "\n");
1625
1850
  }
@@ -2861,6 +3086,14 @@ function workflowStepVerifiesVercelBuildEnv(block) {
2861
3086
  return (/\bvercel-build-env(?:\.mjs)?\b[\s\S]*\bverify\b/.test(block) ||
2862
3087
  /\bloom\b[\s\S]*\bdb\s+release\s+verify-build-env\b/.test(block)) && /\.vercel\/output\b/.test(block);
2863
3088
  }
3089
+ function workflowStepVerifiesMigrationEnv(block) {
3090
+ return /\bloom\b[\s\S]*\bdb\s+migrations\s+verify-env\b/.test(block);
3091
+ }
3092
+ function workflowStepVerifiesMigrationEnvWithPulledSnapshot(block) {
3093
+ return workflowStepVerifiesMigrationEnv(block) &&
3094
+ /--env-file(?:=|\s+)["']?\$RUNNER_TEMP\/vercel-production\.env["']?/
3095
+ .test(block);
3096
+ }
2864
3097
  function workflowStepStagesVercelProductionDeployment(block) {
2865
3098
  return workflowStepUsesVercelCommand(block, "deploy") &&
2866
3099
  /\s--prebuilt\b/.test(block) &&
@@ -2956,6 +3189,7 @@ function inspectDbMigrationWorkflow(relativePath, workflowText) {
2956
3189
  const metadataStepIndex = job.stepBlocks.findIndex(workflowStepQueriesVercelProductionEnvMetadata);
2957
3190
  const prepareBuildEnvStepIndex = job.stepBlocks.findIndex(workflowStepPreparesVercelBuildEnv);
2958
3191
  const verifyBuildEnvStepIndex = job.stepBlocks.findIndex(workflowStepVerifiesVercelBuildEnv);
3192
+ const migrationVerifyStepIndex = job.stepBlocks.findIndex(workflowStepVerifiesMigrationEnv);
2959
3193
  const stageStepIndex = job.stepBlocks.findIndex(workflowStepStagesVercelProductionDeployment);
2960
3194
  const migrateStepIndex = job.stepBlocks.findIndex(workflowStepRunsDbMigrate);
2961
3195
  const migrateWithVercelProductionEnvStepIndex = job.stepBlocks.findIndex(workflowStepRunsDbMigrateWithVercelProductionEnv);
@@ -2964,6 +3198,9 @@ function inspectDbMigrationWorkflow(relativePath, workflowText) {
2964
3198
  const migrateStep = migrateStepIndex >= 0
2965
3199
  ? job.stepBlocks[migrateStepIndex]
2966
3200
  : "";
3201
+ const migrationVerifyStep = migrationVerifyStepIndex >= 0
3202
+ ? job.stepBlocks[migrationVerifyStepIndex]
3203
+ : "";
2967
3204
  const promoteStep = promoteStepIndex >= 0
2968
3205
  ? job.stepBlocks[promoteStepIndex]
2969
3206
  : "";
@@ -2974,6 +3211,8 @@ function inspectDbMigrationWorkflow(relativePath, workflowText) {
2974
3211
  hasWorkflowEnvBinding(migrateStep, "DATABASE_URL"),
2975
3212
  id: job.id,
2976
3213
  metadataStepIndex,
3214
+ migrationVerifyStepIndex,
3215
+ migrationVerifyUsesPulledSnapshot: workflowStepVerifiesMigrationEnvWithPulledSnapshot(migrationVerifyStep),
2977
3216
  migrateStepIndex,
2978
3217
  migrateStepRestoresPulledEnv: workflowStepRestoresVercelMigrationEnv(migrateStep),
2979
3218
  migrateWithVercelProductionEnvStepIndex,
@@ -3077,6 +3316,10 @@ async function checkDbProductionMigrationFlow(cwd, production) {
3077
3316
  const databaseUrlVariableWorkflows = mainPushWorkflows.filter((inspection) => inspection.usesGithubDatabaseUrlVariable);
3078
3317
  const legacyUnpooledSecretWorkflows = mainPushWorkflows.filter((inspection) => inspection.usesGithubUnpooledDatabaseUrlSecret &&
3079
3318
  !inspection.usesGithubMigrationDatabaseUrlSecret);
3319
+ const invalidMigrationValidationPaths = mainPushWorkflows.flatMap((inspection) => inspection.jobs.flatMap((job) => job.migrationVerifyStepIndex >= 0 &&
3320
+ !job.migrationVerifyUsesPulledSnapshot
3321
+ ? [inspection.relativePath]
3322
+ : []));
3080
3323
  const vercelCurlWorkflowPaths = mainPushWorkflows.flatMap((inspection) => inspection.jobs.some((job) => job.vercelCurlStepIndex >= 0)
3081
3324
  ? [inspection.relativePath]
3082
3325
  : []);
@@ -3128,6 +3371,11 @@ async function checkDbProductionMigrationFlow(cwd, production) {
3128
3371
  }
3129
3372
  suggestions.add('Add a production GitHub Actions workflow that runs `vercel pull --environment=production --scope "$VERCEL_ORG_ID"`, preserves an untouched migration snapshot, masks usable pulled values, queries `vercel env ls production --format=json`, adds unique build-only placeholders for unreadable Sensitive values, runs `vercel build --prod --scope "$VERCEL_ORG_ID"`, rejects placeholder leakage from `.vercel/output`, stages with `vercel deploy --prebuilt --prod --skip-domain --scope "$VERCEL_ORG_ID"`, restores the migration snapshot with an optional GitHub `MIGRATION_DATABASE_URL_UNPOOLED` override, runs migrations, then runs `vercel promote --scope "$VERCEL_ORG_ID"`.');
3130
3373
  }
3374
+ if (invalidMigrationValidationPaths.length) {
3375
+ findings.push("DB production migration validation does not load the preserved Vercel production env snapshot: " +
3376
+ [...new Set(invalidMigrationValidationPaths)].join(", "));
3377
+ suggestions.add('Run `loom db migrations verify-env --env-file "$RUNNER_TEMP/vercel-production.env"` so the optional GitHub migration secret overlays the readable gradual-adoption pull snapshot.');
3378
+ }
3131
3379
  if (legacyUnpooledSecretWorkflows.length) {
3132
3380
  warnings.push("DB production migration flow still uses the gradual-adoption GitHub secret `DATABASE_URL_UNPOOLED` instead of the migration-scoped `MIGRATION_DATABASE_URL_UNPOOLED`: " +
3133
3381
  legacyUnpooledSecretWorkflows.map((workflow) => workflow.relativePath)
@@ -4106,6 +4354,560 @@ export const { GET, POST } = createFilesRouteHandlers({
4106
4354
  });
4107
4355
  `;
4108
4356
  }
4357
+ function mailAccessTemplate() {
4358
+ return `// Generated deny-all boundary. Replace with the app's fresh admin check.
4359
+ export async function authorizeMailAdmin(): Promise<void> {
4360
+ throw new Error("Mail admin access policy is not configured.");
4361
+ }
4362
+ `;
4363
+ }
4364
+ function mailTransportTemplate() {
4365
+ return `import type { LoomMailTransport } from "@gadicc/loom/mail";
4366
+ import {
4367
+ createPostalMailTransport,
4368
+ type PostalWebhookPublicKey,
4369
+ } from "@gadicc/loom/mail/postal";
4370
+
4371
+ function requireEnv(name: "POSTAL_API_KEY" | "POSTAL_FROM_EMAIL" | "POSTAL_HOST") {
4372
+ const value = process.env[name]?.trim();
4373
+ if (!value) throw new Error(\`\${name} is not set.\`);
4374
+ return value;
4375
+ }
4376
+
4377
+ export const mailTransport: LoomMailTransport = {
4378
+ provider: "postal",
4379
+ send(message) {
4380
+ return createPostalMailTransport({
4381
+ apiKey: requireEnv("POSTAL_API_KEY"),
4382
+ host: requireEnv("POSTAL_HOST"),
4383
+ }).send(message);
4384
+ },
4385
+ };
4386
+
4387
+ export function getDefaultMailFromEmail() {
4388
+ return requireEnv("POSTAL_FROM_EMAIL");
4389
+ }
4390
+
4391
+ export function getPostalWebhookPublicKeys(): PostalWebhookPublicKey[] {
4392
+ const raw = process.env.POSTAL_WEBHOOK_PUBLIC_KEYS?.trim();
4393
+ if (!raw) throw new Error("POSTAL_WEBHOOK_PUBLIC_KEYS is not set.");
4394
+ const parsed = JSON.parse(raw) as unknown;
4395
+ if (!Array.isArray(parsed)) {
4396
+ throw new Error("POSTAL_WEBHOOK_PUBLIC_KEYS must be a JSON array of public JWKs.");
4397
+ }
4398
+ return parsed.map((candidate) => {
4399
+ if (
4400
+ typeof candidate !== "object" || candidate === null ||
4401
+ !("kid" in candidate) || typeof candidate.kid !== "string" ||
4402
+ !("kty" in candidate) || candidate.kty !== "RSA"
4403
+ ) {
4404
+ throw new Error("Every Postal webhook key must be an RSA JWK with a kid.");
4405
+ }
4406
+ return candidate as PostalWebhookPublicKey;
4407
+ });
4408
+ }
4409
+ `;
4410
+ }
4411
+ function mailServiceTemplate(config) {
4412
+ return `import { createLoomMailService } from "@gadicc/loom/mail";
4413
+ import { mailRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4414
+ import {
4415
+ getDefaultMailFromEmail,
4416
+ mailTransport,
4417
+ } from "${toAliasImportPath(config.modules.transportModule)}";
4418
+
4419
+ export const mailService = createLoomMailService({
4420
+ get defaultFromEmail() {
4421
+ return getDefaultMailFromEmail();
4422
+ },
4423
+ repository: mailRepository,
4424
+ transport: mailTransport,
4425
+ });
4426
+ `;
4427
+ }
4428
+ function mailRepositoryTemplate(config, dbConfig) {
4429
+ const [messages, deliveries, events] = [
4430
+ config.schema.exports[0] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[0],
4431
+ config.schema.exports[1] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[1],
4432
+ config.schema.exports[2] ?? MAIL_SCHEMA_DEFAULT_EXPORTS[2],
4433
+ ];
4434
+ return `import { and, asc, desc, eq, lte, or } from "drizzle-orm";
4435
+ import type {
4436
+ LoomMailDeliveryRecord,
4437
+ LoomMailDeliveryStatus,
4438
+ LoomMailMessageRecord,
4439
+ LoomMailRepository,
4440
+ } from "@gadicc/loom/mail";
4441
+ import { db } from "${toAliasImportPath(dbConfig.modules.neonFullModule)}";
4442
+ import {
4443
+ ${deliveries},
4444
+ ${events},
4445
+ ${messages},
4446
+ } from "${toAliasImportPath(config.schema.module)}";
4447
+
4448
+ type MessageRow = typeof ${messages}.$inferSelect;
4449
+ type MessageInsert = typeof ${messages}.$inferInsert;
4450
+ type DeliveryRow = typeof ${deliveries}.$inferSelect;
4451
+
4452
+ function toMessage(row: MessageRow): LoomMailMessageRecord {
4453
+ return row as LoomMailMessageRecord;
4454
+ }
4455
+
4456
+ function toDelivery(row: DeliveryRow): LoomMailDeliveryRecord {
4457
+ return row as LoomMailDeliveryRecord;
4458
+ }
4459
+
4460
+ function aggregateStatus(statuses: LoomMailDeliveryStatus[]) {
4461
+ if (statuses.length === 0) return "sent" as const;
4462
+ if (statuses.every((status) => status === "delivered")) return "delivered" as const;
4463
+ const terminal = new Set<LoomMailDeliveryStatus>([
4464
+ "bounced", "cancelled", "delivered", "failed",
4465
+ ]);
4466
+ if (statuses.every((status) => terminal.has(status))) {
4467
+ return statuses.includes("delivered") ? "partially_delivered" as const : "failed" as const;
4468
+ }
4469
+ return "sent" as const;
4470
+ }
4471
+
4472
+ export const mailRepository = {
4473
+ async cancel(messageId, occurredAt) {
4474
+ return db.transaction(async (trx) => {
4475
+ const [current] = await trx.select().from(${messages})
4476
+ .where(eq(${messages}.id, messageId)).limit(1).for("update");
4477
+ if (!current || !["queued", "failed"].includes(current.status)) return false;
4478
+ await trx.update(${messages}).set({
4479
+ cancelledAt: occurredAt,
4480
+ leaseExpiresAt: null,
4481
+ leaseToken: null,
4482
+ status: "cancelled",
4483
+ updatedAt: occurredAt,
4484
+ }).where(eq(${messages}.id, messageId));
4485
+ await trx.update(${deliveries}).set({ status: "cancelled", updatedAt: occurredAt })
4486
+ .where(and(eq(${deliveries}.messageId, messageId), eq(${deliveries}.status, "queued")));
4487
+ await trx.insert(${events}).values({
4488
+ eventType: "cancelled",
4489
+ messageId,
4490
+ payload: {},
4491
+ provider: current.provider,
4492
+ sourceEvent: "cancelled",
4493
+ occurredAt,
4494
+ });
4495
+ return true;
4496
+ });
4497
+ },
4498
+
4499
+ async claim(request) {
4500
+ return db.transaction(async (trx) => {
4501
+ const due = or(
4502
+ eq(${messages}.status, "queued"),
4503
+ and(eq(${messages}.status, "sending"), lte(${messages}.leaseExpiresAt, request.now)),
4504
+ );
4505
+ const [current] = await trx.select().from(${messages})
4506
+ .where(and(
4507
+ request.messageId ? eq(${messages}.id, request.messageId) : undefined,
4508
+ lte(${messages}.availableAt, request.now),
4509
+ due,
4510
+ ))
4511
+ .orderBy(asc(${messages}.availableAt), asc(${messages}.createdAt))
4512
+ .limit(1)
4513
+ .for("update", { skipLocked: true });
4514
+ if (!current) return null;
4515
+ const [claimed] = await trx.update(${messages}).set({
4516
+ attemptCount: current.attemptCount + 1,
4517
+ leaseExpiresAt: request.leaseExpiresAt,
4518
+ leaseToken: request.leaseToken,
4519
+ status: "sending",
4520
+ updatedAt: request.now,
4521
+ }).where(eq(${messages}.id, current.id)).returning();
4522
+ if (!claimed) return null;
4523
+ await trx.insert(${events}).values({
4524
+ eventType: "attempted",
4525
+ messageId: current.id,
4526
+ payload: {
4527
+ attemptCount: claimed.attemptCount,
4528
+ leaseExpiresAt: request.leaseExpiresAt.toISOString(),
4529
+ },
4530
+ provider: current.provider,
4531
+ sourceEvent: "attempted",
4532
+ occurredAt: request.now,
4533
+ });
4534
+ return toMessage(claimed) as ReturnType<typeof toMessage> & {
4535
+ leaseExpiresAt: Date;
4536
+ leaseToken: string;
4537
+ status: "sending";
4538
+ };
4539
+ });
4540
+ },
4541
+
4542
+ async completeFailure(input) {
4543
+ return db.transaction(async (trx) => {
4544
+ const [updated] = await trx.update(${messages}).set({
4545
+ availableAt: input.retryAt ?? input.occurredAt,
4546
+ failedAt: input.retryAt ? null : input.occurredAt,
4547
+ lastErrorCode: input.failure.code,
4548
+ lastErrorMessage: input.failure.message,
4549
+ leaseExpiresAt: null,
4550
+ leaseToken: null,
4551
+ status: input.retryAt ? "queued" : "failed",
4552
+ updatedAt: input.occurredAt,
4553
+ }).where(and(
4554
+ eq(${messages}.id, input.messageId),
4555
+ eq(${messages}.status, "sending"),
4556
+ eq(${messages}.leaseToken, input.leaseToken),
4557
+ )).returning({ provider: ${messages}.provider });
4558
+ if (!updated) return false;
4559
+ await trx.insert(${events}).values({
4560
+ eventType: input.retryAt ? "retry_scheduled" : "failed",
4561
+ messageId: input.messageId,
4562
+ payload: {
4563
+ code: input.failure.code,
4564
+ message: input.failure.message,
4565
+ retryAt: input.retryAt?.toISOString() ?? null,
4566
+ retryable: input.failure.retryable,
4567
+ ...input.failure.payload,
4568
+ },
4569
+ provider: updated.provider,
4570
+ sourceEvent: input.retryAt ? "retry_scheduled" : "failed",
4571
+ occurredAt: input.occurredAt,
4572
+ });
4573
+ return true;
4574
+ });
4575
+ },
4576
+
4577
+ async completeSuccess(input) {
4578
+ return db.transaction(async (trx) => {
4579
+ const [updated] = await trx.update(${messages}).set({
4580
+ lastErrorCode: null,
4581
+ lastErrorMessage: null,
4582
+ leaseExpiresAt: null,
4583
+ leaseToken: null,
4584
+ providerMessageId: input.result.providerMessageId,
4585
+ sentAt: input.occurredAt,
4586
+ status: "sent",
4587
+ updatedAt: input.occurredAt,
4588
+ }).where(and(
4589
+ eq(${messages}.id, input.messageId),
4590
+ eq(${messages}.status, "sending"),
4591
+ eq(${messages}.leaseToken, input.leaseToken),
4592
+ )).returning({ provider: ${messages}.provider });
4593
+ if (!updated) return false;
4594
+ for (const result of input.result.deliveries) {
4595
+ await trx.update(${deliveries}).set({
4596
+ providerDeliveryId: result.providerDeliveryId,
4597
+ providerToken: result.providerToken,
4598
+ status: "accepted",
4599
+ updatedAt: input.occurredAt,
4600
+ }).where(and(
4601
+ eq(${deliveries}.messageId, input.messageId),
4602
+ eq(${deliveries}.email, result.email),
4603
+ eq(${deliveries}.status, "queued"),
4604
+ ));
4605
+ }
4606
+ await trx.insert(${events}).values({
4607
+ eventType: "sent",
4608
+ messageId: input.messageId,
4609
+ payload: {
4610
+ providerMessageId: input.result.providerMessageId,
4611
+ providerResponse: input.result.providerResponse ?? {},
4612
+ },
4613
+ provider: updated.provider,
4614
+ sourceEvent: "sent",
4615
+ occurredAt: input.occurredAt,
4616
+ });
4617
+ return true;
4618
+ });
4619
+ },
4620
+
4621
+ async enqueue(input, occurredAt) {
4622
+ return db.transaction(async (trx) => {
4623
+ const [message] = await trx.insert(${messages}).values({
4624
+ ...input,
4625
+ availableAt: occurredAt,
4626
+ createdAt: occurredAt,
4627
+ updatedAt: occurredAt,
4628
+ } as MessageInsert).returning();
4629
+ if (!message) throw new Error("Failed to enqueue mail.");
4630
+ const recipients = [
4631
+ ...input.to.map((email) => ({ email, kind: "to" })),
4632
+ ...input.cc.map((email) => ({ email, kind: "cc" })),
4633
+ ...input.bcc.map((email) => ({ email, kind: "bcc" })),
4634
+ ];
4635
+ await trx.insert(${deliveries}).values(recipients.map((recipient) => ({
4636
+ ...recipient,
4637
+ messageId: message.id,
4638
+ createdAt: occurredAt,
4639
+ updatedAt: occurredAt,
4640
+ })));
4641
+ await trx.insert(${events}).values({
4642
+ eventType: "queued",
4643
+ messageId: message.id,
4644
+ payload: { bcc: input.bcc, cc: input.cc, to: input.to },
4645
+ provider: input.provider,
4646
+ sourceEvent: "queued",
4647
+ occurredAt,
4648
+ });
4649
+ return toMessage(message);
4650
+ });
4651
+ },
4652
+
4653
+ async findById(messageId) {
4654
+ const [row] = await db.select().from(${messages})
4655
+ .where(eq(${messages}.id, messageId)).limit(1);
4656
+ return row ? toMessage(row) : null;
4657
+ },
4658
+
4659
+ async listDeliveries(messageId: string) {
4660
+ const rows = await db.select().from(${deliveries})
4661
+ .where(eq(${deliveries}.messageId, messageId));
4662
+ return rows.map(toDelivery);
4663
+ },
4664
+
4665
+ async listRecent(limit = 100) {
4666
+ const rows = await db.select().from(${messages})
4667
+ .orderBy(desc(${messages}.createdAt)).limit(limit);
4668
+ return rows.map(toMessage);
4669
+ },
4670
+
4671
+ async recordProviderEvent(event) {
4672
+ return db.transaction(async (trx) => {
4673
+ let [delivery] = event.providerDeliveryId
4674
+ ? await trx.select().from(${deliveries})
4675
+ .where(eq(${deliveries}.providerDeliveryId, event.providerDeliveryId)).limit(1)
4676
+ : [];
4677
+ let [message] = delivery
4678
+ ? await trx.select().from(${messages})
4679
+ .where(eq(${messages}.id, delivery.messageId)).limit(1)
4680
+ : event.providerMessageId
4681
+ ? await trx.select().from(${messages})
4682
+ .where(and(
4683
+ eq(${messages}.provider, event.provider),
4684
+ eq(${messages}.providerMessageId, event.providerMessageId),
4685
+ )).limit(1)
4686
+ : [];
4687
+ if (message && message.provider !== event.provider) {
4688
+ return { inserted: false, messageId: null };
4689
+ }
4690
+ if (!message) return { inserted: false, messageId: null };
4691
+ if (!delivery && event.recipient) {
4692
+ [delivery] = await trx.select().from(${deliveries}).where(and(
4693
+ eq(${deliveries}.messageId, message.id),
4694
+ eq(${deliveries}.email, event.recipient),
4695
+ )).limit(1);
4696
+ }
4697
+ const [inserted] = await trx.insert(${events}).values({
4698
+ deliveryId: delivery?.id ?? null,
4699
+ eventType: event.eventType,
4700
+ messageId: message.id,
4701
+ occurredAt: event.occurredAt,
4702
+ payload: event.payload,
4703
+ provider: event.provider,
4704
+ providerEventId: event.providerEventId,
4705
+ sourceEvent: event.sourceEvent,
4706
+ }).onConflictDoNothing().returning({ id: ${events}.id });
4707
+ if (!inserted) return { inserted: false, messageId: message.id };
4708
+
4709
+ if (delivery && event.eventType !== "unknown") {
4710
+ const nextStatus = event.eventType;
4711
+ await trx.update(${deliveries}).set({
4712
+ deliveredAt: nextStatus === "delivered" ? event.occurredAt : delivery.deliveredAt,
4713
+ lastErrorCode: ["bounced", "failed", "held"].includes(nextStatus)
4714
+ ? event.sourceEvent : delivery.lastErrorCode,
4715
+ lastErrorMessage: ["bounced", "failed", "held"].includes(nextStatus)
4716
+ ? String(event.payload.message ?? event.sourceEvent) : delivery.lastErrorMessage,
4717
+ status: nextStatus,
4718
+ updatedAt: event.occurredAt,
4719
+ }).where(eq(${deliveries}.id, delivery.id));
4720
+ }
4721
+ const statusRows = await trx.select({ status: ${deliveries}.status })
4722
+ .from(${deliveries}).where(eq(${deliveries}.messageId, message.id));
4723
+ const status = aggregateStatus(
4724
+ statusRows.map((row) => row.status as LoomMailDeliveryStatus),
4725
+ );
4726
+ await trx.update(${messages}).set({
4727
+ deliveredAt: status === "delivered" ? event.occurredAt : message.deliveredAt,
4728
+ failedAt: status === "failed" ? event.occurredAt : message.failedAt,
4729
+ status,
4730
+ updatedAt: event.occurredAt,
4731
+ }).where(eq(${messages}.id, message.id));
4732
+ return { inserted: true, messageId: message.id };
4733
+ });
4734
+ },
4735
+ } satisfies LoomMailRepository & {
4736
+ listDeliveries(messageId: string): Promise<LoomMailDeliveryRecord[]>;
4737
+ listRecent(limit?: number): Promise<LoomMailMessageRecord[]>;
4738
+ };
4739
+ `;
4740
+ }
4741
+ function mailActionsTemplate(config) {
4742
+ const adminPath = config.entrypoints.adminPage
4743
+ .replace(/^src\/app|^app/, "")
4744
+ .replace(/\/page\.tsx$/, "") || "/";
4745
+ return `"use server";
4746
+
4747
+ import { LoomMailDeliveryError } from "@gadicc/loom/mail";
4748
+ import { revalidatePath } from "next/cache";
4749
+ import { authorizeMailAdmin } from "${toAliasImportPath(config.modules.accessModule)}";
4750
+ import { mailRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4751
+ import { mailService } from "${toAliasImportPath(config.modules.serviceModule)}";
4752
+
4753
+ export interface MailTestActionState {
4754
+ message: string | null;
4755
+ messageId?: string;
4756
+ status: "error" | "idle" | "success";
4757
+ }
4758
+
4759
+ function text(formData: FormData, key: string) {
4760
+ const value = formData.get(key);
4761
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
4762
+ }
4763
+
4764
+ function recipients(value?: string) {
4765
+ return (value ?? "").split(/[,\\n]+/).map((item) => item.trim()).filter(Boolean);
4766
+ }
4767
+
4768
+ export async function sendTestMail(
4769
+ _previous: MailTestActionState,
4770
+ formData: FormData,
4771
+ ): Promise<MailTestActionState> {
4772
+ await authorizeMailAdmin();
4773
+ try {
4774
+ const result = await mailService.sendMail({
4775
+ bcc: recipients(text(formData, "bcc")),
4776
+ cc: recipients(text(formData, "cc")),
4777
+ htmlBody: text(formData, "htmlBody"),
4778
+ metadata: { sentFromMailAdmin: true },
4779
+ plainBody: text(formData, "plainBody"),
4780
+ replyTo: text(formData, "replyTo"),
4781
+ subject: text(formData, "subject") ?? "",
4782
+ tag: text(formData, "tag"),
4783
+ to: recipients(text(formData, "to")),
4784
+ });
4785
+ revalidatePath("${adminPath}");
4786
+ return {
4787
+ message: "Test email accepted by the provider.",
4788
+ messageId: result.message.id,
4789
+ status: "success",
4790
+ };
4791
+ } catch (error) {
4792
+ return {
4793
+ message: error instanceof Error ? error.message : "Mail send failed.",
4794
+ messageId: error instanceof LoomMailDeliveryError ? error.messageId : undefined,
4795
+ status: "error",
4796
+ };
4797
+ }
4798
+ }
4799
+
4800
+ function requiredMessageId(formData: FormData) {
4801
+ const messageId = text(formData, "messageId");
4802
+ if (!messageId) throw new Error("Missing mail message id.");
4803
+ return messageId;
4804
+ }
4805
+
4806
+ export async function cancelMail(formData: FormData) {
4807
+ await authorizeMailAdmin();
4808
+ if (!await mailService.cancelMail(requiredMessageId(formData))) {
4809
+ throw new Error("Mail message cannot be cancelled in its current state.");
4810
+ }
4811
+ revalidatePath("${adminPath}");
4812
+ }
4813
+
4814
+ export async function retryMail(formData: FormData) {
4815
+ await authorizeMailAdmin();
4816
+ const sourceId = requiredMessageId(formData);
4817
+ const source = await mailRepository.findById(sourceId);
4818
+ if (!source) throw new Error("Mail message not found.");
4819
+ await mailService.sendMail({
4820
+ attachments: source.attachments,
4821
+ bcc: source.bcc,
4822
+ cc: source.cc,
4823
+ fromEmail: source.fromEmail,
4824
+ fromName: source.fromName ?? undefined,
4825
+ headers: source.headers,
4826
+ htmlBody: source.htmlBody ?? undefined,
4827
+ metadata: { ...source.metadata, retriedFromMessageId: source.id },
4828
+ plainBody: source.plainBody ?? undefined,
4829
+ replyTo: source.replyTo ?? undefined,
4830
+ subject: source.subject,
4831
+ tag: source.tag ?? undefined,
4832
+ to: source.to,
4833
+ });
4834
+ revalidatePath("${adminPath}");
4835
+ }
4836
+ `;
4837
+ }
4838
+ function mailAdminPageTemplate(config) {
4839
+ if (config.ui.adapter !== "mui") {
4840
+ return `import { authorizeMailAdmin } from "${toAliasImportPath(config.modules.accessModule)}";
4841
+
4842
+ export default async function MailAdminPage() {
4843
+ await authorizeMailAdmin();
4844
+ return <main><h1>Mail</h1><p>Connect an app-owned admin UI to the Loom mail service.</p></main>;
4845
+ }
4846
+ `;
4847
+ }
4848
+ return `import { AdminMailConsole, type MailAdminRow } from "@gadicc/loom/mui/mail";
4849
+ import { authorizeMailAdmin } from "${toAliasImportPath(config.modules.accessModule)}";
4850
+ import { cancelMail, retryMail, sendTestMail } from "${toAliasImportPath(config.modules.actionsModule)}";
4851
+ import { mailRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4852
+
4853
+ export default async function MailAdminPage() {
4854
+ await authorizeMailAdmin();
4855
+ const messages = await mailRepository.listRecent(100);
4856
+ const deliveries = await Promise.all(
4857
+ messages.map((message) => mailRepository.listDeliveries(message.id)),
4858
+ );
4859
+ const rows: MailAdminRow[] = messages.map((message, index) => ({
4860
+ createdAt: message.createdAt.toISOString(),
4861
+ id: message.id,
4862
+ providerMessageId: message.providerMessageId,
4863
+ recipients: (deliveries[index] ?? []).map((delivery) => ({
4864
+ email: delivery.email,
4865
+ kind: delivery.kind,
4866
+ status: delivery.status,
4867
+ })),
4868
+ status: message.status,
4869
+ subject: message.subject,
4870
+ tag: message.tag,
4871
+ }));
4872
+ return (
4873
+ <AdminMailConsole
4874
+ cancelAction={cancelMail}
4875
+ retryAction={retryMail}
4876
+ rows={rows}
4877
+ testAction={sendTestMail}
4878
+ />
4879
+ );
4880
+ }
4881
+ `;
4882
+ }
4883
+ function mailWebhookRouteTemplate(config) {
4884
+ return `import { createPostalWebhookRouteHandler } from "@gadicc/loom/next/mail";
4885
+ import { mailService } from "${toAliasImportPath(config.modules.serviceModule)}";
4886
+ import { getPostalWebhookPublicKeys } from "${toAliasImportPath(config.modules.transportModule)}";
4887
+
4888
+ export const POST = createPostalWebhookRouteHandler({
4889
+ handleEvent: (event) => mailService.handleProviderEvent(event),
4890
+ publicKeys: getPostalWebhookPublicKeys,
4891
+ });
4892
+ `;
4893
+ }
4894
+ function mailJobTemplate(config) {
4895
+ return `import type { Job } from "@gadicc/loom/jobs";
4896
+ import { mailService } from "${toAliasImportPath(config.modules.serviceModule)}";
4897
+
4898
+ export const meta = {
4899
+ id: "mail-drain",
4900
+ desc: "Deliver due messages from the durable mail outbox.",
4901
+ };
4902
+
4903
+ export const handler: Job["handler"] = async (job, params) => {
4904
+ const parsed = typeof params.limit === "string" ? Number(params.limit) : Number.NaN;
4905
+ const limit = Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 20;
4906
+ const result = await mailService.drain(limit);
4907
+ job.json({ result });
4908
+ };
4909
+ `;
4910
+ }
4109
4911
  async function readTsModuleNames(path) {
4110
4912
  try {
4111
4913
  const entries = await (0, promises_1.readdir)(path, { withFileTypes: true });
@@ -4148,7 +4950,9 @@ function getLatestManagedSchemaConfig(schema) {
4148
4950
  ? schema.idGeneration === "uuid-v7"
4149
4951
  ? FILES_SCHEMA_UUID_V7_BLUEPRINT_VERSION
4150
4952
  : FILES_SCHEMA_UUID_V4_BLUEPRINT_VERSION
4151
- : API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION,
4953
+ : schema.blueprint === "mail"
4954
+ ? MAIL_SCHEMA_BLUEPRINT_VERSION
4955
+ : API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION,
4152
4956
  };
4153
4957
  return {
4154
4958
  ...latest,
@@ -4161,6 +4965,8 @@ function getManagedSchemaText(schema) {
4161
4965
  return buildApiKeyAuditSchemaText(schema);
4162
4966
  case "files":
4163
4967
  return buildFilesSchemaText(schema);
4968
+ case "mail":
4969
+ return buildMailSchemaText(schema);
4164
4970
  }
4165
4971
  }
4166
4972
  function getSchemaBarrelExportLine(schema, dbConfig) {
@@ -4342,8 +5148,25 @@ async function syncDbSchemas(cwd) {
4342
5148
  suggestions.add("Move API-key audit schema additions to separate local schema files, then rerun `loom db schemas sync`.");
4343
5149
  }
4344
5150
  }
5151
+ const mailFeature = manifest.features.mail;
5152
+ if (mailFeature?.status === "active") {
5153
+ const mailConfig = getMailConfig(framework, dbConfig, (await readProjectPackageJson(cwd)).packageJson, mailFeature.config, manifest.features.jobs?.status === "active");
5154
+ const materialized = await materializeManagedSchema(cwd, mailConfig.schema, dbConfig);
5155
+ changedFiles.push(...materialized.changedFiles);
5156
+ issues.push(...materialized.issues);
5157
+ notes.push(...materialized.notes);
5158
+ if (!materialized.issues.length) {
5159
+ mailConfig.schema = materialized.schema;
5160
+ mailFeature.config = mailConfig;
5161
+ manifest.features.mail = mailFeature;
5162
+ }
5163
+ else {
5164
+ suggestions.add("Move mail schema additions to separate local schema files, then rerun `loom db schemas sync`.");
5165
+ }
5166
+ }
4345
5167
  if ((!filesFeature || filesFeature.status !== "active") &&
4346
- (!apiKeysFeature || apiKeysFeature.status !== "active")) {
5168
+ (!apiKeysFeature || apiKeysFeature.status !== "active") &&
5169
+ (!mailFeature || mailFeature.status !== "active")) {
4347
5170
  notes.push("No active Loom-managed DB schemas are configured.");
4348
5171
  }
4349
5172
  const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
@@ -6570,6 +7393,93 @@ async function applyFilesFeature(cwd, framework, manifest, activate) {
6570
7393
  manifest.features.files = feature;
6571
7394
  return { changedFiles, notes };
6572
7395
  }
7396
+ async function applyMailFeature(cwd, framework, manifest, activate) {
7397
+ const changedFiles = [];
7398
+ const notes = [];
7399
+ const currentFeature = manifest.features.mail;
7400
+ if (!activate && currentFeature?.status !== "active") {
7401
+ return { changedFiles, notes };
7402
+ }
7403
+ for (const dependency of ["auth", "db"]) {
7404
+ if (manifest.features[dependency]?.status !== "active") {
7405
+ if (activate) {
7406
+ throw new Error(`The mail feature requires the active ${dependency} feature. Run \`loom add ${dependency}\` first.`);
7407
+ }
7408
+ notes.push(`Mail requires the active ${dependency} feature.`);
7409
+ return { changedFiles, notes };
7410
+ }
7411
+ }
7412
+ const { packageJson } = await readProjectPackageJson(cwd);
7413
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
7414
+ const config = getMailConfig(framework, dbConfig, packageJson, currentFeature?.config, manifest.features.jobs?.status === "active");
7415
+ const feature = currentFeature
7416
+ ? structuredClone(currentFeature)
7417
+ : { status: "planned" };
7418
+ if (activate && feature.status !== "active") {
7419
+ feature.status = "active";
7420
+ feature.activatedOn ??= todayIso();
7421
+ }
7422
+ if (activate) {
7423
+ const materialized = await materializeManagedSchema(cwd, config.schema, dbConfig);
7424
+ if (materialized.issues.length) {
7425
+ throw new Error(materialized.issues.join("\n"));
7426
+ }
7427
+ changedFiles.push(...materialized.changedFiles);
7428
+ notes.push(...materialized.notes);
7429
+ config.schema = materialized.schema;
7430
+ 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.");
7431
+ }
7432
+ const scaffolds = [
7433
+ [config.modules.accessModule, mailAccessTemplate(), "admin access policy"],
7434
+ [
7435
+ config.modules.repositoryModule,
7436
+ mailRepositoryTemplate(config, dbConfig),
7437
+ "repository",
7438
+ ],
7439
+ [
7440
+ config.modules.transportModule,
7441
+ mailTransportTemplate(),
7442
+ "Postal transport",
7443
+ ],
7444
+ [config.modules.serviceModule, mailServiceTemplate(config), "service"],
7445
+ [
7446
+ config.modules.actionsModule,
7447
+ mailActionsTemplate(config),
7448
+ "admin actions",
7449
+ ],
7450
+ [config.entrypoints.adminPage, mailAdminPageTemplate(config), "admin page"],
7451
+ [
7452
+ config.entrypoints.webhookRoute,
7453
+ mailWebhookRouteTemplate(config),
7454
+ "Postal webhook route",
7455
+ ],
7456
+ ];
7457
+ if (config.jobs.enabled) {
7458
+ scaffolds.push([
7459
+ config.modules.jobModule,
7460
+ mailJobTemplate(config),
7461
+ "outbox drain job",
7462
+ ]);
7463
+ }
7464
+ for (const [relativePath, text, label] of scaffolds) {
7465
+ const scaffoldState = await scaffoldTextFile((0, node_path_1.join)(cwd, relativePath), text);
7466
+ if (scaffoldState === "created") {
7467
+ changedFiles.push(relativePath);
7468
+ }
7469
+ else if (activate && scaffoldState === "preserved") {
7470
+ notes.push(`Preserved existing mail ${label}: ${relativePath}`);
7471
+ }
7472
+ }
7473
+ if (config.ui.adapter === "mui") {
7474
+ 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.`);
7475
+ }
7476
+ if (config.jobs.enabled) {
7477
+ notes.push(`Register ${config.modules.jobModule} in the app-owned jobs catalogs and scheduling policy; Loom did not rewrite them.`);
7478
+ }
7479
+ feature.config = config;
7480
+ manifest.features.mail = feature;
7481
+ return { changedFiles, notes };
7482
+ }
6573
7483
  async function applyApiKeysFeature(cwd, framework, manifest, activate) {
6574
7484
  const changedFiles = [];
6575
7485
  const notes = [];
@@ -7328,6 +8238,147 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
7328
8238
  warnings,
7329
8239
  };
7330
8240
  }
8241
+ async function checkMailFeature(cwd, framework, manifest, options) {
8242
+ const issues = [];
8243
+ const suggestions = new Set();
8244
+ const warnings = [];
8245
+ const feature = manifest.features.mail;
8246
+ if (!feature || feature.status !== "active") {
8247
+ return { issues, suggestions: [], warnings };
8248
+ }
8249
+ for (const dependency of ["auth", "db"]) {
8250
+ if (manifest.features[dependency]?.status !== "active") {
8251
+ issues.push(`Mail feature requires the active ${dependency} feature.`);
8252
+ suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
8253
+ }
8254
+ }
8255
+ if (issues.length)
8256
+ return { issues, suggestions: [...suggestions], warnings };
8257
+ const { packageJson } = await readProjectPackageJson(cwd);
8258
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
8259
+ const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
8260
+ const schema = config.schema;
8261
+ const latestSchema = getLatestManagedSchemaConfig(schema);
8262
+ if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
8263
+ issues.push("Mail must use the managed-local mail schema blueprint.");
8264
+ suggestions.add("Run `loom add mail` to restore the mail schema config.");
8265
+ }
8266
+ if (schema.exports.length !== 3) {
8267
+ issues.push("Mail schema must configure message, delivery, and event exports.");
8268
+ }
8269
+ if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
8270
+ issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
8271
+ }
8272
+ else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
8273
+ warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
8274
+ suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
8275
+ }
8276
+ const schemaText = await readTextIfExists((0, node_path_1.join)(cwd, schema.module));
8277
+ if (!schemaText) {
8278
+ issues.push(`Mail schema file is missing: ${schema.module}`);
8279
+ suggestions.add("Run `loom db schemas sync`.");
8280
+ }
8281
+ else {
8282
+ const currentHash = hashManagedSchemaText(schemaText);
8283
+ if (currentHash !== schema.hash) {
8284
+ if (currentHash === latestSchema.hash) {
8285
+ warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
8286
+ suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
8287
+ }
8288
+ else {
8289
+ issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
8290
+ suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
8291
+ }
8292
+ }
8293
+ const barrelText = await readTextIfExists((0, node_path_1.join)(cwd, dbConfig.dirs.schemaDir, "index.ts"));
8294
+ if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
8295
+ issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
8296
+ suggestions.add("Run `loom db schemas sync`.");
8297
+ }
8298
+ }
8299
+ const requiredFiles = [
8300
+ config.modules.accessModule,
8301
+ config.modules.actionsModule,
8302
+ config.modules.repositoryModule,
8303
+ config.modules.serviceModule,
8304
+ config.modules.transportModule,
8305
+ config.entrypoints.adminPage,
8306
+ config.entrypoints.webhookRoute,
8307
+ ...(config.jobs.enabled ? [config.modules.jobModule] : []),
8308
+ ];
8309
+ for (const relativePath of requiredFiles) {
8310
+ if (!await exists((0, node_path_1.join)(cwd, relativePath))) {
8311
+ issues.push(`Mail scaffold file is missing: ${relativePath}`);
8312
+ suggestions.add("Run `loom add mail` to restore missing scaffolds.");
8313
+ }
8314
+ }
8315
+ const accessText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.accessModule));
8316
+ if (accessText && !accessText.includes("authorizeMailAdmin")) {
8317
+ issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
8318
+ }
8319
+ const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
8320
+ if (generatedDenyAll) {
8321
+ const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
8322
+ if (options.production)
8323
+ issues.push(message);
8324
+ else
8325
+ warnings.push(message);
8326
+ suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
8327
+ }
8328
+ const contentChecks = [
8329
+ [
8330
+ config.modules.repositoryModule,
8331
+ "@gadicc/loom/mail",
8332
+ "Mail repository is not typed against the shared mail contract",
8333
+ ],
8334
+ [
8335
+ config.modules.serviceModule,
8336
+ "createLoomMailService",
8337
+ "Mail service is not wired to the shared durable service",
8338
+ ],
8339
+ [
8340
+ config.modules.transportModule,
8341
+ "createPostalMailTransport",
8342
+ "Mail transport is not wired to the Postal adapter",
8343
+ ],
8344
+ [
8345
+ config.modules.transportModule,
8346
+ "POSTAL_WEBHOOK_PUBLIC_KEYS",
8347
+ "Mail transport does not configure Postal webhook public keys",
8348
+ ],
8349
+ [
8350
+ config.entrypoints.webhookRoute,
8351
+ "createPostalWebhookRouteHandler",
8352
+ "Mail webhook route does not use the signed shared route handler",
8353
+ ],
8354
+ [
8355
+ config.modules.actionsModule,
8356
+ "authorizeMailAdmin",
8357
+ "Mail admin actions do not enforce the app-owned admin boundary",
8358
+ ],
8359
+ [
8360
+ config.entrypoints.adminPage,
8361
+ "authorizeMailAdmin",
8362
+ "Mail admin page does not enforce the app-owned admin boundary",
8363
+ ],
8364
+ ];
8365
+ for (const [relativePath, snippet, label] of contentChecks) {
8366
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
8367
+ if (text && !text.includes(snippet)) {
8368
+ issues.push(`${label}: ${relativePath}`);
8369
+ suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
8370
+ }
8371
+ }
8372
+ if (config.ui.adapter === "mui" &&
8373
+ !hasPackageDependency(packageJson, "@mui/material")) {
8374
+ issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
8375
+ }
8376
+ if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
8377
+ warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
8378
+ suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
8379
+ }
8380
+ return { issues, suggestions: [...suggestions], warnings };
8381
+ }
7331
8382
  function packageDependencySpec(packageJson, dependencyName) {
7332
8383
  return packageJson.dependencies?.[dependencyName] ??
7333
8384
  packageJson.devDependencies?.[dependencyName];
@@ -7816,6 +8867,10 @@ const featureHooks = {
7816
8867
  apply: applyJobsFeature,
7817
8868
  check: checkJobsFeature,
7818
8869
  },
8870
+ mail: {
8871
+ apply: applyMailFeature,
8872
+ check: checkMailFeature,
8873
+ },
7819
8874
  pwa: {
7820
8875
  apply: applyPwaFeature,
7821
8876
  check: checkPwaFeature,
@@ -8657,7 +9712,7 @@ function printHelp({ out }) {
8657
9712
  out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
8658
9713
  out(" db neon setup Provision and connect a Vercel-managed Neon database for Production and Preview.");
8659
9714
  out(" db neon check Run the DB/Neon network checks registered for the active DB feature.");
8660
- out(" db migrations verify-env Validate migration URL precedence and role metadata without printing credentials.");
9715
+ out(" db migrations verify-env Validate migration URL precedence and role metadata without printing credentials. Accepts --env-file <path>.");
8661
9716
  out(" db migrations setup-github Store an existing direct migration URL as a protected GitHub Environment secret.");
8662
9717
  out(" db release setup-github Create/update GitHub production release config for staged Vercel deploys.");
8663
9718
  out(" db release prepare-build-env <env> <metadata> <policy> <manifest> Prepare metadata-backed placeholders for an external Vercel build.");
@@ -8691,6 +9746,7 @@ function printHelp({ out }) {
8691
9746
  out(" --repair Apply declared non-secret Files provider drift; never deletes resources or rotates credentials.");
8692
9747
  out(" --token-name <name> Override the Vercel token name for `loom db release setup-github`.");
8693
9748
  out(" --environment <name> GitHub Environment for migration credential setup (default production).");
9749
+ out(" --env-file <path> Preserved env snapshot for `db migrations verify-env`; process values take precedence.");
8694
9750
  out(" --resource <name> Permission resource for API-key integration.");
8695
9751
  out(" --action <name> Permission action for API-key integration.");
8696
9752
  out(" --allow-query Allow the integration's explicit query credential transport.");
@@ -9282,7 +10338,9 @@ async function runDbMigrations(cwd, command, io, options) {
9282
10338
  return 0;
9283
10339
  }
9284
10340
  case "verify-env": {
9285
- const result = (0, migrationEnv_js_1.resolveMigrationEnvironment)(node_process_1.default.env);
10341
+ const result = options.envFile
10342
+ ? (0, migrationEnv_js_1.resolveMigrationEnvironmentFromEnvFile)((0, node_path_1.resolve)(cwd, options.envFile), node_process_1.default.env)
10343
+ : (0, migrationEnv_js_1.resolveMigrationEnvironment)(node_process_1.default.env);
9286
10344
  io.out(`Migration database environment is usable: ${result.envName} selects role ${result.role} and database ${result.database}.`);
9287
10345
  if (!result.envName.startsWith("MIGRATION_")) {
9288
10346
  io.out("Warning: using the gradual-adoption application database fallback; prefer MIGRATION_DATABASE_URL_UNPOOLED after provisioning a dedicated migration credential.");
@@ -9462,6 +10520,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
9462
10520
  "configure-secrets": { type: "boolean" },
9463
10521
  cwd: { type: "string" },
9464
10522
  environment: { type: "string" },
10523
+ "env-file": { type: "string" },
9465
10524
  force: { type: "boolean" },
9466
10525
  help: { short: "h", type: "boolean" },
9467
10526
  jurisdiction: { type: "string" },
@@ -9565,6 +10624,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
9565
10624
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
9566
10625
  name: parsed.values.name,
9567
10626
  environment: parsed.values.environment,
10627
+ envFile: parsed.values["env-file"],
9568
10628
  noColor: parsed.values["no-color"],
9569
10629
  noProgress: parsed.values["no-progress"],
9570
10630
  neonAuth: parsed.values["neon-auth"],