@fabriktor/fx 0.0.187 → 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.
@@ -109,6 +109,9 @@ export type GlobalChatRoomsSession = {
109
109
  export interface ChatFXOperator {
110
110
  newSendQueue(opts: Omit<ChatSendQueueOptions, "chat">): ChatSendQueue;
111
111
  createChat(opts: CreateChatOptions): Promise<Chat>;
112
+ chatMessage(opts: Pick<Chat, "id" | "chat_room_id"> & {
113
+ signal?: AbortSignal;
114
+ }): Promise<Chat>;
112
115
  ensureChatRoom(opts: EnsureChatRoomOptions): Promise<string>;
113
116
  markChatObjectsUploaded(opts: MarkChatObjectsUploadedOptions): Promise<Chat>;
114
117
  clearChatObjects(opts: ClearChatObjectsOptions): Promise<Chat>;
@@ -130,6 +133,9 @@ export declare class ChatFX implements ChatFXOperator {
130
133
  private users;
131
134
  constructor(opts: ChatFXOptions);
132
135
  newSendQueue(opts: Omit<ChatSendQueueOptions, "chat">): ChatSendQueue;
136
+ chatMessage(opts: Pick<Chat, "id" | "chat_room_id"> & {
137
+ signal?: AbortSignal;
138
+ }): Promise<Chat>;
133
139
  createChat(opts: CreateChatOptions): Promise<Chat>;
134
140
  ensureChatRoom(opts: EnsureChatRoomOptions): Promise<string>;
135
141
  markChatObjectsUploaded(opts: MarkChatObjectsUploadedOptions): Promise<Chat>;
@@ -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;
@@ -37,8 +38,24 @@ export class ChatFX {
37
38
  newSendQueue(opts) {
38
39
  return new ChatSendQueue({ ...opts, chat: this.chat });
39
40
  }
41
+ async chatMessage(opts) {
42
+ const out = await this.chat.queryChats({
43
+ query: queryParams({
44
+ id: opts.id,
45
+ chat_room_id: opts.chat_room_id,
46
+ }),
47
+ signal: opts.signal,
48
+ });
49
+ const chat = out.value?.find((entry) => entry.id === opts.id && entry.chat_room_id === opts.chat_room_id);
50
+ if (!chat)
51
+ throw errResolveFailed({ resource: resourceChat, msg: msgChatMissing });
52
+ return chat;
53
+ }
40
54
  async createChat(opts) {
41
- const out = await this.chat.insertOneChat(opts);
55
+ const out = await this.chat.insertOneChat({
56
+ ...opts,
57
+ in: { ...opts.in, is_talkie: opts.in.is_talkie ?? false },
58
+ });
42
59
  const id = requiredOperationID(out, msgCreatedChatIDMissing);
43
60
  return await this.findChat(id);
44
61
  }
@@ -477,7 +494,7 @@ export class ChatFX {
477
494
  }
478
495
  return {
479
496
  id: user.id,
480
- full_name: user.full_name,
497
+ full_name: userDisplayName(user),
481
498
  username: user.username,
482
499
  account_identity: user.account_identity,
483
500
  picture_id: user.picture_id,
@@ -4,6 +4,7 @@ export declare function newChatInput(opts: {
4
4
  text: string;
5
5
  quoted_message_id?: string;
6
6
  has_objects?: boolean;
7
+ is_talkie?: boolean;
7
8
  }): InChat;
8
9
  export declare function newOptimisticChat(opts: {
9
10
  owner_id: string;
@@ -9,6 +9,7 @@ export function newChatInput(opts) {
9
9
  mentions: [],
10
10
  has_objects: opts.has_objects ?? false,
11
11
  objects_uploaded: false,
12
+ is_talkie: opts.is_talkie ?? false,
12
13
  };
13
14
  }
14
15
  export function newOptimisticChat(opts) {
@@ -30,7 +31,8 @@ export function matchesOptimisticChat(chat, optimistic) {
30
31
  chat.chat_room_id === optimistic.chat_room_id &&
31
32
  chat.text === optimistic.text &&
32
33
  chat.quoted_message_id === optimistic.quoted_message_id &&
33
- chat.has_objects === optimistic.has_objects);
34
+ chat.has_objects === optimistic.has_objects &&
35
+ !!chat.is_talkie === !!optimistic.is_talkie);
34
36
  }
35
37
  /** Reconcile only the local outgoing bubbles. Server timestamps/IDs stay authoritative. */
36
38
  export function projectQueuedChats(chats, snapshot, ownerID, roomID) {
@@ -369,7 +369,10 @@ export class ChatSendQueue {
369
369
  requestSignal.throwIfAborted();
370
370
  requestStarted = true;
371
371
  const out = await this.opts.chat.insertOneChat({
372
- in: current.input,
372
+ in: {
373
+ ...current.input,
374
+ is_talkie: current.input.is_talkie ?? false,
375
+ },
373
376
  signal: requestSignal,
374
377
  idempotency_key: current.id,
375
378
  });
@@ -536,7 +539,8 @@ export class ChatSendQueue {
536
539
  }
537
540
  const stored = (await this.opts.store.list(owner)).find((value) => value.id === entry.id);
538
541
  if (!stored?.chat ||
539
- (stored.status !== ChatSendStatus.Queued && !chatSendNeedsRetry(stored))) {
542
+ (stored.status !== ChatSendStatus.Queued &&
543
+ !chatSendNeedsRetry(stored))) {
540
544
  return;
541
545
  }
542
546
  try {
@@ -0,0 +1,59 @@
1
+ import { type Notification } from "@fabriktor/schema";
2
+ import type { ChatFXOperator } from "./chat.js";
3
+ import type { ChatSendQueue } from "./send-queue.js";
4
+ import type { StorageFXOperator } from "../storage/storage.js";
5
+ export type Talkie = {
6
+ notification_id: string;
7
+ chat_id: string;
8
+ chat_room_id: string;
9
+ sender_id: string;
10
+ sender_name: string;
11
+ };
12
+ export type TalkieReply = Talkie & {
13
+ owner_id: string;
14
+ label: string;
15
+ members: number;
16
+ };
17
+ export declare function notificationTalkie(item: Notification): Talkie | undefined;
18
+ export type TalkiePlayer = {
19
+ load: (url: string) => void;
20
+ play: () => Promise<void>;
21
+ pause: () => void;
22
+ reset: () => void;
23
+ };
24
+ export type TalkieState = {
25
+ playing_id: string;
26
+ loading_id: string;
27
+ selecting_id: string;
28
+ reply?: TalkieReply;
29
+ };
30
+ export type TalkieSessionOptions = {
31
+ chat: Pick<ChatFXOperator, "chatMessage" | "chatRooms" | "chatRoomParticipants">;
32
+ storage: Pick<StorageFXOperator, "downloadObjects">;
33
+ queue: Pick<ChatSendQueue, "enqueue">;
34
+ player: TalkiePlayer;
35
+ mark_read: (id: string) => void;
36
+ on_change: (state: TalkieState) => void;
37
+ };
38
+ export declare class TalkieSession {
39
+ private readonly opts;
40
+ private owner;
41
+ private identity;
42
+ private playback;
43
+ private selection;
44
+ private loaded;
45
+ private value;
46
+ constructor(opts: TalkieSessionOptions);
47
+ get state(): TalkieState;
48
+ setOwner(owner_id: string, identity: string): void;
49
+ play(item: Notification): Promise<void>;
50
+ select(item: Notification): Promise<void>;
51
+ reply(file: File, target: TalkieReply): string;
52
+ clearReply(): void;
53
+ stop(): void;
54
+ ended(): void;
55
+ failed(): void;
56
+ clear(): void;
57
+ private resolve;
58
+ private patch;
59
+ }
@@ -0,0 +1,205 @@
1
+ import { ColStorageChat, MimePrefixAudio, NotifKChatChatsTalkieReceived, NotifChatIDKey, NotifChatRoomIDKey, NotifSenderIDKey, NotifSenderNameKey, } from "@fabriktor/schema";
2
+ import { newChatInput } from "./optimistic.js";
3
+ import { notifyObserver } from "../core/events.js";
4
+ import { resolvedID } from "../core/id.js";
5
+ import { errResolveFailed } from "../core/err.js";
6
+ export function notificationTalkie(item) {
7
+ if (item.notif_k !== NotifKChatChatsTalkieReceived)
8
+ return;
9
+ const data = item.custom_data;
10
+ const chat_id = resolvedID(data[NotifChatIDKey]);
11
+ const chat_room_id = resolvedID(data[NotifChatRoomIDKey]);
12
+ const sender_id = resolvedID(data[NotifSenderIDKey]);
13
+ if (!chat_id || !chat_room_id || !sender_id)
14
+ return;
15
+ return {
16
+ notification_id: item.id,
17
+ chat_id,
18
+ chat_room_id,
19
+ sender_id,
20
+ sender_name: data[NotifSenderNameKey] ?? "",
21
+ };
22
+ }
23
+ // Notification history supplies the entries. Resolve media only on user intent.
24
+ export class TalkieSession {
25
+ opts;
26
+ owner = "";
27
+ identity = "";
28
+ playback = new AbortController();
29
+ selection = 0;
30
+ loaded = "";
31
+ value = {
32
+ playing_id: "",
33
+ loading_id: "",
34
+ selecting_id: "",
35
+ };
36
+ constructor(opts) {
37
+ this.opts = opts;
38
+ }
39
+ get state() {
40
+ return this.value;
41
+ }
42
+ setOwner(owner_id, identity) {
43
+ if (this.identity === identity && this.owner === owner_id)
44
+ return;
45
+ this.clear();
46
+ this.owner = owner_id;
47
+ this.identity = identity;
48
+ }
49
+ async play(item) {
50
+ const talkie = this.resolve(item);
51
+ if (this.value.playing_id === item.id ||
52
+ this.value.loading_id === item.id) {
53
+ this.stop();
54
+ return;
55
+ }
56
+ this.stop();
57
+ const abort = this.playback;
58
+ this.patch({ loading_id: item.id });
59
+ try {
60
+ if (this.loaded !== item.id) {
61
+ const chat = await this.opts.chat.chatMessage({
62
+ id: talkie.chat_id,
63
+ chat_room_id: talkie.chat_room_id,
64
+ signal: abort.signal,
65
+ });
66
+ if (abort.signal.aborted)
67
+ return;
68
+ if (!chat.is_talkie ||
69
+ !chat.has_objects ||
70
+ !chat.objects_uploaded ||
71
+ chat.chat_room_id !== talkie.chat_room_id)
72
+ throw unavailable();
73
+ const out = await this.opts.storage.downloadObjects({
74
+ col: ColStorageChat,
75
+ owner_id: talkie.chat_id,
76
+ mime_prefix: MimePrefixAudio,
77
+ signal: abort.signal,
78
+ });
79
+ if (abort.signal.aborted)
80
+ return;
81
+ const object = out.value?.find((entry) => entry.mime_prefix === MimePrefixAudio);
82
+ const url = object?.public_url || object?.signed_url;
83
+ if (!url)
84
+ throw unavailable();
85
+ this.opts.player.load(url);
86
+ this.loaded = item.id;
87
+ }
88
+ await this.opts.player.play();
89
+ if (abort.signal.aborted)
90
+ return;
91
+ this.patch({ playing_id: item.id });
92
+ if (!item.is_read)
93
+ notifyObserver(() => this.opts.mark_read(item.id));
94
+ }
95
+ catch (error) {
96
+ if (abort.signal.aborted)
97
+ return;
98
+ // Keep a prepared source for a second user gesture if autoplay was blocked.
99
+ if (!(error instanceof Error && error.name === "NotAllowedError"))
100
+ this.loaded = "";
101
+ throw error;
102
+ }
103
+ finally {
104
+ if (!abort.signal.aborted)
105
+ this.patch({ loading_id: "" });
106
+ }
107
+ }
108
+ async select(item) {
109
+ const talkie = this.resolve(item);
110
+ const request = ++this.selection;
111
+ const owner = this.owner;
112
+ this.patch({ selecting_id: item.id, reply: undefined });
113
+ try {
114
+ const [rooms, participants, chat] = await Promise.all([
115
+ this.opts.chat.chatRooms({ ids: [talkie.chat_room_id] }),
116
+ this.opts.chat.chatRoomParticipants({
117
+ chat_room_ids: [talkie.chat_room_id],
118
+ }),
119
+ this.opts.chat.chatMessage({
120
+ id: talkie.chat_id,
121
+ chat_room_id: talkie.chat_room_id,
122
+ }),
123
+ ]);
124
+ if (request !== this.selection)
125
+ return;
126
+ const room = rooms.find((entry) => entry.id === talkie.chat_room_id);
127
+ const members = participants[talkie.chat_room_id];
128
+ if (!chat.is_talkie ||
129
+ !chat.objects_uploaded ||
130
+ !room ||
131
+ !members?.members.some((entry) => entry.owner_id === owner))
132
+ throw unavailable();
133
+ const names = members.users
134
+ .filter((entry) => entry.id !== owner)
135
+ .map((entry) => entry.full_name || entry.username);
136
+ this.patch({
137
+ reply: {
138
+ ...talkie,
139
+ owner_id: owner,
140
+ label: room.name.trim() || names.join(", ") || talkie.sender_name,
141
+ members: members.members.length,
142
+ },
143
+ });
144
+ }
145
+ catch (error) {
146
+ if (request === this.selection)
147
+ throw error;
148
+ }
149
+ finally {
150
+ if (request === this.selection)
151
+ this.patch({ selecting_id: "" });
152
+ }
153
+ }
154
+ // The caller freezes this target at pointer-down; release queues exactly one reply.
155
+ reply(file, target) {
156
+ if (!this.owner || target.owner_id !== this.owner)
157
+ throw unavailable();
158
+ return this.opts.queue.enqueue(newChatInput({
159
+ chat_room_id: target.chat_room_id,
160
+ quoted_message_id: target.chat_id,
161
+ text: "",
162
+ has_objects: true,
163
+ is_talkie: true,
164
+ }), { files: [file], save_to_personal_box: false, full_quality: false });
165
+ }
166
+ clearReply() {
167
+ ++this.selection;
168
+ this.patch({ reply: undefined, selecting_id: "" });
169
+ }
170
+ stop() {
171
+ this.playback.abort();
172
+ this.playback = new AbortController();
173
+ this.opts.player.pause();
174
+ this.patch({ playing_id: "", loading_id: "" });
175
+ }
176
+ ended() {
177
+ this.patch({ playing_id: "" });
178
+ }
179
+ failed() {
180
+ this.loaded = "";
181
+ this.stop();
182
+ }
183
+ clear() {
184
+ this.stop();
185
+ this.clearReply();
186
+ this.loaded = "";
187
+ this.opts.player.reset();
188
+ }
189
+ resolve(item) {
190
+ const talkie = notificationTalkie(item);
191
+ if (!this.owner || item.owner_id !== this.owner || !talkie)
192
+ throw unavailable();
193
+ return talkie;
194
+ }
195
+ patch(value) {
196
+ this.value = { ...this.value, ...value };
197
+ notifyObserver(() => this.opts.on_change(this.value));
198
+ }
199
+ }
200
+ function unavailable() {
201
+ return errResolveFailed({
202
+ resource: "talkie",
203
+ msg: "This voice message or conversation is no longer available.",
204
+ });
205
+ }
@@ -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
@@ -8,6 +8,7 @@ export * from "./chat/forms.js";
8
8
  export * from "./chat/optimistic.js";
9
9
  export * from "./chat/scroll.js";
10
10
  export * from "./chat/send-queue.js";
11
+ export * from "./chat/talkies.js";
11
12
  export * from "./contacts/contacts.js";
12
13
  export * from "./contacts/scope.js";
13
14
  export * from "./core/address.js";
@@ -65,5 +66,6 @@ export * from "./timesheets/workspace.js";
65
66
  export * from "./users/email.js";
66
67
  export * from "./users/phone.js";
67
68
  export * from "./users/picture.js";
69
+ export * from "./users/profile.js";
68
70
  export * from "./users/username.js";
69
71
  export * from "./users/users.js";
package/dist/src/index.js CHANGED
@@ -8,6 +8,7 @@ export * from "./chat/forms.js";
8
8
  export * from "./chat/optimistic.js";
9
9
  export * from "./chat/scroll.js";
10
10
  export * from "./chat/send-queue.js";
11
+ export * from "./chat/talkies.js";
11
12
  export * from "./contacts/contacts.js";
12
13
  export * from "./contacts/scope.js";
13
14
  export * from "./core/address.js";
@@ -65,5 +66,6 @@ export * from "./timesheets/workspace.js";
65
66
  export * from "./users/email.js";
66
67
  export * from "./users/phone.js";
67
68
  export * from "./users/picture.js";
69
+ export * from "./users/profile.js";
68
70
  export * from "./users/username.js";
69
71
  export * from "./users/users.js";
@@ -10,6 +10,8 @@ export type NotificationInboxState = SearchState<Notification> & {
10
10
  };
11
11
  export type NotificationInboxOptions = {
12
12
  notifications: NotificationsFXOperator;
13
+ notif_k?: Notification["notif_k"];
14
+ track_unread?: boolean;
13
15
  events: EventBus;
14
16
  on_change: (state: NotificationInboxState) => void;
15
17
  on_error?: (error: unknown) => void;
@@ -29,6 +31,7 @@ export declare class NotificationInboxController {
29
31
  private readonly reads;
30
32
  private readonly deletes;
31
33
  private readonly deleted;
34
+ private readonly read;
32
35
  constructor(options: NotificationInboxOptions);
33
36
  get state(): NotificationInboxState;
34
37
  setOwner(owner_id?: string, session_id?: string): void;
@@ -18,6 +18,7 @@ export class NotificationInboxController {
18
18
  reads = new Map();
19
19
  deletes = new Map();
20
20
  deleted = new Set();
21
+ read = new Set();
21
22
  constructor(options) {
22
23
  this.options = options;
23
24
  this.search = new SearchController({
@@ -27,6 +28,7 @@ export class NotificationInboxController {
27
28
  this.stopRead = options.events.subscribe(NotificationsEvents.Read, ({ owner_id, id }) => {
28
29
  if (owner_id !== this.ownerID)
29
30
  return;
31
+ this.read.add(id);
30
32
  this.search.patchResult(id, { is_read: true });
31
33
  void this.refreshUnread();
32
34
  });
@@ -43,7 +45,11 @@ export class NotificationInboxController {
43
45
  get state() {
44
46
  const state = this.search.state;
45
47
  // An older in-flight response must never restore a confirmed deletion.
46
- const results = state.results.filter((item) => !this.deleted.has(item.id));
48
+ const results = state.results
49
+ .filter((item) => !this.deleted.has(item.id))
50
+ .map((item) => this.read.has(item.id) && !item.is_read
51
+ ? { ...item, is_read: true }
52
+ : item);
47
53
  return {
48
54
  ...state,
49
55
  results,
@@ -83,7 +89,10 @@ export class NotificationInboxController {
83
89
  await Promise.all([
84
90
  this.search.state.ready
85
91
  ? this.search.refresh()
86
- : this.search.replace({ owner_id }),
92
+ : this.search.replace({
93
+ owner_id,
94
+ notif_k: this.options.notif_k,
95
+ }),
87
96
  this.refreshUnread(),
88
97
  ]);
89
98
  }
@@ -108,7 +117,10 @@ export class NotificationInboxController {
108
117
  await Promise.all([this.search.retry(), this.refreshUnread()]);
109
118
  }
110
119
  markRead(id) {
111
- if (!this.ownerID || this.deleted.has(id) || this.deletes.has(id))
120
+ if (!this.ownerID ||
121
+ this.read.has(id) ||
122
+ this.deleted.has(id) ||
123
+ this.deletes.has(id))
112
124
  return Promise.resolve();
113
125
  const pending = this.reads.get(id);
114
126
  if (pending)
@@ -179,6 +191,8 @@ export class NotificationInboxController {
179
191
  this.clear();
180
192
  }
181
193
  async refreshUnread() {
194
+ if (this.options.track_unread === false)
195
+ return;
182
196
  this.unreadRequest?.abort();
183
197
  const request = new AbortController();
184
198
  this.unreadRequest = request;
@@ -186,6 +200,7 @@ export class NotificationInboxController {
186
200
  const out = await this.options.notifications.searchNotifications({
187
201
  owner_id: this.ownerID,
188
202
  is_read: false,
203
+ notif_k: this.options.notif_k,
189
204
  per_page: 1,
190
205
  signal: request.signal,
191
206
  });
@@ -216,6 +231,7 @@ export class NotificationInboxController {
216
231
  this.reads.clear();
217
232
  this.deletes.clear();
218
233
  this.deleted.clear();
234
+ this.read.clear();
219
235
  this.search.clear();
220
236
  }
221
237
  publish() {
@@ -46,3 +46,4 @@ export declare class NotificationsFX implements NotificationsFXOperator {
46
46
  unregisterDeviceToken(opts: UnregisterDeviceTokenOptions): Promise<void>;
47
47
  }
48
48
  export declare function newNotificationsFX(opts: NotificationsFXOptions): NotificationsFX;
49
+ export declare function notificationToggles(toggles: Record<string, boolean>): Record<string, boolean>;
@@ -1,4 +1,4 @@
1
- import { IDKey, OwnerIDKey, ZeroID, PushTransportFCM, } from "@fabriktor/schema";
1
+ import { IDKey, NotifKChatChatsReceived, NotifKChatChatsTalkieReceived, OwnerIDKey, ZeroID, PushTransportFCM, } from "@fabriktor/schema";
2
2
  import { isClientErr, queryParams, } from "@fabriktor/client";
3
3
  import { errRequired } from "../core/err.js";
4
4
  import { createEvent, EventBus } from "../core/events.js";
@@ -137,3 +137,11 @@ export class NotificationsFX {
137
137
  export function newNotificationsFX(opts) {
138
138
  return new NotificationsFX(opts);
139
139
  }
140
+ export function notificationToggles(toggles) {
141
+ return {
142
+ ...toggles,
143
+ [NotifKChatChatsTalkieReceived]: toggles[NotifKChatChatsTalkieReceived] ??
144
+ toggles[NotifKChatChatsReceived] ??
145
+ false,
146
+ };
147
+ }
@@ -50,7 +50,12 @@ export class RecordedFileWorkflow {
50
50
  });
51
51
  if (!this.current())
52
52
  return;
53
- const out = this.opts.queue.enqueue(newChatInput({ chat_room_id: room, text: "", has_objects: true }), {
53
+ const out = this.opts.queue.enqueue(newChatInput({
54
+ chat_room_id: room,
55
+ text: "",
56
+ has_objects: true,
57
+ is_talkie: true,
58
+ }), {
54
59
  files: [this.opts.file],
55
60
  save_to_personal_box: false,
56
61
  full_quality: false,
@@ -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.187",
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.114",
20
+ "@fabriktor/client": "0.0.116",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.85",
22
+ "@fabriktor/schema": "0.0.87",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }