@fabriktor/fx 0.0.188 → 0.0.189

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.
@@ -4,6 +4,7 @@ import { errRequired, errResolveFailed, errValidation, FXErrKind, isFXErr, } fro
4
4
  import { requiredOperationID, normalizeIDs } from "../core/id.js";
5
5
  import { normalizeSearchPage, normalizeSearchPerPage, normalizeSearchQuery, runSearch, } from "../core/search.js";
6
6
  import { isFabriktorUser } from "../users/users.js";
7
+ import { userDisplayName } from "../users/profile.js";
7
8
  import { ChatSendQueue } from "./send-queue.js";
8
9
  const closeCodeNormal = 1000;
9
10
  const wsRefreshMilliseconds = 40 * 60 * 1000;
@@ -493,7 +494,7 @@ export class ChatFX {
493
494
  }
494
495
  return {
495
496
  id: user.id,
496
- full_name: user.full_name,
497
+ full_name: userDisplayName(user),
497
498
  username: user.username,
498
499
  account_identity: user.account_identity,
499
500
  picture_id: user.picture_id,
@@ -1,4 +1,4 @@
1
- import type { RPFeedLinkPreview } from "@fabriktor/schema";
1
+ import { type RPFeedLinkPreview } from "@fabriktor/schema";
2
2
  export declare const linkPreviewConcurrency = 3;
3
3
  export declare const linkPreviewDelayMs = 400;
4
4
  export declare const linkPreviewCacheSize = 64;
@@ -4,13 +4,14 @@
4
4
  // not use this file except in compliance with the License. You may obtain
5
5
  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
6
  import { MultiCreatePool } from "./multi-create.js";
7
+ import { HTTPScheme, HTTPSScheme, } from "@fabriktor/schema";
7
8
  export const linkPreviewConcurrency = 3;
8
9
  export const linkPreviewDelayMs = 400;
9
10
  export const linkPreviewCacheSize = 64;
10
11
  export function publicLinkURL(value) {
11
12
  try {
12
13
  const url = new URL(value);
13
- return ["https:", "http:"].includes(url.protocol) &&
14
+ return [`${HTTPSScheme}:`, `${HTTPScheme}:`].includes(url.protocol) &&
14
15
  !url.username &&
15
16
  !url.password
16
17
  ? url.href
@@ -66,5 +66,6 @@ export * from "./timesheets/workspace.js";
66
66
  export * from "./users/email.js";
67
67
  export * from "./users/phone.js";
68
68
  export * from "./users/picture.js";
69
+ export * from "./users/profile.js";
69
70
  export * from "./users/username.js";
70
71
  export * from "./users/users.js";
package/dist/src/index.js CHANGED
@@ -66,5 +66,6 @@ export * from "./timesheets/workspace.js";
66
66
  export * from "./users/email.js";
67
67
  export * from "./users/phone.js";
68
68
  export * from "./users/picture.js";
69
+ export * from "./users/profile.js";
69
70
  export * from "./users/username.js";
70
71
  export * from "./users/users.js";
@@ -38,6 +38,11 @@ export type DeleteOwnedStorageObjectOptions = {
38
38
  uploader_id: string;
39
39
  signal?: AbortSignal;
40
40
  };
41
+ export type ResolveUserImageOptions = {
42
+ id: string;
43
+ owner_id: string;
44
+ signal?: AbortSignal;
45
+ };
41
46
  export type UploadUserObjectsOptions = RequestOptions & {
42
47
  user_id: string;
43
48
  uploader_id?: string;
@@ -73,6 +78,7 @@ export type StoragePersonalBoxUploadResult = {
73
78
  };
74
79
  export type UploadChatObjectsResult = StoragePersonalBoxUploadResult;
75
80
  export interface StorageFXOperator {
81
+ resolveUserImage(opts: ResolveUserImageOptions): Promise<StorageObject>;
76
82
  deleteOwnedObject(opts: DeleteOwnedStorageObjectOptions): Promise<void>;
77
83
  uploadObjects(opts: UploadObjectsOptions): Promise<StorageUploadResult>;
78
84
  uploadObjectsWithPersonalBox(opts: UploadObjectsWithPersonalBoxOptions): Promise<StoragePersonalBoxUploadResult>;
@@ -86,6 +92,7 @@ export declare class StorageFX implements StorageFXOperator {
86
92
  uploadObjects(opts: UploadObjectsOptions): Promise<StorageUploadResult>;
87
93
  uploadObjectsWithPersonalBox(opts: UploadObjectsWithPersonalBoxOptions): Promise<StoragePersonalBoxUploadResult>;
88
94
  downloadObjects(opts: DownloadObjectsOptions): Promise<OperationResultOf<StorageObject[]>>;
95
+ resolveUserImage(opts: ResolveUserImageOptions): Promise<StorageObject>;
89
96
  deleteOwnedObject(opts: DeleteOwnedStorageObjectOptions): Promise<void>;
90
97
  uploadUserObjects(opts: UploadUserObjectsOptions): Promise<StorageUploadResult>;
91
98
  uploadChatObjects(opts: UploadChatObjectsOptions): Promise<UploadChatObjectsResult>;
@@ -1,6 +1,8 @@
1
- import { ColStorageChat, ColStorageUsers, } from "@fabriktor/schema";
1
+ import { ColStorageChat, ColStorageUsers, MimePrefixImage, } from "@fabriktor/schema";
2
2
  import { isClientErr } from "@fabriktor/client";
3
3
  import { errRequired, errValidation } from "../core/err.js";
4
+ import { resolvedID } from "../core/id.js";
5
+ import { runPreActionCheck } from "../core/pre-action.js";
4
6
  import { notifyObserver } from "../core/events.js";
5
7
  export const storageMaxFiles = 20;
6
8
  export const storageMaxBytes = 1024 * 1024 * 1024;
@@ -108,6 +110,27 @@ export class StorageFX {
108
110
  mime_prefix: mime_prefix?.trim() ?? mimePrefixAll,
109
111
  });
110
112
  }
113
+ async resolveUserImage(opts) {
114
+ await runPreActionCheck({
115
+ reason: "profile-picture-unavailable",
116
+ allowed: () => !!resolvedID(opts.id) && !!resolvedID(opts.owner_id),
117
+ });
118
+ const out = await this.downloadObjects({
119
+ col: ColStorageUsers,
120
+ owner_id: opts.owner_id,
121
+ mime_prefix: MimePrefixImage,
122
+ signal: opts.signal,
123
+ });
124
+ opts.signal?.throwIfAborted();
125
+ const object = out.value?.find((value) => value.id === opts.id &&
126
+ value.owner_id === opts.owner_id &&
127
+ value.mime_prefix === MimePrefixImage);
128
+ await runPreActionCheck({
129
+ reason: "profile-picture-unavailable",
130
+ allowed: () => !!object,
131
+ });
132
+ return object;
133
+ }
111
134
  async deleteOwnedObject(opts) {
112
135
  opts.signal?.throwIfAborted();
113
136
  const stored = await this.downloadObjects(opts);
@@ -1,8 +1,7 @@
1
1
  import { type InUser, type User } from "@fabriktor/schema";
2
- export type UserAvatarProfile = Pick<User, "id" | "full_name" | "username" | "picture_id" | "picture_preview" | "picture_url">;
2
+ export type UserAvatarProfile = Pick<User, "id" | "full_name" | "username" | "picture_id" | "picture_preview" | "picture_url"> & Partial<Pick<User, "account_identity" | "company_name" | "show_as_company">>;
3
3
  export type UserPictureInput = Pick<InUser, "picture_id" | "picture_preview">;
4
- export declare const userPictureMaxBytes: number;
5
- export declare const userPictureMaxSize = 128;
6
4
  export declare function hasUserPicture(user: Pick<User, "picture_id"> | null | undefined): boolean;
7
5
  export declare function userPicturePreview(user: Pick<User, "picture_id" | "picture_preview"> | null | undefined): string;
8
6
  export declare function validUserPicturePreview(value: string): boolean;
7
+ export declare function validImagePreview(value: string, maxBytes: number): boolean;
@@ -1,7 +1,5 @@
1
- import { MimeJPEG, MimePNG } from "@fabriktor/schema";
1
+ import { MimeJPEG, MimePNG, UserPictureMaxBytes, UserPreviewMinBytes, } from "@fabriktor/schema";
2
2
  import { resolvedID } from "../core/id.js";
3
- export const userPictureMaxBytes = 16 * 1024;
4
- export const userPictureMaxSize = 128;
5
3
  const previewTypes = [MimeJPEG, MimePNG];
6
4
  export function hasUserPicture(user) {
7
5
  return !!resolvedID(user?.picture_id);
@@ -14,16 +12,19 @@ export function userPicturePreview(user) {
14
12
  return validUserPicturePreview(value) ? value : "";
15
13
  }
16
14
  export function validUserPicturePreview(value) {
15
+ return validImagePreview(value, UserPictureMaxBytes);
16
+ }
17
+ export function validImagePreview(value, maxBytes) {
17
18
  const comma = value.indexOf(",");
18
19
  if (comma < 0 ||
19
20
  !previewTypes.some((mime) => value.slice(0, comma) === `data:${mime};base64`))
20
21
  return false;
21
22
  const data = value.slice(comma + 1);
22
23
  if (!data ||
23
- data.length > Math.ceil(userPictureMaxBytes / 3) * 4 ||
24
+ data.length > Math.ceil(maxBytes / 3) * 4 ||
24
25
  !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))
25
26
  return false;
26
27
  const bytes = (data.length / 4) * 3 -
27
28
  (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
28
- return bytes > 0 && bytes <= userPictureMaxBytes;
29
+ return bytes >= UserPreviewMinBytes && bytes <= maxBytes;
29
30
  }
@@ -0,0 +1,22 @@
1
+ import { type InUser, type User } from "@fabriktor/schema";
2
+ export type UserCardInput = Pick<InUser, "bio" | "urls" | "show_as_company" | "banner_id" | "banner_preview">;
3
+ export type UserCardIdentity = Pick<User, "id" | "username" | "full_name" | "company_name"> & Partial<Pick<User, "show_as_company">>;
4
+ export type BannerFrame = {
5
+ x: number;
6
+ y: number;
7
+ zoom: number;
8
+ };
9
+ export declare const defaultBannerFrame: BannerFrame;
10
+ export declare const bannerMaxZoom = 4;
11
+ export declare function userDisplayName(user: UserCardIdentity): string;
12
+ export declare function userCardInput(user?: Partial<User> | null): UserCardInput;
13
+ export declare function normalizeUserCardInput(value: UserCardInput): UserCardInput;
14
+ export declare function validateUserCardInput(input: UserCardInput): void;
15
+ export declare function userBannerPreview(user: Partial<User> | null | undefined): string;
16
+ export declare function bannerCrop(width: number, height: number, frame: BannerFrame): {
17
+ x: number;
18
+ y: number;
19
+ width: number;
20
+ height: number;
21
+ };
22
+ export declare function moveBannerFrame(width: number, height: number, frame: BannerFrame, dx: number, dy: number, viewportWidth: number): BannerFrame;
@@ -0,0 +1,84 @@
1
+ import { ZeroID, UserBioMaxLength, UserURLsMaxCount, UserURLMaxLength, UserBannerMaxBytes, UserBannerWidth, UserBannerHeight, } from "@fabriktor/schema";
2
+ import { errValidation } from "../core/err.js";
3
+ import { publicLinkURL } from "../core/links.js";
4
+ import { resolvedID } from "../core/id.js";
5
+ import { validImagePreview } from "./picture.js";
6
+ const msgBioLength = "Profile bio is too long.";
7
+ const msgPublicLinks = "At most two HTTP or HTTPS links are allowed.";
8
+ const msgBannerRequired = "A valid banner preview is required.";
9
+ export const defaultBannerFrame = { x: 0.5, y: 0.5, zoom: 1 };
10
+ export const bannerMaxZoom = 4;
11
+ export function userDisplayName(user) {
12
+ return ((user.show_as_company
13
+ ? user.company_name?.trim()
14
+ : user.full_name?.trim()) ||
15
+ user.full_name?.trim() ||
16
+ user.company_name?.trim() ||
17
+ user.username?.trim() ||
18
+ user.id);
19
+ }
20
+ export function userCardInput(user) {
21
+ return {
22
+ bio: user?.bio ?? "",
23
+ urls: [...(user?.urls ?? [])],
24
+ show_as_company: user?.show_as_company ?? false,
25
+ banner_id: resolvedID(user?.banner_id) ?? ZeroID,
26
+ banner_preview: user?.banner_preview ?? "",
27
+ };
28
+ }
29
+ export function normalizeUserCardInput(value) {
30
+ const input = userCardInput(value);
31
+ input.bio = input.bio.trim();
32
+ input.urls = input.urls.map((url) => url.trim()).filter(Boolean);
33
+ if (!resolvedID(input.banner_id))
34
+ input.banner_preview = "";
35
+ return input;
36
+ }
37
+ export function validateUserCardInput(input) {
38
+ if ([...input.bio].length > UserBioMaxLength)
39
+ throw errValidation({ field: "bio", msg: msgBioLength });
40
+ if (input.urls.length > UserURLsMaxCount ||
41
+ input.urls.some((url) => new TextEncoder().encode(url).length > UserURLMaxLength ||
42
+ !publicLinkURL(url)))
43
+ throw errValidation({
44
+ field: "urls",
45
+ msg: msgPublicLinks,
46
+ });
47
+ if (resolvedID(input.banner_id) &&
48
+ !validImagePreview(input.banner_preview, UserBannerMaxBytes))
49
+ throw errValidation({
50
+ field: "banner_preview",
51
+ msg: msgBannerRequired,
52
+ });
53
+ }
54
+ export function userBannerPreview(user) {
55
+ const preview = user?.banner_preview ?? "";
56
+ return resolvedID(user?.banner_id) &&
57
+ validImagePreview(preview, UserBannerMaxBytes)
58
+ ? preview
59
+ : "";
60
+ }
61
+ // Position is relative to available travel, so the same crop works at every viewport size.
62
+ export function bannerCrop(width, height, frame) {
63
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, Number.isFinite(value) ? value : min));
64
+ const zoom = clamp(frame.zoom, 1, bannerMaxZoom);
65
+ const ratio = UserBannerWidth / UserBannerHeight;
66
+ const w = Math.min(width, height * ratio) / zoom;
67
+ const h = w / ratio;
68
+ return {
69
+ x: (width - w) * clamp(frame.x, 0, 1),
70
+ y: (height - h) * clamp(frame.y, 0, 1),
71
+ width: w,
72
+ height: h,
73
+ };
74
+ }
75
+ export function moveBannerFrame(width, height, frame, dx, dy, viewportWidth) {
76
+ const crop = bannerCrop(width, height, frame);
77
+ const scale = crop.width / Math.max(1, viewportWidth);
78
+ const clamp = (value) => Math.min(1, Math.max(0, value));
79
+ return {
80
+ ...frame,
81
+ x: clamp(frame.x - (dx * scale) / Math.max(1, width - crop.width)),
82
+ y: clamp(frame.y - (dy * scale) / Math.max(1, height - crop.height)),
83
+ };
84
+ }
@@ -2,6 +2,7 @@ import { type GetByUIDOptions, type OperationResultOf, type TmpPhonesOperator, t
2
2
  import { UserTypeEmployee, UserTypeEmployer, type InAddress, type InUser, type User } from "@fabriktor/schema";
3
3
  import { type RunSearchOptions, type SearchPage } from "../core/search.js";
4
4
  import { type UserPictureInput } from "./picture.js";
5
+ import { type UserCardInput } from "./profile.js";
5
6
  export type ResolveUsernameOptions = Parameters<UsersOperator["resolveUsername"]>[0];
6
7
  export type VerifyUsernameOptions = Parameters<TmpUsernamesOperator["verify"]>[0];
7
8
  export type GenerateUsernamesOptions = VerifyUsernameOptions;
@@ -11,7 +12,7 @@ export type UsersByIDsOptions = {
11
12
  ids: readonly string[];
12
13
  signal?: AbortSignal;
13
14
  };
14
- export type ExternalUserInput = Omit<InUser, "account_identity" | "active_mode" | "privacy">;
15
+ export type ExternalUserInput = Omit<InUser, "account_identity" | "active_mode" | "privacy" | keyof UserCardInput>;
15
16
  export type CreateExternalUserOptions = {
16
17
  in: ExternalUserInput;
17
18
  };
@@ -31,6 +32,12 @@ export type UpdateUserProfileOptions = GetByUIDOptions & {
31
32
  id: string;
32
33
  in: UserProfileInput;
33
34
  };
35
+ export type PublicUserProfileOptions = Parameters<UsersOperator["publicProfile"]>[0];
36
+ export type UpdateUserCardOptions = GetByUIDOptions & {
37
+ id: string;
38
+ in: UserCardInput;
39
+ signal?: AbortSignal;
40
+ };
34
41
  export type UpdateUserPictureOptions = GetByUIDOptions & {
35
42
  id: string;
36
43
  in: UserPictureInput;
@@ -65,6 +72,8 @@ export interface UsersFXOperator {
65
72
  createExternalUser(opts: CreateExternalUserOptions): Promise<User>;
66
73
  updateExternalUser(opts: UpdateExternalUserOptions): Promise<User>;
67
74
  searchExternalUsers(opts: SearchExternalUsersOptions): Promise<SearchExternalUsersPage>;
75
+ publicProfile(opts: PublicUserProfileOptions): Promise<User>;
76
+ updateUserCard(opts: UpdateUserCardOptions): Promise<User>;
68
77
  updateUserProfile(opts: UpdateUserProfileOptions): Promise<User>;
69
78
  updateUserPicture(opts: UpdateUserPictureOptions): Promise<User>;
70
79
  updateUserPhone(opts: UpdateUserPhoneOptions): Promise<User>;
@@ -86,6 +95,8 @@ export declare class UsersFX implements UsersFXOperator {
86
95
  createExternalUser(opts: CreateExternalUserOptions): Promise<User>;
87
96
  updateExternalUser(opts: UpdateExternalUserOptions): Promise<User>;
88
97
  searchExternalUsers(opts: SearchExternalUsersOptions): Promise<SearchExternalUsersPage>;
98
+ publicProfile(opts: PublicUserProfileOptions): Promise<User>;
99
+ updateUserCard(opts: UpdateUserCardOptions): Promise<User>;
89
100
  updateUserProfile(opts: UpdateUserProfileOptions): Promise<User>;
90
101
  updateUserPicture(opts: UpdateUserPictureOptions): Promise<User>;
91
102
  updateUserPhone(opts: UpdateUserPhoneOptions): Promise<User>;
@@ -1,5 +1,5 @@
1
1
  import { isNotFoundClientErr, } from "@fabriktor/client";
2
- import { UserTypeClient, UserTypeEmployee, UserTypeEmployer, UserTypeExternal, } from "@fabriktor/schema";
2
+ import { UserTypeClient, UserTypeEmployee, UserTypeEmployer, UserTypeExternal, ZeroID, } from "@fabriktor/schema";
3
3
  import { errRequired, errResolveFailed, errValidation, } from "../core/err.js";
4
4
  import { normalizeIDs, requiredOperationID, resolvedID } from "../core/id.js";
5
5
  import { runSearch, } from "../core/search.js";
@@ -7,6 +7,10 @@ import { normalizePhone, normalizePhoneCode, validatePhone, validatePhoneCode, }
7
7
  import { normalizeEmail, isValidEmail } from "./email.js";
8
8
  import { validUserPicturePreview } from "./picture.js";
9
9
  import { normalizeUsername, validateUsernameFormat } from "./username.js";
10
+ import { userCardInput, normalizeUserCardInput, validateUserCardInput, } from "./profile.js";
11
+ const msgProfileRequired = "A valid account is required to update the public profile.";
12
+ const msgPublicUserRequired = "A valid user is required.";
13
+ const msgPublicUserMissing = "Public profile could not be resolved.";
10
14
  const msgPictureRequired = "A valid account and profile preview are required.";
11
15
  const msgUnableToResolveUsername = "Unable to resolve username.";
12
16
  const msgPhoneRequired = "Phone number is required.";
@@ -94,6 +98,7 @@ export class UsersFX {
94
98
  const out = await this.users.insertOneUser({
95
99
  in: {
96
100
  ...input,
101
+ ...userCardInput(),
97
102
  account_identity: UserTypeExternal,
98
103
  active_mode: UserTypeExternal,
99
104
  privacy: {
@@ -147,6 +152,32 @@ export class UsersFX {
147
152
  }),
148
153
  });
149
154
  }
155
+ async publicProfile(opts) {
156
+ if (!resolvedID(opts.id))
157
+ throw errValidation({ field: "id", msg: msgPublicUserRequired });
158
+ const out = await this.users.publicProfile(opts);
159
+ if (!out.value || out.value.id !== opts.id)
160
+ throw errResolveFailed({
161
+ resource: resourceUser,
162
+ msg: msgPublicUserMissing,
163
+ });
164
+ return out.value;
165
+ }
166
+ async updateUserCard(opts) {
167
+ const input = normalizeUserCardInput(opts.in);
168
+ validateUserCardInput(input);
169
+ if (!resolvedID(opts.id) || !opts.uid.trim())
170
+ throw errValidation({ msg: msgProfileRequired });
171
+ await this.users.replaceOneUser({
172
+ id: opts.id,
173
+ in: input,
174
+ signal: opts.signal,
175
+ });
176
+ opts.signal?.throwIfAborted();
177
+ const user = await this.updatedUser(opts.uid);
178
+ opts.signal?.throwIfAborted();
179
+ return user;
180
+ }
150
181
  async updateUserProfile(opts) {
151
182
  const input = normalizeUserProfileInput(opts.in);
152
183
  validateUserProfileInput(input);
@@ -159,16 +190,16 @@ export class UsersFX {
159
190
  async updateUserPicture(opts) {
160
191
  opts.signal?.throwIfAborted();
161
192
  const id = resolvedID(opts.id);
162
- const picture_id = resolvedID(opts.in.picture_id) ?? "";
163
- const picture_preview = picture_id ? opts.in.picture_preview : "";
193
+ const pictureID = resolvedID(opts.in.picture_id);
194
+ const picturePreview = pictureID ? opts.in.picture_preview : "";
164
195
  if (!id ||
165
196
  !opts.uid.trim() ||
166
- (picture_id && !validUserPicturePreview(picture_preview))) {
197
+ (pictureID && !validUserPicturePreview(picturePreview))) {
167
198
  throw errValidation({ msg: msgPictureRequired });
168
199
  }
169
200
  await this.users.replaceOneUser({
170
201
  id,
171
- in: { picture_id, picture_preview },
202
+ in: { picture_id: pictureID ?? ZeroID, picture_preview: picturePreview },
172
203
  signal: opts.signal,
173
204
  });
174
205
  opts.signal?.throwIfAborted();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.188",
3
+ "version": "0.0.189",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,9 +17,9 @@
17
17
  "typescript": "^6.0.3"
18
18
  },
19
19
  "dependencies": {
20
- "@fabriktor/client": "0.0.115",
20
+ "@fabriktor/client": "0.0.116",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.86",
22
+ "@fabriktor/schema": "0.0.87",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }