@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
@@ -1,4 +1,5 @@
1
1
  import { parseAppRoles } from "./app-roles.js";
2
+ import { acrossOrganizations, inOrganization } from "../../organization-scope/sign-in-organization.js";
2
3
  import { sql } from "kysely";
3
4
  //#region src/better-auth/organizations/store.ts
4
5
  /** Better Auth's `findMany` returns 100 rows unless told otherwise; these lists are read whole. */
@@ -14,8 +15,9 @@ const organizationRoleOf = (member) => {
14
15
  };
15
16
  /** A member who is an owner, in SQL: `owner` is one of the names in their role, as `organizationRoleOf` reads it. */
16
17
  const isOwner = (role) => sql`'owner' = any(regexp_split_to_array(regexp_replace(${role}, '^\\s+|\\s+$', '', 'g'), '\\s*,\\s*'))`;
18
+ /** Someone's membership of the organization named, read in that organization. */
17
19
  const findMember = async (adapter, where) => {
18
- const row = await adapter.findOne({
20
+ const row = await inOrganization(where.organizationId, () => adapter.findOne({
19
21
  model: "member",
20
22
  where: [{
21
23
  field: "organizationId",
@@ -24,27 +26,29 @@ const findMember = async (adapter, where) => {
24
26
  field: "userId",
25
27
  value: where.userId
26
28
  }]
27
- });
29
+ }));
28
30
  return row ? memberOf(row) : void 0;
29
31
  };
32
+ /** A membership by its id, whatever its organization: the caller's right to it is checked in its organization next. */
30
33
  const findMemberById = async (adapter, id) => {
31
- const row = await adapter.findOne({
34
+ const row = await acrossOrganizations("a member is found by its id, before the caller's right is checked in its organization", () => adapter.findOne({
32
35
  model: "member",
33
36
  where: [{
34
37
  field: "id",
35
38
  value: id
36
39
  }]
37
- });
40
+ }));
38
41
  return row ? memberOf(row) : void 0;
39
42
  };
40
- const membershipsOf = async (adapter, userId) => (await adapter.findMany({
43
+ /** Every organization someone is a member of. */
44
+ const membershipsOf = async (adapter, userId) => (await acrossOrganizations("a user lists their own memberships, one in each organization", () => adapter.findMany({
41
45
  model: "member",
42
46
  where: [{
43
47
  field: "userId",
44
48
  value: userId
45
49
  }],
46
50
  limit: everyRow
47
- })).map(memberOf);
51
+ }))).map(memberOf);
48
52
  const findOrganization = (adapter, id) => adapter.findOne({
49
53
  model: "organization",
50
54
  where: [{
@@ -52,13 +56,14 @@ const findOrganization = (adapter, id) => adapter.findOne({
52
56
  value: id
53
57
  }]
54
58
  });
55
- const setAppRoles = (adapter, memberId, appRoles) => adapter.update({
59
+ /** Sets a member's app roles, in the member's organization. */
60
+ const setAppRoles = (adapter, member, appRoles) => inOrganization(member.organizationId, () => adapter.update({
56
61
  model: "member",
57
62
  where: [{
58
63
  field: "id",
59
- value: memberId
64
+ value: member.id
60
65
  }],
61
66
  update: { appRoles: [...appRoles] }
62
- });
67
+ }));
63
68
  //#endregion
64
69
  export { everyRow, findMember, findMemberById, findOrganization, isOwner, membershipsOf, organizationRoleOf, setAppRoles };
@@ -0,0 +1,23 @@
1
+ import { sql } from "kysely";
2
+ //#region src/better-auth/personal-access-tokens/pinned-tokens.ts
3
+ /** Stores a token made in the pinned organization `organizationId`, as `storeToken` stores one. */
4
+ const storePinnedToken = async (store, kept, data) => {
5
+ const token = kept.table("personal_access_token");
6
+ const c = token.columns;
7
+ const [row] = (await sql`insert into ${token} (id, ${c.user_id}, ${c.name}, ${c.token_hash}, ${c.role}, ${c.organization_id}, ${c.created_at}, ${c.expires_at})
8
+ values (${store.newId}, ${data.userId}, ${data.name}, ${data.tokenHash}, ${data.role}, ${data.organizationId}, ${data.createdAt}, ${data.expiresAt ?? null})
9
+ returning id::text as id`.execute(store.db)).rows;
10
+ return {
11
+ ...data,
12
+ id: row.id,
13
+ lastUsedAt: null
14
+ };
15
+ };
16
+ /** The organization the token `id` was made in, `null` for one made in none, such as one made before tokens kept theirs while organizations were off. */
17
+ const tokenOrganization = async (store, kept, id) => {
18
+ const token = kept.table("personal_access_token");
19
+ const [row] = (await sql`select ${token.columns.organization_id}::text as organization_id from ${token} where id = ${id}`.execute(store.db)).rows;
20
+ return row?.organization_id ?? null;
21
+ };
22
+ //#endregion
23
+ export { storePinnedToken, tokenOrganization };
@@ -1,6 +1,8 @@
1
1
  import { everyRow } from "../organizations/store.js";
2
2
  import { sessionRoles } from "../roles/session-role.js";
3
+ import { storeSqlOf } from "../store/store-sql.js";
3
4
  import { newToken, tokenHash } from "./token-format.js";
5
+ import { storePinnedToken } from "./pinned-tokens.js";
4
6
  import { deleteToken, listedToken, personalAccessTokenModel, storeToken, tokensOf } from "./token-store.js";
5
7
  import * as z$1 from "zod";
6
8
  import { APIError, createAuthEndpoint, sessionMiddleware } from "better-auth/api";
@@ -18,6 +20,10 @@ const noRole = {
18
20
  code: "NO_ROLE",
19
21
  message: "You have no role in this app here, so a token could do nothing."
20
22
  };
23
+ const noOrganization = {
24
+ code: "NO_ORGANIZATION",
25
+ message: "Choose the organization the token works in first."
26
+ };
21
27
  const idsIn = (values) => [{
22
28
  field: "id",
23
29
  value: values,
@@ -40,63 +46,78 @@ const labelsFor = async (adapter, definitions, rows) => {
40
46
  * The signed-in person's personal access tokens, which act as them from a script:
41
47
  * `GET /account/personal-access-tokens` lists them, newest first, without the tokens themselves;
42
48
  * `POST /account/personal-access-tokens/create { name, expiresInDays? }` makes one with the role and organization the
43
- * session works with, and answers the token, once, beside the listed entry;
49
+ * session works with, and answers the token, once, beside the listed entry; with `organizations`, a session without an
50
+ * active organization makes none, as every token works in one; with `pinned`, while organizations are off after being
51
+ * on, every token is made in the organization `pin` reads, in its column as `kept` names it, which the account page
52
+ * does not name;
44
53
  * `POST /account/personal-access-tokens/revoke { id }` deletes one, so it stops at its next request; one that is gone
45
54
  * already is no error. Each acts on the session's own person only. The store keeps each token's SHA-256 hash alone.
46
55
  */
47
- const personalAccessTokensPlugin = ({ options, definitions, names }) => ({
48
- id: "protobase-personal-access-tokens",
49
- schema: names.tables(personalAccessTokenModel),
50
- endpoints: {
51
- listPersonalAccessTokens: createAuthEndpoint(personalAccessTokenPaths.list, {
52
- method: "GET",
53
- use: [sessionMiddleware]
54
- }, async (ctx) => {
55
- const rows = await tokensOf(ctx.context.adapter, ctx.context.session.user.id);
56
- const labels = await labelsFor(ctx.context.adapter, definitions, rows);
57
- return ctx.json({ tokens: rows.map((row) => listedToken(row, labels)) });
58
- }),
59
- createPersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.create, {
60
- method: "POST",
61
- use: [sessionMiddleware],
62
- body: z$1.object({
63
- name: z$1.string().trim().min(1).max(100),
64
- expiresInDays: z$1.number().int().min(1).max(maxTokenDays).optional()
56
+ const personalAccessTokensPlugin = ({ options, definitions, names, organizations, pinned }) => {
57
+ const shown = (row) => organizations ? row : {
58
+ ...row,
59
+ organizationId: null
60
+ };
61
+ return {
62
+ id: "protobase-personal-access-tokens",
63
+ schema: names.tables(personalAccessTokenModel),
64
+ endpoints: {
65
+ listPersonalAccessTokens: createAuthEndpoint(personalAccessTokenPaths.list, {
66
+ method: "GET",
67
+ use: [sessionMiddleware]
68
+ }, async (ctx) => {
69
+ const rows = (await tokensOf(ctx.context.adapter, ctx.context.session.user.id)).map(shown);
70
+ const labels = await labelsFor(ctx.context.adapter, definitions, rows);
71
+ return ctx.json({ tokens: rows.map((row) => listedToken(row, labels)) });
72
+ }),
73
+ createPersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.create, {
74
+ method: "POST",
75
+ use: [sessionMiddleware],
76
+ body: z$1.object({
77
+ name: z$1.string().trim().min(1).max(100),
78
+ expiresInDays: z$1.number().int().min(1).max(maxTokenDays).optional()
79
+ })
80
+ }, async (ctx) => {
81
+ const { user, session } = ctx.context.session;
82
+ if (organizations && !session.activeOrganizationId) throw new APIError("FORBIDDEN", noOrganization);
83
+ const context = ctx.context;
84
+ const { active } = await sessionRoles(context, {
85
+ user,
86
+ session
87
+ });
88
+ if (!active) throw new APIError("FORBIDDEN", noRole);
89
+ const token = newToken(options.prefix);
90
+ const now = /* @__PURE__ */ new Date();
91
+ const data = {
92
+ userId: user.id,
93
+ name: ctx.body.name,
94
+ tokenHash: await tokenHash(token),
95
+ role: active,
96
+ organizationId: session.activeOrganizationId ?? null,
97
+ createdAt: now,
98
+ expiresAt: ctx.body.expiresInDays === void 0 ? null : new Date(now.getTime() + ctx.body.expiresInDays * dayMs)
99
+ };
100
+ const pin = await pinned?.pin();
101
+ const row = pin ? await storePinnedToken(storeSqlOf(ctx.context), pinned.kept, {
102
+ ...data,
103
+ organizationId: pin.id
104
+ }) : await storeToken(ctx.context.adapter, data);
105
+ const labels = await labelsFor(ctx.context.adapter, definitions, [shown(row)]);
106
+ return ctx.json({
107
+ token,
108
+ personalAccessToken: listedToken(shown(row), labels)
109
+ });
110
+ }),
111
+ revokePersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.revoke, {
112
+ method: "POST",
113
+ use: [sessionMiddleware],
114
+ body: z$1.object({ id: z$1.string().min(1) })
115
+ }, async (ctx) => {
116
+ await deleteToken(ctx.context.adapter, ctx.context.session.user.id, ctx.body.id);
117
+ return ctx.json({ revoked: true });
65
118
  })
66
- }, async (ctx) => {
67
- const { user, session } = ctx.context.session;
68
- const context = ctx.context;
69
- const { active } = await sessionRoles(context, {
70
- user,
71
- session
72
- });
73
- if (!active) throw new APIError("FORBIDDEN", noRole);
74
- const token = newToken(options.prefix);
75
- const now = /* @__PURE__ */ new Date();
76
- const row = await storeToken(ctx.context.adapter, {
77
- userId: user.id,
78
- name: ctx.body.name,
79
- tokenHash: await tokenHash(token),
80
- role: active,
81
- organizationId: session.activeOrganizationId ?? null,
82
- createdAt: now,
83
- expiresAt: ctx.body.expiresInDays === void 0 ? null : new Date(now.getTime() + ctx.body.expiresInDays * dayMs)
84
- });
85
- const labels = await labelsFor(ctx.context.adapter, definitions, [row]);
86
- return ctx.json({
87
- token,
88
- personalAccessToken: listedToken(row, labels)
89
- });
90
- }),
91
- revokePersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.revoke, {
92
- method: "POST",
93
- use: [sessionMiddleware],
94
- body: z$1.object({ id: z$1.string().min(1) })
95
- }, async (ctx) => {
96
- await deleteToken(ctx.context.adapter, ctx.context.session.user.id, ctx.body.id);
97
- return ctx.json({ revoked: true });
98
- })
99
- }
100
- });
119
+ }
120
+ };
121
+ };
101
122
  //#endregion
102
123
  export { maxTokenDays, personalAccessTokenPaths, personalAccessTokensPlugin };
@@ -17,19 +17,22 @@ const refused = () => unauthorized("The personal access token is invalid, expire
17
17
  * as a token's does (`checkUserStanding`): exist, not be banned, and still hold the token's role where it works, in its
18
18
  * organization with organizations on. The session has that one role and organization, as a token of the session that
19
19
  * made it would, and no `signIn`, so what only the person's own sign-in may do is refused. Use is noted at most once a
20
- * minute (`noteUse`).
20
+ * minute (`noteUse`). While organizations are off after being on, a token works only when made in the pinned
21
+ * organization, and its user is still a member there; any other is refused as an unknown one is.
21
22
  */
22
- const personalAccessTokenSessions = ({ prefix, context, organizations, tenant }) => async (token, now = /* @__PURE__ */ new Date()) => {
23
+ const personalAccessTokenSessions = ({ prefix, context, organizations, pinned, tenant }) => async (token, now = /* @__PURE__ */ new Date()) => {
23
24
  if (!isWellFormed(token, prefix)) throw refused();
24
25
  const store = await context();
25
26
  const row = await findTokenByHash(store.adapter, await tokenHash(token));
26
27
  if (!row || row.expiresAt && new Date(row.expiresAt) <= now) throw refused();
28
+ const pin = organizations ? void 0 : (await pinned?.pin())?.id;
29
+ if (pin !== void 0 && await pinned.organizationOf(store, row.id) !== pin) throw refused();
27
30
  const organizationId = organizations ? row.organizationId ?? void 0 : void 0;
28
31
  const organizationRole = await checkUserStanding(store, {
29
32
  userId: row.userId,
30
33
  roles: [row.role],
31
34
  ...organizationId && { organizationId }
32
- }, organizations, now);
35
+ }, organizations, now, pin);
33
36
  await noteUse(store.adapter, row, now);
34
37
  const roles = [row.role].filter((role) => role !== noGlobalRole);
35
38
  const tenantValue = tenant === void 0 ? organizationId : typeof tenant === "function" ? await tenant() : tenant;
@@ -1,3 +1,4 @@
1
+ import { acrossOrganizations, inOrganization } from "../../organization-scope/sign-in-organization.js";
1
2
  import { everyRow } from "../organizations/store.js";
2
3
  //#region src/better-auth/personal-access-tokens/token-store.ts
3
4
  /** Better Auth's model for personal access tokens: one row per token, holding its hash and never the token. */
@@ -13,15 +14,17 @@ const listedToken = (row, labels) => ({
13
14
  ...row.expiresAt && { expiresAt: iso(row.expiresAt) },
14
15
  ...row.lastUsedAt && { lastUsedAt: iso(row.lastUsedAt) }
15
16
  });
16
- const findTokenByHash = (adapter, tokenHash) => adapter.findOne({
17
+ const organizationOf = (row) => row.organizationId ?? void 0;
18
+ /** The token of a hash, whatever its organization. */
19
+ const findTokenByHash = (adapter, tokenHash) => acrossOrganizations("a token is looked up by its hash, a key unique across the app, before its organization is known", () => adapter.findOne({
17
20
  model: personalAccessTokenModel,
18
21
  where: [{
19
22
  field: "tokenHash",
20
23
  value: tokenHash
21
24
  }]
22
- });
23
- /** The user's tokens, newest first. */
24
- const tokensOf = (adapter, userId) => adapter.findMany({
25
+ }));
26
+ /** The user's tokens, newest first, from every organization. */
27
+ const tokensOf = (adapter, userId) => acrossOrganizations("a user lists their own tokens, each made in an organization of theirs", () => adapter.findMany({
25
28
  model: personalAccessTokenModel,
26
29
  where: [{
27
30
  field: "userId",
@@ -32,13 +35,14 @@ const tokensOf = (adapter, userId) => adapter.findMany({
32
35
  direction: "desc"
33
36
  },
34
37
  limit: everyRow
35
- });
36
- const storeToken = (adapter, data) => adapter.create({
38
+ }));
39
+ /** Stores a token, in the organization it works in. */
40
+ const storeToken = (adapter, data) => inOrganization(organizationOf(data), () => adapter.create({
37
41
  model: personalAccessTokenModel,
38
42
  data
39
- });
43
+ }));
40
44
  /** Deletes the user's token `id`; one that is not theirs, or gone already, is left as it is. */
41
- const deleteToken = (adapter, userId, id) => adapter.deleteMany({
45
+ const deleteToken = (adapter, userId, id) => acrossOrganizations("a user deletes one of their own tokens, made in any organization of theirs", () => adapter.deleteMany({
42
46
  model: personalAccessTokenModel,
43
47
  where: [{
44
48
  field: "id",
@@ -47,20 +51,20 @@ const deleteToken = (adapter, userId, id) => adapter.deleteMany({
47
51
  field: "userId",
48
52
  value: userId
49
53
  }]
50
- });
54
+ }));
51
55
  /** How stale `lastUsedAt` may get: a script's many requests update it once a minute, not on each one. */
52
56
  const lastUsedPrecisionMs = 6e4;
53
57
  /** Notes that the token was used `now`, unless it was within the last minute. */
54
58
  const noteUse = async (adapter, row, now) => {
55
59
  if (row.lastUsedAt && now.getTime() - new Date(row.lastUsedAt).getTime() < 6e4) return;
56
- await adapter.update({
60
+ await inOrganization(organizationOf(row), () => adapter.update({
57
61
  model: personalAccessTokenModel,
58
62
  where: [{
59
63
  field: "id",
60
64
  value: row.id
61
65
  }],
62
66
  update: { lastUsedAt: now }
63
- });
67
+ }));
64
68
  };
65
69
  //#endregion
66
70
  export { deleteToken, findTokenByHash, lastUsedPrecisionMs, listedToken, noteUse, personalAccessTokenModel, storeToken, tokensOf };
@@ -1,10 +1,12 @@
1
+ import { allModules } from "../names/modules-on.js";
1
2
  import { resolveNames } from "../names/resolve-names.js";
2
3
  import { ddl } from "./ddl.js";
3
- import { recordMigrations } from "./migrations-table.js";
4
- import { legacyVersions } from "./steps/legacy-versions.js";
5
- import { statementsSql } from "./migration-sql.js";
6
4
  import { moduleSteps } from "./steps/index.js";
5
+ import { recordSteps } from "./step-record.js";
6
+ import { statementsSql } from "./migration-sql.js";
7
+ import { legacyVersions } from "./steps/legacy-versions.js";
7
8
  import { renderSteps } from "./steps/render.js";
9
+ import { stepsOfVersions } from "./legacy-record.js";
8
10
  import { migrationNames } from "./steps/step.js";
9
11
  import { sql } from "kysely";
10
12
  //#region src/better-auth/store/adoption.ts
@@ -12,9 +14,17 @@ const key = ({ table, column }) => `${table}.${column}`;
12
14
  const columnsIn = async (db, schema) => (await sql`select table_name as "table", column_name as "column", udt_name as "type" from information_schema.columns
13
15
  where table_schema = ${schema === void 0 ? sql`current_schema()` : schema} order by table_name, ordinal_position`.execute(db)).rows;
14
16
  const scratchSchema = "protobase_auth_adoption";
17
+ const scratchOrganizations = {
18
+ default: {
19
+ id: "00000000-0000-0000-0000-000000000000",
20
+ name: "scratch",
21
+ slug: "scratch"
22
+ },
23
+ existingUsersRole: "scratch"
24
+ };
15
25
  /**
16
- * For each version, the columns its steps make: every step of every module runs in a scratch schema, in a transaction
17
- * that is rolled back.
26
+ * For each version, the columns its steps make: every step of every module, as the former chain made them with every
27
+ * module on, runs in a scratch schema, in a transaction that is rolled back.
18
28
  */
19
29
  const madeColumns = async (db, names) => {
20
30
  const tx = await db.startTransaction().execute();
@@ -22,7 +32,8 @@ const madeColumns = async (db, names) => {
22
32
  await sql`create schema ${sql.id(scratchSchema)}`.execute(tx);
23
33
  const scratch = resolveNames({
24
34
  ...names.names.input,
25
- schema: scratchSchema
35
+ schema: scratchSchema,
36
+ modules: allModules
26
37
  });
27
38
  const made = new Map(legacyVersions.map(({ version }) => [version, []]));
28
39
  let before = [];
@@ -30,7 +41,7 @@ const madeColumns = async (db, names) => {
30
41
  ...names,
31
42
  schema: scratchSchema,
32
43
  names: scratch
33
- }), scratch.modules, () => false)) {
44
+ }), scratch.modules, () => false, scratchOrganizations)) {
34
45
  for (const statement of part.statements) await statement.execute(tx);
35
46
  const after = await columnsIn(tx, scratchSchema);
36
47
  made.get(part.version).push(...after.filter((column) => !before.some((earlier) => key(earlier) === key(column))));
@@ -43,7 +54,11 @@ const madeColumns = async (db, names) => {
43
54
  /** Whether the store has any table of the steps besides the user table, which may be another system's. */
44
55
  const storeHasTables = async (db, names) => {
45
56
  const tables = new Set((await columnsIn(db, names.schema)).map((column) => column.table));
46
- return Object.values(moduleSteps).some((steps) => steps.some((step) => step.tables.some((table) => tables.has(names.names.tables[table].name))));
57
+ const every = resolveNames({
58
+ ...names.names.input,
59
+ modules: allModules
60
+ });
61
+ return Object.values(moduleSteps).some((steps) => steps.some((step) => step.tables.some((table) => tables.has(every.tables[table].name))));
47
62
  };
48
63
  /** Which versions the store matches and which it still needs; a version it matches only partly is an error. */
49
64
  const planAdoption = async (db, names) => {
@@ -70,7 +85,7 @@ const planAdoption = async (db, names) => {
70
85
  return adoption;
71
86
  };
72
87
  /**
73
- * The SQL that records the adopted migrations as applied, once it finds every column they make with its type; it
88
+ * The SQL that records the steps of the adopted versions as applied, once it finds every column they make with its type; it
74
89
  * stops the migration, naming what it lacks, on a database that differs from the one it was written from.
75
90
  */
76
91
  const adoptionSql = (names, adopted) => {
@@ -91,7 +106,7 @@ begin
91
106
  end if;
92
107
  end
93
108
  $adopt$`;
94
- return `-- The auth store an earlier Protobase made, without a record of its migrations, adopted: ${adopted.map(({ migration }) => `${migration.version} ${migration.name}`).join(", ")}\n-- recorded as applied, once every table and column they make is there.\n${statementsSql([check, recordMigrations(names, adopted.map(({ migration }) => migration))])}`;
109
+ return `-- The auth store an earlier Protobase made, without a record of its migrations, adopted: ${adopted.map(({ migration }) => `${migration.version} ${migration.name}`).join(", ")}\n-- recorded as applied, once every table and column they make is there.\n${statementsSql([check, recordSteps(names, stepsOfVersions(adopted.map(({ migration }) => migration.version)))])}`;
95
110
  };
96
111
  //#endregion
97
112
  export { adoptionSql, planAdoption, storeHasTables };
@@ -1,5 +1,5 @@
1
- import { plainStoreDb } from "./store-db.js";
2
1
  import { storeNames } from "./store-names.js";
2
+ import { plainStoreDb } from "./store-db.js";
3
3
  import { sql } from "kysely";
4
4
  import { getSchema } from "better-auth/db";
5
5
  import { getMigrations } from "better-auth/db/migration";
@@ -31,10 +31,11 @@ const authSchemaDrift = async (auth) => {
31
31
  } : auth.options;
32
32
  const { toBeCreated, toBeAdded, toBeAddedIndexes, schemaProblems } = await getMigrations(options, { throwOnUnsafe: false });
33
33
  const view = auth.users.keyTable ? auth.names.table("user").name : void 0;
34
+ const compared = ({ table }) => table !== view && !auth.keptTables.includes(table);
34
35
  const tables = [
35
- ...toBeCreated.filter(({ table }) => table !== view).map(({ table }) => `lacks the table ${table}`),
36
- ...toBeAdded.filter(({ table }) => table !== view).flatMap(({ table, fields }) => Object.keys(fields).map((field) => `lacks the column ${table}.${field}`)),
37
- ...toBeAddedIndexes.filter(({ table }) => table !== view).map(({ name }) => `lacks the index ${name}`),
36
+ ...toBeCreated.filter(compared).map(({ table }) => `lacks the table ${table}`),
37
+ ...toBeAdded.filter(compared).flatMap(({ table, fields }) => Object.keys(fields).map((field) => `lacks the column ${table}.${field}`)),
38
+ ...toBeAddedIndexes.filter(compared).map(({ name }) => `lacks the index ${name}`),
38
39
  ...schemaProblems
39
40
  ];
40
41
  return view ? [...tables, ...await userViewDrift(auth)] : tables;
@@ -0,0 +1,10 @@
1
+ import "../names/resolve-names.js";
2
+ import { StoreNames } from "./store-names.js";
3
+ import { AppliedStep } from "./step-record.js";
4
+ import { Kysely } from "kysely";
5
+ //#region src/better-auth/store/legacy-record.d.ts
6
+ /** The parts the store applied, from the versions it recorded: every part of each version. */
7
+ export declare const stepsOfVersions: (versions: readonly number[]) => AppliedStep[];
8
+ /** The record of the store's steps, made when it is missing and filled from `auth_migrations`, for a store that recorded versions. */
9
+ export declare const stepRecordMigration: (names: StoreNames) => string;
10
+ //#endregion
@@ -0,0 +1,56 @@
1
+ import { allModules } from "../names/modules-on.js";
2
+ import { ddl } from "./ddl.js";
3
+ import { moduleSteps } from "./steps/index.js";
4
+ import { stepRecordTable } from "./step-record.js";
5
+ import { guardedBlock, stepRecordSql } from "./migration-sql.js";
6
+ import { latestStoreVersion } from "./steps/legacy-versions.js";
7
+ import { partVersion } from "./steps/render.js";
8
+ import { sql } from "kysely";
9
+ //#region src/better-auth/store/legacy-record.ts
10
+ /** The table, in the store's schema, as the store's names resolve `auth_migrations`. */
11
+ const legacyRecordTable = ({ names }) => names.table("auth_migrations");
12
+ /** Every part of every step with the version of the former chain that made it, as that chain made them, every module on. */
13
+ const legacyParts = () => allModules.flatMap((module) => moduleSteps[module].flatMap((step) => [module, ...allModules.filter((target) => step.adds?.[target])].map((target) => ({
14
+ module,
15
+ step: step.step,
16
+ target,
17
+ version: partVersion(module, step, target)
18
+ }))));
19
+ /** The parts the store applied, from the versions it recorded: every part of each version. */
20
+ const stepsOfVersions = (versions) => {
21
+ const newer = versions.filter((version) => version > latestStoreVersion);
22
+ if (newer.length > 0) throw new Error(`The auth store records version ${newer.join(", ")} in auth_migrations, which this version of Protobase does not ship; upgrade Protobase`);
23
+ return legacyParts().filter((part) => versions.includes(part.version)).map(({ module, step, target }) => ({
24
+ module,
25
+ step,
26
+ target
27
+ }));
28
+ };
29
+ /** The versions the store recorded, in order; `undefined` when it has no `auth_migrations`. */
30
+ const appliedVersions = async (db, names) => {
31
+ const table = legacyRecordTable(names);
32
+ const [found] = (await sql`select to_regclass(${String(table)}) is not null as found`.execute(db)).rows;
33
+ if (!found?.found) return;
34
+ const { version } = table.columns;
35
+ return (await sql`select ${version} as version from ${table} order by ${version}`.execute(db)).rows.map((row) => row.version);
36
+ };
37
+ /**
38
+ * The statement that fills `auth_steps` from `auth_migrations`, once that table is there: every part of each version
39
+ * it records, at the time it recorded it. A part recorded already is left as it is.
40
+ */
41
+ const fillFromLegacySql = (names) => {
42
+ const legacy = legacyRecordTable(names);
43
+ const steps = stepRecordTable(names);
44
+ const { module, step, target, applied_at } = steps.columns;
45
+ const parts = legacyParts().map((part) => ddl`(${sql.lit(part.module)}, ${sql.lit(part.step)}, ${sql.lit(part.target)}, ${sql.lit(part.version)})`);
46
+ const fill = ddl`insert into ${steps} (${module}, ${step}, ${target}, ${applied_at})
47
+ select part.module, part.step, part.target, legacy.${legacy.columns.applied_at}
48
+ from (values ${sql.join(parts, sql`, `)}) as part (module, step, target, version)
49
+ join ${legacy} legacy on legacy.${legacy.columns.version} = part.version
50
+ on conflict do nothing`;
51
+ return `-- The steps the store recorded by version in ${legacy.name}, recorded by step.\n${guardedBlock(ddl`to_regclass(${sql.lit(String(legacy))}) is not null`, [fill])}`;
52
+ };
53
+ /** The record of the store's steps, made when it is missing and filled from `auth_migrations`, for a store that recorded versions. */
54
+ const stepRecordMigration = (names) => [stepRecordSql(names), fillFromLegacySql(names)].join("\n\n");
55
+ //#endregion
56
+ export { appliedVersions, fillFromLegacySql, legacyParts, legacyRecordTable, stepRecordMigration, stepsOfVersions };
@@ -1,43 +1,48 @@
1
1
  import { ddl, ddlText } from "./ddl.js";
2
- import { createMigrationsTable, migrationsTable, recordMigrations } from "./migrations-table.js";
3
- import { legacyVersions } from "./steps/legacy-versions.js";
4
- import { sql } from "kysely";
2
+ import { createStepRecord, partOf, recordSteps, stepRecorded } from "./step-record.js";
5
3
  //#region src/better-auth/store/migration-sql.ts
6
4
  /** The statements as SQL text. */
7
5
  const statementsSql = (statements) => statements.map((statement) => `${ddlText(statement)};`).join("\n\n");
8
6
  const comment = ({ module, step, on }) => `-- ${module} ${step.step} ${step.name}${on === void 0 ? "" : `, on the tables of ${on}`}: ${step.title}.`;
9
- const partStatements = (names, rendered, versions, i) => {
10
- const part = rendered[i];
11
- const recorded = versions.includes(part.version) && !rendered.slice(i + 1).some((later) => later.version === part.version);
12
- return [...part.statements, ...recorded ? [recordMigrations(names, legacyVersions.filter(({ version }) => version === part.version))] : []];
13
- };
7
+ const partStatements = (names, part) => [...part.statements, recordSteps(names, [partOf(part)])];
8
+ /**
9
+ * The rendered steps, each under a comment naming it, each followed by the row that records it in `auth_steps`, as
10
+ * one transaction: what a part leaves for after it commits runs in it, before that row.
11
+ */
12
+ const stepsSql = (names, rendered) => rendered.map((part) => `${comment(part)}\n${statementsSql([
13
+ ...part.statements,
14
+ ...part.after(false),
15
+ recordSteps(names, [partOf(part)])
16
+ ])}`).join("\n\n");
14
17
  /**
15
- * The rendered steps, each under a comment naming it; after the last statements of each version of `versions`, the
16
- * row that records it in `auth_migrations`.
18
+ * What the rendered steps leave for once the migration's transaction commits, as a migration's `.after.sql` runs it:
19
+ * outside a transaction, each statement under a comment naming its part; `undefined` when they leave nothing.
17
20
  */
18
- const stepsSql = (names, rendered, versions) => rendered.map((part, i) => `${comment(part)}\n${statementsSql(partStatements(names, rendered, versions, i))}`).join("\n\n");
19
- const blockQuote = "$version$";
21
+ const afterStepsSql = (rendered) => {
22
+ const parts = rendered.flatMap((part) => {
23
+ const statements = part.after(true);
24
+ return statements.length === 0 ? [] : [`${comment(part)}\n${statementsSql(statements)}`];
25
+ });
26
+ return parts.length === 0 ? void 0 : `${parts.join("\n\n")}\n`;
27
+ };
28
+ const blockQuote = "$step$";
20
29
  const statementQuote = "$statement$";
21
- const unlessRecorded = (names, version, statements) => {
30
+ /** The statements as one block that runs them only while `when` holds, each executed as text. */
31
+ const guardedBlock = (when, statements) => {
22
32
  const texts = statements.map(ddlText);
23
33
  const quoted = texts.find((text) => text.includes(blockQuote) || text.includes(statementQuote));
24
34
  if (quoted) throw new Error(`A step's statement holds ${blockQuote} or ${statementQuote}, which guard it: ${quoted}`);
25
- const table = migrationsTable(names);
26
- const recorded = ddlText(ddl`select from ${table} where ${table.columns.version} = ${sql.lit(version)}`);
27
- return `do ${blockQuote} begin\nif not exists (${recorded}) then\n${texts.map((text) => `execute ${statementQuote}${text}${statementQuote};`).join("\n")}\nend if;\nend ${blockQuote};`;
35
+ return `do ${blockQuote} begin\nif ${ddlText(when)} then\n${texts.map((text) => `execute ${statementQuote}${text}${statementQuote};`).join("\n")}\nend if;\nend ${blockQuote};`;
28
36
  };
29
37
  /**
30
- * The rendered steps as `stepsSql` writes them, each part run only while `auth_migrations` lacks its version, so a
31
- * database that has a version already, such as one `protobase-serve migrate-release` brought to a release, skips it.
32
- */
33
- const guardedStepsSql = (names, rendered, versions) => rendered.map((part, i) => `${comment(part)}\n${unlessRecorded(names, part.version, partStatements(names, rendered, versions, i))}`).join("\n\n");
34
- /**
35
- * The migrations table, for a store that has none yet, in the store's schema, made when it is missing. With
36
- * `ifMissing`, the table too is made only when missing, for a database a host made it in already.
38
+ * The rendered steps as `stepsSql` writes them, each part run only while `auth_steps` lacks it, so a database that has
39
+ * it already, such as one `protobase-serve migrate-release` brought to a release, skips it.
37
40
  */
38
- const migrationsTableSql = (names, ifMissing = false) => {
41
+ const guardedStepsSql = (names, rendered) => rendered.map((part) => `${comment(part)}\n${guardedBlock(ddl`not ${stepRecorded(names, part)}`, partStatements(names, part))}`).join("\n\n");
42
+ /** The record of the store's steps, for a store that has none yet, in the store's schema, made when it is missing. */
43
+ const stepRecordSql = (names) => {
39
44
  const schema = names.schema === void 0 ? [] : [ddl`create schema if not exists ${names.schema}`];
40
- return `-- The record of the auth store's migrations.\n${statementsSql([...schema, createMigrationsTable(names, ifMissing)])}`;
45
+ return `-- The record of the auth store's steps.\n${statementsSql([...schema, createStepRecord(names)])}`;
41
46
  };
42
47
  //#endregion
43
- export { guardedStepsSql, migrationsTableSql, statementsSql, stepsSql };
48
+ export { afterStepsSql, guardedBlock, guardedStepsSql, statementsSql, stepRecordSql, stepsSql };
@@ -0,0 +1,35 @@
1
+ import { StoreNames } from "../store-names.js";
2
+ import { KeptModule, LastSteps } from "./store-model.js";
3
+ import { AppliedStep } from "../step-record.js";
4
+ //#region src/better-auth/store/offline/baseline-store.d.ts
5
+ /** A relation in the store's schema: its `pg_class.relkind` and its columns. */
6
+ export type LiveRelation = {
7
+ kind: string;
8
+ columns: string[];
9
+ };
10
+ /** The store as the database has it: the parts of steps it recorded, and every relation of its schema by name. */
11
+ export type LiveStore = {
12
+ applied: AppliedStep[];
13
+ relations: Record<string, LiveRelation>;
14
+ };
15
+ /**
16
+ * What the store is: each module's last step, the modules off that have tables, whether organizations were ever on,
17
+ * the relations Protobase did not make, and whether it has `auth_steps`.
18
+ */
19
+ export type BaselineStore = {
20
+ lastSteps: LastSteps;
21
+ kept: KeptModule[];
22
+ organizationsEverOn: boolean;
23
+ external: string[];
24
+ stepRecord: boolean;
25
+ };
26
+ /**
27
+ * The store at `live` under the config's `names`: each module that is on at the step the record holds, every module
28
+ * 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
29
+ * the column that names it, and the user table as external when the config reads it through a view over another
30
+ * system's (`users.keyTable`). Refuses a user table the database has as anything but a table without `users.keyTable`,
31
+ * since the steps' foreign keys would point at it, and a table a recorded step made that the schema lacks under the
32
+ * config's name, such as one renamed since, naming each.
33
+ */
34
+ export declare const baselineStore: (names: StoreNames, live: LiveStore) => BaselineStore;
35
+ //#endregion