@jskit-ai/users-core 0.2.15 → 0.2.17

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 (50) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/package.json +24 -17
  3. package/patterns/user-administration-server/PATTERN.md +63 -10
  4. package/patterns/user-administration-server/example/packages/users/package.json +5 -4
  5. package/patterns/user-administration-server/example/packages/users/src/server/UsersFeature.js +7 -5
  6. package/patterns/user-administration-server/example/packages/users/src/shared/index.js +1 -1
  7. package/patterns/user-administration-server/example/packages/users/src/shared/userCrud.js +21 -0
  8. package/patterns/user-administration-server/example/packages/users-workspace/package.json +11 -5
  9. package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +14 -5
  10. package/patterns/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +52 -0
  11. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/index.js +1 -1
  12. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userCrud.js +21 -0
  13. package/src/server/UsersFeature.js +10 -6
  14. package/src/server/UsersIdentityProvider.js +13 -29
  15. package/src/server/accountNotifications/accountNotificationsActions.js +3 -3
  16. package/src/server/accountNotifications/accountNotificationsRoutes.js +3 -3
  17. package/src/server/accountPreferences/accountPreferencesActions.js +3 -3
  18. package/src/server/accountPreferences/accountPreferencesRoutes.js +3 -3
  19. package/src/server/accountProfile/accountProfileActions.js +9 -9
  20. package/src/server/accountProfile/accountProfileRoutes.js +5 -5
  21. package/src/server/accountSecurity/accountSecurityActions.js +10 -10
  22. package/src/server/accountSecurity/accountSecurityRoutes.js +9 -9
  23. package/src/server/common/repositories/recordsByIds.js +38 -0
  24. package/src/server/common/repositories/userProfilesRepository.js +261 -146
  25. package/src/server/common/repositories/userSettingsRepository.js +37 -49
  26. package/src/server/common/services/authProfileSyncService.js +3 -5
  27. package/src/server/types.js +9 -1
  28. package/src/server/usersIdentity.js +11 -11
  29. package/src/server/usersRuntime.js +13 -11
  30. package/src/shared/resources/userProfileResource.js +43 -13
  31. package/src/shared/resources/userSettingsResource.js +35 -29
  32. package/test/accountSecurityService.test.js +2 -2
  33. package/test/authProfileSyncService.test.js +13 -9
  34. package/test/exportsContract.test.js +2 -0
  35. package/test/featureRuntime.test.js +63 -20
  36. package/test/i18nCodes.test.js +6 -10
  37. package/test/listByIds.mysql.test.js +5 -0
  38. package/test/listByIds.postgres.test.js +6 -0
  39. package/test/repositories.mysql.test.js +384 -0
  40. package/test/resourcesCanonical.test.js +58 -22
  41. package/test/support/listByIdsCases.js +115 -0
  42. package/test/support/usersDatabases.js +135 -0
  43. package/test/userSettingsInternalResource.test.js +3 -3
  44. package/test/userSettingsResource.test.js +3 -3
  45. package/test/usersPackageScaffoldContract.test.js +70 -12
  46. package/test/usersRouteRequestInputValidator.test.js +2 -2
  47. package/test/usersRouteResources.test.js +73 -29
  48. package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
  49. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
  50. package/test/repositoryContracts.test.js +0 -596
@@ -1,19 +1,13 @@
1
1
  import {
2
2
  findDuplicateEntryError,
3
3
  isLostDuplicateInsertRace,
4
- joinOrOpenTransaction,
5
4
  normalizeDbRecordId,
6
- resolveTransaction,
7
- retryDeadlocks,
8
5
  toIsoString
9
6
  } from "@jskit-ai/database-runtime/shared";
10
7
  import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
11
- import {
12
- createJsonRestContext,
13
- extractJsonRestCollectionRows,
14
- queryAllJsonRestCollectionRows
15
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
8
+ import { isSystemContext } from "@jskit-ai/resource-runtime/server";
16
9
  import { normalizeIdentity } from "../support/identity.js";
10
+ import { queryAllByIds } from "./recordsByIds.js";
17
11
  import { USERNAME_MAX_LENGTH, normalizeNullableString, normalizeNullableVersion, normalizeUsername } from "../../../shared/resources/userProfileValues.js";
18
12
 
19
13
  function normalizeProfileRecord(payload = null) {
@@ -77,7 +71,6 @@ function usernameBaseFromEmail(email) {
77
71
 
78
72
  // The base, then base-2 to base-1000.
79
73
  const USERNAME_CANDIDATE_LIMIT = 1000;
80
-
81
74
  function buildUsernameCandidate(baseUsername, suffix) {
82
75
  const normalizedBase = normalizeUsername(baseUsername) || "user";
83
76
  if (suffix < 1) {
@@ -110,6 +103,23 @@ function duplicateTargetsUsername(error) {
110
103
  return message.includes("username");
111
104
  }
112
105
 
106
+ function buildDuplicateUsernameConflictError(cause = undefined) {
107
+ const error = new Error("Username is already taken.", cause ? { cause } : undefined);
108
+ error.transactionOutcome = cause?.transactionOutcome;
109
+ error.code = "USER_PROFILE_USERNAME_CONFLICT";
110
+ return error;
111
+ }
112
+
113
+ // The fields a new profile needs, normalized; `context` names the call for its errors.
114
+ function requireNewProfile(profileLike, context) {
115
+ const payload = normalizeCreatePayload(profileLike);
116
+ const missing = ["authProvider", "authProviderUserSid", "email", "displayName"].filter((field) => !payload[field]);
117
+ if (missing.length > 0) {
118
+ throw new TypeError(`${context} requires ${missing.join(", ")}.`);
119
+ }
120
+ return payload;
121
+ }
122
+
113
123
  function buildDuplicateEmailConflictError(cause) {
114
124
  const error = new Error("Email is already linked to a different profile.", { cause });
115
125
  error.transactionOutcome = cause.transactionOutcome;
@@ -118,11 +128,14 @@ function buildDuplicateEmailConflictError(cause) {
118
128
  }
119
129
 
120
130
  /**
121
- * @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} api
131
+ * The username a profile gets: the base, or the first of base-2 to base-1000
132
+ * no other profile holds.
133
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} userProfiles
122
134
  * @param {string} baseUsername
123
- * @param {{ excludeUserId?: unknown, transaction?: object | null }} [options]
135
+ * @param {unknown} excludeUserId The profile whose own username stays available to it.
136
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
124
137
  */
125
- async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null, transaction = null } = {}) {
138
+ async function resolveUniqueUsername(userProfiles, baseUsername, excludeUserId, options) {
126
139
  const normalizedExcludeUserId = normalizeDbRecordId(excludeUserId, { fallback: null });
127
140
  const candidates = Array.from(
128
141
  { length: USERNAME_CANDIDATE_LIMIT },
@@ -130,18 +143,7 @@ async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null,
130
143
  );
131
144
 
132
145
  // One read of every profile holding a candidate, however many namesakes came before.
133
- const existingRows = await queryAllJsonRestCollectionRows(
134
- api.resources.userProfiles,
135
- {
136
- queryParams: {
137
- filters: {
138
- usernames: candidates
139
- }
140
- },
141
- transaction,
142
- format: "plain"
143
- }
144
- );
146
+ const existingRows = await userProfiles.queryAll({ filters: { usernames: candidates } }, options);
145
147
  const holderIdByUsername = new Map(
146
148
  existingRows.map((row) => [normalizeLowerText(row.username), normalizeDbRecordId(row.id, { fallback: null })])
147
149
  );
@@ -156,25 +158,25 @@ async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null,
156
158
  throw new Error("Unable to generate unique username.");
157
159
  }
158
160
 
159
- /** @param {{ api: import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi }} dependencies */
160
- function createRepository({ api }) {
161
- const withTransaction = (work) => retryDeadlocks(() => api.transaction(work));
162
-
163
- async function queryFirst(filters = {}, options = {}) {
164
- const rows = extractJsonRestCollectionRows(
165
- await api.resources.userProfiles.query(
166
- {
167
- queryParams: {
168
- filters
169
- },
170
- transaction: resolveTransaction(options),
171
- format: "plain"
172
- },
173
- createJsonRestContext(options.context)
174
- )
175
- );
161
+ /**
162
+ * The `users.profiles` capability: the users table's records. Every method
163
+ * takes the caller's options last and joins their transaction. Its reads
164
+ * `query`, `get` and `pageLimits` also serve a CRUD feature that names it as
165
+ * its `ownerRepository`.
166
+ * @param {object} dependencies
167
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.userProfiles The users table's handle.
168
+ * @param {import("../../types.js").UserSettingsRepository} dependencies.userSettings The settings that
169
+ * createWithSettings writes beside a profile.
170
+ */
171
+ function createRepository({ userProfiles, userSettings }) {
172
+ async function countProfiles(filters, options) {
173
+ const rows = await userProfiles.aggregate({ measures: { count: { count: "*" } }, filters }, options);
174
+ return Number(rows?.[0]?.count || 0);
175
+ }
176
176
 
177
- return rows[0] || null;
177
+ async function queryFirst(filters, options) {
178
+ const { records } = await userProfiles.query({ filters, page: { size: 1 } }, options);
179
+ return records[0] || null;
178
180
  }
179
181
 
180
182
  async function findById(userId, options = {}) {
@@ -212,77 +214,38 @@ function createRepository({ api }) {
212
214
  );
213
215
  }
214
216
 
215
- async function updateDisplayNameById(userId, displayName, options = {}) {
217
+ // A profile's changed fields, stamped with the update time; null for a missing id or profile.
218
+ async function patchProfile(userId, changes, options) {
216
219
  const normalizedUserId = normalizeRecordId(userId, { fallback: null });
217
220
  if (!normalizedUserId) {
218
221
  return null;
219
222
  }
220
223
 
221
- const updated = await api.resources.userProfiles.patch(
222
- {
223
- id: normalizedUserId,
224
- data: {
225
- displayName,
226
- updatedAt: new Date().toISOString()
227
- },
228
- format: "plain",
229
- returning: "full",
230
- transaction: resolveTransaction(options)
231
- },
232
- createJsonRestContext(options.context)
233
- );
224
+ return normalizeProfileRecord(await userProfiles.patch(
225
+ normalizedUserId,
226
+ { ...changes, updatedAt: new Date().toISOString() },
227
+ { ...options, missing: "skip" }
228
+ ));
229
+ }
234
230
 
235
- return normalizeProfileRecord(updated);
231
+ async function updateDisplayNameById(userId, displayName, options = {}) {
232
+ return patchProfile(userId, { displayName }, options);
236
233
  }
237
234
 
238
235
  async function updateAvatarById(userId, avatar = {}, options = {}) {
239
- const normalizedUserId = normalizeRecordId(userId, { fallback: null });
240
- if (!normalizedUserId) {
241
- return null;
242
- }
243
-
244
- const updated = await api.resources.userProfiles.patch(
245
- {
246
- id: normalizedUserId,
247
- data: {
248
- avatarStorageKey: avatar.avatarStorageKey ?? null,
249
- avatarVersion: avatar.avatarVersion ?? null,
250
- avatarUpdatedAt: toIsoString(avatar.avatarUpdatedAt ?? new Date()),
251
- updatedAt: new Date().toISOString()
252
- },
253
- format: "plain",
254
- returning: "full",
255
- transaction: resolveTransaction(options)
256
- },
257
- createJsonRestContext(options.context)
258
- );
259
-
260
- return normalizeProfileRecord(updated);
236
+ return patchProfile(userId, {
237
+ avatarStorageKey: avatar.avatarStorageKey ?? null,
238
+ avatarVersion: avatar.avatarVersion ?? null,
239
+ avatarUpdatedAt: toIsoString(avatar.avatarUpdatedAt ?? new Date())
240
+ }, options);
261
241
  }
262
242
 
263
243
  async function clearAvatarById(userId, options = {}) {
264
- const normalizedUserId = normalizeRecordId(userId, { fallback: null });
265
- if (!normalizedUserId) {
266
- return null;
267
- }
268
-
269
- const updated = await api.resources.userProfiles.patch(
270
- {
271
- id: normalizedUserId,
272
- data: {
273
- avatarStorageKey: null,
274
- avatarVersion: null,
275
- avatarUpdatedAt: null,
276
- updatedAt: new Date().toISOString()
277
- },
278
- format: "plain",
279
- returning: "full",
280
- transaction: resolveTransaction(options)
281
- },
282
- createJsonRestContext(options.context)
283
- );
284
-
285
- return normalizeProfileRecord(updated);
244
+ return patchProfile(userId, {
245
+ avatarStorageKey: null,
246
+ avatarVersion: null,
247
+ avatarUpdatedAt: null
248
+ }, options);
286
249
  }
287
250
 
288
251
  async function upsert(profileLike = {}, options = {}) {
@@ -302,69 +265,45 @@ function createRepository({ api }) {
302
265
  throw new TypeError("upsert requires email and displayName.");
303
266
  }
304
267
 
305
- const executeUpsert = async (trx) => {
306
- const existing = await findByIdentity(identity, {
307
- trx,
308
- context: options.context
309
- });
268
+ const executeUpsert = async (txOptions) => {
269
+ const existing = await findByIdentity(identity, txOptions);
310
270
 
311
271
  if (existing) {
312
272
  const existingUsername = normalizeUsername(existing.username);
313
273
  const username = existingUsername || (
314
274
  await resolveUniqueUsername(
315
- api,
275
+ userProfiles,
316
276
  requestedUsername || usernameBaseFromEmail(email),
317
- { excludeUserId: existing.id, transaction: trx }
277
+ existing.id,
278
+ txOptions
318
279
  )
319
280
  );
320
281
 
321
- const updated = await api.resources.userProfiles.patch(
322
- {
323
- id: normalizeDbRecordId(existing.id, { fallback: null }),
324
- data: {
325
- email,
326
- displayName,
327
- username,
328
- updatedAt: new Date().toISOString()
329
- },
330
- format: "plain",
331
- returning: "full",
332
- transaction: trx
333
- },
334
- createJsonRestContext(options.context)
335
- );
336
-
337
- return normalizeProfileRecord(updated);
282
+ return patchProfile(existing.id, { email, displayName, username }, txOptions);
338
283
  }
339
284
 
340
285
  const username = await resolveUniqueUsername(
341
- api,
286
+ userProfiles,
342
287
  requestedUsername || usernameBaseFromEmail(email),
343
- { transaction: trx }
288
+ null,
289
+ txOptions
344
290
  );
345
291
 
346
- const created = await api.resources.userProfiles.post(
292
+ return normalizeProfileRecord(await userProfiles.create(
347
293
  {
348
- data: {
349
- authProvider: identity.provider,
350
- authProviderUserSid: identity.providerUserId,
351
- email,
352
- displayName,
353
- username,
354
- createdAt: new Date().toISOString()
355
- },
356
- format: "plain",
357
- returning: "full",
358
- transaction: trx
294
+ authProvider: identity.provider,
295
+ authProviderUserSid: identity.providerUserId,
296
+ email,
297
+ displayName,
298
+ username,
299
+ createdAt: new Date().toISOString()
359
300
  },
360
- createJsonRestContext(options.context)
361
- );
362
-
363
- return normalizeProfileRecord(created);
301
+ txOptions
302
+ ));
364
303
  };
365
304
 
366
305
  try {
367
- return await joinOrOpenTransaction(options, withTransaction, executeUpsert);
306
+ return await userProfiles.withTransaction(options, executeUpsert);
368
307
  } catch (error) {
369
308
  if (["pending", "rolledBack"].includes(error?.transactionOutcome) && duplicateTargetsEmail(error)) {
370
309
  throw buildDuplicateEmailConflictError(error);
@@ -384,15 +323,191 @@ function createRepository({ api }) {
384
323
  }
385
324
  }
386
325
 
326
+ /**
327
+ * Creates (or, for an identity that already has one, updates) a profile and
328
+ * gives it its settings, in one transaction: the caller's, or one it opens.
329
+ * Settings start from the defaults; the given fields replace them.
330
+ * @param {{ profile: object, settings?: object }} input
331
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
332
+ */
333
+ async function createWithSettings({ profile, settings = {} }, options = {}) {
334
+ return userProfiles.withTransaction(options, async (txOptions) => {
335
+ const created = await upsert(profile, txOptions);
336
+ return {
337
+ profile: created,
338
+ settings: await userSettings.patchUserSettings(created.id, settings, txOptions)
339
+ };
340
+ });
341
+ }
342
+
343
+ /**
344
+ * Creates a profile with the id it is given, as an application that keeps
345
+ * the ids of an earlier users table does, in one transaction: the caller's,
346
+ * or one it opens. Its username is the one given or one made from its email,
347
+ * the first of base, base-2 to base-1000 no other profile holds. A taken id or
348
+ * identity fails. On PostgreSQL the id sequence does not move past a given
349
+ * id, so an import advances it (setval) before the table creates profiles of
350
+ * its own again.
351
+ * @param {{ id: unknown, authProvider: string, authProviderUserSid: string, email: string, displayName: string, username?: string, avatarStorageKey?: string | null, avatarVersion?: string | null, avatarUpdatedAt?: Date | string | null }} profile
352
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
353
+ */
354
+ async function createWithId(profile, options = {}) {
355
+ const id = normalizeDbRecordId(profile?.id, { fallback: null });
356
+ if (!id) {
357
+ throw new TypeError("createWithId requires id.");
358
+ }
359
+ const payload = requireNewProfile(profile, "createWithId");
360
+ return userProfiles.withTransaction(options, async (txOptions) => {
361
+ const username = await resolveUniqueUsername(
362
+ userProfiles,
363
+ payload.username || usernameBaseFromEmail(payload.email),
364
+ null,
365
+ txOptions
366
+ );
367
+ const now = new Date().toISOString();
368
+ return normalizeProfileRecord(await userProfiles.create(
369
+ { ...payload, id, username, createdAt: now, updatedAt: now },
370
+ txOptions
371
+ ));
372
+ });
373
+ }
374
+
375
+ /**
376
+ * The profiles with these emails, compared in lower case, in one read; an
377
+ * email no profile has is left out.
378
+ * @param {readonly string[]} emails
379
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
380
+ */
381
+ async function listByEmails(emails, options = {}) {
382
+ if (!Array.isArray(emails)) {
383
+ throw new TypeError("listByEmails takes an array of emails.");
384
+ }
385
+ const normalizedEmails = [...new Set(emails.map((email) => normalizeLowerText(email)).filter(Boolean))];
386
+ if (normalizedEmails.length < 1) {
387
+ return [];
388
+ }
389
+ const rows = await userProfiles.queryAll({ filters: { emails: normalizedEmails } }, options);
390
+ return rows.map(normalizeProfileRecord);
391
+ }
392
+
393
+ /**
394
+ * The profiles with these ids, all of them in one call however many, sorted
395
+ * by id: one read per 1,000 distinct ids, each joining the caller's
396
+ * transaction and seeing what `query` sees for the caller's context. An id
397
+ * named twice answers its profile once; an id naming no profile the caller
398
+ * can see, or that is no id, is left out.
399
+ * @param {readonly unknown[]} userIds
400
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
401
+ */
402
+ async function listByIds(userIds, options = {}) {
403
+ return (await queryAllByIds(userProfiles, "listByIds", userIds, options)).map(normalizeProfileRecord);
404
+ }
405
+
406
+ /**
407
+ * Creates the profiles whose identity (authProvider and authProviderUserSid)
408
+ * has none yet, in one INSERT per chunk, and leaves those that have one as
409
+ * they are: a bulk import that may run again. Only background work may call
410
+ * it, in a system context (`systemContext(reason)`), since it writes users no
411
+ * caller signed in as. Each row names its username; an email or username
412
+ * another identity holds fails the whole call.
413
+ * @param {ReadonlyArray<{ authProvider: string, authProviderUserSid: string, email: string, displayName: string, username: string }>} profiles
414
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
415
+ * @returns {Promise<string[]>} The ids of the profiles it created; a row whose identity already had one adds none.
416
+ */
417
+ async function createManyIgnoringExisting(profiles, options = {}) {
418
+ if (!isSystemContext(options.context)) {
419
+ throw new TypeError("createManyIgnoringExisting runs only in a system context: pass { context: systemContext(reason) }.");
420
+ }
421
+ if (!Array.isArray(profiles)) {
422
+ throw new TypeError("createManyIgnoringExisting takes an array of profiles.");
423
+ }
424
+ const now = new Date().toISOString();
425
+ const rows = profiles.map((profile, index) => {
426
+ const payload = requireNewProfile(profile, `createManyIgnoringExisting row ${index}`);
427
+ if (!payload.username) {
428
+ throw new TypeError(`createManyIgnoringExisting row ${index} requires username.`);
429
+ }
430
+ return { ...payload, createdAt: now, updatedAt: now };
431
+ });
432
+ if (rows.length < 1) {
433
+ return [];
434
+ }
435
+ return userProfiles.createMany(rows, {
436
+ ...options,
437
+ returning: "ids",
438
+ onConflict: { keys: ["authProvider", "authProviderUserSid"], action: "ignore" }
439
+ });
440
+ }
441
+
442
+ /**
443
+ * Gives a profile a new username, in one transaction: the caller's, or one
444
+ * it opens. A username another profile holds is USER_PROFILE_USERNAME_CONFLICT,
445
+ * found before the write so the caller's transaction stays usable; null for a
446
+ * missing id or profile.
447
+ * @param {unknown} userId
448
+ * @param {string} username
449
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
450
+ */
451
+ async function changeUsername(userId, username, options = {}) {
452
+ const normalizedUsername = normalizeUsername(username);
453
+ if (!normalizedUsername) {
454
+ throw new TypeError("changeUsername requires a username.");
455
+ }
456
+ const normalizedUserId = normalizeDbRecordId(userId, { fallback: null });
457
+ try {
458
+ return await userProfiles.withTransaction(options, async (txOptions) => {
459
+ const holders = await userProfiles.queryAll({ filters: { usernames: [normalizedUsername] } }, txOptions);
460
+ if (holders.some((row) => normalizeDbRecordId(row.id, { fallback: null }) !== normalizedUserId)) {
461
+ throw buildDuplicateUsernameConflictError();
462
+ }
463
+ return patchProfile(userId, { username: normalizedUsername }, txOptions);
464
+ });
465
+ } catch (error) {
466
+ // Another request took it between the read and the write.
467
+ if (["pending", "rolledBack"].includes(error?.transactionOutcome) && duplicateTargetsUsername(error)) {
468
+ throw buildDuplicateUsernameConflictError(error);
469
+ }
470
+ throw error;
471
+ }
472
+ }
473
+
474
+ /**
475
+ * The number of users, leaving out `excludeIds` and, with `createdSince`,
476
+ * those created before it; with `authProvider`, only those who sign in with it.
477
+ * @param {{ excludeIds?: readonly unknown[], createdSince?: Date | string | null, authProvider?: string }} [criteria]
478
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
479
+ */
480
+ async function countUsers({ excludeIds = [], createdSince = null, authProvider = "" } = {}, options = {}) {
481
+ const filters = {
482
+ ...(createdSince == null ? {} : { createdSince: toIsoString(createdSince) }),
483
+ ...(normalizeLowerText(authProvider) ? { authProvider: normalizeLowerText(authProvider) } : {})
484
+ };
485
+ const ids = [...new Set(excludeIds.map((id) => normalizeDbRecordId(id, { fallback: null })).filter(Boolean))];
486
+ const total = await countProfiles(filters, options);
487
+ // The id filter has no "not in": the excluded users who match are subtracted.
488
+ return ids.length < 1 ? total : total - await countProfiles({ ...filters, id: ids }, options);
489
+ }
490
+
387
491
  return Object.freeze({
388
- withTransaction,
492
+ withTransaction: userProfiles.withTransaction,
389
493
  findById,
390
494
  findByEmail,
391
495
  findByIdentity,
392
496
  updateDisplayNameById,
393
497
  updateAvatarById,
394
498
  clearAvatarById,
395
- upsert
499
+ upsert,
500
+ createWithSettings,
501
+ createWithId,
502
+ createManyIgnoringExisting,
503
+ listByEmails,
504
+ listByIds,
505
+ changeUsername,
506
+ countUsers,
507
+ // The CRUD surface's reads (a CRUD feature serving the users table names this repository as its ownerRepository).
508
+ query: userProfiles.query,
509
+ get: userProfiles.get,
510
+ pageLimits: userProfiles.pageLimits
396
511
  });
397
512
  }
398
513
 
@@ -1,10 +1,7 @@
1
- import { isLostDuplicateInsertRace, resolveTransaction, retryDeadlocks } from "@jskit-ai/database-runtime/shared";
1
+ import { isLostDuplicateInsertRace } from "@jskit-ai/database-runtime/shared";
2
2
  import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
3
- import {
4
- createJsonRestContext,
5
- extractJsonRestCollectionRows
6
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
7
3
  import { DEFAULT_USER_SETTINGS, normalizeLocaleCode } from "../../../shared/settings.js";
4
+ import { queryAllByIds } from "./recordsByIds.js";
8
5
 
9
6
  const USER_SETTINGS_PATCH_FIELDS = Object.freeze([
10
7
  "theme",
@@ -33,6 +30,11 @@ function pickPatchFields(source = {}) {
33
30
  return patch;
34
31
  }
35
32
 
33
+ // Rows saved before locales were canonical hold lowercased tags ("en-us").
34
+ function withCanonicalLocale(row) {
35
+ return typeof row?.locale === "string" ? { ...row, locale: normalizeLocaleCode(row.locale) } : row;
36
+ }
37
+
36
38
  function buildDefaultUserSettingsCreatePayload(userId) {
37
39
  return {
38
40
  id: userId,
@@ -51,36 +53,33 @@ function buildDefaultUserSettingsCreatePayload(userId) {
51
53
  };
52
54
  }
53
55
 
54
- /** @param {{ api: import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi }} dependencies */
55
- function createRepository({ api }) {
56
- const withTransaction = (work) => retryDeadlocks(() => api.transaction(work));
57
-
58
- async function queryFirst(filters = {}, options = {}) {
59
- const rows = extractJsonRestCollectionRows(
60
- await api.resources.userSettings.query(
61
- {
62
- queryParams: {
63
- filters
64
- },
65
- transaction: resolveTransaction(options),
66
- format: "plain"
67
- },
68
- createJsonRestContext(options.context)
69
- )
70
- );
71
-
72
- const row = rows[0] || null;
73
- // Rows saved before locales were canonical hold lowercased tags ("en-us").
74
- return typeof row?.locale === "string" ? { ...row, locale: normalizeLocaleCode(row.locale) } : row;
75
- }
76
-
56
+ /**
57
+ * The `users.settings` capability: the user_settings table's records. Every
58
+ * method takes the caller's options last and joins their transaction.
59
+ * @param {{ userSettings: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }} dependencies
60
+ * The user_settings table's handle.
61
+ */
62
+ function createRepository({ userSettings }) {
77
63
  async function findByUserId(userId, options = {}) {
78
64
  const normalizedUserId = normalizeRecordId(userId, { fallback: null });
79
65
  if (!normalizedUserId) {
80
66
  return null;
81
67
  }
82
68
 
83
- return queryFirst({ id: normalizedUserId }, options);
69
+ const { records } = await userSettings.query({ filters: { id: normalizedUserId }, page: { size: 1 } }, options);
70
+ return withCanonicalLocale(records[0] || null);
71
+ }
72
+
73
+ /**
74
+ * The settings of these users, all of them in one call however many, sorted
75
+ * by user id: one read per 1,000 distinct ids, each joining the caller's
76
+ * transaction. A user named twice answers once; a user without settings,
77
+ * or a value that is no id, is left out.
78
+ * @param {readonly unknown[]} userIds
79
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
80
+ */
81
+ async function listByUserIds(userIds, options = {}) {
82
+ return (await queryAllByIds(userSettings, "listByUserIds", userIds, options)).map(withCanonicalLocale);
84
83
  }
85
84
 
86
85
  async function ensureForUserId(userId, options = {}) {
@@ -95,16 +94,9 @@ function createRepository({ api }) {
95
94
  }
96
95
 
97
96
  try {
98
- await api.resources.userSettings.post(
99
- {
100
- data: buildDefaultUserSettingsCreatePayload(normalizedUserId),
101
- format: "plain",
102
- returning: "full",
103
- transaction: resolveTransaction(options)
104
- },
105
- createJsonRestContext(options.context)
106
- );
97
+ await userSettings.create(buildDefaultUserSettingsCreatePayload(normalizedUserId), { ...options, returning: "none" });
107
98
  } catch (error) {
99
+ // A standalone insert that lost to another one reads the winner; inside the caller's transaction it fails it.
108
100
  if (!isLostDuplicateInsertRace(error, options)) {
109
101
  throw error;
110
102
  }
@@ -127,18 +119,13 @@ function createRepository({ api }) {
127
119
  return findByUserId(normalizedUserId, options);
128
120
  }
129
121
 
130
- await api.resources.userSettings.patch(
122
+ await userSettings.patch(
123
+ normalizedUserId,
131
124
  {
132
- id: normalizedUserId,
133
- data: {
134
- ...updatePayload,
135
- updatedAt: new Date().toISOString()
136
- },
137
- format: "plain",
138
- returning: "full",
139
- transaction: resolveTransaction(options)
125
+ ...updatePayload,
126
+ updatedAt: new Date().toISOString()
140
127
  },
141
- createJsonRestContext(options.context)
128
+ { ...options, returning: "none" }
142
129
  );
143
130
 
144
131
  return findByUserId(normalizedUserId, options);
@@ -170,8 +157,9 @@ function createRepository({ api }) {
170
157
  }
171
158
 
172
159
  return Object.freeze({
173
- withTransaction,
160
+ withTransaction: userSettings.withTransaction,
174
161
  findByUserId,
162
+ listByUserIds,
175
163
  ensureForUserId,
176
164
  patchUserSettings,
177
165
  updatePreferences,
@@ -1,4 +1,3 @@
1
- import { joinOrOpenTransaction } from "@jskit-ai/database-runtime/shared";
2
1
  import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
2
  import { normalizeIdentity } from "../support/identity.js";
4
3
 
@@ -93,7 +92,7 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
93
92
  * contributors (personal workspace provisioning). With `onlyWhenChanged`, an existing row that already
94
93
  * matches the identity is answered after one read, without that work: an ordinary request's check.
95
94
  * @param {object} profileLike
96
- * @param {{ onlyWhenChanged?: boolean, trx?: object }} [options]
95
+ * @param {{ onlyWhenChanged?: boolean, trx?: object, context?: object }} [options]
97
96
  */
98
97
  async function syncIdentityProfile(profileLike, { onlyWhenChanged = false, ...options } = {}) {
99
98
  const normalized = buildNormalizedIdentityProfile(profileLike);
@@ -103,8 +102,7 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
103
102
  }
104
103
  const lifecycleContributors = resolveLifecycleContributors();
105
104
 
106
- const runSync = async (trx) => {
107
- const operationOptions = { ...options, trx };
105
+ const runSync = async (operationOptions) => {
108
106
  const existing = await findByIdentity(normalized, operationOptions);
109
107
  let created = false;
110
108
  if (!profileNeedsUpdate(existing, normalized)) {
@@ -135,7 +133,7 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
135
133
  return synchronizedProfile;
136
134
  };
137
135
 
138
- return joinOrOpenTransaction(options, userProfilesRepository.withTransaction, runSync);
136
+ return userProfilesRepository.withTransaction(options, runSync);
139
137
  }
140
138
 
141
139
  return Object.freeze({