@indigoai-us/hq-cloud 6.15.0 → 6.15.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.
- package/dist/bin/sync-mutation.d.ts +16 -0
- package/dist/bin/sync-mutation.d.ts.map +1 -0
- package/dist/bin/sync-mutation.js +60 -0
- package/dist/bin/sync-mutation.js.map +1 -0
- package/dist/bin/sync-mutation.test.d.ts +2 -0
- package/dist/bin/sync-mutation.test.d.ts.map +1 -0
- package/dist/bin/sync-mutation.test.js +165 -0
- package/dist/bin/sync-mutation.test.js.map +1 -0
- package/dist/bin/sync-runner-company.d.ts +8 -0
- package/dist/bin/sync-runner-company.d.ts.map +1 -1
- package/dist/bin/sync-runner-company.js +16 -0
- package/dist/bin/sync-runner-company.js.map +1 -1
- package/dist/bin/sync-runner-company.test.d.ts +2 -0
- package/dist/bin/sync-runner-company.test.d.ts.map +1 -0
- package/dist/bin/sync-runner-company.test.js +36 -0
- package/dist/bin/sync-runner-company.test.js.map +1 -0
- package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
- package/dist/bin/sync-runner-watch-loop.js +98 -8
- package/dist/bin/sync-runner-watch-loop.js.map +1 -1
- package/dist/bin/sync-runner.d.ts +17 -0
- package/dist/bin/sync-runner.d.ts.map +1 -1
- package/dist/bin/sync-runner.js.map +1 -1
- package/dist/bin/sync-runner.test.js +109 -0
- package/dist/bin/sync-runner.test.js.map +1 -1
- package/dist/cli/conflict-recovery.test.d.ts +2 -0
- package/dist/cli/conflict-recovery.test.d.ts.map +1 -0
- package/dist/cli/conflict-recovery.test.js +201 -0
- package/dist/cli/conflict-recovery.test.js.map +1 -0
- package/dist/cli/conflict.d.ts +60 -0
- package/dist/cli/conflict.d.ts.map +1 -1
- package/dist/cli/conflict.js +333 -0
- package/dist/cli/conflict.js.map +1 -1
- package/dist/cli/sync.d.ts +35 -0
- package/dist/cli/sync.d.ts.map +1 -1
- package/dist/cli/sync.js +100 -0
- package/dist/cli/sync.js.map +1 -1
- package/dist/cli/sync.test.js +85 -1
- package/dist/cli/sync.test.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/skill-telemetry.d.ts +6 -0
- package/dist/skill-telemetry.d.ts.map +1 -1
- package/dist/skill-telemetry.js +14 -2
- package/dist/skill-telemetry.js.map +1 -1
- package/dist/skill-telemetry.test.js +79 -0
- package/dist/skill-telemetry.test.js.map +1 -1
- package/dist/sync/candidate-uploader.d.ts +88 -0
- package/dist/sync/candidate-uploader.d.ts.map +1 -0
- package/dist/sync/candidate-uploader.js +212 -0
- package/dist/sync/candidate-uploader.js.map +1 -0
- package/dist/sync/candidate-uploader.test.d.ts +2 -0
- package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
- package/dist/sync/candidate-uploader.test.js +132 -0
- package/dist/sync/candidate-uploader.test.js.map +1 -0
- package/dist/sync/delta-client.d.ts +73 -0
- package/dist/sync/delta-client.d.ts.map +1 -0
- package/dist/sync/delta-client.js +201 -0
- package/dist/sync/delta-client.js.map +1 -0
- package/dist/sync/delta-client.test.d.ts +2 -0
- package/dist/sync/delta-client.test.d.ts.map +1 -0
- package/dist/sync/delta-client.test.js +97 -0
- package/dist/sync/delta-client.test.js.map +1 -0
- package/dist/sync/durable-apply.d.ts +76 -0
- package/dist/sync/durable-apply.d.ts.map +1 -0
- package/dist/sync/durable-apply.js +530 -0
- package/dist/sync/durable-apply.js.map +1 -0
- package/dist/sync/durable-apply.test.d.ts +2 -0
- package/dist/sync/durable-apply.test.d.ts.map +1 -0
- package/dist/sync/durable-apply.test.js +180 -0
- package/dist/sync/durable-apply.test.js.map +1 -0
- package/dist/sync/event-sync.d.ts +33 -1
- package/dist/sync/event-sync.d.ts.map +1 -1
- package/dist/sync/event-sync.js +149 -1
- package/dist/sync/event-sync.js.map +1 -1
- package/dist/sync/event-sync.test.js +142 -1
- package/dist/sync/event-sync.test.js.map +1 -1
- package/dist/sync/index.d.ts +2 -0
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/index.js +1 -0
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/multipart-uploader.d.ts +99 -0
- package/dist/sync/multipart-uploader.d.ts.map +1 -0
- package/dist/sync/multipart-uploader.js +447 -0
- package/dist/sync/multipart-uploader.js.map +1 -0
- package/dist/sync/multipart-uploader.test.d.ts +2 -0
- package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
- package/dist/sync/multipart-uploader.test.js +119 -0
- package/dist/sync/multipart-uploader.test.js.map +1 -0
- package/dist/sync/mutation-client.d.ts +85 -0
- package/dist/sync/mutation-client.d.ts.map +1 -0
- package/dist/sync/mutation-client.js +245 -0
- package/dist/sync/mutation-client.js.map +1 -0
- package/dist/sync/mutation-client.test.d.ts +2 -0
- package/dist/sync/mutation-client.test.d.ts.map +1 -0
- package/dist/sync/mutation-client.test.js +51 -0
- package/dist/sync/mutation-client.test.js.map +1 -0
- package/dist/sync/push-receiver.d.ts +45 -0
- package/dist/sync/push-receiver.d.ts.map +1 -1
- package/dist/sync/push-receiver.js +101 -0
- package/dist/sync/push-receiver.js.map +1 -1
- package/dist/sync/push-receiver.test.js +54 -2
- package/dist/sync/push-receiver.test.js.map +1 -1
- package/dist/sync/scope-inventory-client.d.ts +69 -0
- package/dist/sync/scope-inventory-client.d.ts.map +1 -0
- package/dist/sync/scope-inventory-client.js +210 -0
- package/dist/sync/scope-inventory-client.js.map +1 -0
- package/dist/sync/scope-inventory-client.test.d.ts +2 -0
- package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
- package/dist/sync/scope-inventory-client.test.js +94 -0
- package/dist/sync/scope-inventory-client.test.js.map +1 -0
- package/dist/sync/snapshot-client.d.ts +98 -0
- package/dist/sync/snapshot-client.d.ts.map +1 -0
- package/dist/sync/snapshot-client.js +402 -0
- package/dist/sync/snapshot-client.js.map +1 -0
- package/dist/sync/snapshot-client.test.d.ts +2 -0
- package/dist/sync/snapshot-client.test.d.ts.map +1 -0
- package/dist/sync/snapshot-client.test.js +169 -0
- package/dist/sync/snapshot-client.test.js.map +1 -0
- package/dist/sync/uploader-finalization.d.ts +97 -0
- package/dist/sync/uploader-finalization.d.ts.map +1 -0
- package/dist/sync/uploader-finalization.js +273 -0
- package/dist/sync/uploader-finalization.js.map +1 -0
- package/dist/sync/uploader-finalization.test.d.ts +2 -0
- package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
- package/dist/sync/uploader-finalization.test.js +92 -0
- package/dist/sync/uploader-finalization.test.js.map +1 -0
- package/dist/telemetry.d.ts +11 -1
- package/dist/telemetry.d.ts.map +1 -1
- package/dist/telemetry.js +21 -2
- package/dist/telemetry.js.map +1 -1
- package/dist/telemetry.test.js +80 -0
- package/dist/telemetry.test.js.map +1 -1
- package/package.json +6 -1
- package/.claude/policies/hq-cloud-esm-cannot-spy-fs-builtins.md +0 -30
- package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +0 -22
- package/.github/workflows/ci.yml +0 -84
- package/.github/workflows/publish.yml +0 -56
- package/.github/workflows/unreleased-commits-nag.yml +0 -256
- package/eslint.config.js +0 -67
- package/pnpm-workspace.yaml +0 -2
- package/scripts/presign-transport-e2e.mjs +0 -250
- package/scripts/vault-rebaseline.sh +0 -323
- package/scripts/vault-rescue.sh +0 -332
- package/src/active-company.test.ts +0 -188
- package/src/active-company.ts +0 -168
- package/src/agent-codex-instructions.test.ts +0 -332
- package/src/agent-codex-instructions.ts +0 -309
- package/src/auth.ts +0 -146
- package/src/backup-prune.test.ts +0 -98
- package/src/backup-prune.ts +0 -182
- package/src/bin/backup-prune-runner.ts +0 -33
- package/src/bin/rescue-runner.ts +0 -25
- package/src/bin/sync-runner-company.ts +0 -695
- package/src/bin/sync-runner-events.test.ts +0 -143
- package/src/bin/sync-runner-events.ts +0 -55
- package/src/bin/sync-runner-planning.test.ts +0 -311
- package/src/bin/sync-runner-planning.ts +0 -258
- package/src/bin/sync-runner-rollup.test.ts +0 -37
- package/src/bin/sync-runner-rollup.ts +0 -97
- package/src/bin/sync-runner-telemetry.ts +0 -15
- package/src/bin/sync-runner-watch-loop.ts +0 -1235
- package/src/bin/sync-runner-watch-routes.test.ts +0 -71
- package/src/bin/sync-runner-watch-routes.ts +0 -184
- package/src/bin/sync-runner.test.ts +0 -8767
- package/src/bin/sync-runner.ts +0 -2190
- package/src/cli/accept.ts +0 -124
- package/src/cli/conflict.ts +0 -119
- package/src/cli/doctor.test.ts +0 -581
- package/src/cli/doctor.ts +0 -642
- package/src/cli/index.ts +0 -49
- package/src/cli/invite.test.ts +0 -250
- package/src/cli/invite.ts +0 -214
- package/src/cli/promote.ts +0 -157
- package/src/cli/reindex-knowledge.test.ts +0 -307
- package/src/cli/reindex-knowledge.ts +0 -450
- package/src/cli/reindex.test.ts +0 -957
- package/src/cli/reindex.ts +0 -979
- package/src/cli/rescue-classify-ordering.test.ts +0 -548
- package/src/cli/rescue-clone-diagnostics.test.ts +0 -120
- package/src/cli/rescue-core.ts +0 -3011
- package/src/cli/rescue-drift-reconcile.test.ts +0 -179
- package/src/cli/rescue-drop-dir-symlink.test.ts +0 -224
- package/src/cli/rescue-exec-bit-preserve.test.ts +0 -187
- package/src/cli/rescue-hq-root-guard.test.ts +0 -232
- package/src/cli/rescue-journal-reconcile.test.ts +0 -215
- package/src/cli/rescue-mtime-preserve.test.ts +0 -203
- package/src/cli/rescue-settings-reconcile.test.ts +0 -637
- package/src/cli/rescue-snapshot.test.ts +0 -57
- package/src/cli/rescue-snapshot.ts +0 -51
- package/src/cli/rescue.reindex.test.ts +0 -63
- package/src/cli/rescue.test.ts +0 -131
- package/src/cli/rescue.ts +0 -182
- package/src/cli/share.test.ts +0 -7843
- package/src/cli/share.ts +0 -3663
- package/src/cli/sync-scope.test.ts +0 -652
- package/src/cli/sync.test.ts +0 -5207
- package/src/cli/sync.ts +0 -3470
- package/src/cli/tombstones.ts +0 -106
- package/src/cli/watch-event-push-conflict.test.ts +0 -234
- package/src/client-info.test.ts +0 -214
- package/src/client-info.ts +0 -121
- package/src/cognito-auth.test.ts +0 -712
- package/src/cognito-auth.ts +0 -1422
- package/src/company-resolver.test.ts +0 -618
- package/src/company-resolver.ts +0 -521
- package/src/context.test.ts +0 -583
- package/src/context.ts +0 -378
- package/src/daemon-worker.ts +0 -26
- package/src/daemon.ts +0 -99
- package/src/entity-resolver.test.ts +0 -315
- package/src/entity-resolver.ts +0 -180
- package/src/ignore.test.ts +0 -466
- package/src/ignore.ts +0 -469
- package/src/index.ts +0 -439
- package/src/journal.test.ts +0 -968
- package/src/journal.ts +0 -765
- package/src/lib/cloud-authoritative.test.ts +0 -45
- package/src/lib/cloud-authoritative.ts +0 -59
- package/src/lib/conflict-file.ts +0 -86
- package/src/lib/conflict-index.ts +0 -289
- package/src/lib/conflict.test.ts +0 -348
- package/src/lib/describe-error.test.ts +0 -100
- package/src/lib/describe-error.ts +0 -58
- package/src/lib/exit-codes.ts +0 -24
- package/src/lib/machine-id.test.ts +0 -231
- package/src/lib/machine-id.ts +0 -175
- package/src/lib/net-errors.test.ts +0 -65
- package/src/lib/net-errors.ts +0 -86
- package/src/lib/readlink-safe.test.ts +0 -43
- package/src/lib/readlink-safe.ts +0 -29
- package/src/local-path-codec.test.ts +0 -138
- package/src/local-path-codec.ts +0 -161
- package/src/machine-auth.test.ts +0 -1323
- package/src/manifest-reconcile.test.ts +0 -1123
- package/src/manifest-reconcile.ts +0 -518
- package/src/object-io.test.ts +0 -1221
- package/src/object-io.ts +0 -1306
- package/src/operation-lock.test.ts +0 -484
- package/src/operation-lock.ts +0 -680
- package/src/outcome-telemetry.test.ts +0 -498
- package/src/outcome-telemetry.ts +0 -639
- package/src/personal-vault-exclusions.test.ts +0 -308
- package/src/personal-vault-exclusions.ts +0 -354
- package/src/personal-vault.test.ts +0 -756
- package/src/personal-vault.ts +0 -496
- package/src/prefix-coalesce.test.ts +0 -240
- package/src/prefix-coalesce.ts +0 -273
- package/src/public-surface.test.ts +0 -117
- package/src/qmd-reindex.test.ts +0 -877
- package/src/qmd-reindex.ts +0 -842
- package/src/read-only-state-dir.test.ts +0 -188
- package/src/remote-pull.test.ts +0 -1130
- package/src/remote-pull.ts +0 -618
- package/src/s3.symlink-materialize.test.ts +0 -492
- package/src/s3.test.ts +0 -1789
- package/src/s3.ts +0 -1532
- package/src/schemas/signal-types.test.ts +0 -82
- package/src/schemas/signal-types.ts +0 -38
- package/src/schemas/source-channels.test.ts +0 -82
- package/src/schemas/source-channels.ts +0 -53
- package/src/scope-shrink.test.ts +0 -633
- package/src/scope-shrink.ts +0 -481
- package/src/signals/get.test.ts +0 -310
- package/src/signals/get.ts +0 -75
- package/src/signals/internals.ts +0 -195
- package/src/signals/list.test.ts +0 -420
- package/src/signals/list.ts +0 -79
- package/src/signals/parse.ts +0 -8
- package/src/signals/types.ts +0 -91
- package/src/skill-telemetry.test.ts +0 -1825
- package/src/skill-telemetry.ts +0 -1439
- package/src/sources/get.test.ts +0 -293
- package/src/sources/get.ts +0 -66
- package/src/sources/internals.ts +0 -198
- package/src/sources/list.test.ts +0 -402
- package/src/sources/list.ts +0 -84
- package/src/sources/parse.ts +0 -43
- package/src/sources/types.ts +0 -84
- package/src/sync/event-sync.test.ts +0 -594
- package/src/sync/event-sync.ts +0 -545
- package/src/sync/feature-flags.test.ts +0 -378
- package/src/sync/feature-flags.ts +0 -62
- package/src/sync/index.ts +0 -76
- package/src/sync/lease-client.test.ts +0 -128
- package/src/sync/lease-client.ts +0 -207
- package/src/sync/logger.test.ts +0 -242
- package/src/sync/logger.ts +0 -79
- package/src/sync/metrics.test.ts +0 -462
- package/src/sync/metrics.ts +0 -213
- package/src/sync/pull-scope.ts +0 -265
- package/src/sync/push-event.test.ts +0 -266
- package/src/sync/push-event.ts +0 -224
- package/src/sync/push-receiver.test.ts +0 -566
- package/src/sync/push-receiver.ts +0 -1048
- package/src/sync/push-transport.ts +0 -231
- package/src/sync/realtime-rollout.test.ts +0 -86
- package/src/sync/realtime-rollout.ts +0 -262
- package/src/sync/state-store.test.ts +0 -194
- package/src/sync/state-store.ts +0 -727
- package/src/sync-core.ts +0 -58
- package/src/sync-progress.test.ts +0 -94
- package/src/sync-progress.ts +0 -140
- package/src/telemetry-events.test.ts +0 -88
- package/src/telemetry-events.ts +0 -205
- package/src/telemetry.test.ts +0 -1280
- package/src/telemetry.ts +0 -1109
- package/src/types.ts +0 -314
- package/src/vault-client.test.ts +0 -1380
- package/src/vault-client.ts +0 -1694
- package/src/version.ts +0 -24
- package/src/watch-roots.test.ts +0 -278
- package/src/watch-roots.ts +0 -162
- package/src/watcher-event-gate.test.ts +0 -212
- package/src/watcher.test.ts +0 -1079
- package/src/watcher.ts +0 -1741
- package/test/e2e/sync/cross-tenant-isolation.test.ts +0 -630
- package/test/e2e/sync/skill-telemetry-oversized-transcript.test.ts +0 -124
- package/test/e2e/sync/transient-company-leg.test.ts +0 -384
- package/test/e2e/sync/windows-unreadable-link-leg.test.ts +0 -191
- package/test/e2e/watcher-real-chokidar.test.ts +0 -165
- package/test/e2e/watcher-recursive-backend.test.ts +0 -181
- package/test/e2e/watcher-scoped-coverage.test.ts +0 -381
- package/test/invite-flow.integration.test.ts +0 -244
- package/test/joiner-manifest-reconcile.integration.test.ts +0 -322
- package/test/share-sync.integration.test.ts +0 -213
- package/tsconfig.json +0 -19
- package/vitest.config.ts +0 -22
|
@@ -1,231 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* PushTransport — outbound shipping seam for the watcher daemon.
|
|
3
|
-
*
|
|
4
|
-
* The daemon wires file-watcher events into a transport that ships each
|
|
5
|
-
* PushEvent to the cloud. Defining the interface here lets the daemon ship
|
|
6
|
-
* with a swappable boundary — tests inject a fake, a later story swaps in a
|
|
7
|
-
* concrete WebSocket/HTTP implementation, and the daemon entry point never
|
|
8
|
-
* changes.
|
|
9
|
-
*
|
|
10
|
-
* Lifecycle
|
|
11
|
-
* ─────────
|
|
12
|
-
* - `start()` is awaited BEFORE the watcher is started. It's the place
|
|
13
|
-
* to open sockets, refresh tokens, etc.
|
|
14
|
-
* - `publish(event)` is called for every coalesced PushEvent the watcher
|
|
15
|
-
* emits. Implementations decide whether to buffer, batch, or send
|
|
16
|
-
* inline; the daemon awaits the returned promise so back-pressure can
|
|
17
|
-
* be honored.
|
|
18
|
-
* - `dispose()` is awaited DURING shutdown, AFTER the watcher has been
|
|
19
|
-
* torn down. Implementations should drain in-flight publishes (with
|
|
20
|
-
* their own internal timeout) and close any sockets.
|
|
21
|
-
* - `connected` is a passive boolean used by the health endpoint. It MAY
|
|
22
|
-
* flap during reconnect attempts — that's fine; consumers treat it as
|
|
23
|
-
* advisory, not a contract.
|
|
24
|
-
*
|
|
25
|
-
* The `NoopPushTransport` shipped here is the default when no transport
|
|
26
|
-
* is wired in: it counts publishes (so unit tests can assert delivery)
|
|
27
|
-
* and logs nothing — observers should rely on the watcher's `onEvent`
|
|
28
|
-
* counter on the daemon side, not the transport's internals.
|
|
29
|
-
*
|
|
30
|
-
* Ported from indigoai-us/hq-pro PR #112 (src/sync/push-transport.ts) into
|
|
31
|
-
* @indigoai-us/hq-cloud (Path B) per project event-driven-sync-menubar US-007.
|
|
32
|
-
*/
|
|
33
|
-
|
|
34
|
-
import { encodePushEvent, type PushEvent } from "./push-event.js";
|
|
35
|
-
|
|
36
|
-
export interface PushTransport {
|
|
37
|
-
/** Open sockets, refresh tokens. Awaited before the watcher starts. */
|
|
38
|
-
start(): Promise<void>;
|
|
39
|
-
/** Ship one coalesced PushEvent. Awaited per event for back-pressure. */
|
|
40
|
-
publish(event: PushEvent): Promise<void>;
|
|
41
|
-
/** Drain + close. Awaited during daemon shutdown after watcher.dispose. */
|
|
42
|
-
dispose(): Promise<void>;
|
|
43
|
-
/** Advisory: is the transport currently believed to be connected? */
|
|
44
|
-
readonly connected: boolean;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Default `PushTransport` used until a real implementation lands.
|
|
49
|
-
*
|
|
50
|
-
* Behavior:
|
|
51
|
-
* - `start()` flips `connected` to true.
|
|
52
|
-
* - `publish()` increments a counter (visible via `publishedCount`).
|
|
53
|
-
* - `dispose()` flips `connected` back to false.
|
|
54
|
-
*
|
|
55
|
-
* Deliberately silent: when the daemon runs with this default, the
|
|
56
|
-
* watcher's per-event log line (emitted by the daemon itself, not the
|
|
57
|
-
* transport) is the only observability. That keeps the noop from drowning
|
|
58
|
-
* the log when high-rate writes hit a dev machine.
|
|
59
|
-
*/
|
|
60
|
-
export class NoopPushTransport implements PushTransport {
|
|
61
|
-
private _connected = false;
|
|
62
|
-
private _count = 0;
|
|
63
|
-
|
|
64
|
-
get connected(): boolean {
|
|
65
|
-
return this._connected;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Test/observability hook: how many events have been published. */
|
|
69
|
-
get publishedCount(): number {
|
|
70
|
-
return this._count;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
async start(): Promise<void> {
|
|
74
|
-
this._connected = true;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
async publish(_event: PushEvent): Promise<void> {
|
|
78
|
-
this._count += 1;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
async dispose(): Promise<void> {
|
|
82
|
-
this._connected = false;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// ─── HttpPushTransport ───────────────────────────────────────────────────────
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Minimal fetch surface so tests can inject a mocked `fetch` without pulling
|
|
90
|
-
* in DOM/undici types. Matches the subset of the global `fetch` we use.
|
|
91
|
-
*/
|
|
92
|
-
export type FetchLike = (
|
|
93
|
-
input: string,
|
|
94
|
-
init?: {
|
|
95
|
-
method?: string;
|
|
96
|
-
headers?: Record<string, string>;
|
|
97
|
-
body?: string;
|
|
98
|
-
signal?: AbortSignal;
|
|
99
|
-
},
|
|
100
|
-
) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Async getter for the current Cognito access token. Long-running daemons MUST
|
|
104
|
-
* pass a getter (not a captured string) so each publish resolves the freshest
|
|
105
|
-
* token — mirrors {@link VaultServiceConfig.authToken} semantics in types.ts.
|
|
106
|
-
* A static string is also accepted for short-lived tools and tests.
|
|
107
|
-
*/
|
|
108
|
-
export type AuthTokenSource = string | (() => string | Promise<string>);
|
|
109
|
-
|
|
110
|
-
export interface HttpPushTransportOptions {
|
|
111
|
-
/**
|
|
112
|
-
* Vault API base URL (e.g. `https://vault-api.example.com`). The same
|
|
113
|
-
* `apiUrl` the runner already resolves for VaultClient. Trailing slashes
|
|
114
|
-
* are stripped. Required — config/env-driven, no hard-coded default.
|
|
115
|
-
*/
|
|
116
|
-
apiUrl: string;
|
|
117
|
-
/**
|
|
118
|
-
* Endpoint path the PushEvent is POSTed to. Defaults to `/sync/push`
|
|
119
|
-
* (matches the deployed hq-pro endpoint from US-006). Override for testing
|
|
120
|
-
* or future endpoint moves.
|
|
121
|
-
*/
|
|
122
|
-
pushPath?: string;
|
|
123
|
-
/** Cognito JWT — static string OR async getter. See {@link AuthTokenSource}. */
|
|
124
|
-
authToken: AuthTokenSource;
|
|
125
|
-
/**
|
|
126
|
-
* Optional extra headers (e.g. client identification) merged onto every
|
|
127
|
-
* request. Authorization + Content-Type are always set by the transport.
|
|
128
|
-
*/
|
|
129
|
-
headers?: Record<string, string>;
|
|
130
|
-
/**
|
|
131
|
-
* Per-request timeout in milliseconds. Default 10_000. On timeout the
|
|
132
|
-
* publish rejects — the daemon treats a rejected publish as a transient
|
|
133
|
-
* miss (the cadence poll still covers it) and MUST NOT crash.
|
|
134
|
-
*/
|
|
135
|
-
timeoutMs?: number;
|
|
136
|
-
/** Injectable fetch (tests). Defaults to the global `fetch`. */
|
|
137
|
-
fetchImpl?: FetchLike;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Real client `PushTransport` that POSTs encoded PushEvents to the deployed
|
|
142
|
-
* `/sync/push` endpoint, authenticating with the menubar's existing Cognito
|
|
143
|
-
* bearer token — the same auth path VaultClient uses (Authorization: Bearer
|
|
144
|
-
* <accessToken>, token resolved per-request via the supplied getter so it
|
|
145
|
-
* self-heals across refreshes).
|
|
146
|
-
*
|
|
147
|
-
* Failure posture
|
|
148
|
-
* ───────────────
|
|
149
|
-
* `publish()` rejects on a network error, a non-2xx response, or a timeout.
|
|
150
|
-
* The DAEMON is responsible for not letting that rejection crash it — the
|
|
151
|
-
* watcher's emit path catches publish errors and logs them; the periodic
|
|
152
|
-
* cadence poll remains the safety net that eventually ships the change. This
|
|
153
|
-
* transport never swallows errors itself, so callers retain full visibility.
|
|
154
|
-
*
|
|
155
|
-
* `connected` flips true on `start()` and false on `dispose()`. It is purely
|
|
156
|
-
* advisory (HTTP is connectionless); the health endpoint may read it but it
|
|
157
|
-
* carries no delivery guarantee.
|
|
158
|
-
*/
|
|
159
|
-
export class HttpPushTransport implements PushTransport {
|
|
160
|
-
private readonly apiUrl: string;
|
|
161
|
-
private readonly pushPath: string;
|
|
162
|
-
private readonly getAuthToken: () => Promise<string>;
|
|
163
|
-
private readonly extraHeaders: Record<string, string>;
|
|
164
|
-
private readonly timeoutMs: number;
|
|
165
|
-
private readonly fetchImpl: FetchLike;
|
|
166
|
-
private _connected = false;
|
|
167
|
-
|
|
168
|
-
constructor(opts: HttpPushTransportOptions) {
|
|
169
|
-
if (!opts.apiUrl || opts.apiUrl.trim() === "") {
|
|
170
|
-
throw new Error("HttpPushTransport: apiUrl is required");
|
|
171
|
-
}
|
|
172
|
-
this.apiUrl = opts.apiUrl.replace(/\/+$/, "");
|
|
173
|
-
const path = opts.pushPath ?? "/sync/push";
|
|
174
|
-
this.pushPath = path.startsWith("/") ? path : `/${path}`;
|
|
175
|
-
const tok = opts.authToken;
|
|
176
|
-
// Normalize string|getter into a single async getter (mirrors VaultClient).
|
|
177
|
-
this.getAuthToken =
|
|
178
|
-
typeof tok === "function" ? async () => tok() : async () => tok;
|
|
179
|
-
this.extraHeaders = opts.headers ?? {};
|
|
180
|
-
this.timeoutMs = opts.timeoutMs ?? 10_000;
|
|
181
|
-
// Bind so a destructured global fetch keeps its receiver.
|
|
182
|
-
this.fetchImpl =
|
|
183
|
-
opts.fetchImpl ??
|
|
184
|
-
((input, init) => (globalThis.fetch as unknown as FetchLike)(input, init));
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
get connected(): boolean {
|
|
188
|
-
return this._connected;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
async start(): Promise<void> {
|
|
192
|
-
this._connected = true;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
async publish(event: PushEvent): Promise<void> {
|
|
196
|
-
// Validate-on-encode (US-007 contract) — a malformed event throws a typed
|
|
197
|
-
// PushEventDecodeError BEFORE we hit the network.
|
|
198
|
-
const body = encodePushEvent(event);
|
|
199
|
-
const token = await this.getAuthToken();
|
|
200
|
-
|
|
201
|
-
const controller = new AbortController();
|
|
202
|
-
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
203
|
-
try {
|
|
204
|
-
const res = await this.fetchImpl(`${this.apiUrl}${this.pushPath}`, {
|
|
205
|
-
method: "POST",
|
|
206
|
-
headers: {
|
|
207
|
-
...this.extraHeaders,
|
|
208
|
-
Authorization: `Bearer ${token}`,
|
|
209
|
-
"Content-Type": "application/json",
|
|
210
|
-
Accept: "application/json",
|
|
211
|
-
},
|
|
212
|
-
body,
|
|
213
|
-
signal: controller.signal,
|
|
214
|
-
});
|
|
215
|
-
if (!res.ok) {
|
|
216
|
-
const text = await res.text().catch(() => "");
|
|
217
|
-
throw new Error(
|
|
218
|
-
`HttpPushTransport: POST ${this.pushPath} failed (${res.status})${
|
|
219
|
-
text ? `: ${text}` : ""
|
|
220
|
-
}`,
|
|
221
|
-
);
|
|
222
|
-
}
|
|
223
|
-
} finally {
|
|
224
|
-
clearTimeout(timer);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
async dispose(): Promise<void> {
|
|
229
|
-
this._connected = false;
|
|
230
|
-
}
|
|
231
|
-
}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from "vitest";
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
MAX_REALTIME_ROLLOUT_CACHE_MS,
|
|
5
|
-
RealtimeRolloutClient,
|
|
6
|
-
parseRealtimeInventory,
|
|
7
|
-
type RealtimeCapabilityVector,
|
|
8
|
-
} from "./realtime-rollout.js";
|
|
9
|
-
|
|
10
|
-
const capability: RealtimeCapabilityVector = {
|
|
11
|
-
hqCloud: "6.14.49",
|
|
12
|
-
hqDesktop: "none",
|
|
13
|
-
protocol: 2,
|
|
14
|
-
journal: 3,
|
|
15
|
-
durableApply: 1,
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
function jsonResponse(body: unknown, status = 200) {
|
|
19
|
-
return { ok: status >= 200 && status < 300, status, text: async () => JSON.stringify(body) };
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function request(overrides: Partial<Parameters<RealtimeRolloutClient["inventory"]>[0]> = {}) {
|
|
23
|
-
return {
|
|
24
|
-
bearer: "token-a",
|
|
25
|
-
deviceId: "machine_a",
|
|
26
|
-
capabilityVector: capability,
|
|
27
|
-
configurationFingerprint: "config-a",
|
|
28
|
-
scopeFingerprint: "personal:prs_1",
|
|
29
|
-
...overrides,
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const readyInventory = {
|
|
34
|
-
scopes: [{ scopeUid: "prs_1", scopeHandle: "handle_1", scopeRevision: "rev_1", state: "v2-ready", cursor: "cursor_1" }],
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
describe("RealtimeRolloutClient", () => {
|
|
38
|
-
it("never reuses a cached positive across bearer, configuration, or scope changes", async () => {
|
|
39
|
-
let now = 1_000;
|
|
40
|
-
const requests: Array<{ headers?: Record<string, string> }> = [];
|
|
41
|
-
const fetchImpl = async (_url: string, init?: { headers?: Record<string, string> }) => {
|
|
42
|
-
requests.push({ headers: init?.headers });
|
|
43
|
-
return jsonResponse(readyInventory);
|
|
44
|
-
};
|
|
45
|
-
const client = new RealtimeRolloutClient({ apiUrl: "https://api.example/", fetchImpl, now: () => now });
|
|
46
|
-
|
|
47
|
-
await client.inventory(request());
|
|
48
|
-
await client.inventory(request());
|
|
49
|
-
await client.inventory(request({ bearer: "token-b" }));
|
|
50
|
-
await client.inventory(request({ configurationFingerprint: "config-b" }));
|
|
51
|
-
await client.inventory(request({ scopeFingerprint: "company:cmp_1" }));
|
|
52
|
-
now += MAX_REALTIME_ROLLOUT_CACHE_MS;
|
|
53
|
-
await client.inventory(request());
|
|
54
|
-
|
|
55
|
-
expect(requests).toHaveLength(5);
|
|
56
|
-
expect(requests[0]?.headers).toMatchObject({
|
|
57
|
-
Authorization: "Bearer token-a",
|
|
58
|
-
"X-HQ-Sync-Contract": "2",
|
|
59
|
-
"X-HQ-Device-ID": "machine_a",
|
|
60
|
-
"X-HQ-Cloud-Version": "6.14.49",
|
|
61
|
-
"X-HQ-Desktop-Version": "none",
|
|
62
|
-
"X-HQ-Sync-Journal": "3",
|
|
63
|
-
"X-HQ-Sync-Durable-Apply": "1",
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
it("fails closed for malformed or non-explicit legacy inventory", () => {
|
|
68
|
-
expect(() => parseRealtimeInventory({ scopes: [{ scopeUid: "prs_1", scopeHandle: "h", scopeRevision: "r", state: "legacy", v1Allowed: false }] })).toThrow("legacy must explicitly allow v1");
|
|
69
|
-
expect(() => parseRealtimeInventory({ scopes: [{ scopeUid: "prs_1", scopeHandle: "h", scopeRevision: "r", state: "v2-ready", cursor: "c", surprise: true }] })).toThrow("unknown field");
|
|
70
|
-
expect(() => parseRealtimeInventory({ scopes: [{ scopeUid: "prs_1", scopeHandle: "h", scopeRevision: "r", state: "unknown" }] })).toThrow("unsupported scope state");
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
it("rejects cache durations greater than the protocol maximum", () => {
|
|
74
|
-
expect(() => new RealtimeRolloutClient({ apiUrl: "https://api.example", maxCacheAgeMs: MAX_REALTIME_ROLLOUT_CACHE_MS + 1 })).toThrow("maxCacheAgeMs");
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
it("honors transitional retryAfterMs instead of holding a stale negative state", async () => {
|
|
78
|
-
const fetchImpl = vi.fn(async () => jsonResponse({ scopes: [
|
|
79
|
-
{ scopeUid: "prs_1", scopeHandle: "handle_1", scopeRevision: "rev_1", state: "restoring", retryAfterMs: 0 },
|
|
80
|
-
] }));
|
|
81
|
-
const client = new RealtimeRolloutClient({ apiUrl: "https://api.example", fetchImpl });
|
|
82
|
-
await client.inventory(request());
|
|
83
|
-
await client.inventory(request());
|
|
84
|
-
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
85
|
-
});
|
|
86
|
-
});
|
|
@@ -1,262 +0,0 @@
|
|
|
1
|
-
import type { AuthTokenSource, FetchLike } from "./push-transport.js";
|
|
2
|
-
|
|
3
|
-
export const REALTIME_SYNC_CONTRACT_VERSION = 2 as const;
|
|
4
|
-
export const MAX_REALTIME_ROLLOUT_CACHE_MS = 30_000;
|
|
5
|
-
export const DEFAULT_REALTIME_AUTHORIZATION_TIMEOUT_MS = 15_000;
|
|
6
|
-
|
|
7
|
-
export interface RealtimeCapabilityVector {
|
|
8
|
-
hqCloud: string;
|
|
9
|
-
hqDesktop: string | "none";
|
|
10
|
-
protocol: 2;
|
|
11
|
-
journal: number;
|
|
12
|
-
durableApply: number;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export type RealtimeInventoryState =
|
|
16
|
-
| { state: "legacy"; v1Allowed: true }
|
|
17
|
-
| { state: "qualifying" | "frozen" | "seeding"; retryAfterMs: number }
|
|
18
|
-
| { state: "bootstrap-required"; snapshotDescriptorId: string }
|
|
19
|
-
| { state: "v2-ready"; cursor: string }
|
|
20
|
-
| { state: "paused"; reasonCode: string }
|
|
21
|
-
| { state: "reset-required"; resetId: string; snapshotDescriptorId: string }
|
|
22
|
-
| { state: "revoked"; localMaterialPolicy: string }
|
|
23
|
-
| { state: "restoring"; retryAfterMs: number }
|
|
24
|
-
| { state: "blocked"; reasonCode: string };
|
|
25
|
-
|
|
26
|
-
export type RealtimeInventoryGrant = RealtimeInventoryState & {
|
|
27
|
-
scopeUid: string;
|
|
28
|
-
scopeHandle: string;
|
|
29
|
-
scopeRevision: string;
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
export interface RealtimeInventory {
|
|
33
|
-
scopes: readonly RealtimeInventoryGrant[];
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface RealtimeInventoryRequest {
|
|
37
|
-
/** A changed token must never reuse a positive inventory result. */
|
|
38
|
-
bearer: string;
|
|
39
|
-
deviceId: string;
|
|
40
|
-
capabilityVector: RealtimeCapabilityVector;
|
|
41
|
-
/** Identifies the active client configuration/capability selection. */
|
|
42
|
-
configurationFingerprint: string;
|
|
43
|
-
/** Identifies the scopes this guarded pass is about to touch. */
|
|
44
|
-
scopeFingerprint: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export interface RealtimeRolloutClientOptions {
|
|
48
|
-
apiUrl: string;
|
|
49
|
-
fetchImpl?: FetchLike;
|
|
50
|
-
now?: () => number;
|
|
51
|
-
maxCacheAgeMs?: number;
|
|
52
|
-
authorizationTimeoutMs?: number;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
interface CachedInventory {
|
|
56
|
-
expiresAt: number;
|
|
57
|
-
value: RealtimeInventory;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
61
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function nonEmpty(value: unknown, field: string): string {
|
|
65
|
-
if (typeof value !== "string" || value.trim() === "") {
|
|
66
|
-
throw new Error(`realtime inventory: ${field} must be a non-empty string`);
|
|
67
|
-
}
|
|
68
|
-
return value;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function exactKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {
|
|
72
|
-
if (Object.keys(value).some((key) => !allowed.includes(key))) {
|
|
73
|
-
throw new Error(`realtime inventory: ${label} contains an unknown field`);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function parseState(value: unknown): RealtimeInventoryState {
|
|
78
|
-
if (!isRecord(value) || typeof value.state !== "string") {
|
|
79
|
-
throw new Error("realtime inventory: scope state is invalid");
|
|
80
|
-
}
|
|
81
|
-
switch (value.state) {
|
|
82
|
-
case "legacy":
|
|
83
|
-
exactKeys(value, ["state", "v1Allowed"], "legacy state");
|
|
84
|
-
if (value.v1Allowed !== true) throw new Error("realtime inventory: legacy must explicitly allow v1");
|
|
85
|
-
return { state: "legacy", v1Allowed: true };
|
|
86
|
-
case "qualifying":
|
|
87
|
-
case "frozen":
|
|
88
|
-
case "seeding":
|
|
89
|
-
case "restoring":
|
|
90
|
-
exactKeys(value, ["state", "retryAfterMs"], `${value.state} state`);
|
|
91
|
-
if (
|
|
92
|
-
typeof value.retryAfterMs !== "number" ||
|
|
93
|
-
!Number.isSafeInteger(value.retryAfterMs) ||
|
|
94
|
-
value.retryAfterMs < 0
|
|
95
|
-
) {
|
|
96
|
-
throw new Error(`realtime inventory: ${value.state} retryAfterMs is invalid`);
|
|
97
|
-
}
|
|
98
|
-
return { state: value.state, retryAfterMs: value.retryAfterMs };
|
|
99
|
-
case "bootstrap-required":
|
|
100
|
-
exactKeys(value, ["state", "snapshotDescriptorId"], "bootstrap-required state");
|
|
101
|
-
return { state: value.state, snapshotDescriptorId: nonEmpty(value.snapshotDescriptorId, "snapshotDescriptorId") };
|
|
102
|
-
case "v2-ready":
|
|
103
|
-
exactKeys(value, ["state", "cursor"], "v2-ready state");
|
|
104
|
-
return { state: value.state, cursor: nonEmpty(value.cursor, "cursor") };
|
|
105
|
-
case "paused":
|
|
106
|
-
case "blocked":
|
|
107
|
-
exactKeys(value, ["state", "reasonCode"], `${value.state} state`);
|
|
108
|
-
return { state: value.state, reasonCode: nonEmpty(value.reasonCode, "reasonCode") };
|
|
109
|
-
case "reset-required":
|
|
110
|
-
exactKeys(value, ["state", "resetId", "snapshotDescriptorId"], "reset-required state");
|
|
111
|
-
return {
|
|
112
|
-
state: value.state,
|
|
113
|
-
resetId: nonEmpty(value.resetId, "resetId"),
|
|
114
|
-
snapshotDescriptorId: nonEmpty(value.snapshotDescriptorId, "snapshotDescriptorId"),
|
|
115
|
-
};
|
|
116
|
-
case "revoked":
|
|
117
|
-
exactKeys(value, ["state", "localMaterialPolicy"], "revoked state");
|
|
118
|
-
return { state: value.state, localMaterialPolicy: nonEmpty(value.localMaterialPolicy, "localMaterialPolicy") };
|
|
119
|
-
default:
|
|
120
|
-
throw new Error(`realtime inventory: unsupported scope state ${value.state}`);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
export function parseRealtimeInventory(value: unknown): RealtimeInventory {
|
|
125
|
-
if (!isRecord(value)) throw new Error("realtime inventory: response is not an object");
|
|
126
|
-
exactKeys(value, ["scopes"], "response");
|
|
127
|
-
if (!Array.isArray(value.scopes)) throw new Error("realtime inventory: scopes is not an array");
|
|
128
|
-
const scopeHandles = new Set<string>();
|
|
129
|
-
const scopes = value.scopes.map((entry): RealtimeInventoryGrant => {
|
|
130
|
-
if (!isRecord(entry)) throw new Error("realtime inventory: scope grant is not an object");
|
|
131
|
-
const { scopeUid, scopeHandle, scopeRevision, ...state } = entry;
|
|
132
|
-
const parsedState = parseState(state);
|
|
133
|
-
const grant = {
|
|
134
|
-
scopeUid: nonEmpty(scopeUid, "scopeUid"),
|
|
135
|
-
scopeHandle: nonEmpty(scopeHandle, "scopeHandle"),
|
|
136
|
-
scopeRevision: nonEmpty(scopeRevision, "scopeRevision"),
|
|
137
|
-
...parsedState,
|
|
138
|
-
} as RealtimeInventoryGrant;
|
|
139
|
-
if (scopeHandles.has(grant.scopeHandle)) {
|
|
140
|
-
throw new Error("realtime inventory: duplicate scopeHandle");
|
|
141
|
-
}
|
|
142
|
-
scopeHandles.add(grant.scopeHandle);
|
|
143
|
-
return grant;
|
|
144
|
-
});
|
|
145
|
-
return { scopes };
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function inventoryCacheKey(request: RealtimeInventoryRequest): string {
|
|
149
|
-
const capability = request.capabilityVector;
|
|
150
|
-
return JSON.stringify([
|
|
151
|
-
request.bearer,
|
|
152
|
-
request.deviceId,
|
|
153
|
-
request.configurationFingerprint,
|
|
154
|
-
request.scopeFingerprint,
|
|
155
|
-
capability.hqCloud,
|
|
156
|
-
capability.hqDesktop,
|
|
157
|
-
capability.protocol,
|
|
158
|
-
capability.journal,
|
|
159
|
-
capability.durableApply,
|
|
160
|
-
]);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function cacheAgeForInventory(inventory: RealtimeInventory, maximum: number): number {
|
|
164
|
-
return inventory.scopes.reduce((age, grant) => {
|
|
165
|
-
if (
|
|
166
|
-
grant.state === "qualifying" ||
|
|
167
|
-
grant.state === "frozen" ||
|
|
168
|
-
grant.state === "seeding" ||
|
|
169
|
-
grant.state === "restoring"
|
|
170
|
-
) return Math.min(age, grant.retryAfterMs);
|
|
171
|
-
if (grant.state === "legacy" || grant.state === "v2-ready") return age;
|
|
172
|
-
return 0;
|
|
173
|
-
}, maximum);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Strict client for the authenticated inventory endpoint. The cache is keyed
|
|
178
|
-
* by bearer, device, capability/configuration, and the scope selection. A
|
|
179
|
-
* positive inventory record is only an optimization: callers must still mint
|
|
180
|
-
* a new lease before I/O, where the server strongly rechecks all authority.
|
|
181
|
-
*/
|
|
182
|
-
export class RealtimeRolloutClient {
|
|
183
|
-
private readonly apiUrl: string;
|
|
184
|
-
private readonly fetchImpl: FetchLike;
|
|
185
|
-
private readonly now: () => number;
|
|
186
|
-
private readonly maxCacheAgeMs: number;
|
|
187
|
-
private readonly authorizationTimeoutMs: number;
|
|
188
|
-
private readonly cache = new Map<string, CachedInventory>();
|
|
189
|
-
|
|
190
|
-
constructor(options: RealtimeRolloutClientOptions) {
|
|
191
|
-
if (!options.apiUrl.trim()) throw new Error("realtime inventory: apiUrl is required");
|
|
192
|
-
this.apiUrl = options.apiUrl.replace(/\/+$/, "");
|
|
193
|
-
this.fetchImpl = options.fetchImpl ?? ((input, init) => (globalThis.fetch as unknown as FetchLike)(input, init));
|
|
194
|
-
this.now = options.now ?? Date.now;
|
|
195
|
-
this.maxCacheAgeMs = options.maxCacheAgeMs ?? MAX_REALTIME_ROLLOUT_CACHE_MS;
|
|
196
|
-
if (!Number.isSafeInteger(this.maxCacheAgeMs) || this.maxCacheAgeMs < 0 || this.maxCacheAgeMs > MAX_REALTIME_ROLLOUT_CACHE_MS) {
|
|
197
|
-
throw new Error(`realtime inventory: maxCacheAgeMs must be within 0-${MAX_REALTIME_ROLLOUT_CACHE_MS}`);
|
|
198
|
-
}
|
|
199
|
-
this.authorizationTimeoutMs = options.authorizationTimeoutMs ?? DEFAULT_REALTIME_AUTHORIZATION_TIMEOUT_MS;
|
|
200
|
-
if (!Number.isSafeInteger(this.authorizationTimeoutMs) || this.authorizationTimeoutMs <= 0) {
|
|
201
|
-
throw new Error("realtime inventory: authorizationTimeoutMs must be a positive integer");
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
invalidate(): void {
|
|
206
|
-
this.cache.clear();
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
async inventory(request: RealtimeInventoryRequest): Promise<RealtimeInventory> {
|
|
210
|
-
const now = this.now();
|
|
211
|
-
for (const [key, entry] of this.cache) {
|
|
212
|
-
if (entry.expiresAt <= now) this.cache.delete(key);
|
|
213
|
-
}
|
|
214
|
-
const cacheKey = inventoryCacheKey(request);
|
|
215
|
-
const cached = this.cache.get(cacheKey);
|
|
216
|
-
if (cached && now < cached.expiresAt) return cached.value;
|
|
217
|
-
|
|
218
|
-
const controller = new AbortController();
|
|
219
|
-
const timeout = setTimeout(() => controller.abort(), this.authorizationTimeoutMs);
|
|
220
|
-
let response: Awaited<ReturnType<FetchLike>>;
|
|
221
|
-
try {
|
|
222
|
-
response = await this.fetchImpl(`${this.apiUrl}/v2/sync/scopes`, {
|
|
223
|
-
method: "GET",
|
|
224
|
-
headers: {
|
|
225
|
-
Authorization: `Bearer ${request.bearer}`,
|
|
226
|
-
Accept: "application/json",
|
|
227
|
-
"X-HQ-Sync-Contract": String(REALTIME_SYNC_CONTRACT_VERSION),
|
|
228
|
-
"X-HQ-Device-ID": request.deviceId,
|
|
229
|
-
"X-HQ-Cloud-Version": request.capabilityVector.hqCloud,
|
|
230
|
-
"X-HQ-Desktop-Version": request.capabilityVector.hqDesktop,
|
|
231
|
-
"X-HQ-Sync-Journal": String(request.capabilityVector.journal),
|
|
232
|
-
"X-HQ-Sync-Durable-Apply": String(request.capabilityVector.durableApply),
|
|
233
|
-
},
|
|
234
|
-
signal: controller.signal,
|
|
235
|
-
});
|
|
236
|
-
} catch (error) {
|
|
237
|
-
throw new Error(`realtime inventory: GET /v2/sync/scopes failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
238
|
-
} finally {
|
|
239
|
-
clearTimeout(timeout);
|
|
240
|
-
}
|
|
241
|
-
const text = await response.text().catch((error: unknown) => {
|
|
242
|
-
throw new Error(`realtime inventory: unable to read response: ${error instanceof Error ? error.message : String(error)}`);
|
|
243
|
-
});
|
|
244
|
-
if (!response.ok) throw new Error(`realtime inventory: GET /v2/sync/scopes failed (${response.status}): ${text.slice(0, 300)}`);
|
|
245
|
-
let parsed: unknown;
|
|
246
|
-
try {
|
|
247
|
-
parsed = JSON.parse(text);
|
|
248
|
-
} catch (error) {
|
|
249
|
-
throw new Error(`realtime inventory: response is not JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
250
|
-
}
|
|
251
|
-
const inventory = parseRealtimeInventory(parsed);
|
|
252
|
-
const cacheAgeMs = cacheAgeForInventory(inventory, this.maxCacheAgeMs);
|
|
253
|
-
if (cacheAgeMs > 0) this.cache.set(cacheKey, { value: inventory, expiresAt: this.now() + cacheAgeMs });
|
|
254
|
-
return inventory;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
export async function resolveRealtimeBearer(source: AuthTokenSource): Promise<string> {
|
|
259
|
-
const bearer = typeof source === "function" ? await source() : source;
|
|
260
|
-
if (typeof bearer !== "string" || bearer.trim() === "") throw new Error("realtime authorization: access token is empty");
|
|
261
|
-
return bearer;
|
|
262
|
-
}
|