@fabriktor/fx 0.0.180 → 0.0.182

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.
@@ -20,12 +20,16 @@ export declare class SearchController<T extends SearchResultWithID, Options exte
20
20
  private request?;
21
21
  private next_page;
22
22
  private current;
23
+ private retryRefresh;
24
+ private readonly patches;
23
25
  constructor(options: SearchControllerOptions<T, Options>);
24
26
  get state(): SearchState<T>;
25
27
  clear(): void;
26
28
  replace(selection: Options): Promise<boolean>;
27
29
  loadMore(): Promise<boolean>;
28
30
  retry(): Promise<boolean>;
31
+ refresh(): Promise<boolean>;
32
+ patchResult(id: string, patch: Partial<T>): void;
29
33
  updateResult(value: T): void;
30
34
  private load;
31
35
  private emptyState;
@@ -9,6 +9,8 @@ export class SearchController {
9
9
  request;
10
10
  next_page = normalizeSearchPage();
11
11
  current = this.emptyState();
12
+ retryRefresh = false;
13
+ patches = new Map();
12
14
  constructor(options) {
13
15
  this.options = options;
14
16
  }
@@ -22,6 +24,8 @@ export class SearchController {
22
24
  this.options.on_clear?.();
23
25
  this.selection = undefined;
24
26
  this.next_page = normalizeSearchPage();
27
+ this.retryRefresh = false;
28
+ this.patches.clear();
25
29
  this.publish(this.emptyState());
26
30
  }
27
31
  async replace(selection) {
@@ -36,8 +40,26 @@ export class SearchController {
36
40
  return await this.load(true);
37
41
  }
38
42
  async retry() {
43
+ if (this.retryRefresh)
44
+ return await this.refresh();
39
45
  return await this.load(this.next_page > normalizeSearchPage());
40
46
  }
47
+ // Refresh the displayed pages without clearing the list or its scroll region.
48
+ async refresh() {
49
+ return await this.load(false, true);
50
+ }
51
+ // Keep confirmed field updates when an older in-flight page finishes.
52
+ patchResult(id, patch) {
53
+ if (this.request) {
54
+ this.patches.set(id, { ...this.patches.get(id), ...patch });
55
+ }
56
+ if (!this.current.results.some((result) => result.id === id))
57
+ return;
58
+ this.publish({
59
+ ...this.current,
60
+ results: this.current.results.map((result) => result.id === id ? { ...result, ...patch } : result),
61
+ });
62
+ }
41
63
  // Update a displayed record without changing membership or backend position.
42
64
  // Use query replacement when a mutation can affect either of those.
43
65
  updateResult(value) {
@@ -48,32 +70,58 @@ export class SearchController {
48
70
  results: this.current.results.map((result) => result.id === value.id ? value : result),
49
71
  });
50
72
  }
51
- async load(append) {
52
- if (!this.selection || this.current.loading || this.current.loading_more) {
73
+ async load(append, refresh = false) {
74
+ if (!this.selection ||
75
+ (!refresh && (this.current.loading || this.current.loading_more))) {
53
76
  return false;
54
77
  }
78
+ this.request?.abort();
55
79
  const request = new AbortController();
56
80
  this.request = request;
81
+ this.patches.clear();
82
+ this.retryRefresh = refresh;
83
+ const lastPage = this.next_page - (this.current.has_more ? 1 : 0);
84
+ const background = refresh && this.current.ready;
57
85
  this.publish({
58
86
  ...this.current,
59
- loading: !append,
60
- loading_more: append,
87
+ loading: !append && !background,
88
+ loading_more: append || background,
61
89
  error: undefined,
62
90
  });
63
91
  try {
64
- const page = await this.options.search({
65
- ...this.selection,
66
- page: this.next_page,
67
- signal: request.signal,
68
- });
69
- if (this.request !== request || request.signal.aborted) {
70
- return false;
92
+ let next = refresh ? normalizeSearchPage() : this.next_page;
93
+ let page;
94
+ let results = [];
95
+ do {
96
+ page = await this.options.search({
97
+ ...this.selection,
98
+ page: next,
99
+ signal: request.signal,
100
+ });
101
+ if (this.request !== request || request.signal.aborted)
102
+ return false;
103
+ results = refresh
104
+ ? appendUniqueSearchResults(results, page.results)
105
+ : page.results;
106
+ if (!refresh ||
107
+ !page.has_more ||
108
+ next >= lastPage ||
109
+ page.next_page <= next)
110
+ break;
111
+ next = page.next_page;
112
+ } while (true);
113
+ if (this.patches.size) {
114
+ results = results.map((result) => ({
115
+ ...result,
116
+ ...this.patches.get(result.id),
117
+ }));
71
118
  }
72
119
  this.next_page = page.next_page;
120
+ this.retryRefresh = false;
73
121
  this.publish({
74
122
  results: append
75
- ? appendUniqueSearchResults(this.current.results, page.results)
76
- : page.results,
123
+ ? appendUniqueSearchResults(this.current.results, results)
124
+ : results,
77
125
  ready: true,
78
126
  loading: false,
79
127
  loading_more: false,
@@ -100,6 +148,7 @@ export class SearchController {
100
148
  finally {
101
149
  if (this.request === request) {
102
150
  this.request = undefined;
151
+ this.patches.clear();
103
152
  }
104
153
  }
105
154
  }
package/dist/src/fx.js CHANGED
@@ -71,6 +71,7 @@ export class FX {
71
71
  this.notifications = newNotificationsFX({
72
72
  notifications: opts.notifications,
73
73
  get_device_token: opts.get_device_token,
74
+ events: this.events,
74
75
  });
75
76
  this.payments = newPaymentsFX({
76
77
  payments: opts.payments,
@@ -35,6 +35,7 @@ export * from "./jobs/jobs.js";
35
35
  export * from "./marketplace/marketplace.js";
36
36
  export * from "./marketplace/validation.js";
37
37
  export * from "./memos/memos.js";
38
+ export * from "./notifications/inbox.js";
38
39
  export * from "./notifications/notifications.js";
39
40
  export * from "./notifications/route.js";
40
41
  export * from "./payments/payments.js";
package/dist/src/index.js CHANGED
@@ -35,6 +35,7 @@ export * from "./jobs/jobs.js";
35
35
  export * from "./marketplace/marketplace.js";
36
36
  export * from "./marketplace/validation.js";
37
37
  export * from "./memos/memos.js";
38
+ export * from "./notifications/inbox.js";
38
39
  export * from "./notifications/notifications.js";
39
40
  export * from "./notifications/route.js";
40
41
  export * from "./payments/payments.js";
@@ -0,0 +1,39 @@
1
+ import type { Notification } from "@fabriktor/schema";
2
+ import { EventBus } from "../core/events.js";
3
+ import { type SearchState } from "../core/search-controller.js";
4
+ import { type NotificationsFXOperator } from "./notifications.js";
5
+ export type NotificationInboxState = SearchState<Notification> & {
6
+ readonly identity: string;
7
+ readonly reading: readonly string[];
8
+ readonly has_unread: boolean;
9
+ };
10
+ export type NotificationInboxOptions = {
11
+ notifications: NotificationsFXOperator;
12
+ events: EventBus;
13
+ on_change: (state: NotificationInboxState) => void;
14
+ on_error?: (error: unknown) => void;
15
+ };
16
+ export declare class NotificationInboxController {
17
+ private readonly options;
18
+ private readonly search;
19
+ private readonly stopRead;
20
+ private ownerID;
21
+ private identity;
22
+ private session;
23
+ private refreshing?;
24
+ private refreshPending;
25
+ private unreadRequest?;
26
+ private hasUnread;
27
+ private readonly reads;
28
+ constructor(options: NotificationInboxOptions);
29
+ get state(): NotificationInboxState;
30
+ setOwner(owner_id?: string, session_id?: string): void;
31
+ refresh(): Promise<void>;
32
+ loadMore(): Promise<void>;
33
+ retry(): Promise<void>;
34
+ markRead(id: string): Promise<void>;
35
+ dispose(): void;
36
+ private refreshUnread;
37
+ private clear;
38
+ private publish;
39
+ }
@@ -0,0 +1,163 @@
1
+ import { notifyObserver } from "../core/events.js";
2
+ import { resolvedID } from "../core/id.js";
3
+ import { SearchController, } from "../core/search-controller.js";
4
+ import { NotificationsEvents, } from "./notifications.js";
5
+ // One owner's displayed pages; pushes invalidate them, never insert local records.
6
+ export class NotificationInboxController {
7
+ options;
8
+ search;
9
+ stopRead;
10
+ ownerID = "";
11
+ identity = "";
12
+ session = new AbortController();
13
+ refreshing;
14
+ refreshPending = false;
15
+ unreadRequest;
16
+ hasUnread = false;
17
+ reads = new Map();
18
+ constructor(options) {
19
+ this.options = options;
20
+ this.search = new SearchController({
21
+ search: (opts) => options.notifications.searchNotifications(opts),
22
+ on_change: () => this.publish(),
23
+ });
24
+ this.stopRead = options.events.subscribe(NotificationsEvents.Read, ({ owner_id, id }) => {
25
+ if (owner_id !== this.ownerID)
26
+ return;
27
+ this.search.patchResult(id, { is_read: true });
28
+ void this.refreshUnread();
29
+ });
30
+ }
31
+ get state() {
32
+ return {
33
+ ...this.search.state,
34
+ identity: this.identity,
35
+ reading: [...this.reads.keys()],
36
+ has_unread: this.hasUnread,
37
+ };
38
+ }
39
+ setOwner(owner_id, session_id = "") {
40
+ const owner = resolvedID(owner_id) ?? "";
41
+ const identity = owner ? `${owner}:${session_id}` : "";
42
+ if (identity === this.identity)
43
+ return;
44
+ this.clear();
45
+ this.ownerID = owner;
46
+ this.identity = identity;
47
+ this.publish();
48
+ void this.refresh();
49
+ }
50
+ refresh() {
51
+ if (!this.ownerID)
52
+ return Promise.resolve();
53
+ this.refreshPending = true;
54
+ if (this.refreshing)
55
+ return this.refreshing;
56
+ const session = this.session;
57
+ const owner_id = this.ownerID;
58
+ // Coalesce bursts and keep one follow-up for pushes received during a fetch.
59
+ const run = Promise.resolve()
60
+ .then(async () => {
61
+ while (!session.signal.aborted && this.refreshPending) {
62
+ this.refreshPending = false;
63
+ await Promise.all([
64
+ this.search.state.ready
65
+ ? this.search.refresh()
66
+ : this.search.replace({ owner_id }),
67
+ this.refreshUnread(),
68
+ ]);
69
+ }
70
+ })
71
+ .finally(() => {
72
+ if (this.refreshing === run)
73
+ this.refreshing = undefined;
74
+ });
75
+ this.refreshing = run;
76
+ return run;
77
+ }
78
+ async loadMore() {
79
+ const session = this.session;
80
+ await this.refreshing;
81
+ if (this.ownerID && session === this.session)
82
+ await this.search.loadMore();
83
+ }
84
+ async retry() {
85
+ const session = this.session;
86
+ await this.refreshing;
87
+ if (this.ownerID && session === this.session)
88
+ await Promise.all([this.search.retry(), this.refreshUnread()]);
89
+ }
90
+ markRead(id) {
91
+ if (!this.ownerID)
92
+ return Promise.resolve();
93
+ const pending = this.reads.get(id);
94
+ if (pending)
95
+ return pending;
96
+ const session = this.session;
97
+ const owner_id = this.ownerID;
98
+ const run = Promise.resolve()
99
+ .then(() => {
100
+ if (session.signal.aborted)
101
+ return;
102
+ return this.options.notifications.markNotificationRead({
103
+ id,
104
+ owner_id,
105
+ signal: session.signal,
106
+ });
107
+ })
108
+ .finally(() => {
109
+ if (this.reads.get(id) !== run)
110
+ return;
111
+ this.reads.delete(id);
112
+ this.publish();
113
+ });
114
+ this.reads.set(id, run);
115
+ this.publish();
116
+ return run;
117
+ }
118
+ dispose() {
119
+ this.stopRead();
120
+ this.clear();
121
+ }
122
+ async refreshUnread() {
123
+ this.unreadRequest?.abort();
124
+ const request = new AbortController();
125
+ this.unreadRequest = request;
126
+ try {
127
+ const out = await this.options.notifications.searchNotifications({
128
+ owner_id: this.ownerID,
129
+ is_read: false,
130
+ per_page: 1,
131
+ signal: request.signal,
132
+ });
133
+ if (this.unreadRequest !== request || request.signal.aborted)
134
+ return;
135
+ this.hasUnread = out.results.length > 0;
136
+ this.publish();
137
+ }
138
+ catch (error) {
139
+ if (!request.signal.aborted)
140
+ notifyObserver(() => this.options.on_error?.(error));
141
+ }
142
+ finally {
143
+ if (this.unreadRequest === request)
144
+ this.unreadRequest = undefined;
145
+ }
146
+ }
147
+ clear() {
148
+ this.session.abort();
149
+ this.unreadRequest?.abort();
150
+ this.unreadRequest = undefined;
151
+ this.hasUnread = false;
152
+ this.session = new AbortController();
153
+ this.ownerID = "";
154
+ this.identity = "";
155
+ this.refreshing = undefined;
156
+ this.refreshPending = false;
157
+ this.reads.clear();
158
+ this.search.clear();
159
+ }
160
+ publish() {
161
+ notifyObserver(() => this.options.on_change(this.state));
162
+ }
163
+ }
@@ -1,9 +1,19 @@
1
- import type { NotificationsOperator } from "@fabriktor/client";
1
+ import { type Notification } from "@fabriktor/schema";
2
+ import { type NotificationsOperator, type RequestOptions } from "@fabriktor/client";
3
+ import { EventBus } from "../core/events.js";
4
+ import { type OwnerSearchOptions, type SearchPage } from "../core/search.js";
5
+ export declare const NotificationsEvents: {
6
+ readonly Read: import("../index.js").EventKey<Pick<Notification, "id" | "owner_id">>;
7
+ };
2
8
  export type DeviceTokenProvider = () => Promise<string>;
3
9
  export type NotificationsFXOptions = {
4
10
  notifications: NotificationsOperator;
5
11
  get_device_token: DeviceTokenProvider;
12
+ events?: EventBus;
6
13
  };
14
+ export type SearchNotificationsOptions = OwnerSearchOptions & Partial<Pick<Notification, "is_read" | "notif_k" | "key">>;
15
+ export type SearchNotificationsPage = SearchPage<Notification>;
16
+ export type MarkNotificationReadOptions = RequestOptions & Pick<Notification, "id" | "owner_id">;
7
17
  export type SyncDeviceTokenOptions = {
8
18
  owner_id: string;
9
19
  previous_id?: string;
@@ -16,13 +26,18 @@ export type UnregisterDeviceTokenOptions = {
16
26
  };
17
27
  export type SyncDeviceTokenResult = Awaited<ReturnType<NotificationsOperator["upsertOneDTok"]>>;
18
28
  export interface NotificationsFXOperator {
29
+ searchNotifications(opts: SearchNotificationsOptions): Promise<SearchNotificationsPage>;
30
+ markNotificationRead(opts: MarkNotificationReadOptions): Promise<void>;
19
31
  syncDeviceToken(opts: SyncDeviceTokenOptions): Promise<SyncDeviceTokenResult>;
20
32
  unregisterDeviceToken(opts: UnregisterDeviceTokenOptions): Promise<void>;
21
33
  }
22
34
  export declare class NotificationsFX implements NotificationsFXOperator {
23
35
  private notifications;
24
36
  private getDeviceToken;
37
+ private readonly events;
25
38
  constructor(opts: NotificationsFXOptions);
39
+ searchNotifications(opts: SearchNotificationsOptions): Promise<SearchNotificationsPage>;
40
+ markNotificationRead(opts: MarkNotificationReadOptions): Promise<void>;
26
41
  syncDeviceToken(opts: SyncDeviceTokenOptions): Promise<SyncDeviceTokenResult>;
27
42
  unregisterDeviceToken(opts: UnregisterDeviceTokenOptions): Promise<void>;
28
43
  }
@@ -1,16 +1,64 @@
1
- import { ZeroID, PushTransportFCM } from "@fabriktor/schema";
1
+ import { IDKey, OwnerIDKey, ZeroID, PushTransportFCM, } from "@fabriktor/schema";
2
+ import { queryParams, } from "@fabriktor/client";
2
3
  import { errRequired } from "../core/err.js";
4
+ import { createEvent, EventBus } from "../core/events.js";
3
5
  import { requiredOperationID, resolvedID } from "../core/id.js";
6
+ import { runOwnerSearch, } from "../core/search.js";
7
+ export const NotificationsEvents = {
8
+ Read: createEvent(),
9
+ };
4
10
  const msgOwnerIDRequired = "Owner ID is required.";
11
+ const msgNotificationIDRequired = "Notification ID is required.";
5
12
  const msgDeviceTokenRequired = "Device token is required.";
6
13
  const msgDeviceRegistrationRequired = "Device registration is required.";
7
14
  const msgDeviceRegistrationMissing = "Device registration response did not contain an ID.";
8
15
  export class NotificationsFX {
9
16
  notifications;
10
17
  getDeviceToken;
18
+ events;
11
19
  constructor(opts) {
12
20
  this.notifications = opts.notifications;
13
21
  this.getDeviceToken = opts.get_device_token;
22
+ this.events = opts.events ?? new EventBus();
23
+ }
24
+ async searchNotifications(opts) {
25
+ const { is_read, notif_k, key, ...searchOpts } = opts;
26
+ const owner_id = resolvedID(opts.owner_id);
27
+ if (owner_id === undefined) {
28
+ throw errRequired({
29
+ field: OwnerIDKey,
30
+ msg: msgOwnerIDRequired,
31
+ });
32
+ }
33
+ return await runOwnerSearch({
34
+ ...searchOpts,
35
+ owner_id,
36
+ query: queryParams({ is_read, notif_k, key }),
37
+ search: (searchOpts) => this.notifications.searchManyNotifications(searchOpts),
38
+ });
39
+ }
40
+ async markNotificationRead(opts) {
41
+ const owner_id = resolvedID(opts.owner_id);
42
+ if (owner_id === undefined) {
43
+ throw errRequired({
44
+ field: OwnerIDKey,
45
+ msg: msgOwnerIDRequired,
46
+ });
47
+ }
48
+ const id = resolvedID(opts.id);
49
+ if (id === undefined) {
50
+ throw errRequired({
51
+ field: IDKey,
52
+ msg: msgNotificationIDRequired,
53
+ });
54
+ }
55
+ await this.notifications.replaceOneNotification({
56
+ id,
57
+ in: { is_read: true },
58
+ signal: opts.signal,
59
+ idempotency_key: opts.idempotency_key,
60
+ });
61
+ this.events.publish(NotificationsEvents.Read, { owner_id, id });
14
62
  }
15
63
  async syncDeviceToken(opts) {
16
64
  const owner_id = opts.owner_id.trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.180",
3
+ "version": "0.0.182",
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.111",
20
+ "@fabriktor/client": "0.0.112",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.83",
22
+ "@fabriktor/schema": "0.0.84",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }