@tempo-kit/plugin-ntp 0.0.0-stage → 2.0.0

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,535 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // auto-inject-version:tempo-kit/plugin/sdk
20
+ var sdk_exports = {};
21
+ __export(sdk_exports, {
22
+ definePlugin: () => definePlugin,
23
+ defineTerm: () => defineTerm
24
+ });
25
+ __reExport(sdk_exports, sdk_star);
26
+ import * as sdk_star from "tempo-kit/plugin/sdk";
27
+ import { definePlugin as originalPlugin, defineTerm as originalTerm } from "tempo-kit/plugin/sdk";
28
+ var definePlugin = (config) => originalPlugin({ ...config, version: "2.0.0" });
29
+ var defineTerm = (config) => originalTerm({ ...config, version: "2.0.0" });
30
+
31
+ // src/engine.ts
32
+ var RE_SERVER_TIMING = /(?:clock|server_time|epoch)=(\d+(?:\.\d+)?)/i;
33
+ var ClockDriftEngine = class {
34
+ #state = {
35
+ offsetMs: 0,
36
+ uncertaintyMs: 0,
37
+ lastSyncedAt: 0,
38
+ sampleCount: 0
39
+ };
40
+ #options;
41
+ #syncTimer = null;
42
+ #unregisterFinalizer = null;
43
+ #activeSyncAbortController = null;
44
+ #isSyncing = false;
45
+ #baselineNtpMs = 0;
46
+ #baselinePerfNow = 0;
47
+ #offsetSignal = new sdk_exports.Signify.State(0);
48
+ #isCalibratedSignal = new sdk_exports.Signify.State(false);
49
+ #driftSignal = new sdk_exports.Signify.State({
50
+ offsetMs: 0,
51
+ uncertaintyMs: 0,
52
+ lastSyncedAt: 0,
53
+ sampleCount: 0
54
+ });
55
+ #cachedSignalsNamespace;
56
+ constructor(options = {}) {
57
+ this.#options = {
58
+ server: options.server ?? "/api/time",
59
+ syncInterval: options.syncInterval ?? 0,
60
+ interceptFetch: options.interceptFetch ?? false,
61
+ trustedOrigins: options.trustedOrigins ?? [],
62
+ maxAcceptableRttMs: options.maxAcceptableRttMs ?? 1e3,
63
+ alpha: Math.min(1, Math.max(0.01, options.alpha ?? 0.3))
64
+ };
65
+ }
66
+ get [Symbol.toStringTag]() {
67
+ return "Tempo.ClockDriftEngine";
68
+ }
69
+ /**
70
+ * Returns the current calculated clock drift state snapshot.
71
+ */
72
+ get drift() {
73
+ return { ...this.#state };
74
+ }
75
+ /**
76
+ * Returns the raw clock drift offset in milliseconds.
77
+ */
78
+ get offset() {
79
+ return this.#state.offsetMs;
80
+ }
81
+ /**
82
+ * Whether at least one valid synchronization sample has been successfully recorded.
83
+ */
84
+ get isCalibrated() {
85
+ return this.#state.sampleCount > 0;
86
+ }
87
+ /**
88
+ * Returns the reactive signals namespace for drift, offset, and calibration state.
89
+ */
90
+ get signals() {
91
+ return this.#cachedSignalsNamespace ??= Object.freeze({
92
+ offset: sdk_exports.Signify.computed(() => this.#offsetSignal.get()),
93
+ isCalibrated: sdk_exports.Signify.computed(() => this.#isCalibratedSignal.get()),
94
+ drift: sdk_exports.Signify.computed(() => this.#driftSignal.get())
95
+ });
96
+ }
97
+ /**
98
+ * Calculates the current calibrated epoch time in milliseconds.
99
+ */
100
+ nowMs() {
101
+ return this.#state.sampleCount > 0 && this.#baselineNtpMs > 0 && (0, sdk_exports.isFunction)(globalThis.performance?.now) ? Math.round(this.#baselineNtpMs + (performance.now() - this.#baselinePerfNow)) : Date.now() + this.#state.offsetMs;
102
+ }
103
+ /**
104
+ * Resets the clock calibration state back to zero.
105
+ */
106
+ reset() {
107
+ this.#baselineNtpMs = 0;
108
+ this.#baselinePerfNow = 0;
109
+ this.#state = {
110
+ offsetMs: 0,
111
+ uncertaintyMs: 0,
112
+ lastSyncedAt: 0,
113
+ sampleCount: 0
114
+ };
115
+ this.#offsetSignal.set(0);
116
+ this.#isCalibratedSignal.set(false);
117
+ this.#driftSignal.set(this.drift);
118
+ }
119
+ /**
120
+ * Actively requests a network timestamp from an endpoint to calibrate client clock drift.
121
+ *
122
+ * @param endpoint - Target HTTP endpoint URL (defaults to configured server)
123
+ * @returns The updated ClockDriftState
124
+ */
125
+ async sync(endpoint) {
126
+ const target = endpoint || this.#options.server;
127
+ if (!target || !(0, sdk_exports.isFunction)(globalThis.fetch))
128
+ return this.drift;
129
+ let t0 = performance.now();
130
+ let localBefore = Date.now();
131
+ const timeoutMs = Math.max(3e3, this.#options.maxAcceptableRttMs * 2);
132
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
133
+ this.#activeSyncAbortController = controller;
134
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
135
+ if ((0, sdk_exports.isFunction)(timer?.unref)) timer.unref();
136
+ try {
137
+ const init = {
138
+ method: "HEAD",
139
+ cache: "no-store",
140
+ headers: { "X-Tempo-Sync": "1" }
141
+ };
142
+ if (controller) init.signal = controller.signal;
143
+ let response = await fetch(target, init);
144
+ if (response.status === 405) {
145
+ t0 = performance.now();
146
+ localBefore = Date.now();
147
+ response = await fetch(target, {
148
+ ...init,
149
+ method: "GET"
150
+ });
151
+ response.body?.cancel?.().catch(() => {
152
+ });
153
+ }
154
+ const t1 = performance.now();
155
+ const rtt = t1 - t0;
156
+ if (rtt > this.#options.maxAcceptableRttMs)
157
+ return this.drift;
158
+ const extracted = this.extractServerTime(response.headers);
159
+ if (extracted === null)
160
+ return this.drift;
161
+ this.ingestSample(extracted.timeMs, rtt, localBefore, extracted.isCoarse);
162
+ } catch {
163
+ } finally {
164
+ if (timer) clearTimeout(timer);
165
+ if (this.#activeSyncAbortController === controller)
166
+ this.#activeSyncAbortController = null;
167
+ }
168
+ return this.drift;
169
+ }
170
+ /**
171
+ * Incorporates a raw server timestamp and round-trip duration sample into the drift state.
172
+ *
173
+ * @param serverTimeMs - Authoritative server timestamp in milliseconds
174
+ * @param rttMs - Measured network Round-Trip Time in milliseconds
175
+ * @param localBefore - Local Date.now() timestamp captured at request initiation
176
+ * @param isCoarse - Whether the timestamp comes from a 1-second coarse source (adds 500ms uncertainty)
177
+ */
178
+ ingestSample(serverTimeMs, rttMs, localBefore = Date.now() - rttMs, isCoarse = false) {
179
+ if (!Number.isFinite(serverTimeMs) || !Number.isFinite(rttMs) || !Number.isFinite(localBefore)) return;
180
+ if (rttMs < 0 || rttMs > this.#options.maxAcceptableRttMs) return;
181
+ const measuredOffset = serverTimeMs - (localBefore + rttMs / 2);
182
+ const sampleUncertainty = rttMs / 2 + (isCoarse ? 500 : 0);
183
+ let finalOffset = measuredOffset;
184
+ let finalUncertainty = sampleUncertainty;
185
+ if (this.#state.sampleCount === 0) {
186
+ this.#state = {
187
+ offsetMs: Math.round(measuredOffset),
188
+ uncertaintyMs: Math.round(sampleUncertainty),
189
+ lastSyncedAt: Date.now(),
190
+ sampleCount: 1
191
+ };
192
+ } else {
193
+ finalOffset = this.#options.alpha * measuredOffset + (1 - this.#options.alpha) * this.#state.offsetMs;
194
+ finalUncertainty = this.#options.alpha * sampleUncertainty + (1 - this.#options.alpha) * this.#state.uncertaintyMs;
195
+ this.#state = {
196
+ offsetMs: Math.round(finalOffset),
197
+ uncertaintyMs: Math.round(finalUncertainty),
198
+ lastSyncedAt: Date.now(),
199
+ sampleCount: this.#state.sampleCount + 1
200
+ };
201
+ }
202
+ this.#baselineNtpMs = localBefore + rttMs + finalOffset;
203
+ this.#baselinePerfNow = (0, sdk_exports.isFunction)(globalThis.performance?.now) ? performance.now() : 0;
204
+ this.#offsetSignal.set(this.#state.offsetMs);
205
+ this.#isCalibratedSignal.set(true);
206
+ this.#driftSignal.set(this.drift);
207
+ }
208
+ /**
209
+ * Parses server timestamp from HTTP response headers.
210
+ * Priority 1: High-precision `Server-Timing: clock=<epochMs>`, `server_time=<epochMs>`, or `epoch=<epochMs>`
211
+ * Priority 2: Standard RFC 7231 `Date` header
212
+ */
213
+ extractServerTime(headers) {
214
+ const serverTiming = headers.get("Server-Timing") || headers.get("server-timing");
215
+ if (serverTiming) {
216
+ const match = serverTiming.match(RE_SERVER_TIMING);
217
+ if (match && match[1]) {
218
+ const val = parseFloat(match[1]);
219
+ const ms = val < 1e11 ? Math.round(val * 1e3) : Math.round(val);
220
+ if (Number.isFinite(ms) && ms >= 9466848e5) return { timeMs: ms, isCoarse: false };
221
+ }
222
+ }
223
+ const dateHeader = headers.get("Date") || headers.get("date");
224
+ if (dateHeader) {
225
+ const parsed = new Date(dateHeader).getTime();
226
+ if (!Number.isNaN(parsed) && parsed >= 9466848e5)
227
+ return { timeMs: parsed, isCoarse: true };
228
+ }
229
+ return null;
230
+ }
231
+ /**
232
+ * Initializes periodic background re-synchronization if configured.
233
+ */
234
+ startBackgroundSync(intervalMs) {
235
+ this.stopBackgroundSync();
236
+ if (intervalMs > 0 && (0, sdk_exports.isFunction)(globalThis.setInterval)) {
237
+ const timer = setInterval(() => {
238
+ if (this.#isSyncing) return;
239
+ this.#isSyncing = true;
240
+ this.sync().finally(() => {
241
+ this.#isSyncing = false;
242
+ }).catch(() => {
243
+ });
244
+ }, intervalMs);
245
+ if ((0, sdk_exports.isFunction)(timer?.unref))
246
+ timer.unref();
247
+ this.#syncTimer = timer;
248
+ this.#unregisterFinalizer = sdk_exports.Finalizer.register(this, () => {
249
+ if (timer) clearInterval(timer);
250
+ });
251
+ }
252
+ }
253
+ /**
254
+ * Stops active periodic background sync timers.
255
+ */
256
+ stopBackgroundSync() {
257
+ if (this.#syncTimer !== null) {
258
+ clearInterval(this.#syncTimer);
259
+ this.#syncTimer = null;
260
+ }
261
+ if (this.#unregisterFinalizer !== null) {
262
+ this.#unregisterFinalizer();
263
+ this.#unregisterFinalizer = null;
264
+ }
265
+ if (this.#activeSyncAbortController !== null) {
266
+ this.#activeSyncAbortController.abort();
267
+ this.#activeSyncAbortController = null;
268
+ }
269
+ this.#isSyncing = false;
270
+ }
271
+ /**
272
+ * Stops background synchronization and releases active timer resources.
273
+ */
274
+ dispose() {
275
+ this.stopBackgroundSync();
276
+ }
277
+ /**
278
+ * Explicit deterministic disposal (Dual-Layer Lifecycle Model).
279
+ */
280
+ [Symbol.dispose]() {
281
+ this.dispose();
282
+ }
283
+ };
284
+
285
+ // src/index.ts
286
+ var RE_INTERVAL = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i;
287
+ function parseIntervalMs(interval) {
288
+ if (!interval) return 0;
289
+ if ((0, sdk_exports.isNumber)(interval)) return Math.max(0, interval);
290
+ const match = String(interval).trim().match(RE_INTERVAL);
291
+ if (!match) return 0;
292
+ const val = parseFloat(match[1] ?? "0");
293
+ const unit = (match[2] || "ms").toLowerCase();
294
+ switch (unit) {
295
+ case "s":
296
+ return val * 1e3;
297
+ case "m":
298
+ return val * 60 * 1e3;
299
+ case "h":
300
+ return val * 3600 * 1e3;
301
+ case "d":
302
+ return val * 86400 * 1e3;
303
+ default:
304
+ return val;
305
+ }
306
+ }
307
+ var _globalNtpEngine = null;
308
+ var _globalSyncOptions = {};
309
+ var _fetchPatched = false;
310
+ var _originalFetch = null;
311
+ var _installedFetchWrapper = null;
312
+ function extractRequestUrl(input) {
313
+ if ((0, sdk_exports.isString)(input)) return input;
314
+ if ((0, sdk_exports.isObject)(input)) {
315
+ if ("url" in input && (0, sdk_exports.isString)(input.url)) return input.url;
316
+ if ("href" in input && (0, sdk_exports.isString)(input.href)) return input.href;
317
+ if ((0, sdk_exports.isFunction)(input.toString)) {
318
+ try {
319
+ return input.toString();
320
+ } catch {
321
+ return "";
322
+ }
323
+ }
324
+ }
325
+ return "";
326
+ }
327
+ function matchesRule(url, rule) {
328
+ if ((0, sdk_exports.isFunction)(rule)) {
329
+ try {
330
+ return Boolean(rule(url));
331
+ } catch {
332
+ return false;
333
+ }
334
+ }
335
+ if (rule instanceof RegExp)
336
+ return rule.test(url);
337
+ if ((0, sdk_exports.isString)(rule)) {
338
+ try {
339
+ const parsedUrl = new URL(url, "http://localhost");
340
+ if (rule.startsWith("/")) {
341
+ return parsedUrl.pathname.startsWith(rule);
342
+ }
343
+ if (rule.includes("://") || rule.startsWith("//")) {
344
+ const parsedRule = new URL(rule, "http://localhost");
345
+ if (parsedUrl.origin !== parsedRule.origin) {
346
+ return false;
347
+ }
348
+ if (parsedRule.pathname === "/" || parsedRule.pathname === "") {
349
+ return true;
350
+ }
351
+ return parsedUrl.pathname.startsWith(parsedRule.pathname);
352
+ }
353
+ if (parsedUrl.host === rule || parsedUrl.hostname === rule) {
354
+ return true;
355
+ }
356
+ } catch {
357
+ return false;
358
+ }
359
+ }
360
+ return false;
361
+ }
362
+ function isUrlAllowed(url, interceptFetch, trustedOrigins) {
363
+ if (interceptFetch === false) return false;
364
+ if (!interceptFetch && !trustedOrigins) return false;
365
+ if (trustedOrigins) {
366
+ return Array.isArray(trustedOrigins) ? trustedOrigins.some((rule) => matchesRule(url, rule)) : matchesRule(url, trustedOrigins);
367
+ }
368
+ if (interceptFetch === true) return true;
369
+ return Array.isArray(interceptFetch) ? interceptFetch.some((rule) => matchesRule(url, rule)) : matchesRule(url, interceptFetch);
370
+ }
371
+ var NtpPlugin = definePlugin({
372
+ name: "ntp",
373
+ install(TempoClass, rawOptions = {}) {
374
+ const options = (0, sdk_exports.isObject)(rawOptions) ? rawOptions : {};
375
+ _globalSyncOptions = options;
376
+ if (_globalNtpEngine)
377
+ _globalNtpEngine.stopBackgroundSync();
378
+ const engine = new ClockDriftEngine(options);
379
+ _globalNtpEngine = engine;
380
+ const getEngine = () => _globalNtpEngine ?? engine;
381
+ const ntpNamespace = {
382
+ now(timeZone) {
383
+ return new TempoClass(getEngine().nowMs(), (0, sdk_exports.isString)(timeZone) ? { timeZone } : timeZone);
384
+ },
385
+ sync(endpoint) {
386
+ return getEngine().sync(endpoint);
387
+ },
388
+ get drift() {
389
+ return getEngine().drift;
390
+ },
391
+ get offset() {
392
+ return getEngine().offset;
393
+ },
394
+ get isCalibrated() {
395
+ return getEngine().isCalibrated;
396
+ },
397
+ get signals() {
398
+ return getEngine().signals;
399
+ },
400
+ signal(options2) {
401
+ const interval = options2?.interval ?? 1;
402
+ const timeZone = options2?.timeZone;
403
+ const tzOpt = (0, sdk_exports.isString)(timeZone) ? { timeZone } : timeZone;
404
+ const getCurrent = () => new TempoClass(getEngine().nowMs(), tzOpt);
405
+ const state = new sdk_exports.Signify.State(getCurrent());
406
+ let disposeCadence;
407
+ if ((0, sdk_exports.isFunction)(TempoClass.ticker?.signal)) {
408
+ const tickerInterval = (0, sdk_exports.isString)(interval) ? parseIntervalMs(interval) / 1e3 || 1 : interval;
409
+ const tickerSig = TempoClass.ticker.signal({
410
+ interval: tickerInterval,
411
+ timeZone
412
+ });
413
+ const subEffect = sdk_exports.Signify.effect(() => {
414
+ tickerSig();
415
+ state.set(getCurrent());
416
+ });
417
+ disposeCadence = () => {
418
+ subEffect.dispose();
419
+ tickerSig.dispose?.();
420
+ };
421
+ } else {
422
+ const intervalMs2 = (0, sdk_exports.isNumber)(interval) ? interval * 1e3 : parseIntervalMs(interval) || 1e3;
423
+ const timer = setInterval(() => {
424
+ state.set(getCurrent());
425
+ }, intervalMs2);
426
+ disposeCadence = () => {
427
+ clearInterval(timer);
428
+ };
429
+ }
430
+ const calibrationWatch = sdk_exports.Signify.effect(() => {
431
+ getEngine().signals.offset();
432
+ getEngine().signals.isCalibrated();
433
+ state.set(getCurrent());
434
+ });
435
+ const dispose = () => {
436
+ calibrationWatch.dispose();
437
+ disposeCadence();
438
+ };
439
+ const accessor = function() {
440
+ return state.get();
441
+ };
442
+ const proxy = new Proxy(accessor, {
443
+ get(_, prop) {
444
+ if (prop === "dispose" || prop === Symbol.dispose) return dispose;
445
+ if (prop === "get") return () => state.get();
446
+ if (prop === "value") return state.get();
447
+ if (prop === "epoch") return state.epoch;
448
+ if (prop === "addConsumer") return (c) => state.addConsumer(c);
449
+ if (prop === "removeConsumer") return (c) => state.removeConsumer(c);
450
+ if (prop === "poll") return () => state.poll();
451
+ return state[prop];
452
+ },
453
+ apply(_, thisArg, argArray) {
454
+ return state.get();
455
+ }
456
+ });
457
+ sdk_exports.Finalizer.register(proxy, () => {
458
+ dispose();
459
+ });
460
+ return proxy;
461
+ },
462
+ reset() {
463
+ getEngine().reset();
464
+ },
465
+ dispose() {
466
+ getEngine().dispose();
467
+ if (_fetchPatched) {
468
+ if (_originalFetch && globalThis.fetch === _installedFetchWrapper)
469
+ globalThis.fetch = _originalFetch;
470
+ _fetchPatched = false;
471
+ _originalFetch = null;
472
+ _installedFetchWrapper = null;
473
+ }
474
+ },
475
+ [Symbol.dispose]() {
476
+ this.dispose();
477
+ }
478
+ };
479
+ Object.defineProperty(TempoClass, "ntp", {
480
+ value: sdk_exports.deepFreeze ? (0, sdk_exports.deepFreeze)(ntpNamespace) : Object.freeze(ntpNamespace),
481
+ writable: false,
482
+ configurable: true,
483
+ enumerable: false
484
+ });
485
+ if (!TempoClass.prototype.toNtpTime) {
486
+ TempoClass.prototype.toNtpTime = function() {
487
+ const calibratedEpochMs = this.epoch.ms + getEngine().offset;
488
+ return new TempoClass(calibratedEpochMs, { timeZone: this.tz });
489
+ };
490
+ }
491
+ const shouldIntercept = options.interceptFetch !== false && (Boolean(options.interceptFetch) || Boolean(options.trustedOrigins));
492
+ if (shouldIntercept && !_fetchPatched && (0, sdk_exports.isFunction)(globalThis.fetch)) {
493
+ _fetchPatched = true;
494
+ _originalFetch = globalThis.fetch;
495
+ const originalFetch = globalThis.fetch;
496
+ const fetchWrapper = async function(...args) {
497
+ const init = args[1];
498
+ const isInternalSync = init?.headers && ((0, sdk_exports.isFunction)(init.headers.get) && init.headers.get("X-Tempo-Sync") || "X-Tempo-Sync" in init.headers);
499
+ const t0 = performance.now();
500
+ const localBefore = Date.now();
501
+ const response = await originalFetch.apply(this, args);
502
+ const rtt = performance.now() - t0;
503
+ try {
504
+ const requestUrl = extractRequestUrl(args[0]);
505
+ const isAllowed = isUrlAllowed(requestUrl, _globalSyncOptions.interceptFetch, _globalSyncOptions.trustedOrigins);
506
+ if (!isInternalSync && isAllowed && response?.headers) {
507
+ const activeEngine = getEngine();
508
+ const extracted = activeEngine.extractServerTime(response.headers);
509
+ if (extracted !== null)
510
+ activeEngine.ingestSample(extracted.timeMs, rtt, localBefore, extracted.isCoarse);
511
+ }
512
+ } catch {
513
+ }
514
+ return response;
515
+ };
516
+ _installedFetchWrapper = fetchWrapper;
517
+ globalThis.fetch = fetchWrapper;
518
+ }
519
+ const intervalMs = parseIntervalMs(options.syncInterval);
520
+ if (intervalMs > 0)
521
+ engine.startBackgroundSync(intervalMs);
522
+ if (options.server)
523
+ engine.sync(options.server).catch(() => {
524
+ });
525
+ }
526
+ });
527
+ var index_default = NtpPlugin;
528
+
529
+ // src/install.ts
530
+ (0, sdk_exports.autoInstall)(NtpPlugin);
531
+ export {
532
+ ClockDriftEngine,
533
+ NtpPlugin,
534
+ index_default as default
535
+ };
@@ -0,0 +1,148 @@
1
+ import type { Tempo } from 'tempo-kit';
2
+ import type { ReadonlySignal } from 'tempo-kit/library';
3
+ /**
4
+ * Origin, URL prefix, regex, or predicate function used to filter passive fetch requests.
5
+ */
6
+ export type NtpOriginMatcher = string | RegExp | ((url: string) => boolean);
7
+ export type NtpFetchFilter = boolean | NtpOriginMatcher | readonly (string | RegExp)[];
8
+ /**
9
+ * ## NtpSyncOptions
10
+ * Configuration options for the NTP & Clock Drift plugin.
11
+ */
12
+ export interface NtpSyncOptions {
13
+ /**
14
+ * Target HTTP endpoint for clock synchronization (e.g. '/api/time').
15
+ * The endpoint should return a `Date` or `Server-Timing: clock=<epochMs>` response header.
16
+ */
17
+ server?: string;
18
+ /**
19
+ * Optional periodic re-synchronization interval (e.g., '15m' or milliseconds).
20
+ */
21
+ syncInterval?: number | string;
22
+ /**
23
+ * Automatically intercept `globalThis.fetch` responses to passively calibrate clock drift.
24
+ *
25
+ * - `true`: Passively intercepts all fetch requests (unrestricted origin sniffing).
26
+ * - `false`: Disabled (default).
27
+ * - `string`: Single trusted origin or URL prefix (e.g. `'https://api.example.com'` or `'/api/'`).
28
+ * - `Array<string | RegExp>`: List of trusted origins or URL patterns to intercept.
29
+ * - `RegExp`: Regular expression pattern matching trusted endpoints.
30
+ * - `(url: string) => boolean`: Custom predicate evaluating whether a request URL is trusted.
31
+ *
32
+ * @default false
33
+ */
34
+ interceptFetch?: NtpFetchFilter;
35
+ /**
36
+ * Optional trusted origin(s), URL prefixes, regex patterns, or predicate to restrict passive fetch interception.
37
+ * Automatically enables `interceptFetch` unless `interceptFetch: false` is explicitly specified.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * Tempo.use(NtpPlugin, {
42
+ * trustedOrigins: ['https://api.mycompany.com', '/api/']
43
+ * });
44
+ * ```
45
+ */
46
+ trustedOrigins?: NtpOriginMatcher | readonly (string | RegExp)[];
47
+ /**
48
+ * Maximum acceptable Round-Trip Time (RTT) in milliseconds. Samples exceeding this threshold are discarded.
49
+ * @default 1000
50
+ */
51
+ maxAcceptableRttMs?: number;
52
+ /**
53
+ * Exponential Moving Average (EMA) smoothing weight factor between 0.0 and 1.0 for new samples.
54
+ * @default 0.3
55
+ */
56
+ alpha?: number;
57
+ }
58
+ /**
59
+ * ## ClockDriftState
60
+ * Telemetry snapshot of the current clock drift and synchronization confidence.
61
+ */
62
+ export interface ClockDriftState {
63
+ /**
64
+ * Calculated clock offset in milliseconds:
65
+ * `serverTime = localTime + offsetMs`
66
+ */
67
+ readonly offsetMs: number;
68
+ /**
69
+ * Estimated network uncertainty in milliseconds: `±(RTT / 2)`
70
+ */
71
+ readonly uncertaintyMs: number;
72
+ /**
73
+ * Epoch timestamp in milliseconds of the last successful calibration.
74
+ */
75
+ readonly lastSyncedAt: number;
76
+ /**
77
+ * Total count of valid sync samples aggregated into the current drift offset.
78
+ */
79
+ readonly sampleCount: number;
80
+ }
81
+ /**
82
+ * ## NtpNamespace
83
+ * Public static API attached to `Tempo.ntp`.
84
+ */
85
+ export interface NtpNamespace {
86
+ /**
87
+ * Creates a new Tempo instance calibrated to authoritative atomic/server time.
88
+ *
89
+ * @param timeZone - Optional IANA timezone identifier
90
+ * @returns A calibrated Tempo instance
91
+ */
92
+ now(timeZone?: string): Tempo;
93
+ /**
94
+ * Actively synchronizes clock drift against the configured or specified time endpoint.
95
+ *
96
+ * @param endpoint - Optional URL/endpoint override
97
+ * @returns A promise resolving to the updated ClockDriftState
98
+ */
99
+ sync(endpoint?: string): Promise<ClockDriftState>;
100
+ /**
101
+ * Telemetry snapshot of current clock drift and uncertainty bounds.
102
+ */
103
+ readonly drift: ClockDriftState;
104
+ /**
105
+ * The current clock drift offset in milliseconds (fast integer getter).
106
+ */
107
+ readonly offset: number;
108
+ /**
109
+ * Whether at least one valid network synchronization sample has been acquired.
110
+ */
111
+ readonly isCalibrated: boolean;
112
+ /**
113
+ * Resets the clock drift calibration state back to zero.
114
+ */
115
+ reset(): void;
116
+ /**
117
+ * Stops background synchronization and releases active timer resources.
118
+ */
119
+ dispose(): void;
120
+ /**
121
+ * Explicit deterministic disposal (Dual-Layer Lifecycle Model).
122
+ */
123
+ [Symbol.dispose](): void;
124
+ /**
125
+ * Reactive signals namespace for clock drift offset, calibration status, and telemetry.
126
+ */
127
+ readonly signals: NtpSignalsNamespace;
128
+ /**
129
+ * Spawns an auto-ticking ReadonlySignal<Tempo> calibrated to network time.
130
+ * Supports explicit disposal via `using clock = Tempo.ntp.signal(...)`.
131
+ */
132
+ signal(options?: {
133
+ interval?: number | string;
134
+ timeZone?: string;
135
+ }): ReadonlySignal<Tempo> & Disposable;
136
+ }
137
+ /**
138
+ * ## NtpSignalsNamespace
139
+ * Fine-grained reactive TC39 signals namespace for NTP telemetry and calibrated offset.
140
+ */
141
+ export interface NtpSignalsNamespace {
142
+ /** Reactive signal containing the current clock drift offset in milliseconds */
143
+ readonly offset: ReadonlySignal<number>;
144
+ /** Reactive signal indicating whether clock synchronization has completed at least one valid calibration */
145
+ readonly isCalibrated: ReadonlySignal<boolean>;
146
+ /** Reactive signal emitting the complete ClockDriftState snapshot (RTT, jitter, confidence) */
147
+ readonly drift: ReadonlySignal<ClockDriftState>;
148
+ }