@jskit-ai/workspaces-core 0.2.23 → 0.2.25

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 (27) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/locales/en.json +2 -1
  3. package/package.json +10 -10
  4. package/patterns/workspace-server/PATTERN.md +9 -0
  5. package/src/server/WorkspacesFeature.js +8 -2
  6. package/src/server/WorkspacesIntegrationsProvider.js +16 -3
  7. package/src/server/common/repositories/workspaceInvitesRepository.js +30 -0
  8. package/src/server/common/repositories/workspaceMemberPagesRepository.js +84 -0
  9. package/src/server/common/repositories/workspaceMembershipsRepository.js +43 -14
  10. package/src/server/common/services/workspaceDirectoryService.js +42 -27
  11. package/src/server/types.js +11 -0
  12. package/src/server/workspaceDirectory/noWorkspaceCreatedParticipant.js +9 -0
  13. package/src/server/workspaceMembers/workspaceMembersActions.js +22 -4
  14. package/src/server/workspaceMembers/workspaceMembersRoutes.js +8 -2
  15. package/src/server/workspaceMembers/workspaceMembersService.js +43 -12
  16. package/src/server/workspacesRuntime.js +8 -0
  17. package/src/shared/resources/workspaceMembersResource.js +15 -0
  18. package/test/featureRuntime.test.js +39 -0
  19. package/test/repositories.integration.test.js +147 -0
  20. package/test/roleLabels.test.js +7 -1
  21. package/test/support/mysqlWorkspaces.js +2 -0
  22. package/test/userAdministrationExample.mysql.test.js +98 -0
  23. package/test/workspaceDirectoryService.mysql.test.js +2 -0
  24. package/test/workspaceMembersService.mysql.test.js +62 -4
  25. package/test/workspaceMembersService.test.js +106 -56
  26. package/test/workspaceRecords.test.js +24 -0
  27. package/test/workspaceService.test.js +76 -4
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
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`.
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.
5
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.
6
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.
7
15
  - `workspaces.joinSource` and `workspaces.memberships.joinSource` are the handle's `joinSource` (`@jskit-ai/resource-runtime`): the same `{ query, column }` for the same params, carrying the columns a read answers instead of every column of the table. A report that names its columns with `column(field)` reads as before.
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.23",
3
+ "version": "0.2.25",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -23,10 +23,10 @@
23
23
  "./locales/en.json": "./locales/en.json"
24
24
  },
25
25
  "dependencies": {
26
- "@jskit-ai/resource-core": "0.1.208",
27
- "@jskit-ai/resource-crud-core": "0.1.208",
28
- "@jskit-ai/users-core": "0.2.23",
29
- "json-rest-schema": "^1.0.17"
26
+ "@jskit-ai/resource-core": "0.1.209",
27
+ "@jskit-ai/resource-crud-core": "0.1.210",
28
+ "@jskit-ai/users-core": "0.2.25",
29
+ "json-rest-schema": "^1.0.20"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
32
32
  "jskit": {
@@ -206,10 +206,10 @@
206
206
  }
207
207
  },
208
208
  "peerDependencies": {
209
- "@jskit-ai/auth-core": "0.2.17",
210
- "@jskit-ai/database-runtime": "0.1.266",
211
- "@jskit-ai/http-runtime": "0.2.17",
212
- "@jskit-ai/kernel": "0.2.17",
213
- "@jskit-ai/resource-runtime": "0.2.19"
209
+ "@jskit-ai/auth-core": "0.2.18",
210
+ "@jskit-ai/database-runtime": "0.1.267",
211
+ "@jskit-ai/http-runtime": "0.2.18",
212
+ "@jskit-ai/kernel": "0.2.18",
213
+ "@jskit-ai/resource-runtime": "0.2.21"
214
214
  }
215
215
  }
@@ -74,6 +74,15 @@ external effects out of it. Without the capability, acceptance activates the
74
74
  membership only. Allow ordinary invitations; reject stale, revoked, conflicting
75
75
  or unexpectedly missing application associations.
76
76
 
77
+ Provide the optional `workspaces.workspace-created-participant` capability the
78
+ same way to write application records for every new workspace. The
79
+ `workspace.workspaces.create` action and personal workspace provisioning invoke
80
+ `fn({ workspace, owner }, txOptions)` after writing the workspace, its owner's
81
+ membership and its settings, in the creation's uncommitted transaction (the
82
+ caller's when it passes one). Pass `txOptions` on and propagate failures: a
83
+ failure rolls the whole creation back. An existing personal workspace does not
84
+ call it.
85
+
77
86
  Call `members.prepareInvite(workspace, actor, payload, txOptions)` inside
78
87
  `repositories.workspaceInvites.withTransaction(options, async (txOptions) => …)`
79
88
  or another resource handle's `withTransaction`. It returns
@@ -10,6 +10,7 @@ import { registerWorkspaceSettingsRoutes } from "./workspaceSettings/workspaceSe
10
10
  import { unconfiguredWorkspaceInviteMailer } from "./workspaceMembers/unconfiguredWorkspaceInviteMailer.js";
11
11
  import { renderDefaultWorkspaceInviteEmail } from "./workspaceMembers/defaultWorkspaceInviteEmail.js";
12
12
  import { noInviteAcceptanceParticipant } from "./workspacePendingInvitations/noInviteAcceptanceParticipant.js";
13
+ import { noWorkspaceCreatedParticipant } from "./workspaceDirectory/noWorkspaceCreatedParticipant.js";
13
14
  import { buildWorkspaceName } from "./common/services/workspaceDirectoryService.js";
14
15
  import { createWorkspaceSettingsActions } from "./workspaceSettings/workspaceSettingsActions.js";
15
16
  import { WORKSPACES_TABLES, createWorkspaceRecords, createWorkspacesRuntime } from "./workspacesRuntime.js";
@@ -31,7 +32,8 @@ const WorkspacesFeature = defineFeature({
31
32
  inviteAcceptanceParticipant: "workspaces.invite-acceptance-participant",
32
33
  inviteEmailTemplate: "workspaces.invite-email-template",
33
34
  inviteMailer: "workspaces.invite-mailer",
34
- personalWorkspaceName: "workspaces.personal-workspace-name"
35
+ personalWorkspaceName: "workspaces.personal-workspace-name",
36
+ workspaceCreatedParticipant: "workspaces.workspace-created-participant"
35
37
  },
36
38
  provides: {
37
39
  workspaces: "workspaces.core",
@@ -52,6 +54,7 @@ const WorkspacesFeature = defineFeature({
52
54
  * @param {import("./types.js").WorkspacesResources} capabilities.resources
53
55
  * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} capabilities.userProfiles
54
56
  * @param {import("@jskit-ai/users-core/server/types").UsersSettings} capabilities.userSettings
57
+ * @param {import("./types.js").WorkspaceCreatedParticipant | null} capabilities.workspaceCreatedParticipant
55
58
  */
56
59
  async setup({
57
60
  appRoot,
@@ -65,7 +68,8 @@ const WorkspacesFeature = defineFeature({
65
68
  personalWorkspaceName,
66
69
  resources,
67
70
  userProfiles,
68
- userSettings
71
+ userSettings,
72
+ workspaceCreatedParticipant
69
73
  }) {
70
74
  const records = createWorkspaceRecords(resources);
71
75
  const workspaces = createWorkspacesRuntime({
@@ -79,6 +83,7 @@ const WorkspacesFeature = defineFeature({
79
83
  resources,
80
84
  userProfiles,
81
85
  userSettings,
86
+ workspaceCreatedParticipant: workspaceCreatedParticipant ?? noWorkspaceCreatedParticipant,
82
87
  workspaces: records.workspaces,
83
88
  workspaceMemberships: records.memberships
84
89
  });
@@ -139,6 +144,7 @@ export {
139
144
  createWorkspaceRecords,
140
145
  createWorkspacesRuntime,
141
146
  noInviteAcceptanceParticipant,
147
+ noWorkspaceCreatedParticipant,
142
148
  renderDefaultWorkspaceInviteEmail,
143
149
  unconfiguredWorkspaceInviteMailer
144
150
  };
@@ -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
 
@@ -58,6 +58,7 @@ function buildWorkspaceName(user) {
58
58
  * @param {import("../../types.js").WorkspaceTenancyProfile} dependencies.tenancyProfile
59
59
  * @param {import("../../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
60
60
  * @param {import("../../types.js").PersonalWorkspaceName} dependencies.personalWorkspaceName
61
+ * @param {import("../../types.js").WorkspaceCreatedParticipant} dependencies.createdParticipant
61
62
  * @param {import("../../types.js").WorkspacesRepository} dependencies.workspacesRepository
62
63
  * @param {import("../../types.js").WorkspaceMembershipsRepository} dependencies.workspaceMembershipsRepository
63
64
  * @param {import("../../types.js").WorkspaceSettingsRepository} dependencies.workspaceSettingsRepository
@@ -66,6 +67,7 @@ function createService({
66
67
  tenancyProfile,
67
68
  roleCatalog,
68
69
  personalWorkspaceName,
70
+ createdParticipant,
69
71
  workspacesRepository,
70
72
  workspaceMembershipsRepository,
71
73
  workspaceSettingsRepository
@@ -88,33 +90,54 @@ function createService({
88
90
  throw new Error("Unable to generate unique workspace slug.");
89
91
  }
90
92
 
93
+ async function ensureWorkspaceSettingsForWorkspace(workspace, options = {}) {
94
+ return workspaceSettingsRepository.ensureForWorkspaceId(workspace.id, {
95
+ ...options,
96
+ workspace
97
+ });
98
+ }
99
+
91
100
  /**
92
- * Creates a workspace under the first free slug from baseSlug. When another owner's create takes that slug between
93
- * the read and the insert, it picks again; inside the caller's transaction the duplicate fails the transaction.
101
+ * Creates a workspace under the first free slug from baseSlug, its owner's membership and its settings, then runs the
102
+ * `workspaces.workspace-created-participant`, all in one transaction: the caller's (`options.trx`), or one of its own.
103
+ * Any failure, the participant's included, rolls the whole creation back. When another create takes the slug between
104
+ * the read and the insert, a transaction of its own answers the winner when it is the same owner's same kind of
105
+ * workspace (a personal workspace made at two first sign-ins at once, a form sent twice), and otherwise runs again
106
+ * under a new slug; inside the caller's transaction the duplicate fails the caller's transaction.
94
107
  * @param {string} baseSlug
95
- * @param {Record<string, unknown>} payload The workspace, without its slug.
108
+ * @param {{ name: string, isPersonal: boolean, avatarUrl: string }} payload The workspace, without its slug and owner.
109
+ * @param {{ id: string }} owner The user who owns it.
96
110
  * @param {object} [options]
97
111
  */
98
- async function insertWithFreeSlug(baseSlug, payload, options = {}) {
112
+ async function createOwnedWorkspace(baseSlug, payload, owner, options = {}) {
113
+ // The slug while the workspace's own insert runs: a duplicate from a later write is not a lost slug.
114
+ let insertingSlug = null;
99
115
  for (let attempt = 1; ; attempt += 1) {
100
- const slug = await ensureUniqueWorkspaceSlug(baseSlug, options);
101
116
  try {
102
- return await workspacesRepository.insert({ ...payload, slug }, options);
117
+ return await workspacesRepository.withTransaction(options, async (txOptions) => {
118
+ insertingSlug = await ensureUniqueWorkspaceSlug(baseSlug, txOptions);
119
+ const workspace = await workspacesRepository.insert(
120
+ { ...payload, slug: insertingSlug, ownerUserId: owner.id },
121
+ txOptions
122
+ );
123
+ insertingSlug = null;
124
+ await workspaceMembershipsRepository.ensureOwnerMembership(workspace.id, owner.id, txOptions);
125
+ await ensureWorkspaceSettingsForWorkspace(workspace, txOptions);
126
+ await createdParticipant({ workspace: Object.freeze({ ...workspace }), owner: Object.freeze({ ...owner }) }, txOptions);
127
+ return workspace;
128
+ });
103
129
  } catch (error) {
104
- if (attempt >= WORKSPACE_SLUG_ATTEMPTS || !isLostDuplicateInsertRace(error, options)) {
130
+ if (attempt >= WORKSPACE_SLUG_ATTEMPTS || !insertingSlug || !isLostDuplicateInsertRace(error, options)) {
105
131
  throw error;
106
132
  }
133
+ const winner = await workspacesRepository.findBySlug(insertingSlug, options);
134
+ if (winner && winner.ownerUserId === owner.id && winner.isPersonal === payload.isPersonal) {
135
+ return winner;
136
+ }
107
137
  }
108
138
  }
109
139
  }
110
140
 
111
- async function ensureWorkspaceSettingsForWorkspace(workspace, options = {}) {
112
- return workspaceSettingsRepository.ensureForWorkspaceId(workspace.id, {
113
- ...options,
114
- workspace
115
- });
116
- }
117
-
118
141
  async function ensurePersonalWorkspaceForUser(user, options = {}) {
119
142
  const normalizedUserId = normalizeRecordId(user?.id, { fallback: null });
120
143
  if (!normalizedUserId) {
@@ -128,20 +151,16 @@ function createService({
128
151
  return existing;
129
152
  }
130
153
 
131
- const inserted = await insertWithFreeSlug(
154
+ return createOwnedWorkspace(
132
155
  buildWorkspaceBaseSlug(user),
133
156
  {
134
157
  name: normalizeText(personalWorkspaceName(user)) || buildWorkspaceName(user),
135
- ownerUserId: normalizedUserId,
136
158
  isPersonal: true,
137
159
  avatarUrl: ""
138
160
  },
161
+ { ...user, id: normalizedUserId },
139
162
  options
140
163
  );
141
-
142
- await workspaceMembershipsRepository.ensureOwnerMembership(inserted.id, normalizedUserId, options);
143
- await ensureWorkspaceSettingsForWorkspace(inserted, options);
144
- return inserted;
145
164
  }
146
165
 
147
166
  async function listWorkspacesForUser(user, options = {}) {
@@ -205,20 +224,16 @@ function createService({
205
224
  });
206
225
  }
207
226
 
208
- const inserted = await insertWithFreeSlug(
227
+ return returnJsonApiData(await createOwnedWorkspace(
209
228
  requestedSlug || toSlugPart(name),
210
229
  {
211
230
  name,
212
- ownerUserId: normalizedUserId,
213
231
  isPersonal: false,
214
232
  avatarUrl: ""
215
233
  },
234
+ { ...user, id: normalizedUserId },
216
235
  options
217
- );
218
-
219
- await workspaceMembershipsRepository.ensureOwnerMembership(inserted.id, normalizedUserId, options);
220
- await ensureWorkspaceSettingsForWorkspace(inserted, options);
221
- return returnJsonApiData(inserted);
236
+ ));
222
237
  }
223
238
 
224
239
  async function getWorkspaceForAuthenticatedUser(user, workspaceSlug, options = {}) {
@@ -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 */
@@ -49,6 +50,16 @@
49
50
  * @typedef {(acceptance: { invite: object, user: object }, options: { trx: unknown, context?: object }) => Promise<void>} WorkspaceInviteAcceptanceParticipant
50
51
  */
51
52
 
53
+ /**
54
+ * The `workspaces.workspace-created-participant` capability: the application's
55
+ * writes for a new workspace, personal (provisioned at sign-in) or created by
56
+ * `workspace.workspaces.create`. It runs after the workspace, its owner's
57
+ * membership and its settings are written, inside the uncommitted creation
58
+ * transaction, and a failure rolls the whole creation back. `owner` is the user
59
+ * who owns the workspace. Its options join that transaction: pass them to every call.
60
+ * @typedef {(created: { workspace: object, owner: object }, options: { trx: unknown, context?: object }) => Promise<void>} WorkspaceCreatedParticipant
61
+ */
62
+
52
63
  /**
53
64
  * The `workspaces.personal-workspace-name` capability: names the personal
54
65
  * workspace provisioned for a user. An empty name falls back to the default.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The `workspaces.workspace-created-participant` default when no feature
3
+ * provides one: creating a workspace writes the workspace, its owner
4
+ * membership and its settings only.
5
+ * @type {import("../types.js").WorkspaceCreatedParticipant}
6
+ */
7
+ async function noWorkspaceCreatedParticipant() {}
8
+
9
+ export { noWorkspaceCreatedParticipant };
@@ -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
  }),