@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
@@ -2,7 +2,15 @@
2
2
 
3
3
  /** @typedef {ReturnType<typeof import("./usersRuntime.js").createUsersRuntime>} UsersCore */
4
4
  /** @typedef {ReturnType<typeof import("./usersExtensions.js").createUsersExtensions>} UsersExtensions */
5
- /** @typedef {ReturnType<typeof import("./usersIdentity.js").createUsersIdentity>} UsersIdentity */
5
+ /**
6
+ * The handles of the tables `users.identity` owns: users (`userProfiles`) and user_settings (`userSettings`).
7
+ * @typedef {{
8
+ * userProfiles: import("@jskit-ai/resource-runtime/server/types").ResourceHandle,
9
+ * userSettings: import("@jskit-ai/resource-runtime/server/types").ResourceHandle
10
+ * }} UsersResources
11
+ */
12
+ /** @typedef {ReturnType<typeof import("./common/repositories/userProfilesRepository.js").createRepository>} UsersProfiles The users table's records: `users.profiles`. */
13
+ /** @typedef {ReturnType<typeof import("./common/repositories/userSettingsRepository.js").createRepository>} UsersSettings The users' settings records: `users.settings`. */
6
14
 
7
15
  /**
8
16
  * The users' profile repository, as the account services receive it.
@@ -3,24 +3,24 @@ import { createRepository as createUserSettingsRepository } from "./common/repos
3
3
  import { createService as createAuthProfileSyncService } from "./common/services/authProfileSyncService.js";
4
4
 
5
5
  /**
6
- * The users' profile and settings records, and the projector that keeps a
7
- * profile in step with the identity that signs in.
6
+ * The users' profile and settings records (`users.profiles`, `users.settings`),
7
+ * and the projector that keeps a profile in step with the identity that signs
8
+ * in (`auth.profile.projector`).
8
9
  * @param {object} dependencies
9
- * @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} dependencies.jsonRestApi
10
+ * @param {import("./types.js").UsersResources} dependencies.resources The handles of the users and user_settings tables.
10
11
  * @param {import("./types.js").UsersExtensions} dependencies.extensions
11
12
  */
12
- function createUsersIdentity({ jsonRestApi, extensions }) {
13
- const repositories = Object.freeze({
14
- userProfiles: createUserProfilesRepository({ api: jsonRestApi }),
15
- userSettings: createUserSettingsRepository({ api: jsonRestApi })
16
- });
13
+ function createUsersIdentity({ resources, extensions }) {
14
+ const settings = createUserSettingsRepository({ userSettings: resources.userSettings });
15
+ const profiles = createUserProfilesRepository({ userProfiles: resources.userProfiles, userSettings: settings });
17
16
  const profileProjector = createAuthProfileSyncService({
18
- userProfilesRepository: repositories.userProfiles,
19
- userSettingsRepository: repositories.userSettings,
17
+ userProfilesRepository: profiles,
18
+ userSettingsRepository: settings,
20
19
  resolveLifecycleContributors: extensions.profileSyncLifecycleContributors
21
20
  });
22
21
  return Object.freeze({
23
- repositories,
22
+ profiles,
23
+ settings,
24
24
  profileProjector
25
25
  });
26
26
  }
@@ -7,16 +7,22 @@ import { createService as createAvatarStorageService } from "./accountProfile/av
7
7
  import { createService as createAccountSecurityService } from "./accountSecurity/accountSecurityService.js";
8
8
 
9
9
  /**
10
- * The `users.core` capability: the users' repositories and the account
11
- * services built on them.
10
+ * The `users.core` capability: the account services built on the users'
11
+ * records. The records themselves are `users.profiles` and `users.settings`.
12
12
  * @param {object} dependencies
13
13
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService
14
- * @param {import("./types.js").UsersIdentity} dependencies.identity
14
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
15
+ * @param {import("./types.js").UsersProfiles} dependencies.profiles
16
+ * @param {import("./types.js").UsersSettings} dependencies.settings
15
17
  * @param {import("@jskit-ai/storage-runtime/server/types").RuntimeStorage} dependencies.storage
16
18
  */
17
- function createUsersRuntime({ authService, identity, storage }) {
18
- const userProfilesRepository = identity.repositories.userProfiles;
19
- const userSettingsRepository = identity.repositories.userSettings;
19
+ function createUsersRuntime({
20
+ authService,
21
+ profileProjector,
22
+ profiles: userProfilesRepository,
23
+ settings: userSettingsRepository,
24
+ storage
25
+ }) {
20
26
  const avatarStorageService = createAvatarStorageService({ storage });
21
27
  const avatarService = createAvatarService({ userProfilesRepository, avatarStorageService });
22
28
  const accountProfileService = createAccountProfileService({
@@ -42,17 +48,13 @@ function createUsersRuntime({ authService, identity, storage }) {
42
48
  });
43
49
 
44
50
  return Object.freeze({
45
- repositories: Object.freeze({
46
- userProfiles: userProfilesRepository,
47
- userSettings: userSettingsRepository
48
- }),
49
51
  services: Object.freeze({
50
52
  accountNotifications: accountNotificationsService,
51
53
  accountPreferences: accountPreferencesService,
52
54
  accountProfile: accountProfileService,
53
55
  accountSecurity: accountSecurityService,
54
56
  avatar: avatarService,
55
- profileProjector: identity.profileProjector
57
+ profileProjector
56
58
  }),
57
59
  shared: USERS_SHARED_API
58
60
  });
@@ -1,7 +1,9 @@
1
1
  import { createSchema } from "json-rest-schema";
2
2
  import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
3
  import { normalizeLowerText, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
4
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
4
+ import { defineApiContract } from "@jskit-ai/resource-core/shared/apiContract";
5
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
6
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
5
7
  import { OPERATION_MESSAGES } from "../operationMessages.js";
6
8
  import { userProfileOutputSchema } from "./accountSettingsSchemas.js";
7
9
  import { userSettingsOutputSchema } from "./userSettingsResource.js";
@@ -61,12 +63,23 @@ const avatarUploadBodySchema = createSchema({
61
63
  }
62
64
  });
63
65
 
64
- const userProfileResource = defineCrudResource({
65
- namespace: "userProfile",
66
+ // The users table.
67
+ const userProfileTableResource = defineTableResource({
68
+ name: "userProfiles",
66
69
  tableName: "users",
70
+ ownership: "public",
67
71
  searchSchema: {
68
- id: { type: "id", actualField: "id" },
69
- usernames: { type: "array", actualField: "username", filterOperator: "in", items: { type: "string" } }
72
+ usernames: { type: "array", actualField: "username", filterOperator: "in", items: { type: "string" } },
73
+ emails: { type: "array", actualField: "email", filterOperator: "in", items: { type: "string" } },
74
+ createdSince: { type: "dateTime", actualField: "createdAt", filterOperator: ">=" },
75
+ // A list's free-text search: every word in the display name, email or username.
76
+ q: {
77
+ type: "string",
78
+ oneOf: ["displayName", "email", "username"],
79
+ filterOperator: "like",
80
+ splitBy: " ",
81
+ matchAll: true
82
+ }
70
83
  },
71
84
  schema: {
72
85
  authProvider: {
@@ -130,7 +143,6 @@ const userProfileResource = defineCrudResource({
130
143
  },
131
144
  createdAt: {
132
145
  type: "dateTime",
133
- default: "now()",
134
146
  storage: {
135
147
  column: "created_at",
136
148
  writeSerializer: "datetime-utc"
@@ -138,20 +150,38 @@ const userProfileResource = defineCrudResource({
138
150
  },
139
151
  updatedAt: {
140
152
  type: "dateTime",
141
- default: "now()",
142
153
  storage: {
143
154
  column: "updated_at",
144
155
  writeSerializer: "datetime-utc"
145
156
  }
146
157
  }
147
158
  },
159
+ // A users list reads by name, then email; the id breaks ties.
160
+ defaultSort: ["displayName", "email"]
161
+ });
162
+
163
+ // The account profile's CRUD surface on the users table: view, list, create,
164
+ // replace and patch, each with the account profile's output and display name
165
+ // body. No JSKIT route serves it; an application that offers these operations
166
+ // serves this contract.
167
+ const userProfileCrud = defineCrudContract(userProfileTableResource, {
168
+ namespace: "userProfile",
169
+ messages: OPERATION_MESSAGES,
170
+ operations: ["view", "list", "create", "replace", "patch"],
171
+ output: userProfileOutputSchema,
172
+ body: userProfileBodySchema
173
+ });
174
+
175
+ // The signed-in user's profile over HTTP.
176
+ const userProfileContract = defineApiContract({
177
+ namespace: "userProfile",
148
178
  messages: OPERATION_MESSAGES,
149
- crudOperations: ["view", "list", "create", "replace", "patch"],
150
- crud: {
151
- output: userProfileOutputSchema,
152
- body: userProfileBodySchema
153
- },
154
179
  operations: {
180
+ patch: {
181
+ method: "PATCH",
182
+ body: userProfileBodySchema,
183
+ output: userProfileOutputSchema
184
+ },
155
185
  avatarUpload: {
156
186
  method: "POST",
157
187
  body: avatarUploadBodySchema,
@@ -165,4 +195,4 @@ const userProfileResource = defineCrudResource({
165
195
  }
166
196
  });
167
197
 
168
- export { userProfileResource };
198
+ export { userProfileContract, userProfileCrud, userProfileTableResource };
@@ -2,9 +2,11 @@ import { createSchema } from "json-rest-schema";
2
2
  import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
3
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
4
4
  import {
5
- createSchemaDefinition
6
- } from "@jskit-ai/resource-core/shared/resource";
7
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
5
+ createSchemaDefinition,
6
+ defineApiContract
7
+ } from "@jskit-ai/resource-core/shared/apiContract";
8
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
9
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
8
10
  import { OPERATION_MESSAGES } from "../operationMessages.js";
9
11
  import { DEFAULT_USER_SETTINGS, normalizeLocaleCode } from "../settings.js";
10
12
  import {
@@ -64,6 +66,7 @@ function normalizePositiveInteger(value) {
64
66
  return Number(value);
65
67
  }
66
68
 
69
+ // Every preference and notification setting at once: the CRUD contract's body.
67
70
  const userSettingsBodySchema = createSchema({
68
71
  theme: { type: "string", required: true, minLength: 1, maxLength: 32 },
69
72
  locale: { type: "string", required: true, minLength: 1, maxLength: 24 },
@@ -277,38 +280,34 @@ const logoutOtherSessionsOutputSchema = createSchema({
277
280
  ok: { type: "boolean", required: true }
278
281
  });
279
282
 
280
- const userSettingsResource = defineCrudResource({
281
- namespace: "userSettings",
283
+ // The user_settings table, one row per user.
284
+ const userSettingsTableResource = defineTableResource({
285
+ name: "userSettings",
282
286
  tableName: "user_settings",
287
+ ownership: "public",
288
+ foreignKeys: [{ columns: ["id"], referencedTableName: "users" }],
283
289
  idProperty: "user_id",
284
- searchSchema: {
285
- id: { type: "id", actualField: "id" }
286
- },
287
290
  schema: {
288
291
  id: {
289
292
  type: "id",
290
293
  primary: true,
291
294
  required: true,
292
- search: true,
293
295
  storage: { column: "user_id" }
294
296
  },
295
297
  theme: {
296
298
  type: "string",
297
- required: true,
298
299
  max: 32,
299
300
  defaultTo: DEFAULT_USER_SETTINGS.theme,
300
301
  setter: (value) => normalizeText(value)
301
302
  },
302
303
  locale: {
303
304
  type: "string",
304
- required: true,
305
305
  max: 24,
306
306
  defaultTo: DEFAULT_USER_SETTINGS.locale,
307
307
  setter: (value) => normalizeLocaleCode(value)
308
308
  },
309
309
  timeZone: {
310
310
  type: "string",
311
- required: true,
312
311
  max: 64,
313
312
  defaultTo: DEFAULT_USER_SETTINGS.timeZone,
314
313
  storage: { column: "time_zone" },
@@ -316,7 +315,6 @@ const userSettingsResource = defineCrudResource({
316
315
  },
317
316
  dateFormat: {
318
317
  type: "string",
319
- required: true,
320
318
  max: 32,
321
319
  defaultTo: DEFAULT_USER_SETTINGS.dateFormat,
322
320
  storage: { column: "date_format" },
@@ -324,7 +322,6 @@ const userSettingsResource = defineCrudResource({
324
322
  },
325
323
  numberFormat: {
326
324
  type: "string",
327
- required: true,
328
325
  max: 32,
329
326
  defaultTo: DEFAULT_USER_SETTINGS.numberFormat,
330
327
  storage: { column: "number_format" },
@@ -332,7 +329,6 @@ const userSettingsResource = defineCrudResource({
332
329
  },
333
330
  currencyCode: {
334
331
  type: "string",
335
- required: true,
336
332
  minLength: 3,
337
333
  maxLength: 3,
338
334
  defaultTo: DEFAULT_USER_SETTINGS.currencyCode,
@@ -341,7 +337,6 @@ const userSettingsResource = defineCrudResource({
341
337
  },
342
338
  avatarSize: {
343
339
  type: "number",
344
- required: true,
345
340
  min: 1,
346
341
  defaultTo: DEFAULT_USER_SETTINGS.avatarSize,
347
342
  storage: { column: "avatar_size" },
@@ -349,37 +344,31 @@ const userSettingsResource = defineCrudResource({
349
344
  },
350
345
  passwordSignInEnabled: {
351
346
  type: "boolean",
352
- required: true,
353
347
  defaultTo: DEFAULT_USER_SETTINGS.passwordSignInEnabled,
354
348
  storage: { column: "password_sign_in_enabled" }
355
349
  },
356
350
  passwordSetupRequired: {
357
351
  type: "boolean",
358
- required: true,
359
352
  defaultTo: DEFAULT_USER_SETTINGS.passwordSetupRequired,
360
353
  storage: { column: "password_setup_required" }
361
354
  },
362
355
  productUpdates: {
363
356
  type: "boolean",
364
- required: true,
365
357
  defaultTo: DEFAULT_USER_SETTINGS.productUpdates,
366
358
  storage: { column: "notify_product_updates" }
367
359
  },
368
360
  accountActivity: {
369
361
  type: "boolean",
370
- required: true,
371
362
  defaultTo: DEFAULT_USER_SETTINGS.accountActivity,
372
363
  storage: { column: "notify_account_activity" }
373
364
  },
374
365
  securityAlerts: {
375
366
  type: "boolean",
376
- required: true,
377
367
  defaultTo: DEFAULT_USER_SETTINGS.securityAlerts,
378
368
  storage: { column: "notify_security_alerts" }
379
369
  },
380
370
  createdAt: {
381
371
  type: "dateTime",
382
- default: "now()",
383
372
  storage: {
384
373
  column: "created_at",
385
374
  writeSerializer: "datetime-utc"
@@ -387,20 +376,35 @@ const userSettingsResource = defineCrudResource({
387
376
  },
388
377
  updatedAt: {
389
378
  type: "dateTime",
390
- default: "now()",
391
379
  storage: {
392
380
  column: "updated_at",
393
381
  writeSerializer: "datetime-utc"
394
382
  }
395
383
  }
396
384
  },
385
+ });
386
+
387
+ // The account settings' CRUD surface on the user_settings table: view, list,
388
+ // create, replace and patch, each with the account settings output and every
389
+ // setting as its body. No JSKIT route serves it; an application that offers
390
+ // these operations serves this contract.
391
+ const userSettingsCrud = defineCrudContract(userSettingsTableResource, {
392
+ namespace: "userSettings",
393
+ messages: OPERATION_MESSAGES,
394
+ operations: ["view", "list", "create", "replace", "patch"],
395
+ output: userSettingsOutputValidator,
396
+ body: userSettingsBodySchema
397
+ });
398
+
399
+ // The signed-in user's settings over HTTP.
400
+ const userSettingsContract = defineApiContract({
401
+ namespace: "userSettings",
397
402
  messages: OPERATION_MESSAGES,
398
- crudOperations: ["view", "list", "create", "replace", "patch"],
399
- crud: {
400
- output: userSettingsOutputValidator,
401
- body: userSettingsBodySchema
402
- },
403
403
  operations: {
404
+ view: {
405
+ method: "GET",
406
+ output: userSettingsOutputValidator
407
+ },
404
408
  preferencesUpdate: {
405
409
  method: "PATCH",
406
410
  body: userSettingsPreferencesSchema,
@@ -446,6 +450,8 @@ export {
446
450
  USER_SETTINGS_NOTIFICATION_KEYS,
447
451
  USER_SETTINGS_PREFERENCE_KEYS,
448
452
  userSettingsOutputSchema,
453
+ userSettingsContract,
454
+ userSettingsCrud,
449
455
  userSettingsOutputValidator,
450
- userSettingsResource
456
+ userSettingsTableResource
451
457
  };
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { buildSecurityStatusFromAuthMethodsStatus } from "@jskit-ai/auth-core/shared/authSecurityStatus";
4
4
  import { validateOperationSection } from "@jskit-ai/http-runtime/shared/validators/operationValidation";
5
5
  import { createService } from "../src/server/accountSecurity/accountSecurityService.js";
6
- import { userSettingsResource } from "../src/shared/resources/userSettingsResource.js";
6
+ import { userSettingsContract } from "../src/shared/resources/userSettingsResource.js";
7
7
 
8
8
  test("account security service returns no content result for other sessions", async () => {
9
9
  const calls = [];
@@ -41,7 +41,7 @@ test("unlinking returns the security status in the settings output contract", as
41
41
  ]
42
42
  });
43
43
  const outputOf = (value) => validateOperationSection({
44
- operation: userSettingsResource.operations.oauthUnlink,
44
+ operation: userSettingsContract.operations.oauthUnlink,
45
45
  section: "output",
46
46
  value
47
47
  });
@@ -22,9 +22,9 @@ test("authProfileSyncService.syncIdentityProfile uses shared transaction for pro
22
22
  displayName: payload.displayName
23
23
  };
24
24
  },
25
- async withTransaction(work) {
25
+ async withTransaction(options, work) {
26
26
  calls.push({ step: "withTransaction", trx: transaction });
27
- return work(transaction);
27
+ return work({ ...options, trx: transaction });
28
28
  }
29
29
  },
30
30
  userSettingsRepository: {
@@ -82,8 +82,8 @@ test("authProfileSyncService.syncIdentityProfile skips write path when profile i
82
82
  upsertCalls += 1;
83
83
  return null;
84
84
  },
85
- async withTransaction(work) {
86
- return work({ trxId: "tx-2" });
85
+ async withTransaction(options, work) {
86
+ return work({ ...options, trx: { trxId: "tx-2" } });
87
87
  }
88
88
  },
89
89
  userSettingsRepository: {
@@ -126,8 +126,8 @@ test("authProfileSyncService.findByIdentity normalizes provider identity input",
126
126
  async upsert() {
127
127
  return null;
128
128
  },
129
- async withTransaction(work) {
130
- return work({ trxId: "tx-3" });
129
+ async withTransaction(options, work) {
130
+ return work({ ...options, trx: { trxId: "tx-3" } });
131
131
  }
132
132
  },
133
133
  userSettingsRepository: {
@@ -160,7 +160,11 @@ test("auth profile sync joins the supplied managed transaction and propagates co
160
160
  userProfilesRepository: {
161
161
  async findByIdentity(_identity, options) { calls.push(options.trx); return null; },
162
162
  async upsert(_data, options) { calls.push(options.trx); return profile; },
163
- async withTransaction() { throw new Error("Must join the caller's owner"); }
163
+ // The repository joins the caller's transaction instead of opening one.
164
+ async withTransaction(options, work) {
165
+ if (!options.trx) throw new Error("Must join the caller's owner");
166
+ return work(options);
167
+ }
164
168
  },
165
169
  userSettingsRepository: {
166
170
  async ensureForUserId(_id, options) { calls.push(options.trx); }
@@ -191,9 +195,9 @@ test("an ordinary request's profile check (onlyWhenChanged) reads a matching pro
191
195
  row = { id: row?.id || "8", ...payload };
192
196
  return row;
193
197
  },
194
- async withTransaction(work) {
198
+ async withTransaction(options, work) {
195
199
  calls.push("transaction");
196
- return work({ trxId: "tx" });
200
+ return work({ ...options, trx: { trxId: "tx" } });
197
201
  }
198
202
  },
199
203
  userSettingsRepository: {
@@ -14,6 +14,8 @@ test("users-core exports are explicit and aligned with production/template usage
14
14
  packageDir: PACKAGE_DIR,
15
15
  packageId: "@jskit-ai/users-core",
16
16
  requiredExports: [
17
+ // An application's tests start it with UsersIdentityProvider for users.profiles.
18
+ "./server/UsersExtensionsProvider",
17
19
  "./server/UsersFeature",
18
20
  "./server/UsersIdentityProvider",
19
21
  "./server/usersExtensions",
@@ -1,5 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+ import knexLib from "knex";
4
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
3
5
  import { ActionProvider } from "@jskit-ai/kernel/server/actions";
4
6
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
7
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
@@ -7,26 +9,18 @@ import { createBootstrapRuntime, EventProvider } from "@jskit-ai/kernel/server/r
7
9
  import { UsersExtensionsProvider } from "../src/server/UsersExtensionsProvider.js";
8
10
  import { UsersFeature } from "../src/server/UsersFeature.js";
9
11
  import { UsersIdentityProvider } from "../src/server/UsersIdentityProvider.js";
12
+ import { userProfileTableResource } from "../src/shared/resources/userProfileResource.js";
13
+ import { userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
10
14
 
11
- function createJsonRestApiFixture() {
12
- const resources = {};
13
- return {
14
- resources,
15
- async addResource(scopeName) {
16
- resources[scopeName] = Object.freeze({
17
- query: async () => ({ data: [] }),
18
- post: async () => null,
19
- patch: async () => null
20
- });
21
- }
22
- };
23
- }
24
-
25
- test("UsersFeature assembles account behavior through explicit capabilities", async () => {
15
+ test("UsersFeature assembles account behavior through explicit capabilities", async (t) => {
26
16
  const routes = [];
27
17
  const bootstrap = createBootstrapRuntime();
28
- const jsonRestApi = createJsonRestApiFixture();
18
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
19
+ t.after(() => knex.destroy());
20
+ const resourceRuntime = await createTestResourceRuntime({ knex });
29
21
  let users = null;
22
+ let profiles = null;
23
+ let settings = null;
30
24
  let actionCatalogue = null;
31
25
  let profileProjector = null;
32
26
  const probe = defineProvider({
@@ -34,11 +28,15 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
34
28
  requires: {
35
29
  actions: "runtime.actions",
36
30
  projector: "auth.profile.projector",
31
+ profilesCapability: "users.profiles",
32
+ settingsCapability: "users.settings",
37
33
  usersCapability: "users.core"
38
34
  },
39
- setup({ actions, projector, usersCapability }) {
35
+ setup({ actions, projector, profilesCapability, settingsCapability, usersCapability }) {
40
36
  actionCatalogue = actions;
41
37
  profileProjector = projector;
38
+ profiles = profilesCapability;
39
+ settings = settingsCapability;
42
40
  users = usersCapability;
43
41
  return {};
44
42
  }
@@ -55,7 +53,7 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
55
53
  }
56
54
  }
57
55
  },
58
- "runtime.json-rest-api": jsonRestApi,
56
+ "runtime.resources": resourceRuntime,
59
57
  "runtime.storage": {
60
58
  async getItemRaw() { return null; },
61
59
  async setItemRaw() {},
@@ -68,8 +66,21 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
68
66
 
69
67
  await runtime.start();
70
68
 
71
- assert.deepEqual(Object.keys(jsonRestApi.resources).sort(), ["userProfiles", "userSettings"]);
72
- assert.equal(typeof users.repositories.userProfiles.findByIdentity, "function");
69
+ assert.deepEqual(resourceRuntime.ownedTables(), [
70
+ { name: "userProfiles", tableName: "users", featureId: "users.identity" },
71
+ { name: "userSettings", tableName: "user_settings", featureId: "users.identity" }
72
+ ]);
73
+ assert.equal(typeof profiles.findByIdentity, "function");
74
+ assert.equal(typeof profiles.createWithSettings, "function");
75
+ assert.equal(typeof profiles.countUsers, "function");
76
+ assert.deepEqual(
77
+ ["query", "get", "pageLimits"].map((method) => typeof profiles[method]),
78
+ ["function", "function", "function"],
79
+ "users.profiles serves a CRUD feature's reads"
80
+ );
81
+ assert.equal(Object.hasOwn(profiles, "create"), false, "and no handle writes");
82
+ assert.equal(typeof settings.ensureForUserId, "function");
83
+ assert.equal(Object.hasOwn(users, "repositories"), false);
73
84
  assert.equal(typeof users.services.accountProfile.updateProfile, "function");
74
85
  assert.equal(routes.includes("GET /api/settings"), true);
75
86
  assert.equal(routes.includes("POST /api/settings/security/change-password"), true);
@@ -78,3 +89,35 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
78
89
  assert.equal(typeof profileProjector.syncIdentityProfile, "function");
79
90
  assert.equal(typeof profileProjector.findByIdentity, "function");
80
91
  });
92
+
93
+ test("every search entry of the users tables filters, and id takes one id or a list", async (t) => {
94
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
95
+ t.after(() => knex.destroy());
96
+ const resourceRuntime = await createTestResourceRuntime({ knex, createTables: true });
97
+ const { userProfiles, userSettings } = await resourceRuntime.own("test.users", [userProfileTableResource, userSettingsTableResource]);
98
+ const options = { context: {} };
99
+ const people = [["ada", "Ada Lovelace"], ["grace", "Grace Hopper"], ["alan", "Alan Turing"]];
100
+ const ids = [];
101
+ for (const [username, displayName] of people) {
102
+ const { id } = await userProfiles.create({
103
+ authProvider: "local",
104
+ authProviderUserSid: username,
105
+ email: `${username}@example.com`,
106
+ username,
107
+ displayName
108
+ }, options);
109
+ ids.push(id);
110
+ }
111
+ const usernames = async (filters) => (await userProfiles.queryAll({ filters }, options)).map(({ username }) => username).sort();
112
+
113
+ assert.deepEqual(await usernames({ id: ids[1] }), ["grace"]);
114
+ assert.deepEqual(await usernames({ id: [ids[0], ids[2]] }), ["ada", "alan"]);
115
+ assert.deepEqual(await usernames({ id: [] }), []);
116
+ assert.deepEqual(await usernames({ usernames: ["ada", "grace"] }), ["ada", "grace"]);
117
+ assert.deepEqual(await usernames({ emails: ["alan@example.com"] }), ["alan"]);
118
+ assert.deepEqual(await usernames({ createdSince: "2000-01-01T00:00:00.000Z" }), ["ada", "alan", "grace"]);
119
+ assert.deepEqual(await usernames({ q: "lovelace" }), ["ada"]);
120
+ assert.deepEqual(await usernames({ authProvider: "local", authProviderUserSid: "grace" }), ["grace"]);
121
+ // The settings table is keyed by its user's id, and its id filter takes a list as well.
122
+ assert.deepEqual(await userSettings.queryAll({ filters: { id: [ids[0], ids[1]] } }, options), []);
123
+ });
@@ -6,7 +6,7 @@ import en from "../locales/en.json" with { type: "json" };
6
6
  import { createService as createAccountProfileService } from "../src/server/accountProfile/accountProfileService.js";
7
7
  import { createService as createAccountSecurityService } from "../src/server/accountSecurity/accountSecurityService.js";
8
8
  import { createRepository as createUserSettingsRepository } from "../src/server/common/repositories/userSettingsRepository.js";
9
- import { userSettingsResource } from "../src/shared/resources/userSettingsResource.js";
9
+ import { userSettingsContract, userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
10
10
  import { normalizeLocaleCode } from "../src/shared/settings.js";
11
11
 
12
12
  // A code's catalog English, rendered with its params, is exactly the English sent.
@@ -71,7 +71,7 @@ test("saved locales are canonical BCP 47 tags", () => {
71
71
 
72
72
  test("preference input keeps the locale's case and storage canonicalizes it", async () => {
73
73
  const parsed = validateOperationSection({
74
- operation: userSettingsResource.operations.preferencesUpdate,
74
+ operation: userSettingsContract.operations.preferencesUpdate,
75
75
  section: "body",
76
76
  value: {
77
77
  theme: "system",
@@ -85,18 +85,14 @@ test("preference input keeps the locale's case and storage canonicalizes it", as
85
85
  });
86
86
  assert.equal(parsed.ok, true);
87
87
  assert.equal(parsed.value.locale, "en-US");
88
- assert.equal(userSettingsResource.schema.locale.setter("it-it"), "it-IT");
88
+ assert.equal(userSettingsTableResource.schema.locale.setter("it-it"), "it-IT");
89
89
  });
90
90
 
91
91
  test("user settings reads canonicalize locales saved lowercased", async () => {
92
92
  const repository = createUserSettingsRepository({
93
- api: {
94
- resources: {
95
- userSettings: {
96
- async query() {
97
- return { data: [{ id: "7", locale: "en-us", theme: "dark" }] };
98
- }
99
- }
93
+ userSettings: {
94
+ async query() {
95
+ return { records: [{ id: "7", locale: "en-us", theme: "dark" }], page: { size: 1, hasMore: false, next: null } };
100
96
  }
101
97
  }
102
98
  });
@@ -0,0 +1,5 @@
1
+ import { listByIdsCases } from "./support/listByIdsCases.js";
2
+ import { usersDatabase } from "./support/usersDatabases.js";
3
+
4
+ // users.profiles.listByIds on MariaDB/MySQL.
5
+ listByIdsCases(usersDatabase("users_ids"));
@@ -0,0 +1,6 @@
1
+ import { listByIdsCases } from "./support/listByIdsCases.js";
2
+ import { POSTGRES_ELSEWHERE, postgresUsersDatabase } from "./support/usersDatabases.js";
3
+
4
+ // users.profiles.listByIds on PostgreSQL: run with TEST_DB_NAME (and the usual DB_HOST, DB_PORT, DB_USER and
5
+ // DB_PASSWORD) naming a PostgreSQL database, and DB_CLIENT unset or pg.
6
+ listByIdsCases(postgresUsersDatabase("users_ids"), { skip: POSTGRES_ELSEWHERE });