@protobase/server 0.129.0 → 0.130.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 (243) hide show
  1. package/dist/assistant/query-runner/grants-sql.js +32 -0
  2. package/dist/assistant/query-runner/query-input.js +33 -0
  3. package/dist/assistant/query-runner/query-module.js +44 -0
  4. package/dist/assistant/query-runner/query-runner.d.ts +8 -11
  5. package/dist/assistant/query-runner/query-runner.js +15 -57
  6. package/dist/assistant/query-runner/read-query.js +54 -0
  7. package/dist/assistant/query-runner/runner-sql.js +4 -20
  8. package/dist/assistant/query-runner/steps/001-role.js +19 -0
  9. package/dist/auth-store.d.ts +2 -2
  10. package/dist/auth-store.js +3 -3
  11. package/dist/better-auth/auth-schema.d.ts +13 -4
  12. package/dist/better-auth/auth-schema.js +40 -32
  13. package/dist/better-auth/auth-settings.d.ts +59 -11
  14. package/dist/better-auth/auth-settings.js +57 -13
  15. package/dist/better-auth/auth-tables.d.ts +6 -3
  16. package/dist/better-auth/auth-tables.js +12 -7
  17. package/dist/better-auth/authenticator.js +10 -2
  18. package/dist/better-auth/create-auth.d.ts +62 -7
  19. package/dist/better-auth/create-auth.js +55 -14
  20. package/dist/better-auth/device-sign-in-check.js +13 -0
  21. package/dist/better-auth/names/declaration.d.ts +18 -5
  22. package/dist/better-auth/names/declaration.js +3 -1
  23. package/dist/better-auth/names/modules/auth.js +9 -0
  24. package/dist/better-auth/names/modules/index.d.ts +34 -4
  25. package/dist/better-auth/names/modules/organizations.js +10 -3
  26. package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
  27. package/dist/better-auth/names/modules-on.js +25 -2
  28. package/dist/better-auth/names/resolve-names.d.ts +9 -1
  29. package/dist/better-auth/names/resolve-names.js +15 -9
  30. package/dist/better-auth/organizations/accept-invitation.js +5 -4
  31. package/dist/better-auth/organizations/add-every-user.js +3 -2
  32. package/dist/better-auth/organizations/host-scope.d.ts +10 -0
  33. package/dist/better-auth/organizations/host-scope.js +15 -0
  34. package/dist/better-auth/organizations/host.d.ts +12 -6
  35. package/dist/better-auth/organizations/host.js +99 -61
  36. package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
  37. package/dist/better-auth/organizations/kept-organizations.js +62 -0
  38. package/dist/better-auth/organizations/member-endpoints.js +4 -3
  39. package/dist/better-auth/organizations/options.d.ts +15 -0
  40. package/dist/better-auth/organizations/options.js +19 -1
  41. package/dist/better-auth/organizations/people-endpoint.js +3 -2
  42. package/dist/better-auth/organizations/pinned-membership.js +81 -0
  43. package/dist/better-auth/organizations/pinned-sessions.js +46 -0
  44. package/dist/better-auth/organizations/session-organization.js +3 -2
  45. package/dist/better-auth/organizations/store.js +14 -9
  46. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  47. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  48. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  49. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  50. package/dist/better-auth/store/adoption.js +25 -10
  51. package/dist/better-auth/store/drift.js +5 -4
  52. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  53. package/dist/better-auth/store/legacy-record.js +56 -0
  54. package/dist/better-auth/store/migration-sql.js +31 -26
  55. package/dist/better-auth/store/offline/baseline-store.d.ts +35 -0
  56. package/dist/better-auth/store/offline/baseline-store.js +65 -0
  57. package/dist/better-auth/store/offline/module-switches.d.ts +27 -0
  58. package/dist/better-auth/store/offline/module-switches.js +94 -0
  59. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  60. package/dist/better-auth/store/offline/name-changes.js +5 -2
  61. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -6
  62. package/dist/better-auth/store/offline/offline-steps.js +30 -20
  63. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  64. package/dist/better-auth/store/offline/retired-watch.js +36 -0
  65. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  66. package/dist/better-auth/store/offline/settings-names.js +10 -3
  67. package/dist/better-auth/store/offline/store-model.d.ts +9 -1
  68. package/dist/better-auth/store/offline/store-model.js +22 -5
  69. package/dist/better-auth/store/resources-outside.js +1 -1
  70. package/dist/better-auth/store/step-record.d.ts +13 -0
  71. package/dist/better-auth/store/step-record.js +59 -0
  72. package/dist/better-auth/store/steps/index.js +6 -1
  73. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  74. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  75. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  76. package/dist/better-auth/store/steps/render.d.ts +3 -0
  77. package/dist/better-auth/store/steps/render.js +48 -25
  78. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  79. package/dist/better-auth/store/steps/step-lint.js +31 -10
  80. package/dist/better-auth/store/steps/step.d.ts +18 -0
  81. package/dist/better-auth/store/steps/step.js +13 -4
  82. package/dist/better-auth/store/store-db.d.ts +6 -0
  83. package/dist/better-auth/store/store-db.js +11 -5
  84. package/dist/better-auth/store/store-names.d.ts +4 -0
  85. package/dist/better-auth/token-standing.js +12 -7
  86. package/dist/better-auth/users.d.ts +7 -2
  87. package/dist/better-auth/users.js +25 -3
  88. package/dist/built-in-resources.js +1 -1
  89. package/dist/calls/calls-module.js +42 -0
  90. package/dist/calls/calls-sql.js +4 -30
  91. package/dist/changes/capture-names.d.ts +3 -1
  92. package/dist/changes/capture-names.js +5 -2
  93. package/dist/changes/capture-schema-sql.d.ts +10 -0
  94. package/dist/changes/capture-schema-sql.js +21 -0
  95. package/dist/changes/capture-schema.d.ts +0 -18
  96. package/dist/changes/capture-schema.js +1 -74
  97. package/dist/changes/capture-sql.js +30 -24
  98. package/dist/changes/changes-input.js +36 -0
  99. package/dist/changes/changes-module.js +44 -0
  100. package/dist/changes/read-capture.js +67 -0
  101. package/dist/changes/steps/001-outbox.js +23 -0
  102. package/dist/channels/sends-module.js +37 -0
  103. package/dist/channels/sends-schema-sql.js +5 -5
  104. package/dist/comments/comments-module.js +30 -0
  105. package/dist/comments/comments-sql.js +1 -22
  106. package/dist/computed/buckets-sql.d.ts +5 -1
  107. package/dist/computed/buckets-sql.js +39 -46
  108. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  109. package/dist/computed/buckets-targets.js +50 -0
  110. package/dist/computed/computed-input.js +65 -0
  111. package/dist/computed/computed-module.js +102 -0
  112. package/dist/computed/formula-sql.js +14 -1
  113. package/dist/computed/read-computed.js +100 -0
  114. package/dist/computed/rollup-sql.js +13 -10
  115. package/dist/config-exports.d.ts +2 -2
  116. package/dist/create-admin.js +21 -5
  117. package/dist/derived/derived-module.js +89 -0
  118. package/dist/derived/derived-sql.js +1 -47
  119. package/dist/functions/define-function.d.ts +10 -4
  120. package/dist/functions/routes.js +5 -3
  121. package/dist/functions/supabase-routes.js +7 -5
  122. package/dist/history/history-module.js +34 -0
  123. package/dist/index.d.ts +19 -28
  124. package/dist/index.js +11 -21
  125. package/dist/internal.d.ts +27 -10
  126. package/dist/internal.js +22 -7
  127. package/dist/jobs/functions-sql.js +7 -11
  128. package/dist/jobs/job-data.js +36 -0
  129. package/dist/jobs/job-types.d.ts +6 -3
  130. package/dist/jobs/jobs-module.d.ts +5 -0
  131. package/dist/jobs/jobs-module.js +84 -0
  132. package/dist/jobs/run-job.d.ts +1 -1
  133. package/dist/jobs/run-job.js +7 -5
  134. package/dist/jobs/runtime.d.ts +9 -4
  135. package/dist/jobs/runtime.js +11 -6
  136. package/dist/jobs/schema.d.ts +0 -11
  137. package/dist/jobs/schema.js +1 -59
  138. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  139. package/dist/live/notices-module.js +30 -0
  140. package/dist/live/notices-sql.js +2 -1
  141. package/dist/mail/feedback/feedback-schema.js +3 -30
  142. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  143. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  144. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  145. package/dist/migration-record/check-record.d.ts +9 -7
  146. package/dist/migration-record/check-record.js +12 -11
  147. package/dist/migration-record/module-needs.js +30 -0
  148. package/dist/migration-record/read-record.js +27 -15
  149. package/dist/migration-record/record-model.d.ts +7 -2
  150. package/dist/migration-record/record-model.js +14 -6
  151. package/dist/migration-record/startup-decision.js +18 -7
  152. package/dist/migration-sql/additive-statements.d.ts +4 -0
  153. package/dist/migration-sql/additive-statements.js +105 -0
  154. package/dist/notifications/devices-module.js +61 -0
  155. package/dist/notifications/history-module.js +50 -0
  156. package/dist/notifications/notifications-targets.js +23 -0
  157. package/dist/notifications/read-table.js +16 -0
  158. package/dist/notifications/schema-sql.js +1 -22
  159. package/dist/notifications/schema.js +1 -101
  160. package/dist/notifications/table-names.js +40 -0
  161. package/dist/organization-scope/app-scope.js +38 -0
  162. package/dist/organization-scope/auth-request-organization.js +71 -0
  163. package/dist/organization-scope/organization-tables.js +20 -0
  164. package/dist/organization-scope/sign-in-organization.js +21 -0
  165. package/dist/package.js +1 -1
  166. package/dist/personal-mail/shared-sender-store.js +4 -2
  167. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  168. package/dist/relation-found.js +6 -0
  169. package/dist/relay/read-relay.js +85 -0
  170. package/dist/relay/realtime-members-sql.js +51 -28
  171. package/dist/relay/relay-module.js +53 -0
  172. package/dist/relay/relay-targets.js +28 -0
  173. package/dist/relay/session-end.js +1 -3
  174. package/dist/relay/sessions-sql.js +4 -27
  175. package/dist/rest/table-routes.js +9 -2
  176. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  177. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  178. package/dist/schema-modules/module-difference.d.ts +31 -0
  179. package/dist/schema-modules/module-difference.js +98 -0
  180. package/dist/schema-modules/modules-sql.js +13 -0
  181. package/dist/schema-modules/modules.d.ts +37 -0
  182. package/dist/schema-modules/modules.js +56 -0
  183. package/dist/schema-modules/needed-modules.d.ts +41 -0
  184. package/dist/schema-modules/needed-modules.js +61 -0
  185. package/dist/schema-modules/resource-difference.js +83 -0
  186. package/dist/schema-modules/schema-module.d.ts +112 -0
  187. package/dist/schema-modules/schema-module.js +8 -0
  188. package/dist/status/status-module.js +63 -0
  189. package/dist/status/status-targets.js +21 -0
  190. package/dist/types.d.ts +6 -1
  191. package/dist/user-tables/reloading-admin.d.ts +1 -0
  192. package/dist/user-tables/reloading-admin.js +1 -0
  193. package/dist/user-tables/schema-sql.js +1 -14
  194. package/dist/user-tables/schema.js +4 -27
  195. package/dist/user-tables/user-tables-module.js +38 -0
  196. package/dist/webhooks/table/delivery-log-module.js +36 -0
  197. package/dist/webhooks/table/owner-roles.js +3 -2
  198. package/dist/webhooks/table/schema-sql.js +27 -26
  199. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  200. package/dist/webhooks/table/webhooks-targets.js +26 -0
  201. package/dist/webhooks/webhooks.js +1 -1
  202. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  203. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  204. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  205. package/dist/workflows/read-catalogue.js +23 -0
  206. package/dist/workflows/schema-sql.js +12 -9
  207. package/dist/workflows/status-sql.js +12 -6
  208. package/dist/workflows/storage/storage-module.js +39 -0
  209. package/dist/workflows/storage/storage-sql.js +8 -5
  210. package/dist/workflows/workflows-schema-module.js +49 -0
  211. package/dist/workflows/workflows-tables-sql.js +32 -0
  212. package/dist/workflows/workflows-targets.js +16 -0
  213. package/package.json +6 -6
  214. package/dist/assistant/query-runner/runner-plan.js +0 -30
  215. package/dist/better-auth/store/migrations-table.js +0 -27
  216. package/dist/better-auth/store/modules-off.js +0 -17
  217. package/dist/calls/calls-sql.d.ts +0 -11
  218. package/dist/changes/capture-plan.js +0 -79
  219. package/dist/channels/sends-schema.d.ts +0 -7
  220. package/dist/channels/sends-schema.js +0 -18
  221. package/dist/comments/comments-sql.d.ts +0 -14
  222. package/dist/computed/buckets-plan.d.ts +0 -2
  223. package/dist/computed/buckets-plan.js +0 -88
  224. package/dist/computed/buckets-schema.js +0 -39
  225. package/dist/computed/computed-plan.js +0 -81
  226. package/dist/computed/computed-schema.d.ts +0 -16
  227. package/dist/computed/computed-schema.js +0 -63
  228. package/dist/derived/derived-sql.d.ts +0 -12
  229. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  230. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  231. package/dist/notifications/schema.d.ts +0 -14
  232. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  233. package/dist/realtime/relay/relay-schema.js +0 -20
  234. package/dist/relay/realtime-members-schema.js +0 -67
  235. package/dist/relay/relay-schema.d.ts +0 -14
  236. package/dist/relay/relay-schema.js +0 -28
  237. package/dist/status/schema.d.ts +0 -12
  238. package/dist/status/schema.js +0 -33
  239. package/dist/user-tables/schema.d.ts +0 -11
  240. package/dist/webhooks/table/schema.d.ts +0 -16
  241. package/dist/webhooks/table/schema.js +0 -56
  242. package/dist/workflows/schema.d.ts +0 -13
  243. package/dist/workflows/schema.js +0 -88
@@ -0,0 +1,65 @@
1
+ import { allModules } from "../../names/modules-on.js";
2
+ import { resolveNames } from "../../names/resolve-names.js";
3
+ import { moduleSteps } from "../steps/index.js";
4
+ import { refuseUnshipped } from "../step-record.js";
5
+ import { keptModule } from "./store-model.js";
6
+ //#region src/better-auth/store/offline/baseline-store.ts
7
+ const tableKinds = ["r", "p"];
8
+ const relationOf = (live, name) => Object.hasOwn(live.relations, name) ? live.relations[name] : void 0;
9
+ /**
10
+ * Each module's last step whose own part, and that of every step before it in its chain, the store recorded. Refuses a
11
+ * recorded step this version does not ship, which the prefix would otherwise leave out unseen.
12
+ */
13
+ const recordedSteps = (applied) => {
14
+ refuseUnshipped(applied);
15
+ const steps = {};
16
+ for (const module of allModules) {
17
+ const had = moduleSteps[module].findIndex((step) => !applied.some((part) => part.module === module && part.step === step.step && part.target === module));
18
+ const count = had === -1 ? moduleSteps[module].length : had;
19
+ if (count > 0) steps[module] = moduleSteps[module][count - 1].step;
20
+ }
21
+ return steps;
22
+ };
23
+ /**
24
+ * The store at `live` under the config's `names`: each module that is on at the step the record holds, every module
25
+ * that is off but has a table as kept at the step the record holds, organizations as ever on when a table whose rows belong to an organization has
26
+ * the column that names it, and the user table as external when the config reads it through a view over another
27
+ * system's (`users.keyTable`). Refuses a user table the database has as anything but a table without `users.keyTable`,
28
+ * since the steps' foreign keys would point at it, and a table a recorded step made that the schema lacks under the
29
+ * config's name, such as one renamed since, naming each.
30
+ */
31
+ const baselineStore = (names, live) => {
32
+ const recorded = recordedSteps(live.applied);
33
+ const on = names.names.modules;
34
+ const every = resolveNames({
35
+ ...names.names.input,
36
+ modules: allModules
37
+ });
38
+ const has = (internal) => relationOf(live, every.tables[internal].name) !== void 0;
39
+ const user = names.names.table("user");
40
+ const externalUser = names.users.keyTable !== void 0;
41
+ const userRelation = relationOf(live, user.name);
42
+ if (!externalUser && userRelation && !tableKinds.includes(userRelation.kind)) throw new Error(`The auth store's ${user.name} is a view or another relation that is not a table: name the table that holds the user ids in users.keyTable, which the steps' foreign keys point at, and run the baseline again`);
43
+ const lastSteps = Object.fromEntries(on.filter((module) => recorded[module] !== void 0).map((module) => [module, recorded[module]]));
44
+ const made = Object.entries(lastSteps).flatMap(([module, last]) => moduleSteps[module].filter((step) => step.step <= last).flatMap((step) => step.tables));
45
+ const missing = [...lastSteps.auth !== void 0 && !externalUser ? ["user"] : [], ...made].filter((internal) => !has(internal));
46
+ if (missing.length > 0) {
47
+ const listed = missing.map((internal) => every.tables[internal].name).join(", ");
48
+ throw new Error(`The auth store's schema lacks ${listed}, which the steps the store recorded made: name each as the store has it in auth.tables, or apply the project's migrations first`);
49
+ }
50
+ const kept = allModules.filter((module) => !on.includes(module) && Object.values(every.tables).some((table) => table.module === module && has(table.internal))).map((module) => keptModule(names, module, recorded[module] ?? 0));
51
+ const organizationsEverOn = Object.values(every.tables).some((table) => {
52
+ const column = table.columns.organization_id;
53
+ return table.scope === "organization" && column !== void 0 && (relationOf(live, table.name)?.columns.includes(column.name) ?? false);
54
+ });
55
+ const prefix = names.schema === void 0 ? "" : `${names.schema}.`;
56
+ return {
57
+ lastSteps,
58
+ kept,
59
+ organizationsEverOn,
60
+ external: externalUser ? [`${prefix}${user.name}`] : [],
61
+ stepRecord: has("auth_steps")
62
+ };
63
+ };
64
+ //#endregion
65
+ export { baselineStore, recordedSteps };
@@ -0,0 +1,27 @@
1
+ import { ModuleId } from "../../names/modules/index.js";
2
+ import { ResolvedTable } from "../../names/resolve-names.js";
3
+ import { StoreNames } from "../store-names.js";
4
+ import "./retired-watch.js";
5
+ //#region src/better-auth/store/offline/module-switches.d.ts
6
+ /** What becomes of a module's tables once it is off. */
7
+ export declare const offChoices: readonly ["keep", "archive", "delete"];
8
+ export type OffChoice = (typeof offChoices)[number];
9
+ /** The setting `protobase migrate --force` sets in its transactions, which lets a module whose kept tables hold rows on again. */
10
+ export declare const forceSetting = "protobase.force";
11
+ /** The tables of `module` its steps up to `step` made, under the store's names. */
12
+ export declare const keptTables: (names: StoreNames, module: ModuleId, step: number) => ResolvedTable<string>[];
13
+ /** The message that refuses turning `module` on again while its kept tables hold rows: `found` lists each table with its count. */
14
+ export declare const revivalRefusal: (module: ModuleId, found: string) => string;
15
+ /**
16
+ * The block that refuses, before the steps, to turn `module` on again while the tables it kept at `step` hold rows,
17
+ * naming each table with its count; `protobase migrate --force` lets it through. Empty tables pass.
18
+ */
19
+ export declare const revivalCheckSql: (names: StoreNames, module: ModuleId, step: number) => string;
20
+ /** The statements that keep `module` while off, as SQL text under a comment naming it; none when there are none. */
21
+ export declare const keepSql: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[], externalUser?: boolean) => string;
22
+ /**
23
+ * The statements that stop the watch on the columns `module` retired, as it turns on again, whose values they kept;
24
+ * none when it retired none.
25
+ */
26
+ export declare const unwatchSql: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[], externalUser?: boolean) => string | undefined;
27
+ //#endregion
@@ -0,0 +1,94 @@
1
+ import { builtInModules } from "../../names/modules/index.js";
2
+ import { allModules } from "../../names/modules-on.js";
3
+ import { resolveNames } from "../../names/resolve-names.js";
4
+ import { ddl } from "../ddl.js";
5
+ import { moduleSteps } from "../steps/index.js";
6
+ import { statementsSql } from "../migration-sql.js";
7
+ import { unwatchStatements, watchStatements } from "./retired-watch.js";
8
+ import { sql } from "kysely";
9
+ //#region src/better-auth/store/offline/module-switches.ts
10
+ /** What becomes of a module's tables once it is off. */
11
+ const offChoices = [
12
+ "keep",
13
+ "archive",
14
+ "delete"
15
+ ];
16
+ /** The setting `protobase migrate --force` sets in its transactions, which lets a module whose kept tables hold rows on again. */
17
+ const forceSetting = "protobase.force";
18
+ const everyTable = (names) => resolveNames({
19
+ ...names.names.input,
20
+ modules: allModules
21
+ }).tables;
22
+ const writtenWhileOff = { organizations: { personal_access_token: ["organization_id"] } };
23
+ /**
24
+ * The columns `module` adds to the tables of the modules that stay on, which retire once it is off: each table one of
25
+ * `existing`, whose tables the store has before the migration; a column the server still writes while it is off stays
26
+ * in use (`writtenWhileOff`). A table of a module turned on in the same migration is made without the column. The user
27
+ * table is left alone when it is a relation Protobase did not make.
28
+ */
29
+ const retiredColumns = (names, module, existing, externalUser = names.users.keyTable !== void 0) => {
30
+ const every = everyTable(names);
31
+ const declaration = builtInModules.find(({ id }) => id === module);
32
+ return Object.entries(declaration.columns ?? {}).filter(([table]) => {
33
+ const kept = names.names.tables[table];
34
+ return kept !== void 0 && existing.includes(kept.module) && !(table === "user" && externalUser);
35
+ }).flatMap(([table, columns]) => Object.keys(columns).filter((column) => !writtenWhileOff[module]?.[table]?.includes(column)).map((column) => ({
36
+ table: every[table],
37
+ column: every[table].columns[column]
38
+ })));
39
+ };
40
+ /**
41
+ * The statements that keep `module`'s tables and rows while it is off: each column it retires (`retiredColumns`) loses
42
+ * `not null`, so the code that no longer writes it still inserts rows, and is watched for the writes of the code that
43
+ * still does (`watchStatements`).
44
+ */
45
+ const keepStatements = (names, module, existing, externalUser) => {
46
+ const columns = retiredColumns(names, module, existing, externalUser);
47
+ return [...columns.map(({ table, column }) => ddl`alter table ${table} alter column ${column} drop not null`), ...watchStatements(columns)];
48
+ };
49
+ /** The tables of `module` its steps up to `step` made, under the store's names. */
50
+ const keptTables = (names, module, step) => {
51
+ const every = everyTable(names);
52
+ return moduleSteps[module].filter((made) => made.step <= step).flatMap((made) => made.tables.map((table) => every[table]));
53
+ };
54
+ /** The message that refuses turning `module` on again while its kept tables hold rows: `found` lists each table with its count. */
55
+ const revivalRefusal = (module, found) => `The ${module} module was kept while off, and its tables still hold rows: ${found}. Turning it on again brings them back into use, such as personal access tokens, which act again for their users: delete them in a migration of the project's own written before this one, or apply with \`protobase migrate --force\` to bring them back`;
56
+ /**
57
+ * The block that refuses, before the steps, to turn `module` on again while the tables it kept at `step` hold rows,
58
+ * naming each table with its count; `protobase migrate --force` lets it through. Empty tables pass.
59
+ */
60
+ const revivalCheckSql = (names, module, step) => {
61
+ const counts = keptTables(names, module, step).map((table) => ddl`select ${sql.lit(table.name)} as name, (select count(*) from ${table}) as rows`);
62
+ const check = ddl`do $revive$
63
+ declare
64
+ found text;
65
+ begin
66
+ if coalesce(current_setting(${sql.lit(forceSetting)}, true), '') <> 'true' then
67
+ select string_agg(counted.name || ' ' || counted.rows, ', ' order by counted.name) into found
68
+ from (${sql.join(counts, sql` union all `)}) as counted
69
+ where counted.rows > 0;
70
+ if found is not null then
71
+ raise exception '%', format(${sql.lit(revivalRefusal(module, "%s"))}, found);
72
+ end if;
73
+ end if;
74
+ end
75
+ $revive$`;
76
+ return `-- ${module} on again: its kept tables must be empty, or the migration applied with \`protobase migrate --force\`.\n${statementsSql([check])}`;
77
+ };
78
+ /** The statements that keep `module` while off, as SQL text under a comment naming it; none when there are none. */
79
+ const keepSql = (names, module, existing, externalUser) => {
80
+ const statements = keepStatements(names, module, existing, externalUser);
81
+ if (statements.length === 0) return `-- ${module} off: its tables and rows are kept as they are.`;
82
+ return `-- ${module} off: its tables and rows are kept, and the columns it adds to the tables of the modules that are on may stay empty, watched for writes in retired.writes.\n${statementsSql(statements)}`;
83
+ };
84
+ /**
85
+ * The statements that stop the watch on the columns `module` retired, as it turns on again, whose values they kept;
86
+ * none when it retired none.
87
+ */
88
+ const unwatchSql = (names, module, existing, externalUser) => {
89
+ const statements = unwatchStatements(retiredColumns(names, module, existing, externalUser));
90
+ if (statements.length === 0) return;
91
+ return `-- ${module} on again: the columns it adds are in use again, with the values they kept, and no longer watched.\n${statementsSql(statements)}`;
92
+ };
93
+ //#endregion
94
+ export { forceSetting, keepSql, keepStatements, keptTables, offChoices, retiredColumns, revivalCheckSql, revivalRefusal, unwatchSql };
@@ -1,5 +1,8 @@
1
1
  import { StoreModel } from "./store-model.js";
2
2
  //#region src/better-auth/store/offline/name-changes.d.ts
3
- /** How `after` changes what `before`, from `source`, has, one line each, the last steps aside; none when it only adds. */
3
+ /**
4
+ * How `after` changes what `before`, from `source`, has, one line each, the last steps and the tables' scopes aside:
5
+ * a scope is Protobase's to declare, not a name the store has; none when it only adds.
6
+ */
4
7
  export declare const nameChanges: (before: StoreModel, after: StoreModel, source?: string) => string[];
5
8
  //#endregion
@@ -4,11 +4,14 @@ const changes = (before, after, at, source) => {
4
4
  if (typeof before !== "object" || before === null || typeof after !== "object" || after === null) return before === after ? [] : [`${at} is ${JSON.stringify(before)} in ${source} and ${JSON.stringify(after)} now`];
5
5
  return Object.entries(before).flatMap(([key, value]) => changes(value, after[key], at === "" ? key : `${at}.${key}`, source));
6
6
  };
7
- /** How `after` changes what `before`, from `source`, has, one line each, the last steps aside; none when it only adds. */
7
+ /**
8
+ * How `after` changes what `before`, from `source`, has, one line each, the last steps and the tables' scopes aside:
9
+ * a scope is Protobase's to declare, not a name the store has; none when it only adds.
10
+ */
8
11
  const nameChanges = (before, after, source = "the snapshot") => {
9
12
  const withoutSteps = (model) => ({
10
13
  ...model,
11
- modules: Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, entry.tables]))
14
+ modules: Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, Object.fromEntries(Object.entries(entry.tables).map(([internal, { scope: _, ...table }]) => [internal, table]))]))
12
15
  });
13
16
  return changes(withoutSteps(before), withoutSteps(after), "", source);
14
17
  };
@@ -1,14 +1,29 @@
1
+ import { ModuleId } from "../../names/modules/index.js";
1
2
  import { StoreNames } from "../store-names.js";
3
+ import { OrganizationsInput } from "../steps/step.js";
2
4
  import { LastSteps } from "./store-model.js";
3
5
  //#region src/better-auth/store/offline/offline-steps.d.ts
4
6
  /**
5
- * The steps of the modules that are on after `lastSteps`, the snapshot's, each version of the store's former chain
6
- * followed by its row in `auth_migrations`, which the server's check reads, each run only while that table lacks its
7
- * version, so a database that has it already skips it; for a store the snapshot has none of
8
- * (`lastSteps` undefined), that table first. `checks`: the checks of the steps on tables the store has already, which
9
- * refuse when its rows break what a step assumes. `undefined` when the snapshot has every step.
7
+ * The store as a project's snapshot has it: each module's last step, those kept while off included; the modules that
8
+ * are on; and whether it has `auth_steps`, which a store a version before it made lacks.
10
9
  */
11
- export declare const offlineStepsMigration: (names: StoreNames, lastSteps: LastSteps | undefined) => {
10
+ export type SnapshotStore = {
11
+ lastSteps: LastSteps;
12
+ on: readonly ModuleId[];
13
+ stepRecord: boolean;
14
+ };
15
+ /**
16
+ * The parts of the modules that are on that the snapshot's store lacks, each followed by its row in `auth_steps`, each
17
+ * run only while that table lacks it, so a database that has it already skips it; for a store the snapshot has none of
18
+ * (`store` undefined), that table first, and for one without it, that table, filled from `auth_migrations`. `checks`:
19
+ * the checks of the parts on tables the store has already, which refuse when its rows break what a step assumes;
20
+ * `after`, what the parts leave for the migration's `.after.sql`, when they leave anything. `undefined` when the
21
+ * snapshot's store has every part. `externalUser`: the snapshot records the user table as a relation Protobase did
22
+ * not make, whose statements are left out. `organizations`: the config's default organization and the role of the
23
+ * users there already (`renderSteps`).
24
+ */
25
+ export declare const offlineStepsMigration: (names: StoreNames, store: SnapshotStore | undefined, organizations: OrganizationsInput | undefined, externalUser?: boolean) => {
26
+ after?: string | undefined;
12
27
  sql: string;
13
28
  checks: string[];
14
29
  } | undefined;
@@ -1,9 +1,8 @@
1
- import { legacyVersions } from "../steps/legacy-versions.js";
2
- import { guardedStepsSql, migrationsTableSql, statementsSql } from "../migration-sql.js";
3
1
  import { moduleSteps } from "../steps/index.js";
2
+ import { afterStepsSql, guardedStepsSql, statementsSql, stepRecordSql } from "../migration-sql.js";
4
3
  import { renderSteps } from "../steps/render.js";
4
+ import { stepRecordMigration } from "../legacy-record.js";
5
5
  import { migrationNames } from "../steps/step.js";
6
- import { refuseModulesOff } from "../modules-off.js";
7
6
  //#region src/better-auth/store/offline/offline-steps.ts
8
7
  const refuseNewer = (lastSteps) => {
9
8
  for (const [module, last] of Object.entries(lastSteps)) {
@@ -12,25 +11,36 @@ const refuseNewer = (lastSteps) => {
12
11
  }
13
12
  };
14
13
  /**
15
- * The steps of the modules that are on after `lastSteps`, the snapshot's, each version of the store's former chain
16
- * followed by its row in `auth_migrations`, which the server's check reads, each run only while that table lacks its
17
- * version, so a database that has it already skips it; for a store the snapshot has none of
18
- * (`lastSteps` undefined), that table first. `checks`: the checks of the steps on tables the store has already, which
19
- * refuse when its rows break what a step assumes. `undefined` when the snapshot has every step.
14
+ * The parts the store has: those of each module's steps up to its last, and those a step adds to another module's
15
+ * tables while both are on. Those it added to a module that was off since, or before, are written again, and their
16
+ * guard skips them where the database has them.
20
17
  */
21
- const offlineStepsMigration = (names, lastSteps) => {
22
- refuseModulesOff(names);
23
- if (lastSteps) refuseNewer(lastSteps);
24
- const had = (module, step) => step.step <= (lastSteps?.[module] ?? 0);
25
- const migration = migrationNames(names);
26
- const rendered = renderSteps(migration, names.names.modules, had);
27
- if (rendered.length === 0) return void 0;
28
- const recorded = (version) => Object.entries(moduleSteps).every(([module, steps]) => steps.filter((step) => step.version === version).every((step) => had(module, step)));
29
- const steps = guardedStepsSql(names, rendered, legacyVersions.map(({ version }) => version).filter((version) => !recorded(version)));
30
- const checks = rendered.filter(({ module, step, on }) => on === void 0 && step.check && had(module, moduleSteps[module][0])).map(({ step }) => statementsSql([step.check(migration)]));
18
+ const snapshotHad = ({ lastSteps, on }) => (module, step, target) => step <= (lastSteps[module] ?? 0) && (target === module || on.includes(module) && on.includes(target));
19
+ /**
20
+ * The parts of the modules that are on that the snapshot's store lacks, each followed by its row in `auth_steps`, each
21
+ * run only while that table lacks it, so a database that has it already skips it; for a store the snapshot has none of
22
+ * (`store` undefined), that table first, and for one without it, that table, filled from `auth_migrations`. `checks`:
23
+ * the checks of the parts on tables the store has already, which refuse when its rows break what a step assumes;
24
+ * `after`, what the parts leave for the migration's `.after.sql`, when they leave anything. `undefined` when the
25
+ * snapshot's store has every part. `externalUser`: the snapshot records the user table as a relation Protobase did
26
+ * not make, whose statements are left out. `organizations`: the config's default organization and the role of the
27
+ * users there already (`renderSteps`).
28
+ */
29
+ const offlineStepsMigration = (names, store, organizations, externalUser = false) => {
30
+ if (store) refuseNewer(store.lastSteps);
31
+ const had = store ? snapshotHad(store) : () => false;
32
+ const migration = migrationNames(names, externalUser || names.users.keyTable !== void 0);
33
+ const rendered = renderSteps(migration, names.names.modules, had, organizations);
34
+ const record = !store ? [stepRecordSql(names)] : store.stepRecord ? [] : [stepRecordMigration(names)];
35
+ if (rendered.length === 0 && record.length === 0) return;
36
+ const steps = rendered.length === 0 ? [] : [guardedStepsSql(names, rendered)];
37
+ const onTablesThere = ({ module, on = module }) => had(on, moduleSteps[on][0].step, on);
38
+ const checks = rendered.filter((part) => part.check && onTablesThere(part)).map((part) => statementsSql([part.check]));
39
+ const after = afterStepsSql(rendered);
31
40
  return {
32
- sql: lastSteps ? steps : [migrationsTableSql(names, true), steps].join("\n\n"),
33
- checks
41
+ sql: [...record, ...steps].join("\n\n"),
42
+ checks,
43
+ ...after && { after }
34
44
  };
35
45
  };
36
46
  //#endregion
@@ -0,0 +1,5 @@
1
+ import "../../names/identifiers.js";
2
+ //#region src/better-auth/store/offline/retired-watch.d.ts
3
+ /** The schema of the watch, made by the first migration that retires a column. */
4
+ export declare const retiredSchema = "retired";
5
+ //#endregion
@@ -0,0 +1,36 @@
1
+ import { generatedName } from "../../names/identifier-length.js";
2
+ import { ddl } from "../ddl.js";
3
+ import { sql } from "kysely";
4
+ //#region src/better-auth/store/offline/retired-watch.ts
5
+ /** The schema of the watch, made by the first migration that retires a column. */
6
+ const retiredSchema = "retired";
7
+ const triggerName = (column) => generatedName(`${column.name}_retired_writes`);
8
+ const watchTable = ddl`create table if not exists ${retiredSchema}.${"writes"} (
9
+ table_name text not null,
10
+ column_name text not null,
11
+ hour timestamptz not null,
12
+ writes bigint not null,
13
+ primary key (table_name, column_name, hour)
14
+ )`;
15
+ const countFunction = ddl`create or replace function ${retiredSchema}.${"count_write"}() returns trigger language plpgsql security definer set search_path = pg_catalog, pg_temp as $retired$
16
+ begin
17
+ insert into retired.writes as counted (table_name, column_name, hour, writes)
18
+ values (format('%I.%I', tg_table_schema, tg_table_name), tg_argv[0], date_trunc('hour', now()), 1)
19
+ on conflict (table_name, column_name, hour) do update set writes = counted.writes + 1;
20
+ return null;
21
+ end
22
+ $retired$`;
23
+ /** The statements that start the watch on `columns`: its schema, table and function, then a trigger on each column. */
24
+ const watchStatements = (columns) => {
25
+ if (columns.length === 0) return [];
26
+ return [
27
+ ddl`create schema if not exists ${retiredSchema}`,
28
+ watchTable,
29
+ countFunction,
30
+ ...columns.map(({ table, column }) => ddl`create trigger ${triggerName(column)} after insert or update of ${column} on ${table} for each row when (new.${column} is not null) execute function ${retiredSchema}.${"count_write"}(${sql.lit(column.name)})`)
31
+ ];
32
+ };
33
+ /** The statements that stop the watch on `columns`, once their module is on again; a column retired before the watch existed has none. */
34
+ const unwatchStatements = (columns) => columns.map(({ table, column }) => ddl`drop trigger if exists ${triggerName(column)} on ${table}`);
35
+ //#endregion
36
+ export { retiredSchema, unwatchStatements, watchStatements };
@@ -2,9 +2,10 @@ import { AuthSettings } from "../../auth-settings.js";
2
2
  import { StoreNames } from "../store-names.js";
3
3
  //#region src/better-auth/store/offline/settings-names.d.ts
4
4
  /**
5
- * The store's names from the app's `auth` settings alone, as the app's Better Auth resolves them, without building it:
5
+ * The store's names from the app's `auth` settings alone, the modules its features turn on, as the app's Better Auth
6
+ * resolves them, without building it:
6
7
  * no database, URL or secret. `ownUserIds`: the app's hooks give new users their ids (`generateUserId` in
7
8
  * auth/hooks.ts), which the hooks then decide over `generateUserId: 'uuid'`.
8
9
  */
9
- export declare const settingsStoreNames: (settings: Pick<AuthSettings, "schema" | "tables" | "users" | "generateUserId">, ownUserIds?: boolean) => StoreNames;
10
+ export declare const settingsStoreNames: (settings: Pick<AuthSettings, "schema" | "tables" | "users" | "generateUserId" | "organizations" | "mcp" | "openIdProvider" | "personalAccessTokens" | "personalMail" | "signInProviders" | "signInDevices">, ownUserIds?: boolean) => StoreNames;
10
11
  //#endregion
@@ -1,8 +1,11 @@
1
- import { userTable } from "../../user-table.js";
1
+ import { modulesOf } from "../../names/modules-on.js";
2
2
  import { resolveNames } from "../../names/resolve-names.js";
3
+ import { organizationsEnabled } from "../../organizations/options.js";
4
+ import { userTable } from "../../user-table.js";
3
5
  //#region src/better-auth/store/offline/settings-names.ts
4
6
  /**
5
- * The store's names from the app's `auth` settings alone, as the app's Better Auth resolves them, without building it:
7
+ * The store's names from the app's `auth` settings alone, the modules its features turn on, as the app's Better Auth
8
+ * resolves them, without building it:
6
9
  * no database, URL or secret. `ownUserIds`: the app's hooks give new users their ids (`generateUserId` in
7
10
  * auth/hooks.ts), which the hooks then decide over `generateUserId: 'uuid'`.
8
11
  */
@@ -12,7 +15,11 @@ const settingsStoreNames = (settings, ownUserIds = false) => {
12
15
  schema,
13
16
  names: resolveNames({
14
17
  schema,
15
- tables: settings.tables
18
+ tables: settings.tables,
19
+ modules: modulesOf({
20
+ ...settings,
21
+ organizations: organizationsEnabled(settings.organizations)
22
+ })
16
23
  }),
17
24
  users: userTable(settings.users),
18
25
  uuidIds: !ownUserIds && settings.generateUserId === "uuid"
@@ -17,7 +17,7 @@ export type StoreModel = {
17
17
  userKeyTable: string | null;
18
18
  /** The user table's JSON metadata column (`users.metadata`). */
19
19
  userMetadata: string | null;
20
- /** Whether every table whose rows belong to an organization has the column that names it. */
20
+ /** Whether every table whose rows belong to an organization has the column that names it while organizations are on. */
21
21
  scopedTablesCarryOrganization: boolean;
22
22
  /** Each module that is on: its last step applied and its tables by internal name. */
23
23
  modules: Partial<Record<ModuleId, {
@@ -33,4 +33,12 @@ export declare const latestSteps: (modules: readonly ModuleId[]) => LastSteps;
33
33
  export declare const storeModel: ({ schema, names, users, uuidIds }: StoreNames, lastSteps: LastSteps) => StoreModel;
34
34
  /** Every name the store has in the database: its schema, each table, `table.column` and index, sorted. */
35
35
  export declare const storeNamesList: (model: StoreModel) => string[];
36
+ /** A module turned off whose tables and rows the store keeps: the last step it had, and its tables' names then. */
37
+ export type KeptModule = {
38
+ module: ModuleId;
39
+ step: number;
40
+ tables: Record<string, ModelTable>;
41
+ };
42
+ /** `module` kept at `step`, its tables named as `names` would name them with it on. */
43
+ export declare const keptModule: ({ schema, names, users, uuidIds }: StoreNames, module: ModuleId, step: number) => KeptModule;
36
44
  //#endregion
@@ -1,9 +1,9 @@
1
- import { builtInModules } from "../../names/modules/index.js";
1
+ import { allModules } from "../../names/modules-on.js";
2
+ import { resolveNames } from "../../names/resolve-names.js";
2
3
  import { moduleSteps } from "../steps/index.js";
3
4
  //#region src/better-auth/store/offline/store-model.ts
4
5
  /** The last step of each module of `modules`, as this version of Protobase ships them. */
5
6
  const latestSteps = (modules) => Object.fromEntries(modules.map((module) => [module, moduleSteps[module].at(-1).step]));
6
- const declaredIndexes = (internal) => builtInModules.flatMap((module) => module.tables[internal]?.indexes ?? []);
7
7
  /** The model of a store with `names` at `lastSteps`: a module `lastSteps` leaves out is not in it. */
8
8
  const storeModel = ({ schema, names, users, uuidIds }, lastSteps) => {
9
9
  const tables = Object.values(names.tables);
@@ -13,14 +13,14 @@ const storeModel = ({ schema, names, users, uuidIds }, lastSteps) => {
13
13
  ids: uuidIds ? "uuid" : "text",
14
14
  userKeyTable: users.keyTable ? `${users.keyTable.schema}.${users.keyTable.table}` : null,
15
15
  userMetadata: users.metadata ?? null,
16
- scopedTablesCarryOrganization: tables.filter((table) => table.scope === "organization").every((table) => "organization_id" in table.columns),
16
+ scopedTablesCarryOrganization: !names.modules.includes("organizations") || tables.filter((table) => table.scope === "organization").every((table) => "organization_id" in table.columns),
17
17
  modules: Object.fromEntries(modules.map((module) => [module, {
18
18
  lastStep: lastSteps[module],
19
19
  tables: Object.fromEntries(tables.filter((table) => table.module === module).map((table) => [table.internal, {
20
20
  name: table.name,
21
21
  scope: table.scope,
22
22
  columns: Object.fromEntries(Object.values(table.columns).map((column) => [column.internal, column.name])),
23
- indexes: Object.fromEntries(declaredIndexes(table.internal).map((index) => [index, table.index(index).name]))
23
+ indexes: Object.fromEntries(Object.keys(table.indexes).map((index) => [index, table.index(index).name]))
24
24
  }]))
25
25
  }]))
26
26
  };
@@ -36,5 +36,22 @@ const storeNamesList = (model) => {
36
36
  ...Object.values(table.indexes).map((index) => `${prefix}${index}`)
37
37
  ])].sort();
38
38
  };
39
+ /** `module` kept at `step`, its tables named as `names` would name them with it on. */
40
+ const keptModule = ({ schema, names, users, uuidIds }, module, step) => {
41
+ const withIt = resolveNames({
42
+ ...names.input,
43
+ modules: allModules.filter((other) => other === module || names.modules.includes(other))
44
+ });
45
+ return {
46
+ module,
47
+ step,
48
+ tables: storeModel({
49
+ schema,
50
+ names: withIt,
51
+ users,
52
+ uuidIds
53
+ }, { [module]: step }).modules[module].tables
54
+ };
55
+ };
39
56
  //#endregion
40
- export { latestSteps, storeModel, storeNamesList };
57
+ export { keptModule, latestSteps, storeModel, storeNamesList };
@@ -1,5 +1,5 @@
1
- import { plainStoreDb } from "./store-db.js";
2
1
  import { authStoreTables } from "../auth-tables.js";
2
+ import { plainStoreDb } from "./store-db.js";
3
3
  import { sql } from "kysely";
4
4
  //#region src/better-auth/store/resources-outside.ts
5
5
  const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
@@ -0,0 +1,13 @@
1
+ import { ModuleId } from "../names/modules/index.js";
2
+ import "../names/resolve-names.js";
3
+ import "./store-names.js";
4
+ import "./steps/render.js";
5
+ import { Kysely } from "kysely";
6
+ //#region src/better-auth/store/step-record.d.ts
7
+ /** A part of a step the store applied. */
8
+ export type AppliedStep = {
9
+ module: ModuleId;
10
+ step: number;
11
+ target: ModuleId;
12
+ };
13
+ //#endregion
@@ -0,0 +1,59 @@
1
+ import { builtInModules } from "../names/modules/index.js";
2
+ import { ddl } from "./ddl.js";
3
+ import { moduleSteps } from "./steps/index.js";
4
+ import { sql } from "kysely";
5
+ //#region src/better-auth/store/step-record.ts
6
+ /** `Had` over a list of applied parts. */
7
+ const hadOf = (applied) => (module, step, target) => applied.some((part) => part.module === module && part.step === step && part.target === target);
8
+ /** The table, in the store's schema, as the store's names resolve `auth_steps`. */
9
+ const stepRecordTable = ({ names }) => names.table("auth_steps");
10
+ /** The statement that makes the table when it is missing. */
11
+ const createStepRecord = (names) => {
12
+ const table = stepRecordTable(names);
13
+ const { module, step, target, applied_at } = table.columns;
14
+ return ddl`create table if not exists ${table} (
15
+ ${module} text not null,
16
+ ${step} integer not null,
17
+ ${target} text not null,
18
+ ${applied_at} timestamptz,
19
+ primary key (${module}, ${step}, ${target})
20
+ )`;
21
+ };
22
+ /** The part a rendered step is. */
23
+ const partOf = (part) => ({
24
+ module: part.module,
25
+ step: part.step.step,
26
+ target: part.on ?? part.module
27
+ });
28
+ /** The statement that records `parts` as applied, now. */
29
+ const recordSteps = (names, parts) => {
30
+ const table = stepRecordTable(names);
31
+ const { module, step, target, applied_at } = table.columns;
32
+ const rows = parts.map((part) => ddl`(${sql.lit(part.module)}, ${sql.lit(part.step)}, ${sql.lit(part.target)}, now())`);
33
+ return ddl`insert into ${table} (${module}, ${step}, ${target}, ${applied_at}) values ${sql.join(rows, sql`, `)}`;
34
+ };
35
+ /** The condition that holds once `part` is recorded. */
36
+ const stepRecorded = (names, part) => {
37
+ const table = stepRecordTable(names);
38
+ const { module, step, target } = table.columns;
39
+ const key = partOf(part);
40
+ return ddl`exists (select from ${table} where ${module} = ${sql.lit(key.module)} and ${step} = ${sql.lit(key.step)} and ${target} = ${sql.lit(key.target)})`;
41
+ };
42
+ const known = (part) => builtInModules.some(({ id }) => id === part.module) && builtInModules.some(({ id }) => id === part.target) && moduleSteps[part.module].some(({ step }) => step === part.step);
43
+ /** Refuses a recorded part of a step this version does not ship, such as one a newer Protobase applied. */
44
+ const refuseUnshipped = (rows) => {
45
+ const unknown = rows.filter((row) => !known(row));
46
+ if (unknown.length > 0) throw new Error(`The auth store records ${unknown.map((row) => `step ${row.step} of ${row.module}`).join(", ")}, which this version of Protobase does not ship; upgrade Protobase`);
47
+ };
48
+ /** The parts the store recorded; `undefined` when it has no `auth_steps`. Refuses a step this version does not ship. */
49
+ const appliedSteps = async (db, names) => {
50
+ const table = stepRecordTable(names);
51
+ const [found] = (await sql`select to_regclass(${String(table)}) is not null as found`.execute(db)).rows;
52
+ if (!found?.found) return;
53
+ const { module, step, target } = table.columns;
54
+ const { rows } = await sql`select ${module} as module, ${step} as step, ${target} as target from ${table} order by 1, 2, 3`.execute(db);
55
+ refuseUnshipped(rows);
56
+ return rows;
57
+ };
58
+ //#endregion
59
+ export { appliedSteps, createStepRecord, hadOf, partOf, recordSteps, refuseUnshipped, stepRecordTable, stepRecorded };
@@ -11,6 +11,7 @@ import { senderSharing } from "./mail-senders/005-sender-sharing.js";
11
11
  import { mcp } from "./mcp/001-mcp.js";
12
12
  import { organizations } from "./organizations/001-organizations.js";
13
13
  import { organizationIndex } from "./organizations/002-organization-index.js";
14
+ import { defaultOrganization } from "./organizations/003-default-organization.js";
14
15
  import { passkeys } from "./passkeys/001-passkeys.js";
15
16
  import { rpIdIndex } from "./passkeys/002-rp-id-index.js";
16
17
  import { personalAccessTokens } from "./personal-access-tokens/001-personal-access-tokens.js";
@@ -33,7 +34,11 @@ const moduleSteps = {
33
34
  passkeys: [passkeys, rpIdIndex],
34
35
  sign_in_policy: [signInPolicy],
35
36
  staff_sign_in: [staffSignIn, staffSignInIndexes],
36
- organizations: [organizations, organizationIndex],
37
+ organizations: [
38
+ organizations,
39
+ organizationIndex,
40
+ defaultOrganization
41
+ ],
37
42
  mcp: [mcp],
38
43
  personal_access_tokens: [personalAccessTokens],
39
44
  mail_senders: [
@@ -0,0 +1,7 @@
1
+ //#region src/better-auth/store/steps/legacy-versions.d.ts
2
+ /** Each version with the name its row in `auth_migrations` holds. */
3
+ export declare const legacyVersions: {
4
+ version: number;
5
+ name: string;
6
+ }[];
7
+ //#endregion
@@ -68,6 +68,10 @@ const legacyVersions = [
68
68
  {
69
69
  version: 17,
70
70
  name: "sender_sharing"
71
+ },
72
+ {
73
+ version: 18,
74
+ name: "default_organization"
71
75
  }
72
76
  ];
73
77
  /** The version the store is at once every step is applied. */