@go-avro/avro-js 1.6.1 → 1.6.2

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.
@@ -11,6 +11,8 @@ export declare class AuthManager {
11
11
  private tokenRefreshedCallbacks;
12
12
  private tokenRefreshFailedCallbacks;
13
13
  private refreshing;
14
+ /** Bumped on every login and logout; see refreshTokens. */
15
+ private generation;
14
16
  constructor({ baseUrl, storage }: {
15
17
  baseUrl: string;
16
18
  storage: Cache | Cache[];
@@ -43,6 +45,8 @@ export declare class AuthManager {
43
45
  * failure notifies `onTokenRefreshFailed` listeners (→ logout).
44
46
  */
45
47
  refreshTokens(): Promise<Tokens>;
48
+ /** Start a new session: in-flight refreshes of the old one are void. */
49
+ private newSession;
46
50
  setTokens(tokens: Tokens): Promise<void>;
47
51
  setCache(data: Partial<CacheData> | Object): Promise<void>;
48
52
  getCache(key?: keyof CacheData | string): Promise<CacheData[keyof CacheData] | Object | string | null>;
@@ -13,6 +13,8 @@ export class AuthManager {
13
13
  this.tokenRefreshedCallbacks = [];
14
14
  this.tokenRefreshFailedCallbacks = [];
15
15
  this.refreshing = null;
16
+ /** Bumped on every login and logout; see refreshTokens. */
17
+ this.generation = 0;
16
18
  this.storages = Array.isArray(storage) ? storage : [storage];
17
19
  if (this.storages.length === 0) {
18
20
  throw new Error('At least one token storage must be provided');
@@ -162,9 +164,16 @@ export class AuthManager {
162
164
  refreshTokens() {
163
165
  if (this.refreshing)
164
166
  return this.refreshing;
167
+ const generation = this.generation;
165
168
  this.refreshing = (async () => {
166
169
  try {
167
170
  const newToken = await this.fetchNewTokens();
171
+ // A logout or a new login while this was in flight: these
172
+ // tokens belong to the old session, so never store them.
173
+ // Not an auth status: that would log out the new session.
174
+ if (generation !== this.generation) {
175
+ throw new StandardError(0, 'Session changed during token refresh');
176
+ }
168
177
  await Promise.all(this.storages.map((s) => s.set(newToken)));
169
178
  this.tokenRefreshedCallbacks.forEach((cb) => {
170
179
  if (newToken?.access_token)
@@ -173,7 +182,8 @@ export class AuthManager {
173
182
  return newToken;
174
183
  }
175
184
  catch (err) {
176
- if (isDefinitiveAuthFailure(err)) {
185
+ // Only the current session's failure means "log out".
186
+ if (isDefinitiveAuthFailure(err) && generation === this.generation) {
177
187
  this.tokenRefreshFailedCallbacks.forEach((cb) => {
178
188
  try {
179
189
  cb();
@@ -186,12 +196,20 @@ export class AuthManager {
186
196
  throw err;
187
197
  }
188
198
  finally {
189
- this.refreshing = null;
199
+ // A newer session may already have its own refresh running.
200
+ if (generation === this.generation)
201
+ this.refreshing = null;
190
202
  }
191
203
  })();
192
204
  return this.refreshing;
193
205
  }
206
+ /** Start a new session: in-flight refreshes of the old one are void. */
207
+ newSession() {
208
+ this.generation++;
209
+ this.refreshing = null;
210
+ }
194
211
  async setTokens(tokens) {
212
+ this.newSession();
195
213
  await Promise.all(this.storages.map((s) => s.set(tokens)));
196
214
  }
197
215
  async setCache(data) {
@@ -209,6 +227,7 @@ export class AuthManager {
209
227
  return null;
210
228
  }
211
229
  async clearCache() {
230
+ this.newSession();
212
231
  await Promise.all(this.storages.map((s) => s.clear()));
213
232
  }
214
233
  async getCompanyId() {
@@ -433,7 +433,17 @@ export class AvroQueryClient {
433
433
  const known = this._companyVersions.get(companyId);
434
434
  this._companyVersions.set(companyId, ack.version);
435
435
  this._persister?.setCompanyVersion(companyId, ack.version);
436
- if (known !== undefined && known !== ack.version) {
436
+ if (known === undefined) {
437
+ // First join: nothing to compare with, and changes made
438
+ // between the initial REST loads and joining the room
439
+ // were never delivered. Refresh what loaded before now
440
+ // once; later joins compare versions instead.
441
+ const joinedAt = Date.now();
442
+ this._queryClient?.invalidateQueries({
443
+ predicate: (q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt,
444
+ });
445
+ }
446
+ else if (known !== ack.version) {
437
447
  this._queryClient?.invalidateQueries();
438
448
  }
439
449
  });
@@ -2,7 +2,7 @@ import { useInfiniteQuery, useQuery, useMutation } from '@tanstack/react-query';
2
2
  import { AvroQueryClient } from '../QueryClient.js';
3
3
  import { restoreNs, snapshotNs, seedDetails, removeOptimisticRow } from '../cache.js';
4
4
  import { keys, matchesList } from '../realtime.js';
5
- import { constructEvent, DelayEvent, Job, LineItemStatus, Task, } from '../../types/api.js';
5
+ import { constructEvent, DelayEvent, Job, LineItemStatus, Task, getTaskOverdueTime, } from '../../types/api.js';
6
6
  const isJobsQuery = (q) => q.queryKey[0] === 'jobs';
7
7
  const isEventsQuery = (q) => q.queryKey[0] === 'events';
8
8
  const isEventsQueryFor = (item) => (q) => q.queryKey[0] === 'events' && matchesList('event', q.queryKey, item) === 'match';
@@ -179,12 +179,19 @@ AvroQueryClient.prototype.useCreateDelayEvent = function () {
179
179
  const delayUntil = Math.max(task.delay_until != null && task.delay_until > now
180
180
  ? task.delay_until
181
181
  : 0, now + delayData.delay_seconds);
182
+ if (task.overdue_time == null) {
183
+ return new Task({ ...task, delay_until: delayUntil });
184
+ }
185
+ // `delay` is how far the delay holds the task back,
186
+ // so the snapshot catches up once it lapses.
187
+ const live = getTaskOverdueTime(task, now);
188
+ const held = Math.min(live, now - delayUntil);
182
189
  return new Task({
183
190
  ...task,
184
191
  delay_until: delayUntil,
185
- overdue_time: task.overdue_time != null
186
- ? Math.min(task.overdue_time, now - delayUntil)
187
- : task.overdue_time,
192
+ delay: live - held,
193
+ overdue_time: held,
194
+ overdue_at: now,
188
195
  });
189
196
  }
190
197
  return task;
@@ -43,7 +43,13 @@ export interface EntitySpec {
43
43
  export declare function constructJob(raw: any): Job;
44
44
  export declare const REGISTRY: Record<string, EntitySpec>;
45
45
  export declare function removeEntity(qc: QueryClient, ns: string, id: string): void;
46
- export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any): void;
46
+ /**
47
+ * Write an entity into its detail entry and every list it belongs in.
48
+ * `company` is the company the change came from: list scopes are company
49
+ * ids, so another company's lists are left alone (a member of two
50
+ * companies keeps both companies' lists cached).
51
+ */
52
+ export declare function upsertEntity(qc: QueryClient, spec: EntitySpec, item: any, company?: string | null): void;
47
53
  export declare function matchesList(type: string, key: readonly unknown[], item: any): ListMatch;
48
54
  export declare function invalidateType(qc: QueryClient, spec: EntitySpec): void;
49
55
  export declare class ChangeApplier {
@@ -59,6 +65,8 @@ export declare class ChangeApplier {
59
65
  */
60
66
  private seq;
61
67
  private latest;
68
+ /** Company each pending `type:id` change came from (see upsertEntity). */
69
+ private companyOf;
62
70
  private inflight;
63
71
  constructor(client: AvroQueryClient, qc: QueryClient);
64
72
  private mark;
@@ -311,7 +311,13 @@ export function removeEntity(qc, ns, id) {
311
311
  qc.removeQueries({ queryKey: keys.detail(ns, id), exact: true });
312
312
  qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => (old ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old));
313
313
  }
314
- export function upsertEntity(qc, spec, item) {
314
+ /**
315
+ * Write an entity into its detail entry and every list it belongs in.
316
+ * `company` is the company the change came from: list scopes are company
317
+ * ids, so another company's lists are left alone (a member of two
318
+ * companies keeps both companies' lists cached).
319
+ */
320
+ export function upsertEntity(qc, spec, item, company) {
315
321
  const id = item?.id;
316
322
  if (!id)
317
323
  return;
@@ -321,6 +327,9 @@ export function upsertEntity(qc, spec, item) {
321
327
  .findAll({ predicate: (q) => q.queryKey[0] === spec.ns && isListKey(q.queryKey) });
322
328
  for (const query of lists) {
323
329
  const key = query.queryKey;
330
+ const scope = listScope(key);
331
+ if (company && scope && scope !== company)
332
+ continue;
324
333
  const verdict = spec.listMatch
325
334
  ? spec.listMatch(listFilters(key), item, listScope(key))
326
335
  : searchAware(listFilters(key));
@@ -380,6 +389,8 @@ export class ChangeApplier {
380
389
  */
381
390
  this.seq = 0;
382
391
  this.latest = new Map();
392
+ /** Company each pending `type:id` change came from (see upsertEntity). */
393
+ this.companyOf = new Map();
383
394
  this.inflight = new Map();
384
395
  }
385
396
  mark(type, id) {
@@ -396,6 +407,7 @@ export class ChangeApplier {
396
407
  }
397
408
  apply(payload) {
398
409
  const entries = Array.isArray(payload?.changes) ? payload.changes : [];
410
+ const company = payload?.company ?? null;
399
411
  for (const entry of entries) {
400
412
  const spec = REGISTRY[entry.type];
401
413
  if (!spec)
@@ -417,10 +429,11 @@ export class ChangeApplier {
417
429
  }
418
430
  if (entry.data !== undefined && entry.data !== null) {
419
431
  this.markApplied(entry.type, entry.id);
420
- upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data);
432
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data, company);
421
433
  spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
422
434
  continue;
423
435
  }
436
+ this.companyOf.set(`${entry.type}:${entry.id}`, company);
424
437
  this.enqueue(entry.type, entry.id);
425
438
  }
426
439
  }
@@ -475,8 +488,10 @@ export class ChangeApplier {
475
488
  return;
476
489
  }
477
490
  this.inflight.delete(key);
478
- if (current(id))
491
+ if (current(id)) {
479
492
  this.latest.delete(key);
493
+ this.companyOf.delete(key);
494
+ }
480
495
  };
481
496
  ids.forEach((id) => {
482
497
  const key = `${type}:${id}`;
@@ -528,7 +543,7 @@ export class ChangeApplier {
528
543
  for (const [id, raw] of found) {
529
544
  if (!current(id))
530
545
  continue;
531
- upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw);
546
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw, this.companyOf.get(`${type}:${id}`));
532
547
  }
533
548
  for (const id of gone) {
534
549
  if (current(id))
@@ -551,6 +566,7 @@ export class ChangeApplier {
551
566
  clearTimeout(this.timer);
552
567
  this.timer = null;
553
568
  this.pending.clear();
569
+ this.companyOf.clear();
554
570
  this.latest.clear();
555
571
  this.inflight.clear();
556
572
  }
@@ -3,21 +3,15 @@ export interface Email {
3
3
  id: string;
4
4
  company_id: string;
5
5
  name: string;
6
- mail_server: string;
7
- mail_port: number;
8
6
  mail_username: string;
9
- mail_password: string | null;
10
7
  mail_default_sender: string;
11
- mail_use_tls: boolean;
12
- mail_use_ssl: boolean;
13
8
  mail_api_key: string;
14
9
  is_company_wide: boolean;
15
10
  users: User[];
16
- type: 'OUTLOOK' | 'SMTP' | 'GMAIL';
11
+ type: 'OUTLOOK' | 'GMAIL';
17
12
  /**
18
- * False when an OAuth (Outlook/Gmail) account's grant was revoked or
19
- * expired: sends fail until someone signs in again. Always true for
20
- * SMTP accounts.
13
+ * False when the account's grant was revoked or expired: sends fail
14
+ * until someone signs in again.
21
15
  */
22
16
  connected: boolean;
23
17
  }
@@ -19,7 +19,7 @@ export interface EmailError {
19
19
  * raised before any provider could be selected (e.g. missing
20
20
  * billing email, no recipients).
21
21
  */
22
- provider: 'outlook' | 'gmail' | 'smtp' | 'unknown';
22
+ provider: 'outlook' | 'gmail' | 'unknown';
23
23
  }
24
24
  export type EmailType = 'bill' | 'proposal' | 'job' | 'generic';
25
25
  export interface EmailSucceededPayload {
@@ -1,5 +1,5 @@
1
1
  import { assignData } from './assignData.js';
2
- import { Task, TaskStatus } from './Task.js';
2
+ import { Task, TaskStatus, getTaskOverdueness } from './Task.js';
3
3
  import { RouteJob } from './RouteJob.js';
4
4
  export class Job {
5
5
  constructor(init) {
@@ -11,11 +11,14 @@ export class Job {
11
11
  if (activeTasks.length === 0) {
12
12
  return 'N/A';
13
13
  }
14
+ const now = Date.now() / 1000;
15
+ const live = (t) => getTaskOverdueness(t, now);
14
16
  const mostOverdueTask = activeTasks.reduce((mostOverdue, t) => {
15
- if (!t.overdueness || t.overdueness <= 0) {
17
+ const overdueness = live(t);
18
+ if (!overdueness || overdueness <= 0) {
16
19
  return mostOverdue;
17
20
  }
18
- if (!mostOverdue || t.overdueness > (mostOverdue.overdueness ?? 0)) {
21
+ if (!mostOverdue || overdueness > (live(mostOverdue) ?? 0)) {
19
22
  return t;
20
23
  }
21
24
  return mostOverdue;
@@ -45,8 +45,19 @@ declare module './Task.js' {
45
45
  time_updated: number | null;
46
46
  status: TaskStatus;
47
47
  created_by: UserCompanyAssociation | null;
48
+ /**
49
+ * Overdueness as of `overdue_at`. It grows with time while nothing
50
+ * in the database changes, so no realtime event refreshes it:
51
+ * prefer `getOverdueness()`.
52
+ */
48
53
  overdueness: number | null;
54
+ /** Seconds overdue as of `overdue_at`; prefer `getOverdueTime()`. */
49
55
  overdue_time: number;
56
+ /**
57
+ * When (epoch seconds) `overdueness`/`overdue_time` were computed:
58
+ * when the server payload arrived, unless the copy carried one.
59
+ */
60
+ overdue_at: number;
50
61
  last_completed_event: _Event | null;
51
62
  current_event: _Event | null;
52
63
  /**
@@ -84,12 +95,25 @@ declare module './Task.js' {
84
95
  export declare const getTaskDelayUntil: (task: {
85
96
  delay_until?: number | null;
86
97
  }, now?: number) => number | null;
98
+ /**
99
+ * Seconds overdue at `now`, rolled forward from the server's snapshot.
100
+ * Mirrors the backend: the clock only moves the value forward, except that
101
+ * a delay stops counting once it has ended.
102
+ */
103
+ type OverdueSnapshot = Partial<Pick<Task, 'overdueness' | 'overdue_time' | 'overdue_at' | 'delay' | 'delay_until' | 'status' | 'frequency' | 'priority'>>;
104
+ export declare const getTaskOverdueTime: (task: OverdueSnapshot, now?: number) => number;
105
+ /** The backend's overdueness formula, evaluated at `now`. */
106
+ export declare const getTaskOverdueness: (task: OverdueSnapshot, now?: number) => number | null;
87
107
  export declare class Task {
88
108
  constructor(init?: Partial<Task>);
89
109
  getStatusLabel: () => "Active" | "Archived" | "Pending Activation" | "Draft" | "Pending Customer Approval" | "Pending Company Approval" | "Pending Payment";
90
110
  getUnroutedReasonLabel: () => string | null;
91
- isOverdue: () => boolean;
92
- getOverdueLabel: () => string;
111
+ /** Seconds overdue right now (negative: due in that many seconds). */
112
+ getOverdueTime: (now?: number) => number;
113
+ /** Overdueness right now; null when the server reported none. */
114
+ getOverdueness: (now?: number) => number | null;
115
+ isOverdue: (now?: number) => boolean;
116
+ getOverdueLabel: (now?: number) => string;
93
117
  /** End (epoch seconds) of this task's delay if it's still in effect. */
94
118
  getDelayUntil: (now?: number) => number | null;
95
119
  isDelayed: (now?: number) => boolean;
@@ -99,3 +123,4 @@ export declare class Task {
99
123
  getPrepaidMonthsRemaining: () => number;
100
124
  isDone: (route: Route) => boolean;
101
125
  }
126
+ export {};
@@ -40,6 +40,32 @@ export const UNROUTED_REASON_LABELS = {
40
40
  * A plain function so it works on spread copies of a Task too.
41
41
  */
42
42
  export const getTaskDelayUntil = (task, now = Date.now() / 1000) => (task.delay_until != null && task.delay_until > now ? task.delay_until : null);
43
+ export const getTaskOverdueTime = (task, now = Date.now() / 1000) => {
44
+ if (task.overdue_time == null)
45
+ return 0;
46
+ const at = task.overdue_at ?? now;
47
+ let time = task.overdue_time + Math.max(now - at, 0);
48
+ // The snapshot subtracted a delay that has since lapsed.
49
+ if (task.delay_until != null && task.delay_until > at && task.delay_until <= now) {
50
+ time += task.delay ?? 0;
51
+ }
52
+ return time;
53
+ };
54
+ /** The backend's overdueness formula, evaluated at `now`. */
55
+ export const getTaskOverdueness = (task, now = Date.now() / 1000) => {
56
+ if (task.overdueness == null || task.status !== TaskStatus.ACTIVE) {
57
+ return task.overdueness ?? null;
58
+ }
59
+ const overdueTime = getTaskOverdueTime(task, now);
60
+ if (task.frequency && task.frequency > 0) {
61
+ // overdue_time counts from the due date; overdueness from the
62
+ // last service, one period earlier.
63
+ const scalar = task.priority ? 3 : 1;
64
+ const ratio = Math.max((overdueTime + task.frequency) / task.frequency, 0.01);
65
+ return Math.min(ratio * scalar, task.priority ? 10 : 3);
66
+ }
67
+ return overdueTime / (86400 * (task.priority ? 1 : 7));
68
+ };
43
69
  export class Task {
44
70
  constructor(init) {
45
71
  this.getStatusLabel = () => {
@@ -67,23 +93,28 @@ export class Task {
67
93
  return null;
68
94
  return UNROUTED_REASON_LABELS[this.last_unrouted_reason] ?? this.last_unrouted_reason;
69
95
  };
70
- this.isOverdue = () => {
96
+ /** Seconds overdue right now (negative: due in that many seconds). */
97
+ this.getOverdueTime = (now) => getTaskOverdueTime(this, now);
98
+ /** Overdueness right now; null when the server reported none. */
99
+ this.getOverdueness = (now) => getTaskOverdueness(this, now);
100
+ this.isOverdue = (now) => {
71
101
  return (this.status === TaskStatus.ACTIVE &&
72
102
  this.overdue_time !== undefined &&
73
- this.overdue_time > 0);
103
+ this.getOverdueTime(now) > 0);
74
104
  };
75
- this.getOverdueLabel = () => {
105
+ this.getOverdueLabel = (now) => {
106
+ const overdueTime = this.getOverdueTime(now);
76
107
  if (this.overdueness === null || this.status !== TaskStatus.ACTIVE) {
77
108
  return this.getStatusLabel();
78
109
  }
79
- else if (this.overdue_time <= 0) {
80
- return `In ${Math.abs(Math.round(this.overdue_time / 86400))}d`;
110
+ else if (overdueTime <= 0) {
111
+ return `In ${Math.abs(Math.round(overdueTime / 86400))}d`;
81
112
  }
82
- else if (this.overdue_time < 86400) {
113
+ else if (overdueTime < 86400) {
83
114
  return '< 1d overdue';
84
115
  }
85
116
  else {
86
- return `${Math.floor(this.overdue_time / 86400)}d overdue`;
117
+ return `${Math.floor(overdueTime / 86400)}d overdue`;
87
118
  }
88
119
  };
89
120
  /** End (epoch seconds) of this task's delay if it's still in effect. */
@@ -155,6 +186,10 @@ export class Task {
155
186
  return (this.last_completed_event?.time_ended ?? 0) >= cutoff;
156
187
  };
157
188
  assignData(this, init);
189
+ // Payloads from the server carry no timestamp: they were computed
190
+ // just now. Copies keep the one they were made with.
191
+ if (this.overdue_at == null)
192
+ this.overdue_at = Date.now() / 1000;
158
193
  if (init?.prepayments) {
159
194
  this.prepayments = init.prepayments.map((p) => new Prepayment(p));
160
195
  }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "1.6.1";
1
+ export declare const AVRO_JS_VERSION = "1.6.2";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // AUTO-GENERATED by scripts/gen-version.js — do not edit by hand.
2
2
  // Regenerated from package.json by the `prebuild` npm hook.
3
- export const AVRO_JS_VERSION = '1.6.1';
3
+ export const AVRO_JS_VERSION = '1.6.2';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",