@jskit-ai/workspaces-core 0.2.24 → 0.2.26

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The realtime audience contributor answers a question about some scopes by reading only the memberships of the workspaces they name, with the new `workspaces.memberships.listActiveWorkspaceIdsByUserIdsAmong(userIds, workspaceIds, options)`, and reads nothing when they name no workspace (a publish to user rooms). Before, every publish read all the active memberships of every online actor.
6
+ - **Breaking.** The members and invites lists answer one page at a time, and each page is one statement. Before this, they read every active membership or pending invite and sorted them in code.
7
+ - `GET .../members` and `GET .../invites` (the `workspace.members.list` and `workspace.invites.list` actions) take `limit` (1 to 100, 20 when none) and `cursor`, the previous page's `nextCursor`. They answer the page with `nextCursor`, which is null on the last page.
8
+ - Members stay in display-name order, now by the database's collation and then by user id. Invites stay newest first, with invites made in the same second in the order they were made.
9
+ - `services.members.listMembersPage(workspace, query, options)` answers one page of members, for a screen. `listMembers(workspace, options)` still answers every active member, for work that needs them all. `listMembersResponse` and `listInvitesResponse`, which the list actions call, take the page query before the options. A member change, an invitation and a revocation answer the list's first page.
10
+ - The members page is one report on the memberships joined to `users.profiles`' join source (`workspaceMemberPagesRepository`, a new dependency of the members service). The invites repository gains `listPendingPageByWorkspaceId(workspaceId, { size, after }, options)`.
11
+ - A cursor the members list did not answer is refused with 400 `workspaces.member.cursorInvalid`.
5
12
  - The optional `workspaces.workspace-created-participant` capability writes an application's records for every new workspace in the creation's transaction, as `workspaces.invite-acceptance-participant` does for an accepted invitation: one function `({ workspace, owner }, { trx, context })`, with `workspace` and `owner` shallow frozen. Both creation paths call it, the `workspace.workspaces.create` action (`createWorkspaceForAuthenticatedUser`) and a personal workspace's provisioning (`ensurePersonalWorkspaceForUser`, inside a first sign-in's profile sync), after the workspace, its owner's membership and its settings are written. Creating a workspace is now one transaction, the caller's or its own, where the named create wrote its three rows one after the other: a failure, the participant's or a later write's, leaves no workspace, membership or settings row and none of the participant's writes, and the caller receives the failure itself. A create that loses its slug to another create runs again with the next free slug, and one that loses it to the same owner's identical create answers that workspace, as the repository's insert did, without calling the participant twice. Without the capability, creation writes the workspace, membership and settings only.
6
13
  - A member's role change and their removal lock the membership before they check it, so two at once run one after the other and the second decides on what the first left: a role change that waited for a removal answers 404 `workspaces.member.notFound` instead of making the removed member active again, and a removal that waited for a role change keeps the new role instead of writing back the one it read. `workspaces.memberships` gains `lockByWorkspaceIdAndUserId(workspaceId, userId, txOptions)`, the membership locked until the caller's transaction ends, or null.
7
14
  - Expiring an email's pending invites (`expirePendingByWorkspaceIdAndEmail`, which every new invite runs first) is one `patchWhere` on the invites, where it locked them and then patched them one at a time: its statements no longer grow with the invites the email had.
package/locales/en.json CHANGED
@@ -20,7 +20,8 @@
20
20
  "userIdRequired": "Member user id is required.",
21
21
  "notFound": "Member not found.",
22
22
  "ownerRoleLocked": "Cannot change workspace owner role.",
23
- "ownerNotRemovable": "Cannot remove workspace owner."
23
+ "ownerNotRemovable": "Cannot remove workspace owner.",
24
+ "cursorInvalid": "This list's cursor is not one it answered."
24
25
  },
25
26
  "invite": {
26
27
  "disabled": "Workspace invitations are disabled.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.24",
3
+ "version": "0.2.26",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -24,8 +24,8 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@jskit-ai/resource-core": "0.1.209",
27
- "@jskit-ai/resource-crud-core": "0.1.209",
28
- "@jskit-ai/users-core": "0.2.24",
27
+ "@jskit-ai/resource-crud-core": "0.1.210",
28
+ "@jskit-ai/users-core": "0.2.26",
29
29
  "json-rest-schema": "^1.0.20"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -210,6 +210,6 @@
210
210
  "@jskit-ai/database-runtime": "0.1.267",
211
211
  "@jskit-ai/http-runtime": "0.2.18",
212
212
  "@jskit-ai/kernel": "0.2.18",
213
- "@jskit-ai/resource-runtime": "0.2.20"
213
+ "@jskit-ai/resource-runtime": "0.2.22"
214
214
  }
215
215
  }
@@ -10,11 +10,24 @@ import {
10
10
  /**
11
11
  * Every active membership puts the actor in the workspace audience and in its
12
12
  * own workspace-user audience. All the actors' memberships are one bulk read.
13
+ * Asked about some scopes only (a publish asking whether actors outside its
14
+ * rooms belong to them), it reads only the memberships of the workspaces those
15
+ * scopes name, and nothing when they name none (user rooms).
13
16
  * @param {import("./types.js").WorkspacesMemberships} workspaceMemberships
14
17
  * @param {string[]} actorIds
18
+ * @param {{ scopes?: Array<{ kind: string, id?: string, workspaceId?: string }> }} [question]
15
19
  */
16
- async function resolveWorkspaceRealtimeScopes(workspaceMemberships, actorIds) {
17
- const workspaceIdsByActorId = await workspaceMemberships.listActiveWorkspaceIdsByUserIds(actorIds);
20
+ async function resolveWorkspaceRealtimeScopes(workspaceMemberships, actorIds, { scopes } = {}) {
21
+ const askedWorkspaceIds = scopes === undefined
22
+ ? null
23
+ : [...new Set(scopes.flatMap((scope) => {
24
+ if (scope.kind === "workspace") return [scope.id];
25
+ return scope.kind === "workspace_user" ? [scope.workspaceId] : [];
26
+ }))];
27
+ if (askedWorkspaceIds !== null && askedWorkspaceIds.length === 0) return new Map();
28
+ const workspaceIdsByActorId = askedWorkspaceIds === null
29
+ ? await workspaceMemberships.listActiveWorkspaceIdsByUserIds(actorIds)
30
+ : await workspaceMemberships.listActiveWorkspaceIdsByUserIdsAmong(actorIds, askedWorkspaceIds);
18
31
  const scopesByActorId = new Map();
19
32
  for (const [actorId, workspaceIds] of workspaceIdsByActorId) {
20
33
  scopesByActorId.set(actorId, workspaceIds.flatMap((workspaceId) => [
@@ -94,7 +107,7 @@ const WorkspacesIntegrationsProvider = defineProvider({
94
107
  if (realtime) {
95
108
  realtime.registerAudienceContributor({
96
109
  id: "workspaces.memberships",
97
- resolveActorsScopes: (actorIds) => resolveWorkspaceRealtimeScopes(workspaceMemberships, actorIds)
110
+ resolveActorsScopes: (actorIds, question) => resolveWorkspaceRealtimeScopes(workspaceMemberships, actorIds, question)
98
111
  });
99
112
  }
100
113
 
@@ -165,6 +165,35 @@ function createRepository({ workspaceInvites, workspaces }) {
165
165
  .sort((left, right) => String(right.createdAt || "").localeCompare(String(left.createdAt || "")));
166
166
  }
167
167
 
168
+ /**
169
+ * One page of the workspace's pending invites, newest first (then oldest id), each with its workspace as
170
+ * listPendingByWorkspaceIdWithWorkspace reads it: `{ invites, next }`, where `next` is the cursor of the page after,
171
+ * or null on the last page. It reads one page however many invites are pending.
172
+ * @param {unknown} workspaceId
173
+ * @param {{ size: number, after?: string }} page At most the invites handle's pageLimits().request invites.
174
+ * @param {object} [options]
175
+ */
176
+ async function listPendingPageByWorkspaceId(workspaceId, { size, after }, options = {}) {
177
+ const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
178
+ if (!normalizedWorkspaceId) {
179
+ return { invites: [], next: null };
180
+ }
181
+
182
+ const { records, page } = await workspaceInvites.query(
183
+ {
184
+ filters: { workspace: normalizedWorkspaceId, status: "pending" },
185
+ sort: ["-createdAt", "id"],
186
+ include: ["workspace"],
187
+ page: {
188
+ size: Math.min(Number(size), workspaceInvites.pageLimits().request),
189
+ ...(after === undefined ? {} : { after })
190
+ }
191
+ },
192
+ options
193
+ );
194
+ return { invites: records.map(normalizeInviteWithWorkspace).filter(Boolean), next: page.next };
195
+ }
196
+
168
197
  async function insert(payload, options = {}) {
169
198
  const source = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
170
199
  const workspaceId = normalizeRecordId(source.workspaceId, { fallback: null });
@@ -313,6 +342,7 @@ function createRepository({ workspaceInvites, workspaces }) {
313
342
  findByTokenHashWithWorkspace,
314
343
  listPendingByEmail,
315
344
  listPendingByWorkspaceIdWithWorkspace,
345
+ listPendingPageByWorkspaceId,
316
346
  insert,
317
347
  expirePendingByWorkspaceIdAndEmail,
318
348
  markAcceptedById,
@@ -0,0 +1,84 @@
1
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
3
+ import { normalizeMemberSummaryRow } from "./workspaceMembershipsRepository.js";
4
+
5
+ // A page's cursor: its last member's display name and user id, the list's order, as base64url JSON.
6
+ function encodeCursor(row) {
7
+ return Buffer.from(JSON.stringify([row.display_name, String(row.user_id)])).toString("base64url");
8
+ }
9
+
10
+ function decodeCursor(cursor) {
11
+ try {
12
+ const [displayName, userId] = JSON.parse(Buffer.from(String(cursor), "base64url").toString("utf8"));
13
+ if (typeof displayName === "string" && typeof userId === "string") {
14
+ return { displayName, userId };
15
+ }
16
+ } catch {
17
+ // Not a cursor this list answered: refused below.
18
+ }
19
+ throw new AppError(400, "This list's cursor is not one it answered.", { code: "workspaces.member.cursorInvalid" });
20
+ }
21
+
22
+ /**
23
+ * A workspace's members a page at a time, with their users' names and emails: the members list of
24
+ * `workspaces.core`. A page is one statement on the memberships joined to users.profiles' join source, so it reads
25
+ * a page of rows however many members the workspace has.
26
+ * @param {object} dependencies
27
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaceMemberships
28
+ * The workspace_memberships table's handle.
29
+ * @param {Pick<import("@jskit-ai/users-core/server/types").UsersProfiles, "joinSource">} dependencies.userProfiles
30
+ */
31
+ function createRepository({ workspaceMemberships, userProfiles }) {
32
+ /**
33
+ * One page of the workspace's active members by display name (then user id), each as listActiveByWorkspaceId
34
+ * summarizes it: `{ members, next }`, where `next` is the cursor of the page after, or null on the last page.
35
+ * @param {unknown} workspaceId
36
+ * @param {{ size: number, after?: string }} page At most the memberships handle's pageLimits().request members.
37
+ * @param {object} [options]
38
+ */
39
+ // Knex: report - one page of a workspace's active members with their users' names and emails, by display name
40
+ async function listActivePage(workspaceId, { size, after }, options = {}) {
41
+ const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
42
+ if (!normalizedWorkspaceId) {
43
+ return { members: [], next: null };
44
+ }
45
+
46
+ const limit = Math.min(Number(size), workspaceMemberships.pageLimits().request);
47
+ const user = await userProfiles.joinSource({ alias: "u" }, options);
48
+ const profiles = user.query
49
+ .select({ userId: user.column("id"), shown: user.column("displayName"), mail: user.column("email") })
50
+ .as("p");
51
+ const { query } = await workspaceMemberships.scopedQuery(
52
+ { alias: "m", filters: { workspace: normalizedWorkspaceId, status: "active" } },
53
+ options
54
+ );
55
+ const memberUserId = workspaceMemberships.column("userId", "m");
56
+ query
57
+ .join(profiles, "p.userId", memberUserId)
58
+ .select({
59
+ user_id: memberUserId,
60
+ role_sid: workspaceMemberships.column("roleSid", "m"),
61
+ status: workspaceMemberships.column("status", "m"),
62
+ display_name: "p.shown",
63
+ email: "p.mail"
64
+ })
65
+ .orderBy(["p.shown", memberUserId])
66
+ .limit(limit + 1);
67
+ if (after !== undefined) {
68
+ const last = decodeCursor(after);
69
+ query.where((later) => later.where("p.shown", ">", last.displayName)
70
+ .orWhere((tie) => tie.where("p.shown", last.displayName).where(memberUserId, ">", last.userId)));
71
+ }
72
+ const rows = await query;
73
+ return {
74
+ members: rows.slice(0, limit).map(normalizeMemberSummaryRow),
75
+ next: rows.length > limit ? encodeCursor(rows[limit - 1]) : null
76
+ };
77
+ }
78
+
79
+ return Object.freeze({
80
+ listActivePage
81
+ });
82
+ }
83
+
84
+ export { createRepository };
@@ -159,7 +159,8 @@ function createRepository({ workspaceMemberships }) {
159
159
  }
160
160
 
161
161
  /**
162
- * The ids of the workspace's active members, in one read without their profiles.
162
+ * The ids of the workspace's active members, in one read without their profiles. It reads every active membership,
163
+ * so its cost grows with the workspace: a screen lists members a page at a time (workspaceMemberPagesRepository).
163
164
  * @param {unknown} workspaceId
164
165
  * @param {object} [options]
165
166
  * @returns {Promise<string[]>}
@@ -247,6 +248,30 @@ function createRepository({ workspaceMemberships }) {
247
248
  * @returns {Promise<Map<string, string[]>>} Every asked user, with no workspaces when they have none.
248
249
  */
249
250
  async function listActiveWorkspaceIdsByUserIds(userIds, options = {}) {
251
+ return activeWorkspaceIdsByUserIds(userIds, [{}], options);
252
+ }
253
+
254
+ /**
255
+ * Which of the workspaces each user is an active member of: listActiveWorkspaceIdsByUserIds narrowed to
256
+ * `workspaceIds`, so it reads only those workspaces' memberships of the users, one query per workspace and 1,000
257
+ * users. No workspace needs no query.
258
+ * @param {Iterable<string | number>} userIds
259
+ * @param {Iterable<string | number>} workspaceIds
260
+ * @param {object} [options]
261
+ * @returns {Promise<Map<string, string[]>>} Every asked user, with no workspaces when they are a member of none of them.
262
+ */
263
+ async function listActiveWorkspaceIdsByUserIdsAmong(userIds, workspaceIds, options = {}) {
264
+ const normalizedWorkspaceIds = new Set();
265
+ for (const workspaceId of workspaceIds) {
266
+ const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
267
+ if (normalizedWorkspaceId) normalizedWorkspaceIds.add(normalizedWorkspaceId);
268
+ }
269
+ return activeWorkspaceIdsByUserIds(userIds, [...normalizedWorkspaceIds].map((workspace) => ({ workspace })), options);
270
+ }
271
+
272
+ // Each user's active workspace ids, reading the users' active memberships 1,000 users at a time under each of the
273
+ // filters in turn.
274
+ async function activeWorkspaceIdsByUserIds(userIds, filtersList, options) {
250
275
  const workspaceIdsByUserId = new Map();
251
276
  for (const userId of userIds) {
252
277
  const normalizedUserId = normalizeRecordId(userId, { fallback: null });
@@ -254,18 +279,21 @@ function createRepository({ workspaceMemberships }) {
254
279
  }
255
280
 
256
281
  const normalizedUserIds = [...workspaceIdsByUserId.keys()];
257
- for (let start = 0; start < normalizedUserIds.length; start += USER_IDS_PER_QUERY) {
258
- const rows = await queryMemberships(
259
- {
260
- users: normalizedUserIds.slice(start, start + USER_IDS_PER_QUERY),
261
- status: "active"
262
- },
263
- options
264
- );
265
- for (const row of rows) {
266
- const userId = normalizeDbRecordId(row.userId, { fallback: null });
267
- const workspaceId = normalizeDbRecordId(row.workspaceId, { fallback: null });
268
- if (workspaceId) workspaceIdsByUserId.get(userId)?.push(workspaceId);
282
+ for (const filters of filtersList) {
283
+ for (let start = 0; start < normalizedUserIds.length; start += USER_IDS_PER_QUERY) {
284
+ const rows = await queryMemberships(
285
+ {
286
+ ...filters,
287
+ users: normalizedUserIds.slice(start, start + USER_IDS_PER_QUERY),
288
+ status: "active"
289
+ },
290
+ options
291
+ );
292
+ for (const row of rows) {
293
+ const userId = normalizeDbRecordId(row.userId, { fallback: null });
294
+ const workspaceId = normalizeDbRecordId(row.workspaceId, { fallback: null });
295
+ if (workspaceId) workspaceIdsByUserId.get(userId)?.push(workspaceId);
296
+ }
269
297
  }
270
298
  }
271
299
  return workspaceIdsByUserId;
@@ -287,7 +315,8 @@ function createRepository({ workspaceMemberships }) {
287
315
  listByWorkspaceId,
288
316
  findActiveByWorkspaceIdAndUserId,
289
317
  listActiveWorkspaceIdsByUserId,
290
- listActiveWorkspaceIdsByUserIds
318
+ listActiveWorkspaceIdsByUserIds,
319
+ listActiveWorkspaceIdsByUserIdsAmong
291
320
  });
292
321
  }
293
322
 
@@ -20,6 +20,7 @@
20
20
  */
21
21
  /** @typedef {ReturnType<typeof import("./common/repositories/workspacesRepository.js").createRepository>} WorkspacesRepository */
22
22
  /** @typedef {ReturnType<typeof import("./common/repositories/workspaceMembershipsRepository.js").createRepository>} WorkspaceMembershipsRepository */
23
+ /** @typedef {ReturnType<typeof import("./common/repositories/workspaceMemberPagesRepository.js").createRepository>} WorkspaceMemberPagesRepository */
23
24
  /** @typedef {ReturnType<typeof import("./common/repositories/workspaceInvitesRepository.js").createRepository>} WorkspaceInvitesRepository */
24
25
  /** @typedef {ReturnType<typeof import("./workspaceSettings/workspaceSettingsRepository.js").createRepository>} WorkspaceSettingsRepository */
25
26
  /** @typedef {ReturnType<typeof import("../shared/roles.js").createWorkspaceRoleCatalog>} WorkspaceRoleCatalog */
@@ -16,6 +16,22 @@ const WORKSPACE_MEMBER_CHANGED_EVENTS = createWorkspaceEntityAndBootstrapEvents(
16
16
  workspaceRealtimeEvent: "workspace.members.changed"
17
17
  });
18
18
 
19
+ const membersListActionInput = composeSchemaDefinitions([
20
+ workspaceSlugParamsValidator,
21
+ workspaceMembersContract.operations.membersList.query
22
+ ], {
23
+ mode: "create",
24
+ context: "workspaceMembersActions.membersListActionInput"
25
+ });
26
+
27
+ const invitesListActionInput = composeSchemaDefinitions([
28
+ workspaceSlugParamsValidator,
29
+ workspaceMembersContract.operations.invitesList.query
30
+ ], {
31
+ mode: "create",
32
+ context: "workspaceMembersActions.invitesListActionInput"
33
+ });
34
+
19
35
  const updateMemberRoleActionInput = composeSchemaDefinitions([
20
36
  workspaceSlugParamsValidator,
21
37
  workspaceMembersContract.operations.updateMemberRole.input
@@ -99,17 +115,18 @@ function createWorkspaceMembersActions({ workspaceMembersService }) {
99
115
  require: "all",
100
116
  permissions: ["workspace.members.view"]
101
117
  },
102
- input: workspaceSlugParamsValidator,
118
+ input: membersListActionInput,
103
119
  output: null,
104
120
  extensions: {
105
121
  assistant: {
106
- description: "List members of the active workspace.",
122
+ description: "List members of the active workspace, a page at a time: pass a page's nextCursor as cursor for the next.",
107
123
  output: workspaceMembersContract.operations.membersList.output,
108
124
  transformResult: (result) => result.value
109
125
  }
110
126
  },
111
127
  execute: (input, context) => workspaceMembersService.listMembersResponse(
112
128
  resolveWorkspace(context, input),
129
+ input,
113
130
  { context }
114
131
  )
115
132
  }),
@@ -175,17 +192,18 @@ function createWorkspaceMembersActions({ workspaceMembersService }) {
175
192
  require: "all",
176
193
  permissions: ["workspace.members.view"]
177
194
  },
178
- input: workspaceSlugParamsValidator,
195
+ input: invitesListActionInput,
179
196
  output: null,
180
197
  extensions: {
181
198
  assistant: {
182
- description: "List invitations for the active workspace without invitation tokens.",
199
+ description: "List invitations for the active workspace without invitation tokens, a page at a time: pass a page's nextCursor as cursor for the next.",
183
200
  output: workspaceMembersContract.operations.invitesList.output,
184
201
  transformResult: (result) => result.value
185
202
  }
186
203
  },
187
204
  execute: (input, context) => workspaceMembersService.listInvitesResponse(
188
205
  resolveWorkspace(context, input),
206
+ input,
189
207
  { context }
190
208
  )
191
209
  }),
@@ -68,6 +68,7 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
68
68
  params: workspaceSlugParamsValidator,
69
69
  ...createJsonApiResourceRouteContract({
70
70
  ...WORKSPACE_MEMBERS_TRANSPORT,
71
+ query: workspaceMembersContract.operations.membersList.query,
71
72
  output: workspaceMembersContract.operations.membersList.output,
72
73
  outputKind: "record",
73
74
  getRecordId: resolveWorkspaceRecordId
@@ -77,7 +78,9 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
77
78
  const response = await request.executeAction({
78
79
  actionId: "workspace.members.list",
79
80
  input: {
80
- workspaceSlug: request.input.params.workspaceSlug
81
+ workspaceSlug: request.input.params.workspaceSlug,
82
+ cursor: request.input.query.cursor,
83
+ limit: request.input.query.limit
81
84
  }
82
85
  });
83
86
  reply.code(200).send(response);
@@ -167,6 +170,7 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
167
170
  params: workspaceSlugParamsValidator,
168
171
  ...createJsonApiResourceRouteContract({
169
172
  ...WORKSPACE_INVITES_TRANSPORT,
173
+ query: workspaceMembersContract.operations.invitesList.query,
170
174
  output: workspaceMembersContract.operations.invitesList.output,
171
175
  outputKind: "record",
172
176
  getRecordId: resolveWorkspaceRecordId
@@ -176,7 +180,9 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
176
180
  const response = await request.executeAction({
177
181
  actionId: "workspace.invites.list",
178
182
  input: {
179
- workspaceSlug: request.input.params.workspaceSlug
183
+ workspaceSlug: request.input.params.workspaceSlug,
184
+ cursor: request.input.query.cursor,
185
+ limit: request.input.query.limit
180
186
  }
181
187
  });
182
188
  reply.code(200).send(response);
@@ -11,6 +11,13 @@ import {
11
11
 
12
12
  const DEFAULT_LOCALE = "en";
13
13
  const DEFAULT_TIME_ZONE = "UTC";
14
+ // A members or invites list page's size when the request names none, as a client list's first request asks.
15
+ const DEFAULT_PAGE_SIZE = 20;
16
+
17
+ // The page a list request asks for: its size and the cursor of the page before, as the repositories read it.
18
+ function listPage({ cursor, limit } = {}) {
19
+ return { size: Number(limit) || DEFAULT_PAGE_SIZE, ...(cursor ? { after: cursor } : {}) };
20
+ }
14
21
 
15
22
  function roleNotAssignableError() {
16
23
  return createValidationError({
@@ -33,6 +40,7 @@ function inviteIdRequiredError() {
33
40
  /**
34
41
  * @param {object} dependencies
35
42
  * @param {import("../types.js").WorkspaceMembershipsRepository} dependencies.workspaceMembershipsRepository
43
+ * @param {import("../types.js").WorkspaceMemberPagesRepository} dependencies.workspaceMemberPagesRepository
36
44
  * @param {import("../types.js").WorkspaceInvitesRepository} dependencies.workspaceInvitesRepository
37
45
  * @param {number} dependencies.inviteExpiresInMs
38
46
  * @param {import("../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
@@ -47,6 +55,7 @@ function inviteIdRequiredError() {
47
55
  */
48
56
  function createService({
49
57
  workspaceMembershipsRepository,
58
+ workspaceMemberPagesRepository,
50
59
  workspaceInvitesRepository,
51
60
  inviteExpiresInMs,
52
61
  roleCatalog,
@@ -189,7 +198,8 @@ function createService({
189
198
  }
190
199
 
191
200
  // Applications read the role catalog and member list as they are; the
192
- // *Response methods answer with them as JSON:API data, for the actions.
201
+ // *Response methods answer with them as JSON:API data, for the actions. The actions' members and invites lists answer
202
+ // a page at a time: `query` names its size (`limit`, 20 when none) and the `nextCursor` of the page before (`cursor`).
193
203
  async function listRoles() {
194
204
  return cloneWorkspaceRoleCatalog(roleCatalog);
195
205
  }
@@ -198,6 +208,7 @@ function createService({
198
208
  return returnJsonApiData(await listRoles());
199
209
  }
200
210
 
211
+ // Every active member of the workspace, for work that needs them all, such as a delivery's recipients.
201
212
  async function listMembers(workspace, options = {}) {
202
213
  const members = await workspaceMembershipsRepository.listActiveByWorkspaceId(workspace.id, options);
203
214
 
@@ -207,6 +218,23 @@ function createService({
207
218
  });
208
219
  }
209
220
 
221
+ /**
222
+ * One page of the workspace's active members, by display name, and the `nextCursor` of the page after (null on the
223
+ * last page): the members list a screen shows.
224
+ * @param {object} workspace
225
+ * @param {{ cursor?: string, limit?: number }} [query]
226
+ * @param {object} [options]
227
+ */
228
+ async function listMembersPage(workspace, query = {}, options = {}) {
229
+ const page = await workspaceMemberPagesRepository.listActivePage(workspace.id, listPage(query), options);
230
+
231
+ return withRoleCatalog({
232
+ workspace: mapMembersWorkspace(workspace),
233
+ members: page.members.map((member) => mapMemberSummary(member, workspace)),
234
+ nextCursor: page.next
235
+ });
236
+ }
237
+
210
238
  // One active member's summary, the same as their listMembers entry, or null for a removed or
211
239
  // unknown member. It reads one membership, so a per-member lookup costs the same in any workspace.
212
240
  async function getMember(workspace, userId, options = {}) {
@@ -214,11 +242,11 @@ function createService({
214
242
  return member ? mapMemberSummary(member, workspace) : null;
215
243
  }
216
244
 
217
- async function listMembersResponse(workspace, options = {}) {
218
- return returnJsonApiData(await listMembers(workspace, options));
245
+ async function listMembersResponse(workspace, query = {}, options = {}) {
246
+ return returnJsonApiData(await listMembersPage(workspace, query, options));
219
247
  }
220
248
 
221
- // Changes an active member who is not the owner, and answers the members. The membership is locked before it is
249
+ // Changes an active member who is not the owner, and answers the members' first page. The membership is locked before it is
222
250
  // checked, so a role change and a removal of one member at once run one after the other, and the second decides on
223
251
  // what the first left: a removed member is not made active again by a role change, and keeps the role they had.
224
252
  async function changeActiveMember(workspace, memberUserId, { ownerError, changes }, options) {
@@ -233,7 +261,7 @@ function createService({
233
261
  await workspaceMembershipsRepository.upsertMembership(workspace.id, memberUserId, changes(membership), txOptions);
234
262
  });
235
263
 
236
- return returnJsonApiData(await listMembers(workspace, options));
264
+ return returnJsonApiData(await listMembersPage(workspace, {}, options));
237
265
  }
238
266
 
239
267
  async function updateMemberRole(workspace, payload, options = {}) {
@@ -264,18 +292,20 @@ function createService({
264
292
  }, options);
265
293
  }
266
294
 
267
- async function listInvitesPayload(workspace, options = {}) {
295
+ // One page of the workspace's pending invites, newest first, and the nextCursor of the page after.
296
+ async function listInvitesPayload(workspace, query, options) {
268
297
  ensureWorkspaceInvitationsEnabled();
269
- const invites = await workspaceInvitesRepository.listPendingByWorkspaceIdWithWorkspace(workspace.id, options);
298
+ const page = await workspaceInvitesRepository.listPendingPageByWorkspaceId(workspace.id, listPage(query), options);
270
299
 
271
300
  return withRoleCatalog({
272
301
  workspace: mapMembersWorkspace(workspace),
273
- invites: invites.map((invite) => mapInviteSummary(invite))
302
+ invites: page.invites.map((invite) => mapInviteSummary(invite)),
303
+ nextCursor: page.next
274
304
  });
275
305
  }
276
306
 
277
- async function listInvitesResponse(workspace, options = {}) {
278
- return returnJsonApiData(await listInvitesPayload(workspace, options));
307
+ async function listInvitesResponse(workspace, query = {}, options = {}) {
308
+ return returnJsonApiData(await listInvitesPayload(workspace, query, options));
279
309
  }
280
310
 
281
311
  async function prepareInvite(workspace, user, payload, options = {}) {
@@ -348,7 +378,7 @@ function createService({
348
378
  avatarUrl: invite.workspaceAvatarUrl
349
379
  };
350
380
  const inviteUrl = inviteUrlBuilder({ token, invite, workspace: savedWorkspace });
351
- const response = await listInvitesPayload(savedWorkspace, options);
381
+ const response = await listInvitesPayload(savedWorkspace, {}, options);
352
382
  const inviteDelivery = await deliverInviteEmail({ workspace: savedWorkspace, user, invite, inviteUrl }, options);
353
383
  return {
354
384
  ...response,
@@ -391,7 +421,7 @@ function createService({
391
421
  };
392
422
  const revokedInviteId = await workspaceInvitesRepository.withTransaction(options, revoke);
393
423
 
394
- const response = await listInvitesPayload(workspace, options);
424
+ const response = await listInvitesPayload(workspace, {}, options);
395
425
  return returnJsonApiData({
396
426
  ...response,
397
427
  revokedInviteId
@@ -415,6 +445,7 @@ function createService({
415
445
  listRoles,
416
446
  listRolesResponse,
417
447
  listMembers,
448
+ listMembersPage,
418
449
  getMember,
419
450
  listMembersResponse,
420
451
  updateMemberRole,
@@ -7,6 +7,7 @@ import { workspaceResource } from "../shared/resources/workspaceResource.js";
7
7
  import { workspaceSettingsResource } from "../shared/resources/workspaceSettingsResource.js";
8
8
  import { createRepository as createWorkspaceInvitesRepository } from "./common/repositories/workspaceInvitesRepository.js";
9
9
  import { createRepository as createWorkspaceMembershipsRepository } from "./common/repositories/workspaceMembershipsRepository.js";
10
+ import { createRepository as createWorkspaceMemberPagesRepository } from "./common/repositories/workspaceMemberPagesRepository.js";
10
11
  import { createRepository as createWorkspacesRepository } from "./common/repositories/workspacesRepository.js";
11
12
  import { createService as createWorkspaceService } from "./common/services/workspaceDirectoryService.js";
12
13
  import { createWorkspacesServerI18n } from "./i18n.js";
@@ -134,6 +135,10 @@ function createWorkspacesRuntime({
134
135
  });
135
136
  const workspaceMembersService = createWorkspaceMembersService({
136
137
  workspaceMembershipsRepository,
138
+ workspaceMemberPagesRepository: createWorkspaceMemberPagesRepository({
139
+ workspaceMemberships: resources.workspaceMemberships,
140
+ userProfiles
141
+ }),
137
142
  workspaceInvitesRepository,
138
143
  inviteExpiresInMs: requirePositiveInteger(
139
144
  config?.workspaceMembers?.defaults?.inviteExpiresInMs,
@@ -39,6 +39,15 @@ const inviteSummaryOutputSchema = createSchema({
39
39
  invitedByUserId: { type: "string", required: false, nullable: true, minLength: 1, pattern: RECORD_ID_PATTERN }
40
40
  });
41
41
 
42
+ // A members or invites list request: the page's size, and the nextCursor of the page before.
43
+ const listPageQuerySchema = createSchema({
44
+ cursor: { type: "string", required: false, minLength: 1, maxLength: 1024 },
45
+ limit: { type: "number", required: false, min: 1, max: 100 }
46
+ });
47
+
48
+ // The cursor of the list's next page, or null on its last page.
49
+ const nextCursorOutputField = Object.freeze({ type: "string", required: false, nullable: true });
50
+
42
51
  const workspaceMembersOutputSchema = createSchema({
43
52
  workspace: {
44
53
  type: "object",
@@ -50,6 +59,7 @@ const workspaceMembersOutputSchema = createSchema({
50
59
  required: true,
51
60
  items: memberSummaryOutputSchema
52
61
  },
62
+ nextCursor: { ...nextCursorOutputField },
53
63
  roleCatalog: {
54
64
  type: "object",
55
65
  required: true,
@@ -68,6 +78,7 @@ const workspaceInvitesListOutputSchema = createSchema({
68
78
  required: true,
69
79
  items: inviteSummaryOutputSchema
70
80
  },
81
+ nextCursor: { ...nextCursorOutputField },
71
82
  roleCatalog: {
72
83
  type: "object",
73
84
  required: true,
@@ -86,6 +97,7 @@ const workspaceInviteCreateOutputSchema = createSchema({
86
97
  required: true,
87
98
  items: inviteSummaryOutputSchema
88
99
  },
100
+ nextCursor: { ...nextCursorOutputField },
89
101
  roleCatalog: {
90
102
  type: "object",
91
103
  required: true,
@@ -148,6 +160,7 @@ const workspaceInviteRevokeOutputSchema = createSchema({
148
160
  required: true,
149
161
  items: inviteSummaryOutputSchema
150
162
  },
163
+ nextCursor: { ...nextCursorOutputField },
151
164
  roleCatalog: {
152
165
  type: "object",
153
166
  required: true,
@@ -223,6 +236,7 @@ const workspaceMembersContract = defineApiContract({
223
236
  },
224
237
  membersList: {
225
238
  method: "GET",
239
+ query: listPageQuerySchema,
226
240
  output: workspaceMembersOutputSchema
227
241
  },
228
242
  updateMemberRole: {
@@ -238,6 +252,7 @@ const workspaceMembersContract = defineApiContract({
238
252
  },
239
253
  invitesList: {
240
254
  method: "GET",
255
+ query: listPageQuerySchema,
241
256
  output: workspaceInvitesListOutputSchema
242
257
  },
243
258
  createInvite: {