easy-ping 0.1.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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +374 -0
  3. package/dist/adapter-f0OR2DhY.d.cts +200 -0
  4. package/dist/adapter-f0OR2DhY.d.ts +200 -0
  5. package/dist/adapters/drizzle.cjs +440 -0
  6. package/dist/adapters/drizzle.cjs.map +1 -0
  7. package/dist/adapters/drizzle.d.cts +991 -0
  8. package/dist/adapters/drizzle.d.ts +991 -0
  9. package/dist/adapters/drizzle.js +409 -0
  10. package/dist/adapters/drizzle.js.map +1 -0
  11. package/dist/adapters/mongodb.cjs +458 -0
  12. package/dist/adapters/mongodb.cjs.map +1 -0
  13. package/dist/adapters/mongodb.d.cts +32 -0
  14. package/dist/adapters/mongodb.d.ts +32 -0
  15. package/dist/adapters/mongodb.js +376 -0
  16. package/dist/adapters/mongodb.js.map +1 -0
  17. package/dist/browser.cjs +96 -0
  18. package/dist/browser.cjs.map +1 -0
  19. package/dist/browser.d.cts +45 -0
  20. package/dist/browser.d.ts +45 -0
  21. package/dist/browser.js +89 -0
  22. package/dist/browser.js.map +1 -0
  23. package/dist/chunk-BV3U542P.js +11 -0
  24. package/dist/chunk-BV3U542P.js.map +1 -0
  25. package/dist/chunk-NYDVNMKG.js +62 -0
  26. package/dist/chunk-NYDVNMKG.js.map +1 -0
  27. package/dist/chunk-OZSOIX23.js +120 -0
  28. package/dist/chunk-OZSOIX23.js.map +1 -0
  29. package/dist/chunk-PTGHMCCG.js +23 -0
  30. package/dist/chunk-PTGHMCCG.js.map +1 -0
  31. package/dist/chunk-W3BMEPPQ.js +50 -0
  32. package/dist/chunk-W3BMEPPQ.js.map +1 -0
  33. package/dist/client.cjs +160 -0
  34. package/dist/client.cjs.map +1 -0
  35. package/dist/client.d.cts +42 -0
  36. package/dist/client.d.ts +42 -0
  37. package/dist/client.js +158 -0
  38. package/dist/client.js.map +1 -0
  39. package/dist/index.cjs +920 -0
  40. package/dist/index.cjs.map +1 -0
  41. package/dist/index.d.cts +203 -0
  42. package/dist/index.d.ts +203 -0
  43. package/dist/index.js +723 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/node.cjs +49 -0
  46. package/dist/node.cjs.map +1 -0
  47. package/dist/node.d.cts +8 -0
  48. package/dist/node.d.ts +8 -0
  49. package/dist/node.js +46 -0
  50. package/dist/node.js.map +1 -0
  51. package/dist/plugin-Bqj9xAOS.d.cts +217 -0
  52. package/dist/plugin-bTJKmnlq.d.ts +217 -0
  53. package/dist/plugins/digests.cjs +206 -0
  54. package/dist/plugins/digests.cjs.map +1 -0
  55. package/dist/plugins/digests.d.cts +68 -0
  56. package/dist/plugins/digests.d.ts +68 -0
  57. package/dist/plugins/digests.js +201 -0
  58. package/dist/plugins/digests.js.map +1 -0
  59. package/dist/plugins/preferences-client.cjs +23 -0
  60. package/dist/plugins/preferences-client.cjs.map +1 -0
  61. package/dist/plugins/preferences-client.d.cts +29 -0
  62. package/dist/plugins/preferences-client.d.ts +29 -0
  63. package/dist/plugins/preferences-client.js +18 -0
  64. package/dist/plugins/preferences-client.js.map +1 -0
  65. package/dist/plugins/preferences-react.cjs +125 -0
  66. package/dist/plugins/preferences-react.cjs.map +1 -0
  67. package/dist/plugins/preferences-react.d.cts +40 -0
  68. package/dist/plugins/preferences-react.d.ts +40 -0
  69. package/dist/plugins/preferences-react.js +101 -0
  70. package/dist/plugins/preferences-react.js.map +1 -0
  71. package/dist/plugins/preferences.cjs +147 -0
  72. package/dist/plugins/preferences.cjs.map +1 -0
  73. package/dist/plugins/preferences.d.cts +22 -0
  74. package/dist/plugins/preferences.d.ts +22 -0
  75. package/dist/plugins/preferences.js +119 -0
  76. package/dist/plugins/preferences.js.map +1 -0
  77. package/dist/plugins/push.cjs +146 -0
  78. package/dist/plugins/push.cjs.map +1 -0
  79. package/dist/plugins/push.d.cts +60 -0
  80. package/dist/plugins/push.d.ts +60 -0
  81. package/dist/plugins/push.js +144 -0
  82. package/dist/plugins/push.js.map +1 -0
  83. package/dist/provider-CA45WVqt.d.cts +23 -0
  84. package/dist/provider-CA45WVqt.d.ts +23 -0
  85. package/dist/providers/resend.cjs +69 -0
  86. package/dist/providers/resend.cjs.map +1 -0
  87. package/dist/providers/resend.d.cts +20 -0
  88. package/dist/providers/resend.d.ts +20 -0
  89. package/dist/providers/resend.js +66 -0
  90. package/dist/providers/resend.js.map +1 -0
  91. package/dist/providers/web-push.cjs +211 -0
  92. package/dist/providers/web-push.cjs.map +1 -0
  93. package/dist/providers/web-push.d.cts +33 -0
  94. package/dist/providers/web-push.d.ts +33 -0
  95. package/dist/providers/web-push.js +193 -0
  96. package/dist/providers/web-push.js.map +1 -0
  97. package/dist/react.cjs +218 -0
  98. package/dist/react.cjs.map +1 -0
  99. package/dist/react.d.cts +57 -0
  100. package/dist/react.d.ts +57 -0
  101. package/dist/react.js +193 -0
  102. package/dist/react.js.map +1 -0
  103. package/dist/schema.cjs +263 -0
  104. package/dist/schema.cjs.map +1 -0
  105. package/dist/schema.d.cts +180 -0
  106. package/dist/schema.d.ts +180 -0
  107. package/dist/schema.js +200 -0
  108. package/dist/schema.js.map +1 -0
  109. package/dist/testing.cjs +342 -0
  110. package/dist/testing.cjs.map +1 -0
  111. package/dist/testing.d.cts +38 -0
  112. package/dist/testing.d.ts +38 -0
  113. package/dist/testing.js +340 -0
  114. package/dist/testing.js.map +1 -0
  115. package/package.json +168 -0
package/dist/schema.js ADDED
@@ -0,0 +1,200 @@
1
+ import { toSnakeCase } from './chunk-NYDVNMKG.js';
2
+ export { coreSchema, toSnakeCase } from './chunk-NYDVNMKG.js';
3
+
4
+ // src/schema/render-sql.ts
5
+ var SQL_TYPE = {
6
+ string: "text",
7
+ number: "integer",
8
+ boolean: "boolean",
9
+ date: "timestamptz",
10
+ json: "jsonb"
11
+ };
12
+ var quote = (value) => `"${value.replace(/"/g, '""')}"`;
13
+ var defaultClause = (field) => {
14
+ if (field.defaultNow) return " DEFAULT now()";
15
+ if (field.default === void 0) return "";
16
+ if (typeof field.default === "string") return ` DEFAULT '${field.default.replace(/'/g, "''")}'`;
17
+ return ` DEFAULT ${field.default}`;
18
+ };
19
+ function renderPostgresDdl(schema, prefix = "") {
20
+ const statements = [];
21
+ for (const table of Object.values(schema)) {
22
+ const name = quote(prefix + table.tableName);
23
+ const columns = Object.entries(table.fields).map(([field, spec]) => {
24
+ const nullability = spec.required ? " NOT NULL" : "";
25
+ return ` ${quote(toSnakeCase(field))} ${SQL_TYPE[spec.type]}${nullability}${defaultClause(spec)}`;
26
+ });
27
+ if (table.primaryKey?.length) {
28
+ const key = table.primaryKey.map((field) => quote(toSnakeCase(field))).join(", ");
29
+ columns.push(` PRIMARY KEY (${key})`);
30
+ }
31
+ statements.push(`CREATE TABLE IF NOT EXISTS ${name} (
32
+ ${columns.join(",\n")}
33
+ )`);
34
+ for (const declaration of table.indexes ?? []) {
35
+ const indexName2 = quote(
36
+ prefix + (declaration.name ?? `${table.tableName}_${declaration.on.join("_")}_idx`)
37
+ );
38
+ const columns2 = declaration.on.map((field) => quote(toSnakeCase(field))).join(", ");
39
+ const unique = declaration.unique ? "UNIQUE " : "";
40
+ statements.push(`CREATE ${unique}INDEX IF NOT EXISTS ${indexName2} ON ${name} (${columns2})`);
41
+ }
42
+ }
43
+ return statements;
44
+ }
45
+
46
+ // src/schema/migrate-sql.ts
47
+ var SQL_TYPE2 = {
48
+ string: "text",
49
+ number: "integer",
50
+ boolean: "boolean",
51
+ date: "timestamptz",
52
+ json: "jsonb"
53
+ };
54
+ var LIVE_TYPE = {
55
+ string: ["text", "character varying", "character"],
56
+ number: ["integer", "bigint", "smallint"],
57
+ boolean: ["boolean"],
58
+ date: ["timestamp with time zone", "timestamp without time zone"],
59
+ json: ["jsonb", "json"]
60
+ };
61
+ var quote2 = (value) => `"${value.replace(/"/g, '""')}"`;
62
+ var defaultClause2 = (field) => {
63
+ if (field.defaultNow) return " DEFAULT now()";
64
+ if (field.default === void 0) return "";
65
+ if (typeof field.default === "string") return ` DEFAULT '${field.default.replace(/'/g, "''")}'`;
66
+ return ` DEFAULT ${field.default}`;
67
+ };
68
+ var indexName = (table, declaration) => declaration.name ?? `${table.tableName}_${declaration.on.join("_")}_idx`;
69
+ var INTROSPECT_SQL = `
70
+ SELECT table_name, column_name, data_type, is_nullable
71
+ FROM information_schema.columns
72
+ WHERE table_schema = current_schema()
73
+ `;
74
+ async function planPostgresMigration(introspect, schema, prefix = "") {
75
+ const live = await introspect();
76
+ const byTable = /* @__PURE__ */ new Map();
77
+ for (const column of live) {
78
+ const columns = byTable.get(column.table) ?? /* @__PURE__ */ new Map();
79
+ columns.set(column.column, column);
80
+ byTable.set(column.table, columns);
81
+ }
82
+ const statements = [];
83
+ const unsupported = [];
84
+ const createdTables = [];
85
+ for (const table of Object.values(schema)) {
86
+ const qualified = prefix + table.tableName;
87
+ const existing = byTable.get(qualified);
88
+ if (!existing || existing.size === 0) {
89
+ createdTables.push(qualified);
90
+ statements.push(...renderPostgresDdl({ [table.tableName]: table }, prefix));
91
+ continue;
92
+ }
93
+ for (const [field, spec] of Object.entries(table.fields)) {
94
+ const column = toSnakeCase(field);
95
+ const found = existing.get(column);
96
+ if (!found) {
97
+ const canFill = spec.defaultNow || spec.default !== void 0;
98
+ const nullability = spec.required && canFill ? " NOT NULL" : "";
99
+ statements.push(
100
+ `ALTER TABLE ${quote2(qualified)} ADD COLUMN IF NOT EXISTS ${quote2(column)} ${SQL_TYPE2[spec.type]}${nullability}${defaultClause2(spec)}`
101
+ );
102
+ if (spec.required && !canFill) {
103
+ unsupported.push(
104
+ `${qualified}.${column} is declared required but has no default; it was added nullable. Backfill it, then ALTER ... SET NOT NULL yourself.`
105
+ );
106
+ }
107
+ continue;
108
+ }
109
+ if (!LIVE_TYPE[spec.type].includes(found.type)) {
110
+ unsupported.push(
111
+ `${qualified}.${column} is ${found.type} but ${spec.type} is declared (${SQL_TYPE2[spec.type]}). Changing a column type can lose data \u2014 do it yourself.`
112
+ );
113
+ }
114
+ }
115
+ for (const declaration of table.indexes ?? []) {
116
+ const name = quote2(prefix + indexName(table, declaration));
117
+ const columns = declaration.on.map((field) => quote2(toSnakeCase(field))).join(", ");
118
+ statements.push(
119
+ `CREATE ${declaration.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${name} ON ${quote2(qualified)} (${columns})`
120
+ );
121
+ }
122
+ for (const column of existing.keys()) {
123
+ const declared = Object.keys(table.fields).some((field) => toSnakeCase(field) === column);
124
+ if (!declared) {
125
+ unsupported.push(
126
+ `${qualified}.${column} exists but is not declared. Left alone \u2014 drop it yourself if it is ours and no longer needed.`
127
+ );
128
+ }
129
+ }
130
+ }
131
+ return { statements, unsupported, createdTables };
132
+ }
133
+
134
+ // src/schema/render-drizzle.ts
135
+ var COLUMN_BUILDER = {
136
+ string: "text",
137
+ number: "integer",
138
+ boolean: "boolean",
139
+ date: "timestamp",
140
+ json: "jsonb"
141
+ };
142
+ var literal = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
143
+ function renderColumn(name, field, isSinglePk) {
144
+ const builder = COLUMN_BUILDER[field.type];
145
+ const column = toSnakeCase(name);
146
+ let expression = field.type === "date" ? `${builder}(${JSON.stringify(column)}, { withTimezone: true })` : `${builder}(${JSON.stringify(column)})`;
147
+ if (isSinglePk) return ` ${name}: ${expression}.primaryKey(),`;
148
+ if (field.required) expression += ".notNull()";
149
+ if (field.defaultNow) expression += ".defaultNow()";
150
+ else if (field.default !== void 0) expression += `.default(${literal(field.default)})`;
151
+ return ` ${name}: ${expression},`;
152
+ }
153
+ function renderTable(key, table, prefix) {
154
+ const compositePk = (table.primaryKey?.length ?? 0) > 1;
155
+ const singlePk = !compositePk ? table.primaryKey?.[0] : void 0;
156
+ const columns = Object.entries(table.fields).map(([name, field]) => renderColumn(name, field, name === singlePk)).join("\n");
157
+ const extras = [];
158
+ for (const declaration of table.indexes ?? []) {
159
+ const builder = declaration.unique ? "uniqueIndex" : "index";
160
+ const name = declaration.name ?? `${table.tableName}_${declaration.on.join("_")}_idx`;
161
+ const columns2 = declaration.on.map((field) => `table.${field}`).join(", ");
162
+ extras.push(` ${builder}(${JSON.stringify(prefix + name)}).on(${columns2}),`);
163
+ }
164
+ if (compositePk) {
165
+ const columns2 = (table.primaryKey ?? []).map((field) => `table.${field}`).join(", ");
166
+ extras.push(` primaryKey({ columns: [${columns2}] }),`);
167
+ }
168
+ const third = extras.length ? `,
169
+ (table) => [
170
+ ${extras.join("\n")}
171
+ ]` : "";
172
+ return `export const ${key} = pgTable(
173
+ ${JSON.stringify(prefix + table.tableName)},
174
+ {
175
+ ${columns}
176
+ }${third},
177
+ );`;
178
+ }
179
+ function renderDrizzleSchema(schema, prefix = "") {
180
+ const tables = Object.entries(schema);
181
+ const used = /* @__PURE__ */ new Set(["pgTable"]);
182
+ for (const [, table] of tables) {
183
+ for (const field of Object.values(table.fields)) used.add(COLUMN_BUILDER[field.type]);
184
+ for (const declaration of table.indexes ?? []) {
185
+ used.add(declaration.unique ? "uniqueIndex" : "index");
186
+ }
187
+ if ((table.primaryKey?.length ?? 0) > 1) used.add("primaryKey");
188
+ }
189
+ const imports = [...used].sort().join(", ");
190
+ const body = tables.map(([key, table]) => renderTable(key, table, prefix)).join("\n\n");
191
+ return `// Generated by easy-ping. Do not edit by hand.
192
+ import { ${imports} } from "drizzle-orm/pg-core";
193
+
194
+ ${body}
195
+ `;
196
+ }
197
+
198
+ export { INTROSPECT_SQL, planPostgresMigration, renderDrizzleSchema, renderPostgresDdl };
199
+ //# sourceMappingURL=schema.js.map
200
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema/render-sql.ts","../src/schema/migrate-sql.ts","../src/schema/render-drizzle.ts"],"names":["indexName","columns","SQL_TYPE","quote","defaultClause"],"mappings":";;;;AAGA,IAAM,QAAA,GAAqD;AAAA,EACzD,MAAA,EAAQ,MAAA;AAAA,EACR,MAAA,EAAQ,SAAA;AAAA,EACR,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,EAAQ,KAAK,CAAA;AAAA,EAAA,CAAA;AACrH;AAGO,SAAS,mBAAA,CAAoB,MAAA,EAA2B,MAAA,GAAS,EAAA,EAAY;AAClF,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA;AAEpC,EAAA,MAAM,IAAA,mBAAO,IAAI,GAAA,CAAY,CAAC,SAAS,CAAC,CAAA;AACxC,EAAA,KAAA,MAAW,GAAG,KAAK,CAAA,IAAK,MAAA,EAAQ;AAC9B,IAAA,KAAA,MAAW,KAAA,IAAS,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,MAAM,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,cAAA,CAAe,KAAA,CAAM,IAAI,CAAC,CAAA;AACpF,IAAA,KAAA,MAAW,WAAA,IAAe,KAAA,CAAM,OAAA,IAAW,EAAC,EAAG;AAC7C,MAAA,IAAA,CAAK,GAAA,CAAI,WAAA,CAAY,MAAA,GAAS,aAAA,GAAgB,OAAO,CAAA;AAAA,IACvD;AACA,IAAA,IAAA,CAAK,MAAM,UAAA,EAAY,MAAA,IAAU,KAAK,CAAA,EAAG,IAAA,CAAK,IAAI,YAAY,CAAA;AAAA,EAChE;AAEA,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,IAAI,EAAE,IAAA,EAAK,CAAE,KAAK,IAAI,CAAA;AAC1C,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,KAAK,CAAA,KAAM,WAAA,CAAY,KAAK,KAAA,EAAO,MAAM,CAAC,CAAA,CAAE,KAAK,MAAM,CAAA;AAEtF,EAAA,OAAO,CAAA;AAAA,SAAA,EAA6D,OAAO,CAAA;;AAAA,EAAqC,IAAI;AAAA,CAAA;AACtH","file":"schema.js","sourcesContent":["import type { FieldDeclaration, SchemaDeclaration } from \"../core/plugin\";\nimport { toSnakeCase } from \"./declaration\";\n\nconst SQL_TYPE: Record<FieldDeclaration[\"type\"], string> = {\n string: \"text\",\n number: \"integer\",\n boolean: \"boolean\",\n date: \"timestamptz\",\n json: \"jsonb\",\n};\n\nconst quote = (value: string) => `\"${value.replace(/\"/g, '\"\"')}\"`;\n\nconst defaultClause = (field: FieldDeclaration): string => {\n if (field.defaultNow) return \" DEFAULT now()\";\n if (field.default === undefined) return \"\";\n if (typeof field.default === \"string\") return ` DEFAULT '${field.default.replace(/'/g, \"''\")}'`;\n return ` DEFAULT ${field.default}`;\n};\n\n/** SchemaDeclaration to Postgres DDL, from the same source as the Drizzle renderer. */\nexport function renderPostgresDdl(schema: SchemaDeclaration, prefix = \"\"): string[] {\n const statements: string[] = [];\n\n for (const table of Object.values(schema)) {\n const name = quote(prefix + table.tableName);\n\n const columns = Object.entries(table.fields).map(([field, spec]) => {\n const nullability = spec.required ? \" NOT NULL\" : \"\";\n return ` ${quote(toSnakeCase(field))} ${SQL_TYPE[spec.type]}${nullability}${defaultClause(spec)}`;\n });\n\n if (table.primaryKey?.length) {\n const key = table.primaryKey.map((field) => quote(toSnakeCase(field))).join(\", \");\n columns.push(` PRIMARY KEY (${key})`);\n }\n\n statements.push(`CREATE TABLE IF NOT EXISTS ${name} (\\n${columns.join(\",\\n\")}\\n)`);\n\n for (const declaration of table.indexes ?? []) {\n const indexName = quote(\n prefix + (declaration.name ?? `${table.tableName}_${declaration.on.join(\"_\")}_idx`),\n );\n const columns = declaration.on.map((field) => quote(toSnakeCase(field))).join(\", \");\n const unique = declaration.unique ? \"UNIQUE \" : \"\";\n statements.push(`CREATE ${unique}INDEX IF NOT EXISTS ${indexName} ON ${name} (${columns})`);\n }\n }\n\n return statements;\n}\n","import type { FieldDeclaration, SchemaDeclaration, TableDeclaration } from \"../core/plugin\";\nimport { toSnakeCase } from \"./declaration\";\nimport { renderPostgresDdl } from \"./render-sql\";\n\n/**\n * Introspects a live Postgres schema and emits only what is missing.\n *\n * renderPostgresDdl emits CREATE TABLE IF NOT EXISTS, which is correct exactly\n * once. On an existing database it is a silent no-op, so an adopter who\n * bootstrapped with raw SQL had no way to pick up a column a later version\n * added — their app broke at runtime with \"column does not exist\" instead.\n *\n * Additive only, on purpose. Dropping a column or changing a type is\n * destructive and context-dependent, so those are reported in `unsupported`\n * rather than guessed at.\n */\n\nconst SQL_TYPE: Record<FieldDeclaration[\"type\"], string> = {\n string: \"text\",\n number: \"integer\",\n boolean: \"boolean\",\n date: \"timestamptz\",\n json: \"jsonb\",\n};\n\n/** What information_schema reports for each of our declared types. */\nconst LIVE_TYPE: Record<FieldDeclaration[\"type\"], readonly string[]> = {\n string: [\"text\", \"character varying\", \"character\"],\n number: [\"integer\", \"bigint\", \"smallint\"],\n boolean: [\"boolean\"],\n date: [\"timestamp with time zone\", \"timestamp without time zone\"],\n json: [\"jsonb\", \"json\"],\n};\n\nconst quote = (value: string) => `\"${value.replace(/\"/g, '\"\"')}\"`;\n\nconst defaultClause = (field: FieldDeclaration): string => {\n if (field.defaultNow) return \" DEFAULT now()\";\n if (field.default === undefined) return \"\";\n if (typeof field.default === \"string\") return ` DEFAULT '${field.default.replace(/'/g, \"''\")}'`;\n return ` DEFAULT ${field.default}`;\n};\n\nconst indexName = (\n table: TableDeclaration,\n declaration: { on: readonly string[]; name?: string },\n) => declaration.name ?? `${table.tableName}_${declaration.on.join(\"_\")}_idx`;\n\nexport type LiveColumn = { table: string; column: string; type: string; nullable: boolean };\n\nexport type MigrationPlan = {\n /** Run in order. Empty means the live schema already matches. */\n statements: readonly string[];\n /** Differences this cannot express safely. Read them; they need a human. */\n unsupported: readonly string[];\n /** Tables that do not exist yet — these get a full CREATE TABLE. */\n createdTables: readonly string[];\n};\n\n/**\n * Reads the live column list. Pass a function that runs the query — this\n * module stays driver-agnostic, as the rest of the schema tooling does.\n */\nexport type Introspector = () => Promise<readonly LiveColumn[]>;\n\n/** The query an Introspector should run. Exported so callers need not retype it. */\nexport const INTROSPECT_SQL = `\n SELECT table_name, column_name, data_type, is_nullable\n FROM information_schema.columns\n WHERE table_schema = current_schema()\n`;\n\nexport async function planPostgresMigration(\n introspect: Introspector,\n schema: SchemaDeclaration,\n prefix = \"\",\n): Promise<MigrationPlan> {\n const live = await introspect();\n\n const byTable = new Map<string, Map<string, LiveColumn>>();\n for (const column of live) {\n const columns = byTable.get(column.table) ?? new Map<string, LiveColumn>();\n columns.set(column.column, column);\n byTable.set(column.table, columns);\n }\n\n const statements: string[] = [];\n const unsupported: string[] = [];\n const createdTables: string[] = [];\n\n for (const table of Object.values(schema)) {\n const qualified = prefix + table.tableName;\n const existing = byTable.get(qualified);\n\n // Absent entirely: the ordinary bootstrap path still applies.\n if (!existing || existing.size === 0) {\n createdTables.push(qualified);\n statements.push(...renderPostgresDdl({ [table.tableName]: table }, prefix));\n continue;\n }\n\n for (const [field, spec] of Object.entries(table.fields)) {\n const column = toSnakeCase(field);\n const found = existing.get(column);\n\n if (!found) {\n // NOT NULL on a populated table fails without a default, so a required\n // column that cannot fill itself is added nullable and flagged.\n const canFill = spec.defaultNow || spec.default !== undefined;\n const nullability = spec.required && canFill ? \" NOT NULL\" : \"\";\n\n statements.push(\n `ALTER TABLE ${quote(qualified)} ADD COLUMN IF NOT EXISTS ` +\n `${quote(column)} ${SQL_TYPE[spec.type]}${nullability}${defaultClause(spec)}`,\n );\n\n if (spec.required && !canFill) {\n unsupported.push(\n `${qualified}.${column} is declared required but has no default; ` +\n \"it was added nullable. Backfill it, then ALTER ... SET NOT NULL yourself.\",\n );\n }\n continue;\n }\n\n if (!LIVE_TYPE[spec.type].includes(found.type)) {\n unsupported.push(\n `${qualified}.${column} is ${found.type} but ${spec.type} is declared ` +\n `(${SQL_TYPE[spec.type]}). Changing a column type can lose data — do it yourself.`,\n );\n }\n }\n\n // Indexes are cheap and idempotent, so they are re-issued unconditionally.\n for (const declaration of table.indexes ?? []) {\n const name = quote(prefix + indexName(table, declaration));\n const columns = declaration.on.map((field) => quote(toSnakeCase(field))).join(\", \");\n statements.push(\n `CREATE ${declaration.unique ? \"UNIQUE \" : \"\"}INDEX IF NOT EXISTS ${name} ` +\n `ON ${quote(qualified)} (${columns})`,\n );\n }\n\n for (const column of existing.keys()) {\n const declared = Object.keys(table.fields).some((field) => toSnakeCase(field) === column);\n if (!declared) {\n unsupported.push(\n `${qualified}.${column} exists but is not declared. Left alone — ` +\n \"drop it yourself if it is ours and no longer needed.\",\n );\n }\n }\n }\n\n return { statements, unsupported, createdTables };\n}\n","import type { FieldDeclaration, SchemaDeclaration, TableDeclaration } from \"../core/plugin\";\nimport { toSnakeCase } from \"./declaration\";\n\nconst COLUMN_BUILDER: Record<FieldDeclaration[\"type\"], string> = {\n string: \"text\",\n number: \"integer\",\n boolean: \"boolean\",\n date: \"timestamp\",\n json: \"jsonb\",\n};\n\nconst literal = (value: string | number | boolean) =>\n typeof value === \"string\" ? JSON.stringify(value) : String(value);\n\nfunction renderColumn(name: string, field: FieldDeclaration, isSinglePk: boolean): string {\n const builder = COLUMN_BUILDER[field.type];\n const column = toSnakeCase(name);\n\n let expression =\n field.type === \"date\"\n ? `${builder}(${JSON.stringify(column)}, { withTimezone: true })`\n : `${builder}(${JSON.stringify(column)})`;\n\n if (isSinglePk) return ` ${name}: ${expression}.primaryKey(),`;\n\n if (field.required) expression += \".notNull()\";\n if (field.defaultNow) expression += \".defaultNow()\";\n else if (field.default !== undefined) expression += `.default(${literal(field.default)})`;\n\n return ` ${name}: ${expression},`;\n}\n\nfunction renderTable(key: string, table: TableDeclaration, prefix: string): string {\n const compositePk = (table.primaryKey?.length ?? 0) > 1;\n const singlePk = !compositePk ? table.primaryKey?.[0] : undefined;\n\n const columns = Object.entries(table.fields)\n .map(([name, field]) => renderColumn(name, field, name === singlePk))\n .join(\"\\n\");\n\n const extras: string[] = [];\n\n for (const declaration of table.indexes ?? []) {\n const builder = declaration.unique ? \"uniqueIndex\" : \"index\";\n const name = declaration.name ?? `${table.tableName}_${declaration.on.join(\"_\")}_idx`;\n const columns = declaration.on.map((field) => `table.${field}`).join(\", \");\n extras.push(` ${builder}(${JSON.stringify(prefix + name)}).on(${columns}),`);\n }\n\n if (compositePk) {\n const columns = (table.primaryKey ?? []).map((field) => `table.${field}`).join(\", \");\n extras.push(` primaryKey({ columns: [${columns}] }),`);\n }\n\n const third = extras.length ? `,\\n (table) => [\\n${extras.join(\"\\n\")}\\n ]` : \"\";\n\n return `export const ${key} = pgTable(\\n ${JSON.stringify(prefix + table.tableName)},\\n {\\n${columns}\\n }${third},\\n);`;\n}\n\n/** Renders a SchemaDeclaration to Drizzle pg-core source. */\nexport function renderDrizzleSchema(schema: SchemaDeclaration, prefix = \"\"): string {\n const tables = Object.entries(schema);\n\n const used = new Set<string>([\"pgTable\"]);\n for (const [, table] of tables) {\n for (const field of Object.values(table.fields)) used.add(COLUMN_BUILDER[field.type]);\n for (const declaration of table.indexes ?? []) {\n used.add(declaration.unique ? \"uniqueIndex\" : \"index\");\n }\n if ((table.primaryKey?.length ?? 0) > 1) used.add(\"primaryKey\");\n }\n\n const imports = [...used].sort().join(\", \");\n const body = tables.map(([key, table]) => renderTable(key, table, prefix)).join(\"\\n\\n\");\n\n return `// Generated by easy-ping. Do not edit by hand.\\nimport { ${imports} } from \"drizzle-orm/pg-core\";\\n\\n${body}\\n`;\n}\n"]}
@@ -0,0 +1,342 @@
1
+ 'use strict';
2
+
3
+ // src/testing/conformance.ts
4
+ var ConformanceError = class extends Error {
5
+ };
6
+ function assert(condition, message) {
7
+ if (!condition) throw new ConformanceError(message);
8
+ }
9
+ var equal = (actual, expected, message) => assert(actual === expected, `${message} (got ${String(actual)}, expected ${String(expected)})`);
10
+ var counter = 0;
11
+ function uid(label) {
12
+ counter += 1;
13
+ return `${label}_${Date.now().toString(36)}_${counter}`;
14
+ }
15
+ async function seed(ctx, options = {}) {
16
+ const count = options.count ?? 1;
17
+ const userId = options.userId ?? uid("user");
18
+ const rows = Array.from({ length: count }, () => {
19
+ const id = uid("notif");
20
+ return {
21
+ id,
22
+ userId,
23
+ type: "commentReply",
24
+ payload: { authorName: "Dana" },
25
+ ...options.dedupeKey ? { dedupeKey: options.dedupeKey } : {},
26
+ deliveries: [
27
+ {
28
+ id: uid("delivery"),
29
+ channel: options.channel ?? "email",
30
+ maxAttempts: options.maxAttempts ?? 5,
31
+ notBefore: options.notBefore ?? new Date(Date.now() - 1e3)
32
+ }
33
+ ]
34
+ };
35
+ });
36
+ const result = await ctx.adapter.createNotifications(rows);
37
+ return { userId, rows, result };
38
+ }
39
+ var CLAIM = { limit: 10, leaseMs: 6e4 };
40
+ var adapterConformanceCases = [
41
+ {
42
+ /**
43
+ * The case that actually distinguishes a correct adapter.
44
+ *
45
+ * A row locked by another transaction must be *skipped*, not waited on.
46
+ * Without SKIP LOCKED the claim blocks until the holder commits, which on
47
+ * a busy table serialises every worker behind the slowest one.
48
+ */
49
+ name: "a row locked by another transaction is skipped, not waited on",
50
+ requires: "rowLock",
51
+ run: async (ctx) => {
52
+ const { lockRow } = ctx;
53
+ assert(lockRow, "case requires lockRow");
54
+ const { rows } = await seed(ctx, { count: 2 });
55
+ const locked = rows[0]?.deliveries[0]?.id;
56
+ const free = rows[1]?.deliveries[0]?.id;
57
+ assert(locked && free, "seed produced too few deliveries");
58
+ await lockRow(locked, async () => {
59
+ const claimed = await Promise.race([
60
+ ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("token") }),
61
+ new Promise(
62
+ (_, reject) => setTimeout(
63
+ () => reject(
64
+ new ConformanceError(
65
+ "claim blocked on a row locked by another transaction \u2014 SKIP LOCKED is missing"
66
+ )
67
+ ),
68
+ 2e3
69
+ )
70
+ )
71
+ ]);
72
+ const ids = new Set(claimed.map((row) => row.id));
73
+ assert(!ids.has(locked), "claimed a row locked by another transaction");
74
+ assert(ids.has(free), "skipped an unlocked row alongside the locked one");
75
+ });
76
+ }
77
+ },
78
+ {
79
+ name: "concurrent claims return disjoint sets",
80
+ run: async (ctx) => {
81
+ await seed(ctx, { count: 40 });
82
+ const claimed = await Promise.all(
83
+ Array.from(
84
+ { length: 8 },
85
+ () => ctx.adapter.claimPendingDeliveries({ limit: 5, leaseMs: 6e4, claimToken: uid("t") })
86
+ )
87
+ );
88
+ const all = claimed.flatMap((batch) => batch.map((row) => row.id));
89
+ equal(new Set(all).size, all.length, "the same delivery was claimed by two callers");
90
+ assert(all.length <= 40, "claimed more rows than exist");
91
+ }
92
+ },
93
+ {
94
+ name: "a claimed row is invisible before its lease expires",
95
+ run: async (ctx) => {
96
+ const { rows } = await seed(ctx);
97
+ const target = rows[0]?.deliveries[0]?.id;
98
+ const first = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
99
+ assert(
100
+ first.some((row) => row.id === target),
101
+ "seeded delivery was not claimed"
102
+ );
103
+ const second = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
104
+ assert(!second.some((row) => row.id === target), "leased row was claimed twice");
105
+ }
106
+ },
107
+ {
108
+ name: "a claimed row is re-claimable after its lease expires",
109
+ run: async (ctx) => {
110
+ const { rows } = await seed(ctx);
111
+ const target = rows[0]?.deliveries[0]?.id;
112
+ await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
113
+ const later = new Date(Date.now() + CLAIM.leaseMs + 5e3);
114
+ const reclaimed = await ctx.adapter.claimPendingDeliveries({
115
+ ...CLAIM,
116
+ claimToken: uid("t"),
117
+ now: later
118
+ });
119
+ assert(
120
+ reclaimed.some((row) => row.id === target),
121
+ "expired lease was not reclaimed"
122
+ );
123
+ }
124
+ },
125
+ {
126
+ name: "not_before in the future is never claimed",
127
+ run: async (ctx) => {
128
+ const { rows } = await seed(ctx, { notBefore: new Date(Date.now() + 36e5) });
129
+ const target = rows[0]?.deliveries[0]?.id;
130
+ const claimed = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
131
+ assert(!claimed.some((row) => row.id === target), "claimed a delivery before its not_before");
132
+ }
133
+ },
134
+ {
135
+ name: "attempts at or beyond max_attempts is never claimed",
136
+ run: async (ctx) => {
137
+ const { rows } = await seed(ctx, { maxAttempts: 3 });
138
+ const target = rows[0]?.deliveries[0]?.id;
139
+ assert(target, "seed produced no delivery");
140
+ await ctx.setAttempts(target, 3);
141
+ const claimed = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
142
+ assert(!claimed.some((row) => row.id === target), "claimed an exhausted delivery");
143
+ }
144
+ },
145
+ {
146
+ name: "claims are ordered by not_before ascending",
147
+ run: async (ctx) => {
148
+ const userId = uid("user");
149
+ const older = uid("delivery");
150
+ const newer = uid("delivery");
151
+ await ctx.adapter.createNotifications([
152
+ {
153
+ id: uid("notif"),
154
+ userId,
155
+ type: "t",
156
+ payload: {},
157
+ deliveries: [
158
+ {
159
+ id: newer,
160
+ channel: "email",
161
+ maxAttempts: 5,
162
+ notBefore: new Date(Date.now() - 1e3)
163
+ }
164
+ ]
165
+ },
166
+ {
167
+ id: uid("notif"),
168
+ userId,
169
+ type: "t",
170
+ payload: {},
171
+ deliveries: [
172
+ {
173
+ id: older,
174
+ channel: "email",
175
+ maxAttempts: 5,
176
+ notBefore: new Date(Date.now() - 6e5)
177
+ }
178
+ ]
179
+ }
180
+ ]);
181
+ const claimed = await ctx.adapter.claimPendingDeliveries({
182
+ limit: 1,
183
+ leaseMs: 6e4,
184
+ claimToken: uid("t")
185
+ });
186
+ equal(claimed[0]?.id, older, "oldest eligible delivery was not claimed first");
187
+ }
188
+ },
189
+ {
190
+ name: "release with a stale token still writes the terminal state",
191
+ run: async (ctx) => {
192
+ const { rows } = await seed(ctx);
193
+ const target = rows[0]?.deliveries[0]?.id;
194
+ assert(target, "seed produced no delivery");
195
+ await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("real") });
196
+ await ctx.adapter.releaseDeliveries([
197
+ {
198
+ id: target,
199
+ claimToken: "a-token-that-never-held-this-lease",
200
+ outcome: { result: "sent" }
201
+ }
202
+ ]);
203
+ const stillClaimable = await ctx.adapter.claimPendingDeliveries({
204
+ ...CLAIM,
205
+ claimToken: uid("t"),
206
+ now: new Date(Date.now() + CLAIM.leaseMs + 5e3)
207
+ });
208
+ assert(
209
+ !stillClaimable.some((row) => row.id === target),
210
+ "row stayed claimable after being marked sent"
211
+ );
212
+ }
213
+ },
214
+ {
215
+ name: "retryable failure re-arms; non-retryable fails immediately",
216
+ run: async (ctx) => {
217
+ const retry = await seed(ctx, { maxAttempts: 5 });
218
+ const retryId = retry.rows[0]?.deliveries[0]?.id;
219
+ assert(retryId, "seed produced no delivery");
220
+ await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
221
+ const soon = new Date(Date.now() + 3e4);
222
+ await ctx.adapter.releaseDeliveries([
223
+ {
224
+ id: retryId,
225
+ claimToken: "t",
226
+ outcome: { result: "failed", error: "smtp timeout", retryable: true },
227
+ nextAttemptAt: soon
228
+ }
229
+ ]);
230
+ const tooEarly = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
231
+ assert(
232
+ !tooEarly.some((row) => row.id === retryId),
233
+ "re-armed delivery was claimable before its backoff elapsed"
234
+ );
235
+ const afterBackoff = await ctx.adapter.claimPendingDeliveries({
236
+ ...CLAIM,
237
+ claimToken: uid("t"),
238
+ now: new Date(soon.getTime() + 1e3)
239
+ });
240
+ assert(
241
+ afterBackoff.some((row) => row.id === retryId),
242
+ "re-armed delivery never became claimable"
243
+ );
244
+ const terminal = await seed(ctx, { maxAttempts: 5 });
245
+ const terminalId = terminal.rows[0]?.deliveries[0]?.id;
246
+ assert(terminalId, "seed produced no delivery");
247
+ await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid("t") });
248
+ await ctx.adapter.releaseDeliveries([
249
+ {
250
+ id: terminalId,
251
+ claimToken: "t",
252
+ outcome: { result: "failed", error: "invalid api key", retryable: false }
253
+ }
254
+ ]);
255
+ const failed = await ctx.adapter.getFailedDeliveries({
256
+ since: new Date(Date.now() - 6e4),
257
+ limit: 50
258
+ });
259
+ assert(
260
+ failed.some((row) => row.id === terminalId),
261
+ "non-retryable failure did not land in failed"
262
+ );
263
+ }
264
+ },
265
+ {
266
+ name: "duplicate dedupeKey is skipped, not thrown",
267
+ run: async (ctx) => {
268
+ const userId = uid("user");
269
+ const key = uid("dedupe");
270
+ const first = await seed(ctx, { userId, dedupeKey: key });
271
+ equal(first.result.created.length, 1, "first insert was not created");
272
+ const second = await seed(ctx, { userId, dedupeKey: key });
273
+ equal(second.result.created.length, 0, "duplicate was created");
274
+ equal(second.result.deduped.length, 1, "duplicate was not reported as deduped");
275
+ }
276
+ },
277
+ {
278
+ name: "notifications with no dedupeKey never collide",
279
+ run: async (ctx) => {
280
+ const userId = uid("user");
281
+ const result = await seed(ctx, { userId, count: 3 });
282
+ equal(result.result.created.length, 3, "undeduped notifications collided");
283
+ }
284
+ },
285
+ {
286
+ name: "markRead is scoped to the owning user",
287
+ run: async (ctx) => {
288
+ const owner = uid("user");
289
+ const { rows } = await seed(ctx, { userId: owner });
290
+ const notificationId = rows[0]?.id;
291
+ assert(notificationId, "seed produced no notification");
292
+ const stolen = await ctx.adapter.markRead(uid("attacker"), [notificationId]);
293
+ equal(stolen, 0, "another user marked a notification read");
294
+ const own = await ctx.adapter.markRead(owner, [notificationId]);
295
+ equal(own, 1, "owner could not mark their own notification read");
296
+ }
297
+ },
298
+ {
299
+ name: "unseen count and markSeen agree",
300
+ run: async (ctx) => {
301
+ const userId = uid("user");
302
+ await seed(ctx, { userId, count: 3 });
303
+ equal(await ctx.adapter.countUnseen(userId), 3, "unseen count wrong before markSeen");
304
+ await ctx.adapter.markSeen(userId, /* @__PURE__ */ new Date());
305
+ equal(await ctx.adapter.countUnseen(userId), 0, "unseen count wrong after markSeen");
306
+ }
307
+ },
308
+ {
309
+ /**
310
+ * createdAt must come from the same clock as the cutoff it is compared to.
311
+ *
312
+ * An adapter that leaves createdAt to a database DEFAULT now() is comparing
313
+ * the database clock against the application clock. On one machine they
314
+ * agree and this never fails; in production they are different hosts, and a
315
+ * database a second ahead means markSeen(now) silently misses the newest
316
+ * notifications and the unseen badge never clears. Found when a laptop
317
+ * resumed from sleep with its Docker VM 6s ahead.
318
+ */
319
+ name: "createdAt comes from the caller clock, not the database clock",
320
+ run: async (ctx) => {
321
+ const userId = uid("user");
322
+ const before = /* @__PURE__ */ new Date();
323
+ await seed(ctx, { userId, count: 1 });
324
+ const after = /* @__PURE__ */ new Date();
325
+ const { notifications } = await ctx.adapter.listNotifications({ userId, limit: 10 });
326
+ const createdAt = notifications[0]?.createdAt;
327
+ assert(createdAt, "seed produced no notification");
328
+ const skewMs = Math.max(
329
+ before.getTime() - createdAt.getTime(),
330
+ createdAt.getTime() - after.getTime()
331
+ );
332
+ assert(
333
+ skewMs <= 1e3,
334
+ `createdAt is ${skewMs}ms outside the window the caller observed \u2014 it is coming from another clock`
335
+ );
336
+ }
337
+ }
338
+ ];
339
+
340
+ exports.adapterConformanceCases = adapterConformanceCases;
341
+ //# sourceMappingURL=testing.cjs.map
342
+ //# sourceMappingURL=testing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing/conformance.ts"],"names":[],"mappings":";;;AAsCA,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAC,CAAA;AAEtC,SAAS,MAAA,CAAO,WAAoB,OAAA,EAAoC;AACtE,EAAA,IAAI,CAAC,SAAA,EAAW,MAAM,IAAI,iBAAiB,OAAO,CAAA;AACpD;AAEA,IAAM,QAAQ,CAAC,MAAA,EAAiB,UAAmB,OAAA,KACjD,MAAA,CAAO,WAAW,QAAA,EAAU,CAAA,EAAG,OAAO,CAAA,MAAA,EAAS,OAAO,MAAM,CAAC,cAAc,MAAA,CAAO,QAAQ,CAAC,CAAA,CAAA,CAAG,CAAA;AAEhG,IAAI,OAAA,GAAU,CAAA;AACd,SAAS,IAAI,KAAA,EAAuB;AAClC,EAAA,OAAA,IAAW,CAAA;AACX,EAAA,OAAO,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAA,CAAK,GAAA,GAAM,QAAA,CAAS,EAAE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,CAAA,EAAG,SAAA;AACpC,MAAA,MAAA,CAAO,WAAW,+BAA+B,CAAA;AAIjD,MAAA,MAAM,SAAS,IAAA,CAAK,GAAA;AAAA,QAClB,MAAA,CAAO,OAAA,EAAQ,GAAI,SAAA,CAAU,OAAA,EAAQ;AAAA,QACrC,SAAA,CAAU,OAAA,EAAQ,GAAI,KAAA,CAAM,OAAA;AAAQ,OACtC;AACA,MAAA,MAAA;AAAA,QACE,MAAA,IAAU,GAAA;AAAA,QACV,gBAAgB,MAAM,CAAA,gFAAA;AAAA,OACxB;AAAA,IACF;AAAA;AAEJ","file":"testing.cjs","sourcesContent":["import type { DatabaseAdapter, InsertNotification } from \"../core/adapter\";\nimport type { Channel } from \"../core/types\";\n\nexport type ConformanceContext = {\n adapter: DatabaseAdapter;\n /**\n * Forces a delivery's attempt count. Not reachable through the public API —\n * the adapter would have marked the row failed on the way there — so each\n * backend writes it directly.\n */\n setAttempts: (deliveryId: string, attempts: number) => Promise<void>;\n /**\n * Empties the tables. Cases must run against a clean table: claims are\n * ordered by not_before ASC and bounded by limit, so leftover rows from an\n * earlier case can push the row under test out of the claim window.\n */\n reset: () => Promise<void>;\n /**\n * Holds a row lock on a separate connection for the duration of `fn`.\n *\n * Required to test SKIP LOCKED deterministically. Two Promise.all'd claims\n * do not reliably overlap — they complete in single-digit milliseconds and\n * simply queue — so a race-based test passes even with no locking at all.\n *\n * Only meaningful where a claim can block on someone else's lock. A document\n * store whose claim is a single atomic update has nothing to skip, so cases\n * tagged `rowLock` do not apply to it.\n */\n lockRow?: (deliveryId: string, fn: () => Promise<void>) => Promise<void>;\n};\n\nexport type ConformanceCase = {\n name: string;\n /** Capability the case needs; a backend without it must filter the case out. */\n requires?: \"rowLock\";\n run: (ctx: ConformanceContext) => Promise<void>;\n};\n\nclass ConformanceError extends Error {}\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) throw new ConformanceError(message);\n}\n\nconst equal = (actual: unknown, expected: unknown, message: string) =>\n assert(actual === expected, `${message} (got ${String(actual)}, expected ${String(expected)})`);\n\nlet counter = 0;\nfunction uid(label: string): string {\n counter += 1;\n return `${label}_${Date.now().toString(36)}_${counter}`;\n}\n\ntype SeedOptions = {\n count?: number;\n notBefore?: Date;\n maxAttempts?: number;\n channel?: Channel;\n dedupeKey?: string;\n userId?: string;\n};\n\nasync function seed(ctx: ConformanceContext, options: SeedOptions = {}) {\n const count = options.count ?? 1;\n const userId = options.userId ?? uid(\"user\");\n\n const rows: InsertNotification[] = Array.from({ length: count }, () => {\n const id = uid(\"notif\");\n return {\n id,\n userId,\n type: \"commentReply\",\n payload: { authorName: \"Dana\" },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n deliveries: [\n {\n id: uid(\"delivery\"),\n channel: options.channel ?? \"email\",\n maxAttempts: options.maxAttempts ?? 5,\n notBefore: options.notBefore ?? new Date(Date.now() - 1000),\n },\n ],\n };\n });\n\n const result = await ctx.adapter.createNotifications(rows);\n return { userId, rows, result };\n}\n\nconst CLAIM = { limit: 10, leaseMs: 60_000 };\n\nexport const adapterConformanceCases: readonly ConformanceCase[] = [\n {\n /**\n * The case that actually distinguishes a correct adapter.\n *\n * A row locked by another transaction must be *skipped*, not waited on.\n * Without SKIP LOCKED the claim blocks until the holder commits, which on\n * a busy table serialises every worker behind the slowest one.\n */\n name: \"a row locked by another transaction is skipped, not waited on\",\n requires: \"rowLock\",\n run: async (ctx) => {\n const { lockRow } = ctx;\n assert(lockRow, \"case requires lockRow\");\n\n const { rows } = await seed(ctx, { count: 2 });\n const locked = rows[0]?.deliveries[0]?.id;\n const free = rows[1]?.deliveries[0]?.id;\n assert(locked && free, \"seed produced too few deliveries\");\n\n await lockRow(locked, async () => {\n const claimed = await Promise.race([\n ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"token\") }),\n new Promise<never>((_, reject) =>\n setTimeout(\n () =>\n reject(\n new ConformanceError(\n \"claim blocked on a row locked by another transaction — SKIP LOCKED is missing\",\n ),\n ),\n 2_000,\n ),\n ),\n ]);\n\n const ids = new Set(claimed.map((row) => row.id));\n assert(!ids.has(locked), \"claimed a row locked by another transaction\");\n assert(ids.has(free), \"skipped an unlocked row alongside the locked one\");\n });\n },\n },\n\n {\n name: \"concurrent claims return disjoint sets\",\n run: async (ctx) => {\n await seed(ctx, { count: 40 });\n\n // Eight callers over 40 rows, repeated — a single Promise.all pair is\n // too fast to overlap and proves nothing on its own.\n const claimed = await Promise.all(\n Array.from({ length: 8 }, () =>\n ctx.adapter.claimPendingDeliveries({ limit: 5, leaseMs: 60_000, claimToken: uid(\"t\") }),\n ),\n );\n\n const all = claimed.flatMap((batch) => batch.map((row) => row.id));\n equal(new Set(all).size, all.length, \"the same delivery was claimed by two callers\");\n assert(all.length <= 40, \"claimed more rows than exist\");\n },\n },\n\n {\n name: \"a claimed row is invisible before its lease expires\",\n run: async (ctx) => {\n const { rows } = await seed(ctx);\n const target = rows[0]?.deliveries[0]?.id;\n\n const first = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n assert(\n first.some((row) => row.id === target),\n \"seeded delivery was not claimed\",\n );\n\n const second = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n assert(!second.some((row) => row.id === target), \"leased row was claimed twice\");\n },\n },\n\n {\n name: \"a claimed row is re-claimable after its lease expires\",\n run: async (ctx) => {\n const { rows } = await seed(ctx);\n const target = rows[0]?.deliveries[0]?.id;\n\n await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n\n const later = new Date(Date.now() + CLAIM.leaseMs + 5_000);\n const reclaimed = await ctx.adapter.claimPendingDeliveries({\n ...CLAIM,\n claimToken: uid(\"t\"),\n now: later,\n });\n\n assert(\n reclaimed.some((row) => row.id === target),\n \"expired lease was not reclaimed\",\n );\n },\n },\n\n {\n name: \"not_before in the future is never claimed\",\n run: async (ctx) => {\n const { rows } = await seed(ctx, { notBefore: new Date(Date.now() + 3_600_000) });\n const target = rows[0]?.deliveries[0]?.id;\n\n const claimed = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n assert(!claimed.some((row) => row.id === target), \"claimed a delivery before its not_before\");\n },\n },\n\n {\n name: \"attempts at or beyond max_attempts is never claimed\",\n run: async (ctx) => {\n const { rows } = await seed(ctx, { maxAttempts: 3 });\n const target = rows[0]?.deliveries[0]?.id;\n assert(target, \"seed produced no delivery\");\n\n await ctx.setAttempts(target, 3);\n\n const claimed = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n assert(!claimed.some((row) => row.id === target), \"claimed an exhausted delivery\");\n },\n },\n\n {\n name: \"claims are ordered by not_before ascending\",\n run: async (ctx) => {\n const userId = uid(\"user\");\n const older = uid(\"delivery\");\n const newer = uid(\"delivery\");\n\n await ctx.adapter.createNotifications([\n {\n id: uid(\"notif\"),\n userId,\n type: \"t\",\n payload: {},\n deliveries: [\n {\n id: newer,\n channel: \"email\",\n maxAttempts: 5,\n notBefore: new Date(Date.now() - 1_000),\n },\n ],\n },\n {\n id: uid(\"notif\"),\n userId,\n type: \"t\",\n payload: {},\n deliveries: [\n {\n id: older,\n channel: \"email\",\n maxAttempts: 5,\n notBefore: new Date(Date.now() - 600_000),\n },\n ],\n },\n ]);\n\n const claimed = await ctx.adapter.claimPendingDeliveries({\n limit: 1,\n leaseMs: 60_000,\n claimToken: uid(\"t\"),\n });\n\n equal(claimed[0]?.id, older, \"oldest eligible delivery was not claimed first\");\n },\n },\n\n {\n name: \"release with a stale token still writes the terminal state\",\n run: async (ctx) => {\n const { rows } = await seed(ctx);\n const target = rows[0]?.deliveries[0]?.id;\n assert(target, \"seed produced no delivery\");\n\n await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"real\") });\n\n await ctx.adapter.releaseDeliveries([\n {\n id: target,\n claimToken: \"a-token-that-never-held-this-lease\",\n outcome: { result: \"sent\" },\n },\n ]);\n\n const stillClaimable = await ctx.adapter.claimPendingDeliveries({\n ...CLAIM,\n claimToken: uid(\"t\"),\n now: new Date(Date.now() + CLAIM.leaseMs + 5_000),\n });\n\n assert(\n !stillClaimable.some((row) => row.id === target),\n \"row stayed claimable after being marked sent\",\n );\n },\n },\n\n {\n name: \"retryable failure re-arms; non-retryable fails immediately\",\n run: async (ctx) => {\n const retry = await seed(ctx, { maxAttempts: 5 });\n const retryId = retry.rows[0]?.deliveries[0]?.id;\n assert(retryId, \"seed produced no delivery\");\n\n await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n\n const soon = new Date(Date.now() + 30_000);\n await ctx.adapter.releaseDeliveries([\n {\n id: retryId,\n claimToken: \"t\",\n outcome: { result: \"failed\", error: \"smtp timeout\", retryable: true },\n nextAttemptAt: soon,\n },\n ]);\n\n const tooEarly = await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n assert(\n !tooEarly.some((row) => row.id === retryId),\n \"re-armed delivery was claimable before its backoff elapsed\",\n );\n\n const afterBackoff = await ctx.adapter.claimPendingDeliveries({\n ...CLAIM,\n claimToken: uid(\"t\"),\n now: new Date(soon.getTime() + 1_000),\n });\n assert(\n afterBackoff.some((row) => row.id === retryId),\n \"re-armed delivery never became claimable\",\n );\n\n const terminal = await seed(ctx, { maxAttempts: 5 });\n const terminalId = terminal.rows[0]?.deliveries[0]?.id;\n assert(terminalId, \"seed produced no delivery\");\n\n await ctx.adapter.claimPendingDeliveries({ ...CLAIM, claimToken: uid(\"t\") });\n await ctx.adapter.releaseDeliveries([\n {\n id: terminalId,\n claimToken: \"t\",\n outcome: { result: \"failed\", error: \"invalid api key\", retryable: false },\n },\n ]);\n\n const failed = await ctx.adapter.getFailedDeliveries({\n since: new Date(Date.now() - 60_000),\n limit: 50,\n });\n assert(\n failed.some((row) => row.id === terminalId),\n \"non-retryable failure did not land in failed\",\n );\n },\n },\n\n {\n name: \"duplicate dedupeKey is skipped, not thrown\",\n run: async (ctx) => {\n const userId = uid(\"user\");\n const key = uid(\"dedupe\");\n\n const first = await seed(ctx, { userId, dedupeKey: key });\n equal(first.result.created.length, 1, \"first insert was not created\");\n\n const second = await seed(ctx, { userId, dedupeKey: key });\n equal(second.result.created.length, 0, \"duplicate was created\");\n equal(second.result.deduped.length, 1, \"duplicate was not reported as deduped\");\n },\n },\n\n {\n name: \"notifications with no dedupeKey never collide\",\n run: async (ctx) => {\n const userId = uid(\"user\");\n const result = await seed(ctx, { userId, count: 3 });\n equal(result.result.created.length, 3, \"undeduped notifications collided\");\n },\n },\n\n {\n name: \"markRead is scoped to the owning user\",\n run: async (ctx) => {\n const owner = uid(\"user\");\n const { rows } = await seed(ctx, { userId: owner });\n const notificationId = rows[0]?.id;\n assert(notificationId, \"seed produced no notification\");\n\n const stolen = await ctx.adapter.markRead(uid(\"attacker\"), [notificationId]);\n equal(stolen, 0, \"another user marked a notification read\");\n\n const own = await ctx.adapter.markRead(owner, [notificationId]);\n equal(own, 1, \"owner could not mark their own notification read\");\n },\n },\n\n {\n name: \"unseen count and markSeen agree\",\n run: async (ctx) => {\n const userId = uid(\"user\");\n await seed(ctx, { userId, count: 3 });\n\n equal(await ctx.adapter.countUnseen(userId), 3, \"unseen count wrong before markSeen\");\n\n await ctx.adapter.markSeen(userId, new Date());\n equal(await ctx.adapter.countUnseen(userId), 0, \"unseen count wrong after markSeen\");\n },\n },\n\n {\n /**\n * createdAt must come from the same clock as the cutoff it is compared to.\n *\n * An adapter that leaves createdAt to a database DEFAULT now() is comparing\n * the database clock against the application clock. On one machine they\n * agree and this never fails; in production they are different hosts, and a\n * database a second ahead means markSeen(now) silently misses the newest\n * notifications and the unseen badge never clears. Found when a laptop\n * resumed from sleep with its Docker VM 6s ahead.\n */\n name: \"createdAt comes from the caller clock, not the database clock\",\n run: async (ctx) => {\n const userId = uid(\"user\");\n const before = new Date();\n await seed(ctx, { userId, count: 1 });\n const after = new Date();\n\n const { notifications } = await ctx.adapter.listNotifications({ userId, limit: 10 });\n const createdAt = notifications[0]?.createdAt;\n assert(createdAt, \"seed produced no notification\");\n\n // A second of slack for a slow round trip, far under the skew that breaks\n // markSeen but tight enough to catch a foreign clock.\n const skewMs = Math.max(\n before.getTime() - createdAt.getTime(),\n createdAt.getTime() - after.getTime(),\n );\n assert(\n skewMs <= 1_000,\n `createdAt is ${skewMs}ms outside the window the caller observed — it is coming from another clock`,\n );\n },\n },\n];\n"]}