@drfed/models 0.0.0-stage → 0.1.0-dev.554

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 (132) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +230 -2
  3. package/dist/activity-delivery.d.mts +111 -0
  4. package/dist/activity-delivery.d.mts.map +1 -0
  5. package/dist/activity-delivery.mjs +240 -0
  6. package/dist/activity-delivery.mjs.map +1 -0
  7. package/dist/db-DtcLuISw.d.mts +3098 -0
  8. package/dist/db-DtcLuISw.d.mts.map +1 -0
  9. package/dist/db.d.mts +2 -0
  10. package/dist/db.mjs +3 -0
  11. package/dist/email.d.mts +39 -0
  12. package/dist/email.d.mts.map +1 -0
  13. package/dist/email.mjs +12 -0
  14. package/dist/email.mjs.map +1 -0
  15. package/dist/index.d.mts +14 -0
  16. package/dist/index.mjs +18 -0
  17. package/dist/instance.d.mts +11 -0
  18. package/dist/instance.d.mts.map +1 -0
  19. package/dist/instance.mjs +21 -0
  20. package/dist/instance.mjs.map +1 -0
  21. package/dist/key.d.mts +2 -0
  22. package/dist/key.mjs +86 -0
  23. package/dist/key.mjs.map +1 -0
  24. package/dist/login.d.mts +49 -0
  25. package/dist/login.d.mts.map +1 -0
  26. package/dist/login.mjs +71 -0
  27. package/dist/login.mjs.map +1 -0
  28. package/dist/migrate.d.mts +46 -0
  29. package/dist/migrate.d.mts.map +1 -0
  30. package/dist/migrate.mjs +58 -0
  31. package/dist/migrate.mjs.map +1 -0
  32. package/dist/migration-manifest.d.mts +39 -0
  33. package/dist/migration-manifest.d.mts.map +1 -0
  34. package/dist/migration-manifest.mjs +77 -0
  35. package/dist/migration-manifest.mjs.map +1 -0
  36. package/dist/migration-session-B4xHeU_a.d.mts +56 -0
  37. package/dist/migration-session-B4xHeU_a.d.mts.map +1 -0
  38. package/dist/migration-session.d.mts +2 -0
  39. package/dist/migration-session.mjs +204 -0
  40. package/dist/migration-session.mjs.map +1 -0
  41. package/dist/migration-snapshot-OM5jQN1-.mjs +69 -0
  42. package/dist/migration-snapshot-OM5jQN1-.mjs.map +1 -0
  43. package/dist/migration-state.d.mts +41 -0
  44. package/dist/migration-state.d.mts.map +1 -0
  45. package/dist/migration-state.mjs +155 -0
  46. package/dist/migration-state.mjs.map +1 -0
  47. package/dist/migrations-manifest.json +109 -0
  48. package/dist/pglite-preparation.d.mts +23 -0
  49. package/dist/pglite-preparation.d.mts.map +1 -0
  50. package/dist/pglite-preparation.mjs +77 -0
  51. package/dist/pglite-preparation.mjs.map +1 -0
  52. package/dist/pglite-store.d.mts +29 -0
  53. package/dist/pglite-store.d.mts.map +1 -0
  54. package/dist/pglite-store.mjs +117 -0
  55. package/dist/pglite-store.mjs.map +1 -0
  56. package/dist/relations.d.mts +2 -0
  57. package/dist/relations.mjs +307 -0
  58. package/dist/relations.mjs.map +1 -0
  59. package/dist/resource.d.mts +50 -0
  60. package/dist/resource.d.mts.map +1 -0
  61. package/dist/resource.mjs +123 -0
  62. package/dist/resource.mjs.map +1 -0
  63. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  64. package/dist/schema.d.mts +2 -0
  65. package/dist/schema.mjs +495 -0
  66. package/dist/schema.mjs.map +1 -0
  67. package/dist/slug.d.mts +28 -0
  68. package/dist/slug.d.mts.map +1 -0
  69. package/dist/slug.mjs +55 -0
  70. package/dist/slug.mjs.map +1 -0
  71. package/dist/text.d.mts +10 -0
  72. package/dist/text.d.mts.map +1 -0
  73. package/dist/text.mjs +11 -0
  74. package/dist/text.mjs.map +1 -0
  75. package/dist/uuid-CKMzlIND.d.mts +26 -0
  76. package/dist/uuid-CKMzlIND.d.mts.map +1 -0
  77. package/dist/uuid.d.mts +2 -0
  78. package/dist/uuid.mjs +28 -0
  79. package/dist/uuid.mjs.map +1 -0
  80. package/drizzle/20260622021748_init/migration.sql +25 -0
  81. package/drizzle/20260622021748_init/snapshot.json +246 -0
  82. package/drizzle/20260623162238_dear_felicia_hardy/migration.sql +5 -0
  83. package/drizzle/20260623162238_dear_felicia_hardy/snapshot.json +321 -0
  84. package/drizzle/20260624094817_lethal_sinister_six/migration.sql +2 -0
  85. package/drizzle/20260624094817_lethal_sinister_six/snapshot.json +347 -0
  86. package/drizzle/20260716000333_email_auth/migration.sql +20 -0
  87. package/drizzle/20260716000333_email_auth/snapshot.json +575 -0
  88. package/drizzle/20260723065002_chief_colleen_wing/migration.sql +2 -0
  89. package/drizzle/20260723065002_chief_colleen_wing/snapshot.json +595 -0
  90. package/drizzle/20260802205417_separate-instance-local-remote/migration.sql +26 -0
  91. package/drizzle/20260802205417_separate-instance-local-remote/snapshot.json +768 -0
  92. package/drizzle/20260804061119_instances-local-remote-constraint/migration.sql +7 -0
  93. package/drizzle/20260804061119_instances-local-remote-constraint/snapshot.json +843 -0
  94. package/drizzle/20260818080259_dark_night_thrasher/migration.sql +15 -0
  95. package/drizzle/20260818080259_dark_night_thrasher/snapshot.json +722 -0
  96. package/drizzle/20260821072150_merge_remote_actors/migration.sql +54 -0
  97. package/drizzle/20260821072150_merge_remote_actors/snapshot.json +1312 -0
  98. package/drizzle/20260906052949_rename_followees_to_following/migration.sql +2 -0
  99. package/drizzle/20260906052949_rename_followees_to_following/snapshot.json +1315 -0
  100. package/drizzle/20260908062446_rename_login_tokens_to_login_challenges/migration.sql +1 -0
  101. package/drizzle/20260908062446_rename_login_tokens_to_login_challenges/snapshot.json +1312 -0
  102. package/drizzle/20260908065945_simplify_login_challenges/migration.sql +7 -0
  103. package/drizzle/20260908065945_simplify_login_challenges/snapshot.json +1290 -0
  104. package/drizzle/20260915061356_tighten_slug_constraint/migration.sql +12 -0
  105. package/drizzle/20260915061356_tighten_slug_constraint/snapshot.json +1290 -0
  106. package/drizzle/20260915063339_widen_instance_host/migration.sql +1 -0
  107. package/drizzle/20260915063339_widen_instance_host/snapshot.json +1290 -0
  108. package/drizzle/20260916085902_add_objects_activities_and_resources/migration.sql +110 -0
  109. package/drizzle/20260916085902_add_objects_activities_and_resources/snapshot.json +2263 -0
  110. package/drizzle/20260917163517_order_local_outbox_items/migration.sql +22 -0
  111. package/drizzle/20260917163517_order_local_outbox_items/snapshot.json +2263 -0
  112. package/drizzle/20260918071839_add_activity_object_index/migration.sql +1 -0
  113. package/drizzle/20260918071839_add_activity_object_index/snapshot.json +2298 -0
  114. package/drizzle/20261006061745_add_activity_deliveries_and_keys/migration.sql +106 -0
  115. package/drizzle/20261006061745_add_activity_deliveries_and_keys/snapshot.json +3538 -0
  116. package/drizzle/20261006085045_snake_case_columns/migration.sql +42 -0
  117. package/drizzle/20261006085045_snake_case_columns/snapshot.json +3570 -0
  118. package/drizzle/20261006122653_local_actor_keys/migration.sql +11 -0
  119. package/drizzle/20261006122653_local_actor_keys/snapshot.json +3627 -0
  120. package/drizzle/20261010044954_link_activity_deliveries_to_activities/migration.sql +8 -0
  121. package/drizzle/20261010044954_link_activity_deliveries_to_activities/snapshot.json +3714 -0
  122. package/drizzle/20261010073134_check_inbound_activity_link/migration.sql +1 -0
  123. package/drizzle/20261010073134_check_inbound_activity_link/snapshot.json +3721 -0
  124. package/drizzle/20261010104304_record_object_activity/migration.sql +3 -0
  125. package/drizzle/20261010104304_record_object_activity/snapshot.json +3756 -0
  126. package/drizzle/20261010111648_record_delivery_snapshot/migration.sql +29 -0
  127. package/drizzle/20261010111648_record_delivery_snapshot/snapshot.json +3769 -0
  128. package/drizzle/20261011144453_record_object_snapshot/migration.sql +10 -0
  129. package/drizzle/20261011144453_record_object_snapshot/snapshot.json +3808 -0
  130. package/drizzle/20261011192718_record_actor_followers/migration.sql +1 -0
  131. package/drizzle/20261011192718_record_actor_followers/snapshot.json +3821 -0
  132. package/package.json +193 -3
@@ -0,0 +1,155 @@
1
+ import { t as schema_exports } from "./schema.mjs";
2
+ import { migrationTimestamp, parseMigrationManifest, verifyMigrationManifest } from "./migration-manifest.mjs";
3
+ import { is } from "drizzle-orm";
4
+ import { PgTable, getTableConfig } from "drizzle-orm/pg-core";
5
+ import { Buffer } from "node:buffer";
6
+ //#region src/migration-state.ts
7
+ function integer$1(value) {
8
+ const parsed = typeof value === "number" ? value : typeof value === "bigint" || typeof value === "string" && /^\d+$/u.test(value) ? Number(value) : NaN;
9
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
10
+ }
11
+ function historyIdentity(row, format) {
12
+ const id = integer$1(row.id);
13
+ const rawDate = integer$1(row.created_at);
14
+ if (id === void 0 || rawDate === void 0 || typeof row.hash !== "string" || !/^[a-f0-9]{64}$/u.test(row.hash)) return;
15
+ const date = format === "legacy" || row.applied_at === null ? Math.floor(rawDate / 1e3) * 1e3 : rawDate;
16
+ if (format === "current") {
17
+ if (typeof row.name !== "string") return;
18
+ try {
19
+ if (migrationTimestamp(row.name) !== date) return;
20
+ } catch {
21
+ return;
22
+ }
23
+ }
24
+ return {
25
+ id,
26
+ date,
27
+ hash: row.hash,
28
+ name: row.name
29
+ };
30
+ }
31
+ /**
32
+ * Compare ordered raw history rows with the immutable manifest, without SQL.
33
+ * Legacy and metadata-upgraded legacy dates may retain generation milliseconds.
34
+ * Both second and hash
35
+ * must match the corresponding prefix entry before metadata can be upgraded.
36
+ * @returns The compatibility state; invalid histories never list pending SQL.
37
+ */
38
+ function classifyMigrationHistory(manifest, rows, format) {
39
+ const identities = parseMigrationManifest(manifest).migrations;
40
+ const incompatible = (status) => ({
41
+ status,
42
+ format,
43
+ applied: 0,
44
+ pending: []
45
+ });
46
+ let previousId = 0;
47
+ let previousDate = -1;
48
+ let newer = false;
49
+ for (const [index, row] of rows.entries()) {
50
+ const identity = historyIdentity(row, format);
51
+ if (!identity || identity.id <= previousId || identity.date <= previousDate) return incompatible("diverged");
52
+ const { id, date, hash, name } = identity;
53
+ previousId = id;
54
+ previousDate = date;
55
+ const expected = identities[index];
56
+ if (expected === void 0) {
57
+ const last = identities.at(-1);
58
+ if (last === void 0 || date <= migrationTimestamp(last.name)) return incompatible("diverged");
59
+ newer = true;
60
+ continue;
61
+ }
62
+ if (date !== migrationTimestamp(expected.name) || format === "current" && name !== expected.name) return incompatible("diverged");
63
+ if (hash !== expected.sha256) return incompatible("modified");
64
+ }
65
+ if (newer) return incompatible("newer");
66
+ return {
67
+ status: format === "legacy" ? "upgrade-required" : rows.length === 0 ? "uninitialized" : rows.length === identities.length ? "ready" : "pending",
68
+ format,
69
+ applied: rows.length,
70
+ pending: identities.slice(rows.length)
71
+ };
72
+ }
73
+ function identifier(value) {
74
+ if (value === "" || value.includes("\0") || Buffer.byteLength(value, "utf8") > 63) throw new Error("Invalid migration history identifier.");
75
+ return `"${value.replaceAll("\"", "\"\"")}"`;
76
+ }
77
+ const businessTables = [
78
+ ...Object.values(schema_exports).filter((value) => is(value, PgTable)).map((table) => {
79
+ const config = getTableConfig(table);
80
+ return {
81
+ name: config.name,
82
+ schema: config.schema ?? "public"
83
+ };
84
+ }),
85
+ {
86
+ name: "login_tokens",
87
+ schema: "public"
88
+ },
89
+ {
90
+ name: "remote_instances",
91
+ schema: "public"
92
+ }
93
+ ];
94
+ async function hasBusinessTables(client) {
95
+ const namespaces = [...new Set(businessTables.map((table) => table.schema))];
96
+ return (await Promise.all(namespaces.map((namespace) => {
97
+ const names = businessTables.filter((table) => table.schema === namespace).map((table) => table.name);
98
+ return client.query(`SELECT c.relname FROM pg_catalog.pg_class c
99
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
100
+ WHERE n.nspname = $1 AND c.relname = ANY($2::text[])`, [namespace, names]);
101
+ }))).some((result) => result.rows.length > 0);
102
+ }
103
+ /**
104
+ * Inspect migration catalogs and history using SELECT statements only.
105
+ * Missing/empty history with DrFed tables fails closed; metadata and permission
106
+ * errors propagate instead of being mistaken for an empty database.
107
+ * @returns A compatibility state without modifying the database or the client.
108
+ */
109
+ async function inspectMigrationState(client, options = {}) {
110
+ const manifest = options.manifest === void 0 ? await verifyMigrationManifest() : parseMigrationManifest(options.manifest);
111
+ const namespace = options.migrationsSchema ?? "drizzle";
112
+ const table = options.migrationsTable ?? "__drizzle_migrations";
113
+ const qualified = `${identifier(namespace)}.${identifier(table)}`;
114
+ const relation = await client.query(`SELECT c.oid::text AS oid, c.relkind,
115
+ CASE WHEN c.relkind IN ('r', 'p') THEN pg_catalog.row_security_active(c.oid)
116
+ ELSE false END AS row_security_active
117
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
118
+ WHERE n.nspname = $1 AND c.relname = $2`, [namespace, table]);
119
+ const missing = async () => {
120
+ const untracked = await hasBusinessTables(client);
121
+ return {
122
+ status: untracked ? "untracked-schema" : "uninitialized",
123
+ format: null,
124
+ applied: 0,
125
+ pending: untracked ? [] : manifest.migrations
126
+ };
127
+ };
128
+ if (relation.rows.length === 0) return missing();
129
+ const record = relation.rows[0];
130
+ const unsupported = () => ({
131
+ status: "unsupported-format",
132
+ format: null,
133
+ applied: 0,
134
+ pending: []
135
+ });
136
+ if (relation.rows.length !== 1 || !record || record.row_security_active !== false || !["r", "p"].includes(String(record.relkind))) return unsupported();
137
+ const actual = (await client.query(`SELECT a.attname, a.atttypid::text AS type
138
+ FROM pg_catalog.pg_attribute a WHERE a.attrelid = $1::oid
139
+ AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`, [record.oid])).rows.map((column) => `${column.attname}:${column.type}`).sort().join(",");
140
+ const format = actual === "applied_at:1184,created_at:20,hash:25,id:23,name:25" ? "current" : actual === "created_at:20,hash:25,id:23" ? "legacy" : void 0;
141
+ if (format === void 0) return unsupported();
142
+ const result = await client.query(`SELECT id, hash, created_at${format === "current" ? ", name, applied_at" : ""}
143
+ FROM ${qualified} ORDER BY created_at, id`);
144
+ if (result.rows.length === 0 && await hasBusinessTables(client)) return {
145
+ status: "untracked-schema",
146
+ format,
147
+ applied: 0,
148
+ pending: []
149
+ };
150
+ return classifyMigrationHistory(manifest, result.rows, format);
151
+ }
152
+ //#endregion
153
+ export { classifyMigrationHistory, inspectMigrationState };
154
+
155
+ //# sourceMappingURL=migration-state.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-state.mjs","names":["integer","schema"],"sources":["../src/migration-state.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport { Buffer } from \"node:buffer\";\n\nimport { is } from \"drizzle-orm\";\nimport { PgTable, getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport {\n type MigrationIdentity,\n type MigrationManifest,\n migrationTimestamp,\n parseMigrationManifest,\n verifyMigrationManifest,\n} from \"./migration-manifest.ts\";\nimport * as schema from \"./schema.ts\";\n\n/** A query-only client; the caller owns its connection and lifetime. */\nexport interface MigrationQueryClient {\n query<Row extends Record<string, unknown>>(\n sql: string,\n parameters?: unknown[],\n ): Promise<{ rows: Row[] }>;\n}\n\nexport type MigrationHistoryFormat = \"current\" | \"legacy\";\nexport type MigrationStatus =\n | \"ready\"\n | \"pending\"\n | \"uninitialized\"\n | \"upgrade-required\"\n | \"modified\"\n | \"newer\"\n | \"diverged\"\n | \"untracked-schema\"\n | \"unsupported-format\";\n\n/** Only ready permits startup without applying or upgrading migrations. */\nexport interface MigrationState {\n readonly status: MigrationStatus;\n readonly format: MigrationHistoryFormat | null;\n readonly applied: number;\n readonly pending: readonly MigrationIdentity[];\n}\n\nexport interface InspectMigrationStateOptions {\n readonly migrationsSchema?: string;\n readonly migrationsTable?: string;\n /** A trusted explicit identity set; otherwise verify the installed SQL. */\n readonly manifest?: MigrationManifest;\n}\n\nfunction integer(value: unknown): number | undefined {\n const parsed =\n typeof value === \"number\"\n ? value\n : typeof value === \"bigint\" ||\n (typeof value === \"string\" && /^\\d+$/u.test(value))\n ? Number(value)\n : NaN;\n return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction historyIdentity(\n row: Record<string, unknown>,\n format: MigrationHistoryFormat,\n): { id: number; date: number; hash: string; name: unknown } | undefined {\n const id = integer(row.id);\n const rawDate = integer(row.created_at);\n if (\n id === undefined ||\n rawDate === undefined ||\n typeof row.hash !== \"string\" ||\n !/^[a-f0-9]{64}$/u.test(row.hash)\n ) {\n return undefined;\n }\n // Drizzle marks metadata-upgraded legacy rows with applied_at SQL NULL.\n const legacyDate = format === \"legacy\" || row.applied_at === null;\n const date = legacyDate ? Math.floor(rawDate / 1000) * 1000 : rawDate;\n if (format === \"current\") {\n if (typeof row.name !== \"string\") {\n return undefined;\n }\n try {\n if (migrationTimestamp(row.name) !== date) {\n return undefined;\n }\n } catch {\n return undefined;\n }\n }\n return { id, date, hash: row.hash, name: row.name };\n}\n\n/**\n * Compare ordered raw history rows with the immutable manifest, without SQL.\n * Legacy and metadata-upgraded legacy dates may retain generation milliseconds.\n * Both second and hash\n * must match the corresponding prefix entry before metadata can be upgraded.\n * @returns The compatibility state; invalid histories never list pending SQL.\n */\nexport function classifyMigrationHistory(\n manifest: MigrationManifest,\n rows: readonly Record<string, unknown>[],\n format: MigrationHistoryFormat,\n): MigrationState {\n const identities = parseMigrationManifest(manifest).migrations;\n const incompatible = (status: MigrationStatus): MigrationState => ({\n status,\n format,\n applied: 0,\n pending: [],\n });\n let previousId = 0;\n let previousDate = -1;\n let newer = false;\n for (const [index, row] of rows.entries()) {\n const identity = historyIdentity(row, format);\n if (\n !identity ||\n identity.id <= previousId ||\n identity.date <= previousDate\n ) {\n return incompatible(\"diverged\");\n }\n const { id, date, hash, name } = identity;\n previousId = id;\n previousDate = date;\n const expected = identities[index];\n if (expected === undefined) {\n const last = identities.at(-1);\n if (last === undefined || date <= migrationTimestamp(last.name)) {\n return incompatible(\"diverged\");\n }\n newer = true;\n continue;\n }\n if (\n date !== migrationTimestamp(expected.name) ||\n (format === \"current\" && name !== expected.name)\n ) {\n return incompatible(\"diverged\");\n }\n if (hash !== expected.sha256) {\n return incompatible(\"modified\");\n }\n }\n if (newer) {\n return incompatible(\"newer\");\n }\n return {\n status:\n format === \"legacy\"\n ? \"upgrade-required\"\n : rows.length === 0\n ? \"uninitialized\"\n : rows.length === identities.length\n ? \"ready\"\n : \"pending\",\n format,\n applied: rows.length,\n pending: identities.slice(rows.length),\n };\n}\n\nfunction identifier(value: string): string {\n if (\n value === \"\" ||\n value.includes(\"\\0\") ||\n Buffer.byteLength(value, \"utf8\") > 63\n ) {\n throw new Error(\"Invalid migration history identifier.\");\n }\n return `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\n// Retired names still identify a partially removed historical DrFed schema.\nconst businessTables = [\n ...Object.values(schema)\n .filter((value) => is(value, PgTable))\n .map((table) => {\n const config = getTableConfig(table);\n return { name: config.name, schema: config.schema ?? \"public\" };\n }),\n { name: \"login_tokens\", schema: \"public\" },\n { name: \"remote_instances\", schema: \"public\" },\n];\n\nasync function hasBusinessTables(\n client: MigrationQueryClient,\n): Promise<boolean> {\n const namespaces = [...new Set(businessTables.map((table) => table.schema))];\n const results = await Promise.all(\n namespaces.map((namespace) => {\n const names = businessTables\n .filter((table) => table.schema === namespace)\n .map((table) => table.name);\n return client.query(\n `SELECT c.relname FROM pg_catalog.pg_class c\n JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relname = ANY($2::text[])`,\n [namespace, names],\n );\n }),\n );\n return results.some((result) => result.rows.length > 0);\n}\n\n/**\n * Inspect migration catalogs and history using SELECT statements only.\n * Missing/empty history with DrFed tables fails closed; metadata and permission\n * errors propagate instead of being mistaken for an empty database.\n * @returns A compatibility state without modifying the database or the client.\n */\nexport async function inspectMigrationState(\n client: MigrationQueryClient,\n options: InspectMigrationStateOptions = {},\n): Promise<MigrationState> {\n const manifest =\n options.manifest === undefined\n ? await verifyMigrationManifest()\n : parseMigrationManifest(options.manifest);\n const namespace = options.migrationsSchema ?? \"drizzle\";\n const table = options.migrationsTable ?? \"__drizzle_migrations\";\n const qualified = `${identifier(namespace)}.${identifier(table)}`;\n const relation = await client.query(\n `SELECT c.oid::text AS oid, c.relkind,\n CASE WHEN c.relkind IN ('r', 'p') THEN pg_catalog.row_security_active(c.oid)\n ELSE false END AS row_security_active\n FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relname = $2`,\n [namespace, table],\n );\n const missing = async (): Promise<MigrationState> => {\n const untracked = await hasBusinessTables(client);\n return {\n status: untracked ? \"untracked-schema\" : \"uninitialized\",\n format: null,\n applied: 0,\n pending: untracked ? [] : manifest.migrations,\n };\n };\n if (relation.rows.length === 0) {\n return missing();\n }\n const record = relation.rows[0];\n const unsupported = (): MigrationState => ({\n status: \"unsupported-format\",\n format: null,\n applied: 0,\n pending: [],\n });\n if (\n relation.rows.length !== 1 ||\n !record ||\n record.row_security_active !== false ||\n ![\"r\", \"p\"].includes(String(record.relkind))\n ) {\n return unsupported();\n }\n const columns = await client.query(\n `SELECT a.attname, a.atttypid::text AS type\n FROM pg_catalog.pg_attribute a WHERE a.attrelid = $1::oid\n AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`,\n [record.oid],\n );\n const actual = columns.rows\n .map((column) => `${column.attname}:${column.type}`)\n .sort()\n .join(\",\");\n const legacy = \"created_at:20,hash:25,id:23\";\n const current = \"applied_at:1184,created_at:20,hash:25,id:23,name:25\";\n const format =\n actual === current ? \"current\" : actual === legacy ? \"legacy\" : undefined;\n if (format === undefined) {\n return unsupported();\n }\n const result =\n await client.query(`SELECT id, hash, created_at${format === \"current\" ? \", name, applied_at\" : \"\"}\n FROM ${qualified} ORDER BY created_at, id`);\n if (result.rows.length === 0 && (await hasBusinessTables(client))) {\n return { status: \"untracked-schema\", format, applied: 0, pending: [] };\n }\n return classifyMigrationHistory(manifest, result.rows, format);\n}\n"],"mappings":";;;;;;AAgEA,SAASA,UAAQ,OAAoC;CACnD,MAAM,SACJ,OAAO,UAAU,WACb,QACA,OAAO,UAAU,YACd,OAAO,UAAU,YAAY,SAAS,KAAK,KAAK,IACjD,OAAO,KAAK,IACZ;CACR,OAAO,OAAO,cAAc,MAAM,KAAK,UAAU,IAAI,SAAS,KAAA;AAChE;AAEA,SAAS,gBACP,KACA,QACuE;CACvE,MAAM,KAAKA,UAAQ,IAAI,EAAE;CACzB,MAAM,UAAUA,UAAQ,IAAI,UAAU;CACtC,IACE,OAAO,KAAA,KACP,YAAY,KAAA,KACZ,OAAO,IAAI,SAAS,YACpB,CAAC,kBAAkB,KAAK,IAAI,IAAI,GAEhC;CAIF,MAAM,OADa,WAAW,YAAY,IAAI,eAAe,OACnC,KAAK,MAAM,UAAU,GAAI,IAAI,MAAO;CAC9D,IAAI,WAAW,WAAW;EACxB,IAAI,OAAO,IAAI,SAAS,UACtB;EAEF,IAAI;GACF,IAAI,mBAAmB,IAAI,IAAI,MAAM,MACnC;EAEJ,QAAQ;GACN;EACF;CACF;CACA,OAAO;EAAE;EAAI;EAAM,MAAM,IAAI;EAAM,MAAM,IAAI;CAAK;AACpD;;;;;;;;AASA,SAAgB,yBACd,UACA,MACA,QACgB;CAChB,MAAM,aAAa,uBAAuB,QAAQ,CAAC,CAAC;CACpD,MAAM,gBAAgB,YAA6C;EACjE;EACA;EACA,SAAS;EACT,SAAS,CAAC;CACZ;CACA,IAAI,aAAa;CACjB,IAAI,eAAe;CACnB,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,OAAO,QAAQ,KAAK,QAAQ,GAAG;EACzC,MAAM,WAAW,gBAAgB,KAAK,MAAM;EAC5C,IACE,CAAC,YACD,SAAS,MAAM,cACf,SAAS,QAAQ,cAEjB,OAAO,aAAa,UAAU;EAEhC,MAAM,EAAE,IAAI,MAAM,MAAM,SAAS;EACj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AW,wDAAU,YAAY,WAAW,gCAAS,WAAW,KAAA;CAClE,IAAI,WAAW,KAAA,GACb,OAAO,YAAY;CAErB,MAAM,SACJ,MAAM,OAAO,MAAM,8BAA8B,WAAW,YAAY,uBAAuB,GAAG;WAC3F,UAAU,yBAAyB;CAC5C,IAAI,OAAO,KAAK,WAAW,KAAM,MAAM,kBAAkB,MAAM,GAC7D,OAAO;EAAE,QAAQ;EAAoB;EAAQ,SAAS;EAAG,SAAS,CAAC;CAAE;CAEvE,OAAO,yBAAyB,UAAU,OAAO,MAAM,MAAM;AAC/D"}
@@ -0,0 +1,109 @@
1
+ {
2
+ "formatVersion": 1,
3
+ "migrations": [
4
+ {
5
+ "name": "20260622021748_init",
6
+ "sha256": "c53c69f3b81ab5c5b862b142101fcfb6e8388aafa238b617e94f158a14ec1b8d"
7
+ },
8
+ {
9
+ "name": "20260623162238_dear_felicia_hardy",
10
+ "sha256": "06694a869f5eb31a423eec5cf8544a12c5a00bb9305e7abad7798be118679398"
11
+ },
12
+ {
13
+ "name": "20260624094817_lethal_sinister_six",
14
+ "sha256": "0cb8f1727da4bae40f068928263eb937376fd59109322127c09a15c3e00c1aac"
15
+ },
16
+ {
17
+ "name": "20260716000333_email_auth",
18
+ "sha256": "5faf2d37d92576c15721581c3833afe15fd24111190af029f218ef099e987688"
19
+ },
20
+ {
21
+ "name": "20260723065002_chief_colleen_wing",
22
+ "sha256": "e9b0349b322cc70eedc65f4771185b70c0a9878de6955f36981d3a7679364bf8"
23
+ },
24
+ {
25
+ "name": "20260802205417_separate-instance-local-remote",
26
+ "sha256": "8221217046d163cb9a863f0fa7889a77fe374ea15d8e1e53a99a90de76324bfc"
27
+ },
28
+ {
29
+ "name": "20260804061119_instances-local-remote-constraint",
30
+ "sha256": "14e73ae74c623f1a940aa0a0ddc9126514008583674a91c295bc1bfb2d93f223"
31
+ },
32
+ {
33
+ "name": "20260818080259_dark_night_thrasher",
34
+ "sha256": "48af5f9cfce3a328035b4b8c9eb39f39df987208c2947e64223f61fbc862539e"
35
+ },
36
+ {
37
+ "name": "20260821072150_merge_remote_actors",
38
+ "sha256": "db962e0bc90f64d40d90e90be2debbe8ad73b439db7ea4ea05815b3d95bfbf21"
39
+ },
40
+ {
41
+ "name": "20260906052949_rename_followees_to_following",
42
+ "sha256": "4f387d028ef48882be0fd8c44cb21e334e046891079ddc7d4e2da791479eeb6e"
43
+ },
44
+ {
45
+ "name": "20260908062446_rename_login_tokens_to_login_challenges",
46
+ "sha256": "9386fb9587a9640925c9da2cfcbc1d5afe2f142a6514a463c71066b7079564d9"
47
+ },
48
+ {
49
+ "name": "20260908065945_simplify_login_challenges",
50
+ "sha256": "aa3d935918a64ead17dae7c0d7330dd7677b9a2418d5220641fed1840dc47123"
51
+ },
52
+ {
53
+ "name": "20260915061356_tighten_slug_constraint",
54
+ "sha256": "8ed9c8c2d7cb7029d5f452df75c7cda7c81713af6fa746bd9568e8134f40a284"
55
+ },
56
+ {
57
+ "name": "20260915063339_widen_instance_host",
58
+ "sha256": "b390e154c8f6f8ee1789f73e775d5cbcad0d951841ab8a9ebef979ba400d37c6"
59
+ },
60
+ {
61
+ "name": "20260916085902_add_objects_activities_and_resources",
62
+ "sha256": "51219ac09c7f483fe95ac2dc0a07e6ad0beb5497503f8ffa2b0afa9d04fba01b"
63
+ },
64
+ {
65
+ "name": "20260917163517_order_local_outbox_items",
66
+ "sha256": "84a20b15ca7579e3c94d05e07c06a6311b2ffea45ec7674c2631b216d41d964b"
67
+ },
68
+ {
69
+ "name": "20260918071839_add_activity_object_index",
70
+ "sha256": "496cead2a7b9ebb3a82a6c03104b6275246a1b81201266d75d6d771e4385b965"
71
+ },
72
+ {
73
+ "name": "20261006061745_add_activity_deliveries_and_keys",
74
+ "sha256": "01362db69eacbb398ee6da3a8364e700e583aa23a7008fd5c0fc5ef9baf6ecdd"
75
+ },
76
+ {
77
+ "name": "20261006085045_snake_case_columns",
78
+ "sha256": "595470797f3ed0c38a1f420660d39a32781d4f9365db8d9e6c1037b5d7738e29"
79
+ },
80
+ {
81
+ "name": "20261006122653_local_actor_keys",
82
+ "sha256": "f4761a17dda22ffc7a578f9dd55668eee03ff6525707c85df83cbe1706fa9a3d"
83
+ },
84
+ {
85
+ "name": "20261010044954_link_activity_deliveries_to_activities",
86
+ "sha256": "8dfa33c73cf9abb9096b3742f4546937a1d2113fe20ce0c1263c42b6ece5a931"
87
+ },
88
+ {
89
+ "name": "20261010073134_check_inbound_activity_link",
90
+ "sha256": "450493aafc42035067fc4dc54a55bd065def8e1f901cee8d9964c6743d0b8108"
91
+ },
92
+ {
93
+ "name": "20261010104304_record_object_activity",
94
+ "sha256": "2afbd79ef6f6ee9d507261c8c63bdb780dcb7cdb757a9cfaafbc9e02d5d29d41"
95
+ },
96
+ {
97
+ "name": "20261010111648_record_delivery_snapshot",
98
+ "sha256": "22cf87bfd0ee7386df1a6fb377606bb20f5ddd0517250cb434c47eb7c0876965"
99
+ },
100
+ {
101
+ "name": "20261011144453_record_object_snapshot",
102
+ "sha256": "b4f9ae1fd9c0e8c193313814e54c8a49a7459a22e205006183b9f1d09475b56d"
103
+ },
104
+ {
105
+ "name": "20261011192718_record_actor_followers",
106
+ "sha256": "7ad5dafd71aae445354315e4bec4466196228dabd081bb76171874817cb38ff4"
107
+ }
108
+ ]
109
+ }
@@ -0,0 +1,23 @@
1
+ import { MigrationManifestPaths } from "./migration-manifest.mjs";
2
+ import { MigrationState } from "./migration-state.mjs";
3
+ import { PersistentPgliteStore } from "./pglite-store.mjs";
4
+ //#region src/pglite-preparation.d.ts
5
+ interface PreparePgliteOptions extends MigrationManifestPaths {
6
+ /** Borrowed exclusive owner. The caller must drain preparation before close. */
7
+ readonly store: PersistentPgliteStore;
8
+ readonly migrationsSchema?: string;
9
+ readonly migrationsTable?: string;
10
+ /** Abort is checked at safe boundaries; active WASM SQL is allowed to settle. */
11
+ readonly signal?: AbortSignal;
12
+ }
13
+ /**
14
+ * Prepare schema on a caller-owned exclusive persistent PGlite store.
15
+ * Serialize preparers sharing the same client. Other callers must not issue
16
+ * queries or close that borrowed store until preparation settles. No ownership
17
+ * is released here, including after abort or SQL failure.
18
+ * @returns Verified exact ready history after applying SQL or upgrading metadata.
19
+ */
20
+ declare function preparePgliteDatabase(options: PreparePgliteOptions): Promise<MigrationState>;
21
+ //#endregion
22
+ export { PreparePgliteOptions, preparePgliteDatabase };
23
+ //# sourceMappingURL=pglite-preparation.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-preparation.d.mts","names":[],"sources":["../src/pglite-preparation.ts"],"mappings":";;;;UA8BiB,6BAA6B;;WAEnC,OAAO;WACP;WACA;;WAEA,SAAS;;;;;;;;;iBAmFE,sBACpB,SAAS,uBACR,QAAQ"}
@@ -0,0 +1,77 @@
1
+ import { verifyMigrationManifest } from "./migration-manifest.mjs";
2
+ import { inspectMigrationState } from "./migration-state.mjs";
3
+ import { n as MigrationPreparationError, t as withVerifiedMigrationSnapshot } from "./migration-snapshot-OM5jQN1-.mjs";
4
+ //#region src/pglite-preparation.ts
5
+ const preparations = /* @__PURE__ */ new WeakMap();
6
+ function checkAbort(signal) {
7
+ if (signal?.aborted) throw new MigrationPreparationError("aborted");
8
+ }
9
+ async function inspect(options, manifest) {
10
+ checkAbort(options.signal);
11
+ try {
12
+ const state = await inspectMigrationState(options.store.client, {
13
+ manifest,
14
+ migrationsSchema: options.migrationsSchema ?? "drizzle",
15
+ migrationsTable: options.migrationsTable ?? "__drizzle_migrations"
16
+ });
17
+ checkAbort(options.signal);
18
+ return state;
19
+ } catch (error) {
20
+ if (error instanceof MigrationPreparationError) throw error;
21
+ throw new MigrationPreparationError("inspection-failed");
22
+ }
23
+ }
24
+ async function prepare(options) {
25
+ checkAbort(options.signal);
26
+ let manifest;
27
+ try {
28
+ manifest = await verifyMigrationManifest(options);
29
+ } catch {
30
+ throw new MigrationPreparationError("invalid-migration-files");
31
+ }
32
+ checkAbort(options.signal);
33
+ await options.store.ready;
34
+ const state = await inspect(options, manifest);
35
+ if (![
36
+ "ready",
37
+ "pending",
38
+ "uninitialized",
39
+ "upgrade-required"
40
+ ].includes(state.status)) throw new MigrationPreparationError("incompatible-history", state);
41
+ if (state.status === "ready") return state;
42
+ try {
43
+ const [{ drizzle }, { migrate }] = await Promise.all([import("drizzle-orm/pglite"), import("drizzle-orm/pglite/migrator")]);
44
+ await withVerifiedMigrationSnapshot(manifest, options, async (migrationsFolder) => {
45
+ checkAbort(options.signal);
46
+ await migrate(drizzle({ client: options.store.client }), {
47
+ migrationsFolder,
48
+ migrationsSchema: options.migrationsSchema ?? "drizzle",
49
+ migrationsTable: options.migrationsTable ?? "__drizzle_migrations"
50
+ });
51
+ });
52
+ } catch (error) {
53
+ checkAbort(options.signal);
54
+ if (error instanceof MigrationPreparationError) throw error;
55
+ throw new MigrationPreparationError("migration-failed");
56
+ }
57
+ const result = await inspect(options, manifest);
58
+ if (result.status !== "ready") throw new MigrationPreparationError("incompatible-history", result);
59
+ return result;
60
+ }
61
+ /**
62
+ * Prepare schema on a caller-owned exclusive persistent PGlite store.
63
+ * Serialize preparers sharing the same client. Other callers must not issue
64
+ * queries or close that borrowed store until preparation settles. No ownership
65
+ * is released here, including after abort or SQL failure.
66
+ * @returns Verified exact ready history after applying SQL or upgrading metadata.
67
+ */
68
+ async function preparePgliteDatabase(options) {
69
+ checkAbort(options.signal);
70
+ const result = (preparations.get(options.store.client) ?? Promise.resolve()).then(() => prepare(options));
71
+ preparations.set(options.store.client, result.then(() => void 0, () => void 0));
72
+ return await result;
73
+ }
74
+ //#endregion
75
+ export { preparePgliteDatabase };
76
+
77
+ //# sourceMappingURL=pglite-preparation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-preparation.mjs","names":[],"sources":["../src/pglite-preparation.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport type { PGlite } from \"@electric-sql/pglite\";\n\nimport {\n type MigrationManifest,\n type MigrationManifestPaths,\n verifyMigrationManifest,\n} from \"./migration-manifest.ts\";\nimport { MigrationPreparationError } from \"./migration-preparation-error.ts\";\nimport { withVerifiedMigrationSnapshot } from \"./migration-snapshot.ts\";\nimport {\n type MigrationState,\n inspectMigrationState,\n} from \"./migration-state.ts\";\nimport type { PersistentPgliteStore } from \"./pglite-store.ts\";\n\nexport interface PreparePgliteOptions extends MigrationManifestPaths {\n /** Borrowed exclusive owner. The caller must drain preparation before close. */\n readonly store: PersistentPgliteStore;\n readonly migrationsSchema?: string;\n readonly migrationsTable?: string;\n /** Abort is checked at safe boundaries; active WASM SQL is allowed to settle. */\n readonly signal?: AbortSignal;\n}\n\nconst preparations = new WeakMap<PGlite, Promise<void>>();\n\nfunction checkAbort(signal?: AbortSignal): void {\n if (signal?.aborted) throw new MigrationPreparationError(\"aborted\");\n}\n\nasync function inspect(\n options: PreparePgliteOptions,\n manifest: MigrationManifest,\n): Promise<MigrationState> {\n checkAbort(options.signal);\n try {\n const state = await inspectMigrationState(options.store.client, {\n manifest,\n migrationsSchema: options.migrationsSchema ?? \"drizzle\",\n migrationsTable: options.migrationsTable ?? \"__drizzle_migrations\",\n });\n checkAbort(options.signal);\n return state;\n } catch (error) {\n if (error instanceof MigrationPreparationError) throw error;\n throw new MigrationPreparationError(\"inspection-failed\");\n }\n}\n\nasync function prepare(options: PreparePgliteOptions): Promise<MigrationState> {\n checkAbort(options.signal);\n let manifest: MigrationManifest;\n try {\n manifest = await verifyMigrationManifest(options);\n } catch {\n throw new MigrationPreparationError(\"invalid-migration-files\");\n }\n checkAbort(options.signal);\n await options.store.ready;\n const state = await inspect(options, manifest);\n if (\n ![\"ready\", \"pending\", \"uninitialized\", \"upgrade-required\"].includes(\n state.status,\n )\n ) {\n throw new MigrationPreparationError(\"incompatible-history\", state);\n }\n if (state.status === \"ready\") return state;\n try {\n const [{ drizzle }, { migrate }] = await Promise.all([\n import(\"drizzle-orm/pglite\"),\n import(\"drizzle-orm/pglite/migrator\"),\n ]);\n await withVerifiedMigrationSnapshot(\n manifest,\n options,\n async (migrationsFolder) => {\n checkAbort(options.signal);\n await migrate(drizzle({ client: options.store.client }), {\n migrationsFolder,\n migrationsSchema: options.migrationsSchema ?? \"drizzle\",\n migrationsTable: options.migrationsTable ?? \"__drizzle_migrations\",\n });\n },\n );\n } catch (error) {\n checkAbort(options.signal);\n if (error instanceof MigrationPreparationError) throw error;\n throw new MigrationPreparationError(\"migration-failed\");\n }\n const result = await inspect(options, manifest);\n if (result.status !== \"ready\") {\n throw new MigrationPreparationError(\"incompatible-history\", result);\n }\n return result;\n}\n\n/**\n * Prepare schema on a caller-owned exclusive persistent PGlite store.\n * Serialize preparers sharing the same client. Other callers must not issue\n * queries or close that borrowed store until preparation settles. No ownership\n * is released here, including after abort or SQL failure.\n * @returns Verified exact ready history after applying SQL or upgrading metadata.\n */\nexport async function preparePgliteDatabase(\n options: PreparePgliteOptions,\n): Promise<MigrationState> {\n checkAbort(options.signal);\n const previous = preparations.get(options.store.client) ?? Promise.resolve();\n // Keep the queue tail fulfilled while returning each caller's actual outcome.\n // oxlint-disable promise/prefer-await-to-then\n const result = previous.then(() => prepare(options));\n preparations.set(\n options.store.client,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n // oxlint-enable promise/prefer-await-to-then\n return await result;\n}\n"],"mappings":";;;;AAuCA,MAAM,+BAAe,IAAI,QAA+B;AAExD,SAAS,WAAW,QAA4B;CAC9C,IAAI,QAAQ,SAAS,MAAM,IAAI,0BAA0B,SAAS;AACpE;AAEA,eAAe,QAC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9C,IAAI,OAAO,WAAW,SACpB,MAAM,IAAI,0BAA0B,wBAAwB,MAAM;CAEpE,OAAO;AACT;;;;;;;;AASA,eAAsB,sBACpB,SACyB;CACzB,WAAW,QAAQ,MAAM;CAIzB,MAAM,UAHW,aAAa,IAAI,QAAQ,MAAM,MAAM,KAAK,QAAQ,QAAQ,EAAA,CAGnD,WAAW,QAAQ,OAAO,CAAC;CACnD,aAAa,IACX,QAAQ,MAAM,QACd,OAAO,WACC,KAAA,SACA,KAAA,CACR,CACF;CAEA,OAAO,MAAM;AACf"}
@@ -0,0 +1,29 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ //#region src/pglite-store.d.ts
3
+ type PgliteStoreCode = "invalid-path" | "lock-unavailable" | "locked" | "open-failed" | "close-failed";
4
+ /** A sanitized storage failure; filesystem and database causes are omitted. */
5
+ declare class PgliteStoreError extends Error {
6
+ readonly code: PgliteStoreCode;
7
+ constructor(code: PgliteStoreCode);
8
+ }
9
+ interface PersistentPgliteStore {
10
+ readonly client: PGlite;
11
+ /** Initialization completion with sanitized open-failed errors. */
12
+ readonly ready: Promise<void>;
13
+ /** The real absolute data directory, shared by all aliases of this store. */
14
+ readonly dataPath: string;
15
+ /** Shared completion; closes the database before releasing its native lock. */
16
+ close(): Promise<void>;
17
+ }
18
+ /**
19
+ * Open an exclusively owned persistent PGlite store on a local filesystem.
20
+ * Register close immediately, then await ready before using the client.
21
+ * The stable .drfed.lock file is never removed: replacing its inode could split
22
+ * owners across two locks. OS locks survive suspension and release on process
23
+ * exit; no heartbeat, PID guessing or stale-lock deletion is used.
24
+ * @returns The initializing client, canonical directory and owned close method.
25
+ */
26
+ declare function openPersistentPglite(dataPath: string): Promise<PersistentPgliteStore>;
27
+ //#endregion
28
+ export { PersistentPgliteStore, PgliteStoreCode, PgliteStoreError, openPersistentPglite };
29
+ //# sourceMappingURL=pglite-store.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-store.d.mts","names":[],"sources":["../src/pglite-store.ts"],"mappings":";;KA4BY;;cAkBC,yBAAyB;WAC3B,MAAM;EACf,YAAY,MAAM;;UAOH;WACN,QAAQ;;WAER,OAAO;;WAEP;;EAET,SAAS;;;;;;;;;;iBAsFW,qBACpB,mBACC,QAAQ"}
@@ -0,0 +1,117 @@
1
+ import { constants } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { PGlite } from "@electric-sql/pglite";
4
+ import { lstat, mkdir, open, realpath } from "node:fs/promises";
5
+ //#region src/pglite-store.ts
6
+ const explanations = {
7
+ "invalid-path": "Invalid persistent PGlite data directory or lock file.",
8
+ "lock-unavailable": "The native PGlite file lock is unavailable on this platform.",
9
+ locked: "The PGlite data directory is already in use by another owner.",
10
+ "open-failed": "Could not open the persistent PGlite store.",
11
+ "close-failed": "Could not close PGlite storage cleanly; terminate this owner before retrying."
12
+ };
13
+ /** A sanitized storage failure; filesystem and database causes are omitted. */
14
+ var PgliteStoreError = class extends Error {
15
+ code;
16
+ constructor(code) {
17
+ super(explanations[code]);
18
+ this.name = "PgliteStoreError";
19
+ this.code = code;
20
+ }
21
+ };
22
+ const heldFiles = /* @__PURE__ */ new Set();
23
+ async function canonicalDataPath(dataPath) {
24
+ if (typeof dataPath !== "string" || dataPath.trim() === "") throw new PgliteStoreError("invalid-path");
25
+ try {
26
+ await mkdir(dataPath, {
27
+ recursive: true,
28
+ mode: 448
29
+ });
30
+ return await realpath(dataPath);
31
+ } catch {
32
+ throw new PgliteStoreError("invalid-path");
33
+ }
34
+ }
35
+ async function closeLock(handle) {
36
+ try {
37
+ await handle.close();
38
+ heldFiles.delete(handle);
39
+ } catch {
40
+ heldFiles.add(handle);
41
+ throw new PgliteStoreError("close-failed");
42
+ }
43
+ }
44
+ async function acquireLock(dataPath) {
45
+ let tryLock;
46
+ try {
47
+ ({tryLock} = await import("fs-native-extensions"));
48
+ } catch {
49
+ throw new PgliteStoreError("lock-unavailable");
50
+ }
51
+ const path = join(dataPath, ".drfed.lock");
52
+ let handle;
53
+ try {
54
+ handle = await open(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 384);
55
+ } catch {
56
+ throw new PgliteStoreError("invalid-path");
57
+ }
58
+ try {
59
+ const [file, entry] = await Promise.all([handle.stat(), lstat(path)]);
60
+ if (!file.isFile() || !entry.isFile() || file.nlink !== 1 || file.dev !== entry.dev || file.ino !== entry.ino) throw new PgliteStoreError("invalid-path");
61
+ if (!tryLock(handle.fd)) throw new PgliteStoreError("locked");
62
+ heldFiles.add(handle);
63
+ return handle;
64
+ } catch (error) {
65
+ await closeLock(handle);
66
+ if (error instanceof PgliteStoreError) throw error;
67
+ throw new PgliteStoreError("lock-unavailable");
68
+ }
69
+ }
70
+ async function readyStore(client) {
71
+ try {
72
+ await client.waitReady;
73
+ } catch {
74
+ throw new PgliteStoreError("open-failed");
75
+ }
76
+ }
77
+ /**
78
+ * Open an exclusively owned persistent PGlite store on a local filesystem.
79
+ * Register close immediately, then await ready before using the client.
80
+ * The stable .drfed.lock file is never removed: replacing its inode could split
81
+ * owners across two locks. OS locks survive suspension and release on process
82
+ * exit; no heartbeat, PID guessing or stale-lock deletion is used.
83
+ * @returns The initializing client, canonical directory and owned close method.
84
+ */
85
+ async function openPersistentPglite(dataPath) {
86
+ const canonical = await canonicalDataPath(dataPath);
87
+ const handle = await acquireLock(canonical);
88
+ let client;
89
+ try {
90
+ client = new PGlite(canonical);
91
+ } catch {
92
+ await closeLock(handle);
93
+ throw new PgliteStoreError("open-failed");
94
+ }
95
+ const ready = readyStore(client);
96
+ ready.catch(() => void 0);
97
+ let closing;
98
+ return {
99
+ client,
100
+ ready,
101
+ dataPath: canonical,
102
+ close() {
103
+ return closing ??= Promise.resolve().then(async () => {
104
+ try {
105
+ await client.close();
106
+ } catch {
107
+ throw new PgliteStoreError("close-failed");
108
+ }
109
+ await closeLock(handle);
110
+ });
111
+ }
112
+ };
113
+ }
114
+ //#endregion
115
+ export { PgliteStoreError, openPersistentPglite };
116
+
117
+ //# sourceMappingURL=pglite-store.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-store.mjs","names":[],"sources":["../src/pglite-store.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n/// <reference path=\"./fs-native-extensions.d.ts\" />\nimport { constants } from \"node:fs\";\nimport {\n type FileHandle,\n lstat,\n mkdir,\n open,\n realpath,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { PGlite } from \"@electric-sql/pglite\";\n\nexport type PgliteStoreCode =\n | \"invalid-path\"\n | \"lock-unavailable\"\n | \"locked\"\n | \"open-failed\"\n | \"close-failed\";\n\nconst explanations: Record<PgliteStoreCode, string> = {\n \"invalid-path\": \"Invalid persistent PGlite data directory or lock file.\",\n \"lock-unavailable\":\n \"The native PGlite file lock is unavailable on this platform.\",\n locked: \"The PGlite data directory is already in use by another owner.\",\n \"open-failed\": \"Could not open the persistent PGlite store.\",\n \"close-failed\":\n \"Could not close PGlite storage cleanly; terminate this owner before retrying.\",\n};\n\n/** A sanitized storage failure; filesystem and database causes are omitted. */\nexport class PgliteStoreError extends Error {\n readonly code: PgliteStoreCode;\n constructor(code: PgliteStoreCode) {\n super(explanations[code]);\n this.name = \"PgliteStoreError\";\n this.code = code;\n }\n}\n\nexport interface PersistentPgliteStore {\n readonly client: PGlite;\n /** Initialization completion with sanitized open-failed errors. */\n readonly ready: Promise<void>;\n /** The real absolute data directory, shared by all aliases of this store. */\n readonly dataPath: string;\n /** Shared completion; closes the database before releasing its native lock. */\n close(): Promise<void>;\n}\n\n// Keep failed-close owners' handles reachable: garbage collection must not\n// silently release a lock while the corresponding database might remain active.\nconst heldFiles = new Set<FileHandle>();\n\nasync function canonicalDataPath(dataPath: string): Promise<string> {\n if (typeof dataPath !== \"string\" || dataPath.trim() === \"\") {\n throw new PgliteStoreError(\"invalid-path\");\n }\n try {\n await mkdir(dataPath, { recursive: true, mode: 0o700 });\n return await realpath(dataPath);\n } catch {\n throw new PgliteStoreError(\"invalid-path\");\n }\n}\n\nasync function closeLock(handle: FileHandle): Promise<void> {\n try {\n await handle.close();\n heldFiles.delete(handle);\n } catch {\n heldFiles.add(handle);\n throw new PgliteStoreError(\"close-failed\");\n }\n}\n\nasync function acquireLock(dataPath: string): Promise<FileHandle> {\n let tryLock: (fd: number) => boolean;\n try {\n ({ tryLock } = await import(\"fs-native-extensions\"));\n } catch {\n throw new PgliteStoreError(\"lock-unavailable\");\n }\n const path = join(dataPath, \".drfed.lock\");\n let handle: FileHandle;\n try {\n handle = await open(\n path,\n // Native open flags are deliberately combined; never follow a lock symlink.\n // oxlint-disable-next-line no-bitwise\n constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW,\n 0o600,\n );\n } catch {\n throw new PgliteStoreError(\"invalid-path\");\n }\n try {\n const [file, entry] = await Promise.all([handle.stat(), lstat(path)]);\n if (\n !file.isFile() ||\n !entry.isFile() ||\n file.nlink !== 1 ||\n file.dev !== entry.dev ||\n file.ino !== entry.ino\n ) {\n throw new PgliteStoreError(\"invalid-path\");\n }\n if (!tryLock(handle.fd)) throw new PgliteStoreError(\"locked\");\n heldFiles.add(handle);\n return handle;\n } catch (error) {\n await closeLock(handle);\n if (error instanceof PgliteStoreError) throw error;\n throw new PgliteStoreError(\"lock-unavailable\");\n }\n}\n\nasync function readyStore(client: PGlite): Promise<void> {\n try {\n await client.waitReady;\n } catch {\n throw new PgliteStoreError(\"open-failed\");\n }\n}\n\n/**\n * Open an exclusively owned persistent PGlite store on a local filesystem.\n * Register close immediately, then await ready before using the client.\n * The stable .drfed.lock file is never removed: replacing its inode could split\n * owners across two locks. OS locks survive suspension and release on process\n * exit; no heartbeat, PID guessing or stale-lock deletion is used.\n * @returns The initializing client, canonical directory and owned close method.\n */\nexport async function openPersistentPglite(\n dataPath: string,\n): Promise<PersistentPgliteStore> {\n const canonical = await canonicalDataPath(dataPath);\n const handle = await acquireLock(canonical);\n let client: PGlite;\n try {\n client = new PGlite(canonical);\n } catch {\n await closeLock(handle);\n throw new PgliteStoreError(\"open-failed\");\n }\n const ready = readyStore(client);\n // The caller may close before awaiting readiness; retain its rejection for\n // observers without creating an unhandled promise during ownership transfer.\n // oxlint-disable-next-line promise/prefer-await-to-then\n void ready.catch(() => undefined);\n let closing: Promise<void> | undefined;\n return {\n client,\n ready,\n dataPath: canonical,\n close() {\n // Assign completion before invoking callbacks, including reentrant close.\n // oxlint-disable-next-line promise/prefer-await-to-then\n return (closing ??= Promise.resolve().then(async () => {\n try {\n await client.close();\n } catch {\n throw new PgliteStoreError(\"close-failed\");\n }\n await closeLock(handle);\n return undefined;\n }));\n },\n };\n}\n"],"mappings":";;;;;AAmCA,MAAM,eAAgD;CACpD,gBAAgB;CAChB,oBACE;CACF,QAAQ;CACR,eAAe;CACf,gBACE;AACJ;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CACA,YAAY,MAAuB;EACjC,MAAM,aAAa,KAAK;EACxB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAcA,MAAM,4BAAY,IAAI,IAAgB;AAEtC,eAAe,kBAAkB,UAAmC;CAClE,IAAI,OAAO,aAAa,YAAY,SAAS,KAAK,MAAM,IACtD,MAAM,IAAI,iBAAiB,cAAc;CAE3C,IAAI;EACF,MAAM,MAAM,UAAU;GAAE,WAAW;GAAM,MAAM;EAAM,CAAC;EACtD,OAAO,MAAM,SAAS,QAAQ;CAChC,QAAQ;EACN,MAAM,IAAI,iBAAiB,cAAc;CAC3C;AACF;AA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