@go-avro/avro-js 0.0.119 → 0.0.120

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.
@@ -0,0 +1,470 @@
1
+ /**
2
+ * Realtime cache sync. Applies backend `changes` batches (id-only) to
3
+ * the TanStack cache: id entries coalesce into one bulk fetch per type,
4
+ * `delete` removes, `invalidate` refetches. Query keys: `[ns, id]`
5
+ * detail, `keys.list/keys.infinite(ns, scope, filters)` for lists.
6
+ */
7
+ import { constructEvent, Job, Route } from '../types/api';
8
+ export const keys = {
9
+ detail: (ns, id) => [ns, id],
10
+ list: (ns, scope, filters = {}) => [ns, 'list', scope ?? '', filters],
11
+ infinite: (ns, scope, filters = {}) => [ns, 'infinite', scope ?? '', filters],
12
+ };
13
+ export function isListKey(key) {
14
+ return key.length >= 4 && (key[1] === 'list' || key[1] === 'infinite');
15
+ }
16
+ export function isDetailKey(key) {
17
+ return key.length === 2 && typeof key[1] === 'string';
18
+ }
19
+ export function listFilters(key) {
20
+ const f = key[3];
21
+ return f && typeof f === 'object' ? f : {};
22
+ }
23
+ export function listScope(key) {
24
+ return typeof key[2] === 'string' ? key[2] : '';
25
+ }
26
+ function searchAware(filters) {
27
+ const q = filters.query;
28
+ return typeof q === 'string' && q.length > 0 ? 'unknown' : 'match';
29
+ }
30
+ function withIds(filters, item) {
31
+ const known = filters.known_ids;
32
+ const unknown = filters.unknown_ids;
33
+ if (Array.isArray(known) && known.length > 0 && !known.includes(item.id))
34
+ return 'nomatch';
35
+ if (Array.isArray(unknown) && unknown.length > 0 && unknown.includes(item.id))
36
+ return 'nomatch';
37
+ return null;
38
+ }
39
+ export function constructJob(raw) {
40
+ const job = new Job(raw);
41
+ job.current_event = job.tasks.reduce((latest, task) => {
42
+ return task.current_event &&
43
+ (!latest || task.current_event.time_started > latest.time_started)
44
+ ? task.current_event
45
+ : latest;
46
+ }, job.current_event);
47
+ job.last_completed_event = job.tasks.reduce((latest, task) => {
48
+ return task.last_completed_event &&
49
+ (!latest || task.last_completed_event.time_started > latest.time_started)
50
+ ? task.last_completed_event
51
+ : latest;
52
+ }, job.last_completed_event);
53
+ return job;
54
+ }
55
+ function matchJobs(filters, item) {
56
+ const routeId = filters.routeId;
57
+ if (typeof routeId === 'string' && routeId.length > 0) {
58
+ const routes = item.routes ?? [];
59
+ if (!routes.some((r) => r?.route_id === routeId))
60
+ return 'nomatch';
61
+ }
62
+ return searchAware(filters);
63
+ }
64
+ function isPaidStatus(status) {
65
+ return status === 'PAID' || status === 'PREPAID' || status === 'EXTERNALLY_PAID';
66
+ }
67
+ function isBilledStatus(status) {
68
+ return status === 'BILLED' || status === 'EXTERNALLY_BILLED';
69
+ }
70
+ /** Shared by events / months / prepayments (line-item lists). */
71
+ function matchLineItems(filters, item) {
72
+ const byIds = withIds(filters, item);
73
+ if (byIds)
74
+ return byIds;
75
+ const parentKey = typeof filters.jobId === 'string' ? 'job_id' : null;
76
+ if (parentKey && filters.jobId && item[parentKey] !== filters.jobId)
77
+ return 'nomatch';
78
+ if (typeof filters.taskId === 'string' && filters.taskId && item.task_id !== filters.taskId)
79
+ return 'nomatch';
80
+ const types = filters.line_item_types;
81
+ if (Array.isArray(types) &&
82
+ types.length > 0 &&
83
+ item.line_item_type !== undefined &&
84
+ !types.includes(item.line_item_type))
85
+ return 'nomatch';
86
+ const status = item.status;
87
+ if (status !== undefined) {
88
+ const paid = isPaidStatus(status);
89
+ const billed = isBilledStatus(status);
90
+ const unbilled = !paid && !billed;
91
+ if (filters.paid === false && paid)
92
+ return 'nomatch';
93
+ if (filters.billed === false && billed)
94
+ return 'nomatch';
95
+ if (filters.unbilled === false && unbilled)
96
+ return 'nomatch';
97
+ }
98
+ return searchAware(filters);
99
+ }
100
+ function matchBills(filters, item) {
101
+ const byIds = withIds(filters, item);
102
+ if (byIds)
103
+ return byIds;
104
+ const status = item.status;
105
+ if (typeof filters.paid === 'boolean' && status !== undefined) {
106
+ const paid = status === 'PAID' || status === 'MANUALLY_PAID';
107
+ if (filters.paid !== paid)
108
+ return 'nomatch';
109
+ }
110
+ const hard = ['created_from', 'created_to', 'paid_from', 'paid_to', 'amount_min', 'amount_max'];
111
+ if (hard.some((k) => filters[k] !== undefined && filters[k] !== null))
112
+ return 'unknown';
113
+ if (Array.isArray(filters.labels) && filters.labels.length > 0)
114
+ return 'unknown';
115
+ return searchAware(filters);
116
+ }
117
+ function matchSessions(filters, item, _scope) {
118
+ if (filters.scope === 'active')
119
+ return item.time_ended ? 'nomatch' : 'match';
120
+ if (filters.scope === 'mine')
121
+ return 'unknown';
122
+ const byIds = withIds(filters, item);
123
+ if (byIds)
124
+ return byIds;
125
+ return searchAware(filters);
126
+ }
127
+ function matchCheckins(filters, item) {
128
+ if (typeof filters.jobId === 'string' && item.job_id !== filters.jobId)
129
+ return 'nomatch';
130
+ return 'unknown';
131
+ }
132
+ function matchTimecards(filters, item) {
133
+ if (filters.userCompanyId && item.user_company_id !== filters.userCompanyId)
134
+ return 'nomatch';
135
+ if (filters.status && item.status !== filters.status)
136
+ return 'nomatch';
137
+ if (filters.periodStart && item.period_start !== filters.periodStart)
138
+ return 'nomatch';
139
+ return 'match';
140
+ }
141
+ function matchPayouts(filters, item) {
142
+ const byIds = withIds(filters, item);
143
+ if (byIds)
144
+ return byIds;
145
+ if (filters.status && item.status !== filters.status)
146
+ return 'nomatch';
147
+ const hard = [
148
+ 'created_from',
149
+ 'created_to',
150
+ 'arrival_from',
151
+ 'arrival_to',
152
+ 'amount_min',
153
+ 'amount_max',
154
+ ];
155
+ if (hard.some((k) => filters[k] !== undefined && filters[k] !== null))
156
+ return 'unknown';
157
+ return searchAware(filters);
158
+ }
159
+ const bulk = (method) => (client, ids) => client[method]({ unknown_ids: ids, amt: ids.length });
160
+ export const REGISTRY = {
161
+ job: {
162
+ ns: 'jobs',
163
+ construct: constructJob,
164
+ fetchMany: bulk('fetchJobs'),
165
+ listMatch: matchJobs,
166
+ },
167
+ event: {
168
+ ns: 'events',
169
+ construct: constructEvent,
170
+ fetchMany: bulk('fetchEvents'),
171
+ listMatch: matchLineItems,
172
+ },
173
+ route: {
174
+ ns: 'routes',
175
+ construct: (d) => new Route(d),
176
+ fetchMany: bulk('fetchRoutes'),
177
+ listMatch: searchAware,
178
+ },
179
+ team: { ns: 'teams', fetchMany: bulk('fetchTeams'), listMatch: searchAware },
180
+ group: { ns: 'groups', fetchMany: bulk('fetchGroups'), listMatch: searchAware },
181
+ label: { ns: 'labels', fetchMany: bulk('fetchLabels'), listMatch: searchAware },
182
+ skill: { ns: 'skills', fetchMany: bulk('fetchSkills'), listMatch: searchAware },
183
+ catalog_item: {
184
+ ns: 'catalog_items',
185
+ fetchOne: (client, id) => client.get({ path: `/catalog_item/${id}` }),
186
+ listMatch: searchAware,
187
+ },
188
+ proposal: {
189
+ ns: 'proposals',
190
+ fetchOne: (client, id) => client.get({ path: `/proposal/${id}` }),
191
+ alsoInvalidate: [['tasks']],
192
+ },
193
+ month: { ns: 'months', fetchMany: bulk('fetchMonths'), listMatch: matchLineItems },
194
+ prepayment: {
195
+ ns: 'prepayments',
196
+ fetchMany: bulk('fetchPrepayments'),
197
+ listMatch: matchLineItems,
198
+ },
199
+ bill: { ns: 'bills', fetchMany: bulk('fetchBills'), listMatch: matchBills },
200
+ session: {
201
+ ns: 'sessions',
202
+ fetchMany: (client, ids) => client.post({
203
+ path: `/company/${client.companyId}/sessions?amount=${ids.length}`,
204
+ data: JSON.stringify({ unknown_ids: ids }),
205
+ headers: { 'Content-Type': 'application/json' },
206
+ }),
207
+ listMatch: matchSessions,
208
+ alsoInvalidate: [['analytics', 'sessions']],
209
+ },
210
+ checkin: { ns: 'checkins', listMatch: matchCheckins },
211
+ waiver: { ns: 'waivers', fetchMany: bulk('fetchWaivers'), listMatch: searchAware },
212
+ payout: { ns: 'payouts', fetchMany: bulk('fetchPayouts'), listMatch: matchPayouts },
213
+ timecard: {
214
+ ns: 'timecards',
215
+ fetchOne: (client, id) => client
216
+ .get({ path: `/timecard/${id}` })
217
+ .then((r) => r?.timecard ?? r),
218
+ listMatch: matchTimecards,
219
+ },
220
+ company: {
221
+ ns: 'companies',
222
+ invalidateOnly: true,
223
+ alsoInvalidate: [['/company/list'], ['companies', 'current']],
224
+ },
225
+ member: { ns: 'members', invalidateOnly: true, alsoInvalidate: [['users', 'company']] },
226
+ user: { ns: 'users', invalidateOnly: true, alsoInvalidate: [['user']] },
227
+ plan: { ns: 'plans', invalidateOnly: true },
228
+ };
229
+ function mapList(data, fn) {
230
+ if (Array.isArray(data))
231
+ return fn(data);
232
+ if (data && Array.isArray(data.pages)) {
233
+ return {
234
+ ...data,
235
+ pages: data.pages.map((p) => (Array.isArray(p) ? fn(p) : p)),
236
+ };
237
+ }
238
+ return data;
239
+ }
240
+ function listHas(data, id) {
241
+ if (Array.isArray(data))
242
+ return data.some((x) => x?.id === id);
243
+ if (data && Array.isArray(data.pages))
244
+ return data.pages.some((p) => p?.some?.((x) => x?.id === id));
245
+ return false;
246
+ }
247
+ function insertInto(data, item) {
248
+ if (Array.isArray(data))
249
+ return [...data, item];
250
+ if (data && Array.isArray(data.pages)) {
251
+ const pages = data.pages;
252
+ return { ...data, pages: [[item, ...(pages[0] ?? [])], ...pages.slice(1)] };
253
+ }
254
+ return data;
255
+ }
256
+ export function removeEntity(qc, ns, id) {
257
+ qc.removeQueries({ queryKey: keys.detail(ns, id), exact: true });
258
+ qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => (old ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old));
259
+ }
260
+ export function upsertEntity(qc, spec, item) {
261
+ const id = item?.id;
262
+ if (!id)
263
+ return;
264
+ qc.setQueryData(keys.detail(spec.ns, id), item);
265
+ const lists = qc
266
+ .getQueryCache()
267
+ .findAll({ predicate: (q) => q.queryKey[0] === spec.ns && isListKey(q.queryKey) });
268
+ for (const query of lists) {
269
+ const key = query.queryKey;
270
+ const verdict = spec.listMatch
271
+ ? spec.listMatch(listFilters(key), item, listScope(key))
272
+ : searchAware(listFilters(key));
273
+ if (verdict === 'unknown') {
274
+ qc.invalidateQueries({ queryKey: key, exact: true });
275
+ continue;
276
+ }
277
+ qc.setQueryData(key, (old) => {
278
+ if (!old)
279
+ return old;
280
+ const present = listHas(old, id);
281
+ if (verdict === 'nomatch') {
282
+ return present ? mapList(old, (items) => items.filter((x) => x?.id !== id)) : old;
283
+ }
284
+ if (present)
285
+ return mapList(old, (items) => items.map((x) => (x?.id === id ? item : x)));
286
+ return insertInto(old, item);
287
+ });
288
+ // A fresh insert into a server-ordered paged list: settle order.
289
+ if (verdict === 'match' &&
290
+ key[1] === 'infinite' &&
291
+ !listHas(query.state.data, id)) {
292
+ qc.invalidateQueries({ queryKey: key, exact: true });
293
+ }
294
+ }
295
+ }
296
+ export function matchesList(type, key, item) {
297
+ const spec = REGISTRY[type];
298
+ if (!spec || !isListKey(key))
299
+ return 'nomatch';
300
+ return spec.listMatch
301
+ ? spec.listMatch(listFilters(key), item, listScope(key))
302
+ : searchAware(listFilters(key));
303
+ }
304
+ export function invalidateType(qc, spec) {
305
+ qc.invalidateQueries({ queryKey: [spec.ns] });
306
+ spec.alsoInvalidate?.forEach((k) => qc.invalidateQueries({ queryKey: [...k] }));
307
+ }
308
+ // ─── Applying batches ───────────────────────────────────────────────
309
+ const FETCH_COALESCE_MS = 50;
310
+ const FETCH_CHUNK = 100;
311
+ export class ChangeApplier {
312
+ constructor(client, qc) {
313
+ this.client = client;
314
+ this.qc = qc;
315
+ this.pending = new Map();
316
+ this.timer = null;
317
+ }
318
+ apply(payload) {
319
+ const entries = Array.isArray(payload?.changes) ? payload.changes : [];
320
+ for (const entry of entries) {
321
+ const spec = REGISTRY[entry.type];
322
+ if (!spec)
323
+ continue;
324
+ if (entry.op === 'invalidate' || spec.invalidateOnly) {
325
+ invalidateType(this.qc, spec);
326
+ if (spec.ns === 'users' && entry.id) {
327
+ this.qc.invalidateQueries({ queryKey: keys.detail('users', entry.id) });
328
+ }
329
+ continue;
330
+ }
331
+ if (!entry.id)
332
+ continue;
333
+ if (entry.op === 'delete') {
334
+ removeEntity(this.qc, spec.ns, entry.id);
335
+ spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
336
+ continue;
337
+ }
338
+ if (entry.data !== undefined && entry.data !== null) {
339
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(entry.data) : entry.data);
340
+ spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
341
+ continue;
342
+ }
343
+ this.enqueue(entry.type, entry.id);
344
+ }
345
+ }
346
+ enqueue(type, id) {
347
+ let set = this.pending.get(type);
348
+ if (!set) {
349
+ set = new Set();
350
+ this.pending.set(type, set);
351
+ }
352
+ set.add(id);
353
+ if (!this.timer) {
354
+ this.timer = setTimeout(() => {
355
+ this.timer = null;
356
+ void this.flush();
357
+ }, FETCH_COALESCE_MS);
358
+ }
359
+ }
360
+ async flush() {
361
+ const batches = Array.from(this.pending.entries());
362
+ this.pending.clear();
363
+ await Promise.all(batches.map(([type, ids]) => this.fetchAndApply(type, [...ids])));
364
+ }
365
+ async fetchAndApply(type, ids) {
366
+ const spec = REGISTRY[type];
367
+ if (!spec)
368
+ return;
369
+ try {
370
+ let raws = [];
371
+ if (spec.fetchMany) {
372
+ for (let i = 0; i < ids.length; i += FETCH_CHUNK) {
373
+ const chunk = ids.slice(i, i + FETCH_CHUNK);
374
+ const got = await spec.fetchMany(this.client, chunk);
375
+ raws = raws.concat(Array.isArray(got) ? got : []);
376
+ }
377
+ }
378
+ else if (spec.fetchOne) {
379
+ const results = await Promise.allSettled(ids.map((id) => spec.fetchOne(this.client, id)));
380
+ raws = results
381
+ .filter((r) => r.status === 'fulfilled')
382
+ .map((r) => r.value)
383
+ .filter(Boolean);
384
+ }
385
+ else {
386
+ invalidateType(this.qc, spec);
387
+ return;
388
+ }
389
+ const seen = new Set();
390
+ for (const raw of raws) {
391
+ if (!raw?.id)
392
+ continue;
393
+ seen.add(raw.id);
394
+ upsertEntity(this.qc, spec, spec.construct ? spec.construct(raw) : raw);
395
+ }
396
+ for (const id of ids)
397
+ if (!seen.has(id))
398
+ removeEntity(this.qc, spec.ns, id);
399
+ spec.alsoInvalidate?.forEach((k) => this.qc.invalidateQueries({ queryKey: [...k] }));
400
+ }
401
+ catch (err) {
402
+ console.error(`[realtime] bulk fetch for ${type} failed:`, err);
403
+ invalidateType(this.qc, spec);
404
+ }
405
+ }
406
+ dispose() {
407
+ if (this.timer)
408
+ clearTimeout(this.timer);
409
+ this.timer = null;
410
+ this.pending.clear();
411
+ }
412
+ }
413
+ /** Namespaces a mutation should refetch when no socket can deliver the change. */
414
+ export function fallbackInvalidate(qc, types) {
415
+ for (const t of types) {
416
+ const spec = REGISTRY[t];
417
+ if (spec)
418
+ invalidateType(qc, spec);
419
+ else
420
+ qc.invalidateQueries({ queryKey: [t] });
421
+ }
422
+ }
423
+ // ─── Live-location patches (no refetch) ─────────────────────────────
424
+ export function patchMemberLocation(qc, data) {
425
+ const userId = data?.user_id;
426
+ if (!userId || typeof userId !== 'string' || typeof data?.latitude !== 'number') {
427
+ qc.invalidateQueries({ queryKey: ['users', 'company'] });
428
+ return;
429
+ }
430
+ qc.setQueriesData({ queryKey: ['users', 'company'] }, (old) => {
431
+ if (!Array.isArray(old))
432
+ return old;
433
+ let changed = false;
434
+ const next = old.map((u) => {
435
+ if (u?.user?.id !== userId)
436
+ return u;
437
+ changed = true;
438
+ return { ...u, last_location: data };
439
+ });
440
+ return changed ? next : old;
441
+ });
442
+ }
443
+ export function patchTeamLocation(qc, data) {
444
+ const teamId = data?.team_id;
445
+ if (!teamId || typeof teamId !== 'string')
446
+ return;
447
+ const patch = (teams) => {
448
+ let changed = false;
449
+ const next = teams.map((t) => {
450
+ if (t?.id !== teamId)
451
+ return t;
452
+ changed = true;
453
+ return { ...t, current_location: data };
454
+ });
455
+ return changed ? next : teams;
456
+ };
457
+ qc.setQueriesData({ queryKey: ['teams'] }, (old) => {
458
+ if (Array.isArray(old))
459
+ return patch(old);
460
+ if (old?.pages) {
461
+ return {
462
+ ...old,
463
+ pages: old.pages.map((p) => (Array.isArray(p) ? patch(p) : p)),
464
+ };
465
+ }
466
+ if (old?.id === teamId)
467
+ return { ...old, current_location: data };
468
+ return old;
469
+ });
470
+ }
@@ -39,7 +39,7 @@ export declare class Job {
39
39
  isOverdue: () => boolean;
40
40
  getOverdueLabel: () => string;
41
41
  getStatus(): "PENDING_CUSTOMER" | "PENDING_COMPANY" | "ACTIVE" | "ARCHIVED" | "DRAFT" | "PENDING_PAYMENT" | "PENDING_ACTIVATION";
42
- getStatusLabel(): "Active" | "Draft" | "Archived" | "Pending Activation" | "Customer Approval" | "Company Approval" | "Awaiting Payment";
42
+ getStatusLabel(): "Active" | "Archived" | "Customer Approval" | "Company Approval" | "Awaiting Payment" | "Pending Activation" | "Draft";
43
43
  /**
44
44
  * Returns the sum of `service` (in seconds) for the tasks attached to a
45
45
  * given routeJob. Use this to compute predicted completion time:
@@ -68,7 +68,7 @@ declare module '../../types/api/Task' {
68
68
  }
69
69
  export declare class Task {
70
70
  constructor(init?: Partial<Task>);
71
- getStatusLabel: () => "Active" | "Draft" | "Archived" | "Pending Customer Approval" | "Pending Company Approval" | "Pending Payment" | "Pending Activation";
71
+ getStatusLabel: () => "Active" | "Archived" | "Pending Activation" | "Draft" | "Pending Customer Approval" | "Pending Company Approval" | "Pending Payment";
72
72
  getUnroutedReasonLabel: () => string | null;
73
73
  isOverdue: () => boolean;
74
74
  getOverdueLabel: () => string;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "0.0.119";
1
+ export declare const AVRO_JS_VERSION = "0.0.120";
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 = '0.0.119';
3
+ export const AVRO_JS_VERSION = '0.0.120';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.0.119",
3
+ "version": "0.0.120",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",